Files
hyperf_service/app/Lib/Crypto/JwtCrypto.php
2024-10-27 19:34:20 +08:00

95 lines
1.9 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* This lib file is part of item.
*
* @author ctexthuang
* @contact ctexthuang@qq.com
*/
declare(strict_types=1);
namespace App\Lib\Crypto;
use Exception;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use function Hyperf\Config\config;
class JwtCrypto implements CryptoInterface
{
/**
* 加密数据
* @var string
*/
public string $data = '';
/**
* 登录类型
* @var string
*/
public string $type = '';
/**
* 加密 key
* @var string
*/
private string $key;
/**
* 加密过期时间
* @var int
*/
private int $expire;
/**
* 构造函数 获取配置
*/
public function __construct()
{
$this->key = config('system.jwt_key');
}
/**
* jwt 加密
* @return string
*/
public function encrypt(): string
{
switch ($this->type) {
case 'admin-jwt':
$this->expire = (int)config('system.admin_jwt_expire');
break;
default:
case 'jwt':
$this->expire = (int)config('system.jwt_expire');
break;
}
try {
$time = time();
$payload = [
'iat' => $time, //签发时间
'nbf' => $time, //(Not Before)某个时间点后才能访问比如设置time+30表示当前时间30秒后才能使用
'exp' => $time + $this->expire,
'data' => json_decode($this->data,true),
];
return JWT::encode($payload, $this->key,'HS256');
} catch (Exception) {
return '';
}
}
/**
* jwt 解密
* @return array
*/
public function decrypt(): array
{
try {
return (array)JWT::decode($this->data, new Key($this->key, 'HS256'));
} catch (Exception) {
return [];
}
}
}