Skip to main content

rsa/algorithms/
reduction.rs

1//! Reduction modulo an odd, potentially secret modulus using fixed-width Montgomery arithmetic.
2
3use crypto_bigint::{
4    BoxedUint, Resize,
5    modular::{BoxedMontyForm, BoxedMontyParams},
6};
7
8/// Convert any input precision to Montgomery form. Loop counts and allocations depend only on
9/// buffer precisions, which callers must choose independently of secret values.
10pub(crate) fn to_monty(x: &BoxedUint, p: &BoxedMontyParams) -> BoxedMontyForm {
11    let bits = p.bits_precision();
12
13    if x.bits_precision() <= bits {
14        // With R = 2^bits, x < R and R² mod p < p, so REDC's input is below R*p.
15        return BoxedMontyForm::new(x.resize_unchecked(bits), p);
16    }
17
18    // Evaluate base-R digits with Horner's rule. R^2 mod p is the Montgomery representation of R,
19    // so this avoids division even when the input is wider than the secret modulus.
20    let radix = BoxedMontyForm::from_montgomery(p.as_ref().r2().clone(), p);
21    let digit = |limbs: &[crypto_bigint::Limb]| {
22        let mut value = BoxedUint::zero_with_precision(bits);
23        value.as_mut_limbs()[..limbs.len()].copy_from_slice(limbs);
24        BoxedMontyForm::new(value, p)
25    };
26
27    // Align digits at the low end; only the highest digit may be short.
28    let mut chunks = x.as_limbs().chunks(p.modulus().as_limbs().len()).rev();
29    let mut acc = digit(chunks.next().expect("nonempty integer"));
30    for chunk in chunks {
31        acc *= &radix;
32        acc += &digit(chunk);
33    }
34
35    acc
36}
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41    use alloc::vec::Vec;
42    use crypto_bigint::Odd;
43
44    #[test]
45    fn reduction_with_leading_zero_moduli_and_partial_digits() {
46        for bits in [64, 128, 192] {
47            for modulus in [
48                BoxedUint::from(1u64),
49                BoxedUint::from(3u64),
50                BoxedUint::from(u64::MAX),
51                BoxedUint::max(bits),
52            ] {
53                let modulus = Odd::new(modulus.resize_unchecked(bits)).expect("odd modulus");
54                let params = BoxedMontyParams::new(modulus.clone());
55                for input_bits in [64u32, 128, 192, 256, 320, 512] {
56                    let bytes: Vec<u8> = (0..input_bits.div_ceil(8))
57                        .map(|i| i.wrapping_mul(73).wrapping_add(19).to_le_bytes()[0])
58                        .collect();
59                    for input in [
60                        BoxedUint::zero_with_precision(input_bits),
61                        BoxedUint::one_with_precision(input_bits),
62                        BoxedUint::max(input_bits),
63                        BoxedUint::from_be_slice(&bytes, input_bits).expect("pattern"),
64                    ] {
65                        let expected = input
66                            .rem_vartime(modulus.as_nz_ref())
67                            .resize_unchecked(bits);
68                        assert_eq!(to_monty(&input, &params).retrieve(), expected);
69                    }
70                }
71            }
72        }
73    }
74}