Demo entry 1947251

asiduhasd

   

Submitted by anonymous on Jun 17, 2015 at 17:06
Language: Python 3. Code size: 5.9 kB.

import random #Imports the random module before everything.
import sys #allows me to exit the program.

#This function reads the file, catches any errors and returns read file.
def read_file():
    file_name = input('Enter the name of the file (without .txt) >> ')+'.txt' #Input allows the user to enter text.
    try: #Attempt to do the following:
        with open(file_name,'r') as file: #Opens file but closes it when it is done with it.
            return file.read()
    except IOError: #Catches all errors.
        print("That file does not exist!")
        return read_file() #Runs function again


#Splits text into chunks of a specified number (n).
def split_text(l, n):
    result = [] #Empty list.
    #Iteration
    for i in range(0,len(l),n):
        result.append(l[i:i+n])
    return result #Returns the text splitted.
    

#This function makes a new file and will be used to store the encrypted text.
def write_file(text):
    new_file_name = input('Enter the new file name (without .txt) >> ')+'.txt' #.txt adds the extension on the end so the user doesn't have to.
    with open(new_file_name, 'w') as file: #opens the file in write mode
        return file.write(text)

#Creates a random key and calculates the offset factor from it.
def offset():
    print() #new line
    print('Generating a random key: ')
    count = 0
    key = '' #Empty string
    while count <= 7: #The while loop counts up to 8 characters
        count += 1 #Adds on to count
        random_number = random.randrange(33,126) #Random number inbetween a given range
        key += chr(random_number) # 'chr' turns the number into an ASCII character.
    print (key) #Displays the key so he 
    print()
    total = 0
    for i in key:
        number = ord (i) #turns the UNICODE character back into an interger.
        total += number
    return (total//8)-32 #this equation calculates the offset.
    

        
                          




#This is the main body of the program which calls all the dependant functions.
def encrypt(encrypt, secure_mode):
    #Encrypting
    if encrypt:
        if secure_mode:
            print("Encrypting securely... \n")
            text = list(read_file())
            while " " in text:
                text.remove(" ")
            result = split_text(text,5)
        else:
            print('\nBasic Encryption')
            text = (read_file())
            result = text.split(' ')

        #This does the encrypting after the text file has been split up depending on the type of encryption
        offset_factor = offset()  #runs to get the offset factor and makes a variable to store it.
        encrypted_words = []
        for i in result: #for loop that goes through each word (separated into lists earlier)
            encrypted_list = []
            #Decrypting the individual characters.
            for j in i:
                number = ord(j)
                number += offset_factor
                if number > 126: 
                    number -= 94
                encrypted_number = chr(number)
                encrypted_list.append(encrypted_number)
            encrypted_words.append(''.join(encrypted_list)) #joins the letters together.
        encrypted = ' '.join(encrypted_words) #joins the word's list together and makes a variable for the encrypted text.
        print('Your encrypted text: \n'+encrypted)
        print()
        write_file(encrypted)
        
            
    else:
        #The decryption block
        print('\nDecryption\n')
        encrypted_text = (read_file())
        key = input('\nWrite the key that encrypted the text file >> ')
        total = 0
        for i in key:
            number = ord (i)
            total += number
        offset_factor = (total//8)-32
        #print(offset_factor)
        result = encrypted_text.split(' ')
        decrypted_words = []
        for i in result: #This for loop goes through the words.
            decrypted_list = []
            for j in i: #This for loop goes through the letters in those words.
                number = ord(j)
                number -= offset_factor
                if number < 33:
                    number += 94
                decrypted_number = chr(number)
                decrypted_list.append(decrypted_number)
            decrypted_words.append(''.join(decrypted_list))
        decrypted = ' '.join(decrypted_words)
        print('Your decryped text: \n'+decrypted)
        print()
        
#Runs all encrypt/decrypt functions
def menu():
    while True:
        print('''

        __________________________________________________
           Main Menu: Select an option
                       1. Encrypt
                       2. Decrypt
                       3. Exit
        __________________________________________________


        ''')
        choice = input ('         Please select >> ')
        if choice == '1':
            print('''

              __________________________________________________
               Encrypt Menu: Select an option
                           1. Encrypt
                           2. Secure Encrypt
                           3. Back
              __________________________________________________

            ''')

            choice_two = input ('         Please select >> ')
            if choice_two == '1':
                encrypt(True,False)
            elif choice_two == '2':
                encrypt(True,True)
            elif choice_two == '3':
                pass
                
            else:
                print('Select a valid option please')

        elif choice == '2':

            encrypt(False,False)
        elif choice == '3':
            sys.exit()
        else:
            print('Select a valid option please')

menu()

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).