You can use single bytes or multiple-byte keys for XOR in Python, and use looping to test keys. Here’s the XOR truth table.
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0
XOR operates one bit at a time. Python indicates XOR with the ^
operator.
Python XOR bytes
Simple example code XOR 2 bytes objects.
def bxor(b1, b2): # use xor for bytes
result = b""
for b1, b2 in zip(b1, b2):
result += bytes([b1 ^ b2])
return result
Alternatively, you can use a bytearray
which is mutable and can therefore avoid the problem. It also allows you to not allocate a new bytes
object on every iteration, you can just append the byte/int
.
def bxor(b1, b2): # use xor for bytes
result = bytearray()
for b1, b2 in zip(b1, b2):
result.append(b1 ^ b2)
return result
If you want something faster than the “manual” methods given, there’s always Numpy:
import numpy
def bxor_numpy(b1, b2):
n_b1 = numpy.fromstring(b1, dtype='uint8')
n_b2 = numpy.fromstring(b2, dtype='uint8')
return (n_b1 ^ n_b2).tostring()
A quick timeit
comparison:
import timeit
def bxor_ba(b1, b2):
result = bytearray(b1)
for i, b in enumerate(b2):
result[i] ^= b
return bytes(result)
def bxor(b1, b2): # use xor for bytes
result = b""
for b1, b2 in zip(b1, b2):
result += bytes([b1 ^ b2])
return result
b1, b2 = b'abcdefg' * 10, b'aaaaaaa' * 10
print(timeit.timeit('it(b1, b2)', 'from __main__ import b1, b2, bxor as it', number=10000))
print(timeit.timeit('it(b1, b2)', 'from __main__ import b1, b2, bxor_ba as it', number=10000))
Output:
Do comment if you have any doubts or suggestions on this Python XOR topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.