Reputation: 83
I'm trying to create a function that will take the sha1
hash and update it 500 times with itself, so for example:
>>> import hashlib
>>> d = hashlib.sha1()
>>> d.update("test")
>>> d.hexdigest()
'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3'
>>> e = hashlib.sha1()
>>> e.update("a94a8fe5ccb19ba61c4c0873d391e987982fbbd3")
>>> e.hexdigest()
'c4033bff94b567a190e33faa551f411caef444f2'
>>>
What I want to do is take the hash of the original string test
and rehash it into another hash, from the given hash.
I'm having some trouble doing this:
def sha1_rounds(string, salt=None, front=False, back=False, rounds=500, **placeholder):
obj = hashlib.sha1()
if salt is not None and front and not back:
obj.update(salt + string)
elif salt is not None and back and not front:
obj.update(string + salt)
else:
obj.update(string)
for _ in range(rounds):
obj1 = obj.hexdigest()
obj = obj.update(obj1)
return obj.hexdigest()
When this code is run, it's giving me the following error:
Traceback (most recent call last):
File "<pyshell#93>", line 1, in <module>
sha1_rounds("test")
File "<pyshell#92>", line 10, in sha1_rounds
obj1 = obj.hexdigest()
AttributeError: 'NoneType' object has no attribute 'hexdigest'
If I'm understanding this correctly, what this error is telling me is that when I'm trying to re-update the hash object it's resulting in None
. However, I've tried a few different things, and I'm not entirely sure how I can successfully do this. How can I create a new hash object inside of a for loop from a given hash?
Upvotes: 2
Views: 831
Reputation: 83
I think I figured this out, by creating a new hash object and hexdigesting the string before the rounds, I might be able to speed up performance by moving the hash object creation outside of the for loop. If anyone has any other ideas, I would be excited to see them:
def sha1_rounds(string, salt=None, front=False, back=False, rounds=500, **placeholder):
obj = hashlib.sha1()
if salt is not None and front and not back:
obj.update(salt + string)
elif salt is not None and back and not front:
obj.update(string + salt)
else:
obj.update(string)
hashed = obj.hexdigest()
for _ in range(rounds):
obj1 = hashlib.sha1()
obj1.update(hashed)
hashed = obj1.hexdigest()
return hashed
Upvotes: 1