Skip to main content

quantaegis_ml_kem/
lib.rs

1//! From-scratch, pure-Rust, `#![no_std]`, constant-time implementation of **NIST FIPS 203**
2//! (Module-Lattice-Based Key-Encapsulation Mechanism Standard: **ML-KEM-512**, **ML-KEM-768**,
3//! and **ML-KEM-1024**).
4//!
5//! # Security & Engineering Properties
6//! - Zero external cryptographic dependencies; `#![no_std]`; `#![forbid(unsafe_code)]`.
7//! - Division-free finite-field arithmetic and `Compress_d` (immune to KyberSlash-class timing
8//!   side-channels).
9//! - Mandatory FIPS 203 Section 7.2 / 7.3 encapsulation and decapsulation key validation checks.
10//! - Constant-time Fujisaki-Okamoto ciphertext verification and implicit rejection.
11//! - Automatic zeroization on drop and redacted `Debug` formatting for all secret material.
12//! - Strict separation between randomized production APIs ([`quantaegis_core::Kem`]) and deterministic
13//!   internal APIs (`hazmat`, matching FIPS 203 Section 6 `*_internal`).
14//!
15//! > **Note**: Pre-`1.0.0` software — an independent third-party cryptographic audit has not yet
16//! > been completed; please take this into account when using this crate. The project-wide maturity
17//! > stage is tracked in one place:
18//! > [SECURITY.md](https://github.com/PyRin-c/quantaegis/blob/main/SECURITY.md#maturity--production-readiness-status).
19
20#![no_std]
21#![forbid(unsafe_code)]
22
23#[cfg(feature = "std")]
24extern crate std;
25
26mod encoding;
27mod field;
28mod kpke;
29mod mlkem;
30mod ntt;
31pub mod params;
32mod poly;
33mod sampling;
34
35/// Generates a strongly typed parameter-set module (`ml_kem_512`, `ml_kem_768`, `ml_kem_1024`).
36macro_rules! define_ml_kem_variant {
37    (
38        mod_name: $mod_name:ident,
39        kem_type: $kem_type:ident,
40        doc_name: $doc_name:literal,
41        security_cat: $sec_cat:literal,
42        k: $k:expr,
43        eta1: $eta1:expr,
44        eta2: $eta2:expr,
45        du: $du:expr,
46        dv: $dv:expr,
47        ek_len: $ek_len:expr,
48        dk_len: $dk_len:expr,
49        ct_len: $ct_len:expr,
50    ) => {
51        #[doc = concat!("**", $doc_name, "** parameter set (", $sec_cat, ", NIST FIPS 203).")]
52        pub mod $mod_name {
53            use core::fmt;
54
55            use quantaegis_core::{CryptoRng, Error, Kem, Result, SecretBytes, SharedSecret, Zeroize};
56
57            use crate::mlkem::{
58                mlkem_decaps_internal_into, mlkem_encaps_internal_into, mlkem_keygen_internal_into,
59                validate_decapsulation_key_ref, validate_encapsulation_key,
60            };
61            use crate::params::SEED_LEN;
62
63            /// Encapsulation (public) key length in bytes.
64            pub const EK_LEN: usize = $ek_len;
65            /// Decapsulation (private) key length in bytes.
66            pub const DK_LEN: usize = $dk_len;
67            /// Ciphertext length in bytes.
68            pub const CT_LEN: usize = $ct_len;
69
70            #[doc = concat!("Validated ", $doc_name, " encapsulation (public) key.")]
71            #[derive(Clone, Eq, PartialEq)]
72            pub struct EncapsulationKey([u8; EK_LEN]);
73
74            impl EncapsulationKey {
75                /// Parses and validates an encapsulation key per **FIPS 203, Section 7.2**
76                /// (exact length + every 12-bit coefficient `< 3329`).
77                pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
78                    let validated = validate_encapsulation_key::<$k, EK_LEN>(bytes)?;
79                    Ok(Self(validated))
80                }
81
82                /// Returns the canonical byte representation of this encapsulation key.
83                #[inline]
84                pub const fn as_bytes(&self) -> &[u8; EK_LEN] {
85                    &self.0
86                }
87
88                /// Returns an all-zero placeholder encapsulation key for in-place initialization.
89                #[inline]
90                pub const fn zeroed() -> Self {
91                    Self([0u8; EK_LEN])
92                }
93            }
94
95            impl fmt::Debug for EncapsulationKey {
96                fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97                    write!(f, concat!($doc_name, "::EncapsulationKey([{} bytes])"), EK_LEN)
98                }
99            }
100
101            #[doc = concat!("Validated ", $doc_name, " decapsulation (private) key. Automatically zeroized on drop.")]
102            pub struct DecapsulationKey {
103                bytes: SecretBytes<DK_LEN>,
104                initialized: bool,
105            }
106
107            impl DecapsulationKey {
108                /// Parses and validates a decapsulation key per **FIPS 203, Section 7.3**
109                /// (exact length + coefficient bounds + constant-time `H(ek)` hash check).
110                pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
111                    validate_decapsulation_key_ref::<$k, EK_LEN, DK_LEN>(bytes)?;
112                    let mut dk = Self::zeroed();
113                    dk.bytes.expose_secret_mut().copy_from_slice(bytes);
114                    dk.initialized = true;
115                    Ok(dk)
116                }
117
118                /// Validates this decapsulation key in place per **FIPS 203, Section 7.3**
119                /// without creating a stack copy of the key material.
120                pub fn validate(&self) -> Result<()> {
121                    if !self.initialized {
122                        return Err(Error::InvalidDecapsulationKey);
123                    }
124                    validate_decapsulation_key_ref::<$k, EK_LEN, DK_LEN>(self.bytes.expose_secret())
125                }
126
127                /// Explicitly borrows the underlying secret key bytes.
128                #[inline]
129                pub const fn expose_bytes(&self) -> &[u8; DK_LEN] {
130                    self.bytes.expose_secret()
131                }
132
133                /// Returns an uninitialized all-zero placeholder decapsulation key for in-place
134                /// heap initialization without stack-to-heap secret moves.
135                ///
136                /// Uninitialized (or subsequently zeroized) placeholder keys are rejected by
137                /// [`DecapsulationKey::validate`], [`Kem::decaps`], and `decaps_into` with
138                /// [`Error::InvalidDecapsulationKey`] until populated by `keygen_into`.
139                #[inline]
140                pub const fn zeroed() -> Self {
141                    Self {
142                        bytes: SecretBytes::new([0u8; DK_LEN]),
143                        initialized: false,
144                    }
145                }
146            }
147
148            impl Zeroize for DecapsulationKey {
149                #[inline]
150                fn zeroize(&mut self) {
151                    self.bytes.zeroize();
152                    self.initialized = false;
153                }
154            }
155
156            impl fmt::Debug for DecapsulationKey {
157                fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158                    write!(f, concat!($doc_name, "::DecapsulationKey([REDACTED; {} bytes])"), DK_LEN)
159                }
160            }
161
162            #[doc = concat!($doc_name, " encapsulated ciphertext.")]
163            #[derive(Clone, Eq, PartialEq)]
164            pub struct Ciphertext([u8; CT_LEN]);
165
166            impl Ciphertext {
167                /// Constructs a ciphertext after checking exact length (`CT_LEN`).
168                pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
169                    if bytes.len() != CT_LEN {
170                        return Err(Error::InvalidLength {
171                            expected: CT_LEN,
172                            actual: bytes.len(),
173                        });
174                    }
175                    let mut out = [0u8; CT_LEN];
176                    out.copy_from_slice(bytes);
177                    Ok(Self(out))
178                }
179
180                /// Returns the canonical byte representation of this ciphertext.
181                #[inline]
182                pub const fn as_bytes(&self) -> &[u8; CT_LEN] {
183                    &self.0
184                }
185
186                /// Returns an all-zero placeholder ciphertext for in-place initialization.
187                #[inline]
188                pub const fn zeroed() -> Self {
189                    Self([0u8; CT_LEN])
190                }
191            }
192
193            impl fmt::Debug for Ciphertext {
194                fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195                    write!(f, concat!($doc_name, "::Ciphertext([{} bytes])"), CT_LEN)
196                }
197            }
198
199            #[doc = concat!($doc_name, " KEM marker type implementing [`quantaegis_core::Kem`].")]
200            pub struct $kem_type;
201
202            impl $kem_type {
203                /// Generates a fresh key pair directly into caller-owned storage without creating
204                /// serialized stack copies of the decapsulation key (`FIPS 203, Algorithm 19`).
205                pub fn keygen_into<R: CryptoRng + ?Sized>(
206                    rng: &mut R,
207                    ek_out: &mut EncapsulationKey,
208                    dk_out: &mut DecapsulationKey,
209                ) -> Result<()> {
210                    dk_out.zeroize();
211                    let mut d = SecretBytes::new([0u8; SEED_LEN]);
212                    let mut z = SecretBytes::new([0u8; SEED_LEN]);
213                    rng.try_fill_bytes(d.expose_secret_mut())?;
214                    rng.try_fill_bytes(z.expose_secret_mut())?;
215
216                    mlkem_keygen_internal_into::<$k, $eta1, EK_LEN, DK_LEN>(
217                        d.expose_secret(),
218                        z.expose_secret(),
219                        &mut ek_out.0,
220                        dk_out.bytes.expose_secret_mut(),
221                    );
222                    dk_out.initialized = true;
223                    Ok(())
224                }
225
226                /// Encapsulates directly into caller-owned `ct_out` and `ss_out` without leaving
227                /// an unwiped stack copy of the shared secret (`FIPS 203, Algorithm 20`).
228                pub fn encaps_into<R: CryptoRng + ?Sized>(
229                    ek: &EncapsulationKey,
230                    rng: &mut R,
231                    ct_out: &mut Ciphertext,
232                    ss_out: &mut SharedSecret,
233                ) -> Result<()> {
234                    let mut m = SecretBytes::new([0u8; SEED_LEN]);
235                    rng.try_fill_bytes(m.expose_secret_mut())?;
236
237                    mlkem_encaps_internal_into::<$k, $eta1, $eta2, $du, $dv, EK_LEN, CT_LEN>(
238                        ek.as_bytes(),
239                        m.expose_secret(),
240                        &mut ct_out.0,
241                        ss_out,
242                    );
243                    Ok(())
244                }
245
246                /// Decapsulates directly into caller-owned `ss_out` without leaving an unwiped
247                /// stack copy of the shared secret (`FIPS 203, Algorithm 21`).
248                ///
249                /// Returns [`Error::InvalidDecapsulationKey`] if `dk` is an uninitialized or
250                /// zeroized placeholder.
251                pub fn decaps_into(
252                    dk: &DecapsulationKey,
253                    ct: &Ciphertext,
254                    ss_out: &mut SharedSecret,
255                ) -> Result<()> {
256                    if !dk.initialized {
257                        return Err(Error::InvalidDecapsulationKey);
258                    }
259                    mlkem_decaps_internal_into::<$k, $eta1, $eta2, $du, $dv, EK_LEN, DK_LEN, CT_LEN>(
260                        dk.expose_bytes(),
261                        ct.as_bytes(),
262                        ss_out,
263                    );
264                    Ok(())
265                }
266            }
267
268            impl Kem for $kem_type {
269                type EncapsulationKey = EncapsulationKey;
270                type DecapsulationKey = DecapsulationKey;
271                type Ciphertext = Ciphertext;
272                type SharedSecret = SharedSecret;
273
274                /// Generates a fresh key pair (`FIPS 203, Algorithm 19: ML-KEM.KeyGen()`).
275                ///
276                /// Note: returning secret key material by value in safe Rust can leave an
277                /// unzeroized copy in the callee's return staging slot; FIPS/zeroization-critical
278                /// callers should use `keygen_into` directly into caller-owned storage.
279                fn keygen<R: CryptoRng + ?Sized>(
280                    rng: &mut R,
281                ) -> Result<(Self::EncapsulationKey, Self::DecapsulationKey)> {
282                    let mut res = Ok((EncapsulationKey::zeroed(), DecapsulationKey::zeroed()));
283                    if let Ok((ref mut ek, ref mut dk)) = res
284                        && let Err(e) = Self::keygen_into(rng, ek, dk)
285                    {
286                        res = Err(e);
287                    }
288                    res
289                }
290
291                /// Encapsulates a shared secret to `ek` (`FIPS 203, Algorithm 20: ML-KEM.Encaps()`).
292                ///
293                /// Note: returning `SharedSecret` by value in safe Rust can leave an unzeroized
294                /// copy in the callee's return staging slot; FIPS/zeroization-critical callers
295                /// should use `encaps_into` directly into caller-owned storage.
296                fn encaps<R: CryptoRng + ?Sized>(
297                    ek: &Self::EncapsulationKey,
298                    rng: &mut R,
299                ) -> Result<(Self::Ciphertext, Self::SharedSecret)> {
300                    let mut res = Ok((Ciphertext::zeroed(), SharedSecret::new([0u8; 32])));
301                    if let Ok((ref mut ct, ref mut ss)) = res
302                        && let Err(e) = Self::encaps_into(ek, rng, ct, ss)
303                    {
304                        res = Err(e);
305                    }
306                    res
307                }
308
309                /// Decapsulates `ct` using `dk` (`FIPS 203, Algorithm 21: ML-KEM.Decaps()`).
310                ///
311                /// Note: returning `SharedSecret` by value in safe Rust can leave an unzeroized
312                /// copy in the callee's return staging slot; FIPS/zeroization-critical callers
313                /// should use `decaps_into` directly into caller-owned storage.
314                fn decaps(
315                    dk: &Self::DecapsulationKey,
316                    ct: &Self::Ciphertext,
317                ) -> Result<Self::SharedSecret> {
318                    let mut res = Ok(SharedSecret::new([0u8; 32]));
319                    if let Ok(ref mut ss) = res
320                        && let Err(e) = Self::decaps_into(dk, ct, ss)
321                    {
322                        res = Err(e);
323                    }
324                    res
325                }
326            }
327
328            /// Deterministic internal FIPS 203 algorithms (`Section 6`) for ACVP/KAT validation.
329            ///
330            /// **Hazardous Materials** (requires Cargo feature `hazmat`): Never pass static,
331            /// predictable, or reused seeds in production. Prefer the randomized [`Kem`] trait
332            /// methods instead.
333            #[cfg(feature = "hazmat")]
334            pub mod hazmat {
335                use super::*;
336
337                /// `ML-KEM.KeyGen_internal(d, z)` (FIPS 203, Algorithm 16).
338                pub fn keygen_internal(
339                    d: &[u8; SEED_LEN],
340                    z: &[u8; SEED_LEN],
341                ) -> (EncapsulationKey, DecapsulationKey) {
342                    let mut pair = (EncapsulationKey::zeroed(), DecapsulationKey::zeroed());
343                    mlkem_keygen_internal_into::<$k, $eta1, EK_LEN, DK_LEN>(
344                        d,
345                        z,
346                        &mut pair.0.0,
347                        pair.1.bytes.expose_secret_mut(),
348                    );
349                    pair.1.initialized = true;
350                    pair
351                }
352
353                /// `ML-KEM.Encaps_internal(ek, m)` (FIPS 203, Algorithm 17).
354                pub fn encaps_internal(
355                    ek: &EncapsulationKey,
356                    m: &[u8; SEED_LEN],
357                ) -> (Ciphertext, SharedSecret) {
358                    let mut pair = (Ciphertext::zeroed(), SharedSecret::new([0u8; 32]));
359                    mlkem_encaps_internal_into::<$k, $eta1, $eta2, $du, $dv, EK_LEN, CT_LEN>(
360                        ek.as_bytes(),
361                        m,
362                        &mut pair.0.0,
363                        &mut pair.1,
364                    );
365                    pair
366                }
367
368                /// `ML-KEM.Decaps_internal(dk, c)` (FIPS 203, Algorithm 18).
369                ///
370                /// # Preconditions
371                /// `dk` MUST be an initialized, validated [`DecapsulationKey`] produced by
372                /// [`DecapsulationKey::from_bytes`], [`Kem::keygen`], `keygen_into`, or
373                /// [`keygen_internal`] — never an uninitialized [`DecapsulationKey::zeroed`]
374                /// placeholder or a previously zeroized key. Unlike [`Kem::decaps`] and
375                /// `decaps_into`, this raw KAT entry point is infallible and relies on the caller
376                /// to uphold this precondition (checked via `debug_assert!` in debug builds).
377                pub fn decaps_internal(
378                    dk: &DecapsulationKey,
379                    ct: &Ciphertext,
380                ) -> SharedSecret {
381                    debug_assert!(
382                        dk.initialized,
383                        "hazmat::decaps_internal requires an initialized DecapsulationKey"
384                    );
385                    let mut ss = SharedSecret::new([0u8; 32]);
386                    mlkem_decaps_internal_into::<$k, $eta1, $eta2, $du, $dv, EK_LEN, DK_LEN, CT_LEN>(
387                        dk.expose_bytes(),
388                        ct.as_bytes(),
389                        &mut ss,
390                    );
391                    ss
392                }
393            }
394        }
395    };
396}
397
398define_ml_kem_variant! {
399    mod_name: ml_kem_512,
400    kem_type: MlKem512,
401    doc_name: "ML-KEM-512",
402    security_cat: "NIST Security Category 1",
403    k: 2,
404    eta1: 3,
405    eta2: 2,
406    du: 10,
407    dv: 4,
408    ek_len: 800,
409    dk_len: 1632,
410    ct_len: 768,
411}
412
413define_ml_kem_variant! {
414    mod_name: ml_kem_768,
415    kem_type: MlKem768,
416    doc_name: "ML-KEM-768",
417    security_cat: "NIST Security Category 3",
418    k: 3,
419    eta1: 2,
420    eta2: 2,
421    du: 10,
422    dv: 4,
423    ek_len: 1184,
424    dk_len: 2400,
425    ct_len: 1088,
426}
427
428define_ml_kem_variant! {
429    mod_name: ml_kem_1024,
430    kem_type: MlKem1024,
431    doc_name: "ML-KEM-1024",
432    security_cat: "NIST Security Category 5",
433    k: 4,
434    eta1: 2,
435    eta2: 2,
436    du: 11,
437    dv: 5,
438    ek_len: 1568,
439    dk_len: 3168,
440    ct_len: 1568,
441}
442
443pub use ml_kem_512::MlKem512;
444pub use ml_kem_768::MlKem768;
445pub use ml_kem_1024::MlKem1024;
446
447#[cfg(test)]
448#[allow(clippy::expect_used)]
449mod rng_failure_tests {
450    use super::*;
451    use quantaegis_core::{CryptoRng, Error, Kem, Result};
452
453    struct FailAfterNCalls {
454        succeed_calls: usize,
455        calls: usize,
456    }
457
458    impl CryptoRng for FailAfterNCalls {
459        fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<()> {
460            self.calls += 1;
461            if self.calls > self.succeed_calls {
462                let half = dest.len() / 2;
463                dest[..half].fill(0xA5);
464                return Err(Error::RngFailure);
465            }
466            dest.fill(0xA5);
467            Ok(())
468        }
469    }
470
471    #[test]
472    fn keygen_propagates_rng_failure_on_second_seed_call() {
473        let mut rng = FailAfterNCalls {
474            succeed_calls: 1,
475            calls: 0,
476        };
477        assert!(matches!(MlKem768::keygen(&mut rng), Err(Error::RngFailure)));
478        assert_eq!(rng.calls, 2);
479    }
480
481    #[test]
482    fn encaps_propagates_rng_failure_after_partial_write() {
483        let mut ok_rng = FailAfterNCalls {
484            succeed_calls: 2,
485            calls: 0,
486        };
487        let (ek, _dk) = MlKem768::keygen(&mut ok_rng).expect("keygen with 2 RNG calls succeeds");
488        let mut fail_rng = FailAfterNCalls {
489            succeed_calls: 0,
490            calls: 0,
491        };
492        assert!(matches!(
493            MlKem768::encaps(&ek, &mut fail_rng),
494            Err(Error::RngFailure)
495        ));
496        assert_eq!(fail_rng.calls, 1);
497    }
498
499    #[test]
500    fn placeholder_and_zeroized_decapsulation_keys_are_rejected() {
501        use quantaegis_core::{SharedSecret, Zeroize};
502
503        let ct = ml_kem_768::Ciphertext::zeroed();
504        let placeholder = ml_kem_768::DecapsulationKey::zeroed();
505        let mut ss = SharedSecret::new([0xAA; 32]);
506
507        assert!(matches!(
508            placeholder.validate(),
509            Err(Error::InvalidDecapsulationKey)
510        ));
511        assert!(matches!(
512            MlKem768::decaps(&placeholder, &ct),
513            Err(Error::InvalidDecapsulationKey)
514        ));
515        assert!(matches!(
516            MlKem768::decaps_into(&placeholder, &ct, &mut ss),
517            Err(Error::InvalidDecapsulationKey)
518        ));
519        assert_eq!(ss.expose_secret(), &[0xAA; 32]);
520
521        let mut ok_rng = FailAfterNCalls {
522            succeed_calls: 2,
523            calls: 0,
524        };
525        let mut ek = ml_kem_768::EncapsulationKey::zeroed();
526        let mut dk = ml_kem_768::DecapsulationKey::zeroed();
527        MlKem768::keygen_into(&mut ok_rng, &mut ek, &mut dk).expect("keygen_into succeeds");
528        dk.validate().expect("generated key passes §7.3 check");
529
530        dk.zeroize();
531        assert!(matches!(dk.validate(), Err(Error::InvalidDecapsulationKey)));
532        assert!(matches!(
533            MlKem768::decaps(&dk, &ct),
534            Err(Error::InvalidDecapsulationKey)
535        ));
536        assert!(matches!(
537            MlKem768::decaps_into(&dk, &ct, &mut ss),
538            Err(Error::InvalidDecapsulationKey)
539        ));
540    }
541}