Search code examples
pythonencryptionxor

Creating a XOR key in Python


This has to do with encryption/decryption. I have an original string that i've created list of characters from.

['f', 'i', 'r', 's', 't', ' ']

I've encrypted the original string into a second list.

['h', '=', 'g', 'l', 'x', 'k']

What I need to do is create a XOR key so that encrypted list ^ XOR key = original list

How to create a XOR key (list) in order to accomplish this?


Solution

  • I may be way off here...

    >>> original = ['f', 'i', 'r', 's', 't', ' ']
    >>> xored = ['h', '=', 'g', 'l', 'x', 'k']
    >>> key = [chr(ord(a) ^ ord(xored[i])) for i, a in enumerate(original)]
    >>> key
    ['\x0e', 'T', '\x15', '\x1f', '\x0c', 'K']
    >>> [chr(ord(a) ^ ord(xored[i])) for i, a in enumerate(key)]
    ['f', 'i', 'r', 's', 't', ' ']
    >>> [chr(ord(a) ^ ord(key[i])) for i, a in enumerate(original)]
    ['h', '=', 'g', 'l', 'x', 'k']
    

    XOR'ing the ordinal of each element in original with the corresponding indexed ordinal of the key gives you the xored version.

    EDIT
    Since you seem to be trying to xor the list itself you can do this

    class XOR(list):
    
        def __xor__(self, other):
            return map(chr, [ord(x[0]) ^ ord(x[1]) for x in zip(self, other)])
    
    
    l = XOR(['f', 'i', 'r', 's', 't', ' '])
    print(l ^ ['\x0e', 'T', '\x15', '\x1f', '\x0c', 'K'])