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