Example #1
0
def main():

    message = input("Enter message: ")
    key = int(input("Enter key: "))
    remove_spaces = input("Remove spaces <y/n>?: ")
    if remove_spaces.upper() == 'Y':
        message = ''.join(message.split())
    #explanation of reversed_blocks:
    #ex. if the length of the message is 10
    #and it is encrypted using a key of 2
    #then after encryption, every block of 5 letters in the message will be reversed
    reversed_blocks = input("Reversed blocks <y/n>?: ")
    rb = True if reversed_blocks.upper() == 'Y' else False
    mode = input("Mode? <encrypt/decrypt>: ")
    if mode.upper() == 'ENCRYPT':
        filler = input("Filler = ")
        plaintext = encrypt(key, message, filler=filler, reversed_blocks=rb)
    elif mode.upper() == 'DECRYPT':
        plaintext = decrypt(key, message, reversed_blocks=rb)
    else:
        plaintext = "ERROR: Invalid mode"
    # Print with a | ("pipe" character) after it in case
    # there are spaces at the end of the decrypted message.
    print(plaintext + '|')
    print()
    pyperclip.copy(plaintext)
    print("<Copied to clipboard>")
    print("Warning: do not copy this manually because there is a pipe character at the end of the message that"
          " will mess up decryption.")
Example #2
0
def main():
    message = input("Message: ")
    remove_spaces = input("Remove spaces <y/n>?: ")
    #inp validation
    while not remove_spaces.upper() in 'YN':
        remove_spaces = input("Remove spaces <y/n>?: ")

    if remove_spaces.upper() == 'Y':
        message = ''.join(message.split())

    mode = input("Encrypt/decrypt <e/d>: ")
    # inp validation
    while not mode.upper() in 'ED':
        mode = input("Encrypt/decrypt <e/d>: ")

    key = int(input("Key = "))

    if mode.upper() == 'E':
        p = encrypt(message, key)
    else:
        p = decrypt(message, key)

    print(p + '|')
    copy(p)
    print("<Copied to clipboard>")
    print(
        "Warning: do not copy this manually because there is a pipe character at the end of the message that"
        " will mess up decryption.")
Example #3
0
def main():
    message = input("Enter a message: ")
    remove = input("Remove spaces? [y/n]: ")
    if remove == 'y':
        message = message.replace(' ', '')

    raw_inp = input("Enter key: ")
    try:
        # if converting it to a tuple doesn't work
        key = get_permutation((convert_to_tuple(list(raw_inp))))
    except ValueError:
        # it must be a string key
        key = key_permutation(raw_inp)
        #
    offset = int(input("Enter offset: "))

    mode = input("Mode <encrypt/decrypt>?: ")

    if mode.upper() == 'ENCRYPT':
        ciphertext = encrypt(message, key, offset)
    else:
        ciphertext = decrypt(message, key, offset)

    # Print w/ a | ("pipe" character) in case there are any spaces
    # at the end of the message
    print(ciphertext + '|')
    print()
    pyperclip.copy(ciphertext)
    print("<Copied to clipboard>")
    print(
        "Warning: do not copy this manually because there is a pipe character at the end of the message that"
        " will mess up decryption.")
Example #4
0
def main():
    message = input("Enter a message: ")
    remove = input("Remove spaces? [y/n]: ")
    if remove == 'y':
        message = message.replace(' ', '')
    direction = input("Cipher direction <horizontal/vertical>?: ")
    #additional input --> n for the n-grams
    n = int(input("n = "))
    crack = input("Crack code? <y/n>: ")
    if crack == 'y':
        lower_bound = int(input("Enter lower bound: "))
        higher_bound = int(input("Enter higher bound: "))
        print()
        display_best_decryptions(message=message,
                                 direction=direction,
                                 lowerBound=lower_bound,
                                 higherBound=higher_bound,
                                 num_of_decryptions=10,
                                 n=n)

    else:
        raw_inp = input("Enter key: ")
        try:
            #if converting it to a tuple doesn't work
            key = get_permutation((convert_to_tuple(list(raw_inp))))
        except ValueError:
            #it must be a string key
            key = key_permutation(raw_inp)

        mode = input("Mode <encrypt/decrypt>?: ")
        filler = input("Filler = ")
        if mode == 'encrypt':
            if direction == 'horizontal':
                ciphertext = encrypt_horizontal(message, key, n, filler)
            else:
                ciphertext = encrypt_vertical(message, key, n, filler)
        else:
            if direction == 'horizontal':
                ciphertext = decrypt_horizontal(message, key, n)
            else:
                ciphertext = decrypt_vertical(message, key, n)

        # Print with a | ("pipe" character) after it in case there are spaces at
        # the end of the encrypted message.
        print(ciphertext + '|')

        # Copy the encrypted string in ciphertext to the clipboard.
        pyperclip.copy(ciphertext)
        print()
        print("<Copied to clipboard>")
        print(
            "Warning: do not copy this manually because there is a pipe character at the end of the message that"
            " will mess up decryption.")
Example #5
0
def print_best_solutions(scores_list):
    print(color.RED + color.BOLD + "10 BEST SOLUTIONS: " + color.END)
    print((color.BOLD + "%12s %18s %29s" + color.END) %
          ("Score:", "Alphabet:", "Message:"))
    for i in range(10):
        try:
            print("%-5d %-15.2f %-30s %-10s" %
                  (i + 1, scores_list[i][0], ''.join(
                      scores_list[i][1]), scores_list[i][2]))
        except IndexError:
            break

    pyperclip.copy(scores_list[0][2])
Example #6
0
def main():
    message = input("Enter message: ")
    key = int(input("Enter key: "))
    mode = input("Encrypt/Decrypt <e/d>?: ")
    if mode.upper() == 'E':
        res = encrypt(message, key)
    elif mode.upper() == 'D':
        res = decrypt(message, key)

    # Print with a | ("pipe" character) after it in case
    # there are spaces at the end of the decrypted message.
    print(res + "|")
    pyperclip.copy(res)
    print("<Copied to clipboard>")
    print(
        "Warning: do not copy this manually because there is a pipe character at the end of the message that"
        " will mess up decryption.")
Example #7
0
def main():
    message = input("Enter a message: ")
    remove = input("Remove spaces <y/n>?: ")
    if remove.upper() == 'Y':
        message = ''.join(message.split())
    mode = input("Encrypt or decrypt <e/d>?: ")
    start_index = int(input("Start index = "))
    skip = int(input("Skip = "))
    res = encrypt_skip(message, skip,
                       start_index) if mode.upper() == 'E' else decrypt_skip(
                           message, skip, start_index)

    # Print with a | ("pipe" character) after it in case
    # there are spaces at the end of the decrypted message.
    print(res + "|")
    pyperclip.copy(res)
    print("<Copied to clipboard>")
    print(
        "Warning: do not copy this manually because there is a pipe character at the end of the message that"
        " will mess up decryption.")
Example #8
0
def main():
    c = input("Enter a message: ")
    remove_spaces = input("Remove spaces <y/n>?: ")
    if remove_spaces.upper() == 'Y':
        c = ''.join(c.split())
    n = int(input("n = "))
    period = int(input("period = "))
    mode = input("Encrypt/Decrypt (e/d)?: ")
    if mode.upper() == 'E':
        res = nfid_encode(c, period, n)
    elif mode.upper() == 'D':
        res = nfid_decode(c, period, n)

    # Print with a | ("pipe" character) after it in case
    # there are spaces at the end of the decrypted message.
    print(res + "|")
    print()
    pyperclip.copy(res)
    print("<Copied to clipboard>")
    print(
        "Warning: do not copy this manually because there is a pipe character at the end of the message that"
        " will mess up decryption.")
Example #9
0
def main(ciphertext: str):

    try:
        parts = ast.literal_eval(ciphertext)
        #extract data from a saved list (if that is the input)
        ciphertext, bold_letters, non_bold_letters, replaced_characters = parts[
            0], parts[1], parts[2], parts[3]
    except (SyntaxError, ValueError):
        #otherwise if the input is not a list, assume that input is a normal ciphertext
        bold_letters = []
        non_bold_letters = get_distinct_ngrams(ciphertext, n=1)
        replaced_characters = []
    print()
    print_with_bolds(ciphertext)
    print()
    while True:
        character = input(
            "Enter a character to replace,'/UNDO' to undo a character replacement, '/FREQ' to view frequencies,\
'/RESET' to undo all character replacements, or '/Q' to save & quit: ")

        if character == '/Q':
            print()  #padding
            print("Your current message: ", end='')
            print_with_bolds(ciphertext)
            print()  #more padding
            save_list = str([
                ciphertext, bold_letters, non_bold_letters, replaced_characters
            ])
            print("Enter this next time to resume <copied to clipboard>: " +
                  save_list)
            pyperclip.copy(save_list)
            sys.exit(0)

        elif character.upper() == '/FREQ':
            print()
            print_special_frequency_analysis(''.join(ciphertext.split()),
                                             bold_letters, non_bold_letters,
                                             replaced_characters)
            print_with_bolds(ciphertext)
            print()
            continue

        elif character.upper() == '/RESET':
            print()
            ciphertext = reset_message(ciphertext)
            bold_letters.clear()
            non_bold_letters = get_distinct_ngrams(ciphertext, n=1)
            replaced_characters.clear()
            print_with_bolds(ciphertext)
            print()
            continue

        elif character in non_bold_letters:
            new_character = input("Enter replacement character: ")
            #intermediate ciphertext to indicate which letters are bold
            ciphertext = special_replace(ciphertext, character,
                                         new_character + BOLD_CHAR + character)
            #add an entry to replaced characters
            replaced_characters.append((character, new_character))
            #character has been bolded now -- remove from non-bolded
            non_bold_letters.remove(character)
            bold_letters.append(new_character)
            print()
            print_with_bolds(ciphertext)
            print()  #one extra line of padding

        elif character.upper() == '/UNDO':
            character_to_revert = input("Enter bolded character to revert: ")
            if character_to_revert in bold_letters:
                possible_reverts = [
                ]  #a list of possible bold mappings to revert
                for i in range(len(replaced_characters)):
                    if replaced_characters[i][1] == character_to_revert:
                        possible_reverts.append(replaced_characters[i][0])

                if len(possible_reverts) == 1:
                    reverted_character = possible_reverts[0]

                else:
                    print(
                        "The bolded character %s has been used to replace: " %
                        character_to_revert,
                        end='')
                    print(*possible_reverts)
                    reverted_character = input(
                        "Which of those characters would you like to see nonbolded? "
                    )
                    #input validation
                    while reverted_character not in possible_reverts:
                        reverted_character = input(
                            "Please enter one of the characters listed above: "
                        )

                # finally, do the replacement
                ciphertext = ciphertext.replace(
                    character_to_revert + BOLD_CHAR + reverted_character,
                    reverted_character)
                #update bold & non-bold letters lists
                bold_letters.remove(character_to_revert)
                non_bold_letters.append(reverted_character)
                #delete entry from replaced_characters
                replaced_characters.remove(
                    (reverted_character, character_to_revert))

                print()  #padding
                print_with_bolds(ciphertext)
                print()  #padding

            else:
                print(
                    "Invalid input -- character entered is not among bolded letters"
                )
                print()
                print_with_bolds(ciphertext)
                print()
                continue

        else:
            print(
                "Invalid input -- character entered is not among nonbolded letters"
            )
            print()
            print_with_bolds(ciphertext)
            print()
            continue
Example #10
0
def main(ciphertext: str):
    #check to see if ciphertext is a save list
    #if it is a save list, it MOST LIKELY WILL NOT APPEAR EXACTLY THE SAME due to order of operations if the
    #key does not go in evenly due to unknown order of operations (did it get inverted first or rows reversed first?)

    # declare booleans to use later
    inverted = False
    reversed_msg = False
    reversed_rows = False
    columnar = False

    try:
        parts = ast.literal_eval(ciphertext)
        #extract data from a saved list (if that is the input)
        ciphertext, key, column_nums = parts[0], parts[1], parts[2]
        grid = get_grid(ciphertext, key)
        #do the initial printout
        print()
        print_grid(grid, column_nums)

    except (SyntaxError, ValueError):

        remove_spaces = input("Remove spaces <y/n>?: ")
        # input validation
        while not remove_spaces.upper() in 'YN':
            remove_spaces = input("Remove spaces <y/n>?: ")
        if remove_spaces.upper() == 'Y':
            ciphertext = ''.join(ciphertext.split())

        ciphertext = ciphertext.upper()
        print()
        #show probable key lengths and prompt user to enter one
        length = len(ciphertext)
        print("The length of the message is %d." % length)
        print("Probable key lengths are: ", end='')
        print(*factors(length), sep=', ')
        print()
        key = input("Enter grid key: ")
        #input validation
        while not (key.isnumeric() and 0 < int(key) < len(ciphertext)):
            key = input("Please enter a valid grid key: ")

        key = int(key)  #key str --> int. This is also the # of columns

        print()  #padding
        print("TRANSPOSITION MANUAL DECRYPTION, Key = %d" % key)
        print()
        grid = get_grid(ciphertext, key)
        column_nums = list(range(1, key + 1))  #1-based index, not 0-based
        print_grid(grid, column_nums)

    while True:  #main loop

        character = input("""
S) switch two columns
C) change grid type (horizontal/vertical)
T) transpose/revert grid
R) reverse each row
M) reverse the entire message
K) change grid key
Q) save and quit\n""")
        #input validation
        while not character.upper() in 'SCTRMKQ':
            character = input(
                "Please enter 'S', 'C', 'T', 'R', 'M', 'K', or 'Q': ")

        if character.upper() == 'S':
            c_1 = input("Enter 1st column number: ")
            #input validation
            while not (c_1.isnumeric() and 0 < int(c_1) < key + 1):
                c_1 = input("Please enter a valid column number: ")

            c_2 = input("Enter 2nd column number: ")
            #more input validation
            while not (c_2.isnumeric() and 0 < int(c_2) < key + 1):
                c_2 = input("Please enter a valid column number: ")

            grid, column_nums = switch_columns(grid, int(c_1), int(c_2),
                                               column_nums)
            print()
            print_grid(grid, column_nums)

        elif character.upper() == 'C':
            print()  # padding
            columnar = not columnar
            if not columnar:  # if horizontal grid
                print(color.BOLD + "HORIZONTAL TRANSPOSITION GRID " +
                      color.END)
            else:  # otherwise if columnar grid
                print(color.BOLD + "COLUMNAR TRANSPOSITION GRID " + color.END)

            print()
            grid = get_columnar_grid(grid, columnar)
            print_grid(grid, column_nums)

        elif character.upper() == 'Q':
            print()  # padding
            print("Your message: ", end='')
            print(color.RED + color.BOLD + ''.join(grid) + color.END)
            print("Encryption Key = " + color.BOLD +
                  str(tuple(ngramTransposition.invert(column_nums))) +
                  color.END,
                  end='')
            print()  # even more padding
            save_list = str([''.join(grid), key, column_nums])
            print("Enter this next time to resume <copied to clipboard>: " +
                  save_list)
            pyperclip.copy(save_list)
            sys.exit(0)

        elif character.upper() == 'T':
            print()  #padding
            inverted = not inverted
            if not inverted:  #if horizontal view
                print("Read off the " + color.BOLD + "ROWS: " + color.END)
            else:  #otherwise if columns view
                print("Read off the " + color.BOLD + "COLUMNS: " + color.END)

            print()
            grid = invert_grid(grid, inverted)
            print_grid(grid, column_nums)

        elif character.upper() == 'R':
            print()  #padding
            reversed_rows = not reversed_rows
            if not reversed_rows:  # if horizontal view
                print("Read every row " + color.BOLD + "LEFT TO RIGHT: " +
                      color.END)
            else:  # otherwise if columns view
                print("Read every row " + color.BOLD + "RIGHT TO LEFT: " +
                      color.END)

            print()
            grid = reverse_rows(grid)
            column_nums = list(reversed(column_nums))
            print_grid(grid, column_nums)

        elif character.upper() == 'M':
            print()  # padding
            reversed_msg = not reversed_msg
            if not reversed_msg:  # if horizontal view
                print("Read the message " + color.BOLD + "LEFT TO RIGHT: " +
                      color.END)
            else:  # otherwise if columns view
                print("Read the message " + color.BOLD + "RIGHT TO LEFT: " +
                      color.END)

            print()
            grid = reverse(grid)
            print_grid(grid, column_nums)

        elif character.upper() == 'K':
            print()
            are_you_sure = input(
                "Are you sure you would like to change the grid key? "
                "This will erase all of your current progress <y/n>?: ")
            #input validation
            while not are_you_sure.upper() in 'YN':
                are_you_sure = input("Change grid key <y/n>?: ")

            if are_you_sure.upper() == 'N':
                print()
                continue

            else:
                print()  # padding
                #ask for the grid key
                length = len(ciphertext)
                print(
                    "Recall the length of the message is %d. Probable key lengths are: "
                    % length)
                print(*factors(length), sep=', ')
                print()
                key = input("Enter a grid key: ")
                #more input validation
                while not (key.isnumeric() and 0 < int(key) < len(ciphertext)):
                    key = input("Please enter a valid grid key: ")

                key = int(key)
                #reinitalize grid and column_nums
                grid = get_grid(ciphertext, key)
                column_nums = list(range(1, key + 1, 1))
                #print the new initialized grid
                print_grid(grid, column_nums)
Example #11
0
def main(ciphertext: str):

    print()
    #check to see if ciphertext is a save list
    try:
        parts = ast.literal_eval(ciphertext)
        #extract data from a saved list (if that is the input)
        ciphertext, columns, letter_shifts, view_columns = parts[0], parts[
            1], parts[2], parts[3]
        key = len(letter_shifts)
        #do the initial printout
        print_columns_with_bolds(columns, key, letter_shifts) if view_columns else \
            print_with_bolds(convert_to_rows_message(ciphertext, columns) + "\n")

    except (SyntaxError, ValueError):

        #show probable key lengths output
        print(probableKeyLengths.print_probable_key_lengths(msg=ciphertext))
        key = input(
            "Based on the output above, what do you think is the key length?: "
        )
        #input validation
        while not (key.isnumeric() and 0 < int(key) < len(ciphertext)):
            key = input("Please enter a valid key length: ")

        key = int(key)  #key str --> int. This is also the # of columns

        print()  #padding
        print("VIGENERE MANUAL DECRYPTION, L = %d" % key)
        columns = re.sub(nonletters, '', ciphertext).upper(
        )  #convert to uppercase & remove spaces for columns view
        print_columns_with_bolds(columns, key)
        # boolean to indicate viewing window
        view_columns = True
        letter_shifts = ['?'] * key
        print()  # padding
        print()

    while True:  #main loop

        character = input("""Enter a column number [1 - %d]
F) view overall frequencies of original message
V) change viewing window
R) reset message
Q) save and quit\n""" % key)

        #input validation
        while not (character.isnumeric() or character.upper() in 'FVRQ'):
            character = input(
                "Please enter a valid column number or 'F', 'V', 'R', or 'Q': "
            )

        if character.isnumeric():

            #input validation
            while not (0 < int(character) <= key):
                try:
                    character = input("Please enter a valid column number: ")
                except TypeError:
                    continue

            n = int(character)
            print_columns_with_bolds(columns, key, letter_shifts) if view_columns else \
                print_with_bolds("\n" + convert_to_rows_message(ciphertext, columns) + "\n")

            while True:
                print(color.BOLD + "COLUMN #%d: " % n + color.END, end='')
                print_with_bolds(get_nth_column(columns, key, n))
                print()  #padding
                character_2 = input("""F) View frequencies
H) highlight column in original message
S) Shift
R) Revert
B) Go Back\n""")

                while not character_2.upper() in 'HFSRB':
                    character_2 = input(
                        "Please enter 'F', 'H', 'S', 'R', or 'B': ")

                if character_2.upper() == 'H':
                    print()
                    print_highlighted_message(ciphertext, columns, key, n)
                    print()
                    continue
                elif character_2.upper() == 'B':  #go back
                    break
                elif character_2.upper() == 'F':  #frequencies
                    print_nth_column_frequencies(columns, key, n)
                    continue  #printing after this will hide the frequency analysis
                elif character_2.upper() == 'S':  #shift
                    nth_letter, m_new = shift_nth_column(columns, key, n)
                    letter_shifts[n - 1] = nth_letter
                    columns = m_new
                else:  #revert
                    columns = revert_nth_column(columns, key, n)
                    letter_shifts[n - 1] = '?'
                #print out the changed columns
                print_columns_with_bolds(columns, key, letter_shifts, BOLD_CHAR) if view_columns else \
                print_with_bolds("\n" + convert_to_rows_message(ciphertext, columns, BOLD_CHAR) + "\n")
                print()
            #do this even if user chooses "Go Back" so they don't have to scroll up
            print_columns_with_bolds(columns, key, letter_shifts, BOLD_CHAR) if view_columns else \
                print_with_bolds("\n" + convert_to_rows_message(ciphertext, columns, BOLD_CHAR))
            print()

        elif character.upper() == 'Q':
            print()  # padding
            print("Your message: ", end='')
            print_with_bolds(
                convert_to_rows_message(ciphertext, columns, BOLD_CHAR))
            print("Key = " + color.BOLD + ''.join(letter_shifts) + color.END,
                  end='')
            print()  # even more padding
            save_list = str([ciphertext, columns, letter_shifts, view_columns])
            print("Enter this next time to resume <copied to clipboard>: " +
                  save_list)
            pyperclip.copy(save_list)
            sys.exit(0)

        elif character.upper() == 'V':
            print()  #padding
            view_columns = not view_columns
            if not view_columns:  #if horizontal view
                print("Window changed to " + color.BOLD +
                      "HORIZONTAL VIEWING WINDOW: " + color.END)
                print()
                print_with_bolds(
                    convert_to_rows_message(ciphertext, columns, BOLD_CHAR))
                print()
            else:  #otherwise if columns view
                print("Window changed to " + color.BOLD + "COLUMNS VIEW: " +
                      color.END)
                print_columns_with_bolds(columns, key, letter_shifts,
                                         BOLD_CHAR)

        elif character.upper() == 'R':
            print()
            are_you_sure = input(
                "Are you sure you would like to reset? This will erase all of your current progress <y/n>?: "
            )
            #input validation
            while not are_you_sure.upper() in 'YN':
                are_you_sure = input("Reset <y/n>?: ")

            if are_you_sure.upper() == 'N':
                print()
                continue
            else:
                #set back to defaults
                start_over = input(
                    "Would you like to start over completely and try with a different key <y/n>?: "
                )
                #more input validation
                while not start_over.upper() in 'YN':
                    start_over = input("Reset <y/n>?: ")

                if start_over.upper() == 'N':
                    columns = re.sub(nonletters, '', ciphertext).upper()
                    letter_shifts = ['?'] * key
                    print_columns_with_bolds(columns, key, letter_shifts, BOLD_CHAR) if view_columns else \
                        print_with_bolds(convert_to_rows_message(ciphertext, columns, BOLD_CHAR))
                    continue

                else:  #starting over completely -- make a recursive call to the main function
                    main(ciphertext)

        elif character.upper() == 'F':
            print_special_frequency_analysis(ciphertext, default_input='Y')
            print()
            continue