embedded_wg_display/util/hasher.rs
1//! SHA-256 hashing with hardware SHA peripheral.
2use esp_hal::{
3 peripherals::SHA,
4 sha::{Sha, Sha256},
5};
6use nb::block;
7
8/// Wraps the ESP32 hardware SHA peripheral for SHA-256 computation.
9pub struct Hasher<'d> {
10 sha: Sha<'d>,
11}
12
13impl<'d> Hasher<'d> {
14 /// Creates a new [`Hasher`] from the `SHA` peripheral.
15 pub fn new(sha_peripherals: SHA<'d>) -> Self {
16 Self {
17 sha: Sha::new(sha_peripherals),
18 }
19 }
20
21 // create a 14 bit hash for the wasm binary nvs storage
22 // based on the example from https://docs.rs/esp32-hal/latest/esp32_hal/sha/index.html
23 pub fn hash(&mut self, input: &str) -> [u8; 14] {
24 let mut hasher = self.sha.start::<Sha256>();
25 let mut remaining = input.as_bytes();
26 let mut output = [0u8; 14];
27
28 while !remaining.is_empty() {
29 // update() returns the not-yet-consumed tail until the HW block is processed.
30 remaining = block!(hasher.update(remaining)).unwrap();
31 }
32
33 // Provide a shorter output buffer to get a truncated digest.
34 block!(hasher.finish(output.as_mut_slice())).unwrap();
35 output
36 }
37}