Skip to content

Commit 53f3f42

Browse files
committed
elliptic-curve: make SecretKey::new failible
This fixes an invariant violation where you could create a secret key from an all-zero scalar and convert it to a non-zero scala. :
1 parent 8efa5bd commit 53f3f42

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

elliptic-curve/src/secret_key.rs

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,13 @@ mod pkcs8;
1111
use crate::{Curve, Error, FieldBytes, Result, ScalarPrimitive};
1212
use core::fmt::{self, Debug};
1313
use hybrid_array::typenum::Unsigned;
14-
use subtle::{Choice, ConstantTimeEq};
14+
use subtle::{Choice, ConstantTimeEq, CtOption};
1515
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
1616

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

2323
#[cfg(feature = "jwk")]
@@ -29,17 +29,17 @@ use pem_rfc7468::{self as pem, PemLabel};
2929
#[cfg(feature = "sec1")]
3030
use {
3131
crate::{
32-
FieldBytesSize,
3332
sec1::{EncodedPoint, ModulusSize, ValidatePublicKey},
33+
FieldBytesSize,
3434
},
3535
sec1::der::{self, oid::AssociatedOid},
3636
};
3737

3838
#[cfg(all(feature = "alloc", feature = "arithmetic", feature = "sec1"))]
3939
use {
4040
crate::{
41-
AffinePoint,
4241
sec1::{FromEncodedPoint, ToEncodedPoint},
42+
AffinePoint,
4343
},
4444
alloc::vec::Vec,
4545
sec1::der::Encode,
@@ -117,8 +117,12 @@ where
117117
}
118118

119119
/// Create a new secret key from a scalar value.
120-
pub fn new(scalar: ScalarPrimitive<C>) -> Self {
121-
Self { inner: scalar }
120+
///
121+
/// # Returns
122+
///
123+
/// This will return a none if the scalar is all-zero.
124+
pub fn new(scalar: ScalarPrimitive<C>) -> CtOption<Self> {
125+
CtOption::new(Self { inner: scalar }, !scalar.is_zero())
122126
}
123127

124128
/// Borrow the inner secret [`ScalarPrimitive`] value.

0 commit comments

Comments
 (0)