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            let rhs = carry.wrapping_sub(Limb::ONE) & c;
53            lo.borrowing_sub_assign(rhs, Limb::ZERO);
54        }
55
56        lo
57    }
58
59    /// Computes `self * self mod p`.
60    #[must_use]
61    pub fn square_mod(&self, p: &NonZero<BoxedUint>) -> Self {
62        self.concatenating_square().rem(p)
63    }
64
65    /// Computes `self * self mod p` in variable time with respect to `p`.
66    #[must_use]
67    pub fn square_mod_vartime(&self, p: &NonZero<BoxedUint>) -> Self {
68        self.concatenating_square().rem_vartime(p)
69    }
70}
71
72impl MulMod for BoxedUint {
73    type Output = Self;
74
75    fn mul_mod(&self, rhs: &Self, p: &NonZero<Self>) -> Self {
76        self.mul_mod(rhs, p)
77    }
78}
79
80impl SquareMod for BoxedUint {
81    type Output = Self;
82
83    fn square_mod(&self, p: &NonZero<Self>) -> Self {
84        self.square_mod(p)
85    }
86}
87
88/// Computes `a + (b * c) + carry`, returning the result along with the new carry.
89fn mac_by_limb(a: &UintRef, b: &UintRef, c: Limb, carry: Limb) -> (BoxedUint, Limb) {
90    let mut res = BoxedUint::zero_with_precision(a.bits_precision());
91    let mut carry = carry;
92
93    for i in 0..a.nlimbs() {
94        (res.limbs[i], carry) = b.limbs[i].carrying_mul_add(c, a.limbs[i], carry);
95    }
96
97    (res, carry)
98}
99
100#[cfg(all(test, feature = "rand_core"))]
101mod tests {
102    use crate::{BoxedUint, ConcatenatingMul, Limb, NonZero, Random, RandomMod, Resize};
103    use rand_core::SeedableRng;
104
105    #[test]
106    fn mul_mod_special_zero_c() {
107        for size in [1, 2, 3, 4] {
108            let bits = size * Limb::BITS;
109            let zero = BoxedUint::zero_with_precision(bits);
110            let one = BoxedUint::one_with_precision(bits);
111            let max = zero.wrapping_sub(&one);
112
113            for a in [&zero, &one, &max] {
114                for b in [&zero, &one, &max] {
115                    assert_eq!(a.mul_mod_special(b, Limb::ZERO), a.wrapping_mul(b));
116                }
117            }
118        }
119    }
120
121    #[test]
122    fn mul_mod_special_max_c() {
123        for size in [3, 4] {
124            let bits = size * Limb::BITS;
125            let c = BoxedUint::from(Limb::MAX).resize(bits);
126            let p = NonZero::new(BoxedUint::zero_with_precision(bits).wrapping_sub(&c)).unwrap();
127            let a = p.wrapping_sub(&c);
128
129            // (p - c)^2 mod p = c^2. With at least three limbs, the first
130            // reduction produces a carry of Limb::MAX, so carry + 1 overflows.
131            let expected = c.wrapping_mul(&c);
132            assert_eq!(a.mul_mod_special(&a, Limb::MAX), expected);
133            assert_eq!(a.mul_mod(&a, &p), expected);
134        }
135    }
136
137    #[test]
138    fn mul_mod_special() {
139        let mut rng = chacha20::ChaCha8Rng::seed_from_u64(1);
140        let moduli = [
141            NonZero::<Limb>::random_from_rng(&mut rng),
142            NonZero::<Limb>::random_from_rng(&mut rng),
143        ];
144        let sizes = if cfg!(miri) {
145            &[1, 2, 3][..]
146        } else {
147            &[1, 2, 3, 4, 8, 16][..]
148        };
149
150        for size in sizes.iter().copied() {
151            let bits = size * Limb::BITS;
152
153            for special in &moduli {
154                let zero = BoxedUint::zero_with_precision(bits);
155                let one = BoxedUint::one_with_precision(bits);
156                let p = NonZero::new(zero.wrapping_sub(special.get())).unwrap();
157                let minus_one = p.wrapping_sub(Limb::ONE);
158
159                let base_cases = [
160                    (&zero, &zero, &zero),
161                    (&one, &zero, &zero),
162                    (&zero, &one, &zero),
163                    (&one, &one, &one),
164                    (&minus_one, &minus_one, &one),
165                    (&minus_one, &one, &minus_one),
166                    (&one, &minus_one, &minus_one),
167                ];
168                for (a, b, c) in base_cases {
169                    let x = a.mul_mod_special(b, *special.as_ref());
170                    assert_eq!(&x, c, "{} * {} mod {} = {} != {}", a, b, p, x, c);
171                }
172
173                for _i in 0..100 {
174                    let a = BoxedUint::random_mod_vartime(&mut rng, &p);
175                    let b = BoxedUint::random_mod_vartime(&mut rng, &p);
176
177                    let c = a.mul_mod_special(&b, *special.as_ref());
178                    assert!(c < p.as_ref(), "not reduced: {} >= {} ", c, p);
179
180                    let expected = {
181                        let prod = a.concatenating_mul(&b);
182                        prod.rem_vartime(&p)
183                    };
184                    assert_eq!(c, expected, "incorrect result");
185                }
186            }
187        }
188    }
189}