forked from ultramancool/tweetnacl-usable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
randombytes.c
41 lines (40 loc) · 868 Bytes
/
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
#ifdef WIN32
#include "Windows.h"
#endif
#include <stdio.h>
#include <stdlib.h>
void randombytes(unsigned char * ptr,unsigned int length)
{
char failed = 0;
#ifdef WIN32
static HCRYPTPROV prov = 0;
if (prov == 0) {
if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, 0)) {
failed = 1;
}
}
if (!failed && !CryptGenRandom(prov, length, ptr)) {
failed = 1;
}
#else
FILE* fh = fopen("/dev/urandom", "rb");
if (fh != NULL) {
if (fread(ptr, length, 1, fh) == 0) {
failed = 1;
}
fclose(fh);
} else {
failed = 1;
}
#endif
/*
* yes, this is horrible error handling but we don't have better
* options from here and I don't want to start changing the design
* of the library
*/
if (failed) {
fprintf(stderr, "Generating random data failed. Please report "
"this to https://github.com/ultramancool\n");
exit(1);
}
}