1use std::fmt;
2use std::str::FromStr;
3
4use super::hasher::{Hasher, bytes_to_hex};
5use super::registry::HashRegistry;
6use crate::error::HashUtilityError;
7
8#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, serde::Serialize)]
10#[serde(rename_all = "kebab-case")]
11pub enum Algorithm {
12 Md5,
14 Sha1,
16 Sha224,
18 Sha256,
20 Sha384,
22 Sha512,
24 Sha3_224,
26 Sha3_256,
28 Sha3_384,
30 Sha3_512,
32 Blake2b512,
34 Blake2s256,
36 Blake3,
38 Xxh3,
40 Xxh128,
42}
43
44impl Algorithm {
45 pub const ALL: [Self; 15] = [
50 Self::Md5,
51 Self::Sha1,
52 Self::Sha224,
53 Self::Sha256,
54 Self::Sha384,
55 Self::Sha512,
56 Self::Sha3_224,
57 Self::Sha3_256,
58 Self::Sha3_384,
59 Self::Sha3_512,
60 Self::Blake2b512,
61 Self::Blake2s256,
62 Self::Blake3,
63 Self::Xxh3,
64 Self::Xxh128,
65 ];
66
67 pub const fn canonical_name(self) -> &'static str {
69 match self {
70 Self::Md5 => "md5",
71 Self::Sha1 => "sha1",
72 Self::Sha224 => "sha224",
73 Self::Sha256 => "sha256",
74 Self::Sha384 => "sha384",
75 Self::Sha512 => "sha512",
76 Self::Sha3_224 => "sha3-224",
77 Self::Sha3_256 => "sha3-256",
78 Self::Sha3_384 => "sha3-384",
79 Self::Sha3_512 => "sha3-512",
80 Self::Blake2b512 => "blake2b-512",
81 Self::Blake2s256 => "blake2s-256",
82 Self::Blake3 => "blake3",
83 Self::Xxh3 => "xxh3",
84 Self::Xxh128 => "xxh128",
85 }
86 }
87
88 pub const fn display_name(self) -> &'static str {
90 match self {
91 Self::Md5 => "MD5",
92 Self::Sha1 => "SHA1",
93 Self::Sha224 => "SHA-224",
94 Self::Sha256 => "SHA-256",
95 Self::Sha384 => "SHA-384",
96 Self::Sha512 => "SHA-512",
97 Self::Sha3_224 => "SHA3-224",
98 Self::Sha3_256 => "SHA3-256",
99 Self::Sha3_384 => "SHA3-384",
100 Self::Sha3_512 => "SHA3-512",
101 Self::Blake2b512 => "BLAKE2b-512",
102 Self::Blake2s256 => "BLAKE2s-256",
103 Self::Blake3 => "BLAKE3",
104 Self::Xxh3 => "XXH3",
105 Self::Xxh128 => "XXH128",
106 }
107 }
108
109 pub const fn output_size(self) -> usize {
111 match self {
112 Self::Md5 | Self::Xxh128 => 16,
113 Self::Sha1 => 20,
114 Self::Sha224 | Self::Sha3_224 => 28,
115 Self::Sha256 | Self::Sha3_256 | Self::Blake2s256 | Self::Blake3 => 32,
116 Self::Sha384 | Self::Sha3_384 => 48,
117 Self::Sha512 | Self::Sha3_512 | Self::Blake2b512 => 64,
118 Self::Xxh3 => 8,
119 }
120 }
121
122 pub const fn required_feature(self) -> &'static str {
124 match self {
125 Self::Md5 => "md5",
126 Self::Sha1 => "sha1",
127 Self::Sha224 | Self::Sha256 | Self::Sha384 | Self::Sha512 => "sha2",
128 Self::Sha3_224 | Self::Sha3_256 | Self::Sha3_384 | Self::Sha3_512 => "sha3",
129 Self::Blake2b512 | Self::Blake2s256 => "blake2",
130 Self::Blake3 => "blake3",
131 Self::Xxh3 | Self::Xxh128 => "xxhash",
132 }
133 }
134
135 pub const fn is_available(self) -> bool {
137 match self {
138 Self::Md5 => cfg!(feature = "md5"),
139 Self::Sha1 => cfg!(feature = "sha1"),
140 Self::Sha224 | Self::Sha256 | Self::Sha384 | Self::Sha512 => cfg!(feature = "sha2"),
141 Self::Sha3_224 | Self::Sha3_256 | Self::Sha3_384 | Self::Sha3_512 => {
142 cfg!(feature = "sha3")
143 }
144 Self::Blake2b512 | Self::Blake2s256 => cfg!(feature = "blake2"),
145 Self::Blake3 => cfg!(feature = "blake3"),
146 Self::Xxh3 | Self::Xxh128 => cfg!(feature = "xxhash"),
147 }
148 }
149
150 pub fn hasher(self) -> Result<Box<dyn Hasher>, HashUtilityError> {
155 HashRegistry::get_hasher(self.canonical_name())
156 }
157}
158
159impl fmt::Display for Algorithm {
160 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
161 formatter.write_str(self.canonical_name())
162 }
163}
164
165impl FromStr for Algorithm {
166 type Err = HashUtilityError;
167
168 fn from_str(value: &str) -> Result<Self, Self::Err> {
169 let trimmed = value.trim();
170 match trimmed {
171 "md5" => Ok(Self::Md5),
172 "sha1" | "sha-1" => Ok(Self::Sha1),
173 "sha224" | "sha-224" => Ok(Self::Sha224),
174 "sha256" | "sha-256" => Ok(Self::Sha256),
175 "sha384" | "sha-384" => Ok(Self::Sha384),
176 "sha512" | "sha-512" => Ok(Self::Sha512),
177 "sha3-224" => Ok(Self::Sha3_224),
178 "sha3-256" => Ok(Self::Sha3_256),
179 "sha3-384" => Ok(Self::Sha3_384),
180 "sha3-512" => Ok(Self::Sha3_512),
181 "blake2b" | "blake2b-512" => Ok(Self::Blake2b512),
182 "blake2s" | "blake2s-256" => Ok(Self::Blake2s256),
183 "blake3" => Ok(Self::Blake3),
184 "xxh3" => Ok(Self::Xxh3),
185 "xxh128" => Ok(Self::Xxh128),
186 _ => parse_algorithm_case_insensitive(trimmed, value),
187 }
188 }
189}
190
191fn parse_algorithm_case_insensitive(
192 trimmed: &str,
193 original: &str,
194) -> Result<Algorithm, HashUtilityError> {
195 for algorithm in Algorithm::ALL {
196 if trimmed.eq_ignore_ascii_case(algorithm.canonical_name())
197 || trimmed.eq_ignore_ascii_case(algorithm.display_name())
198 {
199 return Ok(algorithm);
200 }
201 }
202 Err(HashUtilityError::UnsupportedAlgorithm {
203 algorithm: original.to_owned(),
204 })
205}
206
207#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize)]
208#[serde(rename_all = "kebab-case")]
209pub enum HashMode {
211 #[default]
213 Full,
214 Sampled,
216}
217
218#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)]
220pub struct DigestValue {
221 pub algorithm: Algorithm,
223 pub(crate) bytes: Vec<u8>,
224}
225
226impl DigestValue {
227 pub fn from_bytes(algorithm: Algorithm, bytes: Vec<u8>) -> Result<Self, HashUtilityError> {
231 if bytes.len() != algorithm.output_size() {
232 return Err(HashUtilityError::InvalidDigest {
233 algorithm: algorithm.to_string(),
234 reason: format!(
235 "expected {} bytes, found {}",
236 algorithm.output_size(),
237 bytes.len()
238 ),
239 });
240 }
241 Ok(Self { algorithm, bytes })
242 }
243
244 pub fn from_hex(algorithm: Algorithm, value: &str) -> Result<Self, HashUtilityError> {
246 if value.len() != algorithm.output_size() * 2 {
247 return Err(HashUtilityError::InvalidDigest {
248 algorithm: algorithm.to_string(),
249 reason: format!(
250 "expected {} hexadecimal characters, found {}",
251 algorithm.output_size() * 2,
252 value.len()
253 ),
254 });
255 }
256 let bytes = value
257 .as_bytes()
258 .as_chunks::<2>()
259 .0
260 .iter()
261 .map(|pair| {
262 let text = std::str::from_utf8(pair).expect("hexadecimal text is ASCII");
263 u8::from_str_radix(text, 16).map_err(|_| HashUtilityError::InvalidDigest {
264 algorithm: algorithm.to_string(),
265 reason: "digest contains a non-hexadecimal character".to_owned(),
266 })
267 })
268 .collect::<Result<Vec<_>, _>>()?;
269 Ok(Self { algorithm, bytes })
270 }
271
272 pub fn to_hex(&self) -> String {
274 bytes_to_hex(&self.bytes)
275 }
276
277 pub fn as_bytes(&self) -> &[u8] {
279 &self.bytes
280 }
281}
282
283#[derive(Debug, Clone, serde::Serialize)]
285#[non_exhaustive]
286pub struct AlgorithmInfo {
287 pub name: String,
289 pub output_bits: usize,
291 pub post_quantum: bool,
293 pub cryptographic: bool,
295}