123456789101112131415161718192021222324252627282930313233343536373839 |
- package bcrypt
- import (
- "fmt"
- "golang.org/x/crypto/bcrypt"
- )
- var _ Password = (*password)(nil)
- type Password interface {
- i()
- Generate(pwd string) string
- Validate(pwd, hash string) bool
- }
- type password struct {
- cost int
- }
- func (p *password) i() {}
- func NewPassword(cost int) (Password, error) {
- if cost < bcrypt.MinCost || cost > bcrypt.MaxCost {
- return nil, fmt.Errorf("cost out of range")
- }
- return &password{
- cost: cost,
- }, nil
- }
- func (p *password) Generate(pwd string) string {
- hash, _ := bcrypt.GenerateFromPassword([]byte(pwd), p.cost)
- return string(hash)
- }
- func (p *password) Validate(pwd, hash string) bool {
- err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(pwd))
- return err == nil
- }
|