Python 3 XOR bytearrays

user1045890 picture user1045890 · Oct 17, 2018 · Viewed 7.6k times · Source

Is there a built in function in python 3 that can bitwise-xor bytes? For example, if I have 2 bytearrays:

one = oE1ltQSsoEqRC4j1EMz1ORU1dyucIcI4WstKz-uhuKA=
two = Rffs1PW5zA1h5RFVh5MkLw5R7a2QVHY7cwnjuSPktwc=

one XOR two = 5bqJYfEVbEfw7pmgl1_RFhtkmoYMdbQDKcKpdshFD6c=

Answer

AKX picture AKX · Oct 17, 2018

In general, if you have two byteses, you can do

one_xor_two = bytes(a ^ b for (a, b) in zip(one, two))

to element-wise XOR them.

In your case, you'd first base64 decode the strings, then XOR, then base64 encode... however, the example strings won't work due to Python not liking the bad padding in them.

import base64

one = base64.b64decode('oE1ltQSsoEqRC4j1EMz1ORU1dyucIcI4WstKz-uhuKA=')
two = base64.b64decode('Rffs1PW5zA1h5RFVh5MkLw5R7a2QVHY7cwnjuSPktwc=')

one_xor_two = bytes(a ^ b for (a, b) in zip(one, two))

print(base64.b64encode(one_xor_two))