Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Published by Scroll Versions from space JavaSec and version Publish
Panel
borderColorgray
borderStyledashed

Category: 2018-12-10_16-48-19_CWE > CWE-335

Description:

Excerpt
Using a predictable seed in a pseudo-random number generator can lead to predictability of the numbers generated by it.

Using a predictable seed in a pseudo-random number generator can lead to predictability of the numbers generated by it.

Recommendation

If the predictability of the pseudo-random number generator does not matter then consider using the faster Random class from java.util. If it is important that the pseudo-random number generator produces completely unpredictable values then either let the generator securely seed itself by not specifing specifying a seed or specify a randomly generated, unpredictable seed.

Example

In the first example shown here, a constant value is used as a seed. Depending on the implementation of SecureRandom, this could lead to the same random number being generated each time the code is executed.

In the second example shown here, the system time is used as a seed. Depending on the implementation of SecureRandom, if an attacker knows what time the code was run, they could predict the generated random number.

In the third example shown here, the random number generator is allowed to generate its own seed, which it will do in a secure way.

Print only
     1SecureRandom prng = new SecureRandom();
     2int randomData = 0;
     3
     4// BAD: Using a constant value as a seed for a random number generator means all numbers it generates are predictable.
     5prng.setSeed(12345L);
     6randomData = prng.next(32);
     7
     8// BAD: System.currentTimeMillis() returns the system time which is predictable.
     9prng.setSeed(System.currentTimeMillis());
    10randomData = prng.next(32);
    11
    12// GOOD: SecureRandom implementations seed themselves securely by default.
    13prng = new SecureRandom();
    14randomData = prng.next(32);
Dont print
Code Block
languagejava
themeEclipse
linenumberstrue
SecureRandom prng = new SecureRandom();
int randomData = 0;

// BAD: Using a constant value as a seed for a random number generator means all numbers it generates are predictable.
prng.setSeed(12345L);
randomData = prng.next(32);

// BAD: System.currentTimeMillis() returns the system time which is predictable.
prng.setSeed(System.currentTimeMillis());
randomData = prng.next(32);

// GOOD: SecureRandom implementations seed themselves securely by default.
prng = new SecureRandom();
randomData = prng.next(32);
References
    Htmlcomment
    hiddentrue
    hashconfluence_uploader_hash:bcd20a58418ac54aeb664eabd645332dbf10b984d64624bbc6a320002fb11114d28f1dea32d7c1dc