1
  • 我已将用户名和密码(phpass 加密)插入数据库
  • 当用户登录时,系统会比较匹配的用户名和密码
  • 但是由于我通过对输入密码进行哈希处理来比较输入密码和存储的密码,所以它总是返回“错误密码”

我的代码如下所示。我究竟做错了什么?

if(isset($_POST["btn_submitlogin"])){          
  $userpass1 = "admin1234";
  $this->load->library('phpass');
  $this->load->database();
  $hashed1 = $this->phpass->hash($userpass1);  

  $userpass2 = "admin1234"; // For example, I load the DB password here
  $this->load->database();
  $hashed2 = $this->phpass->hash($userpass2);

  if ($this->phpass->check($hashed1, $hashed2))
    echo 'logged in';
  else
    echo 'wrong password';
}
4

1 回答 1

3

如果保存在数据库中的密码已经过哈希处理(应该如此,您只需对从用户输入中获取的密码进行哈希处理,并将其与数据库中已经哈希处理的值进行比较。

phpass 库有一本手册,您可以查看该手册,其中提供了有关如何正确使用其方法的教程(以及如何防止 SQL 注入等常见漏洞)。

从手册中,我看到有一个称为CheckPassword($password, $hash)返回布尔值的方法。

这个想法是您将用户输入的原始密码作为第一个参数传递,并将数据库中的散列值作为第二个参数传递。如果密码匹配(phpass 在内部进行散列和检查),则返回 true,否则返回 false。

例如

$pass = $_POST['password']; // Your user input.

// .. Check the existence of your user in the DB, and fetch the hashed password (as $hash) if they exist.

if($phpass->CheckPassword($pass, $hash)) {

    // Authenticated!

} else {

    /// Incorrect password.

}
于 2014-01-30T14:16:32.573 回答