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