Skip to main content

noxtls_crypto/hash/mdigest/
sha256.rs

1// Copyright (c) 2019-2026, Argenox Technologies LLC
2// All rights reserved.
3//
4// SPDX-License-Identifier: GPL-2.0-only OR LicenseRef-Argenox-Commercial-License
5//
6// This file is part of the NoxTLS Library.
7//
8// This program is free software: you can redistribute it and/or modify
9// it under the terms of the GNU General Public License as published by the
10// Free Software Foundation; version 2 of the License.
11//
12// Alternatively, this file may be used under the terms of a commercial
13// license from Argenox Technologies LLC.
14//
15// See `noxtls/LICENSE` and `noxtls/LICENSE.md` in this repository for full details.
16// CONTACT: info@argenox.com
17
18use super::Digest;
19use crate::internal_alloc::Vec;
20
21/// Implements SHA-256 compression and streaming digest state.
22#[derive(Debug, Clone)]
23pub struct Sha256 {
24    state: [u32; 8],
25    buffer: [u8; 64],
26    buffer_len: usize,
27    bit_len: u64,
28}
29
30impl Default for Sha256 {
31    /// Builds a SHA-256 hasher with standard IV constants and an empty buffer.
32    ///
33    /// # Returns
34    ///
35    /// Fresh [`Sha256`] in the initial state.
36    ///
37    /// # Panics
38    ///
39    /// This function does not panic.
40    fn default() -> Self {
41        Self {
42            state: [
43                0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
44                0x5be0cd19,
45            ],
46            buffer: [0; 64],
47            buffer_len: 0,
48            bit_len: 0,
49        }
50    }
51}
52
53impl Sha256 {
54    /// Creates a new SHA-256 hasher initialized with standard IV constants.
55    ///
56    /// # Returns
57    /// A fresh `Sha256` instance with empty input state.
58    ///
59    /// # Panics
60    ///
61    /// This function does not panic.
62    pub fn new() -> Self {
63        Self::default()
64    }
65
66    /// Compresses one 512-bit SHA-256 message block into the eight working words.
67    ///
68    /// # Arguments
69    ///
70    /// * `self` — Running hasher whose `state` is updated.
71    /// * `block` — One fully prepared 64-byte big-endian message block.
72    ///
73    /// # Returns
74    ///
75    /// `()`; folds the round function output into `self.state`.
76    ///
77    /// # Panics
78    ///
79    /// This function does not panic.
80    fn compress(&mut self, block: &[u8; 64]) {
81        const K: [u32; 64] = [
82            0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
83            0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
84            0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
85            0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
86            0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
87            0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
88            0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
89            0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
90            0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
91            0xc67178f2,
92        ];
93        let mut w = [0_u32; 64];
94        for (i, chunk) in block.chunks_exact(4).enumerate().take(16) {
95            w[i] = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
96        }
97        for i in 16..64 {
98            let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
99            let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
100            w[i] = w[i - 16]
101                .wrapping_add(s0)
102                .wrapping_add(w[i - 7])
103                .wrapping_add(s1);
104        }
105
106        let mut a = self.state[0];
107        let mut b = self.state[1];
108        let mut c = self.state[2];
109        let mut d = self.state[3];
110        let mut e = self.state[4];
111        let mut f = self.state[5];
112        let mut g = self.state[6];
113        let mut h = self.state[7];
114
115        for i in 0..64 {
116            let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
117            let ch = (e & f) ^ ((!e) & g);
118            let temp1 = h
119                .wrapping_add(s1)
120                .wrapping_add(ch)
121                .wrapping_add(K[i])
122                .wrapping_add(w[i]);
123            let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
124            let maj = (a & b) ^ (a & c) ^ (b & c);
125            let temp2 = s0.wrapping_add(maj);
126
127            h = g;
128            g = f;
129            f = e;
130            e = d.wrapping_add(temp1);
131            d = c;
132            c = b;
133            b = a;
134            a = temp1.wrapping_add(temp2);
135        }
136
137        self.state[0] = self.state[0].wrapping_add(a);
138        self.state[1] = self.state[1].wrapping_add(b);
139        self.state[2] = self.state[2].wrapping_add(c);
140        self.state[3] = self.state[3].wrapping_add(d);
141        self.state[4] = self.state[4].wrapping_add(e);
142        self.state[5] = self.state[5].wrapping_add(f);
143        self.state[6] = self.state[6].wrapping_add(g);
144        self.state[7] = self.state[7].wrapping_add(h);
145    }
146}
147
148impl Digest for Sha256 {
149    /// Absorbs `data` into the running digest, compressing whenever 64 bytes accumulate.
150    ///
151    /// # Arguments
152    ///
153    /// * `self` — Running SHA-256 hasher.
154    /// * `data` — Next message bytes to append.
155    ///
156    /// # Returns
157    ///
158    /// `()`.
159    ///
160    /// # Panics
161    ///
162    /// This function does not panic.
163    fn update(&mut self, mut data: &[u8]) {
164        self.bit_len = self.bit_len.wrapping_add((data.len() as u64) * 8);
165        while !data.is_empty() {
166            let to_copy = (64 - self.buffer_len).min(data.len());
167            self.buffer[self.buffer_len..self.buffer_len + to_copy]
168                .copy_from_slice(&data[..to_copy]);
169            self.buffer_len += to_copy;
170            data = &data[to_copy..];
171            if self.buffer_len == 64 {
172                let block = self.buffer;
173                self.compress(&block);
174                self.buffer_len = 0;
175            }
176        }
177    }
178
179    /// Finalizes SHA-256 padding and returns the 32-byte digest in a newly allocated vector.
180    ///
181    /// # Arguments
182    ///
183    /// * `self` — Consumed hasher holding buffered tail bytes and the bit length.
184    ///
185    /// # Returns
186    ///
187    /// [`Vec`] containing exactly 32 digest bytes (big-endian words from internal state).
188    ///
189    /// # Panics
190    ///
191    /// This function does not panic.
192    fn finalize(mut self) -> Vec<u8> {
193        self.buffer[self.buffer_len] = 0x80;
194        self.buffer_len += 1;
195
196        if self.buffer_len > 56 {
197            self.buffer[self.buffer_len..].fill(0);
198            let block = self.buffer;
199            self.compress(&block);
200            self.buffer_len = 0;
201        }
202
203        self.buffer[self.buffer_len..56].fill(0);
204        self.buffer[56..64].copy_from_slice(&self.bit_len.to_be_bytes());
205        let block = self.buffer;
206        self.compress(&block);
207
208        let mut out = Vec::with_capacity(32);
209        for word in self.state {
210            out.extend_from_slice(&word.to_be_bytes());
211        }
212        out
213    }
214}
215
216/// Computes SHA-256 of `data` and returns the 32-byte digest.
217///
218/// # Arguments
219/// * `data`: Input bytes to hash.
220///
221/// # Returns
222/// A 32-byte SHA-256 digest.
223///
224/// # Panics
225///
226/// This function does not panic.
227#[must_use]
228pub fn sha256(data: &[u8]) -> [u8; 32] {
229    let mut hasher = Sha256::new();
230    hasher.update(data);
231    let digest = hasher.finalize();
232    let mut out = [0_u8; 32];
233    out.copy_from_slice(&digest);
234    out
235}