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
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ pub use crate::{
};

// TODO(tarcieri): get rid of `Const*` prefix
pub use ctutils::{Choice as ConstChoice, CtOption as ConstCtOption};
pub use ctutils::{Choice as ConstChoice, CtOption as ConstCtOption, CtSelect};

#[cfg(feature = "alloc")]
pub use crate::uint::boxed::BoxedUint;
Expand Down
2 changes: 1 addition & 1 deletion src/modular/pow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ where
// Constant-time lookup in the array of powers
power.as_mut_limbs().copy_from_slice(powers[0].as_limbs());
for i in 1..(1 << WINDOW) {
power.ct_assign(&powers[i], (i as Word).ct_eq(&idx));
power.ct_assign(&powers[i], (i as Word).ct_eq(&idx).into());
}

multiplier.mul_amm_assign(&mut z, &power);
Expand Down
6 changes: 3 additions & 3 deletions src/modular/safegcd/boxed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

use super::{GCD_BATCH_SIZE, Matrix, iterations, jump};
use crate::{
BoxedUint, ConstChoice, ConstantTimeSelect, I64, Int, Limb, NonZero, Odd, Resize, U64, Uint,
BoxedUint, ConstChoice, CtSelect, I64, Int, Limb, NonZero, Odd, Resize, U64, Uint,
primitives::{u32_max, u32_min},
};
use core::fmt;
Expand Down Expand Up @@ -127,7 +127,7 @@ fn invert_odd_mod_precomp<const VARTIME: bool>(

/// Calculate the greatest common denominator of `f` and `g`.
pub fn gcd<const VARTIME: bool>(f: &BoxedUint, g: &BoxedUint) -> BoxedUint {
let f_is_zero = f.is_zero();
let f_is_zero = f.is_zero().into();
// Note: is non-zero by construction
let f_nz = NonZero(BoxedUint::ct_select(
f,
Expand Down Expand Up @@ -407,7 +407,7 @@ impl SignedBoxedInt {

/// Normalize the value to a `BoxedUint` in the range `[0, m)`.
fn norm(&self, f_sign: ConstChoice, m: &BoxedUint) -> BoxedUint {
let swap = Choice::from(f_sign.xor(self.sign)) & self.is_nonzero();
let swap = f_sign.xor(self.sign) & self.is_nonzero().into();
BoxedUint::ct_select(&self.magnitude, &m.wrapping_sub(&self.magnitude), swap)
}
}
Expand Down
50 changes: 2 additions & 48 deletions src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ pub use num_traits::{
WrappingSub,
};

use crate::{Limb, NonZero, Odd, Reciprocal, modular::Retrieve};
use crate::{CtSelect, Limb, NonZero, Odd, Reciprocal, modular::Retrieve};
use core::{
fmt::{self, Debug},
ops::{
Expand All @@ -31,52 +31,6 @@ pub trait Bounded {
const BYTES: usize;
}

/// Trait for types which are conditionally selectable in constant time.
///
/// Similar to (and blanket impl'd for) `subtle`'s [`ConditionallySelectable`] trait, but without
/// the `Copy` bound which allows it to be impl'd for heap allocated types such as `BoxedUint`.
///
/// It also provides generic implementations of conditional assignment and conditional swaps.
pub trait ConstantTimeSelect: Clone {
/// Select `a` or `b` according to `choice`.
///
/// # Returns
/// - `a` if `choice == Choice(0)`;
/// - `b` if `choice == Choice(1)`.
fn ct_select(a: &Self, b: &Self, choice: Choice) -> Self;

/// Conditionally assign `other` to `self`, according to `choice`.
#[inline]
fn ct_assign(&mut self, other: &Self, choice: Choice) {
*self = Self::ct_select(self, other, choice);
}

/// Conditionally swap `self` and `other` if `choice == 1`; otherwise, reassign both unto themselves.
#[inline]
fn ct_swap(a: &mut Self, b: &mut Self, choice: Choice) {
let t: Self = a.clone();
a.ct_assign(b, choice);
b.ct_assign(&t, choice);
}
}

impl<T: ConditionallySelectable> ConstantTimeSelect for T {
#[inline(always)]
fn ct_select(a: &Self, b: &Self, choice: Choice) -> Self {
T::conditional_select(a, b, choice)
}

#[inline(always)]
fn ct_assign(&mut self, other: &Self, choice: Choice) {
self.conditional_assign(other, choice)
}

#[inline(always)]
fn ct_swap(a: &mut Self, b: &mut Self, choice: Choice) {
T::conditional_swap(a, b, choice)
}
}

/// Integer trait: represents common functionality of integer types provided by this crate.
pub trait Integer:
'static
Expand Down Expand Up @@ -105,7 +59,7 @@ pub trait Integer:
+ ConstantTimeEq
+ ConstantTimeGreater
+ ConstantTimeLess
+ ConstantTimeSelect
+ CtSelect
+ Debug
+ Default
+ DivAssign<NonZero<Self>>
Expand Down
43 changes: 21 additions & 22 deletions src/uint/boxed/ct.rs
Original file line number Diff line number Diff line change
@@ -1,38 +1,37 @@
//! Constant-time helper functions.

use super::BoxedUint;
use crate::{ConstantTimeSelect, Limb};
use subtle::{Choice, ConditionallyNegatable, ConditionallySelectable};
use crate::{ConstChoice, CtSelect, Limb};
use subtle::{Choice, ConditionallyNegatable};

/// NOTE: can't impl `subtle`'s [`ConditionallySelectable`] trait due to its `Copy` bound
impl ConstantTimeSelect for BoxedUint {
impl CtSelect for BoxedUint {
#[inline]
fn ct_select(a: &Self, b: &Self, choice: Choice) -> Self {
debug_assert_eq!(a.bits_precision(), b.bits_precision());
let mut limbs = vec![Limb::ZERO; a.nlimbs()].into_boxed_slice();
fn ct_select(&self, other: &Self, choice: ConstChoice) -> Self {
debug_assert_eq!(self.bits_precision(), other.bits_precision());
let mut limbs = vec![Limb::ZERO; self.nlimbs()].into_boxed_slice();

for i in 0..a.nlimbs() {
limbs[i] = Limb::conditional_select(&a.limbs[i], &b.limbs[i], choice);
for i in 0..self.nlimbs() {
limbs[i] = self.limbs[i].ct_select(&other.limbs[i], choice);
}

Self { limbs }
}

#[inline]
fn ct_assign(&mut self, other: &Self, choice: Choice) {
fn ct_assign(&mut self, other: &Self, choice: ConstChoice) {
debug_assert_eq!(self.bits_precision(), other.bits_precision());

for i in 0..self.nlimbs() {
self.limbs[i].conditional_assign(&other.limbs[i], choice);
self.limbs[i].ct_assign(&other.limbs[i], choice);
}
}

#[inline]
fn ct_swap(a: &mut Self, b: &mut Self, choice: Choice) {
debug_assert_eq!(a.bits_precision(), b.bits_precision());
fn ct_swap(&mut self, other: &mut Self, choice: ConstChoice) {
debug_assert_eq!(self.bits_precision(), other.bits_precision());

for i in 0..a.nlimbs() {
Limb::conditional_swap(&mut a.limbs[i], &mut b.limbs[i], choice);
for i in 0..self.nlimbs() {
self.limbs[i].ct_swap(&mut other.limbs[i], choice);
}
}
}
Expand All @@ -41,33 +40,33 @@ impl ConditionallyNegatable for BoxedUint {
#[inline]
fn conditional_negate(&mut self, choice: Choice) {
let self_neg = self.wrapping_neg();
self.ct_assign(&self_neg, choice)
self.ct_assign(&self_neg, choice.into())
}
}

#[cfg(test)]
mod tests {
use crate::{BoxedUint, ConstantTimeSelect};
use subtle::{Choice, ConditionallyNegatable};
use crate::{BoxedUint, ConstChoice, CtSelect};
use subtle::ConditionallyNegatable;

#[test]
fn conditional_select() {
let a = BoxedUint::zero_with_precision(128);
let b = BoxedUint::max(128);

assert_eq!(a, BoxedUint::ct_select(&a, &b, Choice::from(0)));
assert_eq!(b, BoxedUint::ct_select(&a, &b, Choice::from(1)));
assert_eq!(a, BoxedUint::ct_select(&a, &b, ConstChoice::FALSE));
assert_eq!(b, BoxedUint::ct_select(&a, &b, ConstChoice::TRUE));
}

#[test]
fn conditional_negate() {
let mut a = BoxedUint::from(123u64);
let control = a.clone();

a.conditional_negate(Choice::from(0));
a.conditional_negate(ConstChoice::FALSE.into());
assert_eq!(a, control);

a.conditional_negate(Choice::from(1));
a.conditional_negate(ConstChoice::TRUE.into());
assert_ne!(a, control);
assert_eq!(a, control.wrapping_neg());
}
Expand Down
6 changes: 3 additions & 3 deletions src/uint/boxed/div.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
//! [`BoxedUint`] division operations.

use crate::{
BoxedUint, CheckedDiv, ConstantTimeSelect, DivRemLimb, DivVartime, Limb, NonZero, Reciprocal,
RemLimb, RemMixed, UintRef, Wrapping,
BoxedUint, CheckedDiv, CtSelect, DivRemLimb, DivVartime, Limb, NonZero, Reciprocal, RemLimb,
RemMixed, UintRef, Wrapping,
};
use core::ops::{Div, DivAssign, Rem, RemAssign};
use subtle::CtOption;
Expand Down Expand Up @@ -121,7 +121,7 @@ impl BoxedUint {
let mut quo = self.clone();
let is_nz = rhs.is_nonzero();
let mut rem = Self::one_with_precision(self.bits_precision());
rem.ct_assign(rhs, is_nz);
rem.ct_assign(rhs, is_nz.into());
quo.as_mut_uint_ref().div_rem(rem.as_mut_uint_ref());
CtOption::new(quo, is_nz)
}
Expand Down
12 changes: 6 additions & 6 deletions src/uint/boxed/invert_mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! [`BoxedUint`] modular inverse (i.e. reciprocal) operations.

use crate::{
BoxedUint, ConstantTimeSelect, Integer, InvertMod, Limb, NonZero, Odd, U64, modular::safegcd,
BoxedUint, CtSelect, Integer, InvertMod, Limb, NonZero, Odd, U64, modular::safegcd,
uint::invert_mod::expand_invert_mod2k,
};
use subtle::{Choice, ConstantTimeEq, ConstantTimeLess, CtOption};
Expand Down Expand Up @@ -50,7 +50,7 @@ impl BoxedUint {
let inv = Odd(Self::ct_select(
&Self::one_with_precision(bits),
self,
is_some,
is_some.into(),
))
.invert_mod2k_vartime(k);
(inv, is_some)
Expand All @@ -76,14 +76,14 @@ impl BoxedUint {
let mut inv = Odd(Self::ct_select(
&Self::one_with_precision(bits),
self,
is_some,
is_some.into(),
))
.invert_mod_precision();
inv.restrict_bits(k);
(inv, is_some)
}

/// Computes the multiplicaitve inverse of `self` mod `modulus`
/// Computes the multiplicative inverse of `self` mod `modulus`
///
/// `self` and `modulus` must have the same number of limbs, or the function will panic
///
Expand All @@ -94,7 +94,7 @@ impl BoxedUint {
let m = NonZero(Self::ct_select(
&Self::one_with_precision(self.bits_precision()),
modulus,
is_nz,
is_nz.into(),
));
let inv_mod_s = self.invert_mod(&m);
let is_some = inv_mod_s.is_some();
Expand All @@ -103,7 +103,7 @@ impl BoxedUint {
CtOption::new(result, is_some & is_nz)
}

/// Computes the multiplicaitve inverse of `self` mod `modulus`
/// Computes the multiplicative inverse of `self` mod `modulus`
///
/// `self` and `modulus` must have the same number of limbs, or the function will panic
///
Expand Down
6 changes: 3 additions & 3 deletions src/uint/boxed/sqrt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use subtle::{ConstantTimeEq, ConstantTimeGreater, CtOption};

use crate::{BitOps, BoxedUint, ConstantTimeSelect, Limb, SquareRoot};
use crate::{BitOps, BoxedUint, CtSelect, Limb, SquareRoot};

impl BoxedUint {
/// Computes √(`self`) in constant time.
Expand All @@ -29,7 +29,7 @@ impl BoxedUint {
// TODO (#378): the tests indicate that just `Self::LOG2_BITS` may be enough.
while i < self.log2_bits() + 2 {
let x_nonzero = x.is_nonzero();
nz_x.ct_assign(&x, x_nonzero);
nz_x.ct_assign(&x, x_nonzero.into());

// Calculate `x_{i+1} = floor((x_i + self / x_i) / 2)`
quo.limbs.copy_from_slice(&self.limbs);
Expand All @@ -44,7 +44,7 @@ impl BoxedUint {
// At this point `x_prev == x_{n}` and `x == x_{n+1}`
// where `n == i - 1 == LOG2_BITS + 1 == floor(log2(BITS)) + 1`.
// Thus, according to Hast, `sqrt(self) = min(x_n, x_{n+1})`.
x.ct_assign(&nz_x, Self::ct_gt(&x, &nz_x));
x.ct_assign(&nz_x, Self::ct_gt(&x, &nz_x).into());
x
}

Expand Down