-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbcrypt.go
63 lines (50 loc) · 1.25 KB
/
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package password
import (
"fmt"
"golang.org/x/crypto/bcrypt"
)
type BcryptPassword struct {
Cost int
plaintext []byte
password []byte
}
func NewBcryptPlaintext(plaintext string, opts ...BcryptPasswordOption) (Plaintext, error) {
p := &BcryptPassword{
Cost: bcrypt.DefaultCost,
plaintext: []byte(plaintext),
password: nil,
}
for _, opt := range opts {
opt(p)
}
return p, nil
}
func (p *BcryptPassword) Password() (string, error) {
if p.password == nil {
password, err := bcrypt.GenerateFromPassword(p.plaintext, p.Cost)
if err != nil {
return "", err
}
p.password = password
}
return string(p.password), nil
}
func NewBcryptPassword(password string) Password {
return &BcryptPassword{
password: []byte(password),
}
}
// Verify verifies the plaintext with the password hash.
func (p *BcryptPassword) Verify(plaintext string) error {
if err := bcrypt.CompareHashAndPassword(p.password, []byte(plaintext)); err != nil {
return fmt.Errorf("%w: %v", ErrMissmatchedPassword, err)
}
return nil
}
// BcryptPasswordOption is a function that can be used to configure a BcryptPassword.
type BcryptPasswordOption func(*BcryptPassword)
func BcryptCost(cost int) BcryptPasswordOption {
return func(p *BcryptPassword) {
p.Cost = cost
}
}