Skip to main content

aptos_sdk/crypto/
secp256r1.rs

1//! Secp256r1 (P-256) ECDSA signature scheme implementation.
2//!
3//! Secp256r1, also known as P-256 or prime256v1, is commonly used in
4//! `WebAuthn` and passkey implementations.
5//!
6//! # Security: Signature Malleability
7//!
8//! This implementation enforces **low-S only** signatures to match the Aptos
9//! blockchain's on-chain verification, which rejects high-S signatures to
10//! prevent signature malleability attacks.
11//!
12//! - **Signing** always produces low-S signatures (normalized by this SDK,
13//!   independent of the `p256` crate's default behavior).
14//! - **Parsing** (`from_bytes`, `from_hex`) rejects high-S signatures.
15//! - **Verification** also rejects high-S signatures as a defense-in-depth
16//!   measure.
17
18use crate::crypto::traits::{PublicKey, Signature, Signer, Verifier};
19use crate::error::{AptosError, AptosResult};
20use p256::ecdsa::{
21    Signature as P256Signature, SigningKey, VerifyingKey,
22    signature::Signer as P256Signer,
23    signature::Verifier as P256Verifier,
24    signature::hazmat::{PrehashSigner, PrehashVerifier},
25};
26use p256::elliptic_curve::Generate;
27use serde::{Deserialize, Serialize};
28use std::fmt;
29use zeroize::Zeroize;
30
31/// Secp256r1 private key length in bytes.
32pub const SECP256R1_PRIVATE_KEY_LENGTH: usize = 32;
33/// Secp256r1 public key length in bytes (compressed).
34pub const SECP256R1_PUBLIC_KEY_LENGTH: usize = 33;
35/// Secp256r1 signature length in bytes.
36pub const SECP256R1_SIGNATURE_LENGTH: usize = 64;
37
38/// A Secp256r1 (P-256) ECDSA private key.
39///
40/// The private key is zeroized when dropped.
41#[derive(Clone, Zeroize)]
42#[zeroize(drop)]
43pub struct Secp256r1PrivateKey {
44    #[zeroize(skip)]
45    #[allow(unused)] // Field is used; lint false positive from Zeroize derive
46    inner: SigningKey,
47}
48
49impl Secp256r1PrivateKey {
50    /// Generates a new random Secp256r1 private key.
51    pub fn generate() -> Self {
52        let signing_key = SigningKey::generate();
53        Self { inner: signing_key }
54    }
55
56    /// Creates a private key from raw bytes.
57    ///
58    /// # Errors
59    ///
60    /// Returns [`AptosError::InvalidPrivateKey`] if:
61    /// - The byte slice length is not exactly 32 bytes
62    /// - The bytes do not represent a valid Secp256r1 private key
63    pub fn from_bytes(bytes: &[u8]) -> AptosResult<Self> {
64        if bytes.len() != SECP256R1_PRIVATE_KEY_LENGTH {
65            return Err(AptosError::InvalidPrivateKey(format!(
66                "expected {} bytes, got {}",
67                SECP256R1_PRIVATE_KEY_LENGTH,
68                bytes.len()
69            )));
70        }
71        let signing_key = SigningKey::from_slice(bytes)
72            .map_err(|e| AptosError::InvalidPrivateKey(e.to_string()))?;
73        Ok(Self { inner: signing_key })
74    }
75
76    /// Creates a private key from a hex string.
77    ///
78    /// # Errors
79    ///
80    /// Returns [`AptosError::Hex`] if the hex string is invalid.
81    /// Returns [`AptosError::InvalidPrivateKey`] if the decoded bytes are not exactly 32 bytes or do not represent a valid Secp256r1 private key.
82    pub fn from_hex(hex_str: &str) -> AptosResult<Self> {
83        let bytes = const_hex::decode(hex_str)?;
84        Self::from_bytes(&bytes)
85    }
86
87    /// Creates a private key from AIP-80 format string.
88    ///
89    /// AIP-80 format: `secp256r1-priv-0x{hex_bytes}`
90    ///
91    /// # Errors
92    ///
93    /// Returns an error if the format is invalid or the key bytes are invalid.
94    pub fn from_aip80(s: &str) -> AptosResult<Self> {
95        const PREFIX: &str = "secp256r1-priv-";
96        if let Some(hex_part) = s.strip_prefix(PREFIX) {
97            Self::from_hex(hex_part)
98        } else {
99            Err(AptosError::InvalidPrivateKey(format!(
100                "invalid AIP-80 format: expected prefix '{PREFIX}'"
101            )))
102        }
103    }
104
105    /// Returns the private key as bytes.
106    pub fn to_bytes(&self) -> [u8; SECP256R1_PRIVATE_KEY_LENGTH] {
107        self.inner.to_bytes().into()
108    }
109
110    /// Returns the private key as a hex string.
111    pub fn to_hex(&self) -> String {
112        const_hex::encode_prefixed(self.inner.to_bytes())
113    }
114
115    /// Returns the private key in AIP-80 format.
116    ///
117    /// AIP-80 format: `secp256r1-priv-0x{hex_bytes}`
118    pub fn to_aip80(&self) -> String {
119        format!("secp256r1-priv-{}", self.to_hex())
120    }
121
122    /// Returns the corresponding public key.
123    pub fn public_key(&self) -> Secp256r1PublicKey {
124        Secp256r1PublicKey {
125            inner: *self.inner.verifying_key(),
126        }
127    }
128
129    /// Signs a message (pre-hashed with SHA256) and returns a low-S signature.
130    ///
131    /// The signature is normalized to low-S form to match Aptos on-chain
132    /// verification requirements.
133    pub fn sign(&self, message: &[u8]) -> Secp256r1Signature {
134        // `p256::ecdsa::SigningKey: signature::Signer<Signature>` hashes its input
135        // with SHA-256 internally before signing. The historical SDK code
136        // pre-hashed the message *and* called `sign()`, producing a signature
137        // over `SHA-256(SHA-256(message))` instead of `SHA-256(message)`. That
138        // double-hashing was self-consistent (sign + verify both double-hashed)
139        // but did not match Aptos on-chain ECDSA verification, which hashes
140        // once. We now sign the raw message and let `p256` apply SHA-256 once.
141        let signature: P256Signature = self.inner.sign(message);
142        // SECURITY: Normalize to low-S to match Aptos on-chain verification.
143        // The p256 crate does not guarantee low-S output from signing.
144        let normalized = signature.normalize_s();
145        Secp256r1Signature { inner: normalized }
146    }
147
148    /// Signs a pre-hashed message directly and returns a low-S signature.
149    ///
150    /// The 32-byte `hash` is signed as-is: it is treated as the ECDSA message
151    /// digest and is **not** hashed again. This uses the `PrehashSigner` hazmat
152    /// API (like the `secp256k1` equivalent); the ordinary `Signer::sign` path
153    /// would apply SHA-256 to its input, so signing a digest through it would
154    /// produce a signature over `SHA-256(hash)` that no external or on-chain
155    /// verifier could check against `hash`.
156    ///
157    /// The signature is normalized to low-S form to match Aptos on-chain
158    /// verification requirements.
159    ///
160    /// # Panics
161    ///
162    /// Panics only if `p256::ecdsa::SigningKey::sign_prehash` returns `Err`,
163    /// which per the `signature::hazmat::PrehashSigner` contract for `secp256r1`
164    /// does not happen for a 32-byte digest (the field size is 32 bytes).
165    pub fn sign_prehashed(&self, hash: &[u8; 32]) -> Secp256r1Signature {
166        // `p256::ecdsa::SigningKey::sign_prehash` returns `Err` only for a
167        // prehash shorter than the field size; a 32-byte digest is always valid.
168        let signature: P256Signature = self
169            .inner
170            .sign_prehash(hash)
171            .expect("32-byte digest is a valid ECDSA prehash");
172        // SECURITY: Normalize to low-S to match Aptos on-chain verification.
173        let normalized = signature.normalize_s();
174        Secp256r1Signature { inner: normalized }
175    }
176}
177
178impl Signer for Secp256r1PrivateKey {
179    type Signature = Secp256r1Signature;
180
181    fn sign(&self, message: &[u8]) -> Secp256r1Signature {
182        Secp256r1PrivateKey::sign(self, message)
183    }
184
185    fn public_key(&self) -> Secp256r1PublicKey {
186        Secp256r1PrivateKey::public_key(self)
187    }
188}
189
190impl fmt::Debug for Secp256r1PrivateKey {
191    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192        write!(f, "Secp256r1PrivateKey([REDACTED])")
193    }
194}
195
196/// A Secp256r1 (P-256) ECDSA public key.
197#[derive(Clone, Copy, PartialEq, Eq)]
198pub struct Secp256r1PublicKey {
199    inner: VerifyingKey,
200}
201
202impl Secp256r1PublicKey {
203    /// Creates a public key from bytes in any accepted encoding.
204    ///
205    /// Accepts all of the following:
206    /// - 33-byte SEC1 compressed (`0x02`/`0x03` prefix)
207    /// - 65-byte SEC1 uncompressed (`0x04` prefix)
208    /// - 64-byte raw `X || Y` affine coordinates (the Aptos on-chain encoding,
209    ///   with the leading `0x04` marker dropped)
210    ///
211    /// # Errors
212    ///
213    /// Returns [`AptosError::InvalidPublicKey`] if the bytes do not decode to a
214    /// valid Secp256r1 public key in one of the accepted encodings.
215    pub fn from_bytes(bytes: &[u8]) -> AptosResult<Self> {
216        // Accept SEC1-style encodings (33 compressed, 65 uncompressed) *and*
217        // the raw 64-byte `(X || Y)` Aptos on-chain encoding.
218        if bytes.len() == 64 {
219            let mut sec1 = Vec::with_capacity(65);
220            sec1.push(0x04);
221            sec1.extend_from_slice(bytes);
222            return VerifyingKey::from_sec1_bytes(&sec1)
223                .map(|inner| Self { inner })
224                .map_err(|e| AptosError::InvalidPublicKey(e.to_string()));
225        }
226        let verifying_key = VerifyingKey::from_sec1_bytes(bytes)
227            .map_err(|e| AptosError::InvalidPublicKey(e.to_string()))?;
228        Ok(Self {
229            inner: verifying_key,
230        })
231    }
232
233    /// Creates a public key from a hex string.
234    ///
235    /// # Errors
236    ///
237    /// Returns [`AptosError::Hex`] if the hex string is invalid.
238    /// Returns [`AptosError::InvalidPublicKey`] if the decoded bytes do not represent a valid
239    /// Secp256r1 public key in one of the encodings accepted by [`Self::from_bytes`]
240    /// (33-byte compressed, 65-byte SEC1 uncompressed, or 64-byte raw `X || Y`).
241    pub fn from_hex(hex_str: &str) -> AptosResult<Self> {
242        let bytes = const_hex::decode(hex_str)?;
243        Self::from_bytes(&bytes)
244    }
245
246    /// Creates a public key from AIP-80 format string.
247    ///
248    /// AIP-80 format: `secp256r1-pub-0x{hex_bytes}`
249    ///
250    /// # Errors
251    ///
252    /// Returns an error if the format is invalid or the key bytes are invalid.
253    pub fn from_aip80(s: &str) -> AptosResult<Self> {
254        const PREFIX: &str = "secp256r1-pub-";
255        if let Some(hex_part) = s.strip_prefix(PREFIX) {
256            Self::from_hex(hex_part)
257        } else {
258            Err(AptosError::InvalidPublicKey(format!(
259                "invalid AIP-80 format: expected prefix '{PREFIX}'"
260            )))
261        }
262    }
263
264    /// Returns the public key as compressed bytes (33 bytes).
265    pub fn to_bytes(&self) -> Vec<u8> {
266        self.inner.to_sec1_point(true).as_bytes().to_vec()
267    }
268
269    /// Returns the public key in SEC1 uncompressed encoding (65 bytes, leading 0x04 marker).
270    ///
271    /// Most Aptos on-chain APIs use the *raw* 64-byte encoding (the `X || Y`
272    /// coordinates with the 0x04 marker dropped); see [`Self::to_raw_bytes`].
273    /// This method is retained for callers that need the SEC1 form.
274    pub fn to_uncompressed_bytes(&self) -> Vec<u8> {
275        self.inner.to_sec1_point(false).as_bytes().to_vec()
276    }
277
278    /// Returns the public key as the raw 64 bytes of the `X || Y` affine
279    /// coordinates, without the leading SEC1 0x04 uncompressed-point marker.
280    ///
281    /// This is the encoding expected by the on-chain
282    /// `AnyPublicKey::Secp256r1Ecdsa` variant (carrying a `vector<u8>` of
283    /// length 64).
284    pub fn to_raw_bytes(&self) -> [u8; 64] {
285        let uncompressed = self.to_uncompressed_bytes();
286        debug_assert_eq!(uncompressed.len(), 65);
287        debug_assert_eq!(uncompressed[0], 0x04);
288        let mut out = [0u8; 64];
289        out.copy_from_slice(&uncompressed[1..]);
290        out
291    }
292
293    /// Returns the public key as a hex string (compressed format).
294    pub fn to_hex(&self) -> String {
295        const_hex::encode_prefixed(self.to_bytes())
296    }
297
298    /// Returns the public key in AIP-80 format (compressed).
299    ///
300    /// AIP-80 format: `secp256r1-pub-0x{hex_bytes}`
301    pub fn to_aip80(&self) -> String {
302        format!("secp256r1-pub-{}", self.to_hex())
303    }
304
305    /// Verifies a signature against a message.
306    ///
307    /// # Security
308    ///
309    /// Rejects high-S signatures before verification, matching Aptos on-chain
310    /// behavior. This is a defense-in-depth check; signatures created through
311    /// this SDK's `from_bytes` are already guaranteed to be low-S.
312    ///
313    /// # Errors
314    ///
315    /// Returns [`AptosError::SignatureVerificationFailed`] if the signature has
316    /// a high-S value, is invalid, or does not match the message.
317    pub fn verify(&self, message: &[u8], signature: &Secp256r1Signature) -> AptosResult<()> {
318        // SECURITY: Reject high-S signatures (matches aptos-core behavior)
319        if signature.inner.normalize_s() != signature.inner {
320            return Err(AptosError::SignatureVerificationFailed);
321        }
322        // `Verifier::verify` SHA-256s the message internally, mirroring how
323        // `sign(message)` produces a signature over SHA-256(message).
324        self.inner
325            .verify(message, &signature.inner)
326            .map_err(|_| AptosError::SignatureVerificationFailed)
327    }
328
329    /// Verifies a signature against a pre-hashed message.
330    ///
331    /// # Security
332    ///
333    /// Rejects high-S signatures before verification, matching Aptos on-chain
334    /// behavior.
335    ///
336    /// # Errors
337    ///
338    /// Returns [`AptosError::SignatureVerificationFailed`] if the signature has
339    /// a high-S value, is invalid, or does not match the hash.
340    pub fn verify_prehashed(
341        &self,
342        hash: &[u8; 32],
343        signature: &Secp256r1Signature,
344    ) -> AptosResult<()> {
345        // SECURITY: Reject high-S signatures (matches aptos-core behavior)
346        if signature.inner.normalize_s() != signature.inner {
347            return Err(AptosError::SignatureVerificationFailed);
348        }
349        // Verify against the digest directly via `verify_prehash`; the ordinary
350        // `Verifier::verify` would apply SHA-256 to `hash` again, which would
351        // reject a signature legitimately produced over the digest.
352        self.inner
353            .verify_prehash(hash, &signature.inner)
354            .map_err(|_| AptosError::SignatureVerificationFailed)
355    }
356
357    /// Derives the account address for this public key.
358    ///
359    /// Uses the `SingleKey` authentication scheme (`scheme_id` = 2):
360    /// `auth_key = SHA3-256(BCS(AnyPublicKey::Secp256r1Ecdsa) || 0x02)`
361    ///
362    /// Where `BCS(AnyPublicKey::Secp256r1Ecdsa)` = `0x02 || ULEB128(65) || uncompressed_public_key`
363    pub fn to_address(&self) -> crate::types::AccountAddress {
364        // Mirrors secp256k1: the chain canonicalises P-256 public keys to
365        // 65-byte SEC1 uncompressed form (0x04 || X || Y) when computing
366        // authentication keys via `bcs::to_bytes(&AnyPublicKey)`. The SDK
367        // matches that exact encoding so the derived address agrees with
368        // the chain.
369        let uncompressed = self.to_uncompressed_bytes();
370        let mut bcs_bytes = Vec::with_capacity(1 + 1 + uncompressed.len());
371        bcs_bytes.push(0x02); // Secp256r1Ecdsa variant
372        bcs_bytes.push(65); // ULEB128(65)
373        bcs_bytes.extend_from_slice(&uncompressed);
374        crate::crypto::derive_address(&bcs_bytes, crate::crypto::SINGLE_KEY_SCHEME)
375    }
376}
377
378impl PublicKey for Secp256r1PublicKey {
379    const LENGTH: usize = SECP256R1_PUBLIC_KEY_LENGTH;
380
381    fn from_bytes(bytes: &[u8]) -> AptosResult<Self> {
382        Secp256r1PublicKey::from_bytes(bytes)
383    }
384
385    fn to_bytes(&self) -> Vec<u8> {
386        Secp256r1PublicKey::to_bytes(self)
387    }
388}
389
390impl Verifier for Secp256r1PublicKey {
391    type Signature = Secp256r1Signature;
392
393    fn verify(&self, message: &[u8], signature: &Secp256r1Signature) -> AptosResult<()> {
394        Secp256r1PublicKey::verify(self, message, signature)
395    }
396}
397
398impl fmt::Debug for Secp256r1PublicKey {
399    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
400        write!(f, "Secp256r1PublicKey({})", self.to_hex())
401    }
402}
403
404impl fmt::Display for Secp256r1PublicKey {
405    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
406        write!(f, "{}", self.to_hex())
407    }
408}
409
410impl Serialize for Secp256r1PublicKey {
411    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
412    where
413        S: serde::Serializer,
414    {
415        if serializer.is_human_readable() {
416            serializer.serialize_str(&self.to_hex())
417        } else {
418            serializer.serialize_bytes(&self.to_bytes())
419        }
420    }
421}
422
423impl<'de> Deserialize<'de> for Secp256r1PublicKey {
424    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
425    where
426        D: serde::Deserializer<'de>,
427    {
428        if deserializer.is_human_readable() {
429            let s = String::deserialize(deserializer)?;
430            Self::from_hex(&s).map_err(serde::de::Error::custom)
431        } else {
432            let bytes = Vec::<u8>::deserialize(deserializer)?;
433            Self::from_bytes(&bytes).map_err(serde::de::Error::custom)
434        }
435    }
436}
437
438/// A Secp256r1 (P-256) ECDSA signature.
439#[derive(Clone, Copy, PartialEq, Eq)]
440pub struct Secp256r1Signature {
441    inner: P256Signature,
442}
443
444impl Secp256r1Signature {
445    /// Creates a signature from raw bytes (64 bytes, r || s).
446    ///
447    /// # Security
448    ///
449    /// Rejects high-S signatures to match Aptos on-chain verification behavior.
450    /// The Aptos VM only accepts low-S (canonical) ECDSA signatures to prevent
451    /// signature malleability attacks.
452    ///
453    /// # Errors
454    ///
455    /// Returns [`AptosError::InvalidSignature`] if:
456    /// - The byte slice length is not exactly 64 bytes
457    /// - The bytes do not represent a valid Secp256r1 signature
458    /// - The signature has a high-S value (not canonical)
459    pub fn from_bytes(bytes: &[u8]) -> AptosResult<Self> {
460        if bytes.len() != SECP256R1_SIGNATURE_LENGTH {
461            return Err(AptosError::InvalidSignature(format!(
462                "expected {} bytes, got {}",
463                SECP256R1_SIGNATURE_LENGTH,
464                bytes.len()
465            )));
466        }
467        let signature = P256Signature::from_slice(bytes)
468            .map_err(|e| AptosError::InvalidSignature(e.to_string()))?;
469        // SECURITY: Reject high-S signatures. Aptos on-chain verification only
470        // accepts low-S (canonical) signatures to prevent malleability.
471        // normalize_s() changes the signature iff it was high-S.
472        if signature.normalize_s() != signature {
473            return Err(AptosError::InvalidSignature(
474                "high-S signature rejected: Aptos requires low-S (canonical) ECDSA signatures"
475                    .into(),
476            ));
477        }
478        Ok(Self { inner: signature })
479    }
480
481    /// Creates a signature from a hex string.
482    ///
483    /// # Errors
484    ///
485    /// Returns [`AptosError::Hex`] if the hex string is invalid.
486    /// Returns [`AptosError::InvalidSignature`] if the decoded bytes are not exactly 64 bytes or do not represent a valid Secp256r1 signature.
487    pub fn from_hex(hex_str: &str) -> AptosResult<Self> {
488        let bytes = const_hex::decode(hex_str)?;
489        Self::from_bytes(&bytes)
490    }
491
492    /// Returns the signature as bytes (64 bytes, r || s).
493    pub fn to_bytes(&self) -> [u8; SECP256R1_SIGNATURE_LENGTH] {
494        self.inner.to_bytes().into()
495    }
496
497    /// Returns the signature as a hex string.
498    pub fn to_hex(&self) -> String {
499        const_hex::encode_prefixed(self.to_bytes())
500    }
501}
502
503impl Signature for Secp256r1Signature {
504    type PublicKey = Secp256r1PublicKey;
505    const LENGTH: usize = SECP256R1_SIGNATURE_LENGTH;
506
507    fn from_bytes(bytes: &[u8]) -> AptosResult<Self> {
508        Secp256r1Signature::from_bytes(bytes)
509    }
510
511    fn to_bytes(&self) -> Vec<u8> {
512        self.inner.to_bytes().to_vec()
513    }
514}
515
516impl fmt::Debug for Secp256r1Signature {
517    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
518        write!(f, "Secp256r1Signature({})", self.to_hex())
519    }
520}
521
522impl fmt::Display for Secp256r1Signature {
523    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
524        write!(f, "{}", self.to_hex())
525    }
526}
527
528impl Serialize for Secp256r1Signature {
529    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
530    where
531        S: serde::Serializer,
532    {
533        if serializer.is_human_readable() {
534            serializer.serialize_str(&self.to_hex())
535        } else {
536            serializer.serialize_bytes(&self.to_bytes())
537        }
538    }
539}
540
541impl<'de> Deserialize<'de> for Secp256r1Signature {
542    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
543    where
544        D: serde::Deserializer<'de>,
545    {
546        if deserializer.is_human_readable() {
547            let s = String::deserialize(deserializer)?;
548            Self::from_hex(&s).map_err(serde::de::Error::custom)
549        } else {
550            let bytes = Vec::<u8>::deserialize(deserializer)?;
551            Self::from_bytes(&bytes).map_err(serde::de::Error::custom)
552        }
553    }
554}
555
556#[cfg(test)]
557mod tests {
558    use super::*;
559
560    #[test]
561    fn test_generate_and_sign() {
562        let private_key = Secp256r1PrivateKey::generate();
563        let message = b"hello world";
564        let signature = private_key.sign(message);
565
566        let public_key = private_key.public_key();
567        assert!(public_key.verify(message, &signature).is_ok());
568    }
569
570    #[test]
571    fn test_wrong_message_fails() {
572        let private_key = Secp256r1PrivateKey::generate();
573        let message = b"hello world";
574        let wrong_message = b"hello world!";
575        let signature = private_key.sign(message);
576
577        let public_key = private_key.public_key();
578        assert!(public_key.verify(wrong_message, &signature).is_err());
579    }
580
581    #[test]
582    fn test_sign_prehashed_and_verify_prehashed_roundtrip() {
583        let private_key = Secp256r1PrivateKey::generate();
584        let public_key = private_key.public_key();
585        let hash = crate::crypto::sha3_256(b"prehash roundtrip");
586
587        let signature = private_key.sign_prehashed(&hash);
588        public_key.verify_prehashed(&hash, &signature).unwrap();
589    }
590
591    #[test]
592    fn test_verify_prehashed_wrong_hash_fails() {
593        let private_key = Secp256r1PrivateKey::generate();
594        let public_key = private_key.public_key();
595        let hash = crate::crypto::sha3_256(b"prehash correct");
596        let wrong_hash = crate::crypto::sha3_256(b"prehash wrong");
597
598        let signature = private_key.sign_prehashed(&hash);
599        assert!(
600            public_key
601                .verify_prehashed(&wrong_hash, &signature)
602                .is_err()
603        );
604    }
605
606    #[test]
607    fn test_sign_prehashed_signs_digest_directly_not_double_hashed() {
608        // The interop property that guards against double-hashing: signing the
609        // SHA-256 digest of a message via `sign_prehashed` must produce a
610        // signature the *message* verifier accepts, because `verify(message)`
611        // hashes the message with SHA-256 exactly once. If `sign_prehashed`
612        // hashed the digest again (the historical bug), this would fail.
613        let private_key = Secp256r1PrivateKey::generate();
614        let public_key = private_key.public_key();
615        let message = b"prehash must match single-hash signing";
616        let digest = crate::crypto::sha2_256(message);
617
618        let signature = private_key.sign_prehashed(&digest);
619        public_key
620            .verify(message, &signature)
621            .expect("signature over SHA-256(message) must verify against the message");
622    }
623
624    #[test]
625    fn test_from_bytes_roundtrip() {
626        let private_key = Secp256r1PrivateKey::generate();
627        let bytes = private_key.to_bytes();
628        let restored = Secp256r1PrivateKey::from_bytes(&bytes).unwrap();
629        assert_eq!(private_key.to_bytes(), restored.to_bytes());
630    }
631
632    #[test]
633    fn test_public_key_from_bytes_roundtrip() {
634        let private_key = Secp256r1PrivateKey::generate();
635        let public_key = private_key.public_key();
636        let bytes = public_key.to_bytes();
637        let restored = Secp256r1PublicKey::from_bytes(&bytes).unwrap();
638        assert_eq!(public_key.to_bytes(), restored.to_bytes());
639    }
640
641    #[test]
642    fn test_signature_from_bytes_roundtrip() {
643        let private_key = Secp256r1PrivateKey::generate();
644        let signature = private_key.sign(b"test");
645        let bytes = signature.to_bytes();
646        let restored = Secp256r1Signature::from_bytes(&bytes).unwrap();
647        assert_eq!(signature.to_bytes(), restored.to_bytes());
648    }
649
650    #[test]
651    fn test_hex_roundtrip() {
652        let private_key = Secp256r1PrivateKey::generate();
653        let hex = private_key.to_hex();
654        let restored = Secp256r1PrivateKey::from_hex(&hex).unwrap();
655        assert_eq!(private_key.to_bytes(), restored.to_bytes());
656    }
657
658    #[test]
659    fn test_public_key_hex_roundtrip() {
660        let private_key = Secp256r1PrivateKey::generate();
661        let public_key = private_key.public_key();
662        let hex = public_key.to_hex();
663        let restored = Secp256r1PublicKey::from_hex(&hex).unwrap();
664        assert_eq!(public_key.to_bytes(), restored.to_bytes());
665    }
666
667    #[test]
668    fn test_signature_hex_roundtrip() {
669        let private_key = Secp256r1PrivateKey::generate();
670        let signature = private_key.sign(b"test");
671        let hex = signature.to_hex();
672        let restored = Secp256r1Signature::from_hex(&hex).unwrap();
673        assert_eq!(signature.to_bytes(), restored.to_bytes());
674    }
675
676    #[test]
677    fn test_invalid_private_key_bytes() {
678        let bytes = vec![0u8; 16]; // Wrong length
679        let result = Secp256r1PrivateKey::from_bytes(&bytes);
680        assert!(result.is_err());
681    }
682
683    #[test]
684    fn test_invalid_public_key_bytes() {
685        let bytes = vec![0u8; 16]; // Wrong length
686        let result = Secp256r1PublicKey::from_bytes(&bytes);
687        assert!(result.is_err());
688    }
689
690    #[test]
691    fn test_invalid_signature_bytes() {
692        let bytes = vec![0u8; 16]; // Wrong length
693        let result = Secp256r1Signature::from_bytes(&bytes);
694        assert!(result.is_err());
695    }
696
697    #[test]
698    fn test_high_s_signature_rejected() {
699        use p256::elliptic_curve::ops::Neg;
700
701        // Sign a message (produces low-S after normalization)
702        let private_key = Secp256r1PrivateKey::generate();
703        let signature = private_key.sign(b"test message");
704
705        // Construct high-S by negating the S component: S' = n - S
706        let low_s_sig = P256Signature::from_slice(&signature.to_bytes()).unwrap();
707        let (r, s) = low_s_sig.split_scalars();
708        let neg_s = s.neg();
709        let high_s_sig = P256Signature::from_scalars(r, neg_s).unwrap();
710        // Confirm it really is high-S (normalize_s changes high-S signatures)
711        assert!(
712            high_s_sig.normalize_s() != high_s_sig,
713            "constructed signature should be high-S"
714        );
715        let high_s_bytes = high_s_sig.to_bytes();
716
717        // from_bytes should reject high-S
718        let result = Secp256r1Signature::from_bytes(&high_s_bytes);
719        assert!(result.is_err(), "high-S signature should be rejected");
720        assert!(
721            result
722                .unwrap_err()
723                .to_string()
724                .contains("high-S signature rejected"),
725            "error message should mention high-S rejection"
726        );
727
728        // Verify should also reject high-S (defense-in-depth via inner field)
729        let sig_with_high_s = Secp256r1Signature { inner: high_s_sig };
730        let public_key = private_key.public_key();
731        let result = public_key.verify(b"test message", &sig_with_high_s);
732        assert!(result.is_err(), "verify should reject high-S signature");
733    }
734
735    #[test]
736    fn test_signing_always_produces_low_s() {
737        // Run multiple iterations to increase confidence
738        for _ in 0..20 {
739            let private_key = Secp256r1PrivateKey::generate();
740            let signature = private_key.sign(b"test low-s");
741            // normalize_s leaves already low-S signatures unchanged
742            assert!(
743                signature.inner.normalize_s() == signature.inner,
744                "signing must always produce low-S signatures"
745            );
746        }
747    }
748
749    #[test]
750    fn test_json_serialization_public_key() {
751        let private_key = Secp256r1PrivateKey::generate();
752        let public_key = private_key.public_key();
753        let json = serde_json::to_string(&public_key).unwrap();
754        let restored: Secp256r1PublicKey = serde_json::from_str(&json).unwrap();
755        assert_eq!(public_key.to_bytes(), restored.to_bytes());
756    }
757
758    #[test]
759    fn test_json_serialization_signature() {
760        let private_key = Secp256r1PrivateKey::generate();
761        let signature = private_key.sign(b"test");
762        let json = serde_json::to_string(&signature).unwrap();
763        let restored: Secp256r1Signature = serde_json::from_str(&json).unwrap();
764        assert_eq!(signature.to_bytes(), restored.to_bytes());
765    }
766
767    #[test]
768    fn test_key_lengths() {
769        assert_eq!(Secp256r1PublicKey::LENGTH, SECP256R1_PUBLIC_KEY_LENGTH);
770        assert_eq!(Secp256r1Signature::LENGTH, SECP256R1_SIGNATURE_LENGTH);
771    }
772
773    #[test]
774    fn test_display_debug() {
775        let private_key = Secp256r1PrivateKey::generate();
776        let public_key = private_key.public_key();
777        let signature = private_key.sign(b"test");
778
779        // Debug should contain type name
780        assert!(format!("{public_key:?}").contains("Secp256r1PublicKey"));
781        assert!(format!("{signature:?}").contains("Secp256r1Signature"));
782
783        // Display should show hex
784        assert!(format!("{public_key}").starts_with("0x"));
785        assert!(format!("{signature}").starts_with("0x"));
786    }
787
788    #[test]
789    fn test_compressed_public_key_length() {
790        let private_key = Secp256r1PrivateKey::generate();
791        let public_key = private_key.public_key();
792        // Compressed public key should be 33 bytes
793        assert_eq!(public_key.to_bytes().len(), 33);
794    }
795
796    #[test]
797    fn test_private_key_aip80_roundtrip() {
798        let private_key = Secp256r1PrivateKey::generate();
799        let aip80 = private_key.to_aip80();
800
801        // Should have correct prefix
802        assert!(aip80.starts_with("secp256r1-priv-0x"));
803
804        // Should roundtrip correctly
805        let restored = Secp256r1PrivateKey::from_aip80(&aip80).unwrap();
806        assert_eq!(private_key.to_bytes(), restored.to_bytes());
807    }
808
809    #[test]
810    fn test_private_key_aip80_format() {
811        let bytes = [0x01; 32];
812        let private_key = Secp256r1PrivateKey::from_bytes(&bytes).unwrap();
813        let aip80 = private_key.to_aip80();
814
815        // Expected format: secp256r1-priv-0x0101...01
816        let expected = format!("secp256r1-priv-0x{}", "01".repeat(32));
817        assert_eq!(aip80, expected);
818    }
819
820    #[test]
821    fn test_private_key_aip80_invalid_prefix() {
822        let result = Secp256r1PrivateKey::from_aip80("ed25519-priv-0x01");
823        assert!(result.is_err());
824    }
825
826    #[test]
827    fn test_public_key_aip80_roundtrip() {
828        let private_key = Secp256r1PrivateKey::generate();
829        let public_key = private_key.public_key();
830        let aip80 = public_key.to_aip80();
831
832        // Should have correct prefix
833        assert!(aip80.starts_with("secp256r1-pub-0x"));
834
835        // Should roundtrip correctly
836        let restored = Secp256r1PublicKey::from_aip80(&aip80).unwrap();
837        assert_eq!(public_key.to_bytes(), restored.to_bytes());
838    }
839
840    #[test]
841    fn test_public_key_aip80_invalid_prefix() {
842        let result = Secp256r1PublicKey::from_aip80("ed25519-pub-0x01");
843        assert!(result.is_err());
844    }
845
846    #[test]
847    fn test_signer_trait() {
848        use crate::crypto::traits::Signer;
849
850        let private_key = Secp256r1PrivateKey::generate();
851        let message = b"trait test";
852
853        let signature = Signer::sign(&private_key, message);
854        let public_key = Signer::public_key(&private_key);
855
856        assert!(public_key.verify(message, &signature).is_ok());
857    }
858
859    #[test]
860    fn test_verifier_trait() {
861        use crate::crypto::traits::Verifier;
862
863        let private_key = Secp256r1PrivateKey::generate();
864        let public_key = private_key.public_key();
865        let message = b"verifier test";
866        let signature = private_key.sign(message);
867
868        assert!(Verifier::verify(&public_key, message, &signature).is_ok());
869    }
870
871    #[test]
872    fn test_public_key_trait() {
873        use crate::crypto::traits::PublicKey;
874
875        let private_key = Secp256r1PrivateKey::generate();
876        let public_key = private_key.public_key();
877        let bytes = PublicKey::to_bytes(&public_key);
878        let restored = Secp256r1PublicKey::from_bytes(&bytes).unwrap();
879        assert_eq!(public_key.to_bytes(), restored.to_bytes());
880    }
881
882    #[test]
883    fn test_signature_trait() {
884        use crate::crypto::traits::Signature;
885
886        let private_key = Secp256r1PrivateKey::generate();
887        let signature = private_key.sign(b"test");
888        let bytes = Signature::to_bytes(&signature);
889        let restored = Secp256r1Signature::from_bytes(&bytes).unwrap();
890        assert_eq!(signature.to_bytes(), restored.to_bytes());
891    }
892
893    #[test]
894    fn test_private_key_debug() {
895        let private_key = Secp256r1PrivateKey::generate();
896        let debug = format!("{private_key:?}");
897        assert!(debug.contains("REDACTED"));
898        assert!(!debug.contains(&private_key.to_hex()));
899    }
900
901    #[test]
902    fn test_address_derivation() {
903        let private_key = Secp256r1PrivateKey::generate();
904        let public_key = private_key.public_key();
905        let address = public_key.to_address();
906
907        // Address should not be zero
908        assert!(!address.is_zero());
909
910        // Same public key should derive same address
911        let address2 = public_key.to_address();
912        assert_eq!(address, address2);
913    }
914
915    #[test]
916    fn test_uncompressed_bytes() {
917        let private_key = Secp256r1PrivateKey::generate();
918        let public_key = private_key.public_key();
919
920        // Uncompressed should be 65 bytes (0x04 prefix + 64 bytes)
921        let uncompressed = public_key.to_uncompressed_bytes();
922        assert_eq!(uncompressed.len(), 65);
923        assert_eq!(uncompressed[0], 0x04); // Uncompressed point prefix
924    }
925
926    #[test]
927    fn test_private_key_clone() {
928        let private_key = Secp256r1PrivateKey::generate();
929        let cloned = private_key.clone();
930        assert_eq!(private_key.to_bytes(), cloned.to_bytes());
931    }
932
933    #[test]
934    fn test_public_key_equality() {
935        let private_key = Secp256r1PrivateKey::generate();
936        let pk1 = private_key.public_key();
937        let pk2 = private_key.public_key();
938        assert_eq!(pk1, pk2);
939
940        let different = Secp256r1PrivateKey::generate().public_key();
941        assert_ne!(pk1, different);
942    }
943
944    #[test]
945    fn test_signature_verification() {
946        let private_key = Secp256r1PrivateKey::generate();
947        let sig1 = private_key.sign(b"test");
948        let sig2 = private_key.sign(b"test");
949        // Note: ECDSA signatures may have randomness, so they might not be equal
950        // But they should both verify
951        let public_key = private_key.public_key();
952        assert!(public_key.verify(b"test", &sig1).is_ok());
953        assert!(public_key.verify(b"test", &sig2).is_ok());
954    }
955
956    /// The documented drop-clearing guarantee relies on the inner `p256`
957    /// `SigningKey` zeroizing its secret on drop. This compile-time assertion
958    /// pins that contract so the `crypto/mod.rs` docs stay truthful.
959    #[test]
960    fn test_inner_key_zeroizes_on_drop() {
961        fn assert_zeroize_on_drop<T: zeroize::ZeroizeOnDrop>() {}
962        assert_zeroize_on_drop::<SigningKey>();
963    }
964}