码迷,mamicode.com
首页 > 其他好文 > 详细

签名服务

时间:2018-10-11 20:04:51      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:php   验证   int   name   ring   unset   create   fun   str   

<?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);

签名服务

标签:php   验证   int   name   ring   unset   create   fun   str   

原文地址:http://blog.51cto.com/phpme/2298934

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!