lablnet / hashing
PHP 哈希包。
1.0.1
2019-02-06 08:16 UTC
This package is auto-updated.
Last update: 2024-09-07 00:37:41 UTC
README
此包提供了安全bcrypt和Argon2哈希算法,用于存储用户密码。
要求
- PHP 7(推荐7.3)。
- Composer。
Argon2i驱动程序需要PHP 7.2.0或更高版本,Argon2id驱动程序需要PHP 7.3.0或更高版本。
Bcrypt是加密密码的一个很好的选择,因为它的“工作因子”是可调节的,这意味着随着硬件功率的增加,生成哈希值所需的时间可以增加。
安装
安装此包非常简单,首先确保您有正确的PHP版本和已安装composer,然后在您的终端/命令提示符中运行:composer require lablnet/hashing
基本用法
您可以通过在哈希类上调用make方法来对密码进行哈希处理
<?php use Lablnet\Hashing; require '../vendor/autoload.php'; $hashing = new Hashing(); //Original password $password = 123456; //Hash the password $password_hash = $hashing->make($password); echo $password_hash;
调整Bcrypt工作因子
如果您使用Bcrypt算法,make方法允许您使用cost选项来管理算法的工作因子
$hashing = new Hashing('bcrypt'); $password_hash = $hashing->make($password, [ 'cost' => 12 ]);
调整Argon2工作因子
如果您使用Argon2I或Argon2Id算法,make方法允许您使用内存、时间和线程选项来管理算法的工作因子
$hashing = new Hashing('argon2i'); $password_hash = $hashing->make($password, [ 'memory' => 1024, 'time' => 2, 'threads' => 2, ]);
有关这些选项的更多信息,请参阅官方PHP文档。
验证密码与哈希值
verify方法允许您验证给定的明文字符串是否与给定的哈希值相对应
if ($hashing->verify($password,$password_hash)) { //The password matched. }
检查密码是否需要重新哈希
needsRehash函数允许您确定自密码被哈希处理后,哈希中使用的工作因子是否已更改
if ($hashing->needsRehash($hashed)) { $password_hash = $hashing->make($password); }
支持的算法
在这个库中,支持三种算法
- Bcrypt
- Argon2I
- Argon2ID
算法之间切换
$hashing = new Hashing('supported-algorithm'); $bvcryptHashing = new Hashing('bcrypt');
默认工作因子
您可以提供默认工作因子,如下所示
//Argon2 $argon2Hashing = new Hashing('argon2i',[ 'memory' => 1024, 'time' => 2, 'threads' => 2, 'verify' => false, ]); //Bcrypt $vcryptHashing = new Hashing('bcrypt'[ 'cost' => 12, 'verify' => false, ]);
这里,verify选项是附加的,表示如果设置为true,则算法也会在验证时进行粘性检查;如果两种算法都不匹配,则表示密码不正确。