Skip to main content

rsa/
private_key.rs

1//! RSA private key type.
2
3use alloc::vec::Vec;
4use core::fmt;
5use core::hash::{Hash, Hasher};
6
7use crate::algorithms::generate::{generate_multi_prime_key_with_exp, generate_prime_with_rng};
8use crate::algorithms::rsa::{
9    compute_modulus, compute_private_exponent_carmicheal, compute_private_exponent_euler_totient,
10    recover_primes, to_monty,
11};
12#[cfg(not(feature = "getrandom"))]
13use crate::dummy_rng::DummyRng;
14use crate::errors::{Error, Result};
15use crate::traits::keys::{CrtValue, PrivateKeyParts, PublicKeyParts};
16use crate::traits::{PaddingScheme, SignatureScheme};
17use crate::{Generate, PublicKey, public_key};
18
19use crypto_bigint::{
20    BoxedUint, Choice, ConcatenatingMul, CtEq, CtLt, Integer, NonZero, Odd, Resize,
21    modular::{BoxedMontyForm, BoxedMontyParams},
22};
23use rand_core::TryCryptoRng;
24use zeroize::{Zeroize, ZeroizeOnDrop};
25
26#[cfg(feature = "serde")]
27use {
28    pkcs8::{DecodePrivateKey, EncodePrivateKey},
29    serdect::serde::{Deserialize, Serialize, de, ser},
30};
31
32/// Type we use for representing secret prime values.
33pub(crate) type SecretPrime = crypto_bigint::modular::MontyParams<BoxedUint>;
34
35/// Represents a whole RSA key, public and private parts.
36#[derive(Clone)]
37pub struct PrivateKey {
38    /// Public components of the private key.
39    pubkey_components: PublicKey,
40    /// Private exponent.
41    pub(crate) d: BoxedUint,
42    /// Prime factors of N, contains >= 2 elements.
43    pub(crate) primes: Vec<Odd<BoxedUint>>,
44    /// Precomputed values to speed up private operations.
45    pub(crate) precomputed: Option<PrecomputedValues>,
46}
47
48impl fmt::Debug for PrivateKey {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        let precomputed = if self.precomputed.is_some() {
51            "Some(...)"
52        } else {
53            "None"
54        };
55        f.debug_struct("PrivateKey")
56            .field("pubkey_components", &self.pubkey_components)
57            .field("d", &"...")
58            .field("primes", &"&[...]")
59            .field("precomputed", &precomputed)
60            .finish()
61    }
62}
63
64impl Eq for PrivateKey {}
65impl PartialEq for PrivateKey {
66    #[inline]
67    fn eq(&self, other: &PrivateKey) -> bool {
68        self.pubkey_components == other.pubkey_components
69            && self.d == other.d
70            && self.primes == other.primes
71    }
72}
73
74impl AsRef<PublicKey> for PrivateKey {
75    fn as_ref(&self) -> &PublicKey {
76        &self.pubkey_components
77    }
78}
79
80impl Hash for PrivateKey {
81    fn hash<H: Hasher>(&self, state: &mut H) {
82        // Domain separator for RSA private keys
83        state.write(b"PrivateKey");
84        Hash::hash(&self.pubkey_components, state);
85    }
86}
87
88impl Drop for PrivateKey {
89    fn drop(&mut self) {
90        self.d.zeroize();
91        self.primes.zeroize();
92        self.precomputed.zeroize();
93    }
94}
95
96impl ZeroizeOnDrop for PrivateKey {}
97
98#[derive(Clone)]
99pub(crate) struct PrecomputedValues {
100    /// Montgomery params for `p`
101    pub(crate) p: SecretPrime,
102    /// Montgomery params for `q`
103    pub(crate) q: SecretPrime,
104    /// D mod (P-1)
105    pub(crate) dp: BoxedUint,
106    /// D mod (Q-1)
107    pub(crate) dq: BoxedUint,
108    /// Q^-1 mod P
109    pub(crate) qinv: BoxedMontyForm,
110}
111
112impl ZeroizeOnDrop for PrecomputedValues {}
113
114impl Zeroize for PrecomputedValues {
115    fn zeroize(&mut self) {
116        self.p.zeroize();
117        self.q.zeroize();
118        self.dp.zeroize();
119        self.dq.zeroize();
120    }
121}
122
123impl Drop for PrecomputedValues {
124    fn drop(&mut self) {
125        self.zeroize();
126    }
127}
128
129impl PublicKeyParts for PrivateKey {
130    fn n(&self) -> &NonZero<BoxedUint> {
131        &self.pubkey_components.n
132    }
133
134    fn e(&self) -> &BoxedUint {
135        &self.pubkey_components.e
136    }
137
138    fn n_params(&self) -> &BoxedMontyParams {
139        &self.pubkey_components.n_params
140    }
141}
142
143impl PrivateKey {
144    /// Default modulus size in bits used by [`Generate`].
145    ///
146    /// A 3072-bit RSA modulus provides an estimated 128-bit security strength according to
147    /// [NIST SP 800-57 Part 1 Rev. 5, Table 2](https://doi.org/10.6028/NIST.SP.800-57pt1r5).
148    pub const DEFAULT_BITS: usize = 3072;
149
150    /// Default exponent for RSA keys.
151    const EXP: u64 = 65537;
152
153    /// Generate a new RSA key pair with a modulus of the given bit size using the passed in `rng`.
154    ///
155    /// # Errors
156    /// - If `bit_size` is lower than the minimum 1024-bits.
157    /// - If the RNG fails, returns [`Error::Rng`].
158    pub fn new<R: TryCryptoRng + ?Sized>(rng: &mut R, bit_size: usize) -> Result<Self> {
159        Self::new_with_exp(rng, bit_size, Self::EXP.into())
160    }
161
162    /// Generate a new RSA key pair of the given bit size.
163    ///
164    /// <div class="warning">
165    /// <b>⚠️Warning: Hazmat!</b>
166    /// This version does not apply minimum key size checks, and as such may generate keys
167    /// which are insecure!
168    /// </div>
169    #[cfg(feature = "hazmat")]
170    #[allow(clippy::missing_errors_doc, reason = "TODO")]
171    pub fn new_unchecked<R: TryCryptoRng + ?Sized>(rng: &mut R, bit_size: usize) -> Result<Self> {
172        Self::new_with_exp_unchecked(rng, bit_size, Self::EXP.into())
173    }
174
175    /// Generate a new RSA key pair of the given bit size and the public exponent
176    /// using the passed in `rng`.
177    ///
178    /// Unless you have specific needs, you should use [`PrivateKey::new`] instead.
179    #[allow(clippy::missing_errors_doc, reason = "TODO")]
180    pub fn new_with_exp<R: TryCryptoRng + ?Sized>(
181        rng: &mut R,
182        bit_size: usize,
183        exp: BoxedUint,
184    ) -> Result<PrivateKey> {
185        if bit_size < PublicKey::MIN_SIZE {
186            return Err(Error::ModulusTooSmall);
187        }
188
189        let components = generate_multi_prime_key_with_exp(rng, 2, bit_size, exp)?;
190        PrivateKey::from_components(
191            components.n.get(),
192            components.e,
193            components.d,
194            components.primes,
195        )
196    }
197
198    /// Generate a new RSA key pair of the given bit size and the public exponent
199    /// using the passed in `rng`.
200    ///
201    /// Unless you have specific needs, you should use [`PrivateKey::new`] instead.
202    ///
203    /// <div class="warning">
204    /// <b>⚠️Warning: Hazmat!</b>
205    /// This version does not apply minimum key size checks, and as such may generate keys
206    /// which are insecure!
207    /// </div>
208    #[cfg(feature = "hazmat")]
209    #[allow(clippy::missing_errors_doc, reason = "TODO")]
210    pub fn new_with_exp_unchecked<R: TryCryptoRng + ?Sized>(
211        rng: &mut R,
212        bit_size: usize,
213        exp: BoxedUint,
214    ) -> Result<PrivateKey> {
215        let components = generate_multi_prime_key_with_exp(rng, 2, bit_size, exp)?;
216        PrivateKey::from_components(
217            components.n.get(),
218            components.e,
219            components.d,
220            components.primes,
221        )
222    }
223
224    /// Private helper function that constructs an RSA key pair from components
225    /// WITHOUT performing any validation or precomputation.
226    ///
227    /// This is the shared implementation used by `from_components` and
228    /// `from_components_with_large_exponent`.
229    ///
230    /// Callers are responsible for:
231    /// 1. Validating the key
232    /// 2. Calling `precompute()` after validation, propagating any error
233    fn from_components_inner(
234        n: BoxedUint,
235        e: BoxedUint,
236        d: BoxedUint,
237        mut primes: Vec<BoxedUint>,
238        wide_primes: bool,
239    ) -> Result<PrivateKey> {
240        let n = Odd::new(n).into_option().ok_or(Error::InvalidModulus)?;
241
242        // The modulus may come in padded with zeros, shorten it
243        // to ensure optimal performance of arithmetic operations.
244        let n_bits = n.bit_width_vartime();
245        let n = n.resize_unchecked(n_bits);
246
247        // Use a public storage width even when the caller supplies a short or zero-padded `d`.
248        // Check for truncation before resizing so an oversized exponent cannot become valid.
249        let d = d
250            .try_resize(n.bits_precision())
251            .ok_or(Error::InvalidExponent)?;
252
253        let n_params = BoxedMontyParams::new(n.clone());
254        let n_c = NonZero::new(n.get())
255            .into_option()
256            .ok_or(Error::InvalidModulus)?;
257
258        match primes.len() {
259            0 => {
260                // Recover `p` and `q` from `d`.
261                // See method in Appendix C.2: https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Br2.pdf
262                let (p, q) = recover_primes(&n_c, &e, &d)?;
263                primes.push(p);
264                primes.push(q);
265            }
266            1 => return Err(Error::NprimesTooSmall),
267            _ => {
268                // Check that the product of primes matches the modulus.
269                // This also ensures that `bit_precision` of each prime is <= that of the modulus,
270                // and `bit_precision` of their product is >= that of the modulus.
271                if primes
272                    .iter()
273                    .fold(BoxedUint::one(), |acc, p| acc.concatenating_mul(&p))
274                    != n_c.as_ref()
275                {
276                    return Err(Error::InvalidModulus);
277                }
278            }
279        }
280
281        // The caller's public policy and the public modulus determine every prime's width.
282        // Do not automatically select a wider policy based on the secret values of the primes.
283        // Multiprime operations use the non-CRT path and retain modulus-width factors.
284        let prime_bits = if wide_primes || primes.len() > 2 {
285            n_bits
286        } else {
287            n_bits.div_ceil(2)
288        };
289
290        let primes = primes
291            .into_iter()
292            .map(|p| {
293                if p.bit_width() > prime_bits {
294                    return Err(Error::InvalidPrime);
295                }
296
297                Odd::new(p.resize_unchecked(prime_bits))
298                    .into_option()
299                    .ok_or(Error::InvalidPrime)
300            })
301            .collect::<Result<Vec<_>>>()?;
302
303        let k = PrivateKey {
304            pubkey_components: PublicKey {
305                n: n_c,
306                e,
307                n_params,
308            },
309            d,
310            primes,
311            precomputed: None,
312        };
313
314        Ok(k)
315    }
316
317    /// Constructs an RSA key pair from individual components, accepting exponents outside
318    /// the normal size bounds.
319    ///
320    /// See [`PrivateKey::from_components`] for an explanation on the parameters.
321    ///
322    /// <div class="warning">
323    /// <b>⚠️ Warning: Hazmat!</b>
324    ///
325    /// This method accepts public exponents outside the standard bounds (2 ≤ e ≤ 2^33-1),
326    /// but still performs full cryptographic validation to ensure the key is mathematically
327    /// correct (i.e., verifies that de ≡ 1 mod λ(n)).
328    ///
329    /// **Note:** This method is dangerous as it can be used as a DOS vector if used with
330    /// untrusted input: <https://www.imperialviolet.org/2012/03/17/rsados.html>
331    ///
332    /// This is intended for interoperating with systems that use non-standard exponents
333    /// or loading legacy keys. Use [`PrivateKey::from_components`] for standard key
334    /// construction.
335    /// </div>
336    #[cfg(feature = "hazmat")]
337    #[allow(clippy::missing_errors_doc, reason = "TODO")]
338    pub fn from_components_with_large_exponent(
339        n: BoxedUint,
340        e: BoxedUint,
341        d: BoxedUint,
342        primes: Vec<BoxedUint>,
343    ) -> Result<PrivateKey> {
344        let mut k = Self::from_components_inner(n, e, d, primes, false)?;
345
346        // Validate everything except exponent size bounds.
347        validate_skip_exponent_size(&k)?;
348        k.precompute()?;
349
350        Ok(k)
351    }
352
353    /// Constructs an RSA key pair from individual components:
354    ///
355    /// - `n`: RSA modulus
356    /// - `e`: public exponent (i.e. encrypting exponent)
357    /// - `d`: private exponent (i.e. decrypting exponent)
358    /// - `primes`: distinct prime factors of `n`: typically two primes `p` and `q`. More than two
359    ///   primes can be provided for multiprime RSA, however this is generally not recommended.
360    ///   If no `primes` are provided, a prime factor recovery algorithm will be employed to attempt
361    ///   to recover the factors (as described in [NIST SP 800-56B Revision 2] Appendix C.2).
362    ///   This algorithm only works if there are just two prime factors `p` and `q` (as opposed to
363    ///   multiprime), and `e` is between 2^16 and 2^256.
364    ///
365    /// For two-prime keys, each prime must fit in `ceil(bit_length(n) / 2)` bits. Both primes
366    /// and their CRT exponents use this public-derived storage width, rounded up to whole limbs.
367    /// Use [`Self::from_components_with_wide_primes`] to explicitly import unbalanced factors.
368    /// Multiprime keys use modulus-width factors and the non-CRT private operation.
369    ///
370    ///  [NIST SP 800-56B Revision 2]: https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Br2.pdf
371    #[allow(clippy::missing_errors_doc, reason = "TODO")]
372    pub fn from_components(
373        n: BoxedUint,
374        e: BoxedUint,
375        d: BoxedUint,
376        primes: Vec<BoxedUint>,
377    ) -> Result<PrivateKey> {
378        let mut k = Self::from_components_inner(n, e, d, primes, false)?;
379        k.validate()?;
380        k.precompute()?;
381        Ok(k)
382    }
383
384    /// Constructs a key using public-modulus-width storage for every prime and CRT exponent.
385    ///
386    /// This explicitly supports unbalanced prime factors which do not fit the half-modulus bit
387    /// bound of [`Self::from_components`]. It is slower than ordinary two-prime CRT arithmetic.
388    /// The width policy must be chosen as public configuration, not by inspecting secret factor
389    /// sizes or retrying a failed half-width import with this constructor.
390    ///
391    /// Encoded-key decoding uses the ordinary half-width policy. For unbalanced encoded keys,
392    /// decode the components and pass them to this constructor explicitly.
393    #[allow(clippy::missing_errors_doc, reason = "TODO")]
394    pub fn from_components_with_wide_primes(
395        n: BoxedUint,
396        e: BoxedUint,
397        d: BoxedUint,
398        primes: Vec<BoxedUint>,
399    ) -> Result<PrivateKey> {
400        let mut k = Self::from_components_inner(n, e, d, primes, true)?;
401        k.validate()?;
402        k.precompute()?;
403        Ok(k)
404    }
405
406    /// Constructs an RSA key pair from its two primes p and q.
407    ///
408    /// The half-modulus factor bound of [`Self::from_components`] applies.
409    ///
410    /// This will rebuild the private exponent and the modulus.
411    ///
412    /// Private exponent will be rebuilt using the method defined in
413    /// [NIST 800-56B Section 6.2.1](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Br2.pdf#page=47).
414    #[allow(clippy::missing_errors_doc, reason = "TODO")]
415    pub fn from_p_q(p: BoxedUint, q: BoxedUint, public_exponent: BoxedUint) -> Result<PrivateKey> {
416        // RSA factors must be odd and greater than one. Check before deriving n or d.
417        let two = BoxedUint::from(2u64);
418        if (p.ct_lt(&two) | q.ct_lt(&two) | !p.is_odd() | !q.is_odd()).to_bool() {
419            return Err(Error::InvalidPrime);
420        }
421
422        let d = compute_private_exponent_carmicheal(&p, &q, &public_exponent)?;
423        let primes = vec![p, q];
424        let n = compute_modulus(&primes);
425
426        Self::from_components(n.get(), public_exponent, d, primes)
427    }
428
429    /// Constructs an RSA key pair from its primes.
430    ///
431    /// The factor-width policy of [`Self::from_components`] applies.
432    ///
433    /// This will rebuild the private exponent and the modulus.
434    #[allow(clippy::missing_errors_doc, reason = "TODO")]
435    pub fn from_primes(primes: Vec<BoxedUint>, public_exponent: BoxedUint) -> Result<PrivateKey> {
436        if primes.len() < 2 {
437            return Err(Error::NprimesTooSmall);
438        }
439
440        // RSA factors must be odd and greater than one. Check before deriving n or d.
441        let two = BoxedUint::from(2u64);
442        let invalid_primes = primes.iter().fold(Choice::FALSE, |invalid, p| {
443            invalid | p.ct_lt(&two) | !p.is_odd()
444        });
445
446        if invalid_primes.to_bool() {
447            return Err(Error::InvalidPrime);
448        }
449
450        let n = compute_modulus(&primes);
451        let d = compute_private_exponent_euler_totient(&primes, &public_exponent)?;
452
453        Self::from_components(n.get(), public_exponent, d, primes)
454    }
455
456    /// Get the public key from the private key.
457    ///
458    /// Specific alternative to [`AsRef::as_ref`].
459    #[must_use]
460    pub fn as_public_key(&self) -> &PublicKey {
461        &self.pubkey_components
462    }
463
464    /// Get the public key from the private key, cloning `n` and `e`.
465    ///
466    /// Generally this is not needed since `PrivateKey` implements the `PublicKey` trait,
467    /// but it can occasionally be useful to discard the private information entirely.
468    #[must_use]
469    pub fn to_public_key(&self) -> PublicKey {
470        self.pubkey_components.clone()
471    }
472
473    /// Performs some calculations to speed up private key operations.
474    ///
475    /// # Errors
476    /// Returns [`Error::InvalidPrime`] if either of the first two factors is one, or if they
477    /// are not coprime and the CRT coefficient cannot be computed.
478    pub fn precompute(&mut self) -> Result<()> {
479        if self.precomputed.is_some() {
480            return Ok(());
481        }
482
483        let d = &self.d;
484        let p = self.primes[0].clone();
485        let q = self.primes[1].clone();
486
487        let p_params = BoxedMontyParams::new(p.clone());
488        let q_params = BoxedMontyParams::new(q.clone());
489
490        let x = NonZero::new(p.wrapping_sub(BoxedUint::one()))
491            .into_option()
492            .ok_or(Error::InvalidPrime)?;
493
494        let dp = d.rem(&x);
495
496        let x = NonZero::new(q.wrapping_sub(BoxedUint::one()))
497            .into_option()
498            .ok_or(Error::InvalidPrime)?;
499        let dq = d.rem(&x);
500
501        let q_mod_p = to_monty(q.as_ref(), &p_params);
502        let qinv = q_mod_p.invert().into_option().ok_or(Error::InvalidPrime)?;
503
504        debug_assert_eq!(dp.bits_precision(), p.bits_precision());
505        debug_assert_eq!(dq.bits_precision(), q.bits_precision());
506        debug_assert_eq!(qinv.bits_precision(), p.bits_precision());
507        debug_assert_eq!(p_params.bits_precision(), p.bits_precision());
508        debug_assert_eq!(q_params.bits_precision(), q.bits_precision());
509
510        // TODO(tarcieri): zeroize intermediate parameters
511        let p = p_params.as_ref().clone();
512        let q = q_params.as_ref().clone();
513        self.precomputed = Some(PrecomputedValues { p, q, dp, dq, qinv });
514        Ok(())
515    }
516
517    /// Clears precomputed values by setting to None
518    pub fn clear_precomputed(&mut self) {
519        self.precomputed = None;
520    }
521
522    /// Compute CRT coefficient: `(1/q) mod p`.
523    #[must_use]
524    pub fn crt_coefficient(&self) -> Option<BoxedUint> {
525        let p = &self.primes[0];
526        let q = &self.primes[1];
527        Option::from(q.invert_odd_mod(p))
528    }
529
530    /// Performs basic sanity checks on the key.
531    /// Returns `Ok(())` if everything is good, otherwise an appropriate error.
532    #[allow(clippy::missing_errors_doc, reason = "TODO")]
533    pub fn validate(&self) -> Result<()> {
534        public_key::check_public(self)?;
535        validate_private_key_parts(self)?;
536        Ok(())
537    }
538
539    /// Decrypt the given message.
540    ///
541    /// With the `getrandom` feature (enabled by default), uses the operating system RNG for
542    /// RSA blinding. Without this feature, decryption is unblinded; use [`Self::decrypt_blinded`]
543    /// to supply an RNG explicitly.
544    ///
545    /// [`Pkcs1v15Encrypt`][crate::Pkcs1v15Encrypt] uses implicit rejection: invalid padding returns
546    /// deterministic synthetic plaintext, not an error. The enclosing protocol must authenticate
547    /// the returned message.
548    #[allow(clippy::missing_errors_doc, reason = "TODO")]
549    pub fn decrypt<P: PaddingScheme>(&self, padding: P, ciphertext: &[u8]) -> Result<Vec<u8>> {
550        #[cfg(feature = "getrandom")]
551        {
552            padding.decrypt(
553                Some(&mut crypto_common::getrandom::SysRng),
554                self,
555                ciphertext,
556            )
557        }
558        #[cfg(not(feature = "getrandom"))]
559        {
560            padding.decrypt(Option::<&mut DummyRng>::None, self, ciphertext)
561        }
562    }
563
564    /// Decrypt the given message.
565    ///
566    /// Uses `rng` to blind the decryption process.
567    ///
568    /// [`Pkcs1v15Encrypt`][crate::Pkcs1v15Encrypt] has the same implicit-rejection
569    /// behavior as [`Self::decrypt`], independently of the blinding randomness.
570    #[allow(clippy::missing_errors_doc, reason = "TODO")]
571    pub fn decrypt_blinded<R: TryCryptoRng + ?Sized, P: PaddingScheme>(
572        &self,
573        rng: &mut R,
574        padding: P,
575        ciphertext: &[u8],
576    ) -> Result<Vec<u8>> {
577        padding.decrypt(Some(rng), self, ciphertext)
578    }
579
580    /// Sign the given digest.
581    ///
582    /// With the `getrandom` feature (enabled by default), supplies the operating system RNG for
583    /// RSA blinding and any randomness required by the signature scheme. Without this feature,
584    /// use [`Self::sign_with_rng`] to supply an RNG explicitly.
585    #[allow(clippy::missing_errors_doc, reason = "TODO")]
586    pub fn sign<S: SignatureScheme>(&self, padding: S, digest_in: &[u8]) -> Result<Vec<u8>> {
587        #[cfg(feature = "getrandom")]
588        {
589            padding.sign(Some(&mut crypto_common::getrandom::SysRng), self, digest_in)
590        }
591        #[cfg(not(feature = "getrandom"))]
592        {
593            padding.sign(Option::<&mut DummyRng>::None, self, digest_in)
594        }
595    }
596
597    /// Sign the given digest using the provided `rng`, which is used in the
598    /// following ways depending on the [`SignatureScheme`]:
599    ///
600    /// - [`Pkcs1v15Sign`][`crate::Pkcs1v15Sign`] padding: uses the RNG
601    ///   to mask the private key operation with random blinding, which helps
602    ///   mitigate sidechannel attacks.
603    /// - [`Pss`][`crate::Pss`] always requires randomness. Use
604    ///   [`Pss::new`][`crate::Pss::new`] for a standard RSASSA-PSS signature with
605    ///   RSA base blinding enabled by default.
606    #[allow(clippy::missing_errors_doc, reason = "TODO")]
607    pub fn sign_with_rng<R: TryCryptoRng + ?Sized, S: SignatureScheme>(
608        &self,
609        rng: &mut R,
610        padding: S,
611        digest_in: &[u8],
612    ) -> Result<Vec<u8>> {
613        padding.sign(Some(rng), self, digest_in)
614    }
615}
616
617/// Generate a key with a [`Self::DEFAULT_BITS`]-bit modulus and public exponent 65537.
618impl Generate for PrivateKey {
619    fn try_generate_from_rng<R: TryCryptoRng + ?Sized>(
620        rng: &mut R,
621    ) -> core::result::Result<Self, R::Error> {
622        let Ok(prime_bits) = u32::try_from(Self::DEFAULT_BITS.div_euclid(2)) else {
623            unreachable!("default prime size fits in u32");
624        };
625
626        loop {
627            // Setting the top two bits of both primes ensures a full-size modulus.
628            let p = generate_prime_with_rng(rng, prime_bits)?;
629            let q = generate_prime_with_rng(rng, prime_bits)?;
630
631            match Self::from_primes(vec![p, q], Self::EXP.into()) {
632                Ok(key) => return Ok(key),
633                // Retry if the primes coincide or the public exponent is not invertible.
634                Err(Error::InvalidPrime) => continue,
635                Err(err) => unreachable!("invalid generated RSA key: {err}"),
636            }
637        }
638    }
639}
640
641impl PrivateKeyParts for PrivateKey {
642    fn d(&self) -> &BoxedUint {
643        &self.d
644    }
645
646    fn primes(&self) -> &[Odd<BoxedUint>] {
647        &self.primes
648    }
649
650    fn dp(&self) -> Option<&BoxedUint> {
651        self.precomputed.as_ref().map(|p| &p.dp)
652    }
653
654    fn dq(&self) -> Option<&BoxedUint> {
655        self.precomputed.as_ref().map(|p| &p.dq)
656    }
657
658    fn qinv(&self) -> Option<&BoxedMontyForm> {
659        self.precomputed.as_ref().map(|p| &p.qinv)
660    }
661
662    fn crt_values(&self) -> Option<&[CrtValue]> {
663        None
664    }
665
666    fn p(&self) -> Option<&SecretPrime> {
667        self.precomputed.as_ref().map(|p| &p.p)
668    }
669
670    fn q(&self) -> Option<&SecretPrime> {
671        self.precomputed.as_ref().map(|p| &p.q)
672    }
673}
674
675/// Helper function that validates the private key structure and cryptographic correctness.
676///
677/// This performs the structural and mathematical validation checks that are common to both
678/// `validate()` and `validate_skip_exponent_size()`.
679fn validate_private_key_parts(key: &PrivateKey) -> Result<()> {
680    // RFC8017 §3.2 requires `d < n`, even if a larger exponent satisfies the congruences below.
681    // Preserve the supplied d rather than reducing it.
682    if key.d >= key.n().as_ref() {
683        return Err(Error::InvalidExponent);
684    }
685
686    // Check that Πprimes == n.
687    let mut m = BoxedUint::one_with_precision(key.pubkey_components.n.bits_precision());
688    let two = BoxedUint::from(2u64);
689    let mut invalid_primes = Choice::FALSE;
690    for (i, prime) in key.primes.iter().enumerate() {
691        // Any primes <= 1 will cause divide-by-zero panics later.
692        invalid_primes |= prime.as_ref().ct_lt(&two);
693
694        // RFC 8017 §3.2 requires distinct prime factors, including for multiprime RSA.
695        for other in &key.primes[..i] {
696            invalid_primes |= prime.ct_eq(other);
697        }
698        m = m.wrapping_mul(prime.as_ref());
699    }
700
701    // Reveal only whether the factors are invalid, not which factor or pair failed.
702    if invalid_primes.to_bool() {
703        return Err(Error::InvalidPrime);
704    }
705
706    if m.ct_ne(key.pubkey_components.n.as_ref()).to_bool() {
707        return Err(Error::InvalidModulus);
708    }
709
710    // Check that de ≡ 1 mod p-1, for each prime.
711    // This implies that e is coprime to each p-1 as e has a multiplicative
712    // inverse. Therefore e is coprime to lcm(p-1,q-1,r-1,...) =
713    // exponent(ℤ/nℤ). It also implies that a^de ≡ a mod p as a^(p-1) ≡ 1
714    // mod p. Thus a^de ≡ a mod n for all a coprime to n, as required.
715    let de = key.d.concatenating_mul(&key.pubkey_components.e);
716
717    for prime in &key.primes {
718        let x = NonZero::new(prime.wrapping_sub(BoxedUint::one())).unwrap();
719        let congruence = de.rem(&x);
720        if !congruence.is_one().to_bool() {
721            return Err(Error::InvalidExponent);
722        }
723    }
724
725    Ok(())
726}
727
728/// Validate the private key structure and cryptographic correctness,
729/// skipping only the exponent size bounds checks.
730///
731/// This performs all the same checks as `PrivateKey::validate()` except
732/// it doesn't verify that the exponent is within the standard bounds.
733#[cfg(feature = "hazmat")]
734fn validate_skip_exponent_size(key: &PrivateKey) -> Result<()> {
735    // Check public key properties (without exponent size checks)
736    public_key::check_public_skip_exponent_size(
737        key.pubkey_components.n.as_ref(),
738        &key.pubkey_components.e,
739    )?;
740
741    // Perform common private key validation
742    validate_private_key_parts(key)?;
743
744    Ok(())
745}
746
747#[cfg(feature = "serde")]
748impl Serialize for PrivateKey {
749    fn serialize<S>(&self, serializer: S) -> core::prelude::v1::Result<S::Ok, S::Error>
750    where
751        S: ser::Serializer,
752    {
753        let der = self.to_pkcs8_der().map_err(ser::Error::custom)?;
754        serdect::slice::serialize_hex_lower_or_bin(&der.as_bytes(), serializer)
755    }
756}
757
758#[cfg(feature = "serde")]
759impl<'de> Deserialize<'de> for PrivateKey {
760    fn deserialize<D>(deserializer: D) -> core::prelude::v1::Result<Self, D::Error>
761    where
762        D: de::Deserializer<'de>,
763    {
764        let der_bytes = serdect::slice::deserialize_hex_or_bin_vec(deserializer)?;
765        Self::from_pkcs8_der(&der_bytes).map_err(de::Error::custom)
766    }
767}
768
769#[cfg(test)]
770mod tests {
771    use super::*;
772    use crate::algorithms::rsa::{rsa_decrypt_and_check, rsa_encrypt};
773    use crate::traits::{PrivateKeyParts, PublicKeyParts};
774
775    use hex_literal::hex;
776    use rand::rngs::ChaCha8Rng;
777    use rand_core::SeedableRng;
778
779    #[cfg(feature = "encoding")]
780    use pkcs8::DecodePrivateKey;
781
782    #[test]
783    fn non_coprime_factors_precompute_error() {
784        // Distinct odd composite factors can pass validation: 3 * 19 = 1 mod 8 and mod 14.
785        // However, neither factor is invertible modulo the other, so precomputation fails.
786        for (p, q) in [(9u64, 15u64), (15, 9)] {
787            let n = BoxedUint::from(p * q);
788            let e = BoxedUint::from(3u64);
789            let d = BoxedUint::from(19u64);
790            let primes = vec![BoxedUint::from(p), BoxedUint::from(q)];
791            let mut key = PrivateKey::from_components_inner(
792                n.clone(),
793                e.clone(),
794                d.clone(),
795                primes.clone(),
796                false,
797            )
798            .unwrap();
799            key.validate().unwrap();
800            assert_eq!(key.precompute(), Err(Error::InvalidPrime));
801            assert!(key.precomputed.is_none());
802
803            assert_eq!(
804                PrivateKey::from_components(n.clone(), e.clone(), d.clone(), primes.clone()),
805                Err(Error::InvalidPrime)
806            );
807            assert_eq!(
808                PrivateKey::from_components_with_wide_primes(
809                    n.clone(),
810                    e.clone(),
811                    d.clone(),
812                    primes.clone(),
813                ),
814                Err(Error::InvalidPrime)
815            );
816            #[cfg(feature = "hazmat")]
817            assert_eq!(
818                PrivateKey::from_components_with_large_exponent(n, e.clone(), d, primes.clone()),
819                Err(Error::InvalidPrime)
820            );
821            assert_eq!(
822                PrivateKey::from_p_q(primes[0].clone(), primes[1].clone(), e.clone()),
823                Err(Error::InvalidPrime)
824            );
825            assert_eq!(PrivateKey::from_primes(primes, e), Err(Error::InvalidPrime));
826        }
827    }
828
829    #[test]
830    fn repeated_prime_factors() {
831        // Each d satisfies e*d = 1 mod (p-1) for every supplied factor, so the exponent
832        // checks alone cannot reject these keys. Include duplicates in every pair of a
833        // three-factor key and a duplicate which does not involve either CRT factor.
834        for (factors, d) in [
835            (&[61u64, 61][..], 53u64),
836            (&[61, 61, 53][..], 413),
837            (&[61, 53, 61][..], 413),
838            (&[61, 53, 53][..], 413),
839            (&[61, 53, 47, 47][..], 10553),
840        ] {
841            // Different input precisions must not disguise equal factors.
842            let primes: Vec<_> = factors
843                .iter()
844                .zip([64, 128, 192, 256])
845                .map(|(&p, bits)| BoxedUint::from(p).resize_unchecked(bits))
846                .collect();
847            let n = compute_modulus(&primes).get();
848            let e = BoxedUint::from(17u64);
849            let d = BoxedUint::from(d);
850            let key = PrivateKey::from_components_inner(
851                n.clone(),
852                e.clone(),
853                d.clone(),
854                primes.clone(),
855                false,
856            )
857            .unwrap();
858            assert_eq!(key.validate(), Err(Error::InvalidPrime));
859            assert_eq!(
860                PrivateKey::from_components(n.clone(), e.clone(), d.clone(), primes.clone()),
861                Err(Error::InvalidPrime)
862            );
863            assert_eq!(
864                PrivateKey::from_components_with_wide_primes(
865                    n.clone(),
866                    e.clone(),
867                    d.clone(),
868                    primes.clone(),
869                ),
870                Err(Error::InvalidPrime)
871            );
872            #[cfg(feature = "hazmat")]
873            assert_eq!(
874                PrivateKey::from_components_with_large_exponent(n, e.clone(), d, primes.clone()),
875                Err(Error::InvalidPrime)
876            );
877            if primes.len() == 2 {
878                assert_eq!(
879                    PrivateKey::from_p_q(primes[0].clone(), primes[1].clone(), e.clone()),
880                    Err(Error::InvalidPrime)
881                );
882            }
883            assert_eq!(PrivateKey::from_primes(primes, e), Err(Error::InvalidPrime));
884        }
885    }
886
887    #[test]
888    fn invalid_factors_before_exponent_derivation() {
889        for p in [0u64, 1, 2, 4] {
890            for q in [0u64, 1, 2, 4, 61] {
891                for (p, q) in [(p, q), (q, p)] {
892                    let p = BoxedUint::from(p);
893                    let q = BoxedUint::from(q);
894                    let e = BoxedUint::from(17u64);
895                    assert_eq!(
896                        PrivateKey::from_p_q(p.clone(), q.clone(), e.clone()),
897                        Err(Error::InvalidPrime)
898                    );
899                    assert_eq!(
900                        PrivateKey::from_primes(vec![p, q], e),
901                        Err(Error::InvalidPrime)
902                    );
903                }
904            }
905
906            // Check every position in a multiprime key, including beyond the first two factors.
907            for i in 0..3 {
908                let mut primes = vec![61u64.into(), 53u64.into(), 47u64.into()];
909                primes[i] = BoxedUint::from(p);
910                assert_eq!(
911                    PrivateKey::from_primes(primes, BoxedUint::from(17u64)),
912                    Err(Error::InvalidPrime)
913                );
914            }
915        }
916    }
917
918    #[test]
919    fn key_generation_rejects_repeated_factors() {
920        use core::{convert::Infallible, result::Result};
921        use rand_core::{TryCryptoRng, TryRng};
922
923        // Repeating entropy produces the same prime twice. Bound the entropy budget so retrying
924        // forever on this broken RNG fails the test instead of hanging it.
925        struct RepeatingRng(usize);
926
927        impl TryRng for RepeatingRng {
928            type Error = Infallible;
929
930            fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
931                let mut bytes = [0; 4];
932                self.try_fill_bytes(&mut bytes)?;
933                Ok(u32::from_le_bytes(bytes))
934            }
935
936            fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
937                let mut bytes = [0; 8];
938                self.try_fill_bytes(&mut bytes)?;
939                Ok(u64::from_le_bytes(bytes))
940            }
941
942            fn try_fill_bytes(&mut self, bytes: &mut [u8]) -> Result<(), Self::Error> {
943                self.0 = self
944                    .0
945                    .checked_sub(bytes.len())
946                    .expect("key generation retried");
947                bytes.fill(0xaa);
948                Ok(())
949            }
950        }
951
952        impl TryCryptoRng for RepeatingRng {}
953
954        assert_eq!(
955            PrivateKey::new(&mut RepeatingRng(128), 1024),
956            Err(Error::InvalidPrime)
957        );
958    }
959
960    #[test]
961    fn private_exponent_range_and_identity() {
962        // For `e=17`, these exponents are equivalent modulo `lambda(n)=780`.
963        for (e, d) in [(17u64, 413u64), (17, 2753), (17, 5873), (497, 3233)] {
964            let result = PrivateKey::from_components(
965                BoxedUint::from(3233u64),
966                BoxedUint::from(e),
967                BoxedUint::from(d),
968                vec![BoxedUint::from(61u64), BoxedUint::from(53u64)],
969            );
970            if d < 3233 {
971                assert_eq!(result.unwrap().d(), &BoxedUint::from(d));
972            } else {
973                assert_eq!(result, Err(Error::InvalidExponent));
974            }
975        }
976    }
977
978    #[test]
979    fn test_from_into() {
980        let raw_n = BoxedUint::from(101u64);
981        let n_odd = Odd::new(raw_n.clone()).unwrap();
982        let private_key = PrivateKey {
983            pubkey_components: PublicKey {
984                n: NonZero::new(raw_n.clone()).unwrap(),
985                e: BoxedUint::from(200u64),
986                n_params: BoxedMontyParams::new(n_odd),
987            },
988            d: BoxedUint::from(123u64),
989            primes: vec![],
990            precomputed: None,
991        };
992        let public_key: PublicKey = private_key.into();
993
994        assert_eq!(PublicKeyParts::n(&public_key).as_ref(), &raw_n);
995        assert_eq!(PublicKeyParts::e(&public_key), &BoxedUint::from(200u64));
996        assert_eq!(PublicKeyParts::e_bytes(&public_key), [200].into());
997        assert_eq!(PublicKeyParts::n_bytes(&public_key), [101].into());
998    }
999
1000    fn test_key_basics(private_key: &PrivateKey) {
1001        private_key.validate().expect("invalid private key");
1002
1003        assert_eq!(
1004            private_key.d().bits_precision(),
1005            private_key.n_bits_precision()
1006        );
1007
1008        if private_key.primes().len() > 2 {
1009            for prime in private_key.primes() {
1010                assert_eq!(prime.bits_precision(), private_key.n_bits_precision());
1011            }
1012        }
1013
1014        assert!(
1015            PrivateKeyParts::d(private_key) < PublicKeyParts::n(private_key).as_ref(),
1016            "private exponent too large"
1017        );
1018
1019        let pub_key: PublicKey = private_key.clone().into();
1020        let m = BoxedUint::from(42u64);
1021        let c = rsa_encrypt(&pub_key, &m).expect("encryption successful");
1022
1023        let m2 = rsa_decrypt_and_check::<ChaCha8Rng>(private_key, None, &c)
1024            .expect("unable to decrypt without blinding");
1025        assert_eq!(m, m2);
1026        let mut rng = ChaCha8Rng::from_seed([42; 32]);
1027        let m3 = rsa_decrypt_and_check(private_key, Some(&mut rng), &c)
1028            .expect("unable to decrypt with blinding");
1029        assert_eq!(m, m3);
1030    }
1031
1032    #[test]
1033    fn private_component_widths() {
1034        // A 65-bit modulus and a 61-bit private exponent. Minimal storage for `d` is narrower than
1035        // storage for `n` on both 32-bit and 64-bit targets.
1036        let n = BoxedUint::from(18_446_744_116_659_224_501u128);
1037        let e = BoxedUint::from(65537u64);
1038        let d = BoxedUint::from(1_721_699_869_695_564_833u64);
1039        let p = BoxedUint::from(4_294_967_291u64);
1040        let q = BoxedUint::from(4_294_967_311u64);
1041
1042        for input_bits in [64, 128, 256] {
1043            for reverse in [false, true] {
1044                let mut primes = vec![
1045                    (&p).resize_unchecked(input_bits),
1046                    (&q).resize_unchecked(input_bits),
1047                ];
1048
1049                if reverse {
1050                    primes.reverse();
1051                }
1052
1053                let mut key = PrivateKey::from_components(
1054                    (&n).resize_unchecked(256),
1055                    e.clone(),
1056                    (&d).resize_unchecked(input_bits),
1057                    primes,
1058                )
1059                .unwrap();
1060                assert_eq!(key.d(), &d);
1061                let prime_precision =
1062                    BoxedUint::zero_with_precision(key.n().bit_width().div_ceil(2))
1063                        .bits_precision();
1064                for prime in key.primes() {
1065                    assert_eq!(prime.bits_precision(), prime_precision);
1066                }
1067                assert_eq!(key.dp().expect("dp").bits_precision(), prime_precision);
1068                assert_eq!(key.dq().expect("dq").bits_precision(), prime_precision);
1069                assert_eq!(key.qinv().expect("qinv").bits_precision(), prime_precision);
1070
1071                for clear_precomputed in [false, true] {
1072                    if clear_precomputed {
1073                        key.clear_precomputed();
1074                    }
1075                    test_key_basics(&key);
1076
1077                    // This representative does not fit in `d`'s original 64-bit buffer.
1078                    // With odd `e` and `d`, both RSA operations fix `n-1`.
1079                    let c = key.n().as_ref().wrapping_sub(BoxedUint::one());
1080                    let m = rsa_decrypt_and_check::<ChaCha8Rng>(&key, None, &c).unwrap();
1081                    assert_eq!(m, c);
1082                }
1083
1084                key.precompute().unwrap();
1085                test_key_basics(&key);
1086            }
1087        }
1088
1089        // Resizing must reject significant high bits instead of silently truncating them into the
1090        // valid private exponent above.
1091        let oversized = d
1092            .resize_unchecked(256)
1093            .wrapping_add(&(BoxedUint::one_with_precision(256) << 128));
1094
1095        assert_eq!(
1096            PrivateKey::from_components(n, e, oversized, vec![p, q]),
1097            Err(Error::InvalidExponent)
1098        );
1099    }
1100
1101    macro_rules! key_generation {
1102        ($name:ident, $multi:expr, $size:expr) => {
1103            #[test]
1104            fn $name() {
1105                let mut rng = ChaCha8Rng::from_seed([42; 32]);
1106                let exp = BoxedUint::from(PrivateKey::EXP);
1107
1108                for _ in 0..10 {
1109                    let components =
1110                        generate_multi_prime_key_with_exp(&mut rng, $multi, $size, exp.clone())
1111                            .unwrap();
1112                    let private_key = PrivateKey::from_components(
1113                        components.n.get(),
1114                        components.e,
1115                        components.d,
1116                        components.primes,
1117                    )
1118                    .unwrap();
1119                    assert_eq!(PublicKeyParts::n(&private_key).bit_width(), $size);
1120
1121                    test_key_basics(&private_key);
1122                }
1123            }
1124        };
1125    }
1126
1127    key_generation!(key_generation_128, 2, 128);
1128    key_generation!(key_generation_1024, 2, 1024);
1129
1130    key_generation!(key_generation_multi_3_256, 3, 256);
1131
1132    key_generation!(key_generation_multi_4_64, 4, 64);
1133
1134    key_generation!(key_generation_multi_5_64, 5, 64);
1135    key_generation!(key_generation_multi_8_576, 8, 576);
1136    key_generation!(key_generation_multi_16_1024, 16, 1024);
1137
1138    #[test]
1139    fn test_negative_decryption_value() {
1140        let bits = 128;
1141        let private_key = PrivateKey::from_components(
1142            BoxedUint::from_le_slice(
1143                &[
1144                    99, 192, 208, 179, 0, 220, 7, 29, 49, 151, 75, 107, 75, 73, 200, 180,
1145                ],
1146                bits,
1147            )
1148            .unwrap(),
1149            BoxedUint::from_le_slice(&[1, 0, 1, 0, 0, 0, 0, 0], 64).unwrap(),
1150            BoxedUint::from_le_slice(
1151                &[
1152                    81, 163, 254, 144, 171, 159, 144, 42, 244, 133, 51, 249, 28, 12, 63, 65,
1153                ],
1154                bits,
1155            )
1156            .unwrap(),
1157            vec![
1158                BoxedUint::from_le_slice(&[105, 101, 60, 173, 19, 153, 3, 192], bits / 2).unwrap(),
1159                BoxedUint::from_le_slice(&[235, 65, 160, 134, 32, 136, 6, 241], bits / 2).unwrap(),
1160            ],
1161        )
1162        .unwrap();
1163
1164        for _ in 0..1000 {
1165            test_key_basics(&private_key);
1166        }
1167    }
1168
1169    #[test]
1170    #[cfg(all(feature = "hazmat", feature = "serde"))]
1171    fn test_serde() {
1172        use rand::rngs::ChaCha8Rng;
1173        use rand_core::SeedableRng;
1174        use serde_test::{Configure, Token, assert_ser_tokens, assert_tokens};
1175
1176        let mut rng = ChaCha8Rng::from_seed([42; 32]);
1177        let priv_key = PrivateKey::new_unchecked(&mut rng, 64).expect("failed to generate key");
1178
1179        let priv_tokens = [Token::Str(concat!(
1180            "3056020100300d06092a864886f70d010101050004423040020100020900a",
1181            "b240c3361d02e370203010001020811e54a15259d22f9020500ceff5cf302",
1182            "0500d3a7aaad020500ccaddf17020500cb529d3d020500bb526d6f"
1183        ))];
1184        assert_tokens(&priv_key.clone().readable(), &priv_tokens);
1185
1186        let pub_tokens = [Token::Str(
1187            "3024300d06092a864886f70d01010105000313003010020900ab240c3361d02e370203010001",
1188        )];
1189        // Small public keys can still be serialized, but default decoding rejects them.
1190        assert_ser_tokens(&PublicKey::from(priv_key.clone()).readable(), &pub_tokens);
1191    }
1192
1193    #[test]
1194    fn invalid_coeff_private_key_regression() {
1195        use base64ct::{Base64, Encoding};
1196
1197        let n = Base64::decode_vec(
1198            "wC8GyQvTCZOK+iiBR5fGQCmzRCTWX9TQ3aRG5gGFk0wB6EFoLMAyEEqeG3gS8xhA\
1199             m2rSWYx9kKufvNat3iWlbSRVqkcbpVAYlj2vTrpqDpJl+6u+zxFYoUEBevlJJkAh\
1200             l8EuCccOA30fVpcfRvXPTtvRd3yFT9E9EwZljtgSI02w7gZwg7VIxaGeajh5Euz6\
1201             ZVQZ+qNRKgXrRC7gPRqVyI6Dt0Jc+Su5KBGNn0QcPDzOahWha1ieaeMkFisZ9mdp\
1202             sJoZ4tw5eicLaUomKzALHXQVt+/rcZSrCd6/7uUo11B/CYBM4UfSpwXaL88J9AE6\
1203             A5++no9hmJzaF2LLp+Qwx4yY3j9TDutxSAjsraxxJOGZ3XyA9nG++Ybt3cxZ5fP7\
1204             ROjxCfROBmVv5dYn0O9OBIqYeCH6QraNpZMadlLNIhyMv8Y+P3r5l/PaK4VJaEi5\
1205             pPosnEPawp0W0yZDzmjk2z1LthaRx0aZVrAjlH0Rb/6goLUQ9qu1xsDtQVVpN4A8\
1206             9ZUmtTWORnnJr0+595eHHxssd2gpzqf4bPjNITdAEuOCCtpvyi4ls23zwuzryUYj\
1207             cUOEnsXNQ+DrZpLKxdtsD/qNV/j1hfeyBoPllC3cV+6bcGOFcVGbjYqb+Kw1b0+j\
1208             L69RSKQqgmS+qYqr8c48nDRxyq3QXhR8qtzUwBFSLVk=",
1209        )
1210        .unwrap();
1211        let e = Base64::decode_vec("AQAB").unwrap();
1212        let d = Base64::decode_vec(
1213            "qQazSQ+FRN7nVK1bRsROMRB8AmsDwLVEHivlz1V3Td2Dr+oW3YUMgxedhztML1Id\
1214             QJPq/ad6qErJ6yRFNySVIjDaxzBTOEoB1eHa1btOnBJWb8rVvvjaorixvJ6Tn3i4\
1215             EuhsvVy9DoR1k4rGj3qSIiFjUVvLRDAbLyhpGgEfsr0Z577yJmTC5E8JLRMOKX8T\
1216             mxsk3jPVpsgd65Hu1s8S/ZmabwuHCf9SkdMeY/1bd/9i7BqqJeeDLE4B5x1xcC3z\
1217             3scqDUTzqGO+vZPhjgprPDRlBamVwgenhr7KwCn8iaLamFinRVwOAag8BeBqOJj7\
1218             lURiOsKQa9FIX1kdFUS1QMQxgtPycLjkbvCJjriqT7zWKsmJ7l8YLs6Wmm9/+QJR\
1219             wNCEVdMTXKfCP1cJjudaiskEQThfUldtgu8gUDNYbQ/Filb2eKfiX4h1TiMxZqUZ\
1220             HVZyb9nShbQoXJ3vj/MGVF0QM8TxhXM8r2Lv9gDYU5t9nQlUMLhs0jVjai48jHAB\
1221             bFNyH3sEcOmJOIwJrCXw1dzG7AotwyaEVUHOmL04TffmwCFfnyrLjbFgnyOeoyII\
1222             BYjcY7QFRm/9nupXMTH5hZ2qrHfCJIp0KK4tNBdQqmnHapFl5l6Le1s4qBS5bEIz\
1223             jitobLvAFm9abPlDGfxmY6mlrMK4+nytwF9Ct7wc1AE=",
1224        )
1225        .unwrap();
1226        let primes = [
1227            Base64::decode_vec(
1228                "9kQWEAzsbzOcdPa+s5wFfw4XDd7bB1q9foZ31b1+TNjGNxbSBCFlDF1q98vwpV6n\
1229                 M8bWDh/wtbNoETSQDgpEnYOQ26LWEw6YY1+q1Q2GGEFceYUf+Myk8/vTc8TN6Zw0\
1230                 bKZBWy10Qo8h7xk4JpzuI7NcxvjJYTkS9aErFxi3vVH0aiZC0tmfaCqr8a2rJxyV\
1231                 wqreRpOjwAWrotMsf2wGsF4ofx5ScoFy5GB5fJkkdOrW1LyTvZAUCX3cstPr19+T\
1232                 NC5zZOk7WzZatnCkN5H5WzalWtZuu0oVL205KPOa3R8V2yv5e6fm0v5fTmqSuvjm\
1233                 aMJLXCN4QJkmIzojO99ckQ==",
1234            )
1235            .unwrap(),
1236            Base64::decode_vec(
1237                "x8exdMjVA2CiI+Thx7loHtVcevoeE2sZ7btRVAvmBqo+lkHwxb7FHRnWvuj6eJSl\
1238                 D2f0T50EewIhhiW3R9BmktCk7hXjbSCnC1u9Oxc1IAUm/7azRqyfCMx43XhLxpD+\
1239                 xkBCpWkKDLxGczsRwTuaP3lKS3bSdBrNlGmdblubvVBIq4YZ2vXVlnYtza0cS+dg\
1240                 CK7BGTqUsrCUd/ZbIvwcwZkZtpkhj1KQfto9X/0OMurBzAqbkeq1cyRHXHkOfN/q\
1241                 bUIIRqr9Ii7Eswf9Vk8xp2O1Nt8nzcYS9PFD12M5eyaeFEkEYfpNMNGuTzp/31oq\
1242                 VjbpoCxS6vuWAZyADxhISQ==",
1243            )
1244            .unwrap(),
1245            Base64::decode_vec(
1246                "is7d0LY4HoXszlC2NO7gejkq7XqL4p1W6hZJPYTNx+r37t1CC2n3Vvzg6kNdpRix\
1247                 DhIpXVTLjN9O7UO/XuqSumYKJIKoP52eb4Tg+a3hw5Iz2Zsb5lUTNSLgkQSBPAf7\
1248                 1LHxbL82JL4g1nBUog8ae60BwnVArThKY4EwlJguGNw09BAU4lwf6csDl/nX2vfV\
1249                 wiAloYpeZkHL+L8m+bueGZM5KE2jEz+7ztZCI+T+E5i69rZEYDjx0lfLKlEhQlCW\
1250                 3HbCPELqXgNJJkRfi6MP9kXa9lSfnZmoT081RMvqonB/FUa4HOcKyCrw9XZEtnbN\
1251                 CIdbitfDVEX+pSSD7596wQ==",
1252            )
1253            .unwrap(),
1254            Base64::decode_vec(
1255                "GPs0injugfycacaeIP5jMa/WX55VEnKLDHom4k6WlfDF4L4gIGoJdekcPEUfxOI5\
1256                 faKvHyFwRP1wObkPoRBDM0qZxRfBl4zEtpvjHrd5MibSyJkM8+J0BIKk/nSjbRIG\
1257                 eb3hV5O56PvGB3S0dKhCUnuVObiC+ne7izplsD4OTG70l1Yud33UFntyoMxrxGYL\
1258                 USqhBMmZfHquJg4NOWOzKNY/K+EcHDLj1Kjvkcgv9Vf7ocsVxvpFdD9uGPceQ6kw\
1259                 RDdEl6mb+6FDgWuXVyqR9+904oanEIkbJ7vfkthagLbEf57dyG6nJlqh5FBZWxGI\
1260                 R72YGypPuAh7qnnqXXjY2Q==",
1261            )
1262            .unwrap(),
1263            Base64::decode_vec(
1264                "CUWC+hRWOT421kwRllgVjy6FYv6jQUcgDNHeAiYZnf5HjS9iK2ki7v8G5dL/0f+Y\
1265                 f+NhE/4q8w4m8go51hACrVpP1p8GJDjiT09+RsOzITsHwl+ceEKoe56ZW6iDHBLl\
1266                 rNw5/MtcYhKpjNU9KJ2udm5J/c9iislcjgckrZG2IB8ADgXHMEByZ5DgaMl4AKZ1\
1267                 Gx8/q6KftTvmOT5rNTMLi76VN5KWQcDWK/DqXiOiZHM7Nr4dX4me3XeRgABJyNR8\
1268                 Fqxj3N1+HrYLe/zs7LOaK0++F9Ul3tLelhrhsvLxei3oCZkF9A/foD3on3luYA+1\
1269                 cRcxWpSY3h2J4/22+yo4+Q==",
1270            )
1271            .unwrap(),
1272        ];
1273
1274        let e = BoxedUint::from_be_slice(&e, 64).unwrap();
1275
1276        let bits = 4096;
1277        let n = BoxedUint::from_be_slice(&n, bits).unwrap();
1278        let d = BoxedUint::from_be_slice(&d, bits).unwrap();
1279        let primes = primes
1280            .iter()
1281            .map(|p| BoxedUint::from_be_slice(p, bits / 2).unwrap())
1282            .collect();
1283        let res = PrivateKey::from_components(n, e, d, primes);
1284        assert_eq!(res, Err(Error::InvalidModulus));
1285    }
1286
1287    #[test]
1288    fn reject_oversized_private_key() {
1289        // -----BEGIN PUBLIC KEY-----
1290        // MIIEKjANBgkqhkiG9w0BAQEFAAOCBBcAMIIEEgKCBAkAqQn6O7pd9ioQJEOwS2sh
1291        // nD2bM3+PaLovro+OKOE9t7jxrp+b9Xq81oeT6zN5u5yPewa+V08ZsAJQEbF9D5AM
1292        // UZkHZc/sW/XAItC8CojQhHoCQfjOXZpONmGsQxnSJNgwLV5TDVKUApbQIPzIm9yD
1293        // wOvl1yXIypaRINHzthz36ysHmaHlNVZZQ40BHVkOiUd+ws7W9U9vHN0QcaSHC8lH
1294        // UEqb/Iyb0FSmZs+qbm4NXyaI90oloAFftOnt8VFbHfT/TXS0VwMyescxFsuvcuTr
1295        // Xx8EYc9TuJThW22wBAFOK6SpftgtZ6i4WJqk0F8JrTwZ3TyhzKsPRwe8KeNmtmqY
1296        // oaGiPj9lUOc928QzOyTETVd8pV7UpnaOe9Q4WHL0QmnXn61pCu4qpoLuK8jB+IO7
1297        // xifRZHj3PMfsjJurZ4MF57LgpSrI60ekYNh1o6ViXODHQuzGxzTaF3n/7GITDBQX
1298        // DRTlGuQH77hykxFqPclRGI0wxECPKasxpzjhiaTua9eipKedXB+o5XFyosnDt/X4
1299        // Ygqxj/q2/18LPuQgFLqWRzsHd4TdVQyiq9xCmzIoGUjAPz1Q8cjIXRpUnp2rZQjE
1300        // SCLeTjewrGNbjSMDUhdF5M2OBRmn7Q8XHHCUxT9fY/BZeydeE54KvEdEkomxkbXo
1301        // hHKEmbWeEdhp78h04/xW364p1Nu9Y49w7gtO+9nmwKcpNJq32M6Qb0d2dQ3wJ0oI
1302        // I9ml+n/DTna+IIwwbI8UOFEI4KZQzZaqmNv3TzGmpnocHK7eMyEtAUeQZUIGrPmr
1303        // FQEmKZn9rkgr/2Hw8T20q7e0lE65Is69vTP2wXm17B5zKFYska41jJoZ6jIpbMOt
1304        // uVPZV3SoGYM39Z4Ax3JaGZE0L/dQ6lJJhdFUACFIQXwNWqzd7srnvbym4hLqoPuM
1305        // hjkUtTcv6YODEk7LB2FLDcymmH/zCL3w4VSi4+HyZZ13gM7Cz8WmkX4H+jeL0+Ja
1306        // QyG1CzqV/HA78vUpJv/bb/J1+X1i/1HltLeTjteY4rBhVT1cxBoVBGQaCwindAs+
1307        // Fjcp+8cAK+/3pMQghnkrGHzrx9YIYoOGXs4vQIMGngYaTa7aXAaft4fWjg4EeSjd
1308        // rZwqqrPNuUcEuneFP9RPffj8f3vkhqCFgoVBfVM7ontu2d2nRu/hhAkgT13Uc68J
1309        // dM2imBvHAo6DDUt6msWCAMOAEXYuO7aA+n3eettnBqtECoQAoCJdCHCebjIploMB
1310        // XMLXyseGtLK9arI48hDvcxSlf7/1lkBB6LgNQmQJ7925TDipiYQIZ63f4d5Z2JCp
1311        // W0vUkwzrH4iPb2hy+TBQSOw1kvjLyG/lHWjzDQa60xxVW9u59DxQueHsNEMHUORD
1312        // 1oFXvFLe/AllAgMBAAE=
1313        // -----END PUBLIC KEY-----
1314
1315        let n = BoxedUint::from_be_slice(
1316            &hex!(
1317                "a909fa3bba5df62a102443b04b6b219c3d9b337f8f68ba2fae8f8e28e13db7b8
1318                 f1ae9f9bf57abcd68793eb3379bb9c8f7b06be574f19b0025011b17d0f900c51
1319                 990765cfec5bf5c022d0bc0a88d0847a0241f8ce5d9a4e3661ac4319d224d830
1320                 2d5e530d52940296d020fcc89bdc83c0ebe5d725c8ca969120d1f3b61cf7eb2b
1321                 0799a1e5355659438d011d590e89477ec2ced6f54f6f1cdd1071a4870bc94750
1322                 4a9bfc8c9bd054a666cfaa6e6e0d5f2688f74a25a0015fb4e9edf1515b1df4ff
1323                 4d74b45703327ac73116cbaf72e4eb5f1f0461cf53b894e15b6db004014e2ba4
1324                 a97ed82d67a8b8589aa4d05f09ad3c19dd3ca1ccab0f4707bc29e366b66a98a1
1325                 a1a23e3f6550e73ddbc4333b24c44d577ca55ed4a6768e7bd4385872f44269d7
1326                 9fad690aee2aa682ee2bc8c1f883bbc627d16478f73cc7ec8c9bab678305e7b2
1327                 e0a52ac8eb47a460d875a3a5625ce0c742ecc6c734da1779ffec62130c14170d
1328                 14e51ae407efb87293116a3dc951188d30c4408f29ab31a738e189a4ee6bd7a2
1329                 a4a79d5c1fa8e57172a2c9c3b7f5f8620ab18ffab6ff5f0b3ee42014ba96473b
1330                 077784dd550ca2abdc429b32281948c03f3d50f1c8c85d1a549e9dab6508c448
1331                 22de4e37b0ac635b8d2303521745e4cd8e0519a7ed0f171c7094c53f5f63f059
1332                 7b275e139e0abc47449289b191b5e884728499b59e11d869efc874e3fc56dfae
1333                 29d4dbbd638f70ee0b4efbd9e6c0a729349ab7d8ce906f4776750df0274a0823
1334                 d9a5fa7fc34e76be208c306c8f14385108e0a650cd96aa98dbf74f31a6a67a1c
1335                 1caede33212d014790654206acf9ab1501262999fdae482bff61f0f13db4abb7
1336                 b4944eb922cebdbd33f6c179b5ec1e7328562c91ae358c9a19ea32296cc3adb9
1337                 53d95774a8198337f59e00c7725a1991342ff750ea524985d154002148417c0d
1338                 5aacddeecae7bdbca6e212eaa0fb8c863914b5372fe98383124ecb07614b0dcc
1339                 a6987ff308bdf0e154a2e3e1f2659d7780cec2cfc5a6917e07fa378bd3e25a43
1340                 21b50b3a95fc703bf2f52926ffdb6ff275f97d62ff51e5b4b7938ed798e2b061
1341                 553d5cc41a1504641a0b08a7740b3e163729fbc7002beff7a4c42086792b187c
1342                 ebc7d6086283865ece2f4083069e061a4daeda5c069fb787d68e0e047928ddad
1343                 9c2aaab3cdb94704ba77853fd44f7df8fc7f7be486a0858285417d533ba27b6e
1344                 d9dda746efe18409204f5dd473af0974cda2981bc7028e830d4b7a9ac58200c3
1345                 8011762e3bb680fa7dde7adb6706ab440a8400a0225d08709e6e32299683015c
1346                 c2d7cac786b4b2bd6ab238f210ef7314a57fbff5964041e8b80d426409efddb9
1347                 4c38a989840867addfe1de59d890a95b4bd4930ceb1f888f6f6872f9305048ec
1348                 3592f8cbc86fe51d68f30d06bad31c555bdbb9f43c50b9e1ec34430750e443d6
1349                 8157bc52defc0965"
1350            ),
1351            8256,
1352        )
1353        .unwrap();
1354
1355        let e = BoxedUint::from(65_537u64);
1356
1357        assert_eq!(PublicKey::new(n, e).err().unwrap(), Error::ModulusTooLarge);
1358    }
1359
1360    #[test]
1361    #[cfg(feature = "encoding")]
1362    fn build_key_from_primes() {
1363        const RSA_2048_PRIV_DER: &[u8] = include_bytes!("../tests/examples/pkcs8/rsa2048-priv.der");
1364        let ref_key = PrivateKey::from_pkcs8_der(RSA_2048_PRIV_DER).unwrap();
1365        assert_eq!(ref_key.validate(), Ok(()));
1366
1367        let primes: Vec<_> = PrivateKeyParts::primes(&ref_key)
1368            .iter()
1369            .map(|p| p.as_ref().clone())
1370            .collect();
1371
1372        let exp = PublicKeyParts::e(&ref_key);
1373        let key =
1374            PrivateKey::from_primes(primes, exp.clone()).expect("failed to import key from primes");
1375        assert_eq!(key.validate(), Ok(()));
1376
1377        assert_eq!(PublicKeyParts::n(&key), PublicKeyParts::n(&ref_key));
1378
1379        assert_eq!(PrivateKeyParts::dp(&key), PrivateKeyParts::dp(&ref_key));
1380        assert_eq!(PrivateKeyParts::dq(&key), PrivateKeyParts::dq(&ref_key));
1381
1382        assert_eq!(PrivateKeyParts::d(&key), PrivateKeyParts::d(&ref_key));
1383    }
1384
1385    #[test]
1386    #[cfg(feature = "encoding")]
1387    fn build_key_from_p_q() {
1388        const RSA_2048_SP800_PRIV_DER: &[u8] =
1389            include_bytes!("../tests/examples/pkcs8/rsa2048-sp800-56b-priv.der");
1390        let ref_key = PrivateKey::from_pkcs8_der(RSA_2048_SP800_PRIV_DER).unwrap();
1391        assert_eq!(ref_key.validate(), Ok(()));
1392
1393        let primes: Vec<_> = PrivateKeyParts::primes(&ref_key)
1394            .iter()
1395            .map(|p| p.as_ref().clone())
1396            .collect();
1397        let exp = PublicKeyParts::e(&ref_key);
1398
1399        let key = PrivateKey::from_p_q(primes[0].clone(), primes[1].clone(), exp.clone())
1400            .expect("failed to import key from primes");
1401        assert_eq!(key.validate(), Ok(()));
1402
1403        assert_eq!(PublicKeyParts::n(&key), PublicKeyParts::n(&ref_key));
1404
1405        assert_eq!(PrivateKeyParts::dp(&key), PrivateKeyParts::dp(&ref_key));
1406        assert_eq!(PrivateKeyParts::dq(&key), PrivateKeyParts::dq(&ref_key));
1407
1408        assert_eq!(PrivateKeyParts::d(&key), PrivateKeyParts::d(&ref_key));
1409    }
1410
1411    #[test]
1412    #[cfg(feature = "hazmat")]
1413    fn test_from_components_with_large_exponent() {
1414        // Test that from_components_with_large_exponent accepts exponents outside normal bounds
1415        // while from_components would reject them
1416
1417        use rand::rngs::ChaCha8Rng;
1418        use rand_core::SeedableRng;
1419
1420        let mut rng = ChaCha8Rng::from_seed([42; 32]);
1421
1422        // Use an exponent larger than the normal maximum (2^33 - 1)
1423        let large_e = BoxedUint::from((1u64 << 34) + 1); // 2^34 + 1 (odd number)
1424
1425        // Generate a key with this large exponent
1426        let components =
1427            generate_multi_prime_key_with_exp(&mut rng, 2, 1024, large_e.clone()).unwrap();
1428
1429        // Extract components
1430        let n = components.n.get().clone();
1431        let d = components.d;
1432        let primes = components.primes;
1433
1434        // from_components should fail with PublicExponentTooLarge
1435        let result =
1436            PrivateKey::from_components(n.clone(), large_e.clone(), d.clone(), primes.clone());
1437        assert!(result.is_err());
1438        assert_eq!(result.unwrap_err(), Error::PublicExponentTooLarge);
1439
1440        // from_components_with_large_exponent should succeed
1441        let key_with_large_exp = PrivateKey::from_components_with_large_exponent(
1442            n.clone(),
1443            large_e.clone(),
1444            d.clone(),
1445            primes.clone(),
1446        );
1447        assert!(key_with_large_exp.is_ok());
1448
1449        let key_with_large_exp = key_with_large_exp.unwrap();
1450        assert_eq!(PublicKeyParts::e(&key_with_large_exp), &large_e);
1451        assert_eq!(PublicKeyParts::n(&key_with_large_exp).as_ref(), &n);
1452        assert_eq!(PrivateKeyParts::d(&key_with_large_exp), &d);
1453
1454        // Verify that the key is still cryptographically valid (de ≡ 1 mod λ(n))
1455        // by checking that validation with skip_exponent_size passes
1456        assert!(validate_skip_exponent_size(&key_with_large_exp).is_ok());
1457    }
1458
1459    #[test]
1460    #[cfg(feature = "hazmat")]
1461    fn test_from_components_with_small_exponent() {
1462        // Test that from_components_with_large_exponent accepts exponents below normal minimum
1463        // (despite the name, it works for any non-standard exponent size)
1464
1465        use rand::rngs::ChaCha8Rng;
1466        use rand_core::SeedableRng;
1467
1468        let mut rng = ChaCha8Rng::from_seed([43; 32]);
1469
1470        // Use an exponent smaller than the normal minimum (2)
1471        let small_e = BoxedUint::from(1u64); // This is odd, which is required
1472
1473        // Generate a key with this small exponent
1474        let components =
1475            generate_multi_prime_key_with_exp(&mut rng, 2, 1024, small_e.clone()).unwrap();
1476
1477        // Extract components
1478        let n = components.n.get().clone();
1479        let d = components.d;
1480        let primes = components.primes;
1481
1482        // from_components should fail
1483        let result =
1484            PrivateKey::from_components(n.clone(), small_e.clone(), d.clone(), primes.clone());
1485        assert!(result.is_err());
1486
1487        // from_components_with_large_exponent should succeed
1488        let key_with_small_exp = PrivateKey::from_components_with_large_exponent(
1489            n.clone(),
1490            small_e.clone(),
1491            d.clone(),
1492            primes,
1493        );
1494        assert!(key_with_small_exp.is_ok());
1495
1496        let key_with_small_exp = key_with_small_exp.unwrap();
1497        assert_eq!(PublicKeyParts::e(&key_with_small_exp), &small_e);
1498
1499        // Verify that the key is cryptographically valid
1500        assert!(validate_skip_exponent_size(&key_with_small_exp).is_ok());
1501    }
1502
1503    /// Regression test for CVE-2026-21895 / GHSA-9c48-w39g-hm26.
1504    ///
1505    /// Loading a secret key whose prime factor is `1` must be rejected with
1506    /// `Error::InvalidPrime` rather than panicking via a divide-by-zero in
1507    /// the validation/precompute path.
1508    ///
1509    /// Adapted from the test added in upstream commit 2926c91bef (PR #624);
1510    /// the original used `num-bigint` `BigUint` types, this version uses
1511    /// `crypto-bigint` `BoxedUint` and goes through
1512    /// `from_components_with_large_exponent` so the small (out-of-range) `e`
1513    /// can be supplied verbatim from the original test.
1514    #[test]
1515    #[cfg(feature = "hazmat")]
1516    fn test_key_invalid_primes() {
1517        let e = PrivateKey::from_components_with_large_exponent(
1518            BoxedUint::from(239u64),
1519            BoxedUint::from(185u64),
1520            BoxedUint::from(0u64),
1521            vec![BoxedUint::from(1u64), BoxedUint::from(239u64)],
1522        )
1523        .unwrap_err();
1524        assert_eq!(e, Error::InvalidPrime);
1525    }
1526}