English 中文(简体)
KeyGenerator
  • 时间:2024-09-17

Java Cryptography - KeyGenerator


Previous Page Next Page  

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: Initiapze the KeyGenerator

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

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

//Initiapzing 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;

pubpc class KeyGeneratorExample {
   pubpc static void main(String args[]) throws Exception{
      //Creating a KeyGenerator object
      KeyGenerator keyGen = KeyGenerator.getInstance("DES");
      
      //Creating a SecureRandom object
      SecureRandom secRandom = new SecureRandom();
      
      //Initiapzing 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
Advertisements