// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The encodings password hashes are written in. //! //! There are more than there should be. Standard base64 is only one of them. //! Most of the Unix `crypt` formats use a different alphabet (`h64`, starting //! `./0-9`), and different formats pack bits into it in opposite orders. //! bcrypt has an alphabet of its own. passlib's own formats use "adapted" //! base64, with `.` in place of `+` and no padding. A decoder that gets the //! alphabet or the bit order wrong still produces bytes, just the wrong ones. //! //! `Engine` is passlib's `Base64Engine`: an alphabet and a bit order, with //! the byte, integer and transposed-byte encodings the `crypt` formats are //! written with. `h64`, `h64big` and `bcrypt64` are its three instances. //! `ab64` and `b64s` are passlib's unpadded standard base64, with and without //! the `.` substitution. //! //! Every decoder here returns `error.MalformedHash` on input it cannot //! decode, never a panic, since what it decodes is a stored hash that may be //! damaged or hostile. const std = @import("std"); const testing = std.testing; /// The alphabet of the Unix `crypt` family: `./`, digits, then upper and /// lower case letters. Also the order the characters sort in. pub const hash64_chars = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; /// bcrypt's alphabet: `./`, then upper and lower case letters, then digits. pub const bcrypt_chars = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; /// RFC 4648 base64. pub const base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// passlib's adapted base64: standard base64 with `.` for `+`. pub const ab64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789./"; pub const hex_chars = "0123456789abcdefABCDEF"; pub const lower_hex_chars = "0123456789abcdef"; pub const upper_hex_chars = "0123456789ABCDEF"; pub const Error = error{MalformedHash}; /// Whether every byte of `s` is one of `chars`. pub fn allIn(s: []const u8, comptime chars: []const u8) bool { const table = comptime membership(chars); for (s) |c| if (!table[c]) return false; return true; } fn membership(comptime chars: []const u8) [256]bool { var table = [_]bool{false} ** 256; for (chars) |c| table[c] = true; return table; } /// An alphabet of 64 characters and the order bits are packed into it. /// /// Little-endian packing, `h64`'s, puts the low bits of each byte into the /// first character. Big-endian packing, used by `h64big` and bcrypt, puts the /// high bits first, as RFC 4648 does. A final group short of three bytes /// leaves unused bits in its last character: its top bits when little-endian, /// its low bits when big-endian. pub fn Engine(comptime charmap: *const [64]u8, comptime big: bool) type { return struct { pub const chars = charmap; pub const big_endian = big; const decode_table = blk: { var table = [_]u8{0xff} ** 256; for (charmap, 0..) |c, i| table[c] = i; break :blk table; }; /// The value of character `c`, or null if it is not in the alphabet. pub fn value(c: u8) ?u6 { const v = decode_table[c]; return if (v == 0xff) null else @intCast(v); } pub fn char(v: u6) u8 { return charmap[v]; } pub fn isValid(s: []const u8) bool { for (s) |c| if (decode_table[c] == 0xff) return false; return true; } /// Encoded length of `n` bytes: four characters per three bytes, and /// two or three for a final partial group. pub fn encodedLen(n: usize) usize { return (n / 3) * 4 + switch (n % 3) { 0 => @as(usize, 0), 1 => 2, else => 3, }; } /// Decoded length of `n` characters, or `error.MalformedHash` for a /// length that is one more than a multiple of four, which cannot /// hold a whole byte. pub fn decodedLen(n: usize) Error!usize { return (n / 4) * 3 + switch (n % 4) { 0 => @as(usize, 0), 1 => return error.MalformedHash, 2 => 1, else => 2, }; } /// Encodes `src` into `dst`, which must be `encodedLen(src.len)` /// long, and returns it. pub fn encode(dst: []u8, src: []const u8) []u8 { std.debug.assert(dst.len >= encodedLen(src.len)); var o: usize = 0; var i: usize = 0; while (i < src.len) : (i += 3) { const n: usize = @min(3, src.len - i); const v1: u32 = src[i]; const v2: u32 = if (n > 1) src[i + 1] else 0; const v3: u32 = if (n > 2) src[i + 2] else 0; var out: [4]u32 = undefined; if (big) { out = .{ v1 >> 2, ((v1 & 0x03) << 4) | (v2 >> 4), ((v2 & 0x0f) << 2) | (v3 >> 6), v3 & 0x3f }; } else { out = .{ v1 & 0x3f, ((v2 & 0x0f) << 2) | (v1 >> 6), ((v3 & 0x03) << 4) | (v2 >> 4), v3 >> 2 }; } for (out[0 .. n + 1]) |v| { dst[o] = charmap[@intCast(v)]; o += 1; } } return dst[0..o]; } /// Decodes `src` into `dst`, which must be `decodedLen(src.len)` /// long, and returns it. The unused bits of a final partial group /// are ignored, as passlib ignores them. pub fn decode(dst: []u8, src: []const u8) Error![]u8 { const len = try decodedLen(src.len); std.debug.assert(dst.len >= len); var o: usize = 0; var i: usize = 0; while (i < src.len) : (i += 4) { const n: usize = @min(4, src.len - i); var v: [4]u32 = .{ 0, 0, 0, 0 }; for (0..n) |k| v[k] = value(src[i + k]) orelse return error.MalformedHash; var out: [3]u8 = undefined; if (big) { out = .{ @truncate((v[0] << 2) | (v[1] >> 4)), @truncate(((v[1] & 0xf) << 4) | (v[2] >> 2)), @truncate(((v[2] & 0x3) << 6) | v[3]), }; } else { out = .{ @truncate(v[0] | ((v[1] & 0x3) << 6)), @truncate((v[1] >> 2) | ((v[2] & 0xf) << 4)), @truncate((v[2] >> 4) | (v[3] << 2)), }; } @memcpy(dst[o..][0 .. n - 1], out[0 .. n - 1]); o += n - 1; } return dst[0..o]; } /// The bits of the last character that encode nothing, for an /// encoding `len` characters long. fn unusedMask(len: usize) u6 { return switch (len % 4) { 2 => if (big) 0x0f else 0x3c, 3 => if (big) 0x03 else 0x30, else => 0, }; } /// Whether the unused bits of the last character are clear, as an /// encoder would have left them. passlib calls a string that fails /// this one with "dirty" padding bits. pub fn hasCleanPadding(src: []const u8) bool { if (src.len == 0) return true; const v = value(src[src.len - 1]) orelse return false; return v & unusedMask(src.len) == 0; } /// `src`'s last character with its unused bits cleared, as passlib's /// `repair_unused` makes it. The character is invalid if it is not /// in the alphabet, and is then returned unchanged. pub fn repairedLast(src: []const u8) u8 { const last = src[src.len - 1]; const v = value(last) orelse return last; return charmap[v & ~unusedMask(src.len)]; } /// `bits` of `v` as `ceil(bits / 6)` characters. The spare bits of a /// width that is not a multiple of six are at the top of the last /// character when little-endian and at the bottom of the first /// character's worth when big-endian, as passlib's `_encode_int` has /// them. pub fn encodeInt(comptime bits: u16, dst: *[(bits + 5) / 6]u8, v: std.meta.Int(.unsigned, bits)) void { const n = (bits + 5) / 6; const pad = n * 6 - bits; const W = std.meta.Int(.unsigned, n * 6); const wide: W = if (big) @as(W, v) << pad else v; for (0..n) |k| { const shift: std.math.Log2Int(W) = @intCast(if (big) (n - 1 - k) * 6 else k * 6); dst[k] = charmap[@as(u6, @truncate(wide >> shift))]; } } /// The inverse of `encodeInt`. The spare bits are discarded. pub fn decodeInt(comptime bits: u16, src: *const [(bits + 5) / 6]u8) Error!std.meta.Int(.unsigned, bits) { const n = (bits + 5) / 6; const pad = n * 6 - bits; const W = std.meta.Int(.unsigned, n * 6); var wide: W = 0; for (0..n) |k| { const c = if (big) src[k] else src[n - 1 - k]; const v = value(c) orelse return error.MalformedHash; wide = if (n == 1) v else (wide << 6) | v; } return @truncate(if (big) wide >> pad else wide); } /// `src` reordered by `offsets`, then encoded: the transposition the /// MD5 and SHA `crypt` formats apply before encoding their digests. pub fn encodeTransposed(dst: []u8, src: []const u8, comptime offsets: []const u8) []u8 { var tmp: [offsets.len]u8 = undefined; inline for (offsets, 0..) |off, k| tmp[k] = src[off]; return encode(dst, &tmp); } /// The inverse of `encodeTransposed`. `dst` must be `offsets.len` /// long, and `src` must encode exactly that many bytes. pub fn decodeTransposed(dst: []u8, src: []const u8, comptime offsets: []const u8) Error!void { if ((try decodedLen(src.len)) != offsets.len) return error.MalformedHash; var tmp: [offsets.len]u8 = undefined; _ = try decode(&tmp, src); inline for (offsets, 0..) |off, k| dst[off] = tmp[k]; } }; } /// The `crypt` alphabet, packed little-endian: MD5-crypt, SHA-crypt, and /// most of the rest of the Unix family. pub const h64 = Engine(hash64_chars, false); /// The `crypt` alphabet, packed big-endian: the DES `crypt` formats. pub const h64big = Engine(hash64_chars, true); /// bcrypt's alphabet, packed big-endian. pub const bcrypt64 = Engine(bcrypt_chars, true); /// RFC 4648 base64 without padding, as an engine, for code that wants the /// engine interface over the standard alphabet. pub const std64 = Engine(base64_chars, true); /// passlib's adapted base64 as an engine: `ab64` for strings, this for the /// engine interface. pub const ab64_engine = Engine(ab64_chars, true); /// passlib's `b64s`: RFC 4648 base64 with the padding left off. pub const b64s = struct { pub fn encodedLen(n: usize) usize { return std64.encodedLen(n); } pub fn decodedLen(n: usize) Error!usize { return std64.decodedLen(n); } pub fn encode(dst: []u8, src: []const u8) []u8 { return std64.encode(dst, src); } pub fn decode(dst: []u8, src: []const u8) Error![]u8 { return std64.decode(dst, src); } }; /// passlib's `ab64`: unpadded base64 with `.` for `+`. Decoding accepts `+` /// as well, as passlib's does. pub const ab64 = struct { pub fn encodedLen(n: usize) usize { return std64.encodedLen(n); } pub fn decodedLen(n: usize) Error!usize { return std64.decodedLen(n); } pub fn encode(dst: []u8, src: []const u8) []u8 { return ab64_engine.encode(dst, src); } pub fn decode(dst: []u8, src: []const u8) Error![]u8 { const len = try decodedLen(src.len); std.debug.assert(dst.len >= len); var o: usize = 0; var i: usize = 0; var group: [4]u8 = undefined; while (i < src.len) : (i += 4) { const n: usize = @min(4, src.len - i); for (0..n) |k| group[k] = if (src[i + k] == '+') '.' else src[i + k]; const out = try ab64_engine.decode(dst[o..], group[0..n]); o += out.len; } return dst[0..o]; } }; /// RFC 4648 base64 with padding, which the LDAP `{SSHA}` family and Django /// use. /// /// Decoding follows Python's `base64.b64decode`, since passlib reads these /// hashes with it: a final group of two characters needs `==`, one of three /// needs `=`, a complete final group may be followed by up to two `=` that /// are ignored, and the unused bits of the last character are ignored rather /// than checked. Anything else is `error.MalformedHash`. pub const b64 = struct { pub fn encodedLen(n: usize) usize { return std.base64.standard.Encoder.calcSize(n); } pub fn encode(dst: []u8, src: []const u8) []const u8 { return std.base64.standard.Encoder.encode(dst, src); } /// `src` split into its characters and its padding, if Python would /// accept the padding. fn unpad(src: []const u8) Error![]const u8 { var n = src.len; while (n > 0 and src.len - n < 2 and src[n - 1] == '=') n -= 1; const pads = src.len - n; const data = src[0..n]; switch (data.len % 4) { 0 => {}, 1 => return error.MalformedHash, 2 => if (pads != 2) return error.MalformedHash, else => if (pads < 1) return error.MalformedHash, } return data; } /// The decoded length, or `error.MalformedHash`. pub fn decodedLen(src: []const u8) Error!usize { return std64.decodedLen((try unpad(src)).len); } pub fn decode(dst: []u8, src: []const u8) Error![]u8 { return std64.decode(dst, try unpad(src)); } }; /// Lower-case hex into `dst`, which must be twice `src`'s length. pub fn hexLower(dst: []u8, src: []const u8) []u8 { for (src, 0..) |b, i| { dst[2 * i] = lower_hex_chars[b >> 4]; dst[2 * i + 1] = lower_hex_chars[b & 0xf]; } return dst[0 .. 2 * src.len]; } /// Upper-case hex into `dst`, which must be twice `src`'s length. pub fn hexUpper(dst: []u8, src: []const u8) []u8 { for (src, 0..) |b, i| { dst[2 * i] = upper_hex_chars[b >> 4]; dst[2 * i + 1] = upper_hex_chars[b & 0xf]; } return dst[0 .. 2 * src.len]; } /// Hex of either case into `dst`, which must be half `src`'s length. pub fn hexDecode(dst: []u8, src: []const u8) Error![]u8 { if (src.len % 2 != 0) return error.MalformedHash; return std.fmt.hexToBytes(dst[0 .. src.len / 2], src) catch error.MalformedHash; } // -- tests ------------------------------------------------------------------ test "h64 bytes agree with passlib" { // passlib 1.7.4: h64.encode_bytes(b"\x00\x01\x02\xfd\xfe\xff\x10") and // the same through h64big. var buf: [16]u8 = undefined; const src = "\x00\x01\x02\xfd\xfe\xff\x10"; try testing.expectEqualStrings(".2U.xvzzE.", h64.encode(&buf, src)); try testing.expectEqualStrings("..20zTvz2.", h64big.encode(&buf, src)); var back: [8]u8 = undefined; try testing.expectEqualSlices(u8, src, try h64.decode(&back, ".2U.xvzzE.")); try testing.expectEqualSlices(u8, src, try h64big.decode(&back, "..20zTvz2.")); } test "lengths one past a multiple of four are refused" { var buf: [8]u8 = undefined; try testing.expectError(error.MalformedHash, h64.decode(&buf, "abcde")); try testing.expectError(error.MalformedHash, h64.decode(&buf, "ab!d")); } test "integers agree with passlib" { // h64.encode_int12(0x9e6) == b"ab", h64big.encode_int64(0x573b2cf6d341fa25) // == b"JnggxhB/yWI", h64.encode_int24(0x123456) and h64big's. var two: [2]u8 = undefined; h64.encodeInt(12, &two, 0x9e6); try testing.expectEqualStrings("ab", &two); try testing.expectEqual(@as(u12, 0x9e6), try h64.decodeInt(12, "ab")); var eleven: [11]u8 = undefined; h64big.encodeInt(64, &eleven, 0x573b2cf6d341fa25); try testing.expectEqualStrings("JnggxhB/yWI", &eleven); try testing.expectEqual(@as(u64, 0x573b2cf6d341fa25), try h64big.decodeInt(64, "JnggxhB/yWI")); var four: [4]u8 = undefined; h64.encodeInt(24, &four, 0x123456); try testing.expectEqualStrings("KFX2", &four); h64big.encodeInt(24, &four, 0x123456); try testing.expectEqualStrings("2XFK", &four); var one: [1]u8 = undefined; h64.encodeInt(6, &one, 63); try testing.expectEqualStrings("z", &one); try testing.expectEqual(@as(u6, 63), try h64.decodeInt(6, "z")); } test "padding bits" { // Two characters hold one byte and leave four bits spare. // passlib: h64.check_repair_unused("zD") and ("zz") both repair to // "z1", and "z3" repairs to "z/". try testing.expect(h64.hasCleanPadding("z1")); try testing.expect(!h64.hasCleanPadding("zD")); try testing.expect(!h64.hasCleanPadding("zz")); try testing.expectEqual(@as(u8, '/'), h64.repairedLast("z3")); try testing.expectEqual(@as(u8, '1'), h64.repairedLast("zz")); try testing.expect(bcrypt64.hasCleanPadding("..e")); try testing.expect(!bcrypt64.hasCleanPadding("../")); } test "ab64 decodes both spellings" { var buf: [8]u8 = undefined; var enc: [8]u8 = undefined; const src = "\xfb\xef\xbe"; try testing.expectEqualStrings("..../AA", ab64.encode(&enc, src ++ "\xfc\x00")); try testing.expectEqualSlices(u8, src, try ab64.decode(&buf, "....")); try testing.expectEqualSlices(u8, src, try ab64.decode(&buf, "++++")); } test "padded base64 as Python reads it" { // Python 3: base64.b64decode on each of these. var buf: [8]u8 = undefined; try testing.expectEqualSlices(u8, "ab", try b64.decode(&buf, "YWI=")); try testing.expectEqualSlices(u8, "\x00\x00", try b64.decode(&buf, "AAB=")); try testing.expectEqualSlices(u8, "\x00\x00\x00", try b64.decode(&buf, "AAAA==")); try testing.expectEqualSlices(u8, "\x00", try b64.decode(&buf, "AA==")); for ([_][]const u8{ "YWI", "AA=", "A", "AAAAA=", "AAAAAA=" }) |bad| { try testing.expectError(error.MalformedHash, b64.decode(&buf, bad)); } }