雜湊

簡介

Laravel 的 Hash Facade 提供了安全的 Bcrypt 與 Argon2 雜湊,用以儲存使用者密碼。若使用 Laravel 專案入門套件,則預設會使用 Bcrypt 來註冊與登入。

Bcrypt 是雜湊密碼的一個不錯的選擇,因為其「Work Factor(工作因)」是可調整的,這表示,隨著硬體功能的提升,我們也能調整產生雜湊所需的時間。在雜湊密碼時,慢即是好。若演算法需要更多的時間來雜湊密碼,惡意使用者要產生「彩虹表(Rainbow Table)」的時間也就更長。彩虹表是一個包含各種可能字串雜湊值的表格,可用來暴力破解密碼。

設定

專案中預設的雜湊 Driver 設定在專案的 config/hashing.php 設定檔中。目前有支援多個 Driver: BcryptArgon2 (Argon2i 與 Argon2id 變形)。

基礎用法

雜湊密碼

可以呼叫 Hash Facade 上的 make 方法來雜湊密碼:

1<?php
2 
3namespace App\Http\Controllers;
4 
5use App\Http\Controllers\Controller;
6use Illuminate\Http\Request;
7use Illuminate\Support\Facades\Hash;
8 
9class PasswordController extends Controller
10{
11 /**
12 * Update the password for the user.
13 *
14 * @param \Illuminate\Http\Request $request
15 * @return \Illuminate\Http\Response
16 */
17 public function update(Request $request)
18 {
19 // Validate the new password length...
20 
21 $request->user()->fill([
22 'password' => Hash::make($request->newPassword)
23 ])->save();
24 }
25}
1<?php
2 
3namespace App\Http\Controllers;
4 
5use App\Http\Controllers\Controller;
6use Illuminate\Http\Request;
7use Illuminate\Support\Facades\Hash;
8 
9class PasswordController extends Controller
10{
11 /**
12 * Update the password for the user.
13 *
14 * @param \Illuminate\Http\Request $request
15 * @return \Illuminate\Http\Response
16 */
17 public function update(Request $request)
18 {
19 // Validate the new password length...
20 
21 $request->user()->fill([
22 'password' => Hash::make($request->newPassword)
23 ])->save();
24 }
25}

調整 Bcrypt 的 Work Factor

若使用 Bcrypt 演算法,可使用 rounds 選項來在 make 方法中控制 Bcrypt 的 Work Factor。不過,Laravel 所控制的預設 Work Factor 對於大多數專案來說應是可接受的值:

1$hashed = Hash::make('password', [
2 'rounds' => 12,
3]);
1$hashed = Hash::make('password', [
2 'rounds' => 12,
3]);

調整 Argon2 的 Work Factor

若使用 Argon2 演算法,可使用 memorytimethreads 等選項來在 make 方法中控制 Argon2 演算法的 Work Factor。不過,Laravel 所控制的預設 Work Factor 對於大多數專案來說應是可接受的值:

1$hashed = Hash::make('password', [
2 'memory' => 1024,
3 'time' => 2,
4 'threads' => 2,
5]);
1$hashed = Hash::make('password', [
2 'memory' => 1024,
3 'time' => 2,
4 'threads' => 2,
5]);
lightbulb

有關這些選項的詳細資訊,請參考 PHP 官方說明文件中有關 Argon 雜湊的說明

驗證密碼是否符合雜湊

Hash Facade 的 check 方法可用來驗證給定的純文字字串是否對應給定的雜湊:

1if (Hash::check('plain-text', $hashedPassword)) {
2 // 密碼正確...
3}
1if (Hash::check('plain-text', $hashedPassword)) {
2 // 密碼正確...
3}

判斷密碼是否需要重新雜湊

Hash Facade 的 needsRehash 方法可用來判斷自從該密碼被雜湊以來 Hash 程式的 Work Factor 是否有經過更改。有的專案會在網站的身份驗證過程中做這項檢查:

1if (Hash::needsRehash($hashed)) {
2 $hashed = Hash::make('plain-text');
3}
1if (Hash::needsRehash($hashed)) {
2 $hashed = Hash::make('plain-text');
3}
翻譯進度
100% 已翻譯
更新時間:
2023年2月11日 上午10:27:00 [世界標準時間]
翻譯人員:
  • cornch
幫我們翻譯此頁

留言

尚無留言

“Laravel” is a Trademark of Taylor Otwell.
The source documentation is released under MIT license. See laravel/docs on GitHub for details.
The translated documentations are released under MIT license. See cornch/laravel-docs-l10n on GitHub for details.