You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Next »

The java.security.SecureRandom class is widely used for generating cryptographically strong random numbers. Random number generation depends on a source of entropy such as signals, devices or inputs from hardware. According to the java.security file present in the JRE's lib\security folder:

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.

An adversary should not be able to determine the original seed given several samples of random numbers. If that is not ensured, all future random numbers may be successfully predicted.

Noncompliant Code Example

This noncompliant code example constructs a secure random number generator that is seeded with the specified seed bytes.

 SecureRandom random = new SecureRandom(String.valueOf(new Date().getTime()).getBytes());

This constructor searches a registry of security providers and returns the first provider that supports secure random number generation. If no such provider exists, an implementation specific default is selected. Furthermore, the default system provided seed is overridden by a seed provided by the programmer. The current system time used as seed is predictable and can result in the generation of random numbers with insufficient entropy.

Compliant Solution 

Prefer the no-argument constructor of SecureRandom that uses the system specified seed value to generate a 128 byte long random number..

byte[] randomBytes = new byte[128];
SecureRandom random = new SecureRandom("SHA1PRNG", "SUN");
random.nextBytes(randomBytes);

Note that use of the setSeed() method to seed the SecureRandom object prior to invoking nextBytes() is insecure because that bypasses the standard system generated seeding mechanism. It is also recommended to specify the exact random number generator and provider for better portability.

Applicability

 

Bibliography

 


  

  • No labels