Definition
Counter Mode
Counter mode is a mode of operation for a block cipher in which the cipher is applied to a sequence of nonce-counter values to generate a keystream.
Mechanism
Counter mode does not encrypt the plaintext blocks directly. Instead, it encrypts a sequence of inputs derived from a nonce and a counter. The resulting block sequence is used as a keystream, which is XORed with the plaintext.
This makes CTR behave like a stream cipher built from a block cipher.
Encryption
For plaintext block :

Decryption
Decryption uses the same keystream:

The plaintext blocks do not influence the keystream. For fixed key , nonce , and counter values , the keystream is fixed in advance.
Properties
Parallelisation
Encryption and decryption can be fully parallelised, and random read access is possible.
Error Propagation
A bit flip in a ciphertext block causes a bit flip at the corresponding position in the plaintext. A bit flip in the nonce produces unpredictable errors in all decrypted blocks.
Same keystream for encryption and decryption
Let
Then encryption computes
and decryption computes
The same keystream block is used in both directions.
Malleability
Because ciphertext is obtained by XORing plaintext with a keystream, modifying the ciphertext modifies the plaintext in a predictable way.
Suppose a ciphertext block satisfies
for some keystream block . If an attacker replaces by
then the decrypted plaintext becomes
So an attacker can force a chosen plaintext change by choosing the same XOR difference in the ciphertext.
This is why CTR provides confidentiality, but not integrity protection.
Changing one field value
logstoflagIn ASCII:
Therefore, the required XOR difference is:
If these four bytes are XORed into the ciphertext at the position corresponding to
logs, the decrypted plaintext becomesflag.
Why equal length matters
The same method works cleanly only when the old and new plaintext fragments have the same length.
For example,
logscan be changed toflag, since both strings have length .In contrast,
logscannot be changed tosecretby modifying only the corresponding ciphertext bytes, since the two strings have different lengths. CTR malleability lets the attacker change bytes in place, but it does not let the attacker insert or remove bytes.
Nonce
CTR mode requires that the nonce be unique for each encryption under the same key. If the same nonce is reused, then the same keystream is reused, which breaks security.
Nonce reuse
Suppose two plaintexts and are encrypted under the same key and the same nonce. Then the same keystream is used for both, so
Therefore,
The keystream cancels out, so the relation between the two plaintexts is exposed.