forked from weikaishio/ali_mns
-
Notifications
You must be signed in to change notification settings - Fork 1
/
credential.go
90 lines (71 loc) · 1.95 KB
/
credential.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package ali_mns
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"net/http"
"sort"
"strings"
"time"
"github.com/gogap/errors"
)
const (
AUTHORIZATION = "Authorization"
CONTENT_TYPE = "Content-Type"
CONTENT_MD5 = "Content-MD5"
MQ_VERSION = "x-mns-version"
HOST = "Host"
DATE = "Date"
KEEP_ALIVE = "Keep-Alive"
)
type Credential interface {
Signature(method Method, headers map[string]string, resource string) (signature string, err error)
SetSecretKey(accessKeySecret string)
}
type AliMNSCredential struct {
accessKeySecret string
}
func NewAliMNSCredential(accessKeySecret string) *AliMNSCredential {
aliMNSCredential := new(AliMNSCredential)
aliMNSCredential.accessKeySecret = accessKeySecret
return aliMNSCredential
}
func (p *AliMNSCredential) SetSecretKey(accessKeySecret string) {
p.accessKeySecret = accessKeySecret
}
func (p *AliMNSCredential) Signature(method Method, headers map[string]string, resource string) (signature string, err error) {
signItems := []string{}
signItems = append(signItems, string(method))
contentMD5 := ""
contentType := ""
date := time.Now().UTC().Format(http.TimeFormat)
if v, exist := headers[CONTENT_MD5]; exist {
contentMD5 = v
}
if v, exist := headers[CONTENT_TYPE]; exist {
contentType = v
}
if v, exist := headers[DATE]; exist {
date = v
}
mnsHeaders := []string{}
for k, v := range headers {
if strings.HasPrefix(k, "x-mns-") {
mnsHeaders = append(mnsHeaders, k+":"+strings.TrimSpace(v))
}
}
sort.Sort(sort.StringSlice(mnsHeaders))
stringToSign := string(method) + "\n" +
contentMD5 + "\n" +
contentType + "\n" +
date + "\n" +
strings.Join(mnsHeaders, "\n") + "\n" +
resource
sha1Hash := hmac.New(sha1.New, []byte(p.accessKeySecret))
if _, e := sha1Hash.Write([]byte(stringToSign)); e != nil {
err = ERR_SIGN_MESSAGE_FAILED.New(errors.Params{"err": e})
return
}
signature = base64.StdEncoding.EncodeToString(sha1Hash.Sum(nil))
return
}