我已经通过互联网搜索并找到了哈希密码的功能。但
我无法处理存储在数据库中的散列密码。我正在使用的函数生成随机密码,因为它与随机生成的盐连接。
当用户想要更改密码时会出现问题。
current_password = random hashed password( which must match the one stored in db).
if(current_password == $db_password){
enter new password
}
上述条件不会成立,因为密码总是随机的。
我的职能
function cryptPass($input,$rounds = 9) {
$salt = "";
$saltChars = array_merge(range('A','Z'),range('a','z'),range(0,9));
for($i = 0;$i < 22; $i++){
$salt .= $saltChars[array_rand($saltChars)];
}
return crypt($input,sprintf('$2y$%02d$', $rounds).$salt);
}
$pass = "password";
$hashedPass = cryptPass($pass);
echo $hashedPass;
i have 3 column in my user table (id, username, password).
任何人都可以告诉我如何正确使用这个功能, 或者有最佳方法吗?
答案 0 :(得分:0)
您希望将数据库中生成的$salt
与散列密码一起存储。然后,当您检查密码时,您将能够从数据库中获取salt并再次在散列过程中使用它。
所以你的数据库表中有一个额外的列叫做“salt”
(id, username, password, salt)
答案 1 :(得分:0)
您需要执行与登录相同的步骤。检查输入的旧密码是否与数据库中的密码哈希匹配,然后根据输入的新密码创建哈希并存储。
PHP已经有一个函数password_hash()来创建一个哈希,一个函数password_verify()来检查输入的密码是否与存储的密码哈希相匹配。
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);
所以你的代码看起来像这样:
if (password_verify(current_password, $db_password))
{
enter new password
}