-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathrandom.c
86 lines (70 loc) · 2.15 KB
/
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
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
/***********************************************************************************
* FourQlib: a high-performance crypto library based on the elliptic curve FourQ
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
* Abstract: pseudo-random function
************************************************************************************/
#include "random.h"
#include <stdlib.h>
#include <stdbool.h>
#if defined(__WINDOWS__)
#include <windows.h>
#include <bcrypt.h>
#define RTL_GENRANDOM "SystemFunction036"
NTSTATUS last_bcrypt_error = 0;
#elif defined(__LINUX__)
#include <unistd.h>
#include <fcntl.h>
static int lock = -1;
#endif
static __inline void delay(unsigned int count)
{
while (count--) {}
}
int random_bytes(unsigned char* random_array, unsigned int nbytes)
{ // Generation of "nbytes" of random values
#if defined(__WINDOWS__)
if (BCRYPT_SUCCESS(last_bcrypt_error)) {
NTSTATUS status = BCryptGenRandom(NULL, random_array, nbytes, BCRYPT_USE_SYSTEM_PREFERRED_RNG);
if (BCRYPT_SUCCESS(status)) {
return true;
}
last_bcrypt_error = status;
}
HMODULE hAdvApi = LoadLibraryA("ADVAPI32.DLL");
if (!hAdvApi) {
return false;
}
BOOLEAN(APIENTRY * RtlGenRandom)(void*, ULONG) = (BOOLEAN(APIENTRY*)(void*, ULONG))GetProcAddress(hAdvApi, RTL_GENRANDOM);
BOOLEAN genrand_result = FALSE;
if (RtlGenRandom) {
genrand_result = RtlGenRandom(random_array, nbytes);
}
FreeLibrary(hAdvApi);
if (!genrand_result) {
return false;
}
#elif defined(__LINUX__)
int r, n = nbytes, count = 0;
if (lock == -1) {
do {
lock = open("/dev/urandom", O_RDONLY);
if (lock == -1) {
delay(0xFFFFF);
}
} while (lock == -1);
}
while (n > 0) {
do {
r = read(lock, random_array+count, n);
if (r == -1) {
delay(0xFFFF);
}
} while (r == -1);
count += r;
n -= r;
}
#endif
return true;
}