Search code examples
javascriptcryptojsecb

Encrypting With CryptoJS


I am trying to use the CryptoJS library to get the same value as I'm getting from an encryption tool, but I'm not able to get the same encrypted value.

Result using encryption tool:

enter image description here

Base64 Encoded Key: SisBCd6mVzPzZP7cpl/HvjqdkCpnujnJKUu8iosq/Yc=
Value to Encrypt: 55554444
Encrypted (ECB) Base64 Encoded Value: MLnK8JOyp+J4CoaqcWTAnW==

Here is my code where I'm trying to get that same result:

var data = '55554444'
var key = 'SisBCd6mVzPzZP7cpl/HvjqdkCpnujnJKUu8iosq/Yc='

// encrypt with key
var encrypted_ecb = CryptoJS.AES.encrypt(data, key, {mode: CryptoJS.mode.ECB});

console.log('encrypted_ecb: ', encrypted_ecb.toString())

// to base64
var rawStr = encrypted_ecb;
var wordArray = CryptoJS.enc.Utf8.parse(rawStr);
var base64_ecb = CryptoJS.enc.Base64.stringify(wordArray);

console.log('encrypted_base64_ecb: ', base64_ecb);

// Console Result:
// encrypted_ecb: U2FsdGVkX196PQg/s6RPQr3V9GEjf/WP7qRXxVh5GEU=
// encrypted_base64_ecb: VTJGc2RHVmtYMTk2UFFnL3M2UlBRcjNWOUdFamYvV1A3cVJYeFZoNUdFVT0=

As you can see I am getting the result I get is far different than the result I'm getting with the tool. Can anyone point me in the right direction?

Thank you!


Solution

  • You'll need to parse the key as well. Change the following line

    var key = 'SisBCd6mVzPzZP7cpl/HvjqdkCpnujnJKUu8iosq/Yc='
    

    to

    var key = CryptoJS.enc.Base64.parse('SisBCd6mVzPzZP7cpl/HvjqdkCpnujnJKUu8iosq/Yc=');