Search code examples
pythonxor

xor function in python


I'll be happy if someone can help with XOR function in python.

for example, I have two quite big messages (about 300 symbols) that is writteb by hex code how can I XOR them properly? I tried use general functions and converted to another types, but I wasn't able to do that(

I don't know which type of data I need to convert for?


Solution

  • Iterate over the string chars, then convert each char to int (int(a,16)), then apply xor, reconvert to hex with hex, strip the leading '0x' with [2:], and finally join everything

    stra = 'abc'
    strb = 'abd'
    ''.join(hex( int(a,16) ^ int(b,16) )[2:] for a,b in zip(stra, strb))
    

    Note that, as pointed in the comments, it will work only if the two strings have the same length. Otherwise some chars of the longer string will be ignored.