PHP password_verify 对数据库无效

PHP password_verify not working against database

我想给我一个更安全的页面,我开始使用密码加密它的一部分。我正在尝试实施 password_hash + 密码验证,但到目前为止,我一直未能使整个工作正常进行。所以,它在我的登录区:

$username = mysqli_real_escape_string($connection, $_POST['username']);

$password = mysqli_real_escape_string($connection, $_POST['password']);

$query = "SELECT username, password FROM `users` WHERE username='$username' and user_enabled='1'";
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
if($row = mysqli_fetch_assoc($result)) { $dbpassword = $row['password']; }

if(password_verify($password, $dbpassword)) {
    echo "Successful login";
}else{
    echo "Invalid Login Credentials.";
}

我总是收到无效的登录凭据。

当我为用户修改新密码时,我正在做以下事情:

$pass = mysqli_real_escape_string($connection, $_POST['password']);
$options = [ 'cost' => 10,
             'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
           ];
$password = password_hash($pass,  PASSWORD_BCRYPT, $options)."\n";

$query = "UPDATE users 
          SET `password` = '".$password."'
          WHERE id = ".$_POST['user_id']."
          ";

$result = mysqli_query($connection, $query) or die(mysqli_error($connection));

数据库中的密码是 VARCHAR(255),它存储的内容类似于:

y$Y5HIyAsLMfkXIFSJONPsfO3Gxx3b46H.8/WFdLVH3Fqk2XNfy2Uaq

我做错了什么?

下一行中的\n,嵌入了一个换行符,(编辑:不能包含在用户输入的密码中).

$password = password_hash($pass,  PASSWORD_BCRYPT, $options)."\n";

您需要删除它并使用新的哈希重新开始。

Jay Blanchard, a member here on Stack submitted a note about it not too long also in the password_hash()手册,这是我和他实际谈过的东西

Be care when using the example from the documentation which concatenates a newline character \n to the end of the hash, i.e.:

echo password_hash("rasmuslerdorf", PASSWORD_DEFAULT)."\n";

People are storing the hash with the concatenated newline and consequently password_verify() will fail.

另一种选择是使用 trim();这也有效(在散列时)。

$password = password_hash($pass,  PASSWORD_BCRYPT, $options)."\n";
$password = trim($password);
// Store in db after

但是您仍然需要通过清除旧哈希并创建新哈希来重新开始。

不过请记住,您不应该对密码进行转义。

诸如 123'\abc(完全有效)之类的将由 real_escape_string(); it's not needed. password_verify() 修改为 123\'\abc 以确保安全。