crypto_bigint/uint/
mul_mod.rs

1//! [`UInt`] multiplication modulus operations.
2
3use crate::{Limb, UInt, WideWord, Word};
4
5impl<const LIMBS: usize> UInt<LIMBS> {
6    /// Computes `self * rhs mod p` in constant time for the special modulus
7    /// `p = MAX+1-c` where `c` is small enough to fit in a single [`Limb`].
8    /// For the modulus reduction, this function implements Algorithm 14.47 from
9    /// the "Handbook of Applied Cryptography", by A. Menezes, P. van Oorschot,
10    /// and S. Vanstone, CRC Press, 1996.
11    pub const fn mul_mod_special(&self, rhs: &Self, c: Limb) -> Self {
12        // We implicitly assume `LIMBS > 0`, because `UInt<0>` doesn't compile.
13        // Still the case `LIMBS == 1` needs special handling.
14        if LIMBS == 1 {
15            let prod = self.limbs[0].0 as WideWord * rhs.limbs[0].0 as WideWord;
16            let reduced = prod % Word::MIN.wrapping_sub(c.0) as WideWord;
17            return Self::from_word(reduced as Word);
18        }
19
20        let (lo, hi) = self.mul_wide(rhs);
21
22        // Now use Algorithm 14.47 for the reduction
23        let (lo, carry) = mac_by_limb(lo, hi, c, Limb::ZERO);
24
25        let (lo, carry) = {
26            let rhs = (carry.0 + 1) as WideWord * c.0 as WideWord;
27            lo.adc(&Self::from_wide_word(rhs), Limb::ZERO)
28        };
29
30        let (lo, _) = {
31            let rhs = carry.0.wrapping_sub(1) & c.0;
32            lo.sbb(&Self::from_word(rhs), Limb::ZERO)
33        };
34
35        lo
36    }
37}
38
39/// Computes `a + (b * c) + carry`, returning the result along with the new carry.
40const fn mac_by_limb<const LIMBS: usize>(
41    mut a: UInt<LIMBS>,
42    b: UInt<LIMBS>,
43    c: Limb,
44    mut carry: Limb,
45) -> (UInt<LIMBS>, Limb) {
46    let mut i = 0;
47
48    while i < LIMBS {
49        let (n, c) = a.limbs[i].mac(b.limbs[i], c, carry);
50        a.limbs[i] = n;
51        carry = c;
52        i += 1;
53    }
54
55    (a, carry)
56}
57
58#[cfg(all(test, feature = "rand"))]
59mod tests {
60    use crate::{Limb, NonZero, Random, RandomMod, UInt};
61    use rand_core::SeedableRng;
62
63    macro_rules! test_mul_mod_special {
64        ($size:expr, $test_name:ident) => {
65            #[test]
66            fn $test_name() {
67                let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1);
68                let moduli = [
69                    NonZero::<Limb>::random(&mut rng),
70                    NonZero::<Limb>::random(&mut rng),
71                ];
72
73                for special in &moduli {
74                    let p = &NonZero::new(UInt::ZERO.wrapping_sub(&UInt::from_word(special.0)))
75                        .unwrap();
76
77                    let minus_one = p.wrapping_sub(&UInt::ONE);
78
79                    let base_cases = [
80                        (UInt::ZERO, UInt::ZERO, UInt::ZERO),
81                        (UInt::ONE, UInt::ZERO, UInt::ZERO),
82                        (UInt::ZERO, UInt::ONE, UInt::ZERO),
83                        (UInt::ONE, UInt::ONE, UInt::ONE),
84                        (minus_one, minus_one, UInt::ONE),
85                        (minus_one, UInt::ONE, minus_one),
86                        (UInt::ONE, minus_one, minus_one),
87                    ];
88                    for (a, b, c) in &base_cases {
89                        let x = a.mul_mod_special(&b, *special.as_ref());
90                        assert_eq!(*c, x, "{} * {} mod {} = {} != {}", a, b, p, x, c);
91                    }
92
93                    for _i in 0..100 {
94                        let a = UInt::<$size>::random_mod(&mut rng, p);
95                        let b = UInt::<$size>::random_mod(&mut rng, p);
96
97                        let c = a.mul_mod_special(&b, *special.as_ref());
98                        assert!(c < **p, "not reduced: {} >= {} ", c, p);
99
100                        let expected = {
101                            let (lo, hi) = a.mul_wide(&b);
102                            let mut prod = UInt::<{ 2 * $size }>::ZERO;
103                            prod.limbs[..$size].clone_from_slice(&lo.limbs);
104                            prod.limbs[$size..].clone_from_slice(&hi.limbs);
105                            let mut modulus = UInt::ZERO;
106                            modulus.limbs[..$size].clone_from_slice(&p.as_ref().limbs);
107                            let reduced = prod.reduce(&modulus).unwrap();
108                            let mut expected = UInt::ZERO;
109                            expected.limbs[..].clone_from_slice(&reduced.limbs[..$size]);
110                            expected
111                        };
112                        assert_eq!(c, expected, "incorrect result");
113                    }
114                }
115            }
116        };
117    }
118
119    test_mul_mod_special!(1, mul_mod_special_1);
120    test_mul_mod_special!(2, mul_mod_special_2);
121    test_mul_mod_special!(3, mul_mod_special_3);
122    test_mul_mod_special!(4, mul_mod_special_4);
123    test_mul_mod_special!(5, mul_mod_special_5);
124    test_mul_mod_special!(6, mul_mod_special_6);
125    test_mul_mod_special!(7, mul_mod_special_7);
126    test_mul_mod_special!(8, mul_mod_special_8);
127    test_mul_mod_special!(9, mul_mod_special_9);
128    test_mul_mod_special!(10, mul_mod_special_10);
129    test_mul_mod_special!(11, mul_mod_special_11);
130    test_mul_mod_special!(12, mul_mod_special_12);
131}