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 //! ECDSA Signatures using the P-256 and P-384 curves.
16 
17 use super::digest_scalar::digest_scalar;
18 use crate::{
19     arithmetic::montgomery::*,
20     cpu, digest,
21     ec::{
22         self,
23         suite_b::{ops::*, private_key},
24     },
25     error,
26     io::der,
27     limb, pkcs8, rand, sealed, signature,
28 };
29 /// An ECDSA signing algorithm.
30 pub struct EcdsaSigningAlgorithm {
31     curve: &'static ec::Curve,
32     private_scalar_ops: &'static PrivateScalarOps,
33     private_key_ops: &'static PrivateKeyOps,
34     digest_alg: &'static digest::Algorithm,
35     pkcs8_template: &'static pkcs8::Template,
36     format_rs: fn(ops: &'static ScalarOps, r: &Scalar, s: &Scalar, out: &mut [u8]) -> usize,
37     id: AlgorithmID,
38 }
39 
40 #[derive(Debug, Eq, PartialEq)]
41 enum AlgorithmID {
42     ECDSA_P256_SHA256_FIXED_SIGNING,
43     ECDSA_P384_SHA384_FIXED_SIGNING,
44     ECDSA_P256_SHA256_ASN1_SIGNING,
45     ECDSA_P384_SHA384_ASN1_SIGNING,
46 }
47 
48 derive_debug_via_id!(EcdsaSigningAlgorithm);
49 
50 impl PartialEq for EcdsaSigningAlgorithm {
eq(&self, other: &Self) -> bool51     fn eq(&self, other: &Self) -> bool {
52         self.id == other.id
53     }
54 }
55 
56 impl Eq for EcdsaSigningAlgorithm {}
57 
58 impl sealed::Sealed for EcdsaSigningAlgorithm {}
59 
60 /// An ECDSA key pair, used for signing.
61 pub struct EcdsaKeyPair {
62     d: Scalar<R>,
63     nonce_key: NonceRandomKey,
64     alg: &'static EcdsaSigningAlgorithm,
65     public_key: PublicKey,
66 }
67 
68 derive_debug_via_field!(EcdsaKeyPair, stringify!(EcdsaKeyPair), public_key);
69 
70 impl EcdsaKeyPair {
71     /// Generates a new key pair and returns the key pair serialized as a
72     /// PKCS#8 document.
73     ///
74     /// The PKCS#8 document will be a v1 `OneAsymmetricKey` with the public key
75     /// included in the `ECPrivateKey` structure, as described in
76     /// [RFC 5958 Section 2] and [RFC 5915]. The `ECPrivateKey` structure will
77     /// not have a `parameters` field so the generated key is compatible with
78     /// PKCS#11.
79     ///
80     /// [RFC 5915]: https://tools.ietf.org/html/rfc5915
81     /// [RFC 5958 Section 2]: https://tools.ietf.org/html/rfc5958#section-2
generate_pkcs8( alg: &'static EcdsaSigningAlgorithm, rng: &dyn rand::SecureRandom, ) -> Result<pkcs8::Document, error::Unspecified>82     pub fn generate_pkcs8(
83         alg: &'static EcdsaSigningAlgorithm,
84         rng: &dyn rand::SecureRandom,
85     ) -> Result<pkcs8::Document, error::Unspecified> {
86         let private_key = ec::Seed::generate(alg.curve, rng, cpu::features())?;
87         let public_key = private_key.compute_public_key()?;
88         Ok(pkcs8::wrap_key(
89             alg.pkcs8_template,
90             private_key.bytes_less_safe(),
91             public_key.as_ref(),
92         ))
93     }
94 
95     /// Constructs an ECDSA key pair by parsing an unencrypted PKCS#8 v1
96     /// id-ecPublicKey `ECPrivateKey` key.
97     ///
98     /// The input must be in PKCS#8 v1 format. It must contain the public key in
99     /// the `ECPrivateKey` structure; `from_pkcs8()` will verify that the public
100     /// key and the private key are consistent with each other. The algorithm
101     /// identifier must identify the curve by name; it must not use an
102     /// "explicit" encoding of the curve. The `parameters` field of the
103     /// `ECPrivateKey`, if present, must be the same named curve that is in the
104     /// algorithm identifier in the PKCS#8 header.
from_pkcs8( alg: &'static EcdsaSigningAlgorithm, pkcs8: &[u8], rng: &dyn rand::SecureRandom, ) -> Result<Self, error::KeyRejected>105     pub fn from_pkcs8(
106         alg: &'static EcdsaSigningAlgorithm,
107         pkcs8: &[u8],
108         rng: &dyn rand::SecureRandom,
109     ) -> Result<Self, error::KeyRejected> {
110         let key_pair = ec::suite_b::key_pair_from_pkcs8(
111             alg.curve,
112             alg.pkcs8_template,
113             untrusted::Input::from(pkcs8),
114             cpu::features(),
115         )?;
116         Self::new(alg, key_pair, rng)
117     }
118 
119     /// Constructs an ECDSA key pair from the private key and public key bytes
120     ///
121     /// The private key must encoded as a big-endian fixed-length integer. For
122     /// example, a P-256 private key must be 32 bytes prefixed with leading
123     /// zeros as needed.
124     ///
125     /// The public key is encoding in uncompressed form using the
126     /// Octet-String-to-Elliptic-Curve-Point algorithm in
127     /// [SEC 1: Elliptic Curve Cryptography, Version 2.0].
128     ///
129     /// This is intended for use by code that deserializes key pairs. It is
130     /// recommended to use `EcdsaKeyPair::from_pkcs8()` (with a PKCS#8-encoded
131     /// key) instead.
132     ///
133     /// [SEC 1: Elliptic Curve Cryptography, Version 2.0]:
134     ///     http://www.secg.org/sec1-v2.pdf
from_private_key_and_public_key( alg: &'static EcdsaSigningAlgorithm, private_key: &[u8], public_key: &[u8], rng: &dyn rand::SecureRandom, ) -> Result<Self, error::KeyRejected>135     pub fn from_private_key_and_public_key(
136         alg: &'static EcdsaSigningAlgorithm,
137         private_key: &[u8],
138         public_key: &[u8],
139         rng: &dyn rand::SecureRandom,
140     ) -> Result<Self, error::KeyRejected> {
141         let key_pair = ec::suite_b::key_pair_from_bytes(
142             alg.curve,
143             untrusted::Input::from(private_key),
144             untrusted::Input::from(public_key),
145             cpu::features(),
146         )?;
147         Self::new(alg, key_pair, rng)
148     }
149 
new( alg: &'static EcdsaSigningAlgorithm, key_pair: ec::KeyPair, rng: &dyn rand::SecureRandom, ) -> Result<Self, error::KeyRejected>150     fn new(
151         alg: &'static EcdsaSigningAlgorithm,
152         key_pair: ec::KeyPair,
153         rng: &dyn rand::SecureRandom,
154     ) -> Result<Self, error::KeyRejected> {
155         let (seed, public_key) = key_pair.split();
156         let d = private_key::private_key_as_scalar(alg.private_key_ops, &seed);
157         let d = alg
158             .private_scalar_ops
159             .scalar_ops
160             .scalar_product(&d, &alg.private_scalar_ops.oneRR_mod_n);
161 
162         let nonce_key = NonceRandomKey::new(alg, &seed, rng)?;
163         Ok(Self {
164             d,
165             nonce_key,
166             alg,
167             public_key: PublicKey(public_key),
168         })
169     }
170 
171     /// Returns the signature of the `message` using a random nonce generated by `rng`.
sign( &self, rng: &dyn rand::SecureRandom, message: &[u8], ) -> Result<signature::Signature, error::Unspecified>172     pub fn sign(
173         &self,
174         rng: &dyn rand::SecureRandom,
175         message: &[u8],
176     ) -> Result<signature::Signature, error::Unspecified> {
177         // Step 4 (out of order).
178         let h = digest::digest(self.alg.digest_alg, message);
179 
180         // Incorporate `h` into the nonce to hedge against faulty RNGs. (This
181         // is not an approved random number generator that is mandated in
182         // the spec.)
183         let nonce_rng = NonceRandom {
184             key: &self.nonce_key,
185             message_digest: &h,
186             rng,
187         };
188 
189         self.sign_digest(h, &nonce_rng)
190     }
191 
192     #[cfg(test)]
sign_with_fixed_nonce_during_test( &self, rng: &dyn rand::SecureRandom, message: &[u8], ) -> Result<signature::Signature, error::Unspecified>193     fn sign_with_fixed_nonce_during_test(
194         &self,
195         rng: &dyn rand::SecureRandom,
196         message: &[u8],
197     ) -> Result<signature::Signature, error::Unspecified> {
198         // Step 4 (out of order).
199         let h = digest::digest(self.alg.digest_alg, message);
200 
201         self.sign_digest(h, rng)
202     }
203 
204     /// Returns the signature of message digest `h` using a "random" nonce
205     /// generated by `rng`.
sign_digest( &self, h: digest::Digest, rng: &dyn rand::SecureRandom, ) -> Result<signature::Signature, error::Unspecified>206     fn sign_digest(
207         &self,
208         h: digest::Digest,
209         rng: &dyn rand::SecureRandom,
210     ) -> Result<signature::Signature, error::Unspecified> {
211         // NSA Suite B Implementer's Guide to ECDSA Section 3.4.1: ECDSA
212         // Signature Generation.
213 
214         // NSA Guide Prerequisites:
215         //
216         //     Prior to generating an ECDSA signature, the signatory shall
217         //     obtain:
218         //
219         //     1. an authentic copy of the domain parameters,
220         //     2. a digital signature key pair (d,Q), either generated by a
221         //        method from Appendix A.1, or obtained from a trusted third
222         //        party,
223         //     3. assurance of the validity of the public key Q (see Appendix
224         //        A.3), and
225         //     4. assurance that he/she/it actually possesses the associated
226         //        private key d (see [SP800-89] Section 6).
227         //
228         // The domain parameters are hard-coded into the source code.
229         // `EcdsaKeyPair::generate_pkcs8()` can be used to meet the second
230         // requirement; otherwise, it is up to the user to ensure the key pair
231         // was obtained from a trusted private key. The constructors for
232         // `EcdsaKeyPair` ensure that #3 and #4 are met subject to the caveats
233         // in SP800-89 Section 6.
234 
235         let ops = self.alg.private_scalar_ops;
236         let scalar_ops = ops.scalar_ops;
237         let cops = scalar_ops.common;
238         let private_key_ops = self.alg.private_key_ops;
239 
240         for _ in 0..100 {
241             // XXX: iteration conut?
242             // Step 1.
243             let k = private_key::random_scalar(self.alg.private_key_ops, rng)?;
244             let k_inv = scalar_ops.scalar_inv_to_mont(&k);
245 
246             // Step 2.
247             let r = private_key_ops.point_mul_base(&k);
248 
249             // Step 3.
250             let r = {
251                 let (x, _) = private_key::affine_from_jacobian(private_key_ops, &r)?;
252                 let x = cops.elem_unencoded(&x);
253                 elem_reduced_to_scalar(cops, &x)
254             };
255             if cops.is_zero(&r) {
256                 continue;
257             }
258 
259             // Step 4 is done by the caller.
260 
261             // Step 5.
262             let e = digest_scalar(scalar_ops, h);
263 
264             // Step 6.
265             let s = {
266                 let dr = scalar_ops.scalar_product(&self.d, &r);
267                 let e_plus_dr = scalar_sum(cops, &e, &dr);
268                 scalar_ops.scalar_product(&k_inv, &e_plus_dr)
269             };
270             if cops.is_zero(&s) {
271                 continue;
272             }
273 
274             // Step 7 with encoding.
275             return Ok(signature::Signature::new(|sig_bytes| {
276                 (self.alg.format_rs)(scalar_ops, &r, &s, sig_bytes)
277             }));
278         }
279 
280         Err(error::Unspecified)
281     }
282 }
283 
284 /// Generates an ECDSA nonce in a way that attempts to protect against a faulty
285 /// `SecureRandom`.
286 struct NonceRandom<'a> {
287     key: &'a NonceRandomKey,
288     message_digest: &'a digest::Digest,
289     rng: &'a dyn rand::SecureRandom,
290 }
291 
292 impl core::fmt::Debug for NonceRandom<'_> {
fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result293     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
294         f.debug_struct("NonceRandom").finish()
295     }
296 }
297 
298 impl rand::sealed::SecureRandom for NonceRandom<'_> {
fill_impl(&self, dest: &mut [u8]) -> Result<(), error::Unspecified>299     fn fill_impl(&self, dest: &mut [u8]) -> Result<(), error::Unspecified> {
300         // Use the same digest algorithm that will be used to digest the
301         // message. The digest algorithm's output is exactly the right size;
302         // this is checked below.
303         //
304         // XXX(perf): The single iteration will require two digest block
305         // operations because the amount of data digested is larger than one
306         // block.
307         let digest_alg = self.key.0.algorithm();
308         let mut ctx = digest::Context::new(digest_alg);
309 
310         // Digest the randomized digest of the private key.
311         let key = self.key.0.as_ref();
312         ctx.update(key);
313 
314         // The random value is digested between the key and the message so that
315         // the key and the message are not directly digested in the same digest
316         // block.
317         assert!(key.len() <= digest_alg.block_len() / 2);
318         {
319             let mut rand = [0u8; digest::MAX_BLOCK_LEN];
320             let rand = &mut rand[..digest_alg.block_len() - key.len()];
321             assert!(rand.len() >= dest.len());
322             self.rng.fill(rand)?;
323             ctx.update(rand);
324         }
325 
326         ctx.update(self.message_digest.as_ref());
327 
328         let nonce = ctx.finish();
329 
330         // `copy_from_slice()` panics if the lengths differ, so we don't have
331         // to separately assert that the lengths are the same.
332         dest.copy_from_slice(nonce.as_ref());
333 
334         Ok(())
335     }
336 }
337 
338 impl<'a> sealed::Sealed for NonceRandom<'a> {}
339 
340 struct NonceRandomKey(digest::Digest);
341 
342 impl NonceRandomKey {
new( alg: &EcdsaSigningAlgorithm, seed: &ec::Seed, rng: &dyn rand::SecureRandom, ) -> Result<Self, error::KeyRejected>343     fn new(
344         alg: &EcdsaSigningAlgorithm,
345         seed: &ec::Seed,
346         rng: &dyn rand::SecureRandom,
347     ) -> Result<Self, error::KeyRejected> {
348         let mut rand = [0; digest::MAX_OUTPUT_LEN];
349         let rand = &mut rand[0..alg.curve.elem_scalar_seed_len];
350 
351         // XXX: `KeyRejected` isn't the right way to model  failure of the RNG,
352         // but to fix that we'd need to break the API by changing the result type.
353         // TODO: Fix the API in the next breaking release.
354         rng.fill(rand)
355             .map_err(|error::Unspecified| error::KeyRejected::rng_failed())?;
356 
357         let mut ctx = digest::Context::new(alg.digest_alg);
358         ctx.update(rand);
359         ctx.update(seed.bytes_less_safe());
360         Ok(Self(ctx.finish()))
361     }
362 }
363 
364 impl signature::KeyPair for EcdsaKeyPair {
365     type PublicKey = PublicKey;
366 
public_key(&self) -> &Self::PublicKey367     fn public_key(&self) -> &Self::PublicKey {
368         &self.public_key
369     }
370 }
371 
372 #[derive(Clone, Copy)]
373 pub struct PublicKey(ec::PublicKey);
374 
375 derive_debug_self_as_ref_hex_bytes!(PublicKey);
376 
377 impl AsRef<[u8]> for PublicKey {
as_ref(&self) -> &[u8]378     fn as_ref(&self) -> &[u8] {
379         self.0.as_ref()
380     }
381 }
382 
format_rs_fixed(ops: &'static ScalarOps, r: &Scalar, s: &Scalar, out: &mut [u8]) -> usize383 fn format_rs_fixed(ops: &'static ScalarOps, r: &Scalar, s: &Scalar, out: &mut [u8]) -> usize {
384     let scalar_len = ops.scalar_bytes_len();
385 
386     let (r_out, rest) = out.split_at_mut(scalar_len);
387     limb::big_endian_from_limbs(&r.limbs[..ops.common.num_limbs], r_out);
388 
389     let (s_out, _) = rest.split_at_mut(scalar_len);
390     limb::big_endian_from_limbs(&s.limbs[..ops.common.num_limbs], s_out);
391 
392     2 * scalar_len
393 }
394 
format_rs_asn1(ops: &'static ScalarOps, r: &Scalar, s: &Scalar, out: &mut [u8]) -> usize395 fn format_rs_asn1(ops: &'static ScalarOps, r: &Scalar, s: &Scalar, out: &mut [u8]) -> usize {
396     // This assumes `a` is not zero since neither `r` or `s` is allowed to be
397     // zero.
398     fn format_integer_tlv(ops: &ScalarOps, a: &Scalar, out: &mut [u8]) -> usize {
399         let mut fixed = [0u8; ec::SCALAR_MAX_BYTES + 1];
400         let fixed = &mut fixed[..(ops.scalar_bytes_len() + 1)];
401         limb::big_endian_from_limbs(&a.limbs[..ops.common.num_limbs], &mut fixed[1..]);
402 
403         // Since `a_fixed_out` is an extra byte long, it is guaranteed to start
404         // with a zero.
405         debug_assert_eq!(fixed[0], 0);
406 
407         // There must be at least one non-zero byte since `a` isn't zero.
408         let first_index = fixed.iter().position(|b| *b != 0).unwrap();
409 
410         // If the first byte has its high bit set, it needs to be prefixed with 0x00.
411         let first_index = if fixed[first_index] & 0x80 != 0 {
412             first_index - 1
413         } else {
414             first_index
415         };
416         let value = &fixed[first_index..];
417 
418         out[0] = der::Tag::Integer as u8;
419 
420         // Lengths less than 128 are encoded in one byte.
421         assert!(value.len() < 128);
422         out[1] = value.len() as u8;
423 
424         out[2..][..value.len()].copy_from_slice(value);
425 
426         2 + value.len()
427     }
428 
429     out[0] = der::Tag::Sequence as u8;
430     let r_tlv_len = format_integer_tlv(ops, r, &mut out[2..]);
431     let s_tlv_len = format_integer_tlv(ops, s, &mut out[2..][r_tlv_len..]);
432 
433     // Lengths less than 128 are encoded in one byte.
434     let value_len = r_tlv_len + s_tlv_len;
435     assert!(value_len < 128);
436     out[1] = value_len as u8;
437 
438     2 + value_len
439 }
440 
441 /// Signing of fixed-length (PKCS#11 style) ECDSA signatures using the
442 /// P-256 curve and SHA-256.
443 ///
444 /// See "`ECDSA_*_FIXED` Details" in `ring::signature`'s module-level
445 /// documentation for more details.
446 pub static ECDSA_P256_SHA256_FIXED_SIGNING: EcdsaSigningAlgorithm = EcdsaSigningAlgorithm {
447     curve: &ec::suite_b::curve::P256,
448     private_scalar_ops: &p256::PRIVATE_SCALAR_OPS,
449     private_key_ops: &p256::PRIVATE_KEY_OPS,
450     digest_alg: &digest::SHA256,
451     pkcs8_template: &EC_PUBLIC_KEY_P256_PKCS8_V1_TEMPLATE,
452     format_rs: format_rs_fixed,
453     id: AlgorithmID::ECDSA_P256_SHA256_FIXED_SIGNING,
454 };
455 
456 /// Signing of fixed-length (PKCS#11 style) ECDSA signatures using the
457 /// P-384 curve and SHA-384.
458 ///
459 /// See "`ECDSA_*_FIXED` Details" in `ring::signature`'s module-level
460 /// documentation for more details.
461 pub static ECDSA_P384_SHA384_FIXED_SIGNING: EcdsaSigningAlgorithm = EcdsaSigningAlgorithm {
462     curve: &ec::suite_b::curve::P384,
463     private_scalar_ops: &p384::PRIVATE_SCALAR_OPS,
464     private_key_ops: &p384::PRIVATE_KEY_OPS,
465     digest_alg: &digest::SHA384,
466     pkcs8_template: &EC_PUBLIC_KEY_P384_PKCS8_V1_TEMPLATE,
467     format_rs: format_rs_fixed,
468     id: AlgorithmID::ECDSA_P384_SHA384_FIXED_SIGNING,
469 };
470 
471 /// Signing of ASN.1 DER-encoded ECDSA signatures using the P-256 curve and
472 /// SHA-256.
473 ///
474 /// See "`ECDSA_*_ASN1` Details" in `ring::signature`'s module-level
475 /// documentation for more details.
476 pub static ECDSA_P256_SHA256_ASN1_SIGNING: EcdsaSigningAlgorithm = EcdsaSigningAlgorithm {
477     curve: &ec::suite_b::curve::P256,
478     private_scalar_ops: &p256::PRIVATE_SCALAR_OPS,
479     private_key_ops: &p256::PRIVATE_KEY_OPS,
480     digest_alg: &digest::SHA256,
481     pkcs8_template: &EC_PUBLIC_KEY_P256_PKCS8_V1_TEMPLATE,
482     format_rs: format_rs_asn1,
483     id: AlgorithmID::ECDSA_P256_SHA256_ASN1_SIGNING,
484 };
485 
486 /// Signing of ASN.1 DER-encoded ECDSA signatures using the P-384 curve and
487 /// SHA-384.
488 ///
489 /// See "`ECDSA_*_ASN1` Details" in `ring::signature`'s module-level
490 /// documentation for more details.
491 pub static ECDSA_P384_SHA384_ASN1_SIGNING: EcdsaSigningAlgorithm = EcdsaSigningAlgorithm {
492     curve: &ec::suite_b::curve::P384,
493     private_scalar_ops: &p384::PRIVATE_SCALAR_OPS,
494     private_key_ops: &p384::PRIVATE_KEY_OPS,
495     digest_alg: &digest::SHA384,
496     pkcs8_template: &EC_PUBLIC_KEY_P384_PKCS8_V1_TEMPLATE,
497     format_rs: format_rs_asn1,
498     id: AlgorithmID::ECDSA_P384_SHA384_ASN1_SIGNING,
499 };
500 
501 static EC_PUBLIC_KEY_P256_PKCS8_V1_TEMPLATE: pkcs8::Template = pkcs8::Template {
502     bytes: include_bytes!("ecPublicKey_p256_pkcs8_v1_template.der"),
503     alg_id_range: core::ops::Range { start: 8, end: 27 },
504     curve_id_index: 9,
505     private_key_index: 0x24,
506 };
507 
508 static EC_PUBLIC_KEY_P384_PKCS8_V1_TEMPLATE: pkcs8::Template = pkcs8::Template {
509     bytes: include_bytes!("ecPublicKey_p384_pkcs8_v1_template.der"),
510     alg_id_range: core::ops::Range { start: 8, end: 24 },
511     curve_id_index: 9,
512     private_key_index: 0x23,
513 };
514 
515 #[cfg(test)]
516 mod tests {
517     use crate::{rand, signature, test};
518 
519     #[test]
signature_ecdsa_sign_fixed_test()520     fn signature_ecdsa_sign_fixed_test() {
521         let rng = rand::SystemRandom::new();
522 
523         test::run(
524             test_file!("ecdsa_sign_fixed_tests.txt"),
525             |section, test_case| {
526                 assert_eq!(section, "");
527 
528                 let curve_name = test_case.consume_string("Curve");
529                 let digest_name = test_case.consume_string("Digest");
530                 let msg = test_case.consume_bytes("Msg");
531                 let d = test_case.consume_bytes("d");
532                 let q = test_case.consume_bytes("Q");
533                 let k = test_case.consume_bytes("k");
534 
535                 let expected_result = test_case.consume_bytes("Sig");
536 
537                 let alg = match (curve_name.as_str(), digest_name.as_str()) {
538                     ("P-256", "SHA256") => &signature::ECDSA_P256_SHA256_FIXED_SIGNING,
539                     ("P-384", "SHA384") => &signature::ECDSA_P384_SHA384_FIXED_SIGNING,
540                     _ => {
541                         panic!("Unsupported curve+digest: {}+{}", curve_name, digest_name);
542                     }
543                 };
544 
545                 let private_key =
546                     signature::EcdsaKeyPair::from_private_key_and_public_key(alg, &d, &q, &rng)
547                         .unwrap();
548                 let rng = test::rand::FixedSliceRandom { bytes: &k };
549 
550                 let actual_result = private_key
551                     .sign_with_fixed_nonce_during_test(&rng, &msg)
552                     .unwrap();
553 
554                 assert_eq!(actual_result.as_ref(), &expected_result[..]);
555 
556                 Ok(())
557             },
558         );
559     }
560 
561     #[test]
signature_ecdsa_sign_asn1_test()562     fn signature_ecdsa_sign_asn1_test() {
563         let rng = rand::SystemRandom::new();
564 
565         test::run(
566             test_file!("ecdsa_sign_asn1_tests.txt"),
567             |section, test_case| {
568                 assert_eq!(section, "");
569 
570                 let curve_name = test_case.consume_string("Curve");
571                 let digest_name = test_case.consume_string("Digest");
572                 let msg = test_case.consume_bytes("Msg");
573                 let d = test_case.consume_bytes("d");
574                 let q = test_case.consume_bytes("Q");
575                 let k = test_case.consume_bytes("k");
576 
577                 let expected_result = test_case.consume_bytes("Sig");
578 
579                 let alg = match (curve_name.as_str(), digest_name.as_str()) {
580                     ("P-256", "SHA256") => &signature::ECDSA_P256_SHA256_ASN1_SIGNING,
581                     ("P-384", "SHA384") => &signature::ECDSA_P384_SHA384_ASN1_SIGNING,
582                     _ => {
583                         panic!("Unsupported curve+digest: {}+{}", curve_name, digest_name);
584                     }
585                 };
586 
587                 let private_key =
588                     signature::EcdsaKeyPair::from_private_key_and_public_key(alg, &d, &q, &rng)
589                         .unwrap();
590                 let rng = test::rand::FixedSliceRandom { bytes: &k };
591 
592                 let actual_result = private_key
593                     .sign_with_fixed_nonce_during_test(&rng, &msg)
594                     .unwrap();
595 
596                 assert_eq!(actual_result.as_ref(), &expected_result[..]);
597 
598                 Ok(())
599             },
600         );
601     }
602 }
603