aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/crypto/rand/rand_urandom.go
blob: e9a8d485e957209c7e3490a1aab5e1a427fc4dfb (plain)
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
//go:build linux && !baremetal && !wasip1

// This implementation of crypto/rand uses the /dev/urandom pseudo-file to
// generate random numbers.
// TODO: convert to the getentropy or getrandom libc function on Linux once it
// is more widely supported.

package rand

import (
	"syscall"
)

func init() {
	Reader = &reader{}
}

type reader struct {
	fd int
}

func (r *reader) Read(b []byte) (n int, err error) {
	if len(b) == 0 {
		return
	}

	// Open /dev/urandom first if needed.
	if r.fd == 0 {
		fd, err := syscall.Open("/dev/urandom", syscall.O_RDONLY, 0)
		if err != nil {
			return 0, err
		}
		r.fd = fd
	}

	// Read from the file.
	return syscall.Read(r.fd, b)
}