1 // Copyright 2010 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
7 // Unix cryptographically secure pseudorandom number
23 import "crypto/internal/boring"
25 const urandomDevice = "/dev/urandom"
29 Reader = boring.RandReader
35 // A reader satisfies reads by reading from urandomDevice
39 used int32 // atomic; whether this reader has been used
42 // altGetRandom if non-nil specifies an OS-specific function to get
43 // urandom-style randomness.
44 var altGetRandom func([]byte) (ok bool)
47 println("crypto/rand: blocked for 60 seconds waiting to read random data from the kernel")
50 func (r *reader) Read(b []byte) (n int, err error) {
52 if atomic.CompareAndSwapInt32(&r.used, 0, 1) {
53 // First use of randomness. Start timer to warn about
54 // being blocked on entropy not being available.
55 t := time.AfterFunc(time.Minute, warnBlocked)
58 if altGetRandom != nil && altGetRandom(b) {
64 f, err := os.Open(urandomDevice)
68 r.f = bufio.NewReader(hideAgainReader{f})
73 // hideAgainReader masks EAGAIN reads from /dev/urandom.
74 // See golang.org/issue/9205
75 type hideAgainReader struct {
79 func (hr hideAgainReader) Read(p []byte) (n int, err error) {
81 if errors.Is(err, syscall.EAGAIN) {