first commit
This commit is contained in:
39
pkg/bcrypt/password.go
Normal file
39
pkg/bcrypt/password.go
Normal file
@ -0,0 +1,39 @@
|
||||
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
|
||||
}
|
Reference in New Issue
Block a user