Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/modular/boxed_residue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
//! is chosen at runtime.

mod add;
mod inv;
mod mul;
mod neg;
mod pow;
Expand Down
35 changes: 35 additions & 0 deletions src/modular/boxed_residue/inv.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
//! Multiplicative inverses of boxed residue.

use super::BoxedResidue;
use crate::{modular::reduction::montgomery_reduction_boxed, traits::Invert};
use subtle::CtOption;

impl BoxedResidue {
/// Computes the residue `self^-1` representing the multiplicative inverse of `self`.
/// I.e. `self * self^-1 = 1`.
pub fn invert(&self) -> CtOption<Self> {
let (inverse, is_some) = self
.montgomery_form
.inv_odd_mod(&self.residue_params.modulus);

let montgomery_form = montgomery_reduction_boxed(
&mut inverse.mul_wide(&self.residue_params.r3),
&self.residue_params.modulus,
self.residue_params.mod_neg_inv,
);

let value = Self {
montgomery_form,
residue_params: self.residue_params.clone(),
};

CtOption::new(value, is_some)
}
}

impl Invert for BoxedResidue {
type Output = CtOption<Self>;
fn invert(&self) -> Self::Output {
self.invert()
}
}
2 changes: 1 addition & 1 deletion src/uint/boxed/inv_mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ impl BoxedUint {

/// Computes the multiplicative inverse of `self` mod `modulus`, where `modulus` is odd.
/// Returns `None` if an inverse does not exist.
fn inv_odd_mod(&self, modulus: &Self) -> (Self, Choice) {
pub(crate) fn inv_odd_mod(&self, modulus: &Self) -> (Self, Choice) {
self.inv_odd_mod_bounded(modulus, self.bits_precision(), modulus.bits_precision())
}

Expand Down
18 changes: 17 additions & 1 deletion tests/boxed_residue_proptests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crypto_bigint::{
modular::{BoxedResidue, BoxedResidueParams},
BoxedUint, Limb, NonZero,
};
use num_bigint::BigUint;
use num_bigint::{BigUint, ModInverse};
use proptest::prelude::*;
use std::cmp::Ordering;

Expand Down Expand Up @@ -59,6 +59,22 @@ prop_compose! {
}

proptest! {
#[test]
fn inv(x in uint(), n in modulus()) {
let x = reduce(&x, n.clone());
let actual = Option::<BoxedResidue>::from(x.invert()).map(|a| a.retrieve());

let x_bi = retrieve_biguint(&x);
let n_bi = to_biguint(n.modulus());
let expected = x_bi.mod_inverse(&n_bi);

match (expected, actual) {
(Some(exp), Some(act)) => prop_assert_eq!(exp, to_biguint(&act).into()),
(None, None) => (),
(_, _) => panic!("disagreement on if modular inverse exists")
}
}

#[test]
fn mul((a, b) in residue_pair()) {
let p = a.params().modulus();
Expand Down