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: Signature = signing_key.sign(message);
33//!
34//! // Verification
35//! use p256::ecdsa::{VerifyingKey, signature::Verifier};
36//!
37//! let verifying_key = VerifyingKey::from(&signing_key); // Serialize with `::to_encoded_point()`
38//! assert!(verifying_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, Scalar},
49    ecdsa_core::hazmat::{SignPrimitive, VerifyPrimitive},
50};
51
52/// ECDSA/P-256 signature (fixed-size)
53pub type Signature = ecdsa_core::Signature<NistP256>;
54
55/// ECDSA/P-256 signature (ASN.1 DER encoded)
56pub type DerSignature = ecdsa_core::der::Signature<NistP256>;
57
58/// ECDSA/P-256 signing key
59#[cfg(feature = "ecdsa")]
60pub type SigningKey = ecdsa_core::SigningKey<NistP256>;
61
62/// ECDSA/P-256 verification key (i.e. public key)
63#[cfg(feature = "ecdsa")]
64pub type VerifyingKey = ecdsa_core::VerifyingKey<NistP256>;
65
66#[cfg(feature = "sha256")]
67impl ecdsa_core::hazmat::DigestPrimitive for NistP256 {
68    type Digest = sha2::Sha256;
69}
70
71#[cfg(feature = "ecdsa")]
72impl SignPrimitive<NistP256> for Scalar {}
73
74#[cfg(feature = "ecdsa")]
75impl VerifyPrimitive<NistP256> for AffinePoint {}
76
77#[cfg(all(test, feature = "ecdsa"))]
78mod tests {
79    use crate::{
80        ecdsa::{
81            signature::hazmat::{PrehashSigner, PrehashVerifier},
82            signature::Signer,
83            Signature, SigningKey, VerifyingKey,
84        },
85        test_vectors::ecdsa::ECDSA_TEST_VECTORS,
86        AffinePoint, BlindedScalar, EncodedPoint, Scalar,
87    };
88    use ecdsa_core::hazmat::SignPrimitive;
89    use elliptic_curve::{
90        generic_array::GenericArray, group::ff::PrimeField, rand_core::OsRng,
91        sec1::FromEncodedPoint,
92    };
93    use hex_literal::hex;
94    use sha2::Digest;
95
96    // Test vector from RFC 6979 Appendix 2.5 (NIST P-256 + SHA-256)
97    // <https://tools.ietf.org/html/rfc6979#appendix-A.2.5>
98    #[test]
99    fn rfc6979() {
100        let x = hex!("c9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721");
101        let signer = SigningKey::from_bytes(&x.into()).unwrap();
102        let signature: Signature = signer.sign(b"sample");
103        assert_eq!(
104            signature.to_bytes().as_slice(),
105            &hex!(
106                "efd48b2aacb6a8fd1140dd9cd45e81d69d2c877b56aaf991c34d0ea84eaf3716
107                 f7cb1c942d657c41d436c7a1b6e29f65f3e900dbb9aff4064dc4ab2f843acda8"
108            )
109        );
110        let signature: Signature = signer.sign(b"test");
111        assert_eq!(
112            signature.to_bytes().as_slice(),
113            &hex!(
114                "f1abb023518351cd71d881567b1ea663ed3efcf6c5132b354f28d3b0b7d38367
115                 019f4113742a2b14bd25926b49c649155f267e60d3814b4c0cc84250e46f0083"
116            )
117        );
118    }
119
120    // Test signing with PrehashSigner using SHA-384 which output is larger than P-256 field size.
121    #[test]
122    fn prehash_signer_signing_with_sha384() {
123        let x = hex!("c9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721");
124        let signer = SigningKey::from_bytes(&x.into()).unwrap();
125        let digest = sha2::Sha384::digest(b"test");
126        let signature: Signature = signer.sign_prehash(&digest).unwrap();
127        assert_eq!(
128            signature.to_bytes().as_slice(),
129            &hex!(
130                "ebde85f1539af67e70dd7a8a6afeeb332aa7f08f01ebb6ab6e04e2a62d2fef75
131                 871af45800daddf55619b005a601a7a84f544260f1d2625b2ef5aa7a4f4dd76f"
132            )
133        );
134    }
135
136    // Test verifying with PrehashVerifier using SHA-256 which output is larger than P-256 field size.
137    #[test]
138    fn prehash_signer_verification_with_sha384() {
139        // The following test vector adapted from the FIPS 186-4 ECDSA test vectors
140        // (P-256, SHA-384, from `SigGen.txt` in `186-4ecdsatestvectors.zip`)
141        // <https://csrc.nist.gov/projects/cryptographic-algorithm-validation-program/digital-signatures>
142        let verifier = VerifyingKey::from_affine(
143            AffinePoint::from_encoded_point(&EncodedPoint::from_affine_coordinates(
144                GenericArray::from_slice(&hex!(
145                    "e0e7b99bc62d8dd67883e39ed9fa0657789c5ff556cc1fd8dd1e2a55e9e3f243"
146                )),
147                GenericArray::from_slice(&hex!(
148                    "63fbfd0232b95578075c903a4dbf85ad58f8350516e1ec89b0ee1f5e1362da69"
149                )),
150                false,
151            ))
152            .unwrap(),
153        )
154        .unwrap();
155        let signature = Signature::from_scalars(
156            GenericArray::clone_from_slice(&hex!(
157                "f5087878e212b703578f5c66f434883f3ef414dc23e2e8d8ab6a8d159ed5ad83"
158            )),
159            GenericArray::clone_from_slice(&hex!(
160                "306b4c6c20213707982dffbb30fba99b96e792163dd59dbe606e734328dd7c8a"
161            )),
162        )
163        .unwrap();
164        let result = verifier.verify_prehash(
165            &hex!("d9c83b92fa0979f4a5ddbd8dd22ab9377801c3c31bf50f932ace0d2146e2574da0d5552dbed4b18836280e9f94558ea6"),
166            &signature,
167        );
168        assert!(result.is_ok());
169    }
170
171    #[test]
172    fn scalar_blinding() {
173        let vector = &ECDSA_TEST_VECTORS[0];
174        let d = Scalar::from_repr(GenericArray::clone_from_slice(vector.d)).unwrap();
175        let k = Scalar::from_repr(GenericArray::clone_from_slice(vector.k)).unwrap();
176        let k_blinded = BlindedScalar::new(k, &mut OsRng);
177        let z = GenericArray::clone_from_slice(vector.m);
178        let sig = d.try_sign_prehashed(k_blinded, &z).unwrap().0;
179
180        assert_eq!(vector.r, sig.r().to_bytes().as_slice());
181        assert_eq!(vector.s, sig.s().to_bytes().as_slice());
182    }
183
184    mod sign {
185        use crate::{test_vectors::ecdsa::ECDSA_TEST_VECTORS, NistP256};
186        ecdsa_core::new_signing_test!(NistP256, ECDSA_TEST_VECTORS);
187    }
188
189    mod verify {
190        use crate::{test_vectors::ecdsa::ECDSA_TEST_VECTORS, NistP256};
191        ecdsa_core::new_verification_test!(NistP256, ECDSA_TEST_VECTORS);
192    }
193
194    mod wycheproof {
195        use crate::NistP256;
196        ecdsa_core::new_wycheproof_test!(wycheproof, "wycheproof", NistP256);
197    }
198}