使用 CryptoJS 生成 AES-CBC-192 的正确方法是什么?

What is the correct way to generate AES-CBC-192 with CryptoJS?

我得到了以下代码,想知道这是否是使用 CryptoJS 生成 AES-CBC-192 密码的正确且安全的方法:

原题码:

let encrypt = (text,key) => {


    let salt = "M@Tr05K@";

    let iv = CryptoJS.lib.WordArray.random(16);

    let key_to_bits = CryptoJS.PBKDF2(key,salt,{keySize: 192/8, iterations:30000});

    return CryptoJS.AES.encrypt(text,key,{iv:iv}).toString();


}

encrypt("Lorem ipsum...","¿MinhaSenha?>Segur@?");

建议更改的代码:

let encrypt = (text, key) => {
  let salt = CryptoJS.lib.WordArray.random(16);
  let iv = CryptoJS.lib.WordArray.random(16);
  let key_to_bits = CryptoJS.PBKDF2(key, salt, {
    keySize: 192 / 32,
    iterations: 30000
  });

  return {result : CryptoJS.AES.encrypt(text, key_to_bits, {
    iv: iv
  }).toString(),
  salt:CryptoJS.enc.Hex.stringify(salt),
  iv:CryptoJS.enc.Hex.stringify(iv)
};
}

encrypt("Lorem ipsum...", "¿MinhaSenha?>Segur@?");

感谢收听:)

这里是我刚刚使用 PBKdf2 从密码完成 AES-CBC-256,这是使用 Web 加密 api https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API

不是你要找的东西,但它可能有助于指导,从下面删除 importKey 并继续阅读 https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/generateKey

function generateKey(passwd, iterations) {

  var encoder = new TextEncoder('utf-8');
  var passphraseKey = encoder.encode(passwd);
  var saltBuffer = encoder.encode("carthage");

  crypto.subtle.importKey(
    'raw',
    passphraseKey,
    {name: 'PBKDF2'},
    false,
    ['deriveBits', 'deriveKey']
  ).then(function(key) {
//    console.log(key);
    return window.crypto.subtle.deriveKey(
    { "name": 'PBKDF2',
      "salt": saltBuffer,
      "iterations": iterations,
      "hash": 'SHA-256'
    },
    key,
    { "name": 'AES-CBC',
      "length": 256
    },
    true,
    [ "encrypt", "decrypt" ]
  )
  }).then(function (webKey) {
//    console.log(webKey);
    return crypto.subtle.exportKey("raw", webKey);
  }).then(function (buffer) {
//    console.log(buffer);
//    console.log(saltBuffer);
    console.log("Private Key = " + buf2hex(buffer));
    console.log("Salt = " + bytesToHexString(saltBuffer));
  });


}


function buf2hex(buffer) { // buffer is an ArrayBuffer
  return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
}

function bytesToHexString(byteArray) {
  return Array.prototype.map.call(byteArray, function(byte) {
    return ('0' + (byte & 0xFF).toString(16)).slice(-2);
  }).join('');
}