Skip to main content

rsa/algorithms/
generate.rs

1//! Generate prime components for the RSA Private Key
2
3#![allow(clippy::integer_division_remainder_used, reason = "TODO")]
4
5use alloc::vec::Vec;
6use core::num::NonZeroU32;
7use crypto_bigint::{BitOps, BoxedUint, Odd, RandomBits, RandomBitsError};
8use crypto_primes::{Flavor, hazmat::SmallFactorsSieve, is_prime};
9use rand_core::TryCryptoRng;
10
11use crate::{
12    algorithms::rsa::{compute_modulus, compute_private_exponent_euler_totient},
13    errors::{Error, Result},
14};
15
16/// Raw generated components, which must be subsequently validated by the private key constructor.
17pub struct RsaPrivateKeyComponents {
18    pub n: Odd<BoxedUint>,
19    pub e: BoxedUint,
20    pub d: BoxedUint,
21    pub primes: Vec<BoxedUint>,
22}
23
24/// Generates a multi-prime RSA keypair of the given bit size, public exponent,
25/// and the given random source, as suggested in [1]. Although the public
26/// keys are compatible (actually, indistinguishable) from the 2-prime case,
27/// the private keys are not. Thus it may not be possible to export multi-prime
28/// private keys in certain formats or to subsequently import them into other
29/// code.
30///
31/// Table 1 in [2] suggests maximum numbers of primes for a given size.
32///
33/// [1]: https://patents.google.com/patent/US4405829A/en
34/// [2]: http://www.cacr.math.uwaterloo.ca/techreports/2006/cacr2006-16.pdf
35pub(crate) fn generate_multi_prime_key_with_exp<R: TryCryptoRng + ?Sized>(
36    rng: &mut R,
37    nprimes: usize,
38    bit_size: usize,
39    exp: BoxedUint,
40) -> Result<RsaPrivateKeyComponents> {
41    if nprimes < 2 {
42        return Err(Error::NprimesTooSmall);
43    }
44
45    #[allow(clippy::cast_precision_loss, reason = "TODO")]
46    if bit_size < 64 {
47        let prime_limit = (1u64 << (bit_size / nprimes) as u64) as f64;
48
49        // pi approximates the number of primes less than prime_limit
50
51        // Calculate `log(prime_limit)` as `log(x) = log2(x) / log2(e) = log2(x) * log(2)`.
52        let mut pi = prime_limit / ((bit_size / nprimes) as f64 * core::f64::consts::LN_2 - 1.);
53
54        // Generated primes start with 0b11, so we can only use a quarter of them.
55        pi /= 4f64;
56        // Use a factor of two to ensure that key generation terminates in a
57        // reasonable amount of time.
58        pi /= 2f64;
59
60        if pi < nprimes as f64 {
61            return Err(Error::TooFewPrimes);
62        }
63    }
64
65    let mut primes = vec![BoxedUint::zero(); nprimes];
66    let n_final: Odd<BoxedUint>;
67    let d_final: BoxedUint;
68
69    loop {
70        let mut todo = bit_size;
71        // `generate_prime_with_rng` should set the top two bits in each prime.
72        // Thus each prime has the form
73        //   p_i = 2^bitlen(p_i) × 0.11... (in base 2).
74        // And the product is:
75        //   P = 2^todo × α
76        // where α is the product of nprimes numbers of the form 0.11...
77        //
78        // If α < 1/2 (which can happen for nprimes > 2), we need to
79        // shift todo to compensate for lost bits: the mean value of 0.11...
80        // is 7/8, so todo + shift - nprimes * log2(7/8) ~= bits - 1/2
81        // will give good results.
82        if nprimes >= 7 {
83            todo += (nprimes - 2) / 5;
84        }
85
86        #[allow(clippy::cast_possible_truncation, reason = "TODO")]
87        for (i, prime) in primes.iter_mut().enumerate() {
88            let bits = (todo / (nprimes - i)) as u32;
89            *prime = generate_prime_with_rng(rng, bits).map_err(|_| Error::Rng)?;
90            todo -= prime.bit_width() as usize;
91        }
92
93        let n = compute_modulus(&primes);
94
95        if n.bit_width() as usize != bit_size {
96            // This should never happen for nprimes == 2 because
97            // generate_prime_with_rng should set the top two bits in each prime.
98            // For nprimes > 2 we hope it does not happen often.
99            continue;
100        }
101
102        if let Ok(d) = compute_private_exponent_euler_totient(&primes, &exp) {
103            n_final = n;
104            d_final = d;
105            break;
106        }
107    }
108
109    Ok(RsaPrivateKeyComponents {
110        n: n_final,
111        e: exp,
112        d: d_final,
113        primes,
114    })
115}
116
117/// Generate an odd prime with its top two bits set.
118///
119/// # Panics
120/// Panics if `bit_length` is less than two.
121pub(crate) fn generate_prime_with_rng<R: TryCryptoRng + ?Sized>(
122    rng: &mut R,
123    bit_length: u32,
124) -> core::result::Result<BoxedUint, R::Error> {
125    let bit_length = NonZeroU32::new(bit_length)
126        .filter(|bits| bits.get() >= 2)
127        .expect("prime bit length must be at least two");
128
129    loop {
130        // Sample directly because `SmallFactorsSieveFactory` requires an infallible RNG.
131        let mut start =
132            BoxedUint::try_random_bits(rng, bit_length.get()).map_err(|err| match err {
133                RandomBitsError::RandCore(err) => err,
134                // The precision is determined by the requested bit length.
135                _ => unreachable!("random integer has the requested precision"),
136            })?;
137
138        // Match `SetBits::TwoMsb`: make the candidate odd and set its top two bits.
139        start.set_bit_vartime(0, true);
140        start.set_bit_vartime(bit_length.get() - 1, true);
141        start.set_bit_vartime(bit_length.get() - 2, true);
142
143        let Ok(mut sieve) = SmallFactorsSieve::new(start, bit_length, false) else {
144            unreachable!("candidate fits the bit length");
145        };
146        if let Some(prime) = sieve.find(|candidate| is_prime(Flavor::Any, candidate)) {
147            return Ok(prime);
148        }
149    }
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155    use rand::rngs::ChaCha8Rng;
156    use rand_core::SeedableRng;
157
158    const EXP: u64 = 65537;
159
160    #[test]
161    fn test_impossible_keys() {
162        let mut rng = ChaCha8Rng::from_seed([42; 32]);
163        let exp = BoxedUint::from(EXP);
164
165        for i in 0..32 {
166            let _ = generate_multi_prime_key_with_exp(&mut rng, 2, i, exp.clone());
167            let _ = generate_multi_prime_key_with_exp(&mut rng, 3, i, exp.clone());
168            let _ = generate_multi_prime_key_with_exp(&mut rng, 4, i, exp.clone());
169            let _ = generate_multi_prime_key_with_exp(&mut rng, 5, i, exp.clone());
170        }
171    }
172
173    macro_rules! key_generation {
174        ($name:ident, $multi:expr, $size:expr) => {
175            #[test]
176            fn $name() {
177                let mut rng = ChaCha8Rng::from_seed([42; 32]);
178                let exp = BoxedUint::from(EXP);
179                for _ in 0..10 {
180                    let components =
181                        generate_multi_prime_key_with_exp(&mut rng, $multi, $size, exp.clone())
182                            .unwrap();
183                    assert_eq!(components.n.bit_width(), $size);
184                    assert_eq!(components.primes.len(), $multi);
185                }
186            }
187        };
188    }
189
190    key_generation!(key_generation_128, 2, 128);
191    key_generation!(key_generation_1024, 2, 1024);
192
193    key_generation!(key_generation_multi_3_256, 3, 256);
194
195    key_generation!(key_generation_multi_4_64, 4, 64);
196
197    key_generation!(key_generation_multi_5_64, 5, 64);
198    key_generation!(key_generation_multi_8_576, 8, 576);
199    // TODO: reenable, currently slow
200    // key_generation!(key_generation_multi_16_1024, 16, 1024);
201}