Im new to python and I have (maybe) a dumb question.
I have to XOR two value. currently my values look like this:
v1 =
<class 'str'>
2dbdd2157b5a10ba61838a462fc7754f7cb712d6
v2 =
<class 'str'>
5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
but the thing is, i need to XOR the actual HEX value instead of the ascii value of the given character in the string.
so for example:
the first byte in the first string is s1 = 2d
, in the second string s2 = 5b
def sxor(s1,s2):
return ''.join(chr(ord(a) ^ ord(b)) for a,b in zip(s1,s2))
this will not work, because it gives back the ASCII value of each character (then XOR them), which is obviously differs from the actual hex value.
Your mistake is converting the characters to their ASCII codepoints, not to integer values.
You can convert them using int()
and format()
instead:
return ''.join(format(int(a, 16) ^ int(b, 16), 'x') for a,b in zip(s1,s2))
int(string, 16)
interprets the input string as a hexadecimal value. format(integer, 'x')
outputs a hexadecimal string for the given integer.
You can do this without zip()
by just taking the whole strings as one big integer number:
return '{1:0{0}x}'.format(len(s1), int(s1, 16) ^ int(s2, 16))
To make sure leading 0
characters are not lost, the above uses str.format()
to format the resulting integer to the right length of zero-padded hexadecimal.