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

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

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

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

1 Answer

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...