Skip to main content

crypto_bigint/uint/
mul_mod.rs

1//! [`Uint`] modular multiplication operations.
2
3use crate::{Limb, MulMod, NonZero, SquareMod, Uint, WideWord, Word, 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    /// For the modulus reduction, this function implements Algorithm 14.47 from
24    /// the "Handbook of Applied Cryptography", by A. Menezes, P. van Oorschot,
25    /// and S. Vanstone, CRC Press, 1996.
26    #[must_use]
27    pub const fn mul_mod_special(&self, rhs: &Self, c: Limb) -> Self {
28        // We implicitly assume `LIMBS > 0`, because `Uint<0>` doesn't compile.
29        // Still the case `LIMBS == 1` needs special handling.
30        if LIMBS == 1 {
31            let reduced = mul_rem(
32                self.limbs[0],
33                rhs.limbs[0],
34                NonZero::<Limb>::new_unwrap(Limb(Word::MIN.wrapping_sub(c.0))),
35            );
36            return Self::from_word(reduced.0);
37        }
38
39        let (lo, hi) = self.widening_mul(rhs);
40
41        // Now use Algorithm 14.47 for the reduction
42        let (lo, carry) = mac_by_limb(&lo, &hi, c, Limb::ZERO);
43
44        let (lo, carry) = {
45            let rhs = (carry.0 + 1) as WideWord * c.0 as WideWord;
46            lo.carrying_add(&Self::from_wide_word(rhs), Limb::ZERO)
47        };
48
49        let (lo, _) = {
50            let rhs = carry.0.wrapping_sub(1) & c.0;
51            lo.borrowing_sub(&Self::from_word(rhs), Limb::ZERO)
52        };
53
54        lo
55    }
56
57    /// Computes `self * self mod p`.
58    #[must_use]
59    pub const fn square_mod(&self, p: &NonZero<Uint<LIMBS>>) -> Self {
60        let lo_hi = self.widening_square();
61        Self::rem_wide(lo_hi, p)
62    }
63
64    /// Computes `self * self mod p` in variable time with respect to `p`.
65    #[must_use]
66    pub const fn square_mod_vartime(&self, p: &NonZero<Uint<LIMBS>>) -> Self {
67        let lo_hi = self.widening_square();
68        Self::rem_wide_vartime(lo_hi, p)
69    }
70}
71
72impl<const LIMBS: usize> MulMod for Uint<LIMBS> {
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<const LIMBS: usize> SquareMod for Uint<LIMBS> {
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.
89const fn mac_by_limb<const LIMBS: usize>(
90    a: &Uint<LIMBS>,
91    b: &Uint<LIMBS>,
92    c: Limb,
93    carry: Limb,
94) -> (Uint<LIMBS>, Limb) {
95    let mut i = 0;
96    let mut a = *a;
97    let mut carry = carry;
98
99    while i < LIMBS {
100        (a.limbs[i], carry) = b.limbs[i].carrying_mul_add(c, a.limbs[i], carry);
101        i += 1;
102    }
103
104    (a, carry)
105}
106
107#[cfg(all(test, feature = "rand_core"))]
108mod tests {
109    use crate::{Limb, NonZero, Random, RandomMod, Uint};
110    use rand_core::SeedableRng;
111
112    #[test]
113    fn mul_mod_special() {
114        fn test_size<const LIMBS: usize>() {
115            let mut rng = chacha20::ChaCha8Rng::seed_from_u64(1);
116            let moduli = [
117                NonZero::<Limb>::random_from_rng(&mut rng),
118                NonZero::<Limb>::random_from_rng(&mut rng),
119            ];
120
121            for special in &moduli {
122                let p = &NonZero::new(Uint::ZERO.wrapping_sub(&Uint::from(special.get()))).unwrap();
123
124                let minus_one = p.wrapping_sub(&Uint::ONE);
125
126                let base_cases = [
127                    (Uint::ZERO, Uint::ZERO, Uint::ZERO),
128                    (Uint::ONE, Uint::ZERO, Uint::ZERO),
129                    (Uint::ZERO, Uint::ONE, Uint::ZERO),
130                    (Uint::ONE, Uint::ONE, Uint::ONE),
131                    (minus_one, minus_one, Uint::ONE),
132                    (minus_one, Uint::ONE, minus_one),
133                    (Uint::ONE, minus_one, minus_one),
134                ];
135                for (a, b, c) in &base_cases {
136                    let x = a.mul_mod_special(b, *special.as_ref());
137                    assert_eq!(*c, x, "{} * {} mod {} = {} != {}", a, b, p, x, c);
138                }
139
140                let rounds = if cfg!(miri) { 10 } else { 100 };
141                for _i in 0..rounds {
142                    let a = Uint::<LIMBS>::random_mod_vartime(&mut rng, p);
143                    let b = Uint::<LIMBS>::random_mod_vartime(&mut rng, p);
144
145                    let c = a.mul_mod_special(&b, *special.as_ref());
146                    assert!(c < **p, "not reduced: {} >= {} ", c, p);
147
148                    let expected = {
149                        let prod = a.widening_mul(&b);
150                        Uint::rem_wide_vartime(prod, p)
151                    };
152                    assert_eq!(c, expected, "incorrect result");
153                }
154            }
155        }
156
157        test_size::<1>();
158        test_size::<2>();
159        test_size::<3>();
160        if cfg!(not(miri)) {
161            test_size::<4>();
162            test_size::<8>();
163            test_size::<16>();
164        }
165    }
166}