# Use SecureRandom

# Properties

Property Value
Rule ID UseSecureRandom
First seen in jSparrow version 3.20.0
Minimum Java version 1.2
Remediation cost 5 min
Links

# Description

Because the class java.util.Random (opens new window) relies on a pseudo-random number generator, it should not be used for security-critical applications. An attacker might be able to guess the next value generated by a pseudo-random number generator and thus access sensitive data. A more secure alternative is the class java.security.SecureRandom (opens new window) which relies on a cryptographically strong random number generator (RNG). This rule replaces invocations of the constructors Random() (opens new window) and Random(long seed) (opens new window) with invocations of SecureRandom (opens new window). In case of a seed argument, an additional statement is generated to invoke setSeed(long seed) (opens new window). Sonarcloud marks this issue (opens new window) as "Critical" by default.

# Benefits

Prevents generating predictable pseudo-random numbers.

# Code Changes

# Using Constructor Without Any Argument

Pre

Random random = new Random();
byte[] bytes = new byte[20];
random.nextBytes(bytes);

Post

Random random = new SecureRandom();
byte[] bytes = new byte[20];
random.nextBytes(bytes);

# Using Constructor With Seed Argument

Pre

Random random = new Random(System.currentTimeMillis());
byte[] bytes = new byte[20];
random.nextBytes(bytes);

Post

Random random = new SecureRandom();
random.setSeed(System.currentTimeMillis());
byte[] bytes = new byte[20];
random.nextBytes(bytes);

Automatic Application of This Rule

The automatic application of this rule is supported in the following jSparrow versions:

# Tags

1
default
You & jSparrow
default

Hey there! May I help you? 😊