Commit | Line | Data |
---|---|---|
fcdff139 RK |
1 | /* |
2 | * This file is part of DisOrder | |
3 | * Copyright (C) 2008 Richard Kettlewell | |
4 | * | |
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. | |
9 | * | |
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. | |
14 | * | |
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 | |
18 | * USA | |
19 | */ | |
20 | ||
21 | /** @file lib/random.c | |
22 | * @brief Random number generator | |
23 | * | |
24 | */ | |
25 | ||
26 | #include <config.h> | |
27 | #include "types.h" | |
28 | ||
29 | #include <fcntl.h> | |
30 | #include <unistd.h> | |
31 | #include <errno.h> | |
32 | #include <string.h> | |
33 | ||
34 | #include "random.h" | |
35 | #include "log.h" | |
36 | #include "arcfour.h" | |
37 | ||
38 | static int random_count; | |
39 | static int random_fd = -1; | |
40 | static arcfour_context random_ctx[1]; | |
41 | ||
42 | /** @brief Rekey the RNG | |
43 | * | |
44 | * Resets the RNG's key to a random one read from /dev/urandom | |
45 | */ | |
46 | static void random__rekey(void) { | |
47 | char key[128]; | |
48 | int n; | |
49 | ||
50 | if(random_fd < 0) { | |
51 | if((random_fd = open("/dev/urandom", O_RDONLY)) < 0) | |
52 | fatal(errno, "opening /dev/urandom"); | |
53 | } | |
54 | if((n = read(random_fd, key, sizeof key)) < 0) | |
55 | fatal(errno, "reading from /dev/urandom"); | |
56 | if((size_t)n < sizeof key) | |
57 | fatal(0, "reading from /dev/urandom: short read"); | |
58 | arcfour_setkey(random_ctx, key, sizeof key); | |
59 | random_count = 8 * 1024 * 1024; | |
60 | } | |
61 | ||
62 | /** @brief Get random bytes | |
63 | * @param ptr Where to put random bytes | |
64 | * @param bytes How many random bytes to generate | |
65 | */ | |
66 | void random_get(uint8_t *ptr, size_t bytes) { | |
67 | if(random_count == 0) | |
68 | random__rekey(); | |
69 | /* Encrypting 0s == just returning the keystream */ | |
70 | memset(ptr, 0, bytes); | |
71 | arcfour_stream(random_ctx, (char *)ptr, (char *)ptr, bytes); | |
72 | if(bytes > (size_t)random_count) | |
73 | random_count = 0; | |
74 | else | |
75 | random_count -= bytes; | |
76 | } | |
77 | ||
78 | /* | |
79 | Local Variables: | |
80 | c-basic-offset:2 | |
81 | comment-column:40 | |
82 | fill-column:79 | |
83 | indent-tabs-mode:nil | |
84 | End: | |
85 | */ |