# Use SecureRandom

# 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.

# Tags

# 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);

Use a Java Refactoring Tool

Automate this Refactoring system-wide

You can apply this refactoring for free with the jSparrow Eclipse IDE plug-in.
Install the plug-in for Eclipse IDE: Eclipse Marketplace.

a drawn cute bird pointing at a graph that shows positive results

# Properties

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