DefaultPasswordHasher generates different hashes for the same value.

I have a password stored in a database hashed with DefaultPasswordHasher on add .

I have another action for changing the password for the loggedin user, in this form I have a field called current_password , which I need to compare with the current password value from database .

The problem is that DefaultPasswordHasher generates a different hash for every time I hash the value of the form, so this will never match the hash from the database.

Follow the confirmation code for 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' ]) 
+6
source share
1 answer

This is how 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 this can be compared if the original string can be hashed with 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' 
+12
source

Source: https://habr.com/ru/post/984811/


All Articles