Skip to content

Commit 30da3cc

Browse files
authored
p521: use reduction in ReduceNonZero<U576> (#1345)
1 parent 5524cdd commit 30da3cc

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

p521/src/arithmetic/scalar.rs

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ use core::{
2222
};
2323
use elliptic_curve::{
2424
Curve as _, Error, FieldBytesEncoding, Result,
25-
bigint::{self, Integer},
25+
bigint::{self, Integer, NonZero},
2626
ff::{self, Field, PrimeField},
2727
ops::{Invert, Reduce, ReduceNonZero},
2828
rand_core::TryRngCore,
@@ -575,11 +575,8 @@ impl Reduce<U576> for Scalar {
575575
impl ReduceNonZero<U576> for Scalar {
576576
fn reduce_nonzero(w: U576) -> Self {
577577
const ORDER_MINUS_ONE: U576 = NistP521::ORDER.wrapping_sub(&U576::ONE);
578-
let (r, underflow) = w.borrowing_sub(&ORDER_MINUS_ONE, bigint::Limb::ZERO);
579-
let underflow = Choice::from((underflow.0 >> (bigint::Limb::BITS - 1)) as u8);
580-
Self::from_uint_unchecked(
581-
U576::conditional_select(&w, &r, !underflow).wrapping_add(&U576::ONE),
582-
)
578+
let r = w.rem(&NonZero::new(ORDER_MINUS_ONE).unwrap());
579+
Self::from_uint_unchecked(r.wrapping_add(&U576::ONE))
583580
}
584581

585582
fn reduce_nonzero_bytes(bytes: &FieldBytes) -> Self {
@@ -707,6 +704,13 @@ mod tests {
707704
)),
708705
U576::from_u8(4),
709706
);
707+
708+
assert_eq!(
709+
U576::from(Scalar::reduce_nonzero(
710+
NistP521::ORDER.wrapping_mul(&U576::from_u8(3))
711+
)),
712+
U576::from_u8(4),
713+
);
710714
}
711715

712716
prop_compose! {

0 commit comments

Comments
 (0)