Search code examples
pythonpython-3.xhashlib

Adding a hash of the string to the same line in Python 3


I'm trying to write a script which would take a password txt file (with cleartext passwords in each line) as input. The new output txt file would include passwords in cleartext and hash (SHA1) in each line as:

password:5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8 password2:2aa60a8ff7fcd473d321e0146afd9e26df395147 ...

So far, this is what I have:


wordlist = input("Input name of wordlist file: ")
result = input("Enter name of result file: ")

with open(result, 'w') as results:
    for word in open(wordlist).read().split():
        hash = hashlib.md5(word.encode())
        hash.update(bytes(word, 'utf-8'))
        results.write(word + ':' + hash + '\n')

The error:

Traceback (most recent call last):
  File "rainbow.py", line 11, in <module>
    results.write(word + ':' + hash + '\n')
TypeError: must be str, not _hashlib.HASH

Thanks a bunch!


Solution

  • hash is an instance of _hashlib.HASH (as the traceback says), so you cannot simply add it to a string. Instead you have to generate a string from hash using hash.hexdigest():

    import hashlib
    
    word = 'password:5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8'
    hash = hashlib.md5()
    hash.update(bytes(word, 'utf-8'))
    print(word + ':' + hash.hexdigest() + '\n')enter code here
    # password:5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8:5c56610768a788522ad3502b58b660fd
    

    Used in your original code, the fix would look like this:

    wordlist = input("Input name of wordlist file: ")
    result = input("Enter name of result file: ")
    
    with open(result, 'w') as results:
        for word in open(wordlist).read().split():
            hash = hashlib.md5()
            hash.update(bytes(word, 'utf-8'))
            results.write(word + ':' + hash.hexdigest() + '\n')
    

    edited based on comments by @OndrejK. and @wwii