forked from albertobsd/keyhunt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Random.cpp
94 lines (85 loc) · 2.45 KB
/
Random.cpp
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
94
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gmp.h>
#if defined(_WIN32) || defined(_WIN64)
#include <Windows.h>
#include <bcrypt.h>
#pragma comment(lib, "bcrypt.lib")
#elif __unix__ || __unix || __APPLE__ || __MACH__ || __CYGWIN__
#include <unistd.h>
#include <fcntl.h>
#include <sys/syscall.h>
#include <linux/random.h>
#if defined(GRND_NONBLOCK)
#define USE_GETRANDOM
#endif
#endif
#include "Int.h"
static int r_state_mt_ready = 0;
static gmp_randstate_t r_state_mt;
void int_randominit() {
if(r_state_mt_ready) {
fprintf(stderr,"r_state_mt already initialized, file %s, line %i\n",__FILE__,__LINE__ - 1);
exit(0);
}
mpz_t mpz_seed;
int bytes_readed,bytes = 64;
unsigned char seed[64];
bytes_readed = random_bytes(seed, bytes);
if(bytes_readed != bytes) {
fprintf(stderr,"Error random_bytes(), file %s, line %i\n",__FILE__,__LINE__ - 2);
exit(0);
}
mpz_init(mpz_seed);
mpz_import(mpz_seed,bytes,1,sizeof(unsigned char),0,0,seed);
gmp_randinit_mt(r_state_mt);
gmp_randseed(r_state_mt,mpz_seed);
r_state_mt_ready = 1;
mpz_clear(mpz_seed);
memset(seed,0,bytes);
}
void Int::Rand(int nbit) {
if(!r_state_mt_ready) {
fprintf(stderr,"Error Rand(), file %s, line %i\n",__FILE__,__LINE__ - 1);
exit(0);
}
mpz_urandomb(num,r_state_mt,nbit);
mpz_setbit(num,nbit-1);
}
void Int::Rand(Int *min,Int *max) {
if(!r_state_mt_ready) {
fprintf(stderr,"Error Rand(), file %s, line %i\n",__FILE__,__LINE__ - 1);
exit(0);
}
Int diff(max);
diff.Sub(min);
this->Rand(256);
this->Mod(&diff);
this->Add(min);
}
int random_bytes(unsigned char *buffer,int bytes) {
#if defined(_WIN32) || defined(_WIN64)
if (!BCryptGenRandom(NULL, buffer, length, BCRYPT_USE_SYSTEM_PREFERRED_RNG)) {
fprintf(stderr,"Not BCryptGenRandom available\n");
exit(EXIT_FAILURE);
}
else
return bytes;
#elif __unix__ || __unix || __APPLE__ || __MACH__ || __CYGWIN__
#ifdef USE_GETRANDOM
return syscall(SYS_getrandom, buffer, bytes, GRND_NONBLOCK);
#else
int fd = open("/dev/urandom", O_RDONLY);
if (fd == -1) {
fprintf(stderr,"Not /dev/urandom available\n");
exit(EXIT_FAILURE);
}
ssize_t result = read(fd, buffer, bytes);
close(fd);
return result;
#endif
#else
#error "Unsupported platform"
#endif
}