/rust/registry/src/index.crates.io-1949cf8c6b5b557f/crypto-bigint-0.5.5/src/limb/rand.rs
Line | Count | Source |
1 | | //! Random number generator support |
2 | | |
3 | | use super::Limb; |
4 | | use crate::{Encoding, NonZero, Random, RandomMod}; |
5 | | use rand_core::CryptoRngCore; |
6 | | use subtle::ConstantTimeLess; |
7 | | |
8 | | impl Random for Limb { |
9 | | #[cfg(target_pointer_width = "32")] |
10 | | fn random(rng: &mut impl CryptoRngCore) -> Self { |
11 | | Self(rng.next_u32()) |
12 | | } |
13 | | |
14 | | #[cfg(target_pointer_width = "64")] |
15 | 0 | fn random(rng: &mut impl CryptoRngCore) -> Self { |
16 | 0 | Self(rng.next_u64()) |
17 | 0 | } |
18 | | } |
19 | | |
20 | | impl RandomMod for Limb { |
21 | 0 | fn random_mod(rng: &mut impl CryptoRngCore, modulus: &NonZero<Self>) -> Self { |
22 | 0 | let mut bytes = <Self as Encoding>::Repr::default(); |
23 | | |
24 | 0 | let n_bits = modulus.bits(); |
25 | 0 | let n_bytes = (n_bits + 7) / 8; |
26 | 0 | let mask = 0xff >> (8 * n_bytes - n_bits); |
27 | | |
28 | | loop { |
29 | 0 | rng.fill_bytes(&mut bytes[..n_bytes]); |
30 | 0 | bytes[n_bytes - 1] &= mask; |
31 | | |
32 | 0 | let n = Limb::from_le_bytes(bytes); |
33 | 0 | if n.ct_lt(modulus).into() { |
34 | 0 | return n; |
35 | 0 | } |
36 | | } |
37 | 0 | } |
38 | | } |