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/signature/mldsa.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-DSA (FIPS 204, August 13 2024): key generation, signing and verification.42//!43//! | FIPS 204 | Here |44//! |---------------------------------------|-------------------------------|45//! | Table 1 parameter sets | [`Params`], `MLDSA_44/65/87` |46//! | Alg. 6 `ML-DSA.KeyGen_internal` | [`keygen_internal`] |47//! | Alg. 7 `ML-DSA.Sign_internal` | [`sign_internal`], [`sign_mu`]|48//! | Alg. 8 `ML-DSA.Verify_internal` | [`verify_internal`], [`verify_mu`] |49//! | Alg. 20/21 `HintBitPack/Unpack` | `hint_pack`, `hint_unpack` |50//! | Alg. 22/23 `pkEncode/pkDecode` | inlined in keygen / verify |51//! | Alg. 24/25 `skEncode/skDecode` | inlined in keygen, `SecretKey::decode` |52//! | Alg. 26/27 `sigEncode/sigDecode` | inlined in sign / verify |53//! | Alg. 28 `w1Encode` | `w1_encode` |54//! | Alg. 32 `ExpandA` | `expand_a` |55//! | Alg. 33 `ExpandS` | inlined in keygen |56//! | Alg. 34 `ExpandMask` | `expand_mask` |57//!58//! The external interfaces (Alg. 1–5: context string, pure and pre-hash59//! message encodings, hedged / deterministic randomness) live in60//! [`crate::signature`].61//!62//! Timing: signing is a Fiat–Shamir-with-aborts loop; the number of iterations63//! depends on the secret key and the message *by design of the standard*. Each64//! iteration's rejection tests scan every coefficient without early exit.6566use crate::ct::{self, wipe};67use crate::error::{Error, Result};68use crate::hash::keccak::{shake256, Shake};69use crate::math::mldsa::{70 add_assign, bit_pack, bit_unpack, bitlen, decompose, freeze, inf_norm, make_hint, ntt,71 ntt_inv_tomont, pointwise_montgomery, poly_freeze, poly_reduce, power2round, rej_bounded_poly,72 rej_ntt_poly, sample_in_ball, simple_bit_pack, simple_bit_unpack, sub_assign, use_hint, Poly,73 D, N, Q,74};7576/// An ML-DSA parameter set (FIPS 204 Table 1).77#[derive(Clone, Copy, Debug, PartialEq, Eq)]78pub struct Params {79 /// Rows of the matrix A.80 pub k: usize,81 /// Columns of the matrix A.82 pub l: usize,83 /// Private key coefficient range.84 pub eta: i32,85 /// Number of ±1 coefficients in the challenge.86 pub tau: usize,87 /// `β = τ·η`.88 pub beta: i32,89 /// Mask coefficient range.90 pub gamma1: i32,91 /// Low-order rounding range.92 pub gamma2: i32,93 /// Maximum number of ones in the hint.94 pub omega: usize,95 /// Length of the commitment hash `c̃` in bytes (`λ/4`).96 pub ctilde_len: usize,97}9899/// ML-DSA-44.100pub const MLDSA_44: Params = Params {101 k: 4,102 l: 4,103 eta: 2,104 tau: 39,105 beta: 78,106 gamma1: 1 << 17,107 gamma2: (Q - 1) / 88,108 omega: 80,109 ctilde_len: 32,110};111/// ML-DSA-65.112pub const MLDSA_65: Params = Params {113 k: 6,114 l: 5,115 eta: 4,116 tau: 49,117 beta: 196,118 gamma1: 1 << 19,119 gamma2: (Q - 1) / 32,120 omega: 55,121 ctilde_len: 48,122};123/// ML-DSA-87.124pub const MLDSA_87: Params = Params {125 k: 8,126 l: 7,127 eta: 2,128 tau: 60,129 beta: 120,130 gamma1: 1 << 19,131 gamma2: (Q - 1) / 32,132 omega: 75,133 ctilde_len: 64,134};135136impl Params {137 const fn eta_bits(&self) -> u32 {138 bitlen(2 * self.eta as u32)139 }140 const fn z_bits(&self) -> u32 {141 1 + bitlen(self.gamma1 as u32 - 1)142 }143 const fn w1_bits(&self) -> u32 {144 bitlen(((Q - 1) / (2 * self.gamma2)) as u32 - 1)145 }146 /// Public-key length in bytes.147 pub const fn pk_len(&self) -> usize {148 32 + 320 * self.k149 }150 /// Private-key length in bytes.151 pub const fn sk_len(&self) -> usize {152 128 + 32 * self.eta_bits() as usize * (self.k + self.l) + 416 * self.k153 }154 /// Signature length in bytes.155 pub const fn sig_len(&self) -> usize {156 self.ctilde_len + 32 * self.z_bits() as usize * self.l + self.omega + self.k157 }158}159160const T0_BITS: u32 = D; // bitlen(2^12 − 1 + 2^12)161const T1_BITS: u32 = 10; // bitlen(q − 1) − d162163/// `ExpandA` (Alg. 32): `Â[r][s] = RejNTTPoly(ρ ‖ s ‖ r)`.164fn expand_a(p: &Params, rho: &[u8]) -> Vec<Vec<Poly>> {165 let mut seed = [0u8; 34];166 seed[..32].copy_from_slice(rho);167 (0..p.k)168 .map(|r| {169 (0..p.l)170 .map(|s| {171 seed[32] = s as u8;172 seed[33] = r as u8;173 rej_ntt_poly(&seed)174 })175 .collect()176 })177 .collect()178}179180/// `ExpandMask` (Alg. 34): `y[r] = BitUnpack(H(ρ'' ‖ (κ + r), 32c), γ1 − 1, γ1)`.181fn expand_mask(p: &Params, rho2: &[u8; 64], kappa: u16) -> Vec<Poly> {182 let bits = p.z_bits();183 let mut v = [0u8; 640];184 let v = &mut v[..32 * bits as usize];185 let y = (0..p.l)186 .map(|r| {187 let n = kappa.wrapping_add(r as u16).to_le_bytes();188 shake256(&[rho2, &n], v);189 bit_unpack(v, p.gamma1, bits)190 })191 .collect();192 wipe(v);193 y194}195196/// Row `i` of `Â ∘ v̂`, brought back to the coefficient domain, `|c| < q`.197fn mat_row_times_vec(row: &[Poly], v_hat: &[Poly]) -> Poly {198 let mut acc = Poly::zero();199 for (a, v) in row.iter().zip(v_hat.iter()) {200 let t = pointwise_montgomery(a, v);201 add_assign(&mut acc, &t);202 }203 poly_reduce(&mut acc); // ≤ l·q in magnitude before, inside the reduce32 domain204 ntt_inv_tomont(&mut acc);205 acc206}207208/// `c · v` for a challenge and one NTT-domain polynomial, coefficient domain, `|c| < q`.209fn challenge_times(c_hat: &Poly, v_hat: &Poly) -> Poly {210 let mut t = pointwise_montgomery(c_hat, v_hat);211 ntt_inv_tomont(&mut t);212 t213}214215/// `w1Encode` (Alg. 28).216fn w1_encode(p: &Params, w1: &[Poly], out: &mut Vec<u8>) {217 let bits = p.w1_bits();218 let step = 32 * bits as usize;219 let start = out.len();220 out.resize(start + step * w1.len(), 0);221 for (i, w) in w1.iter().enumerate() {222 simple_bit_pack(w, bits, &mut out[start + step * i..start + step * (i + 1)]);223 }224}225226/// `HintBitPack` (Alg. 20). `h[i][j] ∈ {0, 1}`, at most ω ones in total.227fn hint_pack(p: &Params, h: &[Poly], out: &mut [u8]) {228 debug_assert_eq!(out.len(), p.omega + p.k);229 out.fill(0);230 let mut index = 0;231 for i in 0..p.k {232 for j in 0..N {233 if h[i].c[j] != 0 {234 out[index] = j as u8;235 index += 1;236 }237 }238 out[p.omega + i] = index as u8;239 }240}241242/// `HintBitUnpack` (Alg. 21): `None` for any non-canonical encoding.243fn hint_unpack(p: &Params, y: &[u8]) -> Option<Vec<Poly>> {244 let mut h: Vec<Poly> = (0..p.k).map(|_| Poly::zero()).collect();245 let mut index = 0usize;246 for i in 0..p.k {247 let limit = y[p.omega + i] as usize;248 if limit < index || limit > p.omega {249 return None;250 }251 let first = index;252 while index < limit {253 if index > first && y[index - 1] >= y[index] {254 return None;255 }256 h[i].c[y[index] as usize] = 1;257 index += 1;258 }259 }260 if y[index..p.omega].iter().any(|&b| b != 0) {261 return None;262 }263 Some(h)264}265266/// `ML-DSA.KeyGen_internal(ξ)` (Alg. 6): returns `(pk, sk)` encodings.267pub(crate) fn keygen_internal(p: &Params, xi: &[u8; 32]) -> (Vec<u8>, Vec<u8>) {268 let mut seed = [0u8; 128];269 shake256(&[xi, &[p.k as u8], &[p.l as u8]], &mut seed);270 let (rho, rest) = seed.split_at(32);271 let (rho_prime, key) = rest.split_at(64);272273 let a = expand_a(p, rho);274 // ExpandS (Alg. 33)275 let mut s_seed = [0u8; 66];276 s_seed[..64].copy_from_slice(rho_prime);277 let mut sample = |r: usize| {278 s_seed[64..].copy_from_slice(&(r as u16).to_le_bytes());279 rej_bounded_poly(&s_seed, p.eta)280 };281 let s1: Vec<Poly> = (0..p.l).map(&mut sample).collect();282 let s2: Vec<Poly> = (0..p.k).map(|r| sample(r + p.l)).collect();283 wipe(&mut s_seed);284285 let mut s1_hat = s1.clone();286 s1_hat.iter_mut().for_each(ntt);287288 let mut pk = vec![0u8; p.pk_len()];289 pk[..32].copy_from_slice(rho);290 let mut t0: Vec<Poly> = Vec::with_capacity(p.k);291 for i in 0..p.k {292 let mut t = mat_row_times_vec(&a[i], &s1_hat);293 add_assign(&mut t, &s2[i]);294 poly_freeze(&mut t);295 let mut t1 = Poly::zero();296 let mut low = Poly::zero();297 for n in 0..N {298 let (hi, lo) = power2round(t.c[n]);299 t1.c[n] = hi;300 low.c[n] = lo;301 }302 simple_bit_pack(&t1, T1_BITS, &mut pk[32 + 320 * i..32 + 320 * (i + 1)]);303 t0.push(low);304 }305306 let mut sk = vec![0u8; p.sk_len()];307 sk[..32].copy_from_slice(rho);308 sk[32..64].copy_from_slice(key);309 shake256(&[&pk], &mut sk[64..128]); // tr = H(pk, 64)310 let eb = p.eta_bits();311 let es = 32 * eb as usize;312 let mut off = 128;313 for s in s1.iter().chain(s2.iter()) {314 bit_pack(s, p.eta, eb, &mut sk[off..off + es]);315 off += es;316 }317 for t in t0.iter() {318 bit_pack(t, 1 << (D - 1), T0_BITS, &mut sk[off..off + 416]);319 off += 416;320 }321 debug_assert_eq!(off, sk.len());322 wipe(&mut seed);323 (pk, sk)324}325326/// Decoded private key (`skDecode`, Alg. 25), vectors already in the NTT domain.327struct SecretKey {328 rho: [u8; 32],329 key: [u8; 32],330 tr: [u8; 64],331 s1_hat: Vec<Poly>,332 s2_hat: Vec<Poly>,333 t0_hat: Vec<Poly>,334}335336impl Drop for SecretKey {337 fn drop(&mut self) {338 wipe(&mut self.key);339 }340}341342impl SecretKey {343 /// Decodes and validates: exact length, and every `s1`/`s2` coefficient344 /// inside `[−η, η]` (stricter than FIPS 204, which leaves malformed private345 /// keys unspecified).346 fn decode(p: &Params, sk: &[u8]) -> Result<Self> {347 if sk.len() != p.sk_len() {348 return Err(Error::InvalidLength);349 }350 let mut rho = [0u8; 32];351 let mut key = [0u8; 32];352 let mut tr = [0u8; 64];353 rho.copy_from_slice(&sk[..32]);354 key.copy_from_slice(&sk[32..64]);355 tr.copy_from_slice(&sk[64..128]);356 let eb = p.eta_bits();357 let es = 32 * eb as usize;358 let mut off = 128;359 let mut in_range = true;360 let mut small = |off: &mut usize| {361 let s = bit_unpack(&sk[*off..*off + es], p.eta, eb);362 *off += es;363 // b − z with z < 2^bits: only the lower bound can be violated364 in_range &= s.c.iter().fold(true, |ok, &c| ok & (c >= -p.eta));365 s366 };367 let mut s1_hat: Vec<Poly> = (0..p.l).map(|_| small(&mut off)).collect();368 let mut s2_hat: Vec<Poly> = (0..p.k).map(|_| small(&mut off)).collect();369 let mut t0_hat: Vec<Poly> = (0..p.k)370 .map(|_| {371 let t = bit_unpack(&sk[off..off + 416], 1 << (D - 1), T0_BITS);372 off += 416;373 t374 })375 .collect();376 if !in_range {377 wipe(&mut key);378 return Err(Error::InvalidPrivateKey);379 }380 s1_hat.iter_mut().for_each(ntt);381 s2_hat.iter_mut().for_each(ntt);382 t0_hat.iter_mut().for_each(ntt);383 Ok(SecretKey {384 rho,385 key,386 tr,387 s1_hat,388 s2_hat,389 t0_hat,390 })391 }392}393394/// Validates a private-key encoding without keeping it.395pub(crate) fn check_private_key(p: &Params, sk: &[u8]) -> Result<()> {396 SecretKey::decode(p, sk).map(|_| ())397}398399/// Recomputes the public key `(ρ, t1)` from a private key: `t = A·s1 + s2`400/// cannot be rebuilt from `t0` alone, so this re-derives `t` from `s1`, `s2`.401pub(crate) fn public_from_private(p: &Params, sk: &[u8]) -> Result<Vec<u8>> {402 let key = SecretKey::decode(p, sk)?;403 let a = expand_a(p, &key.rho);404 let mut pk = vec![0u8; p.pk_len()];405 pk[..32].copy_from_slice(&key.rho);406 for i in 0..p.k {407 let mut t = mat_row_times_vec(&a[i], &key.s1_hat);408 // s2 is held in the NTT domain: bring it back (the 2^32 factor is removed by a409 // Montgomery product with 1).410 let mut s2 = key.s2_hat[i].clone();411 poly_reduce(&mut s2);412 ntt_inv_tomont(&mut s2);413 for c in s2.c.iter_mut() {414 *c = crate::math::mldsa::montgomery_reduce(*c as i64);415 }416 add_assign(&mut t, &s2);417 poly_freeze(&mut t);418 let mut t1 = Poly::zero();419 for n in 0..N {420 t1.c[n] = power2round(t.c[n]).0;421 }422 simple_bit_pack(&t1, T1_BITS, &mut pk[32 + 320 * i..32 + 320 * (i + 1)]);423 }424 // The stored tr must match H(pk): binds the private key to this public key.425 let mut tr = [0u8; 64];426 shake256(&[&pk], &mut tr);427 if !ct::eq(&tr, &key.tr) {428 return Err(Error::InvalidPrivateKey);429 }430 Ok(pk)431}432433/// `μ = H(BytesToBits(tr) ‖ M', 64)` for the message representative given in parts.434fn compute_mu(tr: &[u8], m_prime: &[&[u8]]) -> [u8; 64] {435 let mut h = Shake::new_256();436 h.absorb(tr);437 for part in m_prime {438 h.absorb(part);439 }440 let mut mu = [0u8; 64];441 h.squeeze(&mut mu);442 mu443}444445/// `ML-DSA.Sign_internal(sk, M', rnd)` (Alg. 7), `M'` given as concatenated parts.446pub(crate) fn sign_internal(447 p: &Params,448 sk: &[u8],449 m_prime: &[&[u8]],450 rnd: &[u8; 32],451) -> Result<Vec<u8>> {452 let key = SecretKey::decode(p, sk)?;453 let mu = compute_mu(&key.tr, m_prime);454 sign_with_key(p, &key, &mu, rnd)455}456457/// Signing from an externally computed `μ` (FIPS 204 §6.2, "external μ" option).458#[cfg(feature = "kat")]459pub(crate) fn sign_mu(p: &Params, sk: &[u8], mu: &[u8; 64], rnd: &[u8; 32]) -> Result<Vec<u8>> {460 let key = SecretKey::decode(p, sk)?;461 sign_with_key(p, &key, mu, rnd)462}463464fn sign_with_key(p: &Params, key: &SecretKey, mu: &[u8; 64], rnd: &[u8; 32]) -> Result<Vec<u8>> {465 let a = expand_a(p, &key.rho);466 let mut rho2 = [0u8; 64];467 shake256(&[&key.key, rnd, mu], &mut rho2); // ρ'' = H(K ‖ rnd ‖ μ, 64)468469 let mut w1_bytes = Vec::with_capacity(p.k * 32 * p.w1_bits() as usize);470 let mut kappa: u16 = 0;471 let result = loop {472 let y = expand_mask(p, &rho2, kappa);473 // κ advances by ℓ per attempt; refuse to wrap the 16-bit counter (> 9000 attempts,474 // probability far below 2^-256 for honest keys — FIPS 204 Appendix C).475 kappa = match kappa.checked_add(p.l as u16) {476 Some(next) => next,477 None => break Err(Error::Internal),478 };479 let mut y_hat = y.clone();480 y_hat.iter_mut().for_each(ntt);481482 // w = NTT^-1(Â ∘ NTT(y)), w1 = HighBits(w)483 let mut w: Vec<Poly> = Vec::with_capacity(p.k);484 let mut w1: Vec<Poly> = Vec::with_capacity(p.k);485 for row in a.iter() {486 let mut wi = mat_row_times_vec(row, &y_hat);487 poly_freeze(&mut wi);488 let mut hi = Poly::zero();489 for n in 0..N {490 hi.c[n] = decompose(wi.c[n], p.gamma2).0;491 }492 w.push(wi);493 w1.push(hi);494 }495496 // c̃ = H(μ ‖ w1Encode(w1), λ/4), c = SampleInBall(c̃)497 w1_bytes.clear();498 w1_encode(p, &w1, &mut w1_bytes);499 let mut ctilde = vec![0u8; p.ctilde_len];500 shake256(&[mu, &w1_bytes], &mut ctilde);501 let mut c_hat = sample_in_ball(&ctilde, p.tau);502 ntt(&mut c_hat);503504 // z = y + c·s1 ; reject if ‖z‖∞ ≥ γ1 − β505 let mut z: Vec<Poly> = Vec::with_capacity(p.l);506 let mut z_max = 0;507 for (yj, s1j) in y.iter().zip(key.s1_hat.iter()) {508 let mut zj = challenge_times(&c_hat, s1j);509 add_assign(&mut zj, yj);510 z_max = z_max.max(inf_norm(&zj));511 z.push(zj);512 }513514 // r = w − c·s2 ; reject if ‖LowBits(r)‖∞ ≥ γ2 − β515 let mut r: Vec<Poly> = Vec::with_capacity(p.k);516 let mut r0_max = 0;517 for (wi, s2i) in w.iter().zip(key.s2_hat.iter()) {518 let cs2 = challenge_times(&c_hat, s2i);519 let mut ri = wi.clone();520 sub_assign(&mut ri, &cs2);521 poly_freeze(&mut ri);522 for n in 0..N {523 let r0 = decompose(ri.c[n], p.gamma2).1;524 r0_max = r0_max.max(r0.abs());525 }526 r.push(ri);527 }528 if z_max >= p.gamma1 - p.beta || r0_max >= p.gamma2 - p.beta {529 continue;530 }531532 // h = MakeHint(−c·t0, w − c·s2 + c·t0) ; reject if ‖c·t0‖∞ ≥ γ2 or too many ones533 let mut h: Vec<Poly> = Vec::with_capacity(p.k);534 let mut ct0_max = 0;535 let mut ones = 0usize;536 for (ri, t0i) in r.iter().zip(key.t0_hat.iter()) {537 let ct0 = challenge_times(&c_hat, t0i);538 ct0_max = ct0_max.max(inf_norm(&ct0));539 let mut hi = Poly::zero();540 for n in 0..N {541 let minus_ct0 = freeze(-ct0.c[n]);542 let base = freeze(ri.c[n] + ct0.c[n]);543 let bit = make_hint(minus_ct0, base, p.gamma2) as i32;544 hi.c[n] = bit;545 ones += bit as usize;546 }547 h.push(hi);548 }549 if ct0_max >= p.gamma2 || ones > p.omega {550 continue;551 }552553 // σ = sigEncode(c̃, z mod± q, h)554 let mut sig = vec![0u8; p.sig_len()];555 sig[..p.ctilde_len].copy_from_slice(&ctilde);556 let zb = p.z_bits();557 let zs = 32 * zb as usize;558 let mut off = p.ctilde_len;559 for zj in z.iter_mut() {560 for c in zj.c.iter_mut() {561 *c = crate::math::mldsa::center(freeze(*c));562 }563 bit_pack(zj, p.gamma1, zb, &mut sig[off..off + zs]);564 off += zs;565 }566 hint_pack(p, &h, &mut sig[off..]);567 break Ok(sig);568 };569 wipe(&mut rho2);570 wipe(&mut w1_bytes);571 result572}573574/// `ML-DSA.Verify_internal(pk, M', σ)` (Alg. 8).575pub(crate) fn verify_internal(p: &Params, pk: &[u8], m_prime: &[&[u8]], sig: &[u8]) -> bool {576 if pk.len() != p.pk_len() {577 return false;578 }579 let mut tr = [0u8; 64];580 shake256(&[pk], &mut tr);581 let mu = compute_mu(&tr, m_prime);582 verify_mu(p, pk, &mu, sig)583}584585/// Verification from an externally computed `μ`.586pub(crate) fn verify_mu(p: &Params, pk: &[u8], mu: &[u8; 64], sig: &[u8]) -> bool {587 if pk.len() != p.pk_len() || sig.len() != p.sig_len() {588 return false;589 }590 let rho = &pk[..32];591 let (ctilde, rest) = sig.split_at(p.ctilde_len);592 let zb = p.z_bits();593 let zs = 32 * zb as usize;594 let (z_bytes, h_bytes) = rest.split_at(zs * p.l);595596 let Some(h) = hint_unpack(p, h_bytes) else {597 return false;598 };599 let mut z_hat: Vec<Poly> = Vec::with_capacity(p.l);600 for chunk in z_bytes.chunks_exact(zs) {601 let z = bit_unpack(chunk, p.gamma1, zb);602 if inf_norm(&z) >= p.gamma1 - p.beta {603 return false;604 }605 z_hat.push(z);606 }607 z_hat.iter_mut().for_each(ntt);608609 let a = expand_a(p, rho);610 let mut c_hat = sample_in_ball(ctilde, p.tau);611 ntt(&mut c_hat);612613 let mut w1: Vec<Poly> = Vec::with_capacity(p.k);614 for i in 0..p.k {615 // t1·2^d ≤ 1023·2^13 = q − 1616 let mut t1 = simple_bit_unpack(&pk[32 + 320 * i..32 + 320 * (i + 1)], T1_BITS);617 for c in t1.c.iter_mut() {618 *c <<= D;619 }620 ntt(&mut t1);621 let ct1 = pointwise_montgomery(&c_hat, &t1);622 // Â ∘ ẑ − ĉ ∘ t̂1·2^d, then back to coefficients623 let mut acc = Poly::zero();624 for (aij, zj) in a[i].iter().zip(z_hat.iter()) {625 let t = pointwise_montgomery(aij, zj);626 add_assign(&mut acc, &t);627 }628 sub_assign(&mut acc, &ct1);629 poly_reduce(&mut acc);630 ntt_inv_tomont(&mut acc);631 poly_freeze(&mut acc);632 let mut hi = Poly::zero();633 for n in 0..N {634 hi.c[n] = use_hint(h[i].c[n] != 0, acc.c[n], p.gamma2);635 }636 w1.push(hi);637 }638 let mut w1_bytes = Vec::new();639 w1_encode(p, &w1, &mut w1_bytes);640 let mut expect = vec![0u8; p.ctilde_len];641 shake256(&[mu, &w1_bytes], &mut expect);642 ct::eq(&expect, ctilde)643}644645#[cfg(test)]646mod tests {647 use super::*;648649 #[test]650 fn sizes_match_fips204_table_2() {651 assert_eq!(652 (MLDSA_44.pk_len(), MLDSA_44.sk_len(), MLDSA_44.sig_len()),653 (1312, 2560, 2420)654 );655 assert_eq!(656 (MLDSA_65.pk_len(), MLDSA_65.sk_len(), MLDSA_65.sig_len()),657 (1952, 4032, 3309)658 );659 assert_eq!(660 (MLDSA_87.pk_len(), MLDSA_87.sk_len(), MLDSA_87.sig_len()),661 (2592, 4896, 4627)662 );663 }664665 #[test]666 fn sign_verify_round_trip_and_tamper() {667 for p in [MLDSA_44, MLDSA_65, MLDSA_87] {668 let (pk, sk) = keygen_internal(&p, &[5u8; 32]);669 assert_eq!(public_from_private(&p, &sk).unwrap(), pk);670 let msg: &[&[u8]] = &[b"hello ", b"world"];671 let sig = sign_internal(&p, &sk, msg, &[0u8; 32]).unwrap();672 assert_eq!(sig.len(), p.sig_len());673 assert!(verify_internal(&p, &pk, msg, &sig));674 assert!(675 verify_internal(&p, &pk, &[b"hello world"], &sig),676 "parts are concatenated"677 );678 assert!(!verify_internal(&p, &pk, &[b"hello worle"], &sig));679 // deterministic for a fixed rnd, different for another rnd680 assert_eq!(sign_internal(&p, &sk, msg, &[0u8; 32]).unwrap(), sig);681 let sig2 = sign_internal(&p, &sk, msg, &[1u8; 32]).unwrap();682 assert_ne!(sig2, sig);683 assert!(verify_internal(&p, &pk, msg, &sig2));684 // every region of the signature is covered by verification685 for pos in [686 0usize,687 p.ctilde_len,688 p.ctilde_len + 100,689 sig.len() - p.k - 1,690 sig.len() - 1,691 ] {692 let mut bad = sig.clone();693 bad[pos] ^= 0x04;694 assert!(!verify_internal(&p, &pk, msg, &bad), "flip at {pos}");695 }696 assert!(!verify_internal(&p, &pk, msg, &sig[..sig.len() - 1]));697 let mut bad_pk = pk.clone();698 bad_pk[40] ^= 1;699 assert!(!verify_internal(&p, &bad_pk, msg, &sig));700 }701 }702703 #[test]704 fn hint_encoding_is_strict() {705 let p = MLDSA_44;706 let mut y = vec![0u8; p.omega + p.k];707 assert!(hint_unpack(&p, &y).is_some());708 // two indices in poly 0, strictly increasing709 y[0] = 3;710 y[1] = 9;711 y[p.omega] = 2;712 y[p.omega + 1] = 2;713 y[p.omega + 2] = 2;714 y[p.omega + 3] = 2;715 let h = hint_unpack(&p, &y).unwrap();716 assert_eq!((h[0].c[3], h[0].c[9]), (1, 1));717 let mut out = vec![0u8; p.omega + p.k];718 hint_pack(&p, &h, &mut out);719 assert_eq!(out, y);720 // not increasing721 let mut bad = y.clone();722 bad[1] = 3;723 assert!(hint_unpack(&p, &bad).is_none());724 // decreasing cumulative counter725 let mut bad = y.clone();726 bad[p.omega + 1] = 1;727 assert!(hint_unpack(&p, &bad).is_none());728 // counter above ω729 let mut bad = y.clone();730 bad[p.omega + 3] = (p.omega + 1) as u8;731 assert!(hint_unpack(&p, &bad).is_none());732 // non-zero padding733 let mut bad = y.clone();734 bad[5] = 1;735 assert!(hint_unpack(&p, &bad).is_none());736 }737738 #[test]739 fn private_key_decoding_is_strict() {740 let p = MLDSA_44;741 let (_pk, sk) = keygen_internal(&p, &[6u8; 32]);742 assert!(check_private_key(&p, &sk).is_ok());743 assert_eq!(check_private_key(&p, &sk[1..]), Err(Error::InvalidLength));744 // η = 2 uses 3 bits per coefficient; the value 7 decodes to 2 − 7 = −5 ∉ [−2, 2]745 let mut bad = sk.clone();746 bad[128] |= 0x07;747 assert_eq!(check_private_key(&p, &bad), Err(Error::InvalidPrivateKey));748 // a consistent-looking key with a different tr does not yield a public key749 let mut bad = sk.clone();750 bad[70] ^= 1;751 assert_eq!(public_from_private(&p, &bad), Err(Error::InvalidPrivateKey));752 }753}754