扫码一下
查看教程更方便
laravel hash facade
提供了安全bcrypt
和argon2
哈希函数来存储用户密码。如果使用的是laravel应用程序自带的内置logincontroller
和registercontroller
类,则默认情况下它们将使用bcrypt
进行注册和身份验证。
bcrypt是散列密码的绝佳选择,因为它的“work 因子”是可调的,这意味着随着硬件能力的提高,生成散列所花费的时间可以增加。
在config/hashing.php
配置文件中配置了应用程序的默认哈希驱动程序。当前支持三种驱动程序:bcrypt
和argon2
(argon2i和argon2id变体)。
argon2i
驱动程序需要php 7.2.0或更高版本,而argon2id
驱动程序需要php 7.3.0或更高版本。
我们可以通过调用hash facade的make方法来对密码进行哈希处理:
user()->fill([
'password' => hash::make($request->newpassword)
])->save();
}
}
如果使用的是bcrypt算法,则make方法允许使用rounds选项管理算法的工作因数;但是,大多数应用程序是使用默认值的,不用改变这个系数:
$hashed = hash::make('password', [
'rounds' => 12,
]);
如果使用的是argon2
算法,make方法允许使用memory、time和threads来控制算法的工作因子; 但是,大多数应用程序使用默认值:
$hashed = hash::make('password', [
'memory' => 1024,
'time' => 2,
'threads' => 2,
]);
有关这些选项的更多信息,请查阅。
check方法使我们可以验证给定的纯文本字符串是否与给定的哈希相对应。但是,如果使用的是laravel自带的控制器logincontroller
,则可能不需要直接使用check方法,因为此控制器会自动调用此方法:
if (hash::check('plain-text', $hashedpassword)) {
// the passwords match...
}
needsrehash
函数允许我们确定自哈希密码生成以来哈希器使用的工作因子是否已更改:
if (hash::needsrehash($hashed)) {
$hashed = hash::make('plain-text');
}