How to use AES-CTR with same IV in Python?

Question:

With the pycryptodome library, when encrypting with AES-CTR, the iv keyword argument is unavailable for MODE_CTR. I tried setting nonce to 0, but the second ciphertext is still different from the first ciphertext.

from Crypto.Cipher import AES

key = '1111111111111111'
message = 'Hello, world!'

cipher = AES.new(key, AES.MODE_CTR, nonce=b'0')
ciphertext1 = cipher.encrypt(message)
ciphertext2 = cipher.encrypt(message)

Asked By: user8624

||

Answers:

You have to start afresh with a new instance, so:

cipher1 = AES.new(key, AES.MODE_CTR, nonce='0')
ct_1 = cipher1.encrypt(message)
cipher2 = AES.new(key, AES.MODE_CTR, nonce='0')
ct_2 = cipher2.encrypt(message)

Otherwise the offset will have progressed, and that means that you are encrypting with a different part of the generated key stream. After more than 16 bytes the counter will have progressed as well, and you are using key stream bits consisting of the next encrypted counter.

Remember that cipher instances are stateful. Fortunately they are also pretty lightweight, so re-instantiating a new one is next to harmless.

Answered By: Maarten Bodewes
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.