base-golang/pkg/bcrypt/password.go

40 lines
725 B
Go
Raw Normal View History

2024-07-23 10:23:43 +08:00
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
}