aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPaul Duncan <pabs@pablotron.org>2024-04-29 12:02:51 -0400
committerPaul Duncan <pabs@pablotron.org>2024-04-29 12:02:51 -0400
commit1e6c0ef4d6cfaa5d985c6812286603b25ee420f8 (patch)
tree39563b99fe997eb6eb24fad9c82fe1c58ca8d325
parent493bd74756150e3827ba328e531cd7e0d8df1533 (diff)
downloadsha3-1e6c0ef4d6cfaa5d985c6812286603b25ee420f8.tar.bz2
sha3-1e6c0ef4d6cfaa5d985c6812286603b25ee420f8.zip
add rand-bytes.h
-rw-r--r--rand-bytes.h20
1 files changed, 20 insertions, 0 deletions
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 <stddef.h> // size_t
+#include <sys/random.h> // getrandom()
+#include <err.h> // 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 */