-
Notifications
You must be signed in to change notification settings - Fork 39
/
ent.c
74 lines (56 loc) · 1.89 KB
/
ent.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
65
66
67
68
69
70
71
72
73
74
// Use `getentropy` from unistd.h //////////////////////////////////////////////
#if defined(ENT_GETENTROPY_UNISTD)
#include <stddef.h>
#include <unistd.h>
int ent_getentropy(void* buf, size_t len) {
return getentropy(buf, len);
}
// Use `getentropy` from sys/random.h //////////////////////////////////////////
#elif defined(ENT_GETENTROPY_SYSRANDOM)
#include <stddef.h>
// See https://www.mail-archive.com/[email protected]/msg38583.html.
#include <stdlib.h>
#include <sys/random.h>
int ent_getentropy(void* buf, size_t len) {
return getentropy(buf, len);
}
// Use the `getrandom` syscall /////////////////////////////////////////////////
#elif defined(ENT_GETRANDOM_SYSCALL)
#include <stddef.h>
#include <errno.h>
#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>
#define ENTFAIL { errno=EIO; return -1; }
int ent_getentropy(void* buf, size_t len) {
if (len > 256) ENTFAIL
int r = syscall(SYS_getrandom, buf, len, 0);
if (r < 0) return r;
if (r != len) ENTFAIL
return 0;
}
// Use `/dev/urandom` //////////////////////////////////////////////////////////
#elif defined(ENT_DEV_URANDOM)
#include <stddef.h>
#include <errno.h>
#include <stdio.h>
#define ENTFAIL { errno=EIO; return -1; }
int ent_getentropy(void* buf, size_t len) {
if (len > 256) ENTFAIL;
FILE *f = fopen("/dev/urandom", "re");
if (!f) return -1;
int r = fread(buf, 1, len, f);
(void) fclose(f);
if (r != len) ENTFAIL
return 0;
}
// Use `BCryptGenRandom` on Windows ////////////////////////////////////////////
#elif defined(ENT_GETENTROPY_BCRYPTGENRANDOM)
#include <windows.h>
#include <bcrypt.h>
int ent_getentropy(void* buf, size_t len) {
return BCryptGenRandom(NULL, (PUCHAR)buf, len, BCRYPT_USE_SYSTEM_PREFERRED_RNG);
}
#else
#error "One of these must be set: ENT_GETENTROPY_BCRYPTGENRANDOM, ENT_DEV_URANDOM, ENT_GETENTROPY_UNISTD, ENT_GETENTROPY_SYSRANDOM, ENT_GETRANDOM_SYSCALL"
#endif