p384/
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-384 signature). Does not require the `arithmetic` feature. This is
8//!   useful for 3rd-party crates which wish to use the `Signature` type for
9//!   interoperability purposes (particularly in conjunction with the
10//!   [`signature::Signer`] trait. Example use cases for this include other
11//!   software implementations of ECDSA/P-384 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-384 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 p384::ecdsa::{signature::Signer, Signature, SigningKey};
25//! use rand_core::OsRng; // requires 'getrandom' feature
26//!
27//! // Signing
28//! let signing_key = SigningKey::random(&mut OsRng); // Serialize with `::to_bytes()`
29//! let message = b"ECDSA proves knowledge of a secret number in the context of a single message";
30//! let signature: Signature = signing_key.sign(message);
31//!
32//! // Verification
33//! use p384::ecdsa::{signature::Verifier, VerifyingKey};
34//!
35//! let verifying_key = VerifyingKey::from(&signing_key); // Serialize with `::to_encoded_point()`
36//! assert!(verifying_key.verify(message, &signature).is_ok());
37//! # }
38//! ```
39
40pub use ecdsa_core::signature::{self, Error};
41#[cfg(feature = "ecdsa")]
42use {
43    crate::{AffinePoint, Scalar},
44    ecdsa_core::hazmat::{SignPrimitive, VerifyPrimitive},
45};
46
47use super::NistP384;
48
49/// ECDSA/P-384 signature (fixed-size)
50pub type Signature = ecdsa_core::Signature<NistP384>;
51
52/// ECDSA/P-384 signature (ASN.1 DER encoded)
53pub type DerSignature = ecdsa_core::der::Signature<NistP384>;
54
55/// ECDSA/P-384 signing key
56#[cfg(feature = "ecdsa")]
57pub type SigningKey = ecdsa_core::SigningKey<NistP384>;
58
59/// ECDSA/P-384 verification key (i.e. public key)
60#[cfg(feature = "ecdsa")]
61pub type VerifyingKey = ecdsa_core::VerifyingKey<NistP384>;
62
63#[cfg(feature = "sha384")]
64impl ecdsa_core::hazmat::DigestPrimitive for NistP384 {
65    type Digest = sha2::Sha384;
66}
67
68#[cfg(feature = "ecdsa")]
69impl SignPrimitive<NistP384> for Scalar {}
70
71#[cfg(feature = "ecdsa")]
72impl VerifyPrimitive<NistP384> for AffinePoint {}
73
74#[cfg(all(test, feature = "ecdsa"))]
75mod tests {
76    use crate::{
77        ecdsa::{
78            signature::hazmat::{PrehashSigner, PrehashVerifier},
79            signature::Signer,
80            Signature, SigningKey, VerifyingKey,
81        },
82        AffinePoint, EncodedPoint, SecretKey,
83    };
84
85    use elliptic_curve::{generic_array::GenericArray, sec1::FromEncodedPoint};
86    use hex_literal::hex;
87    use sha2::Digest;
88
89    // Test vector from RFC 6979 Appendix 2.6 (NIST P-384 + SHA-384)
90    // <https://tools.ietf.org/html/rfc6979#appendix-A.2.6>
91    #[test]
92    fn rfc6979() {
93        let x = hex!("6b9d3dad2e1b8c1c05b19875b6659f4de23c3b667bf297ba9aa47740787137d896d5724e4c70a825f872c9ea60d2edf5");
94        let signer = SigningKey::from_bytes(&x.into()).unwrap();
95        let signature: Signature = signer.sign(b"sample");
96        assert_eq!(
97            signature.to_bytes().as_slice(),
98            &hex!(
99                "94edbb92a5ecb8aad4736e56c691916b3f88140666ce9fa73d64c4ea95ad133c81a648152e44acf96e36dd1e80fabe46
100                99ef4aeb15f178cea1fe40db2603138f130e740a19624526203b6351d0a3a94fa329c145786e679e7b82c71a38628ac8"
101            )
102        );
103
104        let signature: Signature = signer.sign(b"test");
105        assert_eq!(
106            signature.to_bytes().as_slice(),
107            &hex!(
108                "8203b63d3c853e8d77227fb377bcf7b7b772e97892a80f36ab775d509d7a5feb0542a7f0812998da8f1dd3ca3cf023db
109                ddd0760448d42d8a43af45af836fce4de8be06b485e9b61b827c2f13173923e06a739f040649a667bf3b828246baa5a5"
110            )
111        );
112    }
113
114    // Test signing with PrehashSigner using SHA-256 which output is smaller than P-384 field size.
115    #[test]
116    fn prehash_signer_signing_with_sha256() {
117        let x = hex!("6b9d3dad2e1b8c1c05b19875b6659f4de23c3b667bf297ba9aa47740787137d896d5724e4c70a825f872c9ea60d2edf5");
118        let signer = SigningKey::from_bytes(&x.into()).unwrap();
119        let digest = sha2::Sha256::digest(b"test");
120        let signature: Signature = signer.sign_prehash(&digest).unwrap();
121        assert_eq!(
122            signature.to_bytes().as_slice(),
123            &hex!(
124                "010c3ab1a300f8c9d63eafa9a41813f0c5416c08814bdfc0236458d6c2603d71c4941f4696e60aff5717476170bb6ab4
125                03c4ad6274c61691346b2178def879424726909af308596ffb6355a042f48a114e2eb28eaa6918592b4727961057c0c1"
126            )
127        );
128    }
129
130    // Test verifying with PrehashVerifier using SHA-256 which output is smaller than P-384 field size.
131    #[test]
132    fn prehash_signer_verification_with_sha256() {
133        // The following test vector adapted from the FIPS 186-4 ECDSA test vectors
134        // (P-384, SHA-256, from `SigGen.txt` in `186-4ecdsatestvectors.zip`)
135        // <https://csrc.nist.gov/projects/cryptographic-algorithm-validation-program/digital-signatures>
136        let verifier = VerifyingKey::from_affine(
137            AffinePoint::from_encoded_point(
138                &EncodedPoint::from_affine_coordinates(
139                    GenericArray::from_slice(&hex!("0400193b21f07cd059826e9453d3e96dd145041c97d49ff6b7047f86bb0b0439e909274cb9c282bfab88674c0765bc75")),
140                    GenericArray::from_slice(&hex!("f70d89c52acbc70468d2c5ae75c76d7f69b76af62dcf95e99eba5dd11adf8f42ec9a425b0c5ec98e2f234a926b82a147")),
141                    false,
142                ),
143            ).unwrap()
144        ).unwrap();
145        let signature = Signature::from_scalars(
146            GenericArray::clone_from_slice(&hex!("b11db00cdaf53286d4483f38cd02785948477ed7ebc2ad609054551da0ab0359978c61851788aa2ec3267946d440e878")),
147            GenericArray::clone_from_slice(&hex!("16007873c5b0604ce68112a8fee973e8e2b6e3319c683a762ff5065a076512d7c98b27e74b7887671048ac027df8cbf2")),
148        ).unwrap();
149        let result = verifier.verify_prehash(
150            &hex!("bbbd0a5f645d3fda10e288d172b299455f9dff00e0fbc2833e18cd017d7f3ed1"),
151            &signature,
152        );
153        assert!(result.is_ok());
154    }
155
156    #[test]
157    fn signing_secret_key_equivalent() {
158        let raw_sk: [u8; 48] = [
159            32, 52, 118, 9, 96, 116, 119, 172, 168, 251, 251, 197, 230, 33, 132, 85, 243, 25, 150,
160            105, 121, 46, 248, 180, 102, 250, 168, 123, 220, 103, 121, 129, 68, 200, 72, 221, 3,
161            102, 30, 237, 90, 198, 36, 97, 52, 12, 234, 150,
162        ];
163
164        let seck = SecretKey::from_bytes(&raw_sk.into()).unwrap();
165        let sigk = SigningKey::from_bytes(&raw_sk.into()).unwrap();
166
167        assert_eq!(seck.to_bytes().as_slice(), &raw_sk);
168        assert_eq!(sigk.to_bytes().as_slice(), &raw_sk);
169    }
170
171    mod sign {
172        use crate::{test_vectors::ecdsa::ECDSA_TEST_VECTORS, NistP384};
173        ecdsa_core::new_signing_test!(NistP384, ECDSA_TEST_VECTORS);
174    }
175
176    mod verify {
177        use crate::{test_vectors::ecdsa::ECDSA_TEST_VECTORS, NistP384};
178        ecdsa_core::new_verification_test!(NistP384, ECDSA_TEST_VECTORS);
179    }
180
181    mod wycheproof {
182        use crate::NistP384;
183        ecdsa_core::new_wycheproof_test!(wycheproof, "wycheproof", NistP384);
184    }
185}