415

このエラーがあります:

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()
4

10 に答える 10

408

からの文字エンコーディングを探している可能性がありwordlistfileます。

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

または、行単位で作業している場合:

line.encode('utf-8')

編集

以下のコメントとこの回答に従って

上記の私の答えは、目的の出力がファイルstrからのものであることを前提としていwordlistます。での作業に慣れている場合はbytes、 を使用することをお勧めしますopen(wordlist, "rb")。ただし、 の出力と比較する場合は使用しないhashfileでください。バイトオブジェクトと直接比較できない and を出力します: 。(このトピックには他にもたくさんありますが、私は時間 ATM を持っていません)。rbhexdigesthashlib.md5(value).hashdigest()str'abc' != b'abc'

また、次の行にも注意してください。

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

おそらくあるはずです

line.strip()

これは、バイトと str の両方で機能します。ただし、単純に に変換することにしたbytes場合は、行を次のように変更できます。

line.replace(b"\n", b"")
于 2011-09-28T15:10:20.107 に答える
41
import hashlib
string_to_hash = '123'
hash_object = hashlib.sha256(str(string_to_hash).encode('utf-8'))
print('Hash', hash_object.hexdigest())
于 2018-12-16T14:15:18.730 に答える
20

エラーは、あなたがしなければならないことをすでに示しています。bytesMD5 はバイト単位で動作するため、Unicode 文字列をにエンコードする必要がありますline.encode('utf-8')

于 2011-09-28T15:09:17.083 に答える
14

その答えをまず見てください。

これで、エラー メッセージは明確になりました。使用できるのはバイトのみであり、Python 文字列 (以前は Python < 3 で使用されていたもの)ではunicodeありません。ビットエンコーディング (コードページと呼ばれるもの)。utf-32utf-16utf-8

ワードリスト ファイルのバイトは、ファイルから読み取るときに Python 3 によって自動的に Unicode にデコードされます。私はあなたがすることをお勧めします:

m.update(line.encode(wordlistfile.encoding))

md5アルゴリズムにプッシュされたエンコードされたデータが、基になるファイルとまったく同じようにエンコードされるようにします。

于 2011-10-15T14:14:05.830 に答える
11

バイナリ モードでファイルを開くことができます。

import hashlib

with open(hash_file) as file:
    control_hash = file.readline().rstrip("\n")

wordlistfile = open(wordlist, "rb")
# ...
for line in wordlistfile:
    if hashlib.md5(line.rstrip(b'\n\r')).hexdigest() == control_hash:
       # collision
于 2014-03-25T19:36:49.680 に答える