synta-certificate 0.2.6

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

#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(feature = "alloc")]
extern crate alloc;

// Test module for lifetime issues
mod test_lifetime;

// RFC 7512 PKCS#11 URI parser (crate-private).
pub(crate) mod pkcs11_uri;
/// RFC 7512 `pkcs11:` URI — holds the verbatim URI string and decoded
/// attributes (token label, object label, CKA_ID, PIN).  Returned by
/// [`Pkcs11Uri`] for HSM-backed keys.
pub use pkcs11_uri::{merge_object_label, pct_encode_path, Pkcs11Uri, Pkcs11UriAttributes};

// PKCS#11 token management (slot listing, key find/list/delete/generate-in-token).
#[cfg(feature = "pkcs11-mgmt")]
pub mod pkcs11_mgmt;
#[cfg(feature = "pkcs11-mgmt")]
pub use crypto::token_manager::{Pkcs11KeyInfo, SlotInfo, TokenManager};

/// Return a [`Pkcs11Manager`] using the active module (resolved from
/// `PKCS11_MODULE_PATH` env var or `/usr/lib64/pkcs11/p11-kit-proxy.so`).
///
/// [`Pkcs11Manager`]: pkcs11_mgmt::Pkcs11Manager
#[cfg(feature = "pkcs11-mgmt")]
pub fn pkcs11_manager() -> Result<pkcs11_mgmt::Pkcs11Manager, crypto::PrivateKeyError> {
    pkcs11_mgmt::Pkcs11Manager::from_env()
}

/// List all PKCS#11 token slots using the active module.
///
/// Equivalent to `pkcs11_manager()?.list_slots()`.
#[cfg(feature = "pkcs11-mgmt")]
pub fn list_pkcs11_slots() -> Result<Vec<SlotInfo>, crypto::PrivateKeyError> {
    pkcs11_manager()?.list_slots()
}

// RFC 4514-style Distinguished Name formatter
pub mod name;
pub use name::{decode_string_value, format_dn, format_dn_slash, parse_name_attrs, NameBuilder};

// Public key algorithm identification and decoded key data
pub mod pubkey;
pub use pubkey::{decode_public_key_info, PublicKeyInfo};

// Well-known OID component arrays for algorithms and DN attribute types
pub mod oids;

// Human-readable algorithm name strings returned by the identify_* helpers
pub mod names;

// Dependency-free PEM → DER decoder
pub mod pem;
pub use pem::{decode_base64, der_to_pem, encode_base64, pem_blocks, pem_to_der};

// Shared time-string parsing helpers used by the builder modules.
pub mod time_utils;
pub use time_utils::{parse_generalized_time, parse_time};

// Zero-copy borrowed types at crate root (optimal for parse-only workloads).
// OCTET STRING / BIT STRING fields borrow from the input buffer;
// issuer, subject, and extensions are stored as raw DER for lazy parsing.
include!(concat!(env!("OUT_DIR"), "/x509_borrowed.rs"));

/// Owned X.509 types for constructing certificates programmatically.
///
/// Unlike the zero-copy borrowed types at the crate root, these types use
/// heap-allocating representations for binary fields and fully-parsed types
/// for `issuer`, `subject`, and `extensions`.  They are convenient when you
/// need to build or mutate certificate structures without keeping a reference
/// to an input byte slice alive.
pub mod owned {
    include!(concat!(env!("OUT_DIR"), "/x509_owned.rs"));
}

/// PKCS #10 Certificate Signing Request (RFC 2986) types.
///
/// Generated from `asn1/PKCS10-CSR.asn1`.  Shared types (`AlgorithmIdentifier`,
/// `SubjectPublicKeyInfo`, `Name`) are imported from the crate root via
/// `use crate::*` in the generated file.
pub mod csr {
    include!(concat!(env!("OUT_DIR"), "/csr_borrowed.rs"));
}

/// X.509 Certificate Revocation List (RFC 5280 §5) types.
///
/// Generated from `asn1/X509-CRL.asn1`.  Shared types (`AlgorithmIdentifier`,
/// `Name`, `Time`, `Extensions`) are imported from the crate root.
pub mod crl {
    include!(concat!(env!("OUT_DIR"), "/crl_borrowed.rs"));
}

/// Online Certificate Status Protocol (RFC 6960) types.
///
/// Generated from `asn1/OCSP.asn1`.  Shared types (`AlgorithmIdentifier`,
/// `Extensions`) are imported from the crate root.  The `responder_id` field
/// on `ResponseData` is stored as `RawDer<'a>` for lazy decoding.
pub mod ocsp {
    include!(concat!(env!("OUT_DIR"), "/ocsp_borrowed.rs"));
}

/// CMS / PKCS#7 OID constants and ContentInfo type.
///
/// Generated from `asn1/PKCS7-CMS.asn1`.  Use [`certs_from_pkcs7`] to extract
/// certificates from a PKCS#7 SignedData blob without importing this module
/// directly.
pub mod pkcs7_types {
    include!(concat!(env!("OUT_DIR"), "/pkcs7_generated.rs"));
}

/// PKCS#12 OID constants and parameter types.
///
/// Generated from `asn1/PKCS12.asn1`.  Use [`certs_from_pkcs12`] to extract
/// certificates from a PKCS#12 archive without importing this module directly.
pub mod pkcs12_types {
    include!(concat!(env!("OUT_DIR"), "/pkcs12_generated.rs"));
}

/// PKCS #9 attribute type OID constants.
///
/// Generated from `asn1/PKCS9.asn1`.  Covers RFC 2985 attribute OIDs and the
/// well-known CMS signed-attribute OIDs from RFC 5652 §11 (`id-contentType`,
/// `id-messageDigest`, `id-signingTime`, `id-countersignature`), PKCS #10
/// request attributes (`id-extensionRequest`, `id-challengePassword`), and
/// PKCS #12 bag attributes (`id-friendlyName`, `id-localKeyId`).
///
/// Key OIDs re-exported in [`crate::oids`]:
/// - [`crate::oids::PKCS9_CONTENT_TYPE`] — `id-contentType` (1.2.840.113549.1.9.3)
/// - [`crate::oids::PKCS9_MESSAGE_DIGEST`] — `id-messageDigest` (1.2.840.113549.1.9.4)
/// - [`crate::oids::PKCS9_SIGNING_TIME`] — `id-signingTime` (1.2.840.113549.1.9.5)
/// - [`crate::oids::PKCS9_COUNTERSIGNATURE`] — `id-countersignature` (1.2.840.113549.1.9.6)
/// - [`crate::oids::PKCS9_EXTENSION_REQUEST`] — `id-extensionRequest` (1.2.840.113549.1.9.14)
pub mod pkcs9_types {
    include!(concat!(env!("OUT_DIR"), "/pkcs9_generated.rs"));
}

/// PKCS #1 RSA key structures and algorithm parameters (RFC 8017).
///
/// Generated from `asn1/PKCS1.asn1`.  Defines the RSA public and private key
/// DER structures, RSASSA-PSS and RSAES-OAEP algorithm parameters, DigestInfo,
/// and the PKCS #1 OID constants not already in [`crate::oids`].
///
/// [`RsaPublicKey`] is re-exported at the crate root so that existing callers
/// using `synta_certificate::RsaPublicKey` continue to work.
///
/// Key types:
/// - [`RsaPublicKey`] — `SEQUENCE { modulus INTEGER, publicExponent INTEGER }`
/// - [`RSAPrivateKey`] — multi-prime RSA private key (RFC 8017 §3.2)
/// - [`RsassaPssParams`] — RSASSA-PSS algorithm parameters (RFC 8017 §A.2.3)
/// - [`RsaesOaepParams`] — RSAES-OAEP algorithm parameters (RFC 8017 §A.2.1)
/// - [`DigestInfo`] — `SEQUENCE { digestAlgorithm, digest OCTET STRING }`
///
/// [`RsaPublicKey`]: pkcs1_types::RsaPublicKey
/// [`RSAPrivateKey`]: pkcs1_types::RSAPrivateKey
/// [`RsassaPssParams`]: pkcs1_types::RsassaPssParams
/// [`RsaesOaepParams`]: pkcs1_types::RsaesOaepParams
/// [`DigestInfo`]: pkcs1_types::DigestInfo
pub mod pkcs1_types {
    include!(concat!(env!("OUT_DIR"), "/pkcs1_generated.rs"));
}

// Re-export at crate root so `crate::RsaPublicKey` keeps working.
pub use pkcs1_types::RsaPublicKey;

// Re-export ML-DSA types at crate root.
pub use mldsa_types::{
    MlDsa44PrivateKey, MlDsa44PrivateKeyBoth, MlDsa44PublicKey, MlDsa65PrivateKey,
    MlDsa65PrivateKeyBoth, MlDsa65PublicKey, MlDsa87PrivateKey, MlDsa87PrivateKeyBoth,
    MlDsa87PublicKey,
};

/// ML-DSA key structure types (RFC 9881 / FIPS 204).
///
/// Generated from `asn1/MLDSA.asn1`.  Defines the public and private key types
/// for the three ML-DSA parameter sets:
///
/// | Type | Parameter set | Pub key | Seed | Expanded key |
/// |------|--------------|---------|------|-------------|
/// | [`MlDsa44PrivateKey`] | ML-DSA-44 | 1312 B | 32 B | 2560 B |
/// | [`MlDsa65PrivateKey`] | ML-DSA-65 | 1952 B | 32 B | 4032 B |
/// | [`MlDsa87PrivateKey`] | ML-DSA-87 | 2592 B | 32 B | 4896 B |
///
/// Each private key is a CHOICE of `seed`, `expandedKey`, or `both` (RFC 9881 §4).
/// The `both` variant has a synthetic helper struct (e.g. [`MlDsa44PrivateKeyBoth`])
/// that holds both seed and expanded key together.
///
/// OIDs are in [`crate::oids`]: [`crate::oids::ML_DSA_44`], [`crate::oids::ML_DSA_65`],
/// [`crate::oids::ML_DSA_87`].
///
/// [`MlDsa44PrivateKey`]: mldsa_types::MlDsa44PrivateKey
/// [`MlDsa65PrivateKey`]: mldsa_types::MlDsa65PrivateKey
/// [`MlDsa87PrivateKey`]: mldsa_types::MlDsa87PrivateKey
/// [`MlDsa44PrivateKeyBoth`]: mldsa_types::MlDsa44PrivateKeyBoth
pub mod mldsa_types {
    include!(concat!(env!("OUT_DIR"), "/mldsa_generated.rs"));
}

/// RFC 3279 algorithm parameter and signature types (DSA, DH, ECDSA).
///
/// Generated from `asn1/PKIXAlgs.asn1`.  Covers the algorithm identifiers
/// and associated parameter structures defined in RFC 3279 and X9.62:
///
/// - [`DssParms`] — DSA domain parameters (p, q, g) for use in SubjectPublicKeyInfo
/// - [`DssSigValue`] — DER encoding of a DSA signature (r, s)
/// - [`EcdsaSigValue`] — DER encoding of an ECDSA signature (r, s)
/// - [`DomainParameters`] — Diffie-Hellman domain parameters
/// - [`SpecifiedECDomain`] — Full EC domain parameters (FieldID, Curve, base point)
/// - [`ECParameters`] — EC algorithm parameters CHOICE (named curve OID or explicit)
///
/// Named curve OIDs: `prime192v1`, `prime256v1`, `secp224r1`,
/// `secp384r1`, `secp521r1`, `id-ecPublicKey`, `ecdsa-with-SHA256`, etc.
///
/// [`DssParms`]: pkixalgs_types::DssParms
/// [`DssSigValue`]: pkixalgs_types::DssSigValue
/// [`EcdsaSigValue`]: pkixalgs_types::EcdsaSigValue
/// [`DomainParameters`]: pkixalgs_types::DomainParameters
/// [`SpecifiedECDomain`]: pkixalgs_types::SpecifiedECDomain
/// [`ECParameters`]: pkixalgs_types::ECParameters
pub mod pkixalgs_types {
    include!(concat!(env!("OUT_DIR"), "/pkixalgs_generated.rs"));
}

/// RFC 5755 X.509 Attribute Certificate v2 types.
///
/// Generated from `asn1/AttributeCertificate.asn1`.  An Attribute Certificate
/// (AC) binds attributes (roles, clearances, service info) to a holder
/// without re-issuing the underlying Public Key Certificate (PKC).
///
/// Key types:
/// - [`AttributeCertificate`] — outer signed structure (acinfo + signature)
/// - [`AttributeCertificateInfo`] — inner TBS with holder, issuer, attributes
/// - [`Holder`] — links AC to PKC via baseCertificateID, entityName, or digest
/// - [`AttCertIssuer`] — CHOICE between v1Form (GeneralNames) and v2Form
/// - [`IetfAttrSyntax`] — standard attribute value syntax (OID/octet/string)
/// - [`RoleSyntax`] — role attribute value (id-at-role)
/// - [`Clearance`] — clearance attribute value (id-at-clearance)
/// - [`AAControls`] — AA Controls extension (id-pe-aaControls)
/// - [`Targets`] / [`Target`] — target information extension
///
/// [`AttributeCertificate`]: attribute_cert_types::AttributeCertificate
/// [`AttributeCertificateInfo`]: attribute_cert_types::AttributeCertificateInfo
/// [`Holder`]: attribute_cert_types::Holder
/// [`AttCertIssuer`]: attribute_cert_types::AttCertIssuer
/// [`IetfAttrSyntax`]: attribute_cert_types::IetfAttrSyntax
/// [`RoleSyntax`]: attribute_cert_types::RoleSyntax
/// [`Clearance`]: attribute_cert_types::Clearance
/// [`AAControls`]: attribute_cert_types::AAControls
/// [`Targets`]: attribute_cert_types::Targets
/// [`Target`]: attribute_cert_types::Target
#[allow(clippy::large_enum_variant)]
pub mod attribute_cert_types {
    include!(concat!(env!("OUT_DIR"), "/attribute_cert_generated.rs"));
}

/// RFC 4211 Certificate Request Message Format (CRMF) types.
///
/// Generated from `asn1/CRMF.asn1`.  CRMF defines the wire format for
/// certificate requests sent to a CA via CMP (RFC 9810) or other protocols.
///
/// Key types:
/// - [`CertReqMessages`] — SEQUENCE OF CertReqMsg (outer container)
/// - [`CertReqMsg`] — single request: CertRequest + optional POP + regInfo
/// - [`CertRequest`] — request ID + CertTemplate + optional Controls
/// - [`CertTemplate`] — all-optional \[0\]-\[9\] IMPLICIT template fields
/// - [`ProofOfPossession`] — CHOICE: raVerified, signature, keyEncipherment, keyAgreement
/// - [`POPOSigningKey`] — signature-based proof of possession
/// - [`PBMParameter`] — password-based MAC parameters
/// - [`EncryptedKey`] — CHOICE: EncryptedValue or EnvelopedData (as [`RawDer`])
/// - [`PKIArchiveOptions`] — key archival options
/// - [`PKIPublicationInfo`] — certificate publication options
///
/// Complex `ANY` fields (e.g. `AttributeTypeAndValue.value`, EnvelopedData arms)
/// are stored as [`RawDer<'a>`] for lazy decoding.
///
/// [`CertReqMessages`]: crmf_types::CertReqMessages
/// [`CertReqMsg`]: crmf_types::CertReqMsg
/// [`CertRequest`]: crmf_types::CertRequest
/// [`CertTemplate`]: crmf_types::CertTemplate
/// [`ProofOfPossession`]: crmf_types::ProofOfPossession
/// [`POPOSigningKey`]: crmf_types::POPOSigningKey
/// [`PBMParameter`]: crmf_types::PBMParameter
/// [`EncryptedKey`]: crmf_types::EncryptedKey
/// [`PKIArchiveOptions`]: crmf_types::PKIArchiveOptions
/// [`PKIPublicationInfo`]: crmf_types::PKIPublicationInfo
/// [`RawDer`]: synta::RawDer
/// [`RawDer<'a>`]: synta::RawDer
#[allow(clippy::large_enum_variant)]
pub mod crmf_types {
    include!(concat!(env!("OUT_DIR"), "/crmf_generated.rs"));
}

/// Builder for CRMF (RFC 4211) certificate request messages.
///
/// [`CertReqMsgBuilder`] assembles a single `CertReqMsg` DER from pre-encoded
/// Name and SubjectPublicKeyInfo bytes.  [`CertReqMessagesBuilder`] wraps a
/// list of pre-encoded `CertReqMsg` DER blobs in the outer SEQUENCE envelope.
pub mod crmf_builder;
pub use crmf_builder::{
    CertReqMessagesBuilder, CertReqMsgBuilder, PUB_METHOD_DONT_CARE, PUB_METHOD_LDAP,
    PUB_METHOD_WEB, PUB_METHOD_X500,
};

/// RFC 9810 Certificate Management Protocol (CMP) v3 types.
///
/// Generated from `asn1/CMP.asn1`.  CMP provides a complete PKI management
/// protocol for certificate issuance, renewal, revocation, key recovery,
/// and CA key update.  RFC 9810 (CMP v3) supersedes RFC 4210 and adds
/// KEM-based MAC (`KemBMParameter`) and v3 CA key update (`RootCaKeyUpdateContent`).
///
/// Key types:
/// - [`PKIMessage`] — outer CMP message (header + body + optional protection)
/// - [`PKIHeader`] — message header (sender, recipient, transactionID, nonces, …)
/// - [`PKIBody`] — CHOICE of 27 message types; all arms are [`RawDer<'a>`] for
///   lazy decoding; callers dispatch on the known message type
/// - [`PKIStatusInfo`] — status code + optional text + optional failure info
/// - [`PBMParameter`] — password-based MAC parameters
/// - [`DHBMParameter`] — DH-based MAC parameters
/// - [`KemBMParameter`] — KEM-based MAC parameters (new in v3)
/// - [`CertRepMessage`] / [`CertResponse`] — ip/cp/kup/ccp response body
/// - [`CertConfirmContent`] / [`CertStatus`] — certConf body
/// - [`RevReqContent`] / [`RevRepContent`] — rr/rp revocation body
/// - [`ErrorMsgContent`] — error message body
/// - [`InfoTypeAndValue`] — genm/genp body elements
/// - [`PollReqContent`] / [`PollRepContent`] — pollReq/pollRep body
///
/// [`PKIMessage`]: cmp_types::PKIMessage
/// [`PKIHeader`]: cmp_types::PKIHeader
/// [`PKIBody`]: cmp_types::PKIBody
/// [`PKIStatusInfo`]: cmp_types::PKIStatusInfo
/// [`PBMParameter`]: cmp_types::PBMParameter
/// [`DHBMParameter`]: cmp_types::DHBMParameter
/// [`KemBMParameter`]: cmp_types::KemBMParameter
/// [`CertRepMessage`]: cmp_types::CertRepMessage
/// [`CertResponse`]: cmp_types::CertResponse
/// [`CertConfirmContent`]: cmp_types::CertConfirmContent
/// [`CertStatus`]: cmp_types::CertStatus
/// [`RevReqContent`]: cmp_types::RevReqContent
/// [`RevRepContent`]: cmp_types::RevRepContent
/// [`ErrorMsgContent`]: cmp_types::ErrorMsgContent
/// [`InfoTypeAndValue`]: cmp_types::InfoTypeAndValue
/// [`PollReqContent`]: cmp_types::PollReqContent
/// [`PollRepContent`]: cmp_types::PollRepContent
/// [`RawDer<'a>`]: synta::RawDer
pub mod cmp_types {
    include!(concat!(env!("OUT_DIR"), "/cmp_generated.rs"));
}

pub mod cmp_builder;
pub use cmp_builder::CMPMessageBuilder;

/// RFC 9925 Unsigned X.509 Certificate OID constants.
///
/// Generated from `asn1/RFC9925-UnsignedCert.asn1`.  RFC 9925 defines a
/// profile for unsigned X.509 certificates — certificates used as containers
/// for subject information without any cryptographic binding to an issuer.
/// The standard Certificate structure (RFC 5280) is used unchanged; RFC 9925
/// only introduces two OID assignments:
///
/// - [`ID_ALG_UNSIGNED`] — signature algorithm identifier placed in both
///   `Certificate.signatureAlgorithm` and `TBSCertificate.signature`.
///   Parameters MUST be absent.  The `signatureValue` field MUST be a
///   zero-length BIT STRING (DER: `03 01 00`).
///
/// - [`ID_RDNA_UNSIGNED`] — optional placeholder RDN attribute for the
///   issuer field.  Value is a zero-length UTF8String (`0C 00`).
///
/// These OIDs are re-exported in [`crate::oids`] as
/// [`crate::oids::ALG_UNSIGNED`] and [`crate::oids::RDNA_UNSIGNED`].
///
/// [`ID_ALG_UNSIGNED`]: rfc9925_types::ID_ALG_UNSIGNED
/// [`ID_RDNA_UNSIGNED`]: rfc9925_types::ID_RDNA_UNSIGNED
pub mod rfc9925_types {
    include!(concat!(env!("OUT_DIR"), "/rfc9925_generated.rs"));
}
/// RFC 7773 Authentication Context Certificate Extension (ACE-88, 1988 syntax).
///
/// Generated from `asn1/ACE-88.asn1`.  Defines the X.509 extension type for
/// linking authentication contexts to end-entity certificates, as used by
/// Swedish e-ID infrastructure (e-Legitimationsnämnden).
///
/// Key types:
/// - [`AuthenticationContexts`] — SEQUENCE SIZE (1..MAX) OF AuthenticationContext;
///   the extension value wrapped in an OCTET STRING
/// - [`AuthenticationContext`] — a single context entry: `contextType` UTF8String
///   and optional `contextInfo` UTF8String
///
/// OID: `id-ce-authContext` (1.2.752.201.5.1)
///
/// [`AuthenticationContexts`]: ace88_types::AuthenticationContexts
/// [`AuthenticationContext`]: ace88_types::AuthenticationContext
pub mod ace88_types {
    include!(concat!(env!("OUT_DIR"), "/ace88_generated.rs"));
}

/// RFC 8769 CBOR content type OID constants for CMS.
///
/// Generated from `asn1/CborContentTypes.asn1`.  Defines two OBJECT IDENTIFIER
/// constants for use in CMS `ContentInfo.contentType` when the content is
/// CBOR-encoded data (RFC 8949):
///
/// - [`ID_CT_CBOR`] — `id-ct-cbor` (1.2.840.113549.1.9.16.1.44) — a single
///   CBOR data item
/// - [`ID_CT_CBOR_SEQUENCE`] — `id-ct-cborSequence` (1.2.840.113549.1.9.16.1.45)
///   — a sequence of CBOR data items concatenated without any outer wrapper
///
/// The content for both types is encoded directly (raw bytes, no ASN.1
/// structure); no additional Rust types are generated beyond the OID constants.
///
/// [`ID_CT_CBOR`]: cbor_content_types::ID_CT_CBOR
/// [`ID_CT_CBOR_SEQUENCE`]: cbor_content_types::ID_CT_CBOR_SEQUENCE
pub mod cbor_content_types {
    include!(concat!(env!("OUT_DIR"), "/cbor_content_types_generated.rs"));
}

/// RFC 8737: ACME TLS-ALPN-01 identifier extension (`id-pe-acmeIdentifier`).
///
/// Generated from `asn1/ACME-RFC8737.asn1`.  Defines the X.509 extension and
/// type used by an ACME server to validate domain control via the TLS-ALPN-01
/// challenge (RFC 8737 §3):
///
/// - [`ID_PE_ACME_IDENTIFIER`] — OID `id-pe-acmeIdentifier`
///   (1.3.6.1.5.5.7.1.31).  The extension MUST be marked critical.
/// - [`Authorization`] — `OCTET STRING (SIZE (32))`.  The extension value is
///   the DER encoding of a 32-byte SHA-256 digest of the ACME key
///   authorization string for the challenge token.
///
/// The OID is re-exported in [`crate::oids`] as
/// [`crate::oids::PE_ACME_IDENTIFIER`].
///
/// [`ID_PE_ACME_IDENTIFIER`]: acme_types::ID_PE_ACME_IDENTIFIER
/// [`Authorization`]: acme_types::Authorization
pub mod acme_types {
    include!(concat!(env!("OUT_DIR"), "/acme_rfc8737_generated.rs"));
}

/// `FileAndHash` for RPKI signed object manifest content type.
pub mod rpki_manifest_types {
    include!(concat!(env!("OUT_DIR"), "/rpki_manifest_generated.rs"));
}

/// for S/MIME 4.0 message handling.
pub mod smime_v3dot1_types {
    include!(concat!(env!("OUT_DIR"), "/smime_v3dot1_generated.rs"));
}

/// RPKI signed manifest types (RFC 9286).
///
/// Generated from `asn1/RPKIManifest.asn1`. Defines `Manifest` and
/// use in PKCS#12 MAC computation.
pub mod pkcs12_pbmac1_2023_types {
    include!(concat!(env!("OUT_DIR"), "/pkcs12_pbmac1_2023_generated.rs"));
}

/// S/MIME v3.1 message types and OIDs (RFC 8551).
///
/// Generated from `asn1/SecureMimeMessageV3dot1.asn1`. Defines
/// `SMIMECapability`, `SMIMECapabilities`, and related OID constants
/// wrapping via HKDF-SHA-256.
pub mod cms_cek_hkdf_sha256_2023_types {
    include!(concat!(
        env!("OUT_DIR"),
        "/cms_cek_hkdf_sha256_2023_generated.rs"
    ));
}

/// PKCS#12 PBMAC1 MAC parameters (RFC 9879).
///
/// Generated from `asn1/PKCS12-PBMAC1-2023.asn1`. Defines
/// `PBMAC1-params` and HMAC OID constants for SHA-2 based PBKDF2/PBMAC1
/// `CMSORIforPSKOtherInfo` for PSK-based CMS recipient info.
pub mod cms_ori_for_psk_2019_types {
    include!(concat!(
        env!("OUT_DIR"),
        "/cms_ori_for_psk_2019_generated.rs"
    ));
}

/// CMS CEK-HKDF-SHA256 Algorithm OID (RFC 9709).
///
/// Generated from `asn1/CMS-CEK-HKDF-SHA256-Module-2023.asn1`.
/// Defines `id-alg-cek-hkdf-sha256` for content encryption key
/// the `GMACParameters` structure.
pub mod cms_gmac_algorithms_types {
    include!(concat!(
        env!("OUT_DIR"),
        "/cms_gmac_algorithms_generated.rs"
    ));
}

/// CMS OtherRecipientInfo for Pre-Shared Key (RFC 8696).
///
/// Generated from `asn1/CMSORIforPSK-2019.asn1`. Defines
/// `KeyTransPSKRecipientInfo`, `KeyAgreePSKRecipientInfo`, and
/// `id-kp-rpcTLSClient` and `id-kp-rpcTLSServer` EKU OIDs.
pub mod rpc_with_tls_2021_types {
    include!(concat!(env!("OUT_DIR"), "/rpc_with_tls_2021_generated.rs"));
}

/// CMS GMAC Algorithm OIDs and parameters (RFC 9044).
///
/// Generated from `asn1/CryptographicMessageSyntaxGMACAlgorithms.asn1`.
/// Defines `id-aes128-GMAC`, `id-aes192-GMAC`, `id-aes256-GMAC`, and
/// `id-alg-hkdf-with-sha512` for use with HKDF key derivation.
pub mod hkdf_oid_2019_types {
    include!(concat!(env!("OUT_DIR"), "/hkdf_oid_2019_generated.rs"));
}

/// PKCS #8 private key structure types.
///
/// Generated from `asn1/PKCS8.asn1`.  Defines [`OneAsymmetricKey`] (RFC 5958)
/// and its backward-compatible alias [`PrivateKeyInfo`] (RFC 5208) — the
/// standard DER container for private keys, typically PEM-armoured as
/// `"-----BEGIN PRIVATE KEY-----"`.
///
/// The `attributes` and `publicKey` fields are stored as [`RawDer<'a>`] for
/// lazy decoding; the caller must decode them according to the private key
/// algorithm.
///
/// [`OneAsymmetricKey`]: pkcs8_types::OneAsymmetricKey
/// [`PrivateKeyInfo`]: pkcs8_types::PrivateKeyInfo
/// [`RawDer<'a>`]: synta::RawDer
pub mod pkcs8_types {
    include!(concat!(env!("OUT_DIR"), "/pkcs8_generated.rs"));
}

/// PKINIT OID constants and protocol structures.
///
/// Generated from `asn1/PKINIT.asn1` based on RFC 4556 (PKINIT), RFC 6112
/// (anonymous PKINIT), and RFC 8636 (PKINIT algorithm agility).
/// Key OIDs re-exported in [`crate::oids`]:
/// - [`crate::oids::ID_PKINIT_SAN`] — KRB5PrincipalName SAN OtherName type (1.3.6.1.5.2.2)
/// - [`crate::oids::ID_PKINIT_KPCLIENT_AUTH`] — PKINIT client EKU (1.3.6.1.5.2.3.4)
/// - [`crate::oids::ID_PKINIT_KPKDC`] — PKINIT KDC EKU (1.3.6.1.5.2.3.5)
pub mod pkinit_types {
    include!(concat!(env!("OUT_DIR"), "/pkinit_generated.rs"));
}

/// Microsoft PKI OID constants and AD CS extension structures.
///
/// Generated from `asn1/MicrosoftPKI.asn1`.  Covers Active Directory Certificate
/// Services (AD CS) OIDs from [MS-WCCE] and related specifications.
/// Key OIDs re-exported in [`crate::oids`]:
/// - [`crate::oids::ID_MS_CERTIFICATE_TEMPLATE_NAME`] — MS template name V1 (1.3.6.1.4.1.311.20.2)
/// - [`crate::oids::ID_MS_CERTIFICATE_TEMPLATE`] — MS template info V2 (1.3.6.1.4.1.311.21.7)
/// - [`crate::oids::ID_MS_SAN_UPN`] — UPN SAN OtherName type (1.3.6.1.4.1.311.20.2.3)
pub mod ms_pki_types {
    include!(concat!(env!("OUT_DIR"), "/ms_pki_generated.rs"));
}

/// PKCS #5 v2.1 parameter types and OID constants (RFC 8018).
///
/// Generated from `asn1/PKCS5v2-1.asn1`.  Defines parameter structures for
/// the PBKDF2 key derivation function, PBES1/PBES2 encryption schemes, and
/// PBMAC1 MAC scheme, along with all supporting OID constants.
///
/// Key types:
/// - `Pkcs5AlgorithmIdentifier` — local AlgorithmIdentifier (avoids crate-root clash)
/// - `Pkcs5Pbkdf2Params` — PBKDF2 parameters (RFC 8018 §5.2)
/// - `Pkcs5PbeParameter` — PBES1 parameters (RFC 8018 §6.1)
/// - `Pkcs5Pbes2Params` — PBES2 parameters (RFC 8018 §6.2)
/// - `Pkcs5Pbmac1Params` — PBMAC1 parameters (RFC 8018 §7.1)
/// - `Rc2CbcParameter` — RC2 cipher parameters (RFC 8018 Appendix B.2.3)
/// - `Rc5CbcParameters` — RC5 cipher parameters (RFC 8018 Appendix B.2.4)
///
/// Key OID constants:
/// - `id_PBKDF2` — PBKDF2 (1.2.840.113549.1.5.12)
/// - `id_PBES2` — PBES2 (1.2.840.113549.1.5.13)
/// - `id_PBMAC1` — PBMAC1 (1.2.840.113549.1.5.14)
/// - `aes128_CBC_PAD` / `aes192_CBC_PAD` / `aes256_CBC_PAD` — AES-CBC-PAD OIDs
pub mod pkcs5_types {
    include!(concat!(env!("OUT_DIR"), "/pkcs5_generated.rs"));
}

/// RFC 5912 PKIX-CommonTypes-2009 — information object class definitions and
/// parameterized helper types used across the 2009-syntax PKIX module suite.
///
/// Defines the `ATTRIBUTE`, `EXTENSION`, and `MATCHING-RULE` information object
/// classes (generated as comments only — no DER structure) and the concrete
/// parameterized types:
/// - `AttributeSet` — `SEQUENCE { type ATTRIBUTE.&id, values SET OF ATTRIBUTE.&Type }`
/// - `SingleAttribute` — single-valued ATTRIBUTE instance
/// - `Extension` — `SEQUENCE { extnID OBJECT IDENTIFIER, critical BOOLEAN DEFAULT FALSE, extnValue OCTET STRING }`
/// - `SecurityCategory` — security category label
///
/// Source: RFC 5912 §2.
pub mod pkix_common_types {
    include!(concat!(env!("OUT_DIR"), "/pkix_common_types_generated.rs"));
}

/// RFC 5912 AlgorithmInformation-2009 — algorithm information object classes
/// and the parameterized `AlgorithmIdentifier` type for 2009-syntax modules.
///
/// The generated code provides:
/// - `ParamOptions` — ENUMERATED describing parameter presence requirements
/// - `AlgorithmIdentifier2009` — `SEQUENCE { algorithm OID, parameters ANY OPTIONAL }`
/// - `SmimeCapability` — `SEQUENCE { capabilityID OID, parameters ANY OPTIONAL }`
/// - `SmimeCapabilities` — `SEQUENCE OF SmimeCapability`
///
/// The CLASS definitions (`DIGEST-ALGORITHM`, `SIGNATURE-ALGORITHM`, `PUBLIC-KEY`,
/// etc.) carry no DER encoding; they are emitted as documentation comments only.
///
/// Source: RFC 5912 §3.
pub mod alg_info_types {
    include!(concat!(env!("OUT_DIR"), "/alg_info_generated.rs"));
}

/// RFC 5912 PKIXAlgs-2009 — 2009-syntax restatement of RFC 3279 / RFC 5480
/// public key and signature algorithm parameters.
///
/// Provides OID constants for RSA, DSA, DH, KEA, ECDH, ECMQV and ECDSA
/// algorithms, named curve OIDs, and the concrete structures:
/// - `DsaParams` — DSA parameters `SEQUENCE { p INTEGER, q INTEGER, g INTEGER }`
/// - `DomainParameters` — DH domain parameters
/// - `ValidationParams` — DH validation parameters
/// - `EcParameters` — `CHOICE { namedCurve OID, ... }`
/// - `DsaSigValue` — DSA signature `SEQUENCE { r INTEGER, s INTEGER }`
/// - `EcdsaSigValue` — ECDSA signature `SEQUENCE { r INTEGER, s INTEGER }`
///
/// Source: RFC 5912 §6 (cross-references RFC 3279 and RFC 5480).
pub mod pkixalgs_2009_types {
    include!(concat!(env!("OUT_DIR"), "/pkixalgs_2009_generated.rs"));
}

/// RFC 5912 PKIX1Explicit-2009 — 2009-syntax restatement of the RFC 5280
/// explicit-tags module, using information object classes and parameterized types.
///
/// Provides OID constants for the PKIX hierarchy (`id-pkix`, `id-pe`, `id-qt`,
/// `id-kp`, `id-ad`, etc.), attribute type OIDs (`id-at-*`), the DN attribute
/// types (`X520name`, `X520CommonName`, …), and the core X.509 structures:
/// - `Certificate2009` — `SIGNED { TBSCertificate }` (parameterized wrapper)
/// - `TbsCertificate2009` — `SEQUENCE { version, serialNumber, … }` with 2009
///   extension addition groups
/// - `Name2009` — `CHOICE { rdnSequence RDNSequence }`
/// - `SubjectPublicKeyInfo2009` — `SEQUENCE { algorithm, subjectPublicKey }`
///
/// Source: RFC 5912 §14.
pub mod pkix1_explicit_types {
    include!(concat!(env!("OUT_DIR"), "/pkix1_explicit_generated.rs"));
}

/// RFC 5912 PKIX1Implicit-2009 — 2009-syntax restatement of the RFC 5280
/// implicit-tags module, defining X.509v3 certificate extension structures.
///
/// Provides OID constants for all standard X.509v3 extensions (`id-ce-*`)
/// and the extension value types:
/// - [`AuthorityKeyIdentifier`] — key identifier + optional issuer + serial
/// - [`KeyUsage`] — BIT STRING with named bits (digitalSignature, …)
/// - [`GeneralName`] — CHOICE of subject/issuer name forms
/// - [`GeneralNames`] — `SEQUENCE OF GeneralName`
/// - [`DistributionPoint`] — CRL distribution point
/// - [`AccessDescription`] — authority / subject information access
/// - and many more standard extension types
///
/// Source: RFC 5912 §14.
pub mod pkix1_implicit_types {
    include!(concat!(env!("OUT_DIR"), "/pkix1_implicit_generated.rs"));
}

/// RFC 5652 / RFC 6268 Cryptographic Message Syntax (CMS) 2010 types.
///
/// Generated from `asn1/CMS-2010.asn1`.  Defines the subset of CMS types
/// used by CMS-KEM (RFC 9629): [`CMSVersion`], [`RecipientIdentifier`],
/// [`IssuerAndSerialNumber`], [`KeyDerivationAlgorithmIdentifier`],
/// [`KeyEncryptionAlgorithmIdentifier`], [`EncryptedKey`], and
/// [`UserKeyingMaterial`].
///
/// [`CMSVersion`]: cms_2010_types::CMSVersion
/// [`RecipientIdentifier`]: cms_2010_types::RecipientIdentifier
/// [`IssuerAndSerialNumber`]: cms_2010_types::IssuerAndSerialNumber
/// [`KeyDerivationAlgorithmIdentifier`]: cms_2010_types::KeyDerivationAlgorithmIdentifier
/// [`KeyEncryptionAlgorithmIdentifier`]: cms_2010_types::KeyEncryptionAlgorithmIdentifier
/// [`EncryptedKey`]: cms_2010_types::EncryptedKey
/// [`UserKeyingMaterial`]: cms_2010_types::UserKeyingMaterial
pub mod cms_2010_types {
    include!(concat!(env!("OUT_DIR"), "/cms_2010_generated.rs"));
}

/// RFC 9629 §6.1 KEM Algorithm Information Object Class.
///
/// Generated from `asn1/KEMAlgorithmInformation.asn1`.  The module contains only
/// an ASN.1 CLASS definition (`KEM-ALGORITHM`) which has no DER encoding; no
/// Rust types are generated — the module is a documentation stub only.
pub mod kem_alg_info_types {
    include!(concat!(env!("OUT_DIR"), "/kem_alg_info_generated.rs"));
}

/// RFC 7229 test certificate policy OIDs.
///
/// Generated from `asn1/PKIXTestCertPolicies.asn1`.  Defines eight PKIX test
/// policy OIDs under the `id-TEST` arc (`1.3.6.1.5.5.7.13`):
///
/// | Constant                  | OID                      |
/// |---------------------------|--------------------------|
/// | `ID_TEST_CERT_POLICY_ONE`   | `1.3.6.1.5.5.7.13.1`  |
/// | `ID_TEST_CERT_POLICY_TWO`   | `1.3.6.1.5.5.7.13.2`  |
/// | `ID_TEST_CERT_POLICY_THREE` | `1.3.6.1.5.5.7.13.3`  |
/// | `ID_TEST_CERT_POLICY_FOUR`  | `1.3.6.1.5.5.7.13.4`  |
/// | `ID_TEST_CERT_POLICY_FIVE`  | `1.3.6.1.5.5.7.13.5`  |
/// | `ID_TEST_CERT_POLICY_SIX`   | `1.3.6.1.5.5.7.13.6`  |
/// | `ID_TEST_CERT_POLICY_SEVEN` | `1.3.6.1.5.5.7.13.7`  |
/// | `ID_TEST_CERT_POLICY_EIGHT` | `1.3.6.1.5.5.7.13.8`  |
///
/// These OIDs are intended **exclusively for testing** certificate policy
/// processing implementations and MUST NOT appear in production certificates.
pub mod pkix_test_cert_policies_types {
    include!(concat!(
        env!("OUT_DIR"),
        "/pkix_test_cert_policies_generated.rs"
    ));
}

/// RFC 9629 §6.2 CMS KEM Recipient Info types.
///
/// Generated from `asn1/CMS-KEM.asn1`.  Defines [`KEMRecipientInfo`] and
/// [`CMSORIforKEMOtherInfo`] for quantum-safe (KEM-based) key establishment
/// in CMS `EnvelopedData`.  `KEMRecipientInfo` is carried as an
/// `OtherRecipientInfo` alternative identified by `id-ori-kem`.
///
/// [`KEMRecipientInfo`]: cms_kem_types::KEMRecipientInfo
/// [`CMSORIforKEMOtherInfo`]: cms_kem_types::CMSORIforKEMOtherInfo
pub mod cms_kem_types {
    include!(concat!(env!("OUT_DIR"), "/cms_kem_generated.rs"));
}

/// RFC 5652 Cryptographic Message Syntax (CMS) full structure types.
///
/// Generated from `asn1/CMS-RFC5652.asn1`.  Covers the complete set of CMS
/// structures from RFC 5652: [`SignedData`], [`EnvelopedData`],
/// [`DigestedData`], [`EncryptedData`], [`AuthenticatedData`] and all
/// supporting types (SignerInfo, EncapsulatedContentInfo, OriginatorInfo,
/// EncryptedContentInfo, RecipientEncryptedKey, KEKRecipientInfo, etc.).
///
/// CHOICE fields that cannot be decoded by the derive macro at compile time
/// (CertificateSet, RevocationInfoChoices, SignerIdentifier, SignedAttributes,
/// RecipientInfos, OriginatorIdentifierOrKey, etc.) are stored as
/// [`RawDer<'a>`] for lazy decoding by the caller.
///
/// [`SignedData`]: cms_rfc5652_types::SignedData
/// [`EnvelopedData`]: cms_rfc5652_types::EnvelopedData
/// [`DigestedData`]: cms_rfc5652_types::DigestedData
/// [`EncryptedData`]: cms_rfc5652_types::EncryptedData
/// [`AuthenticatedData`]: cms_rfc5652_types::AuthenticatedData
/// [`RawDer<'a>`]: synta::RawDer
pub mod cms_rfc5652_types {
    include!(concat!(env!("OUT_DIR"), "/cms_rfc5652_generated.rs"));
}

/// RFC 9399 §A.1 Certificate Image OID module.
///
/// Generated from `asn1/CERT-IMAGE-MODULE.asn1`.  Defines the
/// `id-logo-certImage` object identifier
/// (`1.3.6.1.5.5.7.20.3`), which identifies the certificate image logotype
/// type carried in `otherLogos` of a [`logotype_cert_extn_types::LogotypeExtn`].
/// The certificate image is a complete visual representation of the certificate
/// intended for human display (Section 4.4.3 of RFC 9399).
///
/// This module was previously published as RFC 6170, which is now obsoleted by
/// RFC 9399.
///
/// [`logotype_cert_extn_types::LogotypeExtn`]: logotype_cert_extn_types::LogotypeExtn
pub mod cert_image_module_types {
    include!(concat!(env!("OUT_DIR"), "/cert_image_module_generated.rs"));
}

/// RFC 9399 §A.1 Logotype certificate extension types (1988 ASN.1 syntax).
///
/// Generated from `asn1/LogotypeCertExtn.asn1`.  Defines the logotype
/// certificate extension (OID `1.3.6.1.5.5.7.1.12`, `id-pe-logotype`) and
/// all supporting structures for embedding or referencing logotype image and
/// audio data in X.509 public key certificates and attribute certificates.
///
/// Key types:
/// - [`LogotypeExtn`] — the top-level extension value (community, issuer,
///   subject, and other logotypes).
/// - [`LogotypeInfo`] — CHOICE between direct ([`LogotypeData`]) and indirect
///   ([`LogotypeReference`]) addressing.
/// - [`LogotypeDetails`] — media type, hash(es), and URI(s) for one logotype object.
/// - [`HashAlgAndValue`] — one-way hash algorithm and computed value pair.
/// - [`LogotypeImageInfo`] — recommended display dimensions and colour depth.
/// - [`LogotypeAudioInfo`] — audio file metadata (size, duration, channels, language).
/// - [`OtherLogotypeInfo`] — logotype identified by an arbitrary OID
///   (loyalty, background, certificate image, or private extensions).
///
/// Other logotype OIDs defined here: `id-logo` (`1.3.6.1.5.5.7.20`),
/// `id-logo-loyalty` (`…20.1`), `id-logo-background` (`…20.2`).
/// The `id-logo-certImage` (`…20.3`) OID is in [`cert_image_module_types`].
///
/// [`LogotypeExtn`]: logotype_cert_extn_types::LogotypeExtn
/// [`LogotypeInfo`]: logotype_cert_extn_types::LogotypeInfo
/// [`LogotypeData`]: logotype_cert_extn_types::LogotypeData
/// [`LogotypeReference`]: logotype_cert_extn_types::LogotypeReference
/// [`LogotypeDetails`]: logotype_cert_extn_types::LogotypeDetails
/// [`HashAlgAndValue`]: logotype_cert_extn_types::HashAlgAndValue
/// [`LogotypeImageInfo`]: logotype_cert_extn_types::LogotypeImageInfo
/// [`LogotypeAudioInfo`]: logotype_cert_extn_types::LogotypeAudioInfo
/// [`OtherLogotypeInfo`]: logotype_cert_extn_types::OtherLogotypeInfo
/// [`cert_image_module_types`]: cert_image_module_types
pub mod logotype_cert_extn_types {
    include!(concat!(env!("OUT_DIR"), "/logotype_cert_extn_generated.rs"));
}

/// RFC 2634 Extended Security Services (ESS) types.
///
/// Generated from `asn1/ESS.asn1`.  ESS defines optional security service
/// extensions for S/MIME: signed receipts, security labels, secure mailing
/// lists, and signing certificates.
///
/// Key types:
/// - [`ReceiptRequest`] — signed receipt request attribute
/// - [`Receipt`] — signed receipt content type
/// - [`ContentHints`] — content hints attribute
/// - [`MsgSigDigest`] — message signature digest (alias for OCTET STRING)
/// - [`ContentReference`] — content reference attribute
/// - [`ESSSecurityLabel`] — security label attribute (SET)
/// - [`ESSPrivacyMark`] — privacy mark CHOICE (PrintableString or UTF8String)
/// - [`SecurityCategories`] / [`SecurityCategory`] — security category set
/// - [`EquivalentLabels`] — equivalent labels attribute
/// - [`MLExpansionHistory`] / [`MLData`] — mailing list expansion history
/// - [`SigningCertificate`] — signing certificate attribute
/// - [`ESSCertID`] — certificate hash + issuer/serial (SHA-1 based)
/// - [`IssuerSerial`] — issuer GeneralNames + serial number
///
/// [`ReceiptRequest`]: ess_types::ReceiptRequest
/// [`Receipt`]: ess_types::Receipt
/// [`ContentHints`]: ess_types::ContentHints
/// [`MsgSigDigest`]: ess_types::MsgSigDigest
/// [`ContentReference`]: ess_types::ContentReference
/// [`ESSSecurityLabel`]: ess_types::ESSSecurityLabel
/// [`ESSPrivacyMark`]: ess_types::ESSPrivacyMark
/// [`SecurityCategories`]: ess_types::SecurityCategories
/// [`SecurityCategory`]: ess_types::SecurityCategory
/// [`EquivalentLabels`]: ess_types::EquivalentLabels
/// [`MLExpansionHistory`]: ess_types::MLExpansionHistory
/// [`MLData`]: ess_types::MLData
/// [`SigningCertificate`]: ess_types::SigningCertificate
/// [`ESSCertID`]: ess_types::ESSCertID
/// [`IssuerSerial`]: ess_types::IssuerSerial
pub mod ess_types {
    include!(concat!(env!("OUT_DIR"), "/ess_generated.rs"));
}

/// RFC 3161 Time-Stamp Protocol (TSP) types.
///
/// Generated from `asn1/PKIXTSP.asn1`.  Defines the wire format for
/// Time-Stamp Requests and Responses as specified in RFC 3161.
///
/// Key types:
/// - [`TimeStampReq`] — time-stamp request (version, messageImprint, reqPolicy, nonce, certReq, extensions)
/// - [`MessageImprint`] — hash algorithm OID + hash value of the data to be time-stamped
/// - [`TimeStampResp`] — response containing a PKIStatusInfo and an optional TimeStampToken
/// - [`PKIStatusInfo`] — status code, optional free text, optional failure info
/// - [`TSTInfo`] — the TSTInfo structure encapsulated within a SignedData ContentInfo
/// - [`Accuracy`] — optional time-stamp accuracy in seconds, milliseconds, microseconds
///
/// The `timeStampToken` field in [`TimeStampResp`] and the `TimeStampToken` type alias
/// are both `ContentInfo` (from [`crate::pkcs7_types`]); the eContentType OID is
/// `id-ct-TSTInfo` (1.2.840.113549.1.9.16.1.4), and the eContent is a DER-encoded
/// `TSTInfo` structure wrapped in a `SignedData`.
///
/// [`TimeStampReq`]: tsp_types::TimeStampReq
/// [`MessageImprint`]: tsp_types::MessageImprint
/// [`TimeStampResp`]: tsp_types::TimeStampResp
/// [`PKIStatusInfo`]: tsp_types::PKIStatusInfo
/// [`TSTInfo`]: tsp_types::TSTInfo
/// [`Accuracy`]: tsp_types::Accuracy
pub mod tsp_types {
    include!(concat!(env!("OUT_DIR"), "/pkixtsp_generated.rs"));
}

/// RFC 5911 CryptographicMessageSyntax-2009 OID constants and structural types.
///
/// Generated from `asn1/CryptographicMessageSyntax-2009.asn1`.  The module
/// uses 2009 IOC syntax; codegen emits OID constants and any plain
/// SEQUENCE/CHOICE types it can resolve, skipping CLASS and VALUE assignments.
pub mod cms_2009_types {
    include!(concat!(env!("OUT_DIR"), "/cms_2009_generated.rs"));
}

/// RFC 5912 §8 PKIX1-PSS-OAEP-Algorithms-2009 — RSA-PSS and RSA-OAEP.
///
/// Generated from `asn1/PKIX1-PSS-OAEP-Algorithms-2009.asn1`.  Defines
/// `RSASSA-PSS-params`, `RSAES-OAEP-params`, `HashAlgorithm`,
/// `MaskGenAlgorithm`, `PSourceAlgorithm`, and SHA-224/256/384/512 OID
/// constants.  IOC object-set values are skipped by codegen.
pub mod pkix1_pss_oaep_alg_2009_types {
    include!(concat!(
        env!("OUT_DIR"),
        "/pkix1_pss_oaep_alg_2009_generated.rs"
    ));
}

/// RFC 9654 OCSP-2024-88 — updated OCSP module in 1988 ASN.1 syntax.
///
/// This is the normative 1988-syntax module from RFC 9654 (which obsoletes
/// RFC 8954).  It defines the same OCSP types as [`ocsp`] (generated from
/// RFC 6960) but with the updated module OID `id-mod-ocsp-2024-88(111)` and
/// includes the `PreferredSignatureAlgorithm` and extended-revoke OID from
/// RFC 8954.
///
/// The types in this module (`OCSPRequest`, `OCSPResponse`, `BasicOCSPResponse`,
/// etc.) are structurally identical to those in [`ocsp`]; this module exists to
/// expose the RFC 9654 OID constants.
///
/// Source: RFC 9654 Appendix A.1.
#[allow(unused_imports, dead_code)]
pub mod ocsp_2024_88_types {
    include!(concat!(env!("OUT_DIR"), "/ocsp_2024_88_generated.rs"));
}

/// RFC 9654 OCSP-2024-08 — updated OCSP module in 2008 ASN.1 syntax.
///
/// This is the 2008/2009-syntax module from RFC 9654 Appendix A.2, provided
/// for compatibility with RFC 5912-style information object class (IOC)
/// consumers.  It defines the same OCSP wire types as [`ocsp_2024_88_types`]
/// using parameterized `AlgorithmIdentifier` and `EXTENSION` constraints.
///
/// Because the 2009 IOC syntax (`RESPONSE ::= TYPE-IDENTIFIER`, parameterized
/// `Extensions{{...}}`) is structural-only, the codegen emits the concrete
/// types (`OCSPRequest`, `OCSPResponse`, etc.) without the IOC wrappers.
///
/// Source: RFC 9654 Appendix A.2.
#[allow(unused_imports, dead_code)]
pub mod ocsp_2024_08_types {
    include!(concat!(env!("OUT_DIR"), "/ocsp_2024_08_generated.rs"));
}

/// RFC 9608 NoRevAvailExtn — `noRevAvail` certificate extension (OID 2.5.29.56).
///
/// The `noRevAvail` extension signals that no revocation information will ever
/// be available for a certificate (e.g. short-lived certificates).  Including
/// this extension allows relying parties to skip revocation checking.
///
/// Key constants:
/// - [`no_rev_avail_extn_types::ID_CE_NO_REV_AVAIL`] — OID 2.5.29.56
///
/// Source: RFC 9608 §5.
#[allow(unused_imports, dead_code)]
pub mod no_rev_avail_extn_types {
    include!(concat!(env!("OUT_DIR"), "/no_rev_avail_extn_generated.rs"));
}

/// RFC 9345 DelegatedCredentialExtn — `DelegationUsage` certificate extension.
///
/// The `DelegationUsage` extension marks an end-entity certificate as suitable
/// for issuing TLS delegated credentials (RFC 9345).  The extension value is
/// NULL; its presence alone is the signal.
///
/// Key constants:
/// - [`delegated_cred_extn_types::ID_PE_DELEGATION_USAGE`] — Cloudflare enterprise OID
///
/// Source: RFC 9345 §4.2.
#[allow(unused_imports, dead_code)]
pub mod delegated_cred_extn_types {
    include!(concat!(
        env!("OUT_DIR"),
        "/delegated_cred_extn_generated.rs"
    ));
}

/// RFC 9310 NFTypeCertExtn — Network Function type certificate extension.
///
/// The `NFType` extension (`id-pe-nftype`, 1.3.6.1.5.5.7.1.34) carries a
/// sequence of IA5String network function type identifiers in 5G NF
/// certificates per 3GPP TS 33.310.
///
/// Key types:
/// - [`nf_type_cert_extn_types::NFTypes`] — `SEQUENCE SIZE (1..MAX) OF NFType`
/// - [`nf_type_cert_extn_types::NFType`] — `IA5String (SIZE (1..32))`
///
/// Source: RFC 9310 §4.
#[allow(unused_imports, dead_code)]
pub mod nf_type_cert_extn_types {
    include!(concat!(env!("OUT_DIR"), "/nf_type_cert_extn_generated.rs"));
}

/// RFC 8479 PrivateKeyValidationAttrV1 — private key validation attribute.
///
/// Defines the `at-validation-parameters` ATTRIBUTE and the `ValidationParams`
/// SEQUENCE for carrying key validation parameters (hash algorithm OID + seed)
/// in PKCS#8 PrivateKeyInfo structures, as used by some HSMs and key-generation
/// procedures that need to prove a key was generated with a known seed.
///
/// Key types:
/// - [`pk_validation_attr_types::ValidationParams`] — `SEQUENCE { hashAlg OID, seed OCTET STRING }`
///
/// Source: RFC 8479 §3.
#[allow(unused_imports, dead_code)]
pub mod pk_validation_attr_types {
    include!(concat!(env!("OUT_DIR"), "/pk_validation_attr_generated.rs"));
}

/// RFC 7633 TLS-Feature-Module-2015 — TLS features certificate extension.
///
/// The `TLSFeature` extension (`id-pe-tlsfeature`, 1.3.6.1.5.5.7.1.24) carries
/// a sequence of TLS extension identifiers (as integers) that a relying party
/// must request in the TLS handshake.  The most common use is to require OCSP
/// stapling (`status_request`, value 5).
///
/// Key types:
/// - [`tls_feature_module_types::Features`] — `SEQUENCE OF INTEGER`
///
/// Key constants:
/// - `id-pe-tlsfeature` — OID 1.3.6.1.5.5.7.1.24
///
/// Source: RFC 7633 Appendix A.
#[allow(unused_imports, dead_code)]
pub mod tls_feature_module_types {
    include!(concat!(env!("OUT_DIR"), "/tls_feature_module_generated.rs"));
}

/// RFC 9814 SLH-DSA (SPHINCS+) X.509 key-container types.
///
/// Generated from `asn1/SLH-DSA-Module-2024.asn1`.  Defines the raw OCTET STRING
/// containers for SLH-DSA public and private keys as placed in
/// `SubjectPublicKeyInfo.subjectPublicKey` and `OneAsymmetricKey.privateKey`.
///
/// Key types:
/// - [`SlhDsaPublicKey`] — public key octet string (32, 48, or 64 bytes depending
///   on the SLH-DSA parameter set: sha2-128, sha2-192/shake-192, sha2-256/shake-256)
/// - [`SlhDsaPrivateKey`] — private key octet string (64, 96, or 128 bytes)
///
/// All SLH-DSA algorithm OIDs (`id-slh-dsa-sha2-128s` through `id-slh-dsa-shake-256f`)
/// are already present in [`crate::oids`] from the base X.509 schema.
///
/// [`SlhDsaPublicKey`]: slh_dsa_module_2024_types::SlhDsaPublicKey
/// [`SlhDsaPrivateKey`]: slh_dsa_module_2024_types::SlhDsaPrivateKey
pub mod slh_dsa_module_2024_types {
    include!(concat!(
        env!("OUT_DIR"),
        "/slh_dsa_module_2024_generated.rs"
    ));
}

/// RFC 9881 X.509 ML-DSA (CRYSTALS-Dilithium) algorithm identifier module.
///
/// Generated from `asn1/X509-ML-DSA-2025.asn1`.  All ML-DSA types and OID constants
/// from RFC 9881 are provided by the existing crate infrastructure:
///
/// - OID constants (`id-ml-dsa-44`, `id-ml-dsa-65`, `id-ml-dsa-87`) — in [`crate::oids`]
/// - Key structure types — in [`crate::mldsa_types`]
///
/// This module is a documentation stub confirming the RFC 9881 module identity
/// (`id-mod-x509-ml-dsa-2025`, OID 1.3.6.1.5.5.7.0.119).  It generates no new
/// Rust types as all structural content is already covered.
pub mod x509_ml_dsa_2025_types {
    include!(concat!(env!("OUT_DIR"), "/x509_ml_dsa_2025_generated.rs"));
}

/// RFC 9935 ML-KEM (CRYSTALS-Kyber) X.509 key-container types.
///
/// Generated from `asn1/X509-ML-KEM-2025.asn1`.  Defines the private and public key
/// structure types for the three ML-KEM parameter sets as specified in RFC 9935.
///
/// ML-KEM OID constants (`id-ml-kem-512`, `id-ml-kem-768`, `id-ml-kem-1024`) are
/// already in [`crate::oids`] from the base X.509 schema.
/// RFC 9935 refers to the same OID values as `id-alg-ml-kem-512/768/1024`.
///
/// Key types:
/// - [`MlKem512PrivateKey`] / [`MlKem768PrivateKey`] / [`MlKem1024PrivateKey`] — CHOICE
///   of seed (64 B), expandedKey, or both; parallel structure to ML-DSA private keys
/// - [`MlKem512PublicKey`] / [`MlKem768PublicKey`] / [`MlKem1024PublicKey`] — raw public
///   key octet strings (800 / 1184 / 1568 bytes)
/// - `MlKem512PrivateKeyBoth` / `MlKem768PrivateKeyBoth` / `MlKem1024PrivateKeyBoth` —
///   helper SEQUENCE structs for the `both` arm of each private key CHOICE
///
/// Information Object Class assignments (PUBLIC-KEY, KEM-ALGORITHM instances) are not
/// representable in synta-codegen and are omitted.
///
/// [`MlKem512PrivateKey`]: x509_ml_kem_2025_types::MlKem512PrivateKey
/// [`MlKem768PrivateKey`]: x509_ml_kem_2025_types::MlKem768PrivateKey
/// [`MlKem1024PrivateKey`]: x509_ml_kem_2025_types::MlKem1024PrivateKey
/// [`MlKem512PublicKey`]: x509_ml_kem_2025_types::MlKem512PublicKey
/// [`MlKem768PublicKey`]: x509_ml_kem_2025_types::MlKem768PublicKey
/// [`MlKem1024PublicKey`]: x509_ml_kem_2025_types::MlKem1024PublicKey
pub mod x509_ml_kem_2025_types {
    include!(concat!(env!("OUT_DIR"), "/x509_ml_kem_2025_generated.rs"));
}

// ── Decryption trait and no-op sentinel ──────────────────────────────────────

pub mod crypto;
pub use crypto::{
    constant_time_eq, default_key_id_hasher, default_signature_verifier, BackendPrivateKey,
    BackendPublicKey, BlockCipherProvider, CertificateSigner, CmsDecryptor, CmsEncryptor,
    DataHasher, Encryptor, EnvelopedDataDecryptor, ErasedCertificateSigner, ErasedDataHasher,
    ErasedHmacProvider, ErasedKeyIdHasher, ErasedSignatureVerifier, ErasedStreamingHasher,
    ErasedStreamingHmacProvider, HashState, HmacProvider, HmacState, KeyDecryptor, KeyEncryptor,
    KeyIdHasher, KeyIdMethod, KeySpec, KeyWrapAlgorithm, NoCmsDecryptor, NoCrypto, NoCryptoError,
    NoEncryptor, NoEncryptorError, NoEnvelopedDataDecryptor, NoEnvelopedDataDecryptorError,
    NoKeyIdHasher, NoKeyIdHasherError, NoPkcs12Encryptor, NoSignatureVerifier,
    NoSignatureVerifierError, NoSigner, NoSignerError, NoSymmetricCrypto, Pbkdf2Provider,
    Pkcs12Decryptor, Pkcs12Encryptor, PrivateKey, PrivateKeyBuilder, PrivateKeyError,
    RsaPrivateComponents, SecureRandom, SignatureVerifier, StreamingHasher, StreamingHmacProvider,
    UnsignedCertificateSigner,
};
#[cfg(any(feature = "openssl", feature = "nss"))]
pub use crypto::{
    default_create_enveloped_data, default_prepare_enveloped_data, DefaultCrypto,
    DefaultCryptoError, DefaultEnvelopedDataDecryptor,
};
pub use crypto::{hkdf_expand, hkdf_extract, hmac_output_len};

/// Return the default [`DataHasher`] for the active crypto backend.
///
/// When the `openssl` feature is enabled, returns an OpenSSL-backed hasher.
/// Returns a [`PrivateKeyError`]-yielding stub when no backend is available.
///
/// The returned [`Box<dyn ErasedDataHasher>`] implements [`DataHasher`] directly
/// via a blanket impl, so it can be stored in a struct field or passed to any
/// function accepting `impl DataHasher`, without naming the backend type.
pub fn default_data_hasher() -> Box<dyn crypto::ErasedDataHasher> {
    #[cfg(all(feature = "nss", not(feature = "openssl")))]
    {
        crate::nss_backend::nss_data_hasher()
    }
    #[cfg(feature = "openssl")]
    {
        crate::openssl_backend::openssl_data_hasher()
    }
    #[cfg(not(any(feature = "openssl", feature = "nss")))]
    {
        Box::new(crypto::NoSymmetricCrypto)
    }
}

/// Return the default [`HmacProvider`] for the active crypto backend.
///
/// When the `openssl` feature is enabled, returns an OpenSSL-backed provider.
/// Returns a [`PrivateKeyError`]-yielding stub when no backend is available.
///
/// The returned [`Box<dyn ErasedHmacProvider>`] implements [`HmacProvider`]
/// directly via a blanket impl, so it can be stored in a struct field or passed
/// to any function accepting `impl HmacProvider`, without naming the backend
/// type.
pub fn default_hmac_provider() -> Box<dyn crypto::ErasedHmacProvider> {
    #[cfg(all(feature = "nss", not(feature = "openssl")))]
    {
        crate::nss_backend::nss_hmac_provider()
    }
    #[cfg(feature = "openssl")]
    {
        crate::openssl_backend::openssl_hmac_provider()
    }
    #[cfg(not(any(feature = "openssl", feature = "nss")))]
    {
        Box::new(crypto::NoSymmetricCrypto)
    }
}

/// Return the default [`StreamingHasher`] for the active crypto backend.
///
/// When the `nss` feature is enabled, returns an NSS PKCS#11-backed hasher.
/// When the `openssl` feature is enabled (and `nss` is not), returns an
/// OpenSSL-backed hasher.  Returns a [`PrivateKeyError`]-yielding stub when no
/// backend is available.
///
/// The returned [`Box<dyn ErasedStreamingHasher>`] implements [`StreamingHasher`]
/// directly via a blanket impl, so it can be stored in a struct field or passed
/// to any function accepting `impl StreamingHasher`, without naming the backend
/// type.
///
/// [`StreamingHasher`]: crypto::StreamingHasher
/// [`ErasedStreamingHasher`]: crypto::ErasedStreamingHasher
pub fn default_streaming_hasher() -> Box<dyn crypto::ErasedStreamingHasher> {
    #[cfg(all(feature = "nss", not(feature = "openssl")))]
    {
        crate::nss_backend::nss_streaming_hasher()
    }
    #[cfg(feature = "openssl")]
    {
        crate::openssl_backend::openssl_streaming_hasher()
    }
    #[cfg(not(any(feature = "openssl", feature = "nss")))]
    {
        Box::new(crypto::NoSymmetricCrypto)
    }
}

/// Return the default [`StreamingHmacProvider`] for the active crypto backend.
///
/// The returned [`Box<dyn ErasedStreamingHmacProvider>`] implements
/// [`StreamingHmacProvider`] directly via a blanket impl.
pub fn default_streaming_hmac_provider() -> Box<dyn crypto::ErasedStreamingHmacProvider> {
    #[cfg(all(feature = "nss", not(feature = "openssl")))]
    {
        crate::nss_backend::nss_streaming_hmac_provider()
    }
    #[cfg(feature = "openssl")]
    {
        crate::openssl_backend::openssl_streaming_hmac_provider()
    }
    #[cfg(not(any(feature = "openssl", feature = "nss")))]
    {
        Box::new(crypto::NoSymmetricCrypto)
    }
}

/// Return the default [`Pbkdf2Provider`] for the active crypto backend.
pub fn default_pbkdf2_provider() -> impl crypto::Pbkdf2Provider {
    #[cfg(all(feature = "nss", not(feature = "openssl")))]
    {
        crate::nss_backend::nss_pbkdf2_provider()
    }
    #[cfg(feature = "openssl")]
    {
        crate::openssl_backend::openssl_symmetric_crypto()
    }
    #[cfg(not(any(feature = "openssl", feature = "nss")))]
    {
        crypto::NoSymmetricCrypto
    }
}

/// Return the default [`BlockCipherProvider`] for the active crypto backend.
pub fn default_block_cipher_provider() -> impl crypto::BlockCipherProvider {
    #[cfg(all(feature = "nss", not(feature = "openssl")))]
    {
        crate::nss_backend::nss_block_cipher_provider()
    }
    #[cfg(feature = "openssl")]
    {
        crate::openssl_backend::openssl_symmetric_crypto()
    }
    #[cfg(not(any(feature = "openssl", feature = "nss")))]
    {
        crypto::NoSymmetricCrypto
    }
}

/// Return the default [`SecureRandom`] for the active crypto backend.
pub fn default_secure_random() -> impl crypto::SecureRandom {
    #[cfg(all(feature = "nss", not(feature = "openssl")))]
    {
        crate::nss_backend::nss_secure_random()
    }
    #[cfg(feature = "openssl")]
    {
        crate::openssl_backend::openssl_symmetric_crypto()
    }
    #[cfg(not(any(feature = "openssl", feature = "nss")))]
    {
        crypto::NoSymmetricCrypto
    }
}

// ── PKCS#7 certificate extraction ────────────────────────────────────────────

pub mod pkcs7;
pub use pkcs7::{certs_from_pkcs7, Pkcs7Error};

// ── PKCS#12 certificate extraction ───────────────────────────────────────────

pub mod pkcs12;
pub use pkcs12::{certs_from_pkcs12, keys_from_pkcs12, pki_from_pkcs12, Pkcs12Error, Pkcs12Pki};

// ── PKCS#12 archive builder ───────────────────────────────────────────────────

pub mod pkcs12_builder;
pub use pkcs12_builder::{Pkcs12Builder, Pkcs12BuilderError};

// ── CMS EnvelopedData builder ─────────────────────────────────────────────────

pub mod enveloped_data_builder;
pub use enveloped_data_builder::{EnvelopedDataBuilder, EnvelopedDataBuilderError};

// ── NSS crypto backend (optional feature) ────────────────────────────────────

#[cfg(all(feature = "nss", not(feature = "openssl")))]
pub mod nss_backend;
#[cfg(all(feature = "nss", not(feature = "openssl")))]
pub use nss_backend::{NssKeyIdHasher, NssSignatureVerifier, NssVerifierError};

// ── OpenSSL crypto backend (optional feature) ─────────────────────────────────

#[cfg(feature = "openssl")]
pub mod openssl_backend;
#[cfg(feature = "openssl")]
pub use openssl_backend::{
    create_enveloped_data, prepare_enveloped_data, OpensslCertificateSigner,
    OpensslCertificateSignerError, OpensslDecryptor, OpensslDecryptorError, OpensslEncryptor,
    OpensslEncryptorError, OpensslEnvelopedDataDecryptor, OpensslKeyError, OpensslKeyIdHasher,
    OpensslKeyIdHasherError, OpensslPkcs12Encryptor, OpensslPrivateKey, OpensslRsaOaepDecryptor,
    OpensslRsaOaepEncryptor, OpensslRsaPkcs1Decryptor, OpensslRsaPkcs1Encryptor,
    OpensslSignatureVerifier, OpensslSymmetricCrypto, OpensslSymmetricError, OpensslVerifierError,
    Pkcs12Cipher, Pkcs12Config, Pkcs12HmacAlgorithm,
};

// ── X.509 extension value builders ───────────────────────────────────────────

pub mod ext_builder;
pub use ext_builder::{
    encode_authority_key_identifier, encode_basic_constraints, encode_key_usage,
    encode_subject_key_identifier, AuthorityInformationAccessBuilder, CRLDistributionPointsBuilder,
    CertificatePoliciesBuilder, ExtendedKeyUsageBuilder, IssuerAlternativeNameBuilder,
    IssuingDistributionPointBuilder, NameConstraintsBuilder, SubjectAlternativeNameBuilder,
};

// ── Certificate builder ───────────────────────────────────────────────────────

pub mod builder;
pub use builder::{BuilderError, CertificateBuilder};

pub mod csr_builder;
pub use csr_builder::{CsrBuilder, CsrBuilderError};

/// Builder for RFC 5755 Attribute Certificate TBS encoding.
///
/// [`AttributeCertificateBuilder`] assembles the `AttributeCertificateInfo`
/// (TBS) SEQUENCE using generated [`attribute_cert_types`] and [`GeneralNameSpec`].
pub mod ac_builder;
pub use ac_builder::AttributeCertificateBuilder;

/// Builder for RFC 5280 §5 Certificate Revocation List TBS encoding.
///
/// [`CertificateListBuilder`] assembles a `TBSCertList` DER blob suitable
/// for external signing.  Call [`CertificateListBuilder::assemble`] to wrap
/// the signed TBS in the outer `CertificateList` SEQUENCE.
pub mod crl_builder;
pub use crl_builder::CertificateListBuilder;

/// Builder for RFC 6960 OCSP response encoding.
///
/// [`OCSPResponseBuilder`] assembles a `ResponseData` DER blob suitable for
/// external signing.  Call [`OCSPResponseBuilder::assemble`] to wrap the
/// signed TBS in the complete `OCSPResponse` envelope.
pub mod ocsp_builder;
pub use ocsp_builder::{OCSPResponseBuilder, SingleResponseSpec};

/// Builder for RFC 6960 OCSP request encoding.
///
/// [`OCSPRequestBuilder`] assembles a `TBSRequest` DER blob suitable for
/// direct submission to an OCSP responder (unsigned) or for external signing.
/// Call [`OCSPRequestBuilder::assemble`] to wrap the signed TBS in the complete
/// `OCSPRequest` envelope when a signature is required.
pub mod ocsp_request_builder;
pub use ocsp_request_builder::{CertIDSpec, OCSPRequestBuilder};

/// Builder for RFC 3161 Time-Stamp Protocol (TSP) request encoding.
///
/// [`TimeStampReqBuilder`] assembles a `TimeStampReq` DER blob suitable for
/// submission to a Time Stamping Authority (TSA).
pub mod tsp_builder;
pub use tsp_builder::TimeStampReqBuilder;

/// Builders for RFC 2634 Extended Security Services (ESS) structures.
///
/// - [`SigningCertificateBuilder`] — assembles a `SigningCertificate` DER blob.
/// - [`ReceiptRequestBuilder`] — assembles a `ReceiptRequest` DER blob.
/// - [`ESSSecurityLabelBuilder`] — assembles an `ESSSecurityLabel` DER blob.
pub mod ess_builder;
pub use ess_builder::{ESSSecurityLabelBuilder, ReceiptRequestBuilder, SigningCertificateBuilder};

/// Builders for PKCS #5 v2.1 (RFC 8018) parameter structures.
///
/// - [`Pbkdf2ParamsBuilder`] — assembles `Pkcs5Pbkdf2Params` DER.
/// - [`Pbes2ParamsBuilder`] — assembles `Pkcs5Pbes2Params` DER.
pub mod pkcs5_builder;
pub use pkcs5_builder::{Pbes2ParamsBuilder, Pbkdf2ParamsBuilder};

/// Builder for RFC 9399 Logotype certificate extension (OID 1.3.6.1.5.5.7.1.12).
///
/// [`LogotypeExtnBuilder`] assembles a `LogotypeExtn` DER value for use as
/// the `id-pe-logotype` extension value.
pub mod logotype_builder;
pub use logotype_builder::{LogotypeDetailsSpec, LogotypeExtnBuilder};

/// Builder for RFC 7773 Authentication Context certificate extension (ACE-88).
///
/// [`AuthenticationContextsBuilder`] assembles an `AuthenticationContexts`
/// DER SEQUENCE OF for the `id-ce-authContext` extension value.
pub mod ace88_builder;
pub use ace88_builder::AuthenticationContextsBuilder;

// ── Format-agnostic PKI reader ────────────────────────────────────────────────

pub mod reader;
pub use reader::{read_pki_blocks, PkiDecryptor, ReadAnyError};

// ============================================================================
// Helper functions
// ============================================================================

/// Return the canonical display name for a signature algorithm OID.
///
/// Recognizes specific PKCS #1 RSA variants (MD5, SHA-1, SHA-256, SHA-384,
/// SHA-512), ECDSA variants (SHA-1, SHA-256, SHA-384, SHA-512), DSA,
/// EdDSA (Ed25519/Ed448), and post-quantum ML-DSA (FIPS 204). Returns
/// [`names::OTHER`] for any OID not in those families. Return values are
/// [`names`] constants, so callers can compare with `==` or pattern-match
/// on them directly.
///
/// # Performance note
///
/// All families use two-level integer dispatch rather than `&[u32]` slice
/// equality: a length+prefix check selects the family, then a `u32` match
/// dispatches to the variant. All discriminant values are derived from the
/// generated `oids` constants via const-indexing, so they stay in sync with
/// the ASN.1 schema automatically. Unknown RSA/ECDSA/DSA variants fall
/// through to `starts_with` prefix checks as a final safety net.
pub fn identify_signature_algorithm(oid: &ObjectIdentifier) -> &'static str {
    let c = oid.components();

    // ── EdDSA (RFC 8410): [1, 3, 101, sub] — 4 arcs ─────────────────────────
    const ED0: u32 = oids::ED25519[0]; // 1
    const ED1: u32 = oids::ED25519[1]; // 3
    const ED2: u32 = oids::ED25519[2]; // 101
    const ED25519_V: u32 = oids::ED25519[3]; // 112
    const ED448_V: u32 = oids::ED448[3]; // 113

    // ── ML-DSA (FIPS 204): [2, 16, 840, 1, 101, 3, 4, 3, sub] — 9 arcs ─────
    // First 7 arcs are shared with ML-KEM; arc[7]=3 selects the ML-DSA family.
    const PQC0: u32 = oids::ML_DSA_44[0]; // 2
    const PQC1: u32 = oids::ML_DSA_44[1]; // 16
    const PQC2: u32 = oids::ML_DSA_44[2]; // 840
    const PQC3: u32 = oids::ML_DSA_44[3]; // 1
    const PQC4: u32 = oids::ML_DSA_44[4]; // 101
    const PQC5: u32 = oids::ML_DSA_44[5]; // 3
    const PQC6: u32 = oids::ML_DSA_44[6]; // 4
    const MLDSA_D: u32 = oids::ML_DSA_44[7]; // 3
    const MLDSA44_V: u32 = oids::ML_DSA_44[8]; // 17
    const MLDSA65_V: u32 = oids::ML_DSA_65[8]; // 18
    const MLDSA87_V: u32 = oids::ML_DSA_87[8]; // 19

    // ── RSA (PKCS #1): [1, 2, 840, 113549, 1, 1, sub] — 7 arcs ─────────────
    const RSA0: u32 = oids::RSA[0]; // 1
    const RSA1: u32 = oids::RSA[1]; // 2
    const RSA2: u32 = oids::RSA[2]; // 840
    const RSA3: u32 = oids::RSA[3]; // 113549
    const RSA4: u32 = oids::RSA[4]; // 1
    const RSA5: u32 = oids::RSA[5]; // 1
    const MD5_RSA_V: u32 = oids::MD5_WITH_RSA[6]; // 4
    const SHA1_RSA_V: u32 = oids::SHA1_WITH_RSA[6]; // 5
    const SHA256_RSA_V: u32 = oids::SHA256_WITH_RSA[6]; // 11
    const SHA384_RSA_V: u32 = oids::SHA384_WITH_RSA[6]; // 12
    const SHA512_RSA_V: u32 = oids::SHA512_WITH_RSA[6]; // 13

    // ── ECDSA (ANSI X9.62 / RFC 5758) ────────────────────────────────────────
    // SHA-1: [1, 2, 840, 10045, 4, 1] — 6 arcs.
    // SHA-2: [1, 2, 840, 10045, 4, 3, sub] — 7 arcs; arc[5]=3 is the sub-family.
    const EC0: u32 = oids::ECDSA_SIG[0]; // 1
    const EC1: u32 = oids::ECDSA_SIG[1]; // 2
    const EC2: u32 = oids::ECDSA_SIG[2]; // 840
    const EC3: u32 = oids::ECDSA_SIG[3]; // 10045
    const EC4: u32 = oids::ECDSA_SIG[4]; // 4
    const ECDSA_SHA1_V: u32 = oids::ECDSA_WITH_SHA1[5]; // 1
    const ECDSA_SUB: u32 = oids::ECDSA_WITH_SHA256[5]; // 3
    const ECDSA_SHA256_V: u32 = oids::ECDSA_WITH_SHA256[6]; // 2
    const ECDSA_SHA384_V: u32 = oids::ECDSA_WITH_SHA384[6]; // 3
    const ECDSA_SHA512_V: u32 = oids::ECDSA_WITH_SHA512[6]; // 4

    // Length + prefix check, then integer dispatch on the sub-variant arc.
    if let &[ED0, ED1, ED2, sub] = c {
        return match sub {
            ED25519_V => names::ED25519,
            ED448_V => names::ED448,
            _ => names::OTHER,
        };
    }
    if let &[PQC0, PQC1, PQC2, PQC3, PQC4, PQC5, PQC6, MLDSA_D, sub] = c {
        match sub {
            MLDSA44_V => return names::ML_DSA_44,
            MLDSA65_V => return names::ML_DSA_65,
            MLDSA87_V => return names::ML_DSA_87,
            _ => {} // Unknown 9-arc NIST PQC OID with ML-DSA family arc.
        }
    }
    if let &[RSA0, RSA1, RSA2, RSA3, RSA4, RSA5, sub] = c {
        return match sub {
            MD5_RSA_V => names::MD5_WITH_RSA,
            SHA1_RSA_V => names::SHA1_WITH_RSA,
            SHA256_RSA_V => names::SHA256_WITH_RSA,
            SHA384_RSA_V => names::SHA384_WITH_RSA,
            SHA512_RSA_V => names::SHA512_WITH_RSA,
            _ => names::RSA, // Unknown PKCS #1 variant (e.g. rsaEncryption, PSS).
        };
    }
    if let &[EC0, EC1, EC2, EC3, EC4, ECDSA_SHA1_V] = c {
        return names::ECDSA_WITH_SHA1;
    }
    if let &[EC0, EC1, EC2, EC3, EC4, ECDSA_SUB, sub] = c {
        return match sub {
            ECDSA_SHA256_V => names::ECDSA_WITH_SHA256,
            ECDSA_SHA384_V => names::ECDSA_WITH_SHA384,
            ECDSA_SHA512_V => names::ECDSA_WITH_SHA512,
            _ => names::ECDSA, // Unknown 7-arc ECDSA variant.
        };
    }

    // ── id-alg-unsigned (RFC 9925): [1, 3, 6, 1, 5, 5, 7, 6, 36] — 9 arcs ─────
    const UNSIGNED_OID: &[u32] = oids::ALG_UNSIGNED;
    if c == UNSIGNED_OID {
        return names::UNSIGNED;
    }

    // ── Composite ML-DSA (draft-ietf-lamps-pq-composite-sigs): [1,3,6,1,5,5,7,6,sub] — 9 arcs ─
    // Arc prefix shared with id-alg-unsigned; sub-arc 37–54 selects the variant.
    const CA0: u32 = oids::COMPOSITE_MLDSA_ARC[0]; // 1
    const CA1: u32 = oids::COMPOSITE_MLDSA_ARC[1]; // 3
    const CA2: u32 = oids::COMPOSITE_MLDSA_ARC[2]; // 6
    const CA3: u32 = oids::COMPOSITE_MLDSA_ARC[3]; // 1
    const CA4: u32 = oids::COMPOSITE_MLDSA_ARC[4]; // 5
    const CA5: u32 = oids::COMPOSITE_MLDSA_ARC[5]; // 5
    const CA6: u32 = oids::COMPOSITE_MLDSA_ARC[6]; // 7
    const CA7: u32 = oids::COMPOSITE_MLDSA_ARC[7]; // 6
    if let &[CA0, CA1, CA2, CA3, CA4, CA5, CA6, CA7, sub] = c {
        match sub {
            37 => return names::MLDSA44_RSA2048_PSS_SHA256,
            38 => return names::MLDSA44_RSA2048_PKCS15_SHA256,
            39 => return names::MLDSA44_ED25519_SHA512,
            40 => return names::MLDSA44_ECDSA_P256_SHA256,
            41 => return names::MLDSA65_RSA3072_PSS_SHA512,
            42 => return names::MLDSA65_RSA3072_PKCS15_SHA512,
            43 => return names::MLDSA65_RSA4096_PSS_SHA512,
            44 => return names::MLDSA65_RSA4096_PKCS15_SHA512,
            45 => return names::MLDSA65_ECDSA_P256_SHA512,
            46 => return names::MLDSA65_ECDSA_P384_SHA512,
            47 => return names::MLDSA65_ECDSA_BRAINPOOL_P256R1_SHA512,
            48 => return names::MLDSA65_ED25519_SHA512,
            49 => return names::MLDSA87_ECDSA_P384_SHA512,
            50 => return names::MLDSA87_ECDSA_BRAINPOOL_P384R1_SHA512,
            51 => return names::MLDSA87_ED448_SHAKE256,
            52 => return names::MLDSA87_RSA3072_PSS_SHA512,
            53 => return names::MLDSA87_RSA4096_PSS_SHA512,
            54 => return names::MLDSA87_ECDSA_P521_SHA512,
            _ => {} // Unknown id-alg sub-arc.
        }
    }

    // Safety net for RSA/ECDSA/DSA OIDs with arc counts not matched above.
    if c.starts_with(oids::RSA) {
        names::RSA
    } else if c.starts_with(oids::ECDSA_SIG) {
        names::ECDSA
    } else if c.starts_with(oids::DSA) {
        names::DSA
    } else {
        names::OTHER
    }
}

/// Return the canonical display name for a public key algorithm OID, if known.
///
/// Recognizes RSA, EC/ECDSA, DSA, EdDSA (Ed25519/Ed448), post-quantum
/// ML-DSA (FIPS 204) and ML-KEM (FIPS 203), and all 18 composite ML-DSA
/// algorithms (draft-ietf-lamps-pq-composite-sigs). Returns `None` for
/// unrecognized OIDs. Return values are [`names`] constants.
///
/// # Performance note
///
/// Same two-level dispatch as [`identify_signature_algorithm`].  ML-DSA and
/// ML-KEM share a 7-arc NIST PQC prefix; arc\[7\] (3 vs 4) selects the family
/// and arc\[8\] selects the variant.  Composite ML-DSA OIDs share the id-alg
/// arc prefix `[1,3,6,1,5,5,7,6]` and use sub-arcs 37–54.
/// All values derived from `oids` constants.
pub fn identify_public_key_algorithm(oid: &ObjectIdentifier) -> Option<&'static str> {
    let c = oid.components();

    // ── EdDSA (RFC 8410): [1, 3, 101, sub] — 4 arcs ─────────────────────────
    const ED0: u32 = oids::ED25519[0]; // 1
    const ED1: u32 = oids::ED25519[1]; // 3
    const ED2: u32 = oids::ED25519[2]; // 101
    const ED25519_V: u32 = oids::ED25519[3]; // 112
    const ED448_V: u32 = oids::ED448[3]; // 113

    // ── NIST PQC shared prefix: [2, 16, 840, 1, 101, 3, 4] — 7 arcs ─────────
    // arc[7]: 3 = ML-DSA family, 4 = ML-KEM family.
    const PQC0: u32 = oids::ML_DSA_44[0]; // 2
    const PQC1: u32 = oids::ML_DSA_44[1]; // 16
    const PQC2: u32 = oids::ML_DSA_44[2]; // 840
    const PQC3: u32 = oids::ML_DSA_44[3]; // 1
    const PQC4: u32 = oids::ML_DSA_44[4]; // 101
    const PQC5: u32 = oids::ML_DSA_44[5]; // 3
    const PQC6: u32 = oids::ML_DSA_44[6]; // 4

    // ML-DSA (FIPS 204): arc[7] = 3, arc[8] = variant.
    const MLDSA_D: u32 = oids::ML_DSA_44[7]; // 3
    const MLDSA44_V: u32 = oids::ML_DSA_44[8]; // 17
    const MLDSA65_V: u32 = oids::ML_DSA_65[8]; // 18
    const MLDSA87_V: u32 = oids::ML_DSA_87[8]; // 19

    // ML-KEM (FIPS 203): arc[7] = 4, arc[8] = variant.
    const MLKEM_D: u32 = oids::ML_KEM_512[7]; // 4
    const MLKEM512_V: u32 = oids::ML_KEM_512[8]; // 1
    const MLKEM768_V: u32 = oids::ML_KEM_768[8]; // 2
    const MLKEM1024_V: u32 = oids::ML_KEM_1024[8]; // 3

    // EdDSA: length + prefix check, then integer dispatch on sub-variant arc.
    if let &[ED0, ED1, ED2, sub] = c {
        return match sub {
            ED25519_V => Some(names::ED25519),
            ED448_V => Some(names::ED448),
            _ => None,
        };
    }

    // NIST PQC: length + shared-prefix check, then dispatch on family (arc[7])
    // and variant (arc[8]).
    if let &[PQC0, PQC1, PQC2, PQC3, PQC4, PQC5, PQC6, d, sub] = c {
        match d {
            MLDSA_D => {
                return match sub {
                    MLDSA44_V => Some(names::ML_DSA_44),
                    MLDSA65_V => Some(names::ML_DSA_65),
                    MLDSA87_V => Some(names::ML_DSA_87),
                    _ => None,
                }
            }
            MLKEM_D => {
                return match sub {
                    MLKEM512_V => Some(names::ML_KEM_512),
                    MLKEM768_V => Some(names::ML_KEM_768),
                    MLKEM1024_V => Some(names::ML_KEM_1024),
                    _ => None,
                }
            }
            _ => {} // Unknown 9-arc NIST PQC OID, fall through.
        }
    }

    // ── Composite ML-DSA (draft-ietf-lamps-pq-composite-sigs): [1,3,6,1,5,5,7,6,sub] ─
    const CA0: u32 = oids::COMPOSITE_MLDSA_ARC[0]; // 1
    const CA1: u32 = oids::COMPOSITE_MLDSA_ARC[1]; // 3
    const CA2: u32 = oids::COMPOSITE_MLDSA_ARC[2]; // 6
    const CA3: u32 = oids::COMPOSITE_MLDSA_ARC[3]; // 1
    const CA4: u32 = oids::COMPOSITE_MLDSA_ARC[4]; // 5
    const CA5: u32 = oids::COMPOSITE_MLDSA_ARC[5]; // 5
    const CA6: u32 = oids::COMPOSITE_MLDSA_ARC[6]; // 7
    const CA7: u32 = oids::COMPOSITE_MLDSA_ARC[7]; // 6
    if let &[CA0, CA1, CA2, CA3, CA4, CA5, CA6, CA7, sub] = c {
        let name = match sub {
            37 => names::MLDSA44_RSA2048_PSS_SHA256,
            38 => names::MLDSA44_RSA2048_PKCS15_SHA256,
            39 => names::MLDSA44_ED25519_SHA512,
            40 => names::MLDSA44_ECDSA_P256_SHA256,
            41 => names::MLDSA65_RSA3072_PSS_SHA512,
            42 => names::MLDSA65_RSA3072_PKCS15_SHA512,
            43 => names::MLDSA65_RSA4096_PSS_SHA512,
            44 => names::MLDSA65_RSA4096_PKCS15_SHA512,
            45 => names::MLDSA65_ECDSA_P256_SHA512,
            46 => names::MLDSA65_ECDSA_P384_SHA512,
            47 => names::MLDSA65_ECDSA_BRAINPOOL_P256R1_SHA512,
            48 => names::MLDSA65_ED25519_SHA512,
            49 => names::MLDSA87_ECDSA_P384_SHA512,
            50 => names::MLDSA87_ECDSA_BRAINPOOL_P384R1_SHA512,
            51 => names::MLDSA87_ED448_SHAKE256,
            52 => names::MLDSA87_RSA3072_PSS_SHA512,
            53 => names::MLDSA87_RSA4096_PSS_SHA512,
            54 => names::MLDSA87_ECDSA_P521_SHA512,
            _ => return None, // Unknown id-alg sub-arc.
        };
        return Some(name);
    }

    // RSA / ECDSA / DSA: variable-length OIDs, identified by arc prefix.
    if c.starts_with(oids::RSA) {
        Some(names::RSA)
    } else if c.starts_with(oids::ECDSA_KEY) {
        Some(names::ECDSA)
    } else if c.starts_with(oids::DSA) {
        Some(names::DSA)
    } else {
        None
    }
}

/// Build and DER-encode a signing `AlgorithmIdentifier` from a key type OID and
/// a hash algorithm name.
///
/// This is the companion to [`identify_signature_algorithm`] and
/// [`identify_public_key_algorithm`]: given the key type OID (as found in the
/// `algorithm` field of a PKCS#8 `PrivateKeyInfo`) and a hash algorithm name,
/// returns the DER-encoded `AlgorithmIdentifier` for the corresponding signing
/// operation.  RSA algorithms include a `NULL` parameters element (as required
/// by RFC 3279 §2.2.1); EdDSA and ML-DSA algorithms have no parameters.
///
/// # Supported mappings
///
/// | Key OID | `hash_algo` | Signing OID |
/// |---|---|---|
/// | `id-ecPublicKey` | `"sha256"` | `ecdsa-with-SHA256` |
/// | `id-ecPublicKey` | `"sha384"` | `ecdsa-with-SHA384` |
/// | `id-ecPublicKey` | `"sha512"` | `ecdsa-with-SHA512` |
/// | `rsaEncryption` | `"sha1"` | `sha1WithRSAEncryption` |
/// | `rsaEncryption` | `"sha256"` | `sha256WithRSAEncryption` |
/// | `rsaEncryption` | `"sha384"` | `sha384WithRSAEncryption` |
/// | `rsaEncryption` | `"sha512"` | `sha512WithRSAEncryption` |
/// | `id-Ed25519` | (ignored) | `id-Ed25519` |
/// | `id-Ed448` | (ignored) | `id-Ed448` |
/// | `id-ML-DSA-44` | (ignored) | `id-ML-DSA-44` |
/// | `id-ML-DSA-65` | (ignored) | `id-ML-DSA-65` |
/// | `id-ML-DSA-87` | (ignored) | `id-ML-DSA-87` |
///
/// Returns `None` if the key OID is unrecognised, the `hash_algo` is not valid
/// for the key type, or DER encoding fails.
pub fn signing_algorithm_der(key_oid: &ObjectIdentifier, hash_algo: &str) -> Option<Vec<u8>> {
    use synta::{Element, Null};

    // ── Signing OID + RSA NULL-params flag ────────────────────────────────────
    let (sig_oid_comps, null_params): (&[u32], bool) = {
        let c = key_oid.components();

        if c == oids::EC_PUBLIC_KEY {
            let sig = match hash_algo {
                "sha256" => oids::ECDSA_WITH_SHA256,
                "sha384" => oids::ECDSA_WITH_SHA384,
                "sha512" => oids::ECDSA_WITH_SHA512,
                _ => return None,
            };
            (sig, false)
        } else if c == oids::RSA_ENCRYPTION {
            let sig = match hash_algo {
                "sha1" => oids::SHA1_WITH_RSA,
                "sha256" => oids::SHA256_WITH_RSA,
                "sha384" => oids::SHA384_WITH_RSA,
                "sha512" => oids::SHA512_WITH_RSA,
                _ => return None,
            };
            (sig, true)
        } else if c == oids::ED25519 {
            (oids::ED25519, false)
        } else if c == oids::ED448 {
            (oids::ED448, false)
        } else if c == oids::ML_DSA_44 {
            (oids::ML_DSA_44, false)
        } else if c == oids::ML_DSA_65 {
            (oids::ML_DSA_65, false)
        } else if c == oids::ML_DSA_87 {
            (oids::ML_DSA_87, false)
        } else {
            return None;
        }
    };

    // ── Build and DER-encode the signing AlgorithmIdentifier ──────────────────
    let sig_oid = ObjectIdentifier::new(sig_oid_comps).ok()?;
    let sig_alg = AlgorithmIdentifier {
        algorithm: sig_oid,
        parameters: if null_params {
            Some(Element::Null(Null))
        } else {
            None
        },
    };
    sig_alg.to_der().ok()
}

/// Return the [`AlgorithmIdentifier`] for a named hash (digest) algorithm.
///
/// The returned value has a `'static` lifetime because the only borrowed field,
/// `parameters`, holds `Element::Null` which owns no data.
///
/// # Supported names
///
/// | `hash_algo` | OID |
/// |---|---|
/// | `"sha1"` | 1.3.14.3.2.26 (`id-sha1`) |
/// | `"sha256"` | 2.16.840.1.101.3.4.2.1 (`id-sha256`) |
/// | `"sha384"` | 2.16.840.1.101.3.4.2.2 (`id-sha384`) |
/// | `"sha512"` | 2.16.840.1.101.3.4.2.3 (`id-sha512`) |
///
/// Returns `None` for unknown names.
pub fn digest_alg_id(hash_algo: &str) -> Option<AlgorithmIdentifier<'static>> {
    use synta::{Element, Null};
    let oid_comps: &[u32] = match hash_algo {
        "sha1" => oids::ID_SHA1,
        "sha256" => oids::ID_SHA256,
        "sha384" => oids::ID_SHA384,
        "sha512" => oids::ID_SHA512,
        _ => return None,
    };
    let oid = ObjectIdentifier::new(oid_comps).ok()?;
    Some(AlgorithmIdentifier {
        algorithm: oid,
        parameters: Some(Element::Null(Null)),
    })
}

/// Return the key size in bits for a well-known EC named curve OID.
///
/// Returns the field size (security parameter) of the named curve, which is
/// what tools like OpenSSL report as the "Public-Key" bit count for EC keys.
/// Returns `None` for unrecognized curves; callers should fall back to the
/// raw BIT STRING length.
///
/// # Example
///
/// ```rust
/// use synta_certificate::{oids, ec_curve_key_bits};
///
/// assert_eq!(ec_curve_key_bits(oids::EC_CURVE_P256), Some(256));
/// assert_eq!(ec_curve_key_bits(oids::EC_CURVE_P384), Some(384));
/// assert_eq!(ec_curve_key_bits(oids::EC_CURVE_P521), Some(521));
/// assert_eq!(ec_curve_key_bits(&[1, 2, 3]), None);
/// ```
pub fn ec_curve_key_bits(c: &[u32]) -> Option<usize> {
    match c {
        _ if c == oids::EC_CURVE_P256 => Some(256),
        _ if c == oids::EC_CURVE_P384 => Some(384),
        _ if c == oids::EC_CURVE_P521 => Some(521),
        _ if c == oids::EC_CURVE_SECP256K1 => Some(256),
        _ => None,
    }
}

/// Return the short ASN.1 name for a well-known EC named curve OID.
///
/// Returns `None` for unrecognized curves; callers should fall back to the
/// dotted OID notation.
///
/// # Example
///
/// ```rust
/// use synta_certificate::{oids, ec_curve_short_name};
///
/// assert_eq!(ec_curve_short_name(oids::EC_CURVE_P256), Some("prime256v1"));
/// assert_eq!(ec_curve_short_name(oids::EC_CURVE_P384), Some("secp384r1"));
/// assert_eq!(ec_curve_short_name(&[1, 2, 3]), None);
/// ```
pub fn ec_curve_short_name(c: &[u32]) -> Option<&'static str> {
    match c {
        _ if c == oids::EC_CURVE_P256 => Some("prime256v1"),
        _ if c == oids::EC_CURVE_P384 => Some("secp384r1"),
        _ if c == oids::EC_CURVE_P521 => Some("secp521r1"),
        _ if c == oids::EC_CURVE_SECP256K1 => Some("secp256k1"),
        _ => None,
    }
}

/// Return the NIST curve name for a well-known EC named curve OID.
///
/// Returns `None` for curves with no NIST name (e.g. `secp256k1`).
///
/// # Example
///
/// ```rust
/// use synta_certificate::{oids, ec_curve_nist_name};
///
/// assert_eq!(ec_curve_nist_name(oids::EC_CURVE_P256), Some("P-256"));
/// assert_eq!(ec_curve_nist_name(oids::EC_CURVE_SECP256K1), None);
/// ```
pub fn ec_curve_nist_name(c: &[u32]) -> Option<&'static str> {
    match c {
        _ if c == oids::EC_CURVE_P256 => Some("P-256"),
        _ if c == oids::EC_CURVE_P384 => Some("P-384"),
        _ if c == oids::EC_CURVE_P521 => Some("P-521"),
        _ => None,
    }
}

/// Return the display name for a well-known X.509v3 extension OID.
///
/// Covers the standard RFC 5280 extensions and the Certificate Transparency
/// SCT extension. Unknown OIDs are returned as their dotted decimal notation.
///
/// # Example
///
/// ```rust
/// use synta_certificate::{oids, extension_oid_name};
/// use synta::ObjectIdentifier;
///
/// // Construct an OID from known components for testing
/// let key_usage = ObjectIdentifier::new(oids::KEY_USAGE).unwrap();
/// assert_eq!(extension_oid_name(&key_usage), "X509v3 Key Usage");
/// ```
pub fn extension_oid_name(oid: &synta::ObjectIdentifier) -> String {
    match oid.components() {
        c if c == oids::SUBJECT_KEY_IDENTIFIER => "X509v3 Subject Key Identifier".into(),
        c if c == oids::KEY_USAGE => "X509v3 Key Usage".into(),
        c if c == oids::SUBJECT_ALT_NAME => "X509v3 Subject Alternative Name".into(),
        c if c == oids::ISSUER_ALT_NAME => "X509v3 Issuer Alternative Name".into(),
        c if c == oids::BASIC_CONSTRAINTS => "X509v3 Basic Constraints".into(),
        c if c == oids::CRL_DISTRIBUTION_POINTS => "X509v3 CRL Distribution Points".into(),
        c if c == oids::CERTIFICATE_POLICIES => "X509v3 Certificate Policies".into(),
        c if c == oids::AUTHORITY_KEY_IDENTIFIER => "X509v3 Authority Key Identifier".into(),
        c if c == oids::EXTENDED_KEY_USAGE => "X509v3 Extended Key Usage".into(),
        c if c == oids::AUTHORITY_INFO_ACCESS => "Authority Information Access".into(),
        c if c == oids::CT_PRECERT_SCTS => "CT Precertificate SCTs".into(),
        _ => oid.to_string(),
    }
}

/// Decode the raw DER bytes of an Extensions SEQUENCE OF into a `Vec<Extension>`.
///
/// `raw` must be the DER of `SEQUENCE OF Extension` — exactly what
/// `tbs_certificate.extensions.as_bytes()` returns after the outer `[3]
/// EXPLICIT` tag has been stripped by the parser.  Returns an empty `Vec` on
/// decode error.
pub fn decode_extensions<'a>(raw: &'a [u8]) -> Vec<Extension<'a>> {
    use synta::Decode;
    let mut decoder = synta::Decoder::new(raw, synta::Encoding::Der);
    Vec::<Extension<'a>>::decode(&mut decoder).unwrap_or_default()
}

/// Validate the outer Certificate SEQUENCE envelope without fully decoding.
///
/// Performs a shallow 4-operation structural scan:
/// 1. outer `Certificate` SEQUENCE tag
/// 2. outer `Certificate` SEQUENCE length
/// 3. `TBSCertificate` SEQUENCE tag
/// 4. `TBSCertificate` SEQUENCE length
///
/// Returns the byte range `tbs_start..tbs_end` of the complete
/// `TBSCertificate` TLV (tag + length + content) within `data`.  The range
/// can be used to extract the exact bytes that must be covered by the
/// certificate's signature.
///
/// This is approximately 10× faster than [`Certificate::decode()`] and is
/// useful for:
/// - Pre-validation before committing to a full parse
/// - Extracting the TBS byte range for offline signature verification
/// - Benchmarking the minimum parse cost (envelope scan only)
///
/// Returns an error if `data` is not a structurally valid DER SEQUENCE (e.g.
/// truncated, wrong tag, or indefinite-length TBS).
///
/// # Example
///
/// ```rust
/// let der: &[u8] = &[
///     // Minimal Certificate: SEQUENCE { SEQUENCE {} SEQUENCE {} BIT STRING {} }
///     0x30, 0x0a,               // Certificate SEQUENCE, length 10
///     0x30, 0x00,               // TBSCertificate SEQUENCE, length 0
///     0x30, 0x00,               // signatureAlgorithm SEQUENCE, length 0
///     0x03, 0x04, 0x00, 0xde, 0xad, 0xbe, // signature BIT STRING
/// ];
/// let range = synta_certificate::validate_envelope(der).unwrap();
/// // TBS starts at byte 2 (after the 2-byte outer header), ends at byte 4
/// assert_eq!(range, 2..4);
/// ```
pub fn validate_envelope(data: &[u8]) -> synta::Result<core::ops::Range<usize>> {
    use synta::{Decoder, Encoding};
    let mut d = Decoder::new(data, Encoding::Der);
    // Outer Certificate SEQUENCE tag + length.
    d.read_tag()?;
    d.read_length()?.definite()?;
    // TBSCertificate: record full TLV range (tag + length + content).
    let tbs_start = d.position();
    d.read_tag()?;
    let tbs_content_len = d.read_length()?.definite()?;
    Ok(tbs_start..(d.position() + tbs_content_len))
}

/// Test one bit in a `KeyUsage` BIT STRING.
///
/// `n` is the named-bit index as defined in RFC 5280 §4.2.1.3 and the
/// `KEY_USAGE_*` constants exported from this crate.  Returns `true` if the
/// bit is set, `false` if the bit is absent or if `n` is beyond the length of
/// the encoding.
///
/// # Example
///
/// ```rust,ignore
/// use synta_certificate::{key_usage_bit, KEY_USAGE_KEY_CERT_SIGN};
/// let is_ca = key_usage_bit(&ku, KEY_USAGE_KEY_CERT_SIGN);
/// ```
pub fn key_usage_bit(ku: &KeyUsage, n: usize) -> bool {
    let bytes = ku.as_bytes();
    bytes
        .get(n / 8)
        .is_some_and(|&b| (b >> (7 - (n % 8))) & 1 != 0)
}

/// Byte ranges within a DER-encoded `Certificate` needed for signature
/// verification.
///
/// All ranges index into the same `cert_der` byte slice that was passed to
/// [`cert_byte_ranges`].
pub struct CertByteRanges {
    /// The complete `TBSCertificate` TLV (tag + length + content).
    pub tbs: core::ops::Range<usize>,
    /// The outer `signatureAlgorithm` TLV (tag + length + content).
    pub signature_algorithm: core::ops::Range<usize>,
    /// The `SubjectPublicKeyInfo` TLV (tag + length + content), found inside
    /// `TBSCertificate`.
    pub subject_public_key_info: core::ops::Range<usize>,
}

/// Extract the byte ranges required for certificate signature verification
/// from a DER-encoded `Certificate`.
///
/// The returned ranges all index into `cert_der`.  Typical usage:
///
/// ```rust,ignore
/// let subject_ranges = cert_byte_ranges(subject_der)?;
/// let issuer_ranges  = cert_byte_ranges(issuer_der)?;
/// verifier.verify_certificate_signature(
///     &subject_der[subject_ranges.tbs],
///     &subject_der[subject_ranges.signature_algorithm],
///     signature_bits,
///     &issuer_der[issuer_ranges.subject_public_key_info],
/// )?;
/// ```
///
/// Returns `None` if `cert_der` is structurally malformed (truncated, wrong
/// tag, or indefinite length).  The input is expected to have already passed
/// synta's strict DER decoder.
pub fn cert_byte_ranges(cert_der: &[u8]) -> Option<CertByteRanges> {
    use synta::{Decoder, Encoding, TagClass};

    let mut d = Decoder::new(cert_der, Encoding::Der);

    // Outer Certificate SEQUENCE header.
    d.read_tag().ok()?;
    d.read_length().ok()?.definite().ok()?;

    // TBSCertificate: record start, read header, skip content.
    let tbs_start = d.position();
    d.read_tag().ok()?;
    let tbs_content_len = d.read_length().ok()?.definite().ok()?;
    let tbs_content_start = d.position();
    let tbs_end = tbs_content_start + tbs_content_len;
    d.read_bytes(tbs_content_len).ok()?;

    // signatureAlgorithm: record start, read header, skip content.
    let sig_alg_start = d.position();
    d.read_tag().ok()?;
    let sig_alg_content_len = d.read_length().ok()?.definite().ok()?;
    let sig_alg_end = d.position() + sig_alg_content_len;

    // SubjectPublicKeyInfo: walk into TBS content via a fresh decoder.
    let tbs_content = cert_der.get(tbs_content_start..tbs_end)?;
    let mut t = Decoder::new(tbs_content, Encoding::Der);

    // Skip optional [0] EXPLICIT version.
    let first_tag = t.peek_tag().ok()?;
    if first_tag.class() == TagClass::ContextSpecific && first_tag.number() == 0 {
        t.read_tag().ok()?;
        let n = t.read_length().ok()?.definite().ok()?;
        t.read_bytes(n).ok()?;
    }
    // Skip serialNumber (INTEGER), signature (SEQUENCE), issuer (SEQUENCE),
    // validity (SEQUENCE), subject (SEQUENCE) — five fields, each a full TLV.
    for _ in 0..5 {
        t.read_tag().ok()?;
        let n = t.read_length().ok()?.definite().ok()?;
        t.read_bytes(n).ok()?;
    }
    // SubjectPublicKeyInfo starts here.
    let spki_start = tbs_content_start + t.position();
    t.read_tag().ok()?;
    let spki_content_len = t.read_length().ok()?.definite().ok()?;
    let spki_end = tbs_content_start + t.position() + spki_content_len;

    Some(CertByteRanges {
        tbs: tbs_start..tbs_end,
        signature_algorithm: sig_alg_start..sig_alg_end,
        subject_public_key_info: spki_start..spki_end,
    })
}

/// Format the human-readable content of a well-known X.509v3 extension value.
///
/// Returns `Some(content)` for recognized extensions (e.g. `"Digital Signature"` for Key
/// Usage, `"DNS:example.com"` for Subject Alternative Name).  Returns `None` for
/// unrecognized extensions.  The returned string does not include the extension name or
/// criticality; callers handle those separately.
///
/// # Performance note
///
/// All id-ce OIDs (2.5.29.N) share a 3-arc prefix; a single length+prefix check selects
/// the id-ce family, then a `u32` match dispatches to the specific extension decoder.
/// This avoids repeated `&[u32]` slice comparisons across known extensions.
pub fn format_extension_value<'a>(ext: &Extension<'a>) -> Option<String> {
    let c = ext.extn_id.components();
    let bytes = ext.extn_value.as_bytes();

    // ── id-ce (2.5.29.N) — 4 arcs ────────────────────────────────────────────
    const CE0: u32 = oids::KEY_USAGE[0]; // 2
    const CE1: u32 = oids::KEY_USAGE[1]; // 5
    const CE2: u32 = oids::KEY_USAGE[2]; // 29
    const CE_SKI_V: u32 = oids::SUBJECT_KEY_IDENTIFIER[3]; // 14
    const CE_KU_V: u32 = oids::KEY_USAGE[3]; // 15
    const CE_SAN_V: u32 = oids::SUBJECT_ALT_NAME[3]; // 17
    const CE_IAN_V: u32 = oids::ISSUER_ALT_NAME[3]; // 18
    const CE_BC_V: u32 = oids::BASIC_CONSTRAINTS[3]; // 19
    const CE_CDP_V: u32 = oids::CRL_DISTRIBUTION_POINTS[3]; // 31
    const CE_CP_V: u32 = oids::CERTIFICATE_POLICIES[3]; // 32
    const CE_AKI_V: u32 = oids::AUTHORITY_KEY_IDENTIFIER[3]; // 35
    const CE_EKU_V: u32 = oids::EXTENDED_KEY_USAGE[3]; // 37

    if let &[CE0, CE1, CE2, sub] = c {
        return match sub {
            CE_SKI_V => format_ski_ext(bytes),
            CE_KU_V => format_key_usage_ext(bytes),
            CE_SAN_V | CE_IAN_V => format_general_names_ext(bytes),
            CE_BC_V => format_basic_constraints_ext(bytes),
            CE_CDP_V => format_crl_dp_ext(bytes),
            CE_CP_V => format_cert_policies_ext(bytes),
            CE_AKI_V => format_aki_ext(bytes),
            CE_EKU_V => format_eku_ext(bytes),
            _ => None,
        };
    }

    // Authority Information Access is in the id-pe arc (1.3.6.1.5.5.7.1.N),
    // not id-ce, so it falls outside the 4-arc dispatch above.
    if c == oids::AUTHORITY_INFO_ACCESS {
        return format_aia_ext(bytes);
    }

    None
}

fn format_key_usage_ext(bytes: &[u8]) -> Option<String> {
    let mut decoder = synta::Decoder::new(bytes, synta::Encoding::Der);
    let ku: KeyUsage = decoder.decode().ok()?;
    let ku_bytes = ku.as_bytes();

    let bit_set = |n: usize| -> bool {
        ku_bytes
            .get(n / 8)
            .is_some_and(|&b| (b >> (7 - (n % 8))) & 1 != 0)
    };

    let mut parts = Vec::new();
    if bit_set(KEY_USAGE_DIGITAL_SIGNATURE) {
        parts.push("Digital Signature");
    }
    if bit_set(KEY_USAGE_NON_REPUDIATION) {
        parts.push("Non Repudiation");
    }
    if bit_set(KEY_USAGE_KEY_ENCIPHERMENT) {
        parts.push("Key Encipherment");
    }
    if bit_set(KEY_USAGE_DATA_ENCIPHERMENT) {
        parts.push("Data Encipherment");
    }
    if bit_set(KEY_USAGE_KEY_AGREEMENT) {
        parts.push("Key Agreement");
    }
    if bit_set(KEY_USAGE_KEY_CERT_SIGN) {
        parts.push("Certificate Sign");
    }
    if bit_set(KEY_USAGE_C_RLSIGN) {
        parts.push("CRL Sign");
    }
    if bit_set(KEY_USAGE_ENCIPHER_ONLY) {
        parts.push("Encipher Only");
    }
    if bit_set(KEY_USAGE_DECIPHER_ONLY) {
        parts.push("Decipher Only");
    }

    Some(parts.join(", "))
}

fn format_eku_ext(bytes: &[u8]) -> Option<String> {
    let mut decoder = synta::Decoder::new(bytes, synta::Encoding::Der);
    let eku: Vec<ObjectIdentifier> = decoder.decode().ok()?;

    // ── id-kp (1.3.6.1.5.5.7.3.N) — 9 arcs ──────────────────────────────────
    const KP0: u32 = ID_KP_SERVER_AUTH[0]; // 1
    const KP1: u32 = ID_KP_SERVER_AUTH[1]; // 3
    const KP2: u32 = ID_KP_SERVER_AUTH[2]; // 6
    const KP3: u32 = ID_KP_SERVER_AUTH[3]; // 1
    const KP4: u32 = ID_KP_SERVER_AUTH[4]; // 5
    const KP5: u32 = ID_KP_SERVER_AUTH[5]; // 5
    const KP6: u32 = ID_KP_SERVER_AUTH[6]; // 7
    const KP7: u32 = ID_KP_SERVER_AUTH[7]; // 3
    const KP_SERVER_V: u32 = ID_KP_SERVER_AUTH[8]; // 1
    const KP_CLIENT_V: u32 = ID_KP_CLIENT_AUTH[8]; // 2
    const KP_CODESIGN_V: u32 = ID_KP_CODE_SIGNING[8]; // 3
    const KP_EMAIL_V: u32 = ID_KP_EMAIL_PROTECTION[8]; // 4
    const KP_TIME_V: u32 = ID_KP_TIME_STAMPING[8]; // 8
    const KP_OCSP_V: u32 = ID_KP_OCSPSIGNING[8]; // 9

    let names: Vec<&str> = eku
        .iter()
        .map(|oid| {
            if let &[KP0, KP1, KP2, KP3, KP4, KP5, KP6, KP7, sub] = oid.components() {
                match sub {
                    KP_SERVER_V => "TLS Web Server Authentication",
                    KP_CLIENT_V => "TLS Web Client Authentication",
                    KP_CODESIGN_V => "Code Signing",
                    KP_EMAIL_V => "E-mail Protection",
                    KP_TIME_V => "Time Stamping",
                    KP_OCSP_V => "OCSP Signing",
                    _ => "Unknown Purpose",
                }
            } else {
                "Unknown Purpose"
            }
        })
        .collect();

    Some(names.join(", "))
}

/// Context-specific tag numbers for the `GeneralName` CHOICE type (RFC 5280 §4.2.1.6).
///
/// These constants correspond to the `u32` tag number values returned by
/// [`parse_general_names`] and [`Certificate::subject_alt_names`].
///
/// | Constant | Tag | `GeneralName` alternative |
/// |----------|-----|--------------------------|
/// | [`general_name::OTHER_NAME`] | 0 | `otherName` |
/// | [`general_name::RFC822_NAME`] | 1 | `rfc822Name` (email) |
/// | [`general_name::DNS_NAME`] | 2 | `dNSName` |
/// | [`general_name::X400_ADDRESS`] | 3 | `x400Address` |
/// | [`general_name::DIRECTORY_NAME`] | 4 | `directoryName` |
/// | [`general_name::EDI_PARTY_NAME`] | 5 | `ediPartyName` |
/// | [`general_name::URI`] | 6 | `uniformResourceIdentifier` |
/// | [`general_name::IP_ADDRESS`] | 7 | `iPAddress` |
/// | [`general_name::REGISTERED_ID`] | 8 | `registeredID` |
pub mod general_name {
    /// `otherName [0]` — content is the full `OtherNameValue` TLV (constructed).
    pub const OTHER_NAME: u32 = 0;
    /// `rfc822Name [1]` — content is raw IA5String bytes (e-mail address).
    pub const RFC822_NAME: u32 = 1;
    /// `dNSName [2]` — content is raw IA5String bytes (DNS host name).
    pub const DNS_NAME: u32 = 2;
    /// `x400Address [3]`.
    pub const X400_ADDRESS: u32 = 3;
    /// `directoryName [4]` — content is the complete Name SEQUENCE TLV.
    pub const DIRECTORY_NAME: u32 = 4;
    /// `ediPartyName [5]`.
    pub const EDI_PARTY_NAME: u32 = 5;
    /// `uniformResourceIdentifier [6]` — content is raw IA5String bytes (URI).
    pub const URI: u32 = 6;
    /// `iPAddress [7]` — content is 4 raw bytes (IPv4) or 16 raw bytes (IPv6).
    pub const IP_ADDRESS: u32 = 7;
    /// `registeredID [8]` — content is raw OID value bytes (no tag/length).
    pub const REGISTERED_ID: u32 = 8;

    // ── GeneralNameSpec ───────────────────────────────────────────────────────

    /// A `GeneralName` specification used by builders (e.g. [`crate::CMPMessageBuilder`]).
    ///
    /// Holds the data needed to construct a [`crate::GeneralName`] at build
    /// time without going through an intermediate DER encode/decode round-trip.
    /// Use the associated constructors rather than matching on variants directly.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use synta_certificate::{CMPMessageBuilder, general_name::GeneralNameSpec};
    ///
    /// let der = CMPMessageBuilder::new()
    ///     .sender(GeneralNameSpec::rfc822("ca@example.com"))
    ///     .recipient(GeneralNameSpec::directory_name(&name_der))
    ///     .body_pkiconf()
    ///     .build()?;
    /// ```
    #[derive(Clone)]
    pub enum GeneralNameSpec {
        /// `rfc822Name [1]` — e-mail address (ASCII).
        Rfc822(String),
        /// `dNSName [2]` — DNS host name (ASCII).
        Dns(String),
        /// `uniformResourceIdentifier [6]` — URI (ASCII).
        Uri(String),
        /// `directoryName [4]` — pre-encoded `Name` DER SEQUENCE TLV.
        DirectoryName(Vec<u8>),
        /// `iPAddress [7]` — 4 raw bytes (IPv4) or 16 raw bytes (IPv6).
        IpAddress(Vec<u8>),
        /// `registeredID [8]` — an object identifier.
        RegisteredId(synta::ObjectIdentifier),
    }

    impl GeneralNameSpec {
        /// Create a `rfc822Name` spec from an e-mail address string.
        pub fn rfc822(email: &str) -> Self {
            Self::Rfc822(email.to_string())
        }

        /// Create a `dNSName` spec from a DNS host name string.
        pub fn dns(host: &str) -> Self {
            Self::Dns(host.to_string())
        }

        /// Create a `uniformResourceIdentifier` spec from a URI string.
        pub fn uri(uri: &str) -> Self {
            Self::Uri(uri.to_string())
        }

        /// Create a `directoryName` spec from a pre-encoded `Name` DER SEQUENCE TLV.
        ///
        /// Pass the output of [`crate::NameBuilder::build`] or
        /// `Certificate::subject_raw_der()` directly.
        pub fn directory_name(name_der: &[u8]) -> Self {
            Self::DirectoryName(name_der.to_vec())
        }

        /// Create an `iPAddress` spec from raw address bytes.
        ///
        /// Pass 4 bytes for IPv4 or 16 bytes for IPv6.
        pub fn ip_address(addr: &[u8]) -> Self {
            Self::IpAddress(addr.to_vec())
        }

        /// Create a `registeredID` spec from an object identifier.
        pub fn registered_id(oid: synta::ObjectIdentifier) -> Self {
            Self::RegisteredId(oid)
        }

        /// Construct a [`crate::GeneralName`] from `self`.
        ///
        /// For string-based variants the string data is cloned into the result.
        /// For `DirectoryName` the result borrows from the stored `Vec<u8>`.
        pub fn to_general_name(&self) -> synta::Result<crate::GeneralName<'_>> {
            match self {
                Self::Rfc822(s) => {
                    let ia5 = synta::IA5String::new(s.clone())?;
                    Ok(crate::GeneralName::Rfc822Name(ia5))
                }
                Self::Dns(s) => {
                    let ia5 = synta::IA5String::new(s.clone())?;
                    Ok(crate::GeneralName::DNSName(ia5))
                }
                Self::Uri(s) => {
                    let ia5 = synta::IA5String::new(s.clone())?;
                    Ok(crate::GeneralName::UniformResourceIdentifier(ia5))
                }
                Self::DirectoryName(bytes) => {
                    let name = synta::Decoder::new(bytes, synta::Encoding::Der)
                        .decode::<crate::Name<'_>>()?;
                    Ok(crate::GeneralName::DirectoryName(name))
                }
                Self::IpAddress(bytes) => Ok(crate::GeneralName::IPAddress(
                    synta::OctetString::new(bytes.clone()),
                )),
                Self::RegisteredId(oid) => Ok(crate::GeneralName::RegisteredID(oid.clone())),
            }
        }
    }
}

/// Re-export [`general_name::GeneralNameSpec`] at the crate root for convenience.
pub use general_name::GeneralNameSpec;

/// Parse a DER-encoded `SEQUENCE OF GeneralName` into raw `(tag_number, content)` pairs.
///
/// `raw` must be the **complete DER bytes** of the `SEQUENCE OF GeneralName` value —
/// exactly the bytes you get from an extension's `extn_value` octet-string content for
/// SAN (2.5.29.17) or IAN (2.5.29.18).
///
/// Returns one `(tag_number, content_bytes)` tuple per `GeneralName` alternative.
/// Tag numbers follow RFC 5280:
///
/// | Tag | GeneralName alternative |
/// |-----|------------------------|
/// | 0 | otherName (constructed; content is the full `OtherNameValue` TLV) |
/// | 1 | rfc822Name — raw IA5String bytes |
/// | 2 | dNSName — raw IA5String bytes |
/// | 3 | x400Address |
/// | 4 | directoryName — the Name SEQUENCE TLV |
/// | 5 | ediPartyName |
/// | 6 | uniformResourceIdentifier — raw IA5String bytes |
/// | 7 | iPAddress — 4 (IPv4) or 16 (IPv6) raw bytes |
/// | 8 | registeredID — raw OID value bytes |
///
/// Returns an empty `Vec` if `raw` is not a valid DER SEQUENCE.
///
/// This is the Rust counterpart to `synta.parse_general_names()` in the Python binding.
///
/// # Example
///
/// ```
/// use synta_certificate::{general_name, parse_general_names};
///
/// // SEQUENCE { [2] IMPLICIT IA5String "a.b" }  (dNSName)
/// let der: &[u8] = &[0x30, 0x05, 0x82, 0x03, b'a', b'.', b'b'];
/// let entries = parse_general_names(der);
/// assert_eq!(entries.len(), 1);
/// let (tag, content) = &entries[0];
/// assert_eq!(*tag, general_name::DNS_NAME);
/// assert_eq!(content, b"a.b");
/// ```
pub fn parse_general_names(raw: &[u8]) -> Vec<(u32, Vec<u8>)> {
    parse_general_names_inner(raw).unwrap_or_default()
}

/// Encode a list of ``(tag_number, content_bytes)`` pairs as a DER
/// ``SEQUENCE OF GeneralName``.
///
/// This is the Rust-level inverse of [`parse_general_names`]: call it with the
/// ``(u32, &[u8])`` pairs that `parse_general_names` returns (possibly after
/// modification) to get back the DER-encoded `SEQUENCE OF GeneralName` bytes.
///
/// Each entry is `(tag_number, value_bytes)` where `value_bytes` is the raw
/// **value** of the context-specific TLV (without tag/length bytes), exactly
/// as returned by `parse_general_names`.  Use the [`general_name`] constants
/// for tag numbers.
///
/// Returns `None` if any entry cannot be constructed (e.g. invalid UTF-8 for
/// an IA5String variant or an invalid OID value encoding).
pub fn encode_general_names(entries: &[(u32, &[u8])]) -> Option<Vec<u8>> {
    use synta::traits::Decode;

    // Append a DER length to `out`.
    fn push_der_len(out: &mut Vec<u8>, len: usize) {
        if len < 0x80 {
            out.push(len as u8);
        } else if len <= 0xFF {
            out.extend_from_slice(&[0x81, len as u8]);
        } else {
            out.extend_from_slice(&[0x82, (len >> 8) as u8, len as u8]);
        }
    }

    // Emit a context-specific CONSTRUCTED TLV: (0x80 | 0x20 | tag) + len + value.
    //
    // Used for IMPLICIT SEQUENCE alternatives (otherName [0], x400Address [3],
    // ediPartyName [5]) where parse_general_names has already stripped the 0x30
    // SEQUENCE tag, returning only the SEQUENCE body in `value`.  Re-wrapping
    // with the original context-specific constructed tag reconstructs the exact
    // wire bytes without needing to decode the inner structure.
    fn context_constructed_tlv(tag: u8, value: &[u8]) -> Vec<u8> {
        let mut tlv = Vec::with_capacity(3 + value.len());
        tlv.push(0xA0 | tag); // context-specific (0x80) | constructed (0x20) | tag
        push_der_len(&mut tlv, value.len());
        tlv.extend_from_slice(value);
        tlv
    }

    // Encode one GeneralName entry as raw DER bytes.
    fn encode_one(tag_num: u32, content: &[u8]) -> Option<Vec<u8>> {
        use general_name as gn;
        match tag_num {
            gn::OTHER_NAME | gn::X400_ADDRESS | gn::EDI_PARTY_NAME => {
                // [0]/[3]/[5] IMPLICIT SEQUENCE: parse_general_names returns the
                // SEQUENCE body without the 0x30 wrapper (IMPLICIT tagging replaced
                // the SEQUENCE tag with the context-specific constructed tag).
                // Re-wrap directly — no decode/re-encode of the inner structure needed.
                Some(context_constructed_tlv(tag_num as u8, content))
            }
            gn::RFC822_NAME => {
                // IMPLICIT [1]: content = raw IA5String bytes
                let s = std::str::from_utf8(content).ok()?;
                GeneralName::Rfc822Name(synta::IA5String::new(s.to_string()).ok()?)
                    .to_der()
                    .ok()
            }
            gn::DNS_NAME => {
                // IMPLICIT [2]: content = raw IA5String bytes
                let s = std::str::from_utf8(content).ok()?;
                GeneralName::DNSName(synta::IA5String::new(s.to_string()).ok()?)
                    .to_der()
                    .ok()
            }
            gn::DIRECTORY_NAME => {
                // EXPLICIT [4]: content = full Name SEQUENCE TLV
                let mut dec = synta::Decoder::new(content, synta::Encoding::Der);
                GeneralName::DirectoryName(Name::decode(&mut dec).ok()?)
                    .to_der()
                    .ok()
            }
            gn::URI => {
                // IMPLICIT [6]: content = raw IA5String bytes
                let s = std::str::from_utf8(content).ok()?;
                GeneralName::UniformResourceIdentifier(synta::IA5String::new(s.to_string()).ok()?)
                    .to_der()
                    .ok()
            }
            gn::IP_ADDRESS => {
                // IMPLICIT [7]: content = 4 (IPv4) or 16 (IPv6) raw bytes
                GeneralName::IPAddress(synta::OctetString::new(content.to_vec()))
                    .to_der()
                    .ok()
            }
            gn::REGISTERED_ID => {
                // IMPLICIT [8]: content = raw OID value bytes (no tag/length)
                let oid = synta::ObjectIdentifier::from_content_bytes(content).ok()?;
                GeneralName::RegisteredID(oid).to_der().ok()
            }
            _ => None,
        }
    }

    // Accumulate encoded GeneralName TLVs, then wrap in an outer SEQUENCE.
    let mut body: Vec<u8> = Vec::new();
    for &(tag_num, content) in entries {
        body.extend_from_slice(&encode_one(tag_num, content)?);
    }
    let mut out = Vec::with_capacity(4 + body.len());
    out.push(0x30); // SEQUENCE tag
    push_der_len(&mut out, body.len());
    out.extend_from_slice(&body);
    Some(out)
}

/// Convenience methods for [`crl::CertificateList`].
///
/// Adds high-level accessors for commonly-needed CRL fields that are buried
/// inside the extension list.
impl<'a> crl::CertificateList<'a> {
    /// Return the CRL sequence number from the ``cRLNumber`` extension
    /// (OID `2.5.29.20`), if present.
    ///
    /// The integer is decoded from the DER-encoded ``extnValue`` and returned
    /// as an owned [`synta::Integer`] (arbitrary precision, heap-allocated only
    /// for values larger than 16 bytes).
    ///
    /// Returns `None` when the CRL carries no ``cRLExtensions``, no
    /// ``cRLNumber`` extension, or the extension value fails to decode as an
    /// INTEGER.
    pub fn crl_number(&self) -> Option<synta::Integer> {
        let exts = self.tbs_cert_list.crl_extensions.as_ref()?;
        for ext in exts {
            if ext.extn_id.components() == oids::CRL_NUMBER {
                use synta::Decode;
                let mut dec = synta::Decoder::new(ext.extn_value.as_bytes(), synta::Encoding::Der);
                return synta::Integer::decode(&mut dec).ok();
            }
        }
        None
    }
}

/// Convenience method for accessing Subject Alternative Names.
///
/// This `impl` block adds [`subject_alt_names`][Certificate::subject_alt_names]
/// directly on the generated [`Certificate`] type.
impl<'a> Certificate<'a> {
    /// Return the Subject Alternative Names carried by this certificate.
    ///
    /// Locates the SAN extension (OID `2.5.29.17`) in the certificate's
    /// extension list and returns its `GeneralName` entries as
    /// `(tag_number, content_bytes)` pairs, exactly as
    /// [`parse_general_names`] does.  Tag numbers follow RFC 5280 §4.2.1.6:
    ///
    /// | Tag | `GeneralName` alternative |
    /// |-----|--------------------------|
    /// | 1 | `rfc822Name` — raw IA5String bytes (email) |
    /// | 2 | `dNSName` — raw IA5String bytes |
    /// | 4 | `directoryName` — complete Name SEQUENCE TLV |
    /// | 6 | `uniformResourceIdentifier` — raw IA5String bytes |
    /// | 7 | `iPAddress` — 4 bytes (IPv4) or 16 bytes (IPv6) |
    /// | 8 | `registeredID` — raw OID value bytes |
    ///
    /// Returns an empty `Vec` when the certificate has no SAN extension or
    /// the extension value cannot be parsed.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use synta_certificate::Certificate;
    /// use synta::{Decoder, Encoding};
    ///
    /// let mut dec = Decoder::new(der, Encoding::Der);
    /// let cert: Certificate = dec.decode().unwrap();
    ///
    /// for (tag, content) in cert.subject_alt_names() {
    ///     match tag {
    ///         2 => println!("DNS: {}", std::str::from_utf8(&content).unwrap_or("?")),
    ///         7 if content.len() == 4 => println!("IPv4: {}.{}.{}.{}", content[0], content[1], content[2], content[3]),
    ///         7 => println!("IPv6: {} bytes", content.len()),
    ///         1 => println!("email: {}", std::str::from_utf8(&content).unwrap_or("?")),
    ///         _ => {}
    ///     }
    /// }
    /// ```
    pub fn subject_alt_names(&self) -> Vec<(u32, Vec<u8>)> {
        let raw = match self.tbs_certificate.extensions.as_ref() {
            Some(r) => r,
            None => return Vec::new(),
        };
        find_extension_value(raw.as_bytes(), oids::SUBJECT_ALT_NAME)
            .map(parse_general_names)
            .unwrap_or_default()
    }
}

/// Single-pass scan of a DER-encoded `SEQUENCE OF Extension`, returning the
/// `extnValue` content bytes of the first extension whose `extnId` matches
/// `oid`.  Stops as soon as the matching extension is found without decoding
/// the remainder of the sequence.
///
/// `raw` must be the complete TLV of the `Extensions` SEQUENCE (i.e. the
/// bytes captured by the `RawDer<'a>` extensions field, which already has
/// the `[3] EXPLICIT` wrapper stripped by the derive macro).
///
/// Returns `None` on parse error or if no matching extension is found.
pub fn find_extension_value<'a>(raw: &'a [u8], oid: &[u32]) -> Option<&'a [u8]> {
    use synta::tag::TAG_SEQUENCE;
    use synta::Tag;

    let mut dec = synta::Decoder::new(raw, synta::Encoding::Der);
    let seq_tag = Tag::universal_constructed(TAG_SEQUENCE);
    let mut outer = dec.enter_constructed(seq_tag).ok()?;

    while !outer.is_empty() {
        let ext: Extension<'_> = outer.decode().ok()?;
        if ext.extn_id.components() == oid {
            return Some(ext.extn_value.as_bytes());
        }
    }
    None
}

fn parse_general_names_inner(raw: &[u8]) -> Option<Vec<(u32, Vec<u8>)>> {
    use synta::tag::TAG_SEQUENCE;
    use synta::{Tag, TagClass};

    let mut decoder = synta::Decoder::new(raw, synta::Encoding::Der);
    let seq_tag = Tag::universal_constructed(TAG_SEQUENCE);
    let mut inner = decoder.enter_constructed(seq_tag).ok()?;

    let mut result = Vec::new();
    while !inner.is_empty() {
        let tag = inner.read_tag().ok()?;
        let len = inner.read_length().ok()?.definite().ok()?;
        let content = inner.read_bytes(len).ok()?.to_vec();
        // GeneralName alternatives always use context-specific IMPLICIT tags [0]–[8].
        // Silently skip any non-context-specific element (malformed input defence),
        // consistent with the class check in format_general_names_ext.
        if tag.class() != TagClass::ContextSpecific {
            continue;
        }
        result.push((tag.number(), content));
    }
    Some(result)
}

fn format_general_names_ext(bytes: &[u8]) -> Option<String> {
    // GeneralName alternatives use IMPLICIT context-specific tags per RFC 5280
    // (the module uses IMPLICIT TAGS default).  We parse raw TLVs directly:
    //   [1] IMPLICIT IA5String  → email address
    //   [2] IMPLICIT IA5String  → DNS name
    //   [6] IMPLICIT IA5String  → URI
    //   [7] IMPLICIT OCTET STRING → IP address (4 or 16 bytes)
    // All others (OtherName, directoryName, …) are silently skipped.
    use synta::tag::TAG_SEQUENCE;
    use synta::TagClass;

    let mut decoder = synta::Decoder::new(bytes, synta::Encoding::Der);
    let seq_tag = synta::Tag::universal_constructed(TAG_SEQUENCE);
    let mut inner = decoder.enter_constructed(seq_tag).ok()?;

    let mut parts = Vec::new();
    while !inner.is_empty() {
        let tag = inner.read_tag().ok()?;
        let len = inner.read_length().ok()?.definite().ok()?;
        let content = inner.read_bytes(len).ok()?;

        if tag.class() != TagClass::ContextSpecific {
            continue;
        }
        let s = match tag.number() {
            1 => format!("email:{}", core::str::from_utf8(content).unwrap_or("?")),
            2 => format!("DNS:{}", core::str::from_utf8(content).unwrap_or("?")),
            6 => format!("URI:{}", core::str::from_utf8(content).unwrap_or("?")),
            7 => format_ip_address(content),
            _ => continue,
        };
        parts.push(s);
    }

    if parts.is_empty() {
        None
    } else {
        Some(parts.join(", "))
    }
}

fn format_ip_address(bytes: &[u8]) -> String {
    match bytes.len() {
        4 => format!(
            "IP Address:{}.{}.{}.{}",
            bytes[0], bytes[1], bytes[2], bytes[3]
        ),
        16 => {
            let parts: Vec<String> = bytes
                .chunks(2)
                .map(|c| format!("{:02X}{:02X}", c[0], c[1]))
                .collect();
            format!("IP Address:{}", parts.join(":"))
        }
        _ => format!(
            "IP Address:{}",
            bytes
                .iter()
                .map(|b| format!("{:02x}", b))
                .collect::<Vec<_>>()
                .join(":")
        ),
    }
}

fn format_basic_constraints_ext(bytes: &[u8]) -> Option<String> {
    let mut decoder = synta::Decoder::new(bytes, synta::Encoding::Der);
    let bc: BasicConstraints = decoder.decode().ok()?;

    let mut parts = Vec::new();
    let is_ca = bc.c_a.map(|b| b.0).unwrap_or(false);
    parts.push(if is_ca { "CA:TRUE" } else { "CA:FALSE" }.to_string());
    if let Some(path_len) = &bc.path_len_constraint {
        parts.push(format!("pathlen:{}", path_len.as_i64().unwrap_or(0)));
    }
    Some(parts.join(", "))
}

fn format_ski_ext<'a>(bytes: &'a [u8]) -> Option<String> {
    use synta::OctetStringRef;
    let mut decoder = synta::Decoder::new(bytes, synta::Encoding::Der);
    let ski: OctetStringRef<'a> = decoder.decode().ok()?;
    let hex: String = ski
        .as_bytes()
        .iter()
        .map(|b| format!("{:02X}", b))
        .collect::<Vec<_>>()
        .join(":");
    Some(hex)
}

fn format_crl_dp_ext(bytes: &[u8]) -> Option<String> {
    // CRLDistributionPoints ::= SEQUENCE OF DistributionPoint
    // DistributionPoint ::= SEQUENCE {
    //   distributionPoint [0] DistributionPointName OPTIONAL,  -- CHOICE
    //     fullName         [0] GeneralNames,                    -- IMPLICIT
    //     nameRelative...  [1] RelativeDistinguishedName        -- IMPLICIT
    //   reasons [1] OPTIONAL, cRLIssuer [2] OPTIONAL }
    //
    // In practice nearly all certificates use fullName with a single URI.
    use synta::tag::TAG_SEQUENCE;
    use synta::{Tag, TagClass};

    let mut decoder = synta::Decoder::new(bytes, synta::Encoding::Der);
    let seq_tag = Tag::universal_constructed(TAG_SEQUENCE);
    let mut outer = decoder.enter_constructed(seq_tag).ok()?;

    let mut parts = Vec::new();
    while !outer.is_empty() {
        // Each element is a DistributionPoint SEQUENCE.
        let mut dp = outer.enter_constructed(seq_tag).ok()?;
        while !dp.is_empty() {
            let dp_tag = dp.read_tag().ok()?;
            let dp_len = dp.read_length().ok()?.definite().ok()?;
            let dp_content = dp.read_bytes(dp_len).ok()?;

            // distributionPoint is [0] — a DistributionPointName CHOICE.
            if dp_tag.class() == TagClass::ContextSpecific && dp_tag.number() == 0 {
                // fullName [0] IMPLICIT GeneralNames — walk the GeneralNames entries.
                let mut gn_dec = synta::Decoder::new(dp_content, synta::Encoding::Der);
                while !gn_dec.is_empty() {
                    let gn_tag = gn_dec.read_tag().ok()?;
                    let gn_len = gn_dec.read_length().ok()?.definite().ok()?;
                    let gn_content = gn_dec.read_bytes(gn_len).ok()?;
                    if gn_tag.class() == TagClass::ContextSpecific && gn_tag.number() == 6 {
                        // uniformResourceIdentifier [6] IMPLICIT IA5String
                        let uri = core::str::from_utf8(gn_content).unwrap_or("?");
                        parts.push(format!("URI:{}", uri));
                    }
                }
            }
            // reasons [1] and cRLIssuer [2] are skipped — rarely needed for display.
        }
    }

    if parts.is_empty() {
        None
    } else {
        Some(parts.join(", "))
    }
}

fn format_cert_policies_ext(bytes: &[u8]) -> Option<String> {
    // CertificatePolicies ::= SEQUENCE OF PolicyInformation
    // Decode using the code-generated PolicyInformation<'a> type.
    let mut decoder = synta::Decoder::new(bytes, synta::Encoding::Der);
    let infos: Vec<PolicyInformation<'_>> = decoder.decode().ok()?;
    if infos.is_empty() {
        return None;
    }
    Some(
        infos
            .iter()
            .map(|pi| format!("Policy: {}", pi.policy_identifier))
            .collect::<Vec<_>>()
            .join(", "),
    )
}

fn format_aia_ext(bytes: &[u8]) -> Option<String> {
    // AuthorityInfoAccessSyntax ::= SEQUENCE OF AccessDescription
    // AccessDescription ::= SEQUENCE { accessMethod OID, accessLocation GeneralName }
    use synta::tag::TAG_SEQUENCE;
    use synta::{Tag, TagClass};

    let mut decoder = synta::Decoder::new(bytes, synta::Encoding::Der);
    let seq_tag = Tag::universal_constructed(TAG_SEQUENCE);
    let mut outer = decoder.enter_constructed(seq_tag).ok()?;

    // Prefix and sub-arc constants derived from the autogenerated OID arrays so
    // they stay in sync with the ASN.1 schema if the OID values ever change.
    const AD0: u32 = ID_AD[0];
    const AD1: u32 = ID_AD[1];
    const AD2: u32 = ID_AD[2];
    const AD3: u32 = ID_AD[3];
    const AD4: u32 = ID_AD[4];
    const AD5: u32 = ID_AD[5];
    const AD6: u32 = ID_AD[6];
    const AD7: u32 = ID_AD[7];
    const OCSP_V: u32 = oids::AD_OCSP[oids::AD_OCSP.len() - 1];
    const CA_ISSUERS_V: u32 = oids::AD_CA_ISSUERS[oids::AD_CA_ISSUERS.len() - 1];

    let mut parts = Vec::new();
    while !outer.is_empty() {
        let mut ad = outer.enter_constructed(seq_tag).ok()?;
        let oid = synta::ObjectIdentifier::decode(&mut ad).ok()?;
        let gn_tag = ad.read_tag().ok()?;
        let gn_len = ad.read_length().ok()?.definite().ok()?;
        let gn_content = ad.read_bytes(gn_len).ok()?;

        // accessLocation: [6] IMPLICIT IA5String for URI (most common).
        let location_str = if gn_tag.class() == TagClass::ContextSpecific && gn_tag.number() == 6 {
            match core::str::from_utf8(gn_content) {
                Ok(uri) => format!("URI:{}", uri),
                Err(_) => format!("URI:<invalid UTF-8: {} bytes>", gn_content.len()),
            }
        } else {
            format!("[tag {}]", gn_tag.number())
        };

        let label = if let &[AD0, AD1, AD2, AD3, AD4, AD5, AD6, AD7, sub] = oid.components() {
            match sub {
                OCSP_V => "OCSP",
                CA_ISSUERS_V => "CA Issuers",
                _ => "Unknown",
            }
        } else {
            "Unknown"
        };
        parts.push(format!("{} - {}", label, location_str));
    }

    if parts.is_empty() {
        None
    } else {
        Some(parts.join("\n"))
    }
}

fn format_aki_ext(bytes: &[u8]) -> Option<String> {
    // AuthorityKeyIdentifier ::= SEQUENCE {
    //   keyIdentifier             [0] IMPLICIT OCTET STRING OPTIONAL,
    //   authorityCertIssuer       [1] IMPLICIT GeneralNames OPTIONAL,
    //   authorityCertSerialNumber [2] IMPLICIT INTEGER OPTIONAL }
    // Tag bytes: 0x80 = primitive ctx 0, 0xA1 = constructed ctx 1, 0x82 = primitive ctx 2
    use synta::tag::TAG_SEQUENCE;
    use synta::TagClass;

    let mut decoder = synta::Decoder::new(bytes, synta::Encoding::Der);
    let seq_tag = synta::Tag::universal_constructed(TAG_SEQUENCE);
    let mut inner = decoder.enter_constructed(seq_tag).ok()?;

    let mut parts = Vec::new();
    while !inner.is_empty() {
        let tag = inner.read_tag().ok()?;
        let len = inner.read_length().ok()?.definite().ok()?;
        let content = inner.read_bytes(len).ok()?;

        if tag.class() != TagClass::ContextSpecific {
            continue;
        }
        match tag.number() {
            0 => {
                // keyIdentifier [0] IMPLICIT OCTET STRING
                let hex = content
                    .iter()
                    .map(|b| format!("{:02X}", b))
                    .collect::<Vec<_>>()
                    .join(":");
                parts.push(format!("keyid:{}", hex));
            }
            2 => {
                // authorityCertSerialNumber [2] IMPLICIT INTEGER
                let hex = content
                    .iter()
                    .map(|b| format!("{:02X}", b))
                    .collect::<Vec<_>>()
                    .join(":");
                parts.push(format!("serial:{}", hex));
            }
            1 => {
                // authorityCertIssuer [1] IMPLICIT GeneralNames
                // Content is SEQUENCE OF GeneralName; directoryName uses [4] EXPLICIT Name.
                let mut gn_dec = synta::Decoder::new(content, synta::Encoding::Der);
                while !gn_dec.is_empty() {
                    let gn_tag = gn_dec.read_tag().ok()?;
                    let gn_len = gn_dec.read_length().ok()?.definite().ok()?;
                    let gn_content = gn_dec.read_bytes(gn_len).ok()?;
                    // directoryName [4] — EXPLICIT: gn_content starts with the Name TLV (0x30)
                    if gn_tag.class() == synta::TagClass::ContextSpecific && gn_tag.number() == 4 {
                        parts.push(format!("DirName:{}", format_dn_slash(gn_content)));
                    }
                }
            }
            _ => {} // skip unknown fields
        }
    }

    if parts.is_empty() {
        None
    } else {
        Some(parts.join("\n                "))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── parse_general_names ───────────────────────────────────────────────────

    /// A Universal-class tag (here UTF8String, tag 0x0C) inside a GeneralNames
    /// SEQUENCE must be silently skipped; only context-specific tags make it
    /// into the result.
    #[test]
    fn parse_general_names_skips_universal_class_tags() {
        // GeneralNames SEQUENCE (0x30) containing:
        //   [2] PRIMITIVE "a.com"         — dNSName          (keep)
        //   UTF8String "skip"             — Universal 0x0C   (skip)
        //   [6] PRIMITIVE "http://b.com"  — URI              (keep)
        //
        // Byte layout:
        //   30 1b          SEQUENCE (27 bytes)
        //   82 05 ...      [2] dNSName "a.com"    (7 bytes)
        //   0c 04 ...      UTF8String "skip"       (6 bytes)
        //   86 0c ...      [6] URI "http://b.com"  (14 bytes)
        let gn_der: &[u8] = &[
            0x30, 0x1b, 0x82, 0x05, b'a', b'.', b'c', b'o', b'm', 0x0c, 0x04, b's', b'k', b'i',
            b'p', 0x86, 0x0c, b'h', b't', b't', b'p', b':', b'/', b'/', b'b', b'.', b'c', b'o',
            b'm',
        ];
        let result = parse_general_names(gn_der);
        assert_eq!(
            result.len(),
            2,
            "Universal tag must be skipped; got {result:?}"
        );
        assert_eq!(result[0], (2, b"a.com".to_vec()));
        assert_eq!(result[1], (6, b"http://b.com".to_vec()));
    }

    // ── encode_general_names ──────────────────────────────────────────────────

    /// `encode_general_names` must round-trip an otherName entry.
    ///
    /// Wire layout of the input SEQUENCE OF GeneralName:
    ///
    ///   30 10              SEQUENCE (16 bytes)
    ///   A0 0E              [0] CONSTRUCTED — otherName
    ///     06 02 2A 03      OID 1.2.3 (type-id)
    ///     A0 08            [0] EXPLICIT (value)
    ///       0C 06 ...      UTF8String "foobar"
    ///
    /// parse_general_names returns tag=0, content=the 14 bytes inside A0 0E.
    /// encode_general_names must reconstruct the identical 18-byte sequence.
    #[test]
    fn encode_general_names_roundtrip_othername() {
        // Build the input: SEQUENCE { [0] CONSTRUCTED { OID 1.2.3, [0] UTF8String "foobar" } }
        //   OID 1.2.3 value bytes: 2A 03  (1*40+2=42=0x2A, then 3)
        //   UTF8String "foobar": 0C 06 66 6F 6F 62 61 72
        //   [0] EXPLICIT value: A0 08 0C 06 66 6F 6F 62 61 72
        //   OtherName body (inside A0 0E): 06 02 2A 03 A0 08 0C 06 66 6F 6F 62 61 72  (14 bytes)
        //   GeneralName [0]: A0 0E <14 bytes>  (16 bytes)
        //   SEQUENCE OF: 30 10 <16 bytes>  (18 bytes)
        #[rustfmt::skip]
        let gn_seq: &[u8] = &[
            0x30, 0x10,                              // SEQUENCE (16)
            0xA0, 0x0E,                              // [0] CONSTRUCTED (14)
              0x06, 0x02, 0x2A, 0x03,                //   OID 1.2.3
              0xA0, 0x08,                            //   [0] EXPLICIT
                0x0C, 0x06,                          //     UTF8String (6)
                  b'f', b'o', b'o', b'b', b'a', b'r',
        ];

        let parsed = parse_general_names(gn_seq);
        assert_eq!(parsed.len(), 1);
        assert_eq!(parsed[0].0, general_name::OTHER_NAME);

        let entries: Vec<(u32, &[u8])> = parsed.iter().map(|(t, c)| (*t, c.as_slice())).collect();
        let re_encoded = encode_general_names(&entries).expect("encode_general_names failed");
        assert_eq!(
            re_encoded, gn_seq,
            "OtherName roundtrip mismatch:\n  got:      {re_encoded:02X?}\n  expected: {gn_seq:02X?}"
        );
    }

    /// `encode_general_names` must round-trip an ediPartyName entry.
    ///
    ///   30 0C              SEQUENCE (12 bytes)
    ///   A5 0A              [5] CONSTRUCTED — ediPartyName
    ///     81 08 ...        [1] IMPLICIT UTF8String "testname" (partyName)
    #[test]
    fn encode_general_names_roundtrip_edipartyname() {
        #[rustfmt::skip]
        let gn_seq: &[u8] = &[
            0x30, 0x0C,                              // SEQUENCE (12)
            0xA5, 0x0A,                              // [5] CONSTRUCTED (10)
              0x81, 0x08,                            //   [1] IMPLICIT (partyName, 8 bytes)
                b't', b'e', b's', b't', b'n', b'a', b'm', b'e',
        ];

        let parsed = parse_general_names(gn_seq);
        assert_eq!(parsed.len(), 1);
        assert_eq!(parsed[0].0, general_name::EDI_PARTY_NAME);

        let entries: Vec<(u32, &[u8])> = parsed.iter().map(|(t, c)| (*t, c.as_slice())).collect();
        let re_encoded = encode_general_names(&entries).expect("encode_general_names failed");
        assert_eq!(
            re_encoded, gn_seq,
            "EDIPartyName roundtrip mismatch:\n  got:      {re_encoded:02X?}\n  expected: {gn_seq:02X?}"
        );
    }

    /// `encode_general_names` must round-trip dNSName and iPAddress entries.
    #[test]
    fn encode_general_names_roundtrips_simple_types() {
        // GeneralNames: dNSName "x.y" (5 bytes TLV) + iPAddress 1.2.3.4 (6 bytes TLV)
        // Inner total = 11 = 0x0B.
        let gn_der: &[u8] = &[
            0x30, 0x0b, // SEQUENCE 11 bytes
            0x82, 0x03, b'x', b'.', b'y', // [2] dNSName "x.y"
            0x87, 0x04, 1, 2, 3, 4, // [7] iPAddress 1.2.3.4
        ];
        let tuples = parse_general_names(gn_der);
        assert_eq!(tuples.len(), 2);
        let encoded = encode_general_names(
            &tuples
                .iter()
                .map(|(t, v)| (*t, v.as_slice()))
                .collect::<Vec<_>>(),
        );
        assert_eq!(encoded.as_deref(), Some(gn_der));
    }

    // ── format_extension_value — new formatters ───────────────────────────────

    /// Build a raw `SEQUENCE OF Extension` byte vector containing a single
    /// Extension with the given OID content bytes and extnValue DER.
    ///
    /// Used to drive `decode_extensions` + `format_extension_value` without
    /// needing real certificate files.
    #[cfg(feature = "derive")]
    fn make_extensions_der(oid_content: &[u8], ext_value_der: &[u8]) -> Vec<u8> {
        assert!(oid_content.len() <= 127);
        assert!(ext_value_der.len() <= 127);

        let oid_tlv: Vec<u8> = {
            let mut v = vec![0x06u8, oid_content.len() as u8];
            v.extend_from_slice(oid_content);
            v
        };
        let octet_tlv: Vec<u8> = {
            let mut v = vec![0x04u8, ext_value_der.len() as u8];
            v.extend_from_slice(ext_value_der);
            v
        };
        let ext_body: Vec<u8> = [oid_tlv.as_slice(), octet_tlv.as_slice()].concat();
        assert!(ext_body.len() <= 127);
        let ext_tlv: Vec<u8> = {
            let mut v = vec![0x30u8, ext_body.len() as u8];
            v.extend_from_slice(&ext_body);
            v
        };
        assert!(ext_tlv.len() <= 127);
        let mut out = vec![0x30u8, ext_tlv.len() as u8];
        out.extend_from_slice(&ext_tlv);
        out
    }

    /// CRL Distribution Points (2.5.29.31) — single DistributionPoint with a
    /// fullName URI.
    ///
    /// DER for the extension value:
    ///   30 19  SEQUENCE OF DistributionPoint
    ///     30 17  DistributionPoint SEQUENCE
    ///       A0 15  [0] CONSTRUCTED (distributionPoint / fullName)
    ///         86 13  [6] PRIMITIVE URI "http://crl.test/crl" (19 bytes)
    #[cfg(feature = "derive")]
    #[test]
    fn format_extension_value_crl_distribution_points() {
        let uri = b"http://crl.test/crl"; // 19 bytes
        let ext_val: Vec<u8> = {
            let mut v = vec![
                0x30,
                0x19, // SEQUENCE OF DistributionPoint
                0x30,
                0x17, // DistributionPoint
                0xA0,
                0x15, // [0] CONSTRUCTED
                0x86,
                uri.len() as u8,
            ];
            v.extend_from_slice(uri);
            v
        };
        // OID 2.5.29.31 content bytes
        let raw = make_extensions_der(&[0x55, 0x1D, 0x1F], &ext_val);
        let exts = decode_extensions(&raw);
        assert_eq!(exts.len(), 1);
        let result = format_extension_value(&exts[0]);
        assert_eq!(result.as_deref(), Some("URI:http://crl.test/crl"));
    }

    /// Certificate Policies (2.5.29.32) — single PolicyInformation with OID
    /// 2.5.29.32.0 (anyPolicy).
    ///
    /// DER for the extension value:
    ///   30 08  SEQUENCE OF PolicyInformation
    ///     30 06  PolicyInformation
    ///       06 04 55 1D 20 00  OID 2.5.29.32.0
    #[cfg(feature = "derive")]
    #[test]
    fn format_extension_value_certificate_policies() {
        // OID 2.5.29.32.0 (anyPolicy): 55 1D 20 00
        let ext_val: &[u8] = &[
            0x30, 0x08, // SEQUENCE OF PolicyInformation
            0x30, 0x06, // PolicyInformation
            0x06, 0x04, 0x55, 0x1D, 0x20, 0x00, // OID 2.5.29.32.0
        ];
        // OID 2.5.29.32 content bytes
        let raw = make_extensions_der(&[0x55, 0x1D, 0x20], ext_val);
        let exts = decode_extensions(&raw);
        assert_eq!(exts.len(), 1);
        let result = format_extension_value(&exts[0]);
        assert_eq!(result.as_deref(), Some("Policy: 2.5.29.32.0"));
    }

    /// Authority Information Access (1.3.6.1.5.5.7.1.1) — single OCSP
    /// AccessDescription with URI "http://ocsp.test".
    ///
    /// DER for the extension value:
    ///   30 1E  SEQUENCE OF AccessDescription
    ///     30 1C  AccessDescription
    ///       06 08 2B...  OID 1.3.6.1.5.5.7.48.1 (id-ad-ocsp)
    ///       86 10        [6] PRIMITIVE URI "http://ocsp.test" (16 bytes)
    #[cfg(feature = "derive")]
    #[test]
    fn format_extension_value_authority_info_access() {
        let uri = b"http://ocsp.test"; // 16 bytes
        let ext_val: Vec<u8> = {
            let mut v = vec![
                0x30,
                0x1E, // SEQUENCE OF AccessDescription
                0x30,
                0x1C, // AccessDescription
                // OID 1.3.6.1.5.5.7.48.1 (id-ad-ocsp)
                0x06,
                0x08,
                0x2B,
                0x06,
                0x01,
                0x05,
                0x05,
                0x07,
                0x30,
                0x01,
                0x86,
                uri.len() as u8,
            ];
            v.extend_from_slice(uri);
            v
        };
        // OID 1.3.6.1.5.5.7.1.1 (id-pe-authorityInfoAccess) content bytes
        let raw = make_extensions_der(&[0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x01, 0x01], &ext_val);
        let exts = decode_extensions(&raw);
        assert_eq!(exts.len(), 1);
        let result = format_extension_value(&exts[0]);
        assert_eq!(result.as_deref(), Some("OCSP - URI:http://ocsp.test"));
    }
}