Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast pseudorandom number generator for cryptography in C

I was using the following code to generate sequence of pseudo-random numbers that was used for cryptographic purposes, but then I read somewhere that it may not be very secure. Can someone give me C implementation of a better generator -- the main goal is for this method to be fast. For instance, I did some research and came across Blum Blum Shub method, which would totally kill performance by doing pow(N) calculations.

PS. And please don't quote Wikipedia articles w/o C/C++ code. I'm looking for C or C++ code sample of what I'm showing below.

#define ROL(v, shift) ((((v) >> ((sizeof(v) * 8) - (shift))) | ((v) << (shift))))

ULONGLONG uiPSN = doSeed();   //64-bit unsigned integer

for(int i = 0; i < sizeOfArray; i++)
{
    uiPSN = uiPSN * 214013L + 2531011L;
    uiPSN = ROL(uiPSN, 16);

    //Apply 'uiPSN'
}
like image 834
c00000fd Avatar asked Aug 19 '13 21:08

c00000fd


People also ask

How are random numbers generated in cryptography?

Random number generation A PRNG is a deterministic algorithm that produces seemingly random numbers. It needs a seed as an initial value, and will produce the same “random” sequence for a fixed seed. Applications such as games, simulations, and cryptography use such generators.

Why is using a pseudorandom number generator inappropriate for generating cryptographic keys?

Its value is unpredictable in advance. It cannot be reliably reproduced after generation.

Is there a random number generator in C?

C library function - rand() The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX. RAND_MAX is a constant whose default value may vary between implementations but it is granted to be at least 32767.


1 Answers

ISAAC (http://www.burtleburtle.net/bob/rand/isaacafa.html) is probably one of the fastest cryptographically secure PRNGs (code at site). Another approach is to use a block cipher in counter mode. Something like TwoFish, which is reasonably fast and freely available, would be effective.

If you don't need a lot of numbers, all modern operating systems have built-in RNGs suitable for cryptographic use, though they typically can't produce lots of numbers because they rely on accumulating entropy from sources like input timings. Unix-like systems (Linux, OSX) have /dev/random, Windows has CryptGenRandom. Even if these aren't suitable for your needs, you probably should use them to seed the PRNG you do end up using.

like image 57
Lee Daniel Crocker Avatar answered Oct 20 '22 14:10

Lee Daniel Crocker