我有这样的错误:

Traceback (most recent call last):
  File "python_md5_cracker.py", line 27, in <module>
  m.update(line)
TypeError: Unicode-objects must be encoded before hashing

当我尝试在Python 3.2.2中执行这段代码时:

import hashlib, sys
m = hashlib.md5()
hash = ""
hash_file = input("What is the file name in which the hash resides?  ")
wordlist = input("What is your wordlist?  (Enter the file name)  ")
try:
  hashdocument = open(hash_file, "r")
except IOError:
  print("Invalid file.")
  raw_input()
  sys.exit()
else:
  hash = hashdocument.readline()
  hash = hash.replace("\n", "")

try:
  wordlistfile = open(wordlist, "r")
except IOError:
  print("Invalid file.")
  raw_input()
  sys.exit()
else:
  pass
for line in wordlistfile:
  # Flush the buffer (this caused a massive problem when placed 
  # at the beginning of the script, because the buffer kept getting
  # overwritten, thus comparing incorrect hashes)
  m = hashlib.md5()
  line = line.replace("\n", "")
  m.update(line)
  word_hash = m.hexdigest()
  if word_hash == hash:
    print("Collision! The word corresponding to the given hash is", line)
    input()
    sys.exit()

print("The hash given does not correspond to any supplied word in the wordlist.")
input()
sys.exit()

当前回答

如果是单行字符串。用b或b把它包起来。

variable = b"This is a variable"

or

variable2 = B"This is also a variable"

其他回答

它可能正在从wordlistfile中寻找字符编码。

wordlistfile = open(wordlist,"r",encoding='utf-8')

或者,如果你在逐行工作:

line.encode('utf-8')

EDIT

根据下面的评论和这个答案。

我上面的回答假设所需的输出是来自wordlist文件的str。如果您习惯使用字节,那么您最好使用open(wordlist,“rb”)。但是重要的是要记住,如果你将hashfile与hexdigest的输出进行比较,那么你的hashfile不应该使用rb。Hashlib.md5 (value).hashdigest()输出一个不能与bytes对象直接比较的STR: 'abc' != b'abc'。(关于这个话题还有很多,但我没有时间)。

还应该注意到这句话:

line.replace("\n", "")

应该是

line.strip()

这对bytes和str都适用。但是如果你决定简单地转换为字节,那么你可以将行更改为:

line.replace(b"\n", b"")

错误已经告诉了你要做什么。MD5操作在字节上,所以你必须将Unicode字符串编码成字节,例如line.encode('utf-8')。

如果是单行字符串。用b或b把它包起来。

variable = b"This is a variable"

or

variable2 = B"This is also a variable"

编码这一行为我解决了这个问题。

m.update(line.encode('utf-8'))

存储密码(PY3):

import hashlib, os
password_salt = os.urandom(32).hex()
password = '12345'

hash = hashlib.sha512()
hash.update(('%s%s' % (password_salt, password)).encode('utf-8'))
password_hash = hash.hexdigest()