sign.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package wechat
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "math/rand"
  6. "sort"
  7. "strings"
  8. "time"
  9. "git.chuangxin1.com/myth/sacred/hash"
  10. )
  11. // Sign 微信计算签名的函数
  12. func Sign(req map[string]interface{}, key string) (sign string) {
  13. keys := make([]string, 0)
  14. for k := range req {
  15. keys = append(keys, k)
  16. }
  17. sort.Strings(keys)
  18. var s string
  19. for _, k := range keys {
  20. value := fmt.Sprintf("%v", req[k])
  21. if value != "" {
  22. s = s + k + "=" + value + "&"
  23. }
  24. }
  25. if key != "" {
  26. s = s + "key=" + key
  27. }
  28. hs, _ := hash.MD5([]byte(s))
  29. sign = strings.ToUpper(hex.EncodeToString(hs))
  30. return
  31. }
  32. // Random 指定长度的随机字符串(字母或数字)
  33. func Random(n int) string {
  34. str := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  35. bytes := []byte(str)
  36. result := []byte{}
  37. r := rand.New(rand.NewSource(time.Now().UnixNano()))
  38. n1 := len(bytes)
  39. for i := 0; i < n; i++ {
  40. result = append(result, bytes[r.Intn(n1)])
  41. }
  42. return string(result)
  43. }
  44. // makeSignature echo 签名验证
  45. func makeSignature(token, signature, timestamp, nonce string) bool {
  46. sl := []string{token, timestamp, nonce}
  47. sort.Strings(sl)
  48. hs, _ := hash.SHA1([]byte(strings.Join(sl, "")))
  49. return strings.Compare(signature, hex.EncodeToString(hs)) == 0
  50. }