用户接口远程调用
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.

129 lines
2.2 KiB

  1. package userrpc
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "encoding/json"
  6. "errors"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "git.tetele.net/tgo/crypter"
  11. )
  12. /**
  13. * 签名
  14. */
  15. func Sign(data string, salt string) string {
  16. var build strings.Builder
  17. build.WriteString(data)
  18. build.WriteString(salt)
  19. build.WriteString("user&rpc")
  20. data_str := build.String()
  21. h := md5.New()
  22. h.Write([]byte(data_str)) // 需要加密的字符串
  23. return hex.EncodeToString(h.Sum(nil)) // 输出加密结果
  24. }
  25. /**
  26. * 验证签名
  27. */
  28. func CheckSign(sign_str, data, salt string) bool {
  29. sign := Sign(data, salt)
  30. if strings.Compare(sign_str, sign) > -1 {
  31. return true
  32. }
  33. return false
  34. }
  35. /**
  36. * 处理返回结果
  37. */
  38. func HandleRes(res *Response) (*Res, error) {
  39. res_data := res.GetData()
  40. if res_data == "" {
  41. return nil, errors.New("未收到收据")
  42. }
  43. time_int64, err := strconv.ParseInt(res.GetTime(), 10, 64)
  44. if err != nil {
  45. return nil, err
  46. }
  47. now_int64 := time.Now().Unix()
  48. if now_int64-time_int64 > 10 || time_int64-now_int64 > 10 {
  49. //时间误差前后10秒,返回
  50. return nil, errors.New("返回时间错误")
  51. }
  52. check_sign := CheckSign(res.GetSign(), res_data, res.GetTime())
  53. if !check_sign {
  54. return nil, errors.New("返回数据签名错误")
  55. }
  56. //解密
  57. res_data_de := crypter.DesDe(res_data, DES_KEY)
  58. var res_arr Res
  59. err = json.Unmarshal([]byte(res_data_de), &res_arr)
  60. if err != nil {
  61. return nil, err
  62. }
  63. return &res_arr, nil
  64. }
  65. /**
  66. * 处理返回结果
  67. */
  68. func HandleUserRes(res *Response) (map[string]string, error) {
  69. res_data := res.GetData()
  70. if res_data == "" {
  71. return nil, errors.New("未收到收据")
  72. }
  73. time_int64, err := strconv.ParseInt(res.GetTime(), 10, 64)
  74. if err != nil {
  75. return nil, err
  76. }
  77. now_int64 := time.Now().Unix()
  78. if now_int64-time_int64 > 10 || time_int64-now_int64 > 10 {
  79. //时间误差前后10秒,返回
  80. return nil, errors.New("返回时间错误")
  81. }
  82. check_sign := CheckSign(res.GetSign(), res_data, res.GetTime())
  83. if !check_sign {
  84. return nil, errors.New("返回数据签名错误")
  85. }
  86. //解密
  87. res_data_de := crypter.DesDe(res_data, DES_KEY)
  88. var res_arr map[string]string
  89. err = json.Unmarshal([]byte(res_data_de), &res_arr)
  90. if err != nil {
  91. return nil, err
  92. }
  93. return res_arr, nil
  94. }