JDD
JDD

Reputation: 417

trying to convert hex to binary and xor the result

I have two hex strings. I'm trying to convert those strings to binary and xor them. Changing into a binary string is working but when I xor them together I get block looking symbols as the output.

texts = []

texts.insert(0, '315c4eeaa8b5f8aaf9174145bf43e1784b8fa00dc71d885a804e5ee9fa40b16349c146fb778cdf2d3aff021dfff5b403b510d0d0455468aeb98622b137dae857553ccd8883a7bc37520e06e515d22c954eba5025b8cc57ee59418ce7dc6bc41556bdb36bbca3e8774301fbcaa3b83b220809560987815f65286764703de0f3d524400a19b159610b11ef3e')

texts.insert(1, '234c02ecbbfbafa3ed18510abd11fa724fcda2018a1a8342cf064bbde548b12b07df44ba7191d9606ef4081ffde5ad46a5069d9f7f543bedb9c861bf29c7e205132eda9382b0bc2c5c4b45f919cf3a9f1cb74151f6d551f4480c82b2cb24cc5b028aa76eb7b4ab24171ab3cdadb8356f')

def sxor(s1,s2):    
    return ''.join((chr(ord(a) ^ ord(b))) for a,b in zip(s1,s2))


if __name__== "__main__":
    # print as binary string
    print bin(int(texts[1], 16))[2:]
    # xor two binary strings
    result = sxor( bin(int(texts[1], 16))[2:] , bin(int(texts[0], 16))[2:]) 
    print result

Upvotes: 0

Views: 156

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798526

Since xor is a bitwise operation (i.e., it works on numbers), you need to decode from and encode to hex around the actual operation.

return ''.join((chr(ord(a) ^ ord(b))) for a,b in zip(s1.decode('hex'),
  s2.decode('hex'))).encode('hex')

Upvotes: 1

Related Questions