...
Source file
src/crypto/rand/rand_unix.go
1
2
3
4
5
6
7
8
9
10
11 package rand
12
13 import (
14 "bufio"
15 "crypto/aes"
16 "crypto/cipher"
17 "encoding/binary"
18 "io"
19 "os"
20 "runtime"
21 "sync"
22 "sync/atomic"
23 "time"
24 )
25
26 const urandomDevice = "/dev/urandom"
27
28
29
30
31 func init() {
32 if runtime.GOOS == "plan9" {
33 Reader = newReader(nil)
34 } else {
35 Reader = &devReader{name: urandomDevice}
36 }
37 }
38
39
40 type devReader struct {
41 name string
42 f io.Reader
43 mu sync.Mutex
44 used int32
45 }
46
47
48
49 var altGetRandom func([]byte) (err error)
50
51 func warnBlocked() {
52 println("crypto/rand: blocked for 60 seconds waiting to read random data from the kernel")
53 }
54
55 func (r *devReader) Read(b []byte) (n int, err error) {
56 if atomic.CompareAndSwapInt32(&r.used, 0, 1) {
57
58
59 t := time.AfterFunc(60*time.Second, warnBlocked)
60 defer t.Stop()
61 }
62 if altGetRandom != nil && r.name == urandomDevice && altGetRandom(b) == nil {
63 return len(b), nil
64 }
65 r.mu.Lock()
66 defer r.mu.Unlock()
67 if r.f == nil {
68 f, err := os.Open(r.name)
69 if f == nil {
70 return 0, err
71 }
72 if runtime.GOOS == "plan9" {
73 r.f = f
74 } else {
75 r.f = bufio.NewReader(hideAgainReader{f})
76 }
77 }
78 return r.f.Read(b)
79 }
80
81 var isEAGAIN func(error) bool
82
83
84
85 type hideAgainReader struct {
86 r io.Reader
87 }
88
89 func (hr hideAgainReader) Read(p []byte) (n int, err error) {
90 n, err = hr.r.Read(p)
91 if err != nil && isEAGAIN != nil && isEAGAIN(err) {
92 err = nil
93 }
94 return
95 }
96
97
98
99
100
101
102
103
104
105
106
107
108
109 func newReader(entropy io.Reader) io.Reader {
110 if entropy == nil {
111 entropy = &devReader{name: "/dev/random"}
112 }
113 return &reader{entropy: entropy}
114 }
115
116 type reader struct {
117 mu sync.Mutex
118 budget int
119 cipher cipher.Block
120 entropy io.Reader
121 time, seed, dst, key [aes.BlockSize]byte
122 }
123
124 func (r *reader) Read(b []byte) (n int, err error) {
125 r.mu.Lock()
126 defer r.mu.Unlock()
127 n = len(b)
128
129 for len(b) > 0 {
130 if r.budget == 0 {
131 _, err := io.ReadFull(r.entropy, r.seed[0:])
132 if err != nil {
133 return n - len(b), err
134 }
135 _, err = io.ReadFull(r.entropy, r.key[0:])
136 if err != nil {
137 return n - len(b), err
138 }
139 r.cipher, err = aes.NewCipher(r.key[0:])
140 if err != nil {
141 return n - len(b), err
142 }
143 r.budget = 1 << 20
144 }
145 r.budget -= aes.BlockSize
146
147
148
149
150
151
152
153 ns := time.Now().UnixNano()
154 binary.BigEndian.PutUint64(r.time[:], uint64(ns))
155 r.cipher.Encrypt(r.time[0:], r.time[0:])
156 for i := 0; i < aes.BlockSize; i++ {
157 r.dst[i] = r.time[i] ^ r.seed[i]
158 }
159 r.cipher.Encrypt(r.dst[0:], r.dst[0:])
160 for i := 0; i < aes.BlockSize; i++ {
161 r.seed[i] = r.time[i] ^ r.dst[i]
162 }
163 r.cipher.Encrypt(r.seed[0:], r.seed[0:])
164
165 m := copy(b, r.dst[0:])
166 b = b[m:]
167 }
168
169 return n, nil
170 }
171
View as plain text