SHA512 Python对同一个字符串产生了不同的结果

2024-05-05 22:12:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个id列表,我想用字符串“text”附加。 我想检查是否有任何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]

Tags: 字符串textinidfalsetrueidsfor
3条回答

你的问题是你正在使用同一个哈希对象,所以你只是不断地添加它。每次应该实例化一个新的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

这里的问题是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)
# ...

您缺少以下行: h=hashlib.sha512()

就在h.update(t)之前

如果你检查python文档(http://docs.python.org/2/library/hashlib.html) 它解释了update将返回到目前为止提供给hashlib的所有字符串的摘要。 所以在你的例子中,你要散列的字符串是:

循环1:“1beruk makye”

循环2:“1beruk makye2beruk makye”

循环3:“1beruk makye2beruk makye3beruk makye”

相关问题 更多 >