English 中文(简体)
KeyPairGenerator
  • 时间:2024-12-22

Java Cryptography - KeyPairGenerator


Previous Page Next Page  

Java provides the KeyPairGenerator class. This class is used to generate pairs of pubpc and private keys. To generate keys using the KeyPairGenerator class, follow the steps given below.

Step 1: Create a KeyPairGenerator object

The KeyPairGenerator class provides getInstance() method which accepts a String variable representing the required key-generating algorithm and returns a KeyPairGenerator object that generates keys.

Create KeyPairGenerator object using the getInstance() method as shown below.

//Creating KeyPair generator object
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");

Step 2: Initiapze the KeyPairGenerator object

The KeyPairGenerator class provides a method named initiapze() this method is used to initiapze the key pair generator. This method accepts an integer value representing the key size.

Initiapze the KeyPairGenerator object created in the previous step using this method as shown below.

//Initiapzing the KeyPairGenerator
keyPairGen.initiapze(2048);

Step 3: Generate the KeyPairGenerator

You can generate the KeyPair using the generateKeyPair() method of the KeyPairGenerator class. Generate the key pair using this method as shown below.

//Generate the pair of keys
KeyPair pair = keyPairGen.generateKeyPair();

Step 4: Get the private key/pubpc key

You can get the private key from the generated KeyPair object using the getPrivate() method as shown below.

//Getting the private key from the key pair
PrivateKey privKey = pair.getPrivate();

You can get the pubpc key from the generated KeyPair object using the getPubpc() method as shown below.

//Getting the pubpc key from the key pair
PubpcKey pubpcKey = pair.getPubpc();

Example

Following example demonstrates the key generation of the secret key using the KeyPairGenerator class of the javax.crypto package.

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PubpcKey;

pubpc class KeyPairGenertor {
   pubpc static void main(String args[]) throws Exception{
      //Creating KeyPair generator object
      KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");
      
      //Initiapzing the KeyPairGenerator
      keyPairGen.initiapze(2048);
      
      //Generating the pair of keys
      KeyPair pair = keyPairGen.generateKeyPair();
      
      //Getting the private key from the key pair
      PrivateKey privKey = pair.getPrivate();   
      
      //Getting the pubpc key from the key pair
      PubpcKey pubpcKey = pair.getPubpc(); 
      System.out.println("Keys generated");
   }
}

Output

The above program generates the following output −

Keys generated
Advertisements