class AffineCipher(Cipher): def __init__(self): super().__init__() self.multiplication = MultiplicationCipher() self.caesar = Caesar() def encode(self, plaintext, key): return self.caesar.encode( self.multiplication.encode(plaintext, key[0]), key[1]) def decode(self, ciphertext, key): return self.multiplication.decode( self.caesar.decode(ciphertext, key[1]), key[0]) def generate_keys(self): return (self.multiplication.generate_keys(), self.caesar.generate_keys()) def get_possible_keys(self): for key1 in self.multiplication.get_possible_keys(): for key2 in self.caesar.get_possible_keys(): yield key1, key2 def __str__(self): return "Affine Cipher"
def test_caesar_basic(): mess = "UNMENSAJECONÑ" mess1, mess7 = "VÑNFÑTBKFDPÑO", "BTSLTZHPLJVTU" assert c1.cipher(mess) == mess1 assert c2.cipher(mess) == mess7 assert c3.cipher(mess) == mess assert c1.decipher(mess1) == mess assert c2.decipher(mess7) == mess assert c3.decipher(mess) == mess caesar = Caesar(alphabet) crip = caesar.cipher(mess) assert mess == caesar.decipher(crip)
def __init__(self, alphabet, password=None): #Recomendación, ingeniárselas para no cargar siempre O(n^2) en memoria aunque esto no #será evaluado, con n el tamaño del alfabeto. """ Constructor de clase, recibe un parámetro obligatorio correspondiente al alfabeto y un parámetro opcional que es la palabra clave, en caso de ser None, entonces generar una palabra pseudoaleatoria de al menos tamaño 4. :param alphabet: Alfabeto a trabajar con el cifrado. :param password: El password que puede ser o no dada por el usuario. """ self.alphabet = alphabet if password == None: self.password = "******" else: self.password = password self.cesar = Caesar(self.alphabet)
receiver.set_key(key[1]) else: sender.set_key(key) receiver.set_key(key) message = "shady crypto" print("Key is: ", key) print("Plaintext: ", message) crypted = message = sender.operate_cipher(message) print("Cryptedtext : ", message) message = receiver.operate_cipher(message) print("Cryptedtext converted back to Plaintext: ", message) if cipher.verify("text hacking example", key): print("Cipher is verified") else: print("Cipher is invalid") if not rsa: hacker = Hacker() print("Hacker will hack this cryptedtext: ", crypted) hacked = hacker.operate_cipher(crypted, cipher) print("Message:", '"' + str(hacked[0]) + '"', "is hacked with Key:", hacked[1]) print("\n"*2) main(Caesar()) main(MultiplicationCipher()) main(AffineCipher()) main(UnbreakableCipher()) main(RSACipher(), 1)
from caesar_cipher import Caesar alphabet = "ABCDEFGHIJKLMNÑOPQRSTUVWXYZ" c1, c2, c3 = Caesar(alphabet, 1), Caesar(alphabet, 7), Caesar(alphabet,27) def aux_tests(caesar, message, ciphered): one = caesar.cipher(message) == ciphered two = caesar.decipher(ciphered) == message return (one, two) def test_caesar_basic(): mess = "UNMENSAJECONÑ" mess1, mess7 = "VÑNFÑTBKFDPÑO", "BTSLTZHPLJVTU" assert c1.cipher(mess) == mess1 assert c2.cipher(mess) == mess7 assert c3.cipher(mess) == mess assert c1.decipher(mess1) == mess assert c2.decipher(mess7) == mess assert c3.decipher(mess) == mess caesar = Caesar(alphabet) crip = caesar.cipher(mess) assert mess == caesar.decipher(crip) def test_caesar_spaces(): mess = "UN MENSAJE CON Ñ Y ESPACIOS" mess1, mess7 = "VÑ NFÑTBKF DPÑ O Z FTQBDJPT", "BT SLTZHPL JVT U F LZWHJOVZ" assert c1.cipher(mess, True) == mess1 assert c2.cipher(mess, True) == mess7 assert c1.decipher(mess1, True) == mess assert c2.decipher(mess7, True) == mess
class Vigenere(): def __init__(self, alphabet, password=None): #Recomendación, ingeniárselas para no cargar siempre O(n^2) en memoria aunque esto no #será evaluado, con n el tamaño del alfabeto. """ Constructor de clase, recibe un parámetro obligatorio correspondiente al alfabeto y un parámetro opcional que es la palabra clave, en caso de ser None, entonces generar una palabra pseudoaleatoria de al menos tamaño 4. :param alphabet: Alfabeto a trabajar con el cifrado. :param password: El password que puede ser o no dada por el usuario. """ self.alphabet = alphabet if password == None: self.password = "******" else: self.password = password self.cesar = Caesar(self.alphabet) def lToN(self, letter): i = 0 for e in self.alphabet: if(e == letter): return i i = i+1 return -1 def convierteLlave(self,llave): llaveInt = [] for i in llave: llaveInt.append(self.lToN(i)) return llaveInt def cipher(self, message): """ Usando el algoritmo de cifrado de vigenere, cifrar el mensaje recibido como parámetro, usando la tabla descrita en el PDF. :param message: El mensaje a cifrar. :return: Una cadena de texto con el mensaje cifrado. """ j = 0 llave = self.convierteLlave(self.password) longitud = len(llave) strg = "" for i in message: self.cesar.key = llave[j%longitud] strg = strg+(self.cesar.cipher(i)) j = j+1 return strg def decipher(self, ciphered): """ Implementación del algoritmo de decifrado, según el criptosistema de vigenere. :param ciphered: El criptotexto a decifrar. :return: El texto plano correspondiente del parámetro recibido. """ j = 0 llave = self.convierteLlave(self.password) longitud = len(llave) strg = "" for i in ciphered: self.cesar.key = llave[j%longitud] strg = strg+(self.cesar.decipher(i)) j = j+1 return strg
def welcome(): """Enables the user to select a cipher and either encrypt or decrypt a message. Once complete the encrypted/decrypted message will be returned, and the user will be prompted to restart or quit. """ clear() cipher_choice = None encrypt_or_decrypt = None cipher_dict = { '1': 'Caesar', '2': 'Keyword', '3': 'Affine', '4': 'Transposition' } print("""Welcome to the Secret Messages project for treehouse techdegree. Select a cipher from the list below or press 'q' to quit:\n 1 - Caesar 2 - Keyword 3 - Affine 4 - Transposition""") # Select cipher type. while cipher_choice is None: cipher_choice = input("Enter 1, 2, 3, or 4 to begin.\n>> ").lower() if cipher_choice not in ['1', '2', '3', '4']: if cipher_choice == 'q': print("Good Bye.") sys.exit() else: print("Invalid selection, Try again.") cipher_choice = None print("You have selected {}.".format(cipher_dict[cipher_choice])) # Select Encryption or decryption. while encrypt_or_decrypt is None: encrypt_or_decrypt = input("Would you like to encrypt or decrypt?\n>>\ ").lower() if encrypt_or_decrypt not in ['encrypt', 'decrypt']: if encrypt_or_decrypt == 'q': print("Good Bye.") sys.exit() else: print("Invalid selection, Try again.") encrypt_or_decrypt = None # Prints Caesar encryption/decrytion. clear() if cipher_choice == '1': if encrypt_or_decrypt == 'encrypt': print("The {}ed message is: {}".format(encrypt_or_decrypt, Caesar().encrypt())) else: print("The {}ed message is: {}".format(encrypt_or_decrypt, Caesar().decrypt())) # Prints Keyword encryption/decrytion. if cipher_choice == '2': if encrypt_or_decrypt == 'encrypt': print("The {}ed message is: {}".format(encrypt_or_decrypt, Keyword().encrypt())) else: print("The {}ed message is: {}".format(encrypt_or_decrypt, Keyword().decrypt())) # Prints Affine encryption/decrytion. if cipher_choice == '3': if encrypt_or_decrypt == 'encrypt': print("The {}ed message is: {}".format(encrypt_or_decrypt, Affine().encrypt())) else: print("The {}ed message is: {}".format(encrypt_or_decrypt, Affine().decrypt())) # Prints Transposition encryption/decrytion. if cipher_choice == '4': if encrypt_or_decrypt == 'encrypt': print("The {}ed message is: {}".format(encrypt_or_decrypt, Transposition().encrypt())) else: print("The {}ed message is: {}".format(encrypt_or_decrypt, Transposition().decrypt())) # Ask user to restart or quit. restart = input("Would you like to encrypt/decrypt another message? Y/n\n\ >> ").upper() if restart == 'Y': welcome() else: print("Good Bye.") sys.exit()
def test_caesar(self): caesar = Caesar(self.test_string) cipher_text = caesar.encrypt(self.test_string, self.shift) self.failUnless(cipher_text == self.answer_string) plaintext = caesar.decrypt(self.answer_string, self.shift) self.failUnless(plaintext == self.test_string)
def __init__(self): super().__init__() self.multiplication = MultiplicationCipher() self.caesar = Caesar()