In Java, the getInstance()
method is used to get the instance of the SecureRandom
class. If we create an instance of the SecureRandom
class using a new operator, it will use the SHA1PRNG
algorithm. We can provide an algorithm name to the getInstance()
method. The SecureRandom
class offers this method, which consists of methods to generate substantial random numbers.
SecureRandom.getInstance("algorithm name", "algorithm provider")
algorithm name
: This is the name of the algorithm. A NoSuchAlgorithmException
is thrown if the algorithm is not found.algorithm provider
: This is the name of the algorithm provider. A NoSuchProviderException
is thrown if the provider is not found in the list of registered security providers.This method returns a SecuredRandom
object.
import java.security.*;import java.util.*;public class main {public static void main(String[] argv){try{//create instance of securerandom with new operatorSecureRandom rndm = new SecureRandom();//create instance of securerandom with getInstance methodSecureRandom rndm1 = SecureRandom.getInstance("NativePRNG", "SUN");//get random integerSystem.out.println(rndm1.nextInt());}catch(Exception e){System.out.println("Exception is thrown");}}}
try/catch
block, since the getInstance()
method throws an exception.SecureRandom
object, rndm
, using the new operator.SecureRandom
object, rndm1
, using the getInstance()
method. Next, we pass the algorithm name as NativePRNG
and provider as SUN
.nextInt()
method on rndm1
object.Free Resources