crypto_bigint/limb/
rand.rs

1//! Random number generator support
2
3use super::Limb;
4use crate::{Encoding, NonZero, Random, RandomMod};
5use rand_core::{CryptoRng, RngCore};
6use subtle::ConstantTimeLess;
7
8#[cfg_attr(docsrs, doc(cfg(feature = "rand_core")))]
9impl Random for Limb {
10    #[cfg(target_pointer_width = "32")]
11    fn random(mut rng: impl CryptoRng + RngCore) -> Self {
12        Self(rng.next_u32())
13    }
14
15    #[cfg(target_pointer_width = "64")]
16    fn random(mut rng: impl CryptoRng + RngCore) -> Self {
17        Self(rng.next_u64())
18    }
19}
20
21#[cfg_attr(docsrs, doc(cfg(feature = "rand_core")))]
22impl RandomMod for Limb {
23    fn random_mod(mut rng: impl CryptoRng + RngCore, modulus: &NonZero<Self>) -> Self {
24        let mut bytes = <Self as Encoding>::Repr::default();
25
26        // TODO(tarcieri): use `div_ceil` when available
27        // See: https://github.com/rust-lang/rust/issues/88581
28        let mut n_bytes = modulus.bits() / 8;
29
30        // Ensure the randomly generated value can always be larger than
31        // the modulus in order to ensure a uniform distribution
32        if n_bytes < Self::BYTE_SIZE {
33            n_bytes += 1;
34        }
35
36        loop {
37            rng.fill_bytes(&mut bytes[..n_bytes]);
38            let n = Limb::from_le_bytes(bytes);
39
40            if n.ct_lt(modulus).into() {
41                return n;
42            }
43        }
44    }
45}