-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
rnd.go
44 lines (33 loc) · 791 Bytes
/
rnd.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
package unchained
import (
crand "crypto/rand"
"math/big"
"math/rand"
)
const (
allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
allowedCharsSize = len(allowedChars)
maxInt = 1<<63 - 1
)
type source struct{}
func (s *source) Int63() int64 {
return int64(s.Uint64() & ^uint64(1<<63))
}
func (s *source) Uint64() uint64 {
i, err := crand.Int(crand.Reader, big.NewInt(maxInt))
if err != nil {
panic(err)
}
return i.Uint64()
}
func (s *source) Seed(seed int64) {}
// GetRandomString returns a securely generated random string.
func GetRandomString(length int) string {
b := make([]byte, length)
rnd := rand.New(&source{})
for i := range b {
c := rnd.Intn(allowedCharsSize)
b[i] = allowedChars[c]
}
return string(b)
}