Something went wrong. Try again.
passlib's password hash schemes, ported to Zig 0.16
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! FSHP, the Fairly Secure Hashed Password: passlib's//! `passlib.handlers.fshp`.//!//! Berk D. Demir's format, 2008, for LDAP directories. It is PBKDF1 over//! SHA-1 or SHA-2 with the roles of password and salt swapped: the digest of//! the salt followed by the password, then the digest of that digest,//! `rounds` times in all. A hash is `{FSHP`, the variant, `|`, the salt's//! length in bytes, `|`, the round count, `}`, and the salt followed by the//! digest in padded base64. The variant chooses the digest: 0 for SHA-1, 1//! for SHA-256, 2 for SHA-384, and 3 for SHA-512.//!//! **It is obsolete.** PBKDF1 has been superseded by PBKDF2, and the format//! saw little use beyond the directories it was written for. It is here to//! check passwords already stored with it.
const std = @import("std");const Io = std.Io;const Allocator = std.mem.Allocator;const Sha1 = std.crypto.hash.Sha1;const sha2 = std.crypto.hash.sha2;const testing = std.testing;
const encoding = @import("../encoding.zig");const handler = @import("../handler.zig");const Context = handler.Context;const Error = handler.Error;const python = @import("../python.zig");
pub const ident = "{FSHP";pub const min_rounds = 1;pub const max_rounds = std.math.maxInt(u32);pub const default_salt_len = 16;/// The longest digest of any variant, SHA-512's.const max_digest_len = 64;
/// The digest a hash is built on, numbered as the format numbers them.pub const Variant = enum(u2) { sha1 = 0, sha256 = 1, sha384 = 2, sha512 = 3,
/// The length of the variant's digest, which is the checksum's length. pub fn digestLen(v: Variant) usize { return switch (v) { .sha1 => Sha1.digest_length, .sha256 => sha2.Sha256.digest_length, .sha384 => sha2.Sha384.digest_length, .sha512 => sha2.Sha512.digest_length, }; }};
/// PBKDF1 with `salt` as the secret and `password` as the salt, as FSHP/// uses it: `rounds` digests in all, the first of the salt then the/// password, each after it of the one before.fn pbkdf1(comptime H: type, salt: []const u8, password: []const u8, rounds: u32, out: *[H.digest_length]u8) void { var h = H.init(.{}); h.update(salt); h.update(password); h.final(out); for (1..rounds) |_| { const prev = out.*; H.hash(&prev, out, .{}); }}
/// The checksum for `password`, `salt` and `rounds` under `variant`, into/// the first `variant.digestLen()` bytes of `out`.fn compute(variant: Variant, password: []const u8, salt: []const u8, rounds: u32, out: *[max_digest_len]u8) []const u8 { const len = variant.digestLen(); switch (variant) { .sha1 => pbkdf1(Sha1, salt, password, rounds, out[0..Sha1.digest_length]), .sha256 => pbkdf1(sha2.Sha256, salt, password, rounds, out[0..32]), .sha384 => pbkdf1(sha2.Sha384, salt, password, rounds, out[0..48]), .sha512 => pbkdf1(sha2.Sha512, salt, password, rounds, out[0..64]), } return out[0..len];}
/// The parts of a hash, with the base64 data still encoded.const Parsed = struct { variant: Variant, salt_len: usize, rounds: u32, /// The base64 characters and their padding. data: []const u8,};
pub const fshp = struct { pub const name = "fshp";
pub const Options = struct { /// The salt, as raw bytes of any length. Null, the default, draws /// random bytes, `salt_size` of them. salt: ?[]const u8 = null, /// The length of a random salt in bytes. passlib's default is 16; /// FSHP's own is 8. salt_size: usize = default_salt_len, /// The number of rounds, from 1 to 4,294,967,295. passlib's default /// is 480,000; FSHP's own is 4096. rounds: u32 = 480_000, /// The digest to build on. variant: Variant = .sha256, /// `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 that starts with /// `{FSHP` is still identified as this scheme's. pub fn identify(h: []const u8) bool { return std.mem.startsWith(u8, h, ident); }
/// Up to and including the `|` or `}` ending a decimal field starting /// at `s[pos]`: the field's value, and where the next one starts. /// Leading zeros are allowed, as Python's `int` allows them. fn field(s: []const u8, pos: usize, end: u8) Error!struct { u64, usize } { const stop = std.mem.findScalarPos(u8, s, pos, end) orelse return error.MalformedHash; return .{ try handler.parseDecimal(u64, s[pos..stop], true), stop + 1 }; }
/// passlib's regular expression, /// `^\{FSHP(\d+)\|(\d+)\|(\d+)\}([a-zA-Z0-9+/]+={0,3})$`, then the checks /// its constructor makes. Python's `$` also matches just before a final /// newline, so a hash followed by one `\n` is accepted, as passlib /// accepts it. /// /// The data is decoded as Python's `b64decode` decodes it, by /// `python.pythonB64Decode`: unused bits in the last character are /// ignored, and padding is needed only to complete the last group, with /// any more of it ignored. fn parse(h_in: []const u8) Error!Parsed { const h = if (std.mem.endsWith(u8, h_in, "\n")) h_in[0 .. h_in.len - 1] else h_in; if (!identify(h)) return error.MalformedHash; const variant_num, const p1 = try field(h, ident.len, '|'); const salt_len, const p2 = try field(h, p1, '|'); const rounds, const p3 = try field(h, p2, '}');
const data = h[p3..]; var pads: usize = 0; while (pads < data.len and data[data.len - 1 - pads] == '=') pads += 1; if (pads > 3) return error.MalformedHash; const chars = data[0 .. data.len - pads]; if (chars.len == 0 or !encoding.allIn(chars, encoding.base64_chars)) return error.MalformedHash; const decoded_len = try python.pythonB64Decode(null, data);
if (variant_num > 3) return error.MalformedHash; const variant: Variant = @enumFromInt(variant_num); if (rounds < min_rounds or rounds > max_rounds) return error.MalformedHash; // passlib slices the salt off the decoded data, and what is left // must be exactly one digest. const checksum_len = decoded_len -| salt_len; if (checksum_len != variant.digestLen()) return error.MalformedHash; return .{ .variant = variant, .salt_len = @intCast(salt_len), .rounds = @intCast(rounds), .data = data, }; }
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; const salt_len = if (options.salt) |s| s.len else options.salt_size; const digest_len = options.variant.digestLen(); const raw = try ctx.gpa.alloc(u8, salt_len + digest_len); defer ctx.gpa.free(raw); const salt = raw[0..salt_len]; if (options.salt) |s| @memcpy(salt, s) else _ = try handler.randomBytes(ctx.io, salt); var digest: [max_digest_len]u8 = undefined; @memcpy(raw[salt_len..], compute(options.variant, password, salt, options.rounds, &digest));
const text = try ctx.gpa.alloc(u8, encoding.b64.encodedLen(raw.len)); defer ctx.gpa.free(text); try w.print("{s}{d}|{d}|{d}}}{s}", .{ ident, @intFromEnum(options.variant), salt_len, options.rounds, encoding.b64.encode(text, raw), }); }
pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { try handler.checkPasswordLen(password); const parsed = try parse(h); // `parse` has held the decoded data to one salt and one digest. const raw = try ctx.gpa.alloc(u8, parsed.salt_len + parsed.variant.digestLen()); defer ctx.gpa.free(raw); _ = try python.pythonB64Decode(raw, parsed.data); const salt = raw[0..parsed.salt_len]; var digest: [max_digest_len]u8 = undefined; return handler.eql(raw[parsed.salt_len..], compute(parsed.variant, password, salt, parsed.rounds, &digest)); }
/// True when the hash's rounds fall outside `min_desired_rounds` and /// `max_desired_rounds`. The variant is not compared, as passlib does /// not compare it. 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 = .{fshp};
comptime { handler.check(fshp);}
const test_ctx: Context = .{ .io = testing.io, .gpa = testing.allocator };
test "fixed salts reproduce passlib" { // passlib 1.7.4: fshp.using(salt=..., rounds=..., variant=...).hash(...). const cases = .{ .{ "test", "12345678", 4096, Variant.sha256, "{FSHP1|8|4096}MTIzNDU2NzjTdHcmoXwNc0ff9+ArUHoN0CvlbPZpxFi1C6RDM/MHSA==" }, .{ "test", "", 1, Variant.sha1, "{FSHP0|0|1}qUqP5cyxm6YcTAhz05Hph5gvu9M=" }, .{ "test", "saltsalt", 10, Variant.sha384, "{FSHP2|8|10}c2FsdHNhbHRwMACB/MqoM2/4pfdrppxEEgaVveJ9q3TkxBnIwjyC7hcQmkw3b2UdFGvimaZX4jo=" }, .{ "test", "saltsalt", 10, Variant.sha512, "{FSHP3|8|10}c2FsdHNhbHStDFfbym346PU03g1tBULafhjV6na9tgN0bp4TSaSmXV1TKeb9ypE8bmCFrLX24MiytAwn+oyoxD+F1IlL2ien" }, .{ "t\x00est", "saltsalt", 10, Variant.sha384, "{FSHP2|8|10}c2FsdHNhbHT73OhblQ645hVo2mQQQCqBVCn2fWflTbYZ+9wCrKWecewiw8rZfBYYcoRXE2+vKtQ=" }, }; inline for (cases) |c| { var buf: [160]u8 = undefined; var w: Io.Writer = .fixed(&buf); try fshp.hash(test_ctx, c[0], .{ .salt = c[1], .rounds = c[2], .variant = c[3] }, &w); try testing.expectEqualStrings(c[4], w.buffered()); try testing.expect(try fshp.verify(test_ctx, c[0], c[4])); }}
test "round trip with a random salt" { var buf: [160]u8 = undefined; var w: Io.Writer = .fixed(&buf); try fshp.hash(test_ctx, "hunter2", .{ .rounds = 100 }, &w); const h = w.buffered(); try testing.expect(std.mem.startsWith(u8, h, "{FSHP1|16|100}")); try testing.expect(try fshp.verify(test_ctx, "hunter2", h)); try testing.expect(!try fshp.verify(test_ctx, "hunter3", h));}
test "what passlib's parsing lets through" { // Each of these verifies in passlib 1.7.4: a trailing newline, surplus // padding, unused bits set in the last character, zero-padded fields. const accepted = [_][]const u8{ "{FSHP0|0|1}qUqP5cyxm6YcTAhz05Hph5gvu9M=\n", "{FSHP0|0|1}qUqP5cyxm6YcTAhz05Hph5gvu9M==", "{FSHP0|0|1}qUqP5cyxm6YcTAhz05Hph5gvu9M===", "{FSHP0|0|1}qUqP5cyxm6YcTAhz05Hph5gvu9N=", "{FSHP00|0|01}qUqP5cyxm6YcTAhz05Hph5gvu9M=", }; for (accepted) |h| try testing.expect(try fshp.verify(test_ctx, "test", h));}
test "refusals" { const refused = [_][]const u8{ "{FSHP0|0|1}qUqP5cyxm6YcTAhz05Hph5gvu9M", "{FSHP0|0|1}qUqP5cyxm6YcTAhz05Hph5gvu9M====", "{FSHP4|0|1}qUqP5cyxm6YcTAhz05Hph5gvu9M=", "{FSHP0|1|0}qUqP5cyxm6YcTAhz05Hph5gvu9M=", "{FSHP0|1|1}qUqP5cyxm6YcTAhz05Hph5gvu9M=", "{FSHP0|99|1}qUqP5cyxm6YcTAhz05Hph5gvu9M=", "{FSHP0|0|A}qUqP5cyxm6YcTAhz05Hph5gvu9M=", "{FSHP0|0|1}qUqP5cyxm6YcTAhz05Hph5gvu9M=\n\n", "{FSHP0|0|1}", "{FSHP|0|1}qUqP5cyxm6YcTAhz05Hph5gvu9M=", "{FSHP0|0|4294967296}qUqP5cyxm6YcTAhz05Hph5gvu9M=", }; for (refused) |h| try testing.expectError(error.MalformedHash, fshp.verify(test_ctx, "test", h));
var buf: [160]u8 = undefined; var w: Io.Writer = .fixed(&buf); try testing.expectError(error.InvalidOptions, fshp.hash(test_ctx, "x", .{ .rounds = 0 }, &w));}
test "needsUpdate" { const h = "{FSHP1|8|4096}MTIzNDU2NzjTdHcmoXwNc0ff9+ArUHoN0CvlbPZpxFi1C6RDM/MHSA=="; try testing.expect(!try fshp.needsUpdate(h, .{})); try testing.expect(try fshp.needsUpdate(h, .{ .min_desired_rounds = 5000 })); try testing.expect(try fshp.needsUpdate(h, .{ .max_desired_rounds = 4000 })); try testing.expect(!try fshp.needsUpdate(h, .{ .variant = .sha512 }));}