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.
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");
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();
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);
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); } }
The above program generates the following output −
com.sun.crypto.provider.DESKey@18629 [B@2ac1fdc4