purecrypto 0.6.5

A pure-Rust cryptography toolkit with no foreign-code dependencies, from constant-time primitives up to keys, X.509 and TLS.
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
//! ML-KEM — the FIPS 203 module-lattice key-encapsulation mechanism (the
//! standardized form of Kyber), in all three parameter sets:
//!
//!  - [`MlKem512`]  / [`MlKem512DecapsKey`]  / [`MlKem512EncapsKey`]  / [`MlKem512Ciphertext`]
//!  - [`MlKem768`]  / [`MlKem768DecapsKey`]  / [`MlKem768EncapsKey`]  / [`MlKem768Ciphertext`]
//!  - [`MlKem1024`] / [`MlKem1024DecapsKey`] / [`MlKem1024EncapsKey`] / [`MlKem1024Ciphertext`]
//!
//! This is a `no_std`, allocation-free implementation: keys, ciphertexts and
//! all intermediate state live on the stack as fixed-size arrays.
//! Randomness is supplied through the [`RngCore`] trait;
//! deterministic constructors (`from_seeds`, `encapsulate_deterministic`)
//! expose the FIPS 203 internal functions for known-answer testing.
//!
//! Decapsulation never branches on secret data: the Fujisaki–Okamoto
//! re-encryption check and the implicit-rejection fallback both run in
//! constant time (see the `kem` submodule).
//!
//! # Test-vector coverage — known gap
//!
//! Unit tests cover the FIPS 203 reference flow at all three parameter
//! sets, but the crate does **not** ship the full NIST ACVP test set for
//! ML-KEM (`testdata/` carries ACVP for ML-DSA and SLH-DSA, but not yet
//! for ML-KEM). The ACVP corpus is multi-megabyte and out of scope for
//! the audit hardening batch; landing it is tracked as future work.
//! In the meantime the existing per-set fixed vectors plus deterministic
//! constructors (`from_seeds`, `encapsulate_deterministic`) make the
//! algorithm fully testable against external implementations.

pub(crate) mod indcpa;
pub(crate) mod kem;
pub(crate) mod poly;

/// Returned by the per-variant `EncapsKey::from_bytes_validated` constructor
/// when the supplied encapsulation-key bytes contain off-modulus coefficients
/// (FIPS 203 §7.2 "Encapsulation key check" failure).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct EncapsKeyCheckError;

impl core::fmt::Display for EncapsKeyCheckError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str("ML-KEM encapsulation key has off-modulus coefficients (FIPS 203 §7.2)")
    }
}

impl core::error::Error for EncapsKeyCheckError {}

use crate::rng::RngCore;

/// Marker for one ML-KEM parameter set; carries no data, only used to choose
/// among the typed APIs by name.
pub struct MlKem512;
/// Marker for ML-KEM-768 (the default and most widely deployed set).
pub struct MlKem768;
/// Marker for ML-KEM-1024 (highest security level).
pub struct MlKem1024;

/// Size in bytes of an ML-KEM-768 encapsulation key (kept for back-compat).
pub const ENCAPS_KEY_BYTES: usize = kem::ek_bytes(3);
/// Size in bytes of an ML-KEM-768 decapsulation key (kept for back-compat).
pub const DECAPS_KEY_BYTES: usize = kem::dk_bytes(3);
/// Size in bytes of an ML-KEM-768 ciphertext (kept for back-compat).
pub const CIPHERTEXT_BYTES: usize = kem::ct_bytes(3, 10, 4);
/// Size in bytes of a shared secret (same across all ML-KEM sets).
pub const SHARED_SECRET_BYTES: usize = 32;

#[cfg(feature = "der")]
mod oids {
    /// `id-alg-ml-kem-512`  — 2.16.840.1.101.3.4.4.1.
    pub(crate) const ML_KEM_512: &[u64] = &[2, 16, 840, 1, 101, 3, 4, 4, 1];
    /// `id-alg-ml-kem-768`  — 2.16.840.1.101.3.4.4.2.
    pub(crate) const ML_KEM_768: &[u64] = &[2, 16, 840, 1, 101, 3, 4, 4, 2];
    /// `id-alg-ml-kem-1024` — 2.16.840.1.101.3.4.4.3.
    pub(crate) const ML_KEM_1024: &[u64] = &[2, 16, 840, 1, 101, 3, 4, 4, 3];
}

/// Emits the per-set newtype wrappers and impls for one ML-KEM parameter set.
///
/// `$ek_size`, `$dk_size`, `$ct_size` are passed alongside the FIPS 203
/// (K, η₁, η₂, dᵤ, dᵥ) tuple — Rust const generics can't (yet, stably) compute
/// array sizes from other const params, so we name them at the macro call site.
macro_rules! ml_kem_set {
    (
        $set_doc:literal,
        $dk_name:ident, $ek_name:ident, $ct_name:ident,
        $k:expr, $eta1:expr, $eta2:expr, $du:expr, $dv:expr,
        $ek_size:expr, $dk_size:expr, $ct_size:expr,
        $oid:ident
    ) => {
        #[doc = concat!("An ", $set_doc, " encapsulation (public) key.")]
        #[derive(Clone, Copy, PartialEq, Eq, Debug)]
        pub struct $ek_name([u8; $ek_size]);

        #[doc = concat!("An ", $set_doc, " decapsulation (secret) key.")]
        #[derive(Clone)]
        pub struct $dk_name([u8; $dk_size]);

        #[doc = concat!("An ", $set_doc, " ciphertext.")]
        #[derive(Clone, Copy, PartialEq, Eq, Debug)]
        pub struct $ct_name([u8; $ct_size]);

        impl $dk_name {
            /// Encapsulation-key size in bytes.
            pub const ENCAPS_KEY_BYTES: usize = $ek_size;
            /// Decapsulation-key size in bytes.
            pub const DECAPS_KEY_BYTES: usize = $dk_size;
            /// Ciphertext size in bytes.
            pub const CIPHERTEXT_BYTES: usize = $ct_size;

            /// Generates a fresh key pair from `rng` (32 bytes each of `d` and `z`).
            ///
            /// `rng` SHOULD be a cryptographically secure CSPRNG (see
            /// [`CryptoRng`](crate::rng::CryptoRng)). The bound is left at
            /// [`RngCore`] only so the TLS / DTLS handshake layers can
            /// thread a single shared RNG type through hybrid key-share
            /// generation; production callers should pass `OsRng` or an
            /// HMAC-DRBG seeded from one.
            pub fn generate<R: RngCore>(rng: &mut R) -> ($dk_name, $ek_name) {
                let mut d = [0u8; 32];
                let mut z = [0u8; 32];
                rng.fill_bytes(&mut d);
                rng.fill_bytes(&mut z);
                Self::from_seeds(&d, &z)
            }

            /// Deterministically derives a key pair from `(d, z)`
            /// (ML-KEM.KeyGen_internal). Intended for testing.
            pub fn from_seeds(d: &[u8; 32], z: &[u8; 32]) -> ($dk_name, $ek_name) {
                let mut ek = [0u8; $ek_size];
                let mut dk = [0u8; $dk_size];
                kem::keygen::<$k, $eta1>(d, z, &mut ek, &mut dk);
                ($dk_name(dk), $ek_name(ek))
            }

            /// The matching encapsulation key.
            pub fn encapsulation_key(&self) -> $ek_name {
                let pke_dk = 384 * $k;
                let mut ek = [0u8; $ek_size];
                ek.copy_from_slice(&self.0[pke_dk..pke_dk + $ek_size]);
                $ek_name(ek)
            }

            /// Decapsulates `ct`, returning the 32-byte shared secret. On an
            /// invalid ciphertext this returns a pseudo-random value (implicit
            /// rejection), not an error — the difference is unobservable to
            /// the sender.
            pub fn decapsulate(&self, ct: &$ct_name) -> [u8; SHARED_SECRET_BYTES] {
                kem::decaps::<$k, $eta1, $eta2, $du, $dv>(&self.0, &ct.0)
            }

            /// Restores a decapsulation key from its byte encoding.
            /// **No validation.** Use
            /// [`from_bytes_validated`](Self::from_bytes_validated) when
            /// the bytes come from an untrusted source.
            pub fn from_bytes(bytes: [u8; $dk_size]) -> Self {
                $dk_name(bytes)
            }

            /// FIPS 203 §7.3 "Decapsulation key check": confirms that the
            /// SHA3-256 hash of the embedded encapsulation key matches
            /// the H(ek) field stored at offset `pke_dk + ek_size` of the
            /// decapsulation key. This guards against a corrupted /
            /// adversarially-modified key file that would otherwise
            /// produce wrong shared secrets at decapsulation time.
            pub fn from_bytes_validated(
                bytes: [u8; $dk_size],
            ) -> Result<Self, crate::mlkem::EncapsKeyCheckError> {
                use crate::hash::Digest;
                let pke_dk = 384 * $k;
                let ek_start = pke_dk;
                let ek_end = ek_start + $ek_size;
                // H(ek) is the 32-byte SHA3-256 hash placed right after
                // the embedded encapsulation key, per FIPS 203 §7.3.
                let h_start = ek_end;
                let h_end = h_start + 32;
                // Defensive: a malformed bytes slice short of these
                // bounds is structurally impossible (the array length is
                // fixed at $dk_size), but assert anyway so a future
                // size mistake fails loudly rather than silently passing.
                assert!(h_end <= $dk_size);
                let mut hasher = crate::hash::Sha3_256::new();
                hasher.update(&bytes[ek_start..ek_end]);
                let h = hasher.finalize();
                if h.as_ref() != &bytes[h_start..h_end] {
                    return Err(crate::mlkem::EncapsKeyCheckError);
                }
                Ok($dk_name(bytes))
            }

            /// The byte encoding.
            pub fn to_bytes(&self) -> [u8; $dk_size] {
                self.0
            }
        }

        // FIPS 203 §3.3 mandates that decapsulation-key material be
        // zeroed before deallocation. We avoid pulling in the `zeroize`
        // crate by overwriting the bytes and routing them through
        // `core::hint::black_box`, which prevents LLVM from eliminating
        // the writes as dead stores.
        impl Drop for $dk_name {
            fn drop(&mut self) {
                for b in self.0.iter_mut() {
                    *b = 0;
                }
                let _ = core::hint::black_box(&self.0);
            }
        }

        impl $ek_name {
            /// Encapsulation-key size in bytes.
            pub const BYTES: usize = $ek_size;

            /// Encapsulates to a fresh shared secret, returning `(ciphertext, secret)`.
            ///
            /// `rng` SHOULD be a cryptographically secure CSPRNG (see
            /// [`CryptoRng`](crate::rng::CryptoRng)) — the shared secret
            /// derives from `m`, so a predictable `rng` directly compromises
            /// the secret. The bound is left at [`RngCore`] only so the TLS
            /// / DTLS handshake layers can thread a single shared RNG type;
            /// production callers should pass `OsRng` or an HMAC-DRBG seeded
            /// from one.
            pub fn encapsulate<R: RngCore>(
                &self,
                rng: &mut R,
            ) -> ($ct_name, [u8; SHARED_SECRET_BYTES]) {
                let mut m = [0u8; 32];
                rng.fill_bytes(&mut m);
                self.encapsulate_deterministic(&m)
            }

            /// Encapsulates with an explicit message `m` (ML-KEM.Encaps_internal).
            /// Intended for testing.
            pub fn encapsulate_deterministic(
                &self,
                m: &[u8; 32],
            ) -> ($ct_name, [u8; SHARED_SECRET_BYTES]) {
                let mut ct = [0u8; $ct_size];
                let ss = kem::encaps::<$k, $eta1, $eta2, $du, $dv>(&self.0, m, &mut ct);
                ($ct_name(ct), ss)
            }

            /// Restores an encapsulation key from its byte encoding.
            ///
            /// **No validation.** Use [`from_bytes_validated`](Self::from_bytes_validated)
            /// when the bytes come from an untrusted source — FIPS 203 §7.2
            /// requires verifying that every 12-bit coefficient is in `[0, q)`
            /// (re-encoding round-trip), otherwise an attacker can supply
            /// off-modulus EKs as an oracle into the encapsulator's noise.
            pub fn from_bytes(bytes: [u8; $ek_size]) -> Self {
                $ek_name(bytes)
            }

            /// FIPS 203 §7.2 "Encapsulation key check": confirms
            /// `ByteEncode₁₂(ByteDecode₁₂(t)) == t` for the polynomial-vector
            /// portion of the EK (the trailing 32-byte `rho` is opaque and
            /// not checked). Returns the validated key on success.
            pub fn from_bytes_validated(
                bytes: [u8; $ek_size],
            ) -> Result<Self, crate::mlkem::EncapsKeyCheckError> {
                const POLYBYTES_LOCAL: usize = 384;
                let polyvec = &bytes[..POLYBYTES_LOCAL * $k];
                for i in 0..$k {
                    let chunk = &polyvec[i * POLYBYTES_LOCAL..(i + 1) * POLYBYTES_LOCAL];
                    let p = crate::mlkem::poly::from_bytes(chunk);
                    let re = crate::mlkem::poly::to_bytes(&p);
                    if re != chunk {
                        return Err(crate::mlkem::EncapsKeyCheckError);
                    }
                }
                Ok($ek_name(bytes))
            }

            /// The byte encoding.
            pub fn to_bytes(&self) -> [u8; $ek_size] {
                self.0
            }
        }

        impl $ct_name {
            /// Ciphertext size in bytes.
            pub const BYTES: usize = $ct_size;

            /// Restores a ciphertext from its byte encoding.
            pub fn from_bytes(bytes: [u8; $ct_size]) -> Self {
                $ct_name(bytes)
            }

            /// The byte encoding.
            pub fn to_bytes(&self) -> [u8; $ct_size] {
                self.0
            }
        }

        /// PKCS#8 (raw expanded dk) for the decapsulation key.
        #[cfg(feature = "der")]
        impl $dk_name {
            /// Encodes the key as a PKCS#8 `PrivateKeyInfo` DER.
            pub fn to_pkcs8_der(&self) -> alloc::vec::Vec<u8> {
                use crate::der::{encode_integer, encode_octet_string, encode_sequence, oid_tlv};
                let algid = encode_sequence(&oid_tlv(oids::$oid));
                encode_sequence(
                    &[encode_integer(&[0]), algid, encode_octet_string(&self.0)].concat(),
                )
            }

            /// Encodes the key as a PKCS#8 PEM document.
            pub fn to_pkcs8_pem(&self) -> alloc::string::String {
                crate::der::pem_encode("PRIVATE KEY", &self.to_pkcs8_der())
            }

            /// Parses a PKCS#8 `PrivateKeyInfo` DER (raw `dk` form).
            pub fn from_pkcs8_der(der: &[u8]) -> Result<Self, crate::der::Error> {
                use crate::der::{Error, Reader, parse_oid};
                let mut r = Reader::new(der);
                let mut seq = r.read_sequence()?;
                seq.read_integer_bytes()?;
                let mut algid = seq.read_sequence()?;
                if parse_oid(algid.read_oid()?)?.as_slice() != oids::$oid {
                    return Err(Error::Malformed);
                }
                let inner = seq.read_octet_string()?;
                let bytes: [u8; $dk_size] = inner.try_into().map_err(|_| Error::Malformed)?;
                Ok($dk_name(bytes))
            }

            /// Parses a PKCS#8 PEM private key.
            pub fn from_pkcs8_pem(pem: &str) -> Result<Self, crate::der::Error> {
                Self::from_pkcs8_der(&crate::der::pem_decode(pem, "PRIVATE KEY")?)
            }

            /// Encrypts the PKCS#8 encoding under PBES2 (RFC 5958 §3 +
            /// RFC 8018 §6.2), returning the DER-encoded
            /// `EncryptedPrivateKeyInfo`.
            #[cfg(all(feature = "kdf", feature = "der"))]
            pub fn to_pkcs8_der_encrypted(
                &self,
                password: &[u8],
                params: &crate::kdf::pbes2::Pbes2Params,
                rng: &mut impl crate::rng::RngCore,
            ) -> alloc::vec::Vec<u8> {
                crate::kdf::pbes2::encrypt(&self.to_pkcs8_der(), password, params, rng)
            }

            /// PEM-wrapped variant of [`Self::to_pkcs8_der_encrypted`].
            #[cfg(all(feature = "kdf", feature = "der"))]
            pub fn to_pkcs8_pem_encrypted(
                &self,
                password: &[u8],
                params: &crate::kdf::pbes2::Pbes2Params,
                rng: &mut impl crate::rng::RngCore,
            ) -> alloc::string::String {
                crate::kdf::pbes2::encrypt_pem(&self.to_pkcs8_der(), password, params, rng)
            }

            /// Parses an `EncryptedPrivateKeyInfo` DER and decrypts it
            /// back to a PKCS#8 ML-KEM decapsulation key.
            #[cfg(all(feature = "kdf", feature = "der"))]
            pub fn from_pkcs8_der_encrypted(
                der: &[u8],
                password: &[u8],
            ) -> Result<Self, crate::der::Error> {
                let inner = crate::kdf::pbes2::decrypt(der, password)
                    .map_err(|_| crate::der::Error::Malformed)?;
                Self::from_pkcs8_der(&inner)
            }

            /// PEM-wrapped variant of [`Self::from_pkcs8_der_encrypted`].
            #[cfg(all(feature = "kdf", feature = "der"))]
            pub fn from_pkcs8_pem_encrypted(
                pem: &str,
                password: &[u8],
            ) -> Result<Self, crate::der::Error> {
                let inner = crate::kdf::pbes2::decrypt_pem(pem, password)
                    .map_err(|_| crate::der::Error::Malformed)?;
                Self::from_pkcs8_der(&inner)
            }
        }

        /// PKIX `SubjectPublicKeyInfo` for the encapsulation key.
        #[cfg(feature = "der")]
        impl $ek_name {
            /// Encodes the key as a PKIX `SubjectPublicKeyInfo` DER structure.
            pub fn to_spki_der(&self) -> alloc::vec::Vec<u8> {
                use crate::der::{encode_bit_string, encode_sequence, oid_tlv};
                let algid = encode_sequence(&oid_tlv(oids::$oid));
                encode_sequence(&[algid, encode_bit_string(&self.0)].concat())
            }

            /// Encodes the key as a PKIX PEM document (`-----BEGIN PUBLIC KEY-----`).
            pub fn to_spki_pem(&self) -> alloc::string::String {
                crate::der::pem_encode("PUBLIC KEY", &self.to_spki_der())
            }

            /// Parses a PKIX `SubjectPublicKeyInfo` DER structure.
            pub fn from_spki_der(der: &[u8]) -> Result<Self, crate::der::Error> {
                use crate::der::{Error, Reader, parse_oid};
                let mut reader = Reader::new(der);
                let mut spki = reader.read_sequence()?;
                let mut algid = spki.read_sequence()?;
                if parse_oid(algid.read_oid()?)?.as_slice() != oids::$oid {
                    return Err(Error::Malformed);
                }
                let key_bits = spki.read_bit_string()?;
                let bytes: [u8; $ek_size] = key_bits.try_into().map_err(|_| Error::Malformed)?;
                Ok($ek_name(bytes))
            }

            /// Parses a PKIX PEM public key.
            pub fn from_spki_pem(pem: &str) -> Result<Self, crate::der::Error> {
                Self::from_spki_der(&crate::der::pem_decode(pem, "PUBLIC KEY")?)
            }
        }
    };
}

ml_kem_set!(
    "ML-KEM-512 (FIPS 203, security level 1)",
    MlKem512DecapsKey,
    MlKem512EncapsKey,
    MlKem512Ciphertext,
    2,
    3,
    2,
    10,
    4,
    /* ek */ 800,
    /* dk */ 1632,
    /* ct */ 768,
    ML_KEM_512
);

ml_kem_set!(
    "ML-KEM-768 (FIPS 203, security level 3)",
    MlKem768DecapsKey,
    MlKem768EncapsKey,
    MlKem768Ciphertext,
    3,
    2,
    2,
    10,
    4,
    /* ek */ 1184,
    /* dk */ 2400,
    /* ct */ 1088,
    ML_KEM_768
);

ml_kem_set!(
    "ML-KEM-1024 (FIPS 203, security level 5)",
    MlKem1024DecapsKey,
    MlKem1024EncapsKey,
    MlKem1024Ciphertext,
    4,
    2,
    2,
    11,
    5,
    /* ek */ 1568,
    /* dk */ 3168,
    /* ct */ 1568,
    ML_KEM_1024
);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hash::Sha256;
    use crate::rng::HmacDrbg;

    #[test]
    fn fips203_sizes() {
        // FIPS 203 §8.
        assert_eq!(
            (
                MlKem512DecapsKey::ENCAPS_KEY_BYTES,
                MlKem512DecapsKey::DECAPS_KEY_BYTES,
                MlKem512DecapsKey::CIPHERTEXT_BYTES,
            ),
            (800, 1632, 768)
        );
        assert_eq!(
            (
                MlKem768DecapsKey::ENCAPS_KEY_BYTES,
                MlKem768DecapsKey::DECAPS_KEY_BYTES,
                MlKem768DecapsKey::CIPHERTEXT_BYTES,
            ),
            (1184, 2400, 1088)
        );
        assert_eq!(
            (
                MlKem1024DecapsKey::ENCAPS_KEY_BYTES,
                MlKem1024DecapsKey::DECAPS_KEY_BYTES,
                MlKem1024DecapsKey::CIPHERTEXT_BYTES,
            ),
            (1568, 3168, 1568)
        );
    }

    #[test]
    fn roundtrip_768() {
        let mut rng = HmacDrbg::<Sha256>::new(b"mlkem-768", b"nonce", &[]);
        let (dk, ek) = MlKem768DecapsKey::generate(&mut rng);
        let (ct, ss_a) = ek.encapsulate(&mut rng);
        let ss_b = dk.decapsulate(&ct);
        assert_eq!(ss_a, ss_b);
    }

    #[test]
    fn roundtrip_512() {
        let mut rng = HmacDrbg::<Sha256>::new(b"mlkem-512", b"nonce", &[]);
        let (dk, ek) = MlKem512DecapsKey::generate(&mut rng);
        let (ct, ss_a) = ek.encapsulate(&mut rng);
        let ss_b = dk.decapsulate(&ct);
        assert_eq!(ss_a, ss_b);
    }

    #[test]
    fn roundtrip_1024() {
        let mut rng = HmacDrbg::<Sha256>::new(b"mlkem-1024", b"nonce", &[]);
        let (dk, ek) = MlKem1024DecapsKey::generate(&mut rng);
        let (ct, ss_a) = ek.encapsulate(&mut rng);
        let ss_b = dk.decapsulate(&ct);
        assert_eq!(ss_a, ss_b);
    }

    #[test]
    fn implicit_rejection_512() {
        let mut rng = HmacDrbg::<Sha256>::new(b"reject-512", b"nonce", &[]);
        let (dk, ek) = MlKem512DecapsKey::generate(&mut rng);
        let (ct, ss) = ek.encapsulate(&mut rng);
        let mut bad = ct.to_bytes();
        bad[0] ^= 1;
        let rejected = dk.decapsulate(&MlKem512Ciphertext::from_bytes(bad));
        assert_ne!(rejected, ss);
        // Deterministic: same bad ciphertext maps to the same rejection secret.
        assert_eq!(
            rejected,
            dk.decapsulate(&MlKem512Ciphertext::from_bytes(bad))
        );
    }

    #[test]
    fn implicit_rejection_1024() {
        let mut rng = HmacDrbg::<Sha256>::new(b"reject-1024", b"nonce", &[]);
        let (dk, ek) = MlKem1024DecapsKey::generate(&mut rng);
        let (ct, ss) = ek.encapsulate(&mut rng);
        let mut bad = ct.to_bytes();
        bad[0] ^= 1;
        let rejected = dk.decapsulate(&MlKem1024Ciphertext::from_bytes(bad));
        assert_ne!(rejected, ss);
        assert_eq!(
            rejected,
            dk.decapsulate(&MlKem1024Ciphertext::from_bytes(bad))
        );
    }

    /// ML-KEM-768 byte-compat with OpenSSL 3.5 (deterministic keygen with
    /// `d = z = 0³²`). The refactor must produce identical bytes.
    #[test]
    fn openssl_interop_768_unchanged_after_refactor() {
        use crate::test_util::{from_hex, from_hex_vec};
        let (dk, ek) = MlKem768DecapsKey::from_seeds(&[0u8; 32], &[0u8; 32]);

        let e = ek.to_bytes();
        assert_eq!(e[..16], from_hex::<16>("254a797885c63b1440aa389c65340ef3"));
        assert_eq!(
            e[e.len() - 32..],
            from_hex::<32>("6d3ae406763c50457d1481402aafc7e23f43f9d1d7c0af7060ac1daa9ecb0e67")
        );

        let ct_bytes = from_hex_vec(include_str!("../../testdata/mlkem768_openssl_ct.hex"));
        let mut ct = [0u8; MlKem768DecapsKey::CIPHERTEXT_BYTES];
        ct.copy_from_slice(&ct_bytes);
        let ss = dk.decapsulate(&MlKem768Ciphertext::from_bytes(ct));
        assert_eq!(
            ss,
            from_hex::<32>("2b59302b878ffc5eae9e4f5d4ddc8a73cea97ef10af90d7945b331d288683066")
        );
    }

    #[cfg(feature = "der")]
    #[test]
    fn spki_768_matches_openssl_and_roundtrips() {
        use crate::test_util::from_hex_vec;
        let (_dk, ek) = MlKem768DecapsKey::from_seeds(&[0u8; 32], &[0u8; 32]);
        let expected = from_hex_vec(include_str!("../../testdata/mlkem768_openssl_spki.hex"));
        assert_eq!(ek.to_spki_der(), expected);

        let pem = ek.to_spki_pem();
        assert!(pem.starts_with("-----BEGIN PUBLIC KEY-----"));
        let parsed = MlKem768EncapsKey::from_spki_pem(&pem).unwrap();
        assert_eq!(parsed, ek);
    }

    #[cfg(feature = "der")]
    #[test]
    fn pkcs8_roundtrip_each_set() {
        let mut rng = HmacDrbg::<Sha256>::new(b"pkcs8", b"nonce", &[]);
        // 512
        let (dk, _) = MlKem512DecapsKey::generate(&mut rng);
        let pem = dk.to_pkcs8_pem();
        let parsed = MlKem512DecapsKey::from_pkcs8_pem(&pem).unwrap();
        assert_eq!(parsed.to_bytes(), dk.to_bytes());
        // 768
        let (dk, _) = MlKem768DecapsKey::generate(&mut rng);
        let pem = dk.to_pkcs8_pem();
        let parsed = MlKem768DecapsKey::from_pkcs8_pem(&pem).unwrap();
        assert_eq!(parsed.to_bytes(), dk.to_bytes());
        // 1024
        let (dk, _) = MlKem1024DecapsKey::generate(&mut rng);
        let pem = dk.to_pkcs8_pem();
        let parsed = MlKem1024DecapsKey::from_pkcs8_pem(&pem).unwrap();
        assert_eq!(parsed.to_bytes(), dk.to_bytes());
    }

    /// FIPS 203 §7.3 — the decapsulation key embeds `H(ek)` so a future
    /// decap can short-circuit a key that's been corrupted on disk. The
    /// trusted-input fast path `from_bytes` accepts anything; the strict
    /// path `from_bytes_validated` rejects a byte-flipped key.
    #[test]
    fn decaps_key_from_bytes_validated_catches_corruption() {
        let mut rng = HmacDrbg::<Sha256>::new(b"validated", b"nonce", &[]);
        // ML-KEM-512.
        let (dk, _) = MlKem512DecapsKey::generate(&mut rng);
        let good = dk.to_bytes();
        assert!(MlKem512DecapsKey::from_bytes_validated(good).is_ok());
        let mut bad = good;
        // Flip a byte inside the H(ek) digest field. Offset:
        // pke_dk = 384 * k = 768; ek_size = 800 → H starts at 1568,
        // 32 bytes long.
        bad[1570] ^= 1;
        // Trusted-input fast path: no check.
        let _trusted = MlKem512DecapsKey::from_bytes(bad);
        // Strict path: must reject.
        assert!(MlKem512DecapsKey::from_bytes_validated(bad).is_err());

        // ML-KEM-1024.
        let (dk, _) = MlKem1024DecapsKey::generate(&mut rng);
        let good = dk.to_bytes();
        assert!(MlKem1024DecapsKey::from_bytes_validated(good).is_ok());
        let mut bad = good;
        // pke_dk = 384 * 4 = 1536; ek_size = 1568 → H starts at 3104.
        bad[3105] ^= 1;
        assert!(MlKem1024DecapsKey::from_bytes_validated(bad).is_err());
    }
}