pythonencryptionxorbitwise-xor

Why XOR function does not print out the expected hex value?


So I have the following function and I wonder why when I xor X and Y, it does not print out the hex value as expected_result? Is there anything I need to add? Am I missing something in the function?

def xor(X, Y):
  return "".join([chr(ord(a) ^ ord(b)) for (a, b) in zip(X, Y)])
X = "Hello World"
Y = "supersecret"
print(xor(X,Y))

expected_result = "3b101c091d53320c000910"


Solution

  • You are forgetting the part where you need to convert the resulting bytes to hexadecimals. Instead, you convert the bytes directly to characters, which means that you are decoding bytes that themselves may not be printable.

    Here is the code where the binary result of the two encoded character values (using ord) are converted to hex before being printed.

    def xor(X, Y):
      return "".join('{:02x}'.format(ord(a) ^ ord(b)) for (a, b) in zip(X, Y))
    X = "Hello World"
    Y = "supersecret"
    print(xor(X,Y))
    

    Note that this fixes the issue. However, the xor function should really be returning a binary array. Ciphertext is generally binary, hexadecimals are just used to make them presentable for human consumption:

    def xor(X, Y):
      return bytes([(ord(a) ^ ord(b)) for (a, b) in zip(X, Y)])
    X = "Hello World"
    Y = "supersecret"
    print(xor(X,Y).hex())
    

    Note that I've used Python 3, which is strongly recommended if you want to perform many conversions and handle byte arrays.