-
Notifications
You must be signed in to change notification settings - Fork 1
/
aksk.go
117 lines (104 loc) · 2.46 KB
/
aksk.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/*
Package ginaksk 基于ak, sk实现的服务认证中间件
*/
package ginaksk
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"hash"
"sort"
"strconv"
"strings"
"time"
)
// HashFunc 返回一个hash.Hash接口
type HashFunc func() hash.Hash
var hashFunc HashFunc = sha256.New
// SetHash 使用自定义Hash算法,使用Validate后再次调用会panic
func SetHash(h HashFunc) {
if initialized {
panic("必须在使用Validate前调用")
}
if h != nil {
hashFunc = h
}
}
// KeyFunc 查询accesskey,返回secretKey的函数
type KeyFunc func(accessKey string) (secretKey string)
const (
// headerAccessKey 访问key
headerAccessKey = `x-auth-accesskey`
// headerTimestamp 访问时间戳, 前1分钟或者后5分钟之内有效
headerTimestamp = `x-auth-timestamp`
// headerSignature 签名hmac的签名
headerSignature = `x-auth-signature`
// headerBodyHash http的Body hash计算的mac
headerBodyHash = `x-auth-body-hash`
// headerRandomStr 随机字符串
headerRandomStr = `x-auth-random-str`
)
const (
maxDuration = 5 * time.Minute
minDuration = -1 * time.Minute
)
// parseTimestamp 解析时间戳
func parseTimestamp(s string) error {
if s == "" {
return ErrTimestampEmpty
}
n, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return err
}
t := time.Unix(n, 0)
d := time.Now().Sub(t)
if d > maxDuration {
return ErrTimestampExpired
} else if d < minDuration {
return ErrTimestampInvalid
}
return nil
}
func hashSum(b []byte) []byte {
h := hashFunc()
h.Write(b)
return h.Sum(nil)
}
func hmacSum(key []byte, elems ...string) []byte {
h := hmac.New(hashFunc, key)
sort.Strings(elems)
s := strings.Join(elems, "")
h.Write([]byte(s))
return h.Sum(nil)
}
// validBytes 通过计算请求b的sha256值验证请求内容
// 如果b长度为0, 返回真; 否则检查mac和编码器计算的Mac是否一致
func validBytes(b []byte, s string) error {
if len(b) == 0 {
return nil
}
if s == "" {
return ErrBodyHashInvalid
}
mac, err := encoder.DecodeString(s)
if err != nil {
return ErrBodyHashInvalid
}
if ok := bytes.Equal(mac, hashSum(b)); ok {
return nil
}
return ErrBodyHashInvalid
}
// validSignature 校验头部签名
func validSignature(sk, sign string, elems ...string) error {
// 解码签名,得道原始的字节切片
mac, err := encoder.DecodeString(sign)
if err != nil {
return ErrSignatureInvalid
}
if ok := hmac.Equal(mac, hmacSum([]byte(sk), elems...)); ok {
return nil
}
return ErrSignatureInvalid
}