#[cfg(feature = "std")]
use alloc::string::String;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
#[cfg(feature = "alloc")]
use crate::eks::Backend;
use crate::encoding::{HashParts, Version};
use crate::error::{BcryptError, BcryptResult};
pub const MIN_COST: u32 = 4;
pub const MAX_COST: u32 = 31;
pub const DEFAULT_COST: u32 = 12;
fn padded_key(password: &[u8]) -> ([u8; 72], usize) {
let mut key = [0u8; 72];
let copied = password.len().min(72);
key[..copied].copy_from_slice(&password[..copied]);
(key, (copied + 1).min(72))
}
#[inline]
fn check_cost(cost: u32) -> BcryptResult<()> {
if (MIN_COST..=MAX_COST).contains(&cost) {
Ok(())
} else {
Err(BcryptError::CostNotAllowed(cost))
}
}
#[inline]
fn check_truncation(password_len: usize) -> BcryptResult<()> {
if password_len >= 72 {
Err(BcryptError::Truncation(password_len + 1))
} else {
Ok(())
}
}
#[cfg(feature = "std")]
fn random_salt() -> BcryptResult<[u8; 16]> {
let mut salt = [0u8; 16];
crate::random::os_random(&mut salt).map_err(BcryptError::Rand)?;
Ok(salt)
}
#[inline(always)]
fn wipe_key(key: &mut [u8; 72]) {
#[cfg(feature = "zeroize")]
crate::wipe::secure_wipe_bytes(key);
#[cfg(not(feature = "zeroize"))]
let _ = key;
}
#[inline(always)]
fn wipe_words(words: &mut [u32]) {
#[cfg(feature = "zeroize")]
crate::wipe::secure_wipe_u32(words);
#[cfg(not(feature = "zeroize"))]
let _ = words;
}
#[cfg(feature = "alloc")]
#[inline(always)]
fn wipe_bytes(bytes: &mut [u8]) {
#[cfg(feature = "zeroize")]
crate::wipe::secure_wipe_bytes(bytes);
#[cfg(not(feature = "zeroize"))]
let _ = bytes;
}
#[inline(never)]
#[must_use]
pub fn constant_time_eq(a: &[u8; 23], b: &[u8; 23]) -> bool {
let diff = a.iter().zip(b.iter()).fold(0u8, |d, (x, y)| d | (x ^ y));
core::hint::black_box(diff) == 0
}
#[must_use]
pub fn bcrypt(cost: u32, salt: [u8; 16], password: &[u8]) -> [u8; 24] {
let (mut key, key_len) = padded_key(password);
let mut key_words = [crate::eks::expand_key_words(&key, key_len)];
wipe_key(&mut key);
let salt_words = [crate::eks::salt_words(&salt)];
let mut out = [0u8; 24];
crate::eks::scalar::bcrypt_lanes(
cost,
&key_words,
&salt_words,
core::slice::from_mut(&mut out),
);
wipe_words(key_words.as_flattened_mut());
out
}
#[cfg(feature = "std")]
pub fn hash<P: AsRef<[u8]>>(password: P, cost: u32) -> BcryptResult<String> {
Ok(hash_with_result(password, cost)?.format_for_version(Version::TwoB))
}
#[cfg(feature = "std")]
pub fn hash_bytes<P: AsRef<[u8]>>(password: P, cost: u32) -> BcryptResult<[u8; 60]> {
Ok(hash_with_result(password, cost)?.format_bytes(Version::TwoB))
}
#[cfg(feature = "std")]
pub fn hash_with_result<P: AsRef<[u8]>>(password: P, cost: u32) -> BcryptResult<HashParts> {
check_cost(cost)?;
let salt = random_salt()?;
hash_with_salt(password, cost, salt)
}
pub fn hash_with_salt<P: AsRef<[u8]>>(
password: P,
cost: u32,
salt: [u8; 16],
) -> BcryptResult<HashParts> {
check_cost(cost)?;
let out = bcrypt(cost, salt, password.as_ref());
let mut hash = [0u8; 23];
hash.copy_from_slice(&out[..23]);
Ok(HashParts::new(cost, salt, hash))
}
pub fn hash_with_salt_bytes<P: AsRef<[u8]>>(
password: P,
cost: u32,
salt: [u8; 16],
) -> BcryptResult<[u8; 60]> {
Ok(hash_with_salt(password, cost, salt)?.format_bytes(Version::TwoB))
}
pub fn verify<P: AsRef<[u8]>>(password: P, hash: &str) -> BcryptResult<bool> {
let parts: HashParts = hash.parse()?;
let out = bcrypt(parts.get_cost(), parts.get_salt_raw(), password.as_ref());
let mut computed = [0u8; 23];
computed.copy_from_slice(&out[..23]);
Ok(constant_time_eq(&computed, &parts.get_hash()))
}
#[cfg(feature = "std")]
pub fn non_truncating_hash<P: AsRef<[u8]>>(password: P, cost: u32) -> BcryptResult<String> {
check_truncation(password.as_ref().len())?;
hash(password, cost)
}
#[cfg(feature = "std")]
pub fn non_truncating_hash_bytes<P: AsRef<[u8]>>(
password: P,
cost: u32,
) -> BcryptResult<[u8; 60]> {
check_truncation(password.as_ref().len())?;
hash_bytes(password, cost)
}
#[cfg(feature = "std")]
pub fn non_truncating_hash_with_result<P: AsRef<[u8]>>(
password: P,
cost: u32,
) -> BcryptResult<HashParts> {
check_truncation(password.as_ref().len())?;
hash_with_result(password, cost)
}
pub fn non_truncating_hash_with_salt<P: AsRef<[u8]>>(
password: P,
cost: u32,
salt: [u8; 16],
) -> BcryptResult<HashParts> {
check_truncation(password.as_ref().len())?;
hash_with_salt(password, cost, salt)
}
pub fn non_truncating_hash_with_salt_bytes<P: AsRef<[u8]>>(
password: P,
cost: u32,
salt: [u8; 16],
) -> BcryptResult<[u8; 60]> {
check_truncation(password.as_ref().len())?;
hash_with_salt_bytes(password, cost, salt)
}
pub fn non_truncating_verify<P: AsRef<[u8]>>(password: P, hash: &str) -> BcryptResult<bool> {
check_truncation(password.as_ref().len())?;
verify(password, hash)
}
#[cfg(feature = "alloc")]
unsafe fn bcrypt_many_inner(
backend: Backend,
cost: u32,
kws: &[[u32; 18]],
sws: &[[u32; 4]],
outs: &mut [[u8; 24]],
) {
debug_assert_eq!(kws.len(), sws.len());
debug_assert_eq!(kws.len(), outs.len());
if kws.is_empty() {
return;
}
#[cfg(feature = "parallel")]
{
let workers = parallel_workers(kws.len());
if workers > 1 {
unsafe { bcrypt_many_scoped(backend, cost, kws, sws, outs, workers) };
return;
}
}
unsafe { bcrypt_many_chunked(backend, cost, kws, sws, outs) };
}
#[cfg(feature = "alloc")]
unsafe fn bcrypt_many_chunked(
backend: Backend,
cost: u32,
kws: &[[u32; 18]],
sws: &[[u32; 4]],
outs: &mut [[u8; 24]],
) {
debug_assert_eq!(kws.len(), sws.len());
debug_assert_eq!(kws.len(), outs.len());
if kws.is_empty() {
return;
}
let kernel = crate::eks::bcrypt_lanes_fn(backend);
let scalar = crate::eks::bcrypt_lanes_fn(Backend::Scalar);
let lanes = backend.lanes();
debug_assert!(lanes <= 16);
let mut kw = [[0u32; 18]; 16];
let mut sw = [[0u32; 4]; 16];
let mut out = [[0u8; 24]; 16];
let mut base = 0;
while base < kws.len() {
let remaining = kws.len() - base;
if remaining <= 2 && remaining < lanes {
for (slot, (&kw_in, &sw_in)) in kws[base..].iter().zip(&sws[base..]).enumerate() {
kw[0] = kw_in;
sw[0] = sw_in;
unsafe { scalar(cost, &kw[..1], &sw[..1], &mut out[..1]) };
outs[base + slot] = out[0];
}
wipe_words(kw.as_flattened_mut());
wipe_words(sw.as_flattened_mut());
wipe_bytes(out.as_flattened_mut());
break;
}
let group = lanes.min(remaining);
debug_assert!(group >= 1);
kw[..group].copy_from_slice(&kws[base..base + group]);
sw[..group].copy_from_slice(&sws[base..base + group]);
let fill_kw = kw[0];
let fill_sw = sw[0];
for slot in &mut kw[group..lanes] {
*slot = fill_kw;
}
for slot in &mut sw[group..lanes] {
*slot = fill_sw;
}
unsafe { kernel(cost, &kw[..lanes], &sw[..lanes], &mut out[..lanes]) };
outs[base..base + group].copy_from_slice(&out[..group]);
base += group;
wipe_words(kw.as_flattened_mut());
wipe_words(sw.as_flattened_mut());
wipe_bytes(out.as_flattened_mut());
}
}
#[cfg(feature = "parallel")]
fn parallel_workers(items: usize) -> usize {
let cores = std::thread::available_parallelism().map_or(1, core::num::NonZero::get);
if cores > 1 && items >= 2 * cores { cores } else { 1 }
}
#[cfg(feature = "parallel")]
#[derive(Copy, Clone)]
struct OutBase(*mut [u8; 24]);
#[cfg(feature = "parallel")]
unsafe impl Send for OutBase {}
#[cfg(feature = "parallel")]
unsafe impl Sync for OutBase {}
#[cfg(feature = "parallel")]
impl OutBase {
unsafe fn at(self, start: usize) -> *mut [u8; 24] {
unsafe { self.0.add(start) }
}
}
#[cfg(feature = "parallel")]
unsafe fn bcrypt_many_scoped(
backend: Backend,
cost: u32,
kws: &[[u32; 18]],
sws: &[[u32; 4]],
outs: &mut [[u8; 24]],
workers: usize,
) {
use core::sync::atomic::{AtomicUsize, Ordering};
debug_assert!(workers > 1);
let per = kws.len().div_ceil(workers).next_multiple_of(backend.lanes());
let chunks = kws.len().div_ceil(per);
let base = OutBase(outs.as_mut_ptr());
let next = AtomicUsize::new(0);
let next = &next;
let run = move || loop {
let i = next.fetch_add(1, Ordering::Relaxed);
if i >= chunks {
return;
}
let start = i * per;
let end = (start + per).min(kws.len());
let out = unsafe { core::slice::from_raw_parts_mut(base.at(start), end - start) };
unsafe { bcrypt_many_chunked(backend, cost, &kws[start..end], &sws[start..end], out) };
};
std::thread::scope(|scope| {
for _ in 1..workers {
let _ = std::thread::Builder::new().spawn_scoped(scope, run);
}
run();
});
}
#[cfg(feature = "alloc")]
fn check_batch(cost: u32, passwords: &[&[u8]], salts: &[[u8; 16]]) -> BcryptResult<()> {
check_cost(cost)?;
if passwords.len() != salts.len() {
return Err(BcryptError::BatchLengthMismatch {
passwords: passwords.len(),
salts: salts.len(),
});
}
Ok(())
}
#[cfg(feature = "alloc")]
fn prep_words(passwords: &[&[u8]], salts: &[[u8; 16]]) -> (Vec<[u32; 18]>, Vec<[u32; 4]>) {
let mut key_words: Vec<[u32; 18]> = Vec::with_capacity(passwords.len());
let mut salt_words: Vec<[u32; 4]> = Vec::with_capacity(salts.len());
for (password, salt) in passwords.iter().zip(salts) {
let (mut key, key_len) = padded_key(password);
key_words.push(crate::eks::expand_key_words(&key, key_len));
wipe_key(&mut key);
salt_words.push(crate::eks::salt_words(salt));
}
(key_words, salt_words)
}
#[cfg(feature = "alloc")]
pub fn bcrypt_many(
cost: u32,
passwords: &[&[u8]],
salts: &[[u8; 16]],
) -> BcryptResult<Vec<[u8; 24]>> {
check_batch(cost, passwords, salts)?;
if passwords.is_empty() {
return Ok(Vec::new());
}
let (mut key_words, salt_words) = prep_words(passwords, salts);
let mut outs = alloc::vec![[0u8; 24]; passwords.len()];
unsafe { bcrypt_many_inner(crate::eks::backend(), cost, &key_words, &salt_words, &mut outs) };
wipe_words(key_words.as_flattened_mut());
Ok(outs)
}
#[cfg(all(feature = "internal-api", feature = "alloc"))]
pub unsafe fn bcrypt_many_with_backend(
backend: Backend,
cost: u32,
passwords: &[&[u8]],
salts: &[[u8; 16]],
) -> BcryptResult<Vec<[u8; 24]>> {
check_batch(cost, passwords, salts)?;
let (mut key_words, salt_words) = prep_words(passwords, salts);
let mut outs = alloc::vec![[0u8; 24]; passwords.len()];
unsafe { bcrypt_many_inner(backend, cost, &key_words, &salt_words, &mut outs) };
wipe_words(key_words.as_flattened_mut());
Ok(outs)
}
#[cfg(feature = "alloc")]
pub fn hash_many_with_salts(
passwords: &[&[u8]],
salts: &[[u8; 16]],
cost: u32,
) -> BcryptResult<Vec<HashParts>> {
let outs = bcrypt_many(cost, passwords, salts)?;
Ok(outs
.iter()
.zip(salts.iter())
.map(|(out, salt)| {
let mut hash = [0u8; 23];
hash.copy_from_slice(&out[..23]);
HashParts::new(cost, *salt, hash)
})
.collect())
}
#[cfg(feature = "std")]
pub fn hash_many(passwords: &[&[u8]], cost: u32) -> BcryptResult<Vec<String>> {
check_cost(cost)?;
let mut salts: Vec<[u8; 16]> = Vec::with_capacity(passwords.len());
for _ in passwords {
salts.push(random_salt()?);
}
let parts = hash_many_with_salts(passwords, &salts, cost)?;
Ok(parts
.iter()
.map(|p| p.format_for_version(Version::TwoB))
.collect())
}
#[cfg(feature = "alloc")]
type VerifyItem = (usize, [u8; 16], [u8; 23]);
#[cfg(feature = "alloc")]
type CostGroups = Vec<(u32, Vec<VerifyItem>)>;
#[cfg(feature = "alloc")]
pub fn verify_many(passwords: &[&[u8]], hashes: &[&str]) -> Vec<BcryptResult<bool>> {
let mut results: Vec<BcryptResult<bool>> = Vec::with_capacity(hashes.len());
let mut groups: CostGroups = Vec::new();
for (i, hash) in hashes.iter().enumerate() {
if passwords.get(i).is_none() {
results.push(Err(BcryptError::BatchLengthMismatch {
passwords: passwords.len(),
salts: hashes.len(),
}));
continue;
}
match hash.parse::<HashParts>() {
Ok(parts) => {
let cost = parts.get_cost();
let pos = match groups.iter().position(|&(c, _)| c == cost) {
Some(p) => p,
None => {
groups.push((cost, Vec::new()));
groups.len() - 1
}
};
groups[pos]
.1
.push((i, parts.get_salt_raw(), parts.get_hash()));
results.push(Ok(false));
}
Err(e) => results.push(Err(e)),
}
}
for (cost, items) in &groups {
let mut key_words: Vec<[u32; 18]> = Vec::with_capacity(items.len());
let mut salt_words: Vec<[u32; 4]> = Vec::with_capacity(items.len());
for &(i, salt, _) in items {
let (mut key, key_len) = padded_key(passwords[i]);
key_words.push(crate::eks::expand_key_words(&key, key_len));
wipe_key(&mut key);
salt_words.push(crate::eks::salt_words(&salt));
}
let mut outs = alloc::vec![[0u8; 24]; items.len()];
unsafe { bcrypt_many_inner(crate::eks::backend(), *cost, &key_words, &salt_words, &mut outs) };
for (j, &(i, _, expected)) in items.iter().enumerate() {
let mut computed = [0u8; 23];
computed.copy_from_slice(&outs[j][..23]);
results[i] = Ok(constant_time_eq(&computed, &expected));
}
wipe_words(key_words.as_flattened_mut());
}
results
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
const VECTOR_2A: &str = "$2a$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW";
#[test]
fn padded_key_edge_cases() {
let (key, len) = padded_key(b"");
assert_eq!(len, 1);
assert!(key.iter().all(|&b| b == 0));
let pw71 = [b'a'; 71];
let (key, len) = padded_key(&pw71);
assert_eq!(len, 72);
assert_eq!(&key[..71], &pw71[..]);
assert_eq!(key[71], 0);
let pw72 = [b'a'; 72];
let (key, len) = padded_key(&pw72);
assert_eq!(len, 72);
assert_eq!(key, pw72);
for too_long in [&[b'a'; 73][..], &[b'a'; 100][..]] {
let (key_long, len_long) = padded_key(too_long);
assert_eq!(len_long, 72);
assert_eq!(key_long, key);
}
}
#[cfg(not(miri))]
#[test]
fn passwords_longer_than_72_bytes_hash_like_their_prefix() {
let salt = [0x42; 16];
let pw72 = [b'x'; 72];
let pw73 = [b'x'; 73];
let pw100 = [b'x'; 100];
assert_eq!(bcrypt(4, salt, &pw72), bcrypt(4, salt, &pw73));
assert_eq!(bcrypt(4, salt, &pw72), bcrypt(4, salt, &pw100));
let mut other = pw72;
other[71] = b'y';
assert_ne!(bcrypt(4, salt, &pw72), bcrypt(4, salt, &other));
}
#[test]
fn openbsd_vector_end_to_end() {
assert_eq!(verify(b"U*U", VECTOR_2A), Ok(true));
#[cfg(not(miri))]
{
assert_eq!(verify(b"U*U*", VECTOR_2A), Ok(false));
assert_eq!(verify(b"", VECTOR_2A), Ok(false));
}
let salt = crate::base64::decode_16(b"CCCCCCCCCCCCCCCCCCCCC.").expect("salt decodes");
let bytes = hash_with_salt_bytes(b"U*U", 5, salt).expect("valid cost");
assert_eq!(
core::str::from_utf8(&bytes).expect("ASCII"),
"$2b$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW"
);
}
#[cfg(not(miri))]
#[test]
fn round_trip_and_wrong_password() {
let salt = [7u8; 16];
let bytes = hash_with_salt_bytes(b"hunter2", 4, salt).expect("valid cost");
let s = core::str::from_utf8(&bytes).expect("ASCII");
assert!(s.starts_with("$2b$04$"));
assert_eq!(s.len(), 60);
assert_eq!(verify(b"hunter2", s), Ok(true));
assert_eq!(verify(b"hunter3", s), Ok(false));
assert_eq!(verify(b"", s), Ok(false));
}
#[cfg(not(miri))]
#[test]
fn all_version_markers_verify_the_same() {
let salt = [3u8; 16];
let parts = hash_with_salt(b"correct horse", 4, salt).expect("valid cost");
for version in [Version::TwoA, Version::TwoB, Version::TwoX, Version::TwoY] {
let bytes = parts.format_bytes(version);
let s = core::str::from_utf8(&bytes).expect("ASCII");
assert_eq!(verify(b"correct horse", s), Ok(true), "{version}");
}
assert_eq!(parts.get_cost(), 4);
assert_eq!(parts.get_salt_raw(), salt);
let raw = bcrypt(4, salt, b"correct horse");
assert_eq!(&parts.get_hash()[..], &raw[..23]);
}
#[test]
fn cost_arguments_are_validated() {
let salt = [0u8; 16];
assert!(check_cost(MIN_COST).is_ok());
assert!(check_cost(MAX_COST).is_ok());
for bad in [0, 3, 32, 100] {
assert_eq!(
hash_with_salt(b"pw", bad, salt),
Err(BcryptError::CostNotAllowed(bad))
);
assert_eq!(
hash_with_salt_bytes(b"pw", bad, salt),
Err(BcryptError::CostNotAllowed(bad))
);
assert_eq!(
non_truncating_hash_with_salt(b"pw", bad, salt),
Err(BcryptError::CostNotAllowed(bad))
);
}
assert_eq!(
verify(b"pw", "$2b$03$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW"),
Err(BcryptError::InvalidHash("cost"))
);
assert_eq!(
verify(b"pw", "$2b$32$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW"),
Err(BcryptError::InvalidHash("cost"))
);
}
#[test]
fn non_truncating_variants_reject_72_bytes_and_up() {
let salt = [5u8; 16];
#[cfg(not(miri))]
let pw71 = [b'a'; 71];
let pw72 = [b'a'; 72];
let pw100 = [b'a'; 100];
#[cfg(not(miri))]
assert!(non_truncating_hash_with_salt(pw71, 4, salt).is_ok());
assert_eq!(
non_truncating_hash_with_salt(pw72, 4, salt),
Err(BcryptError::Truncation(73))
);
assert_eq!(
non_truncating_hash_with_salt(pw100, 4, salt),
Err(BcryptError::Truncation(101))
);
assert_eq!(
non_truncating_hash_with_salt_bytes(pw72, 4, salt),
Err(BcryptError::Truncation(73))
);
assert_eq!(
non_truncating_verify(pw72, VECTOR_2A),
Err(BcryptError::Truncation(73))
);
assert_eq!(
non_truncating_verify(pw72, "not a hash"),
Err(BcryptError::Truncation(73))
);
#[cfg(not(miri))]
{
let a = hash_with_salt(pw71, 4, salt).expect("valid cost");
let b = non_truncating_hash_with_salt(pw71, 4, salt).expect("71 bytes pass");
assert_eq!(a, b);
}
}
#[test]
fn verify_rejects_malformed_hashes() {
assert_eq!(
verify(b"pw", "not a hash"),
Err(BcryptError::InvalidHash("length"))
);
}
#[test]
fn constant_time_eq_basics() {
let a = [0xABu8; 23];
let mut b = a;
assert!(constant_time_eq(&a, &b));
b[22] ^= 1;
assert!(!constant_time_eq(&a, &b));
b[22] ^= 1;
b[0] ^= 0x80;
assert!(!constant_time_eq(&a, &b));
}
#[cfg(feature = "alloc")]
#[test]
fn bcrypt_many_matches_bcrypt_for_sizes_0_to_17() {
let max = if cfg!(miri) { 2 } else { 17 };
for n in 0..=max {
let store: Vec<[u8; 8]> = (0..n)
.map(|i| {
let mut a = [0xA5u8; 8];
a[0] = i as u8;
a
})
.collect();
let pws: Vec<&[u8]> = store.iter().map(|a| &a[..]).collect();
let salts: Vec<[u8; 16]> = (0..n)
.map(|i| {
let mut s = [0u8; 16];
s[0] = i as u8;
s[15] = 0xFF - i as u8;
s
})
.collect();
let batch = bcrypt_many(4, &pws, &salts).expect("valid cost");
assert_eq!(batch.len(), n);
for (i, ((got, &salt), &pw)) in
batch.iter().zip(&salts).zip(&pws).enumerate()
{
assert_eq!(*got, bcrypt(4, salt, pw), "size {n} lane {i}");
}
}
}
#[cfg(feature = "alloc")]
#[test]
fn bcrypt_many_empty_and_mismatched_inputs() {
let empty_p: [&[u8]; 0] = [];
let empty_s: [[u8; 16]; 0] = [];
assert_eq!(bcrypt_many(4, &empty_p, &empty_s), Ok(Vec::new()));
assert_eq!(
bcrypt_many(3, &empty_p, &empty_s),
Err(BcryptError::CostNotAllowed(3))
);
let pws: [&[u8]; 2] = [b"a", b"b"];
let salts = [[0u8; 16]];
assert_eq!(
bcrypt_many(4, &pws, &salts),
Err(BcryptError::BatchLengthMismatch {
passwords: 2,
salts: 1
})
);
assert_eq!(
hash_many_with_salts(&pws, &salts, 4),
Err(BcryptError::BatchLengthMismatch {
passwords: 2,
salts: 1
})
);
}
#[cfg(all(feature = "alloc", not(miri)))]
#[test]
fn hash_many_with_salts_round_trip() {
let pws: [&[u8]; 3] = [b"alpha", b"bravo", b"charlie"];
let salts = [[1u8; 16], [2u8; 16], [3u8; 16]];
let parts = hash_many_with_salts(&pws, &salts, 4).expect("valid cost");
assert_eq!(parts.len(), 3);
for ((part, &salt), pw) in parts.iter().zip(&salts).zip(&pws) {
assert_eq!(part.get_cost(), 4);
assert_eq!(part.get_salt_raw(), salt);
let bytes = part.format_bytes(Version::TwoB);
let s = core::str::from_utf8(&bytes).expect("ASCII");
assert_eq!(verify(pw, s), Ok(true));
}
}
#[cfg(all(feature = "alloc", not(miri)))]
#[test]
fn verify_many_mixed_costs_with_failures() {
let parts4 = hash_with_salt(b"correct horse", 4, [1u8; 16]).expect("valid cost");
let parts5 = hash_with_salt(b"battery staple", 5, [2u8; 16]).expect("valid cost");
let h4 = parts4.format_bytes(Version::TwoB);
let h5 = parts5.format_bytes(Version::TwoA);
let h4 = core::str::from_utf8(&h4).expect("ASCII");
let h5 = core::str::from_utf8(&h5).expect("ASCII");
let pws: [&[u8]; 4] = [
b"correct horse",
b"battery staple",
b"wrong",
b"correct horse",
];
let hashes: [&str; 4] = [h4, h5, h5, "not a real hash"];
let results = verify_many(&pws, &hashes);
assert_eq!(results.len(), 4);
assert_eq!(results[0], Ok(true));
assert_eq!(results[1], Ok(true), "cost-5 group in the same call");
assert_eq!(results[2], Ok(false), "wrong password, right hash");
assert_eq!(
results[3],
Err(BcryptError::InvalidHash("length")),
"malformed hash stays a per-item error"
);
let results = verify_many(&pws[..1], &hashes[..2]);
assert_eq!(results.len(), 2);
assert_eq!(results[0], Ok(true));
assert_eq!(
results[1],
Err(BcryptError::BatchLengthMismatch {
passwords: 1,
salts: 2
})
);
assert!(verify_many(&[], &[]).is_empty());
}
#[cfg(all(feature = "std", not(miri)))]
#[test]
fn hash_family_with_random_salts() {
let h = hash(b"hunter2", 4).expect("hashing works");
assert_eq!(h.len(), 60);
assert!(h.starts_with("$2b$04$"));
assert_eq!(verify(b"hunter2", &h), Ok(true));
assert_eq!(verify(b"hunter3", &h), Ok(false));
let hb = hash_bytes(b"hunter2", 4).expect("hashing works");
assert_eq!(verify(b"hunter2", core::str::from_utf8(&hb).expect("ASCII")), Ok(true));
let parts = hash_with_result(b"hunter2", 4).expect("hashing works");
assert_eq!(parts.get_cost(), 4);
assert_ne!(hash(b"hunter2", 4).expect("hashing works"), h);
assert_eq!(hash(b"pw", 3), Err(BcryptError::CostNotAllowed(3)));
assert_eq!(hash_bytes(b"pw", 32), Err(BcryptError::CostNotAllowed(32)));
assert_eq!(
non_truncating_hash([b'a'; 72], 4),
Err(BcryptError::Truncation(73))
);
assert_eq!(
non_truncating_hash_bytes([b'a'; 72], 4),
Err(BcryptError::Truncation(73))
);
assert_eq!(
non_truncating_hash_with_result([b'a'; 72], 4),
Err(BcryptError::Truncation(73))
);
}
#[cfg(all(feature = "std", not(miri)))]
#[test]
fn hash_many_round_trip() {
let pws: [&[u8]; 3] = [b"alpha", b"bravo", b"charlie"];
let hashes = hash_many(&pws, 4).expect("hashing works");
assert_eq!(hashes.len(), 3);
for (pw, h) in pws.iter().zip(&hashes) {
assert!(h.starts_with("$2b$04$"));
assert_eq!(verify(pw, h), Ok(true));
}
assert_ne!(hashes[0], hashes[1]);
assert_eq!(hash_many(&pws, 3), Err(BcryptError::CostNotAllowed(3)));
let empty: [&[u8]; 0] = [];
assert_eq!(hash_many(&empty, 4), Ok(Vec::new()));
}
#[cfg(feature = "parallel")]
#[test]
fn parallel_workers_threshold() {
let cores = std::thread::available_parallelism().map_or(1, core::num::NonZero::get);
assert_eq!(parallel_workers(0), 1);
assert_eq!(parallel_workers(2 * cores - 1), 1);
assert_eq!(parallel_workers(2 * cores), cores);
assert_eq!(parallel_workers(1_000_000), cores);
}
#[cfg(all(feature = "alloc", feature = "parallel"))]
#[test]
fn parallel_batch_matches_single_hashes() {
let cores = std::thread::available_parallelism().map_or(1, core::num::NonZero::get);
let sizes = [0usize, 1, 2, 3, 7, 8, 16, 17, 33, 64];
for &n in sizes.iter().chain([2 * cores, 2 * cores + 1].iter()) {
let store: Vec<Vec<u8>> = (0..n)
.map(|i| alloc::vec![(i as u8).wrapping_mul(37); 4 + i % 29])
.collect();
let pws: Vec<&[u8]> = store.iter().map(Vec::as_slice).collect();
let salts: Vec<[u8; 16]> = (0..n)
.map(|i| {
let mut s = [0x5Au8; 16];
s[0] = i as u8;
s
})
.collect();
let batch = bcrypt_many(4, &pws, &salts).expect("valid cost");
assert_eq!(batch.len(), n);
for (i, ((got, &salt), &pw)) in batch.iter().zip(&salts).zip(&pws).enumerate() {
assert_eq!(*got, bcrypt(4, salt, pw), "size {n} lane {i}");
}
}
}
}