跳转到内容

std.crypto.ascon

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

第 1 行

Ascon 是一种 320 位置换,在 NIST 轻量级密码学竞赛(2019–2023 年)中被选为新的轻量级密码学标准。 https://csrc.nist.gov/pubs/sp/800/232/ipd

此置换结构紧凑,并针对时序攻击和侧信道抵抗进行优化,适合嵌入式应用。

不应直接使用它,而应将其作为对称密码学的构建模块。

std.crypto.ascon.AsconAead128

命名空间

第 317 行

NIST SP 800-232 第 4 节规定的 Ascon-AEAD128

std.crypto.ascon.AsconAead128.AeadState

容器

第 323 行

字段

st: AsconState
k0: u64
k1: u64

std.crypto.ascon.AsconAead128.AeadState.finalize

函数

第 395 行

结束 AEAD 操作并生成标签。

应用最终置换并与密钥异或,以生成标签。

fn finalize(self: *AeadState) void

参数

self: *AeadState

std.crypto.ascon.AsconAead128.AeadState.init

函数

第 335 行

使用密钥和 nonce 初始化 AEAD 状态。

参数:

  • key:16 字节密钥
  • nonce:16 字节 nonce

返回值:已初始化、可开始处理的 AEAD 状态。

fn init(key: [16]u8, nonce: [16]u8) AeadState

参数

key: [16]u8
nonce: [16]u8

std.crypto.ascon.AsconAead128.AeadState.processAd

函数

第 360 行

处理用于认证的关联数据。

参数:

  • ad:要认证的关联数据。

更新状态,将 AD 纳入认证标签计算。

fn processAd(self: *AeadState, ad: []const u8) void

参数

self: *AeadState
ad: []const u8

std.crypto.ascon.AsconAead128.block_length

常量

第 321 行

std.crypto.ascon.AsconAead128.decrypt

函数

第 499 行

使用 Ascon-AEAD128 解密消息。

参数:

  • m:明文输出缓冲区,长度必须与 c 相同。
  • c:待解密密文。
  • tag:认证标签,16 字节。
  • ad:经过认证的关联数据。
  • npub:加密时使用的公开 nonce,16 字节。
  • k:秘密密钥,16 字节。

返回:标签验证失败时返回 AuthenticationError。

注意:认证失败时,会安全地将输出缓冲区清零。

pub fn decrypt(m: []u8, c: []const u8, tag: [tag_length]u8, ad: []const u8, npub: [nonce_length]u8, k: [key_length]u8) AuthenticationError!void

参数

m: []u8
c: []const u8
tag: [tag_length]u8
ad: []const u8
npub: [nonce_length]u8
k: [key_length]u8

错误

AuthenticationFailed AuthenticationError

std.crypto.ascon.AsconAead128.encrypt

函数

第 418 行

使用 Ascon-AEAD128 加密消息。

参数:

  • c:密文输出缓冲区,长度必须与 m 相同。
  • tag:认证标签输出缓冲区,16 字节。
  • m:待加密明文消息。
  • ad:只认证而不加密的关联数据。
  • npub:公开 nonce,16 字节,每条消息必须唯一。
  • k:秘密密钥,16 字节。

注意:解密需要一并传输密文和标签。

pub fn encrypt(c: []u8, tag: *[tag_length]u8, m: []const u8, ad: []const u8, npub: [nonce_length]u8, k: [key_length]u8) void

参数

c: []u8
tag: *[tag_length]u8
m: []const u8
ad: []const u8
npub: [nonce_length]u8
k: [key_length]u8

std.crypto.ascon.AsconAead128.key_length

常量

第 320 行

std.crypto.ascon.AsconAead128.nonce_length

常量

第 319 行

std.crypto.ascon.AsconAead128.tag_length

常量

第 318 行

std.crypto.ascon.AsconCxof128

容器

第 793 行

NIST SP 800-232 第 5 节规定的 Ascon-CXOF128。

字段

st: AsconState
squeezed: bool
buf: [block_length]u8
buf_len: usize

std.crypto.ascon.AsconCxof128.block_length

常量

第 794 行

std.crypto.ascon.AsconCxof128.hash

函数

第 872 行

对字节切片计算哈希,支持自定义参数和可变长度输出。

参数:

  • bytes:要计算哈希的输入数据
  • out:输出缓冲区(长度任意)
  • options:包含可选自定义字符串的配置

注意:这是组合 init、update 和 squeeze 的便利函数。

pub fn hash(bytes: []const u8, out: []u8, options: Options) void

参数

bytes: []const u8
out: []u8
options: Options

std.crypto.ascon.AsconCxof128.init

函数

第 813 行

初始化新的 Ascon-CXOF128 可定制 XOF。

参数:

  • options:配置,包含可选的自定义字符串
    • custom:自定义字符串,最长 256 字节

返回:初始化后的 AsconCxof128 实例。

注意:不同自定义字符串产生相互独立的 XOF 实例。

pub fn init(options: Options) AsconCxof128

参数

options: Options

std.crypto.ascon.AsconCxof128.max_custom_length

常量

第 795 行

std.crypto.ascon.AsconCxof128.Options

容器

第 802 行

字段

custom: []const u8 = ""

std.crypto.ascon.AsconCxof128.squeeze

函数

第 919 行

从可自定义的 XOF 中挤出输出字节。

参数:

  • out:要填入伪随机字节的输出缓冲区

注意:可多次调用以生成更多输出。 首次调用后,不能再通过 update() 吸收数据。

pub fn squeeze(self: *AsconCxof128, out: []u8) void

参数

self: *AsconCxof128
out: []u8

std.crypto.ascon.AsconCxof128.update

函数

第 884 行

使用额外数据更新 CXOF 状态。

参数:

  • b:要吸收到 CXOF 状态的数据

注意:调用 squeeze() 后不能再调用此函数。

pub fn update(self: *AsconCxof128, b: []const u8) void

参数

self: *AsconCxof128
b: []const u8

std.crypto.ascon.AsconHash256

容器

第 587 行

NIST SP 800-232 第 5 节规定的 Ascon-Hash256

字段

std.crypto.ascon.AsconHash256.block_length

常量

第 589 行

std.crypto.ascon.AsconHash256.digest_length

常量

第 588 行

std.crypto.ascon.AsconHash256.final

函数

第 660 行

完成哈希计算并输出摘要。

参数:

  • out:用于输出 32 字节哈希摘要的缓冲区。

注意:调用 final() 后,不应再次使用该哈希器。

pub fn final(self: *AsconHash256, out: *[digest_length]u8) void

参数

self: *AsconHash256
out: *[digest_length]u8

std.crypto.ascon.AsconHash256.finalResult

函数

第 677 行

pub fn finalResult(d: *AsconHash256) [digest_length]u8

参数

std.crypto.ascon.AsconHash256.hash

函数

第 618 行

一次调用计算输入数据的 Ascon-Hash256 哈希。

参数:

  • b:待哈希的输入数据
  • out:用于 32 字节哈希摘要的输出缓冲区
  • options:配置选项,目前未使用
pub fn hash(b: []const u8, out: *[digest_length]u8, options: Options) void

参数

b: []const u8
out: *[digest_length]u8
options: Options

std.crypto.ascon.AsconHash256.init

函数

第 601 行

初始化新的 Ascon-Hash256 哈希器。

参数:

  • options:配置选项,目前未使用

返回:已初始化的 AsconHash256 哈希器。

pub fn init(options: Options) AsconHash256

参数

options: Options

std.crypto.ascon.AsconHash256.Options

命名空间

第 593 行

std.crypto.ascon.AsconHash256.update

函数

第 630 行

使用额外数据更新哈希状态。

参数:

  • b:加入哈希的数据

注意:可在 final() 前多次调用。

pub fn update(self: *AsconHash256, b: []const u8) void

参数

self: *AsconHash256
b: []const u8

std.crypto.ascon.AsconState

类型

第 313 行

std.crypto.ascon.AsconXof128

容器

第 685 行

NIST SP 800-232 第 5 节规定的 Ascon-XOF128

字段

st: AsconState
squeezed: bool
buf: [block_length]u8
buf_len: usize

std.crypto.ascon.AsconXof128.block_length

常量

第 686 行

std.crypto.ascon.AsconXof128.hash

函数

第 720 行

对字节切片计算哈希,输出长度可变。

参数:

  • bytes:要计算哈希的输入数据
  • out:输出缓冲区(长度任意)
  • options:配置选项(当前未使用)

注意:这是组合 init、update 和 squeeze 的便利函数。

pub fn hash(bytes: []const u8, out: []u8, options: Options) void

参数

bytes: []const u8
out: []u8
options: Options

std.crypto.ascon.AsconXof128.init

函数

第 701 行

初始化新的 Ascon-XOF128 可扩展输出函数。

参数:

  • options:配置选项,目前未使用

返回:已初始化的 AsconXof128 实例。

pub fn init(options: Options) AsconXof128

参数

options: Options

std.crypto.ascon.AsconXof128.Options

命名空间

第 693 行

std.crypto.ascon.AsconXof128.squeeze

函数

第 767 行

从 XOF 中挤出输出字节。

参数:

  • out:要填入伪随机字节的输出缓冲区

注意:可多次调用以生成更多输出。 首次调用后,不能再通过 update() 吸收数据。

pub fn squeeze(self: *AsconXof128, out: []u8) void

参数

self: *AsconXof128
out: []u8

std.crypto.ascon.AsconXof128.update

函数

第 732 行

使用额外数据更新 XOF 状态。

参数:

  • b:要吸收到 XOF 状态中的数据

注意:调用 squeeze() 之后不可再调用。

pub fn update(self: *AsconXof128, b: []const u8) void

参数

self: *AsconXof128
b: []const u8

std.crypto.ascon.AuthenticationError

别名

第 314 行

别名目标 std.crypto.errors.AuthenticationError

std.crypto.ascon.builtin

常量

第 11 行

std.crypto.ascon.crypto

别名

第 12 行

别名目标 std.crypto

std.crypto.ascon.debug

别名

第 13 行

别名目标 std.debug

std.crypto.ascon.mem

别名

第 14 行

别名目标 std.mem

std.crypto.ascon.native_endian

常量

第 17 行

std.crypto.ascon.rotr

别名

第 16 行

别名目标 std.math.rotr

std.crypto.ascon.State

类型函数

第 26 行

Ascon 状态。

状态表示为 5 个 64 位字。

最初提交给 NIST 的版本 v1.2 按大端序列化这些字,但 NIST SP 800-232 改为小端表示。 软件实现可自由采用原生字节序,不会降低安全性。

pub fn State(comptime endian: std.builtin.Endian) type

参数

endian: std.builtin.Endian

字段

st: Block

std.crypto.ascon.State.addByte

函数

第 125 行

将一个字节异或到状态的给定偏移处。

参数:

  • byte:要异或到状态中的字节
  • offset:状态中的字节偏移,范围 0-39
pub fn addByte(self: *Self, byte: u8, offset: usize) void

参数

self: *Self
byte: u8
offset: usize

std.crypto.ascon.State.addBytes

函数

第 139 行

将字节异或到状态开头。

参数:

  • bytes:要异或到状态中的字节切片,最多 40 字节

注意:对不足一个块的输入补零处理。

pub fn addBytes(self: *Self, bytes: []const u8) void

参数

self: *Self
bytes: []const u8

std.crypto.ascon.State.asBytes

函数

第 89 行

状态的字节表示。字节序取决于架构。

返回:指向状态内部字节表示的指针。

pub fn asBytes(self: *Self) *[block_bytes]u8

参数

self: *Self

std.crypto.ascon.State.Block

类型

第 33 行

std.crypto.ascon.State.block_bytes

常量

第 31 行

状态的字节数。

std.crypto.ascon.State.clear

函数

第 200 行

将存储给定字节范围的各个字清零。

参数:

  • from:起始字节偏移,包含该位置
  • to:结束字节偏移,包含该位置

注意:会清除覆盖指定字节范围的整个字。

pub fn clear(self: *Self, from: usize, to: usize) void

参数

self: *Self
from: usize
to: usize

std.crypto.ascon.State.endianSwap

函数

第 96 行

如果架构字节序与所需字节序不匹配,则交换整个状态的字节顺序。

这可确保状态使用当前平台所需的正确字节序。

pub fn endianSwap(self: *Self) void

参数

self: *Self

std.crypto.ascon.State.extractBytes

函数

第 157 行

提取状态开头的字节。

参数:

  • out:接收提取字节的输出缓冲区

注意:从状态开头最多提取 out.len 字节。

pub fn extractBytes(self: *Self, out: []u8) void

参数

self: *Self
out: []u8

std.crypto.ascon.State.init

函数

第 43 行

通过字节切片初始化状态。

参数:

  • initial_state:用于初始化状态的 40 字节数组。

返回:使用所提供字节初始化的新 State。

pub fn init(initial_state: [block_bytes]u8) Self

参数

initial_state: [block_bytes]u8

std.crypto.ascon.State.initFromWords

函数

第 56 行

使用本机字节序的 u64 字初始化状态。

参数:

  • initial_state:包含 5 个本机字节序 u64 字的数组

返回值:使用所提供字创建的新 State。

pub fn initFromWords(initial_state: [5]u64) Self

参数

initial_state: [5]u64

std.crypto.ascon.State.initXof

函数

第 63 行

为 Ascon XOF 初始化状态。

返回:使用 Ascon XOF 初始化向量初始化的新 State

pub fn initXof() Self

std.crypto.ascon.State.initXofA

函数

第 76 行

初始化 Ascon XOFa 状态。

返回:以 Ascon XOFa 初始化向量初始化的新 State。

pub fn initXofA() Self

std.crypto.ascon.State.permute

函数

第 228 行

对状态应用完整轮数的置换。

应用标准的 12 轮 Ascon 置换。

pub fn permute(state: *Self) void

参数

state: *Self

std.crypto.ascon.State.permuteR

函数

第 218 行

对状态应用减轮置换。

参数:

  • rounds:要应用的轮数(1-12)。

注意:使用完整轮常量集合中的最后 rounds 个常量。

pub fn permuteR(state: *Self, comptime rounds: u4) void

参数

state: *Self
rounds: u4

std.crypto.ascon.State.permuteRatchet

函数

第 240 行

对状态应用置换,并防止回溯。

参数:

  • rounds:要应用的置换轮数
  • rate:速率,以字节为单位,必须为 8 的倍数且 < 40

置换前后均对容量部分进行异或, 以提供前向安全性,即棘轮机制。

pub fn permuteRatchet(state: *Self, comptime rounds: u4, comptime rate: u6) void

参数

state: *Self
rounds: u4
rate: u6

std.crypto.ascon.State.round

函数

第 255 行

Ascon 核心置换轮函数。

参数:

  • rk:本轮的轮常量

实现 Ascon 置换的一轮,包括 S 盒与线性层。

fn round(state: *Self, rk: u64) void

参数

state: *Self
rk: u64

std.crypto.ascon.State.secureZero

函数

第 208 行

清除整个状态,并禁止编译器优化此操作。

使用安全清零,防止编译器消除 清除操作。用于清理敏感数据。

pub fn secureZero(self: *Self) void

参数

self: *Self

std.crypto.ascon.State.Self

别名

第 28 行

别名目标 std.crypto.ascon.State

std.crypto.ascon.State.setBytes

函数

第 108 行

从状态的起始位置开始设置字节。

参数:

  • bytes:写入状态的字节切片(最多 40 字节)

注意:若 bytes.len < 40,则将剩余状态字填零。

pub fn setBytes(self: *Self, bytes: []const u8) void

参数

self: *Self
bytes: []const u8

std.crypto.ascon.State.xorBytes

函数

第 176 行

将状态的前几个字节异或到字节切片中。

参数:

  • out:异或结果的输出缓冲区
  • in:要与状态异或的输入字节

要求:out.len == in.len

pub fn xorBytes(self: *Self, out: []u8, in: []const u8) void

参数

self: *Self
out: []u8
in: []const u8

std.crypto.ascon.std

别名

第 10 行

别名目标 std

std.crypto.ascon.testing

别名

第 15 行

别名目标 std.testing

源码

std/crypto/ascon.zig

//! Ascon 是一种 320 位置换,在 NIST 轻量级密码学竞赛(2019–2023 年)中被选为新的轻量级密码学标准。
//! https://csrc.nist.gov/pubs/sp/800/232/ipd
//!
//! 此置换结构紧凑,并针对时序攻击和侧信道抵抗进行优化,适合嵌入式应用。
//!
//! 不应直接使用它,而应将其作为对称密码学的构建模块。
//!
//!

const std = @import("std");
const builtin = @import("builtin");
const crypto = std.crypto;
const debug = std.debug;
const mem = std.mem;
const testing = std.testing;
const rotr = std.math.rotr;
const native_endian = builtin.cpu.arch.endian();

/// Ascon 状态。
///
/// 状态表示为 5 个 64 位字。
///
/// 最初提交给 NIST 的版本 v1.2 按大端序列化这些字,但 NIST SP 800-232 改为小端表示。
/// 软件实现可自由采用原生字节序,不会降低安全性。
///
pub fn State(comptime endian: std.builtin.Endian) type {
    return struct {
        const Self = @This();

        /// 状态的字节数。
        pub const block_bytes = 40;

        const Block = [5]u64;

        st: Block,

        /// 通过字节切片初始化状态。
        ///
        /// 参数:
        ///   - initial_state:用于初始化状态的 40 字节数组。
        ///
        /// 返回:使用所提供字节初始化的新 State。
        pub fn init(initial_state: [block_bytes]u8) Self {
            var state = Self{ .st = undefined };
            @memcpy(state.asBytes(), &initial_state);
            state.endianSwap();
            return state;
        }

        /// 使用本机字节序的 u64 字初始化状态。
        ///
        /// 参数:
        ///   - initial_state:包含 5 个本机字节序 u64 字的数组
        ///
        /// 返回值:使用所提供字创建的新 State。
        pub fn initFromWords(initial_state: [5]u64) Self {
            return .{ .st = initial_state };
        }

        /// 为 Ascon XOF 初始化状态。
        ///
        /// 返回:使用 Ascon XOF 初始化向量初始化的新 State
        pub fn initXof() Self {
            return Self{ .st = Block{
                0xb57e273b814cd416,
                0x2b51042562ae2420,
                0x66a3a7768ddf2218,
                0x5aad0a7a8153650c,
                0x4f3e0e32539493b6,
            } };
        }

        /// 初始化 Ascon XOFa 状态。
        ///
        /// 返回:以 Ascon XOFa 初始化向量初始化的新 State。
        pub fn initXofA() Self {
            return Self{ .st = Block{
                0x44906568b77b9832,
                0xcd8d6cae53455532,
                0xf7b5212756422129,
                0x246885e1de0d225b,
                0xa8cb5ce33449973f,
            } };
        }

        /// 状态的字节表示。字节序取决于架构。
        ///
        /// 返回:指向状态内部字节表示的指针。
        pub fn asBytes(self: *Self) *[block_bytes]u8 {
            return mem.asBytes(&self.st);
        }

        /// 如果架构字节序与所需字节序不匹配,则交换整个状态的字节顺序。
        ///
        /// 这可确保状态使用当前平台所需的正确字节序。
        pub fn endianSwap(self: *Self) void {
            for (&self.st) |*w| {
                w.* = mem.toNative(u64, w.*, endian);
            }
        }

        /// 从状态的起始位置开始设置字节。
        ///
        /// 参数:
        ///   - bytes:写入状态的字节切片(最多 40 字节)
        ///
        /// 注意:若 bytes.len < 40,则将剩余状态字填零。
        pub fn setBytes(self: *Self, bytes: []const u8) void {
            var i: usize = 0;
            while (i + 8 <= bytes.len) : (i += 8) {
                self.st[i / 8] = mem.readInt(u64, bytes[i..][0..8], endian);
            }
            if (i < bytes.len) {
                var padded: [8]u8 = @splat(0);
                @memcpy(padded[0 .. bytes.len - i], bytes[i..]);
                self.st[i / 8] = mem.readInt(u64, padded[0..], endian);
            }
        }

        /// 将一个字节异或到状态的给定偏移处。
        ///
        /// 参数:
        ///   - byte:要异或到状态中的字节
        ///   - offset:状态中的字节偏移,范围 0-39
        pub fn addByte(self: *Self, byte: u8, offset: usize) void {
            const z = switch (endian) {
                .big => 64 - 8 - 8 * @as(u6, @truncate(offset % 8)),
                .little => 8 * @as(u6, @truncate(offset % 8)),
            };
            self.st[offset / 8] ^= @as(u64, byte) << z;
        }

        /// 将字节异或到状态开头。
        ///
        /// 参数:
        ///   - bytes:要异或到状态中的字节切片,最多 40 字节
        ///
        /// 注意:对不足一个块的输入补零处理。
        pub fn addBytes(self: *Self, bytes: []const u8) void {
            var i: usize = 0;
            while (i + 8 <= bytes.len) : (i += 8) {
                self.st[i / 8] ^= mem.readInt(u64, bytes[i..][0..8], endian);
            }
            if (i < bytes.len) {
                var padded: [8]u8 = @splat(0);
                @memcpy(padded[0 .. bytes.len - i], bytes[i..]);
                self.st[i / 8] ^= mem.readInt(u64, padded[0..], endian);
            }
        }

        /// 提取状态开头的字节。
        ///
        /// 参数:
        ///   - out:接收提取字节的输出缓冲区
        ///
        /// 注意:从状态开头最多提取 out.len 字节。
        pub fn extractBytes(self: *Self, out: []u8) void {
            var i: usize = 0;
            while (i + 8 <= out.len) : (i += 8) {
                mem.writeInt(u64, out[i..][0..8], self.st[i / 8], endian);
            }
            if (i < out.len) {
                var padded: [8]u8 = @splat(0);
                mem.writeInt(u64, padded[0..], self.st[i / 8], endian);
                @memcpy(out[i..], padded[0 .. out.len - i]);
            }
        }

        /// 将状态的前几个字节异或到字节切片中。
        ///
        /// 参数:
        ///   - out:异或结果的输出缓冲区
        ///   - in:要与状态异或的输入字节
        ///
        /// 要求:out.len == in.len
        pub fn xorBytes(self: *Self, out: []u8, in: []const u8) void {
            debug.assert(out.len == in.len);

            var i: usize = 0;
            while (i + 8 <= in.len) : (i += 8) {
                const x = mem.readInt(u64, in[i..][0..8], native_endian) ^ mem.nativeTo(u64, self.st[i / 8], endian);
                mem.writeInt(u64, out[i..][0..8], x, native_endian);
            }
            if (i < in.len) {
                var padded: [8]u8 = @splat(0);
                @memcpy(padded[0 .. in.len - i], in[i..]);
                const x = mem.readInt(u64, &padded, native_endian) ^ mem.nativeTo(u64, self.st[i / 8], endian);
                mem.writeInt(u64, &padded, x, native_endian);
                @memcpy(out[i..], padded[0 .. in.len - i]);
            }
        }

        /// 将存储给定字节范围的各个字清零。
        ///
        /// 参数:
        ///   - from:起始字节偏移,包含该位置
        ///   - to:结束字节偏移,包含该位置
        ///
        /// 注意:会清除覆盖指定字节范围的整个字。
        pub fn clear(self: *Self, from: usize, to: usize) void {
            @memset(self.st[from / 8 .. @divCeil(to, 8)], 0);
        }

        /// 清除整个状态,并禁止编译器优化此操作。
        ///
        /// 使用安全清零,防止编译器消除
        /// 清除操作。用于清理敏感数据。
        pub fn secureZero(self: *Self) void {
            crypto.secureZero(u64, &self.st);
        }

        /// 对状态应用减轮置换。
        ///
        /// 参数:
        ///   - rounds:要应用的轮数(1-12)。
        ///
        /// 注意:使用完整轮常量集合中的最后 `rounds` 个常量。
        pub fn permuteR(state: *Self, comptime rounds: u4) void {
            const rks = [16]u64{ 0x3c, 0x2d, 0x1e, 0x0f, 0xf0, 0xe1, 0xd2, 0xc3, 0xb4, 0xa5, 0x96, 0x87, 0x78, 0x69, 0x5a, 0x4b };
            inline for (rks[rks.len - rounds ..]) |rk| {
                state.round(rk);
            }
        }

        /// 对状态应用完整轮数的置换。
        ///
        /// 应用标准的 12 轮 Ascon 置换。
        pub fn permute(state: *Self) void {
            state.permuteR(12);
        }

        /// 对状态应用置换,并防止回溯。
        ///
        /// 参数:
        ///   - rounds:要应用的置换轮数
        ///   - rate:速率,以字节为单位,必须为 8 的倍数且 < 40
        ///
        /// 置换前后均对容量部分进行异或,
        /// 以提供前向安全性,即棘轮机制。
        pub fn permuteRatchet(state: *Self, comptime rounds: u4, comptime rate: u6) void {
            const capacity = block_bytes - rate;
            debug.assert(capacity > 0 and capacity % 8 == 0); // 容量必须为 64 位的倍数
            var mask: [capacity / 8]u64 = undefined;
            inline for (&mask, state.st[state.st.len - mask.len ..]) |*m, x| m.* = x;
            state.permuteR(rounds);
            inline for (mask, state.st[state.st.len - mask.len ..]) |m, *x| x.* ^= m;
        }

        /// Ascon 核心置换轮函数。
        ///
        /// 参数:
        ///   - rk:本轮的轮常量
        ///
        /// 实现 Ascon 置换的一轮,包括 S 盒与线性层。
        fn round(state: *Self, rk: u64) void {
            const x = &state.st;
            x[2] ^= rk;

            x[0] ^= x[4];
            x[4] ^= x[3];
            x[2] ^= x[1];
            var t: Block = .{
                x[0] ^ (~x[1] & x[2]),
                x[1] ^ (~x[2] & x[3]),
                x[2] ^ (~x[3] & x[4]),
                x[3] ^ (~x[4] & x[0]),
                x[4] ^ (~x[0] & x[1]),
            };
            t[1] ^= t[0];
            t[3] ^= t[2];
            t[0] ^= t[4];

            x[2] = t[2] ^ rotr(u64, t[2], 6 - 1);
            x[3] = t[3] ^ rotr(u64, t[3], 17 - 10);
            x[4] = t[4] ^ rotr(u64, t[4], 41 - 7);
            x[0] = t[0] ^ rotr(u64, t[0], 28 - 19);
            x[1] = t[1] ^ rotr(u64, t[1], 61 - 39);
            x[2] = t[2] ^ rotr(u64, x[2], 1);
            x[3] = t[3] ^ rotr(u64, x[3], 10);
            x[4] = t[4] ^ rotr(u64, x[4], 7);
            x[0] = t[0] ^ rotr(u64, x[0], 19);
            x[1] = t[1] ^ rotr(u64, x[1], 39);
            x[2] = ~x[2];
        }
    };
}

test "ascon" {
    const Ascon = State(.big);
    var bytes: [Ascon.block_bytes]u8 = undefined;
    @memset(&bytes, 1);
    var st = Ascon.init(bytes);
    var out: [Ascon.block_bytes]u8 = undefined;
    st.permute();
    st.extractBytes(&out);
    const expected1 = [_]u8{ 148, 147, 49, 226, 218, 221, 208, 113, 186, 94, 96, 10, 183, 219, 119, 150, 169, 206, 65, 18, 215, 97, 78, 106, 118, 81, 211, 150, 52, 17, 117, 64, 216, 45, 148, 240, 65, 181, 90, 180 };
    try testing.expectEqualSlices(u8, &expected1, &out);
    st.clear(0, 10);
    st.extractBytes(&out);
    const expected2 = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 169, 206, 65, 18, 215, 97, 78, 106, 118, 81, 211, 150, 52, 17, 117, 64, 216, 45, 148, 240, 65, 181, 90, 180 };
    try testing.expectEqualSlices(u8, &expected2, &out);
    st.addByte(1, 5);
    st.addByte(2, 5);
    st.extractBytes(&out);
    const expected3 = [_]u8{ 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 169, 206, 65, 18, 215, 97, 78, 106, 118, 81, 211, 150, 52, 17, 117, 64, 216, 45, 148, 240, 65, 181, 90, 180 };
    try testing.expectEqualSlices(u8, &expected3, &out);
    st.addBytes(&bytes);
    st.extractBytes(&out);
    const expected4 = [_]u8{ 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 168, 207, 64, 19, 214, 96, 79, 107, 119, 80, 210, 151, 53, 16, 116, 65, 217, 44, 149, 241, 64, 180, 91, 181 };
    try testing.expectEqualSlices(u8, &expected4, &out);
}

const AsconState = State(.little);
const AuthenticationError = crypto.errors.AuthenticationError;

/// NIST SP 800-232 第 4 节规定的 Ascon-AEAD128
pub const AsconAead128 = struct {
    pub const tag_length = 16;
    pub const nonce_length = 16;
    pub const key_length = 16;
    pub const block_length = 16;

    const AeadState = struct {
        st: AsconState,
        k0: u64,
        k1: u64,

        /// 使用密钥和 nonce 初始化 AEAD 状态。
        ///
        /// 参数:
        ///   - key:16 字节密钥
        ///   - nonce:16 字节 nonce
        ///
        /// 返回值:已初始化、可开始处理的 AEAD 状态。
        fn init(key: [16]u8, nonce: [16]u8) AeadState {
            const k0 = mem.readInt(u64, key[0..8], .little);
            const k1 = mem.readInt(u64, key[8..16], .little);
            const n0 = mem.readInt(u64, nonce[0..8], .little);
            const n1 = mem.readInt(u64, nonce[8..16], .little);

            // Ascon-AEAD128(Ascon-128a)的 IV
            const iv: u64 = 0x00001000808C0001;
            const words: [5]u64 = .{ iv, k0, k1, n0, n1 };

            var st = AsconState.initFromWords(words);
            st.permuteR(12);

            st.st[3] ^= k0;
            st.st[4] ^= k1;

            return AeadState{ .st = st, .k0 = k0, .k1 = k1 };
        }

        /// 处理用于认证的关联数据。
        ///
        /// 参数:
        ///   - ad:要认证的关联数据。
        ///
        /// 更新状态,将 AD 纳入认证标签计算。
        fn processAd(self: *AeadState, ad: []const u8) void {
            if (ad.len == 0) return;

            var i: usize = 0;
            // 处理完整的 128 位数据块
            while (i + 16 <= ad.len) : (i += 16) {
                self.st.addBytes(ad[i..][0..16]);
                self.st.permuteR(8);
            }

            // 处理末尾不完整的 AD 块
            const adrem = ad.len - i;
            if (adrem > 0) {
                if (adrem >= 8) {
                    var buf: [8]u8 = @splat(0);
                    @memcpy(buf[0..8], ad[i..][0..8]);
                    self.st.st[0] ^= mem.readInt(u64, &buf, .little);

                    buf = @splat(0);
                    @memcpy(buf[0 .. adrem - 8], ad[i + 8 ..]);
                    buf[adrem - 8] = 0x01;
                    self.st.st[1] ^= mem.readInt(u64, &buf, .little);
                } else {
                    var buf: [8]u8 = @splat(0);
                    @memcpy(buf[0..adrem], ad[i..]);
                    buf[adrem] = 0x01;
                    self.st.st[0] ^= mem.readInt(u64, &buf, .little);
                }
                self.st.permuteR(8);
            }
        }

        /// 结束 AEAD 操作并生成标签。
        ///
        /// 应用最终置换并与密钥异或,以生成标签。
        fn finalize(self: *AeadState) void {
            // 最终置换前异或密钥
            self.st.st[2] ^= self.k0;
            self.st.st[3] ^= self.k1;
            self.st.permuteR(12);

            // 再次异或密钥以生成标签
            self.st.st[3] ^= self.k0;
            self.st.st[4] ^= self.k1;
        }
    };

    /// 使用 Ascon-AEAD128 加密消息。
    ///
    /// 参数:
    ///   - c:密文输出缓冲区,长度必须与 m 相同。
    ///   - tag:认证标签输出缓冲区,16 字节。
    ///   - m:待加密明文消息。
    ///   - ad:只认证而不加密的关联数据。
    ///   - npub:公开 nonce,16 字节,每条消息必须唯一。
    ///   - k:秘密密钥,16 字节。
    ///
    /// 注意:解密需要一并传输密文和标签。
    pub fn encrypt(c: []u8, tag: *[tag_length]u8, m: []const u8, ad: []const u8, npub: [nonce_length]u8, k: [key_length]u8) void {
        debug.assert(c.len == m.len);

        var state = AeadState.init(k, npub);

        // 处理关联数据
        state.processAd(ad);

        // 域分离(小端序第 7 字节处 DSEP = 0x80)。
        state.st.st[4] ^= 0x8000000000000000;

        // 处理明文
        var i: usize = 0;
        while (i + 16 <= m.len) : (i += 16) {
            state.st.addBytes(m[i..][0..16]);
            state.st.extractBytes(c[i..][0..16]);
            state.st.permuteR(8);
        }

        // 处理最后一个不完整块
        const remaining = m.len - i;
        if (remaining > 8) {
            // 在两个字之间拆分
            state.st.addBytes(m[i..][0..8]);
            state.st.extractBytes(c[i..][0..8]);

            var buf: [8]u8 = @splat(0);
            @memcpy(buf[0 .. remaining - 8], m[i + 8 ..]);
            const m1 = mem.readInt(u64, &buf, .little);
            state.st.st[1] ^= m1;
            mem.writeInt(u64, buf[0..], state.st.st[1], .little);
            @memcpy(c[i + 8 ..], buf[0 .. remaining - 8]);

            // 添加填充
            state.st.st[1] ^= @as(u64, 0x01) << @intCast((remaining - 8) * 8);
        } else if (remaining == 8) {
            // 恰好 8 字节:全部位于字 0,填充位于字 1
            state.st.addBytes(m[i..][0..8]);
            state.st.extractBytes(c[i..][0..8]);

            // 在字 1 的位置 0 添加填充
            state.st.st[1] ^= 0x01;
        } else if (remaining > 0) {
            // 全部在第一个字中
            var temp: [8]u8 = @splat(0);
            @memcpy(temp[0..remaining], m[i..]);
            state.st.addBytes(&temp);
            state.st.extractBytes(c[i..][0..remaining]);
            // 添加填充
            temp = @splat(0);
            temp[remaining] = 0x01;
            state.st.addBytes(&temp);
            // 第二个字保持为零
        } else {
            // 消息为空或长度为整倍数时,添加填充块
            var padded: [16]u8 = @splat(0);
            padded[0] = 0x01;
            state.st.addBytes(&padded);
        }

        // 最终处理
        state.finalize();

        // 提取标签
        mem.writeInt(u64, tag[0..8], state.st.st[3], .little);
        mem.writeInt(u64, tag[8..16], state.st.st[4], .little);
    }

    /// 使用 Ascon-AEAD128 解密消息。
    ///
    /// 参数:
    ///   - m:明文输出缓冲区,长度必须与 c 相同。
    ///   - c:待解密密文。
    ///   - tag:认证标签,16 字节。
    ///   - ad:经过认证的关联数据。
    ///   - npub:加密时使用的公开 nonce,16 字节。
    ///   - k:秘密密钥,16 字节。
    ///
    /// 返回:标签验证失败时返回 AuthenticationError。
    ///
    /// 注意:认证失败时,会安全地将输出缓冲区清零。
    pub fn decrypt(m: []u8, c: []const u8, tag: [tag_length]u8, ad: []const u8, npub: [nonce_length]u8, k: [key_length]u8) AuthenticationError!void {
        debug.assert(m.len == c.len);

        var state = AeadState.init(k, npub);

        // 处理关联数据
        state.processAd(ad);

        // 域分离(小端序第 7 字节处 DSEP = 0x80)。
        state.st.st[4] ^= 0x8000000000000000;

        // 处理密文
        var i: usize = 0;
        while (i + 16 <= c.len) : (i += 16) {
            const ct_block = c[i..][0..16].*; // 保存密文块,以支持原地操作。
            state.st.xorBytes(m[i..][0..16], &ct_block);
            state.st.setBytes(&ct_block);
            state.st.permuteR(8);
        }

        // 最后一个不完整密文块
        const crem = c.len - i;
        if (crem > 8) {
            // 保存密文以支持原地操作
            var saved_ct: [16]u8 = undefined;
            @memcpy(saved_ct[0..crem], c[i..]);

            const c0 = mem.readInt(u64, saved_ct[0..8], .little);
            state.st.st[0] ^= c0;
            mem.writeInt(u64, m[i..][0..8], state.st.st[0], .little);
            state.st.st[0] = c0;

            var buf: [8]u8 = @splat(0);
            @memcpy(buf[0 .. crem - 8], saved_ct[8..][0 .. crem - 8]);
            const c1 = mem.readInt(u64, &buf, .little);
            const m1 = state.st.st[1] ^ c1;
            mem.writeInt(u64, buf[0..], m1, .little);
            @memcpy(m[i + 8 ..], buf[0 .. crem - 8]);

            // 仅替换已读取的字节,保持高位字节不变
            const mask = (@as(u64, 1) << @intCast((crem - 8) * 8)) - 1;
            state.st.st[1] = (state.st.st[1] & ~mask) | (c1 & mask);

            state.st.st[1] ^= @as(u64, 0x01) << @intCast((crem - 8) * 8);
        } else if (crem == 8) {
            // 恰好 8 字节:仅处理字 0,在字 1 中添加填充。
            const saved_ct = c[i..][0..8].*;

            const c0 = mem.readInt(u64, &saved_ct, .little);
            state.st.st[0] ^= c0;
            mem.writeInt(u64, m[i..][0..8], state.st.st[0], .little);
            state.st.st[0] = c0;

            // 在字 1 的位置 0 添加填充
            state.st.st[1] ^= 0x01;
        } else if (crem > 0) {
            var buf: [8]u8 = @splat(0);
            @memcpy(buf[0..crem], c[i..]);
            const c0 = mem.readInt(u64, &buf, .little);
            const m0 = state.st.st[0] ^ c0;
            mem.writeInt(u64, buf[0..], m0, .little);
            @memcpy(m[i..], buf[0..crem]);

            // 仅替换已读取的字节,保持高位字节不变
            const mask = (@as(u64, 1) << @intCast(crem * 8)) - 1;
            state.st.st[0] = (state.st.st[0] & ~mask) | (c0 & mask);

            state.st.st[0] ^= @as(u64, 0x01) << @intCast(crem * 8);
        } else {
            state.st.st[0] ^= 0x01;
        }

        // 最终处理
        state.finalize();

        // 验证标签
        var computed_tag: [tag_length]u8 = undefined;
        mem.writeInt(u64, computed_tag[0..8], state.st.st[3], .little);
        mem.writeInt(u64, computed_tag[8..16], state.st.st[4], .little);

        if (!crypto.timing_safe.eql([tag_length]u8, tag, computed_tag)) {
            crypto.secureZero(u8, m);
            return error.AuthenticationFailed;
        }
    }
};

/// NIST SP 800-232 第 5 节规定的 Ascon-Hash256
pub const AsconHash256 = struct {
    pub const digest_length = 32;
    pub const block_length = 8;

    st: AsconState,

    pub const Options = struct {};

    /// 初始化新的 Ascon-Hash256 哈希器。
    ///
    /// 参数:
    ///   - options:配置选项,目前未使用
    ///
    /// 返回:已初始化的 AsconHash256 哈希器。
    pub fn init(options: Options) AsconHash256 {
        _ = options;

        // Ascon-Hash256 的初始向量:0x0000080100cc0002
        const iv: u64 = 0x0000080100cc0002;
        const words: [5]u64 = .{ iv, 0, 0, 0, 0 };
        var st = AsconState.initFromWords(words);
        st.permuteR(12);
        return AsconHash256{ .st = st };
    }

    /// 一次调用计算输入数据的 Ascon-Hash256 哈希。
    ///
    /// 参数:
    ///   - b:待哈希的输入数据
    ///   - out:用于 32 字节哈希摘要的输出缓冲区
    ///   - options:配置选项,目前未使用
    pub fn hash(b: []const u8, out: *[digest_length]u8, options: Options) void {
        var h = init(options);
        h.update(b);
        h.final(out);
    }

    /// 使用额外数据更新哈希状态。
    ///
    /// 参数:
    ///   - b:加入哈希的数据
    ///
    /// 注意:可在 final() 前多次调用。
    pub fn update(self: *AsconHash256, b: []const u8) void {
        var i: usize = 0;

        // 处理完整的 64 位数据块
        while (i + 8 <= b.len) : (i += 8) {
            self.st.addBytes(b[i..][0..8]);
            self.st.permuteR(12);
        }

        // 保存不完整数据块供最终处理
        if (i < b.len) {
            var padded: [8]u8 = @splat(0);
            const remaining = b.len - i;
            @memcpy(padded[0..remaining], b[i..]);
            padded[remaining] = 0x01;
            self.st.addBytes(&padded);
        } else {
            // 添加填充块
            var padded: [8]u8 = @splat(0);
            padded[0] = 0x01;
            self.st.addBytes(&padded);
        }
    }

    /// 完成哈希计算并输出摘要。
    ///
    /// 参数:
    ///   - out:用于输出 32 字节哈希摘要的缓冲区。
    ///
    /// 注意:调用 final() 后,不应再次使用该哈希器。
    pub fn final(self: *AsconHash256, out: *[digest_length]u8) void {
        // 填充后的最终置换
        self.st.permuteR(12);

        // 提取哈希输出(4 × 64 位 = 256 位)
        var h: [4]u64 = undefined;
        for (0..4) |i| {
            h[i] = self.st.st[0];
            self.st.permuteR(12);
        }

        // 写入输出
        for (0..4) |i| {
            mem.writeInt(u64, out[i * 8 ..][0..8], h[i], .little);
        }
    }

    pub fn finalResult(d: *AsconHash256) [digest_length]u8 {
        var result: [digest_length]u8 = undefined;
        d.final(&result);
        return result;
    }
};

/// NIST SP 800-232 第 5 节规定的 Ascon-XOF128
pub const AsconXof128 = struct {
    pub const block_length = 8;

    st: AsconState,
    squeezed: bool,
    buf: [block_length]u8,
    buf_len: usize,

    pub const Options = struct {};

    /// 初始化新的 Ascon-XOF128 可扩展输出函数。
    ///
    /// 参数:
    ///   - options:配置选项,目前未使用
    ///
    /// 返回:已初始化的 AsconXof128 实例。
    pub fn init(options: Options) AsconXof128 {
        _ = options;

        // Ascon-XOF128 的 IV:0x0000080000cc0003
        const iv: u64 = 0x0000080000cc0003;
        const words: [5]u64 = .{ iv, 0, 0, 0, 0 };
        var st = AsconState.initFromWords(words);
        st.permuteR(12);
        return AsconXof128{ .st = st, .squeezed = false, .buf = @splat(0), .buf_len = 0 };
    }

    /// 对字节切片计算哈希,输出长度可变。
    ///
    /// 参数:
    ///   - bytes:要计算哈希的输入数据
    ///   - out:输出缓冲区(长度任意)
    ///   - options:配置选项(当前未使用)
    ///
    /// 注意:这是组合 init、update 和 squeeze 的便利函数。
    pub fn hash(bytes: []const u8, out: []u8, options: Options) void {
        var st = init(options);
        st.update(bytes);
        st.squeeze(out);
    }

    /// 使用额外数据更新 XOF 状态。
    ///
    /// 参数:
    ///   - b:要吸收到 XOF 状态中的数据
    ///
    /// 注意:调用 squeeze() 之后不可再调用。
    pub fn update(self: *AsconXof128, b: []const u8) void {
        debug.assert(!self.squeezed); // 开始挤出后无法更新

        var i: usize = 0;

        if (self.buf_len > 0) {
            const to_fill = @min(block_length - self.buf_len, b.len);
            @memcpy(self.buf[self.buf_len..][0..to_fill], b[0..to_fill]);
            self.buf_len += to_fill;
            i += to_fill;
            if (self.buf_len == block_length) {
                self.st.addBytes(&self.buf);
                self.st.permuteR(12);
                self.buf_len = 0;
            }
        }

        while (i + block_length <= b.len) : (i += block_length) {
            self.st.addBytes(b[i..][0..block_length]);
            self.st.permuteR(12);
        }

        if (i < b.len) {
            self.buf_len = b.len - i;
            @memcpy(self.buf[0..self.buf_len], b[i..]);
        }
    }

    /// 从 XOF 中挤出输出字节。
    ///
    /// 参数:
    ///   - out:要填入伪随机字节的输出缓冲区
    ///
    /// 注意:可多次调用以生成更多输出。
    /// 首次调用后,不能再通过 update() 吸收数据。
    pub fn squeeze(self: *AsconXof128, out: []u8) void {
        if (!self.squeezed) {
            var padded: [block_length]u8 = @splat(0);
            @memcpy(padded[0..self.buf_len], self.buf[0..self.buf_len]);
            padded[self.buf_len] = 0x01;
            self.st.addBytes(&padded);
            self.st.permuteR(12);
            self.squeezed = true;
        }

        var i: usize = 0;
        while (i < out.len) {
            const to_copy = @min(8, out.len - i);
            var block: [8]u8 = undefined;
            mem.writeInt(u64, &block, self.st.st[0], .little);
            @memcpy(out[i..][0..to_copy], block[0..to_copy]);
            i += to_copy;

            if (i < out.len) {
                self.st.permuteR(12);
            }
        }
    }
};

/// NIST SP 800-232 第 5 节规定的 Ascon-CXOF128。
pub const AsconCxof128 = struct {
    pub const block_length = 8;
    pub const max_custom_length = 256; // 2048 位

    st: AsconState,
    squeezed: bool,
    buf: [block_length]u8,
    buf_len: usize,

    pub const Options = struct { custom: []const u8 = "" };

    /// 初始化新的 Ascon-CXOF128 可定制 XOF。
    ///
    /// 参数:
    ///   - options:配置,包含可选的自定义字符串
    ///     - custom:自定义字符串,最长 256 字节
    ///
    /// 返回:初始化后的 AsconCxof128 实例。
    ///
    /// 注意:不同自定义字符串产生相互独立的 XOF 实例。
    pub fn init(options: Options) AsconCxof128 {
        debug.assert(options.custom.len <= max_custom_length);

        // Ascon-CXOF128 的 IV:0x0000080000cc0004
        const iv: u64 = 0x0000080000cc0004;
        const words: [5]u64 = .{ iv, 0, 0, 0, 0 };
        var st = AsconState.initFromWords(words);
        st.permuteR(12);

        var self = AsconCxof128{ .st = st, .squeezed = false, .buf = @splat(0), .buf_len = 0 };

        // 处理自定义字符串;始终处理长度和填充。
        // 首块:自定义字符串的长度。
        const len_block = @as(u64, options.custom.len * 8); // 位长度
        self.st.st[0] ^= len_block;
        self.st.permuteR(12);

        if (options.custom.len > 0) {
            // 处理定制字符串分组
            var i: usize = 0;
            while (i + 8 <= options.custom.len) : (i += 8) {
                self.st.addBytes(options.custom[i..][0..8]);
                self.st.permuteR(12);
            }

            // 使用填充处理末尾不完整的数据块
            if (i < options.custom.len) {
                var padded: [8]u8 = @splat(0);
                const remaining = options.custom.len - i;
                @memcpy(padded[0..remaining], options.custom[i..]);
                padded[remaining] = 0x01;
                self.st.addBytes(&padded);
                self.st.permuteR(12);
            } else {
                // 添加填充块
                var padded: [8]u8 = @splat(0);
                padded[0] = 0x01;
                self.st.addBytes(&padded);
                self.st.permuteR(12);
            }
        } else {
            // 空的自定义内容仍需要填充
            var padded: [8]u8 = @splat(0);
            padded[0] = 0x01;
            self.st.addBytes(&padded);
            self.st.permuteR(12);
        }

        return self;
    }

    /// 对字节切片计算哈希,支持自定义参数和可变长度输出。
    ///
    /// 参数:
    ///   - bytes:要计算哈希的输入数据
    ///   - out:输出缓冲区(长度任意)
    ///   - options:包含可选自定义字符串的配置
    ///
    /// 注意:这是组合 init、update 和 squeeze 的便利函数。
    pub fn hash(bytes: []const u8, out: []u8, options: Options) void {
        var st = init(options);
        st.update(bytes);
        st.squeeze(out);
    }

    /// 使用额外数据更新 CXOF 状态。
    ///
    /// 参数:
    ///   - b:要吸收到 CXOF 状态的数据
    ///
    /// 注意:调用 squeeze() 后不能再调用此函数。
    pub fn update(self: *AsconCxof128, b: []const u8) void {
        debug.assert(!self.squeezed); // 开始挤出后无法更新

        var i: usize = 0;

        if (self.buf_len > 0) {
            const to_fill = @min(block_length - self.buf_len, b.len);
            @memcpy(self.buf[self.buf_len..][0..to_fill], b[0..to_fill]);
            self.buf_len += to_fill;
            i += to_fill;
            if (self.buf_len == block_length) {
                self.st.addBytes(&self.buf);
                self.st.permuteR(12);
                self.buf_len = 0;
            }
        }

        while (i + block_length <= b.len) : (i += block_length) {
            self.st.addBytes(b[i..][0..block_length]);
            self.st.permuteR(12);
        }

        if (i < b.len) {
            self.buf_len = b.len - i;
            @memcpy(self.buf[0..self.buf_len], b[i..]);
        }
    }

    /// 从可自定义的 XOF 中挤出输出字节。
    ///
    /// 参数:
    ///   - out:要填入伪随机字节的输出缓冲区
    ///
    /// 注意:可多次调用以生成更多输出。
    /// 首次调用后,不能再通过 update() 吸收数据。
    pub fn squeeze(self: *AsconCxof128, out: []u8) void {
        if (!self.squeezed) {
            var padded: [block_length]u8 = @splat(0);
            @memcpy(padded[0..self.buf_len], self.buf[0..self.buf_len]);
            padded[self.buf_len] = 0x01;
            self.st.addBytes(&padded);
            self.st.permuteR(12);
            self.squeezed = true;
        }

        var i: usize = 0;
        while (i < out.len) {
            const to_copy = @min(8, out.len - i);
            var block: [8]u8 = undefined;
            mem.writeInt(u64, &block, self.st.st[0], .little);
            @memcpy(out[i..][0..to_copy], block[0..to_copy]);
            i += to_copy;

            if (i < out.len) {
                self.st.permuteR(12);
            }
        }
    }
};

test "Ascon-Hash256 basic test" {
    const message = "The quick brown fox jumps over the lazy dog";
    var hash: [32]u8 = undefined;

    AsconHash256.hash(message, &hash, .{});

    // 验证已生成哈希(精确值取决于测试向量)
    try testing.expect(hash.len == 32);
}

test "Ascon-XOF128 basic test" {
    var xof = AsconXof128.init(.{});
    xof.update("Hello, ");
    xof.update("World!");

    var out1: [16]u8 = undefined;
    xof.squeeze(&out1);

    var out2: [32]u8 = undefined;
    xof.squeeze(&out2);

    // XOF 的输出应连续——out2 不应与 out1 匹配
    // 每次挤出操作均生成新的输出
    try testing.expect(!mem.eql(u8, &out1, out2[0..16]));
}

test "Ascon-CXOF128 with customization" {
    const custom = "MyCustomString";
    var xof = AsconCxof128.init(.{ .custom = custom });
    xof.update("Test message");

    var out: [32]u8 = undefined;
    xof.squeeze(&out);

    // 不同的自定义信息应产生不同输出
    var xof2 = AsconCxof128.init(.{ .custom = "DifferentCustom" });
    xof2.update("Test message");

    var out2: [32]u8 = undefined;
    xof2.squeeze(&out2);

    try testing.expect(!mem.eql(u8, &out, &out2));
}

test "Ascon-AEAD128 round trip with various data sizes" {
    const key = [_]u8{ 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10 };
    const nonce = [_]u8{ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };

    // 使用空明文测试
    {
        const plaintext = "";
        const ad = "metadata";
        var ciphertext: [plaintext.len]u8 = undefined;
        var tag: [16]u8 = undefined;

        AsconAead128.encrypt(&ciphertext, &tag, plaintext, ad, nonce, key);

        var decrypted: [plaintext.len]u8 = undefined;
        try AsconAead128.decrypt(&decrypted, &ciphertext, tag, ad, nonce, key);
        try testing.expectEqualStrings(plaintext, &decrypted);
    }

    // 使用短明文测试
    {
        const plaintext = "Short";
        const ad = "";
        var ciphertext: [plaintext.len]u8 = undefined;
        var tag: [16]u8 = undefined;

        AsconAead128.encrypt(&ciphertext, &tag, plaintext, ad, nonce, key);

        var decrypted: [plaintext.len]u8 = undefined;
        try AsconAead128.decrypt(&decrypted, &ciphertext, tag, ad, nonce, key);
        try testing.expectEqualStrings(plaintext, &decrypted);
    }

    // 使用更长明文及关联数据测试。
    {
        const plaintext = "This is a longer message to test the round trip encryption and decryption process";
        const ad = "Additional authenticated data that is not encrypted but is authenticated";
        var ciphertext: [plaintext.len]u8 = undefined;
        var tag: [16]u8 = undefined;

        AsconAead128.encrypt(&ciphertext, &tag, plaintext, ad, nonce, key);

        var decrypted: [plaintext.len]u8 = undefined;
        try AsconAead128.decrypt(&decrypted, &ciphertext, tag, ad, nonce, key);
        try testing.expectEqualStrings(plaintext, &decrypted);
    }

    // 使用被篡改的密文测试认证失败
    {
        const plaintext = "Tamper test";
        const ad = "metadata";
        var ciphertext: [plaintext.len]u8 = undefined;
        var tag: [16]u8 = undefined;

        AsconAead128.encrypt(&ciphertext, &tag, plaintext, ad, nonce, key);

        // 篡改密文
        ciphertext[0] ^= 0xFF;

        var decrypted: [plaintext.len]u8 = undefined;
        const result = AsconAead128.decrypt(&decrypted, &ciphertext, tag, ad, nonce, key);
        try testing.expectError(error.AuthenticationFailed, result);
    }

    // 测试标签错误时的认证失败
    {
        const plaintext = "Tag test";
        const ad = "metadata";
        var ciphertext: [plaintext.len]u8 = undefined;
        var tag: [16]u8 = undefined;

        AsconAead128.encrypt(&ciphertext, &tag, plaintext, ad, nonce, key);

        // 篡改标签
        var wrong_tag = tag;
        wrong_tag[0] ^= 0xFF;

        var decrypted: [plaintext.len]u8 = undefined;
        const result = AsconAead128.decrypt(&decrypted, &ciphertext, wrong_tag, ad, nonce, key);
        try testing.expectError(error.AuthenticationFailed, result);
    }

    // 使用错误的关联数据测试认证失败
    {
        const plaintext = "AD test";
        const ad = "original";
        var ciphertext: [plaintext.len]u8 = undefined;
        var tag: [16]u8 = undefined;

        AsconAead128.encrypt(&ciphertext, &tag, plaintext, ad, nonce, key);

        var decrypted: [plaintext.len]u8 = undefined;
        const wrong_ad = "modified";
        const result = AsconAead128.decrypt(&decrypted, &ciphertext, tag, wrong_ad, nonce, key);
        try testing.expectError(error.AuthenticationFailed, result);
    }
}

// 测试向量来自 NIST SP 800-232 / ascon-c 参考实现
test "Ascon-AEAD128 official test vectors" {

    // 测试向量 1:空 PT,空 AD
    {
        var key: [16]u8 = undefined;
        var nonce: [16]u8 = undefined;
        _ = std.fmt.hexToBytes(&key, "000102030405060708090A0B0C0D0E0F") catch unreachable;
        _ = std.fmt.hexToBytes(&nonce, "101112131415161718191A1B1C1D1E1F") catch unreachable;

        const plaintext = "";
        const ad = "";
        var ciphertext: [plaintext.len]u8 = undefined;
        var tag: [16]u8 = undefined;

        AsconAead128.encrypt(&ciphertext, &tag, plaintext, ad, nonce, key);

        var expected_tag: [16]u8 = undefined;
        _ = std.fmt.hexToBytes(&expected_tag, "4F9C278211BEC9316BF68F46EE8B2EC6") catch unreachable;
        try testing.expectEqualSlices(u8, &expected_tag, &tag);
    }

    // 测试向量 2:空 PT,AD = "30"
    {
        var key: [16]u8 = undefined;
        var nonce: [16]u8 = undefined;
        _ = std.fmt.hexToBytes(&key, "000102030405060708090A0B0C0D0E0F") catch unreachable;
        _ = std.fmt.hexToBytes(&nonce, "101112131415161718191A1B1C1D1E1F") catch unreachable;

        const plaintext = "";
        var ad: [1]u8 = undefined;
        _ = std.fmt.hexToBytes(&ad, "30") catch unreachable;
        var ciphertext: [plaintext.len]u8 = undefined;
        var tag: [16]u8 = undefined;

        AsconAead128.encrypt(&ciphertext, &tag, plaintext, &ad, nonce, key);

        var expected_tag: [16]u8 = undefined;
        _ = std.fmt.hexToBytes(&expected_tag, "CCCB674FE18A09A285D6AB11B35675C0") catch unreachable;
        try testing.expectEqualSlices(u8, &expected_tag, &tag);
    }

    // 测试向量 34:单字节明文 0x20
    {
        var key: [16]u8 = undefined;
        var nonce: [16]u8 = undefined;
        _ = std.fmt.hexToBytes(&key, "000102030405060708090A0B0C0D0E0F") catch unreachable;
        _ = std.fmt.hexToBytes(&nonce, "101112131415161718191A1B1C1D1E1F") catch unreachable;

        var plaintext: [1]u8 = undefined;
        _ = std.fmt.hexToBytes(&plaintext, "20") catch unreachable;
        const ad = "";
        var ciphertext: [1]u8 = undefined;
        var tag: [16]u8 = undefined;

        AsconAead128.encrypt(&ciphertext, &tag, &plaintext, ad, nonce, key);

        var expected_ct: [1]u8 = undefined;
        _ = std.fmt.hexToBytes(&expected_ct, "E8") catch unreachable;
        var expected_tag: [16]u8 = undefined;
        _ = std.fmt.hexToBytes(&expected_tag, "DD576ABA1CD3E6FC704DE02AEDB79588") catch unreachable;

        try testing.expectEqualSlices(u8, &expected_ct, &ciphertext);
        try testing.expectEqualSlices(u8, &expected_tag, &tag);

        // 验证解密
        var decrypted: [1]u8 = undefined;
        try AsconAead128.decrypt(&decrypted, &ciphertext, tag, ad, nonce, key);
        try testing.expectEqualSlices(u8, &plaintext, &decrypted);
    }

    // 含有 3 字节明文的测试向量
    {
        var key: [16]u8 = undefined;
        var nonce: [16]u8 = undefined;
        _ = std.fmt.hexToBytes(&key, "000102030405060708090A0B0C0D0E0F") catch unreachable;
        _ = std.fmt.hexToBytes(&nonce, "101112131415161718191A1B1C1D1E1F") catch unreachable;

        var plaintext: [3]u8 = undefined;
        _ = std.fmt.hexToBytes(&plaintext, "202122") catch unreachable;
        const ad = "";
        var ciphertext: [3]u8 = undefined;
        var tag: [16]u8 = undefined;

        AsconAead128.encrypt(&ciphertext, &tag, &plaintext, ad, nonce, key);

        var expected_ct: [3]u8 = undefined;
        _ = std.fmt.hexToBytes(&expected_ct, "E8C3DE") catch unreachable;
        var expected_tag: [16]u8 = undefined;
        _ = std.fmt.hexToBytes(&expected_tag, "AF8E12816B8EDF39AD1571A9492B7CA2") catch unreachable;

        try testing.expectEqualSlices(u8, &expected_ct, &ciphertext);
        try testing.expectEqualSlices(u8, &expected_tag, &tag);

        // 验证解密
        var decrypted: [3]u8 = undefined;
        try AsconAead128.decrypt(&decrypted, &ciphertext, tag, ad, nonce, key);
        try testing.expectEqualSlices(u8, &plaintext, &decrypted);
    }
}

test "Ascon-Hash256 official test vectors" {

    // 测试向量 1:空消息
    {
        const message = "";
        var hash: [32]u8 = undefined;
        AsconHash256.hash(message, &hash, .{});

        var expected: [32]u8 = undefined;
        _ = std.fmt.hexToBytes(&expected, "0B3BE5850F2F6B98CAF29F8FDEA89B64A1FA70AA249B8F839BD53BAA304D92B2") catch unreachable;
        try testing.expectEqualSlices(u8, &expected, &hash);
    }

    // 测试向量 2:单字节 0x00
    {
        const message = [_]u8{0x00};
        var hash: [32]u8 = undefined;
        AsconHash256.hash(&message, &hash, .{});

        var expected: [32]u8 = undefined;
        _ = std.fmt.hexToBytes(&expected, "0728621035AF3ED2BCA03BF6FDE900F9456F5330E4B5EE23E7F6A1E70291BC80") catch unreachable;
        try testing.expectEqualSlices(u8, &expected, &hash);
    }

    // 测试向量 3:0x00、0x01
    {
        const message = [_]u8{ 0x00, 0x01 };
        var hash: [32]u8 = undefined;
        AsconHash256.hash(&message, &hash, .{});

        var expected: [32]u8 = undefined;
        _ = std.fmt.hexToBytes(&expected, "6115E7C9C4081C2797FC8FE1BC57A836AFA1C5381E556DD583860CA2DFB48DD2") catch unreachable;
        try testing.expectEqualSlices(u8, &expected, &hash);
    }

    // 测试向量 4:0x00、0x01、0x02
    {
        const message = [_]u8{ 0x00, 0x01, 0x02 };
        var hash: [32]u8 = undefined;
        AsconHash256.hash(&message, &hash, .{});

        var expected: [32]u8 = undefined;
        _ = std.fmt.hexToBytes(&expected, "265AB89A609F5A05DCA57E83FBBA700F9A2D2C4211BA4CC9F0A1A369E17B915C") catch unreachable;
        try testing.expectEqualSlices(u8, &expected, &hash);
    }

    // 测试向量 5:0x00..0x03
    {
        const message = [_]u8{ 0x00, 0x01, 0x02, 0x03 };
        var hash: [32]u8 = undefined;
        AsconHash256.hash(&message, &hash, .{});

        var expected: [32]u8 = undefined;
        _ = std.fmt.hexToBytes(&expected, "D7E4C7ED9B8A325CD08B9EF259F8877054ECD8304FE1B2D7FD847137DF6727EE") catch unreachable;
        try testing.expectEqualSlices(u8, &expected, &hash);
    }
}

test "Ascon-XOF128 official test vectors" {

    // 测试向量 1:空消息,64 字节输出
    {
        var xof = AsconXof128.init(.{});
        xof.update("");

        var output: [64]u8 = undefined;
        xof.squeeze(&output);

        var expected: [64]u8 = undefined;
        _ = std.fmt.hexToBytes(&expected, "473D5E6164F58B39DFD84AACDB8AE42EC2D91FED33388EE0D960D9B3993295C6AD77855A5D3B13FE6AD9E6098988373AF7D0956D05A8F1665D2C67D1A3AD10FF") catch unreachable;
        try testing.expectEqualSlices(u8, &expected, &output);
    }

    // 测试向量 2:单字节 0x00,64 字节输出。
    {
        var xof = AsconXof128.init(.{});
        const msg = [_]u8{0x00};
        xof.update(&msg);

        var output: [64]u8 = undefined;
        xof.squeeze(&output);

        var expected: [64]u8 = undefined;
        _ = std.fmt.hexToBytes(&expected, "51430E0438ECDF642B393630D977625F5F337656BA58AB1E960784AC32A16E0D446405551F5469384F8EA283CF12E64FA72C426BFEBAEA3AA1529E2C4AB23A2F") catch unreachable;
        try testing.expectEqualSlices(u8, &expected, &output);
    }

    // 测试向量 3:0x00、0x01,64 字节输出
    {
        var xof = AsconXof128.init(.{});
        const msg = [_]u8{ 0x00, 0x01 };
        xof.update(&msg);

        var output: [64]u8 = undefined;
        xof.squeeze(&output);

        var expected: [64]u8 = undefined;
        _ = std.fmt.hexToBytes(&expected, "A05383077AF971D3830BD37E7B981497A773D441DB077C6494CC73125953846EB6427FBA4CD308FF90A11385D51101341BF5379249217BFDACE9CCA1148CC966") catch unreachable;
        try testing.expectEqualSlices(u8, &expected, &output);
    }
}

test "Ascon-XOF128/CXOF128 streaming chunking invariance" {
    const msg = "Hello, World!";

    // XOF128:一次调用与拆分调用的结果必须一致
    var out1: [32]u8 = undefined;
    var out2: [32]u8 = undefined;
    var xof1 = AsconXof128.init(.{});
    xof1.update(msg);
    xof1.squeeze(&out1);
    var xof2 = AsconXof128.init(.{});
    xof2.update("Hello, ");
    xof2.update("World!");
    xof2.squeeze(&out2);
    try testing.expectEqualSlices(u8, &out1, &out2);

    // CXOF128:一次性处理与分次处理必须匹配
    var cout1: [32]u8 = undefined;
    var cout2: [32]u8 = undefined;
    var cxof1 = AsconCxof128.init(.{ .custom = "cust" });
    cxof1.update(msg);
    cxof1.squeeze(&cout1);
    var cxof2 = AsconCxof128.init(.{ .custom = "cust" });
    cxof2.update("Hello, ");
    cxof2.update("World!");
    cxof2.squeeze(&cout2);
    try testing.expectEqualSlices(u8, &cout1, &cout2);
}

test "Ascon-CXOF128 official test vectors" {

    // 测试向量 1:空消息、空自定义信息、64 字节输出
    {
        var xof = AsconCxof128.init(.{});
        xof.update("");

        var output: [64]u8 = undefined;
        xof.squeeze(&output);

        var expected: [64]u8 = undefined;
        _ = std.fmt.hexToBytes(&expected, "4F50159EF70BB3DAD8807E034EAEBD44C4FA2CBBC8CF1F05511AB66CDCC529905CA12083FC186AD899B270B1473DC5F7EC88D1052082DCDFE69FB75D269E7B74") catch unreachable;
        try testing.expectEqualSlices(u8, &expected, &output);
    }

    // 测试向量 2:空消息,customization = 0x10,64 字节输出。
    {
        const custom = [_]u8{0x10};
        var xof = AsconCxof128.init(.{ .custom = &custom });
        xof.update("");

        var output: [64]u8 = undefined;
        xof.squeeze(&output);

        var expected: [64]u8 = undefined;
        _ = std.fmt.hexToBytes(&expected, "0C93A483E7D574D49FE52CCE03EE646117977D57A8AA57704AB4DAF44B501430FF6AC11A5D1FD6F2154B5C65728268270C8BB578508487B8965718ADA6272FD6") catch unreachable;
        try testing.expectEqualSlices(u8, &expected, &output);
    }

    // 测试向量 3:空消息,customization = 0x10, 0x11,输出 64 字节
    {
        const custom = [_]u8{ 0x10, 0x11 };
        var xof = AsconCxof128.init(.{ .custom = &custom });
        xof.update("");

        var output: [64]u8 = undefined;
        xof.squeeze(&output);

        var expected: [64]u8 = undefined;
        _ = std.fmt.hexToBytes(&expected, "D1106C7622E79FE955BD9D79E03B918E770FE0E0CDDDE28BEB924B02C5FC936B33ACCA299C89ECA5D71886CBBFA4D54A21C55FDE2B679F5E2488063A1719DC32") catch unreachable;
        try testing.expectEqualSlices(u8, &expected, &output);
    }
}