为什么在 Symfony 4 中使用相同的盐和密码调用 encodePassword() 会产生不同的哈希值? [英] Why does calling encodePassword() with identical salts and passwords produces diffent hashes in Symfony 4?

查看:30
本文介绍了为什么在 Symfony 4 中使用相同的盐和密码调用 encodePassword() 会产生不同的哈希值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

UserPassword 编码器,

public function encodePassword(UserInterface $user, string $plainPassword)
{
    $encoder = $this->encoderFactory->getEncoder($user);
    return $encoder->encodePassword($plainPassword, $user->getSalt());
}

编码器从用户实体获取盐.

encoder gets the salt from user entity.

我为 User 实体中的 getSalt() 设置了一个静态变量:

I set a static variable to the getSalt() in User entity:

public function getSalt()
{
    return 'my-static-salt';
}

但是当我编码时:

$password  = $encoder->encodePassword($user, "my-password");
$password2 = $encoder->encodePassword($user, "my-password");

$password$password2 彼此不同,就好像 encodePassword() 方法使用随机盐一样.

$password and $password2 are different from each other as if the encodePassword() method uses a random salt.

我错过了什么?

推荐答案

EncoderFactory 是,默认情况下,给你一个 NativePasswordEncoder 的实例(除非你有安装了 libsodium 库,在这种情况下,它会给你一个 SodiumPasswordEncoder).

The EncoderFactory is, by default, giving you an instance of the NativePasswordEncoder (unless you have the libsodium library installed, in which case it would give you a SodiumPasswordEncoder).

如果你查看 NativePasswordEncoder::encodePassword() 你会看到 这个:

If you look at NativePasswordEncoder::encodePassword() you'll see this:

public function encodePassword($raw, $salt)
{
    if (\strlen($raw) > self::MAX_PASSWORD_LENGTH) {
        throw new BadCredentialsException('Invalid password.');
    }

    // Ignore $salt, the auto-generated one is always the best

    $encoded = password_hash($raw, $this->algo, $this->options);

    if (72 < \strlen($raw) && 0 === strpos($encoded, '$2')) {
        // BCrypt encodes only the first 72 chars
        throw new BadCredentialsException('Invalid password.');
    }

    return $encoded;
}

注意这个评论:

//忽略 $salt,自动生成的总是最好的

// Ignore $salt, the auto-generated one is always the best

如果你不给password_hash()传递一个salt字符串,它会在你每次调用它时生成它自己随机生成的salt,并将salt存储在操作的结果中(和使用哈希算法).

If you do not pass a salt string to password_hash(), it will generate its own randomly generated salt each time you call it, and store the salt within the result of the operation (and the hashing algorithm used).

(同样,在 SodiumPasswordEncoder 中,您会看到 $salt 根本没有使用,尽管不存在类似的注释.

(Similarly, in SodiumPasswordEncoder you'll see that $salt is not used at all, although a similar comment does not exist).

进一步阅读:

这篇关于为什么在 Symfony 4 中使用相同的盐和密码调用 encodePassword() 会产生不同的哈希值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆