I am trying to encrypt some data in PHP using the Rijndael cipher in CBC mode with a 256bit key but for some reason I get the following error message:
mcrypt_encrypt() Module initialization failed
My code:
$hashKey = hash('sha256',$key);
$iv = hash('sha256',$hashKey);
// ------Cipher-------------key-------------Data-------------Mode---------IV--
$encryptedQuestion = base64_encode(mcrypt_encrypt('MCRYPT_RIJNDAEL_256', $hashKey , $_POST['question'], MCRYPT_MODE_CBC, $iv));
Can anyone see whats wrong with this?
There are a few issues with the code that I can spot:
Your $iv
should not be dependent on $hashKey
; rather, you should create it separately using mcrypt_create_iv()
.
Your $hashKey
should be binary rather than textual.
MCRYPT_RIJNDAEL_256
is a constant, it should not be passed as a string.
The following code is more verbose than yours, but it should give you an insight in the steps required to encrypt something:
$crypto = mcrypt_module_open(MCRYPT_RIJNDAEL_256, '', MCRYPT_MODE_CBC, '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($crypto), MCRYPT_DEV_URANDOM);
$hkey = hash('sha256', $key, true);
mcrypt_generic_init($handle, $hkey, $iv);
$enc_question = mcrypt_generic($handle, $_POST['question']);
mcrypt_generic_deinit($handle);
mcrypt_module_close($handle);
I've also left out any error checks.