yubikit 1.0.0-beta.0

YubiKey management 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
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
// Copyright 2026 Yubico AB
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Cryptographic key types and parsing utilities.
//!
//! This module provides:
//! - [`crate::keys::KeyAlgorithm`] — algorithm identifier for asymmetric keys
//! - [`crate::keys::PrivateKey`] — private key material parsed from PKCS#8 or constructed directly
//! - [`crate::keys::PublicKey`] — public key material with SPKI serialization
//! - OID encoding/decoding utilities
//! - Well-known curve OID constants

use std::fmt;

use x509_cert::der;
use x509_cert::der::asn1::BitString;
use x509_cert::der::{Decode, Encode};
use x509_cert::spki::{AlgorithmIdentifierOwned, ObjectIdentifier, SubjectPublicKeyInfoOwned};
use zeroize::Zeroizing;

use crate::__internal::SecretValue;
use crate::__internal::tlv::tlv_parse;

// ---------------------------------------------------------------------------
// Well-known curve OIDs (dotted-decimal strings)
// ---------------------------------------------------------------------------

/// NIST P-256 (secp256r1 / prime256v1).
pub(crate) const OID_SECP256R1: ObjectIdentifier =
    ObjectIdentifier::new_unwrap("1.2.840.10045.3.1.7");
/// secp256k1 (used in Bitcoin / Ethereum).
pub(crate) const OID_SECP256K1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.132.0.10");
/// NIST P-384 (secp384r1).
pub(crate) const OID_SECP384R1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.132.0.34");
/// NIST P-521 (secp521r1).
pub(crate) const OID_SECP521R1: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.132.0.35");
/// Brainpool P-256r1.
pub(crate) const OID_BRAINPOOL_P256R1: ObjectIdentifier =
    ObjectIdentifier::new_unwrap("1.3.36.3.3.2.8.1.1.7");
/// Brainpool P-384r1.
pub(crate) const OID_BRAINPOOL_P384R1: ObjectIdentifier =
    ObjectIdentifier::new_unwrap("1.3.36.3.3.2.8.1.1.11");
/// Brainpool P-512r1.
pub(crate) const OID_BRAINPOOL_P512R1: ObjectIdentifier =
    ObjectIdentifier::new_unwrap("1.3.36.3.3.2.8.1.1.13");

// ---------------------------------------------------------------------------
// KeyAlgorithm
// ---------------------------------------------------------------------------

/// RSA modulus bit length.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u16)]
#[non_exhaustive]
pub enum RsaKeySize {
    /// 1024-bit RSA key.
    Rsa1024 = 1024,
    /// 2048-bit RSA key.
    Rsa2048 = 2048,
    /// 3072-bit RSA key.
    Rsa3072 = 3072,
    /// 4096-bit RSA key.
    Rsa4096 = 4096,
}

impl RsaKeySize {
    /// Returns the bit length of this RSA key size.
    pub fn bit_len(self) -> usize {
        self as usize
    }

    /// Create from a bit length, if it matches a known size.
    pub fn from_bit_len(bits: usize) -> Option<Self> {
        match bits {
            1024 => Some(Self::Rsa1024),
            2048 => Some(Self::Rsa2048),
            3072 => Some(Self::Rsa3072),
            4096 => Some(Self::Rsa4096),
            _ => None,
        }
    }
}

/// Cryptographic algorithm for an asymmetric key.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum KeyAlgorithm {
    /// RSA with the given key size.
    Rsa(RsaKeySize),
    /// Elliptic curve (NIST/Brainpool/secp256k1).
    Ec(EcCurve),
    /// Ed25519 signing key.
    Ed25519,
    /// X25519 key agreement.
    X25519,
    /// ML-DSA (FIPS 204) signing.
    MlDsa(MlDsaParameterSet),
    /// ML-KEM (FIPS 203) key encapsulation.
    MlKem(MlKemParameterSet),
}

/// Elliptic curve identifiers for use with ECDSA and/or ECDH.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum EcCurve {
    /// NIST P-256 (secp256r1).
    P256,
    /// NIST P-384 (secp384r1).
    P384,
    /// NIST P-521 (secp521r1).
    P521,
    /// secp256k1.
    Secp256k1,
    /// Brainpool P-256r1.
    BrainpoolP256r1,
    /// Brainpool P-384r1.
    BrainpoolP384r1,
    /// Brainpool P-512r1.
    BrainpoolP512r1,
}

impl EcCurve {
    /// The expected scalar length in bytes.
    pub fn scalar_len(&self) -> usize {
        match self {
            Self::P256 | Self::Secp256k1 | Self::BrainpoolP256r1 => 32,
            Self::P384 | Self::BrainpoolP384r1 => 48,
            Self::P521 => 66,
            Self::BrainpoolP512r1 => 64,
        }
    }

    fn oid(&self) -> ObjectIdentifier {
        match self {
            Self::P256 => OID_SECP256R1,
            Self::P384 => OID_SECP384R1,
            Self::P521 => OID_SECP521R1,
            Self::Secp256k1 => OID_SECP256K1,
            Self::BrainpoolP256r1 => OID_BRAINPOOL_P256R1,
            Self::BrainpoolP384r1 => OID_BRAINPOOL_P384R1,
            Self::BrainpoolP512r1 => OID_BRAINPOOL_P512R1,
        }
    }

    pub(crate) fn from_oid(oid: &ObjectIdentifier) -> Option<Self> {
        match *oid {
            OID_SECP256R1 => Some(Self::P256),
            OID_SECP384R1 => Some(Self::P384),
            OID_SECP521R1 => Some(Self::P521),
            OID_SECP256K1 => Some(Self::Secp256k1),
            OID_BRAINPOOL_P256R1 => Some(Self::BrainpoolP256r1),
            OID_BRAINPOOL_P384R1 => Some(Self::BrainpoolP384r1),
            OID_BRAINPOOL_P512R1 => Some(Self::BrainpoolP512r1),
            _ => None,
        }
    }

    /// Parse a dotted-decimal OID string to an `EcCurve`.
    pub fn from_oid_str(s: &str) -> Option<Self> {
        let oid = ObjectIdentifier::new(s).ok()?;
        Self::from_oid(&oid)
    }
}

/// ML-DSA parameter sets (FIPS 204).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum MlDsaParameterSet {
    /// ML-DSA-44 (security category 2).
    MlDsa44,
    /// ML-DSA-65 (security category 3).
    MlDsa65,
    /// ML-DSA-87 (security category 5).
    MlDsa87,
}

/// ML-KEM parameter sets (FIPS 203).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum MlKemParameterSet {
    /// ML-KEM-512 (security category 1).
    MlKem512,
    /// ML-KEM-768 (security category 3).
    MlKem768,
    /// ML-KEM-1024 (security category 5).
    MlKem1024,
}

// ---------------------------------------------------------------------------
// PrivateKey
// ---------------------------------------------------------------------------

/// An asymmetric private key.
///
/// Key material is automatically zeroized when dropped.
/// Construct via [`PrivateKey::from_pkcs8`] or directly from components.
#[non_exhaustive]
pub enum PrivateKey {
    /// RSA private key in CRT form.
    Rsa(RsaPrivateKey),
    /// Elliptic curve private key (NIST/Brainpool/secp256k1).
    Ec(EcPrivateKey),
    /// Ed25519 signing key.
    Ed25519(Ed25519PrivateKey),
    /// X25519 key agreement key.
    X25519(X25519PrivateKey),
    /// ML-DSA private key.
    MlDsa(MlDsaPrivateKey),
    /// ML-KEM private key.
    MlKem(MlKemPrivateKey),
}

impl Drop for PrivateKey {
    fn drop(&mut self) {
        // Each inner struct has its own Drop implementation.
        match self {
            Self::Rsa(_)
            | Self::Ec(_)
            | Self::Ed25519(_)
            | Self::X25519(_)
            | Self::MlDsa(_)
            | Self::MlKem(_) => {}
        }
    }
}

/// RSA private key components in CRT form.
pub struct RsaPrivateKey {
    /// Key size.
    pub(crate) key_size: RsaKeySize,
    /// Public modulus n = p*q.
    pub(crate) n: Vec<u8>,
    /// Public exponent (typically 65537).
    pub(crate) e: Vec<u8>,
    /// First prime factor.
    pub(crate) p: SecretValue<Vec<u8>>,
    /// Second prime factor.
    pub(crate) q: SecretValue<Vec<u8>>,
    /// d mod (p-1).
    pub(crate) dp: SecretValue<Vec<u8>>,
    /// d mod (q-1).
    pub(crate) dq: SecretValue<Vec<u8>>,
    /// q^{-1} mod p.
    pub(crate) qinv: SecretValue<Vec<u8>>,
}

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

impl RsaPrivateKey {
    /// Construct an RSA private key from integer components.
    ///
    /// Components are big-endian unsigned integers. `n`, `dp`, `dq`, and `qinv`
    /// may be empty for OpenPGP import formats that omit them.
    pub fn new(
        key_size: RsaKeySize,
        n: Vec<u8>,
        e: Vec<u8>,
        p: Vec<u8>,
        q: Vec<u8>,
        dp: Vec<u8>,
        dq: Vec<u8>,
        qinv: Vec<u8>,
    ) -> Result<Self, KeyError> {
        let key_len = key_size.bit_len() / 8;
        let prime_len = key_len / 2;

        validate_non_empty("RSA public exponent", &e)?;
        validate_non_empty("RSA prime p", &p)?;
        validate_non_empty("RSA prime q", &q)?;
        validate_max_int_len("RSA prime p", &p, prime_len)?;
        validate_max_int_len("RSA prime q", &q, prime_len)?;
        validate_optional_int_len("RSA private exponent dp", &dp, prime_len)?;
        validate_optional_int_len("RSA private exponent dq", &dq, prime_len)?;
        validate_optional_int_len("RSA CRT coefficient qinv", &qinv, prime_len)?;
        if !n.is_empty() {
            validate_exact_int_len("RSA modulus", &n, key_len)?;
        }

        Ok(Self {
            key_size,
            n,
            e,
            p: SecretValue::new(p),
            q: SecretValue::new(q),
            dp: SecretValue::new(dp),
            dq: SecretValue::new(dq),
            qinv: SecretValue::new(qinv),
        })
    }

    /// Returns the algorithm of this key.
    pub fn algorithm(&self) -> KeyAlgorithm {
        KeyAlgorithm::Rsa(self.key_size)
    }

    /// Parse a PKCS#1 RSAPrivateKey DER encoding into an `RsaPrivateKey`.
    pub fn from_pkcs1(pkcs1_der: &[u8]) -> Result<Self, KeyError> {
        let (_, seq_off, seq_len, _) =
            tlv_parse(pkcs1_der, 0).map_err(|_| KeyError("Invalid RSA DER"))?;
        let seq_data = &pkcs1_der[seq_off..seq_off + seq_len];

        let mut offset = 0;
        let mut fields: Vec<&[u8]> = Vec::new();
        while offset < seq_data.len() {
            let (_, val_off, val_len, end) =
                tlv_parse(seq_data, offset).map_err(|_| KeyError("Invalid RSA field"))?;
            fields.push(&seq_data[val_off..val_off + val_len]);
            offset = end;
        }

        if fields.len() < 9 {
            return Err(KeyError("RSA key missing required fields"));
        }

        let n = strip_leading_zero(fields[1]).to_vec();
        let key_size =
            RsaKeySize::from_bit_len(n.len() * 8).ok_or(KeyError("Unsupported RSA key size"))?;

        Self::new(
            key_size,
            n,
            strip_leading_zero(fields[2]).to_vec(),
            strip_leading_zero(fields[4]).to_vec(),
            strip_leading_zero(fields[5]).to_vec(),
            strip_leading_zero(fields[6]).to_vec(),
            strip_leading_zero(fields[7]).to_vec(),
            strip_leading_zero(fields[8]).to_vec(),
        )
    }
}

/// Elliptic curve private key.
pub struct EcPrivateKey {
    /// The curve.
    pub(crate) curve: EcCurve,
    /// The scalar value (big-endian, zero-padded to curve scalar length).
    pub(crate) scalar: SecretValue<Vec<u8>>,
    /// Optional uncompressed public key point.
    pub(crate) public_key: Option<Vec<u8>>,
}

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

impl EcPrivateKey {
    /// Construct an EC private key.
    ///
    /// `scalar` is a big-endian unsigned integer and may be shorter than the
    /// curve scalar length; import code will left-pad it for applet wire formats.
    pub fn new(
        curve: EcCurve,
        scalar: Vec<u8>,
        public_key: Option<Vec<u8>>,
    ) -> Result<Self, KeyError> {
        validate_non_empty("EC scalar", &scalar)?;
        validate_max_int_len("EC scalar", &scalar, curve.scalar_len())?;
        if strip_leading_zero(&scalar).is_empty() {
            return Err(KeyError("EC scalar must not be zero"));
        }
        if let Some(point) = &public_key {
            validate_ec_public_point(&curve, point)?;
        }
        Ok(Self {
            curve,
            scalar: SecretValue::new(scalar),
            public_key,
        })
    }

    /// Returns the algorithm of this key.
    pub fn algorithm(&self) -> KeyAlgorithm {
        KeyAlgorithm::Ec(self.curve.clone())
    }
}

/// Ed25519 signing private key (32-byte secret).
pub struct Ed25519PrivateKey {
    /// The 32-byte secret.
    pub(crate) secret: SecretValue<Vec<u8>>,
}

impl fmt::Debug for Ed25519PrivateKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Ed25519PrivateKey")
    }
}

impl Ed25519PrivateKey {
    /// Construct an Ed25519 private key from a 32-byte secret.
    pub fn new(secret: Vec<u8>) -> Result<Self, KeyError> {
        validate_exact_len("Ed25519 secret key", &secret, 32)?;
        Ok(Self {
            secret: SecretValue::new(secret),
        })
    }

    /// Returns the algorithm of this key.
    pub fn algorithm(&self) -> KeyAlgorithm {
        KeyAlgorithm::Ed25519
    }
}

/// X25519 key agreement private key (32-byte secret).
pub struct X25519PrivateKey {
    /// The 32-byte secret.
    pub(crate) secret: SecretValue<Vec<u8>>,
}

impl fmt::Debug for X25519PrivateKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "X25519PrivateKey")
    }
}

impl X25519PrivateKey {
    /// Construct an X25519 private key from a 32-byte secret.
    pub fn new(secret: Vec<u8>) -> Result<Self, KeyError> {
        validate_exact_len("X25519 secret key", &secret, 32)?;
        Ok(Self {
            secret: SecretValue::new(secret),
        })
    }

    /// Returns the algorithm of this key.
    pub fn algorithm(&self) -> KeyAlgorithm {
        KeyAlgorithm::X25519
    }
}

/// ML-DSA (FIPS 204) private key.
pub struct MlDsaPrivateKey {
    /// The ML-DSA parameter set.
    pub(crate) parameter_set: MlDsaParameterSet,
    /// The raw private key bytes.
    pub(crate) private_key: SecretValue<Vec<u8>>,
}

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

impl MlDsaPrivateKey {
    /// Construct an ML-DSA private key from raw private key bytes.
    pub fn new(parameter_set: MlDsaParameterSet, private_key: Vec<u8>) -> Result<Self, KeyError> {
        validate_non_empty("ML-DSA private key", &private_key)?;
        Ok(Self {
            parameter_set,
            private_key: SecretValue::new(private_key),
        })
    }

    /// Returns the algorithm of this key.
    pub fn algorithm(&self) -> KeyAlgorithm {
        KeyAlgorithm::MlDsa(self.parameter_set)
    }
}

/// ML-KEM (FIPS 203) private key.
pub struct MlKemPrivateKey {
    /// The ML-KEM parameter set.
    pub(crate) parameter_set: MlKemParameterSet,
    /// The raw private key bytes.
    pub(crate) private_key: SecretValue<Vec<u8>>,
}

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

impl MlKemPrivateKey {
    /// Construct an ML-KEM private key from raw private key bytes.
    pub fn new(parameter_set: MlKemParameterSet, private_key: Vec<u8>) -> Result<Self, KeyError> {
        validate_non_empty("ML-KEM private key", &private_key)?;
        Ok(Self {
            parameter_set,
            private_key: SecretValue::new(private_key),
        })
    }

    /// Returns the algorithm of this key.
    pub fn algorithm(&self) -> KeyAlgorithm {
        KeyAlgorithm::MlKem(self.parameter_set)
    }
}

impl PrivateKey {
    /// Parse a PKCS#8 PrivateKeyInfo DER encoding.
    ///
    /// For ML-DSA and ML-KEM, both seed-only and seed-plus-expanded-key
    /// encodings are imported using the seed.
    pub fn from_pkcs8(pkcs8_der: &[u8]) -> Result<Self, KeyError> {
        let (algorithm, key_data) = parse_pkcs8(pkcs8_der)?;

        match algorithm {
            KeyAlgorithm::Rsa(_) => Ok(Self::Rsa(RsaPrivateKey::from_pkcs1(&key_data)?)),
            KeyAlgorithm::Ec(curve) => {
                Ok(Self::Ec(EcPrivateKey::new(curve, key_data.to_vec(), None)?))
            }
            KeyAlgorithm::Ed25519 => Ok(Self::Ed25519(Ed25519PrivateKey::new(key_data.to_vec())?)),
            KeyAlgorithm::X25519 => Ok(Self::X25519(X25519PrivateKey::new(key_data.to_vec())?)),
            KeyAlgorithm::MlDsa(parameter_set) => Ok(Self::MlDsa(MlDsaPrivateKey::new(
                parameter_set,
                key_data.to_vec(),
            )?)),
            KeyAlgorithm::MlKem(parameter_set) => Ok(Self::MlKem(MlKemPrivateKey::new(
                parameter_set,
                key_data.to_vec(),
            )?)),
        }
    }

    /// Returns the algorithm of this private key.
    pub fn algorithm(&self) -> KeyAlgorithm {
        match self {
            Self::Rsa(k) => k.algorithm(),
            Self::Ec(k) => k.algorithm(),
            Self::Ed25519(k) => k.algorithm(),
            Self::X25519(k) => k.algorithm(),
            Self::MlDsa(k) => k.algorithm(),
            Self::MlKem(k) => k.algorithm(),
        }
    }
}

impl fmt::Debug for PrivateKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Rsa(k) => write!(f, "PrivateKey::Rsa({k:?})"),
            Self::Ec(k) => write!(f, "PrivateKey::Ec({k:?})"),
            Self::Ed25519(k) => write!(f, "PrivateKey::{k:?}"),
            Self::X25519(k) => write!(f, "PrivateKey::{k:?}"),
            Self::MlDsa(k) => write!(f, "PrivateKey::{k:?}"),
            Self::MlKem(k) => write!(f, "PrivateKey::{k:?}"),
        }
    }
}

impl From<RsaPrivateKey> for PrivateKey {
    fn from(k: RsaPrivateKey) -> Self {
        Self::Rsa(k)
    }
}

impl From<EcPrivateKey> for PrivateKey {
    fn from(k: EcPrivateKey) -> Self {
        Self::Ec(k)
    }
}

impl From<Ed25519PrivateKey> for PrivateKey {
    fn from(k: Ed25519PrivateKey) -> Self {
        Self::Ed25519(k)
    }
}

impl From<X25519PrivateKey> for PrivateKey {
    fn from(k: X25519PrivateKey) -> Self {
        Self::X25519(k)
    }
}

impl From<MlDsaPrivateKey> for PrivateKey {
    fn from(k: MlDsaPrivateKey) -> Self {
        Self::MlDsa(k)
    }
}

impl From<MlKemPrivateKey> for PrivateKey {
    fn from(k: MlKemPrivateKey) -> Self {
        Self::MlKem(k)
    }
}

// ---------------------------------------------------------------------------
// PublicKey
// ---------------------------------------------------------------------------

/// An asymmetric public key.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum PublicKey {
    /// RSA public key.
    Rsa(RsaPublicKey),
    /// Elliptic curve public key.
    Ec(EcPublicKey),
    /// Ed25519 public key (32 bytes).
    Ed25519(Ed25519PublicKey),
    /// X25519 public key (32 bytes).
    X25519(X25519PublicKey),
    /// ML-DSA public key.
    MlDsa(MlDsaPublicKey),
    /// ML-KEM public key.
    MlKem(MlKemPublicKey),
}

impl From<RsaPublicKey> for PublicKey {
    fn from(k: RsaPublicKey) -> Self {
        Self::Rsa(k)
    }
}

impl From<EcPublicKey> for PublicKey {
    fn from(k: EcPublicKey) -> Self {
        Self::Ec(k)
    }
}

impl From<Ed25519PublicKey> for PublicKey {
    fn from(k: Ed25519PublicKey) -> Self {
        Self::Ed25519(k)
    }
}

impl From<X25519PublicKey> for PublicKey {
    fn from(k: X25519PublicKey) -> Self {
        Self::X25519(k)
    }
}

impl From<MlDsaPublicKey> for PublicKey {
    fn from(k: MlDsaPublicKey) -> Self {
        Self::MlDsa(k)
    }
}

impl From<MlKemPublicKey> for PublicKey {
    fn from(k: MlKemPublicKey) -> Self {
        Self::MlKem(k)
    }
}

/// RSA public key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RsaPublicKey {
    /// Key size.
    pub key_size: RsaKeySize,
    /// Modulus (big-endian, unsigned).
    pub n: Vec<u8>,
    /// Public exponent (big-endian, unsigned).
    pub e: Vec<u8>,
}

impl RsaPublicKey {
    /// Construct an RSA public key.
    pub fn new(n: Vec<u8>, e: Vec<u8>) -> Result<Self, KeyError> {
        validate_non_empty("RSA modulus", &n)?;
        validate_non_empty("RSA public exponent", &e)?;
        let n = strip_leading_zero(&n).to_vec();
        let key_size =
            RsaKeySize::from_bit_len(n.len() * 8).ok_or(KeyError("Unsupported RSA key size"))?;
        Ok(Self { key_size, n, e })
    }

    /// Returns the algorithm of this key.
    pub fn algorithm(&self) -> KeyAlgorithm {
        KeyAlgorithm::Rsa(self.key_size)
    }

    /// Encode this public key as SubjectPublicKeyInfo (SPKI) DER.
    pub fn to_spki(&self) -> Result<Vec<u8>, KeyError> {
        let mod_int =
            der::asn1::UintRef::new(&self.n).map_err(|_| KeyError("Invalid RSA modulus"))?;
        let exp_int =
            der::asn1::UintRef::new(&self.e).map_err(|_| KeyError("Invalid RSA exponent"))?;
        let mut rsa_body = Vec::new();
        mod_int
            .encode_to_vec(&mut rsa_body)
            .map_err(|_| KeyError("Failed to encode RSA modulus"))?;
        exp_int
            .encode_to_vec(&mut rsa_body)
            .map_err(|_| KeyError("Failed to encode RSA exponent"))?;
        let mut rsa_pub_key = Vec::new();
        rsa_pub_key.push(0x30);
        der::Length::new(rsa_body.len() as u16)
            .encode_to_vec(&mut rsa_pub_key)
            .map_err(|_| KeyError("Failed to encode RSA length"))?;
        rsa_pub_key.extend_from_slice(&rsa_body);

        let spki = SubjectPublicKeyInfoOwned {
            algorithm: AlgorithmIdentifierOwned {
                oid: SPKI_OID_RSA,
                parameters: Some(der::Any::from(der::asn1::Null)),
            },
            subject_public_key: BitString::from_bytes(&rsa_pub_key)
                .map_err(|_| KeyError("Failed to encode RSA BIT STRING"))?,
        };
        spki.to_der()
            .map_err(|_| KeyError("Failed to encode SPKI DER"))
    }
}

/// Elliptic curve public key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EcPublicKey {
    /// The curve.
    pub curve: EcCurve,
    /// Uncompressed point (0x04 || x || y).
    pub point: Vec<u8>,
}

impl EcPublicKey {
    /// Construct an EC public key from an uncompressed SEC 1 point.
    pub fn new(curve: EcCurve, point: Vec<u8>) -> Result<Self, KeyError> {
        validate_ec_public_point(&curve, &point)?;
        Ok(Self { curve, point })
    }

    /// Returns the algorithm of this key.
    pub fn algorithm(&self) -> KeyAlgorithm {
        KeyAlgorithm::Ec(self.curve.clone())
    }

    /// Encode this public key as SubjectPublicKeyInfo (SPKI) DER.
    pub fn to_spki(&self) -> Result<Vec<u8>, KeyError> {
        let spki = SubjectPublicKeyInfoOwned {
            algorithm: AlgorithmIdentifierOwned {
                oid: SPKI_OID_EC,
                parameters: Some(der::Any::from(&self.curve.oid())),
            },
            subject_public_key: BitString::from_bytes(&self.point)
                .map_err(|_| KeyError("Failed to encode EC BIT STRING"))?,
        };
        spki.to_der()
            .map_err(|_| KeyError("Failed to encode SPKI DER"))
    }
}

/// Ed25519 public key (32 bytes).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Ed25519PublicKey {
    /// The 32-byte public key.
    pub key: Vec<u8>,
}

impl Ed25519PublicKey {
    /// Construct an Ed25519 public key from 32 raw bytes.
    pub fn new(key: Vec<u8>) -> Result<Self, KeyError> {
        validate_exact_len("Ed25519 public key", &key, 32)?;
        Ok(Self { key })
    }

    /// Returns the algorithm of this key.
    pub fn algorithm(&self) -> KeyAlgorithm {
        KeyAlgorithm::Ed25519
    }

    /// Encode this public key as SubjectPublicKeyInfo (SPKI) DER.
    pub fn to_spki(&self) -> Result<Vec<u8>, KeyError> {
        let spki = SubjectPublicKeyInfoOwned {
            algorithm: AlgorithmIdentifierOwned {
                oid: SPKI_OID_ED25519,
                parameters: None,
            },
            subject_public_key: BitString::from_bytes(&self.key)
                .map_err(|_| KeyError("Failed to encode Ed25519 BIT STRING"))?,
        };
        spki.to_der()
            .map_err(|_| KeyError("Failed to encode SPKI DER"))
    }
}

/// X25519 public key (32 bytes).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct X25519PublicKey {
    /// The 32-byte public key.
    pub key: Vec<u8>,
}

impl X25519PublicKey {
    /// Construct an X25519 public key from 32 raw bytes.
    pub fn new(key: Vec<u8>) -> Result<Self, KeyError> {
        validate_exact_len("X25519 public key", &key, 32)?;
        Ok(Self { key })
    }

    /// Returns the algorithm of this key.
    pub fn algorithm(&self) -> KeyAlgorithm {
        KeyAlgorithm::X25519
    }

    /// Encode this public key as SubjectPublicKeyInfo (SPKI) DER.
    pub fn to_spki(&self) -> Result<Vec<u8>, KeyError> {
        let spki = SubjectPublicKeyInfoOwned {
            algorithm: AlgorithmIdentifierOwned {
                oid: SPKI_OID_X25519,
                parameters: None,
            },
            subject_public_key: BitString::from_bytes(&self.key)
                .map_err(|_| KeyError("Failed to encode X25519 BIT STRING"))?,
        };
        spki.to_der()
            .map_err(|_| KeyError("Failed to encode SPKI DER"))
    }
}

/// ML-DSA (FIPS 204) public key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MlDsaPublicKey {
    /// The ML-DSA parameter set.
    pub parameter_set: MlDsaParameterSet,
    /// The raw public key bytes.
    pub key: Vec<u8>,
}

impl MlDsaPublicKey {
    /// Construct an ML-DSA public key from raw public key bytes.
    pub fn new(parameter_set: MlDsaParameterSet, key: Vec<u8>) -> Result<Self, KeyError> {
        validate_non_empty("ML-DSA public key", &key)?;
        Ok(Self { parameter_set, key })
    }

    /// Returns the algorithm of this key.
    pub fn algorithm(&self) -> KeyAlgorithm {
        KeyAlgorithm::MlDsa(self.parameter_set)
    }

    /// Encode this public key as SubjectPublicKeyInfo (SPKI) DER.
    pub fn to_spki(&self) -> Result<Vec<u8>, KeyError> {
        let oid = match self.parameter_set {
            MlDsaParameterSet::MlDsa44 => SPKI_OID_ML_DSA_44,
            MlDsaParameterSet::MlDsa65 => SPKI_OID_ML_DSA_65,
            MlDsaParameterSet::MlDsa87 => SPKI_OID_ML_DSA_87,
        };
        let spki = SubjectPublicKeyInfoOwned {
            algorithm: AlgorithmIdentifierOwned {
                oid,
                parameters: None,
            },
            subject_public_key: BitString::from_bytes(&self.key)
                .map_err(|_| KeyError("Failed to encode ML-DSA BIT STRING"))?,
        };
        spki.to_der()
            .map_err(|_| KeyError("Failed to encode SPKI DER"))
    }
}

/// ML-KEM (FIPS 203) public key.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MlKemPublicKey {
    /// The ML-KEM parameter set.
    pub parameter_set: MlKemParameterSet,
    /// The raw public key bytes.
    pub key: Vec<u8>,
}

impl MlKemPublicKey {
    /// Construct an ML-KEM public key from raw public key bytes.
    pub fn new(parameter_set: MlKemParameterSet, key: Vec<u8>) -> Result<Self, KeyError> {
        validate_non_empty("ML-KEM public key", &key)?;
        Ok(Self { parameter_set, key })
    }

    /// Returns the algorithm of this key.
    pub fn algorithm(&self) -> KeyAlgorithm {
        KeyAlgorithm::MlKem(self.parameter_set)
    }

    /// Encode this public key as SubjectPublicKeyInfo (SPKI) DER.
    pub fn to_spki(&self) -> Result<Vec<u8>, KeyError> {
        let oid = match self.parameter_set {
            MlKemParameterSet::MlKem512 => SPKI_OID_ML_KEM_512,
            MlKemParameterSet::MlKem768 => SPKI_OID_ML_KEM_768,
            MlKemParameterSet::MlKem1024 => SPKI_OID_ML_KEM_1024,
        };
        let spki = SubjectPublicKeyInfoOwned {
            algorithm: AlgorithmIdentifierOwned {
                oid,
                parameters: None,
            },
            subject_public_key: BitString::from_bytes(&self.key)
                .map_err(|_| KeyError("Failed to encode ML-KEM BIT STRING"))?,
        };
        spki.to_der()
            .map_err(|_| KeyError("Failed to encode SPKI DER"))
    }
}

fn strip_leading_zero(b: &[u8]) -> &[u8] {
    if !b.is_empty() && b[0] == 0 {
        &b[1..]
    } else {
        b
    }
}

fn validate_non_empty(name: &'static str, value: &[u8]) -> Result<(), KeyError> {
    if value.is_empty() {
        Err(KeyError(name))
    } else {
        Ok(())
    }
}

fn validate_exact_len(name: &'static str, value: &[u8], len: usize) -> Result<(), KeyError> {
    if value.len() == len {
        Ok(())
    } else {
        Err(KeyError(name))
    }
}

fn validate_max_int_len(name: &'static str, value: &[u8], max_len: usize) -> Result<(), KeyError> {
    if strip_leading_zero(value).len() <= max_len {
        Ok(())
    } else {
        Err(KeyError(name))
    }
}

fn validate_optional_int_len(
    name: &'static str,
    value: &[u8],
    max_len: usize,
) -> Result<(), KeyError> {
    if value.is_empty() {
        Ok(())
    } else {
        validate_max_int_len(name, value, max_len)
    }
}

fn validate_exact_int_len(name: &'static str, value: &[u8], len: usize) -> Result<(), KeyError> {
    if strip_leading_zero(value).len() == len {
        Ok(())
    } else {
        Err(KeyError(name))
    }
}

fn validate_ec_public_point(curve: &EcCurve, point: &[u8]) -> Result<(), KeyError> {
    let coordinate_len = curve.scalar_len();
    if point.len() == 1 + coordinate_len * 2 && point.first() == Some(&0x04) {
        Ok(())
    } else {
        Err(KeyError("Invalid EC public point"))
    }
}

// SPKI OID constants
const SPKI_OID_EC: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.10045.2.1");
const SPKI_OID_RSA: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.1.1");
const SPKI_OID_ED25519: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.101.112");
const SPKI_OID_X25519: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.101.110");
const SPKI_OID_ML_DSA_44: ObjectIdentifier =
    ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.3.17");
const SPKI_OID_ML_DSA_65: ObjectIdentifier =
    ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.3.18");
const SPKI_OID_ML_DSA_87: ObjectIdentifier =
    ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.3.19");
const SPKI_OID_ML_KEM_512: ObjectIdentifier =
    ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.4.1");
const SPKI_OID_ML_KEM_768: ObjectIdentifier =
    ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.4.2");
const SPKI_OID_ML_KEM_1024: ObjectIdentifier =
    ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.4.3");

impl PublicKey {
    /// Parse a public key from SubjectPublicKeyInfo (SPKI) DER encoding.
    pub fn from_spki(der: &[u8]) -> Result<Self, KeyError> {
        let spki = SubjectPublicKeyInfoOwned::from_der(der)
            .map_err(|_| KeyError("Invalid SPKI DER encoding"))?;

        let key_bytes = spki
            .subject_public_key
            .as_bytes()
            .ok_or(KeyError("Invalid BIT STRING in SPKI"))?;

        let oid = spki.algorithm.oid;
        if oid == SPKI_OID_RSA {
            // RSA: key_bytes is a DER SEQUENCE { INTEGER modulus, INTEGER exponent }
            let (_, seq_off, seq_len, _) =
                tlv_parse(key_bytes, 0).map_err(|_| KeyError("Invalid RSA public key"))?;
            let inner = &key_bytes[seq_off..seq_off + seq_len];
            let (_, n_off, n_len, n_end) =
                tlv_parse(inner, 0).map_err(|_| KeyError("Invalid RSA modulus"))?;
            let (_, e_off, e_len, _) =
                tlv_parse(inner, n_end).map_err(|_| KeyError("Invalid RSA exponent"))?;
            let n = strip_leading_zero(&inner[n_off..n_off + n_len]);
            let e = strip_leading_zero(&inner[e_off..e_off + e_len]);
            let key_size = RsaKeySize::from_bit_len(n.len() * 8)
                .ok_or(KeyError("Unsupported RSA key size"))?;
            let public_key = RsaPublicKey::new(n.to_vec(), e.to_vec())?;
            if public_key.key_size != key_size {
                return Err(KeyError("RSA public key size mismatch"));
            }
            Ok(Self::Rsa(public_key))
        } else if oid == SPKI_OID_EC {
            let curve_oid = spki
                .algorithm
                .parameters
                .as_ref()
                .and_then(|p| ObjectIdentifier::from_bytes(p.value()).ok())
                .ok_or(KeyError("Missing EC curve parameter"))?;
            let curve =
                EcCurve::from_oid(&curve_oid).ok_or(KeyError("Unsupported EC curve in SPKI"))?;
            Ok(Self::Ec(EcPublicKey::new(curve, key_bytes.to_vec())?))
        } else if oid == SPKI_OID_ED25519 {
            Ok(Self::Ed25519(Ed25519PublicKey::new(key_bytes.to_vec())?))
        } else if oid == SPKI_OID_X25519 {
            Ok(Self::X25519(X25519PublicKey::new(key_bytes.to_vec())?))
        } else if oid == SPKI_OID_ML_DSA_44 {
            Ok(Self::MlDsa(MlDsaPublicKey::new(
                MlDsaParameterSet::MlDsa44,
                key_bytes.to_vec(),
            )?))
        } else if oid == SPKI_OID_ML_DSA_65 {
            Ok(Self::MlDsa(MlDsaPublicKey::new(
                MlDsaParameterSet::MlDsa65,
                key_bytes.to_vec(),
            )?))
        } else if oid == SPKI_OID_ML_DSA_87 {
            Ok(Self::MlDsa(MlDsaPublicKey::new(
                MlDsaParameterSet::MlDsa87,
                key_bytes.to_vec(),
            )?))
        } else if oid == SPKI_OID_ML_KEM_512 {
            Ok(Self::MlKem(MlKemPublicKey::new(
                MlKemParameterSet::MlKem512,
                key_bytes.to_vec(),
            )?))
        } else if oid == SPKI_OID_ML_KEM_768 {
            Ok(Self::MlKem(MlKemPublicKey::new(
                MlKemParameterSet::MlKem768,
                key_bytes.to_vec(),
            )?))
        } else if oid == SPKI_OID_ML_KEM_1024 {
            Ok(Self::MlKem(MlKemPublicKey::new(
                MlKemParameterSet::MlKem1024,
                key_bytes.to_vec(),
            )?))
        } else {
            Err(KeyError("Unsupported algorithm in SPKI"))
        }
    }

    /// Returns the algorithm of this public key.
    pub fn algorithm(&self) -> KeyAlgorithm {
        match self {
            Self::Rsa(k) => k.algorithm(),
            Self::Ec(k) => k.algorithm(),
            Self::Ed25519(k) => k.algorithm(),
            Self::X25519(k) => k.algorithm(),
            Self::MlDsa(k) => k.algorithm(),
            Self::MlKem(k) => k.algorithm(),
        }
    }

    /// Encode this public key as SubjectPublicKeyInfo (SPKI) DER.
    pub fn to_spki(&self) -> Result<Vec<u8>, KeyError> {
        match self {
            Self::Rsa(k) => k.to_spki(),
            Self::Ec(k) => k.to_spki(),
            Self::Ed25519(k) => k.to_spki(),
            Self::X25519(k) => k.to_spki(),
            Self::MlDsa(k) => k.to_spki(),
            Self::MlKem(k) => k.to_spki(),
        }
    }
}

// ---------------------------------------------------------------------------
// Error
// ---------------------------------------------------------------------------

/// Error type for key parsing/encoding operations.
#[derive(Debug, Clone, thiserror::Error)]
#[error("{0}")]
pub struct KeyError(pub &'static str);

// ---------------------------------------------------------------------------
// Internal parsing helpers
// ---------------------------------------------------------------------------

/// Parse a PKCS#8 PrivateKeyInfo DER encoding, returning the algorithm and raw key data.
fn parse_pkcs8(pkcs8_der: &[u8]) -> Result<(KeyAlgorithm, Zeroizing<Vec<u8>>), KeyError> {
    let (_, seq_off, seq_len, _) = tlv_parse(pkcs8_der, 0).map_err(|_| KeyError("Invalid DER"))?;
    let seq_data = &pkcs8_der[seq_off..seq_off + seq_len];

    let (_, _, _, ver_end) = tlv_parse(seq_data, 0).map_err(|_| KeyError("Invalid version"))?;

    let (_, algo_off, algo_len, algo_end) =
        tlv_parse(seq_data, ver_end).map_err(|_| KeyError("Invalid AlgorithmIdentifier"))?;
    let algo_data = &seq_data[algo_off..algo_off + algo_len];

    let (_, oid_off, oid_len, oid_end) =
        tlv_parse(algo_data, 0).map_err(|_| KeyError("Invalid OID"))?;
    let oid = &algo_data[oid_off..oid_off + oid_len];

    let (_, oct_off, oct_len, _) =
        tlv_parse(seq_data, algo_end).map_err(|_| KeyError("Invalid OCTET STRING"))?;
    let private_key_data = &seq_data[oct_off..oct_off + oct_len];

    if oid == SPKI_OID_RSA.as_bytes() {
        // For RSA, determine key size from the modulus in the inner PKCS#1 structure
        let (_, inner_off, inner_len, _) =
            tlv_parse(private_key_data, 0).map_err(|_| KeyError("Invalid RSA inner SEQUENCE"))?;
        let inner = &private_key_data[inner_off..inner_off + inner_len];
        let (_, _, _, mod_start) =
            tlv_parse(inner, 0).map_err(|_| KeyError("Invalid RSA version"))?;
        let (_, mod_off, mod_len, _) =
            tlv_parse(inner, mod_start).map_err(|_| KeyError("Invalid RSA modulus"))?;
        let modulus = &inner[mod_off..mod_off + mod_len];
        let mod_bytes = if !modulus.is_empty() && modulus[0] == 0 {
            modulus.len() - 1
        } else {
            modulus.len()
        };
        let mod_bits = mod_bytes * 8;
        let key_size =
            RsaKeySize::from_bit_len(mod_bits).ok_or(KeyError("Unsupported RSA key size"))?;
        Ok((
            KeyAlgorithm::Rsa(key_size),
            Zeroizing::new(private_key_data.to_vec()),
        ))
    } else if oid == SPKI_OID_EC.as_bytes() {
        let (_, curve_off, curve_len, _) =
            tlv_parse(algo_data, oid_end).map_err(|_| KeyError("Invalid EC curve OID"))?;
        let curve_oid = &algo_data[curve_off..curve_off + curve_len];
        let curve = ObjectIdentifier::from_bytes(curve_oid)
            .ok()
            .and_then(|o| EcCurve::from_oid(&o))
            .ok_or(KeyError("Unsupported EC curve"))?;
        // Extract the raw scalar from ECPrivateKey SEQUENCE
        let (_, inner_off, inner_len, _) =
            tlv_parse(private_key_data, 0).map_err(|_| KeyError("Invalid ECPrivateKey"))?;
        let inner = &private_key_data[inner_off..inner_off + inner_len];
        let (_, _, _, ec_ver_end) =
            tlv_parse(inner, 0).map_err(|_| KeyError("Invalid EC version"))?;
        let (_, key_off, key_len, _) =
            tlv_parse(inner, ec_ver_end).map_err(|_| KeyError("Invalid EC private key"))?;
        Ok((
            KeyAlgorithm::Ec(curve),
            Zeroizing::new(inner[key_off..key_off + key_len].to_vec()),
        ))
    } else {
        let algo_oid =
            ObjectIdentifier::from_bytes(oid).map_err(|_| KeyError("Invalid algorithm OID"))?;
        let algorithm = match algo_oid {
            SPKI_OID_ED25519 => KeyAlgorithm::Ed25519,
            SPKI_OID_X25519 => KeyAlgorithm::X25519,
            SPKI_OID_ML_DSA_44 => KeyAlgorithm::MlDsa(MlDsaParameterSet::MlDsa44),
            SPKI_OID_ML_DSA_65 => KeyAlgorithm::MlDsa(MlDsaParameterSet::MlDsa65),
            SPKI_OID_ML_DSA_87 => KeyAlgorithm::MlDsa(MlDsaParameterSet::MlDsa87),
            SPKI_OID_ML_KEM_512 => KeyAlgorithm::MlKem(MlKemParameterSet::MlKem512),
            SPKI_OID_ML_KEM_768 => KeyAlgorithm::MlKem(MlKemParameterSet::MlKem768),
            SPKI_OID_ML_KEM_1024 => KeyAlgorithm::MlKem(MlKemParameterSet::MlKem1024),
            _ => return Err(KeyError("Unsupported key algorithm")),
        };
        let key = match &algorithm {
            KeyAlgorithm::MlDsa(parameter_set) => {
                let expanded_len = match parameter_set {
                    MlDsaParameterSet::MlDsa44 => 2560,
                    MlDsaParameterSet::MlDsa65 => 4032,
                    MlDsaParameterSet::MlDsa87 => 4896,
                };
                parse_pqc_seed(private_key_data, 32, expanded_len)?
            }
            KeyAlgorithm::MlKem(parameter_set) => {
                let expanded_len = match parameter_set {
                    MlKemParameterSet::MlKem512 => 1632,
                    MlKemParameterSet::MlKem768 => 2400,
                    MlKemParameterSet::MlKem1024 => 3168,
                };
                parse_pqc_seed(private_key_data, 64, expanded_len)?
            }
            _ => {
                // Raw key is wrapped in an OCTET STRING inside the outer OCTET STRING
                let (_, key_off, key_len, _) = tlv_parse(private_key_data, 0)
                    .map_err(|_| KeyError("Invalid key OCTET STRING"))?;
                &private_key_data[key_off..key_off + key_len]
            }
        };
        Ok((algorithm, Zeroizing::new(key.to_vec())))
    }
}

fn parse_pqc_seed(
    private_key_data: &[u8],
    seed_len: usize,
    expanded_len: usize,
) -> Result<&[u8], KeyError> {
    let invalid = || KeyError("Invalid ML-DSA or ML-KEM private key encoding");
    let (tag, value_off, value_len, end) = tlv_parse(private_key_data, 0).map_err(|_| invalid())?;
    if end != private_key_data.len() {
        return Err(invalid());
    }
    match tag {
        // OpenSSL's seed-only encoding uses a context-specific implicit OCTET STRING.
        0x80 | 0x04 if value_len == seed_len => {
            Ok(&private_key_data[value_off..value_off + value_len])
        }
        // The default OpenSSL encoding contains the seed followed by the expanded key.
        0x30 => {
            let fields = &private_key_data[value_off..value_off + value_len];
            let (seed_tag, seed_off, seed_size, seed_end) =
                tlv_parse(fields, 0).map_err(|_| invalid())?;
            let (expanded_tag, _, expanded_size, expanded_end) =
                tlv_parse(fields, seed_end).map_err(|_| invalid())?;
            if seed_tag != 0x04
                || seed_size != seed_len
                || expanded_tag != 0x04
                || expanded_size != expanded_len
                || expanded_end != fields.len()
            {
                return Err(invalid());
            }
            Ok(&fields[seed_off..seed_off + seed_size])
        }
        _ => Err(invalid()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::__internal::tlv::tlv_encode;

    fn pqc_pkcs8(oid: ObjectIdentifier, key: &[u8]) -> Vec<u8> {
        let algorithm = tlv_encode(0x30, &tlv_encode(0x06, oid.as_bytes()));
        let mut fields = tlv_encode(0x02, &[0]);
        fields.extend_from_slice(&algorithm);
        fields.extend_from_slice(&tlv_encode(0x04, key));
        tlv_encode(0x30, &fields)
    }

    #[test]
    fn openssl_pqc_pkcs8_import_uses_seed() {
        for (oid, seed_len, expanded_len) in [
            (SPKI_OID_ML_DSA_44, 32, 2560),
            (SPKI_OID_ML_DSA_65, 32, 4032),
            (SPKI_OID_ML_DSA_87, 32, 4896),
            (SPKI_OID_ML_KEM_512, 64, 1632),
            (SPKI_OID_ML_KEM_768, 64, 2400),
            (SPKI_OID_ML_KEM_1024, 64, 3168),
        ] {
            let seed = vec![0x42; seed_len];
            let mut expanded_fields = tlv_encode(0x04, &seed);
            expanded_fields.extend_from_slice(&tlv_encode(0x04, &vec![0x53; expanded_len]));
            for key in [
                tlv_encode(0x80, &seed),
                tlv_encode(0x30, &expanded_fields),
                tlv_encode(0x04, &seed),
            ] {
                let parsed = PrivateKey::from_pkcs8(&pqc_pkcs8(oid, &key)).unwrap();
                let imported_seed = match &parsed {
                    PrivateKey::MlDsa(k) => k.private_key.expose_secret(),
                    PrivateKey::MlKem(k) => k.private_key.expose_secret(),
                    _ => panic!("Expected PQC key"),
                };
                assert_eq!(imported_seed, &seed);
            }
        }
    }

    #[test]
    fn malformed_pqc_pkcs8_is_rejected() {
        let seed = vec![0x42; 32];
        let valid_expanded = tlv_encode(0x04, &vec![0x53; 2560]);
        for inner in [
            tlv_encode(0x80, &seed[..31]),
            tlv_encode(0x81, &seed),
            tlv_encode(0x04, &vec![0x53; 2560]),
            tlv_encode(0x30, &tlv_encode(0x04, &seed)),
            tlv_encode(
                0x30,
                &[tlv_encode(0x04, &seed), tlv_encode(0x04, &[0x53])].concat(),
            ),
            tlv_encode(
                0x30,
                &[tlv_encode(0x04, &seed), valid_expanded.clone(), vec![0]].concat(),
            ),
            [tlv_encode(0x80, &seed), vec![0]].concat(),
        ] {
            assert!(PrivateKey::from_pkcs8(&pqc_pkcs8(SPKI_OID_ML_DSA_44, &inner)).is_err());
        }
        assert!(
            PrivateKey::from_pkcs8(&pqc_pkcs8(SPKI_OID_ML_KEM_512, &tlv_encode(0x80, &seed)))
                .is_err()
        );
    }

    fn assert_spki_roundtrip(public_key: PublicKey) {
        let spki = public_key.to_spki().expect("encode SPKI");
        let decoded = PublicKey::from_spki(&spki).expect("decode SPKI");
        assert_eq!(decoded, public_key);

        let reencoded = decoded.to_spki().expect("re-encode SPKI");
        assert_eq!(reencoded, spki);
    }

    #[test]
    fn rsa_public_keys_roundtrip_spki() {
        for size in [
            RsaKeySize::Rsa1024,
            RsaKeySize::Rsa2048,
            RsaKeySize::Rsa3072,
            RsaKeySize::Rsa4096,
        ] {
            let n = vec![0x01; size.bit_len() / 8];
            let e = vec![0x01, 0x00, 0x01];
            assert_spki_roundtrip(RsaPublicKey::new(n, e).unwrap().into());
        }
    }

    #[test]
    fn ec_public_keys_roundtrip_spki() {
        for curve in [
            EcCurve::P256,
            EcCurve::P384,
            EcCurve::P521,
            EcCurve::Secp256k1,
            EcCurve::BrainpoolP256r1,
            EcCurve::BrainpoolP384r1,
            EcCurve::BrainpoolP512r1,
        ] {
            let mut point = vec![0x04];
            point.extend(vec![0x01; curve.scalar_len() * 2]);
            assert_spki_roundtrip(EcPublicKey::new(curve, point).unwrap().into());
        }
    }

    #[test]
    fn ed25519_public_key_roundtrips_spki() {
        assert_spki_roundtrip(Ed25519PublicKey::new(vec![0x01; 32]).unwrap().into());
    }

    #[test]
    fn x25519_public_key_roundtrips_spki() {
        assert_spki_roundtrip(X25519PublicKey::new(vec![0x02; 32]).unwrap().into());
    }

    #[test]
    fn ml_dsa_public_keys_roundtrip_spki() {
        for parameter_set in [
            MlDsaParameterSet::MlDsa44,
            MlDsaParameterSet::MlDsa65,
            MlDsaParameterSet::MlDsa87,
        ] {
            assert_spki_roundtrip(
                MlDsaPublicKey::new(parameter_set, vec![0x03; 32])
                    .unwrap()
                    .into(),
            );
        }
    }

    #[test]
    fn ml_kem_public_keys_roundtrip_spki() {
        for parameter_set in [
            MlKemParameterSet::MlKem512,
            MlKemParameterSet::MlKem768,
            MlKemParameterSet::MlKem1024,
        ] {
            assert_spki_roundtrip(
                MlKemPublicKey::new(parameter_set, vec![0x04; 32])
                    .unwrap()
                    .into(),
            );
        }
    }
}