-
Notifications
You must be signed in to change notification settings - Fork 0
/
random.go
39 lines (35 loc) · 920 Bytes
/
random.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
package foxkit
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
)
func RandomBytes(length uint32) ([]byte, error) {
b := make([]byte, length)
_, err := rand.Read(b)
return b, err
}
func RandomString(length uint32) (string, error) {
raw, err := RandomBytes(length)
if err != nil {
return "", err
}
return base64.RawStdEncoding.EncodeToString(raw), nil
}
// decodes the strings and cryptographically compares them, returns true if they match
func RandomStringCompare(stringOne, stringTwo *string) (bool, error) {
// decode both strings
stringOneDec, err := base64.RawStdEncoding.DecodeString(*stringOne)
if err != nil {
return false, err
}
stringTwoDec, err := base64.RawStdEncoding.DecodeString(*stringTwo)
if err != nil {
return false, err
}
// securely compare both strings
if subtle.ConstantTimeCompare(stringOneDec, stringTwoDec) != 1 {
return false, nil
}
return true, nil
}