summaryrefslogtreecommitdiffstats
path: root/extra/wolfssl/wolfssl/wolfcrypt/src/asn.c
blob: 3e00b1338e6feaffc5494b57e7ddd1179c6ac2a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
23392
23393
23394
23395
23396
23397
23398
23399
23400
23401
23402
23403
23404
23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426
23427
23428
23429
23430
23431
23432
23433
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471
23472
23473
23474
23475
23476
23477
23478
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489
23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514
23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543
23544
23545
23546
23547
23548
23549
23550
23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565
23566
23567
23568
23569
23570
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
23586
23587
23588
23589
23590
23591
23592
23593
23594
23595
23596
23597
23598
23599
23600
23601
23602
23603
23604
23605
23606
23607
23608
23609
23610
23611
23612
23613
23614
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626
23627
23628
23629
23630
23631
23632
23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649
23650
23651
23652
23653
23654
23655
23656
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669
23670
23671
23672
23673
23674
23675
23676
23677
23678
23679
23680
23681
23682
23683
23684
23685
23686
23687
23688
23689
23690
23691
23692
23693
23694
23695
23696
23697
23698
23699
23700
23701
23702
23703
23704
23705
23706
23707
23708
23709
23710
23711
23712
23713
23714
23715
23716
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750
23751
23752
23753
23754
23755
23756
23757
23758
23759
23760
23761
23762
23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773
23774
23775
23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788
23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801
23802
23803
23804
23805
23806
23807
23808
23809
23810
23811
23812
23813
23814
23815
23816
23817
23818
23819
23820
23821
23822
23823
23824
23825
23826
23827
23828
23829
23830
23831
23832
23833
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844
23845
23846
23847
23848
23849
23850
23851
23852
23853
23854
23855
23856
23857
23858
23859
23860
23861
23862
23863
23864
23865
23866
23867
23868
23869
23870
23871
23872
23873
23874
23875
23876
23877
23878
23879
23880
23881
23882
23883
23884
23885
23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902
23903
23904
23905
23906
23907
23908
23909
23910
23911
23912
23913
23914
23915
23916
23917
23918
23919
23920
23921
23922
23923
23924
23925
23926
23927
23928
23929
23930
23931
23932
23933
23934
23935
23936
23937
23938
23939
23940
23941
23942
23943
23944
23945
23946
23947
23948
23949
23950
23951
23952
23953
23954
23955
23956
23957
23958
23959
23960
23961
23962
23963
23964
23965
23966
23967
23968
23969
23970
23971
23972
23973
23974
23975
23976
23977
23978
23979
23980
23981
23982
23983
23984
23985
23986
23987
23988
23989
23990
23991
23992
23993
23994
23995
23996
23997
23998
23999
24000
24001
24002
24003
24004
24005
24006
24007
24008
24009
24010
24011
24012
24013
24014
24015
24016
24017
24018
24019
24020
24021
24022
24023
24024
24025
24026
24027
24028
24029
24030
24031
24032
24033
24034
24035
24036
24037
24038
24039
24040
24041
24042
24043
24044
24045
24046
24047
24048
24049
24050
24051
24052
24053
24054
24055
24056
24057
24058
24059
24060
24061
24062
24063
24064
24065
24066
24067
24068
24069
24070
24071
24072
24073
24074
24075
24076
24077
24078
24079
24080
24081
24082
24083
24084
24085
24086
24087
24088
24089
24090
24091
24092
24093
24094
24095
24096
24097
24098
24099
24100
24101
24102
24103
24104
24105
24106
24107
24108
24109
24110
24111
24112
24113
24114
24115
24116
24117
24118
24119
24120
24121
24122
24123
24124
24125
24126
24127
24128
24129
24130
24131
24132
24133
24134
24135
24136
24137
24138
24139
24140
24141
24142
24143
24144
24145
24146
24147
24148
24149
24150
24151
24152
24153
24154
24155
24156
24157
24158
24159
24160
24161
24162
24163
24164
24165
24166
24167
24168
24169
24170
24171
24172
24173
24174
24175
24176
24177
24178
24179
24180
24181
24182
24183
24184
24185
24186
24187
24188
24189
24190
24191
24192
24193
24194
24195
24196
24197
24198
24199
24200
24201
24202
24203
24204
24205
24206
24207
24208
24209
24210
24211
24212
24213
24214
24215
24216
24217
24218
24219
24220
24221
24222
24223
24224
24225
24226
24227
24228
24229
24230
24231
24232
24233
24234
24235
24236
24237
24238
24239
24240
24241
24242
24243
24244
24245
24246
24247
24248
24249
24250
24251
24252
24253
24254
24255
24256
24257
24258
24259
24260
24261
24262
24263
24264
24265
24266
24267
24268
24269
24270
24271
24272
24273
24274
24275
24276
24277
24278
24279
24280
24281
24282
24283
24284
24285
24286
24287
24288
24289
24290
24291
24292
24293
24294
24295
24296
24297
24298
24299
24300
24301
24302
24303
24304
24305
24306
24307
24308
24309
24310
24311
24312
24313
24314
24315
24316
24317
24318
24319
24320
24321
24322
24323
24324
24325
24326
24327
24328
24329
24330
24331
24332
24333
24334
24335
24336
24337
24338
24339
24340
24341
24342
24343
24344
24345
24346
24347
24348
24349
24350
24351
24352
24353
24354
24355
24356
24357
24358
24359
24360
24361
24362
24363
24364
24365
24366
24367
24368
24369
24370
24371
24372
24373
24374
24375
24376
24377
24378
24379
24380
24381
24382
24383
24384
24385
24386
24387
24388
24389
24390
24391
24392
24393
24394
24395
24396
24397
24398
24399
24400
24401
24402
24403
24404
24405
24406
24407
24408
24409
24410
24411
24412
24413
24414
24415
24416
24417
24418
24419
24420
24421
24422
24423
24424
24425
24426
24427
24428
24429
24430
24431
24432
24433
24434
24435
24436
24437
24438
24439
24440
24441
24442
24443
24444
24445
24446
24447
24448
24449
24450
24451
24452
24453
24454
24455
24456
24457
24458
24459
24460
24461
24462
24463
24464
24465
24466
24467
24468
24469
24470
24471
24472
24473
24474
24475
24476
24477
24478
24479
24480
24481
24482
24483
24484
24485
24486
24487
24488
24489
24490
24491
24492
24493
24494
24495
24496
24497
24498
24499
24500
24501
24502
24503
24504
24505
24506
24507
24508
24509
24510
24511
24512
24513
24514
24515
24516
24517
24518
24519
24520
24521
24522
24523
24524
24525
24526
24527
24528
24529
24530
24531
24532
24533
24534
24535
24536
24537
24538
24539
24540
24541
24542
24543
24544
24545
24546
24547
24548
24549
24550
24551
24552
24553
24554
24555
24556
24557
24558
24559
24560
24561
24562
24563
24564
24565
24566
24567
24568
24569
24570
24571
24572
24573
24574
24575
24576
24577
24578
24579
24580
24581
24582
24583
24584
24585
24586
24587
24588
24589
24590
24591
24592
24593
24594
24595
24596
24597
24598
24599
24600
24601
24602
24603
24604
24605
24606
24607
24608
24609
24610
24611
24612
24613
24614
24615
24616
24617
24618
24619
24620
24621
24622
24623
24624
24625
24626
24627
24628
24629
24630
24631
24632
24633
24634
24635
24636
24637
24638
24639
24640
24641
24642
24643
24644
24645
24646
24647
24648
24649
24650
24651
24652
24653
24654
24655
24656
24657
24658
24659
24660
24661
24662
24663
24664
24665
24666
24667
24668
24669
24670
24671
24672
24673
24674
24675
24676
24677
24678
24679
24680
24681
24682
24683
24684
24685
24686
24687
24688
24689
24690
24691
24692
24693
24694
24695
24696
24697
24698
24699
24700
24701
24702
24703
24704
24705
24706
24707
24708
24709
24710
24711
24712
24713
24714
24715
24716
24717
24718
24719
24720
24721
24722
24723
24724
24725
24726
24727
24728
24729
24730
24731
24732
24733
24734
24735
24736
24737
24738
24739
24740
24741
24742
24743
24744
24745
24746
24747
24748
24749
24750
24751
24752
24753
24754
24755
24756
24757
24758
24759
24760
24761
24762
24763
24764
24765
24766
24767
24768
24769
24770
24771
24772
24773
24774
24775
24776
24777
24778
24779
24780
24781
24782
24783
24784
24785
24786
24787
24788
24789
24790
24791
24792
24793
24794
24795
24796
24797
24798
24799
24800
24801
24802
24803
24804
24805
24806
24807
24808
24809
24810
24811
24812
24813
24814
24815
24816
24817
24818
24819
24820
24821
24822
24823
24824
24825
24826
24827
24828
24829
24830
24831
24832
24833
24834
24835
24836
24837
24838
24839
24840
24841
24842
24843
24844
24845
24846
24847
24848
24849
24850
24851
24852
24853
24854
24855
24856
24857
24858
24859
24860
24861
24862
24863
24864
24865
24866
24867
24868
24869
24870
24871
24872
24873
24874
24875
24876
24877
24878
24879
24880
24881
24882
24883
24884
24885
24886
24887
24888
24889
24890
24891
24892
24893
24894
24895
24896
24897
24898
24899
24900
24901
24902
24903
24904
24905
24906
24907
24908
24909
24910
24911
24912
24913
24914
24915
24916
24917
24918
24919
24920
24921
24922
24923
24924
24925
24926
24927
24928
24929
24930
24931
24932
24933
24934
24935
24936
24937
24938
24939
24940
24941
24942
24943
24944
24945
24946
24947
24948
24949
24950
24951
24952
24953
24954
24955
24956
24957
24958
24959
24960
24961
24962
24963
24964
24965
24966
24967
24968
24969
24970
24971
24972
24973
24974
24975
24976
24977
24978
24979
24980
24981
24982
24983
24984
24985
24986
24987
24988
24989
24990
24991
24992
24993
24994
24995
24996
24997
24998
24999
25000
25001
25002
25003
25004
25005
25006
25007
25008
25009
25010
25011
25012
25013
25014
25015
25016
25017
25018
25019
25020
25021
25022
25023
25024
25025
25026
25027
25028
25029
25030
25031
25032
25033
25034
25035
25036
25037
25038
25039
25040
25041
25042
25043
25044
25045
25046
25047
25048
25049
25050
25051
25052
25053
25054
25055
25056
25057
25058
25059
25060
25061
25062
25063
25064
25065
25066
25067
25068
25069
25070
25071
25072
25073
25074
25075
25076
25077
25078
25079
25080
25081
25082
25083
25084
25085
25086
25087
25088
25089
25090
25091
25092
25093
25094
25095
25096
25097
25098
25099
25100
25101
25102
25103
25104
25105
25106
25107
25108
25109
25110
25111
25112
25113
25114
25115
25116
25117
25118
25119
25120
25121
25122
25123
25124
25125
25126
25127
25128
25129
25130
25131
25132
25133
25134
25135
25136
25137
25138
25139
25140
25141
25142
25143
25144
25145
25146
25147
25148
25149
25150
25151
25152
25153
25154
25155
25156
25157
25158
25159
25160
25161
25162
25163
25164
25165
25166
25167
25168
25169
25170
25171
25172
25173
25174
25175
25176
25177
25178
25179
25180
25181
25182
25183
25184
25185
25186
25187
25188
25189
25190
25191
25192
25193
25194
25195
25196
25197
25198
25199
25200
25201
25202
25203
25204
25205
25206
25207
25208
25209
25210
25211
25212
25213
25214
25215
25216
25217
25218
25219
25220
25221
25222
25223
25224
25225
25226
25227
25228
25229
25230
25231
25232
25233
25234
25235
25236
25237
25238
25239
25240
25241
25242
25243
25244
25245
25246
25247
25248
25249
25250
25251
25252
25253
25254
25255
25256
25257
25258
25259
25260
25261
25262
25263
25264
25265
25266
25267
25268
25269
25270
25271
25272
25273
25274
25275
25276
25277
25278
25279
25280
25281
25282
25283
25284
25285
25286
25287
25288
25289
25290
25291
25292
25293
25294
25295
25296
25297
25298
25299
25300
25301
25302
25303
25304
25305
25306
25307
25308
25309
25310
25311
25312
25313
25314
25315
25316
25317
25318
25319
25320
25321
25322
25323
25324
25325
25326
25327
25328
25329
25330
25331
25332
25333
25334
25335
25336
25337
25338
25339
25340
25341
25342
25343
25344
25345
25346
25347
25348
25349
25350
25351
25352
25353
25354
25355
25356
25357
25358
25359
25360
25361
25362
25363
25364
25365
25366
25367
25368
25369
25370
25371
25372
25373
25374
25375
25376
25377
25378
25379
25380
25381
25382
25383
25384
25385
25386
25387
25388
25389
25390
25391
25392
25393
25394
25395
25396
25397
25398
25399
25400
25401
25402
25403
25404
25405
25406
25407
25408
25409
25410
25411
25412
25413
25414
25415
25416
25417
25418
25419
25420
25421
25422
25423
25424
25425
25426
25427
25428
25429
25430
25431
25432
25433
25434
25435
25436
25437
25438
25439
25440
25441
25442
25443
25444
25445
25446
25447
25448
25449
25450
25451
25452
25453
25454
25455
25456
25457
25458
25459
25460
25461
25462
25463
25464
25465
25466
25467
25468
25469
25470
25471
25472
25473
25474
25475
25476
25477
25478
25479
25480
25481
25482
25483
25484
25485
25486
25487
25488
25489
25490
25491
25492
25493
25494
25495
25496
25497
25498
25499
25500
25501
25502
25503
25504
25505
25506
25507
25508
25509
25510
25511
25512
25513
25514
25515
25516
25517
25518
25519
25520
25521
25522
25523
25524
25525
25526
25527
25528
25529
25530
25531
25532
25533
25534
25535
25536
25537
25538
25539
25540
25541
25542
25543
25544
25545
25546
25547
25548
25549
25550
25551
25552
25553
25554
25555
25556
25557
25558
25559
25560
25561
25562
25563
25564
25565
25566
25567
25568
25569
25570
25571
25572
25573
25574
25575
25576
25577
25578
25579
25580
25581
25582
25583
25584
25585
25586
25587
25588
25589
25590
25591
25592
25593
25594
25595
25596
25597
25598
25599
25600
25601
25602
25603
25604
25605
25606
25607
25608
25609
25610
25611
25612
25613
25614
25615
25616
25617
25618
25619
25620
25621
25622
25623
25624
25625
25626
25627
25628
25629
25630
25631
25632
25633
25634
25635
25636
25637
25638
25639
25640
25641
25642
25643
25644
25645
25646
25647
25648
25649
25650
25651
25652
25653
25654
25655
25656
25657
25658
25659
25660
25661
25662
25663
25664
25665
25666
25667
25668
25669
25670
25671
25672
25673
25674
25675
25676
25677
25678
25679
25680
25681
25682
25683
25684
25685
25686
25687
25688
25689
25690
25691
25692
25693
25694
25695
25696
25697
25698
25699
25700
25701
25702
25703
25704
25705
25706
25707
25708
25709
25710
25711
25712
25713
25714
25715
25716
25717
25718
25719
25720
25721
25722
25723
25724
25725
25726
25727
25728
25729
25730
25731
25732
25733
25734
25735
25736
25737
25738
25739
25740
25741
25742
25743
25744
25745
25746
25747
25748
25749
25750
25751
25752
25753
25754
25755
25756
25757
25758
25759
25760
25761
25762
25763
25764
25765
25766
25767
25768
25769
25770
25771
25772
25773
25774
25775
25776
25777
25778
25779
25780
25781
25782
25783
25784
25785
25786
25787
25788
25789
25790
25791
25792
25793
25794
25795
25796
25797
25798
25799
25800
25801
25802
25803
25804
25805
25806
25807
25808
25809
25810
25811
25812
25813
25814
25815
25816
25817
25818
25819
25820
25821
25822
25823
25824
25825
25826
25827
25828
25829
25830
25831
25832
25833
25834
25835
25836
25837
25838
25839
25840
25841
25842
25843
25844
25845
25846
25847
25848
25849
25850
25851
25852
25853
25854
25855
25856
25857
25858
25859
25860
25861
25862
25863
25864
25865
25866
25867
25868
25869
25870
25871
25872
25873
25874
25875
25876
25877
25878
25879
25880
25881
25882
25883
25884
25885
25886
25887
25888
25889
25890
25891
25892
25893
25894
25895
25896
25897
25898
25899
25900
25901
25902
25903
25904
25905
25906
25907
25908
25909
25910
25911
25912
25913
25914
25915
25916
25917
25918
25919
25920
25921
25922
25923
25924
25925
25926
25927
25928
25929
25930
25931
25932
25933
25934
25935
25936
25937
25938
25939
25940
25941
25942
25943
25944
25945
25946
25947
25948
25949
25950
25951
25952
25953
25954
25955
25956
25957
25958
25959
25960
25961
25962
25963
25964
25965
25966
25967
25968
25969
25970
25971
25972
25973
25974
25975
25976
25977
25978
25979
25980
25981
25982
25983
25984
25985
25986
25987
25988
25989
25990
25991
25992
25993
25994
25995
25996
25997
25998
25999
26000
26001
26002
26003
26004
26005
26006
26007
26008
26009
26010
26011
26012
26013
26014
26015
26016
26017
26018
26019
26020
26021
26022
26023
26024
26025
26026
26027
26028
26029
26030
26031
26032
26033
26034
26035
26036
26037
26038
26039
26040
26041
26042
26043
26044
26045
26046
26047
26048
26049
26050
26051
26052
26053
26054
26055
26056
26057
26058
26059
26060
26061
26062
26063
26064
26065
26066
26067
26068
26069
26070
26071
26072
26073
26074
26075
26076
26077
26078
26079
26080
26081
26082
26083
26084
26085
26086
26087
26088
26089
26090
26091
26092
26093
26094
26095
26096
26097
26098
26099
26100
26101
26102
26103
26104
26105
26106
26107
26108
26109
26110
26111
26112
26113
26114
26115
26116
26117
26118
26119
26120
26121
26122
26123
26124
26125
26126
26127
26128
26129
26130
26131
26132
26133
26134
26135
26136
26137
26138
26139
26140
26141
26142
26143
26144
26145
26146
26147
26148
26149
26150
26151
26152
26153
26154
26155
26156
26157
26158
26159
26160
26161
26162
26163
26164
26165
26166
26167
26168
26169
26170
26171
26172
26173
26174
26175
26176
26177
26178
26179
26180
26181
26182
26183
26184
26185
26186
26187
26188
26189
26190
26191
26192
26193
26194
26195
26196
26197
26198
26199
26200
26201
26202
26203
26204
26205
26206
26207
26208
26209
26210
26211
26212
26213
26214
26215
26216
26217
26218
26219
26220
26221
26222
26223
26224
26225
26226
26227
26228
26229
26230
26231
26232
26233
26234
26235
26236
26237
26238
26239
26240
26241
26242
26243
26244
26245
26246
26247
26248
26249
26250
26251
26252
26253
26254
26255
26256
26257
26258
26259
26260
26261
26262
26263
26264
26265
26266
26267
26268
26269
26270
26271
26272
26273
26274
26275
26276
26277
26278
26279
26280
26281
26282
26283
26284
26285
26286
26287
26288
26289
26290
26291
26292
26293
26294
26295
26296
26297
26298
26299
26300
26301
26302
26303
26304
26305
26306
26307
26308
26309
26310
26311
26312
26313
26314
26315
26316
26317
26318
26319
26320
26321
26322
26323
26324
26325
26326
26327
26328
26329
26330
26331
26332
26333
26334
26335
26336
26337
26338
26339
26340
26341
26342
26343
26344
26345
26346
26347
26348
26349
26350
26351
26352
26353
26354
26355
26356
26357
26358
26359
26360
26361
26362
26363
26364
26365
26366
26367
26368
26369
26370
26371
26372
26373
26374
26375
26376
26377
26378
26379
26380
26381
26382
26383
26384
26385
26386
26387
26388
26389
26390
26391
26392
26393
26394
26395
26396
26397
26398
26399
26400
26401
26402
26403
26404
26405
26406
26407
26408
26409
26410
26411
26412
26413
26414
26415
26416
26417
26418
26419
26420
26421
26422
26423
26424
26425
26426
26427
26428
26429
26430
26431
26432
26433
26434
26435
26436
26437
26438
26439
26440
26441
26442
26443
26444
26445
26446
26447
26448
26449
26450
26451
26452
26453
26454
26455
26456
26457
26458
26459
26460
26461
26462
26463
26464
26465
26466
26467
26468
26469
26470
26471
26472
26473
26474
26475
26476
26477
26478
26479
26480
26481
26482
26483
26484
26485
26486
26487
26488
26489
26490
26491
26492
26493
26494
26495
26496
26497
26498
26499
26500
26501
26502
26503
26504
26505
26506
26507
26508
26509
26510
26511
26512
26513
26514
26515
26516
26517
26518
26519
26520
26521
26522
26523
26524
26525
26526
26527
26528
26529
26530
26531
26532
26533
26534
26535
26536
26537
26538
26539
26540
26541
26542
26543
26544
26545
26546
26547
26548
26549
26550
26551
26552
26553
26554
26555
26556
26557
26558
26559
26560
26561
26562
26563
26564
26565
26566
26567
26568
26569
26570
26571
26572
26573
26574
26575
26576
26577
26578
26579
26580
26581
26582
26583
26584
26585
26586
26587
26588
26589
26590
26591
26592
26593
26594
26595
26596
26597
26598
26599
26600
26601
26602
26603
26604
26605
26606
26607
26608
26609
26610
26611
26612
26613
26614
26615
26616
26617
26618
26619
26620
26621
26622
26623
26624
26625
26626
26627
26628
26629
26630
26631
26632
26633
26634
26635
26636
26637
26638
26639
26640
26641
26642
26643
26644
26645
26646
26647
26648
26649
26650
26651
26652
26653
26654
26655
26656
26657
26658
26659
26660
26661
26662
26663
26664
26665
26666
26667
26668
26669
26670
26671
26672
26673
26674
26675
26676
26677
26678
26679
26680
26681
26682
26683
26684
26685
26686
26687
26688
26689
26690
26691
26692
26693
26694
26695
26696
26697
26698
26699
26700
26701
26702
26703
26704
26705
26706
26707
26708
26709
26710
26711
26712
26713
26714
26715
26716
26717
26718
26719
26720
26721
26722
26723
26724
26725
26726
26727
26728
26729
26730
26731
26732
26733
26734
26735
26736
26737
26738
26739
26740
26741
26742
26743
26744
26745
26746
26747
26748
26749
26750
26751
26752
26753
26754
26755
26756
26757
26758
26759
26760
26761
26762
26763
26764
26765
26766
26767
26768
26769
26770
26771
26772
26773
26774
26775
26776
26777
26778
26779
26780
26781
26782
26783
26784
26785
26786
26787
26788
26789
26790
26791
26792
26793
26794
26795
26796
26797
26798
26799
26800
26801
26802
26803
26804
26805
26806
26807
26808
26809
26810
26811
26812
26813
26814
26815
26816
26817
26818
26819
26820
26821
26822
26823
26824
26825
26826
26827
26828
26829
26830
26831
26832
26833
26834
26835
26836
26837
26838
26839
26840
26841
26842
26843
26844
26845
26846
26847
26848
26849
26850
26851
26852
26853
26854
26855
26856
26857
26858
26859
26860
26861
26862
26863
26864
26865
26866
26867
26868
26869
26870
26871
26872
26873
26874
26875
26876
26877
26878
26879
26880
26881
26882
26883
26884
26885
26886
26887
26888
26889
26890
26891
26892
26893
26894
26895
26896
26897
26898
26899
26900
26901
26902
26903
26904
26905
26906
26907
26908
26909
26910
26911
26912
26913
26914
26915
26916
26917
26918
26919
26920
26921
26922
26923
26924
26925
26926
26927
26928
26929
26930
26931
26932
26933
26934
26935
26936
26937
26938
26939
26940
26941
26942
26943
26944
26945
26946
26947
26948
26949
26950
26951
26952
26953
26954
26955
26956
26957
26958
26959
26960
26961
26962
26963
26964
26965
26966
26967
26968
26969
26970
26971
26972
26973
26974
26975
26976
26977
26978
26979
26980
26981
26982
26983
26984
26985
26986
26987
26988
26989
26990
26991
26992
26993
26994
26995
26996
26997
26998
26999
27000
27001
27002
27003
27004
27005
27006
27007
27008
27009
27010
27011
27012
27013
27014
27015
27016
27017
27018
27019
27020
27021
27022
27023
27024
27025
27026
27027
27028
27029
27030
27031
27032
27033
27034
27035
27036
27037
27038
27039
27040
27041
27042
27043
27044
27045
27046
27047
27048
27049
27050
27051
27052
27053
27054
27055
27056
27057
27058
27059
27060
27061
27062
27063
27064
27065
27066
27067
27068
27069
27070
27071
27072
27073
27074
27075
27076
27077
27078
27079
27080
27081
27082
27083
27084
27085
27086
27087
27088
27089
27090
27091
27092
27093
27094
27095
27096
27097
27098
27099
27100
27101
27102
27103
27104
27105
27106
27107
27108
27109
27110
27111
27112
27113
27114
27115
27116
27117
27118
27119
27120
27121
27122
27123
27124
27125
27126
27127
27128
27129
27130
27131
27132
27133
27134
27135
27136
27137
27138
27139
27140
27141
27142
27143
27144
27145
27146
27147
27148
27149
27150
27151
27152
27153
27154
27155
27156
27157
27158
27159
27160
27161
27162
27163
27164
27165
27166
27167
27168
27169
27170
27171
27172
27173
27174
27175
27176
27177
27178
27179
27180
27181
27182
27183
27184
27185
27186
27187
27188
27189
27190
27191
27192
27193
27194
27195
27196
27197
27198
27199
27200
27201
27202
27203
27204
27205
27206
27207
27208
27209
27210
27211
27212
27213
27214
27215
27216
27217
27218
27219
27220
27221
27222
27223
27224
27225
27226
27227
27228
27229
27230
27231
27232
27233
27234
27235
27236
27237
27238
27239
27240
27241
27242
27243
27244
27245
27246
27247
27248
27249
27250
27251
27252
27253
27254
27255
27256
27257
27258
27259
27260
27261
27262
27263
27264
27265
27266
27267
27268
27269
27270
27271
27272
27273
27274
27275
27276
27277
27278
27279
27280
27281
27282
27283
27284
27285
27286
27287
27288
27289
27290
27291
27292
27293
27294
27295
27296
27297
27298
27299
27300
27301
27302
27303
27304
27305
27306
27307
27308
27309
27310
27311
27312
27313
27314
27315
27316
27317
27318
27319
27320
27321
27322
27323
27324
27325
27326
27327
27328
27329
27330
27331
27332
27333
27334
27335
27336
27337
27338
27339
27340
27341
27342
27343
27344
27345
27346
27347
27348
27349
27350
27351
27352
27353
27354
27355
27356
27357
27358
27359
27360
27361
27362
27363
27364
27365
27366
27367
27368
27369
27370
27371
27372
27373
27374
27375
27376
27377
27378
27379
27380
27381
27382
27383
27384
27385
27386
27387
27388
27389
27390
27391
27392
27393
27394
27395
27396
27397
27398
27399
27400
27401
27402
27403
27404
27405
27406
27407
27408
27409
27410
27411
27412
27413
27414
27415
27416
27417
27418
27419
27420
27421
27422
27423
27424
27425
27426
27427
27428
27429
27430
27431
27432
27433
27434
27435
27436
27437
27438
27439
27440
27441
27442
27443
27444
27445
27446
27447
27448
27449
27450
27451
27452
27453
27454
27455
27456
27457
27458
27459
27460
27461
27462
27463
27464
27465
27466
27467
27468
27469
27470
27471
27472
27473
27474
27475
27476
27477
27478
27479
27480
27481
27482
27483
27484
27485
27486
27487
27488
27489
27490
27491
27492
27493
27494
27495
27496
27497
27498
27499
27500
27501
27502
27503
27504
27505
27506
27507
27508
27509
27510
27511
27512
27513
27514
27515
27516
27517
27518
27519
27520
27521
27522
27523
27524
27525
27526
27527
27528
27529
27530
27531
27532
27533
27534
27535
27536
27537
27538
27539
27540
27541
27542
27543
27544
27545
27546
27547
27548
27549
27550
27551
27552
27553
27554
27555
27556
27557
27558
27559
27560
27561
27562
27563
27564
27565
27566
27567
27568
27569
27570
27571
27572
27573
27574
27575
27576
27577
27578
27579
27580
27581
27582
27583
27584
27585
27586
27587
27588
27589
27590
27591
27592
27593
27594
27595
27596
27597
27598
27599
27600
27601
27602
27603
27604
27605
27606
27607
27608
27609
27610
27611
27612
27613
27614
27615
27616
27617
27618
27619
27620
27621
27622
27623
27624
27625
27626
27627
27628
27629
27630
27631
27632
27633
27634
27635
27636
27637
27638
27639
27640
27641
27642
27643
27644
27645
27646
27647
27648
27649
27650
27651
27652
27653
27654
27655
27656
27657
27658
27659
27660
27661
27662
27663
27664
27665
27666
27667
27668
27669
27670
27671
27672
27673
27674
27675
27676
27677
27678
27679
27680
27681
27682
27683
27684
27685
27686
27687
27688
27689
27690
27691
27692
27693
27694
27695
27696
27697
27698
27699
27700
27701
27702
27703
27704
27705
27706
27707
27708
27709
27710
27711
27712
27713
27714
27715
27716
27717
27718
27719
27720
27721
27722
27723
27724
27725
27726
27727
27728
27729
27730
27731
27732
27733
27734
27735
27736
27737
27738
27739
27740
27741
27742
27743
27744
27745
27746
27747
27748
27749
27750
27751
27752
27753
27754
27755
27756
27757
27758
27759
27760
27761
27762
27763
27764
27765
27766
27767
27768
27769
27770
27771
27772
27773
27774
27775
27776
27777
27778
27779
27780
27781
27782
27783
27784
27785
27786
27787
27788
27789
27790
27791
27792
27793
27794
27795
27796
27797
27798
27799
27800
27801
27802
27803
27804
27805
27806
27807
27808
27809
27810
27811
27812
27813
27814
27815
27816
27817
27818
27819
27820
27821
27822
27823
27824
27825
27826
27827
27828
27829
27830
27831
27832
27833
27834
27835
27836
27837
27838
27839
27840
27841
27842
27843
27844
27845
27846
27847
27848
27849
27850
27851
27852
27853
27854
27855
27856
27857
27858
27859
27860
27861
27862
27863
27864
27865
27866
27867
27868
27869
27870
27871
27872
27873
27874
27875
27876
27877
27878
27879
27880
27881
27882
27883
27884
27885
27886
27887
27888
27889
27890
27891
27892
27893
27894
27895
27896
27897
27898
27899
27900
27901
27902
27903
27904
27905
27906
27907
27908
27909
27910
27911
27912
27913
27914
27915
27916
27917
27918
27919
27920
27921
27922
27923
27924
27925
27926
27927
27928
27929
27930
27931
27932
27933
27934
27935
27936
27937
27938
27939
27940
27941
27942
27943
27944
27945
27946
27947
27948
27949
27950
27951
27952
27953
27954
27955
27956
27957
27958
27959
27960
27961
27962
27963
27964
27965
27966
27967
27968
27969
27970
27971
27972
27973
27974
27975
27976
27977
27978
27979
27980
27981
27982
27983
27984
27985
27986
27987
27988
27989
27990
27991
27992
27993
27994
27995
27996
27997
27998
27999
28000
28001
28002
28003
28004
28005
28006
28007
28008
28009
28010
28011
28012
28013
28014
28015
28016
28017
28018
28019
28020
28021
28022
28023
28024
28025
28026
28027
28028
28029
28030
28031
28032
28033
28034
28035
28036
28037
28038
28039
28040
28041
28042
28043
28044
28045
28046
28047
28048
28049
28050
28051
28052
28053
28054
28055
28056
28057
28058
28059
28060
28061
28062
28063
28064
28065
28066
28067
28068
28069
28070
28071
28072
28073
28074
28075
28076
28077
28078
28079
28080
28081
28082
28083
28084
28085
28086
28087
28088
28089
28090
28091
28092
28093
28094
28095
28096
28097
28098
28099
28100
28101
28102
28103
28104
28105
28106
28107
28108
28109
28110
28111
28112
28113
28114
28115
28116
28117
28118
28119
28120
28121
28122
28123
28124
28125
28126
28127
28128
28129
28130
28131
28132
28133
28134
28135
28136
28137
28138
28139
28140
28141
28142
28143
28144
28145
28146
28147
28148
28149
28150
28151
28152
28153
28154
28155
28156
28157
28158
28159
28160
28161
28162
28163
28164
28165
28166
28167
28168
28169
28170
28171
28172
28173
28174
28175
28176
28177
28178
28179
28180
28181
28182
28183
28184
28185
28186
28187
28188
28189
28190
28191
28192
28193
28194
28195
28196
28197
28198
28199
28200
28201
28202
28203
28204
28205
28206
28207
28208
28209
28210
28211
28212
28213
28214
28215
28216
28217
28218
28219
28220
28221
28222
28223
28224
28225
28226
28227
28228
28229
28230
28231
28232
28233
28234
28235
28236
28237
28238
28239
28240
28241
28242
28243
28244
28245
28246
28247
28248
28249
28250
28251
28252
28253
28254
28255
28256
28257
28258
28259
28260
28261
28262
28263
28264
28265
28266
28267
28268
28269
28270
28271
28272
28273
28274
28275
28276
28277
28278
28279
28280
28281
28282
28283
28284
28285
28286
28287
28288
28289
28290
28291
28292
28293
28294
28295
28296
28297
28298
28299
28300
28301
28302
28303
28304
28305
28306
28307
28308
28309
28310
28311
28312
28313
28314
28315
28316
28317
28318
28319
28320
28321
28322
28323
28324
28325
28326
28327
28328
28329
28330
28331
28332
28333
28334
28335
28336
28337
28338
28339
28340
28341
28342
28343
28344
28345
28346
28347
28348
28349
28350
28351
28352
28353
28354
28355
28356
28357
28358
28359
28360
28361
28362
28363
28364
28365
28366
28367
28368
28369
28370
28371
28372
28373
28374
28375
28376
28377
28378
28379
28380
28381
28382
28383
28384
28385
28386
28387
28388
28389
28390
28391
28392
28393
28394
28395
28396
28397
28398
28399
28400
28401
28402
28403
28404
28405
28406
28407
28408
28409
28410
28411
28412
28413
28414
28415
28416
28417
28418
28419
28420
28421
28422
28423
28424
28425
28426
28427
28428
28429
28430
28431
28432
28433
28434
28435
28436
28437
28438
28439
28440
28441
28442
28443
28444
28445
28446
28447
28448
28449
28450
28451
28452
28453
28454
28455
28456
28457
28458
28459
28460
28461
28462
28463
28464
28465
28466
28467
28468
28469
28470
28471
28472
28473
28474
28475
28476
28477
28478
28479
28480
28481
28482
28483
28484
28485
28486
28487
28488
28489
28490
28491
28492
28493
28494
28495
28496
28497
28498
28499
28500
28501
28502
28503
28504
28505
28506
28507
28508
28509
28510
28511
28512
28513
28514
28515
28516
28517
28518
28519
28520
28521
28522
28523
28524
28525
28526
28527
28528
28529
28530
28531
28532
28533
28534
28535
28536
28537
28538
28539
28540
28541
28542
28543
28544
28545
28546
28547
28548
28549
28550
28551
28552
28553
28554
28555
28556
28557
28558
28559
28560
28561
28562
28563
28564
28565
28566
28567
28568
28569
28570
28571
28572
28573
28574
28575
28576
28577
28578
28579
28580
28581
28582
28583
28584
28585
28586
28587
28588
28589
28590
28591
28592
28593
28594
28595
28596
28597
28598
28599
28600
28601
28602
28603
28604
28605
28606
28607
28608
28609
28610
28611
28612
28613
28614
28615
28616
28617
28618
28619
28620
28621
28622
28623
28624
28625
28626
28627
28628
28629
28630
28631
28632
28633
28634
28635
28636
28637
28638
28639
28640
28641
28642
28643
28644
28645
28646
28647
28648
28649
28650
28651
28652
28653
28654
28655
28656
28657
28658
28659
28660
28661
28662
28663
28664
28665
28666
28667
28668
28669
28670
28671
28672
28673
28674
28675
28676
28677
28678
28679
28680
28681
28682
28683
28684
28685
28686
28687
28688
28689
28690
28691
28692
28693
28694
28695
28696
28697
28698
28699
28700
28701
28702
28703
28704
28705
28706
28707
28708
28709
28710
28711
28712
28713
28714
28715
28716
28717
28718
28719
28720
28721
28722
28723
28724
28725
28726
28727
28728
28729
28730
28731
28732
28733
28734
28735
28736
28737
28738
28739
28740
28741
28742
28743
28744
28745
28746
28747
28748
28749
28750
28751
28752
28753
28754
28755
28756
28757
28758
28759
28760
28761
28762
28763
28764
28765
28766
28767
28768
28769
28770
28771
28772
28773
28774
28775
28776
28777
28778
28779
28780
28781
28782
28783
28784
28785
28786
28787
28788
28789
28790
28791
28792
28793
28794
28795
28796
28797
28798
28799
28800
28801
28802
28803
28804
28805
28806
28807
28808
28809
28810
28811
28812
28813
28814
28815
28816
28817
28818
28819
28820
28821
28822
28823
28824
28825
28826
28827
28828
28829
28830
28831
28832
28833
28834
28835
28836
28837
28838
28839
28840
28841
28842
28843
28844
28845
28846
28847
28848
28849
28850
28851
28852
28853
28854
28855
28856
28857
28858
28859
28860
28861
28862
28863
28864
28865
28866
28867
28868
28869
28870
28871
28872
28873
28874
28875
28876
28877
28878
28879
28880
28881
28882
28883
28884
28885
28886
28887
28888
28889
28890
28891
28892
28893
28894
28895
28896
28897
28898
28899
28900
28901
28902
28903
28904
28905
28906
28907
28908
28909
28910
28911
28912
28913
28914
28915
28916
28917
28918
28919
28920
28921
28922
28923
28924
28925
28926
28927
28928
28929
28930
28931
28932
28933
28934
28935
28936
28937
28938
28939
28940
28941
28942
28943
28944
28945
28946
28947
28948
28949
28950
28951
28952
28953
28954
28955
28956
28957
28958
28959
28960
28961
28962
28963
28964
28965
28966
28967
28968
28969
28970
28971
28972
28973
28974
28975
28976
28977
28978
28979
28980
28981
28982
28983
28984
28985
28986
28987
28988
28989
28990
28991
28992
28993
28994
28995
28996
28997
28998
28999
29000
29001
29002
29003
29004
29005
29006
29007
29008
29009
29010
29011
29012
29013
29014
29015
29016
29017
29018
29019
29020
29021
29022
29023
29024
29025
29026
29027
29028
29029
29030
29031
29032
29033
29034
29035
29036
29037
29038
29039
29040
29041
29042
29043
29044
29045
29046
29047
29048
29049
29050
29051
29052
29053
29054
29055
29056
29057
29058
29059
29060
29061
29062
29063
29064
29065
29066
29067
29068
29069
29070
29071
29072
29073
29074
29075
29076
29077
29078
29079
29080
29081
29082
29083
29084
29085
29086
29087
29088
29089
29090
29091
29092
29093
29094
29095
29096
29097
29098
29099
29100
29101
29102
29103
29104
29105
29106
29107
29108
29109
29110
29111
29112
29113
29114
29115
29116
29117
29118
29119
29120
29121
29122
29123
29124
29125
29126
29127
29128
29129
29130
29131
29132
29133
29134
29135
29136
29137
29138
29139
29140
29141
29142
29143
29144
29145
29146
29147
29148
29149
29150
29151
29152
29153
29154
29155
29156
29157
29158
29159
29160
29161
29162
29163
29164
29165
29166
29167
29168
29169
29170
29171
29172
29173
29174
29175
29176
29177
29178
29179
29180
29181
29182
29183
29184
29185
29186
29187
29188
29189
29190
29191
29192
29193
29194
29195
29196
29197
29198
29199
29200
29201
29202
29203
29204
29205
29206
29207
29208
29209
29210
29211
29212
29213
29214
29215
29216
29217
29218
29219
29220
29221
29222
29223
29224
29225
29226
29227
29228
29229
29230
29231
29232
29233
29234
29235
29236
29237
29238
29239
29240
29241
29242
29243
29244
29245
29246
29247
29248
29249
29250
29251
29252
29253
29254
29255
29256
29257
29258
29259
29260
29261
29262
29263
29264
29265
29266
29267
29268
29269
29270
29271
29272
29273
29274
29275
29276
29277
29278
29279
29280
29281
29282
29283
29284
29285
29286
29287
29288
29289
29290
29291
29292
29293
29294
29295
29296
29297
29298
29299
29300
29301
29302
29303
29304
29305
29306
29307
29308
29309
29310
29311
29312
29313
29314
29315
29316
29317
29318
29319
29320
29321
29322
29323
29324
29325
29326
29327
29328
29329
29330
29331
29332
29333
29334
29335
29336
29337
29338
29339
29340
29341
29342
29343
29344
29345
29346
29347
29348
29349
29350
29351
29352
29353
29354
29355
29356
29357
29358
29359
29360
29361
29362
29363
29364
29365
29366
29367
29368
29369
29370
29371
29372
29373
29374
29375
29376
29377
29378
29379
29380
29381
29382
29383
29384
29385
29386
29387
29388
29389
29390
29391
29392
29393
29394
29395
29396
29397
29398
29399
29400
29401
29402
29403
29404
29405
29406
29407
29408
29409
29410
29411
29412
29413
29414
29415
29416
29417
29418
29419
29420
29421
29422
29423
29424
29425
29426
29427
29428
29429
29430
29431
29432
29433
29434
29435
29436
29437
29438
29439
29440
29441
29442
29443
29444
29445
29446
29447
29448
29449
29450
29451
29452
29453
29454
29455
29456
29457
29458
29459
29460
29461
29462
29463
29464
29465
29466
29467
29468
29469
29470
29471
29472
29473
29474
29475
29476
29477
29478
29479
29480
29481
29482
29483
29484
29485
29486
29487
29488
29489
29490
29491
29492
29493
29494
29495
29496
29497
29498
29499
29500
29501
29502
29503
29504
29505
29506
29507
29508
29509
29510
29511
29512
29513
29514
29515
29516
29517
29518
29519
29520
29521
29522
29523
29524
29525
29526
29527
29528
29529
29530
29531
29532
29533
29534
29535
29536
29537
29538
29539
29540
29541
29542
29543
29544
29545
29546
29547
29548
29549
29550
29551
29552
29553
29554
29555
29556
29557
29558
29559
29560
29561
29562
29563
29564
29565
29566
29567
29568
29569
29570
29571
29572
29573
29574
29575
29576
29577
29578
29579
29580
29581
29582
29583
29584
29585
29586
29587
29588
29589
29590
29591
29592
29593
29594
29595
29596
29597
29598
29599
29600
29601
29602
29603
29604
29605
29606
29607
29608
29609
29610
29611
29612
29613
29614
29615
29616
29617
29618
29619
29620
29621
29622
29623
29624
29625
29626
29627
29628
29629
29630
29631
29632
29633
29634
29635
29636
29637
29638
29639
29640
29641
29642
29643
29644
29645
29646
29647
29648
29649
29650
29651
29652
29653
29654
29655
29656
29657
29658
29659
29660
29661
29662
29663
29664
29665
29666
29667
29668
29669
29670
29671
29672
29673
29674
29675
29676
29677
29678
29679
29680
29681
29682
29683
29684
29685
29686
29687
29688
29689
29690
29691
29692
29693
29694
29695
29696
29697
29698
29699
29700
29701
29702
29703
29704
29705
29706
29707
29708
29709
29710
29711
29712
29713
29714
29715
29716
29717
29718
29719
29720
29721
29722
29723
29724
29725
29726
29727
29728
29729
29730
29731
29732
29733
29734
29735
29736
29737
29738
29739
29740
29741
29742
29743
29744
29745
29746
29747
29748
29749
29750
29751
29752
29753
29754
29755
29756
29757
29758
29759
29760
29761
29762
29763
29764
29765
29766
29767
29768
29769
29770
29771
29772
29773
29774
29775
29776
29777
29778
29779
29780
29781
29782
29783
29784
29785
29786
29787
29788
29789
29790
29791
29792
29793
29794
29795
29796
29797
29798
29799
29800
29801
29802
29803
29804
29805
29806
29807
29808
29809
29810
29811
29812
29813
29814
29815
29816
29817
29818
29819
29820
29821
29822
29823
29824
29825
29826
29827
29828
29829
29830
29831
29832
29833
29834
29835
29836
29837
29838
29839
29840
29841
29842
29843
29844
29845
29846
29847
29848
29849
29850
29851
29852
29853
29854
29855
29856
29857
29858
29859
29860
29861
29862
29863
29864
29865
29866
29867
29868
29869
29870
29871
29872
29873
29874
29875
29876
29877
29878
29879
29880
29881
29882
29883
29884
29885
29886
29887
29888
29889
29890
29891
29892
29893
29894
29895
29896
29897
29898
29899
29900
29901
29902
29903
29904
29905
29906
29907
29908
29909
29910
29911
29912
29913
29914
29915
29916
29917
29918
29919
29920
29921
29922
29923
29924
29925
29926
29927
29928
29929
29930
29931
29932
29933
29934
29935
29936
29937
29938
29939
29940
29941
29942
29943
29944
29945
29946
29947
29948
29949
29950
29951
29952
29953
29954
29955
29956
29957
29958
29959
29960
29961
29962
29963
29964
29965
29966
29967
29968
29969
29970
29971
29972
29973
29974
29975
29976
29977
29978
29979
29980
29981
29982
29983
29984
29985
29986
29987
29988
29989
29990
29991
29992
29993
29994
29995
29996
29997
29998
29999
30000
30001
30002
30003
30004
30005
30006
30007
30008
30009
30010
30011
30012
30013
30014
30015
30016
30017
30018
30019
30020
30021
30022
30023
30024
30025
30026
30027
30028
30029
30030
30031
30032
30033
30034
30035
30036
30037
30038
30039
30040
30041
30042
30043
30044
30045
30046
30047
30048
30049
30050
30051
30052
30053
30054
30055
30056
30057
30058
30059
30060
30061
30062
30063
30064
30065
30066
30067
30068
30069
30070
30071
30072
30073
30074
30075
30076
30077
30078
30079
30080
30081
30082
30083
30084
30085
30086
30087
30088
30089
30090
30091
30092
30093
30094
30095
30096
30097
30098
30099
30100
30101
30102
30103
30104
30105
30106
30107
30108
30109
30110
30111
30112
30113
30114
30115
30116
30117
30118
30119
30120
30121
30122
30123
30124
30125
30126
30127
30128
30129
30130
30131
30132
30133
30134
30135
30136
30137
30138
30139
30140
30141
30142
30143
30144
30145
30146
30147
30148
30149
30150
30151
30152
30153
30154
30155
30156
30157
30158
30159
30160
30161
30162
30163
30164
30165
30166
30167
30168
30169
30170
30171
30172
30173
30174
30175
30176
30177
30178
30179
30180
30181
30182
30183
30184
30185
30186
30187
30188
30189
30190
30191
30192
30193
30194
30195
30196
30197
30198
30199
30200
30201
30202
30203
30204
30205
30206
30207
30208
30209
30210
30211
30212
30213
30214
30215
30216
30217
30218
30219
30220
30221
30222
30223
30224
30225
30226
30227
30228
30229
30230
30231
30232
30233
30234
30235
30236
30237
30238
30239
30240
30241
30242
30243
30244
30245
30246
30247
30248
30249
30250
30251
30252
30253
30254
30255
30256
30257
30258
30259
30260
30261
30262
30263
30264
30265
30266
30267
30268
30269
30270
30271
30272
30273
30274
30275
30276
30277
30278
30279
30280
30281
30282
30283
30284
30285
30286
30287
30288
30289
30290
30291
30292
30293
30294
30295
30296
30297
30298
30299
30300
30301
30302
30303
30304
30305
30306
30307
30308
30309
30310
30311
30312
30313
30314
30315
30316
30317
30318
30319
30320
30321
30322
30323
30324
30325
30326
30327
30328
30329
30330
30331
30332
30333
30334
30335
30336
30337
30338
30339
30340
30341
30342
30343
30344
30345
30346
30347
30348
30349
30350
30351
30352
30353
30354
30355
30356
30357
30358
30359
30360
30361
30362
30363
30364
30365
30366
30367
30368
30369
30370
30371
30372
30373
30374
30375
30376
30377
30378
30379
30380
30381
30382
30383
30384
30385
30386
30387
30388
30389
30390
30391
30392
30393
30394
30395
30396
30397
30398
30399
30400
30401
30402
30403
30404
30405
30406
30407
30408
30409
30410
30411
30412
30413
30414
30415
30416
30417
30418
30419
30420
30421
30422
30423
30424
30425
30426
30427
30428
30429
30430
30431
30432
30433
30434
30435
30436
30437
30438
30439
30440
30441
30442
30443
30444
30445
30446
30447
30448
30449
30450
30451
30452
30453
30454
30455
30456
30457
30458
30459
30460
30461
30462
30463
30464
30465
30466
30467
30468
30469
30470
30471
30472
30473
30474
30475
30476
30477
30478
30479
30480
30481
30482
30483
30484
30485
30486
30487
30488
30489
30490
30491
30492
30493
30494
30495
30496
30497
30498
30499
30500
30501
30502
30503
30504
30505
30506
30507
30508
30509
30510
30511
30512
30513
30514
30515
30516
30517
30518
30519
30520
30521
30522
30523
30524
30525
30526
30527
30528
30529
30530
30531
30532
30533
30534
30535
30536
30537
30538
30539
30540
30541
30542
30543
30544
30545
30546
30547
30548
30549
30550
30551
30552
30553
30554
30555
30556
30557
30558
30559
30560
30561
30562
30563
30564
30565
30566
30567
30568
30569
30570
30571
30572
30573
30574
30575
30576
30577
30578
30579
30580
30581
30582
30583
30584
30585
30586
30587
30588
30589
30590
30591
30592
30593
30594
30595
30596
30597
30598
30599
30600
30601
30602
30603
30604
30605
30606
30607
30608
30609
30610
30611
30612
30613
30614
30615
30616
30617
30618
30619
30620
30621
30622
30623
30624
30625
30626
30627
30628
30629
30630
30631
30632
30633
30634
30635
30636
30637
30638
30639
30640
30641
30642
30643
30644
30645
30646
30647
30648
30649
30650
30651
30652
30653
30654
30655
30656
30657
30658
30659
30660
30661
30662
30663
30664
30665
30666
30667
30668
30669
30670
30671
30672
30673
30674
30675
30676
30677
30678
30679
30680
30681
30682
30683
30684
30685
30686
30687
30688
30689
30690
30691
30692
30693
30694
30695
30696
30697
30698
30699
30700
30701
30702
30703
30704
30705
30706
30707
30708
30709
30710
30711
30712
30713
30714
30715
30716
30717
30718
30719
30720
30721
30722
30723
30724
30725
30726
30727
30728
30729
30730
30731
30732
30733
30734
30735
30736
30737
30738
30739
30740
30741
30742
30743
30744
30745
30746
30747
30748
30749
30750
30751
30752
30753
30754
30755
30756
30757
30758
30759
30760
30761
30762
30763
30764
30765
30766
30767
30768
30769
30770
30771
30772
30773
30774
30775
30776
30777
30778
30779
30780
30781
30782
30783
30784
30785
30786
30787
30788
30789
30790
30791
30792
30793
30794
30795
30796
30797
30798
30799
30800
30801
30802
30803
30804
30805
30806
30807
30808
30809
30810
30811
30812
30813
30814
30815
30816
30817
30818
30819
30820
30821
30822
30823
30824
30825
30826
30827
30828
30829
30830
30831
30832
30833
30834
30835
30836
30837
30838
30839
30840
30841
30842
30843
30844
30845
30846
30847
30848
30849
30850
30851
30852
30853
30854
30855
30856
30857
30858
30859
30860
30861
30862
30863
30864
30865
30866
30867
30868
30869
30870
30871
30872
30873
30874
30875
30876
30877
30878
30879
30880
30881
30882
30883
30884
30885
30886
30887
30888
30889
30890
30891
30892
30893
30894
30895
30896
30897
30898
30899
30900
30901
30902
30903
30904
30905
30906
30907
30908
30909
30910
30911
30912
30913
30914
30915
30916
30917
30918
30919
30920
30921
30922
30923
30924
30925
30926
30927
30928
30929
30930
30931
30932
30933
30934
30935
30936
30937
30938
30939
30940
30941
30942
30943
30944
30945
30946
30947
30948
30949
30950
30951
30952
30953
30954
30955
30956
30957
30958
30959
30960
30961
30962
30963
30964
30965
30966
30967
30968
30969
30970
30971
30972
30973
30974
30975
30976
30977
30978
30979
30980
30981
30982
30983
30984
30985
30986
30987
30988
30989
30990
30991
30992
30993
30994
30995
30996
30997
30998
30999
31000
31001
31002
31003
31004
31005
31006
31007
31008
31009
31010
31011
31012
31013
31014
31015
31016
31017
31018
31019
31020
31021
31022
31023
31024
31025
31026
31027
31028
31029
31030
31031
31032
31033
31034
31035
31036
31037
31038
31039
31040
31041
31042
31043
31044
31045
31046
31047
31048
31049
31050
31051
31052
31053
31054
31055
31056
31057
31058
31059
31060
31061
31062
31063
31064
31065
31066
31067
31068
31069
31070
31071
31072
31073
31074
31075
31076
31077
31078
31079
31080
31081
31082
31083
31084
31085
31086
31087
31088
31089
31090
31091
31092
31093
31094
31095
31096
31097
31098
31099
31100
31101
31102
31103
31104
31105
31106
31107
31108
31109
31110
31111
31112
31113
31114
31115
31116
31117
31118
31119
31120
31121
31122
31123
31124
31125
31126
31127
31128
31129
31130
31131
31132
31133
31134
31135
31136
31137
31138
31139
31140
31141
31142
31143
31144
31145
31146
31147
31148
31149
31150
31151
31152
31153
31154
31155
31156
31157
31158
31159
31160
31161
31162
31163
31164
31165
31166
31167
31168
31169
31170
31171
31172
31173
31174
31175
31176
31177
31178
31179
31180
31181
31182
31183
31184
31185
31186
31187
31188
31189
31190
31191
31192
31193
31194
31195
31196
31197
31198
31199
31200
31201
31202
31203
31204
31205
31206
31207
31208
31209
31210
31211
31212
31213
31214
31215
31216
31217
31218
31219
31220
31221
31222
31223
31224
31225
31226
31227
31228
31229
31230
31231
31232
31233
31234
31235
31236
31237
31238
31239
31240
31241
31242
31243
31244
31245
31246
31247
31248
31249
31250
31251
31252
31253
31254
31255
31256
31257
31258
31259
31260
31261
31262
31263
31264
31265
31266
31267
31268
31269
31270
31271
31272
31273
31274
31275
31276
31277
31278
31279
31280
31281
31282
31283
31284
31285
31286
31287
31288
31289
31290
31291
31292
31293
31294
31295
31296
31297
31298
31299
31300
31301
31302
31303
31304
31305
31306
31307
31308
31309
31310
31311
31312
31313
31314
31315
31316
31317
31318
31319
31320
31321
31322
31323
31324
31325
31326
31327
31328
31329
31330
31331
31332
31333
31334
31335
31336
31337
31338
31339
31340
31341
31342
31343
31344
31345
31346
31347
31348
31349
31350
31351
31352
31353
31354
31355
31356
31357
31358
31359
31360
31361
31362
31363
31364
31365
31366
31367
31368
31369
31370
31371
31372
31373
31374
31375
31376
31377
31378
31379
31380
31381
31382
31383
31384
31385
31386
31387
31388
31389
31390
31391
31392
31393
31394
31395
31396
31397
31398
31399
31400
31401
31402
31403
31404
31405
31406
31407
31408
31409
31410
31411
31412
31413
31414
31415
31416
31417
31418
31419
31420
31421
31422
31423
31424
31425
31426
31427
31428
31429
31430
31431
31432
31433
31434
31435
31436
31437
31438
31439
31440
31441
31442
31443
31444
31445
31446
31447
31448
31449
31450
31451
31452
31453
31454
31455
31456
31457
31458
31459
31460
31461
31462
31463
31464
31465
31466
31467
31468
31469
31470
31471
31472
31473
31474
31475
31476
31477
31478
31479
31480
31481
31482
31483
31484
31485
31486
31487
31488
31489
31490
31491
31492
31493
31494
31495
31496
31497
31498
31499
31500
31501
31502
31503
31504
31505
31506
31507
31508
31509
31510
31511
31512
31513
31514
31515
31516
31517
31518
31519
31520
31521
31522
31523
31524
31525
31526
31527
31528
31529
31530
31531
31532
31533
31534
31535
31536
31537
31538
31539
31540
31541
31542
31543
31544
31545
31546
31547
31548
31549
31550
31551
31552
31553
31554
31555
31556
31557
31558
31559
31560
31561
31562
31563
31564
31565
31566
31567
31568
31569
31570
31571
31572
31573
31574
31575
31576
31577
31578
31579
31580
31581
31582
31583
31584
31585
31586
31587
31588
31589
31590
31591
31592
31593
31594
31595
31596
31597
31598
31599
31600
31601
31602
31603
31604
31605
31606
31607
31608
31609
31610
31611
31612
31613
31614
31615
31616
31617
31618
31619
31620
31621
31622
31623
31624
31625
31626
31627
31628
31629
31630
31631
31632
31633
31634
31635
31636
31637
31638
31639
31640
31641
31642
31643
31644
31645
31646
31647
31648
31649
31650
31651
31652
31653
31654
31655
31656
31657
31658
31659
31660
31661
31662
31663
31664
31665
31666
31667
31668
31669
31670
31671
31672
31673
31674
31675
31676
31677
31678
31679
31680
31681
31682
31683
31684
31685
31686
31687
31688
31689
31690
31691
31692
31693
31694
31695
31696
31697
31698
31699
31700
31701
31702
31703
31704
31705
31706
31707
31708
31709
31710
31711
31712
31713
31714
31715
31716
31717
31718
31719
31720
31721
31722
31723
31724
31725
31726
31727
31728
31729
31730
31731
31732
31733
31734
31735
31736
31737
31738
31739
31740
31741
31742
31743
31744
31745
31746
31747
31748
31749
31750
31751
31752
31753
31754
31755
31756
31757
31758
31759
31760
31761
31762
31763
31764
31765
31766
31767
31768
31769
31770
31771
31772
31773
31774
31775
31776
31777
31778
31779
31780
31781
31782
31783
31784
31785
31786
31787
31788
31789
31790
31791
31792
31793
31794
31795
31796
31797
31798
31799
31800
31801
31802
31803
31804
31805
31806
31807
31808
31809
31810
31811
31812
31813
31814
31815
31816
31817
31818
31819
31820
31821
31822
31823
31824
31825
31826
31827
31828
31829
31830
31831
31832
31833
31834
31835
31836
31837
31838
31839
31840
31841
31842
31843
31844
31845
31846
31847
31848
31849
31850
31851
31852
31853
31854
31855
31856
31857
31858
31859
31860
31861
31862
31863
31864
31865
31866
31867
31868
31869
31870
31871
31872
31873
31874
31875
31876
31877
31878
31879
31880
31881
31882
31883
31884
31885
31886
31887
31888
31889
31890
31891
31892
31893
31894
31895
31896
31897
31898
31899
31900
31901
31902
31903
31904
31905
31906
31907
31908
31909
31910
31911
31912
31913
31914
31915
31916
31917
31918
31919
31920
31921
31922
31923
31924
31925
31926
31927
31928
31929
31930
31931
31932
31933
31934
31935
31936
31937
31938
31939
31940
31941
31942
31943
31944
31945
31946
31947
31948
31949
31950
31951
31952
31953
31954
31955
31956
31957
31958
31959
31960
31961
31962
31963
31964
31965
31966
31967
31968
31969
31970
31971
31972
31973
31974
31975
31976
31977
31978
31979
31980
31981
31982
31983
31984
31985
31986
31987
31988
31989
31990
31991
31992
31993
31994
31995
31996
31997
31998
31999
32000
32001
32002
32003
32004
32005
32006
32007
32008
32009
32010
32011
32012
32013
32014
32015
32016
32017
32018
32019
32020
32021
32022
32023
32024
32025
32026
32027
32028
32029
32030
32031
32032
32033
32034
32035
32036
32037
32038
32039
32040
32041
32042
32043
32044
32045
32046
32047
32048
32049
32050
32051
32052
32053
32054
32055
32056
32057
32058
32059
32060
32061
32062
32063
32064
32065
32066
32067
32068
32069
32070
32071
32072
32073
32074
32075
32076
32077
32078
32079
32080
32081
32082
32083
32084
32085
32086
32087
32088
32089
32090
32091
32092
32093
32094
32095
32096
32097
32098
32099
32100
32101
32102
32103
32104
32105
32106
32107
32108
32109
32110
32111
32112
32113
32114
32115
32116
32117
32118
32119
32120
32121
32122
32123
32124
32125
32126
32127
32128
32129
32130
32131
32132
32133
32134
32135
32136
32137
32138
32139
32140
32141
32142
32143
32144
32145
32146
32147
32148
32149
32150
32151
32152
32153
32154
32155
32156
32157
32158
32159
32160
32161
32162
32163
32164
32165
32166
32167
32168
32169
32170
32171
32172
32173
32174
32175
32176
32177
32178
32179
32180
32181
32182
32183
32184
32185
32186
32187
32188
32189
32190
32191
32192
32193
32194
32195
32196
32197
32198
32199
32200
32201
32202
32203
32204
32205
32206
32207
32208
32209
32210
32211
32212
32213
32214
32215
32216
32217
32218
32219
32220
32221
32222
32223
32224
32225
32226
32227
32228
32229
32230
32231
32232
32233
32234
32235
32236
32237
32238
32239
32240
32241
32242
32243
32244
32245
32246
32247
32248
32249
32250
32251
32252
32253
32254
32255
32256
32257
32258
32259
32260
32261
32262
32263
32264
32265
32266
32267
32268
32269
32270
32271
32272
32273
32274
32275
32276
32277
32278
32279
32280
32281
32282
32283
32284
32285
32286
32287
32288
32289
32290
32291
32292
32293
32294
32295
32296
32297
32298
32299
32300
32301
32302
32303
32304
32305
32306
32307
32308
32309
32310
32311
32312
32313
32314
32315
32316
32317
32318
32319
32320
32321
32322
32323
32324
32325
32326
32327
32328
32329
32330
32331
32332
32333
32334
32335
32336
32337
32338
32339
32340
32341
32342
32343
32344
32345
32346
32347
32348
32349
32350
32351
32352
32353
32354
32355
32356
32357
32358
32359
32360
32361
32362
32363
32364
32365
32366
32367
32368
32369
32370
32371
32372
32373
32374
32375
32376
32377
32378
32379
32380
32381
32382
32383
32384
32385
32386
32387
32388
32389
32390
32391
32392
32393
32394
32395
32396
32397
32398
32399
32400
32401
32402
32403
32404
32405
32406
32407
32408
32409
32410
32411
32412
32413
32414
32415
32416
32417
32418
32419
32420
32421
32422
32423
32424
32425
32426
32427
32428
32429
32430
32431
32432
32433
32434
32435
32436
32437
32438
32439
32440
32441
32442
32443
32444
32445
32446
32447
32448
32449
32450
32451
32452
32453
32454
32455
32456
32457
32458
32459
32460
32461
32462
32463
32464
32465
32466
32467
32468
32469
32470
32471
32472
32473
32474
32475
32476
32477
32478
32479
32480
32481
32482
32483
32484
32485
32486
32487
32488
32489
32490
32491
32492
32493
32494
32495
32496
32497
32498
32499
32500
32501
32502
32503
32504
32505
32506
32507
32508
32509
32510
32511
32512
32513
32514
32515
32516
32517
32518
32519
32520
32521
32522
32523
32524
32525
32526
32527
32528
32529
32530
32531
32532
32533
32534
32535
32536
32537
32538
32539
32540
32541
32542
32543
32544
32545
32546
32547
32548
32549
32550
32551
32552
32553
32554
32555
32556
32557
32558
32559
32560
32561
32562
32563
32564
32565
32566
32567
32568
32569
32570
32571
32572
32573
32574
32575
32576
32577
32578
32579
32580
32581
32582
32583
32584
32585
32586
32587
32588
32589
32590
32591
32592
32593
32594
32595
32596
32597
32598
32599
32600
32601
32602
32603
32604
32605
32606
32607
32608
32609
32610
32611
32612
32613
32614
32615
32616
32617
32618
32619
32620
32621
32622
32623
32624
32625
32626
32627
32628
32629
32630
32631
32632
32633
32634
32635
32636
32637
32638
32639
32640
32641
32642
32643
32644
32645
32646
32647
32648
32649
32650
32651
32652
32653
32654
32655
32656
32657
32658
32659
32660
32661
32662
32663
32664
32665
32666
32667
32668
32669
32670
32671
32672
32673
32674
32675
32676
32677
32678
32679
32680
32681
32682
32683
32684
32685
32686
32687
32688
32689
32690
32691
32692
32693
32694
32695
32696
32697
32698
32699
32700
32701
32702
32703
32704
32705
32706
32707
32708
32709
32710
32711
32712
32713
32714
32715
32716
32717
32718
32719
32720
32721
32722
32723
32724
32725
32726
32727
32728
32729
32730
32731
32732
32733
32734
32735
32736
32737
32738
32739
32740
32741
32742
32743
32744
32745
32746
32747
32748
32749
32750
32751
32752
32753
32754
32755
32756
32757
32758
32759
32760
32761
32762
32763
32764
32765
32766
32767
32768
32769
32770
32771
32772
32773
32774
32775
32776
32777
32778
32779
32780
32781
32782
32783
32784
32785
32786
32787
32788
32789
32790
32791
32792
32793
32794
32795
32796
32797
32798
32799
32800
32801
32802
32803
32804
32805
32806
32807
32808
32809
32810
32811
32812
32813
32814
32815
32816
32817
32818
32819
32820
32821
32822
32823
32824
32825
32826
32827
32828
32829
32830
32831
32832
32833
32834
32835
32836
32837
32838
32839
32840
32841
32842
32843
32844
32845
32846
32847
32848
32849
32850
32851
32852
32853
32854
32855
32856
32857
32858
32859
32860
32861
32862
32863
32864
32865
32866
32867
32868
32869
32870
32871
32872
32873
32874
32875
32876
32877
32878
32879
32880
32881
32882
32883
32884
32885
32886
32887
32888
32889
32890
32891
32892
32893
32894
32895
32896
32897
32898
32899
32900
32901
32902
32903
32904
32905
32906
32907
32908
32909
32910
32911
32912
32913
32914
32915
32916
32917
32918
32919
32920
32921
32922
32923
32924
32925
32926
32927
32928
32929
32930
32931
32932
32933
32934
32935
32936
32937
32938
32939
32940
32941
32942
32943
32944
32945
32946
32947
32948
32949
32950
32951
32952
32953
32954
32955
32956
32957
32958
32959
32960
32961
32962
32963
32964
32965
32966
32967
32968
32969
32970
32971
32972
32973
32974
32975
32976
32977
32978
32979
32980
32981
32982
32983
32984
32985
32986
32987
32988
32989
32990
32991
32992
32993
32994
32995
32996
32997
32998
32999
33000
33001
33002
33003
33004
33005
33006
33007
33008
33009
33010
33011
33012
33013
33014
33015
33016
33017
33018
33019
33020
33021
33022
33023
33024
33025
33026
33027
33028
33029
33030
33031
33032
33033
33034
33035
33036
33037
33038
33039
33040
33041
33042
33043
33044
33045
33046
33047
33048
33049
33050
33051
33052
33053
33054
33055
33056
33057
33058
33059
33060
33061
33062
33063
33064
33065
33066
33067
33068
33069
33070
33071
33072
33073
33074
33075
33076
33077
33078
33079
33080
33081
33082
33083
33084
33085
33086
33087
33088
33089
33090
33091
33092
33093
33094
33095
33096
33097
33098
33099
33100
33101
33102
33103
33104
33105
33106
33107
33108
33109
33110
33111
33112
33113
33114
33115
33116
33117
33118
33119
33120
33121
33122
33123
33124
33125
33126
33127
33128
33129
33130
33131
33132
33133
33134
33135
33136
33137
33138
33139
33140
33141
33142
33143
33144
33145
33146
33147
33148
33149
33150
33151
33152
33153
33154
33155
33156
33157
33158
33159
33160
33161
33162
33163
33164
33165
33166
33167
33168
33169
33170
33171
33172
33173
33174
33175
33176
33177
33178
33179
33180
33181
33182
33183
33184
33185
33186
33187
33188
33189
33190
33191
33192
33193
33194
33195
33196
33197
33198
33199
33200
33201
33202
33203
33204
33205
33206
33207
33208
33209
33210
33211
33212
33213
33214
33215
33216
33217
33218
33219
33220
33221
33222
33223
33224
33225
33226
33227
33228
33229
33230
33231
33232
33233
33234
33235
33236
33237
33238
33239
33240
33241
33242
33243
33244
33245
33246
33247
33248
33249
33250
33251
33252
33253
33254
33255
33256
33257
33258
33259
33260
33261
33262
33263
33264
33265
33266
33267
33268
33269
33270
33271
33272
33273
33274
33275
33276
33277
33278
33279
33280
33281
33282
33283
33284
33285
33286
33287
33288
33289
33290
33291
33292
33293
33294
33295
33296
33297
33298
33299
33300
33301
33302
33303
33304
33305
33306
33307
33308
33309
33310
33311
33312
33313
33314
33315
33316
33317
33318
33319
33320
33321
33322
33323
33324
33325
33326
33327
33328
33329
33330
33331
33332
33333
33334
33335
33336
33337
33338
33339
33340
33341
33342
33343
33344
33345
33346
33347
33348
33349
33350
33351
33352
33353
33354
33355
33356
33357
33358
33359
33360
33361
33362
33363
33364
33365
33366
33367
33368
33369
33370
33371
33372
33373
33374
33375
33376
33377
33378
33379
33380
33381
33382
33383
33384
33385
33386
33387
33388
33389
33390
33391
33392
33393
33394
33395
33396
33397
33398
33399
33400
33401
33402
33403
33404
33405
33406
33407
33408
33409
33410
33411
33412
33413
33414
33415
33416
33417
33418
33419
33420
33421
33422
33423
33424
33425
33426
33427
33428
33429
33430
33431
33432
33433
33434
33435
33436
33437
33438
33439
33440
33441
33442
33443
33444
33445
33446
33447
33448
33449
33450
33451
33452
33453
33454
33455
33456
33457
33458
33459
33460
33461
33462
33463
33464
33465
33466
33467
33468
33469
33470
33471
33472
33473
33474
33475
33476
33477
33478
33479
33480
33481
33482
33483
33484
33485
33486
33487
33488
33489
33490
33491
33492
33493
33494
33495
33496
33497
33498
33499
33500
33501
33502
33503
33504
33505
33506
33507
33508
33509
33510
33511
33512
33513
33514
33515
33516
33517
33518
33519
33520
33521
33522
33523
33524
33525
33526
33527
33528
33529
33530
33531
33532
33533
33534
33535
33536
33537
33538
33539
33540
33541
33542
33543
33544
33545
33546
33547
33548
33549
33550
33551
33552
33553
33554
33555
33556
33557
33558
33559
33560
33561
33562
33563
33564
33565
33566
33567
33568
33569
33570
33571
33572
33573
33574
33575
33576
33577
33578
33579
33580
33581
33582
33583
33584
33585
33586
33587
33588
33589
33590
33591
33592
33593
33594
33595
33596
33597
33598
33599
33600
33601
33602
33603
33604
33605
33606
33607
33608
33609
33610
33611
33612
33613
33614
33615
33616
33617
33618
33619
33620
33621
33622
33623
33624
33625
33626
33627
33628
33629
33630
33631
33632
33633
33634
33635
33636
33637
33638
33639
33640
33641
33642
33643
33644
33645
33646
33647
33648
33649
33650
33651
33652
33653
33654
33655
33656
33657
33658
33659
33660
33661
33662
33663
33664
33665
33666
33667
33668
33669
33670
33671
33672
33673
33674
33675
33676
33677
33678
33679
33680
33681
33682
33683
33684
33685
33686
33687
33688
33689
33690
33691
33692
33693
33694
33695
33696
33697
33698
33699
33700
33701
33702
33703
33704
33705
33706
33707
33708
33709
33710
33711
33712
33713
33714
33715
33716
33717
33718
33719
33720
33721
33722
33723
33724
33725
33726
33727
33728
33729
33730
33731
33732
33733
33734
33735
33736
33737
33738
33739
33740
33741
33742
33743
33744
33745
33746
33747
33748
33749
33750
33751
33752
33753
33754
33755
33756
33757
33758
33759
33760
33761
33762
33763
33764
33765
33766
33767
33768
33769
33770
33771
33772
33773
33774
33775
33776
33777
33778
33779
33780
33781
33782
33783
33784
33785
33786
33787
33788
33789
33790
33791
33792
33793
33794
33795
33796
33797
33798
33799
33800
33801
33802
33803
33804
33805
33806
33807
33808
33809
33810
33811
33812
33813
33814
33815
33816
33817
33818
33819
33820
33821
33822
33823
33824
33825
33826
33827
33828
33829
33830
33831
33832
33833
33834
33835
33836
33837
33838
33839
33840
33841
33842
33843
33844
33845
33846
33847
33848
33849
33850
33851
33852
33853
33854
33855
33856
33857
33858
33859
33860
33861
33862
33863
33864
33865
33866
33867
33868
33869
33870
33871
33872
33873
33874
33875
33876
33877
33878
33879
33880
33881
33882
33883
33884
33885
33886
33887
33888
33889
33890
33891
33892
33893
33894
33895
33896
33897
33898
33899
33900
33901
33902
33903
33904
33905
33906
33907
33908
33909
33910
33911
33912
33913
33914
33915
33916
33917
33918
33919
33920
33921
33922
33923
33924
33925
33926
33927
33928
33929
33930
33931
33932
33933
33934
33935
33936
33937
33938
33939
33940
33941
33942
33943
33944
33945
33946
33947
33948
33949
33950
33951
33952
33953
33954
33955
33956
33957
33958
33959
33960
33961
33962
33963
33964
33965
33966
33967
33968
33969
33970
33971
33972
33973
33974
33975
33976
33977
33978
33979
33980
33981
33982
33983
33984
33985
33986
33987
33988
33989
33990
33991
33992
33993
33994
33995
33996
33997
33998
33999
34000
34001
34002
34003
34004
34005
34006
34007
34008
34009
34010
34011
34012
34013
34014
34015
34016
34017
34018
34019
34020
34021
34022
34023
34024
34025
34026
34027
34028
34029
34030
34031
34032
34033
34034
34035
34036
34037
34038
34039
34040
34041
34042
34043
34044
34045
34046
34047
34048
34049
34050
34051
34052
34053
34054
34055
34056
34057
34058
34059
34060
34061
34062
34063
34064
34065
34066
34067
34068
34069
34070
34071
34072
34073
34074
34075
34076
34077
34078
34079
34080
34081
34082
34083
34084
34085
34086
34087
34088
34089
34090
34091
34092
34093
34094
34095
34096
34097
34098
34099
34100
34101
34102
34103
34104
34105
34106
34107
34108
34109
34110
34111
34112
34113
34114
34115
34116
34117
34118
34119
34120
34121
34122
34123
34124
34125
34126
34127
34128
34129
34130
34131
34132
34133
34134
34135
34136
34137
34138
34139
34140
34141
34142
34143
34144
34145
34146
34147
34148
34149
34150
34151
34152
34153
34154
34155
34156
34157
34158
34159
34160
34161
34162
34163
34164
34165
34166
34167
34168
34169
34170
34171
34172
34173
34174
34175
34176
34177
34178
34179
34180
34181
34182
34183
34184
34185
34186
34187
34188
34189
34190
34191
34192
34193
34194
34195
34196
34197
34198
34199
34200
34201
34202
34203
34204
34205
34206
34207
34208
34209
34210
34211
34212
34213
34214
34215
34216
34217
34218
34219
34220
34221
34222
34223
34224
34225
34226
34227
34228
34229
34230
34231
34232
34233
34234
34235
34236
34237
34238
34239
34240
34241
34242
34243
34244
34245
34246
34247
34248
34249
34250
34251
34252
34253
34254
34255
34256
34257
34258
34259
34260
34261
34262
34263
34264
34265
34266
34267
34268
34269
34270
34271
34272
34273
34274
34275
34276
34277
34278
34279
34280
34281
34282
34283
34284
34285
34286
34287
34288
34289
34290
34291
34292
34293
34294
34295
34296
34297
34298
34299
34300
34301
34302
34303
34304
34305
34306
34307
34308
34309
34310
34311
34312
34313
34314
34315
34316
34317
34318
34319
34320
34321
34322
34323
34324
34325
34326
34327
34328
34329
34330
34331
34332
34333
34334
34335
34336
34337
34338
34339
34340
34341
34342
34343
34344
34345
34346
34347
34348
34349
34350
34351
34352
34353
34354
34355
34356
34357
34358
34359
34360
34361
34362
34363
34364
34365
34366
34367
34368
34369
34370
34371
34372
34373
34374
34375
34376
34377
34378
34379
34380
34381
34382
34383
34384
34385
34386
34387
34388
34389
34390
34391
34392
34393
34394
34395
34396
34397
34398
34399
34400
34401
34402
34403
34404
34405
34406
34407
34408
34409
34410
34411
34412
34413
34414
34415
34416
34417
34418
34419
34420
34421
34422
34423
34424
34425
34426
34427
34428
34429
34430
34431
34432
34433
34434
34435
34436
34437
34438
34439
34440
34441
34442
34443
34444
34445
34446
34447
34448
34449
34450
34451
34452
34453
34454
34455
34456
34457
34458
34459
34460
34461
34462
34463
34464
34465
34466
34467
34468
34469
34470
34471
34472
34473
34474
34475
34476
34477
34478
34479
34480
34481
34482
34483
34484
34485
34486
34487
34488
34489
34490
34491
34492
34493
34494
34495
34496
34497
34498
34499
34500
34501
34502
34503
34504
34505
34506
34507
34508
34509
34510
34511
34512
34513
34514
34515
34516
34517
34518
34519
34520
34521
34522
34523
34524
34525
34526
34527
34528
34529
34530
34531
34532
34533
34534
34535
34536
34537
34538
34539
34540
34541
34542
34543
34544
34545
34546
34547
34548
34549
34550
34551
34552
34553
34554
34555
34556
34557
34558
34559
34560
34561
34562
34563
34564
34565
34566
34567
34568
34569
34570
34571
34572
34573
34574
34575
34576
34577
34578
34579
34580
34581
34582
34583
34584
34585
34586
34587
34588
34589
34590
34591
34592
34593
34594
34595
34596
34597
34598
34599
34600
34601
34602
34603
34604
34605
34606
34607
34608
34609
34610
34611
34612
34613
34614
34615
34616
34617
34618
34619
34620
34621
34622
34623
34624
34625
34626
34627
34628
34629
34630
34631
34632
34633
34634
34635
34636
34637
34638
34639
34640
34641
34642
34643
34644
34645
34646
34647
34648
34649
34650
34651
34652
34653
34654
34655
34656
34657
34658
34659
34660
34661
34662
34663
34664
34665
34666
34667
34668
34669
34670
34671
34672
34673
34674
34675
34676
34677
34678
34679
34680
34681
34682
34683
34684
34685
34686
34687
34688
34689
34690
34691
34692
34693
34694
34695
34696
34697
34698
34699
34700
34701
34702
34703
34704
34705
34706
34707
34708
34709
34710
34711
34712
34713
34714
34715
34716
34717
34718
34719
34720
34721
34722
34723
34724
34725
34726
34727
34728
34729
34730
34731
34732
34733
34734
34735
34736
34737
34738
34739
34740
34741
34742
34743
34744
34745
34746
34747
34748
34749
34750
34751
34752
34753
34754
34755
34756
34757
34758
34759
34760
34761
34762
34763
34764
34765
34766
34767
34768
34769
34770
34771
34772
34773
34774
34775
34776
34777
34778
34779
34780
34781
34782
34783
34784
34785
34786
34787
34788
34789
34790
34791
34792
34793
34794
34795
34796
34797
34798
34799
34800
34801
34802
34803
34804
34805
34806
34807
34808
34809
34810
34811
34812
34813
34814
34815
34816
34817
34818
34819
34820
34821
34822
34823
34824
34825
34826
34827
34828
34829
34830
34831
34832
34833
34834
34835
34836
34837
34838
34839
34840
34841
34842
34843
34844
34845
34846
34847
34848
34849
34850
34851
34852
34853
34854
34855
34856
34857
34858
34859
34860
34861
34862
34863
34864
34865
34866
34867
34868
34869
34870
34871
34872
34873
34874
34875
34876
34877
34878
34879
34880
34881
34882
34883
34884
34885
34886
34887
34888
34889
34890
34891
34892
34893
34894
34895
34896
34897
34898
34899
34900
34901
34902
34903
34904
34905
34906
34907
34908
34909
34910
34911
34912
34913
34914
34915
34916
34917
34918
34919
34920
34921
34922
34923
34924
34925
34926
34927
34928
34929
34930
34931
34932
34933
34934
34935
34936
34937
34938
34939
34940
34941
34942
34943
34944
34945
34946
34947
34948
34949
34950
34951
34952
34953
34954
34955
34956
34957
34958
34959
34960
34961
34962
34963
34964
34965
34966
34967
34968
34969
34970
34971
34972
34973
34974
34975
34976
34977
34978
34979
34980
34981
34982
34983
34984
34985
34986
34987
34988
34989
34990
34991
34992
34993
34994
34995
34996
34997
34998
34999
35000
35001
35002
35003
35004
35005
35006
35007
35008
35009
35010
35011
35012
35013
35014
35015
35016
35017
35018
35019
35020
35021
35022
35023
35024
35025
35026
35027
35028
35029
35030
35031
35032
35033
35034
35035
35036
35037
35038
35039
35040
35041
35042
35043
35044
35045
35046
35047
35048
35049
35050
35051
35052
35053
35054
35055
35056
35057
35058
35059
35060
35061
35062
35063
35064
35065
35066
35067
35068
35069
35070
35071
35072
35073
35074
35075
35076
35077
35078
35079
35080
35081
35082
35083
35084
35085
35086
35087
35088
35089
35090
35091
35092
35093
35094
35095
35096
35097
35098
35099
35100
35101
35102
35103
35104
35105
35106
35107
35108
35109
35110
35111
35112
35113
35114
35115
35116
35117
35118
35119
35120
35121
35122
35123
35124
35125
35126
35127
35128
35129
35130
35131
35132
35133
35134
35135
35136
35137
35138
35139
35140
35141
35142
35143
35144
35145
35146
35147
35148
35149
35150
35151
35152
35153
35154
35155
35156
35157
35158
35159
35160
35161
35162
35163
35164
35165
35166
35167
35168
35169
35170
35171
35172
35173
35174
35175
35176
35177
35178
35179
35180
35181
35182
35183
35184
35185
35186
35187
35188
35189
35190
35191
35192
35193
35194
35195
35196
35197
35198
35199
35200
35201
35202
35203
35204
35205
35206
35207
35208
35209
35210
35211
35212
35213
35214
35215
35216
35217
35218
35219
35220
35221
35222
35223
35224
35225
35226
35227
35228
35229
35230
35231
35232
35233
35234
35235
35236
35237
35238
35239
35240
35241
35242
35243
35244
35245
35246
35247
35248
35249
35250
35251
35252
35253
35254
35255
35256
35257
35258
35259
35260
35261
35262
35263
35264
35265
35266
35267
35268
35269
35270
35271
35272
35273
35274
35275
35276
35277
35278
35279
35280
35281
35282
35283
35284
35285
35286
35287
35288
35289
35290
35291
35292
35293
35294
35295
35296
35297
35298
35299
35300
35301
35302
35303
35304
35305
35306
35307
35308
35309
35310
35311
35312
35313
35314
35315
35316
35317
35318
35319
35320
35321
35322
35323
35324
35325
35326
35327
35328
35329
35330
35331
35332
35333
35334
35335
35336
35337
35338
35339
35340
35341
35342
35343
35344
35345
35346
35347
35348
35349
35350
35351
35352
35353
35354
35355
35356
35357
35358
35359
35360
35361
35362
35363
35364
35365
35366
35367
35368
35369
35370
35371
35372
35373
35374
35375
35376
35377
35378
35379
35380
35381
35382
35383
35384
35385
35386
35387
35388
35389
35390
35391
35392
35393
35394
35395
35396
35397
35398
35399
35400
35401
35402
35403
35404
35405
35406
35407
35408
35409
35410
35411
35412
35413
35414
35415
35416
35417
35418
35419
35420
35421
35422
35423
35424
35425
35426
35427
35428
35429
35430
35431
35432
35433
35434
35435
35436
35437
35438
35439
35440
35441
35442
35443
35444
35445
35446
35447
35448
35449
35450
35451
35452
35453
35454
35455
35456
35457
35458
35459
35460
35461
35462
35463
35464
35465
35466
35467
35468
35469
35470
35471
35472
35473
35474
35475
35476
35477
35478
35479
35480
35481
35482
35483
35484
35485
35486
35487
35488
35489
35490
35491
35492
35493
35494
35495
35496
35497
35498
35499
35500
35501
35502
35503
35504
35505
35506
35507
35508
35509
35510
35511
35512
35513
35514
35515
35516
35517
35518
35519
35520
35521
35522
35523
35524
35525
35526
35527
35528
35529
35530
35531
35532
35533
35534
35535
35536
35537
35538
35539
35540
35541
35542
35543
35544
35545
35546
35547
35548
35549
35550
35551
35552
35553
35554
35555
35556
35557
35558
35559
35560
35561
35562
35563
35564
35565
35566
35567
35568
35569
35570
35571
35572
35573
35574
35575
35576
35577
35578
35579
35580
35581
35582
35583
35584
35585
35586
35587
35588
35589
35590
35591
35592
35593
35594
35595
35596
35597
35598
35599
35600
35601
35602
35603
35604
35605
35606
35607
35608
35609
35610
35611
35612
35613
35614
35615
35616
35617
35618
35619
35620
35621
35622
35623
35624
35625
35626
35627
35628
35629
35630
35631
35632
35633
35634
35635
35636
35637
35638
35639
35640
35641
35642
35643
35644
35645
35646
35647
35648
35649
35650
35651
35652
35653
35654
35655
35656
35657
35658
35659
35660
35661
35662
35663
35664
35665
35666
35667
35668
35669
35670
35671
35672
35673
35674
35675
35676
35677
35678
35679
35680
35681
35682
35683
35684
35685
35686
35687
35688
35689
35690
35691
35692
35693
35694
35695
35696
35697
35698
35699
35700
35701
35702
35703
35704
35705
35706
35707
35708
35709
35710
35711
35712
35713
35714
35715
35716
35717
35718
35719
35720
35721
35722
35723
35724
35725
35726
35727
35728
35729
35730
35731
35732
35733
35734
35735
35736
35737
35738
35739
35740
35741
35742
35743
35744
35745
35746
35747
35748
35749
35750
35751
35752
35753
35754
35755
35756
35757
35758
35759
35760
35761
35762
35763
35764
35765
35766
35767
35768
35769
35770
35771
35772
35773
35774
35775
35776
35777
35778
35779
35780
35781
35782
35783
35784
35785
35786
35787
35788
35789
35790
35791
35792
35793
35794
35795
35796
35797
35798
35799
35800
35801
35802
35803
35804
35805
35806
35807
35808
35809
35810
35811
35812
35813
35814
35815
35816
35817
35818
35819
35820
35821
35822
35823
35824
35825
35826
35827
35828
35829
35830
35831
35832
35833
35834
35835
35836
35837
35838
35839
35840
35841
35842
35843
35844
35845
35846
35847
35848
35849
35850
35851
35852
35853
35854
35855
35856
35857
35858
35859
35860
35861
35862
35863
35864
35865
35866
35867
35868
35869
35870
35871
35872
35873
35874
35875
35876
35877
35878
35879
35880
35881
35882
35883
35884
35885
35886
35887
35888
35889
35890
35891
35892
35893
35894
35895
35896
35897
35898
35899
35900
35901
35902
35903
35904
35905
35906
35907
35908
35909
35910
35911
35912
35913
35914
35915
35916
35917
35918
35919
35920
35921
35922
35923
35924
35925
35926
35927
35928
35929
35930
35931
35932
35933
35934
35935
35936
35937
35938
35939
35940
35941
35942
35943
35944
35945
35946
35947
35948
35949
35950
35951
35952
35953
35954
35955
35956
35957
35958
35959
35960
35961
35962
35963
35964
35965
35966
35967
35968
35969
35970
35971
35972
35973
35974
35975
35976
35977
35978
35979
35980
35981
35982
35983
35984
35985
35986
35987
35988
35989
35990
35991
35992
35993
35994
35995
35996
35997
35998
35999
36000
36001
36002
36003
36004
36005
36006
36007
36008
36009
36010
36011
36012
36013
36014
36015
36016
36017
36018
36019
36020
36021
36022
36023
36024
36025
36026
36027
36028
36029
36030
36031
36032
36033
36034
36035
36036
36037
36038
36039
36040
36041
36042
36043
36044
36045
36046
36047
36048
36049
36050
36051
36052
36053
36054
36055
36056
36057
36058
36059
36060
36061
36062
36063
36064
36065
36066
36067
36068
36069
36070
36071
36072
36073
36074
36075
36076
36077
36078
36079
36080
36081
36082
36083
36084
36085
36086
36087
36088
36089
36090
36091
36092
36093
36094
36095
36096
36097
36098
36099
36100
36101
36102
36103
36104
36105
36106
36107
36108
36109
36110
36111
36112
36113
36114
36115
36116
36117
36118
36119
36120
36121
36122
36123
36124
36125
36126
36127
36128
36129
36130
36131
36132
36133
36134
36135
36136
36137
36138
36139
36140
36141
36142
36143
36144
36145
36146
36147
36148
36149
36150
36151
36152
36153
36154
36155
36156
36157
36158
36159
36160
36161
36162
36163
36164
36165
36166
36167
36168
36169
36170
36171
36172
36173
36174
36175
36176
36177
36178
36179
36180
36181
36182
36183
36184
36185
36186
36187
36188
36189
36190
36191
36192
36193
36194
36195
36196
36197
36198
36199
36200
36201
36202
36203
36204
36205
36206
36207
36208
36209
36210
36211
36212
36213
36214
36215
36216
36217
36218
36219
36220
36221
36222
36223
36224
36225
36226
36227
36228
36229
36230
36231
36232
36233
36234
36235
36236
36237
36238
36239
36240
36241
36242
36243
36244
36245
36246
36247
36248
36249
36250
36251
36252
36253
36254
36255
36256
36257
36258
36259
36260
36261
36262
36263
36264
36265
36266
36267
36268
36269
36270
36271
36272
36273
36274
36275
36276
36277
36278
36279
36280
36281
36282
36283
36284
36285
36286
36287
36288
36289
36290
36291
36292
36293
36294
36295
36296
36297
36298
36299
36300
36301
36302
36303
36304
36305
36306
36307
36308
36309
36310
36311
36312
36313
36314
36315
36316
36317
36318
36319
36320
36321
36322
36323
36324
36325
36326
36327
36328
36329
36330
36331
36332
36333
36334
36335
36336
36337
36338
36339
36340
36341
36342
36343
36344
36345
36346
36347
36348
36349
36350
36351
36352
36353
36354
36355
36356
36357
36358
36359
36360
36361
36362
36363
36364
36365
36366
36367
36368
36369
36370
36371
36372
36373
36374
36375
36376
36377
36378
36379
36380
36381
36382
36383
36384
36385
36386
36387
36388
36389
36390
36391
36392
36393
36394
36395
36396
36397
36398
36399
36400
36401
36402
36403
36404
36405
36406
36407
36408
36409
36410
36411
36412
36413
36414
36415
36416
36417
36418
36419
36420
36421
36422
36423
36424
36425
36426
36427
36428
36429
36430
36431
36432
36433
36434
36435
36436
36437
36438
36439
36440
36441
36442
36443
36444
36445
36446
36447
36448
36449
36450
36451
36452
36453
36454
36455
36456
36457
36458
36459
36460
36461
36462
36463
36464
36465
36466
36467
36468
36469
36470
36471
36472
36473
36474
36475
36476
36477
36478
36479
36480
36481
36482
36483
36484
36485
36486
36487
36488
36489
36490
36491
36492
36493
36494
36495
36496
36497
36498
36499
36500
36501
36502
36503
36504
36505
36506
36507
36508
36509
36510
36511
36512
36513
36514
36515
36516
36517
36518
36519
36520
36521
36522
36523
36524
36525
36526
36527
36528
36529
36530
36531
36532
36533
36534
36535
36536
36537
36538
36539
36540
36541
36542
36543
36544
36545
36546
36547
36548
36549
36550
36551
36552
36553
36554
36555
36556
36557
36558
36559
36560
36561
36562
36563
36564
36565
36566
36567
36568
36569
36570
36571
36572
36573
36574
36575
36576
36577
36578
36579
36580
36581
36582
36583
36584
36585
36586
36587
36588
36589
36590
36591
36592
36593
36594
36595
36596
36597
36598
36599
36600
36601
36602
36603
36604
36605
36606
36607
36608
36609
36610
36611
36612
36613
36614
36615
36616
36617
36618
36619
36620
36621
36622
36623
36624
36625
36626
36627
36628
36629
36630
36631
36632
36633
36634
36635
36636
36637
36638
36639
36640
36641
36642
36643
36644
36645
36646
36647
36648
36649
36650
36651
36652
36653
36654
36655
36656
36657
36658
36659
36660
36661
36662
36663
36664
36665
36666
36667
36668
36669
36670
36671
36672
36673
36674
36675
36676
36677
36678
36679
36680
36681
36682
36683
36684
36685
36686
36687
36688
36689
36690
36691
36692
36693
36694
36695
36696
36697
36698
36699
36700
36701
36702
36703
36704
36705
36706
36707
36708
36709
36710
36711
36712
36713
36714
36715
36716
36717
36718
36719
36720
36721
36722
36723
36724
36725
36726
36727
36728
36729
36730
36731
36732
36733
36734
36735
36736
36737
36738
36739
36740
36741
36742
36743
36744
36745
36746
36747
36748
36749
36750
36751
36752
36753
36754
36755
36756
36757
36758
36759
36760
36761
36762
36763
36764
36765
36766
36767
36768
36769
36770
36771
36772
36773
36774
36775
36776
36777
36778
36779
36780
36781
36782
36783
36784
36785
36786
36787
36788
36789
36790
36791
36792
36793
36794
36795
36796
36797
36798
36799
36800
36801
36802
36803
36804
36805
36806
36807
36808
36809
36810
36811
36812
36813
36814
36815
36816
36817
36818
36819
36820
36821
36822
36823
36824
36825
36826
36827
36828
36829
36830
36831
36832
36833
36834
36835
36836
36837
36838
36839
36840
36841
36842
36843
36844
36845
36846
36847
36848
36849
36850
36851
36852
36853
36854
36855
36856
36857
36858
36859
36860
36861
36862
36863
36864
36865
36866
36867
36868
36869
36870
36871
36872
36873
36874
36875
36876
36877
36878
36879
36880
36881
36882
36883
36884
36885
36886
36887
36888
36889
36890
36891
36892
36893
36894
36895
36896
36897
36898
36899
36900
36901
36902
36903
36904
36905
36906
36907
36908
36909
36910
36911
36912
36913
36914
36915
36916
36917
36918
36919
36920
36921
36922
36923
36924
36925
36926
36927
36928
36929
36930
36931
36932
36933
36934
36935
36936
36937
36938
36939
36940
36941
36942
36943
36944
36945
36946
36947
36948
36949
36950
36951
36952
36953
36954
36955
36956
36957
36958
36959
36960
36961
36962
36963
36964
36965
36966
36967
36968
36969
36970
36971
36972
36973
36974
36975
36976
36977
36978
36979
36980
36981
36982
36983
36984
36985
36986
36987
36988
36989
36990
36991
36992
36993
36994
36995
36996
36997
36998
36999
37000
37001
37002
37003
37004
37005
37006
37007
37008
37009
37010
37011
37012
37013
37014
37015
37016
37017
37018
37019
37020
37021
37022
37023
37024
37025
37026
37027
37028
37029
37030
37031
37032
37033
37034
37035
37036
37037
37038
37039
37040
37041
37042
37043
37044
37045
37046
37047
37048
37049
37050
37051
37052
37053
37054
37055
37056
37057
37058
37059
37060
37061
37062
37063
37064
37065
37066
37067
37068
37069
37070
37071
37072
37073
37074
37075
37076
37077
37078
37079
37080
37081
37082
37083
37084
37085
37086
37087
37088
37089
37090
37091
37092
37093
37094
37095
37096
37097
37098
37099
37100
37101
37102
37103
37104
37105
37106
37107
37108
37109
37110
37111
37112
37113
37114
37115
37116
37117
37118
37119
37120
37121
37122
37123
37124
37125
37126
37127
37128
37129
37130
37131
37132
37133
37134
37135
37136
37137
37138
37139
37140
37141
37142
37143
37144
37145
37146
37147
37148
37149
37150
37151
37152
37153
37154
37155
37156
37157
37158
37159
37160
37161
37162
37163
37164
37165
37166
37167
37168
37169
37170
37171
37172
37173
37174
37175
37176
37177
37178
37179
37180
37181
37182
37183
37184
37185
37186
37187
37188
37189
37190
37191
37192
37193
37194
37195
37196
37197
37198
37199
37200
37201
37202
37203
37204
37205
37206
37207
37208
37209
37210
37211
37212
37213
37214
37215
37216
37217
37218
37219
37220
37221
37222
37223
37224
37225
37226
37227
37228
37229
37230
37231
37232
37233
37234
37235
37236
37237
37238
37239
37240
37241
37242
37243
37244
37245
37246
37247
37248
37249
37250
37251
37252
37253
37254
37255
37256
37257
37258
37259
37260
37261
37262
37263
37264
37265
37266
37267
37268
37269
37270
37271
37272
37273
37274
37275
37276
37277
37278
37279
37280
37281
37282
37283
37284
37285
37286
37287
37288
37289
37290
37291
37292
37293
37294
37295
37296
37297
37298
37299
37300
37301
37302
37303
37304
37305
37306
37307
37308
37309
37310
37311
37312
37313
37314
37315
37316
37317
37318
37319
37320
37321
37322
37323
37324
37325
37326
37327
37328
37329
37330
37331
37332
37333
37334
37335
37336
37337
37338
37339
37340
37341
37342
37343
37344
37345
37346
37347
37348
37349
37350
37351
37352
37353
37354
37355
37356
37357
37358
37359
37360
37361
37362
37363
37364
37365
37366
37367
37368
37369
37370
37371
37372
37373
37374
37375
37376
37377
37378
37379
37380
37381
37382
37383
37384
37385
37386
37387
37388
37389
37390
37391
37392
37393
37394
37395
37396
37397
37398
37399
37400
37401
37402
37403
37404
37405
37406
37407
37408
37409
37410
37411
37412
37413
37414
37415
37416
37417
37418
37419
37420
37421
37422
37423
37424
37425
37426
37427
37428
37429
37430
37431
37432
37433
37434
37435
37436
37437
37438
37439
37440
37441
37442
37443
37444
37445
37446
37447
37448
37449
37450
37451
37452
37453
37454
37455
37456
37457
37458
37459
37460
37461
37462
37463
37464
37465
37466
37467
37468
37469
37470
37471
37472
37473
37474
37475
37476
37477
37478
37479
37480
37481
37482
37483
37484
37485
37486
37487
37488
37489
37490
37491
37492
37493
37494
37495
37496
37497
37498
37499
37500
37501
37502
37503
37504
37505
37506
37507
37508
37509
37510
37511
37512
37513
37514
37515
37516
37517
37518
37519
37520
37521
37522
37523
37524
37525
37526
37527
37528
37529
37530
37531
37532
37533
37534
37535
37536
37537
37538
37539
37540
37541
37542
37543
37544
37545
37546
37547
37548
37549
37550
37551
37552
37553
37554
37555
37556
37557
37558
37559
37560
37561
37562
37563
37564
37565
37566
37567
37568
37569
37570
37571
37572
37573
37574
37575
37576
37577
37578
37579
37580
37581
37582
37583
37584
37585
37586
37587
37588
37589
37590
37591
37592
37593
37594
37595
37596
37597
37598
37599
37600
37601
37602
37603
37604
37605
37606
37607
37608
37609
37610
37611
37612
37613
37614
37615
37616
37617
37618
37619
37620
37621
37622
37623
37624
37625
37626
37627
37628
37629
37630
37631
37632
37633
37634
37635
37636
37637
37638
37639
37640
37641
37642
37643
37644
37645
37646
37647
37648
37649
37650
37651
37652
37653
37654
37655
37656
37657
37658
37659
37660
37661
37662
37663
37664
37665
37666
37667
37668
37669
37670
37671
37672
37673
37674
37675
37676
37677
37678
37679
37680
37681
37682
37683
37684
37685
37686
37687
37688
37689
37690
37691
37692
37693
37694
37695
37696
37697
37698
37699
37700
37701
37702
37703
37704
37705
37706
37707
37708
37709
37710
37711
37712
37713
37714
37715
37716
37717
37718
37719
37720
37721
37722
37723
37724
37725
37726
37727
37728
37729
37730
37731
37732
37733
37734
37735
37736
37737
37738
37739
37740
37741
37742
37743
37744
37745
37746
37747
37748
37749
37750
37751
37752
37753
37754
37755
37756
37757
37758
37759
37760
37761
37762
37763
37764
37765
37766
37767
37768
37769
37770
37771
37772
37773
37774
37775
37776
37777
37778
37779
37780
37781
37782
37783
37784
37785
37786
37787
37788
37789
37790
37791
37792
37793
37794
37795
37796
37797
37798
37799
37800
37801
37802
37803
37804
37805
37806
37807
37808
37809
37810
37811
37812
37813
37814
37815
37816
37817
37818
37819
37820
37821
37822
37823
37824
37825
37826
37827
37828
37829
37830
37831
37832
37833
37834
37835
/* asn.c
 *
 * Copyright (C) 2006-2023 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 2 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
 */

/*
 * DESCRIPTION
 * This library provides the interface to Abstract Syntax Notation One (ASN.1)
 * objects.
 * ASN.1 is a standard interface description language for defining data
 * structures that can be serialized and deserialized in a cross-platform way.
 *
 * Encoding of ASN.1 is either using Basic Encoding Rules (BER) or
 * Distinguished Encoding Rules (DER). DER has only one possible encoding for a
 * ASN.1 description and the data.
 * Encode using DER and decode BER or DER.
 *
 * Provides routines to convert BER into DER. Replaces indefinite length
 * encoded items with explicit lengths.
 */
#ifdef HAVE_CONFIG_H
    #include <config.h>
#endif

#include <wolfssl/wolfcrypt/settings.h>

/*
ASN Options:
 * NO_ASN_TIME_CHECK: Disables ASN time checks (avoiding the ASN_BEFORE_DATE_E
 * and ASN_AFTER_DATE_E errors). Safer ways to avoid date errors would be to
 * set the WOLFSSL_LOAD_FLAG_DATE_ERR_OKAY flag when calling the _ex versions of
 * cert loading functions or to define the WOLFSSL_NO_OCSP_DATE_CHECK macro to
 * skip OCSP date errors. Defining NO_ASN_TIME_CHECK will skip ALL date checks
 * and could pose a security risk.
 * NO_ASN_TIME: Disables time parts of the ASN code for systems without an RTC
    or wishing to save space.
 * IGNORE_NAME_CONSTRAINTS: Skip ASN name checks.
 * ASN_DUMP_OID: Allows dump of OID information for debugging.
 * RSA_DECODE_EXTRA: Decodes extra information in RSA public key.
 * WOLFSSL_CERT_GEN: Cert generation. Saves extra certificate info in GetName.
 * WOLFSSL_NO_ASN_STRICT: Disable strict RFC compliance checks to
    restore 3.13.0 behavior.
 * WOLFSSL_NO_OCSP_OPTIONAL_CERTS: Skip optional OCSP certs (responder issuer
    must still be trusted)
 * WOLFSSL_NO_TRUSTED_CERTS_VERIFY: Workaround for situation where entire cert
    chain is not loaded. This only matches on subject and public key and
    does not perform a PKI validation, so it is not a secure solution.
    Only enabled for OCSP.
 * WOLFSSL_NO_OCSP_ISSUER_CHECK: Can be defined for backwards compatibility to
    disable checking of OCSP subject hash with issuer hash.
 * WOLFSSL_SMALL_CERT_VERIFY: Verify the certificate signature without using
    DecodedCert. Doubles up on some code but allows smaller dynamic memory
    usage.
 * WOLFSSL_NO_OCSP_DATE_CHECK: Disable date checks for OCSP responses. This
    may be required when the system's real-time clock is not very accurate.
    It is recommended to enforce the nonce check instead if possible.
 * WOLFSSL_FORCE_OCSP_NONCE_CHECK: Require nonces to be available in OCSP
    responses. The nonces are optional and may not be supported by all
    responders. If it can be ensured that the used responder sends nonces this
    option may improve security.
 * WOLFSSL_ASN_TEMPLATE: Encoding and decoding using a template.
 * WOLFSSL_DEBUG_ASN_TEMPLATE: Enables debugging output when using ASN.1
    templates.
 * WOLFSSL_ASN_TEMPLATE_TYPE_CHECK: Use ASN functions to better test compiler
    type issues for testing
 * CRLDP_VALIDATE_DATA: For ASN template only, validates the reason data
 * WOLFSSL_AKID_NAME: Enable support for full AuthorityKeyIdentifier extension.
    Only supports copying full AKID from an existing certificate.
 * WOLFSSL_CUSTOM_OID: Enable custom OID support for subject and request
    extensions
 * WOLFSSL_HAVE_ISSUER_NAMES: Store pointers to issuer name components and their
    lengths and encodings.
 * WOLFSSL_SUBJ_DIR_ATTR: Enable support for SubjectDirectoryAttributes
    extension.
 * WOLFSSL_SUBJ_INFO_ACC: Enable support for SubjectInfoAccess extension.
 * WOLFSSL_FPKI: Enable support for FPKI (Federal PKI) extensions.
 * WOLFSSL_CERT_NAME_ALL: Adds more certificate name capability at the
    cost of taking up more memory. Adds initials, givenname, dnQualifer for
    example.
 * WC_ASN_HASH_SHA256: Force use of SHA2-256 for the internal hash ID calcs.
*/

#include <wolfssl/wolfcrypt/error-crypt.h>
#ifndef NO_RSA
    #include <wolfssl/wolfcrypt/rsa.h>
    #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
        extern int wc_InitRsaHw(RsaKey* key);
    #endif
#endif

#ifndef NO_ASN

#include <wolfssl/wolfcrypt/asn.h>
#include <wolfssl/wolfcrypt/coding.h>
#include <wolfssl/wolfcrypt/md2.h>
#include <wolfssl/wolfcrypt/hmac.h>
#include <wolfssl/wolfcrypt/pwdbased.h>
#include <wolfssl/wolfcrypt/des3.h>
#include <wolfssl/wolfcrypt/aes.h>
#include <wolfssl/wolfcrypt/rc2.h>
#include <wolfssl/wolfcrypt/wc_encrypt.h>
#include <wolfssl/wolfcrypt/logging.h>

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

#ifndef NO_RC4
    #include <wolfssl/wolfcrypt/arc4.h>
#endif

#if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384)
    #include <wolfssl/wolfcrypt/sha512.h>
#endif

#ifndef NO_SHA256
    #include <wolfssl/wolfcrypt/sha256.h>
#endif

#ifdef HAVE_ECC
    #include <wolfssl/wolfcrypt/ecc.h>
#endif

#ifdef HAVE_ED25519
    #include <wolfssl/wolfcrypt/ed25519.h>
#endif
#ifdef HAVE_CURVE25519
    #include <wolfssl/wolfcrypt/curve25519.h>
#endif

#ifdef HAVE_ED448
    #include <wolfssl/wolfcrypt/ed448.h>
#endif
#ifdef HAVE_CURVE448
    #include <wolfssl/wolfcrypt/curve448.h>
#endif

#ifdef HAVE_PQC
    #if defined(HAVE_FALCON)
    #include <wolfssl/wolfcrypt/falcon.h>
    #endif
    #if defined(HAVE_DILITHIUM)
    #include <wolfssl/wolfcrypt/dilithium.h>
    #endif
    #if defined(HAVE_SPHINCS)
    #include <wolfssl/wolfcrypt/sphincs.h>
    #endif
#endif

#ifdef WOLFSSL_QNX_CAAM
    #include <wolfssl/wolfcrypt/port/caam/wolfcaam.h>
#endif

#if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_TSIP_TLS)
    #include <wolfssl/wolfcrypt/port/Renesas/renesas_cmn.h>
#endif

#ifndef NO_DSA
    #include <wolfssl/wolfcrypt/dsa.h>
#else
    typedef void* DsaKey;
#endif

#ifdef WOLF_CRYPTO_CB
    #include <wolfssl/wolfcrypt/cryptocb.h>
#endif

#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
    #include <wolfssl/internal.h>
    #include <wolfssl/openssl/objects.h>
#endif

#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
        !defined(WOLFCRYPT_ONLY)
    #define WOLFSSL_X509_NAME_AVAILABLE
#endif

#ifdef _MSC_VER
    /* 4996 warning to use MS extensions e.g., strcpy_s instead of XSTRNCPY */
    #pragma warning(disable: 4996)
#endif

#define ERROR_OUT(err, eLabel) { ret = (err); goto eLabel; }

#if !defined(NO_SKID) && (!defined(HAVE_FIPS) || !defined(HAVE_FIPS_VERSION))
    #if !defined(HAVE_SELFTEST) || (defined(HAVE_SELFTEST) && \
                                   (!defined(HAVE_SELFTEST_VERSION) || \
                                    HAVE_SELFTEST_VERSION < 2))
    #ifndef WOLFSSL_AES_KEY_SIZE_ENUM
    #define WOLFSSL_AES_KEY_SIZE_ENUM
    enum Asn_Misc {
        AES_IV_SIZE         = 16,
        AES_128_KEY_SIZE    = 16,
        AES_192_KEY_SIZE    = 24,
        AES_256_KEY_SIZE    = 32
    };
    #endif
    #endif /* HAVE_SELFTEST */
#endif

#if defined(WOLFSSL_ASN_PRINT) || defined(WOLFSSL_DEBUG_ASN_TEMPLATE)

/* String representations of tags. */
static const char* tagString[4][32] = {
    /* Universal */
    {
        "EOC",
        "BOOLEAN",
        "INTEGER",
        "BIT STRING",
        "OCTET STRING",
        "NULL",
        "OBJECT ID",
        "ObjectDescriptor",
        "INSTANCE OF",
        "REAL",
        "ENUMERATED",
        "EMBEDDED PDV",
        "UT8String",
        "RELATIVE-OID",
        "(0x0e) 14",
        "(0x0f) 15",
        "SEQUENCE",
        "SET",
        "NumericString",
        "PrintableString",
        "T61String",
        "VideotexString",
        "IA5String",
        "UTCTime",
        "GeneralizedTime",
        "GraphicString",
        "ISO646String",
        "GeneralString",
        "UniversalString",
        "CHARACTER STRING",
        "BMPString",
        "(0x1f) 31",
    },
    /* Application */
    {
         "[A 0]",  "[A 1]",  "[A 2]",  "[A 3]",
         "[A 4]",  "[A 5]",  "[A 6]",  "[A 7]",
         "[A 8]",  "[A 9]", "[A 10]", "[A 11]",
        "[A 12]", "[A 13]", "[A 14]", "[A 15]",
        "[A 16]", "[A 17]", "[A 18]", "[A 19]",
        "[A 20]", "[A 21]", "[A 22]", "[A 23]",
        "[A 24]", "[A 25]", "[A 26]", "[A 27]",
        "[A 28]", "[A 20]", "[A 30]", "[A 31]"
    },
    /* Context-Specific */
    {
         "[0]",  "[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]", "[20]", "[30]", "[31]"
    },
    /* Private */
    {
         "[P 0]",  "[P 1]",  "[P 2]",  "[P 3]",
         "[P 4]",  "[P 5]",  "[P 6]",  "[P 7]",
         "[P 8]",  "[P 9]", "[P 10]", "[P 11]",
        "[P 12]", "[P 13]", "[P 14]", "[P 15]",
        "[P 16]", "[P 17]", "[P 18]", "[P 19]",
        "[P 20]", "[P 21]", "[P 22]", "[P 23]",
        "[P 24]", "[P 25]", "[P 26]", "[P 27]",
        "[P 28]", "[P 20]", "[P 30]", "[P 31]"
    }
};

/* Converts a tag byte to string.
 *
 * @param [in] tag  BER tag value to interpret.
 * @return  String corresponding to tag.
 */
static const char* TagString(byte tag)
{
    return tagString[tag >> 6][tag & ASN_TYPE_MASK];
}

#endif


/* Calculates the minimum number of bytes required to encode the value.
 *
 * Only support up to 2^24-1.
 *
 * @param [in] value  Value to be encoded.
 * @return  Number of bytes to encode value.
 */
static word32 BytePrecision(word32 value)
{
    word32 i;
    for (i = (word32)sizeof(value) - 1; i; --i)
        if (value >> ((i - 1) * WOLFSSL_BIT_SIZE))
            break;

    return i;
}

/* DER encodes the length value in output buffer.
 *
 *    0 ->  2^7-1: <len byte>.
 *  2^7 ->       : <0x80 + #bytes> <len big-endian bytes>
 *
 * @param [in]      length  Value to encode.
 * @param [in, out] output  Buffer to encode into.
 * @return  Number of bytes used in encoding.
 */
WOLFSSL_LOCAL word32 SetASNLength(word32 length, byte* output)
{
    word32 i = 0;

    if (length < ASN_LONG_LENGTH)
        output[i++] = (byte)length;
    else {
        word32 j;

        output[i++] = (byte)(BytePrecision(length) | ASN_LONG_LENGTH);

        for (j = BytePrecision(length); j; --j) {
            output[i] = (byte)(length >> ((j - 1) * WOLFSSL_BIT_SIZE));
            i++;
        }
    }

    return i;
}

#ifdef WOLFSSL_ASN_TEMPLATE
/* Calculate the size of a DER encoded length value.
 *
 *    0 ->  2^7-1: <length byte>.
 *  2^7 ->       : <0x80 + #bytes> <big-endian length bytes>
 *
 * @param [in] length  Value to encode.
 * @return  Number of bytes required to encode.
 */
static word32 SizeASNLength(word32 length)
{
    return 1 + ((length >= ASN_LONG_LENGTH) ? BytePrecision(length) : 0);
}

/* Calculate the size of a DER encoded header.
 *
 * Header = Tag | Encoded length
 *
 * @param [in] length  Length value to encode.
 * @return  Number of bytes required to encode a DER header.
 */
#define SizeASNHeader(length) \
    (1 + SizeASNLength(length))
#endif

#ifdef WOLFSSL_ASN_TEMPLATE
#ifdef WOLFSSL_SMALL_STACK
    /* Declare the variable that is the dynamic data for decoding BER data.
     *
     * @param [in] name  Variable name to declare.
     * @param [in] cnt   Number of elements required.
     */
    #define DECL_ASNGETDATA(name, cnt)                                         \
        ASNGetData* name = NULL

    /* Allocates the dynamic BER decoding data.
     *
     * @param [in]      name  Variable name to declare.
     * @param [in]      cnt   Number of elements required.
     * @param [in, out] err   Error variable.
     * @param [in]      heap  Dynamic memory allocation hint.
     */
    #define ALLOC_ASNGETDATA(name, cnt, err, heap)                             \
    do {                                                                       \
        if ((err) == 0) {                                                      \
            (name) = (ASNGetData*)XMALLOC(sizeof(ASNGetData) * (cnt), (heap),  \
                                        DYNAMIC_TYPE_TMP_BUFFER);              \
            if ((name) == NULL) {                                              \
                (err) = MEMORY_E;                                              \
            }                                                                  \
        }                                                                      \
    }                                                                          \
    while (0)

    /* Allocates the dynamic BER decoding data and clears the memory.
     *
     * @param [in]      name  Variable name to declare.
     * @param [in]      cnt   Number of elements required.
     * @param [in, out] err   Error variable.
     * @param [in]      heap  Dynamic memory allocation hint.
     */
    #define CALLOC_ASNGETDATA(name, cnt, err, heap)                            \
    do {                                                                       \
        ALLOC_ASNGETDATA(name, cnt, err, heap);                                \
        if ((err) == 0) {                                                      \
            XMEMSET((name), 0, sizeof(ASNGetData) * (cnt));                    \
        }                                                                      \
    }                                                                          \
    while (0)

    /* Disposes of the dynamic BER decoding data.
     *
     * @param [in]      name  Variable name to declare.
     * @param [in]      heap  Dynamic memory allocation hint.
     */
    #define FREE_ASNGETDATA(name, heap)                                        \
    do {                                                                       \
        if ((name) != NULL) {                                                  \
            XFREE((name), (heap), DYNAMIC_TYPE_TMP_BUFFER);                    \
        }                                                                      \
    }                                                                          \
    while (0)

    /* Declare the variable that is the dynamic data for encoding DER data.
     *
     * @param [in] name  Variable name to declare.
     * @param [in] cnt   Number of elements required.
     */
    #define DECL_ASNSETDATA(name, cnt)                                         \
        ASNSetData* name = NULL

    /* Allocates the dynamic DER encoding data.
     *
     * @param [in]      name  Variable name to declare.
     * @param [in]      cnt   Number of elements required.
     * @param [in, out] err   Error variable.
     * @param [in]      heap  Dynamic memory allocation hint.
     */
    #define ALLOC_ASNSETDATA(name, cnt, err, heap)                             \
    do {                                                                       \
        if ((err) == 0) {                                                      \
            (name) = (ASNSetData*)XMALLOC(sizeof(ASNGetData) * (cnt), (heap),  \
                                    DYNAMIC_TYPE_TMP_BUFFER);                  \
            if ((name) == NULL) {                                              \
                (err) = MEMORY_E;                                              \
            }                                                                  \
        }                                                                      \
    }                                                                          \
    while (0)

    /* Allocates the dynamic DER encoding data and clears the memory.
     *
     * @param [in]      name  Variable name to declare.
     * @param [in]      cnt   Number of elements required.
     * @param [in, out] err   Error variable.
     * @param [in]      heap  Dynamic memory allocation hint.
     */
    #define CALLOC_ASNSETDATA(name, cnt, err, heap)                            \
    do {                                                                       \
        ALLOC_ASNSETDATA(name, cnt, err, heap);                                \
        if ((err) == 0) {                                                      \
            XMEMSET(name, 0, sizeof(ASNSetData) * (cnt));                      \
        }                                                                      \
    }                                                                          \
    while (0)

    /* Disposes of the dynamic DER encoding data.
     *
     * @param [in]      name  Variable name to declare.
     * @param [in]      heap  Dynamic memory allocation hint.
     */
    #define FREE_ASNSETDATA(name, heap)                                        \
    do {                                                                       \
        if ((name) != NULL) {                                                  \
            XFREE(name, heap, DYNAMIC_TYPE_TMP_BUFFER);                        \
        }                                                                      \
    }                                                                          \
    while (0)
#else
    /* Declare the variable that is the dynamic data for decoding BER data.
     *
     * @param [in] name  Variable name to declare.
     * @param [in] cnt   Number of elements required.
     */
    #define DECL_ASNGETDATA(name, cnt)                  \
        ASNGetData name[cnt]

    /* No implementation as declaration is static.
     *
     * @param [in]      name  Variable name to declare.
     * @param [in]      cnt   Number of elements required.
     * @param [in, out] err   Error variable.
     * @param [in]      heap  Dynamic memory allocation hint.
     */
    #define ALLOC_ASNGETDATA(name, cnt, err, heap)

    /* Clears the memory of the dynamic BER encoding data.
     *
     * @param [in]      name  Variable name to declare.
     * @param [in]      cnt   Number of elements required.
     * @param [in, out] err   Error variable.
     * @param [in]      heap  Dynamic memory allocation hint.
     */
    #define CALLOC_ASNGETDATA(name, cnt, err, heap)     \
        XMEMSET(name, 0, sizeof(name))

    /* No implementation as declaration is static.
     *
     * @param [in]      name  Variable name to declare.
     * @param [in]      heap  Dynamic memory allocation hint.
     */
    #define FREE_ASNGETDATA(name, heap)

    /* Declare the variable that is the dynamic data for encoding DER data.
     *
     * @param [in] name  Variable name to declare.
     * @param [in] cnt   Number of elements required.
     */
    #define DECL_ASNSETDATA(name, cnt)                  \
        ASNSetData name[cnt]

    /* No implementation as declaration is static.
     *
     * @param [in]      name  Variable name to declare.
     * @param [in]      cnt   Number of elements required.
     * @param [in, out] err   Error variable.
     * @param [in]      heap  Dynamic memory allocation hint.
     */
    #define ALLOC_ASNSETDATA(name, cnt, err, heap)

    /* Clears the memory of the dynamic BER encoding data.
     *
     * @param [in]      name  Variable name to declare.
     * @param [in]      cnt   Number of elements required.
     * @param [in, out] err   Error variable.
     * @param [in]      heap  Dynamic memory allocation hint.
     */
    #define CALLOC_ASNSETDATA(name, cnt, err, heap)     \
        XMEMSET(name, 0, sizeof(name))

    /* No implementation as declaration is static.
     *
     * @param [in]      name  Variable name to declare.
     * @param [in]      heap  Dynamic memory allocation hint.
     */
    #define FREE_ASNSETDATA(name, heap)
#endif


#ifdef DEBUG_WOLFSSL
    /* Enable this when debugging the parsing or creation of ASN.1 data. */
    #if 0
        #define WOLFSSL_DEBUG_ASN_TEMPLATE
    #endif
#endif

#ifdef WOLFSSL_DEBUG_ASN_TEMPLATE

#include <stdarg.h>

/* Log a message that has the printf format string.
 *
 * @param [in] <va_args>  printf style arguments.
 */
#define WOLFSSL_MSG_VSNPRINTF(...)                    \
    do {                                              \
      char line[81];                                  \
      snprintf(line, sizeof(line) - 1, __VA_ARGS__);  \
      line[sizeof(line) - 1] = '\0';                  \
      WOLFSSL_MSG(line);                              \
    }                                                 \
    while (0)
#endif

/* Returns whether ASN.1 item is an integer and the Most-Significant Bit is set.
 *
 * @param [in] asn     ASN.1 items to encode.
 * @param [in] data_a  Data to place in each item. Lengths set were not known.
 * @param [in] i       Index of item to check.
 * @return  1 when ASN.1 item is an integer and MSB is 1.
 * @erturn  0 otherwise.
 */
#define ASNIntMSBSet(asn, data_a, i)                  \
    (((asn)[i].tag == ASN_INTEGER) &&                 \
      ((data_a)[i].data.buffer.data != NULL &&        \
      ((data_a)[i].data.buffer.data[0] & 0x80) == 0x80))


/* Calculate the size of a DER encoded number.
 *
 * @param [in] n     Number to be encoded.
 * @param [in] bits  Maximum number of bits to encode.
 * @param [in] tag   BER tag e.g. INTEGER, BIT_STRING, etc.
 * @return  Number of bytes to the ASN.1 item.
 */
static word32 SizeASN_Num(word32 n, int bits, byte tag)
{
    int    j;
    word32 len;

    len = 1 + 1 + (word32)bits / 8;
    /* Discover actual size by checking for high zeros. */
    for (j = bits - 8; j > 0; j -= 8) {
        if (n >> j)
            break;
        len--;
    }
    if (tag == ASN_BIT_STRING)
        len++;
    else if ((tag == ASN_INTEGER) && (((n >> j) & 0x80) == 0x80))
        len++;

    return len;
}

/* Calculate the size of the data in the constructed item based on the
 * length of the ASN.1 items below.
 *
 * @param [in]      asn    ASN.1 items to encode.
 * @param [in, out] data   Data to place in each item. Lengths set were not
 *                         known.
 * @param [in]      idx    Index of item working on.
 */
static void SizeASN_CalcDataLength(const ASNItem* asn, ASNSetData *data,
                                   int idx, int max)
{
    int j;

    data[idx].data.buffer.length = 0;
    /* Sum the item length of all items underneath. */
    for (j = idx + 1; j < max; j++) {
        /* Stop looking if the next ASN.1 is same level or higher. */
        if (asn[j].depth <= asn[idx].depth)
            break;
        /* Only add in length if it is one level below. */
        if (asn[j].depth - 1 == asn[idx].depth) {
            data[idx].data.buffer.length += data[j].length;
            /* The length of a header only item doesn't include the data unless
             * a replacement buffer is supplied.
             */
            if (asn[j].headerOnly && data[j].data.buffer.data == NULL &&
                    data[j].dataType != ASN_DATA_TYPE_REPLACE_BUFFER) {
                data[idx].data.buffer.length += data[j].data.buffer.length;
            }
        }
    }
}

/* Calculate the size of the DER encoding.
 *
 * Call SetASN_Items() to write encoding to a buffer.
 *
 * @param [in]      asn    ASN.1 items to encode.
 * @param [in, out] data   Data to place in each item. Lengths set where not
 *                         known.
 * @param [in]      count  Count of items to encode.
 * @param [out]     encSz  Length of the DER encoding.
 * @return  0 on success.
 * @return  BAD_STATE_E when the data type is not supported.
 */
int SizeASN_Items(const ASNItem* asn, ASNSetData *data, int count, int* encSz)
{
    int    i;
    word32 sz = 0;
    word32 len;
    word32 dataLen;
    int    length;

#ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
    WOLFSSL_ENTER("SizeASN_Items");
#endif

    for (i = count - 1; i >= 0; i--) {
        /* Skip this ASN.1 item when encoding. */
        if (data[i].noOut) {
            /* Set the offset to the current size - used in writing DER. */
            data[i].offset = sz;
            continue;
        }

        len = 0;
        switch (data[i].dataType) {
            /* Calculate the size of the number of different sizes. */
            case ASN_DATA_TYPE_WORD8:
                len = SizeASN_Num(data[i].data.u8, 8, asn[i].tag);
                break;
            case ASN_DATA_TYPE_WORD16:
                len = SizeASN_Num(data[i].data.u16, 16, asn[i].tag);
                break;
        #ifdef WOLFSSL_ASN_TEMPLATE_NEED_SET_INT32
            /* Not used yet! */
            case ASN_DATA_TYPE_WORD32:
                len = SizeASN_Num(data[i].data.u32, 32, asn[i].tag);
                break;
        #endif

            case ASN_DATA_TYPE_MP:
                /* Calculate the size of the MP integer data. */
                length = mp_unsigned_bin_size(data[i].data.mp);
                length += mp_leading_bit(data[i].data.mp) ? 1 : 0;
                len = (word32)SizeASNHeader((word32)length) + (word32)length;
                break;

            case ASN_DATA_TYPE_REPLACE_BUFFER:
                /* Buffer is put in directly - use the length. */
                len = data[i].data.buffer.length;
                break;

            case ASN_DATA_TYPE_NONE:
                /* Calculate the size based on the data to be included.
                 * Mostly used for constructed items.
                 */
                if (asn[i].headerOnly) {
                    if (data[i].data.buffer.data != NULL) {
                        /* Force all child nodes to be ignored. Buffer
                         * overwrites children. */
                        {
                            int ii;
                            for (ii = i + 1; ii < count; ii++) {
                                if (asn[ii].depth <= asn[i].depth)
                                    break;
                                sz -= data[ii].length;
                                data[ii].noOut = 1;
                            }
                        }
                    }
                    else {
                        /* Calculate data length from items below if no buffer
                         * supplied. */
                        SizeASN_CalcDataLength(asn, data, i, count);
                    }
                }
                if (asn[i].tag == ASN_BOOLEAN) {
                    dataLen = 1;
                }
                else {
                    dataLen = data[i].data.buffer.length;
                }
                /* BIT_STRING and INTEGER have one byte prepended. */
                if ((asn[i].tag == ASN_BIT_STRING) ||
                                                   ASNIntMSBSet(asn, data, i)) {
                    dataLen++;
                    /* ASN.1 items are below and cannot include extra byte. */
                    if (asn[i].headerOnly) {
                        len++;
                    }
                }
                /* Add in the size of tag and length. */
                len += SizeASNHeader(dataLen);
                /* Include data in length if not header only or if
                 * buffer supplied. */
                if (!asn[i].headerOnly || data[i].data.buffer.data != NULL) {
                    len += dataLen;
                }
                break;

        #ifdef DEBUG_WOLFSSL
            default:
            #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
                WOLFSSL_MSG_VSNPRINTF("%2d: %d", i, data[i].dataType);
                WOLFSSL_MSG("Bad data type");
            #endif
                return BAD_STATE_E;
        #endif
        }

        /* Set the total length of the item. */
        data[i].length = len;
        /* Add length to total size. */
        sz += len;
        /* Set the offset to the current size - used in writing DER. */
        data[i].offset = sz;

    #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
        WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
                data[i].offset, data[i].length, asn[i].constructed ? '+' : ' ',
                asn[i].depth, "", TagString(asn[i].tag));
    #endif
    }

    *encSz = (int)sz;
    return 0;
}

/* Create the DER encoding of a number.
 *
 * Assumes that the out buffer is large enough for encoding.
 *
 * @param [in] n     Number to be encoded.
 * @param [in] bits  Maximum number of bits to encode.
 * @param [in] tag   DER tag e.g. INTEGER, BIT_STRING, etc.
 */
static void SetASN_Num(word32 n, int bits, byte* out, byte tag)
{
    int    j;
    word32 idx;
    byte   len;

    /* Encoding: Tag (1 byte) | Length (1 byte) | Data (number) */

    /* Data will start at index 2 unless BIT_STRING or INTEGER */
    idx = 2;

    /* Set the length of the number based on maximum bit length. */
    len = (byte)(bits / 8);
    /* Discover actual size by checking for leading zero bytes. */
    for (j = bits - 8; j > 0; j -= 8) {
        if ((n >> j) != 0) {
            break;
        }
        len--;
    }
    /* Keep j, index of first non-zero byte, for writing out. */

    /* A BIT_STRING has the number of unused bits in last byte prepended to
     * data.
     */
    if (tag == ASN_BIT_STRING) {
        byte unusedBits = 0;
        byte lastByte = (byte)(n >> j);

        /* Quick check last bit. */
        if ((lastByte & 0x01) == 0x00) {
            unusedBits++;
            /* Check each bit for first least significant bit set. */
            while (((lastByte >> unusedBits) & 0x01) == 0x00)
                unusedBits++;
        }
        /* Add unused bits byte. */
        len++;
        out[idx++] = unusedBits;
    }

    /* An INTEGER has a prepended byte if MSB of number is 1 - makes encoded
     * value positive. */
    if ((tag == ASN_INTEGER) && (((n >> j) & 0x80) == 0x80)) {
        len++;
        out[idx++] = 0;
    }

    /* Go back and put in length. */
    out[1] = len;
    /* Place in the required bytes of the number. */
    for (; j >= 0; j -= 8)
        out[idx++] = (byte)(n >> j);
}

/* Creates the DER encoding of the ASN.1 items.
 *
 * Assumes the output buffer is large enough to hold encoding.
 * Must call SizeASN_Items() to determine size of encoding and offsets.
 *
 * @param [in]      asn     ASN.1 items to encode.
 * @param [in]      data    Data to place in each item.
 * @param [in]      count   Count of items to encode.
 * @param [in, out] output  Buffer to write encoding into.
 * @return  Size of the DER encoding in bytes.
 */
int SetASN_Items(const ASNItem* asn, ASNSetData *data, int count, byte* output)
{
    int    i;
    int    length;
    int    err;
    word32 sz;
    word32 idx;
    byte*  out;

#ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
    WOLFSSL_ENTER("SetASN_Items");
#endif

    /* Offset of first item is the total length.
     * SizeASN_Items() calculated this. */
    sz = data[0].offset;

    /* Write out each item. */
    for (i = 0; i < count; i++) {
        /* Skip items not writing out. */
        if (data[i].noOut)
            continue;

        /* Start position to write item based on reverse offsets. */
        out = output + sz - data[i].offset;
        /* Index from start of item out. */
        idx = 0;

        if (data[i].dataType != ASN_DATA_TYPE_REPLACE_BUFFER) {
            /* Put in the tag - not dumping in DER from buffer. */
            out[idx++] = asn[i].tag |
                         (asn[i].constructed ? ASN_CONSTRUCTED : 0);
        }

    #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
        WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
                sz - data[i].offset,
                data[i].length, asn[i].constructed ? '+' : ' ', asn[i].depth,
                "", TagString(asn[i].tag));
    #endif

        switch (data[i].dataType) {
            /* Write out the length and data of a number. */
            case ASN_DATA_TYPE_WORD8:
                SetASN_Num(data[i].data.u8, 8, out, asn[i].tag);
                break;
            case ASN_DATA_TYPE_WORD16:
                SetASN_Num(data[i].data.u16, 16, out, asn[i].tag);
                break;
        #ifdef WOLFSSL_ASN_TEMPLATE_NEED_SET_INT32
            /* Not used yet! */
            case ASN_DATA_TYPE_WORD32:
                SetASN_Num(data[i].data.u32, 32, out, asn[i].tag);
                break;
        #endif

            /* Write out the length and data of a multi-precision number. */
            case ASN_DATA_TYPE_MP:
                /* Get length in bytes. */
                length = mp_unsigned_bin_size(data[i].data.mp);
                /* Add one for leading zero to make encoding a positive num. */
                length += mp_leading_bit(data[i].data.mp) ? 1 : 0;
                /* Write out length. */
                idx += SetASNLength((word32)length, out + idx);
                /* Write out leading zero to make positive. */
                if (mp_leading_bit(data[i].data.mp)) {
                    out[idx++] = 0;
                }
                /* Encode number in big-endian byte array. */
                err = mp_to_unsigned_bin(data[i].data.mp, out + idx);
                if (err != MP_OKAY) {
                    WOLFSSL_MSG("SetASN_Items: Failed to write mp_int");
                    return MP_TO_E;
                }
                break;

            case ASN_DATA_TYPE_REPLACE_BUFFER:
                if (data[i].data.buffer.data == NULL) {
                    /* Return pointer for caller to use. */
                    data[i].data.buffer.data = out + idx;
                }
                else {
                    /* Dump in the DER encoded data. */
                    XMEMCPY(out + idx, data[i].data.buffer.data,
                            data[i].data.buffer.length);
                }
                break;

            case ASN_DATA_TYPE_NONE:
                if (asn[i].tag == ASN_BOOLEAN) {
                    /* Always one byte of data. */
                    out[idx++] = 1;
                    /* TRUE = 0xff, FALSE = 0x00 */
                    out[idx] = data[i].data.u8 ? 0xffU : 0x00U;
                }
                else if (asn[i].tag == ASN_TAG_NULL) {
                    /* NULL tag is always a zero length item. */
                    out[idx] = 0;
                }
                else {
                    word32 dataLen = data[i].data.buffer.length;
                    /* Add one to data length for BIT_STRING unused bits and
                     * INTEGER leading zero to make positive.
                     */
                    if ((asn[i].tag == ASN_BIT_STRING) ||
                                                   ASNIntMSBSet(asn, data, i)) {
                        dataLen++;
                    }
                    /* Write out length. */
                    idx += SetASNLength(dataLen, out + idx);
                    if ((asn[i].tag == ASN_BIT_STRING) ||
                                                   ASNIntMSBSet(asn, data, i)) {
                       /* Write out leading byte. BIT_STRING has no unused bits
                        * - use number data types if needed. */
                        out[idx++] = 0x00;
                    }
                    /* Record pointer for caller if data not supplied. */
                    if (data[i].data.buffer.data == NULL) {
                        data[i].data.buffer.data = out + idx;
                    }
                    /* Copy supplied data if not putting out header only or
                     * if buffer supplied. */
                    else if (!asn[i].headerOnly ||
                            data[i].data.buffer.data != NULL) {
                        /* Allow data to come from output buffer. */
                        XMEMMOVE(out + idx, data[i].data.buffer.data,
                                 data[i].data.buffer.length);
                    }
                }
                break;

        #ifdef DEBUG_WOLFSSL
            default:
            #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
                WOLFSSL_MSG_VSNPRINTF("Bad data type: %d", data[i].dataType);
            #endif
                return BAD_STATE_E;
        #endif
        }
    }

    return (int)sz;
}


static int GetOID(const byte* input, word32* inOutIdx, word32* oid,
                  word32 oidType, int length);

/* Maximum supported depth in ASN.1 description. */
#define GET_ASN_MAX_DEPTH          7
/* Maximum number of checked numbered choices. Only one of the items with the
 * number is allowed.
 */
#define GET_ASN_MAX_CHOICES        2

/* Use existing function to decode BER length encoding. */
#define GetASN_Length GetLength_ex

/* Check an INTEGER's first byte - must be a positive number.
 *
 * @param [in] input    BER encoded data.
 * @param [in] idx      Index of BIT_STRING data.
 * @param [in] length   Length of input data.
 * @param [in] positive Indicates number must be positive.
 * @return  0 on success.
 * @return  ASN_PARSE_E when 0 is not required but seen.
 * @return  ASN_EXPECT_0_E when 0 is required and not seen.
 */
static int GetASN_Integer(const byte* input, word32 idx, int length,
                          int positive)
{
#if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) || \
    (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
    /* Check contents consist of one or more octets. */
    if (length == 0) {
        WOLFSSL_MSG("Zero length INTEGER not allowed");
        return ASN_PARSE_E;
    }
#endif
    if (input[idx] == 0) {
        /* Check leading zero byte required. */
        if ((length > 1) && ((input[idx + 1] & 0x80) == 0)) {
            WOLFSSL_MSG("Zero not required on INTEGER");
        #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
            return ASN_PARSE_E;
        #endif
        }
    }
    /* Check whether a leading zero byte was required. */
    else if (positive && (input[idx] & 0x80)) {
        WOLFSSL_MSG("INTEGER is negative");
    #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
        return ASN_EXPECT_0_E;
    #endif /* WOLFSSL_ASN_INT_LEAD_0_ANY */
    }

    return 0;
}

/* Check a BIT_STRING's first byte - unused bits.
 *
 * @param [in] input   BER encoded data.
 * @param [in] idx     Index of BIT_STRING data.
 * @param [in] length  Length of input data.
 * @return  0 on success.
 * @return  ASN_PARSE_E when unused bits is invalid.
 */
static int GetASN_BitString(const byte* input, word32 idx, int length)
{
#if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) || \
    (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
    /* Check contents consist of one or more octets. */
    if (length == 0) {
    #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
        WOLFSSL_MSG("Zero length BIT STRING not allowed");
    #endif
        return ASN_PARSE_E;
    }
#endif
    /* Ensure unused bits value is valid range. */
    if (input[idx] > 7) {
    #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
        WOLFSSL_MSG_VSNPRINTF("BIT STRING unused bits too big: %d > 7",
                input[idx]);
    #endif
        return ASN_PARSE_E;
    }
    /* Ensure unused bits are zero. */
    if ((byte)(input[idx + (word32)length - 1] << (8 - input[idx])) != 0) {
    #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
        WOLFSSL_MSG_VSNPRINTF("BIT STRING unused bits used: %d %02x",
                input[idx], input[idx + length - 1]);
    #endif
        return ASN_PARSE_E;
    }

    return 0;
}

/* Get the ASN.1 items from the BER encoding.
 *
 * @param [in] asn         ASN.1 item expected.
 * @param [in] data        Data array to place found item into.
 * @param [in] input       BER encoded data.
 * @param [in] idx         Starting index of item data.
 * @param [in] len         Length of input buffer upto end of this item's data.
 * @param [in] zeroPadded  INTEGER was zero padded to make positive.
 * @return  0 on success.
 * @return  ASN_PARSE_E when BER encoded data is invalid.
 * @return  ASN_EXPECT_0_E when NULL tagged item has a non-zero length.
 * @return  MP_INIT_E when the unable to initialize an mp_int.
 * @return  ASN_GETINT_E when the unable to convert data to an mp_int.
 * @return  BAD_STATE_E when the data type is not supported.
 * @return  ASN_UNKNOWN_OID_E when the OID cannot be verified.
 */
static int GetASN_StoreData(const ASNItem* asn, ASNGetData* data,
                            const byte* input, word32 idx, int len,
                            int zeroPadded)
{
    int i;
    int err;

    /* Parse data based on data type to extract. */
    switch (data->dataType) {
        /* Parse a data into a number of specified bits. */
        case ASN_DATA_TYPE_WORD8:
            /* Check data is small enough to fit. */
            if (len != 1) {
            #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
                WOLFSSL_MSG_VSNPRINTF("Expecting one byte: %d", len);
            #endif
                return ASN_PARSE_E;
            }
            /* Fill number with all of data. */
            *data->data.u8 = input[idx];
            break;
        case ASN_DATA_TYPE_WORD16:
            /* Check data is small enough to fit. */
            if (len == 0 || len > 2) {
            #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
                WOLFSSL_MSG_VSNPRINTF("Expecting 1 or 2 bytes: %d", len);
            #endif
                return ASN_PARSE_E;
            }
            /* Fill number with all of data. */
            *data->data.u16 = 0;
            for (i = 0; i < len; i++) {
                *data->data.u16 <<= 8;
                *data->data.u16 |= input[idx + (word32)i] ;
            }
            break;
        case ASN_DATA_TYPE_WORD32:
            /* Check data is small enough to fit. */
            if (len == 0 || len > 4) {
            #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
                WOLFSSL_MSG_VSNPRINTF("Expecting 1 to 4 bytes: %d", len);
            #endif
                return ASN_PARSE_E;
            }
            /* Fill number with all of data. */
            *data->data.u32 = 0;
            for (i = 0; i < len; i++) {
                *data->data.u32 <<= 8;
                *data->data.u32 |= input[idx + (word32)i] ;
            }
            break;

        case ASN_DATA_TYPE_BUFFER:
            /* Check buffer is big enough to hold data. */
            if (len > (int)*data->data.buffer.length) {
            #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
                WOLFSSL_MSG_VSNPRINTF("Buffer too small for data: %d %d", len,
                        *data->data.buffer.length);
            #endif
                return ASN_PARSE_E;
            }
            /* Copy in data and record actual length seen. */
            XMEMCPY(data->data.buffer.data, input + idx, (size_t)len);
            *data->data.buffer.length = (word32)len;
            break;

        case ASN_DATA_TYPE_EXP_BUFFER:
            /* Check data is same size expected. */
            if (len != (int)data->data.ref.length) {
            #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
                WOLFSSL_MSG_VSNPRINTF("Data not expected length: %d %d", len,
                        data->data.ref.length);
            #endif
                return ASN_PARSE_E;
            }
            /* Check data is same as expected. */
            if (XMEMCMP(data->data.ref.data, input + idx, (size_t)len) != 0) {
            #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
                WOLFSSL_MSG("Data not as expected");
            #endif
                return ASN_PARSE_E;
            }
            break;

        case ASN_DATA_TYPE_MP:
        case ASN_DATA_TYPE_MP_POS_NEG:
            /* Initialize mp_int and read in big-endian byte array. */
            if (mp_init(data->data.mp) != MP_OKAY) {
            #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
                WOLFSSL_MSG_VSNPRINTF("Failed to init mp: %p", data->data.mp);
            #endif
                return MP_INIT_E;
            }
            FALL_THROUGH;
        case ASN_DATA_TYPE_MP_INITED:
            err = mp_read_unsigned_bin(data->data.mp, (byte*)input + idx,
                                       (word32)len);
            if (err != 0) {
            #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
                WOLFSSL_MSG_VSNPRINTF("Failed to read mp: %d", err);
            #endif
                mp_clear(data->data.mp);
                return ASN_GETINT_E;
            }
        #ifdef HAVE_WOLF_BIGINT
            err = wc_bigint_from_unsigned_bin(&data->data.mp->raw, input + idx,
                    len);
            if (err != 0) {
            #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
                WOLFSSL_MSG_VSNPRINTF("Failed to create bigint: %d", err);
            #endif
                mp_clear(data->data.mp);
                return ASN_GETINT_E;
            }
        #endif /* HAVE_WOLF_BIGINT */

        #ifdef WOLFSSL_SP_INT_NEGATIVE
            /* Don't always read as positive. */
            if ((data->dataType == ASN_DATA_TYPE_MP_POS_NEG) && (!zeroPadded) &&
                (input[idx] & 0x80)) {
                #ifdef MP_NEG
                    data->data.mp->sign = MP_NEG;
                #else
                    #ifdef OPENSSL_EXTRA
                        /* public API wolfSSL_ASN1_INTEGER_get() depends
                         * indirectly on negative bignum handling here.
                         */
                        #error OPENSSL_EXTRA requires negative bignum support.
                    #endif
                    #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
                    WOLFSSL_MSG_VSNPRINTF("ASN negative integer without bignum support.");
                    #endif
                    mp_clear(data->data.mp);
                    return ASN_GETINT_E;
                #endif
            }
        #else
            (void)zeroPadded;
        #endif
            break;

        case ASN_DATA_TYPE_CHOICE:
            /* Check if tag matched any of the choices specified. */
            for (i = 0; data->data.choice[i] != 0; i++)
                if (data->data.choice[i] == data->tag)
                    break;
            if (data->data.choice[i] == 0) {
            #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
                WOLFSSL_MSG("Tag didn't match a choice");
            #endif
                return ASN_PARSE_E;
            }

            /* Store data pointer and length for caller. */
            data->data.ref.data = input + idx;
            data->data.ref.length = (word32)len;
            break;

        case ASN_DATA_TYPE_NONE:
            /* Default behaviour based on tag. */
            if (asn->tag == ASN_BOOLEAN) {
                /* BOOLEAN has only one byte of data in BER. */
                if (len != 1) {
                #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
                    WOLFSSL_MSG_VSNPRINTF("BOOLEAN length too long: %d", len);
                #endif
                    return ASN_PARSE_E;
                }
                if (data->data.u8 == NULL)
                    return BAD_STATE_E;
                /* Store C boolean value. */
                *data->data.u8 = (input[idx] != 0);
                break;
            }
            if (asn->tag == ASN_TAG_NULL) {
                /* NULL has no data in BER. */
                if (len != 0) {
                #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
                    WOLFSSL_MSG_VSNPRINTF("NULL length too long: %d", len);
                #endif
                    return ASN_EXPECT_0_E;
                }
                data->data.ref.data = input + idx;
                break;
            }
            if (asn->tag == ASN_OBJECT_ID) {
                word32 oidIdx = 0;
                /* Store OID data pointer and length */
                data->data.oid.data = input + idx;
                data->data.oid.length = (word32)len;
                /* Get the OID sum. */
                err = GetOID(input + idx, &oidIdx, &data->data.oid.sum,
                        data->data.oid.type, len);
                if (err < 0) {
                #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
                    WOLFSSL_MSG_VSNPRINTF("OID check failed: %d", err);
                #endif
                    return err;
                }
                break;
            }

            /* Otherwise store data pointer and length. */
            data->data.ref.data = input + idx;
            data->data.ref.length = (word32)len;
            break;

    #ifdef DEBUG_WOLFSSL
        default:
            /* Bad ASN data type. */
        #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
            WOLFSSL_MSG_VSNPRINTF("Bad data type: %d", data->dataType);
        #endif
            return BAD_STATE_E;
    #endif
    }

    return 0;
}

/* Get the ASN.1 items from the BER encoding.
 *
 * @param [in]      asn       ASN.1 items expected.
 * @param [in]      data      Data array to place found items into.
 * @param [in]      count     Count of items to parse.
 * @param [in]      complete  Whether the whole buffer is to be used up.
 * @param [in]      input     BER encoded data.
 * @param [in, out] inOutIdx  On in, starting index of data.
 *                            On out, end of parsed data.
 * @param [in]      length    Length of input buffer.
 * @return  0 on success.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
 * @return  ASN_BITSTR_E when the expected BIT_STRING tag is not found.
 * @return  ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
 *          non-zero length.
 * @return  MP_INIT_E when the unable to initialize an mp_int.
 * @return  ASN_GETINT_E when the unable to convert data to an mp_int.
 * @return  BAD_STATE_E when the data type is not supported.
 * @return  ASN_UNKNOWN_OID_E when the OID cannot be verified.
 */
int GetASN_Items(const ASNItem* asn, ASNGetData *data, int count, int complete,
                 const byte* input, word32* inOutIdx, word32 length)
{
    int    i;
    int    j;
    int    err;
    int    len;
    /* Current index into buffer. */
    word32 idx = *inOutIdx;
    /* Initialize the end index at each depth to be the length. */
    word32 endIdx[GET_ASN_MAX_DEPTH] = { length, length, length, length, length,
                                         length, length };
    /* Set choices to -1 to indicate they haven't been seen or found. */
    signed char   choiceMet[GET_ASN_MAX_CHOICES] = { -1, -1 };
    /* Not matching a choice right now. */
    int    choice = 0;
    /* Current depth of ASN.1 item. */
    int    depth;
    /* Minimum depth value seen. */
    int    minDepth;
    /* Integer had a zero prepended. */
    int    zeroPadded;

#ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
    WOLFSSL_ENTER("GetASN_Items");
#endif

    /* Start depth at first items depth. */
    minDepth = depth = asn[0].depth;
    /* Check every ASN.1 item. */
    for (i = 0; i < count; i++) {
        /* Store offset of ASN.1 item. */
        data[i].offset = idx;
        /* Length of data in ASN.1 item starts empty. */
        data[i].length = 0;
        /* Get current item depth. */
        depth = asn[i].depth;
    #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
        if (depth > GET_ASN_MAX_DEPTH) {
            WOLFSSL_MSG("Depth in template too large");
            return ASN_PARSE_E;
        }
    #endif
        /* Keep track of minimum depth. */
        if (depth < minDepth) {
            minDepth = depth;
        }

        /* Reset choice if different from previous. */
        if (choice > 0 && asn[i].optional != choice) {
            choice = 0;
        }
        /* Check if first of numbered choice. */
        if (choice == 0 && asn[i].optional > 1) {
            choice = asn[i].optional;
            if (choiceMet[choice - 2] == -1) {
                /* Choice seen but not found a match yet. */
                choiceMet[choice - 2] = 0;
            }
        }

        /* Check for end of data or not a choice and tag not matching. */
        if (idx == endIdx[depth] || (data[i].dataType != ASN_DATA_TYPE_CHOICE &&
                              (input[idx] & ~ASN_CONSTRUCTED) != asn[i].tag)) {
            if (asn[i].optional) {
                /* Skip over ASN.1 items underneath this optional item. */
                for (j = i + 1; j < count; j++) {
                    if (asn[i].depth >= asn[j].depth)
                        break;
                    data[j].offset = idx;
                    data[j].length = 0;
                }
                i = j - 1;
                continue;
            }

            /* Check for end of data. */
            if (idx == length) {
        #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
                WOLFSSL_MSG_VSNPRINTF(
                    "%2d: %4d %4d %c %*s %-16s%*s  (index past end)",
                    i, data[i].offset, data[i].length,
                    asn[i].constructed ? '+' : ' ', asn[i].depth, "",
                    TagString(asn[i].tag), 6 - asn[i].depth, "");
                WOLFSSL_MSG_VSNPRINTF("Index past end of data: %d %d", idx,
                        length);
        #endif
                return BUFFER_E;
            }
        #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
            /* Show expected versus found. */
            WOLFSSL_MSG_VSNPRINTF(
                "%2d: %4d %4d %c %*s %-16s%*s  Tag=0x%02x (%s)",
                i, data[i].offset, data[i].length,
                asn[i].constructed ? '+' : ' ', asn[i].depth, "",
                TagString(asn[i].tag), 6 - asn[i].depth, "",
                input[idx], TagString(input[idx]));
        #endif
            /* Check for end of data at this depth. */
            if (idx == endIdx[depth]) {
            #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
                WOLFSSL_MSG_VSNPRINTF("Index past outer item: %d %d", idx,
                        endIdx[depth]);
            #endif
                return ASN_PARSE_E;
            }

            /* Expecting an OBJECT_ID */
            if (asn[i].tag == ASN_OBJECT_ID) {
            #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
                WOLFSSL_MSG("Expecting OBJECT ID");
            #endif
                return ASN_OBJECT_ID_E;
            }
            /* Expecting a BIT_STRING */
            if (asn[i].tag == ASN_BIT_STRING) {
            #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
                WOLFSSL_MSG("Expecting BIT STRING");
            #endif
                return ASN_BITSTR_E;
            }
            /* Not the expected tag. */
        #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
            WOLFSSL_MSG("Bad tag");
        #endif
            return ASN_PARSE_E;
        }

        /* Store found tag in data. */
        data[i].tag = input[idx];
        if (data[i].dataType != ASN_DATA_TYPE_CHOICE) {
            int constructed = (input[idx] & ASN_CONSTRUCTED) == ASN_CONSTRUCTED;
            /* Check constructed match expected for non-choice ASN.1 item. */
            if (asn[i].constructed != constructed) {
            #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
                WOLFSSL_MSG_VSNPRINTF(
                        "%2d: %4d %4d %c %*s %-16s%*s  Tag=0x%02x (%s)",
                        i, data[i].offset, data[i].length,
                        asn[i].constructed ? '+' : ' ', asn[i].depth, "",
                        TagString(asn[i].tag), 6 - asn[i].depth, "",
                        input[idx], TagString(input[idx]));
                if (!constructed) {
                    WOLFSSL_MSG("Not constructed");
                }
                else {
                    WOLFSSL_MSG("Not expected to be constructed");
                }
            #endif
                return ASN_PARSE_E;
            }
        }
        /* Move index to start of length. */
        idx++;
        /* Get the encoded length. */
        if (GetASN_Length(input, &idx, &len, endIdx[depth], 1) < 0) {
        #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
            WOLFSSL_MSG_VSNPRINTF("%2d: idx=%d len=%d end=%d", i, idx, len,
                    endIdx[depth]);
        #endif
            return ASN_PARSE_E;
        }
        /* Store length of data. */
        data[i].length = (word32)len;
        /* Note the max length of items under this one. */
        endIdx[depth + 1] = idx + (word32)len;
        if (choice > 1) {
            /* Note we found a number choice. */
            choiceMet[choice - 2] = 1;
        }

    #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
        WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
                data[i].offset, data[i].length, asn[i].constructed ? '+' : ' ',
                asn[i].depth, "", TagString(data[i].tag));
    #endif

        /* Assume no zero padding on INTEGER. */
        zeroPadded = 0;
        /* Check data types that prepended a byte. */
        if (asn[i].tag == ASN_INTEGER) {
            /* Check validity of first byte. */
            err = GetASN_Integer(input, idx, len,
                    data[i].dataType == ASN_DATA_TYPE_MP ||
                    data[i].dataType == ASN_DATA_TYPE_MP_INITED);
            if (err != 0)
                return err;
            if (len > 1 && input[idx] == 0) {
                zeroPadded = 1;
                /* Move over prepended byte. */
                idx++;
                len--;
            }
        }
        else if (asn[i].tag == ASN_BIT_STRING) {
            /* Check prepended byte is correct. */
            err = GetASN_BitString(input, idx, len);
            if (err != 0)
                return err;
            /* Move over prepended byte. */
            idx++;
            len--;
        }
        else if ((asn[i].tag == ASN_OBJECT_ID) && (len < 3)) {
        #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
            WOLFSSL_MSG_VSNPRINTF("OID length must be 3 or more: %d", len);
        #endif
            return ASN_PARSE_E;
        }

        /* Don't parse data if only header required. */
        if (asn[i].headerOnly) {
            /* Store reference to data and length. */
            data[i].data.ref.data = input + idx;
            data[i].data.ref.length = (word32)len;
            continue;
        }

        /* Store the data at idx in the ASN data item. */
        err = GetASN_StoreData(&asn[i], &data[i], input, idx, len, zeroPadded);
        if (err != 0) {
            return err;
        }

        /* Move index to next item. */
        idx += (word32)len;

        /* When matched numbered choice ... */
        if (asn[i].optional > 1) {
            /* Skip over other ASN.1 items of the same number. */
            for (j = i + 1; j < count; j++) {
                if (asn[j].depth <= asn[i].depth &&
                                           asn[j].optional != asn[i].optional) {
                   break;
                }
            }
            i = j - 1;
        }
    }

    if (complete) {
        /* When expecting ASN.1 items to completely use data, check we did. */
        for (j = depth; j > minDepth; j--) {
            if (idx < endIdx[j]) {
            #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
                WOLFSSL_MSG_VSNPRINTF(
                    "More data in constructed item at depth: %d", j - 1);
            #endif
                return ASN_PARSE_E;
            }
        }
    }

    /* Check all choices where met - found an item for them. */
    for (j = 0; j < GET_ASN_MAX_CHOICES; j++) {
        if (choiceMet[j] == 0) {
        #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
            WOLFSSL_MSG_VSNPRINTF("No choice seen: %d", j + 2);
        #endif
            return ASN_PARSE_E;
        }
    }

    /* Return index after ASN.1 data has been parsed. */
    *inOutIdx = idx;

    return 0;
}

#ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
/* Calculate the size of the DER encoding.
 *
 * Call SetASN_Items() to write encoding to a buffer.
 *
 * @param [in]      asn    ASN.1 items to encode.
 * @param [in, out] data   Data to place in each item. Lengths set were not
 *                         known.
 * @param [in]      count  Count of items to encode.
 * @param [out]     len    Length of the DER encoding.
 * @return  Size of the DER encoding in bytes.
 */
static int SizeASN_ItemsDebug(const char* name, const ASNItem* asn,
    ASNSetData *data, int count, int* encSz)
{
    WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
    return SizeASN_Items(asn, data, count, encSz);
}

/* Creates the DER encoding of the ASN.1 items.
 *
 * Assumes the output buffer is large enough to hold encoding.
 * Must call SizeASN_Items() to determine size of encoding and offsets.
 *
 * Displays the template name first.
 *
 * @param [in]      name    Name of ASN.1 template.
 * @param [in]      asn     ASN.1 items to encode.
 * @param [in]      data    Data to place in each item.
 * @param [in]      count   Count of items to encode.
 * @param [in, out] output  Buffer to write encoding into.
 * @return  Size of the DER encoding in bytes.
 */
static int SetASN_ItemsDebug(const char* name, const ASNItem* asn,
    ASNSetData *data, int count, byte* output)
{
    WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
    return SetASN_Items(asn, data, count, output);
}

/* Get the ASN.1 items from the BER encoding.
 *
 * Displays the template name first.
 *
 * @param [in]      name      Name of ASN.1 template.
 * @param [in]      asn       ASN.1 items expected.
 * @param [in]      data      Data array to place found items into.
 * @param [in]      count     Count of items to parse.
 * @param [in]      complete  Whether the whole buffer is to be used up.
 * @param [in]      input     BER encoded data.
 * @param [in, out] inOutIdx  On in, starting index of data.
 *                            On out, end of parsed data.
 * @param [in]      maxIdx    Maximum index of input data.
 * @return  0 on success.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 * is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
 * @return  ASN_BITSTR_E when the expected BIT_STRING tag is not found.
 * @return  ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
 *          non-zero length.
 * @return  MP_INIT_E when the unable to initialize an mp_int.
 * @return  ASN_GETINT_E when the unable to convert data to an mp_int.
 * @return  BAD_STATE_E when the data type is not supported.
 */
static int GetASN_ItemsDebug(const char* name, const ASNItem* asn,
    ASNGetData *data, int count, int complete, const byte* input,
    word32* inOutIdx, word32 maxIdx)
{
    WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
    return GetASN_Items(asn, data, count, complete, input, inOutIdx, maxIdx);
}

/* Calculate the size of the DER encoding.
 *
 * Call SetASN_Items() to write encoding to a buffer.
 *
 * @param [in]      asn    ASN.1 items to encode.
 * @param [in, out] data   Data to place in each item. Lengths set were not
 *                         known.
 * @param [in]      count  Count of items to encode.
 * @param [out]     len    Length of the DER encoding.
 * @return  Size of the DER encoding in bytes.
 */
#define SizeASN_Items(asn, data, count, encSz)  \
    SizeASN_ItemsDebug(#asn, asn, data, count, encSz)

/* Creates the DER encoding of the ASN.1 items.
 *
 * Assumes the output buffer is large enough to hold encoding.
 * Must call SizeASN_Items() to determine size of encoding and offsets.
 *
 * Displays the template name first.
 *
 * @param [in]      name    Name of ASN.1 template.
 * @param [in]      asn     ASN.1 items to encode.
 * @param [in]      data    Data to place in each item.
 * @param [in]      count   Count of items to encode.
 * @param [in, out] output  Buffer to write encoding into.
 * @return  Size of the DER encoding in bytes.
 */
#define SetASN_Items(asn, data, count, output)  \
    SetASN_ItemsDebug(#asn, asn, data, count, output)

/* Get the ASN.1 items from the BER encoding.
 *
 * Displays the template name first.
 *
 * @param [in]      name      Name of ASN.1 template.
 * @param [in]      asn       ASN.1 items expected.
 * @param [in]      data      Data array to place found items into.
 * @param [in]      count     Count of items to parse.
 * @param [in]      complete  Whether the whole buffer is to be used up.
 * @param [in]      input     BER encoded data.
 * @param [in, out] inOutIdx  On in, starting index of data.
 *                            On out, end of parsed data.
 * @param [in]      maxIdx    Maximum index of input data.
 * @return  0 on success.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 * is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
 * @return  ASN_BITSTR_E when the expected BIT_STRING tag is not found.
 * @return  ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
 *          non-zero length.
 * @return  MP_INIT_E when the unable to initialize an mp_int.
 * @return  ASN_GETINT_E when the unable to convert data to an mp_int.
 * @return  BAD_STATE_E when the data type is not supported.
 */
#define GetASN_Items(asn, data, count, complete, input, inOutIdx, maxIdx)  \
    GetASN_ItemsDebug(#asn, asn, data, count, complete, input, inOutIdx, maxIdx)
#endif /* WOLFSSL_DEBUG_ASN_TEMPLATE */

/* Decode a BER encoded constructed sequence.
 *
 * @param [in]       input     Buffer of BER encoded data.
 * @param [in, out]  inOutIdx  On in, index to start decoding from.
 *                             On out, index of next encoded byte.
 * @param [out]      len       Length of data under SEQUENCE.
 * @param [in]       maxIdx    Maximim index of data. Index of byte after SEQ.
 * @param [in]       complete  All data used with SEQUENCE and data under.
 * @return  0 on success.
 * @return  BUFFER_E when not enough data to complete decode.
 * @return  ASN_PARSE when decoding failed.
 */
static int GetASN_Sequence(const byte* input, word32* inOutIdx, int* len,
                           word32 maxIdx, int complete)
{
    int ret = 0;
    word32 idx = *inOutIdx;

    /* Check buffer big enough for tag. */
    if (idx + 1 > maxIdx) {
        ret = BUFFER_E;
    }
    /* Check it is a constructed SEQUENCE. */
    if ((ret == 0) && (input[idx++] != (ASN_SEQUENCE | ASN_CONSTRUCTED))) {
        ret = ASN_PARSE_E;
    }
    /* Get the length. */
    if ((ret == 0) && (GetASN_Length(input, &idx, len, maxIdx, 1) < 0)) {
        ret = ASN_PARSE_E;
    }
    /* Check all data used if complete set. */
    if ((ret == 0) && complete && (idx + (word32)*len != maxIdx)) {
        ret = ASN_PARSE_E;
    }
    if (ret == 0) {
        /* Return index of next byte of encoded data. */
        *inOutIdx = idx;
    }

    return ret;
}


#ifdef WOLFSSL_ASN_TEMPLATE_TYPE_CHECK
/* Setup ASN data item to get an 8-bit number.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] num      Pointer to an 8-bit variable.
 */
void GetASN_Int8Bit(ASNGetData *dataASN, byte* num)
{
    dataASN->dataType = ASN_DATA_TYPE_WORD8;
    dataASN->data.u8  = num;
}

/* Setup ASN data item to get a 16-bit number.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] num      Pointer to a 16-bit variable.
 */
void GetASN_Int16Bit(ASNGetData *dataASN, word16* num)
{
    dataASN->dataType = ASN_DATA_TYPE_WORD16;
    dataASN->data.u16 = num;
}

/* Setup ASN data item to get a 32-bit number.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] num      Pointer to a 32-bit variable.
 */
void GetASN_Int32Bit(ASNGetData *dataASN, word32* num)
{
    dataASN->dataType = ASN_DATA_TYPE_WORD32;
    dataASN->data.u32 = num;
}

/* Setup ASN data item to get data into a buffer of a specific length.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] data     Buffer to hold data.
 * @param [in] length   Length of buffer in bytes.
 */
void GetASN_Buffer(ASNGetData *dataASN, byte* data, word32* length)
{
    dataASN->dataType           = ASN_DATA_TYPE_BUFFER;
    dataASN->data.buffer.data   = data;
    dataASN->data.buffer.length = length;
}

/* Setup ASN data item to check parsed data against expected buffer.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] data     Buffer containing expected data.
 * @param [in] length   Length of buffer in bytes.
 */
void GetASN_ExpBuffer(ASNGetData *dataASN, const byte* data, word32 length)
{
    dataASN->dataType        = ASN_DATA_TYPE_EXP_BUFFER;
    dataASN->data.ref.data   = data;
    dataASN->data.ref.length = length;
}

/* Setup ASN data item to get a number into an mp_int.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] num      Multi-precision number object.
 */
void GetASN_MP(ASNGetData *dataASN, mp_int* num)
{
    dataASN->dataType = ASN_DATA_TYPE_MP;
    dataASN->data.mp  = num;
}

/* Setup ASN data item to get a number into an mp_int that is initialized.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] num      Multi-precision number object.
 */
void GetASN_MP_Inited(ASNGetData *dataASN, mp_int* num)
{
    dataASN->dataType = ASN_DATA_TYPE_MP_INITED;
    dataASN->data.mp  = num;
}

/* Setup ASN data item to get a positive or negative number into an mp_int.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] num      Multi-precision number object.
 */
void GetASN_MP_PosNeg(ASNGetData *dataASN, mp_int* num)
{
    dataASN->dataType = ASN_DATA_TYPE_MP_POS_NEG;
    dataASN->data.mp  = num;
}

/* Setup ASN data item to be a choice of tags.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] options  0 terminated list of tags that are valid.
 */
void GetASN_Choice(ASNGetData *dataASN, const byte* options)
{
    dataASN->dataType    = ASN_DATA_TYPE_CHOICE;
    dataASN->data.choice = options;
}

/* Setup ASN data item to get a boolean value.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] num      Pointer to an 8-bit variable.
 */
void GetASN_Boolean(ASNGetData *dataASN, byte* num)
{
    dataASN->dataType    = ASN_DATA_TYPE_NONE;
    dataASN->data.choice = num;
}

/* Setup ASN data item to be a an OID of a specific type.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] oidType  Type of OID to expect.
 */
void GetASN_OID(ASNGetData *dataASN, int oidType)
{
    dataASN->data.oid.type = oidType;
}

/* Get the data and length from an ASN data item.
 *
 * @param [in]  dataASN  Dynamic ASN data item.
 * @param [out] data     Pointer to data of item.
 * @param [out] length   Length of buffer in bytes.
 */
void GetASN_GetConstRef(ASNGetData * dataASN, const byte** data, word32* length)
{
    *data   = dataASN->data.ref.data;
    *length = dataASN->data.ref.length;
}

/* Get the data and length from an ASN data item.
 *
 * @param [in]  dataASN  Dynamic ASN data item.
 * @param [out] data     Pointer to data of item.
 * @param [out] length   Length of buffer in bytes.
 */
void GetASN_GetRef(ASNGetData * dataASN, byte** data, word32* length)
{
    *data   = (byte*)dataASN->data.ref.data;
    *length =        dataASN->data.ref.length;
}

/* Get the data and length from an ASN data item that is an OID.
 *
 * @param [in]  dataASN  Dynamic ASN data item.
 * @param [out] data     Pointer to .
 * @param [out] length   Length of buffer in bytes.
 */
void GetASN_OIDData(ASNGetData * dataASN, byte** data, word32* length)
{
    *data   = (byte*)dataASN->data.oid.data;
    *length =        dataASN->data.oid.length;
}

/* Setup an ASN data item to set a boolean.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] val      Boolean value.
 */
void SetASN_Boolean(ASNSetData *dataASN, byte val)
{
    dataASN->dataType = ASN_DATA_TYPE_NONE;
    dataASN->data.u8  = val;
}

/* Setup an ASN data item to set an 8-bit number.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] num      8-bit number to set.
 */
void SetASN_Int8Bit(ASNSetData *dataASN, byte num)
{
    dataASN->dataType = ASN_DATA_TYPE_WORD8;
    dataASN->data.u8  = num;
}

/* Setup an ASN data item to set a 16-bit number.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] num      16-bit number to set.
 */
void SetASN_Int16Bit(ASNSetData *dataASN, word16 num)
{
    dataASN->dataType = ASN_DATA_TYPE_WORD16;
    dataASN->data.u16 = num;
}

/* Setup an ASN data item to set the data in a buffer.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] data     Buffer containing data to set.
 * @param [in] length   Length of data in buffer in bytes.
 */
void SetASN_Buffer(ASNSetData *dataASN, const byte* data, word32 length)
{
    dataASN->data.buffer.data   = data;
    dataASN->data.buffer.length = length;
}

/* Setup an ASN data item to set the DER encode data in a buffer.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] data     Buffer containing BER encoded data to set.
 * @param [in] length   Length of data in buffer in bytes.
 */
void SetASN_ReplaceBuffer(ASNSetData *dataASN, const byte* data, word32 length)
{
    dataASN->dataType           = ASN_DATA_TYPE_REPLACE_BUFFER;
    dataASN->data.buffer.data   = data;
    dataASN->data.buffer.length = length;
}

/* Setup an ASN data item to set an multi-precision number.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] num      Multi-precision number.
 */
void SetASN_MP(ASNSetData *dataASN, mp_int* num)
{
    dataASN->dataType = ASN_DATA_TYPE_MP;
    dataASN->data.mp  = num;
}

/* Setup an ASN data item to set an OID based on id and type.
 *
 * oid and oidType pair are unique.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] oid      OID identifier.
 * @param [in] oidType  Type of OID.
 */
void SetASN_OID(ASNSetData *dataASN, int oid, int oidType)
{
    dataASN->data.buffer.data = OidFromId(oid, oidType,
                                                  &dataASN->data.buffer.length);
}
#endif /* WOLFSSL_ASN_TEMPLATE_TYPE_CHECK */

#ifdef CRLDP_VALIDATE_DATA
/* Get the data of the BIT_STRING as a 16-bit number.
 *
 * @param [in]  dataASN  Dynamic ASN data item.
 * @param [out] val      ASN.1 item's data as a 16-bit number.
 * @return  0 on success.
 * @return  ASN_PARSE_E when BITSTRING value is more than 2 bytes.
 * @return  ASN_PARSE_E when unused bits of BITSTRING is invalid.
 */
static int GetASN_BitString_Int16Bit(ASNGetData* dataASN, word16* val)
{
    int ret;
    int i;
    const byte* input = dataASN->data.ref.data;
    int length = dataASN->data.ref.length;

    /* Validate the BIT_STRING data. */
    ret = GetASN_BitString(input, 0, length);
    if (ret == 0) {
        /* Skip unused bits byte. */
        input++;
        length--;

        /* Check the data is usable. */
        if (length == 0 || length > 2) {
#ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
            WOLFSSL_MSG_VSNPRINTF("Expecting 1 or 2 bytes: %d", length);
#endif
            ret = ASN_PARSE_E;
        }
    }
    if (ret == 0) {
        /* Fill 16-bit var with all the data. */
        *val = 0;
        for (i = 0; i < length; i++) {
            *val <<= 8;
            *val |= input[i];
        }
    }
    return ret;
}
#endif /* CRLDP_VALIDATE_DATA */

#endif /* WOLFSSL_ASN_TEMPLATE */


/* Decode the BER/DER length field.
 *
 * @param [in]      input     BER encoded data.
 * @param [in, out] inOutIdx  On in, starting index of length.
 *                            On out, end of parsed length.
 * @param [out]     len       Length value decoded.
 * @param [in]      maxIdx    Maximum index of input data.
 * @return  Length on success.
 * @return  ASN_PARSE_E if the encoding is invalid.
 * @return  BUFFER_E when not enough data to complete decode.
 */
int GetLength(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
{
    return GetLength_ex(input, inOutIdx, len, maxIdx, 1);
}


/* Decode the BER/DER length field and check the length is valid on request.
 *
 * BER/DER has Type-Length-Value triplets.
 * When requested will check that the Length decoded, indicating the number
 * of bytes in the Value, is available in the buffer after the Length bytes.
 *
 * Only supporting a length upto INT_MAX.
 *
 * @param [in]      input     BER encoded data.
 * @param [in, out] inOutIdx  On in, starting index of length.
 *                            On out, end of parsed length.
 * @param [out]     len       Length value decoded.
 * @param [in]      maxIdx    Maximum index of input data.
 * @param [in]      check     Whether to check the buffer has at least the
 *                            decoded length of bytes remaining.
 * @return  Length on success.
 * @return  ASN_PARSE_E if the encoding is invalid.
 * @return  BUFFER_E when not enough data to complete decode.
 */
int GetLength_ex(const byte* input, word32* inOutIdx, int* len, word32 maxIdx,
                 int check)
{
    int     length = 0;
    word32  idx = (word32)*inOutIdx;
    byte    b;

    /* Ensure zero return length on error. */
    *len = 0;

    /* Check there is at least one byte available containing length information.
     */
    if ((idx + 1) > maxIdx) {
        WOLFSSL_MSG("GetLength - bad index on input");
        return BUFFER_E;
    }

    /* Get the first length byte. */
    b = input[idx++];
    /* Check if the first byte indicates the count of bytes. */
    if (b >= ASN_LONG_LENGTH) {
        /* Bottom 7 bits are the number of bytes to calculate length with.
         * Note: 0 indicates indefinite length encoding *not* 0 bytes of length.
         */
        word32 bytes = (word32)b & 0x7FU;
        int minLen;

        /* Calculate minimum length to be encoded with bytes. */
        if (b == ASN_INDEF_LENGTH) {
            /* Indefinite length encoding - no length bytes. */
            minLen = 0;
        }
        else if (bytes == 1) {
            minLen = 0x80;
        }
        /* Only support up to the number of bytes that fit into return var. */
        else if (bytes > sizeof(length)) {
            WOLFSSL_MSG("GetLength - overlong data length spec");
            return ASN_PARSE_E;
        } else {
            minLen = 1 << ((bytes - 1) * 8);
        }

        /* Check the number of bytes required are available. */
        if ((idx + bytes) > maxIdx) {
            WOLFSSL_MSG("GetLength - bad long length");
            return BUFFER_E;
        }

        /* Big-endian encoding of number. */
        while (bytes--) {
            b = input[idx++];
            length = (length << 8) | b;
        }
        /* Negative value indicates we overflowed the signed int. */
        if (length < 0) {
            return ASN_PARSE_E;
        }
        /* Don't allow lengths that are longer than strictly required. */
        if (length < minLen) {
            return ASN_PARSE_E;
        }
    }
    else {
        /* Length in first byte. */
        length = b;
    }

    /* When requested, check the buffer has at least length bytes left. */
    if (check && ((idx + (word32)length) > maxIdx)) {
        WOLFSSL_MSG("GetLength - value exceeds buffer length");
        return BUFFER_E;
    }

    /* Return index after length encoding. */
    *inOutIdx = idx;
    /* Return length if valid. */
    if (length > 0) {
        *len = length;
    }

    /* Return length calculated or error code. */
    return length;
}


/* Gets the tag of next BER/DER encoded item.
 *
 * Checks there is enough data in the buffer for the tag byte.
 *
 * @param [in]      input     BER encoded data.
 * @param [in, out] inOutIdx  On in, starting index of tag.
 *                            On out, end of parsed tag.
 * @param [out]     tag       Tag value found.
 * @param [in]      maxIdx    Maximum index of input data.
 *
 * return  0 on success
 * return  BAD_FUNC_ARG when tag, inOutIdx or input is NULL.
 * return  BUFFER_E when not enough space in buffer for tag.
 */
int GetASNTag(const byte* input, word32* inOutIdx, byte* tag, word32 maxIdx)
{
    int ret = 0;
    word32 idx = 0;

    /* Check validity of parameters. */
    if ((tag == NULL) || (inOutIdx == NULL) || (input == NULL)) {
        ret = BAD_FUNC_ARG;
    }
    if (ret == 0) {
        /* Get index and ensure space for tag. */
        idx = *inOutIdx;
        if (idx + ASN_TAG_SZ > maxIdx) {
            WOLFSSL_MSG("Buffer too small for ASN tag");
            ret = BUFFER_E;
        }
    }
    if (ret == 0) {
        /* Return the tag and the index after tag. */
        *tag = input[idx];
        *inOutIdx = idx + ASN_TAG_SZ;
    }
    /* Return error code. */
    return ret;
}


/* Decode the DER/BER header (Type-Length) and check the length when requested.
 *
 * BER/DER has Type-Length-Value triplets.
 * Check that the tag/type is the required value.
 * When requested will check that the Length decoded, indicating the number
 * of bytes in the Value, is available in the buffer after the Length bytes.
 *
 * Only supporting a length upto INT_MAX.
 *
 * @param [in]      input     Buffer holding DER/BER encoded data.
 * @param [in]      tag       ASN.1 tag value expected in header.
 * @param [in, out] inOutIdx  On in, starting index of header.
 *                            On out, end of parsed header.
 * @param [out]     len       Number of bytes in the ASN.1 data.
 * @param [in]      maxIdx    Length of data in buffer.
 * @param [in]      check     Whether to check the buffer has at least the
 *                            decoded length of bytes remaining.
 * @return  Number of bytes in the ASN.1 data on success.
 * @return  BUFFER_E when there is not enough data to parse.
 * @return  ASN_PARSE_E when the expected tag is not found or length is invalid.
 */
static int GetASNHeader_ex(const byte* input, byte tag, word32* inOutIdx,
                           int* len, word32 maxIdx, int check)
{
    int    ret = 0;
    word32 idx = *inOutIdx;
    byte   tagFound;
    int    length = 0;

    /* Get tag/type. */
    if (GetASNTag(input, &idx, &tagFound, maxIdx) != 0) {
        ret = ASN_PARSE_E;
    }
    /* Ensure tag is the expected value. */
    if ((ret == 0) && (tagFound != tag)) {
        ret = ASN_PARSE_E;
    }
    /* Get the encoded length. */
    if ((ret == 0) && (GetLength_ex(input, &idx, &length, maxIdx, check) < 0)) {
        ret = ASN_PARSE_E;
    }
    if (ret == 0) {
        /* Return the length of data and index after header. */
        *len      = length;
        *inOutIdx = idx;
        ret = length;
    }
    /* Return number of data bytes or error code. */
    return ret;
}


/* Decode the DER/BER header (Type-Length) and check the length.
 *
 * BER/DER has Type-Length-Value triplets.
 * Check that the tag/type is the required value.
 * Checks that the Length decoded, indicating the number of bytes in the Value,
 * is available in the buffer after the Length bytes.
 *
 * @param [in]      input     Buffer holding DER/BER encoded data.
 * @param [in]      tag       ASN.1 tag value expected in header.
 * @param [in, out] inOutIdx  On in, starting index of header.
 *                            On out, end of parsed header.
 * @param [out]     len       Number of bytes in the ASN.1 data.
 * @param [in]      maxIdx    Length of data in buffer.
 * @return  Number of bytes in the ASN.1 data on success.
 * @return  BUFFER_E when there is not enough data to parse.
 * @return  ASN_PARSE_E when the expected tag is not found or length is invalid.
 */
static int GetASNHeader(const byte* input, byte tag, word32* inOutIdx, int* len,
                        word32 maxIdx)
{
    return GetASNHeader_ex(input, tag, inOutIdx, len, maxIdx, 1);
}

#ifndef WOLFSSL_ASN_TEMPLATE
static int GetHeader(const byte* input, byte* tag, word32* inOutIdx, int* len,
                     word32 maxIdx, int check)
{
    word32 idx = *inOutIdx;
    int    length;

    if ((idx + 1) > maxIdx)
        return BUFFER_E;

    *tag = input[idx++];

    if (GetLength_ex(input, &idx, &length, maxIdx, check) < 0)
        return ASN_PARSE_E;

    *len      = length;
    *inOutIdx = idx;
    return length;
}
#endif

/* Decode the header of a BER/DER encoded SEQUENCE.
 *
 * @param [in]      input     Buffer holding DER/BER encoded data.
 * @param [in, out] inOutIdx  On in, starting index of header.
 *                            On out, end of parsed header.
 * @param [out]     len       Number of bytes in the ASN.1 data.
 * @param [in]      maxIdx    Length of data in buffer.
 * @return  Number of bytes in the ASN.1 data on success.
 * @return  BUFFER_E when there is not enough data to parse.
 * @return  ASN_PARSE_E when the tag is not a SEQUENCE or length is invalid.
 */
int GetSequence(const byte* input, word32* inOutIdx, int* len,
                           word32 maxIdx)
{
    return GetASNHeader(input, ASN_SEQUENCE | ASN_CONSTRUCTED, inOutIdx, len,
                        maxIdx);
}

/* Decode the header of a BER/DER encoded SEQUENCE.
 *
 * @param [in]      input     Buffer holding DER/BER encoded data.
 * @param [in, out] inOutIdx  On in, starting index of header.
 *                            On out, end of parsed header.
 * @param [out]     len       Number of bytes in the ASN.1 data.
 * @param [in]      maxIdx    Length of data in buffer.
 * @param [in]      check     Whether to check the buffer has at least the
 *                            decoded length of bytes remaining.
 * @return  Number of bytes in the ASN.1 data on success.
 * @return  BUFFER_E when there is not enough data to parse.
 * @return  ASN_PARSE_E when the tag is not a SEQUENCE or length is invalid.
 */
int GetSequence_ex(const byte* input, word32* inOutIdx, int* len,
                           word32 maxIdx, int check)
{
    return GetASNHeader_ex(input, ASN_SEQUENCE | ASN_CONSTRUCTED, inOutIdx, len,
                        maxIdx, check);
}

/* Decode the header of a BER/DER encoded SET.
 *
 * @param [in]      input     Buffer holding DER/BER encoded data.
 * @param [in, out] inOutIdx  On in, starting index of header.
 *                            On out, end of parsed header.
 * @param [out]     len       Number of bytes in the ASN.1 data.
 * @param [in]      maxIdx    Length of data in buffer.
 * @return  Number of bytes in the ASN.1 data on success.
 * @return  BUFFER_E when there is not enough data to parse.
 * @return  ASN_PARSE_E when the tag is not a SET or length is invalid.
 */
int GetSet(const byte* input, word32* inOutIdx, int* len,
                        word32 maxIdx)
{
    return GetASNHeader(input, ASN_SET | ASN_CONSTRUCTED, inOutIdx, len,
                        maxIdx);
}

/* Decode the header of a BER/DER encoded SET.
 *
 * @param [in]      input     Buffer holding DER/BER encoded data.
 * @param [in, out] inOutIdx  On in, starting index of header.
 *                            On out, end of parsed header.
 * @param [out]     len       Number of bytes in the ASN.1 data.
 * @param [in]      maxIdx    Length of data in buffer.
 * @param [in]      check     Whether to check the buffer has at least the
 *                            decoded length of bytes remaining.
 * @return  Number of bytes in the ASN.1 data on success.
 * @return  BUFFER_E when there is not enough data to parse.
 * @return  ASN_PARSE_E when the tag is not a SET or length is invalid.
 */
int GetSet_ex(const byte* input, word32* inOutIdx, int* len,
                        word32 maxIdx, int check)
{
    return GetASNHeader_ex(input, ASN_SET | ASN_CONSTRUCTED, inOutIdx, len,
                        maxIdx, check);
}

#if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_OCSP)
/* Decode the BER/DER encoded NULL.
 *
 * No data in a NULL ASN.1 item.
 * Ensure that the all fields are as expected and move index past the element.
 *
 * @param [in]      input     Buffer holding DER/BER encoded data.
 * @param [in, out] inOutIdx  On in, starting index of NULL item.
 *                            On out, end of parsed NULL item.
 * @param [in]      maxIdx    Length of data in buffer.
 * @return  0 on success.
 * @return  BUFFER_E when there is not enough data to parse.
 * @return  ASN_TAG_NULL_E when the NULL tag is not found.
 * @return  ASN_EXPECT_0_E when the length is not zero.
 */
static int GetASNNull(const byte* input, word32* inOutIdx, word32 maxIdx)
{
    int ret = 0;
    word32 idx = *inOutIdx;

    /* Check buffer has enough data for a NULL item. */
    if ((idx + 2) > maxIdx) {
        ret = BUFFER_E;
    }
    /* Check the tag is NULL. */
    if ((ret == 0) && (input[idx++] != ASN_TAG_NULL)) {
        ret = ASN_TAG_NULL_E;
    }
    /* Check the length is zero. */
    if ((ret == 0) && (input[idx++] != 0)) {
        ret = ASN_EXPECT_0_E;
    }
    if (ret == 0) {
        /* Return the index after NULL tag. */
        *inOutIdx = idx;
    }
    /* Return error code. */
    return ret;
}
#endif

#ifndef WOLFSSL_ASN_TEMPLATE
/* Set the DER/BER encoding of the ASN.1 NULL element.
 *
 * output  Buffer to write into.
 * returns the number of bytes added to the buffer.
 */
static int SetASNNull(byte* output)
{
    output[0] = ASN_TAG_NULL;
    output[1] = 0;

    return 2;
}
#endif

#ifndef NO_CERTS
#ifndef WOLFSSL_ASN_TEMPLATE
/* Get the DER/BER encoding of an ASN.1 BOOLEAN.
 *
 * input     Buffer holding DER/BER encoded data.
 * inOutIdx  Current index into buffer to parse.
 * maxIdx    Length of data in buffer.
 * returns BUFFER_E when there is not enough data to parse.
 *         ASN_PARSE_E when the BOOLEAN tag is not found or length is not 1.
 *         Otherwise, 0 to indicate the value was false and 1 to indicate true.
 */
static int GetBoolean(const byte* input, word32* inOutIdx, word32 maxIdx)
{
    word32 idx = *inOutIdx;
    byte   b;

    if ((idx + 3) > maxIdx)
        return BUFFER_E;

    b = input[idx++];
    if (b != ASN_BOOLEAN)
        return ASN_PARSE_E;

    if (input[idx++] != 1)
        return ASN_PARSE_E;

    b = input[idx++] != 0;

    *inOutIdx = idx;
    return b;
}
#endif
#endif /* !NO_CERTS*/


/* Decode the header of a BER/DER encoded OCTET STRING.
 *
 * @param [in]      input     Buffer holding DER/BER encoded data.
 * @param [in, out] inOutIdx  On in, starting index of header.
 *                            On out, end of parsed header.
 * @param [out]     len       Number of bytes in the ASN.1 data.
 * @param [in]      maxIdx    Length of data in buffer.
 * @return  Number of bytes in the ASN.1 data on success.
 * @return  BUFFER_E when there is not enough data to parse.
 * @return  ASN_PARSE_E when the tag is not a OCTET STRING or length is invalid.
 */
int GetOctetString(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
{
    return GetASNHeader(input, ASN_OCTET_STRING, inOutIdx, len, maxIdx);
}

#ifndef WOLFSSL_ASN_TEMPLATE
/* Get the DER/BER encoding of an ASN.1 INTEGER header.
 *
 * Removes the leading zero byte when found.
 *
 * input     Buffer holding DER/BER encoded data.
 * inOutIdx  Current index into buffer to parse.
 * len       The number of bytes in the ASN.1 data (excluding any leading zero).
 * maxIdx    Length of data in buffer.
 * returns BUFFER_E when there is not enough data to parse.
 *         ASN_PARSE_E when the INTEGER tag is not found, length is invalid,
 *         or invalid use of or missing leading zero.
 *         Otherwise, 0 to indicate success.
 */
static int GetASNInt(const byte* input, word32* inOutIdx, int* len,
                     word32 maxIdx)
{
    int    ret;

    ret = GetASNHeader(input, ASN_INTEGER, inOutIdx, len, maxIdx);
    if (ret < 0)
        return ret;

    if (*len > 0) {

#ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
        /* check for invalid padding on negative integer.
         * c.f. X.690 (ISO/IEC 8825-2:2003 (E)) 10.4.6; RFC 5280 4.1
         */
        if (*len > 1) {
            if ((input[*inOutIdx] == 0xff) && (input[*inOutIdx + 1] & 0x80))
                return ASN_PARSE_E;
        }
#endif

        /* remove leading zero, unless there is only one 0x00 byte */
        if ((input[*inOutIdx] == 0x00) && (*len > 1)) {
            (*inOutIdx)++;
            (*len)--;

#ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
            if (*len > 0 && (input[*inOutIdx] & 0x80) == 0)
                return ASN_PARSE_E;
#endif
        }
    }

    return 0;
}

#ifndef NO_CERTS
/* Get the DER/BER encoding of an ASN.1 INTEGER that has a value of no more than
 * 7 bits.
 *
 * input     Buffer holding DER/BER encoded data.
 * inOutIdx  Current index into buffer to parse.
 * maxIdx    Length of data in buffer.
 * returns BUFFER_E when there is not enough data to parse.
 *         ASN_PARSE_E when the INTEGER tag is not found or length is invalid.
 *         Otherwise, the 7-bit value.
 */
static int GetInteger7Bit(const byte* input, word32* inOutIdx, word32 maxIdx)
{
    word32 idx = *inOutIdx;
    byte   b;

    if ((idx + 3) > maxIdx)
        return BUFFER_E;

    if (GetASNTag(input, &idx, &b, maxIdx) != 0)
        return ASN_PARSE_E;
    if (b != ASN_INTEGER)
        return ASN_PARSE_E;
    if (input[idx++] != 1)
        return ASN_PARSE_E;
    b = input[idx++];

    *inOutIdx = idx;
    return b;
}

#if defined(WC_RSA_PSS) && !defined(NO_RSA)
/* Get the DER/BER encoding of an ASN.1 INTEGER that has a value of no more than
 * 16 bits.
 *
 * input     Buffer holding DER/BER encoded data.
 * inOutIdx  Current index into buffer to parse.
 * maxIdx    Length of data in buffer.
 * returns BUFFER_E when there is not enough data to parse.
 *         ASN_PARSE_E when the INTEGER tag is not found or length is invalid.
 *         Otherwise, the 16-bit value.
 */
static int GetInteger16Bit(const byte* input, word32* inOutIdx, word32 maxIdx)
{
    word32 idx = *inOutIdx;
    byte tag;
    word16 n;

    if ((idx + 2) > maxIdx)
        return BUFFER_E;

    if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
        return ASN_PARSE_E;
    if (tag != ASN_INTEGER)
        return ASN_PARSE_E;
    if (input[idx] == 1) {
        idx++;
        if ((idx + 1) > maxIdx) {
            return ASN_PARSE_E;
        }
        n = input[idx++];
    }
    else if (input[idx] == 2) {
        idx++;
        if ((idx + 2) > maxIdx) {
            return ASN_PARSE_E;
        }
        n = input[idx++];
        n = (n << 8) | input[idx++];
    }
    else
        return ASN_PARSE_E;

    *inOutIdx = idx;
    return n;
}
#endif /* WC_RSA_PSS && !NO_RSA */
#endif /* !NO_CERTS */
#endif /* !WOLFSSL_ASN_TEMPLATE */

#if !defined(NO_DSA) && !defined(NO_SHA)
static const char sigSha1wDsaName[] = "SHAwDSA";
static const char sigSha256wDsaName[] = "SHA256wDSA";
#endif /* NO_DSA */
#ifndef NO_RSA
#ifdef WOLFSSL_MD2
    static const char  sigMd2wRsaName[] = "md2WithRSAEncryption";
#endif
#ifndef NO_MD5
    static const char  sigMd5wRsaName[] = "md5WithRSAEncryption";
#endif
#ifndef NO_SHA
    static const char  sigSha1wRsaName[] = "sha1WithRSAEncryption";
#endif
#ifdef WOLFSSL_SHA224
    static const char sigSha224wRsaName[] = "sha224WithRSAEncryption";
#endif
#ifndef NO_SHA256
    static const char sigSha256wRsaName[] = "sha256WithRSAEncryption";
#endif
#ifdef WOLFSSL_SHA384
    static const char sigSha384wRsaName[] = "sha384WithRSAEncryption";
#endif
#ifdef WOLFSSL_SHA512
    static const char sigSha512wRsaName[] = "sha512WithRSAEncryption";
#endif
#ifdef WOLFSSL_SHA3
#ifndef WOLFSSL_NOSHA3_224
    static const char sigSha3_224wRsaName[] = "sha3_224WithRSAEncryption";
#endif
#ifndef WOLFSSL_NOSHA3_256
    static const char sigSha3_256wRsaName[] = "sha3_256WithRSAEncryption";
#endif
#ifndef WOLFSSL_NOSHA3_384
    static const char sigSha3_384wRsaName[] = "sha3_384WithRSAEncryption";
#endif
#ifndef WOLFSSL_NOSHA3_512
    static const char sigSha3_512wRsaName[] = "sha3_512WithRSAEncryption";
#endif
#endif
#ifdef WC_RSA_PSS
    static const char sigRsaSsaPssName[] = "rsassaPss";
#endif
#endif /* NO_RSA */
#ifdef HAVE_ECC
#ifndef NO_SHA
    static const char sigSha1wEcdsaName[] = "SHAwECDSA";
#endif
#ifdef WOLFSSL_SHA224
    static const char sigSha224wEcdsaName[] = "SHA224wECDSA";
#endif
#ifndef NO_SHA256
    static const char sigSha256wEcdsaName[] = "SHA256wECDSA";
#endif
#ifdef WOLFSSL_SHA384
    static const char sigSha384wEcdsaName[] = "SHA384wECDSA";
#endif
#ifdef WOLFSSL_SHA512
    static const char sigSha512wEcdsaName[] = "SHA512wECDSA";
#endif
#ifdef WOLFSSL_SHA3
#ifndef WOLFSSL_NOSHA3_224
    static const char sigSha3_224wEcdsaName[] = "SHA3_224wECDSA";
#endif
#ifndef WOLFSSL_NOSHA3_256
    static const char sigSha3_256wEcdsaName[] = "SHA3_256wECDSA";
#endif
#ifndef WOLFSSL_NOSHA3_384
    static const char sigSha3_384wEcdsaName[] = "SHA3_384wECDSA";
#endif
#ifndef WOLFSSL_NOSHA3_512
    static const char sigSha3_512wEcdsaName[] = "SHA3_512wECDSA";
#endif
#endif
#endif /* HAVE_ECC */
static const char sigUnknownName[] = "Unknown";


/* Get the human readable string for a signature type
 *
 * oid  Oid value for signature
 */
const char* GetSigName(int oid) {
    switch (oid) {
    #if !defined(NO_DSA) && !defined(NO_SHA)
        case CTC_SHAwDSA:
            return sigSha1wDsaName;
        case CTC_SHA256wDSA:
            return sigSha256wDsaName;
    #endif /* NO_DSA && NO_SHA */
    #ifndef NO_RSA
        #ifdef WOLFSSL_MD2
        case CTC_MD2wRSA:
            return sigMd2wRsaName;
        #endif
        #ifndef NO_MD5
        case CTC_MD5wRSA:
            return sigMd5wRsaName;
        #endif
        #ifndef NO_SHA
        case CTC_SHAwRSA:
            return sigSha1wRsaName;
        #endif
        #ifdef WOLFSSL_SHA224
        case CTC_SHA224wRSA:
            return sigSha224wRsaName;
        #endif
        #ifndef NO_SHA256
        case CTC_SHA256wRSA:
            return sigSha256wRsaName;
        #endif
        #ifdef WOLFSSL_SHA384
        case CTC_SHA384wRSA:
            return sigSha384wRsaName;
        #endif
        #ifdef WOLFSSL_SHA512
        case CTC_SHA512wRSA:
            return sigSha512wRsaName;
        #endif
        #ifdef WOLFSSL_SHA3
        #ifndef WOLFSSL_NOSHA3_224
        case CTC_SHA3_224wRSA:
            return sigSha3_224wRsaName;
        #endif
        #ifndef WOLFSSL_NOSHA3_256
        case CTC_SHA3_256wRSA:
            return sigSha3_256wRsaName;
        #endif
        #ifndef WOLFSSL_NOSHA3_384
        case CTC_SHA3_384wRSA:
            return sigSha3_384wRsaName;
        #endif
        #ifndef WOLFSSL_NOSHA3_512
        case CTC_SHA3_512wRSA:
            return sigSha3_512wRsaName;
        #endif
        #endif
        #ifdef WC_RSA_PSS
        case CTC_RSASSAPSS:
            return sigRsaSsaPssName;
        #endif
    #endif /* NO_RSA */
    #ifdef HAVE_ECC
        #ifndef NO_SHA
        case CTC_SHAwECDSA:
            return sigSha1wEcdsaName;
        #endif
        #ifdef WOLFSSL_SHA224
        case CTC_SHA224wECDSA:
            return sigSha224wEcdsaName;
        #endif
        #ifndef NO_SHA256
        case CTC_SHA256wECDSA:
            return sigSha256wEcdsaName;
        #endif
        #ifdef WOLFSSL_SHA384
        case CTC_SHA384wECDSA:
            return sigSha384wEcdsaName;
        #endif
        #ifdef WOLFSSL_SHA512
        case CTC_SHA512wECDSA:
            return sigSha512wEcdsaName;
        #endif
        #ifdef WOLFSSL_SHA3
        #ifndef WOLFSSL_NOSHA3_224
        case CTC_SHA3_224wECDSA:
            return sigSha3_224wEcdsaName;
        #endif
        #ifndef WOLFSSL_NOSHA3_256
        case CTC_SHA3_256wECDSA:
            return sigSha3_256wEcdsaName;
        #endif
        #ifndef WOLFSSL_NOSHA3_384
        case CTC_SHA3_384wECDSA:
            return sigSha3_384wEcdsaName;
        #endif
        #ifndef WOLFSSL_NOSHA3_512
        case CTC_SHA3_512wECDSA:
            return sigSha3_512wEcdsaName;
        #endif
        #endif
    #endif /* HAVE_ECC */
        default:
            return sigUnknownName;
    }
}


#if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS7) || \
    defined(OPENSSL_EXTRA)
#if !defined(NO_DSA) || defined(HAVE_ECC) || !defined(NO_CERTS) || \
   (!defined(NO_RSA) && \
        (defined(WOLFSSL_CERT_GEN) || \
        ((defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)) && !defined(HAVE_USER_RSA))))
/* Set the DER/BER encoding of the ASN.1 INTEGER header.
 *
 * When output is NULL, calculate the header length only.
 *
 * @param [in]  len        Length of INTEGER data in bytes.
 * @param [in]  firstByte  First byte of data, most significant byte of integer,
 *                         to encode.
 * @param [out] output     Buffer to write into.
 * @return  Number of bytes added to the buffer.
 */
int SetASNInt(int len, byte firstByte, byte* output)
{
    int idx = 0;

    if (output) {
        /* Write out tag. */
        output[idx] = ASN_INTEGER;
    }
    /* Step over tag. */
    idx += ASN_TAG_SZ;
    /* Check if first byte has top bit set in which case a 0 is needed to
     * maintain positive value. */
    if (firstByte & 0x80) {
        /* Add pre-prepended byte to length of data in INTEGER. */
        len++;
    }
    /* Encode length - passing NULL for output will not encode. */
    idx += (int)SetLength((word32)len, output ? output + idx : NULL);
    /* Put out pre-pended 0 as well. */
    if (firstByte & 0x80) {
        if (output) {
            /* Write out 0 byte. */
            output[idx] = 0x00;
        }
        /* Update index. */
        idx++;
    }

    /* Return index after header. */
    return idx;
}
#endif
#endif

#ifndef WOLFSSL_ASN_TEMPLATE
#if !defined(NO_DSA) || defined(HAVE_ECC) || (defined(WOLFSSL_CERT_GEN) && \
    !defined(NO_RSA)) || ((defined(WOLFSSL_KEY_GEN) || \
    (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)) || \
    defined(OPENSSL_EXTRA)) && !defined(NO_RSA) && !defined(HAVE_USER_RSA))
/* Set the DER/BER encoding of the ASN.1 INTEGER element with an mp_int.
 * The number is assumed to be positive.
 *
 * n       Multi-precision integer to encode.
 * maxSz   Maximum size of the encoded integer.
 *         A negative value indicates no check of length requested.
 * output  Buffer to write into.
 * returns BUFFER_E when the data is too long for the buffer.
 *         MP_TO_E when encoding the integer fails.
 *         Otherwise, the number of bytes added to the buffer.
 */
static int SetASNIntMP(mp_int* n, int maxSz, byte* output)
{
    int idx = 0;
    int leadingBit;
    int length;

    leadingBit = mp_leading_bit(n);
    length = mp_unsigned_bin_size(n);
    if (maxSz >= 0 && (1 + length + (leadingBit ? 1 : 0)) > maxSz)
        return BUFFER_E;
    idx = SetASNInt(length, (byte)(leadingBit ? 0x80U : 0x00U), output);
    if (maxSz >= 0 && (idx + length) > maxSz)
        return BUFFER_E;

    if (output) {
        int err = mp_to_unsigned_bin(n, output + idx);
        if (err != MP_OKAY)
            return MP_TO_E;
    }
    idx += length;

    return idx;
}
#endif

#if !defined(NO_RSA) && defined(HAVE_USER_RSA) && \
    (defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA))
/* Set the DER/BER encoding of the ASN.1 INTEGER element with an mp_int from
 * an RSA key.
 * The number is assumed to be positive.
 *
 * n       Multi-precision integer to encode.
 * output  Buffer to write into.
 * returns BUFFER_E when the data is too long for the buffer.
 *         MP_TO_E when encoding the integer fails.
 *         Otherwise, the number of bytes added to the buffer.
 */
static int SetASNIntRSA(void* n, byte* output)
{
    int idx = 0;
    int leadingBit;
    int length;

    leadingBit = wc_Rsa_leading_bit(n);
    length = wc_Rsa_unsigned_bin_size(n);
    idx = SetASNInt(length, leadingBit ? 0x80 : 0x00, output);
    if ((idx + length) > MAX_RSA_INT_SZ)
        return BUFFER_E;

    if (output) {
        int err = wc_Rsa_to_unsigned_bin(n, output + idx, length);
        if (err != MP_OKAY)
            return MP_TO_E;
    }
    idx += length;

    return idx;
}
#endif /* !NO_RSA && HAVE_USER_RSA && WOLFSSL_CERT_GEN */
#endif /* !WOLFSSL_ASN_TEMPLATE */

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for an INTEGER. */
static const ASNItem intASN[] = {
/* INT */ { 0, ASN_INTEGER, 0, 0, 0 }
};
enum {
    INTASN_IDX_INT = 0
};

/* Number of items in ASN.1 template for an INTEGER. */
#define intASN_Length (sizeof(intASN) / sizeof(ASNItem))
#endif /* WOLFSSL_ASN_TEMPLATE */

/* Windows header clash for WinCE using GetVersion */
/* Decode Version - one byte INTEGER.
 *
 * @param [in]      input     Buffer of BER data.
 * @param [in, out] inOutIdx  On in, start of encoded Version.
 *                            On out, start of next encode ASN.1 item.
 * @param [out]     version   Number encoded in INTEGER.
 * @param [in]      maxIdx    Maximum index of data in buffer.
 * @return  0 on success.
 * @return  ASN_PARSE_E when encoding is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_EXPECT_0_E when the most significant bit is set.
 */
int GetMyVersion(const byte* input, word32* inOutIdx,
                               int* version, word32 maxIdx)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx = *inOutIdx;
    byte   tag;

    if ((idx + MIN_VERSION_SZ) > maxIdx)
        return ASN_PARSE_E;

    if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
        return ASN_PARSE_E;

    if (tag != ASN_INTEGER)
        return ASN_PARSE_E;

    if (input[idx++] != 0x01)
        return ASN_VERSION_E;

    *version  = input[idx++];
    *inOutIdx = idx;

    return *version;
#else
    ASNGetData dataASN[intASN_Length];
    int ret;
    byte num;

    /* Clear dynamic data and set the version number variable. */
    XMEMSET(dataASN, 0, sizeof(dataASN));
    GetASN_Int8Bit(&dataASN[INTASN_IDX_INT], &num);
    /* Decode the version (INTEGER). */
    ret = GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
                       maxIdx);
    if (ret == 0) {
        /* Return version through variable and return value. */
        *version = num;
        ret = num;
    }
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}


#ifndef NO_PWDBASED
/* Decode small integer, 32 bits or less.
 *
 * @param [in]      input     Buffer of BER data.
 * @param [in, out] inOutIdx  On in, start of encoded INTEGER.
 *                            On out, start of next encode ASN.1 item.
 * @param [out]     number    Number encoded in INTEGER.
 * @param [in]      maxIdx    Maximum index of data in buffer.
 * @return  0 on success.
 * @return  ASN_PARSE_E when encoding is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_EXPECT_0_E when the most significant bit is set.
 */
int GetShortInt(const byte* input, word32* inOutIdx, int* number, word32 maxIdx)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx = *inOutIdx;
    word32 len;
    byte   tag;

    *number = 0;

    /* check for type and length bytes */
    if ((idx + 2) > maxIdx)
        return BUFFER_E;

    if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
        return ASN_PARSE_E;

    if (tag != ASN_INTEGER)
        return ASN_PARSE_E;

    len = input[idx++];
    if (len > 4)
        return ASN_PARSE_E;

    if (len + idx > maxIdx)
        return ASN_PARSE_E;

    while (len--) {
        *number  = *number << 8 | input[idx++];
    }

    *inOutIdx = idx;

    return *number;
#else
    ASNGetData dataASN[intASN_Length];
    int ret;
    word32 num;

    /* Clear dynamic data and set the 32-bit number variable. */
    XMEMSET(dataASN, 0, sizeof(dataASN));
    GetASN_Int32Bit(&dataASN[INTASN_IDX_INT], &num);
    /* Decode the short int (INTEGER). */
    ret = GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
                       maxIdx);
    if (ret == 0) {
        /* Return number through variable and return value. */
        *number = (int)num;
        ret = (int)num;
    }
    return ret;
#endif
}


#if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS8) || \
     defined(HAVE_PKCS12)
/* Set small integer, 32 bits or less. DER encoding with no leading 0s
 * returns total amount written including ASN tag and length byte on success */
int SetShortInt(byte* input, word32* inOutIdx, word32 number, word32 maxIdx)
{
    word32 idx = *inOutIdx;
    int    len = 0;
    int    i;
    byte ar[MAX_LENGTH_SZ];

    /* check for room for type and length bytes */
    if ((idx + 2) > maxIdx)
        return BUFFER_E;

    input[idx++] = ASN_INTEGER;
    idx++; /* place holder for length byte */
    if (MAX_LENGTH_SZ + idx > maxIdx)
        return ASN_PARSE_E;

    /* find first non zero byte */
    XMEMSET(ar, 0, MAX_LENGTH_SZ);
    c32toa(number, ar);
    for (i = 0; i < MAX_LENGTH_SZ; i++) {
        if (ar[i] != 0) {
            break;
        }
    }

    /* handle case of 0 */
    if (i == MAX_LENGTH_SZ) {
        input[idx++] = 0; len++;
    }

    for (; i < MAX_LENGTH_SZ && idx < maxIdx; i++) {
        input[idx++] = ar[i]; len++;
    }

    /* jump back to beginning of input buffer using unaltered inOutIdx value
     * and set number of bytes for integer, then update the index value */
    input[*inOutIdx + 1] = (byte)len;
    *inOutIdx = idx;

    return len + 2; /* size of integer bytes plus ASN TAG and length byte */
}
#endif /* !WOLFSSL_ASN_TEMPLATE || HAVE_PKCS8 || HAVE_PKCS12 */
#endif /* !NO_PWDBASED */

#ifndef WOLFSSL_ASN_TEMPLATE
/* May not have one, not an error */
static int GetExplicitVersion(const byte* input, word32* inOutIdx, int* version,
                              word32 maxIdx)
{
    word32 idx = *inOutIdx;
    byte tag;

    WOLFSSL_ENTER("GetExplicitVersion");

    if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
        return ASN_PARSE_E;

    if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
        int ret;

        *inOutIdx = ++idx;  /* skip header */
        ret = GetMyVersion(input, inOutIdx, version, maxIdx);
        if (ret >= 0) {
            /* check if version is expected value rfc 5280 4.1 {0, 1, 2} */
            if (*version > MAX_X509_VERSION || *version < MIN_X509_VERSION) {
                WOLFSSL_MSG("Unexpected certificate version");
                WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
                ret = ASN_VERSION_E;
            }
        }
        return ret;
    }

    /* go back as is */
    *version = 0;

    return 0;
}
#endif

/* Decode small integer, 32 bits or less.
 *
 * mp_int is initialized.
 *
 * @param [out]     mpi       mp_int to hold number.
 * @param [in]      input     Buffer of BER data.
 * @param [in, out] inOutIdx  On in, start of encoded INTEGER.
 *                            On out, start of next encode ASN.1 item.
 * @param [in]      maxIdx    Maximum index of data in buffer.
 * @return  0 on success.
 * @return  ASN_PARSE_E when encoding is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_EXPECT_0_E when the most significant bit is set.
 * @return  MP_INIT_E when the unable to initialize an mp_int.
 * @return  ASN_GETINT_E when the unable to convert data to an mp_int.
 */
int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx, word32 maxIdx)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx = *inOutIdx;
    int    ret;
    int    length;

    ret = GetASNInt(input, &idx, &length, maxIdx);
    if (ret != 0)
        return ret;

    if (mp_init(mpi) != MP_OKAY)
        return MP_INIT_E;

    if (mp_read_unsigned_bin(mpi, input + idx, (word32)length) != 0) {
        mp_clear(mpi);
        return ASN_GETINT_E;
    }

#ifdef HAVE_WOLF_BIGINT
    if (wc_bigint_from_unsigned_bin(&mpi->raw, input + idx, length) != 0) {
        mp_clear(mpi);
        return ASN_GETINT_E;
    }
#endif /* HAVE_WOLF_BIGINT */

    *inOutIdx = idx + (word32)length;

    return 0;
#else
    ASNGetData dataASN[intASN_Length];

    /* Clear dynamic data and set the mp_int to fill with value. */
    XMEMSET(dataASN, 0, sizeof(dataASN));
    GetASN_MP_PosNeg(&dataASN[INTASN_IDX_INT], mpi);
    /* Decode the big number (INTEGER). */
    return GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
                        maxIdx);
#endif
}

#if (defined(HAVE_ECC) || !defined(NO_DSA)) && !defined(WOLFSSL_ASN_TEMPLATE)
static int GetIntPositive(mp_int* mpi, const byte* input, word32* inOutIdx,
    word32 maxIdx, int initNum)
{
    word32 idx = *inOutIdx;
    int    ret;
    int    length;

    ret = GetASNInt(input, &idx, &length, maxIdx);
    if (ret != 0)
        return ret;

    if (((input[idx] & 0x80) == 0x80) && (input[idx - 1] != 0x00))
        return MP_INIT_E;

    if (initNum) {
        if (mp_init(mpi) != MP_OKAY)
            return MP_INIT_E;
    }

    if (mp_read_unsigned_bin(mpi, input + idx, (word32)length) != 0) {
        mp_clear(mpi);
        return ASN_GETINT_E;
    }

#ifdef HAVE_WOLF_BIGINT
    if (wc_bigint_from_unsigned_bin(&mpi->raw, input + idx, length) != 0) {
        mp_clear(mpi);
        return ASN_GETINT_E;
    }
#endif /* HAVE_WOLF_BIGINT */

    *inOutIdx = idx + (word32)length;

    return 0;
}
#endif /* (ECC || !NO_DSA) && !WOLFSSL_ASN_TEMPLATE */

#ifndef WOLFSSL_ASN_TEMPLATE
#if (!defined(NO_RSA) && !defined(HAVE_USER_RSA)) || !defined(NO_DSA)
static int SkipInt(const byte* input, word32* inOutIdx, word32 maxIdx)
{
    word32 idx = *inOutIdx;
    int    ret;
    int    length;

    ret = GetASNInt(input, &idx, &length, maxIdx);
    if (ret != 0)
        return ret;

    *inOutIdx = idx + (word32)length;

    return 0;
}
#endif
#endif /* !WOLFSSL_ASN_TEMPLATE */

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for a BIT_STRING. */
static const ASNItem bitStringASN[] = {
/* BIT_STR */ { 0, ASN_BIT_STRING, 0, 1, 0 }
};
enum {
    BITSTRINGASN_IDX_BIT_STR = 0
};

/* Number of items in ASN.1 template for a BIT_STRING. */
#define bitStringASN_Length (sizeof(bitStringASN) / sizeof(ASNItem))
#endif

/* Decode and check the BIT_STRING is valid. Return length and unused bits.
 *
 * @param [in]      input       Buffer holding BER encoding.
 * @param [in, out] inOutIdx    On in, start of BIT_STRING.
 *                              On out, start of ASN.1 item after BIT_STRING.
 * @param [out]     len         Length of BIT_STRING data.
 * @param [in]      maxIdx      Maximum index of data in buffer.
 * @param [in]      zeroBits    Indicates whether zero unused bits is expected.
 * @param [in]      unusedBits  Number of unused bits in last byte.
 * @return  0 on success.
 * @return  ASN_PARSE_E when encoding is invalid.
 * @return  ASN_BITSTR_E when the expected BIT_STRING tag is not found.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_EXPECT_0_E when unused bits is not zero when expected.
 */
int CheckBitString(const byte* input, word32* inOutIdx, int* len,
                          word32 maxIdx, int zeroBits, byte* unusedBits)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx = *inOutIdx;
    int    length;
    byte   b;

    if (GetASNTag(input, &idx, &b, maxIdx) != 0) {
        return ASN_BITSTR_E;
    }

    if (b != ASN_BIT_STRING) {
        return ASN_BITSTR_E;
    }

    if (GetLength(input, &idx, &length, maxIdx) < 0)
        return ASN_PARSE_E;

    /* extra sanity check that length is greater than 0 */
    if (length <= 0) {
        WOLFSSL_MSG("Error length was 0 in CheckBitString");
        return BUFFER_E;
    }

    if (idx + 1 > maxIdx) {
        WOLFSSL_MSG("Attempted buffer read larger than input buffer");
        return BUFFER_E;
    }

    b = input[idx];
    if (zeroBits && b != 0x00)
        return ASN_EXPECT_0_E;
    if (b >= 0x08)
        return ASN_PARSE_E;
    if (b != 0) {
        if ((byte)(input[idx + (word32)length - 1] << (8 - b)) != 0)
            return ASN_PARSE_E;
    }
    idx++;
    length--; /* length has been checked for greater than 0 */

    *inOutIdx = idx;
    if (len != NULL)
        *len = length;
    if (unusedBits != NULL)
        *unusedBits = b;

    return 0;
#else
    ASNGetData dataASN[bitStringASN_Length];
    int ret;
    int bits;

    /* Parse BIT_STRING and check validity of unused bits. */
    XMEMSET(dataASN, 0, sizeof(dataASN));
    /* Decode BIT_STRING. */
    ret = GetASN_Items(bitStringASN, dataASN, bitStringASN_Length, 0, input,
            inOutIdx, maxIdx);
    if (ret == 0) {
        /* Get unused bits from dynamic ASN.1 data. */
        bits = GetASNItem_UnusedBits(dataASN[BITSTRINGASN_IDX_BIT_STR]);
        /* Check unused bits is 0 when expected. */
        if (zeroBits && (bits != 0)) {
            ret = ASN_EXPECT_0_E;
        }
    }
    if (ret == 0) {
        /* Return length of data and unused bits if required. */
        if (len != NULL) {
            *len = (int)dataASN[BITSTRINGASN_IDX_BIT_STR].data.ref.length;
        }
        if (unusedBits != NULL) {
            *unusedBits = (byte)bits;
        }
    }

    return ret;
#endif
}

/* RSA (with CertGen or KeyGen) OR ECC OR ED25519 OR ED448 (with CertGen or
 * KeyGen) */
#if (!defined(NO_RSA) && !defined(HAVE_USER_RSA) && \
     (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN) || \
      defined(OPENSSL_EXTRA))) || \
    (defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)) || \
    ((defined(HAVE_ED25519) || defined(HAVE_ED448)) && \
     (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN) || \
      defined(OPENSSL_EXTRA))) || \
    (defined(WC_ENABLE_ASYM_KEY_EXPORT) && !defined(NO_CERT)) || \
    (!defined(NO_DSA) && !defined(HAVE_SELFTEST) && defined(WOLFSSL_KEY_GEN)) || \
    (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA))

/* Set the DER/BER encoding of the ASN.1 BIT STRING header.
 *
 * When output is NULL, calculate the header length only.
 *
 * @param [in]  len         Length of BIT STRING data.
 *                          That is, the number of least significant zero bits
 *                          before a one.
 *                          The last byte is the most-significant non-zero byte
 *                          of a number.
 * @param [out] output      Buffer to write into.
 * @return  Number of bytes added to the buffer.
 */
word32 SetBitString(word32 len, byte unusedBits, byte* output)
{
    word32 idx = 0;

    if (output) {
        /* Write out tag. */
        output[idx] = ASN_BIT_STRING;
    }
    /* Step over tag. */
    idx += ASN_TAG_SZ;

    /* Encode length - passing NULL for output will not encode.
     * Add one to length for unused bits. */
    idx += SetLength(len + 1, output ? output + idx : NULL);
    if (output) {
        /* Write out unused bits. */
        output[idx] = unusedBits;
    }
    /* Skip over unused bits. */
    idx++;

    /* Return index after header. */
    return idx;
}
#endif /* !NO_RSA || HAVE_ECC || HAVE_ED25519 || HAVE_ED448 */

#ifdef ASN_BER_TO_DER
/* Convert BER to DER */

/* Pull informtation from the ASN.1 BER encoded item header */
static int GetBerHeader(const byte* data, word32* idx, word32 maxIdx,
                        byte* pTag, word32* pLen, int* indef)
{
    int len = 0;
    byte tag;
    word32 i = *idx;

    *indef = 0;

    /* Check there is enough data for a minimal header */
    if (i + 2 > maxIdx) {
        return ASN_PARSE_E;
    }

    /* Retrieve tag */
    tag = data[i++];

    /* Indefinite length handled specially */
    if (data[i] == ASN_INDEF_LENGTH) {
        /* Check valid tag for indefinite */
        if (((tag & 0xc0) == 0) && ((tag & ASN_CONSTRUCTED) == 0x00)) {
            return ASN_PARSE_E;
        }
        i++;
        *indef = 1;
    }
    else if (GetLength(data, &i, &len, maxIdx) < 0) {
        return ASN_PARSE_E;
    }

    /* Return tag, length and index after BER item header */
    *pTag = tag;
    *pLen = (word32)len;
    *idx = i;
    return 0;
}

#ifndef INDEF_ITEMS_MAX
#define INDEF_ITEMS_MAX       20
#endif

/* Indef length item data */
typedef struct Indef {
    word32 start;
    int depth;
    int headerLen;
    word32 len;
} Indef;

/* Indef length items */
typedef struct IndefItems
{
    Indef len[INDEF_ITEMS_MAX];
    int cnt;
    int idx;
    int depth;
} IndefItems;


/* Get header length of current item */
static int IndefItems_HeaderLen(IndefItems* items)
{
    return items->len[items->idx].headerLen;
}

/* Get data length of current item */
static word32 IndefItems_Len(IndefItems* items)
{
    return items->len[items->idx].len;
}

/* Add a indefinite length item */
static int IndefItems_AddItem(IndefItems* items, word32 start)
{
    int ret = 0;
    int i;

    if (items->cnt == INDEF_ITEMS_MAX) {
        ret = MEMORY_E;
    }
    else {
        i = items->cnt++;
        items->len[i].start = start;
        items->len[i].depth = items->depth++;
        items->len[i].headerLen = 1;
        items->len[i].len = 0;
        items->idx = i;
    }

    return ret;
}

/* Increase data length of current item */
static void IndefItems_AddData(IndefItems* items, word32 length)
{
    items->len[items->idx].len += length;
}

/* Update header length of current item to reflect data length */
static void IndefItems_UpdateHeaderLen(IndefItems* items)
{
    items->len[items->idx].headerLen +=
                               (int)SetLength(items->len[items->idx].len, NULL);
}

/* Go to indefinite parent of current item */
static void IndefItems_Up(IndefItems* items)
{
    int i;
    int depth = items->len[items->idx].depth - 1;

    for (i = items->cnt - 1; i >= 0; i--) {
        if (items->len[i].depth == depth) {
            break;
        }
    }
    items->idx = i;
    items->depth = depth + 1;
}

/* Calculate final length by adding length of indefinite child items */
static void IndefItems_CalcLength(IndefItems* items)
{
    int i;
    int idx = items->idx;

    for (i = idx + 1; i < items->cnt; i++) {
        if (items->len[i].depth == items->depth) {
            items->len[idx].len += (word32)items->len[i].headerLen;
            items->len[idx].len += items->len[i].len;
        }
    }
    items->len[idx].headerLen += (int)SetLength(items->len[idx].len, NULL);
}

/* Add more data to indefinite length item */
static void IndefItems_MoreData(IndefItems* items, word32 length)
{
    if (items->cnt > 0 && items->idx >= 0) {
        items->len[items->idx].len += length;
    }
}

/* Convert a BER encoding with indefinite length items to DER.
 *
 * ber    BER encoded data.
 * berSz  Length of BER encoded data.
 * der    Buffer to hold DER encoded version of data.
 *        NULL indicates only the length is required.
 * derSz  The size of the buffer to hold the DER encoded data.
 *        Will be set if der is NULL, otherwise the value is checked as der is
 *        filled.
 * returns ASN_PARSE_E if the BER data is invalid and BAD_FUNC_ARG if ber or
 * derSz are NULL.
 */
int wc_BerToDer(const byte* ber, word32 berSz, byte* der, word32* derSz)
{
    int ret = 0;
    word32 i, j;
#ifdef WOLFSSL_SMALL_STACK
    IndefItems* indefItems = NULL;
#else
    IndefItems indefItems[1];
#endif
    byte tag, basic;
    word32 length;
    int indef;

    if (ber == NULL || derSz == NULL)
        return BAD_FUNC_ARG;

#ifdef WOLFSSL_SMALL_STACK
    indefItems = (IndefItems *)XMALLOC(sizeof(IndefItems), NULL,
                                                       DYNAMIC_TYPE_TMP_BUFFER);
    if (indefItems == NULL) {
        ret = MEMORY_E;
        goto end;
    }
#endif

    XMEMSET(indefItems, 0, sizeof(*indefItems));

    /* Calculate indefinite item lengths */
    for (i = 0; i < berSz; ) {
        word32 start = i;

        /* Get next BER item */
        ret = GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
        if (ret != 0) {
            goto end;
        }

        if (indef) {
            /* Indefinite item - add to list */
            ret = IndefItems_AddItem(indefItems, i);
            if (ret != 0) {
                goto end;
            }

            if ((tag & 0xC0) == 0 &&
                tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
                tag != (ASN_SET      | ASN_CONSTRUCTED)) {
                /* Constructed basic type - get repeating tag */
                basic = (byte)(tag & (~ASN_CONSTRUCTED));

                /* Add up lengths of each item below */
                for (; i < berSz; ) {
                    /* Get next BER_item */
                    ret = GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
                    if (ret != 0) {
                        goto end;
                    }

                    /* End of content closes item */
                    if (tag == ASN_EOC) {
                        /* Must be zero length */
                        if (length != 0) {
                            ret = ASN_PARSE_E;
                            goto end;
                        }
                        break;
                    }

                    /* Must not be indefinite and tag must match parent */
                    if (indef || tag != basic) {
                        ret = ASN_PARSE_E;
                        goto end;
                    }

                    /* Add to length */
                    IndefItems_AddData(indefItems, length);
                    /* Skip data */
                    i += length;
                }

                /* Ensure we got an EOC and not end of data */
                if (tag != ASN_EOC) {
                    ret = ASN_PARSE_E;
                    goto end;
                }

                /* Set the header length to include the length field */
                IndefItems_UpdateHeaderLen(indefItems);
                /* Go to indefinite parent item */
                IndefItems_Up(indefItems);
            }
        }
        else if (tag == ASN_EOC) {
            /* End-of-content must be 0 length */
            if (length != 0) {
                ret = ASN_PARSE_E;
                goto end;
            }
            /* Check there is an item to close - missing EOC */
            if (indefItems->depth == 0) {
                ret = ASN_PARSE_E;
                goto end;
            }

            /* Finish calculation of data length for indefinite item */
            IndefItems_CalcLength(indefItems);
            /* Go to indefinite parent item */
            IndefItems_Up(indefItems);
        }
        else {
            /* Known length item to add in - make sure enough data for it */
            if (i + length > berSz) {
                ret = ASN_PARSE_E;
                goto end;
            }

            /* Include all data - can't have indefinite inside definite */
            i += length;
            /* Add entire item to current indefinite item */
            IndefItems_MoreData(indefItems, i - start);
        }
    }
    /* Check we had a EOC for each indefinite item */
    if (indefItems->depth != 0) {
        ret = ASN_PARSE_E;
        goto end;
    }

    /* Write out DER */

    j = 0;
    /* Reset index */
    indefItems->idx = 0;
    for (i = 0; i < berSz; ) {
        word32 start = i;

        /* Get item - checked above */
        (void)GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
        if (indef) {
            if (der != NULL) {
                /* Check enough space for header */
                if (j + (word32)IndefItems_HeaderLen(indefItems) > *derSz) {
                    ret = BUFFER_E;
                    goto end;
                }

                if ((tag & 0xC0) == 0 &&
                    tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
                    tag != (ASN_SET      | ASN_CONSTRUCTED)) {
                    /* Remove constructed tag for basic types */
                    tag &= (byte)~ASN_CONSTRUCTED;
                }
                /* Add tag and length */
                der[j] = tag;
                (void)SetLength(IndefItems_Len(indefItems), der + j + 1);
            }
            /* Add header length of indefinite item */
            j += (word32)IndefItems_HeaderLen(indefItems);

            if ((tag & 0xC0) == 0 &&
                tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
                tag != (ASN_SET      | ASN_CONSTRUCTED)) {
                /* For basic type - get each child item and add data */
                for (; i < berSz; ) {
                    (void)GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
                    if (tag == ASN_EOC) {
                        break;
                    }
                    if (der != NULL) {
                        if (j + length > *derSz) {
                            ret = BUFFER_E;
                            goto end;
                        }
                        XMEMCPY(der + j, ber + i, length);
                    }
                    j += length;
                    i += length;
                }
            }

            /* Move to next indef item in list */
            indefItems->idx++;
        }
        else if (tag == ASN_EOC) {
            /* End-Of-Content is not written out in DER */
        }
        else {
            /* Write out definite length item as is. */
            i += length;
            if (der != NULL) {
                /* Ensure space for item */
                if (j + i - start > *derSz) {
                    ret = BUFFER_E;
                    goto end;
                }
                /* Copy item as is */
                XMEMCPY(der + j, ber + start, i - start);
            }
            j += i - start;
        }
    }

    /* Return the length of the DER encoded ASN.1 */
    *derSz = j;
    if (der == NULL) {
        ret = LENGTH_ONLY_E;
    }
end:
#ifdef WOLFSSL_SMALL_STACK
    if (indefItems != NULL) {
        XFREE(indefItems, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    }
#endif
    return ret;
}
#endif

#ifndef WOLFSSL_ASN_TEMPLATE
#if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CERT_GEN)
/* Set the DER/BER encoding of the ASN.1 BIT_STRING with a 16-bit value.
 *
 * val         16-bit value to encode.
 * output      Buffer to write into.
 * returns the number of bytes added to the buffer.
 */
static word32 SetBitString16Bit(word16 val, byte* output)
{
    word32 idx;
    int    len;
    byte   lastByte;
    byte   unusedBits = 0;

    if ((val >> 8) != 0) {
        len = 2;
        lastByte = (byte)(val >> 8);
    }
    else {
        len = 1;
        lastByte = (byte)val;
    }

    while (((lastByte >> unusedBits) & 0x01) == 0x00)
        unusedBits++;

    idx = SetBitString((word32)len, unusedBits, output);
    output[idx++] = (byte)val;
    if (len > 1)
        output[idx++] = (byte)(val >> 8);

    return idx;
}
#endif /* WOLFSSL_CERT_EXT || WOLFSSL_CERT_GEN */
#endif /* !WOLFSSL_ASN_TEMPLATE */

/* hashType */
#ifdef WOLFSSL_MD2
    static const byte hashMd2hOid[] = {42, 134, 72, 134, 247, 13, 2, 2};
#endif
#ifndef NO_MD5
    static const byte hashMd5hOid[] = {42, 134, 72, 134, 247, 13, 2, 5};
#endif
#ifndef NO_SHA
    static const byte hashSha1hOid[] = {43, 14, 3, 2, 26};
#endif
#ifdef WOLFSSL_SHA224
    static const byte hashSha224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 4};
#endif
#ifndef NO_SHA256
    static const byte hashSha256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 1};
#endif
#ifdef WOLFSSL_SHA384
    static const byte hashSha384hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 2};
#endif
#ifdef WOLFSSL_SHA512
    static const byte hashSha512hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 3};
    #ifndef WOLFSSL_NOSHA512_224
    static const byte hashSha512_224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 5};
    #endif
    #ifndef WOLFSSL_NOSHA512_256
    static const byte hashSha512_256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 6};
    #endif
#endif
#ifdef WOLFSSL_SHA3
#ifndef WOLFSSL_NOSHA3_224
    static const byte hashSha3_224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 7};
#endif /* WOLFSSL_NOSHA3_224 */
#ifndef WOLFSSL_NOSHA3_256
    static const byte hashSha3_256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 8};
#endif /* WOLFSSL_NOSHA3_256 */
#ifndef WOLFSSL_NOSHA3_384
    static const byte hashSha3_384hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 9};
#endif /* WOLFSSL_NOSHA3_384 */
#ifndef WOLFSSL_NOSHA3_512
    static const byte hashSha3_512hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 10};
#endif /* WOLFSSL_NOSHA3_512 */
#endif /* WOLFSSL_SHA3 */

/* hmacType */
#ifndef NO_HMAC
    #ifdef WOLFSSL_SHA224
    static const byte hmacSha224Oid[] = {42, 134, 72, 134, 247, 13, 2, 8};
    #endif
    #ifndef NO_SHA256
    static const byte hmacSha256Oid[] = {42, 134, 72, 134, 247, 13, 2, 9};
    #endif
    #ifdef WOLFSSL_SHA384
    static const byte hmacSha384Oid[] = {42, 134, 72, 134, 247, 13, 2, 10};
    #endif
    #ifdef WOLFSSL_SHA512
    static const byte hmacSha512Oid[] = {42, 134, 72, 134, 247, 13, 2, 11};
    #endif
#endif

/* sigType */
#if !defined(NO_DSA) && !defined(NO_SHA)
    static const byte sigSha1wDsaOid[] = {42, 134, 72, 206, 56, 4, 3};
    static const byte sigSha256wDsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 2};
#endif /* NO_DSA */
#ifndef NO_RSA
    #ifdef WOLFSSL_MD2
    static const byte sigMd2wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 2};
    #endif
    #ifndef NO_MD5
    static const byte sigMd5wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 4};
    #endif
    #ifndef NO_SHA
    static const byte sigSha1wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 5};
    #endif
    #ifdef WOLFSSL_SHA224
    static const byte sigSha224wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,14};
    #endif
    #ifndef NO_SHA256
    static const byte sigSha256wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,11};
    #endif
    #ifdef WOLFSSL_SHA384
    static const byte sigSha384wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,12};
    #endif
    #ifdef WOLFSSL_SHA512
    static const byte sigSha512wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,13};
    #endif
    #ifdef WOLFSSL_SHA3
    #ifndef WOLFSSL_NOSHA3_224
    static const byte sigSha3_224wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 13};
    #endif
    #ifndef WOLFSSL_NOSHA3_256
    static const byte sigSha3_256wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 14};
    #endif
    #ifndef WOLFSSL_NOSHA3_384
    static const byte sigSha3_384wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 15};
    #endif
    #ifndef WOLFSSL_NOSHA3_512
    static const byte sigSha3_512wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 16};
    #endif
    #endif
    #ifdef WC_RSA_PSS
    static const byte sigRsaSsaPssOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 10};
    #endif
#endif /* NO_RSA */
#ifdef HAVE_ECC
    #ifndef NO_SHA
    static const byte sigSha1wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 1};
    #endif
    #ifdef WOLFSSL_SHA224
    static const byte sigSha224wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 1};
    #endif
    #ifndef NO_SHA256
    static const byte sigSha256wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 2};
    #endif
    #ifdef WOLFSSL_SHA384
    static const byte sigSha384wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 3};
    #endif
    #ifdef WOLFSSL_SHA512
    static const byte sigSha512wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 4};
    #endif
    #ifdef WOLFSSL_SHA3
    #ifndef WOLFSSL_NOSHA3_224
    static const byte sigSha3_224wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 9};
    #endif
    #ifndef WOLFSSL_NOSHA3_256
    static const byte sigSha3_256wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 10};
    #endif
    #ifndef WOLFSSL_NOSHA3_384
    static const byte sigSha3_384wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 11};
    #endif
    #ifndef WOLFSSL_NOSHA3_512
    static const byte sigSha3_512wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 12};
    #endif
    #endif
#endif /* HAVE_ECC */
#ifdef HAVE_ED25519
    static const byte sigEd25519Oid[] = {43, 101, 112};
#endif /* HAVE_ED25519 */
#ifdef HAVE_ED448
    static const byte sigEd448Oid[] = {43, 101, 113};
#endif /* HAVE_ED448 */
#ifdef HAVE_PQC
#ifdef HAVE_FALCON
    /* Falcon Level 1: 1 3 9999 3 1 */
    static const byte sigFalcon_Level1Oid[] = {43, 206, 15, 3, 1};

    /* Falcon Level 5: 1 3 9999 3 4 */
    static const byte sigFalcon_Level5Oid[] = {43, 206, 15, 3, 4};
#endif /* HAVE_FACON */
#ifdef HAVE_DILITHIUM
    /* Dilithium Level 2: 1.3.6.1.4.1.2.267.7.4.4 */
    static const byte sigDilithium_Level2Oid[] =
        {43, 6, 1, 4, 1, 2, 130, 11, 7, 4, 4};

    /* Dilithium Level 3: 1.3.6.1.4.1.2.267.7.6.5 */
    static const byte sigDilithium_Level3Oid[] =
        {43, 6, 1, 4, 1, 2, 130, 11, 7, 6, 5};

    /* Dilithium Level 5: 1.3.6.1.4.1.2.267.7.8.7 */
    static const byte sigDilithium_Level5Oid[] =
        {43, 6, 1, 4, 1, 2, 130, 11, 7, 8, 7};
#endif /* HAVE_DILITHIUM */
#ifdef HAVE_SPHINCS
    /* Sphincs Fast Level 1: 1 3 9999 6 7 4 */
    static const byte sigSphincsFast_Level1Oid[] =
        {43, 206, 15, 6, 7, 4};

    /* Sphincs Fast Level 3: 1 3 9999 6 8 3 */
    static const byte sigSphincsFast_Level3Oid[] =
        {43, 206, 15, 6, 8, 3};

    /* Sphincs Fast Level 5: 1 3 9999 6 9 3 */
    static const byte sigSphincsFast_Level5Oid[] =
        {43, 206, 15, 6, 9, 3};

    /* Sphincs Small Level 1: 1 3 9999 6 7 10 */
    static const byte sigSphincsSmall_Level1Oid[] =
        {43, 206, 15, 6, 7, 10};

    /* Sphincs Small Level 3: 1 3 9999 6 8 7 */
    static const byte sigSphincsSmall_Level3Oid[] =
        {43, 206, 15, 6, 8, 7};

    /* Sphincs Small Level 5: 1 3 9999 6 9 7 */
    static const byte sigSphincsSmall_Level5Oid[] =
        {43, 206, 15, 6, 9, 7};
#endif /* HAVE_SPHINCS */
#endif /* HAVE_PQC */

/* keyType */
#ifndef NO_DSA
    static const byte keyDsaOid[] = {42, 134, 72, 206, 56, 4, 1};
#endif /* NO_DSA */
#ifndef NO_RSA
    static const byte keyRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 1};
#ifdef WC_RSA_PSS
    static const byte keyRsaPssOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 10};
#endif
#endif /* NO_RSA */
#ifdef HAVE_ECC
    static const byte keyEcdsaOid[] = {42, 134, 72, 206, 61, 2, 1};
#endif /* HAVE_ECC */
#ifdef HAVE_ED25519
    static const byte keyEd25519Oid[] = {43, 101, 112};
#endif /* HAVE_ED25519 */
#ifdef HAVE_CURVE25519
    static const byte keyCurve25519Oid[] = {43, 101, 110};
#endif
#ifdef HAVE_ED448
    static const byte keyEd448Oid[] = {43, 101, 113};
#endif /* HAVE_ED448 */
#ifdef HAVE_CURVE448
    static const byte keyCurve448Oid[] = {43, 101, 111};
#endif /* HAVE_CURVE448 */
#ifndef NO_DH
    static const byte keyDhOid[] = {42, 134, 72, 134, 247, 13, 1, 3, 1};
#endif /* !NO_DH */
#ifdef HAVE_PQC
#ifdef HAVE_FALCON
    /* Falcon Level 1: 1 3 9999 3 1 */
    static const byte keyFalcon_Level1Oid[] = {43, 206, 15, 3, 1};

    /* Falcon Level 5: 1 3 9999 3 4 */
    static const byte keyFalcon_Level5Oid[] = {43, 206, 15, 3, 4};
#endif /* HAVE_FALCON */
#ifdef HAVE_DILITHIUM
    /* Dilithium Level 2: 1.3.6.1.4.1.2.267.7.4.4 */
    static const byte keyDilithium_Level2Oid[] =
        {43, 6, 1, 4, 1, 2, 130, 11, 7, 4, 4};

    /* Dilithium Level 3: 1.3.6.1.4.1.2.267.7.6.5 */
    static const byte keyDilithium_Level3Oid[] =
        {43, 6, 1, 4, 1, 2, 130, 11, 7, 6, 5};

    /* Dilithium Level 5: 1.3.6.1.4.1.2.267.7.8.7 */
    static const byte keyDilithium_Level5Oid[] =
        {43, 6, 1, 4, 1, 2, 130, 11, 7, 8, 7};
#endif /* HAVE_DILITHIUM */
#ifdef HAVE_SPHINCS
    /* Sphincs Fast Level 1: 1 3 9999 6 7 4 */
    static const byte keySphincsFast_Level1Oid[] =
        {43, 206, 15, 6, 7, 4};

    /* Sphincs Fast Level 3: 1 3 9999 6 8 3 */
    static const byte keySphincsFast_Level3Oid[] =
        {43, 206, 15, 6, 8, 3};

    /* Sphincs Fast Level 5: 1 3 9999 6 9 3 */
    static const byte keySphincsFast_Level5Oid[] =
        {43, 206, 15, 6, 9, 3};

    /* Sphincs Small Level 1: 1 3 9999 6 7 10 */
    static const byte keySphincsSmall_Level1Oid[] =
        {43, 206, 15, 6, 7, 10};

    /* Sphincs Small Level 3: 1 3 9999 6 8 7 */
    static const byte keySphincsSmall_Level3Oid[] =
        {43, 206, 15, 6, 8, 7};

    /* Sphincs Small Level 5: 1 3 9999 6 9 7 */
    static const byte keySphincsSmall_Level5Oid[] =
        {43, 206, 15, 6, 9, 7};
#endif /* HAVE_SPHINCS */
#endif /* HAVE_PQC */

/* curveType */
#ifdef HAVE_ECC
    /* See "ecc_sets" table in ecc.c */
#endif /* HAVE_ECC */

#ifdef HAVE_AES_CBC
/* blkType */
    #ifdef WOLFSSL_AES_128
    static const byte blkAes128CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 2};
    #endif
    #ifdef WOLFSSL_AES_192
    static const byte blkAes192CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 22};
    #endif
    #ifdef WOLFSSL_AES_256
    static const byte blkAes256CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 42};
    #endif
#endif /* HAVE_AES_CBC */
#ifdef HAVE_AESGCM
    #ifdef WOLFSSL_AES_128
    static const byte blkAes128GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 6};
    #endif
    #ifdef WOLFSSL_AES_192
    static const byte blkAes192GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 26};
    #endif
    #ifdef WOLFSSL_AES_256
    static const byte blkAes256GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 46};
    #endif
#endif /* HAVE_AESGCM */
#ifdef HAVE_AESCCM
    #ifdef WOLFSSL_AES_128
    static const byte blkAes128CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 7};
    #endif
    #ifdef WOLFSSL_AES_192
    static const byte blkAes192CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 27};
    #endif
    #ifdef WOLFSSL_AES_256
    static const byte blkAes256CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 47};
    #endif
#endif /* HAVE_AESCCM */

#ifndef NO_DES3
    static const byte blkDesCbcOid[]  = {43, 14, 3, 2, 7};
    static const byte blkDes3CbcOid[] = {42, 134, 72, 134, 247, 13, 3, 7};
#endif

/* keyWrapType */
#ifdef WOLFSSL_AES_128
    static const byte wrapAes128Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 5};
#endif
#ifdef WOLFSSL_AES_192
    static const byte wrapAes192Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 25};
#endif
#ifdef WOLFSSL_AES_256
    static const byte wrapAes256Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 45};
#endif
#ifdef HAVE_PKCS7
/* From RFC 3211 */
static const byte wrapPwriKekOid[] = {42, 134, 72, 134, 247, 13, 1, 9, 16, 3,9};
#endif

/* cmsKeyAgreeType */
#ifndef NO_SHA
    static const byte dhSinglePass_stdDH_sha1kdf_Oid[]   =
                                          {43, 129, 5, 16, 134, 72, 63, 0, 2};
#endif
#ifdef WOLFSSL_SHA224
    static const byte dhSinglePass_stdDH_sha224kdf_Oid[] = {43, 129, 4, 1, 11, 0};
#endif
#ifndef NO_SHA256
    static const byte dhSinglePass_stdDH_sha256kdf_Oid[] = {43, 129, 4, 1, 11, 1};
#endif
#ifdef WOLFSSL_SHA384
    static const byte dhSinglePass_stdDH_sha384kdf_Oid[] = {43, 129, 4, 1, 11, 2};
#endif
#ifdef WOLFSSL_SHA512
    static const byte dhSinglePass_stdDH_sha512kdf_Oid[] = {43, 129, 4, 1, 11, 3};
#endif

/* ocspType */
#ifdef HAVE_OCSP
    static const byte ocspBasicOid[]    = {43, 6, 1, 5, 5, 7, 48, 1, 1};
    static const byte ocspNonceOid[]    = {43, 6, 1, 5, 5, 7, 48, 1, 2};
    static const byte ocspNoCheckOid[]  = {43, 6, 1, 5, 5, 7, 48, 1, 5};
#endif /* HAVE_OCSP */

/* certExtType */
static const byte extBasicCaOid[] = {85, 29, 19};
static const byte extAltNamesOid[] = {85, 29, 17};
static const byte extCrlDistOid[] = {85, 29, 31};
static const byte extAuthInfoOid[] = {43, 6, 1, 5, 5, 7, 1, 1};
static const byte extAuthKeyOid[] = {85, 29, 35};
static const byte extSubjKeyOid[] = {85, 29, 14};
static const byte extCertPolicyOid[] = {85, 29, 32};
static const byte extKeyUsageOid[] = {85, 29, 15};
static const byte extInhibitAnyOid[] = {85, 29, 54};
static const byte extExtKeyUsageOid[] = {85, 29, 37};
#ifndef IGNORE_NAME_CONSTRAINTS
    static const byte extNameConsOid[] = {85, 29, 30};
#endif
#ifdef HAVE_CRL
static const byte extCrlNumberOid[] = {85, 29, 20};
#endif
#ifdef WOLFSSL_SUBJ_DIR_ATTR
    static const byte extSubjDirAttrOid[] = {85, 29, 9};
#endif
#ifdef WOLFSSL_SUBJ_INFO_ACC
    static const byte extSubjInfoAccessOid[] = {43, 6, 1, 5, 5, 7, 1, 11};
#endif

/* certAuthInfoType */
static const byte extAuthInfoOcspOid[] = {43, 6, 1, 5, 5, 7, 48, 1};
static const byte extAuthInfoCaIssuerOid[] = {43, 6, 1, 5, 5, 7, 48, 2};
#ifdef WOLFSSL_SUBJ_INFO_ACC
    static const byte extAuthInfoCaRespOid[] = {43, 6, 1, 5, 5, 7, 48, 5};
#endif /* WOLFSSL_SUBJ_INFO_ACC */

/* certPolicyType */
static const byte extCertPolicyAnyOid[] = {85, 29, 32, 0};
#ifdef WOLFSSL_FPKI
#define CERT_POLICY_TYPE_OID_BASE(num) {96, 134, 72, 1, 101, 3, 2, 1, 3, num}
    static const byte extCertPolicyFpkiCommonAuthOid[] =
            CERT_POLICY_TYPE_OID_BASE(13);
    static const byte extCertPolicyFpkiPivAuthOid[] =
            CERT_POLICY_TYPE_OID_BASE(40);
    static const byte extCertPolicyFpkiPivAuthHwOid[] =
            CERT_POLICY_TYPE_OID_BASE(41);
    static const byte extCertPolicyFpkiPiviAuthOid[] =
            CERT_POLICY_TYPE_OID_BASE(45);
#endif /* WOLFSSL_FPKI */

/* certAltNameType */
static const byte extAltNamesHwNameOid[] = {43, 6, 1, 5, 5, 7, 8, 4};

/* certKeyUseType */
static const byte extExtKeyUsageAnyOid[] = {85, 29, 37, 0};
static const byte extExtKeyUsageServerAuthOid[]   = {43, 6, 1, 5, 5, 7, 3, 1};
static const byte extExtKeyUsageClientAuthOid[]   = {43, 6, 1, 5, 5, 7, 3, 2};
static const byte extExtKeyUsageCodeSigningOid[]  = {43, 6, 1, 5, 5, 7, 3, 3};
static const byte extExtKeyUsageEmailProtectOid[] = {43, 6, 1, 5, 5, 7, 3, 4};
static const byte extExtKeyUsageTimestampOid[]    = {43, 6, 1, 5, 5, 7, 3, 8};
static const byte extExtKeyUsageOcspSignOid[]     = {43, 6, 1, 5, 5, 7, 3, 9};
#ifdef WOLFSSL_WOLFSSH
#define EXT_KEY_USAGE_OID_BASE(num) {43, 6, 1, 5, 5, 7, 3, num}
    static const byte extExtKeyUsageSshClientAuthOid[] =
            EXT_KEY_USAGE_OID_BASE(21);
    static const byte extExtKeyUsageSshMSCLOid[] =
            {43, 6, 1, 4, 1, 130, 55, 20, 2, 2};
    static const byte extExtKeyUsageSshKpClientAuthOid[] =
            {43, 6, 1, 5, 2, 3, 4};
#endif /* WOLFSSL_WOLFSSH */

#ifdef WOLFSSL_SUBJ_DIR_ATTR
#define SUBJ_DIR_ATTR_TYPE_OID_BASE(num) {43, 6, 1, 5, 5, 7, 9, num}
    static const byte extSubjDirAttrDobOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(1);
    static const byte extSubjDirAttrPobOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(2);
    static const byte extSubjDirAttrGenderOid[] =
            SUBJ_DIR_ATTR_TYPE_OID_BASE(3);
    static const byte extSubjDirAttrCocOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(4);
    static const byte extSubjDirAttrCorOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(5);
#endif

#if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
    defined(WOLFSSL_ASN_TEMPLATE) || defined(OPENSSL_EXTRA) || \
    defined(OPENSSL_EXTRA_X509_SMALL)
/* csrAttrType */
#define CSR_ATTR_TYPE_OID_BASE(num) {42, 134, 72, 134, 247, 13, 1, 9, num}
#if !defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
    defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
    defined(WOLFSSL_ASN_TEMPLATE)
static const byte attrEmailOid[] =             CSR_ATTR_TYPE_OID_BASE(1);
#endif
#ifdef WOLFSSL_CERT_REQ
static const byte attrUnstructuredNameOid[] =  CSR_ATTR_TYPE_OID_BASE(2);
static const byte attrPkcs9ContentTypeOid[] =  CSR_ATTR_TYPE_OID_BASE(3);
static const byte attrChallengePasswordOid[] = CSR_ATTR_TYPE_OID_BASE(7);
static const byte attrExtensionRequestOid[] =  CSR_ATTR_TYPE_OID_BASE(14);
static const byte attrSerialNumberOid[] = {85, 4, 5};
static const byte attrDnQualifier[] = {85, 4, 46};
static const byte attrInitals[] = {85, 4, 43};
static const byte attrSurname[] = {85, 4, 4};
static const byte attrGivenName[] = {85, 4, 42};
#endif
#endif

/* kdfType */
static const byte pbkdf2Oid[] = {42, 134, 72, 134, 247, 13, 1, 5, 12};

/* PKCS5 */
#if !defined(NO_DES3) && !defined(NO_MD5)
static const byte pbeMd5Des[] = {42, 134, 72, 134, 247, 13, 1, 5, 3};
#endif
#if !defined(NO_DES3) && !defined(NO_SHA)
static const byte pbeSha1Des[] = {42, 134, 72, 134, 247, 13, 1, 5, 10};
#endif
static const byte pbes2[] = {42, 134, 72, 134, 247, 13, 1, 5, 13};

/* PKCS12 */
#if !defined(NO_RC4) && !defined(NO_SHA)
static const byte pbeSha1RC4128[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 1};
#endif
#if !defined(NO_DES3) && !defined(NO_SHA)
static const byte pbeSha1Des3[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 3};
#endif

#ifdef HAVE_LIBZ
/* zlib compression */
static const byte zlibCompress[] = {42, 134, 72, 134, 247, 13, 1, 9, 16, 3, 8};
#endif
#ifdef WOLFSSL_APACHE_HTTPD
/* tlsExtType */
static const byte tlsFeatureOid[] = {43, 6, 1, 5, 5, 7, 1, 24};
/* certNameType */
static const byte dnsSRVOid[] = {43, 6, 1, 5, 5, 7, 8, 7};
#endif

#if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
    defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
    defined(WOLFSSL_ASN_TEMPLATE)
/* Pilot attribute types (0.9.2342.19200300.100.1.*) */
#define PLT_ATTR_TYPE_OID_BASE(num) {9, 146, 38, 137, 147, 242, 44, 100, 1, num}
static const byte uidOid[] = PLT_ATTR_TYPE_OID_BASE(1); /* user id */
static const byte fvrtDrk[] = PLT_ATTR_TYPE_OID_BASE(5);/* favourite drink*/
#endif

#if defined(WOLFSSL_CERT_GEN) || \
    defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
    defined(WOLFSSL_ASN_TEMPLATE)
static const byte dcOid[] = {9, 146, 38, 137, 147, 242, 44, 100, 1, 25}; /* domain component */
#endif


/* Looks up the ID/type of an OID.
 *
 * When known returns the OID as a byte array and its length.
 * ID-type are unique.
 *
 * Use oidIgnoreType to autofail.
 *
 * @param [in]  id     OID id.
 * @param [in]  type   Type of OID (enum Oid_Types).
 * @param [out] oidSz  Length of OID byte array returned.
 * @return  Array of bytes for the OID.
 * @return  NULL when ID/type not recognized.
 */
const byte* OidFromId(word32 id, word32 type, word32* oidSz)
{
    const byte* oid = NULL;

    *oidSz = 0;

    switch (type) {

        case oidHashType:
            switch (id) {
            #ifdef WOLFSSL_MD2
                case MD2h:
                    oid = hashMd2hOid;
                    *oidSz = sizeof(hashMd2hOid);
                    break;
            #endif
            #ifndef NO_MD5
                case MD5h:
                    oid = hashMd5hOid;
                    *oidSz = sizeof(hashMd5hOid);
                    break;
            #endif
            #ifndef NO_SHA
                case SHAh:
                    oid = hashSha1hOid;
                    *oidSz = sizeof(hashSha1hOid);
                    break;
            #endif
            #ifdef WOLFSSL_SHA224
                case SHA224h:
                    oid = hashSha224hOid;
                    *oidSz = sizeof(hashSha224hOid);
                    break;
            #endif
            #ifndef NO_SHA256
                case SHA256h:
                    oid = hashSha256hOid;
                    *oidSz = sizeof(hashSha256hOid);
                    break;
            #endif
            #ifdef WOLFSSL_SHA384
                case SHA384h:
                    oid = hashSha384hOid;
                    *oidSz = sizeof(hashSha384hOid);
                    break;
            #endif
            #ifdef WOLFSSL_SHA512
                #ifndef WOLFSSL_NOSHA512_224
                case SHA512_224h:
                    oid = hashSha512_224hOid;
                    *oidSz = sizeof(hashSha512_224hOid);
                    break;
                #endif
                #ifndef WOLFSSL_NOSHA512_256
                case SHA512_256h:
                    oid = hashSha512_256hOid;
                    *oidSz = sizeof(hashSha512_256hOid);
                    break;
                #endif
                case SHA512h:
                    oid = hashSha512hOid;
                    *oidSz = sizeof(hashSha512hOid);
                    break;
            #endif
            #ifdef WOLFSSL_SHA3
            #ifndef WOLFSSL_NOSHA3_224
                case SHA3_224h:
                    oid = hashSha3_224hOid;
                    *oidSz = sizeof(hashSha3_224hOid);
                    break;
            #endif /* WOLFSSL_NOSHA3_224 */
            #ifndef WOLFSSL_NOSHA3_256
                case SHA3_256h:
                    oid = hashSha3_256hOid;
                    *oidSz = sizeof(hashSha3_256hOid);
                    break;
            #endif /* WOLFSSL_NOSHA3_256 */
            #ifndef WOLFSSL_NOSHA3_384
                case SHA3_384h:
                    oid = hashSha3_384hOid;
                    *oidSz = sizeof(hashSha3_384hOid);
                    break;
            #endif /* WOLFSSL_NOSHA3_384 */
            #ifndef WOLFSSL_NOSHA3_512
                case SHA3_512h:
                    oid = hashSha3_512hOid;
                    *oidSz = sizeof(hashSha3_512hOid);
                    break;
            #endif /* WOLFSSL_NOSHA3_512 */
            #endif /* WOLFSSL_SHA3 */
                default:
                    break;
            }
            break;

        case oidSigType:
            switch (id) {
                #if !defined(NO_DSA) && !defined(NO_SHA)
                case CTC_SHAwDSA:
                    oid = sigSha1wDsaOid;
                    *oidSz = sizeof(sigSha1wDsaOid);
                    break;
                case CTC_SHA256wDSA:
                    oid = sigSha256wDsaOid;
                    *oidSz = sizeof(sigSha256wDsaOid);
                    break;
                #endif /* NO_DSA */
                #ifndef NO_RSA
                #ifdef WOLFSSL_MD2
                case CTC_MD2wRSA:
                    oid = sigMd2wRsaOid;
                    *oidSz = sizeof(sigMd2wRsaOid);
                    break;
                #endif
                #ifndef NO_MD5
                case CTC_MD5wRSA:
                    oid = sigMd5wRsaOid;
                    *oidSz = sizeof(sigMd5wRsaOid);
                    break;
                #endif
                #ifndef NO_SHA
                case CTC_SHAwRSA:
                    oid = sigSha1wRsaOid;
                    *oidSz = sizeof(sigSha1wRsaOid);
                    break;
                #endif
                #ifdef WOLFSSL_SHA224
                case CTC_SHA224wRSA:
                    oid = sigSha224wRsaOid;
                    *oidSz = sizeof(sigSha224wRsaOid);
                    break;
                #endif
                #ifndef NO_SHA256
                case CTC_SHA256wRSA:
                    oid = sigSha256wRsaOid;
                    *oidSz = sizeof(sigSha256wRsaOid);
                    break;
                #endif
                #ifdef WOLFSSL_SHA384
                case CTC_SHA384wRSA:
                    oid = sigSha384wRsaOid;
                    *oidSz = sizeof(sigSha384wRsaOid);
                    break;
                #endif
                #ifdef WOLFSSL_SHA512
                case CTC_SHA512wRSA:
                    oid = sigSha512wRsaOid;
                    *oidSz = sizeof(sigSha512wRsaOid);
                    break;
                #endif /* WOLFSSL_SHA512 */
                #ifdef WOLFSSL_SHA3
                #ifndef WOLFSSL_NOSHA3_224
                case CTC_SHA3_224wRSA:
                    oid = sigSha3_224wRsaOid;
                    *oidSz = sizeof(sigSha3_224wRsaOid);
                    break;
                #endif
                #ifndef WOLFSSL_NOSHA3_256
                case CTC_SHA3_256wRSA:
                    oid = sigSha3_256wRsaOid;
                    *oidSz = sizeof(sigSha3_256wRsaOid);
                    break;
                #endif
                #ifndef WOLFSSL_NOSHA3_384
                case CTC_SHA3_384wRSA:
                    oid = sigSha3_384wRsaOid;
                    *oidSz = sizeof(sigSha3_384wRsaOid);
                    break;
                #endif
                #ifndef WOLFSSL_NOSHA3_512
                case CTC_SHA3_512wRSA:
                    oid = sigSha3_512wRsaOid;
                    *oidSz = sizeof(sigSha3_512wRsaOid);
                    break;
                #endif
                #endif
                #ifdef WC_RSA_PSS
                case CTC_RSASSAPSS:
                    oid = sigRsaSsaPssOid;
                    *oidSz = sizeof(sigRsaSsaPssOid);
                    break;
                #endif
                #endif /* NO_RSA */
                #ifdef HAVE_ECC
                #ifndef NO_SHA
                case CTC_SHAwECDSA:
                    oid = sigSha1wEcdsaOid;
                    *oidSz = sizeof(sigSha1wEcdsaOid);
                    break;
                #endif
                #ifdef WOLFSSL_SHA224
                case CTC_SHA224wECDSA:
                    oid = sigSha224wEcdsaOid;
                    *oidSz = sizeof(sigSha224wEcdsaOid);
                    break;
                #endif
                #ifndef NO_SHA256
                case CTC_SHA256wECDSA:
                    oid = sigSha256wEcdsaOid;
                    *oidSz = sizeof(sigSha256wEcdsaOid);
                    break;
                #endif
                #ifdef WOLFSSL_SHA384
                case CTC_SHA384wECDSA:
                    oid = sigSha384wEcdsaOid;
                    *oidSz = sizeof(sigSha384wEcdsaOid);
                    break;
                #endif
                #ifdef WOLFSSL_SHA512
                case CTC_SHA512wECDSA:
                    oid = sigSha512wEcdsaOid;
                    *oidSz = sizeof(sigSha512wEcdsaOid);
                    break;
                #endif
                #ifdef WOLFSSL_SHA3
                #ifndef WOLFSSL_NOSHA3_224
                case CTC_SHA3_224wECDSA:
                    oid = sigSha3_224wEcdsaOid;
                    *oidSz = sizeof(sigSha3_224wEcdsaOid);
                    break;
                #endif
                #ifndef WOLFSSL_NOSHA3_256
                case CTC_SHA3_256wECDSA:
                    oid = sigSha3_256wEcdsaOid;
                    *oidSz = sizeof(sigSha3_256wEcdsaOid);
                    break;
                #endif
                #ifndef WOLFSSL_NOSHA3_384
                case CTC_SHA3_384wECDSA:
                    oid = sigSha3_384wEcdsaOid;
                    *oidSz = sizeof(sigSha3_384wEcdsaOid);
                    break;
                #endif
                #ifndef WOLFSSL_NOSHA3_512
                case CTC_SHA3_512wECDSA:
                    oid = sigSha3_512wEcdsaOid;
                    *oidSz = sizeof(sigSha3_512wEcdsaOid);
                    break;
                #endif
                #endif
                #endif /* HAVE_ECC */
                #ifdef HAVE_ED25519
                case CTC_ED25519:
                    oid = sigEd25519Oid;
                    *oidSz = sizeof(sigEd25519Oid);
                    break;
                #endif
                #ifdef HAVE_ED448
                case CTC_ED448:
                    oid = sigEd448Oid;
                    *oidSz = sizeof(sigEd448Oid);
                    break;
                #endif
                #ifdef HAVE_PQC
                #ifdef HAVE_FALCON
                case CTC_FALCON_LEVEL1:
                    oid = sigFalcon_Level1Oid;
                    *oidSz = sizeof(sigFalcon_Level1Oid);
                    break;
                case CTC_FALCON_LEVEL5:
                    oid = sigFalcon_Level5Oid;
                    *oidSz = sizeof(sigFalcon_Level5Oid);
                    break;
                #endif /* HAVE_FALCON */
                #ifdef HAVE_DILITHIUM
                case CTC_DILITHIUM_LEVEL2:
                    oid = sigDilithium_Level2Oid;
                    *oidSz = sizeof(sigDilithium_Level2Oid);
                    break;
                case CTC_DILITHIUM_LEVEL3:
                    oid = sigDilithium_Level3Oid;
                    *oidSz = sizeof(sigDilithium_Level3Oid);
                    break;
                case CTC_DILITHIUM_LEVEL5:
                    oid = sigDilithium_Level5Oid;
                    *oidSz = sizeof(sigDilithium_Level5Oid);
                    break;
                #endif /* HAVE_DILITHIUM */
                #ifdef HAVE_SPHINCS
                case CTC_SPHINCS_FAST_LEVEL1:
                    oid = sigSphincsFast_Level1Oid;
                    *oidSz = sizeof(sigSphincsFast_Level1Oid);
                    break;
                case CTC_SPHINCS_FAST_LEVEL3:
                    oid = sigSphincsFast_Level3Oid;
                    *oidSz = sizeof(sigSphincsFast_Level3Oid);
                    break;
                case CTC_SPHINCS_FAST_LEVEL5:
                    oid = sigSphincsFast_Level5Oid;
                    *oidSz = sizeof(sigSphincsFast_Level5Oid);
                    break;
                case CTC_SPHINCS_SMALL_LEVEL1:
                    oid = sigSphincsSmall_Level1Oid;
                    *oidSz = sizeof(sigSphincsSmall_Level1Oid);
                    break;
                case CTC_SPHINCS_SMALL_LEVEL3:
                    oid = sigSphincsSmall_Level3Oid;
                    *oidSz = sizeof(sigSphincsSmall_Level3Oid);
                    break;
                case CTC_SPHINCS_SMALL_LEVEL5:
                    oid = sigSphincsSmall_Level5Oid;
                    *oidSz = sizeof(sigSphincsSmall_Level5Oid);
                    break;
                #endif /* HAVE_SPHINCS */
                #endif /* HAVE_PQC */
                default:
                    break;
            }
            break;

        case oidKeyType:
            switch (id) {
                #ifndef NO_DSA
                case DSAk:
                    oid = keyDsaOid;
                    *oidSz = sizeof(keyDsaOid);
                    break;
                #endif /* NO_DSA */
            #ifndef NO_RSA
                case RSAk:
                    oid = keyRsaOid;
                    *oidSz = sizeof(keyRsaOid);
                    break;
                #ifdef WC_RSA_PSS
                case RSAPSSk:
                    oid = keyRsaPssOid;
                    *oidSz = sizeof(keyRsaPssOid);
                    break;
                #endif
            #endif /* NO_RSA */
                #ifdef HAVE_ECC
                case ECDSAk:
                    oid = keyEcdsaOid;
                    *oidSz = sizeof(keyEcdsaOid);
                    break;
                #endif /* HAVE_ECC */
                #ifdef HAVE_ED25519
                case ED25519k:
                    oid = keyEd25519Oid;
                    *oidSz = sizeof(keyEd25519Oid);
                    break;
                #endif /* HAVE_ED25519 */
                #ifdef HAVE_CURVE25519
                case X25519k:
                    oid = keyCurve25519Oid;
                    *oidSz = sizeof(keyCurve25519Oid);
                    break;
                #endif /* HAVE_CURVE25519 */
                #ifdef HAVE_ED448
                case ED448k:
                    oid = keyEd448Oid;
                    *oidSz = sizeof(keyEd448Oid);
                    break;
                #endif /* HAVE_ED448 */
                #ifdef HAVE_CURVE448
                case X448k:
                    oid = keyCurve448Oid;
                    *oidSz = sizeof(keyCurve448Oid);
                    break;
                #endif /* HAVE_CURVE448 */
                #ifndef NO_DH
                case DHk:
                    oid = keyDhOid;
                    *oidSz = sizeof(keyDhOid);
                    break;
                #endif /* !NO_DH */
                #ifdef HAVE_PQC
                #ifdef HAVE_FALCON
                case FALCON_LEVEL1k:
                    oid = keyFalcon_Level1Oid;
                    *oidSz = sizeof(keyFalcon_Level1Oid);
                    break;
                case FALCON_LEVEL5k:
                    oid = keyFalcon_Level5Oid;
                    *oidSz = sizeof(keyFalcon_Level5Oid);
                    break;
                #endif /* HAVE_FALCON */
                #ifdef HAVE_DILITHIUM
                case DILITHIUM_LEVEL2k:
                    oid = keyDilithium_Level2Oid;
                    *oidSz = sizeof(keyDilithium_Level2Oid);
                    break;
                case DILITHIUM_LEVEL3k:
                    oid = keyDilithium_Level3Oid;
                    *oidSz = sizeof(keyDilithium_Level3Oid);
                    break;
                case DILITHIUM_LEVEL5k:
                    oid = keyDilithium_Level5Oid;
                    *oidSz = sizeof(keyDilithium_Level5Oid);
                    break;
                #endif /* HAVE_DILITHIUM */
                #ifdef HAVE_SPHINCS
                case SPHINCS_FAST_LEVEL1k:
                    oid = keySphincsFast_Level1Oid;
                    *oidSz = sizeof(keySphincsFast_Level1Oid);
                    break;
                case SPHINCS_FAST_LEVEL3k:
                    oid = keySphincsFast_Level3Oid;
                    *oidSz = sizeof(keySphincsFast_Level3Oid);
                    break;
                case SPHINCS_FAST_LEVEL5k:
                    oid = keySphincsFast_Level5Oid;
                    *oidSz = sizeof(keySphincsFast_Level5Oid);
                    break;
                case SPHINCS_SMALL_LEVEL1k:
                    oid = keySphincsSmall_Level1Oid;
                    *oidSz = sizeof(keySphincsSmall_Level1Oid);
                    break;
                case SPHINCS_SMALL_LEVEL3k:
                    oid = keySphincsSmall_Level3Oid;
                    *oidSz = sizeof(keySphincsSmall_Level3Oid);
                    break;
                case SPHINCS_SMALL_LEVEL5k:
                    oid = keySphincsSmall_Level5Oid;
                    *oidSz = sizeof(keySphincsSmall_Level5Oid);
                    break;
                #endif /* HAVE_SPHINCS */
                #endif /* HAVE_PQC */
                default:
                    break;
            }
            break;

        #ifdef HAVE_ECC
        case oidCurveType:
            if (wc_ecc_get_oid(id, &oid, oidSz) < 0) {
                WOLFSSL_MSG("ECC OID not found");
            }
            break;
        #endif /* HAVE_ECC */

        case oidBlkType:
            switch (id) {
    #ifdef HAVE_AES_CBC
        #ifdef WOLFSSL_AES_128
                case AES128CBCb:
                    oid = blkAes128CbcOid;
                    *oidSz = sizeof(blkAes128CbcOid);
                    break;
        #endif
        #ifdef WOLFSSL_AES_192
                case AES192CBCb:
                    oid = blkAes192CbcOid;
                    *oidSz = sizeof(blkAes192CbcOid);
                    break;
        #endif
        #ifdef WOLFSSL_AES_256
                case AES256CBCb:
                    oid = blkAes256CbcOid;
                    *oidSz = sizeof(blkAes256CbcOid);
                    break;
        #endif
    #endif /* HAVE_AES_CBC */
    #ifdef HAVE_AESGCM
        #ifdef WOLFSSL_AES_128
                case AES128GCMb:
                    oid = blkAes128GcmOid;
                    *oidSz = sizeof(blkAes128GcmOid);
                    break;
        #endif
        #ifdef WOLFSSL_AES_192
                case AES192GCMb:
                    oid = blkAes192GcmOid;
                    *oidSz = sizeof(blkAes192GcmOid);
                    break;
        #endif
        #ifdef WOLFSSL_AES_256
                case AES256GCMb:
                    oid = blkAes256GcmOid;
                    *oidSz = sizeof(blkAes256GcmOid);
                    break;
        #endif
    #endif /* HAVE_AESGCM */
    #ifdef HAVE_AESCCM
        #ifdef WOLFSSL_AES_128
                case AES128CCMb:
                    oid = blkAes128CcmOid;
                    *oidSz = sizeof(blkAes128CcmOid);
                    break;
        #endif
        #ifdef WOLFSSL_AES_192
                case AES192CCMb:
                    oid = blkAes192CcmOid;
                    *oidSz = sizeof(blkAes192CcmOid);
                    break;
        #endif
        #ifdef WOLFSSL_AES_256
                case AES256CCMb:
                    oid = blkAes256CcmOid;
                    *oidSz = sizeof(blkAes256CcmOid);
                    break;
        #endif
    #endif /* HAVE_AESCCM */
    #ifndef NO_DES3
                case DESb:
                    oid = blkDesCbcOid;
                    *oidSz = sizeof(blkDesCbcOid);
                    break;
                case DES3b:
                    oid = blkDes3CbcOid;
                    *oidSz = sizeof(blkDes3CbcOid);
                    break;
    #endif /* !NO_DES3 */
                default:
                    break;
            }
            break;

        #ifdef HAVE_OCSP
        case oidOcspType:
            switch (id) {
                case OCSP_BASIC_OID:
                    oid = ocspBasicOid;
                    *oidSz = sizeof(ocspBasicOid);
                    break;
                case OCSP_NONCE_OID:
                    oid = ocspNonceOid;
                    *oidSz = sizeof(ocspNonceOid);
                    break;
                default:
                    break;
            }
            break;
        #endif /* HAVE_OCSP */

        case oidCertExtType:
            switch (id) {
                case BASIC_CA_OID:
                    oid = extBasicCaOid;
                    *oidSz = sizeof(extBasicCaOid);
                    break;
                case ALT_NAMES_OID:
                    oid = extAltNamesOid;
                    *oidSz = sizeof(extAltNamesOid);
                    break;
                case CRL_DIST_OID:
                    oid = extCrlDistOid;
                    *oidSz = sizeof(extCrlDistOid);
                    break;
                case AUTH_INFO_OID:
                    oid = extAuthInfoOid;
                    *oidSz = sizeof(extAuthInfoOid);
                    break;
                case AUTH_KEY_OID:
                    oid = extAuthKeyOid;
                    *oidSz = sizeof(extAuthKeyOid);
                    break;
                case SUBJ_KEY_OID:
                    oid = extSubjKeyOid;
                    *oidSz = sizeof(extSubjKeyOid);
                    break;
                case CERT_POLICY_OID:
                    oid = extCertPolicyOid;
                    *oidSz = sizeof(extCertPolicyOid);
                    break;
                case KEY_USAGE_OID:
                    oid = extKeyUsageOid;
                    *oidSz = sizeof(extKeyUsageOid);
                    break;
                case INHIBIT_ANY_OID:
                    oid = extInhibitAnyOid;
                    *oidSz = sizeof(extInhibitAnyOid);
                    break;
                case EXT_KEY_USAGE_OID:
                    oid = extExtKeyUsageOid;
                    *oidSz = sizeof(extExtKeyUsageOid);
                    break;
            #ifndef IGNORE_NAME_CONSTRAINTS
                case NAME_CONS_OID:
                    oid = extNameConsOid;
                    *oidSz = sizeof(extNameConsOid);
                    break;
            #endif
            #ifdef HAVE_OCSP
                case OCSP_NOCHECK_OID:
                    oid = ocspNoCheckOid;
                    *oidSz = sizeof(ocspNoCheckOid);
                    break;
            #endif
            #ifdef WOLFSSL_SUBJ_DIR_ATTR
                case SUBJ_DIR_ATTR_OID:
                    oid = extSubjDirAttrOid;
                    *oidSz = sizeof(extSubjDirAttrOid);
                    break;
            #endif
            #ifdef WOLFSSL_SUBJ_INFO_ACC
                case SUBJ_INFO_ACC_OID:
                    oid = extSubjInfoAccessOid;
                    *oidSz = sizeof(extSubjInfoAccessOid);
                    break;
            #endif
                default:
                    break;
            }
            break;

        case oidCrlExtType:
            #ifdef HAVE_CRL
            switch (id) {
                case AUTH_KEY_OID:
                    oid = extAuthKeyOid;
                    *oidSz = sizeof(extAuthKeyOid);
                    break;
                case CRL_NUMBER_OID:
                    oid = extCrlNumberOid;
                    *oidSz = sizeof(extCrlNumberOid);
                    break;
                default:
                    break;
            }
            #endif
            break;

        case oidCertAuthInfoType:
            switch (id) {
                case AIA_OCSP_OID:
                    oid = extAuthInfoOcspOid;
                    *oidSz = sizeof(extAuthInfoOcspOid);
                    break;
                case AIA_CA_ISSUER_OID:
                    oid = extAuthInfoCaIssuerOid;
                    *oidSz = sizeof(extAuthInfoCaIssuerOid);
                    break;
                #ifdef WOLFSSL_SUBJ_INFO_ACC
                case AIA_CA_REPO_OID:
                    oid = extAuthInfoCaRespOid;
                    *oidSz = sizeof(extAuthInfoCaRespOid);
                    break;
                #endif /* WOLFSSL_SUBJ_INFO_ACC */
                default:
                    break;
            }
            break;

        case oidCertPolicyType:
            switch (id) {
                case CP_ANY_OID:
                    oid = extCertPolicyAnyOid;
                    *oidSz = sizeof(extCertPolicyAnyOid);
                    break;
                #if defined(WOLFSSL_FPKI)
                case CP_FPKI_COMMON_AUTH_OID:
                    oid = extCertPolicyFpkiCommonAuthOid;
                    *oidSz = sizeof(extCertPolicyFpkiCommonAuthOid);
                    break;
                case CP_FPKI_PIV_AUTH_OID:
                    oid = extCertPolicyFpkiPivAuthOid;
                    *oidSz = sizeof(extCertPolicyFpkiPivAuthOid);
                    break;
                case CP_FPKI_PIV_AUTH_HW_OID: /* collision with AES256CBCb */
                    oid = extCertPolicyFpkiPivAuthHwOid;
                    *oidSz = sizeof(extCertPolicyFpkiPivAuthHwOid);
                    break;
                case CP_FPKI_PIVI_AUTH_OID:
                    oid = extCertPolicyFpkiPiviAuthOid;
                    *oidSz = sizeof(extCertPolicyFpkiPiviAuthOid);
                    break;
                #endif /* WOLFSSL_FPKI */
                default:
                    break;
            }
            break;

        case oidCertAltNameType:
            switch (id) {
                case HW_NAME_OID:
                    oid = extAltNamesHwNameOid;
                    *oidSz = sizeof(extAltNamesHwNameOid);
                    break;
                default:
                    break;
            }
            break;

        case oidCertKeyUseType:
            switch (id) {
                case EKU_ANY_OID:
                    oid = extExtKeyUsageAnyOid;
                    *oidSz = sizeof(extExtKeyUsageAnyOid);
                    break;
                case EKU_SERVER_AUTH_OID:
                    oid = extExtKeyUsageServerAuthOid;
                    *oidSz = sizeof(extExtKeyUsageServerAuthOid);
                    break;
                case EKU_CLIENT_AUTH_OID:
                    oid = extExtKeyUsageClientAuthOid;
                    *oidSz = sizeof(extExtKeyUsageClientAuthOid);
                    break;
                case EKU_CODESIGNING_OID:
                    oid = extExtKeyUsageCodeSigningOid;
                    *oidSz = sizeof(extExtKeyUsageCodeSigningOid);
                    break;
                case EKU_EMAILPROTECT_OID:
                    oid = extExtKeyUsageEmailProtectOid;
                    *oidSz = sizeof(extExtKeyUsageEmailProtectOid);
                    break;
                case EKU_TIMESTAMP_OID:
                    oid = extExtKeyUsageTimestampOid;
                    *oidSz = sizeof(extExtKeyUsageTimestampOid);
                    break;
                case EKU_OCSP_SIGN_OID:
                    oid = extExtKeyUsageOcspSignOid;
                    *oidSz = sizeof(extExtKeyUsageOcspSignOid);
                    break;
                #ifdef WOLFSSL_WOLFSSH
                case EKU_SSH_CLIENT_AUTH_OID:
                    oid = extExtKeyUsageSshClientAuthOid;
                    *oidSz = sizeof(extExtKeyUsageSshClientAuthOid);
                    break;
                case EKU_SSH_MSCL_OID:
                    oid = extExtKeyUsageSshMSCLOid;
                    *oidSz = sizeof(extExtKeyUsageSshMSCLOid);
                    break;
                case EKU_SSH_KP_CLIENT_AUTH_OID:
                    oid = extExtKeyUsageSshKpClientAuthOid;
                    *oidSz = sizeof(extExtKeyUsageSshKpClientAuthOid);
                    break;
                #endif /* WOLFSSL_WOLFSSH */
                default:
                    break;
            }
            break;

        case oidKdfType:
            switch (id) {
                case PBKDF2_OID:
                    oid = pbkdf2Oid;
                    *oidSz = sizeof(pbkdf2Oid);
                    break;
                default:
                    break;
            }
            break;

        case oidPBEType:
            switch (id) {
        #if !defined(NO_SHA) && !defined(NO_RC4)
                case PBE_SHA1_RC4_128_SUM:
                case PBE_SHA1_RC4_128:
                    oid = pbeSha1RC4128;
                    *oidSz = sizeof(pbeSha1RC4128);
                    break;
        #endif
        #if !defined(NO_MD5) && !defined(NO_DES3)
                case PBE_MD5_DES_SUM:
                case PBE_MD5_DES:
                    oid = pbeMd5Des;
                    *oidSz = sizeof(pbeMd5Des);
                    break;

        #endif
        #if !defined(NO_SHA) && !defined(NO_DES3)
                case PBE_SHA1_DES_SUM:
                case PBE_SHA1_DES:
                    oid = pbeSha1Des;
                    *oidSz = sizeof(pbeSha1Des);
                    break;

        #endif
        #if !defined(NO_SHA) && !defined(NO_DES3)
                case PBE_SHA1_DES3_SUM:
                case PBE_SHA1_DES3:
                    oid = pbeSha1Des3;
                    *oidSz = sizeof(pbeSha1Des3);
                    break;
        #endif
                case PBES2_SUM:
                case PBES2:
                    oid = pbes2;
                    *oidSz = sizeof(pbes2);
                    break;
                default:
                    break;
            }
            break;

        case oidKeyWrapType:
            switch (id) {
            #ifdef WOLFSSL_AES_128
                case AES128_WRAP:
                    oid = wrapAes128Oid;
                    *oidSz = sizeof(wrapAes128Oid);
                    break;
            #endif
            #ifdef WOLFSSL_AES_192
                case AES192_WRAP:
                    oid = wrapAes192Oid;
                    *oidSz = sizeof(wrapAes192Oid);
                    break;
            #endif
            #ifdef WOLFSSL_AES_256
                case AES256_WRAP:
                    oid = wrapAes256Oid;
                    *oidSz = sizeof(wrapAes256Oid);
                    break;
            #endif
            #ifdef HAVE_PKCS7
                case PWRI_KEK_WRAP:
                    oid = wrapPwriKekOid;
                    *oidSz = sizeof(wrapPwriKekOid);
                    break;
            #endif
                default:
                    break;
            }
            break;

        case oidCmsKeyAgreeType:
            switch (id) {
            #ifndef NO_SHA
                case dhSinglePass_stdDH_sha1kdf_scheme:
                    oid = dhSinglePass_stdDH_sha1kdf_Oid;
                    *oidSz = sizeof(dhSinglePass_stdDH_sha1kdf_Oid);
                    break;
            #endif
            #ifdef WOLFSSL_SHA224
                case dhSinglePass_stdDH_sha224kdf_scheme:
                    oid = dhSinglePass_stdDH_sha224kdf_Oid;
                    *oidSz = sizeof(dhSinglePass_stdDH_sha224kdf_Oid);
                    break;
            #endif
            #ifndef NO_SHA256
                case dhSinglePass_stdDH_sha256kdf_scheme:
                    oid = dhSinglePass_stdDH_sha256kdf_Oid;
                    *oidSz = sizeof(dhSinglePass_stdDH_sha256kdf_Oid);
                    break;
            #endif
            #ifdef WOLFSSL_SHA384
                case dhSinglePass_stdDH_sha384kdf_scheme:
                    oid = dhSinglePass_stdDH_sha384kdf_Oid;
                    *oidSz = sizeof(dhSinglePass_stdDH_sha384kdf_Oid);
                    break;
            #endif
            #ifdef WOLFSSL_SHA512
                case dhSinglePass_stdDH_sha512kdf_scheme:
                    oid = dhSinglePass_stdDH_sha512kdf_Oid;
                    *oidSz = sizeof(dhSinglePass_stdDH_sha512kdf_Oid);
                    break;
            #endif
                default:
                    break;
            }
            break;

#ifndef NO_HMAC
        case oidHmacType:
            switch (id) {
        #ifdef WOLFSSL_SHA224
                case HMAC_SHA224_OID:
                    oid = hmacSha224Oid;
                    *oidSz = sizeof(hmacSha224Oid);
                    break;
        #endif
        #ifndef NO_SHA256
                case HMAC_SHA256_OID:
                    oid = hmacSha256Oid;
                    *oidSz = sizeof(hmacSha256Oid);
                    break;
        #endif
        #ifdef WOLFSSL_SHA384
                case HMAC_SHA384_OID:
                    oid = hmacSha384Oid;
                    *oidSz = sizeof(hmacSha384Oid);
                    break;
        #endif
        #ifdef WOLFSSL_SHA512
                case HMAC_SHA512_OID:
                    oid = hmacSha512Oid;
                    *oidSz = sizeof(hmacSha512Oid);
                    break;
        #endif
                default:
                    break;
            }
            break;
#endif /* !NO_HMAC */

#ifdef HAVE_LIBZ
        case oidCompressType:
            switch (id) {
                case ZLIBc:
                    oid = zlibCompress;
                    *oidSz = sizeof(zlibCompress);
                    break;
                default:
                    break;
            }
            break;
#endif /* HAVE_LIBZ */
#ifdef WOLFSSL_APACHE_HTTPD
        case oidCertNameType:
            switch (id) {
                 case NID_id_on_dnsSRV:
                    oid = dnsSRVOid;
                    *oidSz = sizeof(dnsSRVOid);
                    break;
                default:
                    break;
            }
            break;
        case oidTlsExtType:
            switch (id) {
                case TLS_FEATURE_OID:
                    oid = tlsFeatureOid;
                    *oidSz = sizeof(tlsFeatureOid);
                    break;
                default:
                    break;
            }
            break;
#endif /* WOLFSSL_APACHE_HTTPD */
#ifdef WOLFSSL_CERT_REQ
        case oidCsrAttrType:
            switch (id) {
                case GIVEN_NAME_OID:
                    oid = attrGivenName;
                    *oidSz = sizeof(attrGivenName);
                    break;
                case SURNAME_OID:
                    oid = attrSurname;
                    *oidSz = sizeof(attrSurname);
                    break;
                case INITIALS_OID:
                    oid = attrInitals;
                    *oidSz = sizeof(attrInitals);
                    break;
                case DNQUALIFIER_OID:
                    oid = attrDnQualifier;
                    *oidSz = sizeof(attrDnQualifier);
                    break;
                case UNSTRUCTURED_NAME_OID:
                    oid = attrUnstructuredNameOid;
                    *oidSz = sizeof(attrUnstructuredNameOid);
                    break;
                case PKCS9_CONTENT_TYPE_OID:
                    oid = attrPkcs9ContentTypeOid;
                    *oidSz = sizeof(attrPkcs9ContentTypeOid);
                    break;
                case CHALLENGE_PASSWORD_OID:
                    oid = attrChallengePasswordOid;
                    *oidSz = sizeof(attrChallengePasswordOid);
                    break;
                case SERIAL_NUMBER_OID:
                    oid = attrSerialNumberOid;
                    *oidSz = sizeof(attrSerialNumberOid);
                    break;
                case USER_ID_OID:
                    oid = uidOid;
                    *oidSz = sizeof(uidOid);
                    break;
                case EXTENSION_REQUEST_OID:
                    oid = attrExtensionRequestOid;
                    *oidSz = sizeof(attrExtensionRequestOid);
                    break;
                default:
                    break;
            }
            break;
#endif
#ifdef WOLFSSL_SUBJ_DIR_ATTR
        case oidSubjDirAttrType:
            switch (id) {
                case SDA_DOB_OID:
                    oid = extSubjDirAttrDobOid;
                    *oidSz = sizeof(extSubjDirAttrDobOid);
                    break;
                case SDA_POB_OID:
                    oid = extSubjDirAttrPobOid;
                    *oidSz = sizeof(extSubjDirAttrPobOid);
                    break;
                case SDA_GENDER_OID:
                    oid = extSubjDirAttrGenderOid;
                    *oidSz = sizeof(extSubjDirAttrGenderOid);
                    break;
                case SDA_COC_OID:
                    oid = extSubjDirAttrCocOid;
                    *oidSz = sizeof(extSubjDirAttrCocOid);
                    break;
                case SDA_COR_OID:
                    oid = extSubjDirAttrCorOid;
                    *oidSz = sizeof(extSubjDirAttrCorOid);
                    break;
                default:
                    break;
            }
            break;
#endif /* WOLFSSL_SUBJ_DIR_ATTR */
        case oidIgnoreType:
        default:
            break;
    }

    return oid;
}

#ifdef HAVE_ECC

/* Check the OID id is for a known elliptic curve.
 *
 * @param [in]  oid  OID id.
 * @return  ECC set id on success.
 * @return  ECC_CURVE_OID_E when OID id is 0 or not supported.
 */
static int CheckCurve(word32 oid)
{
    int ret;
    word32 oidSz;

    /* Lookup OID id. */
    ret = wc_ecc_get_oid(oid, NULL, &oidSz);
    /* Check for error or zero length OID size (can't get OID for encoding). */
    if ((ret < 0) || (oidSz == 0)) {
        WOLFSSL_MSG("CheckCurve not found");
        WOLFSSL_ERROR_VERBOSE(ECC_CURVE_OID_E);
        ret = ECC_CURVE_OID_E;
    }

    /* Return ECC set id or error code. */
    return ret;
}

#endif

#ifdef HAVE_OID_ENCODING
/* Encode dotted form of OID into byte array version.
 *
 * @param [in]      in     Dotted form of OID.
 * @param [in]      inSz   Count of numbers in dotted form.
 * @param [in]      out    Buffer to hold OID.
 * @param [in, out] outSz  On in, size of buffer.
 *                         On out, number of bytes in buffer.
 * @return  0 on success
 * @return  BAD_FUNC_ARG when in or outSz is NULL.
 * @return  BUFFER_E when buffer too small.
 */
int EncodeObjectId(const word16* in, word32 inSz, byte* out, word32* outSz)
{
    int i, x, len;
    word32 d, t;

    /* check args */
    if (in == NULL || outSz == NULL) {
        return BAD_FUNC_ARG;
    }

    /* compute length of encoded OID */
    d = (in[0] * 40) + in[1];
    len = 0;
    for (i = 1; i < (int)inSz; i++) {
        x = 0;
        t = d;
        while (t) {
            x++;
            t >>= 1;
        }
        len += (x / 7) + ((x % 7) ? 1 : 0) + (d == 0 ? 1 : 0);

        if (i < (int)inSz - 1) {
            d = in[i + 1];
        }
    }

    if (out) {
        /* verify length */
        if ((int)*outSz < len) {
            return BUFFER_E; /* buffer provided is not large enough */
        }

        /* calc first byte */
        d = (in[0] * 40) + in[1];

        /* encode bytes */
        x = 0;
        for (i = 1; i < (int)inSz; i++) {
            if (d) {
                int y = x, z;
                byte mask = 0;
                while (d) {
                    out[x++] = (byte)((d & 0x7F) | mask);
                    d     >>= 7;
                    mask  |= 0x80;  /* upper bit is set on all but the last byte */
                }
                /* now swap bytes y...x-1 */
                z = x - 1;
                while (y < z) {
                    mask = out[y];
                    out[y] = out[z];
                    out[z] = mask;
                    ++y;
                    --z;
                }
            }
            else {
              out[x++] = 0x00; /* zero value */
            }

            /* next word */
            if (i < (int)inSz - 1) {
                d = in[i + 1];
            }
        }
    }

    /* return length */
    *outSz = len;

    return 0;
}
#endif /* HAVE_OID_ENCODING */

#if defined(HAVE_OID_DECODING) || defined(WOLFSSL_ASN_PRINT)
/* Encode dotted form of OID into byte array version.
 *
 * @param [in]      in     Byte array containing OID.
 * @param [in]      inSz   Size of OID in bytes.
 * @param [in]      out    Array to hold dotted form of OID.
 * @param [in, out] outSz  On in, number of elements in array.
 *                         On out, count of numbers in dotted form.
 * @return  0 on success
 * @return  BAD_FUNC_ARG when in or outSz is NULL.
 * @return  BUFFER_E when dotted form buffer too small.
 */
int DecodeObjectId(const byte* in, word32 inSz, word16* out, word32* outSz)
{
    int x = 0, y = 0;
    word32 t = 0;

    /* check args */
    if (in == NULL || outSz == NULL) {
        return BAD_FUNC_ARG;
    }

    /* decode bytes */
    while (inSz--) {
        t = (t << 7) | (in[x] & 0x7F);
        if (!(in[x] & 0x80)) {
            if (y >= (int)*outSz) {
                return BUFFER_E;
            }
            if (y == 0) {
                out[0] = (word16)(t / 40);
                out[1] = (word16)(t % 40);
                y = 2;
            }
            else {
                out[y++] = (word16)t;
            }
            t = 0; /* reset tmp */
        }
        x++;
    }

    /* return length */
    *outSz = (word32)y;

    return 0;
}
#endif /* HAVE_OID_DECODING */

/* Decode the header of a BER/DER encoded OBJECT ID.
 *
 * @param [in]      input     Buffer holding DER/BER encoded data.
 * @param [in, out] inOutIdx  On in, starting index of header.
 *                            On out, end of parsed header.
 * @param [out]     len       Number of bytes in the ASN.1 data.
 * @param [in]      maxIdx    Length of data in buffer.
 * @return  0 on success.
 * @return  BUFFER_E when there is not enough data to parse.
 * @return  ASN_PARSE_E when the tag is not a OBJECT ID or length is invalid.
 */
int GetASNObjectId(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
{
    int ret = GetASNHeader(input, ASN_OBJECT_ID, inOutIdx, len, maxIdx);
    if (ret > 0) {
        /* Only return 0 on success. */
        ret = 0;
    }
    return ret;
}

/* Set the DER/BER encoding of the ASN.1 OBJECT ID header.
 *
 * When output is NULL, calculate the header length only.
 *
 * @param [in]  len        Length of OBJECT ID data in bytes.
 * @param [out] output     Buffer to write into.
 * @return  Number of bytes added to the buffer.
 */
int SetObjectId(int len, byte* output)
{
    int idx = 0;

    if (output) {
        /* Write out tag. */
        output[idx] = ASN_OBJECT_ID;
    }
    /* Skip tag. */
    idx += ASN_TAG_SZ;
    /* Encode length - passing NULL for output will not encode. */
    idx += (int)SetLength((word32)len, output ? output + idx : NULL);

    /* Return index after header. */
    return idx;
}

#ifdef ASN_DUMP_OID
/* Dump the OID information.
 *
 * Decode the OID too if function available.
 *
 * @param [in] oidData  OID data from buffer.
 * @param [in] oidSz    Size of OID data in buffer.
 * @param [in] oid      OID id.
 * @param [in] oidType  Type of OID.
 * @return  0 on success.
 * @return  BUFFER_E when not enough bytes for proper decode.
 *          (HAVE_OID_DECODING)
 */
static int DumpOID(const byte* oidData, word32 oidSz, word32 oid,
                   word32 oidType)
{
    int    ret = 0;
    word32 i;

    /* support for dumping OID information */
    printf("OID (Type %d, Sz %d, Sum %d): ", oidType, oidSz, oid);
    /* Dump bytes in decimal. */
    for (i = 0; i < oidSz; i++) {
        printf("%d, ", oidData[i]);
    }
    printf("\n");
    /* Dump bytes in hexadecimal. */
    for (i = 0; i < oidSz; i++) {
        printf("%02x, ", oidData[i]);
    }
    printf("\n");

    #ifdef HAVE_OID_DECODING
    {
        word16 decOid[MAX_OID_SZ];
        word32 decOidSz = sizeof(decOid);
        /* Decode the OID into dotted form. */
        ret = DecodeObjectId(oidData, oidSz, decOid, &decOidSz);
        if (ret == 0) {
            printf("  Decoded (Sz %d): ", decOidSz);
            for (i=0; i<decOidSz; i++) {
                printf("%d.", decOid[i]);
            }
            printf("\n");
        }
        else {
            printf("DecodeObjectId failed: %d\n", ret);
        }
    }
    #endif /* HAVE_OID_DECODING */

    return ret;
}
#endif /* ASN_DUMP_OID */

/* Get the OID data and verify it is of the type specified when compiled in.
 *
 * @param [in]      input     Buffer holding OID.
 * @param [in, out] inOutIdx  On in, starting index of OID.
 *                            On out, end of parsed OID.
 * @param [out]     oid       OID id.
 * @param [in]      oidType   Expected type of OID. Define NO_VERIFY_OID to
 *                            not compile in check.
 * @param [in]      length    Length of OID data in buffer.
 * @return  0 on success.
 * @return  ASN_UNKNOWN_OID_E when OID is not recognized.
 * @return  BUFFER_E when not enough bytes for proper decode. (ASN_DUMP_OID and
 *          HAVE_OID_DECODING)
 */
static int GetOID(const byte* input, word32* inOutIdx, word32* oid,
                  word32 oidType, int length)
{
    int    ret = 0;
    word32 idx = *inOutIdx;
#ifndef NO_VERIFY_OID
    word32 actualOidSz;
    const byte* actualOid;
    const byte* checkOid = NULL;
    word32 checkOidSz;
#endif /* NO_VERIFY_OID */
#ifdef HAVE_PQC
    word32 found_collision = 0;
#endif
    (void)oidType;
    *oid = 0;

#ifndef NO_VERIFY_OID
    /* Keep references to OID data and length for check. */
    actualOid = &input[idx];
    actualOidSz = (word32)length;
#endif /* NO_VERIFY_OID */

#if defined(HAVE_PQC) && defined(HAVE_LIBOQS)
    /* Since we are summing it up, there could be collisions...and indeed there
     * are: SPHINCS_FAST_LEVEL1 and SPHINCS_FAST_LEVEL3.
     *
     * We will look for the special case of SPHINCS_FAST_LEVEL3 and set *oid to
     * 283 instead of 281; 282 is taken.
     *
     * These hacks will hopefully disappear when new standardized OIDs appear.
     */
    if (memcmp(&input[idx], sigSphincsFast_Level3Oid,
               sizeof(sigSphincsFast_Level3Oid)) == 0) {
        found_collision = SPHINCS_FAST_LEVEL3k;
    }
#endif /* HAVE_PQC */

    /* Sum it up for now. */
    while (length--) {
        /* odd HC08 compiler behavior here when input[idx++] */
        *oid += (word32)input[idx];
        idx++;
    }

#ifdef HAVE_PQC
    if (found_collision) {
        *oid = found_collision;
    }
#endif /* HAVE_PQC */

    /* Return the index after the OID data. */
    *inOutIdx = idx;

#ifndef NO_VERIFY_OID
    /* 'Ignore' type means we don't care which OID it is. */
    if (oidType != oidIgnoreType) {
        /* Get the OID data for the id-type. */
        checkOid = OidFromId(*oid, oidType, &checkOidSz);

    #if defined(WOLFSSL_FPKI)
        /* Handle OID sum collision of
            AES256CBCb (454) 2.16.840.1.101.3.4.1.42
            CP_FPKI_PIV_AUTH_HW_OID (454) 2.16.840.1.101.3.2.1.3.41
        */
        #if defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
        if ((actualOidSz == (word32)sizeof(blkAes256CbcOid)) &&
                (XMEMCMP(actualOid, blkAes256CbcOid,
                 sizeof(blkAes256CbcOid)) == 0)) {

            checkOid   = blkAes256CbcOid;
            checkOidSz = sizeof(blkAes256CbcOid);
        }
        #endif /* HAVE_AES_CBC */
    #endif /* WOLFSSL_FPKI */

    #ifdef ASN_DUMP_OID
        /* Dump out the data for debug. */
        ret = DumpOID(actualOid, actualOidSz, *oid, oidType);
    #endif

        /* TODO: Want to fail when checkOid is NULL.
         * Can't as too many situations where unknown OID is to be
         * supported. Extra parameter for must not be NULL?
         */
        /* Check that the OID data matches what we found for the OID id. */
        if ((ret == 0) && (checkOid != NULL) && ((checkOidSz != actualOidSz) ||
                (XMEMCMP(actualOid, checkOid, checkOidSz) != 0))) {
            WOLFSSL_MSG("OID Check Failed");
            WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
            ret = ASN_UNKNOWN_OID_E;
        }
    }
#endif /* NO_VERIFY_OID */

    return ret;
}

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for an OBJECT_ID. */
static const ASNItem objectIdASN[] = {
/* OID */ { 0, ASN_OBJECT_ID, 0, 0, 0 }
};
enum {
    OBJECTIDASN_IDX_OID = 0
};

/* Number of items in ASN.1 template for an OBJECT_ID. */
#define objectIdASN_Length (sizeof(objectIdASN) / sizeof(ASNItem))
#endif

/* Get the OID id/sum from the BER encoded OBJECT_ID.
 *
 * @param [in]      input     Buffer holding BER encoded data.
 * @param [in, out] inOutIdx  On in, start of OBJECT_ID.
 *                            On out, start of ASN.1 item after OBJECT_ID.
 * @param [out]     oid       Id of OID in OBJECT_ID data.
 * @param [in]      oidType   Type of OID to expect.
 * @param [in]      maxIdx    Maximum index of data in buffer.
 * @return  0 on success.
 * @return  ASN_PARSE_E when encoding is invalid.
 * @return  ASN_UNKNOWN_OID_E when the OID cannot be verified.
 */
int GetObjectId(const byte* input, word32* inOutIdx, word32* oid,
                                  word32 oidType, word32 maxIdx)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int ret, length;

    WOLFSSL_ENTER("GetObjectId");

    ret = GetASNObjectId(input, inOutIdx, &length, maxIdx);
    if (ret != 0)
        return ret;

    return GetOID(input, inOutIdx, oid, oidType, length);
#else
    ASNGetData dataASN[objectIdASN_Length];
    int ret;

    WOLFSSL_ENTER("GetObjectId");

    /* Clear dynamic data and set OID type expected. */
    XMEMSET(dataASN, 0, sizeof(dataASN));
    GetASN_OID(&dataASN[OBJECTIDASN_IDX_OID], oidType);
    /* Decode OBJECT_ID. */
    ret = GetASN_Items(objectIdASN, dataASN, objectIdASN_Length, 0, input,
                       inOutIdx, maxIdx);
    if (ret == 0) {
        /* Return the id/sum. */
        *oid = dataASN[OBJECTIDASN_IDX_OID].data.oid.sum;
    }

    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

#ifndef WOLFSSL_ASN_TEMPLATE
static int SkipObjectId(const byte* input, word32* inOutIdx, word32 maxIdx)
{
    word32 idx = *inOutIdx;
    int    length;
    int ret;

    ret = GetASNObjectId(input, &idx, &length, maxIdx);
    if (ret != 0)
        return ret;

    idx += (word32)length;
    *inOutIdx = idx;

    return 0;
}
#endif

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for an algorithm identifier. */
static const ASNItem algoIdASN[] = {
/*  SEQ  */    { 0, ASN_SEQUENCE, 1, 1, 0 },
/*  OID  */        { 1, ASN_OBJECT_ID, 0, 0, 0 },
/*  NULL */        { 1, ASN_TAG_NULL, 0, 0, 1 },
};
enum {
    ALGOIDASN_IDX_SEQ = 0,
    ALGOIDASN_IDX_OID,
    ALGOIDASN_IDX_NULL
};

/* Number of items in ASN.1 template for an algorithm identifier. */
#define algoIdASN_Length (sizeof(algoIdASN) / sizeof(ASNItem))
#endif

/* Get the OID id/sum from the BER encoding of an algorithm identifier.
 *
 * NULL tag is skipped if present.
 *
 * @param [in]      input     Buffer holding BER encoded data.
 * @param [in, out] inOutIdx  On in, start of algorithm identifier.
 *                            On out, start of ASN.1 item after algorithm id.
 * @param [out]     oid       Id of OID in algorithm identifier data.
 * @param [in]      oidType   Type of OID to expect.
 * @param [in]      maxIdx    Maximum index of data in buffer.
 * @return  0 on success.
 * @return  ASN_PARSE_E when encoding is invalid.
 * @return  ASN_UNKNOWN_OID_E when the OID cannot be verified.
 */
int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid,
                     word32 oidType, word32 maxIdx)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int    length;
    word32 idx = *inOutIdx;
    int    ret;
    *oid = 0;

    WOLFSSL_ENTER("GetAlgoId");

    if (GetSequence(input, &idx, &length, maxIdx) < 0)
        return ASN_PARSE_E;

    if (GetObjectId(input, &idx, oid, oidType, maxIdx) < 0)
        return ASN_OBJECT_ID_E;

    /* could have NULL tag and 0 terminator, but may not */
    if (idx < maxIdx) {
        word32 localIdx = idx; /*use localIdx to not advance when checking tag*/
        byte   tag;

        if (GetASNTag(input, &localIdx, &tag, maxIdx) == 0) {
            if (tag == ASN_TAG_NULL) {
                ret = GetASNNull(input, &idx, maxIdx);
                if (ret != 0)
                    return ret;
            }
        }
    }

    *inOutIdx = idx;

    return 0;
#else
    DECL_ASNGETDATA(dataASN, algoIdASN_Length);
    int ret = 0;

    WOLFSSL_ENTER("GetAlgoId");

    CALLOC_ASNGETDATA(dataASN, algoIdASN_Length, ret, NULL);
    if (ret == 0) {
        /* Set OID type expected. */
        GetASN_OID(&dataASN[ALGOIDASN_IDX_OID], oidType);
        /* Decode the algorithm identifier. */
        ret = GetASN_Items(algoIdASN, dataASN, algoIdASN_Length, 0, input,
            inOutIdx, maxIdx);
    }
    if (ret == 0) {
        /* Return the OID id/sum. */
        *oid = dataASN[ALGOIDASN_IDX_OID].data.oid.sum;
    }

    FREE_ASNGETDATA(dataASN, NULL);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

#ifndef NO_RSA

#ifdef WC_RSA_PSS
/* RFC 8017 - PKCS #1 has RSA PSS parameter ASN definition. */

/* Convert a hash OID to a hash type.
 *
 * @param  [in]   oid   Hash OID.
 * @param  [out]  type  Hash type.
 * @return  0 on success.
 * @return  ASN_PARSE_E when hash OID not supported for RSA PSS.
 */
static int RsaPssHashOidToType(word32 oid, enum wc_HashType* type)
{
    int ret = 0;

    switch (oid) {
    /* SHA-1 is missing as it is the default is not allowed to appear. */
#ifdef WOLFSSL_SHA224
    case SHA224h:
        *type = WC_HASH_TYPE_SHA224;
        break;
#endif
#ifndef NO_SHA256
    case SHA256h:
        *type = WC_HASH_TYPE_SHA256;
        break;
#endif
#ifdef WOLFSSL_SHA384
    case SHA384h:
        *type = WC_HASH_TYPE_SHA384;
        break;
#endif
#ifdef WOLFSSL_SHA512
    case SHA512h:
        *type = WC_HASH_TYPE_SHA512;
        break;
    /* TODO: SHA512_224h */
    /* TODO: SHA512_256h */
#endif
    default:
        ret = ASN_PARSE_E;
        break;
    }

    return ret;
}

/* Convert a hash OID to a MGF1 type.
 *
 * @param  [in]   oid   Hash OID.
 * @param  [out]  mgf   MGF type.
 * @return  0 on success.
 * @return  ASN_PARSE_E when hash OID not supported for RSA PSS.
 */
static int RsaPssHashOidToMgf1(word32 oid, int* mgf)
{
    int ret = 0;

    switch (oid) {
    /* SHA-1 is missing as it is the default is not allowed to appear. */
#ifdef WOLFSSL_SHA224
    case SHA224h:
        *mgf = WC_MGF1SHA224;
        break;
#endif
#ifndef NO_SHA256
    case SHA256h:
        *mgf = WC_MGF1SHA256;
        break;
#endif
#ifdef WOLFSSL_SHA384
    case SHA384h:
        *mgf = WC_MGF1SHA384;
        break;
#endif
#ifdef WOLFSSL_SHA512
    case SHA512h:
        *mgf = WC_MGF1SHA512;
        break;
    /* TODO: SHA512_224h */
    /* TODO: SHA512_256h */
#endif
    default:
        ret = ASN_PARSE_E;
        break;
    }

    return ret;
}

/* Convert a hash OID to a fake signature OID.
 *
 * @param  [in]   oid     Hash OID.
 * @param  [out]  sigOid  Signature OID to pass wto HashForSignature().
 * @return  0 on success.
 * @return  ASN_PARSE_E when hash OID not supported for RSA PSS.
 */
static int RsaPssHashOidToSigOid(word32 oid, word32* sigOid)
{
    int ret = 0;

    switch (oid) {
#ifndef NO_SHA
    case WC_HASH_TYPE_SHA:
        *sigOid = CTC_SHAwRSA;
        break;
#endif
#ifdef WOLFSSL_SHA224
    case WC_HASH_TYPE_SHA224:
        *sigOid = CTC_SHA224wRSA;
        break;
#endif
#ifndef NO_SHA256
    case WC_HASH_TYPE_SHA256:
        *sigOid = CTC_SHA256wRSA;
        break;
#endif
#ifdef WOLFSSL_SHA384
    case WC_HASH_TYPE_SHA384:
        *sigOid = CTC_SHA384wRSA;
        break;
#endif
#ifdef WOLFSSL_SHA512
    case WC_HASH_TYPE_SHA512:
        *sigOid = CTC_SHA512wRSA;
        break;
#endif
    /* TODO: SHA512_224h */
    /* TODO: SHA512_256h */
    /* Not supported by HashForSignature() */
    default:
        ret = ASN_PARSE_E;
        break;
    }

    return ret;
}

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN tag for hashAlgorigthm. */
#define ASN_TAG_RSA_PSS_HASH        (ASN_CONTEXT_SPECIFIC | 0)
/* ASN tag for maskGenAlgorithm. */
#define ASN_TAG_RSA_PSS_MGF         (ASN_CONTEXT_SPECIFIC | 1)
/* ASN tag for saltLength. */
#define ASN_TAG_RSA_PSS_SALTLEN     (ASN_CONTEXT_SPECIFIC | 2)
/* ASN tag for trailerField. */
#define ASN_TAG_RSA_PSS_TRAILER     (ASN_CONTEXT_SPECIFIC | 3)

/* ASN.1 template for RSA PSS parameters. */
static const ASNItem rsaPssParamsASN[] = {
/*  SEQ         */  { 0, ASN_SEQUENCE, 1, 1, 0 },
/*  HASH        */      { 1, ASN_TAG_RSA_PSS_HASH, 1, 1, 1 },
/*  HASHSEQ     */          { 2, ASN_SEQUENCE, 1, 1, 0 },
/*  HASHOID     */              { 3, ASN_OBJECT_ID, 0, 0, 0 },
/*  HASHNULL    */              { 3, ASN_TAG_NULL, 0, 0, 1 },
/*  MGF         */      { 1, ASN_TAG_RSA_PSS_MGF, 1, 1, 1 },
/*  MGFSEQ      */          { 2, ASN_SEQUENCE, 1, 1, 0 },
/*  MGFOID      */              { 3, ASN_OBJECT_ID, 0, 0, 0 },
/*  MGFPARAM    */              { 3, ASN_SEQUENCE, 1, 1, 0 },
/*  MGFHOID     */                  { 4, ASN_OBJECT_ID, 0, 0, 0 },
/*  MGFHNULL    */                  { 4, ASN_TAG_NULL, 0, 0, 1 },
/*  SALTLEN     */      { 1, ASN_TAG_RSA_PSS_SALTLEN, 1, 1, 1 },
/*  SALTLENINT  */          { 2, ASN_INTEGER, 0, 0, 0 },
/*  TRAILER     */      { 1, ASN_TAG_RSA_PSS_TRAILER, 1, 1, 1 },
/*  TRAILERINT  */          { 2, ASN_INTEGER, 0, 0, 0 },
};
enum {
    RSAPSSPARAMSASN_IDX_SEQ = 0,
    RSAPSSPARAMSASN_IDX_HASH,
    RSAPSSPARAMSASN_IDX_HASHSEQ,
    RSAPSSPARAMSASN_IDX_HASHOID,
    RSAPSSPARAMSASN_IDX_HASHNULL,
    RSAPSSPARAMSASN_IDX_MGF,
    RSAPSSPARAMSASN_IDX_MGFSEQ,
    RSAPSSPARAMSASN_IDX_MGFOID,
    RSAPSSPARAMSASN_IDX_MGFPARAM,
    RSAPSSPARAMSASN_IDX_MGFHOID,
    RSAPSSPARAMSASN_IDX_MGFHNULL,
    RSAPSSPARAMSASN_IDX_SALTLEN,
    RSAPSSPARAMSASN_IDX_SALTLENINT,
    RSAPSSPARAMSASN_IDX_TRAILER,
    RSAPSSPARAMSASN_IDX_TRAILERINT,
};

/* Number of items in ASN.1 template for an algorithm identifier. */
#define rsaPssParamsASN_Length (sizeof(rsaPssParamsASN) / sizeof(ASNItem))
#else
/* ASN tag for hashAlgorigthm. */
#define ASN_TAG_RSA_PSS_HASH        (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0)
/* ASN tag for maskGenAlgorithm. */
#define ASN_TAG_RSA_PSS_MGF         (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)
/* ASN tag for saltLength. */
#define ASN_TAG_RSA_PSS_SALTLEN     (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)
/* ASN tag for trailerField. */
#define ASN_TAG_RSA_PSS_TRAILER     (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 3)
#endif

/* Decode the RSA PSS parameters.
 *
 * @param  [in]   params   Buffer holding BER encoded RSA PSS parameters.
 * @param  [in]   sz       Size of data in buffer in bytes.
 * @param  [out]  hash     Hash algorithm to use on message.
 * @param  [out]  mgf      MGF algorithm to use with PSS padding.
 * @param  [out]  saltLen  Length of salt in PSS padding.
 * @return  BAD_FUNC_ARG when the params is NULL.
 * @return  ASN_PARSE_E when the decoding fails.
 * @return  0 on success.
 */
static int DecodeRsaPssParams(const byte* params, word32 sz,
    enum wc_HashType* hash, int* mgf, int* saltLen)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int ret = 0;
    word32 idx = 0;
    int len = 0;
    word32 oid = 0;
    byte tag;
    int length;

    if (params == NULL) {
        ret = BAD_FUNC_ARG;
    }
    if ((ret == 0) && (GetSequence_ex(params, &idx, &len, sz, 1) < 0)) {
        ret = ASN_PARSE_E;
    }
    if (ret == 0) {
        if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_HASH)) {
            /* Hash algorithm to use on message. */
            if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
                ret = ASN_PARSE_E;
            }
            if (ret == 0) {
                if (GetAlgoId(params, &idx, &oid, oidHashType, sz) < 0) {
                    ret = ASN_PARSE_E;
                }
            }
            if (ret == 0) {
                ret = RsaPssHashOidToType(oid, hash);
            }
        }
        else {
            /* Default hash algorithm. */
            *hash = WC_HASH_TYPE_SHA;
        }
    }
    if (ret == 0) {
        if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_MGF)) {
            /* MGF and hash algorithm to use with padding. */
            if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
                ret = ASN_PARSE_E;
            }
            if (ret == 0) {
                if (GetAlgoId(params, &idx, &oid, oidIgnoreType, sz) < 0) {
                    ret = ASN_PARSE_E;
                }
            }
            if ((ret == 0) && (oid != MGF1_OID)) {
                ret = ASN_PARSE_E;
            }
            if (ret == 0) {
                ret = GetAlgoId(params, &idx, &oid, oidHashType, sz);
                if (ret == 0) {
                    ret = RsaPssHashOidToMgf1(oid, mgf);
                }
            }
        }
        else {
            /* Default MGF/Hash algorithm. */
            *mgf = WC_MGF1SHA1;
        }
    }
    if (ret == 0) {
        if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_SALTLEN)) {
            /* Salt length to use with padding. */
            if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
                ret = ASN_PARSE_E;
            }
            if (ret == 0) {
                ret = GetInteger16Bit(params, &idx, sz);
                if (ret >= 0) {
                    *saltLen = ret;
                    ret = 0;
                }
            }
        }
        else {
            /* Default salt length. */
            *saltLen = 20;
        }
    }
    if (ret == 0) {
        if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_TRAILER)) {
            /* Unused - trialerField. */
            if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
                ret = ASN_PARSE_E;
            }
            if (ret == 0) {
                ret = GetInteger16Bit(params, &idx, sz);
                if (ret > 0) {
                    ret = 0;
                }
            }
        }
    }
    if ((ret == 0) && (idx != sz)) {
        ret = ASN_PARSE_E;
    }

    return ret;
#else
    DECL_ASNGETDATA(dataASN, rsaPssParamsASN_Length);
    int ret = 0;
    word16 sLen = 20;

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

    CALLOC_ASNGETDATA(dataASN, rsaPssParamsASN_Length, ret, NULL);
    if (ret == 0) {
        word32 inOutIdx = 0;
        /* Default values. */
        *hash = WC_HASH_TYPE_SHA;
        *mgf = WC_MGF1SHA1;

        /* Set OID type expected. */
        GetASN_OID(&dataASN[RSAPSSPARAMSASN_IDX_HASHOID], oidHashType);
        GetASN_OID(&dataASN[RSAPSSPARAMSASN_IDX_MGFHOID], oidHashType);
        /* Place the salt length into 16-bit var sLen. */
        GetASN_Int16Bit(&dataASN[RSAPSSPARAMSASN_IDX_SALTLENINT], &sLen);
        /* Decode the algorithm identifier. */
        ret = GetASN_Items(rsaPssParamsASN, dataASN, rsaPssParamsASN_Length, 1,
            params, &inOutIdx, sz);
    }
    if ((ret == 0) && (dataASN[RSAPSSPARAMSASN_IDX_HASHOID].tag != 0)) {
        word32 oid = dataASN[RSAPSSPARAMSASN_IDX_HASHOID].data.oid.sum;
        ret = RsaPssHashOidToType(oid, hash);
    }
    if ((ret == 0) && (dataASN[RSAPSSPARAMSASN_IDX_MGFHOID].tag != 0)) {
        word32 oid = dataASN[RSAPSSPARAMSASN_IDX_MGFHOID].data.oid.sum;
        ret = RsaPssHashOidToMgf1(oid, mgf);
    }
    if (ret == 0) {
        *saltLen = sLen;
    }

    FREE_ASNGETDATA(dataASN, NULL);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}
#endif /* WC_RSA_PSS */

#ifndef HAVE_USER_RSA
#if defined(WOLFSSL_ASN_TEMPLATE) || (!defined(NO_CERTS) && \
    (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
     defined(WOLFSSL_KCAPI_RSA) || defined(WOLFSSL_SE050)))
/* Byte offset of numbers in RSA key. */
size_t rsaIntOffset[] = {
    OFFSETOF(RsaKey, n),
    OFFSETOF(RsaKey, e),
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
    OFFSETOF(RsaKey, d),
    OFFSETOF(RsaKey, p),
    OFFSETOF(RsaKey, q),
#if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
    OFFSETOF(RsaKey, dP),
    OFFSETOF(RsaKey, dQ),
    OFFSETOF(RsaKey, u)
#endif
#endif
};

/* Get a number from the RSA key based on an index.
 *
 * Order: { n, e, d, p, q, dP, dQ, u }
 *
 * Caller must ensure index is not invalid!
 *
 * @param [in] key  RSA key object.
 * @param [in] idx  Index of number.
 * @return  A pointer to an mp_int when valid index.
 * @return  NULL when invalid index.
 */
static mp_int* GetRsaInt(RsaKey* key, int idx)
{
    /* Cast key to byte array to and use offset to get to mp_int field. */
    return (mp_int*)(((byte*)key) + rsaIntOffset[idx]);
}
#endif

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for an RSA private key.
 * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
 */
static const ASNItem rsaKeyASN[] = {
/*  SEQ */    { 0, ASN_SEQUENCE, 1, 1, 0 },
/*  VER */        { 1, ASN_INTEGER, 0, 0, 0 },
                /* Integers need to be in this specific order
                 * as asn code depends on this. */
/*  N   */        { 1, ASN_INTEGER, 0, 0, 0 },
/*  E   */        { 1, ASN_INTEGER, 0, 0, 0 },
#if !defined(WOLFSSL_RSA_PUBLIC_ONLY) || defined(WOLFSSL_KEY_GEN)
/*  D   */        { 1, ASN_INTEGER, 0, 0, 0 },
/*  P   */        { 1, ASN_INTEGER, 0, 0, 0 },
/*  Q   */        { 1, ASN_INTEGER, 0, 0, 0 },
/*  DP  */        { 1, ASN_INTEGER, 0, 0, 0 },
/*  DQ  */        { 1, ASN_INTEGER, 0, 0, 0 },
/*  U   */        { 1, ASN_INTEGER, 0, 0, 0 },
                /* otherPrimeInfos  OtherPrimeInfos OPTIONAL
                 * v2 - multiprime */
#endif
};
enum {
    RSAKEYASN_IDX_SEQ = 0,
    RSAKEYASN_IDX_VER,
    /* Integers need to be in this specific order
     * as asn code depends on this. */
    RSAKEYASN_IDX_N,
    RSAKEYASN_IDX_E,
#if !defined(WOLFSSL_RSA_PUBLIC_ONLY) || defined(WOLFSSL_KEY_GEN)
    RSAKEYASN_IDX_D,
    RSAKEYASN_IDX_P,
    RSAKEYASN_IDX_Q,
    RSAKEYASN_IDX_DP,
    RSAKEYASN_IDX_DQ,
    RSAKEYASN_IDX_U,
#endif
    WOLF_ENUM_DUMMY_LAST_ELEMENT(RSAKEYASN_IDX)
};

/* Number of items in ASN.1 template for an RSA private key. */
#define rsaKeyASN_Length (sizeof(rsaKeyASN) / sizeof(ASNItem))
#endif

/* Decode RSA private key.
 *
 * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
 *
 * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
 * being extracted.
 *
 * @param [in]      input     Buffer holding BER encoded data.
 * @param [in, out] inOutIdx  On in, start of RSA private key.
 *                            On out, start of ASN.1 item after RSA private key.
 * @param [in, out] key       RSA key object. May be NULL.
 * @param [out]     keySz     Size of key in bytes. May be NULL.
 * @param [in]      inSz      Number of bytes in buffer.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when input or inOutIdx is NULL.
 * @return  BAD_FUNC_ARG when key and keySz are NULL.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
 *          non-zero length.
 * @return  MP_INIT_E when the unable to initialize an mp_int.
 * @return  ASN_GETINT_E when the unable to convert data to an mp_int.
 */
static int _RsaPrivateKeyDecode(const byte* input, word32* inOutIdx,
    RsaKey* key, int* keySz, word32 inSz)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int version, length;
    word32 algId = 0;

    if (inOutIdx == NULL || input == NULL || (key == NULL && keySz == NULL)) {
        return BAD_FUNC_ARG;
    }

    /* if has pkcs8 header skip it */
    if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
        /* ignore error, did not have pkcs8 header */
    }

    if (GetSequence(input, inOutIdx, &length, inSz) < 0)
        return ASN_PARSE_E;

    if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
        return ASN_PARSE_E;

    if (key == NULL) {
        int i;

        /* Modulus */
        if (GetASNInt(input, inOutIdx, keySz, inSz) < 0) {
            return ASN_PARSE_E;
        }
        *inOutIdx += (word32)*keySz;
        for (i = 1; i < RSA_INTS; i++) {
            if (SkipInt(input, inOutIdx, inSz) < 0) {
                return ASN_RSA_KEY_E;
            }
        }
    }
    else {
        key->type = RSA_PRIVATE;

    #ifdef WOLFSSL_CHECK_MEM_ZERO
        mp_memzero_add("Decode RSA key d", &key->d);
        mp_memzero_add("Decode RSA key p", &key->p);
        mp_memzero_add("Decode RSA key q", &key->q);
    #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
        !defined(RSA_LOW_MEM)) && !defined(WOLFSSL_RSA_PUBLIC_ONLY)
        mp_memzero_add("Decode RSA key dP", &key->dP);
        mp_memzero_add("Decode RSA key dQ", &key->dQ);
        mp_memzero_add("Decode RSA key u", &key->u);
    #endif
    #endif

        if (GetInt(&key->n,  input, inOutIdx, inSz) < 0 ||
            GetInt(&key->e,  input, inOutIdx, inSz) < 0 ||
    #ifndef WOLFSSL_RSA_PUBLIC_ONLY
            GetInt(&key->d,  input, inOutIdx, inSz) < 0 ||
            GetInt(&key->p,  input, inOutIdx, inSz) < 0 ||
            GetInt(&key->q,  input, inOutIdx, inSz) < 0
    #else
            SkipInt(input, inOutIdx, inSz) < 0 ||
            SkipInt(input, inOutIdx, inSz) < 0 ||
            SkipInt(input, inOutIdx, inSz) < 0
    #endif
           ) {
                return ASN_RSA_KEY_E;
           }
    #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)) \
        && !defined(WOLFSSL_RSA_PUBLIC_ONLY)
        if (GetInt(&key->dP, input, inOutIdx, inSz) < 0 ||
            GetInt(&key->dQ, input, inOutIdx, inSz) < 0 ||
            GetInt(&key->u,  input, inOutIdx, inSz) < 0 )  return ASN_RSA_KEY_E;
    #else
        if (SkipInt(input, inOutIdx, inSz) < 0 ||
            SkipInt(input, inOutIdx, inSz) < 0 ||
            SkipInt(input, inOutIdx, inSz) < 0 )  return ASN_RSA_KEY_E;
    #endif

    #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
        if (wc_InitRsaHw(key) != 0) {
            return BAD_STATE_E;
        }
    #endif
    }

    return 0;
#else
    DECL_ASNGETDATA(dataASN, rsaKeyASN_Length);
    int        ret = 0;
    byte       version = (byte)-1;
#if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
    word32 algId = 0;
#endif
    void*      heap = NULL;

    /* Check validity of parameters. */
    if ((inOutIdx == NULL) || (input == NULL) || ((key == NULL) &&
            (keySz == NULL))) {
        ret = BAD_FUNC_ARG;
    }

    if ((ret == 0) && (key != NULL)) {
        heap = key->heap;
    }

#if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
    if (ret == 0) {
        /* if has pkcs8 header skip it */
        if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
            /* ignore error, did not have pkcs8 header */
        }
    }
#endif

    (void)heap;
    CALLOC_ASNGETDATA(dataASN, rsaKeyASN_Length, ret, heap);

    if (ret == 0) {
        /* Register variable to hold version field. */
        GetASN_Int8Bit(&dataASN[RSAKEYASN_IDX_VER], &version);
        /* Setup data to store INTEGER data in mp_int's in RSA object. */
    #if defined(WOLFSSL_RSA_PUBLIC_ONLY)
        #define RSA_ASN_INTS        RSA_PUB_INTS
        /* Not extracting all data from BER encoding. */
        #define RSA_ASN_COMPLETE    0
    #else
        #define RSA_ASN_INTS        RSA_INTS
        /* Extracting all data from BER encoding. */
        #define RSA_ASN_COMPLETE    1
    #endif
        if (key != NULL) {
            int i;
            /* Extract all public fields. */
            for (i = 0; i < RSA_ASN_INTS; i++) {
                GetASN_MP(&dataASN[(byte)RSAKEYASN_IDX_N + i],
                    GetRsaInt(key, i));
            }
        }
        /* Parse BER encoding for RSA private key. */
        ret = GetASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length,
            RSA_ASN_COMPLETE, input, inOutIdx, inSz);
    }
    /* Check version: 0 - two prime, 1 - multi-prime
     * Multi-prime has optional sequence after coefficient for extra primes.
     * If extra primes, parsing will fail as not all the buffer was used.
     */
    if ((ret == 0) && (version > PKCS1v1)) {
        ret = ASN_PARSE_E;
    }
    if ((ret == 0) && (key != NULL)) {
    #if !defined(WOLFSSL_RSA_PUBLIC_ONLY)
        /* RSA key object has all private key values. */
        key->type = RSA_PRIVATE;
    #else
        /* RSA key object has all public key values. */
        key->type = RSA_PUBLIC;
    #endif

    #ifdef WOLFSSL_XILINX_CRYPT
        if (wc_InitRsaHw(key) != 0)
            ret = BAD_STATE_E;
    #endif
    }
    else if (ret == 0) {
        /* Not filling in key but do want key size. */
        *keySz = (int)dataASN[(byte)RSAKEYASN_IDX_N].length;
        /* Check whether first byte of data is 0x00 and drop it. */
        if (input[(int)dataASN[RSAKEYASN_IDX_E].offset - *keySz] == 0) {
            (*keySz)--;
        }
    }

    FREE_ASNGETDATA(dataASN, heap);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

/* Decode RSA private key.
 *
 * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
 *
 * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
 * being extracted.
 *
 * @param [in]      input     Buffer holding BER encoded data.
 * @param [in, out] inOutIdx  On in, start of RSA private key.
 *                            On out, start of ASN.1 item after RSA private key.
 * @param [in, out] key       RSA key object.
 * @param [in]      inSz      Number of bytes in buffer.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when input, inOutIdx or key is NULL.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
 *          non-zero length.
 * @return  MP_INIT_E when the unable to initialize an mp_int.
 * @return  ASN_GETINT_E when the unable to convert data to an mp_int.
 */
int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
    word32 inSz)
{
    if (key == NULL) {
        return BAD_FUNC_ARG;
    }
    return _RsaPrivateKeyDecode(input, inOutIdx, key, NULL, inSz);
}

/* Valdidate RSA private key ASN.1 encoding.
 *
 * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
 *
 * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
 * being extracted.
 *
 * @param [in]      input     Buffer holding BER encoded data.
 * @param [in, out] inOutIdx  On in, start of RSA private key.
 *                            On out, start of ASN.1 item after RSA private key.
 * @param [in]      inSz      Number of bytes in buffer.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when input, inOutIdx or keySz is NULL.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
 *          non-zero length.
 * @return  MP_INIT_E when the unable to initialize an mp_int.
 * @return  ASN_GETINT_E when the unable to convert data to an mp_int.
 */
int wc_RsaPrivateKeyValidate(const byte* input, word32* inOutIdx, int* keySz,
     word32 inSz)
{
    return _RsaPrivateKeyDecode(input, inOutIdx, NULL, keySz, inSz);
}

#endif /* HAVE_USER_RSA */
#endif /* NO_RSA */

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for a PKCS #8 key.
 * Ignoring optional attributes and public key.
 * PKCS #8: RFC 5958, 2 - PrivateKeyInfo
 */
static const ASNItem pkcs8KeyASN[] = {
/*  SEQ                 */    { 0, ASN_SEQUENCE, 1, 1, 0 },
/*  VER                 */        { 1, ASN_INTEGER, 0, 0, 0 },
/*  PKEY_ALGO_SEQ       */        { 1, ASN_SEQUENCE, 1, 1, 0 },
/*  PKEY_ALGO_OID_KEY   */            { 2, ASN_OBJECT_ID, 0, 0, 0 },
/*  PKEY_ALGO_OID_CURVE */            { 2, ASN_OBJECT_ID, 0, 0, 1 },
/*  PKEY_ALGO_NULL      */            { 2, ASN_TAG_NULL, 0, 0, 1 },
#ifdef WC_RSA_PSS
/*  PKEY_ALGO_PARAM_SEQ */            { 2, ASN_SEQUENCE, 1, 0, 1 },
#endif
/*  PKEY_DATA           */        { 1, ASN_OCTET_STRING, 0, 0, 0 },
                /* attributes            [0] Attributes OPTIONAL */
                /* [[2: publicKey        [1] PublicKey OPTIONAL ]] */
};
enum {
    PKCS8KEYASN_IDX_SEQ = 0,
    PKCS8KEYASN_IDX_VER,
    PKCS8KEYASN_IDX_PKEY_ALGO_SEQ,
    PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY,
    PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE,
    PKCS8KEYASN_IDX_PKEY_ALGO_NULL,
#ifdef WC_RSA_PSS
    PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ,
#endif
    PKCS8KEYASN_IDX_PKEY_DATA,
    WOLF_ENUM_DUMMY_LAST_ELEMENT(PKCS8KEYASN_IDX)
};

/* Number of items in ASN.1 template for a PKCS #8 key. */
#define pkcs8KeyASN_Length (sizeof(pkcs8KeyASN) / sizeof(ASNItem))
#endif

/* Remove PKCS #8 header around an RSA, ECDSA, Ed25519, or Ed448.
 *
 * @param [in]       input     Buffer holding BER data.
 * @param [in, out]  inOutIdx  On in, start of PKCS #8 encoding.
 *                             On out, start of encoded key.
 * @param [in]       sz        Size of data in buffer.
 * @param [out]      algId     Key's algorithm id from PKCS #8 header.
 * @return  Length of key data on success.
 * @return  BAD_FUNC_ARG when input or inOutIdx is NULL.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
 * @return  ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
 *          non-zero length.
 */
int ToTraditionalInline_ex(const byte* input, word32* inOutIdx, word32 sz,
                           word32* algId)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx;
    int    version, length;
    int    ret;
    byte   tag;

    if (input == NULL || inOutIdx == NULL)
        return BAD_FUNC_ARG;

    idx = *inOutIdx;

    if (GetSequence(input, &idx, &length, sz) < 0)
        return ASN_PARSE_E;

    if (GetMyVersion(input, &idx, &version, sz) < 0)
        return ASN_PARSE_E;

    if (GetAlgoId(input, &idx, algId, oidKeyType, sz) < 0)
        return ASN_PARSE_E;

    if (GetASNTag(input, &idx, &tag, sz) < 0)
        return ASN_PARSE_E;
    idx = idx - 1; /* reset idx after finding tag */

#if defined(WC_RSA_PSS) && !defined(NO_RSA)
    if (*algId == RSAPSSk && tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
        word32 seqIdx = idx;
        int seqLen;
        /* Not set when -1. */
        enum wc_HashType hash = WC_HASH_TYPE_NONE;
        int mgf = -1;
        int saltLen = 0;

        if (GetSequence(input, &idx, &seqLen, sz) < 0) {
            return ASN_PARSE_E;
        }
        /* Get the private key parameters. */
        ret = DecodeRsaPssParams(input + seqIdx,
            seqLen + idx - seqIdx, &hash, &mgf, &saltLen);
        if (ret != 0) {
            return ASN_PARSE_E;
        }
        /* TODO: store parameters so that usage can be checked. */
        idx += seqLen;
    }
#endif /* WC_RSA_PSS && !NO_RSA */

    if (tag == ASN_OBJECT_ID) {
        if (SkipObjectId(input, &idx, sz) < 0)
            return ASN_PARSE_E;
    }

    ret = GetOctetString(input, &idx, &length, sz);
    if (ret < 0) {
        if (ret == BUFFER_E)
            return ASN_PARSE_E;
        /* Some private keys don't expect an octet string */
        WOLFSSL_MSG("Couldn't find Octet string");
    }

    *inOutIdx = idx;

    return length;
#else
    DECL_ASNGETDATA(dataASN, pkcs8KeyASN_Length);
    int ret = 0;
    word32 oid = 9;
    byte version;
    word32 idx;

    /* Check validity of parameters. */
    if (input == NULL || inOutIdx == NULL) {
        return BAD_FUNC_ARG;
    }

    idx = *inOutIdx;

    CALLOC_ASNGETDATA(dataASN, pkcs8KeyASN_Length, ret, NULL);

    if (ret == 0) {
        /* Get version, check key type and curve type. */
        GetASN_Int8Bit(&dataASN[PKCS8KEYASN_IDX_VER], &version);
        GetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY], oidKeyType);
        GetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE], oidCurveType);
        /* Parse data. */
        ret = GetASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, 1, input,
                           &idx, sz);
    }

    if (ret == 0) {
        /* Key type OID. */
        oid = dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY].data.oid.sum;

        /* Version 1 includes an optional public key.
         * If public key is included then the parsing will fail as it did not
         * use all the data.
         */
        if (version > PKCS8v1) {
            ret = ASN_PARSE_E;
        }
    }
    if (ret == 0) {
        switch (oid) {
    #ifndef NO_RSA
            case RSAk:
                /* Must have NULL item but not OBJECT_ID item. */
                if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag == 0) ||
                    (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
                    ret = ASN_PARSE_E;
                }
                break;
        #ifdef WC_RSA_PSS
            case RSAPSSk:
                /* Must not have NULL item. */
                if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) {
                    ret = ASN_PARSE_E;
                }
                if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ].tag != 0) {
                    enum wc_HashType hash;
                    int mgf;
                    int saltLen;
                    const byte* params = GetASNItem_Addr(
                        dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ], input);
                    word32 paramsSz = GetASNItem_Length(
                        dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ], input);

                    /* Validate the private key parameters. */
                    ret = DecodeRsaPssParams(params, paramsSz, &hash, &mgf,
                        &saltLen);
                    if (ret != 0) {
                        return ASN_PARSE_E;
                    }
                    /* TODO: store parameters so that usage can be checked. */
                }
                break;
        #endif
    #endif
        #ifdef HAVE_ECC
            case ECDSAk:
                /* Must not have NULL item. */
                if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) {
                    ret = ASN_PARSE_E;
                }
                break;
        #endif
        #ifdef HAVE_ED25519
            case ED25519k:
                /* Neither NULL item nor OBJECT_ID item allowed. */
                if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
                    (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
                    ret = ASN_PARSE_E;
                }
                break;
        #endif
        #ifdef HAVE_CURVE25519
            case X25519k:
                /* Neither NULL item nor OBJECT_ID item allowed. */
                if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
                    (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
                    ret = ASN_PARSE_E;
                }
                break;
        #endif
        #ifdef HAVE_ED448
            case ED448k:
                /* Neither NULL item nor OBJECT_ID item allowed. */
                if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
                    (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
                    ret = ASN_PARSE_E;
                }
                break;
        #endif
        #ifdef HAVE_CURVE448
            case X448k:
                /* Neither NULL item nor OBJECT_ID item allowed. */
                if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
                    (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
                    ret = ASN_PARSE_E;
                }
                break;
        #endif
            /* DSAk not supported. */
            /* Falcon, Dilithium and Sphincs not supported. */
            /* Ignore OID lookup failures. */
            default:
                break;
        }
    }
    if (ret == 0) {
        /* Return algorithm id of internal key. */
        *algId = oid;
        /* Return index to start of internal key. */
        *inOutIdx = GetASNItem_DataIdx(dataASN[PKCS8KEYASN_IDX_PKEY_DATA], input);
        /* Return value is length of internal key. */
        ret = (int)dataASN[PKCS8KEYASN_IDX_PKEY_DATA].data.ref.length;
    }

    FREE_ASNGETDATA(dataASN, NULL);
    return ret;
#endif
}

/* TODO: test case  */
int ToTraditionalInline(const byte* input, word32* inOutIdx, word32 sz)
{
    word32 oid;

    return ToTraditionalInline_ex(input, inOutIdx, sz, &oid);
}

#if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)

/* Remove PKCS8 header, move beginning of traditional to beginning of input */
int ToTraditional_ex(byte* input, word32 sz, word32* algId)
{
    word32 inOutIdx = 0;
    int    length;

    if (input == NULL)
        return BAD_FUNC_ARG;

    length = ToTraditionalInline_ex(input, &inOutIdx, sz, algId);
    if (length < 0)
        return length;

    if ((word32)length + inOutIdx > sz)
        return BUFFER_E;

    XMEMMOVE(input, input + inOutIdx, (size_t)length);

    return length;
}

int ToTraditional(byte* input, word32 sz)
{
    word32 oid;

    return ToTraditional_ex(input, sz, &oid);
}

#endif /* HAVE_PKCS8 || HAVE_PKCS12 */

#if defined(HAVE_PKCS8) && !defined(NO_CERTS)

int wc_GetPkcs8TraditionalOffset(byte* input, word32* inOutIdx, word32 sz)
{
    int length;
    word32 algId;

    if (input == NULL || inOutIdx == NULL || (*inOutIdx > sz))
        return BAD_FUNC_ARG;

    length = ToTraditionalInline_ex(input, inOutIdx, sz, &algId);

    return length;
}

int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz,
        int algoID, const byte* curveOID, word32 oidSz)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 keyIdx = 0;
    word32 tmpSz  = 0;
    word32 sz;
    word32 tmpAlgId = 0;

    /* If out is NULL then return the max size needed
     * + 2 for ASN_OBJECT_ID and ASN_OCTET_STRING tags */
    if (out == NULL && outSz != NULL) {
        *outSz = keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
                 + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2;

        if (curveOID != NULL)
            *outSz += oidSz + MAX_LENGTH_SZ + 1;

        WOLFSSL_MSG("Checking size of PKCS8");

        return LENGTH_ONLY_E;
    }

    WOLFSSL_ENTER("wc_CreatePKCS8Key");

    if (key == NULL || out == NULL || outSz == NULL) {
        return BAD_FUNC_ARG;
    }

    /* check the buffer has enough room for largest possible size */
    if (curveOID != NULL) {
        if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
               + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 3 + oidSz + MAX_LENGTH_SZ))
            return BUFFER_E;
    }
    else {
        oidSz = 0; /* with no curveOID oid size must be 0 */
        if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
                  + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2))
            return BUFFER_E;
    }

    /* sanity check: make sure the key doesn't already have a PKCS 8 header */
    if (ToTraditionalInline_ex(key, &keyIdx, keySz, &tmpAlgId) >= 0) {
        (void)tmpAlgId;
        return ASN_PARSE_E;
    }

    /* PrivateKeyInfo ::= SEQUENCE */
    keyIdx = MAX_SEQ_SZ; /* save room for sequence */

    /*  version Version
     *  no header information just INTEGER */
    sz = (word32)SetMyVersion(PKCS8v0, out + keyIdx, 0);
    tmpSz += sz; keyIdx += sz;
    /*  privateKeyAlgorithm PrivateKeyAlgorithmIdentifier */
    sz = 0; /* set sz to 0 and get privateKey oid buffer size needed */
    if (curveOID != NULL && oidSz > 0) {
        byte buf[MAX_LENGTH_SZ];
        sz = SetLength(oidSz, buf);
        sz += 1; /* plus one for ASN object id */
    }
    sz = (word32)SetAlgoID(algoID, out + keyIdx, oidKeyType, (int)(oidSz + sz));
    tmpSz += sz; keyIdx += sz;

    /*  privateKey          PrivateKey *
     * pkcs8 ecc uses slightly different format. Places curve oid in
     * buffer */
    if (curveOID != NULL && oidSz > 0) {
        sz = (word32)SetObjectId((int)oidSz, out + keyIdx);
        keyIdx += sz; tmpSz += sz;
        XMEMCPY(out + keyIdx, curveOID, oidSz);
        keyIdx += oidSz; tmpSz += oidSz;
    }

    sz = (word32)SetOctetString(keySz, out + keyIdx);
    keyIdx += sz; tmpSz += sz;
    XMEMCPY(out + keyIdx, key, keySz);
    tmpSz += keySz;

    /*  attributes          optional
     * No attributes currently added */

    /* rewind and add sequence */
    sz = SetSequence(tmpSz, out);
    XMEMMOVE(out + sz, out + MAX_SEQ_SZ, tmpSz);

    *outSz = tmpSz + sz;
    return (int)(tmpSz + sz);
#else
    DECL_ASNSETDATA(dataASN, pkcs8KeyASN_Length);
    int sz;
    int ret = 0;
    word32 keyIdx = 0;
    word32 tmpAlgId = 0;

    WOLFSSL_ENTER("wc_CreatePKCS8Key");

    /* Check validity of parameters. */
    if (out == NULL && outSz != NULL) {
    }
    else if (key == NULL || out == NULL || outSz == NULL) {
        ret = BAD_FUNC_ARG;
    }

    /* Sanity check: make sure key doesn't have PKCS #8 header. */
    if (ToTraditionalInline_ex(key, &keyIdx, keySz, &tmpAlgId) >= 0) {
        (void)tmpAlgId;
        ret = ASN_PARSE_E;
    }

    CALLOC_ASNSETDATA(dataASN, pkcs8KeyASN_Length, ret, NULL);

    if (ret == 0) {
        /* Only support default PKCS #8 format - v0. */
        SetASN_Int8Bit(&dataASN[PKCS8KEYASN_IDX_VER], PKCS8v0);
        /* Set key OID that corresponds to key data. */
        SetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY], (word32)algoID,
                   oidKeyType);
        if (curveOID != NULL && oidSz > 0) {
            /* ECC key and curveOID set to write. */
            SetASN_Buffer(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE], curveOID, oidSz);
        }
        else {
            /* EC curve OID to encode. */
            dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].noOut = 1;
        }
        /* Only RSA keys have NULL tagged item after OID. */
        dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].noOut = (algoID != RSAk);
    #ifdef WC_RSA_PSS
        dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ].noOut = 1;
    #endif
        /* Set key data to encode. */
        SetASN_Buffer(&dataASN[PKCS8KEYASN_IDX_PKEY_DATA], key, keySz);

        /* Get the size of the DER encoding. */
        ret = SizeASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, &sz);
    }
    if (ret == 0) {
        /* Always return the calculated size. */
        *outSz = (word32)sz;
    }
    /* Check for buffer to encoded into. */
    if ((ret == 0) && (out == NULL)) {
        WOLFSSL_MSG("Checking size of PKCS8");
        ret = LENGTH_ONLY_E;
    }
    if (ret == 0) {
        /*  Encode PKCS #8 key into buffer. */
        SetASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, out);
        ret = sz;
    }

    FREE_ASNSETDATA(dataASN, NULL);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

#endif /* HAVE_PKCS8 && !NO_CERTS */

#if defined(HAVE_PKCS12) || !defined(NO_CHECK_PRIVATE_KEY)
/* check that the private key is a pair for the public key
 * return 1 (true) on match
 * return 0 or negative value on failure/error
 *
 * privKey   : buffer holding DER format private key
 * privKeySz : size of private key buffer
 * pubKey    : buffer holding DER format public key
 * pubKeySz  : size of public key buffer
 * ks        : type of key */
int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz,
                       const byte* pubKey, word32 pubKeySz, enum Key_Sum ks)
{
    int ret;
    (void)privKeySz;
    (void)pubKeySz;
    (void)ks;

    if (privKey == NULL || pubKey == NULL) {
        return BAD_FUNC_ARG;
    }

    #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
    /* test if RSA key */
    if (ks == RSAk
    #ifdef WC_RSA_PSS
        || ks == RSAPSSk
    #endif
        ) {
    #ifdef WOLFSSL_SMALL_STACK
        RsaKey* a;
        RsaKey* b = NULL;
    #else
        RsaKey a[1], b[1];
    #endif
        word32 keyIdx = 0;

    #ifdef WOLFSSL_SMALL_STACK
        a = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
        if (a == NULL)
            return MEMORY_E;
        b = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
        if (b == NULL) {
            XFREE(a, NULL, DYNAMIC_TYPE_RSA);
            return MEMORY_E;
        }
    #endif

        if ((ret = wc_InitRsaKey(a, NULL)) < 0) {
    #ifdef WOLFSSL_SMALL_STACK
            XFREE(b, NULL, DYNAMIC_TYPE_RSA);
            XFREE(a, NULL, DYNAMIC_TYPE_RSA);
    #endif
            return ret;
        }
        if ((ret = wc_InitRsaKey(b, NULL)) < 0) {
            wc_FreeRsaKey(a);
    #ifdef WOLFSSL_SMALL_STACK
            XFREE(b, NULL, DYNAMIC_TYPE_RSA);
            XFREE(a, NULL, DYNAMIC_TYPE_RSA);
    #endif
            return ret;
        }
        if ((ret = wc_RsaPrivateKeyDecode(privKey, &keyIdx, a, privKeySz)) == 0) {
            WOLFSSL_MSG("Checking RSA key pair");
            keyIdx = 0; /* reset to 0 for parsing public key */

            if ((ret = wc_RsaPublicKeyDecode(pubKey, &keyIdx, b,
                    pubKeySz)) == 0) {
                /* limit for user RSA crypto because of RsaKey
                 * dereference. */
            #if defined(HAVE_USER_RSA)
                WOLFSSL_MSG("Cannot verify RSA pair with user RSA");
                ret = 1; /* return first RSA cert as match */
            #else
                /* both keys extracted successfully now check n and e
                 * values are the same. This is dereferencing RsaKey */
                if (mp_cmp(&(a->n), &(b->n)) != MP_EQ ||
                    mp_cmp(&(a->e), &(b->e)) != MP_EQ) {
                    ret = MP_CMP_E;
                    WOLFSSL_ERROR_VERBOSE(ret);
                }
                else
                    ret = 1;
            #endif
            }
            else {
                WOLFSSL_ERROR_VERBOSE(ret);
            }
        }
        wc_FreeRsaKey(b);
        wc_FreeRsaKey(a);
    #ifdef WOLFSSL_SMALL_STACK
        XFREE(b, NULL, DYNAMIC_TYPE_RSA);
        XFREE(a, NULL, DYNAMIC_TYPE_RSA);
    #endif
    }
    else
    #endif /* !NO_RSA && !NO_ASN_CRYPT */

    #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)
    if (ks == ECDSAk) {
    #ifdef WOLFSSL_SMALL_STACK
        ecc_key* key_pair;
        byte*    privDer;
    #else
        ecc_key  key_pair[1];
        byte     privDer[MAX_ECC_BYTES];
    #endif
        word32   privSz = MAX_ECC_BYTES;
        word32   keyIdx = 0;

    #ifdef WOLFSSL_SMALL_STACK
        key_pair = (ecc_key*)XMALLOC(sizeof(ecc_key), NULL, DYNAMIC_TYPE_ECC);
        if (key_pair == NULL)
            return MEMORY_E;
        privDer = (byte*)XMALLOC(MAX_ECC_BYTES, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        if (privDer == NULL) {
            XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
            return MEMORY_E;
        }
    #endif

        if ((ret = wc_ecc_init(key_pair)) < 0) {
    #ifdef WOLFSSL_SMALL_STACK
            XFREE(privDer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
            XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
    #endif
            return ret;
        }

        if ((ret = wc_EccPrivateKeyDecode(privKey, &keyIdx, key_pair,
                privKeySz)) == 0) {
            WOLFSSL_MSG("Checking ECC key pair");

            if ((ret = wc_ecc_export_private_only(key_pair, privDer, &privSz))
                                                                         == 0) {
            #ifdef WOLFSSL_CHECK_MEM_ZERO
                wc_MemZero_Add("wc_CheckPrivateKey privDer", privDer, privSz);
            #endif
                wc_ecc_free(key_pair);
                ret = wc_ecc_init(key_pair);
                if (ret == 0) {
                    ret = wc_ecc_import_private_key(privDer,
                                            privSz, pubKey,
                                            pubKeySz, key_pair);
                }

                /* public and private extracted successfully now check if is
                 * a pair and also do sanity checks on key. wc_ecc_check_key
                 * checks that private * base generator equals pubkey */
                if (ret == 0) {
                    if ((ret = wc_ecc_check_key(key_pair)) == 0) {
                        ret = 1;
                    }
                    else {
                        WOLFSSL_ERROR_VERBOSE(ret);
                    }
                }
                ForceZero(privDer, privSz);
            }
        }
        else {
            WOLFSSL_ERROR_VERBOSE(ret);
        }
        wc_ecc_free(key_pair);
    #ifdef WOLFSSL_SMALL_STACK
        XFREE(privDer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
    #elif defined(WOLFSSL_CHECK_MEM_ZERO)
        wc_MemZero_Check(privDer, MAX_ECC_BYTES);
    #endif
    }
    else
    #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT && !NO_ASN_CRYPT */

    #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
    if (ks == ED25519k) {
    #ifdef WOLFSSL_SMALL_STACK
        ed25519_key* key_pair;
    #else
        ed25519_key  key_pair[1];
    #endif
        word32       keyIdx = 0;

    #ifdef WOLFSSL_SMALL_STACK
        key_pair = (ed25519_key*)XMALLOC(sizeof(ed25519_key), NULL,
                                                          DYNAMIC_TYPE_ED25519);
        if (key_pair == NULL)
            return MEMORY_E;
    #endif

        if ((ret = wc_ed25519_init(key_pair)) < 0) {
    #ifdef WOLFSSL_SMALL_STACK
            XFREE(key_pair, NULL, DYNAMIC_TYPE_ED25519);
    #endif
            return ret;
        }
        if ((ret = wc_Ed25519PrivateKeyDecode(privKey, &keyIdx, key_pair,
                privKeySz)) == 0) {
            WOLFSSL_MSG("Checking ED25519 key pair");
            keyIdx = 0;
            if ((ret = wc_ed25519_import_public(pubKey, pubKeySz,
                    key_pair)) == 0) {
                /* public and private extracted successfully no check if is
                 * a pair and also do sanity checks on key. wc_ecc_check_key
                 * checks that private * base generator equals pubkey */
                if ((ret = wc_ed25519_check_key(key_pair)) == 0) {
                    ret = 1;
                }
                else {
                    WOLFSSL_ERROR_VERBOSE(ret);
                }
            }
        }
        else {
            WOLFSSL_ERROR_VERBOSE(ret);
        }
        wc_ed25519_free(key_pair);
    #ifdef WOLFSSL_SMALL_STACK
        XFREE(key_pair, NULL, DYNAMIC_TYPE_ED25519);
    #endif
    }
    else
    #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT && !NO_ASN_CRYPT */

    #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
    if (ks == ED448k) {
    #ifdef WOLFSSL_SMALL_STACK
        ed448_key* key_pair = NULL;
    #else
        ed448_key  key_pair[1];
    #endif
        word32     keyIdx = 0;

    #ifdef WOLFSSL_SMALL_STACK
        key_pair = (ed448_key*)XMALLOC(sizeof(ed448_key), NULL,
                                                            DYNAMIC_TYPE_ED448);
        if (key_pair == NULL)
            return MEMORY_E;
    #endif

        if ((ret = wc_ed448_init(key_pair)) < 0) {
    #ifdef WOLFSSL_SMALL_STACK
            XFREE(key_pair, NULL, DYNAMIC_TYPE_ED448);
    #endif
            return ret;
        }
        if ((ret = wc_Ed448PrivateKeyDecode(privKey, &keyIdx, key_pair,
                privKeySz)) == 0) {
            WOLFSSL_MSG("Checking ED448 key pair");
            keyIdx = 0;
            if ((ret = wc_ed448_import_public(pubKey, pubKeySz,
                    key_pair)) == 0) {
                /* public and private extracted successfully no check if is
                 * a pair and also do sanity checks on key. wc_ecc_check_key
                 * checks that private * base generator equals pubkey */
                if ((ret = wc_ed448_check_key(key_pair)) == 0) {
                    ret = 1;
                }
                else {
                    WOLFSSL_ERROR_VERBOSE(ret);
                }
            }
        }
        else {
            WOLFSSL_ERROR_VERBOSE(ret);
        }
        wc_ed448_free(key_pair);
    #ifdef WOLFSSL_SMALL_STACK
        XFREE(key_pair, NULL, DYNAMIC_TYPE_ED448);
    #endif
    }
    else
    #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT && !NO_ASN_CRYPT */
    #if defined(HAVE_PQC)
    #if defined(HAVE_FALCON)
    if ((ks == FALCON_LEVEL1k) || (ks == FALCON_LEVEL5k)) {
    #ifdef WOLFSSL_SMALL_STACK
        falcon_key* key_pair = NULL;
    #else
        falcon_key  key_pair[1];
    #endif
        word32     keyIdx = 0;

    #ifdef WOLFSSL_SMALL_STACK
        key_pair = (falcon_key*)XMALLOC(sizeof(falcon_key), NULL,
                                        DYNAMIC_TYPE_FALCON);
        if (key_pair == NULL)
            return MEMORY_E;
    #endif
        ret = wc_falcon_init(key_pair);
        if (ret  < 0) {
    #ifdef WOLFSSL_SMALL_STACK
            XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
    #endif
            return ret;
        }

        if (ks == FALCON_LEVEL1k) {
            ret = wc_falcon_set_level(key_pair, 1);
        }
        else if (ks == FALCON_LEVEL5k) {
            ret = wc_falcon_set_level(key_pair, 5);
        }

        if (ret  < 0) {
    #ifdef WOLFSSL_SMALL_STACK
            XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
    #endif
            return ret;
        }
        if ((ret = wc_Falcon_PrivateKeyDecode(privKey, &keyIdx, key_pair,
                                             privKeySz)) == 0) {
            WOLFSSL_MSG("Checking Falcon key pair");
            keyIdx = 0;
            if ((ret = wc_falcon_import_public(pubKey, pubKeySz,
                                               key_pair)) == 0) {
                /* Public and private extracted successfully. Sanity check. */
                if ((ret = wc_falcon_check_key(key_pair)) == 0) {
                    ret = 1;
                }
                else {
                    WOLFSSL_ERROR_VERBOSE(ret);
                }
            }
        }
        else {
            WOLFSSL_ERROR_VERBOSE(ret);
        }
        wc_falcon_free(key_pair);
    #ifdef WOLFSSL_SMALL_STACK
        XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
    #endif
    }
    else
    #endif /* HAVE_FALCON */
    #if defined(HAVE_DILITHIUM)
    if ((ks == DILITHIUM_LEVEL2k) ||
        (ks == DILITHIUM_LEVEL3k) ||
        (ks == DILITHIUM_LEVEL5k)) {
    #ifdef WOLFSSL_SMALL_STACK
        dilithium_key* key_pair = NULL;
    #else
        dilithium_key  key_pair[1];
    #endif
        word32     keyIdx = 0;

    #ifdef WOLFSSL_SMALL_STACK
        key_pair = (dilithium_key*)XMALLOC(sizeof(dilithium_key), NULL,
                                        DYNAMIC_TYPE_DILITHIUM);
        if (key_pair == NULL)
            return MEMORY_E;
    #endif
        ret = wc_dilithium_init(key_pair);
        if (ret  < 0) {
    #ifdef WOLFSSL_SMALL_STACK
            XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
    #endif
            return ret;
        }

        if (ks == DILITHIUM_LEVEL2k) {
            ret = wc_dilithium_set_level(key_pair, 2);
        }
        else if (ks == DILITHIUM_LEVEL3k) {
            ret = wc_dilithium_set_level(key_pair, 3);
        }
        else if (ks == DILITHIUM_LEVEL5k) {
            ret = wc_dilithium_set_level(key_pair, 5);
        }

        if (ret  < 0) {
    #ifdef WOLFSSL_SMALL_STACK
            XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
    #endif
            return ret;
        }
        if ((ret = wc_Dilithium_PrivateKeyDecode(privKey, &keyIdx, key_pair,
                                             privKeySz)) == 0) {
            WOLFSSL_MSG("Checking Dilithium key pair");
            keyIdx = 0;
            if ((ret = wc_dilithium_import_public(pubKey, pubKeySz,
                                               key_pair)) == 0) {
                /* Public and private extracted successfully. Sanity check. */
                if ((ret = wc_dilithium_check_key(key_pair)) == 0)
                    ret = 1;
            }
        }
        wc_dilithium_free(key_pair);
    #ifdef WOLFSSL_SMALL_STACK
        XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
    #endif
    }
    else
    #endif /* HAVE_DILITHIUM */
    #if defined(HAVE_SPHINCS)
    if ((ks == SPHINCS_FAST_LEVEL1k) ||
        (ks == SPHINCS_FAST_LEVEL3k) ||
        (ks == SPHINCS_FAST_LEVEL5k) ||
        (ks == SPHINCS_SMALL_LEVEL1k) ||
        (ks == SPHINCS_SMALL_LEVEL3k) ||
        (ks == SPHINCS_SMALL_LEVEL5k)) {
    #ifdef WOLFSSL_SMALL_STACK
        sphincs_key* key_pair = NULL;
    #else
        sphincs_key  key_pair[1];
    #endif
        word32     keyIdx = 0;

    #ifdef WOLFSSL_SMALL_STACK
        key_pair = (sphincs_key*)XMALLOC(sizeof(sphincs_key), NULL,
                                        DYNAMIC_TYPE_SPHINCS);
        if (key_pair == NULL)
            return MEMORY_E;
    #endif
        ret = wc_sphincs_init(key_pair);
        if (ret  < 0) {
    #ifdef WOLFSSL_SMALL_STACK
            XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
    #endif
            return ret;
        }

        if (ks == SPHINCS_FAST_LEVEL1k) {
            ret = wc_sphincs_set_level_and_optim(key_pair, 1, FAST_VARIANT);
        }
        else if (ks == SPHINCS_FAST_LEVEL3k) {
            ret = wc_sphincs_set_level_and_optim(key_pair, 3, FAST_VARIANT);
        }
        else if (ks == SPHINCS_FAST_LEVEL5k) {
            ret = wc_sphincs_set_level_and_optim(key_pair, 5, FAST_VARIANT);
        }
        else if (ks == SPHINCS_SMALL_LEVEL1k) {
            ret = wc_sphincs_set_level_and_optim(key_pair, 1, SMALL_VARIANT);
        }
        else if (ks == SPHINCS_SMALL_LEVEL3k) {
            ret = wc_sphincs_set_level_and_optim(key_pair, 3, SMALL_VARIANT);
        }
        else if (ks == SPHINCS_SMALL_LEVEL5k) {
            ret = wc_sphincs_set_level_and_optim(key_pair, 5, SMALL_VARIANT);
        }

        if (ret  < 0) {
    #ifdef WOLFSSL_SMALL_STACK
            XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
    #endif
            return ret;
        }
        if ((ret = wc_Sphincs_PrivateKeyDecode(privKey, &keyIdx, key_pair,
                                             privKeySz)) == 0) {
            WOLFSSL_MSG("Checking Sphincs key pair");
            keyIdx = 0;
            if ((ret = wc_sphincs_import_public(pubKey, pubKeySz,
                                               key_pair)) == 0) {
                /* Public and private extracted successfully. Sanity check. */
                if ((ret = wc_sphincs_check_key(key_pair)) == 0)
                    ret = 1;
            }
        }
        wc_sphincs_free(key_pair);
    #ifdef WOLFSSL_SMALL_STACK
        XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
    #endif
    }
    else
    #endif /* HAVE_SPHINCS */
    #endif /* HAVE_PQC */
    {
        ret = 0;
    }
    (void)ks;

    return ret;
}

/* check that the private key is a pair for the public key in certificate
 * return 1 (true) on match
 * return 0 or negative value on failure/error
 *
 * key   : buffer holding DER format key
 * keySz : size of key buffer
 * der   : a initialized and parsed DecodedCert holding a certificate */
int wc_CheckPrivateKeyCert(const byte* key, word32 keySz, DecodedCert* der)
{
    if (key == NULL || der == NULL) {
        return BAD_FUNC_ARG;
    }

    return wc_CheckPrivateKey(key, keySz, der->publicKey,
            der->pubKeySize, (enum Key_Sum) der->keyOID);
}

#endif /* HAVE_PKCS12 || !NO_CHECK_PRIVATE_KEY */

#ifndef NO_PWDBASED

#if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
/* Check the PBE algorithm is supported and return wolfSSL id, version and block
 * size of encryption algorithm.
 *
 * When PBES2, version is PKCS5v2, CheckAlgoV2() must be called to get id and
 * blockSz based on encryption algorithm.
 *
 * @param [in]  first    First byte of OID to use in check.
 * @param [in]  second   Second byte of OID to use in check.
 * @param [out] id       wolfSSL id for PBE algorithm.
 * @param [out] version  Version of PBE OID:
 *                       PKCS12v1 (PBE), PKCS5 (PBES1), PKCS5v2 (PBES2).
 * @param [out] blockSz  Block size of encryption algorithm.
 * @return  0 on success.
 * @return  ALGO_ID_E when OID not supported.
 * @return  ASN_INPUT_E when first byte is invalid.
 */
static int CheckAlgo(int first, int second, int* id, int* version, int* blockSz)
{
    int ret = 0;

    (void)id;
    (void)blockSz;

    *version = -1;

    /* pkcs-12 1 = pkcs-12PbeIds */
    if (first == 1) {
        /* PKCS #12: Appendix C */
        switch (second) {
#if !defined(NO_SHA)
    #ifndef NO_RC4
        case PBE_SHA1_RC4_128:
            *id = PBE_SHA1_RC4_128;
            *version = PKCS12v1;
            if (blockSz != NULL) {
                *blockSz = 1;
            }
            break;
    #endif
    #ifndef NO_DES3
        case PBE_SHA1_DES3:
            *id = PBE_SHA1_DES3;
            *version = PKCS12v1;
            if (blockSz != NULL) {
                *blockSz = DES_BLOCK_SIZE;
            }
            break;
    #endif
    #ifdef WC_RC2
        case PBE_SHA1_40RC2_CBC:
            *id = PBE_SHA1_40RC2_CBC;
            *version = PKCS12v1;
            if (blockSz != NULL) {
                *blockSz = RC2_BLOCK_SIZE;
            }
            break;
    #endif
#endif /* !NO_SHA */
        default:
            ret = ALGO_ID_E;
            break;
        }
    }
    else if (first != PKCS5) {
        /* Bad OID. */
        ret = ASN_INPUT_E;
    }
    /* PKCS #5 PBES2: Appendix A.4
     * pkcs-5 13 = id-PBES2 */
    else if (second == PBES2) {
        *version = PKCS5v2;
        /* Id and block size come from CheckAlgoV2() */
    }
    else  {
        /* PKCS #5 PBES1: Appendix A.3 */
        /* see RFC 2898 for ids */
        switch (second) {
    #ifndef NO_DES3
        #ifndef NO_MD5
        case PBES1_MD5_DES:
            *id = PBE_MD5_DES;
            *version = PKCS5;
            if (blockSz != NULL) {
                *blockSz = DES_BLOCK_SIZE;
            }
            break;
        #endif
        #ifndef NO_SHA
        case PBES1_SHA1_DES:
            *id = PBE_SHA1_DES;
            *version = PKCS5;
            if (blockSz != NULL) {
                *blockSz = DES_BLOCK_SIZE;
            }
            break;
        #endif
    #endif /* !NO_DES3 */
        default:
            ret = ALGO_ID_E;
            break;
        }
    }

    /* Return error code. */
    return ret;
}

#endif /* HAVE_PKCS8 || HAVE_PKCS12 */

#ifdef HAVE_PKCS8

/* Check the encryption algorithm with PBES2 is supported and return block size
 * and wolfSSL id for the PBE.
 *
 * @param [in]  oid      Encryption algorithm OID id.
 * @param [out] id       wolfSSL id for PBE algorithm.
 * @param [out] version  Version of PBE OID:
 *                       PKCS12v1 (PBE), PKCS5 (PBES1), PKCS5v2 (PBES2).
 * @return  0 on success.
 * @return  ALGO_ID_E when encryption algorithm is not supported with PBES2.
 */
static int CheckAlgoV2(int oid, int* id, int* blockSz)
{
    int ret = 0;

    (void)id;
    (void)blockSz;

    switch (oid) {
#if !defined(NO_DES3) && !defined(NO_SHA)
    case DESb:
        *id = PBE_SHA1_DES;
        if (blockSz != NULL) {
            *blockSz = DES_BLOCK_SIZE;
        }
        break;
    case DES3b:
        *id = PBE_SHA1_DES3;
        if (blockSz != NULL) {
            *blockSz = DES_BLOCK_SIZE;
        }
        break;
#endif
#ifdef WOLFSSL_AES_256
    case AES256CBCb:
        *id = PBE_AES256_CBC;
        if (blockSz != NULL) {
            *blockSz = AES_BLOCK_SIZE;
        }
        break;
#endif
#ifdef WOLFSSL_AES_128
    case AES128CBCb:
        *id = PBE_AES128_CBC;
        if (blockSz != NULL) {
            *blockSz = AES_BLOCK_SIZE;
        }
        break;
#endif
    default:
        WOLFSSL_MSG("No PKCS v2 algo found");
        ret = ALGO_ID_E;
        break;
    }

    /* Return error code. */
    return ret;
}

#endif /* HAVE_PKCS8 */

#if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)

int wc_GetKeyOID(byte* key, word32 keySz, const byte** curveOID, word32* oidSz,
        int* algoID, void* heap)
{
    word32 tmpIdx = 0;

    if (key == NULL || algoID == NULL)
        return BAD_FUNC_ARG;

    *algoID = 0;

    #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
    {
        RsaKey *rsa = (RsaKey *)XMALLOC(sizeof *rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
        if (rsa == NULL)
            return MEMORY_E;

        wc_InitRsaKey(rsa, heap);
        if (wc_RsaPrivateKeyDecode(key, &tmpIdx, rsa, keySz) == 0) {
            *algoID = RSAk;
        }
        else {
            WOLFSSL_MSG("Not RSA DER key");
        }
        wc_FreeRsaKey(rsa);
        XFREE(rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
    }
    #endif /* !NO_RSA && !NO_ASN_CRYPT */
    #if defined(HAVE_ECC) && !defined(NO_ASN_CRYPT)
    if (*algoID == 0) {
        ecc_key *ecc = (ecc_key *)XMALLOC(sizeof *ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
        if (ecc == NULL)
            return MEMORY_E;

        tmpIdx = 0;
        wc_ecc_init_ex(ecc, heap, INVALID_DEVID);
        if (wc_EccPrivateKeyDecode(key, &tmpIdx, ecc, keySz) == 0) {
            *algoID = ECDSAk;

            /* now find oid */
            if (wc_ecc_get_oid(ecc->dp->oidSum, curveOID, oidSz) < 0) {
                WOLFSSL_MSG("Error getting ECC curve OID");
                wc_ecc_free(ecc);
                XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
                return BAD_FUNC_ARG;
            }
        }
        else {
            WOLFSSL_MSG("Not ECC DER key either");
        }
        wc_ecc_free(ecc);
        XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
    }
#endif /* HAVE_ECC && !NO_ASN_CRYPT */
#if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
    if (*algoID == 0) {
        ed25519_key *ed25519 = (ed25519_key *)XMALLOC(sizeof *ed25519, heap,
            DYNAMIC_TYPE_TMP_BUFFER);
        if (ed25519 == NULL)
            return MEMORY_E;

        tmpIdx = 0;
        if (wc_ed25519_init_ex(ed25519, heap, INVALID_DEVID) == 0) {
            if (wc_Ed25519PrivateKeyDecode(key, &tmpIdx, ed25519, keySz) == 0) {
                *algoID = ED25519k;
            }
            else {
                WOLFSSL_MSG("Not ED25519 DER key");
            }
            wc_ed25519_free(ed25519);
        }
        else {
            WOLFSSL_MSG("GetKeyOID wc_ed25519_init failed");
        }
        XFREE(ed25519, heap, DYNAMIC_TYPE_TMP_BUFFER);
    }
#endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT && !NO_ASN_CRYPT */
#if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
    if (*algoID == 0) {
        ed448_key *ed448 = (ed448_key *)XMALLOC(sizeof *ed448, heap,
            DYNAMIC_TYPE_TMP_BUFFER);
        if (ed448 == NULL)
            return MEMORY_E;

        tmpIdx = 0;
        if (wc_ed448_init(ed448) == 0) {
            if (wc_Ed448PrivateKeyDecode(key, &tmpIdx, ed448, keySz) == 0) {
                *algoID = ED448k;
            }
            else {
                WOLFSSL_MSG("Not ED448 DER key");
            }
            wc_ed448_free(ed448);
        }
        else {
            WOLFSSL_MSG("GetKeyOID wc_ed448_init failed");
        }
        XFREE(ed448, heap, DYNAMIC_TYPE_TMP_BUFFER);
    }
#endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT && !NO_ASN_CRYPT */
#if defined(HAVE_PQC)
#if defined(HAVE_FALCON)
    if (*algoID == 0) {
        falcon_key *falcon = (falcon_key *)XMALLOC(sizeof(*falcon), heap,
            DYNAMIC_TYPE_TMP_BUFFER);
        if (falcon == NULL)
            return MEMORY_E;

        if (wc_falcon_init(falcon) != 0) {
            tmpIdx = 0;
            if (wc_falcon_set_level(falcon, 1) == 0) {
                if (wc_Falcon_PrivateKeyDecode(key, &tmpIdx, falcon, keySz)
                    == 0) {
                    *algoID = FALCON_LEVEL1k;
                }
                else {
                    WOLFSSL_MSG("Not Falcon Level 1 DER key");
                }
            }
            else if (wc_falcon_set_level(falcon, 5) == 0) {
                if (wc_Falcon_PrivateKeyDecode(key, &tmpIdx, falcon, keySz)
                    == 0) {
                    *algoID = FALCON_LEVEL5k;
                }
                else {
                    WOLFSSL_MSG("Not Falcon Level 5 DER key");
                }
            }
            else {
                WOLFSSL_MSG("GetKeyOID falcon initialization failed");
            }
            wc_falcon_free(falcon);
        }
        XFREE(falcon, heap, DYNAMIC_TYPE_TMP_BUFFER);
    }
#endif /* HAVE_FALCON */
#if defined(HAVE_DILITHIUM)
    if (*algoID == 0) {
        dilithium_key *dilithium = (dilithium_key *)XMALLOC(sizeof(*dilithium),
             heap, DYNAMIC_TYPE_TMP_BUFFER);
        if (dilithium == NULL)
            return MEMORY_E;

        if (wc_dilithium_init(dilithium) != 0) {
            tmpIdx = 0;
            if (wc_dilithium_set_level(dilithium, 2)
                == 0) {
                if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
                    keySz) == 0) {
                    *algoID = DILITHIUM_LEVEL2k;
                }
                else {
                    WOLFSSL_MSG("Not Dilithium Level 2 DER key");
                }
            }
            else if (wc_dilithium_set_level(dilithium, 3)
                == 0) {
                if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
                    keySz) == 0) {
                    *algoID = DILITHIUM_LEVEL3k;
                }
                else {
                    WOLFSSL_MSG("Not Dilithium Level 3 DER key");
                }
            }
            else if (wc_dilithium_set_level(dilithium, 5)
                == 0) {
                if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
                    keySz) == 0) {
                    *algoID = DILITHIUM_LEVEL5k;
                }
                else {
                    WOLFSSL_MSG("Not Dilithium Level 5 DER key");
                }
            }
            else {
                WOLFSSL_MSG("GetKeyOID dilithium initialization failed");
            }
            wc_dilithium_free(dilithium);
        }
        XFREE(dilithium, heap, DYNAMIC_TYPE_TMP_BUFFER);
    }
#endif /* HAVE_DILITHIUM */
#if defined(HAVE_SPHINCS)
    if (*algoID == 0) {
        sphincs_key *sphincs = (sphincs_key *)XMALLOC(sizeof(*sphincs),
             heap, DYNAMIC_TYPE_TMP_BUFFER);
        if (sphincs == NULL)
            return MEMORY_E;

        if (wc_sphincs_init(sphincs) != 0) {
            tmpIdx = 0;
            if (wc_sphincs_set_level_and_optim(sphincs, 1, FAST_VARIANT)
                == 0) {
                if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
                    keySz) == 0) {
                    *algoID = SPHINCS_FAST_LEVEL1k;
                }
                else {
                    WOLFSSL_MSG("Not Sphincs-fast Level 1 DER key");
                }
            }
            else if (wc_sphincs_set_level_and_optim(sphincs, 3, FAST_VARIANT)
                == 0) {
                if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
                    keySz) == 0) {
                    *algoID = SPHINCS_FAST_LEVEL3k;
                }
                else {
                    WOLFSSL_MSG("Not Sphincs-fast Level 3 DER key");
                }
            }
            else if (wc_sphincs_set_level_and_optim(sphincs, 5, FAST_VARIANT)
                == 0) {
                if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
                    keySz) == 0) {
                    *algoID = SPHINCS_FAST_LEVEL5k;
                }
                else {
                    WOLFSSL_MSG("Not Sphincs-fast Level 5 DER key");
                }
            }
            else if (wc_sphincs_set_level_and_optim(sphincs, 1, SMALL_VARIANT)
                == 0) {
                if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
                    keySz) == 0) {
                    *algoID = SPHINCS_SMALL_LEVEL1k;
                }
                else {
                    WOLFSSL_MSG("Not Sphincs-small Level 1 DER key");
                }
            }
            else if (wc_sphincs_set_level_and_optim(sphincs, 3, SMALL_VARIANT)
                == 0) {
                if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
                    keySz) == 0) {
                    *algoID = SPHINCS_SMALL_LEVEL3k;
                }
                else {
                    WOLFSSL_MSG("Not Sphincs-small Level 3 DER key");
                }
            }
            else if (wc_sphincs_set_level_and_optim(sphincs, 5, SMALL_VARIANT)
                == 0) {
                if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
                    keySz) == 0) {
                    *algoID = SPHINCS_SMALL_LEVEL5k;
                }
                else {
                    WOLFSSL_MSG("Not Sphincs-small Level 5 DER key");
                }
            }
            else {
                WOLFSSL_MSG("GetKeyOID sphincs initialization failed");
            }
            wc_sphincs_free(sphincs);
        }
        XFREE(sphincs, heap, DYNAMIC_TYPE_TMP_BUFFER);
    }
#endif /* HAVE_SPHINCS */
#endif /* HAVE_PQC */

    /* if flag is not set then this is not a key that we understand. */
    if (*algoID == 0) {
        WOLFSSL_MSG("Bad key DER or compile options");
        return BAD_FUNC_ARG;
    }

    (void)tmpIdx;
    (void)curveOID;
    (void)oidSz;
    (void)keySz;
    (void)heap;

    return 1;
}

#endif /* HAVE_PKCS8 || HAVE_PKCS12 */

#ifdef WOLFSSL_ASN_TEMPLATE
#if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
/* ASN.1 template for PBES2 parameters.
 * PKCS #5: RFC 8018, A.4 - PBES2-params without outer SEQUENCE
 *                    A.2 - PBKDF2-params
 *                    B.2 - Encryption schemes
 *                    C   - AlgorithmIdentifier
 */
static const ASNItem pbes2ParamsASN[] = {
/* KDF_SEQ                */ { 0, ASN_SEQUENCE, 1, 1, 0 },
               /* PBKDF2 */
/* KDF_OID                */     { 1, ASN_OBJECT_ID, 0, 0, 0 },
/* PBKDF2_PARAMS_SEQ      */     { 1, ASN_SEQUENCE, 1, 1, 0 },
                   /* Salt */
/* PBKDF2_PARAMS_SALT     */         { 2, ASN_OCTET_STRING, 0, 0, 0 },
                   /* Iteration count */
/* PBKDF2_PARAMS_ITER     */         { 2, ASN_INTEGER, 0, 0, 0 },
                   /* Key length */
/* PBKDF2_PARAMS_KEYLEN   */         { 2, ASN_INTEGER, 0, 0, 1 },
                   /* PRF - default is HMAC-SHA1 */
/* PBKDF2_PARAMS_PRF      */         { 2, ASN_SEQUENCE, 1, 1, 1 },
/* PBKDF2_PARAMS_PRF_OID  */             { 3, ASN_OBJECT_ID, 0, 0, 0 },
/* PBKDF2_PARAMS_PRF_NULL */             { 3, ASN_TAG_NULL, 0, 0, 1 },
/* ENCS_SEQ               */ { 0, ASN_SEQUENCE, 1, 1, 0 },
                   /* Encryption algorithm */
/* ENCS_OID               */   { 1, ASN_OBJECT_ID, 0, 0, 0 },
                   /* IV for CBC */
/* ENCS_PARAMS            */   { 1, ASN_OCTET_STRING, 0, 0, 0 },
};
enum {
    PBES2PARAMSASN_IDX_KDF_SEQ = 0,
    PBES2PARAMSASN_IDX_KDF_OID,
    PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SEQ,
    PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SALT,
    PBES2PARAMSASN_IDX_PBKDF2_PARAMS_ITER,
    PBES2PARAMSASN_IDX_PBKDF2_PARAMS_KEYLEN,
    PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF,
    PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID,
    PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_NULL,
    PBES2PARAMSASN_IDX_ENCS_SEQ,
    PBES2PARAMSASN_IDX_ENCS_OID,
    PBES2PARAMSASN_IDX_ENCS_PARAMS
};

/* Number of items in ASN.1 template for PBES2 parameters. */
#define pbes2ParamsASN_Length (sizeof(pbes2ParamsASN) / sizeof(ASNItem))

/* ASN.1 template for PBES1 parameters.
 * PKCS #5: RFC 8018, A.3. - PBEParameter without outer SEQUENCE
 */
static const ASNItem pbes1ParamsASN[] = {
            /* Salt */
/* SALT */    { 0, ASN_OCTET_STRING, 0, 0, 0 },
            /* Iteration count */
/* ITER */    { 0, ASN_INTEGER, 0, 0, 0 },
};
enum {
    PBES1PARAMSASN_IDX_SALT = 0,
    PBES1PARAMSASN_IDX_ITER
};

/* Number of items in ASN.1 template for PBES1 parameters. */
#define pbes1ParamsASN_Length (sizeof(pbes1ParamsASN) / sizeof(ASNItem))
#endif /* HAVE_PKCS8 || HAVE_PKCS12 */
#endif /* WOLFSSL_ASN_TEMPLATE */

#ifdef HAVE_PKCS8

/*
 * Equivalent to calling TraditionalEnc with the same parameters but with
 * encAlgId set to 0. This function must be kept alive because it's sometimes
 * part of the API (WOLFSSL_ASN_API).
 */
int UnTraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz,
        const char* password, int passwordSz, int vPKCS, int vAlgo,
        byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
{
    return TraditionalEnc(key, keySz, out, outSz, password, passwordSz,
                vPKCS, vAlgo, 0, salt, saltSz, itt, rng, heap);
}

static int GetAlgoV2(int encAlgId, const byte** oid, int *len, int* id,
                     int *blkSz)
{
    int ret = 0;

    switch (encAlgId) {
#if !defined(NO_DES3) && !defined(NO_SHA)
    case DESb:
        *len = sizeof(blkDesCbcOid);
        *oid = blkDesCbcOid;
        *id = PBE_SHA1_DES;
        *blkSz = 8;
        break;
    case DES3b:
        *len = sizeof(blkDes3CbcOid);
        *oid = blkDes3CbcOid;
        *id = PBE_SHA1_DES3;
        *blkSz = 8;
        break;
#endif
#if defined(WOLFSSL_AES_256) && defined(HAVE_AES_CBC)
    case AES256CBCb:
        *len = sizeof(blkAes256CbcOid);
        *oid = blkAes256CbcOid;
        *id = PBE_AES256_CBC;
        *blkSz = 16;
        break;
#endif
    default:
        (void)len;
        (void)oid;
        (void)id;
        (void)blkSz;
        ret = ALGO_ID_E;
    }

    return ret;
}

int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz,
        const char* password, int passwordSz, int vPKCS, int pbeOid,
        int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng,
        void* heap)
{
#ifdef WOLFSSL_SMALL_STACK
    byte* saltTmp = NULL;
#else
    byte saltTmp[MAX_SALT_SIZE];
#endif
    int genSalt = 0;
    int ret = 0;
    int version = 0;
    int pbeId = 0;
    int blockSz = 0;
    const byte* encOid = NULL;
    int encOidSz = 0;
    word32 padSz = 0;
    word32 innerLen = 0;
    const byte* pbeOidBuf = NULL;
    word32 pbeOidBufSz = 0;
    word32 pbeLen = 0;
    word32 kdfLen = 0;
    word32 encLen = 0;
    byte cbcIv[MAX_IV_SIZE];
    word32 idx = 0;
    word32 encIdx = 0;

    (void)heap;

    WOLFSSL_ENTER("wc_EncryptPKCS8Key");

    if (key == NULL || outSz == NULL || password == NULL) {
        ret = BAD_FUNC_ARG;
    }

    if (ret == 0) {
        ret = CheckAlgo(vPKCS, pbeOid, &pbeId, &version, &blockSz);
    }
    if (ret == 0 && (salt == NULL || saltSz == 0)) {
        genSalt = 1;
        saltSz = 8;
    }
    if (ret == 0 && version == PKCS5v2) {
        ret = GetAlgoV2(encAlgId, &encOid, &encOidSz, &pbeId, &blockSz);
    }
    if (ret == 0) {
        padSz = (word32)((blockSz - ((int)keySz & (blockSz - 1))) &
            (blockSz - 1));
        /* inner = OCT salt INT itt */
        innerLen = 2 + saltSz + 2 + (itt < 256 ? 1 : 2);

        if (version != PKCS5v2) {
            pbeOidBuf = OidFromId((word32)pbeId, oidPBEType, &pbeOidBufSz);
            /* pbe = OBJ pbse1 SEQ [ inner ] */
            pbeLen = 2 + pbeOidBufSz + 2 + innerLen;
        }
        else {
            pbeOidBuf = pbes2;
            pbeOidBufSz = sizeof(pbes2);
            /* kdf = OBJ pbkdf2 [ SEQ innerLen ] */
            kdfLen = 2 + sizeof(pbkdf2Oid) + 2 + innerLen;
            /* enc = OBJ enc_alg OCT iv */
            encLen = 2 + (word32)encOidSz + 2 + (word32)blockSz;
            /* pbe = OBJ pbse2 SEQ [ SEQ [ kdf ] SEQ [ enc ] ] */
            pbeLen = (word32)(2 + sizeof(pbes2) + 2 + 2 + (size_t)kdfLen + 2 +
                              (size_t)encLen);

            ret = wc_RNG_GenerateBlock(rng, cbcIv, (word32)blockSz);
        }
    }
    if (ret == 0) {
        /* outerLen = length of PBE encoding + octet string data */
        /* Plus 2 for tag and length for pbe */
        word32 outerLen = 2 + pbeLen;
        /* Octet string tag, length */
        outerLen += 1 + SetLength(keySz + padSz, NULL);
        /* Octet string bytes */
        outerLen += keySz + padSz;
        if (out == NULL) {
            /* Sequence tag, length */
            *outSz = 1 + SetLength(outerLen, NULL) + outerLen;
            return LENGTH_ONLY_E;
        }
        SetOctetString(keySz + padSz, out);

        idx += SetSequence(outerLen, out + idx);

        encIdx = idx + outerLen - keySz - padSz;
        /* Put Encrypted content in place. */
        XMEMCPY(out + encIdx, key, keySz);
        if (padSz > 0) {
            XMEMSET(out + encIdx + keySz, (int)padSz, padSz);
            keySz += padSz;
        }

        if (genSalt == 1) {
        #ifdef WOLFSSL_SMALL_STACK
            saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
            if (saltTmp == NULL) {
                ret = MEMORY_E;
            }
            else
        #endif
            {
                salt = saltTmp;
                if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
                    WOLFSSL_MSG("Error generating random salt");
                }
            }
        }
    }
    if (ret == 0) {
        ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, pbeId,
                  out + encIdx, (int)keySz, version, cbcIv, 1, 0);
    }
    if (ret == 0) {
        if (version != PKCS5v2) {
            /* PBE algorithm */
            idx += SetSequence(pbeLen, out + idx);
            idx += (word32)SetObjectId((int)pbeOidBufSz, out + idx);
            XMEMCPY(out + idx, pbeOidBuf, pbeOidBufSz);
            idx += pbeOidBufSz;
        }
        else {
            /* PBES2 algorithm identifier */
            idx += SetSequence(pbeLen, out + idx);
            idx += (word32)SetObjectId((int)pbeOidBufSz, out + idx);
            XMEMCPY(out + idx, pbeOidBuf, pbeOidBufSz);
            idx += pbeOidBufSz;
            /* PBES2 Parameters: SEQ [ kdf ] SEQ [ enc ] */
            idx += SetSequence(2 + kdfLen + 2 + encLen, out + idx);
            /* KDF Algorithm Identifier */
            idx += SetSequence(kdfLen, out + idx);
            idx += (word32)SetObjectId((int)sizeof(pbkdf2Oid), out + idx);
            XMEMCPY(out + idx, pbkdf2Oid, sizeof(pbkdf2Oid));
            idx += sizeof(pbkdf2Oid);
        }
        idx += SetSequence(innerLen, out + idx);
        idx += SetOctetString(saltSz, out + idx);
        XMEMCPY(out + idx, salt, saltSz); idx += saltSz;
        ret = SetShortInt(out, &idx, (word32)itt, *outSz);
        if (ret > 0)
            ret = 0;
    }
    if (ret == 0) {
        if (version == PKCS5v2) {
            /* Encryption Algorithm Identifier */
            idx += SetSequence(encLen, out + idx);
            idx += (word32)SetObjectId(encOidSz, out + idx);
            XMEMCPY(out + idx, encOid, (size_t)encOidSz);
            idx += (word32)encOidSz;
            /* Encryption Algorithm Parameter: CBC IV */
            idx += SetOctetString((word32)blockSz, out + idx);
            XMEMCPY(out + idx, cbcIv, (size_t)blockSz);
            idx += (word32)blockSz;
        }
        idx += SetOctetString(keySz, out + idx);
        /* Default PRF - no need to write out OID */
        idx += keySz;

        ret = (int)idx;
    }

#ifdef WOLFSSL_SMALL_STACK
    if (saltTmp != NULL) {
        XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
    }
#endif

    WOLFSSL_LEAVE("wc_EncryptPKCS8Key", ret);

    return ret;
}

int wc_DecryptPKCS8Key(byte* input, word32 sz, const char* password,
        int passwordSz)
{
    int ret;
    int length;
    word32 inOutIdx = 0;

    if (input == NULL || password == NULL) {
        return BAD_FUNC_ARG;
    }

    if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
        ret = ASN_PARSE_E;
    }
    else {
        ret = DecryptContent(input + inOutIdx, sz - inOutIdx, password,
                passwordSz);
        if (ret > 0) {
            XMEMMOVE(input, input + inOutIdx, (size_t)ret);
        }
    }

    if (ret > 0) {
        /* DecryptContent will decrypt the data, but it will leave any padding
         * bytes intact. This code calculates the length without the padding
         * and we return that to the user. */
        inOutIdx = 0;
        if (GetSequence(input, &inOutIdx, &length, (word32)ret) < 0) {
            ret = ASN_PARSE_E;
        }
        else {
            ret = (int)inOutIdx + length;
        }
    }

    return ret;
}

/* Takes an unencrypted, traditional DER-encoded key and converts it to a PKCS#8
 * encrypted key. If out is not NULL, it will hold the encrypted key. If it's
 * NULL, LENGTH_ONLY_E will be returned and outSz will have the required out
 * buffer size. */
int TraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz,
        const char* password, int passwordSz, int vPKCS, int vAlgo,
        int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng,
        void* heap)
{
    int ret = 0;
    byte *pkcs8Key = NULL;
    word32 pkcs8KeySz = 0;
    int algId = 0;
    const byte* curveOid = NULL;
    word32 curveOidSz = 0;

    if (ret == 0) {
        /* check key type and get OID if ECC */
        ret = wc_GetKeyOID(key, keySz, &curveOid, &curveOidSz, &algId, heap);
        if (ret == 1)
            ret = 0;
    }
    if (ret == 0) {
        ret = wc_CreatePKCS8Key(NULL, &pkcs8KeySz, key, keySz, algId, curveOid,
                                                                    curveOidSz);
        if (ret == LENGTH_ONLY_E)
            ret = 0;
    }
    if (ret == 0) {
        pkcs8Key = (byte*)XMALLOC(pkcs8KeySz, heap, DYNAMIC_TYPE_TMP_BUFFER);
        if (pkcs8Key == NULL)
            ret = MEMORY_E;
    }
    if (ret == 0) {
        ret = wc_CreatePKCS8Key(pkcs8Key, &pkcs8KeySz, key, keySz, algId,
            curveOid, curveOidSz);
        if (ret >= 0) {
            pkcs8KeySz = (word32)ret;
            ret = 0;
        }
    }
#ifdef WOLFSSL_CHECK_MEM_ZERO
    if (ret == 0) {
        wc_MemZero_Add("TraditionalEnc pkcs8Key", pkcs8Key, pkcs8KeySz);
    }
#endif
    if (ret == 0) {
        ret = wc_EncryptPKCS8Key(pkcs8Key, pkcs8KeySz, out, outSz, password,
            passwordSz, vPKCS, vAlgo, encAlgId, salt, saltSz, itt, rng, heap);
    }

    if (pkcs8Key != NULL) {
        ForceZero(pkcs8Key, pkcs8KeySz);
        XFREE(pkcs8Key, heap, DYNAMIC_TYPE_TMP_BUFFER);
    }

    (void)rng;

    return ret;
}

/* Same as TraditionalEnc, but in the public API. */
int wc_CreateEncryptedPKCS8Key(byte* key, word32 keySz, byte* out,
        word32* outSz, const char* password, int passwordSz, int vPKCS,
        int pbeOid, int encAlgId, byte* salt, word32 saltSz, int itt,
        WC_RNG* rng, void* heap)
{
    return TraditionalEnc(key, keySz, out, outSz, password, passwordSz, vPKCS,
        pbeOid, encAlgId, salt, saltSz, itt, rng, heap);
}


#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for PKCS #8/#7 encrypted key for decrypting
 * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo without outer SEQUENCE
 * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo without outer SEQUENCE
 */
static const ASNItem pkcs8DecASN[] = {
/* ENCALGO_SEQ    */ { 1, ASN_SEQUENCE, 1, 1, 0 },
/* ENCALGO_OID    */     { 2, ASN_OBJECT_ID, 0, 0, 0 },
/* ENCALGO_PARAMS */     { 2, ASN_SEQUENCE, 1, 0, 0 },
            /* PKCS #7 */
/* ENCCONTENT     */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ENC_CONTENT,
                                       0, 0, 2 },
            /* PKCS #8 */
/* ENCDATA        */ { 1, ASN_OCTET_STRING, 0, 0, 2 },
};
enum {
    PKCS8DECASN_IDX_ENCALGO_SEQ = 0,
    PKCS8DECASN_IDX_ENCALGO_OID,
    PKCS8DECASN_IDX_ENCALGO_PARAMS,
    PKCS8DECASN_IDX_ENCCONTENT,
    PKCS8DECASN_IDX_ENCDATA
};

/* Number of items in ASN.1 template for PKCS #8/#7 encrypted key. */
#define pkcs8DecASN_Length (sizeof(pkcs8DecASN) / sizeof(ASNItem))
#endif

/* Decrypt data using PBE algorithm.
 *
 * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo without outer SEQUENCE
 * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo without outer SEQUENCE
 *
 * Note: input buffer is overwritten with decrypted data!
 *
 * Salt is in KDF parameters and IV is PBE parameters when needed.
 *
 * @param [in] input       Data to decrypt and unwrap.
 * @param [in] sz          Size of encrypted data.
 * @param [in] password    Password to derive encryption key with.
 * @param [in] passwordSz  Size of password in bytes.
 * @return  Length of decrypted data on success.
 * @return  MEMORY_E when dynamic memory allocation fails.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
 * @return  Other when decryption fails.
 */
int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 inOutIdx = 0, seqEnd, oid, shaOid = 0;
    int    ret = 0, first, second, length = 0, version, saltSz, id = 0;
    int    iterations = 0, keySz = 0;
#ifdef WOLFSSL_SMALL_STACK
    byte*  salt = NULL;
    byte*  cbcIv = NULL;
#else
    byte   salt[MAX_SALT_SIZE];
    byte   cbcIv[MAX_IV_SIZE];
#endif
    byte   tag;

    if (passwordSz < 0) {
        WOLFSSL_MSG("Bad password size");
        return BAD_FUNC_ARG;
    }

    if (GetAlgoId(input, &inOutIdx, &oid, oidIgnoreType, sz) < 0) {
        ERROR_OUT(ASN_PARSE_E, exit_dc);
    }

    first  = input[inOutIdx - 2];   /* PKCS version always 2nd to last byte */
    second = input[inOutIdx - 1];   /* version.algo, algo id last byte */

    if (CheckAlgo(first, second, &id, &version, NULL) < 0) {
        ERROR_OUT(ASN_INPUT_E, exit_dc); /* Algo ID error */
    }

    if (version == PKCS5v2) {
        if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
            ERROR_OUT(ASN_PARSE_E, exit_dc);
        }

        if (GetAlgoId(input, &inOutIdx, &oid, oidKdfType, sz) < 0) {
            ERROR_OUT(ASN_PARSE_E, exit_dc);
        }

        if (oid != PBKDF2_OID) {
            ERROR_OUT(ASN_PARSE_E, exit_dc);
        }
    }

    if (GetSequence(input, &inOutIdx, &length, sz) <= 0) {
        ERROR_OUT(ASN_PARSE_E, exit_dc);
    }
    /* Find the end of this SEQUENCE so we can check for the OPTIONAL and
     * DEFAULT items. */
    seqEnd = inOutIdx + (word32)length;

    ret = GetOctetString(input, &inOutIdx, &saltSz, sz);
    if (ret < 0)
        goto exit_dc;

    if (saltSz > MAX_SALT_SIZE) {
        ERROR_OUT(ASN_PARSE_E, exit_dc);
    }

#ifdef WOLFSSL_SMALL_STACK
    salt = (byte*)XMALLOC(MAX_SALT_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    if (salt == NULL) {
        ERROR_OUT(MEMORY_E, exit_dc);
    }
#endif

    XMEMCPY(salt, &input[inOutIdx], (size_t)saltSz);
    inOutIdx += (word32)saltSz;

    if (GetShortInt(input, &inOutIdx, &iterations, sz) < 0) {
        ERROR_OUT(ASN_PARSE_E, exit_dc);
    }

    /* OPTIONAL key length */
    if (seqEnd > inOutIdx) {
        word32 localIdx = inOutIdx;

        if (GetASNTag(input, &localIdx, &tag, sz) < 0) {
            ERROR_OUT(ASN_PARSE_E, exit_dc);
        }

        if (tag == ASN_INTEGER &&
                GetShortInt(input, &inOutIdx, &keySz, sz) < 0) {
            ERROR_OUT(ASN_PARSE_E, exit_dc);
        }
    }

    /* DEFAULT HMAC is SHA-1 */
    if (seqEnd > inOutIdx) {
        if (GetAlgoId(input, &inOutIdx, &oid, oidHmacType, sz) < 0) {
            ERROR_OUT(ASN_PARSE_E, exit_dc);
        }

        shaOid = oid;
    }

#ifdef WOLFSSL_SMALL_STACK
    cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    if (cbcIv == NULL) {
        ERROR_OUT(MEMORY_E, exit_dc);
    }
#endif

    if (version == PKCS5v2) {
        /* get encryption algo */
        if (GetAlgoId(input, &inOutIdx, &oid, oidBlkType, sz) < 0) {
            ERROR_OUT(ASN_PARSE_E, exit_dc);
        }

        if (CheckAlgoV2((int)oid, &id, NULL) < 0) {
            ERROR_OUT(ASN_PARSE_E, exit_dc); /* PKCS v2 algo id error */
        }

        if (shaOid == 0)
            shaOid = oid;

        ret = GetOctetString(input, &inOutIdx, &length, sz);
        if (ret < 0)
            goto exit_dc;

        if (length > MAX_IV_SIZE) {
            ERROR_OUT(ASN_PARSE_E, exit_dc);
        }

        XMEMCPY(cbcIv, &input[inOutIdx], (size_t)length);
        inOutIdx += (word32)length;
    }

    if (GetASNTag(input, &inOutIdx, &tag, sz) < 0) {
        ERROR_OUT(ASN_PARSE_E, exit_dc);
    }

    if (tag != (ASN_CONTEXT_SPECIFIC | 0) && tag != ASN_OCTET_STRING) {
        ERROR_OUT(ASN_PARSE_E, exit_dc);
    }

    if (GetLength(input, &inOutIdx, &length, sz) < 0) {
        ERROR_OUT(ASN_PARSE_E, exit_dc);
    }

    ret = wc_CryptKey(password, passwordSz, salt, saltSz, iterations, id,
                   input + inOutIdx, length, version, cbcIv, 0, (int)shaOid);

exit_dc:
#ifdef WOLFSSL_SMALL_STACK
    XFREE(salt,  NULL, DYNAMIC_TYPE_TMP_BUFFER);
    XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif

    if (ret == 0) {
        XMEMMOVE(input, input + inOutIdx, (size_t)length);
        ret = length;
    }

    return ret;
#else
    /* pbes2ParamsASN longer than pkcs8DecASN_Length/pbes1ParamsASN_Length. */
    DECL_ASNGETDATA(dataASN, pbes2ParamsASN_Length);
    int    ret = 0;
    int    id = 0;
    int    version;
    word32 idx = 0;
    word32 pIdx = 0;
    word32 iterations;
    word32 keySz = 0;
    word32 saltSz = 0;
    word32 shaOid = 0;
    byte*  salt = NULL;
    byte*  key = NULL;
    byte   cbcIv[MAX_IV_SIZE];
    byte*  params = NULL;

    WOLFSSL_ENTER("DecryptContent");

    CALLOC_ASNGETDATA(dataASN, pbes2ParamsASN_Length, ret, NULL);

    if (ret == 0) {
        /* Check OID is a PBE Type */
        GetASN_OID(&dataASN[PKCS8DECASN_IDX_ENCALGO_OID], oidPBEType);
        ret = GetASN_Items(pkcs8DecASN, dataASN, pkcs8DecASN_Length, 0, input,
                           &idx, sz);
    }
    if (ret == 0) {
        /* Check the PBE algorithm and get the version and id. */
        idx = dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.length;
        /* Second last byte: 1 (PKCS #12 PBE Id) or 5 (PKCS #5)
         * Last byte: Alg or PBES2 */
        ret = CheckAlgo(dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.data[idx - 2],
                  dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.data[idx - 1],
                  &id, &version, NULL);
    }
    if (ret == 0) {
        /* Get the parameters data. */
        GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCALGO_PARAMS], &params, &sz);
        /* Having a numbered choice means none or both will have errored out. */
        if (dataASN[PKCS8DECASN_IDX_ENCCONTENT].tag != 0)
            GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCCONTENT], &key, &keySz);
        else if (dataASN[PKCS8DECASN_IDX_ENCDATA].tag != 0)
            GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCDATA], &key, &keySz);
        else
            ret = ASN_RSA_KEY_E;
    }

    if (ret == 0) {
        if (version != PKCS5v2) {
            /* Initialize for PBES1 parameters and put iterations in var. */
            XMEMSET(dataASN, 0, sizeof(*dataASN) * pbes1ParamsASN_Length);
            GetASN_Int32Bit(&dataASN[PBES1PARAMSASN_IDX_ITER], &iterations);
            /* Parse the PBES1 parameters. */
            ret = GetASN_Items(pbes1ParamsASN, dataASN, pbes1ParamsASN_Length,
                               0, params, &pIdx, sz);
            if (ret == 0) {
                /* Get the salt data. */
                GetASN_GetRef(&dataASN[PBES1PARAMSASN_IDX_SALT], &salt, &saltSz);
            }
        }
        else {
            word32 ivSz = MAX_IV_SIZE;

            /* Initialize for PBES2 parameters. Put iterations in var; match
             * KDF, HMAC and cipher, and copy CBC into buffer. */
            XMEMSET(dataASN, 0, sizeof(*dataASN) * pbes2ParamsASN_Length);
            GetASN_ExpBuffer(&dataASN[PBES2PARAMSASN_IDX_KDF_OID], pbkdf2Oid, sizeof(pbkdf2Oid));
            GetASN_Int32Bit(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_ITER], &iterations);
            GetASN_OID(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID], oidHmacType);
            GetASN_OID(&dataASN[PBES2PARAMSASN_IDX_ENCS_OID], oidBlkType);
            GetASN_Buffer(&dataASN[PBES2PARAMSASN_IDX_ENCS_PARAMS], cbcIv, &ivSz);
            /* Parse the PBES2 parameters  */
            ret = GetASN_Items(pbes2ParamsASN, dataASN, pbes2ParamsASN_Length,
                               0, params, &pIdx, sz);
            if (ret == 0) {
                /* Get the salt data. */
                GetASN_GetRef(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SALT], &salt, &saltSz);
                /* Get the digest and encryption algorithm id. */
                shaOid = dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID].data.oid.sum; /* Default HMAC-SHA1 */
                id     = (int)dataASN[PBES2PARAMSASN_IDX_ENCS_OID].data.oid.sum;
                /* Convert encryption algorithm to a PBE algorithm if needed. */
                CheckAlgoV2(id, &id, NULL);
            }
        }
    }

    if (ret == 0) {
        /* Decrypt the key. */
        ret = wc_CryptKey(
            password, passwordSz, salt, (int)saltSz, (int)iterations, id, key,
            (int)keySz, version, cbcIv, 0, (int)shaOid);
    }
    if (ret == 0) {
        /* Copy the decrypted key into the input (inline). */
        XMEMMOVE(input, key, keySz);
        ret = (int)keySz;
    }

    FREE_ASNGETDATA(dataASN, NULL);
    return ret;
#endif
}

/* Decrypt data using PBE algorithm and get key from PKCS#8 wrapping.
 *
 * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo
 * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo
 *
 * Note: input buffer is overwritten with decrypted key!
 *
 * Salt is in KDF parameters and IV is PBE parameters when needed.
 *
 * @param [in]  input       Data to decrypt and unwrap.
 * @param [in]  sz          Size of encrypted data.
 * @param [in]  password    Password to derive encryption key with.
 * @param [in]  passwordSz  Size of password in bytes.
 * @param [out] algId       Key algorithm from PKCS#8 wrapper.
 * @return  Length of decrypted data on success.
 * @return  MEMORY_E when dynamic memory allocation fails.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
 * @return  Other when decryption fails.
 */
int ToTraditionalEnc(byte* input, word32 sz, const char* password,
                     int passwordSz, word32* algId)
{
    int ret;

    ret = wc_DecryptPKCS8Key(input, sz, password, passwordSz);
    if (ret > 0) {
        ret = ToTraditional_ex(input, (word32)ret, algId);
    }

    return ret;
}

#endif /* HAVE_PKCS8 */

#ifdef HAVE_PKCS12

#define PKCS8_MIN_BLOCK_SIZE 8
static int Pkcs8Pad(byte* buf, int sz, int blockSz)
{
    int padSz;

    /* calculate pad size */
    padSz = blockSz - (sz & (blockSz - 1));

    /* pad with padSz value */
    if (buf) {
        int i;
        for (i = 0; i < padSz; i++) {
            buf[sz+i] = (byte)(padSz & 0xFF);
        }
    }

    /* return adjusted length */
    return sz + padSz;
}

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for PKCS #8 encrypted key with PBES1 parameters.
 * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo
 * PKCS #5: RFC 8018, A.3 - PBEParameter
 */
static const ASNItem p8EncPbes1ASN[] = {
/* SEQ                   */ { 0, ASN_SEQUENCE, 1, 1, 0 },
/* ENCALGO_SEQ           */     { 1, ASN_SEQUENCE, 1, 1, 0 },
                    /* PBE algorithm */
/* ENCALGO_OID           */         { 2, ASN_OBJECT_ID, 0, 0, 0 },
/* ENCALGO_PBEPARAM_SEQ  */         { 2, ASN_SEQUENCE, 1, 1, 0 },
                        /* Salt */
/* ENCALGO_PBEPARAM_SALT */             { 3, ASN_OCTET_STRING, 0, 0, 0 },
                        /* Iteration Count */
/* ENCALGO_PBEPARAM_ITER */             { 3, ASN_INTEGER, 0, 0, 0 },
/* ENCDATA               */     { 1, ASN_OCTET_STRING, 0, 0, 0 },
};
enum {
    P8ENCPBES1ASN_IDX_SEQ = 0,
    P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
    P8ENCPBES1ASN_IDX_ENCALGO_OID,
    P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SEQ,
    P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT,
    P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER,
    P8ENCPBES1ASN_IDX_ENCDATA
};

#define p8EncPbes1ASN_Length (sizeof(p8EncPbes1ASN) / sizeof(ASNItem))
#endif

/* Wrap a private key in PKCS#8 and encrypt.
 *
 * Used for PKCS#12 and PKCS#7.
 * vPKCS is the version of PKCS to use.
 * vAlgo is the algorithm version to use.
 *
 * When salt is NULL, a random number is generated.
 *
 * data returned is :
 * [ seq - obj [ seq -salt,itt]] , construct with encrypted data
 *
 * @param [in]  input       Data to encrypt.
 * @param [in]  inputSz     Length of data in bytes.
 * @param [out] out         Buffer to write wrapped encrypted data into.
 * @param [out] outSz       Length of encrypted data in bytes.
 * @param [in]  password    Password used to create encryption key.
 * @param [in]  passwordSz  Length of password in bytes.
 * @param [in]  vPKCS       First byte used to determine PBE algorithm.
 * @param [in]  vAlgo       Second byte used to determine PBE algorithm.
 * @param [in]  salt        Salt to use with KDF.
 * @param [in]  saltSz      Length of salt in bytes.
 * @param [in]  itt         Number of iterations to use in KDF.
 * @param [in]  rng         Random number generator to use to generate salt.
 * @param [in]  heap        Dynamic memory allocator hint.
 * @return  The size of encrypted data on success
 * @return  LENGTH_ONLY_E when out is NULL and able to encode.
 * @return  ASN_PARSE_E when the salt size is too large.
 * @return  ASN_VERSION_E when attempting to use a PBES2 algorithm (use
 *          TraditionalEnc).
 * @return  MEMORY_E when dynamic memory allocation fails.
 * @return  Other when encryption or random number generation fails.
 */
int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz,
        const char* password, int passwordSz, int vPKCS, int vAlgo,
        byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 sz;
    word32 inOutIdx = 0;
    word32 tmpIdx   = 0;
    word32 totalSz  = 0;
    word32 seqSz;
    word32 innerSz;
    int    ret;
    int    version, id, blockSz = 0;
#ifdef WOLFSSL_SMALL_STACK
    byte*  saltTmp = NULL;
    byte*  cbcIv   = NULL;
#else
    byte   saltTmp[MAX_SALT_SIZE];
    byte   cbcIv[MAX_IV_SIZE];
#endif
    byte   seq[MAX_SEQ_SZ];
    byte   shr[MAX_SHORT_SZ];
    word32 maxShr = MAX_SHORT_SZ;
    word32 algoSz;
    const  byte* algoName;

    (void)heap;

    WOLFSSL_ENTER("EncryptContent");

    if (CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz) < 0)
        return ASN_INPUT_E;  /* Algo ID error */

    if (version == PKCS5v2) {
        WOLFSSL_MSG("PKCS#5 version 2 not supported yet");
        return BAD_FUNC_ARG;
    }

    if (saltSz > MAX_SALT_SIZE)
        return ASN_PARSE_E;

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

    /* calculate size */
    /* size of constructed string at end */
    sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
    totalSz  = ASN_TAG_SZ;
    totalSz += SetLength(sz, seq);
    totalSz += sz;

    /* size of sequence holding object id and sub sequence of salt and itt */
    algoName = OidFromId((word32)id, oidPBEType, &algoSz);
    if (algoName == NULL) {
        WOLFSSL_MSG("Unknown Algorithm");
        return 0;
    }
    innerSz = (word32)SetObjectId((int)algoSz, seq);
    innerSz += algoSz;

    /* get subsequence of salt and itt */
    if (salt == NULL || saltSz == 0) {
        sz = 8;
    }
    else {
        sz = saltSz;
    }
    seqSz  = SetOctetString(sz, seq);
    seqSz += sz;

    tmpIdx = 0;
    ret = SetShortInt(shr, &tmpIdx, (word32)itt, maxShr);
    if (ret >= 0) {
        seqSz += (word32)ret;
    }
    else {
        return ret;
    }
    innerSz += seqSz + SetSequence(seqSz, seq);
    totalSz += innerSz + SetSequence(innerSz, seq);

    if (out == NULL) {
        *outSz = totalSz;
        return LENGTH_ONLY_E;
    }

    inOutIdx = 0;
    if (totalSz > *outSz)
        return BUFFER_E;

    inOutIdx += SetSequence(innerSz, out + inOutIdx);
    inOutIdx += (word32)SetObjectId((int)algoSz, out + inOutIdx);
    XMEMCPY(out + inOutIdx, algoName, algoSz);
    inOutIdx += algoSz;
    inOutIdx += SetSequence(seqSz, out + inOutIdx);

    /* create random salt if one not provided */
    if (salt == NULL || saltSz == 0) {
        saltSz = 8;
    #ifdef WOLFSSL_SMALL_STACK
        saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
        if (saltTmp == NULL)
            return MEMORY_E;
    #endif
        salt = saltTmp;

        if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
            WOLFSSL_MSG("Error generating random salt");
        #ifdef WOLFSSL_SMALL_STACK
            XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
        #endif
            return ret;
        }
    }
    inOutIdx += SetOctetString(saltSz, out + inOutIdx);
    if (saltSz + inOutIdx > *outSz) {
    #ifdef WOLFSSL_SMALL_STACK
        XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
    #endif
        return BUFFER_E;
    }
    XMEMCPY(out + inOutIdx, salt, saltSz);
    inOutIdx += saltSz;

    /* place iteration setting in buffer */
    ret = SetShortInt(out, &inOutIdx, (word32)itt, *outSz);
    if (ret < 0) {
    #ifdef WOLFSSL_SMALL_STACK
        XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
    #endif
        return ret;
    }

    if (inOutIdx + 1 > *outSz) {
    #ifdef WOLFSSL_SMALL_STACK
        XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
    #endif
        return BUFFER_E;
    }
    out[inOutIdx++] = ASN_CONTEXT_SPECIFIC | 0;

    /* get pad size and verify buffer room */
    sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
    if (sz + inOutIdx > *outSz) {
    #ifdef WOLFSSL_SMALL_STACK
        XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
    #endif
        return BUFFER_E;
    }
    inOutIdx += SetLength(sz, out + inOutIdx);

    /* copy input to output buffer and pad end */
    XMEMCPY(out + inOutIdx, input, inputSz);
    sz = (word32)Pkcs8Pad(out + inOutIdx, (int)inputSz, blockSz);
#ifdef WOLFSSL_SMALL_STACK
    cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, heap, DYNAMIC_TYPE_TMP_BUFFER);
    if (cbcIv == NULL) {
        XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
        return MEMORY_E;
    }
#endif

    /* encrypt */
    if ((ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, id,
                   out + inOutIdx, (int)sz, version, cbcIv, 1, 0)) < 0) {

    #ifdef WOLFSSL_SMALL_STACK
        XFREE(cbcIv,   heap, DYNAMIC_TYPE_TMP_BUFFER);
        XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
    #endif
        return ret;  /* encrypt failure */
    }

#ifdef WOLFSSL_SMALL_STACK
    XFREE(cbcIv,   heap, DYNAMIC_TYPE_TMP_BUFFER);
    XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
#endif

    (void)rng;

    return (int)(inOutIdx + sz);
#else
    DECL_ASNSETDATA(dataASN, p8EncPbes1ASN_Length);
    int ret = 0;
    int sz = 0;
    int version;
    int id = -1;
    int blockSz = 0;
    word32 pkcs8Sz = 0;

    (void)heap;

    WOLFSSL_ENTER("EncryptContent");

    /* Must have a output size to return or check. */
    if (outSz == NULL) {
        ret = BAD_FUNC_ARG;
    }
    /* Check salt size is valid. */
    if ((ret == 0) && (saltSz > MAX_SALT_SIZE)) {
        ret = ASN_PARSE_E;
    }
    /* Get algorithm parameters for algorithm identifier. */
    if ((ret == 0) && CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz) < 0) {
        ret = ASN_INPUT_E;
    }
    /* Check PKCS #5 version - only PBSE1 parameters supported. */
    if ((ret == 0) && (version == PKCS5v2)) {
        ret = BAD_FUNC_ARG;
    }

    CALLOC_ASNSETDATA(dataASN, p8EncPbes1ASN_Length, ret, heap);

    if (ret == 0) {
        /* Setup data to go into encoding including PBE algorithm, salt,
         * iteration count, and padded key length. */
        SetASN_OID(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_OID], (word32)id,
                   oidPBEType);
        if (salt == NULL || saltSz == 0) {
            salt = NULL;
            saltSz = PKCS5_SALT_SZ;
            /* Salt generated into encoding below. */
        }
        SetASN_Buffer(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT],
                salt, saltSz);
        SetASN_Int16Bit(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER],
                        (word16)itt);
        pkcs8Sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
        SetASN_Buffer(&dataASN[P8ENCPBES1ASN_IDX_ENCDATA], NULL, pkcs8Sz);

        /* Calculate size of encoding. */
        ret = SizeASN_Items(p8EncPbes1ASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
                dataASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
                (int)(p8EncPbes1ASN_Length - P8ENCPBES1ASN_IDX_ENCALGO_SEQ),
                &sz);
    }
    /* Return size when no output buffer. */
    if ((ret == 0) && (out == NULL)) {
        *outSz = (word32)sz;
        ret = LENGTH_ONLY_E;
    }
    /* Check output buffer is big enough for encoded data. */
    if ((ret == 0) && (sz > (int)*outSz)) {
        ret = BAD_FUNC_ARG;
    }
    if (ret == 0) {
        /* Encode PKCS#8 key. */
        SetASN_Items(p8EncPbes1ASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
                 dataASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
                 (int)(p8EncPbes1ASN_Length - P8ENCPBES1ASN_IDX_ENCALGO_SEQ),
                 out);

        if (salt == NULL) {
            /* Generate salt into encoding. */
            salt = (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT].
                data.buffer.data;
            ret = wc_RNG_GenerateBlock(rng, salt, saltSz);
        }
    }
    if (ret == 0) {
        byte cbcIv[MAX_IV_SIZE];
        /* Store PKCS#8 key in output buffer. */
        byte* pkcs8 =
            (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCDATA].data.buffer.data;
        XMEMCPY(pkcs8, input, inputSz);
        Pkcs8Pad(pkcs8, (int)inputSz, blockSz);

        /* Encrypt PKCS#8 key inline. */
        ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, id,
                          pkcs8, (int)pkcs8Sz, version, cbcIv, 1, 0);
    }
    if (ret == 0) {
        /* Returning size on success. */
        ret = sz;
    }

    FREE_ASNSETDATA(dataASN, heap);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}


#endif /* HAVE_PKCS12 */
#endif /* NO_PWDBASED */

#ifndef NO_RSA

#ifndef HAVE_USER_RSA
#if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
/* This function is to retrieve key position information in a cert.*
 * The information will be used to call TSIP TLS-linked API for    *
 * certificate verification.                                       */
static int RsaPublicKeyDecodeRawIndex(const byte* input, word32* inOutIdx,
                                      word32 inSz, word32* key_n,
                                      word32* key_n_len, word32* key_e,
                                      word32* key_e_len)
{

    int ret = 0;
    int length = 0;
#if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
    byte b;
#endif

    if (input == NULL || inOutIdx == NULL)
        return BAD_FUNC_ARG;

    if (GetSequence(input, inOutIdx, &length, inSz) < 0)
        return ASN_PARSE_E;

#if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
    if ((*inOutIdx + 1) > inSz)
        return BUFFER_E;

    b = input[*inOutIdx];
    if (b != ASN_INTEGER) {
        /* not from decoded cert, will have algo id, skip past */
        if (GetSequence(input, inOutIdx, &length, inSz) < 0)
            return ASN_PARSE_E;

        if (SkipObjectId(input, inOutIdx, inSz) < 0)
            return ASN_PARSE_E;

        /* Option NULL ASN.1 tag */
        if (*inOutIdx  >= inSz) {
            return BUFFER_E;
        }
        if (input[*inOutIdx] == ASN_TAG_NULL) {
            ret = GetASNNull(input, inOutIdx, inSz);
            if (ret != 0)
                return ret;
        }
        /* TODO: support RSA PSS */

        /* should have bit tag length and seq next */
        ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
        if (ret != 0)
            return ret;

        if (GetSequence(input, inOutIdx, &length, inSz) < 0)
            return ASN_PARSE_E;
    }
#endif /* OPENSSL_EXTRA */

    /* Get modulus */
    ret = GetASNInt(input, inOutIdx, &length, inSz);
    *key_n += *inOutIdx;
    if (ret < 0) {
        return ASN_RSA_KEY_E;
    }
    if (key_n_len)
        *key_n_len = length;
    *inOutIdx += length;

    /* Get exponent */
    ret = GetASNInt(input, inOutIdx, &length, inSz);
    *key_e += *inOutIdx;
    if (ret < 0) {
        return ASN_RSA_KEY_E;
    }
    if (key_e_len)
        *key_e_len = length;

    return ret;
}
#endif /* WOLFSSL_RENESAS_TSIP */

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for an RSA public key.
 * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
 * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
 */
static const ASNItem rsaPublicKeyASN[] = {
/*  SEQ            */ { 0, ASN_SEQUENCE, 1, 1, 0 },
/*  ALGOID_SEQ     */     { 1, ASN_SEQUENCE, 1, 1, 0 },
/*  ALGOID_OID     */         { 2, ASN_OBJECT_ID, 0, 0, 0 },
/*  ALGOID_NULL    */         { 2, ASN_TAG_NULL, 0, 0, 1 },
#ifdef WC_RSA_PSS
/*  ALGOID_P_SEQ   */         { 2, ASN_SEQUENCE, 1, 0, 1 },
#endif
/*  PUBKEY         */     { 1, ASN_BIT_STRING, 0, 1, 0 },
                                                  /* RSAPublicKey */
/*  PUBKEY_RSA_SEQ */         { 2, ASN_SEQUENCE, 1, 1, 0 },
/*  PUBKEY_RSA_N   */             { 3, ASN_INTEGER, 0, 0, 0 },
/*  PUBKEY_RSA_E   */             { 3, ASN_INTEGER, 0, 0, 0 },
};
enum {
    RSAPUBLICKEYASN_IDX_SEQ = 0,
    RSAPUBLICKEYASN_IDX_ALGOID_SEQ,
    RSAPUBLICKEYASN_IDX_ALGOID_OID,
    RSAPUBLICKEYASN_IDX_ALGOID_NULL,
#ifdef WC_RSA_PSS
    RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ,
#endif
    RSAPUBLICKEYASN_IDX_PUBKEY,
    RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ,
    RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N,
    RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E
};

/* Number of items in ASN.1 template for an RSA public key. */
#define rsaPublicKeyASN_Length (sizeof(rsaPublicKeyASN) / sizeof(ASNItem))
#endif

/* Decode RSA public key.
 *
 * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
 * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
 *
 * @param [in]      input     Buffer holding BER encoded data.
 * @param [in, out] inOutIdx  On in, start of RSA public key.
 *                            On out, start of ASN.1 item after RSA public key.
 * @param [in]      inSz      Number of bytes in buffer.
 * @param [out]     n         Pointer to modulus in buffer.
 * @param [out]     nSz       Size of modulus in bytes.
 * @param [out]     e         Pointer to exponent in buffer.
 * @param [out]     eSz       Size of exponent in bytes.
 * @return  0 on success.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
 * @return  ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
 *          non-zero length.
 * @return  ASN_BITSTR_E when the expected BIT_STRING tag is not found.
 * @return  ASN_UNKNOWN_OID_E when the OID cannot be verified.
 */
int wc_RsaPublicKeyDecode_ex(const byte* input, word32* inOutIdx, word32 inSz,
    const byte** n, word32* nSz, const byte** e, word32* eSz)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int ret = 0;
    int length = 0;
#if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
    word32 localIdx;
    byte   tag;
#endif

    if (input == NULL || inOutIdx == NULL)
        return BAD_FUNC_ARG;

    if (GetSequence(input, inOutIdx, &length, inSz) < 0)
        return ASN_PARSE_E;

#if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
    localIdx = *inOutIdx;
    if (GetASNTag(input, &localIdx, &tag, inSz) < 0)
        return BUFFER_E;

    if (tag != ASN_INTEGER) {
        /* not from decoded cert, will have algo id, skip past */
        if (GetSequence(input, inOutIdx, &length, inSz) < 0)
            return ASN_PARSE_E;

        if (SkipObjectId(input, inOutIdx, inSz) < 0)
            return ASN_PARSE_E;

        /* Option NULL ASN.1 tag */
        if (*inOutIdx  >= inSz) {
            return BUFFER_E;
        }

        localIdx = *inOutIdx;
        if (GetASNTag(input, &localIdx, &tag, inSz) < 0)
            return ASN_PARSE_E;

        if (tag == ASN_TAG_NULL) {
            ret = GetASNNull(input, inOutIdx, inSz);
            if (ret != 0)
                return ret;
        }
    #ifdef WC_RSA_PSS
        /* Skip RSA PSS parameters. */
        else if (tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
            if (GetSequence(input, inOutIdx, &length, inSz) < 0)
                return ASN_PARSE_E;
            *inOutIdx += length;
        }
    #endif

        /* should have bit tag length and seq next */
        ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
        if (ret != 0)
            return ret;

        if (GetSequence(input, inOutIdx, &length, inSz) < 0)
            return ASN_PARSE_E;
    }
#endif /* OPENSSL_EXTRA */

    /* Get modulus */
    ret = GetASNInt(input, inOutIdx, &length, inSz);
    if (ret < 0) {
        return ASN_RSA_KEY_E;
    }
    if (nSz)
        *nSz = (word32)length;
    if (n)
        *n = &input[*inOutIdx];
    *inOutIdx += (word32)length;

    /* Get exponent */
    ret = GetASNInt(input, inOutIdx, &length, inSz);
    if (ret < 0) {
        return ASN_RSA_KEY_E;
    }
    if (eSz)
        *eSz = (word32)length;
    if (e)
        *e = &input[*inOutIdx];
    *inOutIdx += (word32)length;

    return ret;
#else
    DECL_ASNGETDATA(dataASN, rsaPublicKeyASN_Length);
    int ret = 0;
#ifdef WC_RSA_PSS
    word32 oid = RSAk;
#endif

    /* Check validity of parameters. */
    if (input == NULL || inOutIdx == NULL) {
        ret = BAD_FUNC_ARG;
    }

    CALLOC_ASNGETDATA(dataASN, rsaPublicKeyASN_Length, ret, NULL);

    if (ret == 0) {
        /* Try decoding PKCS #1 public key by ignoring rest of ASN.1. */
        ret = GetASN_Items(&rsaPublicKeyASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ],
           &dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ],
           (int)(rsaPublicKeyASN_Length - RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ),
           0, input, inOutIdx, inSz);
        if (ret != 0) {
            /* Didn't work - try whole SubjectKeyInfo instead. */
        #ifdef WC_RSA_PSS
            /* Could be RSA or RSA PSS key. */
            GetASN_OID(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID], oidKeyType);
        #else
            /* Set the OID to expect. */
            GetASN_ExpBuffer(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID],
                    keyRsaOid, sizeof(keyRsaOid));
        #endif
            /* Decode SubjectKeyInfo. */
            ret = GetASN_Items(rsaPublicKeyASN, dataASN,
                               rsaPublicKeyASN_Length, 1, input, inOutIdx,
                               inSz);
        }
    }
#ifdef WC_RSA_PSS
    if ((ret == 0) && (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID].tag != 0)) {
        /* Two possible OIDs supported - RSA and RSA PSS. */
        oid = dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID].data.oid.sum;
        if ((oid != RSAk) && (oid != RSAPSSk)) {
            ret = ASN_PARSE_E;
        }
    }
    if ((ret == 0) && (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ].tag != 0)) {
        /* Can't have NULL and SEQ. */
        if (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_NULL].tag != 0) {
            ret = ASN_PARSE_E;
        }
        /* SEQ present only with RSA PSS. */
        if ((ret == 0) && (oid != RSAPSSk)) {
            ret = ASN_PARSE_E;
        }
        if (ret == 0) {
            enum wc_HashType hash;
            int mgf;
            int saltLen;
            const byte* params = GetASNItem_Addr(
                dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ], input);
            word32 paramsSz = GetASNItem_Length(
                dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ], input);

            /* Validate the private key parameters. */
            ret = DecodeRsaPssParams(params, paramsSz, &hash, &mgf, &saltLen);
            /* TODO: store parameters so that usage can be checked. */
        }
    }
#endif
    if (ret == 0) {
        /* Return the buffers and lengths asked for. */
        if (n != NULL) {
            *n   = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N].data.ref.data;
        }
        if (nSz != NULL) {
            *nSz = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N].data.ref.length;
        }
        if (e != NULL) {
            *e   = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E].data.ref.data;
        }
        if (eSz != NULL) {
            *eSz = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E].data.ref.length;
        }
    }

    FREE_ASNGETDATA(dataASN, NULL);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

/* Decode RSA public key.
 *
 * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
 * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
 *
 * @param [in]      input     Buffer holding BER encoded data.
 * @param [in, out] inOutIdx  On in, start of RSA public key.
 *                            On out, start of ASN.1 item after RSA public key.
 * @param [in, out] key       RSA key object.
 * @param [in]      inSz      Number of bytes in buffer.
 * @return  0 on success.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
 * @return  ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
 *          non-zero length.
 * @return  ASN_BITSTR_E when the expected BIT_STRING tag is not found.
 * @return  ASN_UNKNOWN_OID_E when the OID cannot be verified.
 */
int wc_RsaPublicKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
                       word32 inSz)
{
    int ret;
    const byte *n = NULL, *e = NULL;
    word32 nSz = 0, eSz = 0;

    if (key == NULL)
        return BAD_FUNC_ARG;

    ret = wc_RsaPublicKeyDecode_ex(input, inOutIdx, inSz, &n, &nSz, &e, &eSz);
    if (ret == 0) {
        ret = wc_RsaPublicKeyDecodeRaw(n, nSz, e, eSz, key);
    }

    return ret;
}
#endif /* HAVE_USER_RSA */
#endif /* !NO_RSA */

#ifndef NO_DH
#if defined(WOLFSSL_DH_EXTRA)
/*
 * Decodes DH public key to fill specified DhKey.
 *
 * return 0 on success, negative on failure
 */
int wc_DhPublicKeyDecode(const byte* input, word32* inOutIdx,
                DhKey* key, word32 inSz)
{
    int ret = 0;
    int length;
    word32 oid = 0;

    if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
        return BAD_FUNC_ARG;

    if (GetSequence(input, inOutIdx, &length, inSz) < 0)
        return ASN_PARSE_E;

    if (GetSequence(input, inOutIdx, &length, inSz) < 0)
        return ASN_PARSE_E;

    ret = GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz);
    if (oid != DHk || ret < 0)
        return ASN_DH_KEY_E;

    if (GetSequence(input, inOutIdx, &length, inSz) < 0)
        return ASN_PARSE_E;

    if (GetInt(&key->p, input, inOutIdx, inSz) < 0)
        return ASN_DH_KEY_E;

    if (GetInt(&key->g, input, inOutIdx, inSz) < 0) {
        mp_clear(&key->p);
        return ASN_DH_KEY_E;
    }
    ret = (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) == 0);
    if (ret > 0) {
        /* Found Bit String WOLFSSL_DH_EXTRA is required to access DhKey.pub */
        if (GetInt(&key->pub, input, inOutIdx, inSz) < 0) {
            mp_clear(&key->p);
            mp_clear(&key->g);
            return ASN_DH_KEY_E;
        }
    }
    else {
        mp_clear(&key->p);
        mp_clear(&key->g);
        return ASN_DH_KEY_E;
    }
    return 0;
}
#endif /* WOLFSSL_DH_EXTRA */

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for DH key.
 * PKCS #3, 9 - DHParameter.
 * (Also in: RFC 2786, 3)
 */
static const ASNItem dhParamASN[] = {
/* SEQ     */    { 0, ASN_SEQUENCE, 1, 1, 0 },
                /* prime */
/* PRIME   */        { 1, ASN_INTEGER, 0, 0, 0 },
                /* base */
/* BASE    */        { 1, ASN_INTEGER, 0, 0, 0 },
                /* privateValueLength */
/* PRIVLEN */        { 1, ASN_INTEGER, 0, 0, 1 },
};
enum {
    DHPARAMASN_IDX_SEQ = 0,
    DHPARAMASN_IDX_PRIME,
    DHPARAMASN_IDX_BASE,
    DHPARAMASN_IDX_PRIVLEN
};

/* Number of items in ASN.1 template for DH key. */
#define dhParamASN_Length (sizeof(dhParamASN) / sizeof(ASNItem))

#ifdef WOLFSSL_DH_EXTRA
/* ASN.1 template for DH key wrapped in PKCS #8 or SubjectPublicKeyInfo.
 * PKCS #8: RFC 5208, 5 - PrivateKeyInfo
 * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
 * RFC 3279, 2.3.3 - DH in SubjectPublicKeyInfo
 */
static const ASNItem dhKeyPkcs8ASN[] = {
/* SEQ                  */ { 0, ASN_SEQUENCE, 1, 1, 0 },
/* VER                  */     { 1, ASN_INTEGER, 0, 0, 1 },
/* PKEYALGO_SEQ         */     { 1, ASN_SEQUENCE, 1, 1, 0 },
/* PKEYALGO_OID         */         { 2, ASN_OBJECT_ID, 0, 0, 0 },
                                                     /* DHParameter */
/* PKEYALGO_PARAM_SEQ   */         { 2, ASN_SEQUENCE, 1, 1, 0 },
                                                         /* p */
/* PKEYALGO_PARAM_P     */             { 3, ASN_INTEGER, 0, 0, 0 },
                                                         /* g */
/* PKEYALGO_PARAM_G     */             { 3, ASN_INTEGER, 0, 0, 0 },
                                                         /* q - factor of p-1 */
/* PKEYALGO_PARAM_Q     */             { 3, ASN_INTEGER, 0, 0, 1 },
                                                         /* j - subgroup factor */
/* PKEYALGO_PARAM_J     */             { 3, ASN_INTEGER, 0, 0, 1 },
                                                         /* ValidationParms */
/* PKEYALGO_PARAM_VALID */             { 3, ASN_SEQUENCE, 0, 0, 1 },
                                                 /* PrivateKey - PKCS #8 */
/* PKEY_STR             */     { 1, ASN_OCTET_STRING, 0, 1, 2 },
/* PKEY_INT             */         { 2, ASN_INTEGER, 0, 0, 0 },
                                                 /* PublicKey - SubjectPublicKeyInfo. */
/* PUBKEY_STR           */     { 1, ASN_BIT_STRING, 0, 1, 2 },
/* PUBKEY_INT           */         { 2, ASN_INTEGER, 0, 0, 0 },
};
enum {
    DHKEYPKCS8ASN_IDX_SEQ = 0,
    DHKEYPKCS8ASN_IDX_VER,
    DHKEYPKCS8ASN_IDX_PKEYALGO_SEQ,
    DHKEYPKCS8ASN_IDX_PKEYALGO_OID,
    DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_SEQ,
    DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P,
    DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G,
    DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q,
    DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_J,
    DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_VALID,
    DHKEYPKCS8ASN_IDX_PKEY_STR,
    DHKEYPKCS8ASN_IDX_PKEY_INT,
    DHKEYPKCS8ASN_IDX_PUBKEY_STR,
    DHKEYPKCS8ASN_IDX_PUBKEY_INT
};

#define dhKeyPkcs8ASN_Length (sizeof(dhKeyPkcs8ASN) / sizeof(ASNItem))
#endif
#endif

/* Decodes either PKCS#3 DH parameters or PKCS#8 DH key file (WOLFSSL_DH_EXTRA).
 *
 * See also wc_DhParamsLoad(). Loads directly into buffers rather than key
 * object.
 *
 * @param [in]      input     BER/DER encoded data.
 * @param [in, out] inOutIdx  On in, start of DH key data.
 *                            On out, end of DH key data.
 * @param [in, out] key       DH key object.
 * @param [in]      inSz      Size of data in bytes.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when input, inOutIDx or key is NULL.
 * @return  MEMORY_E when dynamic memory allocation fails.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
 * @return  ASN_BITSTR_E when the expected BIT_STRING tag is not found.
 * @return  ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
 *          non-zero length.
 * @return  MP_INIT_E when the unable to initialize an mp_int.
 * @return  ASN_GETINT_E when the unable to convert data to an mp_int.
 * @return  ASN_UNKNOWN_OID_E when the OID cannot be verified.
 */
int wc_DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int ret = 0;
    int length;
#ifdef WOLFSSL_DH_EXTRA
    #if !defined(HAVE_FIPS) || \
        (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
    word32 oid = 0, temp = 0;
    #endif
#endif

    WOLFSSL_ENTER("wc_DhKeyDecode");

    if (inOutIdx == NULL)
        return BAD_FUNC_ARG;

    if (GetSequence(input, inOutIdx, &length, inSz) < 0)
        return ASN_PARSE_E;

#ifdef WOLFSSL_DH_EXTRA
    #if !defined(HAVE_FIPS) || \
        (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
    temp = *inOutIdx;
    #endif
#endif
    /* Assume input started after 1.2.840.113549.1.3.1 dhKeyAgreement */
    if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
        ret = ASN_DH_KEY_E;
    }
    if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
        mp_clear(&key->p);
        ret = ASN_DH_KEY_E;
    }

#ifdef WOLFSSL_DH_EXTRA
    #if !defined(HAVE_FIPS) || \
        (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
    /* If ASN_DH_KEY_E: Check if input started at beginning of key */
    if (ret == ASN_DH_KEY_E) {
        *inOutIdx = temp;

        /* the version (0) - private only (for public skip) */
        if (GetASNInt(input, inOutIdx, &length, inSz) == 0) {
            *inOutIdx += (word32)length;
        }

        /* Size of dhKeyAgreement section */
        if (GetSequence(input, inOutIdx, &length, inSz) < 0)
            return ASN_PARSE_E;

        /* Check for dhKeyAgreement */
        ret = GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz);
        if (oid != DHk || ret < 0)
            return ASN_DH_KEY_E;

        if (GetSequence(input, inOutIdx, &length, inSz) < 0)
            return ASN_PARSE_E;

        if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
            return ASN_DH_KEY_E;
        }
        if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
            mp_clear(&key->p);
            return ASN_DH_KEY_E;
        }
    }

    temp = *inOutIdx;
    ret = (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) == 0);
    if (ret > 0) {
        /* Found Bit String */
        if (GetInt(&key->pub, input, inOutIdx, inSz) == 0) {
            WOLFSSL_MSG("Found Public Key");
            ret = 0;
        }
    } else {
        *inOutIdx = temp;
        ret = (GetOctetString(input, inOutIdx, &length, inSz) >= 0);
        if (ret > 0) {
            /* Found Octet String */
            if (GetInt(&key->priv, input, inOutIdx, inSz) == 0) {
                WOLFSSL_MSG("Found Private Key");

                /* Compute public */
                ret = mp_exptmod(&key->g, &key->priv, &key->p, &key->pub);
            }
        } else {
            /* Don't use length from failed CheckBitString/GetOctetString */
            *inOutIdx = temp;
            ret = 0;
        }
    }
    #endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */
#endif /* WOLFSSL_DH_EXTRA */

    WOLFSSL_LEAVE("wc_DhKeyDecode", ret);

    return ret;
#else
#ifdef WOLFSSL_DH_EXTRA
    DECL_ASNGETDATA(dataASN, dhKeyPkcs8ASN_Length);
#else
    DECL_ASNGETDATA(dataASN, dhParamASN_Length);
#endif
    int ret = 0;

    /* Check input parameters are valid. */
    if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
        ret = BAD_FUNC_ARG;
    }

#ifdef WOLFSSL_DH_EXTRA
    ALLOC_ASNGETDATA(dataASN, dhKeyPkcs8ASN_Length, ret, key->heap);
#else
    ALLOC_ASNGETDATA(dataASN, dhParamASN_Length, ret, key->heap);
#endif

    if (ret == 0) {
        /* Initialize data and set mp_ints to hold p and g. */
        XMEMSET(dataASN, 0, sizeof(*dataASN) * dhParamASN_Length);
        GetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], &key->p);
        GetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], &key->g);
        /* Try simple PKCS #3 template. */
        ret = GetASN_Items(dhParamASN, dataASN, dhParamASN_Length, 1, input,
                           inOutIdx, inSz);
#ifdef WOLFSSL_DH_EXTRA
        if (ret != 0) {
            mp_free(&key->p);
            mp_free(&key->g);

            /* Initialize data and set mp_ints to hold p, g, q, priv and pub. */
            XMEMSET(dataASN, 0, sizeof(*dataASN) * dhKeyPkcs8ASN_Length);
            GetASN_ExpBuffer(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_OID],
                    keyDhOid, sizeof(keyDhOid));
            GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P], &key->p);
            GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G], &key->g);
            GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q], &key->q);
            GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT], &key->priv);
            GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT], &key->pub);
            /* Try PKCS #8 wrapped template. */
            ret = GetASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, 1,
                               input, inOutIdx, inSz);
            if (ret == 0) {
                /* VERSION only present in PKCS #8 private key structure */
                if ((dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT].length != 0) &&
                        (dataASN[DHKEYPKCS8ASN_IDX_VER].length == 0)) {
                    ret = ASN_PARSE_E;
                }
                else if ((dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT].length != 0) &&
                        (dataASN[DHKEYPKCS8ASN_IDX_VER].length != 0)) {
                    ret = ASN_PARSE_E;
                }
            }
            if ((ret == 0) && mp_iszero(&key->pub)) {
                ret = mp_exptmod(&key->g, &key->priv, &key->p, &key->pub);
            }
        }
#endif
    }

    FREE_ASNGETDATA(dataASN, key->heap);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

#ifdef WOLFSSL_DH_EXTRA

/* Export DH Key (private or public) */
int wc_DhKeyToDer(DhKey* key, byte* output, word32* outSz, int exportPriv)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int ret, privSz = 0, pubSz = 0;
    word32 keySz, idx, len, total;

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

    /* determine size */
    if (exportPriv) {
        /* octect string: priv */
        privSz = SetASNIntMP(&key->priv, -1, NULL);
        if (privSz < 0)
            return privSz;
        idx = 1 + SetLength((word32)privSz, NULL) +
            (word32)privSz; /* +1 for ASN_OCTET_STRING */
    }
    else {
        /* bit string: public */
        pubSz = SetASNIntMP(&key->pub, -1, NULL);
        if (pubSz < 0)
            return pubSz;
        idx = SetBitString((word32)pubSz, 0, NULL) + (word32)pubSz;
    }
    keySz = idx;

    /* DH Parameters sequence with P and G */
    total = 0;
    ret = wc_DhParamsToDer(key, NULL, &total);
    if (ret != LENGTH_ONLY_E)
        return ret;
    idx += total;

    /* object dhKeyAgreement 1.2.840.113549.1.3.1 */
    idx += (word32)SetObjectId(sizeof(keyDhOid), NULL);
    idx += (word32)sizeof(keyDhOid);
    len = idx - keySz;
    /* sequence - all but pub/priv */
    idx += SetSequence(len, NULL);
    if (exportPriv) {
        /* version: 0 (ASN_INTEGER, 0x01, 0x00) */
        idx += 3;
    }
    /* sequence */
    total = idx + SetSequence(idx, NULL);

    /* if no output, then just getting size */
    if (output == NULL) {
        *outSz = total;
        return LENGTH_ONLY_E;
    }

    /* make sure output fits in buffer */
    if (total > *outSz) {
        return BUFFER_E;
    }
    total = idx;

    /* sequence */
    idx = SetSequence(total, output);
    if (exportPriv) {
        /* version: 0 */
        idx += (word32)SetMyVersion(0, output + idx, 0);
    }
    /* sequence - all but pub/priv */
    idx += SetSequence(len, output + idx);
    /* object dhKeyAgreement 1.2.840.113549.1.3.1 */
    idx += (word32)SetObjectId(sizeof(keyDhOid), output + idx);
    XMEMCPY(output + idx, keyDhOid, sizeof(keyDhOid));
    idx += sizeof(keyDhOid);

    /* DH Parameters sequence with P and G */
    total = *outSz - idx;
    ret = wc_DhParamsToDer(key, output + idx, &total);
    if (ret < 0)
        return ret;
    idx += total;

    /* octect string: priv */
    if (exportPriv) {
        idx += (word32)SetOctetString((word32)privSz, output + idx);
        idx += (word32)SetASNIntMP(&key->priv, -1, output + idx);
    }
    else {
        /* bit string: public */
        idx += (word32)SetBitString((word32)pubSz, 0, output + idx);
        idx += (word32)SetASNIntMP(&key->pub, -1, output + idx);
    }
    *outSz = idx;

    return (int)idx;
#else
    ASNSetData dataASN[dhKeyPkcs8ASN_Length];
    int ret = 0;
    int sz;

    WOLFSSL_ENTER("wc_DhKeyToDer");

    XMEMSET(dataASN, 0, sizeof(dataASN));
    SetASN_Int8Bit(&dataASN[DHKEYPKCS8ASN_IDX_VER], 0);
    SetASN_OID(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_OID], DHk, oidKeyType);
    /* Set mp_int containing p and g. */
    SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P], &key->p);
    SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G], &key->g);
    dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q].noOut = 1;
    dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_J].noOut = 1;
    dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_VALID].noOut = 1;

    if (exportPriv) {
        SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT], &key->priv);
        dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_STR].noOut = 1;
        dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT].noOut = 1;
    }
    else {
        dataASN[DHKEYPKCS8ASN_IDX_VER].noOut = 1;
        dataASN[DHKEYPKCS8ASN_IDX_PKEY_STR].noOut = 1;
        dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT].noOut = 1;
        SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT], &key->pub);
    }

    /* Calculate the size of the DH parameters. */
    ret = SizeASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, &sz);
    if (output == NULL) {
        *outSz = (word32)sz;
        ret = LENGTH_ONLY_E;
    }
    /* Check buffer is big enough for encoding. */
    if ((ret == 0) && ((int)*outSz < sz)) {
        ret = BUFFER_E;
    }
    if (ret == 0) {
        /* Encode the DH parameters into buffer. */
        SetASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, output);
        /* Set the actual encoding size. */
        *outSz = (word32)sz;
        /* Return the actual encoding size. */
        ret = sz;
    }

    return ret;
#endif
}

int wc_DhPubKeyToDer(DhKey* key, byte* out, word32* outSz)
{
    return wc_DhKeyToDer(key, out, outSz, 0);
}
int wc_DhPrivKeyToDer(DhKey* key, byte* out, word32* outSz)
{
    return wc_DhKeyToDer(key, out, outSz, 1);
}


/* Convert DH key parameters to DER format, write to output (outSz)
 * If output is NULL then max expected size is set to outSz and LENGTH_ONLY_E is
 * returned.
 *
 * Note : static function due to redefinition complications with DhKey and FIPS
 * version 2 build.
 *
 * return bytes written on success */
int wc_DhParamsToDer(DhKey* key, byte* output, word32* outSz)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int ret;
    word32 idx, total;

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

    /* determine size */
    /* integer - g */
    ret = SetASNIntMP(&key->g, -1, NULL);
    if (ret < 0)
        return ret;
    idx = (word32)ret;
    /* integer - p */
    ret = SetASNIntMP(&key->p, -1, NULL);
    if (ret < 0)
        return ret;
    idx += (word32)ret;
    total = idx;
     /* sequence */
    idx += SetSequence(idx, NULL);

    if (output == NULL) {
        *outSz = idx;
        return LENGTH_ONLY_E;
    }
    /* make sure output fits in buffer */
    if (idx > *outSz) {
        return BUFFER_E;
    }


    /* write DH parameters */
    /* sequence - for P and G only */
    idx = SetSequence(total, output);
    /* integer - p */
    ret = SetASNIntMP(&key->p, -1, output + idx);
    if (ret < 0)
        return ret;
    idx += (word32)ret;
    /* integer - g */
    ret = SetASNIntMP(&key->g, -1, output + idx);
    if (ret < 0)
        return ret;
    idx += (word32)ret;
    *outSz = idx;

    return (int)idx;
#else
    ASNSetData dataASN[dhParamASN_Length];
    int ret = 0;
    int sz = 0;

    WOLFSSL_ENTER("wc_DhParamsToDer");

    if (key == NULL || outSz == NULL) {
        ret = BAD_FUNC_ARG;
    }

    if (ret == 0) {
        XMEMSET(dataASN, 0, sizeof(dataASN));
        /* Set mp_int containing p and g. */
        SetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], &key->p);
        SetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], &key->g);
        /* privateValueLength not encoded. */
        dataASN[DHPARAMASN_IDX_PRIVLEN].noOut = 1;

        /* Calculate the size of the DH parameters. */
        ret = SizeASN_Items(dhParamASN, dataASN, dhParamASN_Length, &sz);
    }
    if ((ret == 0) && (output == NULL)) {
        *outSz = (word32)sz;
        ret = LENGTH_ONLY_E;
    }
    /* Check buffer is big enough for encoding. */
    if ((ret == 0) && (*outSz < (word32)sz)) {
        ret = BUFFER_E;
    }
    if (ret == 0) {
        /* Encode the DH parameters into buffer. */
        SetASN_Items(dhParamASN, dataASN, dhParamASN_Length, output);
        /* Set the actual encoding size. */
        *outSz = (word32)sz;
        /* Return count of bytes written. */
        ret = sz;
    }

    return ret;
#endif
}

#endif /* WOLFSSL_DH_EXTRA */

/* Decode DH parameters.
 *
 * PKCS #3, 9 - DHParameter.
 * (Also in: RFC 2786, 3)
 *
 * @param [in]      input     Buffer holding BER encoded data.
 * @param [in, out] inOutIdx  On in, start of RSA public key.
 *                            On out, start of ASN.1 item after RSA public key.
 * @param [in]      inSz      Number of bytes in buffer.
 * @param [in, out] p         Buffer to hold prime.
 * @param [out]     pInOutSz  On in, size of buffer to hold prime in bytes.
 *                            On out, size of prime in bytes.
 * @param [in, out] g         Buffer to hold base.
 * @param [out]     gInOutSz  On in, size of buffer to hold base in bytes.
 *                            On out, size of base in bytes.
 * @return  0 on success.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_EXPECT_0_E when the INTEGER has the MSB set.
 */
int wc_DhParamsLoad(const byte* input, word32 inSz, byte* p, word32* pInOutSz,
                 byte* g, word32* gInOutSz)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx = 0;
    int    ret;
    int    length;

    if (GetSequence(input, &idx, &length, inSz) <= 0)
        return ASN_PARSE_E;

    ret = GetASNInt(input, &idx, &length, inSz);
    if (ret != 0)
        return ret;

    if (length <= (int)*pInOutSz) {
        XMEMCPY(p, &input[idx], (size_t)length);
        *pInOutSz = (word32)length;
    }
    else {
        return BUFFER_E;
    }
    idx += (word32)length;

    ret = GetASNInt(input, &idx, &length, inSz);
    if (ret != 0)
        return ret;

    if (length <= (int)*gInOutSz) {
        XMEMCPY(g, &input[idx], (size_t)length);
        *gInOutSz = (word32)length;
    }
    else {
        return BUFFER_E;
    }

    return 0;
#else
    DECL_ASNGETDATA(dataASN, dhParamASN_Length);
    word32 idx = 0;
    int ret = 0;

    /* Make sure pointers are valid before use. */
    if ((input == NULL) || (p == NULL) || (pInOutSz == NULL) || (g == NULL) ||
            (gInOutSz == NULL)) {
        ret = BAD_FUNC_ARG;
    }

    CALLOC_ASNGETDATA(dataASN, dhParamASN_Length, ret, NULL);

    if (ret == 0) {
        /* Set the buffers to copy p and g into. */
        GetASN_Buffer(&dataASN[DHPARAMASN_IDX_PRIME], p, pInOutSz);
        GetASN_Buffer(&dataASN[DHPARAMASN_IDX_BASE], g, gInOutSz);
        /* Decode the DH Parameters. */
        ret = GetASN_Items(dhParamASN, dataASN, dhParamASN_Length, 1, input,
                           &idx, inSz);
    }

    FREE_ASNGETDATA(dataASN, NULL);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}
#endif /* !NO_DH */


#ifndef NO_DSA

static mp_int* GetDsaInt(DsaKey* key, int idx)
{
    if (idx == 0)
        return &key->p;
    if (idx == 1)
        return &key->q;
    if (idx == 2)
        return &key->g;
    if (idx == 3)
        return &key->y;
    if (idx == 4)
        return &key->x;

    return NULL;
}

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for DSA public and private keys.
 * Public key: seq, p, q, g, y
 * Private key: seq, version, p, q, g, y, x
 * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
 */
static const ASNItem dsaKeyASN[] = {
/* SEQ */    { 0, ASN_SEQUENCE, 1, 1, 0 },
/* VER */        { 1, ASN_INTEGER, 0, 0, 0 },
/* P   */        { 1, ASN_INTEGER, 0, 0, 0 },
/* Q   */        { 1, ASN_INTEGER, 0, 0, 0 },
/* G   */        { 1, ASN_INTEGER, 0, 0, 0 },
/* Y   */        { 1, ASN_INTEGER, 0, 0, 0 },
/* X   */        { 1, ASN_INTEGER, 0, 0, 0 },
};
enum {
    DSAKEYASN_IDX_SEQ = 0,
    DSAKEYASN_IDX_VER,
    DSAKEYASN_IDX_P,
    DSAKEYASN_IDX_Q,
    DSAKEYASN_IDX_G,
    DSAKEYASN_IDX_Y,
    DSAKEYASN_IDX_X
};

/* Number of items in ASN.1 template for DSA private key. */
#define dsaKeyASN_Length (sizeof(dsaKeyASN) / sizeof(ASNItem))
/* Number of items in ASN.1 template for DSA public key. */
#define dsaPublicKeyASN_Length ((sizeof(dsaKeyASN) / sizeof(ASNItem)) - 2)

/* ASN.1 template for PublicKeyInfo with DSA.
 * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
 * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
 */
static const ASNItem dsaPubKeyASN[] = {
/* SEQ             */ { 0, ASN_SEQUENCE, 1, 1, 0 },
/* ALGOID_SEQ      */     { 1, ASN_SEQUENCE, 1, 1, 0 },
/* ALGOID_OID      */         { 2, ASN_OBJECT_ID, 0, 0, 0 },
/* ALGOID_PARAMS   */         { 2, ASN_SEQUENCE, 1, 1, 0 },
                                                   /* p */
/* ALGOID_PARAMS_P */             { 3, ASN_INTEGER, 0, 0, 0 },
                                                   /* q */
/* ALGOID_PARAMS_Q */             { 3, ASN_INTEGER, 0, 0, 0 },
                                                   /* g */
/* ALGOID_PARAMS_G */             { 3, ASN_INTEGER, 0, 0, 0 },
/* PUBKEY_STR      */     { 1, ASN_BIT_STRING, 0, 1, 1 },
                                               /* y */
/* PUBKEY_Y        */         { 2, ASN_INTEGER, 0, 0, 0 },
};
enum {
    DSAPUBKEYASN_IDX_SEQ = 0,
    DSAPUBKEYASN_IDX_ALGOID_SEQ,
    DSAPUBKEYASN_IDX_ALGOID_OID,
    DSAPUBKEYASN_IDX_ALGOID_PARAMS,
    DSAPUBKEYASN_IDX_ALGOID_PARAMS_P,
    DSAPUBKEYASN_IDX_ALGOID_PARAMS_Q,
    DSAPUBKEYASN_IDX_ALGOID_PARAMS_G,
    DSAPUBKEYASN_IDX_PUBKEY_STR,
    DSAPUBKEYASN_IDX_PUBKEY_Y
};

/* Number of items in ASN.1 template for PublicKeyInfo with DSA. */
#define dsaPubKeyASN_Length (sizeof(dsaPubKeyASN) / sizeof(ASNItem))
#endif /* WOLFSSL_ASN_TEMPLATE */

/* Decode DSA public key.
 *
 * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
 * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
 *
 * @param [in]      input     Buffer holding BER encoded data.
 * @param [in, out] inOutIdx  On in, start of DSA public key.
 *                            On out, start of ASN.1 item after DSA public key.
 * @param [in, out] key       DSA key object.
 * @param [in]      inSz      Number of bytes in buffer.
 * @return  0 on success.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
 * @return  ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
 *          non-zero length.
 * @return  ASN_BITSTR_E when the expected BIT_STRING tag is not found.
 * @return  ASN_UNKNOWN_OID_E when the OID cannot be verified.
 */
int wc_DsaPublicKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
                          word32 inSz)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int    length;
    int    ret = 0;
    word32 oid;
    word32 maxIdx;

    if (input == NULL || inOutIdx == NULL || key == NULL)
        return BAD_FUNC_ARG;

    if (GetSequence(input, inOutIdx, &length, inSz) < 0)
        return ASN_PARSE_E;

    maxIdx = (word32)(*inOutIdx + (word32)length);
    if (GetInt(&key->p,  input, inOutIdx, maxIdx) < 0 ||
        GetInt(&key->q,  input, inOutIdx, maxIdx) < 0 ||
        GetInt(&key->g,  input, inOutIdx, maxIdx) < 0 ||
        GetInt(&key->y,  input, inOutIdx, maxIdx) < 0 )
        ret = ASN_DH_KEY_E;

    if (ret != 0) {
        if (GetSequence(input, inOutIdx, &length, inSz) < 0)
            return ASN_PARSE_E;

        ret = GetObjectId(input, inOutIdx, &oid, oidIgnoreType, inSz);
        if (ret != 0)
            return ret;

        if (GetSequence(input, inOutIdx, &length, inSz) < 0)
            return ASN_PARSE_E;

        if (GetInt(&key->p,  input, inOutIdx, inSz) < 0 ||
            GetInt(&key->q,  input, inOutIdx, inSz) < 0 ||
            GetInt(&key->g,  input, inOutIdx, inSz) < 0)
            return ASN_DH_KEY_E;

        if (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) < 0)
            return ASN_PARSE_E;

        if (GetInt(&key->y,  input, inOutIdx, inSz) < 0 )
            return ASN_DH_KEY_E;

        ret = 0;
    }

    key->type = DSA_PUBLIC;
    return ret;
#else
    /* dsaPubKeyASN is longer than dsaPublicKeyASN. */
    DECL_ASNGETDATA(dataASN, dsaPubKeyASN_Length);
    int ret = 0;

    /* Validated parameters. */
    if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
        ret = BAD_FUNC_ARG;
    }

    ALLOC_ASNGETDATA(dataASN, dsaPubKeyASN_Length, ret, key->heap);

    if (ret == 0) {
        int i;

        /* Clear dynamic data items. */
        XMEMSET(dataASN, 0, sizeof(ASNGetData) * dsaPublicKeyASN_Length);
        /* seq
         *   p, q, g, y
         * Start DSA ints from DSAKEYASN_IDX_VER instead of DSAKEYASN_IDX_P */
        for (i = 0; i < DSA_INTS - 1; i++)
            GetASN_MP(&dataASN[(int)DSAKEYASN_IDX_VER + i], GetDsaInt(key, i));
        /* Parse as simple form. */
        ret = GetASN_Items(dsaKeyASN, dataASN, dsaPublicKeyASN_Length, 0, input,
                           inOutIdx, inSz);
        if (ret != 0) {
            /* Clear dynamic data items. */
            XMEMSET(dataASN, 0, sizeof(ASNGetData) * dsaPubKeyASN_Length);
            /* Set DSA OID to expect. */
            GetASN_ExpBuffer(&dataASN[DSAPUBKEYASN_IDX_ALGOID_OID],
                    keyDsaOid, sizeof(keyDsaOid));
            /* p, q, g */
            for (i = 0; i < DSA_INTS - 2; i++)
                GetASN_MP(&dataASN[(int)DSAPUBKEYASN_IDX_ALGOID_PARAMS_P + i],
                        GetDsaInt(key, i));
            /* y */
            GetASN_MP(&dataASN[DSAPUBKEYASN_IDX_PUBKEY_Y], GetDsaInt(key, i));
            /* Parse as SubjectPublicKeyInfo. */
            ret = GetASN_Items(dsaPubKeyASN, dataASN, dsaPubKeyASN_Length, 1,
                input, inOutIdx, inSz);
        }
    }

    if (ret == 0) {
        /* Data parsed - set type of key parsed. */
        key->type = DSA_PUBLIC;
    }

    FREE_ASNGETDATA(dataASN, key->heap);
    return ret;
#endif
}

int wc_DsaParamsDecode(const byte* input, word32* inOutIdx, DsaKey* key,
                        word32 inSz)
{
    int    length;
    word32 maxIdx;

    if (input == NULL || inOutIdx == NULL || key == NULL)
        return BAD_FUNC_ARG;

    if (GetSequence(input, inOutIdx, &length, inSz) < 0)
        return ASN_PARSE_E;

    maxIdx = (word32)(*inOutIdx + (word32)length);
    if (GetInt(&key->p, input, inOutIdx, maxIdx) < 0 ||
        GetInt(&key->q, input, inOutIdx, maxIdx) < 0 ||
        GetInt(&key->g, input, inOutIdx, maxIdx) < 0)
        return ASN_DH_KEY_E;

    return 0;
}


#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for a DSA key holding private key in an OCTET_STRING. */
static const ASNItem dsaKeyOctASN[] = {
/*  SEQ      */ { 0, ASN_SEQUENCE, 1, 1, 0 },
                /* p */
/*  P        */     { 1, ASN_INTEGER, 0, 0, 0 },
                /* q */
/*  Q        */     { 1, ASN_INTEGER, 0, 0, 0 },
                /* g */
/*  G        */     { 1, ASN_INTEGER, 0, 0, 0 },
                /* Private key */
/*  PKEY_STR */     { 1, ASN_OCTET_STRING, 0, 1, 0 },
                    /* x */
/*  X        */         { 2, ASN_INTEGER, 0, 0, 0 },
};
enum {
    DSAKEYOCTASN_IDX_SEQ = 0,
    DSAKEYOCTASN_IDX_P,
    DSAKEYOCTASN_IDX_Q,
    DSAKEYOCTASN_IDX_G,
    DSAKEYOCTASN_IDX_PKEY_STR,
    DSAKEYOCTASN_IDX_X
};

/* Number of items in ASN.1 template for a DSA key (OCTET_STRING version). */
#define dsaKeyOctASN_Length (sizeof(dsaKeyOctASN) / sizeof(ASNItem))
#endif

/* Decode DSA private key.
 *
 * @param [in]      input     Buffer holding BER encoded data.
 * @param [in, out] inOutIdx  On in, start of DSA public key.
 *                            On out, start of ASN.1 item after DSA public key.
 * @param [in, out] key       DSA key object.
 * @param [in]      inSz      Number of bytes in buffer.
 * @return  0 on success.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
 *          non-zero length.
 */
int wc_DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
                           word32 inSz)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int length, version, ret = 0, temp = 0;
    word32 algId = 0;

    /* Sanity checks on input */
    if (input == NULL || inOutIdx == NULL || key == NULL) {
        return BAD_FUNC_ARG;
    }

    /* if has pkcs8 header skip it */
    if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
        /* ignore error, did not have pkcs8 header */
    }

    if (GetSequence(input, inOutIdx, &length, inSz) < 0)
        return ASN_PARSE_E;

    temp = (int)*inOutIdx;

    /* Default case expects a certificate with OctetString but no version ID */
    ret = GetInt(&key->p, input, inOutIdx, inSz);
    if (ret < 0) {
        mp_clear(&key->p);
        ret = ASN_PARSE_E;
    }
    else {
        ret = GetInt(&key->q, input, inOutIdx, inSz);
        if (ret < 0) {
            mp_clear(&key->p);
            mp_clear(&key->q);
            ret = ASN_PARSE_E;
        }
        else {
            ret = GetInt(&key->g, input, inOutIdx, inSz);
            if (ret < 0) {
                mp_clear(&key->p);
                mp_clear(&key->q);
                mp_clear(&key->g);
                ret = ASN_PARSE_E;
            }
            else {
                ret = GetOctetString(input, inOutIdx, &length, inSz);
                if (ret < 0) {
                    mp_clear(&key->p);
                    mp_clear(&key->q);
                    mp_clear(&key->g);
                    ret = ASN_PARSE_E;
                }
                else {
                    ret = GetInt(&key->y, input, inOutIdx, inSz);
                    if (ret < 0) {
                        mp_clear(&key->p);
                        mp_clear(&key->q);
                        mp_clear(&key->g);
                        mp_clear(&key->y);
                        ret = ASN_PARSE_E;
                    }
                }
            }
        }
    }
    /* An alternate pass if default certificate fails parsing */
    if (ret == ASN_PARSE_E) {
        *inOutIdx = (word32)temp;
        if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
            return ASN_PARSE_E;

        if (GetInt(&key->p,  input, inOutIdx, inSz) < 0 ||
            GetInt(&key->q,  input, inOutIdx, inSz) < 0 ||
            GetInt(&key->g,  input, inOutIdx, inSz) < 0 ||
            GetInt(&key->y,  input, inOutIdx, inSz) < 0 ||
            GetInt(&key->x,  input, inOutIdx, inSz) < 0 )
            return ASN_DH_KEY_E;
    }

    key->type = DSA_PRIVATE;
    return 0;
#else
    /* dsaKeyASN is longer than dsaKeyOctASN. */
    DECL_ASNGETDATA(dataASN, dsaKeyASN_Length);
    int ret = 0;
    byte version = 0;

    /* Sanity checks on input */
    if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
        ret = BAD_FUNC_ARG;
    }

    CALLOC_ASNGETDATA(dataASN, dsaKeyASN_Length, ret, key->heap);

    if (ret == 0) {
        int i;

        /* Try dsaKeyOctASN */
        /* Initialize key data and set mp_ints for params */
        for (i = 0; i < DSA_INTS - 2; i++) {
            GetASN_MP(&dataASN[(int)DSAKEYOCTASN_IDX_P + i], GetDsaInt(key, i));
        }
        /* and priv */
        GetASN_MP(&dataASN[DSAKEYOCTASN_IDX_X], GetDsaInt(key, i));
        /* Try simple form. */
        ret = GetASN_Items(dsaKeyOctASN, dataASN, dsaKeyOctASN_Length, 1, input,
                           inOutIdx, inSz);

        if (ret != 0) {
            /* Try dsaKeyASN */
            XMEMSET(dataASN, 0, sizeof(*dataASN) * dsaKeyASN_Length);
            GetASN_Int8Bit(&dataASN[DSAKEYASN_IDX_VER], &version);
            for (i = 0; i < DSA_INTS; i++) {
                mp_int* n = GetDsaInt(key, i);
                mp_clear(n);
                GetASN_MP(&dataASN[(int)DSAKEYASN_IDX_P + i], n);
            }

            /* Try simple OCTET_STRING form. */
            ret = GetASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, 1, input,
                               inOutIdx, inSz);
        }
    }

    if (ret == 0) {
        /* Set the contents to be a private key. */
        key->type = DSA_PRIVATE;
    }

    FREE_ASNGETDATA(dataASN, key->heap);
    return ret;
#endif
}

#ifndef WOLFSSL_ASN_TEMPLATE
/* Release Tmp DSA resources */
static WC_INLINE void FreeTmpDsas(byte** tmps, void* heap, int ints)
{
    int i;

    for (i = 0; i < ints; i++)
        XFREE(tmps[i], heap, DYNAMIC_TYPE_DSA);

    (void)heap;
}
#endif /* !WOLFSSL_ASN_TEMPLATE */

#if !defined(HAVE_SELFTEST) && (defined(WOLFSSL_KEY_GEN) || \
        defined(WOLFSSL_CERT_GEN))
/* Encode a DSA public key into buffer.
 *
 * @param [out] output       Buffer to hold encoded data.
 * @param [in]  key          DSA key object.
 * @param [out] outLen       Length of buffer.
 * @param [out] with_header  Whether to encode in SubjectPublicKeyInfo block.
 * @return  Size of encoded data in bytes on success.
 * @return  BAD_FUNC_ARG when output or key is NULL, or buffer size is less
 *          than a minimal size (5 bytes), or buffer size is smaller than
 *          encoding size.
 * @return  MEMORY_E when dynamic memory allocation fails.
 */
int wc_SetDsaPublicKey(byte* output, DsaKey* key, int outLen, int with_header)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    /* p, g, q = DSA params, y = public exponent */
#ifdef WOLFSSL_SMALL_STACK
    byte* p = NULL;
    byte* g = NULL;
    byte* q = NULL;
    byte* y = NULL;
#else
    byte p[MAX_DSA_INT_SZ];
    byte g[MAX_DSA_INT_SZ];
    byte q[MAX_DSA_INT_SZ];
    byte y[MAX_DSA_INT_SZ];
#endif
    byte innerSeq[MAX_SEQ_SZ];
    byte outerSeq[MAX_SEQ_SZ];
    byte bitString[1 + MAX_LENGTH_SZ + 1];
    int pSz, gSz, qSz, ySz;
    word32 idx, innerSeqSz, outerSeqSz, bitStringSz = 0;
    WOLFSSL_ENTER("wc_SetDsaPublicKey");

    if (output == NULL || key == NULL || outLen < MAX_SEQ_SZ) {
        return BAD_FUNC_ARG;
    }

    /* p */
#ifdef WOLFSSL_SMALL_STACK
    p = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    if (p == NULL)
        return MEMORY_E;
#endif
    if ((pSz = SetASNIntMP(&key->p, MAX_DSA_INT_SZ, p)) < 0) {
        WOLFSSL_MSG("SetASNIntMP Error with p");
#ifdef WOLFSSL_SMALL_STACK
        XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
#endif
        return pSz;
    }

    /* q */
#ifdef WOLFSSL_SMALL_STACK
    q = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    if (q == NULL)
        return MEMORY_E;
#endif
    if ((qSz = SetASNIntMP(&key->q, MAX_DSA_INT_SZ, q)) < 0) {
        WOLFSSL_MSG("SetASNIntMP Error with q");
#ifdef WOLFSSL_SMALL_STACK
        XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
        XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
#endif
        return qSz;
    }

    /* g */
#ifdef WOLFSSL_SMALL_STACK
    g = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    if (g == NULL)
        return MEMORY_E;
#endif
    if ((gSz = SetASNIntMP(&key->g, MAX_DSA_INT_SZ, g)) < 0) {
        WOLFSSL_MSG("SetASNIntMP Error with g");
#ifdef WOLFSSL_SMALL_STACK
        XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
        XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
        XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
#endif
        return gSz;
    }

    /* y */
#ifdef WOLFSSL_SMALL_STACK
    y = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    if (y == NULL)
        return MEMORY_E;
#endif
    if ((ySz = SetASNIntMP(&key->y, MAX_DSA_INT_SZ, y)) < 0) {
        WOLFSSL_MSG("SetASNIntMP Error with y");
#ifdef WOLFSSL_SMALL_STACK
        XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
        XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
        XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
        XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
#endif
        return ySz;
    }

    if (with_header) {
        word32 algoSz;
#ifdef WOLFSSL_SMALL_STACK
        byte* algo = NULL;

        algo = (byte*)XMALLOC(MAX_ALGO_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
        if (algo == NULL) {
            XFREE(p,    key->heap, DYNAMIC_TYPE_TMP_BUFFER);
            XFREE(q,    key->heap, DYNAMIC_TYPE_TMP_BUFFER);
            XFREE(g,    key->heap, DYNAMIC_TYPE_TMP_BUFFER);
            XFREE(y,    key->heap, DYNAMIC_TYPE_TMP_BUFFER);
            return MEMORY_E;
        }
#else
        byte algo[MAX_ALGO_SZ];
#endif
        innerSeqSz  = SetSequence((word32)(pSz + qSz + gSz), innerSeq);
        algoSz = SetAlgoID(DSAk, algo, oidKeyType, 0);
        bitStringSz  = SetBitString((word32)ySz, 0, bitString);
        outerSeqSz = SetSequence(algoSz + innerSeqSz +
                                 (word32)(pSz + qSz + gSz), outerSeq);

        idx = SetSequence(algoSz + innerSeqSz + (word32)(pSz + qSz + gSz) +
                          bitStringSz + (word32)ySz + outerSeqSz, output);

        /* check output size */
        if ((idx + algoSz + bitStringSz + innerSeqSz +
             (word32)(pSz + qSz + gSz + ySz)) > (word32)outLen)
        {
            #ifdef WOLFSSL_SMALL_STACK
                XFREE(p,    key->heap, DYNAMIC_TYPE_TMP_BUFFER);
                XFREE(q,    key->heap, DYNAMIC_TYPE_TMP_BUFFER);
                XFREE(g,    key->heap, DYNAMIC_TYPE_TMP_BUFFER);
                XFREE(y,    key->heap, DYNAMIC_TYPE_TMP_BUFFER);
                XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
            #endif
            WOLFSSL_MSG("Error, output size smaller than outlen");
            return BUFFER_E;
        }

        /* outerSeq */
        XMEMCPY(output + idx, outerSeq, outerSeqSz);
        idx += outerSeqSz;
        /* algo */
        XMEMCPY(output + idx, algo, algoSz);
        idx += algoSz;
#ifdef WOLFSSL_SMALL_STACK
        XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
#endif
    } else {
        innerSeqSz  = SetSequence((word32)(pSz + qSz + gSz + ySz), innerSeq);

        /* check output size */
        if ((innerSeqSz + (word32)(pSz + qSz + gSz + ySz)) > (word32)outLen) {
    #ifdef WOLFSSL_SMALL_STACK
            XFREE(p,    key->heap, DYNAMIC_TYPE_TMP_BUFFER);
            XFREE(q,    key->heap, DYNAMIC_TYPE_TMP_BUFFER);
            XFREE(g,    key->heap, DYNAMIC_TYPE_TMP_BUFFER);
            XFREE(y,    key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    #endif
            WOLFSSL_MSG("Error, output size smaller than outlen");
            return BUFFER_E;
        }

        idx = 0;
    }

    /* innerSeq */
    XMEMCPY(output + idx, innerSeq, innerSeqSz);
    idx += innerSeqSz;
    /* p */
    XMEMCPY(output + idx, p, (size_t)pSz);
    idx += (word32)pSz;
    /* q */
    XMEMCPY(output + idx, q, (size_t)qSz);
    idx += (word32)qSz;
    /* g */
    XMEMCPY(output + idx, g, (size_t)gSz);
    idx += (word32)gSz;
    /* bit string */
    if (bitStringSz > 0) {
        XMEMCPY(output + idx, bitString, bitStringSz);
        idx += bitStringSz;
    }
    /* y */
    XMEMCPY(output + idx, y, (size_t)ySz);
    idx += (word32)ySz;

#ifdef WOLFSSL_SMALL_STACK
    XFREE(p,    key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    XFREE(q,    key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    XFREE(g,    key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    XFREE(y,    key->heap, DYNAMIC_TYPE_TMP_BUFFER);
#endif
    return (int)idx;
#else
    DECL_ASNSETDATA(dataASN, dsaPubKeyASN_Length);
    int ret = 0;
    int i;
    int sz = 0;
    const ASNItem *data = NULL;
    int count = 0;

    WOLFSSL_ENTER("wc_SetDsaPublicKey");

    if ((output == NULL) || (key == NULL) || (outLen < MAX_SEQ_SZ)) {
        ret = BAD_FUNC_ARG;
    }

    CALLOC_ASNSETDATA(dataASN, dsaPubKeyASN_Length, ret, key->heap);

    if (ret == 0) {
        if (with_header) {
            /* Using dsaPubKeyASN */
            data = dsaPubKeyASN;
            count = dsaPubKeyASN_Length;
            /* Set the algorithm OID to write out. */
            SetASN_OID(&dataASN[DSAPUBKEYASN_IDX_ALGOID_OID], DSAk, oidKeyType);
            /* Set the mp_ints to encode - parameters and public value. */
            for (i = 0; i < DSA_INTS - 2; i++) {
                SetASN_MP(&dataASN[(int)DSAPUBKEYASN_IDX_ALGOID_PARAMS_P + i],
                        GetDsaInt(key, i));
            }
            SetASN_MP(&dataASN[DSAPUBKEYASN_IDX_PUBKEY_Y], GetDsaInt(key, i));
        }
        else {
            /* Using dsaKeyASN */
            data = dsaKeyASN;
            count = dsaPublicKeyASN_Length;
            /* Set the mp_ints to encode - parameters and public value. */
            for (i = 0; i < DSA_INTS - 1; i++) {
                /* Move all DSA ints up one slot (ignore VERSION so now
                 * it means P) */
                SetASN_MP(&dataASN[(int)DSAKEYASN_IDX_VER + i],
                        GetDsaInt(key, i));
            }
        }
        ret = SizeASN_Items(data, dataASN, count, &sz);
    }
    /* Check buffer is big enough for encoding. */
    if ((ret == 0) && (sz > (int)outLen)) {
        ret = BAD_FUNC_ARG;
    }
    /* Encode the DSA public key into output buffer. */
    if (ret == 0) {
        ret = SetASN_Items(data, dataASN, count, output);
    }

    FREE_ASNSETDATA(dataASN, key->heap);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

/* Encode a DSA public key into buffer.
 *
 * @param [out] output       Buffer to hold encoded data.
 * @param [in]  key          DSA key object.
 * @param [out] outLen       Length of buffer.
 * @param [out] with_header  Whether to encode in SubjectPublicKeyInfo block.
 * @return  Size of encoded data in bytes on success.
 * @return  BAD_FUNC_ARG when output or key is NULL, or buffer size is less
 *          than a minimal size (5 bytes), or buffer size is smaller than
 *          encoding size.
 * @return  MEMORY_E when dynamic memory allocation fails.
 */
int wc_DsaKeyToPublicDer(DsaKey* key, byte* output, word32 inLen)
{
    return wc_SetDsaPublicKey(output, key, (int)inLen, 1);
}
#endif /* !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) */

static int DsaKeyIntsToDer(DsaKey* key, byte* output, word32* inLen,
                           int ints, int includeVersion)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 seqSz = 0, verSz = 0, intTotalLen = 0, outLen, j;
    word32 sizes[DSA_INTS];
    int    i, ret = 0;

    byte  seq[MAX_SEQ_SZ];
    byte  ver[MAX_VERSION_SZ];
    byte* tmps[DSA_INTS];

    if (ints > DSA_INTS || inLen == NULL)
        return BAD_FUNC_ARG;

    XMEMSET(sizes, 0, sizeof(sizes));
    for (i = 0; i < ints; i++)
        tmps[i] = NULL;

    /* write all big ints from key to DER tmps */
    for (i = 0; i < ints; i++) {
        int mpSz;
        mp_int* keyInt = GetDsaInt(key, i);
        word32 rawLen = (word32)mp_unsigned_bin_size(keyInt) + 1;

        tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
                                                              DYNAMIC_TYPE_DSA);
        if (tmps[i] == NULL) {
            ret = MEMORY_E;
            break;
        }

        mpSz = SetASNIntMP(keyInt, -1, tmps[i]);
        if (mpSz < 0) {
            ret = mpSz;
            break;
        }
        sizes[i] = (word32)mpSz;
        intTotalLen += (word32)mpSz;
    }

    if (ret != 0) {
        FreeTmpDsas(tmps, key->heap, ints);
        return ret;
    }

    /* make headers */
    if (includeVersion)
        verSz = (word32)SetMyVersion(0, ver, FALSE);
    seqSz = SetSequence(verSz + intTotalLen, seq);

    outLen = seqSz + verSz + intTotalLen;
    *inLen = outLen;
    if (output == NULL) {
        FreeTmpDsas(tmps, key->heap, ints);
        return LENGTH_ONLY_E;
    }
    if (outLen > *inLen) {
        FreeTmpDsas(tmps, key->heap, ints);
        return BAD_FUNC_ARG;
    }

    /* write to output */
    XMEMCPY(output, seq, seqSz);
    j = seqSz;
    if (includeVersion) {
        XMEMCPY(output + j, ver, verSz);
        j += verSz;
    }

    for (i = 0; i < ints; i++) {
        XMEMCPY(output + j, tmps[i], sizes[i]);
        j += sizes[i];
    }
    FreeTmpDsas(tmps, key->heap, ints);

    return (int)outLen;
#else
    DECL_ASNSETDATA(dataASN, dsaKeyASN_Length);
    int ret = 0;
    int sz = 0;

    (void)ints;

    if ((key == NULL) || (inLen == NULL)) {
        ret = BAD_FUNC_ARG;
    }
    if ((ret == 0) && (ints > DSA_INTS)) {
        ret = BAD_FUNC_ARG;
    }

    CALLOC_ASNSETDATA(dataASN, dsaKeyASN_Length, ret, key->heap);

    if (ret == 0) {
        int i;

        if (includeVersion) {
            /* Set the version. */
            SetASN_Int8Bit(&dataASN[DSAKEYASN_IDX_VER], 0);
        }
        else {
            dataASN[DSAKEYASN_IDX_VER].noOut = 1;
        }
        dataASN[DSAKEYASN_IDX_Y].noOut = mp_iszero(&key->y);
        dataASN[DSAKEYASN_IDX_X].noOut = mp_iszero(&key->x);
        /* Set the mp_ints to encode - params, public and private value. */
        for (i = 0; i < DSA_INTS; i++) {
            if (i < ints)
                SetASN_MP(&dataASN[(int)DSAKEYASN_IDX_P + i], GetDsaInt(key, i));
            else
                dataASN[(int)DSAKEYASN_IDX_P + i].noOut = 1;
        }
        /* Calculate size of the encoding. */
        ret = SizeASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, &sz);
    }
    if ((ret == 0) && (output == NULL)) {
        *inLen = (word32)sz;
        ret = LENGTH_ONLY_E;
    }
    /* Check buffer is big enough for encoding. */
    if ((ret == 0) && (sz > (int)*inLen)) {
        ret = BAD_FUNC_ARG;
    }
    if (ret == 0) {
        /* Encode the DSA private key into output buffer. */
        SetASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, output);
        /* Return the size of the encoding. */
        ret = sz;
    }

    FREE_ASNSETDATA(dataASN, key->heap);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

/* Encode a DSA private key into buffer.
 *
 * @param [in]  key          DSA key object.
 * @param [out] output       Buffer to hold encoded data.
 * @param [out] inLen        Length of buffer.
 * @return  Size of encoded data in bytes on success.
 * @return  BAD_FUNC_ARG when key or output is NULL, or key is not a private key
 *          or, buffer size is smaller than encoding size.
 * @return  MEMORY_E when dynamic memory allocation fails.
 */
int wc_DsaKeyToDer(DsaKey* key, byte* output, word32 inLen)
{
    if (!key || !output)
        return BAD_FUNC_ARG;

    if (key->type != DSA_PRIVATE)
        return BAD_FUNC_ARG;

    return DsaKeyIntsToDer(key, output, &inLen, DSA_INTS, 1);
}

/* Convert DsaKey parameters to DER format, write to output (inLen),
   return bytes written. Version is excluded to be compatible with
   OpenSSL d2i_DSAparams */
int wc_DsaKeyToParamsDer(DsaKey* key, byte* output, word32 inLen)
{
    if (!key || !output)
        return BAD_FUNC_ARG;

    return DsaKeyIntsToDer(key, output, &inLen, DSA_PARAM_INTS, 0);
}

/* This version of the function allows output to be NULL. In that case, the
   DsaKeyIntsToDer will return LENGTH_ONLY_E and the required output buffer
   size will be pointed to by inLen. */
int wc_DsaKeyToParamsDer_ex(DsaKey* key, byte* output, word32* inLen)
{
    if (!key || !inLen)
        return BAD_FUNC_ARG;

    return DsaKeyIntsToDer(key, output, inLen, DSA_PARAM_INTS, 0);
}

#endif /* NO_DSA */

/* Initialize decoded certificate object with buffer of DER encoding.
 *
 * @param [in, out] cert    Decoded certificate object.
 * @param [in]      source  Buffer containing DER encoded certificate.
 * @param [in]      inSz    Size of DER data in buffer in bytes.
 * @param [in]      heap    Dynamic memory hint.
 */
void InitDecodedCert(DecodedCert* cert,
                     const byte* source, word32 inSz, void* heap)
{
    InitDecodedCert_ex(cert, source, inSz, heap, INVALID_DEVID);
}


/* Initialize decoded certificate object with buffer of DER encoding.
 *
 * @param [in, out] cert    Decoded certificate object.
 * @param [in]      source  Buffer containing DER encoded certificate.
 * @param [in]      inSz    Size of DER data in buffer in bytes.
 * @param [in]      heap    Dynamic memory hint.
 * @param [in]      devId   Crypto callback ID to use.
 */
void InitDecodedCert_ex(DecodedCert* cert,
                     const byte* source, word32 inSz, void* heap, int devId)
{
    if (cert != NULL) {
        XMEMSET(cert, 0, sizeof(DecodedCert));

        cert->subjectCNEnc    = CTC_UTF8;
        cert->issuer[0]       = '\0';
        cert->subject[0]      = '\0';
        cert->source          = source;  /* don't own */
        cert->maxIdx          = inSz;    /* can't go over this index */
        cert->heap            = heap;
        cert->maxPathLen      = WOLFSSL_MAX_PATH_LEN;
    #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
        #ifdef WOLFSSL_CERT_NAME_ALL
        cert->subjectNEnc     = CTC_UTF8;
        cert->subjectIEnc     = CTC_UTF8;
        cert->subjectDNQEnc   = CTC_UTF8;
        cert->subjectGNEnc    = CTC_UTF8;
        #endif
        cert->subjectSNEnc    = CTC_UTF8;
        cert->subjectCEnc     = CTC_PRINTABLE;
        cert->subjectLEnc     = CTC_UTF8;
        cert->subjectSTEnc    = CTC_UTF8;
        cert->subjectOEnc     = CTC_UTF8;
        cert->subjectOUEnc    = CTC_UTF8;
    #ifdef WOLFSSL_HAVE_ISSUER_NAMES
        cert->issuerSNEnc    = CTC_UTF8;
        cert->issuerCEnc     = CTC_PRINTABLE;
        cert->issuerLEnc     = CTC_UTF8;
        cert->issuerSTEnc    = CTC_UTF8;
        cert->issuerOEnc     = CTC_UTF8;
        cert->issuerOUEnc    = CTC_UTF8;
    #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
    #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */

    #ifndef NO_CERTS
        InitSignatureCtx(&cert->sigCtx, heap, devId);
    #endif
    }
}

void wc_InitDecodedCert(DecodedCert* cert, const byte* source, word32 inSz,
                        void* heap)
{
    InitDecodedCert(cert, source, inSz, heap);
}

/* Free the alternative names object.
 *
 * Frees each linked list items and its name.
 *
 * @param [in, out] altNames  Alternative names.
 * @param [in]      heap      Dynamic memory hint.
 */
void FreeAltNames(DNS_entry* altNames, void* heap)
{
    (void)heap;

    while (altNames) {
        DNS_entry* tmp = altNames->next;

        XFREE(altNames->name, heap, DYNAMIC_TYPE_ALTNAME);
    #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
        XFREE(altNames->ipString, heap, DYNAMIC_TYPE_ALTNAME);
    #endif
        XFREE(altNames,       heap, DYNAMIC_TYPE_ALTNAME);
        altNames = tmp;
    }
}

/* malloc and initialize a new alt name structure */
DNS_entry* AltNameNew(void* heap)
{
    DNS_entry* ret;
    ret = (DNS_entry*)XMALLOC(sizeof(DNS_entry), heap, DYNAMIC_TYPE_ALTNAME);
    if (ret != NULL) {
        XMEMSET(ret, 0, sizeof(DNS_entry));
    }
    (void)heap;
    return ret;
}


#ifndef IGNORE_NAME_CONSTRAINTS

/* Free the subtree names object.
 *
 * Frees each linked list items and its name.
 *
 * @param [in, out] names  Subtree names.
 * @param [in]      heap   Dynamic memory hint.
 */
void FreeNameSubtrees(Base_entry* names, void* heap)
{
    (void)heap;

    while (names) {
        Base_entry* tmp = names->next;

        XFREE(names->name, heap, DYNAMIC_TYPE_ALTNAME);
        XFREE(names,       heap, DYNAMIC_TYPE_ALTNAME);
        names = tmp;
    }
}

#endif /* IGNORE_NAME_CONSTRAINTS */

/* Free the decoded cert object's dynamic data.
 *
 * @param [in, out] cert  Decoded certificate object.
 */
void FreeDecodedCert(DecodedCert* cert)
{
    if (cert == NULL)
        return;
    if (cert->subjectCNStored == 1) {
        XFREE(cert->subjectCN, cert->heap, DYNAMIC_TYPE_SUBJECT_CN);
    }
    if (cert->pubKeyStored == 1) {
        XFREE((void*)cert->publicKey, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
    }
    if (cert->weOwnAltNames && cert->altNames)
        FreeAltNames(cert->altNames, cert->heap);
#ifndef IGNORE_NAME_CONSTRAINTS
    if (cert->altEmailNames)
        FreeAltNames(cert->altEmailNames, cert->heap);
    if (cert->altDirNames)
        FreeAltNames(cert->altDirNames, cert->heap);
    if (cert->permittedNames)
        FreeNameSubtrees(cert->permittedNames, cert->heap);
    if (cert->excludedNames)
        FreeNameSubtrees(cert->excludedNames, cert->heap);
#endif /* IGNORE_NAME_CONSTRAINTS */
#ifdef WOLFSSL_SEP
    XFREE(cert->deviceType, cert->heap, DYNAMIC_TYPE_X509_EXT);
    XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
    XFREE(cert->hwSerialNum, cert->heap, DYNAMIC_TYPE_X509_EXT);
#endif /* WOLFSSL_SEP */
#ifdef WOLFSSL_X509_NAME_AVAILABLE
    if (cert->issuerName != NULL)
        wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->issuerName);
    if (cert->subjectName != NULL)
        wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->subjectName);
#endif /* WOLFSSL_X509_NAME_AVAILABLE */
#if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
    if (cert->sce_tsip_encRsaKeyIdx != NULL)
        XFREE(cert->sce_tsip_encRsaKeyIdx, cert->heap, DYNAMIC_TYPE_RSA);
#endif
#ifndef NO_CERTS
    FreeSignatureCtx(&cert->sigCtx);
#endif
}

void wc_FreeDecodedCert(DecodedCert* cert)
{
    FreeDecodedCert(cert);
}

#ifndef WOLFSSL_ASN_TEMPLATE
static int GetCertHeader(DecodedCert* cert)
{
    int ret = 0, len;

    if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
        return ASN_PARSE_E;

    /* Reset the max index for the size indicated in the outer wrapper. */
    cert->maxIdx = (word32)len + cert->srcIdx;
    cert->certBegin = cert->srcIdx;

    if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
        return ASN_PARSE_E;

    cert->sigIndex = (word32)len + cert->srcIdx;
    if (cert->sigIndex > cert->maxIdx)
        return ASN_PARSE_E;

    if (GetExplicitVersion(cert->source, &cert->srcIdx, &cert->version,
                                                            cert->sigIndex) < 0)
        return ASN_PARSE_E;

    if (wc_GetSerialNumber(cert->source, &cert->srcIdx, cert->serial,
                                           &cert->serialSz, cert->sigIndex) < 0)
        return ASN_PARSE_E;

    return ret;
}
#endif

#if defined(HAVE_ED25519) || defined(HAVE_ED448) || (defined(HAVE_PQC) && \
    defined(HAVE_LIBOQS))
/* Store the key data under the BIT_STRING in dynamicly allocated data.
 *
 * @param [in, out] cert    Certificate object.
 * @param [in]      source  Buffer containing encoded key.
 * @param [in, out] srcIdx  On in, start of key data.
 *                          On out, start of element after key data.
 * @param [in]      maxIdx  Maximum index of certificate data.
 */
static int StoreKey(DecodedCert* cert, const byte* source, word32* srcIdx,
                    word32 maxIdx)
{
    int ret;
    int length;
    byte* publicKey;

    ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
    if (ret == 0) {
    #ifdef HAVE_OCSP
        ret = CalcHashId(source + *srcIdx, (word32)length,
                         cert->subjectKeyHash);
    }
    if (ret == 0) {
    #endif
        publicKey = (byte*)XMALLOC((size_t)length, cert->heap,
                                   DYNAMIC_TYPE_PUBLIC_KEY);
        if (publicKey == NULL) {
            ret = MEMORY_E;
        }
        else {
            XMEMCPY(publicKey, &source[*srcIdx], (size_t)length);
            cert->publicKey = publicKey;
            cert->pubKeyStored = 1;
            cert->pubKeySize   = (word32)length;

            *srcIdx += (word32)length;
        }
    }

    return ret;
}
#endif /* HAVE_ED25519 || HAVE_ED448 */

#if !defined(NO_RSA)
#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for header before RSA key in certificate. */
static const ASNItem rsaCertKeyASN[] = {
/* STR */ { 0, ASN_BIT_STRING, 0, 1, 0 },
/* SEQ */     { 1, ASN_SEQUENCE, 1, 0, 0 },
};
enum {
    RSACERTKEYASN_IDX_STR = 0,
    RSACERTKEYASN_IDX_SEQ
};

/* Number of items in ASN.1 template for header before RSA key in cert. */
#define rsaCertKeyASN_Length (sizeof(rsaCertKeyASN) / sizeof(ASNItem))
#endif

/* Store RSA key pointer and length in certificate object.
 *
 * @param [in, out] cert    Certificate object.
 * @param [in]      source  Buffer containing encoded key.
 * @param [in, out] srcIdx  On in, start of RSA key data.
 *                          On out, start of element after RSA key data.
 * @param [in]      maxIdx  Maximum index of key data.
 * @return  0 on success.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_BITSTR_E when the expected BIT_STRING tag is not found.
 * @return  ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
 *          non-zero length.
 */
static int StoreRsaKey(DecodedCert* cert, const byte* source, word32* srcIdx,
                       word32 maxIdx)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int    length;
    int    pubLen;
    word32 pubIdx;

    if (CheckBitString(source, srcIdx, &pubLen, maxIdx, 1, NULL) != 0)
        return ASN_PARSE_E;
    pubIdx = *srcIdx;

    if (GetSequence(source, srcIdx, &length, pubIdx + (word32)pubLen) < 0)
        return ASN_PARSE_E;

#if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
    cert->sigCtx.CertAtt.pubkey_n_start =
            cert->sigCtx.CertAtt.pubkey_e_start = pubIdx;
#endif
    cert->pubKeySize = (word32)pubLen;
    cert->publicKey = source + pubIdx;
#ifdef WOLFSSL_MAXQ10XX_TLS
    cert->publicKeyIndex = pubIdx;
#endif
    *srcIdx += (word32)length;

#ifdef HAVE_OCSP
    return CalcHashId(cert->publicKey, cert->pubKeySize, cert->subjectKeyHash);
#else
    return 0;
#endif
#else
    ASNGetData dataASN[rsaCertKeyASN_Length];
    int ret;

    /* No dynamic data. */
    XMEMSET(dataASN, 0, sizeof(dataASN));
    /* Decode the header before the key data. */
    ret = GetASN_Items(rsaCertKeyASN, dataASN, rsaCertKeyASN_Length, 1, source,
                       srcIdx, maxIdx);
    if (ret == 0) {
        /* Store the pointer and length in certificate object starting at
         * SEQUENCE. */
        GetASN_GetConstRef(&dataASN[RSACERTKEYASN_IDX_STR],
                &cert->publicKey, &cert->pubKeySize);

#ifdef WOLFSSL_MAXQ10XX_TLS
    cert->publicKeyIndex = dataASN[RSACERTKEYASN_IDX_SEQ].offset;
#endif

    #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
        /* Start of SEQUENCE. */
        cert->sigCtx.CertAtt.pubkey_n_start =
            cert->sigCtx.CertAtt.pubkey_e_start = dataASN[RSACERTKEYASN_IDX_SEQ].offset;
    #endif
    #ifdef HAVE_OCSP
        /* Calculate the hash of the public key for OCSP. */
        ret = CalcHashId(cert->publicKey, cert->pubKeySize,
                         cert->subjectKeyHash);
    #endif
    }

    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}
#endif /* !NO_RSA */

#ifdef HAVE_ECC

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for header before ECC key in certificate. */
static const ASNItem eccCertKeyASN[] = {
/* OID        */     { 1, ASN_OBJECT_ID, 0, 0, 2 },
                            /* Algo parameters */
/* PARAMS     */     { 1, ASN_SEQUENCE, 1, 0, 2 },
                            /* Subject public key */
/* SUBJPUBKEY */ { 0, ASN_BIT_STRING, 0, 0, 0 },
};
enum {
    ECCCERTKEYASN_IDX_OID = 0,
    ECCCERTKEYASN_IDX_PARAMS,
    ECCCERTKEYASN_IDX_SUBJPUBKEY
};

/* Number of items in ASN.1 template for header before ECC key in cert. */
#define eccCertKeyASN_Length (sizeof(eccCertKeyASN) / sizeof(ASNItem))
#endif /* WOLFSSL_ASN_TEMPLATE */

/* Store public ECC key in certificate object.
 *
 * Parse parameters and store public key data.
 *
 * @param [in, out] cert       Certificate object.
 * @param [in]      source     Buffer containing encoded key.
 * @param [in, out] srcIdx     On in, start of ECC key data.
 *                             On out, start of element after ECC key data.
 * @param [in]      maxIdx     Maximum index of key data.
 * @param [in]      pubKey     Buffer holding encoded public key.
 * @param [in]      pubKeyLen  Length of encoded public key in bytes.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when pubKey is NULL.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_UNKNOWN_OID_E when the OID cannot be verified.
 * @return  ASN_BITSTR_E when the expected BIT_STRING tag is not found.
 * @return  ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
 *          non-zero length.
 * @return  ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
 */
static int StoreEccKey(DecodedCert* cert, const byte* source, word32* srcIdx,
                       word32 maxIdx, const byte* pubKey, word32 pubKeyLen)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int ret;
    word32 localIdx;
    byte* publicKey;
    byte  tag;
    int length;

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

    localIdx = *srcIdx;
    if (GetASNTag(source, &localIdx, &tag, maxIdx) < 0)
        return ASN_PARSE_E;

    if (tag != (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
        if (GetObjectId(source, srcIdx, &cert->pkCurveOID, oidCurveType,
                                                                    maxIdx) < 0)
            return ASN_PARSE_E;

        if ((ret = CheckCurve(cert->pkCurveOID)) < 0)
            return ECC_CURVE_OID_E;

    #if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_TSIP_TLS)
        cert->sigCtx.CertAtt.curve_id = ret;
    #else
        (void)ret;
    #endif
        /* key header */
        ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
        if (ret != 0)
            return ret;
    #if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_TSIP_TLS)
        cert->sigCtx.CertAtt.pubkey_n_start =
                cert->sigCtx.CertAtt.pubkey_e_start = (*srcIdx + 1);
        cert->sigCtx.CertAtt.pubkey_n_len = ((length - 1) >> 1);
        cert->sigCtx.CertAtt.pubkey_e_start +=
                cert->sigCtx.CertAtt.pubkey_n_len;
        cert->sigCtx.CertAtt.pubkey_e_len   =
                cert->sigCtx.CertAtt.pubkey_n_len;
    #endif
    #ifdef WOLFSSL_MAXQ10XX_TLS
        cert->publicKeyIndex = *srcIdx + 1;
    #endif

    #ifdef HAVE_OCSP
        ret = CalcHashId(source + *srcIdx, (word32)length,
                         cert->subjectKeyHash);
        if (ret != 0)
            return ret;
    #endif
        *srcIdx += (word32)length;
    }

    publicKey = (byte*)XMALLOC(pubKeyLen, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
    if (publicKey == NULL)
        return MEMORY_E;
    XMEMCPY(publicKey, pubKey, pubKeyLen);
    cert->publicKey = publicKey;
    cert->pubKeyStored = 1;
    cert->pubKeySize   = pubKeyLen;

    return 0;
#else
    int ret = 0;
    DECL_ASNGETDATA(dataASN, eccCertKeyASN_Length);
    byte* publicKey;

    /* Validate parameters. */
    if (pubKey == NULL) {
        ret = BAD_FUNC_ARG;
    }

    /* Clear dynamic data and check OID is a curve. */
    CALLOC_ASNGETDATA(dataASN, eccCertKeyASN_Length, ret, cert->heap);
    if (ret == 0) {
        GetASN_OID(&dataASN[ECCCERTKEYASN_IDX_OID], oidCurveType);
        /* Parse ECC public key header. */
        ret = GetASN_Items(eccCertKeyASN, dataASN, eccCertKeyASN_Length, 1,
                source, srcIdx, maxIdx);
    }
    if (ret == 0) {
        if (dataASN[ECCCERTKEYASN_IDX_OID].tag != 0) {
            /* Store curve OID. */
            cert->pkCurveOID = dataASN[ECCCERTKEYASN_IDX_OID].data.oid.sum;
        }
        /* Ignore explicit parameters. */

    #ifdef WOLFSSL_MAXQ10XX_TLS
        cert->publicKeyIndex =
            GetASNItem_DataIdx(dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY], source)
            + 1;
    #endif

    #ifdef HAVE_OCSP
        /* Calculate the hash of the subject public key for OCSP. */
        ret = CalcHashId(dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY].data.ref.data,
                         dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY].data.ref.length,
                         cert->subjectKeyHash);
    }
    if (ret == 0) {
    #endif
        /* Store public key data length. */
        cert->pubKeySize = pubKeyLen;
        /* Must allocated space for key.
         * Don't memcpy into constant pointer so use temp. */
        publicKey = (byte*)XMALLOC(cert->pubKeySize, cert->heap,
                                   DYNAMIC_TYPE_PUBLIC_KEY);
        if (publicKey == NULL) {
            ret = MEMORY_E;
        }
        else {
            /* Copy in whole public key and store pointer. */
            XMEMCPY(publicKey, pubKey, cert->pubKeySize);
            cert->publicKey = publicKey;
            /* Indicate publicKey needs to be freed. */
            cert->pubKeyStored = 1;
        }
    }
    FREE_ASNGETDATA(dataASN, cert->heap);

    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}
#endif /* HAVE_ECC */

#if !defined(NO_DSA)
#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for DSA key in certificate.
 * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
 * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
 */
static const ASNItem dsaCertKeyASN[] = {
/*  0 */        { 1, ASN_SEQUENCE, 1, 1, 0 },
/*  1 */            { 2, ASN_INTEGER, 0, 0, 0 },
/*  2 */            { 2, ASN_INTEGER, 0, 0, 0 },
/*  3 */            { 2, ASN_INTEGER, 0, 0, 0 },
/*  4 */    { 0, ASN_BIT_STRING, 0, 1, 0 },
/*  5 */        { 1, ASN_INTEGER, 0, 0, 0 },
};

/* Number of items in ASN.1 template for DSA key in certificate. */
#define dsaCertKeyASN_Length (sizeof(dsaCertKeyASN) / sizeof(ASNItem))
#endif /* WOLFSSL_ASN_TEMPLATE */

/* Parse DSA parameters to ensure valid.
 *
 * @param [in]      source  Buffer containing encoded key.
 * @param [in, out] srcIdx  On in, start of DSA key data.
 *                          On out, start of element after DSA key data.
 * @param [in]      maxIdx  Maximum index of key data.
 * @param [in]      heap    Dynamic memory hint.
 * @return  0 on success.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_BITSTR_E when the expected BIT_STRING tag is not found.
 * @return  ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
 *          non-zero length.
 */
static int ParseDsaKey(const byte* source, word32* srcIdx, word32 maxIdx,
                       void* heap)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int ret;
    int length;

    (void)heap;

    ret = GetSequence(source, srcIdx, &length, maxIdx);
    if (ret < 0)
        return ret;

    ret = SkipInt(source, srcIdx, maxIdx);
    if (ret != 0)
        return ret;
    ret = SkipInt(source, srcIdx, maxIdx);
    if (ret != 0)
        return ret;
    ret = SkipInt(source, srcIdx, maxIdx);
    if (ret != 0)
        return ret;

    ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
    if (ret != 0)
        return ret;

    ret = GetASNInt(source, srcIdx, &length, maxIdx);
    if (ret != 0)
        return ASN_PARSE_E;

    *srcIdx += (word32)length;

    return 0;
#else
    DECL_ASNGETDATA(dataASN, dsaCertKeyASN_Length);
    int ret = 0;

    (void)heap;

    CALLOC_ASNGETDATA(dataASN, dsaCertKeyASN_Length, ret, heap);
    if (ret == 0) {
        /* Parse the DSA key data to ensure valid. */
        ret = GetASN_Items(dsaCertKeyASN, dataASN, dsaCertKeyASN_Length, 1,
                           source, srcIdx, maxIdx);
    }

    FREE_ASNGETDATA(dataASN, heap);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}
#endif /* !NO_DSA */

/* Decode the SubjectPublicKeyInfo block in a certificate.
 *
 * Stores the public key in fields of the certificate object.
 * Validates the BER/DER items and does not store in a key object.
 *
 * @param [in, out] cert      Decoded certificate oject.
 * @param [in]      source    BER/DER encoded SubjectPublicKeyInfo block.
 * @param [in, out] inOutIdx  On in, start of public key.
 *                            On out, start of ASN.1 item after public key.
 * @param [in]      maxIdx    Maximum index of key data.
 * @return  0 on success.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 */
static int GetCertKey(DecodedCert* cert, const byte* source, word32* inOutIdx,
                      word32 maxIdx)
{
    word32 srcIdx = *inOutIdx;
#if defined(HAVE_ECC) || !defined(NO_DSA)
    int pubLen;
#endif
#if defined(HAVE_ECC) || !defined(NO_DSA)
    int pubIdx = (int)srcIdx;
#endif
    int ret = 0;
    int length;

    /* Validate paramaters. */
    if (source == NULL) {
        return ASN_PARSE_E;
    }

#ifndef WOLFSSL_ASN_TEMPLATE
    if (GetSequence(source, &srcIdx, &length, maxIdx) < 0)
#else
    /* Get SEQUENCE and expect all data to be accounted for. */
    if (GetASN_Sequence(source, &srcIdx, &length, maxIdx, 1) != 0)
#endif
    {
        return ASN_PARSE_E;
    }

#if defined(HAVE_ECC) || !defined(NO_DSA)
    pubLen = (int)srcIdx - pubIdx + length;
#endif
    maxIdx = srcIdx + (word32)length;

    /* Decode the algorithm identifier for the key. */
    if (GetAlgoId(source, &srcIdx, &cert->keyOID, oidKeyType, maxIdx) < 0) {
        return ASN_PARSE_E;
    }

    (void)length;

    /* Parse each type of public key. */
    switch (cert->keyOID) {
#ifndef NO_RSA
    #ifdef WC_RSA_PSS
        case RSAPSSk:
            if (srcIdx != maxIdx &&
                          source[srcIdx] == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
                word32 seqIdx = srcIdx;
                int seqLen;
                /* Not set when -1. */
                enum wc_HashType hash = WC_HASH_TYPE_NONE;
                int mgf = -1;
                int saltLen = 0;
                /* Defaults for sig algorithm parameters. */
                enum wc_HashType sigHash = WC_HASH_TYPE_SHA;
                int sigMgf = WC_MGF1SHA1;
                int sigSaltLen = 20;

                if (GetSequence(source, &srcIdx, &seqLen, maxIdx) < 0) {
                    return ASN_PARSE_E;
                }
                /* Get the pubic key parameters. */
                ret = DecodeRsaPssParams(source + seqIdx,
                    (word32)seqLen + srcIdx - seqIdx, &hash, &mgf, &saltLen);
                if (ret != 0) {
                    return ASN_PARSE_E;
                }
                /* Get the signature parameters. */
                ret = DecodeRsaPssParams(source + cert->sigParamsIndex,
                    cert->sigParamsLength, &sigHash, &sigMgf, &sigSaltLen);
                if (ret != 0) {
                    return ASN_PARSE_E;
                }
                /* Validated signature params match public key params. */
                if (hash != WC_HASH_TYPE_NONE && hash != sigHash) {
                    WOLFSSL_MSG("RSA PSS: hash not matching signature hash");
                    return ASN_PARSE_E;
                }
                if (mgf != -1 && mgf != sigMgf) {
                    WOLFSSL_MSG("RSA PSS: MGF not matching signature MGF");
                    return ASN_PARSE_E;
                }
                if (saltLen > sigSaltLen) {
                    WOLFSSL_MSG("RSA PSS: sig salt length too small");
                    return ASN_PARSE_E;
                }
                srcIdx += (word32)seqLen;
            }
            FALL_THROUGH;
    #endif /* WC_RSA_PSS */
        case RSAk:
            ret = StoreRsaKey(cert, source, &srcIdx, maxIdx);
            break;
#endif /* NO_RSA */
    #ifdef HAVE_ECC
        case ECDSAk:
            ret = StoreEccKey(cert, source, &srcIdx, maxIdx, source + pubIdx,
                              (word32)pubLen);
            break;
    #endif /* HAVE_ECC */
    #ifdef HAVE_ED25519
        case ED25519k:
            cert->pkCurveOID = ED25519k;
            ret = StoreKey(cert, source, &srcIdx, maxIdx);
            break;
    #endif /* HAVE_ED25519 */
    #ifdef HAVE_ED448
        case ED448k:
            cert->pkCurveOID = ED448k;
            ret = StoreKey(cert, source, &srcIdx, maxIdx);
            break;
    #endif /* HAVE_ED448 */
    #if defined(HAVE_PQC) && defined(HAVE_LIBOQS)
    #ifdef HAVE_FALCON
        case FALCON_LEVEL1k:
            cert->pkCurveOID = FALCON_LEVEL1k;
            ret = StoreKey(cert, source, &srcIdx, maxIdx);
            break;
        case FALCON_LEVEL5k:
            cert->pkCurveOID = FALCON_LEVEL5k;
            ret = StoreKey(cert, source, &srcIdx, maxIdx);
            break;
    #endif /* HAVE_FALCON */
    #ifdef HAVE_DILITHIUM
        case DILITHIUM_LEVEL2k:
            cert->pkCurveOID = DILITHIUM_LEVEL2k;
            ret = StoreKey(cert, source, &srcIdx, maxIdx);
            break;
        case DILITHIUM_LEVEL3k:
            cert->pkCurveOID = DILITHIUM_LEVEL3k;
            ret = StoreKey(cert, source, &srcIdx, maxIdx);
            break;
        case DILITHIUM_LEVEL5k:
            cert->pkCurveOID = DILITHIUM_LEVEL5k;
            ret = StoreKey(cert, source, &srcIdx, maxIdx);
            break;
    #endif /* HAVE_DILITHIUM */
    #ifdef HAVE_SPHINCS
        case SPHINCS_FAST_LEVEL1k:
            cert->pkCurveOID = SPHINCS_FAST_LEVEL1k;
            ret = StoreKey(cert, source, &srcIdx, maxIdx);
            break;
        case SPHINCS_FAST_LEVEL3k:
            cert->pkCurveOID = SPHINCS_FAST_LEVEL3k;
            ret = StoreKey(cert, source, &srcIdx, maxIdx);
            break;
        case SPHINCS_FAST_LEVEL5k:
            cert->pkCurveOID = SPHINCS_FAST_LEVEL5k;
            ret = StoreKey(cert, source, &srcIdx, maxIdx);
            break;
        case SPHINCS_SMALL_LEVEL1k:
            cert->pkCurveOID = SPHINCS_SMALL_LEVEL1k;
            ret = StoreKey(cert, source, &srcIdx, maxIdx);
            break;
        case SPHINCS_SMALL_LEVEL3k:
            cert->pkCurveOID = SPHINCS_SMALL_LEVEL3k;
            ret = StoreKey(cert, source, &srcIdx, maxIdx);
            break;
        case SPHINCS_SMALL_LEVEL5k:
            cert->pkCurveOID = SPHINCS_SMALL_LEVEL5k;
            ret = StoreKey(cert, source, &srcIdx, maxIdx);
            break;
    #endif /* HAVE_SPHINCS */
    #endif /* HAVE_PQC */
    #ifndef NO_DSA
        case DSAk:
            cert->publicKey = source + pubIdx;
            cert->pubKeySize = (word32)pubLen;
            ret = ParseDsaKey(source, &srcIdx, maxIdx, cert->heap);
            break;
    #endif /* NO_DSA */
        default:
            WOLFSSL_MSG("Unknown or not compiled in key OID");
            WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
            ret = ASN_UNKNOWN_OID_E;
    }

    /* Return index after public key. */
    *inOutIdx = srcIdx;

    /* Return error code. */
    return ret;
}

/* Calculate hash of the id using the SHA-1 or SHA-256.
 *
 * @param [in]  data  Data to hash.
 * @param [in]  len   Length of data to hash.
 * @param [out] hash  Buffer to hold hash.
 * @return  0 on success.
 * @return  MEMORY_E when dynamic memory allocation fails.
 */
int CalcHashId(const byte* data, word32 len, byte* hash)
{
    int ret;

#if defined(NO_SHA) || (!defined(NO_SHA256) && defined(WC_ASN_HASH_SHA256))
    ret = wc_Sha256Hash(data, len, hash);
#elif !defined(NO_SHA)
    ret = wc_ShaHash(data, len, hash);
#else
    ret = NOT_COMPILED_IN;
    (void)data;
    (void)len;
    (void)hash;
#endif

    return ret;
}

#ifndef NO_CERTS
/* Get the hash of the id using the SHA-1 or SHA-256.
 *
 * If the id is not the length of the hash, then hash it.
 *
 * @param [in]  id    Id to get hash for.
 * @param [in]  len   Length of id in bytes.
 * @param [out] hash  Buffer to hold hash.
 * @return  0 on success.
 * @return  MEMORY_E when dynamic memory allocation fails.
 */
static int GetHashId(const byte* id, int length, byte* hash)
{
    int ret;

    if (length == KEYID_SIZE) {
        XMEMCPY(hash, id, (size_t)length);
        ret = 0;
    }
    else {
        ret = CalcHashId(id, (word32)length, hash);
    }

    return ret;
}
#endif /* !NO_CERTS */

#ifdef WOLFSSL_ASN_TEMPLATE
/* Id for email address. */
#define ASN_EMAIL     0x100
/* Id for domain component. */
#define ASN_DC        0x102
/* Id for jurisdiction country. */
#define ASN_JURIS_C   0x203
/* Id for jurisdiction state. */
#define ASN_JURIS_ST  0x202

/* Set the string for a name component into the subject name. */
#define SetCertNameSubject(cert, id, val) \
    *((char**)(((byte *)(cert)) + certNameSubject[(id) - 3].data)) = (val)
/* Set the string length for a name component into the subject name. */
#define SetCertNameSubjectLen(cert, id, val) \
    *((int*)(((byte *)(cert)) + certNameSubject[(id) - 3].len)) = (int)(val)
/* Set the encoding for a name component into the subject name. */
#define SetCertNameSubjectEnc(cert, id, val) \
    *((byte*)(((byte *)(cert)) + certNameSubject[(id) - 3].enc)) = (val)

/* Get the string of a name component from the subject name. */
#define GetCertNameSubjectStr(id) \
    (certNameSubject[(id) - 3].str)
/* Get the string length of a name component from the subject name. */
#define GetCertNameSubjectStrLen(id) \
    (certNameSubject[(id) - 3].strLen)
/* Get the NID of a name component from the subject name. */
#define GetCertNameSubjectNID(id) \
    (certNameSubject[(id) - 3].nid)

#define ValidCertNameSubject(id) \
    (((id) - 3) >= 0 && ((id) - 3) < certNameSubjectSz && \
            (certNameSubject[(id) - 3].strLen > 0))

/* Mapping of certificate name component to useful information. */
typedef struct CertNameData {
    /* Type string of name component. */
    const char* str;
    /* Length of type string of name component. */
    byte        strLen;
#if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
    /* Offset of data in subject name component. */
    size_t      data;
    /* Offset of length in subject name component. */
    size_t      len;
    /* Offset of encoding in subject name component. */
    size_t      enc;
#endif
#ifdef WOLFSSL_X509_NAME_AVAILABLE
    /* NID of type for subject name component. */
    int         nid;
#endif
} CertNameData;

/* List of data for common name components. */
static const CertNameData certNameSubject[] = {
    /* Common Name */
    {
        "/CN=", 4,
#if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
        OFFSETOF(DecodedCert, subjectCN),
        OFFSETOF(DecodedCert, subjectCNLen),
        OFFSETOF(DecodedCert, subjectCNEnc),
#endif
#ifdef WOLFSSL_X509_NAME_AVAILABLE
        NID_commonName
#endif
    },
    /* Surname */
    {
        "/SN=", 4,
#if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
        OFFSETOF(DecodedCert, subjectSN),
        OFFSETOF(DecodedCert, subjectSNLen),
        OFFSETOF(DecodedCert, subjectSNEnc),
#endif
#ifdef WOLFSSL_X509_NAME_AVAILABLE
        NID_surname
#endif
    },
    /* Serial Number */
    {
        "/serialNumber=", 14,
#if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
        OFFSETOF(DecodedCert, subjectSND),
        OFFSETOF(DecodedCert, subjectSNDLen),
        OFFSETOF(DecodedCert, subjectSNDEnc),
#endif
#ifdef WOLFSSL_X509_NAME_AVAILABLE
        NID_serialNumber
#endif
    },
    /* Country Name */
    {
        "/C=", 3,
#if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
        OFFSETOF(DecodedCert, subjectC),
        OFFSETOF(DecodedCert, subjectCLen),
        OFFSETOF(DecodedCert, subjectCEnc),
#endif
#ifdef WOLFSSL_X509_NAME_AVAILABLE
        NID_countryName
#endif
    },
    /* Locality Name */
    {
        "/L=", 3,
#if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
        OFFSETOF(DecodedCert, subjectL),
        OFFSETOF(DecodedCert, subjectLLen),
        OFFSETOF(DecodedCert, subjectLEnc),
#endif
#ifdef WOLFSSL_X509_NAME_AVAILABLE
        NID_localityName
#endif
    },
    /* State Name */
    {
        "/ST=", 4,
#if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
        OFFSETOF(DecodedCert, subjectST),
        OFFSETOF(DecodedCert, subjectSTLen),
        OFFSETOF(DecodedCert, subjectSTEnc),
#endif
#ifdef WOLFSSL_X509_NAME_AVAILABLE
        NID_stateOrProvinceName
#endif
    },
    /* Street Address */
    {
        "/street=", 8,
#if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
        OFFSETOF(DecodedCert, subjectStreet),
        OFFSETOF(DecodedCert, subjectStreetLen),
        OFFSETOF(DecodedCert, subjectStreetEnc),
#endif
#ifdef WOLFSSL_X509_NAME_AVAILABLE
        NID_streetAddress
#endif
    },
    /* Organization Name */
    {
        "/O=", 3,
#if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
        OFFSETOF(DecodedCert, subjectO),
        OFFSETOF(DecodedCert, subjectOLen),
        OFFSETOF(DecodedCert, subjectOEnc),
#endif
#ifdef WOLFSSL_X509_NAME_AVAILABLE
        NID_organizationName
#endif
    },
    /* Organization Unit Name */
    {
        "/OU=", 4,
#if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
        OFFSETOF(DecodedCert, subjectOU),
        OFFSETOF(DecodedCert, subjectOULen),
        OFFSETOF(DecodedCert, subjectOUEnc),
#endif
#ifdef WOLFSSL_X509_NAME_AVAILABLE
        NID_organizationalUnitName
#endif
    },
    /* Title */
    {
        NULL, 0,
#if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
        0,
        0,
        0,
#endif
#ifdef WOLFSSL_X509_NAME_AVAILABLE
        0,
#endif
    },
    /* Undefined */
    {
        NULL, 0,
#if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
        0,
        0,
        0,
#endif
#ifdef WOLFSSL_X509_NAME_AVAILABLE
        0,
#endif
    },
    /* Undefined */
    {
        NULL, 0,
#if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
        0,
        0,
        0,
#endif
#ifdef WOLFSSL_X509_NAME_AVAILABLE
        0,
#endif
    },
    /* Business Category */
    {
        "/businessCategory=", 18,
#if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
        OFFSETOF(DecodedCert, subjectBC),
        OFFSETOF(DecodedCert, subjectBCLen),
        OFFSETOF(DecodedCert, subjectBCEnc),
#endif
#ifdef WOLFSSL_X509_NAME_AVAILABLE
        NID_businessCategory
#endif
    },
    /* Undefined */
    {
        NULL, 0,
#if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
        0,
        0,
        0,
#endif
#ifdef WOLFSSL_X509_NAME_AVAILABLE
        0,
#endif
    },
    /* Postal Code */
    {
        "/postalCode=", 12,
#if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
        OFFSETOF(DecodedCert, subjectPC),
        OFFSETOF(DecodedCert, subjectPCLen),
        OFFSETOF(DecodedCert, subjectPCEnc),
#endif
#ifdef WOLFSSL_X509_NAME_AVAILABLE
        NID_postalCode
#endif
    },
    /* User Id */
    {
        "/userid=", 8,
#if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
        OFFSETOF(DecodedCert, subjectUID),
        OFFSETOF(DecodedCert, subjectUIDLen),
        OFFSETOF(DecodedCert, subjectUIDEnc),
#endif
#ifdef WOLFSSL_X509_NAME_AVAILABLE
        NID_userId
#endif
    },
#ifdef WOLFSSL_CERT_NAME_ALL
    /* Name, id 41 */
    {
        "/N=", 3,
    #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
        OFFSETOF(DecodedCert, subjectN),
        OFFSETOF(DecodedCert, subjectNLen),
        OFFSETOF(DecodedCert, subjectNEnc),
    #endif
    #ifdef WOLFSSL_X509_NAME_AVAILABLE
        NID_name
    #endif
    },
    /* Given Name, id 42 */
    {
        "/GN=", 4,
    #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
        OFFSETOF(DecodedCert, subjectGN),
        OFFSETOF(DecodedCert, subjectGNLen),
        OFFSETOF(DecodedCert, subjectGNEnc),
    #endif
    #ifdef WOLFSSL_X509_NAME_AVAILABLE
        NID_givenName
    #endif
    },
    /* initials, id 43 */
    {
        "/initials=", 10,
    #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
        OFFSETOF(DecodedCert, subjectI),
        OFFSETOF(DecodedCert, subjectILen),
        OFFSETOF(DecodedCert, subjectIEnc),
    #endif
    #ifdef WOLFSSL_X509_NAME_AVAILABLE
        NID_initials
    #endif
    },
    /* DN Qualifier Name, id 46 */
    {
        "/dnQualifier=", 13,
    #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
        OFFSETOF(DecodedCert, subjectDNQ),
        OFFSETOF(DecodedCert, subjectDNQLen),
        OFFSETOF(DecodedCert, subjectDNQEnc),
    #endif
    #ifdef WOLFSSL_X509_NAME_AVAILABLE
        NID_dnQualifier
    #endif
    },
#endif /* WOLFSSL_CERT_NAME_ALL */
};

static const int certNameSubjectSz =
        (int) (sizeof(certNameSubject) / sizeof(CertNameData));

/* ASN.1 template for an RDN.
 * X.509: RFC 5280, 4.1.2.4 - RelativeDistinguishedName
 */
static const ASNItem rdnASN[] = {
/* SET       */ { 1, ASN_SET, 1, 1, 0 },
                           /* AttributeTypeAndValue */
/* ATTR_SEQ  */     { 2, ASN_SEQUENCE, 1, 1, 0 },
                                   /* AttributeType */
/* ATTR_TYPE */         { 3, ASN_OBJECT_ID, 0, 0, 0 },
                           /* AttributeValue: Choice of tags - rdnChoice. */
/* ATTR_VAL  */         { 3, 0, 0, 0, 0 },
};
enum {
    RDNASN_IDX_SET = 0,
    RDNASN_IDX_ATTR_SEQ,
    RDNASN_IDX_ATTR_TYPE,
    RDNASN_IDX_ATTR_VAL
};

/* Number of items in ASN.1 template for an RDN. */
#define rdnASN_Length (sizeof(rdnASN) / sizeof(ASNItem))

/* Supported types of encodings (tags) for RDN strings.
 * X.509: RFC 5280, 4.1.2.4 - DirectoryString
 * (IA5 String not listed in RFC but required for alternative types)
 */
static const byte rdnChoice[] = {
    ASN_PRINTABLE_STRING, ASN_IA5_STRING, ASN_UTF8STRING, ASN_T61STRING,
    ASN_UNIVERSALSTRING, ASN_BMPSTRING, 0
};
#endif

#if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
/* used to set the human readable string for the IP address with a ASN_IP_TYPE
 * DNS entry
 * return 0 on success
 */
static int GenerateDNSEntryIPString(DNS_entry* entry, void* heap)
{
    int ret = 0;
    int nameSz;
    char tmpName[WOLFSSL_MAX_IPSTR] = {0};
    char* ip;

    if (entry == NULL || entry->type != ASN_IP_TYPE) {
        return BAD_FUNC_ARG;
    }

    if (entry->len != WOLFSSL_IP4_ADDR_LEN &&
            entry->len != WOLFSSL_IP6_ADDR_LEN) {
        WOLFSSL_MSG("Unexpected IP size");
        return BAD_FUNC_ARG;
    }
    ip = entry->name;

    /* store IP addresses as a string */
    if (entry->len == WOLFSSL_IP4_ADDR_LEN) {
        if (XSNPRINTF(tmpName, sizeof(tmpName), "%u.%u.%u.%u", 0xFFU & ip[0],
                      0xFFU & ip[1], 0xFFU & ip[2], 0xFFU & ip[3])
            >= (int)sizeof(tmpName))
        {
            WOLFSSL_MSG("IP buffer overrun");
            return BUFFER_E;
        }
    }

    if (entry->len == WOLFSSL_IP6_ADDR_LEN) {
        int i;
        for (i = 0; i < 8; i++) {
            if (XSNPRINTF(tmpName + i * 5, sizeof(tmpName) - i * 5,
                    "%02X%02X%s", 0xFF & ip[2 * i], 0xFF & ip[2 * i + 1],
                    (i < 7) ? ":" : "")
                >= (int)sizeof(tmpName))
            {
                WOLFSSL_MSG("IPv6 buffer overrun");
                return BUFFER_E;
            }
        }
    }

    nameSz = (int)XSTRLEN(tmpName);
    entry->ipString = (char*)XMALLOC(nameSz + 1, heap, DYNAMIC_TYPE_ALTNAME);
    if (entry->ipString == NULL) {
        ret = MEMORY_E;
    }

    if (ret == 0) {
        XMEMCPY(entry->ipString, tmpName, nameSz);
        entry->ipString[nameSz] = '\0';
    }

    (void)heap;

    return ret;
}
#endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */

#ifdef WOLFSSL_ASN_TEMPLATE

#if defined(WOLFSSL_CERT_GEN) || !defined(NO_CERTS)

/* Adds a DNS entry to a list of DNS entries
 *
 * @param [in, out] lst      Linked list of DNS name entries.
 * @param [in]      entry    Entry to add to the list
 * @return  0 on success.
 */
static int AddDNSEntryToList(DNS_entry** lst, DNS_entry* entry)
{
#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_ALT_NAMES_NO_REV)
    entry->next = NULL;
    if (*lst == NULL) {
        /* First on list */
        *lst = entry;
    }
    else {
        DNS_entry* temp = *lst;

        /* Find end */
        for (; (temp->next != NULL); temp = temp->next);

        /* Add to end */
        temp->next = entry;
    }
#else
    /* Prepend entry to linked list. */
    entry->next = *lst;
    *lst = entry;
#endif

    return 0;
}


/* Allocate a DNS entry and set the fields.
 *
 * @param [in]      cert     Certificate object.
 * @param [in]      str      DNS name string.
 * @param [in]      strLen   Length of DNS name string.
 * @param [in]      type     Type of DNS name string.
 * @param [in, out] entries  Linked list of DNS name entries.
 * @return  0 on success.
 * @return  MEMORY_E when dynamic memory allocation fails.
 */
static int SetDNSEntry(DecodedCert* cert, const char* str, int strLen,
                       int type, DNS_entry** entries)
{
    DNS_entry* dnsEntry;
    int ret = 0;

    /* Only used for heap. */
    (void)cert;

    /* TODO: consider one malloc. */
    /* Allocate DNS Entry object. */
    dnsEntry = AltNameNew(cert->heap);
    if (dnsEntry == NULL) {
        ret = MEMORY_E;
    }
    if (ret == 0) {
        /* Allocate DNS Entry name - length of string plus 1 for NUL. */
        dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
                                                          DYNAMIC_TYPE_ALTNAME);
        if (dnsEntry->name == NULL) {
            XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
            ret = MEMORY_E;
        }
    }
    if (ret == 0) {
        /* Set tag type, name length, name and NUL terminate name. */
        dnsEntry->type = type;
        dnsEntry->len = strLen;
        XMEMCPY(dnsEntry->name, str, (size_t)strLen);
        dnsEntry->name[strLen] = '\0';

#if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
        /* store IP addresses as a string */
        if (type == ASN_IP_TYPE) {
            if ((ret = GenerateDNSEntryIPString(dnsEntry, cert->heap)) != 0) {
                XFREE(dnsEntry->name, cert->heap, DYNAMIC_TYPE_ALTNAME);
                XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
            }
        }
    }
    if (ret == 0) {
#endif
        ret = AddDNSEntryToList(entries, dnsEntry);
    }

    return ret;
}
#endif

/* Set the details of a subject name component into a certificate.
 *
 * @param [in, out] cert    Certificate object.
 * @param [in]      id      Id of component.
 * @param [in]      str     String for component.
 * @param [in]      strLen  Length of string.
 * @param [in]      tag     BER tag representing encoding of string.
 * @return  0 on success, negative values on failure.
 */
static int SetSubject(DecodedCert* cert, int id, byte* str, int strLen,
                      byte tag)
{
    int ret = 0;

    /* Put string and encoding into certificate. */
    if (id == ASN_COMMON_NAME) {
        cert->subjectCN = (char *)str;
        cert->subjectCNLen = (int)strLen;
        cert->subjectCNEnc = (char)tag;
    }
#if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
    else if (id > ASN_COMMON_NAME && id <= ASN_USER_ID) {
        /* Use table and offsets to put data into appropriate fields. */
        SetCertNameSubject(cert, id, (char*)str);
        SetCertNameSubjectLen(cert, id, strLen);
        SetCertNameSubjectEnc(cert, id, tag);
    }
#endif
#if !defined(IGNORE_NAME_CONSTRAINTS) || \
     defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
    else if (id == ASN_EMAIL) {
        cert->subjectEmail = (char*)str;
        cert->subjectEmailLen = strLen;
    }
#endif
#ifdef WOLFSSL_CERT_EXT
    /* TODO: consider mapping id to an index and using SetCertNameSubect*(). */
    else if (id == ASN_JURIS_C) {
        cert->subjectJC = (char*)str;
        cert->subjectJCLen = strLen;
        cert->subjectJCEnc = (char)tag;
    }
    else if (id == ASN_JURIS_ST) {
        cert->subjectJS = (char*)str;
        cert->subjectJSLen = strLen;
        cert->subjectJSEnc = (char)tag;
    }
#endif

    return ret;
}

/* Get a RelativeDistinguishedName from the encoding and put in certificate.
 *
 * @param [in, out] cert       Certificate object.
 * @param [in, out] full       Full name string. ([/<type>=<value>]*)
 * @param [in, out] idx        Index int full name to place next component.
 * @param [in, out] nid        NID of component type.
 * @param [in]      isSubject  Whether this data is for a subject name.
 * @param [in]      dataASN    Decoded data of RDN. Expected rdnASN type.
 * @return  0 on success.
 * @return  MEMORY_E when dynamic memory allocation fails.
 * @return  ASN_PARSE_E when type not supported.
 */
static int GetRDN(DecodedCert* cert, char* full, word32* idx, int* nid,
                  int isSubject, ASNGetData* dataASN)
{
    int         ret = 0;
    const char* typeStr = NULL;
    byte        typeStrLen = 0;
    byte*       oid;
    word32      oidSz;
    int         id = 0;

    (void)nid;

    /* Get name type OID from data items. */
    GetASN_OIDData(&dataASN[RDNASN_IDX_ATTR_TYPE], &oid, &oidSz);

    /* v1 name types */
    if ((oidSz == 3) && (oid[0] == 0x55) && (oid[1] == 0x04)) {
        id = oid[2];
        /* Check range of supported ids in table. */
        if (ValidCertNameSubject(id)) {
            /* Get the type string, length and NID from table. */
            typeStr = GetCertNameSubjectStr(id);
            typeStrLen = GetCertNameSubjectStrLen(id);
        #ifdef WOLFSSL_X509_NAME_AVAILABLE
            *nid = GetCertNameSubjectNID(id);
        #endif
        }
    }
    else if (oidSz == sizeof(attrEmailOid) && XMEMCMP(oid, attrEmailOid, oidSz) == 0) {
        /* Set the email id, type string, length and NID. */
        id = ASN_EMAIL;
        typeStr =  WOLFSSL_EMAIL_ADDR;
        typeStrLen = sizeof(WOLFSSL_EMAIL_ADDR) - 1;
    #ifdef WOLFSSL_X509_NAME_AVAILABLE
        *nid = NID_emailAddress;
    #endif
    }
    else if (oidSz == sizeof(uidOid) && XMEMCMP(oid, uidOid, oidSz) == 0) {
        /* Set the user id, type string, length and NID. */
        id = ASN_USER_ID;
        typeStr = WOLFSSL_USER_ID;
        typeStrLen = sizeof(WOLFSSL_USER_ID) - 1;
    #ifdef WOLFSSL_X509_NAME_AVAILABLE
        *nid = NID_userId;
    #endif
    }
    else if (oidSz == sizeof(dcOid) && XMEMCMP(oid, dcOid, oidSz) == 0) {
        /* Set the domain component, type string, length and NID. */
        id = ASN_DC;
        typeStr = WOLFSSL_DOMAIN_COMPONENT;
        typeStrLen = sizeof(WOLFSSL_DOMAIN_COMPONENT) - 1;
    #ifdef WOLFSSL_X509_NAME_AVAILABLE
        *nid = NID_domainComponent;
    #endif
    }
    else if (oidSz == sizeof(fvrtDrk) && XMEMCMP(oid, fvrtDrk, oidSz) == 0) {
        /* Set the favourite drink, type string, length and NID. */
        id = ASN_FAVOURITE_DRINK;
        typeStr = WOLFSSL_FAVOURITE_DRINK;
        typeStrLen = sizeof(WOLFSSL_FAVOURITE_DRINK) - 1;
    #ifdef WOLFSSL_X509_NAME_AVAILABLE
        *nid = NID_favouriteDrink;
    #endif
    }
    /* Other OIDs that start with the same values. */
    else if (oidSz == sizeof(dcOid) && XMEMCMP(oid, dcOid, oidSz-1) == 0) {
        WOLFSSL_MSG("Unknown pilot attribute type");
        WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
        ret = ASN_PARSE_E;
    }
    else if (oidSz == ASN_JOI_PREFIX_SZ + 1 &&
                         XMEMCMP(oid, ASN_JOI_PREFIX, ASN_JOI_PREFIX_SZ) == 0) {
        /* Set the jurisdiction id. */
        id = 0x200 + oid[ASN_JOI_PREFIX_SZ];

        /* Set the jurisdiction type string, length and NID if known. */
        if (oid[ASN_JOI_PREFIX_SZ] == ASN_JOI_C) {
            typeStr = WOLFSSL_JOI_C;
            typeStrLen = sizeof(WOLFSSL_JOI_C) - 1;
        #ifdef WOLFSSL_X509_NAME_AVAILABLE
            *nid = NID_jurisdictionCountryName;
        #endif /* WOLFSSL_X509_NAME_AVAILABLE */
        }
        else if (oid[ASN_JOI_PREFIX_SZ] == ASN_JOI_ST) {
            typeStr = WOLFSSL_JOI_ST;
            typeStrLen = sizeof(WOLFSSL_JOI_ST) - 1;
        #ifdef WOLFSSL_X509_NAME_AVAILABLE
            *nid = NID_jurisdictionStateOrProvinceName;
        #endif /* WOLFSSL_X509_NAME_AVAILABLE */
        }
        else {
            WOLFSSL_MSG("Unknown Jurisdiction, skipping");
        }
    }

    if ((ret == 0) && (typeStr != NULL)) {
        /* OID type to store for subject name and add to full string. */
        byte*  str;
        word32 strLen;
        byte   tag = dataASN[RDNASN_IDX_ATTR_VAL].tag;

        /* Get the string reference and length. */
        GetASN_GetRef(&dataASN[RDNASN_IDX_ATTR_VAL], &str, &strLen);

        if (isSubject) {
            /* Store subject field components. */
            ret = SetSubject(cert, id, str, (int)strLen, tag);
        }
        if (ret == 0) {
            /* Check there is space for this in the full name string and
             * terminating NUL character. */
            if ((typeStrLen + strLen) < (word32)(WC_ASN_NAME_MAX - *idx))
            {
                /* Add RDN to full string. */
                XMEMCPY(&full[*idx], typeStr, typeStrLen);
                *idx += typeStrLen;
                XMEMCPY(&full[*idx], str, strLen);
                *idx += strLen;
            }
            else {
                WOLFSSL_MSG("ASN Name too big, skipping");
            }
        }
    }

    return ret;
}
#endif /* WOLFSSL_ASN_TEMPLATE */

/* Get a certificate name into the certificate object.
 *
 * @param [in, out] cert      Decoded certificate object.
 * @param [out]     full      Buffer to hold full name as a string.
 * @param [out]     hash      Buffer to hold hash of name.
 * @param [in]      nameType  ISSUER or SUBJECT.
 * @param [in]      input     Buffer holding certificate name.
 * @param [in, out] inOutIdx  On in, start of certificate name.
 *                            On out, start of ASN.1 item after cert name.
 * @param [in]      maxIdx    Index of next item after certificate name.
 * @return  0 on success.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
 * @return  ASN_UNKNOWN_OID_E when the OID cannot be verified.
 * @return  MEMORY_E when dynamic memory allocation fails.
 */
static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType,
                       const byte* input, word32* inOutIdx, word32 maxIdx)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int    length;  /* length of all distinguished names */
    int    dummy;
    int    ret;
    word32 idx;
    word32 srcIdx = *inOutIdx;
#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
    !defined(WOLFCRYPT_ONLY)
    WOLFSSL_X509_NAME* dName = NULL;
#endif

    WOLFSSL_MSG("Getting Cert Name");

    /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
     * calculated over the entire DER encoding of the Name field, including
     * the tag and length. */
    if (CalcHashId(input + *inOutIdx, maxIdx - *inOutIdx, hash) != 0)
        return ASN_PARSE_E;

#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
    !defined(WOLFCRYPT_ONLY)
    dName = wolfSSL_X509_NAME_new();
    if (dName == NULL) {
        return MEMORY_E;
    }
#endif /* OPENSSL_EXTRA */

    if (GetSequence(input, &srcIdx, &length, maxIdx) < 0) {
#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
            !defined(WOLFCRYPT_ONLY)
        wolfSSL_X509_NAME_free(dName);
#endif /* OPENSSL_EXTRA */
        return ASN_PARSE_E;
    }

#if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)
    /* store pointer to raw issuer */
    if (nameType == ISSUER) {
        cert->issuerRaw = &input[srcIdx];
        cert->issuerRawLen = length;
    }
#endif
#if !defined(IGNORE_NAME_CONSTRAINTS) || defined(WOLFSSL_CERT_EXT)
    if (nameType == SUBJECT) {
        cert->subjectRaw = &input[srcIdx];
        cert->subjectRawLen = length;
    }
#endif

    length += (int)srcIdx;
    idx = 0;

    while (srcIdx < (word32)length) {
        byte        b       = 0;
        byte        joint[3];
        byte        tooBig  = FALSE;
        int         oidSz;
        const char* copy    = NULL;
        int         copyLen = 0;
        int         strLen  = 0;
        byte        id      = 0;
    #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
                && !defined(WOLFCRYPT_ONLY)
         int        nid = NID_undef;
         int        enc;
    #endif /* OPENSSL_EXTRA */

        if (GetSet(input, &srcIdx, &dummy, maxIdx) < 0) {
            WOLFSSL_MSG("Cert name lacks set header, trying sequence");
        }

        if (GetSequence(input, &srcIdx, &dummy, maxIdx) <= 0) {
        #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
            !defined(WOLFCRYPT_ONLY)
            wolfSSL_X509_NAME_free(dName);
        #endif /* OPENSSL_EXTRA */
            return ASN_PARSE_E;
        }

        ret = GetASNObjectId(input, &srcIdx, &oidSz, maxIdx);
        if (ret != 0) {
        #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
            !defined(WOLFCRYPT_ONLY)
            wolfSSL_X509_NAME_free(dName);
        #endif /* OPENSSL_EXTRA */
            return ret;
        }

        /* make sure there is room for joint */
        if ((srcIdx + sizeof(joint)) > (word32)maxIdx) {
        #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
            !defined(WOLFCRYPT_ONLY)
            wolfSSL_X509_NAME_free(dName);
        #endif /* OPENSSL_EXTRA */
            return ASN_PARSE_E;
        }

        XMEMCPY(joint, &input[srcIdx], sizeof(joint));

        /* v1 name types */
        if (joint[0] == 0x55 && joint[1] == 0x04) {
            srcIdx += 3;
            id = joint[2];
            if (GetHeader(input, &b, &srcIdx, &strLen, maxIdx, 1) < 0) {
            #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
            !defined(WOLFCRYPT_ONLY)
                wolfSSL_X509_NAME_free(dName);
            #endif /* OPENSSL_EXTRA */
                return ASN_PARSE_E;
            }

            if (id == ASN_COMMON_NAME) {
                if (nameType == SUBJECT) {
                    cert->subjectCN = (char *)&input[srcIdx];
                    cert->subjectCNLen = strLen;
                    cert->subjectCNEnc = (char)b;
                }
            #if (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)) && \
                defined(WOLFSSL_HAVE_ISSUER_NAMES)
                else if (nameType == ISSUER) {
                    cert->issuerCN = (char*)&input[srcIdx];
                    cert->issuerCNLen = strLen;
                    cert->issuerCNEnc = (char)b;
                }
            #endif

                copy = WOLFSSL_COMMON_NAME;
                copyLen = sizeof(WOLFSSL_COMMON_NAME) - 1;
            #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
                && !defined(WOLFCRYPT_ONLY)
                nid = NID_commonName;
            #endif /* OPENSSL_EXTRA */
            }
        #ifdef WOLFSSL_CERT_NAME_ALL
            else if (id == ASN_NAME) {
                copy = WOLFSSL_NAME;
                copyLen = sizeof(WOLFSSL_NAME) - 1;
                #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
                    if (nameType == SUBJECT) {
                        cert->subjectN = (char*)&input[srcIdx];
                        cert->subjectNLen = strLen;
                        cert->subjectNEnc = b;
                    }
                #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
                #if (defined(OPENSSL_EXTRA) || \
                        defined(OPENSSL_EXTRA_X509_SMALL)) \
                        && !defined(WOLFCRYPT_ONLY)
                    nid = NID_name;
                #endif /* OPENSSL_EXTRA */
            }
            else if (id == ASN_INITIALS) {
                copy = WOLFSSL_INITIALS;
                copyLen = sizeof(WOLFSSL_INITIALS) - 1;
                #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
                    if (nameType == SUBJECT) {
                        cert->subjectI = (char*)&input[srcIdx];
                        cert->subjectILen = strLen;
                        cert->subjectIEnc = b;
                    }
                #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
                #if (defined(OPENSSL_EXTRA) || \
                        defined(OPENSSL_EXTRA_X509_SMALL)) \
                        && !defined(WOLFCRYPT_ONLY)
                    nid = NID_initials;
                #endif /* OPENSSL_EXTRA */
            }
            else if (id == ASN_GIVEN_NAME) {
                copy = WOLFSSL_GIVEN_NAME;
                copyLen = sizeof(WOLFSSL_GIVEN_NAME) - 1;
                #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
                    if (nameType == SUBJECT) {
                        cert->subjectGN = (char*)&input[srcIdx];
                        cert->subjectGNLen = strLen;
                        cert->subjectGNEnc = b;
                    }
                #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
                #if (defined(OPENSSL_EXTRA) || \
                        defined(OPENSSL_EXTRA_X509_SMALL)) \
                        && !defined(WOLFCRYPT_ONLY)
                    nid = NID_givenName;
                #endif /* OPENSSL_EXTRA */
            }
            else if (id == ASN_DNQUALIFIER) {
                copy = WOLFSSL_DNQUALIFIER;
                copyLen = sizeof(WOLFSSL_DNQUALIFIER) - 1;
                #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
                    if (nameType == SUBJECT) {
                        cert->subjectDNQ = (char*)&input[srcIdx];
                        cert->subjectDNQLen = strLen;
                        cert->subjectDNQEnc = b;
                    }
                #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
                #if (defined(OPENSSL_EXTRA) || \
                        defined(OPENSSL_EXTRA_X509_SMALL)) \
                        && !defined(WOLFCRYPT_ONLY)
                    nid = NID_dnQualifier;
                #endif /* OPENSSL_EXTRA */
            }
        #endif /* WOLFSSL_CERT_NAME_ALL */
            else if (id == ASN_SUR_NAME) {
                copy = WOLFSSL_SUR_NAME;
                copyLen = sizeof(WOLFSSL_SUR_NAME) - 1;
                #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
                    if (nameType == SUBJECT) {
                        cert->subjectSN = (char*)&input[srcIdx];
                        cert->subjectSNLen = strLen;
                        cert->subjectSNEnc = (char)b;
                    }
                #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
                    else if (nameType == ISSUER) {
                        cert->issuerSN = (char*)&input[srcIdx];
                        cert->issuerSNLen = strLen;
                        cert->issuerSNEnc = (char)b;
                    }
                #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
                #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
                #if (defined(OPENSSL_EXTRA) || \
                        defined(OPENSSL_EXTRA_X509_SMALL)) \
                        && !defined(WOLFCRYPT_ONLY)
                    nid = NID_surname;
                #endif /* OPENSSL_EXTRA */
            }
            else if (id == ASN_COUNTRY_NAME) {
                copy = WOLFSSL_COUNTRY_NAME;
                copyLen = sizeof(WOLFSSL_COUNTRY_NAME) - 1;
                #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
                    if (nameType == SUBJECT) {
                        cert->subjectC = (char*)&input[srcIdx];
                        cert->subjectCLen = strLen;
                        cert->subjectCEnc = (char)b;
                    }
                #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
                    else if (nameType == ISSUER) {
                        cert->issuerC = (char*)&input[srcIdx];
                        cert->issuerCLen = strLen;
                        cert->issuerCEnc = (char)b;
                    }
                #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
                #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
                #if (defined(OPENSSL_EXTRA) || \
                        defined(OPENSSL_EXTRA_X509_SMALL)) \
                        && !defined(WOLFCRYPT_ONLY)
                    nid = NID_countryName;
                #endif /* OPENSSL_EXTRA */
            }
            else if (id == ASN_LOCALITY_NAME) {
                copy = WOLFSSL_LOCALITY_NAME;
                copyLen = sizeof(WOLFSSL_LOCALITY_NAME) - 1;
                #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
                    if (nameType == SUBJECT) {
                        cert->subjectL = (char*)&input[srcIdx];
                        cert->subjectLLen = strLen;
                        cert->subjectLEnc = (char)b;
                    }
                    #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
                    else if (nameType == ISSUER) {
                        cert->issuerL = (char*)&input[srcIdx];
                        cert->issuerLLen = strLen;
                        cert->issuerLEnc = (char)b;
                    }
                    #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
                #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
                #if (defined(OPENSSL_EXTRA) || \
                        defined(OPENSSL_EXTRA_X509_SMALL)) \
                        && !defined(WOLFCRYPT_ONLY)
                    nid = NID_localityName;
                #endif /* OPENSSL_EXTRA */
            }
            else if (id == ASN_STATE_NAME) {
                copy = WOLFSSL_STATE_NAME;
                copyLen = sizeof(WOLFSSL_STATE_NAME) - 1;
                #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
                    if (nameType == SUBJECT) {
                        cert->subjectST = (char*)&input[srcIdx];
                        cert->subjectSTLen = strLen;
                        cert->subjectSTEnc = (char)b;
                    }
                #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
                    else if (nameType == ISSUER) {
                        cert->issuerST = (char*)&input[srcIdx];
                        cert->issuerSTLen = strLen;
                        cert->issuerSTEnc = (char)b;
                    }
                #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
                #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT*/
                #if (defined(OPENSSL_EXTRA) || \
                        defined(OPENSSL_EXTRA_X509_SMALL)) \
                        && !defined(WOLFCRYPT_ONLY)
                    nid = NID_stateOrProvinceName;
                #endif /* OPENSSL_EXTRA */
            }
            else if (id == ASN_ORG_NAME) {
                copy = WOLFSSL_ORG_NAME;
                copyLen = sizeof(WOLFSSL_ORG_NAME) - 1;
                #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
                    if (nameType == SUBJECT) {
                        cert->subjectO = (char*)&input[srcIdx];
                        cert->subjectOLen = strLen;
                        cert->subjectOEnc = (char)b;
                    }
                #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
                    else if (nameType == ISSUER) {
                        cert->issuerO = (char*)&input[srcIdx];
                        cert->issuerOLen = strLen;
                        cert->issuerOEnc = (char)b;
                    }
                #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
                #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
                #if (defined(OPENSSL_EXTRA) || \
                        defined(OPENSSL_EXTRA_X509_SMALL)) \
                        && !defined(WOLFCRYPT_ONLY)
                    nid = NID_organizationName;
                #endif /* OPENSSL_EXTRA */
            }
            else if (id == ASN_ORGUNIT_NAME) {
                copy = WOLFSSL_ORGUNIT_NAME;
                copyLen = sizeof(WOLFSSL_ORGUNIT_NAME) - 1;
                #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
                    if (nameType == SUBJECT) {
                        cert->subjectOU = (char*)&input[srcIdx];
                        cert->subjectOULen = strLen;
                        cert->subjectOUEnc = (char)b;
                    }
                #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
                    else if (nameType == ISSUER) {
                        cert->issuerOU = (char*)&input[srcIdx];
                        cert->issuerOULen = strLen;
                        cert->issuerOUEnc = (char)b;
                    }
                #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
                #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
                #if (defined(OPENSSL_EXTRA) || \
                        defined(OPENSSL_EXTRA_X509_SMALL)) \
                        && !defined(WOLFCRYPT_ONLY)
                    nid = NID_organizationalUnitName;
                #endif /* OPENSSL_EXTRA */
            }
            else if (id == ASN_SERIAL_NUMBER) {
                copy = WOLFSSL_SERIAL_NUMBER;
                copyLen = sizeof(WOLFSSL_SERIAL_NUMBER) - 1;
                #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
                    if (nameType == SUBJECT) {
                        cert->subjectSND = (char*)&input[srcIdx];
                        cert->subjectSNDLen = strLen;
                        cert->subjectSNDEnc = (char)b;
                    }
                #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
                    else if (nameType == ISSUER) {
                        cert->issuerSND = (char*)&input[srcIdx];
                        cert->issuerSNDLen = strLen;
                        cert->issuerSNDEnc = (char)b;
                    }
                #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
                #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
                #if (defined(OPENSSL_EXTRA) || \
                        defined(OPENSSL_EXTRA_X509_SMALL)) \
                        && !defined(WOLFCRYPT_ONLY)
                    nid = NID_serialNumber;
                #endif /* OPENSSL_EXTRA */
            }
            else if (id == ASN_USER_ID) {
                copy = WOLFSSL_USER_ID;
                copyLen = sizeof(WOLFSSL_USER_ID) - 1;
                #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
                    if (nameType == SUBJECT) {
                        cert->subjectUID = (char*)&input[srcIdx];
                        cert->subjectUIDLen = strLen;
                        cert->subjectUIDEnc = (char)b;
                    }
                #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
                #if (defined(OPENSSL_EXTRA) || \
                        defined(OPENSSL_EXTRA_X509_SMALL)) \
                        && !defined(WOLFCRYPT_ONLY)
                    nid = NID_userId;
                #endif /* OPENSSL_EXTRA */
            }
        #ifdef WOLFSSL_CERT_EXT
            else if (id == ASN_STREET_ADDR) {
                copy = WOLFSSL_STREET_ADDR_NAME;
                copyLen = sizeof(WOLFSSL_STREET_ADDR_NAME) - 1;
                #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
                    if (nameType == SUBJECT) {
                        cert->subjectStreet = (char*)&input[srcIdx];
                        cert->subjectStreetLen = strLen;
                        cert->subjectStreetEnc = (char)b;
                    }
                #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
                #if (defined(OPENSSL_EXTRA) || \
                        defined(OPENSSL_EXTRA_X509_SMALL)) \
                        && !defined(WOLFCRYPT_ONLY)
                    nid = NID_streetAddress;
                #endif /* OPENSSL_EXTRA */
            }
            else if (id == ASN_BUS_CAT) {
                copy = WOLFSSL_BUS_CAT;
                copyLen = sizeof(WOLFSSL_BUS_CAT) - 1;
            #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
                if (nameType == SUBJECT) {
                    cert->subjectBC = (char*)&input[srcIdx];
                    cert->subjectBCLen = strLen;
                    cert->subjectBCEnc = (char)b;
                }
            #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
            #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
                        && !defined(WOLFCRYPT_ONLY)
                nid = NID_businessCategory;
            #endif /* OPENSSL_EXTRA */
            }
            else if (id == ASN_POSTAL_CODE) {
                copy = WOLFSSL_POSTAL_NAME;
                copyLen = sizeof(WOLFSSL_POSTAL_NAME) - 1;
                #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
                    if (nameType == SUBJECT) {
                        cert->subjectPC = (char*)&input[srcIdx];
                        cert->subjectPCLen = strLen;
                        cert->subjectPCEnc = (char)b;
                    }
                #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT*/
                #if (defined(OPENSSL_EXTRA) || \
                        defined(OPENSSL_EXTRA_X509_SMALL)) \
                        && !defined(WOLFCRYPT_ONLY)
                    nid = NID_postalCode;
                #endif /* OPENSSL_EXTRA */
            }
        #endif /* WOLFSSL_CERT_EXT */
        }
    #ifdef WOLFSSL_CERT_EXT
        else if ((srcIdx + ASN_JOI_PREFIX_SZ + 2 <= (word32)maxIdx) &&
                 (0 == XMEMCMP(&input[srcIdx], ASN_JOI_PREFIX,
                               ASN_JOI_PREFIX_SZ)) &&
                 ((input[srcIdx+ASN_JOI_PREFIX_SZ] == ASN_JOI_C) ||
                  (input[srcIdx+ASN_JOI_PREFIX_SZ] == ASN_JOI_ST)))
        {
            srcIdx += ASN_JOI_PREFIX_SZ;
            id = input[srcIdx++];
            b = input[srcIdx++]; /* encoding */

            if (GetLength(input, &srcIdx, &strLen,
                          maxIdx) < 0) {
            #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
            !defined(WOLFCRYPT_ONLY)
                wolfSSL_X509_NAME_free(dName);
            #endif /* OPENSSL_EXTRA */
                return ASN_PARSE_E;
            }

            /* Check for jurisdiction of incorporation country name */
            if (id == ASN_JOI_C) {
                copy = WOLFSSL_JOI_C;
                copyLen = sizeof(WOLFSSL_JOI_C) - 1;
                #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
                    if (nameType == SUBJECT) {
                        cert->subjectJC = (char*)&input[srcIdx];
                        cert->subjectJCLen = strLen;
                        cert->subjectJCEnc = (char)b;
                    }
                #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
                #if (defined(OPENSSL_EXTRA) || \
                        defined(OPENSSL_EXTRA_X509_SMALL)) \
                        && !defined(WOLFCRYPT_ONLY)
                    nid = NID_jurisdictionCountryName;
                #endif /* OPENSSL_EXTRA */
            }

            /* Check for jurisdiction of incorporation state name */
            else if (id == ASN_JOI_ST) {
                copy = WOLFSSL_JOI_ST;
                copyLen = sizeof(WOLFSSL_JOI_ST) - 1;
                #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
                    if (nameType == SUBJECT) {
                        cert->subjectJS = (char*)&input[srcIdx];
                        cert->subjectJSLen = strLen;
                        cert->subjectJSEnc = (char)b;
                    }
                #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
                #if (defined(OPENSSL_EXTRA) || \
                        defined(OPENSSL_EXTRA_X509_SMALL)) \
                        && !defined(WOLFCRYPT_ONLY)
                    nid = NID_jurisdictionStateOrProvinceName;
                #endif /* OPENSSL_EXTRA */
            }

            if ((strLen + copyLen) > (int)(WC_ASN_NAME_MAX - idx)) {
                WOLFSSL_MSG("ASN Name too big, skipping");
                tooBig = TRUE;
            }
        }
    #endif /* WOLFSSL_CERT_EXT */
        else {
            /* skip */
            byte email = FALSE;
            byte pilot = FALSE;

            if (joint[0] == 0x2a && joint[1] == 0x86) {  /* email id hdr 42.134.* */
                id = ASN_EMAIL_NAME;
                email = TRUE;
            }

            if (joint[0] == 0x9  && joint[1] == 0x92) { /* uid id hdr 9.146.* */
                /* last value of OID is the type of pilot attribute */
                id    = input[srcIdx + (word32)oidSz - 1];
                if (id == 0x01)
                    id = ASN_USER_ID;
                pilot = TRUE;
            }

            srcIdx += (word32)oidSz + 1;

            if (GetLength(input, &srcIdx, &strLen, maxIdx) < 0) {
            #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
            !defined(WOLFCRYPT_ONLY)
                wolfSSL_X509_NAME_free(dName);
            #endif /* OPENSSL_EXTRA */
                return ASN_PARSE_E;
            }

            if (strLen > (int)(WC_ASN_NAME_MAX - idx)) {
                WOLFSSL_MSG("ASN name too big, skipping");
                tooBig = TRUE;
            }

            if (email) {
                copyLen = sizeof(WOLFSSL_EMAIL_ADDR) - 1;
                if ((copyLen + strLen) > (int)(WC_ASN_NAME_MAX - idx)) {
                    WOLFSSL_MSG("ASN name too big, skipping");
                    tooBig = TRUE;
                }
                else {
                    copy = WOLFSSL_EMAIL_ADDR;
                }

                #if !defined(IGNORE_NAME_CONSTRAINTS) || \
                     defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
                    if (nameType == SUBJECT) {
                        cert->subjectEmail = (char*)&input[srcIdx];
                        cert->subjectEmailLen = strLen;
                    }
                #if defined(WOLFSSL_HAVE_ISSUER_NAMES) && \
                    (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT))
                    else if (nameType == ISSUER) {
                        cert->issuerEmail = (char*)&input[srcIdx];
                        cert->issuerEmailLen = strLen;
                    }
                #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
                #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
                #if (defined(OPENSSL_EXTRA) || \
                        defined(OPENSSL_EXTRA_X509_SMALL)) \
                        && !defined(WOLFCRYPT_ONLY)
                    nid = NID_emailAddress;
                #endif /* OPENSSL_EXTRA */
            }

            if (pilot) {
                switch (id) {
                    case ASN_USER_ID:
                        copy = WOLFSSL_USER_ID;
                        copyLen = sizeof(WOLFSSL_USER_ID) - 1;
                    #if (defined(OPENSSL_EXTRA) || \
                        defined(OPENSSL_EXTRA_X509_SMALL)) \
                        && !defined(WOLFCRYPT_ONLY)
                        nid = NID_userId;
                    #endif /* OPENSSL_EXTRA */
                        break;

                    case ASN_DOMAIN_COMPONENT:
                        copy = WOLFSSL_DOMAIN_COMPONENT;
                        copyLen = sizeof(WOLFSSL_DOMAIN_COMPONENT) - 1;
                    #if (defined(OPENSSL_EXTRA) || \
                        defined(OPENSSL_EXTRA_X509_SMALL)) \
                        && !defined(WOLFCRYPT_ONLY)
                        nid = NID_domainComponent;
                    #endif /* OPENSSL_EXTRA */
                        break;
                    case ASN_FAVOURITE_DRINK:
                        copy = WOLFSSL_FAVOURITE_DRINK;
                        copyLen = sizeof(WOLFSSL_FAVOURITE_DRINK) - 1;
                    #if (defined(OPENSSL_EXTRA) || \
                        defined(OPENSSL_EXTRA_X509_SMALL)) \
                        && !defined(WOLFCRYPT_ONLY)
                        nid = NID_favouriteDrink;
                    #endif /* OPENSSL_EXTRA */
                        break;

                    default:
                        WOLFSSL_MSG("Unknown pilot attribute type");
                    #if (defined(OPENSSL_EXTRA) || \
                                defined(OPENSSL_EXTRA_X509_SMALL)) && \
                                !defined(WOLFCRYPT_ONLY)
                        wolfSSL_X509_NAME_free(dName);
                    #endif /* OPENSSL_EXTRA */
                        return ASN_PARSE_E;
                }
            }
        }
        if ((copyLen + strLen) > (int)(WC_ASN_NAME_MAX - idx))
        {
            WOLFSSL_MSG("ASN Name too big, skipping");
            tooBig = TRUE;
        }
        if ((copy != NULL) && !tooBig) {
            XMEMCPY(&full[idx], copy, (size_t)copyLen);
            idx += (word32)copyLen;
            XMEMCPY(&full[idx], &input[srcIdx], (size_t)strLen);
            idx += (word32)strLen;
        }
        #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
            !defined(WOLFCRYPT_ONLY)
        switch (b) {
            case CTC_UTF8:
                enc = MBSTRING_UTF8;
                break;
            case CTC_PRINTABLE:
                enc = V_ASN1_PRINTABLESTRING;
                break;
            default:
                WOLFSSL_MSG("Unknown encoding type, using UTF8 by default");
                enc = MBSTRING_UTF8;
        }

        if (nid != NID_undef) {
            if (wolfSSL_X509_NAME_add_entry_by_NID(dName, nid, enc,
                            &input[srcIdx], strLen, -1, -1) !=
                            WOLFSSL_SUCCESS) {
                wolfSSL_X509_NAME_free(dName);
                return ASN_PARSE_E;
            }
        }
        #endif /* OPENSSL_EXTRA */
        srcIdx += (word32)strLen;
    }
    full[idx++] = 0;

#if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
            !defined(WOLFCRYPT_ONLY)
    if (nameType == ISSUER) {
#if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY)) && \
    (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT))
        dName->rawLen = min(cert->issuerRawLen, WC_ASN_NAME_MAX);
        XMEMCPY(dName->raw, cert->issuerRaw, dName->rawLen);
#endif
        cert->issuerName = dName;
    }
    else {
#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
        dName->rawLen = min(cert->subjectRawLen, WC_ASN_NAME_MAX);
        XMEMCPY(dName->raw, cert->subjectRaw, dName->rawLen);
#endif
        cert->subjectName = dName;
    }
#endif

    *inOutIdx = srcIdx;

    return 0;
#else
    DECL_ASNGETDATA(dataASN, rdnASN_Length);
    int    ret = 0;
    word32 idx = 0;
    int    len;
    word32 srcIdx = *inOutIdx;
#ifdef WOLFSSL_X509_NAME_AVAILABLE
    WOLFSSL_X509_NAME* dName = NULL;
#endif /* WOLFSSL_X509_NAME_AVAILABLE */

    WOLFSSL_MSG("Getting Cert Name");

    /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
     * calculated over the entire DER encoding of the Name field, including
     * the tag and length. */
    if (CalcHashId(input + srcIdx, maxIdx - srcIdx, hash) != 0) {
        ret = ASN_PARSE_E;
    }

    CALLOC_ASNGETDATA(dataASN, rdnASN_Length, ret, cert->heap);

#ifdef WOLFSSL_X509_NAME_AVAILABLE
    if (ret == 0) {
        /* Create an X509_NAME to hold data for OpenSSL compatability APIs. */
        dName = wolfSSL_X509_NAME_new();
        if (dName == NULL) {
            ret = MEMORY_E;
        }
    }
#endif /* WOLFSSL_X509_NAME_AVAILABLE */

    if (ret == 0) {
        /* Expecting a SEQUENCE using up all data. */
        ret = GetASN_Sequence(input, &srcIdx, &len, maxIdx, 1);
    }
    if (ret == 0) {
    #if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)
        /* Store pointer and length to raw issuer. */
        if (nameType == ISSUER) {
            cert->issuerRaw = &input[srcIdx];
            cert->issuerRawLen = len;
        }
    #endif
    #if !defined(IGNORE_NAME_CONSTRAINTS) || defined(WOLFSSL_CERT_EXT)
        /* Store pointer and length to raw subject. */
        if (nameType == SUBJECT) {
            cert->subjectRaw = &input[srcIdx];
            cert->subjectRawLen = len;
        }
    #endif

        /* Process all RDNs in name. */
        while ((ret == 0) && (srcIdx < maxIdx)) {
            int nid = 0;

            /* Initialize for data and setup RDN choice. */
            GetASN_Choice(&dataASN[RDNASN_IDX_ATTR_VAL], rdnChoice);
            /* Ignore type OID as too many to store in table. */
            GetASN_OID(&dataASN[RDNASN_IDX_ATTR_TYPE], oidIgnoreType);
            /* Parse RDN. */
            ret = GetASN_Items(rdnASN, dataASN, rdnASN_Length, 1, input,
                               &srcIdx, maxIdx);
            if (ret == 0) {
                /* Put RDN data into certificate. */
                ret = GetRDN(cert, full, &idx, &nid, nameType == SUBJECT,
                             dataASN);
            }
        #ifdef WOLFSSL_X509_NAME_AVAILABLE
            /* TODO: push this back up to ssl.c
             * (do parsing for WOLFSSL_X509_NAME on demand) */
            if (ret == 0) {
                int enc;
                byte*  str;
                word32 strLen;
                byte   tag = dataASN[RDNASN_IDX_ATTR_VAL].tag;

                /* Get string reference. */
                GetASN_GetRef(&dataASN[RDNASN_IDX_ATTR_VAL], &str, &strLen);

                /* Convert BER tag to a OpenSSL type. */
                switch (tag) {
                    case CTC_UTF8:
                        enc = MBSTRING_UTF8;
                        break;
                    case CTC_PRINTABLE:
                        enc = V_ASN1_PRINTABLESTRING;
                        break;
                    default:
                        WOLFSSL_MSG("Unknown encoding type, default UTF8");
                        enc = MBSTRING_UTF8;
                }
                if (nid != 0) {
                    /* Add an entry to the X509_NAME. */
                    if (wolfSSL_X509_NAME_add_entry_by_NID(dName, nid, enc, str,
                            strLen, -1, -1) != WOLFSSL_SUCCESS) {
                        ret = ASN_PARSE_E;
                    }
                }
            }
        #endif
        }
    }
    if (ret == 0) {
        /* Terminate string. */
        full[idx] = 0;
        /* Return index into encoding after name. */
        *inOutIdx = srcIdx;

#ifdef WOLFSSL_X509_NAME_AVAILABLE
        /* Store X509_NAME in certificate. */
        if (nameType == ISSUER) {
        #if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
             defined(HAVE_LIGHTY)) && \
            (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT))
            dName->rawLen = min(cert->issuerRawLen, WC_ASN_NAME_MAX);
            XMEMCPY(dName->raw, cert->issuerRaw, dName->rawLen);
        #endif
            cert->issuerName = dName;
        }
        else {
        #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
            dName->rawLen = min(cert->subjectRawLen, WC_ASN_NAME_MAX);
            XMEMCPY(dName->raw, cert->subjectRaw, dName->rawLen);
        #endif
            cert->subjectName = dName;
        }
    }
    else {
        /* Dispose of unused X509_NAME. */
        wolfSSL_X509_NAME_free(dName);
#endif
    }

    FREE_ASNGETDATA(dataASN, cert->heap);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for certificate name. */
static const ASNItem certNameASN[] = {
/* OID  */ { 0, ASN_OBJECT_ID, 0, 0, 1 },
/* NAME */ { 0, ASN_SEQUENCE, 1, 0, 0 },
};
enum {
    CERTNAMEASN_IDX_OID = 0,
    CERTNAMEASN_IDX_NAME
};

/* Number of items in ASN.1 template for certificate name. */
#define certNameASN_Length (sizeof(certNameASN) / sizeof(ASNItem))
#endif

/* Get a certificate name into the certificate object.
 *
 * Either the issuer or subject name.
 *
 * @param [in, out] cert      Decoded certificate object.
 * @param [in]      nameType  Type of name being decoded: ISSUER or SUBJECT.
 * @param [in]      maxIdx    Index of next item after certificate name.
 * @return  0 on success.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
 * @return  ASN_UNKNOWN_OID_E when the OID cannot be verified.
 * @return  MEMORY_E when dynamic memory allocation fails.
 */
int GetName(DecodedCert* cert, int nameType, int maxIdx)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    char*  full;
    byte*  hash;
    int    length;
    word32 localIdx;
    byte   tag;

    WOLFSSL_MSG("Getting Name");

    if (nameType == ISSUER) {
        full = cert->issuer;
        hash = cert->issuerHash;
    }
    else {
        full = cert->subject;
        hash = cert->subjectHash;
    }

    if (cert->srcIdx >= (word32)maxIdx) {
        return BUFFER_E;
    }

    localIdx = cert->srcIdx;
    if (GetASNTag(cert->source, &localIdx, &tag, (word32)maxIdx) < 0) {
        return ASN_PARSE_E;
    }

    if (tag == ASN_OBJECT_ID) {
        WOLFSSL_MSG("Trying optional prefix...");

        if (SkipObjectId(cert->source, &cert->srcIdx, (word32)maxIdx) < 0)
            return ASN_PARSE_E;
        WOLFSSL_MSG("Got optional prefix");
    }

    localIdx = cert->srcIdx;
    if (GetASNTag(cert->source, &localIdx, &tag, (word32)maxIdx) < 0) {
        return ASN_PARSE_E;
    }
    localIdx = cert->srcIdx + 1;
    if (GetLength(cert->source, &localIdx, &length, (word32)maxIdx) < 0) {
        return ASN_PARSE_E;
    }
    length += (int)(localIdx - cert->srcIdx);

    return GetCertName(cert, full, hash, nameType, cert->source, &cert->srcIdx,
                       cert->srcIdx + (word32)length);
#else
    ASNGetData dataASN[certNameASN_Length];
    word32 idx = cert->srcIdx;
    int    ret = 0;

    WOLFSSL_MSG("Getting Name");

    XMEMSET(dataASN, 0, sizeof(dataASN));
    /* Initialize for data and don't check optional prefix OID. */
    GetASN_OID(&dataASN[CERTNAMEASN_IDX_OID], oidIgnoreType);
    ret = GetASN_Items(certNameASN, dataASN, certNameASN_Length, 0,
                       cert->source, &idx, (word32)maxIdx);
    if (ret == 0) {
        char* full;
        byte* hash;

        /* Store offset of SEQUENCE that is start of name. */
        cert->srcIdx = dataASN[CERTNAMEASN_IDX_NAME].offset;

        /* Get fields to fill in based on name type. */
        if (nameType == ISSUER) {
            full = cert->issuer;
            hash = cert->issuerHash;
        }
        else {
            full = cert->subject;
            hash = cert->subjectHash;
        }

        /* Parse certificate name. */
        ret = GetCertName(cert, full, hash, nameType, cert->source,
                          &cert->srcIdx, idx);
    }

    return ret;
#endif
}

#ifndef NO_ASN_TIME

/* two byte date/time, add to value */
static WC_INLINE int GetTime(int* value, const byte* date, int* idx)
{
    int i = *idx;

    if (date[i] < 0x30 || date[i] > 0x39 || date[i+1] < 0x30 ||
                                                             date[i+1] > 0x39) {
        return ASN_PARSE_E;
    }

    *value += (int)btoi(date[i++]) * 10;
    *value += (int)btoi(date[i++]);

    *idx = i;

    return 0;
}

#ifdef WOLFSSL_LINUXKM
static WC_INLINE int GetTime_Long(long* value, const byte* date, int* idx)
{
    int i = *idx;

    if (date[i] < 0x30 || date[i] > 0x39 || date[i+1] < 0x30 ||
                                                             date[i+1] > 0x39) {
        return ASN_PARSE_E;
    }

    *value += (long)btoi(date[i++]) * 10;
    *value += (long)btoi(date[i++]);

    *idx = i;

    return 0;
}
#endif

int ExtractDate(const unsigned char* date, unsigned char format,
                                                  struct tm* certTime, int* idx)
{
    XMEMSET(certTime, 0, sizeof(struct tm));

    if (format == ASN_UTC_TIME) {
        if (btoi(date[*idx]) >= 5)
            certTime->tm_year = 1900;
        else
            certTime->tm_year = 2000;
    }
    else  { /* format == GENERALIZED_TIME */
#ifdef WOLFSSL_LINUXKM
        if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
#else
        if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
#endif
        certTime->tm_year *= 100;
    }

#ifdef AVR
    /* Extract the time from the struct tm and adjust tm_year, tm_mon */
    /* AVR libc stores these as uint8_t instead of int */
    /* AVR time_t also offsets from midnight 1 Jan 2000 */
    int tm_year = certTime->tm_year - 2000;
    int tm_mon  = certTime->tm_mon - 1;
    int tm_mday = certTime->tm_mday;
    int tm_hour = certTime->tm_hour;
    int tm_min  = certTime->tm_min;
    int tm_sec  = certTime->tm_sec;

#ifdef WOLFSSL_LINUXKM
    if (GetTime_Long(&tm_year, date, idx) != 0) return 0;
#else
    if (GetTime(&tm_year, date, idx) != 0) return 0;
#endif
    if (GetTime(&tm_mon , date, idx) != 0) return 0;
    if (GetTime(&tm_mday, date, idx) != 0) return 0;
    if (GetTime(&tm_hour, date, idx) != 0) return 0;
    if (GetTime(&tm_min , date, idx) != 0) return 0;
    if (GetTime(&tm_sec , date, idx) != 0) return 0;

    /* Re-populate certTime with computed values */
    certTime->tm_year = tm_year;
    certTime->tm_mon  = tm_mon;
    certTime->tm_mday = tm_mday;
    certTime->tm_hour = tm_hour;
    certTime->tm_min  = tm_min;
    certTime->tm_sec  = tm_sec;
#else
    /* adjust tm_year, tm_mon */
#ifdef WOLFSSL_LINUXKM
    if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
#else
    if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
#endif
    certTime->tm_year -= 1900;
    if (GetTime(&certTime->tm_mon , date, idx) != 0) return 0;
    certTime->tm_mon  -= 1;
    if (GetTime(&certTime->tm_mday, date, idx) != 0) return 0;
    if (GetTime(&certTime->tm_hour, date, idx) != 0) return 0;
    if (GetTime(&certTime->tm_min , date, idx) != 0) return 0;
    if (GetTime(&certTime->tm_sec , date, idx) != 0) return 0;
#endif

    return 1;
}


#if defined(OPENSSL_ALL) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \
    defined(OPENSSL_EXTRA) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
int GetTimeString(byte* date, int format, char* buf, int len)
{
    struct tm t;
    int idx = 0;

    if (!ExtractDate(date, (unsigned char)format, &t, &idx)) {
        return 0;
    }

    if (date[idx] != 'Z') {
        WOLFSSL_MSG("UTCtime, not Zulu") ;
        return 0;
    }

    /* place month in buffer */
    buf[0] = '\0';
    switch(t.tm_mon) {
        case 0:  XSTRNCAT(buf, "Jan ", 5); break;
        case 1:  XSTRNCAT(buf, "Feb ", 5); break;
        case 2:  XSTRNCAT(buf, "Mar ", 5); break;
        case 3:  XSTRNCAT(buf, "Apr ", 5); break;
        case 4:  XSTRNCAT(buf, "May ", 5); break;
        case 5:  XSTRNCAT(buf, "Jun ", 5); break;
        case 6:  XSTRNCAT(buf, "Jul ", 5); break;
        case 7:  XSTRNCAT(buf, "Aug ", 5); break;
        case 8:  XSTRNCAT(buf, "Sep ", 5); break;
        case 9:  XSTRNCAT(buf, "Oct ", 5); break;
        case 10: XSTRNCAT(buf, "Nov ", 5); break;
        case 11: XSTRNCAT(buf, "Dec ", 5); break;
        default:
            return 0;

    }
    idx = 4; /* use idx now for char buffer */

    if (XSNPRINTF(buf + idx, len - idx, "%2d %02d:%02d:%02d %d GMT",
              t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, (int)t.tm_year + 1900)
        >= len - idx)
    {
        WOLFSSL_MSG("buffer overrun in GetTimeString");
        return 0;
    }

    return 1;
}
#endif /* OPENSSL_ALL || WOLFSSL_MYSQL_COMPATIBLE || WOLFSSL_NGINX || WOLFSSL_HAPROXY */


#if !defined(NO_ASN_TIME) && !defined(USER_TIME) && \
    !defined(TIME_OVERRIDES) && (defined(OPENSSL_EXTRA) || defined(HAVE_PKCS7))
/* Set current time string, either UTC or GeneralizedTime.
 * (void*) tm should be a pointer to time_t, output is placed in buf.
 *
 * Return time string length placed in buf on success, negative on error */
int GetAsnTimeString(void* currTime, byte* buf, word32 len)
{
    byte* data_ptr  = buf;
    byte  uf_time[ASN_GENERALIZED_TIME_SIZE];
    int data_len = 0;

    WOLFSSL_ENTER("GetAsnTimeString");

    if (buf == NULL || len == 0)
        return BAD_FUNC_ARG;

    XMEMSET(uf_time, 0, sizeof(uf_time));
    /* GetFormattedTime returns length with null terminator */
    data_len = GetFormattedTime(currTime, uf_time, (word32)sizeof(uf_time));
    if (data_len <= 0) {
        return ASN_TIME_E;
    }
    /* ensure room to add 2 bytes (ASN type and length) before proceeding */
    else if (len < (word32)data_len + 2) {
        return BUFFER_E;
    }

    if (data_len == ASN_UTC_TIME_SIZE-1) {
        /* increment data_len for ASN length byte after adding the data_ptr */
        *data_ptr = (byte)ASN_UTC_TIME; data_ptr++; data_len++;
        /* -1 below excludes null terminator */
        *data_ptr = (byte)ASN_UTC_TIME_SIZE - 1; data_ptr++; data_len++;
        XMEMCPY(data_ptr, (byte *)uf_time, ASN_UTC_TIME_SIZE - 1);
        data_ptr += ASN_UTC_TIME_SIZE - 1;
    }
    else if (data_len == ASN_GENERALIZED_TIME_SIZE-1) {
        /* increment data_len for ASN length byte after adding the data_ptr */
        *data_ptr = (byte)ASN_GENERALIZED_TIME; data_ptr++; data_len++;
        /* -1 below excludes null terminator */
        *data_ptr = (byte)ASN_GENERALIZED_TIME_SIZE - 1; data_ptr++; data_len++;
        XMEMCPY(data_ptr, (byte*)uf_time, ASN_GENERALIZED_TIME_SIZE - 1);
        data_ptr += ASN_GENERALIZED_TIME_SIZE - 1;
    }
    else {
        WOLFSSL_MSG("Invalid time size returned");
        return ASN_TIME_E;
    }
    /* append null terminator */
    *data_ptr = 0;

    /* return length without null terminator */
    return data_len;
}

/* return just the time string as either UTC or Generalized Time*/
int GetFormattedTime(void* currTime, byte* buf, word32 len)
{
    struct tm* ts      = NULL;
    struct tm* tmpTime = NULL;
    int year, mon, day, hour, mini, sec;
    int ret;
#if defined(NEED_TMP_TIME)
    struct tm tmpTimeStorage;
    tmpTime = &tmpTimeStorage;
#endif
    /* Needed in case XGMTIME does not use the tmpTime argument. */
    (void)tmpTime;

    WOLFSSL_ENTER("GetFormattedTime");

    if (buf == NULL || len == 0)
        return BAD_FUNC_ARG;

    ts = (struct tm *)XGMTIME((time_t*)currTime, tmpTime);
    if (ts == NULL) {
        WOLFSSL_MSG("failed to get time data.");
        return ASN_TIME_E;
    }

    /* Note ASN_UTC_TIME_SIZE and ASN_GENERALIZED_TIME_SIZE include space for
     * the null terminator. ASN encoded values leave off the terminator. */

    if (ts->tm_year >= 50 && ts->tm_year < 150) {
        /* UTC Time */
        if (ts->tm_year >= 50 && ts->tm_year < 100) {
            year = ts->tm_year;
        }
        else {
            year = ts->tm_year - 100;
        }
        mon  = ts->tm_mon + 1;
        day  = ts->tm_mday;
        hour = ts->tm_hour;
        mini = ts->tm_min;
        sec  = ts->tm_sec;
    #if defined(WOLF_C89)
        if (len < ASN_UTC_TIME_SIZE) {
            WOLFSSL_MSG("buffer for GetFormattedTime is too short.");
            return BUFFER_E;
        }
        ret = XSPRINTF((char*)buf,
                        "%02d%02d%02d%02d%02d%02dZ", year, mon, day,
                        hour, mini, sec);
    #else
        ret = XSNPRINTF((char*)buf, len,
                        "%02d%02d%02d%02d%02d%02dZ", year, mon, day,
                        hour, mini, sec);
    #endif
    }
    else {
        /* GeneralizedTime */
        year = ts->tm_year + 1900;
        mon  = ts->tm_mon + 1;
        day  = ts->tm_mday;
        hour = ts->tm_hour;
        mini = ts->tm_min;
        sec  = ts->tm_sec;
    #if defined(WOLF_C89)
        if (len < ASN_GENERALIZED_TIME_SIZE) {
            WOLFSSL_MSG("buffer for GetFormattedTime is too short.");
            return BUFFER_E;
        }
        ret = XSPRINTF((char*)buf,
                        "%4d%02d%02d%02d%02d%02dZ", year, mon, day,
                        hour, mini, sec);
    #else
        ret = XSNPRINTF((char*)buf, len,
                        "%4d%02d%02d%02d%02d%02dZ", year, mon, day,
                        hour, mini, sec);
    #endif
    }

    return ret;
}

#endif /* !NO_ASN_TIME && !USER_TIME && !TIME_OVERRIDES &&
        * (OPENSSL_EXTRA || HAVE_PKCS7) */

#if defined(USE_WOLF_VALIDDATE)

/* to the second */
int DateGreaterThan(const struct tm* a, const struct tm* b)
{
    if (a->tm_year > b->tm_year)
        return 1;

    if (a->tm_year == b->tm_year && a->tm_mon > b->tm_mon)
        return 1;

    if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
           a->tm_mday > b->tm_mday)
        return 1;

    if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
        a->tm_mday == b->tm_mday && a->tm_hour > b->tm_hour)
        return 1;

    if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
        a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
        a->tm_min > b->tm_min)
        return 1;

    if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
        a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
        a->tm_min  == b->tm_min  && a->tm_sec > b->tm_sec)
        return 1;

    return 0; /* false */
}


static WC_INLINE int DateLessThan(const struct tm* a, const struct tm* b)
{
    return DateGreaterThan(b,a);
}

/* like atoi but only use first byte */
/* Make sure before and after dates are valid */
int wc_ValidateDate(const byte* date, byte format, int dateType)
{
    time_t ltime;
    struct tm  certTime;
    struct tm* localTime;
    struct tm* tmpTime;
    int    i = 0;
    int    timeDiff = 0;
    int    diffHH = 0, diffMM = 0;

#if defined(NEED_TMP_TIME)
    struct tm tmpTimeStorage;
    tmpTime = &tmpTimeStorage;
#else
    tmpTime = NULL;
#endif
    (void)tmpTime;

    ltime = wc_Time(0);
    if (sizeof(ltime) == sizeof(word32) && (int)ltime < 0){
        /* A negative response here could be due to a 32-bit time_t
         * where the year is 2038 or later. */
        WOLFSSL_MSG("wc_Time failed to return a valid value");
        return 0;
    }

#ifdef WOLFSSL_BEFORE_DATE_CLOCK_SKEW
    if (dateType == BEFORE) {
        WOLFSSL_MSG("Skewing local time for before date check");
        ltime += WOLFSSL_BEFORE_DATE_CLOCK_SKEW;
    }
#endif

#ifdef WOLFSSL_AFTER_DATE_CLOCK_SKEW
    if (dateType == AFTER) {
        WOLFSSL_MSG("Skewing local time for after date check");
        ltime -= WOLFSSL_AFTER_DATE_CLOCK_SKEW;
    }
#endif

    if (!ExtractDate(date, format, &certTime, &i)) {
        WOLFSSL_MSG("Error extracting the date");
        return 0;
    }

    if ((date[i] == '+') || (date[i] == '-')) {
        int diffSign;

        WOLFSSL_MSG("Using time differential, not Zulu") ;
        diffSign = date[i++] == '+' ? 1 : -1 ;
        if (GetTime(&diffHH, date, &i) != 0)
            return 0;
        if (GetTime(&diffMM, date, &i) != 0)
            return 0;
        timeDiff = diffSign * (diffHH*60 + diffMM) * 60 ;
    } else if (date[i] != 'Z') {
        WOLFSSL_MSG("UTCtime, neither Zulu or time differential") ;
        return 0;
    }

    ltime -= (time_t)timeDiff ;
    localTime = XGMTIME(&ltime, tmpTime);

    if (localTime == NULL) {
        WOLFSSL_MSG("XGMTIME failed");
        return 0;
    }

    if (dateType == BEFORE) {
        if (DateLessThan(localTime, &certTime)) {
            WOLFSSL_MSG("Date BEFORE check failed");
            return 0;
        }
    }
    else {  /* dateType == AFTER */
        if (DateGreaterThan(localTime, &certTime)) {
            WOLFSSL_MSG("Date AFTER check failed");
            return 0;
        }
    }

    return 1;
}
#endif /* USE_WOLF_VALIDDATE */

int wc_GetTime(void* timePtr, word32 timeSize)
{
    time_t* ltime = (time_t*)timePtr;

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

    if ((word32)sizeof(time_t) > timeSize) {
        return BUFFER_E;
    }

    *ltime = wc_Time(0);

    return 0;
}

#ifdef TIME_OVERRIDES
    #ifndef HAVE_TIME_T_TYPE
        typedef long time_t;
    #endif
    extern time_t XTIME(time_t* t);
#endif

static wc_time_cb timeFunc = NULL;

int wc_SetTimeCb(wc_time_cb f)
{
    timeFunc = f;
    return 0;
}

time_t wc_Time(time_t* t)
{
    if (timeFunc != NULL) {
        return timeFunc(t);
    }
    return XTIME(t);
}

#endif /* !NO_ASN_TIME */


#ifdef WOLFSSL_ASN_TEMPLATE
/* TODO: use a CHOICE instead of two items? */
/* ASN.1 template for a date - either UTC or Generalized Time. */
static const ASNItem dateASN[] = {
/* UTC */ { 0, ASN_UTC_TIME, 0, 0, 2 },
/* GT  */ { 0, ASN_GENERALIZED_TIME, 0, 0, 2 },
};
enum {
    DATEASN_IDX_UTC = 0,
    DATEASN_IDX_GT
};

/* Number of items in ASN.1 template for a date. */
#define dateASN_Length (sizeof(dateASN) / sizeof(ASNItem))
#endif /* WOLFSSL_ASN_TEMPLATE */

/* Get date buffer, format and length. Returns 0=success or error */
/* Decode a DateInfo - choice of UTC TIME or GENERALIZED TIME.
 *
 * @param [in]      source   Buffer containing encoded date.
 * @param [in, out] idx      On in, the index of the date.
 *                           On out, index after date.
 * @param [out]     pDate    Pointer into buffer of data bytes.
 * @param [out]     pFormat  Format of date - BER/DER tag.
 * @param [out]     pLength  Length of date bytes.
 * @param [in]      maxIdx   Index of next item after date.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when source or idx is NULL.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 */
static int GetDateInfo(const byte* source, word32* idx, const byte** pDate,
                        byte* pFormat, int* pLength, word32 maxIdx)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int length;
    byte format;

    if (source == NULL || idx == NULL)
        return BAD_FUNC_ARG;

    /* get ASN format header */
    if (*idx+1 > maxIdx)
        return BUFFER_E;
    format = source[*idx];
    *idx += 1;
    if (format != ASN_UTC_TIME && format != ASN_GENERALIZED_TIME) {
        WOLFSSL_ERROR_VERBOSE(ASN_TIME_E);
        return ASN_TIME_E;
    }

    /* get length */
    if (GetLength(source, idx, &length, maxIdx) < 0)
        return ASN_PARSE_E;
    if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
        return ASN_DATE_SZ_E;

    /* return format, date and length */
    if (pFormat)
        *pFormat = format;
    if (pDate)
        *pDate = &source[*idx];
    if (pLength)
        *pLength = length;

    *idx += (word32)length;

    return 0;
#else
    ASNGetData dataASN[dateASN_Length];
    int ret = 0;

    if ((source == NULL) || (idx == NULL)) {
        ret = BAD_FUNC_ARG;
    }
    if (ret == 0) {
        /* Initialize data. */
        XMEMSET(dataASN, 0, sizeof(dataASN));
        /* Parse date. */
        ret = GetASN_Items(dateASN, dataASN, dateASN_Length, 0, source, idx,
                           maxIdx);
    }
    if (ret == 0) {
        /* Determine which tag was seen. */
        int i = (dataASN[DATEASN_IDX_UTC].tag != 0) ? DATEASN_IDX_UTC
                                                    : DATEASN_IDX_GT;
        /* Return data from seen item. */
        if (pFormat != NULL) {
            *pFormat = dataASN[i].tag;
        }
        if (pDate != NULL) {
            *pDate = dataASN[i].data.ref.data;
        }
        if (pLength != NULL) {
            *pLength = (int)dataASN[i].data.ref.length;
        }
    }

    return ret;
#endif
}

#ifndef WOLFSSL_ASN_TEMPLATE
static int GetDate(DecodedCert* cert, int dateType, int verify, int maxIdx)
{
    int    ret, length;
    const byte *datePtr = NULL;
    byte   date[MAX_DATE_SIZE];
    byte   format;
    word32 startIdx = 0;

    if (dateType == BEFORE)
        cert->beforeDate = &cert->source[cert->srcIdx];
    else
        cert->afterDate = &cert->source[cert->srcIdx];
    startIdx = cert->srcIdx;

    ret = GetDateInfo(cert->source, &cert->srcIdx, &datePtr, &format,
                      &length, (word32)maxIdx);
    if (ret < 0)
        return ret;

    XMEMSET(date, 0, MAX_DATE_SIZE);
    XMEMCPY(date, datePtr, (size_t)length);

    if (dateType == BEFORE)
        cert->beforeDateLen = (int)(cert->srcIdx - startIdx);
    else
        cert->afterDateLen  = (int)(cert->srcIdx - startIdx);

#ifndef NO_ASN_TIME_CHECK
    if (verify != NO_VERIFY && verify != VERIFY_SKIP_DATE &&
            !XVALIDATE_DATE(date, format, dateType)) {
        if (dateType == BEFORE) {
            WOLFSSL_ERROR_VERBOSE(ASN_BEFORE_DATE_E);
            return ASN_BEFORE_DATE_E;
        }
        else {
            WOLFSSL_ERROR_VERBOSE(ASN_AFTER_DATE_E);
            return ASN_AFTER_DATE_E;
        }
    }
#else
    (void)verify;
#endif

    return 0;
}

static int GetValidity(DecodedCert* cert, int verify, int maxIdx)
{
    int length;
    int badDate = 0;

    if (GetSequence(cert->source, &cert->srcIdx, &length, (word32)maxIdx) < 0)
        return ASN_PARSE_E;

    maxIdx = (int)cert->srcIdx + length;

    if (GetDate(cert, BEFORE, verify, maxIdx) < 0)
        badDate = ASN_BEFORE_DATE_E; /* continue parsing */

    if (GetDate(cert, AFTER, verify, maxIdx) < 0)
        return ASN_AFTER_DATE_E;

    if (badDate != 0)
        return badDate;

    return 0;
}
#endif /* !WOLFSSL_ASN_TEMPLATE */


int wc_GetDateInfo(const byte* certDate, int certDateSz, const byte** date,
    byte* format, int* length)
{
    int ret;
    word32 idx = 0;

    ret = GetDateInfo(certDate, &idx, date, format, length, (word32)certDateSz);

    return ret;
}

#ifndef NO_ASN_TIME
int wc_GetDateAsCalendarTime(const byte* date, int length, byte format,
    struct tm* timearg)
{
    int idx = 0;
    (void)length;
    if (!ExtractDate(date, format, timearg, &idx))
        return ASN_TIME_E;
    return 0;
}

#if defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_ALT_NAMES)
int wc_GetCertDates(Cert* cert, struct tm* before, struct tm* after)
{
    int ret = 0;
    const byte* date;
    byte format;
    int length;

    if (cert == NULL)
        return BAD_FUNC_ARG;

    if (before && cert->beforeDateSz > 0) {
        ret = wc_GetDateInfo(cert->beforeDate, cert->beforeDateSz, &date,
                             &format, &length);
        if (ret == 0)
            ret = wc_GetDateAsCalendarTime(date, length, format, before);
    }
    if (after && cert->afterDateSz > 0) {
        ret = wc_GetDateInfo(cert->afterDate, cert->afterDateSz, &date,
                             &format, &length);
        if (ret == 0)
            ret = wc_GetDateAsCalendarTime(date, length, format, after);
    }

    return ret;
}
#endif /* WOLFSSL_CERT_GEN && WOLFSSL_ALT_NAMES */
#endif /* !NO_ASN_TIME */

#ifndef WOLFSSL_ASN_TEMPLATE
static int GetSigAlg(DecodedCert* cert, word32* sigOid, word32 maxIdx)
{
    int length;
    word32 endSeqIdx;

    if (GetSequence(cert->source, &cert->srcIdx, &length, maxIdx) < 0)
        return ASN_PARSE_E;
    endSeqIdx = cert->srcIdx + (word32)length;

    if (GetObjectId(cert->source, &cert->srcIdx, sigOid, oidSigType,
                    maxIdx) < 0) {
        return ASN_OBJECT_ID_E;
    }

    if (cert->srcIdx != endSeqIdx) {
#ifdef WC_RSA_PSS
        if (*sigOid == CTC_RSASSAPSS) {
            cert->sigParamsIndex = cert->srcIdx;
            cert->sigParamsLength = endSeqIdx - cert->srcIdx;
        }
        else
#endif
        /* Only allowed a ASN NULL header with zero length. */
        if  (endSeqIdx - cert->srcIdx != 2)
            return ASN_PARSE_E;
        else {
            byte tag;
            if (GetASNTag(cert->source, &cert->srcIdx, &tag, endSeqIdx) != 0)
                return ASN_PARSE_E;
            if (tag != ASN_TAG_NULL)
                return ASN_PARSE_E;
        }
    }

    cert->srcIdx = endSeqIdx;

    return 0;
}
#endif

#ifdef WOLFSSL_ASN_TEMPLATE
/* TODO: move code around to not require this. */
static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt,
                              int* badDateRet, int stopAtPubKey,
                              int stopAfterPubKey);
#endif

/* Parse the certificate up to the X.509 public key.
 *
 * If cert data is invalid then badDate get set to error value.
 *
 * @param [in, out] cert     Decoded certificate object.
 * @param [in]      verify   Whether to verify dates.
 * @param [out]     badDate  Error code when verify dates.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when cert or badDate is NULL.
 * @return  ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
 * @return  ASN_DATE_SZ_E when time data is not supported.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
 * @return  ASN_EXPECT_0_E when the INTEGER has the MSB set.
 */
int wc_GetPubX509(DecodedCert* cert, int verify, int* badDate)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int ret;

    if (cert == NULL || badDate == NULL)
        return BAD_FUNC_ARG;

    *badDate = 0;
    if ( (ret = GetCertHeader(cert)) < 0)
        return ret;

    WOLFSSL_MSG("Got Cert Header");

#ifdef WOLFSSL_CERT_REQ
    if (!cert->isCSR) {
#endif
        /* Using the sigIndex as the upper bound because that's where the
         * actual certificate data ends. */
        if ((ret = GetSigAlg(cert, &cert->signatureOID, cert->sigIndex)) < 0)
            return ret;

        WOLFSSL_MSG("Got Algo ID");

        if ( (ret = GetName(cert, ISSUER, (int)cert->sigIndex)) < 0)
            return ret;

        if ( (ret = GetValidity(cert, verify, (int)cert->sigIndex)) < 0)
            *badDate = ret;
#ifdef WOLFSSL_CERT_REQ
    }
#endif

    if ( (ret = GetName(cert, SUBJECT, (int)cert->sigIndex)) < 0)
        return ret;

    WOLFSSL_MSG("Got Subject Name");
    return ret;
#else
    /* Use common decode routine and stop at public key. */
    int ret;

    *badDate = 0;

    ret = DecodeCertInternal(cert, verify, NULL, badDate, 1, 0);
    if (ret >= 0) {
        /* Store current index: public key. */
        cert->srcIdx = (word32)ret;
    }
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

/* Parse the certificate up to and including X.509 public key.
 *
 * @param [in, out] cert     Decoded certificate object.
 * @param [in]      verify   Whether to verify dates.
 * @return  0 on success.
 * @return  ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
 * @return  ASN_DATE_SZ_E when time data is not supported.
 * @return  ASN_BEFORE_DATE_E when BEFORE date is invalid.
 * @return  ASN_AFTER_DATE_E when AFTER date is invalid.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
 * @return  ASN_BITSTR_E when the expected BIT_STRING tag is not found.
 * @return  ASN_EXPECT_0_E when the INTEGER has the MSB set.
 */
int DecodeToKey(DecodedCert* cert, int verify)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int badDate = 0;
    int ret;

    if ( (ret = wc_GetPubX509(cert, verify, &badDate)) < 0)
        return ret;

    /* Determine if self signed */
#ifdef WOLFSSL_CERT_REQ
    if (cert->isCSR)
        cert->selfSigned = 1;
    else
#endif
    {
        cert->selfSigned = XMEMCMP(cert->issuerHash,
                                   cert->subjectHash,
                                   KEYID_SIZE) == 0 ? 1 : 0;
    }

    ret = GetCertKey(cert, cert->source, &cert->srcIdx, cert->maxIdx);
    if (ret != 0)
        return ret;

    WOLFSSL_MSG("Got Key");

    if (badDate != 0)
        return badDate;

    return ret;
#else
    int ret;
    int badDate = 0;

    /* Call internal version and stop after public key. */
    ret = DecodeCertInternal(cert, verify, NULL, &badDate, 0, 1);
    /* Always return date errors. */
    if (ret == 0) {
        ret = badDate;
    }
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

#if !defined(NO_CERTS) && !defined(WOLFSSL_ASN_TEMPLATE)
static int GetSignature(DecodedCert* cert)
{
    int length;
    int ret;

    ret = CheckBitString(cert->source, &cert->srcIdx, &length, cert->maxIdx, 1,
                         NULL);
    if (ret != 0)
        return ret;

    cert->sigLength = (word32)length;
    cert->signature = &cert->source[cert->srcIdx];
    cert->srcIdx += cert->sigLength;

    if (cert->srcIdx != cert->maxIdx)
        return ASN_PARSE_E;

    return 0;
}
#endif /* !NO_CERTS && !WOLFSSL_ASN_TEMPLATE */

#ifndef WOLFSSL_ASN_TEMPLATE
static word32 SetOctetString8Bit(word32 len, byte* output)
{
    output[0] = ASN_OCTET_STRING;
    output[1] = (byte)len;
    return 2;
}
static word32 SetDigest(const byte* digest, word32 digSz, byte* output)
{
    word32 idx = SetOctetString8Bit(digSz, output);
    XMEMCPY(&output[idx], digest, digSz);

    return idx + digSz;
}
#endif


/* Encode a length for DER.
 *
 * @param [in]  length  Value to encode.
 * @param [out] output  Buffer to encode into.
 * @return  Number of bytes encoded.
 */
word32 SetLength(word32 length, byte* output)
{
    /* Start encoding at start of buffer. */
    word32 i = 0;

    if (length < ASN_LONG_LENGTH) {
        /* Only one byte needed to encode. */
        if (output) {
            /* Write out length value. */
            output[i] = (byte)length;
        }
        /* Skip over length. */
        i++;
    }
    else {
        /* Calculate the number of bytes required to encode value. */
        byte j = (byte)BytePrecision(length);

        if (output) {
            /* Encode count byte. */
            output[i] = (byte)(j | ASN_LONG_LENGTH);
        }
        /* Skip over count byte. */
        i++;

        /* Encode value as a big-endian byte array. */
        for (; j > 0; --j) {
            if (output) {
                /* Encode next most-significant byte. */
                output[i] = (byte)(length >> ((j - 1) * WOLFSSL_BIT_SIZE));
            }
            /* Skip over byte. */
            i++;
        }
    }

    /* Return number of bytes in encoded length. */
    return i;
}

/* Encode a DER header - type/tag and length.
 *
 * @param [in]  tag     DER tag of ASN.1 item.
 * @param [in]  len     Length of data in ASN.1 item.
 * @param [out] output  Buffer to encode into.
 * @return  Number of bytes encoded.
 */
static word32 SetHeader(byte tag, word32 len, byte* output)
{
    if (output) {
        /* Encode tag first. */
        output[0] = tag;
    }
    /* Encode the length. */
    return SetLength(len, output ? output + ASN_TAG_SZ : NULL) + ASN_TAG_SZ;
}

/* Encode a SEQUENCE header in DER.
 *
 * @param [in]  len     Length of data in SEQUENCE.
 * @param [out] output  Buffer to encode into.
 * @return  Number of bytes encoded.
 */
word32 SetSequence(word32 len, byte* output)
{
    return SetHeader(ASN_SEQUENCE | ASN_CONSTRUCTED, len, output);
}

/* Encode an OCTET STRING header in DER.
 *
 * @param [in]  len     Length of data in OCTET STRING.
 * @param [out] output  Buffer to encode into.
 * @return  Number of bytes encoded.
 */
word32 SetOctetString(word32 len, byte* output)
{
    return SetHeader(ASN_OCTET_STRING, len, output);
}

/* Encode a SET header in DER.
 *
 * @param [in]  len     Length of data in SET.
 * @param [out] output  Buffer to encode into.
 * @return  Number of bytes encoded.
 */
word32 SetSet(word32 len, byte* output)
{
    return SetHeader(ASN_SET | ASN_CONSTRUCTED, len, output);
}

/* Encode an implicit context specific header in DER.
 *
 * Implicit means that it is constructed only if the included ASN.1 item is.
 *
 * @param [in]  tag     Tag for the implicit ASN.1 item.
 * @param [in]  number  Context specific number.
 * @param [in]  len     Length of data in SET.
 * @param [out] output  Buffer to encode into.
 * @return  Number of bytes encoded.
 */
word32 SetImplicit(byte tag, byte number, word32 len, byte* output)
{
    tag = (byte)(((tag == ASN_SEQUENCE || tag == ASN_SET) ? ASN_CONSTRUCTED : 0)
                 | ASN_CONTEXT_SPECIFIC | number);
    return SetHeader(tag, len, output);
}

/* Encode an explicit context specific header in DER.
 *
 * Explicit means that there will be an ASN.1 item underneath.
 *
 * @param [in]  number  Context specific number.
 * @param [in]  len     Length of data in SET.
 * @param [out] output  Buffer to encode into.
 * @return  Number of bytes encoded.
 */
word32 SetExplicit(byte number, word32 len, byte* output)
{
    return SetHeader((byte)(ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | number),
                     len, output);
}

#if defined(OPENSSL_EXTRA)
/* Encode an Othername into DER.
 *
 * @param [in]  name    Pointer to the WOLFSSL_ASN1_OTHERNAME to be encoded.
 * @param [out] output  Buffer to encode into. If NULL, don't encode.
 * @return  Number of bytes encoded or WOLFSSL_FAILURE if name parameter is bad.
 */
word32 SetOthername(void *name, byte *output)
{
    WOLFSSL_ASN1_OTHERNAME *nm = (WOLFSSL_ASN1_OTHERNAME *)name;
    char *nameStr = NULL;
    int nameSz = 0;
    word32 len = 0;

    if ((nm == NULL) || (nm->value == NULL)) {
        WOLFSSL_MSG("otherName value is NULL");
        return WOLFSSL_FAILURE;
    }

    nameStr = nm->value->value.utf8string->data;
    nameSz = nm->value->value.utf8string->length;

    len = nm->type_id->objSz +
          SetHeader(ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC, nameSz + 2, NULL) +
          SetHeader(CTC_UTF8, nameSz, NULL) + nameSz;

    if (output != NULL) {
        /* otherName OID */
        XMEMCPY(output, nm->type_id->obj, nm->type_id->objSz);
        output += nm->type_id->objSz;

        output += SetHeader(ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC, nameSz + 2,
                            output);

        output += SetHeader(CTC_UTF8, nameSz, output);

        XMEMCPY(output, nameStr, nameSz);
    }

    return len;
}
#endif /* OPENSSL_EXTRA */

#if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)

static int SetCurve(ecc_key* key, byte* output, size_t outSz)
{
#ifdef HAVE_OID_ENCODING
    int ret;
#endif
    int idx;
    word32 oidSz = 0;

    /* validate key */
    if (key == NULL || key->dp == NULL) {
        return BAD_FUNC_ARG;
    }

#ifdef HAVE_OID_ENCODING
    ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, NULL, &oidSz);
    if (ret != 0) {
        return ret;
    }
#else
    oidSz = key->dp->oidSz;
#endif

    idx = SetObjectId((int)oidSz, output);

    /* length only */
    if (output == NULL) {
        return idx + (int)oidSz;
    }

    /* verify output buffer has room */
    if (oidSz > outSz)
        return BUFFER_E;

#ifdef HAVE_OID_ENCODING
    ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, output+idx, &oidSz);
    if (ret != 0) {
        return ret;
    }
#else
    XMEMCPY(output+idx, key->dp->oid, oidSz);
#endif
    idx += (int)oidSz;

    return idx;
}

#endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */


#ifdef HAVE_ECC
/* Determines whether the signature algorithm is using ECDSA.
 *
 * @param [in] algoOID  Signature algorithm identifier.
 * @return  1 when algorithm is using ECDSA.
 * @return  0 otherwise.
 */
static WC_INLINE int IsSigAlgoECDSA(word32 algoOID)
{
    /* ECDSA sigAlgo must not have ASN1 NULL parameters */
    if (algoOID == CTC_SHAwECDSA || algoOID == CTC_SHA256wECDSA ||
        algoOID == CTC_SHA384wECDSA || algoOID == CTC_SHA512wECDSA) {
        return 1;
    }

    return 0;
}
#endif

/* Determines if OID is for an EC signing algorithm including ECDSA and EdDSA
 * and post-quantum algorithms.
 *
 * @param [in] algoOID  Algorithm OID.
 * @return  1 when is EC signing algorithm.
 * @return  0 otherwise.
 */
static WC_INLINE int IsSigAlgoECC(word32 algoOID)
{
    (void)algoOID;

    return (0
        #ifdef HAVE_ECC
              || IsSigAlgoECDSA(algoOID)
        #endif
        #ifdef HAVE_ED25519
              || (algoOID == ED25519k)
        #endif
        #ifdef HAVE_CURVE25519
              || (algoOID == X25519k)
        #endif
        #ifdef HAVE_ED448
              || (algoOID == ED448k)
        #endif
        #ifdef HAVE_CURVE448
              || (algoOID == X448k)
        #endif
        #ifdef HAVE_PQC
        #ifdef HAVE_FACON
              || (algoOID == FALCON_LEVEL1k)
              || (algoOID == FALCON_LEVEL5k)
        #endif
        #ifdef HAVE_DILITHIUM
              || (algoOID == DILITHIUM_LEVEL2k)
              || (algoOID == DILITHIUM_LEVEL3k)
              || (algoOID == DILITHIUM_LEVEL5k)
        #endif
        #ifdef HAVE_SPHINCS
              || (algoOID == SPHINCS_FAST_LEVEL1k)
              || (algoOID == SPHINCS_FAST_LEVEL3k)
              || (algoOID == SPHINCS_FAST_LEVEL5k)
              || (algoOID == SPHINCS_SMALL_LEVEL1k)
              || (algoOID == SPHINCS_SMALL_LEVEL3k)
              || (algoOID == SPHINCS_SMALL_LEVEL5k)
        #endif
        #endif /* HAVE_PQC */
    );
}

/* Encode an algorithm identifier.
 *
 * [algoOID, type] is unique.
 *
 * @param [in]  algoOID   Algorithm identifier.
 * @param [out] output    Buffer to hold encoding.
 * @param [in]  type      Type of OID being encoded.
 * @param [in]  curveSz   Add extra space for curve data.
 * @return  Encoded data size on success.
 * @return  0 when dynamic memory allocation fails.
 */
word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 tagSz, idSz, seqSz, algoSz = 0;
    const  byte* algoName = 0;
    byte   ID_Length[1 + MAX_LENGTH_SZ];
    byte   seqArray[MAX_SEQ_SZ + 1];  /* add object_id to end */
    word32    length = 0;

    tagSz = (type == oidHashType ||
             (type == oidSigType && !IsSigAlgoECC((word32)algoOID)) ||
             (type == oidKeyType && algoOID == RSAk)) ? 2U : 0U;
    algoName = OidFromId((word32)algoOID, (word32)type, &algoSz);
    if (algoName == NULL) {
        WOLFSSL_MSG("Unknown Algorithm");
        return 0;
    }

    idSz  = (word32)SetObjectId((int)algoSz, ID_Length);
    seqSz = SetSequence(idSz + algoSz + tagSz + (word32)curveSz, seqArray);

    /* Copy only algo to output for DSA keys */
    if (algoOID == DSAk && output) {
        XMEMCPY(output, ID_Length, idSz);
        XMEMCPY(output + idSz, algoName, algoSz);
        if (tagSz == 2)
            SetASNNull(&output[seqSz + idSz + algoSz]);
    }
    else if (output) {
        XMEMCPY(output, seqArray, seqSz);
        XMEMCPY(output + seqSz, ID_Length, idSz);
        XMEMCPY(output + seqSz + idSz, algoName, algoSz);
        if (tagSz == 2)
            SetASNNull(&output[seqSz + idSz + algoSz]);
    }

    if (algoOID == DSAk)
        length = idSz + algoSz + tagSz;
    else
        length = seqSz + idSz + algoSz + tagSz;

    return length;
#else
    DECL_ASNSETDATA(dataASN, algoIdASN_Length);
    int ret = 0;
    const byte* algoName = 0;
    word32 algoSz = 0;

    CALLOC_ASNSETDATA(dataASN, algoIdASN_Length, ret, NULL);

    algoName = OidFromId((word32)algoOID, (word32)type, &algoSz);
    if (algoName == NULL) {
        WOLFSSL_MSG("Unknown Algorithm");
    }
    else {
        int sz;
        int o = 0;

        /* Set the OID and OID type to encode. */
        SetASN_OID(&dataASN[ALGOIDASN_IDX_OID], (word32)algoOID, (word32)type);
        /* Hashes, signatures not ECC and keys not RSA output NULL tag. */
        if (!(type == oidHashType ||
                 (type == oidSigType && !IsSigAlgoECC((word32)algoOID)) ||
                 (type == oidKeyType && algoOID == RSAk))) {
            /* Don't put out NULL DER item. */
            dataASN[ALGOIDASN_IDX_NULL].noOut = 1;
        }
        if (algoOID == DSAk) {
            /* Don't include SEQUENCE for DSA keys. */
            o = 1;
        }
        else if (curveSz > 0) {
            /* Don't put out NULL DER item. */
            dataASN[ALGOIDASN_IDX_NULL].noOut = 0;
            /* Include space for extra data of length curveSz.
             * Subtract 1 for sequence and 1 for length encoding. */
            SetASN_Buffer(&dataASN[ALGOIDASN_IDX_NULL], NULL,
                          (word32)curveSz - 2);
        }

        /* Calculate size of encoding. */
        ret = SizeASN_Items(algoIdASN + o, dataASN + o,
                            (int)algoIdASN_Length - (int)o, &sz);
        if (ret == 0 && output != NULL) {
            /* Encode into buffer. */
            SetASN_Items(algoIdASN + o, dataASN + o,
                         (int)algoIdASN_Length - (int)o, output);
            if (curveSz > 0) {
                /* Return size excluding curve data. */
                sz = (int)(dataASN[o].offset -
                           dataASN[ALGOIDASN_IDX_NULL].offset);
            }
        }

        if (ret == 0) {
            /* Return encoded size. */
            ret = sz;
        }
        else {
            /* Unsigned return type so 0 indicates error. */
            ret = 0;
        }
    }

    FREE_ASNSETDATA(dataASN, NULL);
    return (word32)ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

#ifdef WOLFSSL_ASN_TEMPLATE
/* Always encode PKCS#1 v1.5 RSA signature and compare to encoded data. */
/* ASN.1 template for DigestInfo for a PKCS#1 v1.5 RSA signature.
 * PKCS#1 v2.2: RFC 8017, A.2.4 - DigestInfo
 */
static const ASNItem digestInfoASN[] = {
/* SEQ          */ { 0, ASN_SEQUENCE, 1, 1, 0 },
                                         /* digestAlgorithm */
/* DIGALGO_SEQ  */     { 1, ASN_SEQUENCE, 1, 1, 0 },
/* DIGALGO_OID  */         { 2, ASN_OBJECT_ID, 0, 0, 0 },
/* DIGALGO_NULL */         { 2, ASN_TAG_NULL, 0, 0, 0 },
                                         /* digest */
/* DIGEST       */     { 1, ASN_OCTET_STRING, 0, 0, 0 }
};
enum {
    DIGESTINFOASN_IDX_SEQ = 0,
    DIGESTINFOASN_IDX_DIGALGO_SEQ,
    DIGESTINFOASN_IDX_DIGALGO_OID,
    DIGESTINFOASN_IDX_DIGALGO_NULL,
    DIGESTINFOASN_IDX_DIGEST
};

/* Number of items in ASN.1 template for DigestInfo for RSA. */
#define digestInfoASN_Length (sizeof(digestInfoASN) / sizeof(ASNItem))
#endif

/* Encode signature.
 *
 * @param [out] out     Buffer to hold encoding.
 * @param [in]  digest  Buffer holding digest.
 * @param [in]  digSz   Length of digest in bytes.
 * @return  Encoded data size on success.
 * @return  0 when dynamic memory allocation fails.
 */
word32 wc_EncodeSignature(byte* out, const byte* digest, word32 digSz,
                          int hashOID)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    byte digArray[MAX_ENCODED_DIG_SZ];
    byte algoArray[MAX_ALGO_SZ];
    byte seqArray[MAX_SEQ_SZ];
    word32 encDigSz, algoSz, seqSz;

    encDigSz = SetDigest(digest, digSz, digArray);
    algoSz   = SetAlgoID(hashOID, algoArray, oidHashType, 0);
    seqSz    = SetSequence(encDigSz + algoSz, seqArray);

    XMEMCPY(out, seqArray, seqSz);
    XMEMCPY(out + seqSz, algoArray, algoSz);
    XMEMCPY(out + seqSz + algoSz, digArray, encDigSz);

    return encDigSz + algoSz + seqSz;
#else
    DECL_ASNSETDATA(dataASN, digestInfoASN_Length);
    int ret = 0;
    int sz;
    unsigned char dgst[WC_MAX_DIGEST_SIZE];

    CALLOC_ASNSETDATA(dataASN, digestInfoASN_Length, ret, NULL);

    if (ret == 0) {
        /* Set hash OID and type. */
        SetASN_OID(&dataASN[DIGESTINFOASN_IDX_DIGALGO_OID], (word32)hashOID,
                   oidHashType);
        /* Set digest. */
        if (digest == out) {
            XMEMCPY(dgst, digest, digSz);
            digest = dgst;
        }
        SetASN_Buffer(&dataASN[DIGESTINFOASN_IDX_DIGEST], digest, digSz);

        /* Calculate size of encoding. */
        ret = SizeASN_Items(digestInfoASN, dataASN, digestInfoASN_Length, &sz);
    }
    if (ret == 0) {
        /* Encode PKCS#1 v1.5 RSA signature. */
        SetASN_Items(digestInfoASN, dataASN, digestInfoASN_Length, out);
        ret = sz;
    }
    else {
        /* Unsigned return type so 0 indicates error. */
        ret = 0;
    }

    FREE_ASNSETDATA(dataASN, NULL);
    return (word32)ret;
#endif
}


#ifndef NO_CERTS

int wc_GetCTC_HashOID(int type)
{
    int ret;
    enum wc_HashType hType;

    hType = wc_HashTypeConvert(type);
    ret = wc_HashGetOID(hType);
    if (ret < 0) {
        ret = 0; /* backwards compatibility */
    }

    return ret;
}

/* Initialize a signature context object.
 *
 * Object used for signing and verifying a certificate signature.
 *
 * @param [in, out] sigCtx  Signature context object.
 * @param [in]      heap    Dynamic memory hint.
 * @param [in]      devId   Hardware device identifier.
 */
void InitSignatureCtx(SignatureCtx* sigCtx, void* heap, int devId)
{
    if (sigCtx) {
        XMEMSET(sigCtx, 0, sizeof(SignatureCtx));
        sigCtx->devId = devId;
        sigCtx->heap = heap;
    }
}

/* Free dynamic data in a signature context object.
 *
 * @param [in, out] sigCtx  Signature context object.
 */
void FreeSignatureCtx(SignatureCtx* sigCtx)
{
    if (sigCtx == NULL)
        return;

    if (sigCtx->digest) {
        XFREE(sigCtx->digest, sigCtx->heap, DYNAMIC_TYPE_DIGEST);
        sigCtx->digest = NULL;
    }
#if !(defined(NO_RSA) && defined(NO_DSA))
    if (sigCtx->sigCpy) {
        XFREE(sigCtx->sigCpy, sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
        sigCtx->sigCpy = NULL;
    }
#endif
#ifndef NO_ASN_CRYPT
    if (sigCtx->key.ptr) {
        switch (sigCtx->keyOID) {
        #ifndef NO_RSA
            #ifdef WC_RSA_PSS
            case RSAPSSk:
            #endif
            case RSAk:
                wc_FreeRsaKey(sigCtx->key.rsa);
                XFREE(sigCtx->key.rsa, sigCtx->heap, DYNAMIC_TYPE_RSA);
                sigCtx->key.rsa = NULL;
                break;
        #endif /* !NO_RSA */
        #ifndef NO_DSA
            case DSAk:
                wc_FreeDsaKey(sigCtx->key.dsa);
                XFREE(sigCtx->key.dsa, sigCtx->heap, DYNAMIC_TYPE_DSA);
                sigCtx->key.dsa = NULL;
                break;
        #endif
        #ifdef HAVE_ECC
            case ECDSAk:
            #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
                defined(WC_ASYNC_ENABLE_ECC)
                if (sigCtx->key.ecc->nb_ctx != NULL) {
                    XFREE(sigCtx->key.ecc->nb_ctx, sigCtx->heap,
                          DYNAMIC_TYPE_TMP_BUFFER);
                }
            #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
                      WC_ASYNC_ENABLE_ECC */
                wc_ecc_free(sigCtx->key.ecc);
                XFREE(sigCtx->key.ecc, sigCtx->heap, DYNAMIC_TYPE_ECC);
                sigCtx->key.ecc = NULL;
                break;
        #endif /* HAVE_ECC */
        #ifdef HAVE_ED25519
            case ED25519k:
                wc_ed25519_free(sigCtx->key.ed25519);
                XFREE(sigCtx->key.ed25519, sigCtx->heap, DYNAMIC_TYPE_ED25519);
                sigCtx->key.ed25519 = NULL;
                break;
        #endif /* HAVE_ED25519 */
        #ifdef HAVE_ED448
            case ED448k:
                wc_ed448_free(sigCtx->key.ed448);
                XFREE(sigCtx->key.ed448, sigCtx->heap, DYNAMIC_TYPE_ED448);
                sigCtx->key.ed448 = NULL;
                break;
        #endif /* HAVE_ED448 */
        #if defined(HAVE_PQC)
        #if defined(HAVE_FALCON)
            case FALCON_LEVEL1k:
            case FALCON_LEVEL5k:
                wc_falcon_free(sigCtx->key.falcon);
                XFREE(sigCtx->key.falcon, sigCtx->heap,
                      DYNAMIC_TYPE_FALCON);
                sigCtx->key.falcon = NULL;
                break;
        #endif /* HAVE_FALCON */
        #if defined(HAVE_DILITHIUM)
            case DILITHIUM_LEVEL2k:
            case DILITHIUM_LEVEL3k:
            case DILITHIUM_LEVEL5k:
                wc_dilithium_free(sigCtx->key.dilithium);
                XFREE(sigCtx->key.dilithium, sigCtx->heap,
                      DYNAMIC_TYPE_DILITHIUM);
                sigCtx->key.dilithium = NULL;
                break;
        #endif /* HAVE_DILITHIUM */
        #if defined(HAVE_SPHINCS)
            case SPHINCS_FAST_LEVEL1k:
            case SPHINCS_FAST_LEVEL3k:
            case SPHINCS_FAST_LEVEL5k:
            case SPHINCS_SMALL_LEVEL1k:
            case SPHINCS_SMALL_LEVEL3k:
            case SPHINCS_SMALL_LEVEL5k:
                wc_sphincs_free(sigCtx->key.sphincs);
                XFREE(sigCtx->key.sphincs, sigCtx->heap,
                      DYNAMIC_TYPE_SPHINCS);
                sigCtx->key.sphincs = NULL;
                break;
        #endif /* HAVE_SPHINCS */
        #endif /* HAVE_PQC  */
            default:
                break;
        } /* switch (keyOID) */
        sigCtx->key.ptr = NULL;
    }
#endif

    /* reset state, we are done */
    sigCtx->state = SIG_STATE_BEGIN;
}

#if !defined(NO_ASN_CRYPT) && !defined(NO_HASH_WRAPPER)
static int HashForSignature(const byte* buf, word32 bufSz, word32 sigOID,
                            byte* digest, int* typeH, int* digestSz, int verify)
{
    int ret = 0;

    switch (sigOID) {
    #if defined(WOLFSSL_MD2)
        case CTC_MD2wRSA:
            if (!verify) {
                ret = HASH_TYPE_E;
                WOLFSSL_MSG("MD2 not supported for signing");
            }
            else if ((ret = wc_Md2Hash(buf, bufSz, digest)) == 0) {
                *typeH    = MD2h;
                *digestSz = MD2_DIGEST_SIZE;
            }
        break;
    #endif
    #ifndef NO_MD5
        case CTC_MD5wRSA:
            if ((ret = wc_Md5Hash(buf, bufSz, digest)) == 0) {
                *typeH    = MD5h;
                *digestSz = WC_MD5_DIGEST_SIZE;
            }
            break;
    #endif
    #ifndef NO_SHA
        case CTC_SHAwRSA:
        case CTC_SHAwDSA:
        case CTC_SHAwECDSA:
            if ((ret = wc_ShaHash(buf, bufSz, digest)) == 0) {
                *typeH    = SHAh;
                *digestSz = WC_SHA_DIGEST_SIZE;
            }
            break;
    #endif
    #ifdef WOLFSSL_SHA224
        case CTC_SHA224wRSA:
        case CTC_SHA224wECDSA:
            if ((ret = wc_Sha224Hash(buf, bufSz, digest)) == 0) {
                *typeH    = SHA224h;
                *digestSz = WC_SHA224_DIGEST_SIZE;
            }
            break;
    #endif
    #ifndef NO_SHA256
        case CTC_SHA256wRSA:
        case CTC_SHA256wECDSA:
        case CTC_SHA256wDSA:
            if ((ret = wc_Sha256Hash(buf, bufSz, digest)) == 0) {
                *typeH    = SHA256h;
                *digestSz = WC_SHA256_DIGEST_SIZE;
            }
            break;
    #endif
    #ifdef WOLFSSL_SHA384
        case CTC_SHA384wRSA:
        case CTC_SHA384wECDSA:
            if ((ret = wc_Sha384Hash(buf, bufSz, digest)) == 0) {
                *typeH    = SHA384h;
                *digestSz = WC_SHA384_DIGEST_SIZE;
            }
            break;
    #endif
    #ifdef WOLFSSL_SHA512
        case CTC_SHA512wRSA:
        case CTC_SHA512wECDSA:
            if ((ret = wc_Sha512Hash(buf, bufSz, digest)) == 0) {
                *typeH    = SHA512h;
                *digestSz = WC_SHA512_DIGEST_SIZE;
            }
            break;
    #endif
    #ifdef WOLFSSL_SHA3
    #ifndef WOLFSSL_NOSHA3_224
        case CTC_SHA3_224wRSA:
        case CTC_SHA3_224wECDSA:
            if ((ret = wc_Sha3_224Hash(buf, bufSz, digest)) == 0) {
                *typeH    = SHA3_224h;
                *digestSz = WC_SHA3_224_DIGEST_SIZE;
            }
            break;
    #endif
    #ifndef WOLFSSL_NOSHA3_256
        case CTC_SHA3_256wRSA:
        case CTC_SHA3_256wECDSA:
            if ((ret = wc_Sha3_256Hash(buf, bufSz, digest)) == 0) {
                *typeH    = SHA3_256h;
                *digestSz = WC_SHA3_256_DIGEST_SIZE;
            }
            break;
    #endif
    #ifndef WOLFSSL_NOSHA3_384
        case CTC_SHA3_384wRSA:
        case CTC_SHA3_384wECDSA:
            if ((ret = wc_Sha3_384Hash(buf, bufSz, digest)) == 0) {
                *typeH    = SHA3_384h;
                *digestSz = WC_SHA3_384_DIGEST_SIZE;
            }
            break;
    #endif
    #ifndef WOLFSSL_NOSHA3_512
        case CTC_SHA3_512wRSA:
        case CTC_SHA3_512wECDSA:
            if ((ret = wc_Sha3_512Hash(buf, bufSz, digest)) == 0) {
                *typeH    = SHA3_512h;
                *digestSz = WC_SHA3_512_DIGEST_SIZE;
            }
            break;
    #endif
    #endif
    #ifdef HAVE_ED25519
        case CTC_ED25519:
            /* Hashes done in signing operation.
             * Two dependent hashes with prefixes performed.
             */
            break;
    #endif
    #ifdef HAVE_ED448
        case CTC_ED448:
            /* Hashes done in signing operation.
             * Two dependent hashes with prefixes performed.
             */
            break;
    #endif
    #ifdef HAVE_PQC
    #ifdef HAVE_FALCON
        case CTC_FALCON_LEVEL1:
        case CTC_FALCON_LEVEL5:
            /* Hashes done in signing operation. */
            break;
    #endif
    #ifdef HAVE_DILITHIUM
        case CTC_DILITHIUM_LEVEL2:
        case CTC_DILITHIUM_LEVEL3:
        case CTC_DILITHIUM_LEVEL5:
            /* Hashes done in signing operation. */
            break;
    #endif
    #ifdef HAVE_SPHINCS
        case CTC_SPHINCS_FAST_LEVEL1:
        case CTC_SPHINCS_FAST_LEVEL3:
        case CTC_SPHINCS_FAST_LEVEL5:
        case CTC_SPHINCS_SMALL_LEVEL1:
        case CTC_SPHINCS_SMALL_LEVEL3:
        case CTC_SPHINCS_SMALL_LEVEL5:
            /* Hashes done in signing operation. */
            break;
    #endif
    #endif /* HAVE_PQC */

        default:
            ret = HASH_TYPE_E;
            WOLFSSL_MSG("Hash for Signature has unsupported type");
    }

    (void)buf;
    (void)bufSz;
    (void)sigOID;
    (void)digest;
    (void)digestSz;
    (void)typeH;
    (void)verify;

    return ret;
}
#endif /* !NO_ASN_CRYPT && !NO_HASH_WRAPPER */

/* Return codes: 0=Success, Negative (see error-crypt.h), ASN_SIG_CONFIRM_E */
static int ConfirmSignature(SignatureCtx* sigCtx,
    const byte* buf, word32 bufSz,
    const byte* key, word32 keySz, word32 keyOID,
    const byte* sig, word32 sigSz, word32 sigOID,
    const byte* sigParams, word32 sigParamsSz,
    byte* rsaKeyIdx)
{
    int ret = 0;
#if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
    CertAttribute* certatt = NULL;
#endif

    if (sigCtx == NULL || buf == NULL || bufSz == 0 || key == NULL ||
        keySz == 0 || sig == NULL || sigSz == 0) {
        return BAD_FUNC_ARG;
    }

    (void)key;
    (void)keySz;
    (void)sig;
    (void)sigSz;
    (void)sigParams;
    (void)sigParamsSz;

    WOLFSSL_ENTER("ConfirmSignature");

#if !defined(WOLFSSL_RENESAS_TSIP_TLS) && !defined(WOLFSSL_RENESAS_SCEPROTECT)
    (void)rsaKeyIdx;
#else
    #if !defined(NO_RSA) || defined(HAVE_ECC)
    certatt = (CertAttribute*)&sigCtx->CertAtt;
    #endif
    if (certatt) {
        certatt->keyIndex = rsaKeyIdx;
        certatt->cert = buf;
        certatt->certSz = bufSz;
    }
#endif

#ifndef NO_ASN_CRYPT
    switch (sigCtx->state) {
        case SIG_STATE_BEGIN:
        {
            sigCtx->keyOID = keyOID; /* must set early for cleanup */

            sigCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, sigCtx->heap,
                                                    DYNAMIC_TYPE_DIGEST);
            if (sigCtx->digest == NULL) {
                ERROR_OUT(MEMORY_E, exit_cs);
            }

        #if !defined(NO_RSA) && defined(WC_RSA_PSS)
            /* RSA PSS Defaults */
            sigCtx->hash = WC_HASH_TYPE_SHA;
            sigCtx->mgf = WC_MGF1SHA1;
            sigCtx->saltLen = 20;
        #endif

            sigCtx->state = SIG_STATE_HASH;
        } /* SIG_STATE_BEGIN */
        FALL_THROUGH;

        case SIG_STATE_HASH:
        {
        #if !defined(NO_RSA) && defined(WC_RSA_PSS)
            if (sigOID == RSAPSSk) {
                word32 fakeSigOID = 0;
                ret = DecodeRsaPssParams(sigParams, sigParamsSz, &sigCtx->hash,
                    &sigCtx->mgf, &sigCtx->saltLen);
                if (ret != 0) {
                    goto exit_cs;
                }
                ret = RsaPssHashOidToSigOid(sigCtx->hash, &fakeSigOID);
                if (ret != 0) {
                    goto exit_cs;
                }
                /* Decode parameters. */
                ret = HashForSignature(buf, bufSz, fakeSigOID, sigCtx->digest,
                    &sigCtx->typeH, &sigCtx->digestSz, 1);
                if (ret != 0) {
                    goto exit_cs;
                }
            }
            else
        #endif
            {
                ret = HashForSignature(buf, bufSz, sigOID, sigCtx->digest,
                                       &sigCtx->typeH, &sigCtx->digestSz, 1);
                if (ret != 0) {
                    goto exit_cs;
                }
            }

            sigCtx->state = SIG_STATE_KEY;
        } /* SIG_STATE_HASH */
        FALL_THROUGH;

        case SIG_STATE_KEY:
        {
            switch (keyOID) {
            #ifndef NO_RSA
                #ifdef WC_RSA_PSS
                case RSAPSSk:
                #endif
                case RSAk:
                {
                    word32 idx = 0;

                    sigCtx->key.rsa = (RsaKey*)XMALLOC(sizeof(RsaKey),
                                                sigCtx->heap, DYNAMIC_TYPE_RSA);
                    if (sigCtx->key.rsa == NULL) {
                        ERROR_OUT(MEMORY_E, exit_cs);
                    }
                    if ((ret = wc_InitRsaKey_ex(sigCtx->key.rsa, sigCtx->heap,
                                                        sigCtx->devId)) != 0) {
                        goto exit_cs;
                    }
                    sigCtx->sigCpy = (byte*)XMALLOC(sigSz, sigCtx->heap,
                                                        DYNAMIC_TYPE_SIGNATURE);
                    if (sigCtx->sigCpy == NULL) {
                        ERROR_OUT(MEMORY_E, exit_cs);
                    }
                    if (sigSz > MAX_ENCODED_SIG_SZ) {
                        WOLFSSL_MSG("Verify Signature is too big");
                        ERROR_OUT(BUFFER_E, exit_cs);
                    }
                    if ((ret = wc_RsaPublicKeyDecode(key, &idx, sigCtx->key.rsa,
                                                                 keySz)) != 0) {
                        WOLFSSL_MSG("ASN Key decode error RSA");
                        WOLFSSL_ERROR_VERBOSE(ret);
                        goto exit_cs;
                    }
                    XMEMCPY(sigCtx->sigCpy, sig, sigSz);
                    sigCtx->out = NULL;

                #ifdef WOLFSSL_ASYNC_CRYPT
                    sigCtx->asyncDev = &sigCtx->key.rsa->asyncDev;
                #endif
                    break;
                }
            #endif /* !NO_RSA */
            #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
                case DSAk:
                {
                    word32 idx = 0;

                    if (sigSz < DSA_MIN_SIG_SIZE) {
                        WOLFSSL_MSG("Verify Signature is too small");
                        ERROR_OUT(BUFFER_E, exit_cs);
                    }
                    sigCtx->key.dsa = (DsaKey*)XMALLOC(sizeof(DsaKey),
                                                sigCtx->heap, DYNAMIC_TYPE_DSA);
                    sigCtx->sigCpy = (byte*)XMALLOC(sigSz,
                                         sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
                    if (sigCtx->key.dsa == NULL || sigCtx->sigCpy == NULL) {
                        ERROR_OUT(MEMORY_E, exit_cs);
                    }
                    if ((ret = wc_InitDsaKey_h(sigCtx->key.dsa, sigCtx->heap)) != 0) {
                        WOLFSSL_MSG("wc_InitDsaKey_h error");
                        goto exit_cs;
                    }
                    if ((ret = wc_DsaPublicKeyDecode(key, &idx, sigCtx->key.dsa,
                                                                 keySz)) != 0) {
                        WOLFSSL_MSG("ASN Key decode error DSA");
                        WOLFSSL_ERROR_VERBOSE(ret);
                        goto exit_cs;
                    }
                    if (sigSz != DSA_160_SIG_SIZE &&
                            sigSz != DSA_256_SIG_SIZE) {
                        /* Try to parse it as the contents of a bitstring */
                    #ifdef WOLFSSL_SMALL_STACK
                        mp_int* r;
                        mp_int* s;
                    #else
                        mp_int r[1];
                        mp_int s[1];
                    #endif
                        int rSz;
                        int sSz;

                    #ifdef WOLFSSL_SMALL_STACK
                        r = (mp_int*)XMALLOC(sizeof(*r), sigCtx->heap,
                                                       DYNAMIC_TYPE_TMP_BUFFER);
                        if (r == NULL) {
                            ERROR_OUT(MEMORY_E, exit_cs);
                        }
                        s = (mp_int*)XMALLOC(sizeof(*s), sigCtx->heap,
                                                       DYNAMIC_TYPE_TMP_BUFFER);
                        if (s == NULL) {
                            XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
                            ERROR_OUT(MEMORY_E, exit_cs);
                        }
                    #endif
                        if ((ret = mp_init_multi(r, s, NULL, NULL, NULL, NULL)) != MP_OKAY) {
                            goto exit_cs;
                        }

                        idx = 0;
                        if (DecodeECC_DSA_Sig(sig + idx, sigSz - idx, r, s)
                                              != 0) {
                            WOLFSSL_MSG("DSA Sig is in unrecognized or "
                                        "incorrect format");
                            mp_free(r);
                            mp_free(s);
                    #ifdef WOLFSSL_SMALL_STACK
                            XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
                            XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
                    #endif
                            ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
                        }
                        rSz = mp_unsigned_bin_size(r);
                        sSz = mp_unsigned_bin_size(s);
                        if (rSz + sSz > (int)sigSz) {
                            WOLFSSL_MSG("DSA Sig is in unrecognized or "
                                        "incorrect format");
                            mp_free(r);
                            mp_free(s);
                    #ifdef WOLFSSL_SMALL_STACK
                            XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
                            XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
                    #endif
                            ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
                        }
                        if (mp_to_unsigned_bin(r, sigCtx->sigCpy) != MP_OKAY ||
                                mp_to_unsigned_bin(s,
                                        sigCtx->sigCpy + rSz) != MP_OKAY) {
                            WOLFSSL_MSG("DSA Sig is in unrecognized or "
                                        "incorrect format");
                            mp_free(r);
                            mp_free(s);
                    #ifdef WOLFSSL_SMALL_STACK
                            XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
                            XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
                    #endif
                            ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
                        }
                        mp_free(r);
                        mp_free(s);
                    #ifdef WOLFSSL_SMALL_STACK
                        XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
                        XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
                    #endif
                    }
                    else {
                        XMEMCPY(sigCtx->sigCpy, sig, sigSz);
                    }
                    break;
                }
            #endif /* !NO_DSA && !HAVE_SELFTEST */
            #ifdef HAVE_ECC
                case ECDSAk:
                {
                    word32 idx = 0;
            #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
                defined(WC_ASYNC_ENABLE_ECC)
                    ecc_nb_ctx_t* nbCtx;
            #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
                      WC_ASYNC_ENABLE_ECC */

                    sigCtx->verify = 0;
                    sigCtx->key.ecc = (ecc_key*)XMALLOC(sizeof(ecc_key),
                                                sigCtx->heap, DYNAMIC_TYPE_ECC);
                    if (sigCtx->key.ecc == NULL) {
                        ERROR_OUT(MEMORY_E, exit_cs);
                    }
                    if ((ret = wc_ecc_init_ex(sigCtx->key.ecc, sigCtx->heap,
                                                          sigCtx->devId)) < 0) {
                        goto exit_cs;
                    }
            #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
                defined(WC_ASYNC_ENABLE_ECC)
                    nbCtx = (ecc_nb_ctx_t*)XMALLOC(sizeof(ecc_nb_ctx_t),
                                sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
                    if (nbCtx == NULL) {
                        ERROR_OUT(MEMORY_E, exit_cs);
                    }
                    else {
                        ret = wc_ecc_set_nonblock(sigCtx->key.ecc, nbCtx);
                        if (ret != 0) {
                            goto exit_cs;
                        }
                    }
            #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
                      WC_ASYNC_ENABLE_ECC */
                    ret = wc_EccPublicKeyDecode(key, &idx, sigCtx->key.ecc,
                                                                         keySz);
                    if (ret < 0) {
                        WOLFSSL_MSG("ASN Key import error ECC");
                        WOLFSSL_ERROR_VERBOSE(ret);
                        goto exit_cs;
                    }
                #ifdef WOLFSSL_ASYNC_CRYPT
                    sigCtx->asyncDev = &sigCtx->key.ecc->asyncDev;
                #endif
                    break;
                }
            #endif /* HAVE_ECC */
            #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)
                case ED25519k:
                {
                    sigCtx->verify = 0;
                    sigCtx->key.ed25519 = (ed25519_key*)XMALLOC(
                                              sizeof(ed25519_key), sigCtx->heap,
                                              DYNAMIC_TYPE_ED25519);
                    if (sigCtx->key.ed25519 == NULL) {
                        ERROR_OUT(MEMORY_E, exit_cs);
                    }
                    if ((ret = wc_ed25519_init_ex(sigCtx->key.ed25519,
                                            sigCtx->heap, sigCtx->devId)) < 0) {
                        goto exit_cs;
                    }
                    if ((ret = wc_ed25519_import_public(key, keySz,
                                                    sigCtx->key.ed25519)) < 0) {
                        WOLFSSL_MSG("ASN Key import error ED25519");
                        WOLFSSL_ERROR_VERBOSE(ret);
                        goto exit_cs;
                    }
                #ifdef WOLFSSL_ASYNC_CRYPT
                    sigCtx->asyncDev = &sigCtx->key.ed25519->asyncDev;
                #endif
                    break;
                }
            #endif
            #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)
                case ED448k:
                {
                    sigCtx->verify = 0;
                    sigCtx->key.ed448 = (ed448_key*)XMALLOC(
                                                sizeof(ed448_key), sigCtx->heap,
                                                DYNAMIC_TYPE_ED448);
                    if (sigCtx->key.ed448 == NULL) {
                        ERROR_OUT(MEMORY_E, exit_cs);
                    }
                    if ((ret = wc_ed448_init(sigCtx->key.ed448)) < 0) {
                        goto exit_cs;
                    }
                    if ((ret = wc_ed448_import_public(key, keySz,
                                                      sigCtx->key.ed448)) < 0) {
                        WOLFSSL_MSG("ASN Key import error ED448");
                        WOLFSSL_ERROR_VERBOSE(ret);
                        goto exit_cs;
                    }
                #ifdef WOLFSSL_ASYNC_CRYPT
                    sigCtx->asyncDev = &sigCtx->key.ed448->asyncDev;
                #endif
                    break;
                }
            #endif
            #if defined(HAVE_PQC)
            #if defined(HAVE_FALCON)
                case FALCON_LEVEL1k:
                {
                    sigCtx->verify = 0;
                    sigCtx->key.falcon =
                        (falcon_key*)XMALLOC(sizeof(falcon_key),
                                             sigCtx->heap,
                                             DYNAMIC_TYPE_FALCON);
                    if (sigCtx->key.falcon == NULL) {
                        ERROR_OUT(MEMORY_E, exit_cs);
                    }
                    if ((ret = wc_falcon_init(sigCtx->key.falcon)) < 0) {
                        goto exit_cs;
                    }
                    if ((ret = wc_falcon_set_level(sigCtx->key.falcon, 1))
                        < 0) {
                        goto exit_cs;
                    }
                    if ((ret = wc_falcon_import_public(key, keySz,
                        sigCtx->key.falcon)) < 0) {
                        WOLFSSL_MSG("ASN Key import error Falcon Level 1");
                        WOLFSSL_ERROR_VERBOSE(ret);
                        goto exit_cs;
                    }
                    break;
                }
                case FALCON_LEVEL5k:
                {
                    sigCtx->verify = 0;
                    sigCtx->key.falcon =
                        (falcon_key*)XMALLOC(sizeof(falcon_key),
                                             sigCtx->heap,
                                             DYNAMIC_TYPE_FALCON);
                    if (sigCtx->key.falcon == NULL) {
                        ERROR_OUT(MEMORY_E, exit_cs);
                    }
                    if ((ret = wc_falcon_init(sigCtx->key.falcon)) < 0) {
                        goto exit_cs;
                    }
                    if ((ret = wc_falcon_set_level(sigCtx->key.falcon, 5))
                        < 0) {
                        goto exit_cs;
                    }
                    if ((ret = wc_falcon_import_public(key, keySz,
                        sigCtx->key.falcon)) < 0) {
                        WOLFSSL_MSG("ASN Key import error Falcon Level 5");
                        WOLFSSL_ERROR_VERBOSE(ret);
                        goto exit_cs;
                    }
                    break;
                }
            #endif /* HAVE_FALCON */
            #if defined(HAVE_DILITHIUM)
                case DILITHIUM_LEVEL2k:
                {
                    sigCtx->verify = 0;
                    sigCtx->key.dilithium =
                        (dilithium_key*)XMALLOC(sizeof(dilithium_key),
                                             sigCtx->heap,
                                             DYNAMIC_TYPE_DILITHIUM);
                    if (sigCtx->key.dilithium == NULL) {
                        ERROR_OUT(MEMORY_E, exit_cs);
                    }
                    if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
                        goto exit_cs;
                    }
                    if ((ret = wc_dilithium_set_level(
                                   sigCtx->key.dilithium, 2))
                        < 0) {
                        goto exit_cs;
                    }
                    if ((ret = wc_dilithium_import_public(key, keySz,
                        sigCtx->key.dilithium)) < 0) {
                        WOLFSSL_MSG("ASN Key import error Dilithium Level 2");
                        goto exit_cs;
                    }
                    break;
                }
                case DILITHIUM_LEVEL3k:
                {
                    sigCtx->verify = 0;
                    sigCtx->key.dilithium =
                        (dilithium_key*)XMALLOC(sizeof(dilithium_key),
                                             sigCtx->heap,
                                             DYNAMIC_TYPE_DILITHIUM);
                    if (sigCtx->key.dilithium == NULL) {
                        ERROR_OUT(MEMORY_E, exit_cs);
                    }
                    if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
                        goto exit_cs;
                    }
                    if ((ret = wc_dilithium_set_level(
                                   sigCtx->key.dilithium, 3))
                        < 0) {
                        goto exit_cs;
                    }
                    if ((ret = wc_dilithium_import_public(key, keySz,
                        sigCtx->key.dilithium)) < 0) {
                        WOLFSSL_MSG("ASN Key import error Dilithium Level 5");
                        goto exit_cs;
                    }
                    break;
                }
                case DILITHIUM_LEVEL5k:
                {
                    sigCtx->verify = 0;
                    sigCtx->key.dilithium =
                        (dilithium_key*)XMALLOC(sizeof(dilithium_key),
                                             sigCtx->heap,
                                             DYNAMIC_TYPE_DILITHIUM);
                    if (sigCtx->key.dilithium == NULL) {
                        ERROR_OUT(MEMORY_E, exit_cs);
                    }
                    if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
                        goto exit_cs;
                    }
                    if ((ret = wc_dilithium_set_level(
                                   sigCtx->key.dilithium, 5))
                        < 0) {
                        goto exit_cs;
                    }
                    if ((ret = wc_dilithium_import_public(key, keySz,
                        sigCtx->key.dilithium)) < 0) {
                        WOLFSSL_MSG("ASN Key import error Dilithium Level 5");
                        goto exit_cs;
                    }
                    break;
                }
            #endif /* HAVE_DILITHIUM */
            #if defined(HAVE_SPHINCS)
                case SPHINCS_FAST_LEVEL1k:
                {
                    sigCtx->verify = 0;
                    sigCtx->key.sphincs =
                        (sphincs_key*)XMALLOC(sizeof(sphincs_key),
                                             sigCtx->heap,
                                             DYNAMIC_TYPE_SPHINCS);
                    if (sigCtx->key.sphincs == NULL) {
                        ERROR_OUT(MEMORY_E, exit_cs);
                    }
                    if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
                        goto exit_cs;
                    }
                    if ((ret = wc_sphincs_set_level_and_optim(
                                   sigCtx->key.sphincs, 1, FAST_VARIANT))
                        < 0) {
                        goto exit_cs;
                    }
                    if ((ret = wc_sphincs_import_public(key, keySz,
                        sigCtx->key.sphincs)) < 0) {
                        WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level1");
                        goto exit_cs;
                    }
                    break;
                }
                case SPHINCS_FAST_LEVEL3k:
                {
                    sigCtx->verify = 0;
                    sigCtx->key.sphincs =
                        (sphincs_key*)XMALLOC(sizeof(sphincs_key),
                                             sigCtx->heap,
                                             DYNAMIC_TYPE_SPHINCS);
                    if (sigCtx->key.sphincs == NULL) {
                        ERROR_OUT(MEMORY_E, exit_cs);
                    }
                    if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
                        goto exit_cs;
                    }
                    if ((ret = wc_sphincs_set_level_and_optim(
                                   sigCtx->key.sphincs, 3, FAST_VARIANT))
                        < 0) {
                        goto exit_cs;
                    }
                    if ((ret = wc_sphincs_import_public(key, keySz,
                        sigCtx->key.sphincs)) < 0) {
                        WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level3");
                        goto exit_cs;
                    }
                    break;
                }
                case SPHINCS_FAST_LEVEL5k:
                {
                    sigCtx->verify = 0;
                    sigCtx->key.sphincs =
                        (sphincs_key*)XMALLOC(sizeof(sphincs_key),
                                             sigCtx->heap,
                                             DYNAMIC_TYPE_SPHINCS);
                    if (sigCtx->key.sphincs == NULL) {
                        ERROR_OUT(MEMORY_E, exit_cs);
                    }
                    if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
                        goto exit_cs;
                    }
                    if ((ret = wc_sphincs_set_level_and_optim(
                                   sigCtx->key.sphincs, 5, FAST_VARIANT))
                        < 0) {
                        goto exit_cs;
                    }
                    if ((ret = wc_sphincs_import_public(key, keySz,
                        sigCtx->key.sphincs)) < 0) {
                        WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level5");
                        goto exit_cs;
                    }
                    break;
                }

                case SPHINCS_SMALL_LEVEL1k:
                {
                    sigCtx->verify = 0;
                    sigCtx->key.sphincs =
                        (sphincs_key*)XMALLOC(sizeof(sphincs_key),
                                             sigCtx->heap,
                                             DYNAMIC_TYPE_SPHINCS);
                    if (sigCtx->key.sphincs == NULL) {
                        ERROR_OUT(MEMORY_E, exit_cs);
                    }
                    if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
                        goto exit_cs;
                    }
                    if ((ret = wc_sphincs_set_level_and_optim(
                                   sigCtx->key.sphincs, 1, SMALL_VARIANT))
                        < 0) {
                        goto exit_cs;
                    }
                    if ((ret = wc_sphincs_import_public(key, keySz,
                        sigCtx->key.sphincs)) < 0) {
                        WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level1");
                        goto exit_cs;
                    }
                    break;
                }
                case SPHINCS_SMALL_LEVEL3k:
                {
                    sigCtx->verify = 0;
                    sigCtx->key.sphincs =
                        (sphincs_key*)XMALLOC(sizeof(sphincs_key),
                                             sigCtx->heap,
                                             DYNAMIC_TYPE_SPHINCS);
                    if (sigCtx->key.sphincs == NULL) {
                        ERROR_OUT(MEMORY_E, exit_cs);
                    }
                    if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
                        goto exit_cs;
                    }
                    if ((ret = wc_sphincs_set_level_and_optim(
                                   sigCtx->key.sphincs, 3, SMALL_VARIANT))
                        < 0) {
                        goto exit_cs;
                    }
                    if ((ret = wc_sphincs_import_public(key, keySz,
                        sigCtx->key.sphincs)) < 0) {
                        WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level3");
                        goto exit_cs;
                    }
                    break;
                }
                case SPHINCS_SMALL_LEVEL5k:
                {
                    sigCtx->verify = 0;
                    sigCtx->key.sphincs =
                        (sphincs_key*)XMALLOC(sizeof(sphincs_key),
                                             sigCtx->heap,
                                             DYNAMIC_TYPE_SPHINCS);
                    if (sigCtx->key.sphincs == NULL) {
                        ERROR_OUT(MEMORY_E, exit_cs);
                    }
                    if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
                        goto exit_cs;
                    }
                    if ((ret = wc_sphincs_set_level_and_optim(
                                   sigCtx->key.sphincs, 5, SMALL_VARIANT))
                        < 0) {
                        goto exit_cs;
                    }
                    if ((ret = wc_sphincs_import_public(key, keySz,
                        sigCtx->key.sphincs)) < 0) {
                        WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level5");
                        goto exit_cs;
                    }
                    break;
                }
            #endif /* HAVE_SPHINCS */
            #endif /* HAVE_PQC */
                default:
                    WOLFSSL_MSG("Verify Key type unknown");
                    ret = ASN_UNKNOWN_OID_E;
                    WOLFSSL_ERROR_VERBOSE(ret);
                    break;
            } /* switch (keyOID) */

            if (ret != 0) {
                goto exit_cs;
            }

            sigCtx->state = SIG_STATE_DO;

        #ifdef WOLFSSL_ASYNC_CRYPT
            if (sigCtx->devId != INVALID_DEVID && sigCtx->asyncDev && sigCtx->asyncCtx) {
                /* make sure event is initialized */
                WOLF_EVENT* event = &sigCtx->asyncDev->event;
                ret = wolfAsync_EventInit(event, WOLF_EVENT_TYPE_ASYNC_WOLFSSL,
                    sigCtx->asyncCtx, WC_ASYNC_FLAG_CALL_AGAIN);
            }
        #endif
        } /* SIG_STATE_KEY */
        FALL_THROUGH;

        case SIG_STATE_DO:
        {
            switch (keyOID) {
            #ifndef NO_RSA
                case RSAk:
                #ifdef WC_RSA_PSS
                case RSAPSSk:
                if (sigOID == RSAPSSk) {
                    /* TODO: pkCbRsaPss - RSA PSS callback. */
                    ret = wc_RsaPSS_VerifyInline_ex(sigCtx->sigCpy, sigSz,
                        &sigCtx->out, sigCtx->hash, sigCtx->mgf,
                        sigCtx->saltLen, sigCtx->key.rsa);
                }
                else
                #endif
                {
                #if defined(HAVE_PK_CALLBACKS)
                    if (sigCtx->pkCbRsa) {
                        ret = sigCtx->pkCbRsa(
                                sigCtx->sigCpy, sigSz, &sigCtx->out,
                                key, keySz,
                                sigCtx->pkCtxRsa);
                    }
                #if !defined(WOLFSSL_RENESAS_SCEPROTECT) && \
                    !defined(WOLFSSL_RENESAS_TSIP_TLS)
                    else
                #else
                    if (!sigCtx->pkCbRsa || ret == CRYPTOCB_UNAVAILABLE)
                #endif /* WOLFSSL_RENESAS_SCEPROTECT */
                #endif /* HAVE_PK_CALLBACKS */
                    {
                        ret = wc_RsaSSL_VerifyInline(sigCtx->sigCpy, sigSz,
                                                 &sigCtx->out, sigCtx->key.rsa);
                    }
                }
                break;
            #endif /* !NO_RSA */
            #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
                case DSAk:
                {
                    ret = wc_DsaVerify(sigCtx->digest, sigCtx->sigCpy,
                            sigCtx->key.dsa, &sigCtx->verify);
                    break;
                }
            #endif /* !NO_DSA && !HAVE_SELFTEST */
            #if defined(HAVE_ECC) && defined(HAVE_ECC_VERIFY)
                case ECDSAk:
                {
                #if defined(HAVE_PK_CALLBACKS)
                    if (sigCtx->pkCbEcc) {
                        ret = sigCtx->pkCbEcc(
                                sig, sigSz,
                                sigCtx->digest, (unsigned int)sigCtx->digestSz,
                                key, keySz, &sigCtx->verify,
                                sigCtx->pkCtxEcc);
                    }
                #if !defined(WOLFSSL_RENESAS_SCEPROTECT) && \
                    !defined(WOLFSSL_RENESAS_TSIP_TLS)
                    else
                #else
                    if (!sigCtx->pkCbEcc || ret == CRYPTOCB_UNAVAILABLE)
                #endif /* WOLFSSL_RENESAS_SCEPROTECT */
                #endif /* HAVE_PK_CALLBACKS */
                    {
                        ret = wc_ecc_verify_hash(sig, sigSz, sigCtx->digest,
                            (word32)sigCtx->digestSz, &sigCtx->verify,
                            sigCtx->key.ecc);
                    }
                    break;
                }
            #endif /* HAVE_ECC */
            #if defined(HAVE_ED25519) && defined(HAVE_ED25519_VERIFY)
                case ED25519k:
                {
                    ret = wc_ed25519_verify_msg(sig, sigSz, buf, bufSz,
                                          &sigCtx->verify, sigCtx->key.ed25519);
                    break;
                }
            #endif
            #if defined(HAVE_ED448) && defined(HAVE_ED448_VERIFY)
                case ED448k:
                {
                    ret = wc_ed448_verify_msg(sig, sigSz, buf, bufSz,
                                             &sigCtx->verify, sigCtx->key.ed448,
                                             NULL, 0);
                    break;
                }
            #endif
            #if defined(HAVE_PQC)
            #if defined(HAVE_FALCON)
                case FALCON_LEVEL1k:
                case FALCON_LEVEL5k:
                {
                    ret = wc_falcon_verify_msg(sig, sigSz, buf, bufSz,
                                               &sigCtx->verify,
                                               sigCtx->key.falcon);
                    break;
                }
            #endif /* HAVE_FALCON */
            #if defined(HAVE_DILITHIUM)
                case DILITHIUM_LEVEL2k:
                case DILITHIUM_LEVEL3k:
                case DILITHIUM_LEVEL5k:
                {
                    ret = wc_dilithium_verify_msg(sig, sigSz, buf, bufSz,
                                               &sigCtx->verify,
                                               sigCtx->key.dilithium);
                    break;
                }
            #endif /* HAVE_DILITHIUM */
            #if defined(HAVE_SPHINCS)
                case SPHINCS_FAST_LEVEL1k:
                case SPHINCS_FAST_LEVEL3k:
                case SPHINCS_FAST_LEVEL5k:
                case SPHINCS_SMALL_LEVEL1k:
                case SPHINCS_SMALL_LEVEL3k:
                case SPHINCS_SMALL_LEVEL5k:
                {
                    ret = wc_sphincs_verify_msg(sig, sigSz, buf, bufSz,
                                                &sigCtx->verify,
                                                sigCtx->key.sphincs);
                    break;
                }
            #endif /* HAVE_SPHINCS */
            #endif /* HAVE_PQC */
                default:
                    break;
            }  /* switch (keyOID) */

        #ifdef WOLFSSL_ASYNC_CRYPT
            if (ret == WC_PENDING_E) {
                goto exit_cs;
            }
        #endif

            if (ret < 0) {
                /* treat all errors as ASN_SIG_CONFIRM_E */
                ret = ASN_SIG_CONFIRM_E;
                WOLFSSL_ERROR_VERBOSE(ret);
                goto exit_cs;
            }

            sigCtx->state = SIG_STATE_CHECK;
        } /* SIG_STATE_DO */
        FALL_THROUGH;

        case SIG_STATE_CHECK:
        {
            switch (keyOID) {
            #ifndef NO_RSA
                case RSAk:
                #ifdef WC_RSA_PSS
                case RSAPSSk:
                if (sigOID == RSAPSSk) {
                #if (defined(HAVE_SELFTEST) && \
                     (!defined(HAVE_SELFTEST_VERSION) || \
                      (HAVE_SELFTEST_VERSION < 2))) || \
                    (defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
                     (HAVE_FIPS_VERSION < 2))
                    ret = wc_RsaPSS_CheckPadding_ex(sigCtx->digest,
                        sigCtx->digestSz, sigCtx->out, ret, sigCtx->hash,
                        sigCtx->saltLen);
                #elif (defined(HAVE_SELFTEST) && \
                       (HAVE_SELFTEST_VERSION == 2)) || \
                      (defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
                       (HAVE_FIPS_VERSION == 2))
                    ret = wc_RsaPSS_CheckPadding_ex(sigCtx->digest,
                        sigCtx->digestSz, sigCtx->out, ret, sigCtx->hash,
                        sigCtx->saltLen, 0);
                #else
                    ret = wc_RsaPSS_CheckPadding_ex2(sigCtx->digest,
                        (word32)sigCtx->digestSz, sigCtx->out, (word32)ret, sigCtx->hash,
                        sigCtx->saltLen, wc_RsaEncryptSize(sigCtx->key.rsa) * 8,
                        sigCtx->heap);
                #endif
                    break;
                }
                else
                #endif
                {
                    int encodedSigSz, verifySz;
                #if defined(WOLFSSL_RENESAS_TSIP_TLS) || \
                                            defined(WOLFSSL_RENESAS_SCEPROTECT)
                    if (sigCtx->CertAtt.verifyByTSIP_SCE == 1) break;
                #endif
                #ifdef WOLFSSL_SMALL_STACK
                    byte* encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ,
                                        sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
                    if (encodedSig == NULL) {
                        ERROR_OUT(MEMORY_E, exit_cs);
                    }
                #else
                    byte encodedSig[MAX_ENCODED_SIG_SZ];
                #endif

                    verifySz = ret;

                    /* make sure we're right justified */
                    encodedSigSz = (int)wc_EncodeSignature(encodedSig,
                            sigCtx->digest, (word32)sigCtx->digestSz,
                            sigCtx->typeH);
                    if (encodedSigSz == verifySz && sigCtx->out != NULL &&
                        XMEMCMP(sigCtx->out, encodedSig,
                            (size_t)encodedSigSz) == 0) {
                        ret = 0;
                    }
                    else {
                        WOLFSSL_MSG("RSA SSL verify match encode error");
                        ret = ASN_SIG_CONFIRM_E;
                        WOLFSSL_ERROR_VERBOSE(ret);
                    }

                #ifdef WOLFSSL_SMALL_STACK
                    XFREE(encodedSig, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
                #endif
                    break;
                }
            #endif /* NO_RSA */
            #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
                case DSAk:
                {
                    if (sigCtx->verify == 1) {
                        ret = 0;
                    }
                    else {
                        WOLFSSL_MSG("DSA Verify didn't match");
                        ret = ASN_SIG_CONFIRM_E;
                        WOLFSSL_ERROR_VERBOSE(ret);
                    }
                    break;
                }
            #endif /* !NO_DSA && !HAVE_SELFTEST */
            #ifdef HAVE_ECC
                case ECDSAk:
                {
                    if (sigCtx->verify == 1) {
                        ret = 0;
                    }
                    else {
                        WOLFSSL_MSG("ECC Verify didn't match");
                        ret = ASN_SIG_CONFIRM_E;
                        WOLFSSL_ERROR_VERBOSE(ret);
                    }
                    break;
                }
            #endif /* HAVE_ECC */
            #ifdef HAVE_ED25519
                case ED25519k:
                {
                    if (sigCtx->verify == 1) {
                        ret = 0;
                    }
                    else {
                        WOLFSSL_MSG("ED25519 Verify didn't match");
                        ret = ASN_SIG_CONFIRM_E;
                        WOLFSSL_ERROR_VERBOSE(ret);
                    }
                    break;
                }
            #endif /* HAVE_ED25519 */
            #ifdef HAVE_ED448
                case ED448k:
                {
                    if (sigCtx->verify == 1) {
                        ret = 0;
                    }
                    else {
                        WOLFSSL_MSG("ED448 Verify didn't match");
                        ret = ASN_SIG_CONFIRM_E;
                        WOLFSSL_ERROR_VERBOSE(ret);
                    }
                    break;
                }
            #endif /* HAVE_ED448 */
            #ifdef HAVE_PQC
            #ifdef HAVE_FALCON
                case FALCON_LEVEL1k:
                {
                    if (sigCtx->verify == 1) {
                        ret = 0;
                    }
                    else {
                        WOLFSSL_MSG("FALCON_LEVEL1 Verify didn't match");
                        ret = ASN_SIG_CONFIRM_E;
                        WOLFSSL_ERROR_VERBOSE(ret);
                    }
                    break;
                }
                case FALCON_LEVEL5k:
                {
                    if (sigCtx->verify == 1) {
                        ret = 0;
                    }
                    else {
                        WOLFSSL_MSG("FALCON_LEVEL5 Verify didn't match");
                        ret = ASN_SIG_CONFIRM_E;
                        WOLFSSL_ERROR_VERBOSE(ret);
                    }
                    break;
                }
            #endif /* HAVE_FALCON */
            #ifdef HAVE_DILITHIUM
                case DILITHIUM_LEVEL2k:
                {
                    if (sigCtx->verify == 1) {
                        ret = 0;
                    }
                    else {
                        WOLFSSL_MSG("DILITHIUM_LEVEL2 Verify didn't match");
                        ret = ASN_SIG_CONFIRM_E;
                    }
                    break;
                }
                case DILITHIUM_LEVEL3k:
                {
                    if (sigCtx->verify == 1) {
                        ret = 0;
                    }
                    else {
                        WOLFSSL_MSG("DILITHIUM_LEVEL3 Verify didn't match");
                        ret = ASN_SIG_CONFIRM_E;
                    }
                    break;
                }
                case DILITHIUM_LEVEL5k:
                {
                    if (sigCtx->verify == 1) {
                        ret = 0;
                    }
                    else {
                        WOLFSSL_MSG("DILITHIUM_LEVEL5 Verify didn't match");
                        ret = ASN_SIG_CONFIRM_E;
                    }
                    break;
                }
            #endif /* HAVE_DILITHIUM */
            #ifdef HAVE_SPHINCS
                case SPHINCS_FAST_LEVEL1k:
                {
                    if (sigCtx->verify == 1) {
                        ret = 0;
                    }
                    else {
                        WOLFSSL_MSG("SPHINCS_FAST_LEVEL1 Verify didn't match");
                        ret = ASN_SIG_CONFIRM_E;
                    }
                    break;
                }
                case SPHINCS_FAST_LEVEL3k:
                {
                    if (sigCtx->verify == 1) {
                        ret = 0;
                    }
                    else {
                        WOLFSSL_MSG("SPHINCS_FAST_LEVEL3 Verify didn't match");
                        ret = ASN_SIG_CONFIRM_E;
                    }
                    break;
                }
                case SPHINCS_FAST_LEVEL5k:
                {
                    if (sigCtx->verify == 1) {
                        ret = 0;
                    }
                    else {
                        WOLFSSL_MSG("SPHINCS_FAST_LEVEL5 Verify didn't match");
                        ret = ASN_SIG_CONFIRM_E;
                    }
                    break;
                }
                case SPHINCS_SMALL_LEVEL1k:
                {
                    if (sigCtx->verify == 1) {
                        ret = 0;
                    }
                    else {
                        WOLFSSL_MSG("SPHINCS_SMALL_LEVEL1 Verify didn't match");
                        ret = ASN_SIG_CONFIRM_E;
                    }
                    break;
                }
                case SPHINCS_SMALL_LEVEL3k:
                {
                    if (sigCtx->verify == 1) {
                        ret = 0;
                    }
                    else {
                        WOLFSSL_MSG("SPHINCS_SMALL_LEVEL3 Verify didn't match");
                        ret = ASN_SIG_CONFIRM_E;
                    }
                    break;
                }
                case SPHINCS_SMALL_LEVEL5k:
                {
                    if (sigCtx->verify == 1) {
                        ret = 0;
                    }
                    else {
                        WOLFSSL_MSG("SPHINCS_SMALL_LEVEL5 Verify didn't match");
                        ret = ASN_SIG_CONFIRM_E;
                    }
                    break;
                }
            #endif /* HAVE_SPHINCS */
            #endif /* HAVE_PQC */
                default:
                    break;
            }  /* switch (keyOID) */

            break;
        } /* SIG_STATE_CHECK */

        default:
            break;
    } /* switch (sigCtx->state) */

exit_cs:

#endif /* !NO_ASN_CRYPT */

    (void)keyOID;
    (void)sigOID;

    WOLFSSL_LEAVE("ConfirmSignature", ret);

#ifdef WOLFSSL_ASYNC_CRYPT
    if (ret == WC_PENDING_E)
        return ret;
#endif

    FreeSignatureCtx(sigCtx);

    return ret;
}


#ifndef IGNORE_NAME_CONSTRAINTS

static int MatchBaseName(int type, const char* name, int nameSz,
                         const char* base, int baseSz)
{
    if (base == NULL || baseSz <= 0 || name == NULL || nameSz <= 0 ||
            name[0] == '.' || nameSz < baseSz ||
            (type != ASN_RFC822_TYPE && type != ASN_DNS_TYPE &&
             type != ASN_DIR_TYPE)) {
        return 0;
    }

    if (type == ASN_DIR_TYPE)
        return XMEMCMP(name, base, (size_t)baseSz) == 0;

    /* If an email type, handle special cases where the base is only
     * a domain, or is an email address itself. */
    if (type == ASN_RFC822_TYPE) {
        const char* p = NULL;
        int count = 0;

        if (base[0] != '.') {
            p = base;
            count = 0;

            /* find the '@' in the base */
            while (*p != '@' && count < baseSz) {
                count++;
                p++;
            }

            /* No '@' in base, reset p to NULL */
            if (count >= baseSz)
                p = NULL;
        }

        if (p == NULL) {
            /* Base isn't an email address, it is a domain name,
             * wind the name forward one character past its '@'. */
            p = name;
            count = 0;
            while (*p != '@' && count < baseSz) {
                count++;
                p++;
            }

            if (count < baseSz && *p == '@') {
                name = p + 1;
                nameSz -= count + 1;
            }
        }
    }

    /* RFC 5280 section 4.2.1.10
     * "...Any DNS name that can be constructed by simply adding zero or more
     *  labels to the left-hand side of the name satisfies the name constraint."
     * i.e www.host.example.com works for host.example.com name constraint and
     * host1.example.com does not. */
    if (type == ASN_DNS_TYPE || (type == ASN_RFC822_TYPE && base[0] == '.')) {
        int szAdjust = nameSz - baseSz;
        name += szAdjust;
        nameSz -= szAdjust;
    }

    while (nameSz > 0) {
        if (XTOLOWER((unsigned char)*name++) !=
                                               XTOLOWER((unsigned char)*base++))
            return 0;
        nameSz--;
    }

    return 1;
}


/* Search through the list to find if the name is permitted.
 * name     The DNS name to search for
 * dnsList  The list to search through
 * nameType Type of DNS name to currently searching
 * return 1 if found in list or if not needed
 * return 0 if not found in the list but is needed
 */
static int PermittedListOk(DNS_entry* name, Base_entry* dnsList, byte nameType)
{
    Base_entry* current = dnsList;
    int match = 0;
    int need  = 0;
    int ret   = 1; /* is ok unless needed and no match found */

    while (current != NULL) {
        if (current->type == nameType) {
            need = 1; /* restriction on permitted names is set for this type */
            if (name->len >= current->nameSz &&
                MatchBaseName(nameType, name->name, name->len,
                              current->name, current->nameSz)) {
                match = 1; /* found the current name in the permitted list*/
                break;
            }
        }
        current = current->next;
    }

    /* check if permitted name restriction was set and no matching name found */
    if (need && !match)
        ret = 0;

    return ret;
}


/* Search through the list to find if the name is excluded.
 * name     The DNS name to search for
 * dnsList  The list to search through
 * nameType Type of DNS name to currently searching
 * return 1 if found in list and 0 if not found in the list
 */
static int IsInExcludedList(DNS_entry* name, Base_entry* dnsList, byte nameType)
{
    int ret = 0; /* default of not found in the list */
    Base_entry* current = dnsList;

    while (current != NULL) {
        if (current->type == nameType) {
            if (name->len >= current->nameSz &&
                MatchBaseName(nameType, name->name, name->len,
                              current->name, current->nameSz)) {
                ret = 1;
                break;
            }
        }
        current = current->next;
    }

    return ret;
}


static int ConfirmNameConstraints(Signer* signer, DecodedCert* cert)
{
    const byte nameTypes[] = {ASN_RFC822_TYPE, ASN_DNS_TYPE, ASN_DIR_TYPE};
    int i;

    if (signer == NULL || cert == NULL)
        return 0;

    if (signer->excludedNames == NULL && signer->permittedNames == NULL)
        return 1;

    for (i=0; i < (int)sizeof(nameTypes); i++) {
        byte nameType = nameTypes[i];
        DNS_entry* name = NULL;
        DNS_entry  subjectDnsName; /* temporary node used for subject name */

        XMEMSET(&subjectDnsName, 0, sizeof(DNS_entry));
        switch (nameType) {
            case ASN_DNS_TYPE:
                /* Should it also consider CN in subject? It could use
                 * subjectDnsName too */
                name = cert->altNames;
                break;
            case ASN_RFC822_TYPE:
                /* Shouldn't it validade E= in subject as well? */
                name = cert->altEmailNames;

                /* Add subject email for checking. */
                if (cert->subjectEmail != NULL) {
                    /* RFC 5280 section 4.2.1.10
                     * "When constraints are imposed on the rfc822Name name
                     * form, but the certificate does not include a subject
                     * alternative name, the rfc822Name constraint MUST be
                     * applied to the attribute of type emailAddress in the
                     * subject distinguished name" */
                    subjectDnsName.next = NULL;
                    subjectDnsName.type = ASN_RFC822_TYPE;
                    subjectDnsName.len  = cert->subjectEmailLen;
                    subjectDnsName.name = (char *)cert->subjectEmail;
                }
                break;
            case ASN_DIR_TYPE:
            #ifndef WOLFSSL_NO_ASN_STRICT
                name = cert->altDirNames;
            #endif

                /* RFC 5280 section 4.2.1.10
                    "Restrictions of the form directoryName MUST be
                    applied to the subject field .... and to any names
                    of type directoryName in the subjectAltName
                    extension"
                */
                if (cert->subjectRaw != NULL) {
                    subjectDnsName.next = NULL;
                    subjectDnsName.type = ASN_DIR_TYPE;
                    subjectDnsName.len = cert->subjectRawLen;
                    subjectDnsName.name = (char *)cert->subjectRaw;
                }
                break;
            default:
                /* Other types of names are ignored for now.
                 * Shouldn't it be rejected if it there is a altNamesByType[nameType]
                 * and signer->extNameConstraintCrit is set? */
                return 0;
        }

        while (name != NULL) {
            if (IsInExcludedList(name, signer->excludedNames, nameType) == 1) {
                WOLFSSL_MSG("Excluded name was found!");
                return 0;
            }

            /* Check against the permitted list */
            if (PermittedListOk(name, signer->permittedNames, nameType) != 1) {
                WOLFSSL_MSG("Permitted name was not found!");
                return 0;
            }

            name = name->next;
        }

        /* handle comparing against subject name too */
        if (subjectDnsName.len > 0 && subjectDnsName.name != NULL) {
            if (IsInExcludedList(&subjectDnsName, signer->excludedNames,
                        nameType) == 1) {
                WOLFSSL_MSG("Excluded name was found!");
                return 0;
            }

            /* Check against the permitted list */
            if (PermittedListOk(&subjectDnsName, signer->permittedNames,
                        nameType) != 1) {
                WOLFSSL_MSG("Permitted name was not found!");
                return 0;
            }
        }
    }

    return 1;
}

#endif /* IGNORE_NAME_CONSTRAINTS */

#ifndef WOLFSSL_ASN_TEMPLATE
static void AddAltName(DecodedCert* cert, DNS_entry* dnsEntry)
{
#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_ALT_NAMES_NO_REV)
    dnsEntry->next = NULL;
    if (cert->altNames == NULL) {
        /* First on list */
        cert->altNames = dnsEntry;
    }
    else {
        DNS_entry* temp = cert->altNames;

        /* Find end */
        for (; (temp->next != NULL); temp = temp->next);

        /* Add to end */
        temp->next = dnsEntry;
    }
#else
    dnsEntry->next = cert->altNames;
    cert->altNames = dnsEntry;
#endif
}
#endif

#ifdef WOLFSSL_ASN_TEMPLATE
#if defined(WOLFSSL_SEP) || defined(WOLFSSL_FPKI)
/* ASN.1 template for OtherName of an X.509 certificate.
 * X.509: RFC 5280, 4.2.1.6 - OtherName (without implicit outer SEQUENCE).
 * HW Name: RFC 4108, 5 - Hardware Module Name
 * Only support HW Name where the type is a HW serial number.
 *
 * Other Names handled for FPKI (Federal PKI) use:
 * UPN (Universal Principal Name), a non-standard Other Name
 *  (RFC3280 sec 4.2.1.7). Often used with FIPS 201 smartcard login.
 * FASC-N (Federal Agency Smart Credential Number), defined in the document
 *  fpki-x509-cert-policy-common.pdf. Used for a smart card ID.
 */
static const ASNItem otherNameASN[] = {
/* TYPEID   */ { 0, ASN_OBJECT_ID, 0, 0, 0 },
/* VALUE    */ { 0, ASN_CONTEXT_SPECIFIC | ASN_OTHERNAME_VALUE, 1, 1, 0 },
/* UPN      */     { 1, ASN_UTF8STRING, 0, 0, 2 },
/* FASC-N   */     { 1, ASN_OCTET_STRING, 0, 0, 2 },
/* HWN_SEQ  */     { 1, ASN_SEQUENCE, 1, 0, 2 },
/* HWN_TYPE */         { 2, ASN_OBJECT_ID, 0, 0, 0 },
/* HWN_NUM  */         { 2, ASN_OCTET_STRING, 0, 0, 0 }
};
enum {
    OTHERNAMEASN_IDX_TYPEID = 0,
    OTHERNAMEASN_IDX_VALUE,
    OTHERNAMEASN_IDX_UPN,
    OTHERNAMEASN_IDX_FASCN,
    OTHERNAMEASN_IDX_HWN_SEQ,
    OTHERNAMEASN_IDX_HWN_TYPE,
    OTHERNAMEASN_IDX_HWN_NUM
};

/* Number of items in ASN.1 template for OtherName of an X.509 certificate. */
#define otherNameASN_Length (sizeof(otherNameASN) / sizeof(ASNItem))

#ifdef WOLFSSL_SEP
static int DecodeSEP(ASNGetData* dataASN, DecodedCert* cert)
{
    int ret = 0;
    word32 oidLen, serialLen;

    oidLen = dataASN[OTHERNAMEASN_IDX_HWN_TYPE].data.oid.length;
    serialLen = dataASN[OTHERNAMEASN_IDX_HWN_NUM].data.ref.length;

    /* Allocate space for HW type OID. */
    cert->hwType = (byte*)XMALLOC(oidLen, cert->heap,
                                  DYNAMIC_TYPE_X509_EXT);
    if (cert->hwType == NULL)
        ret = MEMORY_E;

    if (ret == 0) {
        /* Copy, into cert HW type OID */
        XMEMCPY(cert->hwType,
                dataASN[OTHERNAMEASN_IDX_HWN_TYPE].data.oid.data, oidLen);
        cert->hwTypeSz = (int)oidLen;
        /* TODO: check this is the HW serial number OID - no test data. */

        /* Allocate space for HW serial number, +1 for null terminator. */
        cert->hwSerialNum = (byte*)XMALLOC(serialLen + 1, cert->heap,
                                           DYNAMIC_TYPE_X509_EXT);
        if (cert->hwSerialNum == NULL) {
            WOLFSSL_MSG("\tOut of Memory");
            ret = MEMORY_E;
        }
    }
    if (ret == 0) {
        /* Copy into cert HW serial number. */
        XMEMCPY(cert->hwSerialNum,
                dataASN[OTHERNAMEASN_IDX_HWN_NUM].data.ref.data, serialLen);
        cert->hwSerialNum[serialLen] = '\0';
        cert->hwSerialNumSz = (int)serialLen;
    }
    return ret;
}
#endif /* WOLFSSL_SEP */

static int DecodeOtherHelper(ASNGetData* dataASN, DecodedCert* cert, int oid)
{
    DNS_entry* entry = NULL;
    int ret = 0;
    word32 bufLen   = 0;
    const char* buf = NULL;

    switch (oid) {
#ifdef WOLFSSL_FPKI
        case FASCN_OID:
            bufLen = dataASN[OTHERNAMEASN_IDX_FASCN].data.ref.length;
            buf    = (const char*)dataASN[OTHERNAMEASN_IDX_FASCN].data.ref.data;
            break;
#endif /* WOLFSSL_FPKI */
        case UPN_OID:
            bufLen = dataASN[OTHERNAMEASN_IDX_UPN].data.ref.length;
            buf    = (const char*)dataASN[OTHERNAMEASN_IDX_UPN].data.ref.data;
            break;
        default:
            WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
            ret = ASN_UNKNOWN_OID_E;
            break;
    }

    if (ret == 0) {
        ret = SetDNSEntry(cert, buf, (int)bufLen, ASN_OTHER_TYPE, &entry);
        if (ret == 0) {
        #ifdef WOLFSSL_FPKI
            entry->oidSum = oid;
        #endif
            AddDNSEntryToList(&cert->altNames, entry);
        }
    }
    return ret;
}

/* Decode data with OtherName format from after implicit SEQUENCE.
 *
 * @param [in, out] cert      Certificate object.
 * @param [in]      input     Buffer containing encoded OtherName.
 * @param [in, out] inOutIdx  On in, the index of the start of the OtherName.
 *                            On out, index after OtherName.
 * @param [in]      maxIdx    Maximum index of data in buffer.
 * @return  0 on success.
 * @return  MEMORY_E on dynamic memory allocation failure.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  ASN_PARSE_E when OID does is not HW Name.
 * @return  ASN_UNKNOWN_OID_E when the OID cannot be verified.
 * @return  BUFFER_E when data in buffer is too small.
 */
static int DecodeOtherName(DecodedCert* cert, const byte* input,
                           word32* inOutIdx, word32 maxIdx)
{
    DECL_ASNGETDATA(dataASN, otherNameASN_Length);
    int ret = 0;

    CALLOC_ASNGETDATA(dataASN, otherNameASN_Length, ret, cert->heap);

    if (ret == 0) {
        /* Check the first OID is a recognized Alt Cert Name type. */
        GetASN_OID(&dataASN[OTHERNAMEASN_IDX_TYPEID], oidCertAltNameType);
        /* Parse OtherName. */
        ret = GetASN_Items(otherNameASN, dataASN, otherNameASN_Length, 1, input,
                           inOutIdx, maxIdx);
    }
    if (ret == 0) {
        /* Ensure expected OID. */
        switch (dataASN[OTHERNAMEASN_IDX_TYPEID].data.oid.sum) {
        #ifdef WOLFSSL_SEP
            case HW_NAME_OID:
                /* Only support HW serial number. */
                GetASN_OID(&dataASN[OTHERNAMEASN_IDX_HWN_TYPE], oidIgnoreType);
                ret = DecodeSEP(dataASN, cert);
                break;
        #endif /* WOLFSSL_SEP */
        #ifdef WOLFSSL_FPKI
            case FASCN_OID:
        #endif /* WOLFSSL_FPKI */
            case UPN_OID:
                ret = DecodeOtherHelper(dataASN, cert,
                           (int)dataASN[OTHERNAMEASN_IDX_TYPEID].data.oid.sum);
                break;
            default:
                WOLFSSL_MSG("\tunsupported OID skipping");
                break;
        }
    }

    FREE_ASNGETDATA(dataASN, cert->heap);
    return ret;
}
#endif /* WOLFSSL_SEP || WOLFSSL_FPKI */

/* Decode a GeneralName.
 *
 * @param [in]      input     Buffer containing encoded OtherName.
 * @param [in, out] inOutIdx  On in, the index of the start of the OtherName.
 *                            On out, index after OtherName.
 * @param [in]      len       Length of data in buffer.
 * @param [in]      cert      Decoded certificate object.
 * @return  0 on success.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_UNKNOWN_OID_E when the OID cannot be verified.
 * @return  MEMORY_E when dynamic memory allocation fails.
 */
static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag,
                             int len, DecodedCert* cert)
{
    int ret = 0;
    word32 idx = *inOutIdx;

    /* GeneralName choice: dnsName */
    if (tag == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
        ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_DNS_TYPE,
                &cert->altNames);
        if (ret == 0) {
            idx += (word32)len;
        }
    }
#ifndef IGNORE_NAME_CONSTRAINTS
    /* GeneralName choice: directoryName */
    else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
        int strLen;
        word32 idxDir = idx;

        /* Expecting a SEQUENCE using up all data. */
        if (GetASN_Sequence(input, &idxDir, &strLen, idx + (word32)len, 1) < 0)
        {
            WOLFSSL_MSG("\tfail: seq length");
            return ASN_PARSE_E;
        }

        ret = SetDNSEntry(cert, (const char*)(input + idxDir), strLen,
                ASN_DIR_TYPE, &cert->altDirNames);
        if (ret == 0) {
            idx += (word32)len;
        }
    }
    /* GeneralName choice: rfc822Name */
    else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
        ret = SetDNSEntry(cert, (const char*)(input + idx), len,
                ASN_RFC822_TYPE, &cert->altEmailNames);
        if (ret == 0) {
            idx += (word32)len;
        }
    }
    /* GeneralName choice: uniformResourceIdentifier */
    else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) {
        WOLFSSL_MSG("\tPutting URI into list but not using");

    #if !defined(WOLFSSL_NO_ASN_STRICT) && !defined(WOLFSSL_FPKI)
        /* Verify RFC 5280 Sec 4.2.1.6 rule:
            "The name MUST NOT be a relative URI"
            As per RFC 3986 Sec 4.3, an absolute URI is only required to contain
            a scheme and hier-part.  So the only strict requirement is a ':'
            being present after the scheme.  If a '/' is present as part of the
            hier-part, it must come after the ':' (see RFC 3986 Sec 3). */
        {
            int i;

            /* skip past scheme (i.e http,ftp,...) finding first ':' char */
            for (i = 0; i < len; i++) {
                if (input[idx + (word32)i] == ':') {
                    break;
                }
                if (input[idx + (word32)i] == '/') {
                    i = len; /* error, found relative path since '/' was
                              * encountered before ':'. Returning error
                              * value in next if statement. */
                }
            }

            /* test hier-part is empty */
            if (i == 0 || i == len) {
                WOLFSSL_MSG("\tEmpty or malformed URI");
                WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
                return ASN_ALT_NAME_E;
            }

            /* test if scheme is missing  */
            if (input[idx + (word32)i] != ':') {
                WOLFSSL_MSG("\tAlt Name must be absolute URI");
                WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
                return ASN_ALT_NAME_E;
            }
        }
    #endif

        ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_URI_TYPE,
                &cert->altNames);
        if (ret == 0) {
            idx += (word32)len;
        }
    }
    #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || \
                                            defined(WOLFSSL_IP_ALT_NAME)
    /* GeneralName choice: iPAddress */
    else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) {
        ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_IP_TYPE,
                &cert->altNames);
        if (ret == 0) {
            idx += len;
        }
    }
    #endif /* WOLFSSL_QT || OPENSSL_ALL */
#endif /* IGNORE_NAME_CONSTRAINTS */
#if defined(WOLFSSL_SEP) || defined(WOLFSSL_FPKI)
    /* GeneralName choice: otherName */
    else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE)) {
        /* TODO: test data for code path */
        ret = DecodeOtherName(cert, input, &idx, idx + (word32)len);
    }
#endif
    /* GeneralName choice: dNSName, x400Address, ediPartyName,
     *                     registeredID */
    else {
        WOLFSSL_MSG("\tUnsupported name type, skipping");
        idx += (word32)len;
    }

    if (ret == 0) {
        /* Return index of next encoded byte. */
        *inOutIdx = idx;
    }
    return ret;
}

/* ASN.1 choices for GeneralName.
 * X.509: RFC 5280, 4.2.1.6 - GeneralName.
 */
static const byte generalNameChoice[] = {
    ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0,
    ASN_CONTEXT_SPECIFIC                   | 1,
    ASN_CONTEXT_SPECIFIC                   | 2,
    ASN_CONTEXT_SPECIFIC                   | 3,
    ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 4,
    ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 5,
    ASN_CONTEXT_SPECIFIC                   | 6,
    ASN_CONTEXT_SPECIFIC                   | 7,
    ASN_CONTEXT_SPECIFIC                   | 8,
    0
};

/* ASN.1 template for GeneralName.
 * X.509: RFC 5280, 4.2.1.6 - GeneralName.
 */
static const ASNItem altNameASN[] = {
    { 0, ASN_CONTEXT_SPECIFIC | 0, 0, 1, 0 }
};
enum {
    ALTNAMEASN_IDX_GN = 0
};

/* Number of items in ASN.1 template for GeneralName. */
#define altNameASN_Length (sizeof(altNameASN) / sizeof(ASNItem))
#endif /* WOLFSSL_ASN_TEMPLATE */

#if defined(WOLFSSL_SEP) && !defined(WOLFSSL_ASN_TEMPLATE)
/* return 0 on success */
static int DecodeSepHwAltName(DecodedCert* cert, const byte* input,
    word32* idxIn, word32 sz)
{
    word32 idx = *idxIn;
    int  strLen;
    int  ret;
    byte tag;

    /* Certificates issued with this OID in the subject alt name are for
     * verifying signatures created on a module.
     * RFC 4108 Section 5. */
    if (cert->hwType != NULL) {
        WOLFSSL_MSG("\tAlready seen Hardware Module Name");
        return ASN_PARSE_E;
    }

    if (GetASNTag(input, &idx, &tag, sz) < 0) {
        return ASN_PARSE_E;
    }

    if (tag != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
        WOLFSSL_MSG("\twrong type");
        return ASN_PARSE_E;
    }

    if (GetLength(input, &idx, &strLen, sz) < 0) {
        WOLFSSL_MSG("\tfail: str len");
        return ASN_PARSE_E;
    }

    if (GetSequence(input, &idx, &strLen, sz) < 0) {
        WOLFSSL_MSG("\tBad Sequence");
        return ASN_PARSE_E;
    }

    ret = GetASNObjectId(input, &idx, &strLen, sz);
    if (ret != 0) {
        WOLFSSL_MSG("\tbad OID");
        return ret;
    }

    cert->hwType = (byte*)XMALLOC((size_t)strLen, cert->heap,
                                  DYNAMIC_TYPE_X509_EXT);
    if (cert->hwType == NULL) {
        WOLFSSL_MSG("\tOut of Memory");
        return MEMORY_E;
    }

    XMEMCPY(cert->hwType, &input[idx], (size_t)strLen);
    cert->hwTypeSz = strLen;
    idx += (word32)strLen;

    ret = GetOctetString(input, &idx, &strLen, sz);
    if (ret < 0) {
        XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
        cert->hwType = NULL;
        return ret;
    }

    cert->hwSerialNum = (byte*)XMALLOC((size_t)strLen + 1, cert->heap,
                                       DYNAMIC_TYPE_X509_EXT);
    if (cert->hwSerialNum == NULL) {
        WOLFSSL_MSG("\tOut of Memory");
        XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
        cert->hwType = NULL;
        return MEMORY_E;
    }

    XMEMCPY(cert->hwSerialNum, &input[idx], (size_t)strLen);
    cert->hwSerialNum[strLen] = '\0';
    cert->hwSerialNumSz = strLen;
    idx += (word32)strLen;

    *idxIn = idx;
    return 0;
}
#endif /* WOLFSSL_SEP */

#if !defined(WOLFSSL_ASN_TEMPLATE)
/* return 0 on success */
static int DecodeConstructedOtherName(DecodedCert* cert, const byte* input,
        word32* idx, word32 sz, int oid)
{
    int ret    = 0;
    int strLen = 0;
    byte tag;
    DNS_entry* dnsEntry = NULL;

    if (GetASNTag(input, idx, &tag, sz) < 0) {
        ret = ASN_PARSE_E;
    }

    if (ret == 0 && (tag != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))) {
        ret = ASN_PARSE_E;
    }

    if (ret == 0 && (GetLength(input, idx, &strLen, sz) < 0)) {
        ret = ASN_PARSE_E;
    }

    if (ret == 0) {
        dnsEntry = AltNameNew(cert->heap);
        if (dnsEntry == NULL) {
            WOLFSSL_MSG("\tOut of Memory");
            return MEMORY_E;
        }

        switch (oid) {
        #ifdef WOLFSSL_FPKI
            case FASCN_OID:
                ret = GetOctetString(input, idx, &strLen, sz);
                if (ret > 0) {
                    ret = 0;
                }
                break;
        #endif /* WOLFSSL_FPKI */
            case UPN_OID:
                if (GetASNTag(input, idx, &tag, sz) < 0) {
                    ret = ASN_PARSE_E;
                }

                if (ret == 0 &&
                        tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
                                    tag != ASN_IA5_STRING) {
                    WOLFSSL_MSG("Was expecting a string for UPN");
                    ret = ASN_PARSE_E;
                }

                if (ret == 0 && (GetLength(input, idx, &strLen, sz) < 0)) {
                    WOLFSSL_MSG("Was expecting a string for UPN");
                    ret = ASN_PARSE_E;
                }
                break;

            default:
                WOLFSSL_MSG("Unknown constructed other name, skipping");
                XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
                dnsEntry = NULL;
        }
    }

    if (ret == 0 && dnsEntry != NULL) {
        dnsEntry->type = ASN_OTHER_TYPE;
        dnsEntry->len = strLen;
        dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
            DYNAMIC_TYPE_ALTNAME);
    #ifdef WOLFSSL_FPKI
        dnsEntry->oidSum = oid;
    #endif /* WOLFSSL_FPKI */
        if (dnsEntry->name == NULL) {
            WOLFSSL_MSG("\tOut of Memory");
            ret = MEMORY_E;
        }
        else {
            XMEMCPY(dnsEntry->name, &input[*idx], (size_t)strLen);
            dnsEntry->name[strLen] = '\0';
            AddAltName(cert, dnsEntry);
        }
    }

    if (ret == 0) {
        *idx += (word32)strLen;
    }
    else {
        XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
    }

    return ret;
}
#endif

/* Decode subject alternative names extension.
 *
 * RFC 5280 4.2.1.6.  Subject Alternative Name
 *
 * @param [in]      input  Buffer holding encoded data.
 * @param [in]      sz     Size of encoded data in bytes.
 * @param [in, out] cert   Decoded certificate object.
 * @return  0 on success.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_UNKNOWN_OID_E when the OID cannot be verified.
 * @return  MEMORY_E when dynamic memory allocation fails.
 */
static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx = 0;
    int length = 0;

    WOLFSSL_ENTER("DecodeAltNames");

    if (GetSequence(input, &idx, &length, sz) < 0) {
        WOLFSSL_MSG("\tBad Sequence");
        return ASN_PARSE_E;
    }

    if (length == 0) {
        /* RFC 5280 4.2.1.6.  Subject Alternative Name
           If the subjectAltName extension is present, the sequence MUST
           contain at least one entry. */
        WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
        return ASN_PARSE_E;
    }

#ifdef OPENSSL_ALL
    cert->extSubjAltNameSrc = input;
    cert->extSubjAltNameSz = sz;
#endif

    cert->weOwnAltNames = 1;

    while (length > 0) {
        byte current_byte;

        /* Verify idx can't overflow input buffer */
        if (idx >= (word32)sz) {
            WOLFSSL_MSG("\tBad Index");
            return BUFFER_E;
        }

        current_byte = input[idx++];

        length--;

        /* Save DNS Type names in the altNames list. */
        /* Save Other Type names in the cert's OidMap */
        if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
            DNS_entry* dnsEntry;
            int strLen;
            word32 lenStartIdx = idx;

            if (GetLength(input, &idx, &strLen, sz) < 0) {
                WOLFSSL_MSG("\tfail: str length");
                return ASN_PARSE_E;
            }
            length -= (int)(idx - lenStartIdx);

            dnsEntry = AltNameNew(cert->heap);
            if (dnsEntry == NULL) {
                WOLFSSL_MSG("\tOut of Memory");
                return MEMORY_E;
            }

            dnsEntry->type = ASN_DNS_TYPE;
            dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
                                         DYNAMIC_TYPE_ALTNAME);
            if (dnsEntry->name == NULL) {
                WOLFSSL_MSG("\tOut of Memory");
                XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
                return MEMORY_E;
            }
            dnsEntry->len = strLen;
            XMEMCPY(dnsEntry->name, &input[idx], (size_t)strLen);
            dnsEntry->name[strLen] = '\0';

            AddAltName(cert, dnsEntry);

            length -= strLen;
            idx    += (word32)strLen;
        }
    #ifndef IGNORE_NAME_CONSTRAINTS
        else if (current_byte ==
                (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
            DNS_entry* dirEntry;
            int strLen;
            word32 lenStartIdx = idx;

            if (GetLength(input, &idx, &strLen, sz) < 0) {
                WOLFSSL_MSG("\tfail: str length");
                return ASN_PARSE_E;
            }

            if (GetSequence(input, &idx, &strLen, sz) < 0) {
                WOLFSSL_MSG("\tfail: seq length");
                return ASN_PARSE_E;
            }
            length -= (int)(idx - lenStartIdx);

            dirEntry = AltNameNew(cert->heap);
            if (dirEntry == NULL) {
                WOLFSSL_MSG("\tOut of Memory");
                return MEMORY_E;
            }

            dirEntry->type = ASN_DIR_TYPE;
            dirEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
                                         DYNAMIC_TYPE_ALTNAME);
            if (dirEntry->name == NULL) {
                WOLFSSL_MSG("\tOut of Memory");
                XFREE(dirEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
                return MEMORY_E;
            }
            dirEntry->len = strLen;
            XMEMCPY(dirEntry->name, &input[idx], (size_t)strLen);
            dirEntry->name[strLen] = '\0';
            dirEntry->next = cert->altDirNames;
            cert->altDirNames = dirEntry;

            length -= strLen;
            idx    += (word32)strLen;
        }
        else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
            DNS_entry* emailEntry;
            int strLen;
            word32 lenStartIdx = idx;

            if (GetLength(input, &idx, &strLen, sz) < 0) {
                WOLFSSL_MSG("\tfail: str length");
                return ASN_PARSE_E;
            }
            length -= (int)(idx - lenStartIdx);

            emailEntry = AltNameNew(cert->heap);
            if (emailEntry == NULL) {
                WOLFSSL_MSG("\tOut of Memory");
                return MEMORY_E;
            }

            emailEntry->type = ASN_RFC822_TYPE;
            emailEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
                                         DYNAMIC_TYPE_ALTNAME);
            if (emailEntry->name == NULL) {
                WOLFSSL_MSG("\tOut of Memory");
                XFREE(emailEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
                return MEMORY_E;
            }
            emailEntry->len = strLen;
            XMEMCPY(emailEntry->name, &input[idx], (size_t)strLen);
            emailEntry->name[strLen] = '\0';

            emailEntry->next = cert->altEmailNames;
            cert->altEmailNames = emailEntry;

            length -= strLen;
            idx    += (word32)strLen;
        }
        else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) {
            DNS_entry* uriEntry;
            int strLen;
            word32 lenStartIdx = idx;

            WOLFSSL_MSG("\tPutting URI into list but not using");
            if (GetLength(input, &idx, &strLen, sz) < 0) {
                WOLFSSL_MSG("\tfail: str length");
                return ASN_PARSE_E;
            }
            length -= (int)(idx - lenStartIdx);

            /* check that strLen at index is not past input buffer */
            if ((word32)strLen + idx > sz) {
                return BUFFER_E;
            }

        #if !defined(WOLFSSL_NO_ASN_STRICT) && !defined(WOLFSSL_FPKI)
            /* Verify RFC 5280 Sec 4.2.1.6 rule:
                "The name MUST NOT be a relative URI"
                As per RFC 3986 Sec 4.3, an absolute URI is only required to contain
                a scheme and hier-part.  So the only strict requirement is a ':'
                being present after the scheme.  If a '/' is present as part of the
                hier-part, it must come after the ':' (see RFC 3986 Sec 3). */

            {
                word32 i;

                /* skip past scheme (i.e http,ftp,...) finding first ':' char */
                for (i = 0; i < (word32)strLen; i++) {
                    if (input[idx + i] == ':') {
                        break;
                    }
                    if (input[idx + i] == '/') {
                        WOLFSSL_MSG("\tAlt Name must be absolute URI");
                        WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
                        return ASN_ALT_NAME_E;
                    }
                }

                /* test hier-part is empty */
                if (i == 0 || i == (word32)strLen) {
                    WOLFSSL_MSG("\tEmpty or malformed URI");
                    WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
                    return ASN_ALT_NAME_E;
                }

                /* test if scheme is missing */
                if (input[idx + i] != ':') {
                    WOLFSSL_MSG("\tAlt Name must be absolute URI");
                    WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
                    return ASN_ALT_NAME_E;
                }
            }
        #endif

            uriEntry = AltNameNew(cert->heap);
            if (uriEntry == NULL) {
                WOLFSSL_MSG("\tOut of Memory");
                return MEMORY_E;
            }

            uriEntry->type = ASN_URI_TYPE;
            uriEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
                                         DYNAMIC_TYPE_ALTNAME);
            if (uriEntry->name == NULL) {
                WOLFSSL_MSG("\tOut of Memory");
                XFREE(uriEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
                return MEMORY_E;
            }
            uriEntry->len = strLen;
            XMEMCPY(uriEntry->name, &input[idx], (size_t)strLen);
            uriEntry->name[strLen] = '\0';

            AddAltName(cert, uriEntry);

            length -= strLen;
            idx    += (word32)strLen;
        }
#if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
        else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) {
            DNS_entry* ipAddr;
            int strLen;
            word32 lenStartIdx = idx;
            WOLFSSL_MSG("Decoding Subject Alt. Name: IP Address");

            if (GetLength(input, &idx, &strLen, sz) < 0) {
                WOLFSSL_MSG("\tfail: str length");
                return ASN_PARSE_E;
            }
            length -= (idx - lenStartIdx);
            /* check that strLen at index is not past input buffer */
            if (strLen + idx > sz) {
                return BUFFER_E;
            }

            ipAddr = AltNameNew(cert->heap);
            if (ipAddr == NULL) {
                WOLFSSL_MSG("\tOut of Memory");
                return MEMORY_E;
            }

            ipAddr->type = ASN_IP_TYPE;
            ipAddr->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
                                         DYNAMIC_TYPE_ALTNAME);
            if (ipAddr->name == NULL) {
                WOLFSSL_MSG("\tOut of Memory");
                XFREE(ipAddr, cert->heap, DYNAMIC_TYPE_ALTNAME);
                return MEMORY_E;
            }
            ipAddr->len = strLen;
            XMEMCPY(ipAddr->name, &input[idx], strLen);
            ipAddr->name[strLen] = '\0';

        #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
            if (GenerateDNSEntryIPString(ipAddr, cert->heap) != 0) {
                WOLFSSL_MSG("\tOut of Memory for IP string");
                XFREE(ipAddr->name, cert->heap, DYNAMIC_TYPE_ALTNAME);
                XFREE(ipAddr, cert->heap, DYNAMIC_TYPE_ALTNAME);
                return MEMORY_E;
            }
        #endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */
            AddAltName(cert, ipAddr);

            length -= strLen;
            idx    += (word32)strLen;
        }
#endif /* WOLFSSL_QT || OPENSSL_ALL */
#endif /* IGNORE_NAME_CONSTRAINTS */
        else if (current_byte ==
                (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE)) {
            int strLen;
            word32 lenStartIdx = idx;
            word32 oid = 0;
            int    ret = 0;

            if (GetLength(input, &idx, &strLen, sz) < 0) {
                WOLFSSL_MSG("\tfail: other name length");
                return ASN_PARSE_E;
            }
            /* Consume the rest of this sequence. */
            length -= (int)(((word32)strLen + idx - lenStartIdx));

            if (GetObjectId(input, &idx, &oid, oidCertAltNameType, sz) < 0) {
                WOLFSSL_MSG("\tbad OID");
                return ASN_PARSE_E;
            }

            /* handle parsing other type alt names */
            switch (oid) {
            #ifdef WOLFSSL_SEP
                case HW_NAME_OID:
                    ret = DecodeSepHwAltName(cert, input, &idx, sz);
                    if (ret != 0)
                        return ret;
                    break;
            #endif /* WOLFSSL_SEP */
            #ifdef WOLFSSL_FPKI
                case FASCN_OID:
                case UPN_OID:
                    ret = DecodeConstructedOtherName(cert, input, &idx, sz,
                            oid);
                    if (ret != 0)
                        return ret;
                    break;
            #endif /* WOLFSSL_FPKI */

                default:
                    WOLFSSL_MSG("\tUnsupported other name type, skipping");
                    if (GetLength(input, &idx, &strLen, sz) < 0) {
                        /* check to skip constructed other names too */
                        if (DecodeConstructedOtherName(cert, input, &idx, sz,
                                    (int)oid) != 0) {
                            WOLFSSL_MSG("\tfail: unsupported other name length");
                            return ASN_PARSE_E;
                        }
                    }
                    else {
                        idx += (word32)strLen;
                    }
            }
            (void)ret;
        }
        else {
            int strLen;
            word32 lenStartIdx = idx;

            WOLFSSL_MSG("\tUnsupported name type, skipping");

            if (GetLength(input, &idx, &strLen, sz) < 0) {
                WOLFSSL_MSG("\tfail: unsupported name length");
                return ASN_PARSE_E;
            }
            length -= (int)((word32)strLen + idx - lenStartIdx);
            idx += (word32)strLen;
        }
    }

    return 0;
#else
    word32 idx = 0;
    int length = 0;
    int ret = 0;

    WOLFSSL_ENTER("DecodeAltNames");

    /* Get SEQUENCE and expect all data to be accounted for. */
    if (GetASN_Sequence(input, &idx, &length, sz, 1) != 0) {
        WOLFSSL_MSG("\tBad Sequence");
        ret = ASN_PARSE_E;
    }

    if ((ret == 0) && (length == 0)) {
        /* RFC 5280 4.2.1.6.  Subject Alternative Name
           If the subjectAltName extension is present, the sequence MUST
           contain at least one entry. */
        WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
        ret = ASN_PARSE_E;
    }
    if (ret == 0) {
    #ifdef OPENSSL_ALL
        cert->extSubjAltNameSrc = input;
        cert->extSubjAltNameSz = sz;
    #endif

        cert->weOwnAltNames = 1;

        if ((word32)length + idx != sz) {
            ret = ASN_PARSE_E;
        }
    }

    while ((ret == 0) && (idx < sz)) {
        ASNGetData dataASN[altNameASN_Length];

        /* Clear dynamic data items. */
        XMEMSET(dataASN, 0, sizeof(dataASN));
        /* Parse GeneralName with the choices supported. */
        GetASN_Choice(&dataASN[ALTNAMEASN_IDX_GN], generalNameChoice);
        /* Decode a GeneralName choice. */
        ret = GetASN_Items(altNameASN, dataASN, altNameASN_Length, 0, input,
                           &idx, sz);
        if (ret == 0) {
            ret = DecodeGeneralName(input, &idx, dataASN[ALTNAMEASN_IDX_GN].tag,
                                  (int)dataASN[ALTNAMEASN_IDX_GN].length, cert);
        }
    }

    return ret;
#endif
}

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for BasicContraints.
 * X.509: RFC 5280, 4.2.1.9 - BasicConstraints.
 */
static const ASNItem basicConsASN[] = {
/* SEQ  */ { 0, ASN_SEQUENCE, 1, 1, 0 },
/* CA   */     { 1, ASN_BOOLEAN, 0, 0, 1 },
/* PLEN */     { 1, ASN_INTEGER, 0, 0, 1 }
};
enum {
    BASICCONSASN_IDX_SEQ = 0,
    BASICCONSASN_IDX_CA,
    BASICCONSASN_IDX_PLEN
};

/* Number of items in ASN.1 template for BasicContraints. */
#define basicConsASN_Length (sizeof(basicConsASN) / sizeof(ASNItem))
#endif

/* Decode basic constraints extension in a certificate.
 *
 * X.509: RFC 5280, 4.2.1.9 - BasicConstraints.
 *
 * @param [in]      input  Buffer holding data.
 * @param [in]      sz     Size of data in buffer.
 * @param [in, out] cert   Certificate object.
 * @return  0 on success.
 * @return  MEMORY_E on dynamic memory allocation failure.
 * @return  ASN_PARSE_E when CA boolean is present and false (default is false).
 * @return  ASN_PARSE_E when CA boolean is not present unless
 *          WOLFSSL_X509_BASICCONS_INT is defined. Only a CA extension.
 * @return  ASN_PARSE_E when path length more than 7 bits.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
 *          non-zero length.
 */
static int DecodeBasicCaConstraint(const byte* input, int sz, DecodedCert* cert)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx = 0;
    int length = 0;
    int ret;

    WOLFSSL_ENTER("DecodeBasicCaConstraint");

    if (GetSequence(input, &idx, &length, (word32)sz) < 0) {
        WOLFSSL_MSG("\tfail: bad SEQUENCE");
        return ASN_PARSE_E;
    }

    if (length == 0)
        return 0;

    /* If the basic ca constraint is false, this extension may be named, but
     * left empty. So, if the length is 0, just return. */

    ret = GetBoolean(input, &idx, (word32)sz);

    /* Removed logic for WOLFSSL_X509_BASICCONS_INT which was mistreating the
     * pathlen value as if it were the CA Boolean value 7/2/2021 - KH.
     * When CA Boolean not asserted use the default value "False" */
    if (ret < 0) {
        WOLFSSL_MSG("\tfail: constraint not valid BOOLEAN, set default FALSE");
        ret = 0;
    }

    cert->isCA = ret ? 1 : 0;

    /* If there isn't any more data, return. */
    if (idx >= (word32)sz) {
        return 0;
    }

    ret = GetInteger7Bit(input, &idx, (word32)sz);
    if (ret < 0)
        return ret;
    cert->pathLength = (byte)ret;
    cert->pathLengthSet = 1;

    return 0;
#else
    DECL_ASNGETDATA(dataASN, basicConsASN_Length);
    int ret = 0;
    word32 idx = 0;
    byte isCA = 0;

    WOLFSSL_ENTER("DecodeBasicCaConstraints");

    CALLOC_ASNGETDATA(dataASN, basicConsASN_Length, ret, cert->heap);

    if (ret == 0) {
        /* Get the CA boolean and path length when present. */
        GetASN_Boolean(&dataASN[BASICCONSASN_IDX_CA], &isCA);
        GetASN_Int8Bit(&dataASN[BASICCONSASN_IDX_PLEN], &cert->pathLength);

        ret = GetASN_Items(basicConsASN, dataASN, basicConsASN_Length, 1, input,
                           &idx, (word32)sz);
    }

    /* Empty SEQUENCE is OK - nothing to store. */
    if ((ret == 0) && (dataASN[BASICCONSASN_IDX_SEQ].length != 0)) {
        /* Bad encoding when CA Boolean is false
         * (default when not present). */
        if ((dataASN[BASICCONSASN_IDX_CA].length != 0) && (!isCA)) {
            WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
            ret = ASN_PARSE_E;
        }
        /* Path length must be a 7-bit value. */
        if ((ret == 0) && (cert->pathLength >= (1 << 7))) {
            WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
            ret = ASN_PARSE_E;
        }
        /* Store CA boolean and whether a path length was seen. */
        if (ret == 0) {
            /* isCA in certificate is a 1 bit of a byte. */
            cert->isCA = isCA ? 1 : 0;
            cert->pathLengthSet = (dataASN[BASICCONSASN_IDX_PLEN].length > 0);
        }
    }

    FREE_ASNGETDATA(dataASN, cert->heap);
    return ret;
#endif
}


static int DecodePolicyConstraints(const byte* input, int sz, DecodedCert* cert)
{
    word32 idx = 0;
    int length = 0;
    int skipLength = 0;
    int ret;
    byte tag;

    WOLFSSL_ENTER("DecodePolicyConstraints");

    if (GetSequence(input, &idx, &length, (word32)sz) < 0) {
        WOLFSSL_MSG("\tfail: bad SEQUENCE");
        return ASN_PARSE_E;
    }

    if (length == 0)
        return ASN_PARSE_E;

    if (GetASNTag(input, &idx, &tag, (word32)sz) < 0) {
        WOLFSSL_MSG("\tfail: bad TAG");
        return ASN_PARSE_E;
    }

    if (tag == (ASN_CONTEXT_SPECIFIC | 0)) {
        /* requireExplicitPolicy */
        cert->extPolicyConstRxpSet = 1;
    }
    else if (tag == (ASN_CONTEXT_SPECIFIC | 1)) {
        /* inhibitPolicyMapping */
        cert->extPolicyConstIpmSet = 1;
    }
    else {
        WOLFSSL_MSG("\tfail: invalid TAG");
        return ASN_PARSE_E;
    }

    ret = GetLength(input, &idx, &skipLength, (word32)sz);
    if (ret < 0) {
        WOLFSSL_MSG("\tfail: invalid length");
        return ret;
    }
    if (skipLength > 1) {
        WOLFSSL_MSG("\tfail: skip value too big");
        return BUFFER_E;
    }
    if (idx >= (word32)sz) {
        WOLFSSL_MSG("\tfail: no policy const skip to read");
        return BUFFER_E;
    }
    cert->policyConstSkip = input[idx];

    return 0;
}


/* Context-Specific value for: DistributionPoint.distributionPoint
 * From RFC5280 SS4.2.1.13, Distribution Point */
#define DISTRIBUTION_POINT  (ASN_CONTEXT_SPECIFIC | 0)
/* Context-Specific value for: DistributionPoint.DistributionPointName.fullName
 *  From RFC3280 SS4.2.1.13, Distribution Point Name */
#define CRLDP_FULL_NAME     (ASN_CONTEXT_SPECIFIC | 0)
/* Context-Specific value for choice: GeneralName.uniformResourceIdentifier
 * From RFC3280 SS4.2.1.7, GeneralName */
#define GENERALNAME_URI     (ASN_CONTEXT_SPECIFIC | 6)

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for CRL distribution points.
 * X.509: RFC 5280, 4.2.1.13 - CRL Distribution Points.
 */
static const ASNItem crlDistASN[] = {
/* SEQ                */ { 0, ASN_SEQUENCE, 1, 1, 0 },
/* DP_SEQ             */     { 1, ASN_SEQUENCE, 1, 1, 0 },
                                                /* Distribution point name */
/* DP_DISTPOINT       */         { 2, DISTRIBUTION_POINT, 1, 1, 1 },
                                                    /* fullName */
/* DP_DISTPOINT_FN    */             { 3, CRLDP_FULL_NAME, 1, 1, 2 },
/* DP_DISTPOINT_FN_GN */                 { 4, GENERALNAME_URI, 0, 0, 0 },
                                                    /* nameRelativeToCRLIssuer */
/* DP_DISTPOINT_RN    */             { 3, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 2 },
                                                /* reasons: IMPLICIT BIT STRING */
/* DP_REASONS         */         { 2, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
                                                /* cRLIssuer */
/* DP_CRLISSUER       */         { 2, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 1 },
};
enum {
    CRLDISTASN_IDX_SEQ = 0,
    CRLDISTASN_IDX_DP_SEQ,
    CRLDISTASN_IDX_DP_DISTPOINT,
    CRLDISTASN_IDX_DP_DISTPOINT_FN,
    CRLDISTASN_IDX_DP_DISTPOINT_FN_GN,
    CRLDISTASN_IDX_DP_DISTPOINT_RN, /* Relative name */
    CRLDISTASN_IDX_DP_REASONS,
    CRLDISTASN_IDX_DP_CRLISSUER
};

/* Number of items in ASN.1 template for CRL distribution points. */
#define crlDistASN_Length (sizeof(crlDistASN) / sizeof(ASNItem))
#endif

/* Decode CRL distribution point extension in a certificate.
 *
 * X.509: RFC 5280, 4.2.1.13 - CRL Distribution Points.
 *
 * @param [in]      input  Buffer holding data.
 * @param [in]      sz     Size of data in buffer.
 * @param [in, out] cert   Certificate object.
 * @return  0 on success.
 * @return  MEMORY_E on dynamic memory allocation failure.
 * @return  ASN_PARSE_E when invalid bits of reason are set.
 * @return  ASN_PARSE_E when BITSTRING value is more than 2 bytes.
 * @return  ASN_PARSE_E when unused bits of BITSTRING is invalid.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 */
static int DecodeCrlDist(const byte* input, word32 sz, DecodedCert* cert)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx = 0, localIdx;
    int length = 0;
    byte tag   = 0;

    WOLFSSL_ENTER("DecodeCrlDist");

    cert->extCrlInfoRaw = input;
    cert->extCrlInfoRawSz = (int)sz;

    /* Unwrap the list of Distribution Points*/
    if (GetSequence(input, &idx, &length, sz) < 0)
        return ASN_PARSE_E;

    /* Unwrap a single Distribution Point */
    if (GetSequence(input, &idx, &length, sz) < 0)
        return ASN_PARSE_E;

    /* The Distribution Point has three explicit optional members
     *  First check for a DistributionPointName
     */
    localIdx = idx;
    if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
            tag == (ASN_CONSTRUCTED | DISTRIBUTION_POINT))
    {
        idx++;
        if (GetLength(input, &idx, &length, sz) < 0)
            return ASN_PARSE_E;

        localIdx = idx;
        if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
                tag == (ASN_CONSTRUCTED | CRLDP_FULL_NAME))
        {
            idx++;
            if (GetLength(input, &idx, &length, sz) < 0)
                return ASN_PARSE_E;

            localIdx = idx;
            if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
                    tag == GENERALNAME_URI)
            {
                idx++;
                if (GetLength(input, &idx, &length, sz) < 0)
                    return ASN_PARSE_E;

                cert->extCrlInfoSz = length;
                cert->extCrlInfo = input + idx;
                idx += (word32)length;
            }
            else
                /* This isn't a URI, skip it. */
                idx += (word32)length;
        }
        else {
            /* This isn't a FULLNAME, skip it. */
            idx += (word32)length;
        }
    }

    /* Check for reasonFlags */
    localIdx = idx;
    if (idx < (word32)sz &&
        GetASNTag(input, &localIdx, &tag, sz) == 0 &&
        tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
    {
        idx++;
        if (GetLength(input, &idx, &length, sz) < 0)
            return ASN_PARSE_E;
        idx += (word32)length;
    }

    /* Check for cRLIssuer */
    localIdx = idx;
    if (idx < (word32)sz &&
        GetASNTag(input, &localIdx, &tag, sz) == 0 &&
        tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 2))
    {
        idx++;
        if (GetLength(input, &idx, &length, sz) < 0)
            return ASN_PARSE_E;
        idx += (word32)length;
    }

    if (idx < (word32)sz)
    {
        WOLFSSL_MSG("\tThere are more CRL Distribution Point records, "
                   "but we only use the first one.");
    }

    return 0;
#else
    DECL_ASNGETDATA(dataASN, crlDistASN_Length);
    word32 idx = 0;
    int ret = 0;
#ifdef CRLDP_VALIDATE_DATA
    word16 reason;
#endif

    WOLFSSL_ENTER("DecodeCrlDist");

    CALLOC_ASNGETDATA(dataASN, crlDistASN_Length, ret, cert->heap);

    cert->extCrlInfoRaw = input;
    cert->extCrlInfoRawSz = (int)sz;

    if  (ret == 0) {
        /* Get the GeneralName choice */
        GetASN_Choice(&dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN], generalNameChoice);
        /* Parse CRL distribtion point. */
        ret = GetASN_Items(crlDistASN, dataASN, crlDistASN_Length, 0, input,
                           &idx, sz);
    }
    if (ret == 0) {
        /* If the choice was a URI, store it in certificate. */
        if (dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN].tag == GENERALNAME_URI) {
            word32 sz32;
            GetASN_GetConstRef(&dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN],
                    &cert->extCrlInfo, &sz32);
            cert->extCrlInfoSz = (int)sz32;
        }

    #ifdef CRLDP_VALIDATE_DATA
        if (dataASN[CRLDISTASN_IDX_DP_REASONS].data.ref.data != NULL) {
             /* TODO: test case */
             /* Validate ReasonFlags. */
             ret = GetASN_BitString_Int16Bit(&dataASN[CRLDISTASN_IDX_DP_REASONS],
                     &reason);
             /* First bit (LSB) unused and eight other bits defined. */
             if ((ret == 0) && ((reason >> 9) || (reason & 0x01))) {
                WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
                ret = ASN_PARSE_E;
             }
        }
    #endif
    }

    /* Only parsing the first one. */
    if (ret == 0 && idx < (word32)sz) {
        WOLFSSL_MSG("\tThere are more CRL Distribution Point records, "
                    "but we only use the first one.");
    }
    /* TODO: validate other points. */

    FREE_ASNGETDATA(dataASN, cert->heap);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for the access description.
 * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
 */
static const ASNItem accessDescASN[] = {
/* SEQ  */ { 0, ASN_SEQUENCE, 1, 1, 0 },
                                 /* accessMethod */
/* METH */     { 1, ASN_OBJECT_ID, 0, 0, 0 },
                                 /* accessLocation: GeneralName */
/* LOC  */     { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
};
enum {
    ACCESSDESCASN_IDX_SEQ = 0,
    ACCESSDESCASN_IDX_METH,
    ACCESSDESCASN_IDX_LOC
};

/* Number of items in ASN.1 template for the access description. */
#define accessDescASN_Length (sizeof(accessDescASN) / sizeof(ASNItem))
#endif

/* Decode authority information access extension in a certificate.
 *
 * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
 *
 * @param [in]      input  Buffer holding data.
 * @param [in]      sz     Size of data in buffer.
 * @param [in, out] cert   Certificate object.
 * @return  0 on success.
 * @return  MEMORY_E on dynamic memory allocation failure.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
 * @return  ASN_UNKNOWN_OID_E when the OID cannot be verified.
 */
static int DecodeAuthInfo(const byte* input, word32 sz, DecodedCert* cert)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx = 0;
    int length = 0;
    int count  = 0;
    byte b = 0;
    word32 oid;

    WOLFSSL_ENTER("DecodeAuthInfo");

    /* Unwrap the list of AIAs */
    if (GetSequence(input, &idx, &length, sz) < 0)
        return ASN_PARSE_E;

    while ((idx < (word32)sz) && (count < MAX_AIA_SZ)) {
        /* Unwrap a single AIA */
        if (GetSequence(input, &idx, &length, sz) < 0)
            return ASN_PARSE_E;

        oid = 0;
        if (GetObjectId(input, &idx, &oid, oidCertAuthInfoType, sz) < 0) {
            return ASN_PARSE_E;
        }

        /* Only supporting URIs right now. */
        if (GetASNTag(input, &idx, &b, sz) < 0)
            return ASN_PARSE_E;

        if (GetLength(input, &idx, &length, sz) < 0)
            return ASN_PARSE_E;

        /* Set ocsp entry */
        if (b == GENERALNAME_URI && oid == AIA_OCSP_OID)
        {
            cert->extAuthInfoSz = length;
            cert->extAuthInfo = input + idx;
        #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
            count++;
        #else
            break;
        #endif
        }
        #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
        /* Set CaIssuers entry */
        else if ((b == GENERALNAME_URI) && oid == AIA_CA_ISSUER_OID)
        {
            cert->extAuthInfoCaIssuerSz = length;
            cert->extAuthInfoCaIssuer = input + idx;
            count++;
        }
        #endif
        idx += (word32)length;
    }

    return 0;
#else
    word32 idx = 0;
    int length = 0;
    int count  = 0;
    int ret    = 0;

    WOLFSSL_ENTER("DecodeAuthInfo");

    /* Unwrap the list of AIAs */
    if (GetASN_Sequence(input, &idx, &length, sz, 1) < 0) {
        ret = ASN_PARSE_E;
    }

    while ((ret == 0) && (idx < (word32)sz) && (count < MAX_AIA_SZ)) {
        ASNGetData dataASN[accessDescASN_Length];

        /* Clear dynamic data and retrieve OID and name. */
        XMEMSET(dataASN, 0, sizeof(dataASN));
        GetASN_OID(&dataASN[ACCESSDESCASN_IDX_METH], oidCertAuthInfoType);
        GetASN_Choice(&dataASN[ACCESSDESCASN_IDX_LOC], generalNameChoice);
        /* Parse AccessDescription. */
        ret = GetASN_Items(accessDescASN, dataASN, accessDescASN_Length, 0,
                           input, &idx, sz);
        if (ret == 0) {
            word32 sz32;

            /* Check we have OCSP and URI. */
            if ((dataASN[ACCESSDESCASN_IDX_METH].data.oid.sum == AIA_OCSP_OID) &&
                    (dataASN[ACCESSDESCASN_IDX_LOC].tag == GENERALNAME_URI)) {
                /* Store URI for OCSP lookup. */
                GetASN_GetConstRef(&dataASN[ACCESSDESCASN_IDX_LOC],
                        &cert->extAuthInfo, &sz32);
                cert->extAuthInfoSz = (int)sz32;
            #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
                count++;
            #else
                break;
            #endif
            }
            #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
            /* Check we have CA Issuer and URI. */
            else if ((dataASN[ACCESSDESCASN_IDX_METH].data.oid.sum ==
                        AIA_CA_ISSUER_OID) &&
                    (dataASN[ACCESSDESCASN_IDX_LOC].tag == GENERALNAME_URI)) {
                /* Set CaIssuers entry */
                GetASN_GetConstRef(&dataASN[ACCESSDESCASN_IDX_LOC],
                        &cert->extAuthInfoCaIssuer, &sz32);
                cert->extAuthInfoCaIssuerSz = sz32;
                count++;
            }
            #endif
            /* Otherwise skip. */
        }
    }

    return ret;
#endif
}


#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for AuthorityKeyIdentifier.
 * X.509: RFC 5280, 4.2.1.1 - Authority Key Identifier.
 */
static const ASNItem authKeyIdASN[] = {
/* SEQ    */    { 0, ASN_SEQUENCE, 1, 1, 0 },
                                     /* keyIdentifier */
/* KEYID  */        { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_KEYID, 0, 0, 1 },
                                     /* authorityCertIssuer */
/* ISSUER */        { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_ISSUER, 1, 0, 1 },
                                     /* authorityCertSerialNumber */
/* SERIAL */        { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_SERIAL, 0, 0, 1 },
};
enum {
    AUTHKEYIDASN_IDX_SEQ = 0,
    AUTHKEYIDASN_IDX_KEYID,
    AUTHKEYIDASN_IDX_ISSUER,
    AUTHKEYIDASN_IDX_SERIAL
};

/* Number of items in ASN.1 template for AuthorityKeyIdentifier. */
#define authKeyIdASN_Length (sizeof(authKeyIdASN) / sizeof(ASNItem))
#endif

/* Decode authority information access extension in a certificate.
 *
 * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
 *
 * @param [in]      input  Buffer holding data.
 * @param [in]      sz     Size of data in buffer.
 * @param [in, out] cert   Certificate object.
 * @return  0 on success.
 * @return  MEMORY_E on dynamic memory allocation failure.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 */
static int DecodeAuthKeyId(const byte* input, word32 sz, DecodedCert* cert)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx = 0;
    int length = 0;
    byte tag;

    WOLFSSL_ENTER("DecodeAuthKeyId");

    if (GetSequence(input, &idx, &length, sz) < 0) {
        WOLFSSL_MSG("\tfail: should be a SEQUENCE");
        return ASN_PARSE_E;
    }

    if (GetASNTag(input, &idx, &tag, sz) < 0) {
        return ASN_PARSE_E;
    }

    if (tag != (ASN_CONTEXT_SPECIFIC | 0)) {
        WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
        cert->extAuthKeyIdSet = 0;
        return 0;
    }

    if (GetLength(input, &idx, &length, sz) <= 0) {
        WOLFSSL_MSG("\tfail: extension data length");
        return ASN_PARSE_E;
    }

#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
#ifdef WOLFSSL_AKID_NAME
    cert->extRawAuthKeyIdSrc = input;
    cert->extRawAuthKeyIdSz = sz;
#endif
    cert->extAuthKeyIdSrc = &input[idx];
    cert->extAuthKeyIdSz = length;
#endif /* OPENSSL_EXTRA */

    return GetHashId(input + idx, length, cert->extAuthKeyId);
#else
    DECL_ASNGETDATA(dataASN, authKeyIdASN_Length);
    int ret = 0;
    word32 idx = 0;

    WOLFSSL_ENTER("DecodeAuthKeyId");

    CALLOC_ASNGETDATA(dataASN, authKeyIdASN_Length, ret, cert->heap);

    if (ret == 0) {
        /* Parse an authority key identifier. */
        ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length, 1, input,
                           &idx, sz);
    }
    if (ret == 0) {
        /* Key id is optional. */
        if (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data == NULL) {
            WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
        }
        else {
#ifdef OPENSSL_EXTRA
            /* Store the authority key id. */
#ifdef WOLFSSL_AKID_NAME
            cert->extRawAuthKeyIdSrc = input;
            cert->extRawAuthKeyIdSz = sz;
#endif
            GetASN_GetConstRef(&dataASN[AUTHKEYIDASN_IDX_KEYID], &cert->extAuthKeyIdSrc,
                               &cert->extAuthKeyIdSz);
#endif /* OPENSSL_EXTRA */

            /* Get the hash or hash of the hash if wrong size. */
            ret = GetHashId(dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
                        (int)dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
                        cert->extAuthKeyId);
        }
    }

    FREE_ASNGETDATA(dataASN, cert->heap);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

/* Decode subject key id extension in a certificate.
 *
 * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
 *
 * @param [in]      input  Buffer holding data.
 * @param [in]      sz     Size of data in buffer.
 * @param [in, out] cert   Certificate object.
 * @return  0 on success.
 * @return  ASN_PARSE_E when the OCTET_STRING tag is not found or length is
 *          invalid.
 * @return  MEMORY_E on dynamic memory allocation failure.
 */
static int DecodeSubjKeyId(const byte* input, word32 sz, DecodedCert* cert)
{
    word32 idx = 0;
    int length = 0;
    int ret = 0;

    WOLFSSL_ENTER("DecodeSubjKeyId");

    ret = GetOctetString(input, &idx, &length, sz);
    if (ret > 0) {
    #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
        cert->extSubjKeyIdSrc = &input[idx];
        cert->extSubjKeyIdSz = length;
    #endif /* OPENSSL_EXTRA */

        /* Get the hash or hash of the hash if wrong size. */
        ret = GetHashId(input + idx, length, cert->extSubjKeyId);
    }

    return ret;
}

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for KeyUsage.
 * X.509: RFC 5280, 4.2.1.3 - Key Usage.
 */
static const ASNItem keyUsageASN[] = {
/* STR */ { 0, ASN_BIT_STRING, 0, 0, 0 },
};
enum {
    KEYUSAGEASN_IDX_STR = 0
};

/* Number of items in ASN.1 template for KeyUsage. */
#define keyUsageASN_Length (sizeof(keyUsageASN) / sizeof(ASNItem))
#endif

/* Decode key usage extension in a certificate.
 *
 * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
 *
 * @param [in]      input  Buffer holding data.
 * @param [in]      sz     Size of data in buffer.
 * @param [in, out] cert   Certificate object.
 * @return  0 on success.
 * @return  ASN_BITSTR_E when the expected BIT_STRING tag is not found.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  MEMORY_E on dynamic memory allocation failure.
 */
static int DecodeKeyUsage(const byte* input, word32 sz, DecodedCert* cert)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx = 0;
    int length;
    int ret;
    WOLFSSL_ENTER("DecodeKeyUsage");

    ret = CheckBitString(input, &idx, &length, sz, 0, NULL);
    if (ret != 0)
        return ret;

    if (length == 0 || length > 2)
        return ASN_PARSE_E;

    cert->extKeyUsage = (word16)(input[idx]);
    if (length == 2)
        cert->extKeyUsage |= (word16)(input[idx+1] << 8);

    return 0;
#else
    ASNGetData dataASN[keyUsageASN_Length];
    word32 idx = 0;
    WOLFSSL_ENTER("DecodeKeyUsage");

    /* Clear dynamic data and set where to store extended key usage. */
    XMEMSET(dataASN, 0, sizeof(dataASN));
    GetASN_Int16Bit(&dataASN[KEYUSAGEASN_IDX_STR], &cert->extKeyUsage);
    /* Parse key usage. */
    return GetASN_Items(keyUsageASN, dataASN, keyUsageASN_Length, 0, input,
                        &idx, sz);
#endif /* WOLFSSL_ASN_TEMPLATE */
}

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for KeyPurposeId.
 * X.509: RFC 5280, 4.2.1.12 - Extended Key Usage.
 */
static const ASNItem keyPurposeIdASN[] = {
/* OID */ { 0, ASN_OBJECT_ID, 0, 0, 0 },
};
enum {
    KEYPURPOSEIDASN_IDX_OID = 0
};

/* Number of items in ASN.1 template for KeyPurposeId. */
#define keyPurposeIdASN_Length (sizeof(keyPurposeIdASN) / sizeof(ASNItem))
#endif

/* Decode extended key usage extension in a certificate.
 *
 * X.509: RFC 5280, 4.2.1.12 - Extended Key Usage.
 *
 * @param [in]      input  Buffer holding data.
 * @param [in]      sz     Size of data in buffer.
 * @param [in, out] cert   Certificate object.
 * @return  0 on success.
 * @return  ASN_BITSTR_E when the expected BIT_STRING tag is not found.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  MEMORY_E on dynamic memory allocation failure.
 */
static int DecodeExtKeyUsage(const byte* input, word32 sz, DecodedCert* cert)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx = 0, oid;
    int length, ret;

    WOLFSSL_ENTER("DecodeExtKeyUsage");

    if (GetSequence(input, &idx, &length, sz) < 0) {
        WOLFSSL_MSG("\tfail: should be a SEQUENCE");
        return ASN_PARSE_E;
    }

#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
    cert->extExtKeyUsageSrc = input + idx;
    cert->extExtKeyUsageSz = length;
#endif

    while (idx < (word32)sz) {
        ret = GetObjectId(input, &idx, &oid, oidCertKeyUseType, sz);
        if (ret == ASN_UNKNOWN_OID_E)
            continue;
        else if (ret < 0)
            return ret;

        switch (oid) {
            case EKU_ANY_OID:
                cert->extExtKeyUsage |= EXTKEYUSE_ANY;
                break;
            case EKU_SERVER_AUTH_OID:
                cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
                break;
            case EKU_CLIENT_AUTH_OID:
                cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
                break;
            case EKU_CODESIGNING_OID:
                cert->extExtKeyUsage |= EXTKEYUSE_CODESIGN;
                break;
            case EKU_EMAILPROTECT_OID:
                cert->extExtKeyUsage |= EXTKEYUSE_EMAILPROT;
                break;
            case EKU_TIMESTAMP_OID:
                cert->extExtKeyUsage |= EXTKEYUSE_TIMESTAMP;
                break;
            case EKU_OCSP_SIGN_OID:
                cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
                break;
            #ifdef WOLFSSL_WOLFSSH
            case EKU_SSH_CLIENT_AUTH_OID:
                cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_CLIENT_AUTH;
                break;
            case EKU_SSH_MSCL_OID:
                cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_MSCL;
                break;
            case EKU_SSH_KP_CLIENT_AUTH_OID:
                cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_KP_CLIENT_AUTH;
                break;
            #endif /* WOLFSSL_WOLFSSH */
            default:
                break;
        }

    #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
        cert->extExtKeyUsageCount++;
    #endif
    }

    return 0;
#else
    word32 idx = 0;
    int length;
    int ret = 0;

    WOLFSSL_ENTER("DecodeExtKeyUsage");

    /* Strip SEQUENCE OF and expect to account for all the data. */
    if (GetASN_Sequence(input, &idx, &length, sz, 1) < 0) {
        WOLFSSL_MSG("\tfail: should be a SEQUENCE");
        ret = ASN_PARSE_E;
    }

    if (ret == 0) {
    #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
        /* Keep reference for WOLFSSL_X509. */
        cert->extExtKeyUsageSrc = input + idx;
        cert->extExtKeyUsageSz = length;
    #endif
    }

    /* Check all OIDs. */
    while ((ret == 0) && (idx < (word32)sz)) {
        ASNGetData dataASN[keyPurposeIdASN_Length];

        /* Clear dynamic data items and set OID type expected. */
        XMEMSET(dataASN, 0, sizeof(dataASN));
        GetASN_OID(&dataASN[KEYPURPOSEIDASN_IDX_OID], oidIgnoreType);
        /* Decode KeyPurposeId. */
        ret = GetASN_Items(keyPurposeIdASN, dataASN, keyPurposeIdASN_Length, 0,
                           input, &idx, sz);
        /* Skip unknown OIDs. */
        if (ret == ASN_UNKNOWN_OID_E) {
            ret = 0;
        }
        else if (ret == 0) {
            /* Store the bit for the OID. */
            switch (dataASN[KEYPURPOSEIDASN_IDX_OID].data.oid.sum) {
                case EKU_ANY_OID:
                    cert->extExtKeyUsage |= EXTKEYUSE_ANY;
                    break;
                case EKU_SERVER_AUTH_OID:
                    cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
                    break;
                case EKU_CLIENT_AUTH_OID:
                    cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
                    break;
                case EKU_CODESIGNING_OID:
                    cert->extExtKeyUsage |= EXTKEYUSE_CODESIGN;
                    break;
                case EKU_EMAILPROTECT_OID:
                    cert->extExtKeyUsage |= EXTKEYUSE_EMAILPROT;
                    break;
                case EKU_TIMESTAMP_OID:
                    cert->extExtKeyUsage |= EXTKEYUSE_TIMESTAMP;
                    break;
                case EKU_OCSP_SIGN_OID:
                    cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
                    break;
            }

        #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
            /* Keep count for WOLFSSL_X509. */
            cert->extExtKeyUsageCount++;
        #endif
        }
    }

    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

#ifndef IGNORE_NETSCAPE_CERT_TYPE

static int DecodeNsCertType(const byte* input, int sz, DecodedCert* cert)
{
    word32 idx = 0;
    int len = 0;

    WOLFSSL_ENTER("DecodeNsCertType");

    if (CheckBitString(input, &idx, &len, (word32)sz, 0, NULL) < 0)
        return ASN_PARSE_E;

    /* Don't need to worry about unused bits as CheckBitString makes sure
     * they're zero. */
    if (idx < (word32)sz)
        cert->nsCertType = input[idx];
    else
        return ASN_PARSE_E;

    return 0;
}
#endif


#ifndef IGNORE_NAME_CONSTRAINTS
#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for GeneralSubtree.
 * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
 */
static const ASNItem subTreeASN[] = {
/* SEQ  */ { 0, ASN_SEQUENCE, 1, 1, 0 },
                              /* base     GeneralName */
/* BASE */     { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
                              /* minimum  BaseDistance DEFAULT 0*/
/* MIN  */     { 1, ASN_CONTEXT_SPECIFIC | ASN_SUBTREE_MIN, 0, 0, 1 },
                              /* maximum  BaseDistance OPTIONAL  */
/* MAX  */     { 1, ASN_CONTEXT_SPECIFIC | ASN_SUBTREE_MAX, 0, 0, 1 },
};
enum {
    SUBTREEASN_IDX_SEQ = 0,
    SUBTREEASN_IDX_BASE,
    SUBTREEASN_IDX_MIN,
    SUBTREEASN_IDX_MAX
};

/* Number of items in ASN.1 template for GeneralSubtree. */
#define subTreeASN_Length (sizeof(subTreeASN) / sizeof(ASNItem))
#endif

#ifdef WOLFSSL_ASN_TEMPLATE
/* Decode the Subtree's GeneralName.
 *
 * @param [in]      input  Buffer holding data.
 * @param [in]      sz     Size of data in buffer.
 * @param [in]      tag    BER tag on GeneralName.
 * @param [in, out] head   Linked list of subtree names.
 * @param [in]      heap   Dynamic memory hint.
 * @return  0 on success.
 * @return  MEMORY_E when dynamic memory allocation fails.
 * @return  ASN_PARSE_E when SEQUENCE is not found as expected.
 */
static int DecodeSubtreeGeneralName(const byte* input, word32 sz, byte tag,
                                    Base_entry** head, void* heap)
{
    Base_entry* entry;
    word32 nameIdx = 0;
    word32 len = sz;
    int strLen;
    int ret = 0;

    (void)heap;

    /* if constructed has leading sequence */
    if ((tag & ASN_CONSTRUCTED) == ASN_CONSTRUCTED) {
        ret = GetASN_Sequence(input, &nameIdx, &strLen, sz, 0);
        if (ret < 0) {
            ret = ASN_PARSE_E;
        }
        else {
            len = (word32)strLen;
            ret = 0;
        }
    }
    if (ret == 0) {
        /* TODO: consider one malloc. */
        /* Allocate Base Entry object. */
        entry = (Base_entry*)XMALLOC(sizeof(Base_entry), heap,
                                     DYNAMIC_TYPE_ALTNAME);
        if (entry == NULL) {
            ret = MEMORY_E;
        }
    }
    if (ret == 0) {
        /* Allocate name. */
        entry->name = (char*)XMALLOC(len + 1, heap, DYNAMIC_TYPE_ALTNAME);
        if (entry->name == NULL) {
            XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME);
            ret = MEMORY_E;
        }
    }
    if (ret == 0) {
        /* Store name, size and tag in object. */
        XMEMCPY(entry->name, &input[nameIdx], len);
        entry->name[len] = '\0';
        entry->nameSz = (int)len;
        entry->type = tag & ASN_TYPE_MASK;

        /* Put entry at front of linked list. */
        entry->next = *head;
        *head = entry;
    }

    return ret;
}
#endif

/* Decode a subtree of a name constraints in a certificate.
 *
 * X.509: RFC 5280, 4.2.1.10 - Name Contraints.
 *
 * @param [in]      input  Buffer holding data.
 * @param [in]      sz     Size of data in buffer.
 * @param [in, out] head   Linked list of subtree names.
 * @param [in]      heap   Dynamic memory hint.
 * @return  0 on success.
 * @return  MEMORY_E when dynamic memory allocation fails.
 * @return  ASN_PARSE_E when SEQUENCE is not found as expected.
 */
static int DecodeSubtree(const byte* input, word32 sz, Base_entry** head,
                         void* heap)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx = 0;
    int ret = 0;

    (void)heap;

    while (idx < (word32)sz) {
        int seqLength, strLength;
        word32 nameIdx;
        byte b, bType;

        if (GetSequence(input, &idx, &seqLength, sz) < 0) {
            WOLFSSL_MSG("\tfail: should be a SEQUENCE");
            return ASN_PARSE_E;
        }

        if (idx >= (word32)sz) {
            WOLFSSL_MSG("\tfail: expecting tag");
            return ASN_PARSE_E;
        }

        nameIdx = idx;
        b = input[nameIdx++];

        if (GetLength(input, &nameIdx, &strLength, sz) <= 0) {
            WOLFSSL_MSG("\tinvalid length");
            return ASN_PARSE_E;
        }

        /* Get type, LSB 4-bits */
        bType = (byte)(b & ASN_TYPE_MASK);

        if (bType == ASN_DNS_TYPE || bType == ASN_RFC822_TYPE ||
                                                        bType == ASN_DIR_TYPE) {
            Base_entry* entry;

            /* if constructed has leading sequence */
            if (b & ASN_CONSTRUCTED) {
                if (GetSequence(input, &nameIdx, &strLength, sz) < 0) {
                    WOLFSSL_MSG("\tfail: constructed be a SEQUENCE");
                    return ASN_PARSE_E;
                }
            }

            entry = (Base_entry*)XMALLOC(sizeof(Base_entry), heap,
                                                          DYNAMIC_TYPE_ALTNAME);
            if (entry == NULL) {
                WOLFSSL_MSG("allocate error");
                return MEMORY_E;
            }

            entry->name = (char*)XMALLOC((size_t)strLength+1, heap,
                DYNAMIC_TYPE_ALTNAME);
            if (entry->name == NULL) {
                WOLFSSL_MSG("allocate error");
                XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME);
                return MEMORY_E;
            }

            XMEMCPY(entry->name, &input[nameIdx], (size_t)strLength);
            entry->name[strLength] = '\0';
            entry->nameSz = strLength;
            entry->type = bType;

            entry->next = *head;
            *head = entry;
        }

        idx += (word32)seqLength;
    }

    return ret;
#else
    DECL_ASNGETDATA(dataASN, subTreeASN_Length);
    word32 idx = 0;
    int ret = 0;

    (void)heap;

    ALLOC_ASNGETDATA(dataASN, subTreeASN_Length, ret, heap);

    /* Process all subtrees. */
    while ((ret == 0) && (idx < (word32)sz)) {
        byte minVal = 0;
        byte maxVal = 0;

        /* Clear dynamic data and set choice for GeneralName and location to
         * store minimum and maximum.
         */
        XMEMSET(dataASN, 0, sizeof(*dataASN) * subTreeASN_Length);
        GetASN_Choice(&dataASN[SUBTREEASN_IDX_BASE], generalNameChoice);
        GetASN_Int8Bit(&dataASN[SUBTREEASN_IDX_MIN], &minVal);
        GetASN_Int8Bit(&dataASN[SUBTREEASN_IDX_MAX], &maxVal);
        /* Parse GeneralSubtree. */
        ret = GetASN_Items(subTreeASN, dataASN, subTreeASN_Length, 0, input,
                           &idx, sz);
        if (ret == 0) {
            byte t = dataASN[SUBTREEASN_IDX_BASE].tag;

            /* Check GeneralName tag is one of the types we can handle. */
            if (t == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE) ||
                t == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE) ||
                t == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
                /* Parse the general name and store a new entry. */
                ret = DecodeSubtreeGeneralName(input +
                    GetASNItem_DataIdx(dataASN[SUBTREEASN_IDX_BASE], input),
                    dataASN[SUBTREEASN_IDX_BASE].length, t, head, heap);
            }
            /* Skip entry. */
        }
    }

    FREE_ASNGETDATA(dataASN, heap);
    return ret;
#endif
}

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for NameConstraints.
 * X.509: RFC 5280, 4.2.1.10 - Name Contraints.
 */
static const ASNItem nameConstraintsASN[] = {
/* SEQ     */ { 0, ASN_SEQUENCE, 1, 1, 0 },
                                         /* permittedSubtrees */
/* PERMIT  */     { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 1 },
                                         /* excludededSubtrees */
/* EXCLUDE */     { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
};
enum {
    NAMECONSTRAINTSASN_IDX_SEQ = 0,
    NAMECONSTRAINTSASN_IDX_PERMIT,
    NAMECONSTRAINTSASN_IDX_EXCLUDE
};

/* Number of items in ASN.1 template for NameConstraints. */
#define nameConstraintsASN_Length (sizeof(nameConstraintsASN) / sizeof(ASNItem))
#endif

/* Decode name constraints extension in a certificate.
 *
 * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
 *
 * @param [in]      input  Buffer holding data.
 * @param [in]      sz     Size of data in buffer.
 * @param [in, out] cert   Certificate object.
 * @return  0 on success.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  MEMORY_E on dynamic memory allocation failure.
 */
static int DecodeNameConstraints(const byte* input, word32 sz,
    DecodedCert* cert)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx = 0;
    int length = 0;

    WOLFSSL_ENTER("DecodeNameConstraints");

    if (GetSequence(input, &idx, &length, sz) < 0) {
        WOLFSSL_MSG("\tfail: should be a SEQUENCE");
        return ASN_PARSE_E;
    }

    while (idx < (word32)sz) {
        byte b = input[idx++];
        Base_entry** subtree = NULL;

        if (GetLength(input, &idx, &length, sz) <= 0) {
            WOLFSSL_MSG("\tinvalid length");
            return ASN_PARSE_E;
        }

        if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0))
            subtree = &cert->permittedNames;
        else if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1))
            subtree = &cert->excludedNames;
        else {
            WOLFSSL_MSG("\tinvalid subtree");
            return ASN_PARSE_E;
        }

        if (DecodeSubtree(input + idx, (word32)length, subtree,
                cert->heap) < 0) {
            WOLFSSL_MSG("\terror parsing subtree");
            return ASN_PARSE_E;
        }

        idx += (word32)length;
    }

    return 0;
#else
    DECL_ASNGETDATA(dataASN, nameConstraintsASN_Length);
    word32 idx = 0;
    int    ret = 0;

    CALLOC_ASNGETDATA(dataASN, nameConstraintsASN_Length, ret, cert->heap);

    if (ret == 0) {
        /* Parse NameConstraints. */
        ret = GetASN_Items(nameConstraintsASN, dataASN,
                           nameConstraintsASN_Length, 1, input, &idx, sz);
    }
    if (ret == 0) {
        /* If there was a permittedSubtrees then parse it. */
        if (dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.data != NULL) {
            ret = DecodeSubtree(
                    dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.data,
                    dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.length,
                    &cert->permittedNames, cert->heap);
        }
    }
    if (ret == 0) {
        /* If there was a excludedSubtrees then parse it. */
        if (dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.data != NULL) {
            ret = DecodeSubtree(
                    dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.data,
                    dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.length,
                    &cert->excludedNames, cert->heap);
        }
    }

    FREE_ASNGETDATA(dataASN, cert->heap);

    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}
#endif /* IGNORE_NAME_CONSTRAINTS */

#if (defined(WOLFSSL_CERT_EXT) && !defined(WOLFSSL_SEP)) || \
    defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)

/* Decode ITU-T X.690 OID format to a string representation
 * return string length */
int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz)
{
    word32 val, inIdx = 0, outIdx = 0;
    int w = 0;

    if (out == NULL || in == NULL || outSz < 4 || inSz < 2)
        return BAD_FUNC_ARG;

    /* The first byte expands into b/40 dot b%40. */
    val = in[inIdx++];

    w = XSNPRINTF(out, outSz, "%u.%u", val / 40, val % 40);
    if (w < 0) {
        w = BUFFER_E;
        goto exit;
    }
    outIdx += w;
    val = 0;

    while (inIdx < inSz && outIdx < outSz) {
        /* extract the next OID digit from in to val */
        /* first bit is used to set if value is coded on 1 or multiple bytes */
        if (in[inIdx] & 0x80) {
            val += in[inIdx] & 0x7F;
            val *= 128;
        }
        else {
            /* write val as text into out */
            val += in[inIdx];
            w = XSNPRINTF(out + outIdx, outSz - outIdx, ".%u", val);
            if (w < 0 || (word32)w > outSz - outIdx) {
                w = BUFFER_E;
                goto exit;
            }
            outIdx += w;
            val = 0;
        }
        inIdx++;
    }
    if (outIdx == outSz)
        outIdx--;
    out[outIdx] = 0;

    w = (int)outIdx;

exit:
    return w;
}
#endif /* WOLFSSL_CERT_EXT && !WOLFSSL_SEP */

#if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_QT)
    #ifdef WOLFSSL_ASN_TEMPLATE
    /* ASN.1 template for PolicyInformation.
     * X.509: RFC 5280, 4.2.1.4 - Certificate Policies.
     */
    static const ASNItem policyInfoASN[] = {
    /* SEQ   */ { 0, ASN_SEQUENCE, 1, 1, 0 },
                                      /* policyIdentifier */
    /* ID    */     { 1, ASN_OBJECT_ID, 0, 0, 0 },
                                      /* policyQualifiers */
    /* QUALI */     { 1, ASN_SEQUENCE, 1, 0, 1 },
    };
    enum {
        POLICYINFOASN_IDX_SEQ = 0,
        POLICYINFOASN_IDX_ID,
        POLICYINFOASN_IDX_QUALI
    };

    /* Number of items in ASN.1 template for PolicyInformation. */
    #define policyInfoASN_Length (sizeof(policyInfoASN) / sizeof(ASNItem))
    #endif

    /* Reference: https://tools.ietf.org/html/rfc5280#section-4.2.1.4 */
    static int DecodeCertPolicy(const byte* input, word32 sz, DecodedCert* cert)
    {
    #ifndef WOLFSSL_ASN_TEMPLATE
        word32 idx = 0;
        word32 oldIdx;
        int policy_length = 0;
        int ret;
        int total_length = 0;
    #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \
        !defined(WOLFSSL_DUP_CERTPOL)
        int i;
    #endif

        WOLFSSL_ENTER("DecodeCertPolicy");

    #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT)
        /* Check if cert is null before dereferencing below */
        if (cert == NULL)
            return BAD_FUNC_ARG;
    #else
        (void)cert;
    #endif

    #if defined(WOLFSSL_CERT_EXT)
         cert->extCertPoliciesNb = 0;
    #endif

        if (GetSequence(input, &idx, &total_length, sz) < 0) {
            WOLFSSL_MSG("\tGet CertPolicy total seq failed");
            return ASN_PARSE_E;
        }

        /* Validate total length */
        if (total_length > (int)(sz - idx)) {
            WOLFSSL_MSG("\tCertPolicy length mismatch");
            return ASN_PARSE_E;
        }

        /* Unwrap certificatePolicies */
        do {
            int length = 0;

            if (GetSequence(input, &idx, &policy_length, sz) < 0) {
                WOLFSSL_MSG("\tGet CertPolicy seq failed");
                return ASN_PARSE_E;
            }

            oldIdx = idx;
            ret = GetASNObjectId(input, &idx, &length, sz);
            if (ret != 0)
                return ret;
            policy_length -= (int)(idx - oldIdx);

            if (length > 0) {
                /* Verify length won't overrun buffer */
                if (length > (int)(sz - idx)) {
                    WOLFSSL_MSG("\tCertPolicy length exceeds input buffer");
                    return ASN_PARSE_E;
                }

        #if defined(WOLFSSL_SEP)
                cert->deviceType = (byte*)XMALLOC((size_t)length, cert->heap,
                                                         DYNAMIC_TYPE_X509_EXT);
                if (cert->deviceType == NULL) {
                    WOLFSSL_MSG("\tCouldn't alloc memory for deviceType");
                    return MEMORY_E;
                }
                cert->deviceTypeSz = length;
                XMEMCPY(cert->deviceType, input + idx, (size_t)length);
                break;
        #elif defined(WOLFSSL_CERT_EXT)
                /* decode cert policy */
                if (DecodePolicyOID(cert->extCertPolicies[
                                       cert->extCertPoliciesNb], MAX_CERTPOL_SZ,
                                       input + idx, length) <= 0) {
                    WOLFSSL_MSG("\tCouldn't decode CertPolicy");
                    WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
                    return ASN_PARSE_E;
                }
            #ifndef WOLFSSL_DUP_CERTPOL
                /* From RFC 5280 section 4.2.1.3 "A certificate policy OID MUST
                 * NOT appear more than once in a certificate policies
                 * extension". This is a sanity check for duplicates.
                 * extCertPolicies should only have OID values, additional
                 * qualifiers need to be stored in a separate array. */
                for (i = 0; i < cert->extCertPoliciesNb; i++) {
                    if (XMEMCMP(cert->extCertPolicies[i],
                            cert->extCertPolicies[cert->extCertPoliciesNb],
                            MAX_CERTPOL_SZ) == 0) {
                            WOLFSSL_MSG("Duplicate policy OIDs not allowed");
                            WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted");
                            WOLFSSL_ERROR_VERBOSE(CERTPOLICIES_E);
                            return CERTPOLICIES_E;
                    }
                }
            #endif /* !WOLFSSL_DUP_CERTPOL */
                cert->extCertPoliciesNb++;
        #else
                WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0);
                return 0;
        #endif
            }
            idx += (word32)policy_length;
        } while((int)idx < total_length
    #if defined(WOLFSSL_CERT_EXT)
            && cert->extCertPoliciesNb < MAX_CERTPOL_NB
    #endif
        );

        WOLFSSL_LEAVE("DecodeCertPolicy", 0);
        return 0;
    #else /* WOLFSSL_ASN_TEMPLATE */
        word32 idx = 0;
        int ret = 0;
        int total_length = 0;
    #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \
        !defined(WOLFSSL_DUP_CERTPOL)
        int i;
    #endif

        WOLFSSL_ENTER("DecodeCertPolicy");
        #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT)
        /* Check if cert is null before dereferencing below */
        if (cert == NULL)
            ret = BAD_FUNC_ARG;
        #endif

        if (ret == 0) {
        #if defined(WOLFSSL_CERT_EXT)
            cert->extCertPoliciesNb = 0;
        #endif

            /* Strip SEQUENCE OF and check using all data. */
            if (GetASN_Sequence(input, &idx, &total_length, (word32)sz, 1) < 0)
            {
               ret = ASN_PARSE_E;
            }
        }

        /* Unwrap certificatePolicies */
        while ((ret == 0) && ((int)idx < total_length)
        #if defined(WOLFSSL_CERT_EXT)
            && (cert->extCertPoliciesNb < MAX_CERTPOL_NB)
        #endif
               ) {
            ASNGetData dataASN[policyInfoASN_Length];
            byte* data = NULL;
            word32 length = 0;

            /* Clear dynamic data and check OID is a cert policy type. */
            XMEMSET(dataASN, 0, sizeof(dataASN));
            GetASN_OID(&dataASN[POLICYINFOASN_IDX_ID], oidCertPolicyType);
            ret = GetASN_Items(policyInfoASN, dataASN, policyInfoASN_Length, 1,
                               input, &idx, (word32)sz);
            if (ret == 0) {
                /* Get the OID. */
                GetASN_OIDData(&dataASN[POLICYINFOASN_IDX_ID], &data, &length);
                if (length == 0) {
                    ret = ASN_PARSE_E;
                }
            }
            #if defined(WOLFSSL_SEP)
            /* Store OID in device type. */
            if (ret == 0) {
                cert->deviceType = (byte*)XMALLOC(length, cert->heap,
                                                  DYNAMIC_TYPE_X509_EXT);
                if (cert->deviceType == NULL) {
                    WOLFSSL_MSG("\tCouldn't alloc memory for deviceType");
                    ret = MEMORY_E;
                }
            }
            if (ret == 0) {
                /* Store device type data and length. */
                cert->deviceTypeSz = (int)length;
                XMEMCPY(cert->deviceType, data, length);
                break;
            }
            #elif defined(WOLFSSL_CERT_EXT)
            if (ret == 0) {
                /* Decode cert policy. */
                if (DecodePolicyOID(
                                 cert->extCertPolicies[cert->extCertPoliciesNb],
                                 MAX_CERTPOL_SZ, data, length) <= 0) {
                    WOLFSSL_MSG("\tCouldn't decode CertPolicy");
                    WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
                    ret = ASN_PARSE_E;
                }
            }
            #ifndef WOLFSSL_DUP_CERTPOL
            /* From RFC 5280 section 4.2.1.3 "A certificate policy OID MUST
             * NOT appear more than once in a certificate policies
             * extension". This is a sanity check for duplicates.
             * extCertPolicies should only have OID values, additional
             * qualifiers need to be stored in a seperate array. */
            for (i = 0; (ret == 0) && (i < cert->extCertPoliciesNb); i++) {
                if (XMEMCMP(cert->extCertPolicies[i],
                            cert->extCertPolicies[cert->extCertPoliciesNb],
                            MAX_CERTPOL_SZ) == 0) {
                    WOLFSSL_MSG("Duplicate policy OIDs not allowed");
                    WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted");
                    WOLFSSL_ERROR_VERBOSE(CERTPOLICIES_E);
                    ret = CERTPOLICIES_E;
                }
            }
            #endif /* !defined(WOLFSSL_DUP_CERTPOL) */
            if (ret == 0) {
                /* Keep count of policies seen. */
                cert->extCertPoliciesNb++;
            }
            #else
                (void)data;
                WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0);
                break;
            #endif
        }

        WOLFSSL_LEAVE("DecodeCertPolicy", 0);
        return ret;
    #endif /* WOLFSSL_ASN_TEMPLATE */
    }
#endif /* WOLFSSL_SEP */

#ifdef WOLFSSL_SUBJ_DIR_ATTR
#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for subject dir attribute.
 * X.509: RFC 5280, 4.2.1.8 - Subject Directory Attributes.
 */
static const ASNItem subjDirAttrASN[] = {
/* SEQ  */     { 1, ASN_SEQUENCE, 1, 1, 0 },
/* OID  */          { 2, ASN_OBJECT_ID, 0, 0, 0 },
/* PLEN */          { 2, ASN_SET, 1, 0, 0 },
};
enum {
    SUBJDIRATTRASN_IDX_SEQ = 0,
    SUBJDIRATTRASN_IDX_OID,
    SUBJDIRATTRASN_IDX_SET,
};

/* Number of items in ASN.1 template for BasicContraints. */
#define subjDirAttrASN_Length (sizeof(subjDirAttrASN) / sizeof(ASNItem))
#endif
/* Decode subject directory attributes extension in a certificate.
 *
 * X.509: RFC 5280, 4.2.1.8 - Subject Directory Attributes.
 *
 * @param [in]      input  Buffer holding data.
 * @param [in]      sz     Size of data in buffer.
 * @param [in, out] cert   Certificate object.
 * @return  0 on success.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 */
static int DecodeSubjDirAttr(const byte* input, int sz, DecodedCert* cert)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx = 0;
    int length = 0;
    int ret = 0;

    WOLFSSL_ENTER("DecodeSubjDirAttr");

#ifdef OPENSSL_ALL
    cert->extSubjDirAttrSrc = input;
    cert->extSubjDirAttrSz = sz;
#endif /* OPENSSL_ALL */

    /* Unwrap the list of Attributes */
    if (GetSequence(input, &idx, &length, sz) < 0)
        return ASN_PARSE_E;

    if (length == 0) {
        /* RFC 5280 4.2.1.8.  Subject Directory Attributes
           If the subjectDirectoryAttributes extension is present, the
           sequence MUST contain at least one entry. */
        WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
        return ASN_PARSE_E;
    }

    /* length is the length of the list contents */
    while (idx < (word32)sz) {
        word32 oid;

        if (GetSequence(input, &idx, &length, sz) < 0)
            return ASN_PARSE_E;

        if (GetObjectId(input, &idx, &oid, oidSubjDirAttrType, sz) < 0)
            return ASN_PARSE_E;

        if (GetSet(input, &idx, &length, sz) < 0)
            return ASN_PARSE_E;

        /* There may be more than one countryOfCitizenship, but save the
         * first one for now. */
        if (oid == SDA_COC_OID) {
            byte tag;

            if (GetHeader(input, &tag, &idx, &length, sz, 1) < 0)
                return ASN_PARSE_E;

            if (length != COUNTRY_CODE_LEN)
                return ASN_PARSE_E;

            if (tag == ASN_PRINTABLE_STRING) {
                XMEMCPY(cert->countryOfCitizenship,
                        input + idx, COUNTRY_CODE_LEN);
                cert->countryOfCitizenship[COUNTRY_CODE_LEN] = 0;
            }
        }
        idx += length;
    }

    return ret;
#else
    DECL_ASNGETDATA(dataASN, subjDirAttrASN_Length);
    int ret = 0;
    word32 idx = 0;
    int length;

    WOLFSSL_ENTER("DecodeSubjDirAttr");

    CALLOC_ASNGETDATA(dataASN, subjDirAttrASN_Length, ret, cert->heap);

    /* Strip outer SEQUENCE. */
    if ((ret == 0) && (GetSequence(input, &idx, &length, sz) < 0)) {
        ret = ASN_PARSE_E;
    }
    /* Handle each inner SEQUENCE. */
    while ((ret == 0) && (idx < (word32)sz)) {
        ret = GetASN_Items(subjDirAttrASN, dataASN, subjDirAttrASN_Length, 1,
            input, &idx, sz);

        /* There may be more than one countryOfCitizenship, but save the
         * first one for now. */
        if ((ret == 0) &&
                (dataASN[SUBJDIRATTRASN_IDX_OID].data.oid.sum == SDA_COC_OID)) {
            int cuLen;
            word32 setIdx = 0;
            byte* setData;
            word32 setLen;

            GetASN_GetRef(&dataASN[SUBJDIRATTRASN_IDX_SET], &setData, &setLen);
            if (GetASNHeader(setData, ASN_PRINTABLE_STRING, &setIdx, &cuLen,
                    setLen) < 0) {
                ret = ASN_PARSE_E;
            }
            if ((ret == 0) && (cuLen != COUNTRY_CODE_LEN)) {
                ret = ASN_PARSE_E;
            }
            if (ret == 0) {
                XMEMCPY(cert->countryOfCitizenship, setData + setIdx, cuLen);
                cert->countryOfCitizenship[COUNTRY_CODE_LEN] = 0;
            }
        }
    }
    FREE_ASNGETDATA(dataASN, cert->heap);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}
#endif /* WOLFSSL_SUBJ_DIR_ATTR */

#ifdef WOLFSSL_SUBJ_INFO_ACC
/* Decode subject infomation access extension in a certificate.
 *
 * X.509: RFC 5280, 4.2.2.2 - Subject Information Access.
 *
 * @param [in]      input  Buffer holding data.
 * @param [in]      sz     Size of data in buffer.
 * @param [in, out] cert   Certificate object.
 * @return  0 on success.
 * @return  ASN_BITSTR_E when the expected BIT_STRING tag is not found.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  MEMORY_E on dynamic memory allocation failure.
 */
static int DecodeSubjInfoAcc(const byte* input, int sz, DecodedCert* cert)
{
    word32 idx = 0;
    int length = 0;
    int ret = 0;

    WOLFSSL_ENTER("DecodeSubjInfoAcc");

#ifdef OPENSSL_ALL
    cert->extSubjAltNameSrc = input;
    cert->extSubjAltNameSz = sz;
#endif /* OPENSSL_ALL */

    /* Unwrap SubjectInfoAccessSyntax, the list of AccessDescriptions */
    if (GetSequence(input, &idx, &length, sz) < 0)
        return ASN_PARSE_E;

    if (length == 0) {
        /* RFC 5280 4.2.2.2.  Subject Information Access
           If the subjectInformationAccess extension is present, the
           sequence MUST contain at least one entry. */
        WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
        return ASN_PARSE_E;
    }

    /* Per fpkx-x509-cert-profile-common... section 5.3.
     * [The] subjectInfoAccess extension must contain at least one
     * instance of the id-ad-caRepository access method containing a
     * publicly accessible HTTP URI which returns as certs-only
     * CMS.
     */

    while (idx < (word32)sz) {
        word32 oid = 0;
        byte b;

        /* Unwrap an AccessDescription */
        if (GetSequence(input, &idx, &length, sz) < 0)
            return ASN_PARSE_E;

        /* Get the accessMethod */
        if (GetObjectId(input, &idx, &oid, oidCertAuthInfoType, sz) < 0)
            return ASN_PARSE_E;

        /* Only supporting URIs right now. */
        if (GetASNTag(input, &idx, &b, sz) < 0)
            return ASN_PARSE_E;

        if (GetLength(input, &idx, &length, sz) < 0)
            return ASN_PARSE_E;

        /* Set caRepo entry */
        if (b == GENERALNAME_URI && oid == AIA_CA_REPO_OID) {
            cert->extSubjInfoAccCaRepoSz = length;
            cert->extSubjInfoAccCaRepo = input + idx;
            break;
        }
        idx += length;
    }

    if (cert->extSubjInfoAccCaRepo == NULL ||
            cert->extSubjInfoAccCaRepoSz == 0) {
        WOLFSSL_MSG("SubjectInfoAccess missing an URL.");
        ret = ASN_PARSE_E;
    }

    WOLFSSL_LEAVE("DecodeSubjInfoAcc", ret);
    return ret;
}
#endif /* WOLFSSL_SUBJ_INFO_ACC */

/* Macro to check if bit is set, if not sets and return success.
    Otherwise returns failure */
/* Macro required here because bit-field operation */
#ifndef WOLFSSL_NO_ASN_STRICT
    #define VERIFY_AND_SET_OID(bit) \
        if ((bit) == 0) \
            (bit) = 1; \
        else \
            return ASN_OBJECT_ID_E;
#else
    /* With no strict defined, the verify is skipped */
#define VERIFY_AND_SET_OID(bit) bit = 1;
#endif

/* Parse extension type specific data based on OID sum.
 *
 * Supported extensions:
 *   Basic Constraints - BASIC_CA_OID
 *   CRL Distribution Points - CRL_DIST_OID
 *   Authority Information Access - AUTH_INFO_OID
 *   Subject Alternative Name - ALT_NAMES_OID
 *   Authority Key Identifier - AUTH_KEY_OID
 *   Subject Key Identifier - SUBJ_KEY_OID
 *   Certificate Policies - CERT_POLICY_OID (conditional parsing)
 *   Key Usage - KEY_USAGE_OID
 *   Extended Key Usage - EXT_KEY_USAGE_OID
 *   Name Constraints - NAME_CONS_OID
 *   Inhibit anyPolicy - INHIBIT_ANY_OID
 *   Netscape Certificate Type - NETSCAPE_CT_OID (able to be excluded)
 *   OCSP no check - OCSP_NOCHECK_OID (when compiling OCSP)
 *   Subject Directory Attributes - SUBJ_DIR_ATTR_OID
 *   Subject Information Access - SUBJ_INFO_ACC_OID
 * Unsupported extensions from RFC 5280:
 *   4.2.1.5 - Policy mappings
 *   4.2.1.7 - Issuer Alternative Name
 *   4.2.1.11 - Policy Constraints
 *   4.2.1.15 - Freshest CRL
 *
 * @param [in]      input     Buffer containing extension type specific data.
 * @param [in]      length    Length of data.
 * @param [in]      oid       OID sum for extension.
 * @param [in]      critical  Whether extension is critical.
 * @param [in, out] cert      Certificate object.
 * @return  0 on success.
 * @return  ASN_PARSE_E when BER encoding is invalid.
 * @return  MEMORY_E on dynamic memory allocation failure.
 * @return  Other negative values on error.
 */
static int DecodeExtensionType(const byte* input, word32 length, word32 oid,
                               byte critical, DecodedCert* cert,
                               int *isUnknownExt)
{
    int ret = 0;
    word32 idx = 0;

    if (isUnknownExt != NULL)
        *isUnknownExt = 0;

    switch (oid) {
        /* Basic Constraints. */
        case BASIC_CA_OID:
            VERIFY_AND_SET_OID(cert->extBasicConstSet);
            cert->extBasicConstCrit = critical ? 1 : 0;
            if (DecodeBasicCaConstraint(input, (int)length, cert) < 0) {
                ret = ASN_PARSE_E;
            }
            break;

        /* CRL Distribution point. */
        case CRL_DIST_OID:
            VERIFY_AND_SET_OID(cert->extCRLdistSet);
            cert->extCRLdistCrit = critical ? 1 : 0;
            if (DecodeCrlDist(input, length, cert) < 0) {
                ret = ASN_PARSE_E;
            }
            break;

        /* Authority information access. */
        case AUTH_INFO_OID:
            VERIFY_AND_SET_OID(cert->extAuthInfoSet);
            cert->extAuthInfoCrit = critical ? 1 : 0;
            if (DecodeAuthInfo(input, length, cert) < 0) {
                ret = ASN_PARSE_E;
            }
            break;

        /* Subject alternative name. */
        case ALT_NAMES_OID:
            VERIFY_AND_SET_OID(cert->extSubjAltNameSet);
            cert->extSubjAltNameCrit = critical ? 1 : 0;
            ret = DecodeAltNames(input, length, cert);
            break;

        /* Authority Key Identifier. */
        case AUTH_KEY_OID:
            VERIFY_AND_SET_OID(cert->extAuthKeyIdSet);
            cert->extAuthKeyIdCrit = critical ? 1 : 0;
            #ifndef WOLFSSL_ALLOW_CRIT_SKID
                /* This check is added due to RFC 5280 section 4.2.1.1
                 * stating that conforming CA's must mark this extension
                 * as non-critical. When parsing extensions check that
                 * certificate was made in compliance with this. */
                if (critical) {
                    WOLFSSL_MSG("Critical Auth Key ID is not allowed");
                    WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_SKID if wanted");
                    ret = ASN_CRIT_EXT_E;
                }
            #endif
            if ((ret == 0) && (DecodeAuthKeyId(input, length, cert) < 0)) {
                ret = ASN_PARSE_E;
            }
            break;

        /* Subject Key Identifier. */
        case SUBJ_KEY_OID:
            VERIFY_AND_SET_OID(cert->extSubjKeyIdSet);
            cert->extSubjKeyIdCrit = critical ? 1 : 0;
            #ifndef WOLFSSL_ALLOW_CRIT_SKID
                /* This check is added due to RFC 5280 section 4.2.1.2
                 * stating that conforming CA's must mark this extension
                 * as non-critical. When parsing extensions check that
                 * certificate was made in compliance with this. */
                if (critical) {
                    WOLFSSL_MSG("Critical Subject Key ID is not allowed");
                    WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_SKID if wanted");
                    ret = ASN_CRIT_EXT_E;
                }
            #endif

            if ((ret == 0) && (DecodeSubjKeyId(input, length, cert) < 0)) {
                ret = ASN_PARSE_E;
            }
            break;

        /* Certificate policies. */
        case CERT_POLICY_OID:
            #if defined(WOLFSSL_SEP) || defined(WOLFSSL_QT)
                VERIFY_AND_SET_OID(cert->extCertPolicySet);
                #if defined(OPENSSL_EXTRA) || \
                    defined(OPENSSL_EXTRA_X509_SMALL)
                    cert->extCertPolicyCrit = critical ? 1 : 0;
                #endif
            #endif
            #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || \
                defined(WOLFSSL_QT)
                if (DecodeCertPolicy(input, length, cert) < 0) {
                    ret = ASN_PARSE_E;
                }
            #else
                WOLFSSL_MSG("Certificate Policy extension not supported yet.");
            #endif
            break;

        /* Key usage. */
        case KEY_USAGE_OID:
            VERIFY_AND_SET_OID(cert->extKeyUsageSet);
            cert->extKeyUsageCrit = critical ? 1 : 0;
            if (DecodeKeyUsage(input, length, cert) < 0) {
                ret = ASN_PARSE_E;
            }
            break;

        /* Extended key usage. */
        case EXT_KEY_USAGE_OID:
            VERIFY_AND_SET_OID(cert->extExtKeyUsageSet);
            cert->extExtKeyUsageCrit = critical ? 1 : 0;
            if (DecodeExtKeyUsage(input, length, cert) < 0) {
                ret = ASN_PARSE_E;
            }
            break;

        #ifndef IGNORE_NAME_CONSTRAINTS
        /* Name constraints. */
        case NAME_CONS_OID:
        #ifndef WOLFSSL_NO_ASN_STRICT
            /* Verify RFC 5280 Sec 4.2.1.10 rule:
                "The name constraints extension,
                which MUST be used only in a CA certificate" */
            if (!cert->isCA) {
                WOLFSSL_MSG("Name constraints allowed only for CA certs");
                WOLFSSL_ERROR_VERBOSE(ASN_NAME_INVALID_E);
                ret = ASN_NAME_INVALID_E;
            }
        #endif
            VERIFY_AND_SET_OID(cert->extNameConstraintSet);
            cert->extNameConstraintCrit = critical ? 1 : 0;
            if (DecodeNameConstraints(input, length, cert) < 0) {
                ret = ASN_PARSE_E;
            }
            break;
        #endif /* IGNORE_NAME_CONSTRAINTS */

        /* Inhibit anyPolicy. */
        case INHIBIT_ANY_OID:
            VERIFY_AND_SET_OID(cert->inhibitAnyOidSet);
            WOLFSSL_MSG("Inhibit anyPolicy extension not supported yet.");
            break;

   #ifndef IGNORE_NETSCAPE_CERT_TYPE
        /* Netscape's certificate type. */
        case NETSCAPE_CT_OID:
            if (DecodeNsCertType(input, (int)length, cert) < 0)
                ret = ASN_PARSE_E;
            break;
    #endif
    #ifdef HAVE_OCSP
        /* OCSP no check. */
        case OCSP_NOCHECK_OID:
            VERIFY_AND_SET_OID(cert->ocspNoCheckSet);
            ret = GetASNNull(input, &idx, length);
            if (ret != 0) {
                ret = ASN_PARSE_E;
            }
            break;
    #endif
        case POLICY_CONST_OID:
            VERIFY_AND_SET_OID(cert->extPolicyConstSet);
            cert->extPolicyConstCrit = critical ? 1 : 0;
            if (DecodePolicyConstraints(&input[idx], (int)length, cert) < 0)
                return ASN_PARSE_E;
            break;
    #ifdef WOLFSSL_SUBJ_DIR_ATTR
        case SUBJ_DIR_ATTR_OID:
            VERIFY_AND_SET_OID(cert->extSubjDirAttrSet);
            if (DecodeSubjDirAttr(&input[idx], length, cert) < 0)
                return ASN_PARSE_E;
            break;
    #endif
    #ifdef WOLFSSL_SUBJ_INFO_ACC
        case SUBJ_INFO_ACC_OID:
            VERIFY_AND_SET_OID(cert->extSubjInfoAccSet);
            if (DecodeSubjInfoAcc(&input[idx], length, cert) < 0)
                return ASN_PARSE_E;
            break;
    #endif
        default:
            if (isUnknownExt != NULL)
                *isUnknownExt = 1;
        #ifndef WOLFSSL_NO_ASN_STRICT
            /* While it is a failure to not support critical extensions,
             * still parse the certificate ignoring the unsupported
             * extension to allow caller to accept it with the verify
             * callback. */
            if (critical) {
                WOLFSSL_ERROR_VERBOSE(ASN_CRIT_EXT_E);
                ret = ASN_CRIT_EXT_E;
            }
        #endif
            break;
    }

    return ret;
}

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for extensions.
 * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
 */
static const ASNItem certExtHdrASN[] = {
/* EXTTAG */ { 0, ASN_CONTEXT_SPECIFIC | 3, 1, 1, 0 },
/* EXTSEQ */     { 1, ASN_SEQUENCE, 1, 1, 0 },
};
enum {
    CERTEXTHDRASN_IDX_EXTTAG = 0,
    CERTEXTHDRASN_IDX_EXTSEQ
};

/* Number of itesm in ASN.1 template for extensions. */
#define certExtHdrASN_Length (sizeof(certExtHdrASN) / sizeof(ASNItem))

/* ASN.1 template for Extension.
 * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
 */
static const ASNItem certExtASN[] = {
/* SEQ  */ { 0, ASN_SEQUENCE, 1, 1, 0 },
                              /* Extension object id */
/* OID  */     { 1, ASN_OBJECT_ID, 0, 0, 0 },
                              /* critical - when true, must be parseable. */
/* CRIT */     { 1, ASN_BOOLEAN, 0, 0, 1 },
                              /* Data for extension - leave index at start of data. */
/* VAL  */     { 1, ASN_OCTET_STRING, 0, 1, 0 },
};
enum {
    CERTEXTASN_IDX_SEQ = 0,
    CERTEXTASN_IDX_OID,
    CERTEXTASN_IDX_CRIT,
    CERTEXTASN_IDX_VAL
};

/* Number of items in ASN.1 template for Extension. */
#define certExtASN_Length (sizeof(certExtASN) / sizeof(ASNItem))
#endif

#if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_ASN_TEMPLATE) \
    && defined(HAVE_OID_DECODING)
int wc_SetUnknownExtCallback(DecodedCert* cert,
                             wc_UnknownExtCallback cb) {
    if (cert == NULL) {
        return BAD_FUNC_ARG;
    }

    cert->unknownExtCallback = cb;
    return 0;
}
#endif

/*
 *  Processing the Certificate Extensions. This does not modify the current
 *  index. It is works starting with the recorded extensions pointer.
 */
static int DecodeCertExtensions(DecodedCert* cert)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int ret = 0;
    word32 idx = 0;
    word32 sz = (word32)cert->extensionsSz;
    const byte* input = cert->extensions;
    int length;
    word32 oid;
    byte critical = 0;
    byte criticalFail = 0;
    byte tag = 0;

    WOLFSSL_ENTER("DecodeCertExtensions");

    if (input == NULL || sz == 0)
        return BAD_FUNC_ARG;

#ifdef WOLFSSL_CERT_REQ
    if (!cert->isCSR)
#endif
    { /* Not included in CSR */
        if (GetASNTag(input, &idx, &tag, sz) < 0) {
            return ASN_PARSE_E;
        }

        if (tag != ASN_EXTENSIONS) {
            WOLFSSL_MSG("\tfail: should be an EXTENSIONS");
            return ASN_PARSE_E;
        }

        if (GetLength(input, &idx, &length, sz) < 0) {
            WOLFSSL_MSG("\tfail: invalid length");
            return ASN_PARSE_E;
        }
    }

    if (GetSequence(input, &idx, &length, sz) < 0) {
        WOLFSSL_MSG("\tfail: should be a SEQUENCE (1)");
        return ASN_PARSE_E;
    }

    while (idx < (word32)sz) {
        word32 localIdx;

        if (GetSequence(input, &idx, &length, sz) < 0) {
            WOLFSSL_MSG("\tfail: should be a SEQUENCE");
            return ASN_PARSE_E;
        }

        oid = 0;
        if ((ret = GetObjectId(input, &idx, &oid, oidCertExtType, sz)) < 0) {
            WOLFSSL_MSG("\tfail: OBJECT ID");
            return ret;
        }

        /* check for critical flag */
        critical = 0;
        if ((idx + 1) > (word32)sz) {
            WOLFSSL_MSG("\tfail: malformed buffer");
            return BUFFER_E;
        }

        localIdx = idx;
        if (GetASNTag(input, &localIdx, &tag, sz) == 0) {
            if (tag == ASN_BOOLEAN) {
                ret = GetBoolean(input, &idx, sz);
                if (ret < 0) {
                    WOLFSSL_MSG("\tfail: critical boolean");
                    return ret;
                }

                critical = (byte)ret;
            }
        }

        /* process the extension based on the OID */
        ret = GetOctetString(input, &idx, &length, sz);
        if (ret < 0) {
            WOLFSSL_MSG("\tfail: bad OCTET STRING");
            return ret;
        }

        ret = DecodeExtensionType(input + idx, (word32)length, oid, critical,
            cert, NULL);
        if (ret == ASN_CRIT_EXT_E) {
            ret = 0;
            criticalFail = 1;
        }
        if (ret < 0)
            goto end;
        idx += (word32)length;
    }

    ret = criticalFail ? ASN_CRIT_EXT_E : 0;
end:
    return ret;
#else
    DECL_ASNGETDATA(dataASN, certExtASN_Length);
    ASNGetData dataExtsASN[certExtHdrASN_Length];
    int ret = 0;
    const byte* input = cert->extensions;
    int sz = cert->extensionsSz;
    word32 idx = 0;
    int criticalRet = 0;
    int offset = 0;

    WOLFSSL_ENTER("DecodeCertExtensions");

    if (input == NULL || sz == 0)
        ret = BAD_FUNC_ARG;

    ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, cert->heap);

#ifdef WOLFSSL_CERT_REQ
    if (cert->isCSR) {
        offset = CERTEXTHDRASN_IDX_EXTSEQ;
    }
#endif
    if (ret == 0) {
        /* Clear dynamic data. */
        XMEMSET(dataExtsASN, 0, sizeof(dataExtsASN));
        /* Parse extensions header. */
        ret = GetASN_Items(certExtHdrASN + offset, dataExtsASN + offset,
                           (int)(certExtHdrASN_Length - (size_t)offset), 0,
                           input, &idx, (word32)sz);
    }
    /* Parse each extension. */
    while ((ret == 0) && (idx < (word32)sz)) {
        byte critical = 0;
        int isUnknownExt = 0;

        /* Clear dynamic data. */
        XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
        /* Ensure OID is an extention type. */
        GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
        /* Set criticality variable. */
        GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
        /* Parse extension wrapper. */
        ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, input,
                           &idx, (word32)sz);
        if (ret == 0) {
            word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
            word32 length = dataASN[CERTEXTASN_IDX_VAL].length;

            /* Decode the extension by type. */
            ret = DecodeExtensionType(input + idx, length, oid, critical, cert,
                                      &isUnknownExt);
#if defined(WOLFSSL_CUSTOM_OID) && defined(HAVE_OID_DECODING)
            if (isUnknownExt && (cert->unknownExtCallback != NULL)) {
                word16 decOid[MAX_OID_SZ];
                word32 decOidSz = sizeof(decOid);
                ret = DecodeObjectId(
                          dataASN[CERTEXTASN_IDX_OID].data.oid.data,
                          dataASN[CERTEXTASN_IDX_OID].data.oid.length,
                          decOid, &decOidSz);
                if (ret != 0) {
                    /* Should never get here as the extension was successfully
                     * decoded earlier. Something might be corrupted. */
                    WOLFSSL_MSG("DecodeObjectId() failed. Corruption?");
                    WOLFSSL_ERROR(ret);
                }

                ret = cert->unknownExtCallback(decOid, decOidSz, critical,
                          dataASN[CERTEXTASN_IDX_VAL].data.buffer.data,
                          dataASN[CERTEXTASN_IDX_VAL].length);
            }
#endif
            (void)isUnknownExt;

            /* Move index on to next extension. */
            idx += length;
        }
        /* Don't fail criticality until all other extensions have been checked.
         */
        if (ret == ASN_CRIT_EXT_E) {
            criticalRet = ASN_CRIT_EXT_E;
            ret = 0;
        }
    }

    if (ret == 0) {
        /* Use criticality return. */
        ret = criticalRet;
    }

    FREE_ASNGETDATA(dataASN, cert->heap);
    return ret;
#endif
}

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN template for an X509 certificate.
 * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
 */
static const ASNItem x509CertASN[] = {
        /* Certificate ::= SEQUENCE */
/* SEQ                           */    { 0, ASN_SEQUENCE, 1, 1, 0 },
                                                   /* tbsCertificate       TBSCertificate */
                                                   /* TBSCertificate ::= SEQUENCE */
/* TBS_SEQ                       */        { 1, ASN_SEQUENCE, 1, 1, 0 },
                                                   /* version         [0]  EXPLICT Version DEFAULT v1 */
/* TBS_VER                       */            { 2, ASN_CONTEXT_SPECIFIC | ASN_X509_CERT_VERSION, 1, 1, 1 },
                                                   /* Version ::= INTEGER { v1(0), v2(1), v3(2) */
/* TBS_VER_INT                   */                { 3, ASN_INTEGER, 0, 0, 0 },
                                                   /* serialNumber         CertificateSerialNumber */
                                                   /* CetificateSerialNumber ::= INTEGER */
/* TBS_SERIAL                    */            { 2, ASN_INTEGER, 0, 0, 0 },
                                                   /* signature            AlgorithmIdentifier */
                                                   /* AlgorithmIdentifier ::= SEQUENCE */
/* TBS_ALGOID_SEQ                */            { 2, ASN_SEQUENCE, 1, 1, 0 },
                                                   /* Algorithm    OBJECT IDENTIFIER */
/* TBS_ALGOID_OID                */                { 3, ASN_OBJECT_ID, 0, 0, 0 },
                                                   /* parameters   ANY defined by algorithm OPTIONAL */
/* TBS_ALGOID_PARAMS_NULL        */                { 3, ASN_TAG_NULL, 0, 0, 2 },
#ifdef WC_RSA_PSS
/* TBS_ALGOID_PARAMS             */                { 3, ASN_SEQUENCE, 1, 0, 2 },
#endif
                                                   /* issuer               Name */
/* TBS_ISSUER_SEQ                */            { 2, ASN_SEQUENCE, 1, 0, 0 },
                                                   /* validity             Validity */
                                                   /* Validity ::= SEQUENCE */
/* TBS_VALIDITY_SEQ              */            { 2, ASN_SEQUENCE, 1, 1, 0 },
                                                   /* notBefore   Time */
                                                   /* Time :: CHOICE { UTCTime, GeneralizedTime } */
/* TBS_VALIDITY_NOTB_UTC         */                { 3, ASN_UTC_TIME, 0, 0, 2 },
/* TBS_VALIDITY_NOTB_GT          */                { 3, ASN_GENERALIZED_TIME, 0, 0, 2 },
                                                   /* notAfter   Time */
                                                   /* Time :: CHOICE { UTCTime, GeneralizedTime } */
/* TBS_VALIDITY_NOTA_UTC         */                { 3, ASN_UTC_TIME, 0, 0, 3 },
/* TBS_VALIDITY_NOTA_GT          */                { 3, ASN_GENERALIZED_TIME, 0, 0, 3 },
                                                   /* subject              Name */
/* TBS_SUBJECT_SEQ               */            { 2, ASN_SEQUENCE, 1, 0, 0 },
                                                   /* subjectPublicKeyInfo SubjectPublicKeyInfo */
/* TBS_SPUBKEYINFO_SEQ           */            { 2, ASN_SEQUENCE, 1, 1, 0 },
                                                   /* algorithm          AlgorithmIdentifier */
                                                   /* AlgorithmIdentifier ::= SEQUENCE */
/* TBS_SPUBKEYINFO_ALGO_SEQ      */                { 3, ASN_SEQUENCE, 1, 1, 0 },
                                                   /* Algorithm    OBJECT IDENTIFIER */
/* TBS_SPUBKEYINFO_ALGO_OID      */                    { 4, ASN_OBJECT_ID, 0, 0, 0 },
                                                   /* parameters   ANY defined by algorithm OPTIONAL */
/* TBS_SPUBKEYINFO_ALGO_NULL     */                    { 4, ASN_TAG_NULL, 0, 0, 2 },
/* TBS_SPUBKEYINFO_ALGO_CURVEID  */                    { 4, ASN_OBJECT_ID, 0, 0, 2 },
#ifdef WC_RSA_PSS
/* TBS_SPUBKEYINFO_ALGO_P_SEQ    */                    { 4, ASN_SEQUENCE, 1, 0, 2 },
#endif
                                                   /* subjectPublicKey   BIT STRING */
/* TBS_SPUBKEYINFO_PUBKEY        */                { 3, ASN_BIT_STRING, 0, 0, 0 },
                                                   /* issuerUniqueID       UniqueIdentfier OPTIONAL */
/* TBS_ISSUERUID                 */            { 2, ASN_CONTEXT_SPECIFIC | 1, 0, 0, 1 },
                                                   /* subjectUniqueID      UniqueIdentfier OPTIONAL */
/* TBS_SUBJECTUID                */            { 2, ASN_CONTEXT_SPECIFIC | 2, 0, 0, 1 },
                                                   /* extensions           Extensions OPTIONAL */
/* TBS_EXT                       */            { 2, ASN_CONTEXT_SPECIFIC | 3, 1, 1, 1 },
/* TBS_EXT_SEQ                   */                { 3, ASN_SEQUENCE, 1, 0, 0 },
                                                   /* signatureAlgorithm   AlgorithmIdentifier */
                                                   /* AlgorithmIdentifier ::= SEQUENCE */
/* SIGALGO_SEQ                   */        { 1, ASN_SEQUENCE, 1, 1, 0 },
                                                   /* Algorithm    OBJECT IDENTIFIER */
/* SIGALGO_OID                   */            { 2, ASN_OBJECT_ID, 0, 0, 0 },
                                                   /* parameters   ANY defined by algorithm OPTIONAL */
/* SIGALGO_PARAMS_NULL           */            { 2, ASN_TAG_NULL, 0, 0, 2 },
#ifdef WC_RSA_PSS
/* SIGALGO_PARAMS                */            { 2, ASN_SEQUENCE, 1, 0, 2 },
#endif
                                                   /* signature            BIT STRING */
/* SIGNATURE                     */        { 1, ASN_BIT_STRING, 0, 0, 0 },
};
enum {
    X509CERTASN_IDX_SEQ = 0,
    X509CERTASN_IDX_TBS_SEQ,
    X509CERTASN_IDX_TBS_VER,
    X509CERTASN_IDX_TBS_VER_INT,
    X509CERTASN_IDX_TBS_SERIAL,
    X509CERTASN_IDX_TBS_ALGOID_SEQ,
    X509CERTASN_IDX_TBS_ALGOID_OID,
    X509CERTASN_IDX_TBS_ALGOID_PARAMS_NULL,
#ifdef WC_RSA_PSS
    X509CERTASN_IDX_TBS_ALGOID_PARAMS,
#endif
    X509CERTASN_IDX_TBS_ISSUER_SEQ,
    X509CERTASN_IDX_TBS_VALIDITY_SEQ,
    X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC,
    X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT,
    X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC,
    X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT,
    X509CERTASN_IDX_TBS_SUBJECT_SEQ,
    X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ,
    X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_SEQ,
    X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID,
    X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_NULL,
    X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID,
#ifdef WC_RSA_PSS
    X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_P_SEQ,
#endif
    X509CERTASN_IDX_TBS_SPUBKEYINFO_PUBKEY,
    X509CERTASN_IDX_TBS_ISSUERUID,
    X509CERTASN_IDX_TBS_SUBJECTUID,
    X509CERTASN_IDX_TBS_EXT,
    X509CERTASN_IDX_TBS_EXT_SEQ,
    X509CERTASN_IDX_SIGALGO_SEQ,
    X509CERTASN_IDX_SIGALGO_OID,
    X509CERTASN_IDX_SIGALGO_PARAMS_NULL,
#ifdef WC_RSA_PSS
    X509CERTASN_IDX_SIGALGO_PARAMS,
#endif
    X509CERTASN_IDX_SIGNATURE,
    WOLF_ENUM_DUMMY_LAST_ELEMENT(X509CERTASN_IDX)
};

/* Number of items in ASN template for an X509 certificate. */
#define x509CertASN_Length (sizeof(x509CertASN) / sizeof(ASNItem))

/* Check the data data.
 *
 * @param [in] dataASN   ASN template dynamic data item.
 * @param [in] dataType  BEFORE or AFTER date.
 * @return  0 on success.
 * @return  ASN_TIME_E when BER tag is nor UTC or GENERALIZED time.
 * @return  ASN_DATE_SZ_E when time data is not supported.
 * @return  ASN_BEFORE_DATE_E when BEFORE date is invalid.
 * @return  ASN_AFTER_DATE_E when AFTER date is invalid.
 */
static int CheckDate(ASNGetData *dataASN, int dateType)
{
    int ret = 0;

    /* Check BER tag is valid. */
    if ((dataASN->tag != ASN_UTC_TIME) &&
            (dataASN->tag != ASN_GENERALIZED_TIME)) {
        ret = ASN_TIME_E;
    }
    /* Check date length is valid. */
    if ((ret == 0) && ((dataASN->length > MAX_DATE_SIZE) ||
                       (dataASN->length < MIN_DATE_SIZE))) {
        ret = ASN_DATE_SZ_E;
    }

#ifndef NO_ASN_TIME_CHECK
    /* Check date is a valid string and BEFORE or AFTER now. */
    if ((ret == 0) &&
            (!XVALIDATE_DATE(dataASN->data.ref.data, dataASN->tag, dateType))) {
        if (dateType == BEFORE) {
            ret = ASN_BEFORE_DATE_E;
        }
        else {
            ret = ASN_AFTER_DATE_E;
        }
    }
#endif
    (void)dateType;

    return ret;
}

/* Decode a certificate. Internal/non-public API.
 *
 * @param [in]  cert             Certificate object.
 * @param [in]  verify           Whether to verify dates before and after now.
 * @param [out] criticalExt      Critical extension return code.
 * @param [out] badDateRet       Bad date return code.
 * @param [in]  stopAtPubKey     Stop parsing before subkectPublicKeyInfo.
 * @param [in]  stopAfterPubKey  Stop parsing after subkectPublicKeyInfo.
 * @return  0 on success.
 * @return  ASN_CRIT_EXT_E when a critical extension was not recognized.
 * @return  ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
 * @return  ASN_DATE_SZ_E when time data is not supported.
 * @return  ASN_BEFORE_DATE_E when BEFORE date is invalid.
 * @return  ASN_AFTER_DATE_E when AFTER date is invalid.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
 * @return  ASN_BITSTR_E when the expected BIT_STRING tag is not found.
 * @return  ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
 *          non-zero length.
 * @return  ASN_UNKNOWN_OID_E when the OID cannot be verified.
 */
static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt,
                              int* badDateRet, int stopAtPubKey,
                              int stopAfterPubKey)
{
    DECL_ASNGETDATA(dataASN, x509CertASN_Length);
    int ret = 0;
    int badDate = 0;
    byte version;
    word32 idx;
    word32 serialSz;
    const unsigned char* issuer = NULL;
    word32 issuerSz = 0;
    const unsigned char* subject = NULL;
    word32 subjectSz = 0;
    word32 pubKeyOffset = 0;
    word32 pubKeyEnd = 0;
    int done = 0;

    CALLOC_ASNGETDATA(dataASN, x509CertASN_Length, ret, cert->heap);

    if (ret == 0) {
        version = 0;
        serialSz = EXTERNAL_SERIAL_SIZE;

        /* Get the version and put the serial number into the buffer. */
        GetASN_Int8Bit(&dataASN[X509CERTASN_IDX_TBS_VER_INT], &version);
        GetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SERIAL], cert->serial,
                &serialSz);
        /* Check OID types for signature, algorithm, ECC curve and sigAlg. */
        GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID], oidSigType);
        GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID],
                oidKeyType);
        GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID],
                oidCurveType);
        GetASN_OID(&dataASN[X509CERTASN_IDX_SIGALGO_OID], oidSigType);
        /* Parse the X509 certificate. */
        ret = GetASN_Items(x509CertASN, dataASN, x509CertASN_Length, 1,
                           cert->source, &cert->srcIdx, cert->maxIdx);
#ifdef WOLFSSL_CLANG_TIDY
        /* work around clang-tidy false positive re cert->source. */
        if ((ret == 0) && (cert->source == NULL)) {
            ret = ASN_PARSE_E;
        }
#endif
    }
    /* Check version is valid/supported - can't be negative. */
    if ((ret == 0) && (version > MAX_X509_VERSION)) {
        WOLFSSL_MSG("Unexpected certificate version");
        WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
        ret = ASN_PARSE_E;
    }
    if (ret == 0) {
        int i;

        pubKeyOffset = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset;
        /* Set fields extracted from data. */
        cert->version = version;
        cert->serialSz = (int)serialSz;
        cert->signatureOID = dataASN[X509CERTASN_IDX_TBS_ALGOID_OID].data.oid.sum;
        cert->keyOID = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID].data.oid.sum;
        cert->certBegin = dataASN[X509CERTASN_IDX_TBS_SEQ].offset;

        /* No bad date error - don't always care. */
        badDate = 0;
        /* Find the item with the BEFORE date and check it. */
        i = (dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].tag != 0)
                ? X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC
                : X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT;
        if ((CheckDate(&dataASN[i], BEFORE) < 0) && verify) {
            badDate = ASN_BEFORE_DATE_E;
        }
        /* Store reference to BEFOREdate. */
        cert->beforeDate = GetASNItem_Addr(dataASN[i], cert->source);
        cert->beforeDateLen = (int)GetASNItem_Length(dataASN[i], cert->source);

        /* Find the item with the AFTER date and check it. */
        i = (dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].tag != 0)
                ? X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC
                : X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT;
        if ((CheckDate(&dataASN[i], AFTER) < 0) && verify) {
            badDate = ASN_AFTER_DATE_E;
        }
        /* Store reference to AFTER date. */
        cert->afterDate = GetASNItem_Addr(dataASN[i], cert->source);
        cert->afterDateLen = (int)GetASNItem_Length(dataASN[i], cert->source);

        /* Get the issuer name. */
        issuer = cert->source + dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].offset;
        issuerSz = dataASN[X509CERTASN_IDX_TBS_VALIDITY_SEQ].offset -
            dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].offset;

        /* Get the subject name. */
        subject = cert->source +
            dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].offset;
        subjectSz = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset -
            dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].offset;
    }
    if ((ret == 0) && stopAtPubKey) {
        /* Return any bad date error through badDateRet and return offset of
         * subjectPublicKeyInfo.
         */
        if (badDateRet != NULL) {
            *badDateRet = badDate;
        }
        done = 1;
    }

    if ((ret == 0) && (!done)) {
        /* Store the signature information. */
        cert->sigIndex = dataASN[X509CERTASN_IDX_SIGALGO_SEQ].offset;
        GetASN_GetConstRef(&dataASN[X509CERTASN_IDX_SIGNATURE],
                &cert->signature, &cert->sigLength);
        /* Make sure 'signature' and 'signatureAlgorithm' are the same. */
        if (dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum
                != cert->signatureOID) {
            WOLFSSL_ERROR_VERBOSE(ASN_SIG_OID_E);
            ret = ASN_SIG_OID_E;
        }
        /* Parameters not allowed after ECDSA or EdDSA algorithm OID. */
        else if (IsSigAlgoECC(cert->signatureOID)) {
            if ((dataASN[X509CERTASN_IDX_SIGALGO_PARAMS_NULL].tag != 0)
        #ifdef WC_RSA_PSS
                || (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0)
        #endif
                ) {
                WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
                ret = ASN_PARSE_E;
            }
        }
        #ifdef WC_RSA_PSS
        /* Check parameters starting with a SEQUENCE. */
        else if (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0) {
            word32 oid = dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum;
            word32 sigAlgParamsSz = 0;

            /* Parameters only with RSA PSS. */
            if (oid != CTC_RSASSAPSS) {
                WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
                ret = ASN_PARSE_E;
            }
            if (ret == 0) {
                const byte* tbsParams;
                word32 tbsParamsSz;
                const byte* sigAlgParams;

                /* Check RSA PSS parameters are the same. */
                tbsParams =
                    GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
                        cert->source);
                tbsParamsSz =
                    GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
                        cert->source);
                sigAlgParams =
                    GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
                        cert->source);
                sigAlgParamsSz =
                    GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
                        cert->source);
                if ((tbsParamsSz != sigAlgParamsSz) ||
                        (XMEMCMP(tbsParams, sigAlgParams, tbsParamsSz) != 0)) {
                    WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
                    ret = ASN_PARSE_E;
                }
            }
            if (ret == 0) {
                /* Store parameters for use in signature verification. */
                cert->sigParamsIndex =
                    dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].offset;
                cert->sigParamsLength = sigAlgParamsSz;
            }
        }
        #endif
    }
    if ((ret == 0) && (!done)) {
        pubKeyEnd = dataASN[X509CERTASN_IDX_TBS_ISSUERUID].offset;
        if (stopAfterPubKey) {
            /* Return any bad date error through badDateRed and return offset
             * after subjectPublicKeyInfo.
             */
            if (badDateRet != NULL) {
                *badDateRet = badDate;
            }
            done = 1;
        }
    }
    if ((ret == 0) && (!done) &&
            (dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.data != NULL)) {
    #ifndef ALLOW_V1_EXTENSIONS
        /* Certificate extensions were only defined in version 2. */
        if (cert->version < 2) {
            WOLFSSL_MSG("\tv1 and v2 certs not allowed extensions");
            WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
            ret = ASN_VERSION_E;
        }
    #endif
        if (ret == 0) {
            /* Save references to extension data. */
            cert->extensions    = GetASNItem_Addr(
                    dataASN[X509CERTASN_IDX_TBS_EXT], cert->source);
            cert->extensionsSz  = (int)GetASNItem_Length(
                    dataASN[X509CERTASN_IDX_TBS_EXT], cert->source);
            cert->extensionsIdx = dataASN[X509CERTASN_IDX_TBS_EXT].offset;
            /* Advance past extensions. */
            cert->srcIdx = dataASN[X509CERTASN_IDX_SIGALGO_SEQ].offset;
        }
    }

    /* Dispose of memory before allocating for extension decoding. */
    FREE_ASNGETDATA(dataASN, cert->heap);

    if ((ret == 0) && (issuer != NULL)) {
        idx = 0;
        /* Put issuer into cert and calculate hash. */
        ret = GetCertName(cert, cert->issuer, cert->issuerHash, ISSUER, issuer,
            &idx, issuerSz);
    }
    if ((ret == 0) && (subject != NULL)) {
        idx = 0;
        /* Put subject into cert and calculate hash. */
        ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT,
            subject, &idx, subjectSz);
    }
    if (ret == 0) {
        /* Determine if self signed by comparing issuer and subject hashes. */
    #ifdef WOLFSSL_CERT_REQ
        if (cert->isCSR) {
            cert->selfSigned = 1;
        }
        else
    #endif
        {
            cert->selfSigned = (XMEMCMP(cert->issuerHash, cert->subjectHash,
                                        KEYID_SIZE) == 0);
        }
        if (stopAtPubKey) {
            ret = (int)pubKeyOffset;
        }
    }

    if ((ret == 0) && (!stopAtPubKey)) {
        /* Parse the public key. */
        idx = pubKeyOffset;
        ret = GetCertKey(cert, cert->source, &idx, pubKeyEnd);
    }
    if ((ret == 0) && (!stopAtPubKey) && (!stopAfterPubKey) &&
            (cert->extensions != NULL)) {
        /* Decode the extension data starting at [3]. */
        ret = DecodeCertExtensions(cert);
        if (criticalExt != NULL) {
            if (ret == ASN_CRIT_EXT_E) {
                /* Return critical extension not recognized. */
                *criticalExt = ret;
                ret = 0;
            }
            else {
                /* No critical extension error. */
                *criticalExt = 0;
            }
        }
    }

    if ((ret == 0) && (!done) && (badDate != 0)) {
        /* Parsed whole certificate fine but return any date errors. */
        ret = badDate;
    }

    return ret;
}

/* Decode BER/DER data into certificate object.
 *
 * BER/DER data information held in source, srcIdx and maxIdx fields of
 * certificate object.
 *
 * @param [in] cert         Decoded certificate object.
 * @param [in] verify       Whether to find CA and verify certificate.
 * @param [in] criticalExt  Any error for critical extensions not recognized.
 * @return  0 on success.
 * @return  ASN_CRIT_EXT_E when a critical extension was not recognized.
 * @return  ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
 * @return  ASN_DATE_SZ_E when time data is not supported.
 * @return  ASN_BEFORE_DATE_E when BEFORE date is invalid.
 * @return  ASN_AFTER_DATE_E when AFTER date is invalid.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
 * @return  ASN_BITSTR_E when the expected BIT_STRING tag is not found.
 * @return  ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
 *          non-zero length.
 * @return  ASN_UNKNOWN_OID_E when the OID cannot be verified.
 */
int DecodeCert(DecodedCert* cert, int verify, int* criticalExt)
{
    return DecodeCertInternal(cert, verify, criticalExt, NULL, 0, 0);
}

#ifdef WOLFSSL_CERT_REQ
/* ASN.1 template for certificate request Attribute.
 * PKCS #10: RFC 2986, 4.1 - CertificationRequestInfo
 */
static const ASNItem reqAttrASN[] = {
/* SEQ  */ { 0, ASN_SEQUENCE, 1, 1, 0 },
                              /* type */
/* TYPE */     { 1, ASN_OBJECT_ID, 0, 0, 0 },
                              /* values */
/* VALS */     { 1, ASN_SET, 1, 0, 0 },
};
enum {
    REQATTRASN_IDX_SEQ = 0,
    REQATTRASN_IDX_TYPE,
    REQATTRASN_IDX_VALS
};

/* Number of items in ASN.1 template for certificate request Attribute. */
#define reqAttrASN_Length (sizeof(reqAttrASN) / sizeof(ASNItem))

/* ASN.1 template for a string choice. */
static const ASNItem strAttrASN[] = {
    { 0, 0, 0, 0, 0 },
};
enum {
    STRATTRASN_IDX_STR = 0
};

/* Number of items in ASN.1 template for a string choice. */
#define strAttrASN_Length (sizeof(strAttrASN) / sizeof(ASNItem))

/* ASN.1 choices for types for a string in an attribute. */
static const byte strAttrChoice[] = {
    ASN_PRINTABLE_STRING, ASN_IA5_STRING, ASN_UTF8STRING, 0
};

/* Decode a certificate request attribute's value.
 *
 * @param [in]  cert         Certificate request object.
 * @param [out] criticalExt  Critical extension return code.
 * @param [in]  oid          OID decribing which attribute was found.
 * @param [in]  aIdx         Index into certificate source to start parsing.
 * @param [in]  input        Attribute value data.
 * @param [in]  maxIdx       Maximum index to parse to.
 * @return  0 on success.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 */
static int DecodeCertReqAttrValue(DecodedCert* cert, int* criticalExt,
    word32 oid, word32 aIdx, const byte* input, word32 maxIdx)
{
    int ret = 0;
    word32 idx = 0;
    ASNGetData strDataASN[strAttrASN_Length];

    switch (oid) {
        case PKCS9_CONTENT_TYPE_OID:
            /* Clear dynamic data and specify choices acceptable. */
            XMEMSET(strDataASN, 0, sizeof(strDataASN));
            GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
            /* Parse a string. */
            ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
                               1, input, &idx, maxIdx);
            if (ret == 0) {
                /* Store references to password data. */
                cert->contentType =
                        (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
                cert->contentTypeLen =
                        (int)strDataASN[STRATTRASN_IDX_STR].data.ref.length;
            }
            break;

        /* A password by which the entity may request certificate revocation.
         * PKCS#9: RFC 2985, 5.4.1 - Challenge password
         */
        case CHALLENGE_PASSWORD_OID:
            /* Clear dynamic data and specify choices acceptable. */
            XMEMSET(strDataASN, 0, sizeof(strDataASN));
            GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
            /* Parse a string. */
            ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
                               1, input, &idx, maxIdx);
            if (ret == 0) {
                /* Store references to password data. */
                cert->cPwd =
                        (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
                cert->cPwdLen = (int)strDataASN[STRATTRASN_IDX_STR].
                    data.ref.length;
            }
            break;

        /* Requested serial number to issue with.
         * PKCS#9: RFC 2985, 5.2.10 - Serial Number
         * (References: ISO/IEC 9594-6:1997)
         */
        case SERIAL_NUMBER_OID:
            /* Clear dynamic data and specify choices acceptable. */
            XMEMSET(strDataASN, 0, sizeof(strDataASN));
            GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
            /* Parse a string. */
            ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
                               1, input, &idx, maxIdx);
            if (ret == 0) {
                /* Store references to serial number. */
                cert->sNum =
                        (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
                cert->sNumLen = (int)strDataASN[STRATTRASN_IDX_STR].
                    data.ref.length;
                /* Store serial number if small enough. */
                if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) {
                    XMEMCPY(cert->serial, cert->sNum, (size_t)cert->sNumLen);
                    cert->serialSz = cert->sNumLen;
                }
            }
            break;

        /* Certificate extensions to be included in generated certificate.
         * PKCS#9: RFC 2985, 5.4.2 - Extension request
         */
        case EXTENSION_REQUEST_OID:
            /* Store references to all extensions. */
            cert->extensions    = input;
            cert->extensionsSz  = (int)maxIdx;
            cert->extensionsIdx = aIdx;

            /* Decode and validate extensions. */
            ret = DecodeCertExtensions(cert);
            if (ret == ASN_CRIT_EXT_E) {
                /* Return critical extension not recognized. */
                *criticalExt = ret;
                ret = 0;
            }
            else {
                /* No critical extension error. */
                *criticalExt = 0;
            }
            break;

        default:
            ret = ASN_PARSE_E;
            break;
    }

    return ret;
}

/* Decode attributes of a BER encoded certificate request.
 *
 * RFC 2986 - PKCS #10: Certification Request Syntax Specification Version 1.7
 *
 * Outer sequence has been removed.
 *
 * @param [in]  cert         Certificate request object.
 * @param [out] criticalExt  Critical extension return code.
 * @param [in]  idx          Index into certificate source to start parsing.
 * @param [in]  maxIdx       Maximum index to parse to.
 * @return  0 on success.
 * @return  ASN_CRIT_EXT_E when a critical extension was not recognized.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
 * @return  ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
 *          non-zero length.
 * @return  ASN_UNKNOWN_OID_E when the OID cannot be verified.
 */
static int DecodeCertReqAttributes(DecodedCert* cert, int* criticalExt,
                                   word32 idx, word32 maxIdx)
{
    DECL_ASNGETDATA(dataASN, reqAttrASN_Length);
    int ret = 0;

    WOLFSSL_ENTER("DecodeCertReqAttributes");

    ALLOC_ASNGETDATA(dataASN, reqAttrASN_Length, ret, cert->heap);

    /* Parse each attribute until all data used up. */
    while ((ret == 0) && (idx < maxIdx)) {
        /* Clear dynamic data. */
        XMEMSET(dataASN, 0, sizeof(ASNGetData) * reqAttrASN_Length);
        GetASN_OID(&dataASN[REQATTRASN_IDX_TYPE], oidIgnoreType);

        /* Parse an attribute. */
        ret = GetASN_Items(reqAttrASN, dataASN, reqAttrASN_Length, 0,
                           cert->source, &idx, maxIdx);
        /* idx is now at end of attribute data. */
        if (ret == 0) {
            ret = DecodeCertReqAttrValue(cert, criticalExt,
                dataASN[REQATTRASN_IDX_TYPE].data.oid.sum,
                GetASNItem_DataIdx(dataASN[REQATTRASN_IDX_VALS], cert->source),
                dataASN[REQATTRASN_IDX_VALS].data.ref.data,
                dataASN[REQATTRASN_IDX_VALS].data.ref.length);
        }
    }

    FREE_ASNGETDATA(dataASN, cert->heap);
    return ret;
}

/* ASN.1 template for a certificate request.
 * PKCS#10: RFC 2986, 4.1 - CertificationRequestInfo
 * PKCS#10: RFC 2986, 4.2 - CertificationRequest
 */
static const ASNItem certReqASN[] = {
            /* CertificationRequest */
/* SEQ                              */ { 0, ASN_SEQUENCE, 1, 1, 0 },
                                                          /* CertificationRequestInfo */
/* INFO_SEQ                         */     { 1, ASN_SEQUENCE, 1, 1, 0 },
                                                              /* version              INTEGER { v1(0), v2(1), v3(2) */
/* INFO_VER                         */         { 2, ASN_INTEGER, 0, 0, 0 },
                                                              /* subject              Name */
/* INFO_SUBJ_SEQ                    */         { 2, ASN_SEQUENCE, 1, 0, 0 },
                                                              /* subjectPublicKeyInfo SubjectPublicKeyInfo */
/* INFO_SPUBKEYINFO_SEQ             */         { 2, ASN_SEQUENCE, 1, 1, 0 },
                                                                  /* algorithm          AlgorithmIdentifier */
/* INFO_SPUBKEYINFO_ALGOID_SEQ      */             { 3, ASN_SEQUENCE, 1, 1, 0 },
                                                                      /* Algorithm    OBJECT IDENTIFIER */
/* INFO_SPUBKEYINFO_ALGOID_OID      */                 { 4, ASN_OBJECT_ID, 0, 0, 0 },
                                                                      /* parameters   ANY defined by algorithm OPTIONAL */
/* INFO_SPUBKEYINFO_ALGOID_NULL     */                 { 4, ASN_TAG_NULL, 0, 0, 1 },
/* INFO_SPUBKEYINFO_ALGOID_CURVEID  */                 { 4, ASN_OBJECT_ID, 0, 0, 1 },
/* INFO_SPUBKEYINFO_ALGOID_PARAMS   */                 { 4, ASN_SEQUENCE, 1, 0, 1 },
                                                                  /* subjectPublicKey   BIT STRING */
/* INFO_SPUBKEYINFO_PUBKEY          */             { 3, ASN_BIT_STRING, 0, 0, 0 },
                                                              /* attributes       [0] Attributes */
/* INFO_ATTRS                       */         { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 1 },
                                                          /* signatureAlgorithm   AlgorithmIdentifier */
/* INFO_SIGALGO_SEQ                 */     { 1, ASN_SEQUENCE, 1, 1, 0 },
                                                              /* Algorithm    OBJECT IDENTIFIER */
/* INFO_SIGALGO_OID                 */         { 2, ASN_OBJECT_ID, 0, 0, 0 },
                                                              /* parameters   ANY defined by algorithm OPTIONAL */
/* INFO_SIGALGO_NULL                */         { 2, ASN_TAG_NULL, 0, 0, 1 },
                                                          /* signature            BIT STRING */
/* INFO_SIGNATURE                   */     { 1, ASN_BIT_STRING, 0, 0, 0 },
};
enum {
    CERTREQASN_IDX_SEQ = 0,
    CERTREQASN_IDX_INFO_SEQ,
    CERTREQASN_IDX_INFO_VER,
    CERTREQASN_IDX_INFO_SUBJ_SEQ,
    CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ,
    CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_SEQ,
    CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID,
    CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_NULL,
    CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID,
    CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_PARAMS,
    CERTREQASN_IDX_INFO_SPUBKEYINFO_PUBKEY,
    CERTREQASN_IDX_INFO_ATTRS,
    CERTREQASN_IDX_INFO_SIGALGO_SEQ,
    CERTREQASN_IDX_INFO_SIGALGO_OID,
    CERTREQASN_IDX_INFO_SIGALGO_NULL,
    CERTREQASN_IDX_INFO_SIGNATURE
};

/* Number of items in ASN.1 template for a certificate request. */
#define certReqASN_Length (sizeof(certReqASN) / sizeof(ASNItem))

/* Parse BER encoded certificate request.
 *
 * RFC 2986 - PKCS #10: Certification Request Syntax Specification Version 1.7
 *
 * @param [in]  cert         Certificate request object.
 * @param [out] criticalExt  Critical extension return code.
 * @return  0 on success.
 * @return  ASN_CRIT_EXT_E when a critical extension was not recognized.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  BUFFER_E when data in buffer is too small.
 * @return  ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
 * @return  ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
 *          non-zero length.
 * @return  ASN_UNKNOWN_OID_E when the OID cannot be verified.
 * @return  MEMORY_E on dynamic memory allocation failure.
 */
static int DecodeCertReq(DecodedCert* cert, int* criticalExt)
{
    DECL_ASNGETDATA(dataASN, certReqASN_Length);
    int ret = 0;
    byte version;
    word32 idx;

    CALLOC_ASNGETDATA(dataASN, certReqASN_Length, ret, cert->heap);

    if (ret == 0) {
        /* Default version is 0. */
        version = 0;

        /* Set version var and OID types to expect. */
        GetASN_Int8Bit(&dataASN[CERTREQASN_IDX_INFO_VER], &version);
        GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID],
                oidKeyType);
        GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID],
                oidCurveType);
        GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID], oidSigType);
        /* Parse a certificate request. */
        ret = GetASN_Items(certReqASN, dataASN, certReqASN_Length, 1,
                           cert->source, &cert->srcIdx, cert->maxIdx);
    }
    /* Check version is valid/supported - can't be negative. */
    if ((ret == 0) && (version > MAX_X509_VERSION)) {
        WOLFSSL_MSG("Unexpected certificate request version");
        ret = ASN_PARSE_E;
    }
    if (ret == 0) {
        /* Set fields of certificate request. */
        cert->version = version;
        cert->signatureOID =
              dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID].data.oid.sum;
        cert->keyOID =
              dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID].data.oid.sum;
        cert->certBegin = dataASN[CERTREQASN_IDX_INFO_SEQ].offset;

        /* Parse the subject name. */
        idx = dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ].offset;
        ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT,
                          cert->source, &idx,
                          dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ].offset);
    }
    if (ret == 0) {
        /* Parse the certificate request Attributes. */
        ret = DecodeCertReqAttributes(cert, criticalExt,
                GetASNItem_DataIdx(dataASN[CERTREQASN_IDX_INFO_ATTRS],
                        cert->source),
                dataASN[CERTREQASN_IDX_INFO_SIGALGO_SEQ].offset);
    }
    if (ret == 0) {
        /* Parse the certificate request's key. */
        idx = dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ].offset;
        ret = GetCertKey(cert, cert->source, &idx,
                dataASN[CERTREQASN_IDX_INFO_ATTRS].offset);
    }
    if (ret == 0) {
        /* Store references to signature. */
        cert->sigIndex = dataASN[CERTREQASN_IDX_INFO_SIGALGO_SEQ].offset;
        GetASN_GetConstRef(&dataASN[CERTREQASN_IDX_INFO_SIGNATURE],
                &cert->signature, &cert->sigLength);
    }

    FREE_ASNGETDATA(dataASN, cert->heap);
    return ret;
}

#endif /* WOLFSSL_CERT_REQ */

#endif

int ParseCert(DecodedCert* cert, int type, int verify, void* cm)
{
    int   ret;
#if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
    defined(WOLFSSL_DYN_CERT)
    char* ptr;
#endif

    ret = ParseCertRelative(cert, type, verify, cm);
    if (ret < 0)
        return ret;

#if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
    defined(WOLFSSL_DYN_CERT)
    /* cert->subjectCN not stored as copy of WOLFSSL_NO_MALLOC defind */
    if (cert->subjectCNLen > 0) {
        ptr = (char*)XMALLOC((size_t)cert->subjectCNLen + 1, cert->heap,
                              DYNAMIC_TYPE_SUBJECT_CN);
        if (ptr == NULL)
            return MEMORY_E;
        XMEMCPY(ptr, cert->subjectCN, (size_t)cert->subjectCNLen);
        ptr[cert->subjectCNLen] = '\0';
        cert->subjectCN = ptr;
        cert->subjectCNStored = 1;
    }
#endif

#if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
    defined(WOLFSSL_DYN_CERT)
    /* cert->publicKey not stored as copy if WOLFSSL_NO_MALLOC defined */
    if ((cert->keyOID == RSAk
    #ifdef WC_RSA_PSS
         || cert->keyOID == RSAPSSk
    #endif
         ) && cert->publicKey != NULL && cert->pubKeySize > 0) {
        ptr = (char*)XMALLOC(cert->pubKeySize, cert->heap,
                              DYNAMIC_TYPE_PUBLIC_KEY);
        if (ptr == NULL)
            return MEMORY_E;
        XMEMCPY(ptr, cert->publicKey, cert->pubKeySize);
        cert->publicKey = (byte *)ptr;
        cert->pubKeyStored = 1;
    }
#endif

    return ret;
}

int wc_ParseCert(DecodedCert* cert, int type, int verify, void* cm)
{
    return ParseCert(cert, type, verify, cm);
}

#if !defined(OPENSSL_EXTRA) && !defined(OPENSSL_EXTRA_X509_SMALL) && \
    !defined(GetCA)
/* from SSL proper, for locking can't do find here anymore.
 * brought in from internal.h if built with compat layer.
 * if defined(GetCA), it's a predefined macro and these prototypes
 * would conflict.
 */
#ifdef __cplusplus
    extern "C" {
#endif
    Signer* GetCA(void* signers, byte* hash);
    #ifndef NO_SKID
        Signer* GetCAByName(void* signers, byte* hash);
    #endif
#ifdef __cplusplus
    }
#endif

#endif /* !OPENSSL_EXTRA && !OPENSSL_EXTRA_X509_SMALL && !GetCA */

#if defined(WOLFCRYPT_ONLY)

/* dummy functions, not using wolfSSL so don't need actual ones */
Signer* GetCA(void* signers, byte* hash)
{
    (void)hash;

    return (Signer*)signers;
}

#ifndef NO_SKID
Signer* GetCAByName(void* signers, byte* hash)
{
    (void)hash;

    return (Signer*)signers;
}
#endif /* NO_SKID */

#endif /* WOLFCRYPT_ONLY */

#if defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY) && !defined(NO_SKID)
static Signer* GetCABySubjectAndPubKey(DecodedCert* cert, void* cm)
{
    Signer* ca = NULL;
    if (cert->extSubjKeyIdSet)
        ca = GetCA(cm, cert->extSubjKeyId);
    if (ca == NULL)
        ca = GetCAByName(cm, cert->subjectHash);
    if (ca) {
        if ((ca->pubKeySize == cert->pubKeySize) &&
               (XMEMCMP(ca->publicKey, cert->publicKey, ca->pubKeySize) == 0)) {
            return ca;
        }
    }
    return NULL;
}
#endif

#if defined(WOLFSSL_SMALL_CERT_VERIFY) || defined(OPENSSL_EXTRA)
#ifdef WOLFSSL_ASN_TEMPLATE
/* Get the Hash of the Authority Key Identifier from the list of extensions.
 *
 * @param [in]  input   Input data.
 * @param [in]  maxIdx  Maximum index for data.
 * @param [out] hash    Hash of AKI.
 * @param [out] set     Whether the hash buffer was set.
 * @param [in]  heap    Dynamic memory allocation hint.
 * @return  0 on success.
 * @return  ASN_PARSE_E when BER encoded data does not match ASN.1 items or
 *          is invalid.
 * @return  MEMORY_E on dynamic memory allocation failure.
 */
static int GetAKIHash(const byte* input, word32 maxIdx, byte* hash, int* set,
                      void* heap)
{
    /* AKI and Certificate Extenion ASN.1 templates are the same length. */
    DECL_ASNGETDATA(dataASN, certExtASN_Length);
    int ret = 0;
    word32 idx = 0;
    word32 extEndIdx;
    byte* extData;
    word32 extDataSz;
    byte critical;

    ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, heap);
    (void)heap;

    extEndIdx = idx + maxIdx;

    /* Step through each extension looking for AKI. */
    while ((ret == 0) && (idx < extEndIdx)) {
        /* Clear dynamic data and check for certificate extension type OIDs. */
        XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
        GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
        /* Set criticality variable. */
        GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
        /* Parse an extension. */
        ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, input,
                &idx, extEndIdx);
        if (ret == 0) {
            /* Get reference to extension data and move index on past this
             * extension. */
            GetASN_GetRef(&dataASN[CERTEXTASN_IDX_VAL], &extData, &extDataSz);
            idx += extDataSz;

            /* Check whether we have the AKI extension. */
            if (dataASN[CERTEXTASN_IDX_OID].data.oid.sum == AUTH_KEY_OID) {
                /* Clear dynamic data. */
                XMEMSET(dataASN, 0, sizeof(*dataASN) * authKeyIdASN_Length);
                /* Start parsing extension data from the start. */
                idx = 0;
                /* Parse AKI extension data. */
                ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length,
                        1, extData, &idx, extDataSz);
                if ((ret == 0) &&
                        (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data
                                != NULL)) {
                    /* We parsed successfully and have data. */
                    *set = 1;
                    /* Get the hash or hash of the hash if wrong size. */
                    ret = GetHashId(
                            dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
                            dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
                            hash);
                }
                break;
            }
        }
    }

    FREE_ASNGETDATA(dataASN, heap);
    return ret;
}
#endif

/* Only quick step through the certificate to find fields that are then used
 * in certificate signature verification.
 * Must use the signature OID from the signed part of the certificate.
 * Works also on certificate signing requests.
 *
 * This is only for minimizing dynamic memory usage during TLS certificate
 * chain processing.
 * Doesn't support:
 *   OCSP Only: alt lookup using subject and pub key w/o sig check
 */
static int CheckCertSignature_ex(const byte* cert, word32 certSz, void* heap,
        void* cm, const byte* pubKey, word32 pubKeySz, int pubKeyOID, int req)
{
#ifndef WOLFSSL_ASN_TEMPLATE
#ifndef WOLFSSL_SMALL_STACK
    SignatureCtx  sigCtx[1];
#else
    SignatureCtx* sigCtx;
#endif
    byte          hash[KEYID_SIZE];
    Signer*       ca = NULL;
    word32        idx = 0;
    int           len;
    word32        tbsCertIdx = 0;
    word32        sigIndex   = 0;
    word32        signatureOID = 0;
    word32        oid = 0;
    word32        issuerIdx = 0;
    word32        issuerSz  = 0;
#ifndef NO_SKID
    int           extLen = 0;
    word32        extIdx = 0;
    word32        extEndIdx = 0;
    int           extAuthKeyIdSet = 0;
#endif
    int           ret = 0;
    word32        localIdx;
    byte          tag;
    const byte*   sigParams = NULL;
    word32        sigParamsSz = 0;


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

#ifdef WOLFSSL_SMALL_STACK
    sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap, DYNAMIC_TYPE_SIGNATURE);
    if (sigCtx == NULL)
        return MEMORY_E;
#endif

    InitSignatureCtx(sigCtx, heap, INVALID_DEVID);

    /* Certificate SEQUENCE */
    if (GetSequence(cert, &idx, &len, certSz) < 0)
        ret = ASN_PARSE_E;
    if (ret == 0) {
        tbsCertIdx = idx;

        /* TBSCertificate SEQUENCE */
        if (GetSequence(cert, &idx, &len, certSz) < 0)
            ret = ASN_PARSE_E;
    }
    if (ret == 0) {
        sigIndex = len + idx;

        if ((idx + 1) > certSz)
            ret = BUFFER_E;
    }
    if (ret == 0) {
        /* version - optional */
        localIdx = idx;
        if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
            if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
                idx++;
                if (GetLength(cert, &idx, &len, certSz) < 0)
                    ret = ASN_PARSE_E;
                idx += len;
            }
        }
    }

    if (ret == 0) {
        /* serialNumber */
        if (GetASNHeader(cert, ASN_INTEGER, &idx, &len, certSz) < 0)
            ret = ASN_PARSE_E;
    }
    if (ret == 0) {
        idx += len;

        /* signature */
        if (!req) {
            if (GetAlgoId(cert, &idx, &signatureOID, oidSigType, certSz) < 0)
                ret = ASN_PARSE_E;
        #ifdef WC_RSA_PSS
            else if (signatureOID == CTC_RSASSAPSS) {
                int start = idx;
                sigParams = cert + idx;
                if (GetSequence(cert, &idx, &len, certSz) < 0)
                    ret = ASN_PARSE_E;
                if (ret == 0) {
                    idx += len;
                    sigParamsSz = idx - start;
                }
            }
        #endif
        }
    }

    if (ret == 0) {
        issuerIdx = idx;
        /* issuer for cert or subject for csr */
        if (GetSequence(cert, &idx, &len, certSz) < 0)
            ret = ASN_PARSE_E;
    }
    if (ret == 0) {
        issuerSz = len + idx - issuerIdx;
    }
#ifndef NO_SKID
    if (!req && ret == 0) {
        idx += len;

        /* validity */
        if (GetSequence(cert, &idx, &len, certSz) < 0)
            ret = ASN_PARSE_E;
    }
    if (!req && ret == 0) {
        idx += len;

        /* subject */
        if (GetSequence(cert, &idx, &len, certSz) < 0)
            ret = ASN_PARSE_E;
    }
    if (ret == 0) {
        idx += len;

        /* subjectPublicKeyInfo */
        if (GetSequence(cert, &idx, &len, certSz) < 0)
            ret = ASN_PARSE_E;
    }
    if (req && ret == 0) {
        idx += len;

        /* attributes */
        if (GetASNHeader_ex(cert,
                ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &idx,
                &len, certSz, 1) < 0)
            ret = ASN_PARSE_E;
    }
    if (!req) {
        if (ret == 0) {
            idx += len;

            if ((idx + 1) > certSz)
                ret = BUFFER_E;
        }
        if (ret == 0) {
            /* issuerUniqueID - optional */
            localIdx = idx;
            if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
                if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)) {
                    idx++;
                    if (GetLength(cert, &idx, &len, certSz) < 0)
                        ret = ASN_PARSE_E;
                    idx += len;
                }
            }
        }
        if (ret == 0) {
            if ((idx + 1) > certSz)
                ret = BUFFER_E;
        }
        if (ret == 0) {
            /* subjectUniqueID - optional */
            localIdx = idx;
            if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
                if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)) {
                    idx++;
                    if (GetLength(cert, &idx, &len, certSz) < 0)
                        ret = ASN_PARSE_E;
                    idx += len;
                }
            }
        }

        if (ret == 0) {
            if ((idx + 1) > certSz)
                ret = BUFFER_E;
        }
        /* extensions - optional */
        localIdx = idx;
        if (ret == 0 && GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
                tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 3)) {
            idx++;
            if (GetLength(cert, &idx, &extLen, certSz) < 0)
                ret = ASN_PARSE_E;
            if (ret == 0) {
                if (GetSequence(cert, &idx, &extLen, certSz) < 0)
                    ret = ASN_PARSE_E;
            }
            if (ret == 0) {
                extEndIdx = idx + extLen;

                /* Check each extension for the ones we want. */
                while (ret == 0 && idx < extEndIdx) {
                    if (GetSequence(cert, &idx, &len, certSz) < 0)
                        ret = ASN_PARSE_E;
                    if (ret == 0) {
                        extIdx = idx;
                        if (GetObjectId(cert, &extIdx, &oid, oidCertExtType,
                                                                  certSz) < 0) {
                            ret = ASN_PARSE_E;
                        }

                        if (ret == 0) {
                            if ((extIdx + 1) > certSz)
                                ret = BUFFER_E;
                        }
                    }

                    if (ret == 0) {
                        localIdx = extIdx;
                        if (GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
                                tag == ASN_BOOLEAN) {
                            if (GetBoolean(cert, &extIdx, certSz) < 0)
                                ret = ASN_PARSE_E;
                        }
                    }
                    if (ret == 0) {
                        if (GetOctetString(cert, &extIdx, &extLen, certSz) < 0)
                            ret = ASN_PARSE_E;
                    }

                    if (ret == 0) {
                        switch (oid) {
                        case AUTH_KEY_OID:
                            if (GetSequence(cert, &extIdx, &extLen, certSz) < 0)
                                ret = ASN_PARSE_E;

                            if (ret == 0 && (extIdx + 1) >= certSz)
                                ret = BUFFER_E;

                            if (ret == 0 &&
                                    GetASNTag(cert, &extIdx, &tag, certSz) == 0 &&
                                    tag == (ASN_CONTEXT_SPECIFIC | 0)) {
                                if (GetLength(cert, &extIdx, &extLen, certSz) <= 0)
                                    ret = ASN_PARSE_E;
                                if (ret == 0) {
                                    extAuthKeyIdSet = 1;
                                    /* Get the hash or hash of the hash if wrong
                                     * size. */
                                    ret = GetHashId(cert + extIdx, extLen,
                                                    hash);
                                }
                            }
                            break;

                        default:
                            break;
                        }
                    }
                    idx += len;
                }
            }
        }
    }
    else if (ret == 0) {
        idx += len;
    }

    if (ret == 0 && pubKey == NULL) {
        if (extAuthKeyIdSet)
            ca = GetCA(cm, hash);
        if (ca == NULL) {
            ret = CalcHashId(cert + issuerIdx, issuerSz, hash);
            if (ret == 0)
                ca = GetCAByName(cm, hash);
        }
    }
#else
    if (ret == 0 && pubKey == NULL) {
        ret = CalcHashId(cert + issuerIdx, issuerSz, hash);
        if (ret == 0)
            ca = GetCA(cm, hash);
    }
#endif /* !NO_SKID */
    if (ca == NULL && pubKey == NULL)
        ret = ASN_NO_SIGNER_E;

    if (ret == 0) {
        idx = sigIndex;
        /* signatureAlgorithm */
        if (GetAlgoId(cert, &idx, &oid, oidSigType, certSz) < 0)
            ret = ASN_PARSE_E;
    #ifdef WC_RSA_PSS
        else if (signatureOID == CTC_RSASSAPSS) {
            word32 sz = idx;
            const byte* params = cert + idx;
            if (GetSequence(cert, &idx, &len, certSz) < 0)
                ret = ASN_PARSE_E;
            if (ret == 0) {
                idx += len;
                sz = idx - sz;

                if (req) {
                    if ((sz != sigParamsSz) ||
                                        (XMEMCMP(sigParams, params, sz) != 0)) {
                        ret = ASN_PARSE_E;
                    }
                }
                else {
                    sigParams = params;
                    sigParamsSz = sz;
                }
            }
        }
    #endif
        /* In CSR signature data is not present in body */
        if (req)
            signatureOID = oid;
    }
    if (ret == 0) {
        if (oid != signatureOID)
            ret = ASN_SIG_OID_E;
    }
    if (ret == 0) {
        /* signatureValue */
        if (CheckBitString(cert, &idx, &len, certSz, 1, NULL) < 0)
            ret = ASN_PARSE_E;
    }

    if (ret == 0) {
        if (pubKey != NULL) {
            ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
                sigIndex - tbsCertIdx, pubKey, pubKeySz, pubKeyOID,
                cert + idx, len, signatureOID, sigParams, sigParamsSz, NULL);
        }
        else {
            ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
                sigIndex - tbsCertIdx, ca->publicKey, ca->pubKeySize,
                ca->keyOID, cert + idx, len, signatureOID, sigParams,
                sigParamsSz, NULL);
        }
        if (ret != 0) {
            WOLFSSL_ERROR_VERBOSE(ret);
            WOLFSSL_MSG("Confirm signature failed");
        }
    }

    FreeSignatureCtx(sigCtx);
#ifdef WOLFSSL_SMALL_STACK
    if (sigCtx != NULL)
        XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE);
#endif
    return ret;
#else /* WOLFSSL_ASN_TEMPLATE */
    /* X509 ASN.1 template longer than Certificate Request template. */
    DECL_ASNGETDATA(dataASN, x509CertASN_Length);
#ifndef WOLFSSL_SMALL_STACK
    SignatureCtx  sigCtx[1];
#else
    SignatureCtx* sigCtx = NULL;
#endif
    byte hash[KEYID_SIZE];
    Signer* ca = NULL;
    int ret = 0;
    word32 idx = 0;
#ifndef NO_SKID
    int extAuthKeyIdSet = 0;
#endif
    const byte* tbs = NULL;
    word32 tbsSz = 0;
#ifdef WC_RSA_PSS
    const byte* tbsParams = NULL;
    word32 tbsParamsSz = 0;
#endif
    const byte* sig = NULL;
    word32 sigSz = 0;
    word32 sigOID = 0;
    const byte* sigParams = NULL;
    word32 sigParamsSz = 0;
    const byte* caName = NULL;
    word32 caNameLen = 0;
#ifndef NO_SKID
    const byte* akiData = NULL;
    word32 akiLen = 0;
#endif

    (void)req;
    (void)heap;

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

    ALLOC_ASNGETDATA(dataASN, x509CertASN_Length, ret, heap);

    if ((ret == 0) && (!req)) {
        /* Clear dynamic data for certificate items. */
        XMEMSET(dataASN, 0, sizeof(ASNGetData) * x509CertASN_Length);
        /* Set OID types expected for signature and public key. */
        GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID], oidSigType);
        GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID],
                oidKeyType);
        GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID],
                oidCurveType);
        GetASN_OID(&dataASN[X509CERTASN_IDX_SIGALGO_OID], oidSigType);
        /* Parse certificate. */
        ret = GetASN_Items(x509CertASN, dataASN, x509CertASN_Length, 1, cert,
                           &idx, certSz);

        /* Check signature OIDs match. */
        if ((ret == 0) && dataASN[X509CERTASN_IDX_TBS_ALGOID_OID].data.oid.sum
                != dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum) {
            ret = ASN_SIG_OID_E;
        }
        /* Store the data for verification in the certificate. */
        if (ret == 0) {
            tbs = GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_SEQ], cert);
            tbsSz = GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_SEQ], cert);
            caName = GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
                    cert);
            caNameLen = GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
                    cert);
            sigOID = dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum;
        #ifdef WC_RSA_PSS
            if (dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS].tag != 0) {
                tbsParams =
                    GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
                        cert);
                tbsParamsSz =
                    GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
                        cert);
            }
            if (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0) {
                sigParams =
                    GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
                        cert);
                sigParamsSz =
                    GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
                        cert);
            }
        #endif
            GetASN_GetConstRef(&dataASN[X509CERTASN_IDX_SIGNATURE], &sig, &sigSz);
        #ifdef WC_RSA_PSS
            if (tbsParamsSz != sigParamsSz) {
                ret = ASN_PARSE_E;
            }
            else if ((tbsParamsSz > 0) && (sigOID != CTC_RSASSAPSS)) {
                ret = ASN_PARSE_E;
            }
            else if ((tbsParamsSz > 0) &&
                     (XMEMCMP(tbsParams, sigParams, tbsParamsSz) != 0)) {
                ret = ASN_PARSE_E;
            }
        #endif
        }
    }
    else if (ret == 0) {
#ifndef WOLFSSL_CERT_REQ
        ret = NOT_COMPILED_IN;
#else
        /* Clear dynamic data for certificate request items. */
        XMEMSET(dataASN, 0, sizeof(ASNGetData) * certReqASN_Length);
        /* Set OID types expected for signature and public key. */
        GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID],
                oidKeyType);
        GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID],
                oidCurveType);
        GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID], oidSigType);
        /* Parse certificate request. */
        ret = GetASN_Items(certReqASN, dataASN, certReqASN_Length, 1, cert,
                           &idx, certSz);
        if (ret == 0) {
            /* Store the data for verification in the certificate. */
            tbs = GetASNItem_Addr(dataASN[CERTREQASN_IDX_INFO_SEQ], cert);
            tbsSz = GetASNItem_Length(dataASN[CERTREQASN_IDX_INFO_SEQ], cert);
            caName = GetASNItem_Addr(
                    dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ], cert);
            caNameLen = GetASNItem_Length(
                    dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ], cert);
            sigOID = dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID].data.oid.sum;
        #ifdef WC_RSA_PSS
            sigParams = GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
                cert);
            sigParamsSz =
                GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
                    cert);
        #endif
            GetASN_GetConstRef(&dataASN[CERTREQASN_IDX_INFO_SIGNATURE], &sig,
                    &sigSz);
        }
#endif
    }

#ifndef NO_SKID
    if ((ret == 0) && (pubKey == NULL) && !req) {
        akiData = dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.data;
        akiLen = dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.length;
    }
#endif

    FREE_ASNGETDATA(dataASN, heap);

    /* If no public passed, then find the CA. */
    if ((ret == 0) && (pubKey == NULL)) {
#ifndef NO_SKID
        /* Find the AKI extension in list of extensions and get hash. */
        if ((!req) && (akiData != NULL)) {
            /* TODO: test case */
            ret = GetAKIHash(akiData, akiLen, hash, &extAuthKeyIdSet, heap);
        }

        /* Get the CA by hash one was found. */
        if (extAuthKeyIdSet) {
            ca = GetCA(cm, hash);
        }
        if (ca == NULL)
#endif
        {
            /* Try hash of issuer name. */
            ret = CalcHashId(caName, caNameLen, hash);
            if (ret == 0) {
                ca = GetCAByName(cm, hash);
            }
        }

        if (ca != NULL) {
            /* Extract public key information. */
            pubKey = ca->publicKey;
            pubKeySz = ca->pubKeySize;
            pubKeyOID = ca->keyOID;
        }
        else {
            /* No public key to verify with. */
            ret = ASN_NO_SIGNER_E;
        }
    }

    if (ret == 0) {
    #ifdef WOLFSSL_SMALL_STACK
        sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap,
            DYNAMIC_TYPE_SIGNATURE);
        if (sigCtx == NULL) {
            ret = MEMORY_E;
        }
        if (ret == 0)
    #endif
        {
            InitSignatureCtx(sigCtx, heap, INVALID_DEVID);

            /* Check signature. */
            ret = ConfirmSignature(sigCtx, tbs, tbsSz, pubKey, pubKeySz,
                pubKeyOID, sig, sigSz, sigOID, sigParams, sigParamsSz, NULL);
            if (ret != 0) {
                WOLFSSL_MSG("Confirm signature failed");
            }

            FreeSignatureCtx(sigCtx);
        #ifdef WOLFSSL_SMALL_STACK
            XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE);
        #endif
        }
    }

    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

#ifdef OPENSSL_EXTRA
/* Call CheckCertSignature_ex using a public key buffer for verification
 */
int CheckCertSignaturePubKey(const byte* cert, word32 certSz, void* heap,
        const byte* pubKey, word32 pubKeySz, int pubKeyOID)
{
    return CheckCertSignature_ex(cert, certSz, heap, NULL,
            pubKey, pubKeySz, pubKeyOID, 0);
}

int wc_CheckCertSigPubKey(const byte* cert, word32 certSz, void* heap,
        const byte* pubKey, word32 pubKeySz, int pubKeyOID)
{
        return CheckCertSignaturePubKey(cert, certSz, heap, pubKey, pubKeySz,
                                        pubKeyOID);
}

#ifdef WOLFSSL_CERT_REQ
int CheckCSRSignaturePubKey(const byte* cert, word32 certSz, void* heap,
        const byte* pubKey, word32 pubKeySz, int pubKeyOID)
{
    return CheckCertSignature_ex(cert, certSz, heap, NULL,
            pubKey, pubKeySz, pubKeyOID, 1);
}
#endif /* WOLFSSL_CERT_REQ */
#endif /* OPENSSL_EXTRA */
#ifdef WOLFSSL_SMALL_CERT_VERIFY
/* Call CheckCertSignature_ex using a certificate manager (cm)
 */
int CheckCertSignature(const byte* cert, word32 certSz, void* heap, void* cm)
{
    return CheckCertSignature_ex(cert, certSz, heap, cm, NULL, 0, 0, 0);
}
#endif /* WOLFSSL_SMALL_CERT_VERIFY */
#endif /* WOLFSSL_SMALL_CERT_VERIFY || OPENSSL_EXTRA */

#if (defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) || \
    (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)))
/* ASN.1 DER decode instruction. */
typedef struct DecodeInstr {
    /* Tag expected. */
    byte tag;
    /* Operation to perform: step in or go over */
    byte op:1;
    /* ASN.1 item is optional. */
    byte optional:1;
} DecodeInstr;

/* Step into ASN.1 item. */
#define DECODE_INSTR_IN    0
/* Step over ASN.1 item. */
#define DECODE_INSTR_OVER  1

/* Get the public key data from the DER encoded X.509 certificate.
 *
 * Assumes data has previously been parsed for complete validity.
 *
 * @param [in]  cert      DER encoded X.509 certificate data.
 * @param [in]  certSz    Length of DER encoding.
 * @param [out] pubKey    Public key data. (From the BIT_STRING.)
 * @param [out] pubKeySz  Length of public key data in bytes.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when cert, pubKey or pubKeySz is NULL.
 * @return  ASN_PARSE_E when certificate encoding is invalid.
 */
int wc_CertGetPubKey(const byte* cert, word32 certSz,
    const unsigned char** pubKey, word32* pubKeySz)
{
    int ret = 0;
    int l;
    word32 o = 0;
    int i;
    static DecodeInstr ops[] = {
        /* Outer SEQ */
        { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN  , 0 },
        /* TBSCertificate: SEQ */
        { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN  , 0 },
        /* Version: [0] */
        { ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_X509_CERT_VERSION,
          DECODE_INSTR_OVER, 1 },
        /* CertificateSerialNumber: INT  */
        { ASN_INTEGER,                    DECODE_INSTR_OVER, 0 },
        /* AlgorithmIdentifier: SEQ */
        { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
        /* issuer: SEQ */
        { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
        /* Validity: SEQ */
        { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
        /* subject: SEQ */
        { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
        /* subjectPublicKeyInfo SEQ */
        { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN  , 0 },
        /* AlgorithmIdentifier: SEQ */
        { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
        /* PublicKey: BIT_STRING  */
        { ASN_BIT_STRING,                 DECODE_INSTR_IN  , 0 },
    };

    /* Validate parameters. */
    if ((cert == NULL) || (pubKey == NULL) || (pubKeySz == NULL)) {
        ret = BAD_FUNC_ARG;
    }

    /* Process each instruction to take us to public key data. */
    for (i = 0; (ret == 0) && (i < (int)(sizeof(ops) / sizeof(*ops))); i++) {
        DecodeInstr op = ops[i];

        /* Check the current ASN.1 item has the expected tag. */
        if (cert[o] != op.tag) {
            /* If not optional then error, otherwise skip op. */
            if (!op.optional) {
                ret = ASN_PARSE_E;
            }
        }
        else {
            /* Move past tag. */
            o++;
            /* Get the length of ASN.1 item and move past length encoding. */
            if (GetLength(cert, &o, &l, certSz) < 0) {
                ret = ASN_PARSE_E;
            }
            /* Skip data if required. */
            else if (op.op == DECODE_INSTR_OVER) {
                o += l;
            }
        }
    }

    if (ret == 0) {
        /* Return the public key data and length.
         * Skip first byte of BIT_STRING data: unused bits. */
        *pubKey = cert + o + 1;
        *pubKeySz = l - 1;
    }

    return ret;
}
#endif

int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm)
{
    int    ret = 0;
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 confirmOID = 0;
#ifdef WOLFSSL_CERT_REQ
    int    len = 0;
#endif
#endif
#if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
    int    idx = 0;
#endif
    byte*  sce_tsip_encRsaKeyIdx;

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

#ifdef WOLFSSL_CERT_REQ
    if (type == CERTREQ_TYPE)
        cert->isCSR = 1;
#endif

    if (cert->sigCtx.state == SIG_STATE_BEGIN) {
#ifndef WOLFSSL_ASN_TEMPLATE
        cert->badDate = 0;
        cert->criticalExt = 0;
        if ((ret = DecodeToKey(cert, verify)) < 0) {
            if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E) {
                cert->badDate = ret;
                if (verify == VERIFY_SKIP_DATE)
                    ret = 0;
            }
            else
                return ret;
        }

        WOLFSSL_MSG("Parsed Past Key");


#ifdef WOLFSSL_CERT_REQ
        /* Read attributes */
        if (cert->isCSR) {
            if (GetASNHeader_ex(cert->source,
                    ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &cert->srcIdx,
                    &len, cert->maxIdx, 1) < 0) {
                WOLFSSL_MSG("GetASNHeader_ex error");
                return ASN_PARSE_E;
            }

            if (len) {
                word32 attrMaxIdx = cert->srcIdx + (word32)len;
                word32 oid;
                byte   tag;

                if (attrMaxIdx > cert->maxIdx) {
                    WOLFSSL_MSG("Attribute length greater than CSR length");
                    return ASN_PARSE_E;
                }

                while (cert->srcIdx < attrMaxIdx) {
                    /* Attributes have the structure:
                     * SEQ -> OID -> SET -> ATTRIBUTE */
                    if (GetSequence(cert->source, &cert->srcIdx, &len,
                            attrMaxIdx) < 0) {
                        WOLFSSL_MSG("attr GetSequence error");
                        return ASN_PARSE_E;
                    }
                    if (GetObjectId(cert->source, &cert->srcIdx, &oid,
                            oidCsrAttrType, attrMaxIdx) < 0) {
                        WOLFSSL_MSG("attr GetObjectId error");
                        return ASN_PARSE_E;
                    }
                    if (GetSet(cert->source, &cert->srcIdx, &len,
                            attrMaxIdx) < 0) {
                        WOLFSSL_MSG("attr GetSet error");
                        return ASN_PARSE_E;
                    }
                    switch (oid) {
                    case PKCS9_CONTENT_TYPE_OID:
                        if (GetHeader(cert->source, &tag,
                                &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
                            WOLFSSL_MSG("attr GetHeader error");
                            return ASN_PARSE_E;
                        }
                        if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
                                tag != ASN_IA5_STRING) {
                            WOLFSSL_MSG("Unsupported attribute value format");
                            return ASN_PARSE_E;
                        }
                        cert->contentType = (char*)cert->source + cert->srcIdx;
                        cert->contentTypeLen = len;
                        cert->srcIdx += (word32)len;
                        break;
                    case CHALLENGE_PASSWORD_OID:
                        if (GetHeader(cert->source, &tag,
                                &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
                            WOLFSSL_MSG("attr GetHeader error");
                            return ASN_PARSE_E;
                        }
                        if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
                                tag != ASN_IA5_STRING) {
                            WOLFSSL_MSG("Unsupported attribute value format");
                            return ASN_PARSE_E;
                        }
                        cert->cPwd = (char*)cert->source + cert->srcIdx;
                        cert->cPwdLen = len;
                        cert->srcIdx += (word32)len;
                        break;
                    case SERIAL_NUMBER_OID:
                        if (GetHeader(cert->source, &tag,
                                &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
                            WOLFSSL_MSG("attr GetHeader error");
                            return ASN_PARSE_E;
                        }
                        if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
                                tag != ASN_IA5_STRING) {
                            WOLFSSL_MSG("Unsupported attribute value format");
                            return ASN_PARSE_E;
                        }
                        cert->sNum = (char*)cert->source + cert->srcIdx;
                        cert->sNumLen = len;
                        cert->srcIdx += (word32)len;
                        if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) {
                            XMEMCPY(cert->serial, cert->sNum,
                                    (size_t)cert->sNumLen);
                            cert->serialSz = cert->sNumLen;
                        }
                        break;
                    case DNQUALIFIER_OID:
                        if (GetHeader(cert->source, &tag,
                                &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
                            WOLFSSL_MSG("attr GetHeader error");
                            return ASN_PARSE_E;
                        }
                        cert->dnQualifier = (char*)cert->source + cert->srcIdx;
                        cert->dnQualifierLen = len;
                        cert->srcIdx += (word32)len;
                        break;
                    case INITIALS_OID:
                        if (GetHeader(cert->source, &tag,
                                &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
                            WOLFSSL_MSG("attr GetHeader error");
                            return ASN_PARSE_E;
                        }
                        cert->initials = (char*)cert->source + cert->srcIdx;
                        cert->initialsLen = len;
                        cert->srcIdx += (word32)len;
                        break;
                    case SURNAME_OID:
                        if (GetHeader(cert->source, &tag,
                                &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
                            WOLFSSL_MSG("attr GetHeader error");
                            return ASN_PARSE_E;
                        }
                        cert->surname = (char*)cert->source + cert->srcIdx;
                        cert->surnameLen = len;
                        cert->srcIdx += (word32)len;
                        break;
                    case GIVEN_NAME_OID:
                        if (GetHeader(cert->source, &tag,
                                &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
                            WOLFSSL_MSG("attr GetHeader error");
                            return ASN_PARSE_E;
                        }
                        cert->givenName = (char*)cert->source + cert->srcIdx;
                        cert->givenNameLen = len;
                        cert->srcIdx += (word32)len;
                        break;
                    case UNSTRUCTURED_NAME_OID:
                        if (GetHeader(cert->source, &tag,
                                &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
                            WOLFSSL_MSG("attr GetHeader error");
                            return ASN_PARSE_E;
                        }
                        cert->unstructuredName =
                            (char*)cert->source + cert->srcIdx;
                        cert->unstructuredNameLen = len;
                        cert->srcIdx += (word32)len;
                        break;
                    case EXTENSION_REQUEST_OID:
                        /* save extensions */
                        cert->extensions    = &cert->source[cert->srcIdx];
                        cert->extensionsSz  = len;
                        cert->extensionsIdx = cert->srcIdx; /* for potential later use */

                        if ((ret = DecodeCertExtensions(cert)) < 0) {
                            if (ret == ASN_CRIT_EXT_E) {
                                cert->criticalExt = ret;
                            }
                            else {
                                return ret;
                            }
                        }
                        cert->srcIdx += (word32)len;
                        break;
                    default:
                        WOLFSSL_MSG("Unsupported attribute type");
                        WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
                        return ASN_PARSE_E;
                    }
                }
            }
        }
#endif

        if (cert->srcIdx < cert->sigIndex) {
        #ifndef ALLOW_V1_EXTENSIONS
            if (cert->version < 2) {
                WOLFSSL_MSG("\tv1 and v2 certs not allowed extensions");
                WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
                return ASN_VERSION_E;
            }
        #endif

            /* save extensions */
            cert->extensions    = &cert->source[cert->srcIdx];
            cert->extensionsSz  = (int)(cert->sigIndex - cert->srcIdx);
            cert->extensionsIdx = cert->srcIdx;   /* for potential later use */

            if ((ret = DecodeCertExtensions(cert)) < 0) {
                if (ret == ASN_CRIT_EXT_E)
                    cert->criticalExt = ret;
                else
                    return ret;
            }

        #ifdef HAVE_OCSP
            if (verify == VERIFY_OCSP_CERT) {
                /* trust for the lifetime of the responder's cert*/
                if (cert->ocspNoCheckSet)
                    verify = VERIFY;
                else
                    verify = VERIFY_OCSP;
            }
        #endif
            /* advance past extensions */
            cert->srcIdx = cert->sigIndex;
        }

        if ((ret = GetSigAlg(cert,
#ifdef WOLFSSL_CERT_REQ
                !cert->isCSR ? &confirmOID : &cert->signatureOID,
#else
                &confirmOID,
#endif
                cert->maxIdx)) < 0) {
            return ret;
        }

        if ((ret = GetSignature(cert)) < 0) {
            return ret;
        }

        if (confirmOID != cert->signatureOID
#ifdef WOLFSSL_CERT_REQ
                && !cert->isCSR
#endif
                ) {
            WOLFSSL_ERROR_VERBOSE(ASN_SIG_OID_E);
            return ASN_SIG_OID_E;
        }
#else
#ifdef WOLFSSL_CERT_REQ
        if (cert->isCSR) {
            ret = DecodeCertReq(cert, &cert->criticalExt);
            if (ret < 0) {
                return ret;
            }
        }
        else
#endif
        {
            ret = DecodeCert(cert, verify, &cert->criticalExt);
            if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E) {
                cert->badDate = ret;
                if (verify == VERIFY_SKIP_DATE)
                    ret = 0;
            }
            else if (ret < 0) {
                WOLFSSL_ERROR_VERBOSE(ret);
                return ret;
            }
        }
#endif

    #ifndef NO_SKID
        if (cert->extSubjKeyIdSet == 0 && cert->publicKey != NULL &&
                                                         cert->pubKeySize > 0) {
            ret = CalcHashId(cert->publicKey, cert->pubKeySize,
                                                            cert->extSubjKeyId);
            if (ret != 0) {
                WOLFSSL_ERROR_VERBOSE(ret);
                return ret;
            }
        }
    #endif /* !NO_SKID */

        if (!cert->selfSigned || (verify != NO_VERIFY && type != CA_TYPE &&
                                                   type != TRUSTED_PEER_TYPE)) {
            cert->ca = NULL;
    #ifndef NO_SKID
            if (cert->extAuthKeyIdSet) {
                cert->ca = GetCA(cm, cert->extAuthKeyId);
            }
            if (cert->ca == NULL && cert->extSubjKeyIdSet
                                 && verify != VERIFY_OCSP) {
                cert->ca = GetCA(cm, cert->extSubjKeyId);
            }
            if (cert->ca != NULL && XMEMCMP(cert->issuerHash,
                                  cert->ca->subjectNameHash, KEYID_SIZE) != 0) {
                cert->ca = NULL;
            }
            if (cert->ca == NULL) {
                cert->ca = GetCAByName(cm, cert->issuerHash);
                /* If AKID is available then this CA doesn't have the public
                 * key required */
                if (cert->ca && cert->extAuthKeyIdSet) {
                    WOLFSSL_MSG("CA SKID doesn't match AKID");
                    cert->ca = NULL;
                }
            }

            /* OCSP Only: alt lookup using subject and pub key w/o sig check */
        #ifdef WOLFSSL_NO_TRUSTED_CERTS_VERIFY
            if (cert->ca == NULL && verify == VERIFY_OCSP) {
                cert->ca = GetCABySubjectAndPubKey(cert, cm);
                if (cert->ca) {
                    ret = 0; /* success */
                    goto exit_pcr;
                }
            }
        #endif /* WOLFSSL_NO_TRUSTED_CERTS_VERIFY */
    #else
            cert->ca = GetCA(cm, cert->issuerHash);
    #endif /* !NO_SKID */

            if (cert->ca) {
                WOLFSSL_MSG("CA found");
            }
        }

        if (cert->selfSigned) {
            cert->maxPathLen = WOLFSSL_MAX_PATH_LEN;
        } else {
            /* RFC 5280 Section 4.2.1.9:
             *
             * load/receive check
             *
             * 1) Is CA boolean set?
             *      No  - SKIP CHECK
             *      Yes - Check key usage
             * 2) Is Key usage extension present?
             *      No  - goto 3
             *      Yes - check keyCertSign assertion
             *     2.a) Is keyCertSign asserted?
             *          No  - goto 4
             *          Yes - goto 3
             * 3) Is pathLen set?
             *      No  - goto 4
             *      Yes - check pathLen against maxPathLen.
             *      3.a) Is pathLen less than maxPathLen?
             *           No - goto 4
             *           Yes - set maxPathLen to pathLen and EXIT
             * 4) Is maxPathLen > 0?
             *      Yes - Reduce by 1
             *      No  - ERROR
             */

            if (cert->ca && cert->pathLengthSet) {
                int checkPathLen = 0;
                int decrementMaxPathLen = 0;
                cert->maxPathLen = cert->pathLength;
                if (cert->isCA) {
                    WOLFSSL_MSG("\tCA boolean set");
                    if (cert->extKeyUsageSet) {
                        WOLFSSL_MSG("\tExtension Key Usage Set");
                        if ((cert->extKeyUsage & KEYUSE_KEY_CERT_SIGN) != 0) {
                            checkPathLen = 1;
                        }
                        else {
                            decrementMaxPathLen = 1;
                        }
                    }
                    else {
                        checkPathLen = 1;
                    } /* !cert->ca check */
                } /* cert is not a CA (assuming entity cert) */

                if (checkPathLen && cert->pathLengthSet) {
                    if (cert->pathLength < cert->ca->maxPathLen) {
                        WOLFSSL_MSG("\tmaxPathLen status: set to pathLength");
                        cert->maxPathLen = cert->pathLength;
                    }
                    else {
                        decrementMaxPathLen = 1;
                    }
                }

                if (decrementMaxPathLen && cert->ca->maxPathLen > 0) {
                    WOLFSSL_MSG("\tmaxPathLen status: reduce by 1");
                    cert->maxPathLen = (byte)(cert->ca->maxPathLen - 1);
                    if (verify != NO_VERIFY && type != CA_TYPE &&
                                                    type != TRUSTED_PEER_TYPE) {
                        WOLFSSL_MSG("\tmaxPathLen status: OK");
                    }
                } else if (decrementMaxPathLen && cert->ca->maxPathLen == 0) {
                    cert->maxPathLen = 0;
                    if (verify != NO_VERIFY && type != CA_TYPE &&
                                                    type != TRUSTED_PEER_TYPE) {
                        WOLFSSL_MSG("\tNon-entity cert, maxPathLen is 0");
                        WOLFSSL_MSG("\tmaxPathLen status: ERROR");
                        WOLFSSL_ERROR_VERBOSE(ASN_PATHLEN_INV_E);
                        return ASN_PATHLEN_INV_E;
                    }
                }
            } else if (cert->ca && cert->isCA) {
                /* case where cert->pathLength extension is not set */
                if (cert->ca->maxPathLen > 0) {
                    cert->maxPathLen = (byte)(cert->ca->maxPathLen - 1);
                } else {
                    cert->maxPathLen = 0;
                    if (verify != NO_VERIFY && type != CA_TYPE &&
                                                    type != TRUSTED_PEER_TYPE) {
                        WOLFSSL_MSG("\tNon-entity cert, maxPathLen is 0");
                        WOLFSSL_MSG("\tmaxPathLen status: ERROR");
                        WOLFSSL_ERROR_VERBOSE(ASN_PATHLEN_INV_E);
                        return ASN_PATHLEN_INV_E;
                    }
                }
            }
        }

        #ifdef HAVE_OCSP
        if (verify != NO_VERIFY && type != CA_TYPE &&
                                                type != TRUSTED_PEER_TYPE) {
            if (cert->ca) {
                /* Need the CA's public key hash for OCSP */
                XMEMCPY(cert->issuerKeyHash, cert->ca->subjectKeyHash,
                                                                KEYID_SIZE);
            }
        }
        #endif /* HAVE_OCSP */
    }
#if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
    /* prepare for TSIP TLS cert verification API use */
    if (cert->keyOID == RSAk) {
        /* to call TSIP API, it needs keys position info in bytes */
        if ((ret = RsaPublicKeyDecodeRawIndex(cert->publicKey, (word32*)&idx,
                                   cert->pubKeySize,
                                   &cert->sigCtx.CertAtt.pubkey_n_start,
                                   &cert->sigCtx.CertAtt.pubkey_n_len,
                                   &cert->sigCtx.CertAtt.pubkey_e_start,
                                   &cert->sigCtx.CertAtt.pubkey_e_len)) != 0) {
            WOLFSSL_MSG("Decoding index from cert failed.");
            return ret;
        }
        cert->sigCtx.CertAtt.certBegin = cert->certBegin;
    } else if (cert->keyOID == ECDSAk) {
        cert->sigCtx.CertAtt.certBegin = cert->certBegin;
    }
    /* check if we can use TSIP for cert verification */
    /* if the ca is verified as tsip root ca.         */
    /* TSIP can only handle 2048 bits(256 byte) key.  */
    if (cert->ca && Renesas_cmn_checkCA(cert->ca->cm_idx) != 0 &&
        (cert->sigCtx.CertAtt.pubkey_n_len == 256 ||
         cert->sigCtx.CertAtt.curve_id == ECC_SECP256R1)) {

        /* assign memory to encrypted tsip Rsa key index */
        if (!cert->sce_tsip_encRsaKeyIdx)
            cert->sce_tsip_encRsaKeyIdx =
                            (byte*)XMALLOC(TSIP_TLS_ENCPUBKEY_SZ_BY_CERTVRFY,
                             cert->heap, DYNAMIC_TYPE_RSA);
        if (cert->sce_tsip_encRsaKeyIdx == NULL)
                return MEMORY_E;
    }
    else {
        if (cert->ca) {
            /* TSIP isn't usable */
            if (Renesas_cmn_checkCA(cert->ca->cm_idx) == 0)
                WOLFSSL_MSG("SCE-TSIP isn't usable because the ca isn't verified "
                            "by TSIP.");
            else if (cert->sigCtx.CertAtt.pubkey_n_len != 256)
                WOLFSSL_MSG("SCE-TSIP isn't usable because the ca isn't signed by "
                            "RSA 2048.");
            else
                WOLFSSL_MSG("SCE-TSIP isn't usable");
        }
        cert->sce_tsip_encRsaKeyIdx = NULL;
    }

    sce_tsip_encRsaKeyIdx = cert->sce_tsip_encRsaKeyIdx;

#else
    sce_tsip_encRsaKeyIdx = NULL;
#endif

    if (verify != NO_VERIFY && type != CA_TYPE && type != TRUSTED_PEER_TYPE) {
        if (cert->ca) {
            if (verify == VERIFY || verify == VERIFY_OCSP ||
                                                 verify == VERIFY_SKIP_DATE) {
                /* try to confirm/verify signature */
                if ((ret = ConfirmSignature(&cert->sigCtx,
                        cert->source + cert->certBegin,
                        cert->sigIndex - cert->certBegin,
                        cert->ca->publicKey, cert->ca->pubKeySize,
                        cert->ca->keyOID, cert->signature,
                        cert->sigLength, cert->signatureOID,
                    #ifdef WC_RSA_PSS
                        cert->source + cert->sigParamsIndex,
                        cert->sigParamsLength,
                    #else
                        NULL, 0,
                    #endif
                        sce_tsip_encRsaKeyIdx)) != 0) {
                    if (ret != WC_PENDING_E) {
                        WOLFSSL_MSG("Confirm signature failed");
                    }
                    WOLFSSL_ERROR_VERBOSE(ret);
                    return ret;
                }
            }
        #ifndef IGNORE_NAME_CONSTRAINTS
            if (verify == VERIFY || verify == VERIFY_OCSP ||
                        verify == VERIFY_NAME || verify == VERIFY_SKIP_DATE) {
                /* check that this cert's name is permitted by the signer's
                 * name constraints */
                if (!ConfirmNameConstraints(cert->ca, cert)) {
                    WOLFSSL_MSG("Confirm name constraint failed");
                    WOLFSSL_ERROR_VERBOSE(ASN_NAME_INVALID_E);
                    return ASN_NAME_INVALID_E;
                }
            }
        #endif /* IGNORE_NAME_CONSTRAINTS */
        }
#ifdef WOLFSSL_CERT_REQ
        else if (type == CERTREQ_TYPE) {
            if ((ret = ConfirmSignature(&cert->sigCtx,
                    cert->source + cert->certBegin,
                    cert->sigIndex - cert->certBegin,
                    cert->publicKey, cert->pubKeySize,
                    cert->keyOID, cert->signature,
                    cert->sigLength, cert->signatureOID,
                #ifdef WC_RSA_PSS
                    cert->source + cert->sigParamsIndex, cert->sigParamsLength,
                #else
                    NULL, 0,
                #endif
                    sce_tsip_encRsaKeyIdx)) != 0) {
                if (ret != WC_PENDING_E) {
                    WOLFSSL_MSG("Confirm signature failed");
                }
                WOLFSSL_ERROR_VERBOSE(ret);
                return ret;
            }
        }
#endif
        else {
            /* no signer */
            WOLFSSL_MSG("No CA signer to verify with");
#if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
            /* ret needs to be self-signer error for Qt compat */
            if (cert->selfSigned) {
                WOLFSSL_ERROR_VERBOSE(ASN_SELF_SIGNED_E);
                return ASN_SELF_SIGNED_E;
            }
            else
#endif
            {
                WOLFSSL_ERROR_VERBOSE(ASN_NO_SIGNER_E);
                return ASN_NO_SIGNER_E;
            }
        }
    }

#if defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY) && !defined(NO_SKID)
exit_pcr:
#endif

    if (cert->badDate != 0) {
        if (verify != VERIFY_SKIP_DATE) {
            return cert->badDate;
        }
        WOLFSSL_MSG("Date error: Verify option is skipping");
    }

    if (cert->criticalExt != 0)
        return cert->criticalExt;

    return ret;
}

/* Create and init an new signer */
Signer* MakeSigner(void* heap)
{
    Signer* signer = (Signer*) XMALLOC(sizeof(Signer), heap,
                                       DYNAMIC_TYPE_SIGNER);
    if (signer) {
        XMEMSET(signer, 0, sizeof(Signer));
    }
    (void)heap;

    return signer;
}


/* Free an individual signer.
 *
 * Used by Certificate Manager.
 *
 * @param [in, out] signer  On in, signer object.
 *                          On out, pointer is no longer valid.
 * @param [in]      heap    Dynamic memory hint.
 */
void FreeSigner(Signer* signer, void* heap)
{
    (void)signer;
    (void)heap;
    XFREE(signer->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
    XFREE((void*)signer->publicKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
#ifndef IGNORE_NAME_CONSTRAINTS
    if (signer->permittedNames)
        FreeNameSubtrees(signer->permittedNames, heap);
    if (signer->excludedNames)
        FreeNameSubtrees(signer->excludedNames, heap);
#endif
#ifdef WOLFSSL_SIGNER_DER_CERT
    FreeDer(&signer->derCert);
#endif
    XFREE(signer, heap, DYNAMIC_TYPE_SIGNER);
}


/* Free the whole singer table with number of rows.
 *
 * Each table entry is a linked list of signers.
 * Used by Certificate Manager.
 *
 * @param [in, out] table   Array of signer objects.
 * @param [in]      rows    Number of entries in table.
 * @param [in]      heap    Dynamic memory hint.
 */
void FreeSignerTable(Signer** table, int rows, void* heap)
{
    int i;

    for (i = 0; i < rows; i++) {
        Signer* signer = table[i];
        while (signer) {
            Signer* next = signer->next;
            FreeSigner(signer, heap);
            signer = next;
        }
        table[i] = NULL;
    }
}

#ifdef WOLFSSL_TRUST_PEER_CERT
/* Free an individual trusted peer cert.
 *
 * @param [in, out] tp    Trusted peer certificate object.
 * @param [in]      heap  Dynamic memory hint.
 */
void FreeTrustedPeer(TrustedPeerCert* tp, void* heap)
{
    if (tp == NULL) {
        return;
    }

    if (tp->name) {
        XFREE(tp->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
    }

    if (tp->sig) {
        XFREE(tp->sig, heap, DYNAMIC_TYPE_SIGNATURE);
    }
#ifndef IGNORE_NAME_CONSTRAINTS
    if (tp->permittedNames)
        FreeNameSubtrees(tp->permittedNames, heap);
    if (tp->excludedNames)
        FreeNameSubtrees(tp->excludedNames, heap);
#endif
    XFREE(tp, heap, DYNAMIC_TYPE_CERT);

    (void)heap;
}

/* Free the whole Trusted Peer linked list.
 *
 * Each table entry is a linked list of trusted peer certificates.
 * Used by Certificate Manager.
 *
 * @param [in, out] table   Array of trusted peer certificate objects.
 * @param [in]      rows    Number of entries in table.
 * @param [in]      heap    Dynamic memory hint.
 */
void FreeTrustedPeerTable(TrustedPeerCert** table, int rows, void* heap)
{
    int i;

    for (i = 0; i < rows; i++) {
        TrustedPeerCert* tp = table[i];
        while (tp) {
            TrustedPeerCert* next = tp->next;
            FreeTrustedPeer(tp, heap);
            tp = next;
        }
        table[i] = NULL;
    }
}
#endif /* WOLFSSL_TRUST_PEER_CERT */

int SetMyVersion(word32 version, byte* output, int header)
{
    int i = 0;

    if (output == NULL)
        return BAD_FUNC_ARG;

    if (header) {
        output[i++] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
        output[i++] = 3;
    }
    output[i++] = ASN_INTEGER;
    output[i++] = 0x01;
    output[i++] = (byte)version;

    return i;
}

#if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS7)
int SetSerialNumber(const byte* sn, word32 snSz, byte* output,
    word32 outputSz, int maxSnSz)
{
    int i;
    int snSzInt = (int)snSz;

    if (sn == NULL || output == NULL || snSzInt < 0)
        return BAD_FUNC_ARG;

    /* remove leading zeros */
    while (snSzInt > 0 && sn[0] == 0) {
        snSzInt--;
        sn++;
    }
    /* RFC 5280 - 4.1.2.2:
     *   Serial numbers must be a positive value (and not zero) */
    if (snSzInt == 0) {
        WOLFSSL_ERROR_VERBOSE(BAD_FUNC_ARG);
        return BAD_FUNC_ARG;
    }

    if (sn[0] & 0x80)
        maxSnSz--;
    /* truncate if input is too long */
    if (snSzInt > maxSnSz)
        snSzInt = maxSnSz;

    i = SetASNInt(snSzInt, sn[0], NULL);
    /* truncate if input is too long */
    if (snSzInt > (int)outputSz - i)
        snSzInt = (int)outputSz - i;
    /* sanity check number of bytes to copy */
    if (snSzInt <= 0) {
        return BUFFER_E;
    }

    /* write out ASN.1 Integer */
    (void)SetASNInt(snSzInt, sn[0], output);
    XMEMCPY(output + i, sn, (size_t)snSzInt);

    /* compute final length */
    i += snSzInt;

    return i;
}
#endif /* !WOLFSSL_ASN_TEMPLATE */

#endif /* !NO_CERTS */

#ifndef WOLFSSL_ASN_TEMPLATE
int wc_GetSerialNumber(const byte* input, word32* inOutIdx,
    byte* serial, int* serialSz, word32 maxIdx)
{
    int result = 0;
    int ret;

    WOLFSSL_ENTER("wc_GetSerialNumber");

    if (serial == NULL || input == NULL || serialSz == NULL) {
        return BAD_FUNC_ARG;
    }

    /* First byte is ASN type */
    if ((*inOutIdx+1) > maxIdx) {
        WOLFSSL_MSG("Bad idx first");
        return BUFFER_E;
    }

    ret = GetASNInt(input, inOutIdx, serialSz, maxIdx);
    if (ret != 0)
        return ret;

    if (*serialSz > EXTERNAL_SERIAL_SIZE || *serialSz <= 0) {
        WOLFSSL_MSG("Serial size bad");
        WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
        return ASN_PARSE_E;
    }

    /* return serial */
    XMEMCPY(serial, &input[*inOutIdx], (size_t)*serialSz);
    *inOutIdx += (word32)*serialSz;

    return result;
}
#endif

#ifndef NO_CERTS

/* TODO: consider moving PEM code out to a different file. */

int AllocDer(DerBuffer** pDer, word32 length, int type, void* heap)
{
    int ret = BAD_FUNC_ARG;
    if (pDer) {
        int dynType = 0;
        DerBuffer* der;

        /* Determine dynamic type */
        switch (type) {
            case CA_TYPE:   dynType = DYNAMIC_TYPE_CA;   break;
            case CERT_TYPE: dynType = DYNAMIC_TYPE_CERT; break;
            case CRL_TYPE:  dynType = DYNAMIC_TYPE_CRL;  break;
            case DSA_TYPE:  dynType = DYNAMIC_TYPE_DSA;  break;
            case ECC_TYPE:  dynType = DYNAMIC_TYPE_ECC;  break;
            case RSA_TYPE:  dynType = DYNAMIC_TYPE_RSA;  break;
            default:        dynType = DYNAMIC_TYPE_KEY;  break;
        }

        /* Setup new buffer */
        *pDer = (DerBuffer*)XMALLOC(sizeof(DerBuffer) + length, heap, dynType);
        if (*pDer == NULL) {
            return MEMORY_E;
        }
        XMEMSET(*pDer, 0, sizeof(DerBuffer) + length);

        der = *pDer;
        der->type = type;
        der->dynType = dynType; /* Cache this for FreeDer */
        der->heap = heap;
        der->buffer = (byte*)der + sizeof(DerBuffer);
        der->length = length;
        ret = 0; /* Success */
    }
    return ret;
}

void FreeDer(DerBuffer** pDer)
{
    if (pDer && *pDer)
    {
        DerBuffer* der = (DerBuffer*)*pDer;

        /* ForceZero private keys */
        if (der->type == PRIVATEKEY_TYPE && der->buffer != NULL) {
            ForceZero(der->buffer, der->length);
        }
        der->buffer = NULL;
        der->length = 0;
        XFREE(der, der->heap, der->dynType);

        *pDer = NULL;
    }
}

int wc_AllocDer(DerBuffer** pDer, word32 length, int type, void* heap)
{
    return AllocDer(pDer, length, type, heap);
}
void wc_FreeDer(DerBuffer** pDer)
{
    FreeDer(pDer);
}


#if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)

/* Note: If items added make sure MAX_X509_HEADER_SZ is
    updated to reflect maximum length and pem_struct_min_sz
    to reflect minimum size */
wcchar BEGIN_CERT           = "-----BEGIN CERTIFICATE-----";
wcchar END_CERT             = "-----END CERTIFICATE-----";
#ifdef WOLFSSL_CERT_REQ
    wcchar BEGIN_CERT_REQ   = "-----BEGIN CERTIFICATE REQUEST-----";
    wcchar END_CERT_REQ     = "-----END CERTIFICATE REQUEST-----";
#endif
#ifndef NO_DH
    wcchar BEGIN_DH_PARAM   = "-----BEGIN DH PARAMETERS-----";
    wcchar END_DH_PARAM     = "-----END DH PARAMETERS-----";
    wcchar BEGIN_X942_PARAM = "-----BEGIN X9.42 DH PARAMETERS-----";
    wcchar END_X942_PARAM   = "-----END X9.42 DH PARAMETERS-----";
#endif
#ifndef NO_DSA
    wcchar BEGIN_DSA_PARAM  = "-----BEGIN DSA PARAMETERS-----";
    wcchar END_DSA_PARAM    = "-----END DSA PARAMETERS-----";
#endif
wcchar BEGIN_X509_CRL       = "-----BEGIN X509 CRL-----";
wcchar END_X509_CRL         = "-----END X509 CRL-----";
wcchar BEGIN_RSA_PRIV       = "-----BEGIN RSA PRIVATE KEY-----";
wcchar END_RSA_PRIV         = "-----END RSA PRIVATE KEY-----";
wcchar BEGIN_RSA_PUB        = "-----BEGIN RSA PUBLIC KEY-----";
wcchar END_RSA_PUB          = "-----END RSA PUBLIC KEY-----";
wcchar BEGIN_PRIV_KEY       = "-----BEGIN PRIVATE KEY-----";
wcchar END_PRIV_KEY         = "-----END PRIVATE KEY-----";
wcchar BEGIN_ENC_PRIV_KEY   = "-----BEGIN ENCRYPTED PRIVATE KEY-----";
wcchar END_ENC_PRIV_KEY     = "-----END ENCRYPTED PRIVATE KEY-----";
#ifdef HAVE_ECC
    wcchar BEGIN_EC_PRIV    = "-----BEGIN EC PRIVATE KEY-----";
    wcchar END_EC_PRIV      = "-----END EC PRIVATE KEY-----";
#ifdef OPENSSL_EXTRA
    wcchar BEGIN_EC_PARAM   = "-----BEGIN EC PARAMETERS-----";
    wcchar END_EC_PARAM     = "-----END EC PARAMETERS-----";
#endif
#endif
#if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
                                                                !defined(NO_DSA)
    wcchar BEGIN_DSA_PRIV   = "-----BEGIN DSA PRIVATE KEY-----";
    wcchar END_DSA_PRIV     = "-----END DSA PRIVATE KEY-----";
#endif
#ifdef OPENSSL_EXTRA
    const char BEGIN_PRIV_KEY_PREFIX[] = "-----BEGIN";
    const char PRIV_KEY_SUFFIX[] = "PRIVATE KEY-----";
    const char END_PRIV_KEY_PREFIX[]   = "-----END";
#endif
wcchar BEGIN_PUB_KEY        = "-----BEGIN PUBLIC KEY-----";
wcchar END_PUB_KEY          = "-----END PUBLIC KEY-----";
#if defined(HAVE_ED25519) || defined(HAVE_ED448)
    wcchar BEGIN_EDDSA_PRIV = "-----BEGIN EDDSA PRIVATE KEY-----";
    wcchar END_EDDSA_PRIV   = "-----END EDDSA PRIVATE KEY-----";
#endif
#if defined(HAVE_PQC)
#if defined(HAVE_FALCON)
    wcchar BEGIN_FALCON_LEVEL1_PRIV  = "-----BEGIN FALCON_LEVEL1 PRIVATE KEY-----";
    wcchar END_FALCON_LEVEL1_PRIV    = "-----END FALCON_LEVEL1 PRIVATE KEY-----";
    wcchar BEGIN_FALCON_LEVEL5_PRIV = "-----BEGIN FALCON_LEVEL5 PRIVATE KEY-----";
    wcchar END_FALCON_LEVEL5_PRIV   = "-----END FALCON_LEVEL5 PRIVATE KEY-----";
#endif /* HAVE_FALCON */
#if defined(HAVE_DILITHIUM)
    wcchar BEGIN_DILITHIUM_LEVEL2_PRIV = "-----BEGIN DILITHIUM_LEVEL2 PRIVATE KEY-----";
    wcchar END_DILITHIUM_LEVEL2_PRIV   = "-----END DILITHIUM_LEVEL2 PRIVATE KEY-----";
    wcchar BEGIN_DILITHIUM_LEVEL3_PRIV = "-----BEGIN DILITHIUM_LEVEL3 PRIVATE KEY-----";
    wcchar END_DILITHIUM_LEVEL3_PRIV   = "-----END DILITHIUM_LEVEL3 PRIVATE KEY-----";
    wcchar BEGIN_DILITHIUM_LEVEL5_PRIV = "-----BEGIN DILITHIUM_LEVEL5 PRIVATE KEY-----";
    wcchar END_DILITHIUM_LEVEL5_PRIV   = "-----END DILITHIUM_LEVEL5 PRIVATE KEY-----";
#endif /* HAVE_DILITHIUM */
#if defined(HAVE_SPHINCS)
    wcchar BEGIN_SPHINCS_FAST_LEVEL1_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL1 PRIVATE KEY-----";
    wcchar END_SPHINCS_FAST_LEVEL1_PRIV   = "-----END SPHINCS_FAST_LEVEL1 PRIVATE KEY-----";
    wcchar BEGIN_SPHINCS_FAST_LEVEL3_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL3 PRIVATE KEY-----";
    wcchar END_SPHINCS_FAST_LEVEL3_PRIV   = "-----END SPHINCS_FAST_LEVEL3 PRIVATE KEY-----";
    wcchar BEGIN_SPHINCS_FAST_LEVEL5_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL5 PRIVATE KEY-----";
    wcchar END_SPHINCS_FAST_LEVEL5_PRIV   = "-----END SPHINCS_FAST_LEVEL5 PRIVATE KEY-----";

    wcchar BEGIN_SPHINCS_SMALL_LEVEL1_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL1 PRIVATE KEY-----";
    wcchar END_SPHINCS_SMALL_LEVEL1_PRIV   = "-----END SPHINCS_SMALL_LEVEL1 PRIVATE KEY-----";
    wcchar BEGIN_SPHINCS_SMALL_LEVEL3_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL3 PRIVATE KEY-----";
    wcchar END_SPHINCS_SMALL_LEVEL3_PRIV   = "-----END SPHINCS_SMALL_LEVEL3 PRIVATE KEY-----";
    wcchar BEGIN_SPHINCS_SMALL_LEVEL5_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----";
    wcchar END_SPHINCS_SMALL_LEVEL5_PRIV   = "-----END SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----";
#endif /* HAVE_SPHINCS */
#endif /* HAVE_PQC */

const int pem_struct_min_sz = XSTR_SIZEOF("-----BEGIN X509 CRL-----"
                                             "-----END X509 CRL-----");

#ifdef WOLFSSL_PEM_TO_DER
static WC_INLINE const char* SkipEndOfLineChars(const char* line,
                                                const char* endOfLine)
{
    /* eat end of line characters */
    while (line < endOfLine &&
              (line[0] == '\r' || line[0] == '\n')) {
        line++;
    }
    return line;
}
#endif

int wc_PemGetHeaderFooter(int type, const char** header, const char** footer)
{
    int ret = BAD_FUNC_ARG;

    switch (type) {
        case CA_TYPE:       /* same as below */
        case TRUSTED_PEER_TYPE:
        case CERT_TYPE:
            if (header) *header = BEGIN_CERT;
            if (footer) *footer = END_CERT;
            ret = 0;
            break;

        case CRL_TYPE:
            if (header) *header = BEGIN_X509_CRL;
            if (footer) *footer = END_X509_CRL;
            ret = 0;
            break;
    #ifndef NO_DH
        case DH_PARAM_TYPE:
            if (header) *header = BEGIN_DH_PARAM;
            if (footer) *footer = END_DH_PARAM;
            ret = 0;
            break;
        case X942_PARAM_TYPE:
            if (header) *header = BEGIN_X942_PARAM;
            if (footer) *footer = END_X942_PARAM;
            ret = 0;
            break;
    #endif
    #ifndef NO_DSA
        case DSA_PARAM_TYPE:
            if (header) *header = BEGIN_DSA_PARAM;
            if (footer) *footer = END_DSA_PARAM;
            ret = 0;
            break;
    #endif
    #ifdef WOLFSSL_CERT_REQ
        case CERTREQ_TYPE:
            if (header) *header = BEGIN_CERT_REQ;
            if (footer) *footer = END_CERT_REQ;
            ret = 0;
            break;
    #endif
    #ifndef NO_DSA
        case DSA_TYPE:
        case DSA_PRIVATEKEY_TYPE:
            if (header) *header = BEGIN_DSA_PRIV;
            if (footer) *footer = END_DSA_PRIV;
            ret = 0;
            break;
    #endif
    #ifdef HAVE_ECC
        case ECC_TYPE:
        case ECC_PRIVATEKEY_TYPE:
            if (header) *header = BEGIN_EC_PRIV;
            if (footer) *footer = END_EC_PRIV;
            ret = 0;
            break;
    #ifdef OPENSSL_EXTRA
        case ECC_PARAM_TYPE:
            if (header) *header = BEGIN_EC_PARAM;
            if (footer) *footer = END_EC_PARAM;
            ret = 0;
            break;
    #endif
    #endif
        case RSA_TYPE:
        case PRIVATEKEY_TYPE:
            if (header) *header = BEGIN_RSA_PRIV;
            if (footer) *footer = END_RSA_PRIV;
            ret = 0;
            break;
    #ifdef HAVE_ED25519
        case ED25519_TYPE:
    #endif
    #ifdef HAVE_ED448
        case ED448_TYPE:
    #endif
    #if defined(HAVE_ED25519) || defined(HAVE_ED448)
        case EDDSA_PRIVATEKEY_TYPE:
            if (header) *header = BEGIN_EDDSA_PRIV;
            if (footer) *footer = END_EDDSA_PRIV;
            ret = 0;
            break;
    #endif
#ifdef HAVE_PQC
#ifdef HAVE_FALCON
        case FALCON_LEVEL1_TYPE:
            if (header) *header = BEGIN_FALCON_LEVEL1_PRIV;
            if (footer) *footer = END_FALCON_LEVEL1_PRIV;
            ret = 0;
            break;
        case FALCON_LEVEL5_TYPE:
            if (header) *header = BEGIN_FALCON_LEVEL5_PRIV;
            if (footer) *footer = END_FALCON_LEVEL5_PRIV;
            ret = 0;
            break;
#endif /* HAVE_FALCON */
#ifdef HAVE_DILITHIUM
        case DILITHIUM_LEVEL2_TYPE:
            if (header) *header = BEGIN_DILITHIUM_LEVEL2_PRIV;
            if (footer) *footer = END_DILITHIUM_LEVEL2_PRIV;
            ret = 0;
            break;
        case DILITHIUM_LEVEL3_TYPE:
            if (header) *header = BEGIN_DILITHIUM_LEVEL3_PRIV;
            if (footer) *footer = END_DILITHIUM_LEVEL3_PRIV;
            ret = 0;
            break;
        case DILITHIUM_LEVEL5_TYPE:
            if (header) *header = BEGIN_DILITHIUM_LEVEL5_PRIV;
            if (footer) *footer = END_DILITHIUM_LEVEL5_PRIV;
            ret = 0;
            break;
#endif /* HAVE_DILITHIUM */
#ifdef HAVE_SPHINCS
        case SPHINCS_FAST_LEVEL1_TYPE:
            if (header) *header = BEGIN_SPHINCS_FAST_LEVEL1_PRIV;
            if (footer) *footer = END_SPHINCS_FAST_LEVEL1_PRIV;
            ret = 0;
            break;
        case SPHINCS_FAST_LEVEL3_TYPE:
            if (header) *header = BEGIN_SPHINCS_FAST_LEVEL3_PRIV;
            if (footer) *footer = END_SPHINCS_FAST_LEVEL3_PRIV;
            ret = 0;
            break;
        case SPHINCS_FAST_LEVEL5_TYPE:
            if (header) *header = BEGIN_SPHINCS_FAST_LEVEL5_PRIV;
            if (footer) *footer = END_SPHINCS_FAST_LEVEL5_PRIV;
            ret = 0;
            break;
        case SPHINCS_SMALL_LEVEL1_TYPE:
            if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL1_PRIV;
            if (footer) *footer = END_SPHINCS_SMALL_LEVEL1_PRIV;
            ret = 0;
            break;
        case SPHINCS_SMALL_LEVEL3_TYPE:
            if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL3_PRIV;
            if (footer) *footer = END_SPHINCS_SMALL_LEVEL3_PRIV;
            ret = 0;
            break;
        case SPHINCS_SMALL_LEVEL5_TYPE:
            if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL5_PRIV;
            if (footer) *footer = END_SPHINCS_SMALL_LEVEL5_PRIV;
            ret = 0;
            break;
#endif /* HAVE_SPHINCS */
#endif /* HAVE_PQC */
        case PUBLICKEY_TYPE:
        case ECC_PUBLICKEY_TYPE:
            if (header) *header = BEGIN_PUB_KEY;
            if (footer) *footer = END_PUB_KEY;
            ret = 0;
            break;
        case RSA_PUBLICKEY_TYPE:
            if (header) *header = BEGIN_RSA_PUB;
            if (footer) *footer = END_RSA_PUB;
            ret = 0;
            break;
    #ifndef NO_DH
        case DH_PRIVATEKEY_TYPE:
    #endif
        case PKCS8_PRIVATEKEY_TYPE:
            if (header) *header = BEGIN_PRIV_KEY;
            if (footer) *footer = END_PRIV_KEY;
            ret = 0;
            break;
        case PKCS8_ENC_PRIVATEKEY_TYPE:
            if (header) *header = BEGIN_ENC_PRIV_KEY;
            if (footer) *footer = END_ENC_PRIV_KEY;
            ret = 0;
            break;
        default:
            break;
    }
    return ret;
}

#ifdef WOLFSSL_ENCRYPTED_KEYS

static wcchar kProcTypeHeader = "Proc-Type";
static wcchar kDecInfoHeader = "DEK-Info";

#ifdef WOLFSSL_PEM_TO_DER
#ifndef NO_DES3
    static wcchar kEncTypeDes = "DES-CBC";
    static wcchar kEncTypeDes3 = "DES-EDE3-CBC";
#endif
#if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_128)
    static wcchar kEncTypeAesCbc128 = "AES-128-CBC";
#endif
#if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_192)
    static wcchar kEncTypeAesCbc192 = "AES-192-CBC";
#endif
#if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
    static wcchar kEncTypeAesCbc256 = "AES-256-CBC";
#endif

int wc_EncryptedInfoGet(EncryptedInfo* info, const char* cipherInfo)
{
    int ret = 0;

    if (info == NULL || cipherInfo == NULL)
        return BAD_FUNC_ARG;

    /* determine cipher information */
#ifndef NO_DES3
    if (XSTRCMP(cipherInfo, kEncTypeDes) == 0) {
        info->cipherType = WC_CIPHER_DES;
        info->keySz = DES_KEY_SIZE;
/* DES_IV_SIZE is incorrectly 16 in FIPS v2. It should be 8, same as the
 * block size. */
#if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
        if (info->ivSz == 0) info->ivSz  = DES_BLOCK_SIZE;
#else
        if (info->ivSz == 0) info->ivSz  = DES_IV_SIZE;
#endif
    }
    else if (XSTRCMP(cipherInfo, kEncTypeDes3) == 0) {
        info->cipherType = WC_CIPHER_DES3;
        info->keySz = DES3_KEY_SIZE;
#if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
        if (info->ivSz == 0) info->ivSz  = DES_BLOCK_SIZE;
#else
        if (info->ivSz == 0) info->ivSz  = DES_IV_SIZE;
#endif
    }
    else
#endif /* !NO_DES3 */
#if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_128)
    if (XSTRCMP(cipherInfo, kEncTypeAesCbc128) == 0) {
        info->cipherType = WC_CIPHER_AES_CBC;
        info->keySz = AES_128_KEY_SIZE;
        if (info->ivSz == 0) info->ivSz  = AES_IV_SIZE;
    }
    else
#endif
#if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_192)
    if (XSTRCMP(cipherInfo, kEncTypeAesCbc192) == 0) {
        info->cipherType = WC_CIPHER_AES_CBC;
        info->keySz = AES_192_KEY_SIZE;
        if (info->ivSz == 0) info->ivSz  = AES_IV_SIZE;
    }
    else
#endif
#if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
    if (XSTRCMP(cipherInfo, kEncTypeAesCbc256) == 0) {
        info->cipherType = WC_CIPHER_AES_CBC;
        info->keySz = AES_256_KEY_SIZE;
        if (info->ivSz == 0) info->ivSz  = AES_IV_SIZE;
    }
    else
#endif
    {
        ret = NOT_COMPILED_IN;
    }
    return ret;
}

int wc_EncryptedInfoParse(EncryptedInfo* info, const char** pBuffer,
                          size_t bufSz)
{
    int         err = 0;
    const char* bufferStart;
    const char* bufferEnd;
    char*       line;

    if (info == NULL || pBuffer == NULL || bufSz == 0)
        return BAD_FUNC_ARG;

    bufferStart = *pBuffer;
    bufferEnd = bufferStart + bufSz;

    /* find encrypted info marker */
    line = XSTRNSTR(bufferStart, kProcTypeHeader,
                    min((word32)bufSz, PEM_LINE_LEN));
    if (line != NULL) {
        word32      lineSz;
        char*       finish;
        char*       start;
        word32      startSz;
        const char* newline = NULL;

        if (line >= bufferEnd) {
            return BUFFER_E;
        }

        lineSz = (word32)(bufferEnd - line);

        /* find DEC-Info marker */
        start = XSTRNSTR(line, kDecInfoHeader, min(lineSz, PEM_LINE_LEN));

        if (start == NULL)
            return BUFFER_E;

        /* skip dec-info and ": " */
        start += XSTRLEN(kDecInfoHeader);
        if (start >= bufferEnd)
            return BUFFER_E;

        if (start[0] == ':') {
            start++;
            if (start >= bufferEnd)
                return BUFFER_E;
        }
        if (start[0] == ' ')
            start++;

        startSz = (word32)(bufferEnd - start);
        finish = XSTRNSTR(start, ",", min(startSz, PEM_LINE_LEN));

        if ((start != NULL) && (finish != NULL) && (start < finish)) {
            word32 finishSz;

            if (finish >= bufferEnd) {
                return BUFFER_E;
            }

            finishSz = (word32)(bufferEnd - finish);
            newline = XSTRNSTR(finish, "\r", min(finishSz, PEM_LINE_LEN));

            /* get cipher name */
            if (NAME_SZ < (finish - start)) /* buffer size of info->name */
                return BUFFER_E;
            if (XMEMCPY(info->name, start, (size_t)(finish - start)) == NULL)
                return BUFFER_E;
            info->name[finish - start] = '\0'; /* null term */

            /* populate info */
            err = wc_EncryptedInfoGet(info, info->name);
            if (err != 0)
                return err;

            /* get IV */
            if (finishSz < info->ivSz + 1)
                return BUFFER_E;

            if (newline == NULL) {
                newline = XSTRNSTR(finish, "\n", min(finishSz,
                                                     PEM_LINE_LEN));
            }
            if ((newline != NULL) && (newline > finish)) {
                finish++;
                info->ivSz = (word32)(newline - finish);
                if (info->ivSz > IV_SZ)
                    return BUFFER_E;
                if (XMEMCPY(info->iv, finish, info->ivSz) == NULL)
                    return BUFFER_E;
                info->set = 1;
            }
            else
                return BUFFER_E;
        }
        else
            return BUFFER_E;

        /* eat end of line characters */
        newline = SkipEndOfLineChars(newline, bufferEnd);

        /* return new headerEnd */

        *pBuffer = newline;
    }

    return err;
}
#endif /* WOLFSSL_PEM_TO_DER */

#ifdef WOLFSSL_DER_TO_PEM
static int wc_EncryptedInfoAppend(char* dest, int destSz, char* cipherInfo)
{
    if (cipherInfo != NULL) {
        int cipherInfoStrLen = (int)XSTRLEN((char*)cipherInfo);

        if (cipherInfoStrLen > HEADER_ENCRYPTED_KEY_SIZE - (9+14+10+3))
            cipherInfoStrLen = HEADER_ENCRYPTED_KEY_SIZE - (9+14+10+3);

        if (destSz - (int)XSTRLEN(dest) >= cipherInfoStrLen + (9+14+8+2+2+1)) {
            /* strncat's src length needs to include the NULL */
            XSTRNCAT(dest, kProcTypeHeader, 10);
            XSTRNCAT(dest, ": 4,ENCRYPTED\n", 15);
            XSTRNCAT(dest, kDecInfoHeader, 9);
            XSTRNCAT(dest, ": ", 3);
            XSTRNCAT(dest, cipherInfo, (size_t)destSz - XSTRLEN(dest) - 1);
            XSTRNCAT(dest, "\n\n", 4);
        }
    }
    return 0;
}
#endif /* WOLFSSL_DER_TO_PEM */
#endif /* WOLFSSL_ENCRYPTED_KEYS */

#ifdef WOLFSSL_DER_TO_PEM

/* Used for compatibility API */
WOLFSSL_ABI
int wc_DerToPem(const byte* der, word32 derSz,
                byte* output, word32 outSz, int type)
{
    return wc_DerToPemEx(der, derSz, output, outSz, NULL, type);
}

/* convert der buffer to pem into output, can't do inplace, der and output
   need to be different */
int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz,
             byte *cipher_info, int type)
{
    const char* headerStr = NULL;
    const char* footerStr = NULL;
#ifdef WOLFSSL_SMALL_STACK
    char* header = NULL;
    char* footer = NULL;
#else
    char header[MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE];
    char footer[MAX_X509_HEADER_SZ];
#endif
    int headerLen = MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE;
    int footerLen = MAX_X509_HEADER_SZ;
    int i;
    int err;
    int outLen;   /* return length or error */

    (void)cipher_info;

    if (der == output)      /* no in place conversion */
        return BAD_FUNC_ARG;

    err = wc_PemGetHeaderFooter(type, &headerStr, &footerStr);
    if (err != 0)
        return err;

#ifdef WOLFSSL_SMALL_STACK
    header = (char*)XMALLOC(headerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    if (header == NULL)
        return MEMORY_E;

    footer = (char*)XMALLOC(footerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    if (footer == NULL) {
        XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        return MEMORY_E;
    }
#endif

    /* build header and footer based on type */
    XSTRNCPY(header, headerStr, (size_t)headerLen - 1);
    header[headerLen - 2] = 0;
    XSTRNCPY(footer, footerStr, (size_t)footerLen - 1);
    footer[footerLen - 2] = 0;

    /* add new line to end */
    XSTRNCAT(header, "\n", 2);
    XSTRNCAT(footer, "\n", 2);

#ifdef WOLFSSL_ENCRYPTED_KEYS
    err = wc_EncryptedInfoAppend(header, headerLen, (char*)cipher_info);
    if (err != 0) {
    #ifdef WOLFSSL_SMALL_STACK
        XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
    #endif
        return err;
    }
#endif

    headerLen = (int)XSTRLEN(header);
    footerLen = (int)XSTRLEN(footer);

    /* if null output and 0 size passed in then return size needed */
    if (!output && outSz == 0) {
#ifdef WOLFSSL_SMALL_STACK
        XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
        outLen = 0;
        if ((err = Base64_Encode(der, derSz, NULL, (word32*)&outLen))
                != LENGTH_ONLY_E) {
            WOLFSSL_ERROR_VERBOSE(err);
            return err;
        }
        return headerLen + footerLen + outLen;
    }

    if (!der || !output) {
#ifdef WOLFSSL_SMALL_STACK
        XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
        return BAD_FUNC_ARG;
    }

    /* don't even try if outSz too short */
    if (outSz < (word32)headerLen + (word32)footerLen + derSz) {
#ifdef WOLFSSL_SMALL_STACK
        XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
        return BAD_FUNC_ARG;
    }

    /* header */
    XMEMCPY(output, header, (size_t)headerLen);
    i = headerLen;

#ifdef WOLFSSL_SMALL_STACK
    XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif

    /* body */
    outLen = (int)outSz - (headerLen + footerLen);  /* input to Base64_Encode */
    if ( (err = Base64_Encode(der, derSz, output + i, (word32*)&outLen)) < 0) {
#ifdef WOLFSSL_SMALL_STACK
        XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
        WOLFSSL_ERROR_VERBOSE(err);
        return err;
    }
    i += outLen;

    /* footer */
    if ( (i + footerLen) > (int)outSz) {
#ifdef WOLFSSL_SMALL_STACK
        XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
        return BAD_FUNC_ARG;
    }
    XMEMCPY(output + i, footer, (size_t)footerLen);

#ifdef WOLFSSL_SMALL_STACK
    XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif

    return outLen + headerLen + footerLen;
}

#endif /* WOLFSSL_DER_TO_PEM */

#ifdef WOLFSSL_PEM_TO_DER

/* Remove PEM header/footer, convert to ASN1, store any encrypted data
   info->consumed tracks of PEM bytes consumed in case multiple parts */
int PemToDer(const unsigned char* buff, long longSz, int type,
              DerBuffer** pDer, void* heap, EncryptedInfo* info, int* keyFormat)
{
    const char* header      = NULL;
    const char* footer      = NULL;
    const char* headerEnd;
    const char* footerEnd;
    const char* consumedEnd;
    const char* bufferEnd   = (const char*)(buff + longSz);
    long        neededSz;
    int         ret         = 0;
    int         sz          = (int)longSz;
    int         encrypted_key = 0;
    DerBuffer*  der;
    word32      algId = 0;
    word32      idx;
#ifdef OPENSSL_EXTRA
    char        beginBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */
    char        endBuf[PEM_LINE_LEN + 1];   /* add 1 for null terminator */
#endif

    WOLFSSL_ENTER("PemToDer");

    /* get PEM header and footer based on type */
    ret = wc_PemGetHeaderFooter(type, &header, &footer);
    if (ret != 0)
        return ret;

    /* map header if not found for type */
    for (;;) {
        headerEnd = XSTRNSTR((char*)buff, header, (word32)sz);
        if (headerEnd) {
            break;
        }

        if (type == PRIVATEKEY_TYPE) {
            if (header == BEGIN_RSA_PRIV) {
                header = BEGIN_PRIV_KEY;
                footer = END_PRIV_KEY;
            }
            else if (header == BEGIN_PRIV_KEY) {
                header = BEGIN_ENC_PRIV_KEY;
                footer = END_ENC_PRIV_KEY;
            }
#ifdef HAVE_ECC
            else if (header == BEGIN_ENC_PRIV_KEY) {
                header = BEGIN_EC_PRIV;
                footer = END_EC_PRIV;
            }
            else if (header == BEGIN_EC_PRIV) {
                header = BEGIN_DSA_PRIV;
                footer = END_DSA_PRIV;
            }
#endif
#if defined(HAVE_ED25519) || defined(HAVE_ED448)
    #ifdef HAVE_ECC
            else if (header == BEGIN_DSA_PRIV) {
    #else
            else if (header == BEGIN_ENC_PRIV_KEY) {
    #endif
                header = BEGIN_EDDSA_PRIV;
                footer = END_EDDSA_PRIV;
            }
#endif
            else {
            #ifdef WOLF_PRIVATE_KEY_ID
                /* allow loading a public key for use with crypto or PK callbacks */
                type = PUBLICKEY_TYPE;
                header = BEGIN_PUB_KEY;
                footer = END_PUB_KEY;
            #else
                break;
            #endif
            }
        }
        else if (type == PUBLICKEY_TYPE) {
            if (header == BEGIN_PUB_KEY) {
                header = BEGIN_RSA_PUB;
                footer = END_RSA_PUB;
            }
            else {
                break;
            }
        }
#if defined(HAVE_ECC) && defined(OPENSSL_EXTRA)
        else if (type == ECC_PARAM_TYPE) {
            if (header == BEGIN_EC_PARAM) {
                header = BEGIN_EC_PARAM;
                footer = END_EC_PARAM;
            }
            else {
                break;
            }
        }
#endif
#ifdef HAVE_CRL
        else if ((type == CRL_TYPE) && (header != BEGIN_X509_CRL)) {
            header =  BEGIN_X509_CRL;
            footer = END_X509_CRL;
        }
#endif
        else {
            break;
        }
    }

    if (!headerEnd) {
#ifdef OPENSSL_EXTRA
        if (type == PRIVATEKEY_TYPE) {
            /* see if there is a -----BEGIN * PRIVATE KEY----- header */
            headerEnd = XSTRNSTR((char*)buff, PRIV_KEY_SUFFIX, sz);
            if (headerEnd) {
                const char* beginEnd;
                int endLen;

                beginEnd = headerEnd + XSTR_SIZEOF(PRIV_KEY_SUFFIX);
                if (beginEnd >= (char*)buff + sz) {
                    return BUFFER_E;
                }

                /* back up to BEGIN_PRIV_KEY_PREFIX */
                while (headerEnd > (char*)buff &&
                        XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
                                XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 &&
                        *headerEnd != '\n') {
                    headerEnd--;
                }
                if (headerEnd <= (char*)buff ||
                        XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
                        XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 ||
                        beginEnd - headerEnd > PEM_LINE_LEN) {
                    WOLFSSL_MSG("Couldn't find PEM header");
                    WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
                    return ASN_NO_PEM_HEADER;
                }

                /* headerEnd now points to beginning of header */
                XMEMCPY(beginBuf, headerEnd, beginEnd - headerEnd);
                beginBuf[beginEnd - headerEnd] = '\0';
                /* look for matching footer */
                footer = XSTRNSTR(beginEnd,
                                beginBuf + XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX),
                                (unsigned int)((char*)buff + sz - beginEnd));
                if (!footer) {
                    WOLFSSL_MSG("Couldn't find PEM footer");
                    WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
                    return ASN_NO_PEM_HEADER;
                }

                footer -= XSTR_SIZEOF(END_PRIV_KEY_PREFIX);
                if (footer > (char*)buff + sz - XSTR_SIZEOF(END_PRIV_KEY_PREFIX)
                        || XSTRNCMP(footer, END_PRIV_KEY_PREFIX,
                            XSTR_SIZEOF(END_PRIV_KEY_PREFIX)) != 0) {
                    WOLFSSL_MSG("Unexpected footer for PEM");
                    return BUFFER_E;
                }

                endLen = (unsigned int)(beginEnd - headerEnd -
                            (XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX) -
                                    XSTR_SIZEOF(END_PRIV_KEY_PREFIX)));
                XMEMCPY(endBuf, footer, endLen);
                endBuf[endLen] = '\0';

                header = beginBuf;
                footer = endBuf;
                headerEnd = beginEnd;
            }
        }

        if (!headerEnd) {
            WOLFSSL_MSG("Couldn't find PEM header");
            WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
            return ASN_NO_PEM_HEADER;
        }
#else
        WOLFSSL_MSG("Couldn't find PEM header");
        return ASN_NO_PEM_HEADER;
#endif
    } else {
        headerEnd += XSTRLEN(header);
    }

    /* eat end of line characters */
    headerEnd = SkipEndOfLineChars(headerEnd, bufferEnd);

    if (keyFormat) {
        /* keyFormat is Key_Sum enum */
        if (type == PRIVATEKEY_TYPE) {
        #ifndef NO_RSA
            if (header == BEGIN_RSA_PRIV)
                *keyFormat = RSAk;
        #endif
        #ifdef HAVE_ECC
            if (header == BEGIN_EC_PRIV)
                *keyFormat = ECDSAk;
        #endif
        #ifndef NO_DSA
            if (header == BEGIN_DSA_PRIV)
                *keyFormat = DSAk;
        #endif
        }
    #ifdef WOLF_PRIVATE_KEY_ID
        else if (type == PUBLICKEY_TYPE) {
        #ifndef NO_RSA
            if (header == BEGIN_RSA_PUB)
                *keyFormat = RSAk;
        #endif
        }
    #endif
    }

#ifdef WOLFSSL_ENCRYPTED_KEYS
    if (info) {
        ret = wc_EncryptedInfoParse(info, &headerEnd,
                                    (size_t)(bufferEnd - headerEnd));
        if (ret < 0)
            return ret;
        if (info->set)
            encrypted_key = 1;
    }
#endif /* WOLFSSL_ENCRYPTED_KEYS */

    /* find footer */
    footerEnd = XSTRNSTR(headerEnd, footer, (unsigned int)((char*)buff +
        sz - headerEnd));
    if (!footerEnd) {
        if (info)
            info->consumed = longSz; /* No more certs if no footer */
        return BUFFER_E;
    }

    consumedEnd = footerEnd + XSTRLEN(footer);

    if (consumedEnd < bufferEnd) { /* handle no end of line on last line */
        /* eat end of line characters */
        consumedEnd = SkipEndOfLineChars(consumedEnd, bufferEnd);
        /* skip possible null term */
        if (consumedEnd < bufferEnd && consumedEnd[0] == '\0')
            consumedEnd++;
    }

    if (info)
        info->consumed = (long)(consumedEnd - (const char*)buff);

    /* set up der buffer */
    neededSz = (long)(footerEnd - headerEnd);
    if (neededSz > sz || neededSz <= 0)
        return BUFFER_E;

    ret = AllocDer(pDer, (word32)neededSz, type, heap);
    if (ret < 0) {
        return ret;
    }
    der = *pDer;

    if (Base64_Decode((byte*)headerEnd, (word32)neededSz,
                      der->buffer, &der->length) < 0) {
        WOLFSSL_ERROR(BUFFER_E);
        return BUFFER_E;
    }

    if ((header == BEGIN_PRIV_KEY
#ifdef OPENSSL_EXTRA
         || header == beginBuf
#endif
#ifdef HAVE_ECC
         || header == BEGIN_EC_PRIV
#endif
        ) && !encrypted_key)
    {
        /* detect pkcs8 key and get alg type */
        /* keep PKCS8 header */
        idx = 0;
        ret = ToTraditionalInline_ex(der->buffer, &idx, der->length, &algId);
        if (ret > 0) {
            if (keyFormat)
                *keyFormat = (int)algId;
        }
        else {
            /* ignore failure here and assume key is not pkcs8 wrapped */
        }
        return 0;
    }

#ifdef WOLFSSL_ENCRYPTED_KEYS
    if (encrypted_key || header == BEGIN_ENC_PRIV_KEY) {
        int   passwordSz = NAME_SZ;
    #ifdef WOLFSSL_SMALL_STACK
        char* password = NULL;
    #else
        char  password[NAME_SZ];
    #endif

        if (!info || !info->passwd_cb) {
            WOLFSSL_MSG("No password callback set");
            WOLFSSL_ERROR_VERBOSE(NO_PASSWORD);
            return NO_PASSWORD;
        }

    #ifdef WOLFSSL_SMALL_STACK
        password = (char*)XMALLOC(passwordSz, heap, DYNAMIC_TYPE_STRING);
        if (password == NULL) {
            return MEMORY_E;
        }
    #endif

        /* get password */
        ret = info->passwd_cb(password, passwordSz, PEM_PASS_READ,
            info->passwd_userdata);
        if (ret >= 0) {
            passwordSz = ret;
        #ifdef WOLFSSL_CHECK_MEM_ZERO
            wc_MemZero_Add("PEM password", password, passwordSz);
        #endif

            /* convert and adjust length */
            if (header == BEGIN_ENC_PRIV_KEY) {
            #ifndef NO_PWDBASED
                ret = wc_DecryptPKCS8Key(der->buffer, der->length,
                    password, passwordSz);
                if (ret > 0) {
                    /* update length by decrypted content */
                    der->length = (word32)ret;
                    idx = 0;
                    /* detect pkcs8 key and get alg type */
                    /* keep PKCS8 header */
                    ret = ToTraditionalInline_ex(der->buffer, &idx, der->length,
                        &algId);
                    if (ret >= 0) {
                        if (keyFormat)
                            *keyFormat = (int)algId;
                        ret = 0;
                    }
                }
            #else
                WOLFSSL_ERROR_VERBOSE(NOT_COMPILED_IN);
                ret = NOT_COMPILED_IN;
            #endif
            }
            /* decrypt the key */
            else {
                if (passwordSz == 0) {
                    /* The key is encrypted but does not have a password */
                    WOLFSSL_MSG("No password for encrypted key");
                    WOLFSSL_ERROR_VERBOSE(NO_PASSWORD);
                    ret = NO_PASSWORD;
                }
                else {
                #if ((defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_DES3)) || \
                         (!defined(NO_AES) && defined(HAVE_AES_CBC) && \
                          defined(HAVE_AES_DECRYPT))) && \
                        !defined(NO_WOLFSSL_SKIP_TRAILING_PAD)
                    int     padVal = 0;
                #endif

                    ret = wc_BufferKeyDecrypt(info, der->buffer, der->length,
                        (byte*)password, passwordSz, WC_MD5);

#ifndef NO_WOLFSSL_SKIP_TRAILING_PAD
                #ifndef NO_DES3
                    if (info->cipherType == WC_CIPHER_DES3) {
                        /* Assuming there is padding:
                         *      (der->length > 0 && der->length > DES_BLOCK_SIZE &&
                         *       (der->length % DES_BLOCK_SIZE) != 0)
                         * and assuming the last value signifies the number of
                         * padded bytes IE if last value is 0x08 then there are
                         * 8 bytes of padding:
                         *      padVal = der->buffer[der->length-1];
                         * then strip this padding before proceeding:
                         * der->length -= padVal;
                         */
                        if (der->length > DES_BLOCK_SIZE &&
                            (der->length % DES_BLOCK_SIZE) != 0) {
                            padVal = der->buffer[der->length-1];
                            if (padVal < DES_BLOCK_SIZE) {
                                der->length -= (word32)padVal;
                            }
                        }
                    }
                #endif /* !NO_DES3 */
                #if !defined(NO_AES) && defined(HAVE_AES_CBC) && \
                    defined(HAVE_AES_DECRYPT)
                    if (info->cipherType == WC_CIPHER_AES_CBC) {
                        if (der->length > AES_BLOCK_SIZE) {
                            padVal = der->buffer[der->length-1];
                            if (padVal <= AES_BLOCK_SIZE) {
                                der->length -= (word32)padVal;
                            }
                        }
                    }
                #endif
#endif /* !NO_WOLFSSL_SKIP_TRAILING_PAD */
                }
            }
#ifdef OPENSSL_EXTRA
            if (ret) {
                PEMerr(0, PEM_R_BAD_DECRYPT);
            }
#endif
            ForceZero(password, (word32)passwordSz);
        }
#ifdef OPENSSL_EXTRA
        else {
            PEMerr(0, PEM_R_BAD_PASSWORD_READ);
        }
#endif

    #ifdef WOLFSSL_SMALL_STACK
        XFREE(password, heap, DYNAMIC_TYPE_STRING);
    #elif defined(WOLFSSL_CHECK_MEM_ZERO)
        wc_MemZero_Check(password, NAME_SZ);
    #endif
    }
#endif /* WOLFSSL_ENCRYPTED_KEYS */

    return ret;
}

int wc_PemToDer(const unsigned char* buff, long longSz, int type,
              DerBuffer** pDer, void* heap, EncryptedInfo* info, int* keyFormat)
{
    int ret = PemToDer(buff, longSz, type, pDer, heap, info, keyFormat);
#if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
    if (ret == 0 && type == PRIVATEKEY_TYPE) {
        DerBuffer* der = *pDer;
        /* if a PKCS8 key header exists remove it */
        ret = ToTraditional(der->buffer, der->length);
        if (ret > 0) {
            der->length = (word32)ret;
        }
        ret = 0; /* ignore error removing PKCS8 header */
    }
#endif
    return ret;
}

#ifdef WOLFSSL_ENCRYPTED_KEYS
/* our KeyPemToDer password callback, password in userData */
static int KeyPemToDerPassCb(char* passwd, int sz, int rw, void* userdata)
{
    (void)rw;

    if (userdata == NULL)
        return 0;

    XSTRNCPY(passwd, (char*)userdata, (size_t)sz);
    return (int)min((word32)sz, (word32)XSTRLEN((char*)userdata));
}
#endif

/* Return bytes written to buff or < 0 for error */
int wc_KeyPemToDer(const unsigned char* pem, int pemSz,
                        unsigned char* buff, int buffSz, const char* pass)
{
    int ret;
    DerBuffer* der = NULL;
#ifdef WOLFSSL_SMALL_STACK
    EncryptedInfo* info = NULL;
#else
    EncryptedInfo  info[1];
#endif

    WOLFSSL_ENTER("wc_KeyPemToDer");

    if (pem == NULL || (buff != NULL && buffSz <= 0)) {
        WOLFSSL_MSG("Bad pem der args");
        return BAD_FUNC_ARG;
    }

#ifdef WOLFSSL_SMALL_STACK
    info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
                                   DYNAMIC_TYPE_ENCRYPTEDINFO);
    if (info == NULL)
        return MEMORY_E;
#endif

    XMEMSET(info, 0, sizeof(EncryptedInfo));
#ifdef WOLFSSL_ENCRYPTED_KEYS
    info->passwd_cb = KeyPemToDerPassCb;
    info->passwd_userdata = (void*)pass;
#else
    (void)pass;
#endif

    ret = PemToDer(pem, pemSz, PRIVATEKEY_TYPE, &der, NULL, info, NULL);

#ifdef WOLFSSL_SMALL_STACK
    XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
#endif

    if (ret < 0 || der == NULL) {
        WOLFSSL_MSG("Bad Pem To Der");
    }
    else if (buff == NULL) {
        WOLFSSL_MSG("Return needed der buff length");
        ret = (int)der->length;
    }
    else if (der->length <= (word32)buffSz) {
        XMEMCPY(buff, der->buffer, der->length);
        ret = (int)der->length;
    }
    else {
        WOLFSSL_MSG("Bad der length");
        ret = BAD_FUNC_ARG;
    }

    FreeDer(&der);
    return ret;
}


/* Return bytes written to buff or < 0 for error */
int wc_CertPemToDer(const unsigned char* pem, int pemSz,
                        unsigned char* buff, int buffSz, int type)
{
    int ret;
    DerBuffer* der = NULL;

    WOLFSSL_ENTER("wc_CertPemToDer");

    if (pem == NULL || buff == NULL || buffSz <= 0) {
        WOLFSSL_MSG("Bad pem der args");
        return BAD_FUNC_ARG;
    }

    if (type != CERT_TYPE && type != CA_TYPE && type != CERTREQ_TYPE) {
        WOLFSSL_MSG("Bad cert type");
        return BAD_FUNC_ARG;
    }


    ret = PemToDer(pem, pemSz, type, &der, NULL, NULL, NULL);
    if (ret < 0 || der == NULL) {
        WOLFSSL_MSG("Bad Pem To Der");
    }
    else {
        if (der->length <= (word32)buffSz) {
            XMEMCPY(buff, der->buffer, der->length);
            ret = (int)der->length;
        }
        else {
            WOLFSSL_MSG("Bad der length");
            ret = BAD_FUNC_ARG;
        }
    }

    FreeDer(&der);
    return ret;
}

#endif /* WOLFSSL_PEM_TO_DER */
#endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */


#ifdef WOLFSSL_PEM_TO_DER
#if defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)
/* Return bytes written to buff, needed buff size if buff is NULL, or less than
   zero for error */
int wc_PubKeyPemToDer(const unsigned char* pem, int pemSz,
                           unsigned char* buff, int buffSz)
{
    int ret;
    DerBuffer* der = NULL;

    WOLFSSL_ENTER("wc_PubKeyPemToDer");

    if (pem == NULL || (buff != NULL && buffSz <= 0)) {
        WOLFSSL_MSG("Bad pem der args");
        return BAD_FUNC_ARG;
    }

    ret = PemToDer(pem, pemSz, PUBLICKEY_TYPE, &der, NULL, NULL, NULL);
    if (ret < 0 || der == NULL) {
        WOLFSSL_MSG("Bad Pem To Der");
    }
    else if (buff == NULL) {
        WOLFSSL_MSG("Return needed der buff length");
        ret = (int)der->length;
    }
    else if (der->length <= (word32)buffSz) {
        XMEMCPY(buff, der->buffer, der->length);
        ret = (int)der->length;
    }
    else {
        WOLFSSL_MSG("Bad der length");
        ret = BAD_FUNC_ARG;
    }

    FreeDer(&der);
    return ret;
}
#endif /* WOLFSSL_CERT_EXT || WOLFSSL_PUB_PEM_TO_DER */
#endif /* WOLFSSL_PEM_TO_DER */

#if !defined(NO_FILESYSTEM) && defined(WOLFSSL_PEM_TO_DER)

#ifdef WOLFSSL_CERT_GEN
int wc_PemCertToDer_ex(const char* fileName, DerBuffer** der)
{
#ifndef WOLFSSL_SMALL_STACK
    byte   staticBuffer[FILE_BUFFER_SIZE];
#endif
    byte*  fileBuf = NULL;
    int    ret     = 0;
    XFILE  file    = XBADFILE;
    int    dynamic = 0;
    long   sz      = 0;

    WOLFSSL_ENTER("wc_PemCertToDer");

    if (fileName == NULL) {
        ret = BAD_FUNC_ARG;
    }
    else {
        file = XFOPEN(fileName, "rb");
        if (file == XBADFILE) {
            ret = IO_FAILED_E;
        }
    }

    if (ret == 0) {
        if (XFSEEK(file, 0, XSEEK_END) != 0) {
            ret = IO_FAILED_E;
        }
    }
    if (ret == 0) {
        sz = XFTELL(file);
        if (sz <= 0) {
            ret = IO_FAILED_E;
        }
    }
    if (ret == 0) {
        if (XFSEEK(file, 0, XSEEK_SET) != 0) {
            ret = IO_FAILED_E;
        }
    }
    if (ret == 0) {
#ifndef WOLFSSL_SMALL_STACK
        if (sz <= (long)sizeof(staticBuffer))
            fileBuf = staticBuffer;
        else
#endif
        {
            fileBuf = (byte*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_FILE);
            if (fileBuf == NULL)
                ret = MEMORY_E;
            else
                dynamic = 1;
        }
    }
    if (ret == 0) {
        if ((size_t)XFREAD(fileBuf, 1, (size_t)sz, file) != (size_t)sz) {
            ret = IO_FAILED_E;
        }
        else {
            ret = PemToDer(fileBuf, sz, CA_TYPE, der,  0, NULL,NULL);
        }
    }

    if (file != XBADFILE)
        XFCLOSE(file);
    if (dynamic)
        XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE);

    return ret;
}
/* load pem cert from file into der buffer, return der size or error */
int wc_PemCertToDer(const char* fileName, unsigned char* derBuf, int derSz)
{
    int ret;
    DerBuffer* converted = NULL;
    ret = wc_PemCertToDer_ex(fileName, &converted);
    if (ret == 0) {
        if (converted->length < (word32)derSz) {
            XMEMCPY(derBuf, converted->buffer, converted->length);
            ret = (int)converted->length;
        }
        else
            ret = BUFFER_E;

        FreeDer(&converted);
    }
    return ret;
}
#endif /* WOLFSSL_CERT_GEN */

#if defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)
/* load pem public key from file into der buffer, return der size or error */
int wc_PemPubKeyToDer_ex(const char* fileName, DerBuffer** der)
{
#ifndef WOLFSSL_SMALL_STACK
    byte   staticBuffer[FILE_BUFFER_SIZE];
#endif
    byte*  fileBuf = NULL;
    int    dynamic = 0;
    int    ret     = 0;
    long   sz      = 0;
    XFILE  file    = XBADFILE;

    WOLFSSL_ENTER("wc_PemPubKeyToDer");

    if (fileName == NULL) {
        ret = BAD_FUNC_ARG;
    }
    else {
        file = XFOPEN(fileName, "rb");
        if (file == XBADFILE) {
            ret = IO_FAILED_E;
        }
    }

    if (ret == 0) {
        if (XFSEEK(file, 0, XSEEK_END) != 0) {
            ret = IO_FAILED_E;
        }
    }
    if (ret == 0) {
        sz = XFTELL(file);
        if (sz <= 0) {
            ret = IO_FAILED_E;
        }
    }
    if (ret == 0) {
        if (XFSEEK(file, 0, XSEEK_SET) != 0) {
            ret = IO_FAILED_E;
        }
    }
    if (ret == 0) {
#ifndef WOLFSSL_SMALL_STACK
        if (sz <= (long)sizeof(staticBuffer))
            fileBuf = staticBuffer;
        else
#endif
        {
            fileBuf = (byte*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_FILE);
            if (fileBuf == NULL)
                ret = MEMORY_E;
            else
                dynamic = 1;
        }
    }
    if (ret == 0) {
        if ((size_t)XFREAD(fileBuf, 1, (size_t)sz, file) != (size_t)sz) {
            ret = BUFFER_E;
        }
        else {
            ret = PemToDer(fileBuf, sz, PUBLICKEY_TYPE, der,
                           0, NULL, NULL);
        }
    }

    if (file != XBADFILE)
        XFCLOSE(file);
    if (dynamic)
        XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE);

    return ret;
}
/* load pem public key from file into der buffer, return der size or error */
int wc_PemPubKeyToDer(const char* fileName,
                           unsigned char* derBuf, int derSz)
{
    int ret;
    DerBuffer* converted = NULL;
    ret = wc_PemPubKeyToDer_ex(fileName, &converted);
    if (ret == 0) {
        if (converted->length < (word32)derSz) {
            XMEMCPY(derBuf, converted->buffer, converted->length);
            ret = (int)converted->length;
        }
        else
            ret = BUFFER_E;

        FreeDer(&converted);
    }
    return ret;
}
#endif /* WOLFSSL_CERT_EXT || WOLFSSL_PUB_PEM_TO_DER */

#endif /* !NO_FILESYSTEM && WOLFSSL_PEM_TO_DER */

/* Get public key in DER format from a populated DecodedCert struct.
 *
 * Users must call wc_InitDecodedCert() and wc_ParseCert() before calling
 * this API. wc_InitDecodedCert() accepts a DER/ASN.1 encoded certificate.
 * To convert a PEM cert to DER first use wc_CertPemToDer() before calling
 * wc_InitDecodedCert().
 *
 * cert   - populated DecodedCert struct holding X.509 certificate
 * derKey - output buffer to place DER/ASN.1 encoded public key
 * derKeySz [IN/OUT] - size of derKey buffer on input, size of public key
 *                     on return. If derKey is passed in as NULL, derKeySz
 *                     will be set to required buffer size for public key
 *                     and LENGTH_ONLY_E will be returned from function.
 * Returns 0 on success, or negative error code on failure. LENGTH_ONLY_E
 * if derKey is NULL and returning length only.
 */
int wc_GetPubKeyDerFromCert(struct DecodedCert* cert,
                            byte* derKey, word32* derKeySz)
{
    int ret = 0;

    /* derKey may be NULL to return length only */
    if (cert == NULL || derKeySz == NULL ||
        (derKey != NULL && *derKeySz == 0)) {
        return BAD_FUNC_ARG;
    }

    if (cert->publicKey == NULL) {
        WOLFSSL_MSG("DecodedCert does not contain public key\n");
        return BAD_FUNC_ARG;
    }

    /* if derKey is NULL, return required output buffer size in derKeySz */
    if (derKey == NULL) {
        *derKeySz = cert->pubKeySize;
        ret = LENGTH_ONLY_E;
    }

    if (ret == 0) {
        if (cert->pubKeySize > *derKeySz) {
            WOLFSSL_MSG("Output buffer not large enough for public key DER");
            ret = BAD_FUNC_ARG;
        }
        else {
            XMEMCPY(derKey, cert->publicKey, cert->pubKeySize);
            *derKeySz = cert->pubKeySize;
        }
    }

    return ret;
}

#ifdef WOLFSSL_FPKI
/* Search through list for first matching alt name of the same type
 * If 'current' is null then the search starts at the head of the list
 * otherwise the search starts from the node after 'current' alt name.
 * Returns 0 on success
 */
static DNS_entry* FindAltName(struct DecodedCert* cert, int nameType,
    DNS_entry* current)
{
    DNS_entry* entry;

    if (current == NULL) {
        entry = cert->altNames;
    }
    else {
        entry = current->next;
    }

    /* cycle through alt names to check for needed types */
    while (entry != NULL) {
        if (entry->type == nameType) {
            break;
        }
        entry = entry->next;
    }

    return entry;
}


/* returns 0 on success */
int wc_GetUUIDFromCert(struct DecodedCert* cert, byte* uuid, word32* uuidSz)
{
    int ret = ALT_NAME_E;
    DNS_entry* id = NULL;

    do {
        id = FindAltName(cert, ASN_URI_TYPE, id);
        if (id != NULL) {
            /* check if URI string matches expected format for UUID */
            if (id->len != DEFAULT_UUID_SZ) {
                continue; /* size not right not a UUID URI */
            }

            if (XMEMCMP(id->name, "urn:uuid:", 9) != 0) {
                continue; /* beginning text not right for a UUID URI */
            }

            if (uuid == NULL) {
                *uuidSz = id->len;
                return LENGTH_ONLY_E;
            }

            if ((int)*uuidSz < id->len) {
                return BUFFER_E;
            }

            XMEMCPY(uuid, id->name, id->len);
            ret = 0; /* success */
            break;
        }
    } while (id != NULL);

    return ret;
}


/* reutrns 0 on success */
int wc_GetFASCNFromCert(struct DecodedCert* cert, byte* fascn, word32* fascnSz)
{
    int ret = ALT_NAME_E;
    DNS_entry* id = NULL;

    do {
        id = FindAltName(cert, ASN_OTHER_TYPE, id);
        if (id != NULL && id->oidSum == FASCN_OID) {
            if (fascn == NULL) {
                *fascnSz = id->len;
                return LENGTH_ONLY_E;
            }

            if ((int)*fascnSz < id->len) {
                return BUFFER_E;
            }

            XMEMCPY(fascn, id->name, id->len);
            ret = 0; /* success */
        }
    } while (id != NULL);

    return ret;
}
#endif /* WOLFSSL_FPKI */

#if !defined(NO_RSA) && (defined(WOLFSSL_CERT_GEN) || \
    defined(WOLFSSL_KCAPI_RSA) || \
    ((defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)) && !defined(HAVE_USER_RSA)))
/* USER RSA ifdef portions used instead of refactor in consideration for
   possible fips build */
/* Encode a public RSA key to output.
 *
 * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
 * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
 *
 * Encoded data can either be SubjectPublicKeyInfo (with header) or just the key
 * (RSAPublicKey).
 *
 * @param [out] output       Buffer to put encoded data in.
 * @param [in]  key          RSA key object.
 * @param [in]  outLen       Size of the output buffer in bytes.
 * @param [in]  with_header  Whether to include SubjectPublicKeyInfo around key.
 * @return  Size of encoded data in bytes on success.
 * @return  BAD_FUNC_ARG when output or key is NULL, or outLen is less than
 *          minimum length (5 bytes).
 * @return  MEMORY_E when dynamic memory allocation failed.
 */
static int SetRsaPublicKey(byte* output, RsaKey* key, int outLen,
                           int with_header)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int  nSz, eSz;
    word32 seqSz, algoSz = 0, headSz = 0, bitStringSz = 0, idx;
    byte seq[MAX_SEQ_SZ];
    byte headSeq[MAX_SEQ_SZ];
    byte bitString[1 + MAX_LENGTH_SZ + 1];
    byte algo[MAX_ALGO_SZ]; /* 20 bytes */

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

#ifdef HAVE_USER_RSA
    nSz = SetASNIntRSA(key->n, NULL);
#else
    nSz = SetASNIntMP(&key->n, MAX_RSA_INT_SZ, NULL);
#endif
    if (nSz < 0)
        return nSz;

#ifdef HAVE_USER_RSA
    eSz = SetASNIntRSA(key->e, NULL);
#else
    eSz = SetASNIntMP(&key->e, MAX_RSA_INT_SZ, NULL);
#endif
    if (eSz < 0)
        return eSz;
    seqSz = SetSequence((word32)(nSz + eSz), seq);

    /* headers */
    if (with_header) {
        algoSz = SetAlgoID(RSAk, algo, oidKeyType, 0);
        bitStringSz = SetBitString(seqSz + (word32)(nSz + eSz), 0, bitString);
        headSz = SetSequence((word32)(nSz + eSz) + seqSz + bitStringSz + algoSz,
                             headSeq);
    }

    /* if getting length only */
    if (output == NULL) {
        return (int)(headSz + algoSz + bitStringSz + seqSz) + nSz + eSz;
    }

    /* check output size */
    if (((int)(headSz + algoSz + bitStringSz + seqSz) + nSz + eSz) > outLen) {
        return BUFFER_E;
    }

    /* write output */
    idx = 0;
    if (with_header) {
        /* header size */
        XMEMCPY(output + idx, headSeq, headSz);
        idx += headSz;
        /* algo */
        XMEMCPY(output + idx, algo, algoSz);
        idx += algoSz;
        /* bit string */
        XMEMCPY(output + idx, bitString, bitStringSz);
        idx += bitStringSz;
    }

    /* seq */
    XMEMCPY(output + idx, seq, seqSz);
    idx += seqSz;
    /* n */
#ifdef HAVE_USER_RSA
    nSz = SetASNIntRSA(key->n, output + idx);
#else
    nSz = SetASNIntMP(&key->n, nSz, output + idx);
#endif
    idx += (word32)nSz;
    /* e */
#ifdef HAVE_USER_RSA
    eSz = SetASNIntRSA(key->e, output + idx);
#else
    eSz = SetASNIntMP(&key->e, eSz, output + idx);
#endif
    idx += (word32)eSz;

    return (int)idx;
#else
    DECL_ASNSETDATA(dataASN, rsaPublicKeyASN_Length);
    int sz = 0;
    int ret = 0;
    int o = 0;

    /* Check parameter validity. */
    if ((key == NULL) || ((output != NULL) && (outLen < MAX_SEQ_SZ))) {
        ret = BAD_FUNC_ARG;
    }

    CALLOC_ASNSETDATA(dataASN, rsaPublicKeyASN_Length, ret, key->heap);

    if (ret == 0) {
        if (!with_header) {
            /* Start encoding with items after header. */
            o = RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ;
        }
        /* Set OID for RSA key. */
        SetASN_OID(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID], RSAk, oidKeyType);
    #ifdef WC_RSA_PSS
        dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ].noOut = 1;
    #endif
        /* Set public key mp_ints. */
    #ifdef HAVE_USER_RSA
        SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N], key->n);
        SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E], key->e);
    #else
        SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N], &key->n);
        SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E], &key->e);
    #endif
        /* Calculate size of RSA public key. */
        ret = SizeASN_Items(rsaPublicKeyASN + o, dataASN + o,
                            (int)rsaPublicKeyASN_Length - o, &sz);
    }
    /* Check output buffer is big enough for encoding. */
    if ((ret == 0) && (output != NULL) && (sz > outLen)) {
        ret = BUFFER_E;
    }
    if ((ret == 0) && (output != NULL)) {
        /* Encode RSA public key. */
        SetASN_Items(rsaPublicKeyASN + o, dataASN + o,
                     (int)rsaPublicKeyASN_Length - o, output);
    }
    if (ret == 0) {
        /* Return size of encoding. */
        ret = sz;
    }

    FREE_ASNSETDATA(dataASN, key->heap);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

/* Calculate size of encoded public RSA key in bytes.
 *
 * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
 * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
 *
 * Encoded data can either be SubjectPublicKeyInfo (with header) or just the key
 * (RSAPublicKey).
 *
 * @param [in]  key          RSA key object.
 * @param [in]  with_header  Whether to include SubjectPublicKeyInfo around key.
 * @return  Size of encoded data in bytes on success.
 * @return  BAD_FUNC_ARG when key is NULL.
 * @return  MEMORY_E when dynamic memory allocation failed.
 */
int wc_RsaPublicKeyDerSize(RsaKey* key, int with_header)
{
    return SetRsaPublicKey(NULL, key, 0, with_header);
}

/* Encode public RSA key in DER format.
 *
 * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
 * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
 *
 * @param [in]  key     RSA key object.
 * @param [out] output  Buffer to put encoded data in.
 * @param [in]  inLen   Size of buffer in bytes.
 * @return  Size of encoded data in bytes on success.
 * @return  BAD_FUNC_ARG when key or output is NULL.
 * @return  MEMORY_E when dynamic memory allocation failed.
 */
int wc_RsaKeyToPublicDer(RsaKey* key, byte* output, word32 inLen)
{
    return SetRsaPublicKey(output, key, (int)inLen, 1);
}

/* Returns public DER version of the RSA key. If with_header is 0 then only a
 * seq + n + e is returned in ASN.1 DER format */
int wc_RsaKeyToPublicDer_ex(RsaKey* key, byte* output, word32 inLen,
    int with_header)
{
    return SetRsaPublicKey(output, key, (int)inLen, with_header);
}

#endif /* !NO_RSA && (WOLFSSL_CERT_GEN || WOLFSSL_KCAPI_RSA ||
            ((OPENSSL_EXTRA || WOLFSSL_KEY_GEN) && !HAVE_USER_RSA))) */

#if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
     defined(WOLFSSL_KCAPI_RSA) || defined(WOLFSSL_SE050)) && \
     !defined(NO_RSA) && !defined(HAVE_USER_RSA)

/* Encode private RSA key in DER format.
 *
 * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
 *
 * @param [in]  key     RSA key object.
 * @param [out] output  Buffer to put encoded data in.
 * @param [in]  inLen   Size of buffer in bytes.
 * @return  Size of encoded data in bytes on success.
 * @return  BAD_FUNC_ARG when key is NULL or not a private key.
 * @return  MEMORY_E when dynamic memory allocation failed.
 */
int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int ret = 0, i;
    word32 seqSz = 0, verSz = 0, intTotalLen = 0, outLen = 0;
    word32 sizes[RSA_INTS];
    byte  seq[MAX_SEQ_SZ];
    byte  ver[MAX_VERSION_SZ];
    byte* tmps[RSA_INTS];

    if (key == NULL)
        return BAD_FUNC_ARG;

    if (key->type != RSA_PRIVATE)
        return BAD_FUNC_ARG;

    for (i = 0; i < RSA_INTS; i++)
        tmps[i] = NULL;

    /* write all big ints from key to DER tmps */
    for (i = 0; i < RSA_INTS; i++) {
        mp_int* keyInt = GetRsaInt(key, i);
        int mpSz;
        word32 rawLen;

        ret = mp_unsigned_bin_size(keyInt);
        if (ret < 0)
            return ret;
        rawLen = (word32)ret + 1;
        ret = 0;
        if (output != NULL) {
            tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
                                 DYNAMIC_TYPE_RSA);
            if (tmps[i] == NULL) {
                ret = MEMORY_E;
                break;
            }
        }

        mpSz = SetASNIntMP(keyInt, MAX_RSA_INT_SZ, tmps[i]);
        if (mpSz < 0) {
            ret = mpSz;
            break;
        }
        sizes[i] = (word32)mpSz;
        intTotalLen += (word32)mpSz;
    }

    if (ret == 0) {
        /* make headers */
        ret = SetMyVersion(0, ver, FALSE);
    }

    if (ret >= 0) {
        verSz = (word32)ret;
        ret = 0;
        seqSz = SetSequence(verSz + intTotalLen, seq);
        outLen = seqSz + verSz + intTotalLen;
        if (output != NULL && outLen > inLen)
            ret = BUFFER_E;
    }
    if (ret == 0 && output != NULL) {
        word32 j;

        /* write to output */
        XMEMCPY(output, seq, seqSz);
        j = seqSz;
        XMEMCPY(output + j, ver, verSz);
        j += verSz;

        for (i = 0; i < RSA_INTS; i++) {
            XMEMCPY(output + j, tmps[i], sizes[i]);
            j += sizes[i];
        }
    }

    for (i = 0; i < RSA_INTS; i++) {
        if (tmps[i])
            XFREE(tmps[i], key->heap, DYNAMIC_TYPE_RSA);
    }

    if (ret == 0)
        ret = (int)outLen;
    return ret;
#else
    DECL_ASNSETDATA(dataASN, rsaKeyASN_Length);
    int i;
    int sz = 0;
    int ret = 0;

    if ((key == NULL) || (key->type != RSA_PRIVATE)) {
        ret = BAD_FUNC_ARG;
    }

    CALLOC_ASNSETDATA(dataASN, rsaKeyASN_Length, ret, key->heap);

    if (ret == 0) {
        /* Set the version. */
        SetASN_Int8Bit(&dataASN[RSAKEYASN_IDX_VER], 0);
        /* Set all the mp_ints in private key. */
        for (i = 0; i < RSA_INTS; i++) {
            SetASN_MP(&dataASN[(byte)RSAKEYASN_IDX_N + i], GetRsaInt(key, i));
        }

        /* Calculate size of RSA private key encoding. */
        ret = SizeASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length, &sz);
    }
    /* Check output buffer has enough space for encoding. */
    if ((ret == 0) && (output != NULL) && (sz > (int)inLen)) {
        ret = BAD_FUNC_ARG;
    }
    if ((ret == 0) && (output != NULL)) {
        /* Encode RSA private key. */
        SetASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length, output);
    }

    if (ret == 0) {
        /* Return size of encoding. */
        ret = sz;
    }

    FREE_ASNSETDATA(dataASN, key->heap);
    return ret;
#endif
}

#endif /* (WOLFSSL_KEY_GEN || OPENSSL_EXTRA) && !NO_RSA && !HAVE_USER_RSA */


#ifdef WOLFSSL_CERT_GEN

/* Initialize and Set Certificate defaults:
   version    = 3 (0x2)
   serial     = 0
   sigType    = SHA_WITH_RSA
   issuer     = blank
   daysValid  = 500
   selfSigned = 1 (true) use subject as issuer
   subject    = blank
*/
int wc_InitCert_ex(Cert* cert, void* heap, int devId)
{
#ifdef WOLFSSL_MULTI_ATTRIB
    int i = 0;
#endif
    if (cert == NULL) {
        return BAD_FUNC_ARG;
    }

    XMEMSET(cert, 0, sizeof(Cert));

    cert->version    = 2;   /* version 3 is hex 2 */
#ifndef NO_SHA
    cert->sigType    = CTC_SHAwRSA;
#elif !defined(NO_SHA256)
    cert->sigType    = CTC_SHA256wRSA;
#else
    cert->sigType    = 0;
#endif
    cert->daysValid  = 500;
    cert->selfSigned = 1;
    cert->keyType    = RSA_KEY;

    cert->issuer.countryEnc = CTC_PRINTABLE;
    cert->issuer.stateEnc = CTC_UTF8;
    cert->issuer.streetEnc = CTC_UTF8;
    cert->issuer.localityEnc = CTC_UTF8;
    cert->issuer.surEnc = CTC_UTF8;
#ifdef WOLFSSL_CERT_NAME_ALL
    cert->issuer.givenNameEnc = CTC_UTF8;
    cert->issuer.initialsEnc = CTC_UTF8;
    cert->issuer.dnQualifierEnc = CTC_UTF8;
    cert->issuer.dnNameEnc = CTC_UTF8;
#endif
    cert->issuer.orgEnc = CTC_UTF8;
    cert->issuer.unitEnc = CTC_UTF8;
    cert->issuer.commonNameEnc = CTC_UTF8;
    cert->issuer.serialDevEnc = CTC_PRINTABLE;
    cert->issuer.userIdEnc = CTC_UTF8;
    cert->issuer.postalCodeEnc = CTC_UTF8;
#ifdef WOLFSSL_CERT_EXT
    cert->issuer.busCatEnc = CTC_UTF8;
    cert->issuer.joiCEnc = CTC_UTF8;
    cert->issuer.joiStEnc = CTC_UTF8;
#endif

    cert->subject.countryEnc = CTC_PRINTABLE;
    cert->subject.stateEnc = CTC_UTF8;
    cert->subject.streetEnc = CTC_UTF8;
    cert->subject.localityEnc = CTC_UTF8;
    cert->subject.surEnc = CTC_UTF8;
#ifdef WOLFSSL_CERT_NAME_ALL
    cert->subject.givenNameEnc = CTC_UTF8;
    cert->subject.initialsEnc = CTC_UTF8;
    cert->subject.dnQualifierEnc = CTC_UTF8;
    cert->subject.dnNameEnc = CTC_UTF8;
#endif
    cert->subject.orgEnc = CTC_UTF8;
    cert->subject.unitEnc = CTC_UTF8;
    cert->subject.commonNameEnc = CTC_UTF8;
    cert->subject.serialDevEnc = CTC_PRINTABLE;
    cert->subject.userIdEnc = CTC_UTF8;
    cert->subject.postalCodeEnc = CTC_UTF8;
#ifdef WOLFSSL_CERT_EXT
    cert->subject.busCatEnc = CTC_UTF8;
    cert->subject.joiCEnc = CTC_UTF8;
    cert->subject.joiStEnc = CTC_UTF8;
#endif

#ifdef WOLFSSL_MULTI_ATTRIB
    for (i = 0; i < CTC_MAX_ATTRIB; i++) {
        cert->issuer.name[i].type   = CTC_UTF8;
        cert->subject.name[i].type  = CTC_UTF8;
    }
#endif /* WOLFSSL_MULTI_ATTRIB */

    cert->heap = heap;
    (void)devId; /* future */

    return 0;
}

WOLFSSL_ABI
int wc_InitCert(Cert* cert)
{
    return wc_InitCert_ex(cert, NULL, INVALID_DEVID);
}

WOLFSSL_ABI
Cert* wc_CertNew(void* heap)
{
    Cert* certNew;

    certNew = (Cert*)XMALLOC(sizeof(Cert), heap, DYNAMIC_TYPE_CERT);

    if (certNew) {
        if (wc_InitCert_ex(certNew, heap, INVALID_DEVID) != 0) {
            XFREE(certNew, heap, DYNAMIC_TYPE_CERT);
            certNew = NULL;
        }
    }

    return certNew;
}

WOLFSSL_ABI
void  wc_CertFree(Cert* cert)
{
    if (cert) {
         void* heap = cert->heap;

         ForceZero(cert, sizeof(Cert));
         XFREE(cert, heap, DYNAMIC_TYPE_CERT);
         (void)heap;
     }
}

/* DER encoded x509 Certificate */
typedef struct DerCert {
    byte size[MAX_LENGTH_SZ];          /* length encoded */
    byte version[MAX_VERSION_SZ];      /* version encoded */
    byte serial[(int)CTC_SERIAL_SIZE + (int)MAX_LENGTH_SZ]; /* serial number encoded */
    byte sigAlgo[MAX_ALGO_SZ];         /* signature algo encoded */
    byte issuer[WC_ASN_NAME_MAX];         /* issuer  encoded */
    byte subject[WC_ASN_NAME_MAX];        /* subject encoded */
    byte validity[MAX_DATE_SIZE*2 + MAX_SEQ_SZ*2];  /* before and after dates */
    byte publicKey[MAX_PUBLIC_KEY_SZ]; /* rsa public key encoded */
    byte ca[MAX_CA_SZ];                /* basic constraint CA true size */
    byte extensions[MAX_EXTENSIONS_SZ]; /* all extensions */
#ifdef WOLFSSL_CERT_EXT
    byte skid[MAX_KID_SZ];             /* Subject Key Identifier extension */
    byte akid[MAX_KID_SZ
#ifdef WOLFSSL_AKID_NAME
              + sizeof(CertName) + CTC_SERIAL_SIZE
#endif
              ]; /* Authority Key Identifier extension */
    byte keyUsage[MAX_KEYUSAGE_SZ];    /* Key Usage extension */
    byte extKeyUsage[MAX_EXTKEYUSAGE_SZ]; /* Extended Key Usage extension */
#ifndef IGNORE_NETSCAPE_CERT_TYPE
    byte nsCertType[MAX_NSCERTTYPE_SZ]; /* Extended Key Usage extension */
#endif
    byte certPolicies[MAX_CERTPOL_NB*MAX_CERTPOL_SZ]; /* Certificate Policies */
    byte crlInfo[CTC_MAX_CRLINFO_SZ];  /* CRL Distribution Points */
#endif
#ifdef WOLFSSL_CERT_REQ
    byte attrib[MAX_ATTRIB_SZ];        /* Cert req attributes encoded */
    #ifdef WOLFSSL_CUSTOM_OID
    byte extCustom[MAX_ATTRIB_SZ];     /* Encoded user oid and value */
    #endif
#endif
#ifdef WOLFSSL_ALT_NAMES
    byte altNames[CTC_MAX_ALT_SIZE];   /* Alternative Names encoded */
#endif
    int  sizeSz;                       /* encoded size length */
    int  versionSz;                    /* encoded version length */
    int  serialSz;                     /* encoded serial length */
    int  sigAlgoSz;                    /* encoded sig algo length */
    int  issuerSz;                     /* encoded issuer length */
    int  subjectSz;                    /* encoded subject length */
    int  validitySz;                   /* encoded validity length */
    int  publicKeySz;                  /* encoded public key length */
    int  caSz;                         /* encoded CA extension length */
#ifdef WOLFSSL_CERT_EXT
    int  skidSz;                       /* encoded SKID extension length */
    int  akidSz;                       /* encoded SKID extension length */
    int  keyUsageSz;                   /* encoded KeyUsage extension length */
    int  extKeyUsageSz;                /* encoded ExtendedKeyUsage extension length */
#ifndef IGNORE_NETSCAPE_CERT_TYPE
    int  nsCertTypeSz;                 /* encoded Netscape Certifcate Type
                                        * extension length */
#endif
    int  certPoliciesSz;               /* encoded CertPolicies extension length*/
    int  crlInfoSz;                    /* encoded CRL Dist Points length */
#endif
#ifdef WOLFSSL_ALT_NAMES
    int  altNamesSz;                   /* encoded AltNames extension length */
#endif
    int  extensionsSz;                 /* encoded extensions total length */
    int  total;                        /* total encoded lengths */
#ifdef WOLFSSL_CERT_REQ
    int  attribSz;
    #ifdef WOLFSSL_CUSTOM_OID
    int  extCustomSz;
    #endif
#endif
} DerCert;


#ifdef WOLFSSL_CERT_REQ
#ifndef WOLFSSL_ASN_TEMPLATE

/* Write a set header to output */
static word32 SetPrintableString(word32 len, byte* output)
{
    output[0] = ASN_PRINTABLE_STRING;
    return SetLength(len, output + 1) + 1;
}

static word32 SetUTF8String(word32 len, byte* output)
{
    output[0] = ASN_UTF8STRING;
    return SetLength(len, output + 1) + 1;
}

#endif
#endif /* WOLFSSL_CERT_REQ */


#ifndef WOLFSSL_CERT_GEN_CACHE
/* wc_SetCert_Free is only public when WOLFSSL_CERT_GEN_CACHE is not defined */
static
#endif
WOLFSSL_ABI
void wc_SetCert_Free(Cert* cert)
{
    if (cert != NULL) {
        cert->der = NULL;
        if (cert->decodedCert) {
            FreeDecodedCert((DecodedCert*)cert->decodedCert);

            XFREE(cert->decodedCert, cert->heap, DYNAMIC_TYPE_DCERT);
            cert->decodedCert = NULL;
        }
    }
}

static int wc_SetCert_LoadDer(Cert* cert, const byte* der, word32 derSz,
    int devId)
{
    int ret;

    if (cert == NULL) {
        ret = BAD_FUNC_ARG;
    }
    else {
        /* Allocate DecodedCert struct and Zero */
        cert->decodedCert = (void*)XMALLOC(sizeof(DecodedCert), cert->heap,
            DYNAMIC_TYPE_DCERT);

        if (cert->decodedCert == NULL) {
            ret = MEMORY_E;
        }
        else {
            XMEMSET(cert->decodedCert, 0, sizeof(DecodedCert));

            InitDecodedCert_ex((DecodedCert*)cert->decodedCert, der, derSz,
                    cert->heap, devId);
            ret = ParseCertRelative((DecodedCert*)cert->decodedCert,
                    CERT_TYPE, 0, NULL);
            if (ret >= 0) {
                cert->der = (byte*)der;
            }
            else {
                wc_SetCert_Free(cert);
            }
        }
    }

    return ret;
}

#endif /* WOLFSSL_CERT_GEN */

#ifdef HAVE_ECC
#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for ECC public key (SubjectPublicKeyInfo).
 * RFC 5480, 2 - Subject Public Key Information Fields
 *           2.1.1 - Unrestricted Algorithm Identifier and Parameters
 * X9.62 ECC point format.
 * See ASN.1 template 'eccSpecifiedASN' for specifiedCurve.
 */
static const ASNItem eccPublicKeyASN[] = {
/* SEQ            */ { 0, ASN_SEQUENCE, 1, 1, 0 },
                                             /* AlgorithmIdentifier */
/* ALGOID_SEQ     */     { 1, ASN_SEQUENCE, 1, 1, 0 },
                                                 /* algorithm */
/* ALGOID_OID     */         { 2, ASN_OBJECT_ID, 0, 0, 0 },
                                                 /* namedCurve */
/* ALGOID_CURVEID */         { 2, ASN_OBJECT_ID, 0, 0, 2 },
                                                 /* specifiedCurve - explicit parameters */
/* ALGOID_PARAMS  */         { 2, ASN_SEQUENCE, 1, 0, 2 },
                                             /* Public Key */
/* PUBKEY         */     { 1, ASN_BIT_STRING, 0, 0, 0 },
};
enum {
    ECCPUBLICKEYASN_IDX_SEQ = 0,
    ECCPUBLICKEYASN_IDX_ALGOID_SEQ,
    ECCPUBLICKEYASN_IDX_ALGOID_OID,
    ECCPUBLICKEYASN_IDX_ALGOID_CURVEID,
    ECCPUBLICKEYASN_IDX_ALGOID_PARAMS,
    ECCPUBLICKEYASN_IDX_PUBKEY
};

/* Number of items in ASN.1 template for ECC public key. */
#define eccPublicKeyASN_Length (sizeof(eccPublicKeyASN) / sizeof(ASNItem))
#endif /* WOLFSSL_ASN_TEMPLATE */
#endif /* HAVE_ECC */

#if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)

/* Encode public ECC key in DER format.
 *
 * RFC 5480, 2 - Subject Public Key Information Fields
 *           2.1.1 - Unrestricted Algorithm Identifier and Parameters
 * X9.62 ECC point format.
 * SEC 1 Ver. 2.0, C.2 - Syntax for Elliptic Curve Domain Parameters
 *
 * @param [out] output       Buffer to put encoded data in.
 * @param [in]  key          ECC key object.
 * @param [in]  outLen       Size of buffer in bytes.
 * @param [in]  with_header  Whether to use SubjectPublicKeyInfo format.
 * @return  Size of encoded data in bytes on success.
 * @return  BAD_FUNC_ARG when key or key's parameters is NULL.
 * @return  MEMORY_E when dynamic memory allocation failed.
 */
static int SetEccPublicKey(byte* output, ecc_key* key, int outLen,
                           int with_header, int comp)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int ret;
    word32 idx = 0, curveSz, algoSz, pubSz, bitStringSz;
    byte bitString[1 + MAX_LENGTH_SZ + 1]; /* 6 */
    byte algo[MAX_ALGO_SZ];  /* 20 */

    /* public size */
    pubSz = key->dp ? (word32)key->dp->size : MAX_ECC_BYTES;
    if (comp)
        pubSz = 1 + pubSz;
    else
        pubSz = 1 + 2 * pubSz;

    /* check for buffer overflow */
    if (output != NULL && pubSz > (word32)outLen) {
        return BUFFER_E;
    }

    /* headers */
    if (with_header) {
        ret = SetCurve(key, NULL, 0);
        if (ret <= 0) {
            return ret;
        }
        curveSz = (word32)ret;
        ret = 0;

        /* calculate size */
        algoSz  = SetAlgoID(ECDSAk, algo, oidKeyType, (int)curveSz);
        bitStringSz = SetBitString(pubSz, 0, bitString);
        idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz, NULL);

        /* check for buffer overflow */
        if (output != NULL &&
                curveSz + algoSz + bitStringSz + idx + pubSz > (word32)outLen) {
            return BUFFER_E;
        }

        idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz,
            output);
        /* algo */
        if (output)
            XMEMCPY(output + idx, algo, algoSz);
        idx += algoSz;
        /* curve */
        if (output)
            (void)SetCurve(key, output + idx, curveSz);
        idx += curveSz;
        /* bit string */
        if (output)
            XMEMCPY(output + idx, bitString, bitStringSz);
        idx += bitStringSz;
    }

    /* pub */
    if (output) {
        PRIVATE_KEY_UNLOCK();
        ret = wc_ecc_export_x963_ex(key, output + idx, &pubSz, comp);
        PRIVATE_KEY_LOCK();
        if (ret != 0) {
            return ret;
        }
    }
    idx += pubSz;

    return (int)idx;
#else
    word32 pubSz = 0;
    int sz = 0;
    int ret = 0;
    int curveIdSz = 0;
    byte* curveOid = NULL;

    /* Check key validity. */
    if ((key == NULL) || (key->dp == NULL)) {
        ret = BAD_FUNC_ARG;
    }

    if (ret == 0) {
        /* Calculate the size of the encoded public point. */
        PRIVATE_KEY_UNLOCK();
    #if defined(HAVE_COMP_KEY) && defined(HAVE_FIPS) && \
            defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
        /* in earlier versions of FIPS the get length functionality is not
         * available with compressed keys */
        pubSz = key->dp ? key->dp->size : MAX_ECC_BYTES;
        if (comp)
            pubSz = 1 + pubSz;
        else
            pubSz = 1 + 2 * pubSz;
        ret = LENGTH_ONLY_E;
    #else
        ret = wc_ecc_export_x963_ex(key, NULL, &pubSz, comp);
    #endif
        PRIVATE_KEY_LOCK();
        /* LENGTH_ONLY_E on success. */
        if (ret == LENGTH_ONLY_E) {
            ret = 0;
        }
    }
    if ((ret == 0) && with_header) {
        /* Including SubjectPublicKeyInfo header. */
        DECL_ASNSETDATA(dataASN, eccPublicKeyASN_Length);

        CALLOC_ASNSETDATA(dataASN, eccPublicKeyASN_Length, ret, key->heap);

        /* Get the length of the named curve OID to put into the encoding. */
        curveIdSz = SetCurve(key, NULL, 0);
        if (curveIdSz < 0) {
            ret = curveIdSz;
        }

        if (ret == 0) {
            /* Set the key type OID. */
            SetASN_OID(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID], ECDSAk,
                    oidKeyType);
            /* Set the curve OID. */
            SetASN_ReplaceBuffer(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_CURVEID],
                NULL, (word32)curveIdSz);
            /* Don't try to write out explicit parameters. */
            dataASN[ECCPUBLICKEYASN_IDX_ALGOID_PARAMS].noOut = 1;
            /* Set size of public point to ensure space is made for it. */
            SetASN_Buffer(&dataASN[ECCPUBLICKEYASN_IDX_PUBKEY], NULL, pubSz);
            /* Calculate size of ECC public key. */
            ret = SizeASN_Items(eccPublicKeyASN, dataASN,
                                eccPublicKeyASN_Length, &sz);
        }

        /* Check buffer, if passed in, is big enough for encoded data. */
        if ((ret == 0) && (output != NULL) && (sz > outLen)) {
            ret = BUFFER_E;
        }
        if ((ret == 0) && (output != NULL)) {
            /* Encode ECC public key. */
            SetASN_Items(eccPublicKeyASN, dataASN, eccPublicKeyASN_Length,
                         output);
            /* Skip to where public point is to be encoded. */
            output += sz - (int)pubSz;
            /* Cache the location to place the name curve OID. */
            curveOid = (byte*)
                dataASN[ECCPUBLICKEYASN_IDX_ALGOID_CURVEID].data.buffer.data;
        }

        FREE_ASNSETDATA(dataASN, key->heap);
    }
    else if ((ret == 0) && (output != NULL) && (pubSz > (word32)outLen)) {
        ret = BUFFER_E;
    }
    else {
        /* Total size is the public point size. */
        sz = (int)pubSz;
    }

    if ((ret == 0) && (output != NULL)) {
        /* Put named curve OID data into encoding. */
        curveIdSz = SetCurve(key, curveOid, (size_t)curveIdSz);
        if (curveIdSz < 0) {
            ret = curveIdSz;
        }
    }
    if ((ret == 0) && (output != NULL)) {
        /* Encode public point. */
        PRIVATE_KEY_UNLOCK();
        ret = wc_ecc_export_x963_ex(key, output, &pubSz, comp);
        PRIVATE_KEY_LOCK();
    }
    if (ret == 0) {
        /* Return the size of the encoding. */
        ret = sz;
    }

    return ret;
#endif
}


/* Encode the public part of an ECC key in a DER.
 *
 * Pass NULL for output to get the size of the encoding.
 *
 * @param [in]  key            ECC key object.
 * @param [out] output         Buffer to hold DER encoding.
 * @param [in]  inLen          Size of buffer in bytes.
 * @param [in]  with_AlgCurve  Whether to use SubjectPublicKeyInfo format.
 * @return  Size of encoded data in bytes on success.
 * @return  BAD_FUNC_ARG when key or key's parameters is NULL.
 * @return  MEMORY_E when dynamic memory allocation failed.
 */
WOLFSSL_ABI
int wc_EccPublicKeyToDer(ecc_key* key, byte* output, word32 inLen,
                                                              int with_AlgCurve)
{
    return SetEccPublicKey(output, key, (int)inLen, with_AlgCurve, 0);
}

int wc_EccPublicKeyToDer_ex(ecc_key* key, byte* output, word32 inLen,
                                                    int with_AlgCurve, int comp)
{
    return SetEccPublicKey(output, key, (int)inLen, with_AlgCurve, comp);
}

int wc_EccPublicKeyDerSize(ecc_key* key, int with_AlgCurve)
{
    return SetEccPublicKey(NULL, key, 0, with_AlgCurve, 0);
}

#endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */

#ifdef WOLFSSL_ASN_TEMPLATE
#if defined(WC_ENABLE_ASYM_KEY_EXPORT) || defined(WC_ENABLE_ASYM_KEY_IMPORT)
/* ASN.1 template for Ed25519 and Ed448 public key (SubkectPublicKeyInfo).
 * RFC 8410, 4 - Subject Public Key Fields
 */
static const ASNItem edPubKeyASN[] = {
            /* SubjectPublicKeyInfo */
/* SEQ        */ { 0, ASN_SEQUENCE, 1, 1, 0 },
                                     /* AlgorithmIdentifier */
/* ALGOID_SEQ */     { 1, ASN_SEQUENCE, 1, 1, 0 },
                                         /* Ed25519/Ed448 OID */
/* ALGOID_OID */         { 2, ASN_OBJECT_ID, 0, 0, 1 },
                                     /* Public key stream */
/* PUBKEY     */     { 1, ASN_BIT_STRING, 0, 0, 0 },
};
enum {
    EDPUBKEYASN_IDX_SEQ = 0,
    EDPUBKEYASN_IDX_ALGOID_SEQ,
    EDPUBKEYASN_IDX_ALGOID_OID,
    EDPUBKEYASN_IDX_PUBKEY
};

/* Number of items in ASN.1 template for Ed25519 and Ed448 public key. */
#define edPubKeyASN_Length (sizeof(edPubKeyASN) / sizeof(ASNItem))
#endif /* WC_ENABLE_ASYM_KEY_EXPORT || WC_ENABLE_ASYM_KEY_IMPORT */
#endif /* WOLFSSL_ASN_TEMPLATE */

#ifdef WC_ENABLE_ASYM_KEY_EXPORT

/* Build ASN.1 formatted public key based on RFC 8410
 *
 * Pass NULL for output to get the size of the encoding.
 *
 * @param [in]  pubKey       public key buffer
 * @param [in]  pubKeyLen    public ket buffer length
 * @param [out] output       Buffer to put encoded data in (optional)
 * @param [in]  outLen       Size of buffer in bytes
 * @param [in]  keyType      is "enum Key_Sum" like ED25519k
 * @param [in]  withHeader   Whether to include SubjectPublicKeyInfo around key.
 * @return  Size of encoded data in bytes on success
 * @return  BAD_FUNC_ARG when key is NULL.
 * @return  MEMORY_E when dynamic memory allocation failed.
 */
int SetAsymKeyDerPublic(const byte* pubKey, word32 pubKeyLen,
    byte* output, word32 outLen, int keyType, int withHeader)
{
    int ret = 0;
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx = 0;
    word32 seqDataSz = 0;
    word32 sz;
#else
    int sz = 0;
    DECL_ASNSETDATA(dataASN, edPubKeyASN_Length);
#endif

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

#ifndef WOLFSSL_ASN_TEMPLATE
    /* calculate size */
    if (withHeader) {
        word32 algoSz      = SetAlgoID(keyType, NULL, oidKeyType, 0);
        word32 bitStringSz = SetBitString(pubKeyLen, 0, NULL);

        seqDataSz = algoSz + bitStringSz + pubKeyLen;
        sz = SetSequence(seqDataSz, NULL) + seqDataSz;
    }
    else {
        sz = pubKeyLen;
    }

    /* checkout output size */
    if (output != NULL && sz > outLen) {
        ret = BUFFER_E;
    }

    /* headers */
    if (ret == 0 && output != NULL && withHeader) {
        /* sequence */
        idx = SetSequence(seqDataSz, output);
        /* algo */
        idx += SetAlgoID(keyType, output + idx, oidKeyType, 0);
        /* bit string */
        idx += SetBitString(pubKeyLen, 0, output + idx);
    }

    if (ret == 0 && output != NULL) {
        /* pub */
        XMEMCPY(output + idx, pubKey, pubKeyLen);
        idx += pubKeyLen;

        sz = idx;
    }

    if (ret == 0) {
        ret = (int)sz;
    }
#else
    if (withHeader) {
        CALLOC_ASNSETDATA(dataASN, edPubKeyASN_Length, ret, NULL);

        if (ret == 0) {
            /* Set the OID. */
            SetASN_OID(&dataASN[EDPUBKEYASN_IDX_ALGOID_OID], (word32)keyType,
                    oidKeyType);
            /* Leave space for public point. */
            SetASN_Buffer(&dataASN[EDPUBKEYASN_IDX_PUBKEY], NULL, pubKeyLen);
            /* Calculate size of public key encoding. */
            ret = SizeASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, &sz);
        }
        if ((ret == 0) && (output != NULL) && (sz > (int)outLen)) {
            ret = BUFFER_E;
        }
        if ((ret == 0) && (output != NULL)) {
            /* Encode public key. */
            SetASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, output);
            /* Set location to encode public point. */
            output = (byte*)dataASN[EDPUBKEYASN_IDX_PUBKEY].data.buffer.data;
        }

        FREE_ASNSETDATA(dataASN, NULL);
    }
    else if ((output != NULL) && (pubKeyLen > outLen)) {
        ret = BUFFER_E;
    }
    else if (ret == 0) {
        sz = (int)pubKeyLen;
    }

    if ((ret == 0) && (output != NULL)) {
        /* Put public key into space provided. */
        XMEMCPY(output, pubKey, pubKeyLen);
    }
    if (ret == 0) {
        ret = sz;
    }
#endif /* WOLFSSL_ASN_TEMPLATE */
    return ret;
}
#endif /* WC_ENABLE_ASYM_KEY_EXPORT */

#if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
/* Encode the public part of an Ed25519 key in DER.
 *
 * Pass NULL for output to get the size of the encoding.
 *
 * @param [in]  key       Ed25519 key object.
 * @param [out] output    Buffer to put encoded data in.
 * @param [in]  outLen    Size of buffer in bytes.
 * @param [in]  withAlg   Whether to use SubjectPublicKeyInfo format.
 * @return  Size of encoded data in bytes on success.
 * @return  BAD_FUNC_ARG when key is NULL.
 * @return  MEMORY_E when dynamic memory allocation failed.
 */
int wc_Ed25519PublicKeyToDer(ed25519_key* key, byte* output, word32 inLen,
                             int withAlg)
{
    int    ret;
    byte   pubKey[ED25519_PUB_KEY_SIZE];
    word32 pubKeyLen = (word32)sizeof(pubKey);

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

    ret = wc_ed25519_export_public(key, pubKey, &pubKeyLen);
    if (ret == 0) {
        ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
            ED25519k, withAlg);
    }
    return ret;
}
#endif /* HAVE_ED25519 && HAVE_ED25519_KEY_EXPORT */

#if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
/* Encode the public part of an Ed448 key in DER.
 *
 * Pass NULL for output to get the size of the encoding.
 *
 * @param [in]  key       Ed448 key object.
 * @param [out] output    Buffer to put encoded data in.
 * @param [in]  outLen    Size of buffer in bytes.
 * @param [in]  withAlg   Whether to use SubjectPublicKeyInfo format.
 * @return  Size of encoded data in bytes on success.
 * @return  BAD_FUNC_ARG when key is NULL.
 * @return  MEMORY_E when dynamic memory allocation failed.
 */
int wc_Ed448PublicKeyToDer(ed448_key* key, byte* output, word32 inLen,
                           int withAlg)
{
    int    ret;
    byte   pubKey[ED448_PUB_KEY_SIZE];
    word32 pubKeyLen = (word32)sizeof(pubKey);

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

    ret = wc_ed448_export_public(key, pubKey, &pubKeyLen);
    if (ret == 0) {
        ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
            ED448k, withAlg);
    }
    return ret;
}
#endif /* HAVE_ED448 && HAVE_ED448_KEY_EXPORT */
#ifdef WOLFSSL_CERT_GEN

#ifndef NO_ASN_TIME
static WC_INLINE byte itob(int number)
{
    return (byte)number + 0x30;
}


/* write time to output, format */
static void SetTime(struct tm* date, byte* output)
{
    int i = 0;

    output[i++] = itob((date->tm_year % 10000) / 1000);
    output[i++] = itob((date->tm_year % 1000)  /  100);
    output[i++] = itob((date->tm_year % 100)   /   10);
    output[i++] = itob( date->tm_year % 10);

    output[i++] = itob(date->tm_mon / 10);
    output[i++] = itob(date->tm_mon % 10);

    output[i++] = itob(date->tm_mday / 10);
    output[i++] = itob(date->tm_mday % 10);

    output[i++] = itob(date->tm_hour / 10);
    output[i++] = itob(date->tm_hour % 10);

    output[i++] = itob(date->tm_min / 10);
    output[i++] = itob(date->tm_min % 10);

    output[i++] = itob(date->tm_sec / 10);
    output[i++] = itob(date->tm_sec % 10);

    output[i] = 'Z';  /* Zulu profile */
}
#endif

#ifndef WOLFSSL_ASN_TEMPLATE

/* Copy Dates from cert, return bytes written */
static int CopyValidity(byte* output, Cert* cert)
{
    word32 seqSz;

    WOLFSSL_ENTER("CopyValidity");

    /* headers and output */
    seqSz = SetSequence((word32)(cert->beforeDateSz + cert->afterDateSz),
                        output);
    if (output) {
        XMEMCPY(output + seqSz, cert->beforeDate, (size_t)cert->beforeDateSz);
        XMEMCPY(output + seqSz + cert->beforeDateSz, cert->afterDate,
                (size_t)cert->afterDateSz);
    }
    return (int)seqSz + cert->beforeDateSz + cert->afterDateSz;
}

#endif /* !WOLFSSL_ASN_TEMPLATE */


/* Simple name OID size. */
#define NAME_OID_SZ     3

/* Domain name OIDs. */
static const byte nameOid[][NAME_OID_SZ] = {
    { 0x55, 0x04, ASN_COUNTRY_NAME },
    { 0x55, 0x04, ASN_STATE_NAME },
    { 0x55, 0x04, ASN_STREET_ADDR },
    { 0x55, 0x04, ASN_LOCALITY_NAME },
#ifdef WOLFSSL_CERT_NAME_ALL
    { 0x55, 0x04, ASN_NAME },
    { 0x55, 0x04, ASN_GIVEN_NAME },
    { 0x55, 0x04, ASN_INITIALS },
    { 0x55, 0x04, ASN_DNQUALIFIER },
#endif
    { 0x55, 0x04, ASN_SUR_NAME },
    { 0x55, 0x04, ASN_ORG_NAME },
    { 0x00, 0x00, ASN_DOMAIN_COMPONENT}, /* not actual OID - see dcOid */
                                         /* list all DC values before OUs */
    { 0x55, 0x04, ASN_ORGUNIT_NAME },
    { 0x55, 0x04, ASN_COMMON_NAME },
    { 0x55, 0x04, ASN_SERIAL_NUMBER },
#ifdef WOLFSSL_CERT_EXT
    { 0x55, 0x04, ASN_BUS_CAT },
#endif
    { 0x55, 0x04, ASN_POSTAL_CODE },
    { 0x00, 0x00, ASN_EMAIL_NAME},       /* not actual OID - see attrEmailOid */
    { 0x00, 0x00, ASN_USER_ID},          /* not actual OID - see uidOid */
#ifdef WOLFSSL_CUSTOM_OID
    { 0x00, 0x00, ASN_CUSTOM_NAME} /* OID comes from CertOidField */
#endif
};
#define NAME_ENTRIES (int)(sizeof(nameOid)/NAME_OID_SZ)


/* Get ASN Name from index */
byte GetCertNameId(int idx)
{
    if (idx < NAME_ENTRIES)
        return nameOid[idx][2];
    return 0;
}

/* Get Which Name from index */
const char* GetOneCertName(CertName* name, int idx)
{
    byte type = GetCertNameId(idx);
    switch (type) {
    case ASN_COUNTRY_NAME:
       return name->country;
    case ASN_STATE_NAME:
       return name->state;
    case ASN_STREET_ADDR:
       return name->street;
    case ASN_LOCALITY_NAME:
       return name->locality;
#ifdef WOLFSSL_CERT_NAME_ALL
    case ASN_NAME:
       return name->dnName;
    case ASN_GIVEN_NAME:
       return name->givenName;
    case ASN_INITIALS:
       return name->initials;
    case ASN_DNQUALIFIER:
       return name->dnQualifier;
#endif /* WOLFSSL_CERT_NAME_ALL */
    case ASN_SUR_NAME:
       return name->sur;
    case ASN_ORG_NAME:
       return name->org;
    case ASN_ORGUNIT_NAME:
       return name->unit;
    case ASN_COMMON_NAME:
       return name->commonName;
    case ASN_SERIAL_NUMBER:
       return name->serialDev;
    case ASN_USER_ID:
       return name->userId;
    case ASN_POSTAL_CODE:
       return name->postalCode;
    case ASN_EMAIL_NAME:
       return name->email;
#ifdef WOLFSSL_CERT_EXT
    case ASN_BUS_CAT:
       return name->busCat;
#endif
#ifdef WOLFSSL_CUSTOM_OID
    case ASN_CUSTOM_NAME:
        return (const char*)name->custom.val;
#endif
    default:
       return NULL;
    }
}


/* Get Which Name Encoding from index */
static char GetNameType(CertName* name, int idx)
{
    byte type = GetCertNameId(idx);
    switch (type) {
    case ASN_COUNTRY_NAME:
       return name->countryEnc;
    case ASN_STATE_NAME:
       return name->stateEnc;
    case ASN_STREET_ADDR:
       return name->streetEnc;
    case ASN_LOCALITY_NAME:
       return name->localityEnc;
#ifdef WOLFSSL_CERT_NAME_ALL
    case ASN_NAME:
       return name->dnNameEnc;
    case ASN_GIVEN_NAME:
       return name->givenNameEnc;
    case ASN_INITIALS:
       return name->initialsEnc;
    case ASN_DNQUALIFIER:
       return name->dnQualifierEnc;
#endif /* WOLFSSL_CERT_NAME_ALL */
    case ASN_SUR_NAME:
       return name->surEnc;
    case ASN_ORG_NAME:
       return name->orgEnc;
    case ASN_ORGUNIT_NAME:
       return name->unitEnc;
    case ASN_COMMON_NAME:
       return name->commonNameEnc;
    case ASN_SERIAL_NUMBER:
       return name->serialDevEnc;
    case ASN_USER_ID:
       return name->userIdEnc;
    case ASN_POSTAL_CODE:
       return name->postalCodeEnc;
    case ASN_EMAIL_NAME:
       return 0; /* special */
#ifdef WOLFSSL_CERT_EXT
    case ASN_BUS_CAT:
       return name->busCatEnc;
#endif
#ifdef WOLFSSL_CUSTOM_OID
    case ASN_CUSTOM_NAME:
        return name->custom.enc;
#endif
    default:
       return 0;
    }
}

#ifndef WOLFSSL_ASN_TEMPLATE
/*
 Extensions ::= SEQUENCE OF Extension

 Extension ::= SEQUENCE {
 extnId     OBJECT IDENTIFIER,
 critical   BOOLEAN DEFAULT FALSE,
 extnValue  OCTET STRING }
 */

/* encode all extensions, return total bytes written */
static int SetExtensions(byte* out, word32 outSz, int *IdxInOut,
                         const byte* ext, int extSz)
{
    if (out == NULL || IdxInOut == NULL || ext == NULL)
        return BAD_FUNC_ARG;

    if (outSz < (word32)(*IdxInOut+extSz))
        return BUFFER_E;

    XMEMCPY(&out[*IdxInOut], ext, (size_t)extSz);  /* extensions */
    *IdxInOut += extSz;

    return *IdxInOut;
}

/* encode extensions header, return total bytes written */
static int SetExtensionsHeader(byte* out, word32 outSz, word32 extSz)
{
    byte sequence[MAX_SEQ_SZ];
    byte len[MAX_LENGTH_SZ];
    word32 seqSz, lenSz, idx = 0;

    if (out == NULL)
        return BAD_FUNC_ARG;

    if (outSz < 3)
        return BUFFER_E;

    seqSz = SetSequence(extSz, sequence);

    /* encode extensions length provided */
    lenSz = SetLength(extSz+seqSz, len);

    if (outSz < (word32)(lenSz+seqSz+1))
        return BUFFER_E;

    out[idx++] = ASN_EXTENSIONS; /* extensions id */
    XMEMCPY(&out[idx], len, lenSz);  /* length */
    idx += lenSz;

    XMEMCPY(&out[idx], sequence, seqSz);  /* sequence */
    idx += seqSz;

    return (int)idx;
}


/* encode CA basic constraints true with path length
 * return total bytes written */
static int SetCaWithPathLen(byte* out, word32 outSz, byte pathLen)
{
    /* ASN1->DER sequence for Basic Constraints True and path length */
    const byte caPathLenBasicConstASN1[] = {
        0x30, 0x0F, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04,
        0x08, 0x30, 0x06, 0x01, 0x01, 0xFF, 0x02, 0x01,
        0x00
    };

    if (out == NULL)
        return BAD_FUNC_ARG;

    if (outSz < sizeof(caPathLenBasicConstASN1))
        return BUFFER_E;

    XMEMCPY(out, caPathLenBasicConstASN1, sizeof(caPathLenBasicConstASN1));

    out[sizeof(caPathLenBasicConstASN1)-1] = pathLen;

    return (int)sizeof(caPathLenBasicConstASN1);
}


/* encode CA basic constraints true
 * return total bytes written */
static int SetCa(byte* out, word32 outSz)
{
    /* ASN1->DER sequence for Basic Constraints True */
    const byte caBasicConstASN1[] = {
        0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
        0x05, 0x30, 0x03, 0x01, 0x01, 0xff
    };

    if (out == NULL)
        return BAD_FUNC_ARG;

    if (outSz < sizeof(caBasicConstASN1))
        return BUFFER_E;

    XMEMCPY(out, caBasicConstASN1, sizeof(caBasicConstASN1));

    return (int)sizeof(caBasicConstASN1);
}

/* encode basic constraints without CA Boolean
 * return total bytes written */
static int SetBC(byte* out, word32 outSz)
{
    /* ASN1->DER sequence for Basic Constraint without CA Boolean */
 const byte BasicConstASN1[] = {
        0x30, 0x09, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
        0x02, 0x30, 0x00
    };

    if (out == NULL)
        return BAD_FUNC_ARG;

    if (outSz < sizeof(BasicConstASN1))
        return BUFFER_E;

    XMEMCPY(out, BasicConstASN1, sizeof(BasicConstASN1));

    return (int)sizeof(BasicConstASN1);
}
#endif


#ifdef WOLFSSL_CERT_EXT
#ifndef WOLFSSL_ASN_TEMPLATE
/* encode OID and associated value, return total bytes written */
static int SetOidValue(byte* out, word32 outSz, const byte *oid, word32 oidSz,
                       byte *in, word32 inSz)
{
    word32 idx = 0;

    if (out == NULL || oid == NULL || in == NULL)
        return BAD_FUNC_ARG;

    if (outSz < 3)
        return BUFFER_E;

    /* sequence,  + 1 => byte to put value size */
    idx = SetSequence(inSz + oidSz + 1, out);

    if ((idx + inSz + oidSz + 1) > outSz)
        return BUFFER_E;

    XMEMCPY(out+idx, oid, oidSz);
    idx += oidSz;
    out[idx++] = (byte)inSz;
    XMEMCPY(out+idx, in, inSz);

    return (int)(idx+inSz);
}

/* encode Subject Key Identifier, return total bytes written
 * RFC5280 : non-critical */
static int SetSKID(byte* output, word32 outSz, const byte *input, word32 length)
{
    byte skid_len[1 + MAX_LENGTH_SZ];
    byte skid_enc_len[MAX_LENGTH_SZ];
    word32 idx = 0, skid_lenSz, skid_enc_lenSz;
    const byte skid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04 };

    if (output == NULL || input == NULL)
        return BAD_FUNC_ARG;

    /* Octet String header */
    skid_lenSz = SetOctetString(length, skid_len);

    /* length of encoded value */
    skid_enc_lenSz = SetLength(length + skid_lenSz, skid_enc_len);

    if (outSz < 3)
        return BUFFER_E;

    idx = SetSequence(length + (word32)sizeof(skid_oid) + skid_lenSz +
                      skid_enc_lenSz, output);

    if ((length + sizeof(skid_oid) + skid_lenSz + skid_enc_lenSz) > outSz)
        return BUFFER_E;

    /* put oid */
    XMEMCPY(output+idx, skid_oid, sizeof(skid_oid));
    idx += sizeof(skid_oid);

    /* put encoded len */
    XMEMCPY(output+idx, skid_enc_len, skid_enc_lenSz);
    idx += skid_enc_lenSz;

    /* put octet header */
    XMEMCPY(output+idx, skid_len, skid_lenSz);
    idx += skid_lenSz;

    /* put value */
    XMEMCPY(output+idx, input, length);
    idx += length;

    return (int)idx;
}

/* encode Authority Key Identifier, return total bytes written
 * RFC5280 : non-critical */
static int SetAKID(byte* output, word32 outSz, byte *input, word32 length,
                   byte rawAkid)
{
    int     enc_valSz;
    byte enc_val_buf[MAX_KID_SZ];
    byte* enc_val;
    const byte akid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x23 };
    const byte akid_cs[] = { 0x80 };
    word32 inSeqSz, idx;

    (void)rawAkid;

    if (output == NULL || input == NULL)
        return BAD_FUNC_ARG;

#ifdef WOLFSSL_AKID_NAME
    if (rawAkid) {
        enc_val = input;
        enc_valSz = length;
    }
    else
#endif
    {
        enc_val = enc_val_buf;
        enc_valSz = (int)length + 3 + (int)sizeof(akid_cs);
        if (enc_valSz > (int)sizeof(enc_val_buf))
            return BAD_FUNC_ARG;

        /* sequence for ContentSpec & value */
        enc_valSz = SetOidValue(enc_val, (word32)enc_valSz, akid_cs,
                                sizeof(akid_cs), input, length);
        if (enc_valSz <= 0)
            return enc_valSz;
    }

    /* The size of the extension sequence contents */
    inSeqSz = (word32)sizeof(akid_oid) +
        SetOctetString((word32)enc_valSz, NULL) + (word32)enc_valSz;

    if (SetSequence(inSeqSz, NULL) + inSeqSz > outSz)
        return BAD_FUNC_ARG;

    /* Write out the sequence header */
    idx = SetSequence(inSeqSz, output);

    /* Write out OID */
    XMEMCPY(output + idx, akid_oid, sizeof(akid_oid));
    idx += sizeof(akid_oid);

    /* Write out AKID */
    idx += SetOctetString((word32)enc_valSz, output + idx);
    XMEMCPY(output + idx, enc_val, (size_t)enc_valSz);

    return (int)idx + enc_valSz;
}

/* encode Key Usage, return total bytes written
 * RFC5280 : critical */
static int SetKeyUsage(byte* output, word32 outSz, word16 input)
{
    byte ku[5];
    word32 idx;
    const byte keyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0f,
                                         0x01, 0x01, 0xff, 0x04};
    if (output == NULL)
        return BAD_FUNC_ARG;

    idx = SetBitString16Bit(input, ku);
    return SetOidValue(output, outSz, keyusage_oid, sizeof(keyusage_oid),
                       ku, idx);
}

static int SetOjectIdValue(byte* output, word32 outSz, word32* idx,
    const byte* oid, word32 oidSz)
{
    /* verify room */
    if (*idx + 2 + oidSz >= outSz)
        return ASN_PARSE_E;

    *idx += (word32)SetObjectId((int)oidSz, &output[*idx]);
    XMEMCPY(&output[*idx], oid, oidSz);
    *idx += oidSz;

    return 0;
}
#endif

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for extended key usage.
 * X.509: RFC 5280, 4.2.12 - Extended Key Usage
 * Dynamic creation of template for encoding.
 */
static const ASNItem ekuASN[] = {
/* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
/* OID */     { 1, ASN_OBJECT_ID, 0, 0, 0 },
};
enum {
    EKUASN_IDX_SEQ = 0,
    EKUASN_IDX_OID
};

/* OIDs corresponding to extended key usage. */
struct {
    const byte* oid;
    word32 oidSz;
} ekuOid[] = {
    { extExtKeyUsageServerAuthOid,   sizeof(extExtKeyUsageServerAuthOid) },
    { extExtKeyUsageClientAuthOid,   sizeof(extExtKeyUsageClientAuthOid) },
    { extExtKeyUsageCodeSigningOid,  sizeof(extExtKeyUsageCodeSigningOid) },
    { extExtKeyUsageEmailProtectOid, sizeof(extExtKeyUsageEmailProtectOid) },
    { extExtKeyUsageTimestampOid,    sizeof(extExtKeyUsageTimestampOid) },
    { extExtKeyUsageOcspSignOid,     sizeof(extExtKeyUsageOcspSignOid) },
};

#define EKU_OID_LO      1
#define EKU_OID_HI      6
#endif /* WOLFSSL_ASN_TEMPLATE */

/* encode Extended Key Usage (RFC 5280 4.2.1.12), return total bytes written */
static int SetExtKeyUsage(Cert* cert, byte* output, word32 outSz, byte input)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx = 0, oidListSz = 0, totalSz;
    int ret = 0;
    const byte extkeyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x25 };

    if (output == NULL)
        return BAD_FUNC_ARG;

    /* Skip to OID List */
    totalSz = 2 + sizeof(extkeyusage_oid) + 4;
    idx = totalSz;

    /* Build OID List */
    /* If any set, then just use it */
    if (input & EXTKEYUSE_ANY) {
        ret |= SetOjectIdValue(output, outSz, &idx,
            extExtKeyUsageAnyOid, sizeof(extExtKeyUsageAnyOid));
    }
    else {
        if (input & EXTKEYUSE_SERVER_AUTH)
            ret |= SetOjectIdValue(output, outSz, &idx,
                extExtKeyUsageServerAuthOid, sizeof(extExtKeyUsageServerAuthOid));
        if (input & EXTKEYUSE_CLIENT_AUTH)
            ret |= SetOjectIdValue(output, outSz, &idx,
                extExtKeyUsageClientAuthOid, sizeof(extExtKeyUsageClientAuthOid));
        if (input & EXTKEYUSE_CODESIGN)
            ret |= SetOjectIdValue(output, outSz, &idx,
                extExtKeyUsageCodeSigningOid, sizeof(extExtKeyUsageCodeSigningOid));
        if (input & EXTKEYUSE_EMAILPROT)
            ret |= SetOjectIdValue(output, outSz, &idx,
                extExtKeyUsageEmailProtectOid, sizeof(extExtKeyUsageEmailProtectOid));
        if (input & EXTKEYUSE_TIMESTAMP)
            ret |= SetOjectIdValue(output, outSz, &idx,
                extExtKeyUsageTimestampOid, sizeof(extExtKeyUsageTimestampOid));
        if (input & EXTKEYUSE_OCSP_SIGN)
            ret |= SetOjectIdValue(output, outSz, &idx,
                extExtKeyUsageOcspSignOid, sizeof(extExtKeyUsageOcspSignOid));
    #ifdef WOLFSSL_EKU_OID
        /* iterate through OID values */
        if (input & EXTKEYUSE_USER) {
            int i, sz;
            for (i = 0; i < CTC_MAX_EKU_NB; i++) {
                sz = cert->extKeyUsageOIDSz[i];
                if (sz > 0) {
                    ret |= SetOjectIdValue(output, outSz, &idx,
                        cert->extKeyUsageOID[i], sz);
                }
            }
        }
    #endif /* WOLFSSL_EKU_OID */
    }
    if (ret != 0)
        return ASN_PARSE_E;

    /* Calculate Sizes */
    oidListSz = idx - totalSz;
    totalSz = idx - 2; /* exclude first seq/len (2) */

    /* 1. Seq + Total Len (2) */
    idx = SetSequence(totalSz, output);

    /* 2. Object ID (2) */
    XMEMCPY(&output[idx], extkeyusage_oid, sizeof(extkeyusage_oid));
    idx += sizeof(extkeyusage_oid);

    /* 3. Octet String (2) */
    idx += SetOctetString(totalSz - idx, &output[idx]);

    /* 4. Seq + OidListLen (2) */
    idx += SetSequence(oidListSz, &output[idx]);

    /* 5. Oid List (already set in-place above) */
    idx += oidListSz;

    (void)cert;
    return (int)idx;
#else
    /* TODO: consider calculating size of OBJECT_IDs, setting length into
     * SEQUENCE, encode SEQUENCE, encode OBJECT_IDs into buffer.  */
    ASNSetData* dataASN;
    ASNItem* extKuASN = NULL;
    int asnIdx = 1;
    size_t cnt = 1 + EKU_OID_HI;
    int i;
    int ret = 0;
    int sz = 0;

#ifdef WOLFSSL_EKU_OID
    cnt += CTC_MAX_EKU_NB;
#endif

    /* Allocate memory for dynamic data items. */
    dataASN = (ASNSetData*)XMALLOC(cnt * sizeof(ASNSetData), cert->heap,
                                                       DYNAMIC_TYPE_TMP_BUFFER);
    if (dataASN == NULL) {
        ret = MEMORY_E;
    }
    if (ret == 0) {
        /* Allocate memory for dynamic ASN.1 template. */
        extKuASN = (ASNItem*)XMALLOC(cnt * sizeof(ASNItem), cert->heap,
                                                       DYNAMIC_TYPE_TMP_BUFFER);
        if (extKuASN == NULL) {
            ret = MEMORY_E;
        }
    }

    if (ret == 0) {
        /* Copy Sequence into dynamic ASN.1 template. */
        XMEMCPY(&extKuASN[EKUASN_IDX_SEQ], ekuASN, sizeof(ASNItem));
        /* Clear dynamic data. */
        XMEMSET(dataASN, 0, cnt * sizeof(ASNSetData));

        /* Build up the template and data. */
        /* If 'any' set, then just use it. */
        if ((input & EXTKEYUSE_ANY) == EXTKEYUSE_ANY) {
            /* Set template item. */
            XMEMCPY(&extKuASN[EKUASN_IDX_OID], &ekuASN[EKUASN_IDX_OID],
                    sizeof(ASNItem));
            /* Set data item. */
            SetASN_Buffer(&dataASN[asnIdx], extExtKeyUsageAnyOid,
                sizeof(extExtKeyUsageAnyOid));
            asnIdx++;
        }
        else {
            /* Step through the flagged purposes. */
            for (i = EKU_OID_LO; i <= EKU_OID_HI; i++) {
                if ((input & (1 << i)) != 0) {
                    /* Set template item. */
                    XMEMCPY(&extKuASN[asnIdx], &ekuASN[EKUASN_IDX_OID],
                            sizeof(ASNItem));
                    /* Set data item. */
                    SetASN_Buffer(&dataASN[asnIdx], ekuOid[i - 1].oid,
                        ekuOid[i - 1].oidSz);
                    asnIdx++;
                }
            }
        #ifdef WOLFSSL_EKU_OID
            if (input & EXTKEYUSE_USER) {
                /* Iterate through OID values */
                for (i = 0; i < CTC_MAX_EKU_NB; i++) {
                    sz = cert->extKeyUsageOIDSz[i];
                    if (sz > 0) {
                        /* Set template item. */
                        XMEMCPY(&extKuASN[asnIdx], &ekuASN[EKUASN_IDX_OID],
                                sizeof(ASNItem));
                        /* Set data item. */
                        SetASN_Buffer(&dataASN[asnIdx], cert->extKeyUsageOID[i],
                            sz);
                        asnIdx++;
                    }
                }
            }
        #endif /* WOLFSSL_EKU_OID */
            (void)cert;
        }

        /* Calculate size of encoding. */
        sz = 0;
        ret = SizeASN_Items(extKuASN, dataASN, asnIdx, &sz);
    }
    /* When buffer to write to, ensure it's big enough. */
    if ((ret == 0) && (output != NULL) && (sz > (int)outSz)) {
        ret = BUFFER_E;
    }
    if ((ret == 0) && (output != NULL)) {
        /* Encode extended key usage. */
        SetASN_Items(extKuASN, dataASN, asnIdx, output);
    }
    if (ret == 0) {
        /* Return the encoding size. */
        ret = sz;
    }

    /* Dispose of allocated data. */
    if (extKuASN != NULL) {
        XFREE(extKuASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
    }
    if (dataASN != NULL) {
        XFREE(dataASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
    }

    return ret;
#endif
}

#ifndef IGNORE_NETSCAPE_CERT_TYPE
#ifndef WOLFSSL_ASN_TEMPLATE
static int SetNsCertType(Cert* cert, byte* output, word32 outSz, byte input)
{
    word32 idx;
    byte unusedBits = 0;
    byte nsCertType = input;
    word32 totalSz;
    word32 bitStrSz;
    const byte nscerttype_oid[] = { 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
                                    0x86, 0xF8, 0x42, 0x01, 0x01 };

    if (cert == NULL || output == NULL ||
            input == 0)
        return BAD_FUNC_ARG;

    totalSz = sizeof(nscerttype_oid);

    /* Get amount of lsb zero's */
    for (;(input & 1) == 0; input >>= 1)
        unusedBits++;

    /* 1 byte of NS Cert Type extension */
    bitStrSz = SetBitString(1, unusedBits, NULL) + 1;
    totalSz += SetOctetString(bitStrSz, NULL) + bitStrSz;

    if (SetSequence(totalSz, NULL) + totalSz > outSz)
        return BAD_FUNC_ARG;

    /* 1. Seq + Total Len */
    idx = SetSequence(totalSz, output);

    /* 2. Object ID */
    XMEMCPY(&output[idx], nscerttype_oid, sizeof(nscerttype_oid));
    idx += sizeof(nscerttype_oid);

    /* 3. Octet String */
    idx += SetOctetString(bitStrSz, &output[idx]);

    /* 4. Bit String */
    idx += SetBitString(1, unusedBits, &output[idx]);
    output[idx++] = nsCertType;

    return (int)idx;
}
#endif
#endif

#ifndef WOLFSSL_ASN_TEMPLATE
static int SetCRLInfo(Cert* cert, byte* output, word32 outSz, byte* input,
                      int inSz)
{
    word32 idx;
    word32 totalSz;
    const byte crlinfo_oid[] = { 0x06, 0x03, 0x55, 0x1D, 0x1F };

    if (cert == NULL || output == NULL ||
            input == 0 || inSz <= 0)
        return BAD_FUNC_ARG;

    totalSz = (word32)sizeof(crlinfo_oid) + SetOctetString((word32)inSz, NULL) +
        (word32)inSz;

    if (SetSequence(totalSz, NULL) + totalSz > outSz)
        return BAD_FUNC_ARG;

    /* 1. Seq + Total Len */
    idx = SetSequence(totalSz, output);

    /* 2. Object ID */
    XMEMCPY(&output[idx], crlinfo_oid, sizeof(crlinfo_oid));
    idx += sizeof(crlinfo_oid);

    /* 3. Octet String */
    idx += SetOctetString((word32)inSz, &output[idx]);

    /* 4. CRL Info */
    XMEMCPY(&output[idx], input, (size_t)inSz);
    idx += (word32)inSz;

    return (int)idx;
}
#endif

/* encode Certificate Policies, return total bytes written
 * each input value must be ITU-T X.690 formatted : a.b.c...
 * input must be an array of values with a NULL terminated for the latest
 * RFC5280 : non-critical */
static int SetCertificatePolicies(byte *output,
                                  word32 outputSz,
                                  char input[MAX_CERTPOL_NB][MAX_CERTPOL_SZ],
                                  word16 nb_certpol,
                                  void* heap)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    byte    oid[MAX_OID_SZ];
    byte    der_oid[MAX_CERTPOL_NB][MAX_OID_SZ];
    byte    out[MAX_CERTPOL_SZ];
    word32  oidSz;
    word32  outSz;
    word32  i = 0;
    word32  der_oidSz[MAX_CERTPOL_NB];
    int     ret;

    const byte certpol_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x20, 0x04 };
    const byte oid_oid[] = { 0x06 };

    if (output == NULL || input == NULL || nb_certpol > MAX_CERTPOL_NB)
        return BAD_FUNC_ARG;

    for (i = 0; i < nb_certpol; i++) {
        oidSz = sizeof(oid);
        XMEMSET(oid, 0, oidSz);

        ret = EncodePolicyOID(oid, &oidSz, input[i], heap);
        if (ret != 0)
            return ret;

        /* compute sequence value for the oid */
        ret = SetOidValue(der_oid[i], MAX_OID_SZ, oid_oid,
                          sizeof(oid_oid), oid, oidSz);
        if (ret <= 0)
            return ret;
        else
            der_oidSz[i] = (word32)ret;
    }

    /* concatenate oid, keep two byte for sequence/size of the created value */
    for (i = 0, outSz = 2; i < nb_certpol; i++) {
        XMEMCPY(out+outSz, der_oid[i], der_oidSz[i]);
        outSz += der_oidSz[i];
    }

    /* add sequence */
    ret = (int)SetSequence(outSz-2, out);
    if (ret <= 0)
        return ret;

    /* add Policy OID to compute final value */
    return SetOidValue(output, outputSz, certpol_oid, sizeof(certpol_oid),
                      out, outSz);
#else
    int    i;
    int    ret = 0;
    byte   oid[MAX_OID_SZ];
    word32 oidSz;
    word32 sz = 0;
    int    piSz;

    if ((input == NULL) || (nb_certpol > MAX_CERTPOL_NB)) {
        ret = BAD_FUNC_ARG;
    }
    /* Put in policyIdentifier but not policyQualifiers. */
    for (i = 0; (ret == 0) && (i < nb_certpol); i++) {
        ASNSetData dataASN[policyInfoASN_Length];

        oidSz = sizeof(oid);
        XMEMSET(oid, 0, oidSz);
        dataASN[POLICYINFOASN_IDX_QUALI].noOut = 1;

        ret = EncodePolicyOID(oid, &oidSz, input[i], heap);
        if (ret == 0) {
            XMEMSET(dataASN, 0, sizeof(dataASN));
            SetASN_Buffer(&dataASN[POLICYINFOASN_IDX_ID], oid, oidSz);
            ret = SizeASN_Items(policyInfoASN, dataASN, policyInfoASN_Length,
                                &piSz);
        }
        if ((ret == 0) && (output != NULL) && (sz + (word32)piSz > outputSz)) {
            ret = BUFFER_E;
        }
        if (ret == 0) {
            if (output != NULL) {
                SetASN_Items(policyInfoASN, dataASN, policyInfoASN_Length,
                    output);
                output += piSz;
            }
            sz += (word32)piSz;
        }
    }

    if (ret == 0) {
        ret = (int)sz;
    }
    return ret;
#endif
}
#endif /* WOLFSSL_CERT_EXT */


#ifdef WOLFSSL_ALT_NAMES

#ifndef WOLFSSL_ASN_TEMPLATE
/* encode Alternative Names, return total bytes written */
static int SetAltNames(byte *output, word32 outSz,
        const byte *input, word32 length, int critical)
{
    byte san_len[1 + MAX_LENGTH_SZ];
    const byte san_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x11 };
    const byte san_crit[] = { 0x01, 0x01, 0xff };
    word32 seqSz, san_lenSz, idx = 0;

    if (output == NULL || input == NULL)
        return BAD_FUNC_ARG;

    if (outSz < length)
        return BUFFER_E;

    /* Octet String header */
    san_lenSz = SetOctetString(length, san_len);

    if (outSz < MAX_SEQ_SZ)
        return BUFFER_E;

    seqSz = length + (word32)sizeof(san_oid) + san_lenSz;
    if (critical)
        seqSz += sizeof(san_crit);
    idx = SetSequence(seqSz, output);

    if (seqSz > outSz)
        return BUFFER_E;

    /* put oid */
    XMEMCPY(output+idx, san_oid, sizeof(san_oid));
    idx += sizeof(san_oid);

    if (critical) {
        XMEMCPY(output+idx, san_crit, sizeof(san_crit));
        idx += sizeof(san_crit);
    }

    /* put octet header */
    XMEMCPY(output+idx, san_len, san_lenSz);
    idx += san_lenSz;

    /* put value */
    XMEMCPY(output+idx, input, length);
    idx += length;

    return (int)idx;
}
#endif /* WOLFSSL_ASN_TEMPLATE */


int FlattenAltNames(byte* output, word32 outputSz, const DNS_entry* names)
{
    word32 idx;
    const DNS_entry* curName;
    word32 namesSz = 0;
#ifdef WOLFSSL_ALT_NAMES_NO_REV
    word32 i;
#endif

    if (output == NULL)
        return BAD_FUNC_ARG;

    if (names == NULL)
        return 0;

    curName = names;
    do {
        namesSz += (word32)curName->len + 2 +
            ((curName->len < ASN_LONG_LENGTH) ? 0
             : BytePrecision((word32)curName->len));
        curName = curName->next;
    } while (curName != NULL);

    if (outputSz < MAX_SEQ_SZ + namesSz)
        return BUFFER_E;

    idx = SetSequence(namesSz, output);
#ifdef WOLFSSL_ALT_NAMES_NO_REV
    namesSz += idx;
    i = namesSz;
#endif

    curName = names;
    do {
#ifdef WOLFSSL_ALT_NAMES_NO_REV
        word32 len = SetLength(curName->len, NULL);
        idx = i - curName->len - len - 1;
        i = idx;
#endif
        output[idx] = (byte) (ASN_CONTEXT_SPECIFIC | curName->type);
        if (curName->type == ASN_DIR_TYPE || curName->type == ASN_OTHER_TYPE) {
            output[idx] |= ASN_CONSTRUCTED;
        }
        idx++;
        idx += SetLength((word32)curName->len, output + idx);
        XMEMCPY(output + idx, curName->name, (size_t)curName->len);
#ifndef WOLFSSL_ALT_NAMES_NO_REV
        idx += (word32)curName->len;
#endif
        curName = curName->next;
    } while (curName != NULL);

#ifdef WOLFSSL_ALT_NAMES_NO_REV
    idx = namesSz;
#endif
    return (int)idx;
}

#endif /* WOLFSSL_ALT_NAMES */
#endif /* WOLFSSL_CERT_GEN */

#if defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
/* Simple domain name OID size. */
#define DN_OID_SZ     3

/* Encodes one attribute of the name (issuer/subject)
 *
 * name     structure to hold result of encoding
 * nameStr  value to be encoded
 * nameTag  tag of encoding i.e CTC_UTF8
 * type     id of attribute i.e ASN_COMMON_NAME
 * emailTag tag of email i.e CTC_UTF8
 * returns length on success
 */
static int EncodeName(EncodedName* name, const char* nameStr,
                    byte nameTag, byte type, byte emailTag, CertName* cname)
{
#if !defined(WOLFSSL_ASN_TEMPLATE)
    word32 idx = 0;
    /* bottom up */
    byte firstLen[1 + MAX_LENGTH_SZ];
    byte secondLen[MAX_LENGTH_SZ];
    byte sequence[MAX_SEQ_SZ];
    byte set[MAX_SET_SZ];

    word32 strLen;
    word32 thisLen;
    word32 firstSz, secondSz, seqSz, setSz;

    if (nameStr == NULL) {
        name->used = 0;
        return 0;
    }

    thisLen = strLen = (word32)XSTRLEN(nameStr);
#ifdef WOLFSSL_CUSTOM_OID
    if (type == ASN_CUSTOM_NAME) {
        if (cname == NULL || cname->custom.oidSz == 0) {
            name->used = 0;
            return 0;
        }
        thisLen = strLen = (word32)cname->custom.valSz;
    }
#else
    (void)cname;
#endif

    if (strLen == 0) { /* no user data for this item */
        name->used = 0;
        return 0;
    }

    /* Restrict country code size */
    if (type == ASN_COUNTRY_NAME && strLen != CTC_COUNTRY_SIZE) {
        WOLFSSL_MSG("Country code size error");
        WOLFSSL_ERROR_VERBOSE(ASN_COUNTRY_SIZE_E);
        return ASN_COUNTRY_SIZE_E;
    }

    secondSz = SetLength(strLen, secondLen);
    thisLen += secondSz;
    switch (type) {
        case ASN_EMAIL_NAME: /* email */
            thisLen += (int)sizeof(attrEmailOid);
            firstSz  = (int)sizeof(attrEmailOid);
            break;
        case ASN_DOMAIN_COMPONENT:
            thisLen += (int)sizeof(dcOid);
            firstSz  = (int)sizeof(dcOid);
            break;
        case ASN_USER_ID:
            thisLen += (int)sizeof(uidOid);
            firstSz  = (int)sizeof(uidOid);
            break;
        case ASN_FAVOURITE_DRINK:
            thisLen += (int)sizeof(fvrtDrk);
            firstSz  = (int)sizeof(fvrtDrk);
            break;
    #ifdef WOLFSSL_CUSTOM_OID
        case ASN_CUSTOM_NAME:
            thisLen += cname->custom.oidSz;
            firstSz = cname->custom.oidSz;
            break;
    #endif
        default:
            thisLen += DN_OID_SZ;
            firstSz  = DN_OID_SZ;
    }
    thisLen++; /* id  type */
    firstSz  = (word32)SetObjectId((int)firstSz, firstLen);
    thisLen += firstSz;

    seqSz = SetSequence(thisLen, sequence);
    thisLen += seqSz;
    setSz = SetSet(thisLen, set);
    thisLen += setSz;

    if (thisLen > (int)sizeof(name->encoded)) {
        return BUFFER_E;
    }

    /* store it */
    idx = 0;
    /* set */
    XMEMCPY(name->encoded, set, setSz);
    idx += setSz;
    /* seq */
    XMEMCPY(name->encoded + idx, sequence, seqSz);
    idx += seqSz;
    /* asn object id */
    XMEMCPY(name->encoded + idx, firstLen, firstSz);
    idx += firstSz;
    switch (type) {
        case ASN_EMAIL_NAME:
            /* email joint id */
            XMEMCPY(name->encoded + idx, attrEmailOid, sizeof(attrEmailOid));
            idx += (int)sizeof(attrEmailOid);
            name->encoded[idx++] = emailTag;
            break;
        case ASN_DOMAIN_COMPONENT:
            XMEMCPY(name->encoded + idx, dcOid, sizeof(dcOid)-1);
            idx += (int)sizeof(dcOid)-1;
            /* id type */
            name->encoded[idx++] = type;
            /* str type */
            name->encoded[idx++] = nameTag;
            break;
        case ASN_USER_ID:
            XMEMCPY(name->encoded + idx, uidOid, sizeof(uidOid));
            idx += (int)sizeof(uidOid);
            /* str type */
            name->encoded[idx++] = nameTag;
            break;
        case ASN_FAVOURITE_DRINK:
            XMEMCPY(name->encoded + idx, fvrtDrk, sizeof(fvrtDrk));
            idx += (int)sizeof(fvrtDrk);
            /* str type */
            name->encoded[idx++] = nameTag;
            break;
    #ifdef WOLFSSL_CUSTOM_OID
        case ASN_CUSTOM_NAME:
            XMEMCPY(name->encoded + idx, cname->custom.oid,
                    cname->custom.oidSz);
            idx += cname->custom.oidSz;
            /* str type */
            name->encoded[idx++] = nameTag;
            break;
    #endif
        default:
            name->encoded[idx++] = 0x55;
            name->encoded[idx++] = 0x04;
            /* id type */
            name->encoded[idx++] = type;
            /* str type */
            name->encoded[idx++] = nameTag;
    }
    /* second length */
    XMEMCPY(name->encoded + idx, secondLen, secondSz);
    idx += secondSz;
    /* str value */
    XMEMCPY(name->encoded + idx, nameStr, strLen);
    idx += strLen;

    name->type = type;
    name->totalLen = (int)idx;
    name->used = 1;

    return (int)idx;
#else
    DECL_ASNSETDATA(dataASN, rdnASN_Length);
    ASNItem namesASN[rdnASN_Length];
    byte dnOid[DN_OID_SZ] = { 0x55, 0x04, 0x00 };
    int ret = 0;
    int sz = 0;
    const byte* oid;
    word32 oidSz;
    word32 nameSz;

    /* Validate input parameters. */
    if ((name == NULL) || (nameStr == NULL)) {
        ret = BAD_FUNC_ARG;
    }

    CALLOC_ASNSETDATA(dataASN, rdnASN_Length, ret, NULL);
    if (ret == 0) {
        nameSz = (word32)XSTRLEN(nameStr);
        /* Copy the RDN encoding template. ASN.1 tag for the name string is set
         * based on type. */
        XMEMCPY(namesASN, rdnASN, sizeof(namesASN));

        /* Set OID and ASN.1 tag for name depending on type. */
        switch (type) {
            case ASN_EMAIL_NAME:
                /* email OID different to standard types. */
                oid = attrEmailOid;
                oidSz = sizeof(attrEmailOid);
                /* Use email specific type/tag. */
                nameTag = emailTag;
                break;
            case ASN_DOMAIN_COMPONENT:
                /* Domain component OID different to standard types. */
                oid = dcOid;
                oidSz = sizeof(dcOid);
                break;
            case ASN_USER_ID:
                /* Domain component OID different to standard types. */
                oid = uidOid;
                oidSz = sizeof(uidOid);
                break;
            case ASN_FAVOURITE_DRINK:
                oid = fvrtDrk;
                oidSz = sizeof(fvrtDrk);
                break;
        #ifdef WOLFSSL_CUSTOM_OID
            case ASN_CUSTOM_NAME:
                nameSz = cname->custom.valSz;
                oid = cname->custom.oid;
                oidSz = cname->custom.oidSz;
                break;
        #endif
            default:
                /* Construct OID using type. */
                dnOid[2] = type;
                oid = dnOid;
                oidSz = DN_OID_SZ;
                break;
        }

        /* Set OID corresponding to the name type. */
        SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_TYPE], oid, oidSz);
        /* Set name string. */
        SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_VAL], (const byte *)nameStr, nameSz);
        /* Set the ASN.1 tag for the name string. */
        namesASN[RDNASN_IDX_ATTR_VAL].tag = nameTag;

        /* Calculate size of encoded name and indexes of components. */
        ret = SizeASN_Items(namesASN, dataASN, rdnASN_Length, &sz);
    }
    /* Check if name's buffer is big enough. */
    if ((ret == 0) && (sz > (int)sizeof(name->encoded))) {
        ret = BUFFER_E;
    }
    if (ret == 0) {
        /* Encode name into the buffer. */
        SetASN_Items(namesASN, dataASN, rdnASN_Length, name->encoded);
        /* Cache the type and size, and set that it is used. */
        name->type = type;
        name->totalLen = sz;
        name->used = 1;

        /* Return size of encoding. */
        ret = sz;
    }
    (void)cname;

    FREE_ASNSETDATA(dataASN, NULL);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

/* canonical encoding one attribute of the name (issuer/subject)
 * call EncodeName with CTC_UTF8 for email type
 *
 * name     structure to hold result of encoding
 * nameStr  value to be encoded
 * nameType type of encoding i.e CTC_UTF8
 * type     id of attribute i.e ASN_COMMON_NAME
 *
 * returns length on success
 */
int wc_EncodeNameCanonical(EncodedName* name, const char* nameStr,
                           char nameType, byte type)
{
    return EncodeName(name, nameStr, (byte)nameType, type,
        ASN_UTF8STRING, NULL);
}
#endif /* WOLFSSL_CERT_GEN || OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */

#ifdef WOLFSSL_CERT_GEN
/* Encodes one attribute of the name (issuer/subject)
 * call we_EncodeName_ex with 0x16, IA5String for email type
 * name     structure to hold result of encoding
 * nameStr  value to be encoded
 * nameType type of encoding i.e CTC_UTF8
 * type     id of attribute i.e ASN_COMMON_NAME
 *
 * returns length on success
 */
int wc_EncodeName(EncodedName* name, const char* nameStr, char nameType,
                  byte type)
{
    return EncodeName(name, nameStr, (byte)nameType, type,
        ASN_IA5_STRING, NULL);
}

#ifdef WOLFSSL_ASN_TEMPLATE
static void SetRdnItems(ASNItem* namesASN, ASNSetData* dataASN, const byte* oid,
    word32 oidSz, byte tag, const byte* data, word32 sz)
{
    XMEMCPY(namesASN, rdnASN, sizeof(rdnASN));
    SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_TYPE], oid, oidSz);
    namesASN[RDNASN_IDX_ATTR_VAL].tag = tag;
    SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_VAL], data, sz);
}

#ifdef WOLFSSL_MULTI_ATTRIB
static int FindMultiAttrib(CertName* name, int id, int* idx)
{
    int i;
    for (i = *idx + 1; i < CTC_MAX_ATTRIB; i++) {
        if (name->name[i].sz > 0 && name->name[i].id == id) {
            break;
        }
    }
    if (i == CTC_MAX_ATTRIB) {
        i = -1;
    }
    *idx = i;
    return i >= 0;
}
#endif

/* ASN.1 template for the SEQUENCE around the RDNs.
 * X.509: RFC 5280, 4.1.2.4 - RDNSequence
 */
static const ASNItem nameASN[] = {
    { 0, ASN_SEQUENCE, 1, 1, 0 },
};
enum {
    NAMEASN_IDX_SEQ = 0
};

/* Number of items in ASN.1 template for the SEQUENCE around the RDNs. */
#define nameASN_Length (sizeof(nameASN) / sizeof(ASNItem))

static int SetNameRdnItems(ASNSetData* dataASN, ASNItem* namesASN,
        int maxIdx, CertName* name)
{
    int         i;
    int         idx;
    int         ret = 0;
    word32      nameLen[NAME_ENTRIES];
#ifdef WOLFSSL_MULTI_ATTRIB
    int         j;
#endif

    for (i = 0; i < NAME_ENTRIES; i++) {
        /* Keep name length to identify component is to be encoded. */
        const char* nameStr = GetOneCertName(name, i);
        nameLen[i] = nameStr ? (word32)XSTRLEN(nameStr) : 0;
    }

    idx = nameASN_Length;
    for (i = 0; i < NAME_ENTRIES; i++) {
        int type = GetCertNameId(i);

    #ifdef WOLFSSL_MULTI_ATTRIB
        j = -1;
        /* Put DomainComponents before OrgUnitName. */
        while (FindMultiAttrib(name, type, &j)) {
            if (GetCertNameId(i) != ASN_DOMAIN_COMPONENT) {
                continue;
            }
            if (dataASN != NULL && namesASN != NULL) {
                if (idx > maxIdx - (int)rdnASN_Length) {
                    WOLFSSL_MSG("Wanted to write more ASN than allocated");
                    ret = BUFFER_E;
                    break;
                }
                /* Copy data into dynamic vars. */
                SetRdnItems(namesASN + idx, dataASN + idx, dcOid,
                            sizeof(dcOid), (byte)name->name[j].type,
                            (byte*)name->name[j].value,
                            (word32)name->name[j].sz);
            }
            idx += (int)rdnASN_Length;
        }
        if (ret != 0)
            break;
    #endif

        if (nameLen[i] > 0) {
            if (dataASN != NULL) {
                if (idx > maxIdx - (int)rdnASN_Length) {
                    WOLFSSL_MSG("Wanted to write more ASN than allocated");
                    ret = BUFFER_E;
                    break;
                }
                /* Write out first instance of attribute type. */
                if (type == ASN_EMAIL_NAME) {
                    /* Copy email data into dynamic vars. */
                    SetRdnItems(namesASN + idx, dataASN + idx, attrEmailOid,
                        sizeof(attrEmailOid), ASN_IA5_STRING,
                        (const byte*)GetOneCertName(name, i), nameLen[i]);
                }
                else if (type == ASN_USER_ID) {
                    /* Copy userID data into dynamic vars. */
                    SetRdnItems(namesASN + idx, dataASN + idx, uidOid,
                                sizeof(uidOid), (byte)GetNameType(name, i),
                        (const byte*)GetOneCertName(name, i), nameLen[i]);
                }
                else if (type == ASN_FAVOURITE_DRINK) {
                    /* Copy favourite drink data into dynamic vars. */
                    SetRdnItems(namesASN + idx, dataASN + idx, fvrtDrk,
                                sizeof(fvrtDrk), (byte)GetNameType(name, i),
                        (const byte*)GetOneCertName(name, i), nameLen[i]);
                }
                else if (type == ASN_CUSTOM_NAME) {
                #ifdef WOLFSSL_CUSTOM_OID
                    SetRdnItems(namesASN + idx, dataASN + idx, name->custom.oid,
                        name->custom.oidSz, name->custom.enc,
                        name->custom.val, name->custom.valSz);
                #endif
                }
                else {
                    /* Copy name data into dynamic vars. */
                    SetRdnItems(namesASN + idx, dataASN + idx, nameOid[i],
                        NAME_OID_SZ, (byte)GetNameType(name, i),
                        (const byte*)GetOneCertName(name, i), nameLen[i]);
                }
            }
            idx += (int)rdnASN_Length;
        }

    #ifdef WOLFSSL_MULTI_ATTRIB
        j = -1;
        /* Write all other attributes of this type. */
        while (FindMultiAttrib(name, type, &j)) {
            if (GetCertNameId(i) == ASN_DOMAIN_COMPONENT) {
                continue;
            }
            if (dataASN != NULL && namesASN != NULL) {
                if (idx > maxIdx - (int)rdnASN_Length) {
                    WOLFSSL_MSG("Wanted to write more ASN than allocated");
                    ret = BUFFER_E;
                    break;
                }
                /* Copy data into dynamic vars. */
                SetRdnItems(namesASN + idx, dataASN + idx, nameOid[i],
                    NAME_OID_SZ, (byte)name->name[j].type,
                    (byte*)name->name[j].value, (word32)name->name[j].sz);
            }
            idx += (int)rdnASN_Length;
        }
        if (ret != 0)
            break;
    #endif
    }
    if (ret == 0)
        ret = idx;
    return ret;
}
#endif

/* encode CertName into output, return total bytes written */
int SetNameEx(byte* output, word32 outputSz, CertName* name, void* heap)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int ret;
    int i;
    word32 idx, totalBytes = 0;
#ifdef WOLFSSL_SMALL_STACK
    EncodedName* names = NULL;
#else
    EncodedName  names[NAME_ENTRIES];
#endif
#ifdef WOLFSSL_MULTI_ATTRIB
    EncodedName addNames[CTC_MAX_ATTRIB];
    int j, type;
#endif

    if (output == NULL || name == NULL)
        return BAD_FUNC_ARG;

    if (outputSz < 3)
        return BUFFER_E;

#ifdef WOLFSSL_SMALL_STACK
    names = (EncodedName*)XMALLOC(sizeof(EncodedName) * NAME_ENTRIES, NULL,
                                                       DYNAMIC_TYPE_TMP_BUFFER);
    if (names == NULL)
        return MEMORY_E;
#endif

    for (i = 0; i < NAME_ENTRIES; i++) {
        const char* nameStr = GetOneCertName(name, i);

        ret = EncodeName(&names[i], nameStr, (byte)GetNameType(name, i),
                          GetCertNameId(i), ASN_IA5_STRING, name);
        if (ret < 0) {
        #ifdef WOLFSSL_SMALL_STACK
            XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
        #endif
            WOLFSSL_MSG("EncodeName failed");
            return BUFFER_E;
        }
        totalBytes += (word32)ret;
    }
#ifdef WOLFSSL_MULTI_ATTRIB
    for (i = 0; i < CTC_MAX_ATTRIB; i++) {
        if (name->name[i].sz > 0) {
            ret = EncodeName(&addNames[i], name->name[i].value,
                             (byte)name->name[i].type, (byte)name->name[i].id,
                        ASN_IA5_STRING, NULL);
            if (ret < 0) {
            #ifdef WOLFSSL_SMALL_STACK
                XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
            #endif
                WOLFSSL_MSG("EncodeName on multiple attributes failed");
                return BUFFER_E;
            }
            totalBytes += (word32)ret;
        }
        else {
            addNames[i].used = 0;
        }
    }
#endif /* WOLFSSL_MULTI_ATTRIB */

    /* header */
    idx = SetSequence(totalBytes, output);
    totalBytes += idx;
    if (totalBytes > WC_ASN_NAME_MAX) {
#ifdef WOLFSSL_SMALL_STACK
        XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
        WOLFSSL_MSG("Total Bytes is greater than WC_ASN_NAME_MAX");
        return BUFFER_E;
    }

    for (i = 0; i < NAME_ENTRIES; i++) {
    #ifdef WOLFSSL_MULTI_ATTRIB
        type = GetCertNameId(i);
        for (j = 0; j < CTC_MAX_ATTRIB; j++) {
            if (name->name[j].sz > 0 && type == name->name[j].id) {
                if (outputSz < idx + (word32)addNames[j].totalLen) {
                #ifdef WOLFSSL_SMALL_STACK
                    XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
                #endif
                    WOLFSSL_MSG("Not enough space left for DC value");
                    return BUFFER_E;
                }

                XMEMCPY(output + idx, addNames[j].encoded,
                        (size_t)addNames[j].totalLen);
                idx += (word32)addNames[j].totalLen;
            }
        }
    #endif /* WOLFSSL_MULTI_ATTRIB */

        if (names[i].used) {
            if (outputSz < idx + (word32)names[i].totalLen) {
#ifdef WOLFSSL_SMALL_STACK
                XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
                return BUFFER_E;
            }

            XMEMCPY(output + idx, names[i].encoded, (size_t)names[i].totalLen);
            idx += (word32)names[i].totalLen;
        }
    }

#ifdef WOLFSSL_SMALL_STACK
    XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif
    (void)heap;

    return (int)totalBytes;
#else
    /* TODO: consider calculating size of entries, putting length into
     * SEQUENCE, encode SEQUENCE, encode entries into buffer.  */
    ASNSetData* dataASN = NULL; /* Can't use DECL_ASNSETDATA. Always dynamic. */
    ASNItem*    namesASN = NULL;
    word32      items = 0;
    int         ret = 0;
    int         sz = 0;

    /* Calculate length of name entries and size for allocating. */
    ret = SetNameRdnItems(NULL, NULL, 0, name);
    if (ret > 0) {
        items = (word32)ret;
        ret = 0;
    }

    /* Allocate dynamic data items. */
    dataASN = (ASNSetData*)XMALLOC(items * sizeof(ASNSetData), heap,
                                   DYNAMIC_TYPE_TMP_BUFFER);
    if (dataASN == NULL) {
        ret = MEMORY_E;
    }
    else {
        /* Allocate dynamic ASN.1 template items. */
        namesASN = (ASNItem*)XMALLOC(items * sizeof(ASNItem), heap,
                                     DYNAMIC_TYPE_TMP_BUFFER);
        if (namesASN == NULL) {
            ret = MEMORY_E;
        }
    }

    if (ret == 0) {
        /* Clear the dynamic data. */
        XMEMSET(dataASN, 0, items * sizeof(ASNSetData));
        /* Copy in the outer sequence. */
        XMEMCPY(namesASN, nameASN, sizeof(nameASN));

        ret = SetNameRdnItems(dataASN, namesASN, (int)items, name);
        if (ret == (int)items)
            ret = 0;
        else if (ret > 0) {
            WOLFSSL_MSG("SetNameRdnItems returned different length");
            ret = BUFFER_E;
        }
    }
    if (ret == 0) {
        /* Calculate size of encoding. */
        ret = SizeASN_Items(namesASN, dataASN, (int)items, &sz);
    }
    /* Check buffer size if passed in. */
    if (ret == 0 && output != NULL && sz > (int)outputSz) {
        ret = BUFFER_E;
    }
    if (ret == 0) {
        if (output != NULL) {
            /* Encode Name. */
            ret = SetASN_Items(namesASN, dataASN, (int)items, output);
        }
        else {
            /* Return the encoding size. */
            ret = sz;
        }
    }

    if (namesASN != NULL)
        XFREE(namesASN, heap, DYNAMIC_TYPE_TMP_BUFFER);
    if (dataASN != NULL)
        XFREE(dataASN, heap, DYNAMIC_TYPE_TMP_BUFFER);
    (void)heap;
    return ret;
#endif
}
int SetName(byte* output, word32 outputSz, CertName* name)
{
    return SetNameEx(output, outputSz, name, NULL);
}

#ifdef WOLFSSL_ASN_TEMPLATE
static int EncodePublicKey(int keyType, byte* output, int outLen,
                           RsaKey* rsaKey, ecc_key* eccKey,
                           ed25519_key* ed25519Key, ed448_key* ed448Key,
                           DsaKey* dsaKey)
{
    int ret = 0;

    (void)outLen;
    (void)rsaKey;
    (void)eccKey;
    (void)ed25519Key;
    (void)ed448Key;
    (void)dsaKey;

    switch (keyType) {
    #ifndef NO_RSA
        case RSA_KEY:
            ret = SetRsaPublicKey(output, rsaKey, outLen, 1);
            if (ret <= 0) {
                ret = PUBLIC_KEY_E;
            }
            break;
    #endif
    #ifdef HAVE_ECC
        case ECC_KEY:
            ret = SetEccPublicKey(output, eccKey, outLen, 1, 0);
            if (ret <= 0) {
                ret = PUBLIC_KEY_E;
            }
            break;
    #endif /* HAVE_ECC */
    #ifdef HAVE_ED25519
        case ED25519_KEY:
            ret = wc_Ed25519PublicKeyToDer(ed25519Key, output,
                                           (word32)outLen, 1);
            if (ret <= 0) {
                ret = PUBLIC_KEY_E;
            }
            break;
    #endif
    #ifdef HAVE_ED448
        case ED448_KEY:
            ret = wc_Ed448PublicKeyToDer(ed448Key, output, (word32)outLen, 1);
            if (ret <= 0) {
                ret = PUBLIC_KEY_E;
            }
            break;
    #endif
        default:
            ret = PUBLIC_KEY_E;
            break;
    }

    return ret;
}

/* ASN.1 template for certificate extensions.
 * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
 * All extensions supported for encoding are described.
 */
static const ASNItem static_certExtsASN[] = {
            /* Basic Constraints Extension - 4.2.1.9 */
/* BC_SEQ        */    { 0, ASN_SEQUENCE, 1, 1, 0 },
/* BC_OID        */        { 1, ASN_OBJECT_ID, 0, 0, 0 },
/* BC_STR        */        { 1, ASN_OCTET_STRING, 0, 1, 0 },
/* BC_STR_SEQ    */            { 2, ASN_SEQUENCE, 1, 1, 0 },
                                                   /* cA */
/* BC_CA         */                { 3, ASN_BOOLEAN, 0, 0, 0 },
                                                   /* pathLenConstraint */
/* BC_PATHLEN    */                { 3, ASN_INTEGER, 0, 0, 1 },
                                       /* Subject Alternative Name - 4.2.1.6  */
/* SAN_SEQ       */    { 0, ASN_SEQUENCE, 1, 1, 0 },
/* SAN_OID       */        { 1, ASN_OBJECT_ID, 0, 0, 0 },
/* SAN_CRIT      */        { 1, ASN_BOOLEAN, 0, 0, 0 },
/* SAN_STR       */        { 1, ASN_OCTET_STRING, 0, 0, 0 },
            /* Subject Key Identifier - 4.2.1.2 */
/* SKID_SEQ      */    { 0, ASN_SEQUENCE, 1, 1, 0 },
/* SKID_OID      */        { 1, ASN_OBJECT_ID, 0, 0, 0 },
/* SKID_STR      */        { 1, ASN_OCTET_STRING, 0, 1, 0 },
/* SKID_KEYID    */            { 2, ASN_OCTET_STRING, 0, 0, 0 },
                                       /* Authority Key Identifier - 4.2.1.1 */
/* AKID_SEQ      */    { 0, ASN_SEQUENCE, 1, 1, 0 },
/* AKID_OID      */        { 1, ASN_OBJECT_ID, 0, 0, 0 },
/* AKID_STR      */        { 1, ASN_OCTET_STRING, 0, 1, 0 },
/* AKID_STR_SEQ, */            { 2, ASN_SEQUENCE, 1, 1, 0 },
/* AKID_KEYID    */                { 3, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
                                       /* Key Usage - 4.2.1.3 */
/* KU_SEQ        */    { 0, ASN_SEQUENCE, 1, 1, 0 },
/* KU_OID        */        { 1, ASN_OBJECT_ID, 0, 0, 0 },
/* KU_CRIT       */        { 1, ASN_BOOLEAN, 0, 0, 0 },
/* KU_STR        */        { 1, ASN_OCTET_STRING, 0, 1, 0 },
/* KU_USAGE      */            { 2, ASN_BIT_STRING, 0, 0, 0 },
                                       /* Extended Key Usage - 4,2,1,12 */
/* EKU_SEQ       */    { 0, ASN_SEQUENCE, 1, 1, 0 },
/* EKU_OID       */        { 1, ASN_OBJECT_ID, 0, 0, 0 },
/* EKU_STR       */        { 1, ASN_OCTET_STRING, 0, 0, 0 },
                                       /* Certificate Policies - 4.2.1.4 */
/* POLICIES_SEQ, */    { 0, ASN_SEQUENCE, 1, 1, 0 },
/* POLICIES_OID, */        { 1, ASN_OBJECT_ID, 0, 0, 0 },
/* POLICIES_STR, */        { 1, ASN_OCTET_STRING, 0, 1, 0 },
/* POLICIES_INFO */            { 2, ASN_SEQUENCE, 1, 0, 0 },
                                       /* Netscape Certificate Type */
/* NSTYPE_SEQ    */    { 0, ASN_SEQUENCE, 1, 1, 0 },
/* NSTYPE_OID    */        { 1, ASN_OBJECT_ID, 0, 0, 0 },
/* NSTYPE_STR    */        { 1, ASN_OCTET_STRING, 0, 1, 0 },
/* NSTYPE_USAGE, */            { 2, ASN_BIT_STRING, 0, 0, 0 },
/* CRLINFO_SEQ   */    { 0, ASN_SEQUENCE, 1, 1, 0 },
/* CRLINFO_OID   */        { 1, ASN_OBJECT_ID, 0, 0, 0 },
/* CRLINFO_STR   */        { 1, ASN_OCTET_STRING, 0, 0, 0 },
/* CUSTOM_SEQ    */    { 0, ASN_SEQUENCE, 1, 1, 0 },
/* CUSTOM_OID    */        { 1, ASN_OBJECT_ID, 0, 0, 0 },
/* CUSTOM_STR    */        { 1, ASN_OCTET_STRING, 0, 0, 0 },
};
enum {
    CERTEXTSASN_IDX_BC_SEQ = 0,
    CERTEXTSASN_IDX_BC_OID,
    CERTEXTSASN_IDX_BC_STR,
    CERTEXTSASN_IDX_BC_STR_SEQ,
    CERTEXTSASN_IDX_BC_CA,
    CERTEXTSASN_IDX_BC_PATHLEN,
    CERTEXTSASN_IDX_SAN_SEQ,
    CERTEXTSASN_IDX_SAN_OID,
    CERTEXTSASN_IDX_SAN_CRIT,
    CERTEXTSASN_IDX_SAN_STR,
    CERTEXTSASN_IDX_SKID_SEQ,
    CERTEXTSASN_IDX_SKID_OID,
    CERTEXTSASN_IDX_SKID_STR,
    CERTEXTSASN_IDX_SKID_KEYID,
    CERTEXTSASN_IDX_AKID_SEQ,
    CERTEXTSASN_IDX_AKID_OID,
    CERTEXTSASN_IDX_AKID_STR,
    CERTEXTSASN_IDX_AKID_STR_SEQ,
    CERTEXTSASN_IDX_AKID_KEYID,
    CERTEXTSASN_IDX_KU_SEQ,
    CERTEXTSASN_IDX_KU_OID,
    CERTEXTSASN_IDX_KU_CRIT,
    CERTEXTSASN_IDX_KU_STR,
    CERTEXTSASN_IDX_KU_USAGE,
    CERTEXTSASN_IDX_EKU_SEQ,
    CERTEXTSASN_IDX_EKU_OID,
    CERTEXTSASN_IDX_EKU_STR,
    CERTEXTSASN_IDX_POLICIES_SEQ,
    CERTEXTSASN_IDX_POLICIES_OID,
    CERTEXTSASN_IDX_POLICIES_STR,
    CERTEXTSASN_IDX_POLICIES_INFO,
    CERTEXTSASN_IDX_NSTYPE_SEQ,
    CERTEXTSASN_IDX_NSTYPE_OID,
    CERTEXTSASN_IDX_NSTYPE_STR,
    CERTEXTSASN_IDX_NSTYPE_USAGE,
    CERTEXTSASN_IDX_CRLINFO_SEQ,
    CERTEXTSASN_IDX_CRLINFO_OID,
    CERTEXTSASN_IDX_CRLINFO_STR,
    CERTEXTSASN_IDX_CUSTOM_SEQ,
    CERTEXTSASN_IDX_CUSTOM_OID,
    CERTEXTSASN_IDX_CUSTOM_STR,
    CERTEXTSASN_IDX_START_CUSTOM
};

/* Number of items in ASN.1 template for certificate extensions. We multiply
 * by 4 because there are 4 things (seq, OID, crit flag, octet string). */
#define certExtsASN_Length ((sizeof(static_certExtsASN) / sizeof(ASNItem)) \
                            + (NUM_CUSTOM_EXT * 4))

static const ASNItem customExtASN[] = {
/* CUSTOM_SEQ    */    { 0, ASN_SEQUENCE, 1, 1, 0 },
/* CUSTOM_OID    */        { 1, ASN_OBJECT_ID, 0, 0, 0 },
/* CUSTOM_CRIT   */        { 1, ASN_BOOLEAN, 0, 0, 0 },
/* CUSTOM_STR    */        { 1, ASN_OCTET_STRING, 0, 0, 0 },
};

static int EncodeExtensions(Cert* cert, byte* output, word32 maxSz,
                            int forRequest)
{
    DECL_ASNSETDATA(dataASN, certExtsASN_Length);
    int sz;
    int ret = 0;
    int i = 0;
    static const byte bcOID[]   = { 0x55, 0x1d, 0x13 };
#ifdef WOLFSSL_ALT_NAMES
    static const byte sanOID[]  = { 0x55, 0x1d, 0x11 };
#endif
#ifdef WOLFSSL_CERT_EXT
    static const byte skidOID[] = { 0x55, 0x1d, 0x0e };
    static const byte akidOID[] = { 0x55, 0x1d, 0x23 };
    static const byte kuOID[]   = { 0x55, 0x1d, 0x0f };
    static const byte ekuOID[]  = { 0x55, 0x1d, 0x25 };
    static const byte cpOID[]   = { 0x55, 0x1d, 0x20 };
    static const byte nsCertOID[] = { 0x60, 0x86, 0x48, 0x01,
                                      0x86, 0xF8, 0x42, 0x01, 0x01 };
    static const byte crlInfoOID[] = { 0x55, 0x1D, 0x1F };
#endif

#ifdef WOLFSSL_SMALL_STACK
#if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
    byte *encodedOids;
#endif
    ASNItem *certExtsASN = (ASNItem *)XMALLOC(certExtsASN_Length *
                                              sizeof(ASNItem), cert->heap,
                                              DYNAMIC_TYPE_TMP_BUFFER);
    if (certExtsASN == NULL) {
        return MEMORY_E;
    }

#if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
    encodedOids = (byte *)XMALLOC(NUM_CUSTOM_EXT * MAX_OID_SZ, cert->heap,
                                  DYNAMIC_TYPE_TMP_BUFFER);
    if (encodedOids == NULL) {
        XFREE(certExtsASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
        return MEMORY_E;
    }
#endif
#else
    ASNItem certExtsASN[certExtsASN_Length];
#if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
    byte encodedOids[NUM_CUSTOM_EXT * MAX_OID_SZ];
#endif
#endif

    /* Clone static_certExtsASN into a certExtsASN and then fill the rest of it
     * with (NUM_CUSTOM_EXT*4) more ASNItems specifying extensions. See comment
     * above definition of certExtsASN_Length. */
    XMEMCPY(certExtsASN, static_certExtsASN, sizeof(static_certExtsASN));
    for (i = sizeof(static_certExtsASN) / sizeof(ASNItem);
         i < (int)certExtsASN_Length; i += 4) {
        XMEMCPY(&certExtsASN[i], customExtASN, sizeof(customExtASN));
    }

    (void)forRequest;

    CALLOC_ASNSETDATA(dataASN, certExtsASN_Length, ret, cert->heap);

    if (ret == 0) {
        if (cert->isCA) {
            /* Set Basic Constraints to be a Certificate Authority. */
            SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_BC_CA], 1);
            SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_BC_OID], bcOID, sizeof(bcOID));
            if (cert->pathLenSet
            #ifdef WOLFSSL_CERT_EXT
                && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
            #endif
            ) {
                SetASN_Int8Bit(&dataASN[CERTEXTSASN_IDX_BC_PATHLEN],
                        cert->pathLen);
            }
            else {
                dataASN[CERTEXTSASN_IDX_BC_PATHLEN].noOut = 1;
            }
        }
        else if (cert->basicConstSet) {
            /* Set Basic Constraints to be a non Certificate Authority. */
            SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_BC_OID], bcOID, sizeof(bcOID));
            dataASN[CERTEXTSASN_IDX_BC_CA].noOut = 1;
            dataASN[CERTEXTSASN_IDX_BC_PATHLEN].noOut = 1;
        }
        else {
            /* Don't write out Basic Constraints extension items. */
            SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_BC_SEQ,
                    CERTEXTSASN_IDX_BC_PATHLEN);
        }
    #ifdef WOLFSSL_ALT_NAMES
        if (cert->altNamesSz > 0) {
            /* Set Subject Alternative Name OID and data. */
            SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SAN_OID],
                    sanOID, sizeof(sanOID));
            if (cert->altNamesCrit) {
                SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_SAN_CRIT], 1);
            }
            else {
                dataASN[CERTEXTSASN_IDX_SAN_CRIT].noOut = 1;
            }
            SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SAN_STR],
                          cert->altNames, (word32)cert->altNamesSz);
        }
        else
    #endif
        {
            /* Don't write out Subject Alternative Name extension items. */
            SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_SAN_SEQ,
                    CERTEXTSASN_IDX_SAN_STR);
        }
    #ifdef WOLFSSL_CERT_EXT
        if (cert->skidSz > 0) {
            /* Set Subject Key Identifier OID and data. */
            SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SKID_OID],
                    skidOID, sizeof(skidOID));
            SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SKID_KEYID],
                          cert->skid, (word32)cert->skidSz);
        }
        else
    #endif
        {
            /* Don't write out Subject Key Identifier extension items. */
            SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_SKID_SEQ,
                    CERTEXTSASN_IDX_SKID_KEYID);
        }
    #ifdef WOLFSSL_CERT_EXT
        if (cert->akidSz > 0) {
            /* Set Authority Key Identifier OID and data. */
            SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_OID],
                    akidOID, sizeof(akidOID));
        #ifdef WOLFSSL_AKID_NAME
            if (cert->rawAkid) {
                SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_STR],
                        cert->akid, cert->akidSz);
                /* cert->akid contains the internal ext structure */
                SetASNItem_NoOutBelow(dataASN, certExtsASN,
                        CERTEXTSASN_IDX_AKID_STR, certExtsASN_Length);
            }
            else
        #endif
            {
                SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_KEYID],
                        cert->akid, (word32)cert->akidSz);
            }
        }
        else
    #endif
        {
            /* Don't write out Authority Key Identifier extension items. */
            SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_AKID_SEQ,
                    CERTEXTSASN_IDX_AKID_KEYID);
        }
    #ifdef WOLFSSL_CERT_EXT
        if (cert->keyUsage != 0) {
            /* Set Key Usage OID, critical and value. */
            SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_KU_OID],
                    kuOID, sizeof(kuOID));
            SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_KU_CRIT], 1);
            SetASN_Int16Bit(&dataASN[CERTEXTSASN_IDX_KU_USAGE],
                    cert->keyUsage);
        }
        else
    #endif
        {
            /* Don't write out Key Usage extension items. */
            SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_KU_SEQ,
                    CERTEXTSASN_IDX_KU_USAGE);
        }
    #ifdef WOLFSSL_CERT_EXT
        if (cert->extKeyUsage != 0) {
            /* Calculate size of Extended Key Usage data. */
            sz = SetExtKeyUsage(cert, NULL, 0, cert->extKeyUsage);
            if (sz <= 0) {
                ret = KEYUSAGE_E;
            }
            /* Set Extended Key Usage OID and data. */
            SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_EKU_OID],
                    ekuOID, sizeof(ekuOID));
            SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_EKU_STR],
                    NULL, (word32)sz);
        }
        else
    #endif
        {
            /* Don't write out Extended Key Usage extension items. */
            SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_EKU_SEQ,
                    CERTEXTSASN_IDX_EKU_STR);
        }

    #ifdef WOLFSSL_CERT_EXT
        if ((!forRequest) && (cert->certPoliciesNb > 0)) {
            /* Calculate size of certificate policies. */
            sz = SetCertificatePolicies(NULL, 0, cert->certPolicies,
                    cert->certPoliciesNb, cert->heap);
            if (sz > 0) {
                /* Set Certificate Policies OID. */
                SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_POLICIES_OID],
                        cpOID, sizeof(cpOID));
                /* Make space for data. */
                SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_POLICIES_INFO],
                        NULL, (word32)sz);
            }
            else {
                ret = CERTPOLICIES_E;
            }
        }
        else
    #endif
        {
            /* Don't write out Certificate Policies extension items. */
            SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_POLICIES_SEQ,
                    CERTEXTSASN_IDX_POLICIES_INFO);
        }
    #if defined(WOLFSSL_CERT_EXT) && !defined(IGNORE_NETSCAPE_CERT_TYPE)
        /* Netscape Certificate Type */
        if (cert->nsCertType != 0) {
            /* Set Netscape Certificate Type OID and data. */
            SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_NSTYPE_OID],
                    nsCertOID, sizeof(nsCertOID));
            SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_NSTYPE_USAGE],
                    &cert->nsCertType, 1);
        }
        else
    #endif
        {
            /* Don't write out Netscape Certificate Type. */
            SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_NSTYPE_SEQ,
                    CERTEXTSASN_IDX_NSTYPE_USAGE);
        }
    #ifdef WOLFSSL_CERT_EXT
        if (cert->crlInfoSz > 0) {
            /* Set CRL Distribution Points OID and data. */
            SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CRLINFO_OID],
                    crlInfoOID, sizeof(crlInfoOID));
            SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CRLINFO_STR],
                    cert->crlInfo, (word32)cert->crlInfoSz);
        }
        else
    #endif
        {
            /* Don't write out CRL Distribution Points. */
            SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_CRLINFO_SEQ,
                    CERTEXTSASN_IDX_CRLINFO_STR);
        }

    #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CUSTOM_OID)
        /* encode a custom oid and value */
        if (cert->extCustom.oidSz > 0) {
            /* Set CRL Distribution Points OID and data. */
            SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CUSTOM_OID],
                    cert->extCustom.oid, cert->extCustom.oidSz);
            SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CUSTOM_STR],
                    cert->extCustom.val, cert->extCustom.valSz);
        }
        else
    #endif
        {
            /* Don't write out custom OID. */
            SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_CUSTOM_SEQ,
                    CERTEXTSASN_IDX_CUSTOM_STR);
        }

        i = 0;
    #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CUSTOM_OID)
        for (; i < cert->customCertExtCount; i++) {
             int idx = CERTEXTSASN_IDX_START_CUSTOM + (i * 4);
             word32 encodedOidSz = MAX_OID_SZ;
             idx++; /* Skip one for for SEQ. */
             /* EncodePolicyOID() will never return error since we parsed this
              * OID when it was set. */
             EncodePolicyOID(&encodedOids[i * MAX_OID_SZ], &encodedOidSz,
                             cert->customCertExt[i].oid, NULL);
             SetASN_Buffer(&dataASN[idx], &encodedOids[i * MAX_OID_SZ],
                           encodedOidSz);
             idx++;
             if (cert->customCertExt[i].crit) {
                 SetASN_Boolean(&dataASN[idx], 1);
             } else {
                 dataASN[idx].noOut = 1;
             }
             idx++;
             SetASN_Buffer(&dataASN[idx], cert->customCertExt[i].val,
                           cert->customCertExt[i].valSz);
        }
    #endif

        while (i < NUM_CUSTOM_EXT) {
            SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_START_CUSTOM + (i * 4),
                             CERTEXTSASN_IDX_START_CUSTOM + (i * 4) + 3);
            i++;
        }
    }

    if (ret == 0) {
        /* Calculate size of encoded extensions. */
        ret = SizeASN_Items(certExtsASN, dataASN, certExtsASN_Length, &sz);
    }
    if (ret == 0) {
        /* Only SEQUENCE - don't encode extensions. */
        if (sz == 2) {
            sz = 0;
        }
        /* Check buffer is big enough. */
        else if ((output != NULL) && (sz > (int)maxSz)) {
            ret = BUFFER_E;
        }
    }

    if ((ret == 0) && (output != NULL) && (sz > 0)) {
        /* Encode certificate extensions into buffer. */
        SetASN_Items(certExtsASN, dataASN, certExtsASN_Length, output);

    #ifdef WOLFSSL_CERT_EXT
        if (cert->extKeyUsage != 0){
            /* Encode Extended Key Usage into space provided. */
            if (SetExtKeyUsage(cert,
                    (byte*)dataASN[CERTEXTSASN_IDX_EKU_STR].data.buffer.data,
                    dataASN[CERTEXTSASN_IDX_EKU_STR].data.buffer.length,
                    cert->extKeyUsage) <= 0) {
                ret = KEYUSAGE_E;
            }
        }
        if ((!forRequest) && (cert->certPoliciesNb > 0)) {
            /* Encode Certificate Policies into space provided. */
            if (SetCertificatePolicies(
                    (byte*)dataASN[CERTEXTSASN_IDX_POLICIES_INFO].data.buffer.data,
                    dataASN[CERTEXTSASN_IDX_POLICIES_INFO].data.buffer.length,
                    cert->certPolicies, cert->certPoliciesNb, cert->heap) <= 0) {
                ret = CERTPOLICIES_E;
            }
        }
    #endif
    }
    if (ret == 0) {
        /* Return the encoding size. */
        ret = sz;
    }

    FREE_ASNSETDATA(dataASN, cert->heap);
#ifdef WOLFSSL_SMALL_STACK
#if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
    XFREE(encodedOids, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
#endif
    XFREE(certExtsASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
#endif

    return ret;
}
#endif /* WOLFSSL_ASN_TEMPLATE */

#ifndef WOLFSSL_ASN_TEMPLATE
/* Set Date validity from now until now + daysValid
 * return size in bytes written to output, 0 on error */
/* TODO https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.2.5
 * "MUST always encode certificate validity dates through the year 2049 as
 *  UTCTime; certificate validity dates in 2050 or later MUST be encoded as
 *  GeneralizedTime." */
static int SetValidity(byte* output, int daysValid)
{
#ifndef NO_ASN_TIME
    byte before[MAX_DATE_SIZE];
    byte  after[MAX_DATE_SIZE];

    word32 beforeSz, afterSz, seqSz;

    time_t now;
    time_t then;
    struct tm* tmpTime;
    struct tm* expandedTime;
    struct tm localTime;

#if defined(NEED_TMP_TIME)
    /* for use with gmtime_r */
    struct tm tmpTimeStorage;
    tmpTime = &tmpTimeStorage;
#else
    tmpTime = NULL;
#endif
    (void)tmpTime;

    now = wc_Time(0);

    /* before now */
    before[0] = ASN_GENERALIZED_TIME;
    beforeSz = SetLength(ASN_GEN_TIME_SZ, before + 1) + 1;  /* gen tag */

    /* subtract 1 day of seconds for more compliance */
    then = now - 86400;
    expandedTime = XGMTIME(&then, tmpTime);
    if (expandedTime == NULL) {
        WOLFSSL_MSG("XGMTIME failed");
        return 0;   /* error */
    }
    localTime = *expandedTime;

    /* adjust */
    localTime.tm_year += 1900;
    localTime.tm_mon +=    1;

    SetTime(&localTime, before + beforeSz);
    beforeSz += ASN_GEN_TIME_SZ;

    after[0] = ASN_GENERALIZED_TIME;
    afterSz  = SetLength(ASN_GEN_TIME_SZ, after + 1) + 1;  /* gen tag */

    /* add daysValid of seconds */
    then = now + (daysValid * (time_t)86400);
    expandedTime = XGMTIME(&then, tmpTime);
    if (expandedTime == NULL) {
        WOLFSSL_MSG("XGMTIME failed");
        return 0;   /* error */
    }
    localTime = *expandedTime;

    /* adjust */
    localTime.tm_year += 1900;
    localTime.tm_mon  +=    1;

    SetTime(&localTime, after + afterSz);
    afterSz += ASN_GEN_TIME_SZ;

    /* headers and output */
    seqSz = SetSequence(beforeSz + afterSz, output);
    XMEMCPY(output + seqSz, before, beforeSz);
    XMEMCPY(output + seqSz + beforeSz, after, afterSz);

    return (int)(seqSz + beforeSz + afterSz);
#else
    (void)output;
    (void)daysValid;
    return NOT_COMPILED_IN;
#endif
}
#else
static int SetValidity(byte* before, byte* after, int daysValid)
{
#ifndef NO_ASN_TIME
    int ret = 0;
    time_t now;
    time_t then;
    struct tm* tmpTime;
    struct tm* expandedTime;
    struct tm localTime;
#if defined(NEED_TMP_TIME)
    /* for use with gmtime_r */
    struct tm tmpTimeStorage;
    tmpTime = &tmpTimeStorage;
#else
    tmpTime = NULL;
#endif
    (void)tmpTime;

    now = wc_Time(0);

    /* subtract 1 day of seconds for more compliance */
    then = now - 86400;
    expandedTime = XGMTIME(&then, tmpTime);
    if (expandedTime == NULL) {
        WOLFSSL_MSG("XGMTIME failed");
        ret = DATE_E;
    }
    if (ret == 0) {
        localTime = *expandedTime;

        /* adjust */
        localTime.tm_year += 1900;
        localTime.tm_mon +=    1;

        SetTime(&localTime, before);

        /* add daysValid of seconds */
        then = now + (daysValid * (time_t)86400);
        expandedTime = XGMTIME(&then, tmpTime);
        if (expandedTime == NULL) {
            WOLFSSL_MSG("XGMTIME failed");
            ret = DATE_E;
        }
    }
    if (ret == 0) {
        localTime = *expandedTime;

        /* adjust */
        localTime.tm_year += 1900;
        localTime.tm_mon  +=    1;

        SetTime(&localTime, after);
    }

    return ret;
#else
    (void)before;
    (void)after;
    (void)daysValid;
    return NOT_COMPILED_IN;
#endif
}
#endif /* WOLFSSL_ASN_TEMPLATE */


#ifndef WOLFSSL_ASN_TEMPLATE
/* encode info from cert into DER encoded format */
static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey,
                      WC_RNG* rng, DsaKey* dsaKey, ed25519_key* ed25519Key,
                      ed448_key* ed448Key, falcon_key* falconKey,
                      dilithium_key* dilithiumKey, sphincs_key* sphincsKey)
{
    int ret;

    if (cert == NULL || der == NULL || rng == NULL)
        return BAD_FUNC_ARG;

    /* make sure at least one key type is provided */
    if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
        dsaKey == NULL && ed448Key == NULL && falconKey == NULL &&
        dilithiumKey == NULL && sphincsKey == NULL) {
        return PUBLIC_KEY_E;
    }

    /* init */
    XMEMSET(der, 0, sizeof(DerCert));

    /* version */
    der->versionSz = SetMyVersion((word32)cert->version, der->version, TRUE);

    /* serial number (must be positive) */
    if (cert->serialSz == 0) {
        /* generate random serial */
        cert->serialSz = CTC_GEN_SERIAL_SZ;
        ret = wc_RNG_GenerateBlock(rng, cert->serial, (word32)cert->serialSz);
        if (ret != 0)
            return ret;
        /* Clear the top bit to avoid a negative value */
        cert->serial[0] &= 0x7f;
    }
    der->serialSz = SetSerialNumber(cert->serial, (word32)cert->serialSz,
                                    der->serial, sizeof(der->serial),
                                    CTC_SERIAL_SIZE);
    if (der->serialSz < 0)
        return der->serialSz;

    /* signature algo */
    der->sigAlgoSz = (int)SetAlgoID(cert->sigType, der->sigAlgo, oidSigType, 0);
    if (der->sigAlgoSz <= 0)
        return ALGO_ID_E;

    /* public key */
#ifndef NO_RSA
    if (cert->keyType == RSA_KEY) {
        if (rsaKey == NULL)
            return PUBLIC_KEY_E;
        der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
                                           sizeof(der->publicKey), 1);
    }
#endif

#ifdef HAVE_ECC
    if (cert->keyType == ECC_KEY) {
        if (eccKey == NULL)
            return PUBLIC_KEY_E;
        der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey,
                                           sizeof(der->publicKey), 1, 0);
    }
#endif

#if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
    if (cert->keyType == DSA_KEY) {
        if (dsaKey == NULL)
            return PUBLIC_KEY_E;
        der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
                                              sizeof(der->publicKey), 1);
    }
#endif

#if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
    if (cert->keyType == ED25519_KEY) {
        if (ed25519Key == NULL)
            return PUBLIC_KEY_E;
        der->publicKeySz = wc_Ed25519PublicKeyToDer(ed25519Key, der->publicKey,
            (word32)sizeof(der->publicKey), 1);
    }
#endif

#if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
    if (cert->keyType == ED448_KEY) {
        if (ed448Key == NULL)
            return PUBLIC_KEY_E;
        der->publicKeySz = wc_Ed448PublicKeyToDer(ed448Key, der->publicKey,
            (word32)sizeof(der->publicKey), 1);
    }
#endif

#if defined(HAVE_PQC)
#if defined(HAVE_FALCON)
    if ((cert->keyType == FALCON_LEVEL1_KEY) ||
        (cert->keyType == FALCON_LEVEL5_KEY)) {
        if (falconKey == NULL)
            return PUBLIC_KEY_E;

        der->publicKeySz =
            wc_Falcon_PublicKeyToDer(falconKey, der->publicKey,
                                     (word32)sizeof(der->publicKey), 1);
    }
#endif /* HAVE_FALCON */
#if defined(HAVE_DILITHIUM)
    if ((cert->keyType == DILITHIUM_LEVEL2_KEY) ||
        (cert->keyType == DILITHIUM_LEVEL3_KEY) ||
        (cert->keyType == DILITHIUM_LEVEL5_KEY)) {
        if (dilithiumKey == NULL)
            return PUBLIC_KEY_E;

        der->publicKeySz =
            wc_Dilithium_PublicKeyToDer(dilithiumKey, der->publicKey,
                                     (word32)sizeof(der->publicKey), 1);
    }
#endif /* HAVE_DILITHIUM */
#if defined(HAVE_SPHINCS)
    if ((cert->keyType == SPHINCS_FAST_LEVEL1_KEY) ||
        (cert->keyType == SPHINCS_FAST_LEVEL3_KEY) ||
        (cert->keyType == SPHINCS_FAST_LEVEL5_KEY) ||
        (cert->keyType == SPHINCS_SMALL_LEVEL1_KEY) ||
        (cert->keyType == SPHINCS_SMALL_LEVEL3_KEY) ||
        (cert->keyType == SPHINCS_SMALL_LEVEL5_KEY)) {
        if (sphincsKey == NULL)
            return PUBLIC_KEY_E;

        der->publicKeySz =
            wc_Sphincs_PublicKeyToDer(sphincsKey, der->publicKey,
                                      (word32)sizeof(der->publicKey), 1);
    }
#endif /* HAVE_SPHINCS */
#endif /* HAVE_PQC */

    if (der->publicKeySz <= 0)
        return PUBLIC_KEY_E;

    der->validitySz = 0;
    /* copy date validity if already set in cert struct */
    if (cert->beforeDateSz && cert->afterDateSz) {
        der->validitySz = CopyValidity(der->validity, cert);
        if (der->validitySz <= 0)
            return DATE_E;
    }

    /* set date validity using daysValid if not set already */
    if (der->validitySz == 0) {
        der->validitySz = SetValidity(der->validity, cert->daysValid);
        if (der->validitySz <= 0)
            return DATE_E;
    }

    /* subject name */
#if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
    if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
        /* Use the raw subject */
        word32 idx;

        der->subjectSz = (int)min((word32)sizeof(der->subject),
                                  (word32)XSTRLEN((const char*)cert->sbjRaw));
        /* header */
        idx = SetSequence((word32)der->subjectSz, der->subject);
        if ((word32)der->subjectSz + idx > (word32)sizeof(der->subject)) {
            return SUBJECT_E;
        }

        XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw,
                (size_t)der->subjectSz);
        der->subjectSz += (int)idx;
    }
    else
#endif
    {
        /* Use the name structure */
        der->subjectSz = SetNameEx(der->subject, sizeof(der->subject),
                &cert->subject, cert->heap);
    }
    if (der->subjectSz <= 0)
        return SUBJECT_E;

    /* issuer name */
#if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
    if (XSTRLEN((const char*)cert->issRaw) > 0) {
        /* Use the raw issuer */
        word32 idx;

        der->issuerSz = (int)min((word32)sizeof(der->issuer),
                                 (word32)XSTRLEN((const char*)cert->issRaw));

        /* header */
        idx = SetSequence((word32)der->issuerSz, der->issuer);
        if ((word32)der->issuerSz + idx > (word32)sizeof(der->issuer)) {
            return ISSUER_E;
        }

        XMEMCPY((char*)der->issuer + idx, (const char*)cert->issRaw,
                (size_t)der->issuerSz);
        der->issuerSz += (int)idx;
    }
    else
#endif
    {
        /* Use the name structure */
        der->issuerSz = SetNameEx(der->issuer, sizeof(der->issuer),
                cert->selfSigned ? &cert->subject : &cert->issuer, cert->heap);
    }
    if (der->issuerSz <= 0)
        return ISSUER_E;

    /* set the extensions */
    der->extensionsSz = 0;

    /* RFC 5280 : 4.2.1.9. Basic Constraints
     * The pathLenConstraint field is meaningful only if the CA boolean is
     * asserted and the key usage extension, if present, asserts the
     * keyCertSign bit */
    /* Set CA and path length */
    if ((cert->isCA) && (cert->pathLenSet)
#ifdef WOLFSSL_CERT_EXT
        && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
#endif
        ) {
        der->caSz = SetCaWithPathLen(der->ca, sizeof(der->ca), cert->pathLen);
        if (der->caSz <= 0)
            return CA_TRUE_E;

        der->extensionsSz += der->caSz;
    }
    /* Set CA */
    else if (cert->isCA) {
        der->caSz = SetCa(der->ca, sizeof(der->ca));
        if (der->caSz <= 0)
            return CA_TRUE_E;

        der->extensionsSz += der->caSz;
    }
    /* Set Basic Constraint */
    else if (cert->basicConstSet) {
        der->caSz = SetBC(der->ca, sizeof(der->ca));
        if (der->caSz <= 0)
            return EXTENSIONS_E;

        der->extensionsSz += der->caSz;
    }
    else
        der->caSz = 0;

#ifdef WOLFSSL_ALT_NAMES
    /* Alternative Name */
    if (cert->altNamesSz) {
        der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
                                      cert->altNames, (word32)cert->altNamesSz,
                                      cert->altNamesCrit);
        if (der->altNamesSz <= 0)
            return ALT_NAME_E;

        der->extensionsSz += der->altNamesSz;
    }
    else
        der->altNamesSz = 0;
#endif

#ifdef WOLFSSL_CERT_EXT
    /* SKID */
    if (cert->skidSz) {
        /* check the provided SKID size */
        if (cert->skidSz > (int)min(CTC_MAX_SKID_SIZE, sizeof(der->skid)))
            return SKID_E;

        /* Note: different skid buffers sizes for der (MAX_KID_SZ) and
            cert (CTC_MAX_SKID_SIZE). */
        der->skidSz = SetSKID(der->skid, sizeof(der->skid),
                              cert->skid, (word32)cert->skidSz);
        if (der->skidSz <= 0)
            return SKID_E;

        der->extensionsSz += der->skidSz;
    }
    else
        der->skidSz = 0;

    /* AKID */
    if (cert->akidSz) {
        /* check the provided AKID size */
        if ((
#ifdef WOLFSSL_AKID_NAME
             !cert->rawAkid &&
#endif
              cert->akidSz > (int)min(CTC_MAX_AKID_SIZE, sizeof(der->akid)))
#ifdef WOLFSSL_AKID_NAME
          || (cert->rawAkid && cert->akidSz > (int)sizeof(der->akid))
#endif
             )
            return AKID_E;

        der->akidSz = SetAKID(der->akid, sizeof(der->akid), cert->akid,
                              (word32)cert->akidSz,
#ifdef WOLFSSL_AKID_NAME
                              cert->rawAkid
#else
                              0
#endif
                              );
        if (der->akidSz <= 0)
            return AKID_E;

        der->extensionsSz += der->akidSz;
    }
    else
        der->akidSz = 0;

    /* Key Usage */
    if (cert->keyUsage != 0){
        der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
                                      cert->keyUsage);
        if (der->keyUsageSz <= 0)
            return KEYUSAGE_E;

        der->extensionsSz += der->keyUsageSz;
    }
    else
        der->keyUsageSz = 0;

    /* Extended Key Usage */
    if (cert->extKeyUsage != 0){
        der->extKeyUsageSz = SetExtKeyUsage(cert, der->extKeyUsage,
                                sizeof(der->extKeyUsage), cert->extKeyUsage);
        if (der->extKeyUsageSz <= 0)
            return EXTKEYUSAGE_E;

        der->extensionsSz += der->extKeyUsageSz;
    }
    else
        der->extKeyUsageSz = 0;

#ifndef IGNORE_NETSCAPE_CERT_TYPE
    /* Netscape Certificate Type */
    if (cert->nsCertType != 0) {
        der->nsCertTypeSz = SetNsCertType(cert, der->nsCertType,
                                sizeof(der->nsCertType), cert->nsCertType);
        if (der->nsCertTypeSz <= 0)
            return EXTENSIONS_E;

        der->extensionsSz += der->nsCertTypeSz;
    }
    else
        der->nsCertTypeSz = 0;
#endif

    if (cert->crlInfoSz > 0) {
        der->crlInfoSz = SetCRLInfo(cert, der->crlInfo, sizeof(der->crlInfo),
                                cert->crlInfo, cert->crlInfoSz);
        if (der->crlInfoSz <= 0)
            return EXTENSIONS_E;

        der->extensionsSz += der->crlInfoSz;
    }
    else
        der->crlInfoSz = 0;

    /* Certificate Policies */
    if (cert->certPoliciesNb != 0) {
        der->certPoliciesSz = SetCertificatePolicies(der->certPolicies,
                                                     sizeof(der->certPolicies),
                                                     cert->certPolicies,
                                                     cert->certPoliciesNb,
                                                     cert->heap);
        if (der->certPoliciesSz <= 0)
            return CERTPOLICIES_E;

        der->extensionsSz += der->certPoliciesSz;
    }
    else
        der->certPoliciesSz = 0;
#endif /* WOLFSSL_CERT_EXT */

    /* put extensions */
    if (der->extensionsSz > 0) {

        /* put the start of extensions sequence (ID, Size) */
        der->extensionsSz = SetExtensionsHeader(der->extensions,
                                                sizeof(der->extensions),
                                                (word32)der->extensionsSz);
        if (der->extensionsSz <= 0)
            return EXTENSIONS_E;

        /* put CA */
        if (der->caSz) {
            ret = SetExtensions(der->extensions, sizeof(der->extensions),
                                &der->extensionsSz,
                                der->ca, der->caSz);
            if (ret == 0)
                return EXTENSIONS_E;
        }

#ifdef WOLFSSL_ALT_NAMES
        /* put Alternative Names */
        if (der->altNamesSz) {
            ret = SetExtensions(der->extensions, sizeof(der->extensions),
                                &der->extensionsSz,
                                der->altNames, der->altNamesSz);
            if (ret <= 0)
                return EXTENSIONS_E;
        }
#endif

#ifdef WOLFSSL_CERT_EXT
        /* put SKID */
        if (der->skidSz) {
            ret = SetExtensions(der->extensions, sizeof(der->extensions),
                                &der->extensionsSz,
                                der->skid, der->skidSz);
            if (ret <= 0)
                return EXTENSIONS_E;
        }

        /* put AKID */
        if (der->akidSz) {
            ret = SetExtensions(der->extensions, sizeof(der->extensions),
                                &der->extensionsSz,
                                der->akid, der->akidSz);
            if (ret <= 0)
                return EXTENSIONS_E;
        }

        /* put CRL Distribution Points */
        if (der->crlInfoSz) {
            ret = SetExtensions(der->extensions, sizeof(der->extensions),
                                &der->extensionsSz,
                                der->crlInfo, der->crlInfoSz);
            if (ret <= 0)
                return EXTENSIONS_E;
        }

        /* put KeyUsage */
        if (der->keyUsageSz) {
            ret = SetExtensions(der->extensions, sizeof(der->extensions),
                                &der->extensionsSz,
                                der->keyUsage, der->keyUsageSz);
            if (ret <= 0)
                return EXTENSIONS_E;
        }

        /* put ExtendedKeyUsage */
        if (der->extKeyUsageSz) {
            ret = SetExtensions(der->extensions, sizeof(der->extensions),
                                &der->extensionsSz,
                                der->extKeyUsage, der->extKeyUsageSz);
            if (ret <= 0)
                return EXTENSIONS_E;
        }

        /* put Netscape Cert Type */
#ifndef IGNORE_NETSCAPE_CERT_TYPE
        if (der->nsCertTypeSz) {
            ret = SetExtensions(der->extensions, sizeof(der->extensions),
                                &der->extensionsSz,
                                der->nsCertType, der->nsCertTypeSz);
            if (ret <= 0)
                return EXTENSIONS_E;
        }
#endif

        /* put Certificate Policies */
        if (der->certPoliciesSz) {
            ret = SetExtensions(der->extensions, sizeof(der->extensions),
                                &der->extensionsSz,
                                der->certPolicies, der->certPoliciesSz);
            if (ret <= 0)
                return EXTENSIONS_E;
        }
#endif /* WOLFSSL_CERT_EXT */
    }

    der->total = der->versionSz + der->serialSz + der->sigAlgoSz +
        der->publicKeySz + der->validitySz + der->subjectSz + der->issuerSz +
        der->extensionsSz;

    return 0;
}


/* write DER encoded cert to buffer, size already checked */
static int WriteCertBody(DerCert* der, byte* buf)
{
    word32 idx;

    /* signed part header */
    idx = SetSequence((word32)der->total, buf);
    /* version */
    XMEMCPY(buf + idx, der->version, (size_t)der->versionSz);
    idx += (word32)der->versionSz;
    /* serial */
    XMEMCPY(buf + idx, der->serial, (size_t)der->serialSz);
    idx += (word32)der->serialSz;
    /* sig algo */
    XMEMCPY(buf + idx, der->sigAlgo, (size_t)der->sigAlgoSz);
    idx += (word32)der->sigAlgoSz;
    /* issuer */
    XMEMCPY(buf + idx, der->issuer, (size_t)der->issuerSz);
    idx += (word32)der->issuerSz;
    /* validity */
    XMEMCPY(buf + idx, der->validity, (size_t)der->validitySz);
    idx += (word32)der->validitySz;
    /* subject */
    XMEMCPY(buf + idx, der->subject, (size_t)der->subjectSz);
    idx += (word32)der->subjectSz;
    /* public key */
    XMEMCPY(buf + idx, der->publicKey, (size_t)der->publicKeySz);
    idx += (word32)der->publicKeySz;
    if (der->extensionsSz) {
        /* extensions */
        XMEMCPY(buf + idx, der->extensions,
                min((word32)der->extensionsSz,
                    (word32)sizeof(der->extensions)));
        idx += (word32)der->extensionsSz;
    }

    return (int)idx;
}
#endif /* !WOLFSSL_ASN_TEMPLATE */


/* Make signature from buffer (sz), write to sig (sigSz) */
static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, word32 sz,
    byte* sig, word32 sigSz, RsaKey* rsaKey, ecc_key* eccKey,
    ed25519_key* ed25519Key, ed448_key* ed448Key, falcon_key* falconKey,
    dilithium_key* dilithiumKey, sphincs_key* sphincsKey, WC_RNG* rng,
    word32 sigAlgoType, void* heap)
{
    int digestSz = 0, typeH = 0, ret = 0;

    (void)digestSz;
    (void)typeH;
    (void)buf;
    (void)sz;
    (void)sig;
    (void)sigSz;
    (void)rsaKey;
    (void)eccKey;
    (void)ed25519Key;
    (void)ed448Key;
    (void)falconKey;
    (void)dilithiumKey;
    (void)sphincsKey;
    (void)rng;
    (void)heap;

    switch (certSignCtx->state) {
    case CERTSIGN_STATE_BEGIN:
    case CERTSIGN_STATE_DIGEST:

        certSignCtx->state = CERTSIGN_STATE_DIGEST;
        certSignCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, heap,
            DYNAMIC_TYPE_TMP_BUFFER);
        if (certSignCtx->digest == NULL) {
            ret = MEMORY_E; goto exit_ms;
        }

        ret = HashForSignature(buf, sz, sigAlgoType, certSignCtx->digest,
                               &typeH, &digestSz, 0);
        /* set next state, since WC_PENDING_E rentry for these are not "call again" */
        certSignCtx->state = CERTSIGN_STATE_ENCODE;
        if (ret != 0) {
            goto exit_ms;
        }
        FALL_THROUGH;

    case CERTSIGN_STATE_ENCODE:
    #ifndef NO_RSA
        if (rsaKey) {
            certSignCtx->encSig = (byte*)XMALLOC(MAX_DER_DIGEST_SZ, heap,
                DYNAMIC_TYPE_TMP_BUFFER);
            if (certSignCtx->encSig == NULL) {
                ret = MEMORY_E; goto exit_ms;
            }

            /* signature */
            certSignCtx->encSigSz = (int)wc_EncodeSignature(certSignCtx->encSig,
                                  certSignCtx->digest, (word32)digestSz, typeH);
        }
    #endif /* !NO_RSA */
        FALL_THROUGH;

    case CERTSIGN_STATE_DO:
        certSignCtx->state = CERTSIGN_STATE_DO;
        ret = ALGO_ID_E; /* default to error */

    #ifndef NO_RSA
        if (rsaKey) {
            /* signature */
            ret = wc_RsaSSL_Sign(certSignCtx->encSig,
                                 (word32)certSignCtx->encSigSz,
                                 sig, sigSz, rsaKey, rng);
        }
    #endif /* !NO_RSA */

    #if defined(HAVE_ECC) && defined(HAVE_ECC_SIGN)
        if (!rsaKey && eccKey) {
            word32 outSz = sigSz;

            ret = wc_ecc_sign_hash(certSignCtx->digest, (word32)digestSz,
                                   sig, &outSz, rng, eccKey);
            if (ret == 0)
                ret = (int)outSz;
        }
    #endif /* HAVE_ECC && HAVE_ECC_SIGN */

    #if defined(HAVE_ED25519) && defined(HAVE_ED25519_SIGN)
        if (!rsaKey && !eccKey && ed25519Key) {
            word32 outSz = sigSz;

            ret = wc_ed25519_sign_msg(buf, sz, sig, &outSz, ed25519Key);
            if (ret == 0)
                ret = (int)outSz;
        }
    #endif /* HAVE_ED25519 && HAVE_ED25519_SIGN */

    #if defined(HAVE_ED448) && defined(HAVE_ED448_SIGN)
        if (!rsaKey && !eccKey && !ed25519Key && ed448Key) {
            word32 outSz = sigSz;

            ret = wc_ed448_sign_msg(buf, sz, sig, &outSz, ed448Key, NULL, 0);
            if (ret == 0)
                ret = (int)outSz;
        }
    #endif /* HAVE_ED448 && HAVE_ED448_SIGN */

    #if defined(HAVE_PQC)
    #if defined(HAVE_FALCON)
        if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && falconKey) {
            word32 outSz = sigSz;
            ret = wc_falcon_sign_msg(buf, sz, sig, &outSz, falconKey);
            if (ret == 0)
                ret = outSz;
        }
    #endif /* HAVE_FALCON */
    #if defined(HAVE_DILITHIUM)
        if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && !falconKey &&
            dilithiumKey) {
            word32 outSz = sigSz;
            ret = wc_dilithium_sign_msg(buf, sz, sig, &outSz, dilithiumKey);
            if (ret == 0)
                ret = outSz;
        }
    #endif /* HAVE_DILITHIUM */
    #if defined(HAVE_SPHINCS)
        if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && !falconKey &&
            !dilithiumKey && sphincsKey) {
            word32 outSz = sigSz;
            ret = wc_sphincs_sign_msg(buf, sz, sig, &outSz, sphincsKey);
            if (ret == 0)
                ret = outSz;
        }
    #endif /* HAVE_SPHINCS */
    #endif /* HAVE_PQC */

        break;
    }

exit_ms:

#ifdef WOLFSSL_ASYNC_CRYPT
    if (ret == WC_PENDING_E) {
        return ret;
    }
#endif

#ifndef NO_RSA
    if (rsaKey) {
        XFREE(certSignCtx->encSig, heap, DYNAMIC_TYPE_TMP_BUFFER);
    }
#endif /* !NO_RSA */

    XFREE(certSignCtx->digest, heap, DYNAMIC_TYPE_TMP_BUFFER);
    certSignCtx->digest = NULL;

    /* reset state */
    certSignCtx->state = CERTSIGN_STATE_BEGIN;

    if (ret < 0) {
        WOLFSSL_ERROR_VERBOSE(ret);
    }

    return ret;
}


#ifdef WOLFSSL_ASN_TEMPLATE
/* Generate a random integer value of at most len bytes.
 *
 * Most-significant bit will not be set when maximum size.
 * Random value may be smaller than maximum size in bytes.
 *
 * @param [in]  rng  Random number generator.
 * @param [out] out  Buffer to hold integer value.
 * @param [in]  len  Maximum number of bytes of integer.
 * @return  0 on success.
 * @return  -ve when random number generation failed.
 */
static int GenerateInteger(WC_RNG* rng, byte* out, word32 len)
{
    int ret;

    /* Generate random number. */
    ret = wc_RNG_GenerateBlock(rng, out, len);
    if (ret == 0) {
        int i;

        /* Clear the top bit to make positive. */
        out[0] &= 0x7f;

        /* Find first non-zero byte. One zero byte is valid though. */
        for (i = 0; i < (int)len - 1; i++) {
            if (out[i] != 0) {
                break;
            }
        }
        if (i != 0) {
            /* Remove leading zeros. */
            XMEMMOVE(out, out + i, (size_t)len - (size_t)i);
        }
    }

    return ret;
}

/* ASN.1 template for a Certificate.
 * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
 */
static const ASNItem sigASN[] = {
/* SEQ          */    { 0, ASN_SEQUENCE, 1, 1, 0 },
                                     /* tbsCertificate */
/* TBS_SEQ      */        { 1, ASN_SEQUENCE, 1, 0, 0 },
                                     /* signatureAlgorithm */
/* SIGALGO_SEQ  */        { 1, ASN_SEQUENCE, 1, 1, 0 },
/* SIGALGO_OID  */            { 2, ASN_OBJECT_ID, 0, 0, 0 },
/* SIGALGO_NULL */            { 2, ASN_TAG_NULL, 0, 0, 0 },
                                     /* signatureValue */
/* SIGNATURE    */        { 1, ASN_BIT_STRING, 0, 0, 0 },
};
enum {
    SIGASN_IDX_SEQ = 0,
    SIGASN_IDX_TBS_SEQ,
    SIGASN_IDX_SIGALGO_SEQ,
    SIGASN_IDX_SIGALGO_OID,
    SIGASN_IDX_SIGALGO_NULL,
    SIGASN_IDX_SIGNATURE
};

/* Number of items in ASN.1 template for a Certificate. */
#define sigASN_Length (sizeof(sigASN) / sizeof(ASNItem))
#endif

/* add signature to end of buffer, size of buffer assumed checked, return
   new length */
int AddSignature(byte* buf, int bodySz, const byte* sig, int sigSz,
                        int sigAlgoType)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    byte seq[MAX_SEQ_SZ];
    word32 idx, seqSz;

    if ((bodySz < 0) || (sigSz < 0))
        return BUFFER_E;

    idx = (word32)bodySz;

    /* algo */
    idx += SetAlgoID(sigAlgoType, buf ? buf + idx : NULL, oidSigType, 0);
    /* bit string */
    idx += SetBitString((word32)sigSz, 0, buf ? buf + idx : NULL);
    /* signature */
    if (buf)
        XMEMCPY(buf + idx, sig, (size_t)sigSz);
    idx += (word32)sigSz;

    /* make room for overall header */
    seqSz = SetSequence(idx, seq);
    if (buf) {
        XMEMMOVE(buf + seqSz, buf, idx);
        XMEMCPY(buf, seq, seqSz);
    }

    return (int)(idx + seqSz);
#else
    DECL_ASNSETDATA(dataASN, sigASN_Length);
    word32 seqSz;
    int sz;
    int ret = 0;

    CALLOC_ASNSETDATA(dataASN, sigASN_Length, ret, NULL);

    /* In place, put body between SEQUENCE and signature. */
    if (ret == 0) {
        /* Set sigature OID and signature data. */
        SetASN_OID(&dataASN[SIGASN_IDX_SIGALGO_OID], (word32)sigAlgoType,
                   oidSigType);
        if (IsSigAlgoECC((word32)sigAlgoType)) {
            /* ECDSA and EdDSA doesn't have NULL tagged item. */
            dataASN[SIGASN_IDX_SIGALGO_NULL].noOut = 1;
        }
        SetASN_Buffer(&dataASN[SIGASN_IDX_SIGNATURE], sig, (word32)sigSz);
        /* Calculate size of signature data. */
        ret = SizeASN_Items(&sigASN[SIGASN_IDX_SIGALGO_SEQ],
                &dataASN[SIGASN_IDX_SIGALGO_SEQ], sigASN_Length - 2, &sz);
    }
    if (ret == 0) {
        /* Calculate size of outer sequence by calculating size of the encoded
         * length and adding 1 for tag. */
        seqSz = SizeASNHeader((word32)bodySz + (word32)sz);
        if (buf != NULL) {
            /* Move body to after sequence. */
            XMEMMOVE(buf + seqSz, buf, (size_t)bodySz);
        }
        /* Leave space for body in encoding. */
        SetASN_ReplaceBuffer(&dataASN[SIGASN_IDX_TBS_SEQ], NULL,
                             (word32)bodySz);

        /* Calculate overall size and put in offsets and lengths. */
        ret = SizeASN_Items(sigASN, dataASN, sigASN_Length, &sz);
    }
    if ((ret == 0) && (buf != NULL)) {
        /* Write SEQUENCE and signature around body. */
        SetASN_Items(sigASN, dataASN, sigASN_Length, buf);
    }

    if (ret == 0) {
        /* Return the encoding size. */
        ret = sz;
    }

    FREE_ASNSETDATA(dataASN, NULL);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}


/* Make an x509 Certificate v3 any key type from cert input, write to buffer */
static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz,
                       RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng,
                       DsaKey* dsaKey, ed25519_key* ed25519Key,
                       ed448_key* ed448Key, falcon_key* falconKey,
                       dilithium_key* dilithiumKey, sphincs_key* sphincsKey)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int ret;
#ifdef WOLFSSL_SMALL_STACK
    DerCert* der;
#else
    DerCert der[1];
#endif

    if (derBuffer == NULL)
        return BAD_FUNC_ARG;

    if (eccKey)
        cert->keyType = ECC_KEY;
    else if (rsaKey)
        cert->keyType = RSA_KEY;
    else if (dsaKey)
        cert->keyType = DSA_KEY;
    else if (ed25519Key)
        cert->keyType = ED25519_KEY;
    else if (ed448Key)
        cert->keyType = ED448_KEY;
#ifdef HAVE_PQC
#ifdef HAVE_FALCON
    else if ((falconKey != NULL) && (falconKey->level == 1))
        cert->keyType = FALCON_LEVEL1_KEY;
    else if ((falconKey != NULL) && (falconKey->level == 5))
        cert->keyType = FALCON_LEVEL5_KEY;
#endif /* HAVE_FALCON */
#ifdef HAVE_DILITHIUM
    else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2))
        cert->keyType = DILITHIUM_LEVEL2_KEY;
    else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3))
        cert->keyType = DILITHIUM_LEVEL3_KEY;
    else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5))
        cert->keyType = DILITHIUM_LEVEL5_KEY;
#endif /* HAVE_DILITHIUM */
#ifdef HAVE_SPHINCS
    else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
             && (sphincsKey->optim == FAST_VARIANT))
        cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
    else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
             && (sphincsKey->optim == FAST_VARIANT))
        cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
    else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
             && (sphincsKey->optim == FAST_VARIANT))
        cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
    else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
             && (sphincsKey->optim == SMALL_VARIANT))
        cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
    else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
             && (sphincsKey->optim == SMALL_VARIANT))
        cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
    else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
             && (sphincsKey->optim == SMALL_VARIANT))
        cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
#endif /* HAVE_SPHINCS */
#endif /* HAVE_PQC */
    else
        return BAD_FUNC_ARG;

#ifdef WOLFSSL_SMALL_STACK
    der = (DerCert*)XMALLOC(sizeof(DerCert), cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
    if (der == NULL)
        return MEMORY_E;
#endif

    ret = EncodeCert(cert, der, rsaKey, eccKey, rng, dsaKey, ed25519Key,
                     ed448Key, falconKey, dilithiumKey, sphincsKey);
    if (ret == 0) {
        if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
            ret = BUFFER_E;
        else
            ret = cert->bodySz = WriteCertBody(der, derBuffer);
    }

#ifdef WOLFSSL_SMALL_STACK
    XFREE(der, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
#endif

    return ret;
#else
    /* TODO: issRaw and sbjRaw should be NUL terminated. */
    DECL_ASNSETDATA(dataASN, x509CertASN_Length);
    word32 publicKeySz = 0;
    word32 issuerSz = 0;
    word32 subjectSz = 0;
    word32 extSz = 0;
    int sz = 0;
    int ret = 0;
    word32 issRawLen = 0;
    word32 sbjRawLen = 0;

    /* Unused without OQS */
    (void)falconKey;
    (void)dilithiumKey;
    (void)sphincsKey;

    CALLOC_ASNSETDATA(dataASN, x509CertASN_Length, ret, cert->heap);

    if (ret == 0) {
        /* Set key type into certificate object based on key passed in. */
        if (rsaKey) {
            cert->keyType = RSA_KEY;
        }
        else if (eccKey) {
            cert->keyType = ECC_KEY;
        }
        else if (dsaKey) {
            cert->keyType = DSA_KEY;
        }
        else if (ed25519Key) {
            cert->keyType = ED25519_KEY;
        }
        else if (ed448Key) {
            cert->keyType = ED448_KEY;
        }
#ifdef HAVE_PQC
#ifdef HAVE_FALCON
        else if ((falconKey != NULL) && (falconKey->level == 1)) {
            cert->keyType = FALCON_LEVEL1_KEY;
        }
        else if ((falconKey != NULL) && (falconKey->level == 5)) {
            cert->keyType = FALCON_LEVEL5_KEY;
        }
#endif /* HAVE_FALCON */
#ifdef HAVE_DILITHIUM
        else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)) {
            cert->keyType = DILITHIUM_LEVEL2_KEY;
        }
        else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)) {
            cert->keyType = DILITHIUM_LEVEL3_KEY;
        }
        else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)) {
            cert->keyType = DILITHIUM_LEVEL5_KEY;
        }
#endif /* HAVE_DILITHIUM */
#ifdef HAVE_SPHINCS
        else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
                 && (sphincsKey->optim == FAST_VARIANT)) {
            cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
        }
        else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
                 && (sphincsKey->optim == FAST_VARIANT)) {
            cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
        }
        else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
                 && (sphincsKey->optim == FAST_VARIANT)) {
            cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
        }
        else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
                 && (sphincsKey->optim == SMALL_VARIANT)) {
            cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
        }
        else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
                 && (sphincsKey->optim == SMALL_VARIANT)) {
            cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
        }
        else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
                 && (sphincsKey->optim == SMALL_VARIANT)) {
            cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
        }
#endif /* HAVE_SPHINCS */
#endif /* HAVE_PQC */
        else {
            ret = BAD_FUNC_ARG;
        }
    }
    if ((ret == 0) && (cert->serialSz == 0)) {
        /* Generate random serial number. */
        cert->serialSz = CTC_GEN_SERIAL_SZ;
        ret = GenerateInteger(rng, cert->serial, CTC_GEN_SERIAL_SZ);
    }
    if (ret == 0) {
        /* Determine issuer name size. */
    #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
        defined(WOLFSSL_CERT_REQ)
        issRawLen = (word32)XSTRLEN((const char*)cert->issRaw);
        if (issRawLen > 0) {
            issuerSz = min(sizeof(cert->issRaw), issRawLen);
        }
        else
    #endif
        {
            /* Calculate issuer name encoding size. If the cert is self-signed
             * use the subject instead of the issuer. */
            ret = SetNameEx(NULL, WC_ASN_NAME_MAX, cert->selfSigned ?
                                 &cert->subject : &cert->issuer, cert->heap);
            issuerSz = (word32)ret;
        }
    }
    if (ret >= 0) {
        /* Determine subject name size. */
    #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
        defined(WOLFSSL_CERT_REQ)
        sbjRawLen = (word32)XSTRLEN((const char*)cert->sbjRaw);
        if (sbjRawLen > 0) {
            subjectSz = min(sizeof(cert->sbjRaw), sbjRawLen);
        }
        else
    #endif
        {
            /* Calculate subject name encoding size. */
            ret = SetNameEx(NULL, WC_ASN_NAME_MAX, &cert->subject,
                                  cert->heap);
            subjectSz = (word32)ret;
        }
    }
    if (ret >= 0) {
        /* Calculate public key encoding size. */
        ret = EncodePublicKey(cert->keyType, NULL, 0, rsaKey,
            eccKey, ed25519Key, ed448Key, dsaKey);
        publicKeySz = (word32)ret;
    }
    if (ret >= 0) {
        /* Calculate extensions encoding size - may be 0. */
        ret = EncodeExtensions(cert, NULL, 0, 0);
        extSz = (word32)ret;
    }
    if (ret >= 0) {
        /* Don't write out outer sequence - only doing body. */
        dataASN[X509CERTASN_IDX_SEQ].noOut = 1;
        /* Set version, serial number and signature OID */
        SetASN_Int8Bit(&dataASN[X509CERTASN_IDX_TBS_VER_INT],
                       (byte)cert->version);
        SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SERIAL], cert->serial,
                (word32)cert->serialSz);
        SetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID],
                   (word32)cert->sigType, oidSigType);
        if (IsSigAlgoECC((word32)cert->sigType)) {
            /* No NULL tagged item with ECDSA and EdDSA signature OIDs. */
            dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS_NULL].noOut = 1;
        }
    #ifdef WC_RSA_PSS
        /* TODO: Encode RSA PSS parameters. */
        dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS].noOut = 1;
    #endif
        if (issRawLen > 0) {
    #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
        defined(WOLFSSL_CERT_REQ)
            /* Put in encoded issuer name. */
            SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
                    cert->issRaw, issuerSz);
    #endif
        }
        else {
            /* Leave space for issuer name. */
            SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
                    NULL, issuerSz);
        }

        if (cert->beforeDateSz && cert->afterDateSz) {
            if (cert->beforeDate[0] == ASN_UTC_TIME) {
                /* Make space for before date data. */
                SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC],
                        cert->beforeDate + 2, ASN_UTC_TIME_SIZE - 1);
                /* Don't put out Generalized Time before data. */
                dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT].noOut = 1;
            }
            else {
                /* Don't put out UTC before data. */
                dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].noOut = 1;
                /* Make space for before date data. */
                SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT],
                        cert->beforeDate + 2, ASN_GEN_TIME_SZ);
            }
            if (cert->afterDate[0] == ASN_UTC_TIME) {
                /* Make space for after date data. */
                SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC],
                        cert->afterDate + 2, ASN_UTC_TIME_SIZE - 1);
                /* Don't put out UTC Generalized Time after data. */
                dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT].noOut = 1;
            }
            else {
                /* Don't put out UTC after data. */
                dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].noOut = 1;
                /* Make space for after date data. */
                SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT],
                        cert->afterDate + 2, ASN_GEN_TIME_SZ);
            }
        }
        else
        {
            /* Don't put out UTC before data. */
            dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].noOut = 1;
            /* Make space for before date data. */
            SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT],
                    NULL, ASN_GEN_TIME_SZ);
            /* Don't put out UTC after data. */
            dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].noOut = 1;
            /* Make space for after date data. */
            SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT],
                    NULL, ASN_GEN_TIME_SZ);
        }
        if (sbjRawLen > 0) {
            /* Put in encoded subject name. */
    #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
        defined(WOLFSSL_CERT_REQ)
            SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ],
                    cert->sbjRaw, subjectSz);
    #endif
        }
        else {
            /* Leave space for subject name. */
            SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ],
                    NULL, subjectSz);
        }
        /* Leave space for public key. */
        SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ],
                NULL, publicKeySz);
        /* Replacement buffer instead of algorithm identifier items. */
        SetASNItem_NoOut(dataASN,
                X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_SEQ,
                X509CERTASN_IDX_TBS_SPUBKEYINFO_PUBKEY);
        /* issuerUniqueID and subjectUniqueID not supported. */
        dataASN[X509CERTASN_IDX_TBS_ISSUERUID].noOut = 1;
        dataASN[X509CERTASN_IDX_TBS_SUBJECTUID].noOut = 1;
        /* Leave space for extensions if any set into certificate object. */
        if (extSz > 0) {
            SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_EXT_SEQ], NULL, extSz);
        }
        else {
            SetASNItem_NoOutNode(dataASN, x509CertASN,
                    X509CERTASN_IDX_TBS_EXT, x509CertASN_Length);
        }
        /* No signature - added later. */
        SetASNItem_NoOut(dataASN, X509CERTASN_IDX_SIGALGO_SEQ,
                X509CERTASN_IDX_SIGNATURE);

        /* Calculate encoded certificate body size. */
        ret = SizeASN_Items(x509CertASN, dataASN, x509CertASN_Length, &sz);
    }
    /* Check buffer is big enough for encoded data. */
    if ((ret == 0) && (sz > (int)derSz)) {
        ret = BUFFER_E;
    }
    if (ret == 0) {
        /* Encode certificate body into buffer. */
        SetASN_Items(x509CertASN, dataASN, x509CertASN_Length, derBuffer);

        if (issRawLen == 0) {
            /* Encode issuer name into buffer. Use the subject as the issuer
             * if it is self-signed. Size will be correct because we did the
             * same for size. */
            ret = SetNameEx(
                (byte*)dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].data.buffer.data,
                dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].data.buffer.length,
                cert->selfSigned ? &cert->subject : &cert->issuer, cert->heap);
        }
    }
    if ((ret >= 0) && (sbjRawLen == 0)) {
        /* Encode subject name into buffer. */
        ret = SetNameEx(
            (byte*)dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].data.buffer.data,
            dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].data.buffer.length,
            &cert->subject, cert->heap);
    }
    if (ret >= 0) {
        if (cert->beforeDateSz == 0 || cert->afterDateSz == 0)
        {
            /* Encode validity into buffer. */
            ret = SetValidity(
                (byte*)dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT]
                               .data.buffer.data,
                (byte*)dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT]
                               .data.buffer.data, cert->daysValid);
        }
    }
    if (ret >= 0) {
        /* Encode public key into buffer. */
        ret = EncodePublicKey(cert->keyType,
            (byte*)dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ]
                           .data.buffer.data,
            (int)dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ]
                           .data.buffer.length,
            rsaKey, eccKey, ed25519Key, ed448Key, dsaKey);
    }
    if ((ret >= 0) && (!dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].noOut)) {
        /* Encode extensions into buffer. */
        ret = EncodeExtensions(cert,
                (byte*)dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.buffer.data,
                dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.buffer.length, 0);
    }
    if (ret >= 0) {
        /* Store encoded certifcate body size. */
        cert->bodySz = sz;
        /* Return the encoding size. */
        ret = sz;
    }

    FREE_ASNSETDATA(dataASN, cert->heap);
    return ret;
#endif
}


/* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
int wc_MakeCert_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
                   void* key, WC_RNG* rng)
{
    RsaKey*            rsaKey = NULL;
    DsaKey*            dsaKey = NULL;
    ecc_key*           eccKey = NULL;
    ed25519_key*       ed25519Key = NULL;
    ed448_key*         ed448Key = NULL;
    falcon_key*        falconKey = NULL;
    dilithium_key*     dilithiumKey = NULL;
    sphincs_key*       sphincsKey = NULL;

    if (keyType == RSA_TYPE)
        rsaKey = (RsaKey*)key;
    else if (keyType == DSA_TYPE)
        dsaKey = (DsaKey*)key;
    else if (keyType == ECC_TYPE)
        eccKey = (ecc_key*)key;
    else if (keyType == ED25519_TYPE)
        ed25519Key = (ed25519_key*)key;
    else if (keyType == ED448_TYPE)
        ed448Key = (ed448_key*)key;
    else if (keyType == FALCON_LEVEL1_TYPE)
        falconKey = (falcon_key*)key;
    else if (keyType == FALCON_LEVEL5_TYPE)
        falconKey = (falcon_key*)key;
    else if (keyType == DILITHIUM_LEVEL2_TYPE)
        dilithiumKey = (dilithium_key*)key;
    else if (keyType == DILITHIUM_LEVEL3_TYPE)
        dilithiumKey = (dilithium_key*)key;
    else if (keyType == DILITHIUM_LEVEL5_TYPE)
        dilithiumKey = (dilithium_key*)key;
    else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
        sphincsKey = (sphincs_key*)key;
    else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
        sphincsKey = (sphincs_key*)key;
    else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
        sphincsKey = (sphincs_key*)key;
    else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
        sphincsKey = (sphincs_key*)key;
    else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
        sphincsKey = (sphincs_key*)key;
    else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
        sphincsKey = (sphincs_key*)key;

    return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, dsaKey,
                       ed25519Key, ed448Key, falconKey, dilithiumKey,
                       sphincsKey);
}

/* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
WOLFSSL_ABI
int wc_MakeCert(Cert* cert, byte* derBuffer, word32 derSz, RsaKey* rsaKey,
             ecc_key* eccKey, WC_RNG* rng)
{
    return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, NULL, NULL,
                       NULL, NULL, NULL, NULL);
}

#ifdef WOLFSSL_CERT_REQ

#ifndef WOLFSSL_ASN_TEMPLATE
/* return size of data set on success
 * if getting size only then attr and oid should be NULL
 */
static word32 SetReqAttribSingle(byte* output, word32* idx, char* attr,
        word32 attrSz, const byte* oid, word32 oidSz, byte printable,
        word32 extSz)
{
    word32 totalSz = 0;
    word32 seqSz = 0;
    word32 setSz = 0;
    word32 strSz = 0;
    byte seq[MAX_SEQ_SZ];
    byte set[MAX_SET_SZ];
    byte str[MAX_PRSTR_SZ];

    totalSz = (word32)SetObjectId((int)oidSz, NULL);
    totalSz += oidSz;
    if (extSz > 0) {
        totalSz += setSz = SetSet(extSz, set);
        totalSz += seqSz = SetSequence(totalSz + extSz, seq);
        totalSz += extSz;
    }
    else {
        if (printable) {
            strSz = SetPrintableString(attrSz, str);
            totalSz += strSz;
        }
        else {
            totalSz += strSz = SetUTF8String(attrSz, str);
        }
        totalSz += setSz = SetSet(strSz + attrSz, set);
        totalSz += seqSz = SetSequence(totalSz + attrSz, seq);
        totalSz += attrSz;
    }

    if (oid) {
        XMEMCPY(&output[*idx], seq, seqSz);
        *idx += seqSz;
        *idx += (word32)SetObjectId((int)oidSz, output + *idx);
        XMEMCPY(&output[*idx], oid, oidSz);
        *idx += oidSz;
        XMEMCPY(&output[*idx], set, setSz);
        *idx += setSz;
        if (strSz > 0) {
            XMEMCPY(&output[*idx], str, strSz);
            *idx += strSz;
            if (attrSz > 0) {
                XMEMCPY(&output[*idx], attr, attrSz);
                *idx += attrSz;
            }
        }
    }
    return totalSz;
}



static int SetReqAttrib(byte* output, Cert* cert, word32 extSz)
{
    word32 sz      = 0; /* overall size */
    word32 setSz   = 0;

    output[0] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
    sz++;

    if (cert->challengePw[0]) {
        setSz += SetReqAttribSingle(output, &sz, NULL,
                (word32)XSTRLEN(cert->challengePw), NULL,
                sizeof(attrChallengePasswordOid),
                (byte)cert->challengePwPrintableString, 0);
    }

    if (cert->unstructuredName[0]) {
        setSz += SetReqAttribSingle(output, &sz, NULL,
                (word32)XSTRLEN(cert->unstructuredName), NULL,
                sizeof(attrUnstructuredNameOid), 1, 0);
    }

    if (extSz) {
        setSz += SetReqAttribSingle(output, &sz, NULL, 0, NULL,
                sizeof(attrExtensionRequestOid), 1, extSz);
    }

    /* Put the pieces together. */
    sz += SetLength(setSz, &output[sz]);
    if (sz + setSz - extSz > MAX_ATTRIB_SZ) {
        WOLFSSL_MSG("Attribute Buffer is not big enough!");
        return REQ_ATTRIBUTE_E;
    }

    if (cert->challengePw[0]) {
        SetReqAttribSingle(output, &sz, cert->challengePw,
                (word32)XSTRLEN(cert->challengePw),
                &attrChallengePasswordOid[0],
                sizeof(attrChallengePasswordOid),
                (byte)cert->challengePwPrintableString, 0);
    }

    if (cert->unstructuredName[0]) {
        SetReqAttribSingle(output, &sz, cert->unstructuredName,
                (word32)XSTRLEN(cert->unstructuredName),
                &attrUnstructuredNameOid[0],
                sizeof(attrUnstructuredNameOid), 1, 0);
    }

    if (extSz) {
        SetReqAttribSingle(output, &sz, NULL, 0, &attrExtensionRequestOid[0],
                sizeof(attrExtensionRequestOid), 1, extSz);
        /* The actual extension data will be tacked onto the output later. */
    }

    return (int)sz;
}

#ifdef WOLFSSL_CUSTOM_OID
/* encode a custom oid and value */
static int SetCustomObjectId(Cert* cert, byte* output, word32 outSz,
    CertOidField* custom)
{
    int idx = 0, cust_lenSz, cust_oidSz;

    if (cert == NULL || output == NULL || custom == NULL) {
        return BAD_FUNC_ARG;
    }
    if (custom->oid == NULL || custom->oidSz <= 0) {
        return 0; /* none set */
    }

    /* Octet String header */
    cust_lenSz = SetOctetString(custom->valSz, NULL);
    cust_oidSz = SetObjectId(custom->oidSz, NULL);

    /* check for output buffer room */
    if ((word32)(custom->valSz + custom->oidSz + cust_lenSz + cust_oidSz) >
                                                                        outSz) {
        return BUFFER_E;
    }

    /* put sequence with total */
    idx = SetSequence(custom->valSz + custom->oidSz + cust_lenSz + cust_oidSz,
                      output);

    /* put oid header */
    idx += SetObjectId(custom->oidSz, output+idx);
    XMEMCPY(output+idx, custom->oid, custom->oidSz);
    idx += custom->oidSz;

    /* put value */
    idx += SetOctetString(custom->valSz, output+idx);
    XMEMCPY(output+idx, custom->val, custom->valSz);
    idx += custom->valSz;

    return idx;
}
#endif /* WOLFSSL_CUSTOM_OID */


/* encode info from cert into DER encoded format */
static int EncodeCertReq(Cert* cert, DerCert* der, RsaKey* rsaKey,
                         DsaKey* dsaKey, ecc_key* eccKey,
                         ed25519_key* ed25519Key, ed448_key* ed448Key,
                         falcon_key* falconKey, dilithium_key* dilithiumKey,
                         sphincs_key* sphincsKey)
{
    int ret;

    (void)eccKey;
    (void)ed25519Key;
    (void)ed448Key;
    (void)falconKey;
    (void)dilithiumKey;
    (void)sphincsKey;

    if (cert == NULL || der == NULL)
        return BAD_FUNC_ARG;

    if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
        dsaKey == NULL && ed448Key == NULL && falconKey == NULL &&
        falconKey == NULL) {
        return PUBLIC_KEY_E;
    }

    /* init */
    XMEMSET(der, 0, sizeof(DerCert));

    /* version */
    der->versionSz = SetMyVersion((word32)cert->version, der->version, FALSE);

    /* subject name */
#if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
    if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
        /* Use the raw subject */
        int idx;

        der->subjectSz = (int)min(sizeof(der->subject),
                (word32)XSTRLEN((const char*)cert->sbjRaw));
        /* header */
        idx = (int)SetSequence((word32)der->subjectSz, der->subject);
        if (der->subjectSz + idx > (int)sizeof(der->subject)) {
            return SUBJECT_E;
        }

        XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw,
                (size_t)der->subjectSz);
        der->subjectSz += idx;
    }
    else
#endif
    {
        der->subjectSz = SetNameEx(der->subject, sizeof(der->subject),
                &cert->subject, cert->heap);
    }
    if (der->subjectSz <= 0)
        return SUBJECT_E;

    /* public key */
#ifndef NO_RSA
    if (cert->keyType == RSA_KEY) {
        if (rsaKey == NULL)
            return PUBLIC_KEY_E;
        der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
                                           sizeof(der->publicKey), 1);
    }
#endif

#if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
    if (cert->keyType == DSA_KEY) {
        if (dsaKey == NULL)
            return PUBLIC_KEY_E;
        der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
                                           sizeof(der->publicKey), 1);
    }
#endif

#ifdef HAVE_ECC
    if (cert->keyType == ECC_KEY) {
        if (eccKey == NULL)
            return PUBLIC_KEY_E;
        der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey,
                                           sizeof(der->publicKey), 1, 0);
    }
#endif

#if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
    if (cert->keyType == ED25519_KEY) {
        if (ed25519Key == NULL)
            return PUBLIC_KEY_E;
        der->publicKeySz = wc_Ed25519PublicKeyToDer(ed25519Key, der->publicKey,
            (word32)sizeof(der->publicKey), 1);
    }
#endif

#if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
    if (cert->keyType == ED448_KEY) {
        if (ed448Key == NULL)
            return PUBLIC_KEY_E;
        der->publicKeySz = wc_Ed448PublicKeyToDer(ed448Key, der->publicKey,
            (word32)sizeof(der->publicKey), 1);
    }
#endif
#if defined(HAVE_PQC)
#if defined(HAVE_FALCON)
    if ((cert->keyType == FALCON_LEVEL1_KEY) ||
        (cert->keyType == FALCON_LEVEL5_KEY)) {
        if (falconKey == NULL)
            return PUBLIC_KEY_E;
        der->publicKeySz = wc_Falcon_PublicKeyToDer(falconKey,
            der->publicKey, (word32)sizeof(der->publicKey), 1);
    }
#endif
#if defined(HAVE_DILITHIUM)
    if ((cert->keyType == DILITHIUM_LEVEL2_KEY) ||
        (cert->keyType == DILITHIUM_LEVEL3_KEY) ||
        (cert->keyType == DILITHIUM_LEVEL5_KEY)) {
        if (dilithiumKey == NULL)
            return PUBLIC_KEY_E;
        der->publicKeySz = wc_Dilithium_PublicKeyToDer(dilithiumKey,
            der->publicKey, (word32)sizeof(der->publicKey), 1);
    }
#endif
#if defined(HAVE_SPHINCS)
    if ((cert->keyType == SPHINCS_FAST_LEVEL1_KEY) ||
        (cert->keyType == SPHINCS_FAST_LEVEL3_KEY) ||
        (cert->keyType == SPHINCS_FAST_LEVEL5_KEY) ||
        (cert->keyType == SPHINCS_SMALL_LEVEL1_KEY) ||
        (cert->keyType == SPHINCS_SMALL_LEVEL3_KEY) ||
        (cert->keyType == SPHINCS_SMALL_LEVEL5_KEY)) {
        if (sphincsKey == NULL)
            return PUBLIC_KEY_E;
        der->publicKeySz = wc_Sphincs_PublicKeyToDer(sphincsKey,
            der->publicKey, (word32)sizeof(der->publicKey), 1);
    }
#endif
#endif /* HAVE_PQC */

    if (der->publicKeySz <= 0)
        return PUBLIC_KEY_E;

    /* set the extensions */
    der->extensionsSz = 0;

    /* RFC 5280 : 4.2.1.9. Basic Constraints
     * The pathLenConstraint field is meaningful only if the CA boolean is
     * asserted and the key usage extension, if present, asserts the
     * keyCertSign bit */
    /* Set CA and path length */
    if ((cert->isCA) && (cert->pathLenSet)
#ifdef WOLFSSL_CERT_EXT
        && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
#endif
        ) {
        der->caSz = SetCaWithPathLen(der->ca, sizeof(der->ca), cert->pathLen);
        if (der->caSz <= 0)
            return CA_TRUE_E;

        der->extensionsSz += der->caSz;
    }
    /* Set CA */
    else if (cert->isCA) {
        der->caSz = SetCa(der->ca, sizeof(der->ca));
        if (der->caSz <= 0)
            return CA_TRUE_E;

        der->extensionsSz += der->caSz;
    }
    /* Set Basic Constraint */
    else if (cert->basicConstSet) {
        der->caSz = SetBC(der->ca, sizeof(der->ca));
        if (der->caSz <= 0)
            return EXTENSIONS_E;

        der->extensionsSz += der->caSz;
    }
    else
        der->caSz = 0;

#ifdef WOLFSSL_ALT_NAMES
    /* Alternative Name */
    if (cert->altNamesSz) {
        der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
                                      cert->altNames, (word32)cert->altNamesSz,
                                      cert->altNamesCrit);
        if (der->altNamesSz <= 0)
            return ALT_NAME_E;

        der->extensionsSz += der->altNamesSz;
    }
    else
        der->altNamesSz = 0;
#endif

#ifdef WOLFSSL_CERT_EXT
    /* SKID */
    if (cert->skidSz) {
        /* check the provided SKID size */
        if (cert->skidSz > (int)min(CTC_MAX_SKID_SIZE, sizeof(der->skid)))
            return SKID_E;

        der->skidSz = SetSKID(der->skid, sizeof(der->skid),
                              cert->skid, (word32)cert->skidSz);
        if (der->skidSz <= 0)
            return SKID_E;

        der->extensionsSz += der->skidSz;
    }
    else
        der->skidSz = 0;

    /* Key Usage */
    if (cert->keyUsage != 0) {
        der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
                                      cert->keyUsage);
        if (der->keyUsageSz <= 0)
            return KEYUSAGE_E;

        der->extensionsSz += der->keyUsageSz;
    }
    else
        der->keyUsageSz = 0;

    /* Extended Key Usage */
    if (cert->extKeyUsage != 0) {
        der->extKeyUsageSz = SetExtKeyUsage(cert, der->extKeyUsage,
                                sizeof(der->extKeyUsage), cert->extKeyUsage);
        if (der->extKeyUsageSz <= 0)
            return EXTKEYUSAGE_E;

        der->extensionsSz += der->extKeyUsageSz;
    }
    else
        der->extKeyUsageSz = 0;

#endif /* WOLFSSL_CERT_EXT */

#ifdef WOLFSSL_CUSTOM_OID
    /* encode a custom oid and value */
    /* zero returns, means none set */
    ret = SetCustomObjectId(cert, der->extCustom,
        sizeof(der->extCustom), &cert->extCustom);
    if (ret < 0)
        return ret;
    der->extCustomSz = ret;
    der->extensionsSz += der->extCustomSz;
#endif

    /* put extensions */
    if (der->extensionsSz > 0) {
        /* put the start of sequence (ID, Size) */
        der->extensionsSz = (int)SetSequence((word32)der->extensionsSz,
                                             der->extensions);
        if (der->extensionsSz <= 0)
            return EXTENSIONS_E;

        /* put CA */
        if (der->caSz) {
            ret = SetExtensions(der->extensions, sizeof(der->extensions),
                                &der->extensionsSz,
                                der->ca, der->caSz);
            if (ret <= 0)
                return EXTENSIONS_E;
        }

#ifdef WOLFSSL_ALT_NAMES
        /* put Alternative Names */
        if (der->altNamesSz) {
            ret = SetExtensions(der->extensions, sizeof(der->extensions),
                                &der->extensionsSz,
                                der->altNames, der->altNamesSz);
            if (ret <= 0)
                return EXTENSIONS_E;
        }
#endif

#ifdef WOLFSSL_CERT_EXT
        /* put SKID */
        if (der->skidSz) {
            ret = SetExtensions(der->extensions, sizeof(der->extensions),
                                &der->extensionsSz,
                                der->skid, der->skidSz);
            if (ret <= 0)
                return EXTENSIONS_E;
        }

        /* put AKID */
        if (der->akidSz) {
            ret = SetExtensions(der->extensions, sizeof(der->extensions),
                                &der->extensionsSz,
                                der->akid, der->akidSz);
            if (ret <= 0)
                return EXTENSIONS_E;
        }

        /* put KeyUsage */
        if (der->keyUsageSz) {
            ret = SetExtensions(der->extensions, sizeof(der->extensions),
                                &der->extensionsSz,
                                der->keyUsage, der->keyUsageSz);
            if (ret <= 0)
                return EXTENSIONS_E;
        }

        /* put ExtendedKeyUsage */
        if (der->extKeyUsageSz) {
            ret = SetExtensions(der->extensions, sizeof(der->extensions),
                                &der->extensionsSz,
                                der->extKeyUsage, der->extKeyUsageSz);
            if (ret <= 0)
                return EXTENSIONS_E;
        }

    #ifdef WOLFSSL_CUSTOM_OID
        if (der->extCustomSz) {
            ret = SetExtensions(der->extensions, sizeof(der->extensions),
                                &der->extensionsSz,
                                der->extCustom, der->extCustomSz);
            if (ret <= 0)
                return EXTENSIONS_E;
        }
    #endif
#endif /* WOLFSSL_CERT_EXT */
    }

    der->attribSz = SetReqAttrib(der->attrib, cert, (word32)der->extensionsSz);
    if (der->attribSz <= 0)
        return REQ_ATTRIBUTE_E;

    der->total = der->versionSz + der->subjectSz + der->publicKeySz +
        der->extensionsSz + der->attribSz;

    return 0;
}


/* write DER encoded cert req to buffer, size already checked */
static int WriteCertReqBody(DerCert* der, byte* buf)
{
    int idx;

    /* signed part header */
    idx = (int)SetSequence((word32)der->total, buf);
    /* version */
    if (buf)
        XMEMCPY(buf + idx, der->version, (size_t)der->versionSz);
    idx += der->versionSz;
    /* subject */
    if (buf)
        XMEMCPY(buf + idx, der->subject, (size_t)der->subjectSz);
    idx += der->subjectSz;
    /* public key */
    if (buf)
        XMEMCPY(buf + idx, der->publicKey, (size_t)der->publicKeySz);
    idx += der->publicKeySz;
    /* attributes */
    if (buf)
        XMEMCPY(buf + idx, der->attrib, (size_t)der->attribSz);
    idx += der->attribSz;
    /* extensions */
    if (der->extensionsSz) {
        if (buf)
            XMEMCPY(buf + idx, der->extensions, min((word32)der->extensionsSz,
                                               sizeof(der->extensions)));
        idx += der->extensionsSz;
    }

    return idx;
}
#endif

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for Certificate Request body.
 * PKCS #10: RFC 2986, 4.1 - CertificationRequestInfo
 */
static const ASNItem certReqBodyASN[] = {
/* SEQ             */ { 0, ASN_SEQUENCE, 1, 1, 0 },
                                             /* version */
/* VER             */     { 1, ASN_INTEGER, 0, 0, 0 },
                                             /* subject */
/* SUBJ_SEQ        */     { 1, ASN_SEQUENCE, 1, 0, 0 },
                                             /* subjectPKInfo */
/* SPUBKEYINFO_SEQ */     { 1, ASN_SEQUENCE, 1, 0, 0 },
                                             /*  attributes*/
/* ATTRS           */     { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
                                                 /* Challenge Password Attribute */
/* ATTRS_CPW_SEQ   */         { 2, ASN_SEQUENCE, 1, 1, 1 },
/* ATTRS_CPW_OID   */             { 3, ASN_OBJECT_ID, 0, 0, 0 },
/* ATTRS_CPW_SET   */             { 3, ASN_SET, 1, 1, 0 },
/* ATTRS_CPW_PS    */                 { 4, ASN_PRINTABLE_STRING, 0, 0, 0 },
/* ATTRS_CPW_UTF   */                 { 4, ASN_UTF8STRING, 0, 0, 0 },
                                                 /* Extensions Attribute */
/* EXT_SEQ         */         { 2, ASN_SEQUENCE, 1, 1, 1 },
/* EXT_OID         */             { 3, ASN_OBJECT_ID, 0, 0, 0 },
/* EXT_SET         */             { 3, ASN_SET, 1, 1, 0 },
/* EXT_BODY        */                 { 4, ASN_SEQUENCE, 1, 0, 0 },
};
enum {
    CERTREQBODYASN_IDX_SEQ = 0,
    CERTREQBODYASN_IDX_VER,
    CERTREQBODYASN_IDX_SUBJ_SEQ,
    CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ,
    CERTREQBODYASN_IDX_ATTRS,
    CERTREQBODYASN_IDX_ATTRS_CPW_SEQ,
    CERTREQBODYASN_IDX_ATTRS_CPW_OID,
    CERTREQBODYASN_IDX_ATTRS_CPW_SET,
    CERTREQBODYASN_IDX_ATTRS_CPW_PS,
    CERTREQBODYASN_IDX_ATTRS_CPW_UTF,
    CERTREQBODYASN_IDX_EXT_SEQ,
    CERTREQBODYASN_IDX_EXT_OID,
    CERTREQBODYASN_IDX_EXT_SET,
    CERTREQBODYASN_IDX_EXT_BODY
};

/* Number of items in ASN.1 template for Certificate Request body. */
#define certReqBodyASN_Length (sizeof(certReqBodyASN) / sizeof(ASNItem))
#endif

static int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
                   RsaKey* rsaKey, DsaKey* dsaKey, ecc_key* eccKey,
                   ed25519_key* ed25519Key, ed448_key* ed448Key,
                   falcon_key* falconKey, dilithium_key* dilithiumKey,
                   sphincs_key* sphincsKey)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int ret;
#ifdef WOLFSSL_SMALL_STACK
    DerCert* der;
#else
    DerCert der[1];
#endif

    if (eccKey)
        cert->keyType = ECC_KEY;
    else if (rsaKey)
        cert->keyType = RSA_KEY;
    else if (dsaKey)
        cert->keyType = DSA_KEY;
    else if (ed25519Key)
        cert->keyType = ED25519_KEY;
    else if (ed448Key)
        cert->keyType = ED448_KEY;
#ifdef HAVE_PQC
#ifdef HAVE_FALCON
    else if ((falconKey != NULL) && (falconKey->level == 1))
        cert->keyType = FALCON_LEVEL1_KEY;
    else if ((falconKey != NULL) && (falconKey->level == 5))
        cert->keyType = FALCON_LEVEL5_KEY;
#endif /* HAVE_FALCON */
#ifdef HAVE_DILITHIUM
    else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2))
        cert->keyType = DILITHIUM_LEVEL2_KEY;
    else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3))
        cert->keyType = DILITHIUM_LEVEL3_KEY;
    else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5))
        cert->keyType = DILITHIUM_LEVEL5_KEY;
#endif /* HAVE_DILITHIUM */
#ifdef HAVE_SPHINCS
    else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
             && (sphincsKey->optim == FAST_VARIANT))
        cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
    else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
             && (sphincsKey->optim == FAST_VARIANT))
        cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
    else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
             && (sphincsKey->optim == FAST_VARIANT))
        cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
    else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
             && (sphincsKey->optim == SMALL_VARIANT))
        cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
    else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
             && (sphincsKey->optim == SMALL_VARIANT))
        cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
    else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
             && (sphincsKey->optim == SMALL_VARIANT))
        cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
#endif /* HAVE_SPHINCS */
#endif /* HAVE_PQC */
    else
        return BAD_FUNC_ARG;

#ifdef WOLFSSL_SMALL_STACK
    der = (DerCert*)XMALLOC(sizeof(DerCert), cert->heap,
                                                    DYNAMIC_TYPE_TMP_BUFFER);
    if (der == NULL)
        return MEMORY_E;
#endif

    ret = EncodeCertReq(cert, der, rsaKey, dsaKey, eccKey, ed25519Key, ed448Key,
                        falconKey, dilithiumKey, sphincsKey);

    if (ret == 0) {
        if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
            ret = BUFFER_E;
        else
            ret = cert->bodySz = WriteCertReqBody(der, derBuffer);
    }

#ifdef WOLFSSL_SMALL_STACK
    XFREE(der, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
#endif

    return ret;
#else
    DECL_ASNSETDATA(dataASN, certReqBodyASN_Length);
    word32 publicKeySz = 0;
    word32 subjectSz = 0;
    word32 extSz = 0;
    int sz = 0;
    int ret = 0;
#if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
    word32 sbjRawSz = 0;
#endif

    /* Unused without OQS */
    (void)falconKey;
    (void)dilithiumKey;
    (void)sphincsKey;

    CALLOC_ASNSETDATA(dataASN, certReqBodyASN_Length, ret, cert->heap);

    if (ret == 0) {
        /* Set key type into certificate object based on key passed in. */
        if (rsaKey != NULL) {
            cert->keyType = RSA_KEY;
        }
        else if (eccKey != NULL) {
            cert->keyType = ECC_KEY;
        }
        else if (dsaKey != NULL) {
            cert->keyType = DSA_KEY;
        }
        else if (ed25519Key != NULL) {
            cert->keyType = ED25519_KEY;
        }
        else if (ed448Key != NULL) {
            cert->keyType = ED448_KEY;
        }
#ifdef HAVE_PQC
#ifdef HAVE_FALCON
        else if ((falconKey != NULL) && (falconKey->level == 1)) {
            cert->keyType = FALCON_LEVEL1_KEY;
        }
        else if ((falconKey != NULL) && (falconKey->level == 5)) {
            cert->keyType = FALCON_LEVEL5_KEY;
        }
#endif /* HAVE_FALCON */
#ifdef HAVE_DILITHIUM
        else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)) {
            cert->keyType = DILITHIUM_LEVEL2_KEY;
        }
        else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)) {
            cert->keyType = DILITHIUM_LEVEL3_KEY;
        }
        else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)) {
            cert->keyType = DILITHIUM_LEVEL5_KEY;
        }
#endif /* HAVE_DILITHIUM */
#ifdef HAVE_SPHINCS
        else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
                 && (sphincsKey->optim == FAST_VARIANT)) {
            cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
        }
        else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
                 && (sphincsKey->optim == FAST_VARIANT)) {
            cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
        }
        else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
                 && (sphincsKey->optim == FAST_VARIANT)) {
            cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
        }
        else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
                 && (sphincsKey->optim == SMALL_VARIANT)) {
            cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
        }
        else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
                 && (sphincsKey->optim == SMALL_VARIANT)) {
            cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
        }
        else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
                 && (sphincsKey->optim == SMALL_VARIANT)) {
            cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
        }
#endif /* HAVE_SPHINCS */
#endif /* HAVE_PQC */
        else {
            ret = BAD_FUNC_ARG;
        }
    }
    if (ret == 0) {
        /* Determine subject name size. */
    #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
        sbjRawSz = (word32)XSTRLEN((const char*)cert->sbjRaw);
        if (sbjRawSz > 0) {
            subjectSz = min(sizeof(cert->sbjRaw), sbjRawSz);
        }
        else
    #endif
        {
            ret = SetNameEx(NULL, WC_ASN_NAME_MAX, &cert->subject, cert->heap);
            subjectSz = (word32)ret;
        }
    }
    if (ret >= 0) {
        /* Determine encode public key size. */
         ret = EncodePublicKey(cert->keyType, NULL, 0, rsaKey,
             eccKey, ed25519Key, ed448Key, dsaKey);
         publicKeySz = (word32)ret;
    }
    if (ret >= 0) {
        /* Determine encode extensions size. */
        ret = EncodeExtensions(cert, NULL, 0, 1);
        extSz = (word32)ret;
    }
    if (ret >= 0) {
        /* Set version. */
        SetASN_Int8Bit(&dataASN[CERTREQBODYASN_IDX_VER], (byte)cert->version);
    #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
        if (sbjRawSz > 0) {
            /* Put in encoded subject name. */
            SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ], cert->sbjRaw,
                    subjectSz);
        }
        else
    #endif
        {
            /* Leave space for subject name. */
            SetASN_ReplaceBuffer(&dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ], NULL,
                    subjectSz);
        }
        /* Leave space for public key. */
        SetASN_ReplaceBuffer(&dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ],
                NULL, publicKeySz);
        if (cert->challengePw[0] != '\0') {
            /* Add challenge password attribute. */
            /* Set challenge password OID. */
            SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_OID],
                attrChallengePasswordOid, sizeof(attrChallengePasswordOid));
            /* Enable the ASN template item with the appropriate tag. */
            if (cert->challengePwPrintableString) {
                /* PRINTABLE_STRING - set buffer */
                SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_PS],
                        (byte*)cert->challengePw,
                        (word32)XSTRLEN(cert->challengePw));
                /* UTF8STRING - don't encode */
                dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_UTF].noOut = 1;
            }
            else {
                /* PRINTABLE_STRING - don't encode */
                dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_PS].noOut = 1;
                /* UTF8STRING - set buffer */
                SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_UTF],
                        (byte*)cert->challengePw,
                        (word32)XSTRLEN(cert->challengePw));
            }
        }
        else {
            /* Leave out challenge password attribute items. */
            SetASNItem_NoOutNode(dataASN, certReqBodyASN,
                    CERTREQBODYASN_IDX_ATTRS_CPW_SEQ, certReqBodyASN_Length);
        }
        if (extSz > 0) {
            /* Set extension attribute OID. */
            SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_EXT_OID], attrExtensionRequestOid,
                sizeof(attrExtensionRequestOid));
            /* Leave space for data. */
            SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_EXT_BODY], NULL, extSz);
        }
        else {
            /* Leave out extension attribute items. */
            SetASNItem_NoOutNode(dataASN, certReqBodyASN,
                    CERTREQBODYASN_IDX_EXT_SEQ, certReqBodyASN_Length);
        }

        /* Calculate size of encoded certificate request body. */
        ret = SizeASN_Items(certReqBodyASN, dataASN, certReqBodyASN_Length,
                            &sz);
    }
    /* Check buffer is big enough for encoded data. */
    if ((ret == 0) && (sz > (int)derSz)) {
        ret = BUFFER_E;
    }
    if (ret == 0 && derBuffer != NULL) {
        /* Encode certificate request body into buffer. */
        SetASN_Items(certReqBodyASN, dataASN, certReqBodyASN_Length, derBuffer);

        /* Put in generated data */
    #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
        if (sbjRawSz == 0)
    #endif
        {
            /* Encode subject name into space in buffer. */
            ret = SetNameEx(
                (byte*)dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ].data.buffer.data,
                dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ].data.buffer.length,
                &cert->subject, cert->heap);
        }
    }
    if (ret >= 0 && derBuffer != NULL) {
        /* Encode public key into space in buffer. */
        ret = EncodePublicKey(cert->keyType,
            (byte*)dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ].data.buffer.data,
            (int)dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ].data.buffer.length,
            rsaKey, eccKey, ed25519Key, ed448Key, dsaKey);
    }
    if ((ret >= 0 && derBuffer != NULL) &&
            (!dataASN[CERTREQBODYASN_IDX_EXT_BODY].noOut)) {
        /* Encode extensions into space in buffer. */
        ret = EncodeExtensions(cert,
                (byte*)dataASN[CERTREQBODYASN_IDX_EXT_BODY].data.buffer.data,
                dataASN[CERTREQBODYASN_IDX_EXT_BODY].data.buffer.length, 1);
    }
    if (ret >= 0) {
        /* Store encoded certifcate request body size. */
        cert->bodySz = sz;
        /* Return the encoding size. */
        ret = sz;
    }

    FREE_ASNSETDATA(dataASN, cert->heap);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

int wc_MakeCertReq_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
                      void* key)
{
    RsaKey*        rsaKey = NULL;
    DsaKey*        dsaKey = NULL;
    ecc_key*       eccKey = NULL;
    ed25519_key*   ed25519Key = NULL;
    ed448_key*     ed448Key = NULL;
    falcon_key*    falconKey = NULL;
    dilithium_key* dilithiumKey = NULL;
    sphincs_key*   sphincsKey = NULL;

    if (keyType == RSA_TYPE)
        rsaKey = (RsaKey*)key;
    else if (keyType == DSA_TYPE)
        dsaKey = (DsaKey*)key;
    else if (keyType == ECC_TYPE)
        eccKey = (ecc_key*)key;
    else if (keyType == ED25519_TYPE)
        ed25519Key = (ed25519_key*)key;
    else if (keyType == ED448_TYPE)
        ed448Key = (ed448_key*)key;
    else if (keyType == FALCON_LEVEL1_TYPE)
        falconKey = (falcon_key*)key;
    else if (keyType == FALCON_LEVEL5_TYPE)
        falconKey = (falcon_key*)key;
    else if (keyType == DILITHIUM_LEVEL2_TYPE)
        dilithiumKey = (dilithium_key*)key;
    else if (keyType == DILITHIUM_LEVEL3_TYPE)
        dilithiumKey = (dilithium_key*)key;
    else if (keyType == DILITHIUM_LEVEL5_TYPE)
        dilithiumKey = (dilithium_key*)key;
    else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
        sphincsKey = (sphincs_key*)key;
    else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
        sphincsKey = (sphincs_key*)key;
    else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
        sphincsKey = (sphincs_key*)key;
    else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
        sphincsKey = (sphincs_key*)key;
    else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
        sphincsKey = (sphincs_key*)key;
    else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
        sphincsKey = (sphincs_key*)key;

    return MakeCertReq(cert, derBuffer, derSz, rsaKey, dsaKey, eccKey,
                       ed25519Key, ed448Key, falconKey, dilithiumKey,
                       sphincsKey);
}

WOLFSSL_ABI
int wc_MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
                   RsaKey* rsaKey, ecc_key* eccKey)
{
    return MakeCertReq(cert, derBuffer, derSz, rsaKey, NULL, eccKey, NULL,
                       NULL, NULL, NULL, NULL);
}
#endif /* WOLFSSL_CERT_REQ */


static int SignCert(int requestSz, int sType, byte* buf, word32 buffSz,
                    RsaKey* rsaKey, ecc_key* eccKey, ed25519_key* ed25519Key,
                    ed448_key* ed448Key, falcon_key* falconKey,
                    dilithium_key* dilithiumKey, sphincs_key* sphincsKey,
                    WC_RNG* rng)
{
    int sigSz = 0;
    void* heap = NULL;
    CertSignCtx  certSignCtx_lcl;
    CertSignCtx* certSignCtx = &certSignCtx_lcl;

    XMEMSET(certSignCtx, 0, sizeof(*certSignCtx));

    if (requestSz < 0)
        return requestSz;

    /* locate ctx */
    if (rsaKey) {
    #ifndef NO_RSA
    #ifdef WOLFSSL_ASYNC_CRYPT
        certSignCtx = &rsaKey->certSignCtx;
    #endif
        heap = rsaKey->heap;
    #else
        return NOT_COMPILED_IN;
    #endif /* NO_RSA */
    }
    else if (eccKey) {
    #ifdef HAVE_ECC
    #ifdef WOLFSSL_ASYNC_CRYPT
        certSignCtx = &eccKey->certSignCtx;
    #endif
        heap = eccKey->heap;
    #else
        return NOT_COMPILED_IN;
    #endif /* HAVE_ECC */
    }

    if (certSignCtx->sig == NULL) {
        certSignCtx->sig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, heap,
            DYNAMIC_TYPE_TMP_BUFFER);
        if (certSignCtx->sig == NULL)
            return MEMORY_E;
    }

    sigSz = MakeSignature(certSignCtx, buf, (word32)requestSz, certSignCtx->sig,
        MAX_ENCODED_SIG_SZ, rsaKey, eccKey, ed25519Key, ed448Key,
        falconKey, dilithiumKey, sphincsKey, rng, (word32)sType, heap);
#ifdef WOLFSSL_ASYNC_CRYPT
    if (sigSz == WC_PENDING_E) {
        /* Not free'ing certSignCtx->sig here because it could still be in use
         * with async operations. */
        return sigSz;
    }
#endif

    if (sigSz >= 0) {
        if (requestSz + MAX_SEQ_SZ * 2 + sigSz > (int)buffSz)
            sigSz = BUFFER_E;
        else
            sigSz = AddSignature(buf, requestSz, certSignCtx->sig, sigSz,
                                 sType);
    }

    XFREE(certSignCtx->sig, heap, DYNAMIC_TYPE_TMP_BUFFER);
    certSignCtx->sig = NULL;

    return sigSz;
}

int wc_SignCert_ex(int requestSz, int sType, byte* buf, word32 buffSz,
                   int keyType, void* key, WC_RNG* rng)
{
    RsaKey*            rsaKey = NULL;
    ecc_key*           eccKey = NULL;
    ed25519_key*       ed25519Key = NULL;
    ed448_key*         ed448Key = NULL;
    falcon_key*        falconKey = NULL;
    dilithium_key*     dilithiumKey = NULL;
    sphincs_key*       sphincsKey = NULL;

    if (keyType == RSA_TYPE)
        rsaKey = (RsaKey*)key;
    else if (keyType == ECC_TYPE)
        eccKey = (ecc_key*)key;
    else if (keyType == ED25519_TYPE)
        ed25519Key = (ed25519_key*)key;
    else if (keyType == ED448_TYPE)
        ed448Key = (ed448_key*)key;
    else if (keyType == FALCON_LEVEL1_TYPE)
        falconKey = (falcon_key*)key;
    else if (keyType == FALCON_LEVEL5_TYPE)
        falconKey = (falcon_key*)key;
    else if (keyType == DILITHIUM_LEVEL2_TYPE)
        dilithiumKey = (dilithium_key*)key;
    else if (keyType == DILITHIUM_LEVEL3_TYPE)
        dilithiumKey = (dilithium_key*)key;
    else if (keyType == DILITHIUM_LEVEL5_TYPE)
        dilithiumKey = (dilithium_key*)key;
    else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
        sphincsKey = (sphincs_key*)key;
    else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
        sphincsKey = (sphincs_key*)key;
    else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
        sphincsKey = (sphincs_key*)key;
    else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
        sphincsKey = (sphincs_key*)key;
    else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
        sphincsKey = (sphincs_key*)key;
    else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
        sphincsKey = (sphincs_key*)key;

    return SignCert(requestSz, sType, buf, buffSz, rsaKey, eccKey, ed25519Key,
                    ed448Key, falconKey, dilithiumKey, sphincsKey, rng);
}

int wc_SignCert(int requestSz, int sType, byte* buf, word32 buffSz,
                RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng)
{
    return SignCert(requestSz, sType, buf, buffSz, rsaKey, eccKey, NULL, NULL,
                    NULL, NULL, NULL, rng);
}

WOLFSSL_ABI
int wc_MakeSelfCert(Cert* cert, byte* buf, word32 buffSz,
                    RsaKey* key, WC_RNG* rng)
{
    int ret;

    ret = wc_MakeCert(cert, buf, buffSz, key, NULL, rng);
    if (ret < 0)
        return ret;

    return wc_SignCert(cert->bodySz, cert->sigType,
                       buf, buffSz, key, NULL, rng);
}


#ifdef WOLFSSL_CERT_EXT

/* Get raw subject from cert, which may contain OIDs not parsed by Decode.
   The raw subject pointer will only be valid while "cert" is valid. */
WOLFSSL_ABI
int wc_GetSubjectRaw(byte **subjectRaw, Cert *cert)
{
    int rc = BAD_FUNC_ARG;
    if ((subjectRaw != NULL) && (cert != NULL)) {
        *subjectRaw = cert->sbjRaw;
        rc = 0;
    }
    return rc;
}

/* Set KID from public key */
static int SetKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey,
                                 ed25519_key* ed25519Key, ed448_key* ed448Key,
                                 falcon_key* falconKey,
                                 dilithium_key* dilithiumKey,
                                 sphincs_key *sphincsKey, int kid_type)
{
    byte *buf;
    int   bufferSz, ret;

    if (cert == NULL ||
        (rsakey == NULL && eckey == NULL && ed25519Key == NULL &&
         ed448Key == NULL && falconKey == NULL && dilithiumKey == NULL &&
         sphincsKey == NULL) ||
        (kid_type != SKID_TYPE && kid_type != AKID_TYPE))
        return BAD_FUNC_ARG;

    buf = (byte *)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap,
                                                       DYNAMIC_TYPE_TMP_BUFFER);
    if (buf == NULL)
        return MEMORY_E;

    /* Public Key */
    bufferSz = -1;
#ifndef NO_RSA
    /* RSA public key */
    if (rsakey != NULL)
        bufferSz = SetRsaPublicKey(buf, rsakey, MAX_PUBLIC_KEY_SZ, 0);
#endif
#ifdef HAVE_ECC
    /* ECC public key */
    if (eckey != NULL)
        bufferSz = SetEccPublicKey(buf, eckey, MAX_PUBLIC_KEY_SZ, 0, 0);
#endif
#if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
    /* ED25519 public key */
    if (ed25519Key != NULL) {
        bufferSz = wc_Ed25519PublicKeyToDer(ed25519Key, buf, MAX_PUBLIC_KEY_SZ, 0);
    }
#endif
#if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
    /* ED448 public key */
    if (ed448Key != NULL) {
        bufferSz = wc_Ed448PublicKeyToDer(ed448Key, buf, MAX_PUBLIC_KEY_SZ, 0);
    }
#endif
#if defined(HAVE_PQC)
#if defined(HAVE_FALCON)
    if (falconKey != NULL) {
        bufferSz = wc_Falcon_PublicKeyToDer(falconKey, buf, MAX_PUBLIC_KEY_SZ,
                                            0);
    }
#endif
#if defined(HAVE_DILITHIUM)
    if (dilithiumKey != NULL) {
        bufferSz = wc_Dilithium_PublicKeyToDer(dilithiumKey, buf,
                                               MAX_PUBLIC_KEY_SZ, 0);
    }
#endif
#if defined(HAVE_SPHINCS)
    if (sphincsKey != NULL) {
        bufferSz = wc_Sphincs_PublicKeyToDer(sphincsKey, buf,
                                               MAX_PUBLIC_KEY_SZ, 0);
    }
#endif
#endif /* HAVE_PQC */

    if (bufferSz <= 0) {
        XFREE(buf, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
        return PUBLIC_KEY_E;
    }

    /* Compute SKID by hashing public key */
    if (kid_type == SKID_TYPE) {
        ret = CalcHashId(buf, (word32)bufferSz, cert->skid);
        cert->skidSz = KEYID_SIZE;
    }
    else if (kid_type == AKID_TYPE) {
        ret = CalcHashId(buf, (word32)bufferSz, cert->akid);
        cert->akidSz = KEYID_SIZE;
    }
    else
        ret = BAD_FUNC_ARG;

    XFREE(buf, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
    return ret;
}

int wc_SetSubjectKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
{
    RsaKey*            rsaKey = NULL;
    ecc_key*           eccKey = NULL;
    ed25519_key*       ed25519Key = NULL;
    ed448_key*         ed448Key = NULL;
    falcon_key*        falconKey = NULL;
    dilithium_key*     dilithiumKey = NULL;
    sphincs_key*       sphincsKey = NULL;

    if (keyType == RSA_TYPE)
        rsaKey = (RsaKey*)key;
    else if (keyType == ECC_TYPE)
        eccKey = (ecc_key*)key;
    else if (keyType == ED25519_TYPE)
        ed25519Key = (ed25519_key*)key;
    else if (keyType == ED448_TYPE)
        ed448Key = (ed448_key*)key;
    else if (keyType == FALCON_LEVEL1_TYPE)
        falconKey = (falcon_key*)key;
    else if (keyType == FALCON_LEVEL5_TYPE)
        falconKey = (falcon_key*)key;
    else if (keyType == DILITHIUM_LEVEL2_TYPE)
        dilithiumKey = (dilithium_key*)key;
    else if (keyType == DILITHIUM_LEVEL3_TYPE)
        dilithiumKey = (dilithium_key*)key;
    else if (keyType == DILITHIUM_LEVEL5_TYPE)
        dilithiumKey = (dilithium_key*)key;
    else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
        sphincsKey = (sphincs_key*)key;
    else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
        sphincsKey = (sphincs_key*)key;
    else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
        sphincsKey = (sphincs_key*)key;
    else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
        sphincsKey = (sphincs_key*)key;
    else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
        sphincsKey = (sphincs_key*)key;
    else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
        sphincsKey = (sphincs_key*)key;

    return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, ed25519Key, ed448Key,
                                 falconKey, dilithiumKey, sphincsKey,
                                 SKID_TYPE);
}

/* Set SKID from RSA or ECC public key */
int wc_SetSubjectKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
{
    return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, NULL, NULL, NULL,
                                 NULL, SKID_TYPE);
}

int wc_SetAuthKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
{
    RsaKey*            rsaKey = NULL;
    ecc_key*           eccKey = NULL;
    ed25519_key*       ed25519Key = NULL;
    ed448_key*         ed448Key = NULL;
    falcon_key*        falconKey = NULL;
    dilithium_key*     dilithiumKey = NULL;
    sphincs_key*       sphincsKey = NULL;

    if (keyType == RSA_TYPE)
        rsaKey = (RsaKey*)key;
    else if (keyType == ECC_TYPE)
        eccKey = (ecc_key*)key;
    else if (keyType == ED25519_TYPE)
        ed25519Key = (ed25519_key*)key;
    else if (keyType == ED448_TYPE)
        ed448Key = (ed448_key*)key;
    else if (keyType == FALCON_LEVEL1_TYPE)
        falconKey = (falcon_key*)key;
    else if (keyType == FALCON_LEVEL5_TYPE)
        falconKey = (falcon_key*)key;
    else if (keyType == DILITHIUM_LEVEL2_TYPE)
        dilithiumKey = (dilithium_key*)key;
    else if (keyType == DILITHIUM_LEVEL3_TYPE)
        dilithiumKey = (dilithium_key*)key;
    else if (keyType == DILITHIUM_LEVEL5_TYPE)
        dilithiumKey = (dilithium_key*)key;
    else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
        sphincsKey = (sphincs_key*)key;
    else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
        sphincsKey = (sphincs_key*)key;
    else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
        sphincsKey = (sphincs_key*)key;
    else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
        sphincsKey = (sphincs_key*)key;
    else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
        sphincsKey = (sphincs_key*)key;
    else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
        sphincsKey = (sphincs_key*)key;

    return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, ed25519Key, ed448Key,
                                 falconKey, dilithiumKey, sphincsKey,
                                 AKID_TYPE);
}

/* Set SKID from RSA or ECC public key */
int wc_SetAuthKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
{
    return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, NULL, NULL, NULL,
                                 NULL, AKID_TYPE);
}


#if !defined(NO_FILESYSTEM) && !defined(NO_ASN_CRYPT)

/* Set SKID from public key file in PEM */
int wc_SetSubjectKeyId(Cert *cert, const char* file)
{
    int     ret, derSz;
    byte*   der;
    word32  idx;
    RsaKey  *rsakey = NULL;
    ecc_key *eckey = NULL;

    if (cert == NULL || file == NULL)
        return BAD_FUNC_ARG;

    der = (byte*)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap, DYNAMIC_TYPE_CERT);
    if (der == NULL) {
        WOLFSSL_MSG("wc_SetSubjectKeyId memory Problem");
        return MEMORY_E;
    }
    derSz = MAX_PUBLIC_KEY_SZ;

    XMEMSET(der, 0, (size_t)derSz);
    derSz = wc_PemPubKeyToDer(file, der, derSz);
    if (derSz <= 0) {
        XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
        return derSz;
    }

    /* Load PubKey in internal structure */
#ifndef NO_RSA
    rsakey = (RsaKey*) XMALLOC(sizeof(RsaKey), cert->heap, DYNAMIC_TYPE_RSA);
    if (rsakey == NULL) {
        XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
        return MEMORY_E;
    }

    if (wc_InitRsaKey(rsakey, cert->heap) != 0) {
        WOLFSSL_MSG("wc_InitRsaKey failure");
        XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
        XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
        return MEMORY_E;
    }

    idx = 0;
    ret = wc_RsaPublicKeyDecode(der, &idx, rsakey, (word32)derSz);
    if (ret != 0)
#endif
    {
#ifndef NO_RSA
        WOLFSSL_MSG("wc_RsaPublicKeyDecode failed");
        wc_FreeRsaKey(rsakey);
        XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
        rsakey = NULL;
#endif
#ifdef HAVE_ECC
        /* Check to load ecc public key */
        eckey = (ecc_key*) XMALLOC(sizeof(ecc_key), cert->heap,
                                                              DYNAMIC_TYPE_ECC);
        if (eckey == NULL) {
            XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
            return MEMORY_E;
        }

        if (wc_ecc_init(eckey) != 0) {
            WOLFSSL_MSG("wc_ecc_init failure");
            wc_ecc_free(eckey);
            XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
            XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
            return MEMORY_E;
        }

        idx = 0;
        ret = wc_EccPublicKeyDecode(der, &idx, eckey, (word32)derSz);
        if (ret != 0) {
            WOLFSSL_MSG("wc_EccPublicKeyDecode failed");
            XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
            wc_ecc_free(eckey);
            XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
            return PUBLIC_KEY_E;
        }
#else
        XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
        return PUBLIC_KEY_E;
#endif /* HAVE_ECC */
    }

    XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);

    ret = wc_SetSubjectKeyIdFromPublicKey(cert, rsakey, eckey);

#ifndef NO_RSA
    wc_FreeRsaKey(rsakey);
    XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
#endif
#ifdef HAVE_ECC
    wc_ecc_free(eckey);
    XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
#endif
    return ret;
}

#endif /* !NO_FILESYSTEM && !NO_ASN_CRYPT */

static int SetAuthKeyIdFromDcert(Cert* cert, DecodedCert* decoded)
{
    int ret = 0;

    /* Subject Key Id not found !! */
    if (decoded->extSubjKeyIdSet == 0) {
        ret = ASN_NO_SKID;
    }

    /* SKID invalid size */
    else if (sizeof(cert->akid) < sizeof(decoded->extSubjKeyId)) {
        ret = MEMORY_E;
    }

    else {
        /* Put the SKID of CA to AKID of certificate */
        XMEMCPY(cert->akid, decoded->extSubjKeyId, KEYID_SIZE);
        cert->akidSz = KEYID_SIZE;
    }

    return ret;
}

/* Set AKID from certificate contains in buffer (DER encoded) */
int wc_SetAuthKeyIdFromCert(Cert *cert, const byte *der, int derSz)
{
    int ret = 0;

    if (cert == NULL) {
        ret = BAD_FUNC_ARG;
    }
    else {
        /* Check if decodedCert is cached */
        if (cert->der != der) {
            /* Allocate cache for the decoded cert */
            ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
        }

        if (ret >= 0) {
            ret = SetAuthKeyIdFromDcert(cert, (DecodedCert*)cert->decodedCert);
#ifndef WOLFSSL_CERT_GEN_CACHE
            wc_SetCert_Free(cert);
#endif
        }
    }

    return ret;
}


#ifndef NO_FILESYSTEM

/* Set AKID from certificate file in PEM */
int wc_SetAuthKeyId(Cert *cert, const char* file)
{
    int         ret;
    DerBuffer*  der = NULL;

    if (cert == NULL || file == NULL)
        return BAD_FUNC_ARG;

    ret = wc_PemCertToDer_ex(file, &der);
    if (ret == 0)
    {
        ret = wc_SetAuthKeyIdFromCert(cert, der->buffer, (int)der->length);
        FreeDer(&der);
    }

    return ret;
}

#endif /* !NO_FILESYSTEM */

/* Set KeyUsage from human readable string */
int wc_SetKeyUsage(Cert *cert, const char *value)
{
    int ret = 0;
    char *token, *str, *ptr;
    word32 len;

    if (cert == NULL || value == NULL)
        return BAD_FUNC_ARG;

    cert->keyUsage = 0;

    /* duplicate string (including terminator) */
    len = (word32)XSTRLEN(value);
    str = (char*)XMALLOC(len+1, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
    if (str == NULL)
        return MEMORY_E;
    XMEMCPY(str, value, len+1);

    /* parse value, and set corresponding Key Usage value */
    if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
        XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
        return KEYUSAGE_E;
    }
    while (token != NULL)
    {
        if (!XSTRCASECMP(token, "digitalSignature"))
            cert->keyUsage |= KEYUSE_DIGITAL_SIG;
        else if (!XSTRCASECMP(token, "nonRepudiation") ||
                 !XSTRCASECMP(token, "contentCommitment"))
            cert->keyUsage |= KEYUSE_CONTENT_COMMIT;
        else if (!XSTRCASECMP(token, "keyEncipherment"))
            cert->keyUsage |= KEYUSE_KEY_ENCIPHER;
        else if (!XSTRCASECMP(token, "dataEncipherment"))
            cert->keyUsage |= KEYUSE_DATA_ENCIPHER;
        else if (!XSTRCASECMP(token, "keyAgreement"))
            cert->keyUsage |= KEYUSE_KEY_AGREE;
        else if (!XSTRCASECMP(token, "keyCertSign"))
            cert->keyUsage |= KEYUSE_KEY_CERT_SIGN;
        else if (!XSTRCASECMP(token, "cRLSign"))
            cert->keyUsage |= KEYUSE_CRL_SIGN;
        else if (!XSTRCASECMP(token, "encipherOnly"))
            cert->keyUsage |= KEYUSE_ENCIPHER_ONLY;
        else if (!XSTRCASECMP(token, "decipherOnly"))
            cert->keyUsage |= KEYUSE_DECIPHER_ONLY;
        else {
            ret = KEYUSAGE_E;
            break;
        }

        token = XSTRTOK(NULL, ",", &ptr);
    }

    XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
    return ret;
}

/* Set ExtendedKeyUsage from human readable string */
int wc_SetExtKeyUsage(Cert *cert, const char *value)
{
    int ret = 0;
    char *token, *str, *ptr;
    word32 len;

    if (cert == NULL || value == NULL)
        return BAD_FUNC_ARG;

    cert->extKeyUsage = 0;

    /* duplicate string (including terminator) */
    len = (word32)XSTRLEN(value);
    str = (char*)XMALLOC(len+1, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
    if (str == NULL)
        return MEMORY_E;
    XMEMCPY(str, value, len+1);

    /* parse value, and set corresponding Key Usage value */
    if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
        XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
        return EXTKEYUSAGE_E;
    }

    while (token != NULL)
    {
        if (!XSTRCASECMP(token, "any"))
            cert->extKeyUsage |= EXTKEYUSE_ANY;
        else if (!XSTRCASECMP(token, "serverAuth"))
            cert->extKeyUsage |= EXTKEYUSE_SERVER_AUTH;
        else if (!XSTRCASECMP(token, "clientAuth"))
            cert->extKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
        else if (!XSTRCASECMP(token, "codeSigning"))
            cert->extKeyUsage |= EXTKEYUSE_CODESIGN;
        else if (!XSTRCASECMP(token, "emailProtection"))
            cert->extKeyUsage |= EXTKEYUSE_EMAILPROT;
        else if (!XSTRCASECMP(token, "timeStamping"))
            cert->extKeyUsage |= EXTKEYUSE_TIMESTAMP;
        else if (!XSTRCASECMP(token, "OCSPSigning"))
            cert->extKeyUsage |= EXTKEYUSE_OCSP_SIGN;
        else {
            ret = EXTKEYUSAGE_E;
            break;
        }

        token = XSTRTOK(NULL, ",", &ptr);
    }

    XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
    return ret;
}

#ifdef WOLFSSL_EKU_OID
/*
 * cert structure to set EKU oid in
 * oid  the oid in byte representation
 * sz   size of oid buffer
 * idx  index of array to place oid
 *
 * returns 0 on success
 */
int wc_SetExtKeyUsageOID(Cert *cert, const char *in, word32 sz, byte idx,
        void* heap)
{
    byte oid[MAX_OID_SZ];
    word32 oidSz = MAX_OID_SZ;

    if (idx >= CTC_MAX_EKU_NB || sz >= CTC_MAX_EKU_OID_SZ) {
        WOLFSSL_MSG("Either idx or sz was too large");
        return BAD_FUNC_ARG;
    }

    if (EncodePolicyOID(oid, &oidSz, in, heap) != 0) {
        return BUFFER_E;
    }

    XMEMCPY(cert->extKeyUsageOID[idx], oid, oidSz);
    cert->extKeyUsageOIDSz[idx] = oidSz;
    cert->extKeyUsage |= EXTKEYUSE_USER;

    return 0;
}
#endif /* WOLFSSL_EKU_OID */

#if defined(WOLFSSL_ASN_TEMPLATE) && defined(WOLFSSL_CERT_GEN) && \
    defined(WOLFSSL_CUSTOM_OID) && defined(HAVE_OID_ENCODING) && \
    defined(WOLFSSL_CERT_EXT)
int wc_SetCustomExtension(Cert *cert, int critical, const char *oid,
                          const byte *der, word32 derSz) {
    CertExtension *ext;
    byte encodedOid[MAX_OID_SZ];
    word32 encodedOidSz = MAX_OID_SZ;
    int ret;

    if (cert == NULL || oid == NULL || der == NULL || derSz == 0) {
        return BAD_FUNC_ARG;
    }

    if (cert->customCertExtCount >= NUM_CUSTOM_EXT) {
        return MEMORY_E;
    }

    /* Make sure we can properly parse the OID. */
    ret = EncodePolicyOID(encodedOid, &encodedOidSz, oid, NULL);
    if (ret != 0) {
        return ret;
    }

    ext = &cert->customCertExt[cert->customCertExtCount];

    ext->oid = oid;
    ext->crit = (critical == 0) ? 0 : 1;
    ext->val = der;
    ext->valSz = derSz;

    cert->customCertExtCount++;
    return 0;
}
#endif

#endif /* WOLFSSL_CERT_EXT */


#ifdef WOLFSSL_ALT_NAMES

static int SetAltNamesFromDcert(Cert* cert, DecodedCert* decoded)
{
    int ret = 0;

    cert->altNamesSz = 0;
    if (decoded->altNames) {
        ret = FlattenAltNames(cert->altNames,
            sizeof(cert->altNames), decoded->altNames);
        if (ret >= 0) {
            cert->altNamesSz = ret;
            ret = 0;
        }
    }

    return ret;
}

#ifndef NO_FILESYSTEM

/* Set Alt Names from der cert, return 0 on success */
static int SetAltNamesFromCert(Cert* cert, const byte* der, int derSz,
    int devId)
{
    int ret;
#ifdef WOLFSSL_SMALL_STACK
    DecodedCert* decoded;
#else
    DecodedCert decoded[1];
#endif

    if (derSz < 0)
        return derSz;

#ifdef WOLFSSL_SMALL_STACK
    decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), cert->heap,
                                                       DYNAMIC_TYPE_TMP_BUFFER);
    if (decoded == NULL)
        return MEMORY_E;
#endif

    InitDecodedCert_ex(decoded, der, (word32)derSz, NULL, devId);
    ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);

    if (ret < 0) {
        WOLFSSL_MSG("ParseCertRelative error");
    }
    else {
        ret = SetAltNamesFromDcert(cert, decoded);
    }

    FreeDecodedCert(decoded);
#ifdef WOLFSSL_SMALL_STACK
    XFREE(decoded, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
#endif

    return ret < 0 ? ret : 0;
}

#endif

static int SetDatesFromDcert(Cert* cert, DecodedCert* decoded)
{
    int ret = 0;

    if (decoded->beforeDate == NULL || decoded->afterDate == NULL) {
        WOLFSSL_MSG("Couldn't extract dates");
        ret = -1;
    }
    else if (decoded->beforeDateLen > MAX_DATE_SIZE ||
                                        decoded->afterDateLen > MAX_DATE_SIZE) {
        WOLFSSL_MSG("Bad date size");
        ret = -1;
    }
    else {
        XMEMCPY(cert->beforeDate, decoded->beforeDate,
                (size_t)decoded->beforeDateLen);
        XMEMCPY(cert->afterDate,  decoded->afterDate,
                (size_t)decoded->afterDateLen);

        cert->beforeDateSz = decoded->beforeDateLen;
        cert->afterDateSz  = decoded->afterDateLen;
    }

    return ret;
}

#endif /* WOLFSSL_ALT_NAMES */

static void SetNameFromDcert(CertName* cn, DecodedCert* decoded)
{
    int sz;

    if (decoded->subjectCN) {
        sz = (decoded->subjectCNLen < CTC_NAME_SIZE) ? decoded->subjectCNLen
                                                     : CTC_NAME_SIZE - 1;
        XSTRNCPY(cn->commonName, decoded->subjectCN, (size_t)sz);
        cn->commonName[sz] = '\0';
        cn->commonNameEnc = decoded->subjectCNEnc;
    }
    if (decoded->subjectC) {
        sz = (decoded->subjectCLen < CTC_NAME_SIZE) ? decoded->subjectCLen
                                                    : CTC_NAME_SIZE - 1;
        XSTRNCPY(cn->country, decoded->subjectC, (size_t)sz);
        cn->country[sz] = '\0';
        cn->countryEnc = decoded->subjectCEnc;
    }
    if (decoded->subjectST) {
        sz = (decoded->subjectSTLen < CTC_NAME_SIZE) ? decoded->subjectSTLen
                                                     : CTC_NAME_SIZE - 1;
        XSTRNCPY(cn->state, decoded->subjectST, (size_t)sz);
        cn->state[sz] = '\0';
        cn->stateEnc = decoded->subjectSTEnc;
    }
    if (decoded->subjectL) {
        sz = (decoded->subjectLLen < CTC_NAME_SIZE) ? decoded->subjectLLen
                                                    : CTC_NAME_SIZE - 1;
        XSTRNCPY(cn->locality, decoded->subjectL, (size_t)sz);
        cn->locality[sz] = '\0';
        cn->localityEnc = decoded->subjectLEnc;
    }
    if (decoded->subjectO) {
        sz = (decoded->subjectOLen < CTC_NAME_SIZE) ? decoded->subjectOLen
                                                    : CTC_NAME_SIZE - 1;
        XSTRNCPY(cn->org, decoded->subjectO, (size_t)sz);
        cn->org[sz] = '\0';
        cn->orgEnc = decoded->subjectOEnc;
    }
    if (decoded->subjectOU) {
        sz = (decoded->subjectOULen < CTC_NAME_SIZE) ? decoded->subjectOULen
                                                     : CTC_NAME_SIZE - 1;
        XSTRNCPY(cn->unit, decoded->subjectOU, (size_t)sz);
        cn->unit[sz] = '\0';
        cn->unitEnc = decoded->subjectOUEnc;
    }
    if (decoded->subjectSN) {
        sz = (decoded->subjectSNLen < CTC_NAME_SIZE) ? decoded->subjectSNLen
                                                     : CTC_NAME_SIZE - 1;
        XSTRNCPY(cn->sur, decoded->subjectSN, (size_t)sz);
        cn->sur[sz] = '\0';
        cn->surEnc = decoded->subjectSNEnc;
    }
    if (decoded->subjectSND) {
        sz = (decoded->subjectSNDLen < CTC_NAME_SIZE) ? decoded->subjectSNDLen
                                                     : CTC_NAME_SIZE - 1;
        XSTRNCPY(cn->serialDev, decoded->subjectSND, (size_t)sz);
        cn->serialDev[sz] = '\0';
        cn->serialDevEnc = decoded->subjectSNDEnc;
    }
    if (decoded->subjectUID) {
        sz = (decoded->subjectUIDLen < CTC_NAME_SIZE) ? decoded->subjectUIDLen
                                                     : CTC_NAME_SIZE - 1;
        XSTRNCPY(cn->userId, decoded->subjectUID, (size_t)sz);
        cn->userId[sz] = '\0';
        cn->userIdEnc = decoded->subjectUIDEnc;
    }
#ifdef WOLFSSL_CERT_EXT
    if (decoded->subjectBC) {
        sz = (decoded->subjectBCLen < CTC_NAME_SIZE) ? decoded->subjectBCLen
                                                     : CTC_NAME_SIZE - 1;
        XSTRNCPY(cn->busCat, decoded->subjectBC, (size_t)sz);
        cn->busCat[sz] = '\0';
        cn->busCatEnc = decoded->subjectBCEnc;
    }
    if (decoded->subjectJC) {
        sz = (decoded->subjectJCLen < CTC_NAME_SIZE) ? decoded->subjectJCLen
                                                     : CTC_NAME_SIZE - 1;
        XSTRNCPY(cn->joiC, decoded->subjectJC, (size_t)sz);
        cn->joiC[sz] = '\0';
        cn->joiCEnc = decoded->subjectJCEnc;
    }
    if (decoded->subjectJS) {
        sz = (decoded->subjectJSLen < CTC_NAME_SIZE) ? decoded->subjectJSLen
                                                     : CTC_NAME_SIZE - 1;
        XSTRNCPY(cn->joiSt, decoded->subjectJS, (size_t)sz);
        cn->joiSt[sz] = '\0';
        cn->joiStEnc = decoded->subjectJSEnc;
    }
#endif
    if (decoded->subjectEmail) {
        sz = (decoded->subjectEmailLen < CTC_NAME_SIZE)
           ?  decoded->subjectEmailLen : CTC_NAME_SIZE - 1;
        XSTRNCPY(cn->email, decoded->subjectEmail, (size_t)sz);
        cn->email[sz] = '\0';
    }
#if defined(WOLFSSL_CERT_NAME_ALL) && \
    (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT))
    if (decoded->subjectN) {
        sz = (decoded->subjectNLen < CTC_NAME_SIZE) ? decoded->subjectNLen
                                                     : CTC_NAME_SIZE - 1;
        XSTRNCPY(cn->dnName, decoded->subjectN, (size_t)sz);
        cn->dnName[sz] = '\0';
        cn->dnNameEnc = decoded->subjectNEnc;
    }
    if (decoded->subjectI) {
        sz = (decoded->subjectILen < CTC_NAME_SIZE) ? decoded->subjectILen
                                                     : CTC_NAME_SIZE - 1;
        XSTRNCPY(cn->initials, decoded->subjectI, (size_t)sz);
        cn->initials[sz] = '\0';
        cn->initialsEnc = decoded->subjectIEnc;
    }
    if (decoded->subjectGN) {
        sz = (decoded->subjectGNLen < CTC_NAME_SIZE) ? decoded->subjectGNLen
                                                     : CTC_NAME_SIZE - 1;
        XSTRNCPY(cn->givenName, decoded->subjectGN, (size_t)sz);
        cn->givenName[sz] = '\0';
        cn->givenNameEnc = decoded->subjectGNEnc;
    }
    if (decoded->subjectDNQ) {
        sz = (decoded->subjectDNQLen < CTC_NAME_SIZE) ? decoded->subjectDNQLen
                                                     : CTC_NAME_SIZE - 1;
        XSTRNCPY(cn->dnQualifier, decoded->subjectDNQ, (size_t)sz);
        cn->dnQualifier[sz] = '\0';
        cn->dnQualifierEnc = decoded->subjectDNQEnc;
    }
#endif /* WOLFSSL_CERT_NAME_ALL */
}

#ifndef NO_FILESYSTEM

/* Set cn name from der buffer, return 0 on success */
static int SetNameFromCert(CertName* cn, const byte* der, int derSz, int devId)
{
    int ret;
#ifdef WOLFSSL_SMALL_STACK
    DecodedCert* decoded;
#else
    DecodedCert decoded[1];
#endif

    if (derSz < 0)
        return derSz;

#ifdef WOLFSSL_SMALL_STACK
    decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
                                                       DYNAMIC_TYPE_TMP_BUFFER);
    if (decoded == NULL)
        return MEMORY_E;
#endif

    InitDecodedCert_ex(decoded, der, (word32)derSz, NULL, devId);
    ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);

    if (ret < 0) {
        WOLFSSL_MSG("ParseCertRelative error");
    }
    else {
        SetNameFromDcert(cn, decoded);
    }

    FreeDecodedCert(decoded);

#ifdef WOLFSSL_SMALL_STACK
    XFREE(decoded, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif

    return ret < 0 ? ret : 0;
}

/* Set cert issuer from issuerFile in PEM */
WOLFSSL_ABI
int wc_SetIssuer(Cert* cert, const char* issuerFile)
{
    int         ret;
    DerBuffer*  der = NULL;

    if (cert == NULL || issuerFile == NULL)
        return BAD_FUNC_ARG;

    ret = wc_PemCertToDer_ex(issuerFile, &der);
    if (ret == 0) {
        cert->selfSigned = 0;
        ret = SetNameFromCert(&cert->issuer, der->buffer, (int)der->length,
            INVALID_DEVID);

        FreeDer(&der);
    }

    return ret;
}


/* Set cert subject from subjectFile in PEM */
WOLFSSL_ABI
int wc_SetSubject(Cert* cert, const char* subjectFile)
{
    int         ret;
    DerBuffer*  der = NULL;

    if (cert == NULL || subjectFile == NULL)
        return BAD_FUNC_ARG;

    ret = wc_PemCertToDer_ex(subjectFile, &der);
    if (ret == 0) {
        ret = SetNameFromCert(&cert->subject, der->buffer, (int)der->length,
            INVALID_DEVID);

        FreeDer(&der);
    }

    return ret;
}

#ifdef WOLFSSL_ALT_NAMES

/* Set alt names from file in PEM */
WOLFSSL_ABI
int wc_SetAltNames(Cert* cert, const char* file)
{
    int         ret;
    DerBuffer*  der = NULL;

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

    ret = wc_PemCertToDer_ex(file, &der);
    if (ret == 0) {
        ret = SetAltNamesFromCert(cert, der->buffer, (int)der->length,
            INVALID_DEVID);

        FreeDer(&der);
    }

    return ret;
}

#endif /* WOLFSSL_ALT_NAMES */

#endif /* !NO_FILESYSTEM */

/* Set cert issuer from DER buffer */
WOLFSSL_ABI
int wc_SetIssuerBuffer(Cert* cert, const byte* der, int derSz)
{
    int ret = 0;

    if (cert == NULL) {
        ret = BAD_FUNC_ARG;
    }
    else {
        cert->selfSigned = 0;

        /* Check if decodedCert is cached */
        if (cert->der != der) {
            /* Allocate cache for the decoded cert */
            ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
        }

        if (ret >= 0) {
            SetNameFromDcert(&cert->issuer, (DecodedCert*)cert->decodedCert);
#ifndef WOLFSSL_CERT_GEN_CACHE
            wc_SetCert_Free(cert);
#endif
        }
    }

    return ret;
}

/* Set cert subject from DER buffer */
WOLFSSL_ABI
int wc_SetSubjectBuffer(Cert* cert, const byte* der, int derSz)
{
    int ret = 0;

    if (cert == NULL) {
        ret = BAD_FUNC_ARG;
    }
    else {
        /* Check if decodedCert is cached */
        if (cert->der != der) {
            /* Allocate cache for the decoded cert */
            ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
        }

        if (ret >= 0) {
            SetNameFromDcert(&cert->subject, (DecodedCert*)cert->decodedCert);
#ifndef WOLFSSL_CERT_GEN_CACHE
            wc_SetCert_Free(cert);
#endif
        }
    }

    return ret;
}
#ifdef WOLFSSL_CERT_EXT
/* Set cert raw subject from DER buffer */
WOLFSSL_ABI
int wc_SetSubjectRaw(Cert* cert, const byte* der, int derSz)
{
    int ret = 0;

    if (cert == NULL) {
        ret = BAD_FUNC_ARG;
    }
    else {
        /* Check if decodedCert is cached */
        if (cert->der != der) {
            /* Allocate cache for the decoded cert */
            ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
        }

        if (ret >= 0) {
            if ((((DecodedCert*)cert->decodedCert)->subjectRaw) &&
                (((DecodedCert*)cert->decodedCert)->subjectRawLen <=
                        (int)sizeof(CertName))) {
                XMEMCPY(cert->sbjRaw,
                        ((DecodedCert*)cert->decodedCert)->subjectRaw,
                        (size_t)((DecodedCert*)cert->decodedCert)->
                        subjectRawLen);
            }
#ifndef WOLFSSL_CERT_GEN_CACHE
            wc_SetCert_Free(cert);
#endif
        }
    }

    return ret;
}

/* Set cert raw issuer from DER buffer */
WOLFSSL_ABI
int wc_SetIssuerRaw(Cert* cert, const byte* der, int derSz)
{
    int ret = 0;

    if (cert == NULL) {
        ret = BAD_FUNC_ARG;
    }
    else {
        /* Check if decodedCert is cached */
        if (cert->der != der) {
            /* Allocate cache for the decoded cert */
            ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
        }

        if (ret >= 0) {
            if ((((DecodedCert*)cert->decodedCert)->subjectRaw) &&
                (((DecodedCert*)cert->decodedCert)->subjectRawLen <=
                        (int)sizeof(CertName))) {
                /* Copy the subject to the issuer field */
                XMEMCPY(cert->issRaw,
                        ((DecodedCert*)cert->decodedCert)->subjectRaw,
                        (size_t)((DecodedCert*)cert->decodedCert)->
                        subjectRawLen);
            }
#ifndef WOLFSSL_CERT_GEN_CACHE
            wc_SetCert_Free(cert);
#endif
        }
    }
    return ret;
}
#endif

#ifdef WOLFSSL_ALT_NAMES

/* Set cert alt names from DER buffer */
WOLFSSL_ABI
int wc_SetAltNamesBuffer(Cert* cert, const byte* der, int derSz)
{
    int ret = 0;

    if (cert == NULL) {
       ret = BAD_FUNC_ARG;
    }
    else {
        /* Check if decodedCert is cached */
        if (cert->der != der) {
            /* Allocate cache for the decoded cert */
            ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
        }

        if (ret >= 0) {
            ret = SetAltNamesFromDcert(cert, (DecodedCert*)cert->decodedCert);
#ifndef WOLFSSL_CERT_GEN_CACHE
            wc_SetCert_Free(cert);
#endif
       }
    }

    return(ret);
}

/* Set cert dates from DER buffer */
WOLFSSL_ABI
int wc_SetDatesBuffer(Cert* cert, const byte* der, int derSz)
{
    int ret = 0;

    if (cert == NULL) {
     ret = BAD_FUNC_ARG;
    }
    else {
        /* Check if decodedCert is cached */
        if (cert->der != der) {
            /* Allocate cache for the decoded cert */
            ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
        }

        if (ret >= 0) {
            ret = SetDatesFromDcert(cert, (DecodedCert*)cert->decodedCert);
#ifndef WOLFSSL_CERT_GEN_CACHE
            wc_SetCert_Free(cert);
#endif
        }
    }

    return(ret);
}

#endif /* WOLFSSL_ALT_NAMES */

#endif /* WOLFSSL_CERT_GEN */

#if (defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_EXT)) \
        || defined(OPENSSL_EXTRA)
/* Encode OID string representation to ITU-T X.690 format */
int EncodePolicyOID(byte *out, word32 *outSz, const char *in, void* heap)
{
    word32 idx = 0, nb_val;
    char *token, *str, *ptr;
    word32 len;

    (void)heap;

    if (out == NULL || outSz == NULL || *outSz < 2 || in == NULL)
        return BAD_FUNC_ARG;

    /* duplicate string (including terminator) */
    len = (word32)XSTRLEN(in);
    str = (char *)XMALLOC(len+1, heap, DYNAMIC_TYPE_TMP_BUFFER);
    if (str == NULL)
        return MEMORY_E;
    XMEMCPY(str, in, len+1);

    nb_val = 0;

    /* parse value, and set corresponding Policy OID value */
    token = XSTRTOK(str, ".", &ptr);
    while (token != NULL)
    {
        word32 val = (word32)XATOI(token);

        if (nb_val == 0) {
            if (val > 2) {
                XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
                return ASN_OBJECT_ID_E;
            }

            out[idx] = (byte)(40 * val);
        }
        else if (nb_val == 1) {
            if (val > 127) {
                XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
                return ASN_OBJECT_ID_E;
            }

            if (idx > *outSz) {
                XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
                return BUFFER_E;
            }

            out[idx++] += (byte)val;
        }
        else {
            word32  tb = 0;
            int     i = 0;
            byte    oid[MAX_OID_SZ];

            while (val >= 128) {
                word32 x = val % 128;
                val /= 128;
                oid[i++] = (byte) (((tb++) ? 0x80 : 0) | x);
            }

            if ((idx+(word32)i) >= *outSz) {
                XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
                return BUFFER_E;
            }

            oid[i] = (byte) (((tb++) ? 0x80 : 0) | val);

            /* push value in the right order */
            while (i >= 0)
                out[idx++] = oid[i--];
        }

        token = XSTRTOK(NULL, ".", &ptr);
        nb_val++;
    }

    *outSz = idx;

    XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
    return 0;
}
#endif /* WOLFSSL_CERT_EXT || OPENSSL_EXTRA */

#endif /* !NO_CERTS */

#if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL))
/* Helper function for wolfSSL_i2d_DHparams */
int StoreDHparams(byte* out, word32* outLen, mp_int* p, mp_int* g)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx = 0;
    word32 total;

    WOLFSSL_ENTER("StoreDHparams");

    if (out == NULL) {
        WOLFSSL_MSG("Null buffer error");
        return BUFFER_E;
    }

    /* determine size */
    /* integer - g */
    idx = SetASNIntMP(g, -1, NULL);
    /* integer - p */
    idx += SetASNIntMP(p, -1, NULL);
    total = idx;
     /* sequence */
    idx += SetSequence(idx, NULL);

    /* make sure output fits in buffer */
    if (idx > *outLen) {
        return BUFFER_E;
    }

    /* write DH parameters */
    /* sequence - for P and G only */
    idx = SetSequence(total, out);
    /* integer - p */
    idx += SetASNIntMP(p, -1, out + idx);
    /* integer - g */
    idx += SetASNIntMP(g, -1, out + idx);
    *outLen = idx;

    return 0;
#else
    ASNSetData dataASN[dhParamASN_Length];
    int ret = 0;
    int sz = 0;

    WOLFSSL_ENTER("StoreDHparams");
    if (out == NULL) {
        ret = BUFFER_E;
    }
    if (ret == 0) {
        XMEMSET(dataASN, 0, sizeof(dataASN));
        /* Set mp_int containing p and g. */
        SetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], p);
        SetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], g);
        /* privateValueLength not encoded. */
        dataASN[DHPARAMASN_IDX_PRIVLEN].noOut = 1;

        /* Calculate the size of the DH parameters. */
        ret = SizeASN_Items(dhParamASN, dataASN, dhParamASN_Length, &sz);
    }
    /* Check buffer is big enough for encoding. */
    if ((ret == 0) && ((int)*outLen < sz)) {
        ret = BUFFER_E;
    }
    if (ret == 0) {
        /* Encode the DH parameters into buffer. */
        SetASN_Items(dhParamASN, dataASN, dhParamASN_Length, out);
        /* Set the actual encoding size. */
        *outLen = sz;
    }

    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}
#endif /* !NO_DH && (WOLFSSL_QT || OPENSSL_ALL) */

#if defined(HAVE_ECC) || !defined(NO_DSA)

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for DSA signature.
 * RFC 5912, 6 - DSA-Sig-Value
 */
static const ASNItem dsaSigASN[] = {
/* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
                            /* r */
/* R   */     { 1, ASN_INTEGER, 0, 0, 0 },
                            /* s */
/* S   */     { 1, ASN_INTEGER, 0, 0, 0 },
};
enum {
    DSASIGASN_IDX_SEQ = 0,
    DSASIGASN_IDX_R,
    DSASIGASN_IDX_S
};

#define dsaSigASN_Length (sizeof(dsaSigASN) / sizeof(ASNItem))
#endif

/* Der Encode r & s ints into out, outLen is (in/out) size */
int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx = 0;
    int    rSz;                           /* encoding size */
    int    sSz;
    int    headerSz = 4;   /* 2*ASN_TAG + 2*LEN(ENUM) */

    /* If the leading bit on the INTEGER is a 1, add a leading zero */
    int rLeadingZero = mp_leading_bit(r);
    int sLeadingZero = mp_leading_bit(s);
    int rLen = mp_unsigned_bin_size(r);   /* big int size */
    int sLen = mp_unsigned_bin_size(s);

    if (*outLen < (word32)((rLen + rLeadingZero + sLen + sLeadingZero +
            headerSz + 2)))  /* SEQ_TAG + LEN(ENUM) */
        return BUFFER_E;

    idx = SetSequence((word32)(rLen + rLeadingZero + sLen + sLeadingZero +
        headerSz), out);

    /* store r */
    rSz = SetASNIntMP(r, (int)(*outLen - idx), &out[idx]);
    if (rSz < 0)
        return rSz;
    idx += (word32)rSz;

    /* store s */
    sSz = SetASNIntMP(s, (int)(*outLen - idx), &out[idx]);
    if (sSz < 0)
        return sSz;
    idx += (word32)sSz;

    *outLen = idx;

    return 0;
#else
    ASNSetData dataASN[dsaSigASN_Length];
    int ret;
    int sz;

    /* Clear dynamic data and set mp_ints r and s */
    XMEMSET(dataASN, 0, sizeof(dataASN));
    SetASN_MP(&dataASN[DSASIGASN_IDX_R], r);
    SetASN_MP(&dataASN[DSASIGASN_IDX_S], s);

    /* Calculate size of encoding. */
    ret = SizeASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, &sz);
    /* Check buffer is big enough for encoding. */
    if ((ret == 0) && ((int)*outLen < sz)) {
       ret = BUFFER_E;
    }
    if (ret == 0) {
        /* Encode DSA signature into buffer. */
        SetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, out);
        /* Set the actual encoding size. */
        *outLen = (word32)sz;
    }

    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

#ifndef WOLFSSL_ASN_TEMPLATE
/* determine if leading bit is set */
static word32 is_leading_bit_set(const byte* input, word32 sz)
{
    byte c = 0;
    if (sz > 0)
        c = input[0];
    return (c & 0x80) != 0;
}
static word32 trim_leading_zeros(const byte** input, word32 sz)
{
    int i;
    word32 leadingZeroCount = 0;
    const byte* tmp = *input;
    for (i=0; i<(int)sz; i++) {
        if (tmp[i] != 0)
            break;
        leadingZeroCount++;
    }
    /* catch all zero case */
    if (sz > 0 && leadingZeroCount == sz) {
        leadingZeroCount--;
    }
    *input += leadingZeroCount;
    sz -= leadingZeroCount;
    return sz;
}
#endif

/* Der Encode r & s ints into out, outLen is (in/out) size */
/* All input/outputs are assumed to be big-endian */
int StoreECC_DSA_Sig_Bin(byte* out, word32* outLen, const byte* r, word32 rLen,
    const byte* s, word32 sLen)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int ret;
    word32 idx;
    word32 headerSz = 4;   /* 2*ASN_TAG + 2*LEN(ENUM) */
    word32 rAddLeadZero, sAddLeadZero;

    if ((out == NULL) || (outLen == NULL) || (r == NULL) || (s == NULL))
        return BAD_FUNC_ARG;

    /* Trim leading zeros */
    rLen = trim_leading_zeros(&r, rLen);
    sLen = trim_leading_zeros(&s, sLen);
    /* If the leading bit on the INTEGER is a 1, add a leading zero */
    /* Add leading zero if MSB is set */
    rAddLeadZero = is_leading_bit_set(r, rLen);
    sAddLeadZero = is_leading_bit_set(s, sLen);

    if (*outLen < (rLen + rAddLeadZero + sLen + sAddLeadZero +
                   headerSz + 2))  /* SEQ_TAG + LEN(ENUM) */
        return BUFFER_E;

    idx = SetSequence(rLen+rAddLeadZero + sLen+sAddLeadZero + headerSz, out);

    /* store r */
    ret = SetASNInt((int)rLen, (byte)(rAddLeadZero ? 0x80U : 0x00U), &out[idx]);
    if (ret < 0)
        return ret;
    idx += (word32)ret;
    XMEMCPY(&out[idx], r, rLen);
    idx += rLen;

    /* store s */
    ret = SetASNInt((int)sLen, (byte)(sAddLeadZero ? 0x80U : 0x00U), &out[idx]);
    if (ret < 0)
        return ret;
    idx += (word32)ret;
    XMEMCPY(&out[idx], s, sLen);
    idx += sLen;

    *outLen = idx;

    return 0;
#else
    ASNSetData dataASN[dsaSigASN_Length];
    int ret;
    int sz;

    /* Clear dynamic data and set buffers for r and s */
    XMEMSET(dataASN, 0, sizeof(dataASN));
    SetASN_Buffer(&dataASN[DSASIGASN_IDX_R], r, rLen);
    SetASN_Buffer(&dataASN[DSASIGASN_IDX_S], s, sLen);

    /* Calculate size of encoding. */
    ret = SizeASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, &sz);
    /* Check buffer is big enough for encoding. */
    if ((ret == 0) && ((int)*outLen < sz)) {
       ret = BUFFER_E;
    }
    if (ret == 0) {
        /* Encode DSA signature into buffer. */
        SetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, out);
        /* Set the actual encoding size. */
        *outLen = (word32)sz;
    }

    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

/* Der Decode ECC-DSA Signature with R/S as unsigned bin */
/* All input/outputs are assumed to be big-endian */
int DecodeECC_DSA_Sig_Bin(const byte* sig, word32 sigLen, byte* r, word32* rLen,
    byte* s, word32* sLen)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int    ret;
    word32 idx = 0;
    int    len = 0;

    if (GetSequence(sig, &idx, &len, sigLen) < 0) {
        return ASN_ECC_KEY_E;
    }

#ifndef NO_STRICT_ECDSA_LEN
    /* enable strict length checking for signature */
    if (sigLen != idx + (word32)len) {
        return ASN_ECC_KEY_E;
    }
#else
    /* allow extra signature bytes at end */
    if ((word32)len > (sigLen - idx)) {
        return ASN_ECC_KEY_E;
    }
#endif

    ret = GetASNInt(sig, &idx, &len, sigLen);
    if (ret != 0)
        return ret;
    if (rLen)
        *rLen = (word32)len;
    if (r)
        XMEMCPY(r, (byte*)sig + idx, (size_t)len);
    idx += (word32)len;

    ret = GetASNInt(sig, &idx, &len, sigLen);
    if (ret != 0)
        return ret;
    if (sLen)
        *sLen = (word32)len;
    if (s)
        XMEMCPY(s, (byte*)sig + idx, (size_t)len);

#ifndef NO_STRICT_ECDSA_LEN
    /* sanity check that the index has been advanced all the way to the end of
     * the buffer */
    if (idx + (word32)len != sigLen) {
        ret = ASN_ECC_KEY_E;
    }
#endif

    return ret;
#else
    ASNGetData dataASN[dsaSigASN_Length];
    word32 idx = 0;

    /* Clear dynamic data and set buffers to put r and s into. */
    XMEMSET(dataASN, 0, sizeof(dataASN));
    GetASN_Buffer(&dataASN[DSASIGASN_IDX_R], r, rLen);
    GetASN_Buffer(&dataASN[DSASIGASN_IDX_S], s, sLen);

    /* Decode the DSA signature. */
    return GetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, 1, sig, &idx,
                        sigLen);
#endif /* WOLFSSL_ASN_TEMPLATE */
}

int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s)
{
    return DecodeECC_DSA_Sig_Ex(sig, sigLen, r, s, 1);
}

int DecodeECC_DSA_Sig_Ex(const byte* sig, word32 sigLen, mp_int* r, mp_int* s,
    int init)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx = 0;
    int    len = 0;

    if (GetSequence(sig, &idx, &len, sigLen) < 0) {
        return ASN_ECC_KEY_E;
    }

#ifndef NO_STRICT_ECDSA_LEN
    /* enable strict length checking for signature */
    if (sigLen != idx + (word32)len) {
        return ASN_ECC_KEY_E;
    }
#else
    /* allow extra signature bytes at end */
    if ((word32)len > (sigLen - idx)) {
        return ASN_ECC_KEY_E;
    }
#endif

    if (GetIntPositive(r, sig, &idx, sigLen, init) < 0) {
        return ASN_ECC_KEY_E;
    }

    if (GetIntPositive(s, sig, &idx, sigLen, init) < 0) {
        mp_clear(r);
        return ASN_ECC_KEY_E;
    }

#ifndef NO_STRICT_ECDSA_LEN
    /* sanity check that the index has been advanced all the way to the end of
     * the buffer */
    if (idx != sigLen) {
        mp_clear(r);
        mp_clear(s);
        return ASN_ECC_KEY_E;
    }
#endif

    return 0;
#else
    ASNGetData dataASN[dsaSigASN_Length];
    word32 idx = 0;
    int ret;

    /* Clear dynamic data and set mp_ints to put r and s into. */
    XMEMSET(dataASN, 0, sizeof(dataASN));
    if (init) {
        GetASN_MP(&dataASN[DSASIGASN_IDX_R], r);
        GetASN_MP(&dataASN[DSASIGASN_IDX_S], s);
    }
    else {
        GetASN_MP_Inited(&dataASN[DSASIGASN_IDX_R], r);
        GetASN_MP_Inited(&dataASN[DSASIGASN_IDX_S], s);
    }

    /* Decode the DSA signature. */
    ret = GetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, 0, sig, &idx,
                       sigLen);
#ifndef NO_STRICT_ECDSA_LEN
    /* sanity check that the index has been advanced all the way to the end of
     * the buffer */
    if ((ret == 0) && (idx != sigLen)) {
        ret = ASN_ECC_KEY_E;
    }
#endif
    if (ret != 0) {
        mp_clear(r);
        mp_clear(s);
    }

    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}
#endif


#ifdef WOLFSSL_ASN_TEMPLATE
#ifdef WOLFSSL_CUSTOM_CURVES
/* Convert data to hex string.
 *
 * Big-endian byte array is converted to big-endian hexadecimal string.
 *
 * @param [in]  input  Buffer containing data.
 * @param [in]  inSz   Size of data in buffer.
 * @param [out] out    Buffer to hold hex string.
 */
static void DataToHexString(const byte* input, word32 inSz, char* out)
{
    static const char hexChar[] = { '0', '1', '2', '3', '4', '5', '6', '7',
                                    '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
    word32 i;

    /* Converting a byte of data at a time to two hex characters. */
    for (i = 0; i < inSz; i++) {
        out[i*2 + 0] = hexChar[input[i] >> 4];
        out[i*2 + 1] = hexChar[input[i] & 0xf];
    }
    /* NUL terminate string. */
    out[i * 2] = '\0';
}

#ifndef WOLFSSL_ECC_CURVE_STATIC
/* Convert data to hex string and place in allocated buffer.
 *
 * Big-endian byte array is converted to big-endian hexadecimal string.
 *
 * @param [in]  input     Buffer containing data.
 * @param [in]  inSz      Size of data in buffer.
 * @param [out] out       Allocated buffer holding hex string.
 * @param [in]  heap      Dynamic memory allocation hint.
 * @param [in]  heapType  Type of heap to use.
 * @return  0 on succcess.
 * @return  MEMORY_E when dynamic memory allocation fails.
 */
static int DataToHexStringAlloc(const byte* input, word32 inSz, char** out,
                                void* heap, int heapType)
{
    int ret = 0;
    char* str;

    /* Allocate for 2 string characters ber byte plus NUL. */
    str = (char*)XMALLOC(inSz * 2 + 1, heap, heapType);
    if (str == NULL) {
        ret = MEMORY_E;
    }
    else {
        /* Convert to hex string. */
        DataToHexString(input, inSz, str);
        *out = str;
    }

    (void)heap;
    (void)heapType;

    return ret;
}
#endif /* WOLFSSL_ECC_CURVE_STATIC */

/* ASN.1 template for SpecifiedECDomain.
 * SEC 1 Ver. 2.0, C.2 - Syntax for Elliptic Curve Domain Parameters
 * NOTE: characteristic-two-field not supported. */
static const ASNItem eccSpecifiedASN[] = {
            /* version */
/* VER        */ { 0, ASN_INTEGER, 0, 0, 0 },
                                     /* fieldID */
/* PRIME_SEQ  */ { 0, ASN_SEQUENCE, 1, 1, 0 },
                                         /* prime-field or characteristic-two-field */
/* PRIME_OID  */     { 1, ASN_OBJECT_ID, 0, 0, 0 },
                                         /* Prime-p */
/* PRIME_P    */     { 1, ASN_INTEGER, 0, 0, 0 },
                                     /* fieldID */
/* PARAM_SEQ, */ { 0, ASN_SEQUENCE, 1, 1, 0 },
                                         /* a */
/* PARAM_A    */     { 1, ASN_OCTET_STRING, 0, 0, 0 },
                                         /* b */
/* PARAM_B    */     { 1, ASN_OCTET_STRING, 0, 0, 0 },
                                         /* seed */
/* PARAM_SEED */     { 1, ASN_BIT_STRING, 0, 0, 1 },
                                     /* base */
/* BASE       */ { 0, ASN_OCTET_STRING, 0, 0, 0 },
                                     /* order */
/* ORDER      */ { 0, ASN_INTEGER, 0, 0, 0 },
                                     /* cofactor */
/* COFACTOR   */ { 0, ASN_INTEGER, 0, 0, 1 },
                                     /* hash */
/* HASH_SEQ   */ { 0, ASN_SEQUENCE, 0, 0, 1 },
};
enum {
    ECCSPECIFIEDASN_IDX_VER = 0,
    ECCSPECIFIEDASN_IDX_PRIME_SEQ,
    ECCSPECIFIEDASN_IDX_PRIME_OID,
    ECCSPECIFIEDASN_IDX_PRIME_P,
    ECCSPECIFIEDASN_IDX_PARAM_SEQ,
    ECCSPECIFIEDASN_IDX_PARAM_A,
    ECCSPECIFIEDASN_IDX_PARAM_B,
    ECCSPECIFIEDASN_IDX_PARAM_SEED,
    ECCSPECIFIEDASN_IDX_BASE,
    ECCSPECIFIEDASN_IDX_ORDER,
    ECCSPECIFIEDASN_IDX_COFACTOR,
    ECCSPECIFIEDASN_IDX_HASH_SEQ
};

/* Number of items in ASN.1 template for SpecifiedECDomain. */
#define eccSpecifiedASN_Length (sizeof(eccSpecifiedASN) / sizeof(ASNItem))

/* OID indicating the prime field is explicity defined. */
static const byte primeFieldOID[] = {
    0x2a, 0x86, 0x48, 0xce, 0x3d, 0x01, 0x01
};
static const char ecSetCustomName[] = "Custom";

/* Explicit EC parameter values. */
static int EccSpecifiedECDomainDecode(const byte* input, word32 inSz,
                                      ecc_key* key)
{
    DECL_ASNGETDATA(dataASN, eccSpecifiedASN_Length);
    int ret = 0;
    ecc_set_type* curve;
    word32 idx = 0;
    byte version;
    byte cofactor;
    const byte *base;
    word32 baseLen;

    /* Allocate a new parameter set. */
    curve = (ecc_set_type*)XMALLOC(sizeof(*curve), key->heap,
                                                       DYNAMIC_TYPE_ECC_BUFFER);
    if (curve == NULL) {
        ret = MEMORY_E;
    }
    else {
        /* Clear out parameters and set fields to indicate it is custom. */
        XMEMSET(curve, 0, sizeof(*curve));
    }

    CALLOC_ASNGETDATA(dataASN, eccSpecifiedASN_Length, ret, key->heap);

    if (ret == 0) {
        /* Set name to be: "Custom" */
    #ifndef WOLFSSL_ECC_CURVE_STATIC
        curve->name = ecSetCustomName;
    #else
        XMEMCPY((void*)curve->name, ecSetCustomName, sizeof(ecSetCustomName));
    #endif
        curve->id = ECC_CURVE_CUSTOM;

        /* Get version, must have prime field OID and get co-factor. */
        GetASN_Int8Bit(&dataASN[ECCSPECIFIEDASN_IDX_VER], &version);
        GetASN_ExpBuffer(&dataASN[ECCSPECIFIEDASN_IDX_PRIME_OID],
                primeFieldOID, sizeof(primeFieldOID));
        GetASN_Int8Bit(&dataASN[ECCSPECIFIEDASN_IDX_COFACTOR], &cofactor);
        /* Decode the explicit parameters. */
        ret = GetASN_Items(eccSpecifiedASN, dataASN, eccSpecifiedASN_Length, 1,
                           input, &idx, inSz);
    }
    /* Version must be 1 or 2 for supporting explicit parameters. */
    if ((ret == 0) && (version < 1 || version > 3)) {
        ret = ASN_PARSE_E;
    }
#ifndef WOLFSSL_NO_ASN_STRICT
    /* Only version 2 and above can have a seed. */
    if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_PARAM_SEED].tag != 0) &&
            (version < 2)) {
        ret = ASN_PARSE_E;
    }
#endif
    /* Only version 2 and above can have a hash algorithm. */
    if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_HASH_SEQ].tag != 0) &&
            (version < 2)) {
        ret = ASN_PARSE_E;
    }
    if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_COFACTOR].tag != 0)) {
        /* Store optional co-factor. */
        curve->cofactor = cofactor;
    }
    if (ret == 0) {
        /* Length of the prime in bytes is the curve size. */
        curve->size =
                (int)dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length;
        /* Base point: 0x04 <x> <y> (must be uncompressed). */
        GetASN_GetConstRef(&dataASN[ECCSPECIFIEDASN_IDX_BASE], &base,
                &baseLen);
        if ((baseLen < (word32)curve->size * 2 + 1) || (base[0] != 0x4)) {
            ret = ASN_PARSE_E;
        }
    }
    /* Put the curve parameters into the set.
     * Convert the big-endian number byte array to a big-endian string.
     */
    #ifndef WOLFSSL_ECC_CURVE_STATIC
    /* Allocate buffer to put hex strings into. */
    if (ret == 0) {
        /* Base X-ordinate */
        ret = DataToHexStringAlloc(base + 1, (word32)curve->size,
                                   (char**)&curve->Gx, key->heap,
                                   DYNAMIC_TYPE_ECC_BUFFER);
    }
    if (ret == 0) {
        /* Base Y-ordinate */
        ret = DataToHexStringAlloc(base + 1 + curve->size, (word32)curve->size,
                                   (char**)&curve->Gy, key->heap,
                                   DYNAMIC_TYPE_ECC_BUFFER);
    }
    if (ret == 0) {
        /* Prime */
        ret = DataToHexStringAlloc(
                dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.data,
                dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length,
                (char**)&curve->prime, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
    }
    if (ret == 0) {
        /* Parameter A */
        ret = DataToHexStringAlloc(
                dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.data,
                dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.length,
                (char**)&curve->Af, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
    }
    if (ret == 0) {
        /* Parameter B */
        ret = DataToHexStringAlloc(
                dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.data,
                dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.length,
                (char**)&curve->Bf, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
    }
    if (ret == 0) {
        /* Order of curve */
        ret = DataToHexStringAlloc(
                dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.data,
                dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.length,
                (char**)&curve->order, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
    }
    #else
    if (ret == 0) {
        /* Base X-ordinate */
        DataToHexString(base + 1, curve->size, curve->Gx);
        /* Base Y-ordinate */
        DataToHexString(base + 1 + curve->size, curve->size, curve->Gy);
        /* Prime */
        DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.data,
                        dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length,
                        curve->prime);
        /* Parameter A */
        DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.data,
                        dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.length,
                        curve->Af);
        /* Parameter B */
        DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.data,
                        dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.length,
                        curve->Bf);
        /* Order of curve */
        DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.data,
                        dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.length,
                        curve->order);
    }
    #endif /* WOLFSSL_ECC_CURVE_STATIC */

    /* Store parameter set in key. */
    if ((ret == 0) && (wc_ecc_set_custom_curve(key, curve) < 0)) {
        ret = ASN_PARSE_E;
    }
    if (ret == 0) {
        /* The parameter set was allocated.. */
        key->deallocSet = 1;
    }

    if ((ret != 0) && (curve != NULL)) {
        /* Failed to set parameters so free paramter set. */
        wc_ecc_free_curve(curve, key->heap);
    }

    FREE_ASNGETDATA(dataASN, key->heap);
    return ret;
}
#endif /* WOLFSSL_CUSTOM_CURVES */
#endif /* WOLFSSL_ASN_TEMPLATE */

#ifdef HAVE_ECC

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for ECC private key.
 * SEC.1 Ver 2.0, C.4 - Syntax for Elliptic Curve Private Keys
 */
static const ASNItem eccKeyASN[] = {
/* SEQ         */    { 0, ASN_SEQUENCE, 1, 1, 0 },
                                       /* version */
/* VER         */        { 1, ASN_INTEGER, 0, 0, 0 },
                                       /* privateKey */
/* PKEY        */        { 1, ASN_OCTET_STRING, 0, 0, 0 },
                                       /* parameters */
/* PARAMS      */        { 1, ASN_CONTEXT_SPECIFIC | ASN_ECC_PARAMS, 1, 1, 1 },
                                           /* named */
/* CURVEID     */            { 2, ASN_OBJECT_ID, 0, 0, 2 },
                                           /* specified */
/* CURVEPARAMS */            { 2, ASN_SEQUENCE, 1, 0, 2 },
                                       /* publicKey */
/* PUBKEY      */        { 1, ASN_CONTEXT_SPECIFIC | ASN_ECC_PUBKEY, 1, 1, 1 },
                                           /* Uncompressed point - X9.62. */
/* PUBKEY_VAL, */            { 2, ASN_BIT_STRING, 0, 0, 0 },
};
enum {
    ECCKEYASN_IDX_SEQ = 0,
    ECCKEYASN_IDX_VER,
    ECCKEYASN_IDX_PKEY,
    ECCKEYASN_IDX_PARAMS,
    ECCKEYASN_IDX_CURVEID,
    ECCKEYASN_IDX_CURVEPARAMS,
    ECCKEYASN_IDX_PUBKEY,
    ECCKEYASN_IDX_PUBKEY_VAL
};

/* Number of items in ASN.1 template for ECC private key. */
#define eccKeyASN_Length (sizeof(eccKeyASN) / sizeof(ASNItem))
#endif

WOLFSSL_ABI
int wc_EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key,
                        word32 inSz)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 oidSum;
    int    version, length;
    int    privSz, pubSz = 0;
    byte   b;
    int    ret = 0;
    int    curve_id = ECC_CURVE_DEF;
#ifdef WOLFSSL_SMALL_STACK
    byte* priv;
    byte* pub = NULL;
#else
    byte priv[ECC_MAXSIZE+1];
    byte pub[2*(ECC_MAXSIZE+1)]; /* public key has two parts plus header */
#endif
    word32 algId = 0;
    byte* pubData = NULL;

    if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
        return BAD_FUNC_ARG;

    /* if has pkcs8 header skip it */
    if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
        /* ignore error, did not have pkcs8 header */
    }

    if (GetSequence(input, inOutIdx, &length, inSz) < 0)
        return ASN_PARSE_E;

    if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
        return ASN_PARSE_E;

    if (*inOutIdx >= inSz)
        return ASN_PARSE_E;

    b = input[*inOutIdx];
    *inOutIdx += 1;

    /* priv type */
    if (b != 4 && b != 6 && b != 7)
        return ASN_PARSE_E;

    if (GetLength(input, inOutIdx, &length, inSz) < 0)
        return ASN_PARSE_E;
    privSz = length;

    if (privSz > ECC_MAXSIZE)
        return BUFFER_E;

#ifdef WOLFSSL_SMALL_STACK
    priv = (byte*)XMALLOC(privSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    if (priv == NULL)
        return MEMORY_E;
#endif

    /* priv key */
    XMEMCPY(priv, &input[*inOutIdx], (size_t)privSz);
    *inOutIdx += (word32)length;

    if ((*inOutIdx + 1) < inSz) {
        /* prefix 0, may have */
        b = input[*inOutIdx];
        if (b == ECC_PREFIX_0) {
            *inOutIdx += 1;

            if (GetLength(input, inOutIdx, &length, inSz) <= 0)
                ret = ASN_PARSE_E;
            else {
                ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType,
                                  inSz);
                if (ret == 0) {
                    if ((ret = CheckCurve(oidSum)) < 0)
                        ret = ECC_CURVE_OID_E;
                    else {
                        curve_id = ret;
                        ret = 0;
                    }
                }
            }
        }
    }

    if (ret == 0 && (*inOutIdx + 1) < inSz) {
        /* prefix 1 */
        b = input[*inOutIdx];
        *inOutIdx += 1;

        if (b != ECC_PREFIX_1) {
            ret = ASN_ECC_KEY_E;
        }
        else if (GetLength(input, inOutIdx, &length, inSz) <= 0) {
            ret = ASN_PARSE_E;
        }
        else {
            /* key header */
            ret = CheckBitString(input, inOutIdx, &length, inSz, 0, NULL);
            if (ret == 0) {
                /* pub key */
                pubSz = length;
                if (pubSz > 2*(ECC_MAXSIZE+1))
                    ret = BUFFER_E;
                else {
            #ifdef WOLFSSL_SMALL_STACK
                    pub = (byte*)XMALLOC(pubSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
                    if (pub == NULL)
                        ret = MEMORY_E;
                    else
            #endif
                    {
                        XMEMCPY(pub, &input[*inOutIdx], (size_t)pubSz);
                        *inOutIdx += (word32)length;
                        pubData = pub;
                    }
                }
            }
        }
    }

    if (ret == 0) {
        ret = wc_ecc_import_private_key_ex(priv, (word32)privSz, pubData,
            (word32)pubSz, key, curve_id);
    }

#ifdef WOLFSSL_SMALL_STACK
    XFREE(priv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    XFREE(pub,  key->heap, DYNAMIC_TYPE_TMP_BUFFER);
#endif

    return ret;
#else
    DECL_ASNGETDATA(dataASN, eccKeyASN_Length);
    byte version;
    int ret = 0;
    int curve_id = ECC_CURVE_DEF;
#if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
    word32 algId = 0;
#endif

    /* Validate parameters. */
    if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) {
        ret = BAD_FUNC_ARG;
    }

#if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
    /* if has pkcs8 header skip it */
    if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
        /* ignore error, did not have pkcs8 header */
    }
#endif

    CALLOC_ASNGETDATA(dataASN, eccKeyASN_Length, ret, key->heap);

    if (ret == 0) {
        /* Get the version and set the expected OID type. */
        GetASN_Int8Bit(&dataASN[ECCKEYASN_IDX_VER], &version);
        GetASN_OID(&dataASN[ECCKEYASN_IDX_CURVEID], oidCurveType);
        /* Decode the private ECC key. */
        ret = GetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, 1, input,
                           inOutIdx, inSz);
    }
    /* Only version 1 supported. */
    if ((ret == 0) && (version != 1)) {
        ret = ASN_PARSE_E;
    }
    /* Curve Parameters are optional. */
    if ((ret == 0) && (dataASN[ECCKEYASN_IDX_PARAMS].tag != 0)) {
        if (dataASN[ECCKEYASN_IDX_CURVEID].tag != 0) {
            /* Named curve - check and get id. */
            curve_id = CheckCurve(dataASN[ECCKEYASN_IDX_CURVEID].data.oid.sum);
            if (curve_id < 0) {
                ret = ECC_CURVE_OID_E;
            }
        }
        else {
    #ifdef WOLFSSL_CUSTOM_CURVES
            /* Parse explicit parameters. */
            ret = EccSpecifiedECDomainDecode(
                    dataASN[ECCKEYASN_IDX_CURVEPARAMS].data.ref.data,
                    dataASN[ECCKEYASN_IDX_CURVEPARAMS].data.ref.length, key);
    #else
            /* Explicit parameters not supported in build configuration. */
            ret = ASN_PARSE_E;
    #endif
        }
    }
    if (ret == 0) {
        /* Import private key value and public point (may be NULL). */
        ret = wc_ecc_import_private_key_ex(
                dataASN[ECCKEYASN_IDX_PKEY].data.ref.data,
                dataASN[ECCKEYASN_IDX_PKEY].data.ref.length,
                dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.ref.data,
                dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.ref.length,
                key, curve_id);
    }

    FREE_ASNGETDATA(dataASN, key->heap);
    return ret;
#endif
}


#ifdef WOLFSSL_CUSTOM_CURVES
#ifndef WOLFSSL_ASN_TEMPLATE
/* returns 0 on success */
static int ASNToHexString(const byte* input, word32* inOutIdx, char** out,
                          word32 inSz, void* heap, int heapType)
{
    int len;
    int i;
    char* str;
    word32 localIdx;
    byte   tag;

    if (*inOutIdx >= inSz) {
        return BUFFER_E;
    }

    localIdx = *inOutIdx;
    if (GetASNTag(input, &localIdx, &tag, inSz) == 0 && tag == ASN_INTEGER) {
        if (GetASNInt(input, inOutIdx, &len, inSz) < 0)
            return ASN_PARSE_E;
    }
    else {
        if (GetOctetString(input, inOutIdx, &len, inSz) < 0)
            return ASN_PARSE_E;
    }

    str = (char*)XMALLOC((size_t)len * 2 + 1, heap, heapType);
    if (str == NULL) {
        return MEMORY_E;
    }

    for (i=0; i<len; i++)
        ByteToHexStr(input[*inOutIdx + (word32)i], str + i*2);
    str[len*2] = '\0';

    *inOutIdx += (word32)len;
    *out = str;

    (void)heap;
    (void)heapType;

    return 0;
}

static int EccKeyParamCopy(char** dst, char* src)
{
    int ret = 0;
#ifdef WOLFSSL_ECC_CURVE_STATIC
    word32 length;
#endif

    if (dst == NULL || src == NULL)
        return BAD_FUNC_ARG;

#ifndef WOLFSSL_ECC_CURVE_STATIC
    *dst = src;
#else
    length = (int)XSTRLEN(src) + 1;
    if (length > MAX_ECC_STRING) {
        WOLFSSL_MSG("ECC Param too large for buffer");
        ret = BUFFER_E;
    }
    else {
        XSTRNCPY(*dst, src, MAX_ECC_STRING);
    }
    XFREE(src, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
#endif

    return ret;
}
#endif /* !WOLFSSL_ASN_TEMPLATE */
#endif /* WOLFSSL_CUSTOM_CURVES */

WOLFSSL_ABI
int wc_EccPublicKeyDecode(const byte* input, word32* inOutIdx,
                          ecc_key* key, word32 inSz)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int    ret;
    int    version, length;
    int    curve_id = ECC_CURVE_DEF;
    word32 oidSum, localIdx;
    byte   tag, isPrivFormat = 0;

    if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
        return BAD_FUNC_ARG;

    if (GetSequence(input, inOutIdx, &length, inSz) < 0)
        return ASN_PARSE_E;

    /* Check if ECC private key is being used and skip private portion */
    if (GetMyVersion(input, inOutIdx, &version, inSz) >= 0) {
        isPrivFormat = 1;

        /* Type private key */
        if (*inOutIdx >= inSz)
            return ASN_PARSE_E;
        tag = input[*inOutIdx];
        *inOutIdx += 1;
        if (tag != 4 && tag != 6 && tag != 7)
            return ASN_PARSE_E;

        /* Skip Private Key */
        if (GetLength(input, inOutIdx, &length, inSz) < 0)
            return ASN_PARSE_E;
        if (length > ECC_MAXSIZE)
            return BUFFER_E;
        *inOutIdx += (word32)length;

        /* Private Curve Header */
        if (*inOutIdx >= inSz)
            return ASN_PARSE_E;
        tag = input[*inOutIdx];
        *inOutIdx += 1;
        if (tag != ECC_PREFIX_0)
            return ASN_ECC_KEY_E;
        if (GetLength(input, inOutIdx, &length, inSz) <= 0)
            return ASN_PARSE_E;
    }
    /* Standard ECC public key */
    else {
        if (GetSequence(input, inOutIdx, &length, inSz) < 0)
            return ASN_PARSE_E;

        ret = SkipObjectId(input, inOutIdx, inSz);
        if (ret != 0)
            return ret;
    }

    if (*inOutIdx >= inSz) {
        return BUFFER_E;
    }

    localIdx = *inOutIdx;
    if (GetASNTag(input, &localIdx, &tag, inSz) == 0 &&
            tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
#ifdef WOLFSSL_CUSTOM_CURVES
        ecc_set_type* curve;
        int len;
        char* point = NULL;

        ret = 0;

        curve = (ecc_set_type*)XMALLOC(sizeof(*curve), key->heap,
                                                       DYNAMIC_TYPE_ECC_BUFFER);
        if (curve == NULL)
            ret = MEMORY_E;

        if (ret == 0) {
            static const char customName[] = "Custom";
            XMEMSET(curve, 0, sizeof(*curve));
        #ifndef WOLFSSL_ECC_CURVE_STATIC
            curve->name = customName;
        #else
            XMEMCPY((void*)curve->name, customName, sizeof(customName));
        #endif
            curve->id = ECC_CURVE_CUSTOM;

            if (GetSequence(input, inOutIdx, &length, inSz) < 0)
                ret = ASN_PARSE_E;
        }

        if (ret == 0) {
            GetInteger7Bit(input, inOutIdx, inSz);
            if (GetSequence(input, inOutIdx, &length, inSz) < 0)
                ret = ASN_PARSE_E;
        }
        if (ret == 0) {
            char* p = NULL;
            SkipObjectId(input, inOutIdx, inSz);
            ret = ASNToHexString(input, inOutIdx, &p, inSz,
                                            key->heap, DYNAMIC_TYPE_ECC_BUFFER);
            if (ret == 0) {
#ifndef WOLFSSL_ECC_CURVE_STATIC
                ret = EccKeyParamCopy((char**)&curve->prime, p);
#else
                const char *_tmp_ptr = &curve->prime[0];
                ret = EccKeyParamCopy((char**)&_tmp_ptr, p);
#endif
            }
        }
        if (ret == 0) {
            curve->size = (int)XSTRLEN(curve->prime) / 2;

            if (GetSequence(input, inOutIdx, &length, inSz) < 0)
                ret = ASN_PARSE_E;
        }
        if (ret == 0) {
            char* af = NULL;
            ret = ASNToHexString(input, inOutIdx, &af, inSz,
                                            key->heap, DYNAMIC_TYPE_ECC_BUFFER);
            if (ret == 0) {
#ifndef WOLFSSL_ECC_CURVE_STATIC
                ret = EccKeyParamCopy((char**)&curve->Af, af);
#else
                const char *_tmp_ptr = &curve->Af[0];
                ret = EccKeyParamCopy((char**)&_tmp_ptr, af);
#endif
            }
        }
        if (ret == 0) {
            char* bf = NULL;
            ret = ASNToHexString(input, inOutIdx, &bf, inSz,
                                            key->heap, DYNAMIC_TYPE_ECC_BUFFER);
            if (ret == 0) {
#ifndef WOLFSSL_ECC_CURVE_STATIC
                ret = EccKeyParamCopy((char**)&curve->Bf, bf);
#else
                const char *_tmp_ptr = &curve->Bf[0];
                ret = EccKeyParamCopy((char**)&_tmp_ptr, bf);
#endif
            }
        }
        if (ret == 0) {
            localIdx = *inOutIdx;
            if (*inOutIdx < inSz && GetASNTag(input, &localIdx, &tag, inSz)
                    == 0 && tag == ASN_BIT_STRING) {
                len = 0;
                ret = GetASNHeader(input, ASN_BIT_STRING, inOutIdx, &len, inSz);
                if (ret > 0)
                    ret = 0; /* reset on success */
                *inOutIdx += (word32)len;
            }
        }
        if (ret == 0) {
            ret = ASNToHexString(input, inOutIdx, (char**)&point, inSz,
                                            key->heap, DYNAMIC_TYPE_ECC_BUFFER);

            /* sanity check that point buffer is not smaller than the expected
             * size to hold ( 0 4 || Gx || Gy )
             * where Gx and Gy are each the size of curve->size * 2 */
            if (ret == 0 && (int)XSTRLEN(point) < (curve->size * 4) + 2) {
                XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
                ret = BUFFER_E;
            }
        }
        if (ret == 0) {
        #ifndef WOLFSSL_ECC_CURVE_STATIC
            curve->Gx = (const char*)XMALLOC((size_t)curve->size * 2 + 2,
                                            key->heap, DYNAMIC_TYPE_ECC_BUFFER);
            curve->Gy = (const char*)XMALLOC((size_t)curve->size * 2 + 2,
                                            key->heap, DYNAMIC_TYPE_ECC_BUFFER);
            if (curve->Gx == NULL || curve->Gy == NULL) {
                XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
                ret = MEMORY_E;
            }
        #else
            if (curve->size * 2 + 2 > MAX_ECC_STRING) {
                WOLFSSL_MSG("curve size is too large to fit in buffer");
                ret = BUFFER_E;
            }
        #endif
        }
        if (ret == 0) {
            char* o = NULL;

            XMEMCPY((char*)curve->Gx, point + 2, (size_t)curve->size * 2);
            XMEMCPY((char*)curve->Gy, point + curve->size * 2 + 2,
                                                 (size_t)curve->size * 2);
            ((char*)curve->Gx)[curve->size * 2] = '\0';
            ((char*)curve->Gy)[curve->size * 2] = '\0';
            XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
            ret = ASNToHexString(input, inOutIdx, &o, inSz,
                                            key->heap, DYNAMIC_TYPE_ECC_BUFFER);
            if (ret == 0) {
#ifndef WOLFSSL_ECC_CURVE_STATIC
                ret = EccKeyParamCopy((char**)&curve->order, o);
#else
                const char *_tmp_ptr = &curve->order[0];
                ret = EccKeyParamCopy((char**)&_tmp_ptr, o);
#endif
            }
        }
        if (ret == 0) {
            curve->cofactor = GetInteger7Bit(input, inOutIdx, inSz);

        #ifndef WOLFSSL_ECC_CURVE_STATIC
            curve->oid = NULL;
        #else
            XMEMSET((void*)curve->oid, 0, sizeof(curve->oid));
        #endif
            curve->oidSz = 0;
            curve->oidSum = 0;

            if (wc_ecc_set_custom_curve(key, curve) < 0) {
                ret = ASN_PARSE_E;
            }

            key->deallocSet = 1;

            curve = NULL;
        }
        if (curve != NULL)
            wc_ecc_free_curve(curve, key->heap);

        if (ret < 0)
            return ret;
#else
        return ASN_PARSE_E;
#endif /* WOLFSSL_CUSTOM_CURVES */
    }
    else {
        /* ecc params information */
        ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType, inSz);
        if (ret != 0)
            return ret;

        /* get curve id */
        if ((ret = CheckCurve(oidSum)) < 0)
            return ECC_CURVE_OID_E;
        else {
            curve_id = ret;
        }
    }

    if (isPrivFormat) {
        /* Public Curve Header - skip */
        if (*inOutIdx >= inSz)
            return ASN_PARSE_E;
        tag = input[*inOutIdx];
        *inOutIdx += 1;
        if (tag != ECC_PREFIX_1)
            return ASN_ECC_KEY_E;
        if (GetLength(input, inOutIdx, &length, inSz) <= 0)
            return ASN_PARSE_E;
    }

    /* key header */
    ret = CheckBitString(input, inOutIdx, &length, inSz, 1, NULL);
    if (ret != 0)
        return ret;

    /* This is the raw point data compressed or uncompressed. */
    if (wc_ecc_import_x963_ex(input + *inOutIdx, (word32)length, key,
                                                            curve_id) != 0) {
        return ASN_ECC_KEY_E;
    }

    *inOutIdx += (word32)length;

    return 0;
#else
    /* eccKeyASN is longer than eccPublicKeyASN. */
    DECL_ASNGETDATA(dataASN, eccKeyASN_Length);
    int ret = 0;
    int curve_id = ECC_CURVE_DEF;
    int oidIdx = ECCPUBLICKEYASN_IDX_ALGOID_CURVEID;
#ifdef WOLFSSL_CUSTOM_CURVES
    int specIdx = ECCPUBLICKEYASN_IDX_ALGOID_PARAMS;
#endif
    int pubIdx = ECCPUBLICKEYASN_IDX_PUBKEY;

    if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) {
        ret = BAD_FUNC_ARG;
    }

    ALLOC_ASNGETDATA(dataASN, eccKeyASN_Length, ret, key->heap);

    if (ret == 0) {
        /* Clear dynamic data for ECC public key. */
        XMEMSET(dataASN, 0, sizeof(*dataASN) * eccPublicKeyASN_Length);
        /* Set required ECDSA OID and ignore the curve OID type. */
        GetASN_ExpBuffer(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID], keyEcdsaOid,
                sizeof(keyEcdsaOid));
        GetASN_OID(&dataASN[oidIdx], oidIgnoreType);
        /* Decode the public ECC key. */
        ret = GetASN_Items(eccPublicKeyASN, dataASN, eccPublicKeyASN_Length, 1,
                           input, inOutIdx, inSz);
        if (ret != 0) {
            oidIdx = ECCKEYASN_IDX_CURVEID;
        #ifdef WOLFSSL_CUSTOM_CURVES
            specIdx = ECCKEYASN_IDX_CURVEPARAMS;
        #endif
            pubIdx = ECCKEYASN_IDX_PUBKEY_VAL;

            /* Clear dynamic data for ECC private key. */
            XMEMSET(dataASN, 0, sizeof(*dataASN) * eccKeyASN_Length);
            /* Check named curve OID type. */
            GetASN_OID(&dataASN[oidIdx], oidIgnoreType);
            /* Try private key format .*/
            ret = GetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, 1, input,
                               inOutIdx, inSz);
            if (ret != 0) {
                ret = ASN_PARSE_E;
            }
        }
    }

    if (ret == 0) {
        if (dataASN[oidIdx].tag != 0) {
            /* Named curve - check and get id. */
            curve_id = CheckCurve(dataASN[oidIdx].data.oid.sum);
            if (curve_id < 0) {
                ret = ASN_OBJECT_ID_E;
            }
        }
        else {
        #ifdef WOLFSSL_CUSTOM_CURVES
            /* Parse explicit parameters. */
            ret = EccSpecifiedECDomainDecode(dataASN[specIdx].data.ref.data,
                                         dataASN[specIdx].data.ref.length, key);
        #else
            /* Explicit parameters not supported in build configuration. */
            ret = ASN_PARSE_E;
        #endif
        }
    }
    if (ret == 0) {
        /* Import public point. */
        ret = wc_ecc_import_x963_ex(dataASN[pubIdx].data.ref.data,
                dataASN[pubIdx].data.ref.length, key, curve_id);
        if (ret != 0) {
            ret = ASN_ECC_KEY_E;
        }
    }

    FREE_ASNGETDATA(dataASN, key->heap);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

#if defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)
/* build DER formatted ECC key, include optional public key if requested,
 * return length on success, negative on error */
static int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen,
                             int pubIn, int curveIn)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    byte   curve[MAX_ALGO_SZ+2];
    byte   ver[MAX_VERSION_SZ];
    byte   seq[MAX_SEQ_SZ];
    int    ret, curveSz, verSz;
    word32 totalSz;
    int    privHdrSz  = ASN_ECC_HEADER_SZ;
    int    pubHdrSz   = ASN_ECC_CONTEXT_SZ + ASN_ECC_HEADER_SZ;
#ifdef WOLFSSL_NO_MALLOC
    byte   prv[MAX_ECC_BYTES + ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
    byte   pub[(MAX_ECC_BYTES * 2) + 1 + ASN_ECC_CONTEXT_SZ +
                              ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
#else
    byte   *prv = NULL, *pub = NULL;
#endif

    word32 idx = 0, prvidx = 0, pubidx = 0, curveidx = 0;
    word32 seqSz, privSz, pubSz = ECC_BUFSIZE;

    if (key == NULL || (output == NULL && inLen == NULL))
        return BAD_FUNC_ARG;

    if (curveIn) {
        /* curve */
        curve[curveidx++] = ECC_PREFIX_0;
        curveidx++ /* to put the size after computation */;
        curveSz = SetCurve(key, curve+curveidx, MAX_ALGO_SZ);
        if (curveSz < 0)
            return curveSz;
        /* set computed size */
        curve[1] = (byte)curveSz;
        curveidx += (word32)curveSz;
    }

    /* private */
    privSz = (word32)key->dp->size;

#ifdef WOLFSSL_QNX_CAAM
    /* check if is a black key, and add MAC size if needed */
    if (key->blackKey > 0 && key->blackKey != CAAM_BLACK_KEY_ECB) {
        privSz = privSz + WC_CAAM_MAC_SZ;
    }
#endif

#ifndef WOLFSSL_NO_MALLOC
    prv = (byte*)XMALLOC(privSz + (word32)privHdrSz + MAX_SEQ_SZ,
                         key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    if (prv == NULL) {
        return MEMORY_E;
    }
#else
    if (sizeof(prv) < privSz + privHdrSz + MAX_SEQ_SZ) {
        return BUFFER_E;
    }
#endif
    if (privSz < ASN_LONG_LENGTH) {
        prvidx += SetOctetString8Bit(privSz, &prv[prvidx]);
    }
    else {
        prvidx += SetOctetString(privSz, &prv[prvidx]);
    }
    ret = wc_ecc_export_private_only(key, prv + prvidx, &privSz);
    if (ret < 0) {
    #ifndef WOLFSSL_NO_MALLOC
        XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    #endif
        return ret;
    }
    prvidx += privSz;

    /* pubIn */
    if (pubIn) {
        PRIVATE_KEY_UNLOCK();
        ret = wc_ecc_export_x963(key, NULL, &pubSz);
        PRIVATE_KEY_LOCK();
        if (ret != LENGTH_ONLY_E) {
        #ifndef WOLFSSL_NO_MALLOC
            XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
        #endif
            return ret;
        }

    #ifndef WOLFSSL_NO_MALLOC
        pub = (byte*)XMALLOC(pubSz + (word32)pubHdrSz + MAX_SEQ_SZ,
                             key->heap, DYNAMIC_TYPE_TMP_BUFFER);
        if (pub == NULL) {
            XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
            return MEMORY_E;
        }
    #else
        if (sizeof(pub) < pubSz + pubHdrSz + MAX_SEQ_SZ) {
            return BUFFER_E;
        }
    #endif

        pub[pubidx++] = ECC_PREFIX_1;
        if (pubSz > 128) /* leading zero + extra size byte */
            pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 2, pub+pubidx);
        else /* leading zero */
            pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 1, pub+pubidx);

        /* SetBitString adds leading zero */
        pubidx += SetBitString(pubSz, 0, pub + pubidx);
        PRIVATE_KEY_UNLOCK();
        ret = wc_ecc_export_x963(key, pub + pubidx, &pubSz);
        PRIVATE_KEY_LOCK();
        if (ret != 0) {
        #ifndef WOLFSSL_NO_MALLOC
            XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
            XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
        #endif
            return ret;
        }
        pubidx += pubSz;
    }

    /* make headers */
    verSz = SetMyVersion(1, ver, FALSE);
    seqSz = SetSequence((word32)verSz + prvidx + pubidx + curveidx, seq);

    totalSz = prvidx + pubidx + curveidx + (word32)verSz + seqSz;
    if (output == NULL) {
        *inLen = totalSz;
    #ifndef WOLFSSL_NO_MALLOC
        XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
        if (pubIn) {
            XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
        }
    #endif
        return LENGTH_ONLY_E;
    }
    if (inLen != NULL && totalSz > *inLen) {
        #ifndef WOLFSSL_NO_MALLOC
        XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
        if (pubIn) {
            XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
        }
        #endif
        return BAD_FUNC_ARG;
    }

    /* write out */
    /* seq */
    XMEMCPY(output + idx, seq, seqSz);
    idx = seqSz;

    /* ver */
    XMEMCPY(output + idx, ver, (size_t)verSz);
    idx += (word32)verSz;

    /* private */
    XMEMCPY(output + idx, prv, prvidx);
    idx += prvidx;
#ifndef WOLFSSL_NO_MALLOC
    XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
#endif

    /* curve */
    XMEMCPY(output + idx, curve, curveidx);
    idx += curveidx;

    /* pubIn */
    if (pubIn) {
        XMEMCPY(output + idx, pub, pubidx);
        /* idx += pubidx;  not used after write, if more data remove comment */
    #ifndef WOLFSSL_NO_MALLOC
        XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    #endif
    }

    return (int)totalSz;
#else
    DECL_ASNSETDATA(dataASN, eccKeyASN_Length);
    word32 privSz, pubSz;
    int sz = 0;
    int ret = 0;
    int curveIdSz = 0;

    /* Check validity of parameters. */
    if ((key == NULL) || ((output == NULL) && (inLen == NULL))) {
        ret = BAD_FUNC_ARG;
    }

    /* Check key has parameters when encoding curve. */
    if ((ret == 0) && curveIn && (key->dp == NULL)) {
        ret = BAD_FUNC_ARG;
    }

    CALLOC_ASNSETDATA(dataASN, eccKeyASN_Length, ret, key->heap);

    if (ret == 0) {
        /* Private key size is the curve size. */
        privSz = (word32)key->dp->size;
        if (pubIn) {
            /* Get the length of the public key. */
            PRIVATE_KEY_UNLOCK();
            ret = wc_ecc_export_x963(key, NULL, &pubSz);
            PRIVATE_KEY_LOCK();
            if (ret == LENGTH_ONLY_E)
                ret = 0;
        }
    }
    if (ret == 0) {
        /* Version: 1 */
        SetASN_Int8Bit(&dataASN[ECCKEYASN_IDX_VER], 1);
        /* Leave space for private key. */
        SetASN_Buffer(&dataASN[ECCKEYASN_IDX_PKEY], NULL, privSz);
        if (curveIn) {
            /* Get length of the named curve OID to put into the encoding. */
            curveIdSz = SetCurve(key, NULL, 0);
            if (curveIdSz < 0) {
                ret = curveIdSz;
            }
            /* Curve OID */
            SetASN_ReplaceBuffer(&dataASN[ECCKEYASN_IDX_CURVEID], NULL,
                (word32)curveIdSz);
            /* TODO: add support for SpecifiedECDomain curve. */
            dataASN[ECCKEYASN_IDX_CURVEPARAMS].noOut = 1;
        }
        else {
            SetASNItem_NoOutNode(dataASN, eccKeyASN, ECCKEYASN_IDX_PARAMS,
                    eccKeyASN_Length);
        }
        if (ret == 0) {
            if (pubIn) {
                /* Leave space for public key. */
                SetASN_Buffer(&dataASN[ECCKEYASN_IDX_PUBKEY_VAL], NULL, pubSz);
            }
            else {
                /* Don't write out public key. */
                SetASNItem_NoOutNode(dataASN, eccKeyASN, ECCKEYASN_IDX_PUBKEY,
                                     eccKeyASN_Length);
            }
            /* Calculate size of the private key encoding. */
            ret = SizeASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, &sz);
        }
    }
    /* Return the size if no buffer. */
    if ((ret == 0) && (output == NULL)) {
        *inLen = (word32)sz;
        ret = LENGTH_ONLY_E;
    }
    /* Check the buffer is big enough. */
    if ((ret == 0) && (inLen != NULL) && (sz > (int)*inLen)) {
        ret = BAD_FUNC_ARG;
    }
    if ((ret == 0) && (output != NULL)) {
        /* Encode the private key. */
        SetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, output);

        if (curveIn) {
            /* Put named curve OID data into encoding. */
            curveIdSz = SetCurve(key,
                (byte*)dataASN[ECCKEYASN_IDX_CURVEID].data.buffer.data,
                (size_t)curveIdSz);
            if (curveIdSz < 0) {
                ret = curveIdSz;
            }
        }
        if (ret == 0) {
            /* Export the private value into the buffer. */
            ret = wc_ecc_export_private_only(key,
                (byte*)dataASN[ECCKEYASN_IDX_PKEY].data.buffer.data, &privSz);
        }
        if ((ret == 0) && pubIn) {
            /* Export the public point into the buffer. */
            PRIVATE_KEY_UNLOCK();
            ret = wc_ecc_export_x963(key,
                    (byte*)dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.buffer.data,
                    &pubSz);
            PRIVATE_KEY_LOCK();
        }
    }
    if (ret == 0) {
        /* Return the encoding size. */
        ret = sz;
    }

    FREE_ASNSETDATA(dataASN, key->heap);
    return ret;
#endif
}

/* Write a Private ecc key, including public to DER format,
 * length on success else < 0 */
WOLFSSL_ABI
int wc_EccKeyToDer(ecc_key* key, byte* output, word32 inLen)
{
    return wc_BuildEccKeyDer(key, output, &inLen, 1, 1);
}

/* Write only private ecc key to DER format,
 * length on success else < 0 */
int wc_EccKeyDerSize(ecc_key* key, int pub)
{
    word32 sz = 0;
    int ret;

    ret = wc_BuildEccKeyDer(key, NULL, &sz, pub, 1);

    if (ret != LENGTH_ONLY_E) {
        return ret;
    }
    return (int)sz;
 }

/* Write only private ecc key to DER format,
 * length on success else < 0 */
int wc_EccPrivateKeyToDer(ecc_key* key, byte* output, word32 inLen)
{
    return wc_BuildEccKeyDer(key, output, &inLen, 0, 1);
}



#ifdef HAVE_PKCS8

/* Write only private ecc key or both private and public parts to unencrypted
 * PKCS#8 format.
 *
 * If output is NULL, places required PKCS#8 buffer size in outLen and
 * returns LENGTH_ONLY_E.
 *
 * return length on success else < 0 */
static int eccToPKCS8(ecc_key* key, byte* output, word32* outLen,
        int includePublic)
{
    int ret;
    word32 tmpDerSz;
    int algoID = 0;
    word32 oidSz = 0;
    word32 pkcs8Sz = 0;
    const byte* curveOID = NULL;
#ifdef WOLFSSL_NO_MALLOC
    byte  tmpDer[ECC_BUFSIZE];
#else
    byte* tmpDer = NULL;
#endif
    word32 sz = ECC_BUFSIZE;

    if (key == NULL || key->dp == NULL || outLen == NULL)
        return BAD_FUNC_ARG;

    /* set algoID, get curve OID */
    algoID = ECDSAk;
    ret = wc_ecc_get_oid(key->dp->oidSum, &curveOID, &oidSz);
    if (ret < 0)
        return ret;

#ifndef WOLFSSL_NO_MALLOC
    /* temp buffer for plain DER key */
    tmpDer = (byte*)XMALLOC(ECC_BUFSIZE, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    if (tmpDer == NULL)
        return MEMORY_E;
#endif
    XMEMSET(tmpDer, 0, ECC_BUFSIZE);

    ret = wc_BuildEccKeyDer(key, tmpDer, &sz, includePublic, 0);
    if (ret < 0) {
    #ifndef WOLFSSL_NO_MALLOC
        XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    #endif
        return ret;
    }
    tmpDerSz = (word32)ret;

    /* get pkcs8 expected output size */
    ret = wc_CreatePKCS8Key(NULL, &pkcs8Sz, tmpDer, tmpDerSz, algoID,
                            curveOID, oidSz);
    if (ret != LENGTH_ONLY_E) {
    #ifndef WOLFSSL_NO_MALLOC
        XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    #endif
        return ret;
    }

    if (output == NULL) {
    #ifndef WOLFSSL_NO_MALLOC
        XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    #endif
        *outLen = pkcs8Sz;
        return LENGTH_ONLY_E;

    }
    else if (*outLen < pkcs8Sz) {
    #ifndef WOLFSSL_NO_MALLOC
        XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    #endif
        WOLFSSL_MSG("Input buffer too small for ECC PKCS#8 key");
        return BUFFER_E;
    }

    ret = wc_CreatePKCS8Key(output, &pkcs8Sz, tmpDer, tmpDerSz,
                            algoID, curveOID, oidSz);
    if (ret < 0) {
    #ifndef WOLFSSL_NO_MALLOC
        XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
    #endif
        return ret;
    }

#ifndef WOLFSSL_NO_MALLOC
    XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
#endif

    *outLen = (word32)ret;
    return ret;
}

/* Write only private ecc key to unencrypted PKCS#8 format.
 *
 * return length on success else < 0 */
int wc_EccPrivateKeyToPKCS8(ecc_key* key, byte* output, word32* outLen)
{
    return eccToPKCS8(key, output, outLen, 0);
}

/* Write both private and public ecc keys to unencrypted PKCS#8 format.
 *
 * return length on success else < 0 */
int wc_EccKeyToPKCS8(ecc_key* key, byte* output,
                     word32* outLen)
{
    return eccToPKCS8(key, output, outLen, 1);
}
#endif /* HAVE_PKCS8 */
#endif /* HAVE_ECC_KEY_EXPORT && !NO_ASN_CRYPT */
#endif /* HAVE_ECC */

#ifdef WC_ENABLE_ASYM_KEY_IMPORT
#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for Ed25519 and Ed448 private key.
 * RFC 8410, 7 - Private Key Format (but public value is EXPLICIT OCTET_STRING)
 */
static const ASNItem edKeyASN[] = {
/* SEQ            */    { 0, ASN_SEQUENCE, 1, 1, 0 },
                                         /* Version */
/* VER            */        { 1, ASN_INTEGER, 0, 0, 0 },
                                         /* privateKeyAlgorithm */
/* PKEYALGO_SEQ   */        { 1, ASN_SEQUENCE, 1, 1, 0 },
/* PKEYALGO_OID   */            { 2, ASN_OBJECT_ID, 0, 0, 1 },
                                         /* privateKey */
/* PKEY           */        { 1, ASN_OCTET_STRING, 0, 1, 0 },
                                             /* CurvePrivateKey */
/* PKEY_CURVEPKEY */            { 2, ASN_OCTET_STRING, 0, 0, 0 },
                                         /* attributes */
/* ATTRS          */        { 1, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_ATTRS, 1, 1, 1 },
                                         /* publicKey */
/* PUBKEY         */        { 1, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY, 0, 0, 1 },
};
enum {
    EDKEYASN_IDX_SEQ = 0,
    EDKEYASN_IDX_VER,
    EDKEYASN_IDX_PKEYALGO_SEQ,
    EDKEYASN_IDX_PKEYALGO_OID,
    EDKEYASN_IDX_PKEY,
    EDKEYASN_IDX_PKEY_CURVEPKEY,
    EDKEYASN_IDX_ATTRS,
    EDKEYASN_IDX_PUBKEY
};

/* Number of items in ASN.1 template for Ed25519 and Ed448 private key. */
#define edKeyASN_Length (sizeof(edKeyASN) / sizeof(ASNItem))
#endif

#if ((defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)) \
    || (defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)) \
    || (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)) \
    || (defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)) \
    || (defined(HAVE_PQC) && defined(HAVE_FALCON)) \
    || (defined(HAVE_PQC) && defined(HAVE_DILITHIUM)) \
    || (defined(HAVE_PQC) && defined(HAVE_SPHINCS)))

int DecodeAsymKey(const byte* input, word32* inOutIdx, word32 inSz,
    byte* privKey, word32* privKeyLen,
    byte* pubKey, word32* pubKeyLen, int keyType)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 oid;
    int version, length, endKeyIdx, privSz, pubSz;
    const byte* priv;
    const byte* pub;
#else
    int ret = 0;
    DECL_ASNGETDATA(dataASN, edKeyASN_Length);
    CALLOC_ASNGETDATA(dataASN, edKeyASN_Length, ret, NULL);
#endif

    if (input == NULL || inOutIdx == NULL || inSz == 0 ||
        privKey == NULL || privKeyLen == NULL) {
        return BAD_FUNC_ARG;
    }

#ifndef WOLFSSL_ASN_TEMPLATE
    if (GetSequence(input, inOutIdx, &length, inSz) >= 0) {
        endKeyIdx = (int)*inOutIdx + length;

        if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
            return ASN_PARSE_E;
        if (version != 0) {
            WOLFSSL_MSG("Unrecognized version of ED25519 private key");
            return ASN_PARSE_E;
        }

        if (GetAlgoId(input, inOutIdx, &oid, oidKeyType, inSz) < 0)
            return ASN_PARSE_E;
        if (oid != (word32)keyType)
            return ASN_PARSE_E;

        if (GetOctetString(input, inOutIdx, &length, inSz) < 0)
            return ASN_PARSE_E;

        if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
            return ASN_PARSE_E;

        priv = input + *inOutIdx;
        *inOutIdx += (word32)privSz;
    }
    else {
        if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
            return ASN_PARSE_E;

        priv = input + *inOutIdx;
        *inOutIdx += (word32)privSz;
        endKeyIdx = (int)*inOutIdx;
    }

    if ((word32)privSz > *privKeyLen)
        return BUFFER_E;

    if (endKeyIdx == (int)*inOutIdx) {
        *privKeyLen = (word32)privSz;
        XMEMCPY(privKey, priv, *privKeyLen);
        if (pubKeyLen != NULL)
            *pubKeyLen = 0;
    }
    else {
        if (pubKeyLen == NULL) {
            return BAD_FUNC_ARG;
        }

        if (GetASNHeader(input, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY | 1,
                         inOutIdx, &pubSz, inSz) < 0) {
            return ASN_PARSE_E;
        }

        if ((word32)pubSz > *pubKeyLen)
            return BUFFER_E;

        pub = input + *inOutIdx;
        *inOutIdx += (word32)pubSz;

        *privKeyLen = (word32)privSz;
        XMEMCPY(privKey, priv, *privKeyLen);
        *pubKeyLen = (word32)pubSz;
        if (pubKey != NULL)
            XMEMCPY(pubKey, pub, *pubKeyLen);
    }
    if (endKeyIdx != (int)*inOutIdx)
        return ASN_PARSE_E;
    return 0;
#else
    if (ret == 0) {
        /* Require OID. */
        word32 oidSz;
        const byte* oid = OidFromId((word32)keyType, oidKeyType, &oidSz);
        GetASN_ExpBuffer(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], oid, oidSz);
        /* Parse full private key. */
        ret = GetASN_Items(edKeyASN, dataASN, edKeyASN_Length, 1, input,
                inOutIdx, inSz);
        if (ret != 0) {
            /* Parse just the OCTET_STRING. */
            ret = GetASN_Items(&edKeyASN[EDKEYASN_IDX_PKEY_CURVEPKEY],
                    &dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY], 1, 0, input,
                    inOutIdx, inSz);
            if (ret != 0) {
                ret = ASN_PARSE_E;
            }
        }
    }
    /* Check the private value length is correct. */
    if ((ret == 0) && dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length
            > *privKeyLen) {
        ret = ASN_PARSE_E;
    }
    if ((ret == 0) && dataASN[EDKEYASN_IDX_PUBKEY].tag == 0) {
        *privKeyLen = dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length;
        XMEMCPY(privKey, dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.data,
                *privKeyLen);
        if (pubKeyLen != NULL)
            *pubKeyLen = 0;
    }
    else if ((ret == 0) &&
             (pubKeyLen != NULL) &&
             (dataASN[EDKEYASN_IDX_PUBKEY].data.ref.length > *pubKeyLen)) {
        ret = ASN_PARSE_E;
    }
    else if (ret == 0) {
        /* Import private and public value. */
        *privKeyLen = dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length;
        XMEMCPY(privKey, dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.data,
                *privKeyLen);
        if (pubKeyLen != NULL)
            *pubKeyLen = dataASN[EDKEYASN_IDX_PUBKEY].data.ref.length;
        if (pubKey != NULL && pubKeyLen != NULL)
            XMEMCPY(pubKey, dataASN[EDKEYASN_IDX_PUBKEY].data.ref.data,
                    *pubKeyLen);
    }

    FREE_ASNGETDATA(dataASN, NULL);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

int DecodeAsymKeyPublic(const byte* input, word32* inOutIdx, word32 inSz,
    byte* pubKey, word32* pubKeyLen, int keyType)
{
    int ret = 0;
#ifndef WOLFSSL_ASN_TEMPLATE
    int length;
    word32 oid;
#else
    word32 len;
    DECL_ASNGETDATA(dataASN, edPubKeyASN_Length);
#endif

    if (input == NULL || inSz == 0 || inOutIdx == NULL ||
        pubKey == NULL || pubKeyLen == NULL) {
        return BAD_FUNC_ARG;
    }

#ifndef WOLFSSL_ASN_TEMPLATE
    if (GetSequence(input, inOutIdx, &length, inSz) < 0)
        return ASN_PARSE_E;

    if (GetSequence(input, inOutIdx, &length, inSz) < 0)
        return ASN_PARSE_E;

    if (GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz) < 0)
        return ASN_PARSE_E;
    if (oid != (word32)keyType)
        return ASN_PARSE_E;

    /* key header */
    ret = CheckBitString(input, inOutIdx, &length, inSz, 1, NULL);
    if (ret != 0)
        return ret;

    /* check that the value found is not too large for pubKey buffer */
    if ((word32)length > *pubKeyLen)
        return ASN_PARSE_E;

    /* check that input buffer is exhausted */
    if (*inOutIdx + (word32)length != inSz)
        return ASN_PARSE_E;

    /* This is the raw point data compressed or uncompressed. */
    *pubKeyLen = (word32)length;
    XMEMCPY(pubKey, input + *inOutIdx, *pubKeyLen);
#else
    len = inSz - *inOutIdx;

    CALLOC_ASNGETDATA(dataASN, edPubKeyASN_Length, ret, NULL);

    if (ret == 0) {
        /* Require OID. */
        word32 oidSz;
        const byte* oid = OidFromId((word32)keyType, oidKeyType, &oidSz);

        GetASN_ExpBuffer(&dataASN[EDPUBKEYASN_IDX_ALGOID_OID], oid, oidSz);
        /* Decode Ed25519 private key. */
        ret = GetASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, 1, input,
                inOutIdx, inSz);
        if (ret != 0)
            ret = ASN_PARSE_E;
        /* check that input buffer is exhausted */
        if (*inOutIdx != inSz)
            ret = ASN_PARSE_E;
    }
    /* Check the public value length is correct. */
    if ((ret == 0) &&
            (dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.length > *pubKeyLen)) {
        ret = ASN_PARSE_E;
    }
    /* Check that the all the buffer was used. */
    if ((ret == 0) &&
            (GetASNItem_Length(dataASN[EDPUBKEYASN_IDX_SEQ], input) != len)) {
        ret = ASN_PARSE_E;
    }
    if (ret == 0) {
        *pubKeyLen = dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.length;
        XMEMCPY(pubKey, dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.data,
                *pubKeyLen);
    }

    FREE_ASNGETDATA(dataASN, NULL);
#endif /* WOLFSSL_ASN_TEMPLATE */
    return ret;
}
#endif
#endif /* WC_ENABLE_ASYM_KEY_IMPORT */

#if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)
int wc_Ed25519PrivateKeyDecode(const byte* input, word32* inOutIdx,
                               ed25519_key* key, word32 inSz)
{
    int ret;
    byte privKey[ED25519_KEY_SIZE], pubKey[ED25519_PUB_KEY_SIZE];
    word32 privKeyLen = (word32)sizeof(privKey);
    word32 pubKeyLen = (word32)sizeof(pubKey);

    if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
        return BAD_FUNC_ARG;
    }

    ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
        pubKey, &pubKeyLen, ED25519k);
    if (ret == 0) {
        if (pubKeyLen == 0) {
            ret = wc_ed25519_import_private_only(privKey, privKeyLen, key);
        }
        else {
            ret = wc_ed25519_import_private_key(privKey, privKeyLen,
                pubKey, pubKeyLen, key);
        }
    }
    return ret;
}

int wc_Ed25519PublicKeyDecode(const byte* input, word32* inOutIdx,
                              ed25519_key* key, word32 inSz)
{
    int ret;
    byte pubKey[ED25519_PUB_KEY_SIZE];
    word32 pubKeyLen = (word32)sizeof(pubKey);

    if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
        return BAD_FUNC_ARG;
    }

    ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
        pubKey, &pubKeyLen, ED25519k);
    if (ret == 0) {
        ret = wc_ed25519_import_public(pubKey, pubKeyLen, key);
    }
    return ret;
}
#endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT */

#if defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)
int wc_Curve25519PrivateKeyDecode(const byte* input, word32* inOutIdx,
                               curve25519_key* key, word32 inSz)
{
    int ret;
    byte privKey[CURVE25519_KEYSIZE];
    word32 privKeyLen = CURVE25519_KEYSIZE;

    if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
        return BAD_FUNC_ARG;
    }

    ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
        NULL, NULL, X25519k);
    if (ret == 0) {
        ret = wc_curve25519_import_private(privKey, privKeyLen, key);
    }
    return ret;
}

int wc_Curve25519PublicKeyDecode(const byte* input, word32* inOutIdx,
                              curve25519_key* key, word32 inSz)
{
    int ret;
    byte pubKey[CURVE25519_KEYSIZE];
    word32 pubKeyLen = (word32)sizeof(pubKey);

    if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
        return BAD_FUNC_ARG;
    }

    ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
        pubKey, &pubKeyLen, X25519k);
    if (ret == 0) {
        ret = wc_curve25519_import_public(pubKey, pubKeyLen, key);
    }
    return ret;
}
#endif /* HAVE_CURVE25519 && HAVE_ED25519_KEY_IMPORT */


#ifdef WC_ENABLE_ASYM_KEY_EXPORT

/* Build ASN.1 formatted key based on RFC 5958 (Asymmetric Key Packages)
 *
 * Pass NULL for output to get the size of the encoding.
 *
 * @param [in]  privKey      private key buffer
 * @param [in]  privKeyLen   private ket buffer length
 * @param [in]  pubKey       public key buffer (optional)
 * @param [in]  pubKeyLen    public ket buffer length
 * @param [out] output       Buffer to put encoded data in (optional)
 * @param [in]  outLen       Size of buffer in bytes
 * @param [in]  keyType      is "enum Key_Sum" like ED25519k
 * @return  Size of encoded data in bytes on success
 * @return  BAD_FUNC_ARG when key is NULL.
 * @return  MEMORY_E when dynamic memory allocation failed.
 */
int SetAsymKeyDer(const byte* privKey, word32 privKeyLen,
    const byte* pubKey, word32 pubKeyLen,
    byte* output, word32 outLen, int keyType)
{
    int ret = 0;
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx = 0, seqSz, verSz, algoSz, privSz, pubSz = 0, sz;
#else
    DECL_ASNSETDATA(dataASN, edKeyASN_Length);
    int sz;
#endif

    /* Validate parameters. */
    if (privKey == NULL || outLen == 0) {
        return BAD_FUNC_ARG;
    }

#ifndef WOLFSSL_ASN_TEMPLATE
    /* calculate size */
    if (pubKey) {
        pubSz = 2 + pubKeyLen;
    }
    privSz = 2 + 2 + privKeyLen;
    algoSz = SetAlgoID(keyType, NULL, oidKeyType, 0);
    verSz  = 3; /* version is 3 bytes (enum + id + version(byte)) */
    seqSz  = SetSequence(verSz + algoSz + privSz + pubSz, NULL);
    sz = seqSz + verSz + algoSz + privSz + pubSz;

    /* checkout output size */
    if (output != NULL && sz > outLen) {
        ret = BAD_FUNC_ARG;
    }

    if (ret == 0 && output != NULL) {
        /* write out */
        /* seq */
        seqSz = SetSequence(verSz + algoSz + privSz + pubSz, output);
        idx = seqSz;
        /* ver */
        SetMyVersion(0, output + idx, FALSE);
        idx += verSz;
        /* algo */
        algoSz = SetAlgoID(keyType, output + idx, oidKeyType, 0);
        idx += algoSz;
        /* privKey */
        idx += SetOctetString(2 + privKeyLen, output + idx);
        idx += SetOctetString(privKeyLen, output + idx);
        XMEMCPY(output + idx, privKey, privKeyLen);
        idx += privKeyLen;
        /* pubKey */
        if (pubKey) {
            idx += SetHeader(ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY |
                             1, pubKeyLen, output + idx);
            XMEMCPY(output + idx, pubKey, pubKeyLen);
            idx += pubKeyLen;
        }
        sz = idx;
    }
    if (ret == 0) {
        /* Return size of encoding. */
        ret = (int)sz;
    }
#else

    CALLOC_ASNSETDATA(dataASN, edKeyASN_Length, ret, NULL);

    if (ret == 0) {
        /* Set version = 0 */
        SetASN_Int8Bit(&dataASN[EDKEYASN_IDX_VER], 0);
        /* Set OID. */
        SetASN_OID(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], (word32)keyType,
                   oidKeyType);
        /* Leave space for private key. */
        SetASN_Buffer(&dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY], NULL, privKeyLen);
        /* Don't write out attributes. */
        dataASN[EDKEYASN_IDX_ATTRS].noOut = 1;
        if (pubKey) {
            /* Leave space for public key. */
            SetASN_Buffer(&dataASN[EDKEYASN_IDX_PUBKEY], NULL, pubKeyLen);
        }
        else {
            /* Don't put out public part. */
            SetASNItem_NoOutNode(dataASN, edKeyASN, EDKEYASN_IDX_PUBKEY,
                    edKeyASN_Length);
        }

        /* Calculate the size of encoding. */
        ret = SizeASN_Items(edKeyASN, dataASN, edKeyASN_Length, &sz);
    }

    /* Check buffer is big enough. */
    if ((ret == 0) && (output != NULL) && (sz > (int)outLen)) {
        ret = BAD_FUNC_ARG;
    }
    if ((ret == 0) && (output != NULL)) {
        /* Encode private key. */
        SetASN_Items(edKeyASN, dataASN, edKeyASN_Length, output);

        /* Put private value into space provided. */
        XMEMCPY((byte*)dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.buffer.data,
                privKey, privKeyLen);

        if (pubKey != NULL) {
            /* Put public value into space provided. */
            XMEMCPY((byte*)dataASN[EDKEYASN_IDX_PUBKEY].data.buffer.data,
                    pubKey, pubKeyLen);
        }
    }
    if (ret == 0) {
        /* Return size of encoding. */
        ret = sz;
    }

    FREE_ASNSETDATA(dataASN, NULL);
#endif
    return ret;
}
#endif /* WC_ENABLE_ASYM_KEY_EXPORT */

#if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
/* Write a Private ED25519 key, including public to DER format,
 * length on success else < 0 */
int wc_Ed25519KeyToDer(ed25519_key* key, byte* output, word32 inLen)
{
    if (key == NULL) {
        return BAD_FUNC_ARG;
    }
    return SetAsymKeyDer(key->k, ED25519_KEY_SIZE,
        key->p, ED25519_PUB_KEY_SIZE, output, inLen, ED25519k);
}

/* Write only private ED25519 key to DER format,
 * length on success else < 0 */
int wc_Ed25519PrivateKeyToDer(ed25519_key* key, byte* output, word32 inLen)
{
    if (key == NULL) {
        return BAD_FUNC_ARG;
    }
    return SetAsymKeyDer(key->k, ED25519_KEY_SIZE,
        NULL, 0, output, inLen, ED25519k);
}
#endif /* HAVE_ED25519 && HAVE_ED25519_KEY_EXPORT */

#if defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_EXPORT)
/* Write only private Curve25519 key to DER format,
 * length on success else < 0 */
int wc_Curve25519PrivateKeyToDer(curve25519_key* key, byte* output, word32 inLen)
{
    int    ret;
    byte   privKey[CURVE25519_KEYSIZE];
    word32 privKeyLen = CURVE25519_KEYSIZE;

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

    ret = wc_curve25519_export_private_raw(key, privKey, &privKeyLen);
    if (ret == 0) {
        ret = SetAsymKeyDer(privKey, privKeyLen, NULL, 0, output, inLen,
            X25519k);
    }
    return ret;
}

/* Write a public Curve25519 key to DER format,
 * length on success else < 0 */
int wc_Curve25519PublicKeyToDer(curve25519_key* key, byte* output, word32 inLen,
                             int withAlg)
{
    int    ret;
    byte   pubKey[CURVE25519_PUB_KEY_SIZE];
    word32 pubKeyLen = (word32)sizeof(pubKey);

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

    ret = wc_curve25519_export_public(key, pubKey, &pubKeyLen);
    if (ret == 0) {
        ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
            X25519k, withAlg);
    }
    return ret;
}
#endif /* HAVE_CURVE25519 && HAVE_CURVE25519_KEY_EXPORT */

#if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)
int wc_Ed448PrivateKeyDecode(const byte* input, word32* inOutIdx,
                               ed448_key* key, word32 inSz)
{
    int ret;
    byte privKey[ED448_KEY_SIZE], pubKey[ED448_PUB_KEY_SIZE];
    word32 privKeyLen = (word32)sizeof(privKey);
    word32 pubKeyLen = (word32)sizeof(pubKey);

    if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
        return BAD_FUNC_ARG;
    }

    ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
        pubKey, &pubKeyLen, ED448k);
    if (ret == 0) {
        if (pubKeyLen == 0) {
            ret = wc_ed448_import_private_only(privKey, privKeyLen, key);
        }
        else {
            ret = wc_ed448_import_private_key(privKey, privKeyLen,
                pubKey, pubKeyLen, key);
        }
    }
    return ret;
}

int wc_Ed448PublicKeyDecode(const byte* input, word32* inOutIdx,
                              ed448_key* key, word32 inSz)
{
    int ret;
    byte pubKey[ED448_PUB_KEY_SIZE];
    word32 pubKeyLen = (word32)sizeof(pubKey);

    if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
        return BAD_FUNC_ARG;
    }

    ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
        pubKey, &pubKeyLen, ED448k);
    if (ret == 0) {
        ret = wc_ed448_import_public(pubKey, pubKeyLen, key);
    }
    return ret;
}
#endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT */

#if defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)
int wc_Curve448PrivateKeyDecode(const byte* input, word32* inOutIdx,
                               curve448_key* key, word32 inSz)
{
    int ret;
    byte privKey[CURVE448_KEY_SIZE];
    word32 privKeyLen = CURVE448_KEY_SIZE;

    if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
        return BAD_FUNC_ARG;
    }

    ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
        NULL, NULL, X448k);
    if (ret == 0) {
        ret = wc_curve448_import_private(privKey, privKeyLen, key);
    }
    return ret;
}

int wc_Curve448PublicKeyDecode(const byte* input, word32* inOutIdx,
                              curve448_key* key, word32 inSz)
{
    int ret;
    byte pubKey[CURVE448_PUB_KEY_SIZE];
    word32 pubKeyLen = (word32)sizeof(pubKey);

    if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
        return BAD_FUNC_ARG;
    }

    ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
        pubKey, &pubKeyLen, X448k);
    if (ret == 0) {
        ret = wc_curve448_import_public(pubKey, pubKeyLen, key);
    }
    return ret;
}
#endif /* HAVE_CURVE448 && HAVE_ED448_KEY_IMPORT */

#if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
/* Write a Private ecc key, including public to DER format,
 * length on success else < 0 */
int wc_Ed448KeyToDer(ed448_key* key, byte* output, word32 inLen)
{
    if (key == NULL) {
        return BAD_FUNC_ARG;
    }
    return SetAsymKeyDer(key->k, ED448_KEY_SIZE,
        key->p, ED448_KEY_SIZE, output, inLen, ED448k);
}

/* Write only private ecc key to DER format,
 * length on success else < 0 */
int wc_Ed448PrivateKeyToDer(ed448_key* key, byte* output, word32 inLen)
{
    if (key == NULL) {
        return BAD_FUNC_ARG;
    }
    return SetAsymKeyDer(key->k, ED448_KEY_SIZE,
        NULL, 0, output, inLen, ED448k);
}

#endif /* HAVE_ED448 && HAVE_ED448_KEY_EXPORT */

#if defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_EXPORT)
/* Write private Curve448 key to DER format,
 * length on success else < 0 */
int wc_Curve448PrivateKeyToDer(curve448_key* key, byte* output, word32 inLen)
{
    int    ret;
    byte   privKey[CURVE448_KEY_SIZE];
    word32 privKeyLen = CURVE448_KEY_SIZE;

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

    ret = wc_curve448_export_private_raw(key, privKey, &privKeyLen);
    if (ret == 0) {
        ret = SetAsymKeyDer(privKey, privKeyLen, NULL, 0, output, inLen,
            X448k);
    }
    return ret;
}
/* Write a public Curve448 key to DER format,
 * length on success else < 0 */
int wc_Curve448PublicKeyToDer(curve448_key* key, byte* output, word32 inLen,
                             int withAlg)
{
    int    ret;
    byte   pubKey[CURVE448_PUB_KEY_SIZE];
    word32 pubKeyLen = (word32)sizeof(pubKey);

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

    ret = wc_curve448_export_public(key, pubKey, &pubKeyLen);
    if (ret == 0) {
        ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
            X448k, withAlg);
    }
    return ret;
}
#endif /* HAVE_CURVE448 && HAVE_CURVE448_KEY_EXPORT */


#ifndef WOLFSSL_ASN_TEMPLATE
#if (defined(HAVE_OCSP) || defined(HAVE_CRL)) && !defined(WOLFCRYPT_ONLY)

/* Get raw Date only, no processing, 0 on success */
static int GetBasicDate(const byte* source, word32* idx, byte* date,
                        byte* format, int maxIdx)
{
    int    ret, length;
    const byte *datePtr = NULL;

    WOLFSSL_ENTER("GetBasicDate");

    ret = GetDateInfo(source, idx, &datePtr, format, &length, maxIdx);
    if (ret < 0)
        return ret;

    XMEMCPY(date, datePtr, length);

    return 0;
}

#endif /* HAVE_OCSP || HAVE_CRL */
#endif /* WOLFSSL_ASN_TEMPLATE */


#if defined(HAVE_OCSP) && !defined(WOLFCRYPT_ONLY)

#ifndef WOLFSSL_ASN_TEMPLATE
static int GetEnumerated(const byte* input, word32* inOutIdx, int *value,
        int sz)
{
    word32 idx = *inOutIdx;
    word32 len;
    byte   tag;

    WOLFSSL_ENTER("GetEnumerated");

    *value = 0;

    if (GetASNTag(input, &idx, &tag, sz) < 0)
        return ASN_PARSE_E;

    if (tag != ASN_ENUMERATED)
        return ASN_PARSE_E;

    if ((int)idx >= sz)
        return BUFFER_E;

    len = input[idx++];
    if (len > 4 || (int)(len + idx) > sz)
        return ASN_PARSE_E;

    while (len--) {
        *value  = *value << 8 | input[idx++];
    }

    *inOutIdx = idx;

    return *value;
}
#endif /* !WOLFSSL_ASN_TEMPLATE */


#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for OCSP single response.
 * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
 */
static const ASNItem singleResponseASN[] = {
/* SEQ                   */ { 0, ASN_SEQUENCE, 1, 1, 0 },
                                                      /* certId */
/* CID_SEQ               */     { 1, ASN_SEQUENCE, 1, 1, 0 },
                                                          /* hashAlgorithm */
/* CID_HASHALGO_SEQ      */         { 2, ASN_SEQUENCE, 1, 1, 0 },
/* CID_HASHALGO_OID      */             { 3, ASN_OBJECT_ID, 0, 0, 0 },
/* CID_HASHALGO_NULL     */             { 3, ASN_TAG_NULL, 0, 0, 1 },
                                                          /* issuerNameHash */
/* CID_ISSUERHASH        */         { 2, ASN_OCTET_STRING, 0, 0, 0 },
                                                          /* issuerKeyHash */
/* CID_ISSUERKEYHASH     */         { 2, ASN_OCTET_STRING, 0, 0, 0 },
                                                          /* serialNumber */
/* CID_SERIAL            */         { 2, ASN_INTEGER, 0, 0, 0 },
                                                      /* certStatus - CHOICE */
                                                      /* good              [0] IMPLICIT NULL */
/* CS_GOOD               */     { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 2 },
                                                      /* revoked           [1] IMPLICIT RevokedInfo */
/* CS_REVOKED            */     { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 1, 2 },
                                                          /* revocationTime */
/* CS_REVOKED_TIME       */         { 2, ASN_GENERALIZED_TIME, 0, 0, 0 },
                                                          /* revocationReason  [0] EXPLICIT CRLReason OPTIONAL */
/* CS_REVOKED_REASON     */         { 2, ASN_CONTEXT_SPECIFIC | 0, 0, 1, 1 },
                                                              /* crlReason */
/* CS_REVOKED_REASON_VAL */             { 3, ASN_ENUMERATED, 0, 0, 0 },
                                                      /* unknown           [2] IMPLICIT UnknownInfo ::= NULL */
/* UNKNOWN               */     { 1, ASN_CONTEXT_SPECIFIC | 2, 0, 0, 2 },

                                                      /* thisUpdate */
/* THISUPDATE_GT         */     { 1, ASN_GENERALIZED_TIME, 0, 0, 0 },
                                                      /* nextUpdate */
/* NEXTUPDATE            */     { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
/* NEXTUPDATE_GT         */         { 2, ASN_GENERALIZED_TIME, 0, 0, 0 },
                                                      /* singleExtensions */
/* EXT                   */     { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
};
enum {
    SINGLERESPONSEASN_IDX_SEQ = 0,
    SINGLERESPONSEASN_IDX_CID_SEQ,
    SINGLERESPONSEASN_IDX_CID_HASHALGO_SEQ,
    SINGLERESPONSEASN_IDX_CID_HASHALGO_OID,
    SINGLERESPONSEASN_IDX_CID_HASHALGO_NULL,
    SINGLERESPONSEASN_IDX_CID_ISSUERHASH,
    SINGLERESPONSEASN_IDX_CID_ISSUERKEYHASH,
    SINGLERESPONSEASN_IDX_CID_SERIAL,
    SINGLERESPONSEASN_IDX_CS_GOOD,
    SINGLERESPONSEASN_IDX_CS_REVOKED,
    SINGLERESPONSEASN_IDX_CS_REVOKED_TIME,
    SINGLERESPONSEASN_IDX_CS_REVOKED_REASON,
    SINGLERESPONSEASN_IDX_CS_REVOKED_REASON_VAL,
    SINGLERESPONSEASN_IDX_UNKNOWN,
    SINGLERESPONSEASN_IDX_THISUPDATE_GT,
    SINGLERESPONSEASN_IDX_NEXTUPDATE,
    SINGLERESPONSEASN_IDX_NEXTUPDATE_GT,
    SINGLERESPONSEASN_IDX_EXT,
};

/* Number of items in ASN.1 template for OCSP single response. */
#define singleResponseASN_Length (sizeof(singleResponseASN) / sizeof(ASNItem))
#endif

static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size,
                                int wrapperSz, OcspEntry* single)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx = *ioIndex, prevIndex, oid, localIdx, certIdIdx;
    int length;
    int ret;
    byte tag;

    WOLFSSL_ENTER("DecodeSingleResponse");

    prevIndex = idx;

    /* Wrapper around the Single Response */
    if (GetSequence(source, &idx, &length, size) < 0)
        return ASN_PARSE_E;

    /* Wrapper around the CertID */
    certIdIdx = idx;
    if (GetSequence(source, &idx, &length, size) < 0)
        return ASN_PARSE_E;
    single->rawCertId = source + certIdIdx;
    /* Hash algorithm */
    ret = GetAlgoId(source, &idx, &oid, oidIgnoreType, size);
    if (ret < 0)
        return ret;
    single->hashAlgoOID = oid;
    /* Save reference to the hash of CN */
    ret = GetOctetString(source, &idx, &length, size);
    if (ret < 0)
        return ret;
    if (length > (int)sizeof(single->issuerHash))
        return BUFFER_E;
    XMEMCPY(single->issuerHash, source + idx, length);
    idx += length;
    /* Save reference to the hash of the issuer public key */
    ret = GetOctetString(source, &idx, &length, size);
    if (ret < 0)
        return ret;
    if (length > (int)sizeof(single->issuerKeyHash))
        return BUFFER_E;
    XMEMCPY(single->issuerKeyHash, source + idx, length);
    idx += length;

    /* Get serial number */
    if (wc_GetSerialNumber(source, &idx, single->status->serial,
                        &single->status->serialSz, size) < 0)
        return ASN_PARSE_E;
    single->rawCertIdSize = idx - certIdIdx;

    if (idx >= size)
        return BUFFER_E;

    /* CertStatus */
    switch (source[idx++])
    {
        case (ASN_CONTEXT_SPECIFIC | CERT_GOOD):
            single->status->status = CERT_GOOD;
            idx++;
            break;
        case (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CERT_REVOKED):
            single->status->status = CERT_REVOKED;
            if (GetLength(source, &idx, &length, size) < 0)
                return ASN_PARSE_E;
            idx += length;
            break;
        case (ASN_CONTEXT_SPECIFIC | CERT_UNKNOWN):
            single->status->status = CERT_UNKNOWN;
            idx++;
            break;
        default:
            return ASN_PARSE_E;
    }

    if (idx >= size)
        return BUFFER_E;

#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
    single->status->thisDateAsn = source + idx;
    localIdx = 0;
    if (GetDateInfo(single->status->thisDateAsn, &localIdx, NULL,
                    (byte*)&single->status->thisDateParsed.type,
                    &single->status->thisDateParsed.length, size - idx) < 0)
        return ASN_PARSE_E;

    if (idx + localIdx >= size)
        return BUFFER_E;

    XMEMCPY(single->status->thisDateParsed.data,
            single->status->thisDateAsn + localIdx - single->status->thisDateParsed.length,
            single->status->thisDateParsed.length);
#endif
    if (GetBasicDate(source, &idx, single->status->thisDate,
                                                &single->status->thisDateFormat, size) < 0)
        return ASN_PARSE_E;

#ifndef NO_ASN_TIME_CHECK
#ifndef WOLFSSL_NO_OCSP_DATE_CHECK
    if (!XVALIDATE_DATE(single->status->thisDate, single->status->thisDateFormat, BEFORE))
        return ASN_BEFORE_DATE_E;
#endif
#endif

    /* The following items are optional. Only check for them if there is more
     * unprocessed data in the singleResponse wrapper. */
    localIdx = idx;
    if (((int)(idx - prevIndex) < wrapperSz) &&
        GetASNTag(source, &localIdx, &tag, size) == 0 &&
        tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
    {
        idx++;
        if (GetLength(source, &idx, &length, size) < 0)
            return ASN_PARSE_E;
#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
        single->status->nextDateAsn = source + idx;
        localIdx = 0;
        if (GetDateInfo(single->status->nextDateAsn, &localIdx, NULL,
                        (byte*)&single->status->nextDateParsed.type,
                        &single->status->nextDateParsed.length, size - idx) < 0)
            return ASN_PARSE_E;

        if (idx + localIdx >= size)
            return BUFFER_E;

        XMEMCPY(single->status->nextDateParsed.data,
                single->status->nextDateAsn + localIdx - single->status->nextDateParsed.length,
                single->status->nextDateParsed.length);
#endif
        if (GetBasicDate(source, &idx, single->status->nextDate,
                                                &single->status->nextDateFormat, size) < 0)
            return ASN_PARSE_E;

#ifndef NO_ASN_TIME_CHECK
#ifndef WOLFSSL_NO_OCSP_DATE_CHECK
        if (!XVALIDATE_DATE(single->status->nextDate, single->status->nextDateFormat, AFTER))
            return ASN_AFTER_DATE_E;
#endif
#endif
    }

    /* Skip the optional extensions in singleResponse. */
    localIdx = idx;
    if (((int)(idx - prevIndex) < wrapperSz) &&
        GetASNTag(source, &localIdx, &tag, size) == 0 &&
        tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
    {
        idx++;
        if (GetLength(source, &idx, &length, size) < 0)
            return ASN_PARSE_E;
        idx += length;
    }

    *ioIndex = idx;

    return 0;
#else
    DECL_ASNGETDATA(dataASN, singleResponseASN_Length);
    int ret = 0;
    CertStatus* cs = NULL;
    word32 serialSz;
    word32 issuerHashLen;
    word32 issuerKeyHashLen;
    word32 thisDateLen;
    word32 nextDateLen;
#if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
    defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
    WOLFSSL_ASN1_TIME *at;
#endif

    (void)wrapperSz;

    WOLFSSL_ENTER("DecodeSingleResponse");

    CALLOC_ASNGETDATA(dataASN, singleResponseASN_Length, ret, NULL);

    if (ret == 0) {
        /* Certificate Status field. */
        cs = single->status;

        /* Set maximum lengths for data. */
        issuerHashLen    = OCSP_DIGEST_SIZE;
        issuerKeyHashLen = OCSP_DIGEST_SIZE;
        serialSz         = EXTERNAL_SERIAL_SIZE;
        thisDateLen      = MAX_DATE_SIZE;
        nextDateLen      = MAX_DATE_SIZE;

        /* Set OID type, buffers to hold data and variables to hold size. */
        GetASN_OID(&dataASN[SINGLERESPONSEASN_IDX_CID_HASHALGO_OID],
                oidHashType);
        GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_ISSUERHASH],
                single->issuerHash, &issuerHashLen);
        GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_ISSUERKEYHASH],
                single->issuerKeyHash, &issuerKeyHashLen);
        GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_SERIAL], cs->serial,
                &serialSz);
        GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_THISUPDATE_GT],
                cs->thisDate, &thisDateLen);
        GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT],
                cs->nextDate, &nextDateLen);
        /* TODO: decode revoked time and reason. */
        /* Decode OCSP single response. */
        ret = GetASN_Items(singleResponseASN, dataASN, singleResponseASN_Length,
                1, source, ioIndex, size);
    }
    /* Validate the issuer hash length is the size required. */
    if ((ret == 0) && (issuerHashLen != OCSP_DIGEST_SIZE)) {
        ret = ASN_PARSE_E;
    }
    /* Validate the issuer key hash length is the size required. */
    if ((ret == 0) && (issuerKeyHashLen != OCSP_DIGEST_SIZE)) {
        ret = ASN_PARSE_E;
    }
    if (ret == 0) {
        /* Store serial size. */
        cs->serialSz = serialSz;

        /* Determine status by which item was found. */
        if (dataASN[SINGLERESPONSEASN_IDX_CS_GOOD].tag != 0) {
            cs->status = CERT_GOOD;
        }
        if (dataASN[SINGLERESPONSEASN_IDX_CS_REVOKED].tag != 0) {
            cs->status = CERT_REVOKED;
        }
        if (dataASN[SINGLERESPONSEASN_IDX_UNKNOWN].tag != 0) {
            cs->status = CERT_UNKNOWN;
        }

        /* Store the thisDate format - only one possible. */
        cs->thisDateFormat = ASN_GENERALIZED_TIME;
    #if !defined(NO_ASN_TIME_CHECK) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK)
        /* Check date is a valid string and BEFORE now. */
        if (!XVALIDATE_DATE(cs->thisDate, ASN_GENERALIZED_TIME, BEFORE)) {
            ret = ASN_BEFORE_DATE_E;
        }
    }
    if (ret == 0) {
    #endif
    #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
        defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
        /* Store ASN.1 version of thisDate. */
        cs->thisDateAsn = GetASNItem_Addr(
                dataASN[SINGLERESPONSEASN_IDX_THISUPDATE_GT], source);
        at = &cs->thisDateParsed;
        at->type = ASN_GENERALIZED_TIME;
        XMEMCPY(at->data, cs->thisDate, thisDateLen);
        at->length = thisDateLen;
    #endif
    }
    if ((ret == 0) &&
            (dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT].tag != 0)) {
        /* Store the nextDate format - only one possible. */
        cs->nextDateFormat = ASN_GENERALIZED_TIME;
    #if !defined(NO_ASN_TIME_CHECK) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK)
        /* Check date is a valid string and AFTER now. */
        if (!XVALIDATE_DATE(cs->nextDate, ASN_GENERALIZED_TIME, AFTER)) {
            ret = ASN_AFTER_DATE_E;
        }
    }
    if ((ret == 0) &&
            (dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT].tag != 0)) {
    #endif
    #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
        defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
        /* Store ASN.1 version of thisDate. */
        cs->nextDateAsn = GetASNItem_Addr(
                dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT], source);
        at = &cs->nextDateParsed;
        at->type = ASN_GENERALIZED_TIME;
        XMEMCPY(at->data, cs->nextDate, nextDateLen);
        at->length = nextDateLen;
    #endif
    }
    if (ret == 0) {
        /* OcspEntry now used. */
        single->used = 1;
    }

    FREE_ASNGETDATA(dataASN, NULL);
    return ret;
#endif
}

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for OCSP response extension header.
 * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
 */
static const ASNItem respExtHdrASN[] = {
                                   /* responseExtensions */
/* EXT     */    { 0, ASN_CONTEXT_SPECIFIC | 1, 1, 1, 0 },
                                       /* extensions */
/* EXT_SEQ */        { 1, ASN_SEQUENCE, 1, 1, 0 },
};
enum {
    RESPEXTHDRASN_IDX_EXT = 0,
    RESPEXTHDRASN_IDX_EXT_SEQ,
};

/* Number of items in ASN.1 template for OCSP response extension header. */
#define respExtHdrASN_Length (sizeof(respExtHdrASN) / sizeof(ASNItem))
#endif

static int DecodeOcspRespExtensions(byte* source, word32* ioIndex,
                                    OcspResponse* resp, word32 sz)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx = *ioIndex;
    int length;
    int ext_bound; /* boundary index for the sequence of extensions */
    word32 oid;
    int ret;
    byte tag;

    WOLFSSL_ENTER("DecodeOcspRespExtensions");

    if ((idx + 1) > sz)
        return BUFFER_E;

    if (GetASNTag(source, &idx, &tag, sz) < 0)
        return ASN_PARSE_E;

    if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
        return ASN_PARSE_E;

    if (GetLength(source, &idx, &length, sz) < 0)
        return ASN_PARSE_E;

    if (GetSequence(source, &idx, &length, sz) < 0)
        return ASN_PARSE_E;

    ext_bound = idx + length;

    while (idx < (word32)ext_bound) {
        word32 localIdx;

        if (GetSequence(source, &idx, &length, sz) < 0) {
            WOLFSSL_MSG("\tfail: should be a SEQUENCE");
            return ASN_PARSE_E;
        }

        oid = 0;
        if (GetObjectId(source, &idx, &oid, oidOcspType, sz) < 0) {
            WOLFSSL_MSG("\tfail: OBJECT ID");
            return ASN_PARSE_E;
        }

        /* check for critical flag */
        if ((idx + 1) > (word32)sz) {
            WOLFSSL_MSG("\tfail: malformed buffer");
            return BUFFER_E;
        }

        localIdx = idx;
        if (GetASNTag(source, &localIdx, &tag, sz) == 0 && tag == ASN_BOOLEAN) {
            WOLFSSL_MSG("\tfound optional critical flag, moving past");
            ret = GetBoolean(source, &idx, sz);
            if (ret < 0)
                return ret;
        }

        ret = GetOctetString(source, &idx, &length, sz);
        if (ret < 0)
            return ret;

        if (oid == OCSP_NONCE_OID) {
            /* get data inside extra OCTET_STRING */
            ret = GetOctetString(source, &idx, &length, sz);
            if (ret < 0)
                return ret;

            resp->nonce = source + idx;
            resp->nonceSz = length;
        }

        idx += length;
    }

    *ioIndex = idx;
    return 0;
#else
    /* certExtASN_Length is greater than respExtHdrASN_Length */
    DECL_ASNGETDATA(dataASN, certExtASN_Length);
    int ret = 0;
    word32 idx = *ioIndex;
    word32 maxIdx = 0;

    WOLFSSL_ENTER("DecodeOcspRespExtensions");

    CALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, resp->heap);

    if (ret == 0) {
        /* Check for header and move past. */
        ret = GetASN_Items(respExtHdrASN, dataASN, respExtHdrASN_Length, 0,
            source, &idx, sz);
    }
    if (ret == 0) {
        /* Keep end extensions index for total length check. */
        maxIdx = idx + dataASN[RESPEXTHDRASN_IDX_EXT_SEQ].length;
    }

    /* Step through all extensions. */
    while ((ret == 0) && (idx < maxIdx)) {
        /* Clear dynamic data, set OID type to expect. */
        XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
        GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidOcspType);
        /* TODO: check criticality. */
        /* Decode OCSP response extension. */
        ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0,
                           source, &idx, sz);
        if (ret == 0) {
            word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
            int length = dataASN[CERTEXTASN_IDX_VAL].length;

            if (oid == OCSP_NONCE_OID) {
                /* Extract nonce data. */
                ret = GetOctetString(source, &idx, &length, sz);
                if (ret >= 0) {
                    ret = 0;
                    /* get data inside extra OCTET_STRING */
                    resp->nonce = source + idx;
                    resp->nonceSz = length;
                }
            }
            /* Ignore all other extension types. */

            /* Skip over rest of extension. */
            idx += length;
        }
    }

    /* Return index after extensions. */
    *ioIndex = idx;

    FREE_ASNGETDATA(dataASN, resp->heap);
    return ret;
#endif
}

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for OCSP ResponseData.
 * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
 */
static const ASNItem ocspRespDataASN[] = {
/* SEQ         */    { 0, ASN_SEQUENCE, 1, 1, 0 },
                                             /* version DEFAULT v1 */
/* VER_PRESENT */        { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
/* VER         */            { 2, ASN_INTEGER, 1, 0, 0 },
                                             /* byName */
/* BYNAME      */        { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 2 },
                                             /* byKey */
/* BYKEY       */        { 1, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 2 },
                                             /* producedAt */
/* PA          */        { 1, ASN_GENERALIZED_TIME, 0, 0, 0, },
                                             /* responses */
/* RESP        */        { 1, ASN_SEQUENCE, 1, 0, 0 },
                                             /* responseExtensions */
/* RESPEXT     */        { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 }
};
enum {
    OCSPRESPDATAASN_IDX_SEQ = 0,
    OCSPRESPDATAASN_IDX_VER_PRESENT,
    OCSPRESPDATAASN_IDX_VER,
    OCSPRESPDATAASN_IDX_BYNAME,
    OCSPRESPDATAASN_IDX_BYKEY,
    OCSPRESPDATAASN_IDX_PA,
    OCSPRESPDATAASN_IDX_RESP,
    OCSPRESPDATAASN_IDX_RESPEXT,
};

/* Number of items in ASN.1 template for OCSP ResponseData. */
#define ocspRespDataASN_Length (sizeof(ocspRespDataASN) / sizeof(ASNItem))
#endif

static int DecodeResponseData(byte* source, word32* ioIndex,
                              OcspResponse* resp, word32 size)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx = *ioIndex, prev_idx, localIdx;
    int length;
    int version;
    int ret;
    byte tag;
    int wrapperSz;
    OcspEntry* single;

    WOLFSSL_ENTER("DecodeResponseData");

    resp->response = source + idx;
    prev_idx = idx;
    if (GetSequence(source, &idx, &length, size) < 0)
        return ASN_PARSE_E;
    resp->responseSz = length + idx - prev_idx;

    /* Get version. It is an EXPLICIT[0] DEFAULT(0) value. If this
     * item isn't an EXPLICIT[0], then set version to zero and move
     * onto the next item.
     */
    localIdx = idx;
    if (GetASNTag(source, &localIdx, &tag, size) == 0 &&
            tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))
    {
        idx += 2; /* Eat the value and length */
        if (GetMyVersion(source, &idx, &version, size) < 0)
            return ASN_PARSE_E;
    } else
        version = 0;

    localIdx = idx;
    if (GetASNTag(source, &localIdx, &tag, size) == 0 &&
        ( tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1) ||
          tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2) ))
    {
        idx++; /* advance past ASN tag */
        if (GetLength(source, &idx, &length, size) < 0)
            return ASN_PARSE_E;
        idx += length;
    }
    else
        return ASN_PARSE_E;

    /* save pointer to the producedAt time */
    if (GetBasicDate(source, &idx, resp->producedDate,
                                        &resp->producedDateFormat, size) < 0)
        return ASN_PARSE_E;

    /* Outer wrapper of the SEQUENCE OF Single Responses. */
    if (GetSequence(source, &idx, &wrapperSz, size) < 0)
        return ASN_PARSE_E;

    localIdx = idx;
    single = resp->single;
    while (idx - localIdx < (word32)wrapperSz) {
        ret = DecodeSingleResponse(source, &idx, size, wrapperSz, single);
        if (ret < 0)
            return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */
        if (idx - localIdx < (word32)wrapperSz) {
            single->next = (OcspEntry*)XMALLOC(sizeof(OcspEntry), resp->heap,
                DYNAMIC_TYPE_OCSP_ENTRY);
            if (single->next == NULL) {
                return MEMORY_E;
            }
            XMEMSET(single->next, 0, sizeof(OcspEntry));

            single->next->status = (CertStatus*)XMALLOC(sizeof(CertStatus),
                resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
            if (single->next->status == NULL) {
                XFREE(single->next, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
                single->next = NULL;
                return MEMORY_E;
            }
            XMEMSET(single->next->status, 0, sizeof(CertStatus));

            single->next->isDynamic = 1;

            single = single->next;
        }
    }

    /*
     * Check the length of the ResponseData against the current index to
     * see if there are extensions, they are optional.
     */
    if (idx - prev_idx < resp->responseSz)
        if (DecodeOcspRespExtensions(source, &idx, resp, size) < 0)
            return ASN_PARSE_E;

    *ioIndex = idx;
    return 0;
#else
    DECL_ASNGETDATA(dataASN, ocspRespDataASN_Length);
    int ret = 0;
    byte version;
    word32 dateSz, idx = *ioIndex;
    OcspEntry* single = NULL;

    WOLFSSL_ENTER("DecodeResponseData");

    CALLOC_ASNGETDATA(dataASN, ocspRespDataASN_Length, ret, resp->heap);

    if (ret == 0) {
        resp->response = source + idx;
        /* Default, not present, is v1 = 0. */
        version = 0;
        /* Max size of date supported. */
        dateSz = MAX_DATE_SIZE;

        /* Set the where to put version an produced date. */
        GetASN_Int8Bit(&dataASN[OCSPRESPDATAASN_IDX_VER], &version);
        GetASN_Buffer(&dataASN[OCSPRESPDATAASN_IDX_PA], resp->producedDate,
                &dateSz);
        /* Decode the ResponseData. */
        ret = GetASN_Items(ocspRespDataASN, dataASN, ocspRespDataASN_Length,
                1, source, ioIndex, size);
    }
    /* Only support v1 == 0 */
    if ((ret == 0) && (version != 0)) {
        ret = ASN_PARSE_E;
    }
    /* Ensure date is a minimal size. */
    if ((ret == 0) && (dateSz < MIN_DATE_SIZE)) {
        ret = ASN_PARSE_E;
    }
    if (ret == 0) {
        /* TODO: use byName/byKey fields. */
        /* Store size of response. */
        resp->responseSz = *ioIndex - idx;
        /* Store date format/tag. */
        resp->producedDateFormat = dataASN[OCSPRESPDATAASN_IDX_PA].tag;

        /* Get the index of the responses SEQUENCE. */
        idx = GetASNItem_DataIdx(dataASN[OCSPRESPDATAASN_IDX_RESP], source);
        /* Start with the pre-existing OcspEntry. */
        single = resp->single;
    }
    while ((ret == 0) && (idx < dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset)) {
        /* Allocate and use a new OCSP entry if this is used. */
        if (single->used) {
            single->next = (OcspEntry*)XMALLOC(sizeof(OcspEntry), resp->heap,
                    DYNAMIC_TYPE_OCSP_ENTRY);
            if (single->next == NULL) {
                ret = MEMORY_E;
            }
            else {
                XMEMSET(single->next, 0, sizeof(OcspEntry));

                single->next->status = (CertStatus*)XMALLOC(sizeof(CertStatus),
                    resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
                if (single->next->status == NULL) {
                    XFREE(single->next, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
                    single->next = NULL;
                    ret = MEMORY_E;
                }
                else {
                    XMEMSET(single->next->status, 0, sizeof(CertStatus));

                    /* Entry to be freed. */
                    single->next->isDynamic = 1;
                    /* used will be 0 (false) */

                    single = single->next;
                }
            }
        }
        if (ret == 0) {
            /* Decode SingleResponse into OcspEntry. */
            ret = DecodeSingleResponse(source, &idx,
                    dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset,
                    dataASN[OCSPRESPDATAASN_IDX_RESP].length, single);
            /* single->used set on successful decode. */
        }
    }

    /* Check if there were extensions. */
    if ((ret == 0) &&
            (dataASN[OCSPRESPDATAASN_IDX_RESPEXT].data.buffer.data != NULL)) {
        /* Get index of [1] */
        idx = dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset;
        /* Decode the response extensions. */
        if (DecodeOcspRespExtensions(source, &idx, resp, *ioIndex) < 0) {
            ret = ASN_PARSE_E;
        }
    }

    FREE_ASNGETDATA(dataASN, resp->heap);
    return ret;
#endif
}


#ifndef WOLFSSL_ASN_TEMPLATE
#ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS

static int DecodeCerts(byte* source,
                            word32* ioIndex, OcspResponse* resp, word32 size)
{
    word32 idx = *ioIndex;
    byte tag;

    WOLFSSL_ENTER("DecodeCerts");

    if (GetASNTag(source, &idx, &tag, size) < 0)
        return ASN_PARSE_E;

    if (tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
    {
        int length;

        if (GetLength(source, &idx, &length, size) < 0)
            return ASN_PARSE_E;

        if (GetSequence(source, &idx, &length, size) < 0)
            return ASN_PARSE_E;

        resp->cert = source + idx;
        resp->certSz = length;

        idx += length;
    }
    *ioIndex = idx;
    return 0;
}

#endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
#endif /* !WOLFSSL_ASN_TEMPLATE */

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for BasicOCSPResponse.
 * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
 */
static const ASNItem ocspBasicRespASN[] = {
/* SEQ          */ { 0, ASN_SEQUENCE, 1, 1, 0 },
                                            /* tbsResponseData */
/* TBS_SEQ      */     { 1, ASN_SEQUENCE, 1, 0, 0, },
                                            /* signatureAlgorithm */
/* SIGALGO      */     { 1, ASN_SEQUENCE, 1, 1, 0, },
/* SIGALGO_OID  */         { 2, ASN_OBJECT_ID, 0, 0, 0 },
/* SIGALGO_NULL */         { 2, ASN_TAG_NULL, 0, 0, 1 },
                                            /* parameters */
#ifdef WC_RSA_PSS
/* SIGALGO_PARAMS      */  { 2, ASN_SEQUENCE, 1, 0, 1 },
#endif
                                            /* signature */
/* SIGNATURE    */     { 1, ASN_BIT_STRING, 0, 0, 0 },
                                            /* certs */
/* CERTS        */     { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
/* CERTS_SEQ    */         { 2, ASN_SEQUENCE, 1, 0, 0, },
};
enum {
    OCSPBASICRESPASN_IDX_SEQ = 0,
    OCSPBASICRESPASN_IDX_TBS_SEQ,
    OCSPBASICRESPASN_IDX_SIGALGO,
    OCSPBASICRESPASN_IDX_SIGALGO_OID,
    OCSPBASICRESPASN_IDX_SIGALGO_NULL,
#ifdef WC_RSA_PSS
    OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS,
#endif
    OCSPBASICRESPASN_IDX_SIGNATURE,
    OCSPBASICRESPASN_IDX_CERTS,
    OCSPBASICRESPASN_IDX_CERTS_SEQ,
};

/* Number of items in ASN.1 template for BasicOCSPResponse. */
#define ocspBasicRespASN_Length (sizeof(ocspBasicRespASN) / sizeof(ASNItem))
#endif /* WOLFSSL_ASN_TEMPLATE */

static int DecodeBasicOcspResponse(byte* source, word32* ioIndex,
            OcspResponse* resp, word32 size, void* cm, void* heap, int noVerify)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int    length;
    word32 idx = *ioIndex;
    #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
    word32 end_index;
    #endif
    int    ret;
    int    sigLength;
    const byte*   sigParams = NULL;
    word32        sigParamsSz = 0;
    WOLFSSL_ENTER("DecodeBasicOcspResponse");
    (void)heap;

    if (GetSequence(source, &idx, &length, size) < 0)
        return ASN_PARSE_E;

    if (idx + length > size)
        return ASN_INPUT_E;
    #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
    end_index = idx + length;
    #endif

    if ((ret = DecodeResponseData(source, &idx, resp, size)) < 0)
        return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */

    /* Get the signature algorithm */
    if (GetAlgoId(source, &idx, &resp->sigOID, oidSigType, size) < 0) {
        return ASN_PARSE_E;
    }
#ifdef WC_RSA_PSS
    else if (resp->sigOID == CTC_RSASSAPSS) {
        word32 sz;
        int len;
        const byte* params;

        sz = idx;
        params = source + idx;
        if (GetSequence(source, &idx, &len, size) < 0)
            ret = ASN_PARSE_E;
        if (ret == 0) {
            idx += len;
            sigParams = params;
            sigParamsSz = idx - sz;
        }
    }
#endif

    ret = CheckBitString(source, &idx, &sigLength, size, 1, NULL);
    if (ret != 0)
        return ret;

    resp->sigSz = sigLength;
    resp->sig = source + idx;
    idx += sigLength;

    /*
     * Check the length of the BasicOcspResponse against the current index to
     * see if there are certificates, they are optional.
     */
#ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
    if (idx < end_index)
    {
        int cert_inited = 0;
#ifdef WOLFSSL_SMALL_STACK
        DecodedCert *cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
                                                  DYNAMIC_TYPE_TMP_BUFFER);
        if (cert == NULL)
            return MEMORY_E;
#else
        DecodedCert cert[1];
#endif

        do {
            if (DecodeCerts(source, &idx, resp, size) < 0) {
                ret = ASN_PARSE_E;
                break;
            }

            InitDecodedCert(cert, resp->cert, resp->certSz, heap);
            cert_inited = 1;

            /* Don't verify if we don't have access to Cert Manager. */
            ret = ParseCertRelative(cert, CERT_TYPE,
                                    noVerify ? NO_VERIFY : VERIFY_OCSP_CERT,
                                    cm);
            if (ret < 0) {
                WOLFSSL_MSG("\tOCSP Responder certificate parsing failed");
                break;
            }

#ifndef WOLFSSL_NO_OCSP_ISSUER_CHECK
            if ((cert->extExtKeyUsage & EXTKEYUSE_OCSP_SIGN) == 0) {
                if (XMEMCMP(cert->subjectHash,
                            resp->single->issuerHash, OCSP_DIGEST_SIZE) == 0) {
                    WOLFSSL_MSG("\tOCSP Response signed by issuer");
                }
                else {
                    WOLFSSL_MSG("\tOCSP Responder key usage check failed");
    #ifdef OPENSSL_EXTRA
                    resp->verifyError = OCSP_BAD_ISSUER;
    #else
                    ret = BAD_OCSP_RESPONDER;
                    break;
    #endif
                }
            }
#endif

            /* ConfirmSignature is blocking here */
            ret = ConfirmSignature(
                &cert->sigCtx,
                resp->response, resp->responseSz,
                cert->publicKey, cert->pubKeySize, cert->keyOID,
                resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
                NULL);

            if (ret != 0) {
                WOLFSSL_MSG("\tOCSP Confirm signature failed");
                ret = ASN_OCSP_CONFIRM_E;
                break;
            }
        } while(0);

        if (cert_inited)
            FreeDecodedCert(cert);
#ifdef WOLFSSL_SMALL_STACK
        XFREE(cert, NULL, DYNAMIC_TYPE_TMP_BUFFER);
#endif

        if (ret != 0)
            return ret;
    }
    else
#endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
    {
        Signer* ca;
        int sigValid = -1;

        #ifndef NO_SKID
            ca = GetCA(cm, resp->single->issuerKeyHash);
        #else
            ca = GetCA(cm, resp->single->issuerHash);
        #endif

        if (ca) {
            SignatureCtx sigCtx;
            InitSignatureCtx(&sigCtx, heap, INVALID_DEVID);

            /* ConfirmSignature is blocking here */
            sigValid = ConfirmSignature(&sigCtx, resp->response,
                resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID,
                resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
                NULL);
        }
        if (ca == NULL || sigValid != 0) {
            WOLFSSL_MSG("\tOCSP Confirm signature failed");
            return ASN_OCSP_CONFIRM_E;
        }

        (void)noVerify;
    }

    *ioIndex = idx;
    return 0;
#else
    DECL_ASNGETDATA(dataASN, ocspBasicRespASN_Length);
    int ret = 0;
    word32 idx = *ioIndex;
    const byte*   sigParams = NULL;
    word32        sigParamsSz = 0;
#ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
    #ifdef WOLFSSL_SMALL_STACK
        DecodedCert* cert = NULL;
    #else
        DecodedCert cert[1];
    #endif
    int certInit = 0;
#endif

    WOLFSSL_ENTER("DecodeBasicOcspResponse");
    (void)heap;

    CALLOC_ASNGETDATA(dataASN, ocspBasicRespASN_Length, ret, heap);

    if (ret == 0) {
        /* Set expecting signature OID. */
        GetASN_OID(&dataASN[OCSPBASICRESPASN_IDX_SIGALGO_OID], oidSigType);
        /* Decode BasicOCSPResponse. */
        ret = GetASN_Items(ocspBasicRespASN, dataASN, ocspBasicRespASN_Length,
                1, source, &idx, size);
    }
    if (ret == 0) {
        word32 dataIdx = 0;
        /* Decode the response data. */
        if (DecodeResponseData(
                GetASNItem_Addr(dataASN[OCSPBASICRESPASN_IDX_TBS_SEQ], source),
                &dataIdx, resp,
                GetASNItem_Length(dataASN[OCSPBASICRESPASN_IDX_TBS_SEQ], source)
                ) < 0) {
            ret = ASN_PARSE_E;
        }
    }
#ifdef WC_RSA_PSS
    if (ret == 0 && (dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS].tag != 0)) {
        sigParams = GetASNItem_Addr(
                dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS],
                source);
        sigParamsSz =
               GetASNItem_Length(dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS],
               source);
    }
#endif
    if (ret == 0) {
        /* Get the signature OID and signature. */
        resp->sigOID = dataASN[OCSPBASICRESPASN_IDX_SIGALGO_OID].data.oid.sum;
        GetASN_GetRef(&dataASN[OCSPBASICRESPASN_IDX_SIGNATURE], &resp->sig,
                &resp->sigSz);
    }
#ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
    if ((ret == 0) &&
            (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
        /* TODO: support more than one certificate. */
        /* Store reference to certificate BER data. */
        GetASN_GetRef(&dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ], &resp->cert,
                &resp->certSz);

        /* Allocate a certificate object to decode cert into. */
    #ifdef WOLFSSL_SMALL_STACK
        cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), heap,
                DYNAMIC_TYPE_TMP_BUFFER);
        if (cert == NULL) {
            ret = MEMORY_E;
        }
    }
    if ((ret == 0) &&
            (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
    #endif
        /* Initialize the crtificate object. */
        InitDecodedCert(cert, resp->cert, resp->certSz, heap);
        certInit = 1;
        /* Parse the certificate and don't verify if we don't have access to
         * Cert Manager. */
        ret = ParseCertRelative(cert, CERT_TYPE, noVerify ? NO_VERIFY : VERIFY,
                cm);
        if (ret < 0) {
            WOLFSSL_MSG("\tOCSP Responder certificate parsing failed");
        }
    }
    if ((ret == 0) &&
            (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
        /* TODO: ConfirmSignature is blocking here */
        /* Check the signature of the response. */
        ret = ConfirmSignature(&cert->sigCtx, resp->response, resp->responseSz,
            cert->publicKey, cert->pubKeySize, cert->keyOID, resp->sig,
            resp->sigSz, resp->sigOID, NULL, 0, NULL);
        if (ret != 0) {
            WOLFSSL_MSG("\tOCSP Confirm signature failed");
            ret = ASN_OCSP_CONFIRM_E;
        }
    }
    if ((ret == 0) &&
            (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data == NULL))
#else
    if (ret == 0)
#endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
    {
        Signer* ca;
        int sigValid = -1;

        /* Resonse didn't have a certificate - lookup CA. */
    #ifndef NO_SKID
        ca = GetCA(cm, resp->single->issuerKeyHash);
    #else
        ca = GetCA(cm, resp->single->issuerHash);
    #endif
        if (ca) {
            SignatureCtx sigCtx;

            /* Initialize he signature context. */
            InitSignatureCtx(&sigCtx, heap, INVALID_DEVID);

            /* TODO: ConfirmSignature is blocking here */
            /* Check the signature of the response CA public key. */
            sigValid = ConfirmSignature(&sigCtx, resp->response,
                resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID,
                resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
                NULL);
        }
        if ((ca == NULL) || (sigValid != 0)) {
            /* Didn't find certificate or signature verificate failed. */
            WOLFSSL_MSG("\tOCSP Confirm signature failed");
            ret = ASN_OCSP_CONFIRM_E;
        }
    }

    if (ret == 0) {
        /* Update the position to after response data. */
        *ioIndex = idx;
    }

#ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
    if (certInit) {
        FreeDecodedCert(cert);
    }
    #ifdef WOLFSSL_SMALL_STACK
    if (cert != NULL) {
        /* Dispose of certificate object. */
        XFREE(cert, heap, DYNAMIC_TYPE_TMP_BUFFER);
    }
    #endif
#endif
    FREE_ASNGETDATA(dataASN, heap);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}


void InitOcspResponse(OcspResponse* resp, OcspEntry* single, CertStatus* status,
                      byte* source, word32 inSz, void* heap)
{
    WOLFSSL_ENTER("InitOcspResponse");

    XMEMSET(status, 0, sizeof(CertStatus));
    XMEMSET(single,  0, sizeof(OcspEntry));
    XMEMSET(resp,   0, sizeof(OcspResponse));

    single->status       = status;
    resp->responseStatus = -1;
    resp->single         = single;
    resp->source         = source;
    resp->maxIdx         = inSz;
    resp->heap           = heap;
}

void FreeOcspResponse(OcspResponse* resp)
{
    OcspEntry *single, *next;

    if (resp != NULL) {
        for (single = resp->single; single; single = next) {
            next = single->next;
            if (single->isDynamic) {
                XFREE(single->status, resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
                XFREE(single, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
            }
        }
    }
}

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for OCSPResponse.
 * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
 */
static const ASNItem ocspResponseASN[] = {
                                     /* OCSPResponse ::= SEQUENCE */
/* SEQ        */ { 0, ASN_SEQUENCE, 1, 1, 0 },
                                         /* responseStatus      OCSPResponseStatus */
/* STATUS     */     { 1, ASN_ENUMERATED, 0, 0, 0, },
                                         /* responseBytes   [0] EXPLICIT ResponseBytes OPTIONAL */
/* BYTES      */     { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
                                             /* ResponseBytes ::= SEQUENCE */
/* BYTES_SEQ  */         { 2, ASN_SEQUENCE, 1, 1, 0 },
                                                /* responseType   OBJECT IDENTIFIER */
/* BYTES_TYPE */            { 3, ASN_OBJECT_ID, 0, 0, 0 },
                                                /* response       OCTET STRING */
/* BYTES_VAL  */            { 3, ASN_OCTET_STRING, 0, 0, 0 },
};
enum {
    OCSPRESPONSEASN_IDX_SEQ = 0,

    OCSPRESPONSEASN_IDX_STATUS,

    OCSPRESPONSEASN_IDX_BYTES,

    OCSPRESPONSEASN_IDX_BYTES_SEQ,

    OCSPRESPONSEASN_IDX_BYTES_TYPE,

    OCSPRESPONSEASN_IDX_BYTES_VAL,
};

/* Number of items in ASN.1 template for OCSPResponse. */
#define ocspResponseASN_Length (sizeof(ocspResponseASN) / sizeof(ASNItem))
#endif /* WOLFSSL_ASN_TEMPLATE */

int OcspResponseDecode(OcspResponse* resp, void* cm, void* heap, int noVerify)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int ret;
    int length = 0;
    word32 idx = 0;
    byte* source = resp->source;
    word32 size = resp->maxIdx;
    word32 oid;
    byte   tag;

    WOLFSSL_ENTER("OcspResponseDecode");

    /* peel the outer SEQUENCE wrapper */
    if (GetSequence(source, &idx, &length, size) < 0) {
        WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
        return ASN_PARSE_E;
    }

    /* First get the responseStatus, an ENUMERATED */
    if (GetEnumerated(source, &idx, &resp->responseStatus, size) < 0) {
        WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
        return ASN_PARSE_E;
    }

    if (resp->responseStatus != OCSP_SUCCESSFUL) {
        WOLFSSL_LEAVE("OcspResponseDecode", 0);
        return 0;
    }

    /* Next is an EXPLICIT record called ResponseBytes, OPTIONAL */
    if (idx >= size) {
        WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
        return ASN_PARSE_E;
    }
    if (GetASNTag(source, &idx, &tag, size) < 0) {
        WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
        return ASN_PARSE_E;
    }
    if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC)) {
        WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
        return ASN_PARSE_E;
    }
    if (GetLength(source, &idx, &length, size) < 0) {
        WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
        return ASN_PARSE_E;
    }

    /* Get the responseBytes SEQUENCE */
    if (GetSequence(source, &idx, &length, size) < 0) {
        WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
        return ASN_PARSE_E;
    }

    /* Check ObjectID for the resposeBytes */
    if (GetObjectId(source, &idx, &oid, oidOcspType, size) < 0) {
        WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
        return ASN_PARSE_E;
    }
    if (oid != OCSP_BASIC_OID) {
        WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
        return ASN_PARSE_E;
    }
    ret = GetOctetString(source, &idx, &length, size);
    if (ret < 0) {
        WOLFSSL_LEAVE("OcspResponseDecode", ret);
        return ret;
    }

    ret = DecodeBasicOcspResponse(source, &idx, resp, size, cm, heap, noVerify);
    if (ret < 0) {
        WOLFSSL_LEAVE("OcspResponseDecode", ret);
        return ret;
    }

    WOLFSSL_LEAVE("OcspResponseDecode", 0);
    return 0;
#else
    DECL_ASNGETDATA(dataASN, ocspResponseASN_Length);
    int ret = 0;
    word32 idx = 0, size = resp->maxIdx;
    byte* source = resp->source;
    byte status;
    byte* basic;
    word32 basicSz;

    WOLFSSL_ENTER("OcspResponseDecode");

    CALLOC_ASNGETDATA(dataASN, ocspResponseASN_Length, ret, resp->heap);

    if (ret == 0) {
        /* Set variable to put status in and expect OCSP OID. */
        GetASN_Int8Bit(&dataASN[OCSPRESPONSEASN_IDX_STATUS], &status);
        GetASN_OID(&dataASN[OCSPRESPONSEASN_IDX_BYTES_TYPE], oidOcspType);
        /* Decode OCSPResponse (and ResponseBytes). */
        ret = GetASN_Items(ocspResponseASN, dataASN, ocspResponseASN_Length, 1,
            source, &idx, size);
    }
    if (ret == 0) {
        /* Get response. */
        resp->responseStatus = status;
        if (dataASN[OCSPRESPONSEASN_IDX_BYTES_TYPE].data.oid.sum
                == OCSP_BASIC_OID) {
            /* Get reference to BasicOCSPResponse. */
            GetASN_GetRef(&dataASN[OCSPRESPONSEASN_IDX_BYTES_VAL], &basic,
                    &basicSz);
            idx = 0;
            /* Decode BasicOCSPResponse. */
            ret = DecodeBasicOcspResponse(basic, &idx, resp, basicSz, cm, heap,
                noVerify);
        }
        /* Only support BasicOCSPResponse. */
        else {
            ret = ASN_PARSE_E;
        }
    }

    FREE_ASNGETDATA(dataASN, resp->heap);
    WOLFSSL_LEAVE("OcspResponseDecode", ret);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for OCSP nonce extension.
 * RFC 6960, 4.4.1 - Nonce
 * X.509: RFC 5280, 4.1 - Basic Certificate Fields. (Extension)
 */
static const ASNItem ocspNonceExtASN[] = {
/* SEQ       */ { 0, ASN_SEQUENCE, 1, 1, 0 },
                                     /* Extension */
/* EXT       */     { 1, ASN_SEQUENCE, 1, 1, 0 },
                                        /* extnId */
/* EXT_OID   */        {2, ASN_OBJECT_ID, 0, 0, 0 },
                                        /* critcal not encoded. */
                                        /* extnValue */
/* EXT_VAL   */        {2, ASN_OCTET_STRING, 0, 1, 0 },
                                               /* nonce */
/* EXT_NONCE */            {3, ASN_OCTET_STRING, 0, 0, 0 },
};
enum {
    OCSPNONCEEXTASN_IDX_SEQ = 0,
    OCSPNONCEEXTASN_IDX_EXT,
    OCSPNONCEEXTASN_IDX_EXT_OID,
    OCSPNONCEEXTASN_IDX_EXT_VAL,
    OCSPNONCEEXTASN_IDX_EXT_NONCE,
};

/* Number of items in ASN.1 template for OCSP nonce extension. */
#define ocspNonceExtASN_Length (sizeof(ocspNonceExtASN) / sizeof(ASNItem))
#endif /* WOLFSSL_ASN_TEMPLATE */

word32 EncodeOcspRequestExtensions(OcspRequest* req, byte* output, word32 size)
{
    const byte NonceObjId[] = { 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07,
                                       0x30, 0x01, 0x02 };
#ifndef WOLFSSL_ASN_TEMPLATE
    byte seqArray[5][MAX_SEQ_SZ];
    word32 seqSz[5], totalSz = (word32)sizeof(NonceObjId);

    WOLFSSL_ENTER("SetOcspReqExtensions");

    if (!req || !output || !req->nonceSz)
        return 0;

    totalSz += req->nonceSz;
    totalSz += seqSz[0] = SetOctetString(req->nonceSz, seqArray[0]);
    totalSz += seqSz[1] = SetOctetString(req->nonceSz + seqSz[0], seqArray[1]);
    totalSz += seqSz[2] = SetObjectId(sizeof(NonceObjId), seqArray[2]);
    totalSz += seqSz[3] = SetSequence(totalSz, seqArray[3]);
    totalSz += seqSz[4] = SetSequence(totalSz, seqArray[4]);

    if (totalSz > size)
        return 0;

    totalSz = 0;

    XMEMCPY(output + totalSz, seqArray[4], seqSz[4]);
    totalSz += seqSz[4];

    XMEMCPY(output + totalSz, seqArray[3], seqSz[3]);
    totalSz += seqSz[3];

    XMEMCPY(output + totalSz, seqArray[2], seqSz[2]);
    totalSz += seqSz[2];

    XMEMCPY(output + totalSz, NonceObjId, sizeof(NonceObjId));
    totalSz += (word32)sizeof(NonceObjId);

    XMEMCPY(output + totalSz, seqArray[1], seqSz[1]);
    totalSz += seqSz[1];

    XMEMCPY(output + totalSz, seqArray[0], seqSz[0]);
    totalSz += seqSz[0];

    XMEMCPY(output + totalSz, req->nonce, req->nonceSz);
    totalSz += req->nonceSz;

    return totalSz;
#else
    int ret = 0;

    WOLFSSL_ENTER("SetOcspReqExtensions");

    /* Check request has nonce to write in extension. */
    if (req != NULL && req->nonceSz != 0) {
        DECL_ASNSETDATA(dataASN, ocspNonceExtASN_Length);
        int sz;

        CALLOC_ASNSETDATA(dataASN, ocspNonceExtASN_Length, ret, req->heap);

        /* Set nonce extension OID and nonce. */
        SetASN_Buffer(&dataASN[OCSPNONCEEXTASN_IDX_EXT_OID], NonceObjId,
                sizeof(NonceObjId));
        SetASN_Buffer(&dataASN[OCSPNONCEEXTASN_IDX_EXT_NONCE], req->nonce,
                req->nonceSz);
        /* Calculate size of nonce extension. */
        ret = SizeASN_Items(ocspNonceExtASN, dataASN, ocspNonceExtASN_Length,
                            &sz);
        /* Check buffer big enough for encoding if supplied. */
        if ((ret == 0) && (output != NULL) && (sz > (int)size)) {
            ret = BUFFER_E;
        }
        if ((ret == 0) && (output != NULL)) {
            /* Encode nonce extension. */
            SetASN_Items(ocspNonceExtASN, dataASN, ocspNonceExtASN_Length,
                         output);
        }
        if (ret == 0) {
            /* Return size of encoding. */
            ret = sz;
        }

        FREE_ASNSETDATA(dataASN, req->heap);
    }

    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}


#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for OCSPRequest.
 * RFC 6960, 4.1.1 - ASN.1 Specification of the OCSP Request
 */
static const ASNItem ocspRequestASN[] = {
                                              /* OCSPRequest */
/* SEQ               */    { 0, ASN_SEQUENCE, 1, 1, 0 },
                                                  /* tbsRequest */
/* TBS               */        { 1, ASN_SEQUENCE, 1, 1, 0 },
                                                      /* version not written - v1 */
                                                      /* requestorName not written */
                                                      /* requestList */
/* TBS_SEQ           */            { 2, ASN_SEQUENCE, 1, 1, 0 },
                                                          /* Request */
/* TBS_LIST          */                { 3, ASN_SEQUENCE, 1, 1, 0 },
                                                              /* reqCert */
/* TBS_REQ_CID       */                    { 4, ASN_SEQUENCE, 1, 1, 0 },
                                                                  /* hashAlgorithm */
/* TBS_REQ_HASH      */                        { 5, ASN_SEQUENCE, 1, 1, 0 },
/* TBS_REQ_HASH_OID  */                            { 6, ASN_OBJECT_ID, 0, 0, 0 },
                                                                  /* issuerNameHash */
/* TBS_REQ_ISSUER    */                        { 5, ASN_OCTET_STRING, 0, 0, 0 },
                                                                  /* issuerKeyHash */
/* TBS_REQ_ISSUERKEY */                        { 5, ASN_OCTET_STRING, 0, 0, 0 },
                                                                  /* serialNumber */
/* TBS_REQ_SERIAL    */                        { 5, ASN_INTEGER, 0, 0, 0 },
                                                      /* requestExtensions */
/* TBS_REQEXT        */            { 2, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 0 },
                                                  /* optionalSignature not written. */
};
enum {
    OCSPREQUESTASN_IDX_SEQ = 0,
    OCSPREQUESTASN_IDX_TBS,
    OCSPREQUESTASN_IDX_TBS_SEQ,
    OCSPREQUESTASN_IDX_TBS_LIST,
    OCSPREQUESTASN_IDX_TBS_REQ_CID,
    OCSPREQUESTASN_IDX_TBS_REQ_HASH,
    OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID,
    OCSPREQUESTASN_IDX_TBS_REQ_ISSUER,
    OCSPREQUESTASN_IDX_TBS_REQ_ISSUERKEY,
    OCSPREQUESTASN_IDX_TBS_REQ_SERIAL,
    OCSPREQUESTASN_IDX_TBS_REQEXT,
};

/* Number of items in ASN.1 template for OCSPRequest. */
#define ocspRequestASN_Length (sizeof(ocspRequestASN) / sizeof(ASNItem))
#endif

int EncodeOcspRequest(OcspRequest* req, byte* output, word32 size)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    byte seqArray[5][MAX_SEQ_SZ];
    /* The ASN.1 of the OCSP Request is an onion of sequences */
    byte algoArray[MAX_ALGO_SZ];
    byte issuerArray[MAX_ENCODED_DIG_SZ];
    byte issuerKeyArray[MAX_ENCODED_DIG_SZ];
    byte snArray[MAX_SN_SZ];
    byte extArray[MAX_OCSP_EXT_SZ];
    word32 seqSz[5], algoSz, issuerSz, issuerKeySz, extSz, totalSz;
    int i, snSz;

    WOLFSSL_ENTER("EncodeOcspRequest");

#ifdef NO_SHA
    algoSz = SetAlgoID(SHA256h, algoArray, oidHashType, 0);
#else
    algoSz = SetAlgoID(SHAh, algoArray, oidHashType, 0);
#endif

    issuerSz    = SetDigest(req->issuerHash,    KEYID_SIZE,    issuerArray);
    issuerKeySz = SetDigest(req->issuerKeyHash, KEYID_SIZE,    issuerKeyArray);
    snSz        = SetSerialNumber(req->serial,  req->serialSz, snArray,
                                                          MAX_SN_SZ, MAX_SN_SZ);
    extSz       = 0;

    if (snSz < 0)
        return snSz;

    if (req->nonceSz) {
        /* TLS Extensions use this function too - put extensions after
         * ASN.1: Context Specific [2].
         */
        extSz = EncodeOcspRequestExtensions(req, extArray + 2,
                                            OCSP_NONCE_EXT_SZ);
        extSz += SetExplicit(2, extSz, extArray);
    }

    totalSz = algoSz + issuerSz + issuerKeySz + snSz;
    for (i = 4; i >= 0; i--) {
        seqSz[i] = SetSequence(totalSz, seqArray[i]);
        totalSz += seqSz[i];
        if (i == 2) totalSz += extSz;
    }

    if (output == NULL)
        return totalSz;
    if (totalSz > size)
        return BUFFER_E;

    totalSz = 0;
    for (i = 0; i < 5; i++) {
        XMEMCPY(output + totalSz, seqArray[i], seqSz[i]);
        totalSz += seqSz[i];
    }

    XMEMCPY(output + totalSz, algoArray, algoSz);
    totalSz += algoSz;

    XMEMCPY(output + totalSz, issuerArray, issuerSz);
    totalSz += issuerSz;

    XMEMCPY(output + totalSz, issuerKeyArray, issuerKeySz);
    totalSz += issuerKeySz;

    XMEMCPY(output + totalSz, snArray, snSz);
    totalSz += snSz;

    if (extSz != 0) {
        XMEMCPY(output + totalSz, extArray, extSz);
        totalSz += extSz;
    }

    return totalSz;
#else
    DECL_ASNSETDATA(dataASN, ocspRequestASN_Length);
    word32 extSz = 0;
    int sz = 0;
    int ret = 0;

    WOLFSSL_ENTER("EncodeOcspRequest");

    CALLOC_ASNSETDATA(dataASN, ocspRequestASN_Length, ret, req->heap);

    if (ret == 0) {
        /* Set OID of hash algorithm use on issuer and key. */
    #ifdef NO_SHA
        SetASN_OID(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID], SHA256h,
                oidHashType);
    #else
        SetASN_OID(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID], SHAh,
                oidHashType);
    #endif
        /* Set issuer, issuer key hash and serial number of certificate being
         * checked. */
        SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_ISSUER],
                req->issuerHash, KEYID_SIZE);
        SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_ISSUERKEY],
                req->issuerKeyHash, KEYID_SIZE);
        SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_SERIAL],
                req->serial, req->serialSz);
        /* Only extension to write is nonce - check if one to encode. */
        if (req->nonceSz) {
            /* Get size of extensions and leave space for them in encoding. */
            ret = extSz = EncodeOcspRequestExtensions(req, NULL, 0);
            SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT], NULL, extSz);
            if (ret > 0) {
                ret = 0;
            }
        }
        else {
            /* Don't write out extensions. */
            dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT].noOut = 1;
        }
    }
    if (ret == 0) {
        /* Calculate size of encoding. */
        ret = SizeASN_Items(ocspRequestASN, dataASN, ocspRequestASN_Length,
                &sz);
    }
    /* Check buffer big enough for encoding if supplied. */
    if ((ret == 0) && (output != NULL) && (sz > (int)size)) {
        ret = BUFFER_E;
    }
    if ((ret == 0) && (output != NULL)) {
        /* Encode OCSPRequest. */
        SetASN_Items(ocspRequestASN, dataASN, ocspRequestASN_Length, output);
        if (req->nonceSz) {
            /* Encode extensions into space provided. */
            ret = EncodeOcspRequestExtensions(req,
                (byte*)dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT].data.buffer.data,
                extSz);
            if (ret > 0) {
                ret = 0;
            }
        }
    }

    if (ret == 0) {
        /* Return size of encoding. */
        ret = sz;
    }

    FREE_ASNSETDATA(dataASN, req->heap);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}


int InitOcspRequest(OcspRequest* req, DecodedCert* cert, byte useNonce,
                                                                     void* heap)
{
    int ret;

    WOLFSSL_ENTER("InitOcspRequest");

    if (req == NULL)
        return BAD_FUNC_ARG;

    XMEMSET(req, 0, sizeof(OcspRequest));
    req->heap = heap;

    if (cert) {
        XMEMCPY(req->issuerHash,    cert->issuerHash,    KEYID_SIZE);
        XMEMCPY(req->issuerKeyHash, cert->issuerKeyHash, KEYID_SIZE);

        req->serial = (byte*)XMALLOC(cert->serialSz, req->heap,
                                                     DYNAMIC_TYPE_OCSP_REQUEST);
        if (req->serial == NULL)
            return MEMORY_E;

        XMEMCPY(req->serial, cert->serial, cert->serialSz);
        req->serialSz = cert->serialSz;

        if (cert->extAuthInfoSz != 0 && cert->extAuthInfo != NULL) {
            req->url = (byte*)XMALLOC(cert->extAuthInfoSz + 1, req->heap,
                                                     DYNAMIC_TYPE_OCSP_REQUEST);
            if (req->url == NULL) {
                XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP);
                req->serial = NULL;
                return MEMORY_E;
            }

            XMEMCPY(req->url, cert->extAuthInfo, cert->extAuthInfoSz);
            req->urlSz = cert->extAuthInfoSz;
            req->url[req->urlSz] = 0;
        }
    }

    if (useNonce) {
        WC_RNG rng;

    #ifndef HAVE_FIPS
        ret = wc_InitRng_ex(&rng, req->heap, INVALID_DEVID);
    #else
        ret = wc_InitRng(&rng);
    #endif
        if (ret != 0) {
            WOLFSSL_MSG("\tCannot initialize RNG. Skipping the OCSP Nonce.");
        } else {
            if (wc_RNG_GenerateBlock(&rng, req->nonce, MAX_OCSP_NONCE_SZ) != 0)
                WOLFSSL_MSG("\tCannot run RNG. Skipping the OCSP Nonce.");
            else
                req->nonceSz = MAX_OCSP_NONCE_SZ;

            wc_FreeRng(&rng);
        }
    }

    return 0;
}

void FreeOcspRequest(OcspRequest* req)
{
    WOLFSSL_ENTER("FreeOcspRequest");

    if (req) {
        if (req->serial)
            XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
        req->serial = NULL;

#ifdef OPENSSL_EXTRA
        if (req->serialInt) {
            if (req->serialInt->isDynamic) {
                XFREE(req->serialInt->data, NULL, DYNAMIC_TYPE_OPENSSL);
            }
            XFREE(req->serialInt, NULL, DYNAMIC_TYPE_OPENSSL);
        }
        req->serialInt = NULL;
#endif

        if (req->url)
            XFREE(req->url, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
        req->url = NULL;
    }
}


int CompareOcspReqResp(OcspRequest* req, OcspResponse* resp)
{
    int cmp = -1; /* default as not matching, cmp gets set on each check */
    OcspEntry *single, *next, *prev = NULL, *top;

    WOLFSSL_ENTER("CompareOcspReqResp");

    if (req == NULL) {
        WOLFSSL_MSG("\tReq missing");
        return -1;
    }
    if (resp == NULL || resp->single == NULL) {
        WOLFSSL_MSG("\tResp missing");
        return 1;
    }

    /* Nonces are not critical. The responder may not necessarily add
     * the nonce to the response. */
    if (req->nonceSz && resp->nonce != NULL
#ifndef WOLFSSL_FORCE_OCSP_NONCE_CHECK
            && resp->nonceSz != 0
#endif
    ) {
        cmp = req->nonceSz - resp->nonceSz;
        if (cmp != 0) {
            WOLFSSL_MSG("\tnonceSz mismatch");
            return cmp;
        }

        cmp = XMEMCMP(req->nonce, resp->nonce, req->nonceSz);
        if (cmp != 0) {
            WOLFSSL_MSG("\tnonce mismatch");
            return cmp;
        }
    }

    /* match based on found status and return */
    for (single = resp->single; single; single = next) {
        cmp = req->serialSz - single->status->serialSz;
        if (cmp == 0) {
            cmp = XMEMCMP(req->serial, single->status->serial, req->serialSz)
               || XMEMCMP(req->issuerHash, single->issuerHash, OCSP_DIGEST_SIZE)
               || XMEMCMP(req->issuerKeyHash, single->issuerKeyHash, OCSP_DIGEST_SIZE);
            if (cmp == 0) {
                /* match found */
                if (resp->single != single && prev) {
                    /* move to top of list */
                    top = resp->single;
                    resp->single = single;
                    prev->next = single->next;
                    single->next = top;
                }
                break;
            }
        }
        next = single->next;
        prev = single;
    }

    if (cmp != 0) {
        WOLFSSL_MSG("\trequest and response mismatch");
        return cmp;
    }

    return 0;
}

#endif /* HAVE_OCSP */


#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for certificate name hash. */
static const ASNItem nameHashASN[] = {
/* OID  */ { 0, ASN_OBJECT_ID, 0, 0, 1 },
/* NAME */ { 0, ASN_SEQUENCE, 1, 0, 0 },
};
enum {
    NAMEHASHASN_IDX_OID = 0,
    NAMEHASHASN_IDX_NAME
};

/* Number of items in ASN.1 template for certificate name hash. */
#define nameHashASN_Length (sizeof(nameHashASN) / sizeof(ASNItem))
#endif /* WOLFSSL_ASN_TEMPLATE */

/* store WC_SHA hash of NAME */
int GetNameHash(const byte* source, word32* idx, byte* hash, int maxIdx)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int    length;  /* length of all distinguished names */
    int    ret;
    word32 dummy;
    byte   tag;

    WOLFSSL_ENTER("GetNameHash");

    dummy = *idx;
    if (GetASNTag(source, &dummy, &tag, (word32)maxIdx) == 0 &&
            tag == ASN_OBJECT_ID) {
        WOLFSSL_MSG("Trying optional prefix...");

        if (GetLength(source, idx, &length, (word32)maxIdx) < 0)
            return ASN_PARSE_E;

        *idx += (word32)length;
        WOLFSSL_MSG("Got optional prefix");
    }

    /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
     * calculated over the entire DER encoding of the Name field, including
     * the tag and length. */
    dummy = *idx;
    if (GetSequence(source, idx, &length, (word32)maxIdx) < 0)
        return ASN_PARSE_E;

    ret = CalcHashId(source + dummy, (word32)length + *idx - dummy, hash);

    *idx += (word32)length;

    return ret;
#else
    ASNGetData dataASN[nameHashASN_Length];
    int ret;

    XMEMSET(dataASN, 0, sizeof(dataASN));
    /* Ignore the OID even when present. */
    GetASN_OID(&dataASN[NAMEHASHASN_IDX_OID], oidIgnoreType);
    /* Decode certificate name. */
    ret = GetASN_Items(nameHashASN, dataASN, nameHashASN_Length, 0, source, idx,
           (word32)maxIdx);
    if (ret == 0) {
        /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
         * calculated over the entire DER encoding of the Name field, including
         * the tag and length. */
        /* Calculate hash of complete name including SEQUENCE. */
        ret = CalcHashId(
                GetASNItem_Addr(dataASN[NAMEHASHASN_IDX_NAME], source),
                GetASNItem_Length(dataASN[NAMEHASHASN_IDX_NAME], source),
                hash);
    }

    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

#if defined(HAVE_CRL) && !defined(WOLFCRYPT_ONLY)

#ifdef OPENSSL_EXTRA
static char* GetNameFromDer(const byte* source, int sz)
{
    char* out;

    out = (char*)XMALLOC(sz, NULL, DYNAMIC_TYPE_OPENSSL);
    if (out == NULL) {
        WOLFSSL_MSG("Name malloc failed");
        return NULL;
    }

    XMEMCPY(out, source, sz);

    return out;
}
#endif

/* initialize decoded CRL */
void InitDecodedCRL(DecodedCRL* dcrl, void* heap)
{
    WOLFSSL_MSG("InitDecodedCRL");

    XMEMSET(dcrl, 0, sizeof(DecodedCRL));
    dcrl->heap = heap;
#ifdef WOLFSSL_HEAP_TEST
    dcrl->heap = (void*)WOLFSSL_HEAP_TEST;
#endif
}


/* free decoded CRL resources */
void FreeDecodedCRL(DecodedCRL* dcrl)
{
    RevokedCert* tmp = dcrl->certs;

    WOLFSSL_MSG("FreeDecodedCRL");

    while(tmp) {
        RevokedCert* next = tmp->next;
        XFREE(tmp, dcrl->heap, DYNAMIC_TYPE_REVOKED);
        tmp = next;
    }
#ifdef OPENSSL_EXTRA
    if (dcrl->issuer != NULL)
        XFREE(dcrl->issuer, NULL, DYNAMIC_TYPE_OPENSSL);
#endif
}


#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for revoked certificates.
 * X.509: RFC 5280, 5.1 - CRL Fields
 */
static const ASNItem revokedASN[] = {
/* SEQ      */    { 0, ASN_SEQUENCE, 1, 1, 0 },
                                     /* userCertificate    CertificateSerialNumber */
/* CERT     */        { 1, ASN_INTEGER, 0, 0, 0 },
                                     /* revocationDate     Time */
/* TIME_UTC */        { 1, ASN_UTC_TIME, 0, 0, 2 },
/* TIME_GT  */        { 1, ASN_GENERALIZED_TIME, 0, 0, 2 },
                                     /* crlEntryExensions  Extensions */
/* TIME_EXT */        { 1, ASN_SEQUENCE, 1, 0, 1 },
};
enum {
    REVOKEDASN_IDX_SEQ = 0,
    REVOKEDASN_IDX_CERT,
    REVOKEDASN_IDX_TIME_UTC,
    REVOKEDASN_IDX_TIME_GT,
    REVOKEDASN_IDX_TIME_EXT,
};

/* Number of items in ASN.1 template for revoked certificates. */
#define revokedASN_Length (sizeof(revokedASN) / sizeof(ASNItem))
#endif

/* Get Revoked Cert list, 0 on success */
static int GetRevoked(RevokedCert* rcert, const byte* buff, word32* idx,
                      DecodedCRL* dcrl, int maxIdx)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int ret;
    int len;
    word32 end;
    RevokedCert* rc;
#ifdef CRL_STATIC_REVOKED_LIST
    int totalCerts = 0;
#endif
    WOLFSSL_ENTER("GetRevoked");

    if (GetSequence(buff, idx, &len, maxIdx) < 0)
        return ASN_PARSE_E;

    end = *idx + len;

#ifdef CRL_STATIC_REVOKED_LIST
    totalCerts = dcrl->totalCerts;

    if (totalCerts >= CRL_MAX_REVOKED_CERTS) {
        return MEMORY_E;
    }

    rc = &rcert[totalCerts];
    ret = wc_GetSerialNumber(buff, idx, rc->serialNumber, &rc->serialSz,maxIdx);
    if (ret < 0) {
        WOLFSSL_MSG("wc_GetSerialNumber error");
        return ret;
    }
#else

    rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), dcrl->heap,
                                                          DYNAMIC_TYPE_REVOKED);
    if (rc == NULL) {
        WOLFSSL_MSG("Alloc Revoked Cert failed");
        return MEMORY_E;
    }
    ret = wc_GetSerialNumber(buff, idx, rc->serialNumber, &rc->serialSz,maxIdx);
    if (ret < 0) {
        WOLFSSL_MSG("wc_GetSerialNumber error");
        XFREE(rc, dcrl->heap, DYNAMIC_TYPE_REVOKED);
        return ret;
    }
    /* add to list */
    rc->next = dcrl->certs;
    dcrl->certs = rc;

    (void)rcert;
#endif /* CRL_STATIC_REVOKED_LIST */
    dcrl->totalCerts++;
    /* get date */
#ifndef NO_ASN_TIME
    ret = GetBasicDate(buff, idx, rc->revDate, &rc->revDateFormat, maxIdx);
    if (ret < 0) {
        WOLFSSL_MSG("Expecting Date");
        return ret;
    }
#endif
    /* skip extensions */
    *idx = end;

    return 0;
#else
    DECL_ASNGETDATA(dataASN, revokedASN_Length);
    int ret = 0;
    word32 serialSz = EXTERNAL_SERIAL_SIZE;
    word32 revDateSz = MAX_DATE_SIZE;
    RevokedCert* rc;
#ifdef CRL_STATIC_REVOKED_LIST
    int totalCerts = dcrl->totalCerts;

    if (totalCerts >= CRL_MAX_REVOKED_CERTS) {
        return MEMORY_E;
    }

    rc = &rcert[totalCerts];

#else
    /* Allocate a new revoked certificate object. */
    rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), dcrl->heap,
            DYNAMIC_TYPE_CRL);
    if (rc == NULL) {
        ret = MEMORY_E;
    }
#endif /* CRL_STATIC_REVOKED_LIST */

    CALLOC_ASNGETDATA(dataASN, revokedASN_Length, ret, dcrl->heap);

    if (ret == 0) {
        /* Set buffer to place serial number into. */
        GetASN_Buffer(&dataASN[REVOKEDASN_IDX_CERT], rc->serialNumber,
                &serialSz);
        /* Set buffer to store revocation date. */
        GetASN_Buffer(&dataASN[REVOKEDASN_IDX_TIME_UTC], rc->revDate,
                &revDateSz);
        GetASN_Buffer(&dataASN[REVOKEDASN_IDX_TIME_GT], rc->revDate,
                &revDateSz);
        /* Decode the Revoked */
        ret = GetASN_Items(revokedASN, dataASN, revokedASN_Length, 1, buff, idx,
                maxIdx);
    }
    if (ret == 0) {
        /* Store size of serial number. */
        rc->serialSz = serialSz;
        rc->revDateFormat = (dataASN[REVOKEDASN_IDX_TIME_UTC].tag != 0)
                ? dataASN[REVOKEDASN_IDX_TIME_UTC].tag
                : dataASN[REVOKEDASN_IDX_TIME_GT].tag;

        /* TODO: use extensions, only v2 */
        /* Add revoked certificate to chain. */
#ifndef CRL_STATIC_REVOKED_LIST
        rc->next = dcrl->certs;
        dcrl->certs = rc;
#endif
        dcrl->totalCerts++;
    }

    FREE_ASNGETDATA(dataASN, dcrl->heap);
#ifndef CRL_STATIC_REVOKED_LIST
    if ((ret != 0) && (rc != NULL)) {
        XFREE(rc, dcrl->heap, DYNAMIC_TYPE_CRL);
    }
    (void)rcert;
#endif
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

#ifdef WOLFSSL_ASN_TEMPLATE
/* Parse the revoked certificates of a CRL.
 *
 * @param [in] dcrl    Decoded CRL object.
 * @param [in] buff    Buffer holding CRL.
 * @param [in] idx     Index into buffer of revoked certificates.
 * @param [in] maxIdx  Maximum index of revoked cartificates data.
 * @return  0 on success.
 * @return  ASN_PARSE_E on failure.
 */
static int ParseCRL_RevokedCerts(RevokedCert* rcert, DecodedCRL* dcrl,
                                 const byte* buff, word32 idx, word32 maxIdx)
{
    int ret = 0;

    /* Parse each revoked cerificate. */
    while ((ret == 0) && (idx < maxIdx)) {
        /* Parse a revoked certificate. */
        if (GetRevoked(rcert, buff, &idx, dcrl, maxIdx) < 0) {
            ret = ASN_PARSE_E;
        }
    }

    return ret;
}
#endif /* WOLFSSL_ASN_TEMPLATE */

#ifndef WOLFSSL_ASN_TEMPLATE
/* Get CRL Signature, 0 on success */
static int GetCRL_Signature(const byte* source, word32* idx, DecodedCRL* dcrl,
                            int maxIdx)
{
    int    length;
    int    ret;

    WOLFSSL_ENTER("GetCRL_Signature");

    ret = CheckBitString(source, idx, &length, maxIdx, 1, NULL);
    if (ret != 0)
        return ret;
    dcrl->sigLength = length;

    dcrl->signature = (byte*)&source[*idx];
    *idx += dcrl->sigLength;

    return 0;
}
#endif /* !WOLFSSL_ASN_TEMPLATE */

int VerifyCRL_Signature(SignatureCtx* sigCtx, const byte* toBeSigned,
                        word32 tbsSz, const byte* signature, word32 sigSz,
                        word32 signatureOID, Signer *ca, void* heap)
{
    /* try to confirm/verify signature */
#ifndef IGNORE_KEY_EXTENSIONS
    if ((ca->keyUsage & KEYUSE_CRL_SIGN) == 0) {
        WOLFSSL_MSG("CA cannot sign CRLs");
        WOLFSSL_ERROR_VERBOSE(ASN_CRL_NO_SIGNER_E);
        return ASN_CRL_NO_SIGNER_E;
    }
#endif /* IGNORE_KEY_EXTENSIONS */

    InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
    if (ConfirmSignature(sigCtx, toBeSigned, tbsSz, ca->publicKey,
                         ca->pubKeySize, ca->keyOID, signature, sigSz,
                         signatureOID, NULL, 0, NULL) != 0) {
        WOLFSSL_MSG("CRL Confirm signature failed");
        WOLFSSL_ERROR_VERBOSE(ASN_CRL_CONFIRM_E);
        return ASN_CRL_CONFIRM_E;
    }

    return 0;
}

#ifdef WOLFSSL_ASN_TEMPLATE
/* Find the signer for the CRL and verify the signature.
 *
 * @param [in] dcrl  Decoded CRL object.
 * @param [in] buff  Buffer holding CRL.
 * @param [in] cm    Certificate manager object.
 * @return  0 on success.
 * @return  ASN_CRL_NO_SIGNER_E when no signer found.
 * @return  ASN_CRL_CONFIRM_E when signature did not verify.
 */
static int PaseCRL_CheckSignature(DecodedCRL* dcrl, const byte* buff, void* cm)
{
    int ret = 0;
    Signer* ca = NULL;
    SignatureCtx sigCtx;

    /* OpenSSL doesn't add skid by default for CRLs cause firefox chokes.
     * If experiencing issues uncomment NO_SKID define in CRL section of
     * wolfssl/wolfcrypt/settings.h */
#ifndef NO_SKID
    if (dcrl->extAuthKeyIdSet) {
        /* more unique than issuerHash */
        ca = GetCA(cm, dcrl->extAuthKeyId);
    }
    /* Check issuerHash matched CA's subjectNameHash. */
    if ((ca != NULL) && (XMEMCMP(dcrl->issuerHash, ca->subjectNameHash,
                                 KEYID_SIZE) != 0)) {
        ca = NULL;
    }
    if (ca == NULL) {
        ca = GetCAByName(cm, dcrl->issuerHash); /* last resort */
        /* If AKID is available then this CA doesn't have the public
         * key required */
        if (ca && dcrl->extAuthKeyIdSet) {
            WOLFSSL_MSG("CA SKID doesn't match AKID");
            ca = NULL;
        }
    }
#else
    ca = GetCA(cm, dcrl->issuerHash);
#endif /* !NO_SKID */
    WOLFSSL_MSG("About to verify CRL signature");

    if (ca == NULL) {
        WOLFSSL_MSG("Did NOT find CRL issuer CA");
        ret = ASN_CRL_NO_SIGNER_E;
        WOLFSSL_ERROR_VERBOSE(ret);
    }

    if (ret == 0) {
        WOLFSSL_MSG("Found CRL issuer CA");
        /* Verify CRL signature with CA. */
        ret = VerifyCRL_Signature(&sigCtx, buff + dcrl->certBegin,
           dcrl->sigIndex - dcrl->certBegin, dcrl->signature, dcrl->sigLength,
           dcrl->signatureOID, ca, dcrl->heap);
    }

    return ret;
}
#endif

#ifndef WOLFSSL_ASN_TEMPLATE
static int ParseCRL_CertList(RevokedCert* rcert, DecodedCRL* dcrl,
                           const byte* buf,word32* inOutIdx, int sz, int verify)
{
    word32 oid, dateIdx, idx, checkIdx;
    int length;
#ifdef WOLFSSL_NO_CRL_NEXT_DATE
    int doNextDate = 1;
#endif
    byte tag;

    if (dcrl == NULL || inOutIdx == NULL || buf == NULL) {
        return BAD_FUNC_ARG;
    }

    /* may have version */
    idx = *inOutIdx;

    checkIdx = idx;
    if (GetASNTag(buf, &checkIdx, &tag, sz) == 0 && tag == ASN_INTEGER) {
        if (GetMyVersion(buf, &idx, &dcrl->version, sz) < 0)
            return ASN_PARSE_E;
        dcrl->version++;
    }

    if (GetAlgoId(buf, &idx, &oid, oidIgnoreType, sz) < 0)
        return ASN_PARSE_E;

    checkIdx = idx;
    if (GetSequence(buf, &checkIdx, &length, sz) < 0) {
        return ASN_PARSE_E;
    }
#ifdef OPENSSL_EXTRA
    dcrl->issuerSz = length + (checkIdx - idx);
    dcrl->issuer   = (byte*)GetNameFromDer(buf + idx, (int)dcrl->issuerSz);
#endif

    if (GetNameHash(buf, &idx, dcrl->issuerHash, sz) < 0)
        return ASN_PARSE_E;

    if (GetBasicDate(buf, &idx, dcrl->lastDate, &dcrl->lastDateFormat, sz) < 0)
        return ASN_PARSE_E;

    dateIdx = idx;

    if (GetBasicDate(buf, &idx, dcrl->nextDate, &dcrl->nextDateFormat, sz) < 0)
    {
#ifndef WOLFSSL_NO_CRL_NEXT_DATE
        (void)dateIdx;
        return ASN_PARSE_E;
#else
        dcrl->nextDateFormat = ASN_OTHER_TYPE;  /* skip flag */
        doNextDate = 0;
        idx = dateIdx;
#endif
    }

#ifdef WOLFSSL_NO_CRL_NEXT_DATE
    if (doNextDate)
#endif
    {
#ifndef NO_ASN_TIME
        if (verify != NO_VERIFY &&
                !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
            WOLFSSL_MSG("CRL after date is no longer valid");
            WOLFSSL_ERROR_VERBOSE(CRL_CERT_DATE_ERR);
            return CRL_CERT_DATE_ERR;
        }
#else
        (void)verify;
#endif
    }

    checkIdx = idx;
    if (idx != dcrl->sigIndex &&
           GetASNTag(buf, &checkIdx, &tag, sz) == 0 && tag != CRL_EXTENSIONS) {

        int len;

        if (GetSequence(buf, &idx, &len, sz) < 0)
            return ASN_PARSE_E;
        len += idx;

        while (idx < (word32)len) {
            if (GetRevoked(rcert, buf, &idx, dcrl, len) < 0)
                return ASN_PARSE_E;
        }
    }

    *inOutIdx = idx;

    return 0;
}
#endif /* !WOLFSSL_ASN_TEMPLATE */


#ifndef NO_SKID
static int ParseCRL_AuthKeyIdExt(const byte* input, int sz, DecodedCRL* dcrl)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    word32 idx = 0;
    int length = 0, ret = 0;
    byte tag;

    WOLFSSL_ENTER("ParseCRL_AuthKeyIdExt");

    if (GetSequence(input, &idx, &length, sz) < 0) {
        WOLFSSL_MSG("\tfail: should be a SEQUENCE");
        return ASN_PARSE_E;
    }

    if (GetASNTag(input, &idx, &tag, sz) < 0) {
        return ASN_PARSE_E;
    }

    if (tag != (ASN_CONTEXT_SPECIFIC | 0)) {
        WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
        return 0;
    }

    if (GetLength(input, &idx, &length, sz) <= 0) {
        WOLFSSL_MSG("\tfail: extension data length");
        return ASN_PARSE_E;
    }

    dcrl->extAuthKeyIdSet = 1;
    /* Get the hash or hash of the hash if wrong size. */
    ret = GetHashId(input + idx, length, dcrl->extAuthKeyId);

    return ret;
#else
    DECL_ASNGETDATA(dataASN, authKeyIdASN_Length);
    int ret = 0;
    word32 idx = 0;

    WOLFSSL_ENTER("ParseCRL_AuthKeyIdExt");

    CALLOC_ASNGETDATA(dataASN, authKeyIdASN_Length, ret, dcrl->heap);

    if (ret == 0) {
        /* Parse an authority key identifier. */
        ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length, 1, input,
                           &idx, sz);
    }
    if (ret == 0) {
        /* Key id is optional. */
        if (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data == NULL) {
            WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
        }
        else {
            /* Get the hash or hash of the hash if wrong size. */
            ret = GetHashId(dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
                dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
                dcrl->extAuthKeyId);
        }
    }

    FREE_ASNGETDATA(dataASN, dcrl->heap);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}
#endif


#ifndef WOLFSSL_ASN_TEMPLATE
static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf,
        word32* inOutIdx, word32 sz)
{
    int length;
    word32 idx;
    word32 ext_bound; /* boundary index for the sequence of extensions */
    word32 oid;
    byte tag;

    WOLFSSL_ENTER("ParseCRL_Extensions");
    (void)dcrl;

    if (inOutIdx == NULL)
        return BAD_FUNC_ARG;

    idx = *inOutIdx;

    /* CRL Extensions are optional */
    if ((idx + 1) > sz)
        return 0;

    /* CRL Extensions are optional */
    if (GetASNTag(buf, &idx, &tag, sz) < 0)
        return 0;

    /* CRL Extensions are optional */
    if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
        return 0;

    if (GetLength(buf, &idx, &length, sz) < 0)
        return ASN_PARSE_E;

    if (GetSequence(buf, &idx, &length, sz) < 0)
        return ASN_PARSE_E;

    ext_bound = idx + length;

    while (idx < (word32)ext_bound) {
        word32 localIdx;
        int ret;

        if (GetSequence(buf, &idx, &length, sz) < 0) {
            WOLFSSL_MSG("\tfail: should be a SEQUENCE");
            return ASN_PARSE_E;
        }

        oid = 0;
        if (GetObjectId(buf, &idx, &oid, oidCrlExtType, sz) < 0) {
            WOLFSSL_MSG("\tfail: OBJECT ID");
            return ASN_PARSE_E;
        }

        /* check for critical flag */
        if ((idx + 1) > (word32)sz) {
            WOLFSSL_MSG("\tfail: malformed buffer");
            return BUFFER_E;
        }

        localIdx = idx;
        if (GetASNTag(buf, &localIdx, &tag, sz) == 0 && tag == ASN_BOOLEAN) {
            WOLFSSL_MSG("\tfound optional critical flag, moving past");
            ret = GetBoolean(buf, &idx, sz);
            if (ret < 0)
                return ret;
        }

        ret = GetOctetString(buf, &idx, &length, sz);
        if (ret < 0)
            return ret;

        if (oid == AUTH_KEY_OID) {
        #ifndef NO_SKID
            ret = ParseCRL_AuthKeyIdExt(buf + idx, length, dcrl);
            if (ret < 0) {
                WOLFSSL_MSG("\tcouldn't parse AuthKeyId extension");
                return ret;
            }
        #endif
        }
        else if (oid == CRL_NUMBER_OID) {
            localIdx = idx;
            if (GetASNTag(buf, &localIdx, &tag, sz) == 0 &&
                    tag == ASN_INTEGER) {
                ret = GetASNInt(buf, &idx, &length, sz);
                if (ret < 0) {
                    WOLFSSL_MSG("\tcouldn't parse CRL number extension");
                    return ret;
                }
                else {
                    if (length > 1) {
                        int    i;
                    #ifdef WOLFSSL_SMALL_STACK
                        mp_int* m = (mp_int*)XMALLOC(sizeof(*m), NULL,
                                DYNAMIC_TYPE_BIGINT);
                        if (m == NULL) {
                            return MEMORY_E;
                        }
                    #else
                        mp_int m[1];
                    #endif

                        if (mp_init(m) != MP_OKAY) {
                            ret = MP_INIT_E;
                        }

                        if (ret == 0)
                            ret = mp_read_unsigned_bin(m, buf + idx, length);
                        if (ret != MP_OKAY)
                            ret = BUFFER_E;

                        if (ret == 0) {
                            dcrl->crlNumber = 0;
                            for (i = 0; i < (int)(*m).used; ++i) {
                                if (i > (CHAR_BIT *
                                         (int)sizeof(word32) / DIGIT_BIT)) {
                                    break;
                                }
                                dcrl->crlNumber |= ((word32)(*m).dp[i]) <<
                                    (DIGIT_BIT * i);
                            }
                        }

                        mp_free(m);
                    #ifdef WOLFSSL_SMALL_STACK
                        XFREE(m, NULL, DYNAMIC_TYPE_BIGINT);
                    #endif

                        if (ret != 0)
                            return ret;
                    }
                    else if (length == 1) {
                        dcrl->crlNumber = buf[idx];
                    }
                }
            }
        }

        idx += length;
    }

    *inOutIdx = idx;

    return 0;
}
#else
/* Parse the extensions of a CRL.
 *
 * @param [in] dcrl    Decoded CRL object.
 * @param [in] buff    Buffer holding CRL.
 * @param [in] idx     Index into buffer of extensions.
 * @param [in] maxIdx  Maximum index of extension data.
 * @return  0 on success.
 * @return  ASN_PARSE_E on failure.
 */
static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf, word32 idx,
        word32 maxIdx)
{
    DECL_ASNGETDATA(dataASN, certExtASN_Length);
    int ret = 0;

    ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, dcrl->heap);

    while ((ret == 0) && (idx < maxIdx)) {
        byte critical = 0;

        /* Clear dynamic data. */
        XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
        /* Ensure OID is an extention type. */
        GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
        /* Set criticality variable. */
        GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
        /* Parse extension wrapper. */
        ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, buf, &idx,
                maxIdx);
        if (ret == 0) {
            /* OID in extension. */
            word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
            /* Length of extension data. */
            int length = dataASN[CERTEXTASN_IDX_VAL].length;

            if (oid == AUTH_KEY_OID) {
            #ifndef NO_SKID
                /* Parse Authority Key Id extesion.
                 * idx is at start of OCTET_STRING data. */
                ret = ParseCRL_AuthKeyIdExt(buf + idx, length, dcrl);
                if (ret != 0) {
                    WOLFSSL_MSG("\tcouldn't parse AuthKeyId extension");
                }
            #endif
            }
            /* TODO: Parse CRL Number extension */
            /* TODO: check criticality */
            /* Move index on to next extension. */
            idx += length;
        }
    }

    if (ret < 0) {
        ret = ASN_PARSE_E;
    }

    FREE_ASNGETDATA(dataASN, dcrl->heap);

    return ret;
}
#endif /* !WOLFSSL_ASN_TEMPLATE */


#ifdef WOLFSSL_ASN_TEMPLATE
/* ASN.1 template for a CRL- CertificateList.
 * X.509: RFC 5280, 5.1 - CRL Fields
 */
static const ASNItem crlASN[] = {
                                       /* CertificateList */
/* SEQ                */    { 0, ASN_SEQUENCE, 1, 1, 0 },
                                           /* tbsCertList */
/* TBS                */        { 1, ASN_SEQUENCE, 1, 1, 0 },
                                               /* version     Version OPTIONAL if present must be v2 */
/* TBS_VER            */            { 2, ASN_INTEGER, 0, 0, 1 },
                                               /* signature */
/* TBS_SIGALGO        */            { 2, ASN_SEQUENCE, 1, 1, 0 },
/* TBS_SIGALGO_OID    */                { 3, ASN_OBJECT_ID, 0, 0, 0 },
/* TBS_SIGALGO_NULL   */                { 3, ASN_TAG_NULL, 0, 0, 1 },
                                               /* issuer */
/* TBS_ISSUER         */            { 2, ASN_SEQUENCE, 1, 0, 0 },
                                               /* thisUpdate */
/* TBS_THISUPDATE_UTC */            { 2, ASN_UTC_TIME, 0, 0, 2 },
/* TBS_THISUPDATE_GT  */            { 2, ASN_GENERALIZED_TIME, 0, 0, 2 },
                                               /* nextUpdate */
/* TBS_NEXTUPDATE_UTC */            { 2, ASN_UTC_TIME, 0, 0, 3 },
/* TBS_NEXTUPDATE_GT  */            { 2, ASN_GENERALIZED_TIME, 0, 0, 3 },
                                               /* revokedCertificates */
/* TBS_REVOKEDCERTS   */            { 2, ASN_SEQUENCE, 1, 0, 1 },
                                               /* crlExtensions */
/* TBS_EXT            */            { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
/* TBS_EXT_SEQ        */                { 3, ASN_SEQUENCE, 1, 0, 0 },
                                           /* signatureAlgorithm */
/* SIGALGO            */        { 1, ASN_SEQUENCE, 1, 1, 0 },
/* SIGALGO_OID        */            { 2, ASN_OBJECT_ID, 0, 0, 0 },
/* SIGALGO_NULL       */            { 2, ASN_TAG_NULL, 0, 0, 1 },
                                           /* signatureValue */
/* SIGNATURE          */        { 1, ASN_BIT_STRING, 0, 0, 0 },
};
enum {
    CRLASN_IDX_SEQ = 0,
    CRLASN_IDX_TBS,
    CRLASN_IDX_TBS_VER,
    CRLASN_IDX_TBS_SIGALGO,
    CRLASN_IDX_TBS_SIGALGO_OID,
    CRLASN_IDX_TBS_SIGALGO_NULL,
    CRLASN_IDX_TBS_ISSUER,
    CRLASN_IDX_TBS_THISUPDATE_UTC,
    CRLASN_IDX_TBS_THISUPDATE_GT,
    CRLASN_IDX_TBS_NEXTUPDATE_UTC,
    CRLASN_IDX_TBS_NEXTUPDATE_GT,
    CRLASN_IDX_TBS_REVOKEDCERTS,
    CRLASN_IDX_TBS_EXT,
    CRLASN_IDX_TBS_EXT_SEQ,
    CRLASN_IDX_SIGALGO,
    CRLASN_IDX_SIGALGO_OID,
    CRLASN_IDX_SIGALGO_NULL,
    CRLASN_IDX_SIGNATURE,
};

/* Number of items in ASN.1 template for a CRL- CertificateList. */
#define crlASN_Length (sizeof(crlASN) / sizeof(ASNItem))
#endif

/* parse crl buffer into decoded state, 0 on success */
int ParseCRL(RevokedCert* rcert, DecodedCRL* dcrl, const byte* buff, word32 sz,
             int verify, void* cm)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    Signer*      ca = NULL;
    SignatureCtx sigCtx;
    int          ret = 0;
    int          len;
    word32       idx = 0;

    WOLFSSL_MSG("ParseCRL");

    /* raw crl hash */
    /* hash here if needed for optimized comparisons
     * wc_Sha sha;
     * wc_InitSha(&sha);
     * wc_ShaUpdate(&sha, buff, sz);
     * wc_ShaFinal(&sha, dcrl->crlHash); */

    if (GetSequence(buff, &idx, &len, sz) < 0)
        return ASN_PARSE_E;

    dcrl->certBegin = idx;
    /* Normalize sz for the length inside the outer sequence. */
    sz = len + idx;

    if (GetSequence(buff, &idx, &len, sz) < 0)
        return ASN_PARSE_E;
    dcrl->sigIndex = len + idx;

    if (ParseCRL_CertList(rcert, dcrl, buff, &idx, dcrl->sigIndex, verify) < 0)
        return ASN_PARSE_E;

    if (ParseCRL_Extensions(dcrl, buff, &idx, dcrl->sigIndex) < 0)
        return ASN_PARSE_E;

    idx = dcrl->sigIndex;

    if (GetAlgoId(buff, &idx, &dcrl->signatureOID, oidSigType, sz) < 0)
        return ASN_PARSE_E;

    if (GetCRL_Signature(buff, &idx, dcrl, sz) < 0)
        return ASN_PARSE_E;

    /* openssl doesn't add skid by default for CRLs cause firefox chokes
       if experiencing issues uncomment NO_SKID define in CRL section of
       wolfssl/wolfcrypt/settings.h */
#ifndef NO_SKID
    if (dcrl->extAuthKeyIdSet) {
        ca = GetCA(cm, dcrl->extAuthKeyId); /* more unique than issuerHash */
    }
    if (ca != NULL && XMEMCMP(dcrl->issuerHash, ca->subjectNameHash,
                KEYID_SIZE) != 0) {
        ca = NULL;
    }
    if (ca == NULL) {
        ca = GetCAByName(cm, dcrl->issuerHash); /* last resort */
        /* If AKID is available then this CA doesn't have the public
         * key required */
        if (ca && dcrl->extAuthKeyIdSet) {
            WOLFSSL_MSG("CA SKID doesn't match AKID");
            ca = NULL;
        }
    }
#else
    ca = GetCA(cm, dcrl->issuerHash);
#endif /* !NO_SKID */
    WOLFSSL_MSG("About to verify CRL signature");

    if (ca == NULL) {
        WOLFSSL_MSG("Did NOT find CRL issuer CA");
        ret = ASN_CRL_NO_SIGNER_E;
        WOLFSSL_ERROR_VERBOSE(ret);
        goto end;
    }

    WOLFSSL_MSG("Found CRL issuer CA");
    ret = VerifyCRL_Signature(&sigCtx, buff + dcrl->certBegin,
           dcrl->sigIndex - dcrl->certBegin, dcrl->signature, dcrl->sigLength,
           dcrl->signatureOID, ca, dcrl->heap);

end:
    return ret;
#else
    DECL_ASNGETDATA(dataASN, crlASN_Length);
    int ret = 0;
    /* Default version - v1 = 0 */
    byte version = 0;
    word32 idx = 0;
    /* Size of buffer for date. */
    word32 lastDateSz = MAX_DATE_SIZE;
    word32 nextDateSz = MAX_DATE_SIZE;

    /* When NO_ASN_TIME is defined, verify not used. */
    (void)verify;

    WOLFSSL_MSG("ParseCRL");

    CALLOC_ASNGETDATA(dataASN, crlASN_Length, ret, dcrl->heap);

    if (ret == 0) {
        /* Set variable to store version. */
        GetASN_Int8Bit(&dataASN[CRLASN_IDX_TBS_VER], &version);
        /* Set expecting signature OID. */
        GetASN_OID(&dataASN[CRLASN_IDX_TBS_SIGALGO_OID], oidSigType);
        /* Set buffer to put last and next date into. */
        GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC], dcrl->lastDate,
                &lastDateSz);
        GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_THISUPDATE_GT], dcrl->lastDate,
                &lastDateSz);
        GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC], dcrl->nextDate,
                &nextDateSz);
        GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_NEXTUPDATE_GT], dcrl->nextDate,
                &nextDateSz);
        /* Set expecting signature OID. */
        GetASN_OID(&dataASN[CRLASN_IDX_SIGALGO_OID], oidSigType);
        /* Decode the CRL. */
        ret = GetASN_Items(crlASN, dataASN, crlASN_Length, 1, buff, &idx, sz);
    }
    /* Version must be v2 = 1 if present. */
    if ((ret == 0) && (dataASN[CRLASN_IDX_TBS_VER].tag != 0) &&
            (version != 1)) {
        ret = ASN_PARSE_E;
    }
    /* Check minimum size of last date. */
    if ((ret == 0) && (lastDateSz < MIN_DATE_SIZE)) {
        ret = ASN_PARSE_E;
    }
    /* Check minimum size of next date. */
    if ((ret == 0) && (nextDateSz < MIN_DATE_SIZE)) {
        ret = ASN_PARSE_E;
    }
    /* 'signatureAlgorithm' OID must be the same as 'signature' OID. */
    if ((ret == 0) && (dataASN[CRLASN_IDX_SIGALGO_OID].data.oid.sum !=
            dataASN[CRLASN_IDX_TBS_SIGALGO_OID].data.oid.sum)) {
        ret = ASN_PARSE_E;
    }
    if (ret == 0) {
        /* Store version */
        dcrl->version = ++version;
        /* Store offset of to be signed part. */
        dcrl->certBegin = dataASN[CRLASN_IDX_TBS].offset;
        /* Store index of signature. */
        dcrl->sigIndex = dataASN[CRLASN_IDX_SIGALGO].offset;
        /* Store address and length of signature data. */
        GetASN_GetRef(&dataASN[CRLASN_IDX_SIGNATURE], &dcrl->signature,
                &dcrl->sigLength);
        /* Get the signature OID. */
        dcrl->signatureOID = dataASN[CRLASN_IDX_SIGALGO_OID].data.oid.sum;
        /* Get the format/tag of the last and next date. */
        dcrl->lastDateFormat = (dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC].tag != 0)
                ? dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC].tag
                : dataASN[CRLASN_IDX_TBS_THISUPDATE_GT].tag;
        dcrl->nextDateFormat = (dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC].tag != 0)
                ? dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC].tag
                : dataASN[CRLASN_IDX_TBS_NEXTUPDATE_GT].tag;
    #ifndef NO_ASN_TIME
        if (dcrl->nextDateFormat != 0) {
            /* Next date was set, so validate it. */
            if (verify != NO_VERIFY &&
                 !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
                WOLFSSL_MSG("CRL after date is no longer valid");
                ret = CRL_CERT_DATE_ERR;
                WOLFSSL_ERROR_VERBOSE(ret);
            }
        }
    }
    if (ret == 0) {
    #endif
    #ifdef OPENSSL_EXTRA
        /* Parse and store the issuer name. */
        dcrl->issuerSz = GetASNItem_Length(dataASN[CRLASN_IDX_TBS_ISSUER],
                            buff);
        dcrl->issuer   = (byte*)GetNameFromDer((byte*)GetASNItem_Addr(
                            dataASN[CRLASN_IDX_TBS_ISSUER], buff),
                            (int)dcrl->issuerSz);
    #endif
        /* Calculate the Hash id from the issuer name. */
        ret = CalcHashId(GetASNItem_Addr(dataASN[CRLASN_IDX_TBS_ISSUER], buff),
                GetASNItem_Length(dataASN[CRLASN_IDX_TBS_ISSUER], buff),
                dcrl->issuerHash);
        if (ret < 0) {
            ret = ASN_PARSE_E;
        }
    }

    if ((ret == 0) && (dataASN[CRLASN_IDX_TBS_REVOKEDCERTS].tag != 0)) {
        /* Parse revoked cerificates - starting after SEQUENCE OF. */
        ret = ParseCRL_RevokedCerts(rcert, dcrl, buff,
            GetASNItem_DataIdx(dataASN[CRLASN_IDX_TBS_REVOKEDCERTS], buff),
            GetASNItem_EndIdx(dataASN[CRLASN_IDX_TBS_REVOKEDCERTS], buff));
    }
    if (ret == 0) {
        /* Parse the extensions - starting after SEQUENCE OF. */
        ret = ParseCRL_Extensions(dcrl, buff,
            GetASNItem_DataIdx(dataASN[CRLASN_IDX_TBS_EXT_SEQ], buff),
            GetASNItem_EndIdx(dataASN[CRLASN_IDX_TBS_EXT_SEQ], buff));
    }
    if (ret == 0) {
        /* Find signer and verify signature. */
        ret = PaseCRL_CheckSignature(dcrl, buff, cm);
    }

    FREE_ASNGETDATA(dataASN, dcrl->heap);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

#endif /* HAVE_CRL */



#ifdef WOLFSSL_CERT_PIV

#ifdef WOLFSSL_ASN_TEMPLATE
/* Template for PIV. */
static const ASNItem pivASN[] = {
/* CERT        */ { 0, ASN_PIV_CERT, 0, 0, 0 },
/* NONCE       */ { 0, ASN_PIV_NONCE, 0, 0, 1 },
/* SIGNEDNONCE */ { 0, ASN_PIV_SIGNED_NONCE, 0, 0, 1 },
};
enum {
    PIVASN_IDX_CERT = 0,
    PIVASN_IDX_NONCE,
    PIVASN_IDX_SIGNEDNONCE,
};

#define pivASN_Length (sizeof(pivASN) / sizeof(ASNItem))

static const ASNItem pivCertASN[] = {
                          /* 0x53 = 0x40 | 0x13 */
/* CERT */ { 1, ASN_APPLICATION | 0x13, 0, 1, 0 },
                               /* 0x70 = 0x40 | 0x10 + 0x20 (CONSTRUCTED) */
/* X509 */      { 2, ASN_APPLICATION | 0x10, 1, 0, 0 },
                               /* 0x71 = 0x40 | 0x11 + 0x20 (CONSTRUCTED) */
/* INFO */      { 2, ASN_APPLICATION | 0x11, 1, 0, 1 },
                               /* 0xFE = 0xC0 | 0x1E + 0x20 (CONSTRUCTED) */
/* ERR */      { 2, ASN_PRIVATE | 0x1e, 1, 0, 1 },
};
enum {
    PIVCERTASN_IDX_CERT,
    PIVCERTASN_IDX_X509,
    PIVCERTASN_IDX_INFO,
    PIVCERTASN_IDX_ERR,
};

#define pivCertASN_Length (sizeof(pivCertASN) / sizeof(ASNItem))
#endif

int wc_ParseCertPIV(wc_CertPIV* piv, const byte* buf, word32 totalSz)
{
#ifndef WOLFSSL_ASN_TEMPLATE
    int length = 0;
    word32 idx = 0;

    WOLFSSL_ENTER("wc_ParseCertPIV");

    if (piv == NULL || buf == NULL || totalSz == 0)
        return BAD_FUNC_ARG;

    XMEMSET(piv, 0, sizeof(wc_CertPIV));

    /* Detect Identiv PIV (with 0x0A, 0x0B and 0x0C sections) */
    /* Certificate (0A 82 05FA) */
    if (GetASNHeader(buf, ASN_PIV_CERT, &idx, &length, totalSz) >= 0) {
        /* Identiv Type PIV card */
        piv->isIdentiv = 1;

        piv->cert =   &buf[idx];
        piv->certSz = length;
        idx += length;

        /* Nonce (0B 14) */
        if (GetASNHeader(buf, ASN_PIV_NONCE, &idx, &length, totalSz) >= 0) {
            piv->nonce =   &buf[idx];
            piv->nonceSz = length;
            idx += length;
        }

        /* Signed Nonce (0C 82 0100) */
        if (GetASNHeader(buf, ASN_PIV_SIGNED_NONCE, &idx, &length, totalSz) >= 0) {
            piv->signedNonce =   &buf[idx];
            piv->signedNonceSz = length;
        }

        idx = 0;
        buf = piv->cert;
        totalSz = piv->certSz;
    }

    /* Certificate Buffer Total Size (53 82 05F6) */
    if (GetASNHeader(buf, ASN_APPLICATION | ASN_PRINTABLE_STRING, &idx,
                                                   &length, totalSz) < 0) {
        return ASN_PARSE_E;
    }
    /* PIV Certificate (70 82 05ED) */
    if (GetASNHeader(buf, ASN_PIV_TAG_CERT, &idx, &length,
                                                         totalSz) < 0) {
        return ASN_PARSE_E;
    }

    /* Capture certificate buffer pointer and length */
    piv->cert =   &buf[idx];
    piv->certSz = length;
    idx += length;

    /* PIV Certificate Info (71 01 00) */
    if (GetASNHeader(buf, ASN_PIV_TAG_CERT_INFO, &idx, &length,
                                                        totalSz) >= 0) {
        if (length >= 1) {
            piv->compression = (buf[idx] & ASN_PIV_CERT_INFO_COMPRESSED);
            piv->isX509 =      ((buf[idx] & ASN_PIV_CERT_INFO_ISX509) != 0);
        }
        idx += length;
    }

    /* PIV Error Detection (FE 00) */
    if (GetASNHeader(buf, ASN_PIV_TAG_ERR_DET, &idx, &length,
                                                        totalSz) >= 0) {
        piv->certErrDet =   &buf[idx];
        piv->certErrDetSz = length;
        idx += length;
    }

    return 0;
#else
    /* pivCertASN_Length is longer than pivASN_Length */
    DECL_ASNGETDATA(dataASN, pivCertASN_Length);
    int ret = 0;
    word32 idx;
    byte info;

    WOLFSSL_ENTER("wc_ParseCertPIV");

    ALLOC_ASNGETDATA(dataASN, pivCertASN_Length, ret, NULL);

    if (ret == 0) {
        /* Clear dynamic data. */
        XMEMSET(dataASN, 0, sizeof(*dataASN) * pivASN_Length);
        /* Start parsing from start of buffer. */
        idx = 0;
        /* Parse Identiv wrapper. */
        ret = GetASN_Items(pivASN, dataASN, pivASN_Length, 1, buf, &idx,
                totalSz);
        if (ret == 0) {
            /* Identiv wrapper found. */
            piv->isIdentiv = 1;
            /* Get nonce reference. */
            if (dataASN[PIVASN_IDX_NONCE].tag != 0) {
                GetASN_GetConstRef(&dataASN[PIVASN_IDX_NONCE], &piv->nonce,
                        &piv->nonceSz);
            }
            /* Get signedNonce reference. */
            if (dataASN[PIVASN_IDX_SIGNEDNONCE].tag != 0) {
                GetASN_GetConstRef(&dataASN[PIVASN_IDX_SIGNEDNONCE],
                        &piv->signedNonce, &piv->signedNonceSz);
            }
            /* Get the certificate data for parsing. */
            GetASN_GetConstRef(&dataASN[PIVASN_IDX_CERT], &buf, &totalSz);
        }
        ret = 0;
    }
    if (ret == 0) {
        /* Clear dynamic data and set variable to put cert info into. */
        XMEMSET(dataASN, 0, sizeof(*dataASN) * pivCertASN_Length);
        GetASN_Int8Bit(&dataASN[PIVCERTASN_IDX_INFO], &info);
        /* Start parsing from start of buffer. */
        idx = 0;
        /* Parse PIV cetificate data. */
        ret = GetASN_Items(pivCertASN, dataASN, pivCertASN_Length, 1, buf, &idx,
                totalSz);
        if (ret == 0) {
            /* Get X.509 certificate reference. */
            GetASN_GetConstRef(&dataASN[PIVCERTASN_IDX_X509], &piv->cert,
                    &piv->certSz);
            /* Set the certificate info if available. */
            if (dataASN[PIVCERTASN_IDX_INFO].tag != 0) {
                /* Bits 1 and 2 are compression. */
                piv->compression = info & ASN_PIV_CERT_INFO_COMPRESSED;
                /* Bits 3 is X509 flag. */
                piv->isX509 = ((info & ASN_PIV_CERT_INFO_ISX509) != 0);
            }
            /* Get X.509 certificate error detection reference. */
            GetASN_GetConstRef(&dataASN[PIVCERTASN_IDX_ERR], &piv->certErrDet,
                     &piv->certErrDetSz);
        }
        ret = 0;
    }

    FREE_ASNGETDATA(dataASN, NULL);
    return ret;
#endif /* WOLFSSL_ASN_TEMPLATE */
}

#endif /* WOLFSSL_CERT_PIV */



#ifdef HAVE_SMIME

/*****************************************************************************
* wc_MIME_parse_headers - Reads the char array in and parses out MIME headers
* and parameters into headers.  Will continue until in has no more content.
*
* RETURNS:
* returns zero on success, non-zero on error.
*/
int wc_MIME_parse_headers(char* in, int inLen, MimeHdr** headers)
{
    MimeHdr* nextHdr = NULL;
    MimeHdr* curHdr = NULL;
    MimeParam* nextParam = NULL;
    size_t start = 0;
    size_t end = 0;
    char* nameAttr = NULL;
    char* bodyVal = NULL;
    MimeTypes mimeType = MIME_HDR;
    MimeStatus mimeStatus = MIME_NAMEATTR;
    int ret = -1;
    size_t pos = 0;
    size_t lineLen = 0;
    char* curLine = NULL;
    char* ptr = NULL;

    if (in == NULL || inLen <= 0 || in[inLen] != '\0' || headers == NULL) {
        ret = BAD_FUNC_ARG;
        goto error;
    }
    nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL, DYNAMIC_TYPE_PKCS7);
    nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
                                    DYNAMIC_TYPE_PKCS7);
    if (nextHdr == NULL || nextParam == NULL) {
        ret = MEMORY_E;
        goto error;
    }
    XMEMSET(nextHdr, 0, sizeof(MimeHdr));
    XMEMSET(nextParam, 0, sizeof(MimeParam));

    curLine = XSTRTOK(in, "\r\n", &ptr);
    if (curLine == NULL) {
        ret = ASN_PARSE_E;
        goto error;
    }

    while (curLine != NULL) {
        /* Leftover from previous line, add params to previous header. */
        if (curLine[0] == ' ' && curHdr) {
            mimeType = MIME_PARAM;
        }
        else {
            mimeType = MIME_HDR;
        }
        start = 0;
        lineLen = XSTRLEN(curLine);
        if (lineLen == 0) {
            ret = BAD_FUNC_ARG;
            goto error;
        }

        for (pos = 0; pos < lineLen; pos++) {
            char cur = curLine[pos];

            if (mimeStatus == MIME_NAMEATTR && ((cur == ':' &&
                mimeType == MIME_HDR) || (cur == '=' &&
                mimeType == MIME_PARAM)) && pos >= 1) {
                mimeStatus = MIME_BODYVAL;
                end = pos-1;
                if (nameAttr != NULL)
                    XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7);
                ret = wc_MIME_header_strip(curLine, &nameAttr, start, end);
                if (ret) {
                    goto error;
                }
                start = pos+1;
            }
            else if (mimeStatus == MIME_BODYVAL && cur == ';' && pos >= 1) {
                end = pos-1;
                if (bodyVal != NULL)
                    XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7);
                ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
                if (ret) {
                    goto error;
                }
                if (mimeType == MIME_HDR) {
                    nextHdr->name = nameAttr;
                    nameAttr = NULL;
                    nextHdr->body = bodyVal;
                    bodyVal = NULL;
                    nextHdr->next = curHdr;
                    curHdr = nextHdr;
                    nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
                                                DYNAMIC_TYPE_PKCS7);
                    if (nextHdr == NULL) {
                        ret = MEMORY_E;
                        goto error;
                    }
                    XMEMSET(nextHdr, 0, sizeof(MimeHdr));
                }
                else {
                    nextParam->attribute = nameAttr;
                    nameAttr = NULL;
                    nextParam->value = bodyVal;
                    bodyVal = NULL;
                    nextParam->next = curHdr->params;
                    curHdr->params = nextParam;
                    nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
                                                    DYNAMIC_TYPE_PKCS7);
                    if (nextParam == NULL) {
                        ret = MEMORY_E;
                        goto error;
                    }
                    XMEMSET(nextParam, 0, sizeof(MimeParam));
                }
                mimeType = MIME_PARAM;
                mimeStatus = MIME_NAMEATTR;
                start = pos+1;
            }
        }

        end = lineLen-1;
        /* Omit newline characters. */
        while ((curLine[end] == '\r' || curLine[end] == '\n') && end > 0) {
            end--;
        }
        if (end >= start && mimeStatus == MIME_BODYVAL) {
            ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
            if (ret) {
                goto error;
            }
            if (mimeType == MIME_HDR) {
                nextHdr->name = nameAttr;
                nameAttr = NULL;
                nextHdr->body = bodyVal;
                bodyVal = NULL;
                nextHdr->next = curHdr;
                curHdr = nextHdr;
                nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
                                            DYNAMIC_TYPE_PKCS7);
                if (nextHdr == NULL) {
                    ret = MEMORY_E;
                    goto error;
                }
                XMEMSET(nextHdr, 0, sizeof(MimeHdr));
            } else {
                nextParam->attribute = nameAttr;
                nameAttr = NULL;
                nextParam->value = bodyVal;
                bodyVal = NULL;
                nextParam->next = curHdr->params;
                curHdr->params = nextParam;
                nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
                                                DYNAMIC_TYPE_PKCS7);
                if (nextParam == NULL) {
                    ret = MEMORY_E;
                    goto error;
                }
                XMEMSET(nextParam, 0, sizeof(MimeParam));
            }
        }

        curLine = XSTRTOK(NULL, "\r\n", &ptr);
        mimeStatus = MIME_NAMEATTR;
    }

    *headers = curHdr;
    ret = 0; /* success if at this point */

error:
    if (ret != 0)
        wc_MIME_free_hdrs(curHdr);
    wc_MIME_free_hdrs(nextHdr);
    if (nameAttr != NULL)
        XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7);
    if (bodyVal != NULL)
        XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7);
    XFREE(nextParam, NULL, DYNAMIC_TYPE_PKCS7);

    return ret;
}

/*****************************************************************************
* wc_MIME_header_strip - Reads the string in from indices start to end, strips
* out disallowed/separator characters and places the rest into *out.
*
* RETURNS:
* returns zero on success, non-zero on error.
*/
int wc_MIME_header_strip(char* in, char** out, size_t start, size_t end)
{
    size_t inPos = start;
    size_t outPos = 0;
    size_t inLen = 0;

    if (end < start || in == NULL || out == NULL) {
        return BAD_FUNC_ARG;
    }

    inLen = XSTRLEN(in);
    if (start > inLen || end > inLen) {
        return BAD_FUNC_ARG;
    }

    *out = (char*)XMALLOC(((end-start)+2)*sizeof(char), NULL,
                          DYNAMIC_TYPE_PKCS7);
    if (*out == NULL) {
        return MEMORY_E;
    }

    while (inPos <= end) {
        if (in[inPos] >= MIME_HEADER_ASCII_MIN && in[inPos] <=
            MIME_HEADER_ASCII_MAX && in[inPos] != ';' && in[inPos] != '\"') {
            (*out)[outPos] = in[inPos];
            outPos++;
        }
        inPos++;
    }
    (*out)[outPos] = '\0';

    return 0;
}

/*****************************************************************************
* wc_MIME_find_header_name - Searches through all given headers until a header with
* a name matching the provided name is found.
*
* RETURNS:
* returns a pointer to the found header, if no match was found, returns NULL.
*/
MimeHdr* wc_MIME_find_header_name(const char* name, MimeHdr* header)
{
    while (header) {
        if (!XSTRCMP(name, header->name)) {
            return header;
        }
        header = header->next;
    }

    return header;
}

/*****************************************************************************
* wc_MIME_find_param_attr - Searches through all parameters until a parameter
* with a attribute matching the provided attribute is found.
*
* RETURNS:
* returns a pointer to the found parameter, if no match was found,
* returns NULL.
*/
MimeParam* wc_MIME_find_param_attr(const char* attribute,
                                    MimeParam* param)
{
    while (param) {
        if (!XSTRCMP(attribute, param->attribute)) {
            return param;
        }
        param = param->next;
    }

    return param;
}

/*****************************************************************************
* wc_MIME_single_canonicalize - Canonicalize a line by converting the trailing
* line ending to CRLF.
*
* line - input line to canonicalize
* len  - length of line in chars on input, length of output array on return
*
* RETURNS:
* returns a pointer to a canonicalized line on success, NULL on error.
*/
char* wc_MIME_single_canonicalize(const char* line, word32* len)
{
    size_t end = 0;
    char* canonLine = NULL;

    if (line == NULL || len == NULL || *len == 0) {
        return NULL;
    }

    end = *len;
    while (end >= 1 && ((line[end-1] == '\r') || (line[end-1] == '\n'))) {
        end--;
    }

    /* Need 2 chars for \r\n and 1 for EOL */
    canonLine = (char*)XMALLOC((end+3)*sizeof(char), NULL, DYNAMIC_TYPE_PKCS7);
    if (canonLine == NULL) {
        return NULL;
    }

    XMEMCPY(canonLine, line, end);
    canonLine[end] = '\r';
    canonLine[end+1] = '\n';
    canonLine[end+2] = '\0';
    *len = (word32)(end + 3);

    return canonLine;
}

/*****************************************************************************
* wc_MIME_free_hdrs - Frees all MIME headers, parameters and strings starting from
* the provided header pointer.
*
* RETURNS:
* returns zero on success, non-zero on error.
*/
int wc_MIME_free_hdrs(MimeHdr* head)
{
    MimeHdr* curHdr = NULL;
    MimeParam* curParam = NULL;

    while (head) {
        while (head->params) {
            curParam = head->params;
            head->params = head->params->next;
            XFREE(curParam->attribute, NULL, DYNAMIC_TYPE_PKCS7);
            XFREE(curParam->value, NULL, DYNAMIC_TYPE_PKCS7);
            XFREE(curParam, NULL, DYNAMIC_TYPE_PKCS7);
        }
        curHdr = head;
        head = head->next;
        XFREE(curHdr->name, NULL, DYNAMIC_TYPE_PKCS7);
        XFREE(curHdr->body, NULL, DYNAMIC_TYPE_PKCS7);
        XFREE(curHdr, NULL, DYNAMIC_TYPE_PKCS7);
    }

    return 0;
}

#endif /* HAVE_SMIME */


#undef ERROR_OUT


#ifdef WOLFSSL_ASN_PRINT

/*******************************************************************************
 * ASN.1 Parsing and Printing Implemenation
 ******************************************************************************/

/* Initialize ASN.1 print options.
 *
 * @param [in, out] opts  ASN.1 options for printing.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when asn1 is NULL.
 */
int wc_Asn1PrintOptions_Init(Asn1PrintOptions* opts)
{
    int ret = 0;

    if (opts == NULL) {
        ret = BAD_FUNC_ARG;
    }
    else {
        XMEMSET(opts, 0, sizeof(*opts));
    }

    return ret;
}

/* Set a print option into Asn1PrintOptions object.
 *
 * @param [in, out] opts  ASN.1 options for printing.
 * @param [in]      opt   Option to set value of.
 * @param [in]      val   Value to set for option.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when asn1 is NULL.
 * @return  BAD_FUNC_ARG when val is out of range for option.
 */
int wc_Asn1PrintOptions_Set(Asn1PrintOptions* opts, enum Asn1PrintOpt opt,
    word32 val)
{
    int ret = 0;

    /* Validate parameters. */
    if (opts == NULL) {
        ret = BAD_FUNC_ARG;
    }

    if (ret == 0) {
        switch (opt) {
        /* Offset into DER/BER data to start decoding from. */
        case ASN1_PRINT_OPT_OFFSET:
            opts->offset = val;
            break;
        /* Length of DER/BER encoding to parse. */
        case ASN1_PRINT_OPT_LENGTH:
            opts->length = val;
            break;
        /* Number of spaces to indent for each change in depth. */
        case ASN1_PRINT_OPT_INDENT:
            /* Only 4 bits allowed for value. */
            if (val >= (1 << 4)) {
                ret = BAD_FUNC_ARG;
            }
            else {
                opts->indent = (word8)val;
            }
            break;
        /* Draw branches instead of indenting. */
        case ASN1_PRINT_OPT_DRAW_BRANCH:
            /* Boolean value. */
            opts->draw_branch = (val > 0);
            break;
        /* Show raw data of primitive types as octets. */
        case ASN1_PRINT_OPT_SHOW_DATA:
            /* Boolean value. */
            opts->show_data = (val > 0);
            break;
        /* Show header data as octets. */
        case ASN1_PRINT_OPT_SHOW_HEADER_DATA:
            /* Boolean value. */
            opts->show_header_data = (val > 0);
            break;
        /* Show the wolfSSL OID value for OBJECT_ID. */
        case ASN1_PRINT_OPT_SHOW_OID:
            /* Boolean value. */
            opts->show_oid = (val > 0);
            break;
        /* Don't show text representations of primitive types. */
        case ASN1_PRINT_OPT_SHOW_NO_TEXT:
            /* Boolean value. */
            opts->show_no_text = (val > 0);
            break;
        /* Don't show dump text representations of primitive types. */
        case ASN1_PRINT_OPT_SHOW_NO_DUMP_TEXT:
            /* Boolean value. */
            opts->show_no_dump_text = (val > 0);
            break;
        }
    }

    return ret;
}

/* Initialize an ASN.1 parse object.
 *
 * @param [in, out] asn1  ASN.1 parse object.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when asn1 is NULL.
 */
int wc_Asn1_Init(Asn1* asn1)
{
    int ret = 0;

    if (asn1 == NULL) {
        ret = BAD_FUNC_ARG;
    }
    else {
        XMEMSET(asn1, 0, sizeof(*asn1));
        asn1->file = XBADFILE;
    }

    return ret;
}

/* Set the file to use when printing.
 *
 * @param [in, out] asn1  ASN.1 parse object.
 * @param [in]      file  File to print to.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when asn1 is NULL.
 * @return  BAD_FUNC_ARG when file is XBADFILE.
 */
int wc_Asn1_SetFile(Asn1* asn1, XFILE file)
{
    int ret = 0;

    if ((asn1 == NULL) || (file == XBADFILE)) {
        ret = BAD_FUNC_ARG;
    }
    else {
        asn1->file = file;
    }

    return ret;
}

/* Maximum OID dotted form size. */
#define ASN1_OID_DOTTED_MAX_SZ         16

/* Print OID in dotted form or as hex bytes.
 *
 * @param [in]  file        File pointer to write to.
 * @param [in]  oid         OBJECT_ID data.
 * @param [in]  oid_len     Length of OBJECT_ID data.
 */
static void PrintObjectIdNum(XFILE file, unsigned char* oid, word32 len)
{
    word16 dotted_nums[ASN1_OID_DOTTED_MAX_SZ];
    word32 num = ASN1_OID_DOTTED_MAX_SZ;
    word32 i;

    /* Decode OBJECT_ID into dotted form array. */
    if (DecodeObjectId(oid, len, dotted_nums, &num) == 0) {
        /* Print out each number of dotted form. */
        for (i = 0; i < num; i++) {
            XFPRINTF(file, "%d", dotted_nums[i]);
            /* Add separetor. */
            if (i < num - 1) {
                XFPRINTF(file, ".");
            }
        }
    }
    else {
        /* Print out bytes as we couldn't decode. */
        for (i = 0; i < len; i++) {
            XFPRINTF(file, "%02x", oid[i]);
            /* Add separetor. */
            if (i < len - 1) {
                XFPRINTF(file, ":");
            }
        }
    }
}

/* OID value to name mapping. */
typedef struct OidName {
    /* wolfSSL OID value. */
    word32 oid;
    /* Long name to print when OID seen. */
    const char* name;
} OidName;

/* Extra OID to name mappings. */
static const OidName extraOids[] = {
    { 0x005c, "commonName" },
    { 0x005d, "surname" },
    { 0x005e, "serialNumber" },
    { 0x005f, "countryName" },
    { 0x0060, "localityName" },
    { 0x0061, "stateOrProvinceName" },
    { 0x0062, "streetAddress" },
    { 0x0063, "organizationName" },
    { 0x0064, "organizationUnitName" },
    { 0x0065, "title" },
    { 0x0086, "certificateExtension" },
    { 0x028d, "emailAddress" },
    { 0x0293, "challengePassword" },
    { 0x029a, "extensionReq" },
};
/* Length of table of extra OID to name mappings. */
#define EXTRA_OIDS_LEN   ((int)(sizeof(extraOids) / sizeof(*extraOids)))

/* Convert OID value to long name.
 *
 * @param [in]  oid   OID value.
 * @param [out] name  Long name for OID when known.
 * @return  1 when OID known.
 * @return  0 when OID not known.
 */
static int Oid2LongName(word32 oid, const char** name)
{
    int ret = 0;
    int i;

    /* Step through each entry in table. */
    for (i = 0; i < EXTRA_OIDS_LEN; i++) {
        if (extraOids[i].oid == oid) {
            /* Return the name associated with the OID value. */
            *name = extraOids[i].name;
            ret = 1;
            break;
        }
    }

    return ret;
}

/* Print the text version of the OBJECT_ID.
 *
 * @param [in] asn1  ASN.1 parse object.
 * @param [in] opts  ASN.1 options for printing.
 */
static void PrintObjectIdText(Asn1* asn1, Asn1PrintOptions* opts)
{
    word32 oid = (word32)-1;
#if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA)
    int nid;
#endif
    const char* ln = NULL;
    word32 i = 0;
    int known = 1;

    /* Get the OID value for the OBJECT_ID. */
    if (GetObjectId(asn1->data + asn1->offset, &i, &oid, oidIgnoreType,
            asn1->item.len + 2) == ASN_PARSE_E) {
        known = 0;
    }
    else
#if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA)
    /* Lookup NID for OID value. */
    if ((nid = oid2nid(oid, oidIgnoreType)) != -1) {
        /* Lookup long name for NID. */
        ln = wolfSSL_OBJ_nid2ln(nid);
    }
    else
#endif
    /* Lookup long name for extra known OID values. */
    if (!Oid2LongName(oid, &ln)) {
        /* Unknown OID value. */
        ln = NULL;
        known = 0;
    }

    XFPRINTF(asn1->file, ":");
    /* Show OID value if not known or asked to. */
    if ((!known) || opts->show_oid) {
        XFPRINTF(asn1->file, "(0x%x) ", oid);
    }
    if (ln != NULL) {
        /* Print long name. */
        XFPRINTF(asn1->file, "%s", ln);
    }
    else {
        /* Print out as numbers - either dotted or hex values. */
        PrintObjectIdNum(asn1->file, asn1->data + asn1->item.data_idx,
            asn1->item.len);
    }
}

/* Print ASN.1 data as a character string.
 *
 * @param [in] asn1  ASN.1 parse object.
 */
static void PrintText(Asn1* asn1)
{
    word32 i;

    XFPRINTF(asn1->file, ":");
    /* Print all data bytes as characters. */
    for (i = 0; i < asn1->item.len; i++) {
        XFPRINTF(asn1->file, "%c", asn1->data[asn1->item.data_idx + i]);
    }
}

/* Print data as a hex bytes.
 *
 * @param [in] file  File pointer to write to.
 * @param [in] data  Data to print.
 * @param [in] len   Number of bytes to print.
 */
static void PrintHex(XFILE file, unsigned char* data, word32 len)
{
    word32 i;

    /* Print data bytes as hex numbers. */
    for (i = 0; i < len; i++) {
        XFPRINTF(file, "%02x", data[i]);
    }
}

/* Print ASN.1 data as a hex bytes.
 *
 * @param [in] asn1  ASN.1 parse object.
 */
static void PrintHexText(Asn1* asn1)
{
    XFPRINTF(asn1->file, ":");
    PrintHex(asn1->file, asn1->data + asn1->item.data_idx, asn1->item.len);
}

/* Print ASN.1 BIT_STRING data as hex bytes noting special first byte.
 *
 * @param [in] asn1  ASN.1 parse object.
 */
static void PrintBitStringText(Asn1* asn1)
{
    if (asn1->item.len > 0) {
        XFPRINTF(asn1->file, ":[%02x]", asn1->data[asn1->item.data_idx]);
        PrintHex(asn1->file, asn1->data + asn1->item.data_idx + 1,
            asn1->item.len - 1);
    }
}

/* Print ASN.1 BOOLEAN data as text with value.
 *
 * @param [in] asn1  ASN.1 parse object.
 */
static void PrintBooleanText(Asn1* asn1)
{
    /* Booleans should be 1 byte of data. */
    if (asn1->item.len == 1) {
        XFPRINTF(asn1->file, ":%s (%d)",
            (asn1->data[asn1->item.data_idx] == 0) ? "FALSE" : "TRUE",
            asn1->data[asn1->item.data_idx]);
    }
}

/* Print ASN.1 data as single byte +/- number.
 *
 * @param [in] asn1  ASN.1 parse object.
 */
static void PrintNumberText(Asn1* asn1)
{
    /* Only supporting 1 byte of data for now. */
    if (asn1->item.len == 1) {
       int num = asn1->data[asn1->item.data_idx];

       XFPRINTF(asn1->file, ":%d", num >= 0x80 ? num - 0x100 : num);
    }
}

/* Print ASN.1 data as a text based on the tag.
 *
 * TODO: handle more tags.
 *
 * @param [in] asn1  ASN.1 parse object.
 * @param [in] opts  ASN.1 options for printing.
 */
static void PrintAsn1Text(Asn1* asn1, Asn1PrintOptions* opts)
{
    /* Get the long name for OBJECT_ID where possible. */
    if (asn1->item.tag == ASN_OBJECT_ID) {
        PrintObjectIdText(asn1, opts);
    }
    /* Data is an array of printable characters. */
    else if ((asn1->item.tag == ASN_UTF8STRING) ||
             (asn1->item.tag == ASN_IA5_STRING) ||
             (asn1->item.tag == ASN_PRINTABLE_STRING) ||
             (asn1->item.tag == ASN_T61STRING) ||
             (asn1->item.tag == ASN_BMPSTRING) ||
             (asn1->item.tag == ASN_UTC_TIME) ||
             (asn1->item.tag == ASN_GENERALIZED_TIME) ||
             (asn1->item.tag == ASN_UNIVERSALSTRING) ||
             (asn1->item.tag == ASN_OBJECT_DESC) ||
             (asn1->item.tag == ASN_CHARACTER_STRING)) {
        PrintText(asn1);
    }
    /* Show TRUE and FALSE with number. */
    else if (asn1->item.tag == ASN_BOOLEAN) {
        PrintBooleanText(asn1);
    }
    /* Show number. */
    else if (asn1->item.tag == ASN_ENUMERATED) {
        PrintNumberText(asn1);
    }
    /* Dumping potentially long string of hex digites. */
    else if (!opts->show_no_dump_text) {
        /* Dump all bytes. */
        if ((asn1->item.tag == ASN_INTEGER) ||
            (asn1->item.tag == ASN_OCTET_STRING) ||
            ((asn1->item.tag > ASN_APPLICATION) && (asn1->item.cons))) {
            PrintHexText(asn1);
        }
        /* First byte is number of unused bits in last byte.
         * Print first specially and dump rest of the bytes. */
        else if (asn1->item.tag == ASN_BIT_STRING) {
            PrintBitStringText(asn1);
        }
    }
}

#define HexToChar(n) ((((n) >= 32) && ((n) < 127)) ? (n) : '.')

/* Dump data as hex bytes.
 *
 * @param [in] file  File pointer to write to.
 * @param [in] data  Data to print.
 * @param [in] len   Number of bytes to print.
 */
static void DumpData(XFILE file, unsigned char* data, word32 len)
{
    word32 i;
    word32 j;

    for (i = 0; i < len; i += j) {
        /* Print offset. */
        XFPRINTF(file, "       %04x:", i);
        for (j = 0; (j < 16) && (i + j < len); j++) {
            /* Print byte as hex number. */
            XFPRINTF(file, "%s%02x", (j == 8) ? "  " : " ", data[i + j]);
        }
        /* Print spaces between hex and characters. */
        XFPRINTF(file, "   %*s", (16 - j) * 3 + ((j < 8) ? 1 : 0), "");
        for (j = 0; (j < 16) && (i + j < len); j++) {
            /* Print byte as hex number. */
            XFPRINTF(file, "%c", HexToChar(data[i + j]));
        }
        XFPRINTF(file, "\n");
    }
}

/* Update current depth based on the current position.
 *
 * @param [in, out] asn1  ASN.1 parse object.
 */
static void UpdateDepth(Asn1* asn1)
{
    /* If current index is greater than or equal end index then it is done. */
    while ((asn1->depth > 0) &&
           (asn1->end_idx[asn1->depth-1] <= asn1->curr)) {
        /* Move up a depth. */
        asn1->depth--;
    }
}

/* Check validity of end index of constructed ASN.1 items.
 *
 * @param [in, out] asn1  ASN.1 parse object.
 * @return  0 on success.
 * @return  ASN_DEPTH_E when end offset invalid.
 */
static int CheckDepth(Asn1* asn1)
{
    int ret = 0;
    int i;
    word32 curr_end = asn1->curr + asn1->item.len;

    for (i = 0; (ret == 0) && (i < asn1->depth); i++) {
        /* Each end index must be at least as large as the current one. */
        if (asn1->end_idx[i] < asn1->end_idx[asn1->depth]) {
            ret = ASN_DEPTH_E;
        }
        /* Each end index must be at least as large as current index. */
        if (asn1->end_idx[i] < curr_end) {
            ret = ASN_DEPTH_E;
        }
    }

    return ret;
}

/* Draw branching based on depth for an ASN.1 item.
 *
 * @param [in] asn1  ASN.1 parse object.
 */
static void DrawBranch(Asn1* asn1)
{
    int i;
    word32 end = asn1->curr + asn1->item.len;

    /* Write out the character for all depths but current. */
    for (i = 0; i < asn1->depth; i++) {
        if (asn1->item.cons || (end < asn1->end_idx[i])) {
            if (i < asn1->depth - 1) {
                /* Constructed or not end index and not current depth: | */
                XFPRINTF(asn1->file, "\xe2\x94\x82");
            }
            else {
                /* Constructed or not end index and current depth: |- */
                XFPRINTF(asn1->file, "\xe2\x94\x9c");
            }
        }
        else if ((i > 1) && (end >= asn1->end_idx[i-1])) {
            /* End index for previous: _|_ (in top half) */
            XFPRINTF(asn1->file, "\xe2\x94\xb4");
        }
        else {
            /* End index but not for previous: L (in top half) */
            XFPRINTF(asn1->file, "\xe2\x94\x94");
        }
    }
    /* Prefix to tag name. */
    if (asn1->item.cons) {
        if (asn1->depth > 0) {
            /* Have other line to connect to: T (in bottom half) */
            XFPRINTF(asn1->file, "\xe2\x94\xac");
        }
        else {
            /* Have no other line to connect to: r */
            XFPRINTF(asn1->file, "\xe2\x94\x8c");
        }
    }
    else {
        /* In a sequence: - */
        XFPRINTF(asn1->file, "\xe2\x94\x80");
    }
}

/* Print data as hex bytes separated by space.
 *
 * @param [in] file  File pointer to write to.
 * @param [in] data  Data to print.
 * @param [in] len   Number of bytes to print.
 */
static void PrintHexBytes(XFILE file, unsigned char* data, word32 len)
{
    word32 i;

    for (i = 0; i < len; i++) {
        XFPRINTF(file, " %02x", data[i]);
    }
}

/* Dump header data.
 *
 * @param [in] asn1  ASN.1 parse object.
 * @param [in] opts  ASN.1 options for printing.
 */
static void DumpHeader(Asn1* asn1, Asn1PrintOptions* opts)
{
    /* Put on same line when not showing data too and not showing text data. */
    if ((!opts->show_data) && opts->show_no_text) {
        XFPRINTF(asn1->file, "%10s", "");
    }
    else {
        /* Align with start of data. */
        XFPRINTF(asn1->file, "\n%12s", "");
    }
    XFPRINTF(asn1->file, " %02x", asn1->item.tag);
    if (asn1->curr >= asn1->offset + 1) {
        /* Print the header bytes as hex bytes separated by a space. */
        PrintHexBytes(asn1->file, asn1->data + asn1->offset + 1,
            asn1->curr - (asn1->offset + 1));
    }
}

/* Print ASN.1 item info based on header and indeces.
 *
 * @param [in] asn1  ASN.1 parse object.
 * @param [in] opts  ASN.1 options for printing.
 */
static void PrintInfo(Asn1* asn1, Asn1PrintOptions* opts)
{
    /* Print offset of this ASN.1 item. */
    XFPRINTF(asn1->file, "%4d: ", asn1->offset);
    /* Print length of header. */
    XFPRINTF(asn1->file, "%1d ", asn1->curr - asn1->offset);
    /* Print data length. */
    XFPRINTF(asn1->file, "%c%4d%c", asn1->item.cons ? '[' : '+', asn1->item.len,
                      asn1->item.cons ? ']' : ' ');
    /* Print depth. */
    XFPRINTF(asn1->file, " %s(%d)", (asn1->depth < 10) ? " " : "", asn1->depth);
    if (!opts->draw_branch) {
        /* Indent to depth as required. */
        XFPRINTF(asn1->file, "%*s ", asn1->depth * opts->indent, "");
        if (!opts->indent) {
            /* Indicate constructed if no indent. */
            XFPRINTF(asn1->file, "%c", asn1->item.cons ? '+' : ' ');
        }
    }
    else {
        /* Draw branch structure for ASN.1 item. */
        XFPRINTF(asn1->file, " ");
        DrawBranch(asn1);
    }
    /* Print tag name. */
    XFPRINTF(asn1->file, "%-16s", TagString(asn1->item.tag));
}

/* Expecting tag part of ASN.1 item. */
#define ASN_PART_TAG        0
/* Expecting length part of ASN.1 item. */
#define ASN_PART_LENGTH     1
/* Expecting data part of ASN.1 item. */
#define ASN_PART_DATA       2

/* Print next ASN.1 item.
 *
 * @param [in, out] asn1  ASN.1 parse object.
 * @param [in]      opts  ASN.1 print options.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when asn1 or opts is NULL.
 * @return  ASN_LEN_E when ASN.1 item's length too long.
 * @return  ASN_DEPTH_E when end offset invalid.
 */
static int wc_Asn1_Print(Asn1* asn1, Asn1PrintOptions* opts)
{
    int ret = 0;

    /* Process tag. */
    if (asn1->part == ASN_PART_TAG) {
        /* Recalculate which depth we are at. */
        UpdateDepth(asn1);
        /* Get tag. */
        asn1->item.tag = asn1->data[asn1->curr] & (byte)~ASN_CONSTRUCTED;
        /* Store whether tag indicates constructed. */
        asn1->item.cons = (asn1->data[asn1->curr] & ASN_CONSTRUCTED) ==
                     ASN_CONSTRUCTED;
        /* Start of ASN.1 item is current index. */
        asn1->offset = asn1->curr;
        /* Step over tag. */
        asn1->curr++;
        /* Next part is length. */
        asn1->part = ASN_PART_LENGTH;
    }
    /* Process length. */
    if (asn1->part == ASN_PART_LENGTH) {
        int len;

        /* Decode length and step over it. */
        if (GetLength(asn1->data, &asn1->curr, &len, asn1->max) < 0) {
            ret = ASN_LEN_E;
        }
        else {
            /* Store ASN.1 item data offset. */
            asn1->item.data_idx = asn1->curr;
            /* Store ASN.1 item data length. */
            asn1->item.len = (word32)len;

            /* Print info about ASN.1 item. */
            PrintInfo(asn1, opts);

            if (!asn1->item.cons) {
                /* Move on to print data. */
                asn1->part = ASN_PART_DATA;
            }
            else {
                /* Print header now if not printing data. */
                if (opts->show_header_data) {
                    DumpHeader(asn1, opts);
                }
                XFPRINTF(asn1->file, "\n");
                /* Record end offset for this depth. */
                asn1->end_idx[asn1->depth++] = asn1->curr + asn1->item.len;
                /* Done with this ASN.1 item. */
                asn1->part = ASN_PART_TAG;
            }
            /* Check end indeces are valid. */
            ret = CheckDepth(asn1);
        }
    }
    /* Process data. */
    if ((ret == 0) && (asn1->part == ASN_PART_DATA)) {
        if (!opts->show_no_text) {
            /* Print text representation of data. */
            PrintAsn1Text(asn1, opts);
        }
        if (opts->show_header_data) {
            /* Dump header bytes. */
            DumpHeader(asn1, opts);
        }
        XFPRINTF(asn1->file, "\n");
        if (opts->show_data) {
            /* Dump data bytes. */
            DumpData(asn1->file, asn1->data + asn1->item.data_idx,
                asn1->item.len);
        }
        /* Step past data to next ASN.1 item. */
        asn1->curr += asn1->item.len;
        /* Update the depth based on end indeces. */
        UpdateDepth(asn1);
        /* Done with this ASN.1 item. */
        asn1->part = ASN_PART_TAG;
    }

    /* Make ASN.1 item printing go out. */
    fflush(asn1->file);

    return ret;
}

/* Print all ASN.1 items.
 *
 * @param [in, out] asn1  ASN.1 parse object.
 * @param [in]      opts  ASN.1 print options.
 * @param [in]      data  BER/DER data to print.
 * @param [in]      len   Length of data to print in bytes.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when asn1, opts or data is NULL.
 * @return  ASN_LEN_E when ASN.1 item's length too long.
 * @return  ASN_DEPTH_E when end offset invalid.
 * @return  ASN_PARSE_E when not all of an ASN.1 item parsed.
 */
int wc_Asn1_PrintAll(Asn1* asn1, Asn1PrintOptions* opts, unsigned char* data,
    word32 len)
{
    int ret = 0;

    if ((asn1 == NULL) || (opts == NULL) || (data == NULL)) {
        ret = BAD_FUNC_ARG;
    }

    if (ret == 0) {
        /* Initialize start position. */
        asn1->curr = 0;
        /* Start parsing at tag. */
        asn1->part = ASN_PART_TAG;
        /* Start depth at 0. */
        asn1->depth = 0;

        /* Store the starting point of the data to parse. */
        asn1->data = data + opts->offset;
        if (opts->length > 0) {
            /* Use user specified maximum length. */
            asn1->max = opts->length;
        }
        else {
            /* Maximum length is up to end from offset. */
            asn1->max = len - opts->offset;
        }

        /* Keep going while no error and have data to parse. */
        while ((ret == 0) && (asn1->curr < asn1->max)) {
            /* Print an ASN.1 item. */
            ret = wc_Asn1_Print(asn1, opts);
        }
    }
    if ((ret == 0) && (asn1->part != ASN_PART_TAG)) {
        /* Stopped before finishing ASN.1 item. */
        ret = ASN_PARSE_E;
    }
    if ((ret == 0) && (asn1->depth != 0)) {
        /* Stopped without seeing all items in a constructed item. */
        ret = ASN_DEPTH_E;
    }

    return ret;
}

#endif /* WOLFSSL_ASN_PRINT */
#endif /* !NO_ASN */

/* Functions that parse, but are not using ASN.1 */
#if !defined(NO_RSA) && !defined(HAVE_USER_RSA) && \
    (!defined(NO_BIG_INT) || defined(WOLFSSL_SP_MATH))
/* import RSA public key elements (n, e) into RsaKey structure (key) */
/* this function does not use any ASN.1 parsing */
int wc_RsaPublicKeyDecodeRaw(const byte* n, word32 nSz, const byte* e,
                             word32 eSz, RsaKey* key)
{
    if (n == NULL || e == NULL || key == NULL)
        return BAD_FUNC_ARG;

    key->type = RSA_PUBLIC;

    if (mp_init(&key->n) != MP_OKAY)
        return MP_INIT_E;

    if (mp_read_unsigned_bin(&key->n, n, nSz) != 0) {
        mp_clear(&key->n);
        return ASN_GETINT_E;
    }
#ifdef HAVE_WOLF_BIGINT
    if ((int)nSz > 0 && wc_bigint_from_unsigned_bin(&key->n.raw, n, nSz) != 0) {
        mp_clear(&key->n);
        return ASN_GETINT_E;
    }
#endif /* HAVE_WOLF_BIGINT */

    if (mp_init(&key->e) != MP_OKAY) {
        mp_clear(&key->n);
        return MP_INIT_E;
    }

    if (mp_read_unsigned_bin(&key->e, e, eSz) != 0) {
        mp_clear(&key->n);
        mp_clear(&key->e);
        return ASN_GETINT_E;
    }
#ifdef HAVE_WOLF_BIGINT
    if ((int)eSz > 0 && wc_bigint_from_unsigned_bin(&key->e.raw, e, eSz) != 0) {
        mp_clear(&key->n);
        mp_clear(&key->e);
        return ASN_GETINT_E;
    }
#endif /* HAVE_WOLF_BIGINT */

#ifdef WOLFSSL_XILINX_CRYPT
    if (wc_InitRsaHw(key) != 0) {
        return BAD_STATE_E;
    }
#endif

    return 0;
}
#endif /* !NO_RSA && !HAVE_USER_RSA && (!NO_BIG_INT || WOLFSSL_SP_MATH) */


#ifdef WOLFSSL_SEP


#endif /* WOLFSSL_SEP */