Ibrahim Ipek
Ibrahim Ipek

Reputation: 525

Is there a random_device equivalent in C

In C++ we can generate true random numbers (if your hardware supports) with random_device. And i am writing a implementation of One-time Pad algorithm with C. Is there a way to generate true random numbers in C? I writing with C for speed and some another reasons. If i use a PRNG, it is will be unsafe.

char *KeyGenerate(unsigned long long StringLength)
{
    std::random_device TrueRandomNumberGenerator;
    char *Key = (char *) malloc(StringLength + 1);

    for(unsigned long long I = 0; I < StringLength; I++)
    {
        Key[I] = TrueRandomNumberGenerator();
    }
    Key[StringLength] = '\0';

    return Key;
}

Upvotes: 2

Views: 733

Answers (3)

Severin Pappadeux
Severin Pappadeux

Reputation: 20110

As noted on Linux you have to read /dev/urandom. On WIndows alternative would be to use CryptGenRandom

This is what is done in Python, I believe - API calls /dev/urandom based code on Linux, but CryptGenRandom on Windows.

Don't know enough about OS X

Upvotes: 1

FreeStyle4
FreeStyle4

Reputation: 282

C uses a PRNG (pseudorandom number generator) so you can't really get true random numbers.

Since your code is generating a bunch of random numbers, you could simply:

srand(time(NULL));
int r = rand();

where srand(time(NULL));

will go above the for loop. This way you seed once, then generate your random numbers

Upvotes: 0

hugomg
hugomg

Reputation: 69954

The C standard library is very very tiny. To get true random numbers, you will need to use OS-specific APIs.

In Linux systems, you can get a stream of cryptographically-strong random bytes from the /dev/urandom file.

Upvotes: 3

Related Questions