rust-bottle 0.2.3

Rust implementation of Bottle protocol - layered message containers with encryption and signatures
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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
//! PKIX/PKCS#8 Key Serialization
//!
//! This module provides functions to marshal and unmarshal cryptographic keys
//! in standard PKIX (SubjectPublicKeyInfo) and PKCS#8 formats. These formats
//! enable interoperability with other cryptographic tools and libraries.
//!
//! # Supported Formats
//!
//! - **PKCS#8**: Private key format (RFC 5208)
//! - **PKIX/SPKI**: Public key format (RFC 5280)
//! - **PEM**: Base64-encoded DER with headers/footers
//! - **DER**: Binary ASN.1 encoding
//!
//! # Example
//!
//! ```rust
//! use rust_bottle::keys::EcdsaP256Key;
//! use rust_bottle::pkix;
//! use rand::rngs::OsRng;
//!
//! let rng = &mut OsRng;
//! let key = EcdsaP256Key::generate(rng);
//!
//! // Marshal public key to PKIX format
//! let pkix_der = pkix::marshal_pkix_public_key(&key.public_key_bytes()).unwrap();
//! let pkix_pem = pkix::marshal_pkix_public_key_pem(&key.public_key_bytes()).unwrap();
//!
//! // Marshal private key to PKCS#8 format
//! let pkcs8_der = pkix::marshal_pkcs8_private_key(&key.private_key_bytes(), pkix::KeyType::EcdsaP256).unwrap();
//! let pkcs8_pem = pkix::marshal_pkcs8_private_key_pem(&key.private_key_bytes(), pkix::KeyType::EcdsaP256).unwrap();
//!
//! // Unmarshal keys
//! let pub_key = pkix::parse_pkix_public_key(&pkix_der).unwrap();
//! let priv_key = pkix::parse_pkcs8_private_key(&pkcs8_der, pkix::KeyType::EcdsaP256).unwrap();
//! ```

use crate::errors::{BottleError, Result};
use const_oid::{db::rfc5912, ObjectIdentifier};
use der::{Decode, Encode};
use pkcs8::{AlgorithmIdentifierRef, PrivateKeyInfo};
use spki::{AlgorithmIdentifier, SubjectPublicKeyInfo};

/// Key type identifier for PKCS#8/PKIX serialization
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyType {
    /// ECDSA P-256 (secp256r1)
    EcdsaP256,
    /// ECDSA P-384 (secp384r1)
    EcdsaP384,
    /// ECDSA P-521 (secp521r1)
    EcdsaP521,
    /// Ed25519
    Ed25519,
    /// X25519
    X25519,
    /// RSA (PKCS#1)
    Rsa,
    /// ML-KEM-768 (requires `ml-kem` feature)
    #[cfg(feature = "ml-kem")]
    MlKem768,
    /// ML-KEM-1024 (requires `ml-kem` feature)
    #[cfg(feature = "ml-kem")]
    MlKem1024,
    /// ML-DSA-44 (requires `post-quantum` feature)
    #[cfg(feature = "post-quantum")]
    MlDsa44,
    /// ML-DSA-65 (requires `post-quantum` feature)
    #[cfg(feature = "post-quantum")]
    MlDsa65,
    /// ML-DSA-87 (requires `post-quantum` feature)
    #[cfg(feature = "post-quantum")]
    MlDsa87,
    /// SLH-DSA-128s (requires `post-quantum` feature)
    #[cfg(feature = "post-quantum")]
    SlhDsa128s,
    /// SLH-DSA-128f (requires `post-quantum` feature)
    #[cfg(feature = "post-quantum")]
    SlhDsa128f,
    /// SLH-DSA-192s (requires `post-quantum` feature)
    #[cfg(feature = "post-quantum")]
    SlhDsa192s,
    /// SLH-DSA-192f (requires `post-quantum` feature)
    #[cfg(feature = "post-quantum")]
    SlhDsa192f,
    /// SLH-DSA-256s (requires `post-quantum` feature)
    #[cfg(feature = "post-quantum")]
    SlhDsa256s,
    /// SLH-DSA-256f (requires `post-quantum` feature)
    #[cfg(feature = "post-quantum")]
    SlhDsa256f,
    /// SLH-DSA-SHA2-128s (requires `post-quantum` feature)
    #[cfg(feature = "post-quantum")]
    SlhDsaSha2_128s,
    /// SLH-DSA-SHA2-128f (requires `post-quantum` feature)
    #[cfg(feature = "post-quantum")]
    SlhDsaSha2_128f,
    /// SLH-DSA-SHA2-192s (requires `post-quantum` feature)
    #[cfg(feature = "post-quantum")]
    SlhDsaSha2_192s,
    /// SLH-DSA-SHA2-192f (requires `post-quantum` feature)
    #[cfg(feature = "post-quantum")]
    SlhDsaSha2_192f,
    /// SLH-DSA-SHA2-256s (requires `post-quantum` feature)
    #[cfg(feature = "post-quantum")]
    SlhDsaSha2_256s,
    /// SLH-DSA-SHA2-256f (requires `post-quantum` feature)
    #[cfg(feature = "post-quantum")]
    SlhDsaSha2_256f,
}

impl KeyType {
    /// Get the OID (Object Identifier) for this key type
    fn oid(&self) -> ObjectIdentifier {
        match self {
            KeyType::EcdsaP256 => rfc5912::ID_EC_PUBLIC_KEY, // ecPublicKey
            KeyType::EcdsaP384 => rfc5912::ID_EC_PUBLIC_KEY, // ecPublicKey
            KeyType::EcdsaP521 => rfc5912::ID_EC_PUBLIC_KEY, // ecPublicKey
            KeyType::Ed25519 => ObjectIdentifier::new("1.3.101.112").expect("Invalid Ed25519 OID"), // Ed25519
            KeyType::X25519 => ObjectIdentifier::new("1.3.101.110").expect("Invalid X25519 OID"), // X25519
            KeyType::Rsa => rfc5912::RSA_ENCRYPTION, // rsaEncryption
            #[cfg(feature = "ml-kem")]
            KeyType::MlKem768 | KeyType::MlKem1024 => {
                // ML-KEM OID (NIST standard) - placeholder, actual OID may differ
                // Using a temporary OID structure - update with official OID when available
                // Note: This is a placeholder OID - update when NIST publishes official OIDs
                ObjectIdentifier::new("1.3.6.1.4.1.2.267.7.6.5").expect("Invalid ML-KEM OID")
            }
            #[cfg(feature = "post-quantum")]
            KeyType::MlDsa44 | KeyType::MlDsa65 | KeyType::MlDsa87 => {
                // ML-DSA OID (NIST standard) - placeholder, actual OID may differ
                // Note: This is a placeholder OID - update when NIST publishes official OIDs
                ObjectIdentifier::new("1.3.6.1.4.1.2.267.7.4.4").expect("Invalid ML-DSA OID")
            }
            #[cfg(feature = "post-quantum")]
            KeyType::SlhDsa128s | KeyType::SlhDsa128f | KeyType::SlhDsa192s | KeyType::SlhDsa192f | KeyType::SlhDsa256s | KeyType::SlhDsa256f
            | KeyType::SlhDsaSha2_128s | KeyType::SlhDsaSha2_128f | KeyType::SlhDsaSha2_192s | KeyType::SlhDsaSha2_192f | KeyType::SlhDsaSha2_256s | KeyType::SlhDsaSha2_256f => {
                // SLH-DSA OID (NIST standard) - placeholder, actual OID may differ
                // Note: This is a placeholder OID - update when NIST publishes official OIDs
                ObjectIdentifier::new("1.3.6.1.4.1.2.267.1.16.7").expect("Invalid SLH-DSA OID")
            }
        }
    }

    /// Get the curve OID for ECDSA keys
    #[allow(dead_code)]
    fn curve_oid(&self) -> Option<&'static [u32]> {
        match self {
            KeyType::EcdsaP256 => Some(&[1, 2, 840, 10045, 3, 1, 7]), // prime256v1
            KeyType::EcdsaP384 => Some(&[1, 3, 132, 0, 34]),          // secp384r1
            KeyType::EcdsaP521 => Some(&[1, 3, 132, 0, 35]),          // secp521r1
            _ => None,
        }
    }
}

/// Marshal a public key to PKIX (SubjectPublicKeyInfo) format in DER encoding.
///
/// This function encodes a public key in the standard PKIX format, which is
/// compatible with OpenSSL, other cryptographic libraries, and tools.
///
/// # Arguments
///
/// * `public_key_bytes` - Raw public key bytes (format depends on key type)
/// * `key_type` - The type of key being marshaled
///
/// # Returns
///
/// * `Ok(Vec<u8>)` - DER-encoded PKIX public key
/// * `Err(BottleError)` - If encoding fails
///
/// # Example
///
/// ```rust
/// use rust_bottle::keys::EcdsaP256Key;
/// use rust_bottle::pkix;
/// use rand::rngs::OsRng;
///
/// let rng = &mut OsRng;
/// let key = EcdsaP256Key::generate(rng);
/// let pkix_der = pkix::marshal_pkix_public_key(&key.public_key_bytes()).unwrap();
/// ```
pub fn marshal_pkix_public_key(public_key_bytes: &[u8]) -> Result<Vec<u8>> {
    // Try to detect key type from the bytes
    let key_type = detect_key_type_from_public_key(public_key_bytes)?;
    marshal_pkix_public_key_with_type(public_key_bytes, key_type)
}

/// Marshal a public key to PKIX format with explicit key type.
///
/// # Arguments
///
/// * `public_key_bytes` - Raw public key bytes
/// * `key_type` - The type of key being marshaled
///
/// # Returns
///
/// * `Ok(Vec<u8>)` - DER-encoded PKIX public key
/// * `Err(BottleError)` - If encoding fails
pub fn marshal_pkix_public_key_with_type(
    public_key_bytes: &[u8],
    key_type: KeyType,
) -> Result<Vec<u8>> {
    match key_type {
        KeyType::EcdsaP256 | KeyType::EcdsaP384 | KeyType::EcdsaP521 => {
            marshal_ecdsa_pkix(public_key_bytes, key_type)
        }
        KeyType::Ed25519 => marshal_ed25519_pkix(public_key_bytes),
        KeyType::X25519 => marshal_x25519_pkix(public_key_bytes),
        KeyType::Rsa => marshal_rsa_pkix(public_key_bytes),
        #[cfg(feature = "ml-kem")]
        KeyType::MlKem768 | KeyType::MlKem1024 => marshal_mlkem_pkix(public_key_bytes, key_type),
        #[cfg(feature = "post-quantum")]
        KeyType::MlDsa44 | KeyType::MlDsa65 | KeyType::MlDsa87 => {
            marshal_mldsa_pkix(public_key_bytes, key_type)
        }
        #[cfg(feature = "post-quantum")]
        KeyType::SlhDsa128s | KeyType::SlhDsa128f | KeyType::SlhDsa192s | KeyType::SlhDsa192f | KeyType::SlhDsa256s | KeyType::SlhDsa256f
        | KeyType::SlhDsaSha2_128s | KeyType::SlhDsaSha2_128f | KeyType::SlhDsaSha2_192s | KeyType::SlhDsaSha2_192f | KeyType::SlhDsaSha2_256s | KeyType::SlhDsaSha2_256f => {
            marshal_slhdsa_pkix(public_key_bytes, key_type)
        }
    }
}

/// Marshal a public key to PKIX format in PEM encoding.
///
/// # Arguments
///
/// * `public_key_bytes` - Raw public key bytes
///
/// # Returns
///
/// * `Ok(String)` - PEM-encoded PKIX public key
/// * `Err(BottleError)` - If encoding fails
///
/// # Example
///
/// ```rust
/// use rust_bottle::keys::EcdsaP256Key;
/// use rust_bottle::pkix;
/// use rand::rngs::OsRng;
///
/// let rng = &mut OsRng;
/// let key = EcdsaP256Key::generate(rng);
/// let pkix_pem = pkix::marshal_pkix_public_key_pem(&key.public_key_bytes()).unwrap();
/// ```
pub fn marshal_pkix_public_key_pem(public_key_bytes: &[u8]) -> Result<String> {
    let der = marshal_pkix_public_key(public_key_bytes)?;
    let pem = pem::encode(&pem::Pem::new("PUBLIC KEY", der));
    Ok(pem)
}

/// Parse a PKIX (SubjectPublicKeyInfo) public key from DER encoding.
///
/// # Arguments
///
/// * `der_bytes` - DER-encoded PKIX public key
/// * `key_type` - Expected key type (for validation)
///
/// # Returns
///
/// * `Ok(Vec<u8>)` - Raw public key bytes
/// * `Err(BottleError)` - If parsing fails
///
/// # Example
///
/// ```rust
/// use rust_bottle::keys::EcdsaP256Key;
/// use rust_bottle::pkix;
/// use rand::rngs::OsRng;
///
/// let rng = &mut OsRng;
/// let key = EcdsaP256Key::generate(rng);
/// let pkix_der = pkix::marshal_pkix_public_key(&key.public_key_bytes()).unwrap();
/// let pub_key = pkix::parse_pkix_public_key(&pkix_der).unwrap();
/// assert_eq!(pub_key, key.public_key_bytes());
/// ```
pub fn parse_pkix_public_key(der_bytes: &[u8]) -> Result<Vec<u8>> {
    use der::asn1::AnyRef;
    use der::asn1::BitString;
    let spki: SubjectPublicKeyInfo<AnyRef, BitString> = SubjectPublicKeyInfo::from_der(der_bytes)
        .map_err(|e| {
        BottleError::Deserialization(format!("Failed to parse PKIX public key: {}", e))
    })?;

    // Extract the raw key bytes from the SPKI structure
    // The algorithm identifier tells us the key type
    // For now, return the raw subjectPublicKey bytes
    // In a full implementation, we'd parse based on the algorithm OID
    Ok(spki.subject_public_key.raw_bytes().to_vec())
}

/// Parse a PKIX public key from PEM encoding.
///
/// # Arguments
///
/// * `pem_str` - PEM-encoded PKIX public key
///
/// # Returns
///
/// * `Ok(Vec<u8>)` - Raw public key bytes
/// * `Err(BottleError)` - If parsing fails
pub fn parse_pkix_public_key_pem(pem_str: &str) -> Result<Vec<u8>> {
    let pem = pem::parse(pem_str)
        .map_err(|e| BottleError::Deserialization(format!("Failed to parse PEM: {}", e)))?;
    parse_pkix_public_key(pem.contents())
}

/// Marshal a private key to PKCS#8 format in DER encoding.
///
/// # Arguments
///
/// * `private_key_bytes` - Raw private key bytes
/// * `key_type` - The type of key being marshaled
///
/// # Returns
///
/// * `Ok(Vec<u8>)` - DER-encoded PKCS#8 private key
/// * `Err(BottleError)` - If encoding fails
///
/// # Example
///
/// ```rust
/// use rust_bottle::keys::EcdsaP256Key;
/// use rust_bottle::pkix;
/// use rand::rngs::OsRng;
///
/// let rng = &mut OsRng;
/// let key = EcdsaP256Key::generate(rng);
/// let pkcs8_der = pkix::marshal_pkcs8_private_key(
///     &key.private_key_bytes(),
///     pkix::KeyType::EcdsaP256
/// ).unwrap();
/// ```
pub fn marshal_pkcs8_private_key(private_key_bytes: &[u8], key_type: KeyType) -> Result<Vec<u8>> {
    match key_type {
        KeyType::EcdsaP256 | KeyType::EcdsaP384 | KeyType::EcdsaP521 => {
            marshal_ecdsa_pkcs8(private_key_bytes, key_type)
        }
        KeyType::Ed25519 => marshal_ed25519_pkcs8(private_key_bytes),
        KeyType::X25519 => marshal_x25519_pkcs8(private_key_bytes),
        KeyType::Rsa => marshal_rsa_pkcs8(private_key_bytes),
        #[cfg(feature = "ml-kem")]
        KeyType::MlKem768 | KeyType::MlKem1024 => marshal_mlkem_pkcs8(private_key_bytes, key_type),
        #[cfg(feature = "post-quantum")]
        KeyType::MlDsa44 | KeyType::MlDsa65 | KeyType::MlDsa87 => {
            marshal_mldsa_pkcs8(private_key_bytes, key_type)
        }
        #[cfg(feature = "post-quantum")]
        KeyType::SlhDsa128s | KeyType::SlhDsa128f | KeyType::SlhDsa192s | KeyType::SlhDsa192f | KeyType::SlhDsa256s | KeyType::SlhDsa256f
        | KeyType::SlhDsaSha2_128s | KeyType::SlhDsaSha2_128f | KeyType::SlhDsaSha2_192s | KeyType::SlhDsaSha2_192f | KeyType::SlhDsaSha2_256s | KeyType::SlhDsaSha2_256f => {
            marshal_slhdsa_pkcs8(private_key_bytes, key_type)
        }
    }
}

/// Marshal a private key to PKCS#8 format in PEM encoding.
///
/// # Arguments
///
/// * `private_key_bytes` - Raw private key bytes
/// * `key_type` - The type of key being marshaled
///
/// # Returns
///
/// * `Ok(String)` - PEM-encoded PKCS#8 private key
/// * `Err(BottleError)` - If encoding fails
///
/// # Example
///
/// ```rust
/// use rust_bottle::keys::EcdsaP256Key;
/// use rust_bottle::pkix;
/// use rand::rngs::OsRng;
///
/// let rng = &mut OsRng;
/// let key = EcdsaP256Key::generate(rng);
/// let pkcs8_pem = pkix::marshal_pkcs8_private_key_pem(
///     &key.private_key_bytes(),
///     pkix::KeyType::EcdsaP256
/// ).unwrap();
/// ```
pub fn marshal_pkcs8_private_key_pem(
    private_key_bytes: &[u8],
    key_type: KeyType,
) -> Result<String> {
    let der = marshal_pkcs8_private_key(private_key_bytes, key_type)?;
    let pem = pem::encode(&pem::Pem::new("PRIVATE KEY", der));
    Ok(pem)
}

/// Parse a PKCS#8 private key from DER encoding.
///
/// # Arguments
///
/// * `der_bytes` - DER-encoded PKCS#8 private key
/// * `key_type` - Expected key type (for validation)
///
/// # Returns
///
/// * `Ok(Vec<u8>)` - Raw private key bytes
/// * `Err(BottleError)` - If parsing fails
///
/// # Example
///
/// ```rust
/// use rust_bottle::keys::EcdsaP256Key;
/// use rust_bottle::pkix;
/// use rand::rngs::OsRng;
///
/// let rng = &mut OsRng;
/// let key = EcdsaP256Key::generate(rng);
/// let pkcs8_der = pkix::marshal_pkcs8_private_key(
///     &key.private_key_bytes(),
///     pkix::KeyType::EcdsaP256
/// ).unwrap();
/// let priv_key = pkix::parse_pkcs8_private_key(&pkcs8_der, pkix::KeyType::EcdsaP256).unwrap();
/// assert_eq!(priv_key, key.private_key_bytes());
/// ```
pub fn parse_pkcs8_private_key(der_bytes: &[u8], key_type: KeyType) -> Result<Vec<u8>> {
    match key_type {
        KeyType::EcdsaP256 => {
            use p256::ecdsa::SigningKey;
            use p256::pkcs8::DecodePrivateKey;
            let signing_key = SigningKey::from_pkcs8_der(der_bytes).map_err(|e| {
                BottleError::Deserialization(format!("Failed to parse P-256 PKCS#8: {}", e))
            })?;
            Ok(signing_key.to_bytes().to_vec())
        }
        KeyType::Ed25519 => {
            use ed25519_dalek::pkcs8::DecodePrivateKey;
            use ed25519_dalek::SigningKey;
            let signing_key = SigningKey::from_pkcs8_der(der_bytes).map_err(|e| {
                BottleError::Deserialization(format!("Failed to parse Ed25519 PKCS#8: {}", e))
            })?;
            Ok(signing_key.to_bytes().to_vec())
        }
        KeyType::X25519 => {
            // X25519 private keys are stored directly as raw bytes in PKCS#8
            let pkcs8 = PrivateKeyInfo::from_der(der_bytes).map_err(|e| {
                BottleError::Deserialization(format!("Failed to parse PKCS#8 private key: {}", e))
            })?;
            Ok(pkcs8.private_key.to_vec())
        }
        KeyType::Rsa => {
            // RSA private keys in PKCS#8 contain RSAPrivateKey structure
            // For now, return error - proper implementation requires RsaPrivateKey parsing
            // TODO: Implement proper RSA PKCS#8 deserialization
            Err(BottleError::Deserialization(
                "RSA PKCS#8 deserialization not yet implemented. Use RsaKey directly.".to_string(),
            ))
        }
        _ => {
            // For other key types, return the raw private key bytes
            // (they may need special handling in the future)
            let pkcs8 = PrivateKeyInfo::from_der(der_bytes).map_err(|e| {
                BottleError::Deserialization(format!("Failed to parse PKCS#8 private key: {}", e))
            })?;
            Ok(pkcs8.private_key.to_vec())
        }
    }
}

/// Parse a PKCS#8 private key from PEM encoding.
///
/// # Arguments
///
/// * `pem_str` - PEM-encoded PKCS#8 private key
/// * `key_type` - Expected key type (for validation)
///
/// # Returns
///
/// * `Ok(Vec<u8>)` - Raw private key bytes
/// * `Err(BottleError)` - If parsing fails
pub fn parse_pkcs8_private_key_pem(pem_str: &str, key_type: KeyType) -> Result<Vec<u8>> {
    let pem = pem::parse(pem_str)
        .map_err(|e| BottleError::Deserialization(format!("Failed to parse PEM: {}", e)))?;
    parse_pkcs8_private_key(pem.contents(), key_type)
}

// Helper functions for specific key types

fn marshal_ecdsa_pkix(public_key_bytes: &[u8], key_type: KeyType) -> Result<Vec<u8>> {
    match key_type {
        KeyType::EcdsaP256 => {
            use p256::pkcs8::EncodePublicKey;
            let pub_key = p256::PublicKey::from_sec1_bytes(public_key_bytes).map_err(|e| {
                BottleError::Serialization(format!("Failed to create P-256 public key: {}", e))
            })?;
            pub_key
                .to_public_key_der()
                .map(|doc| doc.as_bytes().to_vec())
                .map_err(|e| {
                    BottleError::Serialization(format!("Failed to encode P-256 PKIX: {}", e))
                })
        }
        _ => Err(BottleError::UnsupportedAlgorithm),
    }
}

fn marshal_ecdsa_pkcs8(private_key_bytes: &[u8], key_type: KeyType) -> Result<Vec<u8>> {
    match key_type {
        KeyType::EcdsaP256 => {
            use p256::ecdsa::SigningKey;
            use p256::pkcs8::EncodePrivateKey;
            let signing_key = SigningKey::from_bytes(private_key_bytes.into()).map_err(|e| {
                BottleError::Serialization(format!("Invalid P-256 private key: {}", e))
            })?;
            signing_key
                .to_pkcs8_der()
                .map(|doc| doc.as_bytes().to_vec())
                .map_err(|e| {
                    BottleError::Serialization(format!("Failed to encode P-256 PKCS#8: {}", e))
                })
        }
        _ => Err(BottleError::UnsupportedAlgorithm),
    }
}

fn marshal_ed25519_pkix(public_key_bytes: &[u8]) -> Result<Vec<u8>> {
    use ed25519_dalek::pkcs8::EncodePublicKey;
    use ed25519_dalek::VerifyingKey;

    let verifying_key = VerifyingKey::from_bytes(public_key_bytes.try_into().map_err(|_| {
        BottleError::Serialization("Invalid Ed25519 public key length".to_string())
    })?)
    .map_err(|e| BottleError::Serialization(format!("Invalid Ed25519 public key: {}", e)))?;

    verifying_key
        .to_public_key_der()
        .map(|doc| doc.as_bytes().to_vec())
        .map_err(|e| BottleError::Serialization(format!("Failed to encode Ed25519 PKIX: {}", e)))
}

fn marshal_ed25519_pkcs8(private_key_bytes: &[u8]) -> Result<Vec<u8>> {
    use ed25519_dalek::pkcs8::EncodePrivateKey;
    use ed25519_dalek::SigningKey;

    let signing_key = SigningKey::from_bytes(private_key_bytes.try_into().map_err(|_| {
        BottleError::Serialization("Invalid Ed25519 private key length".to_string())
    })?);

    signing_key
        .to_pkcs8_der()
        .map(|doc| doc.as_bytes().to_vec())
        .map_err(|e| BottleError::Serialization(format!("Failed to encode Ed25519 PKCS#8: {}", e)))
}

fn marshal_x25519_pkix(public_key_bytes: &[u8]) -> Result<Vec<u8>> {
    // X25519 public keys are 32 bytes
    if public_key_bytes.len() != 32 {
        return Err(BottleError::Serialization(
            "Invalid X25519 public key length".to_string(),
        ));
    }

    // X25519 uses a simple octet string encoding
    // This is a simplified implementation
    use der::asn1::OctetString;
    let key_octets = OctetString::new(public_key_bytes).map_err(|e| {
        BottleError::Serialization(format!("Failed to create X25519 octet string: {}", e))
    })?;

    // Create SPKI structure
    // X25519 uses no parameters per RFC 8410
    use der::asn1::AnyRef;
    let algorithm = AlgorithmIdentifier {
        oid: KeyType::X25519.oid(),
        parameters: None::<AnyRef>,
    };

    let spki = SubjectPublicKeyInfo {
        algorithm,
        subject_public_key: key_octets,
    };

    spki.to_der()
        .map_err(|e| BottleError::Serialization(format!("Failed to encode X25519 PKIX: {}", e)))
}

fn marshal_x25519_pkcs8(private_key_bytes: &[u8]) -> Result<Vec<u8>> {
    // X25519 private keys are 32 bytes
    if private_key_bytes.len() != 32 {
        return Err(BottleError::Serialization(
            "Invalid X25519 private key length".to_string(),
        ));
    }

    // Create PKCS#8 structure
    // X25519 uses no parameters per RFC 8410
    let algorithm = AlgorithmIdentifierRef {
        oid: KeyType::X25519.oid(),
        parameters: None,
    };

    let pkcs8 = PrivateKeyInfo::new(algorithm, private_key_bytes);

    pkcs8
        .to_der()
        .map_err(|e| BottleError::Serialization(format!("Failed to encode X25519 PKCS#8: {}", e)))
}

fn marshal_rsa_pkix(_public_key_bytes: &[u8]) -> Result<Vec<u8>> {
    // Note: RSA public key bytes from RsaKey::public_key_bytes() are currently empty
    // This is a placeholder - proper implementation requires RsaPublicKey reference
    // For now, return an error indicating PKCS#8 serialization should be used
    // TODO: Implement proper RSA PKIX serialization using RsaPublicKey
    Err(BottleError::Serialization(
        "RSA PKIX serialization requires RsaPublicKey reference. Use PKCS#8 serialization or provide RsaPublicKey directly.".to_string()
    ))
}

fn marshal_rsa_pkcs8(_private_key_bytes: &[u8]) -> Result<Vec<u8>> {
    // Note: RSA private key bytes from RsaKey::private_key_bytes() are currently empty
    // This is a placeholder - proper implementation requires RsaPrivateKey reference
    // For now, return an error indicating direct RsaKey should be used
    // TODO: Implement proper RSA PKCS#8 serialization using RsaPrivateKey
    Err(BottleError::Serialization(
        "RSA PKCS#8 serialization requires RsaPrivateKey reference. Use RsaKey directly or provide RsaPrivateKey.".to_string()
    ))
}

#[cfg(feature = "ml-kem")]
fn marshal_mlkem_pkix(public_key_bytes: &[u8], key_type: KeyType) -> Result<Vec<u8>> {
    use der::asn1::BitString;

    let key_bits = BitString::from_bytes(public_key_bytes).map_err(|e| {
        BottleError::Serialization(format!("Failed to create ML-KEM bit string: {}", e))
    })?;

    use der::asn1::AnyRef;
    let algorithm = AlgorithmIdentifier {
        oid: key_type.oid(),
        parameters: Some(AnyRef::NULL),
    };

    let spki = SubjectPublicKeyInfo {
        algorithm,
        subject_public_key: key_bits,
    };

    spki.to_der()
        .map_err(|e| BottleError::Serialization(format!("Failed to encode ML-KEM PKIX: {}", e)))
}

#[cfg(feature = "ml-kem")]
fn marshal_mlkem_pkcs8(private_key_bytes: &[u8], key_type: KeyType) -> Result<Vec<u8>> {
    use der::asn1::OctetString;

    let _key_octets = OctetString::new(private_key_bytes).map_err(|e| {
        BottleError::Serialization(format!("Failed to create ML-KEM octet string: {}", e))
    })?;

    use der::asn1::AnyRef;
    let algorithm = AlgorithmIdentifierRef {
        oid: key_type.oid(),
        parameters: Some(AnyRef::NULL),
    };

    let pkcs8 = PrivateKeyInfo::new(algorithm, private_key_bytes);

    pkcs8
        .to_der()
        .map_err(|e| BottleError::Serialization(format!("Failed to encode ML-KEM PKCS#8: {}", e)))
}

#[cfg(feature = "post-quantum")]
fn marshal_mldsa_pkix(public_key_bytes: &[u8], key_type: KeyType) -> Result<Vec<u8>> {
    use der::asn1::BitString;

    let key_bits = BitString::from_bytes(public_key_bytes).map_err(|e| {
        BottleError::Serialization(format!("Failed to create ML-DSA bit string: {}", e))
    })?;

    use der::asn1::AnyRef;
    let algorithm = AlgorithmIdentifier {
        oid: key_type.oid(),
        parameters: Some(AnyRef::NULL),
    };

    let spki = SubjectPublicKeyInfo {
        algorithm,
        subject_public_key: key_bits,
    };

    spki.to_der()
        .map_err(|e| BottleError::Serialization(format!("Failed to encode ML-DSA PKIX: {}", e)))
}

#[cfg(feature = "post-quantum")]
fn marshal_mldsa_pkcs8(private_key_bytes: &[u8], key_type: KeyType) -> Result<Vec<u8>> {
    use der::asn1::OctetString;

    let _key_octets = OctetString::new(private_key_bytes).map_err(|e| {
        BottleError::Serialization(format!("Failed to create ML-DSA octet string: {}", e))
    })?;

    use der::asn1::AnyRef;
    let algorithm = AlgorithmIdentifierRef {
        oid: key_type.oid(),
        parameters: Some(AnyRef::NULL),
    };

    let pkcs8 = PrivateKeyInfo::new(algorithm, private_key_bytes);

    pkcs8
        .to_der()
        .map_err(|e| BottleError::Serialization(format!("Failed to encode ML-DSA PKCS#8: {}", e)))
}

#[cfg(feature = "post-quantum")]
fn marshal_slhdsa_pkix(public_key_bytes: &[u8], key_type: KeyType) -> Result<Vec<u8>> {
    use der::asn1::BitString;

    let key_bits = BitString::from_bytes(public_key_bytes).map_err(|e| {
        BottleError::Serialization(format!("Failed to create SLH-DSA bit string: {}", e))
    })?;

    use der::asn1::AnyRef;
    let algorithm = AlgorithmIdentifier {
        oid: key_type.oid(),
        parameters: Some(AnyRef::NULL),
    };

    let spki = SubjectPublicKeyInfo {
        algorithm,
        subject_public_key: key_bits,
    };

    spki.to_der()
        .map_err(|e| BottleError::Serialization(format!("Failed to encode SLH-DSA PKIX: {}", e)))
}

#[cfg(feature = "post-quantum")]
fn marshal_slhdsa_pkcs8(private_key_bytes: &[u8], key_type: KeyType) -> Result<Vec<u8>> {
    use der::asn1::OctetString;

    let _key_octets = OctetString::new(private_key_bytes).map_err(|e| {
        BottleError::Serialization(format!("Failed to create SLH-DSA octet string: {}", e))
    })?;

    use der::asn1::AnyRef;
    let algorithm = AlgorithmIdentifierRef {
        oid: key_type.oid(),
        parameters: Some(AnyRef::NULL),
    };

    let pkcs8 = PrivateKeyInfo::new(algorithm, private_key_bytes);

    pkcs8
        .to_der()
        .map_err(|e| BottleError::Serialization(format!("Failed to encode SLH-DSA PKCS#8: {}", e)))
}

/// Detect key type from public key bytes
fn detect_key_type_from_public_key(public_key_bytes: &[u8]) -> Result<KeyType> {
    match public_key_bytes.len() {
        32 => {
            // Could be Ed25519, X25519, or SLH-DSA-128s - try Ed25519 first (more common for signing)
            // In practice, you'd need context or try both
            #[cfg(feature = "post-quantum")]
            {
                // If post-quantum is enabled, could be SLH-DSA-128s, but default to Ed25519
                Ok(KeyType::Ed25519)
            }
            #[cfg(not(feature = "post-quantum"))]
            {
                Ok(KeyType::Ed25519)
            }
        }
        65 => {
            // SEC1 uncompressed format (0x04 prefix) - likely ECDSA P-256
            if public_key_bytes[0] == 0x04 {
                Ok(KeyType::EcdsaP256)
            } else {
                Err(BottleError::InvalidKeyType)
            }
        }
        97 => {
            // SEC1 uncompressed format for P-384
            if public_key_bytes[0] == 0x04 {
                Ok(KeyType::EcdsaP384)
            } else {
                Err(BottleError::InvalidKeyType)
            }
        }
        133 => {
            // SEC1 uncompressed format for P-521
            if public_key_bytes[0] == 0x04 {
                Ok(KeyType::EcdsaP521)
            } else {
                Err(BottleError::InvalidKeyType)
            }
        }
        1184 => {
            #[cfg(feature = "ml-kem")]
            {
                Ok(KeyType::MlKem768)
            }
            #[cfg(not(feature = "ml-kem"))]
            {
                Err(BottleError::InvalidKeyType)
            }
        }
        1568 => {
            #[cfg(feature = "ml-kem")]
            {
                Ok(KeyType::MlKem1024)
            }
            #[cfg(not(feature = "ml-kem"))]
            {
                Err(BottleError::InvalidKeyType)
            }
        }
        1312 => {
            #[cfg(feature = "post-quantum")]
            {
                Ok(KeyType::MlDsa44)
            }
            #[cfg(not(feature = "post-quantum"))]
            {
                Err(BottleError::InvalidKeyType)
            }
        }
        1952 => {
            #[cfg(feature = "post-quantum")]
            {
                Ok(KeyType::MlDsa65)
            }
            #[cfg(not(feature = "post-quantum"))]
            {
                Err(BottleError::InvalidKeyType)
            }
        }
        2592 => {
            #[cfg(feature = "post-quantum")]
            {
                Ok(KeyType::MlDsa87)
            }
            #[cfg(not(feature = "post-quantum"))]
            {
                Err(BottleError::InvalidKeyType)
            }
        }
        48 => {
            #[cfg(feature = "post-quantum")]
            {
                Ok(KeyType::SlhDsa192s)
            }
            #[cfg(not(feature = "post-quantum"))]
            {
                Err(BottleError::InvalidKeyType)
            }
        }
        64 => {
            #[cfg(feature = "post-quantum")]
            {
                Ok(KeyType::SlhDsa256s)
            }
            #[cfg(not(feature = "post-quantum"))]
            {
                Err(BottleError::InvalidKeyType)
            }
        }
        _ => Err(BottleError::InvalidKeyType),
    }
}