Chris Weit
Chris Weit

Reputation: 70

Yii2 - generated password hash different every time

I'm trying to use Yii's generatePasswordHash() function, but I get a different hash with the same password, every time.

$this->password = Yii::$app->getSecurity()->generatePasswordHash($this->password);

Here 3 hashes created with the password "test":

$2y$13$wsvC4i8YMwKKHJ2K5iYRG.Z0KBetOh3BctVpJN5pVkXGOcW85hRkO ,
$2y$13$QfV2Qxlj4F5gUh1wIL2WUewoZ55CKYKevjRmRqrenxq8L5ym5xX9. ,
$2y$13$rDArvLa8hnpDGiiDdCs7be4iTsr2T3XMXmnapynuD1i1ekbz8zF4m

Anyone an idea what's happening?

EDIT:

When I try to verify with:

Yii::$app->getSecurity()->validatePassword($password, $this->password)

it returns false.

EDIT#2:
function looks like this:

public function validatePassword($password)
{
    return Yii::$app->getSecurity()->validatePassword($password, $this->password);
}

$password is the input password and $this->password is the hash.

Strangely password_verify($password, $this->password) works, but Yii's verifier doesn't.

Upvotes: 1

Views: 933

Answers (2)

yebowhatsay
yebowhatsay

Reputation: 341

Adding to efendi's answer.

Getting a different hash each time Yii's generatePasswordHash() function is run is normal behavour.

Validating the password against the hash requires the 'salt' from the 'hash'.

The first 22 characters after '$2y$13$' in the hash is the salt.

The validatePassword($password, $hash) function gets the salt from the hash, hashes the $password using the salt which should get the same hash as the $hash if the password were to be correct.

Upvotes: 0

efendi
efendi

Reputation: 58

All hashes are correct. Because hash algorithms make different hashes for the same password. Where does the password variable come from in your code? It should be a password string not a hash.

$hash = "hashed version";
$password = "string password";

if (Yii::$app->getSecurity()->validatePassword($password, $hash)){
   // password correct
}

Upvotes: 2

Related Questions