def crack_coltrans(ctext,pbprogress):

            alphabet = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
            max_score = -99 * (10 ** 9)
            count = 0
            top10keys = ["" for x in range(10)]
            for i in range(2, 8):
                current_alphabet = alphabet[:i]
                current_alphabet = "".join(current_alphabet)
                perms = [''.join(p) for p in permutations(current_alphabet)]
                for j in range(len(perms)):
                    deciphered = pycipher.ColTrans(perms[j]).decipher(ctext)
                    score = fitness.score(deciphered)
                    if score > max_score:
                        top10keys.append(perms[j])
                        key_updater(top10keys)
                        bestfitness.config(text=str(round(score)))
                        max_score = score
                        cipher_output.delete('1.0', tk.END)
                        cipher_output.insert(tk.INSERT, restore(deciphered))
                        cipher_output.update()
                    count += 1
                    pbprogress.set(round((count/5912)*100))
                    pb.update()
                    keystested.config(text=str(count))
Пример #2
0
def crack_vigenere_scytale(ctext, pbprogress):
    ctext_class = ctext
    ctext = ctext_class.clean()
    stopper.config(state=tk.NORMAL)
    global stop
    stop = False
    pb.config(mode='indeterminate')
    pb.start()
    top10keys = ["" for x in range(10)]
    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    best_overall = -99e9
    best_scytale = -99e9
    count = 0
    for scytale in range(1, 11):
        cipher = pycipher.ColTrans(alphabet[0:scytale + 1]).decipher(ctext)
        for keylength in range(1, 16):  # Set to 16 down from 21 for efficiency
            parentkey = "A" * keylength
            parentscore = fitness.score(decrypt.vigenere(cipher, parentkey))
            parentkey = list(parentkey)
            best_starter_score = parentscore
            best_starter = "".join(parentkey)
            for i in range(keylength):
                for letter in alphabet:
                    parentkey = list(parentkey)
                    child = parentkey
                    child[i] = letter
                    child = "".join(child)
                    childscore = fitness.score(decrypt.vigenere(cipher, child))
                    if childscore > best_starter_score:
                        best_starter_score = childscore
                        best_starter = child
                    if childscore > best_overall:
                        best_overall = childscore
                        best_key = child
                    pb.update()
                parentkey = best_starter
                count += 1
                keystested.config(text=str(count))
                if stop == True: break
            if stop == True: break
        if stop == True: break

        current_scytale = fitness.score(decrypt.vigenere(cipher, best_key))
        if current_scytale > best_scytale:
            top10keys.append(best_key)
            key_updater(top10keys)
            bestfitness.config(text=str(round(current_scytale)))
            best_scytale = current_scytale
            cipher_output.delete('1.0', tk.END)
            cipher_output.insert(
                tk.INSERT,
                ctext_class.restore(decrypt.vigenere(cipher, best_key)))
            cipher_output.update()
    stopper.config(state=tk.DISABLED)
    pb.stop()
    pb.config(mode='determinate')
    pb.update()
Пример #3
0
def crack_coltrans(ctext):

    alphabet = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
    max_score = -99 * (10**9)
    for i in range(2, 8):
        current_alphabet = alphabet[:i]
        current_alphabet = "".join(current_alphabet)
        perms = [''.join(p) for p in permutations(current_alphabet)]
        for j in range(len(perms)):
            deciphered = pycipher.ColTrans(perms[j]).decipher(ctext)
            score = fitness.score(deciphered)
            if score > max_score:
                max_score = score
                bestkey = perms[j]
                print("\nTYPE: COLUMNAR TRANSPOSITION")
                print("KEY: " + str(bestkey))
                print(deciphered)
    return pycipher.ColTrans(bestkey).decipher(ctext)
Пример #4
0
def crack_vigenere_scytale(ctext):

    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    best_overall = -99e9
    best_scytale = -99e9

    for scytale in range(1, 11):
        cipher = pycipher.ColTrans(alphabet[0:scytale + 1]).decipher(ctext)
        for keylength in range(1, 21):
            parentkey = "A" * keylength
            parentscore = fitness.score(decrypt.vigenere(cipher, parentkey))
            parentkey = list(parentkey)
            best_starter_score = parentscore
            best_starter = "".join(parentkey)
            for i in range(keylength):
                for letter in alphabet:
                    parentkey = list(parentkey)
                    child = parentkey
                    child[i] = letter
                    child = "".join(child)
                    childscore = fitness.score(decrypt.vigenere(cipher, child))
                    if childscore > best_starter_score:
                        best_starter_score = childscore
                        best_starter = child
                    if childscore > best_overall:
                        best_overall = childscore
                        best_key = child
                parentkey = best_starter

        current_scytale = fitness.score(decrypt.vigenere(cipher, best_key))
        if current_scytale > best_scytale:
            best_scytale = current_scytale
            scytalenum = scytale
            print("\nTYPE: VIGENERE + SCYTALE")
            print("SCYTALE WIDTH: ", str(scytale + 1))
            print("KEY:", str(best_key))
            print(decrypt.vigenere(cipher, best_key))
    return decrypt.vigenere(
        pycipher.ColTrans(alphabet[0:scytalenum + 1]).decipher(ctext),
        best_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'))
Пример #6
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'))
Пример #7
0
def columnar_transpose_analysis(e_string):
	digraph_lengths = cipher_heuristics.digraph_key_lengths(e_string)
	possible_key_freq = cipher_heuristics.length_frequency(digraph_lengths)
	print '\n' + '*' * 50 + '\n'
	print("Possible Transpose Key Lengths: ")
	print(digraph_lengths)

	#create columnar transpose key table to display
	key_freq_str = create_ct_key_freq_str(possible_key_freq)
	print key_freq_str

	# open dictionary file for infer_spaces
	# Build a cost dictionary, assuming Zipf's law and cost = -math.log(probability).
	with open('linux_dict.txt') as f:
		words = f.read().split()
	word_cost = dict((k, log((i + 1) * log(len(words)))) for i, k in enumerate(words))
	max_word = max(len(x) for x in words)
	# ------------------------------------------------------------------------------

	#set up loop to try different keys during for decryption
	key_len = -1
	#do not accept any keys out of the range 10
	while key_len > 10 or key_len < 0:
		key_len = int(raw_input("\nWhat length of key would you like to try?(exit with 0): "))
	#exit the columnar transpose decryption on 0
	while key_len != 0:

		#Create a string from 1 to selected key_len ie key_len = 7, '1234567'
		print('\nComputing key permutations...')
		key_string = ''
		for i in range(1, key_len + 1):
			key_string += str(i)

		#create a permutation list of all the possible permutations of the key
		#to try in decryption
		perm_list = list("".join(string) for string in itertools.permutations(key_string))
		perm_list = list(set(perm_list))


		possible_decryptions = [] #keeps track of successful/possible decryptions to display to user

		#attempt to find solutions with the selected key length
		with open('solutions.txt', 'w') as f:
			print("Decrypting plaintext...")
			#try each permutation of the key
			for permutation in perm_list:
				#decrypt using current key using picipher library
				plaintext = pycipher.ColTrans(permutation).decipher(e_string).lower()
				#use infer_spaces to try and find words in a non delimeter string
				word_list = infer_spaces.find_words(plaintext, word_cost, max_word, words)
				#check to see if the word_list returned was a vaild/possible solution
				#if it is write the word and key to the solutions.txt and possible_decryptions
				#otherwise ignore the solution
				if valid_list(word_list.split(" ")):
					f.write('Key is: ' + permutation + ' Plaintext: ' + word_list + '\n')
					possible_decryptions.append(word_list)

		#display possible decryptions
		print("\nPossible Decryptions: ")
		list_number = 1 #formatting/presentation purposes
		for string in possible_decryptions:
			print str(list_number) + '. ' + string
			list_number += 1
		print '\n' + '*' * 50 + '\n'

		#ask the user again in case no solutions were found, and if solutions were found, can exit on entering 0
		print "Possible Transpose Key Lengths:\n" + key_freq_str
		key_len = int(raw_input("\nWhat length of key would you like to try?(exit with 0): "))
		while key_len > 10 or key_len < 0:
			key_len = int(raw_input("\nWhat length of key would you like to try?(exit with 0): "))