Skip to main content

p256/
ecdsa.rs

1//! Elliptic Curve Digital Signature Algorithm (ECDSA)
2//!
3//! This module contains support for computing and verifying ECDSA signatures.
4//! To use it, you will need to enable one of the two following Cargo features:
5//!
6//! - `ecdsa-core`: provides only the [`Signature`] type (which represents an
7//!   ECDSA/P-256 signature). Does not require the `arithmetic` feature.
8//!   This is useful for 3rd-party crates which wish to use the `Signature`
9//!   type for interoperability purposes (particularly in conjunction with the
10//!   [`signature::Signer`] trait. Example use cases for this include other
11//!   software implementations of ECDSA/P-256 and wrappers for cloud KMS
12//!   services or hardware devices (HSM or crypto hardware wallet).
13//! - `ecdsa`: provides `ecdsa-core` features plus the [`SigningKey`] and
14//!   [`VerifyingKey`] types which natively implement ECDSA/P-256 signing and
15//!   verification.
16//!
17//! ## Signing/Verification Example
18//!
19//! This example requires the `ecdsa` Cargo feature is enabled:
20//!
21//! ```
22//! # #[cfg(feature = "ecdsa")]
23//! # {
24//! use p256::{
25//!     ecdsa::{SigningKey, Signature, signature::Signer},
26//! };
27//! use rand_core::OsRng; // requires 'getrandom' feature
28//!
29//! // Signing
30//! let signing_key = SigningKey::random(&mut OsRng); // Serialize with `::to_bytes()`
31//! let message = b"ECDSA proves knowledge of a secret number in the context of a single message";
32//! let signature = signing_key.sign(message);
33//!
34//! // Verification
35//! use p256::ecdsa::{VerifyingKey, signature::Verifier};
36//!
37//! let verify_key = VerifyingKey::from(&signing_key); // Serialize with `::to_encoded_point()`
38//! assert!(verify_key.verify(message, &signature).is_ok());
39//! # }
40//! ```
41
42pub use ecdsa_core::signature::{self, Error};
43
44use super::NistP256;
45
46#[cfg(feature = "ecdsa")]
47use {
48    crate::{AffinePoint, ProjectivePoint, Scalar},
49    core::borrow::Borrow,
50    ecdsa_core::hazmat::{SignPrimitive, VerifyPrimitive},
51    elliptic_curve::ops::Invert,
52};
53
54/// ECDSA/P-256 signature (fixed-size)
55pub type Signature = ecdsa_core::Signature<NistP256>;
56
57/// ECDSA/P-256 signature (ASN.1 DER encoded)
58pub type DerSignature = ecdsa_core::der::Signature<NistP256>;
59
60/// ECDSA/P-256 signing key
61#[cfg(feature = "ecdsa")]
62#[cfg_attr(docsrs, doc(cfg(feature = "ecdsa")))]
63pub type SigningKey = ecdsa_core::SigningKey<NistP256>;
64
65/// ECDSA/P-256 verification key (i.e. public key)
66#[cfg(feature = "ecdsa")]
67#[cfg_attr(docsrs, doc(cfg(feature = "ecdsa")))]
68pub type VerifyingKey = ecdsa_core::VerifyingKey<NistP256>;
69
70#[cfg(feature = "sha256")]
71#[cfg_attr(docsrs, doc(cfg(feature = "sha256")))]
72impl ecdsa_core::hazmat::DigestPrimitive for NistP256 {
73    type Digest = sha2::Sha256;
74}
75
76#[cfg(feature = "ecdsa")]
77impl SignPrimitive<NistP256> for Scalar {
78    #[allow(clippy::many_single_char_names)]
79    fn try_sign_prehashed<K>(&self, ephemeral_scalar: &K, z: &Scalar) -> Result<Signature, Error>
80    where
81        K: Borrow<Scalar> + Invert<Output = Scalar>,
82    {
83        let k_inverse = ephemeral_scalar.invert();
84        let k = ephemeral_scalar.borrow();
85
86        if k_inverse.is_none().into() || k.is_zero().into() {
87            return Err(Error::new());
88        }
89
90        let k_inverse = k_inverse.unwrap();
91
92        // Compute `x`-coordinate of affine point 𝑘×𝑮
93        let x = (ProjectivePoint::generator() * k).to_affine().x;
94
95        // Lift `x` (element of base field) to serialized big endian integer,
96        // then reduce it to an element of the scalar field
97        let r = Scalar::from_bytes_reduced(&x.to_bytes());
98
99        // Compute `s` as a signature over `r` and `z`.
100        let s = k_inverse * (z + &(r * self));
101
102        if s.is_zero().into() {
103            return Err(Error::new());
104        }
105
106        Signature::from_scalars(r, s)
107    }
108}
109
110#[cfg(feature = "ecdsa")]
111impl VerifyPrimitive<NistP256> for AffinePoint {
112    fn verify_prehashed(&self, z: &Scalar, signature: &Signature) -> Result<(), Error> {
113        let r = signature.r();
114        let s = signature.s();
115        let s_inv = s.invert().unwrap();
116        let u1 = z * &s_inv;
117        let u2 = *r * s_inv;
118
119        let x = ((ProjectivePoint::generator() * u1) + (ProjectivePoint::from(*self) * u2))
120            .to_affine()
121            .x;
122
123        if Scalar::from_bytes_reduced(&x.to_bytes()) == *r {
124            Ok(())
125        } else {
126            Err(Error::new())
127        }
128    }
129}
130
131#[cfg(all(test, feature = "ecdsa"))]
132mod tests {
133    use crate::{
134        ecdsa::{signature::Signer, SigningKey},
135        test_vectors::ecdsa::ECDSA_TEST_VECTORS,
136        BlindedScalar, Scalar,
137    };
138    use ecdsa_core::hazmat::SignPrimitive;
139    use elliptic_curve::{generic_array::GenericArray, group::ff::PrimeField, rand_core::OsRng};
140    use hex_literal::hex;
141
142    // Test vector from RFC 6979 Appendix 2.5 (NIST P-256 + SHA-256)
143    // <https://tools.ietf.org/html/rfc6979#appendix-A.2.5>
144    #[test]
145    fn rfc6979() {
146        let x = &hex!("c9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721");
147        let signer = SigningKey::from_bytes(x).unwrap();
148        let signature = signer.sign(b"sample");
149        assert_eq!(
150            signature.as_ref(),
151            &hex!(
152                "efd48b2aacb6a8fd1140dd9cd45e81d69d2c877b56aaf991c34d0ea84eaf3716
153                     f7cb1c942d657c41d436c7a1b6e29f65f3e900dbb9aff4064dc4ab2f843acda8"
154            )[..]
155        );
156    }
157
158    #[test]
159    fn scalar_blinding() {
160        let vector = &ECDSA_TEST_VECTORS[0];
161        let d = Scalar::from_repr(GenericArray::clone_from_slice(vector.d)).unwrap();
162        let k = Scalar::from_repr(GenericArray::clone_from_slice(vector.k)).unwrap();
163        let k_blinded = BlindedScalar::new(k, &mut OsRng);
164        let z = Scalar::from_repr(GenericArray::clone_from_slice(vector.m)).unwrap();
165        let sig = d.try_sign_prehashed(&k_blinded, &z).unwrap();
166
167        assert_eq!(vector.r, sig.r().to_bytes().as_slice());
168        assert_eq!(vector.s, sig.s().to_bytes().as_slice());
169    }
170
171    mod sign {
172        use crate::{test_vectors::ecdsa::ECDSA_TEST_VECTORS, NistP256};
173        ecdsa_core::new_signing_test!(NistP256, ECDSA_TEST_VECTORS);
174    }
175
176    mod verify {
177        use crate::{test_vectors::ecdsa::ECDSA_TEST_VECTORS, NistP256};
178        ecdsa_core::new_verification_test!(NistP256, ECDSA_TEST_VECTORS);
179    }
180
181    mod wycheproof {
182        use crate::NistP256;
183        ecdsa_core::new_wycheproof_test!(wycheproof, "wycheproof", NistP256);
184    }
185}