-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrandombytes.c
65 lines (56 loc) · 1.03 KB
/
randombytes.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <stdio.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "randombytes.h"
#include <sys/syscall.h>
#define _GNU_SOURCE
static int fd = -1;
static void randombytes_fallback(unsigned char *x, size_t xlen)
{
int i;
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,i);
if (i < 1) {
sleep(1);
continue;
}
x += i;
xlen -= i;
}
}
#ifdef SYS_getrandom
void randombytes(unsigned char *buf,size_t buflen)
{
size_t d = 0;
int r;
while(d<buflen)
{
errno = 0;
r = syscall(SYS_getrandom, buf, buflen - d, 0);
if(r < 0)
{
if (errno == EINTR) continue;
randombytes_fallback(buf, buflen);
return;
}
buf += r;
d += r;
}
}
#else
void randombytes(unsigned char *buf,size_t buflen)
{
randombytes_fallback(buf,buflen);
}
#endif