Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_core/src/sha256.rs

10.9 KiB, 1 run

created by r1870400018:76256, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! A self-contained SHA-256 implementation, per FIPS 180-4.
2//!
3//! This exists because the Web Crypto API offers no SHA3, so a digest agreed between a browser
4//! and a Hematite server must be one of the SHA-2 family.
5//!
6//! [Written with AI entirely](https://need2know.ai/entirely-ai/code)\
7//! Anthropic Claude
8//!
9//! 30 Oct 2026: moved here from `fe2o3_hash`, which re-exports it, so that `file::stamp` in
10//! this crate can digest a text without a cycle between the two crates.
11
12// The round constants: the first thirty two bits of the fractional parts of the cube roots of
13// the first sixty four primes.
14const K: [u32; 64] = [
15 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
16 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
17 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
18 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
19 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
20 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
21 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
22 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
23 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
24 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
25 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
26 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
27 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
28 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
29 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
30 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
31];
32
33// The initial hash value: the first thirty two bits of the fractional parts of the square roots
34// of the first eight primes.
35const H0: [u32; 8] = [
36 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
37 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
38];
39
40const BLOCK_LEN: usize = 64; // bytes
41pub const DIGEST_LEN: usize = 32; // bytes
42
43/// An incremental SHA-256 hasher, which buffers input until a full block is available.
44#[derive(Clone, Debug)]
45pub struct Sha256 {
46 state: [u32; 8], // running chaining value
47 buf: [u8; BLOCK_LEN], // partial block awaiting compression
48 buflen: usize, // bytes currently held in buf
49 total: u64, // message length, for the length padding
50}
51
52impl Default for Sha256 {
53 fn default() -> Self {
54 Self {
55 state: H0,
56 buf: [0u8; BLOCK_LEN],
57 buflen: 0,
58 total: 0,
59 }
60 }
61}
62
63impl Sha256 {
64
65 /// Creates a hasher primed with the FIPS 180-4 initial hash value.
66 pub fn new() -> Self {
67 Self::default()
68 }
69
70 /// Absorbs a further slice of the message.
71 pub fn update(&mut self, mut data: &[u8]) {
72 self.total = self.total.wrapping_add(data.len() as u64);
73 // Top up any partial block first.
74 if self.buflen > 0 {
75 let take = std::cmp::min(BLOCK_LEN - self.buflen, data.len());
76 self.buf[self.buflen..self.buflen + take].copy_from_slice(&data[..take]);
77 self.buflen += take;
78 data = &data[take..];
79 if self.buflen == BLOCK_LEN {
80 let block = self.buf;
81 self.compress(&block);
82 self.buflen = 0;
83 }
84 }
85 // Consume whole blocks directly from the input.
86 while data.len() >= BLOCK_LEN {
87 let (block, rest) = data.split_at(BLOCK_LEN);
88 let mut chunk = [0u8; BLOCK_LEN];
89 chunk.copy_from_slice(block);
90 self.compress(&chunk);
91 data = rest;
92 }
93 // Retain the remainder.
94 if !data.is_empty() {
95 self.buf[..data.len()].copy_from_slice(data);
96 self.buflen = data.len();
97 }
98 }
99
100 /// Applies the padding and returns the final digest.
101 pub fn finish(mut self) -> [u8; DIGEST_LEN] {
102 let bitlen = self.total.wrapping_mul(8);
103 // A single one bit, then zeroes. When fewer than eight bytes remain after the one bit the
104 // length spills into a further block, which is the case naive implementations get wrong.
105 let mut pad = [0u8; 2 * BLOCK_LEN];
106 pad[0] = 0x80;
107 let padlen = if self.buflen < 56 {
108 56 - self.buflen
109 } else {
110 120 - self.buflen
111 };
112 pad[padlen..padlen + 8].copy_from_slice(&bitlen.to_be_bytes());
113 // `total` is deliberately not corrected here, the hasher being consumed.
114 self.update_unlogged(&pad[..padlen + 8]);
115
116 let mut out = [0u8; DIGEST_LEN];
117 for (i, word) in self.state.iter().enumerate() {
118 out[4 * i..4 * i + 4].copy_from_slice(&word.to_be_bytes());
119 }
120 out
121 }
122
123 /// Absorbs padding without counting it toward the message length.
124 fn update_unlogged(&mut self, data: &[u8]) {
125 let before = self.total;
126 self.update(data);
127 self.total = before;
128 }
129
130 /// Applies the compression function to one sixty four byte block.
131 fn compress(&mut self, block: &[u8; BLOCK_LEN]) {
132 let mut w = [0u32; 64];
133 for i in 0..16 {
134 w[i] = u32::from_be_bytes([
135 block[4 * i],
136 block[4 * i + 1],
137 block[4 * i + 2],
138 block[4 * i + 3],
139 ]);
140 }
141 for i in 16..64 {
142 let s0 = w[i - 15].rotate_right(7)
143 ^ w[i - 15].rotate_right(18)
144 ^ (w[i - 15] >> 3);
145 let s1 = w[i - 2].rotate_right(17)
146 ^ w[i - 2].rotate_right(19)
147 ^ (w[i - 2] >> 10);
148 w[i] = w[i - 16]
149 .wrapping_add(s0)
150 .wrapping_add(w[i - 7])
151 .wrapping_add(s1);
152 }
153
154 let mut a = self.state[0];
155 let mut b = self.state[1];
156 let mut c = self.state[2];
157 let mut d = self.state[3];
158 let mut e = self.state[4];
159 let mut f = self.state[5];
160 let mut g = self.state[6];
161 let mut h = self.state[7];
162
163 for i in 0..64 {
164 let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
165 let ch = (e & f) ^ ((!e) & g);
166 let temp1 = h
167 .wrapping_add(s1)
168 .wrapping_add(ch)
169 .wrapping_add(K[i])
170 .wrapping_add(w[i]);
171 let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
172 let maj = (a & b) ^ (a & c) ^ (b & c);
173 let temp2 = s0.wrapping_add(maj);
174
175 h = g;
176 g = f;
177 f = e;
178 e = d.wrapping_add(temp1);
179 d = c;
180 c = b;
181 b = a;
182 a = temp1.wrapping_add(temp2);
183 }
184
185 self.state[0] = self.state[0].wrapping_add(a);
186 self.state[1] = self.state[1].wrapping_add(b);
187 self.state[2] = self.state[2].wrapping_add(c);
188 self.state[3] = self.state[3].wrapping_add(d);
189 self.state[4] = self.state[4].wrapping_add(e);
190 self.state[5] = self.state[5].wrapping_add(f);
191 self.state[6] = self.state[6].wrapping_add(g);
192 self.state[7] = self.state[7].wrapping_add(h);
193 }
194}
195
196pub fn digest(msg: &[u8]) -> [u8; DIGEST_LEN] {
197 let mut hasher = Sha256::new();
198 hasher.update(msg);
199 hasher.finish()
200}
201
202#[cfg(test)]
203mod tests {
204 use super::*;
205
206 use crate::{
207 prelude::*,
208 byte::B32,
209 string::ToHexString,
210 };
211
212 /// Renders a digest as lower case hexadecimal, for comparison with the published vectors.
213 fn hex(d: [u8; DIGEST_LEN]) -> String {
214 B32(d).to_hex_string()
215 }
216
217 /// The vectors published with FIPS 180-4 and in the NIST byte oriented test vector set.
218 #[test]
219 fn test_sha256_fips_180_4_vectors() -> Outcome<()> {
220 let vectors: [(&[u8], &str); 3] = [
221 (
222 b"",
223 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
224 ),
225 (
226 b"abc",
227 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
228 ),
229 (
230 b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
231 "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1",
232 ),
233 ];
234 for (msg, expected) in vectors {
235 let d = hex(digest(msg));
236 req!(d, expected.to_string(), "SHA-256 of {:?}", msg);
237 }
238 Ok(())
239 }
240
241 /// The two block vector from FIPS 180-4, which exercises the message schedule across a block
242 /// boundary.
243 #[test]
244 fn test_sha256_multi_block() -> Outcome<()> {
245 let msg: &[u8] =
246 b"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu";
247 let d = hex(digest(msg));
248 req!(d, "cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1".to_string());
249 Ok(())
250 }
251
252 /// Lengths either side of the padding boundary, where the length field either fits in the
253 /// final block or forces an extra one. These are the cases that break naive padding.
254 #[test]
255 fn test_sha256_padding_boundaries() -> Outcome<()> {
256 // Digests of 55, 56, 63, 64 and 65 repetitions of 'a'.
257 let vectors: [(usize, &str); 5] = [
258 (55, "9f4390f8d30c2dd92ec9f095b65e2b9ae9b0a925a5258e241c9f1e910f734318"),
259 (56, "b35439a4ac6f0948b6d6f9e3c6af0f5f590ce20f1bde7090ef7970686ec6738a"),
260 (63, "7d3e74a05d7db15bce4ad9ec0658ea98e3f06eeecf16b4c6fff2da457ddc2f34"),
261 (64, "ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb"),
262 (65, "635361c48bb9eab14198e76ea8ab7f1a41685d6ad62aa9146d301d4f17eb0ae0"),
263 ];
264 for (n, expected) in vectors {
265 let msg = vec![b'a'; n];
266 let d = hex(digest(&msg));
267 req!(d, expected.to_string(), "SHA-256 of {} 'a's", n);
268 }
269 Ok(())
270 }
271
272 /// Streaming in awkwardly sized pieces must agree with hashing in one go, which is what the
273 /// `Hasher` impl relies on when it absorbs several input slices.
274 #[test]
275 fn test_sha256_incremental_matches_oneshot() -> Outcome<()> {
276 let msg = vec![b'x'; 1000];
277 for chunk in [1usize, 7, 31, 63, 64, 65, 127] {
278 let mut hasher = Sha256::new();
279 for piece in msg.chunks(chunk) {
280 hasher.update(piece);
281 }
282 // `req!` renders its arguments again on failure, so the digests are bound first.
283 let streamed = hex(hasher.finish());
284 let oneshot = hex(digest(&msg));
285 req!(streamed, oneshot, "chunk size {}", chunk);
286 }
287 Ok(())
288 }
289
290 /// The one million 'a' vector from FIPS 180-4, ignored by default only for its cost.
291 #[test]
292 #[ignore]
293 fn test_sha256_million_a() -> Outcome<()> {
294 let mut hasher = Sha256::new();
295 let block = [b'a'; 1000];
296 for _ in 0..1000 {
297 hasher.update(&block);
298 }
299 let d = hex(hasher.finish());
300 req!(d, "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0".to_string());
301 Ok(())
302 }
303}