-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
52 lines (47 loc) · 1.28 KB
/
utils.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
package password
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strings"
"golang.org/x/crypto/scrypt"
)
func EncryptScrypt(passwordPlainText string) (string, error) {
salt := make([]byte, 16)
_, err := rand.Read(salt)
if err != nil {
return "", err
}
return encryptInternal([]byte(passwordPlainText), salt)
}
func encryptInternal(passwordPlainText, salt []byte) (string, error) {
pw, err := scrypt.Key(passwordPlainText, salt, 1<<15, 8, 1, 32)
if err != nil {
return "", err
}
return fmt.Sprint(base64.StdEncoding.EncodeToString(pw)) + "." + fmt.Sprint(base64.StdEncoding.EncodeToString(salt)), nil
}
func VerifyScrypt(password string, passwordPlainText string) (bool, error) {
idx := strings.IndexAny(password, ".")
if idx == -1 {
return false, errors.New("cannot find dot char when decrypting scrypt password")
}
if idx+1 == len(password) {
return false, errors.New("no salt found when decrypting scrypt password")
}
salt, err := base64.StdEncoding.DecodeString(password[idx+1:])
if err != nil {
return false, err
}
pw, err := encryptInternal([]byte(passwordPlainText), salt)
if err != nil {
return false, err
}
if subtle.ConstantTimeCompare([]byte(pw), []byte(password)) == 1 {
return true, nil
} else {
return false, nil
}
}