247CTF - Tips And Tricks

posted
read
116 words · 1 min
contents

Recover a XOR encryption key used to encrypt a JPG image.

Approach

XOR encryption is vulnerable when the plaintext is partially known:

  • JPG files have a known magic header: FF D8 FF E0 00 10 4A 46 49 46 00 01
  • XOR the encrypted header with known plaintext to recover the key
  • Apply the recovered key to decrypt the entire file

Solution

#!/usr/bin/env python3
from itertools import cycle
# JPG file magic header
known_header = bytes.fromhex("FF D8 FF E0 00 10 4A 46 49 46 00 01")
# 从命令行传入原始加密附件路径
import sys
if len(sys.argv) != 2:
raise SystemExit("Usage: python decrypt.py ENCRYPTED_FILE")
with open(sys.argv[1], "rb") as f:
cipher_data = f.read()
# Extract encrypted header
cipher_header = cipher_data[:12]
if len(cipher_header) != len(known_header):
raise ValueError("Encrypted file is shorter than the assumed header")
# Recover XOR key: ciphertext XOR plaintext = key
key = bytes([c ^ p for c, p in zip(cipher_header, known_header)])
print(f"[*] Calculated Key: {key.hex().upper()}")
# Decrypt entire file by applying repeating key
decrypted_data = bytes([c ^ k for c, k in zip(cipher_data, cycle(key))])
# Save decrypted image
with open("flag.jpg", "wb") as f:
f.write(decrypted_data)
print("[*] Decrypted! Check flag.jpg")

Key Insight

The script assumes this exact JFIF header and a 12-byte repeating XOR key. A known header recovers only the keystream at those positions; JPEG variants can have different markers, and a longer key cannot be recovered from these bytes alone. The real encrypted attachment and key period are unavailable, so only a synthetic 12-byte-key round trip was checked.

Flag

247CTF{[flag redacted]}