org.randomness
Enum TRNG

java.lang.Object
  extended by java.lang.Enum<TRNG>
      extended by org.randomness.TRNG
All Implemented Interfaces:
Serializable, Comparable<TRNG>

public enum TRNG
extends Enum<TRNG>

List of implemented True Random Number Generators - a sources of unpredictable data.

PROVISIONAL API, WORK IN PROGRESS

An appropriate TRNG produces output that is fully dependent on some unpredictable physical source that produces entropy. Contrast with a PRNG.

Thanks to many people contributed his works and ideas into Truerandomness:

Author:
Anton Kabysh (randomness adaptation),
Joshua Bloch, Gadi Guy (threads synchronization, system entropy ),
Daniel Dyer ( random.org - original uncommons-math RandomDotOrgSeedGenerator),
Damon Hart-Davis ( threaded entropy - Entropy Pool version),
The threaded entropy algorithm is based on an idea of Marcus Lippert.,
QRBG service created by Radomir Stevanović (Center for Informatics and Computing, Ruđer Bošković Institute) and Mario Stipčević (Division of experimental physics, Ruđer Bošković Institute).,
Mads Haahr (parts of TRNG javadoc description),
Doug Lea (idea and implementation of java.util.concurrent.ThreadLocalRandom)
See Also:
Wikipedia - Hardware random number generator, Wikipedia - Entropy (information theory), Wikipedia - Next bit test

Enum Constant Summary
DEV_RANDOM
          TRNG strategy that gets random data from /dev/random on systems that provide it (Solaris/Linux).
DEV_URANDOM
          TRNG strategy that gets random data from unblocking /dev/urandom on systems that provide it (Solaris/Linux).
HOTBITS
          Obtains genuine random data from John Walker's HotBits radioactive decay random sequence generator.
NATIVE
          Default TRNG implementation that uses Java's bundled SecureRandom RNG to generate random data in the way depending on native platform ( it can be CryptoAPI call on Windows, read from dev/random on Linux, or other).
QRBG
          TODO PROVISIONAL API, WORK IN PROGRESS: Quantum random bit generator based on photonic emission in semiconductors from Ruđer Bošković Institute.
RANDOM_ORG
          RANDOM.ORG is a true random number service that generates randomness via atmospheric noise.
SYSTEM_INFORMATION
          This technique gathers into buffer miscellaneous system information, some machine dependent, some not, and hash it using SHA hash.
THREADS_AND_COUNTER
          Generate entropy using Thread synchronization and counter to generate random bytes, its following the same sort of strategy as the thread synchronization entropy generator, but not so expensive in terms of CPU time and always generates new entropy each time.
THREADS_SYNCHRONIZATION
          In this technique entropy produced by counting the number of times the VM manages to loop in a given period.
 
Field Summary
static TRNG ATMSFERIC_NOISE
          A suitable physical phenomenon as entrpy source is atmospheric noise, which is quite easy to pick up with a normal radio.
 AtomicInteger BUFFERLEN
          Determine the recommended TRNG buffer size.
static TRNG RADIOACTIVE_DECAY
          Radioactive decay is the spontaneous, stochastic (i.e. random) physical phenomenon suitable to be entropy source based on quantum effects.
 AtomicInteger TEST_BUFFER_SIZE
          Size of buffer where entropy gathered for testing purposes.
 
Method Summary
static boolean checkGeneratedBits(byte[] bits)
          Simple and fast check on generated bits; throws an Error if the generator may be broken.
 Truerandomness current()
          TODO PROVISIONAL API, WORK IN PROGRESS: Returns a unique TRNG entropy generator isolated to the current thread (thread local random).
static byte[] getSystemEntropy()
          Generate entropy collected from various system sources e.g. time, date, memory loading and processed via SHA-1 cryptosecure hash function.
 boolean isSupported()
          Checks whatever or not this entropy source is acessible on current platform.
static int nextHashCodeEntropy()
          Returns the 32-bit unpredictable value obtained from hash code value containing several bits of entropy.
static int nextTimeEntropy()
          PROVISIONAL API, WORK IN PROGRESS: Retunrn's 64-bit unpredictable value created from system time sources such us System.currentTimeMillis() and System.nanoTime().
 Truerandomness shared()
          TODO PROVISIONAL API, WORK IN PROGRESS:
static TRNG valueOf(String name)
          Returns the enum constant of this type with the specified name.
static TRNG[] values()
          Returns an array containing the constants of this enum type, in the order they are declared.
 
Methods inherited from class java.lang.Enum
clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf
 
Methods inherited from class java.lang.Object
getClass, notify, notifyAll, wait, wait, wait
 

Enum Constant Detail

THREADS_SYNCHRONIZATION

public static final TRNG THREADS_SYNCHRONIZATION
In this technique entropy produced by counting the number of times the VM manages to loop in a given period. This number roughly reflects the machine load at that point in time. The samples are translated using a permutation (s-box) and then XORed together. This process is non linear and should prevent the samples from "averaging out". The s-box was designed to have even statistical distribution; it's specific values are not crucial for the security of the seed. We also create a number of sleeper threads which add entropy to the system by keeping the scheduler busy. Twenty such samples should give us roughly 160 bits of randomness. These values are gathered in the background by a daemon thread thus allowing the system to continue performing it's different activites, which in turn add entropy to the random seed.

Recommended buffer size from 0 to 20 bytes. Entropy produced byte-by-byte, so its very time dependent and slowly.

See Also:
SeedGenerator Source code

SYSTEM_INFORMATION

public static final TRNG SYSTEM_INFORMATION
This technique gathers into buffer miscellaneous system information, some machine dependent, some not, and hash it using SHA hash. It is not recommended to use this TRNG in a critical secure points (e.g. as a seed for CSPRNG), because system information has low entropy. But this TRNG can be very useful in combination with other TRNG as a Nonce.

Recommended buffer size - 20 bytes, entropy produced by 20 bytes word.

See Also:
Source code

NATIVE

public static final TRNG NATIVE
Default TRNG implementation that uses Java's bundled SecureRandom RNG to generate random data in the way depending on native platform ( it can be CryptoAPI call on Windows, read from dev/random on Linux, or other). This is the only entropy strategy that is guaranteed to work on all platforms.

Vary from platform to platform, Default buffer size - 20 bytes. Good quality entropy, should be fast.

See Also:
Seeding random number generators (ctd): looking for entropy

DEV_RANDOM

public static final TRNG DEV_RANDOM
TRNG strategy that gets random data from /dev/random on systems that provide it (Solaris/Linux). If /dev/random does not exist or is not accessible, a UnsupportedOperationException with comments is thrown.

Implementation try's to read's number of bytes from beginning of the file to the byte buffer. It can throw UnsupportedOperationException if we can't create file lock, InternalError if we can't read bytes from file, and IllegalStateException if file lock can't be released.

/dev/random must present in system. Default buffer size - 512 bytes.

See Also:
Wikipedia - /dev/random

DEV_URANDOM

public static final TRNG DEV_URANDOM
TRNG strategy that gets random data from unblocking /dev/urandom on systems that provide it (Solaris/Linux). If /dev/urandom does not exist or is not accessible, a UnsupportedOperationException with comments is thrown.

Implementation try's to read's number of bytes from beginning of the file to the byte buffer. It can throw UnsupportedOperationException if we can't create file lock, InternalError if we can't read bytes from file, and IllegalStateException if file lock can't be released.

Not buffered, /dev/urandom must present in system.

See Also:
Wikipedia - /dev/urandom

RANDOM_ORG

public static final TRNG RANDOM_ORG
RANDOM.ORG is a true random number service that generates randomness via atmospheric noise. The randomness comes from atmospheric noise, which for many purposes is better than the pseudo-random number algorithms typically used in computer programs. RANDOM.ORG uses a simple quota system to make sure nobody hogs all the random numbers produced by the generator. You get a free top-up of up to 200,000 bits every day (just after midnight UTC) until you reach the default allowance of 1,000,000 bits. If the server is lightly loaded, you may get a free top-up earlier, but don't count on it.

Connects to the website (via HTTPS) and downloads a set of random bits. It is generally better to use the DEV_RANDOM where possible, as it should be much quicker. This seed generator is most useful on Microsoft Windows and other platforms that do not provide /dev/random.

Recommended buffer size - 1024 bytes (max allowance 1,000,000 bits per request, or 10000 ints), very good quality entropy. Connection via HTTPS must be open, or exception will be thrown.

See Also:
RANDOM.ORG - True Random Number Service

HOTBITS

public static final TRNG HOTBITS
Obtains genuine random data from John Walker's HotBits radioactive decay random sequence generator. HotBits is an Internet resource that brings genuine random numbers, generated by a process fundamentally governed by the inherent uncertainty in the quantum mechanical laws of nature, directly to your computer in a variety of forms. HotBits are generated by timing successive pairs of radioactive decays detected by a Geiger-Muller tube interfaced to a computer. You order up your serving of HotBits by filling out a request form specifying how many random bytes you want and in which format you'd like them delivered. Your request is relayed to the HotBits server, which flashes the random bytes back to you over the Web. Since the HotBits generation hardware produces data at a modest rate (about 100 bytes per second), requests are filled from an “inventory” of pre-built HotBits. Once the random bytes are delivered to you, they are immediately discarded—the same data will never be sent to any other user and no records are kept of the data at this or any other site. (Of course, if you're using the random data for cryptography or other security-related applications, you can't be certain I'm not squirreling away a copy. But I'm not, really.)

Buffer size - 1024 bytes (maximum 2048 per request). Very good quality entropy. Connection via HTTPS must be open, or exception will be thrown.

See Also:
HotBits: Genuine random numbers, generated by radioactive decay

QRBG

public static final TRNG QRBG
TODO PROVISIONAL API, WORK IN PROGRESS: Quantum random bit generator based on photonic emission in semiconductors from Ruđer Bošković Institute.

QRBG is a fast, nondeterministic and novel random number generator whose randomness relies on intrinsic randomness of the quantum physical process of photonic emission in semiconductors and subsequent detection by the photo-electric effect. The timing information of detected photons is used to generate binary random digits - bits, with effciency of nearly 0.5 bits per detected random event. Device consists of a light source (LED), one single-photon detector and fast electronics for the timing analysis of detected photons providing random output numbers (bits) at (currently) 16 Mbit/sec. By using only one photodetector (in contrast to other similar solutions) there is no need to perform any netuning of the generator, moreover, the method used is immune to detector instability problems, which fosters the autonomous work of the service (with- out the usually required periodic calibrations of the generator). For the purpose of eliminating correlations, a restartable clock method is used for time interval measurement.

The collection of statistical tests (including NIST's "Statistical Test Suite for Random and Pseudorandom Number Generators for Cryptographic Applications" and DIEHARD battery of strong statistical randomness tests) applied to random numbers sequences longer than 1 Gb produced with this quantum random number generator presents results which demonstrate the high quality of randomness resulting in bias1 less than 10-4, autocorrelation consistent with zero, near maximal binary entropy and measured min-entropy near theoretical maximum. For much more details on these and other performed tests results, see publications on the main site.

See Also:
Quantom Random Bit Generator Service

THREADS_AND_COUNTER

public static final TRNG THREADS_AND_COUNTER
Generate entropy using Thread synchronization and counter to generate random bytes, its following the same sort of strategy as the thread synchronization entropy generator, but not so expensive in terms of CPU time and always generates new entropy each time.

This implementation uses two threads A and B. A starts B and sleeps for a certain amount of time (~50 ms). Meanwhile B starts counting up a global variable. When A wakes up again it stops B and checks if the content of the global variable is odd (-> generate a '1') or even (-> generate a '0'). This process is repeated for each bit.

This is not a good substitute for real external entropy, e.g. random.org or hotbits. This may not work with all VMs but attempts to adapt itself to the current VM and workload to be as robust (and fast) as possible.

Recommended buffer size - from 0 to 20 bytes. This type of entropy is very time dependent. Should be faster than THREADS_SYNCHRONIZATION.

See Also:
org.bouncycastle.crypto.prng.ThreadedSeedGenerator
Field Detail

ATMSFERIC_NOISE

public static final TRNG ATMSFERIC_NOISE
A suitable physical phenomenon as entrpy source is atmospheric noise, which is quite easy to pick up with a normal radio. This is the approach used by RANDOM.ORG.

See Also:
Wikipedia - Atmospheric noise, Wikipedia - Atmos

RADIOACTIVE_DECAY

public static final TRNG RADIOACTIVE_DECAY
Radioactive decay is the spontaneous, stochastic (i.e. random) physical phenomenon suitable to be entropy source based on quantum effects. This is the approach used by HOTBITS, where entropy obtained by the beta decay of Cæsium-137 to Barium-137.

See Also:
Wikipedia - Nuclear Decay,

BUFFERLEN

public final AtomicInteger BUFFERLEN
Determine the recommended TRNG buffer size. You can set this configurable to new value.

The default buffer size for all implementer TRNG's:

TRNG Buffer size
/DEV/RANDOM Any, allowed by system. Default - 512 bytes.
/DEV/URANDOM Any, allowed by system. Default - 1024 bytes.
HOTBITS 1024 bytes (maximum 2048 per request)
NATIVE Vary for different platforms. Default - 20 bytes.
RANDOM.ORG 1024 bytes (max 10000 bytes per request)
SYSTEM INFORMATION 20 bytes
THREADS AND COUNTER from 0 to 20 bytes
THREADS SYNCHRONIZATION from 0 to 20 bytes


TEST_BUFFER_SIZE

public final AtomicInteger TEST_BUFFER_SIZE
Size of buffer where entropy gathered for testing purposes.

Method Detail

values

public static TRNG[] values()
Returns an array containing the constants of this enum type, in the order they are declared. This method may be used to iterate over the constants as follows:
for (TRNG c : TRNG.values())
    System.out.println(c);

Returns:
an array containing the constants of this enum type, in the order they are declared

valueOf

public static TRNG valueOf(String name)
Returns the enum constant of this type with the specified name. The string must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)

Parameters:
name - the name of the enum constant to be returned.
Returns:
the enum constant with the specified name
Throws:
IllegalArgumentException - if this enum type has no constant with the specified name
NullPointerException - if the argument is null

checkGeneratedBits

public static boolean checkGeneratedBits(byte[] bits)
                                  throws Error
Simple and fast check on generated bits; throws an Error if the generator may be broken. This does a very simple check that some set of `random' bits that we have generated does appear to be reasonably random.

This does not alter its input array or copy it anywhere and is designed to be fast.

This will ignore very short arrays where its has no reasonable chance of detecting faulty output. Our threshold is about 8 bytes.

The possible indicators of faulty generation looked for are:

This needs to be used thoughtfully...

Parameters:
bits - the byte array to be tested.
Throws:
Error - if it looks like the generator may be grossly faulty.

getSystemEntropy

public static final byte[] getSystemEntropy()
Generate entropy collected from various system sources e.g. time, date, memory loading and processed via SHA-1 cryptosecure hash function.

Returns:
20 byte hashed system entropy

isSupported

public boolean isSupported()
Checks whatever or not this entropy source is acessible on current platform.

For every platform designed own best native generator which works well.

 Truerandomness entropy = null;
 if (TRNG.DEV_RANDOM.isSupported())
        entropy = TRNG.DEV_RANDOM.current();
 else
        entropy = TRNG.NATIVE.current();
 

Returns:
true if generators of this type can be instantiated on this platform, false otherwise.
See Also:
CSPRNG.isSupported()

current

public Truerandomness current()
TODO PROVISIONAL API, WORK IN PROGRESS: Returns a unique TRNG entropy generator isolated to the current thread (thread local random). An attempt to use this instance from annoter thread will throw ConcurrentModificationException.

Usages of this class should typically be of the form: TRNG.XXX.current().nextX(...) (where XXX - one of implemented TRNG generators, and X is Int, Long, etc). When all usages are of this form, it is never possible to accidently share a thread local random across multiple threads.

The thread local random instance is unique for parent thread, so locality can be cheked as:

 public boolean isThreadLocal(Randomness rnd) {
        return TRNG.XXX.current() == rnd;
 }
 
where XXX - one of implemented TRNG generators

Returns:
the thread local instance of TRNG for current thread.
See Also:
ThreadLocal,
PRNG#current() Thread local for Pseudorandomness,,
CSPRNG#current() Thread-local for Cryptorandomness.

shared

public Truerandomness shared()
TODO PROVISIONAL API, WORK IN PROGRESS:

Returns:

nextHashCodeEntropy

public static final int nextHashCodeEntropy()
Returns the 32-bit unpredictable value obtained from hash code value containing several bits of entropy. It is not a substitution of real entropy sources, and cannot be used to create generator's seed, as for cryptographic purposes.

This method should be used to get fast unpredictable value, with several bits of entropy for non cryptographic purposes. Random values created from hash codes obtained from the Ghost-objects (Object created, return hash code, and garbage collected).

Returns:
unique unpredictable 32 bit value from hash code of Ghost-objects.

nextTimeEntropy

public static final int nextTimeEntropy()
PROVISIONAL API, WORK IN PROGRESS: Retunrn's 64-bit unpredictable value created from system time sources such us System.currentTimeMillis() and System.nanoTime().

Returns:
32 bit entropy word