yunzer_go/server/services/crypto.go
2025-11-06 15:56:29 +08:00

52 lines
1.2 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package services
import (
"crypto/rand"
"encoding/base64"
"golang.org/x/crypto/scrypt"
)
// generateUserSalt 生成随机盐值(用于用户密码)
func generateUserSalt() (string, error) {
salt := make([]byte, 16)
_, err := rand.Read(salt)
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(salt), nil
}
// hashUserPassword 使用scrypt算法对密码进行加密用于用户密码
func hashUserPassword(password, salt string) (string, error) {
saltBytes, err := base64.URLEncoding.DecodeString(salt)
if err != nil {
return "", err
}
const (
N = 16384
r = 8
p = 1
)
hashBytes, err := scrypt.Key([]byte(password), saltBytes, N, r, p, 32)
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(hashBytes), nil
}
// verifyUserPassword 验证用户密码是否正确
func verifyUserPassword(password, salt, storedHash string) bool {
hash, err := hashUserPassword(password, salt)
if err != nil {
return false
}
return hash == storedHash
}
// hashPassword 通用密码加密函数(用于员工密码,与用户密码使用相同算法)
func hashPassword(password, salt string) (string, error) {
return hashUserPassword(password, salt)
}