Skip to main content
 首页 » 编程设计

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

2025年05月04日29txw1958

我有一个 ID 列表,我想用字符串 'text' 附加这些 ID。 我想检查是否有任何 id(在附加“文本”字符串后)等于字符串“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] 

请您参考如下方法:

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