Since I’ve become a security engineer, I’ve been working my way through the Cryptopals challenges. I’m going to cover challenges 7 and 8 in this article.

What is AES-128 ECB mode?

ECB stands for Electronic Code Book. In ECB mode, the plaintext is broken into blocks of a given size (128 bits in this case), and the encryption algorithm is run on each block of plaintext individually. The weakness of this encryption mode is that it’s possible to see patterns in the ciphertext. Two identical blocks of plaintext will result in two identical blocks of ciphertext. Like every cryptography blog does, I’ll use this image of the Linux penguin to illustrate the problem with ECB.

Encrypted Using ECB

After encrypting Tux using ECB, the color is distorted, but we can still see a very obvious penguin.

Implementing ECB mode in Go

import "crypto/aes"func DecryptEcb(encryptedBytes, key []byte) ([]byte, error) {

cipher, err := aes.NewCipher(key)
if err != nil {
return nil, err
plainText := make([]byte, len(encryptedBytes)) for i, j:= 0, 16; i< len(encryptedBytes); i, j = i+16, j+16 {
cipher.Decrypt(plainText[i:j], encryptedBytes[i:j])
return plainText, nil

(NOTE: We should probably do some checks to make sure we are not going out of bounds of our byte slice, but I’ll leave those details to you.)

The only thing left is to read in the file and decode the base64, which we’ve done in a few examples already, so I’ll leave those to you.

Detecting ECB

This is a test!!   
This is a test!!

Those blocks would encrypt to (hex encoded for visibility):


So, to see if our ciphertext was encrypted in ECB mode, we just need to check if any blocks are repeating. If they are, then we can be pretty sure that ECB mode was used.

  1. Read in file
  2. For each line
    A. Hex decode the line
    B. Break into 16 byte chunks
    C. If any chunks match, return the line number
    D. If no matches, continue to next line
    E. Return line number of result
import (
func DetectECB(fileName string) (int, error) {
var input [][]byte
f, err := ioutil.ReadFile(fileName)
if err != nil {
return -1, err
scanner := bufio.NewScanner(bytes.NewReader(f))
for scanner.Scan() {
hdl := make([]byte, hex.DecodedLen(len(scanner.Bytes())))
_, err := hex.Decode(hdl, scanner.Bytes())
if err != nil {
return -1, err
input = append(input, hdl)
res := Detect(input)
return res, nil
func Detect (input [][]byte) int {
for i, ln := range input {
chunks := make([][]byte, 0)
for j := 0; j < len(ln); j += 16 {
batch := ln[j:min(j+15, len(ln))]
for _, c := range chunks {
if bytes.Equal(c, batch) {
return i+1
chunks = append(chunks, batch)
return 0
func min(a, b int) int {
if a <= b {
return a
return b

We’re done!

Security engineer at Uber. Musician, gamer, and juggler.