Skip to content

Commit

Permalink
elliptic-curve: make NonZeroScalar::invert infallible
Browse files Browse the repository at this point in the history
Because `NonZeroScalar` means we'll never divide by 0, it's possible to
make the implementation infallible.

To accomplish this, `CtOption` is removed from the `Invert` trait's
signature, and used as the result type for scalars that are potentially
zero as part of the blanket impl of `Invert`.

Fixes RustCrypto/elliptic-curves#499
  • Loading branch information
tarcieri committed Jan 17, 2022
1 parent dc47a5a commit 712434d
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 8 deletions.
7 changes: 3 additions & 4 deletions elliptic-curve/src/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@
pub use core::ops::{Add, AddAssign, Mul, Neg, Sub, SubAssign};

use crypto_bigint::{ArrayEncoding, ByteArray, Integer};
use subtle::CtOption;

#[cfg(feature = "arithmetic")]
use group::Group;
use {group::Group, subtle::CtOption};

#[cfg(feature = "digest")]
use digest::{core_api::BlockSizeUser, Digest, FixedOutput, Reset};
Expand All @@ -17,12 +16,12 @@ pub trait Invert {
type Output;

/// Invert a field element.
fn invert(&self) -> CtOption<Self::Output>;
fn invert(&self) -> Self::Output;
}

#[cfg(feature = "arithmetic")]
impl<F: ff::Field> Invert for F {
type Output = F;
type Output = CtOption<F>;

fn invert(&self) -> CtOption<F> {
ff::Field::invert(self)
Expand Down
10 changes: 6 additions & 4 deletions elliptic-curve/src/scalar/nonzero.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,11 +170,13 @@ impl<C> Invert for NonZeroScalar<C>
where
C: Curve + ScalarArithmetic,
{
type Output = Scalar<C>;
type Output = Self;

/// Perform a scalar inversion
fn invert(&self) -> CtOption<Self::Output> {
ff::Field::invert(&self.scalar)
fn invert(&self) -> Self {
Self {
// This will always succeed since `scalar` will never be 0
scalar: ff::Field::invert(&self.scalar).unwrap(),
}
}
}

Expand Down

0 comments on commit 712434d

Please sign in to comment.