First you need to zip
your strings then use ord
(in python 2
) and ^
for each of characters :
>>> s1 = b'abc'
>>> s2 = b'efg'
>>> ''.join(chr(ord(i)^ord(j)) for i,j in zip(s1,s2))
'\x04\x04\x04'
the ord()
function retuen value of the byte when the argument is an 8-bit string.But if you are using python 3
you dont need ord
:
>>> ''.join(chr(i^j) for i,j in zip(s1,s2))
'\x04\x04\x04'
Since bytes objects are sequences of integers (akin to a tuple), for a bytes object b, b[0]
will be an integer, while b[0:1]
will be a bytes object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1)
example :
>>> s1[0]
97
>>> s1[0:1]
b'a'
and if you want to convert back your strings you need to firs convert the XOR
ed string to binary you can do it by binascii.a2b_qp
function :
>>> import binascii
>>> s=''.join(chr(i^j) for i,j in zip(s1,s2))
>>> s4=binascii.a2b_qp(s)
>>> ''.join(chr(i^j) for i,j in zip(s1,s4))
'efg'