SignUtil.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. namespace common\components\payment\joinpay\util;
  3. use ReflectionClass;
  4. use ReflectionProperty;
  5. use common\components\payment\joinpay\exceptions\SDKException;
  6. /**
  7. * 签名、验签工具类
  8. * Class SignUtil
  9. * @package utils
  10. */
  11. class SignUtil {
  12. const MS5_BOUND_SYMBOL = "&key=";
  13. /**
  14. * 签名
  15. * @param string $signData 需要签名的数据
  16. * @param string $signType 签名类型
  17. * @param string $priKey 用以签名的私钥
  18. * @return string
  19. * @throws SDKException
  20. */
  21. public static function sign(string $signData, string $signType, string $priKey){
  22. if("2" === $signType){
  23. return RSAUtil::sign($signData, $priKey);
  24. }else if("1" === $signType){
  25. return MD5Util::getMd5Str($signData . self::MS5_BOUND_SYMBOL . $priKey);
  26. }else{
  27. throw new SDKException(SDKException::BIZ_ERROR, "未支持的签名类型:" . $signType);
  28. }
  29. }
  30. /**
  31. * 验签
  32. * @param string $signData 需要验签的数据
  33. * @param string $signParam 需要被校验签名的源数据
  34. * @param string $signType 签名类型
  35. * @param string $pubKey 用以验签的公钥
  36. * @return bool
  37. * @throws SDKException
  38. */
  39. public static function verify(string $signData, string $signParam, string $signType, string $pubKey){
  40. if("2" === $signType){
  41. return RSAUtil::verify($signData, $signParam, $pubKey);
  42. }else if("1" === $signType){
  43. $signData = MD5Util::getMd5Str($signData . self::MS5_BOUND_SYMBOL . $pubKey);
  44. return $signData === $signParam;
  45. }else{
  46. throw new SDKException(SDKException::BIZ_ERROR, "未支持的签名类型:" . $signType);
  47. }
  48. }
  49. /**
  50. * 取得 待签名/待验签 的字符串
  51. * @param object $param
  52. * @return string
  53. * @throws \ReflectionException
  54. */
  55. public static function getSortedString(object $param){
  56. $reflect = new ReflectionClass($param);
  57. $props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PROTECTED);
  58. //通过反射取得所有属性和属性的值
  59. $arr = [];
  60. foreach ($props as $prop) {
  61. $prop->setAccessible(true);
  62. $key = $prop->getName();
  63. $value = $prop->getValue($param);
  64. $arr[$key] = $value;
  65. }
  66. //按key的字典序升序排序,并保留key值
  67. ksort($arr);
  68. //拼接字符串
  69. $str = '';
  70. $i = 0;
  71. foreach($arr as $key => $value) {
  72. //不参与签名、验签
  73. if($key == "sign" || $key == "sec_key"){
  74. continue;
  75. }
  76. if($key == 'resp_code' && !$value){
  77. continue;
  78. }
  79. if($value === null){
  80. $value = '';
  81. }
  82. if($i !== 0){
  83. $str .= '&';
  84. }
  85. $str .= $key . '=' . $value;
  86. $i ++;
  87. }
  88. return $str;
  89. }
  90. }