-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcredentials.go
72 lines (60 loc) · 1.68 KB
/
credentials.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package epitome
import (
"crypto/rand"
"github.com/pkg/errors"
"golang.org/x/crypto/bcrypt"
)
// Credentials contains a user's credentials.
type Credentials struct {
Password []byte
Salt []byte
}
const (
saltLen = 16
bcryptCost = 14
)
// ErrPasswordHashingFailed is returned when an error occurrs during the
// password hashing process.
var ErrPasswordHashingFailed = errors.New("failed to hash password")
// GenerateCredentials takes a password and generates a new set of credentials.
func GenerateCredentials(password string) (*Credentials, error) {
hash, salt, err := hashPassword(password)
if err != nil {
return nil, ErrPasswordHashingFailed
}
return &Credentials{
Password: hash,
Salt: salt,
}, nil
}
func hashPassword(p string) (hash []byte, salt []byte, err error) {
// make salt
salt = make([]byte, saltLen)
_, err = rand.Read(salt)
if err != nil {
return nil, nil, errors.Wrap(err, "error generating salt")
}
// prepend salt to password
data := prependSalt(salt, p)
// hash salt and password
hash, err = bcrypt.GenerateFromPassword(data, bcryptCost)
if err != nil {
return nil, nil, errors.Wrap(err, "error hashing data")
}
return hash, salt, err
}
func prependSalt(salt []byte, password string) []byte {
data := make([]byte, len(salt)+len(password))
copy(data, salt)
for i := 0; i < len(password); i++ {
data[saltLen+i] = password[i]
}
return data
}
// MatchPassword compares a user's hashed password agsinst the given password
// and returns whether they match or not.
func (c *Credentials) MatchPassword(password string) bool {
data := prependSalt(c.Salt, password)
err := bcrypt.CompareHashAndPassword(c.Password, data)
return err == nil
}