spoova / hasher
支持多种哈希算法的数据哈希包
README
Hasher 是一个 PHP 包,通过结合不同的哈希算法,以特定次数生成动态或静态哈希。
初始化类
hasher 类可以通过以下方式实例化
include_once 'vendor/autoload.php' use Spoova/Hasher/Hasher; $Hasher = new Hasher;
定义哈希数据
可以通过使用以下语法通过 setHash()
方法定义要哈希的数据
$Hasher->setHash($data, $key);
$data
: 要哈希的数据$key
: 可选的秘密密钥。
以下是一个要哈希的数据示例
$Hasher->setHash(['name' => 'foo'], 'some_secret_key');
定义哈希算法
使用 hashFunc
方法来定义用于哈希数据的哈希算法。例如,在 setHash()
方法之后,我们可以提供以下算法列表
$Hasher->hashFuncs(['md5', 'sha1', 'base64_encode']);
在上面的代码中,每个函数都将用于哈希 setHash()
方法中指定的数据
处理并获得静态哈希数据
为了执行哈希并获取哈希数据,需要调用 hashify()
方法。该方法将执行并返回哈希数据。
处理并返回哈希数据
$hash = $Hasher->hashify(); //process and return hash
hashify()
方法还接受一个整数参数,这使得可以在指定的次数内执行哈希。
$hash = $Hasher->hashify(7); //run hashing 7 times
处理并获得动态哈希数据
虽然 hashify()
方法默认返回静态哈希数据,但可以通过 randomize()
方法指定为动态。这意味着当调用 hashify()
方法时,将生成不同的哈希数据。
从指定数据生成随机哈希
$Hasher->randomize(); $hash = $Hasher->hashify();
使用动态函数生成随机哈希
$Hasher->randomize(time()); $hash = $Hasher->hashify();
hashify 的行为模式
hashify 函数跟踪其最后状态,并在被调用时生成一个新的哈希。这意味着每次调用
hashify()
方法时,都会从其最后状态生成新的哈希数据。例如
$hash1 = $Hasher->hashify(); //new hash one $hash2 = $Hasher->hashify(); //new hash two $hash3 = $Hasher->hashify(); //new hash three $hash4 = $Hasher->hashify(0); //new hash one (reset hash) $hash5 = $Hasher->hashify(); //new hash two
在上面的代码中,hashify 将继续生成新的数据,直到通过向 hashify 方法提供零(0)作为参数来重启哈希节点。一旦哈希节点重启,返回的数据将是第一次哈希,后续的调用将反映其之前的模式。然而,我们可以尝试通过提供的参数来具体指定调用次数。例如
$hash1 = $Hasher->hashify(); //new hash one $hash2 = $Hasher->hashify(); //new hash two $hash3 = $Hasher->hashify(); //new hash three $hash4 = $Hasher->hashify(3); //new hash three
在上面的代码中,
$hash4
数据将记录为与$hash3
相同的数据。这是因为$hash3
包含了在三次成功的 hashify 调用后返回的数据。这些数据与$hash4
中提供的参数次数完全匹配。这意味着我们不必连续四次运行没有参数的hashify()
,而可以轻松地提供特定的哈希次数作为参数,并返回相应的数据。此外,为了防止hashify
不断变化,提供的第一个参数必须为 false,如下所示
$hash1 $Hasher->hashify(); //new hash one $hash2 $Hasher->hashify(); //new hash twp $hash3 $Hasher->hashify(false); //same as hash one above
hashify 函数还假设一个哈希函数列表,如果提供了数组,则覆盖任何默认声明的函数
$hash = $Hasher->hashify(['md5', 'sha']);
在提供两个参数的情况下,第一个必须是整数或布尔值,而第二个数组参数应包含哈希算法。例如
$hash = $Hasher->hashify(false, ['md5', 'sha']);
生成独立的随机哈希
其他随机哈希可以通过randomHash()
方法独立生成。此方法是一个独立的方法,其功能不依赖于任何其他方法。
生成特定长度的字符随机哈希
$hash = $Hasher->randomHash(10); //random hash string of 10 characters
使用特定字符范围的特定长度生成随机哈希
$hash = $Hasher->randomHash(10, 'foo'); //random hash string of 10 characters using characters in 'foo' only
使用指定的算法生成随机哈希。注意,哈希长度只能由最后一个使用的算法指定,因此长度不适用。
$hash = $Hasher->randomHash("", 'foo', ['md5','sha1']); //random hash of 'foo' using specified functions.