次のエラーが発生します:
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()
ベストアンサー1
おそらく からの文字エンコーディングを探しているのでしょうwordlistfile
。
wordlistfile = open(wordlist,"r",encoding='utf-8')
または、行ごとに作業している場合:
line.encode('utf-8')
編集
下記のコメントによるとこの答え。
上記の回答では、必要な出力がファイルstr
からの であると想定していますwordlist
。 での作業に慣れている場合はbytes
、 を使用する方がよいでしょう。ただし、 の出力と比較する場合は を使用しないことopen(wordlist, "rb")
を覚えておくことが重要です。は を出力しますが、これはバイト オブジェクトと直接比較することはできません: 。(このトピックには他にも多くの内容がありますが、今は時間がありません)。hashfile
rb
hexdigest
hashlib.md5(value).hashdigest()
str
'abc' != b'abc'
次の行にも注目すべきです:
line.replace("\n", "")
おそらく
line.strip()
これはバイトと str の両方で機能します。ただし、単に に変換することにした場合はbytes
、行を次のように変更できます。
line.replace(b"\n", b"")