-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhasher.go
68 lines (48 loc) · 1.34 KB
/
hasher.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
/*
password hasher, follows the Mozilla security guide.
blog: https://blog.mozilla.org/webdev/2012/06/08/lets-talk-about-password-storage/
full guide: https://wiki.mozilla.org/WebAppSec/Secure_Coding_Guidelines#Password_Storage
*/
package main
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha512"
"encoding/hex"
"errors"
"io"
"golang.org/x/crypto/bcrypt"
)
const (
KEYLENGTH = 32
)
var ErrGeneratingSalt = errors.New("error generating salt")
var ErrGeneratingBcrypt = errors.New("error generating bcrypt hash")
type Hasher struct{}
func (h *Hasher) NewHash(password string) (string, string, error) {
b := make([]byte, KEYLENGTH)
_, err := io.ReadFull(rand.Reader, b)
if err != nil {
return "", "", ErrGeneratingSalt
}
secret := []byte(password)
salt := b
hmh := hmac.New(sha512.New, salt)
hmh.Write(secret)
hmac_hash := hmh.Sum(nil)
hmh.Reset()
p, err := bcrypt.GenerateFromPassword(hmac_hash, 16)
if err != nil {
return "", "", ErrGeneratingBcrypt
}
return string(p), hex.EncodeToString(salt), nil
}
func (h *Hasher) CompareHash(hashed_password string, salt string, password string) error {
secret := []byte(password)
s, _ := hex.DecodeString(salt)
hmh := hmac.New(sha512.New, s)
hmh.Write(secret)
hmac_password := hmh.Sum(nil)
hmh.Reset()
return bcrypt.CompareHashAndPassword([]byte(hashed_password), hmac_password)
}