Skip to main content

rsa/
pss.rs

1//! Support for the [Probabilistic Signature Scheme] (PSS) a.k.a. RSASSA-PSS.
2//!
3//! Designed by Mihir Bellare and Phillip Rogaway. Specified in [RFC8017 § 8.1].
4//!
5//! # Usage
6//!
7//! See [code example in the toplevel rustdoc](../index.html#pss-signatures).
8//!
9//! [Probabilistic Signature Scheme]: https://en.wikipedia.org/wiki/Probabilistic_signature_scheme
10//! [RFC8017 § 8.1]: https://datatracker.ietf.org/doc/html/rfc8017#section-8.1
11
12mod signature;
13mod signing_key;
14mod verifying_key;
15
16pub use self::{signature::Signature, signing_key::SigningKey, verifying_key::VerifyingKey};
17
18use alloc::vec::Vec;
19use core::fmt::{self, Debug};
20
21use digest::{Digest, FixedOutputReset};
22use rand_core::TryCryptoRng;
23
24use crate::algorithms::pad::{i2osp, os2ip};
25use crate::algorithms::pss::*;
26use crate::algorithms::rsa::{rsa_decrypt_and_check, rsa_encrypt};
27use crate::errors::{Error, Result};
28use crate::traits::PublicKeyParts;
29use crate::traits::SignatureScheme;
30use crate::{PrivateKey, PublicKey};
31
32#[cfg(feature = "getrandom")]
33use crypto_common::getrandom::SysRng;
34
35impl PublicKey {
36    /// Verify a PSS signature after hashing `msg` with `D`.
37    ///
38    /// Requires a salt of `D`'s output size. For other salt lengths or automatic
39    /// salt-length detection, use [`VerifyingKey`].
40    ///
41    /// # Errors
42    /// Returns an error if the signature is invalid, including an incorrect salt length.
43    pub fn pss_verify<D>(&self, msg: &[u8], sig: &[u8]) -> Result<()>
44    where
45        D: Digest + FixedOutputReset,
46    {
47        self.pss_verify_prehash::<D>(&D::digest(msg), sig)
48    }
49
50    /// Verify a PSS signature over a message hash computed using `D`.
51    ///
52    /// The hash is verified directly, without hashing it again. Requires a salt of
53    /// `D`'s output size. For other salt lengths or automatic salt-length detection,
54    /// use [`VerifyingKey`].
55    ///
56    /// # Errors
57    /// Returns an error if the hash has the wrong length or the signature is invalid,
58    /// including an incorrect salt length.
59    pub fn pss_verify_prehash<D>(&self, hash: &[u8], sig: &[u8]) -> Result<()>
60    where
61        D: Digest + FixedOutputReset,
62    {
63        verify_digest::<D>(self, hash, sig, Some(<D as Digest>::output_size()))
64    }
65}
66
67impl PrivateKey {
68    /// Sign `msg` using PSS after hashing it with `D`.
69    ///
70    /// Uses the operating system RNG for the salt and blinding. The salt length is
71    /// `D`'s output size. For other salt lengths, use [`SigningKey`].
72    ///
73    /// # Errors
74    /// Returns an error if the key is too small for `D` or the private operation fails,
75    /// including RNG failures.
76    #[cfg(feature = "getrandom")]
77    pub fn pss_sign<D>(&self, msg: &[u8]) -> Result<Vec<u8>>
78    where
79        D: Digest + FixedOutputReset,
80    {
81        self.pss_sign_with_rng::<D, _>(&mut SysRng, msg)
82    }
83
84    /// Sign a message hash computed using `D` with PSS, without hashing it again.
85    ///
86    /// Uses the operating system RNG for the salt and blinding. The salt length is
87    /// `D`'s output size. For other salt lengths, use [`SigningKey`].
88    ///
89    /// # Errors
90    /// Returns [`Error::InputNotHashed`] if `hash` has the wrong length, or an error
91    /// if the key is too small for `D` or the private operation fails, including RNG failures.
92    #[cfg(feature = "getrandom")]
93    pub fn pss_sign_prehash<D>(&self, hash: &[u8]) -> Result<Vec<u8>>
94    where
95        D: Digest + FixedOutputReset,
96    {
97        self.pss_sign_prehash_with_rng::<D, _>(&mut SysRng, hash)
98    }
99
100    /// Sign `msg` using PSS after hashing it with `D`.
101    ///
102    /// Uses the provided RNG for the salt and blinding. The salt length is `D`'s
103    /// output size. For other salt lengths, use [`SigningKey`].
104    ///
105    /// # Errors
106    /// Returns an error if the key is too small for `D` or the private operation fails,
107    /// including RNG failures.
108    pub fn pss_sign_with_rng<D, R>(&self, rng: &mut R, msg: &[u8]) -> Result<Vec<u8>>
109    where
110        D: Digest + FixedOutputReset,
111        R: TryCryptoRng + ?Sized,
112    {
113        self.pss_sign_prehash_with_rng::<D, _>(rng, &D::digest(msg))
114    }
115
116    /// Sign a message hash computed using `D` with PSS, without hashing it again.
117    ///
118    /// Uses the provided RNG for the salt and blinding. The salt length is `D`'s
119    /// output size. For other salt lengths, use [`SigningKey`].
120    ///
121    /// # Errors
122    /// Returns [`Error::InputNotHashed`] if `hash` has the wrong length, or an error
123    /// if the key is too small for `D` or the private operation fails, including RNG failures.
124    pub fn pss_sign_prehash_with_rng<D, R>(&self, rng: &mut R, hash: &[u8]) -> Result<Vec<u8>>
125    where
126        D: Digest + FixedOutputReset,
127        R: TryCryptoRng + ?Sized,
128    {
129        if hash.len() != <D as Digest>::output_size() {
130            return Err(Error::InputNotHashed);
131        }
132
133        sign_digest::<_, D>(rng, true, self, hash, <D as Digest>::output_size())
134    }
135}
136
137/// DEPRECATED: type alias for legacy blinded signing key. Blinding is now applied automatically
138/// when available.
139#[deprecated(
140    since = "0.10.0",
141    note = "use `SigningKey` which is blinded automatically"
142)]
143pub type BlindedSigningKey<D> = SigningKey<D>;
144
145#[cfg(feature = "encoding")]
146use {
147    crate::encoding::ID_RSASSA_PSS,
148    const_oid::AssociatedOid,
149    pkcs1::RsaPssParams,
150    spki::{
151        AlgorithmIdentifierOwned,
152        der::{Any, ErrorKind},
153    },
154};
155
156/// Digital signatures using PSS padding.
157pub struct Pss<D> {
158    /// Enable RSA base blinding for the private operation (enabled by default).
159    /// This does not change the RSASSA-PSS signature format.
160    pub blinded: bool,
161
162    /// Digest type to use.
163    pub digest: D,
164
165    /// Salt length.
166    /// Required for signing, optional for verifying.
167    pub salt_len: Option<usize>,
168}
169
170impl<D> Default for Pss<D>
171where
172    D: Digest,
173{
174    fn default() -> Self {
175        Self::new()
176    }
177}
178
179impl<D> Pss<D>
180where
181    D: Digest,
182{
183    /// New PSS padding for the given digest.
184    /// Digest output size is used as a salt length.
185    #[must_use]
186    pub fn new() -> Self {
187        Self::new_with_salt(<D as Digest>::output_size())
188    }
189
190    /// New PSS padding for the given digest with a salt value of the given length.
191    #[must_use]
192    pub fn new_with_salt(len: usize) -> Self {
193        Self {
194            blinded: true,
195            digest: D::new(),
196            salt_len: Some(len),
197        }
198    }
199
200    /// New PSS padding with RSA base blinding for the given digest.
201    /// Digest output size is used as a salt length.
202    #[must_use]
203    pub fn new_blinded() -> Self {
204        Self::new_blinded_with_salt(<D as Digest>::output_size())
205    }
206
207    /// New PSS padding with RSA base blinding for the given digest
208    /// with a salt value of the given length.
209    #[must_use]
210    pub fn new_blinded_with_salt(len: usize) -> Self {
211        Self {
212            blinded: true,
213            digest: D::new(),
214            salt_len: Some(len),
215        }
216    }
217}
218
219impl<D> SignatureScheme for Pss<D>
220where
221    D: Digest + FixedOutputReset,
222{
223    #[allow(clippy::unwrap_in_result, reason = "TODO")]
224    fn sign<Rng: TryCryptoRng + ?Sized>(
225        mut self,
226        rng: Option<&mut Rng>,
227        priv_key: &PrivateKey,
228        hashed: &[u8],
229    ) -> Result<Vec<u8>> {
230        sign(
231            rng.ok_or(Error::InvalidPaddingScheme)?,
232            self.blinded,
233            priv_key,
234            hashed,
235            self.salt_len.expect("salt_len to be Some"),
236            &mut self.digest,
237        )
238    }
239
240    fn verify(mut self, pub_key: &PublicKey, hashed: &[u8], sig: &[u8]) -> Result<()> {
241        verify(pub_key, hashed, sig, &mut self.digest, self.salt_len)
242    }
243}
244
245impl<D> Debug for Pss<D> {
246    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
247        f.debug_struct("PSS")
248            .field("blinded", &self.blinded)
249            .field("digest", &"...")
250            .field("salt_len", &self.salt_len)
251            .finish()
252    }
253}
254
255pub(crate) fn verify<D>(
256    pub_key: &PublicKey,
257    hashed: &[u8],
258    sig: &[u8],
259    digest: &mut D,
260    salt_len: Option<usize>,
261) -> Result<()>
262where
263    D: Digest + FixedOutputReset,
264{
265    let mut em = decode_signature(pub_key, sig)?;
266    let em_bits = pub_key.n().bit_width() as usize - 1;
267    emsa_pss_verify(hashed, &mut em, salt_len, digest, em_bits)
268}
269
270pub(crate) fn verify_digest<D>(
271    pub_key: &PublicKey,
272    hashed: &[u8],
273    sig: &[u8],
274    salt_len: Option<usize>,
275) -> Result<()>
276where
277    D: Digest + FixedOutputReset,
278{
279    let mut em = decode_signature(pub_key, sig)?;
280    let em_bits = pub_key.n().bit_width() as usize - 1;
281    emsa_pss_verify_digest::<D>(hashed, &mut em, salt_len, em_bits)
282}
283
284/// Performs the length, RSAVP1, and I2OSP steps of RFC8017 §8.1.2.
285fn decode_signature(pub_key: &PublicKey, signature: &[u8]) -> Result<Vec<u8>> {
286    // Step 1: `S` must be exactly `k` octets, independently of integer storage precision.
287    if signature.len() != pub_key.size() {
288        return Err(Error::Verification);
289    }
290
291    // Steps 2a and 2b: `s = OS2IP(S), m = RSAVP1((n, e), s)`.
292    let s = os2ip(signature, pub_key.n_bits_precision()).map_err(|_| Error::Verification)?;
293    if s >= *pub_key.n().as_ref() {
294        return Err(Error::Verification);
295    }
296    let m = rsa_encrypt(pub_key, &s)?;
297
298    // Step 2c: EM has `emLen` octets, which can be `k - 1`.
299    //
300    // Check the public representative's width before calling infallible I2OSP; discarding a nonzero
301    // leading octet is invalid.
302    let em_bits = pub_key.n().bit_width() as usize - 1;
303    let em_len = em_bits.div_ceil(8);
304    if m.bit_width() as usize > 8 * em_len {
305        return Err(Error::Verification);
306    }
307    Ok(i2osp(m, em_len))
308}
309
310/// SignPSS calculates the signature of hashed using RSASSA-PSS.
311///
312/// Note that hashed must be the result of hashing the input message using the
313/// given hash function. The opts argument may be nil, in which case sensible
314/// defaults are used.
315pub(crate) fn sign<T, D>(
316    rng: &mut T,
317    blind: bool,
318    priv_key: &PrivateKey,
319    hashed: &[u8],
320    salt_len: usize,
321    digest: &mut D,
322) -> Result<Vec<u8>>
323where
324    T: TryCryptoRng + ?Sized,
325    D: Digest + FixedOutputReset,
326{
327    let mut salt = vec![0; salt_len];
328    rng.try_fill_bytes(&mut salt[..]).map_err(|_| Error::Rng)?;
329
330    sign_pss_with_salt(blind.then_some(rng), priv_key, hashed, &salt, digest)
331}
332
333pub(crate) fn sign_digest<T, D>(
334    rng: &mut T,
335    blind: bool,
336    priv_key: &PrivateKey,
337    hashed: &[u8],
338    salt_len: usize,
339) -> Result<Vec<u8>>
340where
341    T: TryCryptoRng + ?Sized,
342    D: Digest + FixedOutputReset,
343{
344    let mut salt = vec![0; salt_len];
345    rng.try_fill_bytes(&mut salt[..]).map_err(|_| Error::Rng)?;
346
347    sign_pss_with_salt_digest::<_, D>(blind.then_some(rng), priv_key, hashed, &salt)
348}
349
350/// signPSSWithSalt calculates the signature of hashed using PSS with specified salt.
351///
352/// Note that hashed must be the result of hashing the input message using the
353/// given hash function. salt is a random sequence of bytes whose length will be
354/// later used to verify the signature.
355fn sign_pss_with_salt<T, D>(
356    blind_rng: Option<&mut T>,
357    priv_key: &PrivateKey,
358    hashed: &[u8],
359    salt: &[u8],
360    digest: &mut D,
361) -> Result<Vec<u8>>
362where
363    T: TryCryptoRng + ?Sized,
364    D: Digest + FixedOutputReset,
365{
366    let em_bits = priv_key.n().bit_width() - 1;
367
368    let em = emsa_pss_encode(hashed, em_bits as _, salt, digest)?;
369
370    let em = os2ip(&em, priv_key.n_bits_precision())?;
371    let raw = rsa_decrypt_and_check(priv_key, blind_rng, &em)?;
372    Ok(i2osp(raw, priv_key.size()))
373}
374
375fn sign_pss_with_salt_digest<T, D>(
376    blind_rng: Option<&mut T>,
377    priv_key: &PrivateKey,
378    hashed: &[u8],
379    salt: &[u8],
380) -> Result<Vec<u8>>
381where
382    T: TryCryptoRng + ?Sized,
383    D: Digest + FixedOutputReset,
384{
385    let em_bits = priv_key.n().bit_width() - 1;
386    let em = emsa_pss_encode_digest::<D>(hashed, em_bits as _, salt)?;
387
388    let em = os2ip(&em, priv_key.n_bits_precision())?;
389    Ok(i2osp(
390        rsa_decrypt_and_check(priv_key, blind_rng, &em)?,
391        priv_key.size(),
392    ))
393}
394
395/// Returns the [`AlgorithmIdentifierOwned`] associated with PSS signature using a given digest.
396#[cfg(feature = "encoding")]
397#[allow(clippy::missing_errors_doc, reason = "TODO")]
398pub fn get_default_pss_signature_algo_id<D>() -> spki::Result<AlgorithmIdentifierOwned>
399where
400    D: Digest + AssociatedOid,
401{
402    get_pss_signature_algo_id::<D>(<D as Digest>::output_size())
403}
404
405#[cfg(feature = "encoding")]
406fn get_pss_signature_algo_id<D>(salt_len: usize) -> spki::Result<AlgorithmIdentifierOwned>
407where
408    D: Digest + AssociatedOid,
409{
410    // RsaPssParams encodes salt_len in a single byte; reject rather than truncate.
411    let salt_len = u8::try_from(salt_len).map_err(|_| ErrorKind::Overflow.to_error())?;
412    let pss_params = RsaPssParams::new::<D>(salt_len);
413
414    Ok(AlgorithmIdentifierOwned {
415        oid: ID_RSASSA_PSS,
416        parameters: Some(Any::encode_from(&pss_params)?),
417    })
418}
419
420#[cfg(all(test, feature = "encoding"))]
421mod test {
422    use crate::pss::{Pss, Signature, SigningKey, VerifyingKey};
423    use crate::{PrivateKey, PublicKey};
424
425    use crate::traits::PublicKeyParts;
426    use hex_literal::hex;
427    use pkcs1::DecodeRsaPrivateKey;
428    use rand::rngs::ChaCha8Rng;
429    use rand_core::SeedableRng;
430    use rstest::rstest;
431    use sha1::{Digest, Sha1};
432    use signature::hazmat::{PrehashVerifier, RandomizedPrehashSigner};
433    use signature::{DigestVerifier, Keypair, RandomizedDigestSigner, RandomizedSigner, Verifier};
434
435    use super::get_default_pss_signature_algo_id;
436    use spki::DynSignatureAlgorithmIdentifier;
437
438    fn get_private_key() -> PrivateKey {
439        // In order to generate new test vectors you'll need the PEM form of this key:
440        // -----BEGIN RSA PRIVATE KEY-----
441        // MIIBOgIBAAJBALKZD0nEffqM1ACuak0bijtqE2QrI/KLADv7l3kK3ppMyCuLKoF0
442        // fd7Ai2KW5ToIwzFofvJcS/STa6HA5gQenRUCAwEAAQJBAIq9amn00aS0h/CrjXqu
443        // /ThglAXJmZhOMPVn4eiu7/ROixi9sex436MaVeMqSNf7Ex9a8fRNfWss7Sqd9eWu
444        // RTUCIQDasvGASLqmjeffBNLTXV2A5g4t+kLVCpsEIZAycV5GswIhANEPLmax0ME/
445        // EO+ZJ79TJKN5yiGBRsv5yvx5UiHxajEXAiAhAol5N4EUyq6I9w1rYdhPMGpLfk7A
446        // IU2snfRJ6Nq2CQIgFrPsWRCkV+gOYcajD17rEqmuLrdIRexpg8N1DOSXoJ8CIGlS
447        // tAboUGBxTDq3ZroNism3DaMIbKPyYrAqhKov1h5V
448        // -----END RSA PRIVATE KEY-----
449
450        let pem = r#"
451-----BEGIN RSA PRIVATE KEY-----
452MIIBOgIBAAJBALKZD0nEffqM1ACuak0bijtqE2QrI/KLADv7l3kK3ppMyCuLKoF0
453fd7Ai2KW5ToIwzFofvJcS/STa6HA5gQenRUCAwEAAQJBAIq9amn00aS0h/CrjXqu
454/ThglAXJmZhOMPVn4eiu7/ROixi9sex436MaVeMqSNf7Ex9a8fRNfWss7Sqd9eWu
455RTUCIQDasvGASLqmjeffBNLTXV2A5g4t+kLVCpsEIZAycV5GswIhANEPLmax0ME/
456EO+ZJ79TJKN5yiGBRsv5yvx5UiHxajEXAiAhAol5N4EUyq6I9w1rYdhPMGpLfk7A
457IU2snfRJ6Nq2CQIgFrPsWRCkV+gOYcajD17rEqmuLrdIRexpg8N1DOSXoJ8CIGlS
458tAboUGBxTDq3ZroNism3DaMIbKPyYrAqhKov1h5V
459-----END RSA PRIVATE KEY-----"#;
460
461        PrivateKey::from_pkcs1_pem(pem).unwrap()
462    }
463
464    #[rstest]
465    #[case(
466        "test\n",
467        hex!(
468            "6f86f26b14372b2279f79fb6807c49889835c204f71e38249b4c5601462da8ae"
469            "30f26ffdd9c13f1c75eee172bebe7b7c89f2f1526c722833b9737d6c172a962f"
470        ),
471        true,
472    )]
473    #[case(
474        "test\n",
475        hex!(
476            "6f86f26b14372b2279f79fb6807c49889835c204f71e38249b4c5601462da8ae"
477            "30f26ffdd9c13f1c75eee172bebe7b7c89f2f1526c722833b9737d6c172a962e"
478        ),
479        false,
480    )]
481    fn test_verify_pss(#[case] text: &str, #[case] sig: [u8; 64], #[case] expected: bool) {
482        let priv_key = get_private_key();
483        let pub_key: PublicKey = priv_key.into();
484
485        let digest = Sha1::digest(text.as_bytes()).to_vec();
486        let result = pub_key.verify(Pss::<Sha1>::new(), &digest, &sig);
487
488        match expected {
489            true => result.expect("failed to verify"),
490            false => {
491                result.expect_err("expected verifying error");
492            }
493        }
494    }
495
496    #[rstest]
497    #[case(
498        "test\n",
499        hex!(
500            "6f86f26b14372b2279f79fb6807c49889835c204f71e38249b4c5601462da8ae"
501            "30f26ffdd9c13f1c75eee172bebe7b7c89f2f1526c722833b9737d6c172a962f"
502        ),
503        true,
504    )]
505    #[case(
506        "test\n",
507        hex!(
508            "6f86f26b14372b2279f79fb6807c49889835c204f71e38249b4c5601462da8ae"
509            "30f26ffdd9c13f1c75eee172bebe7b7c89f2f1526c722833b9737d6c172a962e"
510        ),
511        false,
512    )]
513    fn test_verify_pss_signer(#[case] text: &str, #[case] sig: [u8; 64], #[case] expected: bool) {
514        let priv_key = get_private_key();
515        let pub_key: PublicKey = priv_key.into();
516        let verifying_key: VerifyingKey<Sha1> = VerifyingKey::new(pub_key);
517
518        let result = verifying_key.verify(
519            text.as_bytes(),
520            &Signature::try_from(sig.as_slice()).unwrap(),
521        );
522        match expected {
523            true => result.expect("failed to verify"),
524            false => {
525                result.expect_err("expected verifying error");
526            }
527        }
528    }
529
530    #[rstest]
531    #[case(
532        "test\n",
533        hex!(
534            "6f86f26b14372b2279f79fb6807c49889835c204f71e38249b4c5601462da8ae"
535            "30f26ffdd9c13f1c75eee172bebe7b7c89f2f1526c722833b9737d6c172a962f"
536        ),
537        true,
538    )]
539    #[case(
540        "test\n",
541        hex!(
542            "6f86f26b14372b2279f79fb6807c49889835c204f71e38249b4c5601462da8ae"
543            "30f26ffdd9c13f1c75eee172bebe7b7c89f2f1526c722833b9737d6c172a962e"
544        ),
545        false,
546    )]
547    fn test_verify_pss_digest_signer(
548        #[case] text: &str,
549        #[case] sig: [u8; 64],
550        #[case] expected: bool,
551    ) {
552        let priv_key = get_private_key();
553        let pub_key: PublicKey = priv_key.into();
554        let verifying_key = VerifyingKey::new(pub_key);
555
556        let result = verifying_key.verify_digest(
557            |digest: &mut Sha1| {
558                digest.update(text.as_bytes());
559                Ok(())
560            },
561            &Signature::try_from(sig.as_slice()).unwrap(),
562        );
563        match expected {
564            true => result.expect("failed to verify"),
565            false => {
566                result.expect_err("expected verifying error");
567            }
568        }
569    }
570
571    #[rstest]
572    #[case("test\n")]
573    fn test_sign_and_verify_roundtrip(#[case] test: &str) {
574        let priv_key = get_private_key();
575
576        let mut rng = ChaCha8Rng::from_seed([42; 32]);
577
578        let digest = Sha1::digest(test.as_bytes()).to_vec();
579        let sig = priv_key
580            .sign_with_rng(&mut rng, Pss::<Sha1>::new(), &digest)
581            .expect("failed to sign");
582
583        priv_key
584            .to_public_key()
585            .verify(Pss::<Sha1>::new(), &digest, &sig)
586            .expect("failed to verify");
587    }
588
589    #[rstest]
590    #[case("test\n")]
591    fn test_sign_blinded_and_verify_roundtrip(#[case] test: &str) {
592        let priv_key = get_private_key();
593
594        let mut rng = ChaCha8Rng::from_seed([42; 32]);
595
596        let digest = Sha1::digest(test.as_bytes()).to_vec();
597        let sig = priv_key
598            .sign_with_rng(&mut rng, Pss::<Sha1>::new_blinded(), &digest)
599            .expect("failed to sign");
600
601        priv_key
602            .to_public_key()
603            .verify(Pss::<Sha1>::new(), &digest, &sig)
604            .expect("failed to verify");
605    }
606
607    #[rstest]
608    #[case("test\n")]
609    fn test_sign_and_verify_roundtrip_signer(#[case] test: &str) {
610        let priv_key = get_private_key();
611
612        let mut rng = ChaCha8Rng::from_seed([42; 32]);
613        let signing_key = SigningKey::<Sha1>::new(priv_key);
614        let verifying_key = signing_key.verifying_key();
615
616        let sig = signing_key.sign_with_rng(&mut rng, test.as_bytes());
617        verifying_key
618            .verify(test.as_bytes(), &sig)
619            .expect("failed to verify");
620    }
621
622    #[rstest]
623    #[case("test\n")]
624    fn test_sign_and_verify_roundtrip_digest_signer(#[case] test: &str) {
625        let priv_key = get_private_key();
626
627        let mut rng = ChaCha8Rng::from_seed([42; 32]);
628        let signing_key = SigningKey::new(priv_key);
629        let verifying_key = signing_key.verifying_key();
630
631        let sig = signing_key
632            .sign_digest_with_rng(&mut rng, |digest: &mut Sha1| digest.update(test.as_bytes()));
633
634        verifying_key
635            .verify_digest(
636                |digest: &mut Sha1| {
637                    digest.update(test.as_bytes());
638                    Ok(())
639                },
640                &sig,
641            )
642            .expect("failed to verify");
643    }
644
645    #[rstest]
646    #[case(
647        "test\n",
648        hex!(
649            "6f86f26b14372b2279f79fb6807c49889835c204f71e38249b4c5601462da8ae"
650            "30f26ffdd9c13f1c75eee172bebe7b7c89f2f1526c722833b9737d6c172a962f"
651        ),
652        true
653    )]
654    #[case(
655        "test\n",
656        hex!(
657            "6f86f26b14372b2279f79fb6807c49889835c204f71e38249b4c5601462da8ae"
658            "30f26ffdd9c13f1c75eee172bebe7b7c89f2f1526c722833b9737d6c172a962e"
659        ),
660        false
661    )]
662    fn test_verify_pss_hazmat(#[case] text: &str, #[case] sig: [u8; 64], #[case] expected: bool) {
663        let text = Sha1::digest(text);
664        let priv_key = get_private_key();
665
666        let pub_key: PublicKey = priv_key.into();
667        let verifying_key = VerifyingKey::<Sha1>::new(pub_key);
668
669        let result = verifying_key
670            .verify_prehash(text.as_ref(), &Signature::try_from(sig.as_slice()).unwrap());
671        match expected {
672            true => result.expect("failed to verify"),
673            false => {
674                result.expect_err("expected verifying error");
675            }
676        }
677    }
678
679    #[rstest]
680    #[case("test\n")]
681    fn test_sign_and_verify_pss_hazmat(#[case] test: &str) {
682        let test = &Sha1::digest(test);
683        let priv_key = get_private_key();
684
685        let mut rng = ChaCha8Rng::from_seed([42; 32]);
686        let signing_key = SigningKey::<Sha1>::new(priv_key);
687        let verifying_key = signing_key.verifying_key();
688
689        let sig = signing_key
690            .sign_prehash_with_rng(&mut rng, test)
691            .expect("failed to sign");
692        verifying_key
693            .verify_prehash(test, &sig)
694            .expect("failed to verify");
695    }
696
697    #[test]
698    // Tests the corner case where the key is multiple of 8 + 1 bits long
699    fn test_sign_and_verify_2049bit_key() {
700        let plaintext = "Hello\n";
701        let mut rng = ChaCha8Rng::from_seed([42; 32]);
702        for _ in 0..10 {
703            let priv_key = PrivateKey::new(&mut rng, 2049).unwrap();
704
705            let digest = Sha1::digest(plaintext.as_bytes()).to_vec();
706            let sig = priv_key
707                .sign_with_rng(&mut rng, Pss::<Sha1>::new(), &digest)
708                .expect("failed to sign");
709
710            priv_key
711                .to_public_key()
712                .verify(Pss::<Sha1>::new(), &digest, &sig)
713                .expect("failed to verify");
714        }
715    }
716
717    // Tests the case where the salt length used for signing differs from the default length
718    // while the verifier uses auto-detection.
719    #[rstest]
720    #[case("test\n")]
721    fn test_sign_and_verify_pss_differing_salt_len(#[case] test: &str) {
722        let priv_key = get_private_key();
723
724        let mut rng = ChaCha8Rng::from_seed([42; 32]);
725
726        // signing keys using different salt lengths
727        let signing_keys = [
728            // default salt length
729            SigningKey::<Sha1>::new(priv_key.clone()),
730            // maximum salt length
731            SigningKey::<Sha1>::new_with_salt_len(
732                priv_key.clone(),
733                priv_key.size() - Sha1::output_size() - 2,
734            ),
735            // unsalted
736            SigningKey::<Sha1>::new_with_salt_len(priv_key.clone(), 0),
737        ];
738
739        // verifying key uses default salt length strategy
740        let verifying_key = VerifyingKey::<Sha1>::new_with_auto_salt_len(priv_key.to_public_key());
741
742        for signing_key in &signing_keys {
743            let sig = signing_key.sign_with_rng(&mut rng, test.as_bytes());
744            verifying_key
745                .verify(test.as_bytes(), &sig)
746                .expect("verification to succeed");
747        }
748    }
749
750    // A salt length that does not fit in a byte must be rejected, not truncated (#703).
751    #[test]
752    fn signature_algorithm_identifier_rejects_oversized_salt_len() {
753        use spki::DynSignatureAlgorithmIdentifier;
754
755        let priv_key = get_private_key();
756
757        // largest value that fits in a byte
758        let ok_key = SigningKey::<Sha1>::new_with_salt_len(priv_key.clone(), 255);
759        assert!(ok_key.signature_algorithm_identifier().is_ok());
760
761        // would wrap to 0
762        let bad_key = SigningKey::<Sha1>::new_with_salt_len(priv_key.clone(), 256);
763        assert!(bad_key.signature_algorithm_identifier().is_err());
764    }
765
766    /// `signature_algorithm_identifier()` must advertise the configured salt length
767    /// verbatim: the encoded `AlgorithmIdentifier` parameters must DER-round-trip
768    /// back to the same `salt_len` for both signing key types (see issue #703).
769    #[rstest]
770    #[case(255)]
771    #[case(128)]
772    fn test_pss_algo_id_salt_len_representable(#[case] salt_len: usize) {
773        use spki::der::Encode;
774
775        let priv_key = get_private_key();
776
777        let signing_key = SigningKey::<Sha1>::new_with_salt_len(priv_key.clone(), salt_len);
778
779        let algo_id = signing_key
780            .signature_algorithm_identifier()
781            .expect("salt_len fits in a u8, so encoding must succeed");
782
783        let params_bytes = algo_id
784            .parameters
785            .as_ref()
786            .expect("RSA-PSS AlgorithmIdentifier carries parameters")
787            .to_der()
788            .expect("parameters are DER-encodable");
789        let pss_params = <pkcs1::RsaPssParamsOwned as spki::der::Decode>::from_der(&params_bytes)
790            .expect("RSA-PSS parameters are DER-decodable");
791        assert_eq!(pss_params.salt_len as usize, salt_len);
792    }
793
794    #[rstest]
795    #[case(256)]
796    #[case(300)]
797    #[case(usize::MAX)]
798    fn test_pss_algo_id_salt_len_out_of_range(#[case] salt_len: usize) {
799        let priv_key = get_private_key();
800        let signing_key = SigningKey::<Sha1>::new_with_salt_len(priv_key.clone(), salt_len);
801
802        signing_key
803            .signature_algorithm_identifier()
804            .expect_err("salt_len overflows the u8 in RsaPssParams, so encoding must fail");
805    }
806
807    /// The digest-size default salt length is unchanged by the `u8` validation.
808    #[test]
809    fn test_pss_algo_id_default_salt_len_unchanged() {
810        use spki::der::Encode;
811
812        let algo_id = get_default_pss_signature_algo_id::<Sha1>()
813            .expect("the default salt length must remain encodable");
814        let params_bytes = algo_id
815            .parameters
816            .as_ref()
817            .expect("RSA-PSS AlgorithmIdentifier carries parameters")
818            .to_der()
819            .expect("parameters are DER-encodable");
820        let pss_params = <pkcs1::RsaPssParamsOwned as spki::der::Decode>::from_der(&params_bytes)
821            .expect("RSA-PSS parameters are DER-decodable");
822        assert_eq!(pss_params.salt_len as usize, Sha1::output_size());
823    }
824}