I am having some trouble decrypting data using CryptoJS that was encrypted in PHP. Maybe somebody can advise me on where I am going wrong?
I am encrypting as follows:
- Get hashed password
- Take substring of (0,16) as the key
- Encrypt (MCRYPT_RIJNDAEL_128)
- Encode ciphertext as base64
When decrypting I do the same:
- Get hashed password
- Take substring of (0,16) as the key
- Base64 decode the ciphertext
- Decrypt
PHP:
public function encrypt($input, $key) {
$size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$input = $this->_pkcs5_pad($input, $size);
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $key, $iv);
$data = mcrypt_generic($td, $input);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
$data = base64_encode($data);
return $data;
}
JavaScript:
function decrypt(ciphertext, hashedPsw) {
var key = hashedPsw.substring(0, 16);
var key = CryptoJS.enc.Hex.parse(key);
var options = { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7, keySize:128 / 32 };
ciphertext = CryptoJS.enc.Base64.parse(ciphertext);
var decrypted = CryptoJS.AES.decrypt(ciphertext, key);
return decrypted;
}
I just discovered the answer in a previous thread: Turns out that the problem was the key encoding.