KeyPairGenerator getInstance() method in Java


A KeyPairGenerator object with the key pairs for a particular algorithm can be obtained using the getInstance() method in the class java.security.KeyPairGenerator. This method requires a single parameter i.e. the algorithm name and it returns the KeyPairGenerator object created.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.security.*;
import java.util.*;
public class Demo {
   public static void main(String[] argv) {
      try {
         KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance("RSA");
         String algorithm = kpGenerator.getAlgorithm();
         System.out.println("The Algorithm is: " + algorithm);
      } catch (NoSuchAlgorithmException e) {
         System.out.println("Error!!! NoSuchAlgorithmException");
      } catch (ProviderException e) {
         System.out.println("Error!!! ProviderException");
      }
   }
}

Output

The Algorithm is: RSA

Now let us understand the above program.

A KeyPairGenerator object kpGenerator can be obtained using the getInstance() method. Then the algorithm is obtained using the getAlgorithm() method and it is displayed. A code snippet that demonstrates is given as follows −

try {
   KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance("RSsA");
   String algorithm = kpGenerator.getAlgorithm();
   System.out.println("The Algorithm is: " + algorithm);
}

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

128 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements