菜单
开源

AesGcmParams

注意

实验性模块 k6/experimental/webcrypto 已毕业,其功能现已通过全局的 crypto 对象 提供。该 k6/experimental/webcrypto 已弃用,并将于近期移除。

要迁移您的脚本,请移除 k6/experimental/webcrypto 导入,转而使用 crypto 对象。

AesGcmParams 对象表示在使用 AES-GCM 算法时,应作为算法参数传递给 encryptdecrypt 操作的对象。

更多详细信息,请参阅 MDN Web Crypto API 上的 AES-GCM 文档

属性

属性类型描述
namestring应设置为 AES-GCM
ivArrayBuffer, TypedArrayDataView初始化向量。它必须是 12 字节长,不可预测且是加密安全的随机数。对于使用给定密钥进行的每次加密操作,它必须是唯一的。切勿对同一个密钥重复使用 iv。然而,它不需要保密,可以随密文一起传输。
additionalData (可选)ArrayBuffer, TypedArrayDataView应被认证但不加密的附加数据。它必须包含在认证标签的计算中,但本身不加密。
tagLength (可选)number认证标签的长度(以位为单位)。应设置此值,默认值为 96。

示例

JavaScript
import { crypto } from 'k6/experimental/webcrypto';

export default async function () {
  const plaintext = stringToArrayBuffer('Hello, World!');

  /**
   * Generate a symmetric key using the AES-CBC algorithm.
   */
  const key = await crypto.subtle.generateKey(
    {
      name: 'AES-GCM',
      length: 256,
    },
    true,
    ['encrypt', 'decrypt']
  );

  /**
   * Encrypt the plaintext using the AES-CBC key with
   * have generated.
   */
  const ciphertext = await crypto.subtle.encrypt(
    {
      name: 'AES-GCM',
      iv: crypto.getRandomValues(new Uint8Array(12)),
    },
    key,
    plaintext
  );
}

function stringToArrayBuffer(str) {
  const buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
  const bufView = new Uint16Array(buf);
  for (let i = 0, strLen = str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}