# 哈希加密
- [简介](#introduction)
- [配置](#configuration)
- [基本用法](#basic-usage)
## 简介
Laravel `Hash` [facade](/docs/{{version}}/facades) 为存储用户密码提供了安全的 Bcrypt 和 Argon2 哈希。如果您使用 Laravel 应用程序中内置的 `LoginController` 和 `RegisterController` 类,则默认情况下它们将使用 Bcrypt 进行注册和身份验证。
> {tip} Bcrypt 是哈希密码的理想选择,因为它的「加密系数」可以任意调整,这意味着生成哈希所需的时间可以随着硬件功率的增加而增加。
## 配置
您的应用程序的默认散列驱动程序在 `config/hashing.php` 配置文件中配置。目前有两种支持的驱动程序: [Bcrypt](https://en.wikipedia.org/wiki/Bcrypt) 和 [Argon2](https://en.wikipedia.org/wiki/Argon2)。
> {note} Argon2 驱动程序需要 PHP 7.2.0 或更高版本。
## 基本用法
你可以通过调用 `Hash` Facade 的 `make` 方法来填写密码:
user()->fill([
'password' => Hash::make($request->newPassword)
])->save();
}
}
#### 调整 Bcrypt 加密系数
`make` 方法还能使用 `rounds` 选项来管理 bcrypt 哈希算法的加密系数。然而,大多数应用程序还是能接受默认值的:
$hashed = Hash::make('password', [
'rounds' => 12
]);
#### 调整 Argon2 加密系数
如果你使用 Argon2 算法,可以使用 `make` 方法中的 `memory` ,`time` 和 `threads` 选项来管理该算法的加密系数;然而,大多数应用都是可以接受默认值的:
$hashed = Hash::make('password', [
'memory' => 1024,
'time' => 2,
'threads' => 2,
]);
> {tip} 有关这些选项的更多信息,请查阅 [ PHP 官方文档 ](http://php.net/manual/en/function.password-hash.php).
#### 密码哈希验证
`check` 方法能为你验证一段给定的未加密字符串与给定的哈希串是否一致。然而, 如果你使用 `LoginController` [ Laravel 自带的 ](/docs/{{version}}/authentication) 控制器,你可能不需要直接使用这个方法,因为该控制器会自动调用这个方法:
if (Hash::check('plain-text', $hashedPassword)) {
// 密码匹配
}
#### 检验密码是否需要重新哈希
`needsRehash` 方法可以帮你确定当密码被哈希时,被哈希计算器使用的加密系数是否发生变化:
if (Hash::needsRehash($hashed)) {
$hashed = Hash::make('plain-text');
}