Search code examples
pythoncryptographyxor

How to xor in python using hex


Supossing I have an ascii text "Hello World" and a hex string, how can I xor them in python?

I know the two strings must be in the same format but I don't have any idea how to make it happen.


Solution

  • Depending on exactly what you mean by "a hex string", it should be easy. E.g:

    >>> text=b'Hello World'
    >>> hexi=b'\12\34\45\EF\CD\AB'
    >>> xors=[ord(t)^ord(x) for t,x in zip(text,hexi)]
    >>> xors
    [66, 121, 73, 48, 42, 102, 11, 44, 54, 48, 37]
    

    Now you have to decide how you want to represent this list of small integers. array.array would be best, or, as a bytestring:

    >>> b''.join(chr(x) for x in xors)
    'ByI0*f\x0b,60%'
    

    (this would show with a leading b in Python 3, where the distinction between strings of bytes and actual text is clearer and sharper, but all the code I show here works otherwise the same in Python 2 and 3).