Skip to content

Commit 49db336

Browse files
committed
add _WinRandomProc
1 parent f32c213 commit 49db336

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

src/gmalglib/core/random.c

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
#ifdef _WIN32
77

8+
#pragma comment(lib, "Bcrypt.lib")
89
#include <Windows.h>
910
#include <bcrypt.h>
1011

@@ -28,14 +29,43 @@ static int SimpleRandomProc(void* rand_obj, uint64_t bytes_len, uint8_t* bytes)
2829

2930
static int _WinRandomProc(void* rand_obj, uint64_t bytes_len, uint8_t* bytes)
3031
{
31-
32+
ULONG chunk = 0;
33+
while (bytes_len > 0)
34+
{
35+
chunk = (ULONG)(bytes_len < ULONG_MAX ? bytes_len : ULONG_MAX);
36+
if (!BCRYPT_SUCCESS(BCryptGenRandom(NULL, bytes, chunk, BCRYPT_USE_SYSTEM_PREFERRED_RNG)))
37+
return 0;
38+
bytes += chunk;
39+
bytes_len -= chunk;
40+
}
41+
return 1;
3242
}
3343

3444
#else
3545

3646
static int _LinuxRandomProc(void* rand_obj, uint64_t bytes_len, uint8_t* bytes)
3747
{
48+
int fd = 0;
49+
fd = _Py_open_noraise("/dev/urandom", O_RDONLY);
50+
if (fd < 0)
51+
return 0;
3852

53+
while (bytes_len > 0)
54+
{
55+
do {
56+
n = read(fd, buffer, (size_t)size);
57+
} while (n < 0 && errno == EINTR);
58+
59+
if (n <= 0) {
60+
/* stop on error or if read(size) returned 0 */
61+
close(fd);
62+
return -1;
63+
}
64+
65+
buffer += n;
66+
size -= n;
67+
}
68+
close(fd);
3969
}
4070

4171
#endif // _WIN32

0 commit comments

Comments
 (0)