2012-11-24 50 views
1

我有一个我想用字符串'text'附加的id列表。 我想检查是否有任何ids(在附加'text'字符串后)等于字符串'text_compare'。SHA512 Python为同一个字符串产生了不同的结果

奇怪的是,散列之前的字符串是相同的,但散列发生后,散列似乎没有产生相同的结果。以下是我的代码。您可以在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] 

回答

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 
+0

感谢,我在使用MD5时遇到同样的问题,我犯了同样的错误 – clarenswd

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) 
# ... 
+0

谢谢。我认为update()将替换字符串而不是添加到它。 –

+0

@AfifNajib:不,它实际上是将字符串追加到原始字符串中,因此您不需要一次性传递所有字符串。它可能有这样的方法,因为一些哈希可能不需要一次知道整个字符串,而是将它们存储为已处理的形式。无论如何'update()'用额外的值更新现有的哈希对象,不会创建新的哈希。 – Tadeck

0

你缺少这一行: H = hashlib.sha512()

权h.update之前(T)

如果检查python docs(http://docs.python.org/2/library/hashlib.html) 它解释说update会返回给hashlib所有字符串的摘要。 所以你的情况你是散列字符串是:

LOOP1: '1beruk makye'

环2: '1beruk makye2beruk makye'

循环3: '1beruk makye2beruk makye3beruk makye'

相关问题