def crack_substitution(ctext,pbprogress):
     stopper.config(state=tk.NORMAL)
     global stop
     stop = False
     pb.config(mode='indeterminate')
     pb.start()
     tested = 0
     maxkey = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
     maxscore = -99e9
     parentscore, parentkey = maxscore, maxkey[:]
     # keep going until we are killed by the user
     i = 0
     while True:
         i += 1
         random.shuffle(parentkey)
         deciphered = decrypt.substitution(ctext,parentkey)
         parentscore = fitness.score(deciphered)
         count = 0
         while count < 1000:
             pb.update()
             a = random.randint(0, 25)
             b = random.randint(0, 25)
             child = parentkey[:]
             # swap two characters in the child
             child[a], child[b] = child[b], child[a]
             deciphered = decrypt.substitution(ctext,child)
             score = fitness.score(deciphered)
             # if the child was better, replace the parent with it
             if score > parentscore:
                 parentscore = score
                 parentkey = child[:]
                 count = 0
             count = count + 1
             tested += 1
             keystested.config(text=str(tested))
             if stop == True: break
         # keep track of best score seen so far
         if parentscore > maxscore:
             maxscore, maxkey = parentscore, parentkey[:]
             bestfitness.config(text=str(round(maxscore)))
             current_keys = []
             for i in range(10):
                 current_keys.append(keys_top[i].cget('text'))
             current_keys = current_keys[:-1]
             for i in range(1,10):
                 keys_top[i].config(text=current_keys[i-1])
             keys_top[0].config(text="".join(maxkey)[:15])
             ss = decrypt.substitution(ctext,maxkey)
             cipher_output.delete('1.0', tk.END)
             cipher_output.insert(tk.INSERT, restore(ss))
             cipher_output.update()
         if stop == True: break
     stopper.config(state=tk.DISABLED)
def crack_substitution(ctext):

    key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    def score(key, ctext):
        points = fitness.score(decrypt.substitution(ctext, key))
        return points

    def shuffle(key):
        a = random.randint(0, len(key) - 1)
        b = random.randint(0, len(key) - 1)
        a_v = key[a]
        b_v = key[b]
        am = list(key)
        am[b] = a_v
        am[a] = b_v
        return "".join(am)

    points = -99e9

    max_points = points

    t = 1.0

    freezing = 0.9997

    while t > 0.0001:
        new_key = shuffle(key)

        p = score(new_key, ctext)
        if p > points:
            if p > max_points:
                max_points = p
                print("\nTYPE: SUBSTITUTION")
                print("TEMPERATURE:", t, "SCORE:", p)
                print("KEY", new_key)
                print(decrypt.substitution(
                    ctext,
                    new_key,
                ))
            key = new_key
            points = p

        else:
            if random.random() < t:
                points = p
                key = new_key
        t *= freezing
    return process_encryption.restore_punctuation(
        decrypt.substitution(ctext, key))
class main_page(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        # Ciphertext input box
        ttk.Label(self,text="Encrypted Text").grid(row=0,column=1,columnspan=10,pady=5)
        scrollbar = ttk.Scrollbar(self)
        scrollbar.grid(row=1,column=2,sticky=tk.NSEW)

        cipher_input = tk.Text(self, wrap=tk.WORD, yscrollcommand=scrollbar.set,height=5,width=80)
        cipher_input.grid(row=1,column=1,padx=(20,0))

        scrollbar.config(command=cipher_input.yview)

        def get_cipher():
            return re.sub('[^A-Za-z0-9]+', '', cipher_input.get('1.0', tk.END)).upper()

        # Text manipulation options
        def save_text():
            global text_orig
            text_orig = cipher_input.get('1.0', tk.END)
            global modified
        def reverse_word_lettering():
            #re.sub(r'([^\s\w]|_)+', '', origList)
            global modified
            if modified == False:
                save_text()
            text = cipher_input.get('1.0',tk.END).replace('\n','').replace('\r','').split(' ')
            reversed_text = []
            for word in text:
                reversed_text.append(word[::-1])
            cipher_input.delete('1.0',tk.END)
            reversed_text = " ".join(reversed_text)
            cipher_input.insert(tk.INSERT, reversed_text)
            modified = True
        def reverse_string():
            global modified
            if modified == False:
                save_text()
            text = cipher_input.get('1.0', tk.END).replace('\n', '').replace('\r', '')
            cipher_input.delete('1.0', tk.END)
            cipher_input.insert(tk.INSERT, text[::-1])
            modified = True
        def reset_string():
            global text_orig
            cipher_input.delete('1.0', tk.END)
            cipher_input.insert(tk.INSERT, text_orig)
        def clear():
            global text_orig
            text_orig = ""
            global modified
            modified = False
            cipher_input.delete('1.0', tk.END)

        # Text Manipulation Buttons
        manipulation_frame = ttk.Frame(self)
        ttk.Button(manipulation_frame,text="Reverse Full String",command=lambda: reverse_string()).grid(row=0,column=0)
        ttk.Button(manipulation_frame,text="Reverse Word Lettering",command=lambda: reverse_word_lettering()).grid(row=0,column=1,padx=2)
        ttk.Button(manipulation_frame,text="Reset Full String",command=lambda: reset_string()).grid(row=0,column=2,padx=(0,2))
        ttk.Button(manipulation_frame,text="Clear",command=lambda: clear()).grid(row=0,column=3,padx=(0,2))
        manipulation_frame.grid(row=2,column=1,sticky=tk.W,padx=(20,0),pady=5)


        # Frame enclosing statistics, graphs and decryption labelframes
        layer_frames = ttk.Frame(self)
        # Statistics Frame
        stats = ttk.LabelFrame(layer_frames,text="Statistics",width=200)

        ttk.Label(stats,text="Index of Coincidence",font="Helvetica 8").grid(row=0,column=0,sticky=tk.W)#
        ic = ttk.Label(stats,text="0.0000",font="Helvetica 8 bold")
        ic.grid(row=0,column=2,sticky=tk.E)

        ttk.Label(stats,text="Characters",font="Helvetica 8").grid(row=1,column=0,sticky=tk.W)
        charcount = ttk.Label(stats,text="0",font="Helvetica 8 bold")
        charcount.grid(row=1,column=2,sticky=tk.E)

        ttk.Label(stats,text="Key-length (Confidence)",font="Helvetica 8").grid(row=2,column=0,sticky=tk.W)
        periodic = ttk.Label(stats,text="0",font="Helvetica 8 bold")
        periodic.grid(row=2,column=1,sticky=tk.E)

        difference = ttk.Label(stats,text="(0.00%)",font="Helvetica 8 bold")
        difference.grid(row=2,column=2,sticky=tk.W)

        stats.grid(row=0,column=0,sticky=tk.NSEW,padx=(20,0),pady=5)
        stats.grid_propagate(False)



        # Live updating calculations
        def typing(event):

            text = re.sub('[^A-Za-z0-9]+', '', cipher_input.get('1.0', tk.END)).upper()

            char_count = len(text)
            char_string = str(char_count)
            charcount.config(text=char_string)

            ic_score = round(indice_coincidence(text),4)
            if len(str(ic_score)) != 6:
                ic_score = str(ic_score)
                while len(ic_score) != 6:
                    ic_score += "0"
            displayed_string = str(ic_score)
            ic.config(text = displayed_string)

            periodic_calc = period_ic()
            highest_ic_fig = periodic_calc.index(max(periodic_calc)) + 2
            highest_ic = max(periodic_calc)
            periodic_calc.remove(max(periodic_calc))
            next_ic = max(periodic_calc)
            diff = round(((highest_ic - next_ic)/next_ic)*100,2)
            periodic.config(text=str(highest_ic_fig))
            difference.config(text="(" + str(diff) + "%)")

        cipher_input.bind('<KeyRelease>',typing)

        # Periodic IC calculations
        def period_ic():
            xtext = get_cipher()
            average = []
            for j in range(2, 21):
                sequence = []
                for k in range(j):
                    text = list(xtext[k:])
                    n = j
                    output = []
                    i = 0
                    while i < len(text):
                        output.append(text[i])
                        i = i + int(n)
                    phrase = "".join(output)
                    sequence.append(indice_coincidence(phrase))  # Calculate each index of coincidence
                average.append(sum(sequence) / len(sequence))
            return average

        # Graphs frame
        graphs = ttk.LabelFrame(layer_frames,text="Graphs")

        ttk.Button(graphs,text="Periodic IC",command=lambda: icgraph(get_cipher()),width=20).grid(row=0,column=0,sticky=tk.W)
        ttk.Button(graphs,text="Monogram Frequency",command=lambda: freqanalysis(get_cipher()),width=20).grid(row=1,column=0,pady=5,sticky=tk.W)

        graphs.grid(row=0,column=1,sticky=tk.NSEW,padx=10,pady=5)

        layer_frames.grid(row=3,column=1,columnspan=10,sticky=tk.EW)

        #Decrypted Text output
        ttk.Label(self,text="Decrypted Text").grid(row=4,column=1,columnspan=10,pady=5)
        scrollbar2 = ttk.Scrollbar(self)
        scrollbar2.grid(row=5,column=2,sticky=tk.NSEW)

        cipher_output = tk.Text(self, wrap=tk.WORD, yscrollcommand=scrollbar2.set,height=5,width=80)
        cipher_output.grid(row=5,column=1,padx=(20,0))

        scrollbar2.config(command=cipher_output.yview)
        pbprogress = tk.IntVar(self)
        pb = ttk.Progressbar(self, orient="horizontal",length=644, variable=pbprogress, mode="determinate")
        pb.grid(row=6,column=1,pady=5,padx=(20,0),sticky=tk.W)

        # Statistics after decryption
        final_layer = tk.Frame(self)

        decryptionstats = ttk.LabelFrame(final_layer,text="Results",width=134)
        decryptionstats.grid(row=0,column=3,sticky=tk.NSEW,padx=5)
        decryptionstats.grid_propagate(False)
        ttk.Label(decryptionstats,text="Keys Tested",font="Helvetica 9 bold",anchor=tk.CENTER).grid(row=0,column=0,sticky="ew",padx=5,pady=(2.5,0))
        keystested = ttk.Label(decryptionstats,text="0",font="Helvetica 12",anchor=tk.CENTER)
        keystested.grid(row=1,column=0,sticky="ew",padx=5,pady=5)
        ttk.Label(decryptionstats,text="Best Fitness",font="Helvetica 9 bold",anchor=tk.CENTER).grid(row=2,column=0,sticky="ew",padx=5,pady=(2.5,0))
        bestfitness = ttk.Label(decryptionstats,text="0",font="Helvetica 12",anchor=tk.CENTER)
        bestfitness.grid(row=3,column=0,sticky="ew",padx=5,pady=5)
        ttk.Label(decryptionstats,text="Best Key",font="Helvetica 9 bold",anchor=tk.CENTER).grid(row=4,column=0,sticky="ew",padx=5,pady=(2.5,0))
        bestkey = ttk.Label(decryptionstats,text="-",font="Helvetica 9",anchor=tk.CENTER)
        bestkey.grid(row=5,column=0,sticky="ew",padx=5,pady=5)

        top_keys = ttk.LabelFrame(final_layer,text="Top Keys",height=250,width=180)
        keys_top = {}
        for i in range(10):
            ttk.Label(top_keys,text=str(i+1) + ".").grid(row=i,column=0)
            keys_top[i] = ttk.Label(top_keys,text="",font="Courier 10")
            keys_top[i].grid(row=i,column=1,sticky=tk.NW)

        top_keys.grid(row=0,column=0,sticky=tk.NW,padx=5)
        top_keys.grid_propagate(False)

        # Decryption options frame
        decryptionconfig = ttk.LabelFrame(final_layer,text="Decryption",width=300,height=50)
        decryptionconfig.grid(row=0,column=2,sticky=tk.NSEW,padx=5)
        decryptionconfig.grid_propagate(False)
        selected_cipher = tk.StringVar(decryptionconfig)
        ttk.Label(decryptionconfig,text="Cipher Type",font="Helvetica 9 bold").grid(row=1,column=0,sticky=tk.W,padx=5,pady=(5,0))
        cipher_list = ttk.OptionMenu(decryptionconfig, selected_cipher, "Vigenere", "Vigenere", "Beaufort", "Caesar","Polybius")
        cipher_list.grid(row=1,column=1,padx=5,sticky="ew")
        cipher_list.grid_propagate(False)

        def set_cipherselection(v,cipher_list):
            if v.get() == 1:
                cipher_list.grid_forget()
                # Edit this one for effect
                cipher_list = ttk.OptionMenu(decryptionconfig,selected_cipher,"Vigenere","Vigenere","Beaufort","Caesar","Substitution","Columnar","Polybius","Hill (2x2)","Hill (3x3)")
                cipher_list.grid(row=1, column=1, padx=5, sticky="ew")
                cipher_list.grid_propagate(False)
            else:
                cipher_list.grid_forget()
                cipher_list = ttk.OptionMenu(decryptionconfig,selected_cipher,"Vigenere/Affine","Vigenere/Affine","Vigenere/Scytale")
                cipher_list.grid(row=1, column=1, padx=5, sticky="ew")
                cipher_list.grid_propagate(False)

        v = tk.IntVar(decryptionconfig)
        ttk.Label(decryptionconfig,text="Cipher Layers",font="Helvetica 9 bold").grid(row=0,column=0,sticky=tk.W,padx=5)
        radio1 = ttk.Radiobutton(decryptionconfig,text="Single",command=lambda: set_cipherselection(v,cipher_list),variable=v,value=1,state="normal")
        radio1.grid(row=0,column=1,padx=(5,0),sticky=tk.W)
        radio1.invoke()
        ttk.Radiobutton(decryptionconfig, text="Double",command=lambda: set_cipherselection(v,cipher_list), variable=v, value=2).grid(row=0, column=1,sticky=tk.W,pady=5,padx=(70,0))



        selected_period = tk.StringVar(decryptionconfig)

        key = ttk.Entry(decryptionconfig,text="key")
        key.grid(row=2,column=1,padx=5,sticky="ew")
        ttk.Label(decryptionconfig,text="Key (Optional)",font="Helvetica 9 bold").grid(row=2,column=0,sticky=tk.W,padx=5,pady=10)



        ttk.Label(decryptionconfig,text="Period (Optional)",font="Helvetica 9 bold").grid(row=3,column=0,sticky=tk.W,padx=5)
        period_selection = ttk.OptionMenu(decryptionconfig,selected_period,"-","-","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15")
        period_selection.grid(row=3,column=1,sticky="ew",padx=5)

        #Solve Button
        stop = False
        ttk.Button(decryptionconfig,text="SOLVE",command=lambda: solve_cipher(selected_cipher.get(),pbprogress)).grid(row=4,column=0,columnspan=2,padx=5,pady=(10,0),sticky=tk.NSEW)
        stopper = ttk.Button(decryptionconfig, text="STOP",command=lambda: stop_cipher(pbprogress),state=tk.DISABLED)
        stopper.grid(row=5, column=0, columnspan=2,padx=5, pady=5,sticky=tk.NSEW)
        def stop_cipher(pbprogress):
            pb.stop()
            global stop
            stop = True
            pb.config(mode='determinate')
            pbprogress.set(0)
            pb.update()

        final_layer.grid(row=7,column=1,sticky=tk.NW,pady=5,padx=(20,0))

        def restore(text):
            text = list(text)
            for i in range(len(nonalphabetic)):
                text.insert(nonalphabetic[i][1], nonalphabetic[i][0])
            for i in range(len(case)):
                text[case[i]] = text[case[i]].lower()
            return "".join(text)

        def key_updater(top10keys):
            top10keys = top10keys[-10:]
            for i in range(10):
                keys_top[9 - i].config(text=top10keys[i])

        # Decryption button action
        def solve_cipher(cipher,pbprogress):
            for i in range(10):
                keys_top[i].config(text="")
            bestkey.config(text="-")
            bestfitness.config(text="0")
            keystested.config(text="0")
            pbprogress.set(0)
            pb.update()

            #Save non-alphabetic characters
            global nonalphabetic
            nonalphabetic = []
            raw_text = cipher_input.get('1.0',tk.END)
            alphabet = list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
            global case
            case = []
            for i in range(len(raw_text)):
                if raw_text[i] not in alphabet:
                    nonalphabetic.append([raw_text[i],i])
                else:
                    if raw_text[i].islower() is True:
                        case.append(i)

            if cipher == "*Select Cipher":
                messagebox.showerror("Decryption","No cipher selected")
            elif cipher == "Vigenere":
                if key.get() == "":
                    crack_vigenere(get_cipher(),pbprogress)
                else:
                    cipher_output.delete('1.0',tk.END)
                    cipher_output.insert(tk.INSERT,restore(decrypt.vigenere(process_encryption.process2(get_cipher()),key.get().upper())))
                    cipher_output.update()
                    pbprogress.set(100)
                    pb.update()
            elif cipher == "Beaufort":
                if key.get() == "":
                    crack_beaufort(get_cipher(),pbprogress)
                else:
                    cipher_output.delete('1.0',tk.END)
                    cipher_output.insert(tk.INSERT,restore(decrypt.vigenere(decrypt.atbash(process_encryption.process2(get_cipher())),decrypt.atbash(key.get().upper()))))
                    cipher_output.update()
                    pbprogress.set(100)
                    pb.update()
            elif cipher == "Caesar":
                if key.get() == "":
                    crack_caesar(process_encryption.process2(get_cipher()),pbprogress)
                else:
                    cipher_output.delete('1.0',tk.END)
                    cipher_output.insert(tk.INSERT,restore(decrypt.caesar(process_encryption.process2(get_cipher()),key.get().upper())))
                    cipher_output.update()
                    pbprogress.set(100)
                    pb.update()
            elif cipher == "Columnar":
                if key.get() == "":
                    crack_coltrans(process_encryption.process2(get_cipher()),pbprogress)
                else:
                    cipher_output.delete('1.0',tk.END)
                    cipher_output.insert(tk.INSERT,restore(pycipher.ColTrans(key.get().upper()).decipher(process_encryption.process2(get_cipher()))))
                    cipher_output.update()
                    pbprogress.set(100)
                    pb.update()
            elif cipher == "Polybius":
                if key.get() == "":
                    crack_polybius(process_encryption.process2(get_cipher()),pbprogress)
            elif cipher == "Hill (2x2)":
                if key.get() == "":
                    crack_2x2hill(get_cipher(),pbprogress)
                else:
                    cipher_output.delete('1.0',tk.END)
                    cipher_output.insert(tk.INSERT,restore(decrypt.hill2x2(get_cipher(),key.get())))
                    cipher_output.update()
                    pbprogress.set(100)
                    pb.update()
            elif cipher == "Hill (3x3)":
                if key.get() == "":
                    crack_3x3hill(get_cipher(),pbprogress)
                else:
                    cipher_output.delete('1.0',tk.END)
                    cipher_output.insert(tk.INSERT,restore(decrypt.hill3x3(get_cipher(),key.get())))
                    cipher_output.update()
                    pbprogress.set(100)
                    pb.update()
            elif cipher == "Substitution":
                if key.get() == "":
                    crack_substitution(get_cipher(),pbprogress)
                else:
                    alpha = list("ABCDEFGHIKLMNOPQRSTUVWXYZ")
                    key_in_use = key.get().upper()
                    if len(key_in_use) != 26:
                        for letter in key_in_use:
                            alpha.remove(letter)
                    key_in_use = key_in_use + "".join(alpha)
                    print(key_in_use)
                    cipher_output.delete('1.0',tk.END)
                    cipher_output.insert(tk.INSERT,restore(decrypt.substitution(get_cipher(),key_in_use)))
                    cipher_output.update()
                    pbprogress.set(100)
                    pb.update()
            elif cipher == "Vigenere/Affine":
                if key.get() == "" or selected_period.get() == "-":
                    crack_vigenere_affine(get_cipher(),pbprogress)
                else:
                    cipher_output.delete('1.0',tk.END)
                    cipher_output.insert(tk.INSERT,restore(decrypt.vigenereaffine(get_cipher(),key.get().upper(),int(selected_period.get()))))
                    cipher_output.update()
                    pbprogress.set(100)
                    pb.update()
            elif cipher == "Vigenere/Scytale":
                if key.get() == "" and selected_period.get() == "-":
                    crack_vigenere_scytale(get_cipher(),pbprogress)
                elif selected_period.get() != "-":
                    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                    crack_vigenere(pycipher.ColTrans(alphabet[0:int(selected_period.get())]).decipher(get_cipher()),pbprogress)
                elif key.get() != "":
                    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                    bestsofar = -99e9
                    count = 0
                    for scytale in range(1, 11):
                        cipher2 = decrypt.vigenere(pycipher.ColTrans(alphabet[0:scytale + 1]).decipher(get_cipher()),key.get().upper())
                        print(cipher2)
                        chill = fitness.score(cipher2)
                        if chill > bestsofar:
                            bestsofar = chill
                            cipher_output.delete('1.0', tk.END)
                            cipher_output.insert(tk.INSERT, restore(cipher2))
                            cipher_output.update()
                        count += 1
                        keystested.config(text=str(count))
                        pbprogress.set(round((count/10)*100))
                        pb.update()

                else:
                    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                    text = pycipher.ColTrans(alphabet[0:int(selected_period.get())]).decipher(get_cipher())
                    text = decrypt.vigenere(text,key.get().upper())
                    cipher_output.delete('1.0',tk.END)
                    cipher_output.insert(tk.INSERT,restore(text))
                    cipher_output.update()
                    pbprogress.set(100)
                    pb.update()

            bestkey.config(text=keys_top[0].cget('text'))
Exemple #4
0
def solve_cipher(cipher, pbprogress):
    for i in range(10):
        keys_top[i].config(text="")
    bestkey.config(text="-")
    bestfitness.config(text="0")
    keystested.config(text="0")
    pbprogress.set(0)
    pb.update()

    # ctext_class = Cipher(cipher_input.get('1.0',tk.END))
    global global_cipher
    global_cipher = Cipher()
    ctext_class = global_cipher
    ctext_class.store()

    if cipher == "*Select Cipher":
        messagebox.showerror("Decryption", "No cipher selected")
    elif cipher == "Vigenere":
        if key.get() == "":
            crack_vigenere(ctext_class)
        else:
            cipher_output.delete('1.0', tk.END)
            cipher_output.insert(
                tk.INSERT,
                ctext_class.restore(
                    decrypt.vigenere(ctext_class.clean(),
                                     key.get().upper())))
            cipher_output.update()
            pbprogress.set(100)
            pb.update()
    elif cipher == "Beaufort":
        if key.get() == "":
            crack_beaufort(ctext_class, pbprogress)
        else:
            cipher_output.delete('1.0', tk.END)
            cipher_output.insert(
                tk.INSERT,
                ctext_class.restore(
                    decrypt.vigenere(decrypt.atbash(ctext_class.clean()),
                                     decrypt.atbash(key.get().upper()))))
            cipher_output.update()
            pbprogress.set(100)
            pb.update()
    elif cipher == "Caesar":
        if key.get() == "":
            crack_caesar(ctext_class, pbprogress)
        else:
            cipher_output.delete('1.0', tk.END)
            cipher_output.insert(
                tk.INSERT,
                ctext_class.restore(
                    decrypt.caesar(ctext_class.clean(),
                                   key.get().upper())))
            cipher_output.update()
            pbprogress.set(100)
            pb.update()
    elif cipher == "Columnar":
        if key.get() == "":
            crack_coltrans(ctext_class, pbprogress)
        else:
            cipher_output.delete('1.0', tk.END)
            cipher_output.insert(
                tk.INSERT,
                ctext_class.restore(
                    pycipher.ColTrans(key.get().upper()).decipher(
                        ctext_class.clean())))
            cipher_output.update()
            pbprogress.set(100)
            pb.update()
    elif cipher == "Polybius":
        if key.get() == "":
            crack_polybius(ctext_class, pbprogress)
    elif cipher == "Hill (2x2)":
        if key.get() == "":
            crack_2x2hill(ctext_class, pbprogress)
        else:
            cipher_output.delete('1.0', tk.END)
            cipher_output.insert(
                tk.INSERT,
                ctext_class.restore(
                    decrypt.hill2x2(ctext_class.clean(), key.get())))
            cipher_output.update()
            pbprogress.set(100)
            pb.update()
    elif cipher == "Hill (3x3)":
        if key.get() == "":
            crack_3x3hill(ctext_class, pbprogress)
        else:
            cipher_output.delete('1.0', tk.END)
            cipher_output.insert(
                tk.INSERT,
                ctext_class.restore(
                    decrypt.hill3x3(ctext_class.clean(), key.get())))
            cipher_output.update()
            pbprogress.set(100)
            pb.update()
    elif cipher == "Substitution":
        if key.get() == "":
            crack_substitution(ctext_class, pbprogress)
        else:
            alpha = list("ABCDEFGHIKLMNOPQRSTUVWXYZ")
            key_in_use = key.get().upper()
            if len(key_in_use) != 26:
                for letter in key_in_use:
                    alpha.remove(letter)
            key_in_use = key_in_use + "".join(alpha)
            print(key_in_use)
            cipher_output.delete('1.0', tk.END)
            cipher_output.insert(
                tk.INSERT,
                ctext_class.restore(
                    decrypt.substitution(ctext_class.clean(), key_in_use)))
            cipher_output.update()
            pbprogress.set(100)
            pb.update()
    elif cipher == "Vigenere/Affine":
        if key.get() == "" or selected_period.get() == "-":
            crack_vigenere_affine(ctext_class, pbprogress)
        else:
            cipher_output.delete('1.0', tk.END)
            cipher_output.insert(
                tk.INSERT,
                ctext_class.restore(
                    decrypt.vigenereaffine(ctext_class.clean(),
                                           key.get().upper(),
                                           int(selected_period.get()))))
            cipher_output.update()
            pbprogress.set(100)
            pb.update()
    elif cipher == "Vigenere/Scytale":
        if key.get() == "" and selected_period.get() == "-":
            crack_vigenere_scytale(ctext_class, pbprogress)
        elif selected_period.get() != "-":
            alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
            crack_vigenere(
                pycipher.ColTrans(
                    alphabet[0:int(selected_period.get())]).decipher(
                        ctext_class.clean()), pbprogress)
        elif key.get() != "":
            alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
            bestsofar = -99e9
            count = 0
            for scytale in range(1, 11):
                cipher2 = decrypt.vigenere(
                    pycipher.ColTrans(alphabet[0:scytale + 1]).decipher(
                        ctext_class.clean()),
                    key.get().upper())
                print(cipher2)
                chill = fitness.score(cipher2)
                if chill > bestsofar:
                    bestsofar = chill
                    cipher_output.delete('1.0', tk.END)
                    cipher_output.insert(tk.INSERT,
                                         ctext_class.restore(cipher2))
                    cipher_output.update()
                count += 1
                keystested.config(text=str(count))
                pbprogress.set(round((count / 10) * 100))
                pb.update()

        else:
            alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
            text = pycipher.ColTrans(
                alphabet[0:int(selected_period.get())]).decipher(
                    ctext_class.clean())
            text = decrypt.vigenere(text, key.get().upper())
            cipher_output.delete('1.0', tk.END)
            cipher_output.insert(tk.INSERT, ctext_class.restore(text))
            cipher_output.update()
            pbprogress.set(100)
            pb.update()

    bestkey.config(text=keys_top[0].cget('text'))
Exemple #5
0
def crack_substitution(ctext, pbprogress):

    ctext_class = ctext
    ctext = ctext_class.clean()
    stopper.config(state=tk.NORMAL)
    global stop
    stop = False
    pb.config(mode='indeterminate')
    pb.start()

    alleles = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
    chromosome = ["" for x in range(10)]

    for i in range(10):
        chromosome[i] = alleles[:]
        random.shuffle(chromosome[i])

    while True:
        #Generate Chromosomes

        scores = []
        for i in range(10):
            print("")
            print(decrypt.substitution(ctext, chromosome[i]))
            scores.append(
                fitness.score(decrypt.substitution(ctext, chromosome[i])))

        parents = []
        for i in range(6):
            best = scores.index(max(scores))
            scores.remove(max(scores))
            parents.append(chromosome[best])

        #Position-Based-Crossover (PBX)
        for i in range(0, 5, 2):
            y = []
            child = ["" for j in range(26)]

            for k in range(12):
                k = random.randint(0, 25)
                child[k] = parents[i][k][:]

            for l in range(26):
                if parents[i + 1][l] not in child:
                    y.append(parents[i + 1][l])

            for m in range(26):
                if len(child[m]) == 26:
                    break
                if child[m] == "":
                    child[m] = y[0][:]
                    y.remove(child[m])

            chromosome.append(child)

        mutation_top_six = random.randint(0, 5)
        a = random.randint(0, 25)
        b = random.randint(0, 25)
        pos = chromosome.index(parents[mutation_top_six])
        chromosome.append(chromosome[pos][:])
        chromosome[-1][a], chromosome[-1][b] = chromosome[-1][b], chromosome[
            -1][a]

        pos = scores.index(min(scores))
        a = random.randint(0, 25)
        b = random.randint(0, 25)
        chromosome.append(chromosome[pos][:])
        chromosome[-1][a], chromosome[-1][b] = chromosome[-1][b], chromosome[
            -1][a]

        scores = []
        for i in range(15):
            scores.append(
                fitness.score(decrypt.substitution(ctext, chromosome[i])))

        best_chromosome = []
        for i in range(10):
            best = scores.index(max(scores))
            scores.remove(max(scores))
            best_chromosome.append(chromosome[best])

        chromosome = best_chromosome[:]

        if stop == True:
            break
 def score(key, ctext):
     points = fitness.score(decrypt.substitution(ctext, key))
     return points
Exemple #7
0
alleles = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")

# Random initial generation
chromosome = []
for i in range(NUM_CHROMOSOMES):
    chromosome.append(alleles[:])
    random.shuffle(chromosome[i])

generation = 1
previous = 0
while True:

    # Score the new generation
    scores = []
    for i in range(NUM_CHROMOSOMES):
        scores.append(fitness.score(decrypt.substitution(ctext,
                                                         chromosome[i])))

    scores_original = scores[:]

    # Select NUM_TOP_CHROMOSOMES for breeding
    parents = []
    for i in range(NUM_TOP_CHROMOSOMES):
        best = scores.index(max(scores))
        scores.remove(max(scores))
        parents.append(chromosome[best])

    # Position-Based-Crossover (PBX) of top chromosomes
    for i in range(0, NUM_TOP_CHROMOSOMES - 1, 2):
        y = []
        child = ["" for j in range(26)]