Skip to main content

quantaegis_drbg/
sha256.rs

1//! **NIST FIPS 180-4 SHA-256** cryptographic hash function.
2//!
3//! Pure-Rust, `#![no_std]`, `#![forbid(unsafe_code)]`, division-free, zero-allocation
4//! implementation with automatic state zeroization on drop and in-place digest output.
5
6use core::fmt;
7
8use quantaegis_core::ct::ct_eq_slice;
9use quantaegis_core::{Error, Result, Zeroize};
10
11/// SHA-256 initial hash values (`FIPS 180-4, Section 5.3.3`).
12const H0: [u32; 8] = [
13    0x6a09_e667,
14    0xbb67_ae85,
15    0x3c6e_f372,
16    0xa54f_f53a,
17    0x510e_527f,
18    0x9b05_688c,
19    0x1f83_d9ab,
20    0x5be0_cd19,
21];
22
23/// SHA-256 round constants (`FIPS 180-4, Section 4.2.2`).
24const K: [u32; 64] = [
25    0x428a_2f98,
26    0x7137_4491,
27    0xb5c0_fbcf,
28    0xe9b5_dba5,
29    0x3956_c25b,
30    0x59f1_11f1,
31    0x923f_82a4,
32    0xab1c_5ed5,
33    0xd807_aa98,
34    0x1283_5b01,
35    0x2431_85be,
36    0x550c_7dc3,
37    0x72be_5d74,
38    0x80de_b1fe,
39    0x9bdc_06a7,
40    0xc19b_f174,
41    0xe49b_69c1,
42    0xefbe_4786,
43    0x0fc1_9dc6,
44    0x240c_a1cc,
45    0x2de9_2c6f,
46    0x4a74_84aa,
47    0x5cb0_a9dc,
48    0x76f9_88da,
49    0x983e_5152,
50    0xa831_c66d,
51    0xb003_27c8,
52    0xbf59_7fc7,
53    0xc6e0_0bf3,
54    0xd5a7_9147,
55    0x06ca_6351,
56    0x1429_2967,
57    0x27b7_0a85,
58    0x2e1b_2138,
59    0x4d2c_6dfc,
60    0x5338_0d13,
61    0x650a_7354,
62    0x766a_0abb,
63    0x81c2_c92e,
64    0x9272_2c85,
65    0xa2bf_e8a1,
66    0xa81a_664b,
67    0xc24b_8b70,
68    0xc76c_51a3,
69    0xd192_e819,
70    0xd699_0624,
71    0xf40e_3585,
72    0x106a_a070,
73    0x19a4_c116,
74    0x1e37_6c08,
75    0x2748_774c,
76    0x34b0_bcb5,
77    0x391c_0cb3,
78    0x4ed8_aa4a,
79    0x5b9c_ca4f,
80    0x682e_6ff3,
81    0x748f_82ee,
82    0x78a5_636f,
83    0x84c8_7814,
84    0x8cc7_0208,
85    0x90be_fffa,
86    0xa450_6ceb,
87    0xbef9_a3f7,
88    0xc671_78f2,
89];
90
91/// Streaming **SHA-256** hash context (`FIPS 180-4, Section 6.2`).
92///
93/// Internal state and partial input blocks are automatically zeroized on drop. Once finalized,
94/// further [`Sha256::try_update`] or [`Sha256::try_finalize_into`] calls are rejected until
95/// [`Sha256::reset`] is called.
96pub struct Sha256 {
97    state: [u32; 8],
98    block: [u8; Self::BLOCK_LEN],
99    block_len: usize,
100    total_bytes: u64,
101    finalized: bool,
102    overflowed: bool,
103}
104
105impl Sha256 {
106    /// Output digest length in bytes (`32` bytes / `256` bits).
107    pub const DIGEST_LEN: usize = 32;
108
109    /// Compression block size in bytes (`64` bytes / `512` bits).
110    pub const BLOCK_LEN: usize = 64;
111
112    /// Maximum supported message length in bytes (`2^61 - 1`, matching FIPS 180-4 ยง5.1.1's
113    /// strict `< 2^64` bits ceiling without bit-counter wraparound).
114    pub const MAX_MESSAGE_BYTES: u64 = (1u64 << 61) - 1;
115
116    /// Creates a new SHA-256 hasher initialized to FIPS 180-4 Section 5.3.3 `H^(0)`.
117    #[inline]
118    pub const fn new() -> Self {
119        Self {
120            state: H0,
121            block: [0u8; Self::BLOCK_LEN],
122            block_len: 0,
123            total_bytes: 0,
124            finalized: false,
125            overflowed: false,
126        }
127    }
128
129    /// Resets this hasher in place to FIPS 180-4 Section 5.3.3 `H^(0)` after zeroizing prior state.
130    pub fn reset(&mut self) {
131        self.zeroize();
132        self.state = H0;
133        self.finalized = false;
134        self.overflowed = false;
135    }
136
137    /// Absorbs `data` into the SHA-256 compression state, checking post-finalize misuse and the
138    /// FIPS 180-4 Section 5.1.1 `< 2^64` bits (`MAX_MESSAGE_BYTES`) ceiling.
139    pub fn try_update(&mut self, mut data: &[u8]) -> Result<()> {
140        if self.finalized || self.overflowed {
141            return Err(Error::DrbgInvalidRequest);
142        }
143
144        let add = u64::try_from(data.len()).map_err(|_| {
145            self.overflowed = true;
146            Error::DrbgInvalidRequest
147        })?;
148        let Some(new_total) = self.total_bytes.checked_add(add) else {
149            self.overflowed = true;
150            return Err(Error::DrbgInvalidRequest);
151        };
152        if new_total > Self::MAX_MESSAGE_BYTES {
153            self.overflowed = true;
154            return Err(Error::DrbgInvalidRequest);
155        }
156        self.total_bytes = new_total;
157
158        if self.block_len > 0 {
159            let take = (Self::BLOCK_LEN - self.block_len).min(data.len());
160            self.block[self.block_len..self.block_len + take].copy_from_slice(&data[..take]);
161            self.block_len += take;
162            data = &data[take..];
163
164            if self.block_len == Self::BLOCK_LEN {
165                compress_block(&mut self.state, &self.block);
166                self.block_len = 0;
167            }
168        }
169
170        let (full_blocks, remainder) = data.as_chunks::<{ Self::BLOCK_LEN }>();
171        for blk in full_blocks {
172            compress_block(&mut self.state, blk);
173        }
174
175        if !remainder.is_empty() {
176            self.block[..remainder.len()].copy_from_slice(remainder);
177            self.block_len = remainder.len();
178        }
179        Ok(())
180    }
181
182    /// Absorbs `data` into the SHA-256 compression state.
183    ///
184    /// Prefer [`Self::try_update`] when callers need fallible checking of the `2^61 - 1` byte
185    /// FIPS 180-4 message limit or post-finalize misuse.
186    #[inline]
187    pub fn update(&mut self, data: &[u8]) {
188        let _ = self.try_update(data);
189    }
190
191    /// Finalizes the digest directly into `out`, zeroizes internal state, and marks the hasher
192    /// finalized so subsequent updates or double-finalizations fail until [`Self::reset`].
193    pub fn try_finalize_into(&mut self, out: &mut [u8; Self::DIGEST_LEN]) -> Result<()> {
194        if self.finalized || self.overflowed {
195            return Err(Error::DrbgInvalidRequest);
196        }
197        let bit_len = self.total_bytes << 3;
198
199        // Append 0x80 marker byte.
200        self.block[self.block_len] = 0x80;
201        self.block_len += 1;
202
203        // If fewer than 8 bytes remain for the 64-bit length field, pad and compress now.
204        if self.block_len > Self::BLOCK_LEN - 8 {
205            self.block[self.block_len..].fill(0);
206            compress_block(&mut self.state, &self.block);
207            self.block_len = 0;
208        }
209
210        self.block[self.block_len..Self::BLOCK_LEN - 8].fill(0);
211        self.block[Self::BLOCK_LEN - 8..].copy_from_slice(&bit_len.to_be_bytes());
212        compress_block(&mut self.state, &self.block);
213
214        for (chunk, &word) in out.as_chunks_mut::<4>().0.iter_mut().zip(self.state.iter()) {
215            *chunk = word.to_be_bytes();
216        }
217        self.zeroize();
218        self.finalized = true;
219        Ok(())
220    }
221
222    /// Finalizes the digest directly into `out` and marks the hasher finalized.
223    ///
224    /// If already finalized or overflowed, zeroes `out` without emitting stale state.
225    #[inline]
226    pub fn finalize_into(&mut self, out: &mut [u8; Self::DIGEST_LEN]) {
227        if self.try_finalize_into(out).is_err() {
228            out.zeroize();
229        }
230    }
231
232    /// Finalizes the hash and returns the 32-byte SHA-256 digest.
233    ///
234    /// For secret-derived digests, prefer [`Self::finalize_into`] or [`Self::digest_into`] to
235    /// write directly into caller-owned zeroized storage without an intermediate return copy.
236    pub fn finalize(mut self) -> [u8; Self::DIGEST_LEN] {
237        let mut out = [0u8; Self::DIGEST_LEN];
238        self.finalize_into(&mut out);
239        out
240    }
241
242    /// Computes `SHA-256(data)` directly into `out` without a by-value digest copy.
243    pub fn digest_into(data: &[u8], out: &mut [u8; Self::DIGEST_LEN]) {
244        Self::digest_chunks_into(&[data], out);
245    }
246
247    /// Computes `SHA-256(chunks[0] || chunks[1] || ...)` directly into `out`.
248    pub fn digest_chunks_into(chunks: &[&[u8]], out: &mut [u8; Self::DIGEST_LEN]) {
249        let mut hasher = Self::new();
250        for &chunk in chunks {
251            hasher.update(chunk);
252        }
253        hasher.finalize_into(out);
254    }
255
256    /// Computes `SHA-256(data)` in one shot.
257    pub fn digest(data: &[u8]) -> [u8; Self::DIGEST_LEN] {
258        let mut out = [0u8; Self::DIGEST_LEN];
259        Self::digest_into(data, &mut out);
260        out
261    }
262
263    /// Computes `SHA-256(chunks[0] || chunks[1] || ...)` in one shot.
264    pub fn digest_chunks(chunks: &[&[u8]]) -> [u8; Self::DIGEST_LEN] {
265        let mut out = [0u8; Self::DIGEST_LEN];
266        Self::digest_chunks_into(chunks, &mut out);
267        out
268    }
269
270    /// Executes the FIPS 140-3 known-answer self-test (CAST) for SHA-256.
271    ///
272    /// Verifies both a single-block input (`"abc"`, FIPS 180-4) and a two-block input
273    /// (`"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"`, 56 bytes) in constant time.
274    pub fn self_test() -> Result<()> {
275        const EXPECTED_ABC: [u8; 32] = [
276            0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae,
277            0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61,
278            0xf2, 0x00, 0x15, 0xad,
279        ];
280        const EXPECTED_TWO_BLOCK: [u8; 32] = [
281            0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8, 0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e,
282            0x60, 0x39, 0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67, 0xf6, 0xec, 0xed, 0xd4,
283            0x19, 0xdb, 0x06, 0xc1,
284        ];
285
286        let mut d1 = [0u8; Self::DIGEST_LEN];
287        let mut d2 = [0u8; Self::DIGEST_LEN];
288        Self::digest_into(b"abc", &mut d1);
289        Self::digest_into(
290            b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
291            &mut d2,
292        );
293        let ok = ct_eq_slice(&d1, &EXPECTED_ABC) & ct_eq_slice(&d2, &EXPECTED_TWO_BLOCK);
294        if ok.into_bool() {
295            Ok(())
296        } else {
297            Err(Error::SelfTestFailed)
298        }
299    }
300}
301
302impl Default for Sha256 {
303    #[inline]
304    fn default() -> Self {
305        Self::new()
306    }
307}
308
309impl Zeroize for Sha256 {
310    #[inline]
311    fn zeroize(&mut self) {
312        self.state.zeroize();
313        self.block.zeroize();
314        self.block_len = 0;
315        self.total_bytes = 0;
316        self.finalized = true;
317    }
318}
319
320impl Drop for Sha256 {
321    #[inline]
322    fn drop(&mut self) {
323        self.zeroize();
324    }
325}
326
327impl fmt::Debug for Sha256 {
328    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
329        f.write_str("Sha256([REDACTED])")
330    }
331}
332
333/// FIPS 180-4 Section 6.2.2 SHA-256 compression function on a single 64-byte block.
334#[inline(never)]
335#[allow(clippy::many_single_char_names)]
336pub(crate) fn compress_block(state: &mut [u32; 8], block: &[u8; 64]) {
337    let mut w = [0u32; 64];
338    for (slot, chunk) in w[..16].iter_mut().zip(block.as_chunks::<4>().0.iter()) {
339        *slot = u32::from_be_bytes(*chunk);
340    }
341    for i in 16..64 {
342        let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
343        let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
344        w[i] = w[i - 16]
345            .wrapping_add(s0)
346            .wrapping_add(w[i - 7])
347            .wrapping_add(s1);
348    }
349
350    let mut a = state[0];
351    let mut b = state[1];
352    let mut c = state[2];
353    let mut d = state[3];
354    let mut e = state[4];
355    let mut f = state[5];
356    let mut g = state[6];
357    let mut h = state[7];
358
359    for i in 0..64 {
360        let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
361        let ch = (e & f) ^ ((!e) & g);
362        let temp1 = h
363            .wrapping_add(s1)
364            .wrapping_add(ch)
365            .wrapping_add(K[i])
366            .wrapping_add(w[i]);
367        let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
368        let maj = (a & b) ^ (a & c) ^ (b & c);
369        let temp2 = s0.wrapping_add(maj);
370
371        h = g;
372        g = f;
373        f = e;
374        e = d.wrapping_add(temp1);
375        d = c;
376        c = b;
377        b = a;
378        a = temp1.wrapping_add(temp2);
379    }
380
381    // Reload the chaining words directly from `*state` (which `Sha256::zeroize` wipes) rather than
382    // allowing LLVM to spill hoisted copies of `state[1..8]` onto an unzeroized stack slot across
383    // the 64-round loop.
384    let state = core::hint::black_box(state);
385    state[0] = state[0].wrapping_add(a);
386    state[1] = state[1].wrapping_add(b);
387    state[2] = state[2].wrapping_add(c);
388    state[3] = state[3].wrapping_add(d);
389    state[4] = state[4].wrapping_add(e);
390    state[5] = state[5].wrapping_add(f);
391    state[6] = state[6].wrapping_add(g);
392    state[7] = state[7].wrapping_add(h);
393
394    w.zeroize();
395}
396
397#[cfg(test)]
398mod tests {
399    use super::*;
400
401    fn to_hex(bytes: &[u8; 32]) -> [u8; 64] {
402        const HEX: &[u8; 16] = b"0123456789abcdef";
403        let mut out = [0u8; 64];
404        for (i, &b) in bytes.iter().enumerate() {
405            out[2 * i] = HEX[usize::from(b >> 4)];
406            out[2 * i + 1] = HEX[usize::from(b & 0x0f)];
407        }
408        out
409    }
410
411    #[test]
412    fn sha256_self_test_and_streaming_boundaries() {
413        assert_eq!(Sha256::self_test(), Ok(()));
414
415        // Padding and block boundary lengths: 55, 56, 63, 64, 65 bytes (independently verified).
416        let cases: &[(usize, &str)] = &[
417            (
418                55,
419                "e7313d333c272e639f790978283f9eb392e843d0f29b7016828bb1daa4aac70b",
420            ),
421            (
422                56,
423                "4324d65f3c103567f5589c710bc08f8523f929a9272e3af36fc968e52abc6c27",
424            ),
425            (
426                63,
427                "81c80242132f230c3bd41b3e63bbcff16107339549214a99614ff26664625055",
428            ),
429            (
430                64,
431                "39e3d7b6b5d075d37d053ad89b24b41bef4f3c29760c84447cab3f3be1882241",
432            ),
433            (
434                65,
435                "aacca6ff74fdbb296d165a45cecfa04e5127bc008770fbbdd48006f2d2fae95e",
436            ),
437        ];
438
439        for &(len, expected) in cases {
440            let mut msg = [0u8; 65];
441            for (i, slot) in msg[..len].iter_mut().enumerate() {
442                #[allow(clippy::cast_possible_truncation)]
443                {
444                    *slot = (i.wrapping_mul(7).wrapping_add(3)) as u8;
445                }
446            }
447            let oneshot = Sha256::digest(&msg[..len]);
448            assert_eq!(&to_hex(&oneshot)[..], expected.as_bytes());
449
450            // Split across multiple updates including 1-byte and near-boundary chunks.
451            let mut streamed = Sha256::new();
452            assert_eq!(streamed.try_update(&msg[..1]), Ok(()));
453            assert_eq!(streamed.try_update(&msg[1..len - 1]), Ok(()));
454            assert_eq!(streamed.try_update(&msg[len - 1..len]), Ok(()));
455            let mut out = [0u8; 32];
456            assert_eq!(streamed.try_finalize_into(&mut out), Ok(()));
457            assert_eq!(out, oneshot);
458
459            // Post-finalize update and double-finalize are rejected until reset().
460            assert_eq!(streamed.try_update(b"more"), Err(Error::DrbgInvalidRequest));
461            assert_eq!(
462                streamed.try_finalize_into(&mut out),
463                Err(Error::DrbgInvalidRequest)
464            );
465            streamed.reset();
466            assert_eq!(streamed.try_update(&msg[..len]), Ok(()));
467            assert_eq!(streamed.try_finalize_into(&mut out), Ok(()));
468            assert_eq!(out, oneshot);
469        }
470    }
471
472    #[test]
473    fn sha256_rejects_message_length_above_2_to_61_minus_1_bytes() {
474        let mut h = Sha256::new();
475        h.total_bytes = Sha256::MAX_MESSAGE_BYTES;
476        assert_eq!(h.try_update(&[0u8; 1]), Err(Error::DrbgInvalidRequest));
477        let mut out = [0xAAu8; 32];
478        assert_eq!(
479            h.try_finalize_into(&mut out),
480            Err(Error::DrbgInvalidRequest)
481        );
482        // Output buffer untouched on fallible error.
483        assert_eq!(out, [0xAAu8; 32]);
484    }
485}