简体   繁体   中英

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

Backend developers have encrypted a value in nodejs using crypto module. The code is shown below:

   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;
   }

I need to decrypt this value in the front end (Angular). So I tried decrypting like below:

    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);
    }

using hardcoded value. But Im getting Error: Malformed UTF-8 data error. Can anybody please tell me how to decrypt this in angular side?

This is a tricky enough one.. the crypto.createCipher function creates a key and IV from the password you provide (See the createCipher documentation for details).

This is implemented using the OpenSSL function EVP_BytesToKey .

A JavaScript implementation is available here: openssl-file .. we'll use this to get a key and IV from the password.

So there are two steps here:

  1. Get a key and IV from your password.
  2. Use these with Crypto.js to decode your encoded string.

Step 1: Get key and IV (Run 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'));

Step 2: Decrypt string:

 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>

Note that if you change the password you need to generate a new key and iv using EVP_BytesToKey.

I should note that createCipher is now deprecated, so use with caution. The same applies to EVP_BytesToKey.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM