Tuesday 25 December 2012

PHP Random Generation Functions

Random Number Generation In Better Way :

Random Number are one of the prime need in making a complicated algorithm.  The main aim of a random number generator is to produce a number which is Unpredictable (impassible to predict) an Unbiased (enven chance for every number in a range to appear).
 To achieve is sort of irregularities  PHP introduce several random number generator function. Such generator are discussed below :

Basic Random Generators :

 rand() and mt_rand() :    Each of these functions generates a random number using its own internal algorithm from a seed. Think of the seed as the starting point for the algorithm. If the seed is unknown then the numbers produced are quite strong. However, if the seed is known or is able to be tampered with, then the generated sequence is very predictable. A common attack on programs is “seed poisoning”, where the attacker has found a way to tamper with the seed and use a known value, which will undermine your random number generation process.

lcg_value() : It generates weaker random numbers but the seed is internal and less susceptible to seed poisoning attacks. However,it only receives a seed on the first call and the seed is made up of the process id and current time. An attacker that knows this can use this information to reasonably predict the sequence of numbers generated.

uniquid() : This is another function used to generate random strings and it internally uses the current time and then calls lcg_value(). So if lcg_value() is compromised the generation of unique strings from uniquid() can be guessed fairly easily.

mcrypt(): The best way to generate random numbers in PHP is to use MCrypt, which is a replacement of the UNIX crypt command. MCrypt provides the mcrypt_create_vi() function which can be used with MCRYPT_DEV_RANDOM to generate very strong and unhampered random numbers. the choice of random number generator is yours and may even vary depending on your needs and the project. While random number generation may seem hard on the surface, by understanding the rules of predictability and bias you are better prepared to create better random numbers and avoid the common pitfall of introducing bias to your system. Keeping your random numbers pure and free from attacks is important and can be critical in high-performance systems such as security, where these are frequently used.

string mcrypt_create_iv ( int $size [, int $source = MCRYPT_DEV_RANDOM ] )