bcrypt_rust/lib.rs
1//! A pure-Rust implementation of [bcrypt](https://www.usenix.org/legacy/events/usenix99/provos/provos.pdf),
2//! the Blowfish-based password hash by Provos and Mazières (USENIX 1999),
3//! with runtime-dispatched SIMD backends for **batch** hashing.
4//!
5//! bcrypt hashes a password with a per-password salt and a tunable cost
6//! (`2^cost` iterations of the EksBlowfish key-expansion loop) and is
7//! wire-compatible with every implementation that speaks the `$2*$`
8//! hash-string format: `$2v$cc$<22-char salt><31-char hash>`, exactly 60
9//! ASCII bytes.
10//!
11//! # What SIMD does — and does not — do here
12//!
13//! bcrypt's cost loop is strictly sequential: **one hash cannot be
14//! parallelized**. The SIMD backends (chosen by runtime CPU detection, see
15//! [`detected_backend`]) therefore speed up **batch throughput only**, by
16//! interleaving N *independent* hashes in lockstep, one per vector lane.
17//! Single-hash latency is unchanged, and [`hash`] / [`verify`] always run
18//! the scalar kernel — they never see a [`Backend`] value at all.
19//!
20//! The one other data-parallel step, the base64 codec, is vectorized as
21//! well: NEON on aarch64, an AVX2/SSSE3 runtime pick on x86-64, v128 under
22//! wasm simd128 — each byte-exact against the scalar tables it replaces.
23//!
24//! Measured batch gains (`benches/micro.rs` — every timed iteration
25//! asserted byte-identical to scalar). Apple M5 Max (aarch64), cost 5:
26//!
27//! | backend | lanes | batch | hashes/s | vs scalar |
28//! |---|---|---|---|---|
29//! | scalar | 1 | 16 | 790.4 | 1.00 |
30//! | NEON | 8 | 16 | 3187.1 | 4.03× |
31//! | wasm128 (under wasmtime 48, cost 4) | 8 | 8 | 2006.8 | 1.56× |
32//!
33//! AMD EPYC Zen 4 (x86_64, 4 vCPU), cost 5, batch 16: scalar 568.8 h/s,
34//! SSE4.1 1.11×, AVX2 1.58–1.67×, AVX-512 1.55–1.64× (parity on Zen 4; a
35//! one-time runtime width shootout picks per host — see the README).
36//! Batch-16 speedup vs the `bcrypt` crate: 4.32× (M5 Max) / 1.94× (Zen 4);
37//! full tables and the `parallel` numbers are in the README.
38//!
39//! The batch entry points are [`bcrypt_many`], [`hash_many`],
40//! [`hash_many_with_salts`] and [`verify_many`].
41//!
42//! # Quick start
43//!
44//! ```
45//! # #[cfg(feature = "std")]
46//! # fn run() -> Result<(), bcrypt_rust::BcryptError> {
47//! // Cost 4 keeps the doctest fast; use `DEFAULT_COST` (12) or higher —
48//! // whatever your latency budget tolerates — in real code.
49//! let hash = bcrypt_rust::hash(b"hunter2", 4)?;
50//! assert_eq!(hash.len(), 60);
51//! assert!(bcrypt_rust::verify(b"hunter2", &hash)?);
52//! assert!(!bcrypt_rust::verify(b"hunter3", &hash)?);
53//! # Ok(())
54//! # }
55//! # #[cfg(not(feature = "std"))]
56//! # fn run() -> Result<(), bcrypt_rust::BcryptError> { Ok(()) }
57//! # run().unwrap();
58//! ```
59//!
60//! # Batch hashing
61//!
62//! ```
63//! # #[cfg(feature = "std")]
64//! # fn run() -> Result<(), bcrypt_rust::BcryptError> {
65//! let passwords: [&[u8]; 3] = [b"alpha", b"bravo", b"charlie"];
66//! let hashes = bcrypt_rust::hash_many(&passwords, 4)?;
67//! assert_eq!(hashes.len(), 3);
68//! for (password, hash) in passwords.iter().zip(&hashes) {
69//! assert!(bcrypt_rust::verify(password, hash)?);
70//! }
71//! # Ok(())
72//! # }
73//! # #[cfg(not(feature = "std"))]
74//! # fn run() -> Result<(), bcrypt_rust::BcryptError> { Ok(()) }
75//! # run().unwrap();
76//! ```
77//!
78//! # Features
79//!
80//! | feature | default | what it gates |
81//! |---|---|---|
82//! | `std` | ✓ | runtime CPU feature detection; OS-entropy salts for [`hash`], [`hash_bytes`], [`hash_with_result`], [`hash_many`] |
83//! | `alloc` | via `std` | `String`/`Vec` APIs: [`bcrypt_many`], [`hash_many_with_salts`], [`verify_many`], [`HashParts::get_salt`], [`HashParts::format_for_version`] |
84//! | `zeroize` | ✓ | securely wipe internal buffers that held key material (padded passwords, key words, lane scratch) so `-O3` cannot elide the erasure |
85//! | `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 |
86//! | `internal-api` | — | exposes `__internal` for this crate's own tests and benches; not stable |
87//!
88//! The crate is `#![no_std]` and stays that way with every feature enabled.
89//! With `alloc` but no `std`, everything works except the random-salt
90//! conveniences and runtime detection (backend selection falls back to
91//! compile-time `target_feature` cfgs, then scalar). With neither, the
92//! byte-oriented core — [`bcrypt`], [`hash_with_salt`],
93//! [`hash_with_salt_bytes`], [`verify`], [`HashParts`] parsing/formatting —
94//! is fully functional. With `std`, `BCRYPT_FORCE_BACKEND=<name>` pins
95//! detection to one backend — an escape hatch for simulators and
96//! interpreters that implement fewer instructions than the host CPU
97//! advertises (CodSpeed's Valgrind instrument has no AVX-512).
98//!
99//! # `bcrypt`-crate compatibility
100//!
101//! The API mirrors the [`bcrypt` crate](https://crates.io/crates/bcrypt)
102//! (0.19): same names and semantics — NUL-then-truncate-at-72 key
103//! preparation, all four `$2*$` prefixes accepted on parse, `$2b$` emitted on
104//! format, [`HashParts`] with the same accessors, the same [`BcryptError`]
105//! variant set. Two deliberate departures, both additive or internal:
106//!
107//! * [`BcryptError::Rand`] carries this crate's own [`EntropyError`] — OS
108//! entropy is hand-declared per platform, so the crate has **zero
109//! dependencies**.
110//! * Additions the `bcrypt` crate does not have: the batch API above and
111//! [`HashParts::get_hash`] (the raw 23-byte payload).
112//!
113//! # Variant semantics
114//!
115//! Every accepted prefix — `$2a$`, `$2b$`, `$2x$`, `$2y$` — computes the
116//! same, correct algorithm; the version is a parse/format label, and
117//! formatting always emits `$2b$` unless told otherwise. The historical bug
118//! emulations are deliberately **not** reproduced:
119//!
120//! * crypt_blowfish's `$2x$` sign-extension bug (CVE-2011-2481 era);
121//! * crypt_blowfish's `$2a$` 8-bit "safety" XOR;
122//! * OpenBSD `$2a$`'s `len + 1` byte wraparound for >72-byte passwords.
123//!
124//! See [the design doc, §3](https://github.com/Brooooooklyn/bcrypt-rust/blob/main/docs/superpowers/specs/2026-10-01-bcrypt-rust-design.md#3-variant-semantics-deliberate-documented)
125//! for the full rationale.
126//!
127//! # Panics
128//!
129//! No fallible public path panics: hashing, verifying, parsing and batch
130//! length validation all report failure as a [`BcryptError`].
131//! [`verify_many`] returns per-item `Result`s precisely so that one
132//! malformed string in a batch stays a value, not a panic. The one carve-out
133//! is opt-in: an unknown or unavailable `BCRYPT_FORCE_BACKEND` value panics
134//! on the first dispatched batch call, by design (see the `eks` module
135//! docs).
136
137#![no_std]
138#![warn(missing_docs)]
139// A `pub` item that a downstream crate cannot *name* is only half-public: it
140// works in `let` bindings and nowhere else — not in a struct field, a
141// function signature, or a `Vec`. `HashParts` (returned by
142// `hash_with_result`) and `Backend` (returned by `detected_backend`) are
143// exactly the items a caller needs to store; this lint is the regression
144// guard.
145#![warn(unnameable_types)]
146#![warn(clippy::undocumented_unsafe_blocks)]
147// `__internal` re-exports `eks::scalar` (a module) so tests can drive the
148// scalar kernel directly. Its module doc links to private helpers
149// (`expand_state`), which rustdoc flags once the module is publicly
150// reachable; the link is correct under `--document-private-items` and the
151// module is off-limits to edit, so allow it here rather than churn the docs.
152#![allow(rustdoc::private_intra_doc_links)]
153// clippy suggests `as_chunks`/`as_chunks_mut` (stable since 1.88, so usable at
154// the pinned MSRV 1.89 — this lint fires on stable clippy). Rewriting the
155// verified base64 codec for it is style-only churn, so the lint is allowed
156// crate-wide instead.
157#![allow(clippy::chunks_exact_to_as_chunks)]
158
159// NOTE FOR EVERY CONTRIBUTOR: this crate has a module named `core`, which
160// shadows the `core` crate *in this root module only*. Inside `src/lib.rs`
161// always write `::core::...`. Submodules are unaffected — bare `core::` there
162// still means the `core` crate.
163
164extern crate alloc;
165
166#[cfg(feature = "std")]
167extern crate std;
168
169pub mod error;
170
171// These modules are private, and a good deal of what they expose escapes the
172// crate only through `__internal` (below), which tests and benches enable. In
173// a plain build those items are legitimately unreachable, so `dead_code`
174// would fire on all of them.
175//
176// Rather than blanket-allowing `dead_code` — which would also hide code that
177// is dead by mistake — the allow is tied to `internal-api` being OFF. With
178// the feature ON, `__internal` re-exports the intended surface, so anything
179// the compiler still calls dead really is dead and gets reported.
180macro_rules! private_modules {
181 ($($name:ident),* $(,)?) => {
182 $(
183 #[cfg_attr(not(feature = "internal-api"), allow(dead_code))]
184 mod $name;
185 )*
186 };
187}
188
189private_modules!(base64, consts, core, encoding, eks, wipe);
190
191// OS entropy for the convenience salt API; needs std for the syscall and the
192// /dev/urandom fallback. Declared per-platform inside the module.
193//
194// Deliberately not in `private_modules!`: everything here is reachable from
195// the random-salt entry points (`hash`, `hash_many`, …) on every `std`
196// build, so it needs no `dead_code` allow, and should not have one hiding a
197// future mistake.
198#[cfg(feature = "std")]
199mod random;
200
201pub use crate::core::{
202 DEFAULT_COST, MAX_COST, MIN_COST, bcrypt, hash_with_salt, hash_with_salt_bytes,
203 non_truncating_hash_with_salt, non_truncating_hash_with_salt_bytes, non_truncating_verify,
204 verify,
205};
206#[cfg(feature = "alloc")]
207pub use crate::core::{bcrypt_many, hash_many_with_salts, verify_many};
208#[cfg(feature = "std")]
209pub use crate::core::{
210 hash, hash_bytes, hash_many, hash_with_result, non_truncating_hash, non_truncating_hash_bytes,
211 non_truncating_hash_with_result,
212};
213pub use crate::eks::Backend;
214pub use crate::encoding::{HashParts, Version};
215pub use crate::error::{BcryptError, BcryptResult, EntropyError};
216
217/// The [`Backend`] this CPU resolved to, cached after the first call.
218///
219/// Diagnostic only — the hashing entry points resolve it for you. Remember
220/// it only speaks for *batch* throughput: [`hash`] and [`verify`] always run
221/// scalar (see the crate-level "What SIMD does — and does not — do here").
222///
223/// ```
224/// println!("bcrypt backend: {}", bcrypt_rust::detected_backend());
225/// ```
226#[inline]
227#[must_use]
228pub fn detected_backend() -> Backend {
229 crate::eks::backend()
230}
231
232#[cfg(feature = "internal-api")]
233#[doc(hidden)]
234pub mod __internal {
235 //! Unstable internals, exposed for this crate's own tests and benches.
236 //!
237 //! Gated behind the non-default `internal-api` feature. **No stability
238 //! guarantees**: anything here can change in a patch release.
239 //!
240 //! # Soundness
241 //!
242 //! Unstable is not the same as unsound. Every entry point here that takes
243 //! an explicit [`Backend`] — the [`BcryptLanesFn`] pointers handed out by
244 //! [`bcrypt_lanes_fn`] — is an `unsafe fn`: it dispatches to a
245 //! `#[target_feature(enable = ...)]` kernel, so running one whose feature
246 //! this CPU lacks is undefined behaviour (`SIGILL` in practice), and only
247 //! the caller can rule that out. [`Backend::is_available`] is the
248 //! portable check.
249 //!
250 //! The safe public API — [`hash`](crate::hash), [`verify`](crate::verify),
251 //! the batch functions, [`detected_backend`](crate::detected_backend) —
252 //! never lets a caller name a backend. It takes the backend from the
253 //! cached runtime cascade in [`backend`], which by construction only ever
254 //! names a backend this CPU advertises. That is the whole reason it can
255 //! be safe, and why turning on `internal-api` cannot make a
256 //! `#![forbid(unsafe_code)]` program reachable by UB.
257
258 #[cfg(feature = "alloc")]
259 pub use crate::core::bcrypt_many_with_backend;
260 pub use crate::core::constant_time_eq;
261 pub use crate::eks::scalar;
262 pub use crate::eks::{Backend, BcryptLanesFn, backend, bcrypt_lanes_fn, detect};
263 pub use crate::encoding::HashParts;
264
265 /// The scalar base64 tables — the reference the SIMD kernels are
266 /// checked against, exposed so benches can time dispatch against it.
267 pub mod base64_scalar {
268 pub use crate::base64::scalar::{decode_16, decode_23, encode_16, encode_23};
269 }
270
271 // The base64 codec and wipe helpers are `pub(crate)` in their modules,
272 // so they cannot be re-exported; these thin inline wrappers are the
273 // same functions by another name.
274 /// Encode a 16-byte salt to its 22-char bcrypt-base64 form.
275 #[inline]
276 #[must_use]
277 pub fn encode_16(bytes: &[u8; 16]) -> [u8; 22] {
278 crate::base64::encode_16(bytes)
279 }
280
281 /// Encode the 23 hash bytes to their 31-char bcrypt-base64 form.
282 #[inline]
283 #[must_use]
284 pub fn encode_23(bytes: &[u8; 23]) -> [u8; 31] {
285 crate::base64::encode_23(bytes)
286 }
287
288 // The unit error is the internal codec's exact contract (the only
289 // failure is "bad char or length", with nothing to say about it); these
290 // wrappers exist to give tests that exact signature.
291 /// Decode exactly 22 bcrypt-base64 chars back to the 16-byte salt.
292 #[inline]
293 #[allow(clippy::result_unit_err)]
294 pub fn decode_16(s: &[u8]) -> Result<[u8; 16], ()> {
295 crate::base64::decode_16(s)
296 }
297
298 /// Decode exactly 31 bcrypt-base64 chars back to the 23 hash bytes.
299 #[inline]
300 #[allow(clippy::result_unit_err)]
301 pub fn decode_23(s: &[u8]) -> Result<[u8; 23], ()> {
302 crate::base64::decode_23(s)
303 }
304
305 /// Overwrite `xs` with zeros in a way the optimizer cannot elide.
306 #[inline]
307 pub fn secure_wipe_bytes(xs: &mut [u8]) {
308 crate::wipe::secure_wipe_bytes(xs);
309 }
310
311 /// Overwrite `xs` with zeros in a way the optimizer cannot elide.
312 #[inline]
313 pub fn secure_wipe_u32(xs: &mut [u32]) {
314 crate::wipe::secure_wipe_u32(xs);
315 }
316
317 /// Each backend's `bcrypt_lanes`, reachable directly so a differential
318 /// test can pit two backends against each other on the same inputs.
319 pub mod backends {
320 #[cfg(target_arch = "x86_64")]
321 pub use crate::eks::avx2;
322 #[cfg(target_arch = "x86_64")]
323 pub use crate::eks::avx512;
324 #[cfg(target_arch = "aarch64")]
325 pub use crate::eks::neon;
326 pub use crate::eks::scalar;
327 #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
328 pub use crate::eks::sse41;
329 #[cfg(all(target_arch = "wasm32", target_feature = "simd128"))]
330 pub use crate::eks::wasm128;
331 }
332}