Skip to content

Commit

Permalink
elliptic-curve: add Invert::invert_vartime (RustCrypto#1239)
Browse files Browse the repository at this point in the history
Adds support for optimized variable-time inversions via the `Invert`
trait.

By default, the implementation uses a constant-time inversion by calling
`Invert::invert`.
  • Loading branch information
tarcieri authored Feb 3, 2023
1 parent 771f5df commit d19d50f
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
11 changes: 11 additions & 0 deletions elliptic-curve/src/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,17 @@ pub trait Invert {

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

/// Invert a field element in variable time.
///
/// ⚠️ WARNING!
///
/// This method should not be used with secret values, as its variable-time
/// operation can potentially leak secrets through sidechannels.
fn invert_vartime(&self) -> Self::Output {
// Fall back on constant-time implementation by default.
self.invert()
}
}

impl<F: ff::Field> Invert for F {
Expand Down
8 changes: 8 additions & 0 deletions elliptic-curve/src/scalar/invert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@ use subtle::CtOption;
/// Returns none if the scalar is zero.
///
/// <https://link.springer.com/article/10.1007/s13389-016-0135-4>
///
/// ⚠️ WARNING!
///
/// This generic implementation relies on special properties of the scalar
/// field implementation and may not work correctly! Please ensure your use
/// cases are well-tested!
///
/// USE AT YOUR OWN RISK!
#[allow(non_snake_case)]
pub fn invert_vartime<C>(scalar: &Scalar<C>) -> CtOption<Scalar<C>>
where
Expand Down
10 changes: 9 additions & 1 deletion elliptic-curve/src/scalar/nonzero.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,13 +184,21 @@ where
impl<C> Invert for NonZeroScalar<C>
where
C: CurveArithmetic,
Scalar<C>: Invert<Output = CtOption<Scalar<C>>>,
{
type Output = Self;

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

fn invert_vartime(&self) -> Self::Output {
Self {
// This will always succeed since `scalar` will never be 0
scalar: Invert::invert_vartime(&self.scalar).unwrap(),
}
}
}
Expand Down

0 comments on commit d19d50f

Please sign in to comment.