DefaultPasswordHasher 为相同的值生成不同的散列

DefaultPasswordHasher generating different hash for the same value

我在 database 处存储了一个密码,在 add 操作中使用 DefaultPasswordHasher 进行了哈希处理。

我有另一个更改登录用户密码的操作,在此表单上我有一个名为 current_password 的字段,我需要将其与 database.[=17 中的当前密码值进行比较=]

问题是 DefaultPasswordHasher 每次我对表单的值进行哈希处理时都会生成不同的哈希值,因此它永远不会与数据库中的哈希值匹配。

遵循'current_password'字段的验证码:

    ->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 是一种更强大的密码散列算法,它会根据当前系统熵为相同的值生成不同的散列值,但它能够比较原始字符串是否可以散列为已经散列的密码。

要解决您的问题,请使用 check() 函数而不是 hash() 函数:

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