True random generation in Java

Since tapping into those sources of random data would require hardware access of some kind such a library can't be written portably using pure Java.

You can however try to write platform-dependent code to read the platforms source of random data. For Linux (and possibly other Unix-like systems as well) that could be /dev/random for example.

Also, look at the SecureRandom class, it might already have what you want.


Your question is ambiguous, which is causing the answers to be all over the place.

If you are looking for a Random implementation which relies on the system's source of randomness (as I'm guessing you are), then java.security.SecureRandom does that. The default configuration for the Sun security provider in your java.security file has the following:

#
# Select the source of seed data for SecureRandom. By default an
# attempt is made to use the entropy gathering device specified by
# the securerandom.source property. If an exception occurs when
# accessing the URL then the traditional system/thread activity
# algorithm is used.
#
# On Solaris and Linux systems, if file:/dev/urandom is specified and it
# exists, a special SecureRandom implementation is activated by default.
# This "NativePRNG" reads random bytes directly from /dev/urandom.
#
# On Windows systems, the URLs file:/dev/random and file:/dev/urandom
# enables use of the Microsoft CryptoAPI seed functionality.
#
securerandom.source=file:/dev/urandom

If you are really asking about overriding this with something even more truly random, it can be done either by changing this property, or by using another SecureRandom. For example, you could use a JCE provider backed by an HSM module such as nCipher nShield which has its own PRNG, or other solutions mentioned in the thread.


Quick and dirty:

public static int generateRandom() throws IOException
{
    int num = 0;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    for (int i = 0 ; i < Integer.SIZE ; i++)
    {
        System.out
          .println("Flip a fair coin. Enter h for heads, anything else for tails.");

        if (br.readLine().charAt(0) == 'h')
        {
            num += Math.pow(2, i);
        }
    }

    return num;
}

Check out http://random.org/

RANDOM.ORG is a true random number service that generates randomness via atmospheric noise.

The Java library for interfacing with it can be found here: http://sourceforge.net/projects/trng-random-org/

Tags:

Java

Random