Hi, I need to encrypt some data for a client. I’ve looked at a few code samples and have adapted this from Stack Exchange. Does it ook okay? Are there any ways to make it more secure?
I have a few questions:
- Is it true that MCRYPT_RIJNDAEL_128 == AES 256-bit? If so, why the misnomer?
- I’ve heard you can used a MAC in encryption. What is this and do I need to adapt the code below?
- Why the need for base64? It seems to work without it?
- What is MCRYPT_MODE_CBC and is it the right option?
Thanks.
function encrypt($toEncrypt, $key) {
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_DEV_URANDOM);
return base64_encode($iv . mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $toEncrypt, MCRYPT_MODE_CBC, $iv));
}
function decrypt($toDecrypt, $key) {
$ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$toDecrypt = base64_decode($toDecrypt);
return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, substr($toDecrypt, $ivSize), MCRYPT_MODE_CBC, substr($toDecrypt, 0, $ivSize)));
}
$key = 'my key';
$string = 'Plain text string';
$encrypted = encrypt($string, $key);
echo $encrypted;
echo '<br />';
echo decrypt($encrypted, $key);