You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Web Crypto API中获取AES-GCM加密算法的认证标签?

Web Crypto API获取AES-GCM认证标签的方法

Web Crypto API完全可以实现获取AES-GCM的认证标签,只是它的实现逻辑和Node.js不同:Node.js通过单独方法返回认证标签,而Web Crypto会把认证标签直接拼接在密文的末尾一起返回。

具体实现步骤

  • 调用SubtleCrypto.encrypt()执行AES-GCM加密,得到的结果是包含密文和认证标签的ArrayBuffer。
  • AES-GCM默认使用128位(16字节)的认证标签,直接从加密结果的末尾截取16字节即可得到标签;如果加密时指定了非默认的标签长度(如96位/12字节),则截取对应长度的字节。

示例代码

async function encryptAndExtractAuthTag() {
  // 生成AES-GCM密钥
  const key = await window.crypto.subtle.generateKey(
    { name: "AES-GCM", length: 256 },
    true,
    ["encrypt", "decrypt"]
  );

  // 生成12字节的初始向量(IV,AES-GCM推荐长度)
  const iv = window.crypto.getRandomValues(new Uint8Array(12));

  // 待加密的明文数据
  const plaintext = new TextEncoder().encode("需要加密的内容");

  // 执行加密,得到密文+认证标签的组合数据
  const encryptedData = await window.crypto.subtle.encrypt(
    { name: "AES-GCM", iv: iv },
    key,
    plaintext
  );

  // 截取认证标签(默认16字节)
  const tagLength = 16;
  const ciphertext = encryptedData.slice(0, encryptedData.byteLength - tagLength);
  const authTag = encryptedData.slice(encryptedData.byteLength - tagLength);

  // 转换为Uint8Array方便查看和处理
  console.log("密文:", new Uint8Array(ciphertext));
  console.log("认证标签:", new Uint8Array(authTag));
}

// 执行函数
encryptAndExtractAuthTag();

自定义标签长度的情况

如果需要使用非默认长度的认证标签,只需在加密配置中添加tagLength字段(支持96、104、112、120、128位),示例如下:

// 指定96位(12字节)的标签长度
const encryptedData = await window.crypto.subtle.encrypt(
  { name: "AES-GCM", iv: iv, tagLength: 96 },
  key,
  plaintext
);

// 截取12字节作为标签
const tagLength = 12;
const authTag = encryptedData.slice(encryptedData.byteLength - tagLength);

内容的提问来源于stack exchange,提问作者ollog10

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 22:46:03