// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! SHA256-Crypt and SHA512-Crypt: passlib's `passlib.handlers.sha2_crypt`. //! //! Ulrich Drepper's `$5$` and `$6$` formats, 2007, written for glibc as the //! successors to MD5-crypt and now the default password hash of most Linux //! distributions. The structure is MD5-crypt's, rebuilt on SHA-256 or //! SHA-512: a salt of up to sixteen characters, and a configurable number of //! rounds, from 1000 to 999,999,999, each mixing the password, the salt and //! the previous digest in an order that depends on the round number. //! //! A hash is `$5$` or `$6$`, then optionally `rounds=N$`, then the salt, `$` //! and the checksum: 43 characters for SHA-256 and 86 for SHA-512. The //! specification makes 5000 rounds the default and lets the `rounds=` field //! be left out when it is 5000; a hash written with 5000 rounds leaves it //! out, as passlib's does. const std = @import("std"); const Io = std.Io; const sha2 = std.crypto.hash.sha2; const testing = std.testing; const encoding = @import("../encoding.zig"); const h64 = encoding.h64; const handler = @import("../handler.zig"); const Context = handler.Context; const Error = handler.Error; pub const max_salt_len = 16; pub const min_rounds = 1000; pub const max_rounds = 999_999_999; /// The round count the specification assumes when a hash has no `rounds=` /// field, and the one count a hash is written without the field for. pub const implicit_rounds = 5000; /// The order SHA256-Crypt encodes its digest's bytes in. const transpose_256 = [_]u8{ 20, 10, 0, 11, 1, 21, 2, 22, 12, 23, 13, 3, 14, 4, 24, 5, 25, 15, 26, 16, 6, 17, 7, 27, 8, 28, 18, 29, 19, 9, 30, 31, }; /// The order SHA512-Crypt encodes its digest's bytes in. const transpose_512 = [_]u8{ 42, 21, 0, 1, 43, 22, 23, 2, 44, 45, 24, 3, 4, 46, 25, 26, 5, 47, 48, 27, 6, 7, 49, 28, 29, 8, 50, 51, 30, 9, 10, 52, 31, 32, 11, 53, 54, 33, 12, 13, 55, 34, 35, 14, 56, 57, 36, 15, 16, 58, 37, 38, 17, 59, 60, 39, 18, 19, 61, 40, 41, 20, 62, 63, }; /// The checksum for `password`, `salt` and `rounds` under hash `H`, as /// Drepper's specification describes it. `password` is at most /// `handler.max_password_len` long and `salt` at most `max_salt_len`. fn compute( comptime H: type, comptime transpose: []const u8, password: []const u8, salt: []const u8, rounds: u32, out: []u8, ) void { const n = H.digest_length; std.debug.assert(password.len <= handler.max_password_len); std.debug.assert(salt.len <= max_salt_len); // Digest B: password, salt, password. var db: [n]u8 = undefined; var b = H.init(.{}); b.update(password); b.update(salt); b.update(password); b.final(&db); // Digest A: password and salt, then B repeated to the password's // length, then for each bit of the length, lowest first, B for a one // bit and the password for a zero. var da: [n]u8 = undefined; var a = H.init(.{}); a.update(password); a.update(salt); var remaining = password.len; while (remaining > 0) : (remaining -= @min(remaining, n)) { a.update(db[0..@min(remaining, n)]); } var bits = password.len; while (bits > 0) : (bits >>= 1) { a.update(if (bits & 1 != 0) &db else password); } a.final(&da); // P: the digest of the password repeated once per byte of it, repeated // in turn to the password's length. var dp_digest: [n]u8 = undefined; var dp_ctx = H.init(.{}); for (0..password.len) |_| dp_ctx.update(password); dp_ctx.final(&dp_digest); var p_buf: [handler.max_password_len]u8 = undefined; const p = p_buf[0..password.len]; for (p, 0..) |*c, i| c.* = dp_digest[i % n]; // S: the digest of the salt repeated 16 + A[0] times, cut to the salt's // length. var ds_digest: [n]u8 = undefined; var ds_ctx = H.init(.{}); for (0..16 + @as(usize, da[0])) |_| ds_ctx.update(salt); ds_ctx.final(&ds_digest); const s = ds_digest[0..salt.len]; var c = da; for (0..rounds) |i| { var r = H.init(.{}); if (i & 1 != 0) r.update(p) else r.update(&c); if (i % 3 != 0) r.update(s); if (i % 7 != 0) r.update(p); if (i & 1 != 0) r.update(&c) else r.update(p); r.final(&c); } _ = h64.encodeTransposed(out, &c, transpose); } /// The parts of a hash or configuration string. const Parsed = struct { rounds: u32, salt: []const u8, /// Null for a configuration string, which has no checksum. checksum: ?[]const u8, }; /// A scheme of the family: `ident` is `$5$` or `$6$`, `H` the hash it is /// built on, and `default_rounds` passlib's default for it. pub fn Sha2Crypt( comptime scheme_name: []const u8, comptime ident: []const u8, comptime H: type, comptime transpose: []const u8, comptime default_rounds: u32, ) type { return struct { pub const name = scheme_name; /// The length of the encoded checksum. pub const checksum_len = h64.encodedLen(H.digest_length); pub const Options = struct { /// The salt, up to sixteen characters of `./0-9A-Za-z`. Null, /// the default, draws a random one of `salt_size` characters. salt: ?[]const u8 = null, /// The length of a random salt, up to sixteen. salt_size: u8 = max_salt_len, /// The number of rounds, from 1000 to 999,999,999. passlib's /// default is 535,000 for SHA256-Crypt and 656,000 for /// SHA512-Crypt. rounds: u32 = default_rounds, /// `needsUpdate` reports a hash with fewer rounds than this. min_desired_rounds: ?u32 = null, /// `needsUpdate` reports a hash with more rounds than this. max_desired_rounds: ?u32 = null, }; /// A prefix check, as passlib's is: a malformed hash with the right /// prefix is still identified as this scheme's. pub fn identify(h: []const u8) bool { return std.mem.startsWith(u8, h, ident); } /// `ident`, then an optional `rounds=N$`, then the salt, then an /// optional `$` and checksum. A rounds field with a leading zero is /// refused, so that one hash has one spelling. /// /// A configuration string, one with no checksum, is parsed as /// passlib parses one: leniently, with an overlong salt cut to /// sixteen characters and an out-of-range round count clamped into /// range. With a checksum, both are errors. fn parse(h: []const u8) Error!Parsed { if (!identify(h)) return error.MalformedHash; var fields: [3][]const u8 = undefined; var count: usize = 0; var it = std.mem.splitScalar(u8, h[ident.len..], '$'); while (it.next()) |f| { if (count == fields.len) return error.MalformedHash; fields[count] = f; count += 1; } var rounds: u64 = implicit_rounds; var first: usize = 0; if (std.mem.startsWith(u8, fields[0], "rounds=")) { const digits = fields[0]["rounds=".len..]; if (digits.len > 1 and digits[0] == '0') return error.MalformedHash; rounds = try handler.parseDecimal(u64, digits, true); first = 1; } const salt_field = if (first < count) fields[first] else return error.MalformedHash; const checksum: ?[]const u8 = switch (count - first) { 1 => null, 2 => if (fields[first + 1].len == 0) null else fields[first + 1], else => return error.MalformedHash, }; const relaxed = checksum == null; if (!h64.isValid(salt_field)) return error.MalformedHash; var salt = salt_field; if (salt.len > max_salt_len) { if (!relaxed) return error.MalformedHash; salt = salt[0..max_salt_len]; } if (rounds < min_rounds or rounds > max_rounds) { if (!relaxed) return error.MalformedHash; rounds = std.math.clamp(rounds, min_rounds, max_rounds); } if (checksum) |c| { if (c.len != checksum_len or !h64.isValid(c)) return error.MalformedHash; } return .{ .rounds = @intCast(rounds), .salt = salt, .checksum = checksum }; } fn checkPassword(password: []const u8) Error!void { // glibc's implementation takes a C string, so a password holding // a NUL would hash as though it ended there. passlib refuses it. if (std.mem.findScalar(u8, password, 0) != null) return error.InvalidPassword; } pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { try handler.checkPasswordLen(password); if (options.rounds < min_rounds or options.rounds > max_rounds) return error.InvalidOptions; var salt_buf: [max_salt_len]u8 = undefined; const salt = if (options.salt) |s| blk: { if (s.len > max_salt_len or !h64.isValid(s)) return error.InvalidOptions; break :blk s; } else blk: { if (options.salt_size > max_salt_len) return error.InvalidOptions; break :blk try handler.randomChars(ctx.io, salt_buf[0..options.salt_size], encoding.hash64_chars); }; try checkPassword(password); var checksum: [checksum_len]u8 = undefined; compute(H, transpose, password, salt, options.rounds, &checksum); if (options.rounds == implicit_rounds) { try w.print("{s}{s}${s}", .{ ident, salt, checksum }); } else { try w.print("{s}rounds={d}${s}${s}", .{ ident, options.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); // A configuration string has nothing to compare against. const expected = parsed.checksum orelse return error.MalformedHash; try checkPassword(password); var checksum: [checksum_len]u8 = undefined; compute(H, transpose, password, parsed.salt, parsed.rounds, &checksum); return handler.eql(expected, &checksum); } /// True when the hash's rounds fall outside `min_desired_rounds` and /// `max_desired_rounds`. Like passlib's, it accepts a configuration /// string as well as a hash. pub fn needsUpdate(h: []const u8, options: Options) Error!bool { try checkDesiredRounds(options.min_desired_rounds, options.max_desired_rounds); const parsed = try parse(h); return handler.roundsOutside(parsed.rounds, options.min_desired_rounds, options.max_desired_rounds); } }; } /// Refuses desired round counts passlib's `using()` would refuse: either /// outside the scheme's range, or a maximum below the minimum. fn checkDesiredRounds(min_desired: ?u32, max_desired: ?u32) Error!void { for ([_]?u32{ min_desired, max_desired }) |d| { if (d) |r| if (r < min_rounds or r > max_rounds) return error.InvalidOptions; } if (min_desired) |lo| if (max_desired) |hi| if (hi < lo) return error.InvalidOptions; } pub const sha256_crypt = Sha2Crypt("sha256_crypt", "$5$", sha2.Sha256, &transpose_256, 535_000); pub const sha512_crypt = Sha2Crypt("sha512_crypt", "$6$", sha2.Sha512, &transpose_512, 656_000); /// The schemes this module defines, in the order `registry.identify` tries /// them. pub const schemes = .{ sha512_crypt, sha256_crypt }; comptime { handler.check(sha256_crypt); handler.check(sha512_crypt); } const test_ctx: Context = .{ .io = testing.io, .gpa = testing.allocator }; test "fixed salts reproduce passlib" { // passlib 1.7.4: sha256_crypt.using(salt=..., rounds=...).hash(...), and // the same for sha512_crypt. const cases = .{ .{ sha256_crypt, "test", "abc", 5000, "$5$abc$xhLlZvoXRNo2v63CS0Ku6RxTjR8AtjqvUgTrPKnxyb1" }, .{ sha256_crypt, "test", "abc", 1000, "$5$rounds=1000$abc$1/AFll5u1v/mco1s6gjlnMiJFg8Oj19yltzAO/MaIS/" }, .{ sha512_crypt, "test", "abc", 5000, "$6$abc$XdYVWINHFqAPqCkQNpBc64k/whmYeD3VETO0Hk79c4aGoQEvgiYKd/03lbc/XloI0fcMwRw.Rj.dZbn3LdPVz." }, .{ sha512_crypt, "test", "abcdefghijklmnop", 1000, "$6$rounds=1000$abcdefghijklmnop$sFHv/rkKsZVsIA5tUEyoc7iWMRK2V0RwZLxa/jxtD8z4vY6YZtWGlA26/UQW2H0vtOiXEesKHqRWKD9AeoOog/" }, .{ sha512_crypt, "", "", 1000, "$6$rounds=1000$$NPMepfN3/Cv.LPoa7suAzCVH3BhfhhB2wHuwY51WjZgqg.e601K6RWCJ7AHYXHZcp4ilHQ0xlpG1yRxSYX3TP/" }, .{ sha256_crypt, "a" ** 200, "x", 1000, "$5$rounds=1000$x$0MplCSl.qzr6d8/eX4VY2Q8NLvUYttFyrMBJ1W/m/a." }, }; inline for (cases) |c| { var buf: [128]u8 = undefined; var w: Io.Writer = .fixed(&buf); try c[0].hash(test_ctx, c[1], .{ .salt = c[2], .rounds = c[3] }, &w); try testing.expectEqualStrings(c[4], w.buffered()); try testing.expect(try c[0].verify(test_ctx, c[1], c[4])); } } test "round trip with a random salt" { var buf: [128]u8 = undefined; var w: Io.Writer = .fixed(&buf); try sha512_crypt.hash(test_ctx, "hunter2", .{ .rounds = 1000 }, &w); const h = w.buffered(); try testing.expect(std.mem.startsWith(u8, h, "$6$rounds=1000$")); try testing.expectEqual(@as(usize, "$6$rounds=1000$".len + 16 + 1 + 86), h.len); try testing.expect(try sha512_crypt.verify(test_ctx, "hunter2", h)); try testing.expect(!try sha512_crypt.verify(test_ctx, "hunter3", h)); try testing.expect(!sha256_crypt.identify(h)); } test "refusals" { const good = "$5$rounds=5000$abc$" ++ "a" ** 43; try testing.expect(!try sha256_crypt.verify(test_ctx, "x", good)); try testing.expectError(error.InvalidPassword, sha256_crypt.verify(test_ctx, "x\x00", good)); // Configuration strings. try testing.expectError(error.MalformedHash, sha256_crypt.verify(test_ctx, "x", "$5$saltstring")); try testing.expectError(error.MalformedHash, sha256_crypt.verify(test_ctx, "x", "$5$saltstring$")); // A salt too long, rounds out of range, or a zero-padded or empty // rounds field, alongside a checksum. try testing.expectError(error.MalformedHash, sha256_crypt.verify(test_ctx, "x", "$5$rounds=5000$toolongsaltstring$" ++ "a" ** 43)); try testing.expectError(error.MalformedHash, sha256_crypt.verify(test_ctx, "x", "$5$rounds=10$abc$" ++ "a" ** 43)); try testing.expectError(error.MalformedHash, sha256_crypt.verify(test_ctx, "x", "$5$rounds=05000$abc$" ++ "a" ** 43)); try testing.expectError(error.MalformedHash, sha256_crypt.verify(test_ctx, "x", "$5$rounds=$abc$" ++ "a" ** 43)); try testing.expectError(error.MalformedHash, sha256_crypt.verify(test_ctx, "x", "$5$rounds=5000")); try testing.expectError(error.MalformedHash, sha256_crypt.verify(test_ctx, "x", "$5$abc$" ++ "a" ** 42)); try testing.expectError(error.MalformedHash, sha256_crypt.verify(test_ctx, "x", good ++ "$")); var buf: [128]u8 = undefined; var w: Io.Writer = .fixed(&buf); try testing.expectError(error.InvalidOptions, sha256_crypt.hash(test_ctx, "x", .{ .rounds = 999 }, &w)); try testing.expectError(error.InvalidOptions, sha256_crypt.hash(test_ctx, "x", .{ .salt = "a" ** 17 }, &w)); try testing.expectError(error.InvalidOptions, sha256_crypt.hash(test_ctx, "x", .{ .salt = "a!" }, &w)); try testing.expectError(error.InvalidPassword, sha256_crypt.hash(test_ctx, "a\x00b", .{ .rounds = 1000 }, &w)); } test "needsUpdate" { const h = "$5$rounds=5000$abc$" ++ "a" ** 43; try testing.expect(!try sha256_crypt.needsUpdate(h, .{})); try testing.expect(try sha256_crypt.needsUpdate(h, .{ .min_desired_rounds = 6000 })); try testing.expect(try sha256_crypt.needsUpdate(h, .{ .max_desired_rounds = 4000 })); // passlib parses a configuration string leniently: these clamp and // truncate rather than fail. try testing.expect(!try sha256_crypt.needsUpdate("$5$rounds=10$roundstoolow", .{})); try testing.expect(!try sha256_crypt.needsUpdate("$5$rounds=5000$toolongsaltstring", .{})); try testing.expectError(error.MalformedHash, sha256_crypt.needsUpdate("$5$rounds=00$abc", .{})); try testing.expectError(error.InvalidOptions, sha256_crypt.needsUpdate(h, .{ .min_desired_rounds = 999 })); }