OSDN Git Service

bcb81546fa9ffc65864c9526e16f093f1f0f0edc
[bytom/vapor.git] / vendor / github.com / tendermint / tmlibs / common / random.go
1 package common
2
3 import (
4         crand "crypto/rand"
5         "math/rand"
6 )
7
8 const (
9         strChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" // 62 characters
10 )
11
12 func init() {
13         b := cRandBytes(8)
14         var seed uint64
15         for i := 0; i < 8; i++ {
16                 seed |= uint64(b[i])
17                 seed <<= 8
18         }
19         rand.Seed(int64(seed))
20 }
21
22 // Constructs an alphanumeric string of given length.
23 func RandStr(length int) string {
24         chars := []byte{}
25 MAIN_LOOP:
26         for {
27                 val := rand.Int63()
28                 for i := 0; i < 10; i++ {
29                         v := int(val & 0x3f) // rightmost 6 bits
30                         if v >= 62 {         // only 62 characters in strChars
31                                 val >>= 6
32                                 continue
33                         } else {
34                                 chars = append(chars, strChars[v])
35                                 if len(chars) == length {
36                                         break MAIN_LOOP
37                                 }
38                                 val >>= 6
39                         }
40                 }
41         }
42
43         return string(chars)
44 }
45
46 func RandInt() int {
47         return rand.Int()
48 }
49
50 func RandBytes(n int) []byte {
51         bs := make([]byte, n)
52         for i := 0; i < n; i++ {
53                 bs[i] = byte(rand.Intn(256))
54         }
55         return bs
56 }
57
58 // NOTE: This relies on the os's random number generator.
59 // For real security, we should salt that with some seed.
60 // See github.com/tendermint/go-crypto for a more secure reader.
61 func cRandBytes(numBytes int) []byte {
62         b := make([]byte, numBytes)
63         _, err := crand.Read(b)
64         if err != nil {
65                 PanicCrisis(err)
66         }
67         return b
68 }