MD5-based random number generator

After becoming frustrated with the lack of a standalone, portable, decent random number generator, I decided to make one based on a one-way hash function. I chose MD5 since it is fast and free source was readily available. More cryptographically secure hash functions are available (e.g. SHA-1), but for the purposes of a rand/random/erand48 replacement, MD5 should be more than sufficient.

MD5 takes an arbitrary amount of input and yields a 16 byte hash. This RNG continually MD5's a 16 byte digest, and uses the bottom N bits as the random number yielded, where N is just large enough to include the largest random number desired, e.g.:

	To yield a random number between 0 and r:

             create mask which has enough bits to include all of r
                     (for example, if r is 100, mask would be 0x7F)

             do {
                     digest = MD5(digest)
                     number = digest & mask
             } while (number > r)

The digest should be loaded and saved to a disk file between invocations of a program using the RNG.

Source code

The random number generator is used by the dice server.

Rich Skrenta (

Main Index  |  Olympia  |  Arena  |  PBM FAQ  |  Links