Nor*_*sul 9 python string hex encode xor
我已经在这里发布了几天类似的问题了,但似乎我没有问正确的事情,所以请原谅我,如果我用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
Run Code Online (Sandbox Code Playgroud)
因此,总而言之,我希望能够输入两个不同或相等长度的十六进制字符串(这些字符串通常是以十六进制编码的ASCII字母),并获得它们的XOR,使得每个字节分别进行异或.
Mar*_*ers 12
用binascii.unhexlify()把你的十六进制字符串的二进制数据,然后XOR的是,要回与十六进制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'
Run Code Online (Sandbox Code Playgroud)
实际XOR每经解码的数据的字节应用(使用ord()和chr()去和从整数).
请注意,在您的示例中,我被截断s1为与s2(从开头忽略字符s1)相同的长度.您可以通过循环字节来使用较短的密钥对所有字符进行编码:s1s2
>>> from itertools import cycle
>>> hexlify(''.join(chr(ord(c1) ^ ord(c2)) for c1, c2 in zip(unhexlify(s1), cycle(unhexlify(s2)))))
'2916070d1c'
Run Code Online (Sandbox Code Playgroud)
你不需要有使用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'
Run Code Online (Sandbox Code Playgroud)
我发现了一个很简单的解决方案
def xor_str(a,b):
result = int(a, 16) ^ int(b, 16) # convert to integers and xor them
return '{:x}'.format(result) # convert back to hexadecimal
Run Code Online (Sandbox Code Playgroud)
它将xor字符串直到其中一个主题结束