forked from sysprog21/lab0-c
-
Notifications
You must be signed in to change notification settings - Fork 0
/
random.c
46 lines (40 loc) · 826 Bytes
/
random.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include "random.h"
#include <assert.h>
#include <fcntl.h>
#include <stdint.h>
#include <unistd.h>
/* shameless stolen from ebacs */
void randombytes(uint8_t *x, size_t how_much)
{
ssize_t i;
static int fd = -1;
ssize_t xlen = (ssize_t) how_much;
assert(xlen >= 0);
if (fd == -1) {
for (;;) {
fd = open("/dev/urandom", O_RDONLY);
if (fd != -1)
break;
sleep(1);
}
}
while (xlen > 0) {
if (xlen < 1048576)
i = xlen;
else
i = 1048576;
i = read(fd, x, (size_t) i);
if (i < 1) {
sleep(1);
continue;
}
x += i;
xlen -= i;
}
}
uint8_t randombit(void)
{
uint8_t ret = 0;
randombytes(&ret, 1);
return (ret & 1);
}