Search code examples
pythonpython-2.7xor

How to XOR 2 strings proper in python?


I am currently having issues with XOR'ing two strings in python where it is returning gibberish results.

Based on research I derived the method in XORing is as follows : -

def xor_strings(s,t):
    """xor two strings together"""
    return "".join(chr(ord(a)^ord(b)) for a,b in zip(s,t))

So I proceed to XOR two string as below :

c1 = xor_strings('cisco12300000000','46608024c8f48fd0')
print c1

The resulting string came back with gibberish as shown in the image below : enter image description here

Am i doing something wrong here with the XOR operation ?

In summary im trying to generate a string similar to freeradius hashing of userpassword with shared secret and authenticator IV

EDIT: This is not a duplicate as the attempted solution return gibberish hence the question


Solution

  • Gibberish is what you get when you XOR. But if you XOR the gibberish with the original value you get the original string back:

    #!python2
    def xor_strings(s,t):
        """xor two strings together"""
        return "".join(chr(ord(a)^ord(b)) for a,b in zip(s,t))
    
    c1 = xor_strings('cisco12300000000','46608024c8f48fd0')
    print repr(c1) # To see the unprintable bytes as escape codes
    c1 = xor_strings(c1,'46608024c8f48fd0')
    print c1
    

    Output:

    'W_ESW\x01\x00\x07S\x08V\x04\x08VT\x00'
    cisco12300000000