> For the complete documentation index, see [llms.txt](https://sarpers-organization.gitbook.io/ctftricks/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://sarpers-organization.gitbook.io/ctftricks/_chapter-intro-3/obfuscation/xor-decryption/trick-0454.md).

# Single-Byte XOR Decryption

***

Given hex-encoded ciphertext, such as `4e4f594e5c617763457c2e6c2a282b2d29456d2a287e452b2f45772a2b2f2d67`, decode the hex string into a byte array. Single-byte XOR encryption involves XORing each byte of the plaintext with the same single-byte key.

To begin, the hex-encoded ciphertext must be converted into a byte array. In Python, this can be done using the `bytes.fromhex()` method.

```python
ciphertext_hex = "4e4f594e5c617763457c2e6c2a282b2d29456d2a287e452b2f45772a2b2f2d67"
ciphertext_bytes = bytes.fromhex(ciphertext_hex)
```

The core logic of XOR decryption is to apply the XOR operation with the key. We can define a function that takes the byte array and the key as input and returns the XORed byte array:

```python
def xor_with_single_byte(input_bytes, key):
    output_bytes = bytes([byte ^ key for byte in input_bytes])
    return output_bytes
```

To decrypt, brute-force all 256 possible single-byte keys (0x00 to 0xFF). For each potential key, XOR every byte in the ciphertext array with that key. The result that produces human-readable plaintext is the correct decryption, and the corresponding byte is the key. This process is trivial to automate with a simple script or online tools. To break the single byte XOR cipher, we can iterate through all possible 256 single byte keys (0-255), apply the XOR function, and evaluate the result:

```python
# Assume ciphertext_bytes is already obtained from bytes.fromhex()
# Assume xor_with_single_byte function is defined

for key_candidate in range(256):
    decrypted_message = xor_with_single_byte(ciphertext_bytes, key_candidate)
    # Logic to evaluate decrypted_message for readability/plaintext characteristics
    # For example, check for common English characters or letter frequencies
    # If likely plaintext, print the key and the message
```
