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 sha1;
14pub mod sha2;
15pub mod sha3;
16pub mod shake;
17
18pub use blake2::{Blake2b, Blake2s};
20pub use sha1::Sha1;
21pub use sha2::{Sha224, Sha256, Sha384, Sha512};
22pub use sha3::{Sha3_224, Sha3_256, Sha3_384, Sha3_512};
23pub use shake::{Shake128, Shake256};
24
25pub type Hash = Vec<u8>;
27
28pub trait HashAlgorithm {
30 const OUTPUT_SIZE: usize;
32
33 const BLOCK_SIZE: usize;
35
36 const ALGORITHM_ID: &'static str;
38
39 fn name() -> String {
41 Self::ALGORITHM_ID.to_string()
42 }
43}
44
45pub trait HashFunction: Sized {
65 type Algorithm: HashAlgorithm;
67
68 type Output: AsRef<[u8]> + AsMut<[u8]> + Clone;
70
71 fn new() -> Self;
73
74 fn update(&mut self, data: &[u8]) -> Result<&mut Self>;
76
77 fn finalize(&mut self) -> Result<Self::Output>;
79
80 fn finalize_reset(&mut self) -> Result<Self::Output> {
82 let h = self.finalize()?;
83 *self = Self::new();
84 Ok(h)
85 }
86
87 fn output_size() -> usize {
89 Self::Algorithm::OUTPUT_SIZE
90 }
91
92 fn block_size() -> usize {
94 Self::Algorithm::BLOCK_SIZE
95 }
96
97 fn digest(data: &[u8]) -> Result<Self::Output> {
99 let mut hasher = Self::new();
100 hasher.update(data)?;
101 hasher.finalize()
102 }
103
104 fn name() -> String {
106 Self::Algorithm::name()
107 }
108
109 fn verify(data: &[u8], expected: &Self::Output) -> Result<bool>
111 where
112 Self::Output: PartialEq,
113 {
114 let computed = Self::digest(data)?;
115 Ok(computed == *expected)
116 }
117}
118
119#[derive(Clone)]
121pub struct EnhancedSha256 {
122 inner: sha2::Sha256,
123}
124
125pub enum Sha256Algorithm {}
127
128impl HashAlgorithm for Sha256Algorithm {
129 const OUTPUT_SIZE: usize = 32;
130 const BLOCK_SIZE: usize = 64;
131 const ALGORITHM_ID: &'static str = "SHA-256";
132}
133
134impl HashFunction for EnhancedSha256 {
135 type Algorithm = Sha256Algorithm;
136 type Output = Digest<32>;
137
138 fn new() -> Self {
139 Self {
140 inner: sha2::Sha256::new(),
141 }
142 }
143
144 fn update(&mut self, data: &[u8]) -> Result<&mut Self> {
145 self.inner.update(data)?;
146 Ok(self)
147 }
148
149 fn finalize(&mut self) -> Result<Self::Output> {
150 self.inner.finalize()
151 }
152}