python - 在 Python 中对两个十六进制字符串进行异或 - 哪种方法是正确的?

标签 python string hex ascii xor

几天来,我一直在努力寻找一种方法来正确地异或存储在字符串中的两个十六进制数字,并且我遇到了两种方法,这两种方法对我来说都有意义,但会产生不同的结果。我不太精通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)])])

方法2:

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不再具有字符串的解码功能)

最佳答案

your_string.encode('hex') 会将 your_string 的每个字符替换为其十六进制的 ASCII 值。

例如,知道“A”字母在 ASCII 中是 0x41:

>>> 'AAAA'.encode('hex')
'41414141'

您也可以使用解码来执行另一种方式:

>>> '41414141'.decode('hex')
'AAAA'

但这不是你真正想要的。您想要的是将 0x12 转换为 18 (16 + 2)。为此,正确的方法是使用 int(your_string, 16) 将 your_string 解释为以 16 为基数编码的数字。

所以,正确的解决方案是最后一个。

xor = hex(int(s1, 16) ^ int(s2, 16))

s1s2 是包含数字的十六进制表示形式的字符串,您将它们解码为 int 告诉 Python 它的基数是 16。进行异或,最后使用十六进制表示形式(使用 hex)将其转换回字符串。

关于python - 在 Python 中对两个十六进制字符串进行异或 - 哪种方法是正确的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17390050/

相关文章:

python - AWS Boto3 SQS MessageBody 与 MessageAttributes

python - 除了 NumPy 矩阵中的特定列之外,是否有一种有效的方法来获取最大元素的位置?

java - 这个映射/字符串数组中发生了什么?

mysql - 检查字符串是否包含数字

java - 如何构建匹配十六进制数字的正则表达式?

c# - 将十六进制字符串转换为颜色

Python:嵌套 for 循环或 "next"语句

python - 我收到错误尝试相对导入超出顶级包

python - 从 pandas 的列表中提取唯一的项目

vb.net - 大字符串永远持续到 'create'