我是Python的新手&我正试图学习如何相互之间进行XOR十六进制编码的密文,然后派生ASCII值。
我已经尝试过以前关于这个主题的文章中概述的一些函数--比如bytearray.fromhex、binascii.unhexlify、decode(“十六进制”),它们都产生了不同的错误(显然是因为我缺乏理解)。其中一些错误是由于我的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:奇数长度字符串“,我尝试了上述不同的函数,并试图解决这个特定的错误(条形函数给出了另一个错误),但是我没有成功。我意识到我对这个问题缺乏知识和理解,所以我希望有人能给我提供建议。
完整的例子:
#!/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))
发布于 2018-03-16 04:47:34
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'
发布于 2018-03-16 05:00:41
当执行像XOR这样的逐字节操作时,使用bytes
对象通常更容易(因为单个字节被视为整数)。那么,我们从this question得到:
ciphertext_1 = bytes.fromhex("4A17")
ciphertext_2 = bytes.fromhex("4710")
XORing --字节可以像在this question中那样用一个理解来完成。然后,您可以将其转换为字符串:
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()
https://stackoverflow.com/questions/49320891
复制