当我想要一个字符串时,Unhexlify似乎给了我一个int

时间:2013-07-11 14:59:57

标签: python python-3.x xor ord

我需要对两个十六进制字符串进行XOR运算,以便每个字节分别进行异或,但它不起作用,因为我使用的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中的一个插槽。

2 个答案:

答案 0 :(得分:2)

您在Python 3上使用hexlifyunhexlify,它们返回bytes个对象。然后,您将对这些对象进行压缩,这些对象将遍历bytes个对象以创建对。对bytes对象的迭代会产生整数。请参阅bytes type documentation

  

虽然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'

答案 1 :(得分: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