Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
alist-org
GitHub Repository: alist-org/alist
Path: blob/main/pkg/sign/hmac.go
1560 views
1
package sign
2
3
import (
4
"crypto/hmac"
5
"crypto/sha256"
6
"encoding/base64"
7
"io"
8
"strconv"
9
"strings"
10
"time"
11
)
12
13
type HMACSign struct {
14
SecretKey []byte
15
}
16
17
func (s HMACSign) Sign(data string, expire int64) string {
18
h := hmac.New(sha256.New, s.SecretKey)
19
expireTimeStamp := strconv.FormatInt(expire, 10)
20
_, err := io.WriteString(h, data+":"+expireTimeStamp)
21
if err != nil {
22
return ""
23
}
24
25
return base64.URLEncoding.EncodeToString(h.Sum(nil)) + ":" + expireTimeStamp
26
}
27
28
func (s HMACSign) Verify(data, sign string) error {
29
signSlice := strings.Split(sign, ":")
30
// check whether contains expire time
31
if signSlice[len(signSlice)-1] == "" {
32
return ErrExpireMissing
33
}
34
// check whether expire time is expired
35
expires, err := strconv.ParseInt(signSlice[len(signSlice)-1], 10, 64)
36
if err != nil {
37
return ErrExpireInvalid
38
}
39
// if expire time is expired, return error
40
if expires < time.Now().Unix() && expires != 0 {
41
return ErrSignExpired
42
}
43
// verify sign
44
if s.Sign(data, expires) != sign {
45
return ErrSignInvalid
46
}
47
return nil
48
}
49
50
func NewHMACSign(secret []byte) Sign {
51
return HMACSign{SecretKey: secret}
52
}
53
54