使用CakePHP和blowfish更改密码
我正在尝试设置一个表单,允许用户使用CakePHP2.3更改密码。使用的算法是河豚。我有以下三个字段:使用CakePHP和blowfish更改密码,cakephp,cakephp-2.0,bcrypt,blowfish,Cakephp,Cakephp 2.0,Bcrypt,Blowfish,我正在尝试设置一个表单,允许用户使用CakePHP2.3更改密码。使用的算法是河豚。我有以下三个字段: <?php echo $this->Form->input('old_password', array('type' => 'password', 'autocomplete' => 'off')); ?> <?php echo $this->Form->input('new_password', array('type' => 'p
<?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')); ?>
问题是,即使我正确输入了旧密码,Cake也找不到用户,因为它似乎没有计算正确的散列。每次我使用相同的旧密码提交表单时,Cake每次都会生成不同的散列。这可能是因为我不了解blowfish/bcrypt算法是如何工作的,但我似乎无法理解它
我在这里遗漏了什么?使用河豚哈希与使用其他哈希类型不同。从方法的API文档中: 比较散列:只需将最初散列的密码作为salt传递 这意味着您首先必须检索特定用户的哈希密码,然后将其用作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;
对于示例用户,很容易添加模型 链接来源:
这样更好:
$correct=strcmp($storedHash,$newHash)==0
@MirkoPagliai为什么更好?@MirkoPagliai使用===不是更好吗?不确定链接中的何处回答了为什么首选strcmp。
$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;
/**
* 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;
}
.........
}