From 0f1f8ccf43e1296725cfbef482d19c90b15af98c Mon Sep 17 00:00:00 2001 From: Daniel Borkmann Date: Tue, 4 Jun 2013 09:58:23 +0200 Subject: rnd: break out prng from xutils We only need it in curvetun, this makes it easier to maintain. Signed-off-by: Daniel Borkmann --- rnd.c | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 rnd.c (limited to 'rnd.c') diff --git a/rnd.c b/rnd.c new file mode 100644 index 0000000..ad32175 --- /dev/null +++ b/rnd.c @@ -0,0 +1,49 @@ +#include +#include +#include +#include + +#include "rnd.h" + +static int fd_rnd = -1; + +static void randombytes(unsigned char *x, unsigned long long xlen) +{ + int ret; + + if (fd_rnd == -1) { + for (;;) { + fd_rnd = open("/dev/urandom", O_RDONLY); + if (fd_rnd != -1) + break; + sleep(1); + } + } + + while (xlen > 0) { + if (xlen < 1048576) + ret = xlen; + else + ret = 1048576; + + ret = read(fd_rnd, x, ret); + if (ret < 1) { + sleep(1); + continue; + } + + x += ret; + xlen -= ret; + } +} + +/* Note: it's not really secure, but the name only suggests it's better to use + * than rand(3) when transferring bytes over the network in non-security + * critical structure members. secrand() is only used to fill up salts actually. + */ +int secrand(void) +{ + int ret; + randombytes((void *) &ret, sizeof(ret)); + return ret; +} -- cgit v1.2.3-54-g00ecf