the*_*ark 5 php login php-password-hash
我有一个用于登录应用程序的处理文件。我要么不明白的目的,password_needs_rehash()要么它不起作用。登录正在验证并将我传递到正确的页面。但是我什至无法让代码回显新的哈希值。
我这样做正确吗?
是否if不抛出新的哈希值,因为它并不需要改头换面?如果是这样,如果密码正确散列并存储在数据库中,什么时候需要重新散列?
我的处理文件如下:
$email = $_POST["li_email"];
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$stmt = $conn->query("SELECT * FROM users WHERE email='$email'");
$stmt->execute();
while($row=$stmt->fetch()){ //for each result, do the following
$hash = $row['hash'];
$userPassword = $_POST["li_password"];
if (password_verify($userPassword, $hash)) {
if ( password_needs_rehash($hash, PASSWORD_DEFAULT, ['cost' => 12]) ) {
$newhash = password_hash($userPassword, PASSWORD_DEFAULT, ['cost' => 12]);
echo $newhash;
}
} else {
header('Location: http://' . $_SERVER['HTTP_HOST'] . '?error=loginfailed');
exit();
}
}
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
Run Code Online (Sandbox Code Playgroud)
感谢您的帮助!
仅当您更改通常引用的 时才password_needs_rehash()需要使用该函数。$optionscost
成本越高,哈希密码所需的 CPU 时间就越多,但破解密码也就越困难。如果您更改托管或转移到基于云的系统,其中多台计算机可以为您计算哈希值,您可以自行决定增加它。
您只需要在用户登录时检查密码是否需要重新哈希,因为password_verify()如果您更改了$options. 如果password_needs_rehash()此时返回 true,则使用password_hash()新选项并替换旧哈希。
if (password_verify($_POST["li_password"], $row['hash'])) {
// valid login
if (password_needs_rehash($row['hash'], PASSWORD_DEFAULT, $options = ['cost' => 12])) {
$newhash = password_hash($_POST["li_password"], PASSWORD_DEFAULT, $options);
// store new hash in db.
}
} else {
header('Location: http://' . $_SERVER['HTTP_HOST'] . '?error=loginfailed');
exit();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3075 次 |
| 最近记录: |