Skip to main content

crypto_bigint/uint/boxed/
mul_mod.rs

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