ring/rsa/
keypair.rs

1// Copyright 2015-2016 Brian Smith.
2//
3// Permission to use, copy, modify, and/or distribute this software for any
4// purpose with or without fee is hereby granted, provided that the above
5// copyright notice and this permission notice appear in all copies.
6//
7// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
15use super::{
16    padding::{self, RsaEncoding},
17    KeyPairComponents, PublicExponent, PublicKey, PublicKeyComponents, N,
18};
19
20/// RSA PKCS#1 1.5 signatures.
21use crate::{
22    arithmetic::{
23        bigint,
24        montgomery::{R, RR, RRR},
25        LimbSliceError,
26    },
27    bits::BitLength,
28    cpu, digest,
29    error::{self, KeyRejected},
30    io::der,
31    pkcs8, rand, signature,
32};
33
34/// An RSA key pair, used for signing.
35pub struct KeyPair {
36    p: PrivateCrtPrime<P>,
37    q: PrivateCrtPrime<Q>,
38    qInv: bigint::Elem<P, R>,
39    public: PublicKey,
40}
41
42derive_debug_via_field!(KeyPair, stringify!(RsaKeyPair), public);
43
44impl KeyPair {
45    /// Parses an unencrypted PKCS#8-encoded RSA private key.
46    ///
47    /// This will generate a 2048-bit RSA private key of the correct form using
48    /// OpenSSL's command line tool:
49    ///
50    /// ```sh
51    ///    openssl genpkey -algorithm RSA \
52    ///        -pkeyopt rsa_keygen_bits:2048 \
53    ///        -pkeyopt rsa_keygen_pubexp:65537 | \
54    ///      openssl pkcs8 -topk8 -nocrypt -outform der > rsa-2048-private-key.pk8
55    /// ```
56    ///
57    /// This will generate a 3072-bit RSA private key of the correct form:
58    ///
59    /// ```sh
60    ///    openssl genpkey -algorithm RSA \
61    ///        -pkeyopt rsa_keygen_bits:3072 \
62    ///        -pkeyopt rsa_keygen_pubexp:65537 | \
63    ///      openssl pkcs8 -topk8 -nocrypt -outform der > rsa-3072-private-key.pk8
64    /// ```
65    ///
66    /// Often, keys generated for use in OpenSSL-based software are stored in
67    /// the Base64 “PEM” format without the PKCS#8 wrapper. Such keys can be
68    /// converted to binary PKCS#8 form using the OpenSSL command line tool like
69    /// this:
70    ///
71    /// ```sh
72    /// openssl pkcs8 -topk8 -nocrypt -outform der \
73    ///     -in rsa-2048-private-key.pem > rsa-2048-private-key.pk8
74    /// ```
75    ///
76    /// Base64 (“PEM”) PKCS#8-encoded keys can be converted to the binary PKCS#8
77    /// form like this:
78    ///
79    /// ```sh
80    /// openssl pkcs8 -nocrypt -outform der \
81    ///     -in rsa-2048-private-key.pem > rsa-2048-private-key.pk8
82    /// ```
83    ///
84    /// See [`Self::from_components`] for more details on how the input is
85    /// validated.
86    ///
87    /// See [RFC 5958] and [RFC 3447 Appendix A.1.2] for more details of the
88    /// encoding of the key.
89    ///
90    /// [NIST SP-800-56B rev. 1]:
91    ///     http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Br1.pdf
92    ///
93    /// [RFC 3447 Appendix A.1.2]:
94    ///     https://tools.ietf.org/html/rfc3447#appendix-A.1.2
95    ///
96    /// [RFC 5958]:
97    ///     https://tools.ietf.org/html/rfc5958
98    pub fn from_pkcs8(pkcs8: &[u8]) -> Result<Self, KeyRejected> {
99        const RSA_ENCRYPTION: &[u8] = include_bytes!("../data/alg-rsa-encryption.der");
100        let (der, _) = pkcs8::unwrap_key_(
101            untrusted::Input::from(RSA_ENCRYPTION),
102            pkcs8::Version::V1Only,
103            untrusted::Input::from(pkcs8),
104        )?;
105        Self::from_der(der.as_slice_less_safe())
106    }
107
108    /// Parses an RSA private key that is not inside a PKCS#8 wrapper.
109    ///
110    /// The private key must be encoded as a binary DER-encoded ASN.1
111    /// `RSAPrivateKey` as described in [RFC 3447 Appendix A.1.2]). In all other
112    /// respects, this is just like `from_pkcs8()`. See the documentation for
113    /// `from_pkcs8()` for more details.
114    ///
115    /// It is recommended to use `from_pkcs8()` (with a PKCS#8-encoded key)
116    /// instead.
117    ///
118    /// See [`Self::from_components()`] for more details on how the input is
119    /// validated.
120    ///
121    /// [RFC 3447 Appendix A.1.2]:
122    ///     https://tools.ietf.org/html/rfc3447#appendix-A.1.2
123    ///
124    /// [NIST SP-800-56B rev. 1]:
125    ///     http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Br1.pdf
126    pub fn from_der(input: &[u8]) -> Result<Self, KeyRejected> {
127        untrusted::Input::from(input).read_all(KeyRejected::invalid_encoding(), |input| {
128            der::nested(
129                input,
130                der::Tag::Sequence,
131                KeyRejected::invalid_encoding(),
132                Self::from_der_reader,
133            )
134        })
135    }
136
137    fn from_der_reader(input: &mut untrusted::Reader) -> Result<Self, KeyRejected> {
138        let version = der::small_nonnegative_integer(input)
139            .map_err(|error::Unspecified| KeyRejected::invalid_encoding())?;
140        if version != 0 {
141            return Err(KeyRejected::version_not_supported());
142        }
143
144        fn nonnegative_integer<'a>(
145            input: &mut untrusted::Reader<'a>,
146        ) -> Result<&'a [u8], KeyRejected> {
147            der::nonnegative_integer(input)
148                .map(|input| input.as_slice_less_safe())
149                .map_err(|error::Unspecified| KeyRejected::invalid_encoding())
150        }
151
152        let n = nonnegative_integer(input)?;
153        let e = nonnegative_integer(input)?;
154        let d = nonnegative_integer(input)?;
155        let p = nonnegative_integer(input)?;
156        let q = nonnegative_integer(input)?;
157        let dP = nonnegative_integer(input)?;
158        let dQ = nonnegative_integer(input)?;
159        let qInv = nonnegative_integer(input)?;
160
161        let components = KeyPairComponents {
162            public_key: PublicKeyComponents { n, e },
163            d,
164            p,
165            q,
166            dP,
167            dQ,
168            qInv,
169        };
170
171        Self::from_components(&components)
172    }
173
174    /// Constructs an RSA private key from its big-endian-encoded components.
175    ///
176    /// Only two-prime (not multi-prime) keys are supported. The public modulus
177    /// (n) must be at least 2047 bits. The public modulus must be no larger
178    /// than 4096 bits. It is recommended that the public modulus be exactly
179    /// 2048 or 3072 bits. The public exponent must be at least 65537 and must
180    /// be no more than 33 bits long.
181    ///
182    /// The private key is validated according to [NIST SP-800-56B rev. 1]
183    /// section 6.4.1.4.3, crt_pkv (Intended Exponent-Creation Method Unknown),
184    /// with the following exceptions:
185    ///
186    /// * Section 6.4.1.2.1, Step 1: Neither a target security level nor an
187    ///   expected modulus length is provided as a parameter, so checks
188    ///   regarding these expectations are not done.
189    /// * Section 6.4.1.2.1, Step 3: Since neither the public key nor the
190    ///   expected modulus length is provided as a parameter, the consistency
191    ///   check between these values and the private key's value of n isn't
192    ///   done.
193    /// * Section 6.4.1.2.1, Step 5: No primality tests are done, both for
194    ///   performance reasons and to avoid any side channels that such tests
195    ///   would provide.
196    /// * Section 6.4.1.2.1, Step 6, and 6.4.1.4.3, Step 7:
197    ///   * *ring* has a slightly looser lower bound for the values of `p`
198    ///     and `q` than what the NIST document specifies. This looser lower
199    ///     bound matches what most other crypto libraries do. The check might
200    ///     be tightened to meet NIST's requirements in the future. Similarly,
201    ///     the check that `p` and `q` are not too close together is skipped
202    ///     currently, but may be added in the future.
203    ///   * The validity of the mathematical relationship of `dP`, `dQ`, `e`
204    ///     and `n` is verified only during signing. Some size checks of `d`,
205    ///     `dP` and `dQ` are performed at construction, but some NIST checks
206    ///     are skipped because they would be expensive and/or they would leak
207    ///     information through side channels. If a preemptive check of the
208    ///     consistency of `dP`, `dQ`, `e` and `n` with each other is
209    ///     necessary, that can be done by signing any message with the key
210    ///     pair.
211    ///
212    ///   * `d` is not fully validated, neither at construction nor during
213    ///     signing. This is OK as far as *ring*'s usage of the key is
214    ///     concerned because *ring* never uses the value of `d` (*ring* always
215    ///     uses `p`, `q`, `dP` and `dQ` via the Chinese Remainder Theorem,
216    ///     instead). However, *ring*'s checks would not be sufficient for
217    ///     validating a key pair for use by some other system; that other
218    ///     system must check the value of `d` itself if `d` is to be used.
219    pub fn from_components<Public, Private>(
220        components: &KeyPairComponents<Public, Private>,
221    ) -> Result<Self, KeyRejected>
222    where
223        Public: AsRef<[u8]>,
224        Private: AsRef<[u8]>,
225    {
226        let components = KeyPairComponents {
227            public_key: PublicKeyComponents {
228                n: components.public_key.n.as_ref(),
229                e: components.public_key.e.as_ref(),
230            },
231            d: components.d.as_ref(),
232            p: components.p.as_ref(),
233            q: components.q.as_ref(),
234            dP: components.dP.as_ref(),
235            dQ: components.dQ.as_ref(),
236            qInv: components.qInv.as_ref(),
237        };
238        Self::from_components_(&components, cpu::features())
239    }
240
241    fn from_components_(
242        &KeyPairComponents {
243            public_key,
244            d,
245            p,
246            q,
247            dP,
248            dQ,
249            qInv,
250        }: &KeyPairComponents<&[u8]>,
251        cpu_features: cpu::Features,
252    ) -> Result<Self, KeyRejected> {
253        let d = untrusted::Input::from(d);
254        let p = untrusted::Input::from(p);
255        let q = untrusted::Input::from(q);
256        let dP = untrusted::Input::from(dP);
257        let dQ = untrusted::Input::from(dQ);
258        let qInv = untrusted::Input::from(qInv);
259
260        // XXX: Some steps are done out of order, but the NIST steps are worded
261        // in such a way that it is clear that NIST intends for them to be done
262        // in order. TODO: Does this matter at all?
263
264        // 6.4.1.4.3/6.4.1.2.1 - Step 1.
265
266        // Step 1.a is omitted, as explained above.
267
268        // Step 1.b is omitted per above. Instead, we check that the public
269        // modulus is 2048 to `PRIVATE_KEY_PUBLIC_MODULUS_MAX_BITS` bits.
270        // XXX: The maximum limit of 4096 bits is primarily due to lack of
271        // testing of larger key sizes; see, in particular,
272        // https://www.mail-archive.com/openssl-dev@openssl.org/msg44586.html
273        // and
274        // https://www.mail-archive.com/openssl-dev@openssl.org/msg44759.html.
275        // Also, this limit might help with memory management decisions later.
276
277        // Step 1.c. We validate e >= 65537.
278        let n = untrusted::Input::from(public_key.n);
279        let e = untrusted::Input::from(public_key.e);
280        let public_key = PublicKey::from_modulus_and_exponent(
281            n,
282            e,
283            BitLength::from_bits(2048),
284            super::PRIVATE_KEY_PUBLIC_MODULUS_MAX_BITS,
285            PublicExponent::_65537,
286            cpu_features,
287        )?;
288
289        let n_one = public_key.inner().n().oneRR();
290        let n = &public_key.inner().n().value(cpu_features);
291
292        // 6.4.1.4.3 says to skip 6.4.1.2.1 Step 2.
293
294        // 6.4.1.4.3 Step 3.
295
296        // Step 3.a is done below, out of order.
297        // Step 3.b is unneeded since `n_bits` is derived here from `n`.
298
299        // 6.4.1.4.3 says to skip 6.4.1.2.1 Step 4. (We don't need to recover
300        // the prime factors since they are already given.)
301
302        // 6.4.1.4.3 - Step 5.
303
304        // Steps 5.a and 5.b are omitted, as explained above.
305
306        let n_bits = public_key.inner().n().len_bits();
307
308        let p = PrivatePrime::new(p, n_bits, cpu_features)?;
309        let q = PrivatePrime::new(q, n_bits, cpu_features)?;
310
311        // TODO: Step 5.i
312        //
313        // 3.b is unneeded since `n_bits` is derived here from `n`.
314
315        // 6.4.1.4.3 - Step 3.a (out of order).
316        //
317        // Verify that p * q == n. We restrict ourselves to modular
318        // multiplication. We rely on the fact that we've verified
319        // 0 < q < p < n. We check that q and p are close to sqrt(n) and then
320        // assume that these preconditions are enough to let us assume that
321        // checking p * q == 0 (mod n) is equivalent to checking p * q == n.
322        let q_mod_n = q
323            .modulus
324            .to_elem(n)
325            .map_err(|error::Unspecified| KeyRejected::inconsistent_components())?;
326        let p_mod_n = p
327            .modulus
328            .to_elem(n)
329            .map_err(|error::Unspecified| KeyRejected::inconsistent_components())?;
330        let p_mod_n = bigint::elem_mul(n_one, p_mod_n, n);
331        let pq_mod_n = bigint::elem_mul(&q_mod_n, p_mod_n, n);
332        if !pq_mod_n.is_zero() {
333            return Err(KeyRejected::inconsistent_components());
334        }
335
336        // 6.4.1.4.3/6.4.1.2.1 - Step 6.
337
338        // Step 6.a, partial.
339        //
340        // First, validate `2**half_n_bits < d`. Since 2**half_n_bits has a bit
341        // length of half_n_bits + 1, this check gives us 2**half_n_bits <= d,
342        // and knowing d is odd makes the inequality strict.
343        let d = bigint::OwnedModulusValue::<D>::from_be_bytes(d)
344            .map_err(|_| KeyRejected::invalid_component())?;
345        if !(n_bits.half_rounded_up() < d.len_bits()) {
346            return Err(KeyRejected::inconsistent_components());
347        }
348        // XXX: This check should be `d < LCM(p - 1, q - 1)`, but we don't have
349        // a good way of calculating LCM, so it is omitted, as explained above.
350        d.verify_less_than(n)
351            .map_err(|error::Unspecified| KeyRejected::inconsistent_components())?;
352
353        // Step 6.b is omitted as explained above.
354
355        let pm = &p.modulus.modulus(cpu_features);
356
357        // 6.4.1.4.3 - Step 7.
358
359        // Step 7.c.
360        let qInv = bigint::Elem::from_be_bytes_padded(qInv, pm)
361            .map_err(|error::Unspecified| KeyRejected::invalid_component())?;
362
363        // Steps 7.d and 7.e are omitted per the documentation above, and
364        // because we don't (in the long term) have a good way to do modulo
365        // with an even modulus.
366
367        // Step 7.f.
368        let qInv = bigint::elem_mul(p.oneRR.as_ref(), qInv, pm);
369        let q_mod_p = bigint::elem_reduced(pm.alloc_zero(), &q_mod_n, pm, q.modulus.len_bits());
370        let q_mod_p = bigint::elem_mul(p.oneRR.as_ref(), q_mod_p, pm);
371        bigint::verify_inverses_consttime(&qInv, q_mod_p, pm)
372            .map_err(|error::Unspecified| KeyRejected::inconsistent_components())?;
373
374        // This should never fail since `n` and `e` were validated above.
375
376        let p = PrivateCrtPrime::new(p, dP, cpu_features)?;
377        let q = PrivateCrtPrime::new(q, dQ, cpu_features)?;
378
379        Ok(Self {
380            p,
381            q,
382            qInv,
383            public: public_key,
384        })
385    }
386
387    /// Returns a reference to the public key.
388    pub fn public(&self) -> &PublicKey {
389        &self.public
390    }
391
392    /// Returns the length in bytes of the key pair's public modulus.
393    ///
394    /// A signature has the same length as the public modulus.
395    #[deprecated = "Use `public().modulus_len()`"]
396    #[inline]
397    pub fn public_modulus_len(&self) -> usize {
398        self.public().modulus_len()
399    }
400}
401
402impl signature::KeyPair for KeyPair {
403    type PublicKey = PublicKey;
404
405    fn public_key(&self) -> &Self::PublicKey {
406        self.public()
407    }
408}
409
410struct PrivatePrime<M> {
411    modulus: bigint::OwnedModulus<M>,
412    oneRR: bigint::One<M, RR>,
413}
414
415impl<M> PrivatePrime<M> {
416    fn new(
417        p: untrusted::Input,
418        n_bits: BitLength,
419        cpu_features: cpu::Features,
420    ) -> Result<Self, KeyRejected> {
421        let p = bigint::OwnedModulusValue::from_be_bytes(p)?;
422
423        // 5.c / 5.g:
424        //
425        // TODO: First, stop if `p < (√2) * 2**((nBits/2) - 1)`.
426        // TODO: First, stop if `q < (√2) * 2**((nBits/2) - 1)`.
427        //
428        // Second, stop if `p > 2**(nBits/2) - 1`.
429        // Second, stop if `q > 2**(nBits/2) - 1`.
430        if p.len_bits() != n_bits.half_rounded_up() {
431            return Err(KeyRejected::inconsistent_components());
432        }
433
434        if p.len_bits().as_bits() % 512 != 0 {
435            return Err(KeyRejected::private_modulus_len_not_multiple_of_512_bits());
436        }
437
438        // TODO: Step 5.d: Verify GCD(p - 1, e) == 1.
439        // TODO: Step 5.h: Verify GCD(q - 1, e) == 1.
440
441        // Steps 5.e and 5.f are omitted as explained above.
442        let p = bigint::OwnedModulus::from(p);
443        let pm = p.modulus(cpu_features);
444        let oneRR = bigint::One::newRR(pm.alloc_zero(), &pm);
445
446        Ok(Self { modulus: p, oneRR })
447    }
448}
449
450struct PrivateCrtPrime<M> {
451    modulus: bigint::OwnedModulus<M>,
452    oneRRR: bigint::One<M, RRR>,
453    exponent: bigint::PrivateExponent,
454}
455
456impl<M> PrivateCrtPrime<M> {
457    /// Constructs a `PrivateCrtPrime` from the private prime `p` and `dP` where
458    /// dP == d % (p - 1).
459    fn new(
460        p: PrivatePrime<M>,
461        dP: untrusted::Input,
462        cpu_features: cpu::Features,
463    ) -> Result<Self, KeyRejected> {
464        let m = &p.modulus.modulus(cpu_features);
465        // [NIST SP-800-56B rev. 1] 6.4.1.4.3 - Steps 7.a & 7.b.
466        let dP = bigint::PrivateExponent::from_be_bytes_padded(dP, m)
467            .map_err(|error::Unspecified| KeyRejected::inconsistent_components())?;
468
469        // XXX: Steps 7.d and 7.e are omitted. We don't check that
470        // `dP == d % (p - 1)` because we don't (in the long term) have a good
471        // way to do modulo with an even modulus. Instead we just check that
472        // `1 <= dP < p - 1`. We'll check it, to some unknown extent, when we
473        // do the private key operation, since we verify that the result of the
474        // private key operation using the CRT parameters is consistent with `n`
475        // and `e`. TODO: Either prove that what we do is sufficient, or make
476        // it so.
477
478        let oneRRR = bigint::One::newRRR(p.oneRR, m);
479
480        Ok(Self {
481            modulus: p.modulus,
482            oneRRR,
483            exponent: dP,
484        })
485    }
486}
487
488fn elem_exp_consttime<M>(
489    c: &bigint::Elem<N>,
490    p: &PrivateCrtPrime<M>,
491    other_prime_len_bits: BitLength,
492    cpu_features: cpu::Features,
493) -> Result<bigint::Elem<M>, error::Unspecified> {
494    let m = &p.modulus.modulus(cpu_features);
495    bigint::elem_exp_consttime(
496        m.alloc_zero(),
497        c,
498        &p.oneRRR,
499        &p.exponent,
500        m,
501        other_prime_len_bits,
502    )
503    .map_err(error::erase::<LimbSliceError>)
504}
505
506// Type-level representations of the different moduli used in RSA signing, in
507// addition to `super::N`. See `super::bigint`'s modulue-level documentation.
508
509enum P {}
510
511enum Q {}
512
513enum D {}
514
515impl KeyPair {
516    /// Computes the signature of `msg` and writes it into `signature`.
517    ///
518    /// `msg` is digested using the digest algorithm from `padding_alg` and the
519    /// digest is then padded using the padding algorithm from `padding_alg`.
520    ///
521    /// The signature it written into `signature`; `signature`'s length must be
522    /// exactly the length returned by `self::public().modulus_len()` or else
523    /// an error will be returned. On failure, `signature` may contain
524    /// intermediate results, but won't contain anything that would endanger the
525    /// private key.
526    ///
527    /// `rng` may be used to randomize the padding (e.g. for PSS).
528    ///
529    /// Many other crypto libraries have signing functions that takes a
530    /// precomputed digest as input, instead of the message to digest. This
531    /// function does *not* take a precomputed digest; instead, `sign`
532    /// calculates the digest itself.
533    pub fn sign(
534        &self,
535        padding_alg: &'static dyn RsaEncoding,
536        rng: &dyn rand::SecureRandom,
537        msg: &[u8],
538        signature: &mut [u8],
539    ) -> Result<(), error::Unspecified> {
540        let cpu_features = cpu::features();
541
542        if signature.len() != self.public().modulus_len() {
543            return Err(error::Unspecified);
544        }
545
546        let m_hash = digest::digest(padding_alg.digest_alg(), msg);
547
548        // Use the output buffer as the scratch space for the signature to
549        // reduce the required stack space.
550        padding::encode(
551            padding_alg,
552            m_hash,
553            signature,
554            self.public().inner().n().len_bits(),
555            rng,
556        )?;
557
558        // RFC 8017 Section 5.1.2: RSADP, using the Chinese Remainder Theorem
559        // with Garner's algorithm.
560
561        // Steps 1 and 2.
562        let m = self.private_exponentiate(signature, cpu_features)?;
563
564        // Step 3.
565        m.fill_be_bytes(signature);
566
567        Ok(())
568    }
569
570    /// Returns base**d (mod n).
571    ///
572    /// This does not return or write any intermediate results into any buffers
573    /// that are provided by the caller so that no intermediate state will be
574    /// leaked that would endanger the private key.
575    ///
576    /// Panics if `in_out` is not `self.public().modulus_len()`.
577    fn private_exponentiate(
578        &self,
579        base: &[u8],
580        cpu_features: cpu::Features,
581    ) -> Result<bigint::Elem<N>, error::Unspecified> {
582        assert_eq!(base.len(), self.public().modulus_len());
583
584        // RFC 8017 Section 5.1.2: RSADP, using the Chinese Remainder Theorem
585        // with Garner's algorithm.
586
587        let n = &self.public.inner().n().value(cpu_features);
588        let n_one = self.public.inner().n().oneRR();
589
590        // Step 1. The value zero is also rejected.
591        let base = bigint::Elem::from_be_bytes_padded(untrusted::Input::from(base), n)?;
592
593        // Step 2
594        let c = base;
595
596        // Step 2.b.i.
597        let q_bits = self.q.modulus.len_bits();
598        let m_1 = elem_exp_consttime(&c, &self.p, q_bits, cpu_features)?;
599        let m_2 = elem_exp_consttime(&c, &self.q, self.p.modulus.len_bits(), cpu_features)?;
600
601        // Step 2.b.ii isn't needed since there are only two primes.
602
603        // Step 2.b.iii.
604        let h = {
605            let p = &self.p.modulus.modulus(cpu_features);
606            let m_2 = bigint::elem_reduced_once(p.alloc_zero(), &m_2, p, q_bits);
607            let m_1_minus_m_2 = bigint::elem_sub(m_1, &m_2, p);
608            bigint::elem_mul(&self.qInv, m_1_minus_m_2, p)
609        };
610
611        // Step 2.b.iv. The reduction in the modular multiplication isn't
612        // necessary because `h < p` and `p * q == n` implies `h * q < n`.
613        // Modular arithmetic is used simply to avoid implementing
614        // non-modular arithmetic.
615        let p_bits = self.p.modulus.len_bits();
616        let h = bigint::elem_widen(n.alloc_zero(), h, n, p_bits)?;
617        let q_mod_n = self.q.modulus.to_elem(n)?;
618        let q_mod_n = bigint::elem_mul(n_one, q_mod_n, n);
619        let q_times_h = bigint::elem_mul(&q_mod_n, h, n);
620        let m_2 = bigint::elem_widen(n.alloc_zero(), m_2, n, q_bits)?;
621        let m = bigint::elem_add(m_2, q_times_h, n);
622
623        // Step 2.b.v isn't needed since there are only two primes.
624
625        // Verify the result to protect against fault attacks as described
626        // in "On the Importance of Checking Cryptographic Protocols for
627        // Faults" by Dan Boneh, Richard A. DeMillo, and Richard J. Lipton.
628        // This check is cheap assuming `e` is small, which is ensured during
629        // `KeyPair` construction. Note that this is the only validation of `e`
630        // that is done other than basic checks on its size, oddness, and
631        // minimum value, since the relationship of `e` to `d`, `p`, and `q` is
632        // not verified during `KeyPair` construction.
633        {
634            let verify = n.alloc_zero();
635            let verify = self
636                .public
637                .inner()
638                .exponentiate_elem(verify, &m, cpu_features);
639            bigint::elem_verify_equal_consttime(&verify, &c)?;
640        }
641
642        // Step 3 will be done by the caller.
643
644        Ok(m)
645    }
646}
647
648#[cfg(test)]
649mod tests {
650    use super::*;
651    use crate::testutil as test;
652    use alloc::vec;
653
654    #[test]
655    fn test_rsakeypair_private_exponentiate() {
656        let cpu = cpu::features();
657        test::run(
658            test_vector_file!("keypair_private_exponentiate_tests.txt"),
659            |section, test_case| {
660                assert_eq!(section, "");
661
662                let key = test_case.consume_bytes("Key");
663                let key = KeyPair::from_pkcs8(&key).unwrap();
664                let test_cases = &[
665                    test_case.consume_bytes("p"),
666                    test_case.consume_bytes("p_plus_1"),
667                    test_case.consume_bytes("p_minus_1"),
668                    test_case.consume_bytes("q"),
669                    test_case.consume_bytes("q_plus_1"),
670                    test_case.consume_bytes("q_minus_1"),
671                ];
672                for test_case in test_cases {
673                    // THe call to `elem_verify_equal_consttime` will cause
674                    // `private_exponentiate` to fail if the computation is
675                    // incorrect.
676                    let mut padded = vec![0; key.public.modulus_len()];
677                    let zeroes = padded.len() - test_case.len();
678                    padded[zeroes..].copy_from_slice(test_case);
679                    let _: bigint::Elem<_> = key.private_exponentiate(&padded, cpu).unwrap();
680                }
681                Ok(())
682            },
683        );
684    }
685}