簡介
Laravel 的 Hash 門面為存儲(chǔ)用戶密碼提供了安全的 Bcrypt 哈希。如果你是使用內(nèi)置的 LoginController 和 ReginsterController 類來構(gòu)建認(rèn)證系統(tǒng)的,那么你的用戶密碼在注冊(cè)和認(rèn)證過程中已經(jīng)自動(dòng)使用了 Bcrypt 。
提示:Bcrypt 是哈希加密的理想選擇,因?yàn)樗?「影響因子」 是可調(diào)整的,這就是說明生成哈希的時(shí)間可以隨硬件功率的增加而增加的。
基本用法
你可以通過 Hash 門面的 make 方法來哈希一個(gè)明文密碼。
<? php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Controller;
class UpdatePasswordController extends Controller
{
/**
* Update the password for the user.
*
* @param Request $request
* @return Response
*/
public function update(Request $request)
{
// Validate the new password length
$request->user()->fill([
'password' => Hash::make($request->newPassword)
])->save();
}
}
make 方法允許你使用 rounds 選項(xiàng)來管理 bcrypt 哈希算法的影響因子;然而,使用 make 方法的默認(rèn)值,已經(jīng)足夠了。
$hashed = Hash::make('password', [
'rounds' => 12
]);
比對(duì)哈希值和文本字符
check 方法用來驗(yàn)證給定的純文本字符串是否能對(duì)應(yīng)到給定的一個(gè)哈希值。如果你使用的是 Laravel 內(nèi)置的 LoginController 了,你已經(jīng)在使用它了。
if(Hash::check('plain-text', $hashedPassword)){
// The passwords match ....
}
檢查密碼是否需要重新加密
if(Hash::needsRehash($hashed)){
$hashed = Hash::make('plain-text');
}