1
|
|
|
package crypto |
2
|
|
|
|
3
|
|
|
const DefaultBcryptCost = 10 |
4
|
|
|
|
5
|
|
|
var cryptoHelper = Crypto{ |
6
|
|
|
crypto: NewBcryptCrypto(DefaultBcryptCost), |
7
|
|
|
} |
8
|
|
|
|
9
|
|
|
func InitCrypto(crypto ICrypto) { |
10
|
|
|
cryptoHelper = Crypto{crypto: crypto} |
11
|
|
|
} |
12
|
|
|
|
13
|
|
|
func GetCrypto() Crypto { |
14
|
|
|
return cryptoHelper |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
// ICrypto is the interface for the crypto methods |
18
|
|
|
// It's used to abstract the crypto methods used in the application |
19
|
|
|
// so that they can be easily swapped out if needed |
20
|
|
|
type ICrypto interface { |
21
|
|
|
// Hash hashes a password using the configured crypto method |
22
|
|
|
Hash(password string) ([]byte, error) |
23
|
|
|
// Verify compares a crypto hashed password with its possible plaintext equivalent |
24
|
|
|
Verify(password string, hash []byte) (bool, error) |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
// Crypto is the struct that holds the crypto methods |
28
|
|
|
type Crypto struct { |
29
|
|
|
crypto ICrypto |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
// Hash hashes a password using the configured crypto method |
33
|
|
|
// password is the plaintext password to hash. |
34
|
|
|
// Returns the hashed password, or an error on failure. |
35
|
|
|
func (c Crypto) Hash(password string) ([]byte, error) { |
36
|
|
|
return c.crypto.Hash(password) //nolint:wrapcheck |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
// Verify compares a crypto hashed password with its possible plaintext equivalent |
40
|
|
|
// password is the plaintext password to verify. |
41
|
|
|
// hash is the bcrypt hashed password. |
42
|
|
|
// Returns nil on success, or an error on failure. |
43
|
|
|
// Returns true if the password matches, false if it does not. |
44
|
|
|
func (c Crypto) Verify(password string, hash []byte) (bool, error) { |
45
|
|
|
return c.crypto.Verify(password, hash) //nolint:wrapcheck |
46
|
|
|
} |
47
|
|
|
|