Skip to main content

bcrypt_rust/
encoding.rs

1//! The bcrypt hash-string format: `$2v$cc$<22 salt chars><31 hash chars>`.
2//!
3//! A hash string is exactly 60 ASCII bytes: a `$2v$` version marker, two
4//! decimal cost digits, a `$`, then the salt and hash fields in bcrypt's own
5//! base64 dialect (see `crate::base64`). [`HashParts`] is the parsed form.
6//! Its [`FromStr`](core::str::FromStr) is deliberately strict — a string
7//! that does not decode exactly is rejected, never repaired — and its
8//! [`Display`](core::fmt::Display) always emits the modern `$2b$` spelling.
9//!
10//! Parsing and formatting are stack-only; the two `String` helpers are the
11//! module's only `alloc` affordances.
12
13use core::fmt;
14
15#[cfg(feature = "alloc")]
16use alloc::string::String;
17
18use crate::base64;
19use crate::error::BcryptError;
20
21/// Total length of a bcrypt hash string, in bytes.
22const HASH_STRING_LEN: usize = 60;
23/// Offset of the 22-char salt field.
24const SALT_START: usize = 7;
25/// Offset of the 31-char hash field, immediately after the salt.
26const HASH_START: usize = SALT_START + base64::SALT_B64_LEN;
27
28const _: () = assert!(
29    HASH_START + base64::HASH_B64_LEN == HASH_STRING_LEN,
30    "field offsets must tile the 60-byte hash string exactly"
31);
32
33/// The version marker in a bcrypt hash string: the `v` in `$2v$`.
34///
35/// Versions are **labels**: every variant accepted by this crate computes
36/// the same, correct algorithm (see the crate-level "Variant semantics"
37/// section). The historical `$2x$` / 8-bit-`$2a$` bug emulations are not
38/// reproduced.
39#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
40pub enum Version {
41    /// `$2a$` — the original OpenBSD spelling.
42    TwoA,
43    /// `$2x$` — crypt_blowfish's marker for hashes computed with its
44    /// sign-extension bug. Accepted on parse so databases containing it
45    /// still verify; the correct algorithm is computed regardless.
46    TwoX,
47    /// `$2y$` — crypt_blowfish's post-fix spelling.
48    TwoY,
49    /// `$2b$` — the current spelling, and what this crate emits by default.
50    TwoB,
51}
52
53impl Version {
54    /// The marker byte as it appears at position 2 of a hash string.
55    pub(crate) const fn marker(self) -> u8 {
56        match self {
57            Version::TwoA => b'a',
58            Version::TwoX => b'x',
59            Version::TwoY => b'y',
60            Version::TwoB => b'b',
61        }
62    }
63}
64
65impl fmt::Display for Version {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        f.write_str(match self {
68            Version::TwoA => "2a",
69            Version::TwoX => "2x",
70            Version::TwoY => "2y",
71            Version::TwoB => "2b",
72        })
73    }
74}
75
76/// A parsed bcrypt hash: cost, raw salt, and the 23-byte hash payload.
77///
78/// Obtain one from a hash string with `"...".parse()`, or from hashing with
79/// [`hash_with_result`](crate::hash_with_result) /
80/// [`hash_with_salt`](crate::hash_with_salt). Formatting back is
81/// [`Display`](core::fmt::Display) (always `$2b$`) or
82/// [`format_for_version`](HashParts::format_for_version) /
83/// [`write_for_version`](HashParts::write_for_version) for a chosen marker.
84///
85/// The version marker of a parsed string is **not** retained: versions are
86/// labels (see [`Version`]), so re-formatting a parsed `$2a$` string yields
87/// `$2b$` — the same behaviour as the `bcrypt` crate.
88#[derive(Clone, Debug, PartialEq, Eq, Hash)]
89pub struct HashParts {
90    cost: u32,
91    salt: [u8; 16],
92    hash: [u8; 23],
93}
94
95impl HashParts {
96    /// Assemble the parts. `cost` must already be validated to `4..=31` by
97    /// the caller (`crate::core`); the parser validates it on the way in.
98    pub(crate) fn new(cost: u32, salt: [u8; 16], hash: [u8; 23]) -> Self {
99        debug_assert!((crate::core::MIN_COST..=crate::core::MAX_COST).contains(&cost));
100        HashParts { cost, salt, hash }
101    }
102
103    /// The cost parameter: bcrypt's `log2(rounds)`, in `4..=31`.
104    #[must_use]
105    pub fn get_cost(&self) -> u32 {
106        self.cost
107    }
108
109    /// The salt, encoded in bcrypt's base64 dialect (22 chars).
110    #[cfg(feature = "alloc")]
111    #[must_use]
112    pub fn get_salt(&self) -> String {
113        // The encoded form is pure ASCII by construction, so the lossy
114        // conversion never actually replaces anything.
115        String::from_utf8_lossy(&base64::encode_16(&self.salt)).into_owned()
116    }
117
118    /// The raw 16-byte salt.
119    #[must_use]
120    pub fn get_salt_raw(&self) -> [u8; 16] {
121        self.salt
122    }
123
124    /// The raw 23-byte hash payload: the 24-byte bcrypt ciphertext with its
125    /// last byte dropped, exactly as the string's hash field encodes it.
126    ///
127    /// This accessor is an **extension** over the `bcrypt` crate, which
128    /// exposes the payload only as an encoded string.
129    #[must_use]
130    pub fn get_hash(&self) -> [u8; 23] {
131        self.hash
132    }
133
134    /// The 60-byte hash string with the given version marker.
135    #[cfg(feature = "alloc")]
136    #[must_use]
137    pub fn format_for_version(&self, version: Version) -> String {
138        String::from_utf8_lossy(&self.format_bytes(version)).into_owned()
139    }
140
141    /// Write the 60-byte hash string with the given version marker to `w`.
142    pub fn write_for_version<W: fmt::Write>(
143        &self,
144        version: Version,
145        w: &mut W,
146    ) -> fmt::Result {
147        let bytes = self.format_bytes(version);
148        match core::str::from_utf8(&bytes) {
149            Ok(s) => w.write_str(s),
150            // format_bytes only ever emits ASCII, so this branch is
151            // unreachable; report it as a formatting error, never a panic.
152            Err(_) => Err(fmt::Error),
153        }
154    }
155
156    /// The hash string as stack bytes — the shared core both public
157    /// formatting wrappers build on.
158    pub(crate) fn format_bytes(&self, version: Version) -> [u8; HASH_STRING_LEN] {
159        let mut out = [0u8; HASH_STRING_LEN];
160        out[0] = b'$';
161        out[1] = b'2';
162        out[2] = version.marker();
163        out[3] = b'$';
164        // Cost is 4..=31 by construction, so exactly two decimal digits.
165        out[4] = b'0' + (self.cost / 10) as u8;
166        out[5] = b'0' + (self.cost % 10) as u8;
167        out[6] = b'$';
168        out[SALT_START..HASH_START].copy_from_slice(&base64::encode_16(&self.salt));
169        out[HASH_START..HASH_STRING_LEN].copy_from_slice(&base64::encode_23(&self.hash));
170        out
171    }
172}
173
174impl core::str::FromStr for HashParts {
175    type Err = BcryptError;
176
177    /// Strict parser. Rejects — with [`InvalidHash`](BcryptError::InvalidHash)
178    /// naming the failing part — anything that is not exactly 60 bytes of
179    /// `$2v$cc$<salt><hash>` with `v` one of `a`/`b`/`x`/`y`, two decimal
180    /// cost digits in `4..=31`, and both fields valid bcrypt base64:
181    ///
182    /// * `"length"` — not exactly 60 bytes;
183    /// * `"prefix"` — bad magic, unknown version marker, or missing `$`;
184    /// * `"cost"` — non-decimal digits or a value outside `4..=31` (an
185    ///   out-of-range cost *in a string* is a parse error;
186    ///   [`CostNotAllowed`](BcryptError::CostNotAllowed) is reserved for cost
187    ///   *arguments* to hash functions, matching the `bcrypt` crate);
188    /// * `"salt"` / `"hash"` — a character outside the bcrypt alphabet.
189    ///
190    /// Every check compares bytes, so a non-ASCII string fails the field it
191    /// lands in; no separate ASCII pass is needed.
192    fn from_str(s: &str) -> Result<Self, BcryptError> {
193        let b = s.as_bytes();
194        if b.len() != HASH_STRING_LEN {
195            return Err(BcryptError::InvalidHash("length"));
196        }
197        if b[0] != b'$' || b[1] != b'2' || b[3] != b'$' {
198            return Err(BcryptError::InvalidHash("prefix"));
199        }
200        match b[2] {
201            // The marker is validated but not stored: versions are labels.
202            b'a' | b'b' | b'x' | b'y' => {}
203            _ => return Err(BcryptError::InvalidHash("prefix")),
204        }
205        if !b[4].is_ascii_digit() || !b[5].is_ascii_digit() {
206            return Err(BcryptError::InvalidHash("cost"));
207        }
208        let cost = u32::from(b[4] - b'0') * 10 + u32::from(b[5] - b'0');
209        if !(crate::core::MIN_COST..=crate::core::MAX_COST).contains(&cost) {
210            return Err(BcryptError::InvalidHash("cost"));
211        }
212        if b[6] != b'$' {
213            return Err(BcryptError::InvalidHash("prefix"));
214        }
215        let salt = base64::decode_16(&b[SALT_START..HASH_START])
216            .map_err(|()| BcryptError::InvalidHash("salt"))?;
217        let hash = base64::decode_23(&b[HASH_START..HASH_STRING_LEN])
218            .map_err(|()| BcryptError::InvalidHash("hash"))?;
219        Ok(HashParts { cost, salt, hash })
220    }
221}
222
223impl fmt::Display for HashParts {
224    /// The 60-byte hash string in the default `$2b$` spelling.
225    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226        self.write_for_version(Version::TwoB, f)
227    }
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233
234    /// OpenBSD's own vector, `$2a$05$CCCC…` — 60 bytes.
235    const GOOD: &str = "$2a$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW";
236
237    /// A minimal `fmt::Write` over a stack buffer, so Display and
238    /// `write_for_version` can be tested without `alloc`.
239    struct StackWriter<'a> {
240        buf: &'a mut [u8],
241        len: usize,
242    }
243
244    impl fmt::Write for StackWriter<'_> {
245        fn write_str(&mut self, s: &str) -> fmt::Result {
246            let end = self.len + s.len();
247            if end > self.buf.len() {
248                return Err(fmt::Error);
249            }
250            self.buf[self.len..end].copy_from_slice(s.as_bytes());
251            self.len = end;
252            Ok(())
253        }
254    }
255
256    fn rejection_part(s: &str) -> &'static str {
257        match s.parse::<HashParts>() {
258            Err(BcryptError::InvalidHash(part)) => part,
259            other => panic!("expected InvalidHash, got {other:?}"),
260        }
261    }
262
263    #[test]
264    fn parses_all_four_prefixes_identically() {
265        let parts: HashParts = GOOD.parse().expect("the OpenBSD vector parses");
266        for marker in *b"abxy" {
267            let mut bytes = [0u8; HASH_STRING_LEN];
268            bytes.copy_from_slice(GOOD.as_bytes());
269            bytes[2] = marker;
270            let s = core::str::from_utf8(&bytes).expect("still ASCII");
271            assert_eq!(s.parse::<HashParts>(), Ok(parts.clone()));
272        }
273    }
274
275    #[test]
276    fn getters_return_the_vector_fields() {
277        let parts: HashParts = GOOD.parse().expect("the OpenBSD vector parses");
278        assert_eq!(parts.get_cost(), 5);
279        assert_eq!(
280            parts.get_salt_raw(),
281            base64::decode_16(b"CCCCCCCCCCCCCCCCCCCCC.").expect("salt decodes")
282        );
283        assert_eq!(
284            parts.get_hash(),
285            base64::decode_23(b"E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW").expect("hash decodes")
286        );
287    }
288
289    #[test]
290    fn format_bytes_round_trips_through_the_parser() {
291        let parts: HashParts = GOOD.parse().expect("the OpenBSD vector parses");
292        for (version, prefix) in [
293            (Version::TwoA, "$2a$"),
294            (Version::TwoB, "$2b$"),
295            (Version::TwoX, "$2x$"),
296            (Version::TwoY, "$2y$"),
297        ] {
298            let bytes = parts.format_bytes(version);
299            let s = core::str::from_utf8(&bytes).expect("format_bytes emits ASCII");
300            assert_eq!(s.len(), HASH_STRING_LEN);
301            assert!(s.starts_with(prefix));
302            assert_eq!(s.parse::<HashParts>(), Ok(parts.clone()));
303        }
304    }
305
306    #[test]
307    fn display_defaults_to_2b() {
308        let parts: HashParts = GOOD.parse().expect("the OpenBSD vector parses");
309        let expected = parts.format_bytes(Version::TwoB);
310        let mut buf = [0u8; HASH_STRING_LEN];
311        let mut w = StackWriter {
312            buf: &mut buf,
313            len: 0,
314        };
315        fmt::write(&mut w, format_args!("{parts}")).expect("Display fits the buffer");
316        assert_eq!(w.len, HASH_STRING_LEN);
317        assert_eq!(w.buf, &expected);
318        assert!(expected.starts_with(b"$2b$"));
319    }
320
321    #[test]
322    fn write_for_version_matches_format_bytes() {
323        let parts: HashParts = GOOD.parse().expect("the OpenBSD vector parses");
324        for version in [Version::TwoA, Version::TwoB, Version::TwoX, Version::TwoY] {
325            let mut buf = [0u8; HASH_STRING_LEN];
326            let mut w = StackWriter {
327                buf: &mut buf,
328                len: 0,
329            };
330            parts
331                .write_for_version(version, &mut w)
332                .expect("writing to a stack buffer fits");
333            assert_eq!(w.len, HASH_STRING_LEN);
334            assert_eq!(w.buf, &parts.format_bytes(version));
335        }
336    }
337
338    #[test]
339    fn parser_rejection_matrix() {
340        // Length: 59 and 61 bytes, and the empty string.
341        assert_eq!(rejection_part(""), "length");
342        assert_eq!(rejection_part(&GOOD[..59]), "length");
343        let mut longer = [0u8; 61];
344        longer[..60].copy_from_slice(GOOD.as_bytes());
345        longer[60] = b'W';
346        let longer = core::str::from_utf8(&longer).expect("ASCII");
347        assert_eq!(rejection_part(longer), "length");
348
349        // Prefix: bad magic, unknown marker, and missing `$` at index 3 or 6.
350        for bad in [
351            "$1a$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW",
352            "$2z$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW",
353            "$2aX05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW",
354            "$2a$05XCCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW",
355        ] {
356            assert_eq!(rejection_part(bad), "prefix", "{bad}");
357        }
358
359        // Cost: non-digit, below the floor, above the ceiling.
360        for bad in [
361            "$2a$0x$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW",
362            "$2a$03$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW",
363            "$2a$32$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW",
364        ] {
365            assert_eq!(rejection_part(bad), "cost", "{bad}");
366        }
367
368        // Salt/hash fields: one byte outside the bcrypt alphabet each.
369        assert_eq!(
370            rejection_part("$2a$05$CCC!CCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW"),
371            "salt"
372        );
373        assert_eq!(
374            rejection_part("$2a$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOe*"),
375            "hash"
376        );
377
378        // A non-ASCII byte inside the salt field fails the salt check, not
379        // the length check: "é" is 2 bytes, so the string stays 60 bytes.
380        let non_ascii = "$2a$05$éCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW";
381        assert_eq!(non_ascii.len(), HASH_STRING_LEN);
382        assert_eq!(rejection_part(non_ascii), "salt");
383    }
384
385    #[cfg(feature = "alloc")]
386    #[test]
387    fn alloc_helpers_agree_with_the_stack_core() {
388        use alloc::string::{String, ToString};
389
390        let parts: HashParts = GOOD.parse().expect("the OpenBSD vector parses");
391        assert_eq!(parts.get_salt(), "CCCCCCCCCCCCCCCCCCCCC.");
392        assert_eq!(parts.format_for_version(Version::TwoA), GOOD);
393        // Display normalises any parsed marker to $2b$.
394        assert_eq!(parts.to_string().len(), HASH_STRING_LEN);
395        assert!(parts.to_string().starts_with("$2b$"));
396
397        let mut s = String::new();
398        parts
399            .write_for_version(Version::TwoB, &mut s)
400            .expect("writing to a String is infallible");
401        assert_eq!(s, parts.format_for_version(Version::TwoB));
402    }
403
404    #[test]
405    fn version_display_and_marker_agree() {
406        for (version, text, marker) in [
407            (Version::TwoA, "2a", b'a'),
408            (Version::TwoX, "2x", b'x'),
409            (Version::TwoY, "2y", b'y'),
410            (Version::TwoB, "2b", b'b'),
411        ] {
412            assert_eq!(version.marker(), marker);
413            let mut buf = [0u8; 2];
414            let mut w = StackWriter {
415                buf: &mut buf,
416                len: 0,
417            };
418            fmt::write(&mut w, format_args!("{version}")).expect("two bytes fit");
419            assert_eq!(w.len, 2);
420            assert_eq!(w.buf, text.as_bytes());
421        }
422    }
423}