I'm having trouble getting a message encrypted with cryptojs decrypted with php.
On the javascript side, the code to create the encryption is:
var keySize = 256;
var ivSize = 128;
var saltSize = 256;
var iterations = 100;
var message = "This is my test";
var password = "thepassword";
function encrypt(msg, pass) {
// Generate salt, key and iv
var salt = CryptoJS.lib.WordArray.random(saltSize / 8);
var key = CryptoJS.PBKDF2(pass, salt, {
keySize: 256 / 32,
iterations: iterations
});
console.log('Message key: ' + key);
var iv = CryptoJS.lib.WordArray.random(ivSize / 8);
// encrypt message
var encrypted = CryptoJS.AES.encrypt(msg, key, {
iv: iv,
padding: CryptoJS.pad.Pkcs7,
mode: CryptoJS.mode.CBC
});
// convert encrypted message to hex
var encryptedHex = base64ToHex(encrypted.toString());
// Prepare result to transmit
var base64result = hexToBase64(salt + iv + encryptedHex);
return base64result;
}
This creates a string like:
g281MRrrEdiysHSAolnMmy3Au3yYkb2TK1t7iF4dv8X2k9Fod1DkOt/LF8eLgX8OxRvkSOMqtrcGEMaCL7A8YVBcugcirNg44HcWGWt+hfA=
When I bring that into php, I can correctly pull back the pieces sent (salt, iv, message), but can't decode the message.
$text_key = 'thepassword';
$cipher = "aes-256-cbc";
$received_message = $_REQUEST['message'];
// Decode message and pull out pieces:
$decoded = base64_decode($received_message);
$hex_version = bin2hex($decoded);
// Pull out salt, iv and encrypted message
$salt = substr($hex_version, 0,64);
$iv = substr($hex_version, 64,32);
$encrypted_string = substr($hex_version, 96);
// Message key
$generated_key = bin2hex(openssl_pbkdf2($text_key, $salt, 32, 100, 'sha256'));
// Decode Message
$result = openssl_decrypt($text_encoded, $cipher, $generated_key, $options=0, hex2bin($iv));
If I replace $generated_key with the key displayed in the javascript console, however, the message decrypts successfully.
What am I doing incorrectly to generate the key in php?