window.crypto.subtle.encrypt returns 未定义

window.crypto.subtle.encrypt returns undefined

我正在尝试使用 Web Crypto API 加密文本。以下是我的代码:

const generatedIv = generateIv();
let generatedKey;
generateKey()
  .then(key => {
    generatedKey = key;
    encryptData(encodeText(JSON.stringify(data)), generatedKey, generatedIv);
  }).then(encrypted => {
    console.log(encrypted) // Always returns undefined?
  }).catch(
    err => console.error(err)
  );

function encodeText(data) {
  if ('TextEncoder' in window) {
    return new TextEncoder('utf-8').encode(data);
  }
  return undefined;
}

function generateIv() {
  return window.crypto.getRandomValues(new Uint8Array(12));
}

function generateKey() {
  return window.crypto.subtle.generateKey({
    name: 'AES-GCM',
    length: 256
  }, true, [
    'encrypt',
    'decrypt'
  ]);
}

function encryptData(data, key, iv) {
  return window.crypto.subtle.encrypt({
    name: 'AES-GCM',
    iv: iv,
    tagLength: 128
  }, key, data);
}

出于某种原因,console.log 语句总是打印出 undefined。我尝试在网上寻找可能的解决方案,但我找不到任何解决方案。

我这里有什么地方做错了吗?提前致谢! :)

const generatedIv = generateIv();
let generatedKey;
generateKey()
  .then(key => {
    generatedKey = key;
    // you need to return something if you want the next .then to get anything
    return encryptData(encodeText("Hello World"), generatedKey, generatedIv);
  }).then(encrypted => {
    console.log("encrypted is an ArrayBuffer:", encrypted instanceof ArrayBuffer)
  }).catch(
    err => console.error(err)
  );

function encodeText(data) {
  if ('TextEncoder' in window) {
    return new TextEncoder('utf-8').encode(data);
  }
  return undefined;
}

function generateIv() {
  return window.crypto.getRandomValues(new Uint8Array(12));
}

function generateKey() {
  return window.crypto.subtle.generateKey({
    name: 'AES-GCM',
    length: 256
  }, true, [
    'encrypt',
    'decrypt'
  ]);
}

function encryptData(data, key, iv) {
  return window.crypto.subtle.encrypt({
    name: 'AES-GCM',
    iv: iv,
    tagLength: 128
  }, key, data);
}

运行 以上,你应该看到 encrypted is an ArrayBuffer: true - 因为这就是你所期望的加密结果,一个 ArrayBuffer ... 所以,huzzah - 一个简单的 return所需要的就是 return 一个值(在本例中由 window.crypto.subtle.encrypt 编辑的 promise return)到下一个 .then ... 也称为 promise chaining

祝你有美好的一天