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], ) -> Result<Self, error::KeyRejected>105     pub fn from_pkcs8(
106         alg: &'static EcdsaSigningAlgorithm,
107         pkcs8: &[u8],
108     ) -> Result<Self, error::KeyRejected> {
109         let key_pair = ec::suite_b::key_pair_from_pkcs8(
110             alg.curve,
111             alg.pkcs8_template,
112             untrusted::Input::from(pkcs8),
113             cpu::features(),
114         )?;
115         let rng = rand::SystemRandom::new(); // TODO: make this a parameter.
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], ) -> 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     ) -> Result<Self, error::KeyRejected> {
140         let key_pair = ec::suite_b::key_pair_from_bytes(
141             alg.curve,
142             untrusted::Input::from(private_key),
143             untrusted::Input::from(public_key),
144             cpu::features(),
145         )?;
146         let rng = rand::SystemRandom::new(); // TODO: make this a parameter.
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     /// Deprecated. Returns the signature of the `message` using a random nonce
172     /// generated by `rng`.
sign( &self, rng: &dyn rand::SecureRandom, message: &[u8], ) -> Result<signature::Signature, error::Unspecified>173     pub fn sign(
174         &self,
175         rng: &dyn rand::SecureRandom,
176         message: &[u8],
177     ) -> Result<signature::Signature, error::Unspecified> {
178         // Step 4 (out of order).
179         let h = digest::digest(self.alg.digest_alg, message);
180 
181         // Incorporate `h` into the nonce to hedge against faulty RNGs. (This
182         // is not an approved random number generator that is mandated in
183         // the spec.)
184         let nonce_rng = NonceRandom {
185             key: &self.nonce_key,
186             message_digest: &h,
187             rng,
188         };
189 
190         self.sign_digest(h, &nonce_rng)
191     }
192 
193     #[cfg(test)]
sign_with_fixed_nonce_during_test( &self, rng: &dyn rand::SecureRandom, message: &[u8], ) -> Result<signature::Signature, error::Unspecified>194     fn sign_with_fixed_nonce_during_test(
195         &self,
196         rng: &dyn rand::SecureRandom,
197         message: &[u8],
198     ) -> Result<signature::Signature, error::Unspecified> {
199         // Step 4 (out of order).
200         let h = digest::digest(self.alg.digest_alg, message);
201 
202         self.sign_digest(h, rng)
203     }
204 
205     /// Returns the signature of message digest `h` using a "random" nonce
206     /// generated by `rng`.
sign_digest( &self, h: digest::Digest, rng: &dyn rand::SecureRandom, ) -> Result<signature::Signature, error::Unspecified>207     fn sign_digest(
208         &self,
209         h: digest::Digest,
210         rng: &dyn rand::SecureRandom,
211     ) -> Result<signature::Signature, error::Unspecified> {
212         // NSA Suite B Implementer's Guide to ECDSA Section 3.4.1: ECDSA
213         // Signature Generation.
214 
215         // NSA Guide Prerequisites:
216         //
217         //     Prior to generating an ECDSA signature, the signatory shall
218         //     obtain:
219         //
220         //     1. an authentic copy of the domain parameters,
221         //     2. a digital signature key pair (d,Q), either generated by a
222         //        method from Appendix A.1, or obtained from a trusted third
223         //        party,
224         //     3. assurance of the validity of the public key Q (see Appendix
225         //        A.3), and
226         //     4. assurance that he/she/it actually possesses the associated
227         //        private key d (see [SP800-89] Section 6).
228         //
229         // The domain parameters are hard-coded into the source code.
230         // `EcdsaKeyPair::generate_pkcs8()` can be used to meet the second
231         // requirement; otherwise, it is up to the user to ensure the key pair
232         // was obtained from a trusted private key. The constructors for
233         // `EcdsaKeyPair` ensure that #3 and #4 are met subject to the caveats
234         // in SP800-89 Section 6.
235 
236         let ops = self.alg.private_scalar_ops;
237         let scalar_ops = ops.scalar_ops;
238         let cops = scalar_ops.common;
239         let private_key_ops = self.alg.private_key_ops;
240 
241         for _ in 0..100 {
242             // XXX: iteration conut?
243             // Step 1.
244             let k = private_key::random_scalar(self.alg.private_key_ops, rng)?;
245             let k_inv = scalar_ops.scalar_inv_to_mont(&k);
246 
247             // Step 2.
248             let r = private_key_ops.point_mul_base(&k);
249 
250             // Step 3.
251             let r = {
252                 let (x, _) = private_key::affine_from_jacobian(private_key_ops, &r)?;
253                 let x = cops.elem_unencoded(&x);
254                 elem_reduced_to_scalar(cops, &x)
255             };
256             if cops.is_zero(&r) {
257                 continue;
258             }
259 
260             // Step 4 is done by the caller.
261 
262             // Step 5.
263             let e = digest_scalar(scalar_ops, h);
264 
265             // Step 6.
266             let s = {
267                 let dr = scalar_ops.scalar_product(&self.d, &r);
268                 let e_plus_dr = scalar_sum(cops, &e, &dr);
269                 scalar_ops.scalar_product(&k_inv, &e_plus_dr)
270             };
271             if cops.is_zero(&s) {
272                 continue;
273             }
274 
275             // Step 7 with encoding.
276             return Ok(signature::Signature::new(|sig_bytes| {
277                 (self.alg.format_rs)(scalar_ops, &r, &s, sig_bytes)
278             }));
279         }
280 
281         Err(error::Unspecified)
282     }
283 }
284 
285 /// Generates an ECDSA nonce in a way that attempts to protect against a faulty
286 /// `SecureRandom`.
287 struct NonceRandom<'a> {
288     key: &'a NonceRandomKey,
289     message_digest: &'a digest::Digest,
290     rng: &'a dyn rand::SecureRandom,
291 }
292 
293 impl core::fmt::Debug for NonceRandom<'_> {
fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result294     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
295         f.debug_struct("NonceRandom").finish()
296     }
297 }
298 
299 impl rand::sealed::SecureRandom for NonceRandom<'_> {
fill_impl(&self, dest: &mut [u8]) -> Result<(), error::Unspecified>300     fn fill_impl(&self, dest: &mut [u8]) -> Result<(), error::Unspecified> {
301         // Use the same digest algorithm that will be used to digest the
302         // message. The digest algorithm's output is exactly the right size;
303         // this is checked below.
304         //
305         // XXX(perf): The single iteration will require two digest block
306         // operations because the amount of data digested is larger than one
307         // block.
308         let digest_alg = self.key.0.algorithm();
309         let mut ctx = digest::Context::new(digest_alg);
310 
311         // Digest the randomized digest of the private key.
312         let key = self.key.0.as_ref();
313         ctx.update(key);
314 
315         // The random value is digested between the key and the message so that
316         // the key and the message are not directly digested in the same digest
317         // block.
318         assert!(key.len() <= digest_alg.block_len / 2);
319         {
320             let mut rand = [0u8; digest::MAX_BLOCK_LEN];
321             let rand = &mut rand[..digest_alg.block_len - key.len()];
322             assert!(rand.len() >= dest.len());
323             self.rng.fill(rand)?;
324             ctx.update(rand);
325         }
326 
327         ctx.update(self.message_digest.as_ref());
328 
329         let nonce = ctx.finish();
330 
331         // `copy_from_slice()` panics if the lengths differ, so we don't have
332         // to separately assert that the lengths are the same.
333         dest.copy_from_slice(nonce.as_ref());
334 
335         Ok(())
336     }
337 }
338 
339 impl<'a> sealed::Sealed for NonceRandom<'a> {}
340 
341 struct NonceRandomKey(digest::Digest);
342 
343 impl NonceRandomKey {
new( alg: &EcdsaSigningAlgorithm, seed: &ec::Seed, rng: &dyn rand::SecureRandom, ) -> Result<Self, error::KeyRejected>344     fn new(
345         alg: &EcdsaSigningAlgorithm,
346         seed: &ec::Seed,
347         rng: &dyn rand::SecureRandom,
348     ) -> Result<Self, error::KeyRejected> {
349         let mut rand = [0; digest::MAX_OUTPUT_LEN];
350         let rand = &mut rand[0..alg.curve.elem_scalar_seed_len];
351 
352         // XXX: `KeyRejected` isn't the right way to model  failure of the RNG,
353         // but to fix that we'd need to break the API by changing the result type.
354         // TODO: Fix the API in the next breaking release.
355         rng.fill(rand)
356             .map_err(|error::Unspecified| error::KeyRejected::rng_failed())?;
357 
358         let mut ctx = digest::Context::new(alg.digest_alg);
359         ctx.update(rand);
360         ctx.update(seed.bytes_less_safe());
361         Ok(NonceRandomKey(ctx.finish()))
362     }
363 }
364 
365 impl signature::KeyPair for EcdsaKeyPair {
366     type PublicKey = PublicKey;
367 
public_key(&self) -> &Self::PublicKey368     fn public_key(&self) -> &Self::PublicKey {
369         &self.public_key
370     }
371 }
372 
373 #[derive(Clone, Copy)]
374 pub struct PublicKey(ec::PublicKey);
375 
376 derive_debug_self_as_ref_hex_bytes!(PublicKey);
377 
378 impl AsRef<[u8]> for PublicKey {
as_ref(&self) -> &[u8]379     fn as_ref(&self) -> &[u8] {
380         self.0.as_ref()
381     }
382 }
383 
format_rs_fixed(ops: &'static ScalarOps, r: &Scalar, s: &Scalar, out: &mut [u8]) -> usize384 fn format_rs_fixed(ops: &'static ScalarOps, r: &Scalar, s: &Scalar, out: &mut [u8]) -> usize {
385     let scalar_len = ops.scalar_bytes_len();
386 
387     let (r_out, rest) = out.split_at_mut(scalar_len);
388     limb::big_endian_from_limbs(&r.limbs[..ops.common.num_limbs], r_out);
389 
390     let (s_out, _) = rest.split_at_mut(scalar_len);
391     limb::big_endian_from_limbs(&s.limbs[..ops.common.num_limbs], s_out);
392 
393     2 * scalar_len
394 }
395 
format_rs_asn1(ops: &'static ScalarOps, r: &Scalar, s: &Scalar, out: &mut [u8]) -> usize396 fn format_rs_asn1(ops: &'static ScalarOps, r: &Scalar, s: &Scalar, out: &mut [u8]) -> usize {
397     // This assumes `a` is not zero since neither `r` or `s` is allowed to be
398     // zero.
399     fn format_integer_tlv(ops: &ScalarOps, a: &Scalar, out: &mut [u8]) -> usize {
400         let mut fixed = [0u8; ec::SCALAR_MAX_BYTES + 1];
401         let fixed = &mut fixed[..(ops.scalar_bytes_len() + 1)];
402         limb::big_endian_from_limbs(&a.limbs[..ops.common.num_limbs], &mut fixed[1..]);
403 
404         // Since `a_fixed_out` is an extra byte long, it is guaranteed to start
405         // with a zero.
406         debug_assert_eq!(fixed[0], 0);
407 
408         // There must be at least one non-zero byte since `a` isn't zero.
409         let first_index = fixed.iter().position(|b| *b != 0).unwrap();
410 
411         // If the first byte has its high bit set, it needs to be prefixed with 0x00.
412         let first_index = if fixed[first_index] & 0x80 != 0 {
413             first_index - 1
414         } else {
415             first_index
416         };
417         let value = &fixed[first_index..];
418 
419         out[0] = der::Tag::Integer as u8;
420 
421         // Lengths less than 128 are encoded in one byte.
422         assert!(value.len() < 128);
423         out[1] = value.len() as u8;
424 
425         out[2..][..value.len()].copy_from_slice(&value);
426 
427         2 + value.len()
428     }
429 
430     out[0] = der::Tag::Sequence as u8;
431     let r_tlv_len = format_integer_tlv(ops, r, &mut out[2..]);
432     let s_tlv_len = format_integer_tlv(ops, s, &mut out[2..][r_tlv_len..]);
433 
434     // Lengths less than 128 are encoded in one byte.
435     let value_len = r_tlv_len + s_tlv_len;
436     assert!(value_len < 128);
437     out[1] = value_len as u8;
438 
439     2 + value_len
440 }
441 
442 /// Signing of fixed-length (PKCS#11 style) ECDSA signatures using the
443 /// P-256 curve and SHA-256.
444 ///
445 /// See "`ECDSA_*_FIXED` Details" in `ring::signature`'s module-level
446 /// documentation for more details.
447 pub static ECDSA_P256_SHA256_FIXED_SIGNING: EcdsaSigningAlgorithm = EcdsaSigningAlgorithm {
448     curve: &ec::suite_b::curve::P256,
449     private_scalar_ops: &p256::PRIVATE_SCALAR_OPS,
450     private_key_ops: &p256::PRIVATE_KEY_OPS,
451     digest_alg: &digest::SHA256,
452     pkcs8_template: &EC_PUBLIC_KEY_P256_PKCS8_V1_TEMPLATE,
453     format_rs: format_rs_fixed,
454     id: AlgorithmID::ECDSA_P256_SHA256_FIXED_SIGNING,
455 };
456 
457 /// Signing of fixed-length (PKCS#11 style) ECDSA signatures using the
458 /// P-384 curve and SHA-384.
459 ///
460 /// See "`ECDSA_*_FIXED` Details" in `ring::signature`'s module-level
461 /// documentation for more details.
462 pub static ECDSA_P384_SHA384_FIXED_SIGNING: EcdsaSigningAlgorithm = EcdsaSigningAlgorithm {
463     curve: &ec::suite_b::curve::P384,
464     private_scalar_ops: &p384::PRIVATE_SCALAR_OPS,
465     private_key_ops: &p384::PRIVATE_KEY_OPS,
466     digest_alg: &digest::SHA384,
467     pkcs8_template: &EC_PUBLIC_KEY_P384_PKCS8_V1_TEMPLATE,
468     format_rs: format_rs_fixed,
469     id: AlgorithmID::ECDSA_P384_SHA384_FIXED_SIGNING,
470 };
471 
472 /// Signing of ASN.1 DER-encoded ECDSA signatures using the P-256 curve and
473 /// SHA-256.
474 ///
475 /// See "`ECDSA_*_ASN1` Details" in `ring::signature`'s module-level
476 /// documentation for more details.
477 pub static ECDSA_P256_SHA256_ASN1_SIGNING: EcdsaSigningAlgorithm = EcdsaSigningAlgorithm {
478     curve: &ec::suite_b::curve::P256,
479     private_scalar_ops: &p256::PRIVATE_SCALAR_OPS,
480     private_key_ops: &p256::PRIVATE_KEY_OPS,
481     digest_alg: &digest::SHA256,
482     pkcs8_template: &EC_PUBLIC_KEY_P256_PKCS8_V1_TEMPLATE,
483     format_rs: format_rs_asn1,
484     id: AlgorithmID::ECDSA_P256_SHA256_ASN1_SIGNING,
485 };
486 
487 /// Signing of ASN.1 DER-encoded ECDSA signatures using the P-384 curve and
488 /// SHA-384.
489 ///
490 /// See "`ECDSA_*_ASN1` Details" in `ring::signature`'s module-level
491 /// documentation for more details.
492 pub static ECDSA_P384_SHA384_ASN1_SIGNING: EcdsaSigningAlgorithm = EcdsaSigningAlgorithm {
493     curve: &ec::suite_b::curve::P384,
494     private_scalar_ops: &p384::PRIVATE_SCALAR_OPS,
495     private_key_ops: &p384::PRIVATE_KEY_OPS,
496     digest_alg: &digest::SHA384,
497     pkcs8_template: &EC_PUBLIC_KEY_P384_PKCS8_V1_TEMPLATE,
498     format_rs: format_rs_asn1,
499     id: AlgorithmID::ECDSA_P384_SHA384_ASN1_SIGNING,
500 };
501 
502 static EC_PUBLIC_KEY_P256_PKCS8_V1_TEMPLATE: pkcs8::Template = pkcs8::Template {
503     bytes: include_bytes!("ecPublicKey_p256_pkcs8_v1_template.der"),
504     alg_id_range: core::ops::Range { start: 8, end: 27 },
505     curve_id_index: 9,
506     private_key_index: 0x24,
507 };
508 
509 static EC_PUBLIC_KEY_P384_PKCS8_V1_TEMPLATE: pkcs8::Template = pkcs8::Template {
510     bytes: include_bytes!("ecPublicKey_p384_pkcs8_v1_template.der"),
511     alg_id_range: core::ops::Range { start: 8, end: 24 },
512     curve_id_index: 9,
513     private_key_index: 0x23,
514 };
515 
516 #[cfg(test)]
517 mod tests {
518     use crate::{signature, test};
519 
520     #[test]
signature_ecdsa_sign_fixed_test()521     fn signature_ecdsa_sign_fixed_test() {
522         test::run(
523             test_file!("ecdsa_sign_fixed_tests.txt"),
524             |section, test_case| {
525                 assert_eq!(section, "");
526 
527                 let curve_name = test_case.consume_string("Curve");
528                 let digest_name = test_case.consume_string("Digest");
529                 let msg = test_case.consume_bytes("Msg");
530                 let d = test_case.consume_bytes("d");
531                 let q = test_case.consume_bytes("Q");
532                 let k = test_case.consume_bytes("k");
533 
534                 let expected_result = test_case.consume_bytes("Sig");
535 
536                 let alg = match (curve_name.as_str(), digest_name.as_str()) {
537                     ("P-256", "SHA256") => &signature::ECDSA_P256_SHA256_FIXED_SIGNING,
538                     ("P-384", "SHA384") => &signature::ECDSA_P384_SHA384_FIXED_SIGNING,
539                     _ => {
540                         panic!("Unsupported curve+digest: {}+{}", curve_name, digest_name);
541                     }
542                 };
543 
544                 let private_key =
545                     signature::EcdsaKeyPair::from_private_key_and_public_key(alg, &d, &q).unwrap();
546                 let rng = test::rand::FixedSliceRandom { bytes: &k };
547 
548                 let actual_result = private_key
549                     .sign_with_fixed_nonce_during_test(&rng, &msg)
550                     .unwrap();
551 
552                 assert_eq!(actual_result.as_ref(), &expected_result[..]);
553 
554                 Ok(())
555             },
556         );
557     }
558 
559     #[test]
signature_ecdsa_sign_asn1_test()560     fn signature_ecdsa_sign_asn1_test() {
561         test::run(
562             test_file!("ecdsa_sign_asn1_tests.txt"),
563             |section, test_case| {
564                 assert_eq!(section, "");
565 
566                 let curve_name = test_case.consume_string("Curve");
567                 let digest_name = test_case.consume_string("Digest");
568                 let msg = test_case.consume_bytes("Msg");
569                 let d = test_case.consume_bytes("d");
570                 let q = test_case.consume_bytes("Q");
571                 let k = test_case.consume_bytes("k");
572 
573                 let expected_result = test_case.consume_bytes("Sig");
574 
575                 let alg = match (curve_name.as_str(), digest_name.as_str()) {
576                     ("P-256", "SHA256") => &signature::ECDSA_P256_SHA256_ASN1_SIGNING,
577                     ("P-384", "SHA384") => &signature::ECDSA_P384_SHA384_ASN1_SIGNING,
578                     _ => {
579                         panic!("Unsupported curve+digest: {}+{}", curve_name, digest_name);
580                     }
581                 };
582 
583                 let private_key =
584                     signature::EcdsaKeyPair::from_private_key_and_public_key(alg, &d, &q).unwrap();
585                 let rng = test::rand::FixedSliceRandom { bytes: &k };
586 
587                 let actual_result = private_key
588                     .sign_with_fixed_nonce_during_test(&rng, &msg)
589                     .unwrap();
590 
591                 assert_eq!(actual_result.as_ref(), &expected_result[..]);
592 
593                 Ok(())
594             },
595         );
596     }
597 }
598