gpt4 book ai didi

php - 尝试理解PHP的password_hash

转载 作者:行者123 更新时间:2023-12-03 03:03:46 26 4
gpt4 key购买 nike

我正在尝试了解有关 PHP 安全最佳实践的更多信息,并且遇到了password_hash 和 password_compat安东尼·费拉拉的项目。我想我了解如何实现它,但在测试中,我遇到了一种奇怪的行为,它与我对密码哈希的新手理解相矛盾。

如果我将password_hash函数的结果保存到MySQL数据库用户记录中,然后使用password_verify检索该哈希值进行验证,它会按预期工作。但是,如果我做完全相同的事情,而不是从数据库中提取,而是通过从数据库中复制/粘贴来硬编码密码哈希,则password_verify 函数将失败。

代码如下:

// Get the Username and password hash from the MySQL database.  GetPassTestuser routine returns an array where
// position[0][0] is the username and position[0][1] is the password hash.
$arrUser = GetPassTestuser("mike24");
echo("User Name: ".$arrUser[0][0]."<br/>");
echo("Password hash: ".$arrUser[0][1]."<br/>");

// Run password_verify with the password hash collected from the database. Compare it with the string "mytest"
// (This returns true in my tests).
if (password_verify("mytest",$arrUser[0][1])){
echo("Password verified");
} else {
echo("Password invalid");
}
echo("<hr>Now On to our second test...<br/>");
// Now run password_verify with a string representation directly copied/pasted from the database. This is
// being compared with "mytest", which in my mind should return a true value. But it doesn't and this test
// fails. Not sure why.
if (password_verify("mytest","$2y$10$S33h20qxHndErOoxJL.sceQtBQXtSWrHieBtFv59jwVwJuGeWwKgm")){ // String shown here is the same as value contained in $arrUser[0][1]
echo("2nd Test Password verified");
} else {
echo("2nd test Password invalid");
}

虽然这不是我在实际代码中所做的事情,但我只是想了解其中的区别。为什么当我使用应该包含完全相同的哈希值的字符串变量时它可以正常工作,但在硬编码时却不起作用?

谢谢!

最佳答案

来自 PHP 文档

To specify a literal single quote, escape it with a backslash (). To specify a literal backslash, double it (\). All other instances of backslash will be treated as a literal backslash: this means that the other escape sequences you might be used to, such as \r or \n, will be output literally as specified rather than having any special meaning.

If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces to explicitly specify the end of the name.

使用单引号

替换

"$2y$10$S33h20qxHndErOoxJL.sceQtBQXtSWrHieBtFv59jwVwJuGeWwKgm"

'$2y$10$S33h20qxHndErOoxJL.sceQtBQXtSWrHieBtFv59jwVwJuGeWwKgm'

或者

"\$2y\$10\$S33h20qxHndErOoxJL.sceQtBQXtSWrHieBtFv59jwVwJuGeWwKgm"

关于php - 尝试理解PHP的password_hash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12844322/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com