DefaultPasswordHasher为相同的值生成不同的哈希 [英] DefaultPasswordHasher generating different hash for the same value
问题描述
我有一个密码存储在database
,在add
操作中用DefaultPasswordHasher
散列.
I have a password stored at database
hashed with DefaultPasswordHasher
at add
action.
我还有另一项更改登录用户密码的操作,在此表单上,我有一个名为current_password
的字段,需要将其与database
中的当前密码值进行比较.
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
.
问题在于,每次我对表单的值进行哈希处理时,DefaultPasswordHasher
都会生成一个不同的哈希值,因此这将永远与数据库中的哈希值不匹配.
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.
遵循"current_password"字段的验证码:
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'
])
推荐答案
这是bcrypt的工作方式. Bcrypt是一种更强大的密码哈希算法,它将根据当前的系统熵为相同的值生成不同的哈希值,但是能够比较原始字符串是否可以哈希为已经哈希的密码.
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.
要解决您的问题,请使用check()
函数而不是hash()
函数:
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'
这篇关于DefaultPasswordHasher为相同的值生成不同的哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!