rsa/algorithms/
reduction.rs1use crypto_bigint::{
4 BoxedUint, Resize,
5 modular::{BoxedMontyForm, BoxedMontyParams},
6};
7
8pub(crate) fn to_monty(x: &BoxedUint, p: &BoxedMontyParams) -> BoxedMontyForm {
11 let bits = p.bits_precision();
12
13 if x.bits_precision() <= bits {
14 return BoxedMontyForm::new(x.resize_unchecked(bits), p);
16 }
17
18 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 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, ¶ms).retrieve(), expected);
69 }
70 }
71 }
72 }
73 }
74}