Python: XOR hex strings [duplicate] Python: XOR hex strings [duplicate] python python

Python: XOR hex strings [duplicate]


You are missing a couple of things here.

First, you will not want to XOR those strings. You have the strings in an encoded form, therefore, you need to .decode() them first:

binary_a = a.decode("hex")binary_b = b.decode("hex")

Then, as already mentioned, the zip() function stops iterating as soon as one of the two sequences is exhausted. No slicing is needed.

You need the second version of the loop: First, you want to get the ASCII value of the characters: ord() produces a number. This is necessary because ^ only works on numbers.

After XORing the numbers, you then convert the number back into a character with chr:

def xor_strings(xs, ys):    return "".join(chr(ord(x) ^ ord(y)) for x, y in zip(xs, ys))xored = xor_strings(binary_a, binary_b).encode("hex")

Using .encode() at the end, we get the binary string back into a form, that prints nicely.


int('', 16) converts a hex string to an integer using base 16:

>>> int('f', 16)15 >>> int('10', 16)16

So do this:

result = int(a, 16) ^ int(b, 16) # convert to integers and xor them togetherreturn '{:x}'.format(result)     # convert back to hexadecimal