> For the complete documentation index, see [llms.txt](https://www.ctfrecipes.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.ctfrecipes.com/cryptography/symmetric-cryptography/aes/mode-of-operation/ecb/block-shuffling.md).

# Block shuffling

Because ECB mode encrypts identical plaintext blocks to identical ciphertext blocks, the attacker can replace a ciphertext block with a known ciphertext block of their choice and the resulting plaintext block will be substituted with their desired block as well.

To carry out this attack, the attacker needs to have the ability to observe or manipulate ciphertext blocks in the communication channel.

## Exploitation

Let's take the following code :

```python
data = {"username": input(), "admin": 0}
data = json.dumps(data)
ciphertext = cipher.encrypt(data)
```

The user can forge arbitrary block into the username parameter :

{% hint style="info" %}
There is 13 bytes before the user input ( `{"username":"` ) , so 3 bytes are needed to complete the first block, and the 16 following bytes will be the arbitrary forged block.

To proof that, the user can send 2 exact same blocks that will result into 2 exact same cipher blocks.
{% endhint %}

{% code overflow="wrap" %}

```bash
$ python3 -c 'print("A"*3 + "A"*16*2)' | python3 example.py
0f0db6ff7eb32259e2ab26faad5bea05eb159765773a70532da4789b0305a592eb159765773a70532da4789b0305a59248adcfe72ea9a410137725b6d19fccbe
###
>>> result[:32]
'0f0db6ff7eb32259e2ab26faad5bea05' #First block containing {"username":"AAA
>>> result[32:64]
'eb159765773a70532da4789b0305a592' #Second block containing 16*'A'
>>> result[64:96]
'eb159765773a70532da4789b0305a592' #Third block containing 16*'A'
>>> result[32:64] == result[64:96]
True                               #Second block and third block are the same
```

{% endcode %}
