ave-identity 0.3.0

Generic cryptographic primitives with algorithm identification
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
//! Algorithm-agnostic key pair wrapper.

use serde::{Deserialize, Serialize};

use crate::error::CryptoError;
use std::fmt;

use super::{DSA, DSAlgorithm, Ed25519Signer, PublicKey, SignatureIdentifier};

/// Key pair algorithms supported by this crate.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default,
)]
pub enum KeyPairAlgorithm {
    /// Ed25519 elliptic curve signature scheme.
    #[default]
    Ed25519,
}

impl From<DSAlgorithm> for KeyPairAlgorithm {
    fn from(algo: DSAlgorithm) -> Self {
        match algo {
            DSAlgorithm::Ed25519 => Self::Ed25519,
        }
    }
}

impl From<KeyPairAlgorithm> for DSAlgorithm {
    fn from(kp_type: KeyPairAlgorithm) -> Self {
        match kp_type {
            KeyPairAlgorithm::Ed25519 => Self::Ed25519,
        }
    }
}

impl KeyPairAlgorithm {
    /// Generates a random key pair for this algorithm.
    pub fn generate_keypair(&self) -> Result<KeyPair, CryptoError> {
        KeyPair::generate(*self)
    }
}

impl fmt::Display for KeyPairAlgorithm {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Ed25519 => write!(f, "Ed25519"),
        }
    }
}

/// Owns a signing key and exposes a stable high-level API.
///
/// Use this type when the caller should not depend on a concrete algorithm.
#[derive(Clone)]
pub enum KeyPair {
    Ed25519(Ed25519Signer),
}

impl KeyPair {
    /// Generates a random key pair for `key_type`.
    pub fn generate(key_type: KeyPairAlgorithm) -> Result<Self, CryptoError> {
        match key_type {
            KeyPairAlgorithm::Ed25519 => {
                Ed25519Signer::generate().map(KeyPair::Ed25519)
            }
        }
    }

    /// Imports a key pair from PKCS#8 DER bytes.
    ///
    /// The algorithm is detected from the OID stored in the DER structure.
    pub fn from_secret_der(der: &[u8]) -> Result<Self, CryptoError> {
        use pkcs8::{ObjectIdentifier, PrivateKeyInfo};

        // Parse the DER structure
        let private_key_info = PrivateKeyInfo::try_from(der)
            .map_err(|e| CryptoError::InvalidDerFormat(e.to_string()))?;

        // Get the algorithm OID
        let oid = private_key_info.algorithm.oid;

        // Ed25519 OID: 1.3.101.112
        const ED25519_OID: ObjectIdentifier =
            ObjectIdentifier::new_unwrap("1.3.101.112");

        // Match OID to algorithm
        if oid == ED25519_OID {
            // Extract the secret key bytes from the OCTET STRING
            let secret_key = private_key_info.private_key;

            // Ed25519 keys in PKCS#8 are wrapped in an OCTET STRING
            // The first byte should be 0x04 (OCTET STRING tag), followed by length
            if secret_key.len() < 2 || secret_key[0] != 0x04 {
                return Err(CryptoError::InvalidSecretKey(
                    "Invalid Ed25519 key encoding in DER".to_string(),
                ));
            }

            let key_length = secret_key[1] as usize;
            if secret_key.len() < 2 + key_length {
                return Err(CryptoError::InvalidSecretKey(
                    "Truncated Ed25519 key in DER".to_string(),
                ));
            }

            let actual_key = &secret_key[2..2 + key_length];
            Ed25519Signer::from_secret_key(actual_key).map(KeyPair::Ed25519)
        } else {
            Err(CryptoError::UnsupportedAlgorithm(format!(
                "Algorithm with OID {} is not supported",
                oid
            )))
        }
    }

    /// Builds a key pair from an exact 32-byte seed.
    pub fn from_seed(
        key_type: KeyPairAlgorithm,
        seed: &[u8; 32],
    ) -> Result<Self, CryptoError> {
        match key_type {
            KeyPairAlgorithm::Ed25519 => {
                Ed25519Signer::from_seed(seed).map(KeyPair::Ed25519)
            }
        }
    }

    /// Derives a deterministic key pair from arbitrary bytes.
    pub fn derive_from_data(
        key_type: KeyPairAlgorithm,
        data: &[u8],
    ) -> Result<Self, CryptoError> {
        match key_type {
            KeyPairAlgorithm::Ed25519 => {
                Ed25519Signer::derive_from_data(data).map(KeyPair::Ed25519)
            }
        }
    }

    /// Imports a key pair from raw secret key bytes.
    ///
    /// For explicit algorithm selection, use [`Self::from_secret_key_with_type`].
    pub fn from_secret_key(secret_key: &[u8]) -> Result<Self, CryptoError> {
        // Try to detect algorithm from key length
        match secret_key.len() {
            32 | 64 => {
                Ed25519Signer::from_secret_key(secret_key).map(KeyPair::Ed25519)
            }
            _ => Err(CryptoError::InvalidSecretKey(format!(
                "Unsupported key length: {} bytes",
                secret_key.len()
            ))),
        }
    }

    /// Imports a key pair from raw secret key bytes and an explicit algorithm.
    pub fn from_secret_key_with_type(
        key_type: KeyPairAlgorithm,
        secret_key: &[u8],
    ) -> Result<Self, CryptoError> {
        match key_type {
            KeyPairAlgorithm::Ed25519 => {
                Ed25519Signer::from_secret_key(secret_key).map(KeyPair::Ed25519)
            }
        }
    }

    /// Returns the key pair algorithm.
    #[inline]
    pub const fn key_type(&self) -> KeyPairAlgorithm {
        match self {
            Self::Ed25519(_) => KeyPairAlgorithm::Ed25519,
        }
    }

    /// Signs `message`.
    #[inline]
    pub fn sign(
        &self,
        message: &[u8],
    ) -> Result<SignatureIdentifier, CryptoError> {
        match self {
            Self::Ed25519(signer) => signer.sign(message),
        }
    }

    /// Returns the signature algorithm used by this key pair.
    #[inline]
    pub fn algorithm(&self) -> DSAlgorithm {
        match self {
            Self::Ed25519(signer) => signer.algorithm(),
        }
    }

    /// Returns the one-byte identifier for the algorithm.
    #[inline]
    pub fn algorithm_id(&self) -> u8 {
        match self {
            Self::Ed25519(signer) => signer.algorithm_id(),
        }
    }

    /// Returns the raw public key bytes.
    #[inline]
    pub fn public_key_bytes(&self) -> Vec<u8> {
        match self {
            Self::Ed25519(signer) => signer.public_key_bytes(),
        }
    }

    /// Returns the public key wrapper.
    #[inline]
    pub fn public_key(&self) -> PublicKey {
        PublicKey::new(self.algorithm(), self.public_key_bytes())
            .expect("KeyPair should always have valid public key")
    }

    /// Returns the raw secret key bytes.
    #[inline]
    pub fn secret_key_bytes(&self) -> Result<Vec<u8>, CryptoError> {
        match self {
            Self::Ed25519(signer) => signer.secret_key_bytes(),
        }
    }

    /// Serializes the key pair as `identifier || secret_key`.
    ///
    /// This exposes the secret key material.
    pub fn to_bytes(&self) -> Result<Vec<u8>, CryptoError> {
        let secret = self.secret_key_bytes()?;
        let mut result = Vec::with_capacity(1 + secret.len());
        result.push(self.algorithm_id());
        result.extend_from_slice(&secret);
        Ok(result)
    }

    /// Deserializes a key pair from `identifier || secret_key`.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, CryptoError> {
        if bytes.is_empty() {
            return Err(CryptoError::InvalidSecretKey(
                "Data too short to contain algorithm identifier".to_string(),
            ));
        }

        let id = bytes[0];
        let algorithm = DSAlgorithm::from_identifier(id)?;
        let key_type = KeyPairAlgorithm::from(algorithm);
        let secret_key = &bytes[1..];

        Self::from_secret_key_with_type(key_type, secret_key)
    }

    /// Exports the secret key as PKCS#8 DER.
    pub fn to_secret_der(&self) -> Result<Vec<u8>, CryptoError> {
        use pkcs8::{ObjectIdentifier, PrivateKeyInfo, der::Encode};

        const ED25519_OID: ObjectIdentifier =
            ObjectIdentifier::new_unwrap("1.3.101.112");

        let secret_key_bytes = self.secret_key_bytes()?;

        // Wrap the key in an OCTET STRING (0x04 tag)
        let mut wrapped_key = Vec::with_capacity(2 + secret_key_bytes.len());
        wrapped_key.push(0x04); // OCTET STRING tag
        wrapped_key.push(secret_key_bytes.len() as u8); // length
        wrapped_key.extend_from_slice(&secret_key_bytes);

        let algorithm_identifier = pkcs8::AlgorithmIdentifierRef {
            oid: ED25519_OID,
            parameters: None,
        };

        let private_key_info = PrivateKeyInfo {
            algorithm: algorithm_identifier,
            private_key: &wrapped_key,
            public_key: None,
        };

        private_key_info.to_der().map_err(|e| {
            CryptoError::InvalidSecretKey(format!("DER encoding failed: {}", e))
        })
    }
}

impl Default for KeyPair {
    fn default() -> Self {
        Self::Ed25519(Ed25519Signer::default())
    }
}

impl fmt::Debug for KeyPair {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use crate::common::base64_encoding;
        f.debug_struct("KeyPair")
            .field("type", &self.key_type())
            .field("algorithm", &self.algorithm())
            .field(
                "public_key",
                &base64_encoding::encode(&self.public_key_bytes()),
            )
            .finish_non_exhaustive()
    }
}

impl fmt::Display for KeyPair {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?} KeyPair", self.key_type())
    }
}

// Implement DSA trait for KeyPair to make it fully interchangeable
impl DSA for KeyPair {
    #[inline]
    fn algorithm_id(&self) -> u8 {
        Self::algorithm_id(self)
    }

    #[inline]
    fn signature_length(&self) -> usize {
        match self {
            Self::Ed25519(signer) => signer.signature_length(),
        }
    }

    #[inline]
    fn sign(&self, message: &[u8]) -> Result<SignatureIdentifier, CryptoError> {
        Self::sign(self, message)
    }

    #[inline]
    fn algorithm(&self) -> DSAlgorithm {
        Self::algorithm(self)
    }

    #[inline]
    fn public_key_bytes(&self) -> Vec<u8> {
        Self::public_key_bytes(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_keypair_generate() {
        let keypair = KeyPair::generate(KeyPairAlgorithm::Ed25519).unwrap();
        assert_eq!(keypair.algorithm(), DSAlgorithm::Ed25519);
        assert_eq!(keypair.key_type(), KeyPairAlgorithm::Ed25519);
        assert_eq!(keypair.public_key_bytes().len(), 32);
    }

    #[test]
    fn test_keypair_sign_verify() {
        let keypair = KeyPair::generate(KeyPairAlgorithm::Ed25519).unwrap();
        let message = b"Test message";

        let signature = keypair.sign(message).unwrap();
        let public_key = keypair.public_key();

        assert!(public_key.verify(message, &signature).is_ok());
        assert!(public_key.verify(b"Wrong message", &signature).is_err());
    }

    #[test]
    fn test_keypair_from_seed() {
        let seed = [42u8; 32];
        let keypair1 =
            KeyPair::from_seed(KeyPairAlgorithm::Ed25519, &seed).unwrap();
        let keypair2 =
            KeyPair::from_seed(KeyPairAlgorithm::Ed25519, &seed).unwrap();

        // Same seed should produce same keys
        assert_eq!(keypair1.public_key_bytes(), keypair2.public_key_bytes());
    }

    #[test]
    fn test_keypair_derive_from_data() {
        let data = b"my passphrase";
        let keypair1 =
            KeyPair::derive_from_data(KeyPairAlgorithm::Ed25519, data).unwrap();
        let keypair2 =
            KeyPair::derive_from_data(KeyPairAlgorithm::Ed25519, data).unwrap();

        // Same data should produce same keys
        assert_eq!(keypair1.public_key_bytes(), keypair2.public_key_bytes());

        // Different data should produce different keys
        let keypair3 =
            KeyPair::derive_from_data(KeyPairAlgorithm::Ed25519, b"different")
                .unwrap();
        assert_ne!(keypair1.public_key_bytes(), keypair3.public_key_bytes());
    }

    #[test]
    fn test_keypair_serialization() {
        let keypair = KeyPair::generate(KeyPairAlgorithm::Ed25519).unwrap();
        let message = b"Test message";

        // Serialize
        let bytes = keypair.to_bytes().unwrap();
        assert_eq!(bytes[0], b'E'); // Ed25519 identifier

        // Deserialize
        let keypair2 = KeyPair::from_bytes(&bytes).unwrap();

        // Should produce same signatures
        let sig1 = keypair.sign(message).unwrap();
        let sig2 = keypair2.sign(message).unwrap();

        // Both should verify correctly
        let public_key = keypair.public_key();
        assert!(public_key.verify(message, &sig1).is_ok());
        assert!(public_key.verify(message, &sig2).is_ok());
    }

    #[test]
    fn test_keypair_dsa_trait() {
        let keypair = KeyPair::generate(KeyPairAlgorithm::Ed25519).unwrap();
        let message = b"Test message";

        // Use DSA trait methods
        let signature = DSA::sign(&keypair, message).unwrap();
        assert_eq!(DSA::algorithm(&keypair), DSAlgorithm::Ed25519);
        assert_eq!(DSA::algorithm_id(&keypair), b'E');

        // Verify
        let public_key = keypair.public_key();
        assert!(public_key.verify(message, &signature).is_ok());
    }

    #[test]
    fn test_keypair_public_key_wrapper() {
        let keypair = KeyPair::generate(KeyPairAlgorithm::Ed25519).unwrap();
        let public_key = keypair.public_key();

        assert_eq!(public_key.algorithm(), keypair.algorithm());
        assert_eq!(public_key.as_bytes(), &keypair.public_key_bytes()[..]);
    }

    #[test]
    fn test_keypair_from_secret_key_autodetect() {
        let keypair1 = KeyPair::generate(KeyPairAlgorithm::Ed25519).unwrap();
        let secret_bytes = keypair1.secret_key_bytes().unwrap();

        // Auto-detect should work
        let keypair2 = KeyPair::from_secret_key(&secret_bytes).unwrap();

        assert_eq!(keypair1.public_key_bytes(), keypair2.public_key_bytes());
    }

    #[test]
    fn test_keypair_type_conversion() {
        let kp_type = KeyPairAlgorithm::Ed25519;
        let algo: DSAlgorithm = kp_type.into();
        assert_eq!(algo, DSAlgorithm::Ed25519);

        let kp_type2: KeyPairAlgorithm = algo.into();
        assert_eq!(kp_type, kp_type2);
    }

    #[test]
    fn test_keypair_algorithm_generate() {
        let algorithm = KeyPairAlgorithm::Ed25519;
        let keypair = algorithm.generate_keypair().unwrap();

        assert_eq!(keypair.key_type(), KeyPairAlgorithm::Ed25519);
        assert_eq!(keypair.algorithm(), DSAlgorithm::Ed25519);

        // Should be able to sign
        let message = b"test";
        let signature = keypair.sign(message).unwrap();
        let public_key = keypair.public_key();
        assert!(public_key.verify(message, &signature).is_ok());
    }

    #[test]
    fn test_keypair_algorithm_display() {
        let algorithm = KeyPairAlgorithm::Ed25519;
        assert_eq!(algorithm.to_string(), "Ed25519");
    }

    #[test]
    fn test_default_keypair() {
        let keypair = KeyPair::default();
        assert_eq!(keypair.key_type(), KeyPairAlgorithm::Ed25519);
    }

    #[test]
    fn test_keypair_clone() {
        // Test that cloning works correctly
        let keypair = KeyPair::generate(KeyPairAlgorithm::Ed25519).unwrap();
        let keypair_clone = keypair.clone();

        // Both should have the same public key
        assert_eq!(
            keypair.public_key_bytes(),
            keypair_clone.public_key_bytes()
        );

        // Both should sign the same way
        let message = b"test message";
        let sig1 = keypair.sign(message).unwrap();
        let sig2 = keypair_clone.sign(message).unwrap();

        // Signatures should be identical (deterministic)
        assert_eq!(sig1, sig2);

        // Both signatures should verify
        let public_key = keypair.public_key();
        assert!(public_key.verify(message, &sig1).is_ok());
        assert!(public_key.verify(message, &sig2).is_ok());
    }

    #[test]
    fn test_keypair_der_roundtrip() {
        // Test DER serialization and deserialization
        let keypair1 = KeyPair::generate(KeyPairAlgorithm::Ed25519).unwrap();
        let message = b"Test message for DER roundtrip";

        // Serialize to DER
        let der_bytes = keypair1.to_secret_der().unwrap();

        // Verify it starts with DER SEQUENCE tag
        assert_eq!(der_bytes[0], 0x30); // SEQUENCE tag

        // Deserialize from DER
        let keypair2 = KeyPair::from_secret_der(&der_bytes).unwrap();

        // Should have the same public key
        assert_eq!(keypair1.public_key_bytes(), keypair2.public_key_bytes());

        // Should produce verifiable signatures
        let sig1 = keypair1.sign(message).unwrap();
        let sig2 = keypair2.sign(message).unwrap();

        let public_key = keypair1.public_key();
        assert!(public_key.verify(message, &sig1).is_ok());
        assert!(public_key.verify(message, &sig2).is_ok());
    }

    #[test]
    fn test_keypair_from_der_invalid() {
        // Test error handling for invalid DER data
        let invalid_der = vec![0x00, 0x01, 0x02];
        let result = KeyPair::from_secret_der(&invalid_der);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            CryptoError::InvalidDerFormat(_)
        ));
    }

    #[test]
    fn test_keypair_from_der_unsupported_algorithm() {
        // Create a valid DER structure but with an unsupported OID
        use pkcs8::{ObjectIdentifier, PrivateKeyInfo, der::Encode};

        // Use a different OID (e.g., secp256k1: 1.3.132.0.10)
        let unsupported_oid = ObjectIdentifier::new_unwrap("1.3.132.0.10");

        let fake_key = vec![0x04, 0x20]; // OCTET STRING tag + length
        let fake_key = [&fake_key[..], &[0u8; 32]].concat();

        let algorithm_identifier = pkcs8::AlgorithmIdentifierRef {
            oid: unsupported_oid,
            parameters: None,
        };

        let private_key_info = PrivateKeyInfo {
            algorithm: algorithm_identifier,
            private_key: &fake_key,
            public_key: None,
        };

        let der_bytes = private_key_info.to_der().unwrap();

        let result = KeyPair::from_secret_der(&der_bytes);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            CryptoError::UnsupportedAlgorithm(_)
        ));
    }
}