user12708695
user12708695

Reputation: 47

AES-128-CBC decpription return wrong value

I tried to create an AES-128-CBC decryption over javascript

Here I did so far:

    <script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/components/enc-base64-min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.js"></script>
<script>
 var rawStr = "MyPassword";
      var secret = 'EL12ec@REteLe(0M';
      var wordArray = CryptoJS.enc.Utf8.parse(rawStr);
      var base64 = CryptoJS.enc.Base64.stringify(wordArray);
      var encrypted = '' + CryptoJS.AES.encrypt(base64, secret);
      console.log('base64:', base64);
      console.log('encrypted:', encrypted);
</script>

But the value I got is: TXlQYXNzd29yZA==

The correct value is: S9bEDxeu/jr+8CdRkiUEog== based on this online encryption tools: https://www.devglan.com/online-tools/aes-encryption-decryption

Anyone can help me how to achieved this to get same result encryption same like devglan tools?

Thanks,

Upvotes: 2

Views: 445

Answers (1)

Topaco
Topaco

Reputation: 49141

To reproduce the result of the website, the following has to be considered:

  • The key must be passed to CryptoJS.AES.encrypt as WordArray. Otherwise it is interpreted as a passphrase, here.
  • The CBC mode (CryptoJS default, here) requires an IV, which must be passed to CryptoJS.AES.encrypt as WordArray (if no IV is specified on the website, a 0-vector is implicitly used).
  • The return value of CryptoJS.AES.encrypt is a CipherParams object, which encapsulates the ciphertext among other things, here.

var rawStr = "MyPassword";
var secret = CryptoJS.enc.Utf8.parse('EL12ec@REteLe(0M');
var iv = CryptoJS.enc.Utf8.parse('\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0');
var encrypted = CryptoJS.AES.encrypt(rawStr, secret, {iv: iv});
console.log('Output:',  CryptoJS.enc.Base64.stringify(encrypted.ciphertext)); // Output: S9bEDxeu/jr+8CdRkiUEog==
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9/crypto-js.min.js"></script>

Upvotes: 1

Related Questions