Skip to content

Commit 5154730

Browse files
authored
k256: use TryCryptoRng for generate_vartime (#1132)
We can make this work by reversing the caller relationship with `Field::try_from_rng` and having `generate_vartime` call that
1 parent c6b8af1 commit 5154730

File tree

1 file changed

+12
-13
lines changed

1 file changed

+12
-13
lines changed

k256/src/arithmetic/scalar.rs

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use elliptic_curve::{
1616
bigint::{Limb, U256, U512, Word, prelude::*},
1717
ff::{self, Field, PrimeField},
1818
ops::{Invert, Reduce, ReduceNonZero},
19-
rand_core::{CryptoRng, TryRngCore},
19+
rand_core::{CryptoRng, TryCryptoRng, TryRngCore},
2020
scalar::{FromUintUnchecked, IsHigh},
2121
subtle::{
2222
Choice, ConditionallySelectable, ConstantTimeEq, ConstantTimeGreater, ConstantTimeLess,
@@ -191,17 +191,8 @@ impl Scalar {
191191
}
192192

193193
/// Returns a uniformly-random scalar, generated using rejection sampling.
194-
// TODO(tarcieri): make this a `CryptoRng` when `ff` allows it
195-
pub fn generate_vartime<R: TryRngCore + ?Sized>(rng: &mut R) -> Result<Self, R::Error> {
196-
let mut bytes = FieldBytes::default();
197-
198-
// TODO: pre-generate several scalars to bring the probability of non-constant-timeness down?
199-
loop {
200-
rng.try_fill_bytes(&mut bytes)?;
201-
if let Some(scalar) = Scalar::from_repr(bytes).into() {
202-
return Ok(scalar);
203-
}
204-
}
194+
pub fn generate_vartime<R: TryCryptoRng + ?Sized>(rng: &mut R) -> Result<Self, R::Error> {
195+
Self::try_from_rng(rng)
205196
}
206197

207198
/// Attempts to parse the given byte array as a scalar.
@@ -234,7 +225,15 @@ impl Field for Scalar {
234225
//
235226
// With an unbiased RNG, the probability of failing to complete after 4
236227
// iterations is vanishingly small.
237-
Self::generate_vartime(rng)
228+
let mut bytes = FieldBytes::default();
229+
230+
// TODO: pre-generate several scalars to bring the probability of non-constant-timeness down?
231+
loop {
232+
rng.try_fill_bytes(&mut bytes)?;
233+
if let Some(scalar) = Scalar::from_repr(bytes).into() {
234+
return Ok(scalar);
235+
}
236+
}
238237
}
239238

240239
#[must_use]

0 commit comments

Comments
 (0)