window.crypto.subtle.encrypt返回undefined

时间:2018-03-28 11:09:07

标签: javascript cryptography cryptoapi

我正在尝试使用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。我曾尝试在网上寻找可能的解决方案,但我找不到任何解决方案。

我在这里做错了吗?提前致谢! :)

1 个答案:

答案 0 :(得分:0)

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,返回一个值(在这种情况下由window.crypto.subtle.encrypt返回的承诺)到下一个.then ...也称为promise chaining

度过美好的一天