Python 3 XOR字节数组

时间:2018-10-17 09:01:09

标签: python python-3.x bitwise-xor

python 3中是否有一个内置函数可以bitwise-xor个字节?例如,如果我有2个字节数组:

one = oE1ltQSsoEqRC4j1EMz1ORU1dyucIcI4WstKz-uhuKA=
two = Rffs1PW5zA1h5RFVh5MkLw5R7a2QVHY7cwnjuSPktwc=

one XOR two = 5bqJYfEVbEfw7pmgl1_RFhtkmoYMdbQDKcKpdshFD6c=

1 个答案:

答案 0 :(得分:1)

通常,如果您有两个bytes,则可以

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

对它们进行元素异或。

在您的情况下,您首先需要对字符串进行base64解码,然后对XOR进行解码,然后对base64进行编码...但是,由于Python不喜欢其中的错误填充,因此示例字符串将无法工作。

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))