几天来,我一直在努力寻找一种方法来正确异或存储在字符串中的两个十六进制数字,并且我遇到了两种方法,这两种方法对我来说都很有意义,但会产生不同的结果。我对 Python 不是很精通(例如,我有 3 天的经验 :D),所以我不知道哪种方法是正确的。
方法一:
s1 = #hex number stored in a string 1
s2 = #hex number stored in a string 2
#Decoding the hex strings into ASCII symbols
s3 = s1.decode('hex')
s4 = s2.decode('hex')
#strxor - see the next code segment for the code of this function
xor1 = strxor(s3, s4)
#Encode the result back into ASCII
xor2 = xor1.encode('hex')
strxor 函数:
#This was given in my assignment and I am not entirely sure what is going on in
#here. I've been told that it takes two ASCII strings as input, converts them to
#numbers, XORs the numbers and converts the result back to ASCII again.
def strxor(a, b):
if len(a) > len(b):
return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)])
else:
return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b[:len(a)])])
方法二:
s1 = #ciphertext 1 - hex number in a string
s2 = #ciphertext 2 - hex number in a string
#convert the string to integers, xor them
#and convert back to hex
xor = hex(int(s1, 16) ^ int(s2, 16))
正如我之前所说,对于我有限的大脑来说,这两种解决方案似乎相同,但它们产生的结果却完全不同。问题是什么?我的系统上有 Python 2.7.3 和 3.3.2,我都试过了(虽然方法 1 没有,因为 python 3 不再有字符串的解码功能)