Repository Public Apache-2.0
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SPB Quantum Crypto7// File : crates/spb-pqc-core/src/math/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//! Arithmetic of ML-KEM: `Z_q` with `q = 3329`, the ring `R_q = Z_q[X]/(X^256+1)`,42//! its NTT, compression, byte encoding and sampling (FIPS 203 §4).43//!44//! # Representation and bounds45//!46//! Every coefficient is a `u16` in canonical form `[0, q)` at every function47//! boundary of this module. There is no lazy reduction: each addition,48//! subtraction and multiplication returns a canonical value, which makes the49//! bounds trivially checkable:50//!51//! * [`fq_add`], [`fq_sub`]: inputs `< q`; the intermediate is `< 2q < 2^13`;52//! one constant-time conditional subtraction gives `[0, q)`.53//! * [`fq_mul`]: inputs `< q`; the product is `< q² = 11 082 241 < 2^24`;54//! [`barrett_reduce`] is proven (below) and exhaustively tested for all `a < 2^24`.55//! * [`compress`]: input `< q`, `d ≤ 11`; numerator `< 2^11·q + q/2 < 2^23`.56//!57//! No function branches on, or indexes memory with, a coefficient value. The58//! only data-dependent loops are the two rejection samplers, which run on59//! *public* data only ([`sample_ntt`] expands the public matrix seed ρ).60//!61//! | FIPS 203 | Here |62//! |----------------------------------|------------------------------|63//! | Alg. 5 `ByteEncode_d` | [`byte_encode`] |64//! | Alg. 6 `ByteDecode_d` | [`byte_decode`] |65//! | Alg. 7 `SampleNTT` | [`sample_ntt`] |66//! | Alg. 8 `SamplePolyCBD_η` | [`sample_poly_cbd`] |67//! | Alg. 9 `NTT` | [`ntt`] |68//! | Alg. 10 `NTT⁻¹` | [`ntt_inv`] |69//! | Alg. 11 `MultiplyNTTs` | [`multiply_ntts`] |70//! | Alg. 12 `BaseCaseMultiply` | inlined in [`multiply_ntts`] |71//! | eq. 4.7 `Compress_d` | [`compress`] |72//! | eq. 4.8 `Decompress_d` | [`decompress`] |73//! | Appendix A ζ and γ tables | `ZETAS`, `GAMMAS` (computed at compile time from ζ = 17) |7475use crate::ct::wipe;76use crate::hash::keccak::Shake;7778/// Ring degree.79pub const N: usize = 256;80/// The prime modulus `q = 2^8 · 13 + 1`.81pub const Q: u16 = 3329;82const Q32: u32 = Q as u32;8384/// `⌊2^24 / q⌋`, the Barrett multiplier.85const BARRETT_M: u64 = 5039;8687/// A polynomial of `R_q` (or its NTT representation), coefficients in `[0, q)`.88/// Wiped on drop: polynomials routinely hold secret key or noise material.89#[derive(Clone)]90pub struct Poly {91 /// Coefficients, lowest degree first.92 pub c: [u16; N],93}9495impl Poly {96 /// The zero polynomial.97 pub const fn zero() -> Self {98 Poly { c: [0; N] }99 }100}101102impl Drop for Poly {103 fn drop(&mut self) {104 wipe(&mut self.c);105 }106}107108/// Subtracts `q` once if `a ≥ q`, in constant time. Requires `a < 2q`.109#[inline(always)]110fn cond_sub_q(a: u16) -> u16 {111 let t = a.wrapping_sub(Q);112 // t has its top bit set exactly when a < q (then t = a - q + 2^16 ≥ 2^16 - q > 2^15).113 let mask = 0u16.wrapping_sub(t >> 15);114 t.wrapping_add(mask & Q)115}116117/// Barrett reduction: returns `a mod q` for every `a < 2^24`.118///119/// Proof of the bound. Let `m = ⌊2^24/q⌋ = 5039`, so `2^24/q − m = ε` with120/// `0 < ε < 1` (ε ≈ 0.70). For `quo = ⌊a·m / 2^24⌋`:121/// `a/q − a·m/2^24 = a·ε/2^24 < 1` when `a < 2^24`, hence122/// `⌊a/q⌋ − 1 ≤ quo ≤ ⌊a/q⌋` and `r = a − quo·q ∈ [0, 2q)`. One conditional123/// subtraction finishes. `a·m < 2^24 · 2^13 = 2^37` fits in `u64`.124#[inline(always)]125pub fn barrett_reduce(a: u32) -> u16 {126 debug_assert!(a < (1 << 24));127 let quo = ((a as u64 * BARRETT_M) >> 24) as u32;128 let r = a - quo * Q32;129 cond_sub_q(r as u16)130}131132/// `a + b mod q` for canonical inputs.133#[inline(always)]134pub fn fq_add(a: u16, b: u16) -> u16 {135 cond_sub_q(a + b)136}137138/// `a − b mod q` for canonical inputs.139#[inline(always)]140pub fn fq_sub(a: u16, b: u16) -> u16 {141 cond_sub_q(a + Q - b)142}143144/// `a · b mod q` for canonical inputs.145#[inline(always)]146pub fn fq_mul(a: u16, b: u16) -> u16 {147 barrett_reduce(a as u32 * b as u32)148}149150const fn pow_mod_q(base: u32, mut exp: u32) -> u16 {151 let mut acc: u32 = 1;152 let mut b = base % Q32;153 while exp > 0 {154 if exp & 1 == 1 {155 acc = acc * b % Q32;156 }157 b = b * b % Q32;158 exp >>= 1;159 }160 acc as u16161}162163const fn bitrev7(i: u32) -> u32 {164 let mut r = 0;165 let mut k = 0;166 while k < 7 {167 r |= ((i >> k) & 1) << (6 - k);168 k += 1;169 }170 r171}172173/// `ZETAS[i] = 17^BitRev7(i) mod q` (FIPS 203 Appendix A, first table).174const ZETAS: [u16; 128] = {175 let mut z = [0u16; 128];176 let mut i = 0;177 while i < 128 {178 z[i] = pow_mod_q(17, bitrev7(i as u32));179 i += 1;180 }181 z182};183184/// `GAMMAS[i] = 17^(2·BitRev7(i)+1) mod q` (FIPS 203 Appendix A, second table).185const GAMMAS: [u16; 128] = {186 let mut g = [0u16; 128];187 let mut i = 0;188 while i < 128 {189 g[i] = pow_mod_q(17, 2 * bitrev7(i as u32) + 1);190 i += 1;191 }192 g193};194195/// `128⁻¹ mod q`.196const INV_128: u16 = 3303;197198/// Forward NTT, in place (FIPS 203 Algorithm 9).199pub fn ntt(f: &mut Poly) {200 let f = &mut f.c;201 let mut i = 1;202 let mut len = 128;203 while len >= 2 {204 let mut start = 0;205 while start < N {206 let zeta = ZETAS[i];207 i += 1;208 for j in start..start + len {209 let t = fq_mul(zeta, f[j + len]);210 f[j + len] = fq_sub(f[j], t);211 f[j] = fq_add(f[j], t);212 }213 start += 2 * len;214 }215 len /= 2;216 }217}218219/// Inverse NTT, in place (FIPS 203 Algorithm 10).220pub fn ntt_inv(f: &mut Poly) {221 let f = &mut f.c;222 let mut i = 127;223 let mut len = 2;224 while len <= 128 {225 let mut start = 0;226 while start < N {227 let zeta = ZETAS[i];228 i -= 1;229 for j in start..start + len {230 let t = f[j];231 f[j] = fq_add(t, f[j + len]);232 f[j + len] = fq_mul(zeta, fq_sub(f[j + len], t));233 }234 start += 2 * len;235 }236 len *= 2;237 }238 for c in f.iter_mut() {239 *c = fq_mul(*c, INV_128);240 }241}242243/// Product in the NTT domain (FIPS 203 Algorithms 11 and 12): 128 products of244/// degree-one polynomials modulo `X² − γ_i`.245pub fn multiply_ntts(f: &Poly, g: &Poly) -> Poly {246 let mut h = Poly::zero();247 for i in 0..128 {248 let (a0, a1) = (f.c[2 * i], f.c[2 * i + 1]);249 let (b0, b1) = (g.c[2 * i], g.c[2 * i + 1]);250 let gamma = GAMMAS[i];251 h.c[2 * i] = fq_add(fq_mul(a0, b0), fq_mul(fq_mul(a1, b1), gamma));252 h.c[2 * i + 1] = fq_add(fq_mul(a0, b1), fq_mul(a1, b0));253 }254 h255}256257/// `f ← f + g`.258pub fn poly_add_assign(f: &mut Poly, g: &Poly) {259 for i in 0..N {260 f.c[i] = fq_add(f.c[i], g.c[i]);261 }262}263264/// `f ← f − g`.265pub fn poly_sub_assign(f: &mut Poly, g: &Poly) {266 for i in 0..N {267 f.c[i] = fq_sub(f.c[i], g.c[i]);268 }269}270271/// `Compress_d(x) = ⌈(2^d / q) · x⌋ mod 2^d` for `x < q`, `1 ≤ d ≤ 11` (eq. 4.7).272///273/// Computed as `⌊(2^d·x + ⌊q/2⌋) / q⌋ mod 2^d` with a multiply-and-correct274/// division (no hardware division instruction on secret data, cf. KyberSlash):275/// the numerator is `< 2^11·3329 + 1664 < 2^23`, inside the proven Barrett range.276#[inline(always)]277pub fn compress(x: u16, d: u32) -> u16 {278 debug_assert!(x < Q && (1..=11).contains(&d));279 let num = ((x as u32) << d) + (Q32 / 2);280 let mut quo = ((num as u64 * BARRETT_M) >> 24) as u32;281 let r = num - quo * Q32; // in [0, 2q)282 // quo += (r >= q), constant time283 quo += 1 ^ ((r.wrapping_sub(Q32)) >> 31);284 (quo & ((1u32 << d) - 1)) as u16285}286287/// `Decompress_d(y) = ⌈(q / 2^d) · y⌋` for `y < 2^d`, `1 ≤ d ≤ 11` (eq. 4.8).288#[inline(always)]289pub fn decompress(y: u16, d: u32) -> u16 {290 debug_assert!((1..=11).contains(&d) && (y as u32) < (1 << d));291 (((y as u32) * Q32 + (1 << (d - 1))) >> d) as u16292}293294/// Applies [`compress`] to every coefficient.295pub fn poly_compress(f: &mut Poly, d: u32) {296 for c in f.c.iter_mut() {297 *c = compress(*c, d);298 }299}300301/// Applies [`decompress`] to every coefficient.302pub fn poly_decompress(f: &mut Poly, d: u32) {303 for c in f.c.iter_mut() {304 *c = decompress(*c, d);305 }306}307308/// `ByteEncode_d` (FIPS 203 Algorithm 5): packs 256 `d`-bit integers,309/// little-endian bit order, into `32·d` bytes. Coefficients must be `< 2^d`310/// (`< q` when `d = 12`).311pub fn byte_encode(f: &Poly, d: u32, out: &mut [u8]) {312 debug_assert_eq!(out.len(), 32 * d as usize);313 let mut acc: u32 = 0;314 let mut bits: u32 = 0;315 let mut o = 0;316 for &c in f.c.iter() {317 acc |= (c as u32) << bits;318 bits += d;319 while bits >= 8 {320 out[o] = acc as u8;321 o += 1;322 acc >>= 8;323 bits -= 8;324 }325 }326 debug_assert_eq!(bits, 0);327}328329/// `ByteDecode_d` (FIPS 203 Algorithm 6). For `d < 12` the result is in330/// `[0, 2^d)`; for `d = 12` the 12-bit value is reduced modulo `q` as the331/// standard specifies (constant time).332pub fn byte_decode(bytes: &[u8], d: u32) -> Poly {333 debug_assert_eq!(bytes.len(), 32 * d as usize);334 let mut f = Poly::zero();335 let mask = (1u32 << d) - 1;336 let mut acc: u32 = 0;337 let mut bits: u32 = 0;338 let mut i = 0;339 for &b in bytes {340 acc |= (b as u32) << bits;341 bits += 8;342 while bits >= d {343 let v = (acc & mask) as u16;344 // 12-bit values are < 4096 < 2q: one conditional subtraction reduces them.345 f.c[i] = if d == 12 { cond_sub_q(v) } else { v };346 i += 1;347 acc >>= d;348 bits -= d;349 }350 }351 debug_assert_eq!(i, N);352 f353}354355/// `SampleNTT` (FIPS 203 Algorithm 7): uniform element of `T_q` from the356/// 34-byte seed `ρ ‖ j ‖ i` by rejection sampling on SHAKE128 output.357///358/// Runs in variable time on **public** input only (ρ is part of the public key).359pub fn sample_ntt(seed: &[u8; 34]) -> Poly {360 let mut xof = Shake::new_128();361 xof.absorb(seed);362 let mut a = Poly::zero();363 let mut j = 0;364 let mut block = [0u8; 168]; // one SHAKE128 block, a multiple of 3 bytes365 while j < N {366 xof.squeeze(&mut block);367 for c in block.chunks_exact(3) {368 let d1 = c[0] as u16 | ((c[1] as u16 & 0x0F) << 8);369 let d2 = (c[1] as u16 >> 4) | ((c[2] as u16) << 4);370 if d1 < Q && j < N {371 a.c[j] = d1;372 j += 1;373 }374 if d2 < Q && j < N {375 a.c[j] = d2;376 j += 1;377 }378 }379 }380 a381}382383/// `SamplePolyCBD_η` (FIPS 203 Algorithm 8) for `η ∈ {2, 3}` from `64·η` bytes:384/// each coefficient is the difference of two sums of η bits, mapped to `[0, q)`.385/// Constant time (the input is secret).386pub fn sample_poly_cbd(bytes: &[u8], eta: usize) -> Poly {387 debug_assert!(eta == 2 || eta == 3);388 debug_assert_eq!(bytes.len(), 64 * eta);389 let bit = |k: usize| -> u16 { ((bytes[k / 8] >> (k % 8)) & 1) as u16 };390 let mut f = Poly::zero();391 for i in 0..N {392 let mut x = 0u16;393 let mut y = 0u16;394 for j in 0..eta {395 x += bit(2 * i * eta + j);396 y += bit(2 * i * eta + eta + j);397 }398 f.c[i] = fq_sub(x, y);399 }400 f401}402403#[cfg(test)]404mod tests {405 use super::*;406407 /// Deterministic test polynomial generator (SHAKE-based, not a CSPRNG use).408 fn test_poly(tag: u8) -> Poly {409 let mut seed = [0u8; 34];410 seed[0] = tag;411 sample_ntt(&seed)412 }413414 /// Schoolbook product in Z_q[X]/(X^256+1): the oracle for the NTT.415 fn naive_mul(a: &Poly, b: &Poly) -> Poly {416 let mut r = [0u32; N];417 for i in 0..N {418 for j in 0..N {419 let p = (a.c[i] as u32 * b.c[j] as u32) % Q32;420 let k = (i + j) % N;421 if i + j < N {422 r[k] = (r[k] + p) % Q32;423 } else {424 r[k] = (r[k] + Q32 - p) % Q32; // X^256 = -1425 }426 }427 }428 let mut out = Poly::zero();429 for i in 0..N {430 out.c[i] = r[i] as u16;431 }432 out433 }434435 #[test]436 fn constants_match_fips203_appendix_a() {437 assert_eq!(&ZETAS[..8], &[1, 1729, 2580, 3289, 2642, 630, 1897, 848]);438 assert_eq!(ZETAS[127], 2154);439 assert_eq!(&GAMMAS[..8], &[17, 3312, 2761, 568, 583, 2746, 2649, 680]);440 assert_eq!(GAMMAS[127], 1175);441 assert_eq!((INV_128 as u32 * 128) % Q32, 1);442 // 17 is a primitive 256th root of unity: 17^128 = -1.443 assert_eq!(pow_mod_q(17, 128), Q - 1);444 assert_eq!(pow_mod_q(17, 256), 1);445 }446447 #[test]448 fn barrett_is_exact_on_its_whole_domain() {449 for a in 0u32..(1 << 24) {450 assert_eq!(barrett_reduce(a) as u32, a % Q32, "a = {a}");451 }452 }453454 #[test]455 fn field_ops_boundaries() {456 for &(a, b) in &[457 (0u16, 0u16),458 (0, Q - 1),459 (Q - 1, 0),460 (Q - 1, Q - 1),461 (1, Q - 1),462 (1664, 1665),463 ] {464 assert_eq!(fq_add(a, b) as u32, (a as u32 + b as u32) % Q32);465 assert_eq!(fq_sub(a, b) as u32, (a as u32 + Q32 - b as u32) % Q32);466 assert_eq!(fq_mul(a, b) as u32, (a as u32 * b as u32) % Q32);467 }468 }469470 #[test]471 fn compress_matches_rational_definition_exhaustively() {472 for d in 1..=11u32 {473 for x in 0..Q {474 // round-half-up of (2^d * x) / q, then mod 2^d475 let expect = (((x as u64) << (d + 1)) + Q as u64) / (2 * Q as u64) % (1 << d);476 assert_eq!(compress(x, d) as u64, expect, "x={x} d={d}");477 }478 for y in 0..(1u16 << d) {479 let expect = (2 * (y as u64) * Q as u64 + (1 << d)) >> (d + 1);480 assert_eq!(decompress(y, d) as u64, expect, "y={y} d={d}");481 // Compress_d(Decompress_d(y)) = y (FIPS 203 §4.2.1)482 assert_eq!(compress(decompress(y, d), d), y);483 }484 }485 }486487 #[test]488 fn ntt_round_trip_and_linearity() {489 let a = test_poly(1);490 let b = test_poly(2);491 let mut x = a.clone();492 ntt(&mut x);493 ntt_inv(&mut x);494 assert_eq!(x.c, a.c);495496 // NTT(a + b) = NTT(a) + NTT(b)497 let mut sum = a.clone();498 poly_add_assign(&mut sum, &b);499 ntt(&mut sum);500 let (mut na, mut nb) = (a.clone(), b.clone());501 ntt(&mut na);502 ntt(&mut nb);503 poly_add_assign(&mut na, &nb);504 assert_eq!(sum.c, na.c);505 }506507 #[test]508 fn ntt_product_equals_schoolbook_product() {509 for tag in 0..4u8 {510 let a = test_poly(10 + tag);511 let b = test_poly(20 + tag);512 let (mut na, mut nb) = (a.clone(), b.clone());513 ntt(&mut na);514 ntt(&mut nb);515 let mut prod = multiply_ntts(&na, &nb);516 ntt_inv(&mut prod);517 assert_eq!(prod.c, naive_mul(&a, &b).c);518 }519 // boundary: all coefficients q-1, and X^255 * X = -1520 let mut top = Poly::zero();521 top.c = [Q - 1; N];522 let (mut n1, mut n2) = (top.clone(), top.clone());523 ntt(&mut n1);524 ntt(&mut n2);525 let mut prod = multiply_ntts(&n1, &n2);526 ntt_inv(&mut prod);527 assert_eq!(prod.c, naive_mul(&top, &top).c);528529 let (mut x255, mut x1) = (Poly::zero(), Poly::zero());530 x255.c[255] = 1;531 x1.c[1] = 1;532 ntt(&mut x255);533 ntt(&mut x1);534 let mut prod = multiply_ntts(&x255, &x1);535 ntt_inv(&mut prod);536 let mut minus_one = Poly::zero();537 minus_one.c[0] = Q - 1;538 assert_eq!(prod.c, minus_one.c);539 }540541 #[test]542 fn byte_encode_decode_round_trip() {543 for d in [1u32, 4, 5, 10, 11, 12] {544 let mut p = test_poly(d as u8);545 if d < 12 {546 for c in p.c.iter_mut() {547 *c &= (1 << d) - 1;548 }549 }550 let mut buf = vec![0u8; 32 * d as usize];551 byte_encode(&p, d, &mut buf);552 assert_eq!(byte_decode(&buf, d).c, p.c, "d = {d}");553 }554 // d = 12 decoding reduces modulo q555 let all_ones = [0xFFu8; 384];556 assert!(byte_decode(&all_ones, 12).c.iter().all(|&c| c == 4095 - Q));557 }558559 #[test]560 fn cbd_range_and_extremes() {561 for eta in [2usize, 3] {562 let zeros = vec![0u8; 64 * eta];563 assert!(sample_poly_cbd(&zeros, eta).c.iter().all(|&c| c == 0));564 let ones = vec![0xFFu8; 64 * eta];565 assert!(sample_poly_cbd(&ones, eta).c.iter().all(|&c| c == 0));566 let mut noise = vec![0u8; 64 * eta];567 crate::hash::keccak::shake256(&[b"cbd"], &mut noise);568 for &c in sample_poly_cbd(&noise, eta).c.iter() {569 assert!(570 c <= eta as u16 || c >= Q - eta as u16,571 "coefficient {c} out of [-η, η]"572 );573 }574 }575 }576}577