password.go 725 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package bcrypt
  2. import (
  3. "fmt"
  4. "golang.org/x/crypto/bcrypt"
  5. )
  6. var _ Password = (*password)(nil)
  7. type Password interface {
  8. i()
  9. Generate(pwd string) string
  10. Validate(pwd, hash string) bool
  11. }
  12. type password struct {
  13. cost int
  14. }
  15. func (p *password) i() {}
  16. func NewPassword(cost int) (Password, error) {
  17. if cost < bcrypt.MinCost || cost > bcrypt.MaxCost {
  18. return nil, fmt.Errorf("cost out of range")
  19. }
  20. return &password{
  21. cost: cost,
  22. }, nil
  23. }
  24. func (p *password) Generate(pwd string) string {
  25. hash, _ := bcrypt.GenerateFromPassword([]byte(pwd), p.cost)
  26. return string(hash)
  27. }
  28. func (p *password) Validate(pwd, hash string) bool {
  29. err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(pwd))
  30. return err == nil
  31. }