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.

  • $\begingroup$ 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. $\endgroup$
    – kelalaka
    Mar 26, 2020 at 17:05
  • 1
    $\begingroup$ 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. $\endgroup$ Mar 29, 2020 at 0:02

1 Answer 1


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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.