mirror of
https://gitlab.com/chrony/chrony.git
synced 2025-12-03 17:35:06 -05:00
util: add function to generate random bytes
Add a function to fill a buffer with random bytes which uses a better PRNG than random(). Use arc4random() if it's available on the system. Fall back to reading from /dev/urandom, which should be available on all currently supported systems.
This commit is contained in:
20
util.c
20
util.c
@@ -1070,3 +1070,23 @@ UTI_CheckDirPermissions(const char *path, mode_t perm, uid_t uid, gid_t gid)
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* ================================================== */
|
||||
|
||||
#define DEV_URANDOM "/dev/urandom"
|
||||
|
||||
void
|
||||
UTI_GetRandomBytes(void *buf, unsigned int len)
|
||||
{
|
||||
#ifdef HAVE_ARC4RANDOM
|
||||
arc4random_buf(buf, len);
|
||||
#else
|
||||
static FILE *f = NULL;
|
||||
if (!f)
|
||||
f = fopen(DEV_URANDOM, "r");
|
||||
if (!f)
|
||||
LOG_FATAL(LOGF_Util, "Can't open %s : %s", DEV_URANDOM, strerror(errno));
|
||||
if (fread(buf, 1, len, f) != len)
|
||||
LOG_FATAL(LOGF_Util, "Can't read from %s", DEV_URANDOM);
|
||||
#endif
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user