0

I have a simple piece of Python code where I want to xor two hex strings and unhexlify the result as below

def _xor(s1, s2):
    return hex(int(s1, 16) ^ int(s2, 16))[2:]

if __name__ == "__main__":

    print(unhexlify('11b407ef4f01534a138a8599545dc3c943535dac95477d7f1334fec85408197c'))
    print(unhexlify('199de3b1e4da5664d045d9f07d75d22eb853e875c788147f1db811bebe8c4282'))
    result = _xor('11b407ef4f01534a138a8599545dc3c943535dac95477d7f1334fec85408197c', '199de3b1e4da5664d045d9f07d75d22eb853e875c788147f1db811bebe8c4282')

    print(result)

    print(unhexlify(result))

This fails unless I pad the result with a zero before passing to unhexlify. Can I just check the result is a even number of characters and if not pad with a zero ?

I guess I would like to know why my xor function returns without the zero. Why is there a disconnect here between what the hex function returns and unhexlify ?

Thanks

Glenn Pierce
  • 720
  • 1
  • 6
  • 18
  • 1
    "Can I just check the result is a even number of characters and if not pad with a zero?" - yes, definitely – ForceBru Aug 11 '21 at 11:32
  • 1
    unhexlify (from the binascii module) gives a very explicit exception when the input string has an odd number of characters. Why not write a simple wrapper that checks for that situation and prepends '0' as appropriate? –  Aug 11 '21 at 12:05

0 Answers0