I am creating a simple program with a GUI to encrypt/decrypt text using different ciphers. I tried to make it so that it would be easy to add new ciphers.
This is my code:
import tkinter as tk ALPHABET = "abcdefghijklmnopqrstuvwxyz" class Cipher: # encode_fun and decode_fun should take in args (key, message). def __init__(self, encode_fun, decode_fun): self.encode_fun = encode_fun self.decode_fun = decode_fun self.output = None def encode(self, key, message): try: self.output.delete(0, "end") self.output.insert(0, self.encode_fun(key, message)) except: return def decode(self, key, message): try: self.output.delete(0, "end") self.output.insert(0, self.decode_fun(key, message)) except: return def display(self, master): frame = tk.Frame(master) frame.pack() encode_button = tk.Button(frame, text="Encode") encode_button.pack(side="left") decode_button = tk.Button(frame, text="Decode") decode_button.pack(side="right") tk.Label(frame, text="Key:").pack() key_text_box = tk.Entry(frame) key_text_box.pack() tk.Label(frame, text="Text:").pack() message_text_box = tk.Entry(frame) message_text_box.pack() self.output = tk.Entry(frame, background="gray", foreground="white") self.output.pack() encode_button.config(command= lambda: self.encode(key_text_box.get(), message_text_box.get())) decode_button.config(command= lambda: self.decode(key_text_box.get(), message_text_box.get())) def caesar_shift_encode(key, message): encoded_message = "" for char in message.lower(): try: encoded_message += ALPHABET[(ALPHABET.index(char) + int(key)) % len(ALPHABET)] except: encoded_message += char return encoded_message def caesar_shift_decode(key, message): return caesar_shift_encode(str(-int(key)), message) def xor_cipher_encode(key, message): return "".join( [ALPHABET[ALPHABET.index(key_char) ^ ALPHABET.index(message_char)] for key_char, message_char in zip(key, message)] ) root = tk.Tk() caesar_shift = Cipher(caesar_shift_encode, caesar_shift_decode) caesar_shift.display(root) xor_cipher = Cipher(xor_cipher_encode, xor_cipher_encode) xor_cipher.display(root) tk.mainloop()
I would be grateful to hear about any improvements that could be made to this code.