Coverage Report

Created: 2025-07-12 06:15

/rust/registry/src/index.crates.io-6f17d22bba15001f/ring-0.17.14/src/rsa/keypair.rs
Line
Count
Source (jump to first uncovered line)
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
15
use super::{
16
    padding::{self, RsaEncoding},
17
    KeyPairComponents, PublicExponent, PublicKey, PublicKeyComponents, N,
18
};
19
20
/// RSA PKCS#1 1.5 signatures.
21
use 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.
35
pub struct KeyPair {
36
    p: PrivateCrtPrime<P>,
37
    q: PrivateCrtPrime<Q>,
38
    qInv: bigint::Elem<P, R>,
39
    public: PublicKey,
40
}
41
42
derive_debug_via_field!(KeyPair, stringify!(RsaKeyPair), public);
43
44
impl 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
0
    pub fn from_pkcs8(pkcs8: &[u8]) -> Result<Self, KeyRejected> {
99
        const RSA_ENCRYPTION: &[u8] = include_bytes!("../data/alg-rsa-encryption.der");
100
0
        let (der, _) = pkcs8::unwrap_key_(
101
0
            untrusted::Input::from(RSA_ENCRYPTION),
102
0
            pkcs8::Version::V1Only,
103
0
            untrusted::Input::from(pkcs8),
104
0
        )?;
105
0
        Self::from_der(der.as_slice_less_safe())
106
0
    }
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
0
    pub fn from_der(input: &[u8]) -> Result<Self, KeyRejected> {
127
0
        untrusted::Input::from(input).read_all(KeyRejected::invalid_encoding(), |input| {
128
0
            der::nested(
129
0
                input,
130
0
                der::Tag::Sequence,
131
0
                KeyRejected::invalid_encoding(),
132
0
                Self::from_der_reader,
133
0
            )
134
0
        })
135
0
    }
136
137
0
    fn from_der_reader(input: &mut untrusted::Reader) -> Result<Self, KeyRejected> {
138
0
        let version = der::small_nonnegative_integer(input)
139
0
            .map_err(|error::Unspecified| KeyRejected::invalid_encoding())?;
140
0
        if version != 0 {
141
0
            return Err(KeyRejected::version_not_supported());
142
0
        }
143
144
0
        fn nonnegative_integer<'a>(
145
0
            input: &mut untrusted::Reader<'a>,
146
0
        ) -> Result<&'a [u8], KeyRejected> {
147
0
            der::nonnegative_integer(input)
148
0
                .map(|input| input.as_slice_less_safe())
149
0
                .map_err(|error::Unspecified| KeyRejected::invalid_encoding())
150
0
        }
151
152
0
        let n = nonnegative_integer(input)?;
153
0
        let e = nonnegative_integer(input)?;
154
0
        let d = nonnegative_integer(input)?;
155
0
        let p = nonnegative_integer(input)?;
156
0
        let q = nonnegative_integer(input)?;
157
0
        let dP = nonnegative_integer(input)?;
158
0
        let dQ = nonnegative_integer(input)?;
159
0
        let qInv = nonnegative_integer(input)?;
160
161
0
        let components = KeyPairComponents {
162
0
            public_key: PublicKeyComponents { n, e },
163
0
            d,
164
0
            p,
165
0
            q,
166
0
            dP,
167
0
            dQ,
168
0
            qInv,
169
0
        };
170
0
171
0
        Self::from_components(&components)
172
0
    }
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
0
    pub fn from_components<Public, Private>(
220
0
        components: &KeyPairComponents<Public, Private>,
221
0
    ) -> Result<Self, KeyRejected>
222
0
    where
223
0
        Public: AsRef<[u8]>,
224
0
        Private: AsRef<[u8]>,
225
0
    {
226
0
        let components = KeyPairComponents {
227
0
            public_key: PublicKeyComponents {
228
0
                n: components.public_key.n.as_ref(),
229
0
                e: components.public_key.e.as_ref(),
230
0
            },
231
0
            d: components.d.as_ref(),
232
0
            p: components.p.as_ref(),
233
0
            q: components.q.as_ref(),
234
0
            dP: components.dP.as_ref(),
235
0
            dQ: components.dQ.as_ref(),
236
0
            qInv: components.qInv.as_ref(),
237
0
        };
238
0
        Self::from_components_(&components, cpu::features())
239
0
    }
240
241
0
    fn from_components_(
242
0
        &KeyPairComponents {
243
0
            public_key,
244
0
            d,
245
0
            p,
246
0
            q,
247
0
            dP,
248
0
            dQ,
249
0
            qInv,
250
0
        }: &KeyPairComponents<&[u8]>,
251
0
        cpu_features: cpu::Features,
252
0
    ) -> Result<Self, KeyRejected> {
253
0
        let d = untrusted::Input::from(d);
254
0
        let p = untrusted::Input::from(p);
255
0
        let q = untrusted::Input::from(q);
256
0
        let dP = untrusted::Input::from(dP);
257
0
        let dQ = untrusted::Input::from(dQ);
258
0
        let qInv = untrusted::Input::from(qInv);
259
0
260
0
        // XXX: Some steps are done out of order, but the NIST steps are worded
261
0
        // in such a way that it is clear that NIST intends for them to be done
262
0
        // in order. TODO: Does this matter at all?
263
0
264
0
        // 6.4.1.4.3/6.4.1.2.1 - Step 1.
265
0
266
0
        // Step 1.a is omitted, as explained above.
267
0
268
0
        // Step 1.b is omitted per above. Instead, we check that the public
269
0
        // modulus is 2048 to `PRIVATE_KEY_PUBLIC_MODULUS_MAX_BITS` bits.
270
0
        // XXX: The maximum limit of 4096 bits is primarily due to lack of
271
0
        // testing of larger key sizes; see, in particular,
272
0
        // https://www.mail-archive.com/openssl-dev@openssl.org/msg44586.html
273
0
        // and
274
0
        // https://www.mail-archive.com/openssl-dev@openssl.org/msg44759.html.
275
0
        // Also, this limit might help with memory management decisions later.
276
0
277
0
        // Step 1.c. We validate e >= 65537.
278
0
        let n = untrusted::Input::from(public_key.n);
279
0
        let e = untrusted::Input::from(public_key.e);
280
0
        let public_key = PublicKey::from_modulus_and_exponent(
281
0
            n,
282
0
            e,
283
0
            BitLength::from_bits(2048),
284
0
            super::PRIVATE_KEY_PUBLIC_MODULUS_MAX_BITS,
285
0
            PublicExponent::_65537,
286
0
            cpu_features,
287
0
        )?;
288
289
0
        let n_one = public_key.inner().n().oneRR();
290
0
        let n = &public_key.inner().n().value(cpu_features);
291
0
292
0
        // 6.4.1.4.3 says to skip 6.4.1.2.1 Step 2.
293
0
294
0
        // 6.4.1.4.3 Step 3.
295
0
296
0
        // Step 3.a is done below, out of order.
297
0
        // Step 3.b is unneeded since `n_bits` is derived here from `n`.
298
0
299
0
        // 6.4.1.4.3 says to skip 6.4.1.2.1 Step 4. (We don't need to recover
300
0
        // the prime factors since they are already given.)
301
0
302
0
        // 6.4.1.4.3 - Step 5.
303
0
304
0
        // Steps 5.a and 5.b are omitted, as explained above.
305
0
306
0
        let n_bits = public_key.inner().n().len_bits();
307
308
0
        let p = PrivatePrime::new(p, n_bits, cpu_features)?;
309
0
        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
0
        let q_mod_n = q
323
0
            .modulus
324
0
            .to_elem(n)
325
0
            .map_err(|error::Unspecified| KeyRejected::inconsistent_components())?;
326
0
        let p_mod_n = p
327
0
            .modulus
328
0
            .to_elem(n)
329
0
            .map_err(|error::Unspecified| KeyRejected::inconsistent_components())?;
330
0
        let p_mod_n = bigint::elem_mul(n_one, p_mod_n, n);
331
0
        let pq_mod_n = bigint::elem_mul(&q_mod_n, p_mod_n, n);
332
0
        if !pq_mod_n.is_zero() {
333
0
            return Err(KeyRejected::inconsistent_components());
334
0
        }
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
0
        let d = bigint::OwnedModulusValue::<D>::from_be_bytes(d)
344
0
            .map_err(|_| KeyRejected::invalid_component())?;
345
0
        if !(n_bits.half_rounded_up() < d.len_bits()) {
346
0
            return Err(KeyRejected::inconsistent_components());
347
0
        }
348
0
        // XXX: This check should be `d < LCM(p - 1, q - 1)`, but we don't have
349
0
        // a good way of calculating LCM, so it is omitted, as explained above.
350
0
        d.verify_less_than(n)
351
0
            .map_err(|error::Unspecified| KeyRejected::inconsistent_components())?;
352
353
        // Step 6.b is omitted as explained above.
354
355
0
        let pm = &p.modulus.modulus(cpu_features);
356
357
        // 6.4.1.4.3 - Step 7.
358
359
        // Step 7.c.
360
0
        let qInv = bigint::Elem::from_be_bytes_padded(qInv, pm)
361
0
            .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
0
        let qInv = bigint::elem_mul(p.oneRR.as_ref(), qInv, pm);
369
0
        let q_mod_p = bigint::elem_reduced(pm.alloc_zero(), &q_mod_n, pm, q.modulus.len_bits());
370
0
        let q_mod_p = bigint::elem_mul(p.oneRR.as_ref(), q_mod_p, pm);
371
0
        bigint::verify_inverses_consttime(&qInv, q_mod_p, pm)
372
0
            .map_err(|error::Unspecified| KeyRejected::inconsistent_components())?;
373
374
        // This should never fail since `n` and `e` were validated above.
375
376
0
        let p = PrivateCrtPrime::new(p, dP, cpu_features)?;
377
0
        let q = PrivateCrtPrime::new(q, dQ, cpu_features)?;
378
379
0
        Ok(Self {
380
0
            p,
381
0
            q,
382
0
            qInv,
383
0
            public: public_key,
384
0
        })
385
0
    }
386
387
    /// Returns a reference to the public key.
388
0
    pub fn public(&self) -> &PublicKey {
389
0
        &self.public
390
0
    }
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
0
    pub fn public_modulus_len(&self) -> usize {
398
0
        self.public().modulus_len()
399
0
    }
400
}
401
402
impl signature::KeyPair for KeyPair {
403
    type PublicKey = PublicKey;
404
405
0
    fn public_key(&self) -> &Self::PublicKey {
406
0
        self.public()
407
0
    }
408
}
409
410
struct PrivatePrime<M> {
411
    modulus: bigint::OwnedModulus<M>,
412
    oneRR: bigint::One<M, RR>,
413
}
414
415
impl<M> PrivatePrime<M> {
416
0
    fn new(
417
0
        p: untrusted::Input,
418
0
        n_bits: BitLength,
419
0
        cpu_features: cpu::Features,
420
0
    ) -> Result<Self, KeyRejected> {
421
0
        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
0
        if p.len_bits() != n_bits.half_rounded_up() {
431
0
            return Err(KeyRejected::inconsistent_components());
432
0
        }
433
0
434
0
        if p.len_bits().as_bits() % 512 != 0 {
435
0
            return Err(KeyRejected::private_modulus_len_not_multiple_of_512_bits());
436
0
        }
437
0
438
0
        // TODO: Step 5.d: Verify GCD(p - 1, e) == 1.
439
0
        // TODO: Step 5.h: Verify GCD(q - 1, e) == 1.
440
0
441
0
        // Steps 5.e and 5.f are omitted as explained above.
442
0
        let p = bigint::OwnedModulus::from(p);
443
0
        let pm = p.modulus(cpu_features);
444
0
        let oneRR = bigint::One::newRR(pm.alloc_zero(), &pm);
445
0
446
0
        Ok(Self { modulus: p, oneRR })
447
0
    }
Unexecuted instantiation: <ring::rsa::keypair::PrivatePrime<ring::rsa::keypair::P>>::new
Unexecuted instantiation: <ring::rsa::keypair::PrivatePrime<ring::rsa::keypair::Q>>::new
448
}
449
450
struct PrivateCrtPrime<M> {
451
    modulus: bigint::OwnedModulus<M>,
452
    oneRRR: bigint::One<M, RRR>,
453
    exponent: bigint::PrivateExponent,
454
}
455
456
impl<M> PrivateCrtPrime<M> {
457
    /// Constructs a `PrivateCrtPrime` from the private prime `p` and `dP` where
458
    /// dP == d % (p - 1).
459
0
    fn new(
460
0
        p: PrivatePrime<M>,
461
0
        dP: untrusted::Input,
462
0
        cpu_features: cpu::Features,
463
0
    ) -> Result<Self, KeyRejected> {
464
0
        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
0
        let dP = bigint::PrivateExponent::from_be_bytes_padded(dP, m)
467
0
            .map_err(|error::Unspecified| KeyRejected::inconsistent_components())?;
Unexecuted instantiation: <ring::rsa::keypair::PrivateCrtPrime<ring::rsa::keypair::P>>::new::{closure#0}
Unexecuted instantiation: <ring::rsa::keypair::PrivateCrtPrime<ring::rsa::keypair::Q>>::new::{closure#0}
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
0
        let oneRRR = bigint::One::newRRR(p.oneRR, m);
479
0
480
0
        Ok(Self {
481
0
            modulus: p.modulus,
482
0
            oneRRR,
483
0
            exponent: dP,
484
0
        })
485
0
    }
Unexecuted instantiation: <ring::rsa::keypair::PrivateCrtPrime<ring::rsa::keypair::P>>::new
Unexecuted instantiation: <ring::rsa::keypair::PrivateCrtPrime<ring::rsa::keypair::Q>>::new
486
}
487
488
0
fn elem_exp_consttime<M>(
489
0
    c: &bigint::Elem<N>,
490
0
    p: &PrivateCrtPrime<M>,
491
0
    other_prime_len_bits: BitLength,
492
0
    cpu_features: cpu::Features,
493
0
) -> Result<bigint::Elem<M>, error::Unspecified> {
494
0
    let m = &p.modulus.modulus(cpu_features);
495
0
    bigint::elem_exp_consttime(
496
0
        m.alloc_zero(),
497
0
        c,
498
0
        &p.oneRRR,
499
0
        &p.exponent,
500
0
        m,
501
0
        other_prime_len_bits,
502
0
    )
503
0
    .map_err(error::erase::<LimbSliceError>)
504
0
}
Unexecuted instantiation: ring::rsa::keypair::elem_exp_consttime::<ring::rsa::keypair::P>
Unexecuted instantiation: ring::rsa::keypair::elem_exp_consttime::<ring::rsa::keypair::Q>
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
509
enum P {}
510
511
enum Q {}
512
513
enum D {}
514
515
impl 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
0
    pub fn sign(
534
0
        &self,
535
0
        padding_alg: &'static dyn RsaEncoding,
536
0
        rng: &dyn rand::SecureRandom,
537
0
        msg: &[u8],
538
0
        signature: &mut [u8],
539
0
    ) -> Result<(), error::Unspecified> {
540
0
        let cpu_features = cpu::features();
541
0
542
0
        if signature.len() != self.public().modulus_len() {
543
0
            return Err(error::Unspecified);
544
0
        }
545
0
546
0
        let m_hash = digest::digest(padding_alg.digest_alg(), msg);
547
0
548
0
        // Use the output buffer as the scratch space for the signature to
549
0
        // reduce the required stack space.
550
0
        padding::encode(
551
0
            padding_alg,
552
0
            m_hash,
553
0
            signature,
554
0
            self.public().inner().n().len_bits(),
555
0
            rng,
556
0
        )?;
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
0
        let m = self.private_exponentiate(signature, cpu_features)?;
563
564
        // Step 3.
565
0
        m.fill_be_bytes(signature);
566
0
567
0
        Ok(())
568
0
    }
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
0
    fn private_exponentiate(
578
0
        &self,
579
0
        base: &[u8],
580
0
        cpu_features: cpu::Features,
581
0
    ) -> Result<bigint::Elem<N>, error::Unspecified> {
582
0
        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
0
        let n = &self.public.inner().n().value(cpu_features);
588
0
        let n_one = self.public.inner().n().oneRR();
589
590
        // Step 1. The value zero is also rejected.
591
0
        let base = bigint::Elem::from_be_bytes_padded(untrusted::Input::from(base), n)?;
592
593
        // Step 2
594
0
        let c = base;
595
0
596
0
        // Step 2.b.i.
597
0
        let q_bits = self.q.modulus.len_bits();
598
0
        let m_1 = elem_exp_consttime(&c, &self.p, q_bits, cpu_features)?;
599
0
        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
0
        let h = {
605
0
            let p = &self.p.modulus.modulus(cpu_features);
606
0
            let m_2 = bigint::elem_reduced_once(p.alloc_zero(), &m_2, p, q_bits);
607
0
            let m_1_minus_m_2 = bigint::elem_sub(m_1, &m_2, p);
608
0
            bigint::elem_mul(&self.qInv, m_1_minus_m_2, p)
609
0
        };
610
0
611
0
        // Step 2.b.iv. The reduction in the modular multiplication isn't
612
0
        // necessary because `h < p` and `p * q == n` implies `h * q < n`.
613
0
        // Modular arithmetic is used simply to avoid implementing
614
0
        // non-modular arithmetic.
615
0
        let p_bits = self.p.modulus.len_bits();
616
0
        let h = bigint::elem_widen(n.alloc_zero(), h, n, p_bits)?;
617
0
        let q_mod_n = self.q.modulus.to_elem(n)?;
618
0
        let q_mod_n = bigint::elem_mul(n_one, q_mod_n, n);
619
0
        let q_times_h = bigint::elem_mul(&q_mod_n, h, n);
620
0
        let m_2 = bigint::elem_widen(n.alloc_zero(), m_2, n, q_bits)?;
621
0
        let m = bigint::elem_add(m_2, q_times_h, n);
622
0
623
0
        // Step 2.b.v isn't needed since there are only two primes.
624
0
625
0
        // Verify the result to protect against fault attacks as described
626
0
        // in "On the Importance of Checking Cryptographic Protocols for
627
0
        // Faults" by Dan Boneh, Richard A. DeMillo, and Richard J. Lipton.
628
0
        // This check is cheap assuming `e` is small, which is ensured during
629
0
        // `KeyPair` construction. Note that this is the only validation of `e`
630
0
        // that is done other than basic checks on its size, oddness, and
631
0
        // minimum value, since the relationship of `e` to `d`, `p`, and `q` is
632
0
        // not verified during `KeyPair` construction.
633
0
        {
634
0
            let verify = n.alloc_zero();
635
0
            let verify = self
636
0
                .public
637
0
                .inner()
638
0
                .exponentiate_elem(verify, &m, cpu_features);
639
0
            bigint::elem_verify_equal_consttime(&verify, &c)?;
640
        }
641
642
        // Step 3 will be done by the caller.
643
644
0
        Ok(m)
645
0
    }
646
}
647
648
#[cfg(test)]
649
mod 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
}