class Client(Socket): def __init__(self): super(Client, self).__init__() self.messages = "" self.encryptor = Encryptor() def set_up(self): try: self.socket.connect(('192.168.0.7', 3031)) except ConnectionRefusedError: print("Sorry, server is offline") exit(0) self.socket.setblocking(False) async def listen_socket(self, listened_socket=None): while True: data = await self.main_loop.sock_recv(self.socket, 2048) clean_data = self.encryptor.crypt(data.decode("utf-8")) self.messages += f"{datetime.now().date()}: {clean_data}\n" system("cls") print(self.messages) async def send_data(self, data=None): while True: data = await self.main_loop.run_in_executor(None, input) encrypted_data = self.encryptor.crypt(data) await self.main_loop.sock_sendall(self.socket, encrypted_data.encode("utf-8")) async def main(self): await asyncio.gather(self.main_loop.create_task(self.listen_socket()), self.main_loop.create_task(self.send_data()))
def encrypt1(): conn1 = sqlite3.connect('Database.db') with conn1: cursor1 = conn1.cursor() # Searching for users find_key = ('SELECT * FROM Users') cursor1.execute(find_key) key_users = cursor1.fetchall() print(username) for key_user in key_users: #print(key_user[2]) if (username == key_user[2]): key = key_user[4] #print(type(key_user[4])) print(len(str(key))) if key1_entry.get() == '': ms.showerror('Oops', 'Enter key !!') elif key1_entry.get() == str(key): file1 = filedialog.askopenfile(mode='r') if file1 is not None: file_name = file1.name enc = Encryptor(str(key)) enc.encrypt_file(file_name) else: ms.showerror('Oops', 'Key is invalid !!')
class Application(Frame): def __init__(self, master): self.encryptor = Encryptor("cipher1.txt") super(Application, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): inp = Label(self, text = "Enter the message:")\ .grid(row = 0, column = 1, columnspan = 2, sticky = W) self.inp_ent = Entry(self, width=60) self.inp_ent.grid(row=1, column=1, columnspan=2, sticky=W) enbttn = Button(self, text = "Encrypt", command = self.encrypt)\ .grid(row = 2, column = 1, sticky = E) debttn = Button(self, text = "Decrypt", command = self.decrypt)\ .grid(row = 2, column = 2, sticky = W) Label(self, text = "Out:")\ .grid(row = 3, column = 1, sticky = W) self.out = Text(self, width=45, height=10, wrap=WORD) self.out.grid(row=4, column=1, columnspan=3, sticky=W) def encrypt(self): inp = self.inp_ent.get() nxt = self.encryptor.encrypt_message(inp) self.out.delete(0.0, END) self.out.insert(0.0, nxt) def decrypt(self): inp = self.inp_ent.get() nxt = self.encryptor.decrypt_message(inp) self.out.delete(0.0, END) self.out.insert(0.0, nxt)
def encrypt(self): if not os.path.exists("result"): os.makedirs("result") if not os.path.exists("key"): os.makedirs("key") encryption = Encryptor(self.file_path) encryption.save_file() parsed_image = self.parse_image(encryption.main_image, 500) self.label_image.setPixmap(parsed_image) self.file_path = encryption.encryption_path self.makeHistogram()
def encode(info, img, tx, key): try: image = Image.open(img) contents = encode_file(tx, img) contents = contents + "*//*" + info encriptador = Encryptor() contents = encriptador.run(key, contents) st = stepic.encode(image, contents) name = img.split(".png")[0] + ".png" st.save(name, "png") except Exception as e: print(e)
class CryptoService(object): def __init__(self, rsa_pub_path=None, rsa_pri_path=None, p=None, g=None): self.dh = DiffieHellman(p, g) if p is not None and g is not None else None self.encryptor = Encryptor(rsa_pub_path) self.decryptor = Decryptor(rsa_pri_path) def get_dh_pri_key(self): return self.dh.generate_private_key() def get_dh_pub_key(self, private_key): return self.dh.generate_public_key(private_key) def get_dh_secret(self, private_key, other_public_key): # TODO verify the other_public_key return self.dh.compute_secret(private_key, other_public_key) def sym_encrypt(self, secret, p_text): return self.encryptor.sym_encrypt(secret, p_text) def sym_decrypt(self, secret, c_text): return self.decryptor.sym_decrypt(secret, c_text) def rsa_decrypt(self, c_text): return self.decryptor.rsa_decrypt(c_text) def rsa_sign(self, msg): return self.decryptor.rsa_sign(msg) def rsa_verify(self, msg, sign): return self.encryptor.rsa_verify(msg, sign) def rsa_encrypt(self, p_text): return self.encryptor.rsa_encrypt(p_text) def compute_pw_hash(self, pw, salt): return hashlib.sha256(pw + salt).hexdigest() def new_sym_key(self, size=32): return os.urandom(size) @staticmethod def generate_hmac_sign(dh_key, msg): #generate digest for the cipher text with HMAC h = hmac.HMAC(dh_key, hashes.SHA256(), backend=default_backend()) h.update(msg) sign = h.finalize() return sign @staticmethod def verify_hmac_sign(dh_key, msg, sign): expect_sign = CryptoService.generate_hmac_sign(dh_key, msg) return expect_sign == sign
def main(): file_name=input("Choose a file to load: ") encryptor=Encryptor(file_name) menu=0 while menu!="Q": menu=input("\n\tE - Encrypt a message\n\tD - Decrypt a message\n\tQ - Quit\n\n").upper() print() if menu=="E": msg=input("Enter a message to encrypt: ") print(encryptor.encryptMessage(msg)) elif menu=="D": msg=input("Enter a message to decrypt: ") print(encryptor.decryptMessage(msg))
def main(): file_name = input("Choose a file to load: ") encryptor = Encryptor(file_name) menu = 0 while menu != "Q": menu = input( "\n\tE - Encrypt a message\n\tD - Decrypt a message\n\tQ - Quit\n\n" ).upper() print() if menu == "E": msg = input("Enter a message to encrypt: ") print(encryptor.encryptMessage(msg)) elif menu == "D": msg = input("Enter a message to decrypt: ") print(encryptor.decryptMessage(msg))
class Application(tkinter.Frame): def __init__(self, master): super(Application, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): self.load_file = tkinter.StringVar() self.load_file.set(None) tkinter.Label(self, text="Choose a file to load:").grid(row=0, column=0, sticky=tkinter.W) tkinter.Radiobutton(self, text="Cipher1.txt", variable=self.load_file, value="cipher1.txt", command=self.load_cipher).grid(row=1, column=0, sticky=tkinter.W) tkinter.Radiobutton(self, text="Cipher2.txt", variable=self.load_file, value="cipher2.txt", command=self.load_cipher).grid(row=1, column=1, sticky=tkinter.W) tkinter.Label(self, text="Enter the message:").grid(row=2, column=0, sticky=tkinter.W) self.msg=tkinter.Text(self, width=100, height=10, wrap=tkinter.WORD) self.msg.grid(row=3, column=0, columnspan=3, sticky=tkinter.W) tkinter.Button(self, text="Encrypt Message", command=self.encrypt_message).grid(row=4, column=0, sticky=tkinter.E) tkinter.Button(self, text="Decrypt Message", command=self.decrypt_message).grid(row=4, column=1, sticky=tkinter.E) tkinter.Label(self, text="Out:").grid(row=5, column=0, sticky=tkinter.W) self.out_msg=tkinter.Text(self, width=100, height=15, wrap=tkinter.WORD) self.out_msg.grid(row=6, column=0, columnspan=3, sticky=tkinter.W) def load_cipher(self): self.e = Encryptor(self.load_file.get()) def encrypt_message(self): msg = self.msg.get(0.0, tkinter.END) encrypt = self.e.encrypt_message(msg) self.out_msg.delete(0.0, tkinter.END) self.out_msg.insert(0.0, encrypt) def decrypt_message(self): msg = self.msg.get(0.0, tkinter.END) decrypt = self.e.decrypt_message(msg) self.out_msg.delete(0.0, tkinter.END) self.out_msg.insert(0.0, decrypt)
def KPIServer(datasource, kpidb): """\ KPIServer(datasource, kpidb) -> activates KPISever KPIServer is Session rekeying and Data transmission backend Keyword arguments: - datasource -- any component with an outbox. the datasource sends data to encryptor's inbox - kpidb -- KPIDB instance for key lookup """ Backplane("DataManagement").activate() Backplane("KeyManagement").activate() Graphline(ds=datasource, sc=SessionKeyController(kpidb), keyRx=subscribeTo("KeyManagement"), enc=Encryptor(), sender=publishTo("DataManagement"), pz=DataTx(), linkages={ ("ds", "outbox"): ("enc", "inbox"), ("keyRx", "outbox"): ("sc", "userevent"), ("sc", "notifykey"): ("enc", "keyevent"), ("sc", "outbox"): ("pz", "keyIn"), ("enc", "outbox"): ("pz", "inbox"), ("pz", "outbox"): ("sender", "inbox"), }).activate()
def __init__(self): super(Client, self).__init__() self.messages = "" self.encryptor = Encryptor()
def load_cipher(self): self.e = Encryptor(self.load_file.get())
def __init__(self, master): self.encryptor = Encryptor("cipher1.txt") super(Application, self).__init__(master) self.grid() self.create_widgets()
def main(): global INPUT_FILE global OUTPUT_FILE args = argparse.ArgumentParser(description="Vigenère cipher decryption " "tool.") args.add_argument("-e", "--encrypt", help="Encrypt the input file", action="store_true", dest="mode_encrypt") args.add_argument('-k', '--key', help="Add custom key for encryption or " "decryption") args.add_argument("-d", "--decrypt", help="Decrypt the input file", action="store_true", dest="mode_decrypt") args.add_argument("-i", "--input-file", help="The file from which the text" " will be read to be " "encrypted or decrypted") args.add_argument("-o", "--output-file", help="The file where the output " "will be saved") args.add_argument("-v", "--verbose", help="Enable verbosity", action="store_true") parser = args.parse_args() if not parser.mode_encrypt and not parser.mode_decrypt: display_error("Mode must be set using --encrypt or --decrypt options.") if parser.input_file: INPUT_FILE = parser.input_file try: with open(INPUT_FILE, "r") as _: pass except FileNotFoundError: display_error(f"The file '{INPUT_FILE}' does not exist.") except PermissionError: display_error(f"You do not have enough permissions to read the " f"file '{INPUT_FILE}'") else: display_error("No input file provided.") if parser.output_file: OUTPUT_FILE = parser.output_file else: display_error("No output file provided") if parser.mode_encrypt: # Creating a new Encryptor object and uploading the plaintext to be # encrypted with a random key encryptor = Encryptor(parser.verbose) encryptor.read_plaintext_from_file(INPUT_FILE) if parser.key: encryptor.encrypt(parser.key) else: encryptor.encrypt() encryptor.save_ciphertext_to_file(OUTPUT_FILE) display_info("Encryption performed successfully.") display_info(f"Saved encrypted text to '{OUTPUT_FILE}'") else: # Now, prepare the decrypting process by creating a new Decryptor # object which will crack the key by itself enigma = Decryptor(parser.verbose) enigma.read_ciphertext_from_file(INPUT_FILE) if parser.key: decrypted_key = parser.key display_verbose(f"Decrypting using custom key " f"[green]{decrypted_key}[/green] of length " f"[yellow]{len(decrypted_key)}[/yellow]") else: decrypted_key = enigma.crack_key() enigma.decrypt(decrypted_key) enigma.save_decrypted_plaintext_to_file(OUTPUT_FILE) display_info("Decryption performed successfully.") display_info(f"Saved decrypted text to '{OUTPUT_FILE}'")
def __init__(self, rsa_pub_path=None, rsa_pri_path=None, p=None, g=None): self.dh = DiffieHellman(p, g) if p is not None and g is not None else None self.encryptor = Encryptor(rsa_pub_path) self.decryptor = Decryptor(rsa_pri_path)