You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
36 lines
762 B
Go
36 lines
762 B
Go
1 month ago
|
// 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
|
||
|
}
|