Skip to content
Advertisement

CryptoJS decrypted value differ from the original value

I am trying to encrypt some strings and decrypt it with the use of CryptoJS (AES-256).

My javascript code:

function hexStringToByte(str) {
    if (!str) {
        return new Uint8Array();
    }
    
    var a = [];
    for (var i = 0, len = str.length; i < len; i+=2) {
        a.push(parseInt(str.substr(i,2),16));
    }
    
    return new Uint8Array(a);
}

function aesEcryption(input, key, type){
    var xx = input;
    console.log("Print Value");
    console.log(xx);
    console.log(key);
    var key  = CryptoJS.enc.Hex.parse(key);
    var iv   = CryptoJS.enc.Hex.parse('00000000000000000000000000000000');
    var encrypted = CryptoJS.AES.encrypt(xx, key, {iv: iv, padding: CryptoJS.pad.NoPadding});
    console.log("Encrypted");
    console.log(CryptoJS.enc.Base64.stringify(encrypted.ciphertext))
    console.log(encrypted.toString());
    return encrypted.toString();
}


function aesDecryption(encryptedString, key, type){
    console.log("testttt");
    console.log(key);
    console.log(encryptedString);
    var key  = CryptoJS.enc.Hex.parse(key);
    var iv   = CryptoJS.enc.Hex.parse('00000000000000000000000000000000');
    var decrypted = CryptoJS.AES.decrypt(encryptedString, key,{iv:iv, padding: CryptoJS.pad.NoPadding});
    decrypted = decrypted.toString();
    console.log("decrpyted");
    // console.log(typeof decrypted);
    // console.log(decrypted);
    return decrypted;
}

My setup:
fefe3124bdc21e8a1c1b3fdfb84c79950b394b8f86fd49dddb616037b1bc2474 (key)

a (Input)

Qw== (Encrypted string)

d5 (decrypted value)

May I know which part of my code logic is wrong ?

Advertisement

Answer

Alright, I have figured out why the value would be different. Just need to remove the padding option, the decrypted value will be same as the original.

var encrypted = CryptoJS.AES.encrypt(xx, key, {iv: iv});

var decrypted = CryptoJS.AES.decrypt(encryptedString, key,{iv:iv});

I am just adding this answer, incase someone had the same issue as me.

Cheers!

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement