Chaudhry Talha
Chaudhry Talha

Reputation: 7987

React Native CryptoJS giving empty value for AES-256-CBC decryption

I'm using this https://github.com/imchintan/react-native-crypto-js package for React Native CryptoJS and I used this online tool https://www.javainuse.com/aesgenerator to generate this example data:

    const encryptedData = {
        cipher: "OuCmv1nXCzfy+529oeJU8g==",
        iv: "1234123412341234",
        key: "56785678567856785678567856785678"
    }

While encrypting the Mode selected is CBC, the Key Size is 256 bits, the output format is base64 in react native this is how I'm decrypting it:

    let bytes = CryptoJS.AES.decrypt(encryptedData.cipher, encryptedData.key);
    let originalText = bytes.toString(CryptoJS.enc.Utf8);

    console.log("Text is: " + originalText);

But all I'm getting is Text is: .

Upvotes: 0

Views: 6158

Answers (1)

dave_thompson_085
dave_thompson_085

Reputation: 38771

When you provide a CryptoJS Cipher a 'key' that is actually a string, it treats it as a passphrase and uses password-based key derivation compatible with OpenSSL enc as specified in the documentation. You need to convert the key and iv to WordArrays much as shown just above that, plus I can't find how to make the 'configurable' parsing work so I also parse explicitly as shown just below.

const CryptoJS = require('crypto-js');
var key = CryptoJS.enc.Latin1.parse("56785678567856785678567856785678")
var iv = CryptoJS.enc.Latin1.parse("1234123412341234")
var ctx = CryptoJS.enc.Base64.parse("OuCmv1nXCzfy+529oeJU8g==")
var enc = CryptoJS.lib.CipherParams.create({ciphertext:ctx})
console.log( CryptoJS.AES.decrypt (enc,key,{iv:iv}) .toString(CryptoJS.enc.Utf8) )
->
Talha

Technically the result of decrypt, like parse, is a WordArray, so calling it bytes is somewhat misleading and confusing.

Upvotes: 3

Related Questions