Skip to main content

crypto_bigint/uint/
mul_mod.rs

1//! [`Uint`] modular multiplication operations.
2
3use crate::{Limb, MulMod, NonZero, SquareMod, Uint, WideWord, div_limb::mul_rem};
4
5impl<const LIMBS: usize> Uint<LIMBS> {
6    /// Computes `self * rhs mod p`.
7    #[must_use]
8    pub fn mul_mod(&self, rhs: &Uint<LIMBS>, p: &NonZero<Uint<LIMBS>>) -> Uint<LIMBS> {
9        let lo_hi = self.widening_mul(rhs);
10        Self::rem_wide(lo_hi, p)
11    }
12
13    /// Computes `self * rhs mod p` in variable time with respect to `p`.
14    #[must_use]
15    pub fn mul_mod_vartime(&self, rhs: &Uint<LIMBS>, p: &NonZero<Uint<LIMBS>>) -> Uint<LIMBS> {
16        let lo_hi = self.widening_mul(rhs);
17        Self::rem_wide_vartime(lo_hi, p)
18    }
19
20    /// Computes `self * rhs mod p` for the special modulus
21    /// `p = MAX+1-c` where `c` is small enough to fit in a single [`Limb`].
22    ///
23    /// When `c` is zero, `p = MAX+1` and the result is wrapping multiplication.
24    ///
25    /// For the modulus reduction, this function implements Algorithm 14.47 from
26    /// the "Handbook of Applied Cryptography", by A. Menezes, P. van Oorschot,
27    /// and S. Vanstone, CRC Press, 1996.
28    #[cfg_attr(target_arch = "arm", inline)]
29    #[must_use]
30    pub const fn mul_mod_special(&self, rhs: &Self, c: Limb) -> Self {
31        // We implicitly assume `LIMBS > 0`, because `Uint<0>` doesn't compile.
32        // Still the case `LIMBS == 1` needs special handling.
33        if LIMBS == 1 {
34            let a = self.limbs[0];
35            let b = rhs.limbs[0];
36
37            // For c = 0, use a nonzero placeholder divisor and select the
38            // wrapping product in constant time.
39            let (p, c_is_nonzero) = Limb::ZERO.wrapping_sub(c).to_nz_or_one();
40            let reduced = mul_rem(a, b, p);
41            let reduced = Limb::select(a.wrapping_mul(b), reduced, c_is_nonzero);
42            return Self::from_word(reduced.0);
43        }
44
45        let (lo, hi) = self.widening_mul(rhs);
46
47        // Now use Algorithm 14.47 for the reduction
48        let (lo, carry) = mac_by_limb(&lo, &hi, c, Limb::ZERO);
49
50        let (lo, carry) = {
51            // Widen before adding: carry can equal Limb::MAX.
52            let rhs = (carry.0 as WideWord + 1) * c.0 as WideWord;
53            lo.carrying_add(&Self::from_wide_word(rhs), Limb::ZERO)
54        };
55
56        let (lo, _) = {
57            // LLVM can turn the carry mask into a secret-dependent branch on Thumb.
58            // Use a hardened selection on 32-bit ARM.
59            #[cfg(target_arch = "arm")]
60            let rhs = Limb::select(c, Limb::ZERO, carry.is_nonzero()).0;
61            #[cfg(not(target_arch = "arm"))]
62            let rhs = carry.0.wrapping_sub(1) & c.0;
63            lo.borrowing_sub(&Self::from_word(rhs), Limb::ZERO)
64        };
65
66        lo
67    }
68
69    /// Computes `self * self mod p`.
70    #[must_use]
71    pub const fn square_mod(&self, p: &NonZero<Uint<LIMBS>>) -> Self {
72        let lo_hi = self.widening_square();
73        Self::rem_wide(lo_hi, p)
74    }
75
76    /// Computes `self * self mod p` in variable time with respect to `p`.
77    #[must_use]
78    pub const fn square_mod_vartime(&self, p: &NonZero<Uint<LIMBS>>) -> Self {
79        let lo_hi = self.widening_square();
80        Self::rem_wide_vartime(lo_hi, p)
81    }
82}
83
84impl<const LIMBS: usize> MulMod for Uint<LIMBS> {
85    type Output = Self;
86
87    fn mul_mod(&self, rhs: &Self, p: &NonZero<Self>) -> Self {
88        self.mul_mod(rhs, p)
89    }
90}
91
92impl<const LIMBS: usize> SquareMod for Uint<LIMBS> {
93    type Output = Self;
94
95    fn square_mod(&self, p: &NonZero<Self>) -> Self {
96        self.square_mod(p)
97    }
98}
99
100/// Computes `a + (b * c) + carry`, returning the result along with the new carry.
101const fn mac_by_limb<const LIMBS: usize>(
102    a: &Uint<LIMBS>,
103    b: &Uint<LIMBS>,
104    c: Limb,
105    carry: Limb,
106) -> (Uint<LIMBS>, Limb) {
107    let mut i = 0;
108    let mut a = *a;
109    let mut carry = carry;
110
111    while i < LIMBS {
112        (a.limbs[i], carry) = b.limbs[i].carrying_mul_add(c, a.limbs[i], carry);
113        i += 1;
114    }
115
116    (a, carry)
117}
118
119#[cfg(all(test, feature = "rand_core"))]
120mod tests {
121    use crate::{Limb, NonZero, Random, RandomMod, Uint};
122    use rand_core::SeedableRng;
123
124    #[test]
125    fn mul_mod_special_zero_c() {
126        fn test_size<const LIMBS: usize>() {
127            let values = [Uint::<LIMBS>::ZERO, Uint::ONE, Uint::MAX];
128            for a in values {
129                for b in values {
130                    assert_eq!(a.mul_mod_special(&b, Limb::ZERO), a.wrapping_mul(&b));
131                }
132            }
133        }
134
135        test_size::<1>();
136        test_size::<2>();
137        test_size::<3>();
138        test_size::<4>();
139    }
140
141    #[test]
142    fn mul_mod_special_max_c() {
143        fn test_size<const LIMBS: usize>() {
144            let c = Uint::<LIMBS>::from(Limb::MAX);
145            let p = NonZero::new(Uint::ZERO.wrapping_sub(&c)).unwrap();
146            let a = p.wrapping_sub(&c);
147
148            // (p - c)^2 mod p = c^2. With at least three limbs, the first
149            // reduction produces a carry of Limb::MAX, so carry + 1 overflows.
150            let expected = c.wrapping_mul(&c);
151            assert_eq!(a.mul_mod_special(&a, Limb::MAX), expected);
152            assert_eq!(a.mul_mod(&a, &p), expected);
153        }
154
155        test_size::<3>();
156        test_size::<4>();
157    }
158
159    #[test]
160    fn mul_mod_special() {
161        fn test_size<const LIMBS: usize>() {
162            let mut rng = chacha20::ChaCha8Rng::seed_from_u64(1);
163            let moduli = [
164                NonZero::<Limb>::random_from_rng(&mut rng),
165                NonZero::<Limb>::random_from_rng(&mut rng),
166            ];
167
168            for special in &moduli {
169                let p = &NonZero::new(Uint::ZERO.wrapping_sub(&Uint::from(special.get()))).unwrap();
170
171                let minus_one = p.wrapping_sub(&Uint::ONE);
172
173                let base_cases = [
174                    (Uint::ZERO, Uint::ZERO, Uint::ZERO),
175                    (Uint::ONE, Uint::ZERO, Uint::ZERO),
176                    (Uint::ZERO, Uint::ONE, Uint::ZERO),
177                    (Uint::ONE, Uint::ONE, Uint::ONE),
178                    (minus_one, minus_one, Uint::ONE),
179                    (minus_one, Uint::ONE, minus_one),
180                    (Uint::ONE, minus_one, minus_one),
181                ];
182                for (a, b, c) in &base_cases {
183                    let x = a.mul_mod_special(b, *special.as_ref());
184                    assert_eq!(*c, x, "{} * {} mod {} = {} != {}", a, b, p, x, c);
185                }
186
187                let rounds = if cfg!(miri) { 10 } else { 100 };
188                for _i in 0..rounds {
189                    let a = Uint::<LIMBS>::random_mod_vartime(&mut rng, p);
190                    let b = Uint::<LIMBS>::random_mod_vartime(&mut rng, p);
191
192                    let c = a.mul_mod_special(&b, *special.as_ref());
193                    assert!(c < **p, "not reduced: {} >= {} ", c, p);
194
195                    let expected = {
196                        let prod = a.widening_mul(&b);
197                        Uint::rem_wide_vartime(prod, p)
198                    };
199                    assert_eq!(c, expected, "incorrect result");
200                }
201            }
202        }
203
204        test_size::<1>();
205        test_size::<2>();
206        test_size::<3>();
207        if cfg!(not(miri)) {
208            test_size::<4>();
209            test_size::<8>();
210            test_size::<16>();
211        }
212    }
213}