Java KeyPairGenerator getInstance()

In this guide, you will learn about the KeyPairGenerator getInstance() method in Java programming and how to use it with an example.

1. KeyPairGenerator getInstance() Method Overview


The getInstance() method of the KeyPairGenerator class in Java is used to get a KeyPairGenerator object that generates public/private key pairs for a specified algorithm. This method is a factory method that provides an instance of a key pair generator for the requested algorithm.


public static KeyPairGenerator getInstance(String algorithm) throws NoSuchAlgorithmException


- algorithm: a String representing the standard string name of the algorithm for which a key pair generator is required. Common algorithms include "RSA", "DSA", "EC", etc.

Key Points:

- The getInstance() method throws a NoSuchAlgorithmException if no provider supports a KeyPairGenerator implementation for the specified algorithm.

- Once an instance of KeyPairGenerator is obtained, it must be initialized using the initialize() method before generating any key pair.

- The generateKeyPair() method is then used to generate a new key pair.

2. KeyPairGenerator getInstance() Method Example


public class KeyPairGeneratorExample {

    public static void main(String[] args) {
        try {
            // Get instance of KeyPairGenerator for RSA algorithm
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");

            // Initialize the KeyPairGenerator

            // Generate the KeyPair
            KeyPair keyPair = keyPairGenerator.generateKeyPair();

            // Print the generated keys
            System.out.println("Public Key: " + keyPair.getPublic());
            System.out.println("Private Key: " + keyPair.getPrivate());

        } catch (NoSuchAlgorithmException e) {


Public Key: Sun RSA public key, 2048 bits
  modulus: 238460581...
  public exponent: 65537
Private Key:


In this example, we use KeyPairGenerator.getInstance() to obtain an instance of KeyPairGenerator for the RSA algorithm. We then initialize it with a key size of 2048 bits using the initialize() method. After the initialization, we call the generateKeyPair() method to generate a key pair consisting of a public key and a private key. These keys are then printed to the console.