Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to XOR two hex strings in Python 3?

I have two strings stored in 2 separate files, string1="95274DE03C78B0BD" and string2="48656c6c6f20576f".

How can I do bitwise XOR them in Python 3? I expect to get DD42218C5358E7D2 as my result. Please note that I don't want to ord() the strings, my strings are already in hex.

like image 794
John Smith Avatar asked Oct 23 '15 22:10

John Smith


1 Answers

Strings in Python 3 are unicode objects and so a string of hexadecimal characters does not correspond to the binary representation of the integer in memory (which you need to use XOR).

With this in mind, you could interpret the strings as base-16 integers first, XOR them, and convert the resulting integer back to a hex string:

>>> hex(int(string1, 16) ^ int(string2, 16))
'0xdd42218c5358e7d2'
like image 71
Alex Riley Avatar answered Sep 22 '22 04:09

Alex Riley