diff --git a/elliptic-curve/src/dev.rs b/elliptic-curve/src/dev.rs index 26b14d902..4f1c58811 100644 --- a/elliptic-curve/src/dev.rs +++ b/elliptic-curve/src/dev.rs @@ -99,17 +99,6 @@ impl Field for Scalar { const ZERO: Self = Self(ScalarPrimitive::ZERO); const ONE: Self = Self(ScalarPrimitive::ONE); - fn random(rng: &mut R) -> Self { - let mut bytes = FieldBytes::default(); - - loop { - rng.fill_bytes(&mut bytes); - if let Some(scalar) = Self::from_repr(bytes).into() { - return scalar; - } - } - } - fn try_from_rng(rng: &mut R) -> core::result::Result { let mut bytes = FieldBytes::default(); diff --git a/elliptic-curve/src/ecdh.rs b/elliptic-curve/src/ecdh.rs index c4881fe6e..baf4d9a98 100644 --- a/elliptic-curve/src/ecdh.rs +++ b/elliptic-curve/src/ecdh.rs @@ -34,7 +34,7 @@ use core::{borrow::Borrow, fmt}; use digest::{Digest, crypto_common::BlockSizeUser}; use group::Curve as _; use hkdf::{Hkdf, hmac::SimpleHmac}; -use rand_core::CryptoRng; +use rand_core::{CryptoRng, TryCryptoRng}; use zeroize::{Zeroize, ZeroizeOnDrop}; /// Low-level Elliptic Curve Diffie-Hellman (ECDH) function. @@ -114,6 +114,13 @@ where } } + /// Generate a cryptographically random [`EphemeralSecret`]. + pub fn try_from_rng(rng: &mut R) -> Result { + Ok(Self { + scalar: NonZeroScalar::try_from_rng(rng)?, + }) + } + /// Get the public key associated with this ephemeral secret. /// /// The `compress` flag enables point compression. diff --git a/elliptic-curve/src/secret_key.rs b/elliptic-curve/src/secret_key.rs index 02f9778e8..1c15dc797 100644 --- a/elliptic-curve/src/secret_key.rs +++ b/elliptic-curve/src/secret_key.rs @@ -15,7 +15,10 @@ use subtle::{Choice, ConstantTimeEq}; use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing}; #[cfg(feature = "arithmetic")] -use crate::{CurveArithmetic, NonZeroScalar, PublicKey, rand_core::CryptoRng}; +use crate::{ + CurveArithmetic, NonZeroScalar, PublicKey, + rand_core::{CryptoRng, TryCryptoRng}, +}; #[cfg(feature = "jwk")] use crate::jwk::{JwkEcKey, JwkParameters}; @@ -100,6 +103,19 @@ where } } + /// Generate a random [`SecretKey`]. + #[cfg(feature = "arithmetic")] + pub fn try_from_rng( + rng: &mut R, + ) -> core::result::Result + where + C: CurveArithmetic, + { + Ok(Self { + inner: NonZeroScalar::::try_from_rng(rng)?.into(), + }) + } + /// Create a new secret key from a scalar value. pub fn new(scalar: ScalarPrimitive) -> Self { Self { inner: scalar }