mardi 1 mars 2016

C++ - Extracting random numbers from /dev/urandom

I need many cryptographically secure numbers, so I was thinking about extracting randomness from /dev/urandom and then "converting" it into (say) unsigned long long int. I guess it should be very efficient and it seems it is cryptographically secure, but I will investigate this aspect more in the future.
Now the question is: how can I do so?

I found this code:

char * block;
short size = 1;
ifstream urandom("/dev/urandom", ios::in|ios::binary);
urandom.read(block,size);
urandom.close();

Does it make sense? And how do I convert what I get to the type I desire?

EDIT - Using random interface of C++11

Following a suggestion from the comments, I tried using a uniform distribution over the integers and a random_device initialized as /dev/urandom. Here is the code:

std::uniform_int_distribution<unsigned int> dist(0, modulus-1);
std::random_device urandom("/dev/urandom");
for(unsigned int i = start ; i < end ; ++i)
{
    vector[i] = dist(urandom);
}

The problem is that this code is approximately 1000 times slower than before (I was using a xorshift128+ generator): 5 milliseconds vs. almost 5 seconds. Is this normal? Honestly, I thought that streaming bytes in from /dev/urandom and converting them to unsigned int would have been way faster... Am I missing something?




Aucun commentaire:

Enregistrer un commentaire