Something went wrong. Try again.
passlib's password hash schemes, ported to Zig 0.16
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! MD5-crypt and Apache's variant of it: passlib's//! `passlib.handlers.md5_crypt`.//!//! Poul-Henning Kamp's `$1$` format for FreeBSD, 1994, adopted by nearly//! every Unix after it. A salt of up to eight characters, and a fixed 1000//! rounds of MD5 mixing the password, the salt and the previous digest in//! varying orders. Apache's `$apr1$` is the same algorithm with a different//! magic string mixed in, so the two never produce the same hash.//!//! **It is obsolete.** The round count is fixed, and 1000 rounds of MD5 was//! cheap in 1994. Its author declared it insecure in 2012. It is here to//! check passwords already stored with it, in `/etc/shadow`, in `.htpasswd`//! files, and on Cisco equipment, which uses it with a four-character salt.
const std = @import("std");const Io = std.Io;const Md5 = std.crypto.hash.Md5;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 = 8;const checksum_len = 22;
/// The order the digest's bytes are encoded in.const transpose = [_]u8{ 12, 6, 0, 13, 7, 1, 14, 8, 2, 15, 9, 3, 5, 10, 4, 11 };
/// The 22-character checksum for `password` and `salt`, under `magic`.fn compute(password: []const u8, salt: []const u8, magic: []const u8, out: *[checksum_len]u8) void { var digest: [Md5.digest_length]u8 = undefined;
var alt = Md5.init(.{}); alt.update(password); alt.update(salt); alt.update(password); alt.final(&digest);
var ctx = Md5.init(.{}); ctx.update(password); ctx.update(magic); ctx.update(salt); var remaining = password.len; while (remaining > 0) : (remaining -= @min(remaining, digest.len)) { ctx.update(digest[0..@min(remaining, digest.len)]); } // For each bit of the length, lowest first: a NUL for a one bit, and the // first character of the password for a zero. That is what the original // C does, reading the "cleared" digest as zeros. var bits = password.len; while (bits > 0) : (bits >>= 1) { ctx.update(if (bits & 1 != 0) "\x00" else password[0..1]); } ctx.final(&digest);
for (0..1000) |i| { var round = Md5.init(.{}); if (i & 1 != 0) round.update(password) else round.update(&digest); if (i % 3 != 0) round.update(salt); if (i % 7 != 0) round.update(password); if (i & 1 != 0) round.update(&digest) else round.update(password); round.final(&digest); }
_ = h64.encodeTransposed(out, &digest, &transpose);}
pub fn Md5Crypt(comptime scheme_name: []const u8, comptime ident: []const u8, comptime magic: []const u8) type { return struct { pub const name = scheme_name;
pub const Options = struct { /// The salt, up to eight 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 eight. Cisco's equipment /// wants four. salt_size: u8 = max_salt_len, };
pub fn identify(h: []const u8) bool { return std.mem.startsWith(u8, h, ident); }
const Parsed = struct { salt: []const u8, checksum: []const u8 };
/// `ident` + salt + `$` + checksum. A string with no checksum is a /// configuration string, not a hash, and passlib refuses to verify /// against one, so this refuses it too. fn parse(h: []const u8) Error!Parsed { if (!identify(h)) return error.MalformedHash; const rest = h[ident.len..]; const fields = try handler.splitExact(2, rest, '$'); const salt = fields[0]; const checksum = fields[1]; if (salt.len > max_salt_len or !h64.isValid(salt)) return error.MalformedHash; if (checksum.len != checksum_len or !h64.isValid(checksum)) return error.MalformedHash; return .{ .salt = salt, .checksum = checksum }; }
fn checkPassword(password: []const u8) Error!void { try handler.checkPasswordLen(password); // The C implementations stop at a NUL, so a password holding one // would hash as though it ended there. 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 checkPassword(password); 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); }; var checksum: [checksum_len]u8 = undefined; compute(password, salt, magic, &checksum); try w.print("{s}{s}${s}", .{ ident, salt, checksum }); }
pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { _ = ctx; const parsed = try parse(h); try checkPassword(password); var checksum: [checksum_len]u8 = undefined; compute(password, parsed.salt, magic, &checksum); return handler.eql(parsed.checksum, &checksum); }
/// Always false for a hash that parses: there is no round count or /// variant to be out of date. pub fn needsUpdate(h: []const u8, options: Options) Error!bool { _ = options; _ = try parse(h); return false; } };}
pub const md5_crypt = Md5Crypt("md5_crypt", "$1$", "$1$");pub const apr_md5_crypt = Md5Crypt("apr_md5_crypt", "$apr1$", "$apr1$");
/// The schemes this module defines, in the order `registry.identify` tries/// them.pub const schemes = .{ md5_crypt, apr_md5_crypt };
comptime { handler.check(md5_crypt); handler.check(apr_md5_crypt);}
const test_ctx: Context = .{ .io = testing.io, .gpa = testing.allocator };
test "the salts passlib's backend self-test uses" { // passlib 1.7.4: md5_crypt.using(salt="test").hash("test"), and the same // for apr_md5_crypt and for the empty password and salt. var buf: [64]u8 = undefined; var w: Io.Writer = .fixed(&buf); try md5_crypt.hash(test_ctx, "test", .{ .salt = "test" }, &w); try testing.expectEqualStrings("$1$test$pi/xDtU5WFVRqYS6BMU8X/", w.buffered());
w = .fixed(&buf); try apr_md5_crypt.hash(test_ctx, "test", .{ .salt = "test" }, &w); try testing.expectEqualStrings("$apr1$test$0e8oyYZUPnLv2JmB7wQOB1", w.buffered());
w = .fixed(&buf); try md5_crypt.hash(test_ctx, "", .{ .salt = "" }, &w); try testing.expectEqualStrings("$1$$qRPK7m23GJusamGpoGLby/", w.buffered());}
test "round trip with a random salt" { var buf: [64]u8 = undefined; var w: Io.Writer = .fixed(&buf); try md5_crypt.hash(test_ctx, "hunter2", .{}, &w); try testing.expect(try md5_crypt.verify(test_ctx, "hunter2", w.buffered())); try testing.expect(!try md5_crypt.verify(test_ctx, "hunter3", w.buffered())); try testing.expect(!apr_md5_crypt.identify(w.buffered()));}
test "refusals" { try testing.expectError(error.MalformedHash, md5_crypt.verify(test_ctx, "test", "$1$test")); try testing.expectError(error.MalformedHash, md5_crypt.verify(test_ctx, "test", "$1$test$")); try testing.expectError(error.MalformedHash, md5_crypt.verify(test_ctx, "test", "$1$toolongsalt$pi/xDtU5WFVRqYS6BMU8X/")); try testing.expectError(error.InvalidPassword, md5_crypt.verify(test_ctx, "te\x00st", "$1$test$pi/xDtU5WFVRqYS6BMU8X/")); var buf: [64]u8 = undefined; var w: Io.Writer = .fixed(&buf); try testing.expectError(error.InvalidOptions, md5_crypt.hash(test_ctx, "x", .{ .salt = "bad!" }, &w));}