crypto_bigint/uint/
rand.rs

1//! Random number generator support
2
3use super::UInt;
4use crate::{Limb, NonZero, Random, RandomMod};
5use rand_core::{CryptoRng, RngCore};
6use subtle::ConstantTimeLess;
7
8#[cfg_attr(docsrs, doc(cfg(feature = "rand_core")))]
9impl<const LIMBS: usize> Random for UInt<LIMBS> {
10    /// Generate a cryptographically secure random [`UInt`].
11    fn random(mut rng: impl CryptoRng + RngCore) -> Self {
12        let mut limbs = [Limb::ZERO; LIMBS];
13
14        for limb in &mut limbs {
15            *limb = Limb::random(&mut rng)
16        }
17
18        limbs.into()
19    }
20}
21
22#[cfg_attr(docsrs, doc(cfg(feature = "rand_core")))]
23impl<const LIMBS: usize> RandomMod for UInt<LIMBS> {
24    /// Generate a cryptographically secure random [`UInt`] which is less than
25    /// a given `modulus`.
26    ///
27    /// This function uses rejection sampling, a method which produces an
28    /// unbiased distribution of in-range values provided the underlying
29    /// [`CryptoRng`] is unbiased, but runs in variable-time.
30    ///
31    /// The variable-time nature of the algorithm should not pose a security
32    /// issue so long as the underlying random number generator is truly a
33    /// [`CryptoRng`], where previous outputs are unrelated to subsequent
34    /// outputs and do not reveal information about the RNG's internal state.
35    fn random_mod(mut rng: impl CryptoRng + RngCore, modulus: &NonZero<Self>) -> Self {
36        let mut n = Self::ZERO;
37
38        // TODO(tarcieri): use `div_ceil` when available
39        // See: https://github.com/rust-lang/rust/issues/88581
40        let mut n_limbs = modulus.bits_vartime() / Limb::BIT_SIZE;
41        if n_limbs < LIMBS {
42            n_limbs += 1;
43        }
44
45        // Compute the highest limb of `modulus` as a `NonZero`.
46        // Add one to ensure `Limb::random_mod` returns values inclusive of this limb.
47        let modulus_hi =
48            NonZero::new(modulus.limbs[n_limbs.saturating_sub(1)].saturating_add(Limb::ONE))
49                .unwrap(); // Always at least one due to `saturating_add`
50
51        loop {
52            for i in 0..n_limbs {
53                n.limbs[i] = if (i + 1 == n_limbs) && (*modulus_hi != Limb::MAX) {
54                    // Highest limb
55                    Limb::random_mod(&mut rng, &modulus_hi)
56                } else {
57                    Limb::random(&mut rng)
58                }
59            }
60
61            if n.ct_lt(modulus).into() {
62                return n;
63            }
64        }
65    }
66}
67
68#[cfg(test)]
69mod tests {
70    use crate::{NonZero, RandomMod, U256};
71    use rand_core::SeedableRng;
72
73    #[test]
74    fn random_mod() {
75        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1);
76
77        // Ensure `random_mod` runs in a reasonable amount of time
78        let modulus = NonZero::new(U256::from(42u8)).unwrap();
79        let res = U256::random_mod(&mut rng, &modulus);
80
81        // Sanity check that the return value isn't zero
82        assert_ne!(res, U256::ZERO);
83
84        // Ensure `random_mod` runs in a reasonable amount of time
85        // when the modulus is larger than 1 limb
86        let modulus = NonZero::new(U256::from(0x10000000000000001u128)).unwrap();
87        let res = U256::random_mod(&mut rng, &modulus);
88
89        // Sanity check that the return value isn't zero
90        assert_ne!(res, U256::ZERO);
91    }
92}