-
Notifications
You must be signed in to change notification settings - Fork 0
/
securiry.go
executable file
·93 lines (78 loc) · 2.2 KB
/
securiry.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 support
import (
beego "github.com/beego/beego/v2/server/web"
"github.com/dgrijalva/jwt-go"
"encoding/base64"
"crypto/sha256"
"crypto/sha1"
"math/rand"
"encoding/hex"
"time"
)
func TextToSha1(text string) string{
bv := []byte(text)
hasher := sha1.New()
hasher.Write(bv)
sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
return sha
}
func TextToSha1Hex(text string) string{
bv := []byte(text)
hasher := sha1.New()
hasher.Write(bv)
sha := hex.EncodeToString(hasher.Sum(nil))
return sha
}
func IsSameHash(hash string , text string) bool {
newHash := TextToSha1(text)
return newHash == hash
}
func IsSameHashHex(hash string , text string) bool {
newHash := TextToSha1Hex(text)
return newHash == hash
}
func TextToSha256(text string) string{
bv := []byte(text)
hasher := sha256.New()
hasher.Write(bv)
sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
return sha
}
func TextToSha256Hex(text string) string{
bv := []byte(text)
hasher := sha256.New()
hasher.Write(bv)
sha := hex.EncodeToString(hasher.Sum(nil))
return sha
}
func IsSameHashSha256(hash string , text string) bool {
newHash := TextToSha256(text)
return newHash == hash
}
func IsSameHashSha256Hex(hash string , text string) bool {
newHash := TextToSha256Hex(text)
return newHash == hash
}
func GenereteApiToken(id int64, uuid string, password string, expirationDate time.Time) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"user_id": id,
"user_uuid": uuid,
"user_password": password,
"expiration_date": expirationDate.Unix(),
})
secret, _ := beego.AppConfig.String("jwt_token_secret")
hmacSampleSecret := []byte(secret)
return token.SignedString(hmacSampleSecret)
}
func GenereteToken(password string, expirationDate time.Time) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"password": password,
"expiration_date": expirationDate.Unix(),
})
secret, _ := beego.AppConfig.String("jwt_token_secret")
hmacSampleSecret := []byte(secret)
return token.SignedString(hmacSampleSecret)
}
func GenerateCode(min int, max int) int {
return min + rand.Intn(max-min)
}