企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
* * * * * [TOC] ## 简介 Laravel `Hash` [facade](https://www.kancloud.cn/tonyyu/laravel_5_6/786058) 为存储用户密码提供了安全的 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` 方法来填写密码: ~~~ <?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 加密系数 `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 自带的 ](https://www.kancloud.cn/tonyyu/laravel_5_6/786216)控制器,你可能不需要直接使用这个方法,因为该控制器会自动调用这个方法: ~~~ if (Hash::check('plain-text', $hashedPassword)) { // 密码匹配 } ~~~ #### 检验密码是否需要重新哈希 `needsRehash` 方法可以帮你确定当密码被哈希时,被哈希计算器使用的加密系数是否发生变化: ~~~ if (Hash::needsRehash($hashed)) { $hashed = Hash::make('plain-text'); } ~~~