Skip to main content

quantaegis_sha3/
lib.rs

1//! From-scratch, pure-Rust, `#![no_std]` implementation of **NIST FIPS 202**
2//! (SHA-3 Standard: Permutation-Based Hash and Extendable-Output Functions).
3//!
4//! Provides the four FIPS 202 primitives required by **FIPS 203 (ML-KEM)**,
5//! **FIPS 204 (ML-DSA)**, and **FIPS 205 (SLH-DSA)**:
6//! - [`Sha3_256`] (`H` in ML-KEM, 32-byte digest, rate = 136 bytes)
7//! - [`Sha3_512`] (`G` in ML-KEM, 64-byte digest, rate = 72 bytes)
8//! - [`Shake128`] / [`Shake128Reader`] (`XOF` in ML-KEM, rate = 168 bytes)
9//! - [`Shake256`] / [`Shake256Reader`] (`J` and `PRF` in ML-KEM, rate = 136 bytes)
10//!
11//! # Security Properties
12//! - Zero external cryptographic dependencies; `#![forbid(unsafe_code)]`; `#![no_std]`.
13//! - All internal `Keccak-f[1600]` states and byte buffers are automatically zeroized on drop.
14//! - Constant-time bitwise permutation with no secret-dependent branching or table lookups.
15
16#![no_std]
17#![forbid(unsafe_code)]
18
19mod keccak;
20mod sponge;
21
22use quantaegis_core::Zeroize;
23
24use crate::sponge::{Sponge, XofReader};
25
26/// Domain separation byte for SHA-3 fixed-output hashes (`01` suffix + `pad10*1` -> `0x06`).
27const SHA3_DOMAIN: u8 = 0x06;
28
29/// Domain separation byte for SHAKE XOFs (`1111` suffix + `pad10*1` -> `0x1F`).
30const SHAKE_DOMAIN: u8 = 0x1F;
31
32/// Returns `true` iff the sum of chunk lengths is strictly less than `RATE` (without overflowing).
33#[inline]
34fn fits_single_block<const RATE: usize>(chunks: &[&[u8]]) -> bool {
35    chunks
36        .iter()
37        .try_fold(0usize, |acc, c| acc.checked_add(c.len()))
38        .is_some_and(|total| total < RATE)
39}
40
41/// **SHA3-256** hash function (FIPS 202, Section 6.1).
42///
43/// Rate = 136 bytes (1088 bits), capacity = 64 bytes (512 bits), output = 32 bytes (256 bits).
44pub struct Sha3_256 {
45    sponge: Sponge<136, SHA3_DOMAIN>,
46}
47
48impl Sha3_256 {
49    /// Output digest length in bytes (32).
50    pub const DIGEST_LEN: usize = 32;
51
52    /// Creates a new SHA3-256 hasher.
53    pub const fn new() -> Self {
54        Self {
55            sponge: Sponge::new(),
56        }
57    }
58
59    /// Absorbs `data` into the hasher state.
60    pub fn update(&mut self, data: &[u8]) {
61        self.sponge.absorb(data);
62    }
63
64    /// Finalizes the hash and returns the 32-byte digest.
65    ///
66    /// Finalizes `self.sponge` in place via `&mut` so `Drop` zeroizes the caller's original
67    /// sponge storage (state and input buffer) without creating an unzeroized stack copy.
68    pub fn finalize(mut self) -> [u8; Self::DIGEST_LEN] {
69        let mut out = [0u8; Self::DIGEST_LEN];
70        self.sponge.finalize_and_squeeze(&mut out);
71        out
72    }
73
74    /// Computes `SHA3-256(data)` in one shot.
75    pub fn digest(data: &[u8]) -> [u8; Self::DIGEST_LEN] {
76        Self::digest_chunks(&[data])
77    }
78
79    /// Computes `SHA3-256(chunks[0] || chunks[1] || ...)` in one shot.
80    ///
81    /// Inputs shorter than one rate block (`< 136` bytes) absorb directly into an in-place
82    /// Keccak state without allocating an intermediate byte buffer or copying the state on return.
83    pub fn digest_chunks(chunks: &[&[u8]]) -> [u8; Self::DIGEST_LEN] {
84        let mut out = [0u8; Self::DIGEST_LEN];
85        if fits_single_block::<136>(chunks) {
86            let mut reader = XofReader::<136>::new_zero();
87            reader.absorb_single_block_in_place::<SHA3_DOMAIN>(chunks);
88            reader.squeeze(&mut out);
89            return out;
90        }
91        let mut hasher = Self::new();
92        for &chunk in chunks {
93            hasher.update(chunk);
94        }
95        hasher.sponge.finalize_and_squeeze(&mut out);
96        out
97    }
98}
99
100impl Default for Sha3_256 {
101    fn default() -> Self {
102        Self::new()
103    }
104}
105
106impl Zeroize for Sha3_256 {
107    fn zeroize(&mut self) {
108        self.sponge.zeroize();
109    }
110}
111
112/// **SHA3-512** hash function (FIPS 202, Section 6.1).
113///
114/// Rate = 72 bytes (576 bits), capacity = 128 bytes (1024 bits), output = 64 bytes (512 bits).
115pub struct Sha3_512 {
116    sponge: Sponge<72, SHA3_DOMAIN>,
117}
118
119impl Sha3_512 {
120    /// Output digest length in bytes (64).
121    pub const DIGEST_LEN: usize = 64;
122
123    /// Creates a new SHA3-512 hasher.
124    pub const fn new() -> Self {
125        Self {
126            sponge: Sponge::new(),
127        }
128    }
129
130    /// Absorbs `data` into the hasher state.
131    pub fn update(&mut self, data: &[u8]) {
132        self.sponge.absorb(data);
133    }
134
135    /// Finalizes the hash and returns the 64-byte digest.
136    ///
137    /// Finalizes `self.sponge` in place via `&mut` so `Drop` zeroizes the caller's original
138    /// sponge storage (state and input buffer) without creating an unzeroized stack copy.
139    pub fn finalize(mut self) -> [u8; Self::DIGEST_LEN] {
140        let mut out = [0u8; Self::DIGEST_LEN];
141        self.sponge.finalize_and_squeeze(&mut out);
142        out
143    }
144
145    /// Computes `SHA3-512(data)` in one shot.
146    pub fn digest(data: &[u8]) -> [u8; Self::DIGEST_LEN] {
147        Self::digest_chunks(&[data])
148    }
149
150    /// Computes `SHA3-512(chunks[0] || chunks[1] || ...)` directly into `out`.
151    ///
152    /// Inputs shorter than one rate block (`< 72` bytes) absorb directly into an in-place
153    /// Keccak state without allocating an intermediate byte buffer or copying the digest on
154    /// return.
155    pub fn digest_chunks_into(chunks: &[&[u8]], out: &mut [u8; Self::DIGEST_LEN]) {
156        if fits_single_block::<72>(chunks) {
157            let mut reader = XofReader::<72>::new_zero();
158            reader.absorb_single_block_in_place::<SHA3_DOMAIN>(chunks);
159            reader.squeeze(out);
160            return;
161        }
162        let mut hasher = Self::new();
163        for &chunk in chunks {
164            hasher.update(chunk);
165        }
166        hasher.sponge.finalize_and_squeeze(out);
167    }
168
169    /// Computes `SHA3-512(chunks[0] || chunks[1] || ...)` in one shot.
170    ///
171    /// Inputs shorter than one rate block (`< 72` bytes) absorb directly into an in-place
172    /// Keccak state without allocating an intermediate byte buffer or copying the state on return.
173    pub fn digest_chunks(chunks: &[&[u8]]) -> [u8; Self::DIGEST_LEN] {
174        let mut out = [0u8; Self::DIGEST_LEN];
175        Self::digest_chunks_into(chunks, &mut out);
176        out
177    }
178}
179
180impl Default for Sha3_512 {
181    fn default() -> Self {
182        Self::new()
183    }
184}
185
186impl Zeroize for Sha3_512 {
187    fn zeroize(&mut self) {
188        self.sponge.zeroize();
189    }
190}
191
192/// **SHAKE128** extendable-output function (FIPS 202, Section 6.2).
193///
194/// Rate = 168 bytes (1344 bits), capacity = 32 bytes (256 bits).
195pub struct Shake128 {
196    sponge: Sponge<168, SHAKE_DOMAIN>,
197}
198
199impl Shake128 {
200    /// Creates a new SHAKE128 instance in the absorbing phase.
201    pub const fn new() -> Self {
202        Self {
203            sponge: Sponge::new(),
204        }
205    }
206
207    /// Absorbs `data` into the XOF state.
208    pub fn update(&mut self, data: &[u8]) {
209        self.sponge.absorb(data);
210    }
211
212    /// Finalizes absorption and transitions to a streaming [`Shake128Reader`].
213    ///
214    /// Finalizes `self.sponge` in place via `&mut`, constructs the returned reader directly in
215    /// the caller's return slot, and zeroizes the original `self.sponge` (state + buffer) on drop.
216    pub fn finalize_xof(mut self) -> Shake128Reader {
217        self.sponge.finalize_absorb();
218        Shake128Reader {
219            reader: XofReader::from_state_array(self.sponge.state_array()),
220        }
221    }
222
223    /// Absorbs `chunks` and returns a finalized [`Shake128Reader`].
224    ///
225    /// Inputs shorter than one rate block (`< 168` bytes) absorb directly into an in-place
226    /// Keccak state (zeroized on drop) without allocating an intermediate byte buffer.
227    pub fn xof_reader_from_chunks(chunks: &[&[u8]]) -> Shake128Reader {
228        if fits_single_block::<168>(chunks) {
229            let mut tmp = XofReader::<168>::new_zero();
230            tmp.absorb_single_block_in_place::<SHAKE_DOMAIN>(chunks);
231            return Shake128Reader {
232                reader: XofReader::from_state_array(tmp.state_array()),
233            };
234        }
235        let mut hasher = Self::new();
236        for &chunk in chunks {
237            hasher.update(chunk);
238        }
239        hasher.sponge.finalize_absorb();
240        Shake128Reader {
241            reader: XofReader::from_state_array(hasher.sponge.state_array()),
242        }
243    }
244
245    /// Computes `SHAKE128(data, out.len() * 8)` in one shot, writing into `out`.
246    pub fn xof(data: &[u8], out: &mut [u8]) {
247        Self::xof_chunks(&[data], out);
248    }
249
250    /// Finalizes absorption in place and squeezes `out.len()` bytes directly into `out`.
251    ///
252    /// Unlike [`Self::finalize_xof`], this takes `&mut self` so the sponge is never copied by
253    /// value onto a callee's stack frame before `Drop` zeroizes it.
254    pub fn finalize_xof_into(&mut self, out: &mut [u8]) {
255        self.sponge.finalize_and_squeeze(out);
256    }
257
258    /// Computes `SHAKE128(chunks[0] || chunks[1] || ..., out.len() * 8)` in one shot.
259    pub fn xof_chunks(chunks: &[&[u8]], out: &mut [u8]) {
260        if fits_single_block::<168>(chunks) {
261            let mut reader = XofReader::<168>::new_zero();
262            reader.absorb_single_block_in_place::<SHAKE_DOMAIN>(chunks);
263            reader.squeeze(out);
264            return;
265        }
266        let mut hasher = Self::new();
267        for &chunk in chunks {
268            hasher.update(chunk);
269        }
270        hasher.sponge.finalize_and_squeeze(out);
271    }
272}
273
274impl Default for Shake128 {
275    fn default() -> Self {
276        Self::new()
277    }
278}
279
280impl Zeroize for Shake128 {
281    fn zeroize(&mut self) {
282        self.sponge.zeroize();
283    }
284}
285
286/// Streaming output reader for [`Shake128`].
287///
288/// Supports arbitrary chunk sizes (e.g., 168-byte rate blocks or 3-byte chunks) and zeroizes
289/// its internal Keccak state automatically on drop.
290pub struct Shake128Reader {
291    reader: XofReader<168>,
292}
293
294impl Shake128Reader {
295    /// Squeezes the next `out.len()` bytes from the XOF stream.
296    pub fn squeeze(&mut self, out: &mut [u8]) {
297        self.reader.squeeze(out);
298    }
299}
300
301impl Zeroize for Shake128Reader {
302    fn zeroize(&mut self) {
303        self.reader.zeroize();
304    }
305}
306
307/// **SHAKE256** extendable-output function (FIPS 202, Section 6.2).
308///
309/// Rate = 136 bytes (1088 bits), capacity = 64 bytes (512 bits).
310pub struct Shake256 {
311    sponge: Sponge<136, SHAKE_DOMAIN>,
312}
313
314impl Shake256 {
315    /// Creates a new SHAKE256 instance in the absorbing phase.
316    pub const fn new() -> Self {
317        Self {
318            sponge: Sponge::new(),
319        }
320    }
321
322    /// Absorbs `data` into the XOF state.
323    pub fn update(&mut self, data: &[u8]) {
324        self.sponge.absorb(data);
325    }
326
327    /// Finalizes absorption and transitions to a streaming [`Shake256Reader`].
328    ///
329    /// Finalizes `self.sponge` in place via `&mut`, constructs the returned reader directly in
330    /// the caller's return slot, and zeroizes the original `self.sponge` (state + buffer) on drop.
331    pub fn finalize_xof(mut self) -> Shake256Reader {
332        self.sponge.finalize_absorb();
333        Shake256Reader {
334            reader: XofReader::from_state_array(self.sponge.state_array()),
335        }
336    }
337
338    /// Absorbs `chunks` and returns a finalized [`Shake256Reader`].
339    ///
340    /// Inputs shorter than one rate block (`< 136` bytes) absorb directly into an in-place
341    /// Keccak state (zeroized on drop) without allocating an intermediate byte buffer.
342    pub fn xof_reader_from_chunks(chunks: &[&[u8]]) -> Shake256Reader {
343        if fits_single_block::<136>(chunks) {
344            let mut tmp = XofReader::<136>::new_zero();
345            tmp.absorb_single_block_in_place::<SHAKE_DOMAIN>(chunks);
346            return Shake256Reader {
347                reader: XofReader::from_state_array(tmp.state_array()),
348            };
349        }
350        let mut hasher = Self::new();
351        for &chunk in chunks {
352            hasher.update(chunk);
353        }
354        hasher.sponge.finalize_absorb();
355        Shake256Reader {
356            reader: XofReader::from_state_array(hasher.sponge.state_array()),
357        }
358    }
359
360    /// Finalizes absorption in place and squeezes `out.len()` bytes directly into `out`.
361    ///
362    /// Unlike [`Self::finalize_xof`], this takes `&mut self` so the sponge is never copied by
363    /// value onto a callee's stack frame before `Drop` zeroizes it.
364    pub fn finalize_xof_into(&mut self, out: &mut [u8]) {
365        self.sponge.finalize_and_squeeze(out);
366    }
367
368    /// Computes `SHAKE256(data, out.len() * 8)` in one shot, writing into `out`.
369    pub fn xof(data: &[u8], out: &mut [u8]) {
370        Self::xof_chunks(&[data], out);
371    }
372
373    /// Computes `SHAKE256(chunks[0] || chunks[1] || ..., out.len() * 8)` in one shot.
374    ///
375    /// Inputs shorter than one rate block (`< 136` bytes) absorb directly into an in-place
376    /// Keccak state without allocating an intermediate byte buffer or copying the state on return.
377    pub fn xof_chunks(chunks: &[&[u8]], out: &mut [u8]) {
378        if fits_single_block::<136>(chunks) {
379            let mut reader = XofReader::<136>::new_zero();
380            reader.absorb_single_block_in_place::<SHAKE_DOMAIN>(chunks);
381            reader.squeeze(out);
382            return;
383        }
384        let mut hasher = Self::new();
385        for &chunk in chunks {
386            hasher.update(chunk);
387        }
388        hasher.sponge.finalize_and_squeeze(out);
389    }
390}
391
392impl Default for Shake256 {
393    fn default() -> Self {
394        Self::new()
395    }
396}
397
398impl Zeroize for Shake256 {
399    fn zeroize(&mut self) {
400        self.sponge.zeroize();
401    }
402}
403
404/// Streaming output reader for [`Shake256`].
405///
406/// Zeroizes its internal Keccak state automatically on drop.
407pub struct Shake256Reader {
408    reader: XofReader<136>,
409}
410
411impl Shake256Reader {
412    /// Squeezes the next `out.len()` bytes from the XOF stream.
413    pub fn squeeze(&mut self, out: &mut [u8]) {
414        self.reader.squeeze(out);
415    }
416}
417
418impl Zeroize for Shake256Reader {
419    fn zeroize(&mut self) {
420        self.reader.zeroize();
421    }
422}
423
424#[cfg(test)]
425mod tests {
426    use super::*;
427
428    fn hex_to_bytes<const N: usize>(hex: &str) -> [u8; N] {
429        assert_eq!(hex.len(), N * 2);
430        let bytes = hex.as_bytes();
431        let mut out = [0u8; N];
432        let mut i = 0;
433        while i < N {
434            let hi = hex_nibble(bytes[2 * i]);
435            let lo = hex_nibble(bytes[2 * i + 1]);
436            out[i] = (hi << 4) | lo;
437            i += 1;
438        }
439        out
440    }
441
442    fn hex_nibble(b: u8) -> u8 {
443        match b {
444            b'0'..=b'9' => b - b'0',
445            b'a'..=b'f' => b - b'a' + 10,
446            b'A'..=b'F' => b - b'A' + 10,
447            _ => unreachable!("invalid hex character in test vector"),
448        }
449    }
450
451    #[test]
452    fn nist_sha3_256_known_answer_tests() {
453        // Empty input ""
454        assert_eq!(
455            Sha3_256::digest(b""),
456            hex_to_bytes::<32>("a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a")
457        );
458
459        // "abc"
460        assert_eq!(
461            Sha3_256::digest(b"abc"),
462            hex_to_bytes::<32>("3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532")
463        );
464
465        // 448-bit standard message
466        assert_eq!(
467            Sha3_256::digest(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"),
468            hex_to_bytes::<32>("41c0dba2a9d6240849100376a8235e2c82e1b9998a999e21db32dd97496d3376")
469        );
470    }
471
472    #[test]
473    fn nist_sha3_512_known_answer_tests() {
474        // Empty input ""
475        assert_eq!(
476            Sha3_512::digest(b""),
477            hex_to_bytes::<64>(
478                "a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a6\
479                 15b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26"
480            )
481        );
482
483        // "abc"
484        assert_eq!(
485            Sha3_512::digest(b"abc"),
486            hex_to_bytes::<64>(
487                "b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e\
488                 10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0"
489            )
490        );
491    }
492
493    #[test]
494    fn nist_shake128_known_answer_tests() {
495        // Empty input "" (32 bytes)
496        let mut out = [0u8; 32];
497        Shake128::xof(b"", &mut out);
498        assert_eq!(
499            out,
500            hex_to_bytes::<32>("7f9c2ba4e88f827d616045507605853ed73b8093f6efbc88eb1a6eacfa66ef26")
501        );
502
503        // "abc" (32 bytes)
504        Shake128::xof(b"abc", &mut out);
505        assert_eq!(
506            out,
507            hex_to_bytes::<32>("5881092dd818bf5cf8a3ddb793fbcba74097d5c526a6d35f97b83351940f2cc8")
508        );
509    }
510
511    #[test]
512    fn nist_shake256_known_answer_tests() {
513        // Empty input "" (32 bytes)
514        let mut out = [0u8; 32];
515        Shake256::xof(b"", &mut out);
516        assert_eq!(
517            out,
518            hex_to_bytes::<32>("46b9dd2b0ba88d13233b3feb743eeb243fcd52ea62b81b82b50c27646ed5762f")
519        );
520
521        // "abc" (32 bytes)
522        Shake256::xof(b"abc", &mut out);
523        assert_eq!(
524            out,
525            hex_to_bytes::<32>("483366601360a8771c6863080cc4114d8db44530f8f1e1ee4f94ea37e78b5739")
526        );
527    }
528
529    #[test]
530    fn nist_multiblock_200byte_a3_vectors() {
531        // 1600-bit (200-byte) 0xA3 message crosses the rate boundary of every FIPS 202 variant
532        // (SHA3-512: 72B, SHA3-256 / SHAKE256: 136B, SHAKE128: 168B).
533        let msg = [0xA3u8; 200];
534
535        assert_eq!(
536            Sha3_256::digest(&msg),
537            hex_to_bytes::<32>("79f38adec5c20307a98ef76e8324afbfd46cfd81b22e3973c65fa1bd9de31787")
538        );
539
540        assert_eq!(
541            Sha3_512::digest(&msg),
542            hex_to_bytes::<64>(
543                "e76dfad22084a8b1467fcf2ffa58361bec7628edf5f3fdc0e4805dc48caeeca8\
544                 1b7c13c30adf52a3659584739a2df46be589c51ca1a4a8416df6545a1ce8ba00"
545            )
546        );
547
548        // 200-byte XOF outputs also cross the squeeze rate boundaries (168B and 136B).
549        let mut shake128_out = [0u8; 200];
550        Shake128::xof(&msg, &mut shake128_out);
551        assert_eq!(
552            shake128_out,
553            hex_to_bytes::<200>(
554                "131ab8d2b594946b9c81333f9bb6e0ce75c3b93104fa3469d3917457385da037\
555                 cf232ef7164a6d1eb448c8908186ad852d3f85a5cf28da1ab6fe343817197846\
556                 7f1c05d58c7ef38c284c41f6c2221a76f12ab1c04082660250802294fb871802\
557                 13fdef5b0ecb7df50ca1f8555be14d32e10f6edcde892c09424b29f597afc270\
558                 c904556bfcb47a7d40778d390923642b3cbd0579e60908d5a000c1d08b98ef93\
559                 3f806445bf87f8b009ba9e94f7266122ed7ac24e5e266c42a82fa1bbefb7b8db\
560                 0066e16a85e0493f"
561            )
562        );
563
564        let mut shake256_out = [0u8; 200];
565        Shake256::xof(&msg, &mut shake256_out);
566        assert_eq!(
567            shake256_out,
568            hex_to_bytes::<200>(
569                "cd8a920ed141aa0407a22d59288652e9d9f1a7ee0c1e7c1ca699424da84a904d\
570                 2d700caae7396ece96604440577da4f3aa22aeb8857f961c4cd8e06f0ae6610b\
571                 1048a7f64e1074cd629e85ad7566048efc4fb500b486a3309a8f26724c0ed628\
572                 001a1099422468de726f1061d99eb9e93604d5aa7467d4b1bd6484582a384317\
573                 d7f47d750b8f5499512bb85a226c4243556e696f6bd072c5aa2d9b69730244b5\
574                 6853d16970ad817e213e470618178001c9fb56c54fefa5fee67d2da524bb3b0b\
575                 61ef0e9114a92cdb"
576            )
577        );
578    }
579
580    #[test]
581    fn streaming_absorb_and_squeeze_matches_oneshot_across_block_boundaries() {
582        // Test crossing rate boundaries for all 4 algorithms (input > 168 bytes, output > 504 bytes)
583        let mut msg = [0u8; 400];
584        for (i, b) in msg.iter_mut().enumerate() {
585            *b = u8::try_from(i % 251).unwrap_or(0);
586        }
587
588        // SHA3-256: chunked 17 bytes vs one-shot
589        let oneshot_256 = Sha3_256::digest(&msg);
590        let mut h256 = Sha3_256::new();
591        for chunk in msg.chunks(17) {
592            h256.update(chunk);
593        }
594        assert_eq!(h256.finalize(), oneshot_256);
595
596        // SHA3-512: chunked 13 bytes vs one-shot (rate = 72)
597        let oneshot_512 = Sha3_512::digest(&msg);
598        let mut h512 = Sha3_512::new();
599        for chunk in msg.chunks(13) {
600            h512.update(chunk);
601        }
602        assert_eq!(h512.finalize(), oneshot_512);
603
604        // SHAKE128: absorb in 19-byte chunks, squeeze in 3-byte chunks (ML-KEM SampleNTT pattern)
605        let mut oneshot_xof128 = [0u8; 512];
606        Shake128::xof(&msg, &mut oneshot_xof128);
607
608        let mut x128 = Shake128::new();
609        for chunk in msg.chunks(19) {
610            x128.update(chunk);
611        }
612        let mut reader128 = x128.finalize_xof();
613        let mut streamed_xof128 = [0u8; 512];
614        for chunk in streamed_xof128.chunks_mut(3) {
615            reader128.squeeze(chunk);
616        }
617        assert_eq!(streamed_xof128, oneshot_xof128);
618
619        // SHAKE256: absorb in 29-byte chunks, squeeze in 7-byte chunks across rate=136 boundary
620        let mut oneshot_xof256 = [0u8; 512];
621        Shake256::xof(&msg, &mut oneshot_xof256);
622
623        let mut x256 = Shake256::new();
624        for chunk in msg.chunks(29) {
625            x256.update(chunk);
626        }
627        let mut reader256 = x256.finalize_xof();
628        let mut streamed_xof256 = [0u8; 512];
629        for chunk in streamed_xof256.chunks_mut(7) {
630            reader256.squeeze(chunk);
631        }
632        assert_eq!(streamed_xof256, oneshot_xof256);
633    }
634
635    #[test]
636    fn exact_rate_boundary_padding_consistency() {
637        // Test lengths rate-1, rate, rate+1 for SHA3-256 (rate=136), SHA3-512 (rate=72), SHAKE128 (rate=168)
638        for &len in &[
639            0usize, 1, 7, 8, 33, 34, 64, 66, 71, 72, 73, 128, 135, 136, 137, 167, 168, 169,
640        ] {
641            let mut input = [0u8; 200];
642            for (i, b) in input.iter_mut().enumerate() {
643                *b = u8::try_from((i * 37 + 11) & 0xFF).unwrap_or(0);
644            }
645            let slice = &input[..len];
646
647            let mut h1 = Sha3_256::new();
648            for byte in slice {
649                h1.update(&[*byte]);
650            }
651            assert_eq!(h1.finalize(), Sha3_256::digest(slice));
652
653            let mut h2 = Sha3_512::new();
654            for byte in slice {
655                h2.update(&[*byte]);
656            }
657            assert_eq!(h2.finalize(), Sha3_512::digest(slice));
658
659            let mut one128 = [0u8; 200];
660            Shake128::xof(slice, &mut one128);
661            let mut x128 = Shake128::new();
662            for byte in slice {
663                x128.update(&[*byte]);
664            }
665            let mut r128 = x128.finalize_xof();
666            let mut stream128 = [0u8; 200];
667            r128.squeeze(&mut stream128[..100]);
668            r128.squeeze(&mut stream128[100..]);
669            assert_eq!(stream128, one128);
670
671            let mut one256 = [0u8; 200];
672            Shake256::xof(slice, &mut one256);
673            let mut x256 = Shake256::new();
674            for byte in slice {
675                x256.update(&[*byte]);
676            }
677            let mut r256 = x256.finalize_xof();
678            let mut stream256 = [0u8; 200];
679            r256.squeeze(&mut stream256[..67]);
680            r256.squeeze(&mut stream256[67..]);
681            assert_eq!(stream256, one256);
682        }
683    }
684
685    #[test]
686    fn chunked_single_block_fast_path_matches_streaming_for_all_alignments() {
687        let mut buf = [0u8; 180];
688        for (i, b) in buf.iter_mut().enumerate() {
689            *b = u8::try_from((i * 53 + 7) & 0xFF).unwrap_or(0);
690        }
691        // Exercise aligned (8/16/32B) and unaligned (1/3/5/7/13B) multi-chunk splits.
692        let splits: &[&[usize]] = &[
693            &[0, 0, 0],
694            &[16, 32, 16],       // SLH-DSA-128 PRF/F (64B, 8-byte aligned)
695            &[16, 32, 16, 16],   // SLH-DSA-128 H (80B, 8-byte aligned)
696            &[32, 32, 32, 32],   // SLH-DSA-256 H (128B, 8-byte aligned)
697            &[32, 2],            // ML-KEM / ML-DSA SampleNTT (34B)
698            &[64, 2],            // ML-DSA ExpandMask / RejBounded (66B)
699            &[32, 1],            // ML-KEM G(d || k) (33B)
700            &[1, 7, 3, 13, 5],   // Unaligned fragments
701            &[3, 16, 5, 32, 11], // Mixed unaligned + aligned
702            &[70, 70],           // Crosses SHAKE256 rate (140B >= 136)
703            &[90, 90],           // Crosses SHAKE128 rate (180B >= 168)
704        ];
705        for &lens in splits {
706            let mut chunks: [&[u8]; 5] = [&[]; 5];
707            let mut off = 0usize;
708            for (idx, &l) in lens.iter().enumerate() {
709                chunks[idx] = &buf[off..off + l];
710                off += l;
711            }
712            let slice_chunks = &chunks[..lens.len()];
713            let flat = &buf[..off];
714
715            assert_eq!(
716                Sha3_256::digest_chunks(slice_chunks),
717                Sha3_256::digest(flat)
718            );
719            assert_eq!(
720                Sha3_512::digest_chunks(slice_chunks),
721                Sha3_512::digest(flat)
722            );
723
724            let mut got128 = [0u8; 200];
725            let mut exp128 = [0u8; 200];
726            Shake128::xof_chunks(slice_chunks, &mut got128);
727            let mut s128 = Shake128::new();
728            s128.update(flat);
729            s128.finalize_xof().squeeze(&mut exp128);
730            assert_eq!(got128, exp128);
731
732            let mut got256 = [0u8; 200];
733            let mut exp256 = [0u8; 200];
734            Shake256::xof_chunks(slice_chunks, &mut got256);
735            let mut s256 = Shake256::new();
736            s256.update(flat);
737            s256.finalize_xof().squeeze(&mut exp256);
738            assert_eq!(got256, exp256);
739        }
740    }
741}