Skip to main content

Crate bcrypt_rust

Crate bcrypt_rust 

Source
Expand description

A pure-Rust implementation of bcrypt, the Blowfish-based password hash by Provos and Mazières (USENIX 1999), with runtime-dispatched SIMD backends for batch hashing.

bcrypt hashes a password with a per-password salt and a tunable cost (2^cost iterations of the EksBlowfish key-expansion loop) and is wire-compatible with every implementation that speaks the $2*$ hash-string format: $2v$cc$<22-char salt><31-char hash>, exactly 60 ASCII bytes.

§What SIMD does — and does not — do here

bcrypt’s cost loop is strictly sequential: one hash cannot be parallelized. The SIMD backends (chosen by runtime CPU detection, see detected_backend) therefore speed up batch throughput only, by interleaving N independent hashes in lockstep, one per vector lane. Single-hash latency is unchanged, and hash / verify always run the scalar kernel — they never see a Backend value at all.

The one other data-parallel step, the base64 codec, is vectorized as well: NEON on aarch64, an AVX2/SSSE3 runtime pick on x86-64, v128 under wasm simd128 — each byte-exact against the scalar tables it replaces.

Measured batch gains (benches/micro.rs — every timed iteration asserted byte-identical to scalar). Apple M5 Max (aarch64), cost 5:

backendlanesbatchhashes/svs scalar
scalar116790.41.00
NEON8163187.14.03×
wasm128 (under wasmtime 48, cost 4)882006.81.56×

AMD EPYC Zen 4 (x86_64, 4 vCPU), cost 5, batch 16: scalar 568.8 h/s, SSE4.1 1.11×, AVX2 1.58–1.67×, AVX-512 1.55–1.64× (parity on Zen 4; a one-time runtime width shootout picks per host — see the README). Batch-16 speedup vs the bcrypt crate: 4.32× (M5 Max) / 1.94× (Zen 4); full tables and the parallel numbers are in the README.

The batch entry points are bcrypt_many, hash_many, hash_many_with_salts and verify_many.

§Quick start

// Cost 4 keeps the doctest fast; use `DEFAULT_COST` (12) or higher —
// whatever your latency budget tolerates — in real code.
let hash = bcrypt_rust::hash(b"hunter2", 4)?;
assert_eq!(hash.len(), 60);
assert!(bcrypt_rust::verify(b"hunter2", &hash)?);
assert!(!bcrypt_rust::verify(b"hunter3", &hash)?);

§Batch hashing

let passwords: [&[u8]; 3] = [b"alpha", b"bravo", b"charlie"];
let hashes = bcrypt_rust::hash_many(&passwords, 4)?;
assert_eq!(hashes.len(), 3);
for (password, hash) in passwords.iter().zip(&hashes) {
    assert!(bcrypt_rust::verify(password, hash)?);
}

§Features

featuredefaultwhat it gates
std✓runtime CPU feature detection; OS-entropy salts for hash, hash_bytes, hash_with_result, hash_many
allocvia stdString/Vec APIs: bcrypt_many, hash_many_with_salts, verify_many, HashParts::get_salt, HashParts::format_for_version
zeroize✓securely wipe internal buffers that held key material (padded passwords, key words, lane scratch) so -O3 cannot elide the erasure
parallel—split batches of ≥ 2 × available cores across std::thread::scope workers; a throughput knob for large batches only — output is byte-identical and the sequential loop runs below the threshold
internal-api—exposes __internal for this crate’s own tests and benches; not stable

The crate is #![no_std] and stays that way with every feature enabled. With alloc but no std, everything works except the random-salt conveniences and runtime detection (backend selection falls back to compile-time target_feature cfgs, then scalar). With neither, the byte-oriented core — bcrypt, hash_with_salt, hash_with_salt_bytes, verify, HashParts parsing/formatting — is fully functional. With std, BCRYPT_FORCE_BACKEND=<name> pins detection to one backend — an escape hatch for simulators and interpreters that implement fewer instructions than the host CPU advertises (CodSpeed’s Valgrind instrument has no AVX-512).

§bcrypt-crate compatibility

The API mirrors the bcrypt crate (0.19): same names and semantics — NUL-then-truncate-at-72 key preparation, all four $2*$ prefixes accepted on parse, $2b$ emitted on format, HashParts with the same accessors, the same BcryptError variant set. Two deliberate departures, both additive or internal:

  • BcryptError::Rand carries this crate’s own EntropyError — OS entropy is hand-declared per platform, so the crate has zero dependencies.
  • Additions the bcrypt crate does not have: the batch API above and HashParts::get_hash (the raw 23-byte payload).

§Variant semantics

Every accepted prefix — $2a$, $2b$, $2x$, $2y$ — computes the same, correct algorithm; the version is a parse/format label, and formatting always emits $2b$ unless told otherwise. The historical bug emulations are deliberately not reproduced:

  • crypt_blowfish’s $2x$ sign-extension bug (CVE-2011-2481 era);
  • crypt_blowfish’s $2a$ 8-bit “safety” XOR;
  • OpenBSD $2a$’s len + 1 byte wraparound for >72-byte passwords.

See the design doc, §3 for the full rationale.

§Panics

No fallible public path panics: hashing, verifying, parsing and batch length validation all report failure as a BcryptError. verify_many returns per-item Results precisely so that one malformed string in a batch stays a value, not a panic. The one carve-out is opt-in: an unknown or unavailable BCRYPT_FORCE_BACKEND value panics on the first dispatched batch call, by design (see the eks module docs).

Re-exports§

pub use crate::error::BcryptError;
pub use crate::error::BcryptResult;
pub use crate::error::EntropyError;

Modules§

error
Error and result types for the crate.

Structs§

HashParts
A parsed bcrypt hash: cost, raw salt, and the 23-byte hash payload.

Enums§

Backend
Which bcrypt_lanes implementation to use.
Version
The version marker in a bcrypt hash string: the v in $2v$.

Constants§

DEFAULT_COST
The cost used when none is specified.
MAX_COST
Largest allowed cost: 2^31 expansion-loop iterations.
MIN_COST
Smallest allowed cost: 2^4 expansion-loop iterations.

Functions§

bcrypt
The raw bcrypt core: one hash of password with a caller-supplied salt, returning the full 24-byte ciphertext.
bcrypt_many
Batch-hash passwords at one cost with caller-supplied salts, returning the raw 24-byte ciphertexts in input order.
detected_backend
The Backend this CPU resolved to, cached after the first call.
hash
Hash a password with a fresh random salt, returning the 60-byte $2b$ hash string.
hash_bytes
Like hash, but returns the hash string as stack bytes.
hash_many
Batch-hash passwords at one cost with fresh random salts, returning the 60-byte $2b$ hash strings in input order.
hash_many_with_salts
bcrypt_many, but returns parsed HashParts instead of raw ciphertexts.
hash_with_result
Like hash, but returns the parsed parts rather than the string.
hash_with_salt
Hash a password with a caller-supplied salt — no OS entropy, no std, no alloc.
hash_with_salt_bytes
Like hash_with_salt, but returns the 60-byte hash string as stack bytes.
non_truncating_hash
hash, but rejects passwords of 72 bytes or more instead of silently truncating them.
non_truncating_hash_bytes
hash_bytes, but rejects passwords of 72 bytes or more.
non_truncating_hash_with_result
hash_with_result, but rejects passwords of 72 bytes or more.
non_truncating_hash_with_salt
hash_with_salt, but rejects passwords of 72 bytes or more.
non_truncating_hash_with_salt_bytes
hash_with_salt_bytes, but rejects passwords of 72 bytes or more.
non_truncating_verify
verify, but rejects passwords of 72 bytes or more.
verify
Verify password against a hash string, in constant time per candidate.
verify_many
Verify a batch of password/hash-string pairs, one BcryptResult per input position.