菜单
开源 RSS

SubtleCrypto

注意

实验性模块 k6/experimental/webcrypto 已经升级,其功能现在可通过 crypto 对象全局使用。k6/experimental/webcrypto 已被弃用,并将在不久的将来移除。

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

SubtleCrypto 接口提供了一组低级加密原语,例如加密、解密、数字签名生成和验证,以及密钥生成和管理。它对于在 k6 脚本中使用安全高效的加密操作非常有用。

方法

方法描述
加密使用指定的算法和密钥加密给定的明文数据。
解密使用指定的算法和密钥解密给定的密文数据。
签名使用指定的算法和密钥对给定数据进行签名。
验证使用指定的算法和密钥验证给定数据的签名。
摘要使用指定的算法计算给定数据的摘要(哈希)。
生成密钥为指定的算法生成新的加密密钥。
导入密钥将原始密钥材料导入 Web Crypto API,生成一个新的密钥对象以用于指定的算法。
导出密钥导出给定密钥对象的原始密钥材料。
派生比特使用提供的输入派生比特。

示例

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