atproto_identity/
key.rs

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