// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The PBKDF2 formats: passlib's `passlib.handlers.pbkdf2`. //! //! PBKDF2 is the password-based key derivation function of PKCS #5 v2.0 //! (RFC 2898, now RFC 8018): an HMAC iterated a chosen number of times over //! the password and a salt. Every scheme here is PBKDF2 with a different way //! of writing the result down. //! //! * `pbkdf2_sha1`, `pbkdf2_sha256` and `pbkdf2_sha512` are passlib's own //! format, `$pbkdf2-sha256$$$`, with the salt and //! the full-length derived key in passlib's adapted base64. The SHA-1 one //! is `$pbkdf2$` for historical reasons. //! * `ldap_pbkdf2_sha1`, `ldap_pbkdf2_sha256` and `ldap_pbkdf2_sha512` are //! the same three behind an LDAP-style `{PBKDF2}`, `{PBKDF2-SHA256}` or //! `{PBKDF2-SHA512}` prefix, the form OpenLDAP's contributed `pw-pbkdf2` //! module reads and writes. //! * `cta_pbkdf2_sha1` is Cryptacular's `$p5k2$` format: the rounds in hex, //! and the salt and key in padded URL-safe base64. //! * `dlitz_pbkdf2_sha1` is the `crypt()` of Dwayne Litzenberger's `pbkdf2` //! module for Python. It shares Cryptacular's `$p5k2$` prefix but not its //! layout: the salt is a string of `./0-9A-Za-z`, the rounds field is left //! empty for the module's old default of 400, and the salt PBKDF2 is given //! is the whole `$p5k2$$` settings string rather than the //! salt alone. Because the prefixes collide, each of the two identifies the //! other's hashes, as in passlib. //! * `atlassian_pbkdf2_sha1` is the `{PKCS5S2}` format of Atlassian's Crowd, //! Jira and Confluence: a 16-byte salt and a 32-byte key, base64 together, //! at a fixed 10000 rounds. //! * `grub_pbkdf2_sha512` is what GRUB 2's `grub-mkpasswd-pbkdf2` writes for //! `password_pbkdf2` in `grub.cfg`: rounds, salt and key separated by dots, //! the latter two in upper-case hex. //! //! **PBKDF2 is still acceptable, but it is the weakest modern choice.** It //! costs time and no memory, so a GPU runs many guesses in parallel, and //! only its round count stands in the way. The HMAC-SHA-256 and SHA-512 //! variants with a high round count remain defensible where only //! FIPS-approved primitives are allowed; OWASP's password storage cheat sheet //! asked for 600,000 rounds of PBKDF2-HMAC-SHA256 as of 2023, twenty times //! passlib's default. Otherwise prefer Argon2 or scrypt. The Atlassian format //! cannot raise its round count at all, and Cryptacular's and Litzenberger's //! are here only to read hashes already stored in them. const std = @import("std"); const Io = std.Io; const Hmac = std.crypto.auth.hmac.Hmac; const Sha1 = std.crypto.hash.Sha1; const Sha256 = std.crypto.hash.sha2.Sha256; const Sha512 = std.crypto.hash.sha2.Sha512; const testing = std.testing; const encoding = @import("../encoding.zig"); const ab64 = encoding.ab64; const handler = @import("../handler.zig"); const Context = handler.Context; const Error = handler.Error; /// The largest salt passlib accepts for any of these schemes, in bytes (in /// characters for `dlitz_pbkdf2_sha1`). PBKDF2 itself has no limit; passlib /// sets one as a sanity check. pub const max_salt_size = 1024; /// PBKDF2-HMAC-`Hash` of `password` and `salt`, filling `out`. fn derive(comptime Hash: type, out: []u8, password: []const u8, salt: []const u8, rounds: u32) Error!void { try std.crypto.pwhash.pbkdf2(out, password, salt, rounds, Hmac(Hash)); } /// The salt `options` asks for: `salt` if set, which may be at most /// `max_salt_size` bytes, or else `salt_size` random bytes in `buf`. fn rawSalt(io: Io, buf: *[max_salt_size]u8, salt: ?[]const u8, salt_size: u16) Error![]const u8 { if (salt) |s| { if (s.len > max_salt_size) return error.InvalidOptions; return s; } if (salt_size > max_salt_size) return error.InvalidOptions; return handler.randomBytes(io, buf[0..salt_size]); } /// The three fields of passlib's `parse_mc3` layout, /// `ident` + rounds + `sep` + salt + `sep` + checksum. const Mc3 = struct { rounds: []const u8, salt: []const u8, checksum: []const u8 }; /// Splits `h` into its three fields. A settings string, with the checksum /// missing or empty, is refused: passlib parses one, but will not verify /// against it. fn splitMc3(h: []const u8, comptime ident: []const u8, sep: u8) Error!Mc3 { if (!std.mem.startsWith(u8, h, ident)) return error.MalformedHash; const fields = try handler.splitExact(3, h[ident.len..], sep); if (fields[2].len == 0) return error.MalformedHash; return .{ .rounds = fields[0], .salt = fields[1], .checksum = fields[2] }; } /// A rounds field in `base` 10 or 16, as `parse_mc3` reads it: no leading /// zero, and at least 1. An empty field is `default` if there is one and /// malformed if not. passlib's `int()` also tolerates a sign, underscores and /// surrounding whitespace; nothing that writes these formats produces them, /// and they are refused here. fn parseRounds(s: []const u8, comptime base: u8, default: ?u32) Error!u32 { if (s.len == 0) return default orelse error.MalformedHash; if (s.len > 1 and s[0] == '0') return error.MalformedHash; for (s) |c| { const ok = switch (base) { 10 => std.ascii.isDigit(c), 16 => std.ascii.isHex(c), else => comptime unreachable, }; if (!ok) return error.MalformedHash; } const rounds = std.fmt.parseInt(u32, s, base) catch return error.MalformedHash; if (rounds < 1) return error.MalformedHash; return rounds; } /// Decodes an adapted-base64 field of exactly `N` bytes. fn ab64Exact(comptime N: usize, s: []const u8) Error![N]u8 { if (try ab64.decodedLen(s.len) != N) return error.MalformedHash; var out: [N]u8 = undefined; _ = try ab64.decode(&out, s); return out; } /// A salt held by value, since a parsed hash outlives nothing it points to. const Salt = struct { buf: [max_salt_size]u8 = undefined, len: usize = 0, fn slice(s: *const Salt) []const u8 { return s.buf[0..s.len]; } }; /// passlib's `pbkdf2_` family: `ident` + rounds + `$` + adapted /// base64 salt + `$` + adapted base64 key, the key as long as `Hash`'s /// digest. pub fn Pbkdf2( comptime scheme_name: []const u8, comptime Hash: type, comptime ident: []const u8, comptime default_rounds: u32, ) type { return struct { pub const name = scheme_name; const checksum_len = Hash.digest_length; pub const Options = struct { /// The salt, as raw bytes, at most `max_salt_size` of them. Null, /// the default, draws `salt_size` random bytes. salt: ?[]const u8 = null, /// The length of a random salt in bytes, at most /// `max_salt_size`. salt_size: u16 = 16, /// PBKDF2 iterations, at least 1. rounds: u32 = default_rounds, /// `needsUpdate` is true for a hash with fewer rounds than this. min_desired_rounds: ?u32 = null, /// `needsUpdate` is true for a hash with more rounds than this. max_desired_rounds: ?u32 = null, }; pub fn identify(h: []const u8) bool { return std.mem.startsWith(u8, h, ident); } const Parsed = struct { rounds: u32, salt: Salt, checksum: [checksum_len]u8 }; fn parse(h: []const u8) Error!Parsed { const f = try splitMc3(h, ident, '$'); var p: Parsed = .{ .rounds = try parseRounds(f.rounds, 10, null), .salt = .{}, .checksum = undefined }; const salt_len = try ab64.decodedLen(f.salt.len); if (salt_len > max_salt_size) return error.MalformedHash; p.salt.len = (try ab64.decode(&p.salt.buf, f.salt)).len; p.checksum = try ab64Exact(checksum_len, f.checksum); return p; } pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { try handler.checkPasswordLen(password); if (options.rounds < 1) return error.InvalidOptions; var salt_buf: [max_salt_size]u8 = undefined; const salt = try rawSalt(ctx.io, &salt_buf, options.salt, options.salt_size); var checksum: [checksum_len]u8 = undefined; try derive(Hash, &checksum, password, salt, options.rounds); var salt_enc: [ab64.encodedLen(max_salt_size)]u8 = undefined; var checksum_enc: [ab64.encodedLen(checksum_len)]u8 = undefined; try w.print("{s}{d}${s}${s}", .{ ident, options.rounds, ab64.encode(&salt_enc, salt), ab64.encode(&checksum_enc, &checksum), }); } pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { _ = ctx; try handler.checkPasswordLen(password); const p = try parse(h); var checksum: [checksum_len]u8 = undefined; try derive(Hash, &checksum, password, p.salt.slice(), p.rounds); return handler.eql(&p.checksum, &checksum); } /// True when the hash's rounds fall outside `min_desired_rounds` and /// `max_desired_rounds`. The salt size is not compared, as passlib /// does not compare it. pub fn needsUpdate(h: []const u8, options: Options) Error!bool { const p = try parse(h); return handler.roundsOutside(p.rounds, options.min_desired_rounds, options.max_desired_rounds); } }; } pub const pbkdf2_sha1 = Pbkdf2("pbkdf2_sha1", Sha1, "$pbkdf2$", 131000); pub const pbkdf2_sha256 = Pbkdf2("pbkdf2_sha256", Sha256, "$pbkdf2-sha256$", 29000); pub const pbkdf2_sha512 = Pbkdf2("pbkdf2_sha512", Sha512, "$pbkdf2-sha512$", 25000); pub const ldap_pbkdf2_sha1 = handler.PrefixWrapper("ldap_pbkdf2_sha1", pbkdf2_sha1, "{PBKDF2}", "$pbkdf2$"); pub const ldap_pbkdf2_sha256 = handler.PrefixWrapper("ldap_pbkdf2_sha256", pbkdf2_sha256, "{PBKDF2-SHA256}", "$pbkdf2-sha256$"); pub const ldap_pbkdf2_sha512 = handler.PrefixWrapper("ldap_pbkdf2_sha512", pbkdf2_sha512, "{PBKDF2-SHA512}", "$pbkdf2-sha512$"); /// Cryptacular's `$p5k2$` + hex rounds + `$` + salt + `$` + key, the salt /// and the 20-byte PBKDF2-HMAC-SHA1 key in padded base64 with `-_` for `+/`. pub const cta_pbkdf2_sha1 = struct { pub const name = "cta_pbkdf2_sha1"; const ident = "$p5k2$"; const checksum_len = Sha1.digest_length; pub const Options = struct { /// The salt, as raw bytes, at most `max_salt_size` of them. Null, the /// default, draws `salt_size` random bytes. salt: ?[]const u8 = null, /// The length of a random salt in bytes, at most `max_salt_size`. salt_size: u16 = 16, /// PBKDF2 iterations, at least 1. passlib's default is /// `pbkdf2_sha1`'s. rounds: u32 = 131000, min_desired_rounds: ?u32 = null, max_desired_rounds: ?u32 = null, }; /// Any `$p5k2$` string, `dlitz_pbkdf2_sha1`'s included, as passlib has /// it. pub fn identify(h: []const u8) bool { return std.mem.startsWith(u8, h, ident); } /// Base64 of `src` with `-_` for `+/`, padded. fn encode(dst: []u8, src: []const u8) []u8 { const out = encoding.std64.encode(dst, src); for (out) |*c| c.* = switch (c.*) { '+' => '-', '/' => '_', else => c.*, }; var len = out.len; while (len % 4 != 0) : (len += 1) dst[len] = '='; return dst[0..len]; } fn encodedLen(n: usize) usize { return (n + 2) / 3 * 4; } /// Decodes padded base64 with `-_` for `+/`. Python's `b64decode` with /// those altchars translates them and leaves `+/` meaning what they /// always mean, so both spellings are accepted. It also skips characters /// outside the alphabet rather than refusing them, which this does not /// reproduce: such a string is malformed here. fn decode(dst: []u8, src: []const u8) Error![]u8 { if (src.len % 4 != 0) return error.MalformedHash; var body = src; var pad: usize = 0; while (pad < 2 and body.len > 0 and body[body.len - 1] == '=') : (pad += 1) body = body[0 .. body.len - 1]; var tmp: [encodedLen(max_salt_size)]u8 = undefined; if (body.len > tmp.len) return error.MalformedHash; for (body, tmp[0..body.len]) |c, *t| t.* = switch (c) { '-' => '+', '_' => '/', else => c, }; if (try encoding.std64.decodedLen(body.len) > dst.len) return error.MalformedHash; return encoding.std64.decode(dst, tmp[0..body.len]); } const Parsed = struct { rounds: u32, salt: Salt, checksum: [checksum_len]u8 }; fn parse(h: []const u8) Error!Parsed { const f = try splitMc3(h, ident, '$'); var p: Parsed = .{ .rounds = try parseRounds(f.rounds, 16, null), .salt = .{}, .checksum = undefined }; p.salt.len = (try decode(&p.salt.buf, f.salt)).len; var checksum: [checksum_len + 2]u8 = undefined; const got = try decode(&checksum, f.checksum); if (got.len != checksum_len) return error.MalformedHash; p.checksum = got[0..checksum_len].*; return p; } pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { try handler.checkPasswordLen(password); if (options.rounds < 1) return error.InvalidOptions; var salt_buf: [max_salt_size]u8 = undefined; const salt = try rawSalt(ctx.io, &salt_buf, options.salt, options.salt_size); var checksum: [checksum_len]u8 = undefined; try derive(Sha1, &checksum, password, salt, options.rounds); var salt_enc: [encodedLen(max_salt_size)]u8 = undefined; var checksum_enc: [encodedLen(checksum_len)]u8 = undefined; try w.print("{s}{x}${s}${s}", .{ ident, options.rounds, encode(&salt_enc, salt), encode(&checksum_enc, &checksum) }); } pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { _ = ctx; try handler.checkPasswordLen(password); const p = try parse(h); var checksum: [checksum_len]u8 = undefined; try derive(Sha1, &checksum, password, p.salt.slice(), p.rounds); return handler.eql(&p.checksum, &checksum); } /// True when the hash's rounds fall outside the desired bounds. pub fn needsUpdate(h: []const u8, options: Options) Error!bool { const p = try parse(h); return handler.roundsOutside(p.rounds, options.min_desired_rounds, options.max_desired_rounds); } }; /// Dwayne Litzenberger's `$p5k2$` + hex rounds + `$` + salt + `$` + key. /// /// The rounds field is empty when the rounds are 400. The key is 24 bytes of /// PBKDF2-HMAC-SHA1, in adapted base64, and the salt PBKDF2 is given is the /// settings string `$p5k2$$` as this scheme writes it, which /// is not always as the hash spells it: `$p5k2$C$...` and `$p5k2$190$...` /// are salted as `$p5k2$c$...` and `$p5k2$$...`, as passlib salts them. pub const dlitz_pbkdf2_sha1 = struct { pub const name = "dlitz_pbkdf2_sha1"; const ident = "$p5k2$"; const key_len = 24; const checksum_len = ab64.encodedLen(key_len); /// The rounds an empty rounds field stands for. const implicit_rounds = 400; pub const Options = struct { /// The salt, up to `max_salt_size` characters of `./0-9A-Za-z`. Null, /// the default, draws `salt_size` random characters. salt: ?[]const u8 = null, /// The length of a random salt, at most `max_salt_size`. salt_size: u16 = 16, /// PBKDF2 iterations, at least 1. passlib's default is /// `pbkdf2_sha1`'s, although the extra block this scheme derives /// makes each round cost twice as much. rounds: u32 = 131000, min_desired_rounds: ?u32 = null, max_desired_rounds: ?u32 = null, }; /// Any `$p5k2$` string, `cta_pbkdf2_sha1`'s included, as passlib has it. pub fn identify(h: []const u8) bool { return std.mem.startsWith(u8, h, ident); } const Parsed = struct { rounds: u32, salt: []const u8, checksum: []const u8 }; /// The checksum is not checked for length or alphabet, as passlib does /// not check it: one that could never match simply fails to verify. fn parse(h: []const u8) Error!Parsed { const f = try splitMc3(h, ident, '$'); const rounds = try parseRounds(f.rounds, 16, implicit_rounds); if (f.salt.len > max_salt_size or !encoding.h64.isValid(f.salt)) return error.MalformedHash; return .{ .rounds = rounds, .salt = f.salt, .checksum = f.checksum }; } fn compute(password: []const u8, salt: []const u8, rounds: u32, out: *[checksum_len]u8) Error!void { var config_buf: [ident.len + 8 + 1 + max_salt_size]u8 = undefined; var cw: Io.Writer = .fixed(&config_buf); cw.writeAll(ident) catch unreachable; if (rounds != implicit_rounds) cw.print("{x}", .{rounds}) catch unreachable; cw.print("${s}", .{salt}) catch unreachable; var key: [key_len]u8 = undefined; try derive(Sha1, &key, password, cw.buffered(), rounds); _ = ab64.encode(out, &key); } pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { try handler.checkPasswordLen(password); if (options.rounds < 1) return error.InvalidOptions; var salt_buf: [max_salt_size]u8 = undefined; const salt = if (options.salt) |s| blk: { if (s.len > max_salt_size or !encoding.h64.isValid(s)) return error.InvalidOptions; break :blk s; } else blk: { if (options.salt_size > max_salt_size) return error.InvalidOptions; break :blk try handler.randomChars(ctx.io, salt_buf[0..options.salt_size], encoding.hash64_chars); }; var checksum: [checksum_len]u8 = undefined; try compute(password, salt, options.rounds, &checksum); try w.writeAll(ident); if (options.rounds != implicit_rounds) try w.print("{x}", .{options.rounds}); try w.print("${s}${s}", .{ salt, &checksum }); } pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { _ = ctx; try handler.checkPasswordLen(password); const p = try parse(h); var checksum: [checksum_len]u8 = undefined; try compute(password, p.salt, p.rounds, &checksum); return handler.eql(p.checksum, &checksum); } /// True when the hash's rounds fall outside the desired bounds. pub fn needsUpdate(h: []const u8, options: Options) Error!bool { const p = try parse(h); return handler.roundsOutside(p.rounds, options.min_desired_rounds, options.max_desired_rounds); } }; /// Atlassian's `{PKCS5S2}` + padded base64 of a 16-byte salt followed by a /// 32-byte PBKDF2-HMAC-SHA1 key, at a fixed 10000 rounds. pub const atlassian_pbkdf2_sha1 = struct { pub const name = "atlassian_pbkdf2_sha1"; const ident = "{PKCS5S2}"; const salt_len = 16; const key_len = 32; const rounds = 10000; pub const Options = struct { /// The salt, exactly 16 raw bytes. Null, the default, draws a random /// one. salt: ?[]const u8 = null, }; pub fn identify(h: []const u8) bool { return std.mem.startsWith(u8, h, ident); } fn parse(h: []const u8) Error![salt_len + key_len]u8 { if (!identify(h)) return error.MalformedHash; const data = h[ident.len..]; if (try encoding.b64.decodedLen(data) != salt_len + key_len) return error.MalformedHash; var out: [salt_len + key_len]u8 = undefined; _ = try encoding.b64.decode(&out, data); return out; } pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { try handler.checkPasswordLen(password); var data: [salt_len + key_len]u8 = undefined; if (options.salt) |s| { if (s.len != salt_len) return error.InvalidOptions; @memcpy(data[0..salt_len], s); } else { _ = try handler.randomBytes(ctx.io, data[0..salt_len]); } try derive(Sha1, data[salt_len..], password, data[0..salt_len], rounds); var enc: [encoding.b64.encodedLen(data.len)]u8 = undefined; try w.print("{s}{s}", .{ ident, encoding.b64.encode(&enc, &data) }); } pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { _ = ctx; try handler.checkPasswordLen(password); const data = try parse(h); var key: [key_len]u8 = undefined; try derive(Sha1, &key, password, data[0..salt_len], rounds); return handler.eql(data[salt_len..], &key); } /// Always false for a hash that parses: the rounds are fixed and the /// salt is always 16 bytes. pub fn needsUpdate(h: []const u8, options: Options) Error!bool { _ = options; _ = try parse(h); return false; } }; /// GRUB 2's `grub.pbkdf2.sha512.` + rounds + `.` + salt + `.` + key, the /// salt and the 64-byte PBKDF2-HMAC-SHA512 key in hex. passlib writes them /// in upper case and reads either. pub const grub_pbkdf2_sha512 = struct { pub const name = "grub_pbkdf2_sha512"; const ident = "grub.pbkdf2.sha512."; const checksum_len = Sha512.digest_length; pub const Options = struct { /// The salt, as raw bytes, at most `max_salt_size` of them. Null, the /// default, draws `salt_size` random bytes. salt: ?[]const u8 = null, /// The length of a random salt in bytes, at most `max_salt_size`. salt_size: u16 = 64, /// PBKDF2 iterations, at least 1. passlib's default is /// `pbkdf2_sha512`'s. rounds: u32 = 25000, min_desired_rounds: ?u32 = null, max_desired_rounds: ?u32 = null, }; pub fn identify(h: []const u8) bool { return std.mem.startsWith(u8, h, ident); } const Parsed = struct { rounds: u32, salt: Salt, checksum: [checksum_len]u8 }; fn parse(h: []const u8) Error!Parsed { const f = try splitMc3(h, ident, '.'); var p: Parsed = .{ .rounds = try parseRounds(f.rounds, 10, null), .salt = .{}, .checksum = undefined }; if (f.salt.len > 2 * max_salt_size) return error.MalformedHash; p.salt.len = (try encoding.hexDecode(&p.salt.buf, f.salt)).len; if (f.checksum.len != 2 * checksum_len) return error.MalformedHash; _ = try encoding.hexDecode(&p.checksum, f.checksum); return p; } pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { try handler.checkPasswordLen(password); if (options.rounds < 1) return error.InvalidOptions; var salt_buf: [max_salt_size]u8 = undefined; const salt = try rawSalt(ctx.io, &salt_buf, options.salt, options.salt_size); var checksum: [checksum_len]u8 = undefined; try derive(Sha512, &checksum, password, salt, options.rounds); var salt_hex: [2 * max_salt_size]u8 = undefined; var checksum_hex: [2 * checksum_len]u8 = undefined; try w.print("{s}{d}.{s}.{s}", .{ ident, options.rounds, encoding.hexUpper(&salt_hex, salt), encoding.hexUpper(&checksum_hex, &checksum), }); } pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { _ = ctx; try handler.checkPasswordLen(password); const p = try parse(h); var checksum: [checksum_len]u8 = undefined; try derive(Sha512, &checksum, password, p.salt.slice(), p.rounds); return handler.eql(&p.checksum, &checksum); } /// True when the hash's rounds fall outside the desired bounds. pub fn needsUpdate(h: []const u8, options: Options) Error!bool { const p = try parse(h); return handler.roundsOutside(p.rounds, options.min_desired_rounds, options.max_desired_rounds); } }; /// The schemes this module defines, in the order `registry.identify` tries /// them. pub const schemes = .{ pbkdf2_sha1, pbkdf2_sha256, pbkdf2_sha512, cta_pbkdf2_sha1, dlitz_pbkdf2_sha1, atlassian_pbkdf2_sha1, grub_pbkdf2_sha512, ldap_pbkdf2_sha1, ldap_pbkdf2_sha256, ldap_pbkdf2_sha512, }; comptime { for (schemes) |S| handler.check(S); } const test_ctx: Context = .{ .io = testing.io, .gpa = testing.allocator }; fn expectHash(comptime S: type, password: []const u8, options: S.Options, expected: []const u8) !void { var buf: [512]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(S.identify(w.buffered())); try testing.expect(try S.verify(test_ctx, password, w.buffered())); try testing.expect(!try S.verify(test_ctx, "wrong", w.buffered())); } test "fixed salts reproduce passlib" { // passlib 1.7.4: .using(salt=..., rounds=...).hash("test"). try expectHash(pbkdf2_sha1, "test", .{ .salt = "salt1234", .rounds = 10 }, "$pbkdf2$10$c2FsdDEyMzQ$tOQeL5SsAyepoQLajkkwFBipr3c"); try expectHash(pbkdf2_sha256, "test", .{ .salt = "salt1234", .rounds = 10 }, "$pbkdf2-sha256$10$c2FsdDEyMzQ$9huGt4KsU6tBnukA5iPokgiK73DWYG3PBP4f6eekcTQ"); try expectHash(pbkdf2_sha512, "test", .{ .salt = "salt1234", .rounds = 10 }, "$pbkdf2-sha512$10$c2FsdDEyMzQ$4gx05NSMXqhyZjyxd5y135bdmCkPBXsVIeeN.YK1fX/FuW/wxPLJO5O4/JjjWT7lnFX/fKgC99UlNwQjJLDI2A"); try expectHash(pbkdf2_sha256, "", .{ .salt = "", .rounds = 1 }, "$pbkdf2-sha256$1$$984LZT0tcqQQjPWr6RL/3Xd2Ftu7J6cOggTzri0Pb60"); try expectHash(ldap_pbkdf2_sha1, "test", .{ .salt = "salt1234", .rounds = 10 }, "{PBKDF2}10$c2FsdDEyMzQ$tOQeL5SsAyepoQLajkkwFBipr3c"); try expectHash(ldap_pbkdf2_sha256, "test", .{ .salt = "salt1234", .rounds = 10 }, "{PBKDF2-SHA256}10$c2FsdDEyMzQ$9huGt4KsU6tBnukA5iPokgiK73DWYG3PBP4f6eekcTQ"); try expectHash(ldap_pbkdf2_sha512, "test", .{ .salt = "salt1234", .rounds = 10 }, "{PBKDF2-SHA512}10$c2FsdDEyMzQ$4gx05NSMXqhyZjyxd5y135bdmCkPBXsVIeeN.YK1fX/FuW/wxPLJO5O4/JjjWT7lnFX/fKgC99UlNwQjJLDI2A"); try expectHash(cta_pbkdf2_sha1, "test", .{ .salt = "\xfb\xff\xbe\x00\x01", .rounds = 10 }, "$p5k2$a$-_--AAE=$7JjJNB_wPgIlVofJPbL5haQbAIA="); try expectHash(cta_pbkdf2_sha1, "test", .{ .salt = "salt1234", .rounds = 4000 }, "$p5k2$fa0$c2FsdDEyMzQ=$8RXs-h4cMS6QDuv_yfO8_31p2uU="); try expectHash(dlitz_pbkdf2_sha1, "test", .{ .salt = "abcdefgh", .rounds = 400 }, "$p5k2$$abcdefgh$L8MZCZzClh0bqBWcllYPSIxVg1IbUrwT"); try expectHash(dlitz_pbkdf2_sha1, "test", .{ .salt = "abcdefgh", .rounds = 12 }, "$p5k2$c$abcdefgh$qJXOuAnS7ay4zJZ1bVxfCSOJNFVzpDhe"); try expectHash(atlassian_pbkdf2_sha1, "test", .{ .salt = "0123456789abcdef" }, "{PKCS5S2}MDEyMzQ1Njc4OWFiY2RlZmFCgNHKg8HD2Br5dKJwH5IkVx+tn42+s8AtEAcm8ZBX"); try expectHash(grub_pbkdf2_sha512, "test", .{ .salt = "\x01\xabxyz", .rounds = 10 }, "grub.pbkdf2.sha512.10.01AB78797A.A4279A8B819BC9FA9E1D21884CDF63C515246BC0BCF6B74EBF9EB794ED6917BBBC4CD49866A00C2051F59FEEB723DAD68ACF8E00CC4548F47924CA0FE6AEB11E"); } test "alternative spellings passlib also reads" { // Cryptacular's hash with the standard `+/` in place of `-_`. try testing.expect(try cta_pbkdf2_sha1.verify(test_ctx, "test", "$p5k2$a$+/++AAE=$7JjJNB/wPgIlVofJPbL5haQbAIA=")); // Upper-case hex rounds; the salt PBKDF2 sees is re-rendered in lower // case, so this is the same hash as `$p5k2$c$...`. try testing.expect(try dlitz_pbkdf2_sha1.verify(test_ctx, "test", "$p5k2$C$abcdefgh$qJXOuAnS7ay4zJZ1bVxfCSOJNFVzpDhe")); // 400 written out is salted as the empty rounds field. try testing.expect(try dlitz_pbkdf2_sha1.verify(test_ctx, "test", "$p5k2$190$abcdefgh$L8MZCZzClh0bqBWcllYPSIxVg1IbUrwT")); // Lower-case hex in GRUB's format. try testing.expect(try grub_pbkdf2_sha512.verify(test_ctx, "test", "grub.pbkdf2.sha512.10.01ab78797a.a4279a8b819bc9fa9e1d21884cdf63c515246bc0bcf6b74ebf9eb794ed6917bbbc4cd49866a00c2051f59feeb723dad68acf8e00cc4548f47924ca0fe6aeb11e")); } test "round trip with a random salt" { var buf: [512]u8 = undefined; inline for (.{ pbkdf2_sha256, cta_pbkdf2_sha1, dlitz_pbkdf2_sha1, grub_pbkdf2_sha512, ldap_pbkdf2_sha512 }) |S| { var w: Io.Writer = .fixed(&buf); try S.hash(test_ctx, "hunter2", .{ .rounds = 5 }, &w); try testing.expect(try S.verify(test_ctx, "hunter2", w.buffered())); try testing.expect(!try S.verify(test_ctx, "hunter3", w.buffered())); } var w: Io.Writer = .fixed(&buf); try atlassian_pbkdf2_sha1.hash(test_ctx, "hunter2", .{}, &w); try testing.expect(try atlassian_pbkdf2_sha1.verify(test_ctx, "hunter2", w.buffered())); } test "refusals" { const good = "$pbkdf2$10$c2FsdDEyMzQ$tOQeL5SsAyepoQLajkkwFBipr3c"; try testing.expect(try pbkdf2_sha1.verify(test_ctx, "test", good)); inline for (.{ "$pbkdf2$10$c2FsdDEyMzQ", // a settings string "$pbkdf2$10$c2FsdDEyMzQ$", "$pbkdf2$010$c2FsdDEyMzQ$tOQeL5SsAyepoQLajkkwFBipr3c", "$pbkdf2$0$c2FsdDEyMzQ$tOQeL5SsAyepoQLajkkwFBipr3c", "$pbkdf2$$c2FsdDEyMzQ$tOQeL5SsAyepoQLajkkwFBipr3c", "$pbkdf2$4294967296$c2FsdDEyMzQ$tOQeL5SsAyepoQLajkkwFBipr3c", "$pbkdf2$10$c2FsdDEyMzQ$tOQeL5SsAyepoQLajkkwFBipr3", "$pbkdf2$10$c2FsdDEyMzQ$tOQeL5SsAyepoQLajkkwFBipr3c$", "$pbkdf2$10$c2Fsd!EyMzQ$tOQeL5SsAyepoQLajkkwFBipr3c", }) |h| try testing.expectError(error.MalformedHash, pbkdf2_sha1.verify(test_ctx, "test", h)); try testing.expectError(error.MalformedHash, cta_pbkdf2_sha1.verify(test_ctx, "test", "$p5k2$a$-_--AAE$7JjJNB_wPgIlVofJPbL5haQbAIA=")); try testing.expectError(error.MalformedHash, dlitz_pbkdf2_sha1.verify(test_ctx, "test", "$p5k2$c$abc!efgh$qJXOuAnS7ay4zJZ1bVxfCSOJNFVzpDhe")); try testing.expectError(error.MalformedHash, dlitz_pbkdf2_sha1.verify(test_ctx, "test", "$p5k2$0$abcdefgh$qJXOuAnS7ay4zJZ1bVxfCSOJNFVzpDhe")); try testing.expectError(error.MalformedHash, atlassian_pbkdf2_sha1.verify(test_ctx, "test", "{PKCS5S2}MDEyMzQ1Njc4OWFiY2RlZmFCgNHKg8HD2Br5dKJwH5IkVx+tn42+s8AtEAcm8Z")); try testing.expectError(error.MalformedHash, grub_pbkdf2_sha512.verify(test_ctx, "test", "grub.pbkdf2.sha512.10.01AB78797.A4279A8B819BC9FA9E1D21884CDF63C515246BC0BCF6B74EBF9EB794ED6917BBBC4CD49866A00C2051F59FEEB723DAD68ACF8E00CC4548F47924CA0FE6AEB11E")); try testing.expectError(error.MalformedHash, ldap_pbkdf2_sha1.verify(test_ctx, "test", good)); var buf: [64]u8 = undefined; var w: Io.Writer = .fixed(&buf); try testing.expectError(error.InvalidOptions, pbkdf2_sha1.hash(test_ctx, "x", .{ .rounds = 0 }, &w)); try testing.expectError(error.InvalidOptions, pbkdf2_sha1.hash(test_ctx, "x", .{ .salt_size = 1025 }, &w)); try testing.expectError(error.InvalidOptions, dlitz_pbkdf2_sha1.hash(test_ctx, "x", .{ .salt = "bad!" }, &w)); try testing.expectError(error.InvalidOptions, atlassian_pbkdf2_sha1.hash(test_ctx, "x", .{ .salt = "short" }, &w)); const long = [_]u8{'a'} ** (handler.max_password_len + 1); try testing.expectError(error.PasswordTooLong, pbkdf2_sha1.verify(test_ctx, &long, good)); } test "the two $p5k2$ schemes identify each other's hashes" { try testing.expect(cta_pbkdf2_sha1.identify("$p5k2$c$abcdefgh$qJXOuAnS7ay4zJZ1bVxfCSOJNFVzpDhe")); try testing.expect(dlitz_pbkdf2_sha1.identify("$p5k2$a$-_--AAE=$7JjJNB_wPgIlVofJPbL5haQbAIA=")); } test "needsUpdate compares rounds" { const h = "$pbkdf2-sha256$10$c2FsdDEyMzQ$9huGt4KsU6tBnukA5iPokgiK73DWYG3PBP4f6eekcTQ"; try testing.expect(!try pbkdf2_sha256.needsUpdate(h, .{})); try testing.expect(try pbkdf2_sha256.needsUpdate(h, .{ .min_desired_rounds = 11 })); try testing.expect(!try pbkdf2_sha256.needsUpdate(h, .{ .min_desired_rounds = 10 })); try testing.expect(try pbkdf2_sha256.needsUpdate(h, .{ .max_desired_rounds = 9 })); try testing.expect(try ldap_pbkdf2_sha256.needsUpdate("{PBKDF2-SHA256}10$c2FsdDEyMzQ$9huGt4KsU6tBnukA5iPokgiK73DWYG3PBP4f6eekcTQ", .{ .min_desired_rounds = 100 })); try testing.expect(try dlitz_pbkdf2_sha1.needsUpdate("$p5k2$$abcdefgh$L8MZCZzClh0bqBWcllYPSIxVg1IbUrwT", .{ .min_desired_rounds = 401 })); try testing.expect(!try atlassian_pbkdf2_sha1.needsUpdate("{PKCS5S2}MDEyMzQ1Njc4OWFiY2RlZmFCgNHKg8HD2Br5dKJwH5IkVx+tn42+s8AtEAcm8ZBX", .{})); try testing.expectError(error.MalformedHash, pbkdf2_sha256.needsUpdate("$pbkdf2-sha256$10$c2FsdDEyMzQ", .{})); }