GmService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. <?php
  2. /**
  3. * @Author: Marte
  4. * @Date: 2017-07-31 15:26:02
  5. * @Last Modified by: Marte
  6. * 1、getPostData 获取对方发过来的请求使用此方法对获取到的数据进行解密解签后得到数据
  7. * 2、runJson 返回数据给对方使用此方法对数据进行拼接加签加密后返回
  8. * 3、getToken 获取token方法,可以自行储存在文件内重复使用,过期后再次获取
  9. * 4、postJry 业务请求数据拼接,发送请求接口
  10. * 5、cityQuery 业务请求封装
  11. * 6、decryptByPublicKey rsa解密方法
  12. * 7、encryptByPrivateKey rsa加密方法
  13. * 8、decrypt aes解密方法
  14. * 9、encrypt aes加密方法
  15. */
  16. namespace crmeb\services;
  17. use function halt;
  18. use function input;
  19. use function json;
  20. class GmService
  21. {
  22. //以下参数都需要金融云提供
  23. //AES偏移量
  24. protected static $iv = 'abcdefghABCDEFGH';
  25. protected static $appID = "3f1a51c1-39d4-48e1-8119-a37b63c0ed8c";
  26. protected static $appSecretKey = "66a81e7a-dea3-4870-9c63-58712e13aa9b";
  27. protected static $tokenUrl = "https://tlop.zjtlcb.com/api/HOGENDY";//回归环境
  28. protected static $token;
  29. //合作机构自有公钥
  30. const PUBLIC_KEY = "DE3w4DgjV+np0oHQzSDUgvlxGKPhi/gHBRp8dtjun+z6uqrRJE6B1qswZpaSCs3tp0tm98ZjjL9RTuNh4dyUuA==";
  31. //合作机构自有私钥
  32. const PRIVATE_KEY = "778NKKZgdS9IGm/crvajNPoq5CHJNEKXptciF/1SU3I=";
  33. //泰隆银行公钥
  34. const CGB_PUBLIC_KEY = "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAE6mJz31IQpqtv42a67pfUe6q6UKUa/Lxf2rzJC4iAK0p3dOooG/d+N2fs6qmzK+7smovqcP7VhA8D+OIvaVjMsw==";
  35. public static function _initialize()
  36. {
  37. // 初始化加密扩展
  38. // echo "--------php_crypto_init 初始化开始--------\n";
  39. $path = "/www/server/php/73/libcryptAPIsm_lnx64.so";
  40. php_crypto_init($path);
  41. // echo "--------php_crypto_init 初始化结束-------\n";
  42. }
  43. public static function string2hex($string)
  44. {
  45. $hex = '';
  46. for ($i = 0; $i < strlen($string); $i++) {
  47. $ch = dechex(ord($string[$i]));
  48. if (strlen($ch) == 1) {
  49. $ch = "0" . $ch;
  50. }
  51. $hex .= $ch;
  52. }
  53. return $hex;
  54. }
  55. //获取token
  56. public static function getToken()
  57. {
  58. //获取6位数字符串
  59. $seqNO = (string)rand(100000, 999999);
  60. //获取16位随机字符串并md5 转大写 得到
  61. $key = strtoupper(md5(self::getKey()));
  62. echo self::string2hex(base64_decode(self::PRIVATE_KEY));
  63. echo self::string2hex(base64_decode(self::PUBLIC_KEY));
  64. // dump($key);
  65. // exit;
  66. //初始化转换密钥信息
  67. $k1 = '';
  68. dump(function_exists('php_HextoAsc'));
  69. exit;
  70. php_HextoAsc(self::string2hex(base64_decode(self::PRIVATE_KEY)), $k1);
  71. dump($k1);
  72. exit;
  73. php_HextoAsc(self::string2hex(base64_decode(self::PUBLIC_KEY)), $k2);
  74. dump($k2);
  75. exit;
  76. php_HextoAsc(self::string2hex(base64_decode(self::CGB_PUBLIC_KEY)), $gf_k);
  77. dump($gf_k);
  78. exit;
  79. //拼接参数数组
  80. $data = [
  81. 'appID' => self::$appID,
  82. 'seqNO' => $seqNO,
  83. 'random' => strtoupper(md5($seqNO)),
  84. 'sm2EncryptData' => self::SM2Encrypt($key, $gf_k), //sm2加密key
  85. 'sm2Sign' => self::SM2Sign($key, $k2, $k1), //sm2加密key
  86. ];
  87. dump($data);
  88. exit;
  89. //拼接签名参数,md5转大写
  90. $data['sign'] = self::SM3Crypt($data['random'] . $data['seqNO'] . self::$appSecretKey . $key);
  91. dump($data);
  92. exit;
  93. //发送post接口请求
  94. $res = self::https_post(self::$tokenUrl, $data);
  95. dump($res);
  96. exit;
  97. //解密返回token数据
  98. $token = self::SM2Decrypt(base64_decode($res['sm2EncryptData']), $k1);
  99. self::$token = $token;
  100. //返回token
  101. return $token;
  102. }
  103. //业务请求数据
  104. public static function postJry()
  105. {
  106. //创建模拟请求数据,必须包含head,body
  107. $data = [
  108. 'head' => [
  109. 'id' => 8989
  110. ],
  111. 'body' => [
  112. 'code' => "000000",
  113. 'msg' => "测试请求"
  114. ]
  115. ];
  116. $res = self::scanPaymentCode($data);
  117. dump("返回结果");
  118. halt($res);
  119. }
  120. //业务请求封装
  121. public static function scanPaymentCode($array = [])
  122. {
  123. //初始化转换密钥信息
  124. php_HextoAsc(self::string2hex(base64_decode(self::PRIVATE_KEY)), $k1);
  125. php_HextoAsc(self::string2hex(base64_decode(self::PUBLIC_KEY)), $k2);
  126. php_HextoAsc(self::string2hex(base64_decode(self::CGB_PUBLIC_KEY)), $gf_k);
  127. //数据转json
  128. $json = json_encode($array, JSON_UNESCAPED_UNICODE);
  129. //获取随机6位字符串数字
  130. $seqNO = (string)rand(100000, 999999);
  131. //获取随机字符串秘钥,md5 并转大写
  132. $key = strtoupper(md5(self::getKey()));
  133. //拼接请求数据
  134. $data = [
  135. 'appID' => self::$appID,
  136. 'seqNO' => $seqNO,
  137. 'signMethod' => "SM3",
  138. 'encryptMethod' => "SM4",
  139. 'appAccessToken' => self::getToken(),//获取token
  140. 'sm2EncryptData' => self::SM2Encrypt($key, $gf_k), //sm2加密key
  141. 'sm2Sign' => self::SM2Sign($key, $k2, $k1), //sm2加密key
  142. ];
  143. //拼接签名参数,md5转大写
  144. $data['sign'] = self::SM3Crypt($json . $data['seqNO'] . self::$appSecretKey . $key);
  145. //AES加密业务数据
  146. $data['reqData'] = self::SM4Encrypt($json, $data['seqNO'] . $data['appAccessToken'] . self::$appSecretKey . $key);
  147. dump("业务数据json");
  148. dump($json);
  149. dump("请求数据");
  150. dump($data);
  151. $res = self::https_post("https://mouldai.com/apiSIT/tzyj/scanPaymentCode", $data);
  152. //解密sm2密钥
  153. $sm2Key = self::SM2Decrypt(base64_decode($res['sm2EncryptData']), $k1);
  154. dump("sm2解密数据:" . $sm2Key);
  155. //SM4解密数据
  156. $rspData = self::SM4Decrypt($res['rspData'], $res['seqNO'] . $data['appAccessToken'] . self::$appSecretKey . $sm2Key);
  157. dump("sm4解密报文数据:" . $rspData);
  158. //sm3验签数据校验
  159. $sm3SignData = self::SM3Crypt($rspData . $res['seqNO'] . self::$appSecretKey . $sm2Key);
  160. dump("sm3响应报文拼接加签:" . $sm3SignData);
  161. $signData = $res['sign'];
  162. dump("sm3响应报文签名:" . $signData);
  163. if ($sm3SignData == $signData) {
  164. dump("验签成功!");
  165. }
  166. dump($res);
  167. return $res;
  168. }
  169. //获取post数据并解密解签获得业务数据
  170. public static function getPostData()
  171. {
  172. //获取post数据
  173. $arr = input("post.");
  174. //模拟post获取数据
  175. $arr = '{"sign":"1CA0926A5C8BC2E2347E57016650E731","signMethod":"MD5","rsaEncryptData":"xs8lNVCj4ZCsAbXoJHI+AmRPqDJk01dlt3q7Jb9Vox4SNvvx6F+DclM2v1FdnDxAsNgXBERLXCc3SOFnqtrcMdYxc2GKyF+YTLJKjX0NmlGkXlO2oipIzhIL94la\/NGEzlT+JL4I8KF5vZvE+4gudkg0mZ+jC6jPWc+qyM6RROdwbgYPCiOpVTaQ+jtIxwz4rCY\/a2z\/fAFazzApUbyRxsCTVRESJ+3dU8V9zYxE7VzrV+IlOCwJdAIAfGPcwjq5wd3p\/3yEeFDBbZz0N6jnIEIlkCH99NsNFWIYY2mH0K2z+ccpJlBejoNq+FaxusS2DvZfJhp8xa3dav8itVyiSw==","encryptMethod":"AES","reqData":"QbYx9PwqKwy30K1SSgiorq9Sg9taSxImEw6qwY93N0QhsRb1UHqBghS+WmbBRZxrBTCMYNGBsG1GFvUdJxIrdXaQ4qBU\/PTpIjLlD+bvRyE27OYgHrSpQ6umylxWXSTYUIO0qbdTjNTR8UwRKPlHjuUJ149E5eH+s\/oyE6zZi9KNzx8BwjeZ\/Qeo\/CQF7fMuu3uJF7XOOIDqLidXvevQEr8hHLUyT40a\/NZsOAoqQSoNppazy+tDuttATH7gFWjFKNzRtt89wDdbjWNtK95tc\/uUBojfjg5HKcctSmqQ7jW6HvA2J5k3WnC6mxsTdaU9WPjtKbnqGUTkoM9YbJs1VghcnnQLSH49wAY7kB5SwWwTaPkHZy5kvytfMvLjwgjUioW0qYSpZyaBww4dSXJ0bQ1Mb+TArunrCpIzl2T4ZkzWT3\/j0m4bJoq7le4l03NVAn8iA3ju2asrBbrySTWzQ9vXDQbq1q+S5uh9YTXrVq0dM6CMNV8KquOCEC0UyaTKxCK2+cAS9LDQD4APXRTuNhkR57LKox2CfvN+CTDlWw8QfFfYKdNpmt\/OHklrUez0LcfMluc08ce1fvoDCuOqMN51y5qhV+d3utWa5rBjvzhE8de5qi54l3qW4EV03sQRdvN7R433fxOVt33N1mZ3NOwx1xjnJ4ivdVuhZ1XbGHd\/B7NGGafQbx3RChEIT250Kl3vih\/P2yF1ozQC8MY6sAHgOxAufmos8DoOwwWy9L59lNqN2sAnVpPalvjM4UCa8pkSrToDaoU4Sc44JOBghQ==","appAccessToken":"","seqNO":"127600","appID":"a539d3d7-3d4b-454b-9c49-7fb83fb8b611"}';//正式获取数据删除这里
  176. $arr = json_decode($arr, true); //正式获取数据删除这里
  177. //检验字段是否缺失
  178. if (!isset($arr['rsaEncryptData']) || !isset($arr['seqNO']) || !isset($arr['signMethod']) || !isset($arr['sign']) || !isset($arr['encryptMethod']) || !isset($arr['reqData']) || !isset($arr['appID'])) {
  179. return self::runJson("1000001", "缺少参数");
  180. }
  181. dump("获取到的post数据");
  182. dump($arr);
  183. //rsa解密秘钥字段rsaEncryptData
  184. $rasKey = self::decryptByPublicKey($arr['rsaEncryptData']);
  185. dump("解密后的秘钥");
  186. dump($rasKey);
  187. //拼接秘钥
  188. $key = $arr['seqNO'] . self::$token . self::$appSecretKey . $rasKey;
  189. //秘钥转md5 转大写
  190. $key = strtoupper(md5($key));
  191. //aes解密
  192. $res = $this->decrypt($arr['reqData'], $key);
  193. $res = json_decode($res, true);
  194. dump("数据结果");
  195. halt($res);
  196. }
  197. //SM2Encrypt
  198. public static function SM2Encrypt($data, $pubkey)
  199. {
  200. //sm2加密
  201. $recode = php_SM2Encrypt($data, $cipher, $pubkey);
  202. //php_SM2Encrypt接口返回的密文值是c1c3c2格式,以下示例转DER编码
  203. $recode = php_SM2FormatConvert(102, $cipher, $der);
  204. //SM2加密字符串转base64编码
  205. $sm2encrypted = base64_encode($der);
  206. return $sm2encrypted;
  207. }
  208. //SM2Decrypt
  209. public static function SM2Decrypt($data, $privkey)
  210. {
  211. //php_SM2Decrypt 接收密文值是c1c3c2格式,若对方给的密文值是DER格式 则通过如下方式转换,然后再传入接口解密
  212. $recode = php_SM2FormatConvert(101, $data, $c1c3c2);
  213. //解密
  214. $recode = php_SM2Decrypt($c1c3c2, $plain, $privkey);
  215. return $plain;
  216. }
  217. //SM2Sign
  218. public static function SM2Sign($data, $pubkey, $privkey)
  219. {
  220. //签名
  221. $recode = php_SM2Sign($data, $redata, $privkey, $pubkey);
  222. //php_SM2Sign接口返回的签名值是RS格式,以下示例转DER编码
  223. $php_func = 'php_SM2FormatConvert';
  224. $recode = $php_func(202, $redata, $der);
  225. //加签数据base64返回
  226. $sm2SignData = base64_encode($der);
  227. return $sm2SignData;
  228. }
  229. //SM3Crypt
  230. public static function SM3Crypt($data)
  231. {
  232. $recode = php_SM3Crypt($data, $sm3hash);
  233. // echo "<br/>recode:$recode \n";
  234. //加签数据base64返回
  235. return strtoupper(self::string2hex($sm3hash));
  236. }
  237. //16进制转换为二进制
  238. public static function hex2String($hexdata)
  239. {
  240. $bindata = "";
  241. for ($i = 0; $i < strlen($hexdata); $i += 2) {
  242. $bindata .= chr(hexdec(substr($hexdata, $i, 2)));
  243. }
  244. return $bindata;
  245. }
  246. //SM4Encrypt
  247. public static function SM4Encrypt($data, $password)
  248. {
  249. //加密密码做特殊处理 先MD5转换大写 从第8位开始截取16个字符串
  250. $password = substr(strtoupper(md5($password)), 8, 16);
  251. echo "<br/>【SM4】MD5加密密码=======" . $password;
  252. //接口是密文key,将明文key加密后再传入php_SM4CBCCrypt进行数据加密
  253. //不必要每次都加密key,建议手工加密一次,将key密文保存使用,key明文保存至安全的地方
  254. //若是会话级别的key则自行定策略
  255. $recode = php_CryptKey(0, $password, $key);
  256. echo "<br/>recode:$recode \n";
  257. //加密
  258. $recode = php_SM4CBCCrypt(0, $data, $redata, $key, self::$iv);
  259. echo "<br/>recode:$recode \n";
  260. echo "<br/>redata: " . base64_encode($redata) . " \n";
  261. $SM4Encryptdata = base64_encode($redata);
  262. return $SM4Encryptdata;
  263. }
  264. //SM4Encrypt
  265. public static function SM4Decrypt($data, $password)
  266. {
  267. echo "<br/>SM4解密数据=======" . $data;
  268. //加密密码做特殊处理
  269. $password = substr(strtoupper(md5($password)), 8, 16);
  270. echo "<br/>MD5密码=======" . $password;
  271. //接口是密文key,将明文key加密后再传入php_SM4CBCCrypt进行数据加密
  272. //不必要每次都加密key,建议手工加密一次,将key密文保存使用,key明文保存至安全的地方
  273. //若是会话级别的key则自行定策略
  274. $recode = php_CryptKey(0, $password, $key);
  275. echo "<br/>recode:$recode \n";
  276. //解密
  277. $recode = php_SM4CBCCrypt(1, base64_decode($data), $dedata, $key, self::$iv);
  278. echo "<br/>sm4[解密]recode:$recode \n";
  279. return $dedata;
  280. }
  281. /**
  282. * 公钥解密
  283. * @param mixed $data 密文数据
  284. * @return string 原文结果
  285. */
  286. private static function decryptByPublicKey($data)
  287. {
  288. $data = base64_decode($data);
  289. openssl_public_decrypt($data, $decrypted, self::PUBLIC_KEY, OPENSSL_PKCS1_PADDING);//公钥解密
  290. return $decrypted;
  291. }
  292. /**
  293. * 私钥加密
  294. * @param mixed $data 原始数据
  295. * @return string 密文结果
  296. */
  297. private static function encryptByPrivateKey($data)
  298. {
  299. openssl_private_encrypt($data, $encrypted, self::PRIVATE_KEY, OPENSSL_PKCS1_PADDING);//私钥加密
  300. //加密后的内容通常含有特殊字符,需要编码转换下,在网络间通过url传输时要注意base64编码是否是url安全的
  301. return base64_encode($encrypted);
  302. }
  303. //封装返回数据
  304. private static function runJson($code = "000000", $msg = "完成")
  305. {
  306. return json(['code' => $code, 'message' => $msg]);
  307. //以下加密信息返回,暂时不用使用
  308. // $data = [
  309. // 'signMethod' => 'MD5',
  310. // 'encryptMethod' => 'AES',
  311. // 'appID' => $this->appID,
  312. // 'seqNO' => (string)rand(100000,999999),
  313. // 'appAccessToken' => ''
  314. // ];
  315. // $json = json_encode(['code'=>$code, 'message'=>$msg]);
  316. // $key = strtoupper(md5(getKey()));//随机秘钥
  317. // $data['rsaEncryptData'] = $this->encryptByPrivateKey($key);
  318. // $data['reqData'] = $this->encrypt($json, $key);
  319. // $data['sign'] = strtoupper(md5($data['reqData'] . $data['seqNO'] . $this->appSecretKey . $key ));
  320. // return json($data);
  321. }
  322. // curl post请求
  323. private static function https_post($url, $data = null)
  324. {
  325. $data = json_encode($data, JSON_UNESCAPED_SLASHES);
  326. $header [] = 'Content-Type:application/x-www-form-urlencoded';
  327. $ch = curl_init();
  328. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  329. curl_setopt($ch, CURLOPT_URL, $url);
  330. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
  331. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  332. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  333. curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
  334. @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  335. curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
  336. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  337. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  338. $tmpInfo = curl_exec($ch);
  339. curl_close($ch);
  340. return json_decode($tmpInfo, true);
  341. }
  342. /**
  343. * 获得随机字符串
  344. **/
  345. private static function getKey($length = 16)
  346. {
  347. // 密码字符集,可任意添加你需要的字符
  348. $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ2345678';
  349. $key = '';
  350. for ($i = 0; $i < $length; $i++) {
  351. $key .= $chars[mt_rand(0, strlen($chars) - 1)];
  352. }
  353. return $key;
  354. }
  355. }