Ответ 1
Вероятно, он ищет кодировку символов из wordlistfile
.
wordlistfile = open(wordlist,"r",encoding='utf-8')
Или, если вы работаете поэтапно:
line.encode('utf-8')
У меня есть эта ошибка:
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()
Вероятно, он ищет кодировку символов из wordlistfile
.
wordlistfile = open(wordlist,"r",encoding='utf-8')
Или, если вы работаете поэтапно:
line.encode('utf-8')
Вам нужно определить encoding format
как utf-8
,
Попробуйте этот простой способ,
В этом примере генерируется случайное число с использованием алгоритма SHA256:
>>> import hashlib
>>> hashlib.sha256(str(random.getrandbits(256)).encode('utf-8')).hexdigest()
'cd183a211ed2434eac4f31b317c573c50e6c24e3a28b82ddcb0bf8bedf387a9f'
Чтобы сохранить пароль (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()
Ошибка уже говорит о том, что вы должны делать. MD5 работает с байтами, поэтому вам нужно кодировать строку Unicode в bytes
, например. с line.encode('utf-8')
.
Пожалуйста, взгляните сначала на который отвечает.
Теперь сообщение об ошибке становится понятным: вы можете использовать только байты, а не строки Python (что было unicode
в Python < 3), поэтому вам нужно кодировать строки с предпочтительной кодировкой: utf-32
, utf-16
, utf-8
или даже одно из ограниченных 8-битных кодировок (что некоторые могли бы назвать кодовыми страницами).
Байты в вашем файле списка слов автоматически декодируются в Unicode Python 3 при чтении из файла. Я предлагаю вам:
m.update(line.encode(wordlistfile.encoding))
так что закодированные данные, помещенные в алгоритм md5, кодируются точно так же, как и основной файл.
Вы можете открыть файл в двоичном режиме:
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
import hashlib
string_to_hash = '123'
hash_object = hashlib.sha256(str(string_to_hash).encode('utf-8'))
print('Hash', hash_object.hexdigest())
кодирование этой строки исправило это для меня.
m.update(line.encode('utf-8'))
Эта программа является бесплатной и улучшенной версией вышеупомянутого взломщика MD5, который читает файл, содержащий список хэшированных паролей, и проверяет его на хеш-слово из английского словарного словаря. Надеюсь, это полезно.
Я загрузил английский словарь по следующей ссылке: https://github.com/dwyl/english-words
# md5cracker.py
# English Dictionary https://github.com/dwyl/english-words
import hashlib, sys
hash_file = 'exercise\hashed.txt'
wordlist = 'data_sets\english_dictionary\words.txt'
try:
hashdocument = open(hash_file,'r')
except IOError:
print('Invalid file.')
sys.exit()
else:
count = 0
for hash in hashdocument:
hash = hash.rstrip('\n')
print(hash)
i = 0
with open(wordlist,'r') as wordlistfile:
for word in wordlistfile:
m = hashlib.md5()
word = word.rstrip('\n')
m.update(word.encode('utf-8'))
word_hash = m.hexdigest()
if word_hash==hash:
print('The word, hash combination is ' + word + ',' + hash)
count += 1
break
i += 1
print('Itiration is ' + str(i))
if count == 0:
print('The hash given does not correspond to any supplied word in the wordlist.')
else:
print('Total passwords identified is: ' + str(count))
sys.exit()