Something went wrong. Try again.
passlib's password hash schemes, ported to Zig 0.16
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The PHPass portable hash: passlib's `passlib.handlers.phpass`.//!//! Solar Designer's portable fallback in PHPass, 2004, the password library//! WordPress, Drupal 7 and phpBB 3 were built on. It iterates MD5 over the//! previous digest and the password `2**rounds` times. A hash is `$P$`, one//! character giving the base-two logarithm of the round count, an//! eight-character salt, and a 22-character checksum. phpBB 3 writes `$H$`//! for the same thing.//!//! **It is obsolete.** Iterated MD5 is cheap to attack on modern hardware,//! and PHPass itself used it only where bcrypt was unavailable. It is here//! to check passwords already stored by those applications.
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 salt_len = 8;pub const min_rounds = 7;pub const max_rounds = 30;const checksum_len = 22;
/// The prefixes a hash may start with: PHPass's own, then phpBB 3's.const idents = [_][]const u8{ "$P$", "$H$" };
/// The checksum for `password`, `salt` and `2**rounds` iterations.fn compute(password: []const u8, salt: []const u8, rounds: u5, out: *[checksum_len]u8) void { var result: [Md5.digest_length]u8 = undefined; var first = Md5.init(.{}); first.update(salt); first.update(password); first.final(&result); const count = @as(u32, 1) << rounds; for (0..count) |_| { var h = Md5.init(.{}); h.update(&result); h.update(password); h.final(&result); } _ = h64.encode(out, &result);}
/// The parts of a hash or configuration string.const Parsed = struct { rounds: u5, salt: []const u8, /// Null for a configuration string, which has no checksum. checksum: ?[]const u8,};
pub const phpass = struct { pub const name = "phpass";
pub const Options = struct { /// The salt, exactly eight characters of `./0-9A-Za-z`. Null, the /// default, draws a random one. salt: ?[]const u8 = null, /// The base-two logarithm of the number of iterations, from 7 to /// 30. rounds: u8 = 19, /// `$P$`, the default, or phpBB 3's `$H$`. passlib also takes `P` /// and `H` for them. ident: []const u8 = "$P$", /// `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: `$P$` or `$H$`. pub fn identify(h: []const u8) bool { for (idents) |ident| if (std.mem.startsWith(u8, h, ident)) return true; return false; }
/// The prefix, the rounds character, the eight-character salt, and the /// checksum. /// /// passlib sets no length for the checksum, only its alphabet, so a /// checksum of the wrong length is not an error: it is one no password /// verifies against. An empty one makes a configuration string. fn parse(h: []const u8) Error!Parsed { if (!identify(h)) return error.MalformedHash; const data = h[3..]; // passlib fails here with an IndexError rather than a ValueError. if (data.len == 0) return error.MalformedHash; const rounds = h64.value(data[0]) orelse return error.MalformedHash; if (rounds < min_rounds or rounds > max_rounds) return error.MalformedHash; const salt = data[1..@min(data.len, 1 + salt_len)]; if (salt.len != salt_len or !h64.isValid(salt)) return error.MalformedHash; const rest = data[1 + salt_len ..]; if (!h64.isValid(rest)) return error.MalformedHash; return .{ .rounds = @intCast(rounds), .salt = salt, .checksum = if (rest.len == 0) null else rest, }; }
/// The prefix `ident` names, or `error.InvalidOptions`. fn normIdent(ident: []const u8) Error![]const u8 { for (idents) |i| { if (std.mem.eql(u8, ident, i) or std.mem.eql(u8, ident, i[1..2])) return i; } return error.InvalidOptions; }
pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { try handler.checkPasswordLen(password); const ident = try normIdent(options.ident); if (options.rounds < min_rounds or options.rounds > max_rounds) return error.InvalidOptions; var salt_buf: [salt_len]u8 = undefined; const salt = if (options.salt) |s| blk: { if (s.len != salt_len or !h64.isValid(s)) return error.InvalidOptions; break :blk s; } else try handler.randomChars(ctx.io, &salt_buf, encoding.hash64_chars); const rounds: u5 = @intCast(options.rounds); var checksum: [checksum_len]u8 = undefined; compute(password, salt, rounds, &checksum); try w.print("{s}{c}{s}{s}", .{ ident, h64.char(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; var checksum: [checksum_len]u8 = undefined; compute(password, parsed.salt, parsed.rounds, &checksum); return handler.eql(expected, &checksum); }
/// True when the hash's rounds, the logarithm, fall outside /// `min_desired_rounds` and `max_desired_rounds`. The prefix is not /// compared: passlib treats `$P$` and `$H$` as equally current. 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. for ([_]?u32{ lo, hi }) |d| { if (d) |r| if (r < min_rounds or r > max_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 = .{phpass};
comptime { handler.check(phpass);}
const test_ctx: Context = .{ .io = testing.io, .gpa = testing.allocator };
test "fixed salts reproduce passlib" { // passlib 1.7.4: phpass.using(salt=..., rounds=..., ident=...).hash(...). const cases = .{ .{ "test", "abcdefgh", 7, "$P$", "$P$5abcdefghuGnpkY5zYNED.dJ1.sD660" }, .{ "te\x00st", "abcdefgh", 8, "H", "$H$6abcdefgh.m75viFprHv1CoQALFnz3." }, .{ "", "........", 10, "P", "$P$8........nyf18ygpqxlnGVBS7.REz/" }, }; inline for (cases) |c| { var buf: [64]u8 = undefined; var w: Io.Writer = .fixed(&buf); try phpass.hash(test_ctx, c[0], .{ .salt = c[1], .rounds = c[2], .ident = c[3] }, &w); try testing.expectEqualStrings(c[4], w.buffered()); try testing.expect(try phpass.verify(test_ctx, c[0], c[4])); }}
test "round trip with a random salt" { var buf: [64]u8 = undefined; var w: Io.Writer = .fixed(&buf); try phpass.hash(test_ctx, "hunter2", .{ .rounds = 7 }, &w); const h = w.buffered(); try testing.expectEqual(@as(usize, 34), h.len); try testing.expect(try phpass.verify(test_ctx, "hunter2", h)); try testing.expect(!try phpass.verify(test_ctx, "hunter3", h));}
test "refusals" { const good = "$P$9IQRaTwmfeRo7ud9Fh4E2PdI0S3r.L0"; try testing.expect(try phpass.verify(test_ctx, "test12345", good)); // A checksum of the wrong length verifies nothing, as in passlib. try testing.expect(!try phpass.verify(test_ctx, "test12345", good ++ "x")); try testing.expect(!try phpass.verify(test_ctx, "test12345", good[0 .. good.len - 1])); try testing.expectError(error.MalformedHash, phpass.verify(test_ctx, "x", "$P$9IQRaTwm")); try testing.expectError(error.MalformedHash, phpass.verify(test_ctx, "x", "$P$9IQRaTwmf")); try testing.expectError(error.MalformedHash, phpass.verify(test_ctx, "x", "$P$")); try testing.expectError(error.MalformedHash, phpass.verify(test_ctx, "x", "$P$VIQRaTwmfeRo7ud9Fh4E2PdI0S3r.L0")); try testing.expectError(error.MalformedHash, phpass.verify(test_ctx, "x", "$P$4IQRaTwmfeRo7ud9Fh4E2PdI0S3r.L0")); try testing.expectError(error.MalformedHash, phpass.verify(test_ctx, "x", "$P$9IQRaTwmfeRo7ud9Fh4E2PdI0S3r!L0"));
var buf: [64]u8 = undefined; var w: Io.Writer = .fixed(&buf); try testing.expectError(error.InvalidOptions, phpass.hash(test_ctx, "x", .{ .salt = "abcdefg" }, &w)); try testing.expectError(error.InvalidOptions, phpass.hash(test_ctx, "x", .{ .rounds = 31 }, &w)); try testing.expectError(error.InvalidOptions, phpass.hash(test_ctx, "x", .{ .rounds = 6 }, &w)); try testing.expectError(error.InvalidOptions, phpass.hash(test_ctx, "x", .{ .ident = "$X$" }, &w));}
test "needsUpdate" { const h = "$P$9IQRaTwmfeRo7ud9Fh4E2PdI0S3r.L0"; try testing.expect(!try phpass.needsUpdate(h, .{})); try testing.expect(!try phpass.needsUpdate(h, .{ .min_desired_rounds = 10 })); try testing.expect(try phpass.needsUpdate(h, .{ .min_desired_rounds = 12 })); try testing.expect(try phpass.needsUpdate(h, .{ .max_desired_rounds = 10 })); try testing.expect(!try phpass.needsUpdate("$H$9IQRaTwmf", .{})); try testing.expectError(error.MalformedHash, phpass.needsUpdate("$H$9IQRaTwm", .{})); try testing.expectError(error.InvalidOptions, phpass.needsUpdate(h, .{ .min_desired_rounds = 31 }));}