PHP has certain functions that are meant to be used together, such as mcrypt_decrypt and mcrypt_encrypt. You're using mcrypt_decrypt, but for encryption, you're instead using mcrypt_ecb.
You're also passing incorrect arguments to mcrypt_decrypt. The mode argument needs to be one of MCRYPT_MODE_ECB, MCRYPT_MODE_CBC, MCRYPT_MODE_CFB, etc. The standard choice is CBC. Use that unless you have a good reason to choose differently.
if (empty($_COOKIE['username']))
{
$username='someuser';
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$encrypted_username=mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $username, MCRYPT_MODE_ECB, $iv);
setcookie('username', "$encrypted_username", time()+60*60*24*30, '/');
print 'Cookie created.';
}
elseif (isset($_COOKIE['username']))
{
$username_decrypted=mcrypt_decrypt(MCRYPT_3DES, $key, $_COOKIE['username'], MCRYPT_MODE_CBC);
print 'You are logged in as '.$username_decrypted;
}
And now I'm getting this when I load the page after cookie creation:
Warning: mcrypt_decrypt() [function.mcrypt-decrypt]: Attempt to use an empty IV, which is NOT recommend in C:\xampp\htdocs\xampp\phptest.php on line 15
You are logged in as ‚Dî'üTtNeýNJ5-ró]#P:fÁø†K
The better I get at programming, the more I appreciate arrays. Handy dandy things they are.
You're encrypting with MCRYPT_RIJNDAEL_256 and MCRYPT_MODE_ECB, but decrypting with MCRYPT_3DES and MCRYPT_MODE_CBC. And for the IV... the same IV you use during encryption must also be used during decryption. So if you're going to generate a random IV, then you'll need to save the IV in the cookie so you can reuse it during decryption.
The IV needs to be a specific size, which may be different for each encryption algorithm. If you want an IV of all 0 bytes, here's what you'll need to do.
$ivSize = 8; // I *think* this is 3DES's IV size
$iv = str_repeat("\0", $ivSize);
Ideally we would use mcrypt_enc_get_iv_size, but to do that, we'd have to use a whole other set of mcrypt functions.
Bookmarks