-
Notifications
You must be signed in to change notification settings - Fork 0
/
signature.go
92 lines (80 loc) · 1.86 KB
/
signature.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
package signature
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"net/url"
"strconv"
"time"
"github.com/binbinly/pkg/util"
"github.com/binbinly/pkg/util/xhash"
)
var _ Signature = (*signature)(nil)
// CryptoFunc 签名加密函数
type CryptoFunc func(b, k []byte) []byte
const (
delimiter = "|"
)
type Signature interface {
// Generate 生成签名
Generate(params any) (auth string, ts int64, err error)
// Verify 验证签名
Verify(auth string, ts int64, params any) (ok bool, err error)
}
type signature struct {
key string
secret string
ttl time.Duration
cryptoFunc CryptoFunc
}
func New(key, secret string, ttl time.Duration) Signature {
return &signature{
key: key,
secret: secret,
ttl: ttl,
cryptoFunc: func(b, k []byte) []byte {
buf := bytes.NewBuffer(b)
buf.WriteString("&key=")
buf.Write(k)
return xhash.MD5(buf.Bytes())
},
}
}
func NewSha256(key, secret string, ttl time.Duration) Signature {
return &signature{
key: key,
secret: secret,
ttl: ttl,
cryptoFunc: func(b, k []byte) []byte {
hash := hmac.New(sha256.New, k)
_, _ = hash.Write(b)
return hash.Sum(nil)
},
}
}
func NewCrypto(key, secret string, ttl time.Duration, f CryptoFunc) Signature {
return &signature{
key: key,
secret: secret,
ttl: ttl,
cryptoFunc: f,
}
}
func (s *signature) data(timestamp int64, params any) ([]byte, error) {
buffer := bytes.NewBufferString(strconv.FormatInt(timestamp, 10))
buffer.WriteString(delimiter)
switch p := params.(type) {
case url.Values:
// Encode() 方法中自带 sorted by key
sortParamsEncode, err := url.QueryUnescape(p.Encode())
if err != nil {
return nil, err
}
buffer.WriteString(sortParamsEncode)
case map[string]any:
buffer.WriteString(util.MapBuildQuery(p))
case string:
buffer.WriteString(p)
}
return buffer.Bytes(), nil
}