Hqpay.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. // 使用私钥加密
  3. class Hqpay
  4. {
  5. private $pi_key;
  6. private $pu_key;
  7. private $uid;
  8. private $key;
  9. public function __construct($merchantID,$platpkey){
  10. $cfg = require APP_ROOT_PATH."system/payment/Hqpay/config.php";
  11. $this->pi_key = $cfg['private_key'];
  12. $this->pu_key = openssl_pkey_get_public($cfg['public_key']);;
  13. $this->uid = $merchantID;
  14. $this->key = $platpkey;
  15. }
  16. public function privateEncrypt($data)
  17. {
  18. openssl_private_encrypt($data, $encrypted, $this->pi_key);
  19. return base64_encode($encrypted);
  20. }
  21. // 使用公钥解密
  22. public function publicDecrypt($encrypted)
  23. {
  24. openssl_public_decrypt($encrypted, $decrypted, $this->pu_key);
  25. return $decrypted;
  26. }
  27. /**
  28. * RSA验签
  29. * @param $data 待签名数据
  30. * @param $sign 要校对的的签名结果
  31. * return 验证结果
  32. */
  33. public function rsaVerify($data, $sign) {
  34. $pubkey = $this->pu_key;
  35. $res = openssl_get_publickey($pubkey);
  36. $result = (bool)openssl_verify($data, base64_decode($sign), $res);
  37. openssl_free_key($res);
  38. return $result;
  39. }
  40. /**
  41. * RSA解密
  42. * @param $str 需要解密的内容,密文
  43. * @param $private_key_path 商户私钥文件路径
  44. * return 解密后内容,明文
  45. */
  46. public function rsaDecrypt($str) {
  47. $str = str_replace('_', "+", $str);
  48. $str = base64_decode($str);
  49. // 按128位使用平台公钥分段进行解密
  50. $index = 128;
  51. $indexx = 0;
  52. $string = '';
  53. $strlen = strlen($str);
  54. $step = $strlen / $index;
  55. $decrypted = array();
  56. for ($i = 0; $i < $step; $i ++) {
  57. $strr = substr($str, $indexx, $index);
  58. $indexx += $index;
  59. $decrypted[] .= $this->publicDecrypt($strr);
  60. }
  61. return implode('',$decrypted);
  62. }
  63. }