Digital Marriage Invitation Card

Secure Random Number Example in Java


In Java programming language, we normally use the Math.random() to generate 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 a SecureRandom instance via the no-argument constructor or one of the getInstance methods.

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.


Share this article on: