HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java 8 / Secure Random Number Generation in Java

Secure Random Number Generation in Java

If you’ve been developing software for a while, you know how to generate a random number and perhaps even securely with Java’s SecureRandom class. Unfortunately, generating secure random numbers is not as easy as simply using SecureRandom.

In this java example, we’ve assembled a simple checklist to help you be successful when using secure random numbers in your applications.

Read More : Generate Secure Hash in Java

1. How to generate secure random number

Generally, random number generation depends on a source of entropy (randomness) such as signals, devices, or hardware inputs. In Java, The java.security.SecureRandom class is widely used for generating cryptographically strong random numbers.

Deterministic random numbers have been the source of many software security breaches. The idea is that an adversary (hacker) should not be able to determine the original seed given several samples of random numbers. If this restriction is violated, all future random numbers may be successfully predicted by the adversary.

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;

public class Main 
{
	public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException 
	{
		SecureRandom secureRandomGenerator = SecureRandom.getInstance("SHA1PRNG", "SUN");
		
		// Get 128 random bytes
		byte[] randomBytes = new byte[128];
		secureRandomGenerator.nextBytes(randomBytes);
		
		//Get random integer
		int r = secureRandomGenerator.nextInt();
		
		//Get random integer in range
		int randInRange = secureRandomGenerator.nextInt(999999);
	}
}

2. Secure Random Number – Best Practices

2.1. Determine performance criteria and workload balancing

If performance is a premier consideration, then use SHA1PRNG, which seeds from /dev/urandom. SHA1PRNG can be 17 times faster than NativePRNG, but seeding options are fixed.

Seeding with NativePRNG is more flexible, but it blocks if entropy is not great enough on the server since it reads from /dev/random. If you don’t know where to begin, start with SHA1PRNG.

2.2. Don’t accept defaults; specify the PRNG and the provider you want to use

Specify your criteria like this:

SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "SUN");

Following is additional information about supported PRNGs and providers.

The following is a list of PRNGs for the SUN provider:

  • SHA1PRNG (Initial seeding is currently done via a combination of system attributes and the java.security entropy gathering device)
  • NativePRNG (nextBytes() uses /dev/urandom, generateSeed() uses /dev/random)
  • NativePRNGBlocking (nextBytes() and generateSeed() use /dev/random)
  • NativePRNGNonBlocking (nextBytes() and generateSeed() use /dev/urandom)
  • NativePRNGBlocking and NativePRNGNonBlocking are available in JRE 8+.

For information on additional providers, see Java Cryptography Architecture Oracle Providers Documentation for JDK 8. Oracle also provides documentation describing the providers by OS platform.

2.3. Provide more opportunities increase entropy

Create a new instance of SecureRandom periodically and reseed, like this:

SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "SUN");
sr.setSeed(SecureRandom.generateSeed(int))

Periodic reseeding defends against data disclosure if a seed is leaked. If using SHA1PRNG, always call java.security.SecureRandom.nextBytes(byte[]) immediately after creating a new instance of the PRNG.

2.4. Reduce predictability

If egdSource, a configuration parameter in the java.security file, or the java.security.egd system property is assigned with a predictable file/URL, then SecureRandom can become predictable.

2.5. Patch old Java versions

JRE versions older than 1.4.2 have known problems generating SHA1PRNG secure seeds. Then again, if you’re using versions of Java this old, you have bigger security concerns.

Old versions of Java are very insecure, and staying up-to-date on patches is very important. One of the best ways to keep your customers safe is to quickly certify your software against the most recent Oracle Critical Patch Update possible.

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Java 8 Tutorial

  • Java 8 Features
  • Java 8 forEach
  • Java 8 Stream
  • Java 8 Boxed Stream
  • Java 8 Lambda Expression
  • Java 8 Functional Interface
  • Java 8 Method Reference
  • Java 8 Default Method
  • Java 8 Optional
  • Java 8 Predicate
  • Java 8 Regex as Predicate
  • Java 8 Date Time
  • Java 8 Iterate Directory
  • Java 8 Read File
  • Java 8 Write to File
  • Java 8 WatchService
  • Java 8 String to Date
  • Java 8 Difference Between Dates
  • Java 8 Join Array
  • Java 8 Join String
  • Java 8 Exact Arithmetic
  • Java 8 Comparator
  • Java 8 Base64
  • Java 8 SecureRandom
  • Internal vs External Iteration

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces