AES-256-CBC Mcrypt-PHP decryption and encryption Crypto-JS

I am trying to encrypt in Javascript using CryptoJS and decrypt in PHP. JS Code:

var salt = CryptoJS.lib.WordArray.random(128/8); var key256Bits500Iterations = CryptoJS.PBKDF2("Secret Passphrase", salt, { keySize: 256/32, iterations: 500 }); var iv = CryptoJS.enc.Hex.parse('101112131415161718191a1b1c1d1e1f'); // just chosen for an example, usually random as well encrypted = CryptoJS.AES.encrypt("Message", key512Bits1000Iterations, { iv: iv }); var data_base64 = crypted.ciphertext.toString(CryptoJS.enc.Base64); var iv_base64 = crypted.iv.toString(CryptoJS.enc.Base64); var key_base64 = crypted.key.toString(CryptoJS.enc.Base64); 

And PHP looks like this:

 $encrypted = base64_decode($data_base64); $iv = base64_decode($iv_base64); $key = base64_decode($key_base64); $plaintext = mcrypt_decrypt( MCRYPT_RIJNDAEL_128, $key, $encrypted, MCRYPT_MODE_CBC, $iv); echo ($plaintext); 

This does not return the correct answer.

I'm not sure where everything goes bad! I need to make my own IV, but if I just say:

 CryptoJS.AES.Encrypt("Message", "Secret Passphrase"); var data_base64 = crypted.ciphertext.toString(CryptoJS.enc.Base64); var iv_base64 = crypted.iv.toString(CryptoJS.enc.Base64); var key_base64 = crypted.key.toString(CryptoJS.enc.Base64); 

It works successfully in PHP code - only key_base64 is not something that can be changed, it should be what the user remembers ... And then he gives me salt to get the key from the passphrase and IDK, how it was possible get using cryptojs

+7
javascript php encryption aes cryptojs
source share
1 answer

Your code will work if you just fix some typos there

Js

  <script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script> <script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/pbkdf2.js"></script> <script> var salt = CryptoJS.lib.WordArray.random(128/8); var key256Bits500Iterations = CryptoJS.PBKDF2("Secret Passphrase", salt, { keySize: 256/32, iterations: 500 }); var iv = CryptoJS.enc.Hex.parse('101112131415161718191a1b1c1d1e1f'); // just chosen for an example, usually random as well var encrypted = CryptoJS.AES.encrypt("Message", key256Bits500Iterations, { iv: iv }); var data_base64 = encrypted.ciphertext.toString(CryptoJS.enc.Base64); var iv_base64 = encrypted.iv.toString(CryptoJS.enc.Base64); var key_base64 = encrypted.key.toString(CryptoJS.enc.Base64); </script> 

Php

  <?php $encrypted = base64_decode("data_base64"); // data_base64 from JS $iv = base64_decode("iv_base64"); // iv_base64 from JS $key = base64_decode("key_base64"); // key_base64 from JS $plaintext = rtrim( mcrypt_decrypt( MCRYPT_RIJNDAEL_128, $key, $encrypted, MCRYPT_MODE_CBC, $iv ), "\t\0 " ); 
+15
source share

All Articles