-
Notifications
You must be signed in to change notification settings - Fork 0
/
random.go
46 lines (41 loc) · 1.28 KB
/
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
40
41
42
43
44
45
46
package crypto
import "crypto/rand"
// Random sources.
var (
SourceNum = []byte("0123456789")
SourceAlphaLower = []byte("abcdefghijklmnopqrstuvwxyz")
SourceAlphaUpper = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
SourceAlphaNumLower = []byte("abcdefghijklmnopqrstuvwxyz0123456789")
SourceAlphaNumUpper = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
SourceAlpha = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
SourceAlphaNum = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
SourceAll = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_+=~`[]{}|\\:;\"'<>,.?/")
)
// Random returns random bytes.
func Random(n int) ([]byte, error) {
var bb = make([]byte, n)
_, err := rand.Read(bb)
if err != nil {
panic(err)
}
return bb, nil
}
// RandomSourced returns a random string only containing bytes from a source string.
func RandomSourced(src []byte, n int) ([]byte, error) {
bb, err := Random(n)
if err != nil {
return nil, err
}
for i, b := range bb {
bb[i] = src[b%byte(len(src))]
}
return bb, nil
}
// RandomKey returns a random 32 bytes alphanumeric key.
func RandomKey() string {
k, err := RandomSourced(SourceAlphaNum, 32)
if err != nil {
panic(err)
}
return string(k)
}