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