Something went wrong. Try again.
passlib's password hash schemes, ported to Zig 0.16
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! SHA1-Crypt: passlib's `passlib.handlers.sha1_crypt`.//!//! NetBSD's `$sha1$` format, added in NetBSD 1.6 in 2004. It is PBKDF1//! built on HMAC-SHA1: the message `salt$sha1$rounds` is run through//! HMAC-SHA1, keyed with the password, `rounds` times over. A hash is//! `$sha1$`, the round count in decimal, `$`, a salt of up to 64 characters,//! `$`, and a 28-character checksum.//!//! **It is obsolete.** It was never adopted outside NetBSD, and HMAC-SHA1//! iterations are cheap on modern hardware. It is here to check passwords//! already stored with it.
const std = @import("std");const Io = std.Io;const HmacSha1 = std.crypto.auth.hmac.HmacSha1;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 ident = "$sha1$";pub const max_salt_len = 64;pub const default_salt_len = 8;pub const min_rounds = 1;pub const max_rounds = std.math.maxInt(u32);const checksum_len = 28;
/// The order the digest's bytes are encoded in. Byte 0 appears twice: the/// 20-byte digest is padded to 21 bytes, a multiple of three, with a copy of/// its first byte.const transpose = [_]u8{ 2, 1, 0, 5, 4, 3, 8, 7, 6, 11, 10, 9, 14, 13, 12, 17, 16, 15, 0, 19, 18 };
/// The 28-character checksum for `password`, `salt` and `rounds`.fn compute(password: []const u8, salt: []const u8, rounds: u32, out: *[checksum_len]u8) void { // `salt$sha1$rounds`: at most 64 characters of salt, the separators and // ten digits. var msg_buf: [max_salt_len + "$sha1$".len + 10]u8 = undefined; const msg = std.fmt.bufPrint(&msg_buf, "{s}$sha1${d}", .{ salt, rounds }) catch unreachable; var result: [HmacSha1.mac_length]u8 = undefined; HmacSha1.create(&result, msg, password); for (1..rounds) |_| { const prev = result; HmacSha1.create(&result, &prev, password); } _ = h64.encodeTransposed(out, &result, &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,};
pub const sha1_crypt = struct { pub const name = "sha1_crypt";
pub const Options = struct { /// The salt, up to 64 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 64. salt_size: u8 = default_salt_len, /// The number of rounds, from 1 to 4,294,967,295. rounds: u32 = 480_000, /// `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); }
/// `$sha1$`, rounds, `$`, salt, and optionally `$` and the checksum: /// passlib's `parse_mc3`. The rounds field is required and may not have /// a leading zero. 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; } if (count < 2) return error.MalformedHash;
const rounds = try handler.parseDecimal(u64, fields[0], false); if (rounds < min_rounds or rounds > max_rounds) return error.MalformedHash; const salt = fields[1]; if (salt.len > max_salt_len or !h64.isValid(salt)) return error.MalformedHash; const checksum: ?[]const u8 = if (count == 3 and fields[2].len > 0) fields[2] else null; 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 { // NetBSD's implementation takes a C string. passlib refuses a NUL // rather than hash a different password than it was given. 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) 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(password, salt, options.rounds, &checksum); try w.print("{s}{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(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 { const lo = options.min_desired_rounds; const hi = options.max_desired_rounds; // passlib's `using()` refuses these. if (lo) |r| if (r < min_rounds) return error.InvalidOptions; if (hi) |r| if (r < min_rounds) return error.InvalidOptions; if (lo) |l| if (hi) |u| if (u < l) return error.InvalidOptions; const parsed = try parse(h); return handler.roundsOutside(parsed.rounds, lo, hi); }};
/// The schemes this module defines, in the order `registry.identify` tries/// them.pub const schemes = .{sha1_crypt};
comptime { handler.check(sha1_crypt);}
const test_ctx: Context = .{ .io = testing.io, .gpa = testing.allocator };
test "fixed salts reproduce passlib" { // passlib 1.7.4: sha1_crypt.using(salt=..., rounds=...).hash(...). const cases = .{ .{ "test", "abc", 1000, "$sha1$1000$abc$H6ZmEVLSN7tDezhyHdXxjsXk8vEj" }, .{ "", "", 1, "$sha1$1$$rg56C9XvpFjLaINw7vIIvexWUQJ." }, .{ "pw", "a" ** 64, 5, "$sha1$5$" ++ "a" ** 64 ++ "$hk8eTt5BXYNh4Kjfi0v5zG9Tciao" }, }; inline for (cases) |c| { var buf: [128]u8 = undefined; var w: Io.Writer = .fixed(&buf); try sha1_crypt.hash(test_ctx, c[0], .{ .salt = c[1], .rounds = c[2] }, &w); try testing.expectEqualStrings(c[3], w.buffered()); try testing.expect(try sha1_crypt.verify(test_ctx, c[0], c[3])); }}
test "round trip with a random salt" { var buf: [128]u8 = undefined; var w: Io.Writer = .fixed(&buf); try sha1_crypt.hash(test_ctx, "hunter2", .{ .rounds = 100 }, &w); const h = w.buffered(); try testing.expectEqual(@as(usize, "$sha1$100$".len + 8 + 1 + 28), h.len); try testing.expect(try sha1_crypt.verify(test_ctx, "hunter2", h)); try testing.expect(!try sha1_crypt.verify(test_ctx, "hunter3", h));}
test "refusals" { const chk = "a" ** 28; try testing.expectError(error.MalformedHash, sha1_crypt.verify(test_ctx, "x", "$sha1$0$abc$" ++ chk)); try testing.expectError(error.MalformedHash, sha1_crypt.verify(test_ctx, "x", "$sha1$01000$abc$" ++ chk)); try testing.expectError(error.MalformedHash, sha1_crypt.verify(test_ctx, "x", "$sha1$4294967296$abc$" ++ chk)); try testing.expectError(error.MalformedHash, sha1_crypt.verify(test_ctx, "x", "$sha1$1000$" ++ "a" ** 65 ++ "$" ++ chk)); try testing.expectError(error.MalformedHash, sha1_crypt.verify(test_ctx, "x", "$sha1$1000$abc$" ++ "a" ** 27)); try testing.expectError(error.MalformedHash, sha1_crypt.verify(test_ctx, "x", "$sha1$1000")); try testing.expectError(error.MalformedHash, sha1_crypt.verify(test_ctx, "x", "$sha1$1000$abc")); try testing.expectError(error.MalformedHash, sha1_crypt.verify(test_ctx, "x", "$sha1$1000$abc$")); try testing.expectError(error.InvalidPassword, sha1_crypt.verify(test_ctx, "a\x00b", "$sha1$1000$abc$" ++ chk));
var buf: [128]u8 = undefined; var w: Io.Writer = .fixed(&buf); try testing.expectError(error.InvalidOptions, sha1_crypt.hash(test_ctx, "x", .{ .rounds = 0 }, &w)); try testing.expectError(error.InvalidOptions, sha1_crypt.hash(test_ctx, "x", .{ .salt = "a" ** 65 }, &w)); try testing.expectError(error.InvalidOptions, sha1_crypt.hash(test_ctx, "x", .{ .salt_size = 65 }, &w)); try testing.expectError(error.InvalidPassword, sha1_crypt.hash(test_ctx, "a\x00b", .{ .rounds = 1 }, &w));}
test "needsUpdate" { const h = "$sha1$1000$abc$" ++ "a" ** 28; try testing.expect(!try sha1_crypt.needsUpdate(h, .{})); try testing.expect(try sha1_crypt.needsUpdate(h, .{ .min_desired_rounds = 2000 })); try testing.expect(try sha1_crypt.needsUpdate(h, .{ .max_desired_rounds = 500 })); try testing.expect(!try sha1_crypt.needsUpdate("$sha1$1000$abc", .{}));}