signature_generate.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package signature
  2. import (
  3. "bytes"
  4. "crypto/hmac"
  5. "crypto/sha256"
  6. "encoding/base64"
  7. "fmt"
  8. "net/url"
  9. "strings"
  10. "git.bvbej.com/bvbej/base-golang/pkg/time_parse"
  11. "github.com/pkg/errors"
  12. )
  13. // Generate
  14. // path 请求的路径 (不附带 querystring)
  15. func (s *signature) Generate(path string, method string, params url.Values) (authorization, date string, err error) {
  16. if path == "" {
  17. err = errors.New("path required")
  18. return
  19. }
  20. if method == "" {
  21. err = errors.New("method required")
  22. return
  23. }
  24. methodName := strings.ToUpper(method)
  25. if !methods[methodName] {
  26. err = errors.New("method param error")
  27. return
  28. }
  29. // Date
  30. date = time_parse.CSTLayoutString()
  31. // Encode() 方法中自带 sorted by key
  32. sortParamsEncode, err := url.QueryUnescape(params.Encode())
  33. if err != nil {
  34. err = errors.Errorf("url QueryUnescape error %v", err)
  35. return
  36. }
  37. // 加密字符串规则
  38. buffer := bytes.NewBuffer(nil)
  39. buffer.WriteString(path)
  40. buffer.WriteString(delimiter)
  41. buffer.WriteString(methodName)
  42. buffer.WriteString(delimiter)
  43. buffer.WriteString(sortParamsEncode)
  44. buffer.WriteString(delimiter)
  45. buffer.WriteString(date)
  46. // 对数据进行 sha256 加密,并进行 base64 encode
  47. hash := hmac.New(sha256.New, []byte(s.secret))
  48. hash.Write(buffer.Bytes())
  49. digest := base64.StdEncoding.EncodeToString(hash.Sum(nil))
  50. authorization = fmt.Sprintf("%s %s", s.key, digest)
  51. return
  52. }