The next mode of operation I want to talk about is called CTR mode,
which stands for "Counter." We have a message divided into blocks,
just as before. We'll have our encryption function, just as before,
and we can think of it as AES or any other block cipher.
And that takes a key as input--we'll use the same key--but instead of just
having a message block go in, what we're going to do instead is have a counter:
some value that cycles through the natural numbers.
That's going to be our input message, so we'll get, out of that, some cipher text.
And what we're going to do now--well, so far none of this has anything to do
with the message. Right--we've just encrypted the counting values
from Zero to n - 1.
What we're going to do is EXOR those--EXOR the outputs, here--
with the message, so the message box goes into these EXORs
and what comes out is the cipher text box.
If we did it just like this, we wouldn't have quite as much security as we would like.
We'd be vulnerable to attacks that search the space of counters.
We'd also be vulnerable because we're using the same sequence of counters
for every file that we encrypt with the same key.
So the solution to this is similar to what we did with the initialization vectors
in the previous mode. What we're going to do is add a nonce.
We'll append the nonce with the countervalue.
And a nonce is very similar to a key. A nonce is a one-time, unpredictable value.
Unlike a key, it doesn't need to be kept secret.
The point of the nonce is to make sure every time we use
counter mode with the same key we get different blocks out.
So as an example with AES, if we have 128 bits as the block size,
we might have a 64-bit nonce and a 64-bit counter.
So let me summarize these two modes. So we saw Cipher Block Chaining mode,
and we saw Counter mode, and CBC mode--the "i"th block of the ciphertext,
is a result of encrypting using the key.
The "i"th block of the message with the previous ciphertext block--
and we need a slightly special case for zero,
which would use, instead of the -1 ciphertext block,
which doesn't exist, would use an initialization vector.
With Counter mode, the "i"th ciphertext block is the result of encrypting
the value of "i"--that's our counter--
with some nonce, and I'm writing this as concatenation--
so we have 64 bits here pasted next to those 64 bits
for the counter and the nonce,
and that is EXOR'd with the corresponding message block.
To do decryption with Counter mode, well the "i"th message block
is the "i"th ciphertext block, EXOR'd with this same value,
which, as we know the key,
we can decrypt. So that's how decryption is done.
With CBC mode, the "i"th message block is a result of decrypting the "i"th
ciphertext block and EXORing that with the previous ciphertext block.
Or in the case of the very first block, EXORing that with the IV.
