crypto.*BcryptCrypto.Hash   A
last analyzed

Complexity

Conditions 2

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nop 1
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
package crypto
2
3
import (
4
	"github.com/corentings/kafejo/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
12
// Hash hashes a password using the bcrypt algorithm
13
// password is the plaintext password to hash.
14
// Returns the hashed password, or an error on failure.
15
// The cost is set in the config file.
16
//
17
// see: https://godoc.org/golang.org/x/crypto/bcrypt
18
// see: utils/config.go for the default cost
19
func (*BcryptCrypto) Hash(password string) ([]byte, error) {
20
	key, err := bcrypt.GenerateFromPassword([]byte(password), config.BCryptCost)
21
	if err != nil {
22
		return []byte(""), err
23
	}
24
	return key, nil
25
}
26
27
// Verify compares a bcrypt hashed password with its possible plaintext equivalent.
28
// password is the plaintext password to verify.
29
// hash is the bcrypt hashed password.
30
// Returns nil on success, or an error on failure.
31
// Returns true if the password matches, false if it does not.
32
func (*BcryptCrypto) Verify(password string, hash []byte) (bool, error) {
33
	err := bcrypt.CompareHashAndPassword(hash, []byte(password))
34
	if err != nil {
35
		return false, errors.Wrap(err, errors.New("error comparing bcrypt hash").Error())
36
	}
37
	return true, nil
38
}
39