跳转到内容

std.crypto.argon2

标准库Zig 0.17.1官方原文
源码std/crypto/argon2.zig

第 5 行

std.crypto.argon2.blake2

别名

第 8 行

别名目标 std.crypto.hash.blake2

std.crypto.argon2.Blake2b512

别名

第 14 行

别名目标 std.crypto.blake2.Blake2b512

std.crypto.argon2.blake2bLong

函数

第 143 行

fn blake2bLong(out: []u8, in: []const u8) void

参数

out: []u8
in: []const u8

std.crypto.argon2.blamkaGeneric

函数

第 392 行

fn blamkaGeneric(xs: [16]*u64) void

参数

xs: [16]*u64

std.crypto.argon2.blamkaRound

函数

第 381 行

inline fn blamkaRound(a: *BlamkaVector, b: *BlamkaVector, c: *BlamkaVector, d: *BlamkaVector) void

参数

std.crypto.argon2.BlamkaVector

常量

第 365 行

std.crypto.argon2.block_length

常量

第 24 行

std.crypto.argon2.blockCount

函数

第 469 行

fn blockCount(params: Params) u32

参数

params: Params

std.crypto.argon2.Blocks

类型

第 15 行

std.crypto.argon2.builtin

常量

第 5 行

std.crypto.argon2.calcSize

函数

第 477 行

计算 kdf 对给定 params 所需的临时内存字节数。

pub fn calcSize(params: Params) usize

参数

params: Params

std.crypto.argon2.crypto

别名

第 9 行

别名目标 std.crypto

std.crypto.argon2.default_hash_len

常量

第 29 行

std.crypto.argon2.default_salt_len

常量

第 28 行

std.crypto.argon2.EncodingError

别名

第 18 行

别名目标 std.crypto.errors.EncodingError

std.crypto.argon2.Error

别名

第 21 行

别名目标 std.crypto.pwhash.Error

std.crypto.argon2.fBlaMka

函数

第 367 行

fn fBlaMka(x: BlamkaVector, y: BlamkaVector) BlamkaVector

参数

std.crypto.argon2.finalize

函数

第 414 行

fn finalize( blocks: *Blocks, memory: u32, threads: u24, out: []u8, ) void

参数

blocks: *Blocks
memory: u32
threads: u24
out: []u8

std.crypto.argon2.H0

类型

第 16 行

std.crypto.argon2.HasherError

别名

第 20 行

别名目标 std.crypto.pwhash.HasherError

std.crypto.argon2.HashOptions

容器

第 604 行

密码哈希选项。

argon2 需要分配器。

仅支持 phc 编码。

字段

allocator: ?mem.Allocator
params: Params
mode: Mode = .argon2id
encoding: pwhash.Encoding = .phc

std.crypto.argon2.indexAlpha

函数

第 434 行

fn indexAlpha( rand: u64, lanes: u32, segments: u32, threads: u24, n: u32, slice: u32, lane: u24, index: u32, ) u32

参数

rand: u64
lanes: u32
segments: u32
threads: u24
n: u32
slice: u32
lane: u24
index: u32

std.crypto.argon2.initHash

函数

第 105 行

fn initHash( password: []const u8, salt: []const u8, params: Params, dk_len: usize, mode: Mode, ) H0

参数

password: []const u8
salt: []const u8
params: Params
dk_len: usize
mode: Mode

std.crypto.argon2.Io

别名

第 10 行

别名目标 std.Io

std.crypto.argon2.kdf

函数

第 486 行

根据密码、盐值和 argon2 参数派生密钥。

派生密钥的长度必须至少为 4 字节。

盐值的长度必须至少为 8 字节。

pub fn kdf( allocator: mem.Allocator, derived_key: []u8, password: []const u8, salt: []const u8, params: Params, mode: Mode, io: Io, ) KdfError!void

参数

allocator: mem.Allocator
derived_key: []u8
password: []const u8
salt: []const u8
params: Params
mode: Mode
io: Io

错误

AuthenticationFailed AuthenticationError
Canceled Cancelable

调用方请求停止异步操作。

ContextTooLong ContextTooLongError
IdentityElement IdentityElementError
InvalidEncoding EncodingError
KeyMismatch KeyMismatchError
LockedMemoryLimitExceeded SpawnError

已启用 mlockall,创建线程所需的内存将超出限制。

NonCanonical NonCanonicalError
NotSquare NotSquareError
OutOfMemory SpawnError

用户空间内存不足,无法创建线程。

OutputTooLong OutputTooLongError
PasswordVerificationFailed PasswordVerificationError
SignatureVerificationFailed SignatureVerificationError
SystemResources SpawnError

内核无法分配足够内存,为子进程分配任务结构体, 或复制调用者上下文中必须复制的部分。

ThreadQuotaExceeded SpawnError

触及系统施加的线程数量限制。 以下多种限制都可能触发此错误:

  • 达到 RLIMIT_NPROC 软资源限制,由 setrlimit(2) 设置,用于限制同一真实用户标识下的进程与线程数量。
  • 达到内核的系统级进程与线程数量限制 /proc/sys/kernel/threads-max,参见 proc(5)。
  • 达到最大 PID 数量 /proc/sys/kernel/pid_max,参见 proc(5)。
  • 达到 cgroup“进程数量”(PIDs)控制器施加的 PID 限制 pids.max。
Unexpected SpawnError
UnexpectedSubgroup UnexpectedSubgroupError
WeakParameters WeakParametersError
WeakPublicKey WeakPublicKeyError

std.crypto.argon2.KdfError

别名

第 19 行

别名目标 std.crypto.pwhash.KdfError

std.crypto.argon2.max_hash_len

常量

第 31 行

std.crypto.argon2.max_int

常量

第 26 行

std.crypto.argon2.max_salt_len

常量

第 30 行

std.crypto.argon2.mem

别名

第 11 行

别名目标 std.mem

std.crypto.argon2.Mode

容器

第 34 行

Argon2 类型

字段

argon2d

Argon2d 更快,并使用依赖数据的内存访问,因此能高度抵御 GPU 破解攻击,适用于不存在侧信道 时序攻击威胁的应用,例如加密货币。

argon2i

Argon2i 使用不依赖数据的内存访问方式,更适合密码 哈希和基于密码的密钥派生,但速度较慢,因为为了防御 时间与空间折衷攻击,它需要更多次遍历内存。

argon2id

Argon2id 是 Argon2i 与 Argon2d 的混合体,同时使用依赖数据和 不依赖数据的内存访问方式,因此具备 Argon2i 对缓存计时侧信道攻击的 部分抵抗能力,以及 Argon2d 对 GPU 破解攻击的大部分抵抗能力。

std.crypto.argon2.Params

容器

第 52 行

Argon2 参数

字段

t: u32

时间成本,以迭代次数给出,定义执行的计算量,因而决定 执行时间。

m: u32

内存成本,决定内存用量,单位为 KiB。

p: u24

并行度,即独立任务的数量, 可能时将其复用到线程上执行。

secret: ?[]const u8 = null

用于带密钥哈希的秘密参数。它允许在计算哈希时 从某个外部位置输入密钥,并将其混入哈希值。 这意味着即使盐值和哈希值泄露,攻击者若无密钥, 也无法通过暴力破解找出密码。

ad: ?[]const u8 = null

ad 参数用于将额外数据纳入哈希值。功能上, 它几乎与 secret 或 salt 参数相同,都会 参与哈希计算。但此参数用于不同的数据:salt 应为与密码一起保存的随机字符串,secret 应为仅在哈希时 可用的随机密钥,ad 则用于其他任何数据。

std.crypto.argon2.Params.fromLimits

函数

第 98 行

根据操作次数和内存限制创建参数,其中 mem_limit 以字节为单位

pub fn fromLimits(ops_limit: u32, mem_limit: usize) Self

参数

ops_limit: u32
mem_limit: usize

std.crypto.argon2.Params.interactive_2i

常量

第 80 行

使用 argon2i 类型进行交互式登录的基线参数

std.crypto.argon2.Params.interactive_2id

常量

第 87 行

使用 argon2id 类型进行交互式登录的基线参数

std.crypto.argon2.Params.moderate_2i

常量

第 82 行

使用 argon2i 类型进行常规操作的基准参数

std.crypto.argon2.Params.moderate_2id

常量

第 89 行

使用 argon2id 类型进行常规用途的基准参数。

std.crypto.argon2.Params.owasp_2id

常量

第 95 行

根据 OWASP 备忘单, 为 argon2id 类型推荐的参数。

std.crypto.argon2.Params.Self

别名

第 53 行

别名目标 std.crypto.argon2.Params

std.crypto.argon2.Params.sensitive_2i

常量

第 84 行

使用 argon2i 类型进行离线操作的基准参数

std.crypto.argon2.Params.sensitive_2id

常量

第 91 行

使用 argon2id 类型进行离线处理的基线参数

std.crypto.argon2.phc_format

别名

第 12 行

别名目标 std.crypto.pwhash.phc_format

std.crypto.argon2.PhcFormatHasher

命名空间

第 534 行

std.crypto.argon2.PhcFormatHasher.BinValue

别名

第 535 行

别名目标 std.crypto.phc_encoding.BinValue

std.crypto.argon2.PhcFormatHasher.create

函数

第 547 行

pub fn create( allocator: mem.Allocator, password: []const u8, params: Params, mode: Mode, buf: []u8, io: Io, ) HasherError![]const u8

参数

allocator: mem.Allocator
password: []const u8
params: Params
mode: Mode
buf: []u8
io: Io

错误

AuthenticationFailed AuthenticationError
Canceled Cancelable

调用方请求停止异步操作。

ContextTooLong ContextTooLongError
IdentityElement IdentityElementError
InvalidEncoding EncodingError
KeyMismatch KeyMismatchError
LockedMemoryLimitExceeded SpawnError

已启用 mlockall,创建线程所需的内存将超出限制。

NoSpaceLeft Error
NonCanonical NonCanonicalError
NotSquare NotSquareError
OutOfMemory SpawnError

用户空间内存不足,无法创建线程。

OutputTooLong OutputTooLongError
PasswordVerificationFailed PasswordVerificationError
SignatureVerificationFailed SignatureVerificationError
SystemResources SpawnError

内核无法分配足够内存,为子进程分配任务结构体, 或复制调用者上下文中必须复制的部分。

ThreadQuotaExceeded SpawnError

触及系统施加的线程数量限制。 以下多种限制都可能触发此错误:

  • 达到 RLIMIT_NPROC 软资源限制,由 setrlimit(2) 设置,用于限制同一真实用户标识下的进程与线程数量。
  • 达到内核的系统级进程与线程数量限制 /proc/sys/kernel/threads-max,参见 proc(5)。
  • 达到最大 PID 数量 /proc/sys/kernel/pid_max,参见 proc(5)。
  • 达到 cgroup“进程数量”(PIDs)控制器施加的 PID 限制 pids.max。
Unexpected SpawnError
UnexpectedSubgroup UnexpectedSubgroupError
WeakParameters WeakParametersError
WeakPublicKey WeakPublicKeyError

std.crypto.argon2.PhcFormatHasher.HashResult

容器

第 537 行

字段

alg_id: []const u8
alg_version: ?u32
m: u32
t: u32
p: u24
salt: BinValue(max_salt_len)
hash: BinValue(max_hash_len)

std.crypto.argon2.PhcFormatHasher.verify

函数

第 574 行

pub fn verify( allocator: mem.Allocator, str: []const u8, password: []const u8, io: Io, ) HasherError!void

参数

allocator: mem.Allocator
str: []const u8
password: []const u8
io: Io

错误

AuthenticationFailed AuthenticationError
Canceled Cancelable

调用方请求停止异步操作。

ContextTooLong ContextTooLongError
IdentityElement IdentityElementError
InvalidEncoding EncodingError
KeyMismatch KeyMismatchError
LockedMemoryLimitExceeded SpawnError

已启用 mlockall,创建线程所需的内存将超出限制。

NoSpaceLeft Error
NonCanonical NonCanonicalError
NotSquare NotSquareError
OutOfMemory SpawnError

用户空间内存不足,无法创建线程。

OutputTooLong OutputTooLongError
PasswordVerificationFailed PasswordVerificationError
SignatureVerificationFailed SignatureVerificationError
SystemResources SpawnError

内核无法分配足够内存,为子进程分配任务结构体, 或复制调用者上下文中必须复制的部分。

ThreadQuotaExceeded SpawnError

触及系统施加的线程数量限制。 以下多种限制都可能触发此错误:

  • 达到 RLIMIT_NPROC 软资源限制,由 setrlimit(2) 设置,用于限制同一真实用户标识下的进程与线程数量。
  • 达到内核的系统级进程与线程数量限制 /proc/sys/kernel/threads-max,参见 proc(5)。
  • 达到最大 PID 数量 /proc/sys/kernel/pid_max,参见 proc(5)。
  • 达到 cgroup“进程数量”(PIDs)控制器施加的 PID 限制 pids.max。
Unexpected SpawnError
UnexpectedSubgroup UnexpectedSubgroupError
WeakParameters WeakParametersError
WeakPublicKey WeakPublicKeyError

std.crypto.argon2.processBlock

函数

第 306 行

fn processBlock( out: *align(16) [block_length]u64, in1: *align(16) const [block_length]u64, in2: *align(16) const [block_length]u64, ) void

参数

out: *align(16) [block_length]u64
in1: *align(16) const [block_length]u64
in2: *align(16) const [block_length]u64

std.crypto.argon2.processBlockGeneric

函数

第 322 行

fn processBlockGeneric( out: *[block_length]u64, in1: *const [block_length]u64, in2: *const [block_length]u64, comptime xor: bool, ) void

参数

out: *[block_length]u64
in1: *const [block_length]u64
in2: *const [block_length]u64
xor: bool

std.crypto.argon2.processBlocks

函数

第 179 行

fn processBlocks( blocks: *Blocks, time: u32, memory: u32, threads: u24, mode: Mode, io: Io, ) Io.Cancelable!void

参数

blocks: *Blocks
time: u32
memory: u32
threads: u24
mode: Mode
io: Io

错误

Canceled

调用方请求停止异步操作。

std.crypto.argon2.processBlocksAsync

函数

第 218 行

fn processBlocksAsync( blocks: *Blocks, time: u32, memory: u32, threads: u24, mode: Mode, lanes: u32, segments: u32, io: Io, ) Io.Cancelable!void

参数

blocks: *Blocks
time: u32
memory: u32
threads: u24
mode: Mode
lanes: u32
segments: u32
io: Io

错误

Canceled

调用方请求停止异步操作。

std.crypto.argon2.processBlocksSync

函数

第 197 行

fn processBlocksSync( blocks: *Blocks, time: u32, memory: u32, threads: u24, mode: Mode, lanes: u32, segments: u32, ) void

参数

blocks: *Blocks
time: u32
memory: u32
threads: u24
mode: Mode
lanes: u32
segments: u32

std.crypto.argon2.processBlockXor

函数

第 314 行

fn processBlockXor( out: *[block_length]u64, in1: *const [block_length]u64, in2: *const [block_length]u64, ) void

参数

out: *[block_length]u64
in1: *const [block_length]u64
in2: *const [block_length]u64

std.crypto.argon2.processSegment

函数

第 245 行

fn processSegment( blocks: *Blocks, passes: u32, memory: u32, threads: u24, mode: Mode, lanes: u32, segments: u32, n: u32, slice: u32, lane: u24, ) void

参数

blocks: *Blocks
passes: u32
memory: u32
threads: u24
mode: Mode
lanes: u32
segments: u32
n: u32
slice: u32
lane: u24

std.crypto.argon2.pwhash

别名

第 13 行

别名目标 std.crypto.pwhash

std.crypto.argon2.rotrVector

函数

第 374 行

fn rotrVector(x: BlamkaVector, comptime n: comptime_int) BlamkaVector

参数

x: BlamkaVector
n: comptime_int

std.crypto.argon2.std

别名

第 7 行

别名目标 std

std.crypto.argon2.strHash

函数

第 613 行

使用 argon2 密钥派生函数计算口令哈希。 返回的字符串包含验证所需的全部参数。

pub fn strHash( password: []const u8, options: HashOptions, out: []u8, io: Io, ) Error![]const u8

参数

password: []const u8
options: HashOptions
out: []u8
io: Io

错误

AllocatorRequired Error
AuthenticationFailed AuthenticationError
Canceled Cancelable

调用方请求停止异步操作。

ContextTooLong ContextTooLongError
IdentityElement IdentityElementError
InvalidEncoding EncodingError
KeyMismatch KeyMismatchError
LockedMemoryLimitExceeded SpawnError

已启用 mlockall,创建线程所需的内存将超出限制。

NoSpaceLeft Error
NonCanonical NonCanonicalError
NotSquare NotSquareError
OutOfMemory SpawnError

用户空间内存不足,无法创建线程。

OutputTooLong OutputTooLongError
PasswordVerificationFailed PasswordVerificationError
SignatureVerificationFailed SignatureVerificationError
SystemResources SpawnError

内核无法分配足够内存,为子进程分配任务结构体, 或复制调用者上下文中必须复制的部分。

ThreadQuotaExceeded SpawnError

触及系统施加的线程数量限制。 以下多种限制都可能触发此错误:

  • 达到 RLIMIT_NPROC 软资源限制,由 setrlimit(2) 设置,用于限制同一真实用户标识下的进程与线程数量。
  • 达到内核的系统级进程与线程数量限制 /proc/sys/kernel/threads-max,参见 proc(5)。
  • 达到最大 PID 数量 /proc/sys/kernel/pid_max,参见 proc(5)。
  • 达到 cgroup“进程数量”(PIDs)控制器施加的 PID 限制 pids.max。
Unexpected SpawnError
UnexpectedSubgroup UnexpectedSubgroupError
WeakParameters WeakParametersError
WeakPublicKey WeakPublicKeyError

std.crypto.argon2.strVerify

函数

第 639 行

验证先前计算的哈希对给定密码是否有效。

pub fn strVerify( str: []const u8, password: []const u8, options: VerifyOptions, io: Io, ) Error!void

参数

str: []const u8
password: []const u8
options: VerifyOptions
io: Io

错误

AllocatorRequired Error
AuthenticationFailed AuthenticationError
Canceled Cancelable

调用方请求停止异步操作。

ContextTooLong ContextTooLongError
IdentityElement IdentityElementError
InvalidEncoding EncodingError
KeyMismatch KeyMismatchError
LockedMemoryLimitExceeded SpawnError

已启用 mlockall,创建线程所需的内存将超出限制。

NoSpaceLeft Error
NonCanonical NonCanonicalError
NotSquare NotSquareError
OutOfMemory SpawnError

用户空间内存不足,无法创建线程。

OutputTooLong OutputTooLongError
PasswordVerificationFailed PasswordVerificationError
SignatureVerificationFailed SignatureVerificationError
SystemResources SpawnError

内核无法分配足够内存,为子进程分配任务结构体, 或复制调用者上下文中必须复制的部分。

ThreadQuotaExceeded SpawnError

触及系统施加的线程数量限制。 以下多种限制都可能触发此错误:

  • 达到 RLIMIT_NPROC 软资源限制,由 setrlimit(2) 设置,用于限制同一真实用户标识下的进程与线程数量。
  • 达到内核的系统级进程与线程数量限制 /proc/sys/kernel/threads-max,参见 proc(5)。
  • 达到最大 PID 数量 /proc/sys/kernel/pid_max,参见 proc(5)。
  • 达到 cgroup“进程数量”(PIDs)控制器施加的 PID 限制 pids.max。
Unexpected SpawnError
UnexpectedSubgroup UnexpectedSubgroupError
WeakParameters WeakParametersError
WeakPublicKey WeakPublicKeyError

std.crypto.argon2.sync_points

常量

第 25 行

std.crypto.argon2.VerifyOptions

容器

第 634 行

哈希校验选项。

字段

allocator: mem.Allocator

std.crypto.argon2.version

常量

第 23 行

源码

std/crypto/argon2.zig

// https://datatracker.ietf.org/doc/rfc9106
// https://github.com/golang/crypto/tree/master/argon2
// https://github.com/P-H-C/phc-winner-argon2

const builtin = @import("builtin");

const std = @import("std");
const blake2 = crypto.hash.blake2;
const crypto = std.crypto;
const Io = std.Io;
const mem = std.mem;
const phc_format = pwhash.phc_format;
const pwhash = crypto.pwhash;
const Blake2b512 = blake2.Blake2b512;
const Blocks = std.array_list.AlignedManaged([block_length]u64, .@"16");
const H0 = [Blake2b512.digest_length + 8]u8;

const EncodingError = crypto.errors.EncodingError;
const KdfError = pwhash.KdfError;
const HasherError = pwhash.HasherError;
const Error = pwhash.Error;

const version = 0x13;
const block_length = 128;
const sync_points = 4;
const max_int = 0xffff_ffff;

const default_salt_len = 32;
const default_hash_len = 32;
const max_salt_len = 64;
const max_hash_len = 64;

/// Argon2 类型
pub const Mode = enum {
    /// Argon2d 更快,并使用依赖数据的内存访问,因此能高度抵御
    /// GPU 破解攻击,适用于不存在侧信道
    /// 时序攻击威胁的应用,例如加密货币。
    argon2d,

    /// Argon2i 使用不依赖数据的内存访问方式,更适合密码
    /// 哈希和基于密码的密钥派生,但速度较慢,因为为了防御
    /// 时间与空间折衷攻击,它需要更多次遍历内存。
    argon2i,

    /// Argon2id 是 Argon2i 与 Argon2d 的混合体,同时使用依赖数据和
    /// 不依赖数据的内存访问方式,因此具备 Argon2i 对缓存计时侧信道攻击的
    /// 部分抵抗能力,以及 Argon2d 对 GPU 破解攻击的大部分抵抗能力。
    argon2id,
};

/// Argon2 参数
pub const Params = struct {
    const Self = @This();

    /// 时间成本,以迭代次数给出,定义执行的计算量,因而决定
    /// 执行时间。
    t: u32,

    /// 内存成本,决定内存用量,单位为 KiB。
    m: u32,

    /// 并行度,即独立任务的数量,
    /// 可能时将其复用到线程上执行。
    p: u24,

    /// 用于带密钥哈希的秘密参数。它允许在计算哈希时
    /// 从某个外部位置输入密钥,并将其混入哈希值。
    /// 这意味着即使盐值和哈希值泄露,攻击者若无密钥,
    /// 也无法通过暴力破解找出密码。
    secret: ?[]const u8 = null,

    /// ad 参数用于将额外数据纳入哈希值。功能上,
    /// 它几乎与 secret 或 salt 参数相同,都会
    /// 参与哈希计算。但此参数用于不同的数据:salt
    /// 应为与密码一起保存的随机字符串,secret 应为仅在哈希时
    /// 可用的随机密钥,ad 则用于其他任何数据。
    ad: ?[]const u8 = null,

    /// 使用 argon2i 类型进行交互式登录的基线参数
    pub const interactive_2i = Self.fromLimits(4, 33554432);
    /// 使用 argon2i 类型进行常规操作的基准参数
    pub const moderate_2i = Self.fromLimits(6, 134217728);
    /// 使用 argon2i 类型进行离线操作的基准参数
    pub const sensitive_2i = Self.fromLimits(8, 536870912);

    /// 使用 argon2id 类型进行交互式登录的基线参数
    pub const interactive_2id = Self.fromLimits(2, 67108864);
    /// 使用 argon2id 类型进行常规用途的基准参数。
    pub const moderate_2id = Self.fromLimits(3, 268435456);
    /// 使用 argon2id 类型进行离线处理的基线参数
    pub const sensitive_2id = Self.fromLimits(4, 1073741824);

    /// 根据 [OWASP 备忘单](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html),
    /// 为 argon2id 类型推荐的参数。
    pub const owasp_2id = Self{ .t = 2, .m = 19 * 1024, .p = 1 };

    /// 根据操作次数和内存限制创建参数,其中 mem_limit 以字节为单位
    pub fn fromLimits(ops_limit: u32, mem_limit: usize) Self {
        const m = mem_limit / 1024;
        std.debug.assert(m <= max_int);
        return .{ .t = ops_limit, .m = @as(u32, @intCast(m)), .p = 1 };
    }
};

fn initHash(
    password: []const u8,
    salt: []const u8,
    params: Params,
    dk_len: usize,
    mode: Mode,
) H0 {
    var h0: H0 = undefined;
    var parameters: [24]u8 = undefined;
    var tmp: [4]u8 = undefined;
    var b2 = Blake2b512.init(.{});
    mem.writeInt(u32, parameters[0..4], params.p, .little);
    mem.writeInt(u32, parameters[4..8], @as(u32, @intCast(dk_len)), .little);
    mem.writeInt(u32, parameters[8..12], params.m, .little);
    mem.writeInt(u32, parameters[12..16], params.t, .little);
    mem.writeInt(u32, parameters[16..20], version, .little);
    mem.writeInt(u32, parameters[20..24], @backingInt(mode), .little);
    b2.update(&parameters);
    mem.writeInt(u32, &tmp, @as(u32, @intCast(password.len)), .little);
    b2.update(&tmp);
    b2.update(password);
    mem.writeInt(u32, &tmp, @as(u32, @intCast(salt.len)), .little);
    b2.update(&tmp);
    b2.update(salt);
    const secret = params.secret orelse "";
    std.debug.assert(secret.len <= max_int);
    mem.writeInt(u32, &tmp, @as(u32, @intCast(secret.len)), .little);
    b2.update(&tmp);
    b2.update(secret);
    const ad = params.ad orelse "";
    std.debug.assert(ad.len <= max_int);
    mem.writeInt(u32, &tmp, @as(u32, @intCast(ad.len)), .little);
    b2.update(&tmp);
    b2.update(ad);
    b2.final(h0[0..Blake2b512.digest_length]);
    return h0;
}

fn blake2bLong(out: []u8, in: []const u8) void {
    const H = Blake2b512;
    var outlen_bytes: [4]u8 = undefined;
    mem.writeInt(u32, &outlen_bytes, @as(u32, @intCast(out.len)), .little);

    var out_buf: [H.digest_length]u8 = undefined;

    if (out.len <= H.digest_length) {
        var h = H.init(.{ .expected_out_bits = out.len * 8 });
        h.update(&outlen_bytes);
        h.update(in);
        h.final(&out_buf);
        @memcpy(out, out_buf[0..out.len]);
        return;
    }

    var h = H.init(.{});
    h.update(&outlen_bytes);
    h.update(in);
    h.final(&out_buf);
    var out_slice = out;
    out_slice[0 .. H.digest_length / 2].* = out_buf[0 .. H.digest_length / 2].*;
    out_slice = out_slice[H.digest_length / 2 ..];

    var in_buf: [H.digest_length]u8 = undefined;
    while (out_slice.len > H.digest_length) {
        in_buf = out_buf;
        H.hash(&in_buf, &out_buf, .{});
        out_slice[0 .. H.digest_length / 2].* = out_buf[0 .. H.digest_length / 2].*;
        out_slice = out_slice[H.digest_length / 2 ..];
    }
    in_buf = out_buf;
    H.hash(&in_buf, &out_buf, .{ .expected_out_bits = out_slice.len * 8 });
    @memcpy(out_slice, out_buf[0..out_slice.len]);
}

fn processBlocks(
    blocks: *Blocks,
    time: u32,
    memory: u32,
    threads: u24,
    mode: Mode,
    io: Io,
) Io.Cancelable!void {
    const lanes = memory / threads;
    const segments = lanes / sync_points;

    if (builtin.single_threaded or threads == 1) {
        processBlocksSync(blocks, time, memory, threads, mode, lanes, segments);
    } else {
        try processBlocksAsync(blocks, time, memory, threads, mode, lanes, segments, io);
    }
}

fn processBlocksSync(
    blocks: *Blocks,
    time: u32,
    memory: u32,
    threads: u24,
    mode: Mode,
    lanes: u32,
    segments: u32,
) void {
    var n: u32 = 0;
    while (n < time) : (n += 1) {
        var slice: u32 = 0;
        while (slice < sync_points) : (slice += 1) {
            var lane: u24 = 0;
            while (lane < threads) : (lane += 1) {
                processSegment(blocks, time, memory, threads, mode, lanes, segments, n, slice, lane);
            }
        }
    }
}

fn processBlocksAsync(
    blocks: *Blocks,
    time: u32,
    memory: u32,
    threads: u24,
    mode: Mode,
    lanes: u32,
    segments: u32,
    io: Io,
) Io.Cancelable!void {
    var n: u32 = 0;
    while (n < time) : (n += 1) {
        var slice: u32 = 0;
        while (slice < sync_points) : (slice += 1) {
            var group: Io.Group = .init;
            defer group.cancel(io);
            var lane: u24 = 0;
            while (lane < threads) : (lane += 1) {
                group.async(io, processSegment, .{
                    blocks, time, memory, threads, mode, lanes, segments, n, slice, lane,
                });
            }
            try group.await(io);
        }
    }
}

fn processSegment(
    blocks: *Blocks,
    passes: u32,
    memory: u32,
    threads: u24,
    mode: Mode,
    lanes: u32,
    segments: u32,
    n: u32,
    slice: u32,
    lane: u24,
) void {
    var addresses: [block_length]u64 align(16) = @splat(0);
    var in: [block_length]u64 align(16) = @splat(0);
    const zero: [block_length]u64 align(16) = @splat(0);
    if (mode == .argon2i or (mode == .argon2id and n == 0 and slice < sync_points / 2)) {
        in[0] = n;
        in[1] = lane;
        in[2] = slice;
        in[3] = memory;
        in[4] = passes;
        in[5] = @backingInt(mode);
    }
    var index: u32 = 0;
    if (n == 0 and slice == 0) {
        index = 2;
        if (mode == .argon2i or mode == .argon2id) {
            in[6] += 1;
            processBlock(&addresses, &in, &zero);
            processBlock(&addresses, &addresses, &zero);
        }
    }
    var offset = lane * lanes + slice * segments + index;
    var random: u64 = 0;
    while (index < segments) : ({
        index += 1;
        offset += 1;
    }) {
        var prev = offset -% 1;
        if (index == 0 and slice == 0) {
            prev +%= lanes;
        }
        if (mode == .argon2i or (mode == .argon2id and n == 0 and slice < sync_points / 2)) {
            if (index % block_length == 0) {
                in[6] += 1;
                processBlock(&addresses, &in, &zero);
                processBlock(&addresses, &addresses, &zero);
            }
            random = addresses[index % block_length];
        } else {
            random = blocks.items[prev][0];
        }
        const new_offset = indexAlpha(random, lanes, segments, threads, n, slice, lane, index);
        if (n == 0) {
            processBlock(&blocks.items[offset], &blocks.items[prev], &blocks.items[new_offset]);
        } else {
            processBlockXor(&blocks.items[offset], &blocks.items[prev], &blocks.items[new_offset]);
        }
    }
}

fn processBlock(
    out: *align(16) [block_length]u64,
    in1: *align(16) const [block_length]u64,
    in2: *align(16) const [block_length]u64,
) void {
    processBlockGeneric(out, in1, in2, false);
}

fn processBlockXor(
    out: *[block_length]u64,
    in1: *const [block_length]u64,
    in2: *const [block_length]u64,
) void {
    processBlockGeneric(out, in1, in2, true);
}

fn processBlockGeneric(
    out: *[block_length]u64,
    in1: *const [block_length]u64,
    in2: *const [block_length]u64,
    comptime xor: bool,
) void {
    var t: [block_length]u64 = undefined;
    for (&t, 0..) |*v, i| {
        v.* = in1[i] ^ in2[i];
    }
    var i: usize = 0;
    while (i < block_length) : (i += 16) {
        blamkaGeneric(.{
            &t[i + 0],  &t[i + 1],  &t[i + 2],  &t[i + 3],
            &t[i + 4],  &t[i + 5],  &t[i + 6],  &t[i + 7],
            &t[i + 8],  &t[i + 9],  &t[i + 10], &t[i + 11],
            &t[i + 12], &t[i + 13], &t[i + 14], &t[i + 15],
        });
    }
    i = 0;
    while (i < block_length / 8) : (i += 2) {
        blamkaGeneric(.{
            &t[0 * 16 + i], &t[0 * 16 + i + 1],
            &t[1 * 16 + i], &t[1 * 16 + i + 1],
            &t[2 * 16 + i], &t[2 * 16 + i + 1],
            &t[3 * 16 + i], &t[3 * 16 + i + 1],
            &t[4 * 16 + i], &t[4 * 16 + i + 1],
            &t[5 * 16 + i], &t[5 * 16 + i + 1],
            &t[6 * 16 + i], &t[6 * 16 + i + 1],
            &t[7 * 16 + i], &t[7 * 16 + i + 1],
        });
    }
    if (xor) {
        for (t, 0..) |v, j| {
            out[j] ^= in1[j] ^ in2[j] ^ v;
        }
    } else {
        for (t, 0..) |v, j| {
            out[j] = in1[j] ^ in2[j] ^ v;
        }
    }
}

const BlamkaVector = @Vector(4, u64);

fn fBlaMka(x: BlamkaVector, y: BlamkaVector) BlamkaVector {
    const x_lo: @Vector(4, u32) = @truncate(x);
    const y_lo: @Vector(4, u32) = @truncate(y);
    const xy = @as(BlamkaVector, x_lo) * @as(BlamkaVector, y_lo);
    return x +% y +% @as(BlamkaVector, @splat(2)) *% xy;
}

fn rotrVector(x: BlamkaVector, comptime n: comptime_int) BlamkaVector {
    return (x >> @splat(n)) | (x << @splat(64 - n));
}

// 此处的 `inline` 至关重要:没有它,ReleaseSmall 不会内联此函数,
// 每次调用都会经内存搬运四个向量,
// 在 Apple Silicon 上约损失 9% 性能。
inline fn blamkaRound(a: *BlamkaVector, b: *BlamkaVector, c: *BlamkaVector, d: *BlamkaVector) void {
    a.* = fBlaMka(a.*, b.*);
    d.* = rotrVector(d.* ^ a.*, 32);
    c.* = fBlaMka(c.*, d.*);
    b.* = rotrVector(b.* ^ c.*, 24);
    a.* = fBlaMka(a.*, b.*);
    d.* = rotrVector(d.* ^ a.*, 16);
    c.* = fBlaMka(c.*, d.*);
    b.* = rotrVector(b.* ^ c.*, 63);
}

fn blamkaGeneric(xs: [16]*u64) void {
    var a: BlamkaVector = .{ xs[0].*, xs[1].*, xs[2].*, xs[3].* };
    var b: BlamkaVector = .{ xs[4].*, xs[5].*, xs[6].*, xs[7].* };
    var c: BlamkaVector = .{ xs[8].*, xs[9].*, xs[10].*, xs[11].* };
    var d: BlamkaVector = .{ xs[12].*, xs[13].*, xs[14].*, xs[15].* };

    blamkaRound(&a, &b, &c, &d);

    var b_diag = @shuffle(u64, b, undefined, [_]i32{ 1, 2, 3, 0 });
    var c_diag = @shuffle(u64, c, undefined, [_]i32{ 2, 3, 0, 1 });
    var d_diag = @shuffle(u64, d, undefined, [_]i32{ 3, 0, 1, 2 });
    blamkaRound(&a, &b_diag, &c_diag, &d_diag);
    b = @shuffle(u64, b_diag, undefined, [_]i32{ 3, 0, 1, 2 });
    c = @shuffle(u64, c_diag, undefined, [_]i32{ 2, 3, 0, 1 });
    d = @shuffle(u64, d_diag, undefined, [_]i32{ 1, 2, 3, 0 });

    inline for (0..4) |k| xs[k].* = a[k];
    inline for (0..4) |k| xs[4 + k].* = b[k];
    inline for (0..4) |k| xs[8 + k].* = c[k];
    inline for (0..4) |k| xs[12 + k].* = d[k];
}

fn finalize(
    blocks: *Blocks,
    memory: u32,
    threads: u24,
    out: []u8,
) void {
    const lanes = memory / threads;
    var lane: u24 = 0;
    while (lane < threads - 1) : (lane += 1) {
        for (blocks.items[(lane * lanes) + lanes - 1], 0..) |v, i| {
            blocks.items[memory - 1][i] ^= v;
        }
    }
    var block: [1024]u8 = undefined;
    for (blocks.items[memory - 1], 0..) |v, i| {
        mem.writeInt(u64, block[i * 8 ..][0..8], v, .little);
    }
    blake2bLong(out, &block);
}

fn indexAlpha(
    rand: u64,
    lanes: u32,
    segments: u32,
    threads: u24,
    n: u32,
    slice: u32,
    lane: u24,
    index: u32,
) u32 {
    var ref_lane = @as(u32, @intCast(rand >> 32)) % threads;
    if (n == 0 and slice == 0) {
        ref_lane = lane;
    }
    var m = 3 * segments;
    var s = ((slice + 1) % sync_points) * segments;
    if (lane == ref_lane) {
        m += index;
    }
    if (n == 0) {
        m = slice * segments;
        s = 0;
        if (slice == 0 or lane == ref_lane) {
            m += index;
        }
    }
    if (index == 0 or lane == ref_lane) {
        m -= 1;
    }
    var p = @as(u64, @as(u32, @truncate(rand)));
    p = (p * p) >> 32;
    p = (p * m) >> 32;
    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,
    );
}

/// 计算 `kdf` 对给定 `params` 所需的临时内存字节数。
pub fn calcSize(params: Params) usize {
    return blockCount(params) * @sizeOf([block_length]u64);
}

/// 根据密码、盐值和 argon2 参数派生密钥。
///
/// 派生密钥的长度必须至少为 4 字节。
///
/// 盐值的长度必须至少为 8 字节。
pub fn kdf(
    allocator: mem.Allocator,
    derived_key: []u8,
    password: []const u8,
    salt: []const u8,
    params: Params,
    mode: Mode,
    io: Io,
) KdfError!void {
    if (derived_key.len < 4) return KdfError.WeakParameters;
    if (derived_key.len > max_int) return KdfError.OutputTooLong;

    if (password.len > max_int) return KdfError.WeakParameters;
    if (salt.len < 8 or salt.len > max_int) return KdfError.WeakParameters;
    if (params.t < 1 or params.p < 1) return KdfError.WeakParameters;
    if (params.m / 8 < params.p) return KdfError.WeakParameters;

    var h0 = initHash(password, salt, params, derived_key.len, mode);
    const memory = blockCount(params);

    var blocks = try Blocks.initCapacity(allocator, memory);
    defer blocks.deinit();

    const items = blocks.addManyAsSliceAssumeCapacity(memory);

    var block0: [1024]u8 = undefined;
    var lane: u24 = 0;
    while (lane < params.p) : (lane += 1) {
        const j = lane * (memory / params.p);
        mem.writeInt(u32, h0[Blake2b512.digest_length + 4 ..][0..4], lane, .little);

        mem.writeInt(u32, h0[Blake2b512.digest_length..][0..4], 0, .little);
        blake2bLong(&block0, &h0);
        for (&items[j + 0], 0..) |*v, i| {
            v.* = mem.readInt(u64, block0[i * 8 ..][0..8], .little);
        }

        mem.writeInt(u32, h0[Blake2b512.digest_length..][0..4], 1, .little);
        blake2bLong(&block0, &h0);
        for (&items[j + 1], 0..) |*v, i| {
            v.* = mem.readInt(u64, block0[i * 8 ..][0..8], .little);
        }
    }

    try processBlocks(&blocks, params.t, memory, params.p, mode, io);
    finalize(&blocks, memory, params.p, derived_key);
}

const PhcFormatHasher = struct {
    const BinValue = phc_format.BinValue;

    const HashResult = struct {
        alg_id: []const u8,
        alg_version: ?u32,
        m: u32,
        t: u32,
        p: u24,
        salt: BinValue(max_salt_len),
        hash: BinValue(max_hash_len),
    };

    pub fn create(
        allocator: mem.Allocator,
        password: []const u8,
        params: Params,
        mode: Mode,
        buf: []u8,
        io: Io,
    ) HasherError![]const u8 {
        if (params.secret != null or params.ad != null) return HasherError.InvalidEncoding;

        var salt: [default_salt_len]u8 = undefined;
        io.random(&salt);

        var hash: [default_hash_len]u8 = undefined;
        try kdf(allocator, &hash, password, &salt, params, mode, io);

        return phc_format.serialize(HashResult{
            .alg_id = @tagName(mode),
            .alg_version = version,
            .m = params.m,
            .t = params.t,
            .p = params.p,
            .salt = try BinValue(max_salt_len).fromSlice(&salt),
            .hash = try BinValue(max_hash_len).fromSlice(&hash),
        }, buf);
    }

    pub fn verify(
        allocator: mem.Allocator,
        str: []const u8,
        password: []const u8,
        io: Io,
    ) HasherError!void {
        const hash_result = try phc_format.deserialize(HashResult, str);

        const mode = std.meta.stringToEnum(Mode, hash_result.alg_id) orelse
            return HasherError.PasswordVerificationFailed;
        if (hash_result.alg_version) |v| {
            if (v != version) return HasherError.InvalidEncoding;
        }
        const params = Params{ .t = hash_result.t, .m = hash_result.m, .p = hash_result.p };

        const expected_hash = hash_result.hash.constSlice();
        var hash_buf: [max_hash_len]u8 = undefined;
        if (expected_hash.len > hash_buf.len) return HasherError.InvalidEncoding;
        const hash = hash_buf[0..expected_hash.len];

        try kdf(allocator, hash, password, hash_result.salt.constSlice(), params, mode, io);
        if (!mem.eql(u8, hash, expected_hash)) return HasherError.PasswordVerificationFailed;
    }
};

/// 密码哈希选项。
///
/// argon2 需要分配器。
///
/// 仅支持 phc 编码。
pub const HashOptions = struct {
    allocator: ?mem.Allocator,
    params: Params,
    mode: Mode = .argon2id,
    encoding: pwhash.Encoding = .phc,
};

/// 使用 argon2 密钥派生函数计算口令哈希。
/// 返回的字符串包含验证所需的全部参数。
pub fn strHash(
    password: []const u8,
    options: HashOptions,
    out: []u8,
    io: Io,
) Error![]const u8 {
    const allocator = options.allocator orelse return Error.AllocatorRequired;
    switch (options.encoding) {
        .phc => return PhcFormatHasher.create(
            allocator,
            password,
            options.params,
            options.mode,
            out,
            io,
        ),
        .crypt => return Error.InvalidEncoding,
    }
}

/// 哈希校验选项。
pub const VerifyOptions = struct {
    allocator: mem.Allocator,
};

/// 验证先前计算的哈希对给定密码是否有效。
pub fn strVerify(
    str: []const u8,
    password: []const u8,
    options: VerifyOptions,
    io: Io,
) Error!void {
    return PhcFormatHasher.verify(options.allocator, str, password, io);
}

test "argon2d" {
    if (true) return error.SkipZigTest; // https://codeberg.org/ziglang/zig/issues/30074

    const password: [32]u8 = @splat(0x01);
    const salt: [16]u8 = @splat(0x02);
    const secret: [8]u8 = @splat(0x03);
    const ad: [12]u8 = @splat(0x04);

    var dk: [32]u8 = undefined;
    try kdf(
        std.testing.allocator,
        &dk,
        &password,
        &salt,
        .{ .t = 3, .m = 32, .p = 4, .secret = &secret, .ad = &ad },
        .argon2d,
        std.testing.io,
    );

    const want = [_]u8{
        0x51, 0x2b, 0x39, 0x1b, 0x6f, 0x11, 0x62, 0x97,
        0x53, 0x71, 0xd3, 0x09, 0x19, 0x73, 0x42, 0x94,
        0xf8, 0x68, 0xe3, 0xbe, 0x39, 0x84, 0xf3, 0xc1,
        0xa1, 0x3a, 0x4d, 0xb9, 0xfa, 0xbe, 0x4a, 0xcb,
    };
    try std.testing.expectEqualSlices(u8, &dk, &want);
}

test "argon2i" {
    const password: [32]u8 = @splat(0x01);
    const salt: [16]u8 = @splat(0x02);
    const secret: [8]u8 = @splat(0x03);
    const ad: [12]u8 = @splat(0x04);

    var dk: [32]u8 = undefined;
    try kdf(
        std.testing.allocator,
        &dk,
        &password,
        &salt,
        .{ .t = 3, .m = 32, .p = 4, .secret = &secret, .ad = &ad },
        .argon2i,
        std.testing.io,
    );

    const want = [_]u8{
        0xc8, 0x14, 0xd9, 0xd1, 0xdc, 0x7f, 0x37, 0xaa,
        0x13, 0xf0, 0xd7, 0x7f, 0x24, 0x94, 0xbd, 0xa1,
        0xc8, 0xde, 0x6b, 0x01, 0x6d, 0xd3, 0x88, 0xd2,
        0x99, 0x52, 0xa4, 0xc4, 0x67, 0x2b, 0x6c, 0xe8,
    };
    try std.testing.expectEqualSlices(u8, &dk, &want);
}

test "argon2id" {
    const password: [32]u8 = @splat(0x01);
    const salt: [16]u8 = @splat(0x02);
    const secret: [8]u8 = @splat(0x03);
    const ad: [12]u8 = @splat(0x04);

    var dk: [32]u8 = undefined;
    try kdf(
        std.testing.allocator,
        &dk,
        &password,
        &salt,
        .{ .t = 3, .m = 32, .p = 4, .secret = &secret, .ad = &ad },
        .argon2id,
        std.testing.io,
    );

    const want = [_]u8{
        0x0d, 0x64, 0x0d, 0xf5, 0x8d, 0x78, 0x76, 0x6c,
        0x08, 0xc0, 0x37, 0xa3, 0x4a, 0x8b, 0x53, 0xc9,
        0xd0, 0x1e, 0xf0, 0x45, 0x2d, 0x75, 0xb6, 0x5e,
        0xb5, 0x25, 0x20, 0xe9, 0x6b, 0x01, 0xe6, 0x59,
    };
    try std.testing.expectEqualSlices(u8, &dk, &want);
}

test "kdf" {
    if (true) return error.SkipZigTest; // https://codeberg.org/ziglang/zig/issues/31402

    const password = "password";
    const salt = "somesalt";

    const TestVector = struct {
        mode: Mode,
        time: u32,
        memory: u32,
        threads: u8,
        hash: []const u8,
    };
    const test_vectors = [_]TestVector{
        .{
            .mode = .argon2i,
            .time = 1,
            .memory = 64,
            .threads = 1,
            .hash = "b9c401d1844a67d50eae3967dc28870b22e508092e861a37",
        },
        .{
            .mode = .argon2d,
            .time = 1,
            .memory = 64,
            .threads = 1,
            .hash = "8727405fd07c32c78d64f547f24150d3f2e703a89f981a19",
        },
        .{
            .mode = .argon2id,
            .time = 1,
            .memory = 64,
            .threads = 1,
            .hash = "655ad15eac652dc59f7170a7332bf49b8469be1fdb9c28bb",
        },
        .{
            .mode = .argon2i,
            .time = 2,
            .memory = 64,
            .threads = 1,
            .hash = "8cf3d8f76a6617afe35fac48eb0b7433a9a670ca4a07ed64",
        },
        .{
            .mode = .argon2d,
            .time = 2,
            .memory = 64,
            .threads = 1,
            .hash = "3be9ec79a69b75d3752acb59a1fbb8b295a46529c48fbb75",
        },
        .{
            .mode = .argon2id,
            .time = 2,
            .memory = 64,
            .threads = 1,
            .hash = "068d62b26455936aa6ebe60060b0a65870dbfa3ddf8d41f7",
        },
        .{
            .mode = .argon2i,
            .time = 2,
            .memory = 64,
            .threads = 2,
            .hash = "2089f3e78a799720f80af806553128f29b132cafe40d059f",
        },
        .{
            .mode = .argon2d,
            .time = 2,
            .memory = 64,
            .threads = 2,
            .hash = "68e2462c98b8bc6bb60ec68db418ae2c9ed24fc6748a40e9",
        },
        .{
            .mode = .argon2id,
            .time = 2,
            .memory = 64,
            .threads = 2,
            .hash = "350ac37222f436ccb5c0972f1ebd3bf6b958bf2071841362",
        },
        .{
            .mode = .argon2i,
            .time = 3,
            .memory = 256,
            .threads = 2,
            .hash = "f5bbf5d4c3836af13193053155b73ec7476a6a2eb93fd5e6",
        },
        .{
            .mode = .argon2d,
            .time = 3,
            .memory = 256,
            .threads = 2,
            .hash = "f4f0669218eaf3641f39cc97efb915721102f4b128211ef2",
        },
        .{
            .mode = .argon2id,
            .time = 3,
            .memory = 256,
            .threads = 2,
            .hash = "4668d30ac4187e6878eedeacf0fd83c5a0a30db2cc16ef0b",
        },
        .{
            .mode = .argon2i,
            .time = 4,
            .memory = 256,
            .threads = 4,
            .hash = "f7dbbacbf16999e3700817a7e06f65a8db2e9fa9504ede4c",
        },
        .{
            .mode = .argon2d,
            .time = 4,
            .memory = 256,
            .threads = 4,
            .hash = "ea2970501cf49faa5ba1d2e6370204e9b57ca90a8fea937b",
        },
        .{
            .mode = .argon2id,
            .time = 4,
            .memory = 256,
            .threads = 4,
            .hash = "fbd40d5a8cb92f88c20bda4b3cdb1f9d5af1efa937032410",
        },
        .{
            .mode = .argon2i,
            .time = 4,
            .memory = 256,
            .threads = 8,
            .hash = "15d3c398364e53f68fd12d19baf3f21432d964254fe27467",
        },
        .{
            .mode = .argon2d,
            .time = 4,
            .memory = 256,
            .threads = 8,
            .hash = "23c9adc06f06e21e4612c1466a1be02627690932b02c0df0",
        },
        .{
            .mode = .argon2id,
            .time = 4,
            .memory = 256,
            .threads = 8,
            .hash = "f22802f8ca47be93f9954e4ce20c1e944e938fbd4a125d9d",
        },
        .{
            .mode = .argon2i,
            .time = 2,
            .memory = 64,
            .threads = 3,
            .hash = "5cab452fe6b8479c8661def8cd703b611a3905a6d5477fe6",
        },
        .{
            .mode = .argon2d,
            .time = 2,
            .memory = 64,
            .threads = 3,
            .hash = "22474a423bda2ccd36ec9afd5119e5c8949798cadf659f51",
        },
        .{
            .mode = .argon2id,
            .time = 2,
            .memory = 64,
            .threads = 3,
            .hash = "4a15b31aec7c2590b87d1f520be7d96f56658172deaa3079",
        },
        .{
            .mode = .argon2i,
            .time = 3,
            .memory = 256,
            .threads = 6,
            .hash = "ebc8f91964abd8ceab49a12963b0a9e57d635bfa2aad2884",
        },
        .{
            .mode = .argon2d,
            .time = 3,
            .memory = 256,
            .threads = 6,
            .hash = "1dd7202fd68da6675f769f4034b7a1db30d8785331954117",
        },
        .{
            .mode = .argon2id,
            .time = 3,
            .memory = 256,
            .threads = 6,
            .hash = "424436b6ee22a66b04b9d0cf78f190305c5c166bae8baa09",
        },
    };
    for (test_vectors) |v| {
        var want: [24]u8 = undefined;
        _ = try std.fmt.hexToBytes(&want, v.hash);

        var dk: [24]u8 = undefined;
        try kdf(
            std.testing.allocator,
            &dk,
            password,
            salt,
            .{ .t = v.time, .m = v.memory, .p = v.threads },
            v.mode,
            std.testing.io,
        );

        try std.testing.expectEqualSlices(u8, &dk, &want);
    }
}

test "phc format hasher" {
    const allocator = std.testing.allocator;
    const password = "testpass";
    const io = std.testing.io;

    var buf: [128]u8 = undefined;
    const hash = try PhcFormatHasher.create(
        allocator,
        password,
        .{ .t = 3, .m = 32, .p = 4 },
        .argon2id,
        &buf,
        io,
    );
    try PhcFormatHasher.verify(allocator, hash, password, io);
}

test "password hash and password verify" {
    const allocator = std.testing.allocator;
    const password = "testpass";
    const io = std.testing.io;

    var buf: [128]u8 = undefined;
    const hash = try strHash(
        password,
        .{ .allocator = allocator, .params = .{ .t = 3, .m = 32, .p = 4 } },
        &buf,
        io,
    );
    try strVerify(hash, password, .{ .allocator = allocator }, io);
}

test "kdf derived key length" {
    if (true) return error.SkipZigTest; // https://codeberg.org/ziglang/zig/issues/31504

    const allocator = std.testing.allocator;
    const io = std.testing.io;

    const password = "testpass";
    const salt = "saltsalt";
    const params = Params{ .t = 3, .m = 32, .p = 4 };
    const mode = Mode.argon2id;

    var dk1: [11]u8 = undefined;
    try kdf(allocator, &dk1, password, salt, params, mode, io);

    var dk2: [77]u8 = undefined;
    try kdf(allocator, &dk2, password, salt, params, mode, io);

    var dk3: [111]u8 = undefined;
    try kdf(allocator, &dk3, password, salt, params, mode, io);
}