我正在尝试设置一个表单,允许用户使用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每次都会生成一个不同的哈希值。这可能是由于我对blowfish / bcrypt算法的工作方式缺乏了解,但我似乎无法弄明白。
我在这里缺少什么?
答案 0 :(得分:16)
使用blowfish哈希与其他哈希类型不同。来自hash方法的API文档:
比较哈希:只需将原来的哈希密码作为盐传递。
这意味着在您的情况下,您首先必须检索特定用户的散列密码,然后将其用作salt。像
这样的东西$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;
答案 1 :(得分:1)
轻松添加模型,例如用户。
链接来源: 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;
}
.........
}