Search code examples
pythonpython-3.xcryptographymd5hashlib

How to hash an already hashed value for a given range?


I'm trying to design a One-Time-Password algorithm. I want to get a string input from the user and hash it repeatedly for a 100 times, then store each into an array. I'm stuck on the part that requires repeatedly hashing the string.

I've tried the basics, I know how to get the hash of a string value once using hashlib. In the code below, I tried applying it this way to do it for 10 times, but I feel like there's an easier way that actually works.

import hashlib

hashStore= []

password= input("Password to hash converter: ")
hashedPassword= hashlib.md5(password.encode())
print("Your hash is: ", hashedPassword.hexdigest())

while i in range(1,10):
    reHash= hashlib.md5(hashedPassword)
    hashStore.append(rehash)
    i= i+1
    print("Rehashed ",reHash.hexdigest())

However this code doesn't work. I'm expecting it to "re-hash" the value and each time it does so add it to the array.

Any and all help is appreciated :)


Solution

    1. For-loops in Python can be implemented easier. Just write for i in range(10): without anything in the loop inside.

    2. hashStore.append(rehash) uses rehash instead of reHash

    3. You don't memoize your reHash so you are always try to hash the starting string

    4. You should convert your hash to string if you want to rehash it: reHash.hexdigest().encode('utf-8')

    Here is the full working code:

    import hashlib
    
    hashStore = []
    
    password = input("Password to hash converter: ")
    hashedPassword = hashlib.md5(password.encode())
    print("Your hash is: ", hashedPassword.hexdigest())
    reHash = hashedPassword
    for i in range(10):
        reHash = hashlib.md5(reHash.hexdigest().encode('utf-8'))
        hashStore.append(reHash)
        print("Rehashed ",reHash.hexdigest())