Skip to main content

rsa/algorithms/
blinding.rs

1//! Exponent and CRT modulus blinding for RSA private operations.
2
3use super::reduction::to_monty;
4use crypto_bigint::{
5    BoxedUint, ConcatenatingMul, Odd, Resize,
6    modular::{BoxedMontyForm, BoxedMontyParams},
7};
8use rand_core::TryCryptoRng;
9use zeroize::Zeroizing;
10
11use crate::errors::{Error, Result};
12
13/// Return `exponent + b * totient` for a fresh, uniformly random 128-bit `b`.
14///
15/// This meets the minimum of 64 bits or two machine words in CFRG RSA guidance §6.4
16/// on both 32-bit and 64-bit targets. All arithmetic uses public storage precisions.
17/// <https://www.ietf.org/archive/id/draft-irtf-cfrg-rsa-guidance-10.html#section-6.4>
18pub(crate) fn blind_exponent<R: TryCryptoRng + ?Sized>(
19    rng: &mut R,
20    exponent: &BoxedUint,
21    totient: &BoxedUint,
22) -> Result<Zeroizing<BoxedUint>> {
23    let mut bytes = Zeroizing::new([0u8; 16]);
24    rng.try_fill_bytes(bytes.as_mut()).map_err(|_| Error::Rng)?;
25    let b =
26        Zeroizing::new(BoxedUint::from_le_slice(bytes.as_ref(), 128).map_err(|_| Error::Internal)?);
27
28    let bits = exponent.bits_precision().max(totient.bits_precision());
29    let totient = Zeroizing::new(totient.resize_unchecked(bits));
30    let mut blinded = Zeroizing::new(totient.concatenating_mul(&*b));
31    // Both inputs are below 2^bits, so b * totient + exponent fits in bits + 128 bits.
32    blinded.wrapping_add_assign(exponent);
33    Ok(blinded)
34}
35
36/// Multiply a CRT prime by a fresh random odd factor, using public storage widths.
37///
38/// With `r` uniform over 128 bits, `g = 2*r + 1` is positive and odd and retains all
39/// 128 bits of randomness. Odd factors permit Montgomery arithmetic without rejection sampling.
40/// <https://www.ietf.org/archive/id/draft-irtf-cfrg-rsa-guidance-10.html#section-6.5>
41pub(crate) fn blind_modulus<R: TryCryptoRng + ?Sized>(
42    rng: &mut R,
43    prime: &Odd<BoxedUint>,
44) -> Result<Odd<BoxedUint>> {
45    let mut bytes = Zeroizing::new([0u8; 16]);
46    rng.try_fill_bytes(bytes.as_mut()).map_err(|_| Error::Rng)?;
47    // Reserve the extra bit before doubling, including when every random byte is 0xff.
48    let mut g =
49        Zeroizing::new(BoxedUint::from_le_slice(bytes.as_ref(), 129).map_err(|_| Error::Internal)?);
50    g.shl_assign(1);
51    g.wrapping_add_assign(BoxedUint::one());
52    Odd::new(prime.concatenating_mul(&*g))
53        .into_option()
54        .ok_or(Error::Internal)
55}
56
57/// Exponentiate modulo a fresh multiple of `p`, then return the residue modulo `p`.
58///
59/// `exponent` may already be blinded using a multiple of `p - 1`. Reduce back to `p`
60/// before CRT recombination, whose precomputed coefficient uses the original primes.
61pub(crate) fn pow_mod_blinded<R: TryCryptoRng + ?Sized>(
62    rng: &mut R,
63    base: &BoxedUint,
64    exponent: &BoxedUint,
65    p: &BoxedMontyParams,
66) -> Result<BoxedMontyForm> {
67    let params = BoxedMontyParams::new(blind_modulus(rng, p.modulus())?);
68    let base = Zeroizing::new(to_monty(base, &params));
69    let powered = Zeroizing::new(base.pow(exponent));
70    let residue = Zeroizing::new(powered.retrieve());
71    Ok(to_monty(&residue, p))
72}
73
74/// Compute φ(n) = ∏(p_i - 1) at the public modulus precision for non-CRT operations.
75///
76/// The factors must belong to a valid RSA key; then every partial product is below n.
77pub(crate) fn totient(primes: &[Odd<BoxedUint>], bits: u32) -> Result<Zeroizing<BoxedUint>> {
78    if primes.len() < 2 {
79        return Err(Error::NprimesTooSmall);
80    }
81
82    let mut totient = Zeroizing::new(BoxedUint::one_with_precision(bits));
83    for prime in primes {
84        let pm1 = Zeroizing::new(prime.wrapping_sub(BoxedUint::one()));
85        totient = Zeroizing::new(totient.wrapping_mul(&*pm1));
86    }
87    Ok(totient)
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93    use crate::{
94        PrivateKey,
95        algorithms::rsa::rsa_decrypt_and_check,
96        traits::{PrivateKeyParts, PublicKeyParts},
97    };
98    use alloc::{collections::VecDeque, vec::Vec};
99    use rand_core::TryRng;
100
101    struct MockRng(VecDeque<Vec<u8>>);
102
103    impl TryRng for MockRng {
104        type Error = core::fmt::Error;
105
106        fn try_next_u32(&mut self) -> core::result::Result<u32, Self::Error> {
107            let mut bytes = [0; 4];
108            self.try_fill_bytes(&mut bytes)?;
109            Ok(u32::from_le_bytes(bytes))
110        }
111
112        fn try_next_u64(&mut self) -> core::result::Result<u64, Self::Error> {
113            let mut bytes = [0; 8];
114            self.try_fill_bytes(&mut bytes)?;
115            Ok(u64::from_le_bytes(bytes))
116        }
117
118        fn try_fill_bytes(&mut self, bytes: &mut [u8]) -> core::result::Result<(), Self::Error> {
119            let next = self.0.pop_front().ok_or(core::fmt::Error)?;
120            bytes.copy_from_slice(&next);
121            Ok(())
122        }
123    }
124
125    impl TryCryptoRng for MockRng {}
126
127    #[test]
128    fn exponent_blinding_arithmetic() {
129        for (exponent_bits, totient_bits) in [(64, 64), (64, 128), (128, 64)] {
130            let exponent = BoxedUint::from(17u64).resize_unchecked(exponent_bits);
131            let phi = BoxedUint::from(60u64).resize_unchecked(totient_bits);
132            let bits = exponent_bits.max(totient_bits) + 128;
133
134            let mut rng = MockRng(
135                [0u128, 1, u128::MAX]
136                    .map(|b| b.to_le_bytes().to_vec())
137                    .into(),
138            );
139
140            for expected in [
141                (&exponent).resize_unchecked(bits),
142                BoxedUint::from(77u64).resize_unchecked(bits),
143                // 17 + (2^128 - 1) * 60 = 60 * 2^128 - 43.
144                (&phi)
145                    .resize_unchecked(bits)
146                    .shl(128)
147                    .wrapping_sub(BoxedUint::from(43u64)),
148            ] {
149                let blinded = blind_exponent(&mut rng, &exponent, &phi).expect("blinded exponent");
150                assert_eq!(*blinded, expected);
151                assert_eq!(blinded.bits_precision(), bits);
152            }
153
154            assert!(rng.0.is_empty());
155        }
156
157        // Maximum values exercise the carry into the widened exponent's highest limb.
158        let max = BoxedUint::max(128);
159        let mut rng = MockRng([vec![0xff; 16]].into());
160        let blinded = blind_exponent(&mut rng, &max, &max).expect("blinded exponent");
161
162        assert_eq!(*blinded, max.resize_unchecked(256).shl(128));
163        assert_eq!(blinded.bits_precision(), 256);
164    }
165
166    #[test]
167    fn modulus_blinding_arithmetic() {
168        for bits in [64, 128, 192] {
169            let prime = Odd::new(BoxedUint::max(bits)).expect("odd modulus");
170            let blinded_bits = bits + BoxedUint::zero_with_precision(129).bits_precision();
171            let p = prime.as_ref().resize_unchecked(blinded_bits);
172            let mut rng = MockRng(
173                [0u128, 1, u128::MAX]
174                    .map(|r| r.to_le_bytes().to_vec())
175                    .into(),
176            );
177            for expected in [
178                p.clone(),
179                p.shl(1).wrapping_add(&p),
180                p.shl(129).wrapping_sub(&p),
181            ] {
182                let blinded = blind_modulus(&mut rng, &prime).expect("blinded modulus");
183                assert_eq!(blinded.as_ref(), &expected);
184                assert_eq!(blinded.bits_precision(), blinded_bits);
185            }
186            assert!(rng.0.is_empty());
187        }
188    }
189
190    #[test]
191    fn modulus_blinding_reduces_to_original_prime() {
192        // Exercise inputs both narrower and wider than the blinded modulus, and primes whose
193        // values are much smaller than their storage widths (as in unbalanced RSA keys).
194        for bits in [64, 128, 192] {
195            let p = Odd::new(BoxedUint::from(53u64).resize_unchecked(bits)).expect("prime");
196            let params = BoxedMontyParams::new(p);
197            for base_bits in [64, 512] {
198                for base in [
199                    BoxedUint::max(base_bits),
200                    BoxedUint::zero_with_precision(base_bits),
201                ] {
202                    for exponent in [0u64, 17] {
203                        let exponent = BoxedUint::from(exponent);
204                        let expected = to_monty(&base, &params).pow(&exponent).retrieve();
205                        // r=26 makes g=p=53, so this also covers a factor sharing the prime.
206                        for r in [0u128, 26, u128::MAX] {
207                            let mut rng = MockRng([r.to_le_bytes().to_vec()].into());
208                            let actual = pow_mod_blinded(&mut rng, &base, &exponent, &params)
209                                .expect("blinded exponentiation");
210                            assert_eq!(actual.retrieve(), expected);
211                            assert_eq!(actual.bits_precision(), bits);
212                        }
213                    }
214                }
215            }
216        }
217    }
218
219    #[test]
220    fn blinding_private_operations() {
221        let two_prime =
222            PrivateKey::from_p_q(61u64.into(), 53u64.into(), 17u64.into()).expect("two-prime key");
223        let multi_prime =
224            PrivateKey::from_primes(vec![61u64.into(), 53u64.into(), 47u64.into()], 17u64.into())
225                .expect("multiprime key");
226
227        for mut key in [two_prime, multi_prime] {
228            for clear_precomputed in [false, true] {
229                if clear_precomputed {
230                    key.clear_precomputed();
231                }
232
233                let crt = key.dp().is_some() && key.primes().len() == 2;
234                let bits = key.n_bits_precision();
235
236                for c in [
237                    BoxedUint::zero_with_precision(bits),
238                    BoxedUint::one_with_precision(bits),
239                    BoxedUint::from(42u64).resize_unchecked(bits),
240                    key.primes()[0].as_ref().resize_unchecked(bits), // Not coprime to n.
241                    key.primes()[1].as_ref().resize_unchecked(bits),
242                    key.n().wrapping_sub(BoxedUint::one()),
243                ] {
244                    let expected = rsa_decrypt_and_check::<MockRng>(&key, None, &c)
245                        .expect("unblinded reference");
246                    let mut requests = VecDeque::new();
247
248                    // The last case makes both blinded CRT moduli equal to n (g_p=q, g_q=p).
249                    // The random factors need not be coprime to either prime or to one another.
250                    let blindings = [(0, [0u128; 2]), (0xff, [u128::MAX; 2]), (0xa5, [26, 30])];
251                    for (factor, [rp, rq]) in blindings {
252                        let mut base = vec![0; key.size()];
253                        base[0] = 1; // Invertible base factor, without rejection sampling.
254                        requests.push_back(base);
255                        requests.push_back(vec![factor; 16]);
256                        if crt {
257                            requests.push_back(vec![factor ^ 0xff; 16]);
258                            requests.push_back(rp.to_le_bytes().to_vec());
259                            requests.push_back(rq.to_le_bytes().to_vec());
260                        }
261                    }
262                    let mut rng = MockRng(requests.clone());
263                    // Reusing a key must request fresh factors for each exponent and modulus.
264                    for _ in 0..blindings.len() {
265                        assert_eq!(
266                            rsa_decrypt_and_check(&key, Some(&mut rng), &c)
267                                .expect("blinded result"),
268                            expected,
269                        );
270                    }
271                    assert!(rng.0.is_empty());
272
273                    // Fail at each exponent and modulus blinding request after base blinding.
274                    for available in 1..=if crt { 4 } else { 1 } {
275                        let mut rng = MockRng(requests.iter().take(available).cloned().collect());
276                        assert_eq!(
277                            rsa_decrypt_and_check(&key, Some(&mut rng), &c),
278                            Err(Error::Rng),
279                        );
280                    }
281                }
282            }
283        }
284    }
285
286    #[test]
287    fn totient_requires_factors() {
288        assert_eq!(totient(&[], 128), Err(Error::NprimesTooSmall));
289        assert_eq!(
290            totient(&[Odd::new(BoxedUint::from(61u64)).expect("odd prime")], 128),
291            Err(Error::NprimesTooSmall),
292        );
293    }
294}