Wednesday, September 24, 2014

Random Numbers

Generating random numbers isn't the most straight forward. Here is the correct way to do it in C/C++:

Windows:

int randomNumber;

if (rand_s(&randomNumber))
{
    return randomNumber;

}
else
{
    //TODO error
}


Unix/Linux:

int randomNumber;
int fd = fopen("/dev/random", O_RDONLY));

if (fd > 0 && read(fd, &randomNumber, 4))
{
    return randomNumber;
}
else
{
    //TODO error
}

NOTE: On Linux don't call this too many times because the pool of numbers is limited.

4 comments:

Jouni Aro said...

/dev/urandom gives values from an unlimited pool

Chris Bensen said...

Hi Jouni,

Wikipedia states:

"A counterpart to /dev/random is /dev/urandom ("unlimited"[5]/non-blocking random source[6]) which reuses the internal pool to produce more pseudo-random bits. This means that the call will not block, but the output may contain less entropy than the corresponding read from /dev/random. While it is still intended as a pseudorandom number generator suitable for most cryptographic purposes, it is not recommended for the generation of long-term cryptographic keys."

So yes, you can use /dev/urandom, but it isn't as random.

Jouni Aro said...

Hi Chris,

Well, yes in cases that you need big random numbers it may give you weaker keys, but you can call it without being afraid that it would block. So I merely commented your note that there is an alternative.

I think in normal cases it gives you good enough randomness, unless you are dealing with high-risk security. Well, I am not an expert but that's how I get it.

Chris Bensen said...

Hi Jouni,

Yup, you are correct. I should have specified that I wanted to bring attention how to get a random number that is as random as possible :) I love dialog though, that's what makes the programming trade better!

Post a Comment