wolfssl-sys 4.0.0

System bindings for WolfSSL
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
/* renesas_tsip_util.c
 *
 * Copyright (C) 2006-2026 wolfSSL Inc.
 *
 * This file is part of wolfSSL.
 *
 * wolfSSL is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * wolfSSL is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
 */

#ifdef HAVE_CONFIG_H
    #include <config.h>
#endif

#include <wolfssl/wolfcrypt/settings.h>

#if defined(WOLFSSL_RENESAS_TSIP)

#include <wolfssl/wolfcrypt/wc_port.h>
#include <wolfssl/wolfcrypt/types.h>
#include <wolfssl/wolfcrypt/asn.h>
#include <wolfssl/wolfcrypt/memory.h>
#include <wolfssl/wolfcrypt/error-crypt.h>
#include <wolfssl/wolfcrypt/aes.h>
#ifdef NO_INLINE
    #include <wolfssl/wolfcrypt/misc.h>
#else
    #define WOLFSSL_MISC_INCLUDED
    #include <wolfcrypt/src/misc.c>
#endif

#ifndef WOLFSSL_RENESAS_TSIP_CRYPTONLY
    #include <wolfssl/ssl.h>
    #include <wolfssl/internal.h>
    #include <wolfssl/error-ssl.h>
#endif
#include <wolfssl/wolfcrypt/port/Renesas/renesas_tsip_internal.h>
#include <wolfssl/wolfcrypt/port/Renesas/renesas_cmn.h>

#include <stdio.h>

#define TSIP_SIGNING_DATA_PREFIX_SZ     64
#define TSIP_SIGNING_DATA_PREFIX_BYTE   0x20
#define TSIP_MAX_SIG_DATA_SZ            130
#define TSIP_CERT_VFY_LABEL_SZ          34

/* function pointer typedefs for TSIP SHAxx HMAC Verification  */
typedef e_tsip_err_t (*shaHmacInitFn)
        (tsip_hmac_sha_handle_t*, tsip_hmac_sha_key_index_t*);
typedef e_tsip_err_t (*shaHmacUpdateFn)
        (tsip_hmac_sha_handle_t*, uint8_t*, uint32_t);
typedef e_tsip_err_t (*shaHmacFinalFn)
        (tsip_hmac_sha_handle_t*, uint8_t*, uint32_t);

/* ./ca-cert.der.sign,  */
/* expect to have these variables defined at user application */
#if defined(WOLFSSL_RENESAS_TSIP) && (WOLFSSL_RENESAS_TSIP_VER>=109)
extern uint32_t     s_inst2[R_TSIP_SINST2_WORD_SIZE];
#elif defined(WOLFSSL_RENESAS_TSIP) && (WOLFSSL_RENESAS_TSIP_VER>=106)
extern uint32_t     s_flash[];
extern uint32_t     s_inst1[R_TSIP_SINST_WORD_SIZE];
#endif

#ifndef SINGLE_THREADED
wolfSSL_Mutex       tsip_mutex;
static int          tsip_CryptHwMutexInit_ = 0;
#endif
static tsip_key_data g_user_key_info;
struct WOLFSSL_HEAP_HINT*  tsip_heap_hint = NULL;

/* tsip only keep one encrypted ca public key */
#if defined(WOLFSSL_RENESAS_TSIP_TLS)
static const byte*  ca_cert_sig = NULL;
static uint32_t     g_encrypted_publicCA_key[R_TSIP_SINST_WORD_SIZE];

/* index of CM table. must be global since renesas_common access it. */
extern uint32_t     g_CAscm_Idx;

#if defined(WOLFSSL_TLS13)
/* The server certificate verification label. */
static const byte serverCertVfyLabel[TSIP_CERT_VFY_LABEL_SZ] =
    "TLS 1.3, server CertificateVerify";
static const byte clientCertVfyLabel[TSIP_CERT_VFY_LABEL_SZ] =
    "TLS 1.3, client CertificateVerify";
#endif /* WOLFSSL_TLS13 */

#endif /* WOLFSSL_RENESAS_TSIP_TLS */



static int tsip_CryptHwMutexInit(wolfSSL_Mutex* mutex)
{
    return wc_InitMutex(mutex);
}

static int tsip_CryptHwMutexLock(wolfSSL_Mutex* mutex)
{
    return wc_LockMutex(mutex);
}

static int tsip_CryptHwMutexUnLock(wolfSSL_Mutex* mutex)
{
    return wc_UnLockMutex(mutex);
}

#if defined(WOLFSSL_RENESAS_TSIP_TLS)
/* Set client encrypted public key data.
 * parameters:
 * ssl      WOLFSSL object
 * keyBuf  buffer holding wrapped key which Renesas key tool generated.
 * keyBufLen buffer length
 * keyType  0: RSA 2048bit, 1: RSA 4096bit, 2 ECC P256
 * return   0 on success, others on failure.
 */
WOLFSSL_API int tsip_use_PublicKey_buffer_TLS(WOLFSSL* ssl,
                                const char* keyBuf, int keyBufLen, int keyType)
{
    int ret = 0;
    TsipUserCtx* tuc = NULL;

    WOLFSSL_ENTER("tsip_use_PublicKey_buffer_TLS");

    if (ssl == NULL
    || keyBuf == NULL || keyBufLen == 0 || ssl->RenesasUserCtx == NULL) {
        ret = BAD_FUNC_ARG;
    }

    if (ret == 0){
        tuc = ssl->RenesasUserCtx;
        tuc->internal->wrappedPublicKey  = (uint8_t*)keyBuf;
        tuc->wrappedKeyType    = keyType;
    }

    WOLFSSL_LEAVE("tsip_use_PublicKey_buffer", ret);
    return ret;
}
/* Set client encrypted private key data.
 * parameters:
 * ssl      WOLFSSL object
 * keyBuf  buffer holding wrapped key which Renesas key tool generated.
 * keyBufLen buffer length
 * keyType  0: RSA 2048bit, 1: RSA 4096bit, 2 ECC P256
 * return   0 on success, others on failure.
 */
WOLFSSL_API int tsip_use_PrivateKey_buffer_TLS(struct WOLFSSL* ssl,
                                const char* keyBuf, int keyBufLen, int keyType)
{
    int ret = 0;
    TsipUserCtx* tuc = NULL;

    WOLFSSL_ENTER("tsip_use_PrivateKey_buffer_TLS");

    if (ssl == NULL || keyBuf == NULL || keyBufLen == 0 ||
                                ssl->RenesasUserCtx == NULL) {
        ret = BAD_FUNC_ARG;
    }
    if (ret == 0){
        tuc = ssl->RenesasUserCtx;

        tuc->internal->wrappedPrivateKey = (uint8_t*)keyBuf;
        tuc->wrappedKeyType    = keyType;

        /* store keyType as Id since Id capacity is 32 bytes */
        ret = wolfSSL_use_PrivateKey_Id(ssl,
                                (const unsigned char*)keyBuf, 32,
                                                tuc->devId);
        if (ret == WOLFSSL_SUCCESS) {
            ret = 0;
        }
    }

    WOLFSSL_LEAVE("tsip_use_PrivateKey_buffer_TLS", ret);
    return ret;
}
#endif /* WOLFSSL_RENESAS_TSIP_TLS */

#if defined(WOLFSSL_RENESAS_TSIP_CRYPTONLY)

/* Set client encrypted public key data.
 * parameters:
 * uc      Tsip user context
 * keyBuf  buffer holding wrapped key which Renesas key tool generated.
 * keyBufLen buffer length
 * keyType  0: RSA 2048bit, 1: RSA 4096bit, 2 ECC P256
 * return   0 on success, others on failure.
 */
WOLFSSL_API int tsip_use_PublicKey_buffer_crypt(TsipUserCtx *uc,
                                const char* keyBuf, int keyBufLen, int keyType)
{
    int ret = 0;

    WOLFSSL_ENTER("tsip_use_PublicKey_buffer_crypt");

    if (uc == NULL || keyBuf == NULL || keyBufLen == 0) {
        ret = BAD_FUNC_ARG;
    }

    if (ret == 0){
        uc->internal->wrappedPublicKey  = (uint8_t*)keyBuf;
        uc->wrappedKeyType    = keyType;
    }

    WOLFSSL_LEAVE("tsip_use_PublicKey_buffer_crypt", ret);
    return ret;
}
/* Set client encrypted private key data.
 * parameters:
 * uc      Tsip user context
 * keyBuf  buffer holding wrapped key which Renesas key tool generated.
 * keyBufLen buffer length
 * keyType  0: RSA 2048bit, 1: RSA 4096bit, 2 ECC P256
 * return   0 on success, others on failure.
 */
WOLFSSL_API int tsip_use_PrivateKey_buffer_crypt(TsipUserCtx *uc,
                                const char* keyBuf, int keyBufLen, int keyType)
{
    int ret = 0;

    WOLFSSL_ENTER("tsip_use_PrivateKey_buffer_crypt");

    if (uc == NULL || keyBuf == NULL || keyBufLen == 0 ) {
        ret = BAD_FUNC_ARG;
    }
    if (ret == 0){
        uc->internal->wrappedPrivateKey = (uint8_t*)keyBuf;
        uc->wrappedKeyType    = keyType;
    }

    WOLFSSL_LEAVE("tsip_use_PrivateKey_buffer_crypt", ret);
    return ret;
}
#endif /* WOLFSSL_RENESAS_TSIP_CRYPTONLY */

#ifdef WOLFSSL_RENESAS_TSIP_TLS

/* Obsolete function. Use tsip_use_PrivateKey_buffer instead.
 * Set client encrypted private key data.
 * parameters:
 * key      Renesas Secure Flash Programmer generated key.
 * keyType  0: RSA 2048bit, 1: RSA 4096bit, 2 ECC P256
 * return   0 on success, others on failure.
 */
WOLFSSL_API int  tsip_set_clientPrivateKeyEnc(const byte* encKey, int keyType)
{
    int ret = 0;

    WOLFSSL_ENTER("tsip_set_clientPrivateKeyEnc");

    if (ret == 0) {
        g_user_key_info.encrypted_user_private_key      = (uint8_t*)encKey;
        g_user_key_info.encrypted_user_private_key_type = keyType;
    }

    WOLFSSL_LEAVE("tsip_set_clientPrivateKeyEnc", ret);
    return ret;
}


/*  Flush raw handshake messages in MsgBag
 *
 */
static void tsipFlushMessages(struct WOLFSSL* ssl)
{
    TsipUserCtx* tuc = NULL;
    MsgBag* bag = NULL;

    if (ssl == NULL)
        return;

    /* get user context for TSIP */
    tuc = ssl->RenesasUserCtx;
    if (tuc == NULL) {
        return;
    }

    bag = &(tuc->internal->messageBag);

    ForceZero(bag, sizeof(MsgBag));

}



int tsip_TlsCleanup(struct WOLFSSL* ssl)
{
    int ret = 0;
    TsipUserCtx* tuc = NULL;

    if (ssl == NULL)
        return BAD_FUNC_ARG;

    tuc = ssl->RenesasUserCtx;

    if (tuc == NULL)
        return ret;

    /* free stored messages */
    tsipFlushMessages(ssl);
    /* free internal structure */
    if (tuc->internal) {
        XFREE(tuc->internal, ssl->heap, DYNAMIC_TYPE_TMP_BUFFER);
        tuc->internal = NULL;
    }

    /* zero clear */
    ForceZero(tuc, sizeof(TsipUserCtx));

    return ret;
}



#if defined(WOLFSSL_TLS13)
/* generate ECC P265 key pair for ECDHE.
 * generated public key is stored in KeyShareEntry.pubkey and private key is
 * stored in TsipUserCtx.EcdhPrivKey13Idx as tsip specific format.
 * return 0 on success, CRYPTOCB_UNAVAILABLE when tsip can not handle and is
 * expecting to fallback to S/W, other negative values on error.
 */
int tsip_Tls13GenEccKeyPair(WOLFSSL* ssl, KeyShareEntry* kse)
{
    int ret = 0;
    e_tsip_err_t    err = TSIP_SUCCESS;
    int             isTLS13 = 0;
    word16          curveId;
    ecc_key*        ecckey = NULL;
    TsipUserCtx*    tuc = NULL;

    WOLFSSL_ENTER("tsip_Tls13GenEccKeyPair");

    if (ssl == NULL || kse == NULL)
        ret = BAD_FUNC_ARG;

    if (ret == 0) {
        if (ssl->version.major == SSLv3_MAJOR &&
            ssl->version.minor == TLSv1_3_MINOR) {
            isTLS13 = 1;
        }
        /* TSIP works only in TLS13 client side */
        if (!isTLS13 || ssl->options.side != WOLFSSL_CLIENT_END) {
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        /* TSIP can handle SECP256R1 */
        if (kse->group != WOLFSSL_ECC_SECP256R1) {
            WOLFSSL_MSG("TSIP can't handle the specified ECC curve.");
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        /* get user context for TSIP */
        tuc = ssl->RenesasUserCtx;
        if (tuc == NULL) {
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    curveId = ECC_SECP256R1;

    /* Allocate space for the public key */
    if (ret == 0) {
        kse->pubKey = (byte*)XMALLOC(kse->pubKeyLen, ssl->heap,
                                                DYNAMIC_TYPE_PUBLIC_KEY);
        if (kse->pubKey == NULL) {
            WOLFSSL_MSG("Key data Memory error");
            ret = MEMORY_E;
        }
        else {
            ForceZero(kse->pubKey, kse->pubKeyLen);
        }
    }

    /* Allocate an ECC key to hold private key. */
    if (ret == 0) {
        kse->key = (byte*)XMALLOC(sizeof(ecc_key), ssl->heap, DYNAMIC_TYPE_ECC);
        if (kse->key == NULL) {
            WOLFSSL_MSG("EccTempKey Memory error");
            ret = MEMORY_E;
        }
        else {
            ret = wc_ecc_init_ex((ecc_key*)kse->key, ssl->heap, ssl->devId);
        }
    }
    if (ret == 0) {
        ecckey = (ecc_key*)kse->key;
        ret = wc_ecc_set_curve(ecckey, kse->keyLen, curveId);
    }

    kse->pubKey[0] = ECC_POINT_UNCOMP;

    /* generate ecc key pair with TSIP */
    if (ret == 0) {
        if ((ret = tsip_hw_lock()) == 0) {

            tuc->internal->Dhe_key_set  =0;

            err = R_TSIP_GenerateTls13P256EccKeyIndex(
                    &(tuc->internal->handle13),
                    TSIP_TLS13_MODE_FULL_HANDSHAKE,
                    &(tuc->internal->EcdhPrivKey13Idx),/* private key index */
                    &(kse->pubKey[1]));              /* generated public key */

            if (err != TSIP_SUCCESS){ret = WC_HW_E;}

            if (ret == 0) {
                WOLFSSL_MSG("ECDH private key-index is stored by TSIP");
                tuc->internal->Dhe_key_set  =1;
            }

            tsip_hw_unlock();
        }
        else {
            WOLFSSL_MSG("mutex locking error");
        }
    }

    if ((ret != 0) && (ret != CRYPTOCB_UNAVAILABLE)) {
        XFREE(kse->key, ssl->heap, DYNAMIC_TYPE_PRIVATE_KEY);
        kse->key = NULL;
        XFREE(kse->pubKey, ssl->heap, DYNAMIC_TYPE_PUBLIC_KEY);
        kse->pubKey = NULL;
    }
    WOLFSSL_LEAVE("tsip_Tls13GenEccKeyPair", ret);
    return ret;
}

/* generate shared secret(pre-master secret)
 * get peer's raw ECDHE public key from KeyShareEntry.
 * The pre-master secret generated by TSIP is stored into
 * TsipUserCtx.sharedSecret13Idx as TSIP specific format.
 *
 * return 0 on success, CRYPTOCB_UNAVAILABLE when tsip can not handle and is
 * expecting to fallback to S/W, other negative values on error.
 */
int tsip_Tls13GenSharedSecret(struct WOLFSSL* ssl,
                                                    struct KeyShareEntry* kse)
{
    int ret = 0;
    e_tsip_err_t    err   = TSIP_SUCCESS;
    int             isTLS13   = 0;
    uint8_t*        pubkeyraw = NULL;
    TsipUserCtx*    tuc = NULL;

    WOLFSSL_ENTER("tsip_Tls13GenSharedSecret");
    if (ssl == NULL || kse == NULL)
        ret = BAD_FUNC_ARG;

    if (ret == 0) {
        if (ssl->version.major == SSLv3_MAJOR &&
            ssl->version.minor == TLSv1_3_MINOR) {
            isTLS13 = 1;
        }
        if (!isTLS13 || ssl->options.side != WOLFSSL_CLIENT_END) {
            WOLFSSL_MSG("Not in TLS1.3 or in client");
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        /* make sure it is in TLS13 and in client side */
        if (kse->group != WOLFSSL_ECC_SECP256R1) {
            WOLFSSL_MSG("TSIP can't handle the specified group");
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        /* get user context for TSIP */
        tuc = ssl->RenesasUserCtx;
        if (tuc == NULL) {
            WOLFSSL_MSG("TsipUserCtx hasn't been set to ssl.");
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        if (!tuc->internal->Dhe_key_set) {
            WOLFSSL_MSG("TSIP wasn't involved in the key-exchange.");
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        if ((ret = tsip_hw_lock()) == 0) {

            tuc->internal->SharedSecret_set = 0;
            pubkeyraw = kse->ke + 1;        /* peer's raw public key data */

            /* derive shared secret */
            err = R_TSIP_Tls13GenerateEcdheSharedSecret(
                TSIP_TLS13_MODE_FULL_HANDSHAKE,
                pubkeyraw,                 /* peer's ECDHE public key */
                &(tuc->internal->EcdhPrivKey13Idx),/*(out) own ECDHE priv key */
                &(tuc->internal->sharedSecret13Idx)); /*(out) PreMasterSecret */

            if (err != TSIP_SUCCESS) {
                WOLFSSL_MSG("R_TSIP_Tls13GenerateEcdheSharedSecret error");
                ret = WC_HW_E;
            }
            if (ret == 0) {
                /* set flag for later tsip operations */
                tuc->internal->SharedSecret_set = 1;
            }

            tsip_hw_unlock();
        }
        else {
            WOLFSSL_MSG("mutex locking error");
        }
    }

    WOLFSSL_LEAVE("tsip_Tls13GenSharedSecret", ret);
    return ret;
}

int tsip_Tls13DeriveEarlySecret(struct WOLFSSL* ssl)
{
    int ret = 0;
    TsipUserCtx*    tuc = NULL;

    WOLFSSL_ENTER("tsip_Tls13DeriveEarlySecret");
    if (ssl == NULL)
        ret = BAD_FUNC_ARG;

    if (ret == 0) {
        /* get user context for TSIP */
        tuc = ssl->RenesasUserCtx;
        if (tuc == NULL) {
            WOLFSSL_MSG("TsipUserCtx hasn't been set to ssl.");
            ret = CRYPTOCB_UNAVAILABLE;
        }
        else {
            tuc->internal->EarlySecret_set = 1;
        }
    }

    WOLFSSL_LEAVE("tsip_Tls13DeriveEarlySecret", ret);
    return ret;
}

/* derive handshake secret.
 * get pre-master secret stored in TsipUserCtx.sharedSecret13Idx.
 * Derived handshake secret is stored into TsipUserCtx.handshakeSecret13Idx
 * as tsip specific format.
 *
 * return 0 on success, CRYPTOCB_UNAVAILABLE when tsip can not handle and is
 * expecting to fallback to S/W, other negative values on error.
 */
int tsip_Tls13DeriveHandshakeSecret(struct WOLFSSL* ssl)
{
    int ret = 0;
    e_tsip_err_t err = TSIP_SUCCESS;
    int isTLS13 = 0;
    TsipUserCtx*    tuc = NULL;

    WOLFSSL_ENTER("tsip_Tls13DeriveHandshakeSecret");
    if (ssl == NULL)
        ret = BAD_FUNC_ARG;

    if (ret == 0) {
        if (ssl->version.major == SSLv3_MAJOR &&
            ssl->version.minor == TLSv1_3_MINOR) {
            isTLS13 = 1;
        }

        if (!isTLS13 || (ssl->options.side != WOLFSSL_CLIENT_END)) {
            ret = CRYPTOCB_UNAVAILABLE;   /* expecting to fallback to S/W */
        }
    }

    if (ret == 0) {
        /* get user context for TSIP */
        tuc = ssl->RenesasUserCtx;
        if (tuc == NULL) {
            WOLFSSL_MSG("TsipUserCtx hasn't been set to ssl.");
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        /* check if pre-master secret is generated by tsip */
        if (!tuc->internal->SharedSecret_set) {
            WOLFSSL_MSG("TSIP wasn't involved in the key-exchange.");
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        if ((ret = tsip_hw_lock()) == 0) {

            tuc->internal->HandshakeSecret_set = 0;

            err = R_TSIP_Tls13GenerateHandshakeSecret(
                        &(tuc->internal->sharedSecret13Idx),
                        &(tuc->internal->handshakeSecret13Idx));

            if (err != TSIP_SUCCESS) {
                WOLFSSL_MSG("R_TSIP_Tls13GenerateHandshakeSecret error");
                ret = WC_HW_E;
            }
            if (ret == 0) {
                tuc->internal->HandshakeSecret_set = 1;
            }
            tsip_hw_unlock();
        }
        else {
            WOLFSSL_MSG("mutex locking error");
        }
    }

    WOLFSSL_LEAVE("tsip_Tls13DeriveHandshakeSecret", ret);
    return ret;
}

static int tsipTls13DeriveClientHandshakeKeys(struct WOLFSSL* ssl)
{
    int ret = 0;
    e_tsip_err_t    err = TSIP_SUCCESS;
    int             isTLS13 = 0;
    TsipUserCtx*    tuc = NULL;
    byte            hash[WC_SHA256_DIGEST_SIZE];


    WOLFSSL_ENTER("tsipTls13DeriveClientHandshakeKeys");
    if (ssl == NULL)
        ret = BAD_FUNC_ARG;

    if (ret == 0) {
        if (ssl->version.major == SSLv3_MAJOR &&
            ssl->version.minor == TLSv1_3_MINOR) {
            isTLS13 = 1;
        }
        if (!isTLS13 || (ssl->options.side != WOLFSSL_CLIENT_END)) {
            ret = CRYPTOCB_UNAVAILABLE;   /* expecting to fallback to S/W */
        }
    }

    if (ret == 0) {
        /* get user context for TSIP */
        tuc = ssl->RenesasUserCtx;
        if (tuc == NULL) {
            WOLFSSL_MSG("TsipUserCtx hasn't been set to ssl.");
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        /* make sure client handshake secret is generated by tsip */
        if (!tuc->internal->HandshakeSecret_set) {
            WOLFSSL_MSG("TSIP wasn't involved in the key-exchange.");
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        /* get digest of handshake messages */
        ret = tsip_GetMessageSha256(ssl, hash, NULL);
    }

    if (ret == 0) {
        if ((ret = tsip_hw_lock()) == 0) {

            tuc->internal->HandshakeClientTrafficKey_set = 0;

            err = R_TSIP_Tls13GenerateClientHandshakeTrafficKey(
                    &(tuc->internal->handle13),
                    TSIP_TLS13_MODE_FULL_HANDSHAKE,
                    &(tuc->internal->handshakeSecret13Idx),
                    hash,
                    &(tuc->internal->clientWriteKey13Idx),
                    &(tuc->internal->clientFinished13Idx));

            if (err != TSIP_SUCCESS) {
                WOLFSSL_MSG(
                    "R_TSIP_Tls13GenerateClientHandshakeTrafficKey error");
                ret = WC_HW_E;
            }

            /* key derivation succeeded */
            if (ret == 0) {
                tuc->internal->HandshakeClientTrafficKey_set = 1;
            }

            tsip_hw_unlock();
        }
        else {
            WOLFSSL_MSG("mutex locking error");
        }
    }

    WOLFSSL_LEAVE("tsipTls13DeriveClientHandshakeKeys", ret);
    return ret;
}

static int tsipTls13DeriveServerHandshakeKeys(struct WOLFSSL* ssl)
{
    int ret = 0;
    e_tsip_err_t    err = TSIP_SUCCESS;
    int             isTLS13 = 0;
    TsipUserCtx*    tuc = NULL;
    byte            hash[WC_SHA256_DIGEST_SIZE];


    WOLFSSL_ENTER("tsipTls13DeriveServerHandshakeKeys");
    if (ssl == NULL)
        ret = BAD_FUNC_ARG;

    if (ret == 0) {
        if (ssl->version.major == SSLv3_MAJOR &&
            ssl->version.minor == TLSv1_3_MINOR) {
            isTLS13 = 1;
        }
        if (!isTLS13 || (ssl->options.side != WOLFSSL_CLIENT_END)) {
            ret = CRYPTOCB_UNAVAILABLE;   /* expecting to fallback to S/W */
        }
    }

    if (ret == 0) {
        /* get user context for TSIP */
        tuc = ssl->RenesasUserCtx;
        if (tuc == NULL) {
            WOLFSSL_MSG("TsipUserCtx hasn't been set to ssl.");
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        /* make sure client handshake secret is generated by tsip */
        if (!tuc->internal->HandshakeSecret_set) {
            WOLFSSL_MSG("TSIP wasn't involved in the key-exchange.");
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        /* get digest of handshake packets */
        ret = tsip_GetMessageSha256(ssl, hash, NULL);
    }

    if (ret == 0) {
        if ((ret = tsip_hw_lock()) == 0) {

            tuc->internal->HandshakeServerTrafficKey_set = 0;

            err = R_TSIP_Tls13GenerateServerHandshakeTrafficKey(
                        &(tuc->internal->handle13),
                        TSIP_TLS13_MODE_FULL_HANDSHAKE,
                        &(tuc->internal->handshakeSecret13Idx),
                        hash,
                        &(tuc->internal->serverWriteKey13Idx),
                        &(tuc->internal->serverFinished13Idx));

            if (err != TSIP_SUCCESS) {
                WOLFSSL_MSG(
                    "R_TSIP_Tls13GenerateServerHandshakeTrafficKey error");
                ret = WC_HW_E;
            }

            /* key derivation succeeded */
            if (ret == 0) {
                tuc->internal->HandshakeServerTrafficKey_set = 1;
            }

            tsip_hw_unlock();
        }
        else {
            WOLFSSL_MSG("mutex locking error");
        }
    }

    WOLFSSL_LEAVE("tsipTls13DeriveServerHandshakeKeys", ret);
    return ret;
}

static int tsipTls13DeriveTrafficKeys(struct WOLFSSL* ssl)
{
    int ret = 0;
    e_tsip_err_t    err = TSIP_SUCCESS;
    int             isTLS13 = 0;
    TsipUserCtx*    tuc = NULL;
    byte            hash[WC_SHA256_DIGEST_SIZE];


    WOLFSSL_ENTER("tsipTls13DeriveTrafficKeys");
    if (ssl == NULL)
        ret = BAD_FUNC_ARG;

    if (ret == 0) {
        if (ssl->version.major == SSLv3_MAJOR &&
            ssl->version.minor == TLSv1_3_MINOR) {
            isTLS13 = 1;
        }
        if (!isTLS13 || (ssl->options.side != WOLFSSL_CLIENT_END)) {
            ret = CRYPTOCB_UNAVAILABLE;   /* expecting to fallback to S/W */
        }
    }

    if (ret == 0) {
        /* get user context for TSIP */
        tuc = ssl->RenesasUserCtx;
        if (tuc == NULL) {
            WOLFSSL_MSG("TsipUserCtx hasn't been set to ssl.");
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        /* make sure master secret is generated by tsip */
        if (!tuc->internal->MasterSecret_set) {
            WOLFSSL_MSG("TSIP wasn't involved in the key-exchange.");
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        /* get digest of handshake messages */
        ret = tsip_GetMessageSha256(ssl, hash, NULL);
    }

    if (ret == 0) {
        if ((ret = tsip_hw_lock()) == 0) {

            tuc->internal->ServerTrafficSecret_set   = 0;
            tuc->internal->ClientTrafficSecret_set   = 0;
            tuc->internal->ServerWriteTrafficKey_set = 0;
            tuc->internal->ClientWriteTrafficKey_set = 0;

            err = R_TSIP_Tls13GenerateApplicationTrafficKey(
                        &(tuc->internal->handle13),
                        TSIP_TLS13_MODE_FULL_HANDSHAKE,
                        &(tuc->internal->masterSecret13Idx),
                        (uint8_t*)hash,
                        &(tuc->internal->serverAppTraffic13Secret),
                        &(tuc->internal->clientAppTraffic13Secret),
                        &(tuc->internal->serverAppWriteKey13Idx),
                        &(tuc->internal->clientAppWriteKey13Idx));

            if (err != TSIP_SUCCESS) {
                WOLFSSL_MSG(
                    "R_TSIP_Tls13GenerateApplicationTrafficKey error");
                ret = WC_HW_E;
            }

            /* key derivation succeeded */
            if (ret == 0) {
                tuc->internal->ServerTrafficSecret_set   = 1;
                tuc->internal->ClientTrafficSecret_set   = 1;
                tuc->internal->ServerWriteTrafficKey_set = 1;
                tuc->internal->ClientWriteTrafficKey_set = 1;
            }

            tsip_hw_unlock();
        }
        else {
            WOLFSSL_MSG("mutex locking error");
        }
    }

    WOLFSSL_LEAVE("tsipTls13DeriveTrafficKeys", ret);
    return ret;
}

static int tsipTls13UpdateClientTrafficKeys(struct WOLFSSL* ssl)
{
    int ret     = 0;
    e_tsip_err_t    err = TSIP_SUCCESS;
    int             isTLS13 = 0;
    TsipUserCtx*    tuc = NULL;

     WOLFSSL_ENTER("tsipTls13UpdateClientTrafficKeys");

    if (ssl == NULL)
        ret = BAD_FUNC_ARG;

    if (ret == 0) {
        if (ssl->version.major == SSLv3_MAJOR &&
            ssl->version.minor == TLSv1_3_MINOR) {
            isTLS13 = 1;
        }
        if (!isTLS13 || (ssl->options.side != WOLFSSL_CLIENT_END)) {
            ret = CRYPTOCB_UNAVAILABLE;   /* expecting to fallback to S/W */
        }
    }

    if (ret == 0) {
        /* get user context for TSIP */
        tuc = ssl->RenesasUserCtx;
        if (tuc == NULL) {
            WOLFSSL_MSG("TsipUserCtx hasn't been set to ssl.");
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        /* make sure application secret is generated by tsip */
        if (!tuc->internal->ClientTrafficSecret_set) {
            WOLFSSL_MSG("TSIP wasn't involved in the key-exchange.");
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }
    if (ret == 0) {
        if ((ret = tsip_hw_lock()) == 0) {

            tuc->internal->ClientWriteTrafficKey_set = 0;

            err = R_TSIP_Tls13UpdateApplicationTrafficKey(
                        &(tuc->internal->handle13),
                        TSIP_TLS13_MODE_FULL_HANDSHAKE,
                        TSIP_TLS13_UPDATE_CLIENT_KEY,
                        &(tuc->internal->clientAppTraffic13Secret),
                        &(tuc->internal->clientAppTraffic13Secret),
                        &(tuc->internal->clientAppWriteKey13Idx));
            if (err != TSIP_SUCCESS) {
                WOLFSSL_MSG("R_TSIP_Tls13UpdateApplicationTrafficKey error");
                ret = WC_HW_E;
            }
            else {
                tuc->internal->ClientWriteTrafficKey_set = 1;
            }
            tsip_hw_unlock();
        }
        else {
            WOLFSSL_MSG("mutex locking error");
        }
    }

    WOLFSSL_LEAVE("tsipTls13UpdateClientTrafficKeys", ret);
    return ret;
}

static int tsipTls13UpdateServerTrafficKeys(struct WOLFSSL* ssl)
{
    int ret     = 0;
    e_tsip_err_t    err = TSIP_SUCCESS;
    int             isTLS13 = 0;
    TsipUserCtx*    tuc = NULL;

     WOLFSSL_ENTER("tsipTls13UpdateServerTrafficKeys");

    if (ssl == NULL)
        ret = BAD_FUNC_ARG;

    if (ret == 0) {
        if (ssl->version.major == SSLv3_MAJOR &&
            ssl->version.minor == TLSv1_3_MINOR) {
            isTLS13 = 1;
        }
        if (!isTLS13 || (ssl->options.side != WOLFSSL_CLIENT_END)) {
            ret = CRYPTOCB_UNAVAILABLE;   /* expecting to fallback to S/W */
        }
    }

    if (ret == 0) {
        /* get user context for TSIP */
        tuc = ssl->RenesasUserCtx;
        if (tuc == NULL) {
            WOLFSSL_MSG("TsipUserCtx hasn't been set to ssl.");
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        /* make sure application secret is generated by tsip */
        if (!tuc->internal->ServerTrafficSecret_set) {
            WOLFSSL_MSG("TSIP wasn't involved in the key-exchange.");
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }
    if (ret == 0) {
        if ((ret = tsip_hw_lock()) == 0) {

            tuc->internal->ServerWriteTrafficKey_set = 0;

            err = R_TSIP_Tls13UpdateApplicationTrafficKey(
                        &(tuc->internal->handle13),
                        TSIP_TLS13_MODE_FULL_HANDSHAKE,
                        TSIP_TLS13_UPDATE_SERVER_KEY,
                        &(tuc->internal->serverAppTraffic13Secret),
                        &(tuc->internal->serverAppTraffic13Secret),
                        &(tuc->internal->serverAppWriteKey13Idx));
            if (err != TSIP_SUCCESS) {
                WOLFSSL_MSG("R_TSIP_Tls13UpdateApplicationTrafficKey error");
                ret = WC_HW_E;
            }
            else {
                tuc->internal->ServerWriteTrafficKey_set = 1;
            }
            tsip_hw_unlock();
        }
        else {
            WOLFSSL_MSG("mutex locking error");
        }
    }

    WOLFSSL_LEAVE("tsipTls13UpdateServerTrafficKeys", ret);
    return ret;
}

/* Derive the keys for TLS v1.3.
 *
 * ssl    The WOLFSSL object.
 * keyType  kind of keys to derive.
 *        handshake_key: when deriving keys for encrypting handshake messages.
 *        traffic_key: when deriving first keys for encrypting traffic messages.
 *        update_traffic_key: when deriving next keys for encrypting
 *        traffic messages.
 *
 * side   ENCRYPT_SIDE_ONLY: when only encryption secret needs to be derived.
 *        DECRYPT_SIDE_ONLY: when only decryption secret needs to be derived.
 *        ENCRYPT_AND_DECRYPT_SIDE: when both secret needs to be derived.
 *
 * returns 0 on success, CRYPTOCB_UNAVAILABLE when tsip can not handle and is
 * expecting to fallback to S/W, other negative values on error.
 */
int tsip_Tls13DeriveKeys(struct WOLFSSL* ssl,
                                                int keyType, int side)
{
    int ret = 0;
    int provision;

    WOLFSSL_ENTER("tsip_Tls13DeriveKeys");

    if (side == ENCRYPT_AND_DECRYPT_SIDE) {
        provision = PROVISION_CLIENT_SERVER;
    }
    else {
        provision = ((ssl->options.side != WOLFSSL_CLIENT_END) ^
                     (side == ENCRYPT_SIDE_ONLY)) ? PROVISION_CLIENT :
                                                    PROVISION_SERVER;
    }
    /* derive client key */
    switch (keyType) {
        case early_data_key:
            WOLFSSL_MSG("TSIP can't handle early data key");
            ret = CRYPTOCB_UNAVAILABLE;
            break;

        case handshake_key:
            if (provision & PROVISION_CLIENT) {
                ret = tsipTls13DeriveClientHandshakeKeys(ssl);
            }
            break;

        case traffic_key:
            ret = tsipTls13DeriveTrafficKeys(ssl);
            break;

        case update_traffic_key:
            if (provision & PROVISION_CLIENT) {
                ret = tsipTls13UpdateClientTrafficKeys(ssl);
            }
            break;

        default:
            ret = CRYPTOCB_UNAVAILABLE;
            break;
    }

    if (ret == 0) {
        /* derive server key */
        switch (keyType) {
            case early_data_key:
                WOLFSSL_MSG("TSIP can't handle early data key");
                ret = CRYPTOCB_UNAVAILABLE;
                break;

            case handshake_key:
                if (provision & PROVISION_SERVER) {
                    ret = tsipTls13DeriveServerHandshakeKeys(ssl);
                }
                break;

            case traffic_key:
                /* traffic key for server was derived in
                 * tsipTls13DeriveTrafficKeys
                 */
                break;

            case update_traffic_key:
                if (provision & PROVISION_SERVER) {
                    ret = tsipTls13UpdateServerTrafficKeys(ssl);
                }
                break;

            default:
                ret = CRYPTOCB_UNAVAILABLE;
                break;
        }
    }
    WOLFSSL_LEAVE("tsip_Tls13DeriveKeys", ret);
    return ret;
}

int tsip_Tls13DeriveMasterSecret(struct WOLFSSL* ssl)
{
    int ret = 0;
    e_tsip_err_t    err = TSIP_SUCCESS;
    int             isTLS13 = 0;
    TsipUserCtx*    tuc = NULL;

    WOLFSSL_ENTER("tsip_Tls13DeriveMasterSecret");

    if (ssl == NULL)
        ret = BAD_FUNC_ARG;

    if (ret == 0) {
        if (ssl->version.major == SSLv3_MAJOR &&
            ssl->version.minor == TLSv1_3_MINOR) {
            isTLS13 = 1;
        }
        if (!isTLS13 || (ssl->options.side != WOLFSSL_CLIENT_END)) {
            ret = CRYPTOCB_UNAVAILABLE;   /* expecting to fallback to S/W */
        }
    }
    if (ret == 0) {
        /* get user context for TSIP */
        tuc = ssl->RenesasUserCtx;
        if (tuc == NULL) {
            WOLFSSL_MSG("TsipUserCtx hasn't been set to ssl.");
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }
    if (ret == 0) {
        /* make sure handshake secret and verify data has been set by TSIP */
        if (!tuc->internal->HandshakeSecret_set ||
            !tuc->internal->HandshakeVerifiedData_set) {
            WOLFSSL_MSG("TSIP wasn't involved in the key-exchange.");
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }
    if (ret == 0) {
        if ((ret = tsip_hw_lock()) == 0) {

            tuc->internal->MasterSecret_set = 0;

            err = R_TSIP_Tls13GenerateMasterSecret(
                        &(tuc->internal->handle13),
                        TSIP_TLS13_MODE_FULL_HANDSHAKE,
                        &(tuc->internal->handshakeSecret13Idx),
                        (uint32_t*)tuc->internal->verifyData13Idx,
                        &(tuc->internal->masterSecret13Idx));

            if (err != TSIP_SUCCESS) {
                WOLFSSL_MSG(
                    "R_TSIP_Tls13GenerateMasterSecret( error");
                ret = WC_HW_E;
            }

            if (ret == 0) {
                tuc->internal->MasterSecret_set = 1;
            }

            tsip_hw_unlock();
        }
        else {
            WOLFSSL_MSG("mutex locking error");
        }
    }

    WOLFSSL_LEAVE("tsip_Tls13DeriveMasterSecret", ret);
    return ret;
}

/* verify handshake
 * ssl     WOLFSSL object
 * hash    buffer holding decrypted finished message content from server.
 *
 */
static int tsipTls13VerifyHandshake(struct WOLFSSL* ssl,
                                    const byte* hash)/*finished message*/
{
    int             ret = 0;
    e_tsip_err_t    err = TSIP_SUCCESS;
    int             isTLS13 = 0;
    TsipUserCtx*    tuc = NULL;
    word32          msgHash[WC_SHA256_DIGEST_SIZE/sizeof(word32)];

    WOLFSSL_ENTER("tsipTls13VerifyHandshake");

    if (ssl == NULL)
        ret = BAD_FUNC_ARG;

    if (ret == 0) {
        if (ssl->version.major == SSLv3_MAJOR &&
            ssl->version.minor == TLSv1_3_MINOR) {
            isTLS13 = 1;
        }
        if (!isTLS13 || (ssl->options.side != WOLFSSL_CLIENT_END)) {
            ret = CRYPTOCB_UNAVAILABLE;   /* expecting to fallback to S/W */
        }
    }

    if (ret == 0) {
        /* get user context for TSIP */
        tuc = ssl->RenesasUserCtx;
        if (tuc == NULL) {
            WOLFSSL_MSG("TsipUserCtx hasn't been set to ssl.");
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        /* make sure handshake secret is generated by tsip */
        if (!tuc->internal->HandshakeServerTrafficKey_set) {
            WOLFSSL_MSG("TSIP wasn't involved in the key-exchange.");
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }
    /* get digest of handshake messages */
    if (ret == 0) {
        ret = tsip_GetMessageSha256(ssl, (byte*)msgHash, NULL);
    }

    if (ret == 0) {
        if ((ret = tsip_hw_lock()) == 0) {

            tuc->internal->HandshakeVerifiedData_set = 0;

            err = R_TSIP_Tls13ServerHandshakeVerification(
                                TSIP_TLS13_MODE_FULL_HANDSHAKE,
                                &(tuc->internal->serverFinished13Idx),
                                (uint8_t*)msgHash,
                                (uint8_t*)hash,
                                (uint32_t*)(tuc->internal->verifyData13Idx));

            if (err == TSIP_ERR_VERIFICATION_FAIL) {
                WOLFSSL_MSG("Handshake verification error");
                ret = VERIFY_FINISHED_ERROR;
            }
            else if (err != TSIP_SUCCESS) {
                WOLFSSL_MSG("R_TSIP_Tls13ServerHandshakeVerification error");
                ret = WC_HW_E;
            }
            if (ret == 0) {
                WOLFSSL_MSG("Verified handshake");
                tuc->internal->HandshakeVerifiedData_set = 1;
            }

            tsip_hw_unlock();
        }
        else {
            WOLFSSL_MSG("mutex locking error");
        }
    }

    WOLFSSL_LEAVE("tsipTls13VerifyHandshake", ret);
    return ret;
}

/* handles finished message from server.
 * verify hmac in the message. Also output verify data to
 * TsipUserCtx.verifyDataIdx, which is used for deriving master secret.
 *
 *  ssl       WOLFSSL object
 *  input     the buffer holding decrypted finished message, type and padding
 *  inOutIdx  On entry, the index into the message content of Finished.
 *            On exit, the index of byte after the Finished message and padding.
 *  size      Length of message content(excluding type and padding)
 *  totalSz   Length in the record header. means message + type + pad.
 *  return    0, on success, others on failure.
 */
int tsip_Tls13HandleFinished(
                                            struct WOLFSSL* ssl,
                                            const byte*     input,
                                            word32*         inOutIdx,
                                            word32          size,
                                            word32          totalSz)
{
    int ret = 0;

    WOLFSSL_ENTER("tsip_Tls13HandleFinished");

    if (ssl == NULL || input == NULL || inOutIdx == NULL) {
        ret = BAD_FUNC_ARG;
    }

    if (ret == 0) {
        ret = tsipTls13VerifyHandshake(ssl, input + *inOutIdx);
    }

    if (ret == 0) {
        /* Force input exhaustion at ProcessReply by consuming padSz. */
        *inOutIdx += size + ssl->keys.padSz;

        ssl->options.serverState = SERVER_FINISHED_COMPLETE;
    }

    WOLFSSL_LEAVE("tsip_Tls13HandleFinished", ret);
    return ret;
}

/* Build TLS v1.3 Message and make it encrypted with AEAD algorithm.
 * TSIP supports AES-GCM and AES-CCM.
 * ssl         The WOLFSSL object.
 * output      The buffer to write record message to.
 * outSz       Size of the buffer being written into.
 * input       The handshake message data to encrypt (excluding trailing type).
 * inSz        The size of the handshake message (including message header).
 * type        The real content type being put after the message data.
 * hashOutput  Whether to hash the unencrypted record data.
 * returns     the size of the record including header, CRYPTOCB_UNAVAILABLE
 *             when tsip can not handle and is expecting to fallback to S/W,
 *             other negative values on error.
 */
int tsip_Tls13BuildMessage(struct WOLFSSL* ssl,
                                         byte* output,
                                         int   outSz,
                                         const byte* input,
                                         int   inSz,
                                         int   type,
                                         int hashOutput)
{
    int ret = 0;
    int recSz;
    int isTLS13 = 0;
    RecordLayerHeader* rl = NULL;
    (void)outSz;

    WOLFSSL_ENTER("tsip_Tls13BuildMessage");

    if (ssl == NULL || output == NULL || input == NULL) {
        ret = BAD_FUNC_ARG;
    }

    if (ret == 0) {
        if (ssl->version.major == SSLv3_MAJOR &&
            ssl->version.minor == TLSv1_3_MINOR) {
            isTLS13 = 1;
        }
        if (!isTLS13 || (ssl->options.side != WOLFSSL_CLIENT_END)) {
            ret = CRYPTOCB_UNAVAILABLE;   /* expecting to fallback to S/W */
        }
    }

    if (ret == 0) {
        /* make sure hash algorithm is SHA256 */
        if (ssl->specs.mac_algorithm != sha256_mac ) {
            WOLFSSL_MSG("TSIP can't handle this hash algorithm.");
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        if ((ssl->specs.bulk_cipher_algorithm != wolfssl_aes_gcm) &&
            (ssl->specs.bulk_cipher_algorithm != wolfssl_aes_ccm)) {
            WOLFSSL_MSG("TSIP can't handle the specified algorithm");
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        /* set size in record header */
        recSz = inSz + 1 + ssl->specs.aead_mac_size;

        /* update the record header with the new size. */
        rl = (RecordLayerHeader*)output;
        rl->type    = application_data;
        rl->pvMajor = ssl->version.major;
        rl->pvMinor = TLSv1_2_MINOR;
        c16toa((word16)recSz, rl->length);

        if (input != output + RECORD_HEADER_SZ) {
            XMEMCPY(output + RECORD_HEADER_SZ, input, inSz);
        }

        if (hashOutput) {
            ret = HashOutput(ssl, output, RECORD_HEADER_SZ + inSz, 0);
        }
    }
    if (ret == 0) {
        /* The real record content type goes at the end of the data. */
        output[RECORD_HEADER_SZ + inSz] = (byte)type;

        ret = tsip_Tls13AesEncrypt(ssl,
                           output + RECORD_HEADER_SZ, /* output */
                           output + RECORD_HEADER_SZ, /* plain message */
                           inSz + 1); /* plain data size(= inSz + 1 for type) */

        if (ret > 0) {
            ret = recSz + RECORD_HEADER_SZ; /* return record size */
        }
    }

    WOLFSSL_LEAVE("tsip_Tls13BuildMessage", ret);
    return ret;
}

/* Send finished message to the server.
 *
 * ssl     WOLFSSL object
 * output  buffer to output packet, including packet header and finished message
 * outSz   buffer size of output
 * input   buffer holding finished message
 * hashOut
 * return  0 on success, CRYPTOCB_UNAVAILABLE when TSIP can not handle,
 *         other negative values on error.
 */
int tsip_Tls13SendFinished(
                                struct WOLFSSL* ssl,
                                byte*       output,
                                int         outSz,
                                const byte* input,
                                int         hashOut)
{
    int ret         = 0;
    int finishedSz;
    int headerSz    = HANDSHAKE_HEADER_SZ;
    int recordSz;

    WOLFSSL_ENTER("tsip_Tls13SendFinished");

    if (ssl == NULL || output == NULL || input == NULL || outSz == 0) {
        ret  = BAD_FUNC_ARG;
    }

    if (ret == 0) {
        finishedSz  = ssl->specs.hash_size;

        ret = tsip_Tls13GetHmacMessages(ssl, (byte*)&input[headerSz]);
    }

    if (ret == 0) {
       recordSz = WC_MAX_DIGEST_SIZE + DTLS_HANDSHAKE_HEADER_SZ + MAX_MSG_EXTRA;
        /* check for available size */
        ret = CheckAvailableSize(ssl, recordSz);
        recordSz = 0;
    }

    if (ret == 0) {
        recordSz = tsip_Tls13BuildMessage(ssl,
                                     output, outSz,
                                     input, headerSz + finishedSz,
                                     handshake, hashOut);

        if (recordSz > 0) {
            ssl->options.clientState    = CLIENT_FINISHED_COMPLETE;
            ssl->options.handShakeState = HANDSHAKE_DONE;
            ssl->options.handShakeDone  = 1;
            ssl->buffers.outputBuffer.length += recordSz; /* advance length */

            ret = SendBuffered(ssl);
        }
        else {
            ret = recordSz;
        }
    }
    WOLFSSL_LEAVE("tsip_Tls13SendFinished", ret);
    return ret;
}

/* Parse and handle a TLS v1.3 CertificateVerify message sent from a server.
 *
 * ssl       WOLFSSL object
 * input     buffer holding certificate verify message
 * inOutIdx  On entry, the index into the message buffer of
 *           CertificateVerify.
 *           On exit, the index of byte after the CertificateVerify message.
 * totalSz   The length of the current handshake message.
 * return    0 on success, CRYPTOCB_UNAVAILABLE when TSIP can not handle,
 *           other negative values on error.
 */
int tsip_Tls13CertificateVerify(struct WOLFSSL* ssl,
                                            const byte* input, word32* inOutIdx,
                                            word32 totalSz)
{
    int     ret = 0;
    byte*   sigData = NULL;
    byte    hiAlgo,loAlgo;
    int     messageSz;
    word16  signatureLen;
    word16  idx;
    e_tsip_err_t  err = TSIP_SUCCESS;
    TsipUserCtx*  tuc = NULL;
    e_tsip_tls13_signature_scheme_type_t sig_scheme;

    WOLFSSL_ENTER("tsip_Tls13CertificateVerify");


    if (ssl == NULL || input == NULL || inOutIdx == NULL) {
        ret = BAD_FUNC_ARG;
    }

    if (ret == 0) {
        if (ENUM_LEN + ENUM_LEN > totalSz) {
            ret = BUFFER_ERROR;
        }
        /* parse certificate verify message to get hash-algo */
        hiAlgo  = *(input + *inOutIdx);
        loAlgo  = *(input + *inOutIdx + 1);
    }
    if (ret == 0) {
        /* get signature length */
        ato16(input + *inOutIdx + 2, &signatureLen);

        if (ENUM_LEN + ENUM_LEN + OPAQUE16_LEN > totalSz) {
            ret = BUFFER_ERROR;
        }
    }
    if (ret == 0) {
        if (ENUM_LEN + ENUM_LEN + OPAQUE16_LEN + signatureLen > totalSz) {
            ret = BUFFER_ERROR;
        }
    }
    if (ret == 0) {
        /* check if tsip accepts signature algorithm */
        if (hiAlgo == NEW_SA_MAJOR && loAlgo == sha256_mac) {
            /* rsa_pss_rsae_sha256 0x0804 */
            WOLFSSL_MSG("Peer sent RSA sig");
            sig_scheme = TSIP_TLS13_SIGNATURE_SCHEME_RSA_PSS_RSAE_SHA256;
        }
        else if (hiAlgo == 0x04 && loAlgo == ecc_dsa_sa_algo) {
            /* ecdsa_secp256r1_sha256 0x0403 */
            WOLFSSL_MSG("Peer sent ECC sig");
            sig_scheme = TSIP_TLS13_SIGNATURE_SCHEME_ECDSA_SECP256R1_SHA256;
        }
        else {
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        /* get user context for TSIP */
        tuc = ssl->RenesasUserCtx;
        if (tuc == NULL) {
            WOLFSSL_MSG("TsipUserCtx is not set to ssl.");
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    /* check if peer's public key is stored */
    if (ret == 0) {
        if (ssl->peerSceTsipEncRsaKeyIndex == NULL) {
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        /* create sign data */
        sigData = tuc->internal->sigDataCertVerify;

        idx = 0;
        ForceZero(sigData, sizeof(tuc->internal->sigDataCertVerify));
        XMEMSET(sigData, TSIP_SIGNING_DATA_PREFIX_BYTE,
                                                TSIP_SIGNING_DATA_PREFIX_SZ);

        idx += TSIP_SIGNING_DATA_PREFIX_SZ;
        XMEMCPY(&sigData[idx], serverCertVfyLabel, TSIP_CERT_VFY_LABEL_SZ);

        idx += TSIP_CERT_VFY_LABEL_SZ;
        ret = tsip_GetMessageSha256(ssl, &sigData[idx], &messageSz);
    }

    if (ret == 0) {

        if ((ret = tsip_hw_lock()) == 0) {
            err = R_TSIP_Tls13CertificateVerifyVerification(
                        (uint32_t*)ssl->peerSceTsipEncRsaKeyIndex,
                        sig_scheme,
                        &sigData[idx],
                        (uint8_t*)(input + *inOutIdx),
                        totalSz);

            if (err == TSIP_SUCCESS) {

                *inOutIdx += totalSz;
                *inOutIdx += ssl->keys.padSz;
                ssl->options.peerAuthGood = 1;
                ssl->options.havePeerVerify = 1;
            #if !defined(NO_WOLFSSL_CLIENT)
                if (ssl->options.side == WOLFSSL_CLIENT_END)
                    ssl->options.serverState = SERVER_CERT_VERIFY_COMPLETE;
            #endif
            }
            else {
                ret = WC_HW_E;
                if (err == TSIP_ERR_AUTHENTICATION) {
                    WOLFSSL_MSG("Certificate Verification failed.");
                }
            }

            tsip_hw_unlock();
        }
        else {
            WOLFSSL_MSG("mutex locking error");
        }
    }

    WOLFSSL_LEAVE("tsip_Tls13CertificateVerify", ret);
    return ret;
}

/* Send the TLS v1.3 CertificateVerify message. A part of the message is
 * processed by TSIP for acceleration.
 *
 * Prior to this function call, the appropriate key-pair should be set via
 * tsip_use_PrivateKey_buffer_TLS and tsip_use_PublicKey_buffer_TLS APIs.
 * Those key pair can be generated by the tool named
 * "Renesas secure flash programmer".
 * When RSA certificate is used, both public and private keys should be set.
 * The public key is used for self-verify the generated certificateVerify
 * message. When ECC certificate is used, the self-verify will be performed only
 * WOLFSSL_CHECK_SIG_FAULTS is defined.
 *
 * Returns 0 on success, CRYPTOCB_UNAVAILABLE when the required key is not
 * provided or unsupported algo is specified and otherwise failure.
 */
int tsip_Tls13SendCertVerify(WOLFSSL* ssl)
{
    int ret = 0;
    e_tsip_err_t    err = TSIP_SUCCESS;
    byte*           sigData = NULL;
    word16          idx;
    int             isTLS13 = 0;
    TsipUserCtx*    tuc     = NULL;
    byte*           output  = NULL;
    byte*           message = NULL;
    byte*           derSig  = NULL;
    int             isRsa   = -1;
    uint32_t        messageSz,recordSz,hashSz;
    byte            hash[WC_SHA256_DIGEST_SIZE];
    byte            sig_rs[R_TSIP_ECDSA_DATA_BYTE_SIZE];
    tsip_rsa_byte_data_t   rsa_sig,rsa_hash;
    tsip_ecdsa_byte_data_t ecdsa_sig,ecdsa_hash;

    WOLFSSL_ENTER("tsip_Tls13SendCertVerify");
    (void)derSig;
    (void)rsa_sig;
    (void)rsa_hash;
    (void)ecdsa_sig;
    (void)ecdsa_hash;
    (void)sig_rs;

    if (ssl == NULL) {
        ret = BAD_FUNC_ARG;
    }

    if (ret == 0) {
        if (ssl->version.major == SSLv3_MAJOR &&
            ssl->version.minor == TLSv1_3_MINOR)
            isTLS13 = 1;

        /* check if it's TLS13 and client side */
        if (!isTLS13 || ssl->options.side != WOLFSSL_CLIENT_END) {
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        /* get user context for TSIP */
        tuc = ssl->RenesasUserCtx;
        if (tuc == NULL) {
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        #if !defined(NO_RSA)
        if (ssl->options.haveRSA)
            isRsa = 1;
        else
        #endif
        #ifdef HAVE_ECC
        if (ssl->options.haveECC)
            isRsa = 0;
        else
        #endif /* HAVE_ECC */
            isRsa = -1;

        if (isRsa != 0 && isRsa != 1) {
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        ret = tsip_ImportPrivateKey(tuc, tuc->wrappedKeyType);
    }

    if (ret == 0) {
        if (isRsa) {
            if (!tuc->internal->ClientRsa2048PrivKey_set) {
                ret = NO_PRIVATE_KEY;
            }
        }
        else {
            if (!tuc->internal->ClientEccPrivKey_set) {
                ret = NO_PRIVATE_KEY;
            }
        }
    }

    if (ret == 0) {
        /* get message hash */
        ForceZero(hash, sizeof(hash));
        ret = tsip_GetMessageSha256(ssl, hash, (int*)&hashSz);
    }

    if (ret == 0) {
        recordSz = WC_MAX_CERT_VERIFY_SZ + MAX_MSG_EXTRA * 2;
        /* check for available size */
        ret = CheckAvailableSize(ssl, recordSz);
        recordSz = 0;
    }

    if (ret == 0) {
        /* get output buffer for record header */
        output = ssl->buffers.outputBuffer.buffer +
                 ssl->buffers.outputBuffer.length;

        /* buffer for message header */
        message = output + RECORD_HEADER_SZ;
    }

    /* generate signature */
    if (ret == 0) {
        if ((ret = tsip_hw_lock()) == 0) {
            if (isRsa) {
                err = R_TSIP_Tls13CertificateVerifyGenerate(
                            (uint32_t*)&(tuc->internal->Rsa2048PrivateKeyIdx),
                            TSIP_TLS13_SIGNATURE_SCHEME_RSA_PSS_RSAE_SHA256,
                                                hash,
                                                message + HANDSHAKE_HEADER_SZ,
                                                &messageSz);
            }
            else {
                err = R_TSIP_Tls13CertificateVerifyGenerate(
                            (uint32_t*)&(tuc->internal->EcdsaPrivateKeyIdx),
                            TSIP_TLS13_SIGNATURE_SCHEME_ECDSA_SECP256R1_SHA256,
                                                hash,
                                                message + HANDSHAKE_HEADER_SZ,
                                                &messageSz);
            }
            if (err != TSIP_SUCCESS) {
                WOLFSSL_MSG("failed to make certificate verify message");
                ret = WC_HW_E;
            }
            tsip_hw_unlock();
        }
        else {
            WOLFSSL_MSG("mutex locking error");
        }
    }

    if (ret == 0) {
        if (isRsa) {
            ret = tsip_ImportPublicKey(tuc, tuc->wrappedKeyType);
        }
        else {
#if defined(WOLFSSL_CHECK_SIG_FAULTS)
            ret = tsip_ImportPublicKey(tuc, tuc->wrappedKeyType);
#endif
        }
    }

    if (ret == 0) {
        if (isRsa) {
            if (!tuc->internal->ClientRsa2048PubKey_set) {
                ret = NO_PRIVATE_KEY;
            }
        }
        else {
#if defined(WOLFSSL_CHECK_SIG_FAULTS)
            if (!tuc->ClientEccPubKey_set) {
                ret = NO_PRIVATE_KEY;
            }
#endif /* WOLFSSL_CHECK_SIG_FAULTS */
        }
    }

    if (ret == 0) {
        sigData = tuc->internal->sigDataCertVerify;

        idx = 0;
        ForceZero(sigData, sizeof(tuc->internal->sigDataCertVerify));
        XMEMSET(sigData, TSIP_SIGNING_DATA_PREFIX_BYTE,
                                                TSIP_SIGNING_DATA_PREFIX_SZ);

        idx += TSIP_SIGNING_DATA_PREFIX_SZ;
        XMEMCPY(&sigData[idx], clientCertVfyLabel, TSIP_CERT_VFY_LABEL_SZ);

        idx += TSIP_CERT_VFY_LABEL_SZ;
        XMEMCPY(&sigData[idx], hash, hashSz);
    }

    if (ret == 0) {
        /* extract signature data from generated CertificateVerify message */
        if (!isRsa) {
#if defined(WOLFSSL_CHECK_SIG_FAULTS)
            idx = 4;
            derSig = message +
                        HANDSHAKE_HEADER_SZ + HASH_SIG_SIZE + VERIFY_HEADER;
            if (derSig[idx] == 0x00)
                idx++;
            XMEMCPY(sig_rs, &derSig[idx], R_TSIP_ECDSA_DATA_BYTE_SIZE / 2);
            idx += (R_TSIP_ECDSA_DATA_BYTE_SIZE / 2) + ASN_TAG_SZ + 1;
            if (derSig[idx] == 0x00)
                idx++;
            XMEMCPY(&sig_rs[R_TSIP_ECDSA_DATA_BYTE_SIZE / 2],
                            &derSig[idx], R_TSIP_ECDSA_DATA_BYTE_SIZE / 2);
#endif /* WOLFSSL_CHECK_SIG_FAULTS */
        }
    }

    if (ret == 0) {
        if ((ret = tsip_hw_lock()) == 0) {
            if (isRsa) {
                rsa_sig.pdata  = message + HANDSHAKE_HEADER_SZ +
                                                HASH_SIG_SIZE + VERIFY_HEADER;
                rsa_hash.pdata = sigData;
                rsa_hash.data_length = TSIP_SIGNING_DATA_PREFIX_SZ +
                                         TSIP_CERT_VFY_LABEL_SZ + sizeof(hash);

                rsa_hash.data_type = 0;

                err = R_TSIP_RsassaPss2048SignatureVerification(
                            &rsa_sig, &rsa_hash,
                            &(tuc->internal)->Rsa2048PublicKeyIdx,
                            R_TSIP_RSA_HASH_SHA256);
                WOLFSSL_MSG("Perform self-verify for rsa signature");
            }
            else {
                err = TSIP_SUCCESS;
#if defined(WOLFSSL_CHECK_SIG_FAULTS)
                ecdsa_sig.pdata  = sig_rs;
                ecdsa_hash.pdata = sigData;
                ecdsa_hash.data_length = TSIP_SIGNING_DATA_PREFIX_SZ +
                                         TSIP_CERT_VFY_LABEL_SZ + sizeof(hash);
                ecdsa_hash.data_type = 0;

                err = R_TSIP_EcdsaP256SignatureVerification(
                            &ecdsa_sig, &ecdsa_hash,
                            &tuc->EcdsaPublicKeyIdx);
                WOLFSSL_MSG("Perform self-verify for ecc signature");
#endif /* WOLFSSL_CHECK_SIG_FAULTS */
            }
            if (err != TSIP_SUCCESS) {
                WOLFSSL_MSG("Failed to verify signature");
                ret = VERIFY_SIGN_ERROR;
            }
            tsip_hw_unlock();
        }
        else {
            WOLFSSL_MSG("mutex locking error");
        }
    }

    /* create message header */
    if (ret == 0) {

        ((HandShakeHeader*)message)->type = certificate_verify;

        c32to24(messageSz, ((HandShakeHeader*)message)->length);

        recordSz = tsip_Tls13BuildMessage(ssl, output, 0, message,
                                          messageSz + HANDSHAKE_HEADER_SZ,
                                                             handshake, 1);

        if (recordSz > 0) {
            ssl->buffers.outputBuffer.length += recordSz;
            ret = SendBuffered(ssl);
        }
        else {
            ret = recordSz;
        }
    }

    WOLFSSL_LEAVE("tsip_Tls13SendCertVerify", ret);
    return ret;
}
#endif /* WOLFSSL_TLS13 */
#endif /* WOLFSSL_RENESAS_TSIP_TLS */


#if defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >=109)

static uint32_t GetTsipCipherSuite(
                    uint8_t cipherSuiteFirst,
                    uint8_t cipherSuite)
{
    WOLFSSL_ENTER("GetTsipCipherSuite");
    uint32_t tsipCipher;

    if (cipherSuiteFirst == CIPHER_BYTE)
    {
        switch(cipherSuite) {

            case TLS_RSA_WITH_AES_128_CBC_SHA: /*2F*/
                tsipCipher = R_TSIP_TLS_RSA_WITH_AES_128_CBC_SHA; /*0*/
                break;

            case TLS_RSA_WITH_AES_128_CBC_SHA256:
                tsipCipher = R_TSIP_TLS_RSA_WITH_AES_128_CBC_SHA256;
                break;

            case TLS_RSA_WITH_AES_256_CBC_SHA:
                tsipCipher = R_TSIP_TLS_RSA_WITH_AES_256_CBC_SHA;
                break;

            case TLS_RSA_WITH_AES_256_CBC_SHA256:
                tsipCipher = R_TSIP_TLS_RSA_WITH_AES_256_CBC_SHA256;
                break;

            default:
                tsipCipher = (uint32_t)WOLFSSL_TSIP_ILLEGAL_CIPHERSUITE;
                break;
        }
        WOLFSSL_LEAVE("GetTsipCipherSuite", tsipCipher);
        return tsipCipher;
    }
    else if (cipherSuiteFirst == ECC_BYTE)
    {
        tsipCipher = (uint32_t)WOLFSSL_TSIP_ILLEGAL_CIPHERSUITE;

        switch(cipherSuite) {

            case TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256:
                tsipCipher = R_TSIP_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256;
                break;

            case TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256:
                tsipCipher = R_TSIP_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256;
                break;

            case TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
                tsipCipher = R_TSIP_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256;
                break;

            case TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
                tsipCipher = R_TSIP_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256;
                break;

            default:
                tsipCipher = (uint32_t)WOLFSSL_TSIP_ILLEGAL_CIPHERSUITE;
                break;
        }
    }
    else {
        tsipCipher = (uint32_t)WOLFSSL_TSIP_ILLEGAL_CIPHERSUITE;
    }

    WOLFSSL_LEAVE("GetTsipCipherSuite", tsipCipher);

    return tsipCipher;
}

/*  Attempt to get a public key exchanged with the peer in ECDHE.
 *  the public key is verified by given signature then stored into ctx.
 *
 *  return WOLFSSL_SUCCESS on success, WOLFSSL_FAILURE on failure.
 */
static int tsip_ServerKeyExVerify(
    word32      type,       /* public key type 0:RSA2048 2:ECDSA P-256 */
    WOLFSSL*    ssl,
    const byte* sig,
    word32      sigSz,
    void*       ctx)
{
    int     ret = WOLFSSL_FAILURE;
    byte    qx[MAX_ECC_BYTES], qy[MAX_ECC_BYTES];
    byte*   peerkey = NULL;
    word32  qxLen = sizeof(qx), qyLen = sizeof(qy);
    TsipUserCtx*   userCtx = NULL;

    WOLFSSL_ENTER("tsip_ServerKeyExVerify");

    /* sanity check */
    if (ssl == NULL || sig == NULL || ctx == NULL)
        return ret;

    userCtx = (TsipUserCtx*)ctx;

    /* export public peer public key */
    ret = wc_ecc_export_public_raw(ssl->peerEccKey, qx, &qxLen, qy, &qyLen);

    if (ret != 0) {
        WOLFSSL_MSG("failed to export peer ecc key");
        WOLFSSL_LEAVE("tsip_ServerKeyExVerify", ret);
        return ret;
    }
    /* make peer ecc key data for SCE */
    /* 0padding(24bit) || 04(8bit) || Qx(256bit) || Qy(256bit) */
    peerkey = (byte*)XMALLOC((3 + 1 + qxLen + qyLen), NULL,
                                                 DYNAMIC_TYPE_TMP_BUFFER);
    if (peerkey == NULL) {
        WOLFSSL_MSG("failed to malloc ecc key");
        WOLFSSL_LEAVE("tsip_ServerKeyExVerify", ret);
        return WOLFSSL_FAILURE;
    }

    ForceZero(peerkey, (3 + 1 + qxLen + qyLen));
    peerkey[3] = ECC_POINT_UNCOMP;
    XMEMCPY(&peerkey[4], qx, qxLen);
    XMEMCPY(&peerkey[4+qxLen], qy, qyLen);

    /* 0 : RSA 2048bit, 1 : Reserved, 2 : ECDSA P-256 */
    if ((ret = tsip_hw_lock()) == 0) {
        ret = R_TSIP_TlsServersEphemeralEcdhPublicKeyRetrieves(
            type,
            (uint8_t*) ssl->arrays->clientRandom,
            (uint8_t*) ssl->arrays->serverRandom,
            (uint8_t*) peerkey,
            (uint8_t*) sig,
            (uint32_t*)ssl->peerSceTsipEncRsaKeyIndex,
            (uint32_t*)userCtx->internal->encrypted_ephemeral_ecdh_public_key);

        if (ret !=TSIP_SUCCESS) {
            WOLFSSL_MSG("R_TSIP_TlsServersEphemeralEcdhPublicKeyRetrieves failed");
        }
        else {
            ret = WOLFSSL_SUCCESS;
        }

        tsip_hw_unlock();
    }
    else {
        WOLFSSL_MSG("Failed to lock tsip hw");
    }

    XFREE(peerkey, NULL, DYNAMIC_TYPE_TMP_BUFFER);

    WOLFSSL_LEAVE("tsip_ServerKeyExVerify", ret);
    return ret;
}
/*
 *  return 0 on success
 */
int wc_tsip_RsaVerify(
        WOLFSSL* ssl,
        byte* sig,      word32 sigSz,
        byte** out,
        const byte* key,
        word32 keySz,
        void* ctx)
{
    int ret;

    WOLFSSL_ENTER("tsip_RsaVerify");

    if (tsip_usable(ssl, 0))
        ret = tsip_ServerKeyExVerify(0, ssl, sig, sigSz, ctx);
    else
        ret = CRYPTOCB_UNAVAILABLE;

    if (ret == WOLFSSL_SUCCESS)
        ret = 0;

    WOLFSSL_LEAVE("tsip_RsaVerify", ret);
    return ret;
}
/*  Verify signature for Server Key Exchange with TSIP
 *  TSIP can handle prime256v1 curve and sha256 hash
 *  parameters:
 *   ssl    WOLFSSL object
 *   sig    buffer holding DER encoded ecdsa signature data
 *   sigSz  signature data size
 *   hash   buffer holding sha256 hash data
 *   hashSz hash data size
 *   key    buffer holding peer's public key (NOT used in this function)
 *   keySz  public key size((NOT used in this function))
 *   result address of the variable to output result
 *   ctx    context
 *  return 0 on success, CRYPTOCB_UNAVAILABLE in case TSIP cannot handle
 */
int wc_tsip_EccVerify(
        WOLFSSL*  ssl,
        const byte* sig,    word32 sigSz,
        const byte* hash,   word32 hashSz,
        const byte* key,    word32 keySz,
        int*  result,       void*  ctx)
{
    int         ret = WOLFSSL_FAILURE;
    uint8_t     sigforSCE [R_TSIP_ECDSA_DATA_BYTE_SIZE] = {0};
    const byte  rs_size = R_TSIP_ECDSA_DATA_BYTE_SIZE/2;
    byte        offset = 0x3;

    WOLFSSL_ENTER("wc_tsip_EccVerify");

    /* check if TSIP can handle given cipher suite */
    if (!tsip_usable(ssl, 0)) {
        WOLFSSL_MSG("Cannot handle cipher suite by TSIP");
        WOLFSSL_LEAVE("wc_tsip_EccVerify", CRYPTOCB_UNAVAILABLE);
        return CRYPTOCB_UNAVAILABLE;
    }

    /* in TLS1.3 */
    if (ssl->version.major == SSLv3_MAJOR &&
        ssl->version.minor == TLSv1_3_MINOR) {
        WOLFSSL_LEAVE("wc_tsip_EccVerify", CRYPTOCB_UNAVAILABLE);
        return CRYPTOCB_UNAVAILABLE;
    }

    /* concatenate r and s parts of the signature so that TSIP can handle it */
    /* r */
    if (sig[offset] == 0x20) {
        XMEMCPY(sigforSCE, &sig[offset+1], rs_size);

        offset = 0x25;
        /* s */
        if (sig[offset] == 0x20) {
          XMEMCPY(&sigforSCE[rs_size], &sig[offset+1], rs_size);
        }
        else {
          XMEMCPY(&sigforSCE[rs_size], &sig[offset+2], rs_size);
        }
    }
    else {
        XMEMCPY(sigforSCE, &sig[offset+2], rs_size);

        offset = 0x26;
        /* s */
        if (sig[offset] == rs_size) {
          XMEMCPY(&sigforSCE[rs_size], &sig[offset+1], rs_size);
        }
        else {
          XMEMCPY(&sigforSCE[rs_size], &sig[offset+2], rs_size);
        }
    }

    ret = tsip_ServerKeyExVerify(2, ssl, sigforSCE, 64, ctx);

    if (ret == WOLFSSL_SUCCESS) {
        *result = 1;
        ret = 0; /* for success */
    }
    else
        *result = 0;

    WOLFSSL_LEAVE("wc_tsip_EccVerify", ret);
    return ret;
}

/*
 *  generate premaster secret
 *  1. generate P256 ECC key pair for ECDHE key exchange
 *  2. generate pre-master secret
 *  output 64 bytes premaster secret to "out" buffer.
 */
int wc_tsip_EccSharedSecret(
    WOLFSSL* ssl,
    ecc_key* otherKey,
    unsigned char* pubKeyDer,   unsigned int* pubKeySz,
    unsigned char* out,         unsigned int* outlen,
    int side, void* ctx)
{
    int       ret;
    TsipUserCtx* usrCtx = (TsipUserCtx*)ctx;

    (void)ssl;
    (void)otherKey;

    WOLFSSL_ENTER("wc_tsip_EccSharedSecret");
    /* sanity check */
    if (ssl == NULL || pubKeyDer == NULL || pubKeySz == NULL ||
        out == NULL || outlen == NULL || ctx == NULL) {
        WOLFSSL_LEAVE("wc_tsip_EccSharedSecret", WOLFSSL_FAILURE);
        return WOLFSSL_FAILURE;
    }
    if ((ret = tsip_hw_lock()) == 0) {
        /* Generate ECC public key for key exchange */
        ret = R_TSIP_GenerateTlsP256EccKeyIndex(
                    &(usrCtx->internal->ecc_p256_wrapped_key),
                    (uint8_t*)&(usrCtx->internal->ecc_ecdh_public_key));

        if (ret == TSIP_SUCCESS) {

            /* copy generated ecdh public key into buffer */
            pubKeyDer[0] = ECC_POINT_UNCOMP;
            *pubKeySz = 1 + sizeof(usrCtx->internal->ecc_ecdh_public_key);
            XMEMCPY(&pubKeyDer[1], &(usrCtx->internal->ecc_ecdh_public_key),
                        sizeof(usrCtx->internal->ecc_ecdh_public_key));

            /* Generate Premaster Secret */
            ret = R_TSIP_TlsGeneratePreMasterSecretWithEccP256Key(
            (uint32_t*)&(usrCtx->internal->encrypted_ephemeral_ecdh_public_key),
            &(usrCtx->internal->ecc_p256_wrapped_key),
            (uint32_t*)out/* pre-master secret 64 bytes */);
        }
        if (ret == TSIP_SUCCESS) {
            *outlen = 64;
            wolfSSL_CTX_SetGenMasterSecretCb(ssl->ctx,
                                                Renesas_cmn_genMasterSecret);
            wolfSSL_SetGenMasterSecretCtx(ssl, usrCtx);

        }

        tsip_hw_unlock();
    }
    else {
        WOLFSSL_MSG("Failed to lock tsip hw");
    }
    WOLFSSL_LEAVE("wc_tsip_EccSharedSecret", ret);
    return ret;
}


WOLFSSL_API void tsip_set_callbacks(WOLFSSL_CTX* ctx)
{
    WOLFSSL_ENTER("tsip_set_callbacks");
    wolfSSL_CTX_SetEccVerifyCb(ctx, (CallbackEccVerify)Renesas_cmn_EccVerify);
    wolfSSL_CTX_SetRsaVerifyCb(ctx, (CallbackRsaVerify)Renesas_cmn_RsaVerify);
    wolfSSL_CTX_SetGenPreMasterCb(ctx, Renesas_cmn_generatePremasterSecret);
    wolfSSL_CTX_SetRsaEncCb(ctx, Renesas_cmn_RsaEnc);
#if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_AEAD_ONLY)
    wolfSSL_CTX_SetVerifyMacCb(ctx, (CallbackVerifyMac)Renesas_cmn_VerifyHmac);
#endif /* !WOLFSSL_NO_TLS12 && !WOLFSSL_AEAD_ONLY */
    wolfSSL_CTX_SetEccSharedSecretCb(ctx, NULL);
    /* Set ssl-> options.sendVerify to SEND_CERT by the following two
     * registrations. This will allow the client certificate to be sent to
     * the server even if the private key is empty. The two callbacks do
     * virtually nothing.
     */
    #ifdef WOLFSSL_TLS13
    #ifdef HAVE_ECC
    wolfSSL_CTX_SetEccSignCb(ctx, Renesas_cmn_EccSignCb);
    #endif
    #ifndef NO_RSA
    wolfSSL_CTX_SetRsaSignCb(ctx, Renesas_cmn_RsaSignCb);
    #endif
    #endif /* WOLFSSL_TLS13 */

    wolfSSL_CTX_SetRsaSignCheckCb(ctx, Renesas_cmn_RsaSignCheckCb);

    /* set heap-hint to tsip_heap_hint so that tsip sha funcs can refer it */
    if (ctx->heap != NULL) {
        tsip_heap_hint = ctx->heap;
    }

    WOLFSSL_LEAVE("tsip_set_callbacks", 0);
}

WOLFSSL_API int tsip_set_callback_ctx(WOLFSSL* ssl, void* user_ctx)
{
    WOLFSSL_ENTER("tsip_set_callback_ctx");

    TsipUserCtx* uCtx = (TsipUserCtx*)user_ctx;
    if (user_ctx == NULL || ssl == NULL) {
        WOLFSSL_MSG("user ctx is null");
        return BAD_FUNC_ARG;
    }

    ForceZero(uCtx, sizeof(TsipUserCtx));

    uCtx->internal =
        (TsipUserCtx_Internal*)XMALLOC(sizeof(TsipUserCtx_Internal),
                                        ssl->heap,
                                        DYNAMIC_TYPE_TMP_BUFFER);

    if (!uCtx->internal) {
        printf("Failed to allocate memory for user ctx internal");
        return MEMORY_E;
    }

    ForceZero(uCtx->internal, sizeof(TsipUserCtx_Internal));

    uCtx->internal->ssl  = ssl;
    uCtx->internal->ctx  = ssl->ctx;
    uCtx->internal->heap = ssl->heap;
    uCtx->internal->side = ssl->ctx->method->side;

    ssl->RenesasUserCtx = user_ctx;     /* ssl doesn't own user_ctx */

    wolfSSL_SetEccVerifyCtx(ssl, user_ctx);
    wolfSSL_SetRsaEncCtx(ssl, user_ctx);
    wolfSSL_SetRsaVerifyCtx(ssl, user_ctx);
    wolfSSL_SetRsaSignCtx(ssl, user_ctx);
    wolfSSL_SetGenPreMasterCtx(ssl, user_ctx);
    wolfSSL_SetEccSharedSecretCtx(ssl, NULL);
#if !defined(WOLFSSL_NO_TLS12) && !defined(WOLFSSL_AEAD_ONLY)
    wolfSSL_SetVerifyMacCtx(ssl, user_ctx);
#endif /* !WOLFSSL_NO_TLS12 && !WOLFSSL_AEAD_ONLY */
    /* set up crypt callback */
    wc_CryptoCb_CryptInitRenesasCmn(ssl, user_ctx);
    WOLFSSL_LEAVE("tsip_set_callback_ctx", 0);
    return 0;
}

#elif defined(WOLFSSL_RENESAS_TSIP_TLS) && (WOLFSSL_RENESAS_TSIP_VER >=106)

/* convert def to tsip define */
static byte _tls2tsipdef(byte cipher)
{
    byte def = R_TSIP_TLS_RSA_WITH_AES_128_CBC_SHA;
    switch(cipher) {
        case l_TLS_RSA_WITH_AES_128_CBC_SHA:
            break;
        case l_TLS_RSA_WITH_AES_128_CBC_SHA256:
            def = R_TSIP_TLS_RSA_WITH_AES_128_CBC_SHA256;
            break;
        case l_TLS_RSA_WITH_AES_256_CBC_SHA:
            def = R_TSIP_TLS_RSA_WITH_AES_256_CBC_SHA;
            break;
        case l_TLS_RSA_WITH_AES_256_CBC_SHA256:
            def = R_TSIP_TLS_RSA_WITH_AES_256_CBC_SHA256;
            break;
        default:break;
    }
    return def;
}
#endif

#ifdef WOLFSSL_RENESAS_TSIP_TLS
/*
 * Import wrapped private key then convert it into TSIP key_index format.
 * The target key should be set with tsip_use_PrivateKey_buffer in advance.
 * Acceptable key types are:
 *   TSIP_KEY_TYPE_RSA2048     rsa 2048 bit key
 *   TSIP_KEY_TYPE_RSA3072     rsa 3072 bit key
 *   TSIP_KEY_TYPE_RSA4096     rsa 4096 bit key
 *   TSIP_KEY_TYPE_ECDSAP256   ecdsa p256r1 key
 *   TSIP_KEY_TYPE_ECDSAP384   ecdsa p384r1 key
 */
int tsip_ImportPrivateKey(TsipUserCtx* tuc, int keyType)
{
    int          ret = 0;
    e_tsip_err_t err = TSIP_SUCCESS;
    uint8_t* provisioning_key = g_user_key_info.encrypted_provisioning_key;
    uint8_t* iv               = g_user_key_info.iv;
    uint8_t* encPrivKey;

    WOLFSSL_ENTER("tsip_ImportPrivateKey");

    if (tuc == NULL)
        return BAD_FUNC_ARG;

    encPrivKey = tuc->internal->wrappedPrivateKey;

    if (encPrivKey == NULL || provisioning_key == NULL || iv == NULL) {
        WOLFSSL_MSG("Missing some key materials used for import" );
        return CRYPTOCB_UNAVAILABLE;
    }

    if (ret == 0) {
        if (keyType != tuc->wrappedKeyType) {
            WOLFSSL_MSG("No public key of specified type is set" );
            return CRYPTOCB_UNAVAILABLE;
        }
    }

    if ((ret = tsip_hw_lock()) == 0) {
        switch (keyType) {

            #if !defined(NO_RSA)
            case TSIP_KEY_TYPE_RSA2048:

                tuc->internal->ClientRsa2048PrivKey_set = 0;
                err = R_TSIP_GenerateRsa2048PrivateKeyIndex(
                                    provisioning_key, iv, (uint8_t*)encPrivKey,
                                    &(tuc->internal->Rsa2048PrivateKeyIdx));
                if (err == TSIP_SUCCESS) {
                    tuc->internal->ClientRsa2048PrivKey_set = 1;
                }
                else {
                    ret = WC_HW_E;
                }
                break;
            #endif

            case TSIP_KEY_TYPE_RSA4096:
                /* not supported as of TSIPv1.15 */
                ret = CRYPTOCB_UNAVAILABLE;
                break;

            #if defined(HAVE_ECC)
            case TSIP_KEY_TYPE_ECDSAP256:

                tuc->internal->ClientEccPrivKey_set = 0;
                err = R_TSIP_GenerateEccP256PrivateKeyIndex(
                                    provisioning_key, iv, (uint8_t*)encPrivKey,
                                    &(tuc->internal->EcdsaPrivateKeyIdx));
                if (err == TSIP_SUCCESS) {
                    tuc->internal->ClientEccPrivKey_set = 1;
                }
                else {
                    ret = WC_HW_E;
                }
                break;
            #endif

            default:
                ret = BAD_FUNC_ARG;
                break;
        }
        tsip_hw_unlock();
    }
    else {
        WOLFSSL_MSG("mutex locking error");
    }
    WOLFSSL_LEAVE("tsip_ImportPrivateKey", ret);
    return ret;
}

#endif /* WOLFSSL_RENESAS_TSIP_TLS */

/*
 * Import wrapped public key then convert it into TSIP key_index format.
 * The target key should be set with tsip_use_PublicKey_buffer in advance.
 * Acceptable key types are:
 *   TSIP_KEY_TYPE_RSA2048     rsa 2048 bit key
 *   TSIP_KEY_TYPE_RSA3072     rsa 3072 bit key
 *   TSIP_KEY_TYPE_RSA4096     rsa 4096 bit key
 *   TSIP_KEY_TYPE_ECDSAP256   ecdsa p256r1 key
 *   TSIP_KEY_TYPE_ECDSAP384   ecdsa p384r1 key
 */
int tsip_ImportPublicKey(TsipUserCtx* tuc, int keyType)
{
    int          ret = 0;
    e_tsip_err_t err = TSIP_SUCCESS;
    uint8_t* provisioning_key = g_user_key_info.encrypted_provisioning_key;
    uint8_t* iv               = g_user_key_info.iv;
    uint8_t* encPubKey;

    WOLFSSL_ENTER("tsip_ImportPublicKey");

    if (tuc == NULL ) {
        return BAD_FUNC_ARG;
    }

    encPubKey = tuc->internal->wrappedPublicKey;

    if (encPubKey == NULL || provisioning_key == NULL || iv == NULL) {
        WOLFSSL_MSG("Missing some key materials used for import" );
        return CRYPTOCB_UNAVAILABLE;
    }

    if (ret == 0) {
        if (keyType != tuc->wrappedKeyType) {
            WOLFSSL_MSG("No public key of specified type is set" );
            return CRYPTOCB_UNAVAILABLE;
        }
    }

    if ((ret = tsip_hw_lock()) == 0) {
        switch (keyType) {

        #if !defined(NO_RSA)
        #if ((defined(TSIP_RSAES_2048) && TSIP_RSAES_2048 == 1) || \
            (defined(TSIP_RSASSA_2048) && TSIP_RSASSA_2048 == 1))
            case TSIP_KEY_TYPE_RSA2048:
            #if defined(WOLFSSL_RENESAS_TSIP_TLS)
                tuc->internal->ClientRsa2048PubKey_set = 0;
            #elif defined(WOLFSSL_RENESAS_TSIP_CRYPTONLY)
                XFREE(tuc->rsa2048pub_keyIdx, NULL, DYNAMIC_TYPE_RSA_BUFFER);
                tuc->keyflgs_crypt.bits.rsapub2048_key_set = 0;
                tuc->rsa2048pub_keyIdx =
                    (tsip_rsa2048_public_key_index_t*)XMALLOC(
                        sizeof(tsip_rsa2048_public_key_index_t), NULL,
                        DYNAMIC_TYPE_RSA_BUFFER);
                if (tuc->rsa2048pub_keyIdx == NULL) {
                    return MEMORY_E;
                }
            #endif
                err = R_TSIP_GenerateRsa2048PublicKeyIndex(
                                    provisioning_key, iv, (uint8_t*)encPubKey,
                                #if defined(WOLFSSL_RENESAS_TSIP_TLS)
                                     &(tuc->internal->Rsa2048PublicKeyIdx)
                                #elif defined(WOLFSSL_RENESAS_TSIP_CRYPTONLY)
                                     tuc->rsa2048pub_keyIdx
                                #endif
                                    );
                if (err == TSIP_SUCCESS) {
                #if defined(WOLFSSL_RENESAS_TSIP_TLS)
                    tuc->internal->ClientRsa2048PubKey_set = 1;
                #elif defined(WOLFSSL_RENESAS_TSIP_CRYPTONLY)
                    tuc->keyflgs_crypt.bits.rsapub2048_key_set = 1;
                #endif
                }
                else {
                    ret = WC_HW_E;
                }
                break;
        #endif /* TSIP_RSAES_2048 */
            case TSIP_KEY_TYPE_RSA4096:
                /* not supported as of TSIPv1.15 */
                ret = CRYPTOCB_UNAVAILABLE;
                break;
        #endif /* !NO_RSA */

        #if defined(HAVE_ECC)
            case TSIP_KEY_TYPE_ECDSAP256:
            case TSIP_KEY_TYPE_ECDSAP384:
            #if defined(WOLFSSL_RENESAS_TSIP_TLS)
                tuc->internal->ClientEccPubKey_set = 0;
            #elif defined(WOLFSSL_RENESAS_TSIP_CRYPTONLY)
                tuc->keyflgs_crypt.bits.eccpub_key_set = 0;
            #endif
                if (keyType == TSIP_KEY_TYPE_ECDSAP256) {
                #if defined(TSIP_ECDSA_P256) && TSIP_ECDSA_P256 == 1
                    err = R_TSIP_GenerateEccP256PublicKeyIndex(
                                    provisioning_key, iv, (uint8_t*)encPubKey,
                            #if defined(WOLFSSL_RENESAS_TSIP_TLS)
                                    &(tuc->internal->EcdsaPublicKeyIdx)
                            #elif defined(WOLFSSL_RENESAS_TSIP_CRYPTONLY)
                                    &tuc->eccpub_keyIdx
                            #endif
                    );
                #else
                    err = NOT_COMPILED_IN;
                #endif
                }
                else if (keyType == TSIP_KEY_TYPE_ECDSAP384) {
                #if defined(TSIP_ECDSA_P384) && TSIP_ECDSA_P384 == 1
                    err = R_TSIP_GenerateEccP384PublicKeyIndex(
                                    provisioning_key, iv, (uint8_t*)encPubKey,
                            #if defined(WOLFSSL_RENESAS_TSIP_TLS)
                                    &(tuc->internal->EcdsaPublicKeyIdx)
                            #elif defined(WOLFSSL_RENESAS_TSIP_CRYPTONLY)
                                    &tuc->eccpub_keyIdx
                            #endif
                    );
                #else
                    err = NOT_COMPILED_IN;
                #endif
                }
                if (err == TSIP_SUCCESS) {
                #if defined(WOLFSSL_RENESAS_TSIP_TLS)
                    tuc->internal->ClientEccPubKey_set = 1;
                #elif defined(WOLFSSL_RENESAS_TSIP_CRYPTONLY)
                    tuc->keyflgs_crypt.bits.eccpub_key_set = 1;
                #endif
                }
                else {
                    ret = WC_HW_E;
                }
                break;
        #endif

            default:
                ret = BAD_FUNC_ARG;
                break;
        }
        tsip_hw_unlock();
    }
    else {
        WOLFSSL_MSG("mutex locking error");
    }
    WOLFSSL_LEAVE("tsip_ImportPublicKey", ret);
    return ret;
}

#if defined(WOLFSSL_RENESAS_TSIP_TLS)
/* check if tsip tls functions can be used for the cipher      */
/* return  :1 when tsip can be used , 0 not be used.           */
int tsip_usable(const WOLFSSL *ssl, uint8_t session_key_generated)
{
    byte cipher0 = ssl->options.cipherSuite0;
    byte cipher  = ssl->options.cipherSuite;
    byte side    = ssl->options.side;
    int  ret     = WOLFSSL_SUCCESS;
    const Ciphers *enc;
    const Ciphers *dec;

    WOLFSSL_ENTER("tsip_usable");

    /* sanity check */
    if (ssl == NULL) {
        WOLFSSL_MSG("ssl is NULL");
        ret = BAD_FUNC_ARG;
    }

    /* when rsa key index == NULL, tsip isn't used for cert verification. */
    /* in the case, we cannot use TSIP.                                   */
    if (ret == WOLFSSL_SUCCESS) {
        if (!ssl->peerSceTsipEncRsaKeyIndex) {
            WOLFSSL_MSG("ssl->peerSceTsipEncRsaKeyIndex is NULL");
            ret = WOLFSSL_FAILURE;
        }
    }

    if (ret == WOLFSSL_SUCCESS) {
        if (session_key_generated) {
            enc = &ssl->encrypt;
            dec = &ssl->decrypt;
            if (enc == NULL || dec == NULL) {
                /* something wrong */
                ret = WOLFSSL_FAILURE;
            }
            if (enc->aes == NULL || dec->aes == NULL) {
                ret = WOLFSSL_FAILURE;
            }
            if (enc->aes->ctx.setup == 0) {
                /* session key for SCE is not created */
                ret = WOLFSSL_FAILURE;
            }
        }
    }

    /* when enabled Extended Master Secret, we cannot use TSIP. */

    if (ret == WOLFSSL_SUCCESS) {
        if (ssl->options.haveEMS) {
            WOLFSSL_MSG("ssl->options.haveEMS");
            ret = WOLFSSL_FAILURE;
        }
    }
    /* TSIP works only for TLS client */
    if (ret == WOLFSSL_SUCCESS) {
        if (side != WOLFSSL_CLIENT_END) {
            WOLFSSL_MSG("Not client side");
            ret = WOLFSSL_FAILURE;
        }
    }
    /* Check if TSIP can handle cipher suite */
    if (ret == WOLFSSL_SUCCESS) {
        if (
            (cipher0 == CIPHER_BYTE &&
            (cipher == l_TLS_RSA_WITH_AES_128_CBC_SHA ||
             cipher == l_TLS_RSA_WITH_AES_128_CBC_SHA256 ||
             cipher == l_TLS_RSA_WITH_AES_256_CBC_SHA ||
             cipher == l_TLS_RSA_WITH_AES_256_CBC_SHA256))
        #if (WOLFSSL_RENESAS_TSIP_VER >= 109)
            ||
            (cipher0 == ECC_BYTE &&
            (cipher == l_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 ||
             cipher == l_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 ||
             cipher == l_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 ||
             cipher == l_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256))
        #endif
        #if (WOLFSSL_RENESAS_TSIP_VER >= 114)
            ||
            (cipher0 == TLS13_BYTE &&
            (cipher == l_TLS_AES_128_GCM_SHA256 ||
             cipher == l_TLS_AES_128_CCM_SHA256))
        #endif
        ) {
            WOLFSSL_MSG("supported cipher suite");
        }
        else {
            WOLFSSL_MSG("unsupported cipher suite");
            ret = WOLFSSL_FAILURE;;
        }
    }

    WOLFSSL_LEAVE("tsip_usable", ret);
    return ret;
}
#endif /* WOLFSSL_RENESAS_TSIP_TLS */

#ifndef SINGLE_THREADED
/*
* lock hw engine.
* this should be called before using engine.
*/
int tsip_hw_lock(void)
{
    int ret = 0;

    if (tsip_CryptHwMutexInit_ == 0) {

        ret = tsip_CryptHwMutexInit(&tsip_mutex);

        if (ret == 0) {
            tsip_CryptHwMutexInit_ = 1;
        }
        else {
            WOLFSSL_MSG(" mutex initialization failed.");
            return -1;
        }
    }
    if (tsip_CryptHwMutexLock(&tsip_mutex) != 0) {
        /* this should not happens */
        return -1;
    }

    return ret;
}

/*
* release hw engine
*/
void tsip_hw_unlock(void)
{
    tsip_CryptHwMutexUnLock(&tsip_mutex);
}
#endif

/* open TSIP driver
 * return 0 on success.
 */
int tsip_Open(void)
{
    int ret = TSIP_SUCCESS;

    WOLFSSL_ENTER("tsip_Open");

    if ((ret = tsip_hw_lock()) == 0) {

#if defined(WOLFSSL_RENESAS_TSIP) && (WOLFSSL_RENESAS_TSIP_VER>=109)

        ret = R_TSIP_Open(NULL,NULL);
        if (ret != TSIP_SUCCESS) {
            WOLFSSL_MSG("RENESAS TSIP Open failed");
        }

    #if defined(WOLFSSL_RENESAS_TSIP_TLS)
        if (ret == TSIP_SUCCESS && g_user_key_info.encrypted_user_tls_key) {

            ret = R_TSIP_GenerateTlsRsaPublicKeyIndex(
                    g_user_key_info.encrypted_provisioning_key,
                    g_user_key_info.iv,
                    g_user_key_info.encrypted_user_tls_key,
                    &g_user_key_info.user_rsa2048_tls_pubindex); /* OUT */

            R_TSIP_Close();       /* close once */

            if (ret != TSIP_SUCCESS) {

                WOLFSSL_MSG("R_TSIP_GenerateTlsRsa: NG");

            }
            else {

                /* open again with newly created TLS public key index*/
                ret = R_TSIP_Open(
                        &g_user_key_info.user_rsa2048_tls_pubindex,
                        (tsip_update_key_ring_t*)s_inst2);

                if (ret != TSIP_SUCCESS) {
                    WOLFSSL_MSG("R_TSIP_(Re)Open: NG");
                }

                /* init vars */
                g_CAscm_Idx = (uint32_t)-1;
            }
        }
    #endif

#elif defined(WOLFSSL_RENESAS_TSIP) && (WOLFSSL_RENESAS_TSIP_VER>=106)

        ret = R_TSIP_Open((uint32_t*)s_flash, s_inst1, s_inst2);
        if (ret != TSIP_SUCCESS) {
            WOLFSSL_MSG("RENESAS TSIP Open failed");
        }
       #if defined(WOLFSSL_RENESAS_TLS)
        /* generate TLS Rsa public key for Certificate verification */
        if (ret == TSIP_SUCCESS && g_user_key_info.encrypted_user_tls_key) {
            ret = R_TSIP_GenerateTlsRsaPublicKeyIndex(
                    g_user_key_info.encrypted_session_key,
                    g_user_key_info.iv,
                    g_user_key_info.encrypted_user_tls_key,
                    &g_user_key_info.user_rsa2048_tls_pubindex);

            if (ret != TSIP_SUCCESS) {
                WOLFSSL_MSG("R_TSIP_GenerateTlsRsaPublicKeyIndex failed");
            }
            else {
                /* close once */
                tsip_Close();
                /* open again with s_inst[] */
                XMEMCPY(s_inst1,
                    g_user_key_info.user_rsa2048_tls_pubindex.value,
                    sizeof(s_inst1));
                ret = R_TSIP_Open((uint32_t*)s_flash, s_inst1, s_inst2);
                if (ret != TSIP_SUCCESS) {
                    WOLFSSL_MSG("R_TSIP_(Re)Open failed");
                }

                /* init vars */
                g_CAscm_Idx = (uint32_t)-1;
            }
        }
    #endif
#else
        ret = R_TSIP_Open((uint32_t*)s_flash, s_inst1, s_inst2);
        if (ret != TSIP_SUCCESS) {
            WOLFSSL_MSG("RENESAS TSIP Open failed");
        }
#endif
        /* unlock hw */
        tsip_hw_unlock();
    }
    else
        WOLFSSL_MSG("Failed to lock tsip hw ");

    WOLFSSL_LEAVE("tsip_Open", ret);
    return ret;
}

/* close TSIP driver */
void tsip_Close(void)
{
    WOLFSSL_ENTER("tsip_Close");
    int ret;

    if ((ret = tsip_hw_lock()) == 0) {
        /* close TSIP */
        ret = R_TSIP_Close();
#if defined(WOLFSSL_RENESAS_TSIP_TLS)
        g_CAscm_Idx = (uint32_t)-1;
#endif
        /* unlock hw */
        tsip_hw_unlock();
        if (ret != TSIP_SUCCESS) {
            WOLFSSL_MSG("RENESAS TSIP Close failed");
        }
    }
    else
        WOLFSSL_MSG("Failed to unlock tsip hw");
    WOLFSSL_LEAVE("tsip_Close", 0);
}

int wc_tsip_GenerateRandBlock(byte* output, word32 sz)
{
    /* Generate PRNG based on NIST SP800-90A AES CTR-DRBG */
    int ret = 0;
    word32 buffer[4];

    while (sz > 0) {
        word32 len = sizeof(buffer);

        if (sz < len) {
            len = sz;
        }
        /* return 4 words random number*/
        ret = R_TSIP_GenerateRandomNumber((uint32_t*)buffer);
        if(ret == TSIP_SUCCESS) {
            XMEMCPY(output, &buffer, len);
            output += len;
            sz -= len;
         } else
            return ret;
    }
    return ret;
}

#if (WOLFSSL_RENESAS_TSIP_VER>=109)
void tsip_inform_user_keys_ex(
    byte*     encrypted_provisioning_key,
    byte*     iv,
    byte*     encrypted_user_tls_key,
    word32    encrypted_user_tls_key_type)
{
    WOLFSSL_ENTER("tsip_inform_user_keys_ex");

    XMEMSET(&g_user_key_info, 0, sizeof(g_user_key_info));
    g_user_key_info.encrypted_provisioning_key = NULL;
    g_user_key_info.iv = NULL;

    if (encrypted_provisioning_key) {
        g_user_key_info.encrypted_provisioning_key = encrypted_provisioning_key;
    }
    if (iv) {
        g_user_key_info.iv = iv;
    }
    if (encrypted_user_tls_key) {
        g_user_key_info.encrypted_user_tls_key = encrypted_user_tls_key;
    }

    g_user_key_info.encrypted_user_tls_key_type = encrypted_user_tls_key_type;
    WOLFSSL_LEAVE("tsip_inform_user_keys_ex", 0);
}
#elif (WOLFSSL_RENESAS_TSIP_VER>=106)
/* inform user key                                                     */
/* the function expects to be called from user application             */
/* user has to create these key information by Renesas tool in advance.*/
void tsip_inform_user_keys(
    byte *encrypted_session_key,
    byte *iv,
    byte *encrypted_user_tls_key)
{
    g_user_key_info.encrypted_session_key = NULL;
    g_user_key_info.iv = NULL;
    g_user_key_info.encrypted_user_tls_key = NULL;

    if (encrypted_session_key) {
        g_user_key_info.encrypted_session_key = encrypted_session_key;
    }
    if (iv) {
        g_user_key_info.iv = iv;
    }
    if (encrypted_user_tls_key) {
        g_user_key_info.encrypted_user_tls_key = encrypted_user_tls_key;
    }
}
#endif

/* Support functions for TSIP TLS Capability */
#if defined(WOLFSSL_RENESAS_TSIP_TLS)

/* to inform ca certificate sign */
/* signature format expects RSA 2048 PSS with SHA256 */
void tsip_inform_cert_sign(const byte *sign)
{
    if (sign)
        ca_cert_sig = sign;
}
/* Sha1Hmac */
int wc_tsip_Sha1HmacGenerate(
        const WOLFSSL *ssl,
        const byte* myInner,
        word32      innerSz,
        const byte* in,
        word32      sz,
        byte*       digest)
{
    WOLFSSL_ENTER("wc_tsip_Sha1HmacGenerate");

    tsip_hmac_sha_handle_t _handle;
    tsip_hmac_sha_key_index_t key_index;
    int ret;

    if ((ssl == NULL) || (myInner == NULL) || (in == NULL) ||
        (digest == NULL)) {
        WOLFSSL_LEAVE("wc_tsip_Sha1HmacGenerate", BAD_FUNC_ARG);
        return BAD_FUNC_ARG;
    }

    if ((ret = tsip_hw_lock()) != 0) {
        WOLFSSL_MSG("hw lock failed");
        WOLFSSL_LEAVE("wc_tsip_Sha1HmacGenerate", ret);
        return ret;
    }

    key_index = ssl->keys.tsip_client_write_MAC_secret;

    ret = R_TSIP_Sha1HmacGenerateInit(
                    &_handle,
                    &key_index);

    if (ret == TSIP_SUCCESS)
        ret = R_TSIP_Sha1HmacGenerateUpdate(
                    &_handle,
                    (uint8_t*)myInner,
                    (uint32_t)innerSz);

    if (ret == TSIP_SUCCESS)
        ret = R_TSIP_Sha1HmacGenerateUpdate(
                    &_handle,
                    (uint8_t*)in,
                    sz);

    if (ret == TSIP_SUCCESS)
        ret = R_TSIP_Sha1HmacGenerateFinal(
                    &_handle,
                    digest);

    tsip_hw_unlock();

    WOLFSSL_LEAVE("wc_tsip_Sha1HmacGenerate", ret);
    return ret;
}


/* Sha256Hmac */
int wc_tsip_Sha256HmacGenerate(
        const WOLFSSL *ssl,
        const byte* myInner,
        word32      innerSz,
        const byte* in,
        word32      sz,
        byte*       digest)
{
    WOLFSSL_ENTER("wc_tsip_Sha256HmacGenerate");

    tsip_hmac_sha_handle_t _handle;
    tsip_hmac_sha_key_index_t key_index;
    int ret;

    if ((ssl == NULL) || (myInner == NULL) || (in == NULL) ||
        (digest == NULL))
      return BAD_FUNC_ARG;

    key_index = ssl->keys.tsip_client_write_MAC_secret;

    if ((ret = tsip_hw_lock()) != 0) {
        WOLFSSL_MSG("hw lock failed");
        return ret;
    }

    ret = R_TSIP_Sha256HmacGenerateInit(
                &_handle,
                &key_index);

    if (ret == TSIP_SUCCESS) {
        ret = R_TSIP_Sha256HmacGenerateUpdate(
                &_handle,
                (uint8_t*)myInner,
                innerSz);
    }
    else {
        WOLFSSL_MSG("R_TSIP_Sha256HmacGenerateInit failed");
    }

    if (ret == TSIP_SUCCESS) {
        ret = R_TSIP_Sha256HmacGenerateUpdate(
                &_handle,
                (uint8_t*)in,
                sz);
    }
    else {
        WOLFSSL_MSG("R_TSIP_Sha256HmacGenerateUpdate: inner failed");
    }
    if (ret == TSIP_SUCCESS) {

        ret = R_TSIP_Sha256HmacGenerateFinal(
                &_handle,
                digest);
    }
    else {
        WOLFSSL_MSG("R_TSIP_Sha256HmacGenerateUpdate: in failed");
    }
    if (ret != TSIP_SUCCESS) {
        WOLFSSL_MSG("R_TSIP_Sha256HmacGenerateFinal failed");
        ret = 1;
    }
    /* unlock hw */
    tsip_hw_unlock();
    WOLFSSL_LEAVE("wc_tsip_Sha256HmacGenerate", ret);
    return ret;
}
/*
 *  Perform SHA1 and SHA256 Hmac verification
 */
int wc_tsip_ShaXHmacVerify(
        const WOLFSSL *ssl,
        const byte* message,
        word32      messageSz,
        word32      macSz,
        word32      content)
{
    WOLFSSL_ENTER("tsip_ShaXHmacVerify");

    tsip_hmac_sha_handle_t    handle;
    tsip_hmac_sha_key_index_t wrapped_key;

    shaHmacInitFn   initFn   = NULL;
    shaHmacUpdateFn updateFn = NULL;
    shaHmacFinalFn  finalFn  = NULL;

    byte   myInner[WOLFSSL_TLS_HMAC_INNER_SZ];
    int ret;

    if ((ssl == NULL) || (message == NULL)) {
        WOLFSSL_LEAVE("tsip_ShaXHmacVerify", BAD_FUNC_ARG);
        return BAD_FUNC_ARG;
    }
    wrapped_key = ssl->keys.tsip_server_write_MAC_secret;

    if (wrapped_key.type ==
#if (WOLFSSL_RENESAS_TSIP_VER >= 121)
        TSIP_KEY_INDEX_TYPE_TLS_SERVER_HMAC_SHA1_FOR_CLIENT
#else
        TSIP_KEY_INDEX_TYPE_HMAC_SHA1_FOR_TLS
#endif
     ){
        WOLFSSL_MSG("perform Sha1-Hmac verification");
        initFn   = R_TSIP_Sha1HmacVerifyInit;
        updateFn = R_TSIP_Sha1HmacVerifyUpdate;
        finalFn  = R_TSIP_Sha1HmacVerifyFinal;
    }
    else if (wrapped_key.type ==
#if (WOLFSSL_RENESAS_TSIP_VER >= 121)
        TSIP_KEY_INDEX_TYPE_TLS_SERVER_HMAC_SHA256_FOR_CLIENT
#else
        TSIP_KEY_INDEX_TYPE_HMAC_SHA256_FOR_TLS
#endif
    ) {
        WOLFSSL_MSG("perform Sha256-Hmac verification");
        initFn   = R_TSIP_Sha256HmacVerifyInit;
        updateFn = R_TSIP_Sha256HmacVerifyUpdate;
        finalFn  = R_TSIP_Sha256HmacVerifyFinal;
    }
    else {
        WOLFSSL_MSG("unsupported key type");
        WOLFSSL_LEAVE("tsip_ShaXHmacVerify", BAD_FUNC_ARG);
        return BAD_FUNC_ARG;
    }

    if ((ret = tsip_hw_lock()) != 0) {
        WOLFSSL_MSG("hw lock failed\n");
        WOLFSSL_LEAVE("tsip_ShaXHmacVerify", ret);
        return ret;
    }

    wolfSSL_SetTlsHmacInner((WOLFSSL*)ssl, (byte*)myInner,
                                                     messageSz, content, 1);

    ret = initFn(&handle, &wrapped_key);

    if (ret == TSIP_SUCCESS) {
        ret = updateFn(&handle, myInner, WOLFSSL_TLS_HMAC_INNER_SZ);
    }
    if (ret == TSIP_SUCCESS) {
        ret = updateFn(&handle, (uint8_t*)message, (uint32_t)messageSz);
    }
    if (ret == TSIP_SUCCESS) {
        ret = finalFn(&handle, (uint8_t*)(message + messageSz), (uint32_t)macSz);
    }
    if (ret != TSIP_SUCCESS) {
        WOLFSSL_MSG("TSIP Mac verification failed");
    }

    /* unlock hw */
    tsip_hw_unlock();
    WOLFSSL_LEAVE("tsip_ShaXHmacVerify", ret);
    return ret;
}

/* generate Verify Data based on master secret */
int wc_tsip_generateVerifyData(
    const byte* ms,                 /* master secret */
    const byte* side,               /* 0:client-side 1:server-side */
    const byte* handshake_hash,
          byte* hashes)             /* out */
{
    int ret ;
    uint32_t l_side = R_TSIP_TLS_GENERATE_CLIENT_VERIFY;

    WOLFSSL_ENTER("tsip_generateVerifyData");

    if ((ms == NULL) || (side == NULL) || (handshake_hash == NULL) ||
        (hashes == NULL)) {
        WOLFSSL_LEAVE("tsip_generateVerifyData", BAD_FUNC_ARG);
        return BAD_FUNC_ARG;
    }
    if (XSTRNCMP((const char*)side, (const char*)kTlsServerFinStr,
                                                FINISHED_LABEL_SZ) == 0) {
        l_side = R_TSIP_TLS_GENERATE_SERVER_VERIFY;
    }

    if ((ret = tsip_hw_lock()) == 0) {
        ret = R_TSIP_TlsGenerateVerifyData(l_side, (uint32_t*)ms,
                       (uint8_t*)handshake_hash, hashes/* out */);
        if (ret != TSIP_SUCCESS) {
            WOLFSSL_MSG("R_TSIP_TlsGenerateSessionKey failed");
        }
    }
    /* unlock hw */
    tsip_hw_unlock();
    WOLFSSL_LEAVE("tsip_generateVerifyData", ret);
    return ret;
}

/* generate keys for TLS communication */
int wc_tsip_generateSessionKey(
    WOLFSSL *ssl,
    TsipUserCtx*    ctx,
    int             devId)
{
    int ret;
    Ciphers *enc;
    Ciphers *dec;
    tsip_hmac_sha_key_index_t key_client_mac;
    tsip_hmac_sha_key_index_t key_server_mac;
    tsip_aes_key_index_t key_client_aes;
    tsip_aes_key_index_t key_server_aes;

    WOLFSSL_ENTER("wc_tsip_generateSessionKey");

    if (ssl== NULL)
      return BAD_FUNC_ARG;

    if ((ret = tsip_hw_lock()) == 0) {

#if (WOLFSSL_RENESAS_TSIP_VER>=109)

        uint32_t tsipCS = GetTsipCipherSuite(ssl->options.cipherSuite0,
                                             ssl->options.cipherSuite);

        if (tsipCS == R_TSIP_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 ||
            tsipCS == R_TSIP_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256) {
            WOLFSSL_MSG("Session key for AES-GCM generation skipped.");

            /*  Do not release ssl-> arrays to reference the master secret and
             *  randoms, as the AES GCM session key will be generated in
             *  encryption or description timing.
             */
            wolfSSL_KeepArrays(ssl);
            ret = TSIP_SUCCESS;
        }
        else {

            ret = R_TSIP_TlsGenerateSessionKey(
                    tsipCS,
                    (uint32_t*)ssl->arrays->tsip_masterSecret,
                    (uint8_t*) ssl->arrays->clientRandom,
                    (uint8_t*) ssl->arrays->serverRandom,
                    NULL, /* nonce is required only for AES-GCM key */
                    &key_client_mac,
                    &key_server_mac,
                    &key_client_aes,
                    &key_server_aes,
                    NULL, NULL);
        }
#else /* WOLFSSL_RENESAS_TSIP_VER < 109 */

        ret = R_TSIP_TlsGenerateSessionKey(
                    _tls2tsipdef(ssl->options.cipherSuite),
                    (uint32_t*)ssl->arrays->tsip_masterSecret,
                    (uint8_t*)ssl->arrays->clientRandom,
                    (uint8_t*)ssl->arrays->serverRandom,
                    &key_client_mac,
                    &key_server_mac,
                    &key_client_aes,
                    &key_server_aes,
                    NULL, NULL);
#endif
        if (ret != TSIP_SUCCESS) {
            WOLFSSL_MSG("R_TSIP_TlsGenerateSessionKey failed");
        }
        else {
            /* succeeded creating session keys */
            /* alloc aes instance for both enc and dec */
            enc = &ssl->encrypt;
            dec = &ssl->decrypt;

            if (enc) {
                if (enc->aes == NULL) {
                    enc->aes = (Aes*)XMALLOC(sizeof(Aes), ssl->heap,
                                                    DYNAMIC_TYPE_CIPHER);
                    if (enc->aes == NULL)
                        return MEMORY_E;
                }

                ForceZero(enc->aes, sizeof(Aes));
            }
            if (dec) {
                if (dec->aes == NULL) {
                    dec->aes = (Aes*)XMALLOC(sizeof(Aes), ssl->heap,
                                                    DYNAMIC_TYPE_CIPHER);
                    if (dec->aes == NULL) {
                        if (enc) {
                            XFREE(enc->aes, NULL, DYNAMIC_TYPE_CIPHER);
                        }
                        return MEMORY_E;
                    }
                }

                ForceZero(dec->aes, sizeof(Aes));
            }

            /* copy key index into aes */
            if (ssl->options.side == PROVISION_CLIENT) {
                XMEMCPY(&enc->aes->ctx.tsip_keyIdx, &key_client_aes,
                                                    sizeof(key_client_aes));
                XMEMCPY(&dec->aes->ctx.tsip_keyIdx, &key_server_aes,
                                                    sizeof(key_server_aes));
            }
            else {
                XMEMCPY(&enc->aes->ctx.tsip_keyIdx, &key_server_aes,
                                                    sizeof(key_server_aes));
                XMEMCPY(&dec->aes->ctx.tsip_keyIdx, &key_client_aes,
                                                    sizeof(key_client_aes));
            }

            /* copy hac key index into keys */
            ssl->keys.tsip_client_write_MAC_secret = key_client_mac;
            ssl->keys.tsip_server_write_MAC_secret = key_server_mac;

            /* set up key size and marked ready */
            if (enc) {
                enc->aes->ctx.keySize = ssl->specs.key_size;
                enc->aes->ctx.setup = 1;
                /* ready-for-use flag will be set when SetKeySide() is called */
            }
            /* set up key size and marked ready */
            if (dec) {
                dec->aes->ctx.keySize = ssl->specs.key_size;
                dec->aes->ctx.setup = 1;
                /* ready-for-use flag will be set when SetKeySide() is called */
            }

            if (ctx->internal->tsip_cipher ==
                            R_TSIP_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 ||
                ctx->internal->tsip_cipher ==
                            R_TSIP_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256) {
                enc->aes->nonceSz = AEAD_NONCE_SZ;
                dec->aes->nonceSz = AEAD_NONCE_SZ;
            }

            enc->aes->devId = devId;
            dec->aes->devId = devId;

            ctx->internal->session_key_set = 1;
        }
        /* unlock hw */
        tsip_hw_unlock();
    }
    else
        WOLFSSL_MSG("hw lock failed");

    WOLFSSL_LEAVE("wc_tsip_generateSessionKey", ret);
    return ret;
}



/* generate Master secrete by TSIP */
#if (WOLFSSL_RENESAS_TSIP_VER>=109)

int wc_tsip_generateMasterSecretEx(
        byte        cipherSuiteFirst,
        byte        cipherSuite,
        const byte *pr, /* pre-master    */
        const byte *cr, /* client random */
        const byte *sr, /* server random */
        byte *ms)
{
    int ret;

    WOLFSSL_ENTER("tsip_generateMasterSecretEx");

    if ((pr == NULL) || (cr == NULL) || (sr == NULL) ||
        (ms == NULL))
      return BAD_FUNC_ARG;

    uint32_t tsipCS = GetTsipCipherSuite(cipherSuiteFirst,cipherSuite);
    if (tsipCS == 0xffffffff)
        return BAD_FUNC_ARG;

    if ((ret = tsip_hw_lock()) == 0) {
        ret = R_TSIP_TlsGenerateMasterSecret(
            tsipCS,
            (uint32_t*)pr,
            (uint8_t*)cr, (uint8_t*)sr, (uint32_t*)ms);
        if (ret != TSIP_SUCCESS) {
            WOLFSSL_MSG("R_TSIP_TlsGenerateMasterSecret failed");
        }
        /* unlock hw */
        tsip_hw_unlock();
    }
    else {
        WOLFSSL_MSG(" hw lock failed ");
    }
    WOLFSSL_LEAVE("tsip_generateMasterSecretEx", ret);
    return ret;
}

#else /* WOLFSSL_RENESAS_TSIP_VER < 109 */

int wc_tsip_generateMasterSecret(
        const byte* pr, /* pre-master    */
        const byte* cr, /* client random */
        const byte* sr, /* server random */
        byte*       ms)
{
    int ret;
    WOLFSSL_ENTER("tsip_generateMasterSecret");
    if ((pr == NULL) || (cr == NULL) || (sr == NULL) ||
        (ms == NULL))
      return BAD_FUNC_ARG;

    if ((ret = tsip_hw_lock()) == 0) {
        ret = R_TSIP_TlsGenerateMasterSecret(
                (uint32_t*)pr,
                (uint8_t*)cr,
                (uint8_t*)sr,
                (uint32_t*)ms);

        if (ret != TSIP_SUCCESS) {
            WOLFSSL_MSG("R_TSIP_TlsGenerateMasterSecret failed");
        }
        /* unlock hw */
        tsip_hw_unlock();
    }
    else {
        WOLFSSL_MSG(" hw lock failed ");
    }
    WOLFSSL_LEAVE("tsip_generateMasterSecret", ret);
    return ret;
}
#endif /* WOLFSSL_RENESAS_TSIP_VER */

/*  store elements for session key generation into ssl->keys.
 *  return 0 on success, negative value on failure
 */
int wc_tsip_storeKeyCtx(WOLFSSL* ssl, TsipUserCtx* userCtx)
{
    int ret = 0;

    WOLFSSL_ENTER("tsip_storeKeyCtx");

    if (ssl == NULL || userCtx == NULL)
        ret = BAD_FUNC_ARG;

    if (ret == 0) {
        XMEMCPY(userCtx->internal->tsip_masterSecret,
                ssl->arrays->tsip_masterSecret, TSIP_TLS_MASTERSECRET_SIZE);
        XMEMCPY(userCtx->internal->tsip_clientRandom,
                ssl->arrays->clientRandom, TSIP_TLS_CLIENTRANDOM_SZ);
        XMEMCPY(userCtx->internal->tsip_serverRandom,
                ssl->arrays->serverRandom, TSIP_TLS_SERVERRANDOM_SZ);
        userCtx->internal->tsip_cipher = GetTsipCipherSuite(
                                ssl->options.cipherSuite0,
                                ssl->options.cipherSuite);
    }

    WOLFSSL_LEAVE("tsip_storeKeyCtx", ret);
    return ret;
}

/* generate pre-Master secrete by TSIP */
int wc_tsip_generatePremasterSecret(byte *premaster, word32 preSz)
{
    WOLFSSL_ENTER("tsip_generatePremasterSecret");
    int ret;

    if (premaster == NULL)
      return BAD_FUNC_ARG;

    if ((ret = tsip_hw_lock()) == 0 && preSz >=
                                    (R_TSIP_TLS_MASTER_SECRET_WORD_SIZE*4)) {
        /* generate pre-master, 80 bytes */
        ret = R_TSIP_TlsGeneratePreMasterSecret((uint32_t*)premaster);
        if (ret != TSIP_SUCCESS) {
            WOLFSSL_MSG(" R_TSIP_TlsGeneratePreMasterSecret failed");
        }

        /* unlock hw */
        tsip_hw_unlock();
    }
    else {
        WOLFSSL_MSG(" hw lock failed or preSz is smaller than 80");
    }
    WOLFSSL_LEAVE("tsip_generatePremasterSecret", ret);
    return ret;
}

/*
* generate encrypted pre-Master secrete by TSIP
*/
int wc_tsip_generateEncryptPreMasterSecret(
        WOLFSSL*    ssl,
        byte*       out,
        word32*     outSz)
{
    int ret;

    WOLFSSL_ENTER("tsip_generateEncryptPreMasterSecret");

    if ((ssl == NULL) || (out == NULL) || (outSz == NULL))
      return BAD_FUNC_ARG;

    if ((ret = tsip_hw_lock()) == 0) {
        if (*outSz >= 256)

            #if  (WOLFSSL_RENESAS_TSIP_VER>=109)

            ret = R_TSIP_TlsEncryptPreMasterSecretWithRsa2048PublicKey(
                        (uint32_t*)ssl->peerSceTsipEncRsaKeyIndex,
                        (uint32_t*)ssl->arrays->preMasterSecret,
                        (uint8_t*)out);

            #else

            ret = R_TSIP_TlsEncryptPreMasterSecret(
                          (uint32_t*)ssl->peerSceTsipEncRsaKeyIndex,
                          (uint32_t*)ssl->arrays->preMasterSecret,
                          (uint8_t*)out);

            #endif
        else
            ret = -1;

        if (ret != TSIP_SUCCESS) {
            WOLFSSL_MSG(" R_TSIP_TlsEncryptPreMasterSecret failed");
        }
        else {
            *outSz = 256; /* TSIP can only handles 2048 RSA */
            void* ctx = wolfSSL_GetRsaVerifyCtx(ssl);
            wolfSSL_CTX_SetGenMasterSecretCb(ssl->ctx,
                                                Renesas_cmn_genMasterSecret);
            wolfSSL_SetGenMasterSecretCtx(ssl, ctx);
        }

        tsip_hw_unlock();

    }
    else {
        WOLFSSL_MSG(" hw lock failed ");
    }
    WOLFSSL_LEAVE("tsip_generateEncryptPreMasterSecret", ret);
    return ret;
}


/* Certificate verification by TSIP */
int wc_tsip_tls_CertVerify(
        const uint8_t* cert,       uint32_t certSz,
        const uint8_t* signature,  uint32_t sigSz,
        uint32_t      key_n_start, uint32_t key_n_len,
        uint32_t      key_e_start, uint32_t key_e_len,
        uint8_t*      tsip_encRsaKeyIndex)
{
    int ret;
    uint8_t *sigforSCE = NULL;
    uint8_t *pSig = NULL;
    const byte rs_size = 0x20;
    byte offset = 0x3;

    WOLFSSL_ENTER("wc_tsip_tls_CertVerify");

    if (cert == NULL)
      return BAD_FUNC_ARG;

    if (!signature) {
        WOLFSSL_MSG(" signature for ca verification is not set");
        return -1;
    }
    if (!tsip_encRsaKeyIndex) {
        WOLFSSL_MSG(" tsip_encRsaKeyIndex is NULL.");
        return -1;
    }

    /* Public key type: Prime256r1 */
    if (g_user_key_info.encrypted_user_tls_key_type ==
                                    R_TSIP_TLS_PUBLIC_KEY_TYPE_ECDSA_P256) {

        if ((sigforSCE = (uint8_t*)XMALLOC(R_TSIP_ECDSA_DATA_BYTE_SIZE,
                                        NULL, DYNAMIC_TYPE_ECC)) == NULL) {
            WOLFSSL_MSG("failed to malloc memory");
            return MEMORY_E;
        }
        /* initialization */
        ForceZero(sigforSCE, R_TSIP_ECDSA_DATA_BYTE_SIZE);

        if (signature[offset] == 0x20) {
            XMEMCPY(sigforSCE, &signature[offset+1], rs_size);

            offset = 0x25;
            if (signature[offset] == 0x20) {
                XMEMCPY(&sigforSCE[rs_size], &signature[offset+1], rs_size);
            }
            else {
                XMEMCPY(&sigforSCE[rs_size], &signature[offset+2], rs_size);
            }
        }
        else {
            XMEMCPY(sigforSCE, &signature[offset+2], rs_size);
            offset = 0x26;

            if (signature[offset] == rs_size) {
                XMEMCPY(&sigforSCE[rs_size], &signature[offset+1], rs_size);
            }
            else {
                XMEMCPY(&sigforSCE[rs_size], &signature[offset+2], rs_size);
            }
        }
        pSig = sigforSCE;
    }
    /* Public key type: RSA 2048bit */
    else {
        pSig = (uint8_t*)signature;
    }

    if ((ret = tsip_hw_lock()) == 0) {

        #if (WOLFSSL_RENESAS_TSIP_VER>=109)

        ret = R_TSIP_TlsCertificateVerification(
            g_user_key_info.encrypted_user_tls_key_type,
            (uint32_t*)g_encrypted_publicCA_key,/* encrypted public key  */
            (uint8_t*)cert,                    /* certificate der        */
            certSz,                            /* length of der          */
            (uint8_t*)pSig,                    /* sign data by RSA PSS   */
            key_n_start,  /* start position of public key n in bytes     */
            (key_n_start + key_n_len),     /* length of the public key n */
            key_e_start,                   /* start pos, key e in bytes  */
            (key_e_start + key_e_len),     /* length of the public key e */
            (uint32_t*)tsip_encRsaKeyIndex /* returned encrypted key     */
        );

        #elif (WOLFSSL_RENESAS_TSIP_VER>=106)

        ret = R_TSIP_TlsCertificateVerification(
            (uint32_t*)g_encrypted_publicCA_key,/* encrypted public key  */
            (uint8_t*)cert,                    /* certificate der        */
            certSz,                            /* length of der          */
            (uint8_t*)pSig,                    /* sign data by RSA PSS   */
            key_n_start,  /* start position of public key n in bytes     */
            (key_n_start + key_n_len),     /* length of the public key n */
            key_e_start,                   /* start pos, key e in bytes  */
            (key_e_start + key_e_len),     /* length of the public key e */
            (uint32_t*)tsip_encRsaKeyIndex /* returned encrypted key     */
        );
        #endif

        if (ret != TSIP_SUCCESS) {
            WOLFSSL_MSG(" R_TSIP_TlsCertificateVerification failed");
        }
        XFREE(sigforSCE, NULL, DYNAMIC_TYPE_ECC);
        tsip_hw_unlock();
    }
    else {
        WOLFSSL_MSG(" hw lock failed ");
    }
    WOLFSSL_LEAVE("wc_tsip_tls_CertVerify", ret);
    return ret;
}
/* Root Certificate verification */
int wc_tsip_tls_RootCertVerify(
        const byte* cert,           word32 cert_len,
        word32      key_n_start,    word32 key_n_len,
        word32      key_e_start,    word32 key_e_len,
        word32      cm_row)
{
    int ret;
    /* call to generate encrypted public key for certificate verification */
    uint8_t *signature = (uint8_t*)ca_cert_sig;

    WOLFSSL_ENTER("wc_tsip_tls_RootCertVerify");

    if (cert == NULL)
      return BAD_FUNC_ARG;

    if (!signature) {
        WOLFSSL_MSG(" signature for ca verification is not set");
        return -1;
    }

    if ((ret = tsip_hw_lock()) == 0) {

    #if (WOLFSSL_RENESAS_TSIP_VER>=109)
        ret = R_TSIP_TlsRootCertificateVerification(
            g_user_key_info.encrypted_user_tls_key_type,
            (uint8_t*)cert,             /* CA cert */
            (uint32_t)cert_len,         /* length of CA cert */
            key_n_start,                /* Byte position of public key */
            (key_n_start + key_n_len),
            key_e_start,
            (key_e_start + key_e_len),
            (uint8_t*)ca_cert_sig,      /* RSA 2048 PSS with SHA256 */
            g_encrypted_publicCA_key    /* RSA-2048 public key 560 bytes */
        );
    #else /* WOLFSSL_RENESAS_TSIP_VER < 109 */
        ret = R_TSIP_TlsRootCertificateVerification(
            (uint8_t*)cert,/* CA cert */
            (uint32_t)cert_len,/* length of CA cert */
            key_n_start, /* Byte position of public key */
            (key_n_start + key_n_len),
            key_e_start,
            (key_e_start + key_e_len),
            (uint8_t*)ca_cert_sig,/* "RSA 2048 PSS with SHA256" */
            /* RSA-2048 public key used by RSA-2048 PSS with SHA256. 560 Bytes */
            g_encrypted_publicCA_key
        );
    #endif

        if (ret != TSIP_SUCCESS) {
            WOLFSSL_MSG(" R_TSIP_TlsRootCertificateVerification failed");
        }
        else {
            g_CAscm_Idx = cm_row;
        }

        tsip_hw_unlock();
    }
    else {
        WOLFSSL_MSG(" hw lock failed ");
    }
    WOLFSSL_LEAVE("wc_tsip_tls_RootCertVerify", ret);
    return ret;
}
#endif /* WOLFSSL_RENESAS_TSIP_TLS */

#if !defined(NO_RSA)
/*  Perform signing with the client's RSA private key on hash value of messages
 *  exchanged with server.
 *
 * parameters
 *   info->pk.rsa.in    : not used
 *   info->pk.rsa.inlen : not used
 *   info->pk.rsa.out   : the buffer where the signature data is output to
 *   info->pk.rsa.outlen: the length of the pk.rsa.out
 *   tuc:  the pointer to the TsipUserCtx structure
 * returns
 *   0 on success, CRYPTOCB_UNAVAILABLE on unsupported key type specified.
 *
 */
int tsip_SignRsaPkcs(wc_CryptoInfo* info, TsipUserCtx* tuc)
{
    int ret = 0;
    e_tsip_err_t    err = TSIP_SUCCESS;
    tsip_rsa_byte_data_t hashData, sigData;
    WOLFSSL* ssl = NULL;
    uint8_t  tsip_hash_type;

    WOLFSSL_ENTER("tsip_SignRsaPkcs");

    if (info == NULL || tuc == NULL
    #ifndef WOLFSSL_RENESAS_TSIP_CRYPTONLY
    || tuc->internal->ssl == NULL
    #endif
    ) {
            ret = BAD_FUNC_ARG;
    }

#ifdef WOLFSSL_RENESAS_TSIP_TLS
    if (ret == 0) {
        ssl = tuc->internal->ssl;

        if (ssl->version.major == SSLv3_MAJOR &&
            ssl->version.minor == TLSv1_3_MINOR) {
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        /* import private key_index from wrapped key */
        ret = tsip_ImportPrivateKey(tuc, tuc->wrappedKeyType);
    }

    if (ret == 0) {
        if (ssl->options.hashAlgo == md5_mac)
            tsip_hash_type = R_TSIP_RSA_HASH_MD5;
        else if (ssl->options.hashAlgo == sha_mac)
            tsip_hash_type = R_TSIP_RSA_HASH_SHA1;
        else if (ssl->options.hashAlgo == sha256_mac)
            tsip_hash_type = R_TSIP_RSA_HASH_SHA256;
        else
            ret = CRYPTOCB_UNAVAILABLE;
    }
#else
    (void)ssl;

    if (ret == 0) {
       if (tuc->sign_hash_type == md5_mac)
           tsip_hash_type = R_TSIP_RSA_HASH_MD5;
       else if (tuc->sign_hash_type == sha_mac)
           tsip_hash_type = R_TSIP_RSA_HASH_SHA1;
       else if (tuc->sign_hash_type == sha256_mac)
           tsip_hash_type = R_TSIP_RSA_HASH_SHA256;
       else
           ret = CRYPTOCB_UNAVAILABLE;
    }

    switch (tuc->wrappedKeyType) {
#if defined(TSIP_RSASSA_1024) && TSIP_RSASSA_1024 == 1
        case TSIP_KEY_TYPE_RSA1024:
            if (tuc->keyflgs_crypt.bits.rsapri1024_key_set != 1) {
                WOLFSSL_MSG("tsip rsa private key 1024 not set");
                    ret = CRYPTOCB_UNAVAILABLE;
            }
            break;
#endif
#if defined(TSIP_RSASSA_2048) && TSIP_RSASSA_2048 == 1
        case TSIP_KEY_TYPE_RSA2048:
            if (tuc->keyflgs_crypt.bits.rsapri2048_key_set != 1) {
                WOLFSSL_MSG("tsip rsa private key 2048 not set");
                    ret = CRYPTOCB_UNAVAILABLE;
            }
            break;
#endif
        default:
            WOLFSSL_MSG("wrapped private key is not supported");
            ret = CRYPTOCB_UNAVAILABLE;
            break;
    }
#endif

    if (ret == 0) {
    #ifdef WOLFSSL_RENESAS_TSIP_TLS
        /* since TSIP driver adds ASN.1 input data uses raw digest */
        hashData.pdata      = (uint8_t*)ssl->buffers.digest.buffer;
        hashData.data_length= ssl->buffers.digest.length;
        hashData.data_type  = 1; /* hashed data */
        sigData.pdata       = (uint8_t*)info->pk.rsa.out;
        sigData.data_length = 0; /* signature size will be returned here */
    #else
        hashData.pdata      = (uint8_t*)info->pk.rsa.in;
        hashData.data_length= info->pk.rsa.inLen;
        hashData.data_type  = tuc->keyflgs_crypt.bits.message_type;
        sigData.pdata       = (uint8_t*)info->pk.rsa.out;
        sigData.data_length = 0;
    #endif
        if ((ret = tsip_hw_lock()) == 0) {
            switch (tuc->wrappedKeyType) {
#if (defined(TSIP_RSASSA_1024) && TSIP_RSASSA_1024 == 1) && \
                defined(WOLFSSL_RENESAS_TSIP_CRYPTONLY)
                case TSIP_KEY_TYPE_RSA1024:
                    err = R_TSIP_RsassaPkcs1024SignatureGenerate(
                                                &hashData, &sigData,
                                       (tsip_rsa1024_private_key_index_t*)
                                                tuc->rsa1024pri_keyIdx,
                                                tsip_hash_type);

                    if (err != TSIP_SUCCESS) {
                        ret = WC_HW_E;
                    }
                    break;
#endif
#if defined(TSIP_RSASSA_2048) && TSIP_RSASSA_2048 == 1
                case TSIP_KEY_TYPE_RSA2048:
                    err = R_TSIP_RsassaPkcs2048SignatureGenerate(
                                                &hashData, &sigData,
                                   #ifdef WOLFSSL_RENESAS_TSIP_TLS
                                    &(tuc->internal->Rsa2048PrivateKeyIdx),
                                   #else
                                    (tsip_rsa2048_private_key_index_t*)
                                                tuc->rsa2048pri_keyIdx,
                                   #endif
                                                tsip_hash_type);

                    if (err != TSIP_SUCCESS) {
                        ret = WC_HW_E;
                    }
                    *(info->pk.rsa.outLen) = sigData.data_length;
                    break;
#endif
                case TSIP_KEY_TYPE_RSA4096:
                    ret = CRYPTOCB_UNAVAILABLE;
                    break;

                default:
                    WOLFSSL_MSG("wrapped private key is not supported");
                    ret = CRYPTOCB_UNAVAILABLE;
                    break;
            }

            tsip_hw_unlock();
        }
        else {
            WOLFSSL_MSG("mutex locking error");
        }
    }

    WOLFSSL_LEAVE("tsip_SignRsaPkcs", ret);
    return ret;
}
#endif /* !NO_RSA */

#if !defined(NO_RSA) && defined(WOLFSSL_RENESAS_TSIP_TLS)
int tsip_VerifyRsaPkcsCb(
                        WOLFSSL* ssl,
                        unsigned char* sig, unsigned int sigSz,
                        unsigned char** out,
                        const unsigned char* keyDer, unsigned int keySz,
                        void* ctx)
{
    int ret = 0;
    e_tsip_err_t    err = TSIP_SUCCESS;
    tsip_rsa_byte_data_t hashData, sigData;
    TsipUserCtx* tuc = NULL;
    uint8_t  tsip_hash_type;
    (void)keyDer;
    (void)keySz;

    WOLFSSL_ENTER("tsip_VerifyRsaPkcsCb");

    if (sig == NULL || out == NULL || ctx == NULL) {
            ret = BAD_FUNC_ARG;
    }

    if (ssl->version.major == SSLv3_MAJOR &&
        ssl->version.minor == TLSv1_3_MINOR) {
        ret = CRYPTOCB_UNAVAILABLE;
    }

    if (ret == 0) {
        tuc = (TsipUserCtx*)ctx;
        if (tuc == NULL)
            ret = CRYPTOCB_UNAVAILABLE;
    }

    if (ret == 0) {
        /* import public key_index from wrapped key */
        ret = tsip_ImportPublicKey(tuc, tuc->wrappedKeyType);
    }

    if (ret == 0) {
        if (ssl->options.hashAlgo == md5_mac)
            tsip_hash_type = R_TSIP_RSA_HASH_MD5;
        else if (ssl->options.hashAlgo == sha_mac)
            tsip_hash_type = R_TSIP_RSA_HASH_SHA1;
        else if (ssl->options.hashAlgo == sha256_mac)
            tsip_hash_type = R_TSIP_RSA_HASH_SHA256;
        else {
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        sigData.pdata       = (uint8_t*)sig;
        sigData.data_length = sigSz;
        /* Since TSITP driver handles ASN.1 internally,
         * the expected data is raw hash.
         */
        hashData.pdata      = (uint8_t*)ssl->buffers.digest.buffer;
        hashData.data_type  = 1;  /* hash value */

        if ((ret = tsip_hw_lock()) == 0) {

            switch (tuc->wrappedKeyType) {
#if defined(TSIP_RSASSA_2048) && TSIP_RSASSA_2048 == 1
                case TSIP_KEY_TYPE_RSA2048:
                    err = R_TSIP_RsassaPkcs2048SignatureVerification(
                                        &sigData, &hashData,
                                        &(tuc->internal->Rsa2048PublicKeyIdx),
                                        tsip_hash_type);

                    if (err == TSIP_ERR_AUTHENTICATION) {
                        ret = VERIFY_CERT_ERROR;
                    }
                    else if (err == TSIP_SUCCESS) {
                        ret = 0;
                    }
                    else {
                        ret = WC_HW_E;
                    }
                    break;
#endif
                case TSIP_KEY_TYPE_RSA4096:
                    ret = CRYPTOCB_UNAVAILABLE;
                    break;

                default:
                    WOLFSSL_MSG("wrapped private key is not supported");
                    ret = CRYPTOCB_UNAVAILABLE;
                    break;
            }
            tsip_hw_unlock();
        }
        else {
            WOLFSSL_MSG("mutex locking error");
        }
    }
    WOLFSSL_LEAVE("tsip_VerifyRsaPkcsCb", ret);
    return ret;
}
#endif /* !NO_RSA && TSIP_TLS */

#if defined(HAVE_ECC)
#if defined(WOLFSSL_RENESAS_TSIP_TLS)
/*   Perform signing with the client's ECC private key on hash value of messages
 *   exchanged with server.
 *
 * parameters
 *   info->pk.eccsign.in    : the buffer holding hash value of messages
 *   info->pk.eccsign.inlen : hash data size
 *   info->pk.eccsign.out   : the buffer where the signature data is output to
 *   info->pk.eccsign.outlen: the length of the buffer pk.eccsign.out
 *   tuc:  the pointer to the TsipUserCtx structure
 * returns
 *   0 on success, CRYPTOCB_UNAVAILABLE on unsupported key type specified.
 * note
 *   signature will be DER encoded and stored into out buffer.
 *   the private key must be imported as TSIP specific format.
 */
int tsip_SignEcdsa(wc_CryptoInfo* info, TsipUserCtx* tuc)
{
    int ret = 0;
    e_tsip_err_t    err = TSIP_SUCCESS;
    tsip_ecdsa_byte_data_t hashData, sigData;
    byte  offsetForWork;
    byte* out = NULL;
    byte* sig = NULL;
    int   rSz = 0;
    int   sSz = 0;
    int   idx = 0;
    int   sz = 0;
    WOLFSSL* ssl = NULL;

    WOLFSSL_ENTER("tsip_SignEcdsa");

    if (info == NULL || tuc == NULL) {
        ret = CRYPTOCB_UNAVAILABLE;
    }

    if (ret == 0) {
        ssl = tuc->internal->ssl;

        if (ssl->version.major == SSLv3_MAJOR &&
            ssl->version.minor == TLSv1_3_MINOR) {
            ret = CRYPTOCB_UNAVAILABLE;
        }
    }

    if (ret == 0) {
        /* import private key_index from wrapped key */
        ret = tsip_ImportPrivateKey(tuc, tuc->wrappedKeyType);
    }

    if (ret == 0) {
        hashData.pdata      = (uint8_t*)info->pk.eccsign.in;
        hashData.data_type  = 1;
        sigData.pdata       = (uint8_t*)info->pk.eccsign.out;
        sigData.data_length = 0; /* signature size will be returned here */

        if ((ret = tsip_hw_lock()) == 0) {
            switch (tuc->wrappedKeyType) {

                #if !defined(NO_ECC256)
                case TSIP_KEY_TYPE_ECDSAP256:
                    offsetForWork = R_TSIP_ECDSA_DATA_BYTE_SIZE + 32;
                    if (*(info->pk.eccsign.outlen) <
                                R_TSIP_ECDSA_DATA_BYTE_SIZE + offsetForWork) {
                        ret = BUFFER_E;
                        break;
                    }

                    sigData.pdata = (uint8_t*)info->pk.eccsign.out +
                                                            offsetForWork;
                    err = R_TSIP_EcdsaP256SignatureGenerate(
                                        &hashData, &sigData,
                                        &(tuc->internal->EcdsaPrivateKeyIdx));
                    if (err != TSIP_SUCCESS) {
                        ret = WC_HW_E;
                        break;
                    }

                    out = info->pk.eccsign.out;
                    sig = sigData.pdata;

                    rSz =  sSz = R_TSIP_ECDSA_DATA_BYTE_SIZE / 2;
                    rSz += (sig[0] & 0x80)?1:0;
                    sSz += (sig[sSz] & 0x80)?1:0;
                    sz  =  (ASN_TAG_SZ + 1) * 2 + rSz + sSz;

                    /* encode ASN sequence */
                    out[idx++] = ASN_SEQUENCE | ASN_CONSTRUCTED;
                    out[idx++] = sz;

                    /* copy r part */
                    out[idx++] = ASN_INTEGER;
                    out[idx++] = rSz;
                    if (rSz > R_TSIP_ECDSA_DATA_BYTE_SIZE / 2)
                        out[idx++] = 0x00;
                    XMEMCPY(&out[idx], sig, R_TSIP_ECDSA_DATA_BYTE_SIZE / 2);
                    idx += R_TSIP_ECDSA_DATA_BYTE_SIZE / 2;
                    sig += R_TSIP_ECDSA_DATA_BYTE_SIZE / 2;
                    /* copy s part */
                    out[idx++] = ASN_INTEGER;
                    out[idx++] = sSz;
                    if (sSz > R_TSIP_ECDSA_DATA_BYTE_SIZE / 2)
                        out[idx++] = 0x00;
                    XMEMCPY(&out[idx], sig, R_TSIP_ECDSA_DATA_BYTE_SIZE / 2);

                    /* out size */
                    *(info->pk.eccsign.outlen) = ASN_TAG_SZ + 1 + sz;
                    break;
                #endif

                #if defined(HAVE_ECC384)
                case TSIP_KEY_TYPE_ECDSAP384:
                    ret = CRYPTOCB_UNAVAILABLE;
                    break;
                #endif

                default:
                    WOLFSSL_MSG("wrapped private key is not supported");
                    ret = CRYPTOCB_UNAVAILABLE;
                    break;
            }
            tsip_hw_unlock();
        }
        else {
            WOLFSSL_MSG("mutex locking error");
        }
    }
    WOLFSSL_LEAVE("tsip_SignEcdsa", ret);
    return ret;
}
#endif /* WOLFSSL_RENESAS_TSIP_TLS */

#if defined(WOLFSSL_RENESAS_TSIP_CRYPTONLY)
/* zero pad or truncate hash */
static int tsip_HashPad(int curveSz, uint8_t* hash,
    const uint8_t* hashIn, int hashSz)
{
    if (hashSz > curveSz)
        hashSz = curveSz;
    XMEMCPY(hash + (curveSz - hashSz), hashIn, hashSz);
    return curveSz;
}

/* Perform verify with the wrapped public key, provided hash and signature r+s
 *
 * parameters
 *   info->pk.eccverify.in    : the buffer holding hash value of messages
 *   info->pk.eccverify.inlen : hash data size
 *   info->pk.eccverify.out   : the buffer where the signature data is output to
 *   info->pk.eccverify.outlen: the length of the buffer pk.eccsign.out
 *   tuc:  the pointer to the TsipUserCtx structure
 * returns
 *   0 on success, CRYPTOCB_UNAVAILABLE on unsupported key type specified.
 */
int tsip_VerifyEcdsa(wc_CryptoInfo* info, TsipUserCtx* tuc)
{
    int ret = 0;
    e_tsip_err_t    err = TSIP_SUCCESS;
    tsip_ecdsa_byte_data_t hashData, sigData;
    /* hard coding largest digest size, since WC_MAX_DIGEST_SZ could be 32
     * if using SHA2-256 with ECDSA SECP384R1 */
    uint8_t hash[TSIP_MAX_ECC_BYTES];

    WOLFSSL_ENTER("tsip_VerifyEcdsa");

    if (info == NULL || tuc == NULL) {
        ret = CRYPTOCB_UNAVAILABLE;
    }

    XMEMSET(hash, 0, sizeof(hash));

    if (ret == 0) {
        /* import public key_index from wrapped key */
        ret = tsip_ImportPublicKey(tuc, tuc->wrappedKeyType);
    }

    if (ret == 0) {
        int curveSz = info->pk.eccverify.key->dp->size;
        hashData.pdata      = (uint8_t*)hash;
        hashData.data_type  = tuc->keyflgs_crypt.bits.message_type;
        sigData.pdata       = (uint8_t*)info->pk.eccverify.sig;
        sigData.data_length = info->pk.eccverify.siglen;

        if ((ret = tsip_hw_lock()) == 0) {
            switch (tuc->wrappedKeyType) {
            #if !defined(NO_ECC256)
                case TSIP_KEY_TYPE_ECDSAP256:
                    /* zero pad or truncate */
                    hashData.data_length = tsip_HashPad(curveSz,
                        hash, info->pk.eccverify.hash,
                        info->pk.eccverify.hashlen);

                    err = R_TSIP_EcdsaP256SignatureVerification(&sigData,
                        &hashData, &tuc->eccpub_keyIdx);
                    if (err == TSIP_SUCCESS) {
                        *info->pk.eccverify.res = 1; /* success */
                    }
                    else {
                        ret = WC_HW_E;
                    }
                    break;
                    break;
            #endif

            #if defined(HAVE_ECC384)
                case TSIP_KEY_TYPE_ECDSAP384:
                    /* zero pad or truncate */
                    hashData.data_length = tsip_HashPad(curveSz,
                        hash, info->pk.eccverify.hash,
                        info->pk.eccverify.hashlen);

                    err = R_TSIP_EcdsaP384SignatureVerification(&sigData,
                        &hashData, &tuc->eccpub_keyIdx);
                    if (err == TSIP_SUCCESS) {
                        *info->pk.eccverify.res = 1; /* success */
                    }
                    else {
                        ret = WC_HW_E;
                    }
                    break;
            #endif

                default:
                    WOLFSSL_MSG("ECDSA public key size not available");
                    ret = CRYPTOCB_UNAVAILABLE;
                    break;
            }
            tsip_hw_unlock();
        }
        else {
            WOLFSSL_MSG("mutex locking error");
        }
    }
    WOLFSSL_LEAVE("tsip_VerifyEcdsa", ret);
    return ret;
}
#endif /* WOLFSSL_RENESAS_TSIP_CRYPTONLY */
#endif /* HAVE_ECC */


#ifdef WOLFSSL_RENESAS_TSIP_CRYPT_DEBUG

#if 0
   /* this is here for documentation purposes. */
   enum e_tsip_err {
    TSIP_SUCCESS = 0,
    TSIP_ERR_SELF_CHECK1,       /* Self-check 1 fail or TSIP function internal err. */
    TSIP_ERR_RESOURCE_CONFLICT, /* A resource conflict occurred. */
    TSIP_ERR_SELF_CHECK2,       /* Self-check 2 fail. */
    TSIP_ERR_KEY_SET,           /* setting the invalid key. */
    TSIP_ERR_AUTHENTICATION,    /* Authentication failed. */
    TSIP_ERR_CALLBACK_UNREGIST, /* Callback function is not registered. */
    TSIP_ERR_PARAMETER,         /* Illegal Input data. */
    TSIP_ERR_PROHIBIT_FUNCTION, /* An invalid function call occurred. */
    TSIP_RESUME_FIRMWARE_GENERATE_MAC
                  /* There is a continuation of R_TSIP_GenerateFirmwareMAC. */
   };
#endif

static void hexdump(const uint8_t* in, uint32_t len)
{
    uint32_t i;

    if (in == NULL)
        return;

    for (i = 0; i <= len;i++, in++) {
        printf("%02x:", *in);
        if (((i+1)%16)==0) {
            printf("\n");
        }
    }
    printf("\n");
}

byte *ret2err(word32 ret)
{
    switch(ret) {
        case TSIP_SUCCESS: return "success";
        case TSIP_ERR_SELF_CHECK1: return "selfcheck1";
        case TSIP_ERR_RESOURCE_CONFLICT: return "rsconflict";
        case TSIP_ERR_SELF_CHECK2: return "selfcheck2";
        case TSIP_ERR_KEY_SET: return "keyset";
        case TSIP_ERR_AUTHENTICATION: return "authentication";
        case TSIP_ERR_CALLBACK_UNREGIST: return "callback unreg";
        case TSIP_ERR_PARAMETER: return "badarg";
        case TSIP_ERR_PROHIBIT_FUNCTION: return "prohibitfunc";
        case TSIP_RESUME_FIRMWARE_GENERATE_MAC: return "conti-generate-mac";
        default:return "unknown";
    }
}

#endif /* WOLFSSL_RENESAS_TSIP_CRYPT_DEBUG */
#endif /* WOLFSSL_RENESAS_TSIP */