> 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/xor/trick-0107.md).

# XOR Decryption (Partial Key Brute-Force)

***

Combine known parts of an XOR key with a brute-force approach for the unknown sections when hints about their format or range are available. Generate a list of possible full keys by iterating through potential values for the unknown segments (e.g., if `XX` are unknown digits, iterate `00` to `99`). Perform XOR decryption with each generated key and check the output for characteristics of valid plaintext, such as printable ASCII characters or a known flag format (`THM{...}`).

For instance, if the key is known except for the last two digits, with the known part being `'1109200013'` and the unknown part being `'XX'` where `XX` are two digits from 00 to 99, a brute-force approach can iterate through all 100 possibilities for the unknown digits.

The core XOR decryption function takes ciphertext and a key (both as bytes) and performs the XOR operation byte by byte, repeating the key if it is shorter than the ciphertext.

```python
def xor_decrypt(ciphertext, key):
  decrypted = bytearray(len(ciphertext))
  for i in range(len(ciphertext)):
    decrypted[i] = ciphertext[i] ^ key[i % len(key)]
  return decrypted
```

Alternatively, a more concise function using Python's `itertools` can be used for repeating the key:

```python
import itertools

def xor_bytes(data, key):
    return bytes([a ^ b for a, b in zip(data, itertools.cycle(key))])
```

Using the first decryption function, the brute-force process for the specific example (`1109200013XX`) can be implemented as follows:

```python
def xor_decrypt(ciphertext, key):
  decrypted = bytearray(len(ciphertext))
  for i in range(len(ciphertext)):
    decrypted[i] = ciphertext[i] ^ key[i % len(key)]
  return decrypted

# Example ciphertext (replace with your actual ciphertext)
ciphertext = bytearray(b'b\\\'ey}BQB_^[\\ZEnw\x01uWoY~aF\x0fiRdbum\x04BUn\x06[\x02CHonZ\x03~or\x03UT\x00_\x03]mD\x00W\x02gpScL\\\'')

# Generate key list based on known prefix and unknown parts (e.g., '1109200013' + 00-99)
keys = [f'1109200013{i:02}' for i in range(100)]

for key in keys:
  key_bytes = bytearray(key.encode())
  # Ensure key is long enough or handle short keys if needed, but standard XOR repeats key
  decrypted = xor_decrypt(ciphertext, key_bytes)
  try:
    decrypted_str = decrypted.decode('utf-8')
    # Check for flag format or other plaintext indicators
    if 'THM{' in decrypted_str and all(32 <= byte <= 126 or byte in [9,10,13] for byte in decrypted):
      print(f"Potential Key: '{key}', Decrypted Text: '{decrypted_str}'")
      # Optionally break if expecting only one solution
  except UnicodeDecodeError:
    pass # Ignore non-printable results
  except Exception as e:
    # Handle other potential errors during decryption/checking
    # print(f"Error with key {key}: {e}")
    pass
```
