【问题标题】:How to decrypt a value in frontend which is encrypted in the backend (nodejs)?如何解密在后端(nodejs)中加密的前端值?
【发布时间】:2019-10-29 23:36:10
【问题描述】:

后端开发人员使用加密模块加密了 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 数据错误。谁能告诉我如何在角度方面解密这个?

【问题讨论】:

    标签: node.js angular encryption angular6


    【解决方案1】:

    这是一个非常棘手的问题。crypto.createCipher 函数根据您提供的密码创建一个密钥和 IV(有关详细信息,请参阅createCipher 文档)。

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

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

    所以这里有两个步骤:

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

    第 1 步:获取密钥和 IV(在 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'));
    

    第 2 步:解密字符串:

    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。

    【讨论】:

    • 不客气,这是一个非常棘手的问题,很高兴能为您提供帮助。
    猜你喜欢
    • 2013-02-09
    • 1970-01-01
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    相关资源
    最近更新 更多