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