// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! scrypt: passlib's `passlib.handlers.scrypt`. //! //! Colin Percival's key derivation function, 2009, standardized as RFC 7914. //! It fills a table of `N = 2^ln` blocks of `128 * r` bytes from the password //! and salt, then reads it back in an order that depends on its contents, so //! computing it needs the whole table in memory at once. Memory is what //! makes guessing expensive on GPUs and custom hardware, and scrypt makes it //! the cost. `p` runs that many independent tables one after another. //! //! passlib's format is its own: `$scrypt$ln=16,r=8,p=1$$`, //! with the salt and the 32-byte checksum in base64 without padding. passlib //! also reads and writes the `$7$` format of Percival's reference `crypt`, //! where the parameters are packed into eleven `crypt` base64 characters and //! the salt is the text between them and the `$`, used as it stands. //! //! ## Quirks //! //! **passlib reads the numbers with Python's `int()`.** Leading zeros, a //! `+`, surrounding spaces and underscores between digits are all accepted, //! and so they are here. //! //! **passlib decodes the base64 with Python's `binascii`.** It skips //! characters outside the alphabet, ignores stray bits, and lets `=` appear //! anywhere. `python.zig`'s decoder does the same, so a hash passlib verifies //! verifies here. //! //! **Some parameters passlib accepts cannot be computed.** passlib hands the //! work to Python's `hashlib.scrypt`, which is OpenSSL's, and those refuse //! `r = 1` with more than 2^15 blocks, and anything passlib estimates needs //! more than 2 GiB. A hash with such parameters is an error to verify and an //! error to write, as it is in passlib. `std`'s own implementation stops //! short of that: with `p * 128 * r` of 2^30 or more it overflows its //! arithmetic, so such parameters are `error.WeakParameters` here, which is //! what `std` returns for the other sizes it cannot handle. const std = @import("std"); const Io = std.Io; 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; const python = @import("../python.zig"); const pythonInt = python.pythonInt; const pythonB64sDecode = python.pythonB64sDecode; pub const checksum_len = 32; pub const max_salt_len = 1024; pub const min_rounds = 1; pub const max_rounds = 31; pub const default_rounds = 16; pub const default_block_size = 8; pub const default_salt_size = 16; /// Why `checkComputable` refused a set of parameters. const Uncomputable = enum { /// OpenSSL, through `hashlib`, refuses them: passlib raises ValueError. backend, /// passlib would compute them and `std` cannot. std, }; /// The limits on `N = 2^ln`, `r` and `p` beyond passlib's own checks: those /// of passlib's `validate`, of `hashlib.scrypt` and OpenSSL behind it, which /// is what passlib 1.7.4 computes scrypt with, and of `std`. fn checkComputable(ln: u5, r: u64, p: u64) ?Uncomputable { const max_rp = (1 << 30) - 1; const rp = std.math.mul(u64, r, p) catch return .backend; if (rp > max_rp) return .backend; // OpenSSL: N < 2^(16 r), which only binds for r = 1. if (r == 1 and ln >= 16) return .backend; // passlib's `estimate_maxmem`, which `hashlib` requires to fit a C int. const n: u128 = @as(u128, 1) << ln; const bytes: u128 = @as(u128, r) * (128 * @as(u128, p) + 32 * (n + 2) * 4); const maxmem = @trunc(@as(f64, @floatFromInt(bytes)) * 1.05); if (maxmem > std.math.maxInt(i32)) return .backend; // `std` sizes its buffer as `p * 128 * r` in a u30. if (rp * 128 >= 1 << 30) return .std; return null; } /// The 32-byte scrypt of `password` and `salt` with `N = 2^ln`, into `out`. fn compute(gpa: std.mem.Allocator, password: []const u8, salt: []const u8, ln: u5, r: u64, p: u64, out: *[checksum_len]u8) Error!void { try std.crypto.pwhash.scrypt.kdf(gpa, out, password, salt, .{ .ln = ln, // `checkComputable` has held `r * p` under 2^23. .r = @intCast(r), .p = @intCast(p), }); } /// passlib's `scrypt`. pub const scrypt = struct { pub const name = "scrypt"; /// The format to write. pub const Ident = enum { /// passlib's own `$scrypt$ln=,r=,p=$salt$checksum`. scrypt, /// The reference implementation's `$7$`. @"7", }; pub const Options = struct { /// The format to write. passlib's default is its own. ident: Ident = .scrypt, /// The salt, as bytes, up to 1024 of them. For `$7$` it is written /// as it stands, so it must be ASCII and hold no `$`. Null, the /// default, draws `salt_size` random bytes; for `$7$` those are /// written in base64, as passlib writes them. salt: ?[]const u8 = null, /// The length of a random salt in bytes, up to 1024. salt_size: u16 = default_salt_size, /// `ln`, the log2 of `N`, 1 to 31. Memory and time both double with /// each step. rounds: u8 = default_rounds, /// `r`, the block size. `needsUpdate` reports any other. block_size: u32 = default_block_size, /// `p`, the parallelism. `needsUpdate` reports any other. parallelism: u32 = 1, /// `needsUpdate` reports a hash with a smaller `ln` than this, and /// `hash` raises `rounds` to it. min_desired_rounds: ?u32 = null, /// `needsUpdate` reports a hash with a larger `ln` than this, and /// `hash` lowers `rounds` to it. max_desired_rounds: ?u32 = null, }; pub fn identify(h: []const u8) bool { return std.mem.startsWith(u8, h, "$scrypt$") or std.mem.startsWith(u8, h, "$7$"); } const Parsed = struct { ident: Ident, rounds: u5, block_size: u64, parallelism: u64, salt: []const u8, checksum: ?[checksum_len]u8, }; /// passlib's `from_string`, with the salt decoded into `salt_buf` or, /// for `$7$`, a slice of `h`. A configuration string parses with /// `checksum` null. fn parse(h: []const u8, salt_buf: *[max_salt_len]u8) Error!Parsed { // passlib decodes the whole hash as ASCII first. for (h) |c| if (c >= 0x80) return error.MalformedHash; var p: Parsed = undefined; var rounds: u64 = undefined; if (std.mem.startsWith(u8, h, "$scrypt$")) { p.ident = .scrypt; var parts: [3][]const u8 = undefined; var n: usize = 0; var it = std.mem.splitScalar(u8, h["$scrypt$".len..], '$'); while (it.next()) |part| : (n += 1) { if (n == 3) return error.MalformedHash; parts[n] = part; } if (n < 2) return error.MalformedHash; const settings = try handler.splitExact(3, parts[0], ','); if (!std.mem.startsWith(u8, settings[0], "ln=") or !std.mem.startsWith(u8, settings[1], "r=") or !std.mem.startsWith(u8, settings[2], "p=")) return error.MalformedHash; rounds = try pythonInt(settings[0][3..]); p.block_size = try pythonInt(settings[1][2..]); p.parallelism = try pythonInt(settings[2][2..]); p.salt = salt_buf[0..try pythonB64sDecode(salt_buf, parts[1])]; p.checksum = null; if (n == 3 and parts[2].len > 0) { var checksum_buf: [checksum_len + 3]u8 = undefined; const len = try pythonB64sDecode(&checksum_buf, parts[2]); if (len != checksum_len) return error.MalformedHash; p.checksum = checksum_buf[0..checksum_len].*; } } else if (std.mem.startsWith(u8, h, "$7$")) { p.ident = .@"7"; const rest = h["$7$".len..]; const params, const digest = if (std.mem.findScalar(u8, rest, '$')) |d| .{ rest[0..d], @as(?[]const u8, rest[d + 1 ..]) } else .{ rest, @as(?[]const u8, null) }; if (digest) |d| if (std.mem.findScalar(u8, d, '$') != null) return error.MalformedHash; if (params.len < 11) return error.MalformedHash; rounds = try h64.decodeInt(6, params[0..1]); p.block_size = try h64.decodeInt(30, params[1..6]); p.parallelism = try h64.decodeInt(30, params[6..11]); p.salt = params[11..]; p.checksum = null; if (digest) |d| if (d.len > 0) { if ((try h64.decodedLen(d.len)) != checksum_len) return error.MalformedHash; var checksum: [checksum_len]u8 = undefined; _ = try h64.decode(&checksum, d); p.checksum = checksum; }; } else return error.MalformedHash; if (rounds < min_rounds or rounds > max_rounds) return error.MalformedHash; p.rounds = @intCast(rounds); if (p.block_size < 1 or p.parallelism < 1) return error.MalformedHash; if (p.salt.len > max_salt_len) return error.MalformedHash; return p; } fn checkDesired(options: Options) Error!void { if (options.min_desired_rounds) |m| if (m < min_rounds or m > max_rounds) return error.InvalidOptions; if (options.max_desired_rounds) |m| if (m < min_rounds or m > max_rounds) return error.InvalidOptions; if (options.min_desired_rounds != null and options.max_desired_rounds != null and options.max_desired_rounds.? < options.min_desired_rounds.?) return error.InvalidOptions; } /// What passlib's `using()` checks, and the rounds `hash` will use. fn checkOptions(options: Options) Error!u5 { if (options.rounds < min_rounds or options.rounds > max_rounds) return error.InvalidOptions; if (options.block_size < 1 or options.parallelism < 1) return error.InvalidOptions; if (options.salt_size > max_salt_len) return error.InvalidOptions; if (options.salt) |s| if (s.len > max_salt_len) return error.InvalidOptions; try checkDesired(options); var r: u32 = options.rounds; if (options.min_desired_rounds) |m| r = @max(r, m); if (options.max_desired_rounds) |m| r = @min(r, m); return @intCast(r); } pub fn hash(ctx: Context, password: []const u8, options: Options, w: *Io.Writer) Error!void { const ln = try checkOptions(options); if (checkComputable(ln, options.block_size, options.parallelism)) |why| return switch (why) { .backend => error.InvalidOptions, .std => error.WeakParameters, }; try handler.checkPasswordLen(password); var random: [max_salt_len]u8 = undefined; var encoded: [encoding.b64s.encodedLen(max_salt_len)]u8 = undefined; const salt: []const u8 = if (options.salt) |s| blk: { if (options.ident == .@"7") { for (s) |c| if (c >= 0x80 or c == '$') return error.InvalidOptions; } break :blk s; } else blk: { // Encoded, the salt must still fit in 1024 characters: passlib's // constructor checks the salt it generated. if (options.ident == .@"7" and encoding.b64s.encodedLen(options.salt_size) > max_salt_len) return error.InvalidOptions; const bytes = try handler.randomBytes(ctx.io, random[0..options.salt_size]); break :blk switch (options.ident) { .scrypt => bytes, .@"7" => encoding.b64s.encode(&encoded, bytes), }; }; var checksum: [checksum_len]u8 = undefined; try compute(ctx.gpa, password, salt, ln, options.block_size, options.parallelism, &checksum); switch (options.ident) { .scrypt => { var salt_b64: [encoding.b64s.encodedLen(max_salt_len)]u8 = undefined; var checksum_b64: [encoding.b64s.encodedLen(checksum_len)]u8 = undefined; try w.print("$scrypt$ln={d},r={d},p={d}${s}${s}", .{ ln, options.block_size, options.parallelism, encoding.b64s.encode(&salt_b64, salt), encoding.b64s.encode(&checksum_b64, &checksum), }); }, .@"7" => { var params: [11]u8 = undefined; h64.encodeInt(6, params[0..1], ln); // `checkComputable` has held both under 2^30. h64.encodeInt(30, params[1..6], @intCast(options.block_size)); h64.encodeInt(30, params[6..11], @intCast(options.parallelism)); var checksum_h64: [h64.encodedLen(checksum_len)]u8 = undefined; try w.print("$7${s}{s}${s}", .{ ¶ms, salt, h64.encode(&checksum_h64, &checksum) }); }, } } pub fn verify(ctx: Context, password: []const u8, h: []const u8) Error!bool { var salt_buf: [max_salt_len]u8 = undefined; const parsed = try parse(h, &salt_buf); const stored = parsed.checksum orelse return error.MalformedHash; try handler.checkPasswordLen(password); if (checkComputable(parsed.rounds, parsed.block_size, parsed.parallelism)) |why| return switch (why) { .backend => error.MalformedHash, .std => error.WeakParameters, }; var checksum: [checksum_len]u8 = undefined; try compute(ctx.gpa, password, parsed.salt, parsed.rounds, parsed.block_size, parsed.parallelism, &checksum); return handler.eql(&stored, &checksum); } /// True for a hash whose block size or parallelism differs from /// `options`, or whose `ln` falls outside the desired bounds. `ln` is /// not otherwise compared, as passlib does not compare it. pub fn needsUpdate(h: []const u8, options: Options) Error!bool { _ = try checkOptions(options); var salt_buf: [max_salt_len]u8 = undefined; const parsed = try parse(h, &salt_buf); if (parsed.block_size != options.block_size) return true; if (parsed.parallelism != options.parallelism) return true; return handler.roundsOutside(parsed.rounds, options.min_desired_rounds, options.max_desired_rounds); } }; /// The schemes this module defines, in the order `registry.identify` tries /// them. pub const schemes = .{scrypt}; comptime { handler.check(scrypt); } const test_ctx: Context = .{ .io = testing.io, .gpa = testing.allocator }; fn expectHash(password: []const u8, options: scrypt.Options, expected: []const u8) !void { var buf: [256]u8 = undefined; var w: Io.Writer = .fixed(&buf); try scrypt.hash(test_ctx, password, options, &w); try testing.expectEqualStrings(expected, w.buffered()); try testing.expect(try scrypt.verify(test_ctx, password, expected)); try testing.expect(!try scrypt.verify(test_ctx, "wrong", expected)); } test "fixed salts, both formats" { // passlib 1.7.4: scrypt.using(salt=b"saltsalt", rounds=4, block_size=2, ...).hash("test") try expectHash("test", .{ .salt = "saltsalt", .rounds = 4, .block_size = 2 }, "$scrypt$ln=4,r=2,p=1$c2FsdHNhbHQ$AM+rOIQ+LUGtr4eBiUYa6D1OOAhLJ95AhNuXbBs7LgI"); try expectHash("test", .{ .salt = "saltsalt", .rounds = 4, .block_size = 2, .parallelism = 2 }, "$scrypt$ln=4,r=2,p=2$c2FsdHNhbHQ$0DE+tu/Chl2Y4r0HDS1QX16mcV9CYUHAo/WzAHuQUS4"); try expectHash("test", .{ .salt = "", .rounds = 4, .block_size = 1 }, "$scrypt$ln=4,r=1,p=1$$XjaB4opdKxVInBTaaJKEW00SF1OWAGRFilYm/xKcbnc"); try expectHash("te\x00st", .{ .salt = "saltsalt", .rounds = 4, .block_size = 1 }, "$scrypt$ln=4,r=1,p=1$c2FsdHNhbHQ$F1U71z46hr39hxBN0DCvA8xWeERofPcThFMiiOHSKKk"); try expectHash("test", .{ .salt = "saltsalt", .rounds = 4, .block_size = 2, .ident = .@"7" }, "$7$20..../....saltsalt$.wwesEcDh2IfjSMU7OY4crXHsUkGbsBE2ixZghlCi6."); } test "the reference implementation's own $7$ vector" { // From the scrypt distribution; passlib 1.7.4 verifies it. It is // N = 2^14, r = 8: 16 MiB, which is slow in a debug build, so only the // parse is checked here and the vector tables carry the rest. var salt_buf: [max_salt_len]u8 = undefined; const p = try scrypt.parse("$7$C6..../....SodiumChloride$kBGj9fHznVYFQMEn/qDCfrDevf9YDtcDdKvEqHJLV8D", &salt_buf); try testing.expectEqual(@as(u5, 14), p.rounds); try testing.expectEqual(@as(u64, 8), p.block_size); try testing.expectEqual(@as(u64, 1), p.parallelism); try testing.expectEqualStrings("SodiumChloride", p.salt); } test "Python's leniency in numbers and base64" { const h = "$scrypt$ln=4,r=2,p=1$c2FsdHNhbHQ$AM+rOIQ+LUGtr4eBiUYa6D1OOAhLJ95AhNuXbBs7LgI"; // passlib 1.7.4 verifies every one of these. for ([_][]const u8{ "$scrypt$ln=04,r=2,p=1$c2FsdHNhbHQ$AM+rOIQ+LUGtr4eBiUYa6D1OOAhLJ95AhNuXbBs7LgI", "$scrypt$ln=+4,r=2,p=1$c2FsdHNhbHQ$AM+rOIQ+LUGtr4eBiUYa6D1OOAhLJ95AhNuXbBs7LgI", "$scrypt$ln= 4,r=2,p=1$c2FsdHNhbHQ$AM+rOIQ+LUGtr4eBiUYa6D1OOAhLJ95AhNuXbBs7LgI", "$scrypt$ln=4,r=0_2,p=1$c2FsdHNhbHQ$AM+rOIQ+LUGtr4eBiUYa6D1OOAhLJ95AhNuXbBs7LgI", "$scrypt$ln=4,r=2,p=1$c2FsdHNhbHQ=$AM+rOIQ+LUGtr4eBiUYa6D1OOAhLJ95AhNuXbBs7LgI", // Stray bits in the last character are ignored. "$scrypt$ln=4,r=2,p=1$c2FsdHNhbHQ$AM+rOIQ+LUGtr4eBiUYa6D1OOAhLJ95AhNuXbBs7LgJ", }) |v| try testing.expect(try scrypt.verify(test_ctx, "test", v)); // And refuses these. for ([_][]const u8{ "$scrypt$x=4,r=2,p=1$c2FsdHNhbHQ$AM+rOIQ+LUGtr4eBiUYa6D1OOAhLJ95AhNuXbBs7LgI", "$scrypt$r=2,ln=4,p=1$c2FsdHNhbHQ$AM+rOIQ+LUGtr4eBiUYa6D1OOAhLJ95AhNuXbBs7LgI", "$scrypt$ln=4,r=2,p=1$c2FsdHNhbHQ$AM+rOIQ+LUGtr4eBiUYa6D1OOAhLJ95AhNuXbBs7L", "$scrypt$ln=4,r=2,p=1$c2FsdHNhbHQ$AM+rOIQ+LUGtr4eBiUYa6D1OOAhLJ95AhNuXbBs7!gI", "$scrypt$ln=4,r=2,p=1$c2FsdHNhbHQAA$AM+rOIQ+LUGtr4eBiUYa6D1OOAhLJ95AhNuXbBs7LgI", "$scrypt$ln=4,r=2,p=1$c2FsdHNhbHQ$", "$scrypt$ln=4,r=2,p=1$c2FsdHNhbHQ", h ++ "\n", "$scrypt$ln=4,r=2,p=1073741824$c2FsdHNhbHQ$AM+rOIQ+LUGtr4eBiUYa6D1OOAhLJ95AhNuXbBs7LgI", "$scrypt$ln=4,r=99999999999999999999,p=99999999999999999999$c2FsdHNhbHQ$AM+rOIQ+LUGtr4eBiUYa6D1OOAhLJ95AhNuXbBs7LgI", "$scrypt$ln=16,r=1,p=1$c2FsdHNhbHQ$AM+rOIQ+LUGtr4eBiUYa6D1OOAhLJ95AhNuXbBs7LgI", "$scrypt$ln=21,r=8,p=1$c2FsdHNhbHQ$AM+rOIQ+LUGtr4eBiUYa6D1OOAhLJ95AhNuXbBs7LgI", "$7$20..../....saltsalt$.wwesEcDh2IfjSMU7OY4crXHsUkGbsBE2ixZghlCi6.$x", "$7$20..../....saltsalt$.wwesEcDh2IfjSMU7OY4crXHsUkGbsBE2ixZghlCi", "$7$C6..../....SodiumChloride", "$7$C6..../....", }) |v| try testing.expectError(error.MalformedHash, scrypt.verify(test_ctx, "test", v)); // Parameters passlib accepts and `std` cannot compute. try testing.expectError(error.WeakParameters, scrypt.verify(test_ctx, "test", "$scrypt$ln=1,r=1,p=8388608$c2FsdHNhbHQ$AM+rOIQ+LUGtr4eBiUYa6D1OOAhLJ95AhNuXbBs7LgI")); } test "options" { var buf: [256]u8 = undefined; var w: Io.Writer = .fixed(&buf); try testing.expectError(error.InvalidOptions, scrypt.hash(test_ctx, "x", .{ .rounds = 0 }, &w)); try testing.expectError(error.InvalidOptions, scrypt.hash(test_ctx, "x", .{ .rounds = 32 }, &w)); try testing.expectError(error.InvalidOptions, scrypt.hash(test_ctx, "x", .{ .block_size = 0 }, &w)); try testing.expectError(error.InvalidOptions, scrypt.hash(test_ctx, "x", .{ .salt = "x" ** 1025 }, &w)); try testing.expectError(error.InvalidOptions, scrypt.hash(test_ctx, "x", .{ .rounds = 16, .block_size = 1 }, &w)); try testing.expectError(error.InvalidOptions, scrypt.hash(test_ctx, "x", .{ .ident = .@"7", .salt = "a$b", .rounds = 4 }, &w)); } test "round trip with a random salt" { var buf: [256]u8 = undefined; var w: Io.Writer = .fixed(&buf); try scrypt.hash(test_ctx, "hunter2", .{ .rounds = 4, .block_size = 1 }, &w); try testing.expect(try scrypt.verify(test_ctx, "hunter2", w.buffered())); try testing.expect(!try scrypt.verify(test_ctx, "hunter3", w.buffered())); w = .fixed(&buf); try scrypt.hash(test_ctx, "hunter2", .{ .rounds = 4, .block_size = 1, .ident = .@"7" }, &w); try testing.expect(std.mem.startsWith(u8, w.buffered(), "$7$")); try testing.expect(try scrypt.verify(test_ctx, "hunter2", w.buffered())); } test "needsUpdate" { const h = "$scrypt$ln=4,r=2,p=1$c2FsdHNhbHQ$AM+rOIQ+LUGtr4eBiUYa6D1OOAhLJ95AhNuXbBs7LgI"; // passlib 1.7.4: scrypt.needs_update(h) and the same under using(...). try testing.expect(try scrypt.needsUpdate(h, .{})); try testing.expect(!try scrypt.needsUpdate(h, .{ .block_size = 2 })); try testing.expect(try scrypt.needsUpdate(h, .{ .block_size = 2, .parallelism = 2 })); try testing.expect(try scrypt.needsUpdate(h, .{ .block_size = 2, .min_desired_rounds = 5 })); try testing.expect(!try scrypt.needsUpdate("$scrypt$ln=4,r=2,p=1$c2FsdHNhbHQ", .{ .block_size = 2 })); const h7 = "$7$20..../....saltsalt$.wwesEcDh2IfjSMU7OY4crXHsUkGbsBE2ixZghlCi6."; try testing.expect(!try scrypt.needsUpdate(h7, .{ .block_size = 2 })); try testing.expect(try scrypt.needsUpdate(h7, .{})); }