Skip to main content

pkix_path/
verifiers.rs

1//! `RustCrypto` [`SignatureVerifier`] backends.
2//!
3//! Every verifier here takes the algorithm from two places, as RFC 5280
4//! §4.1.1.2 and RFC 5480 §2.1.1 require:
5//!
6//! - the **key type and curve** come from the issuer's
7//!   `SubjectPublicKeyInfo` (for ECDSA, its `namedCurve` parameter), and
8//! - the **signature scheme and digest** come from the subject's
9//!   `signatureAlgorithm`.
10//!
11//! So a P-384 issuer key that signs with `ecdsa-with-SHA256` (OpenSSL's
12//! default digest for EC keys) verifies, and an ECDSA signature whose
13//! algorithm OID names one digest cannot be checked against a curve chosen
14//! from that OID.
15
16// With only some backend features enabled, the OIDs and helpers of the
17// others are unused; gating each item separately would obscure the code.
18#![cfg_attr(
19    not(all(
20        feature = "p256",
21        feature = "p384",
22        feature = "p521",
23        feature = "rsa",
24        feature = "ed25519"
25    )),
26    allow(dead_code, unused_imports, unused_variables)
27)]
28
29use crate::SignatureVerifier;
30#[cfg(any(feature = "p256", feature = "p384", feature = "p521", feature = "rsa"))]
31use crate::Vec;
32use crate::{VerificationError, VerificationErrorKind};
33use der::asn1::ObjectIdentifier;
34use spki::{AlgorithmIdentifierRef, SubjectPublicKeyInfoRef};
35
36type VerifyResult = core::result::Result<(), VerificationError>;
37
38// ---------------------------------------------------------------------------
39// OIDs
40// ---------------------------------------------------------------------------
41
42/// `ecdsa-with-SHA256` (RFC 5758 §3.2): 1.2.840.10045.4.3.2.
43pub(crate) const OID_ECDSA_WITH_SHA256: ObjectIdentifier =
44    ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.2");
45/// `ecdsa-with-SHA384` (RFC 5758 §3.2): 1.2.840.10045.4.3.3.
46pub(crate) const OID_ECDSA_WITH_SHA384: ObjectIdentifier =
47    ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.3");
48/// `ecdsa-with-SHA512` (RFC 5758 §3.2): 1.2.840.10045.4.3.4.
49pub(crate) const OID_ECDSA_WITH_SHA512: ObjectIdentifier =
50    ObjectIdentifier::new_unwrap("1.2.840.10045.4.3.4");
51
52/// `id-ecPublicKey` (RFC 5480 §2.1.1): 1.2.840.10045.2.1.
53const OID_EC_PUBLIC_KEY: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.2.1");
54/// `secp256r1` / `prime256v1` (RFC 5480 §2.1.1.1).
55const OID_SECP256R1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7");
56/// `secp384r1` (RFC 5480 §2.1.1.1).
57const OID_SECP384R1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.132.0.34");
58/// `secp521r1` (RFC 5480 §2.1.1.1).
59const OID_SECP521R1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.132.0.35");
60
61/// `rsaEncryption` (RFC 3279 §2.3.1).
62pub(crate) const OID_RSA_ENCRYPTION: ObjectIdentifier =
63    ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1");
64/// `sha256WithRSAEncryption` (RFC 4055 §5).
65pub(crate) const OID_SHA256_WITH_RSA: ObjectIdentifier =
66    ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.11");
67/// `sha384WithRSAEncryption` (RFC 4055 §5).
68pub(crate) const OID_SHA384_WITH_RSA: ObjectIdentifier =
69    ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.12");
70/// `sha512WithRSAEncryption` (RFC 4055 §5).
71pub(crate) const OID_SHA512_WITH_RSA: ObjectIdentifier =
72    ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.13");
73/// `id-RSASSA-PSS` (RFC 4055 §3.1).
74pub(crate) const OID_RSASSA_PSS: ObjectIdentifier =
75    ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.10");
76/// `id-mgf1` (RFC 4055 §2.2).
77#[cfg(feature = "rsa")]
78const OID_MGF1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.8");
79/// `id-sha256` (RFC 4055 §2.1).
80#[cfg(feature = "rsa")]
81const OID_SHA256: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.1");
82/// `id-sha384` (RFC 4055 §2.1).
83#[cfg(feature = "rsa")]
84const OID_SHA384: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.2");
85/// `id-sha512` (RFC 4055 §2.1).
86#[cfg(feature = "rsa")]
87const OID_SHA512: ObjectIdentifier = ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.3");
88
89/// `id-Ed25519` (RFC 8410 §3): 1.3.101.112.
90pub(crate) const OID_ED25519: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.101.112");
91
92// ---------------------------------------------------------------------------
93// Digest selection
94// ---------------------------------------------------------------------------
95
96/// A SHA-2 digest named by a signature or hash algorithm OID.
97#[derive(Clone, Copy, Debug, PartialEq, Eq)]
98enum Sha2 {
99    Sha256,
100    Sha384,
101    Sha512,
102}
103
104/// Digest named by an `ecdsa-with-SHA*` signature OID, or `None`.
105fn ecdsa_digest(oid: ObjectIdentifier) -> Option<Sha2> {
106    match oid {
107        OID_ECDSA_WITH_SHA256 => Some(Sha2::Sha256),
108        OID_ECDSA_WITH_SHA384 => Some(Sha2::Sha384),
109        OID_ECDSA_WITH_SHA512 => Some(Sha2::Sha512),
110        _ => None,
111    }
112}
113
114#[cfg(any(feature = "p256", feature = "p384", feature = "p521", feature = "rsa"))]
115fn sha2_digest(alg: Sha2, message: &[u8]) -> Vec<u8> {
116    use sha2::Digest as _;
117    match alg {
118        Sha2::Sha256 => sha2::Sha256::digest(message).to_vec(),
119        Sha2::Sha384 => sha2::Sha384::digest(message).to_vec(),
120        Sha2::Sha512 => sha2::Sha512::digest(message).to_vec(),
121    }
122}
123
124// ---------------------------------------------------------------------------
125// ECDSA
126// ---------------------------------------------------------------------------
127
128/// Named curve of an `id-ecPublicKey` SPKI, or `None` for any other key.
129fn ec_named_curve(spki: &SubjectPublicKeyInfoRef<'_>) -> Option<ObjectIdentifier> {
130    if spki.algorithm.oid != OID_EC_PUBLIC_KEY {
131        return None;
132    }
133    spki.algorithm
134        .parameters?
135        .decode_as::<ObjectIdentifier>()
136        .ok()
137}
138
139/// Left-pads a digest shorter than the curve order with zero bytes.
140///
141/// SEC 1 v2 §4.1.4 step 5 converts the digest to an integer, so leading
142/// zero bytes do not change the value. The `ecdsa` crate rejects prehashes
143/// shorter than half the field size, which would otherwise refuse, for
144/// example, P-521 with `ecdsa-with-SHA256`.
145#[cfg(any(feature = "p256", feature = "p384", feature = "p521"))]
146fn pad_prehash(mut digest: Vec<u8>, field_len: usize) -> Vec<u8> {
147    if digest.len() < field_len {
148        let mut padded = vec![0u8; field_len - digest.len()];
149        padded.append(&mut digest);
150        padded
151    } else {
152        digest
153    }
154}
155
156macro_rules! ecdsa_curve_verify {
157    ($fn_name:ident, $feature:literal, $krate:ident, $field_len:expr) => {
158        #[cfg(feature = $feature)]
159        fn $fn_name(
160            spki: SubjectPublicKeyInfoRef<'_>,
161            digest: Sha2,
162            message: &[u8],
163            signature: &[u8],
164        ) -> VerifyResult {
165            use signature::hazmat::PrehashVerifier as _;
166            use $krate::ecdsa::{DerSignature, VerifyingKey};
167
168            let vk =
169                VerifyingKey::try_from(spki).map_err(|_| VerificationError::malformed_key())?;
170            let sig = DerSignature::try_from(signature)
171                .map_err(|_| VerificationError::invalid_signature())?;
172            let prehash = pad_prehash(sha2_digest(digest, message), $field_len);
173            vk.verify_prehash(&prehash, &sig).map_err(|e| {
174                VerificationError::with_source(VerificationErrorKind::InvalidSignature, e)
175            })
176        }
177    };
178}
179
180ecdsa_curve_verify!(verify_ecdsa_p256, "p256", p256, 32);
181ecdsa_curve_verify!(verify_ecdsa_p384, "p384", p384, 48);
182ecdsa_curve_verify!(verify_ecdsa_p521, "p521", p521, 66);
183
184/// Which curves an ECDSA verifier accepts.
185#[derive(Clone, Copy)]
186struct Curves {
187    p256: bool,
188    p384: bool,
189    p521: bool,
190}
191
192/// ECDSA dispatch: digest from `algorithm`, curve from `issuer_spki`.
193fn verify_ecdsa(
194    curves: Curves,
195    algorithm: AlgorithmIdentifierRef<'_>,
196    issuer_spki: SubjectPublicKeyInfoRef<'_>,
197    message: &[u8],
198    signature: &[u8],
199) -> VerifyResult {
200    let digest =
201        ecdsa_digest(algorithm.oid).ok_or_else(VerificationError::unsupported_algorithm)?;
202    // RFC 5758 §3.2: the parameters field MUST be absent.
203    if algorithm.parameters.is_some() {
204        return Err(VerificationError::unsupported_algorithm());
205    }
206    let curve = ec_named_curve(&issuer_spki).ok_or_else(VerificationError::unsupported_key)?;
207    match curve {
208        #[cfg(feature = "p256")]
209        OID_SECP256R1 if curves.p256 => verify_ecdsa_p256(issuer_spki, digest, message, signature),
210        #[cfg(feature = "p384")]
211        OID_SECP384R1 if curves.p384 => verify_ecdsa_p384(issuer_spki, digest, message, signature),
212        #[cfg(feature = "p521")]
213        OID_SECP521R1 if curves.p521 => verify_ecdsa_p521(issuer_spki, digest, message, signature),
214        _ => Err(VerificationError::unsupported_key()),
215    }
216}
217
218macro_rules! ecdsa_verifier {
219    ($(#[$doc:meta])* $name:ident, $feature:literal, $field:ident) => {
220        $(#[$doc])*
221        #[cfg(feature = $feature)]
222        #[cfg_attr(docsrs, doc(cfg(feature = $feature)))]
223        #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
224        pub struct $name;
225
226        #[cfg(feature = $feature)]
227        impl SignatureVerifier for $name {
228            fn verify_signature(
229                &self,
230                algorithm: AlgorithmIdentifierRef<'_>,
231                issuer_spki: SubjectPublicKeyInfoRef<'_>,
232                message: &[u8],
233                signature: &[u8],
234            ) -> VerifyResult {
235                let curves = Curves {
236                    p256: false,
237                    p384: false,
238                    p521: false,
239                };
240                let curves = Curves {
241                    $field: true,
242                    ..curves
243                };
244                verify_ecdsa(curves, algorithm, issuer_spki, message, signature)
245            }
246        }
247    };
248}
249
250ecdsa_verifier!(
251    /// ECDSA verifier for P-256 (`secp256r1`) issuer keys.
252    ///
253    /// Accepts `ecdsa-with-SHA256`, `ecdsa-with-SHA384` and
254    /// `ecdsa-with-SHA512` (RFC 5758 §3.2; the `parameters` field must be
255    /// absent). Rejects issuer keys on any other curve.
256    /// Feature-gated behind `p256`.
257    EcdsaP256Verifier,
258    "p256",
259    p256
260);
261
262ecdsa_verifier!(
263    /// ECDSA verifier for P-384 (`secp384r1`) issuer keys.
264    ///
265    /// Accepts `ecdsa-with-SHA256`, `ecdsa-with-SHA384` and
266    /// `ecdsa-with-SHA512` (RFC 5758 §3.2; the `parameters` field must be
267    /// absent). Rejects issuer keys on any other curve.
268    /// Feature-gated behind `p384`.
269    EcdsaP384Verifier,
270    "p384",
271    p384
272);
273
274ecdsa_verifier!(
275    /// ECDSA verifier for P-521 (`secp521r1`) issuer keys.
276    ///
277    /// Accepts `ecdsa-with-SHA256`, `ecdsa-with-SHA384` and
278    /// `ecdsa-with-SHA512` (RFC 5758 §3.2; the `parameters` field must be
279    /// absent). Rejects issuer keys on any other curve.
280    /// Feature-gated behind `p521`.
281    EcdsaP521Verifier,
282    "p521",
283    p521
284);
285
286// ---------------------------------------------------------------------------
287// RSA
288// ---------------------------------------------------------------------------
289
290/// Decodes an RSA public key from an SPKI whose algorithm is `rsaEncryption`
291/// (parameters NULL or absent, RFC 3279 §2.3.1) or, when `allow_pss_key` is
292/// set, `id-RSASSA-PSS` (RFC 4055 §1.2).
293///
294/// Moduli from 1024 to 8192 bits are accepted (the `rsa` crate's limits).
295#[cfg(feature = "rsa")]
296fn rsa_public_key(
297    spki: &SubjectPublicKeyInfoRef<'_>,
298    allow_pss_key: bool,
299) -> core::result::Result<rsa::PublicKey, VerificationError> {
300    use rsa::pkcs1::DecodeRsaPublicKey as _;
301
302    let oid_ok = spki.algorithm.oid == OID_RSA_ENCRYPTION
303        && spki.algorithm.parameters.is_none_or(|p| p.is_null());
304    let pss_ok = allow_pss_key && spki.algorithm.oid == OID_RSASSA_PSS;
305    if !(oid_ok || pss_ok) {
306        return Err(VerificationError::unsupported_key());
307    }
308    let key_bytes = spki
309        .subject_public_key
310        .as_bytes()
311        .ok_or_else(VerificationError::malformed_key)?;
312    rsa::PublicKey::from_pkcs1_der(key_bytes)
313        .map_err(|e| VerificationError::with_source(VerificationErrorKind::MalformedKey, e))
314}
315
316/// RSA PKCS#1 v1.5 verification with the given digest.
317#[cfg(feature = "rsa")]
318fn verify_rsa_pkcs1v15(
319    digest: Sha2,
320    algorithm: AlgorithmIdentifierRef<'_>,
321    issuer_spki: SubjectPublicKeyInfoRef<'_>,
322    message: &[u8],
323    signature: &[u8],
324) -> VerifyResult {
325    use rsa::pkcs1v15::{Signature, VerifyingKey};
326    use rsa::signature::Verifier as _;
327
328    // RFC 4055 §5: parameters MUST be NULL; absent is accepted for
329    // interoperability, matching the issuer-key decoding above.
330    if !algorithm.parameters.is_none_or(|p| p.is_null()) {
331        return Err(VerificationError::unsupported_algorithm());
332    }
333    let key = rsa_public_key(&issuer_spki, false)?;
334    let sig = Signature::try_from(signature).map_err(|_| VerificationError::invalid_signature())?;
335    let result = match digest {
336        Sha2::Sha256 => VerifyingKey::<sha2::Sha256>::new(key).verify(message, &sig),
337        Sha2::Sha384 => VerifyingKey::<sha2::Sha384>::new(key).verify(message, &sig),
338        Sha2::Sha512 => VerifyingKey::<sha2::Sha512>::new(key).verify(message, &sig),
339    };
340    result.map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
341}
342
343/// Hash named by an RFC 4055 `HashAlgorithm` identifier (parameters NULL or
344/// absent, RFC 4055 §2.1).
345#[cfg(feature = "rsa")]
346fn rfc4055_hash(alg: &spki::AlgorithmIdentifierOwned) -> Option<Sha2> {
347    if !alg.parameters.as_ref().is_none_or(der::Any::is_null) {
348        return None;
349    }
350    match alg.oid {
351        OID_SHA256 => Some(Sha2::Sha256),
352        OID_SHA384 => Some(Sha2::Sha384),
353        OID_SHA512 => Some(Sha2::Sha512),
354        _ => None,
355    }
356}
357
358/// RSASSA-PSS verification (RFC 4055 §3.1, RFC 8017 §8.1.2).
359///
360/// Supported parameters: `hashAlgorithm` SHA-256, SHA-384 or SHA-512;
361/// `maskGenAlgorithm` MGF1 over the same hash; any `saltLength`;
362/// `trailerField` 1. The default parameters (SHA-1) are rejected.
363#[cfg(feature = "rsa")]
364fn verify_rsa_pss(
365    algorithm: AlgorithmIdentifierRef<'_>,
366    issuer_spki: SubjectPublicKeyInfoRef<'_>,
367    message: &[u8],
368    signature: &[u8],
369) -> VerifyResult {
370    use der::{Decode as _, Encode as _};
371    use rsa::pkcs1::{RsaPssParamsOwned, TrailerField};
372    use rsa::pss::{Signature, VerifyingKey};
373    use rsa::signature::hazmat::PrehashVerifier as _;
374
375    let params_der = algorithm
376        .parameters
377        .ok_or_else(VerificationError::unsupported_algorithm)?
378        .to_der()
379        .map_err(|_| VerificationError::unsupported_algorithm())?;
380    let params = RsaPssParamsOwned::from_der(&params_der)
381        .map_err(|_| VerificationError::unsupported_algorithm())?;
382    let hash = rfc4055_hash(&params.hash).ok_or_else(VerificationError::unsupported_algorithm)?;
383    if params.mask_gen.oid != OID_MGF1 {
384        return Err(VerificationError::unsupported_algorithm());
385    }
386    let mgf_hash = params
387        .mask_gen
388        .parameters
389        .as_ref()
390        .and_then(rfc4055_hash)
391        .ok_or_else(VerificationError::unsupported_algorithm)?;
392    if mgf_hash != hash || params.trailer_field != TrailerField::BC {
393        return Err(VerificationError::unsupported_algorithm());
394    }
395    // RFC 4055 §3.1: when the issuer key is an id-RSASSA-PSS key with
396    // parameters, the signature must use the same hash and MGF and a salt
397    // at least as long. We check the hash and MGF; a key restricted that
398    // way still verifies only signatures that match its own parameters.
399    if issuer_spki.algorithm.oid == OID_RSASSA_PSS {
400        if let Some(key_params) = issuer_spki.algorithm.parameters {
401            let key_params_der = key_params
402                .to_der()
403                .map_err(|_| VerificationError::malformed_key())?;
404            let key_params = RsaPssParamsOwned::from_der(&key_params_der)
405                .map_err(|_| VerificationError::malformed_key())?;
406            let key_hash =
407                rfc4055_hash(&key_params.hash).ok_or_else(VerificationError::unsupported_key)?;
408            if key_hash != hash || params.salt_len < key_params.salt_len {
409                return Err(VerificationError::unsupported_key());
410            }
411        }
412    }
413    let key = rsa_public_key(&issuer_spki, true)?;
414    let sig = Signature::try_from(signature).map_err(|_| VerificationError::invalid_signature())?;
415    let salt_len = usize::from(params.salt_len);
416    let prehash = sha2_digest(hash, message);
417    let result = match hash {
418        Sha2::Sha256 => VerifyingKey::<sha2::Sha256>::new_with_salt_len(key, salt_len)
419            .verify_prehash(&prehash, &sig),
420        Sha2::Sha384 => VerifyingKey::<sha2::Sha384>::new_with_salt_len(key, salt_len)
421            .verify_prehash(&prehash, &sig),
422        Sha2::Sha512 => VerifyingKey::<sha2::Sha512>::new_with_salt_len(key, salt_len)
423            .verify_prehash(&prehash, &sig),
424    };
425    result.map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
426}
427
428macro_rules! rsa_pkcs1v15_verifier {
429    ($(#[$doc:meta])* $name:ident, $oid:ident, $digest:ident) => {
430        $(#[$doc])*
431        #[cfg(feature = "rsa")]
432        #[cfg_attr(docsrs, doc(cfg(feature = "rsa")))]
433        #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
434        pub struct $name;
435
436        #[cfg(feature = "rsa")]
437        impl SignatureVerifier for $name {
438            fn verify_signature(
439                &self,
440                algorithm: AlgorithmIdentifierRef<'_>,
441                issuer_spki: SubjectPublicKeyInfoRef<'_>,
442                message: &[u8],
443                signature: &[u8],
444            ) -> VerifyResult {
445                if algorithm.oid != $oid {
446                    return Err(VerificationError::unsupported_algorithm());
447                }
448                verify_rsa_pkcs1v15(Sha2::$digest, algorithm, issuer_spki, message, signature)
449            }
450        }
451    };
452}
453
454rsa_pkcs1v15_verifier!(
455    /// RSA with PKCS#1 v1.5 padding and SHA-256 signature verifier.
456    ///
457    /// Handles OID `sha256WithRSAEncryption` (1.2.840.113549.1.1.11).
458    /// Feature-gated behind `rsa`.
459    RsaPkcs1v15Sha256Verifier,
460    OID_SHA256_WITH_RSA,
461    Sha256
462);
463
464rsa_pkcs1v15_verifier!(
465    /// RSA with PKCS#1 v1.5 padding and SHA-384 signature verifier.
466    ///
467    /// Handles OID `sha384WithRSAEncryption` (1.2.840.113549.1.1.12).
468    /// Feature-gated behind `rsa`.
469    RsaPkcs1v15Sha384Verifier,
470    OID_SHA384_WITH_RSA,
471    Sha384
472);
473
474rsa_pkcs1v15_verifier!(
475    /// RSA with PKCS#1 v1.5 padding and SHA-512 signature verifier.
476    ///
477    /// Handles OID `sha512WithRSAEncryption` (1.2.840.113549.1.1.13).
478    /// Feature-gated behind `rsa`.
479    RsaPkcs1v15Sha512Verifier,
480    OID_SHA512_WITH_RSA,
481    Sha512
482);
483
484/// RSASSA-PSS signature verifier (RFC 4055 §3.1).
485///
486/// Handles OID `id-RSASSA-PSS` (1.2.840.113549.1.1.10) with
487/// `hashAlgorithm` SHA-256, SHA-384 or SHA-512, `maskGenAlgorithm` MGF1
488/// over the same hash, any `saltLength`, and `trailerField` 1. The issuer
489/// key may be `rsaEncryption` or `id-RSASSA-PSS`. Feature-gated behind
490/// `rsa`.
491#[cfg(feature = "rsa")]
492#[cfg_attr(docsrs, doc(cfg(feature = "rsa")))]
493#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
494pub struct RsaPssVerifier;
495
496#[cfg(feature = "rsa")]
497impl SignatureVerifier for RsaPssVerifier {
498    fn verify_signature(
499        &self,
500        algorithm: AlgorithmIdentifierRef<'_>,
501        issuer_spki: SubjectPublicKeyInfoRef<'_>,
502        message: &[u8],
503        signature: &[u8],
504    ) -> VerifyResult {
505        if algorithm.oid != OID_RSASSA_PSS {
506            return Err(VerificationError::unsupported_algorithm());
507        }
508        verify_rsa_pss(algorithm, issuer_spki, message, signature)
509    }
510}
511
512// ---------------------------------------------------------------------------
513// Ed25519
514// ---------------------------------------------------------------------------
515
516/// Ed25519 signature verifier (RFC 8410, RFC 8032 §5.1.7).
517///
518/// Handles OID `id-Ed25519` (1.3.101.112) for both the signature algorithm
519/// and the issuer key; RFC 8410 §3 requires absent parameters in both.
520/// Verification uses `ed25519-dalek`'s `verify_strict`, which also rejects
521/// small-order public keys and non-canonical signatures.
522/// Feature-gated behind `ed25519`.
523#[cfg(feature = "ed25519")]
524#[cfg_attr(docsrs, doc(cfg(feature = "ed25519")))]
525#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
526pub struct Ed25519Verifier;
527
528#[cfg(feature = "ed25519")]
529impl SignatureVerifier for Ed25519Verifier {
530    fn verify_signature(
531        &self,
532        algorithm: AlgorithmIdentifierRef<'_>,
533        issuer_spki: SubjectPublicKeyInfoRef<'_>,
534        message: &[u8],
535        signature: &[u8],
536    ) -> VerifyResult {
537        if algorithm.oid != OID_ED25519 || algorithm.parameters.is_some() {
538            return Err(VerificationError::unsupported_algorithm());
539        }
540        if issuer_spki.algorithm.oid != OID_ED25519 || issuer_spki.algorithm.parameters.is_some() {
541            return Err(VerificationError::unsupported_key());
542        }
543        let key_bytes: &[u8; 32] = issuer_spki
544            .subject_public_key
545            .as_bytes()
546            .and_then(|b| b.try_into().ok())
547            .ok_or_else(VerificationError::malformed_key)?;
548        let vk = ed25519_dalek::VerifyingKey::from_bytes(key_bytes)
549            .map_err(|_| VerificationError::malformed_key())?;
550        let sig = ed25519_dalek::Signature::from_slice(signature)
551            .map_err(|_| VerificationError::invalid_signature())?;
552        vk.verify_strict(message, &sig)
553            .map_err(|e| VerificationError::with_source(VerificationErrorKind::InvalidSignature, e))
554    }
555}
556
557// ---------------------------------------------------------------------------
558// DefaultVerifier
559// ---------------------------------------------------------------------------
560
561/// A [`SignatureVerifier`] covering every `RustCrypto` backend enabled at
562/// build time.
563///
564/// This is the recommended out-of-the-box verifier. With all backend
565/// features on (`rustcrypto`) it supports:
566///
567/// - ECDSA (`ecdsa-with-SHA256`, `-SHA384`, `-SHA512`) on P-256, P-384 and
568///   P-521 issuer keys (features `p256`, `p384`, `p521`). The curve is taken
569///   from the issuer's `SubjectPublicKeyInfo`, not from the signature OID.
570/// - RSA PKCS#1 v1.5 with SHA-256, SHA-384 or SHA-512 (feature `rsa`).
571/// - RSASSA-PSS as described on [`RsaPssVerifier`] (feature `rsa`).
572/// - Ed25519 (feature `ed25519`).
573///
574/// Anything else returns an [`UnsupportedAlgorithm`] error, including
575/// SHA-1 based algorithms.
576///
577/// [`UnsupportedAlgorithm`]: crate::VerificationErrorKind::UnsupportedAlgorithm
578///
579/// To support additional algorithms, implement [`SignatureVerifier`]
580/// directly and fall back to `DefaultVerifier` for the rest.
581#[cfg(any(
582    feature = "p256",
583    feature = "p384",
584    feature = "p521",
585    feature = "rsa",
586    feature = "ed25519"
587))]
588#[cfg_attr(
589    docsrs,
590    doc(cfg(any(
591        feature = "p256",
592        feature = "p384",
593        feature = "p521",
594        feature = "rsa",
595        feature = "ed25519"
596    )))
597)]
598#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
599pub struct DefaultVerifier;
600
601#[cfg(any(
602    feature = "p256",
603    feature = "p384",
604    feature = "p521",
605    feature = "rsa",
606    feature = "ed25519"
607))]
608impl SignatureVerifier for DefaultVerifier {
609    fn verify_signature(
610        &self,
611        algorithm: AlgorithmIdentifierRef<'_>,
612        issuer_spki: SubjectPublicKeyInfoRef<'_>,
613        message: &[u8],
614        signature: &[u8],
615    ) -> VerifyResult {
616        let oid = algorithm.oid;
617        if ecdsa_digest(oid).is_some() {
618            let curves = Curves {
619                p256: cfg!(feature = "p256"),
620                p384: cfg!(feature = "p384"),
621                p521: cfg!(feature = "p521"),
622            };
623            return verify_ecdsa(curves, algorithm, issuer_spki, message, signature);
624        }
625        #[cfg(feature = "rsa")]
626        {
627            let digest = match oid {
628                OID_SHA256_WITH_RSA => Some(Sha2::Sha256),
629                OID_SHA384_WITH_RSA => Some(Sha2::Sha384),
630                OID_SHA512_WITH_RSA => Some(Sha2::Sha512),
631                _ => None,
632            };
633            if let Some(digest) = digest {
634                return verify_rsa_pkcs1v15(digest, algorithm, issuer_spki, message, signature);
635            }
636            if oid == OID_RSASSA_PSS {
637                return verify_rsa_pss(algorithm, issuer_spki, message, signature);
638            }
639        }
640        #[cfg(feature = "ed25519")]
641        if oid == OID_ED25519 {
642            return Ed25519Verifier.verify_signature(algorithm, issuer_spki, message, signature);
643        }
644        Err(VerificationError::unsupported_algorithm())
645    }
646}