Decoding XOR, Base64 and Layered Encodings
A sample's strings output is suspiciously quiet: no URLs, no paths, no registry keys, but a 120-character run of letters, digits and +/= and a few hundred bytes of gibberish in .rdata. Authors hide their configuration so that a quick look and a simple signature find nothing. The hiding is usually not cryptography but encoding: XOR with a short key, Base64, hex, sometimes stacked two or three deep. Undoing it is routine analyst work, and every decoded string is a new indicator.
In this lesson every "hidden" string is harmless text the example encodes itself, with addresses under lab.test. The techniques are the same ones analysts apply in CyberChef or a Python notebook to real configurations.
Definitions
- Single-byte XOR: every byte is XOR-ed with the same key (one of 256 values). XOR is its own inverse, so applying again decodes. The entropy stays the same, because the byte histogram is only relabelled.
- Multi-byte (rolling) XOR: the key is a short byte string repeated over the data.
- Known-plaintext attack: if you can guess part of the plaintext (a config usually contains
http://, a domain,.exe, a run of zeros), then plaintext XOR ciphertext gives the key bytes at those positions. - Base64: 3 bytes become 4 characters from
A–Z a–z 0–9 + /, padded with=. Recognisable by its alphabet and a length that is a multiple of 4. Variants: Base64url (-and_), and custom alphabets (a shuffled table, which a frequency analysis or the code itself reveals). - Layered encoding: for example
base64(xor(data)); decode from the outside in. - CyberChef: GCHQ's browser-based "cyber Swiss army knife", where decoding steps are chained into a "recipe"; its Magic operation tries common decodings automatically.
Breaking single-byte XOR by scoring
The example hides a harmless lab configuration with a one-byte key, then tries all 256 keys and scores each candidate by how much it looks like text: the share of printable characters plus a bonus for common configuration tokens.
CONFIG = b"server=update.beacon.lab.test;port=8080;interval=60;id=lab-0001"
blob = bytes(b ^ 0x5C for b in CONFIG) # what the sample would store
print("stored:", blob[:24].hex(), "…")
def score(c: bytes) -> float:
printable = sum(32 <= b < 127 for b in c) / len(c)
bonus = sum(tok in c for tok in (b"http", b"=", b";", b".test", b"port", b"server"))
return printable + 0.2 * bonus
ranked = sorted(range(256), key=lambda k: -score(bytes(b ^ k for b in blob)))
for k in ranked[:3]:
cand = bytes(b ^ k for b in blob)
print(f"key 0x{k:02x} score {score(cand):.2f} {cand[:40]!r}")stored: 2f392e2a392e61292c383d2839723e393d3f333272303d3e …
key 0x5c score 2.00 b'server=update.beacon.lab.test;port=8080;'
key 0x02 score 1.40 b'-;,(;,c+.:?*;p<;?=10p2?<p*;-*e.1,*cfnfne'
key 0x03 score 1.40 b',:-):-b*/;>+:q=:><01q3>=q+:,+d/0-+bgogod'
The right key stands out clearly (score 2.00). The runners-up are instructive: keys 0x02 and 0x03 also give 100 % printable output, because this configuration happens to map onto printable bytes under several keys, so a printable-only score would tie at 1.0 for all of them. The token bonus separates real text from printable gibberish.
Multi-byte XOR, Base64 and layers
Real configurations often use a short repeating key and wrap the result in Base64 so it survives as text. The example builds exactly that from a harmless string, then recovers the key from a guess at the plaintext (configuration blocks commonly start with a field name such as server=) and peels the layers:
import base64, re
KEY = b"LAB7"
secret = b"server=update.beacon.lab.test;path=/api/v1/ping;ua=LabAgent/1.0;sleep=60"
stored = base64.b64encode(bytes(b ^ KEY[i % len(KEY)] for i, b in enumerate(secret)))
print("in the sample:", stored.decode()[:48] + "…")
print("looks like Base64:", bool(re.fullmatch(rb"[A-Za-z0-9+/]+={0,2}", stored)) and len(stored) % 4 == 0)
layer1 = base64.b64decode(stored)
guess = b"server="
key_stream = bytes(c ^ p for c, p in zip(layer1, guess))
print("key stream from the guess:", key_stream)
for klen in range(1, 6): # the shortest period that explains the key stream
if all(key_stream[i] == key_stream[i % klen] for i in range(len(key_stream))):
key = key_stream[:klen]
break
plain = bytes(b ^ key[i % len(key)] for i, b in enumerate(layer1))
print("key:", key, "->", plain.decode())
print("indicators:", re.findall(rb"[\w-]+(?:\.[\w-]+)*\.test|/api/[\w/]+", plain))in the sample: PyQwQSkzf0I8JSNDKW8gUi0iLVliLSNVYjUnRDh6MlY4KX8Y…
looks like Base64: True
key stream from the guess: b'LAB7LAB'
key: b'LAB7' -> server=update.beacon.lab.test;path=/api/v1/ping;ua=LabAgent/1.0;sleep=60
indicators: [b'update.beacon.lab.test', b'/api/v1/ping']
Seven guessed bytes reveal a 4-byte key repeated (LAB7LAB), and the period gives the full key. In real work the guess comes from what such configurations usually contain, or from the decoding routine found in the disassembly (RE: crypto constants and library code), which is the more reliable route: read the code that decodes, then reimplement it.
How encoded strings are detected
- YARA modifiers:
xormatches a string under every single-byte XOR key (or a range:xor(0x01-0xff)),base64andbase64widematch it inside Base64 text. A rule on the plaintext thus catches the encoded copies too (YARA basics). - Entropy and alphabet checks: long Base64-alphabet runs, or XOR-encoded text whose entropy stays text-like (around 4 to 5) but which contains no readable words.
- FLOSS and emulation: decode routines executed in an emulator yield the strings without manual work.
- Behaviour: whatever the encoding, the sample must decode before it connects, so the sandbox sees the plain domain in DNS queries (network behaviour).
How defenders make this harder for attackers
Encoding hides nothing from behaviour-based detection, which is why defenders invest there: DNS and proxy logs, EDR telemetry of decoded command lines (PowerShell script block logging records the decoded script, PowerShell security), and AMSI, which lets security products inspect scripts after deobfuscation.
Pitfalls
- Zero bytes leak the key. XOR of a zero byte with the key is the key itself: long runs of zeros in an XOR-encoded block print the key in clear. Look for a repeating pattern.
- Near-miss candidates. For text made only of letters, keys that differ only in bit 5 (
0x20) give the same text with the case swapped, and other keys can give fully printable gibberish; check the top candidates by eye. - Base64 that isn't. Hex strings and random alphanumeric identifiers can match the Base64 alphabet; decode and check that the result makes sense.
- Treating XOR as encryption in reports. Call it encoding or obfuscation; "encrypted with XOR" over-states it, and "custom crypto" may be real AES with a hard-coded key, which is a different finding.
Practice
1. A 64-byte block XOR-encoded with a 4-byte key contains a run of 16 zero bytes in the plaintext. What will you see in the encoded block?
The key repeated four times (16 bytes), because . It is often the fastest way to read the key.
2. Decode by hand: the Base64 string bGFiLnRlc3Q=.
lab.test. Run base64.b64decode("bGFiLnRlc3Q=") to check. The single = means the last group held 2 bytes.
3. Change KEY in the second example to b"K3". Does the key recovery still work?
Yes: the key stream from the 7-byte guess repeats with period 2, so the loop finds K3 and decodes correctly. A key of 6 bytes or more defeats this loop, which only tries periods up to 5, and once the key is as long as the guess (7 bytes or more) no repetition is visible at all: then you need a longer guess or the code.
Test yourself
Why does single-byte XOR not change the entropy of the data?
- It compresses the data
- It only relabels byte values, so the histogram has the same shape
- It adds random bytes
- Entropy ignores XOR
In a known-plaintext attack on repeating-key XOR, how is the key obtained?
- By hashing the ciphertext
- By XOR-ing the ciphertext with the guessed plaintext at the same positions
- By Base64-decoding twice
- By counting zeros
Which YARA string modifier matches a string hidden under any single-byte XOR key?
- nocase
- wide
- xor
- fullword
What is the first decoding step for stored = base64(xor(data, key))?
- XOR with the key
- Base64 decoding
- Decompression
- Hashing