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/hash/keccak.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//! Keccak-f[1600], the sponge construction, SHA-3 and SHAKE (FIPS 202).42//!43//! Standard mapping:44//!45//! | FIPS 202 | Here |46//! |------------------------------|----------------------------------------|47//! | §3.2 step mappings θ ρ π χ ι | [`keccak_f1600`] |48//! | Alg. 5 `rc(t)` | `round_constants` (compile-time LFSR) |49//! | §3.2.2 ρ offsets | `rho_offsets` (compile-time) |50//! | §4 `SPONGE`, Alg. 8 | [`Sponge`] |51//! | §5.1 `pad10*1`, §6 suffixes | [`Sponge::finalize`] (`0x06` / `0x1F`) |52//! | §6.1 SHA3-224/256/384/512 | [`Sha3`] |53//! | §6.2 SHAKE128/256 | [`Shake`] |54//!55//! The state is 25 lanes of 64 bits, lane `(x, y)` at index `x + 5y`, bytes in56//! little-endian order inside a lane (FIPS 202 §3.1.2 / B.1). The permutation57//! is data-independent: no secret-dependent branch or table index.5859use crate::ct::wipe;6061const ROUNDS: usize = 24;6263/// Round constants from the LFSR of FIPS 202 Algorithm 5, evaluated at compile time.64const fn round_constants() -> [u64; ROUNDS] {65 let mut rc = [0u64; ROUNDS];66 let mut r: u16 = 1; // LFSR state, bit i = R[i]67 let mut ir = 0;68 while ir < ROUNDS {69 let mut j = 0;70 while j <= 6 {71 // rc(j + 7*ir) is the current R[0]72 if r & 1 == 1 {73 rc[ir] |= 1u64 << ((1u32 << j) - 1);74 }75 // advance the LFSR one step: R = 0 || R, then feedback from R[8]76 r <<= 1;77 if r & 0x100 != 0 {78 r ^= 0x171;79 }80 j += 1;81 }82 ir += 1;83 }84 rc85}8687/// ρ rotation offsets (FIPS 202 Alg. 2), indexed by `x + 5y`, at compile time.88const fn rho_offsets() -> [u32; 25] {89 let mut off = [0u32; 25];90 let (mut x, mut y) = (1usize, 0usize);91 let mut t = 0u32;92 while t < 24 {93 off[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64;94 let nx = y;95 let ny = (2 * x + 3 * y) % 5;96 x = nx;97 y = ny;98 t += 1;99 }100 off101}102103const RC: [u64; ROUNDS] = round_constants();104const RHO: [u32; 25] = rho_offsets();105106/// The Keccak-p[1600, 24] permutation (FIPS 202 §3.3).107pub fn keccak_f1600(a: &mut [u64; 25]) {108 for rc in RC.iter() {109 // θ110 let mut c = [0u64; 5];111 for x in 0..5 {112 c[x] = a[x] ^ a[x + 5] ^ a[x + 10] ^ a[x + 15] ^ a[x + 20];113 }114 for x in 0..5 {115 let d = c[(x + 4) % 5] ^ c[(x + 1) % 5].rotate_left(1);116 for y in 0..5 {117 a[x + 5 * y] ^= d;118 }119 }120 // ρ and π: B[y, 2x+3y] = rot(A[x, y], r[x, y])121 let mut b = [0u64; 25];122 for x in 0..5 {123 for y in 0..5 {124 let nx = y;125 let ny = (2 * x + 3 * y) % 5;126 b[nx + 5 * ny] = a[x + 5 * y].rotate_left(RHO[x + 5 * y]);127 }128 }129 // χ130 for y in 0..5 {131 for x in 0..5 {132 a[x + 5 * y] = b[x + 5 * y] ^ (!b[(x + 1) % 5 + 5 * y] & b[(x + 2) % 5 + 5 * y]);133 }134 }135 // ι136 a[0] ^= *rc;137 }138}139140/// Byte-oriented sponge over Keccak-f[1600] with `pad10*1` and a domain suffix.141///142/// The state is wiped on drop because the sponge is routinely keyed with secrets143/// (PRFs of ML-KEM / ML-DSA / SLH-DSA).144#[derive(Clone)]145pub struct Sponge {146 state: [u64; 25],147 rate: usize,148 pos: usize,149 suffix: u8,150 squeezing: bool,151}152153impl Sponge {154 /// New sponge with the given rate in bytes and domain-separation suffix155 /// (`0x06` for SHA-3, `0x1F` for SHAKE; the suffix already contains the156 /// first padding bit).157 pub const fn new(rate: usize, suffix: u8) -> Self {158 assert!(rate > 0 && rate < 200 && rate % 8 == 0);159 Sponge {160 state: [0; 25],161 rate,162 pos: 0,163 suffix,164 squeezing: false,165 }166 }167168 #[inline]169 fn xor_byte(&mut self, i: usize, b: u8) {170 self.state[i / 8] ^= (b as u64) << (8 * (i % 8));171 }172173 #[inline]174 fn get_byte(&self, i: usize) -> u8 {175 (self.state[i / 8] >> (8 * (i % 8))) as u8176 }177178 /// Absorbs `data`. Panics if called after squeezing started (API misuse, public).179 pub fn absorb(&mut self, mut data: &[u8]) {180 assert!(!self.squeezing, "absorb after squeeze");181 // complete a partial block182 while self.pos != 0 && !data.is_empty() {183 self.xor_byte(self.pos, data[0]);184 data = &data[1..];185 self.pos += 1;186 if self.pos == self.rate {187 keccak_f1600(&mut self.state);188 self.pos = 0;189 }190 }191 // whole blocks, lane by lane192 while data.len() >= self.rate {193 let (block, rest) = data.split_at(self.rate);194 for (lane, chunk) in self.state.iter_mut().zip(block.chunks_exact(8)) {195 let mut w = [0u8; 8];196 w.copy_from_slice(chunk);197 *lane ^= u64::from_le_bytes(w);198 }199 keccak_f1600(&mut self.state);200 data = rest;201 }202 // tail203 for &b in data {204 self.xor_byte(self.pos, b);205 self.pos += 1;206 }207 }208209 /// Applies the suffix and `pad10*1`, then switches to squeezing.210 pub fn finalize(&mut self) {211 if self.squeezing {212 return;213 }214 self.xor_byte(self.pos, self.suffix);215 self.xor_byte(self.rate - 1, 0x80);216 keccak_f1600(&mut self.state);217 self.pos = 0;218 self.squeezing = true;219 }220221 /// Squeezes `out.len()` bytes; may be called repeatedly (XOF stream).222 pub fn squeeze(&mut self, out: &mut [u8]) {223 self.finalize();224 for o in out.iter_mut() {225 if self.pos == self.rate {226 keccak_f1600(&mut self.state);227 self.pos = 0;228 }229 *o = self.get_byte(self.pos);230 self.pos += 1;231 }232 }233}234235impl Drop for Sponge {236 fn drop(&mut self) {237 wipe(&mut self.state);238 }239}240241/// SHA-3 fixed-output hash (FIPS 202 §6.1): capacity is twice the output length.242#[derive(Clone)]243pub struct Sha3 {244 sponge: Sponge,245 out_len: usize,246}247248impl Sha3 {249 const fn with_output(out_len: usize) -> Self {250 Sha3 {251 sponge: Sponge::new(200 - 2 * out_len, 0x06),252 out_len,253 }254 }255 /// SHA3-224.256 pub const fn new_224() -> Self {257 Self::with_output(28)258 }259 /// SHA3-256.260 pub const fn new_256() -> Self {261 Self::with_output(32)262 }263 /// SHA3-384.264 pub const fn new_384() -> Self {265 Self::with_output(48)266 }267 /// SHA3-512.268 pub const fn new_512() -> Self {269 Self::with_output(64)270 }271 /// Digest length in bytes.272 pub const fn output_len(&self) -> usize {273 self.out_len274 }275 /// Absorbs more input.276 pub fn update(&mut self, data: &[u8]) {277 self.sponge.absorb(data);278 }279 /// Writes the digest into `out`, which must be exactly `output_len()` bytes.280 pub fn finalize_into(mut self, out: &mut [u8]) {281 assert_eq!(out.len(), self.out_len);282 self.sponge.squeeze(out);283 }284}285286/// SHAKE extendable-output function (FIPS 202 §6.2).287#[derive(Clone)]288pub struct Shake {289 sponge: Sponge,290}291292impl Shake {293 /// SHAKE128 (rate 168 bytes).294 pub const fn new_128() -> Self {295 Shake {296 sponge: Sponge::new(168, 0x1F),297 }298 }299 /// SHAKE256 (rate 136 bytes).300 pub const fn new_256() -> Self {301 Shake {302 sponge: Sponge::new(136, 0x1F),303 }304 }305 /// Absorbs more input (before the first squeeze).306 pub fn absorb(&mut self, data: &[u8]) {307 self.sponge.absorb(data);308 }309 /// Squeezes the next `out.len()` bytes of the output stream.310 pub fn squeeze(&mut self, out: &mut [u8]) {311 self.sponge.squeeze(out);312 }313}314315/// One-shot SHA3-256.316pub fn sha3_256(data: &[u8]) -> [u8; 32] {317 let mut h = Sha3::new_256();318 h.update(data);319 let mut out = [0u8; 32];320 h.finalize_into(&mut out);321 out322}323324/// One-shot SHA3-512.325pub fn sha3_512(data: &[u8]) -> [u8; 64] {326 let mut h = Sha3::new_512();327 h.update(data);328 let mut out = [0u8; 64];329 h.finalize_into(&mut out);330 out331}332333/// One-shot SHAKE128 over the concatenation of `parts`.334pub fn shake128(parts: &[&[u8]], out: &mut [u8]) {335 let mut x = Shake::new_128();336 for p in parts {337 x.absorb(p);338 }339 x.squeeze(out);340}341342/// One-shot SHAKE256 over the concatenation of `parts`.343pub fn shake256(parts: &[&[u8]], out: &mut [u8]) {344 let mut x = Shake::new_256();345 for p in parts {346 x.absorb(p);347 }348 x.squeeze(out);349}350351#[cfg(test)]352mod tests {353 use super::*;354355 fn hex(b: &[u8]) -> String {356 b.iter().map(|x| format!("{x:02x}")).collect()357 }358359 #[test]360 fn round_constants_match_fips202() {361 // First, second and last constants as printed in the Keccak reference.362 assert_eq!(RC[0], 0x0000_0000_0000_0001);363 assert_eq!(RC[1], 0x0000_0000_0000_8082);364 assert_eq!(RC[2], 0x8000_0000_0000_808A);365 assert_eq!(RC[23], 0x8000_0000_8000_8008);366 }367368 #[test]369 fn rho_offsets_match_fips202_table2() {370 // Table 2 of FIPS 202 (offsets mod 64), row y, column x.371 assert_eq!(RHO[0], 0);372 assert_eq!(RHO[1], 1);373 assert_eq!(RHO[2], 190 % 64);374 assert_eq!(RHO[3], 28);375 assert_eq!(RHO[4], 91 % 64);376 assert_eq!(RHO[5], 36);377 assert_eq!(RHO[1 + 5], 300 % 64);378 assert_eq!(RHO[4 + 5 * 4], 78 % 64);379 }380381 #[test]382 fn sha3_empty_and_abc() {383 assert_eq!(384 hex(&sha3_256(b"")),385 "a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a"386 );387 assert_eq!(388 hex(&sha3_256(b"abc")),389 "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532"390 );391 assert_eq!(392 hex(&sha3_512(b"abc")),393 "b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e\394 10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0"395 );396 }397398 #[test]399 fn shake_empty() {400 let mut o = [0u8; 32];401 shake128(&[], &mut o);402 assert_eq!(403 hex(&o),404 "7f9c2ba4e88f827d616045507605853ed73b8093f6efbc88eb1a6eacfa66ef26"405 );406 shake256(&[], &mut o);407 assert_eq!(408 hex(&o),409 "46b9dd2b0ba88d13233b3feb743eeb243fcd52ea62b81b82b50c27646ed5762f"410 );411 }412413 #[test]414 fn incremental_equals_one_shot_across_block_boundaries() {415 let data: Vec<u8> = (0..1000u32).map(|i| (i * 7 + 3) as u8).collect();416 for split in [417 0usize, 1, 7, 8, 135, 136, 137, 167, 168, 169, 272, 999, 1000,418 ] {419 let mut x = Shake::new_256();420 x.absorb(&data[..split]);421 x.absorb(&data[split..]);422 let mut a = [0u8; 500];423 // squeeze in uneven pieces424 let (p, q) = a.split_at_mut(137);425 x.squeeze(p);426 x.squeeze(q);427 let mut b = [0u8; 500];428 shake256(&[&data], &mut b);429 assert_eq!(a[..], b[..], "split {split}");430 }431 }432}433