Skip to main content

rsa/algorithms/
rsa.rs

1//! Shared integer arithmetic for RSAEP/RSAVP1 and RSADP/RSASP1 (RFC8017 §5).
2//!
3//! These functions do not implement octet-string conversion or scheme encoding. In particular,
4//! `rsa_encrypt` performs modular exponentiation without checking the representative's range;
5//! callers implementing RSAEP or RSAVP1 must establish that the input is less than `n`.
6
7pub(crate) use super::reduction::to_monty;
8
9use super::blinding::{blind_exponent, pow_mod_blinded, totient};
10use crypto_bigint::{
11    BoxedUint, ConcatenatingMul, ConcatenatingSquare, Gcd, NonZero, Odd, RandomMod, Resize,
12    modular::BoxedMontyParams,
13};
14use rand_core::TryCryptoRng;
15use zeroize::{Zeroize, Zeroizing};
16
17use crate::errors::{Error, Result};
18use crate::traits::keys::{PrivateKeyParts, PublicKeyParts};
19
20/// ⚠️ Raw RSA public-key operation on the integer representative `m`, without padding.
21///
22/// Computes the exponentiation shared by RSAEP (RFC8017 §5.1.1) and RSAVP1 (§5.2.2).
23/// The caller must check that the representative is less than `n` to implement either primitive;
24/// this function reduces out-of-range inputs modulo `n`.
25///
26/// <div class="warning">
27/// <b> ☢️️ WARNING: HAZARDOUS API ☢️</b>
28///
29/// Use this function with great care! Raw RSA should never be used without an appropriate padding
30/// or signature scheme. See the [module-level documentation][crate::hazmat] for more information.
31/// </div>
32#[inline]
33#[allow(clippy::missing_errors_doc, reason = "TODO")]
34pub fn rsa_encrypt<K: PublicKeyParts>(key: &K, m: &BoxedUint) -> Result<BoxedUint> {
35    let e = key.e();
36    let res = pow_mod_params_vartime_exp_bits(m, e, e.bit_width(), key.n_params());
37    Ok(res)
38}
39
40/// ⚠️ Performs the raw RSA private-key operation without padding or a CRT fault check.
41///
42/// Implements the integer arithmetic shared by RSADP (RFC8017 §5.1.2) and RSASP1 (§5.2.1).
43/// Checks that `c < n` and that `c` has the modulus's storage precision.
44///
45/// Returns a plaintext `BoxedUint`. Performs base, exponent, and CRT modulus blinding if an `Rng`
46/// is passed, using fresh factors for each private operation.
47/// Blinded non-CRT operations require the prime factors in [`PrivateKeyParts::primes`].
48///
49/// <div class="warning">
50/// <b> ☢️️ WARNING: HAZARDOUS API ☢️</b>
51///
52/// Use this function with great care! Raw RSA should never be used without an appropriate padding
53/// or signature scheme. See the [module-level documentation][crate::hazmat] for more information.
54/// </div>
55#[inline]
56#[allow(clippy::missing_errors_doc, reason = "TODO")]
57pub fn rsa_decrypt<R: TryCryptoRng + ?Sized>(
58    mut rng: Option<&mut R>,
59    priv_key: &impl PrivateKeyParts,
60    c: &BoxedUint,
61) -> Result<BoxedUint> {
62    let n = priv_key.n();
63    let d = priv_key.d();
64
65    if c.bits_precision() != n.as_ref().bits_precision() {
66        return Err(Error::Decryption);
67    }
68
69    if c >= n.as_ref() {
70        return Err(Error::Decryption);
71    }
72
73    let mut ir = None;
74
75    let n_params = priv_key.n_params();
76    let c = if let Some(rng) = rng.as_deref_mut() {
77        let (blinded, unblinder) = blind(rng, priv_key, c, n_params)?;
78        ir = Some(unblinder);
79        blinded
80    } else {
81        c.clone()
82    };
83
84    let is_multiprime = priv_key.primes().len() > 2;
85
86    let m = match (
87        priv_key.dp(),
88        priv_key.dq(),
89        priv_key.qinv(),
90        priv_key.p(),
91        priv_key.q(),
92    ) {
93        (Some(dp), Some(dq), Some(qinv), Some(p), Some(q)) if !is_multiprime => {
94            // We have the precalculated values needed for the CRT.
95            // precomputed: dP = (1/e) mod (p-1) = d mod (p-1)
96            // precomputed: dQ = (1/e) mod (q-1) = d mod (q-1)
97
98            // TODO(tarcieri): zeroize intermediates
99            let p_params = BoxedMontyParams::from(p.clone());
100            let q_params = BoxedMontyParams::from(q.clone());
101
102            let blinded_exponents = if let Some(rng) = rng.as_deref_mut() {
103                let pm1 = Zeroizing::new(p.modulus().wrapping_sub(BoxedUint::one()));
104                let qm1 = Zeroizing::new(q.modulus().wrapping_sub(BoxedUint::one()));
105                Some((
106                    blind_exponent(rng, dp, &pm1)?,
107                    blind_exponent(rng, dq, &qm1)?,
108                ))
109            } else {
110                None
111            };
112
113            let (dp, dq) = blinded_exponents
114                .as_ref()
115                .map_or((dp, dq), |(dp, dq)| (&**dp, &**dq));
116
117            // Exponentiate modulo independently blinded primes, then reduce both residues back
118            // to the original primes before using the precomputed qInv for CRT recombination.
119            let (mut m1, m2) = if let Some(rng) = rng {
120                (
121                    pow_mod_blinded(rng, &c, dp, &p_params)?,
122                    pow_mod_blinded(rng, &c, dq, &q_params)?.retrieve(),
123                )
124            } else {
125                (
126                    to_monty(&c, &p_params).pow(dp),
127                    to_monty(&c, &q_params).pow(dq).retrieve(),
128                )
129            };
130
131            // (m1 - m2) mod p, also supporting custom keys with unequal public widths.
132            let m2r = to_monty(&m2, &p_params);
133            m1 -= &m2r;
134
135            // precomputed: qInv = (1/q) mod p
136
137            // h = qInv.(m1 - m2) mod p
138            let h = (qinv * m1).retrieve();
139
140            // m = m2 + h.q
141            // With m2 < q and h < p, m < n even when the exponentiations used blinded moduli.
142            let m2 = m2.try_resize(n.bits_precision()).ok_or(Error::Internal)?;
143            let hq = h
144                .concatenating_mul(priv_key.primes()[1].as_ref())
145                .try_resize(n.bits_precision())
146                .ok_or(Error::Internal)?;
147            m2.wrapping_add(&hq)
148        }
149        _ => {
150            // c^d (mod n)
151            let blinded_d = if let Some(rng) = rng {
152                let phi = totient(priv_key.primes(), n.bits_precision())?;
153                Some(blind_exponent(rng, d, &phi)?)
154            } else {
155                None
156            };
157
158            pow_mod_params(&c, blinded_d.as_deref().unwrap_or(d), n_params)
159        }
160    };
161
162    match ir {
163        Some(ref ir) => {
164            // unblind
165            let res = unblind(&m, ir, n_params);
166            Ok(res)
167        }
168        None => Ok(m),
169    }
170}
171
172/// ⚠️ Performs raw RSA decryption with no padding.
173///
174/// Returns a plaintext `BoxedUint`. Performs base, exponent, and CRT modulus blinding if an `Rng`
175/// is passed, using fresh factors for each private operation.
176/// Blinded non-CRT operations require the prime factors in [`PrivateKeyParts::primes`].
177///
178/// `c` must have the same `bits_precision` as the RSA key modulus.
179///
180/// <div class="warning">
181/// <b> ☢️️ WARNING: HAZARDOUS API ☢️</b>
182///
183/// Use this function with great care! Raw RSA should never be used without an appropriate padding
184/// or signature scheme. See the [module-level documentation][crate::hazmat] for more information.
185/// </div>
186#[inline]
187#[allow(clippy::missing_errors_doc, reason = "TODO")]
188pub fn rsa_decrypt_and_check<R: TryCryptoRng + ?Sized>(
189    priv_key: &impl PrivateKeyParts,
190    rng: Option<&mut R>,
191    c: &BoxedUint,
192) -> Result<BoxedUint> {
193    let m = rsa_decrypt(rng, priv_key, c)?;
194
195    // In order to defend against errors in the CRT computation, m^e is
196    // calculated, which should match the original ciphertext.
197    let check = rsa_encrypt(priv_key, &m)?;
198
199    if c != &check {
200        return Err(Error::Internal);
201    }
202
203    Ok(m)
204}
205
206/// Returns the blinded c, along with the unblinding factor.
207fn blind<R: TryCryptoRng + ?Sized, K: PublicKeyParts>(
208    rng: &mut R,
209    key: &K,
210    c: &BoxedUint,
211    n_params: &BoxedMontyParams,
212) -> Result<(BoxedUint, BoxedUint)> {
213    // Blinding involves multiplying c by r^e.
214    // Then the decryption operation performs (m^e * r^e)^d mod n
215    // which equals mr mod n. The factor of r can then be removed
216    // by multiplying by the multiplicative inverse of r.
217    debug_assert_eq!(&key.n().clone().get(), n_params.modulus());
218    let bits = key.n_bits_precision();
219
220    let mut r: BoxedUint = BoxedUint::zero_with_precision(bits);
221    let mut ir: Option<BoxedUint> = None;
222    while ir.is_none() {
223        r = BoxedUint::try_random_mod_vartime(rng, key.n()).map_err(|_| Error::Rng)?;
224
225        // r^-1 (mod n)
226        ir = r.invert_mod(key.n()).into();
227    }
228
229    let blinded = {
230        // r^e (mod n)
231        let e = key.e();
232        let mut rpowe = pow_mod_params_vartime_exp_bits(&r, e, e.bit_width(), n_params);
233        // c * r^e (mod n)
234        let c = c.mul_mod(&rpowe, n_params.modulus().as_nz_ref());
235        rpowe.zeroize();
236
237        c
238    };
239
240    let ir = ir.expect("loop exited");
241    debug_assert_eq!(blinded.bits_precision(), bits);
242    debug_assert_eq!(ir.bits_precision(), bits);
243
244    Ok((blinded, ir))
245}
246
247/// Given an m and unblinding factor, unblind the m.
248fn unblind(m: &BoxedUint, unblinder: &BoxedUint, n_params: &BoxedMontyParams) -> BoxedUint {
249    // m * r^-1 (mod n)
250    debug_assert_eq!(
251        m.bits_precision(),
252        unblinder.bits_precision(),
253        "invalid unblinder"
254    );
255
256    debug_assert_eq!(
257        m.bits_precision(),
258        n_params.bits_precision(),
259        "invalid n_params"
260    );
261
262    m.mul_mod(unblinder, n_params.modulus().as_nz_ref())
263}
264
265/// Computes `base.pow_mod(exp, n)` with precomputed `n_params`.
266///
267/// Constant-time with respect to `base` and `exp`
268fn pow_mod_params(base: &BoxedUint, exp: &BoxedUint, n_params: &BoxedMontyParams) -> BoxedUint {
269    to_monty(base, n_params).pow(exp).retrieve()
270}
271
272/// Computes `base.pow_mod(exp, n)` with a bounded exponent and precomputed `n_params`.
273///
274/// Constant-time with respect to `base`. The exponent bit length `exp_bits` may be leaked in the
275/// time pattern
276fn pow_mod_params_vartime_exp_bits(
277    base: &BoxedUint,
278    exp: &BoxedUint,
279    exp_bits: u32,
280    n_params: &BoxedMontyParams,
281) -> BoxedUint {
282    to_monty(base, n_params)
283        .pow_bounded_exp(exp, exp_bits)
284        .retrieve()
285}
286
287/// The following (deterministic) algorithm also recovers the prime factors `p` and `q` of a modulus `n`, given the
288/// public exponent `e` and private exponent `d` using the method described in
289/// [NIST 800-56B Appendix C.2](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Br2.pdf).
290pub fn recover_primes(
291    n: &NonZero<BoxedUint>,
292    e: &BoxedUint,
293    d: &BoxedUint,
294) -> Result<(BoxedUint, BoxedUint)> {
295    // Check precondition
296
297    // Note: because e is at most u64::MAX, it is already
298    // known to be < 2**256
299    if e <= &BoxedUint::from(2u64.pow(16)) {
300        return Err(Error::InvalidArguments);
301    }
302
303    // 1. Let a = (de – 1) × GCD(n – 1, de – 1).
304    let bits = d.bits_precision() * 2;
305    let one = BoxedUint::one_with_precision(bits);
306    let e = e.resize_unchecked(d.bits_precision());
307    let d = d.resize_unchecked(d.bits_precision());
308    let n = n.resize_unchecked(bits);
309
310    let a1 = d.concatenating_mul(&e) - &one;
311    let a2 = (n.as_ref() - &one).gcd(&a1);
312    let a = a1.concatenating_mul(&a2);
313    let n = n.resize_unchecked(a.bits_precision());
314
315    // 2. Let m = floor(a /n) and r = a – m n, so that a = m n + r and 0 ≤ r < n.
316    let m = &a / &n;
317    let r = a - m.concatenating_mul(&*n);
318    let n = n.get();
319
320    // 3. Let b = ( (n – r)/(m + 1) ) + 1; if b is not an integer or b^2 ≤ 4n, then output an error indicator,
321    //    and exit without further processing.
322    let modulus_check = (&n - &r) % NonZero::new(&m + &one).expect("adding 1");
323    if (!modulus_check.is_zero()).into() {
324        return Err(Error::InvalidArguments);
325    }
326    let b = ((&n - &r) / NonZero::new(&m + &one).expect("adding one")) + one;
327
328    let four = BoxedUint::from(4u32);
329    let four_n = n.concatenating_mul(&four);
330    let b_squared = b.concatenating_square();
331
332    if b_squared <= four_n {
333        return Err(Error::InvalidArguments);
334    }
335    let b_squared_minus_four_n = b_squared - four_n;
336
337    // 4. Let ϒ be the positive square root of b^2 – 4n; if ϒ is not an integer,
338    //    then output an error indicator, and exit without further processing.
339    let y = b_squared_minus_four_n.floor_sqrt();
340
341    let y_squared = y.concatenating_square();
342    let sqrt_is_whole_number = y_squared == b_squared_minus_four_n;
343    if !sqrt_is_whole_number {
344        return Err(Error::InvalidArguments);
345    }
346
347    let bits = core::cmp::max(b.bits_precision(), y.bits_precision());
348    let two = NonZero::new(BoxedUint::from(2u64))
349        .expect("2 is non zero")
350        .resize_unchecked(bits);
351    let p = (&b + &y) / &two;
352    let q = (b - y) / two;
353
354    Ok((p, q))
355}
356
357/// Compute the modulus of a key from its primes.
358pub(crate) fn compute_modulus(primes: &[BoxedUint]) -> Odd<BoxedUint> {
359    let mut primes = primes.iter();
360    let mut out = primes.next().expect("must at least be one prime").clone();
361    for p in primes {
362        out = out.concatenating_mul(&p);
363    }
364    Odd::new(out).expect("modulus must be odd")
365}
366
367/// Compute the private exponent from its primes (p and q) and public exponent
368/// This uses Euler's totient function
369#[inline]
370pub(crate) fn compute_private_exponent_euler_totient(
371    primes: &[BoxedUint],
372    exp: &BoxedUint,
373) -> Result<BoxedUint> {
374    if primes.len() < 2 {
375        return Err(Error::InvalidPrime);
376    }
377    let bits = primes[0].bits_precision();
378    let mut totient = BoxedUint::one_with_precision(bits);
379
380    for prime in primes {
381        totient = totient.concatenating_mul(&(prime - &BoxedUint::one()));
382    }
383    let exp = exp.resize_unchecked(totient.bits_precision());
384
385    // NOTE: `mod_inverse` checks if `exp` evenly divides `totient` and returns `None` if so.
386    // This ensures that `exp` is not a factor of any `(prime - 1)`.
387    let totient = NonZero::new(totient).expect("known");
388    match exp.invert_mod(&totient).into_option() {
389        Some(res) => Ok(res),
390        None => Err(Error::InvalidPrime),
391    }
392}
393
394/// Compute the private exponent from its primes (p and q) and public exponent
395///
396/// This is using the method defined by
397/// [NIST 800-56B Section 6.2.1](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Br2.pdf#page=47).
398/// (Carmichael function)
399///
400/// FIPS 186-4 **requires** the private exponent to be less than λ(n), which would
401/// make Euler's totiem unreliable.
402#[inline]
403pub(crate) fn compute_private_exponent_carmicheal(
404    p: &BoxedUint,
405    q: &BoxedUint,
406    exp: &BoxedUint,
407) -> Result<BoxedUint> {
408    let one = BoxedUint::one();
409    let p1 = p - &one;
410    let q1 = q - &one;
411
412    // LCM inlined
413    let gcd = p1.gcd(&q1);
414    let lcm = (p1 / NonZero::new(gcd).expect("gcd is non zero")).concatenating_mul(&q1);
415    let exp = exp.resize_unchecked(lcm.bits_precision());
416    if let Some(d) = exp.invert_mod(&NonZero::new(lcm).expect("non zero")).into() {
417        Ok(d)
418    } else {
419        // `exp` evenly divides `lcm`
420        Err(Error::InvalidPrime)
421    }
422}
423
424#[cfg(test)]
425mod tests {
426    use super::*;
427    use core::mem;
428
429    #[test]
430    fn recover_primes_works() {
431        let bits = 2048;
432
433        let n = BoxedUint::from_be_hex(
434            concat!(
435                "d397b84d98a4c26138ed1b695a8106ead91d553bf06041b62d3fdc50a041e222",
436                "b8f4529689c1b82c5e71554f5dd69fa2f4b6158cf0dbeb57811a0fc327e1f28e",
437                "74fe74d3bc166c1eabdc1b8b57b934ca8be5b00b4f29975bcc99acaf415b59bb",
438                "28a6782bb41a2c3c2976b3c18dbadef62f00c6bb226640095096c0cc60d22fe7",
439                "ef987d75c6a81b10d96bf292028af110dc7cc1bbc43d22adab379a0cd5d8078c",
440                "c780ff5cd6209dea34c922cf784f7717e428d75b5aec8ff30e5f0141510766e2",
441                "e0ab8d473c84e8710b2b98227c3db095337ad3452f19e2b9bfbccdd8148abf67",
442                "76fa552775e6e75956e45229ae5a9c46949bab1e622f0e48f56524a84ed3483b"
443            ),
444            bits,
445        )
446        .unwrap();
447        let e = BoxedUint::from(65_537u64);
448        let d = BoxedUint::from_be_hex(
449            concat!(
450                "c4e70c689162c94c660828191b52b4d8392115df486a9adbe831e458d7395832",
451                "0dc1b755456e93701e9702d76fb0b92f90e01d1fe248153281fe79aa9763a92f",
452                "ae69d8d7ecd144de29fa135bd14f9573e349e45031e3b76982f583003826c552",
453                "e89a397c1a06bd2163488630d92e8c2bb643d7abef700da95d685c941489a46f",
454                "54b5316f62b5d2c3a7f1bbd134cb37353a44683fdc9d95d36458de22f6c44057",
455                "fe74a0a436c4308f73f4da42f35c47ac16a7138d483afc91e41dc3a1127382e0",
456                "c0f5119b0221b4fc639d6b9c38177a6de9b526ebd88c38d7982c07f98a0efd87",
457                "7d508aae275b946915c02e2e1106d175d74ec6777f5e80d12c053d9c7be1e341"
458            ),
459            bits,
460        )
461        .unwrap();
462        let p = BoxedUint::from_be_hex(
463            concat!(
464                "f827bbf3a41877c7cc59aebf42ed4b29c32defcb8ed96863d5b090a05a8930dd",
465                "624a21c9dcf9838568fdfa0df65b8462a5f2ac913d6c56f975532bd8e78fb07b",
466                "d405ca99a484bcf59f019bbddcb3933f2bce706300b4f7b110120c5df9018159",
467                "067c35da3061a56c8635a52b54273b31271b4311f0795df6021e6355e1a42e61"
468            ),
469            bits / 2,
470        )
471        .unwrap();
472        let q = BoxedUint::from_be_hex(
473            concat!(
474                "da4817ce0089dd36f2ade6a3ff410c73ec34bf1b4f6bda38431bfede11cef1f7",
475                "f6efa70e5f8063a3b1f6e17296ffb15feefa0912a0325b8d1fd65a559e717b5b",
476                "961ec345072e0ec5203d03441d29af4d64054a04507410cf1da78e7b6119d909",
477                "ec66e6ad625bf995b279a4b3c5be7d895cd7c5b9c4c497fde730916fcdb4e41b"
478            ),
479            bits / 2,
480        )
481        .unwrap();
482
483        let (mut p1, mut q1) = recover_primes(&NonZero::new(n).unwrap(), &e, &d).unwrap();
484
485        if p1 < q1 {
486            mem::swap(&mut p1, &mut q1);
487        }
488        assert_eq!(p, p1);
489        assert_eq!(q, q1);
490    }
491
492    #[test]
493    fn to_monty_matches_reference_reduction() {
494        use crypto_bigint::{Odd, Resize};
495
496        let n = Odd::new(
497            BoxedUint::from_be_hex(
498                concat!(
499                    "d397b84d98a4c26138ed1b695a8106ead91d553bf06041b62d3fdc50a041e222",
500                    "b8f4529689c1b82c5e71554f5dd69fa2f4b6158cf0dbeb57811a0fc327e1f28e",
501                    "74fe74d3bc166c1eabdc1b8b57b934ca8be5b00b4f29975bcc99acaf415b59bb",
502                    "28a6782bb41a2c3c2976b3c18dbadef62f00c6bb226640095096c0cc60d22fe7",
503                    "ef987d75c6a81b10d96bf292028af110dc7cc1bbc43d22adab379a0cd5d8078c",
504                    "c780ff5cd6209dea34c922cf784f7717e428d75b5aec8ff30e5f0141510766e2",
505                    "e0ab8d473c84e8710b2b98227c3db095337ad3452f19e2b9bfbccdd8148abf67",
506                    "76fa552775e6e75956e45229ae5a9c46949bab1e622f0e48f56524a84ed3483b"
507                ),
508                2048,
509            )
510            .unwrap(),
511        )
512        .unwrap();
513        let params = BoxedMontyParams::new(n.clone());
514        let nz = n.as_nz_ref();
515
516        let candidates = [
517            BoxedUint::zero_with_precision(2048),
518            BoxedUint::one_with_precision(2048),
519            n.as_ref() - &BoxedUint::one(),
520            n.as_ref().clone(),
521            n.as_ref().wrapping_add(BoxedUint::one()),
522            BoxedUint::max(2048),
523            BoxedUint::from(12345u64),
524            BoxedUint::max(4096),
525            BoxedUint::max(2048)
526                .resize(4096)
527                .wrapping_add(BoxedUint::one()),
528        ];
529        for x in candidates {
530            let expected = x.rem_vartime(nz).resize_unchecked(2048);
531            assert_eq!(to_monty(&x, &params).retrieve(), expected);
532        }
533    }
534}