如何解密在后端(nodejs)中加密的前端值?

How to decrypt a value in frontend which is encrypted in the backend (nodejs)?

后端开发人员使用加密模块在 nodejs 中加密了一个值。代码如下:

   const _encrypt = async function(text){
     var cipher = crypto.createCipher('aes-256-cbc','123|a123123123123123@&12')
     var crypted = cipher.update(text,'utf8','hex')
     crypted += cipher.final('hex');
     console.log("in generic function....encrpted val", crypted)
     return crypted;
   }

我需要在前端解密这个值(Angular)。所以我尝试像下面这样解密:

    let bytes = CryptoJS.AES.decrypt("e0912c26238f29604f5998fa1fbc78f6",'123|a123123123123123@&12'); 
    if(bytes.toString()){
        let m = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
        console.log("data ",m);
    }

使用硬编码值。但我收到错误:格式错误的 UTF-8 数据错误。谁能告诉我如何在 angular 端解密这个?

这已经够棘手了。crypto.createCipher 函数根据您提供的密码创建密钥和 IV(有关详细信息,请参阅 createCipher 文档)。

这是使用 OpenSSL 函数 EVP_BytesToKey 实现的。

此处提供了 JavaScript 实现:openssl-file..我们将使用它从密码中获取密钥和 IV。

所以这里有两个步骤:

  1. 从您的密码中获取密钥和 IV。
  2. 将这些与 Crypto.js 一起使用来解码您的编码字符串。

第 1 步:获取密钥和 IV(运行 in Node.js)

const EVP_BytesToKey = require('openssl-file').EVP_BytesToKey;
const result = EVP_BytesToKey(
    '123|a123123123123123@&12',
    null,
    32,
    'MD5',
    16
);

console.log('key:', result.key.toString('hex'));
console.log('iv:', result.iv.toString('hex'));

第二步:解密字符串:

const encryptedValues = ['e0912c26238f29604f5998fa1fbc78f6', '0888e0558c3bce328cd7cda17e045769'];

// The results of putting the password '123|a123123123123123@&12' through EVP_BytesToKey
const key = '18bcd0b950de300fb873788958fde988fec9b478a936a3061575b16f79977d5b';
const IV = '2e11075e7b38fa20e192bc7089ccf32b';

for(let encrypted of encryptedValues) {
    const decrypted = CryptoJS.AES.decrypt({ ciphertext: CryptoJS.enc.Hex.parse(encrypted) }, CryptoJS.enc.Hex.parse(key), { 
        iv: CryptoJS.enc.Hex.parse(IV), 
        mode: CryptoJS.mode.CBC
    });
     
    console.log('Ciphertext:', encrypted);
    console.log('Plain text:', decrypted.toString(CryptoJS.enc.Utf8));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js"></script>

请注意,如果您更改密码,则需要使用 EVP_BytesToKey 生成新密钥和 iv。

我应该注意到 createCipher 现在已被弃用,因此请谨慎使用。同样适用于 EVP_BytesToKey.