Wednesday 21 December 2011

Nearly True Random Number Generator

The concept of generating random numbers is very important in many scenarios such as in encryption. The normal procedure to generate random numbers is to first use srand() function to seed the random number generator and then use the rand() function repeatedly to generate a pseudorandom number sequence. You can google it and find many such examples. But the problem in such an approach is that each time the seed is same, the same pseudorandom number sequence will be generated. This is a big problem in situations in which the programmer wants somewhat real randomness such as in encryption. One way to get around this problem is to utilize the current date and time to introduce somewhat real randomness in the system. The program snippet that demonstrates this is given below:

#include <windows.h>
#include <stdio.h>

int main()
{
    SYSTEMTIME lt;
    GetLocalTime(&lt);
    int ran, i;
    ran = 10000 * lt.wMilliseconds + 1000 * lt.wSecond + 100 * lt.wMinute + 10 * lt.wHour + lt.wDay;
    srand(ran);
    printf("10 nearly true random numbers:\n");
    for(i = 0; i < 10; i++)
    {
           printf("%d\t", rand());
     }
    return 0;
}

SYSTEMTIME is a structure that can hold date and time. First we define a struct lt of this type. Then we use the GetLocalTime() windows API function which takes the address of  lt as argument to fill this structure with current date and time. Next, the current Milliseconds, second, minute, hour and day are all added after multiplying each by some factor (10, 000, 1000, 100, 10, 1 respectively) and the result is stored in an integer ran. Randomness is actually generated right here. This number ran is used to seed the random number generator. Thus, now each time you execute the program, the random number sequence generated will be different. This trick can also be applied to cure the problems in real programming situations as already mentioned.

No comments:

Post a Comment