Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing password with CakePHP and blowfish

I'm trying to set up a form to allow a user to change their password using CakePHP 2.3. The algorithm being used is blowfish. I have the following three fields:

<?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')); ?>

Here is the code where I'm trying to verify they entered their old password correctly:

$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')
));

The problem is that even though I type in the old password correctly, Cake never finds the user because it doesn't seem to be calculating the correct hash. Each time I submit the form with the same old password, Cake generates a different hash every time. This is likely due to my lack of understanding of how the blowfish/bcrypt algorithm works, but I can't seem to figure it out.

What am I missing here?

like image 612
Hoff Avatar asked Dec 02 '22 19:12

Hoff


1 Answers

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;
like image 169
dhofstet Avatar answered Dec 23 '22 15:12

dhofstet