Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 417
tolga Avatar asked Aug 28 '19 14:08

tolga


1 Answers

Note for Symfony > 5.4

From Symfony 6 these classes and methods are named more appropriately replacing Encode with Hash. And moved from the Security Core package to the Password Hasher package:

For example, Symfony\Component\Security\Core\Encoder\EncoderFactory becomes Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactory, and so on.

But the substance of the answer remains the same.


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
like image 80
yivi Avatar answered Sep 21 '22 14:09

yivi