github.com/tinygo-org/tinygo@v0.31.3-0.20240404173401-90b0bf646c27/src/crypto/rand/rand_urandom.go (about) 1 //go:build linux && !baremetal && !wasip1 2 3 // This implementation of crypto/rand uses the /dev/urandom pseudo-file to 4 // generate random numbers. 5 // TODO: convert to the getentropy or getrandom libc function on Linux once it 6 // is more widely supported. 7 8 package rand 9 10 import ( 11 "syscall" 12 ) 13 14 func init() { 15 Reader = &reader{} 16 } 17 18 type reader struct { 19 fd int 20 } 21 22 func (r *reader) Read(b []byte) (n int, err error) { 23 if len(b) == 0 { 24 return 25 } 26 27 // Open /dev/urandom first if needed. 28 if r.fd == 0 { 29 fd, err := syscall.Open("/dev/urandom", syscall.O_RDONLY, 0) 30 if err != nil { 31 return 0, err 32 } 33 r.fd = fd 34 } 35 36 // Read from the file. 37 return syscall.Read(r.fd, b) 38 }