pkix-path 0.6.0

RFC 5280 X.509 certificate path validation — pure Rust, no_std
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
//! `RustCrypto` [`SignatureVerifier`] backends.
//!
//! Every verifier here takes the algorithm from two places, as RFC 5280
//! §4.1.1.2 and RFC 5480 §2.1.1 require:
//!
//! - the **key type and curve** come from the issuer's
//!   `SubjectPublicKeyInfo` -- for ECDSA from its `parameters` field, in
//!   either form RFC 5480 §2.1.1 defines: a `namedCurve` OID, or an
//!   X9.62 `SpecifiedECDomain` resolved by
//!   [`crate::specified_curve`] -- and
//! - the **signature scheme and digest** come from the subject's
//!   `signatureAlgorithm`.
//!
//! So a P-384 issuer key that signs with `ecdsa-with-SHA256` (OpenSSL's
//! default digest for EC keys) verifies, and an ECDSA signature whose
//! algorithm OID names one digest cannot be checked against a curve chosen
//! from that OID.

// With only some backend features enabled, the OIDs and helpers of the
// others are unused; gating each item separately would obscure the code.
#![cfg_attr(
    not(all(
        feature = "p256",
        feature = "p384",
        feature = "p521",
        feature = "rsa",
        feature = "ed25519"
    )),
    allow(dead_code, unused_imports, unused_variables)
)]

use crate::SignatureVerifier;
// The same list as `sha2_digest` below, for the same reason: every
// brainpool feature reaches a `Vec`-returning digest helper too, and a
// `use` whose cfg is narrower than its users' is invisible until some
// combination turns the users on without it.
#[cfg(any(
    feature = "p256",
    feature = "p384",
    feature = "p521",
    feature = "rsa",
    feature = "bp224",
    feature = "bp256",
    feature = "bp384",
    feature = "bp512"
))]
use crate::Vec;
use crate::{VerificationError, VerificationErrorKind};
use der::asn1::ObjectIdentifier;
use spki::{AlgorithmIdentifierRef, SubjectPublicKeyInfoRef};

type VerifyResult = core::result::Result<(), VerificationError>;

// ---------------------------------------------------------------------------
// OIDs
// ---------------------------------------------------------------------------

/// `ecdsa-with-SHA256` (RFC 5758 §3.2): 1.2.840.10045.4.3.2.
pub(crate) const OID_ECDSA_WITH_SHA256: ObjectIdentifier =
    ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2");
/// `ecdsa-with-SHA384` (RFC 5758 §3.2): 1.2.840.10045.4.3.3.
pub(crate) const OID_ECDSA_WITH_SHA384: ObjectIdentifier =
    ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.3");
/// `ecdsa-with-SHA512` (RFC 5758 §3.2): 1.2.840.10045.4.3.4.
pub(crate) const OID_ECDSA_WITH_SHA512: ObjectIdentifier =
    ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.4");

/// `id-ecPublicKey` (RFC 5480 §2.1.1): 1.2.840.10045.2.1.
const OID_EC_PUBLIC_KEY: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.2.1");
/// `secp256r1` / `prime256v1` (RFC 5480 §2.1.1.1).
const OID_SECP256R1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7");
/// `secp384r1` (RFC 5480 §2.1.1.1).
const OID_SECP384R1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.132.0.34");
/// `secp521r1` (RFC 5480 §2.1.1.1).
const OID_SECP521R1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.132.0.35");
/// `sm2p256v1` (GB/T 32918.5): 1.2.156.10197.1.301.
///
/// The curve SM2 is defined over. Named here rather than in the
/// brainpool block because it is not an RFC 5639 curve and is not
/// reachable through the ECDSA dispatch -- see [`Sm2WithSm3Verifier`].
#[cfg(feature = "sm2")]
const OID_SM2P256V1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.156.10197.1.301");

/// `brainpoolP224r1` (RFC 5639 §4.1): 1.3.36.3.3.2.8.1.1.5.
pub(crate) const OID_BRAINPOOL_P224R1: ObjectIdentifier =
    ObjectIdentifier::new_unwrap("1.3.36.3.3.2.8.1.1.5");
/// `brainpoolP256r1` (RFC 5639 §4.1): 1.3.36.3.3.2.8.1.1.7.
pub(crate) const OID_BRAINPOOL_P256R1: ObjectIdentifier =
    ObjectIdentifier::new_unwrap("1.3.36.3.3.2.8.1.1.7");
/// `brainpoolP384r1` (RFC 5639 §4.1): 1.3.36.3.3.2.8.1.1.11.
pub(crate) const OID_BRAINPOOL_P384R1: ObjectIdentifier =
    ObjectIdentifier::new_unwrap("1.3.36.3.3.2.8.1.1.11");
/// `brainpoolP512r1` (RFC 5639 §4.1): 1.3.36.3.3.2.8.1.1.13.
///
/// Implemented by [`crate::brainpool_p512r1`] rather than by an upstream
/// crate, because none provides this curve. Every German CSCA
/// certificate uses it.
pub(crate) const OID_BRAINPOOL_P512R1: ObjectIdentifier =
    ObjectIdentifier::new_unwrap("1.3.36.3.3.2.8.1.1.13");

/// `rsaEncryption` (RFC 3279 §2.3.1).
pub(crate) const OID_RSA_ENCRYPTION: ObjectIdentifier =
    ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1");
/// `sha256WithRSAEncryption` (RFC 4055 §5).
pub(crate) const OID_SHA256_WITH_RSA: ObjectIdentifier =
    ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.11");
/// `sha384WithRSAEncryption` (RFC 4055 §5).
pub(crate) const OID_SHA384_WITH_RSA: ObjectIdentifier =
    ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.12");
/// `sha512WithRSAEncryption` (RFC 4055 §5).
pub(crate) const OID_SHA512_WITH_RSA: ObjectIdentifier =
    ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.13");
/// `id-RSASSA-PSS` (RFC 4055 §3.1).
pub(crate) const OID_RSASSA_PSS: ObjectIdentifier =
    ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.10");
/// `id-mgf1` (RFC 4055 §2.2).
#[cfg(feature = "rsa")]
const OID_MGF1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.8");
/// `id-sha256` (RFC 4055 §2.1).
#[cfg(feature = "rsa")]
const OID_SHA256: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.1");
/// `id-sha384` (RFC 4055 §2.1).
#[cfg(feature = "rsa")]
const OID_SHA384: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.2");
/// `id-sha512` (RFC 4055 §2.1).
#[cfg(feature = "rsa")]
const OID_SHA512: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.3");

/// `id-Ed25519` (RFC 8410 §3): 1.3.101.112.
pub(crate) const OID_ED25519: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.101.112");

// An intra-doc link only resolves when its target is compiled in, and
// CI documents each feature on its own (`cargo hack doc --each-feature`).
// So a doc comment behind feature A may not link an item behind feature
// B: the three legacy verifiers cross-reference each other, and each
// pair is a configuration where one exists and the other does not. Where
// the doc and the target share a gate, as here, the link is fine; where
// they do not, the name goes in backticks.

/// `sha1WithRSAEncryption` — RFC 3279 §2.2.1.
///
/// Only reachable with the `rsa-sha1` feature. See
/// [`RsaPkcs1v15Sha1Verifier`] for why it is not on by default.
#[cfg(feature = "rsa-sha1")]
const OID_SHA1_WITH_RSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.5");

/// `ripemd160WithRSA` — 1.3.36.3.3.1.2, on the Teletrust arc.
///
/// Not an RFC 3279 algorithm. It comes from the German Teletrust/BSI
/// arc, and nine self-issued roots in
/// `third_party/trust-stores/eu-eidas/` are signed with it: the German
/// qualified-signature CAs, `3R-CA 1:PN` through `11R-CA 1:PN`, issued
/// by the Regulierungsbehörde für Telekommunikation und Post and later
/// the Bundesnetzagentur.
#[cfg(feature = "rsa-ripemd160")]
const OID_RIPEMD160_WITH_RSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.36.3.3.1.2");

/// `sha1WithRSA` — the OIW spelling of the same algorithm,
/// 1.3.14.3.2.29.
///
/// RFC 3279 §2.2.1 names PKCS#1's `sha-1WithRSAEncryption`
/// (1.2.840.113549.1.1.5) and that is what everything modern emits, but
/// the OIW Security Special Interest Group arc carries an equivalent
/// OID for the identical construction, and real certificates use it.
///
/// Measured: six self-issued roots in
/// `third_party/trust-stores/uefi-oem-pk/` are signed this way,
/// VeriSign-era certificates inside OEM Secure Boot key databases. They
/// reported `UnsupportedAlgorithm` for an algorithm this crate
/// implements, which made an OID alias look like a missing primitive.
///
/// The two are the same signature over the same digest, so they share
/// one verifier.
#[cfg(feature = "rsa-sha1")]
const OID_SHA1_WITH_RSA_OIW: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.14.3.2.29");

/// `ecdsa-with-SHA1` — RFC 3279 §2.2.3.
///
/// Only reachable with the `ecdsa-sha1` feature. See
/// [`EcdsaSha1Verifier`].
#[cfg(feature = "ecdsa-sha1")]
const OID_ECDSA_WITH_SHA1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.4.1");

// ---------------------------------------------------------------------------
// Digest selection
// ---------------------------------------------------------------------------

/// A SHA-2 digest named by a signature or hash algorithm OID.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Sha2 {
    Sha256,
    Sha384,
    Sha512,
}

/// Digest named by an `ecdsa-with-SHA*` signature OID, or `None`.
fn ecdsa_digest(oid: ObjectIdentifier) -> Option<Sha2> {
    match oid {
        OID_ECDSA_WITH_SHA256 => Some(Sha2::Sha256),
        OID_ECDSA_WITH_SHA384 => Some(Sha2::Sha384),
        OID_ECDSA_WITH_SHA512 => Some(Sha2::Sha512),
        _ => None,
    }
}

// SHA-1 is kept off the `Sha2` path on purpose. Adding a variant to that
// enum would put SHA-1 into every digest match in this file, including the
// ones reached by default, and would make "is this build willing to use
// SHA-1?" a question about runtime values rather than about compilation.
// Separate functions behind separate features mean the answer is: only if
// you asked for it, and otherwise the code is not here.
// Gated on `ecdsa-sha1` alone, not on both. ECDSA verifies over a
// pre-computed digest so it needs this; the RSA path hands SHA-1 to
// `VerifyingKey<sha1::Sha1>` and never digests separately. With only
// `rsa-sha1` enabled a broader gate leaves this dead, which is an error
// under -D warnings and was caught by the feature powerset.
#[cfg(feature = "ecdsa-sha1")]
fn sha1_digest(message: &[u8]) -> Vec<u8> {
    use sha1::Digest as _;
    sha1::Sha1::digest(message).to_vec()
}

// Every ECDSA and RSA verifier prehashes through here, the brainpool
// curves included: `ecdsa_generic_curve_verify!` and
// `ecdsa_curve_verify!` both call it. The list used to name only the
// NIST curves and RSA, so `bp224` or `bp512` on its own left the
// function cfg'd out while its callers remained -- invisible to any
// build where some other feature happened to be on too.
#[cfg(any(
    feature = "p256",
    feature = "p384",
    feature = "p521",
    feature = "rsa",
    feature = "bp224",
    feature = "bp256",
    feature = "bp384",
    feature = "bp512"
))]
fn sha2_digest(alg: Sha2, message: &[u8]) -> Vec<u8> {
    use sha2::Digest as _;
    match alg {
        Sha2::Sha256 => sha2::Sha256::digest(message).to_vec(),
        Sha2::Sha384 => sha2::Sha384::digest(message).to_vec(),
        Sha2::Sha512 => sha2::Sha512::digest(message).to_vec(),
    }
}

// ---------------------------------------------------------------------------
// ECDSA
// ---------------------------------------------------------------------------

/// Named curve of an `id-ecPublicKey` SPKI, or `None` for any other key.
/// The curve of an EC key, from either form RFC 5480 §2.1.1 allows.
///
/// A `namedCurve` OID is read directly. A `specifiedCurve`
/// (X9.62 `SpecifiedECDomain`) is matched against the curves this crate
/// implements by
/// [`named_curve_from_specified`](crate::specified_curve::named_curve_from_specified),
/// which returns the equivalent OID so the dispatch below is unchanged.
///
/// The second form matters because ICAO Doc 9303 Part 12 §4.1.6.3
/// requires it for every machine-readable travel document CSCA, against
/// RFC 5480's "specifiedCurve MUST NOT be used". Reading only the OID
/// made 79 certificates in `third_party/trust-stores/icao-csca/`
/// unverifiable on curves whose arithmetic is right here -- see
/// `pkix-path/tests/explicit_ec_parameters.rs`.
fn ec_named_curve(spki: &SubjectPublicKeyInfoRef<'_>) -> Option<ObjectIdentifier> {
    if spki.algorithm.oid != OID_EC_PUBLIC_KEY {
        return None;
    }
    let params = spki.algorithm.parameters?;
    if let Ok(oid) = params.decode_as::<ObjectIdentifier>() {
        return Some(oid);
    }
    crate::specified_curve::named_curve_from_specified(params)
}

macro_rules! ecdsa_curve_verify {
    ($fn_name:ident, $feature:literal, $krate:ident) => {
        #[cfg(feature = $feature)]
        fn $fn_name(
            spki: SubjectPublicKeyInfoRef<'_>,
            digest: Sha2,
            message: &[u8],
            signature: &[u8],
        ) -> VerifyResult {
            use signature::hazmat::PrehashVerifier as _;
            use $krate::ecdsa::{DerSignature, VerifyingKey};

            // From the SEC 1 point, not from the SPKI.
            //
            // `VerifyingKey::try_from(spki)` re-reads
            // `algorithm.parameters` and requires the `namedCurve` OID
            // for this curve, so a key carrying an X9.62
            // `SpecifiedECDomain` -- mandatory for every ICAO Doc 9303
            // CSCA, see `crate::specified_curve` -- was rejected as a
            // malformed key even once the curve had been recognized.
            //
            // Nothing is checked less. `ec_named_curve` resolved the
            // curve and the caller matched it against this function's
            // own curve before dispatching here, which is the check
            // `try_from` would repeat. `from_sec1_bytes` still validates
            // the encoding and that the point is on the curve, and it
            // rejects the identity.
            let point = spki
                .subject_public_key
                .as_bytes()
                .ok_or_else(VerificationError::malformed_key)?;
            let vk = VerifyingKey::from_sec1_bytes(point)
                .map_err(|_| VerificationError::malformed_key())?;
            let sig = DerSignature::try_from(signature)
                .map_err(|_| VerificationError::invalid_signature())?;
            // No padding to the field width. SEC 1 v2 §4.1.4 step 5 reads
            // the digest as an integer, taking the leftmost min(N, outlen)
            // bits, and `ecdsa`'s `bytes2scalar` does exactly that: it
            // truncates a digest wider than the curve order and reduces a
            // narrower one unchanged. A shorter digest is therefore the
            // same scalar as the same digest left-padded with zeros, so
            // P-521 with `ecdsa-with-SHA256` needs nothing done to it.
            let prehash = sha2_digest(digest, message);
            vk.verify_prehash(&prehash, &sig).map_err(|e| {
                VerificationError::with_source(VerificationErrorKind::InvalidSignature, e)
            })
        }
    };
}

/// ECDSA verification for a curve whose crate does not re-export
/// `VerifyingKey`.
///
/// `p256` and friends re-export `ecdsa::VerifyingKey<Self>` under
/// `<krate>::ecdsa`; the brainpool crates carry two curves each and
/// re-export only the signature types, so the key type is named
/// generically here instead. Otherwise identical to
/// [`ecdsa_curve_verify!`], including building the key from the SEC 1
/// point rather than the SPKI, for the reason given there.
macro_rules! ecdsa_generic_curve_verify {
    ($fn_name:ident, $feature:literal, $curve:ty) => {
        #[cfg(feature = $feature)]
        fn $fn_name(
            spki: SubjectPublicKeyInfoRef<'_>,
            digest: Sha2,
            message: &[u8],
            signature: &[u8],
        ) -> VerifyResult {
            use signature::hazmat::PrehashVerifier as _;

            let point = spki
                .subject_public_key
                .as_bytes()
                .ok_or_else(VerificationError::malformed_key)?;
            let vk = ecdsa::VerifyingKey::<$curve>::from_sec1_bytes(point)
                .map_err(|_| VerificationError::malformed_key())?;
            let sig = ecdsa::der::Signature::<$curve>::try_from(signature)
                .map_err(|_| VerificationError::invalid_signature())?;
            let prehash = sha2_digest(digest, message);
            vk.verify_prehash(&prehash, &sig).map_err(|e| {
                VerificationError::with_source(VerificationErrorKind::InvalidSignature, e)
            })
        }
    };
}

ecdsa_generic_curve_verify!(
    verify_ecdsa_bp224,
    "bp224",
    crate::brainpool_p224r1::BrainpoolP224r1
);
ecdsa_generic_curve_verify!(verify_ecdsa_bp256, "bp256", bp256::BrainpoolP256r1);
ecdsa_generic_curve_verify!(verify_ecdsa_bp384, "bp384", bp384::BrainpoolP384r1);
ecdsa_generic_curve_verify!(
    verify_ecdsa_bp512,
    "bp512",
    crate::brainpool_p512r1::BrainpoolP512r1
);
ecdsa_curve_verify!(verify_ecdsa_p256, "p256", p256);
ecdsa_curve_verify!(verify_ecdsa_p384, "p384", p384);
ecdsa_curve_verify!(verify_ecdsa_p521, "p521", p521);

/// Which curves an ECDSA verifier accepts.
#[derive(Clone, Copy)]
struct Curves {
    p256: bool,
    p384: bool,
    p521: bool,
    bp224: bool,
    bp256: bool,
    bp384: bool,
    bp512: bool,
}

/// ECDSA dispatch: digest from `algorithm`, curve from `issuer_spki`.
fn verify_ecdsa(
    curves: Curves,
    algorithm: AlgorithmIdentifierRef<'_>,
    issuer_spki: SubjectPublicKeyInfoRef<'_>,
    message: &[u8],
    signature: &[u8],
) -> VerifyResult {
    let digest =
        ecdsa_digest(algorithm.oid).ok_or_else(VerificationError::unsupported_algorithm)?;
    // RFC 5758 §3.2 says the parameters field MUST be omitted for every
    // ECDSA OID, and this accepts it anyway when it is present and NULL.
    //
    // WHY. A bare `05 00` carries nothing. The scheme and digest come
    // from the OID, which is what `ecdsa_digest` just read, so an
    // attacker who adds or strips a NULL changes two bytes that feed
    // into no decision. The security intent of the field -- that the
    // same algorithm be named consistently -- is enforced by
    // `check_oid_consistency`, which compares OIDs across the inner and
    // outer `AlgorithmIdentifier`.
    //
    // That function reached this conclusion first, and said so: "RFC
    // 5280 says the two AlgorithmIdentifiers MUST be identical, but many
    // production CAs generate certs where one field has explicit NULL
    // parameters and the other omits them -- a mismatch that OpenSSL and
    // other validators accept in practice." Refusing the whole
    // certificate here, for the field that function deliberately
    // ignores, was this file contradicting the path validator rather
    // than making a judgement.
    //
    // The RSA path in this same file already takes the NULL-or-absent
    // reading (`is_none_or(|p| p.is_null())`), as RFC 4055 §5 requires
    // of it.
    //
    // MEASURED: 17 certificates across the vendored corpora do this, 4
    // of Germany's 23 among them, and two of those four are CSCA roots.
    // `serialNumber=013` is `ecdsa-with-SHA256` on brainpoolP256r1 --
    // a curve this crate implements -- and this refusal was the only
    // thing standing between it and verifying.
    //
    // An IETF profile rule cannot make a national root unusable. BSI
    // published it, an operator installed it, and the signature is
    // cryptographically valid; OpenSSL verifies it. Same principle as
    // `AnchorAdmission`, one layer down.
    //
    // Still refused: parameters present and NOT NULL. That is a
    // structure making a claim this code does not understand, which is
    // different from a two-byte encoding habit carried over from RSA.
    if !algorithm.parameters.is_none_or(|p| p.is_null()) {
        return Err(VerificationError::unsupported_algorithm());
    }
    let curve = ec_named_curve(&issuer_spki).ok_or_else(VerificationError::unsupported_key)?;
    match curve {
        #[cfg(feature = "p256")]
        OID_SECP256R1 if curves.p256 => verify_ecdsa_p256(issuer_spki, digest, message, signature),
        #[cfg(feature = "p384")]
        OID_SECP384R1 if curves.p384 => verify_ecdsa_p384(issuer_spki, digest, message, signature),
        #[cfg(feature = "p521")]
        OID_SECP521R1 if curves.p521 => verify_ecdsa_p521(issuer_spki, digest, message, signature),
        #[cfg(feature = "bp224")]
        OID_BRAINPOOL_P224R1 if curves.bp224 => {
            verify_ecdsa_bp224(issuer_spki, digest, message, signature)
        }
        #[cfg(feature = "bp256")]
        OID_BRAINPOOL_P256R1 if curves.bp256 => {
            verify_ecdsa_bp256(issuer_spki, digest, message, signature)
        }
        #[cfg(feature = "bp384")]
        OID_BRAINPOOL_P384R1 if curves.bp384 => {
            verify_ecdsa_bp384(issuer_spki, digest, message, signature)
        }
        #[cfg(feature = "bp512")]
        OID_BRAINPOOL_P512R1 if curves.bp512 => {
            verify_ecdsa_bp512(issuer_spki, digest, message, signature)
        }
        _ => Err(VerificationError::unsupported_key()),
    }
}

macro_rules! ecdsa_verifier {
    ($(#[$doc:meta])* $name:ident, $feature:literal, $field:ident) => {
        $(#[$doc])*
        #[cfg(feature = $feature)]
        #[cfg_attr(docsrs, doc(cfg(feature = $feature)))]
        #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
        pub struct $name;

        #[cfg(feature = $feature)]
        impl SignatureVerifier for $name {
            fn verify_signature(
                &self,
                algorithm: AlgorithmIdentifierRef<'_>,
                issuer_spki: SubjectPublicKeyInfoRef<'_>,
                message: &[u8],
                signature: &[u8],
            ) -> VerifyResult {
                let curves = Curves {
                    p256: false,
                    p384: false,
                    p521: false,
                    bp224: false,
                    bp256: false,
                    bp384: false,
                    bp512: false,
                };
                let curves = Curves {
                    $field: true,
                    ..curves
                };
                verify_ecdsa(curves, algorithm, issuer_spki, message, signature)
            }
        }
    };
}

ecdsa_verifier!(
    /// ECDSA verifier for P-256 (`secp256r1`) issuer keys.
    ///
    /// Accepts `ecdsa-with-SHA256`, `ecdsa-with-SHA384` and
    /// `ecdsa-with-SHA512` (RFC 5758 §3.2; the `parameters` field must be
    /// absent). Rejects issuer keys on any other curve.
    /// Feature-gated behind `p256`.
    EcdsaP256Verifier,
    "p256",
    p256
);

ecdsa_verifier!(
    /// ECDSA verifier for P-384 (`secp384r1`) issuer keys.
    ///
    /// Accepts `ecdsa-with-SHA256`, `ecdsa-with-SHA384` and
    /// `ecdsa-with-SHA512` (RFC 5758 §3.2; the `parameters` field must be
    /// absent). Rejects issuer keys on any other curve.
    /// Feature-gated behind `p384`.
    EcdsaP384Verifier,
    "p384",
    p384
);

ecdsa_verifier!(
    /// ECDSA verifier for P-521 (`secp521r1`) issuer keys.
    ///
    /// Accepts `ecdsa-with-SHA256`, `ecdsa-with-SHA384` and
    /// `ecdsa-with-SHA512` (RFC 5758 §3.2; the `parameters` field must be
    /// absent). Rejects issuer keys on any other curve.
    /// Feature-gated behind `p521`.
    EcdsaP521Verifier,
    "p521",
    p521
);

// ---------------------------------------------------------------------------
// RSA
// ---------------------------------------------------------------------------

/// Decodes an RSA public key from an SPKI whose algorithm is `rsaEncryption`
/// (parameters NULL or absent, RFC 3279 §2.3.1) or, when `allow_pss_key` is
/// set, `id-RSASSA-PSS` (RFC 4055 §1.2).
///
/// Moduli from 1024 to 8192 bits are accepted (the `rsa` crate's limits).
/// What an RSA public key's DER had to be forgiven for.
///
/// Returned beside the key by [`rsa_public_key_lenient`], so a caller
/// learns what was tolerated rather than only that it worked. Nothing in
/// this crate acts on the value; it exists because silently accepting
/// malformed input is how a lenient parser becomes a liability.
#[cfg(feature = "rsa")]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RsaKeyDeviation {
    /// An INTEGER carried more leading zero octets than it needs.
    ///
    /// `02 04 00 00 00 03` for the exponent 3, where DER requires the
    /// minimal `02 01 03`. Unambiguous: the extra octets change no
    /// value, and X.690 §8.3.2 forbids them only so that one value has
    /// one encoding.
    ///
    /// Austria's `a-sign Premium CA` and `a-sign uni`, in
    /// `third_party/trust-stores/eu-eidas/`, both do this.
    NonMinimalInteger,
    /// An INTEGER's high bit was set without the leading zero octet that
    /// DER requires, so as written it denotes a negative number.
    ///
    /// `02 04 C0 00 00 01` for the exponent 0xC0000001, where the
    /// canonical form is `02 05 00 C0 00 00 01`. Reading it as positive
    /// is a **reinterpretation**, not a relaxed length check -- see
    /// [`rsa_public_key_lenient`] on why that is sound for this field
    /// and would not be elsewhere.
    ///
    /// Germany's `3R-CA 1:PN` and `4R-CA 1:PN` of January 1999 do this;
    /// `5R-CA` of March 2000 encodes the identical exponent correctly,
    /// so it was an encoder bug they fixed within fourteen months.
    NegativeInteger,
}

/// An RSA public key from an SPKI whose `RSAPublicKey` INTEGERs may not
/// be canonical DER, with whatever had to be forgiven.
///
/// # Why this exists at all
///
/// `rsa::PublicKey::from_pkcs1_der` decodes through `der`'s typed
/// `UintRef`, which enforces X.690 §8.3.2 minimal encoding -- correctly,
/// and this function does not change that for anybody else. It drops to
/// `der`'s untyped layer for this one structure instead, reading each
/// INTEGER's value octets with `Header::decode` and `read_slice` and
/// handing the magnitudes to `rsa::PublicKey::new`.
///
/// **No fork, and no patched dependency.** Everything here is public API
/// of `der` and `rsa`, and `tbs_der_slice` in this crate's root already
/// reads raw TLVs the same way.
///
/// # Why reading these as unsigned is sound
///
/// A modulus and a public exponent are definitionally non-negative, so
/// there is no value a negative encoding could have been intended to
/// mean. That is what makes [`NegativeInteger`](RsaKeyDeviation::NegativeInteger)
/// recoverable here and would not make it recoverable in, say, a
/// validity date or a path length: those have signed interpretations
/// that differ from the unsigned one, and guessing between them would be
/// inventing input.
///
/// The arithmetic is unchanged. `rsa::PublicKey::new` still applies
/// every check it applies to a canonically encoded key -- `e` odd, `e`
/// in `MIN_PUB_EXPONENT..=MAX_PUB_EXPONENT`, `e < n`, `n` odd and
/// non-zero, modulus within `MIN_SIZE..=MAX_SIZE` -- so a key that is
/// weak rather than merely mis-encoded is refused exactly as before.
/// Only the parse is lenient; nothing downstream is.
///
/// # Errors
///
/// [`MalformedKey`](VerificationErrorKind::MalformedKey) when the
/// structure is not two INTEGERs in a SEQUENCE, or when `rsa` rejects
/// the resulting key. A deviation is reported, never an error.
#[cfg(feature = "rsa")]
pub fn rsa_public_key_lenient(
    spki: &SubjectPublicKeyInfoRef<'_>,
) -> core::result::Result<(rsa::PublicKey, Option<RsaKeyDeviation>), VerificationError> {
    use der::{Decode as _, Header, SliceReader, Tag};

    let oid_ok = spki.algorithm.oid == OID_RSA_ENCRYPTION
        && spki.algorithm.parameters.is_none_or(|p| p.is_null());
    if !oid_ok {
        return Err(VerificationError::unsupported_key());
    }
    let key_bytes = spki
        .subject_public_key
        .as_bytes()
        .ok_or_else(VerificationError::malformed_key)?;

    // Strict first, so a conformant key takes the ordinary path and this
    // function is a fallback rather than a replacement.
    if let Ok(key) = {
        use rsa::pkcs1::DecodeRsaPublicKey as _;
        rsa::PublicKey::from_pkcs1_der(key_bytes)
    } {
        return Ok((key, None));
    }

    let mut reader = SliceReader::new(key_bytes).map_err(|_| VerificationError::malformed_key())?;
    let outer = Header::decode(&mut reader).map_err(|_| VerificationError::malformed_key())?;
    if outer.tag() != Tag::Sequence {
        return Err(VerificationError::malformed_key());
    }

    /// One INTEGER's value octets, plus what was wrong with them.
    fn integer<'a>(
        reader: &mut der::SliceReader<'a>,
    ) -> core::result::Result<(&'a [u8], Option<RsaKeyDeviation>), VerificationError> {
        use der::{Decode as _, Header, Reader as _, Tag};

        let header = Header::decode(reader).map_err(|_| VerificationError::malformed_key())?;
        if header.tag() != Tag::Integer {
            return Err(VerificationError::malformed_key());
        }
        let raw = reader
            .read_slice(header.length())
            .map_err(|_| VerificationError::malformed_key())?;
        let (first, rest) = raw
            .split_first()
            .ok_or_else(VerificationError::malformed_key)?;

        // DER (X.690 §8.3.2): the first nine bits may not be all zero or
        // all one. So exactly one leading 0x00 is correct when the next
        // octet's high bit is set, and otherwise there must be none.
        let deviation = if *first == 0x00 {
            match rest.first() {
                // `00 C0 ...` -- the one permitted leading zero.
                Some(b) if b & 0x80 != 0 => None,
                // `00 00 00 03` -- more zeros than needed. Also `00 03`,
                // where the zero buys nothing because 0x03 is positive.
                _ => Some(RsaKeyDeviation::NonMinimalInteger),
            }
        } else if *first & 0x80 != 0 {
            // `C0 00 00 01` -- high bit set with no leading zero, so this
            // denotes a negative number as written.
            Some(RsaKeyDeviation::NegativeInteger)
        } else {
            None
        };

        // The magnitude: leading zero octets carry no value whichever
        // deviation applied, and stripping them is what makes
        // `BoxedUint::from_be_slice` see the number that was meant.
        let magnitude = &raw[raw.iter().take_while(|&&b| b == 0).count()..];
        Ok((magnitude, deviation))
    }

    let (n_bytes, n_dev) = integer(&mut reader)?;
    let (e_bytes, e_dev) = integer(&mut reader)?;

    // `NegativeInteger` is reported ahead of `NonMinimalInteger` when
    // both appear: it is the stronger claim about the input, and a
    // caller logging one line should see the worse of the two.
    let deviation = match (n_dev, e_dev) {
        (Some(RsaKeyDeviation::NegativeInteger), _)
        | (_, Some(RsaKeyDeviation::NegativeInteger)) => Some(RsaKeyDeviation::NegativeInteger),
        (Some(d), _) | (_, Some(d)) => Some(d),
        (None, None) => None,
    };

    let n = rsa::BoxedUint::from_be_slice_vartime(n_bytes);
    let e = rsa::BoxedUint::from_be_slice_vartime(e_bytes);
    let key = rsa::PublicKey::new(n, e)
        .map_err(|e| VerificationError::with_source(VerificationErrorKind::MalformedKey, e))?;
    Ok((key, deviation))
}

#[cfg(feature = "rsa")]
fn rsa_public_key(
    spki: &SubjectPublicKeyInfoRef<'_>,
    allow_pss_key: bool,
) -> core::result::Result<rsa::PublicKey, VerificationError> {
    use rsa::pkcs1::DecodeRsaPublicKey as _;

    let oid_ok = spki.algorithm.oid == OID_RSA_ENCRYPTION
        && spki.algorithm.parameters.is_none_or(|p| p.is_null());
    let pss_ok = allow_pss_key && spki.algorithm.oid == OID_RSASSA_PSS;
    if !(oid_ok || pss_ok) {
        return Err(VerificationError::unsupported_key());
    }
    let key_bytes = spki
        .subject_public_key
        .as_bytes()
        .ok_or_else(VerificationError::malformed_key)?;
    match rsa::PublicKey::from_pkcs1_der(key_bytes) {
        Ok(key) => Ok(key),
        // The lenient retry. In the `rustcrypto` umbrella, so this is
        // the default path for the four certificates that need it.
        //
        // Deliberately NOT reported from here. `verify_signature`
        // returns `Result<(), VerificationError>` and has no channel for
        // "it worked, and here is what was odd about it" -- unlike
        // anchor loading, where `LoadedAnchors::deviations` exists for
        // exactly that. Rather than invent a side channel or log from a
        // `no_std` crate, the deviation is made available to a caller
        // who wants it through the public
        // [`rsa_public_key_lenient`], which returns it beside the key.
        // A caller auditing a bundle calls that; a caller validating a
        // path gets the key.
        //
        // Turning `rsa-noncanonical-key` OFF restores the refusal, which
        // is what an operator who would rather be told should do. The
        // decision to make it the default was measured: four
        // certificates of 2,409 self-issued in the vendored corpus
        // change answer, and nothing else does.
        #[cfg(feature = "rsa-noncanonical-key")]
        Err(_) => rsa_public_key_lenient(spki).map(|(key, _deviation)| key),
        #[cfg(not(feature = "rsa-noncanonical-key"))]
        Err(e) => Err(VerificationError::with_source(
            VerificationErrorKind::MalformedKey,
            e,
        )),
    }
}

/// RSA PKCS#1 v1.5 verification with the given digest.
#[cfg(feature = "rsa")]
fn verify_rsa_pkcs1v15(
    digest: Sha2,
    algorithm: AlgorithmIdentifierRef<'_>,
    issuer_spki: SubjectPublicKeyInfoRef<'_>,
    message: &[u8],
    signature: &[u8],
) -> VerifyResult {
    use rsa::pkcs1v15::{Signature, VerifyingKey};
    use rsa::signature::Verifier as _;

    // RFC 4055 §5: parameters MUST be NULL; absent is accepted for
    // interoperability, matching the issuer-key decoding above.
    if !algorithm.parameters.is_none_or(|p| p.is_null()) {
        return Err(VerificationError::unsupported_algorithm());
    }
    let key = rsa_public_key(&issuer_spki, false)?;
    let sig = Signature::try_from(signature).map_err(|_| VerificationError::invalid_signature())?;
    let result = match digest {
        Sha2::Sha256 => VerifyingKey::<sha2::Sha256>::new(key).verify(message, &sig),
        Sha2::Sha384 => VerifyingKey::<sha2::Sha384>::new(key).verify(message, &sig),
        Sha2::Sha512 => VerifyingKey::<sha2::Sha512>::new(key).verify(message, &sig),
    };
    result.map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
}

/// Hash named by an RFC 4055 `HashAlgorithm` identifier (parameters NULL or
/// absent, RFC 4055 §2.1).
#[cfg(feature = "rsa")]
fn rfc4055_hash(alg: &spki::AlgorithmIdentifierOwned) -> Option<Sha2> {
    if !alg.parameters.as_ref().is_none_or(der::Any::is_null) {
        return None;
    }
    match alg.oid {
        OID_SHA256 => Some(Sha2::Sha256),
        OID_SHA384 => Some(Sha2::Sha384),
        OID_SHA512 => Some(Sha2::Sha512),
        _ => None,
    }
}

/// RSASSA-PSS verification (RFC 4055 §3.1, RFC 8017 §8.1.2).
///
/// Supported parameters: `hashAlgorithm` SHA-256, SHA-384 or SHA-512;
/// `maskGenAlgorithm` MGF1 over the same hash; any `saltLength`;
/// `trailerField` 1. The default parameters (SHA-1) are rejected.
#[cfg(feature = "rsa")]
fn verify_rsa_pss(
    algorithm: AlgorithmIdentifierRef<'_>,
    issuer_spki: SubjectPublicKeyInfoRef<'_>,
    message: &[u8],
    signature: &[u8],
) -> VerifyResult {
    use der::{Decode as _, Encode as _};
    use rsa::pkcs1::{RsaPssParamsOwned, TrailerField};
    use rsa::pss::{Signature, VerifyingKey};
    use rsa::signature::hazmat::PrehashVerifier as _;

    let params_der = algorithm
        .parameters
        .ok_or_else(VerificationError::unsupported_algorithm)?
        .to_der()
        .map_err(|_| VerificationError::unsupported_algorithm())?;
    let params = RsaPssParamsOwned::from_der(&params_der)
        .map_err(|_| VerificationError::unsupported_algorithm())?;
    let hash = rfc4055_hash(&params.hash).ok_or_else(VerificationError::unsupported_algorithm)?;
    if params.mask_gen.oid != OID_MGF1 {
        return Err(VerificationError::unsupported_algorithm());
    }
    let mgf_hash = params
        .mask_gen
        .parameters
        .as_ref()
        .and_then(rfc4055_hash)
        .ok_or_else(VerificationError::unsupported_algorithm)?;
    if mgf_hash != hash || params.trailer_field != TrailerField::BC {
        return Err(VerificationError::unsupported_algorithm());
    }
    // RFC 4055 §3.1: when the issuer key is an id-RSASSA-PSS key with
    // parameters, the signature must use the same hash and MGF and a salt
    // at least as long. We check the hash and MGF; a key restricted that
    // way still verifies only signatures that match its own parameters.
    if issuer_spki.algorithm.oid == OID_RSASSA_PSS
        && let Some(key_params) = issuer_spki.algorithm.parameters
    {
        let key_params_der = key_params
            .to_der()
            .map_err(|_| VerificationError::malformed_key())?;
        let key_params = RsaPssParamsOwned::from_der(&key_params_der)
            .map_err(|_| VerificationError::malformed_key())?;
        let key_hash =
            rfc4055_hash(&key_params.hash).ok_or_else(VerificationError::unsupported_key)?;
        if key_hash != hash || params.salt_len < key_params.salt_len {
            return Err(VerificationError::unsupported_key());
        }
    }
    let key = rsa_public_key(&issuer_spki, true)?;
    let sig = Signature::try_from(signature).map_err(|_| VerificationError::invalid_signature())?;
    let salt_len = usize::from(params.salt_len);
    let prehash = sha2_digest(hash, message);
    let result = match hash {
        Sha2::Sha256 => VerifyingKey::<sha2::Sha256>::new_with_salt_len(key, salt_len)
            .verify_prehash(&prehash, &sig),
        Sha2::Sha384 => VerifyingKey::<sha2::Sha384>::new_with_salt_len(key, salt_len)
            .verify_prehash(&prehash, &sig),
        Sha2::Sha512 => VerifyingKey::<sha2::Sha512>::new_with_salt_len(key, salt_len)
            .verify_prehash(&prehash, &sig),
    };
    result.map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
}

macro_rules! rsa_pkcs1v15_verifier {
    ($(#[$doc:meta])* $name:ident, $oid:ident, $digest:ident) => {
        $(#[$doc])*
        #[cfg(feature = "rsa")]
        #[cfg_attr(docsrs, doc(cfg(feature = "rsa")))]
        #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
        pub struct $name;

        #[cfg(feature = "rsa")]
        impl SignatureVerifier for $name {
            fn verify_signature(
                &self,
                algorithm: AlgorithmIdentifierRef<'_>,
                issuer_spki: SubjectPublicKeyInfoRef<'_>,
                message: &[u8],
                signature: &[u8],
            ) -> VerifyResult {
                if algorithm.oid != $oid {
                    return Err(VerificationError::unsupported_algorithm());
                }
                verify_rsa_pkcs1v15(Sha2::$digest, algorithm, issuer_spki, message, signature)
            }
        }
    };
}

rsa_pkcs1v15_verifier!(
    /// RSA with PKCS#1 v1.5 padding and SHA-256 signature verifier.
    ///
    /// Handles OID `sha256WithRSAEncryption` (1.2.840.113549.1.1.11).
    /// Feature-gated behind `rsa`.
    RsaPkcs1v15Sha256Verifier,
    OID_SHA256_WITH_RSA,
    Sha256
);

rsa_pkcs1v15_verifier!(
    /// RSA with PKCS#1 v1.5 padding and SHA-384 signature verifier.
    ///
    /// Handles OID `sha384WithRSAEncryption` (1.2.840.113549.1.1.12).
    /// Feature-gated behind `rsa`.
    RsaPkcs1v15Sha384Verifier,
    OID_SHA384_WITH_RSA,
    Sha384
);

rsa_pkcs1v15_verifier!(
    /// RSA with PKCS#1 v1.5 padding and SHA-512 signature verifier.
    ///
    /// Handles OID `sha512WithRSAEncryption` (1.2.840.113549.1.1.13).
    /// Feature-gated behind `rsa`.
    RsaPkcs1v15Sha512Verifier,
    OID_SHA512_WITH_RSA,
    Sha512
);

/// Verifies RSA PKCS#1 v1.5 signatures over SHA-1. **Legacy interop only.**
///
/// # Security
///
/// SHA-1 collisions are practical. SHAttered (2017) produced a colliding
/// pair for roughly 2^63 operations, and chosen-prefix collisions followed
/// in 2020 at lower cost. An attacker able to mint a certificate that
/// collides with one a CA signed can substitute it, and the signature will
/// verify. Treat a SHA-1-signed chain as evidence of provenance, not as
/// proof of identity.
///
/// It exists because messages outlive algorithms. S/MIME signed in 2015
/// sits in a mailbox today, and a client that cannot check its chain can
/// tell the user nothing useful — "verify, then warn" is what clients
/// actually do. CA/Browser Forum rules forbid new SHA-1 issuance; they do
/// not delete the archive.
///
/// Off by default, behind the `rsa-sha1` feature, and deliberately *not*
/// in the `rustcrypto` umbrella — that umbrella means "algorithms we
/// recommend". New deployments MUST NOT enable this.
///
/// Verification only. Nothing in this workspace signs with SHA-1 and
/// nothing is intended to.
#[cfg(feature = "rsa-sha1")]
#[cfg_attr(docsrs, doc(cfg(feature = "rsa-sha1")))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct RsaPkcs1v15Sha1Verifier;

#[cfg(feature = "rsa-sha1")]
impl SignatureVerifier for RsaPkcs1v15Sha1Verifier {
    fn verify_signature(
        &self,
        algorithm: AlgorithmIdentifierRef<'_>,
        issuer_spki: SubjectPublicKeyInfoRef<'_>,
        message: &[u8],
        signature: &[u8],
    ) -> VerifyResult {
        use rsa::pkcs1v15::{Signature, VerifyingKey};
        use rsa::signature::Verifier as _;

        if algorithm.oid != OID_SHA1_WITH_RSA && algorithm.oid != OID_SHA1_WITH_RSA_OIW {
            return Err(VerificationError::unsupported_algorithm());
        }
        if !algorithm.parameters.is_none_or(|p| p.is_null()) {
            return Err(VerificationError::unsupported_algorithm());
        }
        let key = rsa_public_key(&issuer_spki, false)?;
        let sig =
            Signature::try_from(signature).map_err(|_| VerificationError::invalid_signature())?;
        VerifyingKey::<sha1::Sha1>::new(key)
            .verify(message, &sig)
            .map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
    }
}

/// ECDSA-over-SHA-1 for one curve.
///
/// Deliberately a separate macro from [`ecdsa_generic_curve_verify!`]
/// rather than a `Sha2` variant. The comment on [`ecdsa_digest`] gives
/// the reason: putting SHA-1 into that enum would put it into every
/// digest match in this file, including the ones reached by default, and
/// make "is this build willing to use SHA-1?" a question about runtime
/// values instead of about compilation. Each of these exists only when
/// both `ecdsa-sha1` and the curve's own feature are on.
macro_rules! ecdsa_sha1_curve_verify {
    ($fn_name:ident, $feature:literal, $curve:ty) => {
        #[cfg(all(feature = "ecdsa-sha1", feature = $feature))]
        fn $fn_name(
            spki: SubjectPublicKeyInfoRef<'_>,
            message: &[u8],
            signature: &[u8],
        ) -> VerifyResult {
            use signature::hazmat::PrehashVerifier as _;

            let point = spki
                .subject_public_key
                .as_bytes()
                .ok_or_else(VerificationError::malformed_key)?;
            let vk = ecdsa::VerifyingKey::<$curve>::from_sec1_bytes(point)
                .map_err(|_| VerificationError::malformed_key())?;
            let sig = ecdsa::der::Signature::<$curve>::try_from(signature)
                .map_err(|_| VerificationError::invalid_signature())?;
            // FIPS 186-4 takes the leftmost min(N, outlen) bits of the
            // hash. For a 160-bit digest and any field here that is all
            // of it, and `ecdsa`'s `bytes2scalar` reduces a narrower
            // digest unchanged, so a 20-byte prehash needs no padding.
            let prehash = sha1_digest(message);
            vk.verify_prehash(&prehash, &sig).map_err(|e| {
                VerificationError::with_source(VerificationErrorKind::InvalidSignature, e)
            })
        }
    };
}

ecdsa_sha1_curve_verify!(verify_ecdsa_sha1_p256, "p256", p256::NistP256);
ecdsa_sha1_curve_verify!(verify_ecdsa_sha1_p384, "p384", p384::NistP384);
ecdsa_sha1_curve_verify!(verify_ecdsa_sha1_p521, "p521", p521::NistP521);
ecdsa_sha1_curve_verify!(
    verify_ecdsa_sha1_bp224,
    "bp224",
    crate::brainpool_p224r1::BrainpoolP224r1
);
ecdsa_sha1_curve_verify!(verify_ecdsa_sha1_bp256, "bp256", bp256::BrainpoolP256r1);
ecdsa_sha1_curve_verify!(verify_ecdsa_sha1_bp384, "bp384", bp384::BrainpoolP384r1);
ecdsa_sha1_curve_verify!(
    verify_ecdsa_sha1_bp512,
    "bp512",
    crate::brainpool_p512r1::BrainpoolP512r1
);

/// `id-Ed448` (RFC 8410 §3) — 1.3.101.113.
#[cfg(feature = "ed448")]
const OID_ED448: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.101.113");

/// Verifies Ed448 signatures (RFC 8032 EdDSA, RFC 8410 encoding).
///
/// # Scope
///
/// Four certificates in `third_party/trust-stores/br-icpbrasil/` are
/// signed with it, ICP-Brasil's `AC Raiz Brasileira v6` among them. No
/// browser root program ships an Ed448 CA, which is why a validator
/// built only against the web PKI never meets one.
///
/// # Encoding
///
/// RFC 8410 §4: the key is the raw 57-octet encoding in the
/// `subjectPublicKey` BIT STRING with no encapsulating `OCTET STRING`,
/// and the signature is the raw 114 octets. Both follow from RFC 8032's
/// `b = 456` for Ed448.
///
/// # The context string
///
/// RFC 8032 Ed448 signs over a context, and RFC 8410 §6 requires it to
/// be **empty** for X.509. `signature::Verifier::verify` is the
/// empty-context path; `verify_ctx` would be wrong here.
///
/// Verification only.
#[cfg(feature = "ed448")]
#[cfg_attr(docsrs, doc(cfg(feature = "ed448")))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Ed448Verifier;

#[cfg(feature = "ed448")]
impl SignatureVerifier for Ed448Verifier {
    fn verify_signature(
        &self,
        algorithm: AlgorithmIdentifierRef<'_>,
        issuer_spki: SubjectPublicKeyInfoRef<'_>,
        message: &[u8],
        signature: &[u8],
    ) -> VerifyResult {
        use ed448_goldilocks::{Signature, VerifyingKey};
        use signature::Verifier as _;

        if algorithm.oid != OID_ED448 {
            return Err(VerificationError::unsupported_algorithm());
        }
        // RFC 8410 §3: "the parameters field MUST be absent". NULL is
        // tolerated as elsewhere in this file, for producers carrying
        // the RSA habit across.
        if !algorithm.parameters.is_none_or(|p| p.is_null()) {
            return Err(VerificationError::unsupported_algorithm());
        }
        let key_bytes = issuer_spki
            .subject_public_key
            .as_bytes()
            .ok_or_else(VerificationError::malformed_key)?;
        let key: &[u8; 57] = key_bytes
            .try_into()
            .map_err(|_| VerificationError::malformed_key())?;
        let vk = VerifyingKey::from_bytes(key).map_err(|_| VerificationError::malformed_key())?;
        let sig: &[u8; 114] = signature
            .try_into()
            .map_err(|_| VerificationError::invalid_signature())?;
        let sig =
            Signature::try_from(&sig[..]).map_err(|_| VerificationError::invalid_signature())?;
        vk.verify(message, &sig)
            .map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
    }
}

/// `id-Ed521` as ICP-Brasil assigns it — 1.3.6.1.4.1.44588.2.1.
///
/// DOC-ICP-01.01 names the algorithm symbolically and never gives this
/// number; the binding rests on the `AC Raiz Brasileira v7` certificate
/// declaring it and then verifying as Ed521. See
/// [`crate::ed521`].
#[cfg(feature = "ed521")]
const OID_ED521: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.6.1.4.1.44588.2.1");

/// Verifies Ed521 signatures (EdDSA over E-521, per ICP-Brasil).
///
/// # ⚠ One certificate, and not for general use
///
/// **Read [`crate::ed521`] before enabling the `ed521` feature.** That
/// module has no published test vectors, no second implementation to
/// compare against, and exactly one real signature exercising it. Its
/// edge cases are untested.
///
/// This verifier exists so that no certificate in
/// `third_party/trust-stores/` is refused for an algorithm nobody
/// looked at. The certificate in question is ICP-Brasil's `AC Raiz
/// Brasileira v7`, and it is the only place this will appear.
///
/// # Encoding
///
/// Both the key and the signature are raw in their BIT STRINGs, with no
/// encapsulating `OCTET STRING` -- like Ed25519 and Ed448 under RFC
/// 8410, and unlike GOST. The key is 66 octets and the signature 132,
/// which follows from `b = 528` in DOC-ICP-01.01.
///
/// Verification only.
#[cfg(feature = "ed521")]
#[cfg_attr(docsrs, doc(cfg(feature = "ed521")))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Ed521Verifier;

#[cfg(feature = "ed521")]
impl SignatureVerifier for Ed521Verifier {
    fn verify_signature(
        &self,
        algorithm: AlgorithmIdentifierRef<'_>,
        issuer_spki: SubjectPublicKeyInfoRef<'_>,
        message: &[u8],
        signature: &[u8],
    ) -> VerifyResult {
        if algorithm.oid != OID_ED521 {
            return Err(VerificationError::unsupported_algorithm());
        }
        // The AC Raiz v7 certificate carries no parameters at all, which
        // matches RFC 8410's treatment of the EdDSA algorithms. NULL is
        // tolerated as elsewhere in this file.
        if !algorithm.parameters.is_none_or(|p| p.is_null()) {
            return Err(VerificationError::unsupported_algorithm());
        }
        let key_bytes = issuer_spki
            .subject_public_key
            .as_bytes()
            .ok_or_else(VerificationError::malformed_key)?;
        let key: &[u8; 66] = key_bytes
            .try_into()
            .map_err(|_| VerificationError::malformed_key())?;
        let sig: &[u8; 132] = signature
            .try_into()
            .map_err(|_| VerificationError::invalid_signature())?;
        if crate::ed521::verify(key, sig, message) {
            Ok(())
        } else {
            Err(VerificationError::invalid_signature())
        }
    }
}

/// `id-ml-dsa-87` (FIPS 204) — 2.16.840.1.101.3.4.3.19, on NIST's CSOR
/// signature arc.
///
/// Identified from the certificates rather than from the registry: the
/// Caliptra chain names the algorithm in its own subjects
/// (`CN=Caliptra 2.0 MlDsa87 FMC Alias`), and the sizes agree -- a
/// 2592-octet key and a 4627-octet signature are exactly
/// `VerifyingKeySize::<MlDsa87>` and `SignatureSize::<MlDsa87>`, which
/// the `ml-dsa` crate asserts for itself.
#[cfg(feature = "ml-dsa")]
const OID_ML_DSA_87: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.3.19");

/// Verifies ML-DSA-87 signatures (FIPS 204).
///
/// # Scope
///
/// ML-DSA-87 only, which is what the Caliptra 2.x DICE chains in
/// `third_party/trust-stores/caliptra-dice/` use. ML-DSA-44 and -65 are
/// not wired up because nothing in any vendored corpus uses them; adding
/// either is a parameter-set constant and a dispatch arm.
///
/// # On by default
///
/// In the `rustcrypto` umbrella, for the same reason as
/// [`Sm2WithSm3Verifier`]: a current standard with a maintained
/// implementation is not a legacy primitive. Post-quantum signatures are
/// the newest thing here, not the oldest, and a silicon root of trust
/// shipping them is exactly the deployment a validator should not refuse
/// by default.
///
/// # The empty context string
///
/// FIPS 204 signs over a context string as well as the message, and
/// X.509 ML-DSA uses an **empty** one. `signature::Verifier::verify`
/// passes `&[]`, which is why it is used here rather than
/// `verify_with_context`: getting that wrong would fail every signature
/// while looking like a key or encoding problem.
///
/// Verification only.
#[cfg(feature = "ml-dsa")]
#[cfg_attr(docsrs, doc(cfg(feature = "ml-dsa")))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct MlDsa87Verifier;

#[cfg(feature = "ml-dsa")]
impl SignatureVerifier for MlDsa87Verifier {
    fn verify_signature(
        &self,
        algorithm: AlgorithmIdentifierRef<'_>,
        issuer_spki: SubjectPublicKeyInfoRef<'_>,
        message: &[u8],
        signature: &[u8],
    ) -> VerifyResult {
        use ml_dsa::signature::Verifier as _;
        use ml_dsa::{EncodedVerifyingKey, MlDsa87, Signature, VerifyingKey};

        if algorithm.oid != OID_ML_DSA_87 {
            return Err(VerificationError::unsupported_algorithm());
        }
        // FIPS 204 and the LAMPS certificate profile give ML-DSA no
        // AlgorithmIdentifier parameters at all. NULL is accepted as
        // elsewhere in this file, for producers that carry the RSA habit
        // across.
        if !algorithm.parameters.is_none_or(|p| p.is_null()) {
            return Err(VerificationError::unsupported_algorithm());
        }
        // The key is the raw FIPS 204 encoding in the BIT STRING, with no
        // encapsulating OCTET STRING -- unlike GOST, and like Ed25519.
        let key_bytes = issuer_spki
            .subject_public_key
            .as_bytes()
            .ok_or_else(VerificationError::malformed_key)?;
        let encoded = EncodedVerifyingKey::<MlDsa87>::try_from(key_bytes)
            .map_err(|_| VerificationError::malformed_key())?;
        let vk = VerifyingKey::<MlDsa87>::decode(&encoded);
        let sig = Signature::<MlDsa87>::try_from(signature)
            .map_err(|_| VerificationError::invalid_signature())?;
        vk.verify(message, &sig)
            .map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
    }
}

/// `GOST R 34.10-2012 with GOST R 34.11-2012 (256-bit)` —
/// 1.2.643.7.1.1.3.2.
#[cfg(feature = "gost")]
const OID_GOST_2012_256: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.643.7.1.1.3.2");
/// `GOST R 34.10-2001 with GOST R 34.11-94` — 1.2.643.2.2.3.
#[cfg(feature = "gost")]
const OID_GOST_2001: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.643.2.2.3");
/// `id-GostR3410-2001-CryptoPro-A-ParamSet` — 1.2.643.2.2.35.1.
///
/// The only GOST curve this crate implements, and the one all six
/// Russian national roots use. A key naming any other parameter set is
/// an unsupported key, not a malformed one.
#[cfg(feature = "gost")]
const OID_GOST_CRYPTOPRO_A: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.643.2.2.35.1");

/// Verifies GOST R 34.10 signatures (RFC 4491, RFC 7091).
///
/// # Scope
///
/// The `id-GostR3410-2001-CryptoPro-A-ParamSet` curve only, which is
/// what all six self-issued roots in
/// `third_party/trust-stores/ru-national/` use. Both digest generations
/// are handled: GOST R 34.11-2012 (Streebog-256) for the five 2012
/// certificates and GOST R 34.11-94 for the one 2001 certificate.
///
/// # Off by default, and not because of the algorithm
///
/// Unlike [`Sm2WithSm3Verifier`], this is outside the `rustcrypto`
/// umbrella. The reason is provenance, not strength: the signature
/// scheme is implemented in [`crate::gost_r3410`] rather than by a
/// maintained upstream, because no crate provides it and our OpenSSL has
/// no GOST to cross-check against. What validates it instead is RFC
/// 7091 §7's own test example plus these six certificates; see that
/// module. A caller who wants it should ask.
///
/// # The encodings
///
/// RFC 4491 specifies two byte orders that disagree, and both are
/// handled here rather than in [`crate::gost_r3410`], which takes
/// big-endian throughout so that its arithmetic can be checked against
/// the RFC vector with no encoding in the way:
///
/// - the key (§2.3.2) is a DER `OCTET STRING` *inside* the BIT STRING,
///   64 octets, **little-endian** `x` then **little-endian** `y`;
/// - the signature (§2.2.2) is 64 raw octets, **big-endian** `s` then
///   **big-endian** `r` -- not a `SEQUENCE`, and reversed from ECDSA.
///
/// The digest is reversed before it becomes the integer `alpha`. RFC
/// 7091 §5.3 defines the integer-to-vector mapping but not how a hash's
/// octets map onto it, and the RFC's example gives `e` without `M`, so
/// the convention was settled by measurement: unreversed verifies 0 of
/// 6 and reversed verifies 6 of 6.
///
/// Verification only.
#[cfg(feature = "gost")]
#[cfg_attr(docsrs, doc(cfg(feature = "gost")))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct GostR3410Verifier;

#[cfg(feature = "gost")]
impl SignatureVerifier for GostR3410Verifier {
    fn verify_signature(
        &self,
        algorithm: AlgorithmIdentifierRef<'_>,
        issuer_spki: SubjectPublicKeyInfoRef<'_>,
        message: &[u8],
        signature: &[u8],
    ) -> VerifyResult {
        use der::{Decode as _, Reader as _};
        use streebog::digest::Digest as _;

        let reversed_digest: [u8; 32] = if algorithm.oid == OID_GOST_2012_256 {
            streebog::Streebog256::digest(message).into()
        } else if algorithm.oid == OID_GOST_2001 {
            gost94::Gost94CryptoPro::digest(message).into()
        } else {
            return Err(VerificationError::unsupported_algorithm());
        };
        // Reversed to become `alpha`; see the type docs.
        let mut e = reversed_digest;
        e.reverse();

        // The key's parameter set, from
        // `GostR3410-2001-PublicKeyParameters ::= SEQUENCE {
        //     publicKeyParamSet OBJECT IDENTIFIER,
        //     digestParamSet    OBJECT IDENTIFIER, ... }`
        // (RFC 4491 §2.3.1). Only the first field is read: it names the
        // curve, and using a curve the key did not name would be
        // verifying against parameters nobody specified.
        let params = algorithm
            .parameters
            .or(issuer_spki.algorithm.parameters)
            .ok_or_else(VerificationError::unsupported_key)?;
        // `value()` is the SEQUENCE content, so the first element is
        // read directly rather than through another SEQUENCE layer --
        // the same approach `specified_curve` takes.
        let mut reader = der::SliceReader::new(params.value())
            .map_err(|_| VerificationError::malformed_key())?;
        let param_set = reader
            .decode::<ObjectIdentifier>()
            .map_err(|_| VerificationError::malformed_key())?;
        if param_set != OID_GOST_CRYPTOPRO_A {
            return Err(VerificationError::unsupported_key());
        }

        // The key: a DER OCTET STRING inside the BIT STRING, 64 octets,
        // each coordinate little-endian.
        let bits = issuer_spki
            .subject_public_key
            .as_bytes()
            .ok_or_else(VerificationError::malformed_key)?;
        let inner = <&der::asn1::OctetStringRef>::from_der(bits)
            .map_err(|_| VerificationError::malformed_key())?;
        let raw = inner.as_bytes();
        if raw.len() != 64 {
            return Err(VerificationError::malformed_key());
        }
        let mut qx = [0u8; 32];
        let mut qy = [0u8; 32];
        qx.copy_from_slice(&raw[..32]);
        qy.copy_from_slice(&raw[32..]);
        qx.reverse();
        qy.reverse();

        // The signature: 64 raw octets, `s` first, both big-endian.
        if signature.len() != 64 {
            return Err(VerificationError::invalid_signature());
        }
        let mut s = [0u8; 32];
        let mut r = [0u8; 32];
        s.copy_from_slice(&signature[..32]);
        r.copy_from_slice(&signature[32..]);

        if crate::gost_r3410::verify_cryptopro_a(&qx, &qy, &r, &s, &e) {
            Ok(())
        } else {
            Err(VerificationError::invalid_signature())
        }
    }
}

/// `SM2-with-SM3` — 1.2.156.10197.1.501, the Chinese national arc.
#[cfg(feature = "sm2")]
const OID_SM2_WITH_SM3: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.156.10197.1.501");

/// The GB/T 32918.2 default distinguishing identifier.
///
/// SM2 is not ECDSA, and this constant is the sharpest expression of
/// why. Before hashing the message, SM2 computes
///
/// ```text
/// Z = SM3(ENTLA || ID || a || b || Gx || Gy || Px || Py)
/// ```
///
/// and signs `SM3(Z || M)`. `ID` is the signer's *distinguishing
/// identifier*, so the digest depends on the curve parameters and on the
/// signer's own public key as well as on the message. No amount of
/// adding the sm2p256v1 curve to the ECDSA dispatch in this file would
/// reach that; the hash input itself differs.
///
/// GB/T 32918.2 §10 specifies this sixteen-octet ASCII default for
/// applications that do not define an identifier of their own, and RFC
/// 8998 §3.2 names the same value for TLS 1.3. Certificate signatures
/// use it, which is what makes verifying them possible without
/// out-of-band knowledge of who signed.
#[cfg(feature = "sm2")]
const SM2_DEFAULT_DISTID: &str = "1234567812345678";

/// Verifies SM2 signatures over SM3 (GB/T 32918).
///
/// # Scope
///
/// Nine self-issued roots in `third_party/trust-stores/cn-sm2/` are
/// signed this way: four from the China Financial Certification
/// Authority, two from UniTrust, two from GDCA and NRCAC's `ROOTCA`.
/// Before this verifier they reported
/// [`UnsupportedAlgorithm`](VerificationErrorKind::UnsupportedAlgorithm),
/// which was accurate and unhelpful.
///
/// The signer's distinguishing identifier is
/// `SM2_DEFAULT_DISTID`; see there for why SM2 needs one at all and
/// why a certificate's is not configurable.
///
/// # Not a legacy primitive
///
/// Unlike `RsaPkcs1v15Sha1Verifier` or
/// `RsaPkcs1v15Ripemd160Verifier`, this is in the `rustcrypto`
/// umbrella and on by default. Those two are named rather than linked
/// on purpose: they are gated on `rsa-sha1` and `rsa-ripemd160`, which
/// `rustcrypto` does not include, so under the default feature set the
/// links have no targets -- which is the whole point the sentence is
/// making. SM2 is a current national standard with
/// no published break, and the roots using it are in production.
///
/// Verification only.
#[cfg(feature = "sm2")]
#[cfg_attr(docsrs, doc(cfg(feature = "sm2")))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Sm2WithSm3Verifier;

#[cfg(feature = "sm2")]
impl SignatureVerifier for Sm2WithSm3Verifier {
    fn verify_signature(
        &self,
        algorithm: AlgorithmIdentifierRef<'_>,
        issuer_spki: SubjectPublicKeyInfoRef<'_>,
        message: &[u8],
        signature: &[u8],
    ) -> VerifyResult {
        use sm2::dsa::signature::Verifier as _;
        use sm2::dsa::{DerSignature, Signature, VerifyingKey};

        if algorithm.oid != OID_SM2_WITH_SM3 {
            return Err(VerificationError::unsupported_algorithm());
        }
        // NULL-or-absent, as elsewhere in this file.
        if !algorithm.parameters.is_none_or(|p| p.is_null()) {
            return Err(VerificationError::unsupported_algorithm());
        }
        // The key must be an EC key on sm2p256v1. The curve is resolved
        // through `ec_named_curve`, so an SM2 key carrying explicit
        // domain parameters is read like any other -- which matters
        // because the Chinese arc predates nobody's habits in
        // particular and both forms occur.
        let curve = ec_named_curve(&issuer_spki).ok_or_else(VerificationError::unsupported_key)?;
        if curve != OID_SM2P256V1 {
            return Err(VerificationError::unsupported_key());
        }
        let point = issuer_spki
            .subject_public_key
            .as_bytes()
            .ok_or_else(VerificationError::malformed_key)?;
        let vk = VerifyingKey::from_sec1_bytes(SM2_DEFAULT_DISTID, point)
            .map_err(|_| VerificationError::malformed_key())?;
        // Certificate signatures carry the DER `SEQUENCE { r, s }`, so it
        // is decoded and then converted to the fixed-width form the
        // verifier takes. `sm2` exposes no single `from_der`, and this
        // is the two-step its own docs use.
        let der_sig = DerSignature::try_from(signature)
            .map_err(|_| VerificationError::invalid_signature())?;
        let sig =
            Signature::try_from(der_sig).map_err(|_| VerificationError::invalid_signature())?;
        // `verify` hashes `Z || message` with SM3 internally, so the
        // TBSCertificate goes in whole rather than pre-hashed.
        vk.verify(message, &sig)
            .map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
    }
}

/// Verifies RSA PKCS#1 v1.5 signatures over RIPEMD-160.
/// **Legacy interop only.**
///
/// # Security
///
/// RIPEMD-160 is **not** in the same position as MD5 or SHA-1. No
/// practical collision attack against the full function has been
/// published; the best results are on reduced-round variants. Its
/// 160-bit output gives the same theoretical collision resistance as
/// SHA-1's, without SHA-1's realised break.
///
/// So this is off by default for a different reason than
/// `RsaPkcs1v15Sha1Verifier`: nothing modern emits it, not that the
/// primitive is broken. A caller enabling it is accepting an
/// unfashionable hash, not a forgeable one.
///
/// # Scope
///
/// Measured: nine self-issued roots in
/// `third_party/trust-stores/eu-eidas/` are signed `ripemd160WithRSA`,
/// the German qualified-signature CAs. They are roots in a bundle the EU
/// publishes and signs, and before this they could not be verified at
/// all -- which was this crate declining a primitive for being German
/// and obscure rather than for being weak.
///
/// The `DigestInfo` prefix comes from `ripemd`'s `AssociatedOid`
/// (1.3.36.3.2.1), so the PKCS#1 v1.5 encoding is built by the `rsa`
/// crate exactly as it is for SHA-1 and SHA-2.
///
/// Verification only.
#[cfg(feature = "rsa-ripemd160")]
#[cfg_attr(docsrs, doc(cfg(feature = "rsa-ripemd160")))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct RsaPkcs1v15Ripemd160Verifier;

#[cfg(feature = "rsa-ripemd160")]
impl SignatureVerifier for RsaPkcs1v15Ripemd160Verifier {
    fn verify_signature(
        &self,
        algorithm: AlgorithmIdentifierRef<'_>,
        issuer_spki: SubjectPublicKeyInfoRef<'_>,
        message: &[u8],
        signature: &[u8],
    ) -> VerifyResult {
        use rsa::pkcs1v15::{Signature, VerifyingKey};
        use rsa::signature::Verifier as _;

        if algorithm.oid != OID_RIPEMD160_WITH_RSA {
            return Err(VerificationError::unsupported_algorithm());
        }
        // NULL-or-absent, as RFC 4055 §5 requires for RSA.
        if !algorithm.parameters.is_none_or(|p| p.is_null()) {
            return Err(VerificationError::unsupported_algorithm());
        }
        let key = rsa_public_key(&issuer_spki, false)?;
        let sig =
            Signature::try_from(signature).map_err(|_| VerificationError::invalid_signature())?;
        VerifyingKey::<ripemd::Ripemd160>::new(key)
            .verify(message, &sig)
            .map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
    }
}

/// Verifies ECDSA signatures over SHA-1, on any curve this build has.
/// **Legacy interop only.**
///
/// # Security
///
/// See `RsaPkcs1v15Sha1Verifier`: the same practical collision attacks
/// apply and the same conclusion follows. A SHA-1-signed chain is
/// provenance, not proof.
///
/// Off by default, behind the `ecdsa-sha1` feature, outside the
/// `rustcrypto` umbrella. New deployments MUST NOT enable this.
///
/// # Scope
///
/// Every curve this build implements, which is the point of the rename:
/// this was `EcdsaP256Sha1Verifier`, P-256 only, on the reasoning that
/// "a deployment old enough to still sign with SHA-1 is overwhelmingly
/// on P-256 or RSA".
///
/// That reasoning was wrong about the one case anybody measured here.
/// `ecdsa-with-SHA1` names no curve, and Germany's oldest CSCA
/// generation -- `CN=csca-germany,serialNumber=001` in
/// `third_party/trust-stores/de-csca/` -- signs with SHA-1 over
/// **brainpoolP256r1**. A P-256-only verifier reported
/// [`UnsupportedKey`](VerificationErrorKind::UnsupportedKey) for it even
/// with the feature on, so the curve was "the problem" for a curve this
/// crate implements. A national root is not out of scope.
///
/// A curve the build does not implement still reports `UnsupportedKey`,
/// which remains the honest answer: it names this build's gap rather
/// than a defect in the certificate.
///
/// Verification only.
#[cfg(feature = "ecdsa-sha1")]
#[cfg_attr(docsrs, doc(cfg(feature = "ecdsa-sha1")))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct EcdsaSha1Verifier;

#[cfg(feature = "ecdsa-sha1")]
impl SignatureVerifier for EcdsaSha1Verifier {
    fn verify_signature(
        &self,
        algorithm: AlgorithmIdentifierRef<'_>,
        issuer_spki: SubjectPublicKeyInfoRef<'_>,
        message: &[u8],
        signature: &[u8],
    ) -> VerifyResult {
        if algorithm.oid != OID_ECDSA_WITH_SHA1 {
            return Err(VerificationError::unsupported_algorithm());
        }
        // NULL-or-absent, for the reason given in `verify_ecdsa`.
        if !algorithm.parameters.is_none_or(|p| p.is_null()) {
            return Err(VerificationError::unsupported_algorithm());
        }
        // The curve from either parameter form, so an explicit-parameter
        // key -- which every ICAO Doc 9303 CSCA carries -- resolves the
        // same way a `namedCurve` one does.
        let curve = ec_named_curve(&issuer_spki).ok_or_else(VerificationError::unsupported_key)?;
        match curve {
            #[cfg(feature = "p256")]
            OID_SECP256R1 => verify_ecdsa_sha1_p256(issuer_spki, message, signature),
            #[cfg(feature = "p384")]
            OID_SECP384R1 => verify_ecdsa_sha1_p384(issuer_spki, message, signature),
            #[cfg(feature = "p521")]
            OID_SECP521R1 => verify_ecdsa_sha1_p521(issuer_spki, message, signature),
            #[cfg(feature = "bp224")]
            OID_BRAINPOOL_P224R1 => verify_ecdsa_sha1_bp224(issuer_spki, message, signature),
            #[cfg(feature = "bp256")]
            OID_BRAINPOOL_P256R1 => verify_ecdsa_sha1_bp256(issuer_spki, message, signature),
            #[cfg(feature = "bp384")]
            OID_BRAINPOOL_P384R1 => verify_ecdsa_sha1_bp384(issuer_spki, message, signature),
            #[cfg(feature = "bp512")]
            OID_BRAINPOOL_P512R1 => verify_ecdsa_sha1_bp512(issuer_spki, message, signature),
            _ => Err(VerificationError::unsupported_key()),
        }
    }
}

/// RSASSA-PSS signature verifier (RFC 4055 §3.1).
///
/// Handles OID `id-RSASSA-PSS` (1.2.840.113549.1.1.10) with
/// `hashAlgorithm` SHA-256, SHA-384 or SHA-512, `maskGenAlgorithm` MGF1
/// over the same hash, any `saltLength`, and `trailerField` 1. The issuer
/// key may be `rsaEncryption` or `id-RSASSA-PSS`. Feature-gated behind
/// `rsa`.
#[cfg(feature = "rsa")]
#[cfg_attr(docsrs, doc(cfg(feature = "rsa")))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct RsaPssVerifier;

#[cfg(feature = "rsa")]
impl SignatureVerifier for RsaPssVerifier {
    fn verify_signature(
        &self,
        algorithm: AlgorithmIdentifierRef<'_>,
        issuer_spki: SubjectPublicKeyInfoRef<'_>,
        message: &[u8],
        signature: &[u8],
    ) -> VerifyResult {
        if algorithm.oid != OID_RSASSA_PSS {
            return Err(VerificationError::unsupported_algorithm());
        }
        verify_rsa_pss(algorithm, issuer_spki, message, signature)
    }
}

// ---------------------------------------------------------------------------
// Ed25519
// ---------------------------------------------------------------------------

/// Ed25519 signature verifier (RFC 8410, RFC 8032 §5.1.7).
///
/// Handles OID `id-Ed25519` (1.3.101.112) for both the signature algorithm
/// and the issuer key; RFC 8410 §3 requires absent parameters in both.
/// Verification uses `ed25519-dalek`'s `verify_strict`, which also rejects
/// small-order public keys and non-canonical signatures.
/// Feature-gated behind `ed25519`.
#[cfg(feature = "ed25519")]
#[cfg_attr(docsrs, doc(cfg(feature = "ed25519")))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Ed25519Verifier;

#[cfg(feature = "ed25519")]
impl SignatureVerifier for Ed25519Verifier {
    fn verify_signature(
        &self,
        algorithm: AlgorithmIdentifierRef<'_>,
        issuer_spki: SubjectPublicKeyInfoRef<'_>,
        message: &[u8],
        signature: &[u8],
    ) -> VerifyResult {
        if algorithm.oid != OID_ED25519 || algorithm.parameters.is_some() {
            return Err(VerificationError::unsupported_algorithm());
        }
        if issuer_spki.algorithm.oid != OID_ED25519 || issuer_spki.algorithm.parameters.is_some() {
            return Err(VerificationError::unsupported_key());
        }
        let key_bytes: &[u8; 32] = issuer_spki
            .subject_public_key
            .as_bytes()
            .and_then(|b| b.try_into().ok())
            .ok_or_else(VerificationError::malformed_key)?;
        let vk = ed25519_dalek::VerifyingKey::from_bytes(key_bytes)
            .map_err(|_| VerificationError::malformed_key())?;
        let sig = ed25519_dalek::Signature::from_slice(signature)
            .map_err(|_| VerificationError::invalid_signature())?;
        vk.verify_strict(message, &sig)
            .map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
    }
}

// ---------------------------------------------------------------------------
// DefaultVerifier
// ---------------------------------------------------------------------------

/// A [`SignatureVerifier`] covering every `RustCrypto` backend enabled at
/// build time.
///
/// This is the recommended out-of-the-box verifier. With all backend
/// features on (`rustcrypto`) it supports:
///
/// - ECDSA (`ecdsa-with-SHA256`, `-SHA384`, `-SHA512`) on P-256, P-384 and
///   P-521 issuer keys (features `p256`, `p384`, `p521`). The curve is taken
///   from the issuer's `SubjectPublicKeyInfo`, not from the signature OID.
/// - RSA PKCS#1 v1.5 with SHA-256, SHA-384 or SHA-512 (feature `rsa`).
/// - RSASSA-PSS as described on [`RsaPssVerifier`] (feature `rsa`).
/// - Ed25519 (feature `ed25519`).
///
/// Anything else returns an [`UnsupportedAlgorithm`] error, including
/// SHA-1 based algorithms.
///
/// [`UnsupportedAlgorithm`]: crate::VerificationErrorKind::UnsupportedAlgorithm
///
/// To support additional algorithms, implement [`SignatureVerifier`]
/// directly and fall back to `DefaultVerifier` for the rest.
#[cfg(any(
    feature = "p256",
    feature = "p384",
    feature = "p521",
    feature = "rsa",
    feature = "ed25519"
))]
#[cfg_attr(
    docsrs,
    doc(cfg(any(
        feature = "p256",
        feature = "p384",
        feature = "p521",
        feature = "rsa",
        feature = "ed25519"
    )))
)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct DefaultVerifier;

#[cfg(any(
    feature = "p256",
    feature = "p384",
    feature = "p521",
    feature = "rsa",
    feature = "ed25519"
))]
impl SignatureVerifier for DefaultVerifier {
    fn verify_signature(
        &self,
        algorithm: AlgorithmIdentifierRef<'_>,
        issuer_spki: SubjectPublicKeyInfoRef<'_>,
        message: &[u8],
        signature: &[u8],
    ) -> VerifyResult {
        let oid = algorithm.oid;
        if ecdsa_digest(oid).is_some() {
            let curves = Curves {
                p256: cfg!(feature = "p256"),
                p384: cfg!(feature = "p384"),
                p521: cfg!(feature = "p521"),
                bp224: cfg!(feature = "bp224"),
                bp256: cfg!(feature = "bp256"),
                bp384: cfg!(feature = "bp384"),
                bp512: cfg!(feature = "bp512"),
            };
            return verify_ecdsa(curves, algorithm, issuer_spki, message, signature);
        }
        #[cfg(feature = "rsa")]
        {
            let digest = match oid {
                OID_SHA256_WITH_RSA => Some(Sha2::Sha256),
                OID_SHA384_WITH_RSA => Some(Sha2::Sha384),
                OID_SHA512_WITH_RSA => Some(Sha2::Sha512),
                _ => None,
            };
            if let Some(digest) = digest {
                return verify_rsa_pkcs1v15(digest, algorithm, issuer_spki, message, signature);
            }
            if oid == OID_RSASSA_PSS {
                return verify_rsa_pss(algorithm, issuer_spki, message, signature);
            }
        }
        #[cfg(feature = "ed25519")]
        if oid == OID_ED25519 {
            return Ed25519Verifier.verify_signature(algorithm, issuer_spki, message, signature);
        }
        // Legacy SHA-1, last and only when asked for. Placed after every
        // modern algorithm so enabling it cannot change how anything else
        // is dispatched.
        #[cfg(feature = "rsa-sha1")]
        if oid == OID_SHA1_WITH_RSA || oid == OID_SHA1_WITH_RSA_OIW {
            return RsaPkcs1v15Sha1Verifier.verify_signature(
                algorithm,
                issuer_spki,
                message,
                signature,
            );
        }
        #[cfg(feature = "ed448")]
        if oid == OID_ED448 {
            return Ed448Verifier.verify_signature(algorithm, issuer_spki, message, signature);
        }
        #[cfg(feature = "ed521")]
        if oid == OID_ED521 {
            return Ed521Verifier.verify_signature(algorithm, issuer_spki, message, signature);
        }
        #[cfg(feature = "ml-dsa")]
        if oid == OID_ML_DSA_87 {
            return MlDsa87Verifier.verify_signature(algorithm, issuer_spki, message, signature);
        }
        #[cfg(feature = "gost")]
        if oid == OID_GOST_2012_256 || oid == OID_GOST_2001 {
            return GostR3410Verifier.verify_signature(algorithm, issuer_spki, message, signature);
        }
        #[cfg(feature = "sm2")]
        if oid == OID_SM2_WITH_SM3 {
            return Sm2WithSm3Verifier.verify_signature(algorithm, issuer_spki, message, signature);
        }
        #[cfg(feature = "rsa-ripemd160")]
        if oid == OID_RIPEMD160_WITH_RSA {
            return RsaPkcs1v15Ripemd160Verifier.verify_signature(
                algorithm,
                issuer_spki,
                message,
                signature,
            );
        }
        #[cfg(feature = "ecdsa-sha1")]
        if oid == OID_ECDSA_WITH_SHA1 {
            return EcdsaSha1Verifier.verify_signature(algorithm, issuer_spki, message, signature);
        }
        Err(VerificationError::unsupported_algorithm())
    }
}