-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrandombytes.c
93 lines (81 loc) · 1.6 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
* Implementors: EagleSign Team
* This implementation is highly inspired from Dilithium and
* Falcon Signatures' implementations
*/
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include "randombytes.h"
#ifdef _WIN32
#include <windows.h>
#include <wincrypt.h>
#else
#include <fcntl.h>
#include <errno.h>
#ifdef __linux__
#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>
#else
#include <unistd.h>
#endif
#endif
#ifdef _WIN32
void randombytes(uint8_t *out, size_t outlen)
{
HCRYPTPROV ctx;
size_t len;
if (!CryptAcquireContext(&ctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
abort();
while (outlen > 0)
{
len = (outlen > 1048576) ? 1048576 : outlen;
if (!CryptGenRandom(ctx, len, (BYTE *)out))
abort();
out += len;
outlen -= len;
}
if (!CryptReleaseContext(ctx, 0))
abort();
}
#elif defined(__linux__) && defined(SYS_getrandom)
void randombytes(uint8_t *out, size_t outlen)
{
ssize_t ret;
while (outlen > 0)
{
ret = syscall(SYS_getrandom, out, outlen, 0);
if (ret == -1 && errno == EINTR)
continue;
else if (ret == -1)
abort();
out += ret;
outlen -= ret;
}
}
#else
void randombytes(uint8_t *out, size_t outlen)
{
static int fd = -1;
ssize_t ret;
while (fd == -1)
{
fd = open("/dev/urandom", O_RDONLY);
if (fd == -1 && errno == EINTR)
continue;
else if (fd == -1)
abort();
}
while (outlen > 0)
{
ret = read(fd, out, outlen);
if (ret == -1 && errno == EINTR)
continue;
else if (ret == -1)
abort();
out += ret;
outlen -= ret;
}
}
#endif