The Java KeyGenerator class (
javax.crypto.KeyGenerator) is used to generate symmetric
encryption keys. A symmetric encryption key
is a key that is used for both encryption and decryption of data, by a symmetric encryption algorithm.
In this Java KeyGenerator tutorial I will show you how to generate symmetric encryption keys.
Creating a KeyGenerator Instance
Before you can use the Java
KeyGenerator class you must create a
instance. You create a
KeyGenerator instance by calling the static method
passing as parameter the name of the encryption algorithm to create a key for. Here is an example of creating
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
This example creates a
KeyGenerator instance which can generate keys for the AES encryption algorithm.
Initializing the KeyGenerator
After creating the
KeyGenerator instance you must initialize it. Initializing a
instance is done by calling its
init() method. Here is an example of initializing a
SecureRandom secureRandom = new SecureRandom(); int keyBitSize = 256; keyGenerator.init(keyBitSize, secureRandom);
init() method takes two parameters: The bit size of the keys to generate,
SecureRandom that is used during key generation.
Generating a Key
Once the Java
KeyGenerator instance is initialized you can use it to generate keys. Generating a
key is done by calling the
generateKey() method. Here is an example of
generating a symmetric key:
SecretKey secretKey = keyGenerator.generateKey();