Skip to main content

kyberlib/
paramsets.rs

1// Copyright © 2026 kyberlib. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! Parameter-pack trait for the three FIPS 203 ML-KEM parameter sets.
5//!
6//! ## Motivation
7//!
8//! The existing reference backend in [`crate::reference`] selects its
9//! parameter set at compile time via Cargo feature gates (`kyber512`,
10//! `kyber768`, `kyber1024`). That means a single build can support
11//! exactly one parameter set: an application that wants to negotiate
12//! between ML-KEM-512 and ML-KEM-1024 at runtime has to either pick
13//! one or link two kyberlib copies.
14//!
15//! This module introduces [`MlKemParams`] — a sealed trait whose
16//! associated constants and associated types pin down everything a
17//! generic FIPS 203 algorithm needs:
18//!
19//! - **Numeric parameters** — module rank `K`, noise widths `ETA1`/`ETA2`,
20//!   compression bit-widths `DU`/`DV`, byte-length constants for keys
21//!   and ciphertexts.
22//! - **Concrete buffer types** — `PublicKeyBytes`, `SecretKeyBytes`,
23//!   `CiphertextBytes` are associated *types* that each impl
24//!   instantiates as the correct `[u8; N]` length for the spec. This
25//!   sidesteps the stable-Rust restriction that prevents
26//!   `[u8; K * Self::POLY_BYTES]` in generic contexts.
27//!
28//! ## Implementation strategy
29//!
30//! Three marker types [`MlKem512`],
31//! [`MlKem768`], [`MlKem1024`]
32//! implement [`MlKemParams`]. Algorithm code that takes
33//! `P: MlKemParams` then has access to `P::K`, `P::ETA1`, etc. as
34//! `const` values and uses `P::PublicKeyBytes` as the concrete byte
35//! array type for keys.
36//!
37//! ## Migration status (v0.0.7)
38//!
39//! This module ships the **trait + impls** so downstream code can be
40//! written against the unified parameter surface, but the algorithm
41//! code in [`crate::reference`] has NOT yet been ported to consume
42//! the trait. The three [`KemCore`] impls remain
43//! Cargo-feature-gated for now. The mechanical port of the reference
44//! backend — `indcpa_keypair`, `indcpa_enc`, `indcpa_dec`,
45//! `crypto_kem_keypair`, `crypto_kem_enc`, `crypto_kem_dec`, plus the
46//! polynomial-arithmetic primitives in `poly.rs`, `polyvec.rs`,
47//! `cbd.rs` — is a multi-day focused PR tracked as **#130b**.
48//!
49//! ## Why the trait lands now
50//!
51//! 1. **Downstream code can begin writing generic algorithms**
52//!    targeting `fn foo<P: MlKemParams>(...)` immediately, with the
53//!    understanding that the body currently has to specialise
54//!    internally.
55//! 2. **It pins down the API contract** for the parameter pack so the
56//!    eventual algorithm refactor has a fixed target to land against.
57//! 3. **Const accessors** — `<MlKem768 as MlKemParams>::PUBLIC_KEY_BYTES`
58//!    is now resolvable at compile time, useful for downstream
59//!    `const fn` size calculations.
60
61use crate::error::KyberLibError;
62#[cfg(doc)]
63use crate::{KemCore, MlKem1024, MlKem512, MlKem768};
64use core::fmt::Debug;
65
66mod sealed {
67    /// Sealed marker — only this crate may add new ML-KEM parameter sets.
68    pub trait Sealed {}
69}
70
71// =============================================================================
72// MlKemParams — the unified parameter-pack trait
73// =============================================================================
74
75/// FIPS 203 parameter pack — every constant and type the algorithm
76/// needs to specialise to one of the three ML-KEM variants.
77///
78/// Implemented by the zero-sized marker types
79/// [`MlKem512`], [`MlKem768`],
80/// [`MlKem1024`]. Sealed: third-party crates cannot
81/// add new implementations.
82///
83/// All associated constants come from FIPS 203 §6 ("Parameter sets")
84/// and the IETF LAMPS draft for the OIDs / algorithm identifiers.
85///
86/// # Example
87///
88/// ```
89/// use kyberlib::{MlKem768, MlKemParams};
90///
91/// const PK_LEN: usize = <MlKem768 as MlKemParams>::PUBLIC_KEY_BYTES;
92/// const CT_LEN: usize = <MlKem768 as MlKemParams>::CIPHERTEXT_BYTES;
93/// assert_eq!(PK_LEN, 1184);
94/// assert_eq!(CT_LEN, 1088);
95/// ```
96pub trait MlKemParams:
97    sealed::Sealed + Sized + Copy + Debug + 'static
98{
99    // --- Numeric parameters (FIPS 203 §6) ---
100
101    /// Module rank `k`. 2 / 3 / 4 for ML-KEM-512 / 768 / 1024.
102    const K: usize;
103
104    /// Centred-binomial width η₁ for the secret-key sampling.
105    /// 3 for ML-KEM-512, 2 for ML-KEM-768 and ML-KEM-1024.
106    const ETA1: usize;
107
108    /// Centred-binomial width η₂ for the ciphertext-noise sampling.
109    /// Always 2.
110    const ETA2: usize = 2;
111
112    /// Polynomial degree N. Always 256.
113    const N: usize = 256;
114
115    /// Modulus q. Always 3329.
116    const Q: usize = 3329;
117
118    /// Ciphertext compression bit-width for the u half. 10 for
119    /// ML-KEM-512/768, 11 for ML-KEM-1024.
120    const DU: usize;
121
122    /// Ciphertext compression bit-width for the v half. 4 for
123    /// ML-KEM-512/768, 5 for ML-KEM-1024.
124    const DV: usize;
125
126    // --- Byte-length constants (computed from the spec) ---
127
128    /// Shared-secret length in bytes. Always 32.
129    const SHARED_SECRET_BYTES: usize = 32;
130
131    /// Symmetric primitive byte length (seeds, hashes). Always 32.
132    const SYM_BYTES: usize = 32;
133
134    /// Public encapsulation-key byte length.
135    /// `K * 384 + 32` per FIPS 203 §6.
136    const PUBLIC_KEY_BYTES: usize;
137
138    /// Secret decapsulation-key byte length.
139    /// `24*K*N/8 + 96` per FIPS 203 §6.1.
140    const SECRET_KEY_BYTES: usize;
141
142    /// Ciphertext byte length.
143    /// `32*(K*DU + DV)` per FIPS 203 §6.
144    const CIPHERTEXT_BYTES: usize;
145
146    // --- Stable identifiers (IETF LAMPS) ---
147
148    /// Stable algorithm identifier — `"ML-KEM-512"`, `"ML-KEM-768"`,
149    /// or `"ML-KEM-1024"`.
150    const ALGORITHM_ID: &'static str;
151
152    /// Object identifier — `2.16.840.1.101.3.4.4.{1,2,3}`.
153    const OID: &'static str;
154
155    // --- Associated buffer types ---
156
157    /// Concrete encapsulation-key byte buffer type. Each impl
158    /// instantiates as `[u8; PUBLIC_KEY_BYTES]`.
159    type PublicKeyBytes: AsRef<[u8]> + AsMut<[u8]> + Copy + Debug;
160
161    /// Concrete decapsulation-key byte buffer type. Each impl
162    /// instantiates as `[u8; SECRET_KEY_BYTES]`. Zeroized on drop
163    /// at the wrapper level (see [`crate::ml_kem`]).
164    type SecretKeyBytes: AsRef<[u8]> + AsMut<[u8]> + Copy + Debug;
165
166    /// Concrete ciphertext byte buffer type. Each impl instantiates
167    /// as `[u8; CIPHERTEXT_BYTES]`.
168    type CiphertextBytes: AsRef<[u8]> + AsMut<[u8]> + Copy + Debug;
169
170    /// Create a new zeroed public-key buffer. Helper so generic code
171    /// can construct buffers without naming the concrete array size.
172    #[must_use]
173    fn zero_public_key() -> Self::PublicKeyBytes;
174
175    /// Create a new zeroed secret-key buffer.
176    #[must_use]
177    fn zero_secret_key() -> Self::SecretKeyBytes;
178
179    /// Create a new zeroed ciphertext buffer.
180    #[must_use]
181    fn zero_ciphertext() -> Self::CiphertextBytes;
182}
183
184// =============================================================================
185// Marker types + MlKemParams impls
186// =============================================================================
187//
188// These markers are the same types exposed in `crate::ml_kem` as
189// `MlKem512` / `MlKem768` / `MlKem1024`. We re-implement the sealed
190// marker here and add the MlKemParams impl. The KemCore impl that
191// wires through to the actual algorithm code stays in `ml_kem.rs`.
192
193impl sealed::Sealed for crate::MlKem512 {}
194impl sealed::Sealed for crate::MlKem768 {}
195impl sealed::Sealed for crate::MlKem1024 {}
196
197impl MlKemParams for crate::MlKem512 {
198    const K: usize = 2;
199    const ETA1: usize = 3;
200    const DU: usize = 10;
201    const DV: usize = 4;
202    const PUBLIC_KEY_BYTES: usize = 800;
203    const SECRET_KEY_BYTES: usize = 1632;
204    const CIPHERTEXT_BYTES: usize = 768;
205    const ALGORITHM_ID: &'static str = "ML-KEM-512";
206    const OID: &'static str = "2.16.840.1.101.3.4.4.1";
207
208    type PublicKeyBytes = [u8; 800];
209    type SecretKeyBytes = [u8; 1632];
210    type CiphertextBytes = [u8; 768];
211
212    fn zero_public_key() -> Self::PublicKeyBytes {
213        [0u8; 800]
214    }
215    fn zero_secret_key() -> Self::SecretKeyBytes {
216        [0u8; 1632]
217    }
218    fn zero_ciphertext() -> Self::CiphertextBytes {
219        [0u8; 768]
220    }
221}
222
223impl MlKemParams for crate::MlKem768 {
224    const K: usize = 3;
225    const ETA1: usize = 2;
226    const DU: usize = 10;
227    const DV: usize = 4;
228    const PUBLIC_KEY_BYTES: usize = 1184;
229    const SECRET_KEY_BYTES: usize = 2400;
230    const CIPHERTEXT_BYTES: usize = 1088;
231    const ALGORITHM_ID: &'static str = "ML-KEM-768";
232    const OID: &'static str = "2.16.840.1.101.3.4.4.2";
233
234    type PublicKeyBytes = [u8; 1184];
235    type SecretKeyBytes = [u8; 2400];
236    type CiphertextBytes = [u8; 1088];
237
238    fn zero_public_key() -> Self::PublicKeyBytes {
239        [0u8; 1184]
240    }
241    fn zero_secret_key() -> Self::SecretKeyBytes {
242        [0u8; 2400]
243    }
244    fn zero_ciphertext() -> Self::CiphertextBytes {
245        [0u8; 1088]
246    }
247}
248
249impl MlKemParams for crate::MlKem1024 {
250    const K: usize = 4;
251    const ETA1: usize = 2;
252    const DU: usize = 11;
253    const DV: usize = 5;
254    const PUBLIC_KEY_BYTES: usize = 1568;
255    const SECRET_KEY_BYTES: usize = 3168;
256    const CIPHERTEXT_BYTES: usize = 1568;
257    const ALGORITHM_ID: &'static str = "ML-KEM-1024";
258    const OID: &'static str = "2.16.840.1.101.3.4.4.3";
259
260    type PublicKeyBytes = [u8; 1568];
261    type SecretKeyBytes = [u8; 3168];
262    type CiphertextBytes = [u8; 1568];
263
264    fn zero_public_key() -> Self::PublicKeyBytes {
265        [0u8; 1568]
266    }
267    fn zero_secret_key() -> Self::SecretKeyBytes {
268        [0u8; 3168]
269    }
270    fn zero_ciphertext() -> Self::CiphertextBytes {
271        [0u8; 1568]
272    }
273}
274
275// =============================================================================
276// Generic-over-Params convenience surface
277// =============================================================================
278
279/// Length of the public encapsulation key for the parameter set `P`,
280/// as a `const fn` so it can be used in array dimensions inside
281/// `const` contexts.
282///
283/// # Example
284///
285/// ```
286/// use kyberlib::{MlKem768, MlKemParams, paramsets::public_key_len};
287///
288/// const PK_LEN: usize = public_key_len::<MlKem768>();
289/// assert_eq!(PK_LEN, MlKem768::PUBLIC_KEY_BYTES);
290/// ```
291#[must_use]
292pub const fn public_key_len<P: MlKemParams>() -> usize {
293    P::PUBLIC_KEY_BYTES
294}
295
296/// Length of the decapsulation secret key for parameter set `P`.
297#[must_use]
298pub const fn secret_key_len<P: MlKemParams>() -> usize {
299    P::SECRET_KEY_BYTES
300}
301
302/// Length of the ciphertext for parameter set `P`.
303#[must_use]
304pub const fn ciphertext_len<P: MlKemParams>() -> usize {
305    P::CIPHERTEXT_BYTES
306}
307
308/// Length of the shared secret. Always 32 bytes per FIPS 203 §6, but
309/// exposed via `P` to keep call sites uniform.
310#[must_use]
311pub const fn shared_secret_len<P: MlKemParams>() -> usize {
312    P::SHARED_SECRET_BYTES
313}
314
315// =============================================================================
316// Generic length-validated byte→typed-buffer conversion
317// =============================================================================
318
319/// Validate a borrowed byte slice and copy it into the parameter-set's
320/// concrete `PublicKeyBytes` buffer.
321///
322/// # Errors
323///
324/// [`KyberLibError::InvalidLength`] if `bytes.len() != P::PUBLIC_KEY_BYTES`.
325///
326/// # Example
327///
328/// ```
329/// use kyberlib::{MlKem768, paramsets::public_key_from_slice};
330///
331/// let pk_bytes = [0u8; 1184];
332/// let buf = public_key_from_slice::<MlKem768>(&pk_bytes).unwrap();
333/// assert_eq!(buf.len(), 1184);
334/// ```
335pub fn public_key_from_slice<P: MlKemParams>(
336    bytes: &[u8],
337) -> Result<P::PublicKeyBytes, KyberLibError> {
338    if bytes.len() != P::PUBLIC_KEY_BYTES {
339        return Err(KyberLibError::InvalidLength);
340    }
341    let mut buf = P::zero_public_key();
342    buf.as_mut().copy_from_slice(bytes);
343    Ok(buf)
344}
345
346/// Validate a borrowed byte slice and copy it into the parameter-set's
347/// concrete `SecretKeyBytes` buffer.
348///
349/// # Errors
350///
351/// [`KyberLibError::InvalidLength`] if
352/// `bytes.len() != P::SECRET_KEY_BYTES`.
353pub fn secret_key_from_slice<P: MlKemParams>(
354    bytes: &[u8],
355) -> Result<P::SecretKeyBytes, KyberLibError> {
356    if bytes.len() != P::SECRET_KEY_BYTES {
357        return Err(KyberLibError::InvalidLength);
358    }
359    let mut buf = P::zero_secret_key();
360    buf.as_mut().copy_from_slice(bytes);
361    Ok(buf)
362}
363
364/// Validate a borrowed byte slice and copy it into the parameter-set's
365/// concrete `CiphertextBytes` buffer.
366///
367/// # Errors
368///
369/// [`KyberLibError::InvalidLength`] if
370/// `bytes.len() != P::CIPHERTEXT_BYTES`.
371pub fn ciphertext_from_slice<P: MlKemParams>(
372    bytes: &[u8],
373) -> Result<P::CiphertextBytes, KyberLibError> {
374    if bytes.len() != P::CIPHERTEXT_BYTES {
375        return Err(KyberLibError::InvalidLength);
376    }
377    let mut buf = P::zero_ciphertext();
378    buf.as_mut().copy_from_slice(bytes);
379    Ok(buf)
380}
381
382// =============================================================================
383// Tests
384// =============================================================================
385
386#[cfg(test)]
387mod tests {
388    use super::*;
389    use crate::{MlKem1024, MlKem512, MlKem768};
390
391    #[test]
392    fn ml_kem_512_params_match_spec() {
393        // FIPS 203 §6 ML-KEM-512 numerical parameters.
394        assert_eq!(MlKem512::K, 2);
395        assert_eq!(MlKem512::ETA1, 3);
396        assert_eq!(MlKem512::ETA2, 2);
397        assert_eq!(MlKem512::DU, 10);
398        assert_eq!(MlKem512::DV, 4);
399        assert_eq!(MlKem512::PUBLIC_KEY_BYTES, 800);
400        assert_eq!(MlKem512::SECRET_KEY_BYTES, 1632);
401        assert_eq!(MlKem512::CIPHERTEXT_BYTES, 768);
402        assert_eq!(MlKem512::SHARED_SECRET_BYTES, 32);
403    }
404
405    #[test]
406    fn ml_kem_768_params_match_spec() {
407        assert_eq!(MlKem768::K, 3);
408        assert_eq!(MlKem768::ETA1, 2);
409        assert_eq!(MlKem768::ETA2, 2);
410        assert_eq!(MlKem768::DU, 10);
411        assert_eq!(MlKem768::DV, 4);
412        assert_eq!(MlKem768::PUBLIC_KEY_BYTES, 1184);
413        assert_eq!(MlKem768::SECRET_KEY_BYTES, 2400);
414        assert_eq!(MlKem768::CIPHERTEXT_BYTES, 1088);
415    }
416
417    #[test]
418    fn ml_kem_1024_params_match_spec() {
419        assert_eq!(MlKem1024::K, 4);
420        assert_eq!(MlKem1024::ETA1, 2);
421        assert_eq!(MlKem1024::ETA2, 2);
422        assert_eq!(MlKem1024::DU, 11);
423        assert_eq!(MlKem1024::DV, 5);
424        assert_eq!(MlKem1024::PUBLIC_KEY_BYTES, 1568);
425        assert_eq!(MlKem1024::SECRET_KEY_BYTES, 3168);
426        assert_eq!(MlKem1024::CIPHERTEXT_BYTES, 1568);
427    }
428
429    #[test]
430    fn public_key_size_formula() {
431        // FIPS 203: PK_BYTES = 32 * K * N/8 + 32 = K * 384 + 32.
432        assert_eq!(
433            <MlKem512 as MlKemParams>::PUBLIC_KEY_BYTES,
434            MlKem512::K * 384 + 32
435        );
436        assert_eq!(
437            <MlKem768 as MlKemParams>::PUBLIC_KEY_BYTES,
438            MlKem768::K * 384 + 32
439        );
440        assert_eq!(
441            <MlKem1024 as MlKemParams>::PUBLIC_KEY_BYTES,
442            MlKem1024::K * 384 + 32
443        );
444    }
445
446    #[test]
447    fn ciphertext_size_formula() {
448        // FIPS 203: CT_BYTES = 32 * (K * DU + DV).
449        // ML-KEM-512:  32*(2*10 + 4)  =  768. ✓
450        // ML-KEM-768:  32*(3*10 + 4)  = 1088. ✓
451        // ML-KEM-1024: 32*(4*11 + 5)  = 1568. ✓
452        assert_eq!(
453            <MlKem512 as MlKemParams>::CIPHERTEXT_BYTES,
454            32 * (MlKem512::K * MlKem512::DU + MlKem512::DV)
455        );
456        assert_eq!(
457            <MlKem768 as MlKemParams>::CIPHERTEXT_BYTES,
458            32 * (MlKem768::K * MlKem768::DU + MlKem768::DV)
459        );
460        assert_eq!(
461            <MlKem1024 as MlKemParams>::CIPHERTEXT_BYTES,
462            32 * (MlKem1024::K * MlKem1024::DU + MlKem1024::DV)
463        );
464    }
465
466    #[test]
467    fn const_len_helpers() {
468        assert_eq!(public_key_len::<MlKem512>(), 800);
469        assert_eq!(public_key_len::<MlKem768>(), 1184);
470        assert_eq!(public_key_len::<MlKem1024>(), 1568);
471
472        assert_eq!(secret_key_len::<MlKem512>(), 1632);
473        assert_eq!(secret_key_len::<MlKem768>(), 2400);
474        assert_eq!(secret_key_len::<MlKem1024>(), 3168);
475
476        assert_eq!(ciphertext_len::<MlKem512>(), 768);
477        assert_eq!(ciphertext_len::<MlKem768>(), 1088);
478        assert_eq!(ciphertext_len::<MlKem1024>(), 1568);
479
480        assert_eq!(shared_secret_len::<MlKem512>(), 32);
481        assert_eq!(shared_secret_len::<MlKem768>(), 32);
482        assert_eq!(shared_secret_len::<MlKem1024>(), 32);
483    }
484
485    #[test]
486    fn from_slice_round_trip() {
487        let pk = [0xABu8; 1184];
488        let buf = public_key_from_slice::<MlKem768>(&pk).unwrap();
489        assert_eq!(buf.as_ref(), &pk);
490
491        // Wrong length → InvalidLength.
492        let bad = [0u8; 100];
493        let err = public_key_from_slice::<MlKem768>(&bad);
494        assert!(matches!(err, Err(KyberLibError::InvalidLength)));
495
496        // ML-KEM-512 with 768's length → InvalidLength (size mismatch).
497        let pk_768 = [0xCDu8; 1184];
498        let err = public_key_from_slice::<MlKem512>(&pk_768);
499        assert!(matches!(err, Err(KyberLibError::InvalidLength)));
500    }
501
502    #[test]
503    fn algorithm_id_and_oid() {
504        assert_eq!(
505            <MlKem512 as MlKemParams>::ALGORITHM_ID,
506            "ML-KEM-512"
507        );
508        assert_eq!(
509            <MlKem768 as MlKemParams>::ALGORITHM_ID,
510            "ML-KEM-768"
511        );
512        assert_eq!(
513            <MlKem1024 as MlKemParams>::ALGORITHM_ID,
514            "ML-KEM-1024"
515        );
516
517        assert_eq!(
518            <MlKem512 as MlKemParams>::OID,
519            "2.16.840.1.101.3.4.4.1"
520        );
521        assert_eq!(
522            <MlKem768 as MlKemParams>::OID,
523            "2.16.840.1.101.3.4.4.2"
524        );
525        assert_eq!(
526            <MlKem1024 as MlKemParams>::OID,
527            "2.16.840.1.101.3.4.4.3"
528        );
529    }
530
531    #[test]
532    fn zero_constructors_correct_size() {
533        let pk_512 = MlKem512::zero_public_key();
534        let pk_768 = MlKem768::zero_public_key();
535        let pk_1024 = MlKem1024::zero_public_key();
536        assert_eq!(pk_512.len(), 800);
537        assert_eq!(pk_768.len(), 1184);
538        assert_eq!(pk_1024.len(), 1568);
539        assert!(pk_768.iter().all(|&b| b == 0));
540    }
541
542    /// Demonstrates the intended generic-algorithm pattern: a function
543    /// generic over `P: MlKemParams` accessing both compile-time
544    /// constants and the associated buffer type.
545    fn pk_size_string<P: MlKemParams>() -> (usize, &'static str) {
546        (P::PUBLIC_KEY_BYTES, P::ALGORITHM_ID)
547    }
548
549    #[test]
550    fn generic_function_dispatches_correctly() {
551        assert_eq!(pk_size_string::<MlKem512>(), (800, "ML-KEM-512"));
552        assert_eq!(pk_size_string::<MlKem768>(), (1184, "ML-KEM-768"));
553        assert_eq!(
554            pk_size_string::<MlKem1024>(),
555            (1568, "ML-KEM-1024")
556        );
557    }
558}