Generating a symmetric encryption key
A symmetric key describes a key that is used for both encryption and decryption. To create cryptographically secure encryption keys in general, we use securely generated pseudorandom numbers. This recipe demonstrates how to correctly initialize the SecureRandom
class and how to use it to initialize an Advanced Encryption Standard (AES) encryption key. AES is the preferred encryption standard to DES, and typically used with key sizes 128 bit and 256 bit.
Note
There are no code differences whether you are using Bouncy Castle or Spongy Castle, as noted in the previous recipe.
How to do it...
Let's create a secure encryption key.
Write the following function to generate a symmetric AES encryption key:
public static SecretKey generateAESKey(int keysize) throws NoSuchAlgorithmException { final SecureRandom random = new SecureRandom(); final KeyGenerator generator = KeyGenerator.getInstance("AES"); generator.init(keysize, random); return generator...