I'm sure there's not one answer to this question, but just trying to find out a general approach.
Using Java 1.4.2, I need to generate a key and IV for use in a symmetric algorithm. These values will be pre-shared with the recipient through a secure channel.
The key I can generate with KeyGenerator.keyGenerate(). But unless I'm missing it, there's no function for generating a random IV.
Should I do something completely arbitrary like pull 16 random bytes from memory? Or is there a preferred way of generating sufficiently random initialization vectors?
To generate the IV, we use the SecureRandom class. The block size required depends on the AES encryption block size. For the default block size of 128 bits, we need an initialization vector of 16 bytes. From the initialization vector, we create an IvParameterSpec which is required when creating the Cipher.
The ideal IV is a random or pseudorandom number. It must also be nonrepeating. Both randomness and nonrepetitiveness are crucial to prevent attackers from finding patterns in similar parts of the encrypted message and then using this information to decrypt the message.
In cryptography, an initialization vector (IV) or starting variable (SV) is an input to a cryptographic primitive being used to provide the initial state. The IV is typically required to be random or pseudorandom, but sometimes an IV only needs to be unpredictable or unique.
It depends on the mode in which you are using your cipher. If you are using CBC, bytes from a SecureRandom
are the easiest, and probably the most secure…as long as your RNG is good.
Most Java providers will generate the required parameters automatically, but in order for you to figure out what was chosen, you need to understand the cipher and mode. For example, if you are using a mode that requires an IV, you'd do something like this:
cipher.init(Cipher.ENCRYPT_MODE, secret);
IvParameterSpec spec =
cipher.getParameters().getParameterSpec(IvParameterSpec.class);
byte[] iv = spec.getIV();
This allows the provider to choose a suitable method for generating the IV itself. But if you were to use the same method on cipher using ECB mode, it would fail.
Using a counter mode obviously requires great care to avoid re-use of the counter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With