DefaultPasswordHasher generating different hash for the same value

爱⌒轻易说出口 提交于 2019-11-27 06:13:07

问题


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'
    ])

回答1:


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'


来源:https://stackoverflow.com/questions/29499287/defaultpasswordhasher-generating-different-hash-for-the-same-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!