Search code examples
pythonxor

XORing file with multi-byte key


I'm simply trying to XOR a file with a multi-byte key. The key may vary in length. Returning the following error:

TypeError: ord() expected string of length 1, but int found

Here is what I'm working with right now.

def xor(data, key):
    l = len(key)

    decoded = ""
    for i in range(0, len(data)):
        decoded += chr(ord(data[i]) ^ ord(key[i % l]))
    return decoded

data = bytearray(open('myfile.bin', 'rb').read())

key = '\x2a\x2b\x2c\x5e\x25\x44'
a = xor(data, key)
print a

I know I'm missing something simple but can't place it.


Solution

  • bytearray are ... array of bytes ... not char.

    You cannot use ord() on a byte. This has no meaning.

    Try that instead:

    def xor(data, key):
        l = len(key)
    
        decoded = ""
        for i in range(0, len(data)):
                decoded += chr(data[i] ^ ord(key[i % l]))
    
    
        return decoded
    

    Not very Pythonic ... I probably could have done better. But seems to work at least.


    EDIT: As explained in the comments, it is not a good idea to mix bytes and unicode characters.

    As you are working with bytes here, your key should have been bytes too. Simplifying the code as a side effet:

    def xor(data, key):
        l = len(key)
        return bytearray((
            (data[i] ^ key[i % l]) for i in range(0,len(data))
        ))
    
    
    data = bytearray(open('myfile.bin', 'rb').read())
    
    key = bytearray([0x2a,0x2b,0x2c,0x5e,0x25,0x44])