Something went wrong. Try again.
passlib's password hash schemes, ported to Zig 0.16
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Django's password formats: passlib's `passlib.handlers.django`.//!//! Django stores `algorithm$...` in its `auth_user.password` column, and has//! changed its default algorithm several times. What it wrote over the years://!//! * `md5$salt$hex` and `sha1$salt$hex`: one pass of a digest over the salt//! and the password. Django's default until 1.4. **Far too fast.**//! * `pbkdf2_sha256$rounds$salt$base64` and `pbkdf2_sha1$...`: PBKDF2, the//! default since 1.4.//! * `bcrypt$...`, `bcrypt_sha256$...` and `argon2$...`: the other schemes,//! behind Django's prefix.//! * `crypt$$...`: DES `crypt`, for sites migrated from something older.//! * `!` and 40 random characters: an unusable password.
const std = @import("std");const Io = std.Io;const testing = std.testing;
const argon2 = @import("argon2.zig");const bcrypt = @import("bcrypt.zig");const des_crypt = @import("des_crypt.zig");const encoding = @import("../encoding.zig");const handler = @import("../handler.zig");const Context = handler.Context;const Error = handler.Error;
/// The characters Django draws salts from.pub const salt_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";const base64_padded_chars = encoding.base64_chars ++ "=";
/// `ident` + salt + `$` + the lower-case hex digest of the salt followed by/// the password.pub fn SaltedDigest(comptime scheme_name: []const u8, comptime ident: []const u8, comptime Hash: type) type { return struct { pub const name = scheme_name;
pub const Options = struct { /// The salt, of `a-zA-Z0-9`. Null, the default, draws a random /// one of `salt_size` characters. salt: ?[]const u8 = null, salt_size: u8 = 12, };
const hex_len = Hash.digest_length * 2;
pub fn identify(h: []const u8) bool { return std.mem.startsWith(u8, h, ident); }
const Parsed = struct { salt: []const u8, checksum: []const u8 };
fn parse(h: []const u8) Error!Parsed { if (!identify(h)) return error.MalformedHash; const fields = try handler.splitExact(2, h[ident.len..], '$'); if (!encoding.allIn(fields[0], salt_chars)) return error.MalformedHash; if (fields[1].len != hex_len or !encoding.allIn(fields[1], encoding.lower_hex_chars)) return error.MalformedHash; return .{ .salt = fields[0], .checksum = fields[1] }; }
fn compute(password: []const u8, salt: []const u8, out: *[hex_len]u8) void { var hasher = Hash.init(.{}); hasher.update(salt); hasher.update(password); var digest: [Hash.digest_length]u8 = undefined; hasher.final(&digest); _ = encoding.hexLower(out, &digest); }
pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { try handler.checkPasswordLen(password); var salt_buf: [255]u8 = undefined; const salt = if (options.salt) |s| blk: { if (!encoding.allIn(s, salt_chars)) return error.InvalidOptions; break :blk s; } else try handler.randomChars(ctx.io, salt_buf[0..options.salt_size], salt_chars); var out: [hex_len]u8 = undefined; compute(password, salt, &out); try w.print("{s}{s}${s}", .{ ident, salt, out }); }
pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { _ = ctx; const parsed = try parse(h); try handler.checkPasswordLen(password); var out: [hex_len]u8 = undefined; compute(password, parsed.salt, &out); return handler.eql(parsed.checksum, &out); }
pub fn needsUpdate(h: []const u8, options: Options) Error!bool { _ = options; _ = try parse(h); return false; } };}
/// `ident` + rounds + `$` + salt + `$` + PBKDF2-HMAC in padded base64.pub fn Pbkdf2(comptime scheme_name: []const u8, comptime ident: []const u8, comptime Hash: type, comptime default_rounds: u32) type { return struct { pub const name = scheme_name; pub const min_rounds = 1; pub const max_rounds = 0xffff_ffff;
pub const Options = struct { /// The salt, at least one character of `a-zA-Z0-9`. Null, the /// default, draws a random one of `salt_size` characters. salt: ?[]const u8 = null, salt_size: u8 = 12, rounds: u32 = default_rounds, /// passlib's `min_desired_rounds` and `max_desired_rounds`: a /// hash with rounds outside them needs updating. min_desired_rounds: ?u32 = null, max_desired_rounds: ?u32 = null, };
const Prf = std.crypto.auth.hmac.Hmac(Hash); const digest_len = Hash.digest_length; const encoded_len = encoding.b64.encodedLen(digest_len);
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 };
fn parse(h: []const u8) Error!Parsed { if (!identify(h)) return error.MalformedHash; const fields = try handler.splitExact(3, h[ident.len..], '$'); const rounds = try handler.parseDecimal(u32, fields[0], false); if (rounds < min_rounds) return error.MalformedHash; if (fields[1].len < 1 or !encoding.allIn(fields[1], salt_chars)) return error.MalformedHash; if (fields[2].len != encoded_len or !encoding.allIn(fields[2], base64_padded_chars)) return error.MalformedHash; return .{ .rounds = rounds, .salt = fields[1], .checksum = fields[2] }; }
fn compute(password: []const u8, salt: []const u8, rounds: u32, out: *[encoded_len]u8) Error!void { var dk: [digest_len]u8 = undefined; try std.crypto.pwhash.pbkdf2(&dk, password, salt, rounds, Prf); _ = encoding.b64.encode(out, &dk); }
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: [255]u8 = undefined; const salt = if (options.salt) |s| blk: { if (s.len < 1 or !encoding.allIn(s, salt_chars)) return error.InvalidOptions; break :blk s; } else blk: { if (options.salt_size < 1) return error.InvalidOptions; break :blk try handler.randomChars(ctx.io, salt_buf[0..options.salt_size], salt_chars); }; var out: [encoded_len]u8 = undefined; try compute(password, salt, options.rounds, &out); try w.print("{s}{d}${s}${s}", .{ ident, options.rounds, salt, out }); }
pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { _ = ctx; const parsed = try parse(h); try handler.checkPasswordLen(password); var out: [encoded_len]u8 = undefined; try compute(password, parsed.salt, parsed.rounds, &out); return handler.eql(parsed.checksum, &out); }
/// True when the rounds fall outside `min_desired_rounds` and /// `max_desired_rounds`. pub fn needsUpdate(h: []const u8, options: Options) Error!bool { const parsed = try parse(h); return handler.roundsOutside(parsed.rounds, options.min_desired_rounds, options.max_desired_rounds); } };}
pub const django_salted_sha1 = SaltedDigest("django_salted_sha1", "sha1$", std.crypto.hash.Sha1);pub const django_salted_md5 = SaltedDigest("django_salted_md5", "md5$", std.crypto.hash.Md5);/// passlib 1.7.4's defaults: those of its own `pbkdf2_sha256` and/// `pbkdf2_sha1`, rather than Django's.pub const django_pbkdf2_sha256 = Pbkdf2("django_pbkdf2_sha256", "pbkdf2_sha256$", std.crypto.hash.sha2.Sha256, 29000);pub const django_pbkdf2_sha1 = Pbkdf2("django_pbkdf2_sha1", "pbkdf2_sha1$", std.crypto.hash.Sha1, 131000);
/// Django's unusable password: `!` and 40 random characters, so that two/// disabled accounts do not share a value. Nothing verifies against it.pub const django_disabled = struct { pub const name = "django_disabled"; pub const Options = struct {}; const suffix_len = 40;
pub fn identify(h: []const u8) bool { return std.mem.startsWith(u8, h, "!"); }
pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { _ = options; try handler.checkPasswordLen(password); var suffix: [suffix_len]u8 = undefined; _ = try handler.randomChars(ctx.io, &suffix, salt_chars); try w.writeByte('!'); try w.writeAll(&suffix); }
pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { _ = ctx; try handler.checkPasswordLen(password); if (!identify(h)) return error.MalformedHash; return false; }
pub fn needsUpdate(h: []const u8, options: Options) Error!bool { _ = options; if (!identify(h)) return error.MalformedHash; return false; }};
/// bcrypt behind `bcrypt$`.pub const django_bcrypt = handler.PrefixWrapper("django_bcrypt", bcrypt.bcrypt, "bcrypt$", "");
/// Argon2 behind `argon2`, so `argon2$argon2i$v=19$...`. Django wrote/// Argon2i, and passlib's `django_argon2` defaults to it where its `argon2`/// defaults to Argon2id.pub const django_argon2 = handler.PrefixWrapper( "django_argon2", handler.Using(argon2.argon2, .{ .type = .i }), "argon2", "",);
/// Django's `bcrypt_sha256$` and a bcrypt hash of the hex SHA-256 of the/// password. The hex digest is 64 characters, so bcrypt's 72-byte limit/// never bites. It is not passlib's own `bcrypt_sha256`, which encodes the/// digest differently.pub const django_bcrypt_sha256 = struct { pub const name = "django_bcrypt_sha256"; pub const Options = bcrypt.bcrypt.Options; const prefix = "bcrypt_sha256$";
pub fn identify(h: []const u8) bool { return std.mem.startsWith(u8, h, prefix); }
/// The bcrypt hash inside, which must start `$2`. fn inner(h: []const u8) Error![]const u8 { if (!identify(h)) return error.MalformedHash; const rest = h[prefix.len..]; if (!std.mem.startsWith(u8, rest, "$2")) return error.MalformedHash; return rest; }
fn prehash(password: []const u8) [64]u8 { var digest: [32]u8 = undefined; std.crypto.hash.sha2.Sha256.hash(password, &digest, .{}); var out: [64]u8 = undefined; _ = encoding.hexLower(&out, &digest); return out; }
pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { try handler.checkPasswordLen(password); const hex = prehash(password); try w.writeAll(prefix); try bcrypt.bcrypt.hash(ctx, &hex, options, w); }
pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { const rest = try inner(h); try handler.checkPasswordLen(password); const hex = prehash(password); return bcrypt.bcrypt.verify(ctx, &hex, rest); }
pub fn needsUpdate(h: []const u8, options: Options) Error!bool { return bcrypt.bcrypt.needsUpdate(try inner(h), options); }};
/// DES `crypt` in Django's clothing: `crypt$` + salt + `$` + the traditional/// thirteen-character hash, whose first two characters repeat the salt./// Only the first two characters of the salt are used.////// passlib accepts the salt field empty, taking the salt from the hash, and/// refuses a salt that disagrees with it.pub const django_des_crypt = struct { pub const name = "django_des_crypt"; pub const Options = struct { /// The salt, at least two characters of `./0-9A-Za-z`, of which two /// are used. Null, the default, draws a random two. salt: ?[]const u8 = null, /// Refuse a password longer than eight bytes, rather than hash only /// its first eight. truncate_error: bool = false, }; const prefix = "crypt$"; const des_len = 13;
pub fn identify(h: []const u8) bool { return std.mem.startsWith(u8, h, prefix); }
const Parsed = struct { salt: []const u8, des: []const u8 };
fn parse(h: []const u8) Error!Parsed { if (!identify(h)) return error.MalformedHash; const fields = try handler.splitExact(2, h[prefix.len..], '$'); const des = fields[1]; if (des.len != des_len or !encoding.h64.isValid(des)) return error.MalformedHash; const salt = if (fields[0].len == 0) des[0..2] else fields[0]; if (salt.len < 2 or !encoding.h64.isValid(salt)) return error.MalformedHash; if (!std.mem.eql(u8, salt[0..2], des[0..2])) return error.MalformedHash; return .{ .salt = salt, .des = des }; }
pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { var salt_buf: [2]u8 = undefined; const salt = if (options.salt) |s| blk: { if (s.len < 2 or !encoding.h64.isValid(s)) return error.InvalidOptions; break :blk s; } else try handler.randomChars(ctx.io, &salt_buf, encoding.hash64_chars); var buf: [des_len]u8 = undefined; var des: Io.Writer = .fixed(&buf); try des_crypt.des_crypt.hash(ctx, password, .{ .salt = salt[0..2], .truncate_error = options.truncate_error }, &des); try w.print("{s}{s}${s}", .{ prefix, salt, des.buffered() }); }
pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { const parsed = try parse(h); return des_crypt.des_crypt.verify(ctx, password, parsed.des); }
pub fn needsUpdate(h: []const u8, options: Options) Error!bool { _ = options; _ = try parse(h); return false; }};
/// The schemes this module defines, in the order `registry.identify` tries/// them. `bcrypt_sha256$` comes before `bcrypt$`, which is not a prefix of/// it, but reads more plainly that way.pub const schemes = .{ django_salted_sha1, django_salted_md5, django_pbkdf2_sha256, django_pbkdf2_sha1, django_bcrypt_sha256, django_bcrypt, django_argon2, django_des_crypt, django_disabled,};
comptime { for (schemes) |S| handler.check(S);}
const test_ctx: Context = .{ .io = testing.io, .gpa = testing.allocator };
test "salted digests reproduce passlib" { // passlib 1.7.4: django_salted_md5.using(salt="abc").hash("password"), // and the same for django_salted_sha1. var buf: [128]u8 = undefined; var w: Io.Writer = .fixed(&buf); try django_salted_md5.hash(test_ctx, "password", .{ .salt = "abc" }, &w); try testing.expectEqualStrings("md5$abc$243c7aa68f30e9dee78b87fe48106f76", w.buffered()); w = .fixed(&buf); try django_salted_sha1.hash(test_ctx, "password", .{ .salt = "abc" }, &w); try testing.expectEqualStrings("sha1$abc$403e4a4698de0d54c867b5cfaf4227eecb48d5da", w.buffered()); try testing.expect(!try django_salted_md5.verify(test_ctx, "x", "md5$$" ++ "a" ** 32)); try testing.expectError(error.MalformedHash, django_salted_md5.verify(test_ctx, "x", "md5$abc$" ++ "A" ** 32)); try testing.expectError(error.MalformedHash, django_salted_md5.verify(test_ctx, "x", "md5$ab-c$" ++ "a" ** 32));}
test "pbkdf2 reproduces passlib" { // passlib 1.7.4: django_pbkdf2_sha256.using(salt="abc", rounds=1000).hash("password") var buf: [128]u8 = undefined; var w: Io.Writer = .fixed(&buf); try django_pbkdf2_sha256.hash(test_ctx, "password", .{ .salt = "abc", .rounds = 1000 }, &w); try testing.expectEqualStrings("pbkdf2_sha256$1000$abc$e/+7RSuHvTHideDuZkpvFXtq65+oHM9xONAsEVJaV6s=", w.buffered()); try testing.expect(try django_pbkdf2_sha256.verify(test_ctx, "password", w.buffered())); try testing.expect(try django_pbkdf2_sha256.needsUpdate(w.buffered(), .{ .min_desired_rounds = 2000 })); try testing.expect(!try django_pbkdf2_sha256.needsUpdate(w.buffered(), .{})); const a43 = "A" ** 43 ++ "="; try testing.expectError(error.MalformedHash, django_pbkdf2_sha256.verify(test_ctx, "x", "pbkdf2_sha256$01000$abc$" ++ a43)); try testing.expectError(error.MalformedHash, django_pbkdf2_sha256.verify(test_ctx, "x", "pbkdf2_sha256$1000$$" ++ a43)); try testing.expect(!try django_pbkdf2_sha256.verify(test_ctx, "x", "pbkdf2_sha256$1000$abc$" ++ a43));}
test "disabled" { var buf: [64]u8 = undefined; var w: Io.Writer = .fixed(&buf); try django_disabled.hash(test_ctx, "x", .{}, &w); try testing.expectEqual(@as(usize, 41), w.buffered().len); try testing.expect(!try django_disabled.verify(test_ctx, "x", w.buffered())); try testing.expectError(error.MalformedHash, django_disabled.verify(test_ctx, "x", ""));}
test "the wrappers reproduce passlib" { // passlib 1.7.4, with salts and costs fixed: // django_bcrypt_sha256.using(salt="abcdefghijklmnopqrstuu", rounds=4) // django_des_crypt.using(salt="ab") // django_bcrypt.using(salt="abcdefghijklmnopqrstuu", rounds=4) // django_argon2.using(salt=b"saltsaltsalt", rounds=1, memory_cost=64, parallelism=1) // each hashing "password". const cases = .{ .{ django_bcrypt_sha256, django_bcrypt_sha256.Options{ .salt = "abcdefghijklmnopqrstuu", .rounds = 4 }, "bcrypt_sha256$$2b$04$abcdefghijklmnopqrstuuavYyybW8SwBYgHrVfEOHIljvgCGgHr2" }, .{ django_des_crypt, django_des_crypt.Options{ .salt = "ab" }, "crypt$ab$abJnggxhB/yWI" }, .{ django_bcrypt, django_bcrypt.Options{ .salt = "abcdefghijklmnopqrstuu", .rounds = 4 }, "bcrypt$$2b$04$abcdefghijklmnopqrstuughE8Ev8uGFaUgY2cNEySvxngrb/Jzdm" }, .{ django_argon2, django_argon2.Options{ .salt = "saltsaltsalt", .rounds = 1, .memory_cost = 64, .parallelism = 1 }, "argon2$argon2i$v=19$m=64,t=1,p=1$c2FsdHNhbHRzYWx0$xWEeig1StJLLIR5JlmXX/ec33iRmwZB89/N6ARIdTXM" }, }; inline for (cases) |c| { var buf: [128]u8 = undefined; var w: Io.Writer = .fixed(&buf); try c[0].hash(test_ctx, "password", c[1], &w); try testing.expectEqualStrings(c[2], w.buffered()); try testing.expect(try c[0].verify(test_ctx, "password", c[2])); try testing.expect(!try c[0].verify(test_ctx, "passwore", c[2])); } // An empty salt field takes the salt from the DES hash. try testing.expect(try django_des_crypt.verify(test_ctx, "password", "crypt$$abJnggxhB/yWI")); try testing.expectError(error.MalformedHash, django_des_crypt.verify(test_ctx, "password", "crypt$xy$abJnggxhB/yWI"));}