From 1e6c0ef4d6cfaa5d985c6812286603b25ee420f8 Mon Sep 17 00:00:00 2001 From: Paul Duncan Date: Mon, 29 Apr 2024 12:02:51 -0400 Subject: add rand-bytes.h --- rand-bytes.h | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 rand-bytes.h diff --git a/rand-bytes.h b/rand-bytes.h new file mode 100644 index 0000000..b9d38d4 --- /dev/null +++ b/rand-bytes.h @@ -0,0 +1,20 @@ +#ifndef RAND_BYTES_H +#define RAND_BYTES_H + +#include // size_t +#include // getrandom() +#include // errx() + +// Fill `buf` with `len` random bytes using `getrandom()`. +// +// 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) { + // print error message, exit with error + errx(-1, "getrandom() failed"); + } +} + +#endif /* RAND_BYTES_H */ -- cgit v1.2.3