1
|
|
|
package crypto |
2
|
|
|
|
3
|
|
|
import "sync" |
4
|
|
|
|
5
|
|
|
const DefaultBcryptCost = 10 |
6
|
|
|
|
7
|
|
|
// HelperSingleton is the struct that holds the crypto helper. |
8
|
|
|
type HelperSingleton struct { |
9
|
|
|
cryptoHelper Crypto |
10
|
|
|
} |
11
|
|
|
|
12
|
|
|
var ( |
13
|
|
|
once sync.Once //nolint:gochecknoglobals //Singleton |
14
|
|
|
instance *HelperSingleton //nolint:gochecknoglobals //Singleton |
15
|
|
|
) |
16
|
|
|
|
17
|
|
|
func GetCryptoHelperInstance() *HelperSingleton { |
18
|
|
|
once.Do(func() { |
19
|
|
|
instance = &HelperSingleton{ |
20
|
|
|
cryptoHelper: Crypto{ |
21
|
|
|
Crypto: NewBcryptCrypto(DefaultBcryptCost), |
22
|
|
|
}, |
23
|
|
|
} |
24
|
|
|
}) |
25
|
|
|
return instance |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
func (c *HelperSingleton) GetCryptoHelper() Crypto { |
29
|
|
|
return c.cryptoHelper |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
func (c *HelperSingleton) SetCryptoHelper(crypto ICrypto) { |
33
|
|
|
c.cryptoHelper.Crypto = crypto |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
// ICrypto is the interface for the crypto methods |
37
|
|
|
// It's used to abstract the crypto methods used in the application |
38
|
|
|
// so that they can be easily swapped out if needed. |
39
|
|
|
type ICrypto interface { |
40
|
|
|
// Hash hashes a password using the configured crypto method |
41
|
|
|
Hash(password string) ([]byte, error) |
42
|
|
|
// Verify compares a crypto hashed password with its possible plaintext equivalent |
43
|
|
|
Verify(password string, hash []byte) (bool, error) |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
// Crypto is the struct that holds the crypto methods. |
47
|
|
|
type Crypto struct { |
48
|
|
|
Crypto ICrypto |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
// Hash hashes a password using the configured crypto method |
52
|
|
|
// password is the plaintext password to hash. |
53
|
|
|
// Returns the hashed password, or an error on failure. |
54
|
|
|
func (c Crypto) Hash(password string) ([]byte, error) { |
55
|
|
|
return c.Crypto.Hash(password) |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
// Verify compares a crypto hashed password with its possible plaintext equivalent |
59
|
|
|
// password is the plaintext password to verify. |
60
|
|
|
// hash is the bcrypt hashed password. |
61
|
|
|
// Returns nil on success, or an error on failure. |
62
|
|
|
// Returns true if the password matches, false if it does not. |
63
|
|
|
func (c Crypto) Verify(password string, hash []byte) (bool, error) { |
64
|
|
|
return c.Crypto.Verify(password, hash) |
65
|
|
|
} |
66
|
|
|
|