-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbcrypt.go
More file actions
61 lines (52 loc) · 1.27 KB
/
bcrypt.go
File metadata and controls
61 lines (52 loc) · 1.27 KB
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
package passwordtool
import (
"golang.org/x/crypto/bcrypt"
)
// TODO: cost setup function, run when user call
var bcryptDefaultCost = bcrypt.DefaultCost
// Bcrypt strategy
type Bcrypt struct {
Cost int
}
func (Bcrypt) String() string {
return "bcrypt"
}
func (hc Bcrypt) cost() int {
if hc.Cost <= 0 {
return bcryptDefaultCost
}
return hc.Cost
}
func (hc Bcrypt) hash(password string) (string, error) {
hashed, err := bcrypt.GenerateFromPassword([]byte(password), hc.cost())
return string(hashed), err
}
func (hc Bcrypt) compare(hashedPassword string, password string) error {
err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
if err == nil {
return nil
}
if err == bcrypt.ErrMismatchedHashAndPassword {
return ErrMismatched
}
if err == bcrypt.ErrHashTooShort {
return ErrInvalidHash
}
return err
}
// Hash hashes password
func (hc Bcrypt) Hash(password string) (string, error) {
hashed, err := hc.hash(password)
if err != nil {
return "", err
}
return hc.String() + "$" + string(hashed), nil
}
// Compare compares hashed with password
func (hc Bcrypt) Compare(hashedPassword string, password string) error {
s, hashed := extract(hashedPassword)
if s != hc.String() {
return ErrInvalidHash
}
return hc.compare(hashed, password)
}