14.4.5 CTR mode
The Counter (CTR) mode, illustrated in Figure 14.12, is a mode of operation that applies the underlying block cipher f to generate a key stream that is subsequently used for encryption and decryption. Effectively, this makes CTR a stream cipher:

Figure 14.12: Working principle of the CTR mode of operation
To encrypt a plaintext using CTR mode, the sender first chooses a random value for the counter ctr. The sender then performs the encryption by generating the key stream and XORing it with the plaintext blocks:

where yi is the result of encrypting the i-th ctr value with block cipher f under key k. The key material yi is then XORed with the corresponding plaintext block mi to obtain the ciphertext block ci.
Decryption using CTR is performed by computing:

From the preceding equations, you can see that CTR, like OFB, requires no inverse function f−1. Moreover, it can be shown that CTR is CPA-secure if f is a pseudorandom function [57].
In contrast to all secure modes of operation discussed so far, both encryption and decryption in CTR mode can be completely parallelized. This is because – as you can easily convince yourself by looking at Figure 14.12 – the CTR key stream blocks yi depend only on the counter ctr and the shared key k. As a result, yi can be computed in parallel.
Clearly, since yi do not depend on the plaintext to be encrypted or ciphertext to be decrypted, the key stream can be pre-generated and cached, similar to OFB. This makes subsequent CTR encryption or decryption very fast.
To encrypt the previously generated plaintext in p.txt using the AES in the CTR mode of operation, we execute the following command:
$ openssl enc -aes-128-cbc -in p.txt -out c.txt -K 000102030405060708090a0b0c0d0e0f -iv 00000000000000000000000000000001 -nopad
Note that the OpenSSL’s option name iv is somewhat misleading in the preceding command since CTR expects a counter value, not an initialization vector. This cryptographic detail was likely ignored to keep the OpenSSL interface as simple as possible.
The resulting ciphertext was written to the c.txt file and we can again view it using the xxd tool:
$ xxd c.txt
00000000: 68be 1fec 72f3 b5bc 2f34 1f9e 21dc 0ab4 h…r…/4..!…
00000010: ae5b e4e7 fd3c 33e4 1498 8cb0 e4db 6ff3 .[…<3…….o.
00000020: f4f8 03bb 1e3e 1595 9cf4 d6e6 175b a076 …..>…….[.v
Our final mode of operation in this section is particularly well suited for the encryption of entire hard disks.