Random number generator that doesn't use rand()/srand() C functions - c

I'm developing some library in C that can be used by various user applications.
The library should be completely "transparent" - a user application can init it and finalize,
and it's not supposed to see any change in the running application.
The problem is - I'm using C srand()/rand() functions in the library initialization,
which means that the library does affect user's application - if a user generates random numbers, they will be affected by the fact that rand() was already called.
So, can anyone point to some simple non-GPL alternative to rand() random number generator in C?
It doesn't have to be really strong - I'n not doing any crypto with the numbers.
I was thinking to write some small and really simple generator (something like take time and XOR with something and do something with some prime number and bla bla bla), but I was wondering if someone has a pointer to a more decent generator.

It generates the next number by keeping some state and modifying the state every time you call the function. Such a function is called a pseudorandom number generator. An old method of creating a PRNG is the linear congruential generator, which is easy enough:
static int rand_state;
int rand(void)
{
rand_state = (rand_state * 1103515245 + 12345) & 0x7fffffff;
return rand_state;
}
As you can see, this method allows you to predict the next number in the series if you know the previous number. There are more sophisticated methods.
Various types of pseudorandom number generators have been designed for specific purposes. There are secure PRNGs which are slow but hard to predict even if you know how they work, and there are big PRNGs like Mersenne Twister which have nice distribution properties and are therefore useful for writing Monte Carlo simulations.
As a rule of thumb, a linear congruential generator is good enough for writing a game (how much damage does the monster deal) but not good enough for writing a simulation. There is a colorful history of researchers who have chosen poor PRNGs for their programs; the results of their simulations are suspect as a result.

If C++ is also acceptable for you, have a look at Boost.
http://www.boost.org/doc/libs/1_51_0/doc/html/boost_random/reference.html
It does not only offer one generator, but several dozen, and gives an overview of speed, memory requirement and randomness quality.

Related

Always the same output with rand() with different ide envirionment too [duplicate]

I am currently trying to teach myself c programming. I am stuck on learning random numbers. Many of the websites I visit use the time() function as a method of seeding the random number generator. But many posts and websites I have read say that using the system clock as a method of producing random numbers is flawed. My question is "what exactly should I be using to generate truly random numbers? Should I just manipulate the numbers with arithmetic or is there something else? To be specific, I'm looking for the "best practices" that programmers follow to generate random numbers in the c programming language.
Here is an example of a website I am talking about:
http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1042005782&id=1043284385
srand(time(NULL)) is good enough for general basic use. Its shortcomings are:
It's not suitable for cryptography, since it's possible for an attacker to predict the pseudo-random sequence. Random numbers used in cryptography need to be really unpredictable.
If you run the program several times in quick succession, the RNG will be seeded with the same or similar values (since the current time hasn't changed much), so you're likely to get similar pseudo-random sequences each time.
If you generate very many random numbers with rand, you're likely to find that they're not well-distributed statistically. This can be important if you're doing something like Monte Carlo simulations.
There are more sophisticated RNG libraries available for cryptographic and statistical use.
In case if you want a random number, use:
randomize () ;
m = random(your limit);
printf("%d", m);// dont forget to include stdlib

Is it acceptable to use rand() for cryptographically insecure random numbers?

Is it acceptable to use the C standard library's rand() function for random numbers that do not have to be cryptographically secure? If so, are there still better choices? If not, what should be used?
Of course, I assume the usual caveats about skew apply.
rand() suffers from some serious drawbacks.
There is no guarantee on the quality of the random number. This will vary from implementation to implementation.
The shared state used by different calls to rand, is not guaranteed to be thread safe.
As for POSIX C alternatives, there is random and random_r. OpenSSL provides more advances ways of generating random numbers.
The C++ (C++11 and later) library also provides a number of random number functions if including C++ in your project is an option.
Cryptographic security aside, there are a lot of systems where rand() has pretty atrocious randomness properties, and the standard advice if you need something better is to use the non-Standard random().
rand's poor properties on many systems include:
nonrandomness in the low-order bits (such that e.g. rand()%2 is guaranteed to alternate 0,1,0,1...).
relatively short period, perhaps "only" 4 billion or so
So my (reluctant) advice is that if you need "good" randomness (say, for a Monte Carlo simulation), you may very well want to investigate using a nonstandard alternative to rand(). (One of my eternal questions about C is why any vendor would spend time deploying a nonstandard random() instead of simply making rand() better. And I do know the canonical answers, although they suck.)
See also this similar question.
Yes, it is fine to use rand() to get pseudo-random numbers. In fact, that is the whole point of rand(). For simple tasks, where it is OK to be deterministic, you can even seed the system clock for simplicity.
The implementation of rand in mainstream C standard libraries may be adequate for casual use of pseudorandom numbers (such as in most single-player games, or for aesthetic purposes), especially if your application doesn't care about repeatable "randomness" across time or across computers. (But note that the rand specification in the C standard doesn't specify a particular distribution that the numbers delivered by rand have to follow.)
However, for more serious use of pseudorandom numbers, such as in a scientific simulation, I refer you to another answer of mine, where I explain that the problem with rand/srand is that rand—
Uses an unspecified RNG algorithm, yet
allows that RNG to be initialized with srand for repeatable "randomness".
These two points, taken together, hamper the ability of implementations to improve on the RNG's implementation; changing that RNG will defeat the goal of repeatable "randomness", especially if an application upgrades to a newer version of the C runtime library by the same vendor or is compiled with library implementations by different vendors. The first point also means that no particular quality of pseudorandom numbers is guaranteed. Another problem is that srand allows for only relatively small seeds — namely those with the same size as an unsigned.
However, even if the application doesn't care about repeatable "randomness", the fact that rand specifies that it behaves by default as though srand(1) were called (and thus, in practice, generates the same pseudorandom sequence by default) makes using rand harder to use effectively than it could be.
A better approach for noncryptographic pseudorandom numbers is to use a PRNG library—
that uses self-contained PRNGs that maintain their own state (e.g., in a single struct) and don't touch global state, and
that implements a PRNG algorithm whose details are known to the application.
I list several examples of high-quality PRNG algorithms for noncryptographic pseudorandom numbers.

seed random numbers in c

I am currently trying to teach myself c programming. I am stuck on learning random numbers. Many of the websites I visit use the time() function as a method of seeding the random number generator. But many posts and websites I have read say that using the system clock as a method of producing random numbers is flawed. My question is "what exactly should I be using to generate truly random numbers? Should I just manipulate the numbers with arithmetic or is there something else? To be specific, I'm looking for the "best practices" that programmers follow to generate random numbers in the c programming language.
Here is an example of a website I am talking about:
http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1042005782&id=1043284385
srand(time(NULL)) is good enough for general basic use. Its shortcomings are:
It's not suitable for cryptography, since it's possible for an attacker to predict the pseudo-random sequence. Random numbers used in cryptography need to be really unpredictable.
If you run the program several times in quick succession, the RNG will be seeded with the same or similar values (since the current time hasn't changed much), so you're likely to get similar pseudo-random sequences each time.
If you generate very many random numbers with rand, you're likely to find that they're not well-distributed statistically. This can be important if you're doing something like Monte Carlo simulations.
There are more sophisticated RNG libraries available for cryptographic and statistical use.
In case if you want a random number, use:
randomize () ;
m = random(your limit);
printf("%d", m);// dont forget to include stdlib

Logic behind the random number generator in C [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How does a random number generator work?
How does C compiler takes decisions whether which number should be generated next in a random number generation function? For example it always generates a new random number between the given range. How is that done?
It generates the next number by keeping some state and modifying the state every time you call the function. Such a function is called a pseudorandom number generator. An old method of creating a PRNG is the linear congruential generator, which is easy enough:
static int rand_state;
int rand(void)
{
rand_state = (rand_state * 1103515245 + 12345) & 0x7fffffff;
return rand_state;
}
As you can see, this method allows you to predict the next number in the series if you know the previous number. There are more sophisticated methods.
Various types of pseudorandom number generators have been designed for specific purposes. There are secure PRNGs which are slow but hard to predict even if you know how they work, and there are big PRNGs like Mersenne Twister which have nice distribution properties and are therefore useful for writing Monte Carlo simulations.
As a rule of thumb, a linear congruential generator is good enough for writing a game (how much damage does the monster deal) but not good enough for writing a simulation. There is a colorful history of researchers who have chosen poor PRNGs for their programs; the results of their simulations are suspect as a result.
It is not a compiler but a C library that has a function to produce pseudorandom (not truly random!) numbers.
Usually linear congruential generators are used for this.
Well, the C compiler doesn't take that decison. The next random number depends on the algorithm. Generating random number is not an easy task. Take a look at
http://www.math.utah.edu/~pa/Random/Random.html
http://computer.howstuffworks.com/question697.htm
http://en.wikipedia.org/wiki/Random_number_generation
It depends on the specific implementation of the pseudo random number generator (PRNG) in question. There are a great many variants in use.
A common example is the family of linear congruential generators (LCGs). These are defined by a recurrence relation:
Xn+1 <- aXn + c (mod m)
So each new sample from the PRNG is determined solely by the previous sample, and the constants a, c and m. Note that the choice of a, c and m is crucial, as discussed here.
LCGs are very simple and efficient. They are often used for the random number generators provided by the standard library. However, they have poor statistical properties and for better randomness, more advanced PRNGs are preferred.
There are many questions regarding this in stackoverflow. Here are few. You can take help from these.
implementation of rand()
Rand function in c
Rand Implementation
This is actually a really big topic. Some of the key things:
Random number generation is done at run-time, rather than compile-time.
The strategy for providing randomness depends (or should depend) greatly on the application. For example, if you simply need a sequence of values that are evenly distributed throughout the given range, solutions such as a linear congruential generator are used. If your application is security/cryptography related, you'll want the stronger property that your values are both randomly distributed and also unpredictable.
A major challenge is acquiring "real" randomness, which you can use to seed your pseudorandom generator (which "stretches" real randomness into an arbitrary amount of usable randomness). A common technique is to use some unpredictable system state (e.g., sample the location of the mouse, or keypress timing) and then use a pseudorandom generator to provide randomness to the system as a whole.

How to 'randomize()' random numbers in C(Linux)?

Trying to generate random numbers in C, rand() doesn't generate different numbers each time i compile the code, can anyone tell me how to use srand() or tell any other method for generating.
In order to generate a sequence of pseudorandom numbers, the generator needs to be seeded. The seed fully determines the sequence of numbers that will be produced. In C, you seed with srand, as you indicate. According to the srand(3) man page, no explicit seeding implies that the generator will use 1 as a seed. This expains why you always see the same numbers (but do remember that the sequence itself is pretty random, with quality depending on the generator used, even though the sequence is the same each time).
User mzabsky points out that one way to get a seed that feels random to a human user is to seed with time. Another common method (which I just saw that mzabsky also points out - sorry) is to seed the generator with the contents of the system's random number generator, which draws from an entropy pool fed by things such as mouse movement, disk timings etc. You can't draw a lot of randomness from the system generator, as it won't be able to gather enough entropy. But if you just draw a seed from it, you'll have chosen at random a sequence of random numbers in your program. Here's an example of how to do that in C on Linux:
unsigned int seed;
FILE* urandom = fopen("/dev/urandom", "r");
fread(&seed, sizeof(int), 1, urandom);
fclose(urandom);
srand(seed);
In light of Conrad Meyer's answer, I thought I'd elaborate a bit more. I'd divide the use of random numbers into three categories:
Variation. If you use random numbers to create seemingly random or varied behavior in for example a game, you don't need to think very hard about the topic, or about choosing a proper seed. Seed with time, and look at some other solution if this turns out not to be good enough. Even relatively bad RNGs will look random enough in this scenario.
Scientific simulations. If you use random numbers for scientific work, such as Monte Carlo calculations, you need to take care to choose a good generator. Your seed should be fixed (or user-changeable). You don't want variation (in the sense above); you want deterministic behavior but good randomness.
Cryptography. You'll want to be extremely careful. This is probably out of the scope of this thread.
This is commonly used solution:
srand ( time(NULL) );
Execution of all C code is deterministic, so you have to bring in something that is different every time you call the srand. In this case it is time.
Or you can read data from /dev/random (open it just like any other file).
If you are using an OS that does not provide /dev/random then use something like what is shown below
timeval t1;
gettimeofday(&t1, NULL);
srand(t1.tv_usec * t1.tv_sec);
This piece of code can be ported easily to other OS.
To improve the seed- you can combine (maybe using MD5 or a checksum algorithm) time product shown above with a MAC address of the host machine.
timeval t1;
gettimeofday(&t1, NULL);
unsigned int seed = t1.tv_usec * t1.tv_sec;
unsigned char mac_addr[6];
getMAC(&mac_addr);
improveSeedWithMAC(&seed, mac_addr) ; // MD5 or checksum ...
srand(seed);
Be careful; the rand(3) manpage on linux notes that rand() implementations on some platforms do not give good randomness on the lower-order bits. For this reason, you might want to use a library to acquire real random numbers. Glib provides useful functions like g_random_int_range() which may better suite your purpose.

Resources