80 lines
1.6 KiB
PHP
80 lines
1.6 KiB
PHP
<?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 = '';
|
||
|
||
/**
|
||
* 加密 key
|
||
* @var string
|
||
*/
|
||
private string $key;
|
||
|
||
/**
|
||
* 加密过期时间
|
||
* @var int
|
||
*/
|
||
private int $expire;
|
||
|
||
/**
|
||
* 构造函数 获取配置
|
||
*/
|
||
public function __construct()
|
||
{
|
||
$this->key = config('system.jwt_key');
|
||
$this->expire = (int)config('system.jwt_expire');
|
||
}
|
||
|
||
/**
|
||
* jwt 加密
|
||
* @return string
|
||
*/
|
||
public function encrypt(): string
|
||
{
|
||
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 [];
|
||
}
|
||
}
|
||
} |