php - YII2默认的密码加密方式是什么?怎么改成BCrypt加密?

 浪迹天涯沃热尔_441 发布于 2022-11-16 10:15

因为Laravel5的密码默认加密方式是bcrypt,希望让YII2也使用这种加密方式,怎么做?Google都难找到资料。

2 个回答
  •  /**
         * @var string strategy, which should be used to generate password hash.
         * Available strategies:
         * - 'password_hash' - use of PHP `password_hash()` function with PASSWORD_DEFAULT algorithm.
         *   This option is recommended, but it requires PHP version >= 5.5.0
         * - 'crypt' - use PHP `crypt()` function.
         * @deprecated Since version 2.0.7, [[generatePasswordHash()]] ignores [[passwordHashStrategy]] and
         * uses `password_hash()` when available or `crypt()` when not.
         */
     
     也就说在2.0.7之后就默认会使用`password_hash`,如果不存在此方法会使用`crypt`
    2022-11-16 10:57 回答
  • 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);
    }
    2022-11-16 10:57 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有