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