Files
TryHackMe/CTF/W1seGuy/decrypt.py
2025-12-04 09:57:17 +01:00

39 lines
1.3 KiB
Python

import itertools
def xor_decrypt(hex_encoded, key):
data = bytes.fromhex(hex_encoded)
decrypted = ''
for i in range(len(data)):
decrypted += chr(data[i] ^ ord(key[i % len(key)]))
return decrypted
def recover_xor_key(hex_encoded, known_start="THM{", known_end="}"):
data = bytes.fromhex(hex_encoded)
# Step 1: Recover partial key from known prefix
partial_key = [chr(data[i] ^ ord(known_start[i])) for i in range(len(known_start))]
# Step 2: Brute-force remaining characters of 5-character key
charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
key_length = 5
unknown_length = key_length - len(partial_key)
for combo in itertools.product(charset, repeat=unknown_length):
key = ''.join(partial_key + list(combo))
decrypted = xor_decrypt(hex_encoded, key)
if decrypted.startswith(known_start) and decrypted.endswith(known_end):
return key, decrypted
return None, None
if __name__ == "__main__":
hex_encoded = "272f0549124206245c16361f3c731607532b590132093a01031f2b315a370113310217011f07401f"
key, message = recover_xor_key(hex_encoded)
if key:
print("✅ Found key:", key)
print("🔓 Decrypted message:", message)
else:
print("❌ Key not found.")