feat():learning后台管理项目初始化
This commit is contained in:
55
pkg/utils/crypto.go
Normal file
55
pkg/utils/crypto.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"math/big"
|
||||
)
|
||||
|
||||
// MD5Hash 计算MD5哈希
|
||||
func MD5Hash(text string) string {
|
||||
hash := md5.Sum([]byte(text))
|
||||
return hex.EncodeToString(hash[:])
|
||||
}
|
||||
|
||||
// SHA256Hash 计算SHA256哈希
|
||||
func SHA256Hash(text string) string {
|
||||
hash := sha256.Sum256([]byte(text))
|
||||
return hex.EncodeToString(hash[:])
|
||||
}
|
||||
|
||||
// GenerateRandomString 生成指定长度的随机字符串
|
||||
func GenerateRandomString(length int) (string, error) {
|
||||
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||
b := make([]byte, length)
|
||||
for i := range b {
|
||||
num, err := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
b[i] = charset[num.Int64()]
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
// GenerateSalt 生成盐值
|
||||
func GenerateSalt() (string, error) {
|
||||
return GenerateRandomString(16)
|
||||
}
|
||||
|
||||
// HashPassword 使用盐值哈希密码
|
||||
func HashPassword(password, salt string) string {
|
||||
return SHA256Hash(password + salt)
|
||||
}
|
||||
|
||||
// VerifyPassword 验证密码
|
||||
func VerifyPassword(password, salt, hash string) bool {
|
||||
return HashPassword(password, salt) == hash
|
||||
}
|
||||
|
||||
// GenerateToken 生成随机token
|
||||
func GenerateToken() (string, error) {
|
||||
return GenerateRandomString(32)
|
||||
}
|
||||
Reference in New Issue
Block a user