signature_generate.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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/errors"
  11. "git.bvbej.com/bvbej/base-golang/pkg/time_parse"
  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. }