forked from bearded-web/bearded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bcrypt.go
39 lines (32 loc) · 761 Bytes
/
bcrypt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package passlib
import "golang.org/x/crypto/bcrypt"
const bcryptName = "bcrypt"
type BcryptAlgo struct {
cost int
}
func NewBcrypt(cost int) *BcryptAlgo {
if cost == 0 {
cost = bcrypt.DefaultCost
}
return &BcryptAlgo{cost}
}
func (a *BcryptAlgo) Name() string {
return bcryptName
}
func (a *BcryptAlgo) Encrypt(password string) (string, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(password), a.cost)
if err != nil {
return "", err
} else {
return string(hash), nil
}
}
func (a *BcryptAlgo) Verify(password, hash string) (bool, error) {
h := []byte(hash)
err := bcrypt.CompareHashAndPassword(h, []byte(password))
verified := err == nil
if err == bcrypt.ErrMismatchedHashAndPassword {
err = nil
}
return verified, err
}