41#if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 25))
42#define N_RANDOM_HAVE_GETRANDOM 1
43#include <sys/random.h>
54#define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
58static int n_random_from_cng(
unsigned char* buf,
size_t n) {
59 NTSTATUS st = BCryptGenRandom(NULL, (PUCHAR)buf, (ULONG)n, BCRYPT_USE_SYSTEM_PREFERRED_RNG);
60 if (st != STATUS_SUCCESS) {
61 n_log(
LOG_ERR,
"n_random_bytes: BCryptGenRandom failed with status 0x%08lx", (
unsigned long)st);
73 FILE* f = fopen(
"/dev/urandom",
"rb");
75 n_log(
LOG_ERR,
"n_random_bytes: cannot open /dev/urandom: %s", strerror(errno));
78 size_t got = fread(buf, 1, n, f);
81 n_log(
LOG_ERR,
"n_random_bytes: short read from /dev/urandom (%zu of %zu)", got, n);
90 n_log(
LOG_ERR,
"n_random_bytes: NULL buffer with n %zu", n);
98 return n_random_from_cng(buf, n);
99#elif defined(N_RANDOM_HAVE_GETRANDOM)
102 ssize_t r = getrandom(buf + got, n - got, 0);
104 if (errno == EINTR)
continue;
123 unsigned char* buf = NULL;
124 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 from the system RNG: BCryptGenRandom on Windows...
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.
N_STR and string function declaration.