1
|
|
|
package crypto |
2
|
|
|
|
3
|
|
|
import ( |
4
|
|
|
"github.com/pkg/errors" |
5
|
|
|
"golang.org/x/crypto/bcrypt" |
6
|
|
|
) |
7
|
|
|
|
8
|
|
|
// BcryptCrypto is the struct that holds the bcrypt crypto methods. |
9
|
|
|
type BcryptCrypto struct { |
10
|
|
|
Cost int |
11
|
|
|
} |
12
|
|
|
|
13
|
|
|
// NewBcryptCrypto returns a new BcryptCrypto. |
14
|
|
|
func NewBcryptCrypto(cost int) *BcryptCrypto { |
15
|
|
|
return &BcryptCrypto{Cost: cost} |
16
|
|
|
} |
17
|
|
|
|
18
|
|
|
// Hash hashes a password using the bcrypt algorithm. |
19
|
|
|
// password is the plaintext password to hash. |
20
|
|
|
// Returns the hashed password, or an error on failure. |
21
|
|
|
// The cost is set in the config file. |
22
|
|
|
// |
23
|
|
|
// see: https://godoc.org/golang.org/x/crypto/bcrypt |
24
|
|
|
// see: utils/config.go for the default cost. |
25
|
|
|
func (b *BcryptCrypto) Hash(password string) ([]byte, error) { |
26
|
|
|
key, err := bcrypt.GenerateFromPassword([]byte(password), b.Cost) |
27
|
|
|
if err != nil { |
28
|
|
|
return []byte(""), err |
29
|
|
|
} |
30
|
|
|
return key, nil |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
// Verify compares a bcrypt hashed password with its possible plaintext equivalent. |
34
|
|
|
// password is the plaintext password to verify. |
35
|
|
|
// hash is the bcrypt hashed password. |
36
|
|
|
// Returns nil on success, or an error on failure. |
37
|
|
|
// Returns true if the password matches, false if it does not. |
38
|
|
|
func (*BcryptCrypto) Verify(password string, hash []byte) (bool, error) { |
39
|
|
|
err := bcrypt.CompareHashAndPassword(hash, []byte(password)) |
40
|
|
|
if err != nil { |
41
|
|
|
return false, errors.Wrap(err, errors.New("error comparing bcrypt hash").Error()) |
42
|
|
|
} |
43
|
|
|
return true, nil |
44
|
|
|
} |
45
|
|
|
|