加盐签名和解密签名的函数
一般用于两个系统之间,共同持有相同salt的时候使用。
/**
* 加盐签名
* @uses CommonLogic::ensign(['aaa'=>123,'bbb'=>'efg']);
* @param array $params 参数
* @return array 参数多了个signature
*/
public static function ensign(array $params)
{
$salt = config('custom.default.project_salt');
$authorized = [
//'basework_appkey' => $appkey,
'timestamp' => microtime(true),
'datetime' => date('Y-m-d H:i:s'),
'formater' => 'json',
'signtype' => 'md5',
'version' => '1.0.0',
];
$authorized = ['authorized'=>json_encode($authorized)];
$params = array_merge($authorized,$params);//halt($params);
ksort($params);//halt($params);
$str = '';
foreach ($params as $k => $v) {
$str .= $k . $v;
}//halt($str);
$signature = md5($salt . $str . $salt);//halt($sign);
$params['signature'] = strtoupper($signature);
return $params;
}
/**
* 加盐解签
* @uses CommonLogic::design($result)
* @param $params 入参
* @return bool 布尔值
*/
public static function design($params): bool
{
if (!isset($params['signature'])) {
return false;
}//halt($params);
$signature = $params['signature'];
unset($params['signature']);//halt($sign);
$result = self::ensign($params);
if ($signature === $result['signature']) {
return true;
}
return false;
}
或者直接使用base64全串加解密:
/**
* 加盐签名
* @param array $params 参数
* @return array 参数多了个signature
* @uses CommonLogic::ensign(['aaa'=>123,'bbb'=>'efg']);
*/
public static function ensign(array $params)
{
$salt = config('custom.default.project_salt');//粤盐集团
$result = ['auth' => [], 'params' => [], 'sign' => ''];//结果
ksort($params);//halt($params);
$str = '';
foreach ($params as $k => $v) {
$str .= $k . $v;
}//halt($str);
$result['params'] = $params;
$result['auth'] = ['t' => microtime(true), 'v' => '1.0.0'];
$result['sign'] = md5($salt . $str . json_encode($result['auth']));
//halt($result);
return base64_encode(json_encode($result));
}
/**
* 加盐解签
* @param $params 入参
* @return bool 布尔值
* @uses CommonLogic::design($result)
*/
public static function design($result): array
{
$result = json_decode(base64_decode($result), true);//halt($result);
if (!isset($result['auth']) or !isset($result['auth']['t']) or !isset($result['auth']['v'])) {
throw new ValidateException('auth construct error');
}//halt($params);
if (!isset($result['params'])) {
throw new ValidateException('params construct error');
}
if (!isset($result['sign']) or strlen($result['sign']) != 32) {
throw new ValidateException('sign construct error');
}
$auth = $result['auth'];
$params = $result['params'];
$sign = $result['sign'];
//超过5分钟算失效
if (!is_numeric($auth['t']) or $auth['t'] < time() - 300) {
throw new ValidateException('auth t expire');
}
$salt = config('custom.default.project_salt');//粤盐集团
ksort($params);//halt($params);
$str = '';
foreach ($params as $k => $v) {
$str .= $k . $v;
}//halt($str);
$signCalc = md5($salt . $str . json_encode($auth));
if ($signCalc === $sign) {
return $params;
}
return [];
}