How to generate secure random number in Java


In Java programming language, we normally use the Math.random() to generate a random number but Math.random() will causes the vulnerability in your application. To generate the cryptographically strong random number, Java provides the SecureRandom class inside java.security package.

A caller obtains an SecureRandom instance via the no-argument constructor or one of the methods getInstance.

For Windows Machine

If you are a Windows user, you need to pass SHA1PRNG algorithm in getInstance methods.

SecureRandomNumberWin.java
package org.websparrow;

import java.security.SecureRandom;

public class SecureRandomNumberWin {

	public static void main(String[] args) {

		SecureRandom secureRandom = null;
		try {
			secureRandom = SecureRandom.getInstance("SHA1PRNG");

			System.out.println(secureRandom.nextInt(1000000));

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}

For Linux Machine

Linux user will pass the NativePRNG algorithm in getInstance methods.

SecureRandomNumberLinux.java
package org.websparrow;

import java.security.SecureRandom;

public class SecureRandomNumberLinux {
	
	public static void main(String[] args) {

		SecureRandom secureRandom = null;
		try {
			secureRandom = SecureRandom.getInstance("NativePRNG");

			System.out.println(secureRandom.nextInt(1000000));

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Throws: NoSuchAlgorithmException – if no Provider supports a SecureRandomSpi implementation for the specified algorithm.


Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.