1use super::digest_scalar::digest_scalar;
18use 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};
29pub 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)]
41enum 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
48derive_debug_via_id!(EcdsaSigningAlgorithm);
49
50impl PartialEq for EcdsaSigningAlgorithm {
51 fn eq(&self, other: &Self) -> bool {
52 self.id == other.id
53 }
54}
55
56impl Eq for EcdsaSigningAlgorithm {}
57
58impl sealed::Sealed for EcdsaSigningAlgorithm {}
59
60pub struct EcdsaKeyPair {
62 d: Scalar<R>,
63 nonce_key: NonceRandomKey,
64 alg: &'static EcdsaSigningAlgorithm,
65 public_key: PublicKey,
66}
67
68derive_debug_via_field!(EcdsaKeyPair, stringify!(EcdsaKeyPair), public_key);
69
70impl EcdsaKeyPair {
71 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 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(); Self::new(alg, key_pair, &rng)
117 }
118
119 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(); Self::new(alg, key_pair, &rng)
148 }
149
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 pub fn sign(
174 &self,
175 rng: &dyn rand::SecureRandom,
176 message: &[u8],
177 ) -> Result<signature::Signature, error::Unspecified> {
178 let h = digest::digest(self.alg.digest_alg, message);
180
181 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)]
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 let h = digest::digest(self.alg.digest_alg, message);
201
202 self.sign_digest(h, rng)
203 }
204
205 fn sign_digest(
208 &self,
209 h: digest::Digest,
210 rng: &dyn rand::SecureRandom,
211 ) -> Result<signature::Signature, error::Unspecified> {
212 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 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 let r = private_key_ops.point_mul_base(&k);
249
250 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 let e = digest_scalar(scalar_ops, h);
264
265 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 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
285struct NonceRandom<'a> {
288 key: &'a NonceRandomKey,
289 message_digest: &'a digest::Digest,
290 rng: &'a dyn rand::SecureRandom,
291}
292
293impl core::fmt::Debug for NonceRandom<'_> {
294 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
295 f.debug_struct("NonceRandom").finish()
296 }
297}
298
299impl rand::sealed::SecureRandom for NonceRandom<'_> {
300 fn fill_impl(&self, dest: &mut [u8]) -> Result<(), error::Unspecified> {
301 let digest_alg = self.key.0.algorithm();
309 let mut ctx = digest::Context::new(digest_alg);
310
311 let key = self.key.0.as_ref();
313 ctx.update(key);
314
315 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 dest.copy_from_slice(nonce.as_ref());
334
335 Ok(())
336 }
337}
338
339impl<'a> sealed::Sealed for NonceRandom<'a> {}
340
341struct NonceRandomKey(digest::Digest);
342
343impl NonceRandomKey {
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 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
365impl signature::KeyPair for EcdsaKeyPair {
366 type PublicKey = PublicKey;
367
368 fn public_key(&self) -> &Self::PublicKey {
369 &self.public_key
370 }
371}
372
373#[derive(Clone, Copy)]
374pub struct PublicKey(ec::PublicKey);
375
376derive_debug_self_as_ref_hex_bytes!(PublicKey);
377
378impl AsRef<[u8]> for PublicKey {
379 fn as_ref(&self) -> &[u8] {
380 self.0.as_ref()
381 }
382}
383
384fn 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
396fn format_rs_asn1(ops: &'static ScalarOps, r: &Scalar, s: &Scalar, out: &mut [u8]) -> usize {
397 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 debug_assert_eq!(fixed[0], 0);
407
408 let first_index = fixed.iter().position(|b| *b != 0).unwrap();
410
411 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 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 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
442pub 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
457pub 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
472pub 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
487pub 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
502static 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
509static 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)]
517mod tests {
518 use crate::{signature, test};
519
520 #[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]
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}