Метод KeyPairGenerator getInstance () в Java с примерами

Опубликовано: 11 Февраля, 2022

getInstance (строковый алгоритм)

Метод getInstance () класса java.security.KeyPairGenerator используется для возврата объекта KeyPairGenerator, который генерирует пары открытого / закрытого ключей для указанного алгоритма.

Этот метод просматривает список зарегистрированных поставщиков безопасности, начиная с наиболее предпочтительного поставщика. Возвращается новый объект KeyPairGenerator, инкапсулирующий реализацию KeyPairGeneratorSpi от первого поставщика, который поддерживает указанный алгоритм.

Синтаксис:

 общедоступный статический KeyPairGenerator 
    getInstance (строковый алгоритм)
        выбрасывает исключение NoSuchAlgorithmException

Параметры: этот метод принимает в качестве параметра стандартное имя алгоритма.

Возвращаемое значение: этот метод возвращает новый объект KeyPairGenerator.

Исключение: этот метод вызывает исключение NoSuchAlgorithmException, если ни один поставщик не поддерживает реализацию подписи для указанного алгоритма.

Ниже приведены примеры, иллюстрирующие метод getInstance () :

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 the object of
            // KeyPairGenerator
            // and getting instance
            // using getInstance() method
            KeyPairGenerator sr = KeyPairGenerator.getInstance("DSA");
  
            // getting the Algorithm
            String algo = sr.getAlgorithm();
  
            // printing the algo String
            System.out.println("Algorithm : " + algo);
        }
  
        catch (NoSuchAlgorithmException e) {
  
            System.out.println("Exception thrown : " + e);
        }
        catch (ProviderException e) {
  
            System.out.println("Exception thrown : " + e);
        }
    }
}
Output:
Algorithm : DSA

Example 2: To show NoSuchAlgorithmException

// 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
            // KeyPairGenerator
            // and getting instance
            // using getInstance() method
  
            System.out.println("Trying to get"
                               + " the instance of unknown Algorithm");
  
            KeyPairGenerator sr = KeyPairGenerator
                                      .getInstance("TAJMAHAL");
  
            // getting the Algorithm
            String algo = sr.getAlgorithm();
  
            // printing the algo String
            System.out.println("Algorithm : " + algo);
        }
  
        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 unknown Algorithm
Exception thrown : java.security.NoSuchAlgorithmException: TAJMAHAL KeyPairGenerator not available

getInstance(String algorithm, Provider provider)

Метод getInstance () класса java.security.KeyPairGenerator используется для возврата объекта KeyPairGenerator, который генерирует пары открытого / закрытого ключей для указанного алгоритма.
Возвращается новый объект KeyPairGenerator, инкапсулирующий реализацию KeyPairGeneratorSpi из указанного объекта Provider. Обратите внимание, что указанный объект Provider не обязательно должен быть зарегистрирован в списке поставщиков.

Синтаксис:

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

Параметры: этот метод принимает в качестве параметров следующие аргументы:

  • алгоритм : имя запрошенного алгоритма.
  • провайдер: провайдер

Возвращаемое значение: этот метод возвращает новый объект KeyPairGenerator.

Exception: This method throws following exceptions:

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

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

    Note: The following program will not run on online IDE.

    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 the object of
                // KeyPairGenerator
                // and getting instance
                // using getInstance() method
                KeyPairGenerator sr = KeyPairGenerator.getInstance("DSA");
      
                // creating Provider object
                Provider pd = sr.getProvider();
      
                // getting algorithm name
                // by using getAlgorithm() mathod
                String algo = sr.getAlgorithm();
      
                // creating the object of KeyPairGenerator and getting instance
                // By usng getInstance() method
                KeyPairGenerator sr1 = KeyPairGenerator.getInstance(algo, pd);
      
                // getting the status of signature object
                KeyPair keypair = sr1.generateKeyPair();
      
                // printing the keypair
                System.out.println("Keypair : " + keypair);
            }
      
            catch (NoSuchAlgorithmException e) {
      
                System.out.println("Exception thrown : " + e);
            }
            catch (ProviderException e) {
      
                System.out.println("Exception thrown : " + e);
            }
        }
    }
    Output:
    Keypair : java.security.KeyPair@12a3a380
    

    Example 2: To show NoSuchAlgorithmException

    // 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
                // KeyPairGenerator
                // and getting instance
                // using getInstance() method
                KeyPairGenerator sr = KeyPairGenerator.getInstance("DSA");
      
                // creating Provider object
                Provider pd = sr.getProvider();
      
                // creating the object of KeyPairGenerator and getting instance
                // By usng getInstance() method
                KeyPairGenerator sr1 = KeyPairGenerator.getInstance("TAJMAHAL", pd);
      
                // getting the status of signature object
                KeyPair keypair = sr1.generateKeyPair();
      
                // printing the keypair
                System.out.println("Keypair : " + keypair);
            }
      
            catch (NoSuchAlgorithmException e) {
      
                System.out.println("Exception thrown : " + e);
            }
            catch (ProviderException e) {
      
                System.out.println("Exception thrown : " + e);
            }
        }
    }
    Output:
    Exception thrown : java.security.NoSuchAlgorithmException: 
    no such algorithm: TAJMAHAL for provider SUN
    

    Example 3: To show IllegalArgumentException

    // 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
                // KeyPairGenerator
                // and getting instance
                // using getInstance() method
                KeyPairGenerator sr = KeyPairGenerator
                                          .getInstance("RSA");
      
                // creating Provider object
                System.out.println("Trying to assign null as a provider");
                Provider pd = null;
      
                // getting algorithm name
                // by using     getAlgorithm() mathod
                String algo = sr.getAlgorithm();
      
                // creating the object of KeyPairGenerator and getting instance
                // By usng getInstance() method
                KeyPairGenerator sr1 = KeyPairGenerator
                                           .getInstance(algo, pd);
      
                // getting the status of signature object
                KeyPair keypair = sr1.generateKeyPair();
      
                // printing the keypair
                System.out.println("Keypair : " + keypair);
            }
      
            catch (NoSuchAlgorithmException e) {
      
                System.out.println("Exception thrown : " + e);
            }
            catch (ProviderException e) {
      
                System.out.println("Exception thrown : " + e);
            }
            catch (IllegalArgumentException e) {
      
                System.out.println("Exception thrown : " + e);
            }
        }
    }
    Output:
    Trying to assign null as a provider
    Exception thrown : java.lang.IllegalArgumentException:
     missing provider
    

    Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.