// password.go package crypto import "golang.org/x/crypto/bcrypt" type PasswordHashService struct { } func NewPasswordHashService() *PasswordHashService { return &PasswordHashService{} } // Hash 使用 bcrypt 算法对密码进行加密 func (s *PasswordHashService) Hash(password string) (string, error) { if password == "" { return "", nil } hashedBytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) if err != nil { return "", err } return string(hashedBytes), nil } // Verify 验证密码是否匹配 func (s *PasswordHashService) Verify(password, hash string) bool { if password == "" || hash == "" { return false } err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) return err == nil }