【发布时间】:2016-03-31 21:45:20
【问题描述】:
我不久前编写了这段代码,现在我正在为一个新项目重新启动它,但它似乎不起作用,我终其一生都无法弄清楚为什么它不会验证哈希值。
在注册第一个passwordEncrypt()函数时,运行的2个函数如下。
当尝试登录时调用 checkPassword() 函数,而不是登录并回显“是”,而是进入它回显“否”的部分。
所以,如果有新的眼睛可以看一下,请提前多谢!
// Encrypt user password
function passwordEncrypt($password) {
// set the salt
$salt = substr(md5(time()), 0, 22);
// encrypt using blowfish with a load of 10
$password = crypt($password, '$2a$10$' . $salt);
// return the encrypted hash
return $password;
}
/*
Check password function when logging in
first we select the password from the supplied username from the database
// get the row and set the hash to the currect password from the database
//run the salts etc and check to see if the passwords match
*/
function checkPassword($userName, $password, $db){
$sql = 'SELECT password FROM users WHERE userName = :userName';
$stmt = $db->prepare($sql);
$stmt->bindValue(':userName', $userName, PDO::PARAM_STR);
$stmt->execute();
$numRows = $stmt->rowCount();
if ($numRows > 0) {
$row = $stmt->fetch();
$hash = $row['password'];
// run the hash function on $password
$fullSalt = substr($hash, 0, 29);
$new_hash = crypt($password, $fullSalt);
// Check that the password matches
if($hash == $new_hash) {
echo 'yes';
exit;
return true;
} else {
echo 'no';
exit;
return false;
}
} else {
echo 'way';
exit;
return false;
}
}
我已经注册了密码,然后试了一下,结果就是这样
密码:$2a$10$023d3086e8462207a1fecueWH4Ub40MWbQJ7F9 输入:$2a$10$023d3086e8462207a1fecueWH4Ub40MWbQJ7F9hapWU3lYxlg3AAa 没有
所以它正在添加 hapWU3lYxlg3AAa
【问题讨论】:
-
密码列的长度和哈希字符串的长度是多少?
-
顺便说一句,你的退出抵消了你的回报。
-
如果您知道如何 ping 某人,很好。您的问题没有资格获得神奇的答案。
-
你真的不应该在密码哈希上使用你自己的盐,你真的应该使用 PHP 的 built-in functions 来处理密码安全。如果您使用的 PHP 版本低于 5.5,则可以使用
password_hash()compatibility pack。 -
它为您执行随机加盐,并且需要更少的代码。