I've been sifting through this forum trying to learn as much as I can about how to correctly use mcrypt. I'd appreciate comments on what I've got so far:
Code: Select all
function encrypt($decrypted, $password) {
$key = md5($password);
$decrypted = rtrim($decrypted, "\0\4");
$hash = md5($decrypted);
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC), MCRYPT_RAND);
$encrypted = trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $decrypted, MCRYPT_MODE_CBC, $iv)));
return $hash . "\n----------\n" . base64_encode($iv) . "\n----------\n" . $encrypted;
}
function decrypt($encrypted, $password) {
$key = md5($password);
list($hash, $iv, $encrypted) = explode("\n----------\n", $encrypted, 3);
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, base64_decode($encrypted), MCRYPT_MODE_CBC, base64_decode($iv)), "\0\4");
if (md5($decrypted) != $hash) return false;
return $decrypted;
}
1) I've read that using the password as the key is bad. Is an md5 of the password sufficient?
2) The script and the data are stored in the filesystem of the server. The password is to be memorized and entered by the operator. Should I salt the key, and if so, how and why?
3) Is there any issue with storing the iv or md5 of the data in clear text?
Thanks to anyone who can answer any of my questions or offer advice about my code to make it more secure.