Skip to main content

quantaegis_sdk/
rfc9881.rs

1//! **RFC 9881** standard ASN.1 DER and PEM codecs for ML-DSA-44, ML-DSA-65, and ML-DSA-87
2//! `SubjectPublicKeyInfo` (SPKI) and `PKCS#8` (`OneAsymmetricKey` / `PrivateKeyInfo`).
3//!
4//! # Official NIST CSOR OIDs (RFC 9881)
5//! - `ML-DSA-44`: `2.16.840.1.101.3.4.3.17` (`06 09 60 86 48 01 65 03 04 03 11`)
6//! - `ML-DSA-65`: `2.16.840.1.101.3.4.3.18` (`06 09 60 86 48 01 65 03 04 03 12`)
7//! - `ML-DSA-87`: `2.16.840.1.101.3.4.3.19` (`06 09 60 86 48 01 65 03 04 03 13`)
8//!
9//! Per RFC 9881:
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`, 32-byte `xi`, RFC 9881 recommended)
13//!   - `expandedKey` (`OCTET STRING`, tag `0x04`, 2560 / 4032 / 4896 bytes)
14//!   - `both` (`SEQUENCE { OCTET STRING (32), OCTET STRING (expanded) }`, tag `0x30`) —
15//!     validated by recomputing `KeyGen_internal(seed)` and checking byte-for-byte equality
16//!     in constant time.
17//! - `PKCS#8` decoding strictly enforces RFC 5958 `OneAsymmetricKey`: `version` 0 MUST omit
18//!   `[1] publicKey`, and `version` 1 MUST include `[1] publicKey`. For `seed` and `both` it must
19//!   equal the key derived from the seed. For `expandedKey` it must match the `rho` and `tr`
20//!   stored in the private key (an expanded key carries no seed to re-derive `t1` from).
21//!   Well-formed `[0] attributes` are accepted and ignored. Encoders emit `version` 0 without a
22//!   public key.
23//! - Secret intermediates are held in zeroize-on-drop buffers, and private-key PEM uses
24//!   constant-time base64.
25
26use quantaegis_core::ct::ct_eq_slice;
27use quantaegis_core::{Error, Result, SecretBytes};
28use quantaegis_ml_dsa::{MlDsa44, MlDsa65, MlDsa87, ml_dsa_44, ml_dsa_65, ml_dsa_87};
29
30use crate::algorithm::SignatureAlgorithm;
31use crate::codec::SecretVec;
32use crate::codec::pkcs8::{self, der_tlv_len, push_der_header};
33use crate::policy::SecurityPolicy;
34use crate::rfc9935::{
35    TAG_BIT_STRING, TAG_CONTEXT_0_PRIMITIVE, TAG_OCTET_STRING, TAG_OID, TAG_SEQUENCE, decode_pem,
36    encode_der_tlv, encode_pem, parse_der_tlv,
37};
38use crate::signature_agility::{AgileSigningKey, AgileVerifyingKey};
39
40/// DER-encoded OID `2.16.840.1.101.3.4.3.17` (ML-DSA-44) without outer tag/length.
41const OID_ML_DSA_44: &[u8] = &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03, 0x11];
42/// DER-encoded OID `2.16.840.1.101.3.4.3.18` (ML-DSA-65) without outer tag/length.
43const OID_ML_DSA_65: &[u8] = &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03, 0x12];
44/// DER-encoded OID `2.16.840.1.101.3.4.3.19` (ML-DSA-87) without outer tag/length.
45const OID_ML_DSA_87: &[u8] = &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03, 0x13];
46
47const fn oid_bytes_for(alg: SignatureAlgorithm) -> Result<&'static [u8]> {
48    match alg {
49        SignatureAlgorithm::MlDsa44 => Ok(OID_ML_DSA_44),
50        SignatureAlgorithm::MlDsa65 => Ok(OID_ML_DSA_65),
51        SignatureAlgorithm::MlDsa87 => Ok(OID_ML_DSA_87),
52        _ => Err(Error::InvalidVerifyingKey),
53    }
54}
55
56fn alg_from_oid_bytes(oid: &[u8]) -> Result<SignatureAlgorithm> {
57    if oid == OID_ML_DSA_44 {
58        Ok(SignatureAlgorithm::MlDsa44)
59    } else if oid == OID_ML_DSA_65 {
60        Ok(SignatureAlgorithm::MlDsa65)
61    } else if oid == OID_ML_DSA_87 {
62        Ok(SignatureAlgorithm::MlDsa87)
63    } else {
64        Err(Error::InvalidVerifyingKey)
65    }
66}
67
68/// Encodes an ML-DSA verifying key into RFC 9881 **SPKI DER** (`SubjectPublicKeyInfo`).
69pub fn encode_spki_der(vk: &AgileVerifyingKey) -> Result<Vec<u8>> {
70    let oid = oid_bytes_for(vk.algorithm())?;
71    let alg_id = encode_der_tlv(TAG_SEQUENCE, &encode_der_tlv(TAG_OID, oid));
72
73    let raw = vk.raw_bytes();
74    let mut bit_string_val = Vec::with_capacity(1 + raw.len());
75    bit_string_val.push(0x00); // 0 unused bits
76    bit_string_val.extend_from_slice(raw);
77    let bit_string = encode_der_tlv(TAG_BIT_STRING, &bit_string_val);
78
79    let mut spki_body = Vec::with_capacity(alg_id.len() + bit_string.len());
80    spki_body.extend_from_slice(&alg_id);
81    spki_body.extend_from_slice(&bit_string);
82    Ok(encode_der_tlv(TAG_SEQUENCE, &spki_body))
83}
84
85/// Decodes an RFC 9881 **SPKI DER** verifying key while enforcing `policy`.
86pub fn decode_spki_der(policy: SecurityPolicy, der: &[u8]) -> Result<AgileVerifyingKey> {
87    let (seq_tag, spki_body, trailing) =
88        parse_der_tlv(der).map_err(|_| Error::InvalidVerifyingKey)?;
89    if seq_tag != TAG_SEQUENCE || !trailing.is_empty() {
90        return Err(Error::InvalidVerifyingKey);
91    }
92
93    let (alg_tag, alg_body, rest) =
94        parse_der_tlv(spki_body).map_err(|_| Error::InvalidVerifyingKey)?;
95    if alg_tag != TAG_SEQUENCE {
96        return Err(Error::InvalidVerifyingKey);
97    }
98    // RFC 9881: AlgorithmIdentifier.parameters MUST be absent.
99    let (oid_tag, oid_val, alg_extra) =
100        parse_der_tlv(alg_body).map_err(|_| Error::InvalidVerifyingKey)?;
101    if oid_tag != TAG_OID || !alg_extra.is_empty() {
102        return Err(Error::InvalidVerifyingKey);
103    }
104    let alg = alg_from_oid_bytes(oid_val)?;
105
106    let (bs_tag, bs_val, rest2) = parse_der_tlv(rest).map_err(|_| Error::InvalidVerifyingKey)?;
107    if bs_tag != TAG_BIT_STRING || !rest2.is_empty() || bs_val.is_empty() || bs_val[0] != 0x00 {
108        return Err(Error::InvalidVerifyingKey);
109    }
110
111    AgileVerifyingKey::from_raw(policy, alg, &bs_val[1..])
112}
113
114/// Encodes an ML-DSA 32-byte seed `xi` into RFC 9881 **PKCS#8 DER** (`seed` CHOICE tag `0x80`).
115///
116/// The seed is written directly into the returned buffer (no intermediate copies).
117pub fn encode_pkcs8_seed_der(alg: SignatureAlgorithm, seed: &[u8; 32]) -> Result<Vec<u8>> {
118    let oid = oid_bytes_for(alg).map_err(|_| Error::InvalidSigningKey)?;
119    pkcs8::encode_v1(
120        oid,
121        der_tlv_len(seed.len()),
122        Error::InvalidSigningKey,
123        |out| {
124            push_der_header(out, TAG_CONTEXT_0_PRIMITIVE, seed.len());
125            out.extend_from_slice(seed);
126        },
127    )
128}
129
130/// Encodes an expanded ML-DSA signing key into RFC 9881 **PKCS#8 DER** (`expandedKey` tag `0x04`).
131///
132/// The key is written directly into the returned buffer (no intermediate copies).
133pub fn encode_pkcs8_expanded_der(sk: &AgileSigningKey) -> Result<Vec<u8>> {
134    let oid = oid_bytes_for(sk.algorithm()).map_err(|_| Error::InvalidSigningKey)?;
135    let expanded = sk.expose_raw_bytes();
136    pkcs8::encode_v1(
137        oid,
138        der_tlv_len(expanded.len()),
139        Error::InvalidSigningKey,
140        |out| {
141            push_der_header(out, TAG_OCTET_STRING, expanded.len());
142            out.extend_from_slice(expanded);
143        },
144    )
145}
146
147/// Encodes both the 32-byte seed `xi` and expanded key into RFC 9881 **PKCS#8 DER** (`both` tag `0x30`).
148///
149/// The seed and the freshly expanded key (borrowed from the typed key, which is wiped on drop)
150/// are written directly into the returned buffer (no intermediate copies).
151pub fn encode_pkcs8_both_der(alg: SignatureAlgorithm, seed: &[u8; 32]) -> Result<Vec<u8>> {
152    let oid = oid_bytes_for(alg).map_err(|_| Error::InvalidSigningKey)?;
153    with_keypair_from_seed(alg, seed, |_, expanded| {
154        let both_len = der_tlv_len(seed.len()) + der_tlv_len(expanded.len());
155        pkcs8::encode_v1(
156            oid,
157            der_tlv_len(both_len),
158            Error::InvalidSigningKey,
159            |out| {
160                push_der_header(out, TAG_SEQUENCE, both_len);
161                push_der_header(out, TAG_OCTET_STRING, seed.len());
162                out.extend_from_slice(seed);
163                push_der_header(out, TAG_OCTET_STRING, expanded.len());
164                out.extend_from_slice(expanded);
165            },
166        )
167    })
168}
169
170/// Runs `f(verifying_key, expanded_signing_key)` on FIPS 204 `ML-DSA.KeyGen_internal(seed)`.
171///
172/// `f` borrows the typed keys in place, so the expanded signing key is never copied into an
173/// intermediate buffer. The typed signing key is wiped when it is dropped.
174fn with_keypair_from_seed<T>(
175    alg: SignatureAlgorithm,
176    seed: &[u8; 32],
177    f: impl FnOnce(&[u8], &[u8]) -> Result<T>,
178) -> Result<T> {
179    match alg {
180        SignatureAlgorithm::MlDsa44 => {
181            let (vk, sk) = MlDsa44::from_seed(seed);
182            f(vk.as_bytes(), sk.expose_bytes())
183        }
184        SignatureAlgorithm::MlDsa65 => {
185            let (vk, sk) = MlDsa65::from_seed(seed);
186            f(vk.as_bytes(), sk.expose_bytes())
187        }
188        SignatureAlgorithm::MlDsa87 => {
189            let (vk, sk) = MlDsa87::from_seed(seed);
190            f(vk.as_bytes(), sk.expose_bytes())
191        }
192        _ => Err(Error::InvalidSigningKey),
193    }
194}
195
196/// Byte range of `tr = SHAKE256(pk, 64)` inside an expanded ML-DSA signing key
197/// (FIPS 204 Algorithm 24: `sk = rho (32) || K (32) || tr (64) || s1 || s2 || t0`).
198const SK_TR_RANGE: core::ops::Range<usize> = 64..128;
199
200/// Byte range of the public seed `rho` at the start of both an expanded ML-DSA signing key and a
201/// verifying key (FIPS 204 Algorithm 22: `pk = rho (32) || t1`).
202const RHO_RANGE: core::ops::Range<usize> = 0..32;
203
204/// Checks an RFC 5958 `publicKey` against a verifying key derived from the seed.
205fn check_derived_public_key(derived: &[u8], public_key: Option<&[u8]>) -> Result<()> {
206    match public_key {
207        Some(pk) if !ct_eq_slice(derived, pk).into_bool() => Err(Error::InvalidSigningKey),
208        _ => Ok(()),
209    }
210}
211
212/// Checks an RFC 5958 `publicKey` against an `expandedKey`-only signing key, which has no seed
213/// to re-derive the verifying key from.
214///
215/// It compares `tr = SHAKE256(public_key, 64)` with the `tr` that FIPS 204 stores in the expanded
216/// key, and the `rho` of both. By SHAKE256 collision resistance this binds `public_key` to the
217/// key's `tr`.
218///
219/// This does **not** prove that `s1`, `s2` and `t0` belong to `public_key`: recomputing `t1`
220/// from them would need a public key-derivation API in `quantaegis-ml-dsa`. The same limit
221/// applies to an `expandedKey` imported without a `publicKey`, whose internal consistency is
222/// not checked either. Only the `seed` and `both` forms are fully re-derived.
223fn check_expanded_public_key(
224    alg: SignatureAlgorithm,
225    sk: &AgileSigningKey,
226    public_key: Option<&[u8]>,
227) -> Result<()> {
228    let Some(public_key) = public_key else {
229        return Ok(());
230    };
231    let tr = match alg {
232        SignatureAlgorithm::MlDsa44 => ml_dsa_44::VerifyingKey::from_bytes(public_key)
233            .map_err(|_| Error::InvalidSigningKey)?
234            .tr(),
235        SignatureAlgorithm::MlDsa65 => ml_dsa_65::VerifyingKey::from_bytes(public_key)
236            .map_err(|_| Error::InvalidSigningKey)?
237            .tr(),
238        SignatureAlgorithm::MlDsa87 => ml_dsa_87::VerifyingKey::from_bytes(public_key)
239            .map_err(|_| Error::InvalidSigningKey)?
240            .tr(),
241        _ => return Err(Error::InvalidSigningKey),
242    };
243    let raw = sk.expose_raw_bytes();
244    let stored_tr = raw.get(SK_TR_RANGE).ok_or(Error::InvalidSigningKey)?;
245    let stored_rho = raw.get(RHO_RANGE).ok_or(Error::InvalidSigningKey)?;
246    let public_rho = public_key.get(RHO_RANGE).ok_or(Error::InvalidSigningKey)?;
247    if (ct_eq_slice(&tr, stored_tr) & ct_eq_slice(public_rho, stored_rho)).into_bool() {
248        Ok(())
249    } else {
250        Err(Error::InvalidSigningKey)
251    }
252}
253
254/// Decodes an RFC 9881 **PKCS#8 DER** private key supporting `seed` (`0x80`), `expandedKey`
255/// (`0x04`), and `both` (`0x30`, with mandatory constant-time seed consistency check).
256///
257/// Strictly enforces RFC 5958 `OneAsymmetricKey`: `version` 0 MUST omit `[1] publicKey`, and
258/// `version` 1 MUST include `[1] publicKey`, which must belong to the private key; otherwise the
259/// key is rejected. For `seed` and `both` it must equal the verifying key derived from the seed.
260/// For `expandedKey` its hash must equal the stored `tr` and its `rho` the stored `rho`; the
261/// secret vectors of an `expandedKey` are not checked against it. Well-formed `[0] attributes`
262/// are accepted and ignored. See `crate::codec::pkcs8::parse` for the exact rules.
263pub fn decode_pkcs8_der(policy: SecurityPolicy, der: &[u8]) -> Result<AgileSigningKey> {
264    let key = pkcs8::parse(der, Error::InvalidSigningKey)?;
265    let alg = alg_from_oid_bytes(key.algorithm_oid).map_err(|_| Error::InvalidSigningKey)?;
266    policy.validate_signature(alg)?;
267
268    let (choice_tag, choice_val, choice_extra) =
269        parse_der_tlv(key.private_key).map_err(|_| Error::InvalidSigningKey)?;
270    if !choice_extra.is_empty() {
271        return Err(Error::InvalidSigningKey);
272    }
273
274    match choice_tag {
275        TAG_CONTEXT_0_PRIMITIVE => {
276            if choice_val.len() != 32 {
277                return Err(Error::InvalidSigningKey);
278            }
279            // Wiped on drop, including on early return.
280            let mut seed = SecretBytes::new([0u8; 32]);
281            seed.expose_secret_mut().copy_from_slice(choice_val);
282            with_keypair_from_seed(alg, seed.expose_secret(), |vk, expanded| {
283                check_derived_public_key(vk, key.public_key)?;
284                AgileSigningKey::from_raw(policy, alg, expanded)
285            })
286        }
287        TAG_OCTET_STRING => {
288            let sk = AgileSigningKey::from_raw(policy, alg, choice_val)?;
289            check_expanded_public_key(alg, &sk, key.public_key)?;
290            Ok(sk)
291        }
292        TAG_SEQUENCE => {
293            let (s_tag, s_val, rest_both) =
294                parse_der_tlv(choice_val).map_err(|_| Error::InvalidSigningKey)?;
295            let (e_tag, e_val, extra_both) =
296                parse_der_tlv(rest_both).map_err(|_| Error::InvalidSigningKey)?;
297            if s_tag != TAG_OCTET_STRING
298                || e_tag != TAG_OCTET_STRING
299                || !extra_both.is_empty()
300                || s_val.len() != 32
301            {
302                return Err(Error::InvalidSigningKey);
303            }
304            let mut seed = SecretBytes::new([0u8; 32]);
305            seed.expose_secret_mut().copy_from_slice(s_val);
306            with_keypair_from_seed(alg, seed.expose_secret(), |vk, recomputed| {
307                if !ct_eq_slice(recomputed, e_val).into_bool() {
308                    return Err(Error::InvalidSigningKey);
309                }
310                check_derived_public_key(vk, key.public_key)?;
311                AgileSigningKey::from_raw(policy, alg, recomputed)
312            })
313        }
314        _ => Err(Error::InvalidSigningKey),
315    }
316}
317
318/// Encodes an ML-DSA verifying key into RFC 9881 **PEM** (`-----BEGIN PUBLIC KEY-----`).
319pub fn encode_spki_pem(vk: &AgileVerifyingKey) -> Result<String> {
320    let der = encode_spki_der(vk)?;
321    encode_pem("PUBLIC KEY", &der).map_err(|_| Error::InvalidVerifyingKey)
322}
323
324/// Decodes an RFC 9881 **PEM** verifying key (`-----BEGIN PUBLIC KEY-----`).
325pub fn decode_spki_pem(policy: SecurityPolicy, pem: &str) -> Result<AgileVerifyingKey> {
326    let der = decode_pem("PUBLIC KEY", pem).map_err(|_| Error::InvalidVerifyingKey)?;
327    decode_spki_der(policy, &der)
328}
329
330/// Encodes an ML-DSA 32-byte seed into RFC 9881 **PEM** (`-----BEGIN PRIVATE KEY-----`).
331pub fn encode_pkcs8_seed_pem(alg: SignatureAlgorithm, seed: &[u8; 32]) -> Result<String> {
332    // The intermediate DER is wiped on drop, on both the success and the error path.
333    let der = SecretVec::from_vec(encode_pkcs8_seed_der(alg, seed)?);
334    encode_pem("PRIVATE KEY", &der).map_err(|_| Error::InvalidSigningKey)
335}
336
337/// Decodes an RFC 9881 **PEM** private key (`-----BEGIN PRIVATE KEY-----`).
338pub fn decode_pkcs8_pem(policy: SecurityPolicy, pem: &str) -> Result<AgileSigningKey> {
339    // The decoded DER is a `SecretVec`, wiped on drop on every path.
340    let der = decode_pem("PRIVATE KEY", pem).map_err(|_| Error::InvalidSigningKey)?;
341    decode_pkcs8_der(policy, &der)
342}
343
344#[cfg(test)]
345mod tests {
346    use super::*;
347    use crate::signature_agility::AgileSigningKeyPair;
348
349    #[test]
350    fn rfc9881_spki_and_pkcs8_all_three_choices_roundtrip() {
351        let policy = SecurityPolicy::Permissive;
352        let seed = [0x5Au8; 32];
353
354        for alg in [
355            SignatureAlgorithm::MlDsa44,
356            SignatureAlgorithm::MlDsa65,
357            SignatureAlgorithm::MlDsa87,
358        ] {
359            let kp = AgileSigningKeyPair::from_seed(policy, alg, &seed)
360                .ok()
361                .unwrap_or_else(|| unreachable!());
362
363            // SPKI DER & PEM
364            let spki_pem = encode_spki_pem(&kp.verifying)
365                .ok()
366                .unwrap_or_else(|| unreachable!());
367            assert!(spki_pem.starts_with("-----BEGIN PUBLIC KEY-----\n"));
368            let decoded_vk = decode_spki_pem(policy, &spki_pem)
369                .ok()
370                .unwrap_or_else(|| unreachable!());
371            assert_eq!(decoded_vk, kp.verifying);
372
373            // PKCS#8 seed [0] PEM
374            let seed_pem = encode_pkcs8_seed_pem(alg, &seed)
375                .ok()
376                .unwrap_or_else(|| unreachable!());
377            assert!(seed_pem.starts_with("-----BEGIN PRIVATE KEY-----\n"));
378            let from_seed_sk = decode_pkcs8_pem(policy, &seed_pem)
379                .ok()
380                .unwrap_or_else(|| unreachable!());
381            assert_eq!(
382                from_seed_sk.expose_raw_bytes(),
383                kp.signing.expose_raw_bytes()
384            );
385
386            // PKCS#8 expandedKey DER
387            let exp_der = encode_pkcs8_expanded_der(&kp.signing)
388                .ok()
389                .unwrap_or_else(|| unreachable!());
390            let from_exp_sk = decode_pkcs8_der(policy, &exp_der)
391                .ok()
392                .unwrap_or_else(|| unreachable!());
393            assert_eq!(
394                from_exp_sk.expose_raw_bytes(),
395                kp.signing.expose_raw_bytes()
396            );
397
398            // PKCS#8 both SEQUENCE DER + consistency check
399            let mut both_der = encode_pkcs8_both_der(alg, &seed)
400                .ok()
401                .unwrap_or_else(|| unreachable!());
402            let from_both_sk = decode_pkcs8_der(policy, &both_der)
403                .ok()
404                .unwrap_or_else(|| unreachable!());
405            assert_eq!(
406                from_both_sk.expose_raw_bytes(),
407                kp.signing.expose_raw_bytes()
408            );
409
410            // Tampering the last byte of expandedKey inside `both` MUST fail consistency check!
411            let last = both_der.len() - 1;
412            both_der[last] ^= 0x01;
413            assert_eq!(
414                decode_pkcs8_der(policy, &both_der).err(),
415                Some(Error::InvalidSigningKey)
416            );
417        }
418
419        // CRYPTREC Category 3+ rejects ML-DSA-44 SPKI PEM
420        let kp44 = AgileSigningKeyPair::from_seed(
421            SecurityPolicy::Permissive,
422            SignatureAlgorithm::MlDsa44,
423            &seed,
424        )
425        .ok()
426        .unwrap_or_else(|| unreachable!());
427        let pem44 = encode_spki_pem(&kp44.verifying)
428            .ok()
429            .unwrap_or_else(|| unreachable!());
430        assert_eq!(
431            decode_spki_pem(SecurityPolicy::CryptrecCategory3Plus, &pem44),
432            Err(Error::PolicyViolation)
433        );
434    }
435
436    #[test]
437    fn rfc9881_pkcs8_v1_and_v2_with_public_key_import_same_key() {
438        use crate::codec::pkcs8::test_util::{public_key_field, rebuild, v2_with_public_key};
439
440        let policy = SecurityPolicy::Permissive;
441        let seed = [0x5Au8; 32];
442        let other_seed = [0x5Bu8; 32];
443        let decode_raw = |der: &[u8]| {
444            decode_pkcs8_der(policy, der)
445                .map(|sk| sk.expose_raw_bytes().to_vec())
446                .ok()
447        };
448
449        for alg in [
450            SignatureAlgorithm::MlDsa44,
451            SignatureAlgorithm::MlDsa65,
452            SignatureAlgorithm::MlDsa87,
453        ] {
454            let kp = AgileSigningKeyPair::from_seed(policy, alg, &seed)
455                .ok()
456                .unwrap_or_else(|| unreachable!());
457            let other = AgileSigningKeyPair::from_seed(policy, alg, &other_seed)
458                .ok()
459                .unwrap_or_else(|| unreachable!());
460            let pk = kp.verifying.raw_bytes();
461            let other_pk = other.verifying.raw_bytes();
462            let expected = kp.signing.expose_raw_bytes();
463
464            let seed_v1 = encode_pkcs8_seed_der(alg, &seed)
465                .ok()
466                .unwrap_or_else(|| unreachable!());
467            let exp_v1 = encode_pkcs8_expanded_der(&kp.signing)
468                .ok()
469                .unwrap_or_else(|| unreachable!());
470            let both_v1 = encode_pkcs8_both_der(alg, &seed)
471                .ok()
472                .unwrap_or_else(|| unreachable!());
473
474            for v1 in [&seed_v1, &exp_v1, &both_v1] {
475                // v1 (no publicKey) and v2 + publicKey: same private key.
476                let v2 = v2_with_public_key(v1, pk);
477                for der in [v1.clone(), v2.clone()] {
478                    assert_eq!(decode_raw(&der).as_deref(), Some(expected));
479                }
480                // PEM of the v2 encoding.
481                let pem = encode_pem("PRIVATE KEY", &v2)
482                    .ok()
483                    .unwrap_or_else(|| unreachable!());
484                let from_pem = decode_pkcs8_pem(policy, &pem)
485                    .ok()
486                    .unwrap_or_else(|| unreachable!());
487                assert_eq!(from_pem.expose_raw_bytes(), expected);
488
489                // Rejections (including strict RFC 5958 v2 without publicKey).
490                let mut flipped = pk.to_vec();
491                let last = flipped.len() - 1;
492                flipped[last] ^= 0x01;
493                for der in [
494                    v2_with_public_key(v1, other_pk),
495                    v2_with_public_key(v1, &flipped),
496                    v2_with_public_key(v1, &pk[..pk.len() - 1]),
497                    rebuild(v1, &[0x00], &public_key_field(pk)),
498                    rebuild(v1, &[0x01], &[]),
499                    rebuild(v1, &[0x02], &[]),
500                    rebuild(v1, &[0x02], &public_key_field(pk)),
501                ] {
502                    assert_eq!(
503                        decode_pkcs8_der(policy, &der).err(),
504                        Some(Error::InvalidSigningKey)
505                    );
506                }
507                let bad_pem = encode_pem("PRIVATE KEY", &v2_with_public_key(v1, other_pk))
508                    .ok()
509                    .unwrap_or_else(|| unreachable!());
510                assert_eq!(
511                    decode_pkcs8_pem(policy, &bad_pem).err(),
512                    Some(Error::InvalidSigningKey)
513                );
514            }
515
516            // `expandedKey` + `publicKey`: a key whose `tr` was replaced by another key's `tr` is
517            // rejected together with that other public key, because its `rho` differs. So is the
518            // honest pair once the private key's `rho` is damaged.
519            let mut spliced = expected.to_vec();
520            spliced[SK_TR_RANGE].copy_from_slice(&other.signing.expose_raw_bytes()[SK_TR_RANGE]);
521            let mut bad_rho = expected.to_vec();
522            bad_rho[5] ^= 0x01;
523            for (raw, with_pk) in [(&spliced, other_pk), (&bad_rho, pk)] {
524                let sk = AgileSigningKey::from_raw(policy, alg, raw)
525                    .ok()
526                    .unwrap_or_else(|| unreachable!());
527                let der = encode_pkcs8_expanded_der(&sk)
528                    .ok()
529                    .unwrap_or_else(|| unreachable!());
530                assert_eq!(
531                    decode_pkcs8_der(policy, &v2_with_public_key(&der, with_pk)).err(),
532                    Some(Error::InvalidSigningKey)
533                );
534            }
535
536            // PEM of the encoder output still round-trips.
537            let seed_pem = encode_pkcs8_seed_pem(alg, &seed)
538                .ok()
539                .unwrap_or_else(|| unreachable!());
540            let from_seed_pem = decode_pkcs8_pem(policy, &seed_pem)
541                .ok()
542                .unwrap_or_else(|| unreachable!());
543            assert_eq!(from_seed_pem.expose_raw_bytes(), expected);
544        }
545    }
546}