Domanda

  • I have inserted a userid and password (phpass encrypted) to the database
  • When a user logs in, the system compares for the matching userid and password
  • But since I'm comparing the input password with the stored password by hashing the input password, it always returns 'wrong password'

My code looks like the following. What am I doing wrong?

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';
}
È stato utile?

Soluzione

If the password saved in your database is already hashed (as it should be, you only need to hash the password taken from your user input and compare it against the already hashed value in your database.

The phpass library has a manual you can look into which provides tutorials on how to use it's methods properly (and also how to prevent common exploits such as SQL injection.

From the manual, I see that there's a method called CheckPassword($password, $hash) which returns a boolean.

The idea is that you pass the original password from the user input as the first argument, and pass the hashed value from the database as the second. It returns true if the passwords match (phpass does the hashing and checking internally), or false if they don't.

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.

}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top