Skip to main content

quantaegis_sdk/
rfc9935.rs

1//! **RFC 9935** standard ASN.1 DER and PEM codecs for ML-KEM-512, ML-KEM-768, and ML-KEM-1024
2//! `SubjectPublicKeyInfo` (SPKI) and `PKCS#8` (`PrivateKeyInfo`).
3//!
4//! # Official NIST CSOR OIDs (RFC 9935)
5//! - `ML-KEM-512`:  `2.16.840.1.101.3.4.4.1` (`06 09 60 86 48 01 65 03 04 04 01`)
6//! - `ML-KEM-768`:  `2.16.840.1.101.3.4.4.2` (`06 09 60 86 48 01 65 03 04 04 02`)
7//! - `ML-KEM-1024`: `2.16.840.1.101.3.4.4.3` (`06 09 60 86 48 01 65 03 04 04 03`)
8//!
9//! Per RFC 9935:
10//! - `AlgorithmIdentifier.parameters` MUST be absent (no `NULL`).
11//! - `PKCS#8` private keys support all three ASN.1 `CHOICE` representations:
12//!   - `seed` (`[0] IMPLICIT OCTET STRING`, tag `0x80`, 64 bytes `d || z`, RFC 9935 recommended)
13//!   - `expandedKey` (`OCTET STRING`, tag `0x04`, 1632 / 2400 / 3168 bytes)
14//!   - `both` (`SEQUENCE { OCTET STRING (64), OCTET STRING (expanded) }`, tag `0x30`)
15//! - `PKCS#8` decoding strictly enforces RFC 5958 `OneAsymmetricKey`: `version` 0 MUST omit
16//!   `[1] publicKey`, and `version` 1 MUST include `[1] publicKey`, which must equal the
17//!   encapsulation key belonging to the private key. Well-formed `[0] attributes` are accepted
18//!   and ignored. Encoders emit `version` 0 without a public key.
19//! - Secret intermediates are held in zeroize-on-drop buffers, and private-key PEM uses
20//!   constant-time base64.
21
22use quantaegis_core::ct::ct_eq_slice;
23use quantaegis_core::{Error, Result, Zeroize};
24use quantaegis_ml_kem::{ml_kem_512, ml_kem_768, ml_kem_1024};
25
26use crate::agility::{AgilePublicKey, AgileSecretKey};
27use crate::algorithm::KemAlgorithm;
28use crate::codec::pkcs8::{self, der_header, der_tlv_len, push_der_header};
29use crate::codec::{SecretVec, base64};
30use crate::policy::SecurityPolicy;
31
32/// DER-encoded OID `2.16.840.1.101.3.4.4.1` (ML-KEM-512) without outer tag/length.
33const OID_ML_KEM_512: &[u8] = &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x04, 0x01];
34/// DER-encoded OID `2.16.840.1.101.3.4.4.2` (ML-KEM-768) without outer tag/length.
35const OID_ML_KEM_768: &[u8] = &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x04, 0x02];
36/// DER-encoded OID `2.16.840.1.101.3.4.4.3` (ML-KEM-1024) without outer tag/length.
37const OID_ML_KEM_1024: &[u8] = &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x04, 0x03];
38
39pub(crate) const TAG_INTEGER: u8 = 0x02;
40pub(crate) const TAG_BIT_STRING: u8 = 0x03;
41pub(crate) const TAG_OCTET_STRING: u8 = 0x04;
42pub(crate) const TAG_OID: u8 = 0x06;
43pub(crate) const TAG_SEQUENCE: u8 = 0x30;
44pub(crate) const TAG_CONTEXT_0_PRIMITIVE: u8 = 0x80; // [0] IMPLICIT OCTET STRING (RFC 9935 / 9881 seed)
45
46fn oid_bytes_for(alg: KemAlgorithm) -> Result<&'static [u8]> {
47    match alg {
48        KemAlgorithm::MlKem512 => Ok(OID_ML_KEM_512),
49        KemAlgorithm::MlKem768 => Ok(OID_ML_KEM_768),
50        KemAlgorithm::MlKem1024 => Ok(OID_ML_KEM_1024),
51        KemAlgorithm::XWing => Err(Error::InvalidEncapsulationKey),
52    }
53}
54
55fn alg_from_oid_bytes(oid: &[u8]) -> Result<KemAlgorithm> {
56    if oid == OID_ML_KEM_512 {
57        Ok(KemAlgorithm::MlKem512)
58    } else if oid == OID_ML_KEM_768 {
59        Ok(KemAlgorithm::MlKem768)
60    } else if oid == OID_ML_KEM_1024 {
61        Ok(KemAlgorithm::MlKem1024)
62    } else {
63        Err(Error::InvalidEncapsulationKey)
64    }
65}
66
67/// Encodes a DER TLV for **public** data (secret encoders write into a
68/// [`SecretVec`] via [`crate::codec::pkcs8`] instead).
69pub(crate) fn encode_der_tlv(tag: u8, value: &[u8]) -> Vec<u8> {
70    let (header, header_len) = der_header(tag, value.len());
71    let mut out = Vec::with_capacity(header_len + value.len());
72    out.extend_from_slice(&header[..header_len]);
73    out.extend_from_slice(value);
74    out
75}
76
77/// Strictly parses a canonical DER TLV element, returning `(tag, value, rest)`.
78pub(crate) fn parse_der_tlv(input: &[u8]) -> Result<(u8, &[u8], &[u8])> {
79    if input.len() < 2 {
80        return Err(Error::InvalidEncapsulationKey);
81    }
82    let tag = input[0];
83    let first_len = input[1];
84    let (len, header_len) = if first_len < 0x80 {
85        (usize::from(first_len), 2usize)
86    } else if first_len == 0x81 {
87        if input.len() < 3 {
88            return Err(Error::InvalidEncapsulationKey);
89        }
90        let l = usize::from(input[2]);
91        if l < 0x80 {
92            return Err(Error::InvalidEncapsulationKey); // non-canonical DER
93        }
94        (l, 3usize)
95    } else if first_len == 0x82 {
96        if input.len() < 4 {
97            return Err(Error::InvalidEncapsulationKey);
98        }
99        let l = usize::from(u16::from_be_bytes([input[2], input[3]]));
100        if l <= 0xFF {
101            return Err(Error::InvalidEncapsulationKey); // non-canonical DER
102        }
103        (l, 4usize)
104    } else {
105        return Err(Error::InvalidEncapsulationKey);
106    };
107
108    let end = header_len
109        .checked_add(len)
110        .ok_or(Error::InvalidEncapsulationKey)?;
111    if input.len() < end {
112        return Err(Error::InvalidEncapsulationKey);
113    }
114    Ok((tag, &input[header_len..end], &input[end..]))
115}
116
117/// Encodes an ML-KEM public key into RFC 9935 **SPKI DER** (`SubjectPublicKeyInfo`).
118pub fn encode_spki_der(pk: &AgilePublicKey) -> Result<Vec<u8>> {
119    let oid = oid_bytes_for(pk.algorithm())?;
120    let alg_id = encode_der_tlv(TAG_SEQUENCE, &encode_der_tlv(TAG_OID, oid));
121
122    let raw = pk.raw_bytes();
123    let mut bit_string_val = Vec::with_capacity(1 + raw.len());
124    bit_string_val.push(0x00); // 0 unused bits
125    bit_string_val.extend_from_slice(raw);
126    let bit_string = encode_der_tlv(TAG_BIT_STRING, &bit_string_val);
127
128    let mut spki_body = Vec::with_capacity(alg_id.len() + bit_string.len());
129    spki_body.extend_from_slice(&alg_id);
130    spki_body.extend_from_slice(&bit_string);
131    Ok(encode_der_tlv(TAG_SEQUENCE, &spki_body))
132}
133
134/// Decodes an RFC 9935 **SPKI DER** public key, enforcing `policy` and FIPS 203 Section 7.2 checks.
135pub fn decode_spki_der(policy: SecurityPolicy, der: &[u8]) -> Result<AgilePublicKey> {
136    let (seq_tag, spki_body, trailing) = parse_der_tlv(der)?;
137    if seq_tag != TAG_SEQUENCE || !trailing.is_empty() {
138        return Err(Error::InvalidEncapsulationKey);
139    }
140
141    let (alg_tag, alg_body, rest) = parse_der_tlv(spki_body)?;
142    if alg_tag != TAG_SEQUENCE {
143        return Err(Error::InvalidEncapsulationKey);
144    }
145    // RFC 9935: parameters MUST be absent (alg_body contains OID only)
146    let (oid_tag, oid_val, alg_extra) = parse_der_tlv(alg_body)?;
147    if oid_tag != TAG_OID || !alg_extra.is_empty() {
148        return Err(Error::InvalidEncapsulationKey);
149    }
150    let alg = alg_from_oid_bytes(oid_val)?;
151
152    let (bs_tag, bs_val, rest2) = parse_der_tlv(rest)?;
153    if bs_tag != TAG_BIT_STRING || !rest2.is_empty() || bs_val.is_empty() || bs_val[0] != 0x00 {
154        return Err(Error::InvalidEncapsulationKey);
155    }
156
157    AgilePublicKey::from_raw(policy, alg, &bs_val[1..])
158}
159
160/// Encodes an ML-KEM 64-byte `(d || z)` seed into RFC 9935 **PKCS#8 DER** (`seed` CHOICE tag `0x80`).
161///
162/// The seed is written directly into the returned buffer (no intermediate copies).
163pub fn encode_pkcs8_seed_der(alg: KemAlgorithm, seed: &[u8; 64]) -> Result<Vec<u8>> {
164    let oid = oid_bytes_for(alg).map_err(|_| Error::InvalidDecapsulationKey)?;
165    pkcs8::encode_v1(
166        oid,
167        der_tlv_len(seed.len()),
168        Error::InvalidDecapsulationKey,
169        |out| {
170            push_der_header(out, TAG_CONTEXT_0_PRIMITIVE, seed.len());
171            out.extend_from_slice(seed);
172        },
173    )
174}
175
176/// Encodes an expanded ML-KEM decapsulation key into RFC 9935 **PKCS#8 DER** (`expandedKey` CHOICE tag `0x04`).
177///
178/// The key is written directly into the returned buffer (no intermediate copies).
179pub fn encode_pkcs8_expanded_der(sk: &AgileSecretKey) -> Result<Vec<u8>> {
180    let oid = oid_bytes_for(sk.algorithm()).map_err(|_| Error::InvalidDecapsulationKey)?;
181    let dk = sk.expose_raw_bytes();
182    pkcs8::encode_v1(
183        oid,
184        der_tlv_len(dk.len()),
185        Error::InvalidDecapsulationKey,
186        |out| {
187            push_der_header(out, TAG_OCTET_STRING, dk.len());
188            out.extend_from_slice(dk);
189        },
190    )
191}
192
193fn expand_seed_to_secret(
194    policy: SecurityPolicy,
195    alg: KemAlgorithm,
196    seed: &[u8],
197) -> Result<AgileSecretKey> {
198    if seed.len() != 64 {
199        return Err(Error::InvalidDecapsulationKey);
200    }
201    let mut d = [0u8; 32];
202    let mut z = [0u8; 32];
203    d.copy_from_slice(&seed[..32]);
204    z.copy_from_slice(&seed[32..64]);
205
206    let res = match alg {
207        KemAlgorithm::MlKem512 => {
208            let (_ek, dk) = ml_kem_512::hazmat::keygen_internal(&d, &z);
209            AgileSecretKey::from_raw(policy, alg, dk.expose_bytes())
210        }
211        KemAlgorithm::MlKem768 => {
212            let (_ek, dk) = ml_kem_768::hazmat::keygen_internal(&d, &z);
213            AgileSecretKey::from_raw(policy, alg, dk.expose_bytes())
214        }
215        KemAlgorithm::MlKem1024 => {
216            let (_ek, dk) = ml_kem_1024::hazmat::keygen_internal(&d, &z);
217            AgileSecretKey::from_raw(policy, alg, dk.expose_bytes())
218        }
219        KemAlgorithm::XWing => Err(Error::InvalidDecapsulationKey),
220    };
221
222    d.zeroize();
223    z.zeroize();
224    res
225}
226
227/// Returns the encapsulation key `ek` embedded in an ML-KEM decapsulation key.
228///
229/// FIPS 203 Algorithm 16 lays out `dk = dk_PKE || ek || H(ek) || z` with 32-byte `H(ek)` and `z`.
230/// `DecapsulationKey::from_bytes` has already verified `H(ek)` (FIPS 203 Section 7.3), and for a
231/// key expanded from a seed this is exactly the derived `ek`.
232fn embedded_encapsulation_key(sk: &AgileSecretKey) -> Result<&[u8]> {
233    let ek_len = match sk.algorithm() {
234        KemAlgorithm::MlKem512 => ml_kem_512::EK_LEN,
235        KemAlgorithm::MlKem768 => ml_kem_768::EK_LEN,
236        KemAlgorithm::MlKem1024 => ml_kem_1024::EK_LEN,
237        KemAlgorithm::XWing => return Err(Error::InvalidDecapsulationKey),
238    };
239    let dk = sk.expose_raw_bytes();
240    let end = dk
241        .len()
242        .checked_sub(64)
243        .ok_or(Error::InvalidDecapsulationKey)?;
244    let start = end
245        .checked_sub(ek_len)
246        .ok_or(Error::InvalidDecapsulationKey)?;
247    dk.get(start..end).ok_or(Error::InvalidDecapsulationKey)
248}
249
250/// Decodes an RFC 9935 **PKCS#8 DER** ML-KEM private key (supports all three `CHOICE` forms:
251/// `seed [0]`, `expandedKey`, and `both`), enforcing `policy` and consistency checks.
252///
253/// Strictly enforces RFC 5958 `OneAsymmetricKey`: `version` 0 MUST omit `[1] publicKey`, and
254/// `version` 1 MUST include `[1] publicKey`, which must equal the encapsulation key belonging
255/// to the decoded private key; otherwise the key is rejected. Well-formed `[0] attributes` are
256/// accepted and ignored. See `crate::codec::pkcs8::parse` for the exact rules.
257pub fn decode_pkcs8_der(policy: SecurityPolicy, der: &[u8]) -> Result<AgileSecretKey> {
258    let key = pkcs8::parse(der, Error::InvalidDecapsulationKey)?;
259    let alg = alg_from_oid_bytes(key.algorithm_oid).map_err(|_| Error::InvalidDecapsulationKey)?;
260    policy.validate_kem(alg)?;
261
262    let (choice_tag, choice_val, choice_extra) =
263        parse_der_tlv(key.private_key).map_err(|_| Error::InvalidDecapsulationKey)?;
264    if !choice_extra.is_empty() {
265        return Err(Error::InvalidDecapsulationKey);
266    }
267
268    let sk = match choice_tag {
269        TAG_CONTEXT_0_PRIMITIVE => expand_seed_to_secret(policy, alg, choice_val),
270        TAG_OCTET_STRING => AgileSecretKey::from_raw(policy, alg, choice_val),
271        TAG_SEQUENCE => {
272            let (t1, seed_val, r1) =
273                parse_der_tlv(choice_val).map_err(|_| Error::InvalidDecapsulationKey)?;
274            let (t2, exp_val, r2) =
275                parse_der_tlv(r1).map_err(|_| Error::InvalidDecapsulationKey)?;
276            if t1 != TAG_OCTET_STRING || t2 != TAG_OCTET_STRING || !r2.is_empty() {
277                return Err(Error::InvalidDecapsulationKey);
278            }
279            let derived = expand_seed_to_secret(policy, alg, seed_val)?;
280            if !ct_eq_slice(derived.expose_raw_bytes(), exp_val).into_bool() {
281                return Err(Error::InvalidDecapsulationKey);
282            }
283            Ok(derived)
284        }
285        _ => Err(Error::InvalidDecapsulationKey),
286    }?;
287
288    // RFC 5958 v2: an included public key must belong to the private key.
289    if let Some(public_key) = key.public_key {
290        let derived = embedded_encapsulation_key(&sk)?;
291        if !ct_eq_slice(derived, public_key).into_bool() {
292            return Err(Error::InvalidDecapsulationKey);
293        }
294    }
295    Ok(sk)
296}
297
298/// Encodes an ML-KEM public key into RFC 9935 **PEM** (`-----BEGIN PUBLIC KEY-----`).
299pub fn encode_spki_pem(pk: &AgilePublicKey) -> Result<String> {
300    let der = encode_spki_der(pk)?;
301    encode_pem("PUBLIC KEY", &der)
302}
303
304/// Decodes an RFC 9935 **PEM** public key (`-----BEGIN PUBLIC KEY-----`).
305pub fn decode_spki_pem(policy: SecurityPolicy, pem: &str) -> Result<AgilePublicKey> {
306    let der = decode_pem("PUBLIC KEY", pem).map_err(|_| Error::InvalidEncapsulationKey)?;
307    decode_spki_der(policy, &der)
308}
309
310/// Encodes an ML-KEM 64-byte seed into RFC 9935 **PEM** (`-----BEGIN PRIVATE KEY-----`).
311pub fn encode_pkcs8_seed_pem(alg: KemAlgorithm, seed: &[u8; 64]) -> Result<String> {
312    // The intermediate DER is wiped on drop, on both the success and the error path.
313    let der = SecretVec::from_vec(encode_pkcs8_seed_der(alg, seed)?);
314    encode_pem("PRIVATE KEY", &der)
315}
316
317/// Decodes an RFC 9935 **PEM** private key (`-----BEGIN PRIVATE KEY-----`).
318pub fn decode_pkcs8_pem(policy: SecurityPolicy, pem: &str) -> Result<AgileSecretKey> {
319    // The decoded DER is a `SecretVec`, wiped on drop on every path.
320    let der = decode_pem("PRIVATE KEY", pem).map_err(|_| Error::InvalidDecapsulationKey)?;
321    decode_pkcs8_der(policy, &der)
322}
323
324/// Line length of the base64 body in PEM output (RFC 7468 Section 2).
325const PEM_LINE_LEN: usize = 64;
326
327/// Encodes `der` as an RFC 7468 PEM block labelled `label`, with 64-character base64 lines and
328/// `\n` line endings.
329///
330/// The text is written directly into one pre-sized zeroize-on-drop buffer that becomes the
331/// returned `String`, so no intermediate base64 copy is left behind. The base64 step is the
332/// constant-time encoder in [`crate::codec::base64`]. Line breaks depend only on the output
333/// position.
334pub(crate) fn encode_pem(label: &str, der: &[u8]) -> Result<String> {
335    const BEGIN: &[u8] = b"-----BEGIN ";
336    const END: &[u8] = b"-----END ";
337    const DASHES_NL: &[u8] = b"-----\n";
338
339    let b64_len = base64::encoded_len(der.len());
340    let total_len = BEGIN.len()
341        + END.len()
342        + 2 * (label.len() + DASHES_NL.len())
343        + b64_len
344        + b64_len.div_ceil(PEM_LINE_LEN);
345
346    let mut pem = SecretVec::with_capacity(total_len);
347    pem.extend_from_slice(BEGIN);
348    pem.extend_from_slice(label.as_bytes());
349    pem.extend_from_slice(DASHES_NL);
350    let mut column = 0usize;
351    base64::encode(der, |c| {
352        pem.push(c);
353        column += 1;
354        if column == PEM_LINE_LEN {
355            pem.push(b'\n');
356            column = 0;
357        }
358    });
359    if column != 0 {
360        pem.push(b'\n');
361    }
362    pem.extend_from_slice(END);
363    pem.extend_from_slice(label.as_bytes());
364    pem.extend_from_slice(DASHES_NL);
365
366    // Always valid UTF-8 (`label` plus ASCII); on the impossible error path the bytes are wiped.
367    String::from_utf8(pem.into_vec()).map_err(|e| {
368        drop(SecretVec::from_vec(e.into_bytes()));
369        Error::InvalidEncapsulationKey
370    })
371}
372
373/// Returns `1` for the ASCII whitespace accepted inside a PEM body (`\t`, `\n`, `\x0C`, `\r`,
374/// space), else `0`, using constant-time comparisons only.
375#[inline]
376fn is_pem_whitespace(c: u8) -> u8 {
377    base64::ct_eq_byte(c, b' ')
378        | base64::ct_eq_byte(c, b'\t')
379        | base64::ct_eq_byte(c, b'\n')
380        | base64::ct_eq_byte(c, 0x0C)
381        | base64::ct_eq_byte(c, b'\r')
382}
383
384/// Returns the offset of the first occurrence of `boundary` (which starts with `-`) in `text`,
385/// like `str::find`, but comparing it only at positions that hold a `-`.
386///
387/// The work done therefore depends only on where `-` occurs in `text`. Base64 text never
388/// contains `-`, so a secret body is skipped without any step depending on its value.
389fn find_boundary(text: &[u8], boundary: &[u8]) -> Option<usize> {
390    debug_assert_eq!(boundary.first(), Some(&b'-'));
391    text.iter()
392        .enumerate()
393        .find(|&(i, &c)| c == b'-' && text[i..].starts_with(boundary))
394        .map(|(i, _)| i)
395}
396
397/// Decodes the first PEM block labelled `expected_label` in `pem` into a zeroize-on-drop buffer.
398///
399/// # Side channels
400///
401/// The base64 body may encode a private key. Each step that reads body characters either uses
402/// constant-time arithmetic, or its outcome is the same for every base64 alphabet character.
403/// Such a step can only reveal where non-alphabet characters (line breaks, the closing boundary)
404/// are, i.e. the PEM layout, which is not secret:
405///
406/// - The opening boundary is compared only at positions that hold a `-`. `-` is not a base64
407///   character, so the scan skips every body character of an earlier block (for example a
408///   private key placed in front of the wanted block) with the same comparison outcome, and the
409///   boundary text is compared only against boundary lines. A substring search such as
410///   `str::find` is avoided for the same reason as for the closing boundary below.
411/// - The body ends at the first `-` after the opening boundary. `-` is not a base64 character,
412///   so the byte-by-byte comparison is false for every secret character and stops only at
413///   the closing boundary, which is then compared in full. A substring search for
414///   `-----END ...` over the body is deliberately avoided: its skip distances depend on whether
415///   body characters such as `E`, `N` or `D` occur in the needle.
416/// - Whitespace may appear anywhere in the body, as before. It is classified with
417///   constant-time comparisons and removed by storing every byte at a cursor that only
418///   advances on non-whitespace. The store addresses therefore depend only on where the
419///   whitespace is.
420/// - The remaining characters go to the constant-time strict decoder in
421///   [`crate::codec::base64`]. It accumulates errors instead of returning early and rejects
422///   invalid characters, malformed padding and non-canonical trailing bits.
423pub(crate) fn decode_pem(expected_label: &str, pem: &str) -> Result<SecretVec> {
424    let begin = format!("-----BEGIN {expected_label}-----");
425    let end = format!("-----END {expected_label}-----");
426
427    let start = find_boundary(pem.as_bytes(), begin.as_bytes())
428        .ok_or(Error::InvalidEncapsulationKey)?
429        + begin.len();
430    let after_begin = &pem.as_bytes()[start..];
431    let body_len = after_begin
432        .iter()
433        .position(|&b| b == b'-')
434        .ok_or(Error::InvalidEncapsulationKey)?;
435    if !after_begin[body_len..].starts_with(end.as_bytes()) {
436        return Err(Error::InvalidEncapsulationKey);
437    }
438    let body = &after_begin[..body_len];
439
440    let mut clean = SecretVec::zeroed(body.len());
441    let mut kept = 0usize;
442    for &c in body {
443        // `kept` never exceeds the index of `c`, so this store is always in bounds.
444        clean[kept] = c;
445        kept += usize::from(1 - is_pem_whitespace(c));
446    }
447    clean.truncate(kept);
448    if clean.is_empty() {
449        return Err(Error::InvalidEncapsulationKey);
450    }
451    base64::decode(&clean)
452}
453
454#[cfg(test)]
455mod tests {
456    use super::*;
457    use crate::agility::AgileKeyPair;
458
459    #[test]
460    fn rfc9935_spki_and_pkcs8_der_pem_roundtrip_all_ml_kem() {
461        let policy = SecurityPolicy::Permissive;
462        for alg in [
463            KemAlgorithm::MlKem512,
464            KemAlgorithm::MlKem768,
465            KemAlgorithm::MlKem1024,
466        ] {
467            let kp = AgileKeyPair::generate(policy, alg)
468                .ok()
469                .unwrap_or_else(|| unreachable!());
470
471            // SPKI DER & PEM
472            let spki_der = encode_spki_der(&kp.public)
473                .ok()
474                .unwrap_or_else(|| unreachable!());
475            let decoded_pk = decode_spki_der(policy, &spki_der)
476                .ok()
477                .unwrap_or_else(|| unreachable!());
478            assert_eq!(decoded_pk, kp.public);
479
480            let spki_pem = encode_spki_pem(&kp.public)
481                .ok()
482                .unwrap_or_else(|| unreachable!());
483            assert!(spki_pem.starts_with("-----BEGIN PUBLIC KEY-----\n"));
484            assert_eq!(
485                decode_spki_pem(policy, &spki_pem)
486                    .ok()
487                    .unwrap_or_else(|| unreachable!()),
488                kp.public
489            );
490
491            // PKCS#8 expandedKey DER
492            let pkcs8_exp = encode_pkcs8_expanded_der(&kp.secret)
493                .ok()
494                .unwrap_or_else(|| unreachable!());
495            let decoded_exp = decode_pkcs8_der(policy, &pkcs8_exp)
496                .ok()
497                .unwrap_or_else(|| unreachable!());
498            assert_eq!(decoded_exp.expose_raw_bytes(), kp.secret.expose_raw_bytes());
499
500            // PKCS#8 seed [0] DER & PEM
501            let seed = [0x42u8; 64];
502            let pkcs8_seed_pem = encode_pkcs8_seed_pem(alg, &seed)
503                .ok()
504                .unwrap_or_else(|| unreachable!());
505            assert!(pkcs8_seed_pem.starts_with("-----BEGIN PRIVATE KEY-----\n"));
506            let decoded_seed = decode_pkcs8_pem(policy, &pkcs8_seed_pem)
507                .ok()
508                .unwrap_or_else(|| unreachable!());
509            assert_eq!(decoded_seed.algorithm(), alg);
510        }
511
512        // CRYPTREC policy rejects importing ML-KEM-512 SPKI
513        let kp512 = AgileKeyPair::generate(SecurityPolicy::Permissive, KemAlgorithm::MlKem512)
514            .ok()
515            .unwrap_or_else(|| unreachable!());
516        let spki512 = encode_spki_der(&kp512.public)
517            .ok()
518            .unwrap_or_else(|| unreachable!());
519        assert_eq!(
520            decode_spki_der(SecurityPolicy::CryptrecCategory3Plus, &spki512),
521            Err(Error::PolicyViolation)
522        );
523    }
524
525    /// Independently derives `ek` from a `(d || z)` seed via FIPS 203 `KeyGen_internal`.
526    fn ek_from_seed(alg: KemAlgorithm, seed: &[u8; 64]) -> Vec<u8> {
527        let mut d = [0u8; 32];
528        let mut z = [0u8; 32];
529        d.copy_from_slice(&seed[..32]);
530        z.copy_from_slice(&seed[32..]);
531        match alg {
532            KemAlgorithm::MlKem512 => ml_kem_512::hazmat::keygen_internal(&d, &z)
533                .0
534                .as_bytes()
535                .to_vec(),
536            KemAlgorithm::MlKem768 => ml_kem_768::hazmat::keygen_internal(&d, &z)
537                .0
538                .as_bytes()
539                .to_vec(),
540            KemAlgorithm::MlKem1024 => ml_kem_1024::hazmat::keygen_internal(&d, &z)
541                .0
542                .as_bytes()
543                .to_vec(),
544            KemAlgorithm::XWing => unreachable!(),
545        }
546    }
547
548    #[test]
549    fn rfc9935_pkcs8_v1_and_v2_with_public_key_import_same_key() {
550        use crate::codec::pkcs8::test_util::{public_key_field, rebuild, v2_with_public_key};
551
552        let policy = SecurityPolicy::Permissive;
553        let seed = [0x42u8; 64];
554        let other_seed = [0x43u8; 64];
555        let attrs: &[u8] = &[
556            0xA0, 0x0C, 0x30, 0x0A, 0x06, 0x03, 0x55, 0x04, 0x03, 0x31, 0x03, 0x0C, 0x01, 0x41,
557        ];
558        let decode_raw = |der: &[u8]| {
559            decode_pkcs8_der(policy, der)
560                .map(|sk| sk.expose_raw_bytes().to_vec())
561                .ok()
562        };
563
564        for alg in [
565            KemAlgorithm::MlKem512,
566            KemAlgorithm::MlKem768,
567            KemAlgorithm::MlKem1024,
568        ] {
569            let ek = ek_from_seed(alg, &seed);
570            let other_ek = ek_from_seed(alg, &other_seed);
571
572            // seed form: v1 (no publicKey) and v2 (with publicKey) give the same private key.
573            let v1 = encode_pkcs8_seed_der(alg, &seed)
574                .ok()
575                .unwrap_or_else(|| unreachable!());
576            let v2 = v2_with_public_key(&v1, &ek);
577            let expected = decode_raw(&v1).unwrap_or_else(|| unreachable!());
578            assert_eq!(decode_raw(&v2).as_deref(), Some(&expected[..]));
579            // v2 with attributes + publicKey is accepted.
580            assert_eq!(
581                decode_raw(&rebuild(
582                    &v1,
583                    &[0x01],
584                    &[attrs, &public_key_field(&ek)].concat()
585                ))
586                .as_deref(),
587                Some(&expected[..])
588            );
589
590            // PEM: both versions import to the same key.
591            let pem_v1 = encode_pkcs8_seed_pem(alg, &seed)
592                .ok()
593                .unwrap_or_else(|| unreachable!());
594            let pem_v2 = encode_pem("PRIVATE KEY", &v2)
595                .ok()
596                .unwrap_or_else(|| unreachable!());
597            for pem in [&pem_v1, &pem_v2] {
598                let sk = decode_pkcs8_pem(policy, pem)
599                    .ok()
600                    .unwrap_or_else(|| unreachable!());
601                assert_eq!(sk.expose_raw_bytes(), &expected[..]);
602            }
603
604            // expandedKey form with publicKey.
605            let sk = decode_pkcs8_der(policy, &v1)
606                .ok()
607                .unwrap_or_else(|| unreachable!());
608            let exp_v1 = encode_pkcs8_expanded_der(&sk)
609                .ok()
610                .unwrap_or_else(|| unreachable!());
611            assert_eq!(
612                decode_raw(&v2_with_public_key(&exp_v1, &ek)).as_deref(),
613                Some(&expected[..])
614            );
615
616            // Rejections: mismatched / truncated publicKey, v1 + publicKey, v2 without publicKey, unknown versions.
617            let mut flipped = ek.clone();
618            flipped[0] ^= 0x01;
619            let rejected = [
620                v2_with_public_key(&v1, &flipped),
621                v2_with_public_key(&v1, &other_ek),
622                v2_with_public_key(&v1, &ek[..ek.len() - 1]),
623                v2_with_public_key(&v1, &[]),
624                v2_with_public_key(&exp_v1, &other_ek),
625                rebuild(&v1, &[0x00], &public_key_field(&ek)),
626                rebuild(&v1, &[0x01], &[]),
627                rebuild(&v1, &[0x01], attrs),
628                rebuild(&v1, &[0x02], &[]),
629                rebuild(&v1, &[0x02], &public_key_field(&ek)),
630                rebuild(
631                    &v1,
632                    &[0x01],
633                    &[public_key_field(&ek), vec![0x05, 0x00]].concat(),
634                ),
635            ];
636            for der in &rejected {
637                assert_eq!(
638                    decode_pkcs8_der(policy, der).err(),
639                    Some(Error::InvalidDecapsulationKey)
640                );
641            }
642            let bad_pem = encode_pem("PRIVATE KEY", &rejected[1])
643                .ok()
644                .unwrap_or_else(|| unreachable!());
645            assert_eq!(
646                decode_pkcs8_pem(policy, &bad_pem).err(),
647                Some(Error::InvalidDecapsulationKey)
648            );
649        }
650
651        // Policy is still enforced for v2 keys.
652        let v1 = encode_pkcs8_seed_der(KemAlgorithm::MlKem512, &seed)
653            .ok()
654            .unwrap_or_else(|| unreachable!());
655        let v2 = v2_with_public_key(&v1, &ek_from_seed(KemAlgorithm::MlKem512, &seed));
656        assert_eq!(
657            decode_pkcs8_der(SecurityPolicy::CryptrecCategory3Plus, &v2).err(),
658            Some(Error::PolicyViolation)
659        );
660    }
661
662    #[test]
663    fn pem_layout_and_strict_body_decoding() {
664        // Line layout: 64-character lines, `\n` endings, and the exact pre-sized length.
665        for len in [0usize, 1, 2, 3, 47, 48, 49, 96, 1000] {
666            let der: Vec<u8> = (0u8..=255)
667                .cycle()
668                .take(len)
669                .map(|b| b.wrapping_mul(37))
670                .collect();
671            let pem = encode_pem("PRIVATE KEY", &der)
672                .ok()
673                .unwrap_or_else(|| unreachable!());
674            // Pre-sizing is exact, so the buffer never had to grow (and copy) while encoding.
675            assert_eq!(pem.len(), pem.capacity());
676            let lines: Vec<&str> = pem.lines().collect();
677            assert_eq!(lines.first(), Some(&"-----BEGIN PRIVATE KEY-----"));
678            assert_eq!(lines.last(), Some(&"-----END PRIVATE KEY-----"));
679            let body = &lines[1..lines.len() - 1];
680            assert!(body.iter().all(|l| !l.is_empty() && l.len() <= 64));
681            assert!(
682                body[..body.len().saturating_sub(1)]
683                    .iter()
684                    .all(|l| l.len() == 64)
685            );
686            if len > 0 {
687                let decoded = decode_pem("PRIVATE KEY", &pem)
688                    .ok()
689                    .unwrap_or_else(|| unreachable!());
690                assert_eq!(&*decoded, &der[..]);
691            }
692        }
693
694        let ok = |pem: &str| decode_pem("PRIVATE KEY", pem).ok().map(|v| v.to_vec());
695        // Explanatory text, CRLF line endings, inner whitespace and a following block are fine.
696        assert_eq!(
697            ok(concat!(
698                "intro\r\n",
699                "-----BEGIN PRIVATE KEY-----\r\n",
700                "Zm9v\r\nYmFy\r\n",
701                "-----END PRIVATE KEY-----\r\n",
702            )),
703            Some(b"foobar".to_vec())
704        );
705        assert_eq!(
706            ok(concat!(
707                "-----BEGIN PRIVATE KEY-----\n",
708                " Zm9v\tYg==\x0C\n",
709                "-----END PRIVATE KEY-----\n",
710                "-----BEGIN X-----\n-----END X-----\n",
711            )),
712            Some(b"foob".to_vec())
713        );
714        assert_eq!(
715            ok("-----BEGIN PRIVATE KEY-----\nZg==\n-----END PRIVATE KEY-----"),
716            Some(b"f".to_vec())
717        );
718        // The wanted block may follow other blocks and text containing `-`. The opening boundary
719        // is found exactly where `str::find` would find it.
720        let bundle = concat!(
721            "key - bundle --\n",
722            "-----BEGIN PUBLIC KEY-----\nYmFy\n-----END PUBLIC KEY-----\n",
723            "------BEGIN PRIVATE KEY-----\nZm9v\n-----END PRIVATE KEY-----\n",
724        );
725        assert_eq!(ok(bundle), Some(b"foo".to_vec()));
726        assert_eq!(
727            decode_pem("PUBLIC KEY", bundle).ok().map(|v| v.to_vec()),
728            Some(b"bar".to_vec())
729        );
730        for text in [bundle, "", "-", "no boundary", "-----BEGIN PRIVATE KEY----"] {
731            for label in ["PRIVATE KEY", "PUBLIC KEY", "X"] {
732                let boundary = format!("-----BEGIN {label}-----");
733                assert_eq!(
734                    find_boundary(text.as_bytes(), boundary.as_bytes()),
735                    text.find(&boundary)
736                );
737            }
738        }
739        // Rejected: non-canonical trailing bits, bad padding, invalid characters, empty body,
740        // missing / mismatched closing boundary.
741        for bad in [
742            "-----BEGIN PRIVATE KEY-----\nZh==\n-----END PRIVATE KEY-----\n",
743            "-----BEGIN PRIVATE KEY-----\nZm9=\n-----END PRIVATE KEY-----\n",
744            "-----BEGIN PRIVATE KEY-----\nZg=\n-----END PRIVATE KEY-----\n",
745            "-----BEGIN PRIVATE KEY-----\nZg==Zg==\n-----END PRIVATE KEY-----\n",
746            "-----BEGIN PRIVATE KEY-----\nZm9v*mFy\n-----END PRIVATE KEY-----\n",
747            "-----BEGIN PRIVATE KEY-----\nZm9v_mFy\n-----END PRIVATE KEY-----\n",
748            "-----BEGIN PRIVATE KEY-----\n \n-----END PRIVATE KEY-----\n",
749            "-----BEGIN PRIVATE KEY-----\nZm9v\n",
750            "-----BEGIN PRIVATE KEY-----\nZm9v\n-----END PUBLIC KEY-----\n",
751            "-----BEGIN PRIVATE KEY-----\nZm9v-YmFy\n-----END PRIVATE KEY-----\n",
752            "-----BEGIN PUBLIC KEY-----\nZm9v\n-----END PUBLIC KEY-----\n",
753        ] {
754            assert!(ok(bad).is_none(), "{bad:?}");
755        }
756    }
757}