支付模块
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 line
2.2 KiB

  1. package zhios_pay_utils
  2. import (
  3. "crypto"
  4. "crypto/rand"
  5. "crypto/rsa"
  6. "encoding/base64"
  7. "fmt"
  8. "golang.org/x/crypto/ssh"
  9. "sort"
  10. "strings"
  11. )
  12. func GetSign(privateKeyStr, data string) (string, error) {
  13. privateKey, err := ssh.ParseRawPrivateKey([]byte(privateKeyStr))
  14. if err != nil {
  15. return "", err
  16. }
  17. fmt.Println(privateKey.(*rsa.PrivateKey))
  18. fmt.Println(data)
  19. h := crypto.Hash.New(crypto.SHA256)
  20. h.Write([]byte(data))
  21. hashed := h.Sum(nil)
  22. sign, err := rsa.SignPKCS1v15(rand.Reader, privateKey.(*rsa.PrivateKey), crypto.SHA256, hashed)
  23. if err != nil {
  24. return "", nil
  25. }
  26. return base64.StdEncoding.EncodeToString(sign), nil
  27. }
  28. //规则:
  29. //◆ 参数名ASCII码从小到大排序(字典序);
  30. //◆ 如果参数的值为空不参与签名;
  31. //◆ 参数名区分大小写;
  32. //◆ 接口請求成功時,需對返回參數使用平台提供的公鑰進行驗簽,传送的sign参数不参与签名,将生成的签名与该sign值作校验。
  33. //
  34. // JoinStringsInASCII
  35. // @Description: 按照规则,参数名ASCII码从小到大排序后拼接
  36. // @param data 待拼接的数据
  37. // @param sep 连接符
  38. // @param onlyValues 是否只包含参数值,true则不包含参数名,否则参数名和参数值均有
  39. // @param includeEmpty 是否包含空值,true则包含空值,否则不包含,注意此参数不影响参数名的存在
  40. // @param exceptKeys 被排除的参数名,不参与排序及拼接
  41. // @return string
  42. //
  43. func JoinStringsInASCII(data map[string]string, sep, KeyValueSep string, onlyValues, includeEmpty bool, exceptKeys ...string) string {
  44. var list []string
  45. var keyList []string
  46. m := make(map[string]int)
  47. if len(exceptKeys) > 0 {
  48. for _, except := range exceptKeys {
  49. m[except] = 1
  50. }
  51. }
  52. for k := range data {
  53. if _, ok := m[k]; ok {
  54. continue
  55. }
  56. value := data[k]
  57. if !includeEmpty && value == "" {
  58. continue
  59. }
  60. if onlyValues {
  61. keyList = append(keyList, k)
  62. } else {
  63. list = append(list, fmt.Sprintf("%s%s%s", k, KeyValueSep, value))
  64. }
  65. }
  66. if onlyValues {
  67. sort.Strings(keyList)
  68. for _, v := range keyList {
  69. list = append(list, data[v])
  70. }
  71. } else {
  72. sort.Strings(list)
  73. }
  74. return strings.Join(list, sep)
  75. }