Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I generate an initialization vector?

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?

like image 817
wadesworld Avatar asked Nov 23 '09 19:11

wadesworld


People also ask

How do you make an IV?

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.

Should IV be random?

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.

Does initialization vector need to be random?

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.


1 Answers

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.

like image 150
erickson Avatar answered Sep 22 '22 10:09

erickson