Monday, March 18, 2013

AES CBC Mode Encryption

If you've used javax.crypto to do encryption, then you're familiar with the code below that obtains an instance of a Cipher (note that the code below is written in Scala).

val encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding", BouncyCastleProvider.PROVIDER_NAME)

The first parameter to getInstance is where you specify the type of encryption you want to use. In the example above, I'm using AES encryption in CBC mode This tutorial explains what CBC mode really means and what's happening under the hood.

AES encryption starts by dividing the plaintext message into 128-bit blocks. The result looks something like this:

Once the message has been divided into 128-bit blocks, the message is encrypted using CBC mode. CBC mode stands for "Cipher Block Chaining" mode. In pseudo-code, the steps of the CBC algorithm are as follows:

1. A random initialization vector (IV) is generated and then XORed with Message[0].
2. The result of the XOR operation is fed into the encryption function E(k, m) where k is the encryption key and m is result of the XOR operation.
3. The result of the encryption function becomes the first 128-bit block of the ciphertext (ciphertext[0]).
4. ciphertext[0] is then XORed with Message[1].
5. The result of the XOR operation is fed into the encryption function E(k, m) where k is the encryption key and m is the result of the XOR operation.
6. This continues until the entire message has been encrypted.

Here's what CBC mode AES encryption looks like with a picture:

You can see why it's called cipher block "chaining", as the result of each encryption function is chained to the XOR of the next plaintext message block. Note that if the message can't be divided evenly into 128-bit blocks, the last plaintext block is padded to make it 128-bits. If, however, the message divides evenly into 128-bits, the plaintext message is appended with a dummy block of 128-bits before encryption.

In a future blog post, I'll describe how AES encryption with CTR mode works, and how it differs from CBC mode.


  1. Hi, first of all thank you, and second: how did you learn so much?

    Im starting taking a crypto course and its really hard (I dont have the basic knowledge nor know how to code), but you still managed to explain all these really easy.

  2. Kawa, I'm glad you found this helpful. I'll try to get some new crypto posts out soon for you to follow.