pkg/crypto/bcrypt.go   A
last analyzed

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 18
dl 0
loc 43
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A crypto.NewBcryptCrypto 0 2 1
A crypto.*BcryptCrypto.Hash 0 6 2
A crypto.*BcryptCrypto.Verify 0 6 2
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