Something went wrong. Try again.
passlib's password hash schemes, ported to Zig 0.16
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Parsing the way Python parses: CPython's lenient `binascii.a2b_base64`//! and `int()`.//!//! passlib reads the fields of many hashes with Python's own functions,//! and those are forgiving. `int()` takes surrounding whitespace, a sign,//! leading zeros and underscores between digits; `a2b_base64` skips//! characters outside the alphabet, lets `=` appear anywhere, and ignores//! stray bits in the last character. A hash that passlib verifies can//! therefore hold things a strict parser refuses. Reproducing passlib's//! verdict on a malformed hash means parsing it the same way, which is//! what these do.
const std = @import("std");const testing = std.testing;
const encoding = @import("encoding.zig");const handler = @import("handler.zig");const Error = handler.Error;
/// Python's `binascii.a2b_base64` in its default, lenient mode, as CPython/// 3.14 has it: characters outside the alphabet are skipped, `=` ends/// nothing, and a partial final group is accepted only if enough `=` follow/// its last character to complete it.pub const A2bBase64 = struct { dst: ?[]u8, len: usize = 0, quad: u2 = 0, left: u8 = 0, pads: usize = 0,
const table = blk: { var t = [_]u8{0xff} ** 256; for (encoding.base64_chars, 0..) |c, i| t[c] = i; break :blk t; };
fn emit(d: *A2bBase64, b: u8) Error!void { if (d.dst) |dst| { // Past the buffer, and output only grows, so too long whatever // follows. if (d.len >= dst.len) return error.MalformedHash; dst[d.len] = b; } d.len += 1; }
pub fn feed(d: *A2bBase64, c: u8) Error!void { if (c == '=') { if (d.quad >= 2) d.pads += 1; return; } const v = table[c]; if (v == 0xff) return; d.pads = 0; switch (d.quad) { 0 => { d.left = v; d.quad = 1; }, 1 => { try d.emit((d.left << 2) | (v >> 4)); d.left = v & 0x0f; d.quad = 2; }, 2 => { try d.emit((d.left << 4) | (v >> 2)); d.left = v & 0x03; d.quad = 3; }, 3 => { try d.emit((d.left << 6) | v); d.left = 0; d.quad = 0; }, } }
/// The number of bytes decoded, or `error.MalformedHash` where Python /// raises `binascii.Error`. pub fn finish(d: *A2bBase64) Error!usize { if (d.quad == 1) return error.MalformedHash; if (d.quad != 0 and @as(usize, d.quad) + d.pads < 4) return error.MalformedHash; return d.len; }};
/// Python's `base64.b64decode` without `validate`, which is/// `binascii.a2b_base64` of `src`. With `dst` null nothing is written and/// only the length is found; with it, a result longer than `dst` is/// `error.MalformedHash`.pub fn pythonB64Decode(dst: ?[]u8, src: []const u8) Error!usize { var d: A2bBase64 = .{ .dst = dst }; for (src) |c| try d.feed(c); return d.finish();}
/// passlib's `b64s_decode`: `=` added to make the length a multiple of four,/// then `binascii.a2b_base64`. A length one past a multiple of four is/// refused first. With `dst` null nothing is written and only the length is/// found; with it, a result longer than `dst` is `error.MalformedHash`.pub fn pythonB64sDecode(dst: ?[]u8, src: []const u8) Error!usize { const pad: usize = switch (src.len & 3) { 0 => 0, 1 => return error.MalformedHash, 2 => 2, 3 => 1, else => unreachable, }; var d: A2bBase64 = .{ .dst = dst }; for (src) |c| try d.feed(c); for (0..pad) |_| try d.feed('='); return d.finish();}
/// Python's `int()` of an ASCII string: surrounding whitespace, an optional/// sign, and decimal digits with single underscores between them. A value/// too large for `u64` saturates, since every field it reads has a maximum/// below that or is only compared for equality with a `u32`. A negative/// value is `error.MalformedHash`, since no field it reads may be negative.pub fn pythonInt(s_in: []const u8) Error!u64 { const s = std.mem.trim(u8, s_in, " \t\n\r\x0b\x0c"); if (s.len == 0) return error.MalformedHash; var i: usize = 0; var negative = false; if (s[0] == '+' or s[0] == '-') { negative = s[0] == '-'; i = 1; } const digits = s[i..]; if (digits.len == 0 or !std.ascii.isDigit(digits[0]) or !std.ascii.isDigit(digits[digits.len - 1])) return error.MalformedHash; var v: u64 = 0; var prev_underscore = false; for (digits) |c| { if (c == '_') { if (prev_underscore) return error.MalformedHash; prev_underscore = true; continue; } if (!std.ascii.isDigit(c)) return error.MalformedHash; prev_underscore = false; v = std.math.mul(u64, v, 10) catch std.math.maxInt(u64); v = std.math.add(u64, v, c - '0') catch std.math.maxInt(u64); } if (negative and v != 0) return error.MalformedHash; return v;}
test "a2b_base64 as CPython 3.14 has it" { // binascii.a2b_base64 of each, run in the devshell. const Case = struct { in: []const u8, out: ?[]const u8 }; for ([_]Case{ .{ .in = "YQ==YQ", .out = "a\x06\x10" }, .{ .in = "Y!Q==", .out = "a" }, .{ .in = "YQ=", .out = null }, .{ .in = "Y=Q=", .out = null }, .{ .in = "YW\nJj", .out = "abc" }, .{ .in = "=YWJj", .out = "abc" }, .{ .in = "YWI=YQ==", .out = null }, .{ .in = "YW=I=", .out = "ab" }, .{ .in = "Y===", .out = null }, .{ .in = "YQ=a=", .out = "a\x06" }, .{ .in = "====", .out = "" }, .{ .in = "!!!!", .out = "" }, }) |c| { var buf: [16]u8 = undefined; var d: A2bBase64 = .{ .dst = &buf }; for (c.in) |ch| try d.feed(ch); if (c.out) |want| { try testing.expectEqualSlices(u8, want, buf[0..try d.finish()]); } else { try testing.expectError(error.MalformedHash, d.finish()); } }}
test "pythonInt" { try testing.expectEqual(@as(u64, 5), try pythonInt(" +5\n")); try testing.expectEqual(@as(u64, 10), try pythonInt("1_0")); try testing.expectEqual(@as(u64, 10), try pythonInt("010")); try testing.expectEqual(@as(u64, 0), try pythonInt("-0")); for ([_][]const u8{ "", " ", "1__0", "_1", "1_", "0x10", "+-1", "+ 5", "-5", "5\x00", "\x1c5" }) |s| { try testing.expectError(error.MalformedHash, pythonInt(s)); } try testing.expectEqual(@as(u64, std.math.maxInt(u64)), try pythonInt("99999999999999999999999"));}
test "b64decode and b64s_decode" { // base64.b64decode, and passlib's b64s_decode, of each. var buf: [8]u8 = undefined; try testing.expectEqualSlices(u8, "ab", buf[0..try pythonB64Decode(&buf, "YW I=")]); try testing.expectError(error.MalformedHash, pythonB64Decode(&buf, "YWI")); try testing.expectEqual(@as(usize, 2), try pythonB64Decode(null, "YWI==")); try testing.expectEqualSlices(u8, "ab", buf[0..try pythonB64sDecode(&buf, "YWI")]); try testing.expectError(error.MalformedHash, pythonB64sDecode(&buf, "YWJjZ")); try testing.expectError(error.MalformedHash, pythonB64sDecode(buf[0..1], "YWI"));}