signature.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. package alils
  2. import (
  3. "crypto/hmac"
  4. "crypto/sha1"
  5. "encoding/base64"
  6. "fmt"
  7. "net/url"
  8. "sort"
  9. "strings"
  10. "time"
  11. )
  12. // GMT location
  13. var gmtLoc = time.FixedZone("GMT", 0)
  14. // NowRFC1123 returns now time in RFC1123 format with GMT timezone,
  15. // eg. "Mon, 02 Jan 2006 15:04:05 GMT".
  16. func nowRFC1123() string {
  17. return time.Now().In(gmtLoc).Format(time.RFC1123)
  18. }
  19. // signature calculates a request's signature digest.
  20. func signature(project *LogProject, method, uri string,
  21. headers map[string]string) (digest string, err error) {
  22. var contentMD5, contentType, date, canoHeaders, canoResource string
  23. var slsHeaderKeys sort.StringSlice
  24. // SignString = VERB + "\n"
  25. // + CONTENT-MD5 + "\n"
  26. // + CONTENT-TYPE + "\n"
  27. // + DATE + "\n"
  28. // + CanonicalizedSLSHeaders + "\n"
  29. // + CanonicalizedResource
  30. if val, ok := headers["Content-MD5"]; ok {
  31. contentMD5 = val
  32. }
  33. if val, ok := headers["Content-Type"]; ok {
  34. contentType = val
  35. }
  36. date, ok := headers["Date"]
  37. if !ok {
  38. err = fmt.Errorf("Can't find 'Date' header")
  39. return
  40. }
  41. // Calc CanonicalizedSLSHeaders
  42. slsHeaders := make(map[string]string, len(headers))
  43. for k, v := range headers {
  44. l := strings.TrimSpace(strings.ToLower(k))
  45. if strings.HasPrefix(l, "x-sls-") {
  46. slsHeaders[l] = strings.TrimSpace(v)
  47. slsHeaderKeys = append(slsHeaderKeys, l)
  48. }
  49. }
  50. sort.Sort(slsHeaderKeys)
  51. for i, k := range slsHeaderKeys {
  52. canoHeaders += k + ":" + slsHeaders[k]
  53. if i+1 < len(slsHeaderKeys) {
  54. canoHeaders += "\n"
  55. }
  56. }
  57. // Calc CanonicalizedResource
  58. u, err := url.Parse(uri)
  59. if err != nil {
  60. return
  61. }
  62. canoResource += url.QueryEscape(u.Path)
  63. if u.RawQuery != "" {
  64. var keys sort.StringSlice
  65. vals := u.Query()
  66. for k, _ := range vals {
  67. keys = append(keys, k)
  68. }
  69. sort.Sort(keys)
  70. canoResource += "?"
  71. for i, k := range keys {
  72. if i > 0 {
  73. canoResource += "&"
  74. }
  75. for _, v := range vals[k] {
  76. canoResource += k + "=" + v
  77. }
  78. }
  79. }
  80. signStr := method + "\n" +
  81. contentMD5 + "\n" +
  82. contentType + "\n" +
  83. date + "\n" +
  84. canoHeaders + "\n" +
  85. canoResource
  86. // Signature = base64(hmac-sha1(UTF8-Encoding-Of(SignString),AccessKeySecret))
  87. mac := hmac.New(sha1.New, []byte(project.AccessKeySecret))
  88. _, err = mac.Write([]byte(signStr))
  89. if err != nil {
  90. return
  91. }
  92. digest = base64.StdEncoding.EncodeToString(mac.Sum(nil))
  93. return
  94. }