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