-
Notifications
You must be signed in to change notification settings - Fork 905
/
sign_util.go
53 lines (46 loc) · 1.04 KB
/
sign_util.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
package auth
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"strings"
)
func Sign(metadata, key string) string {
return doSign([]byte(metadata), key)
}
func SignWithParams(params []interface{}, metadata, key string) (string, error) {
if params == nil || len(params) == 0 {
return Sign(metadata, key), nil
}
data := append(params, metadata)
if bytes, err := toBytes(data); err != nil {
// TODO
return "", errors.New("data convert to bytes failed")
} else {
return doSign(bytes, key), nil
}
}
func toBytes(data []interface{}) ([]byte, error) {
if bytes, err := json.Marshal(data); err != nil {
return nil, errors.New("")
} else {
return bytes, nil
}
}
func doSign(bytes []byte, key string) string {
mac := hmac.New(sha256.New, []byte(key))
mac.Write(bytes)
signature := mac.Sum(nil)
return base64.URLEncoding.EncodeToString(signature)
}
func IsEmpty(s string, allowSpace bool) bool {
if len(s) == 0 {
return true
}
if !allowSpace {
return strings.TrimSpace(s) == ""
}
return false
}