如何使用PHPass存储密码加密并在登录时进行比较

时间:2014-01-30 14:12:53

标签: php codeigniter phpass

  • 我已将用户ID和密码(phpass加密)插入 数据库
  • 当用户登录时,系统会比较匹配的用户ID和 密码
  • 但是因为我将输入的密码与存储的密码进行比较 通过哈希输入密码,它总是返回'错误密码'

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

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';
}

1 个答案:

答案 0 :(得分:3)

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

phpass库有一个manual,您可以查看它提供有关如何正确使用它的方法的教程(以及如何防止SQL注入等常见漏洞。

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

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

e.g。

$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.

}