gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:16:33 25 4
gpt4 key购买 nike

我有一个 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

关于python - SHA512 Python 对同一个字符串产生不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13538122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com