菜单
开源

encrypt

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

使用

encrypt(algorithm, key, data)

参数

名称类型描述
algorithmAesCbcParams, AesCtrParams, 或 AesGcmParams 对象定义要使用的算法及任何额外参数。
keyCryptoKey用于加密的密钥
dataArrayBuffer, TypedArray, 或 DataView要加密的数据(也称为“明文”)。

支持的算法

AES-CBCAES-CTRAES-GCMRSA-OAEP
AesCbcParamsAesCtrParamsAesGcmParamsRsaOaepParams

返回值

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

抛出

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

示例

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