1

我有一个要附加字符串“文本”的 ID 列表。我想检查是否有任何 id(在附加了“text”字符串之后)等于字符串“text_compare”。

奇怪的是,在散列发生之前的字符串是相等的,但是在散列发生之后,散列似乎没有产生相同的结果。下面是我的代码。您可以在 Python 命令行上对其进行测试。

import hashlib
h = hashlib.sha512()

text = 'beruk makye'
text_compare = '3beruk makye'
text_compare_hash = h.update(text_compare)
text_compare_hash = h.hexdigest()

ids = [1,2,3]
texts = []
bool_text = []
bool_text_hash = []

for id in ids:
    texts.append(str(id) + text)

for t in texts:
    if t == text_compare:
        bool_text.append(True)
    else:
        bool_text.append(False)

for t in texts:
    h.update(t)
    t_hash = str(h.hexdigest())
    if t_hash == text_compare_hash:
        bool_text_hash.append(True)
    else:
        bool_text_hash.append(False)

print ids
# [1, 2, 3]
print texts
# ['1beruk makye', '2beruk makye', '3beruk makye']
print bool_text
# [False, False, True]
print bool_text_hash
# [False, False, False]
4

3 回答 3

5

您的问题是您正在重新使用相同的哈希对象,所以您只是不断添加它。每次你应该实例化一个新的 sha512() 对象。下面的代码可以正常工作。

import hashlib
h = hashlib.sha512()

text = 'beruk makye'
text_compare = '3beruk makye'
text_compare_hash = h.update(text_compare)
text_compare_hash = h.hexdigest()

ids = [1,2,3]
texts = []
bool_text = []
bool_text_hash = []

for id in ids:
    texts.append(str(id) + text)

for i in texts:
    hash = hashlib.sha512(i).hexdigest()
    print i, hash, hash == text_compare_hash
于 2012-11-24T04:09:25.083 回答
1

这里的问题h是已经创建了,然后你通过调用方法向它添加字符串。update()

要解决这个问题,你可以例如。重新初始化h为新的 sha512 哈希:

# ...
for t in texts:
    h = hashlib.sha512()  # <--- here
    h.update(t)
    t_hash = str(h.hexdigest())
    if t_hash == text_compare_hash:
        bool_text_hash.append(True)
    else:
        bool_text_hash.append(False)
# ...
于 2012-11-24T04:09:45.200 回答
0

您缺少这一行: h = hashlib.sha512()

就在 h.update(t) 之前

如果您检查 python 文档 (http://docs.python.org/2/library/hashlib.html),它解释说 update 将返回到目前为止给 hashlib 的所有字符串的摘要。因此,在您的情况下,您要散列的字符串是:

loop1: '1beruk makye'

loop2: '1beruk makye2beruk makye'

loop3: '1beruk makye2beruk makye3beruk makye'

于 2012-11-24T04:19:48.370 回答