将字符串的散列添加到 Python 中的同一行 3

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

我正在尝试编写一个脚本,它将一个密码 txt 文件(每行都有明文密码)作为输入。新的输出 txt 文件将在每一行中包含明文和哈希 (SHA1) 密码,如:

密码:5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8 password2:2aa60a8ff7fcd473d321e0146afd9e26df395147 ...

到目前为止,这是我拥有的:


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')

错误:

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

非常感谢!

hash_hashlib.HASH 的一个实例(如回溯所说),因此您不能简单地将它添加到字符串中。相反,您必须使用 hash.hexdigest():

hash 生成一个字符串
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

在您的原始代码中使用,修复如下所示:

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')

根据@OndrejK 的评论编辑。和@wwii