on random

Once I took a course called “An Introduction To Cryptography” or something along those lines as a part of my masters studies. In the first lecture the lecturer stated that the whole point of this course will be to prove mathematically that it’s theoretically possible to generate pseudo random numbers that are indistinguishable from real random phenomena. After that there were lectures upon lectures of proofs of different things that were probably required to prove that. I really didn’t understand most of it…

Anyway, back in the real world programmers rarely seem to care much about randomness and just seed the random with time() and think it’s good enough.  Since time will only give you second precision this seed can be rather easily brute forced if you know the timeframe in which the seeding was done. If you know it down to 1 hour precision you have only 60*60 = 3600 possible seeds to try.

So to get some rust off my C skills I wrote couple of simple random functions that do a bit better seeding by using microseconds in addition to seconds and also extra entropy from the operating systems address space layout randomization (if available).

C version:

#include <stdio.h>
#include <stdlib.h>
 
#include <sys/time.h>
 
long int randint() {
    static char seeded = 0;
 
    if (0 == seeded) {
        struct timeval t;
 
        gettimeofday(&t, NULL);
        // using microseconds will widen search space for the attacker compared to using just seconds as returned by time()
        // in addition we hope to get some additional machine specific entropy from the OS address space layout randomization
        // by XORing with the address of the var t which should be on different address each time
        srand((t.tv_usec*t.tv_sec)^((long)&t));
        seeded = 1;
    }
 
    return random();
}
 
int main(void) {
     printf("%ld\n", randint());
     printf("%ld\n", randint());
}

And here’s the same thing as a C++ functor.

#include <stdio.h>
#include <stdlib.h>
 
#include <sys/time.h>
 
#include <iostream>
 
class Randomize {
public:
    Randomize() {
        struct timeval t;
 
        gettimeofday(&t, NULL);
        // using microseconds will widen search space for the attacker compared to using just seconds as returned by time()
        // in addition we hope to get some additional machine specific entropy from the OS address space layout randomization
        // by XORing with the address of the var t which should be on different address each time
        srand((t.tv_usec*t.tv_sec)^((long)&t));
    }
 
    long int operator() () {
        return random();
    }
};
 
int main(void) {
    Randomize r = Randomize();
    printf("%ld\n", r());
    printf("%ld\n", r());
}

Leave a Reply

Your email address will not be published.


*