signutil.go 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /**
  2. Copyright 1999-2017 Alibaba Group Holding Ltd.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. CSB-HTTP-SDK based on GO language.
  13. */
  14. package csbhttp
  15. import (
  16. "bytes"
  17. "crypto/hmac"
  18. "crypto/sha1"
  19. "encoding/base64"
  20. "hash"
  21. "io"
  22. "sort"
  23. )
  24. /**
  25. 签名处理逻辑
  26. 将请求map中的key按字典顺序排序,然后使用secretKey进行签名处理
  27. */
  28. // 用于signParms的字典排序存放容器。
  29. type paramsSorter struct {
  30. Keys []string
  31. Vals []string
  32. }
  33. // params map 转换为paramsSorter格式
  34. func newParamsSorter(m map[string]string) *paramsSorter {
  35. hs := &paramsSorter{
  36. Keys: make([]string, 0, len(m)),
  37. Vals: make([]string, 0, len(m)),
  38. }
  39. for k, v := range m {
  40. hs.Keys = append(hs.Keys, k)
  41. hs.Vals = append(hs.Vals, v)
  42. }
  43. return hs
  44. }
  45. // 进行字典顺序排序 sort required method
  46. func (hs *paramsSorter) Sort() {
  47. sort.Sort(hs)
  48. }
  49. // Additional function for function sort required method
  50. func (hs *paramsSorter) Len() int {
  51. return len(hs.Vals)
  52. }
  53. // Additional function for function sort required method
  54. func (hs *paramsSorter) Less(i, j int) bool {
  55. return bytes.Compare([]byte(hs.Keys[i]), []byte(hs.Keys[j])) < 0
  56. }
  57. // Additional function for function paramsSorter.
  58. func (hs *paramsSorter) Swap(i, j int) {
  59. hs.Vals[i], hs.Vals[j] = hs.Vals[j], hs.Vals[i]
  60. hs.Keys[i], hs.Keys[j] = hs.Keys[j], hs.Keys[i]
  61. }
  62. // 做签名处理
  63. func doSign(params map[string]string, secretKey string) string {
  64. hs := newParamsSorter(params)
  65. // Sort the temp by the Ascending Order
  66. hs.Sort()
  67. // Get the CanonicalizedOSSHeaders
  68. canonicalizedParams := ""
  69. for i := range hs.Keys {
  70. if i > 0 {
  71. canonicalizedParams += "&"
  72. }
  73. canonicalizedParams += hs.Keys[i] + "=" + hs.Vals[i]
  74. }
  75. printDebug("canonicalizedParams", canonicalizedParams)
  76. signStr := canonicalizedParams
  77. h := hmac.New(func() hash.Hash { return sha1.New() }, []byte(secretKey))
  78. io.WriteString(h, signStr)
  79. signedStr := base64.StdEncoding.EncodeToString(h.Sum(nil))
  80. return signedStr
  81. }