dcrypt_algorithms/hash/
mod.rs1#[cfg(not(feature = "std"))]
7use alloc::vec::Vec;
8
9use crate::error::Result;
10use crate::types::Digest;
11use zeroize::Zeroize;
12
13pub mod blake2;
14pub mod keccak; pub mod sha1;
16pub mod sha2;
17pub mod sha3;
18pub mod shake;
19
20pub use blake2::{Blake2b, Blake2s};
22pub use keccak::Keccak256; pub use sha1::Sha1;
24pub use sha2::{Sha224, Sha256, Sha384, Sha512};
25pub use sha3::{Sha3_224, Sha3_256, Sha3_384, Sha3_512};
26pub use shake::{Shake128, Shake256};
27
28pub type Hash = Vec<u8>;
30
31pub trait HashAlgorithm {
33 const OUTPUT_SIZE: usize;
35
36 const BLOCK_SIZE: usize;
38
39 const ALGORITHM_ID: &'static str;
41
42 fn name() -> String {
44 Self::ALGORITHM_ID.to_string()
45 }
46}
47
48pub trait HashFunction: Sized + Zeroize {
68 type Algorithm: HashAlgorithm;
70
71 type Output: AsRef<[u8]> + AsMut<[u8]> + Clone + Zeroize;
73
74 fn new() -> Self;
76
77 fn update(&mut self, data: &[u8]) -> Result<&mut Self>;
79
80 fn finalize(&mut self) -> Result<Self::Output>;
82
83 fn finalize_reset(&mut self) -> Result<Self::Output> {
85 let h = self.finalize()?;
86 *self = Self::new();
87 Ok(h)
88 }
89
90 fn output_size() -> usize {
92 Self::Algorithm::OUTPUT_SIZE
93 }
94
95 fn block_size() -> usize {
97 Self::Algorithm::BLOCK_SIZE
98 }
99
100 fn digest(data: &[u8]) -> Result<Self::Output> {
102 let mut hasher = Self::new();
103 hasher.update(data)?;
104 hasher.finalize()
105 }
106
107 fn name() -> String {
109 Self::Algorithm::name()
110 }
111
112 fn verify(data: &[u8], expected: &Self::Output) -> Result<bool>
114 where
115 Self::Output: PartialEq,
116 {
117 let computed = Self::digest(data)?;
118 Ok(computed == *expected)
119 }
120}
121
122#[derive(Clone, Zeroize)]
124pub struct EnhancedSha256 {
125 inner: sha2::Sha256,
126}
127
128pub enum Sha256Algorithm {}
130
131impl HashAlgorithm for Sha256Algorithm {
132 const OUTPUT_SIZE: usize = 32;
133 const BLOCK_SIZE: usize = 64;
134 const ALGORITHM_ID: &'static str = "SHA-256";
135}
136
137impl HashFunction for EnhancedSha256 {
138 type Algorithm = Sha256Algorithm;
139 type Output = Digest<32>;
140
141 fn new() -> Self {
142 Self {
143 inner: sha2::Sha256::new(),
144 }
145 }
146
147 fn update(&mut self, data: &[u8]) -> Result<&mut Self> {
148 self.inner.update(data)?;
149 Ok(self)
150 }
151
152 fn finalize(&mut self) -> Result<Self::Output> {
153 self.inner.finalize()
154 }
155}