在Python 3中将字符串的哈希值添加到同一行

时间:2019-01-20 20:58:01

标签: python python-3.x hashlib

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

密码:5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8 密码2: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

谢谢你!

1 个答案:

答案 0 :(得分:1)

hash_hashlib.HASH的实例(如回溯所示),因此您不能简单地将其添加到字符串中。相反,您必须使用hashhash.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

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

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