/
random.go
68 lines (56 loc) · 1.43 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package utils
import (
crand "crypto/rand"
"math/big"
"math/rand"
"os"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano() + int64(os.Getpid()))
}
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
// NewRand new individual random to aviod global mutex
func NewRand() *rand.Rand {
return rand.New(rand.NewSource(time.Now().UnixNano()))
}
// RandomBytesWithLength generate random bytes
func RandomBytesWithLength(n int) ([]byte, error) {
b := make([]byte, n)
_, err := rand.Read(b)
return b, err
}
// SecRandomBytesWithLength generate crypto random bytes
func SecRandomBytesWithLength(n int) ([]byte, error) {
b := make([]byte, n)
_, err := crand.Read(b)
return b, err
}
// RandomStringWithLength generate random string with specific length
func RandomStringWithLength(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}
// SecRandomStringWithLength generate random string with specific length
func SecRandomStringWithLength(n int) (string, error) {
b := make([]rune, n)
for i := range b {
idx, err := SecRandInt(len(letterRunes))
if err != nil {
return "", err
}
b[i] = letterRunes[idx]
}
return string(b), nil
}
// SecRandInt generate security int
func SecRandInt(n int) (int, error) {
bn, err := crand.Int(crand.Reader, big.NewInt(int64(n)))
if err != nil {
return 0, err
}
return int(bn.Int64()), nil
}