//! Unsigned integers up to 4352 bits and arithmetic modulo an odd number //! by Montgomery multiplication: what RSA and the NIST curves' signatures //! are checked with. Checking works on public numbers only (a key, a //! signature, a hash), so nothing here takes care to run in constant time; //! it is not for secrets. use core::cmp::Ordering; /// 64-bit limbs: enough for a 4096-bit RSA key and a product's carry. pub const LIMBS: usize = 68; /// A number, its limbs least significant first. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub struct Num(pub [u64; LIMBS]); impl Num { pub const ZERO: Num = Num([0; LIMBS]); pub fn from_u64(v: u64) -> Num { let mut n = Num::ZERO; n.0[0] = v; n } /// From big-endian bytes; `None` when they do not fit. pub fn from_be_bytes(bytes: &[u8]) -> Option { let bytes = &bytes[bytes.iter().position(|&b| b != 0).unwrap_or(bytes.len())..]; if bytes.len() > LIMBS * 8 { return None; } let mut n = Num::ZERO; for (i, &b) in bytes.iter().rev().enumerate() { n.0[i / 8] |= u64::from(b) << (8 * (i % 8)); } Some(n) } /// Into `out`, big-endian, filling it from the right. pub fn to_be_bytes(&self, out: &mut [u8]) { let len = out.len(); for (i, b) in out.iter_mut().enumerate() { let at = len - 1 - i; *b = if at / 8 < LIMBS { (self.0[at / 8] >> (8 * (at % 8))) as u8 } else { 0 }; } } pub fn is_zero(&self) -> bool { self.0.iter().all(|&l| l == 0) } /// Bits up to the highest set one. pub fn bits(&self) -> usize { match self.0.iter().rposition(|&l| l != 0) { Some(i) => i * 64 + 64 - self.0[i].leading_zeros() as usize, None => 0, } } pub fn bit(&self, i: usize) -> bool { (self.0[i / 64] >> (i % 64)) & 1 == 1 } /// Limbs up to the highest non-zero one. fn len(&self) -> usize { self.0.iter().rposition(|&l| l != 0).map_or(0, |i| i + 1) } /// `self - other`, which must not be negative. pub fn sub(&self, other: &Num) -> Num { let mut out = Num::ZERO; let mut borrow = 0u64; for i in 0..LIMBS { let (d, b1) = self.0[i].overflowing_sub(other.0[i]); let (d, b2) = d.overflowing_sub(borrow); out.0[i] = d; borrow = u64::from(b1 || b2); } out } /// `self + other`, which must fit. pub fn add(&self, other: &Num) -> Num { let mut out = Num::ZERO; let mut carry = 0u64; for i in 0..LIMBS { let (s, c1) = self.0[i].overflowing_add(other.0[i]); let (s, c2) = s.overflowing_add(carry); out.0[i] = s; carry = u64::from(c1 || c2); } out } /// `self` modulo `m`, by shifting and subtracting: slow, for one-offs. pub fn rem(&self, m: &Num) -> Num { let mut r = Num::ZERO; for i in (0..self.bits()).rev() { r = r.shl1(); r.0[0] |= u64::from(self.bit(i)); if r.cmp(m) != Ordering::Less { r = r.sub(m); } } r } fn shl1(&self) -> Num { let mut out = Num::ZERO; let mut carry = 0; for i in 0..LIMBS { out.0[i] = (self.0[i] << 1) | carry; carry = self.0[i] >> 63; } out } } impl PartialOrd for Num { fn partial_cmp(&self, other: &Num) -> Option { Some(self.cmp(other)) } } impl Ord for Num { fn cmp(&self, other: &Num) -> Ordering { for i in (0..LIMBS).rev() { match self.0[i].cmp(&other.0[i]) { Ordering::Equal => {} unequal => return unequal, } } Ordering::Equal } } /// Arithmetic modulo an odd `n`, its numbers kept in Montgomery form /// (`a·R mod n`, R = 2^(64·k) for n's k limbs). #[derive(Clone)] pub struct Modulus { pub n: Num, k: usize, /// -n⁻¹ mod 2^64. n0: u64, /// R² mod n, to bring numbers into the form. r2: Num, } impl Modulus { /// `None` for an even or zero `n`. pub fn new(n: Num) -> Option { if n.0[0] & 1 == 0 { return None; } let k = n.len(); // n⁻¹ mod 2^64 by Newton's iteration, each step doubling the bits. let mut inverse = 1u64; for _ in 0..6 { inverse = inverse.wrapping_mul(2u64.wrapping_sub(n.0[0].wrapping_mul(inverse))); } // R² mod n: 1 doubled 2·64·k times, reduced each time. let mut r2 = Num::from_u64(1); for _ in 0..2 * 64 * k { r2 = r2.shl1(); if r2 >= n { r2 = r2.sub(&n); } } Some(Modulus { n, k, n0: inverse.wrapping_neg(), r2, }) } /// a·b·R⁻¹ mod n (CIOS). pub fn mul(&self, a: &Num, b: &Num) -> Num { let k = self.k; let mut t = [0u64; LIMBS + 2]; for &bi in &b.0[..k] { let mut carry = 0u128; for j in 0..k { let s = u128::from(t[j]) + u128::from(a.0[j]) * u128::from(bi) + carry; t[j] = s as u64; carry = s >> 64; } let s = u128::from(t[k]) + carry; t[k] = s as u64; t[k + 1] = (s >> 64) as u64; let m = t[0].wrapping_mul(self.n0); let s = u128::from(t[0]) + u128::from(m) * u128::from(self.n.0[0]); let mut carry = s >> 64; for j in 1..k { let s = u128::from(t[j]) + u128::from(m) * u128::from(self.n.0[j]) + carry; t[j - 1] = s as u64; carry = s >> 64; } let s = u128::from(t[k]) + carry; t[k - 1] = s as u64; t[k] = t[k + 1] + (s >> 64) as u64; } let mut out = Num::ZERO; // The carry limb too: the result is below 2n, and may pass R. out.0[..=k].copy_from_slice(&t[..=k]); if out >= self.n { out = out.sub(&self.n); } out } /// Into Montgomery form; `a` below n. pub fn to_mont(&self, a: &Num) -> Num { self.mul(a, &self.r2) } /// Out of it. pub fn from_mont(&self, a: &Num) -> Num { self.mul(a, &Num::from_u64(1)) } /// One, in Montgomery form. pub fn one(&self) -> Num { self.to_mont(&Num::from_u64(1)) } pub fn add(&self, a: &Num, b: &Num) -> Num { let s = a.add(b); if s >= self.n { s.sub(&self.n) } else { s } } pub fn sub(&self, a: &Num, b: &Num) -> Num { if a >= b { a.sub(b) } else { a.add(&self.n).sub(b) } } /// base^exponent, all in Montgomery form but the exponent. pub fn pow(&self, base: &Num, exponent: &Num) -> Num { let mut result = self.one(); for i in (0..exponent.bits()).rev() { result = self.mul(&result, &result); if exponent.bit(i) { result = self.mul(&result, base); } } result } /// a⁻¹ (Montgomery form in and out) by Fermat, for a prime n. pub fn inverse(&self, a: &Num) -> Num { self.pow(a, &self.n.sub(&Num::from_u64(2))) } }