Skip to content

Instantly share code, notes, and snippets.

@mattnotmax
Last active January 16, 2023 08:42
Show Gist options
  • Select an option

  • Save mattnotmax/2ad1f65875dee5eb160e345fb05b6466 to your computer and use it in GitHub Desktop.

Select an option

Save mattnotmax/2ad1f65875dee5eb160e345fb05b6466 to your computer and use it in GitHub Desktop.
Step by step example of a data being XORd with a multi-byte key
import binascii # This imports some functions used to convert data to hex values
data = "4d5a90000300000004000000ffff0000b8000000" # string representation of hex bytes start of executable file (notice the 4d 5a 'MZ' header).
text_key = "AABB" # string representation of the XOR key. This can be as long as you like
hex_data = (binascii.unhexlify(data)) # convert the data to Python hex type
hex_key = (binascii.unhexlify(text_key)) # convert the key to Python hex type
print(f"\nXOR Key is {hex_key}")
print(f"\nData to be encrypted is {hex_data}")
input("\nPress any key to encrypt each byte...")
encrypted = [] # set up a list to hold all our encrypted values
"""
Now we set up a loop to take the first byte of our data and XOR it against the bytes in the key.
If your key is 2 hex bytes long, then it will alternative between byte 1, then byte 2, then back to byte 1 as it XORs the bytes in our data
"""
for index,value in enumerate(hex_data):
a = hex_data[index] ^ hex_key[index % len(hex_key)] # This is the actual encryption part which takes the hex byte of the data and XORs it with the alternating bytes of the key.
encrypted.append(a) # This puts the encrypted hex byte into a final list
input(f"\nPosition {index}: {hex(value)} is XORd with {hex(hex_key[index % len(hex_key)])} = {hex(a)}") # printing each encrypted value
print("\nThe final encrypted data is:")
print(f"\n{bytes(encrypted)}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment