Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DefaultPasswordHasher generating different hash for the same value

I have a password stored at database hashed with DefaultPasswordHasher at add action.

I have another action for change the password for the loggedin user, on this form I have a field called current_password that I need compare with the current password value from database.

The issue is that DefaultPasswordHasher is generating a different hash for each time that I'm hashing the value of the form so this will never match with the hash from database.

Follow the validation code of the 'current_password' field:

    ->add('current_password', 'custom', [
        'rule' => function($value, $context){
            $user = $this->get($context['data']['id']);
            if ($user) {
                echo $user->password; // Current password value hashed from database
                echo '<br>';
                echo $value; //foo
                echo '<br>';
                echo (new DefaultPasswordHasher)->hash($value); // Here is displaying a different hash each time that I post the form

                // Here will never match =[
                if ($user->password == (new DefaultPasswordHasher)->hash($value)) {
                    return true;
                }
            }
            return false;
        },
        'message' => 'Você não confirmou a sua senha atual corretamente'
    ])
like image 970
Daniel Faria Avatar asked Apr 07 '15 19:04

Daniel Faria


1 Answers

That is the way bcrypt works. Bcrypt is a stronger password hashing algorithm that will generate different hashes for the same value depending on the current system entropy, but that is able to compare if the original string can be hashed to an already hashed password.

To solve your problem use the check() function instead of the hash() function:

 ->add('current_password', 'custom', [
        'rule' => function($value, $context){
            $user = $this->get($context['data']['id']);
            if ($user) {
                if ((new DefaultPasswordHasher)->check($value, $user->password)) {
                    return true;
                }
            }
            return false;
        },
        'message' => 'Você não confirmou a sua senha atual corretamente'
like image 167
José Lorenzo Rodríguez Avatar answered Sep 26 '22 23:09

José Lorenzo Rodríguez