Skip to content

Commit

Permalink
elliptic-curve: add ReduceNonZero trait (#827)
Browse files Browse the repository at this point in the history
Adds a trait similar to `Reduce`, but where the output of the reduction
is ensured to be non-zero.

Also impls `Reduce` and `ReduceNonZero` for `NonZeroScalar`. This means
that end users need only concern themselves with `Reduce` as they can
use `NonZeroScalar::<C>::from_uint_reduced` instead of the more
cumbersome `Scalar::<C>::from_uint_reduced_non_zero`.

Related: RustCrypto/elliptic-curves#432
  • Loading branch information
tarcieri committed Dec 3, 2021
1 parent afe0b79 commit f6ac4b0
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
10 changes: 10 additions & 0 deletions elliptic-curve/src/ops.rs
Expand Up @@ -40,3 +40,13 @@ pub trait Reduce<UInt: Integer + ArrayEncoding>: Sized {
Self::from_uint_reduced(UInt::from_le_byte_array(bytes))
}
}

/// Modular reduction to a non-zero output.
///
/// This trait is primarily intended for use by curve implementations.
///
/// End users can use the `Reduce` impl on `NonZeroScalar` instead.
pub trait ReduceNonZero<UInt: Integer + ArrayEncoding>: Sized {
/// Perform a modular reduction, returning a field element.
fn from_uint_reduced_non_zero(n: UInt) -> Self;
}
28 changes: 27 additions & 1 deletion elliptic-curve/src/scalar/non_zero.rs
Expand Up @@ -3,7 +3,7 @@
use crate::{
bigint::Encoding as _,
hex,
ops::Invert,
ops::{Invert, Reduce, ReduceNonZero},
rand_core::{CryptoRng, RngCore},
Curve, Error, FieldBytes, IsHigh, Result, Scalar, ScalarArithmetic, ScalarCore, SecretKey,
};
Expand All @@ -12,6 +12,7 @@ use core::{
ops::{Deref, Neg},
str,
};
use crypto_bigint::{ArrayEncoding, Integer};
use ff::{Field, PrimeField};
use generic_array::GenericArray;
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption};
Expand Down Expand Up @@ -198,6 +199,31 @@ where
}
}

/// Note: implementation is the same as `ReduceNonZero`
impl<C, I> Reduce<I> for NonZeroScalar<C>
where
C: Curve + ScalarArithmetic,
I: Integer + ArrayEncoding,
Scalar<C>: ReduceNonZero<I>,
{
fn from_uint_reduced(n: I) -> Self {
Self::from_uint_reduced_non_zero(n)
}
}

impl<C, I> ReduceNonZero<I> for NonZeroScalar<C>
where
C: Curve + ScalarArithmetic,
I: Integer + ArrayEncoding,
Scalar<C>: ReduceNonZero<I>,
{
fn from_uint_reduced_non_zero(n: I) -> Self {
let scalar = Scalar::<C>::from_uint_reduced_non_zero(n);
debug_assert!(!bool::from(scalar.is_zero()));
Self::new(scalar).unwrap()
}
}

impl<C> TryFrom<&[u8]> for NonZeroScalar<C>
where
C: Curve + ScalarArithmetic,
Expand Down

0 comments on commit f6ac4b0

Please sign in to comment.