如何输入包含哈希值的字符串,并将其与hashlib方法一起使用

2024-10-17 06:19:12 发布

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

我正在做一个项目,涉及使用给定的哈希值更新哈希链。我的问题是,我似乎不知道如何使用输入的字符串作为哈希值。你知道吗

我的代码

import hashlib

hash1AsText = hashlib.sha256(b"This is my first hash")
# the origional source of the hash value. I wont have this for other hashes

hash1AsHash = ('F7002A5259567B1F993E743D3128B6A97B153EACFC7BB914802DCFB43D23FA2E')
# The string containing the hash value generated from the text above


chain1 = hashlib.sha256() # hash of blank value to start chain 1
#print hash of initial chain
print("\nInitial Chain1:\n",chain1.hexdigest().upper())

# print what is getting added
print("\nUpdated Chain1\nAdding:\t",hash1AsText.hexdigest().upper()) 

chain1.update(hash1AsText.digest()) # update chain using the "hash1AsText" hashlib object
print("New:\t",chain1.hexdigest().upper())


chain2 = hashlib.sha256() # hash of blank value to start chain 2
#print hash of initial chain
print("\nInitial Chain2:\n",chain2.hexdigest().upper())

# print what is getting added
print("\nUpdated chain2\nAdding:\t", bytes(hash1AsHash.encode('utf-8')))

# update chain using string conveted to bytes
chain2.update(bytes(hash1AsHash.encode('utf-8'))) 
print("New:\t",chain2.hexdigest().upper())

输出

Initial Chain1:
 E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855

Updated Chain1
Adding:  F7002A5259567B1F993E743D3128B6A97B153EACFC7BB914802DCFB43D23FA2E
New:     8E252D5D846A88D22F8EA8D55B79065521DA5AD3CBCEA51B826F9ED0B4B7D4CD

Initial Chain2:
 E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855

Updated chain2
Adding:  b'F7002A5259567B1F993E743D3128B6A97B153EACFC7BB914802DCFB43D23FA2E'
New:     9E213BC13DA41E1E1AF3216F11D0DECA41EACD1FD3496815D7599F830FD32C1A

我很困惑,因为两个链中的两个“加法”值都是相同的散列,但是当它们用于更新初始值时,会产生不同的结果。你知道吗

我假设在将字符串更改为bytes值时格式有问题。是否有其他方法可以导入包含哈希值的字符串,将其转换为hashlib对象(无需重新灰化),并将其与hashlib方法(如.update())一起使用?你知道吗


Tags: ofthechainnewvalueupdatehashupper