How to use php's password_hash() method..?

本小妞迷上赌 提交于 2019-12-04 05:51:15

问题


I'm getting password does not match when I login, when a user signup, I'm saving password as

$password = password_hash($this->input->post('password'), PASSWORD_BCRYPT);

when a user login I'm checking password like this,

    $hash = password_hash($password, PASSWORD_BCRYPT);
    $this->db->select('password');
    $this->db->from('usersdetails');
    $this->db->where('email', $email);
    $this->db->limit(1);
    $query = $this->db->get();
    $passwordcheck = $query->row()->password;
    if (password_verify($passwordcheck, $hash)) {
       return true;
    } else {
        return false;
    }

BUT it always return password does not match..why????? Any help is much appreciated...


回答1:


You are supposed to check the raw unhashed password, as the password_verify() does the re-hashing of the raw password using the hash routine used when creating the hashed password.

If you look at the result of the password_hash() there is information stored in the hash about which hash routine was used to create this hash, and how it was generated

$password = 'FredsTheMan';

$hash = password_hash($password, PASSWORD_BCRYPT);

if (password_verify($password, $hash)) { 
   return true;
} else {
    return false;
}

Another common mistake in this area is not giving the column you use on the database table enough characters to hold the full result of the hash

The hash generated using PASSWORD_BCRYPT is 60 characters

$2y$12$QjSH496pcT5CEbzjD/vtVeH03tfHKFy36d4J0Ltp3lRtee9HDxY3K

Beware, when other hashes are providied in the furure, they may result in a hash longer than 60 characters

So in short you code should be

$this->db->select('password');
$this->db->from('usersdetails');
$this->db->where('email', $email);
$this->db->limit(1);
$query = $this->db->get();
$pwd_from_db = $query->row()->password;

if (password_verify($this->input->post('password'), $pwd_from_db)) {
   return true;
} else {
    return false;
}


来源:https://stackoverflow.com/questions/35683537/how-to-use-phps-password-hash-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!