1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
use blake3::Hasher;
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, PartialOrd)]
pub struct Hash {
password: String,
hash: String,
}
impl Hash {
pub fn entropy(&self) -> f64 {
let mut entropy = 0.0;
for c in self.hash.chars() {
let p = (c as u8) as f64 / 255.0;
entropy -= p * p.log2();
}
entropy
}
pub fn generate_hash(&self) -> String {
let mut hasher = Hasher::new();
hasher.update(self.password.as_bytes());
let hash = hasher.finalize().to_hex();
hash.to_string()
}
pub fn hash(&self) -> &str {
&self.hash
}
pub fn hash_length(&self) -> usize {
self.hash.len()
}
pub fn new() -> Self {
Self {
password: String::default(),
hash: String::default(),
}
}
pub fn password(&self) -> &str {
&self.password
}
pub fn password_length(&self) -> usize {
self.password.len()
}
pub fn set_hash(&mut self, hash: &str) {
self.hash = hash.to_string();
}
pub fn set_password(&mut self, password: &str) {
self.password = password.to_string();
self.hash = self.generate_hash();
}
pub fn verify(&self, hash: &str, password: &str) -> bool {
let mut hasher = Hasher::new();
hasher.update(password.as_bytes());
let password_hash = hasher.finalize().to_hex();
let password_hash_str = password_hash.to_string();
password_hash_str == hash
}
}
impl std::fmt::Display for Hash {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
f,
"Hash {{ password: {}, hash: {} }}",
self.password, self.hash
)
}
}
impl Default for Hash {
fn default() -> Self {
Self::new()
}
}