1use sha2::{Digest as DigestImpl, Sha256 as Sha256Impl};
23
24use crate::constants::CRYPTO_HASH_SHA256_BYTES;
25use crate::types::*;
26
27pub type Digest = StackByteArray<CRYPTO_HASH_SHA256_BYTES>;
29
30pub struct Sha256 {
32 hasher: Sha256Impl,
33}
34
35impl Sha256 {
36 pub fn new() -> Self {
38 Self {
39 hasher: Sha256Impl::new(),
40 }
41 }
42
43 pub fn compute_into_bytes<
46 Input: Bytes + ?Sized,
47 Output: MutByteArray<CRYPTO_HASH_SHA256_BYTES>,
48 >(
49 output: &mut Output,
50 input: &Input,
51 ) {
52 let mut hasher = Self::new();
53 hasher.update(input);
54 hasher.finalize_into_bytes(output)
55 }
56
57 pub fn compute<Input: Bytes + ?Sized, Output: NewByteArray<CRYPTO_HASH_SHA256_BYTES>>(
59 input: &Input,
60 ) -> Output {
61 let mut hasher = Self::new();
62 hasher.update(input);
63 hasher.finalize()
64 }
65
66 pub fn compute_to_vec<Input: Bytes + ?Sized>(input: &Input) -> Vec<u8> {
69 Self::compute(input)
70 }
71
72 pub fn update<Input: Bytes + ?Sized>(&mut self, input: &Input) {
74 self.hasher.update(input.as_slice())
75 }
76
77 pub fn finalize<Output: NewByteArray<CRYPTO_HASH_SHA256_BYTES>>(self) -> Output {
79 let mut hash = Output::new_byte_array();
80 self.finalize_into_bytes(&mut hash);
81 hash
82 }
83
84 pub fn finalize_into_bytes<Output: MutByteArray<CRYPTO_HASH_SHA256_BYTES>>(
86 self,
87 output: &mut Output,
88 ) {
89 let digest = self.hasher.finalize();
90 output.as_mut_slice().copy_from_slice(&digest);
91 }
92
93 pub fn finalize_to_vec(self) -> Vec<u8> {
95 self.finalize()
96 }
97}
98
99impl Default for Sha256 {
100 fn default() -> Self {
101 Self::new()
102 }
103}
104
105#[cfg(test)]
106mod tests {
107 use super::*;
108
109 #[test]
110 fn test_sha256_known_answer() {
111 let digest = Sha256::compute_to_vec(b"abc");
112 assert_eq!(
113 digest,
114 hex::decode("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
115 .expect("hex failed")
116 );
117 }
118}