sign.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. /*
  2. * @Descripttion:
  3. * @version:
  4. * @Author: Neo,Huang
  5. * @Date: 2020-10-16 14:29:56
  6. * @LastEditors: Neo,Huang
  7. * @LastEditTime: 2020-12-16 14:27:06
  8. */
  9. package utils
  10. import (
  11. "crypto/md5"
  12. "fmt"
  13. "io"
  14. "net/url"
  15. "sort"
  16. "github.com/astaxie/beego"
  17. "strconv"
  18. "encoding/hex"
  19. )
  20. // Kv struct
  21. type Kv struct {
  22. Key, Value string
  23. }
  24. // Kvs typenmae
  25. type Kvs []*Kv
  26. func (a Kvs) Len() int { return len(a) }
  27. func (a Kvs) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  28. func (a Kvs) Less(i, j int) bool { return a[i].Key < a[j].Key }
  29. var secrets map[string]string
  30. func init_secrets() {
  31. secrets = make(map[string]string)
  32. secrets["101"] = "39baf5e79adac446131b7c78608cfe3d"
  33. secrets["102"] = "51f4e76fc3b42c56243e9aa504ddfc9e"
  34. }
  35. // 获取appkey对应的appSecret
  36. func GetSecretByKey(appKey string) string {
  37. if appKey == "" {
  38. return ""
  39. }
  40. secret, ok := secrets[appKey]
  41. if ok == false {
  42. init_secrets()
  43. secret, ok = secrets[appKey]
  44. }
  45. return secret
  46. }
  47. //Md5 md5散列函数
  48. func Md5(str string) string {
  49. h := md5.New()
  50. io.WriteString(h, str)
  51. return fmt.Sprintf("%x", h.Sum(nil))
  52. }
  53. var keyMahjong = "am0xNjAzOTUxODE2"
  54. // MakeSign 生成签名秘钥
  55. func MakeSign(m map[string]string, appKey string) string {
  56. var kvs Kvs
  57. for k, v := range m {
  58. kvs = append(kvs, &Kv{k, url.QueryEscape(v)})
  59. }
  60. sort.Sort(kvs)
  61. key := ""
  62. for i := 0; i < kvs.Len(); i++ {
  63. key += kvs[i].Key + kvs[i].Value
  64. }
  65. if appKey != "" {
  66. key += appKey
  67. }
  68. return Md5(key)
  69. }
  70. // MakeSign 生成签名秘钥
  71. func MakeKeySign(m map[string]interface{}) string {
  72. var kvs Kvs
  73. for k, v := range m {
  74. switch val := v.(type) {
  75. case int:
  76. kvs = append(kvs, &Kv{k, IntToString(val)})
  77. case int64:
  78. kvs = append(kvs, &Kv{k, strconv.FormatInt(val, 10)})
  79. case string:
  80. kvs = append(kvs, &Kv{k, url.QueryEscape(val)})
  81. }
  82. }
  83. sort.Sort(kvs)
  84. key := ""
  85. for i := 0; i < kvs.Len(); i++ {
  86. key += kvs[i].Key + kvs[i].Value
  87. }
  88. if beego.AppConfig.String("project") == "mj" {
  89. key += keyMahjong
  90. }
  91. return Md5(key)
  92. }
  93. // Strtomd5 md5
  94. func Strtomd5(s string) string {
  95. h := md5.New()
  96. h.Write([]byte(s))
  97. rs := hex.EncodeToString(h.Sum(nil))
  98. return rs
  99. }