-
Notifications
You must be signed in to change notification settings - Fork 117
/
util.go
31 lines (27 loc) · 693 Bytes
/
util.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
package keychain
import (
"crypto/rand"
"encoding/base32"
"strings"
)
var randRead = rand.Read
// RandomID returns random ID (base32) string with prefix, using 256 bits as
// recommended by tptacek: https://gist.github.com/tqbf/be58d2d39690c3b366ad
func RandomID(prefix string) (string, error) {
buf, err := RandBytes(32)
if err != nil {
return "", err
}
str := base32.StdEncoding.EncodeToString(buf)
str = strings.ReplaceAll(str, "=", "")
str = prefix + str
return str, nil
}
// RandBytes returns random bytes of length
func RandBytes(length int) ([]byte, error) {
buf := make([]byte, length)
if _, err := randRead(buf); err != nil {
return nil, err
}
return buf, nil
}