Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

elliptic-curve: add ReduceNonZero trait #827

Merged
merged 1 commit into from Dec 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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