Changing password with CakePHP and blowfish

倾然丶 夕夏残阳落幕 提交于 2019-12-04 11:18:46

Working with blowfish hashes is different than with other hash types. From the API docs of the hash method:

Comparing Hashes: Simply pass the originally hashed password as the salt.

This means in your case you first have to retrieve the hashed password for the specific user and then use it as the salt. Something like

$user = $this->User->find('first', array(
  'conditions' => array(
    'User.id' => AuthComponent::user('id')
  ),
  'fields' => array('password')
));
$storedHash = $user['User']['password'];
$newHash = Security::hash($this->request->data['User']['old_password'], 'blowfish', $storedHash);
$correct = $storedHash == $newHash;

Is Easy add in Models for example Users.

Link source: https://bitbucket.org/snippets/eom/arzxR

/**
 * Users Model
 */
class Users extends AppModel
{
.........

public function beforeSave($options = array()) {
    parent::beforeSave($options);
    // Save new password is exist..?
    if (isset($this->data[$this->alias]['password'])==true) {
        // Security bcrypt Blowfish
        App::uses('Security', 'Utility');
        $hash = Security::hash($this->data[$this->alias]['password'], 'blowfish');
        $this->data[$this->alias]['password'] = $hash;
    }
    return true;
}

public function password_check($user_id = null, $password_check = null) {
    // Get password old
    $hash_old = $this->field('password',array('id'=>trim($user_id)));
    // Security bcrypt Blowfish
    App::uses('Security', 'Utility');
    $hash_new_check = Security::hash($password_check, 'blowfish', $hash_old);
    // Son iguales
    if($hash_new_check == $hash_old){
        return true;
    }
    return false;
}

public function password_update($user_id = null, $password_new = null) {
    // Update new password
    if($this->save(array('id'=>$user_id, 'password'=>$password_new))){
        return true;
    }
    return false;
}

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