Laravel 用多少 cost/rounds 来哈希?

How much cost/rounds does Laravel use to hash with?

我试图从 BcryptHasher.php 文件中的 Laravel 4.2 了解以下函数的工作原理:

/**
     * Hash the given value.
     *
     * @param  string  $value
     * @param  array   $options
     * @return string
     *
     * @throws \RuntimeException
     */
    public function make($value, array $options = [])
    {
        $cost = isset($options['rounds']) ? $options['rounds'] : $this->rounds;

        $hash = password_hash($value, PASSWORD_BCRYPT, ['cost' => $cost]);

        if ($hash === false) {
            throw new RuntimeException('Bcrypt hashing not supported.');
        }

        return $hash;
    }

我想我明白除了这行以外的所有内容:

$cost = isset($options['rounds']) ? $options['rounds'] : $this->rounds;

我知道 $this->rounds 的默认值设置为 10,这就是密码将被散列的 "cost"。但是,我对 $options 数组在做什么以及它如何影响成本感到困惑?

你可以在调用make方法时传入options。

例如使用门面:

$hashed = Hash::make($value, ['rounds' => 8]);

如果你不传入cost,它将使用$this->rounds,即10

在 laravel 5.5 和之前,因为散列轮数在这些版本中是硬编码的,所以没有办法,除非您构建一个门面或服务来根据您的需要和处理默认散列轮数然后使用包装器 class 而不是原始哈希 class.

但是,由于 laravel 5.6,默认的哈希轮数存储在 config/hashing.php 文件中,您可以使用此部分或设置 BCRYPT_ROUNDS 将默认值更改为您想要的值.env 文件中的环境变量。

/*
|--------------------------------------------------------------------------
| Bcrypt Options
|--------------------------------------------------------------------------
|
| Here you may specify the configuration options that should be used when
| passwords are hashed using the Bcrypt algorithm. This will allow you
| to control the amount of time it takes to hash the given password.
|
*/

'bcrypt' => [
    'rounds' => env('BCRYPT_ROUNDS', 10),
],