Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make Uint::random_mod() work identically on 32- and 64-bit targets #285

Merged
merged 1 commit into from
Nov 9, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 17 additions & 6 deletions src/uint/rand.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Random number generator support

use super::Uint;
use crate::{Limb, NonZero, Random, RandomMod};
use crate::{Encoding, Limb, NonZero, Random, RandomMod};
use rand_core::CryptoRngCore;
use subtle::ConstantTimeLess;

Expand Down Expand Up @@ -30,18 +30,29 @@ impl<const LIMBS: usize> RandomMod for Uint<LIMBS> {
/// issue so long as the underlying random number generator is truly a
/// CSRNG, where previous outputs are unrelated to subsequent
/// outputs and do not reveal information about the RNG's internal state.
fn random_mod(mut rng: &mut impl CryptoRngCore, modulus: &NonZero<Self>) -> Self {
fn random_mod(rng: &mut impl CryptoRngCore, modulus: &NonZero<Self>) -> Self {
let mut n = Self::ZERO;

let n_bits = modulus.as_ref().bits_vartime();
let n_bytes = (n_bits + 7) / 8;
let n_limbs = (n_bits + Limb::BITS - 1) / Limb::BITS;
let mask = Limb::MAX >> (Limb::BITS * n_limbs - n_bits);
let hi_bytes = n_bytes - (n_limbs - 1) * Limb::BYTES;

let mut bytes = Limb::ZERO.to_le_bytes();

loop {
for i in 0..n_limbs {
n.limbs[i] = Limb::random(&mut rng);
for i in 0..n_limbs - 1 {
rng.fill_bytes(bytes.as_mut());
// Need to deserialize from little-endian to make sure that two 32-bit limbs
// deserialized sequentially are equal to one 64-bit limb produced from the same
// byte stream.
n.limbs[i] = Limb::from_le_bytes(bytes);
}
n.limbs[n_limbs - 1] = n.limbs[n_limbs - 1] & mask;
tarcieri marked this conversation as resolved.
Show resolved Hide resolved

// Generate the high limb which may need to only be filled partially.
bytes.as_mut().fill(0);
rng.fill_bytes(&mut (bytes.as_mut()[0..hi_bytes]));
n.limbs[n_limbs - 1] = Limb::from_le_bytes(bytes);

if n.ct_lt(modulus).into() {
return n;
Expand Down