不要使用 MD5。你应该使用hash_hmac() 或者更好的新PHP Hashing API(如果你至少有PHP 5.5)。为了使密码更安全,使用随机生成的,为每个用户使用不同的盐(它只是一个充满随机字符的字符串)并将其与密码一起保存在数据库中。
这是一个生成随机字符串的函数($length决定返回字符串的长度):
function generate($length) {
$dummy = array_merge(range('0', '9'), range('a', 'z'), range('A', 'Z'));
shuffle($dummy);
return substr(implode('', $dummy), 0, $length);
}
这是 PHP Hashing API 的代码 sn-p:
function my_password_hash($salt, $password) {
$phpapi_options = array("algo" => PASSWORD_BCRYPT, "salt" => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM), "cost" => 11);
return password_hash(sha1($salt.$password), $phpapi_options['algo'], $phpapi_options);
}
function my_password_verify($salt, $password, $hash) {
return password_verify(sha1($salt.$password), $hash);
}
my_password_hash() 为给定的盐和密码生成哈希。 my_password_verify() 使用您存储在数据库中的哈希验证给定的密码(用户输入)和盐(来自数据库)。
这是一个带有 hash_hmac() 的代码 sn-p:
function my_password_hash($salt, $password) {
$hash_key = ""; //define a 10 characters long random generated string here (it has to be always the same)
if(empty($hash_key)) {
die('You must enter a valid hash key.');
}
return hash_hmac("sha512", sha1($salt.$password), $hash_key);
}
function my_password_verify($salt, $password, $hash) {
if($hash == my_password_hash($salt, $password)) {
return true;
} else {
return false;
}
}
我希望这对您有所帮助,如果没有或者您有任何问题,请尽管提问。