哈希


介绍

Laravel的 Hash 门面 为存储用户密码提供了安全的 Bcrypt 和 Argon2 哈希。如果你是使用 Laravel 应用入门套件之一,那么默认的注册和认证会使用 Bcrypt。

Bcrypt 是散列密码的好选择,因为它的 "工作因子" 可调,这意味着随着硬件功率的增加,生成哈希的时间可以增加。散列密码, 慢是好的。算法哈希密码的时间越长,恶意用户生成可能用于对应用程序的暴力攻击的所有可能字符串哈希值的 "彩虹表" 的时间就越长。

配置

在你的应用程序的 config/hashing.php 配置文件中,配置了默认的哈希驱动。目前支持的驱动有: BcryptArgon2 (Argon2i 和 Argon2id 变体)。

基本用法

哈希密码

你可以通过在 Hash 门面上调用 make 方法来哈希一个密码:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class PasswordController extends Controller
{
    /**
     * Update the password for the user.
     */
    public function update(Request $request): RedirectResponse
    {
        // Validate the new password length...
        $request->user()->fill([
            'password' => Hash::make($request->newPassword)
        ])->save();
        return redirect('/profile');
    }
}

调整 Bcrypt 的工作因子

如果你使用 Bcrypt 算法, make 方法允许你使用 rounds 选项管理算法的工作因子; 但是, Laravel 管理的默认工作因子对大多数应用来说都是可以接受的:

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

调整 Argon2 的工作因子

如果你使用 Argon2 算法, make 方法允许你使用 memory, time, threads 选项管理算法的工作因子; 然而, Laravel 管理的默认值对于大多数应用来说是可以接受的:

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

注意
有关这些选项的更多信息,请参考关于 Argon 哈希的 官方 PHP 文档

确认密码与哈希值是否匹配

Hash 门面提供的 check 方法允许你验证一个给定的明文字符串是否对应一个给定的哈希:

if (Hash::check('plain-text', $hashedPassword)) {
    // The passwords match...
}

判断密码是否需要重新哈希

Hash 门面提供的 needsRehash 方法允许你判断自密码被哈希以来,哈希的工作因子是否已经发生改变。一些应用程序选择在应用程序的认证过程中执行此检查:

if (Hash::needsRehash($hashed)) {
    $hashed = Hash::make('plain-text');
}

点赞 取消点赞 收藏 取消收藏

<< 上一篇: 加密

>> 下一篇: 密码重置