异或后十六进制字符串转换为 ASCII

Hex string convert to ASCII after XOR

我是 Python 的新手,我正在尝试学习如何对十六进制编码的密文进行异或运算,然后得出其 ASCII 值。

我已经尝试了之前关于该主题的帖子中概述的一些功能 - 例如 bytearray.fromhex、binascii.unhexlify、decode("hex"),它们都产生了不同的错误(显然是由于我缺乏理解)。其中一些错误是由于我的 python 版本 (python 3)。

让我举一个简单的例子,假设我有一个十六进制编码的字符串 ciphertext_1 ("4A17") 和一个十六进制编码的字符串 ciphertext_2。我想对这两个字符串进行异或运算并得出它们的 ASCII 值。我最接近的解决方案是使用以下代码:

result=hex(int(ciphertext_1, 16) ^ int(ciphertext_2, 16))
print(result)

这会打印出以下结果:0xd07 (这是我理解的十六进制字符串??)

然后我尝试将其转换为其 ASCII 值。目前,我正在尝试:

binascii.unhexliy(result)

但是这给了我一个错误:"binascii.Error: Odd-length string" 我已经尝试了上面概述的不同功能,并尝试解决这个特定错误(剥离功能给出另一个错误) - 但是我没有成功。我意识到我缺乏对这个主题的知识和理解,所以我希望有人能给我建议?

完整示例:

#!/usr/bin/env python
import binascii

ciphertext_1="4A17"
ciphertext_2="4710"

result=hex(int(ciphertext_1, 16) ^ int(ciphertext_2, 16))
print(result)
print(binascii.unhexliy(result))
from binascii import unhexlify

ciphertext_1 = "4A17"
ciphertext_2 = "4710"
xored = (int(ciphertext_1, 16) ^ int(ciphertext_2, 16))
# We format this integer: hex, no leading 0x, uppercase
string = format(xored, 'X')
# We pad it with an initial 0 if the length of the string is odd
if len(string) % 2:
    string = '0' + string
# unexlify returns a bytes object, we decode it to obtain a string
print(unhexlify(string).decode())
#
# Not much appears, just a CR followed by a BELL

或者,如果您更喜欢字符串的 repr

print(repr(unhexlify(string).decode()))
# '\r\x07'

当执行像 XOR 这样的 byte-wise 操作时,使用 bytes 对象通常更容易(因为单个字节被视为整数)。从this question,然后,我们得到:

ciphertext_1 = bytes.fromhex("4A17")
ciphertext_2 = bytes.fromhex("4710")

然后可以像 那样通过理解来完成字节的异或运算。然后您可以将其转换为字符串:

result = [c1 ^ c2 for (c1, c2) in zip(ciphertext_1, ciphertext_2)]
result = ''.join(chr(c) for c in result)

我可能会采取稍微不同的角度并创建一个 bytes 对象而不是一个列表,它可以被解码到你的字符串中:

result = bytes(b1 ^ b2 for (b1, b2) in zip(ciphertext_1, ciphertext_2)).decode()