Java Cryptography - KeyGenerator


Advertisements

Java provides KeyGenerator class this class is used to generate secret keys and objects of this class are reusable.

To generate keys using the KeyGenerator class follow the steps given below.

Step 1: Create a KeyGenerator object

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

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

//Creating a KeyGenerator object
KeyGenerator keyGen = KeyGenerator.getInstance("DES");

Step 2: Create SecureRandom object

The SecureRandom class of the java.Security package provides a strong random number generator which is used to generate random numbers in Java. Instantiate this class as shown below.

//Creating a SecureRandom object
SecureRandom secRandom = new SecureRandom();

Step 3: Initialize the KeyGenerator

The KeyGenerator class provides a method named init() this method accepts the SecureRandom object and initializes the current KeyGenerator.

Initialize the KeyGenerator object created in the previous step using the init() method.

//Initializing the KeyGenerator
keyGen.init(secRandom);

Example

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

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

import java.security.Key;
import java.security.SecureRandom;

public class KeyGeneratorExample {
   public static void main(String args[]) throws Exception{
      //Creating a KeyGenerator object
      KeyGenerator keyGen = KeyGenerator.getInstance("DES");
      
      //Creating a SecureRandom object
      SecureRandom secRandom = new SecureRandom();
      
      //Initializing the KeyGenerator
      keyGen.init(secRandom);
      
      //Creating/Generating a key
      Key key = keyGen.generateKey();
      
      System.out.println(key);      
      Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");      
      cipher.init(cipher.ENCRYPT_MODE, key);      

      String msg = new String("Hi how are you");
      byte[] bytes = cipher.doFinal(msg.getBytes());      
      System.out.println(bytes);      
   }
}

Output

The above program generates the following output −

com.sun.crypto.provider.DESKey@18629
[B@2ac1fdc4

Useful Video Courses


Video

Java Date and Time Online Training

16 Lectures 2 hours

Malhar Lathkar

Video

Java Servlet Online Training

19 Lectures 5 hours

Malhar Lathkar

Video

JavaScript Online Training

25 Lectures 2.5 hours

Anadi Sharma

Video

Java Online Training

Most Popular

126 Lectures 7 hours

Tushar Kale

Video

Java Essential Training

119 Lectures 17.5 hours

Monica Mittal

Video

Java Essentials Online Training

76 Lectures 7 hours

Arnab Chakraborty

Advertisements