# Level 8: Detect AES in ECB mode

## <mark style="color:purple;">Task</mark>

[In this file](https://cryptopals.com/static/challenge-data/8.txt) are a bunch of hex-encoded ciphertexts.

One of them has been encrypted with ECB.

Detect it.

Remember that the problem with ECB is that it is stateless and deterministic; the same 16 byte plaintext block will always produce the same 16 byte ciphertext.

***

### <mark style="color:purple;">Explanation</mark>

Now, we already know that AES-128-ECB operates with 16-byte blocks. So, for this exercise, we need to:

* Read the file.
* Convert each line from hexadecimal to bytes.
* Split each ciphertext into 16-byte blocks.
* Count the repeated blocks. The most repetitive block is the ECB cipher block.

***

### <mark style="color:purple;">Resolution</mark>

First, we are going to create a file named `task8.py`

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcC_pJfe-5iaUCHbWfO8MJpaFoqey3xqlN0qDxGJY0ZGPwZYyxuFXmVLKD0VRuKDIP103A5sxdz1zobLWcfFGfGS8QUQXNmYvt3h4Py_H4NB7AdYrjFh_Lk0B56JFfGWT_JphZoUA?key=0z75chVsoEW_cfTQtgh3riLM" alt=""><figcaption></figcaption></figure>

#### Understanding the code

* Two libraries are imported
  * *<mark style="color:blue;">Counter</mark>* to count occurrences.&#x20;
  * *<mark style="color:blue;">base64</mark>* for base64 encoding and decoding functions.
* The file **8.txt** is read using <mark style="color:blue;">`open()`</mark> and stored in the variable `ciphertexts`.
  * <mark style="color:blue;">`splitlines()`</mark>  is then used to separate the lines.
* The function <mark style="color:blue;">`detect_ecb(ciphertext_hex)`</mark> is defined.
  * `ciphertext_bytes` is assigned the value of `ciphertext_hex` converted into bytes.
  * `blocks` is initialized with 16-byte blocks.
  * `unique_blocks` uses the <mark style="color:blue;">`len(set())`</mark> functions where:
    * <mark style="color:blue;">`set()`</mark> converts the list into a set, removing duplicates.
    * <mark style="color:blue;">`len()`</mark> returns the number of unique blocks.
  * The function returns the ECB ciphertext with most repetitive blocks.
* `most_likely_ecb` stores the result of <mark style="color:blue;">`detect_ecb()`</mark> , which is then printed.

***

### <mark style="color:purple;">Result</mark>

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXe3yKaf8eB3NT0T_0J_z_UCIoAxuvTwWJPxMl6OdQeAdshzBHmtuVHaSKtwLOQrxHLGyo5rdXHcK8_uRUCS52vWIQ3ClPXbJvQmBUIFcoZD_G761h7USn30eBuHLCp8EdP0P3lE?key=0z75chVsoEW_cfTQtgh3riLM" alt=""><figcaption></figcaption></figure>
