crypto_bigint/uint/rand.rs
1//! Random number generator support
2
3use super::UInt;
4use crate::Limb;
5use rand_core::{CryptoRng, RngCore};
6use subtle::ConstantTimeLess;
7
8#[cfg_attr(docsrs, doc(cfg(feature = "rand")))]
9impl<const LIMBS: usize> UInt<LIMBS> {
10 /// Generate a cryptographically secure random [`UInt`].
11 pub fn random(mut rng: impl CryptoRng + RngCore) -> Self {
12 let mut limbs = [Limb::default(); LIMBS];
13
14 for limb in &mut limbs {
15 *limb = Limb::random(&mut rng)
16 }
17
18 limbs.into()
19 }
20
21 /// Generate a cryptographically secure random [`UInt`] which is less than
22 /// a given `modulus`.
23 ///
24 /// This function uses rejection sampling, a method which produces an
25 /// unbiased distribution of in-range values provided the underlying
26 /// [`CryptoRng`] is unbiased, but runs in variable-time.
27 ///
28 /// The variable-time nature of the algorithm should not pose a security
29 /// issue so long as the underlying random number generator is truly a
30 /// [`CryptoRng`], where previous outputs are unrelated to subsequent
31 /// outputs and do not reveal information about the RNG's internal state.
32 pub fn random_mod(mut rng: impl CryptoRng + RngCore, modulus: &Self) -> Self {
33 loop {
34 let n = Self::random(&mut rng);
35
36 if n.ct_lt(modulus).into() {
37 return n;
38 }
39 }
40 }
41}