-
Notifications
You must be signed in to change notification settings - Fork 114
Expand file tree
/
Copy pathlib.rs
More file actions
299 lines (276 loc) · 8.71 KB
/
Copy pathlib.rs
File metadata and controls
299 lines (276 loc) · 8.71 KB
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
#![no_std]
#![doc = include_str!("../README.md")]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg",
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg"
)]
//! # Examples
//!
//! PBKDF2 is defined in terms of a keyed pseudo-random function (PRF).
//! The most commonly used PRF for this purpose is HMAC. In such cases
//! you can use [`pbkdf2_hmac`] and [`pbkdf2_hmac_array`] functions.
//! The former accepts a byte slice which gets filled with generated key,
//! while the latter returns an array with generated key of requested length.
//!
//! Note that it is not recommended to generate keys using PBKDF2 that exceed
//! the output size of the PRF (equal to the hash size in the case of HMAC).
//! If you need to generate a large amount of cryptographic material,
//! consider using a separate [key derivation function][KDF].
//!
//! [KDF]: https://github.com/RustCrypto/KDFs
//!
//! ## Low-level API
//!
//! This API operates directly on byte slices:
//!
//! ```
//! # #[cfg(feature = "hmac")] {
//! use hex_literal::hex;
//! use pbkdf2::{pbkdf2_hmac, pbkdf2_hmac_array};
//! use sha2::Sha256;
//!
//! let password = b"password";
//! let salt = b"salt";
//! // number of iterations
//! let n = 600_000;
//! // Expected value of generated key
//! let expected = hex!("669cfe52482116fda1aa2cbe409b2f56c8e45637");
//!
//! let mut key1 = [0u8; 20];
//! pbkdf2_hmac::<Sha256>(password, salt, n, &mut key1);
//! assert_eq!(key1, expected);
//!
//! let key2 = pbkdf2_hmac_array::<Sha256, 20>(password, salt, n);
//! assert_eq!(key2, expected);
//! # }
//! ```
//!
//! If you want to use a different PRF, then you can use [`pbkdf2`] and [`pbkdf2_array`] functions.
//!
//! This crates also provides the high-level password-hashing API through
//! the [`Pbkdf2`] struct and traits defined in the
//! [`password-hash`][password_hash] crate.
//!
//! Add the following to your crate's `Cargo.toml` to import it:
//!
//! ```toml
//! [dependencies]
//! pbkdf2 = { version = "0.12", features = ["password-hash"] }
//! rand_core = { version = "0.6", features = ["std"] }
//! ```
//!
//! ## PHC string API
//!
//! This crate can produce and verify password hash strings encoded in the Password Hashing
//! Competition (PHC) string format.
//!
//! The following example demonstrates the high-level password hashing API:
//!
#![cfg_attr(all(feature = "getrandom", feature = "phc"), doc = "```")]
#![cfg_attr(not(all(feature = "getrandom", feature = "phc")), doc = "```ignore")]
//! # fn main() -> Result<(), Box<dyn core::error::Error>> {
//! // NOTE: example requires `getrandom` feature is enabled
//!
//! use pbkdf2::{
//! password_hash::{PasswordHasher, PasswordVerifier},
//! phc::PasswordHash,
//! Pbkdf2
//! };
//!
//! let pbkdf2 = Pbkdf2::default(); // Uses `Algorithm::default()` and `Params::RECOMMENDED`
//! let password = b"hunter2"; // Bad password; don't actually use!
//!
//! // Hash password to PHC string ($pbkdf2-sha256$...)
//! let pwhash: PasswordHash = pbkdf2.hash_password(password)?;
//! let pwhash_string = pwhash.to_string();
//!
//! // Verify password against PHC string
//! let parsed_hash = PasswordHash::new(&pwhash_string)?;
//! pbkdf2.verify_password(password, &parsed_hash)?;
//! # Ok(())
//! # }
//! ```
#[cfg(feature = "mcf")]
pub mod mcf;
#[cfg(feature = "phc")]
pub mod phc;
#[cfg(any(feature = "mcf", feature = "phc"))]
mod algorithm;
#[cfg(any(feature = "mcf", feature = "phc"))]
mod params;
#[cfg(any(feature = "mcf", feature = "phc"))]
pub use crate::{algorithm::Algorithm, params::Params};
#[cfg(feature = "hmac")]
pub use hmac;
#[cfg(any(feature = "mcf", feature = "phc"))]
pub use password_hash;
#[cfg(any(feature = "mcf", feature = "phc"))]
pub use password_hash::{PasswordHasher, PasswordVerifier};
use digest::{FixedOutput, InvalidLength, KeyInit, Update, typenum::Unsigned};
#[cfg(feature = "hmac")]
use hmac::EagerHash;
#[inline(always)]
fn xor(res: &mut [u8], salt: &[u8]) {
debug_assert!(salt.len() >= res.len(), "length mismatch in xor");
res.iter_mut().zip(salt.iter()).for_each(|(a, b)| *a ^= b);
}
#[inline(always)]
fn pbkdf2_body<PRF>(i: u32, chunk: &mut [u8], prf: &PRF, salt: &[u8], rounds: u32)
where
PRF: Update + FixedOutput + Clone,
{
for v in chunk.iter_mut() {
*v = 0;
}
let mut salt = {
let mut prfc = prf.clone();
prfc.update(salt);
prfc.update(&(i + 1).to_be_bytes());
let salt = prfc.finalize_fixed();
xor(chunk, &salt);
salt
};
for _ in 1..rounds {
let mut prfc = prf.clone();
prfc.update(&salt);
salt = prfc.finalize_fixed();
xor(chunk, &salt);
}
}
/// Generic implementation of PBKDF2 algorithm which accepts an arbitrary keyed PRF.
///
/// ```
/// use hex_literal::hex;
/// use pbkdf2::pbkdf2;
/// use hmac::Hmac;
/// use sha2::Sha256;
///
/// let mut buf = [0u8; 20];
/// pbkdf2::<Hmac<Sha256>>(b"password", b"salt", 600_000, &mut buf)
/// .expect("HMAC can be initialized with any key length");
/// assert_eq!(buf, hex!("669cfe52482116fda1aa2cbe409b2f56c8e45637"));
/// ```
#[inline]
pub fn pbkdf2<PRF>(
password: &[u8],
salt: &[u8],
rounds: u32,
res: &mut [u8],
) -> Result<(), InvalidLength>
where
PRF: KeyInit + Update + FixedOutput + Clone + Sync,
{
let n = PRF::OutputSize::to_usize();
let prf = PRF::new_from_slice(password)?;
for (i, chunk) in res.chunks_mut(n).enumerate() {
pbkdf2_body(i as u32, chunk, &prf, salt, rounds);
}
Ok(())
}
/// A variant of the [`pbkdf2`] function which returns an array instead of filling an input slice.
///
/// ```
/// use hex_literal::hex;
/// use pbkdf2::pbkdf2_array;
/// use hmac::Hmac;
/// use sha2::Sha256;
///
/// let res = pbkdf2_array::<Hmac<Sha256>, 20>(b"password", b"salt", 600_000)
/// .expect("HMAC can be initialized with any key length");
/// assert_eq!(res, hex!("669cfe52482116fda1aa2cbe409b2f56c8e45637"));
/// ```
#[inline]
pub fn pbkdf2_array<PRF, const N: usize>(
password: &[u8],
salt: &[u8],
rounds: u32,
) -> Result<[u8; N], InvalidLength>
where
PRF: KeyInit + Update + FixedOutput + Clone + Sync,
{
let mut buf = [0u8; N];
pbkdf2::<PRF>(password, salt, rounds, &mut buf).map(|()| buf)
}
/// A variant of the [`pbkdf2`] function which uses HMAC for PRF.
///
/// It's generic over (eager) hash functions.
///
/// ```
/// use hex_literal::hex;
/// use pbkdf2::pbkdf2_hmac;
/// use sha2::Sha256;
///
/// let mut buf = [0u8; 20];
/// pbkdf2_hmac::<Sha256>(b"password", b"salt", 600_000, &mut buf);
/// assert_eq!(buf, hex!("669cfe52482116fda1aa2cbe409b2f56c8e45637"));
/// ```
#[cfg(feature = "hmac")]
pub fn pbkdf2_hmac<D>(password: &[u8], salt: &[u8], rounds: u32, res: &mut [u8])
where
D: EagerHash<Core: Sync>,
{
crate::pbkdf2::<hmac::Hmac<D>>(password, salt, rounds, res)
.expect("HMAC can be initialized with any key length");
}
/// A variant of the [`pbkdf2_hmac`] function which returns an array
/// instead of filling an input slice.
///
/// ```
/// use hex_literal::hex;
/// use pbkdf2::pbkdf2_hmac_array;
/// use sha2::Sha256;
///
/// assert_eq!(
/// pbkdf2_hmac_array::<Sha256, 20>(b"password", b"salt", 600_000),
/// hex!("669cfe52482116fda1aa2cbe409b2f56c8e45637"),
/// );
/// ```
#[cfg(feature = "hmac")]
pub fn pbkdf2_hmac_array<D, const N: usize>(password: &[u8], salt: &[u8], rounds: u32) -> [u8; N]
where
D: EagerHash<Core: Sync>,
{
let mut buf = [0u8; N];
pbkdf2_hmac::<D>(password, salt, rounds, &mut buf);
buf
}
/// PBKDF2 type for use with the [`PasswordHasher`] and [`PasswordVerifier`] traits, which
/// implements support for password hash strings.
///
/// Supports the following password hash string formats, gated under the following crate features:
/// - `mcf`: support for the Modular Crypt Format
/// - `phc`: support for the Password Hashing Competition string format
#[cfg(any(feature = "mcf", feature = "phc"))]
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub struct Pbkdf2 {
/// Algorithm to use
algorithm: Algorithm,
/// Default parameters to use.
params: Params,
}
#[cfg(any(feature = "mcf", feature = "phc"))]
impl Pbkdf2 {
/// Initialize [`Pbkdf2`] with default parameters.
pub const fn new(algorithm: Algorithm, params: Params) -> Self {
Self { algorithm, params }
}
}
#[cfg(any(feature = "mcf", feature = "phc"))]
impl From<Algorithm> for Pbkdf2 {
fn from(algorithm: Algorithm) -> Self {
Self {
algorithm,
params: Params::default(),
}
}
}
#[cfg(any(feature = "mcf", feature = "phc"))]
impl From<Params> for Pbkdf2 {
fn from(params: Params) -> Self {
Self {
algorithm: Algorithm::default(),
params,
}
}
}