#![cfg(all(feature = "alloc", feature = "internal-api"))]
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::fs;
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::OnceLock;
use bcrypt_rust::__internal::{bcrypt_many_with_backend, decode_16, encode_16, encode_23};
use bcrypt_rust::{
Backend, HashParts, Version, bcrypt_many, detected_backend, hash_with_salt, verify,
};
const SEED: u64 = 0x_BC27_2015_D1FF_E001;
const HARNESS_C: &str = r#"/* GENERATED by tests/differential.rs - do not edit. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ow-crypt.h"
#define LINE_CAP 4096
#define OUT_SIZE (7 + 22 + 31 + 1)
static char line[LINE_CAP];
static int hexval(int c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
}
int main(void) {
while (fgets(line, (int)sizeof line, stdin) != NULL) {
char *cmd, *setting, *pwdhex, *spare;
char data[OUT_SIZE];
unsigned char pwd[256 + 1];
size_t n, i;
char *out;
if (strchr(line, '\n') == NULL && !feof(stdin)) {
printf("BAD line-too-long\n");
fflush(stdout);
return 1;
}
cmd = strtok(line, " \t\r\n");
if (cmd == NULL) continue; /* blank line */
setting = strtok(NULL, " \t\r\n");
pwdhex = strtok(NULL, " \t\r\n");
spare = strtok(NULL, " \t\r\n");
if (strcmp(cmd, "HASH") != 0 || setting == NULL || pwdhex == NULL ||
spare != NULL) {
printf("BAD request\n");
fflush(stdout);
return 1;
}
n = strlen(pwdhex);
if (n == 0 || n % 2 != 0 || n / 2 > 256) {
printf("BAD pwd-hex\n");
fflush(stdout);
return 1;
}
for (i = 0; i < n / 2; ++i) {
int hi = hexval((unsigned char)pwdhex[2 * i]);
int lo = hexval((unsigned char)pwdhex[2 * i + 1]);
if (hi < 0 || lo < 0) {
printf("BAD pwd-hex\n");
fflush(stdout);
return 1;
}
pwd[i] = (unsigned char)((hi << 4) | lo);
}
pwd[n / 2] = '\0'; /* crypt_rn takes a NUL-terminated C string */
out = crypt_rn((const char *)pwd, setting, data, (int)sizeof data);
if (out != NULL)
printf("OK %s\n", out);
else
printf("ERR null\n");
fflush(stdout);
}
return 0;
}
"#;
fn manifest_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
}
const C_SOURCES: [&str; 3] = ["crypt_blowfish.c", "crypt_gensalt.c", "wrapper.c"];
const C_HEADERS: [&str; 3] = ["crypt_blowfish.h", "crypt_gensalt.h", "ow-crypt.h"];
struct NoCompiler;
impl fmt::Display for NoCompiler {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("none of $CC/cc/gcc/clang answered `--version`")
}
}
fn harness() -> Option<&'static Path> {
static BUILT: OnceLock<Result<PathBuf, NoCompiler>> = OnceLock::new();
match BUILT.get_or_init(build_harness) {
Ok(path) => Some(path.as_path()),
Err(why) => {
assert!(
std::env::var_os("BCRYPT_REQUIRE_C_HARNESS").is_none(),
"differential: BCRYPT_REQUIRE_C_HARNESS is set but no usable C compiler: {why}"
);
eprintln!("differential: skipping, no usable C compiler: {why}");
None
}
}
}
fn find_compiler() -> Option<String> {
let candidates: Vec<String> = match std::env::var("CC") {
Ok(cc) => vec![cc],
Err(_) => ["cc", "gcc", "clang"].map(str::to_string).to_vec(),
};
candidates.into_iter().find(|cc| {
Command::new(cc)
.arg("--version")
.output()
.map(|o| o.status.success())
.unwrap_or(false)
})
}
fn run(what: &str, command: &mut Command) -> Result<(), String> {
let output = command
.output()
.map_err(|e| format!("{what}: failed to spawn: {e}"))?;
if output.status.success() {
return Ok(());
}
Err(format!(
"{what}: exited with {}\n--- stdout ---\n{}\n--- stderr ---\n{}",
output.status,
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
))
}
fn build_harness() -> Result<PathBuf, NoCompiler> {
let root = manifest_dir();
let c_dir = root.join("crypt_blowfish");
for file in C_SOURCES.iter().chain(C_HEADERS.iter()) {
assert!(
c_dir.join(file).is_file(),
"the vendored crypt_blowfish tree is missing {file} at {}",
c_dir.display()
);
}
let Some(cc) = find_compiler() else {
return Err(NoCompiler);
};
let build_dir = root.join("target").join("differential-harness");
fs::create_dir_all(&build_dir).unwrap_or_else(|e| panic!("mkdir {}: {e}", build_dir.display()));
let source = build_dir.join("harness.c");
let stale = fs::read_to_string(&source)
.map(|s| s != HARNESS_C)
.unwrap_or(true);
if stale {
fs::write(&source, HARNESS_C).unwrap_or_else(|e| panic!("write {}: {e}", source.display()));
}
let mut objects = Vec::new();
for c in C_SOURCES {
let src = c_dir.join(c);
let obj = build_dir.join(c.replace(".c", ".o"));
let headers: Vec<PathBuf> = C_HEADERS.iter().map(|h| c_dir.join(h)).collect();
let mut inputs: Vec<&Path> = vec![src.as_path()];
inputs.extend(headers.iter().map(PathBuf::as_path));
if needs_rebuild(&obj, &inputs) {
run(
&format!("{cc} -c {c}"),
Command::new(&cc)
.arg("-O2")
.arg("-Wall")
.arg("-c")
.arg(&src)
.arg("-o")
.arg(&obj),
)
.unwrap_or_else(|e| panic!("{e}"));
}
objects.push(obj);
}
let exe = build_dir.join(format!("harness{}", std::env::consts::EXE_SUFFIX));
let mut inputs: Vec<&Path> = vec![source.as_path()];
inputs.extend(objects.iter().map(PathBuf::as_path));
if !needs_rebuild(&exe, &inputs) {
return Ok(exe);
}
let mut link = Command::new(&cc);
link.arg("-O2")
.arg("-Wall")
.arg("-I")
.arg(&c_dir)
.arg(&source);
for obj in &objects {
link.arg(obj);
}
link.arg("-o").arg(&exe);
run(&format!("{cc} harness.c *.o"), &mut link).unwrap_or_else(|e| panic!("{e}"));
Ok(exe)
}
fn needs_rebuild(target: &Path, inputs: &[&Path]) -> bool {
let Ok(target_time) = fs::metadata(target).and_then(|m| m.modified()) else {
return true;
};
inputs.iter().any(|input| {
fs::metadata(input)
.and_then(|m| m.modified())
.map(|t| t > target_time)
.unwrap_or(true)
})
}
#[derive(Clone, PartialEq, Eq)]
enum CaseKind {
Hash {
version: Version,
cost: u32,
salt: [u8; 16],
},
Reject { rust_input: String },
}
#[derive(Clone, PartialEq, Eq)]
struct Case {
setting: String,
pwd: Vec<u8>,
kind: CaseKind,
}
impl fmt::Debug for Case {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"setting {:?} pwd[{}] {}",
self.setting,
self.pwd.len(),
hex(&self.pwd)
)
}
}
fn hex(bytes: &[u8]) -> String {
let mut s = String::with_capacity(bytes.len() * 2);
for b in bytes {
s.push_str(&format!("{b:02x}"));
}
s
}
fn canonical_setting(version: Version, cost: u32, salt: &[u8; 16]) -> String {
let salt_b64 = encode_16(salt);
format!(
"${version}${cost:02}${}",
std::str::from_utf8(&salt_b64).expect("bcrypt base64 is ASCII")
)
}
impl Case {
fn hash(version: Version, cost: u32, salt: [u8; 16], pwd: Vec<u8>) -> Case {
Case {
setting: canonical_setting(version, cost, &salt),
pwd,
kind: CaseKind::Hash {
version,
cost,
salt,
},
}
}
fn reject(setting: &str, rust_input: &str, pwd: Vec<u8>) -> Case {
Case {
setting: setting.to_string(),
pwd,
kind: CaseKind::Reject {
rust_input: rust_input.to_string(),
},
}
}
fn request(&self) -> String {
format!("HASH {} {}\n", self.setting, hex(&self.pwd))
}
fn key(&self) -> String {
self.request()
}
fn expected(&self, out: &[u8; 24]) -> String {
let CaseKind::Hash {
version,
cost,
salt,
} = &self.kind
else {
unreachable!("expected() is only called on hashing cases")
};
let mut payload = [0u8; 23];
payload.copy_from_slice(&out[..23]);
let salt_b64 = encode_16(salt);
let hash_b64 = encode_23(&payload);
format!(
"${version}${cost:02}${}{}",
std::str::from_utf8(&salt_b64).expect("bcrypt base64 is ASCII"),
std::str::from_utf8(&hash_b64).expect("bcrypt base64 is ASCII"),
)
}
}
fn tampered(c_hash: &str) -> String {
let bytes = c_hash.as_bytes();
assert_eq!(bytes.len(), 60, "tampered() expects a full hash string");
let pos = 29 + bytes.iter().map(|&b| usize::from(b)).sum::<usize>() % 30;
let mut out = bytes.to_vec();
out[pos] = if out[pos] == b'A' { b'B' } else { b'A' };
String::from_utf8(out).expect("the tamper writes ASCII")
}
#[derive(Copy, Clone, PartialEq, Eq)]
enum Driver {
PublicApi,
PublicBatch,
Forced(Backend),
}
impl fmt::Debug for Driver {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Driver::PublicApi => write!(f, "public-api"),
Driver::PublicBatch => write!(f, "public-batch[{}]", detected_backend()),
Driver::Forced(backend) => write!(f, "forced[{backend}]"),
}
}
}
fn drivers() -> Vec<Driver> {
let mut drivers = vec![Driver::PublicApi, Driver::PublicBatch];
drivers.extend(
Backend::ALL
.iter()
.copied()
.filter(|b| b.is_available())
.map(Driver::Forced),
);
drivers
}
#[derive(Debug, PartialEq, Eq)]
enum CResult {
Hashed(String),
Rejected,
}
fn run_c(cases: &[Case]) -> Vec<CResult> {
let exe = harness().expect("run_c called without a harness");
let mut child = Command::new(exe)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
.unwrap_or_else(|e| panic!("cannot spawn {}: {e}", exe.display()));
let mut stdin = child.stdin.take().expect("piped stdin");
let requests: Vec<String> = cases.iter().map(Case::request).collect();
let writer = std::thread::spawn(move || -> std::io::Result<()> {
for request in &requests {
stdin.write_all(request.as_bytes())?;
}
stdin.flush()
});
let stdout = child.stdout.take().expect("piped stdout");
let mut results = Vec::with_capacity(cases.len());
for (index, line) in BufReader::new(stdout).lines().enumerate() {
let line = line.unwrap_or_else(|e| panic!("reading harness stdout: {e}"));
let case = cases.get(index);
results.push(parse_response(&line, case));
}
writer
.join()
.unwrap_or_else(|_| panic!("the harness stdin writer thread panicked"))
.unwrap_or_else(|e| panic!("writing to the harness: {e}"));
let status = child.wait().expect("waiting for the harness");
assert!(status.success(), "the C harness exited with {status}");
assert_eq!(
results.len(),
cases.len(),
"the C harness answered {} of {} cases",
results.len(),
cases.len()
);
results
}
fn parse_response(line: &str, case: Option<&Case>) -> CResult {
if let Some(hash) = line.strip_prefix("OK ") {
assert_eq!(
hash.len(),
60,
"the harness returned a malformed hash {hash:?} for {case:?}"
);
CResult::Hashed(hash.to_string())
} else if line == "ERR null" {
CResult::Rejected
} else {
panic!("unexpected harness output {line:?} for {case:?}");
}
}
fn assert_batch_agrees(label: &str, cases: &[Case]) -> (usize, usize) {
let c_results = run_c(cases);
compare(label, cases, &c_results)
}
fn compare(label: &str, cases: &[Case], c_results: &[CResult]) -> (usize, usize) {
let mut agreed: Option<(Driver, (usize, usize))> = None;
for driver in drivers() {
let counts = compare_with(label, driver, cases, c_results);
match agreed {
None => agreed = Some((driver, counts)),
Some((first, expected)) => assert_eq!(
counts, expected,
"{label}: {driver:?} split the batch {counts:?} but {first:?} split it {expected:?}"
),
}
}
agreed.expect("drivers() always contains the public API").1
}
fn single_answer(case: &Case) -> String {
let CaseKind::Hash {
version,
cost,
salt,
} = &case.kind
else {
unreachable!("single_answer is only called on hashing cases")
};
hash_with_salt(&case.pwd, *cost, *salt)
.unwrap_or_else(|e| panic!("hash_with_salt failed for {case:?}: {e:?}"))
.format_for_version(*version)
}
fn batch_answers(driver: Driver, cases: &[Case]) -> Vec<Option<String>> {
let mut answers = vec![None; cases.len()];
if driver == Driver::PublicApi {
return answers;
}
let mut by_cost: BTreeMap<u32, Vec<usize>> = BTreeMap::new();
for (index, case) in cases.iter().enumerate() {
if let CaseKind::Hash { cost, .. } = &case.kind {
by_cost.entry(*cost).or_default().push(index);
}
}
for (cost, idxs) in by_cost {
let passwords: Vec<&[u8]> = idxs.iter().map(|&i| cases[i].pwd.as_slice()).collect();
let salts: Vec<[u8; 16]> = idxs
.iter()
.map(|&i| match cases[i].kind {
CaseKind::Hash { salt, .. } => salt,
CaseKind::Reject { .. } => unreachable!("grouped on the Hash kind"),
})
.collect();
let outs = match driver {
Driver::PublicBatch => bcrypt_many(cost, &passwords, &salts),
Driver::Forced(backend) => {
unsafe { bcrypt_many_with_backend(backend, cost, &passwords, &salts) }
}
Driver::PublicApi => unreachable!("returned early above"),
}
.unwrap_or_else(|e| panic!("batch driver {driver:?} failed at cost {cost}: {e:?}"));
assert_eq!(
outs.len(),
idxs.len(),
"batch outputs are position-preserving"
);
for (j, &i) in idxs.iter().enumerate() {
answers[i] = Some(cases[i].expected(&outs[j]));
}
}
answers
}
fn compare_with(
label: &str,
driver: Driver,
cases: &[Case],
c_results: &[CResult],
) -> (usize, usize) {
assert!(!cases.is_empty(), "{label}: empty batch");
assert_eq!(cases.len(), c_results.len());
let unique: BTreeSet<String> = cases.iter().map(Case::key).collect();
let answers = batch_answers(driver, cases);
let mut hashed = 0usize;
let mut rejected = 0usize;
for (index, (case, c)) in cases.iter().zip(c_results).enumerate() {
match (&case.kind, c) {
(CaseKind::Hash { .. }, CResult::Hashed(c_hash)) => {
hashed += 1;
let rust = match driver {
Driver::PublicApi => single_answer(case),
_ => answers[index]
.clone()
.expect("batch answers cover every hashing case"),
};
if *c_hash != rust {
let first = c_hash
.bytes()
.zip(rust.bytes())
.position(|(a, b)| a != b)
.unwrap_or(0);
panic!(
"\n{label}[{index}] {driver:?}: HASH MISMATCH (seed {SEED:#018x})\n\
\x20 case: {case:?}\n\
\x20 C: {c_hash}\n\
\x20 Rust: {rust}\n\
\x20 first differing char: index {first} \
(C {:?} vs Rust {:?})\n\n\
This is a real bug in the port. Fix it; do not weaken this test.\n",
c_hash.as_bytes()[first] as char,
rust.as_bytes()[first] as char,
);
}
if driver == Driver::PublicApi {
assert_eq!(
verify(&case.pwd, c_hash),
Ok(true),
"{label}[{index}]: the C's own hash must verify (seed {SEED:#018x})\n\
\x20 case: {case:?}\n\x20 C: {c_hash}"
);
let bad = tampered(c_hash);
assert_eq!(
verify(&case.pwd, &bad),
Ok(false),
"{label}[{index}]: a tampered hash must not verify (seed {SEED:#018x})\n\
\x20 case: {case:?}\n\x20 C: {c_hash}\n\x20 tampered: {bad}"
);
}
}
(CaseKind::Reject { rust_input }, CResult::Rejected) => {
rejected += 1;
let accepted = match driver {
Driver::PublicApi => verify(&case.pwd, rust_input).is_ok(),
_ => rust_input.parse::<HashParts>().is_ok(),
};
assert!(
!accepted,
"\n{label}[{index}] {driver:?}: Rust accepted what the C rejected \
(seed {SEED:#018x})\n\x20 case: {case:?}\n\x20 rust input: {rust_input:?}"
);
}
(CaseKind::Hash { .. }, CResult::Rejected) => panic!(
"\n{label}[{index}] {driver:?}: the C rejected a well-formed case \
(seed {SEED:#018x})\n\x20 case: {case:?}"
),
(CaseKind::Reject { rust_input }, CResult::Hashed(c_hash)) => panic!(
"\n{label}[{index}] {driver:?}: the C hashed what Rust must reject \
(seed {SEED:#018x})\n\x20 case: {case:?}\n\x20 rust input: {rust_input:?}\n\
\x20 C: {c_hash}"
),
}
}
println!(
"{label} {driver:?}: {} cases ({} distinct) -> {hashed} hashed identically, \
{rejected} rejected in agreement",
cases.len(),
unique.len(),
);
(hashed, rejected)
}
struct Rng(u64);
impl Rng {
fn new(seed: u64) -> Rng {
Rng(seed)
}
fn next_u64(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
fn below(&mut self, n: usize) -> usize {
assert!(n > 0);
(self.next_u64() % n as u64) as usize
}
fn pick<T: Copy>(&mut self, choices: &[T]) -> T {
choices[self.below(choices.len())]
}
fn password(&mut self, len: usize) -> Vec<u8> {
(0..len)
.map(|_| match self.next_u64() as u8 {
0x00 => 0x01,
b => b,
})
.collect()
}
fn salt(&mut self) -> [u8; 16] {
let mut salt = [0u8; 16];
let (a, b) = salt.split_at_mut(8);
a.copy_from_slice(&self.next_u64().to_le_bytes());
b.copy_from_slice(&self.next_u64().to_le_bytes());
salt
}
}
const PWD_LENS: [usize; 10] = [1, 5, 16, 55, 56, 71, 72, 73, 100, 255];
const PREFIXES: [Version; 2] = [Version::TwoB, Version::TwoY];
#[test]
fn the_c_harness_is_really_running_bcrypt() {
let Some(_) = harness() else { return };
let salt = decode_16(b"CCCCCCCCCCCCCCCCCCCCC.").expect("vector salt decodes");
let cases = [
Case::hash(Version::TwoA, 5, salt, b"U*U".to_vec()),
Case::hash(Version::TwoB, 5, salt, b"U*U".to_vec()),
Case::reject(
"$2c$05$CCCCCCCCCCCCCCCCCCCCC.",
"$2c$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW",
b"U*U".to_vec(),
),
];
let results = run_c(&cases);
assert_eq!(
results[0],
CResult::Hashed("$2a$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW".to_string()),
"the harness did not reproduce OpenBSD vector #21 under $2a$"
);
assert_eq!(
results[1],
CResult::Hashed("$2b$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW".to_string()),
"the harness did not reproduce OpenBSD vector #21 under $2b$"
);
assert_eq!(results[2], CResult::Rejected, "$2c$ must be rejected");
assert_batch_agrees("harness-sanity", &cases);
}
#[test]
fn length_boundary_grid() {
let Some(_) = harness() else { return };
let mut rng = Rng::new(SEED ^ 0x01);
let mut cases = Vec::new();
for &len in &PWD_LENS {
for version in PREFIXES {
for cost in 4..=6u32 {
cases.push(Case::hash(version, cost, rng.salt(), rng.password(len)));
}
}
}
let (hashed, rejected) = assert_batch_agrees("length-boundary", &cases);
assert_eq!(rejected, 0, "every case here is deliberately well-formed");
assert_eq!(hashed, cases.len());
}
#[test]
fn randomised_sweep() {
let Some(_) = harness() else { return };
let mut rng = Rng::new(SEED ^ 0x02);
let mut cases = Vec::with_capacity(256);
for _ in 0..256 {
let version = rng.pick(&PREFIXES);
let cost = rng.pick(&[4, 4, 4, 5, 5, 6]);
let len = if rng.below(2) == 0 {
rng.pick(&PWD_LENS)
} else {
1 + rng.below(255)
};
cases.push(Case::hash(version, cost, rng.salt(), rng.password(len)));
}
let (hashed, rejected) = assert_batch_agrees("randomised", &cases);
assert_eq!(rejected, 0, "every case here is deliberately well-formed");
assert_eq!(hashed, cases.len());
}
#[test]
fn expensive_costs() {
let Some(_) = harness() else { return };
let mut rng = Rng::new(SEED ^ 0x03);
let lens = [1usize, 72, 73, 255];
let mut cases = Vec::new();
for i in 0..8 {
let version = PREFIXES[i % 2];
cases.push(Case::hash(
version,
7,
rng.salt(),
rng.password(lens[i % 4]),
));
}
for i in 0..4 {
let version = PREFIXES[i % 2];
cases.push(Case::hash(
version,
8,
rng.salt(),
rng.password(lens[(i + 1) % 4]),
));
}
let (hashed, rejected) = assert_batch_agrees("expensive", &cases);
assert_eq!(rejected, 0, "every case here is deliberately well-formed");
assert_eq!(hashed, cases.len());
}
#[test]
fn error_parity_malformed_settings() {
let Some(_) = harness() else { return };
let mut rng = Rng::new(SEED ^ 0x04);
const TAIL: &str = "E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW";
let pwd = rng.password(17);
let settings = [
"$2b$03$CCCCCCCCCCCCCCCCCCCCC.",
"$2b$32$CCCCCCCCCCCCCCCCCCCCC.",
"$2b$33$CCCCCCCCCCCCCCCCCCCCC.",
"$2b$0a$CCCCCCCCCCCCCCCCCCCCC.", "$2b$05$CCCCCCCCCCCCCCCCCCCCC", "$2b$05$CCCCCCCCCCCCCCCCCCCC!",
"$2b$05$!CCCCCCCCCCCCCCCCCCCCC",
"$2c$05$CCCCCCCCCCCCCCCCCCCCC.",
"$2z$05$CCCCCCCCCCCCCCCCCCCCC.",
"$2A$05$CCCCCCCCCCCCCCCCCCCCC.",
"$1$05$CCCCCCCCCCCCCCCCCCCCC.",
"$2b$05XCCCCCCCCCCCCCCCCCCCCC.",
"*0",
];
let mut cases: Vec<Case> = settings
.iter()
.map(|&setting| {
Case::reject(setting, &format!("{setting}{TAIL}"), pwd.clone())
})
.collect();
cases.push(Case::hash(Version::TwoB, 4, rng.salt(), rng.password(9)));
cases.push(Case::hash(Version::TwoY, 4, rng.salt(), rng.password(72)));
let (hashed, rejected) = assert_batch_agrees("error-parity", &cases);
assert!(
rejected >= 12,
"only {rejected} of {} cases were rejected in agreement",
cases.len()
);
assert!(
hashed >= 2,
"only {hashed} boundary cases hashed; the valid side is untested"
);
}
const ALPHABET: &[u8; 64] = b"./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
#[test]
fn salt_spelling_canonicalises_identically() {
let Some(_) = harness() else { return };
let mut rng = Rng::new(SEED ^ 0x05);
let mut cases = Vec::new();
for i in 0..12 {
let version = PREFIXES[i % 2];
let cost = [4u32, 5][i % 2];
let salt = rng.salt();
let len = rng.pick(&[1usize, 16, 72]);
let pwd = rng.password(len);
let mut case = Case::hash(version, cost, salt, pwd);
let mut setting = case.setting.clone().into_bytes();
let canonical = setting[28];
let index = ALPHABET
.iter()
.position(|&c| c == canonical)
.expect("the crate's encoder emits alphabet chars");
setting[28] = ALPHABET[(index & 0x30) + ((index + 1 + rng.below(15)) & 0x0f)];
case.setting = String::from_utf8(setting).expect("alphabet chars are ASCII");
assert_eq!(decode_16(&case.setting.as_bytes()[7..29]), Ok(salt));
cases.push(case);
}
let (hashed, rejected) = assert_batch_agrees("salt-spelling", &cases);
assert_eq!(rejected, 0, "every case here is well-formed once decoded");
assert_eq!(hashed, cases.len());
}
#[test]
fn the_comparison_catches_a_wrong_answer() {
let Some(_) = harness() else { return };
let valid = Case::hash(Version::TwoB, 4, [0x42; 16], b"differential".to_vec());
let invalid = Case::reject(
"$2b$03$CCCCCCCCCCCCCCCCCCCCC.",
"$2b$03$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW",
b"differential".to_vec(),
);
let truth = run_c(&[valid.clone(), invalid.clone()]);
let CResult::Hashed(good) = &truth[0] else {
panic!("the valid case must hash on the C side, got {:?}", truth[0]);
};
assert_eq!(truth[1], CResult::Rejected);
assert_eq!(
compare(
"control-baseline",
&[valid.clone(), invalid.clone()],
&truth
),
(1, 1)
);
let expect_failure = |what: &str, cases: Vec<Case>, results: Vec<CResult>, needle: &str| {
let payload = std::panic::catch_unwind(move || {
compare("negative-control", &cases, &results);
})
.err()
.unwrap_or_else(|| panic!("{what}: a corrupted C answer was accepted"));
let message = payload
.downcast_ref::<String>()
.map(String::as_str)
.or_else(|| payload.downcast_ref::<&str>().copied())
.unwrap_or("")
.to_string();
assert!(
message.contains(needle),
"{what}: the failure message should mention {needle:?}, got:\n{message}"
);
};
expect_failure(
"flipped hash char",
vec![valid.clone()],
vec![CResult::Hashed(tampered(good))],
"HASH MISMATCH",
);
expect_failure(
"C rejected, Rust hashed",
vec![valid.clone()],
vec![CResult::Rejected],
"the C rejected a well-formed case",
);
expect_failure(
"C hashed, Rust rejected",
vec![invalid.clone()],
vec![CResult::Hashed(good.clone())],
"the C hashed what Rust must reject",
);
}