I encrypt and decrypt data using PHP like this:
<?php
function encrypt($data, $secret){
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
return base64_encode($iv.openssl_encrypt($data, 'aes-256-cbc', $secret, 0, $iv));
}
function decrypt($encryptedData, $secret){
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$data = base64_decode($encryptedData);
$iv = substr($data, 0, $iv_size);
return openssl_decrypt(substr($data, $iv_size), 'aes-256-cbc', $secret, 0, $iv);
}
?>
I am now wanting to be able to encrypt my data locally (identically to the PHP method) using Crypto-JS. I have done the same as above to get the key and iv:
var key = '<?php echo $secret;?>';
var iv = '<?php echo base64_encode(mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND));?>';
Now when using Crypto-JS I have tried to encrypt using:
var encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(text), CryptoJS.enc.Hex.parse(key), { iv: CryptoJS.enc.Hex.parse(iv) });
But I also need to store the IV like I do with PHP So I have added:
var withIV = iv+encrypted;
but that is not encoded. So I have added:
CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(withIV));
But this is not the same encoding as the PHP above for some reason?