forked from Laisky/go-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrandom.go
More file actions
48 lines (39 loc) · 955 Bytes
/
random.go
File metadata and controls
48 lines (39 loc) · 955 Bytes
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
package utils
import (
crand "crypto/rand"
"math/big"
"math/rand"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
// 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
}