yii CPasswordHelper:hashPassword和verifyPassword [英] yii CPasswordHelper: hashPassword and verifyPassword
问题描述
我想我在这里错过了一些关键的东西。在 CPasswordHelper :: hashPassword
函数我们有行:
I think I'm missing something critical here. In the CPasswordHelper::hashPassword
function we have lines:
$salt=self::generateSalt($cost);
$hash=crypt($password,$salt);
return $hash;
而在 CPasswordHelper :: verifyPassword
有这一行:
And in the CPasswordHelper::verifyPassword
there is this line:
$test=crypt($password,$hash);
return self::same($test, $hash);
盐怎么样?根据我的理解,它甚至没有保存,但它没有任何意义,所以我猜我完全不明白。
What about the salt? To my understanding its not even beeing kept, but it doesn't make any sense, so I'm guessing I didn't understand it completely.
推荐答案
CPasswordHelper的功能与PHP的函数 password_hash()和 password_verify(),它们是crypt()函数的包装器。当你生成一个BCrypt哈希时,你会得到一个60个字符的字符串,包含盐。
CPasswordHelper works like PHP's functions password_hash() and password_verify(), they are wrappers around the crypt() function. When you generate a BCrypt hash, you will get a string of 60 characters, containing the salt.
// Hash a new password for storing in the database.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
变量$ hashToStoreInDb现在包含一个像这样的哈希值:
The variable $hashToStoreInDb will now contain a hash-value like this:
$2y$10$nOUIs5kJ7naTuTFkBy1veuK0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
| | | |
| | | hash-value = K0kSxUFXfuaOKdOKf9xYT0KKIGSJwFa
| | |
| | salt = nOUIs5kJ7naTuTFkBy1veu
| |
| cost-factor = 10 = 2^10 iterations
|
hash-algorithm = 2y = BCrypt
在第三个 $
,它是由password_hash()使用操作系统的随机源自动生成的。由于salt包含在结果字符串中,所以函数password_verify()或实际包装的crypt函数可以从中提取出来,并且可以使用相同的盐(以及相同的成本因子)计算哈希值。这两个哈希是可比的。
The salt you can find after the third $
, it is generated automatically by password_hash() using the random source of the operating system. Because the salt is included in the resulting string, the function password_verify(), or actually the wrapped crypt function, can extract it from there, and can calculate a hash with the same salt (and the same cost factor). Those two hashes are then comparable.
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);
这篇关于yii CPasswordHelper:hashPassword和verifyPassword的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!