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
#![no_std]
#![doc(html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo_small.png")]
#[cfg(feature = "std")]
extern crate std;
#[cfg(feature = "include_simple")]
extern crate alloc;
mod errors;
mod simple;
#[cfg(feature = "include_simple")]
pub use crate::errors::CheckError;
#[cfg(feature = "include_simple")]
pub use crate::simple::{pbkdf2_check, pbkdf2_simple};
#[cfg(feature = "parallel")]
use rayon::prelude::*;
use crypto_mac::generic_array::typenum::Unsigned;
use crypto_mac::{Mac, NewMac};
#[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<F>(i: u32, chunk: &mut [u8], prf: &F, salt: &[u8], rounds: u32)
where
F: Mac + 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().into_bytes();
xor(chunk, &salt);
salt
};
for _ in 1..rounds {
let mut prfc = prf.clone();
prfc.update(&salt);
salt = prfc.finalize().into_bytes();
xor(chunk, &salt);
}
}
#[cfg(feature = "parallel")]
#[inline]
pub fn pbkdf2<F>(password: &[u8], salt: &[u8], rounds: u32, res: &mut [u8])
where
F: Mac + NewMac + Clone + Sync,
{
let n = F::OutputSize::to_usize();
let prf = F::new_varkey(password).expect("HMAC accepts all key sizes");
res.par_chunks_mut(n).enumerate().for_each(|(i, chunk)| {
pbkdf2_body(i as u32, chunk, &prf, salt, rounds);
});
}
#[cfg(not(feature = "parallel"))]
#[inline]
pub fn pbkdf2<F>(password: &[u8], salt: &[u8], rounds: u32, res: &mut [u8])
where
F: Mac + NewMac + Clone + Sync,
{
let n = F::OutputSize::to_usize();
let prf = F::new_varkey(password).expect("HMAC accepts all key sizes");
for (i, chunk) in res.chunks_mut(n).enumerate() {
pbkdf2_body(i as u32, chunk, &prf, salt, rounds);
}
}