菜单
开源 RSS

crypto

通过此模块,您可以在 k6 脚本中使用 WebCrypto API。但请注意,此 API 尚未完全实现,某些算法和功能可能仍缺失。

Web Crypto API 是一个 JavaScript API,用于执行加密操作,例如加密、解密、数字签名生成和验证以及密钥生成和管理。它提供了一个访问加密功能的标准接口,有助于确保加密操作的正确性和安全性。

API

该模块是一个顶层 crypto 对象,具有以下属性和方法

接口/函数描述
getRandomValues用加密安全的随机值填充传入的 TypedArray
randomUUID返回一个随机生成的 36 字符长 v4 UUID。
subtleSubtleCrypto 接口提供对常见加密原语的访问,例如哈希、签名、加密或解密。

示例

JavaScript
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-CBC',
      length: 256,
    },
    true,
    ['encrypt', 'decrypt']
  );

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

  /**
   * Decrypt the ciphertext using the same key to verify
   * that the resulting plaintext is the same as the original.
   */
  const deciphered = await crypto.subtle.decrypt(
    {
      name: 'AES-CBC',
      iv: iv,
    },
    key,
    ciphertext
  );

  console.log(
    'deciphered text == original plaintext: ',
    arrayBufferToHex(deciphered) === arrayBufferToHex(plaintext)
  );
}

function arrayBufferToHex(buffer) {
  return [...new Uint8Array(buffer)].map((x) => x.toString(16).padStart(2, '0')).join('');
}

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;
}