Skip to main content

rsa/
pkcs1v15.rs

1//! RSAES-PKCS1-v1_5 encryption ([RFC8017 § 7.2]) and RSASSA-PKCS1-v1_5 signatures
2//! ([RFC8017 § 8.2]).
3//!
4//! <div class="warning">
5//! <b>Warning</b>
6//!
7//! PKCS#1 v1.5 padding has a longstanding history of issues generally classed as
8//! [Bleichenbacher Attacks] which were originally discovered in 1998 but keep reappearing in
9//! various forms again and again over the course of decades, including most recently in the 2023
10//! [Marvin Attack], which the `rsa` crate is [still vulnerable] to.
11//!
12//! These attacks can result in complete plaintext recovery for encryption, or signature forgery,
13//! leading to a total failure of either confidentiality or integrity.
14//!
15//! Unless explicitly needed for compatibility reasons, we recommend against using PKCS#1 v1.5,
16//! and suggest using [PSS][`super::pss`] or [OAEP][`super::oaep`] instead (if there is a
17//! requirement to use RSA).
18//! </div>
19//!
20//! [Bleichenbacher Attacks]: https://en.wikipedia.org/wiki/Adaptive_chosen-ciphertext_attack#Practical_attacks
21//! [Marvin Attack]: https://people.redhat.com/~hkario/marvin/
22//! [still vulnerable]: https://github.com/RustCrypto/RSA/issues/626
23//!
24//! # Usage
25//!
26//! See [code example in the toplevel rustdoc](../index.html#pkcs1-v15-signatures).
27//!
28//! [RFC8017 § 7.2]: https://datatracker.ietf.org/doc/html/rfc8017#section-7.2
29//! [RFC8017 § 8.2]: https://datatracker.ietf.org/doc/html/rfc8017#section-8.2
30
31mod decrypting_key;
32mod encrypting_key;
33mod signature;
34mod signing_key;
35mod verifying_key;
36
37pub use self::{
38    decrypting_key::DecryptingKey, encrypting_key::EncryptingKey, signature::Signature,
39    signing_key::SigningKey, verifying_key::VerifyingKey,
40};
41
42use alloc::{boxed::Box, vec::Vec};
43use const_oid::AssociatedOid;
44use core::fmt::Debug;
45use digest::Digest;
46use rand_core::TryCryptoRng;
47
48use crate::algorithms::pad::{i2osp, i2osp_zeroizing, os2ip, os2ip_zeroizing};
49use crate::algorithms::pkcs1v15::*;
50use crate::algorithms::rsa::{rsa_decrypt_and_check, rsa_encrypt};
51use crate::errors::{Error, Result};
52use crate::traits::{PaddingScheme, PrivateKeyParts, PublicKeyParts, SignatureScheme};
53use crate::{PrivateKey, PublicKey, public_key};
54
55#[cfg(feature = "getrandom")]
56use crypto_common::getrandom::SysRng;
57
58impl PublicKey {
59    /// Encrypt `plaintext` using PKCS#1 v1.5 and the operating system RNG.
60    ///
61    /// Prefer [`Self::oaep_encrypt`] for new protocols. See the [`crate::pkcs1v15`]
62    /// module's security notes.
63    ///
64    /// # Errors
65    /// Returns an error if the key is invalid, the plaintext is too long, or the RNG fails.
66    #[cfg(feature = "getrandom")]
67    pub fn pkcs1v15_encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>> {
68        self.pkcs1v15_encrypt_with_rng(&mut SysRng, plaintext)
69    }
70
71    /// Encrypt `plaintext` using PKCS#1 v1.5 and the provided RNG.
72    ///
73    /// Prefer [`Self::oaep_encrypt_with_rng`] for new protocols. See the
74    /// [`crate::pkcs1v15`] module's security notes.
75    ///
76    /// # Errors
77    /// Returns an error if the key is invalid, the plaintext is too long, or the RNG fails.
78    pub fn pkcs1v15_encrypt_with_rng<R>(&self, rng: &mut R, plaintext: &[u8]) -> Result<Vec<u8>>
79    where
80        R: TryCryptoRng + ?Sized,
81    {
82        encrypt(rng, self, plaintext)
83    }
84
85    /// Verify a PKCS#1 v1.5 signature after hashing `msg` with `D`.
86    ///
87    /// # Errors
88    /// Returns an error if the signature is invalid.
89    pub fn pkcs1v15_verify<D>(&self, msg: &[u8], sig: &[u8]) -> Result<()>
90    where
91        D: Digest + AssociatedOid,
92    {
93        self.pkcs1v15_verify_prehash::<D>(&D::digest(msg), sig)
94    }
95
96    /// Verify a PKCS#1 v1.5 signature over a message hash computed using `D`.
97    ///
98    /// The hash is verified directly, without hashing it again.
99    ///
100    /// # Errors
101    /// Returns [`Error::InputNotHashed`] if `hash` has the wrong length, or an error
102    /// if the signature is invalid.
103    pub fn pkcs1v15_verify_prehash<D>(&self, hash: &[u8], sig: &[u8]) -> Result<()>
104    where
105        D: Digest + AssociatedOid,
106    {
107        if hash.len() != <D as Digest>::output_size() {
108            return Err(Error::InputNotHashed);
109        }
110
111        verify(self, &pkcs1v15_generate_prefix::<D>(), hash, sig)
112    }
113}
114
115impl PrivateKey {
116    /// Decrypt `ciphertext` using PKCS#1 v1.5 with implicit rejection.
117    ///
118    /// Invalid padding returns a deterministic synthetic message. `Ok` does not establish
119    /// authenticity; the enclosing protocol must authenticate the returned message.
120    /// See [`Pkcs1v15Encrypt`] and the [`crate::pkcs1v15`] module's security notes.
121    ///
122    /// Uses the operating system RNG for blinding when `getrandom` is enabled.
123    /// Otherwise, this operation is unblinded; use [`Self::pkcs1v15_decrypt_with_rng`]
124    /// to provide blinding randomness.
125    ///
126    /// # Errors
127    /// Returns an error for invalid keys, ciphertext lengths or representatives,
128    /// unsupported modulus lengths, or operational failures, including RNG failures.
129    pub fn pkcs1v15_decrypt(&self, ciphertext: &[u8]) -> Result<Vec<u8>> {
130        #[cfg(feature = "getrandom")]
131        {
132            self.pkcs1v15_decrypt_with_rng(&mut SysRng, ciphertext)
133        }
134        #[cfg(not(feature = "getrandom"))]
135        {
136            decrypt::<crate::dummy_rng::DummyRng>(None, self, ciphertext)
137        }
138    }
139
140    /// Decrypt `ciphertext` using PKCS#1 v1.5, using the provided RNG for blinding.
141    ///
142    /// Uses implicit rejection as described in [`Self::pkcs1v15_decrypt`]. The enclosing
143    /// protocol must authenticate the returned message, even when this returns `Ok`.
144    ///
145    /// # Errors
146    /// Returns the same errors as [`Self::pkcs1v15_decrypt`].
147    pub fn pkcs1v15_decrypt_with_rng<R>(&self, rng: &mut R, ciphertext: &[u8]) -> Result<Vec<u8>>
148    where
149        R: TryCryptoRng + ?Sized,
150    {
151        decrypt(Some(rng), self, ciphertext)
152    }
153
154    /// Sign `msg` using PKCS#1 v1.5 after hashing it with `D`.
155    ///
156    /// Uses the operating system RNG for blinding when `getrandom` is enabled.
157    /// Otherwise, this operation is unblinded; use [`Self::pkcs1v15_sign_with_rng`]
158    /// to provide blinding randomness. Blinding does not change the signature.
159    ///
160    /// # Errors
161    /// Returns an error if the key is too small for `D` or the private operation fails.
162    pub fn pkcs1v15_sign<D>(&self, msg: &[u8]) -> Result<Vec<u8>>
163    where
164        D: Digest + AssociatedOid,
165    {
166        self.pkcs1v15_sign_prehash::<D>(&D::digest(msg))
167    }
168
169    /// Sign a message hash computed using `D` with PKCS#1 v1.5.
170    ///
171    /// The hash is signed directly, without hashing it again. Blinding follows
172    /// [`Self::pkcs1v15_sign`].
173    ///
174    /// # Errors
175    /// Returns [`Error::InputNotHashed`] if `hash` has the wrong length, or an error
176    /// if the key is too small for `D` or the private operation fails.
177    pub fn pkcs1v15_sign_prehash<D>(&self, hash: &[u8]) -> Result<Vec<u8>>
178    where
179        D: Digest + AssociatedOid,
180    {
181        if hash.len() != <D as Digest>::output_size() {
182            return Err(Error::InputNotHashed);
183        }
184
185        sign_with_default_rng(self, &pkcs1v15_generate_prefix::<D>(), hash)
186    }
187
188    /// Sign `msg` using PKCS#1 v1.5 after hashing it with `D`, using the provided RNG
189    /// for blinding. Blinding does not change the signature.
190    ///
191    /// # Errors
192    /// Returns an error if the key is too small for `D` or the private operation fails,
193    /// including RNG failures.
194    pub fn pkcs1v15_sign_with_rng<D, R>(&self, rng: &mut R, msg: &[u8]) -> Result<Vec<u8>>
195    where
196        D: Digest + AssociatedOid,
197        R: TryCryptoRng + ?Sized,
198    {
199        self.pkcs1v15_sign_prehash_with_rng::<D, _>(rng, &D::digest(msg))
200    }
201
202    /// Sign a message hash computed using `D` with PKCS#1 v1.5, using the provided RNG
203    /// for blinding. The hash is signed directly, without hashing it again.
204    ///
205    /// # Errors
206    /// Returns [`Error::InputNotHashed`] if `hash` has the wrong length, or an error
207    /// if the key is too small for `D` or the private operation fails, including RNG failures.
208    pub fn pkcs1v15_sign_prehash_with_rng<D, R>(&self, rng: &mut R, hash: &[u8]) -> Result<Vec<u8>>
209    where
210        D: Digest + AssociatedOid,
211        R: TryCryptoRng + ?Sized,
212    {
213        if hash.len() != <D as Digest>::output_size() {
214            return Err(Error::InputNotHashed);
215        }
216
217        sign(Some(rng), self, &pkcs1v15_generate_prefix::<D>(), hash)
218    }
219}
220
221/// Encryption using PKCS#1 v1.5 padding. Decryption uses implicit rejection from
222/// [draft-irtf-cfrg-rsa-guidance-10 §7.2].
223///
224/// Invalid padding returns a deterministic synthetic message instead of an error. `Ok` therefore
225/// does not establish padding validity or message authenticity; the enclosing protocol must
226/// authenticate the returned message.
227///
228/// Incorrect ciphertext lengths, representatives outside the modulus, unsupported modulus lengths
229/// (over `8191` octets), and operational failures still return errors.
230///
231/// [draft-irtf-cfrg-rsa-guidance-10 §7.2]: https://www.ietf.org/archive/id/draft-irtf-cfrg-rsa-guidance-10.html#section-7.2
232#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
233pub struct Pkcs1v15Encrypt;
234
235impl PaddingScheme for Pkcs1v15Encrypt {
236    fn decrypt<Rng: TryCryptoRng + ?Sized>(
237        self,
238        rng: Option<&mut Rng>,
239        priv_key: &PrivateKey,
240        ciphertext: &[u8],
241    ) -> Result<Vec<u8>> {
242        decrypt(rng, priv_key, ciphertext)
243    }
244
245    fn encrypt<Rng: TryCryptoRng + ?Sized>(
246        self,
247        rng: &mut Rng,
248        pub_key: &PublicKey,
249        msg: &[u8],
250    ) -> Result<Vec<u8>> {
251        encrypt(rng, pub_key, msg)
252    }
253}
254
255/// `RSASSA-PKCS1-v1_5`: digital signatures using PKCS#1 v1.5 padding.
256#[derive(Clone, Debug, Eq, PartialEq)]
257pub struct Pkcs1v15Sign {
258    /// Length of hash to use.
259    pub hash_len: Option<usize>,
260
261    /// Prefix.
262    pub prefix: Box<[u8]>,
263}
264
265impl Pkcs1v15Sign {
266    /// Create new PKCS#1 v1.5 padding for the given digest.
267    ///
268    /// The digest must have an [`AssociatedOid`]. Make sure to enable the `oid`
269    /// feature of the relevant digest crate.
270    #[must_use]
271    pub fn new<D>() -> Self
272    where
273        D: Digest + AssociatedOid,
274    {
275        Self {
276            hash_len: Some(<D as Digest>::output_size()),
277            prefix: pkcs1v15_generate_prefix::<D>().into_boxed_slice(),
278        }
279    }
280
281    /// Create new PKCS#1 v1.5 padding for computing an unprefixed signature.
282    ///
283    /// This sets `hash_len` to `None` and uses an empty `prefix`.
284    #[must_use]
285    pub fn new_unprefixed() -> Self {
286        Self {
287            hash_len: None,
288            prefix: Box::new([]),
289        }
290    }
291}
292
293impl SignatureScheme for Pkcs1v15Sign {
294    fn sign<Rng: TryCryptoRng + ?Sized>(
295        self,
296        rng: Option<&mut Rng>,
297        priv_key: &PrivateKey,
298        hashed: &[u8],
299    ) -> Result<Vec<u8>> {
300        if let Some(hash_len) = self.hash_len {
301            if hashed.len() != hash_len {
302                return Err(Error::InputNotHashed);
303            }
304        }
305
306        sign(rng, priv_key, &self.prefix, hashed)
307    }
308
309    fn verify(self, pub_key: &PublicKey, hashed: &[u8], sig: &[u8]) -> Result<()> {
310        if let Some(hash_len) = self.hash_len {
311            if hashed.len() != hash_len {
312                return Err(Error::InputNotHashed);
313            }
314        }
315
316        verify(pub_key, self.prefix.as_ref(), hashed, sig)
317    }
318}
319
320/// Encrypts the given message with RSA and the padding
321/// scheme from PKCS#1 v1.5.  The message must be no longer than the
322/// length of the public modulus minus 11 bytes.
323#[inline]
324fn encrypt<R: TryCryptoRng + ?Sized>(
325    rng: &mut R,
326    pub_key: &PublicKey,
327    msg: &[u8],
328) -> Result<Vec<u8>> {
329    public_key::check_public(pub_key)?;
330
331    let em = pkcs1v15_encrypt_pad(rng, msg, pub_key.size())?;
332    let int = os2ip_zeroizing(em, pub_key.n_bits_precision())?;
333    Ok(i2osp(rsa_encrypt(pub_key, &int)?, pub_key.size()))
334}
335
336/// Decrypts a plaintext using RSA and the padding scheme from PKCS#1 v1.5.
337///
338/// If an `rng` is passed, it uses RSA blinding to avoid timing side-channel attacks.
339///
340/// Implements draft-irtf-cfrg-rsa-guidance-10 §7.2. Padding validity remains secret: only the final
341/// message and its selected length are returned.
342#[inline]
343fn decrypt<R: TryCryptoRng + ?Sized>(
344    rng: Option<&mut R>,
345    priv_key: &PrivateKey,
346    ciphertext: &[u8],
347) -> Result<Vec<u8>> {
348    public_key::check_public(priv_key)?;
349    let k = priv_key.size();
350
351    // RFC8017 §7.2.2 and draft-irtf-cfrg-rsa-guidance-10 §7.2, step 1.
352    if k < 11 || ciphertext.len() != k {
353        return Err(Error::Decryption);
354    }
355
356    // §7.1 encodes the IRPRF output's bit length in two octets. The stated 8192-octet endpoint is
357    // unrepresentable, so reject it rather than wrap to zero.
358    if k > 8191 {
359        return Err(Error::Decryption);
360    }
361
362    // Step 2.1: c = OS2IP(C).
363    let c = os2ip(ciphertext, priv_key.n_bits_precision())?;
364
365    // Step 2.2: m = RSADP(K, c), with blinding and the CRT fault check.
366    let m = rsa_decrypt_and_check(priv_key, rng, &c)?;
367
368    // Step 2.3: EM = I2OSP(m, k), constant-time with respect to m.
369    let mut em = i2osp_zeroizing(m, k);
370
371    // Step 3: derive KDK, CL, AM, and AL, even when EM has valid padding.
372    let kdk = implicit_rejection::KeyDerivationKey::derive(priv_key.d(), k, ciphertext)?;
373    let (am, al) = kdk.alternative_message(k)?;
374
375    // Step 4: EME-PKCS1-v1_5 decoding produces the secret check variable and L.
376    let (check, l) = eme_pkcs1v15_decode(&em, k);
377
378    // Step 5: select the message and its length without exposing check, AL, or L.
379    let length = select_message(&mut em, &am, al, l, check) as usize;
380
381    // The draft permits the final returned length to be public. Only after both buffers have been
382    // read and selected do we use that length for slicing.
383    Ok(em[k - length..].to_vec())
384}
385
386/// Sign with the default source of blinding randomness, when enabled.
387fn sign_with_default_rng(priv_key: &PrivateKey, prefix: &[u8], hashed: &[u8]) -> Result<Vec<u8>> {
388    #[cfg(feature = "getrandom")]
389    {
390        sign(Some(&mut SysRng), priv_key, prefix, hashed)
391    }
392    #[cfg(not(feature = "getrandom"))]
393    {
394        sign::<crate::dummy_rng::DummyRng>(None, priv_key, prefix, hashed)
395    }
396}
397
398/// Calculates the signature of hashed using `RSASSA-PKCS1-V1_5-SIGN` from RSA PKCS#1 v1.5.
399/// Note that `hashed` must be the result of hashing the input message using the given hash
400/// function. If hash is `None`, hashed is signed directly. This isn't advisable except for
401/// interoperability.
402///
403/// If `rng` is not `None` then RSA blinding will be used to avoid timing
404/// side-channel attacks.
405///
406/// This function is deterministic. Thus, if the set of possible
407/// messages is small, an attacker may be able to build a map from
408/// messages to signatures and identify the signed messages. As ever,
409/// signatures provide authenticity, not confidentiality.
410#[inline]
411fn sign<R: TryCryptoRng + ?Sized>(
412    rng: Option<&mut R>,
413    priv_key: &PrivateKey,
414    prefix: &[u8],
415    hashed: &[u8],
416) -> Result<Vec<u8>> {
417    let em = pkcs1v15_sign_pad(prefix, hashed, priv_key.size())?;
418
419    let em = os2ip(&em, priv_key.n_bits_precision())?;
420    // The signature itself is public; only the computation is secret
421    Ok(i2osp(
422        rsa_decrypt_and_check(priv_key, rng, &em)?,
423        priv_key.size(),
424    ))
425}
426
427/// Verifies an RSA PKCS#1 v1.5 signature.
428#[inline]
429fn verify(pub_key: &PublicKey, prefix: &[u8], hashed: &[u8], sig: &[u8]) -> Result<()> {
430    // RFC8017 §8.2.2 steps 1 and 2: validate S before converting it to s.
431    if sig.len() != pub_key.size() {
432        return Err(Error::Verification);
433    }
434    let s = os2ip(sig, pub_key.n_bits_precision()).map_err(|_| Error::Verification)?;
435    if s >= *pub_key.n().as_ref() {
436        return Err(Error::Verification);
437    }
438
439    let em = i2osp(rsa_encrypt(pub_key, &s)?, pub_key.size());
440
441    pkcs1v15_sign_unpad(prefix, hashed, &em, pub_key.size())
442}
443
444mod oid {
445    use const_oid::ObjectIdentifier;
446
447    /// A trait which associates an RSA-specific OID with a type.
448    pub trait RsaSignatureAssociatedOid {
449        /// The OID associated with this type.
450        const OID: ObjectIdentifier;
451    }
452
453    #[cfg(feature = "sha1")]
454    impl RsaSignatureAssociatedOid for sha1::Sha1 {
455        const OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.5");
456    }
457
458    impl RsaSignatureAssociatedOid for sha2::Sha224 {
459        const OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.14");
460    }
461
462    impl RsaSignatureAssociatedOid for sha2::Sha256 {
463        const OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.11");
464    }
465
466    impl RsaSignatureAssociatedOid for sha2::Sha384 {
467        const OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.12");
468    }
469
470    impl RsaSignatureAssociatedOid for sha2::Sha512 {
471        const OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.13");
472    }
473}
474
475pub use oid::RsaSignatureAssociatedOid;
476
477#[cfg(test)]
478mod tests {
479    use super::*;
480    use ::signature::{
481        DigestSigner, DigestVerifier, Keypair, RandomizedDigestSigner, RandomizedSigner,
482        SignatureEncoding, Signer, Verifier,
483        hazmat::{PrehashSigner, PrehashVerifier},
484    };
485    use base64ct::{Base64, Encoding};
486    use crypto_bigint::BoxedUint;
487    use hex_literal::hex;
488    use rand::rngs::ChaCha8Rng;
489    use rand_core::{Rng, SeedableRng};
490    use rstest::rstest;
491    use sha1::{Digest, Sha1};
492    use sha2::Sha256;
493    use sha3::Sha3_256;
494
495    use crate::traits::{
496        Decryptor, EncryptingKeypair, PublicKeyParts, RandomizedDecryptor, RandomizedEncryptor,
497    };
498    use crate::{PrivateKey, PublicKey};
499
500    fn get_private_key() -> PrivateKey {
501        // In order to generate new test vectors you'll need the PEM form of this key:
502        // -----BEGIN RSA PRIVATE KEY-----
503        // MIIBOgIBAAJBALKZD0nEffqM1ACuak0bijtqE2QrI/KLADv7l3kK3ppMyCuLKoF0
504        // fd7Ai2KW5ToIwzFofvJcS/STa6HA5gQenRUCAwEAAQJBAIq9amn00aS0h/CrjXqu
505        // /ThglAXJmZhOMPVn4eiu7/ROixi9sex436MaVeMqSNf7Ex9a8fRNfWss7Sqd9eWu
506        // RTUCIQDasvGASLqmjeffBNLTXV2A5g4t+kLVCpsEIZAycV5GswIhANEPLmax0ME/
507        // EO+ZJ79TJKN5yiGBRsv5yvx5UiHxajEXAiAhAol5N4EUyq6I9w1rYdhPMGpLfk7A
508        // IU2snfRJ6Nq2CQIgFrPsWRCkV+gOYcajD17rEqmuLrdIRexpg8N1DOSXoJ8CIGlS
509        // tAboUGBxTDq3ZroNism3DaMIbKPyYrAqhKov1h5V
510        // -----END RSA PRIVATE KEY-----
511
512        PrivateKey::from_components(
513            BoxedUint::from_be_hex("B2990F49C47DFA8CD400AE6A4D1B8A3B6A13642B23F28B003BFB97790ADE9A4CC82B8B2A81747DDEC08B6296E53A08C331687EF25C4BF4936BA1C0E6041E9D15", 512).unwrap(),
514            BoxedUint::from(65_537u64),
515            BoxedUint::from_be_hex("8ABD6A69F4D1A4B487F0AB8D7AAEFD38609405C999984E30F567E1E8AEEFF44E8B18BDB1EC78DFA31A55E32A48D7FB131F5AF1F44D7D6B2CED2A9DF5E5AE4535", 512).unwrap(),
516            vec![
517                BoxedUint::from_be_hex("DAB2F18048BAA68DE7DF04D2D35D5D80E60E2DFA42D50A9B04219032715E46B3", 256).unwrap(),
518                BoxedUint::from_be_hex("D10F2E66B1D0C13F10EF9927BF5324A379CA218146CBF9CAFC795221F16A3117", 256).unwrap()
519            ],
520        ).unwrap()
521    }
522
523    #[rstest]
524    #[case(
525        "gIcUIoVkD6ATMBk/u/nlCZCCWRKdkfjCgFdo35VpRXLduiKXhNz1XupLLzTXAybEq15juc+EgY5o0DHv/nt3yg==",
526        "x"
527    )]
528    #[case(
529        "Y7TOCSqofGhkRb+jaVRLzK8xw2cSo1IVES19utzv6hwvx+M8kFsoWQm5DzBeJCZTCVDPkTpavUuEbgp8hnUGDw==",
530        "testing."
531    )]
532    #[case(
533        "arReP9DJtEVyV2Dg3dDp4c/PSk1O6lxkoJ8HcFupoRorBZG+7+1fDAwT1olNddFnQMjmkb8vxwmNMoTAT/BFjQ==",
534        "testing.\n"
535    )]
536    #[case(
537        "WtaBXIoGC54+vH0NH0CHHE+dRDOsMc/6BrfFu2lEqcKL9+uDuWaf+Xj9mrbQCjjZcpQuX733zyok/jsnqe/Ftw==",
538        "01234567890123456789012345678901234567890123456789012"
539    )]
540    fn test_decrypt_pkcs1v15(#[case] ciphertext: &str, #[case] plaintext: &str) {
541        let priv_key = get_private_key();
542
543        let out = priv_key
544            .decrypt(Pkcs1v15Encrypt, &Base64::decode_vec(ciphertext).unwrap())
545            .unwrap();
546        assert_eq!(out, plaintext.as_bytes());
547    }
548
549    #[test]
550    fn test_encrypt_decrypt_pkcs1v15() {
551        let mut rng = ChaCha8Rng::from_seed([42; 32]);
552        let priv_key = get_private_key();
553        let k = priv_key.size();
554
555        for i in 1..100 {
556            let mut input = vec![0u8; i * 8];
557            rng.fill_bytes(&mut input);
558            if input.len() > k - 11 {
559                input = input[0..k - 11].to_vec();
560            }
561
562            let pub_key: PublicKey = priv_key.clone().into();
563            let ciphertext = encrypt(&mut rng, &pub_key, &input).unwrap();
564            assert_ne!(input, ciphertext);
565
566            let blind: bool = rng.next_u32() < (1u32 << 31);
567            let blinder = if blind { Some(&mut rng) } else { None };
568            let plaintext = decrypt(blinder, &priv_key, &ciphertext).unwrap();
569            assert_eq!(input, plaintext);
570        }
571    }
572
573    #[rstest]
574    #[case(
575        "gIcUIoVkD6ATMBk/u/nlCZCCWRKdkfjCgFdo35VpRXLduiKXhNz1XupLLzTXAybEq15juc+EgY5o0DHv/nt3yg==",
576        "x"
577    )]
578    #[case(
579        "Y7TOCSqofGhkRb+jaVRLzK8xw2cSo1IVES19utzv6hwvx+M8kFsoWQm5DzBeJCZTCVDPkTpavUuEbgp8hnUGDw==",
580        "testing."
581    )]
582    #[case(
583        "arReP9DJtEVyV2Dg3dDp4c/PSk1O6lxkoJ8HcFupoRorBZG+7+1fDAwT1olNddFnQMjmkb8vxwmNMoTAT/BFjQ==",
584        "testing.\n"
585    )]
586    #[case(
587        "WtaBXIoGC54+vH0NH0CHHE+dRDOsMc/6BrfFu2lEqcKL9+uDuWaf+Xj9mrbQCjjZcpQuX733zyok/jsnqe/Ftw==",
588        "01234567890123456789012345678901234567890123456789012"
589    )]
590    fn test_decrypt_pkcs1v15_traits(#[case] ciphertext: &str, #[case] plaintext: &str) {
591        let priv_key = get_private_key();
592        let decrypting_key = DecryptingKey::new(priv_key);
593
594        let out = decrypting_key
595            .decrypt(&Base64::decode_vec(ciphertext).unwrap())
596            .unwrap();
597        assert_eq!(out, plaintext.as_bytes());
598    }
599
600    #[test]
601    fn test_decrypt_pkcs1v15_rejects_wrong_length() {
602        let priv_key = get_private_key();
603        // The leading zero is part of the valid k-byte encoding. Dropping it preserves
604        // the ciphertext integer, so only the length check can reject the short form.
605        let ct = hex!(
606            "00a40774c6e201e41714d1ab89c245116ff8f0baada675f22a50c7b6c1210e"
607            "3d2c3b7c595462aa8cb9447c43ef7d50ebcf544789b19ca5c2a26daea72cf9dbde"
608        );
609        assert_eq!(priv_key.decrypt(Pkcs1v15Encrypt, &ct).unwrap(), b"x");
610
611        // RFC8017 § 7.2.2 step 1: a ciphertext shorter than `k` must be rejected.
612        assert_eq!(
613            priv_key.decrypt(Pkcs1v15Encrypt, &ct[1..]),
614            Err(Error::Decryption)
615        );
616        let mut long = vec![0u8];
617        long.extend_from_slice(&ct);
618        assert_eq!(
619            priv_key.decrypt(Pkcs1v15Encrypt, &long),
620            Err(Error::Decryption)
621        );
622    }
623
624    #[test]
625    fn implicit_rejection_preserves_public_errors() {
626        let tiny_key = PrivateKey::from_components(
627            BoxedUint::from(3233u64),
628            BoxedUint::from(17u64),
629            BoxedUint::from(413u64),
630            vec![BoxedUint::from(61u64), BoxedUint::from(53u64)],
631        )
632        .unwrap();
633        assert_eq!(
634            tiny_key.decrypt(Pkcs1v15Encrypt, &[0; 2]),
635            Err(Error::Decryption)
636        );
637
638        let key = get_private_key();
639        let typed = DecryptingKey::new(key.clone());
640        let mut rng = ChaCha8Rng::from_seed([42; 32]);
641        let k = key.size();
642        for ciphertext in [
643            vec![],
644            vec![0; k - 1],
645            vec![0; k + 1],
646            i2osp(key.n().as_ref().clone(), k),
647            vec![0xff; k],
648        ] {
649            assert_eq!(
650                key.decrypt(Pkcs1v15Encrypt, &ciphertext),
651                Err(Error::Decryption)
652            );
653            assert_eq!(
654                key.decrypt_blinded(&mut rng, Pkcs1v15Encrypt, &ciphertext),
655                Err(Error::Decryption)
656            );
657            assert_eq!(typed.decrypt(&ciphertext), Err(Error::Decryption));
658            assert_eq!(
659                typed.decrypt_with_rng(&mut rng, &ciphertext),
660                Err(Error::Decryption)
661            );
662        }
663
664        // c=0 is in range even though EM is entirely zero. Rejection must be
665        // implicit, deterministic, and independent of the blinding randomness.
666        let ciphertext = vec![0; k];
667        let expected = key.decrypt(Pkcs1v15Encrypt, &ciphertext).unwrap();
668        assert!(expected.len() <= k - 11);
669        assert_eq!(
670            typed.decrypt_with_rng(&mut rng, &ciphertext).unwrap(),
671            expected
672        );
673        assert_eq!(typed.decrypt(&ciphertext).unwrap(), expected);
674    }
675
676    #[test]
677    fn implicit_rejection_preserves_rng_errors() {
678        struct FailingRng;
679        impl rand_core::TryRng for FailingRng {
680            type Error = Error;
681            fn try_next_u32(&mut self) -> Result<u32> {
682                Err(Error::Rng)
683            }
684            fn try_next_u64(&mut self) -> Result<u64> {
685                Err(Error::Rng)
686            }
687            fn try_fill_bytes(&mut self, _: &mut [u8]) -> Result<()> {
688                Err(Error::Rng)
689            }
690        }
691        impl TryCryptoRng for FailingRng {}
692        let key = get_private_key();
693        let ciphertext = vec![0; key.size()];
694        assert_eq!(
695            Pkcs1v15Encrypt.decrypt(Some(&mut FailingRng), &key, &ciphertext),
696            Err(Error::Rng)
697        );
698    }
699
700    #[test]
701    fn test_encrypt_decrypt_pkcs1v15_traits() {
702        let mut rng = ChaCha8Rng::from_seed([42; 32]);
703        let priv_key = get_private_key();
704        let k = priv_key.size();
705        let decrypting_key = DecryptingKey::new(priv_key);
706
707        for i in 1..100 {
708            let mut input = vec![0u8; i * 8];
709            rng.fill_bytes(&mut input);
710            if input.len() > k - 11 {
711                input = input[0..k - 11].to_vec();
712            }
713
714            let encrypting_key = decrypting_key.encrypting_key();
715            let ciphertext = encrypting_key.encrypt_with_rng(&mut rng, &input).unwrap();
716            assert_ne!(input, ciphertext);
717
718            let blind: bool = rng.next_u32() < (1u32 << 31);
719            let plaintext = if blind {
720                decrypting_key
721                    .decrypt_with_rng(&mut rng, &ciphertext)
722                    .unwrap()
723            } else {
724                decrypting_key.decrypt(&ciphertext).unwrap()
725            };
726            assert_eq!(input, plaintext);
727        }
728    }
729
730    #[rstest]
731    #[case("Test.\n", hex!(
732        "a4f3fa6ea93bcdd0c57be020c1193ecbfd6f200a3d95c409769b029578fa0e33"
733        "6ad9a347600e40d3ae823b8c7e6bad88cc07c1d54c3a1523cbbb6d58efc362ae"))
734    ]
735    fn test_sign_pkcs1v15(#[case] text: &str, #[case] expected: [u8; 64]) {
736        let priv_key = get_private_key();
737
738        let digest = Sha1::digest(text.as_bytes()).to_vec();
739
740        let out = priv_key.sign(Pkcs1v15Sign::new::<Sha1>(), &digest).unwrap();
741        assert_ne!(out, digest);
742        assert_eq!(out, expected);
743
744        let mut rng = ChaCha8Rng::from_seed([42; 32]);
745        let out2 = priv_key
746            .sign_with_rng(&mut rng, Pkcs1v15Sign::new::<Sha1>(), &digest)
747            .unwrap();
748        assert_eq!(out2, expected);
749    }
750
751    #[rstest]
752    #[case("Test.\n", hex!(
753        "a4f3fa6ea93bcdd0c57be020c1193ecbfd6f200a3d95c409769b029578fa0e33"
754        "6ad9a347600e40d3ae823b8c7e6bad88cc07c1d54c3a1523cbbb6d58efc362ae"))
755    ]
756    fn test_sign_pkcs1v15_signer(#[case] text: &str, #[case] expected: [u8; 64]) {
757        let priv_key = get_private_key();
758
759        let signing_key = SigningKey::<Sha1>::new(priv_key);
760        let out = signing_key.sign(text.as_bytes()).to_bytes();
761        assert_ne!(out.as_ref(), text.as_bytes());
762        assert_ne!(out.as_ref(), &Sha1::digest(text.as_bytes()).to_vec());
763        assert_eq!(out.as_ref(), expected);
764
765        let mut rng = ChaCha8Rng::from_seed([42; 32]);
766        let out2 = signing_key
767            .sign_with_rng(&mut rng, text.as_bytes())
768            .to_bytes();
769        assert_eq!(out2.as_ref(), expected);
770    }
771
772    #[rstest]
773    #[case("Test.\n", hex!(
774        "2ffae3f3e130287b3a1dcb320e46f52e8f3f7969b646932273a7e3a6f2a182ea"
775        "02d42875a7ffa4a148aa311f9e4b562e4e13a2223fb15f4e5bf5f2b206d9451b"))
776    ]
777    fn test_sign_pkcs1v15_signer_sha2_256(#[case] text: &str, #[case] expected: [u8; 64]) {
778        let priv_key = get_private_key();
779        let signing_key = SigningKey::<Sha256>::new(priv_key);
780
781        let out = signing_key.sign(text.as_bytes()).to_bytes();
782        assert_ne!(out.as_ref(), text.as_bytes());
783        assert_eq!(out.as_ref(), expected);
784
785        let mut rng = ChaCha8Rng::from_seed([42; 32]);
786        let out2 = signing_key
787            .sign_with_rng(&mut rng, text.as_bytes())
788            .to_bytes();
789        assert_eq!(out2.as_ref(), expected);
790    }
791
792    #[rstest]
793    #[case("Test.\n", hex!(
794        "55e9fba3354dfb51d2c8111794ea552c86afc2cab154652c03324df8c2c51ba7"
795        "2ff7c14de59a6f9ba50d90c13a7537cc3011948369f1f0ec4a49d21eb7e723f9"))
796    ]
797    fn test_sign_pkcs1v15_signer_sha3_256(#[case] text: &str, #[case] expected: [u8; 64]) {
798        let priv_key = get_private_key();
799        let signing_key = SigningKey::<Sha3_256>::new(priv_key);
800
801        let out = signing_key.sign(text.as_bytes()).to_bytes();
802        assert_ne!(out.as_ref(), text.as_bytes());
803        assert_eq!(out.as_ref(), expected);
804
805        let mut rng = ChaCha8Rng::from_seed([42; 32]);
806        let out2 = signing_key
807            .sign_with_rng(&mut rng, text.as_bytes())
808            .to_bytes();
809        assert_eq!(out2.as_ref(), expected);
810    }
811
812    #[rstest]
813    #[case(
814        "Test.\n",
815        hex!(
816            "a4f3fa6ea93bcdd0c57be020c1193ecbfd6f200a3d95c409769b029578fa0e33"
817            "6ad9a347600e40d3ae823b8c7e6bad88cc07c1d54c3a1523cbbb6d58efc362ae"
818        )
819    )]
820    fn test_sign_pkcs1v15_digest_signer(#[case] text: &str, #[case] expected: [u8; 64]) {
821        let priv_key = get_private_key();
822        let signing_key = SigningKey::new(priv_key);
823
824        let mut digest = Sha1::new();
825        digest.update(text.as_bytes());
826        let out = signing_key
827            .sign_digest(|digest: &mut Sha1| digest.update(text.as_bytes()))
828            .to_bytes();
829        assert_ne!(out.as_ref(), text.as_bytes());
830        assert_ne!(out.as_ref(), &Sha1::digest(text.as_bytes()).to_vec());
831        assert_eq!(out.as_ref(), expected);
832
833        let mut rng = ChaCha8Rng::from_seed([42; 32]);
834        let out2 = signing_key
835            .sign_digest_with_rng(&mut rng, |digest: &mut Sha1| digest.update(text.as_bytes()))
836            .to_bytes();
837        assert_eq!(out2.as_ref(), expected);
838    }
839
840    #[rstest]
841    #[case(
842        "Test.\n",
843        hex!(
844            "a4f3fa6ea93bcdd0c57be020c1193ecbfd6f200a3d95c409769b029578fa0e33"
845            "6ad9a347600e40d3ae823b8c7e6bad88cc07c1d54c3a1523cbbb6d58efc362ae"
846        ),
847        true
848    )]
849    #[case(
850        "Test.\n",
851        hex!(
852            "a4f3fa6ea93bcdd0c57be020c1193ecbfd6f200a3d95c409769b029578fa0e33"
853            "6ad9a347600e40d3ae823b8c7e6bad88cc07c1d54c3a1523cbbb6d58efc362af"
854        ),
855        false
856    )]
857    fn test_verify_pkcs1v15(#[case] text: &str, #[case] sig: [u8; 64], #[case] expected: bool) {
858        let priv_key = get_private_key();
859        let pub_key: PublicKey = priv_key.into();
860
861        let digest = Sha1::digest(text.as_bytes()).to_vec();
862
863        let result = pub_key.verify(Pkcs1v15Sign::new::<Sha1>(), &digest, &sig);
864        match expected {
865            true => result.expect("failed to verify"),
866            false => {
867                result.expect_err("expected verifying error");
868            }
869        }
870    }
871
872    #[rstest]
873    #[case(
874        "Test.\n",
875        hex!(
876            "a4f3fa6ea93bcdd0c57be020c1193ecbfd6f200a3d95c409769b029578fa0e33"
877            "6ad9a347600e40d3ae823b8c7e6bad88cc07c1d54c3a1523cbbb6d58efc362ae"
878        ),
879        true
880    )]
881    #[case(
882        "Test.\n",
883        hex!(
884            "a4f3fa6ea93bcdd0c57be020c1193ecbfd6f200a3d95c409769b029578fa0e33"
885            "6ad9a347600e40d3ae823b8c7e6bad88cc07c1d54c3a1523cbbb6d58efc362af"
886        ),
887        false
888    )]
889    fn test_verify_pkcs1v15_signer(
890        #[case] text: &str,
891        #[case] sig: [u8; 64],
892        #[case] expected: bool,
893    ) {
894        let priv_key = get_private_key();
895
896        let pub_key: PublicKey = priv_key.into();
897        let verifying_key = VerifyingKey::<Sha1>::new(pub_key);
898
899        let result = verifying_key.verify(
900            text.as_bytes(),
901            &Signature::try_from(sig.as_slice()).unwrap(),
902        );
903        match expected {
904            true => result.expect("failed to verify"),
905            false => {
906                result.expect_err("expected verifying error");
907            }
908        }
909    }
910
911    #[rstest]
912    #[case(
913        "Test.\n",
914        hex!(
915            "a4f3fa6ea93bcdd0c57be020c1193ecbfd6f200a3d95c409769b029578fa0e33"
916            "6ad9a347600e40d3ae823b8c7e6bad88cc07c1d54c3a1523cbbb6d58efc362ae"
917        ),
918        true
919    )]
920    #[case(
921        "Test.\n",
922        hex!(
923            "a4f3fa6ea93bcdd0c57be020c1193ecbfd6f200a3d95c409769b029578fa0e33"
924            "6ad9a347600e40d3ae823b8c7e6bad88cc07c1d54c3a1523cbbb6d58efc362af"
925        ),
926        false
927    )]
928    fn test_verify_pkcs1v15_digest_signer(
929        #[case] text: &str,
930        #[case] sig: [u8; 64],
931        #[case] expected: bool,
932    ) {
933        let priv_key = get_private_key();
934
935        let pub_key: PublicKey = priv_key.into();
936        let verifying_key = VerifyingKey::new(pub_key);
937
938        let result = verifying_key.verify_digest(
939            |digest: &mut Sha1| {
940                digest.update(text.as_bytes());
941                Ok(())
942            },
943            &Signature::try_from(sig.as_slice()).unwrap(),
944        );
945        match expected {
946            true => result.expect("failed to verify"),
947            false => {
948                result.expect_err("expected verifying error");
949            }
950        }
951    }
952
953    #[test]
954    fn test_unpadded_signature() {
955        let msg = b"Thu Dec 19 18:06:16 EST 2013\n";
956        let expected_sig = Base64::decode_vec("pX4DR8azytjdQ1rtUiC040FjkepuQut5q2ZFX1pTjBrOVKNjgsCDyiJDGZTCNoh9qpXYbhl7iEym30BWWwuiZg==").unwrap();
957        let priv_key = get_private_key();
958
959        let sig = priv_key.sign(Pkcs1v15Sign::new_unprefixed(), msg).unwrap();
960        assert_eq!(expected_sig, sig);
961
962        let pub_key: PublicKey = priv_key.into();
963        pub_key
964            .verify(Pkcs1v15Sign::new_unprefixed(), msg, &sig)
965            .expect("failed to verify");
966    }
967
968    #[test]
969    fn test_unpadded_signature_hazmat() {
970        let msg = b"Thu Dec 19 18:06:16 EST 2013\n";
971        let expected_sig = Base64::decode_vec("pX4DR8azytjdQ1rtUiC040FjkepuQut5q2ZFX1pTjBrOVKNjgsCDyiJDGZTCNoh9qpXYbhl7iEym30BWWwuiZg==").unwrap();
972        let priv_key = get_private_key();
973
974        let signing_key = SigningKey::<Sha1>::new_unprefixed(priv_key);
975        let sig = signing_key
976            .sign_prehash(msg)
977            .expect("Failure during sign")
978            .to_bytes();
979        assert_eq!(sig.as_ref(), expected_sig);
980
981        let verifying_key = signing_key.verifying_key();
982        verifying_key
983            .verify_prehash(msg, &Signature::try_from(expected_sig.as_slice()).unwrap())
984            .expect("failed to verify");
985    }
986}