synta-certificate 0.2.6

X.509 certificate structures for synta ASN.1 library
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
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
//! Private key abstraction, erased signer trait, and opaque backend key types.

use super::errors::PrivateKeyError;
use super::signature::CertificateSigner;

#[cfg(not(feature = "openssl"))]
use super::errors::NoCryptoError;
#[cfg(not(any(feature = "openssl", feature = "nss")))]
use super::errors::NoSignerError;

// ── ErasedCertificateSigner ───────────────────────────────────────────────────

/// Object-safe [`CertificateSigner`] variant with erased error types.
///
/// Used as the return type of [`PrivateKey::as_signer`] so that different
/// backend implementations can be used without monomorphizing over the error
/// type.  [`crate::CertificateBuilder`] accepts this via the blanket impl of
/// [`CertificateSigner`] below.
pub trait ErasedCertificateSigner {
    /// DER-encoded `AlgorithmIdentifier` for this signer.
    fn signature_algorithm_der_erased(&self) -> Result<Vec<u8>, PrivateKeyError>;
    /// Sign `tbs_der` and return raw signature bytes (no BIT STRING wrapper).
    fn sign_tbs_erased(&self, tbs_der: &[u8]) -> Result<Vec<u8>, PrivateKeyError>;
}

/// Blanket impl: any [`ErasedCertificateSigner`] reference is a [`CertificateSigner`].
///
/// This lets `CertificateBuilder::sign(key.as_signer("sha256").as_ref())` compile
/// without knowing the concrete signer type at the call site.
impl CertificateSigner for dyn ErasedCertificateSigner + '_ {
    type Error = PrivateKeyError;

    fn signature_algorithm_der(&self) -> Result<Vec<u8>, PrivateKeyError> {
        self.signature_algorithm_der_erased()
    }

    fn sign_tbs(&self, tbs_der: &[u8]) -> Result<Vec<u8>, PrivateKeyError> {
        self.sign_tbs_erased(tbs_der)
    }
}

/// Blanket impl: `Box<dyn ErasedCertificateSigner>` implements [`CertificateSigner`].
///
/// This lets a `Box<dyn ErasedCertificateSigner>` (as returned by
/// [`PrivateKey::as_signer`]) be passed directly to [`crate::CertificateBuilder::sign`]
/// without calling `.as_ref()`.
impl CertificateSigner for Box<dyn ErasedCertificateSigner> {
    type Error = PrivateKeyError;

    fn signature_algorithm_der(&self) -> Result<Vec<u8>, PrivateKeyError> {
        self.as_ref().signature_algorithm_der_erased()
    }

    fn sign_tbs(&self, tbs_der: &[u8]) -> Result<Vec<u8>, PrivateKeyError> {
        self.as_ref().sign_tbs_erased(tbs_der)
    }
}

/// Error-reporting signer for unknown composite ML-DSA sub-arcs.
///
/// Returned by `as_signer` when the PKCS#8 OID is in the composite ML-DSA arc
/// but the sub-arc is not one of the 18 recognised values.  All operations fail
/// with the stored message so the error reaches the caller rather than panicking.
#[cfg(any(feature = "openssl", feature = "nss"))]
pub(crate) struct FailedKeySigner(pub String);

#[cfg(any(feature = "openssl", feature = "nss"))]
#[derive(Debug)]
struct FailedKeySignerError(String);
#[cfg(any(feature = "openssl", feature = "nss"))]
impl std::fmt::Display for FailedKeySignerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}
#[cfg(any(feature = "openssl", feature = "nss"))]
impl std::error::Error for FailedKeySignerError {}

#[cfg(any(feature = "openssl", feature = "nss"))]
impl ErasedCertificateSigner for FailedKeySigner {
    fn signature_algorithm_der_erased(&self) -> Result<Vec<u8>, PrivateKeyError> {
        Err(PrivateKeyError::new(FailedKeySignerError(self.0.clone())))
    }

    fn sign_tbs_erased(&self, _tbs_der: &[u8]) -> Result<Vec<u8>, PrivateKeyError> {
        Err(PrivateKeyError::new(FailedKeySignerError(self.0.clone())))
    }
}

/// No-op [`ErasedCertificateSigner`] used when no crypto backend is compiled in.
#[cfg(not(any(feature = "openssl", feature = "nss")))]
pub(crate) struct NoErasedSigner;

#[cfg(not(any(feature = "openssl", feature = "nss")))]
impl ErasedCertificateSigner for NoErasedSigner {
    fn signature_algorithm_der_erased(&self) -> Result<Vec<u8>, PrivateKeyError> {
        Err(PrivateKeyError::new(NoSignerError))
    }

    fn sign_tbs_erased(&self, _tbs_der: &[u8]) -> Result<Vec<u8>, PrivateKeyError> {
        Err(PrivateKeyError::new(NoSignerError))
    }
}

// ── PrivateKey ────────────────────────────────────────────────────────────────

/// A backend-agnostic private key that can produce its public SPKI DER bytes
/// and create a [`CertificateSigner`] for certificate signing.
///
/// Implementations wrap a specific crypto backend (e.g. OpenSSL) and hide its
/// API from callers.  The `OpensslPrivateKey` struct implements this
/// trait when the `openssl` feature is enabled.
///
/// # Object safety
///
/// This trait is object-safe: `Box<dyn PrivateKey>` is valid.
///
/// # Example
///
/// ```rust,ignore
/// use synta_certificate::{PrivateKey, PrivateKeyBuilder, CertificateBuilder};
///
/// let key = PrivateKeyBuilder::ec("P-256").generate()?;
/// let spki_der = key.public_key_spki_der()?;
/// let cert_der = CertificateBuilder::new()
///     .public_key_der(&spki_der)
///     // … other fields …
///     .sign(key.as_signer("sha256").as_ref())?;
/// ```
pub trait PrivateKey {
    /// Return the DER-encoded SubjectPublicKeyInfo for the public half of this key.
    ///
    /// The returned bytes are suitable for use with
    /// [`crate::CertificateBuilder::public_key_der`],
    /// [`crate::encode_subject_key_identifier`], and
    /// [`crate::encode_authority_key_identifier`].
    fn public_key_spki_der(&self) -> Result<Vec<u8>, PrivateKeyError>;

    /// Create a [`CertificateSigner`] for this key with the given hash algorithm.
    ///
    /// `algorithm` selects the hash to use during signing:
    /// - ECDSA / RSA keys: `"sha256"`, `"sha384"`, `"sha512"` (or `"sha1"` if needed).
    /// - Ed25519 / Ed448 keys: the parameter is ignored.
    ///
    /// Returns a boxed signer whose [`CertificateSigner`] methods use
    /// `Box<dyn std::error::Error + Send + Sync>` as the error type.
    fn as_signer(&self, algorithm: &str) -> Box<dyn ErasedCertificateSigner>;
}

// ── PrivateKeyBuilder ─────────────────────────────────────────────────────────

/// Key algorithm and parameters for [`PrivateKeyBuilder`].
///
/// This enum is part of the public API: callers inspect it to discover what
/// algorithm was configured, and backend implementations match on it to
/// dispatch to the appropriate key-generation routine.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum KeySpec {
    /// Elliptic-curve key on a named NIST curve.
    ///
    /// Supported curve names: `"P-256"`, `"P-384"`, `"P-521"`.
    Ec(String),
    /// RSA key with the given modulus bit-length (e.g. 2048, 3072, 4096).
    Rsa(u32),
    /// Ed25519 key (RFC 8032; fixed parameters, no additional configuration).
    Ed25519,
    /// Ed448 key (RFC 8032; fixed parameters, no additional configuration).
    Ed448,
    /// ML-DSA key (FIPS 204 / RFC 9881).
    ///
    /// `parameter_set` selects the security level:
    /// - `"ML-DSA-44"` — NIST security category 2
    /// - `"ML-DSA-65"` — NIST security category 3
    /// - `"ML-DSA-87"` — NIST security category 5
    MlDsa(String),
    /// ML-KEM key (FIPS 203 / draft-ietf-lamps-kyber).
    ///
    /// `parameter_set` selects the security level:
    /// - `"ML-KEM-512"` — NIST security category 1
    /// - `"ML-KEM-768"` — NIST security category 3
    /// - `"ML-KEM-1024"` — NIST security category 5
    MlKem(String),
    /// Composite ML-DSA key (draft-ietf-lamps-pq-composite-sigs-19).
    ///
    /// `sub_arc` is the last component of the OID 1.3.6.1.5.5.7.6.<sub_arc>:
    /// 37–54 for the 18 composite variants.
    #[cfg(any(feature = "openssl", feature = "nss"))]
    CompositeMlDsa(u32),
}

/// Builder for generating asymmetric private keys via the active crypto backend.
///
/// Use the factory methods to select the key algorithm and parameters, then call
/// [`generate`](PrivateKeyBuilder::generate) to produce a backend-agnostic
/// [`PrivateKey`] instance.  All OpenSSL API details are hidden behind the
/// `PrivateKey` trait — callers never need to import `openssl` directly.
///
/// # Example
///
/// ```rust,ignore
/// use synta_certificate::{PrivateKeyBuilder, PrivateKey, CertificateBuilder};
///
/// // Generate an EC P-256 key and get its SPKI DER for the certificate:
/// let key = PrivateKeyBuilder::ec("P-256").generate()?;
/// let spki_der = key.public_key_spki_der()?;
///
/// // Generate an RSA-2048 key:
/// let rsa_key = PrivateKeyBuilder::rsa(2048).generate()?;
///
/// // Generate an Ed25519 key:
/// let ed_key = PrivateKeyBuilder::ed25519().generate()?;
///
/// // Generate an ML-DSA-65 post-quantum key (requires OpenSSL 3.5+):
/// let pqc_key = PrivateKeyBuilder::ml_dsa("ML-DSA-65").generate()?;
/// ```
pub struct PrivateKeyBuilder {
    /// The key algorithm and parameters.
    pub spec: KeySpec,
}

impl PrivateKeyBuilder {
    /// Configure EC key generation on the named curve.
    ///
    /// `curve` must be one of `"P-256"`, `"P-384"`, or `"P-521"`.
    pub fn ec(curve: &str) -> Self {
        Self {
            spec: KeySpec::Ec(curve.to_string()),
        }
    }

    /// Configure RSA key generation with the given modulus bit-length.
    ///
    /// Typical values: `2048`, `3072`, `4096`.
    pub fn rsa(bits: u32) -> Self {
        Self {
            spec: KeySpec::Rsa(bits),
        }
    }

    /// Configure Ed25519 key generation (RFC 8032).
    pub fn ed25519() -> Self {
        Self {
            spec: KeySpec::Ed25519,
        }
    }

    /// Configure Ed448 key generation (RFC 8032).
    pub fn ed448() -> Self {
        Self {
            spec: KeySpec::Ed448,
        }
    }

    /// Configure ML-DSA key generation (FIPS 204 / RFC 9881).
    ///
    /// `parameter_set` selects the security level:
    /// `"ML-DSA-44"`, `"ML-DSA-65"`, or `"ML-DSA-87"`.
    ///
    /// Requires OpenSSL 3.5 or later (or another backend with ML-DSA support).
    pub fn ml_dsa(parameter_set: &str) -> Self {
        Self {
            spec: KeySpec::MlDsa(parameter_set.to_string()),
        }
    }

    /// Configure ML-KEM key generation (FIPS 203).
    ///
    /// `parameter_set` selects the security level:
    /// `"ML-KEM-512"`, `"ML-KEM-768"`, or `"ML-KEM-1024"`.
    ///
    /// Requires OpenSSL 3.5 or later (or another backend with ML-KEM support).
    pub fn ml_kem(parameter_set: &str) -> Self {
        Self {
            spec: KeySpec::MlKem(parameter_set.to_string()),
        }
    }

    /// Configure composite ML-DSA key generation (draft-ietf-lamps-pq-composite-sigs-19).
    ///
    /// `sub_arc` is the OID sub-component (37–54) identifying the composite variant.
    /// Use [`crate::crypto::composite_mldsa::composite_spec`] to look up the full spec.
    ///
    /// Requires a backend with ML-DSA support (OpenSSL 3.5+ or NSS with ML-DSA).
    #[cfg(any(feature = "openssl", feature = "nss"))]
    pub fn composite_ml_dsa(sub_arc: u32) -> Self {
        Self {
            spec: KeySpec::CompositeMlDsa(sub_arc),
        }
    }

    /// Generate the private key using the configured crypto backend.
    ///
    /// When the `openssl` feature is enabled, delegates to OpenSSL.
    /// Returns [`PrivateKeyError`] if the algorithm is unsupported by the
    /// available backend or if key generation fails.
    ///
    /// The returned [`PrivateKey`] is a heap-allocated trait object — no
    /// backend-specific type appears in the caller's code.
    pub fn generate(&self) -> Result<Box<dyn PrivateKey>, PrivateKeyError> {
        #[cfg(feature = "openssl")]
        {
            // Composite ML-DSA generation goes through BackendPrivateKey directly.
            if let KeySpec::CompositeMlDsa(sub_arc) = &self.spec {
                return BackendPrivateKey::generate_composite_ml_dsa(*sub_arc)
                    .map(|k| Box::new(k) as Box<dyn PrivateKey>);
            }
            crate::openssl_backend::generate_private_key(&self.spec)
                .map(|k| Box::new(k) as Box<dyn PrivateKey>)
                .map_err(PrivateKeyError::new)
        }
        #[cfg(all(not(feature = "openssl"), feature = "nss"))]
        {
            if let KeySpec::CompositeMlDsa(sub_arc) = &self.spec {
                return BackendPrivateKey::generate_composite_ml_dsa(*sub_arc)
                    .map(|k| Box::new(k) as Box<dyn PrivateKey>);
            }
            let _ = &self.spec;
            Err(PrivateKeyError::new(NoCryptoError))
        }
        #[cfg(not(any(feature = "openssl", feature = "nss")))]
        {
            let _ = &self.spec;
            Err(PrivateKeyError::new(NoCryptoError))
        }
    }
}

// ── BackendPublicKey ──────────────────────────────────────────────────────────

/// Opaque public key — wraps SPKI DER, delegates operations to the active
/// crypto backend.
///
/// When created via [`BackendPublicKey::from_der`] or [`BackendPublicKey::from_pem`]
/// the parsed `EVP_PKEY` is cached alongside the DER bytes.  Subsequent calls to
/// [`verify_signature`] reuse the cached key (an O(1) refcount clone) rather than
/// re-parsing the DER on every call — critical for repeated verification of many
/// items signed by the same CA key.
///
/// [`verify_signature`]: BackendPublicKey::verify_signature
#[derive(Clone)]
pub struct BackendPublicKey {
    pub(crate) spki_der: Vec<u8>,
    /// Parsed `EVP_PKEY` cached at construction time when DER was available.
    /// `None` only for keys created via [`from_spki_der`] (bytes-only path).
    /// `Pkey<Public>` is internally ref-counted; `clone()` is O(1).
    ///
    /// [`from_spki_der`]: BackendPublicKey::from_spki_der
    #[cfg(feature = "openssl")]
    pub(crate) pkey: Option<native_ossl::pkey::Pkey<native_ossl::pkey::Public>>,
}

impl std::fmt::Debug for BackendPublicKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BackendPublicKey")
            .field("spki_der_len", &self.spki_der.len())
            .finish_non_exhaustive()
    }
}

impl BackendPublicKey {
    /// Wrap a raw SPKI DER buffer as a [`BackendPublicKey`] without validation.
    ///
    /// The key is **not** parsed at construction; `verify_signature` will parse
    /// on the first call.  Use [`from_der`] when the same key will be used for
    /// many verifications — it caches the parsed `EVP_PKEY` at construction time.
    ///
    /// [`from_der`]: BackendPublicKey::from_der
    pub fn from_spki_der(spki_der: Vec<u8>) -> Self {
        Self {
            spki_der,
            #[cfg(feature = "openssl")]
            pkey: None,
        }
    }

    /// Return the stored SPKI DER bytes.
    pub fn spki_der(&self) -> &[u8] {
        &self.spki_der
    }

    /// Load a public key from PEM-encoded SubjectPublicKeyInfo.
    ///
    /// The parsed `EVP_PKEY` is cached so that repeated calls to
    /// [`verify_signature`] on the returned key avoid re-parsing the DER.
    ///
    /// [`verify_signature`]: BackendPublicKey::verify_signature
    #[cfg(feature = "openssl")]
    pub fn from_pem(pem: &[u8]) -> Result<Self, crate::openssl_backend::OpensslKeyError> {
        let pkey = crate::openssl_backend::parse_public_key_from_pem(pem)?;
        let spki_der = pkey.public_key_to_der()?;
        Ok(Self {
            spki_der,
            pkey: Some(pkey),
        })
    }

    /// Load a public key from DER-encoded SubjectPublicKeyInfo.
    ///
    /// The parsed `EVP_PKEY` is cached so that repeated calls to
    /// [`verify_signature`] on the returned key avoid re-parsing the DER.
    /// Prefer this over [`from_spki_der`] whenever the key will be used for
    /// more than one verification.
    ///
    /// [`verify_signature`]: BackendPublicKey::verify_signature
    /// [`from_spki_der`]: BackendPublicKey::from_spki_der
    #[cfg(feature = "openssl")]
    pub fn from_der(der: &[u8]) -> Result<Self, crate::openssl_backend::OpensslKeyError> {
        let pkey = crate::openssl_backend::parse_public_key(der)?;
        Ok(Self {
            spki_der: der.to_vec(),
            pkey: Some(pkey),
        })
    }

    /// Build an RSA public key from raw big-endian modulus (*n*) and
    /// public-exponent (*e*) bytes.  Inverse of [`Self::rsa_modulus`] /
    /// [`Self::rsa_public_exponent`].
    #[cfg(feature = "openssl")]
    pub fn from_rsa_components(
        n: &[u8],
        e: &[u8],
    ) -> Result<Self, crate::openssl_backend::OpensslKeyError> {
        let spki_der = crate::openssl_backend::pub_rsa_from_components(n, e)?;
        let pkey = crate::openssl_backend::parse_public_key(&spki_der)?;
        Ok(Self {
            spki_der,
            pkey: Some(pkey),
        })
    }

    /// Build an EC public key from affine coordinates *x* and *y* (big-endian
    /// bytes) and a NIST curve name (``"P-256"``, ``"P-384"``, or ``"P-521"``).
    /// Inverse of [`Self::ec_affine_coordinates`] / [`Self::ec_curve_name`].
    #[cfg(feature = "openssl")]
    pub fn from_ec_components(
        x: &[u8],
        y: &[u8],
        curve: &str,
    ) -> Result<Self, crate::openssl_backend::OpensslKeyError> {
        let spki_der = crate::openssl_backend::pub_ec_from_components(x, y, curve)?;
        let pkey = crate::openssl_backend::parse_public_key(&spki_der)?;
        Ok(Self {
            spki_der,
            pkey: Some(pkey),
        })
    }

    /// Serialize this key to PEM.
    #[cfg(feature = "openssl")]
    pub fn to_pem(&self) -> Result<Vec<u8>, crate::openssl_backend::OpensslKeyError> {
        Ok(crate::openssl_backend::parse_public_key(&self.spki_der)?.to_pem()?)
    }

    /// Return a clone of the stored SPKI DER.
    #[cfg(feature = "openssl")]
    pub fn to_der(&self) -> Result<Vec<u8>, crate::openssl_backend::OpensslKeyError> {
        Ok(self.spki_der.clone())
    }

    /// The key algorithm as a lowercase string (``"rsa"``, ``"ec"``,
    /// ``"ed25519"``, ``"ed448"``, or ``"unknown"``).
    #[cfg(feature = "openssl")]
    pub fn key_type(&self) -> &'static str {
        crate::openssl_backend::pub_key_type(&self.spki_der)
    }

    /// The key size in bits, or `None` for EdDSA keys.
    #[cfg(feature = "openssl")]
    pub fn key_bit_size(&self) -> Option<i64> {
        crate::openssl_backend::pub_key_bit_size(&self.spki_der)
    }

    /// RSA modulus `n` as big-endian bytes, or `None` for non-RSA keys.
    #[cfg(feature = "openssl")]
    pub fn rsa_modulus(&self) -> Result<Option<Vec<u8>>, crate::openssl_backend::OpensslKeyError> {
        crate::openssl_backend::pub_rsa_modulus(&self.spki_der)
    }

    /// RSA public exponent `e` as big-endian bytes, or `None` for non-RSA keys.
    #[cfg(feature = "openssl")]
    pub fn rsa_public_exponent(
        &self,
    ) -> Result<Option<Vec<u8>>, crate::openssl_backend::OpensslKeyError> {
        crate::openssl_backend::pub_rsa_public_exponent(&self.spki_der)
    }

    /// NIST curve name for EC keys, or `None` for non-EC keys.
    #[cfg(feature = "openssl")]
    pub fn ec_curve_name(
        &self,
    ) -> Result<Option<&'static str>, crate::openssl_backend::OpensslKeyError> {
        crate::openssl_backend::pub_ec_curve_name(&self.spki_der)
    }

    /// Affine (X, Y) coordinates of an EC public key as big-endian bytes.
    #[cfg(feature = "openssl")]
    pub fn ec_affine_coordinates(
        &self,
    ) -> Result<
        Option<crate::openssl_backend::EcAffineCoords>,
        crate::openssl_backend::OpensslKeyError,
    > {
        crate::openssl_backend::pub_ec_affine_coordinates(&self.spki_der)
    }

    /// RSA-OAEP encryption.
    #[cfg(feature = "openssl")]
    pub fn rsa_oaep_encrypt(
        &self,
        plaintext: &[u8],
        hash_alg: &str,
    ) -> Result<Vec<u8>, crate::openssl_backend::OpensslKeyError> {
        crate::openssl_backend::pub_rsa_oaep_encrypt(&self.spki_der, plaintext, hash_alg)
    }

    /// RSA-OAEP encryption.
    #[cfg(all(feature = "nss", not(feature = "openssl")))]
    pub fn rsa_oaep_encrypt(
        &self,
        plaintext: &[u8],
        hash_alg: &str,
    ) -> Result<Vec<u8>, crate::nss_backend::rsa_transport::NssRsaError> {
        crate::nss_backend::nss_rsa_oaep_encrypt(&self.spki_der, plaintext, hash_alg)
    }

    /// RSA PKCS#1 v1.5 encryption.
    #[cfg(feature = "openssl")]
    pub fn rsa_pkcs1v15_encrypt(
        &self,
        plaintext: &[u8],
    ) -> Result<Vec<u8>, crate::openssl_backend::OpensslKeyError> {
        crate::openssl_backend::pub_rsa_pkcs1v15_encrypt(&self.spki_der, plaintext)
    }

    /// RSA PKCS#1 v1.5 encryption.
    #[cfg(all(feature = "nss", not(feature = "openssl")))]
    pub fn rsa_pkcs1v15_encrypt(
        &self,
        plaintext: &[u8],
    ) -> Result<Vec<u8>, crate::nss_backend::rsa_transport::NssRsaError> {
        crate::nss_backend::nss_rsa_pkcs1v15_encrypt(&self.spki_der, plaintext)
    }

    /// Verify a signature over `data`.
    #[cfg(feature = "openssl")]
    pub fn verify_message(
        &self,
        data: &[u8],
        signature: &[u8],
        algorithm: Option<&str>,
    ) -> Result<(), crate::openssl_backend::OpensslKeyError> {
        crate::openssl_backend::pub_verify_message(&self.spki_der, data, signature, algorithm)
    }

    /// Verify a signature using a DER-encoded `AlgorithmIdentifier`.
    ///
    /// Unlike [`verify_message`], which takes a hash-name string, this method
    /// accepts the complete `AlgorithmIdentifier` SEQUENCE from the certificate
    /// or CRL and dispatches to whichever backend is compiled in:
    ///
    /// - When the `nss` feature is enabled, delegates to
    ///   `NssSignatureVerifier` via `VFY_VerifyDataWithAlgorithmID`.
    /// - Otherwise falls back to the OpenSSL-backed verifier.
    ///
    /// When this key was created via [`from_der`] or [`from_pem`] the parsed
    /// `EVP_PKEY` is reused directly, eliminating the `d2i_PUBKEY` DER parse
    /// that would otherwise occur on every call.  This is the main speedup for
    /// workloads that verify many items (e.g. 1 024 certificates) against the
    /// same CA public key.
    ///
    /// Use this method for any signature verification where the full
    /// `AlgorithmIdentifier` is already available (certificates, CRLs, OCSP
    /// responses), to ensure the active backend is used consistently.
    ///
    /// [`verify_message`]: Self::verify_message
    /// [`from_der`]: BackendPublicKey::from_der
    /// [`from_pem`]: BackendPublicKey::from_pem
    pub fn verify_signature(
        &self,
        tbs_der: &[u8],
        sig_alg_der: &[u8],
        signature: &[u8],
    ) -> Result<(), PrivateKeyError> {
        #[cfg(all(feature = "nss", not(feature = "openssl")))]
        {
            use super::signature::SignatureVerifier as _;
            crate::nss_backend::NssSignatureVerifier
                .verify_certificate_signature(tbs_der, sig_alg_der, signature, &self.spki_der)
                .map_err(PrivateKeyError::new)
        }
        #[cfg(feature = "openssl")]
        {
            if let Some(ref pkey) = self.pkey {
                crate::openssl_backend::verify_with_cached_pkey(
                    pkey,
                    tbs_der,
                    sig_alg_der,
                    signature,
                )
                .map_err(PrivateKeyError::new)
            } else {
                crate::openssl_backend::openssl_signature_verifier()
                    .verify_certificate_signature_erased(
                        tbs_der,
                        sig_alg_der,
                        signature,
                        &self.spki_der,
                    )
            }
        }
        #[cfg(not(any(feature = "openssl", feature = "nss")))]
        {
            let _ = (tbs_der, sig_alg_der, signature);
            Err(PrivateKeyError::new(super::errors::NoCryptoError))
        }
    }

    /// ML-DSA signature verification with an explicit context string (FIPS 204).
    ///
    /// `context` is the domain-separation string; pass `b""` for the default
    /// empty context (equivalent to `BackendPublicKey::verify_message` for
    /// ML-DSA keys).  Returns an error if this is not an ML-DSA key.
    pub fn verify_ml_dsa_with_context(
        &self,
        data: &[u8],
        signature: &[u8],
        context: &[u8],
    ) -> Result<(), PrivateKeyError> {
        #[cfg(feature = "openssl")]
        {
            crate::openssl_backend::pub_verify_ml_dsa_with_context(
                &self.spki_der,
                data,
                signature,
                context,
            )
            .map_err(PrivateKeyError::new)
        }
        #[cfg(not(feature = "openssl"))]
        {
            let _ = (data, signature, context);
            Err(PrivateKeyError::new(NoCryptoError))
        }
    }

    /// ML-KEM encapsulation: generate a shared secret and a ciphertext.
    ///
    /// Returns `(ciphertext, shared_secret)`.  The holder of the corresponding
    /// private key can call [`BackendPrivateKey::ml_kem_decapsulate`] to
    /// recover `shared_secret` from `ciphertext`.
    ///
    /// Raises an error if this key is not an ML-KEM key.
    pub fn ml_kem_encapsulate(&self) -> Result<(Vec<u8>, Vec<u8>), PrivateKeyError> {
        #[cfg(feature = "openssl")]
        {
            crate::openssl_backend::pub_ml_kem_encapsulate(&self.spki_der)
                .map_err(PrivateKeyError::new)
        }
        #[cfg(not(feature = "openssl"))]
        {
            Err(PrivateKeyError::new(NoCryptoError))
        }
    }
}

// ── BackendPrivateKey ─────────────────────────────────────────────────────────

/// All eight CRT fields needed to import an RSA private key from raw components.
///
/// All byte slices are big-endian unsigned integers (the same encoding used
/// by JWK and PKCS#1).  Pass a reference to this struct to
/// [`BackendPrivateKey::from_rsa_private_components`].
#[derive(Debug)]
pub struct RsaPrivateComponents<'a> {
    /// RSA modulus *n*.
    pub n: &'a [u8],
    /// Public exponent *e*.
    pub e: &'a [u8],
    /// Private exponent *d*.
    pub d: &'a [u8],
    /// First prime factor *p*.
    pub p: &'a [u8],
    /// Second prime factor *q*.
    pub q: &'a [u8],
    /// CRT exponent *dp* = *d* mod (*p* − 1).
    pub dp: &'a [u8],
    /// CRT exponent *dq* = *d* mod (*q* − 1).
    pub dq: &'a [u8],
    /// CRT coefficient *qi* = *q*⁻¹ mod *p*.
    pub qi: &'a [u8],
}

/// Opaque private key — wraps PKCS#8 DER, delegates operations to the active
/// crypto backend.
///
/// The PKCS#8 DER is computed **lazily**: key-generation helpers populate only
/// the SPKI DER and the live `Pkey` at construction time.  The PKCS#8 bytes are
/// derived from `Pkey` on the first call that needs them (e.g. `to_der()`).
/// This avoids the expensive EC affine-coordinate conversion and the
/// OpenSSL encoder-framework overhead for short-lived subscriber keys whose
/// private DER is never read.
///
/// `Clone` is cheap: the `Pkey<Private>` inside OpenSSL is reference-counted,
/// so cloning the struct increments a refcount rather than copying key material.
/// Cloning also propagates any already-computed PKCS#8 bytes without
/// re-serializing.
#[derive(Clone)]
pub struct BackendPrivateKey {
    // OnceLock lets key-generation helpers skip the expensive PKCS#8
    // serialization when only the public-key SPKI is needed (common for
    // subscriber certificates generated in the parallel cert_gen path).
    // The bytes are computed on the first call that actually needs them.
    #[allow(dead_code)]
    pub(crate) pkcs8_der: std::sync::OnceLock<Vec<u8>>,
    /// SPKI DER cached at key-generation time to avoid re-parsing PKCS#8 on
    /// every `public_key_spki_der()` call.  `None` when the key was loaded
    /// from stored PKCS#8 bytes (re-parse is required in that case).
    #[allow(dead_code)]
    pub(crate) spki_cache: Option<Vec<u8>>,
    /// Parsed `Pkey` cached at construction time — allows `as_signer()` to
    /// build a signer without re-parsing PKCS#8 DER.  `None` only for keys
    /// created via [`from_pkcs8_der_unchecked`] (no-validation path).
    ///
    /// `Pkey<Private>` is internally reference-counted via `EVP_PKEY_up_ref`;
    /// `clone()` is O(1).
    #[cfg(feature = "openssl")]
    #[allow(dead_code)]
    pub(crate) pkey: Option<native_ossl::pkey::Pkey<native_ossl::pkey::Private>>,
    /// PKCS#11 URI for HSM-backed keys.  When `Some`, the key lives in a
    /// hardware or software token; private material never leaves it.
    /// The NSS `as_signer()` path uses this to dispatch to `nss_hsm_signer()`;
    /// the OpenSSL path holds the live `EVP_PKEY` in `pkey` instead.
    #[allow(dead_code)]
    pub(crate) pkcs11: Option<crate::pkcs11_uri::Pkcs11Uri>,
}

impl std::fmt::Debug for BackendPrivateKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BackendPrivateKey")
            .field("pkcs8_der_len", &self.pkcs8_der.get().map(|v| v.len()))
            .field("has_spki_cache", &self.spki_cache.is_some())
            .field("is_pkcs11", &self.pkcs11.is_some())
            .finish_non_exhaustive()
    }
}

impl BackendPrivateKey {
    /// Return the PKCS#8 DER bytes, computing and caching them from the live
    /// `Pkey` on the first call when not yet available.
    ///
    /// Panics only if neither bytes nor a live key are present, which cannot
    /// happen for any key constructed through the public API.
    #[cfg(feature = "openssl")]
    #[allow(dead_code)]
    pub(crate) fn pkcs8_bytes(&self) -> &[u8] {
        self.pkcs8_der.get_or_init(|| {
            if let Some(ref pkey) = self.pkey {
                // Invariant: `pkey` is a fully-constructed EVP_PKEY; serialisation
                // should never fail for any key type OpenSSL accepts.
                return pkey
                    .to_pkcs8_der()
                    .expect("PKCS#8 serialisation of a valid key always succeeds");
            }
            // Invariant: every BackendPrivateKey construction path either populates
            // `pkcs8_der` (from_pkcs8_der_unchecked, composite generation) or `pkey`
            // (parse_private_key, generate_private_key).  Reaching this branch means
            // a new construction path was added without populating either field.
            panic!("BackendPrivateKey has neither cached PKCS#8 bytes nor a live Pkey");
        })
    }

    #[cfg(all(feature = "nss", not(feature = "openssl")))]
    #[allow(dead_code)]
    pub(crate) fn pkcs8_bytes(&self) -> &[u8] {
        // Invariant: the NSS construction paths always pre-populate `pkcs8_der`
        // before returning.  An empty slice here would produce an opaque PKCS#8
        // parse error downstream; if that ever occurs it is a construction bug.
        self.pkcs8_der.get().map(|v| v.as_slice()).unwrap_or(&[])
    }

    /// Wrap a raw PKCS#8 DER buffer as a [`BackendPrivateKey`] without
    /// validation.  The `Pkey` cache is left empty; it will be populated
    /// lazily on the first `as_signer()` call.
    pub fn from_pkcs8_der_unchecked(pkcs8_der: Vec<u8>) -> Self {
        let cell = std::sync::OnceLock::new();
        cell.set(pkcs8_der).expect("fresh OnceLock");
        Self {
            pkcs8_der: cell,
            spki_cache: None,
            #[cfg(feature = "openssl")]
            pkey: None,
            pkcs11: None,
        }
    }

    /// Generate a new ML-DSA private key (FIPS 204).
    ///
    /// `parameter_set` must be `"ML-DSA-44"`, `"ML-DSA-65"`, or `"ML-DSA-87"`.
    /// Requires OpenSSL 3.5 or newer; returns [`PrivateKeyError`] when the
    /// `openssl` feature is disabled.
    pub fn generate_ml_dsa(parameter_set: &str) -> Result<Self, PrivateKeyError> {
        #[cfg(feature = "openssl")]
        {
            crate::openssl_backend::priv_generate_ml_dsa(parameter_set)
                .map_err(PrivateKeyError::new)
        }
        #[cfg(not(feature = "openssl"))]
        {
            let _ = parameter_set;
            Err(PrivateKeyError::new(NoCryptoError))
        }
    }

    /// Generate a new ML-KEM private key (FIPS 203).
    ///
    /// `parameter_set` must be `"ML-KEM-512"`, `"ML-KEM-768"`, or
    /// `"ML-KEM-1024"`.  Requires OpenSSL 3.5 or newer; returns
    /// [`PrivateKeyError`] when the `openssl` feature is disabled.
    pub fn generate_ml_kem(parameter_set: &str) -> Result<Self, PrivateKeyError> {
        #[cfg(feature = "openssl")]
        {
            crate::openssl_backend::priv_generate_ml_kem(parameter_set)
                .map_err(PrivateKeyError::new)
        }
        #[cfg(not(feature = "openssl"))]
        {
            let _ = parameter_set;
            Err(PrivateKeyError::new(NoCryptoError))
        }
    }

    /// ML-KEM decapsulation: recover the shared secret from `ciphertext`.
    ///
    /// The ciphertext was produced by a peer calling
    /// [`BackendPublicKey::ml_kem_encapsulate`].  Returns the shared secret
    /// bytes, or an error if this key is not ML-KEM or decapsulation fails.
    pub fn ml_kem_decapsulate(&self, ciphertext: &[u8]) -> Result<Vec<u8>, PrivateKeyError> {
        #[cfg(feature = "openssl")]
        {
            crate::openssl_backend::priv_ml_kem_decapsulate(self.pkcs8_bytes(), ciphertext)
                .map_err(PrivateKeyError::new)
        }
        #[cfg(not(feature = "openssl"))]
        {
            let _ = ciphertext;
            Err(PrivateKeyError::new(NoCryptoError))
        }
    }

    /// Load a private key from a PKCS#11 URI, keeping key material in the token.
    ///
    /// Dispatches to the OpenSSL `OSSL_STORE_open_ex` path (when the `openssl`
    /// feature is enabled) or to the NSS `PK11_ListPrivKeysInSlot` path (when
    /// the `nss` feature is enabled without `openssl`).  Private key material
    /// never leaves the token; only the public SPKI DER is extracted.
    ///
    /// The `pkcs11-provider` (OpenSSL) or relevant PKCS#11 module (NSS) must
    /// be configured before calling this function.
    pub fn from_pkcs11_uri(uri: &str) -> Result<Self, PrivateKeyError> {
        #[cfg(feature = "openssl")]
        {
            crate::openssl_backend::priv_load_from_pkcs11_uri(uri).map_err(PrivateKeyError::new)
        }
        #[cfg(all(feature = "nss", not(feature = "openssl")))]
        {
            crate::nss_backend::priv_load_from_pkcs11_uri_nss(uri).map_err(PrivateKeyError::new)
        }
        #[cfg(not(any(feature = "openssl", feature = "nss")))]
        {
            let _ = uri;
            Err(PrivateKeyError::new(NoCryptoError))
        }
    }

    /// Generate a composite ML-DSA private key (draft-ietf-lamps-pq-composite-sigs-19).
    ///
    /// `sub_arc` is the OID sub-component (37–54) identifying the composite variant.
    /// Both component keys (ML-DSA + traditional) are generated and combined into a
    /// single composite PKCS#8 DER buffer.
    #[cfg(any(feature = "openssl", feature = "nss"))]
    pub fn generate_composite_ml_dsa(sub_arc: u32) -> Result<Self, PrivateKeyError> {
        #[cfg(feature = "openssl")]
        {
            crate::openssl_backend::priv_generate_composite_mldsa(sub_arc)
                .map_err(PrivateKeyError::new)
        }
        #[cfg(all(not(feature = "openssl"), feature = "nss"))]
        {
            crate::nss_backend::priv_generate_composite_mldsa(sub_arc).map_err(PrivateKeyError::new)
        }
    }

    /// ML-DSA signing with an explicit context string (FIPS 204).
    ///
    /// `context` is the domain-separation string; pass `b""` for the default
    /// empty context (equivalent to signing via [`PrivateKey::as_signer`] for
    /// ML-DSA keys).  Returns an error if this is not an ML-DSA key.
    pub fn sign_ml_dsa_with_context(
        &self,
        data: &[u8],
        context: &[u8],
    ) -> Result<Vec<u8>, PrivateKeyError> {
        #[cfg(feature = "openssl")]
        {
            crate::openssl_backend::priv_sign_ml_dsa_with_context(self.pkcs8_bytes(), data, context)
                .map_err(PrivateKeyError::new)
        }
        #[cfg(not(feature = "openssl"))]
        {
            let _ = (data, context);
            Err(PrivateKeyError::new(NoCryptoError))
        }
    }
}

impl PrivateKey for BackendPrivateKey {
    fn public_key_spki_der(&self) -> Result<Vec<u8>, PrivateKeyError> {
        // Return the SPKI DER cached at key-generation time when available,
        // avoiding a round-trip through PKCS#8 parse + public_key_to_der.
        // This is especially beneficial for ML-DSA keys whose PKCS#8 is 4KB+.
        if let Some(cached) = &self.spki_cache {
            return Ok(cached.clone());
        }
        #[cfg(feature = "openssl")]
        {
            crate::openssl_backend::priv_public_key_spki_der(self.pkcs8_bytes())
                .map_err(PrivateKeyError::new)
        }
        #[cfg(not(feature = "openssl"))]
        {
            Err(PrivateKeyError::new(NoCryptoError))
        }
    }

    fn as_signer(&self, algorithm: &str) -> Box<dyn ErasedCertificateSigner> {
        #[cfg(all(feature = "nss", not(feature = "openssl")))]
        {
            // Check for composite ML-DSA key (NSS path).
            if let Some(oid) = super::utils::pkcs8_key_oid(self.pkcs8_bytes()) {
                let comps = oid.components();
                if comps.starts_with(crate::oids::COMPOSITE_MLDSA_ARC) && comps.len() == 9 {
                    let sub_arc = comps[8];
                    return if let Some(spec) =
                        crate::crypto::composite_mldsa::composite_spec(sub_arc)
                    {
                        crate::nss_backend::composite_mldsa_signer_from_pkcs8(
                            self.pkcs8_bytes(),
                            spec,
                        )
                    } else {
                        Box::new(FailedKeySigner(format!(
                            "unsupported composite ML-DSA sub-arc {sub_arc}"
                        )))
                    };
                }
            }
            // PKCS#11 HSM path: key lives in the token, use nss_hsm_signer.
            if let Some(pkcs11) = &self.pkcs11 {
                if let Some(spki) = &self.spki_cache {
                    return crate::nss_backend::nss_hsm_signer(pkcs11, algorithm, spki);
                }
                return Box::new(crate::nss_backend::NssUnsupportedSigner);
            }
            // Software key path: import PKCS#8 into NSS internal slot.
            if let Some(sig_alg_der) =
                super::utils::sig_alg_der_from_pkcs8(self.pkcs8_bytes(), algorithm)
            {
                if let Some(nss_signer) =
                    crate::nss_backend::NssSigner::new(self.pkcs8_bytes().to_vec(), sig_alg_der)
                {
                    return Box::new(nss_signer);
                }
            }
            // sig_alg_der_from_pkcs8 returned None (unrecognised key / hash) or
            // NssSigner::new returned None (Ed448 — no SEC_OID_ED448_SIGNATURE in
            // NSS ≤ 3.121).  Return a signer that reports the failure on use.
            return Box::new(crate::nss_backend::NssUnsupportedSigner);
        }
        #[cfg(feature = "openssl")]
        {
            // Check for composite ML-DSA key before attempting OpenSSL Pkey parse,
            // since OpenSSL cannot parse composite OIDs.
            if let Some(oid) = super::utils::pkcs8_key_oid(self.pkcs8_bytes()) {
                let comps = oid.components();
                if comps.starts_with(crate::oids::COMPOSITE_MLDSA_ARC) && comps.len() == 9 {
                    let sub_arc = comps[8];
                    return if let Some(spec) =
                        crate::crypto::composite_mldsa::composite_spec(sub_arc)
                    {
                        crate::openssl_backend::composite_mldsa_signer_from_pkcs8(
                            self.pkcs8_bytes(),
                            spec,
                        )
                    } else {
                        Box::new(FailedKeySigner(format!(
                            "unsupported composite ML-DSA sub-arc {sub_arc}"
                        )))
                    };
                }
            }
            use crate::openssl_backend::OpensslPrivateKey;
            let pkey = if let Some(pkey) = &self.pkey {
                pkey.clone()
            } else {
                match crate::openssl_backend::parse_private_key(self.pkcs8_bytes()) {
                    Ok(pkey) => pkey,
                    Err(e) => {
                        return Box::new(FailedKeySigner(format!("PKCS#8 parse failed: {e}")))
                    }
                }
            };
            OpensslPrivateKey::from_pkey(pkey).as_signer(algorithm)
        }
        #[cfg(not(any(feature = "openssl", feature = "nss")))]
        {
            let _ = algorithm;
            Box::new(NoErasedSigner)
        }
    }
}