Image of the glider from the Game of Life by John Conway
Skip to content

ECB vs CBC Encryption

This is something you can do on your computer fairly easily, provided you have OpenSSL installed, which I would be willing to bet you do. Take a bitmap image (any image will work fine, I'm just going to use bitmap headers in this example), such as the Ubuntu logo, and encrypt it with AES in ECB mode. Then encrypt the same image with AES in CBC mode. Apply the 54-byte bitmap header to the encrypted files, and open up in an image viewer. Here are the commands I ran:

$ openssl enc -aes-256-ecb -in ubuntu.bmp -out ubuntu-ecb.bmp
$ openssl enc -aes-256-cbc -in ubuntu.bmp -out ubuntu-cbc.bmp
$ dd if=ubuntu.bmp of=ubuntu-ecb.bmp bs=1 count=54 conv=notrunc
$ dd if=ubuntu.bmp of=ubuntu-cbc.bmp bs=1 count=54 conv=notrunc

Now, open all three files, ubuntu.bmp, ubuntu-ecb.bmp and ubuntu-cbc.bmpp, and see what you get. Here are my results with the password "chi0eeMieng7Ohe8ookeaxae6ieph1":

Plaintext ECB Encrypted CBC Encrypted

Feel free to play with different passwords, and notice the colors change. Or use a different block cipher such as "bf-ecb", "des-ecb", or "rc2-ecb" with OpenSSL, and notice details change.

What's going on here? Why can I clearly make out the image when encrypted with EBC? Well, EBC, or electronic codeblock, is a block cipher that operates on individual blocks at a time. ECB does not use an initialization vector to kickstart the encryption. So, each block is encrypted with the same algorithm. If any underlying block is the same as another, then the encrypted output is exactly the same. Thus, all "#000000" hexadecimal colors in our image, for example, will have the same encrypted output, per block (thus, why you see stripes).

Compare this to CBC, or cipher-block chaining. An initialization vector must be used before the encryption can begin. The password in our case is our initialization vector. It is hashed to provide a 256-bit output, then AES encrypts the hash, plus the first block to provide a 512-bit output, 256-bits for the next vector, and 256-bits encrypted output. That vector is then used to encrypt the next 256-bits. This chaining algorithm continues to the end of the file. This ensures that every "#000000" hexadecimal color will have a different output, thus causing the file to appear as random (I have an attacking algorithm to still leak information out of a CBC-encrypted file, but that will be for another post).

Hopefully, this simple illustration convinces you to use CBC, or at least to not use ECB, when encrypting data that might be public.

{ 17 } Comments