Xor bytes in python

Posted on August 16, 2020
Tags: Programming, Python

I was doing some crypto and needed a way to xor two types “bytes”.

There was some answers on Stack Overflow, but each involved some kind of zipping or list comprehension. I found an easier solution by using the pwntools library, with which one can directly do the conversion:

from pwn import xor
bytes1 = b'0001'
bytes2 = b'0100'
print(xor(bytes1, bytes2))

Result:

b'\x00\x01\x00\x01'



Here is the man page of this function:

xor(*args, **kwargs)
    xor(*args, cut = 'max') -> str

    Flattens its arguments using :func:`pwnlib.util.packing.flat` and
    then xor them together. If the end of a string is reached, it wraps
    around in the string.

    Arguments:
       args: The arguments to be xor'ed together.
       cut: How long a string should be returned.
            Can be either 'min'/'max'/'left'/'right' or a number.

    Returns:
       The string of the arguments xor'ed together.

    Example:
       >>> xor(b'lol', b'hello', 42)
       b'. ***'