Generating cryptographically secure pseudorandom numbers

suggest change

Random is good enough for everyday use, but it is a linear congruential generator whose output can be predicted from enough samples. ThreadLocalRandom is also not suitable for cryptography. Since Java 8 it is not that 48-bit generator. Neither class is suitable for key generation.

One can use java.security.SecureRandom in situations where a PRNG with an output that is very hard to predict is required. Predicting the random numbers created by instances of this class is hard enough to label the class as cryptographically secure.

import java.security.SecureRandom;
import java.util.Arrays;

public class Foo {
    public static void main(String[] args) {
        SecureRandom rng = new SecureRandom();
        byte[] randomBytes = new byte[64];
        rng.nextBytes(randomBytes); // Fills randomBytes with random bytes (duh)
        System.out.println(Arrays.toString(randomBytes));
    }
}

SecureRandom is considerably slower than Random and other non-cryptographic PRNGs such as the Mersenne Twister and Xorshift. Random's period is 248. The SUN SHA1PRNG implementation keeps a 160-bit SHA-1 state, so its period is at most 2160. That is not the period of every SecureRandom algorithm.

The implementation is platform and provider dependent. new SecureRandom() uses the configured default algorithm, which may be NativePRNG or a DRBG rather than SHA1PRNG. The SUN SHA1PRNG class is sun.security.provider.SecureRandom. Seeding uses the platform entropy source:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents