几天来我一直在这里发布类似的问题,但似乎我没有问对问题,如果我的 XOR 问题让您筋疲力尽,请原谅我:D。
要点 - 我有两个十六进制字符串,我想对这些字符串进行异或运算,以便每个字节分别进行异或运算(即每对数字分别进行异或运算)。我想在 python 中执行此操作,并且我希望能够拥有不同长度的字符串。我将手动做一个例子来说明我的观点(我使用代码环境是因为它允许我在我想要的地方放置空格):
Input:
s1 = "48656c6c6f"
s2 = "61736b"
Encoding in binary:
48 65 6c 6c 6f = 01001000 01100101 01101100 01101100 01101111
61 73 6b = 01100001 01110011 01101011
XORing the strings:
01001000 01100101 01101100 01101100 01101111
01100001 01110011 01101011
00001101 00011111 00000100
Converting the result to hex:
00001101 00011111 00000100 = 0d 1f 04
Output:
0d1f04
因此,总而言之,我希望能够输入两个长度不同或相等的十六进制字符串(这些字符串通常是以十六进制编码的 ASCII 字母),并获得它们的异或,以便每个字节分别进行异或。
最佳答案
使用binascii.unhexlify()
将您的十六进制字符串转换为二进制数据,然后将其异或,返回到 binascii.hexlify()
的十六进制:
>>> from binascii import unhexlify, hexlify
>>> s1 = "48656c6c6f"
>>> s2 = "61736b"
>>> hexlify(''.join(chr(ord(c1) ^ ord(c2)) for c1, c2 in zip(unhexlify(s1[-len(s2):]), unhexlify(s2))))
'0d1f04'
实际 XOR 应用于解码数据的每个字节(使用 ord()
和 chr()
来回整数)。
请注意,就像在您的示例中一样,我将 s1
截断为与 s2
相同的长度(忽略 s1
开头的字符) .您可以通过循环字节使用较短的 key s2
对 所有 s1
进行编码:
>>> from itertools import cycle
>>> hexlify(''.join(chr(ord(c1) ^ ord(c2)) for c1, c2 in zip(unhexlify(s1), cycle(unhexlify(s2)))))
'2916070d1c'
您不必使用unhexlify()
,但它比遍历s1
和s2 容易得多
一次 2 个字符,并使用 int(twocharacters, 16)
将其转换为用于 XOR 运算的整数值。
上面的Python 3版本稍微轻一点;使用 bytes()
而不是 str.join()
并且您可以删除 chr()
和 ord()
当你直接迭代整数时调用:
>>> from binascii import unhexlify, hexlify
>>> s1 = "48656c6c6f"
>>> s2 = "61736b"
>>> hexlify(bytes(c1 ^ c2 for c1, c2 in zip(unhexlify(s1[-len(s2):]), unhexlify(s2))))
b'0d1f04'
>>> from itertools import cycle
>>> hexlify(bytes(c1 ^ c2 for c1, c2 in zip(unhexlify(s1), cycle(unhexlify(s2)))))
b'2916070d1c'
关于python - 如何异或两个十六进制字符串,以便每个字节分别异或?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17404690/