4

我正在尝试设置一个表单以允许用户使用 CakePHP 2.3 更改他们的密码。正在使用的算法是河豚。我有以下三个字段:

<?php echo $this->Form->input('old_password', array('type' => 'password', 'autocomplete' => 'off')); ?>
<?php echo $this->Form->input('new_password', array('type' => 'password', 'autocomplete' => 'off')); ?>
<?php echo $this->Form->input('new_password_confirm', array('type' => 'password', 'autocomplete' => 'off', 'label' => 'Confirm Password')); ?>

这是我试图验证他们正确输入旧密码的代码:

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

问题是即使我正确输入了旧密码,Cake 也永远找不到用户,因为它似乎没有计算正确的哈希值。每次我使用相同的旧密码提交表单时,Cake 每次都会生成不同的哈希值。这可能是由于我对河豚/bcrypt 算法的工作原理缺乏了解,但我似乎无法弄清楚。

我在这里想念什么?

4

2 回答 2

16

使用河豚哈希与使用其他哈希类型不同。来自hash方法的 API 文档:

比较哈希:只需将原始哈希密码作为盐传递。

这意味着在您的情况下,您首先必须检索特定用户的散列密码,然后将其用作盐。就像是

$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;
于 2013-06-22T15:51:33.813 回答
2

是否容易添加模型,例如用户。

链接来源: 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;
}

    .........
}
于 2016-03-31T20:13:37.853 回答