Атака по словарю грубой силы Cesher Python Код не работает после 18-й смены - PullRequest
0 голосов
/ 29 января 2020

Это было сделано для грубого кесарева шифрования с использованием файла словаря из http://www.math.sjsu.edu/~foster/dictionary.txt. Он запускается через три функции, lang_lib (), которая превращает текст словаря в вызываемый объект, isEngli sh (), который проверяет процент фразы и, если хотя бы 60% ее совпадает с любыми словами в словаре он вернул бы значение True. Используя это, функция шифрования caeser проходит через все смены и проверяет их по английским sh словам. Он должен возвращать результат с наибольшим процентом, но он работает только в смены 1-18. Я не могу понять, почему это не работает.

def lang_lib():
    file = open('dictionary.txt', 'r')
    file_read = file.read()
    file_split = file_read.split()
    words = []
    for word in file_split:
        words.append(word)
    file.close()
    return words

dictionary = lang_lib()

def isEnglish(text):
    split_text = text.lower().split()
    counter = 0
    not_in_dict = []
    for word in split_text:
        if word in dictionary:
            counter += 1
        else:
            not_in_dict.append(word)

    length = len(split_text)
    text_percent = ((counter / length) * 100)
    #print(text_percent)
    if text_percent >= 60.0:
        return True
    else:
        return False

alphabet = "abcdefghijklmnopqrstuvwxyz0123456789!@#$%/."

def caeser(text): #Put in text, and it will spit out all possible values
    lower_text = text.lower()
    ciphertext = "" #stores current cipher value
    matches = [] #stores possible matches

    for i in range(len(alphabet)): #loops for the length of input alphabet
        for c in lower_text:
            if c in alphabet:
                num = alphabet.find(c)
                newnum = num - i
                if newnum >= len(alphabet):
                    newnum -= len(alphabet)
                elif newnum < 0:
                    newnum += len(alphabet)
                ciphertext = ciphertext + alphabet[newnum]
            else:
                ciphertext = ciphertext + c

            testing = isEnglish(ciphertext)
            for text in ciphertext:
                if testing == True and len(ciphertext) == len(lower_text):
                    matches.append(ciphertext)
                    return i, matches

        ciphertext = "" #clears ciphertext so it doesn't get cluttered

print(caeser('0x447 #0x$x 74w v0%5')) #shift of 19
print(caeser('zw336 @zw9w 63v uz#4')) #shift of 18

Спасибо, ребята.

Ответы [ 2 ]

0 голосов
/ 29 января 2020

Я обнаружил, что dictionary.txt не содержит 2 или 3 буквенных слова, поэтому он будет искажать длинные входные данные со многими из этих слов и возвращать False. Я добавил список общих слов, так что теперь все входы работают точно.

Если кто-нибудь захочет помочь мне сделать этот код более эффективным, я бы хотел несколько указателей. Я очень новичок в Python.

0 голосов
/ 29 января 2020

Эта часть имеет слишком большой отступ, как подсказывает @tripleee:

testing = isEnglish(ciphertext)
for text in ciphertext:
   if testing == True:
        matches.append(ciphertext)
        return i, matches

Также вам не нужно проверять длину, если у вас есть право на отступ и пусть предыдущий l oop завершен .. ..

...