-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrand.go
39 lines (31 loc) · 1.02 KB
/
rand.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 webutils
import (
"crypto/rand"
"encoding/hex"
"github.com/pkg/errors"
)
// RAND strings
const charset = "abcdefghijklmnopqrstuvwxyz" +
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
// SecureRandomString generates a secure random string of a given length, returning a string of
// that same length built with characters from the charset above.
func SecureRandomString(n int) (string, error) {
bytes := make([]byte, n)
if _, err := rand.Read(bytes); err != nil {
return "", errors.Wrap(err, "rand.Read")
}
for i := range bytes {
bytes[i] = charset[int(bytes[i])%len(charset)]
}
return string(bytes), nil
}
// SecureRandomHex returns a secure random hex of a given length times two.
// IE: if you pass in length of 5, you will get a hex encoded string of length 10 back.
// There is no way to generate odd numbered strings.
func SecureRandomHex(n int) (string, error) {
bytes := make([]byte, n)
if _, err := rand.Read(bytes); err != nil {
return "", errors.Wrap(err, "rand.Read")
}
return hex.EncodeToString(bytes), nil
}