First of all, +1 for using PHP's password functions for password hashing!
In contrary to normal hashing functions (such as md5()
, sha1()
, etc. - which should not be used for password hashing), password_hash()
will produce a different hash from the same password every time, because it automatically generates a random salt for every hash. This is a great feature that makes your password hashes a lot safer, but it means that you cannot use password_hash()
to hash the entered password, and use that hashed password in your SQL query (combined with the username) to retrieve the user.
Instead, just retrieve the user based on it's username - and then compare the retrieved password hash with the entered password using password_verify()
. This function is able to compare the entered password with the stored hash, even if the cost or algorithm have changed.
Example (using your code):
public function get_user($username, $password)
{
$this->query = $this->conn->prepare('SELECT * from users WHERE username=:username LIMIT 1');
$this->query->bindParam(':username', $username);
$this->query->execute();
$user = $this->query->fetch(PDO::FETCH_ASSOC);
if (password_verify($password, $user['password']) {
// password is correct, return the user
return $user;
} else {
// incorrect password
return false;
}
}
Increasing the strength of passwords in the future
As I said before, the new password API allows to upgrade the strength of newly generated password hashes without breaking older ones. This is because the cost and the algorithm (as well as the salt, by the way) are stored within the hash.
It is advisable to increase the cost over time, as available hardware becomes stronger (decreasing the time it would take for an attacker to brute-force a password).
If you decide to do so, or if you decide to use another hashing algorithm, don't forget to add a check using password_needs_rehash()
in your login procedure. This way existing passwords will be re-hashed as well.
If the function (called with the hash from the database as a parameter) returns true, simply run password_hash()
again and overwrite the old hash in the database with the new hash. This can obviously only be done when users log in, because that is the only time you should have access to the plain-text passwords.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…