-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrandom.go
43 lines (38 loc) · 1.07 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
package fitbit
import (
crand "crypto/rand"
"math/big"
mrand "math/rand"
"time"
"github.com/anyappinc/fitbit/logger"
)
var (
pseudoRand *mrand.Rand
RandomByteSet = NumberLetters + UppercaseAlphabetLetters + LowercaseAlphabetLetters // RandomByteSet is a set of characters used to construct random bytes
)
func init() {
pseudoRand = mrand.New(mrand.NewSource(time.Now().UnixNano()))
}
func randomBytes(length uint64) []byte {
var (
cryptoRandErr error
randomByteSetLength = len(RandomByteSet)
randomByteSetLengthAsBitInt = big.NewInt(int64(randomByteSetLength))
randBytes = make([]byte, length)
)
for i := range randBytes {
if cryptoRandErr == nil {
idx, err := crand.Int(crand.Reader, randomByteSetLengthAsBitInt)
if err == nil {
randBytes[i] = RandomByteSet[idx.Int64()]
} else {
logger.Warn.Printf("Can not generate secure random number: %v", err)
cryptoRandErr = err
}
}
if cryptoRandErr != nil {
randBytes[i] = RandomByteSet[pseudoRand.Intn(randomByteSetLength)]
}
}
return randBytes
}