Skip to content

Commit bd20996

Browse files
authored
elliptic-curve:: adds try_from_rng method to SecretKey and EphemeralSecret (#1789)
Follow up to #1774
1 parent ea9b99a commit bd20996

File tree

3 files changed

+25
-13
lines changed

3 files changed

+25
-13
lines changed

elliptic-curve/src/dev.rs

-11
Original file line numberDiff line numberDiff line change
@@ -99,17 +99,6 @@ impl Field for Scalar {
9999
const ZERO: Self = Self(ScalarPrimitive::ZERO);
100100
const ONE: Self = Self(ScalarPrimitive::ONE);
101101

102-
fn random<R: RngCore + ?Sized>(rng: &mut R) -> Self {
103-
let mut bytes = FieldBytes::default();
104-
105-
loop {
106-
rng.fill_bytes(&mut bytes);
107-
if let Some(scalar) = Self::from_repr(bytes).into() {
108-
return scalar;
109-
}
110-
}
111-
}
112-
113102
fn try_from_rng<R: TryRngCore + ?Sized>(rng: &mut R) -> core::result::Result<Self, R::Error> {
114103
let mut bytes = FieldBytes::default();
115104

elliptic-curve/src/ecdh.rs

+8-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ use core::{borrow::Borrow, fmt};
3434
use digest::{Digest, crypto_common::BlockSizeUser};
3535
use group::Curve as _;
3636
use hkdf::{Hkdf, hmac::SimpleHmac};
37-
use rand_core::CryptoRng;
37+
use rand_core::{CryptoRng, TryCryptoRng};
3838
use zeroize::{Zeroize, ZeroizeOnDrop};
3939

4040
/// Low-level Elliptic Curve Diffie-Hellman (ECDH) function.
@@ -114,6 +114,13 @@ where
114114
}
115115
}
116116

117+
/// Generate a cryptographically random [`EphemeralSecret`].
118+
pub fn try_from_rng<R: TryCryptoRng + ?Sized>(rng: &mut R) -> Result<Self, R::Error> {
119+
Ok(Self {
120+
scalar: NonZeroScalar::try_from_rng(rng)?,
121+
})
122+
}
123+
117124
/// Get the public key associated with this ephemeral secret.
118125
///
119126
/// The `compress` flag enables point compression.

elliptic-curve/src/secret_key.rs

+17-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,10 @@ use subtle::{Choice, ConstantTimeEq};
1515
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
1616

1717
#[cfg(feature = "arithmetic")]
18-
use crate::{CurveArithmetic, NonZeroScalar, PublicKey, rand_core::CryptoRng};
18+
use crate::{
19+
CurveArithmetic, NonZeroScalar, PublicKey,
20+
rand_core::{CryptoRng, TryCryptoRng},
21+
};
1922

2023
#[cfg(feature = "jwk")]
2124
use crate::jwk::{JwkEcKey, JwkParameters};
@@ -100,6 +103,19 @@ where
100103
}
101104
}
102105

106+
/// Generate a random [`SecretKey`].
107+
#[cfg(feature = "arithmetic")]
108+
pub fn try_from_rng<R: TryCryptoRng + ?Sized>(
109+
rng: &mut R,
110+
) -> core::result::Result<Self, R::Error>
111+
where
112+
C: CurveArithmetic,
113+
{
114+
Ok(Self {
115+
inner: NonZeroScalar::<C>::try_from_rng(rng)?.into(),
116+
})
117+
}
118+
103119
/// Create a new secret key from a scalar value.
104120
pub fn new(scalar: ScalarPrimitive<C>) -> Self {
105121
Self { inner: scalar }

0 commit comments

Comments
 (0)