php - YII2默认的密码加密方式是什么?怎么改成BCrypt加密?
本文介绍了php - YII2默认的密码加密方式是什么?怎么改成BCrypt加密?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
因为Laravel5的密码默认加密方式是bcrypt
,希望让YII2也使用这种加密方式,怎么做?Google都难找到资料。
解决方案
public function generatePasswordHash($password, $cost = null)
{
if ($cost === null) {
$cost = $this->passwordHashCost;
}
if (function_exists('password_hash')) {
/** @noinspection PhpUndefinedConstantInspection */
return password_hash($password, PASSWORD_DEFAULT, ['cost' => $cost]);
}
$salt = $this->generateSalt($cost);
$hash = crypt($password, $salt);
// strlen() is safe since crypt() returns only ascii
if (!is_string($hash) || strlen($hash) !== 60) {
throw new Exception('Unknown error occurred while generating hash.');
}
return $hash;
}
public function validatePassword($password, $hash)
{
if (!is_string($password) || $password === '') {
throw new InvalidParamException('Password must be a string and cannot be empty.');
}
if (!preg_match('/^\$2[axy]\$(\d\d)\$[\.\/0-9A-Za-z]{22}/', $hash, $matches)
|| $matches[1] < 4
|| $matches[1] > 30
) {
throw new InvalidParamException('Hash is invalid.');
}
if (function_exists('password_verify')) {
return password_verify($password, $hash);
}
$test = crypt($password, $hash);
$n = strlen($test);
if ($n !== 60) {
return false;
}
return $this->compareString($test, $hash);
}
这篇关于php - YII2默认的密码加密方式是什么?怎么改成BCrypt加密?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文