-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth_timebase.go
52 lines (47 loc) · 1.09 KB
/
auth_timebase.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
package utils
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"time"
)
func GetTimebaseUnix(seconds int64) int64 {
t := time.Now().Unix()
return t - (t % seconds)
}
func GenerateSignature(key string, second ...int64) (signature string) {
mac := hmac.New(sha256.New, []byte(key))
var t int64
if len(second) > 0 {
t = GetTimebaseUnix(second[0])
} else {
t = GetTimebaseUnix(30)
}
mac.Write([]byte(fmt.Sprintf("%d", t)))
sign := mac.Sum(nil)
signature = hex.EncodeToString(sign)
return
}
func VerifySignature(key string, signature string, second ...int64) bool {
var t, sec int64
if len(second) > 0 {
sec = second[0]
t = GetTimebaseUnix(sec)
} else {
sec = 30
t = GetTimebaseUnix(sec)
}
sign := GenerateSignature(key, t)
if sign == signature {
return true
} else {
return compatibilityBackward(key, signature, t, sec)
}
}
func compatibilityBackward(key string, signature string, t int64, sec int64) bool {
mac := hmac.New(sha256.New, []byte(key))
mac.Write([]byte(fmt.Sprintf("%d", t-sec)))
sign := mac.Sum(nil)
return hex.EncodeToString(sign) == signature
}