init repo

This commit is contained in:
VaalaCat
2024-08-28 00:02:28 +08:00
committed by vaalacat
commit 13148b95e3
97 changed files with 10214 additions and 0 deletions

15
utils/base64.go Normal file
View File

@@ -0,0 +1,15 @@
package utils
import "encoding/base64"
func Base64Encode(s string) string {
return base64.StdEncoding.EncodeToString([]byte(s))
}
func Base64Decode(s string) string {
data, err := base64.StdEncoding.DecodeString(s)
if err != nil {
return ""
}
return string(data)
}

13
utils/crypto.go Normal file
View File

@@ -0,0 +1,13 @@
package utils
import (
"crypto/hmac"
"crypto/sha256"
)
func ValidMAC(message, messageMAC, key []byte) bool {
mac := hmac.New(sha256.New, key)
mac.Write(message)
expectedMAC := mac.Sum(nil)
return hmac.Equal(messageMAC, expectedMAC)
}

21
utils/idgen.go Normal file
View File

@@ -0,0 +1,21 @@
package utils
import (
"strings"
"github.com/google/uuid"
)
func GenerateUID() string {
return uuid.New().String()
}
func L32UID() string {
o := GenerateUID()
n := strings.Replace(o, "-", "", -1)
return n
}
func GenCode() string {
return strings.ToUpper(L32UID()[0:6])
}

65
utils/jwt.go Normal file
View File

@@ -0,0 +1,65 @@
package utils
import (
"errors"
"github.com/golang-jwt/jwt/v5"
)
// @secretKey: JWT 加解密密钥
// @iat: 时间戳
// @seconds: 过期时间,单位秒
// @payload: 数据载体
func GetJwtToken(secretKey string, iat, seconds int64, payload string) (string, error) {
claims := make(jwt.MapClaims)
claims["exp"] = iat + seconds
claims["iat"] = iat
claims["payload"] = payload
token := jwt.New(jwt.SigningMethodHS256)
token.Claims = claims
return token.SignedString([]byte(secretKey))
}
// @secretKey: JWT 加解密密钥
// @iat: 时间戳
// @seconds: 过期时间,单位秒
// @payload: 数据载体
func GetJwtTokenFromMap(secretKey string, iat, seconds int64, payload map[string]string) (string, error) {
claims := make(jwt.MapClaims)
claims["exp"] = iat + seconds
claims["iat"] = iat
for k, v := range payload {
claims[k] = v
}
token := jwt.New(jwt.SigningMethodHS256)
token.Claims = claims
return token.SignedString([]byte(secretKey))
}
// @secretKey: JWT 加解密密钥
// @token: JWT Token 的字符串
func ValidateJwtToken(secretKey, token string) (bool, error) {
t, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
return []byte(secretKey), nil
})
if err != nil {
return false, err
}
return t.Valid, nil
}
func ParseToken(secretKey, tokenStr string) (u jwt.MapClaims, err error) {
token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
return []byte(secretKey), nil
})
if err != nil {
return nil, errors.New("couldn't handle this token")
}
if t, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
return t, nil
}
return nil, errors.New("couldn't handle this token")
}