# Behavior of AES-CTR with 128-bit nonce and possible overflow

If I feed 128 bits of randomness into AES-CTR as its IV / nonce / initial counter, what will happen if I feed in a random 128-bit integer that overflows and wraps around?

I've written a test for this and found that at least some CTR implementations do the expected thing and wrap the entire uint128 around, but is it possible to guarantee this? Are there common implementations that will fail or do different and thus incompatible things here?

I guess what I'm asking is whether this is portable or not.

• We would like to see more about your test results. If I've understood correctly there will no problem till the counter repeats itself. A good library, though, will never let you do this. – kelalaka Mar 26 at 17:05
• AES-CTR would be secure no matter what block input sequence were used, as long as that sequence does not repeat blocks. So incrementing mod $2^{128}$ should be safe even if it wraps back to zero. However questions about programming or about the particulars of software libraries are considered off topic on this website. Questions about specific libraries should go to StackOverflow. More open ended questions about the software ecosystem maybe belongs on SuperUser. – Future Security Mar 29 at 0:02

NIST SP 800-38A ("Recommendation for Block Cipher Modes of Operation Methods and Techniques "), Appendix B states that "The standard incrementing function takes [x]m and returns [x+1 mod 2^m]" (my formatting, they used typesetting to show exponents). Section B.1 goes into more detail about recommendations for the CTR mode incrementing function.

Regarding standards and compliance (which usually force portability), I couldn't really say. And even if it was standardized to be done that way, that doesn't mean there aren't non-compliant implementations, and it doesn't mean all implementations are bug-free.

So, I guess my best answer to you is that while most implementations probably do that (wrap around like an unsigned number), and you can test it with different platforms, I don't think you can count on it, and I don't think you can scream if a vendor /changes/ this later to behave differently. I'm not sure there is anything worded strongly enough that you can point to that would back up a complaint.

Edited to add: The NIST document is interesting reading. For recommendations on the incrementing function, (here I'm paraphrasing / summarizing), it basically says the incrementing function needn't necessarily increment w/ wrap, it simply must provide all 2^n unique values for an n-bit counter. So for example, an LFSR or LCG could also be used.