Ejemplo n.º 1
0
def main():

    print()
    print("This is the Secret Messages project for Treehouse  \n")
    cipher_text = None
    print("These are the current available ciphers:\n")
    ciphers = ["Caesar", "Atbash", "Keyword", "Affine"]
    for cipher in ciphers:
        print("- {}".format(cipher))
    while True:

        answer = input("Which cipher would you like to use? ")
        print()
        if answer.lower() == "atbash":
            cipher_text = Atbash()
            break
        elif answer.lower() == "keyword":
            keyword = input("what key word would you like to use ")
            if keyword is None or keyword == "":
                cipher_text = KeyWords()
                break
            else:
                cipher_text = KeyWords(keyword)
                break

        elif answer.lower() == "affine":
            cipher_text = Affine()
            break
        elif answer.lower() == "caesar":

            key_value = input("Shift Key Value:")
            if isinstance(int(key_value), int):
                cipher_text = Caesar(int(key_value))
                break
            else:
                cipher_text = Caesar()
                break

        else:
            print("not a valid cipher")

    message = input("{} Cipher,type in your message ".format(answer))
    while True:
        what_to_do = input("Do you want to encrypt ot decrypt? ")
        if what_to_do == "encrypt":
            encrypted_message = cipher_text.encrypt(message)
            break
        elif what_to_do == "decrypt":
            encrypted_message = cipher_text.decrypt(message)
            break
        else:
            print("not valid command")

    print("Your {}ed message is {} ".format(what_to_do, encrypted_message))
    regame = input("Do you want to encrypt/decrypt again y/n ")
    clear()
    if regame.lower() == "y":
        main()
    else:
        print("Good bye hope you had fun {}ing ".format(what_to_do))
Ejemplo n.º 2
0
class Affine(Cipher):
    """Implements cipher via the affine method"""
    def __init__(self, key, alphabet_size):
        super().__init__("Affine", alphabet_size, key)
        mkey, ckey = key
        self.multiplication = Multiplication(mkey, alphabet_size)
        self.caesar = Caesar(ckey, alphabet_size)

    def encode(self, message):
        caesared = self.caesar.encode(message)
        multiplied = self.multiplication.encode(caesared)
        return multiplied

    def decode(self, encrypted):
        multiplied = self.multiplication.decode(encrypted)
        caesared = self.caesar.decode(multiplied)
        return caesared

    def candidate_keys(self):
        caesar_candidates = self.caesar.candidate_keys()
        multiplication_candidates = self.multiplication.candidate_keys()

        return product(multiplication_candidates, caesar_candidates)

    @staticmethod
    def generate_key(alphabet_size):
        return Multiplication.generate_key(alphabet_size), Caesar.generate_key(
            alphabet_size)
Ejemplo n.º 3
0
def crack_caesar(ctext,
                 LANG=[ascii_lowercase, ascii_uppercase],
                 ALPHABET=len(ascii_lowercase)):
    # crack Caesar using quadgrams statistics
    # preserve text with punctuation
    ctext_c = ctext[::]

    # leave only letters in ctext
    ctext = re.sub(r'[^a-z]', '', ctext.lower())

    quadgram = ngram()  # load our quadgram statistics
    # calculate score for key=1
    plaintext = Caesar(1).caesar_decode(ctext, LANG, ALPHABET)
    best_score, best_key = quadgram.score(plaintext), 1

    # check for the bestscoring key
    for i in range(2, 26):
        plaintext = Caesar(i).caesar_decode(ctext, LANG, ALPHABET)
        plaintext_score = quadgram.score(plaintext)
        if plaintext_score > best_score:
            best_score, best_key = plaintext_score, i

    plaintext = Caesar(best_key).caesar_decode(ctext_c, LANG, ALPHABET)
    print('Decrypted text with key', best_key, ':', plaintext)
    return best_key, plaintext
Ejemplo n.º 4
0
def test_caesar_encrypt():
    plaintext = ciphertexts['plaintext']
    desired_ciphertext = ciphertexts['Caesar']

    cipher = Caesar()
    encrypted_text = cipher.encrypt(plaintext)

    assert encrypted_text == desired_ciphertext
Ejemplo n.º 5
0
    def setUp(self):
        self.test_word = 'testy'
        self.pad_word = 'loose'

        self.cipher = Cipher()
        self.affine = Affine(5, 9)
        self.atbash = Atbash()
        self.caesar = Caesar()
        self.keyword_cipher = Keyword(self.pad_word)
Ejemplo n.º 6
0
class CipherTests(unittest.TestCase):
    def setUp(self):
        self.test_word = 'testy'
        self.pad_word = 'loose'

        self.cipher = Cipher()
        self.affine = Affine(5, 9)
        self.atbash = Atbash()
        self.caesar = Caesar()
        self.keyword_cipher = Keyword(self.pad_word)

    def test_char_blocks(self):
        assert self.cipher.char_blocks('testytestytest') == 'testy testy test'
        assert self.cipher.char_blocks('exactlyten') == 'exact lyten'

    def test_use_pad(self):
        assert self.cipher.use_pad(self.test_word, self.pad_word) == 'ESGLC'

    def test_affine_encrypt(self):
        """Affine examples from http://crypto.interactive-maths.com/affine-cipher.html."""

        assert self.affine.encrypt(self.test_word) == 'ADVAZ'

    def test_affine_decrypt(self):
        """Affine examples from http://crypto.interactive-maths.com/affine-cipher.html."""

        assert self.affine.decrypt('ADVAZ') == self.test_word.upper()

    def test_atbash_encrypt(self):
        """Atbash examples from http://crypto.interactive-maths.com/atbash-cipher.html."""

        assert self.atbash.encrypt(self.test_word) == 'GVHGB'

    def test_atbash_decrypt(self):
        """Atbash examples from http://crypto.interactive-maths.com/atbash-cipher.html."""

        assert self.atbash.decrypt('GVHGB') == self.test_word.upper()

    def test_caesar_encrypt(self):
        """Caesar shifts by 3 every time.
        Caesar cipher examples from http://crypto.interactive-maths.com/caesar-cipher.html."""

        assert self.caesar.encrypt(self.test_word) == 'WHVWB'

    def test_caesar_decrypt(self):
        """Caesar shifts by 3 every time.
        Caesar cipher examples from http://crypto.interactive-maths.com/caesar-cipher.html."""

        assert self.caesar.decrypt('WHVWB') == self.test_word.upper()

    def test_keyword_encrypt(self):
        assert self.keyword_cipher.encrypt(self.test_word) == 'TARTY'

    def test_keyword_decrypt(self):
        assert self.keyword_cipher.decrypt('TARTY') == self.test_word.upper()
def __caesar_cipher(encrypt_or_decrypt, working_text):
    if encrypt_or_decrypt == "encryption":
        __clear()

        # Define your own offset?
        offset_decision = input(
            "Would you like to define the offset? [y/n] ").upper()

        if offset_decision == "Y":
            __clear()
            # How much offset?
            offset_num = int(
                input(
                    "What would you like the offset to be? (Value must be between 1 and 26): "
                ))
            caesar_encryption = Caesar(offset_num)

        # No user defined offset
        elif offset_decision == "N":
            caesar_encryption = Caesar()

        else:
            # Whoops user mistyped
            __clear()
            input(
                'The option specified by the user was not recognized. \nPlease try again'
            )
            __caesar_cipher(encrypt_or_decrypt, working_text)
        return caesar_encryption.encrypt(working_text)

    elif encrypt_or_decrypt == "decryption":
        __clear()

        # Did user define offset?
        offset_decision = input("Did you define an offset? [y/n] ").upper()

        if offset_decision == "Y":
            __clear()
            # Grab user offset
            offset_num = int(input("What was your offset? "))
            caesar_decryption = Caesar(offset_num)

        # No user defined offset
        elif offset_decision == "N":
            caesar_decryption = Caesar()

        else:
            # Whoops user mistyped
            __clear()
            input(
                'The option specified by the user was not recognized. \nPlease try again'
            )
            __caesar_cipher(encrypt_or_decrypt, working_text)
        return caesar_decryption.decrypt(working_text)
Ejemplo n.º 8
0
def run(params):


	function, infile, outfile, key = parser(params) 

	if(function==0):
		return help()
	else:

		cypher = Caesar(key,infile,outfile) # initialize object 
		cypher.encode() if(function==1) else cypher.decode()
	def key(self,text,enc):
		
		output = ""
		with open(text,'r+b') as f:
			with open(enc,'r+b') as f1:
				read_data = f.read(1)
				read_enc = f1.read(1)

			print "key = "+str( ( ord(read_enc) - ord(read_data)+256 ) % 256 )

			caesar = Caesar()
			test = caesar.decipher(enc,int( ( ord(read_enc) - ord(read_data)+256 ) % 256 ))
Ejemplo n.º 10
0
def encrypt(string, cipher, cipher_pad):
    if cipher == 'atbash':
        atbash = AtBash()
        return atbash.encrypt(string, cipher_pad)
    elif cipher == 'caesar':
        caesar = Caesar()
        return caesar.encrypt(string, cipher_pad)
    elif cipher == 'polybius':
        polybius = Polybius()
        return polybius.encrypt(string, cipher_pad)
    elif cipher == 'keyword':
        keyword = Keyword()
        return keyword.encrypt(string, cipher_pad)
Ejemplo n.º 11
0
 def test_decryption(self):
     keys = (15, 4)
     messages = (
         "ZXAI: P RDHIJBT HDBTIXBTH LDGC QN HRDIRWBTC XC PBTGXRP PCS PBTGXRPCH XC HRDIAPCS.",
         "MQTSWXSV: E VMZEP EWTMVERX XS TYFPMG LSRSVW."
     )
     decrypted_messages = (
         "KILT: A COSTUME SOMETIMES WORN BY SCOTCHMEN IN AMERICA AND AMERICANS IN SCOTLAND.",
         "IMPOSTOR: A RIVAL ASPIRANT TO PUBLIC HONORS."
     )
     for key, message, decrypted_message in (zip(keys, messages, decrypted_messages)):
         with self.subTest(key=key, message=message, decrypted_message=decrypted_message):
             cipher = Caesar(key, ascii_uppercase)
             self.assertEqual(cipher.decrypt(message), decrypted_message)
Ejemplo n.º 12
0
def code(args: argparse.Namespace) -> None:
    if not hasattr(args, 'code'):
        print("Enter something to do: encode, decode, train, hack")
        sys.exit()

    if args.code in ('encode', 'decode'):
        text = fileread(args.input_file)
        cipher = Cipher()
        if args.cipher == 'caesar':
            try:
                key_int = int(args.key)
            except ValueError:
                print("Key for caesar should be integer")
                sys.exit()
            cipher = Caesar()
            cipher.key = key_int
        elif args.cipher == 'vigenere':
            cipher = Vigenere()
            cipher.key = args.key
        elif args.cipher == 'vernam':
            cipher = Vernam()
            cipher.key = args.key
        else:
            print("No such cipher type")
            sys.exit()
        if args.code == 'encode':
            textprint(args.output_file, cipher.encode(text))
        else:
            textprint(args.output_file, cipher.decode(text))
    elif args.code == 'train':
        FreqAnalysis(args.model_file).train(fileread(args.text_file))
    elif args.code == 'hack':
        text = fileread(args.input_file)
        textprint(args.output_file, FreqAnalysis(args.model_file).hack(text))
Ejemplo n.º 13
0
def create_output(args, text):
    if args.mode == 'frequency':
        result = tools.calc_frequency(text)
        if args.output_file:
            with open(args.output_file, 'w', encoding='utf-8') as output_file:
                json.dump(result, output_file)
        else:
            print(result)
    else:
        if args.cipher == 'caesar':
            cipher = Caesar
        else:
            cipher = Vigenere
        if args.mode == 'encode':
            result = cipher.encode(text, args.key)
        elif args.mode == 'decode':
            result = cipher.decode(text, args.key)
        else:
            with open(args.frequency_file, 'r',
                      encoding='utf-8') as frequency_file:
                frequency = json.load(frequency_file)
            result = Caesar.hack(text, frequency)

        if args.output_file:
            with open(args.output_file, 'w', encoding='utf-8') as output_file:
                print(result, file=output_file, end='')
        else:
            print(result, end='')
Ejemplo n.º 14
0
def select_cipher():
    helpers.clear_screen()
    print("Please pick one of the following ciphers:")
    print()
    for cipher in ciphers:
        print(f"- {cipher}")
    print()

    while True:
        try:
            cipher = input("Which cipher would you like to use? ")
            if cipher.upper() == "ATBASH":
                cipher = Atbash()
            elif cipher.upper() == "CAESAR":
                cipher = Caesar()
            elif cipher.upper() == "POLYBIUS":
                cipher = Polybius()
            elif cipher.upper() == "KEYWORD":
                keyword = input(
                    "Which word would you like to use as a keyword? ")
                cipher = Keyword(keyword)
            else:
                raise ValueError("That cipher doesn't exist " +
                                 "or has not yet been implemented.")
        except ValueError as error:
            print(error)
            print()
        else:
            break
    return cipher
Ejemplo n.º 15
0
 def test_encryption(self):
     keys = (4, 21, 21)
     messages = (
         "AMBIDEXTROUS: Able to pick with equal skill a right-hand pocket or a left.",
         "GUILLOTINE: A machine which makes a Frenchman shrug his shoulders with good reason.",
         "IMPIETY: Your irreverence toward my deity."
     )
     encrypted_messages = (
         "EQFMHIbXVSYW:AEfpiAxsAtmgoA1mxlAiuyepAwomppAeAvmklx-lerhAtsgoixAsvAeApijxD",
         "bpdggjodiZ:RVR8vx349zRD34x3R8v6z.RvRa?z9x38v9R.3?B2R34.R.30B7yz?.RD4A3R200yR?zv.09U",
         "dhkdZot:Rt0B?R4??zCz?z9xzRA0Dv?yR8FRyz4AFU"
     )
     for key, message, encrypted_message in (zip(keys, messages, encrypted_messages)):
         with self.subTest(key=key, message=message, encrypted_message=encrypted_message):
             cipher = Caesar(key, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.')
             self.assertEqual(cipher.encrypt(message), encrypted_message)
Ejemplo n.º 16
0
def caesar():
    """Prompts the user on operating a Caesar Cipher"""

    answer = prompt()

    # Controls the choice of encrpytion or decryption
    if answer == 'E':
        word = input("Enter the word you want to encrpyt: ")
        test = Caesar()
        output = test.encrypt(word)
        print("The encrpyted word is:  {} ".format(output))

        # Prompts the user on if they wish to decrpyt the word
        yes_no = input("Do you want to decrypt this word? [Y/N]: ").upper()
        if yes_no == 'Y':
            print("The decrypted word is: {} ".format(test.decrypt(output)))
    elif answer == 'D':
        word = input("Enter the word you want to decrpyt: ")
        test = Caesar()
        output = test.decrypt(word)
        print("The decrpyted word is:  {} ".format(output))
    else:
        caesar()

    # Asks if the user would like to use another cipher
    restart = input("Hit 'R' to restart program. Hit enter to quit").upper()
    if restart == 'R':
        start()
Ejemplo n.º 17
0
 def decode_chi(cipher):
     d2 = {}
     arr = []
     for j in range(26): 
         k = (26-j)%26
         temp = Caesar.decode(cipher,j)
         sum = FrequencyAnalyzer.chisquaredstatistic(temp)
         d2[k] = sum
     return sort_dict_by_values(d2)[:3]
Ejemplo n.º 18
0
def verify_cipher(cipher_name, key_word=''):
    """ Main method to test ciphers """
    # Instantiate cipher
    cipher = None
    if cipher_name == 'caesar':
        cipher = Caesar()
    elif cipher_name == 'multiplication':
        cipher = Multiplication()
    elif cipher_name == 'affine':
        cipher = Affine()
    elif cipher_name == 'unbreakable':
        cipher = Unbreakable()
    elif cipher_name == 'rsa':
        cipher = RSA()
    else:
        raise Exception('Cipher name not recognised')

    print(('\nTesting %s cipher:\n' % cipher_name).upper())

    # Define sender and receiver
    sender = Sender(cipher)
    receiver = Receiver(cipher)

    # Distribute key(s)
    if cipher_name == 'unbreakable':
        encryption_key, decryption_key = cipher.generate_keys(key_word)
    else:
        encryption_key, decryption_key = cipher.generate_keys()
    sender.set_key(encryption_key)
    receiver.set_key(decryption_key)

    # Create message and send it
    message = "Hello world"
    # message = "aaaaaaaaaaa"
    sender.send(message, receiver)

    print("\nSender message:  ", sender.message)
    print("Sender encoded:  ", sender.encoded_message)
    print("Receiver encoded:", receiver.encoded_message)
    print("Receiver decoded:", receiver.message)

    hack = input('\nDo you want to try and hack this message? (y/n): ')
    if hack == 'y':
        hacker = Hacker(cipher)
        if cipher_name in ('caesar', 'multiplication'):
            hacker.hack_caesar_or_multiplication(sender.encoded_message)
        elif cipher_name == 'affine':
            hacker.hack_affine(sender.encoded_message)
        elif cipher_name == 'unbreakable':
            hacker.hack_unbreakable(sender.encoded_message)
        else:
            print('No can do :P')
Ejemplo n.º 19
0
def main():
    """Main program for testing ciphers"""
    key = Affine.generate_key(ALPHABET_SIZE)
    cipher = Affine(key, ALPHABET_SIZE)

    key = Multiplication.generate_key(ALPHABET_SIZE)
    cipher2 = Multiplication(key, ALPHABET_SIZE)

    key = Caesar.generate_key(ALPHABET_SIZE)
    cipher3 = Caesar(key, ALPHABET_SIZE)

    key = Unbreakable.generate_key(ALPHABET_SIZE)
    cipher4 = Unbreakable(key, ALPHABET_SIZE)

    # run_normal_cipher(cipher, "Test of affine")
    # run_normal_cipher(cipher2, "Test of multiplication")
    # run_normal_cipher(cipher3, "Test of caesar")
    run_normal_cipher(cipher4, "Test of unbreakable")

    run_rsa("Test of RSA")
	def breakOpen(self,enc):

		it = 1
		key = it
		words = 0

		while it < 256:
			
			caesar = Caesar()
			file = caesar.decipher(enc,it)

			n = self.compare(file)

			if n > words:
				key = it
				words = n

			it += 1

		print key
Ejemplo n.º 21
0
def cipher_select(ende):
    """Select the cipher."""
    c_selection = input(
        """Excellent.
    Please select your cipher by name or number.
    -------------------------
    ---[1]----Caesar---------
    -------------------------
    ---[2]----Affine---------
    -------------------------
    ---[3]----Atbash---------
    -------------------------
    ---[4]-Polybius Square---
    -------------------------
    > """)
    clear_screen()

    if c_selection.upper() in c_list:
        if c_selection.upper() == c_list[0] or c_selection == "1":
            print("CAESAR: \n The emperor of ciphers.")
            session = Caesar()
            if ende == 'encrypt':
                encrypt_message(session)
                restart()
            elif ende == 'decrypt':
                decrypt_message(session)
                restart()
        elif c_selection.upper() == c_list[1] or c_selection == "2":
            print("AFFINE: \n A very fine cipher indeed!")
            session = Affine()
            affine_session(session, ende)
            restart()
        elif c_selection.upper() == c_list[2] or c_selection == "3":
            print("ATBASH: \n For minimum security messages only.")
            session = Atbash()
            if ende == 'encrypt':
                encrypt_message(session)
                restart()
            elif ende == 'decrypt':
                decrypt_message(session)
                restart()
        elif c_selection.upper() == c_list[3] or c_selection == "4":
            print("POLYBIUS SQUARE: \n Sharp on all four corners.")
            session = PolybiusSquare()
            if ende == 'encrypt':
                polys_encrypt(session)
                restart()
            elif ende == 'decrypt':
                polys_decrypt(session)
                restart()
    else:
        print("""There is no {}.
        Please choose from available ciphers.""".format(c_selection))
        restart()
Ejemplo n.º 22
0
def run_cipher(cipher_choice, message, encode_choice):
    '''Executes the chosen cipher'''
    if cipher_choice == 'caesar':
        if encode_choice == 'encrypt':
            return Caesar().encrypt(message)
        elif encode_choice == 'decrypt':
            return Caesar().decrypt(message)
    elif cipher_choice == 'keyword':
        if encode_choice == 'encrypt':
            return Keyword().encrypt(message)
        elif encode_choice == 'decrypt':
            return Keyword().decrypt(message)
    elif cipher_choice == 'affine':
        if encode_choice == 'encrypt':
            return Affine().encrypt(message)
        elif encode_choice == 'decrypt':
            return Affine().decrypt(message)
    elif cipher_choice == 'polybius':
        if encode_choice == 'encrypt':
            return Polybius().encrypt(message)
        elif encode_choice == 'decrypt':
            return Polybius().decrypt(message)
Ejemplo n.º 23
0
def run_program():
    """This is a function which is called to run the program when
    secret_messages.py is run. It presents the user with a menu containing
    four options to choose from the Ciphers. After the Cipher is selected an
    object of the selected class is created by the name of our_class and the
    method of encrypt and decrypt is used on it. It asks the user for the
    message which they want to either encrypt or decrypt. It then displays the
    output as uppercase letters.
    """

    print('This is the secret messages project for the Treehouse Techdegree'
          '\n\n'
          'These are the current availabe ciphers:\n\n'
          '-Caesar \n'
          '-Atbash \n'
          '-Keyword \n'
          '-Affine \n\n\n'
          )
    valid_ciphers = ['caesar', 'atbash', 'keyword', 'affine']
    response = input('Which cipher would you like to use?')
    response = response.lower()

    while response not in valid_ciphers:
        print('That is an invalid cipher. Please choose from the list')
        response = input('Which cipher would you like to use?')
        response = response.lower()

    our_class = None
    if response == 'keyword':
        our_class = Keyword()
    elif response == 'atbash':
        our_class = Atbash()
    elif response == 'caesar':
        our_class = Caesar()
    elif response == 'affine':
        our_class = Affine()

    text = input("That's an excellent cipher. What's the message?")
    valid_actions = ['encrypt', 'decrypt']
    action = input('Are we going to encrypt or decrypt?')
    action = action.lower()

    while action not in valid_actions:
        print("That is not a valid action. Please either type 'encrypt' or "
              "'decrypt'")
        action = input('Are we going to encrypt or decrypt?')
        action = action.lower()
    if action == 'encrypt':
        print(our_class.encrypt(text))
    elif action == 'decrypt':
        print(our_class.decrypt(text))
Ejemplo n.º 24
0
class Affine:
    """ Affine cipher """
    def __init__(self):
        self.caesar = Caesar()
        self.multiplication = Multiplication()

    def generate_keys(self):
        """ Generates encryption and decryption key """
        multiplication_encrypt, multiplication_decrypt = self.multiplication.generate_keys(
        )
        caesar_encrypt, caesar_decrypt = self.caesar.generate_keys()
        encryption_key = (multiplication_encrypt, caesar_encrypt)  # (48, 90)
        decryption_key = (multiplication_decrypt, caesar_decrypt)  # (2, 5)
        return encryption_key, decryption_key

    def encode(self, message, key):
        """ Encode message with given key """
        multiplication_key = key[0]
        caesar_key = key[1]

        # Encode with Multiplication then Caesar
        partially_encoded = self.multiplication.encode(message,
                                                       multiplication_key)
        encoded_message = self.caesar.encode(partially_encoded, caesar_key)

        return encoded_message

    def decode(self, encoded_message, decryption_keys):
        """ Decode the encoded message with the decryption key """
        multiplication_key = decryption_keys[0]
        caesar_key = decryption_keys[1]

        # Decode with Caesar then Multiplication
        partially_decoded = self.caesar.decode(encoded_message, caesar_key)
        decoded_message = self.multiplication.decode(partially_decoded,
                                                     multiplication_key)

        return decoded_message
def initiating(methd):
	"""
	This method is to create the instance of the cipher you chose
	"""

	if methd == "1":
		cm = AtbashCipher()
	elif methd == "2":
		cm = Caesar()	
	elif methd == "3":
		cm = ADFGVXCCipher()
	elif methd == "4":
		kwrd = input("Whats' your keyword? >")
		cm = KeywordCipher(kwrd)
	return cm
Ejemplo n.º 26
0
 def __init__(self, ciphers=None):
     self.available_ciphers = {
         'caesar': Caesar(),
         'keywordcipher': KeywordCipher(),
         'bifid': Bifid(),
         'hill': Hill()
     }
     self.one_time_pad = ''
     self.one_time_padded_msg = ''
     self.use_one_time_pad = False
     self.cipher = ''
     self.encrypt = False
     self.decrypt = False
     self.message = ''
     self.key = ''
     self.quit = False
Ejemplo n.º 27
0
    def symmetric_cipher(self):
        """Selects a symmetric-key chiper.

        :return: an object of one of the symmetric-key encryption classes or None
        """

        _cipher = None
        if self.algorithm == AlgEnum.CAESAR.name:
            _cipher = Caesar()
        if self.algorithm == AlgEnum.VIGENERE.name:
            _cipher = Vigenere()
        if self.algorithm == AlgEnum.AES.name:
            _cipher = AES()
        if self.algorithm == AlgEnum.DES.name:
            _cipher = DES()
        if self.algorithm == AlgEnum.MAGMA.name:
            _cipher = Magma()
        if self.algorithm == AlgEnum.KUZNECHIK.name:
            _cipher = Kuznechik()

        if self.algorithm == AlgEnum.RSA.name:
            _cipher = Kuznechik()

        return _cipher
Ejemplo n.º 28
0
def game_loop():
    """Prompt the user for input to encrypt or decrypt and, if applicable,
    any additional input settings required to perform the
    cipher process."""
    menu()
    while True:
        cipher = input("\nWhich cipher would you like to use? ").title()
        available_ciphers = ["Caesar", "Affine", "Atbash", "Keyword"]
        if cipher in available_ciphers:
            if cipher.lower() == 'caesar':
                klass = Caesar()
            elif cipher.lower() == 'affine':
                klass = Affine()
            elif cipher.lower() == 'atbash':
                klass = AtBash()
            elif cipher.lower() == 'keyword':
                print("\n{} is a good cipher!\n".format(cipher.title()))
        elif cipher not in available_ciphers:
            print("\nThat's not an availble cipher, please select again!\n")
            continue
        else:
            pass
        user_choice = input("Are we going to encrypt or decrypt? ")
        if user_choice.lower() == 'encrypt':
            cipher_text = input("\nWhat cipher text do you want to encrypt? ")
            print('\n', klass.encrypt(str(cipher_text)))
        elif user_choice.lower() == 'decrypt':
            cipher_text = input("\nWhat cipher text do you want to decrypt? ")
            print('\n', klass.decrypt(str(cipher_text)))
        else:
            continue
        value = input("\nEncrypt/decrypt something else? (Y/N) ")
        if value.lower() == 'y':
            menu()
            continue
        elif value.lower() == 'n':
            print("\nThanks for using the Secret Messages app!!!\n")
            break
        else:
            pass
Ejemplo n.º 29
0
def run_cipher(encrypt=True):
    """Sub menu with a list of implemented ciphers."""

    clear()
    prompt = "Choose a cipher to use:\n\n"
    prompt += "1) (Af)fine\n"
    prompt += "2) (At)bash\n"
    prompt += "3) (C)aesar\n"
    prompt += "4) (K)eyword\n\n"
    prompt += "Type (q) to quit.\n"


    user_input = input(prompt)

    affine_input = [1, '1', 'af']
    atbash_input = [2, '2', 'at']
    caesar_input = [3, '4', 'c']
    keyword_cipher_input = [4, '3', 'k']
    valid_input = affine_input + atbash_input + keyword_cipher_input + caesar_input

    if user_input.lower() == "q":
        return "q"

    while user_input not in valid_input:
        user_input = str(input(prompt))

    def ask_for_value():
        val_input = input("Enter value:\n")

        if not encrypt:
            val_input = Cipher.remove_char_blocks(val_input)

        return val_input

    text = ask_for_value()

    while text.lower().replace(" ", "").isalpha() is False:
        print("Value must contain letters only.\n")
        text = ask_for_value()

    # Affine inputs
    if user_input in affine_input:
        aff_first_number = input("Please enter a beginning number for the Affine cipher (must be odd):\n")
        aff_second_number = input("Please enter an ending number for the Affine cipher:\n")

        while aff_first_number.isnumeric() is False \
                or int(aff_first_number) % 2 == 0 \
                or aff_second_number.isnumeric() is False:
            print("Value must contain numbers. First number must be odd.\n")
            aff_first_number = input("Please enter a beginning number for the Affine Cipher (must be odd):\n")
            aff_second_number = input("Please enter an ending number for the Affine cipher:\n")

        cipher = Affine(aff_first_number, aff_second_number)

    # Atbash inputs
    if user_input in atbash_input:
        cipher = Atbash()

    # Keyword inputs
    if user_input in keyword_cipher_input:
        user_keyword = input("Please enter your keyword for the Keyword Cipher:\n")

        while text.lower().isalpha() is False:
            print("Value must contain letters only.\n")
            user_keyword = input("Please enter keyword for the Keyword Cipher:\n")

        cipher = Keyword(user_keyword)

    if user_input in caesar_input:
        cipher = Caesar()

    if encrypt:
        text = cipher.encrypt(text)
        if input("Do you want to add a secret pad? (Y/n)\n").lower() == "y":
            text = pad_option(text, cipher)

        val = cipher.char_blocks(text)
    else:
        if input("Was a secret pad used? (Y/n)\n").lower() == "y":
            text = pad_option(text, cipher, encrypt=False)

        val = cipher.decrypt(text)

    return val
Ejemplo n.º 30
0
from sys import argv
from caesar import Caesar
from transposition import Transposition
from vigenere import Vigenere
from substitution import Substitution

script,from_file,key,algorithm,option = argv


if algorithm == "c":

	caesar = Caesar()

	if option == "c":
		caesar.cipher(from_file,int(key))
	elif option == "d":
		caesar.decipher(from_file,int(key))
	else:
		print "Option doesn't exist."
elif algorithm == "t":

	transposition = Transposition()

	if option == "c":
		transposition.cipher(from_file,int(key))
	elif option == "d":
		transposition.decipher(from_file,int(key))
	else:
		print "Option doesn't exist."
elif algorithm == "v":
Ejemplo n.º 31
0
        # Takes the message input and converts to uppercase
        message = remove_non_alpha(input("What is your message? ")).upper()

        # CAESAR
        # =====================================================================

        if cipher_type == 'CAESAR':
            offset = input("What is your desired offset? "
                           "(blank for default of 3) ")

            # If an int isn't provided, use the default of 3
            # Could be changed to again prompt for a number
            try:
                offset = int(offset)
            except ValueError:
                cipher = Caesar()
            else:
                cipher = Caesar(offset)

        # ATBASH
        # =====================================================================

        # No input necessary to generate key
        if cipher_type == 'ATBASH':
            cipher = Atbash()

        # BIFID
        # =====================================================================

        if cipher_type == 'BIFID':
            print("Enter a key below, or just hit Enter to use the default "
Ejemplo n.º 32
0
def index():
    if request.method == 'POST':
        # set language
        if request.form.get("lang") == 'english':
            LANG, ALPHABET = [ascii_lowercase,
                              ascii_uppercase], len(ascii_lowercase)
        elif request.form.get("lang") == 'lithuanian':
            LANG, ALPHABET = lt_lang, lt_alphabet
        # get plaintext
        plaintext = request.form.get('plaintext')

        # BREAK (WITHOUT KNOWING CYPHER TYPE)
        if request.form.get("enc_dec") == ("Break"):
            try:
                broken = crack_cipher(plaintext, LANG, ALPHABET)
                if len(broken) == 2:
                    key, text = str(broken[0]) + ", Caesar", broken[1]
                    return render_template("index.html",
                                           cyptext=key,
                                           title="KEY, CYPHER: ",
                                           footnote="DECRYPTED TEXT: ",
                                           cyptext2=text)
                elif broken == "This text is most likely encoded in Vigenere. The program can break lithuanian text encoded only in Caesar's":
                    return render_template("index.html",
                                           cyptext2=broken.upper())
                else:
                    return render_template(
                        "index.html",
                        broken=broken,
                        title="POSSIBLE KEYS AND DECRYPTED TEXT USING THEM:")
            except (ValueError, IndexError):
                return apology("please provide text in chosen language")
        # CAESAR
        if request.form.get("cypher") == 'caesar':
            # set key. If key is not a number, return apology
            try:
                key = int(request.form.get("shift"))
            except BaseException:
                return apology("must provide valid shift size")

            # check if user uses encryption or decryption
            if request.form.get("enc_dec") == 'Encrypt':
                try:
                    ctext = Caesar(key).caesar_encode(plaintext, LANG,
                                                      ALPHABET)
                    return render_template("index.html",
                                           cyptext=ctext,
                                           title="ENCRYPTED TEXT:")
                except ValueError:
                    return apology("please provide text in chosen language")

            elif request.form.get("enc_dec") == 'Decrypt':
                try:
                    ctext = Caesar(key).caesar_decode(plaintext, LANG,
                                                      ALPHABET)
                    return render_template("index.html",
                                           cyptext=ctext,
                                           title="DECRYPTED TEXT:")
                except ValueError:
                    return apology("please provide text in chosen language")

        # VIGENERE
        elif request.form.get("cypher") == 'vigenere':
            key = request.form.get("key")
            if key is None or key.isalpha() == False:
                return apology("must provide valid key")

            if request.form.get("enc_dec") == 'Encrypt':
                try:
                    ctext = Vigenere(key).vigenere_encode(
                        plaintext, LANG, ALPHABET)
                    return render_template("index.html",
                                           cyptext=ctext,
                                           title="ENCRYPTED TEXT:")
                except ValueError:
                    return apology("please provide text in chosen language")

            elif request.form.get("enc_dec") == 'Decrypt':
                try:
                    ctext = Vigenere(key).vigenere_decode(
                        plaintext, LANG, ALPHABET)
                    return render_template("index.html",
                                           cyptext=ctext,
                                           title="DECRYPTED TEXT:")
                except ValueError:
                    return apology("please provide text in chosen language")

    else:  # == if request.method == 'GET'
        return render_template("index.html")
Ejemplo n.º 33
0
 def __init__(self):
     self.caesar = Caesar()
     self.multiplication = Multiplication()