2 * This file is part of DisOrder
3 * Copyright (C) 2008 Richard Kettlewell
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
21 /** @file lib/random.c
22 * @brief Random number generator
40 static int random_count;
41 static int random_fd = -1;
42 static arcfour_context random_ctx[1];
44 /** @brief Rekey the RNG
46 * Resets the RNG's key to a random one read from /dev/urandom
48 static void random__rekey(void) {
53 if((random_fd = open("/dev/urandom", O_RDONLY)) < 0)
54 fatal(errno, "opening /dev/urandom");
56 if((n = read(random_fd, key, sizeof key)) < 0)
57 fatal(errno, "reading from /dev/urandom");
58 if((size_t)n < sizeof key)
59 fatal(0, "reading from /dev/urandom: short read");
60 arcfour_setkey(random_ctx, key, sizeof key);
61 random_count = 8 * 1024 * 1024;
64 /** @brief Get random bytes
65 * @param ptr Where to put random bytes
66 * @param bytes How many random bytes to generate
68 void random_get(void *ptr, size_t bytes) {
71 /* Encrypting 0s == just returning the keystream */
72 memset(ptr, 0, bytes);
73 arcfour_stream(random_ctx, (char *)ptr, (char *)ptr, bytes);
74 if(bytes > (size_t)random_count)
77 random_count -= bytes;
80 /** @brief Return a random ID string */
81 char *random_id(void) {
82 unsigned long words[2];
85 random_get(words, sizeof words);
86 basen(words, 4, id, sizeof id, 62);