Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 XOR bytearrays

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=
like image 489
user1045890 Avatar asked Jul 16 '26 07:07

user1045890


1 Answers

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))
like image 157
AKX Avatar answered Jul 18 '26 21:07

AKX