forked from xinliangnote/go-gin-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
signature_verify.go
73 lines (61 loc) · 1.61 KB
/
signature_verify.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
package signature
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"fmt"
"net/url"
"strings"
"time"
"github.com/xinliangnote/go-gin-api/pkg/errors"
"github.com/xinliangnote/go-gin-api/pkg/timeutil"
)
func (s *signature) Verify(authorization, date string, path string, method string, params url.Values) (ok bool, err error) {
if date == "" {
err = errors.New("date required")
return
}
if path == "" {
err = errors.New("path required")
return
}
if method == "" {
err = errors.New("method required")
return
}
methodName := strings.ToUpper(method)
if !methods[methodName] {
err = errors.New("method param error")
return
}
ts, err := timeutil.ParseCSTInLocation(date)
if err != nil {
err = errors.New("date must follow '2006-01-02 15:04:05'")
return
}
if timeutil.SubInLocation(ts) > float64(s.ttl/time.Second) {
err = errors.Errorf("date exceeds limit %v", s.ttl)
return
}
// Encode() 方法中自带 sorted by key
sortParamsEncode, err := url.QueryUnescape(params.Encode())
if err != nil {
err = errors.Errorf("url QueryUnescape error %v", err)
return
}
buffer := bytes.NewBuffer(nil)
buffer.WriteString(path)
buffer.WriteString(delimiter)
buffer.WriteString(methodName)
buffer.WriteString(delimiter)
buffer.WriteString(sortParamsEncode)
buffer.WriteString(delimiter)
buffer.WriteString(date)
// 对数据进行 hmac 加密,并进行 base64 encode
hash := hmac.New(sha256.New, []byte(s.secret))
hash.Write(buffer.Bytes())
digest := base64.StdEncoding.EncodeToString(hash.Sum(nil))
ok = authorization == fmt.Sprintf("%s %s", s.key, digest)
return
}