Do I understand correctly that crypto/rand.Reader can return Read error only on platforms not listed below, i.e. when it is not actually implemented?
// Reader is a global, shared instance of a cryptographically
// strong pseudo-random generator.
//
// On Linux, Reader uses getrandom(2) if available, /dev/urandom otherwise.
// On OpenBSD, Reader uses getentropy(2).
// On other Unix-like systems, Reader reads from /dev/urandom.
// On Windows systems, Reader uses the CryptGenRandom API.
var Reader io.Reader
TL;DR; crypto/rand
's Read()
(and Reader.Read()
) methods may fail due to a variety of reasons, even on the platforms listed as supported. Do not assume that calls to this functions will always succeed. Always check the error
return value.
Do I understand correctly that crypto/rand.Reader can return Read error only on platforms not listed below, i.e. when it is not actually implemented?
No. For example, have a look at the Linux implementation of rand.Reader
. If available, this implementation will use the getrandom
Linux system call, which may fail with a number of errors (most importantly, EAGAIN
):
EAGAIN
- The requested entropy was not available, andgetrandom()
would have blocked if theGRND_NONBLOCK
flag was not set.
The EAGAIN
error quite literally tells you to "try again later"; the official meaning according to man 3 errno
is "Resource temporarily unavailable". So when receiving an EAGAIN
error you could simply keep trying for a certain time.
If getrandom
is not available, the crypto/rand
module will try to open and read from /dev/urandom
(see source code), which might also fail for any number of reasons. These errors might not necessarily be of temporary nature (for example, issues with file system permissions); if your application depends on the availability of random data, you should treat an error like any other kind of non-recoverable error in your application.
For these reasons, you should not assume that rand.Read()
will always succeed on Linux/UNIX and always check rand.Read()
's error return value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With