yii CPasswordHelper: hashPassword 和 verifyPassword [英] yii CPasswordHelper: hashPassword and verifyPassword

查看:30
本文介绍了yii CPasswordHelper: hashPassword 和 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()使用操作系统的随机源自动生成的.因为盐包含在结果字符串中,函数 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆