41#if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 25))
42#define N_RANDOM_HAVE_GETRANDOM 1
43#include <sys/random.h>
48 FILE* f = fopen(
"/dev/urandom",
"rb");
50 n_log(
LOG_ERR,
"n_random_bytes: cannot open /dev/urandom: %s", strerror(errno));
53 size_t got = fread(buf, 1, n, f);
56 n_log(
LOG_ERR,
"n_random_bytes: short read from /dev/urandom (%zu of %zu)", got, n);
64 n_log(
LOG_ERR,
"n_random_bytes: NULL buffer with n %zu", n);
71#ifdef N_RANDOM_HAVE_GETRANDOM
74 ssize_t r = getrandom(buf + got, n - got, 0);
76 if (errno == EINTR)
continue;
95 unsigned char* buf = NULL;
96 Malloc(buf,
unsigned char, nbytes);
#define Malloc(__ptr, __struct, __size)
Malloc Handler to get errors and set to 0.
#define __n_assert(__ptr, __ret)
macro to assert things
#define Free(__ptr)
Free Handler to get errors.
#define n_log(__LEVEL__,...)
Logging function wrapper to get line and func.
#define LOG_ERR
error conditions
N_STR * n_hex_encode(const unsigned char *data, size_t len)
encode len bytes of data as a lowercase hex N_STR (2*len characters); free with free_nstr.
int n_random_bytes(unsigned char *buf, size_t n)
fill buf with n cryptographically secure random bytes (getrandom(2) when available,...
N_STR * n_random_hex_token(size_t nbytes)
generate nbytes secure random bytes and return them as a lowercase hex N_STR (2*nbytes characters); f...
A box including a string and his lenght.
Common headers and low-level functions & define.
Hexadecimal encode/decode helpers.
static int n_random_from_urandom(unsigned char *buf, size_t n)
Cryptographically secure random bytes and hex tokens (POSIX)
N_STR and string function declaration.