You are using hexlify
and unhexlify
on Python 3, where they return a bytes
object. You then zip these objects, which iterates over the bytes
objects to create the pairs. Iteration over a bytes
object produces integers. See the bytes
type documentation:
While
bytes
literals and representations are based on ASCII text,bytes
objects actually behave like immutable sequences of integers, with each value in the sequence restricted such that0 <= x < 256
.
You do not need to use ord()
when looping over a bytes
object; you already have integers representing the individual bytes.
Simply use a bytes
object again after XOR-ing the values:
def xor_hexstr(s1, s2):
if len(s1) > len(s2):
q = zip(unhexlify(s1[:len(s2)]), unhexlify(s2))
else:
q = zip(unhexlify(s2[:len(s1)]), unhexlify(s1))
return hexlify(bytes(c1 ^ c2 for c1, c2 in q))
Note that hexlify
returns a bytes
object too. If you have to have a string (unicode) object then decode from ASCII:
xor_hexstr(t1, t2).decode('ASCII')
Demo:
>>> xor_hexstr(t1, t2)
b'426173696320434243206d6f64652065'
>>> xor_hexstr(t1, t2).decode('ASCII')
'426173696320434243206d6f64652065'