package corelib import ( "crypto/md5" "encoding/hex" "golang.org/x/crypto/bcrypt" ) // Md5Hash md5加密 func Md5Hash(data string) string { md5Hash := md5.New() md5Hash.Write([]byte(data)) return hex.EncodeToString(md5Hash.Sum(nil)) } // HashPassword 使用Bcrypt哈希密码和盐值 func HashPassword(password, salt string) (string, error) { var ( err error hashedPassword []byte ) passwordWithSalt := append([]byte(password), []byte(salt)...) if hashedPassword, err = bcrypt.GenerateFromPassword(passwordWithSalt, bcrypt.DefaultCost); err != nil { return "", err } return string(hashedPassword), nil } // ComparePasswords 验证密码是否匹配哈希值和盐值 func ComparePasswords(hashedPassword, userInput, salt string) bool { passwordWithSalt := append([]byte(userInput), []byte(salt)...) err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), passwordWithSalt) return err == nil }