Search code examples
reactjsutf-8cryptojs

Cryptojs decryption not working for encrypted url param


When I am running the below code block it's working fine.

var request = "testing decryption";
var encryptedRequest = CryptoJS.AES.encrypt(request, 'somekey');
console.log(encryptedRequest)  
var decryptedRequest = CryptoJS.AES.decrypt(encryptedRequest, 'somekey');
var decryptedMessage = decryptedRequest.toString(CryptoJS.enc.Utf8)
console.log('Decrypted Request: ' + decryptedMessage); //Decrypted Request: testing decryption

But this one is not working. Where I am passing the encoded value in url. I also tried passing the encrypted value hard coded. Still getting the same.

var user_details=this.props.match.params.userdetails
var encryptedRequest = `${user_details}`;
console.log(encryptedRequest) 
var decryptedRequest = CryptoJS.AES.decrypt(encryptedRequest, 'somekey');
var decryptedMessage = decryptedRequest.toString(CryptoJS.enc.Utf8)
console.log('Decrypted Request: ' + decryptedMessage); //Decrypted Request: 

Where am I going wrong?


Solution

  • I had a similar scenario, where I was parsing it wrong way. you can try the below code. You may need to change the mode and padding configuration in your case.

        var key = CryptoJS.enc.Hex.parse(secret_key);
        var user_details = this.props.match.params.userdetails
        var encryptedRequest = `${user_details}`;
        var cipher = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Hex.parse(encryptedRequest));
        var decrypt = CryptoJS.AES.decrypt(cipher, key, {
            mode: CryptoJS.mode.ECB,            //check the mode that was used at the time of encryption
            padding: CryptoJS.pad.Pkcs7         //check the padding that was used at the time of encryption 
        });
    
        var decrypted = decrypt.toString(CryptoJS.enc.Utf8);
    

    Where mode can be either of the following. CryptoJS supports the following modes: CBC (the default), CFB, CTR, OFB, ECB.

    And for the padding scheme, CryptoJS supports the following: Pkcs7 (the default), Iso97971, AnsiX923, Iso10126, ZeroPadding, NoPadding

    For more details you can check https://cryptojs.gitbook.io/docs/