Saturday, November 16, 2024
Google search engine
HomeLanguagesJavaSecureRandom getInstance() method in Java with Examples

SecureRandom getInstance() method in Java with Examples

getInstance( String algorithm )

The getInstance() method of java.security.SecureRandom class is used to return a SecureRandom object that implements the specified Random Number Generator (RNG) algorithm.

This method traverses the list of registered security Providers, starting with the most preferred Provider. A new SecureRandom object encapsulating the SecureRandomSpi implementation from the first Provider that supports the specified algorithm is returned.

Syntax:

public static SecureRandom 
getInstance( String algorithm ) 
throws NoSuchAlgorithmException

Parameters: This method takes the standard RNG algorithm as a parameter.

Return Value:This method returns the new SecureRandom object .

Exception: This method throws NoSuchAlgorithmException – if no Provider supports a SecureRandomSpi implementation for the specified algorithm.

Note:

  1. The programs will not run on online IDE.
  2. Every time Secure Random class will generate random output.

Below are the examples to illustrate the getInstance() method:

Example 1:




// Java program to demonstrate
// nextBytes() method
  
import java.security.*;
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
    {
        try {
            // creating the object of SecureRandom and getting instance
            // By using getInstance() method
            SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
  
            // Declaring the string variable
            String str = "Tajmahal";
  
            // Declaring the byte Array
            // converting string into byte
            byte[] b = str.getBytes();
  
            // printing the byte array
            System.out.println("Byte array before operation : "
                               + Arrays.toString(b));
  
            // generating user-specified number of random bytes
            // using nextBytes() method
            sr.nextBytes(b);
  
            // printing the new byte array
            System.out.println("Byte array after operation : "
                               + Arrays.toString(b));
        }
  
        catch (NoSuchAlgorithmException e) {
  
            System.out.println("Exception thrown : " + e);
        }
        catch (ProviderException e) {
  
            System.out.println("Exception thrown : " + e);
        }
    }
}


Output:

Byte array before operation : [84, 97, 106, 109, 97, 104, 97, 108]
Byte array after operation : [124, -66, -62, -5, -71, -4, 30, 16]

Example 2:




// Java program to demonstrate
// getInstance() method
  
import java.security.*;
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
    {
        try {
            // creating the object of SecureRandom and getting instance
            // By using getInstance() method
            System.out.println("Trying to get the instance of TAJMAHAL");
            SecureRandom sr = SecureRandom.getInstance("TAJMAHAL");
  
            // Declaring the string variable
            String str = "Tajmahal";
  
            // Declaring the byte Array
            // converting string into byte
            byte[] b = str.getBytes();
  
            // printing the byte array
            System.out.println("Byte array before operation : "
                               + Arrays.toString(b));
  
            // generating user-specified number of random bytes
            // using nextBytes() method
            sr.nextBytes(b);
  
            // printing the new byte array
            System.out.println("Byte array after operation : "
                               + Arrays.toString(b));
        }
  
        catch (NoSuchAlgorithmException e) {
  
            System.out.println("Exception thrown : " + e);
        }
        catch (ProviderException e) {
  
            System.out.println("Exception thrown : " + e);
        }
    }
}


Output:

Trying to get the instance of TAJMAHAL
Exception thrown : java.security.NoSuchAlgorithmException: TAJMAHAL SecureRandom not available

getInstance(String algorithm, Provider provider)

The getInstance() method of java.security.SecureRandom class is used to return a SecureRandom object that implements the specified Random Number Generator (RNG) algorithm.
A new SecureRandom object encapsulating the SecureRandomSpi implementation from the specified Provider object is returned. Note that the specified Provider object does not have to be registered in the provider list.

The returned SecureRandom object has not been seeded. To seed the returned object, call the setSeed method. If setSeed is not called, the first call to nextBytes will force the SecureRandom object to seed itself. This self-seeding will not occur if setSeed was previously called.

Syntax:

public static SecureRandom 
getInstance( String algorithm, Provider provider )
throws NoSuchAlgorithmException

Parameters: This method takes following argument as a parameter

  • algorithm –the name of the RNG algorithm.
  • provider – the provider.

Return Value: This method returns the new SecureRandom object .

Exception: This method throws the following Exception

  • NoSuchAlgorithmException – if a SecureRandomSpi implementation for the specified algorithm is not available from the specified Provider object.
  • IllegalArgumentException – if the specified provider is null.
  • Note:

  1. The programs will not run on online IDE.
  2. Every time Secure Random class will generate random output.

Below are the examples to illustrate the getInstance() method:

Example 1:




// Java program to demonstrate
// getInstance() method
  
import java.security.*;
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
    {
        try {
            // creating SecureRandom object
            SecureRandom sr1 = new SecureRandom(new byte[] { 1, 2, 3, 4 });
  
            // creating Provider object
            Provider pd = sr1.getProvider();
  
            // creating the object of SecureRandom and getting instance
            // By using getInstance() method
  
            SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", pd);
  
            // Declaring the string variable
            String str = "Tajmahal";
  
            // Declaring the byte Array
            // converting string into byte
            byte[] b = str.getBytes();
  
            // printing the byte array
            System.out.println("Byte array before operation : "
                               + Arrays.toString(b));
  
            // generating user-specified number of random bytes
            // using nextBytes() method
            sr.nextBytes(b);
  
            // printing the new byte array
            System.out.println("Byte array after operation : "
                               + Arrays.toString(b));
        }
  
        catch (NoSuchAlgorithmException e) {
  
            System.out.println("Exception thrown : " + e);
        }
        catch (ProviderException e) {
  
            System.out.println("Exception thrown : " + e);
        }
    }
}


Output:

Byte array before operation : [84, 97, 106, 109, 97, 104, 97, 108]
Byte array after operation : [109, 55, 116, -15, -83, 126, -128, 88]

Note: The following program produce the following Exception in online IDE
Exception thrown : java.security.ProviderException: init failed

Example 2:




// Java program to demonstrate
// getInstance() method
  
import java.security.*;
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
    {
        try {
            // creating SecureRandom object
            SecureRandom sr1 = new SecureRandom(new byte[] { 1, 2, 3, 4 });
  
            // creating Provider object
            Provider pd = sr1.getProvider();
  
            // creating the object of SecureRandom and getting instance
            // By using getInstance() method
            System.out.println("Trying to getting the instance of TAJMAHAL ");
            SecureRandom sr = SecureRandom.getInstance("TAJMAHAL", pd);
  
            // Declaring the string variable
            String str = "Tajmahal";
  
            // Declaring the byte Array
            // converting string into byte
            byte[] b = str.getBytes();
  
            // printing the byte array
            System.out.println("Byte array before operation : "
                               + Arrays.toString(b));
  
            // generating user-specified number of random bytes
            // using nextBytes() method
            sr.nextBytes(b);
  
            // printing the new byte array
            System.out.println("Byte array after operation : "
                               + Arrays.toString(b));
        }
  
        catch (NoSuchAlgorithmException e) {
  
            System.out.println("Exception thrown : " + e);
        }
        catch (ProviderException e) {
  
            System.out.println("Exception thrown : " + e);
        }
    }
}


Output:

Trying to getting the instance of TAJMAHAL
Exception thrown : java.security.NoSuchAlgorithmException: no such algorithm: TAJMAHAL for provider SUN

getInstance(String algorithm, String provider)

The getInstance() method of java.security.SecureRandom class is used to return a SecureRandom object that implements the specified Random Number Generator (RNG) algorithm.

A new SecureRandom object encapsulating the SecureRandomSpi implementation from the specified provider is returned. The specified provider must be registered in the security provider list.

Syntax:

public static SecureRandom 
getInstance( String algorithm, String provider )
throws NoSuchAlgorithmException, NoSuchProviderException

Parameters: This method takes following argument as a parameter

  • algorithm – the name of the RNG algorithm. See the SecureRandom section in the Java Cryptography Architecture Standard Algorithm Name Documentation for information about standard RNG algorithm names.
  • provider – the name of the provider.

Return Value: This method returns the new SecureRandom object .

Exception: This method throws the following Exception

  • NoSuchAlgorithmException – if a SecureRandomSpi implementation for the specified algorithm is not available from the specified provider.
  • NoSuchProviderException – if the specified provider is not registered in the security provider list.
  • IllegalArgumentException – if the provider name is null or empty.

Note:

  1. The programs will not run on online IDE.
  2. Every time Secure Random class will generate random output.

Below are the examples to illustrate the getInstance() method:

Example 1:




// Java program to demonstrate
// getInstance() method
  
import java.security.*;
import java.util.*;
  
public class GFG1 {
    public static void
        main(String[] argv)
            throws NoSuchAlgorithmException,
                   NoSuchProviderException
    {
        try {
            // creating SecureRandom object
            SecureRandom sr1 = new SecureRandom(new byte[] { 1, 2, 3, 4 });
  
            // creating Provider object
            Provider pd = sr1.getProvider();
  
            // getting provider name
            // by using method getname()
            String provider = pd.getName();
  
            // getting algorithm name
            // by using     getAlgorithm() mathod
            String algo = sr1.getAlgorithm();
  
            // creating the object of SecureRandom and getting instance
            // By using getInstance() method
            SecureRandom sr = SecureRandom.getInstance(algo, provider);
  
            // Declaring the string variable
            String str = "Tajmahal";
  
            // Declaring the byte Array
            // converting string into byte
            byte[] b = str.getBytes();
  
            // printing the byte array
            System.out.println("Byte array before operation : "
                               + Arrays.toString(b));
  
            // generating user-specified number of random bytes
            // using nextBytes() method
            sr.nextBytes(b);
  
            // printing the new byte array
            System.out.println("Byte array after operation : "
                               + Arrays.toString(b));
        }
  
        catch (NoSuchAlgorithmException e) {
  
            System.out.println("Exception thrown : " + e);
        }
        catch (ProviderException e) {
  
            System.out.println("Exception thrown : " + e);
        }
    }
}


Output:

Byte array before operation : [84, 97, 106, 109, 97, 104, 97, 108]
Byte array after operation : [-11, 81, 39, 67, -95, -51, 115, -18]

Example 2:




// Java program to demonstrate
// getInstance() method
  
import java.security.*;
import java.util.*;
  
public class GFG1 {
    public static void
        main(String[] argv)
            throws NoSuchAlgorithmException,
                   NoSuchProviderException
    {
        try {
            // creating SecureRandom object
            SecureRandom sr1 = new SecureRandom(new byte[] { 1, 2, 3, 4 });
  
            // creating Provider object
            Provider pd = sr1.getProvider();
  
            // getting provider name
            // by using method getname()
            String provider = pd.getName();
  
            // creating the object of SecureRandom and getting instance
            // By using getInstance() method
            System.out.println("Trying to take TAJMAHAL as a algorithm");
            SecureRandom sr = SecureRandom.getInstance("TAJMAHAL", provider);
  
            // Declaring the string variable
            String str = "Tajmahal";
  
            // Declaring the byte Array
            // converting string into byte
            byte[] b = str.getBytes();
  
            // printing the byte array
            System.out.println("Byte array before operation : "
                               + Arrays.toString(b));
  
            // generating user-specified number of random bytes
            // using nextBytes() method
            sr.nextBytes(b);
  
            // printing the new byte array
            System.out.println("Byte array after operation : "
                               + Arrays.toString(b));
        }
  
        catch (NoSuchAlgorithmException e) {
  
            System.out.println("Exception thrown : " + e);
        }
        catch (ProviderException e) {
  
            System.out.println("Exception thrown : " + e);
        }
    }
}


Output:

Trying to take TAJMAHAL as a algorithm
Exception thrown : java.security.NoSuchAlgorithmException: no such algorithm: TAJMAHAL for provider SUN

Example 3:




// Java program to demonstrate
// getInstance() method
  
import java.security.*;
import java.util.*;
  
public class GFG1 {
    public static void
        main(String[] argv)
            throws NoSuchAlgorithmException,
                   NoSuchProviderException
    {
        try {
            // creating SecureRandom object
            SecureRandom sr1 = new SecureRandom(new byte[] { 1, 2, 3, 4 });
  
            // getting algorithm name
            // by using     getAlgorithm() mathod
            String algo = sr1.getAlgorithm();
  
            // creating the object of SecureRandom and getting instance
            // By using getInstance() method
            System.out.println("Trying to taking MOON as a provider");
            SecureRandom sr = SecureRandom.getInstance(algo, "MOON");
  
            // Declaring the string variable
            String str = "Tajmahal";
  
            // Declaring the byte Array
            // converting string into byte
            byte[] b = str.getBytes();
  
            // printing the byte array
            System.out.println("Byte array before operation : "
                               + Arrays.toString(b));
  
            // generating user-specified number of random bytes
            // using nextBytes() method
            sr.nextBytes(b);
  
            // printing the new byte array
            System.out.println("Byte array after operation : "
                               + Arrays.toString(b));
        }
  
        catch (NoSuchAlgorithmException e) {
  
            System.out.println("Exception thrown : " + e);
        }
        catch (NoSuchProviderException e) {
  
            System.out.println("Exception thrown : " + e);
        }
    }
}


Output:

Trying to taking MOON as a provider
Exception thrown : java.security.NoSuchProviderException: no such provider: MOON

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments