diff options
author | Paul Duncan <pabs@pablotron.org> | 2024-05-08 17:58:59 -0400 |
---|---|---|
committer | Paul Duncan <pabs@pablotron.org> | 2024-05-08 17:58:59 -0400 |
commit | 6c10c32e03263c1845ac4a028d054937a3c9a5c4 (patch) | |
tree | 37779dc26318d9510ebfd5057594c3ba986e2c59 /rand-bytes.h | |
parent | b8a5fd74a4823b9fbf6194b0b94226f9f044756d (diff) | |
download | sha3-6c10c32e03263c1845ac4a028d054937a3c9a5c4.tar.bz2 sha3-6c10c32e03263c1845ac4a028d054937a3c9a5c4.zip |
rand-bytes.h: use getentropy() instead of getrandom() to support macos
Diffstat (limited to 'rand-bytes.h')
-rw-r--r-- | rand-bytes.h | 32 |
1 files changed, 24 insertions, 8 deletions
diff --git a/rand-bytes.h b/rand-bytes.h index b9d38d4..14b2861 100644 --- a/rand-bytes.h +++ b/rand-bytes.h @@ -2,18 +2,34 @@ #define RAND_BYTES_H #include <stddef.h> // size_t -#include <sys/random.h> // getrandom() +#include <sys/random.h> // getentropy() #include <err.h> // errx() -// Fill `buf` with `len` random bytes using `getrandom()`. +// Fill `buf` with `len` random bytes using `getentropy()`. // -// Prints an error and exits with an error code if `len` random bytes -// could not be read. -static void rand_bytes(void * const buf, const size_t len) { - const ssize_t got = getrandom(buf, len, 0); - if (got < (ssize_t) len) { +// Prints an error message to standard error and exits with a non-zero +// error code if `len` random bytes could not be read. +static void rand_bytes(void * const buf, size_t len) { + uint8_t *u8 = (uint8_t*) buf; + + // the maximum length for getentropy() is 256 bytes, so split requests + // for more than 256 bytes into multiple calls to `getentropy()`. + while (len > 256) { + // read 256 bytes, check for error + if (getentropy(u8, 256) == -1) { + // print error message, exit with error + errx(-1, "getentropy() failed"); + } + + // increment pointer, decrement length + u8 += 256; + len -= 256; + } + + // read remaining bytes, check for error + if (getentropy(u8, len) == -1) { // print error message, exit with error - errx(-1, "getrandom() failed"); + errx(-1, "getentropy() failed"); } } |