DEV Community


Discussion on: Cryptography for programmers 2: Blocks and Randomness

yoursunny profile image
Junxiao Shi • Edited

In CBC mode, IV must be random but does not have to be unique. In case PRNG generates the same IV twice, it's fine.

In CTR or GCM mode, IV must be unique but does not have to be random. I designed a protocol that uses random IV with GCM mode, and the NIST cryptographer rejected that design upon review because there's a small risk of IV collision.
The application/protocol must guarantee that IVs for the same key never repeat.
One method is to split the IV into three portions:

  • A fixed portion that identifies the sender. In my case, the same key is used by a client and a server, so I use 0 for messages from the client, and 1 for messages from the server. If the same key could be used across application restarts, the start timestamp goes into this portion as well.
  • A random portion.
  • A counter portion. This should be incremented by the number of blocks (not messages) encrypted by a particular key.
shierve profile image
Sergi Canal Author

Hi Junxiao, thanks for the reply. I wanted to give general rules for all iv generation to not go into too much detail, and I felt generating random ivs is ok in most cases.

About CBC, I don't agree that ivs don't have to be unique. It is not as important that they are unique than with stream modes, but reusing ivs in CBC can leak information about the first block / repeated prepends in messages. For CBC the very small probability of a PRNG collision is acceptable, but that does not mean that it would be ok to use a static iv, or to reuse the same iv intentionally.

I can see why that probability is not so acceptable in stream modes. Still we should be aware that there is a very very small chance of that happening. I find your solution to guaranteeing uniqueness very interesting, thanks. I will take this into account when I explain GCM.