Exemplo n.º 1
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()
Exemplo n.º 2
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)
Exemplo n.º 4
0
def decrypt(string, cipher, cipher_pad):
    if cipher == 'atbash':
        atbash = AtBash()
        return atbash.decrypt(string, cipher_pad)
    elif cipher == 'caesar':
        caesar = Caesar()
        return caesar.decrypt(string, cipher_pad)
    elif cipher == 'polybius':
        polybius = Polybius()
        return polybius.decrypt(string, cipher_pad)
    elif cipher == 'keyword':
        keyword = Keyword()
        return keyword.decrypt(string, cipher_pad)
Exemplo n.º 5
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)
Exemplo n.º 6
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
                    continue
                break

        # One-time pad
        pad_key = remove_non_alpha(
            input("Provide One-time Pad (letters only, hit Enter to skip): ")
        ).upper()

        # Output results
        encrypt_type = "Encrypted" if encrypt else "Decrypted"
        if encrypt:

            # Encrypt the string, apply one-time pad, then split into chunks
            # of five characters
            message = cipher.one_time_pad(cipher.encrypt(message), pad_key,
                                          encrypt)
            message = cipher.chunks_of_five(message)
            encrypt_type = "Encrypted"
        else:

            # Remove one-time pad, then decrypt the string
            message = cipher.decrypt(
                cipher.one_time_pad(message, pad_key, encrypt))
            encrypt_type = "Decrypted"
        print("{} string: {}".format(encrypt_type, message))

        # Restart loop on user input
        again = input("Encrypt or decrypt something else? (Y/n) ").upper()
        if again == 'N':
            break
def encrypt_decrypt():
    """Encrypt or decrypt text."""

    playing = True

    while playing:
        #User input
        cipher = int(
            input("Enter the number associated with cipher you wish to use: "))
        text = input("What is your message: ")
        choice = input(
            "Are you going to encrypt or decrypt? Enter E or D: ").lower()
        print("\n")

        if choice == "e":
            #Generates affine cipher
            if cipher == 1:
                affine = Affine()
                print(affine.encrypt(text))
                playing = False

            #Generates atbash cipher
            elif cipher == 2:
                atbash = Atbash()
                print(atbash.encrypt(text))
                playing = False

            #Generates keyword cipher
            elif cipher == 3:
                #Ask user keyword
                secret_key = input("Enter your keyword: ")
                keyword = Keyword()
                print("\n")
                print(keyword.encrypt(text, secret_key))
                playing = False

            elif cipher == 4:
                caesar = Caesar()
                print(caesar.encrypt(text))
                playing = False

        if choice == "d":
            #Decrypts affine cipher
            if cipher == 1:
                affine = Affine()
                print(affine.decrypt(text))
                playing = False

            #Decrypts atbash cipher
            elif cipher == 2:
                atbash = Atbash()
                print(atbash.decrypt(text))
                playing = False

            #Decrypts keyword cipher
            elif cipher == 3:
                secret_key = input("Enter your keyword: ")
                keyword = Keyword()
                print("\n")
                print(keyword.decrypt(text, secret_key))
                playing = False

            elif cipher == 4:
                caesar = Caesar()
                print(caesar.decrypt(text))
                playing = False

    #Asks user to play again or not
    else:
        if input("\nDo you want to contine? Y/N: ").lower() == "y":
            welcome()
            encrypt_decrypt()
        else:
            print("See you next time!")
Exemplo n.º 9
0
def main():
    """prints menu gathers user input and instantiates cipher objects:

        prints gerneral interface for the program first implementatio
        of print is Secret Messages and then each cipher is listed
        on its own line. 'eord' is an input meant to gather
        wehether user wants to encrypt or decyrpt a message and stores
        that response. 'cipher' is input meant to gather
        which cipher user to accomplish encryption / decryption and stores
        that response. Exception raised if user cipher input not in cipher
        listif/elif consume 'eord', 'cipher' instantiate objects:
        Caesar, Affine, Atbash, Keyw based upon input stored
        'eord' and 'cipher'.'message' input stores user message
        to encrypt or decrypt" all object instantiation calls take message
        as argument. In additionAffine object instantion takes arguments :
        key_a and key_b. both of which are inputs if key_a and key_b
        out of range  exception will be raised. KeyW object instantation takes
        key as a argument"""

    print('Secret messages: \n\n')

    eord = input('would you like to encrypt or decrypt a message: ')

    cipher = input('which cipher: \n{}\n{}\n{}\n{}'.format(
        'Affine', 'Atbash', 'Caesar', 'Keyword\n\n'))

    if cipher.lower() not in ('affine', 'atbash', 'caesar', 'keyword'):
        raise Exception('not a valid choice')
    # Caesar cipher encrypt
    elif cipher.lower() == 'caesar' and eord.lower() == 'encrypt':
        message = input('please type a message to encrypt: ')
        A = Caesar()
        A.encrypt(message)
    # Caesar cipher decrypt
    elif cipher.lower() == 'caesar' and eord.lower() == 'decrypt':
        message = input('please input message to decrypt: ')
        A = Caesar()
        A.decrypt(message)
    # Affine cipher encrypt
    elif cipher.lower() == 'affine' and eord.lower() == 'encrypt':
        key_a = input('for key_a acceptable choices are,'
                      '1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25: ')

        if int(key_a) not in (1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25):
            raise Exception('this key would not work')
        else:
            key_b = input('for key_b choose a number 1 - 25')
            if int(key_b) not in (range(25)):
                raise Exception('This is not a valid choice')

        message = input('please type a message to encrypt: ')
        A = Affine()
        A.encrypt(message, int(key_a), int(key_b))
    # Affine cipher decrypt
    elif cipher.lower() == 'affine' and eord.lower() == 'decrypt':
        key_a = input('for key_a acceptable choices are'
                      '1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25: ')

        if int(key_a) not in (1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25):
            raise Exception('this key would not work')
        else:
            key_b = input('for key_b choose a number 1 - 25')
            if int(key_b) not in (range(25)):
                raise Exception('This is not a valid choice')

        message = input('please type a message: ')
        A = Affine()
        A.decrypt(message, int(key_a), int(key_b))
    # Attbash cipher encrypt
    elif cipher.lower() == 'atbash' and eord.lower() == 'encrypt':
        message = input('please type a message: ')
        A = Atbash()
        A.encrypt(message)
    # Attbash cipher decrypt
    elif cipher.lower() == 'atbash' and eord.lower() == 'decrypt':
        message = input('please type a message: ')
        A = Atbash()
        A.decrypt(message)
    # Keyword cipher encrypt
    elif cipher.lower() == 'keyword' and eord.lower() == 'encrypt':
        key = input('please type a keyword for encryption: ')
        message = input('please type a message: ')
        A = Keyw()
        A.encrypt(message, key)
    # Keyword cipher decrypt
    elif cipher.lower() == 'keyword' and eord.lower() == 'decrypt':
        key = input('please type the key: ')
        message = input('please type a message: ')
        A = Keyw()
        A.decrypt(message, key)
Exemplo n.º 10
0
def main():
    symbols = string.ascii_lowercase

    # first argument is the cipher
    cipher = sys.argv[1]

    # second arugment is the key
    key = sys.argv[2]

    # 3rd argument is the encrypt/Decrypt
    mode = sys.argv[3]

    # 4th argument is the input text
    input_txt = sys.argv[4]

    # 5th arugment is the output text
    output_txt = sys.argv[5]

    plainText = ''
    cipherText = ''

    text = open(input_txt)
    if mode == 'encrypt':
        plainText = text.read()
    if mode == 'decrypt':
        cipherText = text.read()

    if cipher == 'caesar' or cipher == 'Caesar':
        caesar = Caesar(key, symbols)
        if mode == 'encrypt':
            cipherText = open(output_txt, 'w')
            cipherText.write(caesar.encrypt(plainText))
            cipherText.close()
        if mode == 'decrypt':
            plainText = open(output_txt, 'w')
            plainText.write(caesar.decrypt(cipherText))
            plainText.close()

    if cipher == 'playfair' or cipher == 'Playfair':
        playfair = Playfair(key)
        if mode == 'encrypt':
            cipherText = open(output_txt, 'w')
            cipherText.write(playfair.encrypt(plainText))
            cipherText.close()
        if mode == 'decrypt':
            plainText = open(output_txt, 'w')
            plainText.write(playfair.decrypt(cipherText))
            plainText.close()

    if cipher == 'vigenere' or cipher == 'Vigenere':
        vigenere = Vigenere(key, symbols)
        if mode == 'encrypt':
            cipherText = open(output_txt, 'w')
            cipherText.write(vigenere.encrypt(plainText))
            cipherText.close()
        if mode == 'decrypt':
            plainText = open(output_txt, 'w')
            plainText.write(vigenere.decrypt(cipherText))
            plainText.close()

    if cipher == 'transposition' or cipher == 'Transposition':
        transposition = Transposition(key)
        if mode == 'encrypt':
            cipherText = open(output_txt, 'w')
            cipherText.write(transposition.encrypt(plainText))
            cipherText.close()
        if mode == 'decrypt':
            plainText = open(output_txt, 'w')
            plainText.write(transposition.decrypt(cipherText))
            plainText.close()

    if cipher == 'railfence' or cipher == 'Railfence':
        rail = RailFence(key)
        if mode == 'encrypt':
            cipherText = open(output_txt, 'w')
            cipherText.write(rail.encrypt(plainText))
            cipherText.close()
        if mode == 'decrypt':
            plainText = open(output_txt, 'w')
            plainText.write(rail.decrypt(cipherText))
            plainText.close()
Exemplo n.º 11
0
    elif args['SHOULD_DECRYPT']:
        decrypted = substitution.decrypt(text)
        print(decrypted)

elif args['CIPHER'] == 'VIGENERE':
    vigenere = Vigenere()

    if args['SHOULD_ENCRYPT']:
        key = args['ENCRYPTION_KEY']
        encrypted = vigenere.encrypt(text, key)
        print(encrypted)

    elif args['SHOULD_DECRYPT']:
        key_length = args['VIGENERE_KEY_LENGTH']
        decrypted = vigenere.decrypt(text, key_length)
        print(decrypted)

elif args['CIPHER'] == 'CAESAR':
    caesar = Caesar()

    if args['SHOULD_ENCRYPT']:
        key = args['ENCRYPTION_KEY']
        encrypted = caesar.encrypt(text, key)
        print(encrypted)

    elif args['SHOULD_DECRYPT']:
        decrypted = caesar.decrypt(text)
        print(decrypted)
else:
    print("PLEASE ENTER A VALID CIPHER TYPE")
    def run_cipher():
        print(
            "This is the Secret Message project for the Treehouse Techdegree. \n"
        )
        user_choice = input(
            "Would you like to encrypt or decrypt a message? \n \n")

        if user_choice.lower() == "encrypt":
            text = input("What message would you like to encrypt? \n \n")
            cipher_type = input(
                "Which cipher would you like to use to encrypt? \n"
                "\n - Keyword"
                "\n - Atbash"
                "\n - Affine"
                "\n - Caesar \n"
                "\n")

            #Keyword Cipher
            if cipher_type.lower() == "keyword":
                secret_keyword = input(
                    "Great Choice! What is your keyword? \n \n")
                keyword = Keyword()
                print('\n')
                print(keyword.encrypt(text, secret_keyword))

            #Atbash Cipher
            elif cipher_type.lower() == "atbash":
                atbash = Atbash()
                print('\n')
                print(atbash.encrypt(text))

            #Affine Cipher
            elif cipher_type.lower() == "affine":
                affine = Affine()
                print('\n')
                print(affine.encrypt(text))

            #Caesar Cipher
            elif cipher_type.lower() == "caesar":
                caesar = Caesar()
                print('\n')
                print(caesar.encrypt(text))

            elif ValueError:
                print(" \nSorry, {} is not a choice!".format(cipher_type))
                run_cipher()

        elif user_choice.lower() == "decrypt":
            text = input("What message would you like to decrypt? \n \n")
            cipher_type = input(
                "Which cipher would you like to use to decrypt? \n"
                "\n - Keyword"
                "\n - Atbash"
                "\n - Affine"
                "\n - Caesar \n"
                "\n")

            #Keyword Cipher
            if cipher_type.lower() == "keyword":
                secret_keyword = input(
                    "Great Choice! What is your keyword? \n \n")
                keyword = Keyword()
                print('\n')
                print(keyword.decrypt(text, secret_keyword))

            #Atbash Cipher
            elif cipher_type.lower() == "atbash":
                atbash = Atbash()
                print(atbash.decrypt(text))

            #Affine Cipher
            elif cipher_type.lower() == "affine":
                affine = Affine()
                print('\n')
                print(affine.decrypt(text))

            #Caesar Cipher
            elif cipher_type.lower() == "caesar":
                caesar = Caesar()
                print('\n')
                print(caesar.decrypt(text))

            #If the cipher type is not a choice
            elif ValueError:
                print(" \nSorry, {} is not a choice!".format(cipher_type))
                run_cipher()

        elif ValueError:
            print("{} wasn't an option. \n".format(user_choice))
            run_cipher()