Search code examples
pythonhashxor

doing xor for binaries in python


I'm in the middle of writing a simple hash function which get the input and creates a 32 bit hash file. I'm stuck in the xor part. And i'm not sure how i should write the function for xor. please help me with this. here is the code that i have done yet:

import BitVector
import io
import math
import struct

if __name__ == "__main__":
    message = raw_input("your message:")
    f= open('file.dat','w')
    f.write(message)
    f.close()

    f = open('file.dat')
    while 1:
       r = f.readline(1)
       hx = r.encode("hex")
       data = bin(int(hx, 16))[2:]
       key = 11111111
       x = int(data) ^ int(key)
       print hex(x)
       if not r:break
    f.close()

Solution

  • try using this for xoring:

    def xor_orig(data, key):
        return bool(data) ^ bool(key)
    

    For binary xoring, where data and key are binary values and using ^ character, you can use:

    def xor_orig(data, key):
        return int(data,2) ^ int(key,2)
    
    
    In [1]: data = '1010'
    In [2]: key = '0101'    
    In [3]: int(data,2) ^ int(key,2)
    Out[3]: 15
    In [4]: data = '10'    
    In [5]: key = '01'    
    In [6]: int(data,2) ^ int(key,2)
    Out[6]: 3
    In [7]: data = '10'    
    In [8]: key = '10'    
    In [9]: int(data,2) ^ int(key,2)
    Out[9]: 0
    

    Let me know if this helps.