コード例 #1
0
ファイル: appMenu.py プロジェクト: DimBitsas/Project2
def app_menu():
    """Application menu"""
    enc_dec_choice = input(encrypt_decrypt_prompt).upper()
    if enc_dec_choice != encrypt and enc_dec_choice != decrypt:
        sys.exit()

    algorithm_choice = input(cipher_prompt).upper()

    if algorithm_choice == cipher_keyword:
        keyword_obj = KeywordCipher(input("PROVIDE KEYWORD\n"))
        if enc_dec_choice == encrypt:
            encryption_res = keyword_obj.encrypt(input(user_input_encrypt__prompt))
        else:
            decryption_result = keyword_obj.decrypt(input(user_input_decrypt__prompt))
    elif algorithm_choice == cipher_atbash:
        atbash_obj = Atbash()
        if enc_dec_choice == encrypt:
            encryption_res = atbash_obj.encrypt(input(user_input_encrypt__prompt))
        else:
            decryption_result = atbash_obj.decrypt(input(user_input_decrypt__prompt))
    elif algorithm_choice == cipher_affine:
        affine_obj = Affine()
        print("\nValid values for a factor: {0}".format(a_possible_values))
        a = check_a_factor(int(input(a_factor_prompt)))
        b = int(input(b_factor_prompt))
        if enc_dec_choice == encrypt:
            encryption_res = affine_obj.encrypt(input(user_input_encrypt__prompt), a, b)
        else:
            decryption_result = affine_obj.decrypt(input(user_input_decrypt__prompt), a, b)
    else:
        sys.exit()

    (print("ENCRYPTED STRING: {0}".format(encryption_res)) if enc_dec_choice == encrypt else
     print("DECRYPTED STRING: {0}".format(decryption_result)))
コード例 #2
0
def test_atbash_encrypt():
    plaintext = ciphertexts['plaintext']
    desired_ciphertext = ciphertexts['Atbash']

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

    assert encrypted_text == desired_ciphertext
コード例 #3
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)
コード例 #4
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))
コード例 #5
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()
コード例 #6
0
    def call_cipher(self):
        """
        Calls the cipher selected by the user.
        Encrypts using the selected cipher
        then encrypts that cipher text with a one time pad.  Decrypts the otp
        first then passes the result to the selected cipher for decryption.
        Cipher text is output in uppercase, decrypted plain text is output
        in lowercase.
        """
        if self.cipher_choice == "affine":

            if self.crypt == "encrypt":
                encrypted_message = Affine().encrypt(self.message.upper())
                otp_encrypted = OneTimePad().encrypt(encrypted_message,
                                                     self.otp.upper())
                return (otp_encrypted)

            elif self.crypt == "decrypt":
                otp_decrypted = OneTimePad().decrypt(self.message.upper(),
                                                     self.otp.upper())
                decrypted_message = Affine().decrypt(otp_decrypted)
                return (decrypted_message.lower())

        elif self.cipher_choice == "atbash":

            if self.crypt == "encrypt":
                encrypted_message = Atbash().encrypt(self.message.upper())
                otp_encrypted = OneTimePad().encrypt(encrypted_message,
                                                     self.otp.upper())
                return (otp_encrypted)

            elif self.crypt == "decrypt":
                otp_decrypted = OneTimePad().decrypt(self.message.upper(),
                                                     self.otp.upper())
                decrypted_message = Atbash().decrypt(otp_decrypted)
                return (decrypted_message.lower())

        elif self.cipher_choice == "keyword":

            if self.crypt == "encrypt":
                encrypted_message = KeywordCipher().encrypt(
                    self.message.upper())
                otp_encrypted = OneTimePad().encrypt(encrypted_message,
                                                     self.otp.upper())
                return (otp_encrypted)

            elif self.crypt == "decrypt":
                otp_decrypted = OneTimePad().decrypt(self.message.upper(),
                                                     self.otp.upper())
                decrypted_message = KeywordCipher().decrypt(otp_decrypted)
                return (decrypted_message.lower())
コード例 #7
0
def get_messages():
    cipher = ""
    print("This is the Secret Messages Project for the Treehouse Techdegree.")
    user_prompt = "These are the current available ciphers:\n"
    user_prompt += "-(At)bash-\n"
    user_prompt += "-(K)eyword-\n"
    user_prompt += "-(P)olybius Square-\n"
    user_prompt += "-(Q)uit\n"

    while cipher not in ['at', 'k', 'p', 'q']:
        print(user_prompt)
        cipher = input("Which cipher would you like to use?\n>>>").lower()
        clear_screen()
        if cipher == 'at':
            cipher = Atbash()
        elif cipher == 'k':
            cipher = KeywordCipher()
        elif cipher == 'p':
            cipher = PolybiusSquare()
        elif cipher == 'q':
            break
        else:
            print(
                "Sorry, I didn't get that.  Please choose from the list again."
            )
            print(user_prompt)

        message = input("What is your message?").lower()

        choice = input(
            "Would you like to (e)ncrypt or (d)ecrypt the message?").lower()
        if choice == 'e':
            cipher.encrypt(message)
        else:
            cipher.decrypt(message)
コード例 #8
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
コード例 #9
0
def atbash_encrypt():
    """ encrypts using the atbash cipher """

    user_message = input("What would you like to encrypt? ")

    encrypted_bifid_message = Atbash(user_message).encrypt()
    print(
        "Great! Your encrypted message is: {}".format(encrypted_bifid_message))
コード例 #10
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()
コード例 #11
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))
コード例 #12
0
def atbash_decrypt():
    """decrypts a message using the atbash cipher"""

    user_encrypted_message = input("What would you like to decrypt? ")
    user_decrypted_message = Atbash(user_encrypted_message).decrypt(
        user_encrypted_message)
    print("Your message reads: {}".format(user_decrypted_message))
    another_one = input(
        "If you would like to use another cipher? Type 'Y/N' Or type 'Start Over' to restart. Or 'q' to quit. "
    ).lower()
    if another_one == 'y':
        my_cipher.another_cipher()
    elif another_one == 'start over':
        my_cipher.start_over()
    elif another_one == 'q':
        print("Great Thanks for using the Atbash Cipher!")
コード例 #13
0
def script():
    """Runs the script for the command line menu, asking the user
    for the message to encrypt/decrypt"""
    atb = Atbash()
    key = Keyword()
    poly = Polybius()
    choose_cipher = input("Which one do you want to use? ")

    if choose_cipher.upper() == "ATBASH":
        action = user_input()
        if action.upper() == "ENCRYPT":
            print(encrypt_it(atb))
        elif action.upper() == "DECRYPT":
            print(decrypt_it(atb))
        else:
            print("Sorry I didn't understand that...\n")

    elif choose_cipher.upper() == "KEYWORD":
        our_keyword = input("What keyword would you like to use? ")
        key.get_keyword(our_keyword)
        action = user_input()
        if action.upper() == "ENCRYPT":
            print(encrypt_it(key))
        elif action.upper() == "DECRYPT":
            print(decrypt_it(key))
        else:
            print("Sorry I didn't understand that...\n")

    elif choose_cipher.upper() == "POLYBIUS":
        action = user_input()
        if action.upper() == "ENCRYPT":
            print(encrypt_it(poly))
        elif action.upper() == "DECRYPT":
            print(decrypt_it(poly))
        else:
            print("Sorry I didn't understand that...\n")

    else:
        print("I didn't understand that, please try again!\n")

    # ask the user if he wants to encrypt/decrypt something else
    encrypt_more = input("Encrypt or decrypt something else? Y/N ")
    if encrypt_more.upper() != "N":
        script()
    else:
        print("Thank you, bye!")
コード例 #14
0
def __atbash_cipher(encrypt_or_decrypt, working_text):
    # Run Atbash encryption
    if encrypt_or_decrypt == "encryption":
        atbash_encryption = Atbash()
        __clear()
        return atbash_encryption.encrypt(working_text)

    # Run Atbash decryption
    elif encrypt_or_decrypt == "decryption":
        atbash_decryption = Atbash()
        __clear()
        return atbash_decryption.encrypt(working_text)
コード例 #15
0
def run_atbash_cipher():
    """this method prompts the user if they would like to encrypt or decrypt
    and runs the encrypt or decrypt method of this cipher
    """
    atbash = Atbash()
    while True:
        encrypt_decrypt = input("\nEnter 1 to encrypt. Enter 2 to decrypt: ")
        if encrypt_decrypt == '1':
            atbash.encrypt()
            break
        elif encrypt_decrypt == '2':
            atbash.decrypt()
            break
        else:
            print("\nTry again! That is not a valid choice!")
コード例 #16
0
def secret():

    while True:
        cipher = ''
        print("\nBelow are the available ciphers. Please pick one.")
        ciphers = ['Affine', 'Atbash', 'Keyword']
        for cipher in ciphers:
            print("-{}".format(cipher))

        cipher_choice = input("\nWhich cipher would you like to use? ")
        clear_screen()
        if cipher_choice.lower() == 'affine':
            cipher = Affine()
        elif cipher_choice.lower() == 'atbash':
            cipher = Atbash()
        elif cipher_choice.lower() == 'keyword':
            keyword = input("What would you like your keyword to be? ")
            cipher = Keyword(keyword)
        elif cipher_choice.lower() == 'q':
            quit_program()
        else:
            print("I'm sorry. Please choose a cipher from the list.")
            secret()

        message = input("What would you like your message to be? ")

        choice = input("Would you like to encrypt or decrypt a message?")

        if choice.lower() == 'encrypt':
            cipher.encrypt(message)
        elif choice.lower() == 'decrypt':
            cipher.decrypt(message)
        elif choice.lower() == 'q':
            quit_program()
        elif choice.lower() != 'encrypt' or 'decrypt':
            print("Please choose either encryption or decryption.")
            secret()
コード例 #17
0
 def test_atbash_decryption(self):
     return self.assertEqual(Atbash.decrypt("wVXIBKGRLM DRGS zGYZHS"),
                             "Decryption with Atbash")
コード例 #18
0
# NOTE: Prefer secret_messages.py for seeing functionality.
#       This was simply an extraction of that script for a
#       targeted purpose.
#       It is not up-to-date as of 06/12/18.

import os

from atbash import Atbash
from affine import Affine
from caesar import Caesar
from polybius_square import Polybius

if __name__ == '__main__':
    ciphers = {key: cipher_name for key, cipher_name in 
        zip(range(1, 5), [Affine(), Atbash(), Caesar(), Polybius()])}

    def clear_screen():
        os.system("cls" if os.name == "nt" else "clear")


    def select_cipher():
        while(True):        
            for key, value in ciphers.items():
                print("{}) {}".format(key, value.__class__.__name__))
            
            try:
                cipher_choice = int(input ("\nEnter a number from the options above:  "))
                if cipher_choice not in ciphers.keys():
                    raise ValueError("Please select one of the available options.")
            except ValueError:
コード例 #19
0
ファイル: app.py プロジェクト: whiletrace/Python_Proj2
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)
コード例 #20
0
def main():
    ''' Main(), has available ciphers and runs a while loop to correct for errors.
    Asks for one of the ciphers and runs cipher classes based on the answers.
    Second while loop corrects for Encryption/Decryption input. After cipher classes run
    in second loop, user is asked if he/she would like to play through the loop again.
    '''

    #  First while loop and available cipher list
    available = ["keyword", "atbash", "affine"]
    run = True

    while run:
        play = True
        #  Prints "Main Menu" and asks for choice of cipher
        print(
            "Welcome to the secret messages program!\n\nHere are the available ciphers: "
        )
        print("-Keyword\n-Atbash\n-Affine")
        print(
            "Select a cipher or type \"QUIT\" before the program starts to exit!\n"
        )
        user_input = input("What cipher would you like to use?\n>> ")

        if user_input.upper() == "QUIT":
            print("\nGoodbye!")
            break

        #  Checks user input for validity
        if user_input.lower() in available:
            play = True
        elif user_input.lower() not in available:
            print("That's not an option!\n")
            clear_screen()
            # print('\n' * 80) = Pseudo clear_screen() for Py Charm, ONLY FOR USE ON PYCHARM
            continue

        while play:
            #  3 part for loop to run cipher encode/decode based on user input choice
            if user_input.lower() == "keyword":
                #  Keyword class start
                play_game = Keyword()
                answer = input(
                    "Would you like to (E)ncrypt or (D)ecrypt?\n>> ")
                #  Check for validity answer
                if answer.upper() == "E":
                    print(play_game.encrypt())
                elif answer.upper() == "D":
                    print(play_game.decrypt())
                elif answer.upper() == "QUIT":
                    print("\nGoodbye!")
                    run = False
                    break
                else:
                    print("Wrong input! Try \"E\" or \"D\"!\n")
                    continue
            elif user_input.lower() == "atbash":
                #  Atbash class start
                play_game = Atbash()
                answer = input(
                    "Would you like to (E)ncrypt or (D)ecrypt?\n>> ")
                #  Check for validity answer
                if answer.upper() == "E":
                    print(play_game.encrypt())
                elif answer.upper() == "D":
                    print(play_game.decrypt())
                elif answer.upper() == "QUIT":
                    print("\nGoodbye!")
                    run = False
                    break
                else:
                    print("Wrong input! Try \"E\" or \"D\"!\n")
                    continue
            elif user_input.lower() == "affine":
                #  Affine class start
                play_game = Affine()
                answer = input(
                    "Would you like to (E)ncrypt or (D)ecrypt?\n>> ")
                #  Check for validity answer
                if answer.upper() == "E":
                    print(play_game.encrypt())
                elif answer.upper() == "D":
                    print(play_game.decrypt())
                elif answer.upper() == "QUIT":
                    print("\nGoodbye!")
                    run = False
                    break
                else:
                    print("Wrong input! Try \"E\" or \"D\"!\n")
                    continue

            #  Ask user to play again, if yes clear and play again, else close both loops
            play = input("Would you like to play again (Y or N)?\n>> ")
            if play.upper() == "Y":
                clear_screen()
                break
            elif play.upper() == "N":
                print("Hope you had a good time!")
                play = False
                run = False

        continue
コード例 #21
0
ファイル: test.py プロジェクト: ykurata/techdegree-project-2
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 the 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

        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

    #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!")
コード例 #22
0
            # 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 "
                  "key of: BGWKZQPNDSIOAXEFCLUMTHYVR")
            while True:
                key = input(
                    "Enter a string of 25 characters (A-Z minus J): ").upper()

                # Handles the case where user wants to use default key
                if not key:
                    break
コード例 #23
0
def run_cipher(encrypt=True):
    """Sub menu with a list of implemented ciphers."""
    global key_val     
    clear()
    prompt = "Choose a cipher to use:\n\n"
    prompt += "1) (Af)fine\n"
    prompt += "2) (At)bash\n"
    prompt += "3) (K)eyword\n\n"
    prompt += "Type (q) to quit.\n"


    user_input = input(prompt)

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

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

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

    def ask_for_message():
        val_input = input("Enter message:\n")

        return val_input

    text = ask_for_message()

    while text.lower().isalpha() is False:
        print("Message must contain letters only.\n")
        text = ask_for_message()

    # 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("Message must contain letters only.\n")
            user_keyword = input("Please enter keyword for the Keyword Cipher:\n")

        cipher = Keyword(user_keyword)
    
    if encrypt:
        key_val = cipher.encrypt(text)

    else:
        key_val = cipher.decrypt(text)

    
    return key_val
コード例 #24
0
    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()
コード例 #25
0
def play():
    """
    Asks the user what cipher he wants to use,
    in order to encrypt or decrypt a text message.
    Gives user the option to return the cipher text in 5 characters blocks.
    Asks user for different input based on cipher selection.
    Adds a onetime pad as an additional security layer.
    If encrypting:
    Returns cipher text encrypted with the chosen cipher and onetime pad.
    If decrypting:
    Returns text decrypted with the chosen cipher and onetime pad.
    """
    working = True
    cipher_choice = True
    enc_dec = True
    letters = string.ascii_uppercase
    while working:
        clear_screen()
        print(
            "This is the Secret Messages project for the Treehouse Techdegree. \n"
            "These are the current available ciphers: \n"
            "- Affine \n"
            "- Atbash \n"
            "- Caesar \n"
            "- Keyword \n"
            "- Type (Q) to quit. \n")
        while cipher_choice:
            choice = input(
                "Type the name of the cipher would you like to use? \n")
            if choice.upper() == 'Q':
                exit()
            elif choice.upper() == 'AFFINE':
                cipher = Affine()
                break
            elif choice.upper() == 'ATBASH':
                cipher = Atbash()
                break
            elif choice.upper() == 'CAESAR':
                cipher = Caesar()
                break
            elif choice.upper() == 'KEYWORD':
                cipher = Keyword()
                break
            else:
                print('Type the name of any available cipher. \n')

        user_text = input('What is your message?(Letters only) \n')

        while enc_dec:
            e_or_d = input('Are we going to encrypt or decrypt? \n')
            if e_or_d.upper() == 'ENCRYPT' and isinstance(cipher, Affine):
                alpha, beta = get_keys()
                ot_pad = input('Type your one time pad. \n')
                ot_val = cipher.one_time_pad(user_text, ot_pad)
                value = cipher.encrypt(ot_val, alpha, beta)
                block_choice = yes_or_no()
                if block_choice.upper() == 'Y':
                    value = cipher.add_padding(value)
                    print(value + '\n')
                    repeat()
                    break
                else:
                    print(value + '\n')
                    repeat()
                    break
            elif e_or_d.upper() == 'DECRYPT' and isinstance(cipher, Affine):
                alpha, beta = get_keys()
                ot_pad = input(
                    'Type your one time pad, must be the same used for encrypting. \n'
                )
                block_choice = y_o_n()
                if block_choice.upper() == 'Y':
                    no_block = cipher.remove_padding(user_text)
                    value = cipher.decrypt(no_block, alpha, beta)
                    ot_val = cipher.one_time_pad(value, ot_pad, encrypt=False)
                    print(ot_val + '\n')
                    repeat()
                    break
                else:
                    value = cipher.decrypt(user_text, alpha, beta)
                    ot_val = cipher.one_time_pad(value, ot_pad, encrypt=False)
                    print(ot_val + '\n')
                    repeat()
                    break
            elif e_or_d.upper() == 'ENCRYPT' and isinstance(cipher, Atbash):
                ot_pad = input('Type your one time pad. \n')
                ot_val = cipher.one_time_pad(user_text, ot_pad)
                value = cipher.encrypt(ot_val)
                block_choice = yes_or_no()
                if block_choice.upper() == 'Y':
                    value = cipher.add_padding(value)
                    print(value + '\n')
                    repeat()
                    break
                else:
                    print(value + '\n')
                    repeat()
                    break
            elif e_or_d.upper() == 'DECRYPT' and isinstance(cipher, Atbash):
                ot_pad = input(
                    'Type your one time pad, must be the same used for encrypting. \n'
                )
                block_choice = y_o_n()
                if block_choice.upper() == 'Y':
                    no_block = cipher.remove_padding(user_text)
                    value = cipher.decrypt(no_block)
                    ot_val = cipher.one_time_pad(value, ot_pad, encrypt=False)
                    print(ot_val + '\n')
                    repeat()
                    break
                else:
                    value = cipher.decrypt(user_text)
                    ot_val = cipher.one_time_pad(value, ot_pad, encrypt=False)
                    print(ot_val + '\n')
                    repeat()
                    break
            elif e_or_d.upper() == 'ENCRYPT' and isinstance(cipher, Caesar):
                ot_pad = input('Type your one time pad. \n')
                ot_val = cipher.one_time_pad(user_text, ot_pad)
                value = cipher.encrypt(ot_val)
                block_choice = yes_or_no()
                if block_choice.upper() == 'Y':
                    value = cipher.add_padding(value)
                    print(value + '\n')
                    repeat()
                    break
                else:
                    print(value + '\n')
                    repeat()
                    break
            elif e_or_d.upper() == 'DECRYPT' and isinstance(cipher, Caesar):
                ot_pad = input(
                    'Type your one time pad, must be the same used for encrypting. \n'
                )
                block_choice = y_o_n()
                if block_choice.upper() == 'Y':
                    no_block = cipher.remove_padding(user_text)
                    value = cipher.decrypt(no_block)
                    ot_val = cipher.one_time_pad(value, ot_pad, encrypt=False)
                    print(ot_val + '\n')
                    repeat()
                    break
                else:
                    value = cipher.decrypt(user_text)
                    ot_val = cipher.one_time_pad(value, ot_pad, encrypt=False)
                    print(ot_val + '\n')
                    repeat()
                    break
            elif e_or_d.upper() == 'ENCRYPT' and isinstance(cipher, Keyword):
                ot_pad = input('Type your one time pad. \n')
                keyword_choice = get_keyword()
                ot_val = cipher.one_time_pad(user_text, ot_pad)
                value = cipher.encrypt(ot_val, keyword_choice)
                block_choice = yes_or_no()
                if block_choice.upper() == 'Y':
                    value = cipher.add_padding(value)
                    print(value + '\n')
                    repeat()
                    break
                else:
                    print(value + '\n')
                    repeat()
                    break
            elif e_or_d.upper() == 'DECRYPT' and isinstance(cipher, Keyword):
                ot_pad = input(
                    'Type your one time pad, must be the same used for encrypting. \n'
                )
                block_choice = y_o_n()
                keyword_choice = get_keyword()
                if block_choice.upper() == 'Y':
                    no_block = cipher.remove_padding(user_text)
                    value = cipher.decrypt(no_block, keyword_choice)
                    ot_val = cipher.one_time_pad(value, ot_pad, encrypt=False)
                    print(ot_val + '\n')
                    repeat()
                    break
                else:
                    value = cipher.decrypt(user_text, keyword_choice)
                    ot_val = cipher.one_time_pad(value, ot_pad, encrypt=False)
                    print(ot_val + '\n')
                    repeat()
                    break
コード例 #26
0
required for specific ciphers.
"""
import os
from sys import exit

import utils.utils as utils
from affine import Affine
from atbash import Atbash
from caesar import Caesar
from polybius_square import Polybius

# Create keys for easier display and parsing selections in command line
ciphers = {
    key: cipher
    for key, cipher in zip(range(
        1, 5), [Affine(), Atbash(), Caesar(),
                Polybius()])
}
# Constants for operation selection logic
OPERATION_ENCRYPT = "ENCRYPT"
OPERATION_DECRYPT = "DECRYPT"


def select_cipher():
    """Returns a cipher reference based on user input"""
    while (True):
        for key, value in ciphers.items():
            print("{}) {}".format(key, value.__class__.__name__))

        cipher_choice = input(">>>  ")
コード例 #27
0
 def test_atbash_encryption(self):
     return self.assertEqual(Atbash.encrypt("Encryption with Atbash"),
                             "vMXIBKGRLM DRGS zGYZHS")
コード例 #28
0
ファイル: interface.py プロジェクト: sirelkhatim/Ciphers
    cipher_method= cipher_method.lower()
        

    #use OTP (one-time pad) to encrypt the message if the user wants to encrypt
    onetime= OnePad()
    if option=='encrypt':
        msg = onetime.encrypt(msg,one_pad)

    #Check that the user hasn't typed an invalid cipher method
    while cipher_method not in ["affine", "hill", "atbash"]:
        exit_program(cipher_method)
        cipher_method = input("Please enter a valid method: ")

    #Check which cipher method the user wants
    if cipher_method == "atbash":
        atbash = Atbash()
        #Encrypt or decrypt according to the users choice
        result = encrypt_decrypt(atbash, msg,option = option)

    elif cipher_method=="affine":
        key1 = input("please enter the key a here: ")
        exit_program(key1)
        key2 = input("enter the key b here: ")
        exit_program(key2)
        try:
            key1 = eval(key1)
            key2 = eval(key2)
        except:
            while type(key1)!=int and type(key2)!=int:
                key1 = input("Key must be an integer. please enter the key a here: ")
                key2 = input("Key must be an integer. enter the key b here: ")
コード例 #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
コード例 #30
0
def cipher_selection():
    """The first screen shows all the cipher options to encrypt and decrypt."""
    selection_ed = (input("To encrypt a message, press E.\n"
                          "To decrypt a message, press D.\n"
                          "To quit, press Q.\n")).upper()
    if selection_ed == 'E':
        cipher_option = (input("Please select one of these cipher options:\n"
                               "Affine: Press AFE\n"
                               "Atbash: Press ABE\n"
                               "Polybius: Press POE\n"
                               "To quit, press Q.\n")).upper()
        if cipher_option == "AFE":
            a = int(
                input(
                    'Enter an alpha. Available values: 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25\n'
                ))
            if a not in [3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25]:
                print('Alpha value is not accepted. Please try again.\n')
                a = int(
                    input(
                        'Enter an alpha. Available values: 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25\n'
                    ))
            b = int(input('Enter a beta value. Integer numbers only.\n'))
            text = (input('What is your message?\n')).upper()
            x = Affine(a, b)
            x.encrypt(text)
            menu_back()
        if cipher_option == 'ABE':
            text = (input('What is your message?\n')).upper()
            x = Atbash()
            x.encrypt(text)
            menu_back()
        if cipher_option == 'POE':
            text = (input('What is your message?\n')).upper()
            x = Polybius()
            x.encrypt(text)
            menu_back()
        if cipher_option == 'Q':
            print('You quit.\n')
            os.system('clear')
        else:
            print('Not valid. Please try again.')
            menu_back()

    if selection_ed == 'D':
        cipher_option = (input("Please select one of these cipher options:\n"
                               "Affine: Press AFD\n"
                               "Atbash: Press ABD\n"
                               "Polybius: Press POD\n"
                               "To quit, enter Q.\n")).upper()
        if cipher_option == "AFD":
            a = int(
                input(
                    'Enter an alpha. Available values: 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25\n'
                ))
            b = int(input('Enter a beta value.\n'))
            text = (input('What is your message?\n')).upper()
            x = Affine(a, b)
            x.decrypt(text)
            menu_back()
        if cipher_option == 'ABD':
            text = (input('What is your message?\n')).upper()
            x = Atbash()
            x.decrypt(text)
            menu_back()
        if cipher_option == 'POD':
            text = (input('What is your message?\n')).upper()
            x = Polybius()
            x.decrypt(text)
            menu_back()
        else:
            print('Not valid. Please try again.\n')
            menu_back()
    if selection_ed == 'Q':
        print('You quit.\n')
        os.system('clear')
    else:
        print('Not valid.\n')
        menu_back()