广告平台(站长使用)
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.
 
 
 
 
 

69 line
1.5 KiB

  1. package wechat
  2. import (
  3. "bytes"
  4. "crypto/sha1"
  5. "fmt"
  6. "io"
  7. "math/rand"
  8. "sort"
  9. "strings"
  10. )
  11. // GetSignature 获取签名
  12. func GetSignature(timestamp, nonce string, encrypted string, token string) string {
  13. data := []string{
  14. encrypted,
  15. token,
  16. timestamp,
  17. nonce,
  18. }
  19. sort.Strings(data)
  20. s := sha1.New()
  21. _, err := io.WriteString(s, strings.Join(data, ""))
  22. if err != nil {
  23. panic("签名错误:sign error")
  24. }
  25. return fmt.Sprintf("%x", s.Sum(nil))
  26. }
  27. func makeRandomString(length int) string {
  28. randStr := ""
  29. strSource := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyl"
  30. maxLength := len(strSource) - 1
  31. for i := 0; i < length; i++ {
  32. randomNum := rand.Intn(maxLength)
  33. randStr += strSource[randomNum : randomNum+1]
  34. }
  35. return randStr
  36. }
  37. func pKCS7Pad(plainText []byte, blockSize int) []byte {
  38. // block size must be bigger or equal 2
  39. if blockSize < 1<<1 {
  40. panic("block size is too small (minimum is 2 bytes)")
  41. }
  42. // block size up to 255 requires 1 byte padding
  43. if blockSize < 1<<8 {
  44. // calculate padding length
  45. padLen := padLength(len(plainText), blockSize)
  46. // define PKCS7 padding block
  47. padding := bytes.Repeat([]byte{byte(padLen)}, padLen)
  48. // apply padding
  49. padded := append(plainText, padding...)
  50. return padded
  51. }
  52. // block size bigger or equal 256 is not currently supported
  53. panic("unsupported block size")
  54. }
  55. func padLength(sliceLength, blockSize int) int {
  56. padLen := blockSize - sliceLength%blockSize
  57. if padLen == 0 {
  58. padLen = blockSize
  59. }
  60. return padLen
  61. }