-
Notifications
You must be signed in to change notification settings - Fork 0
/
dsl_sign.go
67 lines (58 loc) · 1.62 KB
/
dsl_sign.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
package datarangers_sdk
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"strconv"
"time"
)
func Sha256Hmac(key, data string) string {
h := hmac.New(sha256.New, []byte(key))
h.Write([]byte(data))
sha := hex.EncodeToString(h.Sum(nil))
return sha
}
func Sign(ak string, sk string, expiration int, method string, url string, params map[string]string, body string) string {
text := canonicalRequest(method, url, params, body)
return doSign(ak, sk, expiration, text)
}
func doSign(ak string, sk string, expiration int, text string) string {
current := strconv.FormatInt(time.Now().Unix(), 10)
signKeyInfo := "ak-v1/" + ak + "/" + current + "/" + strconv.Itoa(expiration)
signKey := Sha256Hmac(sk, signKeyInfo)
signResult := Sha256Hmac(signKey, text)
return signKeyInfo + "/" + signResult
}
func canonicalMethod(method string) string {
return "HTTPMethod:" + method
}
func canonicalUrl(url string) string {
return "CanonicalURI:" + url
}
func formatKeyValue(key, value string) string {
return key + "=" + value
}
func canonicalParam(params map[string]string) string {
res := "CanonicalQueryString:"
if len(params) == 0 {
return res
}
for key := range params {
res = res + formatKeyValue(key, params[key]) + "&"
}
return res[0 : len(res)-1]
}
func canonicalBody(body string) string {
res := "CanonicalBody:"
if body == "" {
return res
}
return res + body
}
func canonicalRequest(method string, url string, params map[string]string, body string) string {
cm := canonicalMethod(method)
cu := canonicalUrl(url)
cp := canonicalParam(params)
cb := canonicalBody(body)
return cm + "\n" + cu + "\n" + cp + "\n" + cb
}