-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.go
71 lines (58 loc) · 1.27 KB
/
crypto.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
package common
import (
"bytes"
"crypto/rand"
"encoding/base64"
"fmt"
"golang.org/x/crypto/scrypt"
)
const Version = 1
const hashFormat = "$%d:%x:%d:%d:%d:%s"
func CreateHash(secretKey string) (string, error) {
const (
n = 15
r = 8
p = 1
keyLen = 64
saltLen = 8
)
salt := make([]byte, saltLen)
_, err := rand.Read(salt)
if err != nil {
return "", err
}
dk, err := scrypt.Key([]byte(secretKey), salt, 1<<n, r, p, keyLen)
if err != nil {
return "", err
}
enc := base64.RawStdEncoding.EncodeToString(dk)
hash := fmt.Sprintf(hashFormat, Version, salt, n, r, p, enc)
return hash, nil
}
func VerifyHash(hash, secretKey string) error {
var (
version, n uint
r, p int
enc string
salt []byte
)
_, err := fmt.Sscanf(hash, hashFormat, &version, &salt, &n, &r, &p, &enc)
if err != nil {
return err
}
if version != Version {
return fmt.Errorf("hash version %d does not match package version %d", version, Version)
}
dk, err := base64.RawStdEncoding.DecodeString(enc)
if err != nil {
return err
}
verify, err := scrypt.Key([]byte(secretKey), salt, 1<<n, r, p, len(dk))
if err != nil {
return err
}
if !bytes.Equal(dk, verify) {
return fmt.Errorf("secretKey hash does not match")
}
return nil
}