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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
//! A pure-Rust implementation of [bcrypt](https://www.usenix.org/legacy/events/usenix99/provos/provos.pdf),
//! 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:
//!
//! | backend | lanes | batch | hashes/s | vs scalar |
//! |---|---|---|---|---|
//! | scalar | 1 | 16 | 790.4 | 1.00 |
//! | NEON | 8 | 16 | 3187.1 | 4.03× |
//! | wasm128 (under wasmtime 48, cost 4) | 8 | 8 | 2006.8 | 1.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
//!
//! ```
//! # #[cfg(feature = "std")]
//! # fn run() -> Result<(), bcrypt_rust::BcryptError> {
//! // 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)?);
//! # Ok(())
//! # }
//! # #[cfg(not(feature = "std"))]
//! # fn run() -> Result<(), bcrypt_rust::BcryptError> { Ok(()) }
//! # run().unwrap();
//! ```
//!
//! # Batch hashing
//!
//! ```
//! # #[cfg(feature = "std")]
//! # fn run() -> Result<(), bcrypt_rust::BcryptError> {
//! 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)?);
//! }
//! # Ok(())
//! # }
//! # #[cfg(not(feature = "std"))]
//! # fn run() -> Result<(), bcrypt_rust::BcryptError> { Ok(()) }
//! # run().unwrap();
//! ```
//!
//! # Features
//!
//! | feature | default | what it gates |
//! |---|---|---|
//! | `std` | ✓ | runtime CPU feature detection; OS-entropy salts for [`hash`], [`hash_bytes`], [`hash_with_result`], [`hash_many`] |
//! | `alloc` | via `std` | `String`/`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](https://crates.io/crates/bcrypt)
//! (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](https://github.com/Brooooooklyn/bcrypt-rust/blob/main/docs/superpowers/specs/2026-10-01-bcrypt-rust-design.md#3-variant-semantics-deliberate-documented)
//! 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 `Result`s 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).
// A `pub` item that a downstream crate cannot *name* is only half-public: it
// works in `let` bindings and nowhere else — not in a struct field, a
// function signature, or a `Vec`. `HashParts` (returned by
// `hash_with_result`) and `Backend` (returned by `detected_backend`) are
// exactly the items a caller needs to store; this lint is the regression
// guard.
// `__internal` re-exports `eks::scalar` (a module) so tests can drive the
// scalar kernel directly. Its module doc links to private helpers
// (`expand_state`), which rustdoc flags once the module is publicly
// reachable; the link is correct under `--document-private-items` and the
// module is off-limits to edit, so allow it here rather than churn the docs.
// clippy suggests `as_chunks`/`as_chunks_mut` (stable since 1.88, so usable at
// the pinned MSRV 1.89 — this lint fires on stable clippy). Rewriting the
// verified base64 codec for it is style-only churn, so the lint is allowed
// crate-wide instead.
// NOTE FOR EVERY CONTRIBUTOR: this crate has a module named `core`, which
// shadows the `core` crate *in this root module only*. Inside `src/lib.rs`
// always write `::core::...`. Submodules are unaffected — bare `core::` there
// still means the `core` crate.
extern crate alloc;
extern crate std;
// These modules are private, and a good deal of what they expose escapes the
// crate only through `__internal` (below), which tests and benches enable. In
// a plain build those items are legitimately unreachable, so `dead_code`
// would fire on all of them.
//
// Rather than blanket-allowing `dead_code` — which would also hide code that
// is dead by mistake — the allow is tied to `internal-api` being OFF. With
// the feature ON, `__internal` re-exports the intended surface, so anything
// the compiler still calls dead really is dead and gets reported.
private_modules!;
// OS entropy for the convenience salt API; needs std for the syscall and the
// /dev/urandom fallback. Declared per-platform inside the module.
//
// Deliberately not in `private_modules!`: everything here is reachable from
// the random-salt entry points (`hash`, `hash_many`, …) on every `std`
// build, so it needs no `dead_code` allow, and should not have one hiding a
// future mistake.
pub use crate;
pub use crate;
pub use crate;
pub use crateBackend;
pub use crate;
pub use crate;
/// The [`Backend`] this CPU resolved to, cached after the first call.
///
/// Diagnostic only — the hashing entry points resolve it for you. Remember
/// it only speaks for *batch* throughput: [`hash`] and [`verify`] always run
/// scalar (see the crate-level "What SIMD does — and does not — do here").
///
/// ```
/// println!("bcrypt backend: {}", bcrypt_rust::detected_backend());
/// ```