蛋蛋星球-客户端
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

84 lines
1.9 KiB

  1. package aes
  2. import (
  3. "applet/app/lib/aes/md"
  4. "applet/app/utils"
  5. "bytes"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "github.com/gin-gonic/gin"
  10. "io/ioutil"
  11. "strconv"
  12. "strings"
  13. "time"
  14. )
  15. func CheckSign(c *gin.Context) error {
  16. var query = map[string]string{}
  17. //1、从请求头中获取必传参数
  18. query["timestamp"] = c.GetHeader("timestamp")
  19. query["nonce"] = c.GetHeader("nonce")
  20. if len(query["nonce"]) != 32 {
  21. return errors.New("随机字符串有误!")
  22. }
  23. sign := c.GetHeader("sign")
  24. //2、判断请求方式,以获取请求参数
  25. if c.Request.Method == "GET" {
  26. queryParams := c.Request.URL.Query()
  27. for key, values := range queryParams {
  28. if len(values) > 0 {
  29. query[key] = values[0]
  30. }
  31. }
  32. } else {
  33. body, _ := ioutil.ReadAll(c.Request.Body)
  34. if string(body) != "" {
  35. str, err := AesDecryptByECB(md.AesKey, string(body))
  36. if err != nil {
  37. return err
  38. }
  39. if str != "" {
  40. c.Request.Body = ioutil.NopCloser(bytes.NewBuffer([]byte(str)))
  41. var bodyParams = map[string]interface{}{}
  42. err = json.Unmarshal([]byte(str), &bodyParams)
  43. if err != nil {
  44. return err
  45. }
  46. for key, value := range bodyParams {
  47. // 使用类型断言判断是否为 string 类型
  48. if _, ok := value.(map[string]interface{}); ok {
  49. query[key] = utils.SerializeStr(value)
  50. } else {
  51. query[key] = utils.AnyToString(value)
  52. }
  53. }
  54. }
  55. }
  56. }
  57. //3.query参数按照 ASCII 码从小到大排序
  58. str := utils.JoinStringsInASCII(query, "&", false, false, "")
  59. //4.md5加密 转小写
  60. signValue := strings.ToLower(utils.Md5(str))
  61. //5.判断跟前端传来的sign是否一致
  62. if sign != signValue {
  63. return errors.New("非法签名!")
  64. }
  65. //6、判断时效性
  66. currentTimestamp := time.Now().Unix()
  67. storedTimestamp, err := strconv.ParseInt(query["timestamp"], 10, 64)
  68. if err != nil {
  69. return err
  70. }
  71. if currentTimestamp-storedTimestamp > 300 { // 5分钟
  72. return fmt.Errorf("签名过期!")
  73. }
  74. return nil
  75. }