1、密钥设置
public $secretKey = 'hgakdfkljalfdjlk';//私钥
public $termValidity = 60;//有效时常(秒)
2、调用方式
$info = ['user_id' => 1];
//生成密钥
$this->CreateToken( $info);
//校验密钥
$this->CheckToken($token);
3、基础方法
/**
*功能:生成token
*参数一:需要解密的密文
*参数二:密钥
*/
function CreateToken($data = []) {
if(empty($data)){
$data['code'] = '400';
$data['message'] = '非法请求';
return $data;
}
$data['request_time'] = time();//当前时间
$data['term_validity'] = $this->termValidity;//过期时间
$dataJson = json_encode( $data );
//根据以上信息信息生成签名
return $this->passport_encrypt($dataJson, $this->secretKey);
}
/**
*功能:校验token
*参数一:需要解密的密文
*参数二:密钥
*/
function CheckToken($token) {
if (!isset($token) || empty($token)) {
$data['code'] = '400';
$data['message'] = '非法请求';
return $data;
}
$explode =$this->passport_decrypt($token, $this->secretKey); //解析token
$expArr = json_decode($explode,true);
$checkToken = $this->passport_encrypt(json_encode($expArr), $this->secretKey);
$requestTime = $expArr['request_time'];
$termValidity = $expArr['term_validity'];
$checkTime = $requestTime+$termValidity;
//对比token
if($token != $checkToken){
$data['code'] = '400';
$data['message'] = '非法请求';
return $data;
}
$time = time();
if ($time > $checkTime) {
$data['code'] = '401';
$data['message'] = 'Token已过期,请重新登录';
return $data;
}
$data['code'] = '200';
$data['message'] = '合法Token';
return $data;
}
/*
*功能:对字符串进行加密处理
*参数一:需要加密的内容
*参数二:密钥
*/
function passport_encrypt($str,$key = 'secretKey'){ //加密函数
return base64_encode($this->passport_key($str,$key));
}
/*
*功能:对字符串进行解密处理
*参数一:需要解密的密文
*参数二:密钥
*/
function passport_decrypt($str,$key = 'secretKey'){ //解密函数
return $this->passport_key(base64_decode($str),$key);
}
/*
*辅助函数
*/
function passport_key($str,$encrypt_key){
$encrypt_key=md5($encrypt_key);
$ctr=0;
$tmp='';
for($i=0;$i<strlen($str);$i++){
$ctr=$ctr==strlen($encrypt_key)?0:$ctr;
$tmp.=$str[$i] ^ $encrypt_key[$ctr++];
}
return $tmp;
}
|