-
Notifications
You must be signed in to change notification settings - Fork 38
/
rand.go
38 lines (33 loc) · 864 Bytes
/
rand.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
package dry
import (
cryptorand "crypto/rand"
"fmt"
mathrand "math/rand"
"time"
)
// RandSeedWithTime calls rand.Seed() with the current time.
func RandSeedWithTime() {
mathrand.Seed(time.Now().UTC().UnixNano())
}
func getRandomHexString(length int, formatStr string) string {
var buffer []byte
if length%2 == 0 {
buffer = make([]byte, length/2)
} else {
buffer = make([]byte, (length+1)/2)
}
_, err := cryptorand.Read(buffer)
if err != nil {
return ""
}
hexString := fmt.Sprintf(formatStr, buffer)
return hexString[:length]
}
// RandomHexString returns a random lower case hex string with length.
func RandomHexString(length int) string {
return getRandomHexString(length, "%x")
}
// RandomHEXString returns a random upper case hex string with length.
func RandomHEXString(length int) string {
return getRandomHexString(length, "%X")
}