简体   繁体   English

Yii2 - 生成的密码 hash 每次都不同

[英]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.我正在尝试使用 Yii 的 generatePasswordHash() function,但每次都使用相同的密码得到不同的 hash。

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

Here 3 hashes created with the password "test":这里使用密码“test”创建了 3 个哈希:

$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:编辑#2:
function looks like this: function 看起来像这样:

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

$password is the input password and $this->password is the hash. $password 是输入密码,$this->password 是 hash。

Strangely password_verify($password, $this->password) works, but Yii's verifier doesn't.奇怪的password_verify($password, $this->password)有效,但 Yii 的验证器无效。

All hashes are correct.所有哈希都是正确的。 Because hash algorithms make different hashes for the same password.因为 hash 算法为相同的密码生成不同的哈希值。 Where does the password variable come from in your code?密码变量在您的代码中来自哪里? It should be a password string not a hash.它应该是密码字符串,而不是 hash。

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

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

Adding to efendi's answer.添加到efendi的答案。

Getting a different hash each time Yii's generatePasswordHash() function is run is normal behavour.每次运行 Yii 的 generatePasswordHash() function 时获取不同的 hash 是正常行为。

Validating the password against the hash requires the 'salt' from the 'hash'.针对 hash 验证密码需要来自“哈希”的“盐”。

The first 22 characters after '$2y$13$' in the hash is the salt. hash 中 '$2y$13$' 之后的前 22 个字符是盐。

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. validatePassword($password, $hash) function 从 hash 获取盐,使用盐对 $password 进行哈希处理,如果密码正确,则应该得到相同的 Z0800FC577294C34E0B28AD283943。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM