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. 4 5 // Package rand implements a cryptographically secure 6 // random number generator. 7 package rand 8 9 import "io" 10 11 // Reader is a global, shared instance of a cryptographically 12 // secure random number generator. 13 // 14 // On Linux, FreeBSD, Dragonfly, NetBSD and Solaris, Reader uses getrandom(2) if 15 // available, /dev/urandom otherwise. 16 // On OpenBSD and macOS, Reader uses getentropy(2). 17 // On other Unix-like systems, Reader reads from /dev/urandom. 18 // On Windows systems, Reader uses the ProcessPrng API. 19 // On JS/Wasm, Reader uses the Web Crypto API. 20 // On WASIP1/Wasm, Reader uses random_get from wasi_snapshot_preview1. 21 var Reader io.Reader 22 23 // Read is a helper function that calls Reader.Read using io.ReadFull. 24 // On return, n == len(b) if and only if err == nil. 25 func Read(b []byte) (n int, err error) { 26 return io.ReadFull(Reader, b) 27 } 28 29 // batched returns a function that calls f to populate a []byte by chunking it 30 // into subslices of, at most, readMax bytes. 31 func batched(f func([]byte) error, readMax int) func([]byte) error { 32 return func(out []byte) error { 33 for len(out) > 0 { 34 read := len(out) 35 if read > readMax { 36 read = readMax 37 } 38 if err := f(out[:read]); err != nil { 39 return err 40 } 41 out = out[read:] 42 } 43 return nil 44 } 45 } 46