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
$ivshould not be dependent on$hashKey; rather, you should create it separately usingmcrypt_create_iv().Your
$hashKeyshould be binary rather than textual.MCRYPT_RIJNDAEL_256is 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:
I’ve also left out any error checks.