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

provide RandomMod::try_random_mod and Random::try_random methods #770

Merged
merged 3 commits into from
Feb 22, 2025
Merged
Show file tree
Hide file tree
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
3 changes: 1 addition & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ subtle = { version = "2.6", default-features = false }
der = { version = "0.8.0-rc.1", optional = true, default-features = false }
hybrid-array = { version = "0.2", optional = true }
num-traits = { version = "0.2.19", default-features = false }
rand_core = { version = "0.9", optional = true, default-features = false }
rand_core = { version = "0.9.2", optional = true, default-features = false }
rlp = { version = "0.6", optional = true, default-features = false }
serdect = { version = "0.3", optional = true, default-features = false }
zeroize = { version = "1", optional = true, default-features = false }
Expand Down
6 changes: 3 additions & 3 deletions src/int/rand.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
//! Random number generator support
use rand_core::{RngCore, TryRngCore};
use rand_core::TryRngCore;

use crate::{Int, Random, RandomBits, RandomBitsError};

use super::Uint;

impl<const LIMBS: usize> Random for Int<LIMBS> {
/// Generate a cryptographically secure random [`Int`].
fn random<R: RngCore + ?Sized>(rng: &mut R) -> Self {
Self(Uint::random(rng))
fn try_random<R: TryRngCore + ?Sized>(rng: &mut R) -> Result<Self, R::Error> {
Ok(Self(Uint::try_random(rng)?))
}
}

Expand Down
24 changes: 13 additions & 11 deletions src/limb/rand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,38 @@
use super::Limb;
use crate::{Encoding, NonZero, Random, RandomMod};
use rand_core::RngCore;
use rand_core::TryRngCore;
use subtle::ConstantTimeLess;

impl Random for Limb {
#[cfg(target_pointer_width = "32")]
fn random<R: RngCore + ?Sized>(rng: &mut R) -> Self {
Self(rng.next_u32())
}
fn try_random<R: TryRngCore + ?Sized>(rng: &mut R) -> Result<Self, R::Error> {
#[cfg(target_pointer_width = "32")]
let val = rng.try_next_u32()?;
#[cfg(target_pointer_width = "64")]
let val = rng.try_next_u64()?;

#[cfg(target_pointer_width = "64")]
fn random<R: RngCore + ?Sized>(rng: &mut R) -> Self {
Self(rng.next_u64())
Ok(Self(val))
}
}

impl RandomMod for Limb {
fn random_mod<R: RngCore + ?Sized>(rng: &mut R, modulus: &NonZero<Self>) -> Self {
fn try_random_mod<R: TryRngCore + ?Sized>(
rng: &mut R,
modulus: &NonZero<Self>,
) -> Result<Self, R::Error> {
let mut bytes = <Self as Encoding>::Repr::default();

let n_bits = modulus.bits() as usize;
let n_bytes = (n_bits + 7) / 8;
let mask = 0xffu8 >> (8 * n_bytes - n_bits);

loop {
rng.fill_bytes(&mut bytes[..n_bytes]);
rng.try_fill_bytes(&mut bytes[..n_bytes])?;
bytes[n_bytes - 1] &= mask;

let n = Limb::from_le_bytes(bytes);
if n.ct_lt(modulus).into() {
return n;
return Ok(n);
}
}
}
Expand Down
9 changes: 6 additions & 3 deletions src/modular/const_monty_form.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use core::{fmt::Debug, marker::PhantomData};
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};

#[cfg(feature = "rand_core")]
use crate::{Random, RandomMod, rand_core::RngCore};
use crate::{Random, RandomMod, rand_core::TryRngCore};

#[cfg(feature = "serde")]
use {
Expand Down Expand Up @@ -204,8 +204,11 @@ where
MOD: ConstMontyParams<LIMBS>,
{
#[inline]
fn random<R: RngCore + ?Sized>(rng: &mut R) -> Self {
Self::new(&Uint::random_mod(rng, MOD::MODULUS.as_nz_ref()))
fn try_random<R: TryRngCore + ?Sized>(rng: &mut R) -> Result<Self, R::Error> {
Ok(Self::new(&Uint::try_random_mod(
rng,
MOD::MODULUS.as_nz_ref(),
)?))
}
}

Expand Down
8 changes: 4 additions & 4 deletions src/non_zero.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption};
use crate::{ArrayEncoding, ByteArray};

#[cfg(feature = "rand_core")]
use {crate::Random, rand_core::RngCore};
use {crate::Random, rand_core::TryRngCore};

#[cfg(feature = "serde")]
use serdect::serde::{
Expand Down Expand Up @@ -246,10 +246,10 @@ where
/// As a result, it runs in variable time. If the generator `rng` is
/// cryptographically secure (for example, it implements `CryptoRng`),
/// then this is guaranteed not to leak anything about the output value.
fn random<R: RngCore + ?Sized>(mut rng: &mut R) -> Self {
fn try_random<R: TryRngCore + ?Sized>(rng: &mut R) -> Result<Self, R::Error> {
loop {
if let Some(result) = Self::new(T::random(&mut rng)).into() {
break result;
if let Some(result) = Self::new(T::try_random(rng)?).into() {
break Ok(result);
}
}
}
Expand Down
10 changes: 5 additions & 5 deletions src/odd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption};
use crate::BoxedUint;

#[cfg(feature = "rand_core")]
use {crate::Random, rand_core::RngCore};
use crate::{Random, rand_core::TryRngCore};

#[cfg(all(feature = "alloc", feature = "rand_core"))]
use {crate::RandomBits, rand_core::TryRngCore};
use crate::RandomBits;

#[cfg(feature = "serde")]
use crate::Zero;
Expand Down Expand Up @@ -153,10 +153,10 @@ impl PartialOrd<Odd<BoxedUint>> for BoxedUint {
#[cfg(feature = "rand_core")]
impl<const LIMBS: usize> Random for Odd<Uint<LIMBS>> {
/// Generate a random `Odd<Uint<T>>`.
fn random<R: RngCore + ?Sized>(rng: &mut R) -> Self {
let mut ret = Uint::random(rng);
fn try_random<R: TryRngCore + ?Sized>(rng: &mut R) -> Result<Self, R::Error> {
let mut ret = Uint::try_random(rng)?;
ret.limbs[0] |= Limb::ONE;
Odd(ret)
Ok(Odd(ret))
}
}

Expand Down
29 changes: 27 additions & 2 deletions src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,15 @@ pub trait Random: Sized {
/// Generate a random value.
///
/// If `rng` is a CSRNG, the generation is cryptographically secure as well.
fn random<R: RngCore + ?Sized>(rng: &mut R) -> Self;
fn random<R: RngCore + ?Sized>(rng: &mut R) -> Self {
let Ok(out) = Self::try_random(rng);
out
}

/// Generate a random value.
///
/// If `rng` is a CSRNG, the generation is cryptographically secure as well.
fn try_random<R: TryRngCore + ?Sized>(rng: &mut R) -> Result<Self, R::Error>;
}

/// Possible errors of the methods in [`RandomBits`] trait.
Expand Down Expand Up @@ -419,7 +427,24 @@ pub trait RandomMod: Sized + Zero {
/// example, it implements `CryptoRng`), then this is guaranteed not to
/// leak anything about the output value aside from it being less than
/// `modulus`.
fn random_mod<R: RngCore + ?Sized>(rng: &mut R, modulus: &NonZero<Self>) -> Self;
fn random_mod<R: RngCore + ?Sized>(rng: &mut R, modulus: &NonZero<Self>) -> Self {
let Ok(out) = Self::try_random_mod(rng, modulus);
out
}

/// Generate a random number which is less than a given `modulus`.
///
/// This uses rejection sampling.
///
/// As a result, it runs in variable time that depends in part on
/// `modulus`. If the generator `rng` is cryptographically secure (for
/// example, it implements `CryptoRng`), then this is guaranteed not to
/// leak anything about the output value aside from it being less than
/// `modulus`.
fn try_random_mod<R: TryRngCore + ?Sized>(
rng: &mut R,
modulus: &NonZero<Self>,
) -> Result<Self, R::Error>;
}

/// Compute `self + rhs mod p`.
Expand Down
11 changes: 10 additions & 1 deletion src/uint/boxed/rand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,18 @@ impl RandomBits for BoxedUint {
impl RandomMod for BoxedUint {
fn random_mod<R: RngCore + ?Sized>(rng: &mut R, modulus: &NonZero<Self>) -> Self {
let mut n = BoxedUint::zero_with_precision(modulus.bits_precision());
random_mod_core(rng, &mut n, modulus, modulus.bits());
let Ok(()) = random_mod_core(rng, &mut n, modulus, modulus.bits());
n
}

fn try_random_mod<R: TryRngCore + ?Sized>(
rng: &mut R,
modulus: &NonZero<Self>,
) -> Result<Self, R::Error> {
let mut n = BoxedUint::zero_with_precision(modulus.bits_precision());
random_mod_core(rng, &mut n, modulus, modulus.bits())?;
Ok(n)
}
}

#[cfg(test)]
Expand Down
35 changes: 23 additions & 12 deletions src/uint/rand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ use rand_core::{RngCore, TryRngCore};
use subtle::ConstantTimeLess;

impl<const LIMBS: usize> Random for Uint<LIMBS> {
fn random<R: RngCore + ?Sized>(mut rng: &mut R) -> Self {
fn try_random<R: TryRngCore + ?Sized>(rng: &mut R) -> Result<Self, R::Error> {
let mut limbs = [Limb::ZERO; LIMBS];

for limb in &mut limbs {
*limb = Limb::random(&mut rng)
*limb = Limb::try_random(rng)?
}

limbs.into()
Ok(limbs.into())
}
}

Expand Down Expand Up @@ -83,35 +83,45 @@ impl<const LIMBS: usize> RandomBits for Uint<LIMBS> {
impl<const LIMBS: usize> RandomMod for Uint<LIMBS> {
fn random_mod<R: RngCore + ?Sized>(rng: &mut R, modulus: &NonZero<Self>) -> Self {
let mut n = Self::ZERO;
random_mod_core(rng, &mut n, modulus, modulus.bits_vartime());
let Ok(()) = random_mod_core(rng, &mut n, modulus, modulus.bits_vartime());
n
}

fn try_random_mod<R: TryRngCore + ?Sized>(
rng: &mut R,
modulus: &NonZero<Self>,
) -> Result<Self, R::Error> {
let mut n = Self::ZERO;
random_mod_core(rng, &mut n, modulus, modulus.bits_vartime())?;
Ok(n)
}
}

/// Generic implementation of `random_mod` which can be shared with `BoxedUint`.
// TODO(tarcieri): obtain `n_bits` via a trait like `Integer`
pub(super) fn random_mod_core<T, R: RngCore + ?Sized>(
pub(super) fn random_mod_core<T, R: TryRngCore + ?Sized>(
rng: &mut R,
n: &mut T,
modulus: &NonZero<T>,
n_bits: u32,
) where
) -> Result<(), R::Error>
where
T: AsMut<[Limb]> + AsRef<[Limb]> + ConstantTimeLess + Zero,
{
#[cfg(target_pointer_width = "64")]
let mut next_word = || rng.next_u64();
let mut next_word = || rng.try_next_u64();
#[cfg(target_pointer_width = "32")]
let mut next_word = || rng.next_u32();
let mut next_word = || rng.try_next_u32();

let n_limbs = n_bits.div_ceil(Limb::BITS) as usize;

let hi_word_modulus = modulus.as_ref().as_ref()[n_limbs - 1].0;
let mask = !0 >> hi_word_modulus.leading_zeros();
let mut hi_word = next_word() & mask;
let mut hi_word = next_word()? & mask;

loop {
while hi_word > hi_word_modulus {
hi_word = next_word() & mask;
hi_word = next_word()? & mask;
}
// Set high limb
n.as_mut()[n_limbs - 1] = Limb::from_le_bytes(hi_word.to_le_bytes());
Expand All @@ -120,15 +130,16 @@ pub(super) fn random_mod_core<T, R: RngCore + ?Sized>(
// 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.as_mut()[i] = Limb::from_le_bytes(next_word().to_le_bytes());
n.as_mut()[i] = Limb::from_le_bytes(next_word()?.to_le_bytes());
}
// If the high limb is equal to the modulus' high limb, it's still possible
// that the full uint is too big so we check and repeat if it is.
if n.ct_lt(modulus).into() {
break;
}
hi_word = next_word() & mask;
hi_word = next_word()? & mask;
}
Ok(())
}

#[cfg(test)]
Expand Down
6 changes: 3 additions & 3 deletions src/wrapping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use core::{
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};

#[cfg(feature = "rand_core")]
use {crate::Random, rand_core::RngCore};
use {crate::Random, rand_core::TryRngCore};

#[cfg(feature = "serde")]
use serdect::serde::{Deserialize, Deserializer, Serialize, Serializer};
Expand Down Expand Up @@ -259,8 +259,8 @@ impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {

#[cfg(feature = "rand_core")]
impl<T: Random> Random for Wrapping<T> {
fn random<R: RngCore + ?Sized>(rng: &mut R) -> Self {
Wrapping(Random::random(rng))
fn try_random<R: TryRngCore + ?Sized>(rng: &mut R) -> Result<Self, R::Error> {
Ok(Wrapping(Random::try_random(rng)?))
}
}

Expand Down