Skip to content

Commit 13379ad

Browse files
committed
Improve P256 hash_to_scalar
1 parent 3d9f02f commit 13379ad

File tree

1 file changed

+9
-13
lines changed

1 file changed

+9
-13
lines changed

src/group/p256.rs

+9-13
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ use num_bigint::{BigInt, Sign};
2525
use num_integer::Integer;
2626
use num_traits::{One, ToPrimitive, Zero};
2727
use once_cell::unsync::Lazy;
28+
use p256_::elliptic_curve::bigint::{Encoding, U384};
2829
use p256_::elliptic_curve::group::prime::PrimeCurveAffine;
2930
use p256_::elliptic_curve::ops::Reduce;
3031
use p256_::elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint};
@@ -122,24 +123,19 @@ impl Group for NistP256 {
122123
// P-256 `n` is defined as
123124
// `115792089210356248762697446949407573529996955224135760342
124125
// 422259061068512044369`
125-
const N: Lazy<BigInt> = Lazy::new(|| {
126-
BigInt::from_str(
127-
"115792089210356248762697446949407573529996955224135760342422259061068512044369",
128-
)
129-
.unwrap()
130-
});
126+
const N: U384 =
127+
U384::from_be_hex("00000000000000000000000000000000FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551");
131128

132129
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-5.3
133130
// `HashToScalar` is `hash_to_field`
134131
let uniform_bytes = super::expand::expand_message_xmd::<H, L>(input, &dst)?;
135-
let bytes = BigInt::from_bytes_be(Sign::Plus, &uniform_bytes)
136-
.mod_floor(&N)
137-
.to_bytes_be()
138-
.1;
139-
let mut result = GenericArray::default();
140-
result[..bytes.len()].copy_from_slice(&bytes);
132+
let bytes = Option::<U384>::from(U384::from_be_slice(&uniform_bytes).reduce(&N))
133+
.unwrap()
134+
.to_be_bytes();
141135

142-
Ok(Scalar::from_be_bytes_reduced(result))
136+
Ok(Scalar::from_be_bytes_reduced(
137+
GenericArray::clone_from_slice(&bytes[16..]),
138+
))
143139
}
144140

145141
fn base_elem() -> Self::Elem {

0 commit comments

Comments
 (0)