You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
45 lines
1.3 KiB
PHTML
45 lines
1.3 KiB
PHTML
|
2 months ago
|
<?php
|
||
|
|
|
||
|
|
namespace App\Utils;
|
||
|
|
|
||
|
|
use App\Services\Config;
|
||
|
|
|
||
|
|
class Hash
|
||
|
|
{
|
||
|
|
public static function passwordHash($str)
|
||
|
|
{
|
||
|
|
$error = self::newPasswordError($str);
|
||
|
|
if ($error !== null) {
|
||
|
|
throw new \InvalidArgumentException($error);
|
||
|
|
}
|
||
|
|
|
||
|
|
return password_hash($str, PASSWORD_BCRYPT, ['cost' => 12]);
|
||
|
|
}
|
||
|
|
|
||
|
|
public static function cookieHash($str)
|
||
|
|
{
|
||
|
|
return substr(hash('sha256', $str.Config::get('key')), 5, 45);
|
||
|
|
}
|
||
|
|
|
||
|
|
public static function newPasswordError($password)
|
||
|
|
{
|
||
|
|
if (!is_string($password) || strlen($password) < 12 || strlen($password) > 72
|
||
|
|
|| strpos($password, "\0") !== false
|
||
|
|
|| preg_match('/[A-Z]/', $password) !== 1
|
||
|
|
|| preg_match('/[a-z]/', $password) !== 1
|
||
|
|
|| preg_match('/[0-9]/', $password) !== 1
|
||
|
|
|| preg_match('/[^A-Za-z0-9\s]/', $password) !== 1) {
|
||
|
|
return '密码需为 12 至 72 字节,包含大写字母、小写字母、数字和符号。';
|
||
|
|
}
|
||
|
|
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
|
||
|
|
public static function checkPassword($hashedPassword, $password)
|
||
|
|
{
|
||
|
|
return is_string($hashedPassword) && is_string($password)
|
||
|
|
&& strlen($password) <= 72 && strpos($password, "\0") === false
|
||
|
|
&& password_verify($password, $hashedPassword);
|
||
|
|
}
|
||
|
|
}
|