# 哈希
Laravel`Hash`[facade](https://laravel-china.org/docs/laravel/5.7/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)(Argon2i and Argon2id variants)。
> {note} Argon2i 驅動程序需要 PHP 7.2.0 或更高版本并且 Argon2id 驅動程序需要 PHP 7.3.0 或更高版本。
## 基本用法
你可以通過調用`Hash`facade 的`make`方法來加密你的密碼:
~~~php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Controller;
class UpdatePasswordController extends Controller
{
/**
* 更新用戶密碼。
*
* @param Request $request
* @return Response
*/
public function update(Request $request)
{
// 驗證新的密碼長度
$request->user()->fill([
'password' => Hash::make($request->newPassword)
])->save();
}
}
~~~
#### 調整 Bcrypt 加密系數
如果使用 Bcrypt 算法,你可以在`make`方法中使用`rounds`選項來管理該算法的加密系數。然而,對大多數應用程序來說,默認值就足夠了:
~~~php
$hashed = Hash::make('password', [
'rounds' => 12
]);
~~~
#### 調整 Argon2 加密系數
如果使用 Argon2 算法,你可以在`make`方法中使用`memory`,`time`和`threads`選項來管理該算法的加密系數。然而,對大多數應用程序來說,默認值就足夠了:
~~~php
$hashed = Hash::make('password', [
'memory' => 1024,
'time' => 2,
'threads' => 2,
]);
~~~
> {tip} 有關這些選項的更多信息,請查閱[PHP 官方文檔](http://php.net/manual/en/function.password-hash.php).
#### 密碼哈希驗證
`check`方法能為你驗證一段給定的未加密字符串與給定的哈希串是否一致。然而,如果你使用[Laravel 內置的](https://laravel-china.org/docs/laravel/5.7/authentication)`LoginController`控制器,你可能不需要直接使用這個方法,因為該控制器會自動調用這個方法:
~~~php
if (Hash::check('plain-text', $hashedPassword)) {
// 密碼匹配
}
~~~
#### 檢查密碼是否需要重新哈希
`needsRehash`方法可以幫你確定當哈希的加密系數改變時,你的密碼是否被新的加密系數重新加密過。
~~~php
if (Hash::needsRehash($hashed)) {
$hashed = Hash::make('plain-text');
}
~~~