-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrand_plan9.go
72 lines (63 loc) · 1.24 KB
/
rand_plan9.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sysrand
import (
"internal/byteorder"
"internal/chacha8rand"
"io"
"os"
"sync"
)
const randomDevice = "/dev/random"
// This is a pseudorandom generator that seeds itself by reading from
// /dev/random. The read function always returns the full amount asked for, or
// else it returns an error.
var (
mu sync.Mutex
seeded sync.Once
seedErr error
state chacha8rand.State
)
func read(b []byte) error {
seeded.Do(func() {
entropy, err := os.Open(randomDevice)
if err != nil {
seedErr = err
return
}
defer entropy.Close()
var seed [32]byte
_, err = io.ReadFull(entropy, seed[:])
if err != nil {
seedErr = err
return
}
state.Init(seed)
})
if seedErr != nil {
return seedErr
}
mu.Lock()
defer mu.Unlock()
for len(b) >= 8 {
if x, ok := state.Next(); ok {
byteorder.BEPutUint64(b, x)
b = b[8:]
} else {
state.Refill()
}
}
for len(b) > 0 {
if x, ok := state.Next(); ok {
var buf [8]byte
byteorder.BEPutUint64(buf[:], x)
n := copy(b, buf[:])
b = b[n:]
} else {
state.Refill()
}
}
state.Reseed()
return nil
}