riptering 0.6.2

Maintained fork of kryptering: cryptographic operations with RustCrypto or AWS-LC software providers and PKCS#11 HSM backends
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
use std::sync::Arc;

use p521::elliptic_curve::sec1::ToEncodedPoint;
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};

use crate::backend::{require_supported, KeyAlgorithm, Operation};
use crate::error::{Error, Result};
use crate::parameters::DhParameters;

/// Opaque, shared software-key handle.
///
/// Cloning this value clones an [`Arc`], not private material. Provider
/// implementation types are intentionally absent from the public API. Secret
/// material is zeroized when the final handle is dropped; dropping one clone
/// does not invalidate or zeroize the allocation still shared by other clones.
#[derive(Clone)]
pub struct SoftwareKey(Arc<RustCryptoKey>);

impl std::fmt::Debug for SoftwareKey {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("SoftwareKey")
            .field("algorithm", &self.algorithm())
            .field("has_private_key", &self.has_private_key())
            .finish_non_exhaustive()
    }
}

impl SoftwareKey {
    pub(crate) fn inner(&self) -> &RustCryptoKey {
        &self.0
    }

    pub(crate) fn from_rustcrypto(key: RustCryptoKey) -> Self {
        Self(Arc::new(key))
    }

    /// Import a private key encoded as PKCS#8 DER.
    pub fn from_pkcs8_der(algorithm: KeyAlgorithm, der: &[u8]) -> Result<Self> {
        require_supported(Operation::KeyImport(algorithm))?;
        let der = Zeroizing::new(der.to_vec());
        let key = match algorithm {
            KeyAlgorithm::Rsa => {
                use rsa::pkcs8::DecodePrivateKey;
                let private = rsa::RsaPrivateKey::from_pkcs8_der(&der)
                    .map_err(|e| Error::Key(format!("RSA PKCS#8 import failed: {e}")))?;
                let public = private.to_public_key();
                RustCryptoKey::Rsa {
                    private: Some(private),
                    public,
                }
            }
            KeyAlgorithm::Ec(crate::algorithm::EcCurve::P256) => {
                use p256::pkcs8::DecodePrivateKey;
                let private = p256::ecdsa::SigningKey::from_pkcs8_der(&der)
                    .map_err(|e| Error::Key(format!("P-256 PKCS#8 import failed: {e}")))?;
                let public = *private.verifying_key();
                RustCryptoKey::EcP256 {
                    private: Some(private),
                    public,
                }
            }
            KeyAlgorithm::Ec(crate::algorithm::EcCurve::P384) => {
                use p384::pkcs8::DecodePrivateKey;
                let private = p384::ecdsa::SigningKey::from_pkcs8_der(&der)
                    .map_err(|e| Error::Key(format!("P-384 PKCS#8 import failed: {e}")))?;
                let public = *private.verifying_key();
                RustCryptoKey::EcP384 {
                    private: Some(private),
                    public,
                }
            }
            KeyAlgorithm::Ec(crate::algorithm::EcCurve::P521) => {
                use p521::pkcs8::DecodePrivateKey;
                let secret = p521::SecretKey::from_pkcs8_der(&der)
                    .map_err(|e| Error::Key(format!("P-521 PKCS#8 import failed: {e}")))?;
                let secret_bytes = Zeroizing::new(secret.to_bytes());
                let private = p521::ecdsa::SigningKey::from_slice(secret_bytes.as_slice())
                    .map_err(|e| Error::Key(format!("P-521 signing key import failed: {e}")))?;
                let public = p521::ecdsa::VerifyingKey::from(&private);
                RustCryptoKey::EcP521 {
                    private: Some(private),
                    public,
                }
            }
            KeyAlgorithm::Ed25519 => {
                use ed25519_dalek::pkcs8::DecodePrivateKey;
                let private = ed25519_dalek::SigningKey::from_pkcs8_der(&der)
                    .map_err(|e| Error::Key(format!("Ed25519 PKCS#8 import failed: {e}")))?;
                let public = private.verifying_key();
                RustCryptoKey::Ed25519 {
                    private: Some(private),
                    public,
                }
            }
            #[cfg(feature = "legacy")]
            KeyAlgorithm::Dsa => {
                use dsa::pkcs8::DecodePrivateKey;
                let private = dsa::SigningKey::from_pkcs8_der(&der)
                    .map_err(|e| Error::Key(format!("DSA PKCS#8 import failed: {e}")))?;
                let public = private.verifying_key().clone();
                RustCryptoKey::Dsa {
                    private: Some(private),
                    public,
                }
            }
            _ => {
                return Err(Error::unsupported(
                    Operation::KeyImport(algorithm),
                    "PKCS#8 for requested key family",
                ))
            }
        };
        Ok(Self::from_rustcrypto(key))
    }

    /// Import a public key encoded as SubjectPublicKeyInfo DER.
    pub fn from_spki_der(algorithm: KeyAlgorithm, der: &[u8]) -> Result<Self> {
        require_supported(Operation::KeyImport(algorithm))?;
        let key = match algorithm {
            KeyAlgorithm::Rsa => {
                use rsa::pkcs8::DecodePublicKey;
                let public = rsa::RsaPublicKey::from_public_key_der(der)
                    .map_err(|e| Error::Key(format!("RSA SPKI import failed: {e}")))?;
                RustCryptoKey::Rsa {
                    private: None,
                    public,
                }
            }
            KeyAlgorithm::Ec(crate::algorithm::EcCurve::P256) => {
                use p256::pkcs8::DecodePublicKey;
                let public = p256::ecdsa::VerifyingKey::from_public_key_der(der)
                    .map_err(|e| Error::Key(format!("P-256 SPKI import failed: {e}")))?;
                RustCryptoKey::EcP256 {
                    private: None,
                    public,
                }
            }
            KeyAlgorithm::Ec(crate::algorithm::EcCurve::P384) => {
                use p384::pkcs8::DecodePublicKey;
                let public = p384::ecdsa::VerifyingKey::from_public_key_der(der)
                    .map_err(|e| Error::Key(format!("P-384 SPKI import failed: {e}")))?;
                RustCryptoKey::EcP384 {
                    private: None,
                    public,
                }
            }
            KeyAlgorithm::Ec(crate::algorithm::EcCurve::P521) => {
                use p521::pkcs8::DecodePublicKey;
                let public = p521::PublicKey::from_public_key_der(der)
                    .map_err(|e| Error::Key(format!("P-521 SPKI import failed: {e}")))?;
                let public =
                    p521::ecdsa::VerifyingKey::from_encoded_point(&public.to_encoded_point(false))
                        .map_err(|e| {
                            Error::Key(format!("P-521 verifying key import failed: {e}"))
                        })?;
                RustCryptoKey::EcP521 {
                    private: None,
                    public,
                }
            }
            KeyAlgorithm::Ed25519 => {
                use ed25519_dalek::pkcs8::DecodePublicKey;
                let public = ed25519_dalek::VerifyingKey::from_public_key_der(der)
                    .map_err(|e| Error::Key(format!("Ed25519 SPKI import failed: {e}")))?;
                RustCryptoKey::Ed25519 {
                    private: None,
                    public,
                }
            }
            #[cfg(feature = "legacy")]
            KeyAlgorithm::Dsa => {
                use dsa::pkcs8::DecodePublicKey;
                let public = dsa::VerifyingKey::from_public_key_der(der)
                    .map_err(|e| Error::Key(format!("DSA SPKI import failed: {e}")))?;
                RustCryptoKey::Dsa {
                    private: None,
                    public,
                }
            }
            _ => {
                return Err(Error::unsupported(
                    Operation::KeyImport(algorithm),
                    "SPKI for requested key family",
                ))
            }
        };
        Ok(Self::from_rustcrypto(key))
    }

    /// Import raw symmetric key bytes.
    pub fn from_symmetric_bytes(algorithm: KeyAlgorithm, bytes: &[u8]) -> Result<Self> {
        require_supported(Operation::KeyImport(algorithm))?;
        if bytes.is_empty() {
            return Err(Error::Key("symmetric key must not be empty".into()));
        }
        let key = match algorithm {
            KeyAlgorithm::Hmac => RustCryptoKey::Hmac(bytes.to_vec()),
            KeyAlgorithm::Aes if matches!(bytes.len(), 16 | 24 | 32) => {
                RustCryptoKey::Aes(bytes.to_vec())
            }
            KeyAlgorithm::Aes => {
                return Err(Error::Key("AES keys must be 16, 24, or 32 bytes".into()))
            }
            #[cfg(feature = "legacy")]
            KeyAlgorithm::TripleDes if bytes.len() == 24 => RustCryptoKey::Des3(bytes.to_vec()),
            #[cfg(feature = "legacy")]
            KeyAlgorithm::TripleDes => return Err(Error::Key("3DES keys must be 24 bytes".into())),
            _ => {
                return Err(Error::unsupported(
                    Operation::KeyImport(algorithm),
                    "raw symmetric bytes for requested key family",
                ))
            }
        };
        Ok(Self::from_rustcrypto(key))
    }

    /// Import raw X25519 key components.
    pub fn from_x25519(private: Option<&[u8]>, public: &[u8]) -> Result<Self> {
        require_supported(Operation::KeyImport(KeyAlgorithm::X25519))?;
        let public: [u8; 32] = public
            .try_into()
            .map_err(|_| Error::Key("X25519 public key must be 32 bytes".into()))?;
        let private = private
            .map(|value| {
                value
                    .try_into()
                    .map_err(|_| Error::Key("X25519 private key must be 32 bytes".into()))
            })
            .transpose()?;
        Ok(Self::from_rustcrypto(RustCryptoKey::X25519 {
            private,
            public,
        }))
    }

    /// Import provider-neutral finite-field Diffie-Hellman components.
    ///
    /// All integers use unsigned big-endian encoding. This constructor only
    /// imports and protects the key material; agreement still returns
    /// `UnsupportedAlgorithm` when the selected provider has no safe
    /// finite-field DH implementation.
    pub fn from_dh_parameters(
        modulus: &[u8],
        generator: &[u8],
        subgroup_order: Option<&[u8]>,
        private: Option<&[u8]>,
        public: &[u8],
    ) -> Result<Self> {
        require_supported(Operation::KeyImport(KeyAlgorithm::Dh))?;
        if modulus.is_empty() || generator.is_empty() || public.is_empty() {
            return Err(Error::Key(
                "DH modulus, generator, and public key must not be empty".into(),
            ));
        }
        if subgroup_order.is_some_and(<[u8]>::is_empty) {
            return Err(Error::Key("DH subgroup order must not be empty".into()));
        }
        if private.is_some_and(<[u8]>::is_empty) {
            return Err(Error::Key("DH private exponent must not be empty".into()));
        }
        Ok(Self::from_rustcrypto(RustCryptoKey::Dh {
            private: private.map(<[u8]>::to_vec),
            parameters: DhParameters::new(modulus, generator, subgroup_order, public),
        }))
    }

    /// Import provider-neutral post-quantum key encodings.
    ///
    /// `private_der` is a PKCS#8 encoding when present and `public_der` is an
    /// SPKI encoding. The selected provider validates support before any key
    /// material is retained. Both encodings must parse, and when a private key
    /// is present the public key derived from it must match `public_der`.
    #[cfg(feature = "post-quantum")]
    pub fn from_post_quantum_der(
        algorithm: crate::algorithm::PqAlgorithm,
        private_der: Option<&[u8]>,
        public_der: &[u8],
    ) -> Result<Self> {
        let key_algorithm = KeyAlgorithm::PostQuantum(algorithm);
        require_supported(Operation::KeyImport(key_algorithm))?;
        if public_der.is_empty() {
            return Err(Error::Key("post-quantum SPKI must not be empty".into()));
        }
        match algorithm {
            crate::algorithm::PqAlgorithm::MlDsa(_) | crate::algorithm::PqAlgorithm::SlhDsa(_) => {
                crate::software::sign::validate_pq_import(algorithm, private_der, public_der)?
            }
            crate::algorithm::PqAlgorithm::MlKem(variant) => {
                crate::software::kem::validate_import(variant, private_der, public_der)?
            }
        }
        Ok(Self::from_rustcrypto(RustCryptoKey::PostQuantum {
            algorithm,
            private_der: private_der.map(|value| value.to_vec()),
            public_der: public_der.to_vec(),
        }))
    }

    /// Import an aggregate raw composite ML-DSA key.
    ///
    /// The public key is `ML-DSA public || traditional public`. When present,
    /// the private key is `32-byte ML-DSA seed || traditional private`.
    /// Component encodings and lengths are fixed by `variant`; DER encodings
    /// are not accepted. The imported public key is checked against the
    /// private key.
    ///
    /// Importers are responsible for the draft's key-origin rule: neither
    /// component may have been used independently or in another composite
    /// combination.
    #[cfg(feature = "post-quantum")]
    pub fn from_composite_ml_dsa(
        variant: crate::algorithm::CompositeMlDsaVariant,
        private: Option<&[u8]>,
        public: &[u8],
    ) -> Result<Self> {
        let key_algorithm = KeyAlgorithm::CompositeMlDsa(variant);
        require_supported(Operation::KeyImport(key_algorithm))?;
        crate::software::composite::validate_import(variant, private, public)?;
        Ok(Self::from_rustcrypto(RustCryptoKey::CompositeMlDsa {
            variant,
            private: private.map(<[u8]>::to_vec),
            public: public.to_vec(),
        }))
    }

    pub fn algorithm(&self) -> KeyAlgorithm {
        match self.inner() {
            RustCryptoKey::Rsa { .. } => KeyAlgorithm::Rsa,
            RustCryptoKey::EcP256 { .. } => KeyAlgorithm::Ec(crate::algorithm::EcCurve::P256),
            RustCryptoKey::EcP384 { .. } => KeyAlgorithm::Ec(crate::algorithm::EcCurve::P384),
            RustCryptoKey::EcP521 { .. } => KeyAlgorithm::Ec(crate::algorithm::EcCurve::P521),
            RustCryptoKey::Ed25519 { .. } => KeyAlgorithm::Ed25519,
            RustCryptoKey::X25519 { .. } => KeyAlgorithm::X25519,
            RustCryptoKey::Dh { .. } => KeyAlgorithm::Dh,
            RustCryptoKey::Hmac(_) => KeyAlgorithm::Hmac,
            RustCryptoKey::Aes(_) => KeyAlgorithm::Aes,
            #[cfg(feature = "legacy")]
            RustCryptoKey::Dsa { .. } => KeyAlgorithm::Dsa,
            #[cfg(feature = "legacy")]
            RustCryptoKey::Des3(_) => KeyAlgorithm::TripleDes,
            #[cfg(feature = "post-quantum")]
            RustCryptoKey::PostQuantum { algorithm, .. } => KeyAlgorithm::PostQuantum(*algorithm),
            #[cfg(feature = "post-quantum")]
            RustCryptoKey::CompositeMlDsa { variant, .. } => KeyAlgorithm::CompositeMlDsa(*variant),
        }
    }

    pub fn has_private_key(&self) -> bool {
        match self.inner() {
            RustCryptoKey::Rsa { private, .. } => private.is_some(),
            RustCryptoKey::EcP256 { private, .. } => private.is_some(),
            RustCryptoKey::EcP384 { private, .. } => private.is_some(),
            RustCryptoKey::EcP521 { private, .. } => private.is_some(),
            RustCryptoKey::Ed25519 { private, .. } => private.is_some(),
            RustCryptoKey::X25519 { private, .. } => private.is_some(),
            RustCryptoKey::Dh { private, .. } => private.is_some(),
            RustCryptoKey::Hmac(_) | RustCryptoKey::Aes(_) => true,
            #[cfg(feature = "legacy")]
            RustCryptoKey::Dsa { private, .. } => private.is_some(),
            #[cfg(feature = "legacy")]
            RustCryptoKey::Des3(_) => true,
            #[cfg(feature = "post-quantum")]
            RustCryptoKey::PostQuantum { private_der, .. } => private_der.is_some(),
            #[cfg(feature = "post-quantum")]
            RustCryptoKey::CompositeMlDsa { private, .. } => private.is_some(),
        }
    }

    /// Return a neutral public component: SPKI DER for ordinary public-key
    /// algorithms, raw X25519/DH values, or an aggregate raw composite key.
    pub fn public_component(&self) -> Result<Vec<u8>> {
        use rsa::pkcs8::EncodePublicKey;
        match self.inner() {
            RustCryptoKey::Rsa { public, .. } => public
                .to_public_key_der()
                .map(|der| der.as_bytes().to_vec())
                .map_err(|e| Error::Key(format!("RSA SPKI export failed: {e}"))),
            RustCryptoKey::EcP256 { public, .. } => public
                .to_public_key_der()
                .map(|der| der.as_bytes().to_vec())
                .map_err(|e| Error::Key(format!("P-256 SPKI export failed: {e}"))),
            RustCryptoKey::EcP384 { public, .. } => public
                .to_public_key_der()
                .map(|der| der.as_bytes().to_vec())
                .map_err(|e| Error::Key(format!("P-384 SPKI export failed: {e}"))),
            RustCryptoKey::EcP521 { public, .. } => {
                p521::PublicKey::from_sec1_bytes(public.to_encoded_point(false).as_bytes())
                    .map_err(|e| Error::Key(format!("P-521 public conversion failed: {e}")))?
                    .to_public_key_der()
                    .map(|der| der.as_bytes().to_vec())
                    .map_err(|e| Error::Key(format!("P-521 SPKI export failed: {e}")))
            }
            RustCryptoKey::Ed25519 { public, .. } => public
                .to_public_key_der()
                .map(|der| der.as_bytes().to_vec())
                .map_err(|e| Error::Key(format!("Ed25519 SPKI export failed: {e}"))),
            RustCryptoKey::X25519 { public, .. } => Ok(public.to_vec()),
            RustCryptoKey::Dh { parameters, .. } => Ok(parameters.public_key().to_vec()),
            #[cfg(feature = "legacy")]
            RustCryptoKey::Dsa { public, .. } => public
                .to_public_key_der()
                .map(|der| der.as_bytes().to_vec())
                .map_err(|e| Error::Key(format!("DSA SPKI export failed: {e}"))),
            #[cfg(feature = "post-quantum")]
            RustCryptoKey::PostQuantum { public_der, .. } => Ok(public_der.clone()),
            #[cfg(feature = "post-quantum")]
            RustCryptoKey::CompositeMlDsa { public, .. } => Ok(public.clone()),
            _ => Err(Error::Key("symmetric keys have no public component".into())),
        }
    }

    /// Explicitly export the public component as SPKI DER.
    ///
    /// X25519 retains its historical raw-byte behavior. Composite ML-DSA keys
    /// are rejected because their draft encoding is an aggregate raw value;
    /// use `export_composite_public` (available with the `post-quantum`
    /// feature).
    pub fn export_spki_der(&self) -> Result<Vec<u8>> {
        require_supported(Operation::KeyExport(self.algorithm()))?;
        #[cfg(feature = "post-quantum")]
        if matches!(self.inner(), RustCryptoKey::CompositeMlDsa { .. }) {
            return Err(Error::Key(
                "composite ML-DSA keys have no SPKI encoding; use export_composite_public".into(),
            ));
        }
        self.public_component()
    }

    /// Explicitly export private or symmetric key material into a zeroizing buffer.
    pub fn export_private(&self) -> Result<Zeroizing<Vec<u8>>> {
        require_supported(Operation::KeyExport(self.algorithm()))?;
        use rsa::pkcs8::EncodePrivateKey;
        let bytes = match self.inner() {
            RustCryptoKey::Rsa {
                private: Some(private),
                ..
            } => private
                .to_pkcs8_der()
                .map(|der| der.as_bytes().to_vec())
                .map_err(|e| Error::Key(format!("RSA PKCS#8 export failed: {e}")))?,
            RustCryptoKey::EcP256 {
                private: Some(private),
                ..
            } => private
                .to_pkcs8_der()
                .map(|der| der.as_bytes().to_vec())
                .map_err(|e| Error::Key(format!("P-256 PKCS#8 export failed: {e}")))?,
            RustCryptoKey::EcP384 {
                private: Some(private),
                ..
            } => private
                .to_pkcs8_der()
                .map(|der| der.as_bytes().to_vec())
                .map_err(|e| Error::Key(format!("P-384 PKCS#8 export failed: {e}")))?,
            RustCryptoKey::EcP521 {
                private: Some(private),
                ..
            } => p521::SecretKey::from_slice(Zeroizing::new(private.to_bytes()).as_slice())
                .map_err(|e| Error::Key(format!("P-521 private conversion failed: {e}")))?
                .to_pkcs8_der()
                .map(|der| der.as_bytes().to_vec())
                .map_err(|e| Error::Key(format!("P-521 PKCS#8 export failed: {e}")))?,
            RustCryptoKey::Ed25519 {
                private: Some(private),
                ..
            } => private
                .to_pkcs8_der()
                .map(|der| der.as_bytes().to_vec())
                .map_err(|e| Error::Key(format!("Ed25519 PKCS#8 export failed: {e}")))?,
            RustCryptoKey::X25519 {
                private: Some(private),
                ..
            } => private.to_vec(),
            RustCryptoKey::Dh {
                private: Some(private),
                ..
            } => private.clone(),
            RustCryptoKey::Hmac(bytes) | RustCryptoKey::Aes(bytes) => bytes.clone(),
            #[cfg(feature = "legacy")]
            RustCryptoKey::Dsa {
                private: Some(private),
                ..
            } => private
                .to_pkcs8_der()
                .map(|der| der.as_bytes().to_vec())
                .map_err(|e| Error::Key(format!("DSA PKCS#8 export failed: {e}")))?,
            #[cfg(feature = "legacy")]
            RustCryptoKey::Des3(bytes) => bytes.clone(),
            #[cfg(feature = "post-quantum")]
            RustCryptoKey::PostQuantum {
                private_der: Some(private),
                ..
            } => private.clone(),
            #[cfg(feature = "post-quantum")]
            RustCryptoKey::CompositeMlDsa {
                private: Some(private),
                ..
            } => private.clone(),
            _ => return Err(Error::Key("key has no private material".into())),
        };
        Ok(Zeroizing::new(bytes))
    }

    /// Export the aggregate raw public key for a composite ML-DSA key.
    #[cfg(feature = "post-quantum")]
    pub fn export_composite_public(&self) -> Result<Vec<u8>> {
        require_supported(Operation::KeyExport(self.algorithm()))?;
        match self.inner() {
            RustCryptoKey::CompositeMlDsa { public, .. } => Ok(public.clone()),
            _ => Err(Error::Key("composite ML-DSA key required".into())),
        }
    }

    /// Export the aggregate raw private key into a zeroizing buffer.
    #[cfg(feature = "post-quantum")]
    pub fn export_composite_private(&self) -> Result<Zeroizing<Vec<u8>>> {
        require_supported(Operation::KeyExport(self.algorithm()))?;
        match self.inner() {
            RustCryptoKey::CompositeMlDsa {
                private: Some(private),
                ..
            } => Ok(Zeroizing::new(private.clone())),
            RustCryptoKey::CompositeMlDsa { private: None, .. } => {
                Err(Error::Key("key has no private material".into()))
            }
            _ => Err(Error::Key("composite ML-DSA key required".into())),
        }
    }

    /// Return neutral finite-field DH public parameters when this is a DH key.
    #[must_use]
    pub fn dh_parameters(&self) -> Option<&DhParameters> {
        match self.inner() {
            RustCryptoKey::Dh { parameters, .. } => Some(parameters),
            _ => None,
        }
    }
}

pub(crate) enum RustCryptoKey {
    Rsa {
        private: Option<rsa::RsaPrivateKey>,
        public: rsa::RsaPublicKey,
    },
    EcP256 {
        private: Option<p256::ecdsa::SigningKey>,
        public: p256::ecdsa::VerifyingKey,
    },
    EcP384 {
        private: Option<p384::ecdsa::SigningKey>,
        public: p384::ecdsa::VerifyingKey,
    },
    EcP521 {
        private: Option<p521::ecdsa::SigningKey>,
        public: p521::ecdsa::VerifyingKey,
    },
    Ed25519 {
        private: Option<ed25519_dalek::SigningKey>,
        public: ed25519_dalek::VerifyingKey,
    },
    X25519 {
        private: Option<[u8; 32]>,
        public: [u8; 32],
    },
    Dh {
        private: Option<Vec<u8>>,
        parameters: DhParameters,
    },
    Hmac(Vec<u8>),
    Aes(Vec<u8>),
    #[cfg(feature = "legacy")]
    Dsa {
        private: Option<dsa::SigningKey>,
        public: dsa::VerifyingKey,
    },
    #[cfg(feature = "legacy")]
    Des3(Vec<u8>),
    #[cfg(feature = "post-quantum")]
    PostQuantum {
        algorithm: crate::algorithm::PqAlgorithm,
        private_der: Option<Vec<u8>>,
        public_der: Vec<u8>,
    },
    #[cfg(feature = "post-quantum")]
    CompositeMlDsa {
        variant: crate::algorithm::CompositeMlDsaVariant,
        private: Option<Vec<u8>>,
        public: Vec<u8>,
    },
}

impl Drop for RustCryptoKey {
    fn drop(&mut self) {
        match self {
            RustCryptoKey::Hmac(bytes) | RustCryptoKey::Aes(bytes) => bytes.zeroize(),
            RustCryptoKey::X25519 { private, .. } => {
                if let Some(bytes) = private {
                    bytes.zeroize();
                }
            }
            RustCryptoKey::Dh { private, .. } => {
                if let Some(bytes) = private {
                    bytes.zeroize();
                }
            }
            #[cfg(feature = "legacy")]
            RustCryptoKey::Des3(bytes) => bytes.zeroize(),
            #[cfg(feature = "post-quantum")]
            RustCryptoKey::PostQuantum { private_der, .. } => {
                if let Some(der) = private_der {
                    der.zeroize();
                }
            }
            #[cfg(feature = "post-quantum")]
            RustCryptoKey::CompositeMlDsa { private, .. } => {
                if let Some(bytes) = private {
                    bytes.zeroize();
                }
            }
            RustCryptoKey::Rsa { .. }
            | RustCryptoKey::EcP256 { .. }
            | RustCryptoKey::EcP384 { .. }
            | RustCryptoKey::EcP521 { .. }
            | RustCryptoKey::Ed25519 { .. } => {}
            #[cfg(feature = "legacy")]
            RustCryptoKey::Dsa { .. } => {}
        }
    }
}

impl ZeroizeOnDrop for RustCryptoKey {}

/// Smallest RSA modulus accepted by any provider, matching AWS-LC's
/// `RSA_*_2048_8192_*` verification floor.
pub(crate) const MIN_RSA_BITS: usize = 2048;

/// Reject RSA keys below [`MIN_RSA_BITS`] with the same error the AWS-LC
/// provider reports, so both providers refuse the same key sizes.
pub(crate) fn enforce_rsa_min_bits(operation: Operation, public: &rsa::RsaPublicKey) -> Result<()> {
    use rsa::traits::PublicKeyParts;
    // `legacy` restores interoperability with historical signatures and
    // encrypted documents that use shorter keys, such as the xmlsec interop
    // corpus. The AWS-LC provider never accepts them.
    if cfg!(feature = "legacy") {
        return Ok(());
    }
    let bits = public.n().bits();
    if bits < MIN_RSA_BITS {
        return Err(Error::unsupported(
            operation,
            format!("{bits}-bit RSA key (riptering requires at least {MIN_RSA_BITS} bits)"),
        ));
    }
    Ok(())
}

impl From<RustCryptoKey> for SoftwareKey {
    fn from(key: RustCryptoKey) -> Self {
        Self::from_rustcrypto(key)
    }
}

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

    #[test]
    fn underlying_key_material_is_zeroize_on_drop() {
        fn assert_zeroize_on_drop<T: ZeroizeOnDrop>() {}
        assert_zeroize_on_drop::<RustCryptoKey>();
    }

    #[test]
    fn debug_redacts_secret() {
        let key = SoftwareKey::from_symmetric_bytes(KeyAlgorithm::Hmac, b"do-not-print").unwrap();
        let debug = format!("{key:?}");
        assert!(!debug.contains("do-not-print"));
    }

    #[test]
    fn cloning_shares_opaque_handle() {
        let key = SoftwareKey::from_symmetric_bytes(KeyAlgorithm::Aes, &[7; 32]).unwrap();
        let clone = key.clone();
        assert!(Arc::ptr_eq(&key.0, &clone.0));
    }

    #[test]
    fn short_rsa_keys_import_and_are_checked_when_used() {
        // The 2048-bit minimum applies when a key signs, verifies or
        // transports a key, so callers get the key-size error at that point.
        use rsa::pkcs8::{EncodePrivateKey, EncodePublicKey};
        let private = rsa::RsaPrivateKey::new(&mut rand::rngs::OsRng, 1024).unwrap();
        let pkcs8 = private.to_pkcs8_der().unwrap();
        let spki = private.to_public_key().to_public_key_der().unwrap();
        assert!(SoftwareKey::from_pkcs8_der(KeyAlgorithm::Rsa, pkcs8.as_bytes()).is_ok());
        assert!(SoftwareKey::from_spki_der(KeyAlgorithm::Rsa, spki.as_bytes()).is_ok());
    }

    #[cfg(feature = "post-quantum")]
    #[test]
    fn post_quantum_import_requires_matching_parseable_keys() {
        use crate::algorithm::{MlDsaVariant, MlKemVariant, PqAlgorithm};

        let cases = [
            (
                PqAlgorithm::MlDsa(MlDsaVariant::MlDsa44),
                crate::software::sign::generate_ml_dsa(MlDsaVariant::MlDsa44).unwrap(),
                crate::software::sign::generate_ml_dsa(MlDsaVariant::MlDsa44).unwrap(),
            ),
            (
                PqAlgorithm::MlKem(MlKemVariant::MlKem512),
                crate::software::kem::generate_ml_kem(MlKemVariant::MlKem512).unwrap(),
                crate::software::kem::generate_ml_kem(MlKemVariant::MlKem512).unwrap(),
            ),
        ];
        for (algorithm, a, b) in cases {
            let a_private = a.export_private().unwrap();
            let a_public = a.public_component().unwrap();
            let b_public = b.public_component().unwrap();

            SoftwareKey::from_post_quantum_der(algorithm, Some(&a_private), &a_public)
                .expect("matching pair imports");
            SoftwareKey::from_post_quantum_der(algorithm, None, &a_public)
                .expect("public-only import");

            let err = SoftwareKey::from_post_quantum_der(algorithm, Some(&a_private), &b_public)
                .unwrap_err();
            assert!(err.to_string().contains("does not match"), "{err}");
            let err =
                SoftwareKey::from_post_quantum_der(algorithm, None, b"not an SPKI").unwrap_err();
            assert!(err.to_string().contains("failed to parse"), "{err}");
            let err = SoftwareKey::from_post_quantum_der(algorithm, Some(b"junk"), &a_public)
                .unwrap_err();
            assert!(err.to_string().contains("failed to parse"), "{err}");
        }
    }

    #[cfg(feature = "post-quantum")]
    #[test]
    fn slh_dsa_import_rejects_private_key_with_forged_public_half() {
        use crate::algorithm::{PqAlgorithm, SlhDsaVariant};
        use pkcs8_pq::spki::EncodePublicKey;

        // Fixed test seeds (n = 16 for SHA2-128f).
        type P = slh_dsa::Sha2_128f;
        let sk = slh_dsa::SigningKey::<P>::slh_keygen_internal(&[1; 16], &[2; 16], &[3; 16]);
        let other = slh_dsa::SigningKey::<P>::slh_keygen_internal(&[4; 16], &[5; 16], &[6; 16]);
        let other_public: &slh_dsa::VerifyingKey<_> = other.as_ref();
        let other_spki = other_public.to_public_key_der().unwrap();
        // Splice the other key's PK.seed || PK.root onto this key's secrets:
        // the embedded public half now matches the SPKI but not the seeds.
        let mut forged = sk.to_bytes().to_vec();
        let n = forged.len() / 4;
        forged[2 * n..].copy_from_slice(&other_public.to_bytes());

        let algorithm = PqAlgorithm::SlhDsa(SlhDsaVariant::Sha2_128f);
        let err =
            SoftwareKey::from_post_quantum_der(algorithm, Some(&forged), other_spki.as_bytes())
                .unwrap_err();
        assert!(err.to_string().contains("does not match"), "{err}");
    }

    #[test]
    fn imports_neutral_dh_parameters_without_exposing_private_exponent() {
        let key = SoftwareKey::from_dh_parameters(&[23], &[4], Some(&[11]), Some(&[5]), &[12])
            .expect("DH import");
        assert_eq!(key.algorithm(), KeyAlgorithm::Dh);
        assert!(key.has_private_key());
        assert_eq!(key.public_component().unwrap(), vec![12]);
        let parameters = key.dh_parameters().expect("DH parameters");
        assert_eq!(parameters.modulus(), &[23]);
        assert_eq!(parameters.generator(), &[4]);
        assert_eq!(parameters.subgroup_order(), Some(&[11][..]));
        assert_eq!(key.export_private().unwrap().as_slice(), &[5]);
        assert!(!format!("{key:?}").contains('5'));
    }
}