Я работаю над некоторым кодом для задания, которое должно взломать zip-файл. Мне было предоставлено первое слово пароля, и я знаю, что в нем есть еще 3 символа алфавита, включая прописные и строчные буквы.
Я могу напечатать каждую из этих комбинаций, но, похоже, не могу найти пароль. Может ли кто-нибудь взглянуть на мой код и посмотреть, не найдете ли вы ошибку или что-то в этом роде?
import zipfile
import itertools
import time
# Function for extracting zip files to test if the password works!
def extractFile(zip_file, password):
try:
zip_file.extractall(pwd=password)
return True
except KeyboardInterrupt:
exit(0)
except Exception:
pass
# Main code starts here...
# The file name of the zip file.
zipfilename = 'planz.zip'
# The first part of the password. We know this for sure!
first_half_password = 'Super'
# We don't know what characters they add afterwards...
# This is case sensitive!
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
zip_file = zipfile.ZipFile(zipfilename)
# We know they always have 3 characters after Super...
# For every possible combination of 3 letters from alphabet...
for c in itertools.product(alphabet, repeat=3):
# Slowing it down on purpose to make it work better with the web terminal
# Remove at your peril
time.sleep(0.009)
# Add the three letters to the first half of the password.
password = first_half_password+''.join(c)
# Try to extract the file.
print ("Trying: %s" % password)
# If the file was extracted, you found the right password.
if extractFile(zip_file, password):
print ('*' * 20)
print ('Password found: %s' % password)
print ('Files extracted...')
exit(0)
# If no password was found by the end, let us know!
print ('Password not found.')
Я ожидаю, что программа найдет пароль, который должен быть Super + еще 3 символа алфавита.
Также я бы посоветовал вам создать zip-файл с паролем Superaaa
, чтобы протестировать свой код. Это будет первый пароль, который попробует ваш код. Вы можете просто добавить разрыв в конце цикла for
, чтобы вам не приходилось ждать всех перестановок.
zip_file.extractall(pwd=password)
ожидает пароль в виде байтов, а не строки. Таким образом, поскольку в качестве пароля передается строка, всегда срабатывает блок try/except внутри extractFile
, поэтому пароль никогда не будет найден. Я обновил ваш код, чтобы включить преобразование байтов из строки для пароля:
import zipfile
import itertools
import time
# Function for extracting zip files to test if the password works!
def extractFile(zip_file, password):
try:
zip_file.extractall(pwd=password)
return True
except KeyboardInterrupt:
exit(0)
except Exception:
pass
# Main code starts here...
# The file name of the zip file.
zipfilename = 'test_archive.zip'
# The first part of the password. We know this for sure!
first_half_password = 'Super'
# We don't know what characters they add afterwards...
# This is case sensitive!
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
zip_file = zipfile.ZipFile(zipfilename)
# We know they always have 3 characters after Super...
# For every possible combination of 3 letters from alphabet...
for c in itertools.product(alphabet, repeat=3):
# Slowing it down on purpose to make it work better with the web terminal
# Remove at your peril
time.sleep(0.009)
# Add the three letters to the first half of the password.
password = first_half_password+''.join(c)
# Try to extract the file.
print ("Trying: %s" % password)
# If the file was extracted, you found the right password.
if extractFile(zip_file, str.encode(password)):
print ('*' * 20)
print ('Password found: %s' % password)
print ('Files extracted...')
exit(0)
# If no password was found by the end, let us know!
print ('Password not found.')
Это достигается с помощью встроенного метода str.encode
.
Проверьте, какое исключение возникает при попытке открыть zip-файл. Например. возможно, файл не найден, а пароль неверный.