wolfssl-sys 4.0.0

System bindings for WolfSSL
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
/* asn.h
 *
 * Copyright (C) 2006-2026 wolfSSL Inc.
 *
 * This file is part of wolfSSL.
 *
 * wolfSSL is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * wolfSSL is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
 */

/*!
    \file wolfssl/wolfcrypt/asn.h
*/

/*

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.

*/
#ifndef WOLF_CRYPT_ASN_H
#define WOLF_CRYPT_ASN_H

#include <wolfssl/wolfcrypt/types.h>

#if !defined(NO_ASN) || !defined(NO_PWDBASED)
/* included openssl/obj_mac.h directly for SN_xxx definitions */
#if !defined(WOLFSSL_OBJ_MAC_H_)
#if !defined(NO_ASN_TIME) && defined(NO_TIME_H)
    #define NO_ASN_TIME /* backwards compatibility with NO_TIME_H */
#endif

#include <wolfssl/wolfcrypt/wolfmath.h>

#ifdef WOLFSSL_ASYNC_CRYPT
    #include <wolfssl/wolfcrypt/async.h>
#endif

#ifndef NO_DH
    #include <wolfssl/wolfcrypt/dh.h>
#endif
#ifndef NO_DSA
    #include <wolfssl/wolfcrypt/dsa.h>
#endif
#ifndef NO_RSA
    #include <wolfssl/wolfcrypt/rsa.h>
#endif
#ifdef HAVE_ECC
    #include <wolfssl/wolfcrypt/ecc.h>
#endif
#ifdef HAVE_ED25519
    #include <wolfssl/wolfcrypt/ed25519.h>
#endif
#ifdef HAVE_ED448
    #include <wolfssl/wolfcrypt/ed448.h>
#endif
#ifdef HAVE_SPHINCS
    #include <wolfssl/wolfcrypt/sphincs.h>
#endif
#ifdef HAVE_FALCON
    #include <wolfssl/wolfcrypt/falcon.h>
#endif
#ifdef HAVE_DILITHIUM
    #include <wolfssl/wolfcrypt/dilithium.h>
#endif
#ifndef NO_SHA
    #include <wolfssl/wolfcrypt/sha.h>
#endif
#ifndef NO_MD5
    #include <wolfssl/wolfcrypt/md5.h>
#endif
#include <wolfssl/wolfcrypt/sha256.h>
#if defined(WOLFSSL_SHA384) || defined(WOLFSSL_SHA512)
    #include <wolfssl/wolfcrypt/sha512.h>
#endif
#ifdef WOLFSSL_SM3
    #include <wolfssl/wolfcrypt/sm3.h>
#endif
#include <wolfssl/wolfcrypt/asn_public.h>   /* public interface */

#if defined(NO_SHA) && defined(NO_SHA256)
    #define WC_SHA256_DIGEST_SIZE 32
#endif

#ifdef __cplusplus
    extern "C" {
#endif

#ifndef NO_ASN

#ifndef EXTERNAL_SERIAL_SIZE
    #define EXTERNAL_SERIAL_SIZE 32
#endif

enum {
    ASN_ISSUER  = 0,
    ASN_SUBJECT = 1,

    ASN_BEFORE  = 0,
    ASN_AFTER   = 1
};

#ifndef NO_ASN_OLD_TYPE_NAMES
    #ifndef ISSUER
        #define ISSUER ASN_ISSUER
    #endif
    #ifndef SUBJECT
        #define SUBJECT ASN_SUBJECT
    #endif
    #ifndef BEFORE
        #define BEFORE ASN_BEFORE
    #endif
    #ifndef AFTER
        #define AFTER ASN_AFTER
    #endif
#endif

/* ASN Tags   */
enum ASN_Tags {
    ASN_EOC               = 0x00,
    ASN_BOOLEAN           = 0x01,
    ASN_INTEGER           = 0x02,
    ASN_BIT_STRING        = 0x03,
    ASN_OCTET_STRING      = 0x04,
    ASN_TAG_NULL          = 0x05,
    ASN_OBJECT_ID         = 0x06,
    ASN_OBJECT_DESC       = 0x07,
    ASN_INSTANCE_OF       = 0x08,
    ASN_REAL              = 0x09,
    ASN_ENUMERATED        = 0x0a,
    ASN_EMBEDDED_PDV      = 0x0b,
    ASN_UTF8STRING        = 0x0c,
    ASN_RELATIVE_OID      = 0x0d,
    ASN_SEQUENCE          = 0x10,
    ASN_SET               = 0x11,
    ASN_NUMERICSTRING     = 0x12,
    ASN_PRINTABLE_STRING  = 0x13,
    ASN_T61STRING         = 0x14,
    ASN_VIDEOTEXSTRING    = 0x15,
    ASN_IA5_STRING        = 0x16,
    ASN_UTC_TIME          = 0x17,
    ASN_GENERALIZED_TIME  = 0x18,
    ASN_GRAPHICSTRING     = 0x19,
    ASN_ISO646STRING      = 0x1a,
    ASN_GENERALSTRING     = 0x1b,
    ASN_UNIVERSALSTRING   = 0x1c,
    ASN_CHARACTER_STRING  = 0x1d,
    ASN_BMPSTRING         = 0x1e,
    ASN_TYPE_MASK         = 0x1f,

    ASN_LONG_LENGTH       = 0x80,
    ASN_INDEF_LENGTH      = 0x80,

    /* ASN_Flags - Bitmask */
    ASN_CONSTRUCTED       = 0x20,
    ASN_APPLICATION       = 0x40,
    ASN_CONTEXT_SPECIFIC  = 0x80,
    ASN_PRIVATE           = 0xC0,
    ASN_CLASS_MASK        = 0xC0,

    CRL_EXTENSIONS        = 0xa0,
    ASN_EXTENSIONS        = 0xa3,

    /* GeneralName types */
    ASN_OTHER_TYPE        = 0x00,
    ASN_RFC822_TYPE       = 0x01,
    ASN_DNS_TYPE          = 0x02,
    ASN_DIR_TYPE          = 0x04,
    ASN_URI_TYPE          = 0x06, /* the value 6 is from GeneralName OID */
    ASN_IP_TYPE           = 0x07, /* the value 7 is from GeneralName OID */
    ASN_RID_TYPE          = 0x08,

    /* PKCS #7 types */
    ASN_ENC_CONTENT       = 0x00,
    ASN_OTHERNAME_VALUE   = 0x00,

    /* AuthorityKeyIdentifier fields */
    ASN_AUTHKEYID_KEYID   = 0x00,
    ASN_AUTHKEYID_ISSUER  = 0x01,
    ASN_AUTHKEYID_SERIAL  = 0x02,

    /* GeneralSubtree fields */
    ASN_SUBTREE_MIN       = 0x00,
    ASN_SUBTREE_MAX       = 0x01,

    /* x509 Cert Fields */
    ASN_X509_CERT_VERSION = 0x00,

    /* x509 Cert Extension Fields */
    ASN_AKID_KEYID        = 0x00,

    /* ECC Key Fields */
    ASN_ECC_PARAMS        = 0x00,
    ASN_ECC_PUBKEY        = 0x01,

    /* OneAsymmetricKey Fields */
    ASN_ASYMKEY_ATTRS     = 0x00,
    ASN_ASYMKEY_PUBKEY    = 0x01,

    /* PKEY Fields */
    ASN_PKEY_SEED         = 0x00
};

/* NOTE: If ASN_UTC_TIME_SIZE or ASN_GENERALIZED_TIME_SIZE are ever modified
 *       one needs to update the logic in asn.c function GetAsnTimeString()
 *       which depends on the size 14 and/or 16 to determine which format to
 *       place in the "buf" (output)
 */
#define ASN_UTC_TIME_SIZE 14 /* Read note above before modifying */
#define ASN_GENERALIZED_TIME_SIZE 16 /* Read note above before modifying */
#define ASN_GENERALIZED_TIME_MAX 68

#ifdef WOLFSSL_ASN_TEMPLATE
/* Different data types that can be stored in ASNGetData/ASNSetData. */
enum ASNItem_DataType {
    /* Default for tag type. */
    ASN_DATA_TYPE_NONE           = 0,
    /* 8-bit integer value. */
    ASN_DATA_TYPE_WORD8          = 1,
    /* 16-bit integer value. */
    ASN_DATA_TYPE_WORD16         = 2,
    /* 32-bit integer value. */
    ASN_DATA_TYPE_WORD32         = 4,
    /* Buffer with data and length. */
    ASN_DATA_TYPE_BUFFER         = 5,
    /* An expected/required buffer with data and length. */
    ASN_DATA_TYPE_EXP_BUFFER     = 6,
    /* Replace the item with buffer (data and length). */
    ASN_DATA_TYPE_REPLACE_BUFFER = 7,
    /* Big number as an mp_int. */
    ASN_DATA_TYPE_MP             = 8,
    /* Big number as an mp_int that has already been initialized. */
    ASN_DATA_TYPE_MP_INITED      = 9,
    /* Big number as a positive or negative mp_int. */
    ASN_DATA_TYPE_MP_POS_NEG     = 10,
    /* ASN.1 CHOICE. A 0 terminated list of tags that are valid. */
    ASN_DATA_TYPE_CHOICE         = 11
};

/* A template entry describing an ASN.1 item. */
typedef struct ASNItem {
    /* Depth of ASN.1 item - how many constructed ASN.1 items above. */
    byte depth;
    /* BER/DER tag to expect. */
    byte tag;
    /* Whether the ASN.1 item is constructed. */
    WC_BITFIELD constructed:1;
    /* Whether to parse the header only or skip data. If
     * ASNSetData.data.buffer.data is supplied then this option gets
     * overwritten and the child nodes get ignored. */
    WC_BITFIELD headerOnly:1;
    /* Whether ASN.1 item is optional.
     *  - 0 means not optional
     *  - 1 means is optional
     *  - 2+ means one of these at the same level with same value must appear.
     */
    byte optional;
} ASNItem;

/* Dynamic data for setting (encoding) an ASN.1 item. */
typedef struct ASNSetData {
    /* Reverse offset into buffer of ASN.1 item - calculated in SizeASN_Items().
     * SetASN_Items() subtracts from total length to get usable value.
     */
    word32 offset;
    /* Length of data in ASN.1 item - calculated in SizeASN_Items(). */
    word32 length;
    /* Different data type representation. */
    union {
        /* 8-bit integer value. */
        byte    u8;
        /* 16-bit integer value. */
        word16  u16;
        /* 32-bit integer value. */
        word32  u32;
        /* Big number as an mp_int. */
        mp_int* mp;
        /* Buffer as data pointer and length. */
        struct {
            /* Data to write out. */
            const byte* data;
            /* Length of data to write out. */
            word32      length;
        } buffer;
    } data;
    /* Type of data stored in data field - enum ASNItem_DataType. */
    byte   dataType;
    /* Don't write this ASN.1 item out.
     * Optional items are dependent on the data being encoded.
     */
    byte   noOut;
} ASNSetData;

/* Dynamic data for getting (decoding) an ASN.1 item. */
typedef struct ASNGetData {
    /* Offset into buffer where encoding starts. */
    word32 offset;
    /* Total length of data in ASN.1 item.
     * BIT_STRING and INTEGER lengths include leading byte. */
    word32 length;
    union {
        /* Pointer to 8-bit integer. */
        byte*       u8;
        /* Pointer to 16-bit integer. */
        word16*     u16;
        /* Pointer to 32-bit integer. */
        word32*     u32;
        /* Pointer to mp_int for big number. */
        mp_int*     mp;
        /* List of possible tags. Useful for CHOICE ASN.1 items. */
        const byte* choice;
        /* Buffer to copy into. */
        struct {
            /* Buffer to hold ASN.1 data. */
            byte*   data;
            /* Maximum length of buffer. */
            word32* length;
        } buffer;
        /* Reference to ASN.1 item's data. */
        struct {
            /* Pointer reference into input buffer. */
            const byte* data;
            /* Length of data. */
            word32      length;
        } ref;
        /* Data of an OBJECT_ID. */
        struct {
            /* OID data reference into input buffer. */
            const byte* data;
            /* Length of OID data. */
            word32      length;
            /* Type of OID expected. */
            word32      type;
            /* OID sum - 32-bit id. */
            word32      sum;
        } oid;
    } data;
    /* Type of data stored in data field - enum ASNItem_DataType. */
    byte dataType;
    /* Tag found in BER/DER item. */
    byte tag;
} ASNGetData;

WOLFSSL_LOCAL int SizeASN_Items(const ASNItem* asn, ASNSetData *data,
    int count, word32* encSz);
WOLFSSL_LOCAL int SetASN_Items(const ASNItem* asn, ASNSetData *data, int count,
    byte* output);
WOLFSSL_LOCAL int GetASN_Items(const ASNItem* asn, ASNGetData *data, int count,
    int complete, const byte* input, word32* inOutIdx, const word32 length);

#ifdef WOLFSSL_ASN_TEMPLATE_TYPE_CHECK
WOLFSSL_LOCAL void GetASN_Int8Bit(ASNGetData *dataASN, byte* num);
WOLFSSL_LOCAL void GetASN_Int16Bit(ASNGetData *dataASN, word16* num);
WOLFSSL_LOCAL void GetASN_Int32Bit(ASNGetData *dataASN, word32* num);
WOLFSSL_LOCAL void GetASN_Buffer(ASNGetData *dataASN, byte* data,
    word32* length);
WOLFSSL_LOCAL void GetASN_ExpBuffer(ASNGetData *dataASN, const byte* data,
    word32 length);
WOLFSSL_LOCAL void GetASN_MP(ASNGetData *dataASN, mp_int* num);
WOLFSSL_LOCAL void GetASN_MP_Inited(ASNGetData *dataASN, mp_int* num);
WOLFSSL_LOCAL void GetASN_MP_PosNeg(ASNGetData *dataASN, mp_int* num);
WOLFSSL_LOCAL void GetASN_Choice(ASNGetData *dataASN, const byte* options);
WOLFSSL_LOCAL void GetASN_Boolean(ASNGetData *dataASN, byte* num);
WOLFSSL_LOCAL void GetASN_OID(ASNGetData *dataASN, int oidType);
WOLFSSL_LOCAL void GetASN_GetConstRef(ASNGetData * dataASN, const byte** data,
    word32* length);
WOLFSSL_LOCAL void GetASN_GetRef(const ASNGetData * dataASN, const byte** data,
    word32* length);
WOLFSSL_LOCAL void GetASN_OIDData(const ASNGetData * dataASN, const byte** data,
    word32* length);
WOLFSSL_LOCAL void SetASN_Boolean(ASNSetData *dataASN, byte val);
WOLFSSL_LOCAL void SetASN_Int8Bit(ASNSetData *dataASN, byte num);
WOLFSSL_LOCAL void SetASN_Int16Bit(ASNSetData *dataASN, word16 num);
WOLFSSL_LOCAL void SetASN_Buffer(ASNSetData *dataASN, const byte* data,
    word32 length);
WOLFSSL_LOCAL void SetASN_ReplaceBuffer(ASNSetData *dataASN, const byte* data,
    word32 length);
WOLFSSL_LOCAL void SetASN_MP(ASNSetData *dataASN, mp_int* num);
WOLFSSL_LOCAL void SetASN_OID(ASNSetData *dataASN, int oid, int oidType);
#else
/* 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.
 */
#define GetASN_Int8Bit(dataASN, num)                                   \
    do {                                                               \
        (dataASN)->dataType = ASN_DATA_TYPE_WORD8;                     \
        (dataASN)->data.u8  = (num);                                   \
    } while (0)

/* 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.
 */
#define GetASN_Int16Bit(dataASN, num)                                  \
    do {                                                               \
        (dataASN)->dataType = ASN_DATA_TYPE_WORD16;                    \
        (dataASN)->data.u16 = (num);                                   \
    } while (0)

/* 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.
 */
#define GetASN_Int32Bit(dataASN, num)                                  \
    do {                                                               \
        (dataASN)->dataType = ASN_DATA_TYPE_WORD32;                    \
        (dataASN)->data.u32 = (num);                                   \
    } while (0)

/* Setup ASN data item to get data into a buffer of a specific length.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] d        Buffer to hold data.
 * @param [in] l        Length of buffer in bytes.
 */
#define GetASN_Buffer(dataASN, d, l)                                   \
    do {                                                               \
        (dataASN)->dataType           = ASN_DATA_TYPE_BUFFER;          \
        (dataASN)->data.buffer.data   = (d);                           \
        (dataASN)->data.buffer.length = (l);                           \
    } while (0)

/* Setup ASN data item to check parsed data against expected buffer.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] d        Buffer containing expected data.
 * @param [in] l        Length of buffer in bytes.
 */
#define GetASN_ExpBuffer(dataASN, d, l)                                \
    do {                                                               \
        (dataASN)->dataType        = ASN_DATA_TYPE_EXP_BUFFER;         \
        (dataASN)->data.ref.data   = (d);                              \
        (dataASN)->data.ref.length = (l);                              \
    } while (0)

/* 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.
 */
#define GetASN_MP(dataASN, num)                                        \
    do {                                                               \
        (dataASN)->dataType = ASN_DATA_TYPE_MP;                        \
        (dataASN)->data.mp  = (num);                                   \
    } while (0)

/* 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.
 */
#define GetASN_MP_Inited(dataASN, num)                                 \
    do {                                                               \
        (dataASN)->dataType = ASN_DATA_TYPE_MP_INITED;                 \
        (dataASN)->data.mp  = (num);                                   \
    } while (0)

/* 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.
 */
#define GetASN_MP_PosNeg(dataASN, num)                                 \
    do {                                                               \
        (dataASN)->dataType = ASN_DATA_TYPE_MP_POS_NEG;                \
        (dataASN)->data.mp  = (num);                                   \
    } while (0)

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

/* 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.
 */
#define GetASN_Boolean(dataASN, num)                                   \
    do {                                                               \
        (dataASN)->dataType = ASN_DATA_TYPE_NONE;                      \
        (dataASN)->data.u8  = (num);                                   \
    } while (0)

/* 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.
 */
#define GetASN_OID(dataASN, 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] d        Pointer to data of item.
 * @param [out] l        Length of buffer in bytes.
 */
#define GetASN_GetConstRef(dataASN, d, l)                              \
    do {                                                               \
        *(d) = (dataASN)->data.ref.data;                               \
        *(l) = (dataASN)->data.ref.length;                             \
    } while (0)

/* Get the data and length from an ASN data item.
 *
 * @param [in]  dataASN  Dynamic ASN data item.
 * @param [out] d        Pointer to data of item.
 * @param [out] l        Length of buffer in bytes.
 */
#define GetASN_GetRef(dataASN, d, l)                                   \
    do {                                                               \
        *(d) = (const byte*)(dataASN)->data.ref.data;                  \
        *(l) =              (dataASN)->data.ref.length;                \
    } while (0)

/* Get the data and length from an ASN data item that is an OID.
 *
 * @param [in]  dataASN  Dynamic ASN data item.
 * @param [out] d        Pointer to .
 * @param [out] l        Length of buffer in bytes.
 */
#define GetASN_OIDData(dataASN, d, l)                                  \
    do {                                                               \
        *(d) = (const byte*)(dataASN)->data.oid.data;                  \
        *(l) =        (dataASN)->data.oid.length;                      \
    } while (0)

/* Setup an ASN data item to set a boolean.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] val      Boolean value.
 */
#define SetASN_Boolean(dataASN, val)                                   \
    do {                                                               \
        (dataASN)->dataType = ASN_DATA_TYPE_NONE;                      \
        (dataASN)->data.u8  = (val);                                   \
    } while (0)

/* 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.
 */
#define SetASN_Int8Bit(dataASN, num)                                   \
    do {                                                               \
        (dataASN)->dataType = ASN_DATA_TYPE_WORD8;                     \
        (dataASN)->data.u8  = (num);                                   \
    } while (0)

/* 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.
 */
#define SetASN_Int16Bit(dataASN, num)                                  \
    do {                                                               \
        (dataASN)->dataType = ASN_DATA_TYPE_WORD16;                    \
        (dataASN)->data.u16 = (num);                                   \
    } while (0)

/* Setup an ASN data item to set the data in a buffer.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] d        Buffer containing data to set.
 * @param [in] l        Length of data in buffer in bytes.
 */
#define SetASN_Buffer(dataASN, d, l)                                   \
    do {                                                               \
        (dataASN)->data.buffer.data   = (d);                           \
        (dataASN)->data.buffer.length = (word32)(l);                   \
    } while (0)

/* Setup an ASN data item to set the DER encode data in a buffer.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] d        Buffer containing BER encoded data to set.
 * @param [in] l        Length of data in buffer in bytes.
 */
#define SetASN_ReplaceBuffer(dataASN, d, l)                            \
    do {                                                               \
        (dataASN)->dataType           = ASN_DATA_TYPE_REPLACE_BUFFER;  \
        (dataASN)->data.buffer.data   = (d);                           \
        (dataASN)->data.buffer.length = (l);                           \
    } while (0)

/* Setup an ASN data item to set an muli-precision number.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] num      Multi-precision number.
 */
#define SetASN_MP(dataASN, num)                                        \
    do {                                                               \
        (dataASN)->dataType = ASN_DATA_TYPE_MP;                        \
        (dataASN)->data.mp  = (num);                                   \
    } while (0)

/* 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.
 */
#define SetASN_OID(dataASN, oid, oidType)                              \
    (dataASN)->data.buffer.data = OidFromId(oid, oidType,              \
                                       &(dataASN)->data.buffer.length)
#endif /* WOLFSSL_ASN_TEMPLATE_TYPE_CHECK */


/* Get address at the start of the BER item.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] in       Input buffer.
 * @return  Address at start of BER item.
 */
#define GetASNItem_Addr(dataASN, in)                                   \
    ((in) + (dataASN).offset)

/* Get length of a BER item - including tag and length.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] in       Input buffer.
 * @return  Length of a BER item.
 */
#define GetASNItem_Length(dataASN, in)                                 \
    ((dataASN).length + (word32)((dataASN).data.buffer.data - (in)) -  \
                                                     (dataASN).offset)

#define GetASNItem_HaveData(dataASN)                                   \
   ((dataASN).data.buffer.data != NULL)

/* Get the index of a BER item's data.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] in       Input buffer.
 * @return  Index of a BER item's data.
 */
#define GetASNItem_DataIdx(dataASN, in)                                \
    (word32)((dataASN).data.ref.data - (in))

#define GetASNItem_HaveIdx(dataASN)                                    \
    ((dataASN).data.ref.data != NULL)

/* Get the end index of a BER item - index of the start of the next item.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] in       Input buffer.
 * @return  End index of a BER item.
 */
#define GetASNItem_EndIdx(dataASN, in)                                 \
    ((word32)((dataASN).data.ref.data - (in)) +                        \
                                            (dataASN).data.ref.length)

/* For a BIT_STRING, get the unused bits byte.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @return  Unused bits byte in BIT_STRING.
 */
#define GetASNItem_UnusedBits(dataASN)                                 \
    (*((dataASN).data.ref.data - 1))

/* Set the data items at indices start to end inclusive to not be encoded.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] start    First item not to be encoded.
 * @param [in] end      Last item not to be encoded.
 */
#define SetASNItem_NoOut(dataASN, start, end)                          \
    do {                                                               \
        int ii;                                                        \
        for (ii = (start); ii <= (end); ii++) {                        \
            (dataASN)[ii].noOut = 1;                                   \
        }                                                              \
    }                                                                  \
    while (0)

/* Set the data items below node to not be encoded.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] asn      ASN template item.
 * @param [in] node     Node who's children should not be encoded.
 * @param [in] dataASNLen Number of items in dataASN.
 */
#define SetASNItem_NoOutBelow(dataASN, asn, node, dataASNLen)          \
    do {                                                               \
        int ii;                                                        \
        for (ii = (node) + 1; ii < (int)(dataASNLen); ii++) {          \
            if ((asn)[ii].depth <= (asn)[node].depth)                  \
                break;                                                 \
            (dataASN)[ii].noOut = 1;                                   \
        }                                                              \
    }                                                                  \
    while (0)

/* Set the node and all nodes below to not be encoded.
 *
 * @param [in] dataASN  Dynamic ASN data item.
 * @param [in] asn      ASN template item.
 * @param [in] node     Node which should not be encoded. Child nodes will
 *                      also not be encoded.
 * @param [in] dataASNLen Number of items in dataASN.
 */
#define SetASNItem_NoOutNode(dataASN, asn, node, dataASNLen)           \
    do {                                                               \
        int ii;                                                        \
        (dataASN)[node].noOut = 1;                                     \
        for (ii = (node) + 1; ii < (int)(dataASNLen); ii++) {          \
            if ((asn)[ii].depth <= (asn)[node].depth)                  \
                break;                                                 \
            (dataASN)[ii].noOut = 1;                                   \
        }                                                              \
    }                                                                  \
    while (0)

#endif /* WOLFSSL_ASN_TEMPLATE */


enum DN_Tags {
    ASN_DN_NULL       = 0x00,
    ASN_COMMON_NAME   = 0x03,   /* CN */
    ASN_SUR_NAME      = 0x04,   /* SN */
    ASN_SERIAL_NUMBER = 0x05,   /* serialNumber */
    ASN_COUNTRY_NAME  = 0x06,   /* C  */
    ASN_LOCALITY_NAME = 0x07,   /* L  */
    ASN_STATE_NAME    = 0x08,   /* ST */
    ASN_STREET_ADDR   = 0x09,   /* street */
    ASN_ORG_NAME      = 0x0a,   /* O  */
    ASN_ORGUNIT_NAME  = 0x0b,   /* OU */
    ASN_BUS_CAT       = 0x0f,   /* businessCategory */
    ASN_POSTAL_CODE   = 0x11,   /* postalCode */
    ASN_USER_ID       = 0x12,   /* UserID */
#ifdef WOLFSSL_CERT_NAME_ALL
    ASN_NAME          = 0x29,   /* name */
    ASN_GIVEN_NAME    = 0x2a,   /* GN */
    ASN_INITIALS      = 0x2b,   /* initials */
    ASN_DNQUALIFIER   = 0x2e,   /* dnQualifier */
#endif /* WOLFSSL_CERT_NAME_ALL */


    ASN_CONTENT_TYPE  = 0x97, /* not actual OID (see attrPkcs9ContentTypeOid) */
    ASN_EMAIL_NAME    = 0x98, /* not actual OID (see attrEmailOid) */
    ASN_CUSTOM_NAME   = 0x99, /* not actual OID (see CertOidField) */

    /* pilot attribute types
     * OID values of 0.9.2342.19200300.100.1.* */
    ASN_FAVOURITE_DRINK  = 0x13, /* favouriteDrink */
    ASN_RFC822_MAILBOX = 0x14, /* rfc822Mailbox */
    ASN_DOMAIN_COMPONENT = 0x19  /* DC */
};

/* This is the size of the smallest possible PEM header and footer */
extern const int pem_struct_min_sz;

#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
typedef struct WOLFSSL_ObjectInfo {
    int nid;
    int id;
    word32 type;
    const char* sName;
    const char* lName;
} WOLFSSL_ObjectInfo;
extern const size_t wolfssl_object_info_sz;
extern const WOLFSSL_ObjectInfo wolfssl_object_info[];
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */

/* DN Tag Strings */
#define WOLFSSL_COMMON_NAME      "/CN="
#define WOLFSSL_LN_COMMON_NAME   "/commonName="
#define WOLFSSL_SUR_NAME         "/SN="
#ifdef WOLFSSL_CERT_NAME_ALL
    #define WOLFSSL_NAME             "/N="
    #define WOLFSSL_INITIALS         "/initials="
    #define WOLFSSL_GIVEN_NAME       "/GN="
    #define WOLFSSL_DNQUALIFIER      "/dnQualifier="
#endif /* WOLFSSL_CERT_NAME_ALL */
#define WOLFSSL_SERIAL_NUMBER    "/serialNumber="
#define WOLFSSL_COUNTRY_NAME     "/C="
#define WOLFSSL_LN_COUNTRY_NAME  "/countryName="
#define WOLFSSL_LOCALITY_NAME    "/L="
#define WOLFSSL_LN_LOCALITY_NAME "/localityName="
#define WOLFSSL_STATE_NAME       "/ST="
#define WOLFSSL_LN_STATE_NAME    "/stateOrProvinceName="
#define WOLFSSL_STREET_ADDR_NAME "/street="
#define WOLFSSL_LN_STREET_ADDR_NAME "/streetAddress="
#define WOLFSSL_POSTAL_NAME      "/postalCode="
#define WOLFSSL_ORG_NAME         "/O="
#define WOLFSSL_LN_ORG_NAME      "/organizationName="
#define WOLFSSL_ORGUNIT_NAME     "/OU="
#define WOLFSSL_LN_ORGUNIT_NAME  "/organizationalUnitName="
#define WOLFSSL_DOMAIN_COMPONENT "/DC="
#define WOLFSSL_LN_DOMAIN_COMPONENT "/domainComponent="
#define WOLFSSL_BUS_CAT          "/businessCategory="
#define WOLFSSL_JOI_C            "/jurisdictionC="
#define WOLFSSL_JOI_ST           "/jurisdictionST="
#define WOLFSSL_EMAIL_ADDR       "/emailAddress="

#define WOLFSSL_USER_ID          "/UID="
#define WOLFSSL_DOMAIN_COMPONENT "/DC="
#define WOLFSSL_RFC822_MAILBOX   "/rfc822Mailbox="
#define WOLFSSL_FAVOURITE_DRINK  "/favouriteDrink="
#define WOLFSSL_CONTENT_TYPE     "/contentType="

#if defined(WOLFSSL_APACHE_HTTPD)
    /* otherName strings */
    #define WOLFSSL_SN_MS_UPN       "msUPN"
    #define WOLFSSL_LN_MS_UPN       "Microsoft User Principal Name"
    #define WOLFSSL_MS_UPN_SUM      UPN_OID
    #define WOLFSSL_SN_DNS_SRV      "id-on-dnsSRV"
    #define WOLFSSL_LN_DNS_SRV      "SRVName"
    #define WOLFSSL_DNS_SRV_SUM     DNS_SRV_OID
    /* TLS features extension strings */
    #define WOLFSSL_SN_TLS_FEATURE  "tlsfeature"
    #define WOLFSSL_LN_TLS_FEATURE  "TLS Feature"
    #define WOLFSSL_TLS_FEATURE_SUM TLS_FEATURE_OID
#endif

/* Maximum number of allowed subject alternative names in a certificate.
 * Any certificate containing more than this number of subject
 * alternative names will cause an error when attempting to parse. */
#ifndef WOLFSSL_MAX_ALT_NAMES
#define WOLFSSL_MAX_ALT_NAMES 1024
#endif

/* Maximum number of allowed name constraints in a certificate.
 * Any certificate containing more than this number of name constraints
 * will cause an error when attempting to parse. */
#ifndef WOLFSSL_MAX_NAME_CONSTRAINTS
#define WOLFSSL_MAX_NAME_CONSTRAINTS 128
#endif

#define WC_NID_undef 0

/* Setup for WC_MAX_RSA_BITS needs to be here, rather than rsa.h, because
 * FIPS headers don't have it.  And it needs to be here, rather than internal.h,
 * so that setup occurs even in cryptonly builds.
 */
#ifndef NO_RSA
    #ifndef WC_MAX_RSA_BITS
        #ifdef USE_FAST_MATH
            /* FP implementation support numbers up to FP_MAX_BITS / 2 bits. */
            #define WC_MAX_RSA_BITS    (FP_MAX_BITS / 2)
        #elif defined(WOLFSSL_SP_MATH_ALL) || defined(WOLFSSL_SP_MATH)
            /* SP implementation supports numbers of SP_INT_BITS bits. */
            #define WC_MAX_RSA_BITS    WC_BITS_FULL_BYTES(SP_INT_BITS)
        #else
            /* Integer maths is dynamic but we only go up to 4096 bits. */
            #define WC_MAX_RSA_BITS 4096
        #endif
    #endif
    #if (WC_MAX_RSA_BITS % 8)
        #error RSA maximum bit size must be multiple of 8
    #endif
#endif

#if defined(HAVE_FALCON) || defined(HAVE_DILITHIUM)
    #define WC_MAX_CERT_VERIFY_SZ 6000            /* For Dilithium */
#elif defined(WOLFSSL_CERT_EXT)
    #define WC_MAX_CERT_VERIFY_SZ 2048            /* For larger extensions */
#elif !defined(NO_RSA) && defined(WC_MAX_RSA_BITS)
    #define WC_MAX_CERT_VERIFY_SZ (WC_MAX_RSA_BITS / 8) /* max RSA bytes */
#elif defined(HAVE_ECC)
    #define WC_MAX_CERT_VERIFY_SZ ECC_MAX_SIG_SIZE /* max ECC  */
#elif defined(HAVE_ED448)
    #define WC_MAX_CERT_VERIFY_SZ ED448_SIG_SIZE   /* max Ed448  */
#elif defined(HAVE_ED25519)
    #define WC_MAX_CERT_VERIFY_SZ ED25519_SIG_SIZE /* max Ed25519  */
#else
    #define WC_MAX_CERT_VERIFY_SZ 1024 /* max default  */
#endif
#endif /* !NO_ASN */
#endif /* !WOLFSSL_OBJ_MAC_H_ */
#if defined(WOLFSSL_OBJ_MAC_H_) || \
    defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
/* short names */
#define WC_SN_md4        "MD4"
#define WC_SN_md5        "MD5"
#define WC_SN_sha1       "SHA1"
#define WC_SN_sha224     "SHA224"
#define WC_SN_sha256     "SHA256"
#define WC_SN_sha384     "SHA384"
#define WC_SN_sha512     "SHA512"
#define WC_SN_sha512_224 "SHA512-224"
#define WC_SN_sha512_256 "SHA512-256"
#define WC_SN_sha3_224   "SHA3-224"
#define WC_SN_sha3_256   "SHA3-256"
#define WC_SN_sha3_384   "SHA3-384"
#define WC_SN_sha3_512   "SHA3-512"
#define WC_SN_shake128   "SHAKE128"
#define WC_SN_shake256   "SHAKE256"
#define WC_SN_blake2s256 "BLAKE2s256"
#define WC_SN_blake2s512 "BLAKE2s512"
#define WC_SN_blake2b512 "BLAKE2b512"
#define WC_SN_sm3        "SM3"

/* NIDs */
#define WC_NID_netscape_cert_type 71
#define WC_NID_des 66
#define WC_NID_des3 67
#define WC_NID_sha256 672
#define WC_NID_sha384 673
#define WC_NID_sha512 674
#define WC_NID_sha512_224 1094
#define WC_NID_sha512_256 1095
#define WC_NID_pkcs7_signed 22
#define WC_NID_pkcs7_enveloped 23
#define WC_NID_pkcs7_signedAndEnveloped 24
#define WC_NID_pkcs9_emailAddress     48
#define WC_NID_pkcs9_unstructuredName 49
#define WC_NID_pkcs9_contentType 50  /* 1.2.840.113549.1.9.3 */
#define WC_NID_pkcs9_challengePassword 54
#define WC_NID_hw_name_oid 73
#define WC_NID_id_pkix_OCSP_basic 74
#define WC_NID_any_policy 75
#define WC_NID_anyExtendedKeyUsage 76
#define WC_NID_givenName 100  /* 2.5.4.42 */
#define WC_NID_initials 101  /* 2.5.4.43 */
#define WC_NID_title 106
#define WC_NID_description 107
#define WC_NID_basic_constraints BASIC_CA_OID
#define WC_NID_key_usage KEY_USAGE_OID      /* 2.5.29.15 */
#define WC_NID_ext_key_usage EXT_KEY_USAGE_OID  /* 2.5.29.37 */
#define WC_NID_subject_key_identifier SUBJ_KEY_OID
#define WC_NID_authority_key_identifier AUTH_KEY_OID
#define WC_NID_private_key_usage_period PRIV_KEY_USAGE_PERIOD_OID
#define WC_NID_subject_alt_name ALT_NAMES_OID
#define WC_NID_issuer_alt_name ISSUE_ALT_NAMES_OID
#define WC_NID_info_access AUTH_INFO_OID
#define WC_NID_sinfo_access SUBJ_INFO_ACC_OID       /* id-pe 11 */
#define WC_NID_name_constraints NAME_CONS_OID  /* 2.5.29.30 */
#define WC_NID_crl_distribution_points CRL_DIST_OID  /* 2.5.29.31 */
#define WC_NID_certificate_policies CERT_POLICY_OID
#define WC_NID_policy_mappings POLICY_MAP_OID
#define WC_NID_policy_constraints POLICY_CONST_OID
#define WC_NID_inhibit_any_policy INHIBIT_ANY_OID       /* 2.5.29.54 */
#define WC_NID_tlsfeature TLS_FEATURE_OID              /* id-pe 24 */
#define WC_NID_buildingName 1494

#define WC_SN_dnQualifier "dnQualifier"
#define WC_LN_dnQualifier "dnQualifier"
#define WC_NID_dnQualifier 174              /* 2.5.4.46 */

#define WC_SN_commonName "CN"
#define WC_LN_commonName "commonName"
#define WC_NID_commonName 14                /* CN Changed to not conflict
                                             * with PBE_SHA1_DES3 */
#define WC_LN_name "name"
#define WC_SN_name "name"
#define WC_NID_name 173                     /* N , OID = 2.5.4.41 */

#define WC_LN_surname "surname"
#define WC_SN_surname "SN"
#define WC_NID_surname 0x04                 /* SN */

#define WC_LN_serialNumber "serialNumber"
#define WC_NID_serialNumber 0x05            /* serialNumber */

#define WC_LN_countryName "countryName"
#define WC_SN_countryName "C"
#define WC_NID_countryName 0x06             /* C  */

#define WC_LN_localityName "localityName"
#define WC_SN_localityName "L"
#define WC_NID_localityName 0x07            /* L  */

#define WC_LN_stateOrProvinceName "stateOrProvinceName"
#define WC_SN_stateOrProvinceName "ST"
#define WC_NID_stateOrProvinceName 0x08     /* ST */

#define WC_LN_streetAddress "streetAddress"
#define WC_SN_streetAddress "street"
#define WC_NID_streetAddress ASN_STREET_ADDR  /* street */

#define WC_LN_organizationName "organizationName"
#define WC_SN_organizationName "O"
#define WC_NID_organizationName 0x0a        /* O  */

#define WC_LN_organizationalUnitName "organizationalUnitName"
#define WC_SN_organizationalUnitName "OU"
#define WC_NID_organizationalUnitName 0x0b  /* OU */

#define WC_LN_jurisdictionCountryName "jurisdictionCountryName"
#define WC_SN_jurisdictionCountryName "jurisdictionC"
#define WC_NID_jurisdictionCountryName 0xc

#define WC_LN_jurisdictionStateOrProvinceName "jurisdictionStateOrProvinceName"
#define WC_SN_jurisdictionStateOrProvinceName "jurisdictionST"
#define WC_NID_jurisdictionStateOrProvinceName 0xd

#define WC_LN_businessCategory "businessCategory"
#define WC_NID_businessCategory ASN_BUS_CAT

#define WC_SN_domainComponent "DC"
#define WC_LN_domainComponent "domainComponent"
#define WC_NID_domainComponent ASN_DOMAIN_COMPONENT

#define WC_LN_postalCode "postalCode"
#define WC_NID_postalCode ASN_POSTAL_CODE   /* postalCode */

#define WC_SN_rfc822Mailbox "mail"
#define WC_LN_rfc822Mailbox "rfc822Mailbox"
#define WC_NID_rfc822Mailbox 460

#define WC_SN_favouriteDrink "coldBrew"
#define WC_LN_favouriteDrink "favouriteDrink"
#define WC_NID_favouriteDrink 462

#define WC_SN_userId "UID"
#define WC_LN_userId "userId"
#define WC_NID_userId 458

#define WC_LN_registeredAddress "registeredAddress"
#define WC_NID_registeredAddress 870

#define WC_LN_emailAddress "emailAddress"
#define WC_NID_emailAddress 0x30            /* emailAddress */

#define WC_SN_id_on_dnsSRV "id-on-dnsSRV"
#define WC_LN_id_on_dnsSRV "SRVName"
#define WC_NID_id_on_dnsSRV 82              /* 1.3.6.1.5.5.7.8.7 */

#define WC_SN_ms_upn "msUPN"
#define WC_LN_ms_upn "Microsoft User Principal Name"
#define WC_NID_ms_upn UPN_OID               /* 1.3.6.1.4.1.311.20.2.3 */

#define WC_NID_X9_62_prime_field 406        /* 1.2.840.10045.1.1 */

#define WC_NID_id_GostR3410_2001     811
#define WC_NID_id_GostR3410_2012_256 979
#define WC_NID_id_GostR3410_2012_512 980

#ifndef OPENSSL_COEXIST

#define NID_undef WC_NID_undef
#define NID_netscape_cert_type WC_NID_netscape_cert_type
#define NID_des WC_NID_des
#define NID_des3 WC_NID_des3
#define NID_sha256 WC_NID_sha256
#define NID_sha384 WC_NID_sha384
#define NID_sha512 WC_NID_sha512
#define NID_sha512_224 WC_NID_sha512_224
#define NID_sha512_256 WC_NID_sha512_256
#define NID_pkcs7_signed WC_NID_pkcs7_signed
#define NID_pkcs7_enveloped WC_NID_pkcs7_enveloped
#define NID_pkcs7_signedAndEnveloped WC_NID_pkcs7_signedAndEnveloped
#define NID_pkcs9_unstructuredName WC_NID_pkcs9_unstructuredName
#define NID_pkcs9_contentType WC_NID_pkcs9_contentType
#define NID_pkcs9_challengePassword WC_NID_pkcs9_challengePassword
#define NID_hw_name_oid WC_NID_hw_name_oid
#define NID_id_pkix_OCSP_basic WC_NID_id_pkix_OCSP_basic
#define NID_any_policy WC_NID_any_policy
#define NID_anyExtendedKeyUsage WC_NID_anyExtendedKeyUsage
#define NID_givenName WC_NID_givenName
#define NID_initials WC_NID_initials
#define NID_title WC_NID_title
#define NID_description WC_NID_description
#define NID_basic_constraints WC_NID_basic_constraints
#define NID_key_usage WC_NID_key_usage
#define NID_ext_key_usage WC_NID_ext_key_usage
#define NID_subject_key_identifier WC_NID_subject_key_identifier
#define NID_authority_key_identifier WC_NID_authority_key_identifier
#define NID_private_key_usage_period WC_NID_private_key_usage_period
#define NID_subject_alt_name WC_NID_subject_alt_name
#define NID_issuer_alt_name WC_NID_issuer_alt_name
#define NID_info_access WC_NID_info_access
#define NID_sinfo_access WC_NID_sinfo_access
#define NID_name_constraints WC_NID_name_constraints
#define NID_crl_distribution_points WC_NID_crl_distribution_points
#define NID_certificate_policies WC_NID_certificate_policies
#define NID_policy_mappings WC_NID_policy_mappings
#define NID_policy_constraints WC_NID_policy_constraints
#define NID_inhibit_any_policy WC_NID_inhibit_any_policy
#define NID_tlsfeature WC_NID_tlsfeature
#define NID_buildingName WC_NID_buildingName

#define SN_dnQualifier WC_SN_dnQualifier
#define LN_dnQualifier WC_LN_dnQualifier
#define NID_dnQualifier WC_NID_dnQualifier

#define SN_commonName WC_SN_commonName
#define LN_commonName WC_LN_commonName
#define NID_commonName WC_NID_commonName

#define LN_name WC_LN_name
#define SN_name WC_SN_name
#define NID_name WC_NID_name

#define LN_surname WC_LN_surname
#define SN_surname WC_SN_surname
#define NID_surname WC_NID_surname

#define LN_serialNumber WC_LN_serialNumber
#define NID_serialNumber WC_NID_serialNumber

#define LN_countryName WC_LN_countryName
#define SN_countryName WC_SN_countryName
#define NID_countryName WC_NID_countryName

#define LN_localityName WC_LN_localityName
#define SN_localityName WC_SN_localityName
#define NID_localityName WC_NID_localityName

#define LN_stateOrProvinceName WC_LN_stateOrProvinceName
#define SN_stateOrProvinceName WC_SN_stateOrProvinceName
#define NID_stateOrProvinceName WC_NID_stateOrProvinceName

#define LN_streetAddress WC_LN_streetAddress
#define SN_streetAddress WC_SN_streetAddress
#define NID_streetAddress WC_NID_streetAddress

#define LN_organizationName WC_LN_organizationName
#define SN_organizationName WC_SN_organizationName
#define NID_organizationName WC_NID_organizationName

#define LN_organizationalUnitName WC_LN_organizationalUnitName
#define SN_organizationalUnitName WC_SN_organizationalUnitName
#define NID_organizationalUnitName WC_NID_organizationalUnitName

#define LN_jurisdictionCountryName WC_LN_jurisdictionCountryName
#define SN_jurisdictionCountryName WC_SN_jurisdictionCountryName
#define NID_jurisdictionCountryName WC_NID_jurisdictionCountryName

#define LN_jurisdictionStateOrProvinceName WC_LN_jurisdictionStateOrProvinceName
#define SN_jurisdictionStateOrProvinceName WC_SN_jurisdictionStateOrProvinceName
#define NID_jurisdictionStateOrProvinceName WC_NID_jurisdictionStateOrProvinceName

#define LN_businessCategory WC_LN_businessCategory
#define NID_businessCategory WC_NID_businessCategory

#define SN_domainComponent WC_SN_domainComponent
#define LN_domainComponent WC_LN_domainComponent
#define NID_domainComponent WC_NID_domainComponent

#define LN_postalCode WC_LN_postalCode
#define NID_postalCode WC_NID_postalCode

#define SN_rfc822Mailbox WC_SN_rfc822Mailbox
#define LN_rfc822Mailbox WC_LN_rfc822Mailbox
#define NID_rfc822Mailbox WC_NID_rfc822Mailbox

#define SN_favouriteDrink WC_SN_favouriteDrink
#define LN_favouriteDrink WC_LN_favouriteDrink
#define NID_favouriteDrink WC_NID_favouriteDrink

#define SN_userId WC_SN_userId
#define LN_userId WC_LN_userId
#define NID_userId WC_NID_userId

#define LN_registeredAddress WC_LN_registeredAddress
#define NID_registeredAddress WC_NID_registeredAddress

#define LN_emailAddress WC_LN_emailAddress
#define NID_emailAddress WC_NID_emailAddress

#define SN_id_on_dnsSRV WC_SN_id_on_dnsSRV
#define LN_id_on_dnsSRV WC_LN_id_on_dnsSRV
#define NID_id_on_dnsSRV WC_NID_id_on_dnsSRV

#define SN_ms_upn WC_SN_ms_upn
#define LN_ms_upn WC_LN_ms_upn
#define NID_ms_upn WC_NID_ms_upn

#define NID_X9_62_prime_field WC_NID_X9_62_prime_field

#define NID_id_GostR3410_2001 WC_NID_id_GostR3410_2001
#define NID_id_GostR3410_2012_256 WC_NID_id_GostR3410_2012_256
#define NID_id_GostR3410_2012_512 WC_NID_id_GostR3410_2012_512

#endif /* !OPENSSL_COEXIST */

#endif /* WOLFSSL_OBJ_MAC_H_ || OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
#if !defined(WOLFSSL_OBJ_MAC_H_)
#if !defined(NO_ASN)
enum ECC_TYPES
{
    ECC_PREFIX_0 = 160,
    ECC_PREFIX_1 = 161
};

#ifdef WOLFSSL_CERT_PIV
    enum PIV_Tags {
        ASN_PIV_CERT          = 0x0A,
        ASN_PIV_NONCE         = 0x0B,
        ASN_PIV_SIGNED_NONCE  = 0x0C,

        ASN_PIV_TAG_CERT      = 0x70,
        ASN_PIV_TAG_CERT_INFO = 0x71,
        ASN_PIV_TAG_MSCUID    = 0x72,
        ASN_PIV_TAG_ERR_DET   = 0xFE,

        /* certificate info masks */
        ASN_PIV_CERT_INFO_COMPRESSED = 0x03,
        ASN_PIV_CERT_INFO_ISX509     = 0x04,
        /* GZIP is 0x01 */
        ASN_PIV_CERT_INFO_GZIP       = 0x01,
    };
#endif /* WOLFSSL_CERT_PIV */


#define ASN_JOI_PREFIX_SZ       10
#define ASN_JOI_PREFIX          "\x2b\x06\x01\x04\x01\x82\x37\x3c\x02\x01"
#define ASN_JOI_C               0x3
#define ASN_JOI_ST              0x2

#ifndef WC_ASN_NAME_MAX
    #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
        defined(WOLFSSL_CERT_EXT)
        #ifdef WOLFSSL_MULTI_ATTRIB
            #define WC_ASN_NAME_MAX 360
        #else
            #define WC_ASN_NAME_MAX 330
        #endif
    #else
        #ifdef WOLFSSL_MULTI_ATTRIB
            #define WC_ASN_NAME_MAX 330
        #else
            #define WC_ASN_NAME_MAX 256
        #endif
    #endif
#endif

/* Maximum OID dotted form size. */
#define ASN1_OID_DOTTED_MAX_SZ         16

#ifndef WOLFSSL_ASN_MAX_LENGTH_SZ
    #define WOLFSSL_ASN_MAX_LENGTH_SZ 5 /* 1 byte length + 4 bytes of number */
#endif

enum Misc_ASN {
    ASN_BOOL_SIZE       =   2,     /* including type */
    ASN_ECC_HEADER_SZ   =   2,     /* String type + 1 byte len */
    ASN_ECC_CONTEXT_SZ  =   2,     /* Content specific type + 1 byte len */
#if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
    KEYID_SIZE          = WC_SM3_DIGEST_SIZE,
#elif defined(NO_SHA) || (!defined(NO_SHA256) && defined(WC_ASN_HASH_SHA256))
    KEYID_SIZE          = WC_SHA256_DIGEST_SIZE,
#else
    KEYID_SIZE          = WC_SHA_DIGEST_SIZE,
#endif
    RSA_INTS            =   2      /* RSA ints in private key */
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
                            + 3
#if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
                            + 3
#endif
#endif
                            ,
    DSA_PARAM_INTS      =   3,     /* DSA parameter ints */
    RSA_PUB_INTS        =   2,     /* RSA ints in public key */
    MIN_DATE_SIZE       =  12,
    MAX_DATE_SIZE       =  CTC_DATE_SIZE,
    ASN_GEN_TIME_SZ     =  15,     /* 7 numbers * 2 + Zulu tag */

#ifdef WOLFSSL_CERT_GEN
    #ifdef WOLFSSL_CERT_REQ
                          /* Max encoded cert req attributes length */
        MAX_ATTRIB_SZ   = MAX_SEQ_SZ * 4 + (11 + MAX_SEQ_SZ) * 3 +
                          MAX_PRSTR_SZ * 2 + CTC_NAME_SIZE * 2,
                          /* 11 is the OID size */
    #endif
    #if defined(WOLFSSL_ALT_NAMES) || defined(WOLFSSL_CERT_EXT)
        MAX_EXTENSIONS_SZ   = 1 + MAX_LENGTH_SZ + CTC_MAX_ALT_SIZE,
    #else
        MAX_EXTENSIONS_SZ   = 1 + MAX_LENGTH_SZ + MAX_CA_SZ,
    #endif
                          /* Max total extensions, id + len + others */
#endif
#ifndef MAX_OID_SZ
    MAX_OID_SZ          = 32,      /* Max DER length of OID*/
#endif
#if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
        defined(HAVE_PKCS7) || defined(OPENSSL_EXTRA_X509_SMALL) || \
        defined(HAVE_OID_DECODING) || defined(HAVE_OID_ENCODING)
    MAX_OID_STRING_SZ   = 64,      /* Max string length representation of OID*/
#endif
#ifdef WOLFSSL_CERT_EXT
    MAX_KID_SZ          = 45,      /* Max encoded KID length (SHA-256 case) */
    MAX_KEYUSAGE_SZ     = 18,      /* Max encoded Key Usage length */
    MAX_EXTKEYUSAGE_SZ  = 12 + (6 * (8 + 2)) +
                          CTC_MAX_EKU_OID_SZ, /* Max encoded ExtKeyUsage
                          (SEQ/LEN + OBJID + OCTSTR/LEN + SEQ +
                          (6 * (SEQ + OID))) */
#ifndef IGNORE_NETSCAPE_CERT_TYPE
    MAX_NSCERTTYPE_SZ   = MAX_SEQ_SZ + 17, /* SEQ + OID + OCTET STR +
                                            * NS BIT STR */
#endif
    MAX_CERTPOL_NB      = CTC_MAX_CERTPOL_NB,/* Max number of Cert Policy */
    MAX_CERTPOL_SZ      = CTC_MAX_CERTPOL_SZ,
#endif
    OCSP_NONCE_EXT_SZ   = 35,      /* OCSP Nonce Extension size */
    MAX_OCSP_EXT_SZ     = 58,      /* Max OCSP Extension length */
    MAX_OCSP_NONCE_SZ   = 16,      /* OCSP Nonce size           */
    TRAILING_ZERO       = 1,       /* Used for size of zero pad */
    ASN_TAG_SZ          = 1,       /* single byte ASN.1 tag */
    ASN_INDEF_END_SZ    = 2,       /* 0x00 0x00 at end of indef */
    MIN_VERSION_SZ      = 3,       /* Min bytes needed for GetMyVersion */
    MAX_X509_VERSION    = 3,       /* Max X509 version allowed */
    MIN_X509_VERSION    = 0,       /* Min X509 version allowed */
    WOLFSSL_X509_V1     = 0,
    WOLFSSL_X509_V2     = 1,
    WOLFSSL_X509_V3     = 2,
#if defined(OPENSSL_ALL)  || defined(WOLFSSL_MYSQL_COMPATIBLE) || \
    defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY) || \
    defined(OPENSSL_EXTRA) || defined(HAVE_PKCS7)
    MAX_TIME_STRING_SZ  = 25,      /* Max length of formatted time string */
#endif

    PKCS5_SALT_SZ       = 8,
    PKCS5V2_SALT_SZ     = 16,

    PEM_LINE_SZ        = 64,               /* Length of Base64 encoded line, not including new line */
    PEM_LINE_LEN       = PEM_LINE_SZ + 12, /* PEM line max + fudge */

    COUNTRY_CODE_LEN   = 2         /* RFC 3739 */
};

#ifndef WC_MAX_NAME_ENTRIES
    /* entries added to x509 name struct */
    #ifdef OPENSSL_EXTRA
    #define WC_MAX_NAME_ENTRIES 16
    #else
    #define WC_MAX_NAME_ENTRIES 14
    #endif
#endif
#define MAX_NAME_ENTRIES WC_MAX_NAME_ENTRIES


enum Oid_Types {
    oidHashType         = 0,
    oidSigType          = 1,
    oidKeyType          = 2,
    oidCurveType        = 3,
    oidBlkType          = 4,
    oidOcspType         = 5,
    oidCertExtType      = 6,
    oidCertAuthInfoType = 7,
    oidCertPolicyType   = 8,
    oidCertAltNameType  = 9,
    oidCertKeyUseType   = 10,
    oidKdfType          = 11,
    oidKeyWrapType      = 12,
    oidCmsKeyAgreeType  = 13,
    oidPBEType          = 14,
    oidHmacType         = 15,
    oidCompressType     = 16,
    oidCertNameType     = 17,
    oidTlsExtType       = 18,
    oidCrlExtType       = 19,
    oidCsrAttrType      = 20,
#ifdef WOLFSSL_SUBJ_DIR_ATTR
    oidSubjDirAttrType  = 21,
#endif
    oidIgnoreType
};


enum VerifyType {
    NO_VERIFY   = 0,
    VERIFY      = 1,
    VERIFY_CRL  = 2,
    VERIFY_OCSP = 3,
    VERIFY_NAME = 4,
    VERIFY_SKIP_DATE = 5,
    VERIFY_OCSP_CERT = 6
};

#ifdef WOLFSSL_CERT_EXT
enum KeyIdType {
    SKID_TYPE = 0,
    AKID_TYPE = 1
};
#endif

/* Key usage extension bits (based on RFC 5280) */
#define KEYUSE_DIGITAL_SIG    0x0080
#define KEYUSE_CONTENT_COMMIT 0x0040
#define KEYUSE_KEY_ENCIPHER   0x0020
#define KEYUSE_DATA_ENCIPHER  0x0010
#define KEYUSE_KEY_AGREE      0x0008
#define KEYUSE_KEY_CERT_SIGN  0x0004
#define KEYUSE_CRL_SIGN       0x0002
#define KEYUSE_ENCIPHER_ONLY  0x0001
#define KEYUSE_DECIPHER_ONLY  0x8000

/* Extended Key Usage bits (internal mapping only) */
#define EXTKEYUSE_USER        0x80
#define EXTKEYUSE_OCSP_SIGN   0x40
#define EXTKEYUSE_TIMESTAMP   0x20
#define EXTKEYUSE_EMAILPROT   0x10
#define EXTKEYUSE_CODESIGN    0x08
#define EXTKEYUSE_CLIENT_AUTH 0x04
#define EXTKEYUSE_SERVER_AUTH 0x02
#define EXTKEYUSE_ANY         0x01
#ifdef WOLFSSL_WOLFSSH
    #define EXTKEYUSE_SSH_CLIENT_AUTH    0x01
    #define EXTKEYUSE_SSH_MSCL           0x02
    #define EXTKEYUSE_SSH_KP_CLIENT_AUTH 0x04
#endif /* WOLFSSL_WOLFSSH */

#define WC_NS_SSL_CLIENT      0x80
#define WC_NS_SSL_SERVER      0x40
#define WC_NS_SMIME           0x20
#define WC_NS_OBJSIGN         0x10
#define WC_NS_SSL_CA          0x04
#define WC_NS_SMIME_CA        0x02
#define WC_NS_OBJSIGN_CA      0x01


#if defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA) || \
    defined(WOLFSSL_WPAS_SMALL) || defined(WOLFSSL_IP_ALT_NAME)
    #ifndef WOLFSSL_MAX_IPSTR
        #define WOLFSSL_MAX_IPSTR 46 /* max ip size IPv4 mapped IPv6 */
    #endif
    #define WOLFSSL_IP4_ADDR_LEN 4
    #define WOLFSSL_IP6_ADDR_LEN 16
#endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */

typedef struct DNS_entry   DNS_entry;

struct DNS_entry {
    DNS_entry* next;   /* next on DNS list */
    int        type;   /* i.e. ASN_DNS_TYPE */
    int        len;    /* actual DNS len */
    const char*
               name;   /* actual DNS name */
    int        nameStored;
#ifdef WOLFSSL_IP_ALT_NAME
    char*      ipString; /* human readable form of IP address */
    int        ipStringStored;
#endif
#ifdef WOLFSSL_RID_ALT_NAME
    char*      ridString; /* human readable form of registeredID */
    int        ridStringStored;
#endif

#ifdef WOLFSSL_FPKI
    int        oidSum; /* provide oid sum for verification */
#endif
};

#ifdef WOLFSSL_FPKI
    /* RFC4122 i.e urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6 */
    #define DEFAULT_UUID_SZ 45
#endif

typedef struct Base_entry  Base_entry;

struct Base_entry {
    Base_entry* next;   /* next on name base list */
    char*       name;   /* actual name base */
    int         nameSz; /* name length */
    byte        type;   /* Name base type (DNS or RFC822) */
};


enum SignatureState {
    SIG_STATE_BEGIN,
    SIG_STATE_HASH,
    SIG_STATE_KEY,
    SIG_STATE_DO,
    SIG_STATE_CHECK
};


#ifdef HAVE_PK_CALLBACKS
#ifdef HAVE_ECC
    typedef int (*wc_CallbackEccVerify)(
           const unsigned char* sig, unsigned int sigSz,
           const unsigned char* hash, unsigned int hashSz,
           const unsigned char* keyDer, unsigned int keySz,
           int* result, void* ctx);
#endif
#ifndef NO_RSA
    typedef int (*wc_CallbackRsaVerify)(
           unsigned char* sig, unsigned int sigSz,
           unsigned char** out,
           const unsigned char* keyDer, unsigned int keySz,
           void* ctx);
#endif
#endif /* HAVE_PK_CALLBACKS */

#if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS) ||\
    defined(HAVE_PK_CALLBACKS)
typedef struct tagCertAttribute {
        byte   verifyByTSIP_SCE;
        word32 certBegin;
        word32 pubkey_n_start;
        word32 pubkey_n_len;
        word32 pubkey_e_start;
        word32 pubkey_e_len;
        int curve_id;
        const byte* cert;
        word32 certSz;
        const byte* keyIndex;
  } CertAttribute;
#endif

struct SignatureCtx {
    void* heap;
    #ifdef WOLFSSL_NO_MALLOC
    byte  digest[WC_MAX_DIGEST_SIZE];
    #else
    byte* digest;
    #endif
#ifndef NO_RSA
    byte* out;
#endif
#if !defined(NO_RSA) || !defined(NO_DSA)
    #ifdef WOLFSSL_NO_MALLOC
    byte  sigCpy[MAX_ENCODED_SIG_SZ];
    #else
    byte* sigCpy;
    #endif
#endif
#if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
    !defined(NO_DSA) || defined(HAVE_DILITHIUM) || defined(HAVE_FALCON) || \
    defined(HAVE_SPHINCS)
    int verify;
#endif
    union {
    #ifndef NO_RSA
        #ifdef WOLFSSL_NO_MALLOC
        struct RsaKey       rsa[1];
        #else
        struct RsaKey*      rsa;
        #endif
    #endif
    #ifndef NO_DSA
        #ifdef WOLFSSL_NO_MALLOC
        struct DsaKey       dsa[1];
        #else
        struct DsaKey*      dsa;
        #endif
    #endif
    #ifdef HAVE_ECC
        #ifdef WOLFSSL_NO_MALLOC
        struct ecc_key      ecc[1];
        #else
        struct ecc_key*     ecc;
        #endif
    #endif
    #ifdef HAVE_ED25519
        #ifdef WOLFSSL_NO_MALLOC
        struct ed25519_key  ed25519[1];
        #else
        struct ed25519_key* ed25519;
        #endif
    #endif
    #ifdef HAVE_ED448
        #ifdef WOLFSSL_NO_MALLOC
        struct ed448_key  ed448[1];
        #else
        struct ed448_key* ed448;
        #endif
    #endif
    #ifdef HAVE_FALCON
        #ifdef WOLFSSL_NO_MALLOC
        struct falcon_key  falcon[1];
        #else
        struct falcon_key* falcon;
        #endif
    #endif
    #ifdef HAVE_DILITHIUM
        #ifdef WOLFSSL_NO_MALLOC
        struct dilithium_key  dilithium[1];
        #else
        struct dilithium_key* dilithium;
        #endif
    #endif
    #ifdef HAVE_SPHINCS
        #ifdef WOLFSSL_NO_MALLOC
        struct sphincs_key  sphincs[1];
        #else
        struct sphincs_key* sphincs;
        #endif
    #endif
    #ifndef WOLFSSL_NO_MALLOC
        void* ptr;
    #endif
    } key;
    int devId;
    int state;
    int typeH;
    int digestSz;
    word32 keyOID;
#ifdef WOLFSSL_ASYNC_CRYPT
    WC_ASYNC_DEV* asyncDev;
    void* asyncCtx;
#endif

#ifdef HAVE_PK_CALLBACKS
#ifdef HAVE_ECC
    wc_CallbackEccVerify pkCbEcc;
    void* pkCtxEcc;
#endif
#ifndef NO_RSA
    wc_CallbackRsaVerify pkCbRsa;
    void* pkCtxRsa;
#endif
#endif /* HAVE_PK_CALLBACKS */
#ifndef NO_RSA
#if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS) ||\
    defined(HAVE_PK_CALLBACKS)
    CertAttribute  CertAtt;
#endif
#ifdef WC_RSA_PSS
    enum wc_HashType hash;
    int mgf;
    int saltLen;
#endif
#endif
};

#define DOMAIN_COMPONENT_MAX 10

struct DecodedName {
    char*   fullName;
    int     fullNameLen;
    int     entryCount;
    int     cnIdx;
    int     cnLen;
    int     cnNid;
    int     snIdx;
    int     snLen;
    int     snNid;
    int     cIdx;
    int     cLen;
    int     cNid;
    int     lIdx;
    int     lLen;
    int     lNid;
    int     stIdx;
    int     stLen;
    int     stNid;
    int     oIdx;
    int     oLen;
    int     oNid;
    int     ouIdx;
    int     ouLen;
#ifdef WOLFSSL_CERT_EXT
    int     bcIdx;
    int     bcLen;
    int     jcIdx;
    int     jcLen;
    int     jsIdx;
    int     jsLen;
#endif
    int     ouNid;
    int     emailIdx;
    int     emailLen;
    int     emailNid;
    int     uidIdx;
    int     uidLen;
    int     uidNid;
    int     serialIdx;
    int     serialLen;
    int     serialNid;
    int     dcIdx[DOMAIN_COMPONENT_MAX];
    int     dcLen[DOMAIN_COMPONENT_MAX];
    int     dcNum;
    int     dcMode;
};

/* ASN Encoded Name field */
typedef struct EncodedName {
    int  nameLen;                /* actual string value length */
    int  totalLen;               /* total encoded length */
    int  type;                   /* type of name */
    int  used;                   /* are we actually using this one */
    byte encoded[CTC_NAME_SIZE * 2]; /* encoding */
} EncodedName;

#ifndef WOLFSSL_MAX_PATH_LEN
    /* RFC 5280 Section 6.1.2. "Initialization" - item (k) defines
     *     (k)  max_path_length:  this integer is initialized to "n", is
     *     decremented for each non-self-issued certificate in the path,
     *     and may be reduced to the value in the path length constraint
     *     field within the basic constraints extension of a CA
     *     certificate.
     *
     * wolfSSL has arbitrarily selected the value 127 for "n" in the above
     * description. Users can modify the maximum path length by setting
     * WOLFSSL_MAX_PATH_LEN to a preferred value at build time
     */
    #define WOLFSSL_MAX_PATH_LEN 127
#endif

typedef struct DecodedName DecodedName;
typedef struct DecodedCert DecodedCert;
typedef struct Signer      Signer;
#ifdef WOLFSSL_TRUST_PEER_CERT
typedef struct TrustedPeerCert TrustedPeerCert;
#endif /* WOLFSSL_TRUST_PEER_CERT */
typedef struct SignatureCtx SignatureCtx;

#ifndef WOLFSSL_AIA_ENTRY_DEFINED
#ifndef WOLFSSL_MAX_AIA_ENTRIES
    #define WOLFSSL_MAX_AIA_ENTRIES 8
#endif

#define WOLFSSL_AIA_ENTRY_DEFINED
typedef struct WOLFSSL_AIA_ENTRY {
    word32      method; /* AIA method OID sum (e.g., AIA_OCSP_OID). */
    const byte* uri;    /* Pointer into cert DER for the URI. */
    word32      uriSz;  /* Length of URI data. */
} WOLFSSL_AIA_ENTRY;
#endif /* WOLFSSL_AIA_ENTRY_DEFINED */

#ifdef WC_ASN_UNKNOWN_EXT_CB
typedef int (*wc_UnknownExtCallback)(const word16* oid, word32 oidSz, int crit,
                                     const unsigned char* der, word32 derSz);
typedef int (*wc_UnknownExtCallbackEx)(const word16* oid, word32 oidSz,
                                       int crit, const unsigned char* der,
                                       word32 derSz, void *ctx);
#endif

struct DecodedCert {
    const byte* publicKey;
    word32  pubKeySize;
#ifdef HAVE_OCSP_RESPONDER
    const byte* publicKeyForHash;
    word32  pubKeyForHashSize;
#endif
    int     pubKeyStored;
    word32  certBegin;               /* offset to start of cert          */
    word32  sigIndex;                /* offset to start of signature     */
    word32  sigLength;               /* length of signature              */
    word32  signatureOID;            /* sum of algorithm object id       */
    word32  keyOID;                  /* sum of key algo  object id       */
#ifdef WC_RSA_PSS
    word32  sigParamsIndex;          /* start of signature parameters    */
    word32  sigParamsLength;         /* length of signature parameters   */
#endif
    int     version;                 /* cert version, 1 or 3             */
    DNS_entry* altNames;             /* alt names list of dns entries    */
#ifndef IGNORE_NAME_CONSTRAINTS
    DNS_entry* altEmailNames;        /* alt names list of RFC822 entries */
    DNS_entry* altDirNames;          /* alt names list of DIR entries    */
    Base_entry* permittedNames;      /* Permitted name bases             */
    Base_entry* excludedNames;       /* Excluded name bases              */
#endif /* IGNORE_NAME_CONSTRAINTS */
    byte    subjectHash[KEYID_SIZE]; /* hash of all Names                */
    byte    issuerHash[KEYID_SIZE];  /* hash of all Names                */
#ifdef HAVE_OCSP
    byte    subjectKeyHash[KEYID_SIZE]; /* hash of the public Key         */
    byte    issuerKeyHash[KEYID_SIZE];  /* hash of the public Key         */
#endif /* HAVE_OCSP */
    const byte*
            signature;               /* not owned, points into raw cert  */
    const char*
            subjectCN;               /* CommonName                       */
    int     subjectCNLen;            /* CommonName Length                */
    char    subjectCNEnc;            /* CommonName Encoding              */
    char    issuer[WC_ASN_NAME_MAX]; /* full name including common name  */
    char    subject[WC_ASN_NAME_MAX];/* full name including common name  */
    int     verify;                  /* Default to yes, but could be off */
    const byte* source;              /* byte buffer holder cert, NOT owner */
    word32  srcIdx;                  /* current offset into buffer       */
    word32  maxIdx;                  /* max offset based on init size    */
    void*   heap;                    /* for user memory overrides        */
    byte    serial[EXTERNAL_SERIAL_SIZE];  /* raw serial number          */
    int     serialSz;                /* raw serial bytes stored */
    const byte* extensions;          /* not owned, points into raw cert  */
    int     extensionsSz;            /* length of cert extensions */
    word32  extensionsIdx;           /* if want to go back and parse later */
    const byte* extAuthInfo;         /* Authority Information Access URI */
    int     extAuthInfoSz;           /* length of the URI                */
#ifdef WOLFSSL_ASN_CA_ISSUER
    const byte* extAuthInfoCaIssuer; /* Authority Info Access caIssuer URI */
    int     extAuthInfoCaIssuerSz;   /* length of the caIssuer URI         */
#endif
    const byte* extCrlInfoRaw;       /* Entire CRL Distribution Points
                                      * Extension. This is useful when
                                      * re-generating the DER. */
    int     extCrlInfoRawSz;         /* length of the extension          */
    const byte* extCrlInfo;          /* CRL Distribution Points          */
    int     extCrlInfoSz;            /* length of the URI                */
    byte    extSubjKeyId[KEYID_SIZE]; /* Subject Key ID                  */
    word32  extSubjKeyIdSz;
    byte    extAuthKeyId[KEYID_SIZE]; /* Authority Key ID                */
    word32  extAuthKeyIdSz;
#ifdef WOLFSSL_AKID_NAME
    const byte* extAuthKeyIdIssuer;  /* Authority Key ID authorityCertIssuer */
    word32  extAuthKeyIdIssuerSz;    /* Authority Key ID authorityCertIssuer length */
    const byte* extAuthKeyIdIssuerSN; /* Authority Key ID authorityCertSerialNumber */
    word32  extAuthKeyIdIssuerSNSz;   /* Authority Key ID authorityCertSerialNumber length */
#endif
    word16    pathLength;              /* CA basic constraint path length  */
    word16    maxPathLen;              /* max_path_len see RFC 5280 section
                                      * 6.1.2 "Initialization" - (k) for
                                      * description of max_path_len */
    byte    policyConstSkip;         /* Policy Constraints skip certs value */
    word16  extKeyUsage;             /* Key usage bitfield               */
    byte    extExtKeyUsage;          /* Extended Key usage bitfield      */
#ifdef WOLFSSL_WOLFSSH
    byte    extExtKeyUsageSsh;       /* Extended Key Usage bitfield for SSH */
#endif /* WOLFSSL_WOLFSSH */

#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
    const byte* extExtKeyUsageSrc;
    word32  extExtKeyUsageSz;
    word32  extExtKeyUsageCount;
#ifdef WOLFSSL_AKID_NAME
    const byte* extRawAuthKeyIdSrc;
    word32  extRawAuthKeyIdSz;
#endif
    const byte* extAuthKeyIdSrc;
    const byte* extSubjKeyIdSrc;
#endif
#ifdef OPENSSL_ALL
    const byte* extSubjAltNameSrc;
    word32  extSubjAltNameSz;
#endif
#ifdef WOLFSSL_SUBJ_DIR_ATTR
    char countryOfCitizenship[COUNTRY_CODE_LEN+1]; /* ISO 3166 Country Code */
    #ifdef OPENSSL_ALL
        const byte* extSubjDirAttrSrc;
        word32 extSubjDirAttrSz;
    #endif
#endif /* WOLFSSL_SUBJ_DIR_ATTR */
#ifdef WOLFSSL_SUBJ_INFO_ACC
    const byte* extSubjInfoAccCaRepo;
    word32 extSubjInfoAccCaRepoSz;
    #ifdef OPENSSL_ALL
        const byte* extSubjInfoAccSrc;
        word32 extSubjInfoAccSz;
    #endif
#endif /* WOLFSSL_SUBJ_INFO_ACC */

#if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
    defined(HAVE_DILITHIUM) || defined(HAVE_FALCON) || defined(HAVE_SPHINCS)
    word32  pkCurveOID;           /* Public Key's curve OID */
    #ifdef WOLFSSL_CUSTOM_CURVES
        int  pkCurveSize;         /* Public Key's curve size */
    #endif
#endif /* HAVE_ECC || HAVE_ED25519 || HAVE_ED448 || HAVE_DILITHIUM ||
        * HAVE_FALCON || HAVE_SPHINCS */
    const byte* beforeDate;
    int     beforeDateLen;
    const byte* afterDate;
    int     afterDateLen;
#if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)
    const byte* issuerRaw;           /* pointer to issuer inside source */
    int     issuerRawLen;
#endif
#ifdef HAVE_OCSP_RESPONDER
    const byte* subjectRawForHash;   /* pointer to subject including tags */
    int     subjectRawForHashLen;
#endif
#if !defined(IGNORE_NAME_CONSTRAINTS) || defined(WOLFSSL_CERT_EXT)
    const byte* subjectRaw;          /* pointer to subject inside source */
    int     subjectRawLen;
#endif
#if !defined(IGNORE_NAME_CONSTRAINTS) || \
     defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
    const char*
            subjectEmail;
    int     subjectEmailLen;
#endif
#if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
    /* easy access to subject info for other sign */
    char*   subjectSN;
    int     subjectSNLen;
    char    subjectSNEnc;
#ifdef WOLFSSL_CERT_NAME_ALL
    char*   subjectN;
    int     subjectNLen;
    char    subjectNEnc;
    char*   subjectI;
    int     subjectILen;
    char    subjectIEnc;
    char*   subjectGN;
    int     subjectGNLen;
    char    subjectGNEnc;
    char*   subjectDNQ;
    int     subjectDNQLen;
    char    subjectDNQEnc;
#endif /* WOLFSSL_CERT_NAME_ALL */
    char*   subjectC;
    int     subjectCLen;
    char    subjectCEnc;
    char*   subjectL;
    int     subjectLLen;
    char    subjectLEnc;
    char*   subjectST;
    int     subjectSTLen;
    char    subjectSTEnc;
    char*   subjectO;
    int     subjectOLen;
    char    subjectOEnc;
    char*   subjectOU;
    int     subjectOULen;
    char    subjectOUEnc;
    char*   subjectSND;
    int     subjectSNDLen;
    char    subjectSNDEnc;
    char*   subjectUID;
    int     subjectUIDLen;
    char    subjectUIDEnc;
    char*   subjectStreet;
    int     subjectStreetLen;
    char    subjectStreetEnc;
    char*   subjectBC;
    int     subjectBCLen;
    char    subjectBCEnc;
    const char*
            subjectJC;
    int     subjectJCLen;
    char    subjectJCEnc;
    const char*
            subjectJS;
    int     subjectJSLen;
    char    subjectJSEnc;
    char*   subjectPC;
    int     subjectPCLen;
    char    subjectPCEnc;
#if defined(WOLFSSL_HAVE_ISSUER_NAMES)
    const char*
            issuerCN;
    int     issuerCNLen;
    char    issuerCNEnc;
    char*   issuerSN;
    int     issuerSNLen;
    char    issuerSNEnc;
    char*   issuerC;
    int     issuerCLen;
    char    issuerCEnc;
    char*   issuerL;
    int     issuerLLen;
    char    issuerLEnc;
    char*   issuerST;
    int     issuerSTLen;
    char    issuerSTEnc;
    char*   issuerO;
    int     issuerOLen;
    char    issuerOEnc;
    char*   issuerOU;
    int     issuerOULen;
    char    issuerOUEnc;
    char*   issuerSND;
    int     issuerSNDLen;
    char    issuerSNDEnc;
    const char*
            issuerEmail;
    int     issuerEmailLen;
#endif /* WOLFSSL_HAVE_ISSUER_NAMES */
#endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
#if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
    /* WOLFSSL_X509_NAME structures (used void* to avoid including ssl.h) */
    void* issuerName;
    void* subjectName;
#endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
#ifdef WOLFSSL_SEP
    int     deviceTypeSz;
    byte*   deviceType;
    int     hwTypeSz;
    byte*   hwType;
    int     hwSerialNumSz;
    byte*   hwSerialNum;
#endif /* WOLFSSL_SEP */
#ifdef WOLFSSL_CERT_EXT
    char    extCertPolicies[MAX_CERTPOL_NB][MAX_CERTPOL_SZ];
    int     extCertPoliciesNb;
#endif /* WOLFSSL_CERT_EXT */
#ifndef IGNORE_NETSCAPE_CERT_TYPE
    byte    nsCertType;
#endif

#ifdef WOLFSSL_CERT_REQ
    /* CSR attributes */
    const char*
            contentType; /* Content Type */
    int     contentTypeLen;
    const char*
            cPwd; /* Challenge Password */
    int     cPwdLen;
    const char*
            sNum; /* Serial Number */
    int     sNumLen;
    char*   dnQualifier;
    int     dnQualifierLen;
    char*   initials;
    int     initialsLen;
    char*   surname;
    int     surnameLen;
    char*   givenName;
    int     givenNameLen;
    const char*
            unstructuredName;
    int     unstructuredNameLen;
#endif /* WOLFSSL_CERT_REQ */

    Signer* ca;
#ifndef NO_CERTS
    SignatureCtx sigCtx;
#endif
#if defined(WOLFSSL_RENESAS_TSIP) || defined(WOLFSSL_RENESAS_FSPSM_TLS)
    byte*  sce_tsip_encRsaKeyIdx;
#endif
#ifdef WOLFSSL_MAXQ10XX_TLS
    word32 publicKeyIndex; /* offset to start of public key */
#endif

    int badDate;
    int criticalExt;

    /* Option Bits */
    WC_BITFIELD subjectCNStored:1;      /* have we saved a copy we own */
    WC_BITFIELD extSubjKeyIdSet:1;      /* Set when the SKID was read from cert */
    WC_BITFIELD extAuthKeyIdSet:1;      /* Set when the AKID was read from cert */
#ifndef IGNORE_NAME_CONSTRAINTS
    WC_BITFIELD extNameConstraintSet:1;
#endif
    WC_BITFIELD isCA:1;                 /* CA basic constraint true */
    WC_BITFIELD pathLengthSet:1;        /* CA basic const path length set */
    WC_BITFIELD weOwnAltNames:1;        /* altNames haven't been given to copy */
    WC_BITFIELD extKeyUsageSet:1;
    WC_BITFIELD extExtKeyUsageSet:1;    /* Extended Key Usage set */
#ifdef HAVE_OCSP
    WC_BITFIELD ocspNoCheckSet:1;       /* id-pkix-ocsp-nocheck set */
#endif
    WC_BITFIELD extCRLdistSet:1;
    WC_BITFIELD extAuthInfoSet:1;
    WC_BITFIELD extBasicConstSet:1;
    WC_BITFIELD extPolicyConstSet:1;
    WC_BITFIELD extPolicyConstRxpSet:1; /* requireExplicitPolicy set */
    WC_BITFIELD extPolicyConstIpmSet:1; /* inhibitPolicyMapping set */
    WC_BITFIELD extSubjAltNameSet:1;
    WC_BITFIELD inhibitAnyOidSet:1;
    WC_BITFIELD selfSigned:1;           /* Indicates subject and issuer are same */
#ifdef WOLFSSL_SEP
    WC_BITFIELD extCertPolicySet:1;
#endif
    WC_BITFIELD extCRLdistCrit:1;
    WC_BITFIELD extAuthInfoCrit:1;
    WC_BITFIELD extBasicConstCrit:1;
    WC_BITFIELD extPolicyConstCrit:1;
    WC_BITFIELD extSubjAltNameCrit:1;
    WC_BITFIELD extAuthKeyIdCrit:1;
#ifndef IGNORE_NAME_CONSTRAINTS
    WC_BITFIELD extNameConstraintCrit:1;
#endif
    WC_BITFIELD extSubjKeyIdCrit:1;
    WC_BITFIELD extKeyUsageCrit:1;
    WC_BITFIELD extExtKeyUsageCrit:1;
#ifdef WOLFSSL_SUBJ_DIR_ATTR
    WC_BITFIELD extSubjDirAttrSet:1;
#endif
#ifdef WOLFSSL_SUBJ_INFO_ACC
    WC_BITFIELD extSubjInfoAccSet:1;
#endif
#ifdef WOLFSSL_SEP
    WC_BITFIELD extCertPolicyCrit:1;
#endif
#ifdef WOLFSSL_CERT_REQ
    WC_BITFIELD isCSR:1;                /* Do we intend on parsing a CSR? */
#endif
#ifdef HAVE_RPK
    WC_BITFIELD isRPK:1;   /* indicate the cert is Raw-Public-Key cert in RFC7250 */
#endif
#ifdef WC_ASN_UNKNOWN_EXT_CB
    wc_UnknownExtCallback unknownExtCallback;
    wc_UnknownExtCallbackEx unknownExtCallbackEx;
    void *unknownExtCallbackExCtx;
#endif
#ifdef WOLFSSL_DUAL_ALG_CERTS
    /* Subject Alternative Public Key Info */
    byte *sapkiDer;
    int sapkiLen;
    word32 sapkiOID;
    /* Alternative Signature Algorithm */
    byte *altSigAlgDer;
    int altSigAlgLen;
    word32 altSigAlgOID;
    /* Alternative Signature Value */
    byte *altSigValDer;
    int altSigValLen;

    WC_BITFIELD extSapkiSet:1;
    WC_BITFIELD extAltSigAlgSet:1;
    WC_BITFIELD extAltSigValSet:1;
    WC_BITFIELD extSapkiCrit:1;
    WC_BITFIELD extAltSigAlgCrit:1;
    WC_BITFIELD extAltSigValCrit:1;
#endif /* WOLFSSL_DUAL_ALG_CERTS */

    WOLFSSL_AIA_ENTRY extAuthInfoList[WOLFSSL_MAX_AIA_ENTRIES];
    WC_BITFIELD extAuthInfoListSz:7;
    WC_BITFIELD extAuthInfoListOverflow:1;
};

#if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
    #define SIGNER_DIGEST_SIZE WC_SM3_DIGEST_SIZE
#elif defined(NO_SHA)
    #define SIGNER_DIGEST_SIZE WC_SHA256_DIGEST_SIZE
#else
    #define SIGNER_DIGEST_SIZE WC_SHA_DIGEST_SIZE
#endif

/* CA Signers */
/* if change layout change PERSIST_CERT_CACHE functions too */
struct Signer {
    word32  pubKeySize;
    word32  keyOID;                  /* key type */
    word16  keyUsage;
    byte    extKeyUsage;
    word16  maxPathLen;
    WC_BITFIELD selfSigned:1;
    const byte* publicKey;
    int     nameLen;
    const char*
            name;                    /* common name */
#ifndef IGNORE_NAME_CONSTRAINTS
    Base_entry* permittedNames;
    Base_entry* excludedNames;
#endif
    byte    subjectNameHash[SIGNER_DIGEST_SIZE];
                                     /* sha hash of names in certificate */
#if defined(HAVE_OCSP) || defined(HAVE_CRL) || defined(WOLFSSL_AKID_NAME)
    byte    issuerNameHash[SIGNER_DIGEST_SIZE];
                                    /* sha hash of issuer names in certificate.
                                    * Used in OCSP to check for authorized
                                    * responders. */
#endif
#ifndef NO_SKID
    byte    subjectKeyIdHash[SIGNER_DIGEST_SIZE];
                                    /* sha hash of key in certificate */
#endif
#ifdef HAVE_OCSP
    byte subjectKeyHash[KEYID_SIZE];
#endif
#if defined(WOLFSSL_AKID_NAME) || defined(HAVE_CRL)
    byte serialHash[SIGNER_DIGEST_SIZE]; /* serial number hash */
#endif
#ifdef WOLFSSL_SIGNER_DER_CERT
    DerBuffer* derCert;
#endif
#if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS)
    word32 cm_idx;
#endif
#ifdef WOLFSSL_DUAL_ALG_CERTS
    word32  sapkiOID; /* key type */
    byte*   sapkiDer;
    int     sapkiLen;
#endif /* WOLFSSL_DUAL_ALG_CERTS */
    byte type;

    Signer* next;
};


#ifdef WOLFSSL_TRUST_PEER_CERT
/* used for having trusted peer certs rather then CA */
struct TrustedPeerCert {
    int     nameLen;
    const char*
            name;                    /* common name */
    #ifndef IGNORE_NAME_CONSTRAINTS
        Base_entry* permittedNames;
        Base_entry* excludedNames;
    #endif /* IGNORE_NAME_CONSTRAINTS */
    byte    subjectNameHash[SIGNER_DIGEST_SIZE];
                                     /* sha hash of names in certificate */
    #ifndef WOLFSSL_NO_ISSUERHASH_TDPEER
    byte    issuerHash[SIGNER_DIGEST_SIZE];
                                    /* sha hash of issuer name in certificate */
    #endif
    #ifndef NO_SKID
        byte    subjectKeyIdHash[SIGNER_DIGEST_SIZE];
                                     /* sha hash of SKID in certificate */
    #endif
    word32 sigLen;
    byte*  sig;
    struct TrustedPeerCert* next;
};
#endif /* WOLFSSL_TRUST_PEER_CERT */


/* for testing or custom openssl wrappers */
#if defined(WOLFSSL_TEST_CERT) || defined(OPENSSL_EXTRA) || \
    defined(OPENSSL_EXTRA_X509_SMALL) || defined(WOLFSSL_PUBLIC_ASN)
    #define WOLFSSL_ASN_API WOLFSSL_API
#else
    #define WOLFSSL_ASN_API WOLFSSL_LOCAL
#endif

#ifdef HAVE_SMIME
#define MIME_HEADER_ASCII_MIN   33
#define MIME_HEADER_ASCII_MAX   126

typedef struct MimeParam MimeParam;
typedef struct MimeHdr MimeHdr;

struct MimeParam
{
    MimeParam*  next;
    char*       attribute;
    char*       value;
};

struct MimeHdr
{
    MimeHdr*    next;
    MimeParam*  params;
    char*       name;
    char*       body;
};

typedef enum MimeTypes
{
    MIME_HDR,
    MIME_PARAM
} MimeTypes;

typedef enum MimeStatus
{
    MIME_NAMEATTR,
    MIME_BODYVAL
} MimeStatus;
#endif /* HAVE_SMIME */

#ifdef WOLFSSL_API_PREFIX_MAP
    #define FreeAltNames wc_FreeAltNames
    #define AltNameNew wc_AltNameNew
    #define AltNameDup wc_AltNameDup
    #ifndef IGNORE_NAME_CONSTRAINTS
        #define FreeNameSubtrees wc_FreeNameSubtrees
    #endif
    #define InitDecodedCert wc_AsnApi_InitDecodedCert
    #define FreeDecodedCert wc_AsnApi_FreeDecodedCert
    #define ParseCert wc_AsnApi_ParseCert
    #define AddSignature wc_AddSignature
    #define ToTraditional wc_ToTraditional
    #define ToTraditional_ex wc_ToTraditional_ex
    #define UnTraditionalEnc wc_UnTraditionalEnc
    #define TraditionalEnc_ex wc_TraditionalEnc_ex
    #define TraditionalEnc wc_TraditionalEnc
    #define SetName wc_SetName
    #define GetShortInt wc_GetShortInt
    #define SetShortInt wc_SetShortInt
    #define GetLength wc_GetLength
    #define SetLength wc_SetLength
    #define SetSequence wc_SetSequence
    #define GetASNInt wc_GetASNInt
    #define GetASNTag wc_GetASNTag
    #define SetAlgoID wc_SetAlgoID
    #define SetAsymKeyDer wc_SetAsymKeyDer
    #define CalcHashId wc_CalcHashId
    #if defined(HAVE_OID_DECODING) || defined(WOLFSSL_ASN_PRINT) || \
        defined(OPENSSL_ALL)
        #define DecodeObjectId wc_DecodeObjectId
    #endif
    #if defined(WOLFSSL_AKID_NAME) && !defined(GetCAByAKID)
        /* GetCAByAKID() has two implementations, a full implementation in
         * src/ssl.c, and a dummy implementation in wolfcrypt/src/asn.c for
         * WOLFCRYPT_ONLY builds.
         */
        #define GetCAByAKID wolfSSL_GetCAByAKID
    #endif
    #define FillSigner wc_FillSigner
    #define MakeSigner wc_MakeSigner
    #define FreeSigner wc_FreeSigner
    #define AllocDer wc_AllocDer
    #define FreeDer wc_FreeDer
#endif /* WOLFSSL_API_PREFIX_MAP */

WOLFSSL_LOCAL int HashIdAlg(word32 oidSum);
WOLFSSL_TEST_VIS int CalcHashId(const byte* data, word32 len, byte* hash);
WOLFSSL_LOCAL int CalcHashId_ex(const byte* data, word32 len, byte* hash,
    int hashAlg);
WOLFSSL_LOCAL int GetHashId(const byte* id, int length, byte* hash,
    int hashAlg);
WOLFSSL_LOCAL int GetName(DecodedCert* cert, int nameType, int maxIdx);

#ifdef ASN_BER_TO_DER
WOLFSSL_API int wc_BerToDer(const byte* ber, word32 berSz, byte* der,
                                word32* derSz);
#endif
WOLFSSL_LOCAL int StreamOctetString(const byte* inBuf, word32 inBufSz,
    byte* out, word32* outSz, word32* idx);

WOLFSSL_ASN_API void FreeAltNames(DNS_entry* altNames, void* heap);
WOLFSSL_ASN_API DNS_entry* AltNameNew(void* heap);
WOLFSSL_ASN_API DNS_entry* AltNameDup(DNS_entry* from, void* heap);
#ifndef IGNORE_NAME_CONSTRAINTS
    WOLFSSL_ASN_API void FreeNameSubtrees(Base_entry* names, void* heap);
#endif /* IGNORE_NAME_CONSTRAINTS */
WOLFSSL_ASN_API void InitDecodedCert(DecodedCert* cert, const byte* source,
                                     word32 inSz, void* heap);
WOLFSSL_LOCAL void InitDecodedCert_ex(DecodedCert* cert, const byte* source,
                                     word32 inSz, void* heap, int devId);
WOLFSSL_ASN_API void FreeDecodedCert(DecodedCert* cert);
WOLFSSL_ASN_API int  ParseCert(DecodedCert* cert, int type, int verify,
                               void* cm);

#ifdef WC_ASN_UNKNOWN_EXT_CB
WOLFSSL_API int wc_SetUnknownExtCallback(DecodedCert* cert,
                                             wc_UnknownExtCallback cb);
WOLFSSL_API int wc_SetUnknownExtCallbackEx(DecodedCert* cert,
                                               wc_UnknownExtCallbackEx cb,
                                               void *ctx);
#endif

WOLFSSL_LOCAL int DecodePolicyOID(char *out, word32 outSz, const byte *in,
                                  word32 inSz);
WOLFSSL_LOCAL int EncodePolicyOID(byte *out, word32 *outSz,
                                  const char *in, void* heap);
WOLFSSL_LOCAL int DecodeExtensionType(const byte* input, word32 length,
                                      word32 oid, byte critical,
                                      DecodedCert* cert, int *isUnknownExt);
WOLFSSL_LOCAL int CheckCertSignaturePubKey(const byte* cert, word32 certSz,
        void* heap, const byte* pubKey, word32 pubKeySz, int pubKeyOID);
#if defined(OPENSSL_EXTRA) || defined(WOLFSSL_SMALL_CERT_VERIFY)
    WOLFSSL_API int wc_CheckCertSignature(const byte* cert, word32 certSz,
                                          void* heap, void* cm);
    /* Deprecated public API name kept for backwards build compatibility */
    #define CheckCertSignature(cert, certSz, heap, cm) \
        wc_CheckCertSignature(cert, certSz, heap, cm)

    WOLFSSL_API int wc_CheckCertSigPubKey(const byte* cert, word32 certSz,
                                        void* heap, const byte* pubKey,
                                        word32 pubKeySz, int pubKeyOID);
#endif /* OPENSSL_EXTRA || WOLFSSL_SMALL_CERT_VERIFY */

#if (defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) || \
    (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)))
WOLFSSL_LOCAL int wc_CertGetPubKey(const byte* cert, word32 certSz,
    const unsigned char** pubKey, word32* pubKeySz);
#endif
WOLFSSL_LOCAL 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);
#ifdef WOLFSSL_CERT_REQ
WOLFSSL_LOCAL int CheckCSRSignaturePubKey(const byte* cert, word32 certSz,
        void* heap, const byte* pubKey, word32 pubKeySz, int pubKeyOID);
#endif /* WOLFSSL_CERT_REQ */
WOLFSSL_ASN_API int AddSignature(byte* buf, int bodySz, const byte* sig, int sigSz,
                        int sigAlgoType);
WOLFSSL_LOCAL int ParseCertRelative(DecodedCert* cert, int type, int verify,
                                    void* cm, Signer *extraCa);
WOLFSSL_LOCAL int DecodeToKey(DecodedCert* cert, int verify);
#ifdef WOLFSSL_ASN_TEMPLATE
WOLFSSL_LOCAL int DecodeCert(DecodedCert* cert, int verify, int* criticalExt);
#endif

WOLFSSL_LOCAL int DecodeBasicCaConstraint(const byte* input, int sz,
                           byte *isCa, word16 *pathLength, byte *pathLengthSet);

WOLFSSL_LOCAL int DecodeSubjKeyId(const byte* input, word32 sz,
                            const byte **extSubjKeyId, word32 *extSubjKeyIdSz);

WOLFSSL_LOCAL int DecodeAuthKeyId(const byte* input, word32 sz,
            const byte **extAuthKeyId, word32 *extAuthKeyIdSz,
            const byte **extAuthKeyIdIssuer, word32 *extAuthKeyIdIssuerSz,
            const byte **extAuthKeyIdIssuerSN, word32 *extAuthKeyIdIssuerSNSz);

WOLFSSL_LOCAL int DecodeKeyUsage(const byte* input, word32 sz,
                                 word16 *extKeyUsage);

WOLFSSL_LOCAL int DecodeExtKeyUsage(const byte* input, word32 sz,
        const byte **extExtKeyUsageSrc, word32 *extExtKeyUsageSz,
        word32 *extExtKeyUsageCount, byte *extExtKeyUsage,
        byte *extExtKeyUsageSsh);

WOLFSSL_LOCAL int TryDecodeRPKToKey(DecodedCert* cert);
WOLFSSL_LOCAL int wc_GetPubX509(DecodedCert* cert, int verify, int* badDate);

WOLFSSL_LOCAL const byte* OidFromId(word32 id, word32 type, word32* oidSz);
WOLFSSL_LOCAL Signer* findSignerByKeyHash(Signer *list, byte *hash);
WOLFSSL_LOCAL Signer* findSignerByName(Signer *list, byte *hash);
WOLFSSL_TEST_VIS int FillSigner(Signer* signer, DecodedCert* cert, int type, DerBuffer *der);
WOLFSSL_TEST_VIS Signer* MakeSigner(void* heap);
WOLFSSL_TEST_VIS void    FreeSigner(Signer* signer, void* heap);
WOLFSSL_LOCAL void    FreeSignerTable(Signer** table, int rows, void* heap);
WOLFSSL_LOCAL void    FreeSignerTableType(Signer** table, int rows, byte type,
                                          void* heap);
#ifdef WOLFSSL_TRUST_PEER_CERT
WOLFSSL_LOCAL void    FreeTrustedPeer(TrustedPeerCert* tp, void* heap);
WOLFSSL_LOCAL void    FreeTrustedPeerTable(TrustedPeerCert** table, int rows,
                                           void* heap);
#endif /* WOLFSSL_TRUST_PEER_CERT */

WOLFSSL_ASN_API int ToTraditional(byte* input, word32 sz);
WOLFSSL_ASN_API int ToTraditional_ex(byte* input, word32 sz, word32* algId);
WOLFSSL_LOCAL int ToTraditionalInline(const byte* input, word32* inOutIdx,
                                      word32 sz);
WOLFSSL_LOCAL int ToTraditionalInline_ex(const byte* input, word32* inOutIdx,
                                         word32 sz, word32* algId);
WOLFSSL_LOCAL int ToTraditionalInline_ex2(const byte* input, word32* inOutIdx,
                                          word32 sz, word32* algId,
                                          word32* eccOid);
WOLFSSL_LOCAL int ToTraditionalEnc(byte* input, word32 sz, const char* password,
                     int passwordSz, word32* algId);
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);
WOLFSSL_ASN_API int TraditionalEnc_ex(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,
        int hmacOid, WC_RNG* rng, void* heap);
WOLFSSL_ASN_API 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);
WOLFSSL_LOCAL int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz);
WOLFSSL_LOCAL int EncryptContent(byte* input, word32 sz, byte* out, word32* outSz,
        const char* password,int passwordSz, int vPKCS, int vAlgo, int encAlgId,
        byte* salt, word32 saltSz, int itt, int hmacOid, WC_RNG* rng,
        void* heap);
WOLFSSL_LOCAL int wc_GetKeyOID(byte* key, word32 keySz, const byte** curveOID,
        word32* oidSz, int* algoID, void* heap);

typedef struct tm wolfssl_tm;
#ifdef WOLFSSL_ASN_TIME_STRING
WOLFSSL_LOCAL int GetTimeString(byte* date, int format, char* buf, int len,
                                int dateLen);
#endif
#if !defined(NO_ASN_TIME) && !defined(USER_TIME) && \
    !defined(TIME_OVERRIDES) && (defined(OPENSSL_EXTRA) || \
            defined(HAVE_PKCS7) || defined(HAVE_OCSP_RESPONDER))
WOLFSSL_LOCAL int GetFormattedTime(void* currTime, byte* buf, word32 len);
WOLFSSL_LOCAL int GetAsnTimeString(void* currTime, byte* buf, word32 len);
WOLFSSL_LOCAL int GetFormattedTime_ex(void* currTime, byte* buf, word32 len, byte format);
#endif
WOLFSSL_LOCAL int ExtractDate(const unsigned char* date, unsigned char format,
                                wolfssl_tm* certTime, int* idx, int len);
WOLFSSL_LOCAL int DateGreaterThan(const struct tm* a, const struct tm* b);
WOLFSSL_LOCAL int wc_ValidateDate(const byte* date, byte format, int dateType,
                                  int len);
#ifndef NO_ASN_TIME
WOLFSSL_LOCAL int wc_ValidateDateWithTime(const byte* date, byte format,
    int dateType, time_t checkTime, int len);
#endif
WOLFSSL_TEST_VIS int wc_AsnSetSkipDateCheck(int skip_p);
WOLFSSL_LOCAL int wc_AsnGetSkipDateCheck(void);
#ifdef HAVE_CRL
WOLFSSL_TEST_VIS int wc_ParseCRLReasonFromExtensions(const byte* ext,
                                                     word32 extSz,
                                                     int* reasonCode);
#endif

/* ASN.1 helper functions */
#ifdef WOLFSSL_CERT_GEN
WOLFSSL_LOCAL   int SetNameEx(byte* output, word32 outputSz, CertName* name, void* heap);
WOLFSSL_ASN_API int SetName(byte* output, word32 outputSz, CertName* name);
WOLFSSL_LOCAL const char* GetOneCertName(CertName* name, int idx);
WOLFSSL_LOCAL byte GetCertNameId(int idx);
#endif
WOLFSSL_TEST_VIS int GetShortInt(const byte* input, word32* inOutIdx,
        int* number, word32 maxIdx);
WOLFSSL_TEST_VIS int SetShortInt(byte* output, word32* inOutIdx, word32 number,
                              word32 maxIdx);

WOLFSSL_LOCAL const char* GetSigName(int oid);
WOLFSSL_ASN_API int GetLength(const byte* input, word32* inOutIdx, int* len,
                              word32 maxIdx);
WOLFSSL_LOCAL int GetLength_ex(const byte* input, word32* inOutIdx, int* len,
                           word32 maxIdx, int check);
WOLFSSL_LOCAL int GetASNHeader(const byte* input, byte tag, word32* inOutIdx,
                               int* len, word32 maxIdx);
WOLFSSL_LOCAL int GetSequence(const byte* input, word32* inOutIdx, int* len,
                             word32 maxIdx);
WOLFSSL_LOCAL int GetSequence_ex(const byte* input, word32* inOutIdx, int* len,
                           word32 maxIdx, int check);
WOLFSSL_TEST_VIS int wc_IndexSequenceOf(byte const * seqOf, word32 seqOfSz,
        size_t seqIndex, byte const ** out, word32 * outSz);
WOLFSSL_LOCAL int GetOctetString(const byte* input, word32* inOutIdx, int* len,
                         word32 maxIdx);
WOLFSSL_LOCAL int CheckBitString(const byte* input, word32* inOutIdx, int* len,
                          word32 maxIdx, int zeroBits, byte* unusedBits);
WOLFSSL_LOCAL int GetSet(const byte* input, word32* inOutIdx, int* len,
                        word32 maxIdx);
WOLFSSL_LOCAL int GetSet_ex(const byte* input, word32* inOutIdx, int* len,
                        word32 maxIdx, int check);
WOLFSSL_LOCAL int GetMyVersion(const byte* input, word32* inOutIdx,
                              int* version, word32 maxIdx);
WOLFSSL_LOCAL int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx,
                         word32 maxIdx);
WOLFSSL_ASN_API int GetASNInt(const byte* input, word32* inOutIdx, int* len,
                              word32 maxIdx);

WOLFSSL_LOCAL word32 wc_oid_sum(const byte* input, int length);

#ifdef HAVE_OID_ENCODING
    WOLFSSL_API int wc_EncodeObjectId(const word16* in, word32 inSz,
        byte* out, word32* outSz);
    WOLFSSL_LOCAL int EncodeObjectId(const word16* in, word32 inSz,
        byte* out, word32* outSz);
#endif
#if defined(HAVE_OID_DECODING) || defined(WOLFSSL_ASN_PRINT) || \
    defined(OPENSSL_ALL)
    WOLFSSL_TEST_VIS int DecodeObjectId(const byte* in, word32 inSz,
        word16* out, word32* outSz);
#endif
WOLFSSL_LOCAL int GetASNObjectId(const byte* input, word32* inOutIdx, int* len,
                                 word32 maxIdx);
WOLFSSL_LOCAL int SetObjectId(int len, byte* output);
WOLFSSL_LOCAL int GetObjectId(const byte* input, word32* inOutIdx, word32* oid,
                              word32 oidType, word32 maxIdx);
WOLFSSL_LOCAL int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid,
                           word32 oidType, word32 maxIdx);
WOLFSSL_LOCAL int GetAlgoIdEx(const byte* input, word32* inOutIdx, word32* oid,
                     word32 oidType, word32 maxIdx, byte *absentParams);
WOLFSSL_ASN_API int GetASNTag(const byte* input, word32* inOutIdx, byte* tag,
                              word32 maxIdx);
WOLFSSL_LOCAL int GetASN_BitString(const byte* input, word32 idx, int length);

WOLFSSL_LOCAL word32 SetASNLength(word32 length, byte* output);
WOLFSSL_LOCAL word32 SetASNSequence(word32 len, byte* output);
WOLFSSL_LOCAL word32 SetASNOctetString(word32 len, byte* output);
WOLFSSL_LOCAL word32 SetASNImplicit(byte tag,byte number, word32 len,
                                    byte* output);
WOLFSSL_LOCAL word32 SetASNExplicit(byte number, word32 len, byte* output);
WOLFSSL_LOCAL word32 SetASNSet(word32 len, byte* output);

WOLFSSL_ASN_API word32 SetLength(word32 length, byte* output);
WOLFSSL_LOCAL word32 SetLengthEx(word32 length, byte* output, byte isIndef);
WOLFSSL_LOCAL word32 SetHeader(byte tag, word32 len, byte* output,
                               byte isIndef);
WOLFSSL_ASN_API word32 SetSequence(word32 len, byte* output);
WOLFSSL_LOCAL word32 SetSequenceEx(word32 len, byte* output, byte isIndef);
WOLFSSL_LOCAL word32 SetIndefEnd(byte* output);
WOLFSSL_LOCAL word32 SetOctetString(word32 len, byte* output);
WOLFSSL_LOCAL word32 SetOctetStringEx(word32 len, byte* output, byte indef);
WOLFSSL_LOCAL int SetASNInt(int len, byte firstByte, byte* output);
WOLFSSL_LOCAL word32 SetBitString(word32 len, byte unusedBits, byte* output);
WOLFSSL_LOCAL word32 SetImplicit(byte tag,byte number,word32 len,byte* output,
        byte isIndef);
WOLFSSL_LOCAL word32 SetExplicit(byte number, word32 len, byte* output,
    byte isIndef);
WOLFSSL_LOCAL word32 SetSet(word32 len, byte* output);
WOLFSSL_API word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz);
WOLFSSL_LOCAL word32 SetAlgoIDEx(int algoOID, byte* output, int type, int curveSz,
                                byte absentParams);
#if defined(WC_RSA_PSS) && !defined(NO_RSA)
WOLFSSL_LOCAL word32 wc_EncodeRsaPssAlgoId(int hashOID, int saltLen, byte* out,
                                           word32 outSz);
WOLFSSL_TEST_VIS int wc_DecodeRsaPssParams(const byte* params, word32 sz,
    enum wc_HashType* hash, int* mgf, int* saltLen);
#endif
WOLFSSL_LOCAL int SetMyVersion(word32 version, byte* output, int header);
WOLFSSL_LOCAL int SetSerialNumber(const byte* sn, word32 snSz, byte* output,
    word32 outputSz, int maxSnSz);
/* name is of type WOLFSSL_ASN1_OTHERNAME; use void* to avoid including ssl.h */
WOLFSSL_LOCAL word32 SetOthername(void *name, byte *output);

#ifndef WOLFSSL_ASN_TEMPLATE
WOLFSSL_LOCAL int wc_GetSerialNumber(const byte* input, word32* inOutIdx,
    byte* serial, int* serialSz, word32 maxIdx);
#endif
WOLFSSL_LOCAL int GetNameHash(const byte* source, word32* idx, byte* hash,
                              int maxIdx);
WOLFSSL_LOCAL int GetNameHash_ex(const byte* source, word32* idx, byte* hash,
                                 int maxIdx, word32 sigOID);
WOLFSSL_LOCAL int wc_CheckPrivateKeyCert(const byte* key, word32 keySz,
                                         DecodedCert* der, int checkAlt,
                                         void* heap);
WOLFSSL_LOCAL int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz,
                                     const byte* pubKey, word32 pubKeySz,
                                     enum Key_Sum ks, void* heap);
WOLFSSL_LOCAL int StoreDHparams(byte* out, word32* outLen, mp_int* p, mp_int* g);
#ifdef WOLFSSL_DH_EXTRA
WOLFSSL_API int wc_DhPublicKeyDecode(const byte* input, word32* inOutIdx,
                        DhKey* key, word32 inSz);
#endif
WOLFSSL_LOCAL int FlattenAltNames(byte* output, word32 outputSz,
                                  const DNS_entry* names);

WOLFSSL_LOCAL int wc_EncodeName(EncodedName* name, const char* nameStr,
        char nameType, byte type);
WOLFSSL_LOCAL int wc_EncodeNameCanonical(EncodedName* name, const char* nameStr,
                                char nameType, byte type);

#if defined(HAVE_ECC) || !defined(NO_DSA)
    /* ASN sig helpers */
    WOLFSSL_LOCAL int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r,
                                      mp_int* s);
    WOLFSSL_LOCAL int StoreECC_DSA_Sig_Bin(byte* out, word32* outLen,
        const byte* r, word32 rLen, const byte* s, word32 sLen);
    WOLFSSL_LOCAL int DecodeECC_DSA_Sig_Bin(const byte* sig, word32 sigLen,
        byte* r, word32* rLen, byte* s, word32* sLen);
    WOLFSSL_LOCAL int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen,
                                       mp_int* r, mp_int* s);
    WOLFSSL_LOCAL int DecodeECC_DSA_Sig_Ex(const byte* sig, word32 sigLen,
                                       mp_int* r, mp_int* s, int init);
#endif
#ifndef NO_DSA
WOLFSSL_LOCAL int StoreDSAParams(byte*, word32*, const mp_int*, const mp_int*,
    const mp_int*);
#endif

WOLFSSL_LOCAL void InitSignatureCtx(SignatureCtx* sigCtx, void* heap, int devId);
WOLFSSL_LOCAL void FreeSignatureCtx(SignatureCtx* sigCtx);

#ifdef WC_ENABLE_ASYM_KEY_EXPORT
WOLFSSL_LOCAL int SetAsymKeyDerPublic(const byte* pubKey, word32 pubKeyLen,
    byte* output, word32 outLen, int keyType, int withHeader);
#endif /* WC_ENABLE_ASYM_KEY_EXPORT */
#ifdef WC_ENABLE_ASYM_KEY_IMPORT
WOLFSSL_LOCAL int DecodeAsymKeyPublic_Assign(const byte* input,
    word32* inOutIdx, word32 inSz, const byte** pubKey, word32* pubKeyLen,
    int* keyType);

WOLFSSL_LOCAL int DecodeAsymKeyPublic(const byte* input, word32* inOutIdx,
    word32 inSz, byte* pubKey, word32* pubKeyLen, int keyType);
#endif /* WC_ENABLE_ASYM_KEY_IMPORT */

#ifndef NO_CERTS

WOLFSSL_LOCAL int wc_EncryptedInfoParse(EncryptedInfo* info,
                                        const char** pBuffer, size_t bufSz);

WOLFSSL_LOCAL int PemToDer(const unsigned char* buff, long longSz, int type,
                          DerBuffer** pDer, void* heap, EncryptedInfo* info,
                          int* keyFormat);
WOLFSSL_API int AllocDer(DerBuffer** der, word32 length, int type,
    void* heap);
WOLFSSL_LOCAL int AllocCopyDer(DerBuffer** der, const unsigned char* buff,
    word32 length, int type, void* heap);
WOLFSSL_API void FreeDer(DerBuffer** der);

#ifdef WOLFSSL_ASN_PARSE_KEYUSAGE
WOLFSSL_LOCAL int ParseKeyUsageStr(const char* value, word16* keyUsage,
        void* heap);
WOLFSSL_LOCAL int ParseExtKeyUsageStr(const char* value, byte* extKeyUsage,
        void* heap);
#endif

#endif /* !NO_CERTS */

#ifdef HAVE_SMIME
WOLFSSL_LOCAL int wc_MIME_parse_headers(char* in, int inLen, MimeHdr** hdrs);
WOLFSSL_LOCAL int wc_MIME_header_strip(char* in, char** out, size_t start, size_t end);
WOLFSSL_LOCAL MimeHdr* wc_MIME_find_header_name(const char* name, MimeHdr* hdr);
WOLFSSL_LOCAL MimeParam* wc_MIME_find_param_attr(const char* attribute, MimeParam* param);
WOLFSSL_LOCAL char* wc_MIME_single_canonicalize(const char* line, word32* len);
WOLFSSL_LOCAL int wc_MIME_free_hdrs(MimeHdr* head);
#endif /* HAVE_SMIME */

#ifdef WOLFSSL_CERT_GEN

enum cert_enums {
    RSA_KEY                  = 10,
    ECC_KEY                  = 12,
    ED25519_KEY              = 13,
    ED448_KEY                = 14,
    DSA_KEY                  = 15,
    FALCON_LEVEL1_KEY        = 16,
    FALCON_LEVEL5_KEY        = 17,
    DILITHIUM_LEVEL2_KEY     = 18,
    DILITHIUM_LEVEL3_KEY     = 19,
    DILITHIUM_LEVEL5_KEY     = 20,
    ML_DSA_LEVEL2_KEY        = 21,
    ML_DSA_LEVEL3_KEY        = 22,
    ML_DSA_LEVEL5_KEY        = 23,
    SPHINCS_FAST_LEVEL1_KEY  = 24,
    SPHINCS_FAST_LEVEL3_KEY  = 25,
    SPHINCS_FAST_LEVEL5_KEY  = 26,
    SPHINCS_SMALL_LEVEL1_KEY = 27,
    SPHINCS_SMALL_LEVEL3_KEY = 28,
    SPHINCS_SMALL_LEVEL5_KEY = 29
};

#endif /* WOLFSSL_CERT_GEN */

/* hashes type for asn */
typedef struct AsnHashes {
    #if !defined(NO_MD5)
        byte md5[WC_MD5_DIGEST_SIZE];
    #endif
    #if !defined(NO_SHA)
        byte sha[WC_SHA_DIGEST_SIZE];
    #endif
    #ifndef NO_SHA256
        byte sha256[WC_SHA256_DIGEST_SIZE];
    #endif
    #ifdef WOLFSSL_SHA384
        byte sha384[WC_SHA384_DIGEST_SIZE];
    #endif
    #ifdef WOLFSSL_SHA512
        byte sha512[WC_SHA512_DIGEST_SIZE];
    #endif
    #ifdef WOLFSSL_SM3
        byte sm3[WC_SM3_DIGEST_SIZE];
    #endif
} AsnHashes;

WOLFSSL_LOCAL int AsnHashesHash(AsnHashes* hashes, const byte* data, word32 dataSz);
WOLFSSL_LOCAL const byte* AsnHashesGetHash(const AsnHashes* hashes, int hashAlg,
    int* size);

/* for pointer use */
typedef struct CertStatus CertStatus;

#ifdef HAVE_OCSP

enum Ocsp_Response_Status {
    OCSP_SUCCESSFUL        = 0, /* Response has valid confirmations */
    OCSP_MALFORMED_REQUEST = 1, /* Illegal confirmation request */
    OCSP_INTERNAL_ERROR    = 2, /* Internal error in issuer */
    OCSP_TRY_LATER         = 3, /* Try again later */
    OCSP_SIG_REQUIRED      = 5, /* Must sign the request (4 is skipped) */
    OCSP_UNAUTHORIZED      = 6  /* Request unauthorized */
};


enum Ocsp_Cert_Status {
    CERT_GOOD    = 0,
    CERT_REVOKED = 1,
    CERT_UNKNOWN = 2
};


#ifdef OPENSSL_EXTRA
enum Ocsp_Verify_Error {
    OCSP_VERIFY_ERROR_NONE = 0,
    OCSP_BAD_ISSUER = 1
};
#endif


typedef struct OcspRequest  OcspRequest;
typedef struct OcspResponse OcspResponse;


struct CertStatus {
    CertStatus* next;

    byte serial[EXTERNAL_SERIAL_SIZE];
    int serialSz;
#ifdef OPENSSL_EXTRA
    WOLFSSL_ASN1_INTEGER* serialInt;
#endif

    int status;

    byte thisDate[MAX_DATE_SIZE];
    byte thisDateSz;
    byte nextDate[MAX_DATE_SIZE];
    byte nextDateSz;
    byte thisDateFormat;
    byte nextDateFormat;
#ifdef WOLFSSL_OCSP_PARSE_STATUS
    WOLFSSL_ASN1_TIME thisDateParsed;
    WOLFSSL_ASN1_TIME nextDateParsed;
    const byte* thisDateAsn;
    const byte* nextDateAsn;
#endif
    byte revocationDate[MAX_DATE_SIZE]; /* ASN-formatted revocation time */
    word32 revocationDateSz;
    byte revocationReason;              /* CRL reason code */

    byte*  rawOcspResponse;
    word32 rawOcspResponseSz;
};

typedef struct OcspEntry OcspEntry;

#if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
#define OCSP_DIGEST WC_HASH_TYPE_SM3
#elif defined(NO_SHA)
#define OCSP_DIGEST WC_HASH_TYPE_SHA256
#else
#define OCSP_DIGEST WC_HASH_TYPE_SHA
#endif

#if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
#define OCSP_DIGEST_SIZE WC_SM3_DIGEST_SIZE
#elif defined(NO_SHA)
#define OCSP_DIGEST_SIZE WC_SHA256_DIGEST_SIZE
#else
#define OCSP_DIGEST_SIZE WC_SHA_DIGEST_SIZE
#endif

struct OcspEntry
{
    OcspEntry *next;                      /* next entry                */
    word32 hashAlgoOID;                   /* hash algo ID              */
    byte issuerHash[WC_MAX_DIGEST_SIZE];    /* issuer hash               */
    byte issuerKeyHash[WC_MAX_DIGEST_SIZE]; /* issuer public key hash    */
    CertStatus *status;                   /* OCSP response list        */
    int totalStatus;                      /* number on list            */
    byte* rawCertId;                      /* raw bytes of the CertID   */
    int rawCertIdSize;                    /* num bytes in raw CertID   */
    /* option bits - using 32-bit for alignment */
    WC_BITFIELD ownStatus:1;              /* do we need to free the status
                                           * response list */
    WC_BITFIELD isDynamic:1;              /* was dynamically allocated */
    WC_BITFIELD used:1;                   /* entry used                */
};

#define OCSP_RESPONDER_ID_KEY_SZ 20
#if !defined(NO_SHA)
#define OCSP_RESPONDER_ID_HASH_TYPE WC_SHA
#else
#define OCSP_RESPONDER_ID_HASH_TYPE WC_SHA256
#endif
enum responderIdType {
    OCSP_RESPONDER_ID_INVALID = 0,
    OCSP_RESPONDER_ID_NAME = 1,
    OCSP_RESPONDER_ID_KEY  = 2
};
/* TODO: Long-term, it would be helpful if we made this struct and other OCSP
         structs conform to the ASN spec as described in RFC 6960. It will help
         with readability and with implementing OpenSSL compatibility API
         functions, because OpenSSL's OCSP data structures conform to the
         RFC. */
struct OcspResponse {
    int     responseStatus;  /* return code from Responder */

    const byte*
            response;        /* Pointer to beginning of OCSP Response */
    word32  responseSz;      /* length of the OCSP Response */

    enum responderIdType responderIdType;
    union {
        byte keyHash[OCSP_RESPONDER_ID_KEY_SZ];
        byte nameHash[KEYID_SIZE];
    } responderId ;

    byte    producedDate[MAX_DATE_SIZE];
                             /* Date at which this response was signed */
    byte    producedDateFormat; /* format of the producedDate */
    byte    producedDateSz;

    const byte*
            cert;
    word32  certSz;

    const byte*
            sig;             /* Pointer to sig in source */
    word32  sigSz;           /* Length in octets for the sig */
    word32  sigOID;          /* OID for hash used for sig */

    const byte*
            sigParams;
    word32  sigParamsSz;

    OcspEntry* single;       /* chain of OCSP single responses */

    const byte*
            nonce;           /* pointer to nonce inside ASN.1 response */
    int     nonceSz;         /* length of the nonce string */

    byte*   source;          /* pointer to source buffer, not owned */
    word32  maxIdx;          /* max offset based on init size */
    Signer* pendingCAs;
    void*  heap;
};


struct OcspRequest {
    byte   issuerHash[WC_MAX_DIGEST_SIZE];
    byte   issuerKeyHash[WC_MAX_DIGEST_SIZE];
    int    hashAlg;  /* Hash_Sum OID, e.g. SHAh, SHA256h */
    byte*  serial;   /* copy of the serial number in source cert */
    int    serialSz;
#ifdef OPENSSL_EXTRA
    WOLFSSL_ASN1_INTEGER* serialInt;
    void* cid; /* WOLFSSL_OCSP_CERTID kept to free */
#endif
    byte*  url;      /* copy of the extAuthInfo in source cert */
    int    urlSz;

    byte   nonce[MAX_OCSP_NONCE_SZ];
    int    nonceSz;
    void*  heap;
    void*  ssl;
};

WOLFSSL_LOCAL void InitOcspResponse(OcspResponse* resp, OcspEntry* single,
                     CertStatus* status, byte* source, word32 inSz, void* heap);
WOLFSSL_LOCAL void FreeOcspResponse(OcspResponse* resp);
WOLFSSL_LOCAL int OcspResponseEncode(OcspResponse* resp, byte* out, word32* outSz,
        RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng);
WOLFSSL_LOCAL int OcspResponseDecode(OcspResponse* resp, void* cm, void* heap,
                                     int noVerifyCert, int noVerifySignature);

WOLFSSL_LOCAL int    InitOcspRequest(OcspRequest* req, DecodedCert* cert,
                                     byte useNonce, void* heap);
WOLFSSL_LOCAL void   FreeOcspRequest(OcspRequest* req);
WOLFSSL_LOCAL int    EncodeOcspRequest(OcspRequest* req, byte* output,
                                       word32 size);
WOLFSSL_LOCAL int DecodeOcspRequest(OcspRequest* req, const byte* input,
                                    word32 size);
WOLFSSL_LOCAL word32 EncodeOcspRequestExtensions(OcspRequest* req, byte* output,
                                                 word32 size);


WOLFSSL_LOCAL int  CompareOcspReqResp(OcspRequest* req, OcspResponse* resp);
WOLFSSL_LOCAL int OcspDecodeCertID(const byte* input, word32* inOutIdx, word32 inSz,
                 OcspEntry* entry);

#ifdef HAVE_OCSP_RESPONDER
/* Revocation reason codes from RFC 5280 */
enum WC_CRL_Reason {
    WC_CRL_REASON_UNSPECIFIED             = 0,
    WC_CRL_REASON_KEY_COMPROMISE          = 1,
    WC_CRL_REASON_CA_COMPROMISE           = 2,
    WC_CRL_REASON_AFFILIATION_CHANGED     = 3,
    WC_CRL_REASON_SUPERSEDED              = 4,
    WC_CRL_REASON_CESSATION_OF_OPERATION  = 5,
    WC_CRL_REASON_CERTIFICATE_HOLD        = 6,
    /* value 7 is not used */
    WC_CRL_REASON_REMOVE_FROM_CRL         = 8,
    WC_CRL_REASON_PRIVILEGE_WITHDRAWN     = 9,
    WC_CRL_REASON_AA_COMPROMISE           = 10
};

/* Certificate status entry for a single certificate */
typedef struct OcspResponderCertStatus OcspResponderCertStatus;
struct OcspResponderCertStatus {
    byte serial[EXTERNAL_SERIAL_SIZE];
    int serialSz;
    enum Ocsp_Cert_Status status;        /* CERT_GOOD, CERT_REVOKED, CERT_UNKNOWN */
    byte revocationDate[MAX_DATE_SIZE];  /* ASN-formatted revocation time (if REVOKED) */
    word32 revocationDateSz;             /* Size of revocation date */
    enum WC_CRL_Reason revocationReason; /* Reason for revocation */
    word32 validityPeriod;               /* Validity period in seconds (for CERT_GOOD) */
    OcspResponderCertStatus* next;
};

/* CA entry with its certificates and key */
typedef struct OcspResponderCa OcspResponderCa;
struct OcspResponderCa {
    char subject[WC_ASN_NAME_MAX];   /* CA subject name for lookup */

    union {
#ifndef NO_RSA
        struct RsaKey rsa;
#endif
#ifdef HAVE_ECC
        struct ecc_key ecc;
#endif
    } key;                           /* private key for signing */
    enum Key_Sum keyType;            /* Type of key */

    AsnHashes issuerHashes;          /* Hashes of CA's subject DN */
    AsnHashes issuerKeyHashes;       /* Hashes of CA's public key */

    byte responderKeyHash[WC_SHA_DIGEST_SIZE]; /* Hash of the responder's public key */

    byte* certDer;                   /* Raw DER certificate (if sendCerts enabled) */
    word32 certDerSz;                /* Size of certificate DER */

    OcspResponderCertStatus* statuses; /* List of certificate statuses for this CA */

    OcspResponderCa* next;           /* Next Auth CA in list */

    WC_BITFIELD authResp:1;          /* Is the cert an authorized responder */
};

typedef struct OcspResponder OcspResponder;
struct OcspResponder {
    OcspResponderCa* caList;         /* List of CAs this responder handles */
    void* heap;
    WC_RNG rng;                      /* RNG for signing responses */
    WC_BITFIELD sendCerts:1;         /* Whether to include CA in responses */
};
#endif /* HAVE_OCSP_RESPONDER */

#endif /* HAVE_OCSP */


/* for pointer use */
typedef struct RevokedCert RevokedCert;

#ifdef HAVE_CRL

struct RevokedCert {
    byte         serialNumber[EXTERNAL_SERIAL_SIZE];
    int          serialSz;
    RevokedCert* next;
    byte         revDate[MAX_DATE_SIZE];
    byte         revDateFormat;
    int          reasonCode;     /* CRL reason code, -1 if absent */
#if defined(OPENSSL_EXTRA)
    byte*        extensions;     /* raw DER of crlEntryExtensions */
    word32       extensionsSz;
#endif
};

#ifndef CRL_MAX_NUM_SZ
#define CRL_MAX_NUM_SZ 20 /* RFC5280 states that CRL number can be up to 20 */
#endif                    /* octets long */

#define CRL_MAX_NUM_HEX_STR_SZ (CRL_MAX_NUM_SZ * 2 + 1)
#define CRL_MAX_NUM_SZ_BITS    (CRL_MAX_NUM_SZ * CHAR_BIT)

typedef struct DecodedCRL DecodedCRL;

struct DecodedCRL {
    word32  certBegin;               /* offset to start of cert          */
    word32  sigIndex;                /* offset to start of signature     */
    word32  sigLength;               /* length of signature              */
    word32  signatureOID;            /* sum of algorithm object id       */
#ifdef WC_RSA_PSS
    word32  sigParamsIndex;          /* start of signature parameters    */
    word32  sigParamsLength;         /* length of signature parameters   */
#endif
    const byte*
            signature;             /* pointer into raw source, not owned */
    char    crlNumber[CRL_MAX_NUM_HEX_STR_SZ];   /* CRL number extension */
    byte    issuerHash[SIGNER_DIGEST_SIZE]; /* issuer name hash          */
    byte    crlHash[SIGNER_DIGEST_SIZE]; /* raw crl data hash            */
    byte    lastDate[MAX_DATE_SIZE]; /* last date updated  */
    byte    nextDate[MAX_DATE_SIZE]; /* next update date   */
    byte    lastDateFormat;          /* format of last date */
    byte    nextDateFormat;          /* format of next date */
    RevokedCert* certs;              /* revoked cert list  */
#if defined(OPENSSL_EXTRA)
    byte*   issuer;                  /* full name including common name  */
    word32  issuerSz;                /* length of the issuer             */
#endif
    int          totalCerts;         /* number on list     */
    int          version;            /* version of cert    */
    void*   heap;
#ifndef NO_SKID
    byte        extAuthKeyId[SIGNER_DIGEST_SIZE]; /* Authority Key ID */
    WC_BITFIELD extAuthKeyIdSet:1;       /* Auth key identifier set indicator */
#endif
    WC_BITFIELD crlNumberSet:1;          /* CRL number set indicator */
};

WOLFSSL_LOCAL void InitDecodedCRL(DecodedCRL* dcrl, void* heap);
WOLFSSL_LOCAL int VerifyCRL_Signature(SignatureCtx* sigCtx,
                                      const byte* toBeSigned, word32 tbsSz,
                                      const byte* signature, word32 sigSz,
                                      word32 signatureOID, const byte* sigParams,
                                      int sigParamsSz, Signer *ca, void* heap);
WOLFSSL_LOCAL int ParseCRL(RevokedCert* rcert, DecodedCRL* dcrl,
                           const byte* buff, word32 sz, int verify, void* cm);
WOLFSSL_LOCAL void FreeDecodedCRL(DecodedCRL* dcrl);

#endif /* HAVE_CRL */

#if defined(WOLFSSL_ACERT)
/* Minimal structure for x509 attribute certificate (rfc 5755).
 *
 * The attributes field is not parsed, but is stored as raw buffer.
 * */
struct DecodedAcert {
    word32       certBegin; /* Offset to start of acert. */
    word32       sigIndex; /* Offset to start of signature. */
    word32       sigLength; /* Signature length. */
    word32       signatureOID; /* Sum of algorithm object id. */
#ifdef WC_RSA_PSS
    word32       sigParamsIndex; /* start of signature parameters */
    word32       sigParamsLength; /* length of signature parameters */
#endif
    const byte * signature; /* Not owned, points into raw acert.  */
    const byte * source; /* Byte buffer holding acert, NOT owned. */
    word32       srcIdx; /* Current offset into buffer. */
    word32       maxIdx; /* Max allowed offset. Set in init. */
    void *       heap; /* For user memory overrides. */
    int          version; /* attribute cert version. */
    byte         serial[EXTERNAL_SERIAL_SIZE];  /* Raw serial number. */
    int          serialSz;
    const byte * beforeDate; /* Before and After dates. */
    int          beforeDateLen;
    const byte * afterDate;
    int          afterDateLen;
    byte         holderSerial[EXTERNAL_SERIAL_SIZE];
    int          holderSerialSz;
    DNS_entry *  holderEntityName;  /* Holder entityName from ACERT */
    DNS_entry *  holderIssuerName;  /* Holder issuerName from ACERT */
    DNS_entry *  AttCertIssuerName; /* AttCertIssuer name from ACERT */
    const byte * rawAttr; /* Not owned, points into raw acert. */
    word32       rawAttrLen;
    SignatureCtx sigCtx;
};

typedef struct DecodedAcert DecodedAcert;

WOLFSSL_LOCAL void InitDecodedAcert(DecodedAcert* acert,
                                    const byte* source, word32 inSz,
                                    void* heap);
WOLFSSL_LOCAL void FreeDecodedAcert(DecodedAcert * acert);
WOLFSSL_LOCAL int  ParseX509Acert(DecodedAcert* cert, int verify);
WOLFSSL_LOCAL int  VerifyX509Acert(const byte* cert, word32 certSz,
                                   const byte* pubKey, word32 pubKeySz,
                                   int pubKeyOID, void * heap);
#endif /* WOLFSSL_ACERT */


#ifndef IGNORE_NAME_CONSTRAINTS
WOLFSSL_TEST_VIS int  wolfssl_local_MatchBaseName(int type, const char* name,
                                                  int nameSz, const char* base,
                                                  int baseSz);
WOLFSSL_TEST_VIS int  wolfssl_local_MatchIpSubnet(const byte* ip, int ipSz,
                                                  const byte* constraint,
                                                  int constraintSz);
#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_FALCON) || defined(HAVE_DILITHIUM) || defined(HAVE_SPHINCS))
WOLFSSL_LOCAL int DecodeAsymKey_Assign(const byte* input, word32* inOutIdx,
    word32 inSz, const byte** seed, word32* seedLen, const byte** privKey,
    word32* privKeyLen, const byte** pubKey, word32* pubKeyLen,
    int* inOutKeyType);

WOLFSSL_LOCAL int DecodeAsymKey(const byte* input, word32* inOutIdx,
    word32 inSz, byte* privKey, word32* privKeyLen, byte* pubKey,
    word32* pubKeyLen, int keyType);
#endif

#ifdef WC_ENABLE_ASYM_KEY_EXPORT
WOLFSSL_TEST_VIS int SetAsymKeyDer(const byte* privKey, word32 privKeyLen,
    const byte* pubKey, word32 pubKeyLen, byte* output, word32 outLen,
    int keyType);
#endif

#endif /* !NO_ASN */

#if !defined(NO_ASN) || !defined(NO_PWDBASED)

#ifndef PKCS_MAX_KEY_SIZE
    #define PKCS_MAX_KEY_SIZE    64  /* MAX PKCS Key length */
#endif
#if !defined(WOLFSSL_GAME_BUILD) && !defined(MAX_KEY_SIZE)
    /* for backwards compatibility */
    #define MAX_KEY_SIZE PKCS_MAX_KEY_SIZE
#endif
#ifndef MAX_UNICODE_SZ
    #define MAX_UNICODE_SZ  256
#endif

enum PBESTypes {
    PBE_MD5_DES        = 0,
    PBE_SHA1_RC4_128   = 1,
    PBE_SHA1_DES       = 2,
    PBE_SHA1_DES3      = 3,
    PBE_AES256_CBC     = 4,
    PBE_AES128_CBC     = 5,
    PBE_SHA1_40RC2_CBC = 6,

    PBE_SHA1_RC4_128_SUM   = 657,
    PBE_SHA1_DES3_SUM      = 659,
    PBE_SHA1_40RC2_CBC_SUM = 662,
    PBE_MD5_DES_SUM        = 651,
    PBE_SHA1_DES_SUM       = 658,
    PBES2_SUM              = 661,

    PBES2              = 13,       /* algo ID */
    PBES1_MD5_DES      = 3,
    PBES1_SHA1_DES     = 10,

    PBE_NONE           = 999
};

enum PKCSTypes {
    PKCS5v2             =   6,     /* PKCS #5 v2.0 */
    PKCS12v1            =  12,     /* PKCS #12 */
    PKCS5               =   5,     /* PKCS oid tag */
    PKCS8v0             =   0,     /* default PKCS#8 version */
    PKCS8v1             =   1,     /* PKCS#8 version including public key */
    PKCS1v0             =   0,     /* default PKCS#1 version */
    PKCS1v1             =   1     /* Multi-prime version */
};

#endif /* !NO_ASN || !NO_PWDBASED */

#ifdef __cplusplus
    } /* extern "C" */
#endif

#endif /* WOLFSSL_OBJ_MAC_H_ */
#endif /* !NO_ASN || !NO_PWDBASED */

#endif /* WOLF_CRYPT_ASN_H */