从数据库验证哈希密码 [英] Verifying a hashed password from database
问题描述
因此,我有一个登录页面,该页面在没有哈希密码的情况下也可以正常工作,但是当然,这并不安全,因此我决定在注册时对密码进行哈希处理.
但是当我从数据库中选择密码时,我不知道如何以及在哪里使用verify_password.
我用一段时间来查看是否输入了这样的用户名和密码:
So I have a login page which worked fine without hashed passwords but of course, that wasn't secure so I decided to hash the passwords when registering.
but I don't know how and where should I use verify_password when I'm selecting the password from the database.
I use while to see if there is a result with the username and password entered like this:
$q = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$x = $conn->query($q);
if ($x->num_rows > 0) {
while ($row = $x->fetch_assoc()) {
//Logged in seccesfully!
}
} else {
// Username or password is wrong!
}
推荐答案
password_hash()函数可以简化我们的生活,并且我们的代码可以安全.当您需要对密码进行哈希处理时,只需将其提供给函数,它将返回可以存储在数据库中的哈希值.
password_hash() function can simplify our lives and our code can be secure. When you need to hash a password, just feed it to the function and it will return the hash which you can store in your database.
$hash = password_hash($password, PASSWORD_DEFAULT);
现在,您已经了解了如何使用新的API生成哈希,下面我们来看看如何验证密码.请记住,您将哈希存储在数据库中,但这是用户登录时获得的普通密码. password_verify()函数采用普通密码和哈希字符串作为其两个参数.如果哈希与指定的密码匹配,则返回true.
Now that you have seen how to generate hashes with the new API, let’s see how to verify a password. Remember that you store the hashes in a database, but it’s the plain password that you get when a user logs in. The password_verify() function takes a plain password and the hashed string as its two arguments. It returns true if the hash matches the specified password.
<?php
if (password_verify($password, $hash)) {
// Success!
}
else {
// Invalid credentials
}
了解更多信息,阅读
这篇关于从数据库验证哈希密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!