AppUtil.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace app\common\payment;
  3. use Payment\Common\PayException;
  4. class AppUtil
  5. {
  6. /**
  7. * 将参数数组签名
  8. */
  9. //RSA签名
  10. public static function Sign(array $array)
  11. {
  12. ksort($array);
  13. $bufSignSrc = AppUtil::ToUrlParams($array);
  14. $private_key = AppConfig::PRIVATEKEY;
  15. $private_key = chunk_split($private_key, 64, "\n");
  16. $key = "-----BEGIN RSA PRIVATE KEY-----\n" . wordwrap($private_key) . "-----END RSA PRIVATE KEY-----";
  17. // echo $key;
  18. if (openssl_sign($bufSignSrc, $signature, $key)) {
  19. $sign = base64_encode($signature);//加密后的内容通常含有特殊字符,需要编码转换下,在网络间通过url传输时要注意base64编码是否是url安全的
  20. } else {
  21. throw new PayException('签名错误');
  22. }
  23. return $sign;
  24. }
  25. public static function ToUrlParams(array $array)
  26. {
  27. $buff = "";
  28. foreach ($array as $k => $v) {
  29. if ($v != "" && !is_array($v)) {
  30. $buff .= $k . "=" . $v . "&";
  31. }
  32. }
  33. $buff = trim($buff, "&");
  34. return $buff;
  35. }
  36. /**
  37. * 校验签名
  38. * @param array 参数
  39. * @param unknown_type appkey
  40. */
  41. public static function ValidSign(array $array)
  42. {
  43. $sign = $array['sign'];
  44. unset($array['sign']);
  45. ksort($array);
  46. $bufSignSrc = AppUtil::ToUrlParams($array);
  47. $public_key = AppConfig::PUBLICKEY;
  48. $public_key = chunk_split($public_key, 64, "\n");
  49. $key = "-----BEGIN PUBLIC KEY-----\n$public_key-----END PUBLIC KEY-----\n";
  50. $result = openssl_verify($bufSignSrc, base64_decode($sign), $key);
  51. return $result;
  52. }
  53. }
  54. ?>