xorxorxor
1 minute to read
We are given a short Python code to encrypt the flag, and we are given the ciphertext in hexadecimal:
#!/usr/bin/python3
import os
flag = open('flag.txt', 'r').read().strip().encode()
class XOR:
def __init__(self):
self.key = os.urandom(4)
def encrypt(self, data: bytes) -> bytes:
xored = b''
for i in range(len(data)):
xored += bytes([data[i] ^ self.key[i % len(self.key)]])
return xored
def decrypt(self, data: bytes) -> bytes:
return self.encrypt(data)
def main():
global flag
crypto = XOR()
print ('Flag:', crypto.encrypt(flag).hex())
if __name__ == '__main__':
main()
Flag: 134af6e1297bc4a96f6a87fe046684e8047084ee046d84c5282dd7ef292dc9
It is using a XOR cipher with a 4-byte key. Here we can extract the key because we know part of the plain text (flags have format HTB{...}). So, given that
But therefore
And also
We will use this last equation to obtain the key:
$ python3 -q
>>> from pwn import xor
>>> c = bytes.fromhex('134af6e1297bc4a96f6a87fe046684e8047084ee046d84c5282dd7ef292dc9')
>>> k = xor(c, b'HTB{')[:4]
>>> k
b'[\x1e\xb4\x9a'
Notice that we took only 4 bytes, because the key has that length. Now we are able to decrypt the ciphertext and get the flag:
>>> xor(c, k)
b'HTB{rep34t3d_x0r_n0t_s0_s3cur3}'