Why does calling encodePassword() with identical salts and passwords produces diffent hashes in Symfony 4?

人盡茶涼 提交于 2019-12-10 22:46:34

问题


In UserPassword encoder,

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.

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

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

But when I encode:

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

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

What am I missing?


回答1:


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).

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;
}

Notice this comment:

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

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).

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

Further reading:

  • New in Symfony 4.3: Native Password Encoder
  • password_hash() docs
  • https://paragonie.com/book/pecl-libsodium/read/07-password-hashing.md


来源:https://stackoverflow.com/questions/57694350/why-does-calling-encodepassword-with-identical-salts-and-passwords-produces-di

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