1. Overview
The Advanced Encryption Standard (AES) is a widely used symmetric block cipher algorithm. Initialization Vector (IV) plays an important role in the AES algorithm.
In this tutorial, we’ll explain how to generate IV in Java. Also, we’ll describe how to avoid InvalidAlgorithmParameterException when we generate the IV and use it in a cipher algorithm.
2. Initialization Vector
The AES algorithm has usually three inputs: plaintext, secret key, and IV. It supports secret keys of 128, 192, and 256 bits to encrypt and decrypt data in blocks of 128 bits. The below figure shows the AES inputs:
The goal of IV is to augment the encryption process. The IV is used in conjunction with the secret key in some AES modes of operation. For example, the Cipher Block Chaining (CBC) mode uses the IV in its algorithm.
In general, the IV is a pseudo-random value chosen by the sender. The IV for the encryption must be the same when decrypting information.
It has the same size as the block that is encrypted. Therefore, the size of the IV is 16 bytes or 128 bits.
3. Generating the IV
It’s recommended to use java.security.SecureRandom class instead of java.util.Random to generate a random IV. In addition, it’s a best practice that the IV be unpredictable. Also, we should not hard-code the IV in the source code.
To use the IV in a cipher, we use the IvParameterSpec class. Let’s create a method for generating the IV:
public static IvParameterSpec generateIv() {
byte[] iv = new byte[16];
new SecureRandom().nextBytes(iv);
return new IvParameterSpec(iv);
}
4. Exception
The AES algorithm requires that the IV size must be 16 bytes (128 bits). So, if we provide an IV whose size is not equal to 16 bytes, an InvalidAlgorithmParameterException will be thrown.
To solve this issue, we’ll have to use the IV with a size of 16 bytes. Sample snippet code regarding the use of IV in AES CBC mode can be found in this article.
5. Conclusion
In summary, we’ve learned how to generate an Initialization Vector (IV) in Java. Also, we’ve described the exception relevant to the IV generation. The source code used in this tutorial is available over on GitHub.