0

我需要对两个十六进制字符串进行异或,以便每个字节单独进行异或,但它不起作用,因为ord()我使用的函数似乎是int作为输入而不是预期的字符串。先看看他的代码,看看我的意思:

from binascii import hexlify, unhexlify

def xor_hexstr(s1, s2):
    if len(s1) > len(s2):
        q = zip(unhexlify(s1[:len(s2)]), unhexlify(s2))
        return hexlify("".join(chr(ord(c1) ^ ord(c2)) for c1, c2 in q))

    else:
        q = zip(unhexlify(s2[:len(s1)]), unhexlify(s1))
        return hexlify("".join(chr(ord(c1) ^ ord(c2)) for c1, c2 in q))


t1 = "0ec17c9dabb8955c5dfb9cef627ddb4d"
t2 = "4ca00ff4c898d61e1edbf1800618fb28"

xor_hexstr(t1, t2)

我得到的错误是:

TypeError: ord() expected string of length 1, but int found

然后我检查了 q 的值,由于某种原因,它们确实是整数。我不明白为什么,因为根据我的逻辑,它们应该是字符串,因为我给了它一个十六进制编码的字符串,将其解开,然后将每个字符插入 q 中的一个槽中。

4

2 回答 2

2

您正在使用hexlifyandunhexlify在 Python 3 上,它们返回一个bytes对象。然后压缩这些对象,它会遍历bytes对象以创建对。对对象的迭代bytes产生整数。请参阅bytes类型文档

虽然bytes文字和表示基于 ASCII 文本,但bytes对象实际上表现得像不可变的整数序列,序列中的每个值都受到限制,因此0 <= x < 256.

ord()循环bytes对象时不需要使用;您已经有代表各个字节的整数。

bytes只需在对值进行异或运算后再次使用对象:

def xor_hexstr(s1, s2):
    if len(s1) > len(s2):
        q = zip(unhexlify(s1[:len(s2)]), unhexlify(s2))
    else:
        q = zip(unhexlify(s2[:len(s1)]), unhexlify(s1))

    return hexlify(bytes(c1 ^ c2 for c1, c2 in q))

请注意,它也hexlify返回一个bytes对象。如果你必须有一个字符串(unicode)对象,然后从 ASCII 解码:

xor_hexstr(t1, t2).decode('ASCII')

演示:

>>> xor_hexstr(t1, t2)
b'426173696320434243206d6f64652065'
>>> xor_hexstr(t1, t2).decode('ASCII')
'426173696320434243206d6f64652065'
于 2013-07-11T15:08:11.660 回答
0
from binascii import hexlify, unhexlify

def xor_hexstr(s1, s2):
    q = zip(unhexlify(s1), unhexlify(s2))
    return "".join(chr(c1 ^ c2) for c1, c2 in q)


s1 = "0ec17c9dabb8955c5dfb9cef627ddb4d"
s2 = "4ca00ff4c898d61e1edbf1800618fb28"

print(xor_hexstr(s1, s2))

输出Basic CBC mode e

于 2013-07-11T15:13:10.970 回答