Search code examples
pythonpython-3.xcryptographyxor

What is the correct way to convert bytes to a hex string in Python 3?


I'm working on the CryptoPals challenges and I'm stuck on Challenge 2 Set 1. I'm familiar with bitwise xor-ing, but I can't get the desired result in a hex string. This is my function right now:

def strxor(s1, s2):
    bytes1 = unhexlify(s1)
    bytes2 = unhexlify(s2)
    b = b""
    for c1, c2 in zip(bytes1, bytes2):
        b += bytes([c1^c2])
    return hexlify(b)

It currently returns the desired hex string, but as a bytes object instead of a string. How do I convert these? Or is there a better way to handle this?


Solution

  • Bytes objects have the "hex" method:

    return b.hex()