crypto.NewBcryptCrypto   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
dl 0
loc 2
rs 10
c 0
b 0
f 0
nop 1
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