crypto_bigint/uint/
rand.rs1use super::Uint;
4use crate::{Encoding, Limb, NonZero, Random, RandomMod};
5use rand_core::CryptoRngCore;
6use subtle::ConstantTimeLess;
7
8impl<const LIMBS: usize> Random for Uint<LIMBS> {
9 fn random(mut rng: &mut impl CryptoRngCore) -> Self {
11 let mut limbs = [Limb::ZERO; LIMBS];
12
13 for limb in &mut limbs {
14 *limb = Limb::random(&mut rng)
15 }
16
17 limbs.into()
18 }
19}
20
21impl<const LIMBS: usize> RandomMod for Uint<LIMBS> {
22 fn random_mod(rng: &mut impl CryptoRngCore, modulus: &NonZero<Self>) -> Self {
34 let mut n = Self::ZERO;
35
36 let n_bits = modulus.as_ref().bits_vartime();
37 let n_bytes = (n_bits + 7) / 8;
38 let n_limbs = (n_bits + Limb::BITS - 1) / Limb::BITS;
39 let hi_bytes = n_bytes - (n_limbs - 1) * Limb::BYTES;
40
41 let mut bytes = Limb::ZERO.to_le_bytes();
42
43 loop {
44 for i in 0..n_limbs - 1 {
45 rng.fill_bytes(bytes.as_mut());
46 n.limbs[i] = Limb::from_le_bytes(bytes);
50 }
51
52 bytes.as_mut().fill(0);
54 rng.fill_bytes(&mut (bytes.as_mut()[0..hi_bytes]));
55 n.limbs[n_limbs - 1] = Limb::from_le_bytes(bytes);
56
57 if n.ct_lt(modulus).into() {
58 return n;
59 }
60 }
61 }
62}
63
64#[cfg(test)]
65mod tests {
66 use crate::{NonZero, RandomMod, U256};
67 use rand_core::SeedableRng;
68
69 #[test]
70 fn random_mod() {
71 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1);
72
73 let modulus = NonZero::new(U256::from(42u8)).unwrap();
75 let res = U256::random_mod(&mut rng, &modulus);
76
77 assert!(res >= U256::ZERO);
79 assert!(res < U256::from(42u8));
80
81 let modulus = NonZero::new(U256::from(0x10000000000000001u128)).unwrap();
84 let res = U256::random_mod(&mut rng, &modulus);
85
86 assert!(res >= U256::ZERO);
88 assert!(res < U256::from(0x10000000000000001u128));
89 }
90}