Matured Fella
Matured Fella

Reputation: 73

Read each four bytes (DWORD) and XOR with 0xBABEBABE with Python

I have a malware sample to analyze for a school project. The payload is encoded by XORing every 4 bytes (DWORD) with 0xBABEBABE. I knew that because XORing the first 4 bytes with it gave me 0x4D5A9000 (MZ header). I want a script that can automate the process so that I can decode the file.

Here's what I have tried so far:

xor_key = 0xfe
result = bytearray('')
with open("myfile.bin","rb") as encoded_file:
    for one_byte in encoded_file.read():
        result.append(one_byte^xor_key)

But this only works for 1byte data at a time.

Thank you

Upvotes: 0

Views: 1872

Answers (1)

Matured Fella
Matured Fella

Reputation: 73

I already solved it but this might help if anyone runs into such an issue some day :)

import struct
from functools import partial

XOR_key = 0xbabebabe
XORed_data = bytearray('')
with open('binaryFile.bin','rb') as fileToXOR:
    for chunk in iter(partial(fileToXOR.read, 4), ''):
        data = struct.unpack('I', chunk)[0]
        if data != 0:
            result = data ^ XOR_key
            XORed_data += bytearray(struct.pack("I", result))
        else:
            XORed_data += bytearray("\x00\x00\x00\x00")

with open('decrypted_file.bin','wb') as XORedFile:
    XORedFile.write(XORed_data)

Upvotes: 1

Related Questions