From 297f3613d87a6bc1b1b421d5c1d09da94ddadebe Mon Sep 17 00:00:00 2001 From: Frank Denis Date: Mon, 22 Jun 2026 16:25:58 +0200 Subject: [PATCH] crypto.argon2: add a function to return the required memory Add a `calcSize()` function to return the number of bytes required for the argon2 scratch buffer. --- lib/std/crypto/argon2.zig | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/lib/std/crypto/argon2.zig b/lib/std/crypto/argon2.zig index b8136ef8788c46ef7b1b2e7ae5f7405b2a16e85b..2c54dc937af31bd3d64ef503733806df6c9fb6a8 100644 --- a/lib/std/crypto/argon2.zig +++ b/lib/std/crypto/argon2.zig @@ -471,6 +471,18 @@ fn indexAlpha( return ref_lane * lanes + @as(u32, @intCast(((s + m - (p + 1)) % lanes))); } +fn blockCount(params: Params) u32 { + return @max( + params.m / (sync_points * params.p) * (sync_points * params.p), + 2 * sync_points * params.p, + ); +} + +/// Compute the number of bytes of scratch memory `kdf` needs for `params`. +pub fn calcSize(params: Params) usize { + return blockCount(params) * @sizeOf([block_length]u64); +} + /// Derives a key from the password, salt, and argon2 parameters. /// /// Derived key has to be at least 4 bytes length. @@ -494,10 +506,7 @@ pub fn kdf( if (params.m / 8 < params.p) return KdfError.WeakParameters; var h0 = initHash(password, salt, params, derived_key.len, mode); - const memory = @max( - params.m / (sync_points * params.p) * (sync_points * params.p), - 2 * sync_points * params.p, - ); + const memory = blockCount(params); var blocks = try Blocks.initCapacity(allocator, memory); defer blocks.deinit(); -- 2.54.0