Something went wrong. Try again.
passlib's password hash schemes, ported to Zig 0.16
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! bcrypt, and bcrypt behind SHA-256: passlib's `passlib.handlers.bcrypt`.//!//! Niels Provos and David Mazières' `$2$` format for OpenBSD, 1999. It is//! Blowfish with an "expensive key schedule": the password and a 128-bit salt//! are mixed into the cipher's state `2^rounds` times, and the result//! encrypts the string `OrpheanBeholderScryDoubt` 64 times. The work factor is//! stored in the hash, so it can be raised as hardware gets faster, and the//! key schedule needs 4 KiB of fast memory that GPUs find awkward. It is//! still a sound choice for a new hash.//!//! A hash is `$2b$12$`, then 22 characters of salt and 31 of checksum, in//! bcrypt's own base64 alphabet (`./A-Za-z0-9`, not the `crypt` order).//!//! ## Quirks//!//! **Only the first 72 bytes of the password count.** The key schedule reads//! 72 bytes, cycling through the password and a terminating NUL, so//! everything past the 72nd byte is ignored. passlib truncates silently//! unless `truncate_error` is set. `bcrypt_sha256` exists to get round it.//!//! **A NUL cannot be part of a password.** The C implementations read the//! password as a C string, so passlib refuses a password holding one rather//! than hash something other than what it was given.//!//! **The idents are a history of bugs.** `$2$` is the original, which does//! not count the terminating NUL as part of the key. `$2a$` added it, and//! then meant different things in different implementations: crypt_blowfish//! sign-extended bytes over 0x7f before 2011 (CVE-2011-2483), and OpenBSD//! wrapped the password length at 256 before 2014. crypt_blowfish renamed its//! fixed algorithm `$2y$` and its buggy one `$2x$`, and OpenBSD called its fix//! `$2b$`. The correct algorithm is the same for `$2a$`, `$2y$` and `$2b$`,//! and that is what this computes for all three, as passlib's own backend//! does. `$2x$` is identified and refused, as passlib refuses it.//!//! **The salt's last character carries four unused bits.** 22 characters//! hold 132 bits for a 128-bit salt, so only `.Oeu` are valid last//! characters. Some old implementations wrote others (passlib issue 25);//! passlib clears the stray bits, which is what OpenBSD's decoder reads//! anyway, and `needsUpdate` reports such a `$2a$` hash so it can be//! rewritten cleanly.
const std = @import("std");const Io = std.Io;const Sha256 = std.crypto.hash.sha2.Sha256;const HmacSha256 = std.crypto.auth.hmac.sha2.HmacSha256;const testing = std.testing;
const encoding = @import("../encoding.zig");const bcrypt64 = encoding.bcrypt64;const handler = @import("../handler.zig");const Context = handler.Context;const Error = handler.Error;
/// Characters of salt in a hash.pub const salt_len = 22;/// Characters of checksum in a hash.pub const checksum_len = 31;/// The bytes of password the key schedule reads. passlib's `truncate_size`.pub const truncate_size = 72;pub const min_rounds = 4;pub const max_rounds = 31;pub const default_rounds = 12;
/// The characters a salt's last character can be once its unused bits are/// clear. passlib's `final_salt_chars`.const final_salt_chars = ".Oeu";
/// The variants of bcrypt passlib will write. `$2x$` is not one of them.pub const Ident = enum { /// The original, which leaves the terminating NUL out of the key. @"2", /// The NUL included. What most stored hashes are. @"2a", /// crypt_blowfish's name for `$2a$` without its sign-extension bug. @"2y", /// OpenBSD's name for `$2a$` without its length-wraparound bug. @"2b",
pub fn prefix(ident: Ident) []const u8 { return switch (ident) { .@"2" => "$2$", .@"2a" => "$2a$", .@"2y" => "$2y$", .@"2b" => "$2b$", }; }};
/// The 31-character bcrypt checksum of `password` under `salt` (22/// characters of bcrypt base64, whose unused bits are ignored) and/// `2^rounds` iterations, as passlib's builtin backend computes it for/// `ident`. The caller has checked `rounds` and refused a NUL in `password`.pub fn rawChecksum(password: []const u8, ident: Ident, salt: *const [salt_len]u8, rounds: u5, out: *[checksum_len]u8) void { var salt_bytes: [16]u8 = undefined; // 22 characters of the alphabet always decode to 16 bytes. _ = bcrypt64.decode(&salt_bytes, salt) catch unreachable;
// `std` appends a NUL to at most 72 bytes of password and reads the first // 72 bytes of that, cycling: `$2a$` and its successors exactly. `$2$` // cycles the password alone, so it gets the password already cycled to // 72 bytes, whose NUL `std` then never reaches. An empty password cycles // to 72 NULs, as the C reads the NUL after it. var key_buf: [truncate_size]u8 = @splat(0); defer std.crypto.secureZero(u8, &key_buf); const key = switch (ident) { .@"2" => blk: { if (password.len > 0) { for (&key_buf, 0..) |*b, i| b.* = password[i % password.len]; } break :blk key_buf[0..]; }, .@"2a", .@"2y", .@"2b" => password, }; const raw = std.crypto.pwhash.bcrypt.bcrypt(key, &salt_bytes, .{ .rounds_log = rounds, // With false, `std` pre-hashes a long password, which is not bcrypt. .silently_truncate_password = true, }); _ = bcrypt64.encode(out, &raw);}
/// `salt` with its last character's unused bits cleared: passlib's/// `bcrypt64.repair_unused`.fn repairSalt(salt: *[salt_len]u8) void { salt[salt_len - 1] = bcrypt64.repairedLast(salt);}
/// A salt from `Options.salt`, or a random one, with its unused bits clear.fn chooseSalt(io: Io, given: ?[]const u8, out: *[salt_len]u8) Error!void { if (given) |s| { if (s.len != salt_len or !bcrypt64.isValid(s)) return error.InvalidOptions; @memcpy(out, s); } else { _ = try handler.randomChars(io, out, encoding.bcrypt_chars); } repairSalt(out);}
/// passlib's `min_desired_rounds` and `max_desired_rounds`, checked as/// `using()` checks them.fn checkDesired(min_desired: ?u32, max_desired: ?u32) Error!void { if (min_desired) |m| if (m < min_rounds or m > max_rounds) return error.InvalidOptions; if (max_desired) |m| if (m < min_rounds or m > max_rounds) return error.InvalidOptions; if (min_desired != null and max_desired != null and max_desired.? < min_desired.?) return error.InvalidOptions;}
/// `rounds`, checked, then clipped to the desired bounds as passlib's/// `_clip_to_desired_rounds` clips its default.fn chooseRounds(rounds: u8, min_desired: ?u32, max_desired: ?u32) Error!u5 { if (rounds < min_rounds or rounds > max_rounds) return error.InvalidOptions; try checkDesired(min_desired, max_desired); var r: u32 = rounds; if (min_desired) |m| r = @max(r, m); if (max_desired) |m| r = @min(r, m); return @intCast(r);}
/// The password checks passlib's `_norm_digest_args` makes.fn checkPassword(password: []const u8) Error!void { try handler.checkPasswordLen(password); if (std.mem.findScalar(u8, password, 0) != null) return error.InvalidPassword;}
/// Two digits, `04` to `31`: the rounds field of a bcrypt hash. passlib/// requires the field to read back exactly as `%02d` writes it, and no other/// spelling of a value in range survives that.fn parseRounds(s: []const u8) Error!u5 { if (s.len != 2 or !std.ascii.isDigit(s[0]) or !std.ascii.isDigit(s[1])) return error.MalformedHash; const r = (s[0] - '0') * 10 + (s[1] - '0'); if (r < min_rounds or r > max_rounds) return error.MalformedHash; return @intCast(r);}
/// A salt field: 22 characters of the alphabet, repaired as passlib's/// `_norm_salt` repairs it.fn parseSalt(s: []const u8) Error![salt_len]u8 { if (s.len != salt_len or !bcrypt64.isValid(s)) return error.MalformedHash; var salt: [salt_len]u8 = s[0..salt_len].*; repairSalt(&salt); return salt;}
/// A checksum field: 31 characters of the alphabet, with the unused bits of/// the last cleared as passlib's `_norm_checksum` clears them, so a checksum/// with stray bits still compares equal to the one computed.fn parseChecksum(s: []const u8) Error![checksum_len]u8 { if (s.len != checksum_len or !bcrypt64.isValid(s)) return error.MalformedHash; var checksum: [checksum_len]u8 = s[0..checksum_len].*; checksum[checksum_len - 1] = bcrypt64.repairedLast(s); return checksum;}
/// passlib's `bcrypt`: `$2b$` and the idents before it.pub const bcrypt = struct { pub const name = "bcrypt";
pub const Options = struct { /// The salt: 22 characters of `./A-Za-z0-9`. Stray bits in the last /// character are cleared, as passlib clears them. Null, the default, /// draws a random one. salt: ?[]const u8 = null, /// log2 of the iterations, 4 to 31. passlib's `default_rounds`. rounds: u8 = default_rounds, /// The variant to write. passlib's default is `$2b$`. ident: Ident = .@"2b", /// Refuse a password over 72 bytes with `error.PasswordTooLong` /// rather than hash its first 72. Only `hash` looks at this: `verify` /// truncates regardless, as passlib does. truncate_error: bool = false, /// `needsUpdate` reports a hash with fewer rounds than this. `hash` /// raises `rounds` to it. min_desired_rounds: ?u32 = null, /// `needsUpdate` reports a hash with more rounds than this. `hash` /// lowers `rounds` to it. max_desired_rounds: ?u32 = null, };
/// Any of `$2$`, `$2a$`, `$2x$`, `$2y$` or `$2b$`, as passlib claims all /// five, even the one it refuses. pub fn identify(h: []const u8) bool { inline for (.{ "$2$", "$2a$", "$2x$", "$2y$", "$2b$" }) |p| { if (std.mem.startsWith(u8, h, p)) return true; } return false; }
const Parsed = struct { ident: Ident, rounds: u5, salt: [salt_len]u8, checksum: ?[checksum_len]u8, };
/// passlib's `from_string`. A configuration string, one with no /// checksum, parses with `checksum` null. fn parse(h: []const u8) Error!Parsed { const ident: Ident, const rest = blk: { inline for (.{ .@"2", .@"2a", .@"2y", .@"2b" }) |i| { const p = comptime Ident.prefix(i); if (std.mem.startsWith(u8, h, p)) break :blk .{ i, h[p.len..] }; } // `$2x$` among them: identified, and refused. return error.MalformedHash; }; const fields = try handler.splitExact(2, rest, '$'); const rounds = try parseRounds(fields[0]); const data = fields[1]; const salt = try parseSalt(data[0..@min(data.len, salt_len)]); const checksum = if (data.len > salt_len) try parseChecksum(data[salt_len..]) else null; return .{ .ident = ident, .rounds = rounds, .salt = salt, .checksum = checksum }; }
pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { const rounds = try chooseRounds(options.rounds, options.min_desired_rounds, options.max_desired_rounds); var salt: [salt_len]u8 = undefined; try chooseSalt(ctx.io, options.salt, &salt); try checkPassword(password); if (options.truncate_error and password.len > truncate_size) return error.PasswordTooLong; var checksum: [checksum_len]u8 = undefined; rawChecksum(password, options.ident, &salt, rounds, &checksum); try w.print("{s}{d:0>2}${s}{s}", .{ options.ident.prefix(), rounds, &salt, &checksum }); }
pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { _ = ctx; const parsed = try parse(h); const stored = parsed.checksum orelse return error.MalformedHash; try checkPassword(password); var checksum: [checksum_len]u8 = undefined; rawChecksum(password, parsed.ident, &parsed.salt, parsed.rounds, &checksum); return handler.eql(&stored, &checksum); }
/// True for a `$2a$` hash whose salt has stray bits in its last /// character, checked before anything else as passlib checks it, and /// for a hash whose rounds fall outside the desired bounds. /// /// The ident is not compared: passlib 1.7.4 does not report a `$2a$` or /// `$2y$` hash when configured for `$2b$`, since the three compute the /// same thing. pub fn needsUpdate(h: []const u8, options: Options) Error!bool { try checkDesired(options.min_desired_rounds, options.max_desired_rounds); _ = try chooseRounds(options.rounds, options.min_desired_rounds, options.max_desired_rounds); if (options.salt) |s| if (s.len != salt_len or !bcrypt64.isValid(s)) return error.InvalidOptions; // passlib reads the 29th character before parsing anything, so a // `$2a$` string too short to have one is an IndexError there. if (std.mem.startsWith(u8, h, "$2a$")) { if (h.len <= 28) return error.MalformedHash; if (std.mem.findScalar(u8, final_salt_chars, h[28]) == null) return true; } const parsed = try parse(h); return handler.roundsOutside(parsed.rounds, options.min_desired_rounds, options.max_desired_rounds); }};
/// passlib's `bcrypt_sha256`: bcrypt of a SHA-256 digest of the password, so/// that every byte of a long password counts.////// Version 2, passlib 1.7.3's and the default, keys an HMAC-SHA256 with the/// salt string and writes `$bcrypt-sha256$v=2,t=2b,r=12$<salt>$<checksum>`./// Version 1 took a plain SHA-256 and wrote `$bcrypt-sha256$2b,12$...`,/// with `2a` as well as `2b`. Either way the digest is base64 encoded, padding/// and all, and the 44 characters of that are the bcrypt password: short/// enough never to be truncated, and free of NULs.pub const bcrypt_sha256 = struct { pub const name = "bcrypt_sha256"; const prefix = "$bcrypt-sha256$";
pub const Options = struct { /// As `bcrypt`'s. salt: ?[]const u8 = null, /// As `bcrypt`'s. rounds: u8 = default_rounds, /// `$2a$` or `$2b$`, and only `$2b$` for version 2. ident: Ident = .@"2b", /// The format to write, 1 or 2. `needsUpdate` reports a hash of an /// older version than this. version: u8 = 2, /// As `bcrypt`'s. min_desired_rounds: ?u32 = null, /// As `bcrypt`'s. max_desired_rounds: ?u32 = null, };
pub fn identify(h: []const u8) bool { return std.mem.startsWith(u8, h, prefix); }
const Parsed = struct { version: u8, ident: Ident, rounds: u5, salt: [salt_len]u8, checksum: ?[checksum_len]u8, };
/// passlib's two regular expressions, tried version 2 first. fn parse(hash_in: []const u8) Error!Parsed { if (!identify(hash_in)) return error.MalformedHash; var h = hash_in[prefix.len..]; // Python's `$` matches before a final newline too. if (std.mem.endsWith(u8, h, "\n")) h = h[0 .. h.len - 1];
var version: u8 = 1; var ident: Ident = undefined; var rest: []const u8 = undefined; if (std.mem.startsWith(u8, h, "v=")) { // v=<digits>,t=2b,r=<digits> const comma = std.mem.findScalar(u8, h, ',') orelse return error.MalformedHash; const v = h[2..comma]; if (v.len == 0) return error.MalformedHash; for (v) |c| if (!std.ascii.isDigit(c)) return error.MalformedHash; // Any spelling of 2, leading zeros and all: 1 is refused by the // pattern's check and 3 or more by `_norm_version`. const trimmed = std.mem.trimStart(u8, v, "0"); if (!std.mem.eql(u8, trimmed, "2")) return error.MalformedHash; version = 2; rest = h[comma + 1 ..]; if (!std.mem.startsWith(u8, rest, "t=2b,r=")) return error.MalformedHash; ident = .@"2b"; rest = rest["t=2b,r=".len..]; } else { // 2a,<digits> or 2b,<digits> if (std.mem.startsWith(u8, h, "2a,")) { ident = .@"2a"; } else if (std.mem.startsWith(u8, h, "2b,")) { ident = .@"2b"; } else return error.MalformedHash; rest = h[3..]; }
const dollar = std.mem.findScalar(u8, rest, '$') orelse return error.MalformedHash; const r = rest[0..dollar]; if (r.len < 1 or r.len > 2) return error.MalformedHash; for (r) |c| if (!std.ascii.isDigit(c)) return error.MalformedHash; if (r[0] == '0' and r.len > 1) return error.MalformedHash; const rounds_value = std.fmt.parseInt(u8, r, 10) catch return error.MalformedHash; if (rounds_value < min_rounds or rounds_value > max_rounds) return error.MalformedHash;
const tail = rest[dollar + 1 ..]; const salt_field, const checksum_field = if (std.mem.findScalar(u8, tail, '$')) |d| .{ tail[0..d], @as(?[]const u8, tail[d + 1 ..]) } else .{ tail, @as(?[]const u8, null) }; const salt = try parseSalt(salt_field); const checksum = if (checksum_field) |c| try parseChecksum(c) else null; return .{ .version = version, .ident = ident, .rounds = @intCast(rounds_value), .salt = salt, .checksum = checksum, }; }
/// The bcrypt password for `password`: the base64 of its SHA-256 /// (version 1) or of its HMAC-SHA256 keyed by the salt string (version 2). fn key(password: []const u8, version: u8, salt: *const [salt_len]u8, out: *[44]u8) void { var digest: [32]u8 = undefined; if (version == 1) { Sha256.hash(password, &digest, .{}); } else { HmacSha256.create(&digest, password, salt); } _ = std.base64.standard.Encoder.encode(out, &digest); }
fn compute(password: []const u8, version: u8, ident: Ident, salt: *const [salt_len]u8, rounds: u5, out: *[checksum_len]u8) void { var k: [44]u8 = undefined; defer std.crypto.secureZero(u8, &k); key(password, version, salt, &k); rawChecksum(&k, ident, salt, rounds, out); }
fn checkOptions(options: Options) Error!u5 { if (options.version != 1 and options.version != 2) return error.InvalidOptions; switch (options.ident) { .@"2b" => {}, .@"2a" => if (options.version != 1) return error.InvalidOptions, .@"2", .@"2y" => return error.InvalidOptions, } if (options.salt) |s| if (s.len != salt_len or !bcrypt64.isValid(s)) return error.InvalidOptions; return chooseRounds(options.rounds, options.min_desired_rounds, options.max_desired_rounds); }
pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { const rounds = try checkOptions(options); var salt: [salt_len]u8 = undefined; try chooseSalt(ctx.io, options.salt, &salt); try handler.checkPasswordLen(password); var checksum: [checksum_len]u8 = undefined; compute(password, options.version, options.ident, &salt, rounds, &checksum); const t = options.ident.prefix(); const t_bare = t[1 .. t.len - 1]; if (options.version == 1) { try w.print("{s}{s},{d}${s}${s}", .{ prefix, t_bare, rounds, &salt, &checksum }); } else { try w.print("{s}v=2,t={s},r={d}${s}${s}", .{ prefix, t_bare, rounds, &salt, &checksum }); } }
pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { _ = ctx; try handler.checkPasswordLen(password); const parsed = try parse(h); const stored = parsed.checksum orelse return error.MalformedHash; var checksum: [checksum_len]u8 = undefined; compute(password, parsed.version, parsed.ident, &parsed.salt, parsed.rounds, &checksum); return handler.eql(&stored, &checksum); }
/// True for a hash of an older version than `options.version`, or with /// rounds outside the desired bounds. pub fn needsUpdate(h: []const u8, options: Options) Error!bool { _ = try checkOptions(options); const parsed = try parse(h); if (parsed.version < options.version) return true; return handler.roundsOutside(parsed.rounds, options.min_desired_rounds, options.max_desired_rounds); }};
/// The schemes this module defines, in the order `registry.identify` tries/// them.pub const schemes = .{ bcrypt, bcrypt_sha256 };
comptime { handler.check(bcrypt); handler.check(bcrypt_sha256);}
const test_ctx: Context = .{ .io = testing.io, .gpa = testing.allocator };const test_salt = "abcdefghijklmnopqrstuu";
fn expectHash(comptime S: type, password: []const u8, options: S.Options, expected: []const u8) !void { var buf: [128]u8 = undefined; var w: Io.Writer = .fixed(&buf); try S.hash(test_ctx, password, options, &w); try testing.expectEqualStrings(expected, w.buffered()); try testing.expect(try S.verify(test_ctx, password, expected));}
test "bcrypt: every ident, as passlib's builtin backend hashes them" { // PASSLIB_BUILTIN_BCRYPT=enabled, passlib 1.7.4: // bcrypt.using(salt="abcdefghijklmnopqrstuu", rounds=4, ident=...).hash(...) try expectHash(bcrypt, "test", .{ .salt = test_salt, .rounds = 4, .ident = .@"2" }, "$2$04$abcdefghijklmnopqrstuu8LSPFHYuC1w82FIvrwCsJ5KPAsbHc/a"); try expectHash(bcrypt, "test", .{ .salt = test_salt, .rounds = 4, .ident = .@"2a" }, "$2a$04$abcdefghijklmnopqrstuuoD8yw7MmybLKVooaTGGZAt3HXugv2.a"); try expectHash(bcrypt, "test", .{ .salt = test_salt, .rounds = 4, .ident = .@"2y" }, "$2y$04$abcdefghijklmnopqrstuuoD8yw7MmybLKVooaTGGZAt3HXugv2.a"); try expectHash(bcrypt, "test", .{ .salt = test_salt, .rounds = 4 }, "$2b$04$abcdefghijklmnopqrstuuoD8yw7MmybLKVooaTGGZAt3HXugv2.a"); try expectHash(bcrypt, "abc", .{ .salt = test_salt, .rounds = 4, .ident = .@"2" }, "$2$04$abcdefghijklmnopqrstuuc6Unxmz12vpy80gkiL8/xgnSIKHKWCO"); // The empty password: `$2$` cycles nothing, which the C reads as NULs, // and so agrees with `$2b$`. try expectHash(bcrypt, "", .{ .salt = test_salt, .rounds = 4, .ident = .@"2" }, "$2$04$abcdefghijklmnopqrstuubyCG3zY1GIXMyxfivm.ClDiInHzxjiq"); try expectHash(bcrypt, "", .{ .salt = test_salt, .rounds = 4 }, "$2b$04$abcdefghijklmnopqrstuubyCG3zY1GIXMyxfivm.ClDiInHzxjiq");}
test "bcrypt: past 72 bytes nothing counts" { const x72 = "x" ** 72; const want = "$2b$04$abcdefghijklmnopqrstuubzadhGtS2zEF.gu0yd0opP6cVzb.e0i"; try expectHash(bcrypt, x72, .{ .salt = test_salt, .rounds = 4 }, want); try expectHash(bcrypt, x72 ++ "yyyyyyyy", .{ .salt = test_salt, .rounds = 4 }, want); try expectHash(bcrypt, x72 ++ "yyyyyyyy", .{ .salt = test_salt, .rounds = 4, .ident = .@"2" }, "$2$04$abcdefghijklmnopqrstuubzadhGtS2zEF.gu0yd0opP6cVzb.e0i"); // truncate_error refuses to hash it, and verify does not care. var buf: [128]u8 = undefined; var w: Io.Writer = .fixed(&buf); try testing.expectError(error.PasswordTooLong, bcrypt.hash(test_ctx, x72 ++ "y", .{ .salt = test_salt, .rounds = 4, .truncate_error = true }, &w)); try expectHash(bcrypt, x72, .{ .salt = test_salt, .rounds = 4, .truncate_error = true }, want); try testing.expect(try bcrypt.verify(test_ctx, x72 ++ "y", want));}
test "bcrypt: stray bits in the salt and checksum" { // A salt ending in `v` hashes as the `u` it repairs to. try expectHash(bcrypt, "test", .{ .salt = "abcdefghijklmnopqrstuv", .rounds = 4 }, "$2b$04$abcdefghijklmnopqrstuuoD8yw7MmybLKVooaTGGZAt3HXugv2.a"); // Both still verify, and only the `$2a$` one needs updating. const dirty = "$2b$04$abcdefghijklmnopqrstuvoD8yw7MmybLKVooaTGGZAt3HXugv2.a"; try testing.expect(try bcrypt.verify(test_ctx, "test", dirty)); try testing.expect(!try bcrypt.needsUpdate(dirty, .{})); try testing.expect(try bcrypt.needsUpdate("$2a$04$abcdefghijklmnopqrstuvoD8yw7MmybLKVooaTGGZAt3HXugv2.a", .{})); try testing.expect(!try bcrypt.needsUpdate("$2y$04$abcdefghijklmnopqrstuvoD8yw7MmybLKVooaTGGZAt3HXugv2.a", .{})); try testing.expect(try bcrypt.verify(test_ctx, "test", "$2b$04$abcdefghijklmnopqrstuuoD8yw7MmybLKVooaTGGZAt3HXugv2.b"));}
test "bcrypt: refusals" { const good = "$2b$04$abcdefghijklmnopqrstuuoD8yw7MmybLKVooaTGGZAt3HXugv2.a"; try testing.expectError(error.MalformedHash, bcrypt.verify(test_ctx, "test", "$2x$04$abcdefghijklmnopqrstuuoD8yw7MmybLKVooaTGGZAt3HXugv2.a")); try testing.expectError(error.MalformedHash, bcrypt.verify(test_ctx, "test", "$2b$4$abcdefghijklmnopqrstuuoD8yw7MmybLKVooaTGGZAt3HXugv2.a")); try testing.expectError(error.MalformedHash, bcrypt.verify(test_ctx, "test", "$2b$004$abcdefghijklmnopqrstuuoD8yw7MmybLKVooaTGGZAt3HXugv2.a")); try testing.expectError(error.MalformedHash, bcrypt.verify(test_ctx, "test", "$2b$03$abcdefghijklmnopqrstuuoD8yw7MmybLKVooaTGGZAt3HXugv2.a")); try testing.expectError(error.MalformedHash, bcrypt.verify(test_ctx, "test", "$2b$32$abcdefghijklmnopqrstuuoD8yw7MmybLKVooaTGGZAt3HXugv2.a")); try testing.expectError(error.MalformedHash, bcrypt.verify(test_ctx, "test", good ++ "$")); try testing.expectError(error.MalformedHash, bcrypt.verify(test_ctx, "test", good[0 .. good.len - 1])); try testing.expectError(error.MalformedHash, bcrypt.verify(test_ctx, "test", good ++ "a")); try testing.expectError(error.MalformedHash, bcrypt.verify(test_ctx, "test", good[0..20])); try testing.expectError(error.MalformedHash, bcrypt.verify(test_ctx, "test", good[0..29])); try testing.expectError(error.InvalidPassword, bcrypt.verify(test_ctx, "te\x00st", good)); try testing.expectError(error.PasswordTooLong, bcrypt.verify(test_ctx, "x" ** 4097, good)); try testing.expect(bcrypt.identify("$2x$")); try testing.expect(!bcrypt.identify("$2")); var buf: [128]u8 = undefined; var w: Io.Writer = .fixed(&buf); try testing.expectError(error.InvalidOptions, bcrypt.hash(test_ctx, "x", .{ .salt = "abcdefghijklmnopqrstu", .rounds = 4 }, &w)); try testing.expectError(error.InvalidOptions, bcrypt.hash(test_ctx, "x", .{ .rounds = 3 }, &w)); try testing.expectError(error.InvalidOptions, bcrypt.hash(test_ctx, "x", .{ .rounds = 32 }, &w)); try testing.expectError(error.InvalidPassword, bcrypt.hash(test_ctx, "te\x00st", .{ .salt = test_salt, .rounds = 4 }, &w));}
test "bcrypt: needsUpdate" { const h = "$2b$04$abcdefghijklmnopqrstuuoD8yw7MmybLKVooaTGGZAt3HXugv2.a"; try testing.expect(!try bcrypt.needsUpdate(h, .{})); // Not the ident, whatever the default: passlib 1.7.4 does not compare it. try testing.expect(!try bcrypt.needsUpdate("$2a$04$abcdefghijklmnopqrstuuoD8yw7MmybLKVooaTGGZAt3HXugv2.a", .{})); try testing.expect(!try bcrypt.needsUpdate(h, .{ .ident = .@"2a" })); try testing.expect(try bcrypt.needsUpdate(h, .{ .min_desired_rounds = 5 })); try testing.expect(try bcrypt.needsUpdate("$2b$05$abcdefghijklmnopqrstuuoD8yw7MmybLKVooaTGGZAt3HXugv2.a", .{ .max_desired_rounds = 4 })); // A configuration string is fine; a short `$2a$` one is not. try testing.expect(!try bcrypt.needsUpdate(h[0..29], .{})); try testing.expectError(error.MalformedHash, bcrypt.needsUpdate("$2a$04$abc", .{})); try testing.expectError(error.InvalidOptions, bcrypt.needsUpdate(h, .{ .min_desired_rounds = 3 }));}
test "bcrypt: round trip with a random salt" { var buf: [128]u8 = undefined; var w: Io.Writer = .fixed(&buf); try bcrypt.hash(test_ctx, "hunter2", .{ .rounds = 4 }, &w); const h = w.buffered(); try testing.expect(std.mem.startsWith(u8, h, "$2b$04$")); try testing.expect(std.mem.findScalar(u8, final_salt_chars, h[28]) != null); try testing.expect(try bcrypt.verify(test_ctx, "hunter2", h)); try testing.expect(!try bcrypt.verify(test_ctx, "hunter3", h)); try testing.expect(!bcrypt_sha256.identify(h));}
test "bcrypt_sha256: both versions" { // passlib 1.7.4: bcrypt_sha256.using(salt=..., rounds=4, ...).hash(...) try expectHash(bcrypt_sha256, "test", .{ .salt = test_salt, .rounds = 4 }, "$bcrypt-sha256$v=2,t=2b,r=4$abcdefghijklmnopqrstuu$PsgV5n0/sNFBnOIfthWD.fbPH8sdKgO"); try expectHash(bcrypt_sha256, "test", .{ .salt = test_salt, .rounds = 4, .version = 1, .ident = .@"2a" }, "$bcrypt-sha256$2a,4$abcdefghijklmnopqrstuu$fdXU7P/wnvIChVvrZHrZ7Ez6TIDlQwS"); try expectHash(bcrypt_sha256, "test", .{ .salt = test_salt, .rounds = 4, .version = 1 }, "$bcrypt-sha256$2b,4$abcdefghijklmnopqrstuu$fdXU7P/wnvIChVvrZHrZ7Ez6TIDlQwS"); // NULs and length are no problem once the password is a digest. try expectHash(bcrypt_sha256, "te\x00st", .{ .salt = test_salt, .rounds = 4 }, "$bcrypt-sha256$v=2,t=2b,r=4$abcdefghijklmnopqrstuu$04V4XWeSQqZgutWLCbaTBdFCpM5Hp5S"); try expectHash(bcrypt_sha256, "te\x00st", .{ .salt = test_salt, .rounds = 4, .version = 1 }, "$bcrypt-sha256$2b,4$abcdefghijklmnopqrstuu$ksm1e8OSAytqxGVijnR.sgphxYRKdOG"); try expectHash(bcrypt_sha256, "x" ** 100, .{ .salt = test_salt, .rounds = 4 }, "$bcrypt-sha256$v=2,t=2b,r=4$abcdefghijklmnopqrstuu$VN/UtE6EwSZ/CIGnzfQAPtA5sMkMG4u");}
test "bcrypt_sha256: the HMAC key is the repaired salt" { const dirty = "$bcrypt-sha256$v=2,t=2b,r=4$abcdefghijklmnopqrstuv$PsgV5n0/sNFBnOIfthWD.fbPH8sdKgO"; try testing.expect(try bcrypt_sha256.verify(test_ctx, "test", dirty)); try testing.expect(!try bcrypt_sha256.needsUpdate(dirty, .{})); // Python's `$` lets a final newline through. try testing.expect(try bcrypt_sha256.verify(test_ctx, "test", dirty ++ "\n")); // A leading zero in the version is fine; in the rounds it is not. try testing.expect(try bcrypt_sha256.verify(test_ctx, "test", "$bcrypt-sha256$v=002,t=2b,r=4$abcdefghijklmnopqrstuu$PsgV5n0/sNFBnOIfthWD.fbPH8sdKgO")); try testing.expectError(error.MalformedHash, bcrypt_sha256.verify(test_ctx, "test", "$bcrypt-sha256$v=2,t=2b,r=04$abcdefghijklmnopqrstuu$PsgV5n0/sNFBnOIfthWD.fbPH8sdKgO")); try testing.expectError(error.MalformedHash, bcrypt_sha256.verify(test_ctx, "test", "$bcrypt-sha256$t=2b,v=2,r=4$abcdefghijklmnopqrstuu$PsgV5n0/sNFBnOIfthWD.fbPH8sdKgO"));}
test "bcrypt_sha256: options and needsUpdate" { var buf: [128]u8 = undefined; var w: Io.Writer = .fixed(&buf); try testing.expectError(error.InvalidOptions, bcrypt_sha256.hash(test_ctx, "x", .{ .ident = .@"2a" }, &w)); try testing.expectError(error.InvalidOptions, bcrypt_sha256.hash(test_ctx, "x", .{ .version = 3 }, &w)); try testing.expectError(error.InvalidOptions, bcrypt_sha256.hash(test_ctx, "x", .{ .ident = .@"2y" }, &w)); const v1 = "$bcrypt-sha256$2b,4$abcdefghijklmnopqrstuu$fdXU7P/wnvIChVvrZHrZ7Ez6TIDlQwS"; const v2 = "$bcrypt-sha256$v=2,t=2b,r=4$abcdefghijklmnopqrstuu$PsgV5n0/sNFBnOIfthWD.fbPH8sdKgO"; try testing.expect(try bcrypt_sha256.needsUpdate(v1, .{})); try testing.expect(!try bcrypt_sha256.needsUpdate(v1, .{ .version = 1 })); try testing.expect(!try bcrypt_sha256.needsUpdate(v2, .{ .version = 1 })); try testing.expect(!try bcrypt_sha256.needsUpdate(v2, .{})); try testing.expect(try bcrypt_sha256.needsUpdate(v2, .{ .min_desired_rounds = 5 })); try testing.expect(!try bcrypt_sha256.needsUpdate("$bcrypt-sha256$v=2,t=2b,r=4$abcdefghijklmnopqrstuu", .{})); try testing.expectError(error.MalformedHash, bcrypt_sha256.verify(test_ctx, "x", "$bcrypt-sha256$v=2,t=2b,r=4$abcdefghijklmnopqrstuu"));}