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
/* maxq10xx.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/types.h>

#if defined(WOLFSSL_MAXQ1065) ||  defined(WOLFSSL_MAXQ108X)

#include <wolfssl/wolfcrypt/port/maxim/maxq10xx.h>

#ifdef NO_INLINE
    #include <wolfssl/wolfcrypt/misc.h>
#else
    #define WOLFSSL_MISC_INCLUDED
    #include <wolfcrypt/src/misc.c>
#endif

#include <stdint.h>
#include <wolfssl/internal.h>
#include <wolfssl/wolfcrypt/cryptocb.h>
#include <wolfssl/wolfcrypt/error-crypt.h>
#include <wolfssl/wolfcrypt/logging.h>
#ifdef USS_API
#include <MXQ_API.h>
#else
#include <wolfssl/wolfcrypt/port/maxim/MXQ_API.h>
#endif

#ifndef WOLFSSL_HAVE_ECC_KEY_GET_PRIV
    /* FIPS build has replaced ecc.h. */
    #define wc_ecc_key_get_priv(key) (&((key)->k))
    #define WOLFSSL_HAVE_ECC_KEY_GET_PRIV
#endif

#ifdef MAXQ_DEBUG
void dbg_dumphex(const char *identifier, const uint8_t* pdata, uint32_t plen);
#else
#define dbg_dumphex(identifier, pdata, plen) WC_DO_NOTHING
#endif /* MAXQ_DEBUG */

#if defined(USE_WINDOWS_API)
# define maxq_CryptHwMutexTryLock() 0
#endif

#define AES_KEY_ID_START      (0x2000)
#define AES_KEY_ID_MAX_NUM    (32)
#define ECC_KEY_ID_START      (AES_KEY_ID_START + AES_KEY_ID_MAX_NUM)
#define ECC_KEY_ID_MAX_NUM    (32)

#define TEMP_KEY_ID_START     (0)
#if defined(WOLFSSL_MAXQ108X)
#define TEMP_KEY_ID_MAX_NUM   (16)
#else
#define TEMP_KEY_ID_MAX_NUM   (2)
#endif

#define PUBKEY_IMPORT_OBJID    0x1000

#if defined (TEST_SETUP)
#define ROOT_CA_CERT_OBJ_ID    0x1006
#define DEVICE_CERT_OBJ_ID     0x1005
#define DEVICE_KEY_PAIR_OBJ_ID 0x1007
#else
#define ROOT_CA_CERT_OBJ_ID    0x1003
#define DEVICE_CERT_OBJ_ID     0x1002
#define DEVICE_KEY_PAIR_OBJ_ID 0x1004
#endif

#define PSK_OBJ_ID             0x1236
#define K_CHUNKSIZE            2032
#define K_CIPHER_BLOCKSIZE     16
#define ECC256_KEYSIZE         32
#define MAX_HASH_CHUNKSIZE     2000
#define MAX_CERT_DATASIZE      2048
#define MAX_KEY_DATASIZE       256
#define MAX_SIGNKEY_DATASIZE   96
#define MAX_SIG_DATASIZE       64
#define ECC_KEYCOMPLEN         32
#define ESTABLISH_OUT_MAX      128
#define FIXED_INFO_LEN         32
#define FIXED_INFO_VALUE       0xaa
#ifdef WOLFSSL_MAXQ108X

#define PSK_KID (0x1235)
static unsigned char tls13active          =  0;
static unsigned char tls13early           =  0;

static int tls13_dh_obj_id                = -1;
static int tls13_ecc_obj_id               = -1;
static int tls13_hs_early_secret_obj_id   = -1;
static int tls13_binder_key_obj_id        = -1;
static int tls13_shared_secret_obj_id     = -1;
static int tls13_early_secret_obj_id      = -1;
static int tls13_derived_secret_obj_id    = -1;
static int tls13_handshake_secret_obj_id  = -1;
static int tls13_master_secret_obj_id     = -1;
static int tls13_client_secret_obj_id     = -1;
static int tls13_server_secret_obj_id     = -1;
static int tls13_client_hs_key_obj_id     = -1;
static int tls13_server_hs_key_obj_id     = -1;
static int tls13_client_app_key_obj_id    = -1;
static int tls13_server_app_key_obj_id    = -1;
static int tls13_server_finish_obj_id     = -1;
static int tls13_client_finish_obj_id     = -1;
static int *tls13_server_key_id           = NULL;
static int *tls13_client_key_id           = NULL;
static int tls13_res_master_obj_id        = -1;
static int tls13_server_cert_id           = -1;
static int tls13_server_key_algo          = -1;
static int tls13_server_key_len           = -1;

#endif /* WOLFSSL_MAXQ108X */

/* Please define MAXQ10XX_PRODUCTION_KEY in your build scripts once you have a
 * production key. */
#if defined(MAXQ10XX_PRODUCTION_KEY)
#include "maxq10xx_key.h"
#else
/* TEST KEY. This must be changed for production environments!! */
static const mxq_u1 KeyPairImport[] = {
    0xd0,0x97,0x31,0xc7,0x63,0xc0,0x9e,0xe3,0x9a,0xb4,0xd0,0xce,0xa7,0x89,0xab,
    0x52,0xc8,0x80,0x3a,0x91,0x77,0x29,0xc3,0xa0,0x79,0x2e,0xe6,0x61,0x8b,0x2d,
    0x53,0x70,0xcc,0xa4,0x62,0xd5,0x4a,0x47,0x74,0xea,0x22,0xfa,0xa9,0xd4,0x95,
    0x4e,0xca,0x32,0x70,0x88,0xd6,0xeb,0x58,0x24,0xa3,0xc5,0xbf,0x29,0xdc,0xfd,
    0xe5,0xde,0x8f,0x48,0x19,0xe8,0xc6,0x4f,0xf2,0x46,0x10,0xe2,0x58,0xb9,0xb6,
    0x72,0x5e,0x88,0xaf,0xc2,0xee,0x8b,0x6f,0xe5,0x36,0xe3,0x60,0x7c,0xf8,0x2c,
    0xea,0x3a,0x4f,0xe3,0x6d,0x73
};
#endif /* MAXQ10XX_PRODUCTION_KEY || !DEBUG_WOLFSSL */

#if defined(WOLFSSL_MAXQ108X) && defined(HAVE_HKDF)

/* These are from Section 7.1 of the TLS 1.3 specification (RFC 8446). */
static const char derivedLabel[]     = "derived";
static const char cHsTrafficLabel[]  = "c hs traffic";
static const char sHsTrafficLabel[]  = "s hs traffic";
static const char cAppTrafficLabel[] = "c ap traffic";
static const char sAppTrafficLabel[] = "s ap traffic";
static const char appTrafUpdLabel[]  = "traffic upd";
static const char keyLabel[]         = "key";
static const char ivLabel[]          = "iv";
static const char finishedLabel[]    = "finished";
static const char resMasterLabel[]   = "res master";
static const char extBinderLabel[]   = "ext binder";

static int local_is_psk = 0;
static int is_hs_key = 0;

#endif /* WOLFSSL_MAXQ108X && HAVE_HKDF */

static int aes_key_id_arr[AES_KEY_ID_MAX_NUM];
static int ecc_key_id_arr[ECC_KEY_ID_MAX_NUM];

static int init_pk_callbacks = 0;
static int device_key_len = 32;

#if defined(WOLFSSL_MAXQ108X)
static int temp_key_id_arr[TEMP_KEY_ID_MAX_NUM] = {0};
static int *mac_key_obj_id = NULL;
static int mac_comp_active = 0;
#endif /* WOLFSSL_MAXQ108X */

#ifdef WOLFSSL_MAXQ10XX_CRYPTO
/*
 * Helper Functions
 */
static int crypto_sha256(const uint8_t *buf, uint32_t len, uint8_t *hash,
    uint32_t hashSz, uint32_t blkSz)
{
    int ret;
    uint32_t i = 0, chunk;
    wc_Sha256 sha256;

    /* validate arguments */
    if ((buf == NULL && len > 0) || hash == NULL ||
        hashSz < WC_SHA256_DIGEST_SIZE || blkSz == 0) {
        return BAD_FUNC_ARG;
    }

    /* Init Sha256 structure */
    ret = wc_InitSha256(&sha256);
    if (ret != 0) {
        return ret;
    }

    sha256.maxq_ctx.soft_hash = 1;

    while (i < len) {
        chunk = blkSz;
        if ((chunk + i) > len) {
            chunk = len - i;
        }
        /* Perform chunked update */
        ret = wc_Sha256Update(&sha256, (buf + i), chunk);
        if (ret != 0) {
            break;
        }
        i += chunk;
    }

    if (ret == 0) {
        /* Get final digest result */
        ret = wc_Sha256Final(&sha256, hash);
    }
    return ret;
}

static int crypto_ecc_sign(const uint8_t *key, uint32_t keySz,
    const uint8_t *hash, uint32_t hashSz, uint8_t *sig, uint32_t* sigSz,
    uint32_t curveSz, int curveId, WC_RNG* rng)
{
    int ret;
    mp_int r, s;
    ecc_key ecc;

    /* validate arguments */
    if (key == NULL || hash == NULL || sig == NULL || sigSz == NULL ||
        curveSz == 0 || hashSz == 0 || keySz < curveSz ||
        *sigSz < (curveSz * 2)) {
        return BAD_FUNC_ARG;
    }

    /* Initialize signature result */
    XMEMSET(sig, 0, curveSz * 2);

    /* Setup the ECC key */
    ret = wc_ecc_init(&ecc);
    if (ret < 0) {
        return ret;
    }

    ecc.maxq_ctx.hw_ecc = -1;

    /* Setup the signature r/s variables */
    ret = mp_init(&r);
    if (ret != MP_OKAY) {
        wc_ecc_free(&ecc);
        return ret;
    }

    ret = mp_init(&s);
    if (ret != MP_OKAY) {
        mp_clear(&r);
        wc_ecc_free(&ecc);
        return ret;
    }

    /* Import private key "k" */
    ret = wc_ecc_import_private_key_ex(key, keySz, /* private key "d" */
                                       NULL, 0,    /* public (optional) */
                                       &ecc, curveId);

    if (ret == 0) {
        ret = wc_ecc_sign_hash_ex(hash, hashSz, /* computed hash digest */
                                  rng, &ecc,    /* random and key context */
                                  &r, &s);
    }

    if (ret == 0) {
        /* export r/s */
        mp_to_unsigned_bin_len(&r, sig, curveSz);
        mp_to_unsigned_bin_len(&s, sig + curveSz, curveSz);
    }

    mp_clear(&r);
    mp_clear(&s);
    wc_ecc_free(&ecc);
    return ret;
}

#ifdef MAXQ_DEBUG
void dbg_dumphex(const char *identifier, const uint8_t* pdata, uint32_t plen)
{
    uint32_t i;

    printf("%s\n", identifier);

    for (i = 0; i < plen; ++i) {
        if ((i > 0) && !(i % 16)) {
            printf("\n");
        }
        printf("%02X ", pdata[i]);
    }

    printf("\n");
}
#endif /* MAXQ_DEBUG */

/*
 * Personalized Utility Functions
 */
static void LoadDefaultImportKey(unsigned char* key, int* keylen,
                                 int* curve, int* type)
{
    *curve  = MXQ_KEYPARAM_EC_P256R1;
    *type   = MXQ_KEYTYPE_ECC;
    *keylen = 32;

    XMEMCPY(key, KeyPairImport, sizeof(KeyPairImport));
}

static int getSignAlgoFromCurve(int c)
{
    switch(c) {
        case MXQ_KEYPARAM_EC_P256R1:  return ALGO_ECDSA_SHA_256;
        case MXQ_KEYPARAM_EC_P384R1:  return ALGO_ECDSA_SHA_384;
        case MXQ_KEYPARAM_EC_P521R1:  return ALGO_ECDSA_SHA_512;
#ifdef HAVE_ECC_BRAINPOOL
        case MXQ_KEYPARAM_EC_BP256R1: return ALGO_ECDSA_SHA_256;
        case MXQ_KEYPARAM_EC_BP384R1: return ALGO_ECDSA_SHA_384;
        case MXQ_KEYPARAM_EC_BP512R1: return ALGO_ECDSA_SHA_512;
#endif
    }
    return BAD_FUNC_ARG;
}

#ifdef WOLFSSL_MAXQ108X

static int wc_MAXQ10XX_HmacSetKey(int type);
static int wc_MAXQ10XX_HmacUpdate(const byte* msg, word32 length);
static int wc_MAXQ10XX_HmacFinal(byte* hash);

static int getMaxqKeyParamFromCurve(int c)
{
    switch(c) {
    case ECC_SECP256R1:       return MXQ_KEYPARAM_EC_P256R1;
    case ECC_SECP384R1:       return MXQ_KEYPARAM_EC_P384R1;
    case ECC_SECP521R1:       return MXQ_KEYPARAM_EC_P521R1;
    case ECC_BRAINPOOLP256R1: return MXQ_KEYPARAM_EC_BP256R1;
    case ECC_BRAINPOOLP384R1: return MXQ_KEYPARAM_EC_BP384R1;
    case ECC_BRAINPOOLP512R1: return MXQ_KEYPARAM_EC_BP512R1;
    }
    return BAD_FUNC_ARG;
}

#endif /* WOLFSSL_MAXQ108X */

static int ECDSA_sign(mxq_u1* dest, int* signlen, mxq_u1* key,
                      mxq_u1* data, mxq_length data_length, int curve)
{
    int ret;
    int hashlen = WC_SHA256_DIGEST_SIZE;
    unsigned char hash[WC_SHA256_DIGEST_SIZE];
    WC_RNG rng;
    int algo = 0;
    int wc_curve_id = ECC_SECP256R1;
    int wc_curve_size = 32;
    uint32_t sigSz = 0;

    if (curve != MXQ_KEYPARAM_EC_P256R1) {
        return BAD_FUNC_ARG;
    }

    algo = getSignAlgoFromCurve(curve);
    if (algo != ALGO_ECDSA_SHA_256) {
        return BAD_FUNC_ARG;
    }

    sigSz = (2 * wc_curve_size);
    if (*signlen < (int)sigSz) {
        return BAD_FUNC_ARG;
    }

    ret = wc_InitRng(&rng);
    if (ret != 0) {
        return ret;
    }

    ret = crypto_sha256(data, data_length, /* input message */
                        hash, hashlen,     /* hash digest result */
                        32                 /* configurable block/chunk size */
                       );

    if (ret == 0) {
        ret = crypto_ecc_sign(
            (key + (2 * wc_curve_size)), wc_curve_size,    /* private key */
            hash, hashlen,               /* computed hash digest */
            dest, &sigSz,                /* signature r/s */
            wc_curve_size,               /* curve size in bytes */
            wc_curve_id,                 /* curve id */
            &rng);

        *signlen = sigSz;
    }

    wc_FreeRng(&rng);
    return ret;
}

#ifdef MAXQ_AESGCM
static int alloc_aes_key_id(void)
{
    int i;
    for (i = 0; i < AES_KEY_ID_MAX_NUM; ++i) {
        if (aes_key_id_arr[i] == 0) {
            aes_key_id_arr[i] = AES_KEY_ID_START + i;
            break;
        }
    }

    if (i == AES_KEY_ID_MAX_NUM) {
        return 0;
    }
    else {
        return aes_key_id_arr[i];
    }
}
#endif /* MAXQ_AESGCM */

static void free_aes_key_id(int obj_id)
{
    int idx_for_arr = obj_id - AES_KEY_ID_START;

    if ((idx_for_arr >= 0) && (idx_for_arr < AES_KEY_ID_MAX_NUM)) {
        aes_key_id_arr[idx_for_arr] = 0;
    }
}

#ifdef MAXQ_ECC
static int alloc_ecc_key_id(void)
{
    int i;
    for (i = 0; i < ECC_KEY_ID_MAX_NUM; ++i) {
        if (ecc_key_id_arr[i] == 0) {
            ecc_key_id_arr[i] = ECC_KEY_ID_START + i;
            break;
        }
    }

    if (i == ECC_KEY_ID_MAX_NUM) {
        return 0;
    }
    else {
        return ecc_key_id_arr[i];
    }
}
#endif /* MAXQ_ECC */

static void free_ecc_key_id(int obj_id)
{
    int idx_for_arr = obj_id - ECC_KEY_ID_START;

    if ((idx_for_arr >= 0) && (idx_for_arr < ECC_KEY_ID_MAX_NUM)) {
        ecc_key_id_arr[idx_for_arr] = 0;
    }
}

#ifdef WOLFSSL_MAXQ108X
static int alloc_temp_key_id(void)
{
    int i;
    for (i = 0; i < TEMP_KEY_ID_MAX_NUM; ++i) {
        if (temp_key_id_arr[i] == 0) {
            temp_key_id_arr[i] = 1;
            break;
        }
    }

    if (i == TEMP_KEY_ID_MAX_NUM) {
        return -1;
    }
    else {
        return i;
    }
}

static void free_temp_key_id(int obj_id)
{
    int idx_for_arr = obj_id - TEMP_KEY_ID_START;

    if (idx_for_arr >=0 && idx_for_arr < TEMP_KEY_ID_MAX_NUM) {
        temp_key_id_arr[idx_for_arr] = 0;
    }
}
#endif /* WOLFSSL_MAXQ108X */

/*
 * WolfCrypt Functions
 */
int wc_MAXQ10XX_AesSetKey(Aes* aes, const byte* userKey, word32 keylen)
{
    XMEMCPY(aes->maxq_ctx.key, userKey, keylen);
    aes->maxq_ctx.key_pending = 1;
    return 0;
}

int wc_MAXQ10XX_EccSetKey(ecc_key* key, word32 keysize)
{
    int err = 0;
    int keytype = key->type;
    word32 bufflen = 0;

    if (key->maxq_ctx.hw_ecc == -1) {
        err = WC_HW_E;
    }

    if (err == 0) {
        if (key->dp->id != ECC_SECP256R1) {
            err = ECC_CURVE_OID_E;
        }
    }

    if (err == 0) {
        if ((keytype != ECC_PUBLICKEY) && (keytype != ECC_PRIVATEKEY) &&
            (keytype != ECC_PRIVATEKEY_ONLY)) {
            err = BAD_FUNC_ARG;
        }
    }

    if (err == 0) {
        bufflen = keysize;
        if ((keytype == ECC_PUBLICKEY) || (keytype == ECC_PRIVATEKEY)) {
            err = wc_export_int(key->pubkey.x, key->maxq_ctx.ecc_key,
                                &bufflen, keysize, WC_TYPE_UNSIGNED_BIN);
        }
    }

    if (err == 0) {
        if ((keytype == ECC_PUBLICKEY) || (keytype == ECC_PRIVATEKEY)) {
            err = wc_export_int(key->pubkey.y, key->maxq_ctx.ecc_key + keysize,
                                &bufflen, keysize, WC_TYPE_UNSIGNED_BIN);
        }
    }

    if (err == 0) {
        if ((keytype == ECC_PRIVATEKEY) || (keytype == ECC_PRIVATEKEY_ONLY)) {
            err = wc_export_int(wc_ecc_key_get_priv(key),
                key->maxq_ctx.ecc_key + (2 * keysize), &bufflen, keysize,
                WC_TYPE_UNSIGNED_BIN);
        }
    }

    if (err == 0) {
        key->maxq_ctx.hw_ecc = 1;
        key->maxq_ctx.key_pending = 1;
    }
    else {
        key->maxq_ctx.hw_ecc = -1;
    }

    return err;
}

#ifdef MAXQ_AESGCM
static int aes_set_key(Aes* aes, const byte* userKey, word32 keylen)
{
    mxq_u1 key_buff[MAX_KEY_DATASIZE];
    mxq_err_t mxq_rc;
    int rc;
    unsigned char sign_key[MAX_SIGNKEY_DATASIZE];
    int sign_key_len, sign_key_curve, sign_key_type;
    mxq_u1 signature[MAX_SIG_DATASIZE];
    int signature_len = (int)sizeof(signature);


    if (aes == NULL || (keylen != AES_128_KEY_SIZE &&
#ifdef WOLFSSL_AES_192
        keylen != AES_192_KEY_SIZE &&
#endif
        keylen != AES_256_KEY_SIZE)) {
        return BAD_FUNC_ARG;
    }

    #if defined(MAXQ10XX_MUTEX)
    rc = maxq_CryptHwMutexTryLock();
    if (rc != 0) {
        WOLFSSL_ERROR_MSG("MAXQ: aes_set_key() lock could not be acquired");
        rc = NOT_COMPILED_IN;
        return rc;
    }
    #endif

    if (aes->maxq_ctx.key_obj_id) {
        wc_MAXQ10XX_AesFree(aes);
    }

    int obj_id = alloc_aes_key_id();
    if (!obj_id) {
        WOLFSSL_ERROR_MSG("MAXQ: alloc_aes_key_id() failed");
        rc = NOT_COMPILED_IN;
        goto end_AesSetKey;
    }

    /* Delete object if one already exists. Ignore error in case it doesn't
     * exist. */
    (void)MXQ_DeleteObject(obj_id);
    mxq_rc = MXQ_CreateObject(obj_id, keylen, MXQ_OBJTYPE_SECRETKEY,
                              OBJPROP_PERSISTENT,
                              (char *)"ahs=rwdgx:ahs=rwdgx:ahs=rwdgx");
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_CreateObject() failed");
        rc = NOT_COMPILED_IN;
        goto end_AesSetKey;
    }

    /* store the object id in the context */
    aes->maxq_ctx.key_obj_id = obj_id;

    mxq_length key_buff_len = sizeof(key_buff);
    mxq_rc = MXQ_BuildKey(key_buff, &key_buff_len, MXQ_KEYTYPE_AES, 0xff,
                          keylen, keylen, MXQ_KEYUSE_ENCRYPTION,
                          ALGO_CIPHER_AES_ECB, MXQ_KEYUSE_NONE, ALGO_NONE,
                          (mxq_u1 *)userKey);
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_BuildKey() failed");
        rc = WC_HW_E;
        goto end_AesSetKey;
    }

    LoadDefaultImportKey(sign_key, &sign_key_len, &sign_key_curve,
                         &sign_key_type);

    /* Unlock because signing operation will need to use the RNG. */
    #if defined(MAXQ10XX_MUTEX)
    wolfSSL_CryptHwMutexUnLock();
    #endif

    rc = ECDSA_sign(signature, &signature_len, sign_key, key_buff, key_buff_len,
                    sign_key_curve);
    if (rc) {
        WOLFSSL_ERROR_MSG("MAXQ: ECDSA_sign() failed");
        goto end_AesSetKey_noUnlock;
    }

    #if defined(MAXQ10XX_MUTEX)
    rc = maxq_CryptHwMutexTryLock();
    if (rc != 0) {
        WOLFSSL_ERROR_MSG("MAXQ: aes_set_key() lock could not be acquired");
        rc = NOT_COMPILED_IN;
        goto end_AesSetKey_noUnlock;
    }
    #endif
    mxq_rc = MXQ_ImportKey(obj_id, getSignAlgoFromCurve(sign_key_curve),
                           PUBKEY_IMPORT_OBJID, key_buff, key_buff_len,
                           signature, signature_len);
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_ImportKey() failed");
        rc = WC_HW_E;
        goto end_AesSetKey;
    }

    /* key stored successfully */
    aes->maxq_ctx.key_pending = 0;

end_AesSetKey:
    wolfSSL_CryptHwMutexUnLock();
end_AesSetKey_noUnlock:
    return rc;
}
#endif /* MAXQ_AESGCM */

void wc_MAXQ10XX_AesFree(Aes* aes)
{
    mxq_err_t mxq_rc;
    int rc = 1;

    if (aes->maxq_ctx.key_obj_id != 0) {
        rc = 0;
    }

    if (rc == 0) {
        rc = wolfSSL_CryptHwMutexLock();
    }

    if (rc == 0) {
        mxq_rc = MXQ_DeleteObject(aes->maxq_ctx.key_obj_id);
        if (mxq_rc) {
            WOLFSSL_ERROR_MSG("MAXQ: MXQ_DeleteObject() failed");
            rc = 1;
        }

        if (rc == 0) {
            free_aes_key_id(aes->maxq_ctx.key_obj_id);
            aes->maxq_ctx.key_obj_id = 0;
        }
        wolfSSL_CryptHwMutexUnLock();
    }
}

#ifdef MAXQ_ECC
static int ecc_set_key(ecc_key* key, const byte* userKey, word32 keycomplen,
                       int for_ecdh)
{
    mxq_err_t mxq_rc;
    int rc;
    word32 keylen;
    int objtype;
    mxq_keyuse_t key_use;
    mxq_u1 key_buff[MAX_KEY_DATASIZE];
    mxq_length key_buff_len = sizeof(key_buff);
    unsigned char sign_key[MAX_SIGNKEY_DATASIZE];
    int sign_key_len, sign_key_curve, sign_key_type;
    mxq_u1 signature[MAX_SIG_DATASIZE];
    int signature_len = (int)sizeof(signature);


    if ((key->type != ECC_PUBLICKEY) && (key->type != ECC_PRIVATEKEY) &&
        (key->type != ECC_PRIVATEKEY_ONLY)) {
        return BAD_FUNC_ARG;
    }

    if (key->type == ECC_PUBLICKEY) {
        keylen = keycomplen * 2;
        objtype = MXQ_OBJTYPE_PUBKEY;
    }
    else {
        keylen = keycomplen * 3;
        objtype = MXQ_OBJTYPE_KEYPAIR;
    }

    if (for_ecdh) {
        key_use = MXQ_KEYUSE_KEY_EXCHAGE;
    }
    else {
        key_use = MXQ_KEYUSE_DATASIGNATURE;
    }

    #if defined(MAXQ10XX_MUTEX)
    rc = maxq_CryptHwMutexTryLock();
    if (rc != 0) {
        WOLFSSL_ERROR_MSG("MAXQ: ecc_set_key() lock could not be acquired");
        rc = NOT_COMPILED_IN;
        return rc;
    }
    #endif

    if (key->maxq_ctx.key_obj_id) {
        wc_MAXQ10XX_EccFree(key);
    }

    int obj_id = alloc_ecc_key_id();
    if (!obj_id) {
        WOLFSSL_ERROR_MSG("MAXQ: alloc_ecc_key_id() failed");
        rc = NOT_COMPILED_IN;
        goto end_EccSetKey;
    }

    /* Delete object if one already exists. Ignore error in case it doesn't
     * exist. */
    (void)MXQ_DeleteObject(obj_id);
    mxq_rc = MXQ_CreateObject(obj_id, keylen, objtype, OBJPROP_PERSISTENT,
                              (char *)"ahs=rwdgx:ahs=rwdgx:ahs=rwdgx");
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_CreateObject() failed");
        rc = NOT_COMPILED_IN;
        goto end_EccSetKey;
    }

    /* store the object id in the context */
    key->maxq_ctx.key_obj_id = obj_id;

    mxq_rc = MXQ_BuildKey(key_buff, &key_buff_len, MXQ_KEYTYPE_ECC,
                          MXQ_KEYPARAM_EC_P256R1, keycomplen, keylen,
                          key_use, ALGO_ECDSA_SHA_256,
                          MXQ_KEYUSE_NONE, ALGO_NONE, (mxq_u1 *)userKey);
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_BuildKey() failed");
        rc = WC_HW_E;
        goto end_EccSetKey;
    }

    LoadDefaultImportKey(sign_key, &sign_key_len, &sign_key_curve,
                         &sign_key_type);

    /* Unlock because signing operation will need to use the RNG. */
    #if defined(MAXQ10XX_MUTEX)
    wolfSSL_CryptHwMutexUnLock();
    #endif

    rc = ECDSA_sign(signature, &signature_len, sign_key, key_buff, key_buff_len,
                    sign_key_curve);
    if (rc) {
        WOLFSSL_ERROR_MSG("MAXQ: ECDSA_sign() failed");
        goto end_EccSetKey_noUnlock;
    }

    #if defined(MAXQ10XX_MUTEX)
    rc = maxq_CryptHwMutexTryLock();
    if (rc != 0) {
        WOLFSSL_ERROR_MSG("MAXQ: ecc_set_key() lock could not be acquired");
        rc = NOT_COMPILED_IN;
        goto end_EccSetKey_noUnlock;
    }
    #endif

    mxq_rc = MXQ_ImportKey(obj_id, getSignAlgoFromCurve(sign_key_curve),
                           PUBKEY_IMPORT_OBJID, key_buff, key_buff_len,
                           signature, signature_len);
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_ImportKey() failed");
        rc = WC_HW_E;
        goto end_EccSetKey;
    }

    /* key stored successfully */
    key->maxq_ctx.key_pending = 0;

end_EccSetKey:
    #if defined(MAXQ10XX_MUTEX)
    wolfSSL_CryptHwMutexUnLock();
    #endif
end_EccSetKey_noUnlock:
    return rc;
}

static int ecc_gen_key(ecc_key* key, word32 keycomplen)
{
    mxq_err_t mxq_rc;
    int rc;
    word32 keylen;
    int objtype;
    mxq_u1 key_buff[MAX_KEY_DATASIZE];
    mxq_length key_buff_len = sizeof(key_buff);
    unsigned char sign_key[MAX_SIGNKEY_DATASIZE];
    int sign_key_len, sign_key_curve, sign_key_type;
    mxq_u1 signature[MAX_SIG_DATASIZE];
    int signature_len = (int)sizeof(signature);


    if ((key->type != 0) && (key->type != ECC_PRIVATEKEY)
        && (key->type != ECC_PRIVATEKEY_ONLY)) {
        return BAD_FUNC_ARG;
    }

    key->type = ECC_PRIVATEKEY;
    keylen = keycomplen * 3;
    objtype = MXQ_OBJTYPE_KEYPAIR;

    #if defined(MAXQ10XX_MUTEX)
    rc = maxq_CryptHwMutexTryLock();
    if (rc != 0) {
        WOLFSSL_ERROR_MSG("MAXQ: ecc_set_key() lock could not be acquired");
        rc = NOT_COMPILED_IN;
        return rc;
    }
    #endif

    if (key->maxq_ctx.key_obj_id) {
        wc_MAXQ10XX_EccFree(key);
    }

    int obj_id = alloc_ecc_key_id();
    if (!obj_id) {
        WOLFSSL_ERROR_MSG("MAXQ: alloc_ecc_key_id() failed");
        rc = NOT_COMPILED_IN;
        goto end_EccGenKey;
    }

    /* Delete object if one already exists. Ignore error in case it doesn't
     * exist. */
    (void)MXQ_DeleteObject(obj_id);
    mxq_rc = MXQ_CreateObject(obj_id, keylen, objtype, OBJPROP_PERSISTENT,
                              (char *)"ahs=rwdgx:ahs=rwdgx:ahs=rwdgx");
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_CreateObject() failed");
        rc = NOT_COMPILED_IN;
        goto end_EccGenKey;
    }

    /* store the object id in the context */
    key->maxq_ctx.key_obj_id = obj_id;

    /* Note that total_keylen is 0 and psrc is NULL. This ensures that when
     * MXQ_ImportKey() is called, it does a keygen; not import. */
    mxq_rc = MXQ_BuildKey(key_buff, &key_buff_len, MXQ_KEYTYPE_ECC,
                          MXQ_KEYPARAM_EC_P256R1, keycomplen, 0,
                          MXQ_KEYUSE_KEY_EXCHAGE, ALGO_ECDSA_SHA_256,
                          MXQ_KEYUSE_NONE, ALGO_NONE, NULL);
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_BuildKey() failed");
        rc = WC_HW_E;
        goto end_EccGenKey;
    }

    LoadDefaultImportKey(sign_key, &sign_key_len, &sign_key_curve,
                         &sign_key_type);

    /* Unlock because signing operation will need to use the RNG. */
    #if defined(MAXQ10XX_MUTEX)
    wolfSSL_CryptHwMutexUnLock();
    #endif

    rc = ECDSA_sign(signature, &signature_len, sign_key, key_buff, key_buff_len,
                    sign_key_curve);
    if (rc) {
        WOLFSSL_ERROR_MSG("MAXQ: ECDSA_sign() failed");
        goto end_EccGenKey_noUnlock;
    }

    #if defined(MAXQ10XX_MUTEX)
    rc = maxq_CryptHwMutexTryLock();
    if (rc != 0) {
        WOLFSSL_ERROR_MSG("MAXQ: ecc_set_key() lock could not be acquired");
        rc = NOT_COMPILED_IN;
        goto end_EccGenKey_noUnlock;
    }
    #endif

    mxq_rc = MXQ_ImportKey(obj_id, getSignAlgoFromCurve(sign_key_curve),
                           PUBKEY_IMPORT_OBJID, key_buff, key_buff_len,
                           signature, signature_len);
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_ImportKey() failed");
        rc = WC_HW_E;
        goto end_EccGenKey;
    }

    key->maxq_ctx.hw_ecc = 1;

end_EccGenKey:
    #if defined(MAXQ10XX_MUTEX)
    wolfSSL_CryptHwMutexUnLock();
    #endif
end_EccGenKey_noUnlock:
    return rc;
}

static int ecc_establish(ecc_key* key, ecc_key* peer, byte *ss, word32 *ss_len)
{
    mxq_err_t mxq_rc;
    int rc = 0;
    byte fixed_info_len = FIXED_INFO_LEN;
    byte fixed_info[FIXED_INFO_LEN];
    mxq_length output_len = ESTABLISH_OUT_MAX;
    byte output[ESTABLISH_OUT_MAX];

    word32 peerKeySz;
    uint8_t  peerKeyBuf[MAX_EC_KEY_SIZE];
    uint8_t* peerKey = peerKeyBuf;
    uint8_t* qx;
    uint8_t* qy;
    word32 qxLen;
    word32 qyLen;

    /* ECC P256 shared secret is 32 bytes. */
    if (*ss_len != 32) {
        return BAD_FUNC_ARG;
    }

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

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

    peerKeySz = peer->dp->size;
    qx = peerKey;
    qy = &peerKey[peerKeySz];
    qxLen = peerKeySz;
    qyLen = peerKeySz;

    if (key->maxq_ctx.hw_ecc != 1) {
        /* The key was not generated. Lets import it. */
        if (key->maxq_ctx.hw_ecc == 0) {
            rc = wc_MAXQ10XX_EccSetKey(key, key->dp->size);
            if (rc != 0) {
                return rc;
            }
        }

        if (key->maxq_ctx.hw_ecc == -1) {
            return CRYPTOCB_UNAVAILABLE;
        }

        rc = ecc_set_key(key, key->maxq_ctx.ecc_key, key->dp->size, 1);
    }

    if (rc != 0) {
        return rc;
    }

    if (key->maxq_ctx.key_obj_id == 0) {
        return WC_HW_E;
    }

    rc = wc_ecc_export_public_raw(peer, qx, &qxLen, qy, &qyLen);
    if (rc != 0) {
        return rc;
    }

    /* This follows what is done in other MAXQ10xx examples. */
    XMEMSET(fixed_info, FIXED_INFO_VALUE, fixed_info_len);

    /* 0xFFFF indicates that the peer's public key will be in the buffer; not
     * referenced via key ID. */
    mxq_rc = MXQ_EstablishKey(SHARE_SECRET, MXQ_KEYPARAM_EC_P256R1,
                              key->maxq_ctx.key_obj_id, 0xFFFF, peerKey,
                              0, NULL, 0, 0, 0, 0, fixed_info_len, fixed_info,
                              0, 0, NULL, output, &output_len);

    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_EstablishKey() failed");
        rc = WC_HW_E;
    }

    /* Output contains the public key and shared secret concatenated. The public
     * key is (0x04 || X || Y) which means its 65 bytes. The shared secret is
     * in the 32 bytes after that. */
    XMEMCPY(ss, &output[1 + ECC256_KEYSIZE + ECC256_KEYSIZE], *ss_len);

    return rc;
}

#endif /* MAXQ_ECC */

void wc_MAXQ10XX_EccFree(ecc_key* key)
{
    if (key->maxq_ctx.key_obj_id == 0) {
        return;
    }

    int rc = wolfSSL_CryptHwMutexLock();
    if (rc != 0) {
        return;
    }

    mxq_err_t mxq_rc = MXQ_DeleteObject(key->maxq_ctx.key_obj_id);
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_DeleteObject() failed");
        wolfSSL_CryptHwMutexUnLock();
        return;
    }

    free_ecc_key_id(key->maxq_ctx.key_obj_id);
    key->maxq_ctx.key_obj_id = 0;
    wolfSSL_CryptHwMutexUnLock();
}

void wc_MAXQ10XX_Sha256Copy(wc_Sha256* sha256)
{
    /* during copying, change to soft hash mode for one context */
    if (sha256->maxq_ctx.hash_running) {
        sha256->maxq_ctx.hash_running = 0;
        sha256->maxq_ctx.soft_hash = 1;
    }
}

void wc_MAXQ10XX_Sha256Free(wc_Sha256* sha256)
{
    /* release the mutex if a hash operation is running on the maxq10xx device
     */
    if (sha256->maxq_ctx.hash_running) {
        sha256->maxq_ctx.hash_running = 0;
        sha256->maxq_ctx.soft_hash = 1;
        wolfSSL_CryptHwMutexUnLock();
    }
}
#endif /* WOLFSSL_MAXQ10XX_CRYPTO */

#ifdef WOLF_CRYPTO_CB
#ifdef MAXQ_SHA256
static int maxq10xx_hash_update_sha256(const mxq_u1* psrc, mxq_length inlen,
                                       int running)
{
    mxq_err_t mxq_rc;

    if (running == 0) {
        mxq_rc = MXQ_MD_Init(ALGO_MD_SHA256);
        if (mxq_rc) {
            WOLFSSL_ERROR_MSG("MAXQ: MXQ_MD_Init() failed");
            return WC_HW_E;
        }
    }

    mxq_length data_offset = 0;
    mxq_length data_len;

    while (inlen) {
        data_len = (inlen < MAX_HASH_CHUNKSIZE) ? inlen : MAX_HASH_CHUNKSIZE;

        mxq_rc = MXQ_MD_Update(&psrc[data_offset], data_len);
        if (mxq_rc) {
            WOLFSSL_ERROR_MSG("MAXQ: MXQ_MD_Update() failed");
            return WC_HW_E;
        }

        data_offset += data_len;
        inlen -= data_len;
    }

    return 0;
}

static int maxq10xx_hash_finish_sha256(mxq_u1* pdest)
{
    mxq_err_t mxq_rc;
    mxq_length hashlen = WC_SHA256_DIGEST_SIZE;

    mxq_rc = MXQ_MD_Finish(pdest, &hashlen);
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_MD_Finish() failed");
        return WC_HW_E;
    }

    return 0;
}
#endif /* MAXQ_SHA256 */

static int maxq10xx_cipher_do(mxq_algo_id_t algo_id, mxq_u1 encrypt,
                              mxq_u2 key_id, mxq_u1* p_in, mxq_u1* p_out,
                              mxq_length data_size, mxq_u1* p_iv,
                              mxq_length iv_len, mxq_u1* p_aad,
                              mxq_length aad_len, mxq_u1* p_tag,
                              mxq_length tag_len)
{
    mxq_err_t mxq_rc;
    ciph_params_t cparams;

    mxq_u1 internal_data[K_CHUNKSIZE + K_CIPHER_BLOCKSIZE];
    mxq_u1 *p_int_data = internal_data;

    mxq_length data_offset = 0;
    mxq_length proc_len = 0, req_len = 0;

    XMEMSET(&cparams, 0, sizeof(cparams));

    cparams.data_length  = data_size;
    cparams.p_iv         = p_iv;
    cparams.iv_length    = iv_len;
    cparams.p_aad        = p_aad;
    cparams.aad_length   = aad_len;

    if ((algo_id == ALGO_CIPHER_AES_GCM) || (algo_id == ALGO_CIPHER_AES_CCM)) {
        if (encrypt) {
            cparams.aead_tag_len = tag_len;
        }
        else {
            XMEMCPY(cparams.aead_tag, p_tag, tag_len);
            cparams.aead_tag_len = tag_len;
        }
    }

    mxq_rc = MXQ_Cipher_Init(encrypt, algo_id, key_id, &cparams, 0);
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_Cipher_Init() failed");
        return WC_HW_E;
    }

    while (data_size) {
        proc_len = (data_size < K_CHUNKSIZE) ? data_size : K_CHUNKSIZE;
        req_len  = proc_len;

        mxq_rc = MXQ_Cipher_Update(&p_out, &p_in[data_offset], &proc_len);
        if (mxq_rc) {
            WOLFSSL_ERROR_MSG("MAXQ: MXQ_Cipher_Update() failed");
            return WC_HW_E;
        }

        data_offset += req_len;
        data_size -= req_len;
    }

    if (encrypt) {
        proc_len = tag_len;
        mxq_rc = MXQ_Cipher_Finish(&p_int_data, &proc_len);
        if (mxq_rc) {
            WOLFSSL_ERROR_MSG("MAXQ: Encrypt, MXQ_Cipher_Finish() failed");
            return WC_HW_E;
        }

        if (proc_len > tag_len) {
            XMEMCPY(p_out, internal_data, proc_len - tag_len);
        }

        if ((tag_len != 0) && (proc_len >= tag_len)) {
            XMEMCPY(p_tag, &internal_data[proc_len - tag_len], tag_len);
        }
    }
    else {
        internal_data[0] = 0xDE;
        XMEMCPY(&internal_data[1], p_tag, tag_len);
        proc_len = tag_len;

        mxq_rc = MXQ_Cipher_Finish(&p_int_data, &proc_len);
        if (mxq_rc) {
            WOLFSSL_ERROR_MSG("MAXQ: Decrypt, MXQ_Cipher_Finish() failed");
            return WC_HW_E;
        }

        if (proc_len) {
            XMEMCPY(p_out, internal_data, proc_len);
        }
    }

    return 0;
}

static int maxq10xx_ecc_sign_local(mxq_u2 key_id,
                                   mxq_u1* p_in, mxq_u2 data_size,
                                   mxq_u1* p_sign_out, mxq_length* sign_len,
                                   mxq_length keycomplen)
{
    mxq_err_t mxq_rc;
    int rc;
    mxq_u1 *input_digest = NULL;
    mxq_u1 *buff_sign = NULL;
    mxq_length buff_len = keycomplen * 2;
    byte *r = NULL;
    byte *s = NULL;

    input_digest = (mxq_u1 *)XMALLOC(keycomplen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    buff_sign = (mxq_u1 *)XMALLOC(keycomplen * 2, NULL,
                                  DYNAMIC_TYPE_TMP_BUFFER);
    if (input_digest == NULL || buff_sign == NULL) {
        XFREE(input_digest, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        XFREE(buff_sign, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        return MEMORY_E;
    }
    r = &buff_sign[0];
    s = &buff_sign[keycomplen];

    /* truncate input to match key size */
    if (data_size > keycomplen) {
        data_size = keycomplen;
    }

    /* build input digest */
    XMEMSET(input_digest, 0, keycomplen);
    XMEMCPY(&input_digest[keycomplen - data_size], p_in, data_size);

    mxq_rc = MXQ_Sign(ALGO_ECDSA_PLAIN, key_id, input_digest,
                      keycomplen, buff_sign, &buff_len);
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_Sign() failed");
        return WC_HW_E;
    }

    /* convert r and s to signature */
    rc = wc_ecc_rs_raw_to_sig((const byte *)r, keycomplen, (const byte *)s,
                              keycomplen, p_sign_out, sign_len);
    if (rc != 0) {
        WOLFSSL_ERROR_MSG("MAXQ: converting r and s to signature failed");
    }

    XFREE(input_digest, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    XFREE(buff_sign, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    return rc;
}

#ifdef MAXQ_ECC
static int maxq10xx_ecc_verify_local(
               mxq_u2 key_id, mxq_u1* p_in, mxq_u2 data_size,
               mxq_u1* p_sign, mxq_u1 sign_len, int *result,
               mxq_length keycomplen)
{
    int rc;
    mxq_err_t mxq_rc;
    mxq_u1 *buff_rs = NULL;
    mxq_u1 *input_digest = NULL;
    mxq_u1 *buff_signature = NULL;
    byte *r = NULL;
    byte *s = NULL;
    word32 r_len = keycomplen;
    word32 s_len = keycomplen;

    input_digest = (mxq_u1 *)XMALLOC(keycomplen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    buff_rs = (mxq_u1 *)XMALLOC(keycomplen * 2, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    buff_signature = (mxq_u1 *)XMALLOC(keycomplen * 2, NULL,
                                       DYNAMIC_TYPE_TMP_BUFFER);

    if (input_digest == NULL || buff_rs == NULL || buff_signature == NULL) {
        XFREE(input_digest, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        XFREE(buff_rs, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        XFREE(buff_signature, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        return MEMORY_E;
    }
    r = &buff_rs[0];
    s = &buff_rs[keycomplen];

    /* truncate input to match key size */
    if (data_size > keycomplen) {
        data_size = keycomplen;
    }

    /* build input digest */
    XMEMSET(input_digest, 0, keycomplen);
    XMEMCPY(&input_digest[keycomplen - data_size], p_in, data_size);

    /* extract r and s from signature */
    XMEMSET(buff_rs, 0, keycomplen * 2);

    rc = wc_ecc_sig_to_rs(p_sign, sign_len, r, &r_len, s, &s_len);
    if (rc != 0) {
        XFREE(input_digest, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        XFREE(buff_rs, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        XFREE(buff_signature, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        WOLFSSL_ERROR_MSG("MAXQ: extracting r and s from signature failed");
        *result = 0;
        return rc;
    }

    if ((r_len > keycomplen) || (s_len > keycomplen)) {
        XFREE(input_digest, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        XFREE(buff_rs, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        XFREE(buff_signature, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        WOLFSSL_ERROR_MSG("MAXQ: r and s corrupted");
        *result = 0;
        return BUFFER_E;
    }

    /* prepare raw signature */
    XMEMSET(buff_signature, 0, keycomplen * 2);

    /* add leading zeros if necessary */
    XMEMCPY(&buff_signature[keycomplen - r_len], r, r_len);
    XMEMCPY(&buff_signature[(keycomplen * 2) - s_len], s, s_len);

    mxq_rc = MXQ_Verify(ALGO_ECDSA_PLAIN, key_id, input_digest,
                        keycomplen, buff_signature, keycomplen * 2);

    XFREE(input_digest, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    XFREE(buff_rs, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    XFREE(buff_signature, NULL, DYNAMIC_TYPE_TMP_BUFFER);

    *result = (mxq_rc ? 0 : 1);
    return 0;
}
#endif /* MAXQ_ECC */

#ifdef MAXQ_RNG
int maxq10xx_random(byte* output, unsigned short sz)
{
    if (output == NULL) {
        return BUFFER_E;
    }

    #if defined(MAXQ10XX_MUTEX)
    int ret = maxq_CryptHwMutexTryLock();
    if (ret != 0) {
        WOLFSSL_ERROR_MSG("MAXQ: maxq10xx_random() lock could not be acquired");
        ret = NOT_COMPILED_IN;
        return ret;
    }
    #endif

    if (MXQ_Get_Random_Ext(output, sz, 0)) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_Get_Random_Ext() failed");
        wolfSSL_CryptHwMutexUnLock();
        return WC_HW_E;
    }

    wolfSSL_CryptHwMutexUnLock();
    return 0;
}
#endif /* MAXQ_RNG */

#if !defined(NO_AES) && defined(HAVE_AESGCM) && defined(MAXQ_AESGCM)
static int do_aesgcm(wc_CryptoInfo* info)
{
    int rc;
    if (info->cipher.enc) {
        if (info->cipher.aesgcm_enc.authTagSz > 16) {
            return CRYPTOCB_UNAVAILABLE;
        }

        if (info->cipher.aesgcm_enc.sz == 0) {
            return CRYPTOCB_UNAVAILABLE;
        }

        if (info->cipher.aesgcm_enc.ivSz != 12) {
            return CRYPTOCB_UNAVAILABLE;
        }

        if (info->cipher.aesgcm_enc.aes->maxq_ctx.key_pending) {
            rc = aes_set_key(
                info->cipher.aesgcm_enc.aes,
                (const byte *)info->cipher.aesgcm_enc.aes->maxq_ctx.key,
                info->cipher.aesgcm_enc.aes->keylen);
            if (rc != 0) {
                return rc;
            }
        }

        rc = wolfSSL_CryptHwMutexLock();
        if (rc != 0) {
            return rc;
        }

        rc = maxq10xx_cipher_do(
            ALGO_CIPHER_AES_GCM,
            1,
            info->cipher.aesgcm_enc.aes->maxq_ctx.key_obj_id,
            (byte *)info->cipher.aesgcm_enc.in,
            (byte *)info->cipher.aesgcm_enc.out,
            info->cipher.aesgcm_enc.sz,
            (byte *)info->cipher.aesgcm_enc.iv,
            info->cipher.aesgcm_enc.ivSz,
            (byte *)info->cipher.aesgcm_enc.authIn,
            info->cipher.aesgcm_enc.authInSz,
            (byte *)info->cipher.aesgcm_enc.authTag,
            info->cipher.aesgcm_enc.authTagSz);
        if (rc != 0) {
            wolfSSL_CryptHwMutexUnLock();
            return rc;
        }

        wolfSSL_CryptHwMutexUnLock();
    }
    else {
        if (info->cipher.aesgcm_dec.authTagSz != 16) {
            return CRYPTOCB_UNAVAILABLE;
        }

        if (info->cipher.aesgcm_dec.sz == 0) {
            return CRYPTOCB_UNAVAILABLE;
        }

        if (info->cipher.aesgcm_dec.ivSz != 12) {
            return CRYPTOCB_UNAVAILABLE;
        }

        if (info->cipher.aesgcm_dec.aes->maxq_ctx.key_pending) {
            rc = aes_set_key(
                info->cipher.aesgcm_dec.aes,
                (const byte *)info->cipher.aesgcm_dec.aes->maxq_ctx.key,
                info->cipher.aesgcm_dec.aes->keylen);
            if (rc != 0) {
                return rc;
            }
        }

        rc = wolfSSL_CryptHwMutexLock();
        if (rc != 0) {
            return rc;
        }

        rc = maxq10xx_cipher_do(
            ALGO_CIPHER_AES_GCM,
            0,
            info->cipher.aesgcm_dec.aes->maxq_ctx.key_obj_id,
            (byte *)info->cipher.aesgcm_dec.in,
            (byte *)info->cipher.aesgcm_dec.out,
            info->cipher.aesgcm_dec.sz,
            (byte *)info->cipher.aesgcm_dec.iv,
            info->cipher.aesgcm_dec.ivSz,
            (byte *)info->cipher.aesgcm_dec.authIn,
            info->cipher.aesgcm_dec.authInSz,
            (byte *)info->cipher.aesgcm_dec.authTag,
            info->cipher.aesgcm_dec.authTagSz);
        if (rc != 0) {
            wolfSSL_CryptHwMutexUnLock();
            return rc;
        }

        wolfSSL_CryptHwMutexUnLock();
    }

    /* done */
    return 0;
}
#endif /* !NO_AES && HAVE_AESGCM && MAXQ_AESGCM */

static int do_aescbc(wc_CryptoInfo* info)
{
    int rc;
    byte *out = info->cipher.aescbc.out;
    const byte *in = info->cipher.aescbc.in;

    if (info->cipher.aescbc.sz == 0) {
        return CRYPTOCB_UNAVAILABLE;
     }

    if (info->cipher.aescbc.aes->reg == NULL) {
        return CRYPTOCB_UNAVAILABLE;
    }

    /* Cannot do in place decryption because we get the incoming IV and that
     * would already get over written. */
    if (in == out) {
        return CRYPTOCB_UNAVAILABLE;
    }

    if (info->cipher.aescbc.aes->maxq_ctx.key_pending) {
        rc = aes_set_key(
            info->cipher.aescbc.aes,
            (const byte *)info->cipher.aescbc.aes->maxq_ctx.key,
            info->cipher.aescbc.aes->keylen);
        if (rc != 0) {
            return rc;
        }
    }

    rc = wolfSSL_CryptHwMutexLock();
    if (rc != 0) {
        return rc;
    }

    rc = maxq10xx_cipher_do(
        ALGO_CIPHER_AES_CBC,
        info->cipher.enc,
        info->cipher.aescbc.aes->maxq_ctx.key_obj_id,
        (byte *)info->cipher.aescbc.in,
        (byte *)info->cipher.aescbc.out,
        info->cipher.aescbc.sz,
        (byte *)info->cipher.aescbc.aes->reg, WC_AES_BLOCK_SIZE,
        NULL, 0,
        NULL, 0);

    wolfSSL_CryptHwMutexUnLock();

    /* Take the last 16 bytes and throw them into reg. Then it will be ready in
     * case Update() is called. For both encryption and decryption, we get it
     * from the ciphertext. (Note in and out usage) */
    if (info->cipher.enc) {
        XMEMCPY(info->cipher.aescbc.aes->reg,
               &out[info->cipher.aescbc.sz - WC_AES_BLOCK_SIZE],
               WC_AES_BLOCK_SIZE);
    }
    else {
        XMEMCPY(info->cipher.aescbc.aes->reg,
               &in[info->cipher.aescbc.sz - WC_AES_BLOCK_SIZE],
               WC_AES_BLOCK_SIZE);
    }
    /* done */
    return rc;
}

#ifdef HAVE_AES_ECB
static int do_aesecb(wc_CryptoInfo* info)
{
    int rc;

    if (info->cipher.aesecb.sz == 0) {
        return CRYPTOCB_UNAVAILABLE;
     }

    if (info->cipher.aesecb.aes->reg == NULL) {
        return CRYPTOCB_UNAVAILABLE;
    }

    if (info->cipher.aesecb.aes->maxq_ctx.key_pending) {
        rc = aes_set_key(
            info->cipher.aesecb.aes,
            (const byte *)info->cipher.aesecb.aes->maxq_ctx.key,
            info->cipher.aesecb.aes->keylen);
        if (rc != 0) {
            return rc;
        }
    }

    rc = wolfSSL_CryptHwMutexLock();
    if (rc != 0) {
        return rc;
    }

    rc = maxq10xx_cipher_do(
        ALGO_CIPHER_AES_ECB,
        info->cipher.enc,
        info->cipher.aesecb.aes->maxq_ctx.key_obj_id,
        (byte *)info->cipher.aesecb.in,
        (byte *)info->cipher.aesecb.out,
        info->cipher.aesecb.sz,
        NULL, 0,
        NULL, 0,
        NULL, 0);

    wolfSSL_CryptHwMutexUnLock();

    /* done */
    return rc;
}
#endif /* HAVE_AES_ECB */

#ifdef HAVE_AESCCM
static int do_aesccm(wc_CryptoInfo* info)
{
    int rc;
    wc_CryptoCb_AesAuthEnc *aesccm = (info->cipher.enc) ?
        (wc_CryptoCb_AesAuthEnc*)&info->cipher.aesccm_enc :
        /* dec->enc cast is okay */
        (wc_CryptoCb_AesAuthEnc*)&info->cipher.aesccm_dec;

    if (aesccm->sz == 0) {
        return CRYPTOCB_UNAVAILABLE;
     }

    if (aesccm->aes->reg == NULL) {
        return CRYPTOCB_UNAVAILABLE;
    }

    /* Cannot do in place decryption because we get the incoming IV and that
     * would already get over written. */
    if (aesccm->in == aesccm->out) {
        return CRYPTOCB_UNAVAILABLE;
    }

    if (aesccm->aes->maxq_ctx.key_pending) {
        rc = aes_set_key(
            aesccm->aes,
            (const byte *)aesccm->aes->maxq_ctx.key,
            aesccm->aes->keylen);
        if (rc != 0) {
            return rc;
        }
    }

    rc = wolfSSL_CryptHwMutexLock();
    if (rc != 0) {
        return rc;
    }

    rc = maxq10xx_cipher_do(
        ALGO_CIPHER_AES_CCM,
        info->cipher.enc,
        aesccm->aes->maxq_ctx.key_obj_id,
        (byte *)aesccm->in,
        (byte *)aesccm->out,
        aesccm->sz,
        (byte *)aesccm->nonce, aesccm->nonceSz,
        (byte *)aesccm->authIn, aesccm->authInSz,
        (byte *)aesccm->authTag, aesccm->authTagSz);

    wolfSSL_CryptHwMutexUnLock();

    /* done */
    return rc;
}
#endif /* HAVE_AESCCM */

#if !defined(NO_SHA) && !defined(NO_SHA256) && defined(MAXQ_SHA256)
static int do_sha256(wc_CryptoInfo* info)
{
    int rc;
    if (info->hash.sha256->maxq_ctx.soft_hash) {
        return CRYPTOCB_UNAVAILABLE;
    }

    if ((info->hash.in == NULL) && (info->hash.digest == NULL)) {
        return WC_HW_E;
    }

    #if defined(MAXQ10XX_MUTEX)
    if (info->hash.sha256->maxq_ctx.hash_running == 0) {
        rc = maxq_CryptHwMutexTryLock();
        if (rc != 0) {
            info->hash.sha256->maxq_ctx.soft_hash = 1;
            return CRYPTOCB_UNAVAILABLE;
        }
    }
    #endif

    if (info->hash.in != NULL) {
        /* wc_Sha256Update */
        if ((info->hash.sha256->maxq_ctx.hash_running == 0) &&
                (info->hash.inSz == 0)) {
            info->hash.sha256->maxq_ctx.soft_hash = 1;
            wolfSSL_CryptHwMutexUnLock();
            return CRYPTOCB_UNAVAILABLE;
        }

        rc = maxq10xx_hash_update_sha256(info->hash.in, info->hash.inSz,
                    info->hash.sha256->maxq_ctx.hash_running);
        if (rc != 0) {
            info->hash.sha256->maxq_ctx.hash_running = 0;
            wolfSSL_CryptHwMutexUnLock();
            return rc;
        }

        info->hash.sha256->maxq_ctx.hash_running = 1;

        /* save soft hash context in case of wc_Sha256Copy */
        return CRYPTOCB_UNAVAILABLE;
    }
    else if (info->hash.digest != NULL) {
        /* wc_Sha256Final */
        if (info->hash.sha256->maxq_ctx.hash_running == 0) {
            info->hash.sha256->maxq_ctx.soft_hash = 1;
            wolfSSL_CryptHwMutexUnLock();
            return CRYPTOCB_UNAVAILABLE;
        }

        rc = maxq10xx_hash_finish_sha256(info->hash.digest);
        if (rc != 0) {
            info->hash.sha256->maxq_ctx.hash_running = 0;
            wolfSSL_CryptHwMutexUnLock();
            return rc;
        }

        info->hash.sha256->maxq_ctx.hash_running = 0;
        wolfSSL_CryptHwMutexUnLock();
        /* done */
        rc = 0;
    }
    return rc;
}
#endif /* !NO_SHA && !NO_SHA256 && MAXQ_SHA256 */

int wolfSSL_MAXQ10XX_CryptoDevCb(int devId, wc_CryptoInfo* info, void* ctx)
{
    int rc = CRYPTOCB_UNAVAILABLE;
    (void)devId;
    (void)ctx;

    /* In the case of MAXQ1065, this callback is always enabled. */
#if defined(WOLFSSL_MAXQ108X)
    if (!tls13active)
        return CRYPTOCB_UNAVAILABLE;
#endif

    if (info->algo_type == WC_ALGO_TYPE_CIPHER) {
#if !defined(NO_AES) || !defined(NO_DES3)
    #if defined(HAVE_AESGCM) && defined(MAXQ_AESGCM)
        if (info->cipher.type == WC_CIPHER_AES_GCM) {
            rc = do_aesgcm(info);
        }
    #endif /* HAVE_AESGCM && MAXQ_AESGCM */
    #ifdef HAVE_AES_CBC
        if (info->cipher.type == WC_CIPHER_AES_CBC) {
            rc = do_aescbc(info);
        }
    #endif /* HAVE_AES_CBC */
    #ifdef HAVE_AESCCM
        if (info->cipher.type == WC_CIPHER_AES_CCM) {
            rc = do_aesccm(info);
        }
    #endif /* HAVE_AESCCM */
    #ifdef HAVE_AES_ECB
        if (info->cipher.type == WC_CIPHER_AES_ECB) {
            rc = do_aesecb(info);
        }
    #endif /* HAVE_AES_ECB */
#endif /* !NO_AES || !NO_DES3 */
    }
#if !defined(NO_SHA) || !defined(NO_SHA256)
    else if (info->algo_type == WC_ALGO_TYPE_HASH) {
    #if !defined(NO_SHA) && defined(MAXQ_SHA1)
        if (info->hash.type == WC_HASH_TYPE_SHA) {
            /* TODO */
            return CRYPTOCB_UNAVAILABLE;
        }
        else
    #endif /* !NO_SHA && MAXQ_SHA1 */
    #if !defined(NO_SHA256) && defined(MAXQ_SHA256)
        if (info->hash.type == WC_HASH_TYPE_SHA256) {
            rc = do_sha256(info);
        }
    #endif /* !NO_SHA256 && MAXQ_SHA256 */
    }
#endif /* !NO_SHA || !NO_SHA256 */
#if !defined(WC_NO_RNG) && defined(MAXQ_RNG)
    else if (info->algo_type == WC_ALGO_TYPE_SEED) {
        rc = maxq10xx_random(info->seed.seed, info->seed.sz);
    }
    else if (info->algo_type == WC_ALGO_TYPE_RNG) {
        rc = maxq10xx_random(info->rng.out, info->rng.sz);
    }
#endif /* !WC_NO_RNG && MAXQ_RNG */
    else if (info->algo_type == WC_ALGO_TYPE_PK) {
    #if defined(HAVE_ECC) && defined(MAXQ_ECC)
        if (info->pk.type == WC_PK_TYPE_EC_KEYGEN) {
            if (info->pk.eckg.key->maxq_ctx.hw_ecc == -1) {
                return CRYPTOCB_UNAVAILABLE;
            }

            rc = ecc_gen_key(info->pk.eckg.key, info->pk.eckg.key->dp->size);
            if (rc != 0) {
                return rc;
            }
        }
        else if (info->pk.type == WC_PK_TYPE_ECDH) {
            rc = ecc_establish(info->pk.ecdh.private_key,
                               info->pk.ecdh.public_key,
                               info->pk.ecdh.out, info->pk.ecdh.outlen);
            if (rc != 0) {
                return rc;
            }
        }
        else if (info->pk.type == WC_PK_TYPE_ECDSA_SIGN) {
            if (info->pk.eccsign.key->maxq_ctx.hw_ecc == 0) {
                rc = wc_MAXQ10XX_EccSetKey(info->pk.eccsign.key,
                                           info->pk.eccsign.key->dp->size);
                if (rc != 0) {
                    return rc;
                }
            }

            if (info->pk.eccsign.key->maxq_ctx.hw_ecc == -1) {
                return CRYPTOCB_UNAVAILABLE;
            }

#if defined(WOLFSSL_MAXQ108X)
            /* This is not done for MAXQ1065 because we want to use the pre-
             * provisioned key in the case of PKCS11. */
            if (info->pk.eccsign.key->maxq_ctx.key_pending) {
                rc = ecc_set_key(info->pk.eccsign.key,
                                 info->pk.eccsign.key->maxq_ctx.ecc_key,
                                 info->pk.eccsign.key->dp->size, 0);
                if (rc != 0) {
                    return rc;
                }
            }
#endif

            rc = wolfSSL_CryptHwMutexLock();
            if (rc != 0) {
                return rc;
            }

            /* Note that we are using the DEVICE_KEY_PAIR_OBJ_ID; its the pre-
             * provisioned key in the case of MAXQ1065. */
            rc = maxq10xx_ecc_sign_local(
#if defined(WOLFSSL_MAXQ108X)
                     info->pk.eccsign.key->maxq_ctx.key_obj_id,
#else
                     DEVICE_KEY_PAIR_OBJ_ID,
#endif
                     (byte *)info->pk.eccsign.in, info->pk.eccsign.inlen,
                     info->pk.eccsign.out, info->pk.eccsign.outlen,
                     info->pk.eccsign.key->dp->size);

            if (rc != 0) {
                wolfSSL_CryptHwMutexUnLock();
                return rc;
            }

            wolfSSL_CryptHwMutexUnLock();
            /* done */
            rc = 0;
        }
        else if (info->pk.type == WC_PK_TYPE_ECDSA_VERIFY) {
            if (info->pk.eccverify.key->type == ECC_PRIVATEKEY_ONLY) {
                return CRYPTOCB_UNAVAILABLE;
            }

            if (info->pk.eccverify.key->maxq_ctx.hw_ecc == 0) {
                rc = wc_MAXQ10XX_EccSetKey(info->pk.eccverify.key,
                                           info->pk.eccverify.key->dp->size);
                if (rc != 0) {
                    return rc;
                }
            }

            if (info->pk.eccverify.key->maxq_ctx.hw_ecc == -1) {
                return CRYPTOCB_UNAVAILABLE;
            }

            if (info->pk.eccverify.key->maxq_ctx.key_pending) {
                rc = ecc_set_key(info->pk.eccverify.key,
                                 info->pk.eccverify.key->maxq_ctx.ecc_key,
                                 info->pk.eccverify.key->dp->size, 0);
                if (rc != 0) {
                    return rc;
                }
            }

            rc = wolfSSL_CryptHwMutexLock();
            if (rc != 0) {
                return rc;
            }

            rc =
                maxq10xx_ecc_verify_local(
                    info->pk.eccverify.key->maxq_ctx.key_obj_id,
                    (byte *)info->pk.eccverify.hash,
                    info->pk.eccverify.hashlen,
                    (byte *)info->pk.eccverify.sig,
                    info->pk.eccverify.siglen,
                    info->pk.eccverify.res,
                    info->pk.eccverify.key->dp->size);

            wolfSSL_CryptHwMutexUnLock();

            if (rc != 0) {
                return rc;
            }

            /* Success */
            rc = 0;
        }
    #endif /* HAVE_ECC && MAXQ_ECC */
    }
#ifdef WOLFSSL_MAXQ108X
    else if (info->algo_type == WC_ALGO_TYPE_HMAC) {
        if (info->hmac.in != NULL && info->hmac.digest == NULL) {
            rc = 0;
            if (mac_comp_active == 0) {
                rc = wc_MAXQ10XX_HmacSetKey(info->hmac.macType);
            }
            if (rc == 0) {
                rc = wc_MAXQ10XX_HmacUpdate(info->hmac.in, info->hmac.inSz);
            }
        }
        else if (info->hmac.in == NULL && info->hmac.digest != NULL) {
            rc = wc_MAXQ10XX_HmacFinal(info->hmac.digest);
        }
        else {
            rc = BAD_FUNC_ARG;
        }
    }
#endif /* WOLFSSL_MAXQ108X */

    if (rc != 0 && rc != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
        rc = WC_HW_E;
    }

    return rc;
}

static int wolfSSL_Soft_CryptoDevCb(int devId, wc_CryptoInfo* info, void* ctx)
{
    (void)devId;
    (void)info;
    (void)ctx;

    return CRYPTOCB_UNAVAILABLE;
}
#endif /* WOLF_CRYPTO_CB */

#ifdef WOLFSSL_MAXQ10XX_TLS
#ifdef WOLFSSL_MAXQ108X
static int calculate_modulus_offset(const unsigned char * cert_data, int offset)
{
    int i;
    int l_offset = offset;
    for (i = 0; i < 2; i++) {
        if ((cert_data[l_offset]) & 0x80) {
            if ((cert_data[l_offset] & 0x7f) == 1) {
                l_offset += 3;
            }
            if ((cert_data[l_offset] & 0x7f) == 2) {
                l_offset += 4;
            }
        }
        else {
            l_offset += 2;
        }
    }
    return l_offset;
}

static int maxq_curve_wolfssl_id2mxq_id(word32 curve_id, mxq_length *keycomplen)
{
    switch (curve_id) {
    case ECC_SECP256R1_OID:
        *keycomplen = 32;
        return MXQ_KEYPARAM_EC_P256R1;
    case ECC_SECP384R1_OID:
        *keycomplen = 48;
        return MXQ_KEYPARAM_EC_P384R1;
    case ECC_SECP521R1_OID:
        *keycomplen = 66;
        return MXQ_KEYPARAM_EC_P521R1;
    case ECC_BRAINPOOLP256R1_OID:
        *keycomplen = 32;
        return MXQ_KEYPARAM_EC_BP256R1;
    case ECC_BRAINPOOLP384R1_OID:
        *keycomplen = 48;
        return MXQ_KEYPARAM_EC_BP384R1;
    case ECC_BRAINPOOLP512R1_OID:
        *keycomplen = 64;
        return MXQ_KEYPARAM_EC_BP512R1;
    default:
        return MXQ_UNKNOWN_CURVE;
    }
}

static int mxq_get_sign_alg_from_sig_oid(word32 maxq_id) {

    switch (maxq_id) {
    case CTC_SHA256wECDSA:
        return ALGO_ECDSA_SHA_256;
    case CTC_SHA384wECDSA:
        return ALGO_ECDSA_SHA_384;
    case CTC_SHA512wECDSA:
        return ALGO_ECDSA_SHA_512;
    case CTC_SHA256wRSA:
        return ALGO_RSASSAPSSPKCS1_V1_5_SHA256;
    case CTC_SHA384wRSA:
        return ALGO_RSASSAPSSPKCS1_V1_5_SHA384;
    case CTC_SHA512wRSA:
        return ALGO_RSASSAPSSPKCS1_V1_5_SHA512;
    default:
        return ALGO_INVALID;
    }
}
#endif /* WOLFSSL_MAXQ108X */

/* TODO: Get rid of publicKeyIndex. Pass in the information it is parsing.
 *       Then Improve this to pass in the parts of decoded cert it needs.
 */
static int maxq10xx_process_server_certificate(WOLFSSL* ssl,
                                               DecodedCert* p_cert)
{
    mxq_keytype_id_t key_type = MXQ_KEYTYPE_ECC;
    mxq_keyparam_id_t keyparam = MXQ_KEYPARAM_EC_P256R1;
    mxq_length totalkeylen;
    mxq_algo_id_t sign_algo = ALGO_ECDSA_SHA_256;
    int pk_offset = p_cert->publicKeyIndex;
    mxq_length keycomplen = ECC_KEYCOMPLEN;
    int rc;
    mxq_err_t mxq_rc;
    mxq_u1 certdata[MAX_CERT_DATASIZE];
    mxq_length certdatalen = sizeof(certdata);
    (void)ssl;
#if defined(WOLFSSL_MAXQ1065)

    if (p_cert->signatureOID != CTC_SHA256wECDSA) {
        WOLFSSL_MSG("MAXQ: signature algo not supported");
        return NOT_COMPILED_IN;
    }

    if (p_cert->keyOID != ECDSAk) {
        WOLFSSL_MSG("MAXQ: key algo not supported");
        return NOT_COMPILED_IN;
    }

    if (p_cert->pkCurveOID != ECC_SECP256R1_OID) {
        WOLFSSL_MSG("MAXQ: key curve not supported");
        return NOT_COMPILED_IN;
    }

    totalkeylen = keycomplen * 2;

#elif defined(WOLFSSL_MAXQ108X)

    if (p_cert->keyOID == ECDSAk )
    {
        keyparam = maxq_curve_wolfssl_id2mxq_id(p_cert->pkCurveOID,
                                                &keycomplen);
        if (keyparam == MXQ_UNKNOWN_CURVE) {
            WOLFSSL_MSG("MAXQ: key curve not supported");
            return NOT_COMPILED_IN;
        }
        totalkeylen = keycomplen * 2;
    }
    else if (p_cert->keyOID == RSAk) {
        pk_offset = calculate_modulus_offset(p_cert->source,
                                             p_cert->publicKeyIndex+1);
        keycomplen = ((p_cert->source[pk_offset-2] << 8) |
                      p_cert->source[pk_offset-1]);

        /* Is there a more elegant way for checking pub key??? */
        if (p_cert->publicKey[p_cert->pubKeySize-1] == 0x03 &&
            p_cert->publicKey[p_cert->pubKeySize-2] == 0x01) {
            keyparam = MXQ_KEYPARAM_RSA_PUB3;
        }
        else if (p_cert->publicKey[p_cert->pubKeySize-1] == 0x01 &&
                 p_cert->publicKey[p_cert->pubKeySize-2] == 0x00 &&
                 p_cert->publicKey[p_cert->pubKeySize-3] == 0x01 &&
                 p_cert->publicKey[p_cert->pubKeySize-4] == 0x03) {
            keyparam = MXQ_KEYPARAM_RSA_PUB65537;
        }
        else {
            WOLFSSL_MSG("MAXQ: RSA public key not supported");
            return NOT_COMPILED_IN;
        }
        key_type = MXQ_KEYTYPE_RSA;
        totalkeylen = keycomplen;

    }
    else {
        WOLFSSL_MSG("MAXQ: key algo not supported");
        return NOT_COMPILED_IN;
    }

    tls13_server_key_algo = p_cert->keyOID;
    tls13_server_key_len = keycomplen;
    sign_algo = mxq_get_sign_alg_from_sig_oid(p_cert->signatureOID);

    if (sign_algo == ALGO_INVALID) {
        WOLFSSL_MSG("MAXQ: signature algo not supported");
        return NOT_COMPILED_IN;
    }
#endif

    rc = wolfSSL_CryptHwMutexLock();
    if (rc != 0) {
        return rc;
    }

    mxq_rc = MXQ_Build_EC_Cert(certdata, &certdatalen, key_type, keyparam,
                               keycomplen, totalkeylen, pk_offset,
                               p_cert->certBegin,
                               (p_cert->sigIndex - p_cert->certBegin),
                               p_cert->maxIdx, sign_algo, ROOT_CA_CERT_OBJ_ID,
                               MXQ_KEYUSE_VERIFY_KEY_CERT, ALGO_ECDSA_SHA_any,
                               MXQ_KEYUSE_DATASIGNATURE, ALGO_ECDSA_SHA_any,
                               (mxq_u1 *)p_cert->source);
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_Build_EC_Cert() failed");
        wolfSSL_CryptHwMutexUnLock();
        return WC_HW_E;
    }

#if defined(WOLFSSL_MAXQ108X)
    if (tls13_server_cert_id == -1) {
        tls13_server_cert_id = alloc_temp_key_id();
        if (tls13_server_cert_id == -1) {
            WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed");
            wolfSSL_CryptHwMutexUnLock();
            return WC_HW_E;
        }
    }

    /* temporary certificate stored in object id cert_id */
    mxq_rc = MXQ_ImportChildCert(tls13_server_cert_id, certdata, certdatalen);
#else
    /* temporary certificate stored in object id 0 */
    mxq_rc = MXQ_ImportChildCert(0, certdata, certdatalen);
#endif

    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_ImportChildCert() failed");
        wolfSSL_CryptHwMutexUnLock();
        return WC_HW_E;
    }

    wolfSSL_CryptHwMutexUnLock();
    return 0;
}

static int maxq10xx_process_server_sig_kex(WOLFSSL* ssl, byte p_sig_algo,
               const byte* p_sig, word32 p_sig_len,
               const byte* p_rand, word32 p_rand_len,
               const byte* p_server_params, word32 p_server_params_len)
{
    int rc;
    mxq_err_t mxq_rc;
    if (ssl->specs.kea != ecc_diffie_hellman_kea) {
        WOLFSSL_MSG("MAXQ: key exchange algo not supported");
        return NOT_COMPILED_IN;
    }

    if (ssl->ecdhCurveOID != ECC_SECP256R1_OID) {
        WOLFSSL_MSG("MAXQ: key curve not supported");
        return NOT_COMPILED_IN;
    }

    if (p_sig_algo != ecc_dsa_sa_algo) {
        WOLFSSL_MSG("MAXQ: signature algo not supported");
        return NOT_COMPILED_IN;
    }

    rc = wolfSSL_CryptHwMutexLock();
    if (rc != 0) {
        return rc;
    }

    /* NOTE: this function also does verification of the signature as well! */
    mxq_rc = MXQ_SetECDHEKey(ALGO_ECDSA_SHA_256, MXQ_KEYPARAM_EC_P256R1, 0,
                             (mxq_u1 *)p_rand, p_rand_len,
                             (mxq_u1 *)p_server_params, p_server_params_len,
                             (mxq_u1 *)p_sig, p_sig_len);
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_SetECDHEKey() failed");
        wolfSSL_CryptHwMutexUnLock();
        return WC_HW_E;
    }

    wolfSSL_CryptHwMutexUnLock();
    return 0;
}

static int maxq10xx_gen_tls_master_secret(WOLFSSL* ssl, void *ctx)
{
    int rc;
    mxq_err_t mxq_rc;
    mxq_secret_context_api_t secret_conf;
    mxq_u1 tls_rand[SEED_LEN];
    (void)ctx;

    if ((ssl->specs.kea != ecc_diffie_hellman_kea) &&
        (ssl->specs.kea != psk_kea)) {
        WOLFSSL_MSG("MAXQ: key exchange algo not supported");
        return NOT_COMPILED_IN;
    }

    if (ssl->specs.kea == ecc_diffie_hellman_kea) {
        if ((ssl->hsKey == NULL ) ||
            (((ecc_key*)ssl->hsKey)->maxq_ctx.hw_storage == 0)) {
            return NOT_COMPILED_IN;
        }
    }

    XMEMCPY(tls_rand, ssl->arrays->clientRandom, RAN_LEN);
    XMEMCPY(&tls_rand[RAN_LEN], ssl->arrays->serverRandom, RAN_LEN);

    XMEMSET(&secret_conf, 0 ,sizeof(secret_conf));
    secret_conf.pass = 0;
    secret_conf.CSID = ssl->options.cipherSuite |
                       (ssl->options.cipherSuite0 << 8);
    secret_conf.Random = tls_rand;
    secret_conf.Random_size = SEED_LEN;
    secret_conf.is_session_key_secret = 1;
    if (ssl->specs.kea == psk_kea) {
        secret_conf.PSK_info.psk_id = PSK_OBJ_ID;
    }

    rc = wolfSSL_CryptHwMutexLock();
    if (rc != 0) {
        return rc;
    }

    mxq_rc = MXQ_Perform_Key_Exchange(&secret_conf);
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_Perform_Key_Exchange() failed");
        wolfSSL_CryptHwMutexUnLock();
        return WC_HW_E;
    }

    ssl->maxq_ctx.use_hw_keys = 1;
    wolfSSL_CryptHwMutexUnLock();

#ifdef MAXQ_EXPORT_TLS_KEYS
    rc = StoreKeys(ssl, secret_conf.PSK_info.psk_key_bloc,
                   PROVISION_CLIENT_SERVER);
    if (rc != 0) {
        WOLFSSL_ERROR_MSG("MAXQ: StoreKeys() failed");
        return rc;
    }
#endif

    return 0;
}

static int maxq10xx_perform_client_finished(WOLFSSL* ssl, const byte* p_label,
               const byte* p_seed, word32 seedSz, byte* p_dest, void* ctx)
{
    int rc;
    mxq_err_t mxq_rc;
    (void)ssl;
    (void)ctx;

    rc = wolfSSL_CryptHwMutexLock();
    if (rc != 0) {
        return rc;
    }

    mxq_rc = MXQ_tls_prf_sha_256(0, p_label, FINISHED_LABEL_SZ,
                                 p_seed, seedSz,
                                 p_dest, TLS_FINISHED_SZ);
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_tls_prf_sha_256() failed");
        wolfSSL_CryptHwMutexUnLock();
        return WC_HW_E;
    }

    wolfSSL_CryptHwMutexUnLock();
    return 0;
}

static int maxq10xx_perform_tls12_record_processing(WOLFSSL* ssl,
               int is_encrypt,
               byte* out, const byte* in, word32 sz,
               const byte* iv, word32 ivSz,
               byte* authTag, word32 authTagSz,
               const byte* authIn, word32 authInSz)
{
    int rc;
    mxq_err_t mxq_rc;
    mxq_u2 key_id = (is_encrypt == 1) ? 1 : 0;
    mxq_algo_id_t algo_id = 0;

    if (! ssl->maxq_ctx.use_hw_keys) {
        return NOT_COMPILED_IN;
    }

    if ((ssl->specs.bulk_cipher_algorithm != wolfssl_aes_gcm) &&
            (ssl->specs.bulk_cipher_algorithm != wolfssl_aes_ccm)) {
        WOLFSSL_MSG("MAXQ: tls record cipher algo not supported");
        return NOT_COMPILED_IN;
    }

    if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm) {
        algo_id = ALGO_CIPHER_AES_GCM;
    }
    else if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_ccm) {
        algo_id = ALGO_CIPHER_AES_CCM;
    }

    rc = wolfSSL_CryptHwMutexLock();
    if (rc != 0) {
        return rc;
    }

    mxq_rc = maxq10xx_cipher_do(algo_id, is_encrypt, key_id, (mxq_u1 *)in,
                                out, sz, (mxq_u1 *)iv, ivSz,
                                (mxq_u1 *)authIn, authInSz, authTag, authTagSz);
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: maxq10xx_cipher_do() failed");
        wolfSSL_CryptHwMutexUnLock();
        return WC_HW_E;
    }

    wolfSSL_CryptHwMutexUnLock();
    return 0;
}

static int maxq10xx_read_device_cert_der(byte* p_dest_buff, word32* p_len)
{
    int rc;
    mxq_err_t mxq_rc;
    word32 cert_size = 0;

#if defined(WOLFSSL_MAXQ108X)
    DecodedCert decoded;
    mxq_keyparam_id_t keyparam = MXQ_KEYPARAM_EC_P256R1;
    int pk_offset = 0;
#endif

    WOLFSSL_ENTER("maxq10xx_read_device_cert_der");
    if (!p_dest_buff || !p_len) {
        return BAD_FUNC_ARG;
    }

    if (*p_len < 1024) {
        WOLFSSL_ERROR_MSG("MAXQ: insufficient buffer length");
        return BAD_FUNC_ARG;
    }

    rc = wolfSSL_CryptHwMutexLock();
    if (rc != 0) {
        return rc;
    }

    mxq_rc = MXQ_ReadObject(DEVICE_CERT_OBJ_ID, 24, p_dest_buff, p_len);
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_ReadObject() failed");
        wolfSSL_CryptHwMutexUnLock();
        return WC_HW_E;
    }
    wolfSSL_CryptHwMutexUnLock();

#if defined(WOLFSSL_MAXQ108X)
    wc_InitDecodedCert(&decoded, p_dest_buff, *p_len, NULL);
    wc_ParseCert(&decoded, CERT_TYPE, NO_VERIFY, NULL);
    pk_offset = decoded.publicKeyIndex;
    if (decoded.keyOID == ECDSAk ) {
        keyparam = maxq_curve_wolfssl_id2mxq_id(decoded.pkCurveOID,
                       (unsigned int *)&device_key_len);
        if (keyparam == MXQ_UNKNOWN_CURVE) {
            WOLFSSL_MSG("MAXQ: key curve not supported");
            return NOT_COMPILED_IN;
        }
    }
    else if (decoded.keyOID == RSAk) {
        pk_offset = calculate_modulus_offset(decoded.source,
                                             decoded.publicKeyIndex+1);
        device_key_len = ((decoded.source[pk_offset-2] << 8) |
                          decoded.source[pk_offset-1]);
    }
#endif

    cert_size = (p_dest_buff[2] << 8) + p_dest_buff[3] + 4;
    if (*p_len < cert_size) {
        return BUFFER_E;
    }
    *p_len = cert_size;
    return 0;
}

#if defined(WOLFSSL_MAXQ10XX_TLS)
int wolfSSL_maxq10xx_load_certificate(WOLFSSL *ssl) {
    DerBuffer* maxq_der = NULL;
    int ret = 0;

    ret = AllocDer(&maxq_der, FILE_BUFFER_SIZE, CERT_TYPE, ssl->heap);
    if (ret != 0) {
        return ret;
    }

    ret = maxq10xx_read_device_cert_der(maxq_der->buffer,
                                        &maxq_der->length);
    if (ret != 0) {
        return ret;
    }

    ssl->maxq_ctx.device_cert = maxq_der;

    if (ssl->buffers.weOwnCert) {
        FreeDer(&ssl->buffers.certificate);
    }

    ssl->buffers.certificate = maxq_der;
    ssl->buffers.weOwnCert = 1;
    return WOLFSSL_SUCCESS;
}
#endif /* WOLFSSL_MAXQ10XX_TLS */

static int maxq10xx_ecc_sign(WOLFSSL* ssl,
               const unsigned char* p_in, unsigned int p_in_len,
               unsigned char* p_out, word32* p_out_len,
               const unsigned char* keyDer, unsigned int keySz, void* ctx)
{
    int rc;
    (void)ssl;
    (void)keyDer;
    (void)keySz;
    (void)ctx;

    rc = wolfSSL_CryptHwMutexLock();
    if (rc != 0) {
        return rc;
    }

    rc = maxq10xx_ecc_sign_local(DEVICE_KEY_PAIR_OBJ_ID, (byte *)p_in, p_in_len,
                                 p_out, p_out_len, device_key_len);

    wolfSSL_CryptHwMutexUnLock();
    if (rc) {
        WOLFSSL_ERROR_MSG("MAXQ: maxq10xx_ecc_sign() failed");
        return rc;
    }

    return 0;
}
#endif /* WOLFSSL_MAXQ10XX_TLS */

int maxq10xx_port_init(void)
{
    int ret = 0;
    mxq_err_t mxq_rc;

    #ifdef WOLF_CRYPTO_CB
    ret = wc_CryptoCb_RegisterDevice(0, wolfSSL_Soft_CryptoDevCb, NULL);
    if (ret != 0) {
        WOLFSSL_ERROR_MSG("MAXQ: wolfSSL_Soft_CryptoDevCb, "
                    "wc_CryptoCb_RegisterDevice() failed");
        return ret;
    }
    #endif

    #if defined(MAXQ10XX_MUTEX)
    ret = maxq_CryptHwMutexTryLock();
    if (ret) {
        WOLFSSL_ERROR_MSG("MAXQ: maxq10xx_port_init() -> device is busy "
                    "(switching to soft mode)");
        return 0;
    }
    #endif

    mxq_rc = MXQ_Module_Init();
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_Module_Init() failed");
        ret = WC_HW_E;
    }

    wolfSSL_CryptHwMutexUnLock();

    #if defined(WOLF_CRYPTO_CB)
    if (ret == 0) {
        ret = wc_CryptoCb_RegisterDevice(MAXQ_DEVICE_ID,
                                         wolfSSL_MAXQ10XX_CryptoDevCb, NULL);
        if (ret != 0) {
            WOLFSSL_ERROR_MSG("MAXQ: wolfSSL_MAXQ10XX_CryptoDevCb, "
                        "wc_CryptoCb_RegisterDevice() failed");
        }
    }
    #endif

    return ret;
}

/* This basically does all the work that SendClientKeyExchange() does in the
 * case of ECDSA. That's because if a callback is defined, almost nothing is
 * done in SendClientKeyExchange(). */
static int maxq10xx_tls12_ecc_shared_secret(WOLFSSL* ssl, ecc_key* otherKey,
               unsigned char* pubKeyDer, word32* pubKeySz,
               unsigned char* out, word32* outlen,
               int side, void* ctx)
{
    int rc;
    mxq_err_t mxq_rc;
    ecc_key *p_key = NULL;
    mxq_length key_len_param;
    mxq_u1* server_public_key_param;
    mxq_u2 csid_param = ssl->options.cipherSuite |
                        (ssl->options.cipherSuite0 << 8);
    byte result_public_key[1 + (2 * ECC256_KEYSIZE)];
    (void)ctx;
    (void)otherKey;
    (void)out;
    (void)outlen;
    (void)side;

    WOLFSSL_ENTER("maxq10xx_ecc_shared_secret");

    if (ssl->specs.kea != ecc_diffie_hellman_kea) {
        WOLFSSL_MSG("MAXQ: key exchange algo not supported");
        return NOT_COMPILED_IN;
    }

    if (ssl->ecdhCurveOID != ECC_SECP256R1_OID) {
        WOLFSSL_MSG("MAXQ: key curve not supported");
        return NOT_COMPILED_IN;
    }

    ssl->hsType = DYNAMIC_TYPE_ECC;
    rc = AllocKey(ssl, ssl->hsType, &ssl->hsKey);
    if (rc != 0) {
        return rc;
    }

    p_key = (ecc_key*)ssl->hsKey;

    rc = wolfSSL_CryptHwMutexLock();
    if (rc != 0) {
        return rc;
    }

    XMEMSET(result_public_key, 0, sizeof(result_public_key));

    server_public_key_param = NULL;
    key_len_param = sizeof(result_public_key);

    mxq_rc = MXQ_Ecdh_Compute_Shared(MXQ_KEYPARAM_EC_P256R1,
                                     server_public_key_param, result_public_key,
                                     key_len_param, csid_param);
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_Ecdh_Compute_Shared() failed");
        wolfSSL_CryptHwMutexUnLock();
        return WC_HW_E;
    }

    wolfSSL_CryptHwMutexUnLock();

    /* client public key */
    p_key->state = 0;

    rc = wc_ecc_set_curve(p_key, ECC256_KEYSIZE, ECC_SECP256R1);
    if (rc != 0) {
        WOLFSSL_ERROR_MSG("MAXQ: wc_ecc_set_curve() failed");
        return rc;
    }

    p_key->flags = WC_ECC_FLAG_NONE;
    p_key->type = ECC_PUBLICKEY;

    rc = mp_read_unsigned_bin(p_key->pubkey.x, &result_public_key[1],
                              ECC256_KEYSIZE);
    if (rc != 0) {
        WOLFSSL_ERROR_MSG("MAXQ: mp_read_unsigned_bin() failed");
        return rc;
    }

    rc = mp_read_unsigned_bin(p_key->pubkey.y,
                              &result_public_key[1 + ECC256_KEYSIZE],
                              ECC256_KEYSIZE);
    if (rc != 0) {
        WOLFSSL_ERROR_MSG("MAXQ: mp_read_unsigned_bin() failed");
        return rc;
    }

    p_key->maxq_ctx.hw_storage = 1;

    PRIVATE_KEY_UNLOCK();
    rc = wc_ecc_export_x963(p_key, pubKeyDer, pubKeySz);
    PRIVATE_KEY_LOCK();

    return rc;
}

#ifdef WOLFSSL_MAXQ108X
static int wc_MAXQ10XX_HmacSetKey(int type)
{
    mxq_algo_id_t algo;
    int rc;
    mxq_err_t mxq_rc;

    if (!tls13active) {
        return NOT_COMPILED_IN;
    }

    if (type == WC_SHA256) {
        algo = ALGO_HMAC_SHA256;
    }
    else if (type == WC_SHA384) {
        algo = ALGO_HMAC_SHA384;
    }
    else {
        return NOT_COMPILED_IN;
    }

    if (tls13_server_finish_obj_id != -1) {
        if (tls13_server_key_id != NULL) {
            free_temp_key_id(*tls13_server_key_id);
            *tls13_server_key_id = -1;
        }
        mac_key_obj_id = &tls13_server_finish_obj_id;
    }
    else if (tls13_client_finish_obj_id != -1) {
        mac_key_obj_id = &tls13_client_finish_obj_id;
    }

    if (mac_key_obj_id == NULL) {
        WOLFSSL_MSG("MAXQ: wc_MAXQ10XX_HmacSetKey No MAC Key is set");
        return NOT_COMPILED_IN;
    }

    rc = wolfSSL_CryptHwMutexLock();
    if (rc != 0) {
        return rc;
    }

    mxq_rc = MXQ_MAC_Init(0x02, algo, *mac_key_obj_id, NULL, 0);
    wolfSSL_CryptHwMutexUnLock();

    if (mxq_rc == 0) {
        mac_comp_active = 1;
    }
    else {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_MAC_Init() failed");
        rc = WC_HW_E;
    }

    return rc;
}

static int wc_MAXQ10XX_HmacUpdate(const byte* msg, word32 length)
{
    int rc;
    mxq_err_t mxq_rc;
    if (!tls13active || !mac_comp_active) {
        return NOT_COMPILED_IN;
    }

    rc = wolfSSL_CryptHwMutexLock();
    if (rc != 0) {
        return rc;
    }

    mxq_rc = MXQ_MAC_Update((unsigned char *)msg, length);
    wolfSSL_CryptHwMutexUnLock();

    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_MAC_Update() failed");
        rc = WC_HW_E;
    }

    return rc;
}

static int wc_MAXQ10XX_HmacFinal(byte* hash)
{
    int rc;
    mxq_err_t mxq_rc;
    mxq_length maclen = 64;
    if (!tls13active || !mac_comp_active) {
        return NOT_COMPILED_IN;
    }

    rc = wolfSSL_CryptHwMutexLock();
    if (rc != 0) {
        return rc;
    }

    mxq_rc = MXQ_MAC_Finish(hash, &maclen);
    wolfSSL_CryptHwMutexUnLock();
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_MAC_Finish() failed");
        rc = WC_HW_E;
    }

    if (mac_key_obj_id != NULL) {
        free_temp_key_id(*mac_key_obj_id);
        *mac_key_obj_id = -1;
        mac_key_obj_id = NULL;
    }
    mac_comp_active = 0;

    return rc;
}

static int maxq10xx_create_dh_key(byte* p, word32 pSz, byte* g, word32 gSz,
                                  byte* pub, word32* pubSz)
{
    int rc;
    mxq_err_t mxq_rc;

    WOLFSSL_ENTER("maxq10xx_create_dh_key");
    if (!tls13active) {
        return NOT_COMPILED_IN;
    }

    *pubSz = pSz;
    if (tls13_dh_obj_id == -1) {
        tls13_dh_obj_id = alloc_temp_key_id();
        if (tls13_dh_obj_id == -1) {
            WOLFSSL_MSG("MAXQ: alloc_temp_key_id() failed");
            rc = NOT_COMPILED_IN;
            return rc;
        }
    }

    rc = wolfSSL_CryptHwMutexLock();
    if (rc != 0) {
        return rc;
    }

    mxq_rc = MXQ_TLS13_Generate_Key(pub, tls13_dh_obj_id, 0, MXQ_KEYPARAM_DHE,
                                    pSz, p, gSz, g);

    wolfSSL_CryptHwMutexUnLock();
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_TLS13_Generate_Key() failed");
        rc = WC_HW_E;
    }

    return rc;
}

static int maxq10xx_dh_gen_key_pair(DhKey* key, WC_RNG* rng,
                                    byte* priv, word32* privSz,
                                    byte* pub, word32* pubSz) {
    word32 p_size, g_size;
    unsigned char pbuf[256], gbuf[4];
    (void)rng;
    (void)priv;
    (void)privSz;

    p_size = mp_unsigned_bin_size(&key->p);
    mp_to_unsigned_bin(&key->p, pbuf);

    g_size = mp_unsigned_bin_size(&key->g);
    mp_to_unsigned_bin(&key->g, gbuf);

    return maxq10xx_create_dh_key(pbuf, p_size, gbuf, g_size, pub, pubSz);
}

static int maxq10xx_dh_agree(WOLFSSL* ssl, struct DhKey* key,
               const unsigned char* priv, unsigned int privSz,
               const unsigned char* pubKeyDer, unsigned int pubKeySz,
               unsigned char* out, unsigned int* outlen,
               void* ctx)
{
    int rc;
    mxq_err_t mxq_rc;
    (void)ctx;
    (void)key;
    (void)priv;
    (void)privSz;

    WOLFSSL_ENTER("maxq10xx_dh_agree");

    mxq_u2 csid_param = ssl->options.cipherSuite |
                        (ssl->options.cipherSuite0 << 8);

    if (tls13_dh_obj_id == -1) {
        WOLFSSL_ERROR_MSG("MAXQ: DH key is not created before");
        rc = NOT_COMPILED_IN;
        return rc;
    }

    if (tls13_shared_secret_obj_id == -1) {
        tls13_shared_secret_obj_id = alloc_temp_key_id();
        if (tls13_shared_secret_obj_id == -1) {
            WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed");
            return NOT_COMPILED_IN;
        }
    }

    rc = wolfSSL_CryptHwMutexLock();
    if (rc != 0) {
        return rc;
    }

    mxq_rc = MXQ_TLS13_Create_Secret((unsigned char*)pubKeyDer, pubKeySz,
                                     tls13_dh_obj_id, 0, MXQ_KEYPARAM_DHE,
                                     csid_param, tls13_shared_secret_obj_id,
                                     out, outlen);
    wolfSSL_CryptHwMutexUnLock();
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: wolfSSL_CryptHwMutexUnLock() failed");
        rc = WC_HW_E;
    }

    *outlen = pubKeySz;
    free_temp_key_id(tls13_dh_obj_id);
    tls13_dh_obj_id = -1;
    free_temp_key_id(tls13_ecc_obj_id);
    tls13_ecc_obj_id = -1;

    return rc;
}

static int  maxq10xx_ecc_key_gen(WOLFSSL* ssl, ecc_key* key, word32 keySz,
                int ecc_curve, void* ctx)
{
    int rc;
    mxq_err_t mxq_rc;
    unsigned char mxq_key[MAX_EC_KEY_SIZE];
    (void)ctx;
    (void)ssl;

    WOLFSSL_ENTER("maxq10xx_ecc_key_gen");

    if (tls13_ecc_obj_id == -1) {
        tls13_ecc_obj_id = alloc_temp_key_id();
        if (tls13_ecc_obj_id == -1) {
            WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed");
            rc = NOT_COMPILED_IN;
            return rc;
        }
    }

    rc = wolfSSL_CryptHwMutexLock();
    if (rc != 0) {
        return rc;
    }
    mxq_rc = MXQ_TLS13_Generate_Key(mxq_key, tls13_ecc_obj_id, MXQ_KEYTYPE_ECC,
                                    getMaxqKeyParamFromCurve(key->dp->id),
                                    keySz, NULL, 0, NULL);

    wolfSSL_CryptHwMutexUnLock();
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_TLS13_Generate_Key() failed");
        return WC_HW_E;
    }

    rc = wc_ecc_import_unsigned(key, (byte*)mxq_key, (byte*)mxq_key + keySz,
                                NULL, ecc_curve);
    if (rc) {
        WOLFSSL_ERROR_MSG("MAXQ: wc_ecc_import_raw_ex() failed");
    }

    return rc;
}

static int maxq10xx_ecc_verify(WOLFSSL* ssl, const byte* sig,
                               word32 sigSz, const byte* hash,
                               word32 hashSz, const byte* key,
                               word32 keySz, int* result, void* ctx)
{
    int rc;
    (void)ssl;
    (void)key;
    (void)keySz;
    (void)ctx;

    WOLFSSL_ENTER("maxq10xx_ecc_verify");

    if (!tls13active) {
        return CRYPTOCB_UNAVAILABLE;
    }

    if (tls13_server_key_algo != ECDSAk) {
        return CRYPTOCB_UNAVAILABLE;
    }

    rc = wolfSSL_CryptHwMutexLock();
    if (rc != 0) {
        return rc;
    }

    rc = maxq10xx_ecc_verify_local(tls13_server_cert_id, (mxq_u1*)hash, hashSz,
                                   (mxq_u1*)sig, sigSz,
                                   result, tls13_server_key_len);
    wolfSSL_CryptHwMutexUnLock();

    return rc;
}

static int maxq10xx_tls13_ecc_shared_secret(WOLFSSL* ssl, ecc_key* otherKey,
               unsigned char* pubKeyDer, word32* pubKeySz,
               unsigned char* out, word32* outlen,
               int side, void* ctx)
{
    int rc;
    mxq_err_t mxq_rc;
    word32 peerKeySz = otherKey->dp->size;
    uint8_t  peerKeyBuf[MAX_EC_KEY_SIZE];
    uint8_t* peerKey = peerKeyBuf;
    uint8_t* qx = peerKey;
    uint8_t* qy = &peerKey[peerKeySz];
    word32 qxLen = peerKeySz,  qyLen = peerKeySz;
    mxq_u2 csid_param = ssl->options.cipherSuite |
                        (ssl->options.cipherSuite0 << 8);
    (void)ctx;
    (void)pubKeyDer;
    (void)side;
    (void)pubKeySz;

    WOLFSSL_ENTER("maxq10xx_ecc_shared_secret");

    rc = wc_ecc_export_public_raw(otherKey, qx, &qxLen, qy, &qyLen);
    if (rc != 0) {
        return rc;
    }

    if (tls13_ecc_obj_id == -1) {
        WOLFSSL_ERROR_MSG("MAXQ: ECDHE key is not created before");
        rc = NOT_COMPILED_IN;
        return rc;
    }

    if (tls13_shared_secret_obj_id == -1) {
        tls13_shared_secret_obj_id = alloc_temp_key_id();
        if (tls13_shared_secret_obj_id == -1) {
            WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed");
            return NOT_COMPILED_IN;
        }
    }

    rc = wolfSSL_CryptHwMutexLock();
    if (rc != 0) {
        return rc;
    }

    mxq_rc = MXQ_TLS13_Create_Secret(peerKey, (2*peerKeySz), tls13_ecc_obj_id,
                                     MXQ_KEYTYPE_ECC,
                                     getMaxqKeyParamFromCurve(otherKey->dp->id),
                                     csid_param, tls13_shared_secret_obj_id,
                                     out, outlen);

    wolfSSL_CryptHwMutexUnLock();
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_TLS13_Create_Secret() failed");
        rc = WC_HW_E;
    }

    *outlen = otherKey->dp->size;
    free_temp_key_id(tls13_dh_obj_id);
    tls13_dh_obj_id = -1;
    free_temp_key_id(tls13_ecc_obj_id);
    tls13_ecc_obj_id = -1;

    return rc;
}

static int maxq10xx_rsa_pss_verify_ex(WOLFSSL* ssl,
                                      byte* hashed_msg, word32 hashed_msg_sz,
                                      byte* pss_sign, word32 pss_signlen,
                                      int isCertId)
{
    mxq_u2 pubkey_objectid;
    int ret;
    mxq_err_t mxq_rc;
    (void)ssl;

    WOLFSSL_ENTER("maxq10xx_rsa_pss_verify_ex");

    if (!tls13active) {
        return NOT_COMPILED_IN;
    }

    if (isCertId) {
        pubkey_objectid = tls13_server_cert_id;
    }
    else {
        pubkey_objectid = DEVICE_KEY_PAIR_OBJ_ID;
    }

    ret = wolfSSL_CryptHwMutexLock();
    if (ret != 0) {
        return ret;
    }
    mxq_rc = MXQ_Verify(ALGO_RSASSAPSSPKCS1_V2_1_PLAIN, pubkey_objectid,
                        hashed_msg, hashed_msg_sz, pss_sign, pss_signlen);

    wolfSSL_CryptHwMutexUnLock();

    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_Verify() failed");
        ret = WC_HW_E;
    }
    return ret;
}

/* This will do all the work that is normally done in RsaVerify() and
 * CheckRSASignature(). That is why at the bottom, we release the key. Because
 * verification has been completed and CheckRSASignature() should be skipped.
 * The same reasoning for maxq10xx_RsaSkipSignCheck() doing nothing. */
static int maxq10xx_rsa_pss_verify(WOLFSSL* ssl,
                                   unsigned char* in, unsigned int inSz,
                                   unsigned char** out, int hash, int mgf,
                                   const unsigned char* key, unsigned int keySz,
                                   void* ctx) {
    int    ret = 0;
    byte   sigData[MAX_SIG_DATA_SZ];
    word16 sigDataSz;
    word32 sigSz;
    (void)out;
    (void)mgf;
    (void)key;
    (void)keySz;
    (void)ctx;

    if (hash == SHA256h) {
        hash = sha256_mac;
    }
    else if (hash == SHA384h) {
        hash = sha384_mac;
    }
    else if (hash  == SHA512h) {
        hash = sha512_mac;
    }
    else {
        return BAD_FUNC_ARG;
    }

    ret = CreateSigData(ssl, sigData, &sigDataSz, 1);
    if (ret != 0)
        return ret;

    /* PSS signature can be done in-place */
    ret = CreateRSAEncodedSig(sigData, sigData, sigDataSz,
                              rsa_pss_sa_algo, hash);
    if (ret < 0)
        return ret;
    sigSz = ret;

    ret = maxq10xx_rsa_pss_verify_ex(ssl, sigData, sigSz, in, inSz, 1);

    if (ret == 0) {
        /* This ensures call to CheckRSASignature() is skipped. */
        ssl->peerRsaKeyPresent = 0;
        FreeKey(ssl, DYNAMIC_TYPE_RSA, (void**)&ssl->peerRsaKey);
        ssl->options.peerAuthGood = 1;
    }

    return ret;
}

static int maxq10xx_skip_sign_check(WOLFSSL* ssl,
               unsigned char* sig, unsigned int sigSz,
               unsigned char** out, int hash, int mgf,
               const unsigned char* key, unsigned int keySz,
               void* ctx) {
    (void)ssl;
    (void)sig;
    (void)sigSz;
    (void)out;
    (void)hash;
    (void)mgf;
    (void)key;
    (void)keySz;
    (void)ctx;
    return 0;
}

static int maxq10xx_rsa_pss_sign(WOLFSSL* ssl, const byte* in, word32 inSz,
                                 byte* out, word32* outSz, int hash, int mgf,
                                 const byte* key, word32 keySz, void* ctx)
{
    int ret;
    mxq_err_t mxq_rc;
    (void)ssl;
    (void)hash;
    (void)mgf;
    (void)key;
    (void)keySz;
    (void)ctx;

    WOLFSSL_ENTER("maxq10xx_rsa_pss_sign");

    if (!tls13active) {
        return NOT_COMPILED_IN;
    }

    ret = wolfSSL_CryptHwMutexLock();
    if (ret != 0) {
        return ret;
    }

    mxq_rc = MXQ_Sign(ALGO_RSASSAPSSPKCS1_V2_1_PLAIN, DEVICE_KEY_PAIR_OBJ_ID,
                      in, inSz, out, outSz);

    wolfSSL_CryptHwMutexUnLock();

    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_Sign() failed");
        return WC_HW_E;
    }

    ret = wolfSSL_CryptHwMutexLock();
    if (ret != 0) {
        return ret;
    }

    mxq_rc = MXQ_Verify(ALGO_RSASSAPSSPKCS1_V2_1_PLAIN, DEVICE_KEY_PAIR_OBJ_ID,
                        in, inSz, out, *outSz);

    wolfSSL_CryptHwMutexUnLock();
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_Verify() failed");
        return WC_HW_E;
    }

    return ret;
}

#ifdef HAVE_HKDF
static int maxq10xx_hkdf_extract(byte* prk, const byte* salt, word32 saltLen,
               byte* ikm, word32 ikmLen, int digest, void* ctx)
{
    int rc;
    mxq_err_t mxq_rc;
    mxq_length prk_len = 0;
    mxq_algo_id_t mxq_digest_id = ALGO_INVALID;
    int salt_kid = -1, ikm_kid = -1, ret_kid = -1;

    (void)ctx;

    switch (digest) {
        #ifndef NO_SHA256
        case WC_SHA256:
            prk_len = WC_SHA256_DIGEST_SIZE;
            mxq_digest_id = ALGO_MD_SHA256;
            break;
        #endif

        #ifdef WOLFSSL_SHA384
        case WC_SHA384:
            prk_len = WC_SHA384_DIGEST_SIZE;
            mxq_digest_id = ALGO_MD_SHA384;
            break;
        #endif

        #ifdef WOLFSSL_TLS13_SHA512
        case WC_SHA512:
            prk_len = WC_SHA512_DIGEST_SIZE;
            mxq_digest_id = ALGO_MD_SHA512;
            break;
        #endif
        default:
            return BAD_FUNC_ARG;
    }

    /* Prepare key id parameters */
    if (saltLen != 0 && ikmLen != 0) {
        /* handshake_secret = HKDF-Extract(salt: derived_secret,
         *                        key: shared_secret) */
        if (tls13_handshake_secret_obj_id == -1) {
            tls13_handshake_secret_obj_id = alloc_temp_key_id();
            if (tls13_handshake_secret_obj_id == -1) {
                WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed");
                return NOT_COMPILED_IN;
            }
        }
        salt_kid = tls13_derived_secret_obj_id;
        ikm_kid  = tls13_shared_secret_obj_id;
        ret_kid  = tls13_handshake_secret_obj_id;
        free_temp_key_id(tls13_derived_secret_obj_id);
        tls13_derived_secret_obj_id = -1;
    }
    else if (saltLen != 0 && ikmLen == 0) {
        /* master_secret = HKDF-Extract(salt: derived_secret,
         *                     key: 00...) */
        if (tls13_master_secret_obj_id == -1) {
            tls13_master_secret_obj_id = alloc_temp_key_id();
            if (tls13_master_secret_obj_id == -1) {
                WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed");
                return NOT_COMPILED_IN;
            }
        }

        salt_kid = tls13_derived_secret_obj_id;
        ikm_kid  = -1;
        ret_kid  = tls13_master_secret_obj_id;
        free_temp_key_id(tls13_derived_secret_obj_id);
        tls13_derived_secret_obj_id = -1;
    }
    else if (saltLen == 0 && ikmLen == 0) {
        /* early_secret = HKDF-Extract(salt: 00, key: 00...) */
        if (tls13_early_secret_obj_id == -1) {
            tls13_early_secret_obj_id = alloc_temp_key_id();
            if (tls13_early_secret_obj_id == -1) {
                WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed");
                return NOT_COMPILED_IN;
            }
        }

        salt_kid = -1;
        ikm_kid  = -1;
        ret_kid  = tls13_early_secret_obj_id;

        tls13early = 1;
    }
    else if (saltLen == 0 && ikmLen != 0) {
        /* early_secret = HKDF-Extract(salt: 00, key: 00...) */
        if (tls13_hs_early_secret_obj_id == -1) {
            tls13_hs_early_secret_obj_id = alloc_temp_key_id();
            if (tls13_hs_early_secret_obj_id == -1) {
                WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed");
                return NOT_COMPILED_IN;
            }
        }

        salt_kid = -1;
        ikm_kid  = PSK_KID;
        ret_kid  = tls13_hs_early_secret_obj_id;

        tls13early = 1;
    }
    else {
        WOLFSSL_MSG("MAXQ: MXQ_TLS13_Extract_Secret() does not support");
        return NOT_COMPILED_IN;
    }

    /* When length is 0 then use zeroed data of digest length. */
    if (ikmLen == 0) {
        ikmLen = prk_len;
        XMEMSET(ikm, 0, prk_len);
    }

    if (salt_kid != -1) {
        saltLen = 0;
    }

    if (ikm_kid != -1) {
        ikmLen = 0;
    }

    if (ret_kid != -1) {
        XMEMSET(prk, 0, prk_len);
        prk_len = 0;
    }

    rc = wolfSSL_CryptHwMutexLock();
    if (rc != 0) {
        return rc;
    }

    mxq_rc = MXQ_TLS13_Extract_Secret(mxq_digest_id, (mxq_u2)ret_kid,
                                      prk, &prk_len, (mxq_u2)salt_kid,
                                      salt, (mxq_u2)saltLen,
                                      (mxq_u2)ikm_kid, ikm, (mxq_u2)ikmLen);
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_TLS13_Extract_Secret() failed");
        wolfSSL_CryptHwMutexUnLock();
        return WC_HW_E;
    }

    wolfSSL_CryptHwMutexUnLock();
    return 0;
}

static char *strstr_with_size(char *str, const char *substr, size_t n)
{
    char *p = str, *pEnd = str + n;
    size_t substr_len = XSTRLEN(substr);

    if (substr_len == 0) {
        return str;
    }

    pEnd -= (substr_len - 1);

    for (;p < pEnd; ++p) {
        if (0 == XSTRNCMP(p, substr, substr_len))
            return p;
    }

    return NULL;
}

static int maxq10xx_HkdfExpand(int digest, const byte* inKey, word32 inKeySz,
                               const byte* info, word32 infoSz, byte* out,
                               word32 outSz, int side)
{
    int rc;
    mxq_err_t mxq_rc;
    mxq_algo_id_t mxq_digest_id = ALGO_INVALID;
    mxq_keytype_id_t ret_keytype = MXQ_KEYTYPE_IKM;
    int prk_kid = -1, ret_kid = -1;
    int ret_isiv = 0;

    switch (digest) {
        #ifndef NO_SHA256
        case WC_SHA256:
            mxq_digest_id = ALGO_MD_SHA256;
            break;
        #endif

        #ifdef WOLFSSL_SHA384
        case WC_SHA384:
            mxq_digest_id = ALGO_MD_SHA384;
            break;
        #endif

        #ifdef WOLFSSL_TLS13_SHA512
        case WC_SHA512:
            mxq_digest_id = ALGO_MD_SHA512;
            break;
        #endif
        default:
            return BAD_FUNC_ARG;
    }

    /* Prepare key id parameters */
    if (strstr_with_size((char *)info, derivedLabel, infoSz) != NULL) {
        if (tls13early) {
            if (local_is_psk) {
                if (tls13_hs_early_secret_obj_id == -1) {
                        WOLFSSL_ERROR_MSG("MAXQ: Handshake early secret is not "
                                    "created yet");
                        return NOT_COMPILED_IN;
                }

                tls13_derived_secret_obj_id = alloc_temp_key_id();
                if (tls13_derived_secret_obj_id == -1) {
                    WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed");
                    return NOT_COMPILED_IN;
                }
                prk_kid = tls13_hs_early_secret_obj_id;
                ret_kid = tls13_derived_secret_obj_id;
                ret_keytype = MXQ_KEYTYPE_IKM;
                free_temp_key_id(tls13_hs_early_secret_obj_id);
                tls13_hs_early_secret_obj_id = -1;
            }
            else {
                /* derived_secret = HKDF-Expand-Label(key: early_secret,
                 *                      label: "derived", ctx: empty_hash) */
                tls13_derived_secret_obj_id = alloc_temp_key_id();
                if (tls13_derived_secret_obj_id == -1) {
                    WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed");
                    return NOT_COMPILED_IN;
                }

                prk_kid = tls13_early_secret_obj_id;
                ret_kid = tls13_derived_secret_obj_id;
                ret_keytype = MXQ_KEYTYPE_IKM;
                free_temp_key_id(tls13_early_secret_obj_id);
                tls13_early_secret_obj_id = -1;
            }
            ret_isiv = 0;
            tls13early = 0;
        }
        else {
            /* derived_secret = HKDF-Expand-Label(key: handshake_secret,
             *                      label: "derived", ctx: empty_hash) */
            tls13_derived_secret_obj_id = alloc_temp_key_id();
            if (tls13_derived_secret_obj_id == -1) {
                WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed");
                return NOT_COMPILED_IN;
            }

            prk_kid = tls13_handshake_secret_obj_id;
            ret_kid = tls13_derived_secret_obj_id;
            ret_keytype = MXQ_KEYTYPE_IKM;
            free_temp_key_id(tls13_handshake_secret_obj_id);
            tls13_handshake_secret_obj_id = -1;
            ret_isiv = 0;
        }
    }
    else if (strstr_with_size((char *)info, cHsTrafficLabel, infoSz)
               != NULL) {
        is_hs_key = 1;
        /* client_secret = HKDF-Expand-Label(key: handshake_secret,
         *                     label: "c hs traffic", ctx: hello_hash) */
        if (tls13_client_secret_obj_id == -1) {
            tls13_client_secret_obj_id = alloc_temp_key_id();
            if (tls13_client_secret_obj_id == -1) {
                WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed");
                return NOT_COMPILED_IN;
            }
        }

        prk_kid = tls13_handshake_secret_obj_id;
        ret_kid = tls13_client_secret_obj_id;
        ret_keytype = MXQ_KEYTYPE_IKM;
        ret_isiv = 0;
    }
    else if (strstr_with_size((char *)info, sHsTrafficLabel, infoSz)
               != NULL) {
        /* client_secret = HKDF-Expand-Label(key: handshake_secret,
         *                     label: "s hs traffic", ctx: hello_hash) */
        if (tls13_server_secret_obj_id == -1) {
            tls13_server_secret_obj_id = alloc_temp_key_id();
            if (tls13_server_secret_obj_id == -1) {
                WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed");
                return NOT_COMPILED_IN;
            }
        }

        prk_kid = tls13_handshake_secret_obj_id;
        ret_kid = tls13_server_secret_obj_id;
        ret_keytype = MXQ_KEYTYPE_IKM;
        ret_isiv = 0;
    }
    else if (strstr_with_size((char *)info, cAppTrafficLabel, infoSz)
               != NULL) {
        is_hs_key = 0;
        /* client_secret = HKDF-Expand-Label(key: master_secret,
         *                     label: "c ap traffic", ctx: handshake_hash) */
        if (tls13_client_secret_obj_id == -1) {
            tls13_client_secret_obj_id = alloc_temp_key_id();
            if (tls13_client_secret_obj_id == -1) {
                WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed");
                return NOT_COMPILED_IN;
            }
        }

        prk_kid = tls13_master_secret_obj_id;
        ret_kid = tls13_client_secret_obj_id;
        ret_keytype = MXQ_KEYTYPE_IKM;
        ret_isiv = 0;
    }
    else if (strstr_with_size((char *)info, sAppTrafficLabel, infoSz)
               != NULL) {
        /* server_secret = HKDF-Expand-Label(key: master_secret,
         *                     label: "s ap traffic", ctx: handshake_hash) */
        tls13_server_secret_obj_id = alloc_temp_key_id();
        if (tls13_server_secret_obj_id == -1) {
            WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed");
            return NOT_COMPILED_IN;
        }

        prk_kid = tls13_master_secret_obj_id;
        ret_kid = tls13_server_secret_obj_id;
        ret_keytype = MXQ_KEYTYPE_IKM;
        ret_isiv = 0;
    }
    else if (strstr_with_size((char *)info, keyLabel, infoSz) != NULL) {
        /* first client key then server */
        if (side == WOLFSSL_CLIENT_END) {
            /* client_handshake_key = HKDF-Expand-Label(key: client_secret,
             *                            label: "key", ctx: "")
             * client_application_key = HKDF-Expand-Label(key: client_secret,
             *                              label: "key", ctx: "") */
            int tls13_client_key_obj_id = -1;
            if (is_hs_key) {
                if (tls13_client_hs_key_obj_id == -1) {
                    tls13_client_hs_key_obj_id = alloc_temp_key_id();
                    if (tls13_client_hs_key_obj_id == -1) {
                        WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed");
                        return NOT_COMPILED_IN;
                    }
                }
                tls13_client_key_obj_id = tls13_client_hs_key_obj_id;
            }
            else {
                if (tls13_client_app_key_obj_id == -1) {
                    tls13_client_app_key_obj_id = alloc_temp_key_id();
                    if (tls13_client_app_key_obj_id == -1) {
                        WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed");
                        return NOT_COMPILED_IN;
                    }
                }
                tls13_client_key_obj_id = tls13_client_app_key_obj_id;
            }

            prk_kid = tls13_client_secret_obj_id;
            ret_kid = tls13_client_key_obj_id;
            ret_keytype = MXQ_KEYTYPE_AES;
            ret_isiv = 0;
        }
        else {
            /* server_handshake_key = HKDF-Expand-Label(key: server_secret,
             *                            label: "key", ctx: "")
             * server_application_key = HKDF-Expand-Label(key: server_secret,
                                            label: "key", ctx: "") */
            int tls13_server_key_obj_id = -1;
            if (is_hs_key) {
                if (tls13_server_hs_key_obj_id == -1) {
                    tls13_server_hs_key_obj_id = alloc_temp_key_id();
                    if (tls13_server_hs_key_obj_id == -1) {
                        WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed");
                        return NOT_COMPILED_IN;
                    }
                }
                tls13_server_key_obj_id = tls13_server_hs_key_obj_id;
            }
            else {
                if (tls13_server_app_key_obj_id == -1) {
                    tls13_server_app_key_obj_id = alloc_temp_key_id();
                    if (tls13_server_app_key_obj_id == -1) {
                        WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed");
                        return NOT_COMPILED_IN;
                    }
                }
                tls13_server_key_obj_id = tls13_server_app_key_obj_id;
            }

            prk_kid = tls13_server_secret_obj_id;
            ret_kid = tls13_server_key_obj_id;
            ret_keytype = MXQ_KEYTYPE_AES;
            ret_isiv = 0;
        }
    }
    else if (strstr_with_size((char *)info, ivLabel, infoSz) != NULL) {
        /* first client key then server */
        if (side == WOLFSSL_CLIENT_END) {
            /* client_handshake_iv = HKDF-Expand-Label(key: client_secret,
             *                           label: "iv", ctx: "")
             * cient_application_iv = HKDF-Expand-Label(key: client_secret,
             *                            label: "iv", ctx: "") */
            int tls13_client_iv_obj_id = -1;
            if (is_hs_key) {
                if (tls13_client_hs_key_obj_id == -1) {
                    WOLFSSL_ERROR_MSG("MAXQ: client hs key not set");
                    return NOT_COMPILED_IN;
                }
                tls13_client_iv_obj_id = tls13_client_hs_key_obj_id;
            }
            else {
                if (tls13_client_app_key_obj_id == -1) {
                    WOLFSSL_ERROR_MSG("MAXQ: client app key not set");
                    return NOT_COMPILED_IN;
                }
                tls13_client_iv_obj_id = tls13_client_app_key_obj_id;
            }

            prk_kid = tls13_client_secret_obj_id;
            ret_kid = tls13_client_iv_obj_id;
            ret_keytype = MXQ_KEYTYPE_AES;
            ret_isiv = 1;
        }
        else {
            /* server_handshake_iv = HKDF-Expand-Label(key: server_secret,
             *                           label: "iv", ctx: "")
             * server_application_iv = HKDF-Expand-Label(key: server_secret,
             * label: "iv", ctx: "") */
            int tls13_server_iv_obj_id = -1;
            if (is_hs_key) {
                if (tls13_server_hs_key_obj_id == -1) {
                    WOLFSSL_ERROR_MSG("MAXQ: server hs key not set");
                    return NOT_COMPILED_IN;
                }
                tls13_server_iv_obj_id = tls13_server_hs_key_obj_id;
            }
            else {
                if (tls13_server_app_key_obj_id == -1) {
                    WOLFSSL_ERROR_MSG("MAXQ: server app key not set");
                    return NOT_COMPILED_IN;
                }
                tls13_server_iv_obj_id = tls13_server_app_key_obj_id;
            }

            prk_kid = tls13_server_secret_obj_id;
            ret_kid = tls13_server_iv_obj_id;
            ret_keytype = MXQ_KEYTYPE_AES;
            ret_isiv = 1;
            local_is_psk = 0;
        }
    }
    else if (strstr_with_size((char *)info, finishedLabel, infoSz) != NULL) {
        if (local_is_psk) {
            if (tls13_client_finish_obj_id == -1) {
                tls13_client_finish_obj_id = alloc_temp_key_id();
                if (tls13_client_finish_obj_id == -1) {
                    WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed");
                    return NOT_COMPILED_IN;
                }
            }
            if (tls13_binder_key_obj_id == -1) {
                WOLFSSL_ERROR_MSG("MAXQ: Binder key is not created yet");
                return NOT_COMPILED_IN;
            }
            prk_kid = tls13_binder_key_obj_id;
            ret_kid = tls13_client_finish_obj_id;
            tls13_client_key_id = &tls13_binder_key_obj_id;
            ret_keytype = MXQ_KEYTYPE_HMAC;
            ret_isiv = 0;
        }
        else {
            /* first client key then server */
            if (side == WOLFSSL_CLIENT_END) {
                /* finished_key = HKDF-Expand-Label(key: client_secret,
                 * label: "finished", ctx: "") */
                if (is_hs_key) {
                    tls13_client_key_id = &tls13_client_hs_key_obj_id;
                }
                else {
                    tls13_client_key_id = &tls13_client_app_key_obj_id;
                }
                if (tls13_client_finish_obj_id == -1) {
                    tls13_client_finish_obj_id = alloc_temp_key_id();
                    if (tls13_client_finish_obj_id == -1) {
                        WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed");
                        return NOT_COMPILED_IN;
                    }
                }

                prk_kid = tls13_client_secret_obj_id;
                ret_kid = tls13_client_finish_obj_id;

                ret_keytype = MXQ_KEYTYPE_HMAC;
                ret_isiv = 0;
                free_temp_key_id(tls13_client_secret_obj_id);
                tls13_client_secret_obj_id = -1;

            }
            else {
                /* finished_key = HKDF-Expand-Label(key: server_secret,
                 *                    label: "finished", ctx: "") */
                if (is_hs_key) {
                    tls13_server_key_id = &tls13_server_hs_key_obj_id;
                }
                else {
                    tls13_server_key_id = &tls13_server_app_key_obj_id;
                }
                if (tls13_server_finish_obj_id == -1) {
                    tls13_server_finish_obj_id = alloc_temp_key_id();
                    if (tls13_server_finish_obj_id == -1) {
                        WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed");
                        return NOT_COMPILED_IN;
                    }
                }

                prk_kid = tls13_server_secret_obj_id;
                ret_kid = tls13_server_finish_obj_id;
                ret_keytype = MXQ_KEYTYPE_HMAC;
                ret_isiv = 0;
                free_temp_key_id(tls13_server_secret_obj_id);
                tls13_server_secret_obj_id = -1;

            }
        }
    }
    else if (strstr_with_size((char *)info, extBinderLabel, infoSz) != NULL) {

            /* binder_key = HKDF-Expand-Label(key: hs_early_secret,
             *                  label: "ext binder", ctx: empty_hash) */
            tls13_binder_key_obj_id = alloc_temp_key_id();
            if (tls13_binder_key_obj_id == -1) {
                WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed");
                return NOT_COMPILED_IN;
            }

            prk_kid = tls13_hs_early_secret_obj_id;
            ret_kid = tls13_binder_key_obj_id;
            ret_keytype = MXQ_KEYTYPE_IKM;
            ret_isiv = 0;
            local_is_psk = 1;

    }
    else if (strstr_with_size((char *)info, resMasterLabel, infoSz) != NULL) {
        /* TODO: */
        tls13_res_master_obj_id = alloc_temp_key_id();
        if (tls13_res_master_obj_id == -1) {
            WOLFSSL_ERROR_MSG("MAXQ: alloc_temp_key_id() failed");
            return NOT_COMPILED_IN;
        }
        prk_kid = tls13_master_secret_obj_id;
        ret_kid = tls13_res_master_obj_id;
        ret_keytype = MXQ_KEYTYPE_IKM;
        ret_isiv = 0;
        if (tls13_client_key_id != NULL) {
            free_temp_key_id(*tls13_client_key_id);
            *tls13_client_key_id = -1;
        }
    }
    else if (strstr_with_size((char *)info, appTrafUpdLabel, infoSz) != NULL) {
        if (side == WOLFSSL_CLIENT_END) {
            /* updated_client_secret = HKDF-Expand-Label(key: client_secret,
             *                             label: "traffic upd", ctx: "") */
            if (tls13_client_app_key_obj_id == -1) {
                WOLFSSL_ERROR_MSG("MAXQ: Client Application Key was not set");
                return NOT_COMPILED_IN;
            }
            prk_kid = tls13_client_secret_obj_id;
            ret_kid = tls13_client_secret_obj_id;
            ret_keytype = MXQ_KEYTYPE_IKM;
            ret_isiv = 0;
        }
        else {
            /* updated_server_secret = HKDF-Expand-Label(key: server_secret,
             *                             label: "traffic upd", ctx: "") */
            if (tls13_server_app_key_obj_id == -1) {
                WOLFSSL_ERROR_MSG("MAXQ: Server Application Key was not set");
                return NOT_COMPILED_IN;
            }
            prk_kid = tls13_server_secret_obj_id;
            ret_kid = tls13_server_secret_obj_id;
            ret_keytype = MXQ_KEYTYPE_IKM;
            ret_isiv = 0;
        }
    }
    else {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_TLS13_Expand_Secret() does not support");
        return NOT_COMPILED_IN;
    }

    if (prk_kid != -1) {
        inKeySz = 0;
    }

    if (ret_kid != -1) {
        XMEMSET(out, 0, outSz);
    }

    rc = wolfSSL_CryptHwMutexLock();
    if (rc != 0) {
        return rc;
    }

    mxq_rc = MXQ_TLS13_Expand_Secret(mxq_digest_id, (mxq_u2)ret_kid,
                                     ret_keytype, ret_isiv, out, &outSz,
                                     (mxq_u2)prk_kid, inKey, inKeySz,
                                     info, infoSz );
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_TLS13_Expand_Secret() failed");
        wolfSSL_CryptHwMutexUnLock();
        return WC_HW_E;
    }

    wolfSSL_CryptHwMutexUnLock();
    return 0;
}

static int maxq10xx_hkdf_expand_label(byte* okm, word32 okmLen,
                                      const byte* prk, word32 prkLen,
                                      const byte* protocol, word32 protocolLen,
                                      const byte* label, word32 labelLen,
                                      const byte* info, word32 infoLen,
                                      int digest, int side)
{
    int    ret = 0;
    int    idx = 0;
    byte   data[MAX_TLS13_HKDF_LABEL_SZ];

    /* Output length. */
    data[idx++] = (byte)(okmLen >> 8);
    data[idx++] = (byte)okmLen;
    /* Length of protocol | label. */
    data[idx++] = (byte)(protocolLen + labelLen);
    /* Protocol */
    XMEMCPY(&data[idx], protocol, protocolLen);
    idx += protocolLen;
    /* Label */
    XMEMCPY(&data[idx], label, labelLen);
    idx += labelLen;
    /* Length of hash of messages */
    data[idx++] = (byte)infoLen;
    /* Hash of messages */
    XMEMCPY(&data[idx], info, infoLen);
    idx += infoLen;

#ifdef WOLFSSL_CHECK_MEM_ZERO
    wc_MemZero_Add("wc_Tls13_HKDF_Expand_Label data", data, idx);
#endif

    ret = maxq10xx_HkdfExpand(digest, prk, prkLen, data, idx, okm, okmLen,
                              side);
    ForceZero(data, idx);

#ifdef WOLFSSL_CHECK_MEM_ZERO
    wc_MemZero_Check(data, MAX_TLS13_HKDF_LABEL_SZ);
#endif

    return ret;
}

static int maxq10xx_perform_tls13_record_processing(WOLFSSL* ssl,
               int is_encrypt, byte* out, const byte* in,
               word32 sz, const byte* iv, word32 ivSz,
               byte* authTag, word32 authTagSz,
               const byte* authIn, word32 authInSz)
{
    int rc;
    mxq_err_t mxq_rc;
    mxq_u2 key_id = 0xFFFF;

    if (!tls13active) {
        return NOT_COMPILED_IN;
    }

    if ((ssl->specs.bulk_cipher_algorithm != wolfssl_aes_gcm) &&
        (ssl->specs.bulk_cipher_algorithm != wolfssl_aes_ccm)) {
        WOLFSSL_MSG("MAXQ: tls record cipher algo not supported");
        return NOT_COMPILED_IN;
    }

    if (is_encrypt) {
        if (tls13_client_hs_key_obj_id != -1) {
            key_id = tls13_client_hs_key_obj_id;
        }
        else if (tls13_client_app_key_obj_id != -1) {
            key_id = tls13_client_app_key_obj_id;
        }
        else {
            WOLFSSL_ERROR_MSG("MAXQ: tls record enc key was not selected");
        }
    }
    else {
        if (tls13_server_hs_key_obj_id != -1) {
            key_id = tls13_server_hs_key_obj_id;
        }
        else if (tls13_server_app_key_obj_id != -1) {
            key_id = tls13_server_app_key_obj_id;
        }
        else {
            WOLFSSL_ERROR_MSG("MAXQ: tls record dec key was not selected");
        }
    }
    mxq_algo_id_t algo_id = 0;

    if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_gcm) {
        algo_id = ALGO_CIPHER_AES_GCM;
    }
    else if (ssl->specs.bulk_cipher_algorithm == wolfssl_aes_ccm) {
        algo_id = ALGO_CIPHER_AES_CCM;
    }

    rc = wolfSSL_CryptHwMutexLock();
    if (rc != 0) {
        return rc;
    }

    WOLFSSL_MSG("MAXQ: MXQ_TLS13_Update_IV");
    mxq_rc = MXQ_TLS13_Update_IV( key_id, (mxq_u1 *)iv, ivSz);
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: MXQ_TLS13_Update_IV() failed");
        wolfSSL_CryptHwMutexUnLock();
        return WC_HW_E;
    }

    mxq_rc = maxq10xx_cipher_do(algo_id, is_encrypt, key_id, (mxq_u1 *)in, out,
                                sz, (mxq_u1 *)iv, ivSz, (mxq_u1 *)authIn,
                                authInSz, authTag, authTagSz);
    if (mxq_rc) {
        WOLFSSL_ERROR_MSG("MAXQ: maxq10xx_cipher_do() failed");
        wolfSSL_CryptHwMutexUnLock();
        return WC_HW_E;
    }

    wolfSSL_CryptHwMutexUnLock();
    return 0;
}
#endif /* HAVE_HKDF */
#endif /* WOLFSSL_MAXQ108X */

void maxq10xx_SetupPkCallbacks(struct WOLFSSL_CTX* ctx, ProtocolVersion *pv)
{
    (void)pv;

    if (pv == NULL) {
        return;
    }

    WOLFSSL_ENTER("maxq10xx_SetupPkCallbacks");
    if (init_pk_callbacks) {
        return;
    }

#ifdef WOLFSSL_MAXQ108X
    #ifdef HAVE_HKDF
    wolfSSL_CTX_SetHKDFExtractCb(ctx, maxq10xx_hkdf_extract);
    wolfSSL_CTX_SetHKDFExpandLabelCb(ctx, maxq10xx_hkdf_expand_label);
    #endif

    if ((pv->major == SSLv3_MAJOR) && (pv->minor == WOLFSSL_TLSV1_3)) {
        tls13active = 1;
        wolfSSL_CTX_SetEccKeyGenCb(ctx, maxq10xx_ecc_key_gen);
        wolfSSL_CTX_SetEccSharedSecretCb(ctx, maxq10xx_tls13_ecc_shared_secret);
        wolfSSL_CTX_SetEccVerifyCb(ctx, maxq10xx_ecc_verify);
        wolfSSL_CTX_SetDhGenerateKeyPair(ctx, maxq10xx_dh_gen_key_pair);
        wolfSSL_CTX_SetDhAgreeCb(ctx, maxq10xx_dh_agree);
        wolfSSL_CTX_SetRsaPssSignCb(ctx, maxq10xx_rsa_pss_sign);
        wolfSSL_CTX_SetRsaPssSignCheckCb(ctx, maxq10xx_skip_sign_check);
        wolfSSL_CTX_SetRsaPssVerifyCb(ctx, maxq10xx_rsa_pss_verify);

        wolfSSL_CTX_SetPerformTlsRecordProcessingCb(ctx,
            maxq10xx_perform_tls13_record_processing);
    }
    else
#endif /* WOLFSSL_MAXQ108X */
    {
        wolfSSL_CTX_SetEccSharedSecretCb(ctx, maxq10xx_tls12_ecc_shared_secret);
        wolfSSL_CTX_SetPerformTlsRecordProcessingCb(ctx,
            maxq10xx_perform_tls12_record_processing);
    }

    wolfSSL_CTX_SetProcessPeerCertCb(ctx, maxq10xx_process_server_certificate);
    wolfSSL_CTX_SetProcessServerSigKexCb(ctx, maxq10xx_process_server_sig_kex);
    wolfSSL_CTX_SetGenMasterSecretCb(ctx, maxq10xx_gen_tls_master_secret);
    wolfSSL_CTX_SetTlsFinishedCb(ctx, maxq10xx_perform_client_finished);

    wolfSSL_CTX_SetEccSignCb(ctx, maxq10xx_ecc_sign);

    init_pk_callbacks = 1;
}

#endif /* WOLFSSL_MAXQ1065 || WOLFSSL_MAXQ108X */