Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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'
    ])
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
225 views
Welcome To Ask or Share your Answers For Others

1 Answer

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...