Skip to main content

logicaffeine_system/
mlkem.rs

1//! ML-KEM-768 (FIPS-203) keygen / encapsulation / decapsulation as a Rust composition of the
2//! verified native kernels in [`crate::ntt`] (NTT, base-multiply, CBD, compress, byte-encode,
3//! 4-way AVX2 matrix expansion) and [`crate::keccak`] (SHA3-256/512, SHAKE256). This is the exact
4//! same primitive set the `assets/std/crypto.lg` Logos ML-KEM orchestrates and that the
5//! `logicaffeine-tests` AOT gates prove bit-exact vs the FIPS-203 reference — here orchestrated in
6//! Rust so the post-quantum channel (`logicaffeine_compile::concurrency::channel`) can run the
7//! handshake. Coefficients ride the fast `Word16` carrier throughout.
8
9use crate::keccak::{sha3_256_bytes, sha3_512_bytes, shake256_bytes};
10use crate::kernel_args as args;
11use crate::ntt::{
12    cadd_q, csub_q, mlkem_base_mul_w16, mlkem_byte_decode_w16, mlkem_byte_encode_w16,
13    mlkem_cbd2_w16, mlkem_compress_w16, mlkem_decompress_w16, mlkem_inv_ntt_w16, mlkem_ntt_w16,
14    mlkem_sample_matrix_w16, mlkem_to_mont_w16,
15};
16use logicaffeine_base::Word16;
17
18const K: usize = 3; // ML-KEM-768 module rank
19const N: usize = 256; // polynomial degree
20const Q: u32 = 3329;
21const DU: usize = 10; // ciphertext u compression
22const DV: usize = 4; //  ciphertext v compression
23const POLY_BYTES: usize = 384; // ByteEncode_12 of one 256-coefficient polynomial
24
25/// `ek` = K·384 + 32 (encapsulation / public key).
26pub const EK_BYTES: usize = POLY_BYTES * K + 32;
27/// `dk` = dk_pke ‖ ek ‖ H(ek) ‖ z (decapsulation / secret key).
28pub const DK_BYTES: usize = POLY_BYTES * K + EK_BYTES + 32 + 32;
29/// `ct` = K·(32·du) + 32·dv (ciphertext).
30pub const CT_BYTES: usize = K * 32 * DU + 32 * DV;
31/// Shared secret length.
32pub const SS_BYTES: usize = 32;
33
34/// G = SHA3-512, split into (ρ, σ) or (K, r) 32-byte halves.
35fn g(input: &[u8]) -> ([u8; 32], [u8; 32]) {
36    let h = sha3_512_bytes(input);
37    let mut a = [0u8; 32];
38    let mut b = [0u8; 32];
39    a.copy_from_slice(&h[..32]);
40    b.copy_from_slice(&h[32..]);
41    (a, b)
42}
43
44/// One CBD_2 noise polynomial, raw (no NTT): PRF_η2(seed, nonce) = CBD_2(SHAKE256(seed ‖ nonce, 128)).
45fn noise_raw(seed: &[u8; 32], nonce: u8) -> Vec<Word16> {
46    let mut pin = seed.to_vec();
47    pin.push(nonce);
48    mlkem_cbd2_w16(&shake256_bytes(&pin, 128))
49}
50
51/// Sample `count` CBD_2 noise polynomials with nonces `base..base+count`, batching the SHAKE256 PRF
52/// four independent streams per 4-way AVX2 Keccak permutation (portable scalar fallback). Returns raw
53/// polys — the caller NTTs the subset that needs it (s/e/r get NTT; e1/e2 do not). This is the win
54/// that closes the keygen/decaps gap vs the hand-tuned reference libs: K-PKE keygen samples 6 noise
55/// polys and encrypt (the FO re-encryption inside decaps) samples 7 — otherwise 6–7 serial Keccak
56/// permutations; batched, that is ⌈count/4⌉ four-way permutations plus a short scalar tail.
57fn noise_batch_raw(seed: &[u8; 32], base: u8, count: usize) -> Vec<Vec<Word16>> {
58    let mut raw: Vec<Vec<Word16>> = Vec::with_capacity(count);
59    #[cfg(target_arch = "x86_64")]
60    {
61        if std::is_x86_feature_detected!("avx2") {
62            let mut i = 0;
63            while i + 4 <= count {
64                let ins: [[u8; 33]; 4] = std::array::from_fn(|l| {
65                    let mut a = [0u8; 33];
66                    a[..32].copy_from_slice(seed);
67                    a[32] = base + (i + l) as u8;
68                    a
69                });
70                let refs: [&[u8]; 4] = [&ins[0], &ins[1], &ins[2], &ins[3]];
71                let outs = unsafe { crate::keccak::shake256_x4_128(&refs) };
72                for o in &outs {
73                    raw.push(mlkem_cbd2_w16(o));
74                }
75                i += 4;
76            }
77            for j in i..count {
78                raw.push(noise_raw(seed, base + j as u8));
79            }
80            return raw;
81        }
82    }
83    for j in 0..count {
84        raw.push(noise_raw(seed, base + j as u8));
85    }
86    raw
87}
88
89/// Coefficient-wise `(a + b) mod q`. Operands are reduced (∈ [0, q)), so `a + b ∈ [0, 2q)` and the
90/// reduction is one masked subtract of q — no division and no branch on the secret sum.
91#[inline]
92fn addq(a: &[Word16], b: &[Word16]) -> Vec<Word16> {
93    (0..N).map(|c| Word16(csub_q(a[c].0 + b[c].0))).collect()
94}
95
96/// Coefficient-wise `(a − b) mod q` of reduced operands: `a − b ∈ (−q, q)`, then one masked add of q.
97#[inline]
98fn subq(a: &[Word16], b: &[Word16]) -> Vec<Word16> {
99    (0..N)
100        .map(|c| Word16(cadd_q(a[c].0 as i16 - b[c].0 as i16)))
101        .collect()
102}
103
104/// K-PKE.KeyGen(d) → (ek_pke = ByteEncode₁₂(t̂) ‖ ρ, dk_pke = ByteEncode₁₂(ŝ)).
105fn kpke_keygen(d: &[u8; 32]) -> (Vec<u8>, Vec<u8>) {
106    let mut gin = d.to_vec();
107    gin.push(K as u8);
108    let (rho, sigma) = g(&gin);
109    let matrix = mlkem_sample_matrix_w16(&rho); // Â[r][c] at slot (r·K+c)·N
110                                                // s (nonces 0..K) and e (nonces K..2K) — all NTT'd — in one 4-way-batched CBD noise pass.
111    let se = noise_batch_raw(&sigma, 0, 2 * K);
112    let s_hat: Vec<Vec<Word16>> = se[0..K].iter().map(|p| mlkem_ntt_w16(p)).collect();
113    let e_hat: Vec<Vec<Word16>> = se[K..2 * K].iter().map(|p| mlkem_ntt_w16(p)).collect();
114
115    let mut ek = Vec::with_capacity(EK_BYTES);
116    for i in 0..K {
117        let mut acc = vec![Word16(0); N];
118        for j in 0..K {
119            let e = (j * K + i) * N; // keygen uses Âᵀ: a_hat[i][j] = Â[j][i]
120            acc = addq(&acc, &mlkem_base_mul_w16(&matrix[e..e + N], &s_hat[j]));
121        }
122        let ti = addq(&mlkem_to_mont_w16(&acc), &e_hat[i]);
123        ek.extend(mlkem_byte_encode_w16(&ti, 12));
124    }
125    ek.extend_from_slice(&rho);
126
127    let mut dk_pke = Vec::with_capacity(POLY_BYTES * K);
128    for poly in &s_hat {
129        dk_pke.extend(mlkem_byte_encode_w16(poly, 12));
130    }
131    (ek, dk_pke)
132}
133
134/// K-PKE.Encrypt(ek, m, r) → c = ByteEncode_du(Compress_du(u)) ‖ ByteEncode_dv(Compress_dv(v)).
135fn kpke_encrypt(ek: &[u8], m: &[u8; 32], r: &[u8; 32]) -> Vec<u8> {
136    let t_hat: Vec<Vec<Word16>> = (0..K)
137        .map(|i| mlkem_byte_decode_w16(&ek[POLY_BYTES * i..POLY_BYTES * (i + 1)], 12))
138        .collect();
139    let rho = &ek[POLY_BYTES * K..POLY_BYTES * K + 32];
140    let matrix = mlkem_sample_matrix_w16(rho); // Â[i][j] at slot (i·K+j)·N
141
142    // r (nonces 0..K, NTT'd) + e1 (nonces K..2K, raw) + e2 (nonce 2K, raw) in one 4-way-batched pass.
143    let all = noise_batch_raw(r, 0, 2 * K + 1);
144    let r_hat: Vec<Vec<Word16>> = all[0..K].iter().map(|p| mlkem_ntt_w16(p)).collect();
145    let e1: Vec<Vec<Word16>> = all[K..2 * K].to_vec();
146    let e2 = all[2 * K].clone();
147
148    let mut c = Vec::with_capacity(CT_BYTES);
149    for i in 0..K {
150        let mut acc = vec![Word16(0); N];
151        for j in 0..K {
152            let e = (i * K + j) * N;
153            acc = addq(&acc, &mlkem_base_mul_w16(&matrix[e..e + N], &r_hat[j]));
154        }
155        let ui = addq(&mlkem_inv_ntt_w16(&acc), &e1[i]);
156        c.extend(mlkem_byte_encode_w16(&mlkem_compress_w16(&ui, DU), DU));
157    }
158    let mu = mlkem_decompress_w16(&mlkem_byte_decode_w16(m, 1), 1);
159    let mut acc = vec![Word16(0); N];
160    for i in 0..K {
161        acc = addq(&acc, &mlkem_base_mul_w16(&t_hat[i], &r_hat[i]));
162    }
163    let v = addq(&addq(&mlkem_inv_ntt_w16(&acc), &e2), &mu);
164    c.extend(mlkem_byte_encode_w16(&mlkem_compress_w16(&v, DV), DV));
165    c
166}
167
168/// K-PKE.Decrypt(dk_pke, c) → m = ByteEncode₁(Compress₁(v − NTT⁻¹(ŝᵀ ∘ NTT(u)))).
169fn kpke_decrypt(dk_pke: &[u8], c: &[u8]) -> [u8; 32] {
170    let s_hat: Vec<Vec<Word16>> = (0..K)
171        .map(|i| mlkem_byte_decode_w16(&dk_pke[POLY_BYTES * i..POLY_BYTES * (i + 1)], 12))
172        .collect();
173    let u: Vec<Vec<Word16>> = (0..K)
174        .map(|i| {
175            let bytes = &c[32 * DU * i..32 * DU * (i + 1)];
176            mlkem_decompress_w16(&mlkem_byte_decode_w16(bytes, DU), DU)
177        })
178        .collect();
179    let v = mlkem_decompress_w16(&mlkem_byte_decode_w16(&c[32 * DU * K..], DV), DV);
180
181    let mut acc = vec![Word16(0); N];
182    for i in 0..K {
183        acc = addq(&acc, &mlkem_base_mul_w16(&s_hat[i], &mlkem_ntt_w16(&u[i])));
184    }
185    let w = subq(&v, &mlkem_inv_ntt_w16(&acc));
186    let mut m = [0u8; 32];
187    m.copy_from_slice(&mlkem_byte_encode_w16(&mlkem_compress_w16(&w, 1), 1));
188    m
189}
190
191/// Why [`encaps`] or [`decaps`] refuses its inputs: the FIPS 203 §7.2–7.3 input checks.
192#[derive(Debug, Clone, Copy, PartialEq, Eq)]
193pub enum KemError {
194    /// The encapsulation key is not [`EK_BYTES`] bytes (the ek type check).
195    EncapsulationKeyLength { len: usize },
196    /// A 12-bit coefficient of the encapsulation key is q or more (the ek modulus check).
197    EncapsulationKeyNotReduced,
198    /// The decapsulation key is not [`DK_BYTES`] bytes (the dk type check).
199    DecapsulationKeyLength { len: usize },
200    /// The H(ek) inside the decapsulation key is not the hash of the ek beside it (the hash check).
201    DecapsulationKeyCorrupt,
202    /// The ciphertext is not [`CT_BYTES`] bytes (the ciphertext type check).
203    CiphertextLength { len: usize },
204}
205
206impl std::fmt::Display for KemError {
207    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
208        match self {
209            KemError::EncapsulationKeyLength { len } => write!(
210                f,
211                "the encapsulation key is {len} bytes; an ML-KEM-768 encapsulation key is {EK_BYTES}"
212            ),
213            KemError::EncapsulationKeyNotReduced => write!(
214                f,
215                "the encapsulation key holds a coefficient of {Q} or more (FIPS 203 modulus check)"
216            ),
217            KemError::DecapsulationKeyLength { len } => write!(
218                f,
219                "the decapsulation key is {len} bytes; an ML-KEM-768 decapsulation key is {DK_BYTES}"
220            ),
221            KemError::DecapsulationKeyCorrupt => write!(
222                f,
223                "the decapsulation key's H(ek) is not the hash of its ek (FIPS 203 hash check)"
224            ),
225            KemError::CiphertextLength { len } => write!(
226                f,
227                "the ciphertext is {len} bytes; an ML-KEM-768 ciphertext is {CT_BYTES}"
228            ),
229        }
230    }
231}
232
233impl std::error::Error for KemError {}
234
235/// ML-KEM.KeyGen(d, z) → (ek, dk) where dk = dk_pke ‖ ek ‖ H(ek) ‖ z.
236pub fn keygen(d: &[u8; 32], z: &[u8; 32]) -> (Vec<u8>, Vec<u8>) {
237    let (ek, dk_pke) = kpke_keygen(d);
238    let mut dk = dk_pke;
239    dk.extend_from_slice(&ek);
240    dk.extend_from_slice(&sha3_256_bytes(&ek));
241    dk.extend_from_slice(z);
242    (ek, dk)
243}
244
245/// ML-KEM.Encaps(ek, m) → (ciphertext, shared secret). `m` is the 32-byte message randomness. An
246/// `ek` that fails the FIPS 203 §7.2 input checks is refused.
247pub fn encaps(ek: &[u8], m: &[u8; 32]) -> Result<(Vec<u8>, [u8; 32]), KemError> {
248    check_encapsulation_key(ek)?;
249    let h = sha3_256_bytes(ek);
250    let (kk, r) = g(&[m.as_slice(), &h].concat());
251    Ok((kpke_encrypt(ek, m, &r), kk))
252}
253
254/// ML-KEM.Decaps(dk, c) → shared secret, with the Fujisaki-Okamoto implicit reject. The FIPS 203
255/// §7.3 input checks run first, the key's before the ciphertext's, so a malformed key is reported
256/// whatever ciphertext arrives with it.
257pub fn decaps(dk: &[u8], c: &[u8]) -> Result<[u8; 32], KemError> {
258    if dk.len() != DK_BYTES {
259        return Err(KemError::DecapsulationKeyLength { len: dk.len() });
260    }
261    let (dk_pke, rest) = dk.split_at(POLY_BYTES * K);
262    let (ek, rest) = rest.split_at(EK_BYTES);
263    let (h, z) = rest.split_at(32);
264    if sha3_256_bytes(ek) != h {
265        return Err(KemError::DecapsulationKeyCorrupt);
266    }
267    if c.len() != CT_BYTES {
268        return Err(KemError::CiphertextLength { len: c.len() });
269    }
270    Ok(fo_decapsulate(dk_pke, ek, h, z, c))
271}
272
273/// FIPS 203 §7.2: the type check (exactly [`EK_BYTES`]) and the modulus check — every 12-bit field of
274/// t̂ below q, which is `ByteEncode₁₂(ByteDecode₁₂(ek[0:384k])) = ek[0:384k]`.
275fn check_encapsulation_key(ek: &[u8]) -> Result<(), KemError> {
276    if ek.len() != EK_BYTES {
277        return Err(KemError::EncapsulationKeyLength { len: ek.len() });
278    }
279    let reduced = ek[..POLY_BYTES * K].chunks_exact(3).all(|pair| {
280        let lo = pair[0] as u16 | ((pair[1] as u16 & 0x0F) << 8);
281        let hi = (pair[1] as u16 >> 4) | ((pair[2] as u16) << 4);
282        lo < Q as u16 && hi < Q as u16
283    });
284    if reduced {
285        Ok(())
286    } else {
287        Err(KemError::EncapsulationKeyNotReduced)
288    }
289}
290
291/// The Fujisaki–Okamoto core of ML-KEM.Decaps_internal (FIPS 203 Algorithm 18, lines 7–11):
292/// decrypt, re-encrypt, and keep K′ only if the re-encryption is the ciphertext, else K̄ = J(z ‖ c).
293/// Both keys are always derived and the choice is a mask over the full-length compare, so the
294/// time it takes says nothing about whether c was honest.
295fn fo_decapsulate(dk_pke: &[u8], ek: &[u8], h: &[u8], z: &[u8], c: &[u8]) -> [u8; 32] {
296    let m_prime = kpke_decrypt(dk_pke, c);
297    let (k_prime, r_prime) = g(&[m_prime.as_slice(), h].concat());
298    let mut k_bar = [0u8; 32];
299    k_bar.copy_from_slice(&shake256_bytes(&[z, c].concat(), 32));
300    let c_prime = kpke_encrypt(ek, &m_prime, &r_prime);
301    ct_select(ct_eq_mask(c, &c_prime), &k_prime, &k_bar)
302}
303
304/// `0xFF` when `a` and `b` (of equal length) hold the same bytes, else 0: every byte is folded in
305/// before the verdict, which `black_box` keeps the optimizer from turning back into a branch.
306#[inline]
307fn ct_eq_mask(a: &[u8], b: &[u8]) -> u8 {
308    debug_assert_eq!(a.len(), b.len());
309    let mut diff = 0u8;
310    for (x, y) in a.iter().zip(b) {
311        diff |= x ^ y;
312    }
313    std::hint::black_box(((diff as u16).wrapping_sub(1) >> 8) as u8)
314}
315
316/// `a` under an all-ones `mask`, `b` under zero, byte by byte.
317#[inline]
318fn ct_select(mask: u8, a: &[u8; 32], b: &[u8; 32]) -> [u8; 32] {
319    std::array::from_fn(|i| (a[i] & mask) | (b[i] & !mask))
320}
321
322// ── Logos-facing wrappers (Seq of Int bytes 0..255) — the natives crypto.lg's handshake calls ────
323
324/// `mlkemNoiseBatch(seed, base, count)` → `count·256` raw CBD_2 Word16 coefficients (nonces
325/// `base..base+count`, no NTT), the flat concatenation of `count` noise polynomials. The fast
326/// primitive the Logos `mlkem768Keygen`/`mlkemEncrypt` call once instead of `count` scalar
327/// `mlkemPrfNoise`s — one 4-way SHAKE256 permutation covers four PRF streams (see `noise_batch_raw`).
328pub fn mlkem_noise_batch_from_int(
329    seed: &[i64],
330    base: i64,
331    count: i64,
332) -> Result<logicaffeine_data::LogosSeq<Word16>, String> {
333    let s = args::byte_array::<32>("seed", seed)?;
334    let base = args::int_in("first nonce", base, 0, 255)?;
335    let n = args::int_in("count", count, 0, 256)?;
336    if n > 0 && base + n - 1 > 255 {
337        return Err(format!(
338            "the nonces run from {base} to {}; each must be a byte (0 to 255)",
339            base + n - 1
340        ));
341    }
342    let n = n as usize;
343    let polys = noise_batch_raw(&s, base as u8, n);
344    let mut out: Vec<Word16> = Vec::with_capacity(n * N);
345    for p in &polys {
346        out.extend_from_slice(p);
347    }
348    Ok(logicaffeine_data::LogosSeq::from_vec(out))
349}
350
351/// `mlkemKeypair(d, z)` → ek(1184) ‖ dk(2400).
352pub fn mlkem_keypair_seq(d: &[i64], z: &[i64]) -> Result<logicaffeine_data::LogosSeq<i64>, String> {
353    let d = args::byte_array::<32>("seed d", d)?;
354    let z = args::byte_array::<32>("seed z", z)?;
355    let (ek, dk) = keygen(&d, &z);
356    let mut out = ek;
357    out.extend(dk);
358    Ok(args::seq_of_bytes(&out))
359}
360/// `mlkemEncapsKem(ek, m)` → ciphertext(1088) ‖ shared_secret(32). The ek is the peer's: one that
361/// fails FIPS 203's checks is answered with an empty sequence, never encapsulated to.
362pub fn mlkem_encaps_seq(ek: &[i64], m: &[i64]) -> Result<logicaffeine_data::LogosSeq<i64>, String> {
363    let ek = args::bytes("encapsulation key", ek)?;
364    let m = args::byte_array::<32>("randomness m", m)?;
365    Ok(match encaps(&ek, &m) {
366        Ok((ct, ss)) => {
367            let mut out = ct;
368            out.extend_from_slice(&ss);
369            args::seq_of_bytes(&out)
370        }
371        Err(_) => logicaffeine_data::LogosSeq::from_vec(Vec::new()),
372    })
373}
374/// `mlkemDecapsKem(dk, ct)` → shared_secret(32). The ciphertext is the peer's: one of the wrong
375/// length is answered with an empty sequence; a malformed decapsulation key fails the program.
376pub fn mlkem_decaps_seq(
377    dk: &[i64],
378    ct: &[i64],
379) -> Result<logicaffeine_data::LogosSeq<i64>, String> {
380    let dk = args::bytes("decapsulation key", dk)?;
381    let ct = args::bytes("ciphertext", ct)?;
382    match decaps(&dk, &ct) {
383        Ok(ss) => Ok(args::seq_of_bytes(&ss)),
384        Err(KemError::CiphertextLength { .. }) => {
385            Ok(logicaffeine_data::LogosSeq::from_vec(Vec::new()))
386        }
387        Err(e) => Err(e.to_string()),
388    }
389}
390
391#[cfg(test)]
392#[path = "../../logicaffeine_tests/unit/logicaffeine_system/mlkem/tests.rs"]
393mod tests;