SPB Git

Repository Public Apache-2.0

mlkem.rs 16.7 KB 522 lines rust

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SPB Quantum Crypto7// File             : crates/spb-pqc-core/src/kem/mlkem.rs8// Module           : Crates9// Repository       : https://git.spboucher.ai/spb-quantum-crypto10// Project Website  : https://pqce.spboucher.ai11// Created          : 2026-12-0312// Last Modified    : 2026-12-0313//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : Apache-2.033//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041//! ML-KEM (FIPS 203, August 13 2024): K-PKE and the key-encapsulation mechanism.42//!43//! | FIPS 203                          | Here                          |44//! |-----------------------------------|-------------------------------|45//! | Table 2 parameter sets            | [`Params`], `MLKEM_512/768/1024` |46//! | Alg. 13 `K-PKE.KeyGen`            | `pke_keygen`                  |47//! | Alg. 14 `K-PKE.Encrypt`           | `pke_encrypt`                 |48//! | Alg. 15 `K-PKE.Decrypt`           | `pke_decrypt`                 |49//! | Alg. 16 `ML-KEM.KeyGen_internal`  | [`keygen_internal`]           |50//! | Alg. 17 `ML-KEM.Encaps_internal`  | [`encaps_internal`]           |51//! | Alg. 18 `ML-KEM.Decaps_internal`  | [`decaps_internal`]           |52//! | §7.2 encapsulation-key check      | [`check_encapsulation_key`]   |53//! | §7.3 decapsulation-key check      | [`check_decapsulation_key`]   |54//! | §4.1 `H`, `J`, `G`, `PRF`, `XOF`  | SHA3-256, SHAKE256, SHA3-512, SHAKE256, SHAKE128 |55//!56//! K-PKE is private to this module: it is not IND-CCA secure on its own and is57//! never exposed as an application-level encryption scheme.58//!59//! Constant-time notes: decapsulation re-encrypts and selects between the real60//! key and the implicit-rejection key with a byte mask; no branch depends on61//! whether the ciphertext was valid. The public matrix expansion is variable62//! time on public data.6364use crate::ct::{self, wipe};65use crate::error::{Error, Result};66use crate::hash::keccak::{sha3_256, shake256, Sha3};67use crate::math::mlkem::{68    byte_decode, byte_encode, multiply_ntts, ntt, ntt_inv, poly_add_assign, poly_compress,69    poly_decompress, poly_sub_assign, sample_ntt, sample_poly_cbd, Poly, N,70};7172/// Shared-secret length in bytes (all parameter sets).73pub const SHARED_SECRET_LEN: usize = 32;74const MAX_K: usize = 4;7576/// An ML-KEM parameter set (FIPS 203 Table 2).77#[derive(Clone, Copy, Debug, PartialEq, Eq)]78pub struct Params {79    /// Module rank.80    pub k: usize,81    /// CBD parameter for the secret and first noise.82    pub eta1: usize,83    /// CBD parameter for the encryption noise.84    pub eta2: usize,85    /// Compression bits for `u`.86    pub du: u32,87    /// Compression bits for `v`.88    pub dv: u32,89}9091/// ML-KEM-512.92pub const MLKEM_512: Params = Params {93    k: 2,94    eta1: 3,95    eta2: 2,96    du: 10,97    dv: 4,98};99/// ML-KEM-768.100pub const MLKEM_768: Params = Params {101    k: 3,102    eta1: 2,103    eta2: 2,104    du: 10,105    dv: 4,106};107/// ML-KEM-1024.108pub const MLKEM_1024: Params = Params {109    k: 4,110    eta1: 2,111    eta2: 2,112    du: 11,113    dv: 5,114};115116impl Params {117    /// Encapsulation-key length: `384k + 32`.118    pub const fn ek_len(&self) -> usize {119        384 * self.k + 32120    }121    /// Decapsulation-key length: `768k + 96`.122    pub const fn dk_len(&self) -> usize {123        768 * self.k + 96124    }125    /// Ciphertext length: `32(d_u·k + d_v)`.126    pub const fn ct_len(&self) -> usize {127        32 * (self.du as usize * self.k + self.dv as usize)128    }129}130131/// A vector of `k ≤ 4` polynomials; unused slots stay zero. Wiped on drop via `Poly`.132struct PolyVec {133    p: [Poly; MAX_K],134}135136impl PolyVec {137    fn zero() -> Self {138        PolyVec {139            p: [Poly::zero(), Poly::zero(), Poly::zero(), Poly::zero()],140        }141    }142}143144/// `G(c) = SHA3-512(c)` split into two 32-byte halves (FIPS 203 eq. 4.5).145fn g(parts: &[&[u8]]) -> ([u8; 32], [u8; 32]) {146    let mut h = Sha3::new_512();147    for p in parts {148        h.update(p);149    }150    let mut out = [0u8; 64];151    h.finalize_into(&mut out);152    let (mut a, mut b) = ([0u8; 32], [0u8; 32]);153    a.copy_from_slice(&out[..32]);154    b.copy_from_slice(&out[32..]);155    wipe(&mut out);156    (a, b)157}158159/// `PRF_η(s, b) = SHAKE256(s ‖ b, 8·64·η)` then `SamplePolyCBD_η`.160fn sample_noise(sigma: &[u8; 32], nonce: u8, eta: usize) -> Poly {161    let mut buf = [0u8; 64 * 3];162    let buf = &mut buf[..64 * eta];163    shake256(&[sigma, &[nonce]], buf);164    let p = sample_poly_cbd(buf, eta);165    wipe(buf);166    p167}168169/// Expands the public matrix  (or its transpose) from ρ:170/// `Â[i][j] = SampleNTT(ρ ‖ j ‖ i)` (FIPS 203 Alg. 13 lines 3–7).171fn expand_matrix(rho: &[u8], k: usize, transpose: bool) -> [[Poly; MAX_K]; MAX_K] {172    let mut a: [[Poly; MAX_K]; MAX_K] =173        core::array::from_fn(|_| core::array::from_fn(|_| Poly::zero()));174    let mut seed = [0u8; 34];175    seed[..32].copy_from_slice(rho);176    for i in 0..k {177        for j in 0..k {178            seed[32] = j as u8;179            seed[33] = i as u8;180            let p = sample_ntt(&seed);181            if transpose {182                a[j][i] = p;183            } else {184                a[i][j] = p;185            }186        }187    }188    a189}190191/// Row-times-vector in the NTT domain: `Σ_j row[j] ∘ v[j]`.192fn dot(row: &[Poly; MAX_K], v: &PolyVec, k: usize) -> Poly {193    let mut acc = Poly::zero();194    for j in 0..k {195        let t = multiply_ntts(&row[j], &v.p[j]);196        poly_add_assign(&mut acc, &t);197    }198    acc199}200201/// `K-PKE.KeyGen(d)` (Alg. 13). Writes `ek_pke` (384k+32) and `dk_pke` (384k).202fn pke_keygen(p: &Params, d: &[u8; 32], ek: &mut [u8], dk_pke: &mut [u8]) {203    let k = p.k;204    let (rho, mut sigma) = g(&[d, &[k as u8]]);205    let a = expand_matrix(&rho, k, false);206    let mut nonce = 0u8;207    let mut s = PolyVec::zero();208    let mut e = PolyVec::zero();209    for i in 0..k {210        s.p[i] = sample_noise(&sigma, nonce, p.eta1);211        nonce += 1;212    }213    for i in 0..k {214        e.p[i] = sample_noise(&sigma, nonce, p.eta1);215        nonce += 1;216    }217    for i in 0..k {218        ntt(&mut s.p[i]);219        ntt(&mut e.p[i]);220    }221    for i in 0..k {222        let mut t = dot(&a[i], &s, k);223        poly_add_assign(&mut t, &e.p[i]);224        byte_encode(&t, 12, &mut ek[384 * i..384 * (i + 1)]);225    }226    ek[384 * k..].copy_from_slice(&rho);227    for i in 0..k {228        byte_encode(&s.p[i], 12, &mut dk_pke[384 * i..384 * (i + 1)]);229    }230    wipe(&mut sigma);231}232233/// `K-PKE.Encrypt(ek, m, r)` (Alg. 14). `ek` must already have passed the modulus check.234fn pke_encrypt(p: &Params, ek: &[u8], m: &[u8; 32], r: &[u8; 32], c: &mut [u8]) {235    let k = p.k;236    let mut t_hat = PolyVec::zero();237    for i in 0..k {238        t_hat.p[i] = byte_decode(&ek[384 * i..384 * (i + 1)], 12);239    }240    let rho = &ek[384 * k..];241    let at = expand_matrix(rho, k, true);242    let mut nonce = 0u8;243    let mut y = PolyVec::zero();244    let mut e1 = PolyVec::zero();245    for i in 0..k {246        y.p[i] = sample_noise(r, nonce, p.eta1);247        nonce += 1;248    }249    for i in 0..k {250        e1.p[i] = sample_noise(r, nonce, p.eta2);251        nonce += 1;252    }253    let e2 = sample_noise(r, nonce, p.eta2);254    for i in 0..k {255        ntt(&mut y.p[i]);256    }257    // u = NTT^-1(Â^T ∘ ŷ) + e1, compressed and encoded as c1258    let du_bytes = 32 * p.du as usize;259    for i in 0..k {260        let mut u = dot(&at[i], &y, k);261        ntt_inv(&mut u);262        poly_add_assign(&mut u, &e1.p[i]);263        poly_compress(&mut u, p.du);264        byte_encode(&u, p.du, &mut c[du_bytes * i..du_bytes * (i + 1)]);265    }266    // v = NTT^-1(t̂^T ∘ ŷ) + e2 + Decompress_1(ByteDecode_1(m)), encoded as c2267    let mut mu = byte_decode(m, 1);268    poly_decompress(&mut mu, 1);269    let mut v = dot(&t_hat.p, &y, k);270    ntt_inv(&mut v);271    poly_add_assign(&mut v, &e2);272    poly_add_assign(&mut v, &mu);273    poly_compress(&mut v, p.dv);274    byte_encode(&v, p.dv, &mut c[du_bytes * k..]);275}276277/// `K-PKE.Decrypt(dk_pke, c)` (Alg. 15).278fn pke_decrypt(p: &Params, dk_pke: &[u8], c: &[u8]) -> [u8; 32] {279    let k = p.k;280    let du_bytes = 32 * p.du as usize;281    let mut u = PolyVec::zero();282    for i in 0..k {283        u.p[i] = byte_decode(&c[du_bytes * i..du_bytes * (i + 1)], p.du);284        poly_decompress(&mut u.p[i], p.du);285        ntt(&mut u.p[i]);286    }287    let mut v = byte_decode(&c[du_bytes * k..], p.dv);288    poly_decompress(&mut v, p.dv);289    let mut s = PolyVec::zero();290    for i in 0..k {291        s.p[i] = byte_decode(&dk_pke[384 * i..384 * (i + 1)], 12);292    }293    let mut su = dot(&s.p, &u, k);294    ntt_inv(&mut su);295    poly_sub_assign(&mut v, &su); // w = v' − NTT^-1(ŝ^T ∘ NTT(u'))296    poly_compress(&mut v, 1);297    let mut m = [0u8; 32];298    byte_encode(&v, 1, &mut m);299    m300}301302/// `ML-KEM.KeyGen_internal(d, z)` (Alg. 16). `ek` and `dk` must have the exact303/// parameter-set lengths.304pub(crate) fn keygen_internal(305    p: &Params,306    d: &[u8; 32],307    z: &[u8; 32],308    ek: &mut [u8],309    dk: &mut [u8],310) -> Result<()> {311    if ek.len() != p.ek_len() || dk.len() != p.dk_len() {312        return Err(Error::InvalidLength);313    }314    let k = p.k;315    let (dk_pke, rest) = dk.split_at_mut(384 * k);316    pke_keygen(p, d, ek, dk_pke);317    let (dk_ek, rest) = rest.split_at_mut(384 * k + 32);318    dk_ek.copy_from_slice(ek);319    rest[..32].copy_from_slice(&sha3_256(ek));320    rest[32..].copy_from_slice(z);321    Ok(())322}323324/// Encapsulation-key check of FIPS 203 §7.2: type check (length) and modulus325/// check (`ByteEncode_12(ByteDecode_12(ek)) = ek` on the polynomial part).326/// The key is public: this runs in variable time.327pub fn check_encapsulation_key(p: &Params, ek: &[u8]) -> Result<()> {328    if ek.len() != p.ek_len() {329        return Err(Error::InvalidLength);330    }331    // Every 12-bit field must already be < q.332    for chunk in ek[..384 * p.k].chunks_exact(3) {333        let d1 = chunk[0] as u16 | ((chunk[1] as u16 & 0x0F) << 8);334        let d2 = (chunk[1] as u16 >> 4) | ((chunk[2] as u16) << 4);335        if d1 >= crate::math::mlkem::Q || d2 >= crate::math::mlkem::Q {336            return Err(Error::InvalidPublicKey);337        }338    }339    Ok(())340}341342/// Decapsulation-key check of FIPS 203 §7.3: type check (length) and hash check343/// (`H(ek) = h` for the `ek` and `h` embedded in `dk`).344pub fn check_decapsulation_key(p: &Params, dk: &[u8]) -> Result<()> {345    if dk.len() != p.dk_len() {346        return Err(Error::InvalidLength);347    }348    let k = p.k;349    let ek = &dk[384 * k..768 * k + 32];350    let h = &dk[768 * k + 32..768 * k + 64];351    let mut expect = sha3_256(ek);352    let ok = ct::eq(&expect, h);353    wipe(&mut expect);354    if ok {355        Ok(())356    } else {357        Err(Error::InvalidPrivateKey)358    }359}360361/// `ML-KEM.Encaps_internal(ek, m)` (Alg. 17). The caller must have run362/// [`check_encapsulation_key`]. Writes the ciphertext and returns the shared secret.363pub(crate) fn encaps_internal(364    p: &Params,365    ek: &[u8],366    m: &[u8; 32],367    c: &mut [u8],368) -> Result<[u8; SHARED_SECRET_LEN]> {369    if ek.len() != p.ek_len() || c.len() != p.ct_len() {370        return Err(Error::InvalidLength);371    }372    let h = sha3_256(ek);373    let (key, mut r) = g(&[m, &h]);374    pke_encrypt(p, ek, m, &r, c);375    wipe(&mut r);376    Ok(key)377}378379/// `ML-KEM.Decaps_internal(dk, c)` (Alg. 18) with implicit rejection. The380/// caller must have run [`check_decapsulation_key`]; the ciphertext type check381/// (length) is done here.382pub(crate) fn decaps_internal(p: &Params, dk: &[u8], c: &[u8]) -> Result<[u8; SHARED_SECRET_LEN]> {383    if dk.len() != p.dk_len() {384        return Err(Error::InvalidLength);385    }386    if c.len() != p.ct_len() {387        return Err(Error::InvalidCiphertext);388    }389    let k = p.k;390    let dk_pke = &dk[..384 * k];391    let ek = &dk[384 * k..768 * k + 32];392    let h = &dk[768 * k + 32..768 * k + 64];393    let z = &dk[768 * k + 64..];394395    let mut m_prime = pke_decrypt(p, dk_pke, c);396    let (mut k_prime, mut r_prime) = g(&[&m_prime, h]);397    let mut k_bar = [0u8; 32];398    shake256(&[z, c], &mut k_bar); // J(z ‖ c)399400    let mut c_prime = [0u8; 1568]; // largest ciphertext (ML-KEM-1024)401    let c_prime = &mut c_prime[..p.ct_len()];402    pke_encrypt(p, ek, &m_prime, &r_prime, c_prime);403404    let same = ct::eq_mask(c, c_prime);405    let mut out = [0u8; 32];406    ct::select(&mut out, &k_prime, &k_bar, same);407408    wipe(&mut m_prime);409    wipe(&mut k_prime);410    wipe(&mut r_prime);411    wipe(&mut k_bar);412    wipe(c_prime);413    Ok(out)414}415416const _: () = assert!(N == 256);417418#[cfg(test)]419mod tests {420    use super::*;421422    #[test]423    fn sizes_match_fips203_table_3() {424        assert_eq!(425            (MLKEM_512.ek_len(), MLKEM_512.dk_len(), MLKEM_512.ct_len()),426            (800, 1632, 768)427        );428        assert_eq!(429            (MLKEM_768.ek_len(), MLKEM_768.dk_len(), MLKEM_768.ct_len()),430            (1184, 2400, 1088)431        );432        assert_eq!(433            (434                MLKEM_1024.ek_len(),435                MLKEM_1024.dk_len(),436                MLKEM_1024.ct_len()437            ),438            (1568, 3168, 1568)439        );440    }441442    #[test]443    fn round_trip_and_implicit_rejection() {444        for p in [MLKEM_512, MLKEM_768, MLKEM_1024] {445            let (d, z, m) = ([1u8; 32], [2u8; 32], [3u8; 32]);446            let mut ek = vec![0u8; p.ek_len()];447            let mut dk = vec![0u8; p.dk_len()];448            keygen_internal(&p, &d, &z, &mut ek, &mut dk).unwrap();449            check_encapsulation_key(&p, &ek).unwrap();450            check_decapsulation_key(&p, &dk).unwrap();451            let mut c = vec![0u8; p.ct_len()];452            let k1 = encaps_internal(&p, &ek, &m, &mut c).unwrap();453            let k2 = decaps_internal(&p, &dk, &c).unwrap();454            assert_eq!(k1, k2);455456            // Any single-bit modification yields a different, deterministic key.457            for pos in [0usize, c.len() / 2, c.len() - 1] {458                let mut bad = c.clone();459                bad[pos] ^= 1;460                let r1 = decaps_internal(&p, &dk, &bad).unwrap();461                let r2 = decaps_internal(&p, &dk, &bad).unwrap();462                assert_ne!(r1, k1);463                assert_eq!(r1, r2);464                // and it is exactly J(z ‖ c)465                let mut j = [0u8; 32];466                shake256(&[&z, &bad], &mut j);467                assert_eq!(r1, j);468            }469470            assert_eq!(471                decaps_internal(&p, &dk, &c[1..]),472                Err(Error::InvalidCiphertext)473            );474        }475    }476477    #[test]478    fn key_checks_reject_malformed_keys() {479        let p = MLKEM_768;480        let mut ek = vec![0u8; p.ek_len()];481        let mut dk = vec![0u8; p.dk_len()];482        keygen_internal(&p, &[9; 32], &[8; 32], &mut ek, &mut dk).unwrap();483484        // coefficient = q (0xD01) in the first 12-bit field: non-canonical485        let mut bad = ek.clone();486        bad[0] = 0x01;487        bad[1] = (bad[1] & 0xF0) | 0x0D;488        assert_eq!(489            check_encapsulation_key(&p, &bad),490            Err(Error::InvalidPublicKey)491        );492        // all-ones polynomial part493        let mut bad = ek.clone();494        bad[..384 * p.k].fill(0xFF);495        assert_eq!(496            check_encapsulation_key(&p, &bad),497            Err(Error::InvalidPublicKey)498        );499        assert_eq!(500            check_encapsulation_key(&p, &ek[1..]),501            Err(Error::InvalidLength)502        );503504        let mut bad = dk.clone();505        bad[768 * p.k + 40] ^= 0x80; // inside h506        assert_eq!(507            check_decapsulation_key(&p, &bad),508            Err(Error::InvalidPrivateKey)509        );510        let mut bad = dk.clone();511        bad[384 * p.k + 5] ^= 1; // inside the embedded ek512        assert_eq!(513            check_decapsulation_key(&p, &bad),514            Err(Error::InvalidPrivateKey)515        );516        assert_eq!(517            check_decapsulation_key(&p, &dk[..dk.len() - 1]),518            Err(Error::InvalidLength)519        );520    }521}522
Files main
Menu

Theme