菜单
开源

encrypt

注意

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

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

encrypt() 方法用于加密一些数据。

用法

encrypt(algorithm, key, data)

参数

名称类型描述
algorithmAesCbcParamsAesCtrParamsAesGcmParams 对象定义要使用的算法以及任何额外的参数。
keyCryptoKey用于加密的 key
dataArrayBufferTypedArrayDataView要加密的数据(也称为“明文”)。

支持的算法

AES-CBCAES-CTRAES-GCMRSA-OAEP
AesCbcParamsAesCtrParamsAesGcmParamsRsaOaepParams

返回值

一个 Promise,解析为一个包含加密数据的新 ArrayBuffer

抛出

类型描述
InvalidAccessError当请求的操作与提供的 key 无效时抛出。例如,使用了无效的加密算法,或者提供了与所选算法不匹配的 key。
OperationError当操作因特定于操作的原因失败时抛出。例如,算法大小无效,或者在解密密文过程中发生错误。

示例

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