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