哈希
哈希
哈希加密
簡(jiǎn)介
Laravel Hash
facade 為存儲(chǔ)用戶密碼提供了安全的 Bcrypt 和 Argon2 哈希加密方式。如果你在你的 Laravel 應(yīng)用程序中使用了內(nèi)置的 LoginController
和 RegisterController
類,那么它們默認(rèn)使用 Bcrypt 進(jìn)行注冊(cè)和身份認(rèn)證。
{tip} Bcrypt 是哈希密碼的理想選擇,因?yàn)樗?「加密系數(shù)」 可以任意調(diào)整,這意味著生成哈希所需的時(shí)間可以隨著硬件功率的增加而增加。
配置
你可以在 config/hashing.php
配置文件中配置默認(rèn)哈希驅(qū)動(dòng)程序。目前支持三種驅(qū)動(dòng)程序:Bcrypt 和 Argon2 (Argon2i and Argon2id variants)。
{note} Argon2i 驅(qū)動(dòng)程序需要 PHP 7.2.0 或更高版本,而 Argon2id 驅(qū)動(dòng)程序則需要 PHP 7.3.0 或更高版本。
基本用法
你可以通過調(diào)用 Hash
facade 的 make
方法來加密你的密碼:
<?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) { // 驗(yàn)證新密碼的長(zhǎng)度 $request->user()->fill([ 'password' => Hash::make($request->newPassword) ])->save(); } }
調(diào)整 Bcrypt 加密系數(shù)
如果使用 Bcrypt 算法,你可以在 make
方法中使用 rounds
選項(xiàng)來配置該算法的加密系數(shù)。然而,對(duì)大多數(shù)應(yīng)用程序來說,默認(rèn)值就足夠了:
$hashed = Hash::make('password', [ 'rounds' => 12 ]);
調(diào)整 Argon2 加密系數(shù)
如果使用 Argon2 算法,你可以在 make
方法中使用 memory
, time
和 threads
選項(xiàng)來配置該算法的加密系數(shù)。然后,對(duì)大多數(shù)應(yīng)用程序來說,默認(rèn)值就足夠了:
$hashed = Hash::make('password', [ 'memory' => 1024, 'time' => 2, 'threads' => 2, ]);
{tip} 有關(guān)這些選項(xiàng)的更多信息,請(qǐng)查閱 PHP 官方文檔。
密碼哈希驗(yàn)證
check
方法能為您驗(yàn)證一段給定的未加密字符串與給定的哈希值是否一致。然而,如果您使用 Laravel 內(nèi)置的 LoginController
控制器,您可能不需要直接使用這個(gè)方法,因?yàn)樵摽刂破鲿?huì)自動(dòng)調(diào)用這個(gè)方法:
if (Hash::check('plain-text', $hashedPassword)) { // 密碼匹配 }
檢查密碼是否需要重新哈希
needsRehash
方法可以為您檢查當(dāng)哈希的加密系數(shù)改變時(shí),您的密碼是否被新的加密系數(shù)重新加密過:
if (Hash::needsRehash($hashed)) { $hashed = Hash::make('plain-text'); }