使用password_verify和MySQL验证密码哈希

4

我正在尝试在MySQL中存储加密密码,对于注册部分,它按照预期工作,但是当我尝试登录时,出现了问题。

我无法将 $_POST['password'] 与存储在MySQL中的哈希值进行验证。我不知道我做错了什么。

这是我的 register.php 文件,它可以正常工作:

register.php(有效)

$post_password = mysqli_real_escape_string($_POST['password']);
$password_hash = password_hash($post_password, PASSWORD_BCRYPT);
mysqli_query goes here...

登录页面(login.php)无法正常工作

$con = mysqli_connect("XXX","XXX","XXX","XXX");
$post_username = mysqli_real_escape_string($con,$_POST['username']);
$post_password = mysqli_real_escape_string($con,$_POST['password']);

// Getting the stored Hash Password from MySQL
$getHash = mysqli_fetch_assoc(mysqli_query($con, "SELECT * FROM anvandare WHERE username = '$post_username'"));
$got_Hash = $getHash['password'];

// Checking if what the user typed in matches the Hash stored in MySQL
// **This is where it all goes wrong**
if (password_verify($post_password, $got_Hash)) {
echo "The posted password matches the hashed one";
}
else {
echo "The posted password does not match the hashed one";
}

当我运行以上代码时,只需输入用户名并将密码字段留空,即可收到“正确的密码”消息。
我错过了什么?

1
您在登录时没有将新输入的密码转换为哈希值进行比较,就像存储密码时所做的那样。 - Purushottam zende
你尝试过mysqli_fetch_array吗?另外,记得使用password_hash()函数对密码进行加密。 - habib ul haq
@habibulhaq 是对的,这种情况发生在每个人身上。我会将它写成一个答案。 - Purushottam zende
1
mysqli_real_escape_string 用于将字符串转义以便插入到数据库中,但不适用于使字符串安全地通过哈希函数运行。 - Quentin
@Dennis 进行一些基本的调试并检查你的哈希密码是否能够完整地通过数据库进行往返传输。一个非常常见的问题是数据库字段太短,从而截断哈希值。此外,正如Quentin所说,在对密码进行哈希之前不要转义密码。阅读The Great Escapism (Or: What You Need To Know To Work With Text Within Text)以更全面地了解这个问题。 - deceze
显示剩余2条评论
1个回答

2

实际上,您需要确保在密码列中允许超过100个字符,以便所有哈希密码都可以保存在该字段中。我也遇到了同样的问题,脚本是正确的,一切都正常工作,但我唯一犯的错误是没有允许密码字段超过40个字符,这是最大的错误。将最大限制从40增加到100后,一切正常:)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接