56 lines
1.2 KiB
Go
56 lines
1.2 KiB
Go
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)
|
|
}
|