<?php
/**
 * Created by PhpStorm.
 * User: zrj
 * Date: 18-10-11
 * Time: 上午11:44
 */

namespace App\Http\Services;

trait SignatureService
{
    public static $requestParamArr = [];

    /**
     * 初始化服务
     * @param array $requestParamArr
     * @return mixed
     */
    public static function init(array $requestParamArr)
    {
        self::$requestParamArr = $requestParamArr;
    }

    /**
     * 校验请求参数
     * @param array $requestParamArr
     * @param bool $isInit
     * @return array
     */
    public static function validateQueryParam(array $requestParamArr = [], bool $isInit = true): array
    {
        try {
            if (empty($requestParamArr)) {
                $requestParamArr = self::$requestParamArr;
            }

            if (!isset($requestParamArr['sign_type'])) throw new \Exception('缺少签名类型参数');
            if (!in_array($requestParamArr['sign_type'], ['MD5', 'HMAC-SHA256'])) throw new \Exception('签名类型错误');
            if (!isset($requestParamArr['timestamp'])) throw new \Exception('缺少时间戳参数');
            if (empty($requestParamArr['timestamp'])) throw new \Exception('时间戳不能为空');
            if (!isset($requestParamArr['nonce_str'])) throw new \Exception('缺少随机字符串参数');
            if (empty($requestParamArr['nonce_str'])) throw new \Exception('随机字符串不能为空');

            if (!$isInit) {
                if (!isset($requestParamArr['key'])) throw new \Exception('缺少密钥参数');
                if (empty($requestParamArr['key'])) throw new \Exception('密钥不能为空');
                if (!isset($requestParamArr['signature'])) throw new \Exception('缺少签名参数');
                if (empty($requestParamArr['signature'])) throw new \Exception('签名不能为空');
            }

            return ['status' => 1, 'data' => [], 'message' => ''];
        } catch (\Exception $e) {
            return ['status' => 0, 'data' => [], 'message' => $e->getMessage()];
        }
    }

    /**
     * 产生随机字符串,不长于32位
     * @param int $length
     * @return string
     */
    public static function createNonceStr(int $length = 32): string
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 产生请求参数的排序后的字符串
     * @param array $requestParamArr
     * @return string
     */
    public static function createSortQueryString(array $requestParamArr): string
    {
        if (isset($requestParamArr['key'])) unset($requestParamArr['key']);
        if (isset($requestParamArr['signature'])) unset($requestParamArr['signature']);

        ksort($requestParamArr);
        return http_build_query($requestParamArr);
    }

    /**
     * 创建签名串
     * @param string $sortQueryString 排序字符串
     * @param string $signType 签名类型:MD5;HMAC-SHA256;
     * @param string $key
     * @return string
     * @throws \Exception
     */
    public static function createSignatureString(string $sortQueryString, string $signType, string $key): string
    {
        $returnStr = '';
        if ($signType == 'MD5') {
            $sortQueryString .= '&key=' . $key;
            $returnStr = md5($sortQueryString);
        } elseif ($signType == 'HMAC-SHA256') {
            $returnStr = hash_hmac('sha256', $sortQueryString, $key);
        } else {
            throw new \Exception('签名类型不支持');
        }
        return $returnStr;
    }

    /**
     * 验证外部请求
     * @param array $originRequestParamArr
     * @return array
     */
    public static function validateRequest(array $originRequestParamArr): array
    {
        try {
            $validate = self::validateQueryParam($originRequestParamArr, false);
            if (!$validate['status']) throw new \Exception($validate['message']);
            $now = time();
            if (($now - $originRequestParamArr['timestamp']) > 15) throw new \Exception('请求时间异常');

            $signType = $originRequestParamArr['sign_type'];
            $originKey = $originRequestParamArr['key'];
            $originSignature = $originRequestParamArr['signature'];
            unset($originRequestParamArr['key'], $originRequestParamArr['signature']);

            $newSignature = self::createSignatureString(self::createSortQueryString($originRequestParamArr), $signType, $originKey);
            if ($originSignature != $newSignature) throw new \Exception('签名错误');

            return ['status' => 1, 'data' => [], 'message' => ''];
        } catch (\Exception $e) {
            return ['status' => 0, 'data' => [], 'message' => $e->getMessage()];
        }
    }
}

使用

//生成签名
$request = [
                'a' => 1,
                'b' => 2,
                'c' => 3,

                'sign_type' => 'HMAC-SHA256',
                'timestamp' => time() + 600,
                'nonce_str' => SignatureService::createNonceStr(),
        ];

            SignatureService::init($request);

            $result = SignatureService::validateQueryParam();

            if (!$result['status']) exit($result['message']);

            $key = 'helloworld';
            $signature = SignatureService::createSignatureString(SignatureService::createSortQueryString($request), $request['sign_type'], $key);
            $request['key'] = $key;
            $request['signature'] = $signature;

            echo "<pre>";
            print_r($request);

            //校验签名
            $validate = SignatureService::validateRequest($request, false);

必要参数:

  • 'sign_type' => 'HMAC-SHA256', //签名类型,当前支持SHA256、MD5
  • 'timestamp' => '1539255134', //时间戳
  • 'nonce_str' => 'n5ryqp0f9ur3u3u8lxfblxw9h03emyka',//随机数
  • 'key' => 'helloworld', //密钥
  • 'signature' => 'f0ca487612f15059c47aba5e8503c6400981fbed20d1af958003e3f798d1bbd2',//签名