atproto_identity/
key.rs

1//! Cryptographic key operations for AT Protocol identity.
2//!
3//! Elliptic curve cryptography for P-256, P-384, and K-256 curves including
4//! key identification, signature validation, and content signing.
5//! - **P-384** (secp384r1/ES384): NIST standard curve, providing higher security than P-256
6//! - **K-256** (secp256k1/ES256K): Bitcoin curve, widely used in blockchain applications
7//!
8//! # Key Operations
9//!
10//! - Key type identification from multibase-encoded DID key strings
11//! - ECDSA signature validation for both public and private keys
12//! - Content signing with private keys
13//! - Cryptographic key generation for private keys
14//! - Public key derivation from private keys
15//! - DID key method prefix handling
16//!
17//! # Example
18//!
19//! ```rust
20//! use atproto_identity::key::{identify_key, generate_key, to_public, validate, sign, KeyType, KeyData};
21//! use elliptic_curve::JwkEcKey;
22//!
23//! fn main() -> Result<(), Box<dyn std::error::Error>> {
24//!   // Identify existing keys
25//!   let key_data = identify_key("did:key:zQ3shNzMp4oaaQ1gQRzCxMGXFrSW3NEM1M9T6KCY9eA7HhyEA")?;
26//!   assert_eq!(*key_data.key_type(), KeyType::K256Public);
27//!
28//!   // Generate new private keys (P-256, P-384, or K-256)
29//!   let p256_key = generate_key(KeyType::P256Private)?;
30//!   let p384_key = generate_key(KeyType::P384Private)?;
31//!   let k256_key = generate_key(KeyType::K256Private)?;
32//!
33//!   // Derive public key from private key
34//!   let p384_public = to_public(&p384_key)?;
35//!   assert_eq!(*p384_public.key_type(), KeyType::P384Public);
36//!
37//!   // Sign and verify with derived keys
38//!   let message = b"Hello AT Protocol!";
39//!   let signature = sign(&p384_key, message)?;
40//!   validate(&p384_public, &signature, message)?;
41//!
42//!   // Convert to JWK format (P-256 and P-384 support JWK)
43//!   let p256_key_data = identify_key("did:key:zDnaeXduWbJ1b1Kgjf3uCdCpMDF1LEDizUiyxAxGwerou3Nh2")?;
44//!   let p256_jwk: JwkEcKey = (&p256_key_data).try_into()?;
45//!   let p384_jwk: JwkEcKey = (&p384_key).try_into()?;
46//!   Ok(())
47//! }
48//! ```
49
50use anyhow::Result;
51use ecdsa::signature::Signer;
52use elliptic_curve::JwkEcKey;
53use elliptic_curve::sec1::ToEncodedPoint;
54
55use crate::errors::KeyError;
56
57#[cfg(feature = "zeroize")]
58use zeroize::{Zeroize, ZeroizeOnDrop};
59
60/// Cryptographic key types supported for AT Protocol identity.
61#[derive(Clone, PartialEq)]
62#[cfg_attr(debug_assertions, derive(Debug))]
63#[cfg_attr(feature = "zeroize", derive(Zeroize, ZeroizeOnDrop))]
64pub enum KeyType {
65    /// A p256 (P-256 / secp256r1 / ES256) public key.
66    /// The multibase / multicodec prefix is 8024.
67    P256Public,
68
69    /// A p256 (P-256 / secp256r1 / ES256) private key.
70    /// The multibase / multicodec prefix is 8626.
71    P256Private,
72
73    /// A p384 (P-384 / secp384r1 / ES384) public key.
74    /// The multibase / multicodec prefix is 1200.
75    P384Public,
76
77    /// A p384 (P-384 / secp384r1 / ES384) private key.
78    /// The multibase / multicodec prefix is 1301.
79    P384Private,
80
81    /// A k256 (K-256 / secp256k1 / ES256K) public key.
82    /// The multibase / multicodec prefix is e701.
83    K256Public,
84
85    /// A k256 (K-256 / secp256k1 / ES256K) private key.
86    /// The multibase / multicodec prefix is 8126.
87    K256Private,
88}
89
90impl std::fmt::Display for KeyType {
91    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92        match self {
93            KeyType::P256Public => write!(f, "P256Public"),
94            KeyType::P256Private => write!(f, "P256Private"),
95            KeyType::P384Public => write!(f, "P384Public"),
96            KeyType::P384Private => write!(f, "P384Private"),
97            KeyType::K256Public => write!(f, "K256Public"),
98            KeyType::K256Private => write!(f, "K256Private"),
99        }
100    }
101}
102
103/// A wrapper for cryptographic key data containing the key type and raw bytes.
104///
105/// This struct encapsulates the result of key identification and provides methods
106/// for accessing the key type and bytes, as well as conversion to JWK format.
107///
108/// When creating variables for instances of this type, they should have the
109/// suffix `key_data`. Additionally the should have the prefix `public_` or
110/// `private_` to indiciate how they are used. Examples include:
111/// * `public_signing_key_data`
112/// * `private_dpop_key_data`
113///
114#[derive(Clone)]
115#[cfg_attr(feature = "zeroize", derive(zeroize::Zeroize, zeroize::ZeroizeOnDrop))]
116pub struct KeyData(pub KeyType, pub Vec<u8>);
117
118impl KeyData {
119    /// Creates a new KeyData instance.
120    pub fn new(key_type: KeyType, bytes: Vec<u8>) -> Self {
121        KeyData(key_type, bytes)
122    }
123
124    /// Returns the key type.
125    pub fn key_type(&self) -> &KeyType {
126        &self.0
127    }
128
129    /// Returns the raw key bytes.
130    pub fn bytes(&self) -> &[u8] {
131        &self.1
132    }
133
134    /// Consumes self and returns the key type and bytes as a tuple.
135    pub fn into_parts(self) -> (KeyType, Vec<u8>) {
136        (self.0.clone(), self.1.clone())
137    }
138}
139
140impl std::fmt::Display for KeyData {
141    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
142        // Get the multicodec prefix based on key type
143        let prefix = match self.key_type() {
144            KeyType::P256Private => [0x86, 0x26],
145            KeyType::P256Public => [0x80, 0x24],
146            KeyType::P384Private => [0x13, 0x01],
147            KeyType::P384Public => [0x12, 0x00],
148            KeyType::K256Private => [0x81, 0x26],
149            KeyType::K256Public => [0xe7, 0x01],
150        };
151
152        // Combine prefix and key bytes
153        let mut multicodec_bytes = Vec::with_capacity(2 + self.bytes().len());
154        multicodec_bytes.extend_from_slice(&prefix);
155        multicodec_bytes.extend_from_slice(self.bytes());
156
157        // Encode using multibase (base58btc)
158        let multibase_encoded = multibase::encode(multibase::Base::Base58Btc, &multicodec_bytes);
159
160        // Add DID key prefix
161        write!(f, "did:key:{}", multibase_encoded)
162    }
163}
164
165/// Trait for providing cryptographic keys by identifier.
166///
167/// This trait defines the interface for key providers that can retrieve private keys
168/// by their identifier. Implementations must be thread-safe to support concurrent access.
169#[async_trait::async_trait]
170pub trait KeyProvider: Send + Sync {
171    /// Retrieves a private key by its identifier.
172    ///
173    /// # Arguments
174    /// * `key_id` - The identifier of the key to retrieve
175    ///
176    /// # Returns
177    /// * `Ok(Some(KeyData))` - If the key was found and successfully retrieved
178    /// * `Ok(None)` - If no key exists for the given identifier
179    /// * `Err(anyhow::Error)` - If an error occurred during key retrieval
180    async fn get_private_key_by_id(&self, key_id: &str) -> Result<Option<KeyData>>;
181}
182
183/// DID key method prefix.
184const DID_METHOD_KEY_PREFIX: &str = "did:key:";
185
186/// Extracts the value portion from a DID key string.
187///
188/// Removes the "did:key:" prefix if present, otherwise returns the original string.
189pub fn did_method_key_value(key: &str) -> &str {
190    match key.strip_prefix(DID_METHOD_KEY_PREFIX) {
191        Some(value) => value,
192        None => key,
193    }
194}
195
196/// Identifies the key type and extracts the key data from a multibase-encoded key.
197///
198/// Returns a KeyData instance containing the key type and the raw key bytes.
199pub fn identify_key(key: &str) -> Result<KeyData, KeyError> {
200    let stripped_key = did_method_key_value(key);
201    let (_, decoded_multibase_key) =
202        multibase::decode(stripped_key).map_err(|error| KeyError::DecodeError { error })?;
203
204    if decoded_multibase_key.len() < 3 {
205        return Err(KeyError::UnidentifiedKeyType);
206    }
207
208    // These values were verified using the following method:
209    //
210    // 1. Use goat to generate p256 and k256 keys to sample.
211    //    `goat key generate -t k256`
212    //
213    // 2. Use `multibase` and `xxd` to view the hex output
214    //    `multibase decode zQ3shj41kYrAKpgMvWFZ8L4uFhQ6P57zpiQEuvL1LWWa8sZqN | xxd`
215    //
216    // See also: https://github.com/bluesky-social/indigo/tree/main/cmd/goat
217    // See also: https://github.com/docknetwork/multibase-cli
218
219    match &decoded_multibase_key[..2] {
220        // P-256 / secp256r1 / ES256 private key
221        [0x86, 0x26] => Ok(KeyData::new(
222            KeyType::P256Private,
223            decoded_multibase_key[2..].to_vec(),
224        )),
225
226        // P-256 / secp256r1 / ES256 public key
227        [0x80, 0x24] => Ok(KeyData::new(
228            KeyType::P256Public,
229            decoded_multibase_key[2..].to_vec(),
230        )),
231
232        // P-384 / secp384r1 / ES384 private key
233        [0x13, 0x01] => Ok(KeyData::new(
234            KeyType::P384Private,
235            decoded_multibase_key[2..].to_vec(),
236        )),
237
238        // P-384 / secp384r1 / ES384 public key
239        [0x12, 0x00] => Ok(KeyData::new(
240            KeyType::P384Public,
241            decoded_multibase_key[2..].to_vec(),
242        )),
243
244        // K-256 / secp256k1 / ES256K private key
245        [0x81, 0x26] => Ok(KeyData::new(
246            KeyType::K256Private,
247            decoded_multibase_key[2..].to_vec(),
248        )),
249
250        // K-256 / secp256k1 / ES256K public key
251        [0xe7, 0x01] => Ok(KeyData::new(
252            KeyType::K256Public,
253            decoded_multibase_key[2..].to_vec(),
254        )),
255
256        _ => Err(KeyError::InvalidMultibaseKeyType {
257            prefix: decoded_multibase_key[..2].to_vec(),
258        }),
259    }
260}
261
262/// Validates a signature against content using the provided key.
263///
264/// Supports both public and private keys for signature verification.
265pub fn validate(key_data: &KeyData, signature: &[u8], content: &[u8]) -> Result<(), KeyError> {
266    match *key_data.key_type() {
267        KeyType::P256Public => {
268            let signature = ecdsa::Signature::from_slice(signature)
269                .map_err(|error| KeyError::SignatureError { error })?;
270            let verifying_key = p256::ecdsa::VerifyingKey::from_sec1_bytes(key_data.bytes())
271                .map_err(|error| KeyError::P256Error { error })?;
272            ecdsa::signature::Verifier::verify(&verifying_key, content, &signature)
273                .map_err(|error| KeyError::ECDSAError { error })
274        }
275        KeyType::P384Public => {
276            let signature = ecdsa::Signature::from_slice(signature)
277                .map_err(|error| KeyError::SignatureError { error })?;
278            let verifying_key = p384::ecdsa::VerifyingKey::from_sec1_bytes(key_data.bytes())
279                .map_err(|error| KeyError::P384Error { error })?;
280            ecdsa::signature::Verifier::verify(&verifying_key, content, &signature)
281                .map_err(|error| KeyError::ECDSAError { error })
282        }
283        KeyType::K256Public => {
284            let signature = ecdsa::Signature::from_slice(signature)
285                .map_err(|error| KeyError::SignatureError { error })?;
286            let verifying_key = k256::ecdsa::VerifyingKey::from_sec1_bytes(key_data.bytes())
287                .map_err(|error| KeyError::K256Error { error })?;
288            ecdsa::signature::Verifier::verify(&verifying_key, content, &signature)
289                .map_err(|error| KeyError::ECDSAError { error })
290        }
291        KeyType::P256Private => {
292            let signature = ecdsa::Signature::from_slice(signature)
293                .map_err(|error| KeyError::SignatureError { error })?;
294            let secret_key: p256::SecretKey =
295                ecdsa::elliptic_curve::SecretKey::from_slice(key_data.bytes())
296                    .map_err(|error| KeyError::SecretKeyError { error })?;
297            let public_key = secret_key.public_key();
298            let verifying_key = p256::ecdsa::VerifyingKey::from(public_key);
299            ecdsa::signature::Verifier::verify(&verifying_key, content, &signature)
300                .map_err(|error| KeyError::ECDSAError { error })
301        }
302        KeyType::P384Private => {
303            let signature = ecdsa::Signature::from_slice(signature)
304                .map_err(|error| KeyError::SignatureError { error })?;
305            let secret_key: p384::SecretKey =
306                ecdsa::elliptic_curve::SecretKey::from_slice(key_data.bytes())
307                    .map_err(|error| KeyError::SecretKeyError { error })?;
308            let public_key = secret_key.public_key();
309            let verifying_key = p384::ecdsa::VerifyingKey::from(public_key);
310            ecdsa::signature::Verifier::verify(&verifying_key, content, &signature)
311                .map_err(|error| KeyError::ECDSAError { error })
312        }
313        KeyType::K256Private => {
314            let signature = ecdsa::Signature::from_slice(signature)
315                .map_err(|error| KeyError::SignatureError { error })?;
316            let secret_key: k256::SecretKey =
317                ecdsa::elliptic_curve::SecretKey::from_slice(key_data.bytes())
318                    .map_err(|error| KeyError::SecretKeyError { error })?;
319            let public_key = secret_key.public_key();
320            let verifying_key = k256::ecdsa::VerifyingKey::from(public_key);
321            ecdsa::signature::Verifier::verify(&verifying_key, content, &signature)
322                .map_err(|error| KeyError::ECDSAError { error })
323        }
324    }
325}
326
327/// Signs content using a private key.
328///
329/// Returns an error if a public key is provided instead of a private key.
330pub fn sign(key_data: &KeyData, content: &[u8]) -> Result<Vec<u8>, KeyError> {
331    match *key_data.key_type() {
332        KeyType::K256Public | KeyType::P256Public | KeyType::P384Public => {
333            Err(KeyError::PrivateKeyRequiredForSignature)
334        }
335        KeyType::P256Private => {
336            let secret_key: p256::SecretKey =
337                ecdsa::elliptic_curve::SecretKey::from_slice(key_data.bytes())
338                    .map_err(|error| KeyError::SecretKeyError { error })?;
339            let signing_key: p256::ecdsa::SigningKey = p256::ecdsa::SigningKey::from(secret_key);
340            let signature: p256::ecdsa::Signature = signing_key
341                .try_sign(content)
342                .map_err(|error| KeyError::ECDSAError { error })?;
343            Ok(signature.to_vec())
344        }
345        KeyType::P384Private => {
346            let secret_key: p384::SecretKey =
347                ecdsa::elliptic_curve::SecretKey::from_slice(key_data.bytes())
348                    .map_err(|error| KeyError::SecretKeyError { error })?;
349            let signing_key: p384::ecdsa::SigningKey = p384::ecdsa::SigningKey::from(secret_key);
350            let signature: p384::ecdsa::Signature = signing_key
351                .try_sign(content)
352                .map_err(|error| KeyError::ECDSAError { error })?;
353            Ok(signature.to_vec())
354        }
355        KeyType::K256Private => {
356            let secret_key: k256::SecretKey =
357                ecdsa::elliptic_curve::SecretKey::from_slice(key_data.bytes())
358                    .map_err(|error| KeyError::SecretKeyError { error })?;
359            let signing_key: k256::ecdsa::SigningKey = k256::ecdsa::SigningKey::from(secret_key);
360            let signature: k256::ecdsa::Signature = signing_key
361                .try_sign(content)
362                .map_err(|error| KeyError::ECDSAError { error })?;
363            Ok(signature.to_vec())
364        }
365    }
366}
367
368impl TryInto<JwkEcKey> for &KeyData {
369    type Error = KeyError;
370
371    fn try_into(self) -> Result<JwkEcKey, Self::Error> {
372        match *self.key_type() {
373            KeyType::P256Public => {
374                let public_key = p256::PublicKey::from_sec1_bytes(self.bytes()).map_err(|e| {
375                    KeyError::JWKConversionFailed {
376                        error: format!("Failed to parse P256 public key: {}", e),
377                    }
378                })?;
379                Ok(public_key.to_jwk())
380            }
381            KeyType::P256Private => {
382                let secret_key = p256::SecretKey::from_slice(self.bytes())
383                    .map_err(|error| KeyError::SecretKeyError { error })?;
384                Ok(secret_key.to_jwk())
385            }
386            KeyType::P384Public => {
387                let public_key = p384::PublicKey::from_sec1_bytes(self.bytes()).map_err(|e| {
388                    KeyError::JWKConversionFailed {
389                        error: format!("Failed to parse P384 public key: {}", e),
390                    }
391                })?;
392                Ok(public_key.to_jwk())
393            }
394            KeyType::P384Private => {
395                let secret_key = p384::SecretKey::from_slice(self.bytes())
396                    .map_err(|error| KeyError::SecretKeyError { error })?;
397                Ok(secret_key.to_jwk())
398            }
399            KeyType::K256Public => {
400                let public_key = k256::PublicKey::from_sec1_bytes(self.bytes()).map_err(|e| {
401                    KeyError::JWKConversionFailed {
402                        error: format!("Failed to parse k256 public key: {}", e),
403                    }
404                })?;
405                Ok(public_key.to_jwk())
406            }
407            KeyType::K256Private => {
408                let secret_key = k256::SecretKey::from_slice(self.bytes())
409                    .map_err(|error| KeyError::SecretKeyError { error })?;
410                Ok(secret_key.to_jwk())
411            }
412        }
413    }
414}
415
416/// Generates a new cryptographic key of the specified type.
417///
418/// # Arguments
419/// * `key_type` - The type of key to generate
420///
421/// # Returns
422/// A `KeyData` containing the generated key material
423///
424/// # Errors
425/// * Returns `KeyError::PublicKeyGenerationNotSupported` for public key types
426/// * Returns `KeyError::SecretKeyError` if key generation fails
427///
428/// # Example
429/// ```rust
430/// use atproto_identity::key::{generate_key, KeyType};
431///
432/// let private_key = generate_key(KeyType::P256Private)?;
433/// assert_eq!(*private_key.key_type(), KeyType::P256Private);
434/// # Ok::<(), atproto_identity::errors::KeyError>(())
435/// ```
436pub fn generate_key(key_type: KeyType) -> Result<KeyData, KeyError> {
437    match key_type {
438        KeyType::P256Private => {
439            let secret_key = p256::SecretKey::random(&mut rand::thread_rng());
440            Ok(KeyData::new(
441                KeyType::P256Private,
442                secret_key.to_bytes().to_vec(),
443            ))
444        }
445        KeyType::P384Private => {
446            let secret_key = p384::SecretKey::random(&mut rand::thread_rng());
447            Ok(KeyData::new(
448                KeyType::P384Private,
449                secret_key.to_bytes().to_vec(),
450            ))
451        }
452        KeyType::K256Private => {
453            let secret_key = k256::SecretKey::random(&mut rand::thread_rng());
454            Ok(KeyData::new(
455                KeyType::K256Private,
456                secret_key.to_bytes().to_vec(),
457            ))
458        }
459        KeyType::P256Public => Err(KeyError::PublicKeyGenerationNotSupported),
460        KeyType::P384Public => Err(KeyError::PublicKeyGenerationNotSupported),
461        KeyType::K256Public => Err(KeyError::PublicKeyGenerationNotSupported),
462    }
463}
464
465/// Derives a public key from a private key, or returns the key if it's already public.
466///
467/// # Arguments
468/// * `key_data` - The key data to convert to public key format
469///
470/// # Returns
471/// A `KeyData` containing the corresponding public key
472///
473/// # Errors
474/// * Returns `KeyError::SecretKeyError` if private key parsing fails
475///
476/// # Example
477/// ```rust
478/// use atproto_identity::key::{generate_key, to_public, KeyType};
479///
480/// let private_key = generate_key(KeyType::P256Private)?;
481/// let public_key = to_public(&private_key)?;
482/// assert_eq!(*public_key.key_type(), KeyType::P256Public);
483///
484/// // Works with public keys too
485/// let same_public_key = to_public(&public_key)?;
486/// assert_eq!(public_key.bytes(), same_public_key.bytes());
487/// # Ok::<(), atproto_identity::errors::KeyError>(())
488/// ```
489pub fn to_public(key_data: &KeyData) -> Result<KeyData, KeyError> {
490    match key_data.key_type() {
491        KeyType::P256Private => {
492            let secret_key: p256::SecretKey =
493                ecdsa::elliptic_curve::SecretKey::from_slice(key_data.bytes())
494                    .map_err(|error| KeyError::SecretKeyError { error })?;
495            let public_key = secret_key.public_key();
496            let compressed = public_key.to_encoded_point(true);
497            let public_key_bytes = compressed.to_bytes();
498            Ok(KeyData::new(KeyType::P256Public, public_key_bytes.to_vec()))
499        }
500        KeyType::P384Private => {
501            let secret_key: p384::SecretKey =
502                ecdsa::elliptic_curve::SecretKey::from_slice(key_data.bytes())
503                    .map_err(|error| KeyError::SecretKeyError { error })?;
504            let public_key = secret_key.public_key();
505            let compressed = public_key.to_encoded_point(true);
506            let public_key_bytes = compressed.to_bytes();
507            Ok(KeyData::new(KeyType::P384Public, public_key_bytes.to_vec()))
508        }
509        KeyType::K256Private => {
510            let secret_key: k256::SecretKey =
511                ecdsa::elliptic_curve::SecretKey::from_slice(key_data.bytes())
512                    .map_err(|error| KeyError::SecretKeyError { error })?;
513            let public_key = secret_key.public_key();
514            let public_key_bytes = public_key.to_sec1_bytes();
515            Ok(KeyData::new(KeyType::K256Public, public_key_bytes.to_vec()))
516        }
517        KeyType::P256Public | KeyType::P384Public | KeyType::K256Public => {
518            // Return a clone of the existing public key
519            Ok(key_data.clone())
520        }
521    }
522}
523
524#[cfg(test)]
525mod tests {
526    use super::*;
527
528    #[test]
529    fn test_identify_key() {
530        // Test valid K256 private key (repeat 4 times as in original test)
531        for _ in 0..4 {
532            let result = identify_key("z3vLVqpQveB3w8G6MQsLVseJ1Z2E1JyQzUj6WgRYNNwB9jdE");
533            assert!(result.is_ok());
534            let key_data = result.unwrap();
535            assert_eq!(*key_data.key_type(), KeyType::K256Private);
536        }
537
538        // Test invalid multibase encoding
539        assert!(matches!(
540            identify_key("asdasdasd"),
541            Err(KeyError::DecodeError { .. })
542        ));
543
544        // Test invalid key type prefix
545        assert!(matches!(
546            identify_key("z4vLVqpQveB3w8G6MQsLVseJ1Z2E1JyQzUj6WgRYNNwB9jdE"),
547            Err(KeyError::InvalidMultibaseKeyType { .. })
548        ));
549    }
550
551    #[test]
552    fn test_sign_p256() -> Result<()> {
553        let private_key = "did:key:z42tnbHmmnhF11nwSnp5kQJbcZQw2Vbw5WF3ABDSxPtDgU2o";
554        let public_key = "did:key:zDnaeXduWbJ1b1Kgjf3uCdCpMDF1LEDizUiyxAxGwerou3Nh2";
555
556        let private_key_data = identify_key(private_key);
557        assert!(private_key_data.is_ok());
558        let private_key_data = private_key_data.unwrap();
559        assert_eq!(*private_key_data.key_type(), KeyType::P256Private);
560
561        let public_key_data = identify_key(public_key);
562        assert!(public_key_data.is_ok());
563        let public_key_data = public_key_data.unwrap();
564        assert_eq!(*public_key_data.key_type(), KeyType::P256Public);
565
566        let content = "hello world".as_bytes();
567
568        let signature = sign(&private_key_data, content);
569        assert!(signature.is_ok());
570        let signature = signature.unwrap();
571
572        {
573            let validation = validate(&public_key_data, &signature, content);
574            assert!(validation.is_ok());
575        }
576        {
577            let validation = validate(&private_key_data, &signature, content);
578            assert!(validation.is_ok());
579        }
580        Ok(())
581    }
582
583    #[test]
584    fn test_sign_k256() -> Result<()> {
585        let private_key = "did:key:z3vLY4nbXy2rV4Qr65gUtfnSF3A8Be7gmYzUiCX6eo2PR1Rt";
586        let public_key = "did:key:zQ3shNzMp4oaaQ1gQRzCxMGXFrSW3NEM1M9T6KCY9eA7HhyEA";
587
588        let private_key_data = identify_key(private_key);
589        assert!(private_key_data.is_ok());
590        let private_key_data = private_key_data.unwrap();
591        assert_eq!(*private_key_data.key_type(), KeyType::K256Private);
592
593        let public_key_data = identify_key(public_key);
594        assert!(public_key_data.is_ok());
595        let public_key_data = public_key_data.unwrap();
596        assert_eq!(*public_key_data.key_type(), KeyType::K256Public);
597
598        let content = "hello world".as_bytes();
599
600        let signature = sign(&private_key_data, content);
601        assert!(signature.is_ok());
602        let signature = signature.unwrap();
603
604        {
605            let validation = validate(&public_key_data, &signature, content);
606            assert!(validation.is_ok());
607        }
608        {
609            let validation = validate(&private_key_data, &signature, content);
610            assert!(validation.is_ok());
611        }
612        Ok(())
613    }
614
615    #[test]
616    fn test_to_jwk_p256() -> Result<()> {
617        let private_key = "did:key:z42tnbHmmnhF11nwSnp5kQJbcZQw2Vbw5WF3ABDSxPtDgU2o";
618        let public_key = "did:key:zDnaeXduWbJ1b1Kgjf3uCdCpMDF1LEDizUiyxAxGwerou3Nh2";
619
620        let private_key_data = identify_key(private_key);
621        assert!(private_key_data.is_ok());
622        let private_key_data = private_key_data.unwrap();
623        assert_eq!(*private_key_data.key_type(), KeyType::P256Private);
624
625        let public_key_data = identify_key(public_key);
626        assert!(public_key_data.is_ok());
627        let public_key_data = public_key_data.unwrap();
628        assert_eq!(*public_key_data.key_type(), KeyType::P256Public);
629
630        // Test private key to JWK conversion
631        let private_jwk: Result<elliptic_curve::JwkEcKey, _> = (&private_key_data).try_into();
632        assert!(private_jwk.is_ok());
633
634        // Test public key to JWK conversion
635        let public_jwk: Result<elliptic_curve::JwkEcKey, _> = (&public_key_data).try_into();
636        assert!(public_jwk.is_ok());
637
638        Ok(())
639    }
640
641    #[test]
642    fn test_to_jwk_k256_supported() -> Result<()> {
643        let private_key = "did:key:z3vLY4nbXy2rV4Qr65gUtfnSF3A8Be7gmYzUiCX6eo2PR1Rt";
644        let public_key = "did:key:zQ3shNzMp4oaaQ1gQRzCxMGXFrSW3NEM1M9T6KCY9eA7HhyEA";
645
646        let private_key_data = identify_key(private_key);
647        assert!(private_key_data.is_ok());
648        let private_key_data = private_key_data.unwrap();
649        assert_eq!(*private_key_data.key_type(), KeyType::K256Private);
650
651        let public_key_data = identify_key(public_key);
652        assert!(public_key_data.is_ok());
653        let public_key_data = public_key_data.unwrap();
654        assert_eq!(*public_key_data.key_type(), KeyType::K256Public);
655
656        // Test that K256 keys successfully convert to JWK format
657        let private_jwk: Result<elliptic_curve::JwkEcKey, _> = (&private_key_data).try_into();
658        assert!(private_jwk.is_ok());
659        let private_jwk = private_jwk.unwrap();
660        assert_eq!(private_jwk.crv(), "secp256k1");
661
662        let public_jwk: Result<elliptic_curve::JwkEcKey, _> = (&public_key_data).try_into();
663        assert!(public_jwk.is_ok());
664        let public_jwk = public_jwk.unwrap();
665        assert_eq!(public_jwk.crv(), "secp256k1");
666
667        Ok(())
668    }
669
670    #[test]
671    fn test_try_into_jwk_keydata() -> Result<()> {
672        let private_key = "did:key:z42tnbHmmnhF11nwSnp5kQJbcZQw2Vbw5WF3ABDSxPtDgU2o";
673        let public_key = "did:key:zDnaeXduWbJ1b1Kgjf3uCdCpMDF1LEDizUiyxAxGwerou3Nh2";
674
675        let private_key_data = identify_key(private_key);
676        assert!(private_key_data.is_ok());
677        let private_key_data = private_key_data.unwrap();
678        assert_eq!(*private_key_data.key_type(), KeyType::P256Private);
679
680        let public_key_data = identify_key(public_key);
681        assert!(public_key_data.is_ok());
682        let public_key_data = public_key_data.unwrap();
683        assert_eq!(*public_key_data.key_type(), KeyType::P256Public);
684
685        // Test TryInto with KeyData directly
686        let private_jwk: Result<JwkEcKey, KeyError> = (&private_key_data).try_into();
687        assert!(private_jwk.is_ok());
688
689        let public_jwk: Result<JwkEcKey, KeyError> = (&public_key_data).try_into();
690        assert!(public_jwk.is_ok());
691
692        Ok(())
693    }
694
695    #[test]
696    fn test_generate_key_p256_private() -> Result<()> {
697        let key_data = generate_key(KeyType::P256Private)?;
698        assert_eq!(*key_data.key_type(), KeyType::P256Private);
699        assert_eq!(key_data.bytes().len(), 32); // P-256 private keys are 32 bytes
700
701        // Test that we can sign with the generated key
702        let content = "test content".as_bytes();
703        let signature = sign(&key_data, content)?;
704        let validation = validate(&key_data, &signature, content);
705        assert!(validation.is_ok());
706
707        Ok(())
708    }
709
710    #[test]
711    fn test_generate_key_k256_private() -> Result<()> {
712        let key_data = generate_key(KeyType::K256Private)?;
713        assert_eq!(*key_data.key_type(), KeyType::K256Private);
714        assert_eq!(key_data.bytes().len(), 32); // K-256 private keys are 32 bytes
715
716        // Test that we can sign with the generated key
717        let content = "test content".as_bytes();
718        let signature = sign(&key_data, content)?;
719        let validation = validate(&key_data, &signature, content);
720        assert!(validation.is_ok());
721
722        Ok(())
723    }
724
725    #[test]
726    fn test_generate_key_public_not_supported() {
727        let result = generate_key(KeyType::P256Public);
728        assert!(matches!(
729            result,
730            Err(KeyError::PublicKeyGenerationNotSupported)
731        ));
732
733        let result = generate_key(KeyType::K256Public);
734        assert!(matches!(
735            result,
736            Err(KeyError::PublicKeyGenerationNotSupported)
737        ));
738    }
739
740    #[test]
741    fn test_generate_key_uniqueness() -> Result<()> {
742        // Generate multiple keys and ensure they're different
743        let key1 = generate_key(KeyType::P256Private)?;
744        let key2 = generate_key(KeyType::P256Private)?;
745        assert_ne!(key1.bytes(), key2.bytes());
746
747        let key3 = generate_key(KeyType::K256Private)?;
748        let key4 = generate_key(KeyType::K256Private)?;
749        assert_ne!(key3.bytes(), key4.bytes());
750
751        Ok(())
752    }
753
754    #[test]
755    fn test_keydata_display_p256_private() -> Result<()> {
756        // Generate a P-256 private key
757        let original_key = generate_key(KeyType::P256Private)?;
758
759        // Convert to string using Display trait
760        let key_string = format!("{}", original_key);
761
762        // Verify it has the correct prefix
763        assert!(key_string.starts_with("did:key:"));
764
765        // Parse it back using identify_key
766        let parsed_key = identify_key(&key_string)?;
767
768        // Verify round-trip: key type should match
769        assert_eq!(original_key.key_type(), parsed_key.key_type());
770
771        // Verify round-trip: bytes should match
772        assert_eq!(original_key.bytes(), parsed_key.bytes());
773
774        // Test signing and verification with both keys
775        let content = "test message for p256".as_bytes();
776
777        // Sign with original key
778        let signature = sign(&original_key, content)?;
779
780        // Verify with original key
781        validate(&original_key, &signature, content)?;
782
783        // Verify with parsed key
784        validate(&parsed_key, &signature, content)?;
785
786        // Sign with parsed key
787        let signature2 = sign(&parsed_key, content)?;
788
789        // Verify both signatures are the same (deterministic signing)
790        // Note: ECDSA signatures may not be deterministic, so we just verify both work
791        validate(&original_key, &signature2, content)?;
792        validate(&parsed_key, &signature2, content)?;
793
794        Ok(())
795    }
796
797    #[test]
798    fn test_keydata_display_k256_private() -> Result<()> {
799        // Generate a K-256 private key
800        let original_key = generate_key(KeyType::K256Private)?;
801
802        // Convert to string using Display trait
803        let key_string = format!("{}", original_key);
804
805        // Verify it has the correct prefix
806        assert!(key_string.starts_with("did:key:"));
807
808        // Parse it back using identify_key
809        let parsed_key = identify_key(&key_string)?;
810
811        // Verify round-trip: key type should match
812        assert_eq!(original_key.key_type(), parsed_key.key_type());
813
814        // Verify round-trip: bytes should match
815        assert_eq!(original_key.bytes(), parsed_key.bytes());
816
817        // Test signing and verification with both keys
818        let content = "test message for k256".as_bytes();
819
820        // Sign with original key
821        let signature = sign(&original_key, content)?;
822
823        // Verify with original key
824        validate(&original_key, &signature, content)?;
825
826        // Verify with parsed key
827        validate(&parsed_key, &signature, content)?;
828
829        // Sign with parsed key
830        let signature2 = sign(&parsed_key, content)?;
831
832        // Verify both signatures work
833        validate(&original_key, &signature2, content)?;
834        validate(&parsed_key, &signature2, content)?;
835
836        Ok(())
837    }
838
839    #[test]
840    fn test_keydata_display_existing_keys() -> Result<()> {
841        // Test with known existing keys from other tests
842        let p256_private_key = "did:key:z42tnbHmmnhF11nwSnp5kQJbcZQw2Vbw5WF3ABDSxPtDgU2o";
843        let k256_private_key = "did:key:z3vLY4nbXy2rV4Qr65gUtfnSF3A8Be7gmYzUiCX6eo2PR1Rt";
844
845        // Parse and re-serialize P-256 key
846        let parsed_p256 = identify_key(p256_private_key)?;
847        let reserialized_p256 = format!("{}", parsed_p256);
848        assert_eq!(p256_private_key, reserialized_p256);
849
850        // Parse and re-serialize K-256 key
851        let parsed_k256 = identify_key(k256_private_key)?;
852        let reserialized_k256 = format!("{}", parsed_k256);
853        assert_eq!(k256_private_key, reserialized_k256);
854
855        Ok(())
856    }
857
858    #[test]
859    fn test_keydata_display_cross_verification() -> Result<()> {
860        // Generate keys and test cross-verification scenarios
861        let p256_key = generate_key(KeyType::P256Private)?;
862        let k256_key = generate_key(KeyType::K256Private)?;
863
864        // Serialize both keys
865        let p256_string = format!("{}", p256_key);
866        let k256_string = format!("{}", k256_key);
867
868        // Verify they produce different strings
869        assert_ne!(p256_string, k256_string);
870
871        // Parse them back
872        let parsed_p256 = identify_key(&p256_string)?;
873        let parsed_k256 = identify_key(&k256_string)?;
874
875        // Verify types are preserved
876        assert_eq!(*parsed_p256.key_type(), KeyType::P256Private);
877        assert_eq!(*parsed_k256.key_type(), KeyType::K256Private);
878
879        // Test that keys from different curves can't be used interchangeably
880        let content = "cross verification test".as_bytes();
881
882        // Sign with P-256
883        let p256_signature = sign(&p256_key, content)?;
884
885        // Sign with K-256
886        let k256_signature = sign(&k256_key, content)?;
887
888        // Verify P-256 signature with P-256 key (should work)
889        assert!(validate(&p256_key, &p256_signature, content).is_ok());
890        assert!(validate(&parsed_p256, &p256_signature, content).is_ok());
891
892        // Verify K-256 signature with K-256 key (should work)
893        assert!(validate(&k256_key, &k256_signature, content).is_ok());
894        assert!(validate(&parsed_k256, &k256_signature, content).is_ok());
895
896        // Cross-verification should fail
897        assert!(validate(&p256_key, &k256_signature, content).is_err());
898        assert!(validate(&k256_key, &p256_signature, content).is_err());
899
900        Ok(())
901    }
902
903    #[test]
904    fn test_keydata_display_format_consistency() -> Result<()> {
905        // Test that the Display format matches expected patterns
906        let p256_key = generate_key(KeyType::P256Private)?;
907        let k256_key = generate_key(KeyType::K256Private)?;
908
909        let p256_string = format!("{}", p256_key);
910        let k256_string = format!("{}", k256_key);
911
912        // Verify format structure
913        assert!(p256_string.starts_with("did:key:z"));
914        assert!(k256_string.starts_with("did:key:z"));
915
916        // Verify they can be parsed
917        let _parsed_p256 = identify_key(&p256_string)?;
918        let _parsed_k256 = identify_key(&k256_string)?;
919
920        // Verify string lengths are reasonable (multibase encoded keys should be consistent length)
921        // P-256 private keys: 2 bytes prefix + 32 bytes key = 34 bytes -> ~46 chars base58 + "did:key:z" prefix
922        assert!(p256_string.len() > 50 && p256_string.len() < 60);
923
924        // K-256 private keys: 2 bytes prefix + 32 bytes key = 34 bytes -> ~46 chars base58 + "did:key:z" prefix
925        assert!(k256_string.len() > 50 && k256_string.len() < 60);
926
927        Ok(())
928    }
929
930    #[test]
931    fn test_complete_workflow_demonstration() -> Result<()> {
932        println!("\n=== KeyData Display Implementation Test ===");
933
934        // Step 1: Generate keys
935        println!("1. Generating keys...");
936        let p256_key = generate_key(KeyType::P256Private)?;
937        let k256_key = generate_key(KeyType::K256Private)?;
938
939        // Step 2: Display keys (serialize)
940        println!("2. Serializing keys to DID format...");
941        let p256_did = format!("{}", p256_key);
942        let k256_did = format!("{}", k256_key);
943        println!("   P-256 DID: {}", p256_did);
944        println!("   K-256 DID: {}", k256_did);
945
946        // Step 3: Parse keys back (identify)
947        println!("3. Parsing DIDs back to KeyData...");
948        let parsed_p256 = identify_key(&p256_did)?;
949        let parsed_k256 = identify_key(&k256_did)?;
950        println!("   P-256 parsed successfully: {:?}", parsed_p256.key_type());
951        println!("   K-256 parsed successfully: {:?}", parsed_k256.key_type());
952
953        // Step 4: Verify round-trip
954        println!("4. Verifying round-trip integrity...");
955        assert_eq!(p256_key.bytes(), parsed_p256.bytes());
956        assert_eq!(k256_key.bytes(), parsed_k256.bytes());
957        println!("   Round-trip successful for both keys!");
958
959        // Step 5: Sign and verify
960        println!("5. Testing signing and verification...");
961        let test_data = "Hello AT Protocol!".as_bytes();
962
963        // Sign with original keys
964        let p256_signature = sign(&p256_key, test_data)?;
965        let k256_signature = sign(&k256_key, test_data)?;
966
967        // Verify with parsed keys
968        validate(&parsed_p256, &p256_signature, test_data)?;
969        validate(&parsed_k256, &k256_signature, test_data)?;
970        println!("   Signatures verified successfully with parsed keys!");
971
972        // Step 6: Cross-verification should fail
973        println!("6. Testing cross-curve verification (should fail)...");
974        assert!(validate(&parsed_p256, &k256_signature, test_data).is_err());
975        assert!(validate(&parsed_k256, &p256_signature, test_data).is_err());
976        println!("   Cross-curve verification correctly failed!");
977
978        println!("=== All tests completed successfully! ===\n");
979
980        Ok(())
981    }
982
983    #[test]
984    fn test_to_public_p256() -> Result<()> {
985        // Generate a P-256 private key
986        let private_key = generate_key(KeyType::P256Private)?;
987
988        // Convert to public key
989        let public_key = to_public(&private_key)?;
990
991        // Verify the key type is correct
992        assert_eq!(*public_key.key_type(), KeyType::P256Public);
993
994        // Test that the derived public key can verify signatures from the private key
995        let content = "test message for p256 public key derivation".as_bytes();
996        let signature = sign(&private_key, content)?;
997
998        // Public key should be able to verify the signature
999        validate(&public_key, &signature, content)?;
1000
1001        // Test that the public key produces a valid DID string
1002        let public_key_did = format!("{}", public_key);
1003        assert!(public_key_did.starts_with("did:key:"));
1004
1005        // Parse the DID back and verify it's the same
1006        let parsed_public_key = identify_key(&public_key_did)?;
1007        assert_eq!(*parsed_public_key.key_type(), KeyType::P256Public);
1008        assert_eq!(public_key.bytes(), parsed_public_key.bytes());
1009
1010        Ok(())
1011    }
1012
1013    #[test]
1014    fn test_to_public_k256() -> Result<()> {
1015        // Generate a K-256 private key
1016        let private_key = generate_key(KeyType::K256Private)?;
1017
1018        // Convert to public key
1019        let public_key = to_public(&private_key)?;
1020
1021        // Verify the key type is correct
1022        assert_eq!(*public_key.key_type(), KeyType::K256Public);
1023
1024        // Test that the derived public key can verify signatures from the private key
1025        let content = "test message for k256 public key derivation".as_bytes();
1026        let signature = sign(&private_key, content)?;
1027
1028        // Public key should be able to verify the signature
1029        validate(&public_key, &signature, content)?;
1030
1031        // Test that the public key produces a valid DID string
1032        let public_key_did = format!("{}", public_key);
1033        assert!(public_key_did.starts_with("did:key:"));
1034
1035        // Parse the DID back and verify it's the same
1036        let parsed_public_key = identify_key(&public_key_did)?;
1037        assert_eq!(*parsed_public_key.key_type(), KeyType::K256Public);
1038        assert_eq!(public_key.bytes(), parsed_public_key.bytes());
1039
1040        Ok(())
1041    }
1042
1043    #[test]
1044    fn test_to_public_with_public_keys() -> Result<()> {
1045        // Test that passing a public key returns the same key
1046        let p256_private = generate_key(KeyType::P256Private)?;
1047        let p256_public = to_public(&p256_private)?;
1048
1049        // Calling to_public on a public key should return the same key
1050        let result = to_public(&p256_public)?;
1051        assert_eq!(*result.key_type(), KeyType::P256Public);
1052        assert_eq!(p256_public.bytes(), result.bytes());
1053
1054        let k256_private = generate_key(KeyType::K256Private)?;
1055        let k256_public = to_public(&k256_private)?;
1056
1057        let result = to_public(&k256_public)?;
1058        assert_eq!(*result.key_type(), KeyType::K256Public);
1059        assert_eq!(k256_public.bytes(), result.bytes());
1060
1061        Ok(())
1062    }
1063
1064    #[test]
1065    fn test_to_public_existing_keys() -> Result<()> {
1066        // Test with known private keys to ensure consistent behavior
1067        let p256_private_key = "did:key:z42tj8ZrAza9WkewDELwWMN37TS3coEbGdZh8bp1URfMVnpx";
1068        let k256_private_key = "did:key:z3vLW46Z1UHwnr7vN33MoFt2sBQDQagn9HTvWnsQDHegUixP";
1069
1070        // Parse the private keys
1071        let parsed_p256_private = identify_key(p256_private_key)?;
1072        let parsed_k256_private = identify_key(k256_private_key)?;
1073
1074        // Convert to public keys
1075        let p256_public = to_public(&parsed_p256_private)?;
1076        let k256_public = to_public(&parsed_k256_private)?;
1077
1078        // Verify types
1079        assert_eq!(*p256_public.key_type(), KeyType::P256Public);
1080        assert_eq!(*k256_public.key_type(), KeyType::K256Public);
1081
1082        // Test signing and verification
1083        let content = "test with existing keys".as_bytes();
1084
1085        let p256_signature = sign(&parsed_p256_private, content)?;
1086        let k256_signature = sign(&parsed_k256_private, content)?;
1087
1088        // Verify with derived public keys
1089        validate(&p256_public, &p256_signature, content)?;
1090        validate(&k256_public, &k256_signature, content)?;
1091
1092        Ok(())
1093    }
1094
1095    #[test]
1096    fn test_to_public_comprehensive_workflow() -> Result<()> {
1097        println!("\n=== Public Key Derivation Test ===");
1098
1099        // Generate private keys
1100        println!("1. Generating private keys...");
1101        let p256_private = generate_key(KeyType::P256Private)?;
1102        let k256_private = generate_key(KeyType::K256Private)?;
1103
1104        // Derive public keys
1105        println!("2. Deriving public keys...");
1106        let p256_public = to_public(&p256_private)?;
1107        let k256_public = to_public(&k256_private)?;
1108
1109        // Serialize all keys
1110        println!("3. Serializing keys to DID format...");
1111        let p256_private_did = format!("{}", p256_private);
1112        let p256_public_did = format!("{}", p256_public);
1113        let k256_private_did = format!("{}", k256_private);
1114        let k256_public_did = format!("{}", k256_public);
1115
1116        println!("   P-256 Private: {}", p256_private_did);
1117        println!("   P-256 Public:  {}", p256_public_did);
1118        println!("   K-256 Private: {}", k256_private_did);
1119        println!("   K-256 Public:  {}", k256_public_did);
1120
1121        // Verify different DID patterns
1122        assert_ne!(p256_private_did, p256_public_did);
1123        assert_ne!(k256_private_did, k256_public_did);
1124        assert_ne!(p256_public_did, k256_public_did);
1125
1126        // Test signing and verification
1127        println!("4. Testing signature verification...");
1128        let test_data = "Public key derivation test data".as_bytes();
1129
1130        let p256_signature = sign(&p256_private, test_data)?;
1131        let k256_signature = sign(&k256_private, test_data)?;
1132
1133        // Verify with derived public keys
1134        validate(&p256_public, &p256_signature, test_data)?;
1135        validate(&k256_public, &k256_signature, test_data)?;
1136        println!("   Signatures verified successfully with derived public keys!");
1137
1138        // Parse public key DIDs and re-verify
1139        println!("5. Testing DID round-trip with public keys...");
1140        let parsed_p256_public = identify_key(&p256_public_did)?;
1141        let parsed_k256_public = identify_key(&k256_public_did)?;
1142
1143        validate(&parsed_p256_public, &p256_signature, test_data)?;
1144        validate(&parsed_k256_public, &k256_signature, test_data)?;
1145        println!("   Parsed public keys also verify signatures correctly!");
1146
1147        println!("=== Public key derivation workflow completed successfully! ===\n");
1148
1149        Ok(())
1150    }
1151
1152    #[test]
1153    fn test_to_public_key_properties() -> Result<()> {
1154        // Test that derived public keys have expected properties
1155        let p256_private = generate_key(KeyType::P256Private)?;
1156        let k256_private = generate_key(KeyType::K256Private)?;
1157
1158        let p256_public = to_public(&p256_private)?;
1159        let k256_public = to_public(&k256_private)?;
1160
1161        // P-256 public keys should be 65 bytes (uncompressed) or 33 bytes (compressed)
1162        // SEC1 format is typically uncompressed for public keys: 0x04 + 32 bytes x + 32 bytes y
1163        assert!(p256_public.bytes().len() == 65 || p256_public.bytes().len() == 33);
1164
1165        // K-256 public keys should also be 65 bytes (uncompressed) or 33 bytes (compressed)
1166        assert!(k256_public.bytes().len() == 65 || k256_public.bytes().len() == 33);
1167
1168        // Test that multiple derivations from the same private key produce the same public key
1169        let p256_public2 = to_public(&p256_private)?;
1170        let k256_public2 = to_public(&k256_private)?;
1171
1172        assert_eq!(p256_public.bytes(), p256_public2.bytes());
1173        assert_eq!(k256_public.bytes(), k256_public2.bytes());
1174
1175        Ok(())
1176    }
1177
1178    #[test]
1179    fn test_to_public_with_existing_public_keys() -> Result<()> {
1180        // Test with known public keys from the test suite
1181        let p256_public_key = "did:key:zDnaeXduWbJ1b1Kgjf3uCdCpMDF1LEDizUiyxAxGwerou3Nh2";
1182        let k256_public_key = "did:key:zQ3shNzMp4oaaQ1gQRzCxMGXFrSW3NEM1M9T6KCY9eA7HhyEA";
1183
1184        // Parse the public keys
1185        let parsed_p256_public = identify_key(p256_public_key)?;
1186        let parsed_k256_public = identify_key(k256_public_key)?;
1187
1188        // Verify they are public keys
1189        assert_eq!(*parsed_p256_public.key_type(), KeyType::P256Public);
1190        assert_eq!(*parsed_k256_public.key_type(), KeyType::K256Public);
1191
1192        // Calling to_public should return the same keys
1193        let same_p256_public = to_public(&parsed_p256_public)?;
1194        let same_k256_public = to_public(&parsed_k256_public)?;
1195
1196        // Verify they are identical
1197        assert_eq!(*same_p256_public.key_type(), KeyType::P256Public);
1198        assert_eq!(*same_k256_public.key_type(), KeyType::K256Public);
1199        assert_eq!(parsed_p256_public.bytes(), same_p256_public.bytes());
1200        assert_eq!(parsed_k256_public.bytes(), same_k256_public.bytes());
1201
1202        // Verify they serialize to the same DID strings
1203        assert_eq!(format!("{}", same_p256_public), p256_public_key);
1204        assert_eq!(format!("{}", same_k256_public), k256_public_key);
1205
1206        Ok(())
1207    }
1208
1209    // ===== P-384 SPECIFIC TESTS =====
1210
1211    #[test]
1212    fn test_generate_key_p384_private() -> Result<()> {
1213        let key_data = generate_key(KeyType::P384Private)?;
1214        assert_eq!(*key_data.key_type(), KeyType::P384Private);
1215        assert_eq!(key_data.bytes().len(), 48); // P-384 private keys are 48 bytes
1216
1217        // Test that we can sign with the generated key
1218        let content = "test content for p384".as_bytes();
1219        let signature = sign(&key_data, content)?;
1220        let validation = validate(&key_data, &signature, content);
1221        assert!(validation.is_ok());
1222
1223        Ok(())
1224    }
1225
1226    #[test]
1227    fn test_generate_key_p384_public_not_supported() {
1228        let result = generate_key(KeyType::P384Public);
1229        assert!(matches!(
1230            result,
1231            Err(KeyError::PublicKeyGenerationNotSupported)
1232        ));
1233    }
1234
1235    #[test]
1236    fn test_generate_key_p384_uniqueness() -> Result<()> {
1237        // Generate multiple P-384 keys and ensure they're different
1238        let key1 = generate_key(KeyType::P384Private)?;
1239        let key2 = generate_key(KeyType::P384Private)?;
1240        assert_ne!(key1.bytes(), key2.bytes());
1241
1242        Ok(())
1243    }
1244
1245    #[test]
1246    fn test_sign_and_validate_p384() -> Result<()> {
1247        // Generate a P-384 private key
1248        let private_key = generate_key(KeyType::P384Private)?;
1249
1250        // Derive the corresponding public key
1251        let public_key = to_public(&private_key)?;
1252        assert_eq!(*public_key.key_type(), KeyType::P384Public);
1253
1254        let content = "hello world p384 test".as_bytes();
1255
1256        // Sign with private key
1257        let signature = sign(&private_key, content)?;
1258        assert!(!signature.is_empty());
1259
1260        // Verify with public key
1261        validate(&public_key, &signature, content)?;
1262
1263        // Verify with private key (should also work)
1264        validate(&private_key, &signature, content)?;
1265
1266        // Test signature verification fails with wrong content
1267        let wrong_content = "wrong content".as_bytes();
1268        assert!(validate(&public_key, &signature, wrong_content).is_err());
1269
1270        Ok(())
1271    }
1272
1273    #[test]
1274    fn test_p384_keydata_display_round_trip() -> Result<()> {
1275        // Generate a P-384 private key
1276        let original_key = generate_key(KeyType::P384Private)?;
1277
1278        // Convert to string using Display trait
1279        let key_string = format!("{}", original_key);
1280
1281        // Verify it has the correct prefix
1282        assert!(key_string.starts_with("did:key:"));
1283
1284        // Parse it back using identify_key
1285        let parsed_key = identify_key(&key_string)?;
1286
1287        // Verify round-trip: key type should match
1288        assert_eq!(original_key.key_type(), parsed_key.key_type());
1289
1290        // Verify round-trip: bytes should match
1291        assert_eq!(original_key.bytes(), parsed_key.bytes());
1292
1293        // Test signing and verification with both keys
1294        let content = "test message for p384 round trip".as_bytes();
1295
1296        // Sign with original key
1297        let signature = sign(&original_key, content)?;
1298
1299        // Verify with original key
1300        validate(&original_key, &signature, content)?;
1301
1302        // Verify with parsed key
1303        validate(&parsed_key, &signature, content)?;
1304
1305        // Sign with parsed key
1306        let signature2 = sign(&parsed_key, content)?;
1307
1308        // Verify both signatures work
1309        validate(&original_key, &signature2, content)?;
1310        validate(&parsed_key, &signature2, content)?;
1311
1312        Ok(())
1313    }
1314
1315    #[test]
1316    fn test_p384_to_public_key_derivation() -> Result<()> {
1317        // Generate a P-384 private key
1318        let private_key = generate_key(KeyType::P384Private)?;
1319
1320        // Convert to public key
1321        let public_key = to_public(&private_key)?;
1322
1323        // Verify the key type is correct
1324        assert_eq!(*public_key.key_type(), KeyType::P384Public);
1325
1326        // Test that the derived public key can verify signatures from the private key
1327        let content = "test message for p384 public key derivation".as_bytes();
1328        let signature = sign(&private_key, content)?;
1329
1330        // Public key should be able to verify the signature
1331        validate(&public_key, &signature, content)?;
1332
1333        // Test that the public key produces a valid DID string
1334        let public_key_did = format!("{}", public_key);
1335        assert!(public_key_did.starts_with("did:key:"));
1336
1337        // Parse the DID back and verify it's the same
1338        let parsed_public_key = identify_key(&public_key_did)?;
1339        assert_eq!(*parsed_public_key.key_type(), KeyType::P384Public);
1340        assert_eq!(public_key.bytes(), parsed_public_key.bytes());
1341
1342        // Calling to_public on a public key should return the same key
1343        let result = to_public(&public_key)?;
1344        assert_eq!(*result.key_type(), KeyType::P384Public);
1345        assert_eq!(public_key.bytes(), result.bytes());
1346
1347        Ok(())
1348    }
1349
1350    #[test]
1351    fn test_p384_jwk_conversion() -> Result<()> {
1352        // Generate P-384 keys
1353        let private_key = generate_key(KeyType::P384Private)?;
1354        let public_key = to_public(&private_key)?;
1355
1356        // Test private key to JWK conversion
1357        let private_jwk: Result<elliptic_curve::JwkEcKey, _> = (&private_key).try_into();
1358        assert!(private_jwk.is_ok());
1359
1360        // Test public key to JWK conversion
1361        let public_jwk: Result<elliptic_curve::JwkEcKey, _> = (&public_key).try_into();
1362        assert!(public_jwk.is_ok());
1363
1364        Ok(())
1365    }
1366
1367    #[test]
1368    fn test_p384_key_properties() -> Result<()> {
1369        // Test that P-384 keys have expected properties
1370        let private_key = generate_key(KeyType::P384Private)?;
1371        let public_key = to_public(&private_key)?;
1372
1373        // P-384 private keys should be 48 bytes
1374        assert_eq!(private_key.bytes().len(), 48);
1375
1376        // P-384 public keys should be 97 bytes (uncompressed) or 49 bytes (compressed)
1377        // SEC1 format: 0x04 + 48 bytes x + 48 bytes y = 97 bytes uncompressed
1378        // or 0x02/0x03 + 48 bytes x = 49 bytes compressed
1379        assert!(public_key.bytes().len() == 97 || public_key.bytes().len() == 49);
1380
1381        // Test that multiple derivations from the same private key produce the same public key
1382        let public_key2 = to_public(&private_key)?;
1383        assert_eq!(public_key.bytes(), public_key2.bytes());
1384
1385        Ok(())
1386    }
1387
1388    #[test]
1389    fn test_p384_cross_curve_verification_fails() -> Result<()> {
1390        // Generate keys from different curves
1391        let p256_key = generate_key(KeyType::P256Private)?;
1392        let p384_key = generate_key(KeyType::P384Private)?;
1393        let k256_key = generate_key(KeyType::K256Private)?;
1394
1395        // Get their public keys
1396        let p256_public = to_public(&p256_key)?;
1397        let p384_public = to_public(&p384_key)?;
1398        let k256_public = to_public(&k256_key)?;
1399
1400        let content = "cross curve verification test".as_bytes();
1401
1402        // Sign with each private key
1403        let p256_signature = sign(&p256_key, content)?;
1404        let p384_signature = sign(&p384_key, content)?;
1405        let k256_signature = sign(&k256_key, content)?;
1406
1407        // Verify each signature works with its corresponding key
1408        validate(&p256_public, &p256_signature, content)?;
1409        validate(&p384_public, &p384_signature, content)?;
1410        validate(&k256_public, &k256_signature, content)?;
1411
1412        // Cross-verification should fail - P-384 vs others
1413        assert!(validate(&p256_public, &p384_signature, content).is_err());
1414        assert!(validate(&p384_public, &p256_signature, content).is_err());
1415        assert!(validate(&k256_public, &p384_signature, content).is_err());
1416        assert!(validate(&p384_public, &k256_signature, content).is_err());
1417
1418        Ok(())
1419    }
1420
1421    #[test]
1422    fn test_p384_sign_with_public_key_fails() {
1423        let private_key = generate_key(KeyType::P384Private).unwrap();
1424        let public_key = to_public(&private_key).unwrap();
1425
1426        let content = "test content".as_bytes();
1427
1428        // Signing with public key should fail
1429        let result = sign(&public_key, content);
1430        assert!(matches!(
1431            result,
1432            Err(KeyError::PrivateKeyRequiredForSignature)
1433        ));
1434    }
1435
1436    #[test]
1437    fn test_p384_comprehensive_workflow() -> Result<()> {
1438        println!("\n=== P-384 Comprehensive Workflow Test ===");
1439
1440        // Step 1: Generate P-384 private key
1441        println!("1. Generating P-384 private key...");
1442        let private_key = generate_key(KeyType::P384Private)?;
1443        assert_eq!(*private_key.key_type(), KeyType::P384Private);
1444        assert_eq!(private_key.bytes().len(), 48);
1445
1446        // Step 2: Derive public key
1447        println!("2. Deriving P-384 public key...");
1448        let public_key = to_public(&private_key)?;
1449        assert_eq!(*public_key.key_type(), KeyType::P384Public);
1450
1451        // Step 3: Serialize keys to DID format
1452        println!("3. Serializing keys to DID format...");
1453        let private_did = format!("{}", private_key);
1454        let public_did = format!("{}", public_key);
1455        println!("   P-384 Private: {}", private_did);
1456        println!("   P-384 Public:  {}", public_did);
1457
1458        assert!(private_did.starts_with("did:key:"));
1459        assert!(public_did.starts_with("did:key:"));
1460        assert_ne!(private_did, public_did);
1461
1462        // Step 4: Parse DIDs back to KeyData
1463        println!("4. Parsing DIDs back to KeyData...");
1464        let parsed_private = identify_key(&private_did)?;
1465        let parsed_public = identify_key(&public_did)?;
1466
1467        assert_eq!(*parsed_private.key_type(), KeyType::P384Private);
1468        assert_eq!(*parsed_public.key_type(), KeyType::P384Public);
1469
1470        // Step 5: Verify round-trip integrity
1471        println!("5. Verifying round-trip integrity...");
1472        assert_eq!(private_key.bytes(), parsed_private.bytes());
1473        assert_eq!(public_key.bytes(), parsed_public.bytes());
1474
1475        // Step 6: Test signing and verification
1476        println!("6. Testing signing and verification...");
1477        let test_data = "P-384 comprehensive test data".as_bytes();
1478
1479        // Sign with original private key
1480        let signature = sign(&private_key, test_data)?;
1481
1482        // Verify with all key variants
1483        validate(&private_key, &signature, test_data)?;
1484        validate(&public_key, &signature, test_data)?;
1485        validate(&parsed_private, &signature, test_data)?;
1486        validate(&parsed_public, &signature, test_data)?;
1487
1488        // Step 7: Test JWK conversion
1489        println!("7. Testing JWK conversion...");
1490        let private_jwk: elliptic_curve::JwkEcKey = (&private_key).try_into()?;
1491        let public_jwk: elliptic_curve::JwkEcKey = (&public_key).try_into()?;
1492
1493        assert_eq!(private_jwk.crv(), "P-384");
1494        assert_eq!(public_jwk.crv(), "P-384");
1495
1496        println!("=== P-384 comprehensive workflow completed successfully! ===\n");
1497
1498        Ok(())
1499    }
1500
1501    #[test]
1502    fn test_p384_multicodec_prefix_identification() -> Result<()> {
1503        // Test that we can identify P-384 keys by their multicodec prefixes
1504        let private_key = generate_key(KeyType::P384Private)?;
1505        let public_key = to_public(&private_key)?;
1506
1507        // Convert to DID strings
1508        let private_did = format!("{}", private_key);
1509        let public_did = format!("{}", public_key);
1510
1511        // Parse back and verify the multicodec prefixes were correctly identified
1512        let parsed_private = identify_key(&private_did)?;
1513        let parsed_public = identify_key(&public_did)?;
1514
1515        assert_eq!(*parsed_private.key_type(), KeyType::P384Private);
1516        assert_eq!(*parsed_public.key_type(), KeyType::P384Public);
1517
1518        // Verify the actual multicodec prefixes in the DID strings
1519        let private_value = did_method_key_value(&private_did);
1520        let public_value = did_method_key_value(&public_did);
1521
1522        let (_, private_decoded) = multibase::decode(private_value)?;
1523        let (_, public_decoded) = multibase::decode(public_value)?;
1524
1525        // Check the multicodec prefixes
1526        assert_eq!(&private_decoded[..2], &[0x13, 0x01]); // P-384 private key prefix
1527        assert_eq!(&public_decoded[..2], &[0x12, 0x00]); // P-384 public key prefix
1528
1529        Ok(())
1530    }
1531}