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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
pub mod error;
use error::Error;
use rand::{thread_rng, Rng};
use std::borrow::Cow;
use std::convert::{TryFrom, TryInto};
use std::fmt;
#[derive(Debug)]
pub struct PhPass<'a> {
passes: usize,
salt: Cow<'a, str>,
hash: [u8; 16],
}
const CRYPT: &str = r"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
impl<'a> TryFrom<&'a str> for PhPass<'a> {
type Error = Error;
fn try_from(s: &'a str) -> Result<Self, Self::Error> {
if s.len() < 34 {
return Err(Error::OldWPFormat);
}
if &s[0..3] != "$P$" {
return Err(Error::InvalidId(s[0..3].to_string()));
}
let passes = s.chars().nth(3);
let passes = CRYPT
.find(passes.ok_or(Error::InvalidPasses(passes))?)
.ok_or(Error::InvalidPasses(passes))?;
let encoded = &s[12..];
let len = encoded.len();
let hash = base64::decode_config(
std::iter::repeat(b'.')
.take(3 - len % 3)
.chain(encoded.bytes().rev())
.collect::<Vec<_>>(),
base64::CRYPT,
)?
.iter()
.rev()
.take(16)
.copied()
.collect::<Vec<_>>()
.as_slice()
.try_into()?;
Ok(Self {
passes,
salt: Cow::Borrowed(&s[4..12]),
hash,
})
}
}
impl fmt::Display for PhPass<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let iter = self.hash.chunks_exact(3);
let end = base64::encode_config([0, 0, iter.remainder()[0]], base64::CRYPT)
.chars()
.rev()
.take(2)
.collect::<String>();
let mapped = iter
.map(|chunk| {
base64::encode_config(
chunk.iter().rev().copied().collect::<Vec<_>>(),
base64::CRYPT,
)
.chars()
.rev()
.collect::<String>()
})
.chain(std::iter::once(end))
.collect::<String>();
write!(
f,
"$P${}{}{}",
&CRYPT[self.passes..self.passes + 1],
self.salt,
mapped
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_round_trip() {
let random_salt = PhPass::new("hello").to_string();
let phpass = PhPass::try_from(random_salt.as_ref()).unwrap();
assert!(
phpass.verify("hello").is_ok(),
"Failed to verify random-salt password hash"
)
}
#[test]
fn test_verify_parse() {
let phpass = PhPass::try_from("$P$BgUdq1RzEBYd9Tm/uZC7mz/l5F.x4N1").unwrap();
assert!(
phpass.verify("development").is_ok(),
"Failed to verify parsed password hash"
)
}
#[test]
fn test_verify_new() {
let phpass = PhPass::new("world!");
assert!(
phpass.verify("world!").is_ok(),
"Failed to verify random-salt password hash"
)
}
}
fn checksum<T: AsRef<[u8]>, U: AsRef<[u8]>>(pass: T, salt: U, passes: usize) -> [u8; 16] {
let pass = pass.as_ref();
let salt = salt.as_ref();
let checksum = (0..1 << passes).fold(md5::compute([salt, pass].concat()), |a, _| {
md5::compute([&a.0, pass].concat())
});
checksum.0
}
impl PhPass<'_> {
pub fn new<'a, T: AsRef<[u8]>>(pass: T) -> PhPass<'a> {
let mut rng = thread_rng();
let passes = 13;
let salt = base64::encode(rng.gen::<[u8; 6]>());
let hash = checksum(&pass, &salt, passes);
PhPass {
passes,
salt: Cow::Owned(salt),
hash,
}
}
pub fn verify<T: AsRef<[u8]>>(&self, pass: T) -> Result<(), Error> {
if self.hash == checksum(pass, self.salt.as_ref(), self.passes) {
Ok(())
} else {
Err(Error::VerificationError)
}
}
}