# Add Key

The AddKey operation is a step in the encryption and decryption processes that involves combining the state matrix with a round key using a XOR operation.

{% hint style="info" %}
The round key is generated from the original secret key using the [Key Schedule](/cryptography/symmetric-cryptography/aes/block-encryption-procedure/key-expansion-key-schedule.md), which generates a sequence of subkeys for each round of the cipher.
{% endhint %}

The AddKey operation is performed by taking each byte of the state matrix and XORing it with the corresponding byte of the round key.

The AddKey operation is denoted as follows:

```java
state matrix ⊕ round key = new state matrix
```

Let's take an example to see how the AddKey operation works. Suppose we have the following state matrix:

```
+-------------+
| 54 4f 4f 20 |
| 77 68 6f 20 |
| 4c 61 72 67 |
| 65 72 20 21 |
+-------------+ 
```

And this round key :

```
+-------------+
| 2b 28 ab 09 |
| 7e ae f7 cf |
| 15 d2 15 4f |
| 16 a6 88 3c |
+-------------+
```

To perform the AddKey operation, we XOR each byte of the state matrix with the corresponding byte of the round key. For example, the first byte of the state matrix is XORed as follows:

```
54 ⊕ 2b = 7f
```

After performing the XOR operation for each byte, the resulting state matrix becomes:

```
+-------------+
| 7f 67 eb 85 |
| 09 c4 3b ec |
| a3 1f 36 8c |
| 33 26 e4 5e |
+-------------+
```

## Python implementation

```python
def add_round_key(s, k):
    for i in range(4):
        for j in range(4):
            s[i][j] ^= k[i][j]
    return s
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.ctfrecipes.com/cryptography/symmetric-cryptography/aes/block-encryption-procedure/add-key.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
