cybersecurity · intermediate · ~15 min · safe pentest lab

Recover a single-byte XOR key

Brute-force all 256 keys and pick the one whose decode looks like text — how analysts crack single-byte XOR.

Challenge

Given a single-byte-XOR blob, recover the key without knowing it:

int recover_xor_key(const unsigned char *buf, size_t n);

Try every key 0-255, score each decode by how many bytes are printable ASCII (0x20-0x7e, plus tab/newline), and return the key with the highest score. On a tie, return the lowest key.

Input format

buf of n bytes.

Output format

The best key (0-255).

Constraints

Ties resolve to the lowest key; empty input returns 0.

Starter code

#include <stddef.h>
/* Return the single-byte key (0-255) whose XOR-decode of buf has the most
   printable bytes. On ties, return the lowest such key. */
int recover_xor_key(const unsigned char *buf, size_t n) {
    (void)buf; (void)n;
    return 0;   /* TODO */
}

Common mistakes

Using >= in the tie comparison (returns the highest key instead of the lowest); treating bytes as signed.

Edge cases to handle

All-zero or tiny buffers may tie — return the lowest maximizing key.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.