auth.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package oss
  2. import (
  3. "bytes"
  4. "crypto/hmac"
  5. "crypto/sha1"
  6. "encoding/base64"
  7. "hash"
  8. "io"
  9. "net/http"
  10. "sort"
  11. "strings"
  12. )
  13. // 用于signHeader的字典排序存放容器。
  14. type headerSorter struct {
  15. Keys []string
  16. Vals []string
  17. }
  18. // 生成签名方法(直接设置请求的Header)。
  19. func (conn Conn) signHeader(req *http.Request, canonicalizedResource string) {
  20. // Find out the "x-oss-"'s address in this request'header
  21. temp := make(map[string]string)
  22. for k, v := range req.Header {
  23. if strings.HasPrefix(strings.ToLower(k), "x-oss-") {
  24. temp[strings.ToLower(k)] = v[0]
  25. }
  26. }
  27. hs := newHeaderSorter(temp)
  28. // Sort the temp by the Ascending Order
  29. hs.Sort()
  30. // Get the CanonicalizedOSSHeaders
  31. canonicalizedOSSHeaders := ""
  32. for i := range hs.Keys {
  33. canonicalizedOSSHeaders += hs.Keys[i] + ":" + hs.Vals[i] + "\n"
  34. }
  35. // Give other parameters values
  36. date := req.Header.Get(HTTPHeaderDate)
  37. contentType := req.Header.Get(HTTPHeaderContentType)
  38. contentMd5 := req.Header.Get(HTTPHeaderContentMD5)
  39. signStr := req.Method + "\n" + contentMd5 + "\n" + contentType + "\n" + date + "\n" + canonicalizedOSSHeaders + canonicalizedResource
  40. h := hmac.New(func() hash.Hash { return sha1.New() }, []byte(conn.config.AccessKeySecret))
  41. io.WriteString(h, signStr)
  42. signedStr := base64.StdEncoding.EncodeToString(h.Sum(nil))
  43. // Get the final Authorization' string
  44. authorizationStr := "OSS " + conn.config.AccessKeyID + ":" + signedStr
  45. // Give the parameter "Authorization" value
  46. req.Header.Set(HTTPHeaderAuthorization, authorizationStr)
  47. }
  48. // Additional function for function SignHeader.
  49. func newHeaderSorter(m map[string]string) *headerSorter {
  50. hs := &headerSorter{
  51. Keys: make([]string, 0, len(m)),
  52. Vals: make([]string, 0, len(m)),
  53. }
  54. for k, v := range m {
  55. hs.Keys = append(hs.Keys, k)
  56. hs.Vals = append(hs.Vals, v)
  57. }
  58. return hs
  59. }
  60. // Additional function for function SignHeader.
  61. func (hs *headerSorter) Sort() {
  62. sort.Sort(hs)
  63. }
  64. // Additional function for function SignHeader.
  65. func (hs *headerSorter) Len() int {
  66. return len(hs.Vals)
  67. }
  68. // Additional function for function SignHeader.
  69. func (hs *headerSorter) Less(i, j int) bool {
  70. return bytes.Compare([]byte(hs.Keys[i]), []byte(hs.Keys[j])) < 0
  71. }
  72. // Additional function for function SignHeader.
  73. func (hs *headerSorter) Swap(i, j int) {
  74. hs.Vals[i], hs.Vals[j] = hs.Vals[j], hs.Vals[i]
  75. hs.Keys[i], hs.Keys[j] = hs.Keys[j], hs.Keys[i]
  76. }