Demo entry 3512136

program

   

Submitted by anonymous on Jan 07, 2016 at 11:43
Language: Python. Code size: 22.4 kB.

#Imports random module for generating a random number.
import random
#Imports sys module for exiting the program.
import sys
#Imports the time module which is used to delay the exit function so the user has time to read the 'exit' message provided.
import time
#Imports the module to perform calculations to create the offset factor.
import math
#Menu input options being created. These are just to make understanding where each module starts and ends in the code.
encrypt = '1'
decrypt = '2'
advencrypt = '3'
exit = '4'
#While loop is used to prevent the program from stopping if the user has selected a wrong option.
while True:
#This is asking the user to input a number to take them to another menu.
#I have not added int before the raw_input because it will allow my error handling at the bottom of the program to run properly.
#This is a multi-line string to make the menu easy to read for the user as there are short phrases on each line rather than having them all grouped up into one single-line string.
    option = (raw_input("""Select one of the options below
1 for Encrypt
2 for Decrypt
3 for Advanced encrypt
4 for Exit
Chosen option: """))
#User selects a option (has to type 1, 2, 3 or 4).
#If the user has typed 1 it will redirect them to the encryption menu.
    if option == encrypt:
#"plaintext" is the name given to a message that has not been encrypted yet.
#This will ask the user to enter an unencrypted file to be encrypted. They will have to add the file extension which is .txt. This try statement will attempt to do what is said below.
        try:
#The try statement will try to ask the user to input a text file. This will be used to make the connection to the text file.
            filename=(raw_input("Select a file to be encrypted: "))
#The program checks if the user has added the file extension (.txt) to the file they want to save it as. This is useful because it prevents errors from occuring. For example, if ".txt" was not
#added to the end of the file name it will create a file that cannot be opened by Notepad.exe.
            if ".txt" not in filename:
#If they didn't add the file extension, it will automatically be added to the end so Notepad.exe and Python are able to open the file.
                filename=filename+".txt"
#The plaintext variable will store the text file contents. This right now is just making the connection between the program and the file.
            plaintext=(open(filename))
#If there is an error it will tell the user they have made an error and then it will ask them to enter a correct text document.
        except:
#This will notify the user that the file entered is invalid.
            print("The file you entered was invalid, please try again.")
            filename=(raw_input("Select a file to be encrypted: "))
#The program checks if the user has added the file extension (.txt) to the file they want to save it as. This is useful because it prevents errors from occuring. For example, if ".txt" was not
#added to the end of the file name it will create a file that cannot be opened by Notepad.exe.
            if ".txt" not in filename:
#If they didn't add the file extension, it will automatically be added to the end so Notepad.exe and Python are able to open the file.
                filename=filename+".txt"
            plaintext=(open(filename))
#If everything is fine it will do these set of instructions.
        else:
#The program will print this message for confirmation.
            print("Thank you for entering a text file.")
            #The program is reading the contents of the text file and replacing the contents of the variable 'plaintext' with the contents of the text file.
            plaintext = plaintext.read()
#Creating the lists before the forloop rather than within the forloop to prevent the program from creating a new list with the same name which will remove all previous items in it.
#This will make sure each of the generated random integers and converted characters are within the lists.
        randints=[]
        randchars=[]
#The forloop mentioned earlier, this will repeat eight times because that is what I set the range to.
        for numbers in range(0,8):
#This will generate a random integer between 33 and 126 and save it to the new variable named 'randint'.
            randint=random.randint(33,126)
#I will then add the contents of the 'randint' variable which is a random integer to the previously created list named 'randints' which will store all of these random integers.
            randints.append(randint)
#It will also then change the random integer stored in 'randint' to a character as a new variable named 'randchar'.
            randchar=chr(randint)
#It will then add the contents of the 'randchar' variable which is the character created above to the list 'randchars'.
            randchars.append(randchar)
#This will join each index in the list at each space so there are no spaces in the final key.
        userkey=''.join(randchars)
#This will then print the eight character key which is user-friendly because it joined all on a single string by joining the items in the list while getting rid of the brackets and commas.
        print 'Here is your key which you will have to take note of: ',userkey
#Here I will start generating the offset factor, this will add all of the items in the 'randints' list to a new variable named 'offset'. This will only work because they all integers.
        offset=sum(randints)
#The program will then set the 'offset' variable to the current variable divided by eight.
        offset=offset/8
#This is where importing the math module comes in. This will let the program round the integer stored in the variable 'offset'. This is to prevent the offset factor being above 127 because it
#rounds down rather than up.
        math.floor(offset)
#This will subtract 32 from the 'offset' variable then save it as the 'offset' variable. This is to make sure the integer is not below 33. The offset factor has been completed.
        offset=offset-32
#The program will need to create the link to the file in order to use the contents of the file.
        plaintext = open(filename)
#The program is reading the contents of the text file and replacing the contents of the variable 'plaintext' with the contents of the text file.
        plaintext = plaintext.read()
#Once again, I am creating a list before the forloop so the program does not overwrite the list every time the forloop runs (if I did this, the list would end up only storing a single character).
        encryptedtext=[]
#This forloop will encrypt every letter in the plaintext variable which stores the contents of the text file.
        for letter in plaintext:
#If the letter is a space then... 
            if letter==" ":
#The program will add it to the list using .append. This is used because the program must ignore spaces as said in the criteria.
                encryptedtext.append(letter)
#Else, if the letter is not a space then the program will then do these set of lines.
            else:
#The program will then change the character to its ascii number equivalent eg. A would be converted to 65. Then the value is saved to a variable named 'numberletter'. This is used throughout the
#encryption.
                numberletter=ord(letter)
#Here, the variable numberletter is then being set to the current value added to the offset factor number.
                numberletter=numberletter+offset
#The number stored in the variable is being converted into a single integer. This is so further calculations can be made without any errors.
                numberletter=int(numberletter)
#If the number is higher than 126 then it will run these set of codes.
                if numberletter>126:
#Because the number is higher than 126 I must subtract 94 from the number as said on the criteria.
                    numberletter=numberletter-94
#Here the program is converting the integer stored in the variable numberletter to a character and this is the final converted character after encryption.
                numberletter=chr(numberletter)
#The number is then being added to the list which stores all of the characters after encryption (unless it is a space).
                encryptedtext.append(numberletter)
#The forloop has finished running and now the program is changing the list so it is readable, removing all of commas, apostrophies and spaces between each list entry.
        encryptedtext=''.join(encryptedtext)
#The program is now converting the contents of the file into a string so it can be added to the new textfile without any errors occuring.
        encryptedtext=str(encryptedtext)
#The program is outputting the contents of the variable (which is the ciphertext) only to show that the file has been encrypted.
        print encryptedtext
#The program is asking the user to input the name of the file they want to save it as.
        filename=(raw_input("Choose a file name to save the file as: "))
#The program checks if the user has added the file extension (.txt) to the file they want to save it as. This is useful because it prevents errors from occuring. For example, if ".txt" was not
#added to the end of the file name it will create a file that cannot be opened by Notepad.exe.
        if ".txt" not in filename:
#If they didn't add the file extension, it will automatically be added to the end so Notepad.exe and Python are able to open the file.
            filename=filename+".txt"
#Opens the file if it exists without truncating the existing file and will create a new file if one does not already exist.
        newfile = open(filename,'a')
#The program is now writing the contents of the variable to the file.
        newfile.write(encryptedtext)
#In order for the contents of the file to save, the program will now close the connection with the file so the created file is not empty.
        newfile.close()
#Since I have used a whileloop for the menu, the program will loop back to the main menu after completing one of the options.
        print "The ciphertext file has been created. Please select another option."
#If the user has typed 2 it will redirect them to the decryption menu.
    elif option == decrypt:
#"ciphertext" is the name given to a message that has been encrypted yet.
#This will ask the user to enter an encrypted file to be decrypted. They will not have to add the file extension which is .txt.
        try:
#The try statement will try to ask the user to input a text file. This will be used to make the connection to the text file.
            filename=(raw_input("Select a file to be decrypted: "))
#The program checks if the user has added the file extension (.txt) to the file they want to save it as. This is useful because it prevents errors from occuring. For example, if ".txt" was not
#added to the end of the file name it will create a file that cannot be opened by Notepad.exe.
            if ".txt" not in filename:
#If they didn't add the file extension, it will automatically be added to the end so Notepad.exe and Python are able to open the file.
                filename=filename+".txt"
#The program will need to create the link to the file in order to use the contents of the file.
            ciphertext = open(filename)
#If there is an error it will tell the user they have made an error and then it will ask them to enter a correct text document.
        except:
            print("The file you entered was invalid, please try again.")
            filename=(raw_input("Select a file to be decrypted: "))
#The program checks if the user has added the file extension (.txt) to the file they want to save it as. This is useful because it prevents errors from occuring. For example, if ".txt" was not
#added to the end of the file name it will create a file that cannot be opened by Notepad.exe.
            if ".txt" not in filename:
#If they didn't add the file extension, it will automatically be added to the end so Notepad.exe and Python are able to open the file.
                filename=filename+".txt"
#The program will need to create the link to the file in order to use the contents of the file.
            ciphertext = open(filename)
#This will then run these set of instructions after a correct file has been entered.
        else:
            print("Thank you for entering a text file.")
#This lets the user input the eight character key given in the encryption of the file. This eight character key is unique for each text file as the offset factor is designed for each text file.
        userkey=(raw_input("Enter the eight character key provided: "))
#This is checking if the length of the eight character key is higher than 8. If it is higher than 8 it means the eight character key that has been inputted has nine or more characters.
        if len(userkey)>8:
#The program will then let the user input the eight character key again since the first one was invalid.
            userkey=(raw_input("Enter the eight character key provided: "))
#I am creating the list to seperate each value (character) in the eight character key so I can add them up. 
        randints=[]
#This forloop will add each value within the eight character key into a new list. This will repeat eight times since there are eight characters in the key.
        for value in userkey:
#This will change the character to an integer so the program can perform calculations.
            value=ord(value)
#Here, the program is adding the integer to the list.
            randints.append(value)
#The program is creating the offset factor once again so I can decrypt the file by subtracting it.
        offset=sum(randints)
#The offset factor is being divided by eight because there are eight characters in the key.
        offset=offset/8
#The program is rounding the number down to a whole number without any decimals.
        math.floor(offset)
#The offset factor is being set to an integer and then taking 32 from it.
        offset=int(offset)-32
#The program is creating the link to the text file once again so it can be used.
        ciphertext=open(filename)
#The program is reading the contents of the text file.
        ciphertext=ciphertext.read()
#The list is being created before the forloop so it will not store the last value by the end of the forloop.
        decryptedtext=[]
#This forloop is now decrypting the characters within the file.
        for letter in ciphertext:
#The program will check if the character is a space.
            if letter==" ":
#if it is a space it will add it to the list since it shouldn't encrypt spaces.
                decryptedtext.append(letter)
#Else, the character is not a space it will run these set of instructions.
            else:
#The program is changing the character to its ascii code equivalent (a number)
                numberletter=ord(letter)
#The program is subtracting the offset factor from the number since encryption was adding the offset factor.
                numberletter=numberletter-offset
#If the number is less than 33 then...
                if numberletter<33:
#The program is now adding 94 to the number since we took 94 in the encryption if it was above 127.
                    numberletter=numberletter+94
#The program is converting the number into a character and then adding it to the list which stores each character.
                decryptedtext.append(chr(numberletter))
#The program is joining the list to get rid of the spaces, brackets and apostrophies between each value so it is in a readable format.
        decryptedtext=''.join(decryptedtext)
#The program is changing the variable to a string so it can be printed/ displayed to the user.
        decryptedtext=str(decryptedtext)
#The program is printing the contents of the original text file (before encryption) to the user.
        print ("Here are the contents of the encrypted file: "+decryptedtext)
#If the user has typed 3 it will redirect them to the advanced encryption menu.
    elif option == advencrypt:
#"plaintext" is the name given to a message that has not been encrypted yet.
#This will ask the user to enter an unencrypted file to be encrypted. They will have to add the file extension which is .txt. This try statement will attempt to do what is said below.
        try:
#The try statement will try to ask the user to input a text file. This will be used to make the connection to the text file.
            filename=(raw_input("Select a file to be encrypted: "))
#The program checks if the user has added the file extension (.txt) to the file they want to save it as. This is useful because it prevents errors from occuring. For example, if ".txt" was not
#added to the end of the file name it will create a file that cannot be opened by Notepad.exe.
            if ".txt" not in filename:
#If they didn't add the file extension, it will automatically be added to the end so Notepad.exe and Python are able to open the file.
                filename=filename+".txt"
#The plaintext variable will store the text file contents. This right now is just making the connection between the program and the file.
            plaintext=(open(filename))
#If there is an error it will tell the user they have made an error and then it will ask them to enter a correct text document.
        except:
#This will notify the user that the file entered is invalid.
            print("The file you entered was invalid, please try again.")
            filename=(raw_input("Select a file to be encrypted: "))
#The program checks if the user has added the file extension (.txt) to the file they want to save it as. This is useful because it prevents errors from occuring. For example, if ".txt" was not
#added to the end of the file name it will create a file that cannot be opened by Notepad.exe.
            if ".txt" not in filename:
#If they didn't add the file extension, it will automatically be added to the end so Notepad.exe and Python are able to open the file.
                filename=filename+".txt"
            plaintext=(open(filename))
#If everything is fine it will do these set of instructions.
        else:
#The program will print this message for confirmation.
            print("Thank you for entering a text file.")
            #The program is reading the contents of the text file and replacing the contents of the variable 'plaintext' with the contents of the text file.
            plaintext = plaintext.read()
#Creating the lists before the forloop rather than within the forloop to prevent the program from creating a new list with the same name which will remove all previous items in it.
#This will make sure each of the generated random integers and converted characters are within the lists.
        randints=[]
        randchars=[]
#The forloop mentioned earlier, this will repeat eight times because that is what I set the range to.
        for numbers in range(0,8):
#This will generate a random integer between 33 and 126 and save it to the new variable named 'randint'.
            randint=random.randint(33,126)
#I will then add the contents of the 'randint' variable which is a random integer to the previously created list named 'randints' which will store all of these random integers.
            randints.append(randint)
#It will also then change the random integer stored in 'randint' to a character as a new variable named 'randchar'.
            randchar=chr(randint)
#It will then add the contents of the 'randchar' variable which is the character created above to the list 'randchars'.
            randchars.append(randchar)
#This will join each index in the list at each space so there are no spaces in the final key.
        userkey=''.join(randchars)
#This will then print the eight character key which is user-friendly because it joined all on a single string by joining the items in the list while getting rid of the brackets and commas.
        print 'Here is your key which you will have to take note of: ',userkey
#Here I will start generating the offset factor, this will add all of the items in the 'randints' list to a new variable named 'offset'. This will only work because they all integers.
        offset=sum(randints)
#The program will then set the 'offset' variable to the current variable divided by eight.
        offset=offset/8
#This is where importing the math module comes in. This will let the program round the integer stored in the variable 'offset'. This is to prevent the offset factor being above 127 because it
#rounds down rather than up.
        math.floor(offset)
#This will subtract 32 from the 'offset' variable then save it as the 'offset' variable. This is to make sure the integer is not below 33. The offset factor has been completed.
        offset=int(offset)-32
#The program will need to create the link to the file in order to use the contents of the file.
        plaintext = open(filename)
#The program is reading the contents of the text file and replacing the contents of the variable 'plaintext' with the contents of the text file.
        plaintext = plaintext.read()
        plaintext = plaintext.replace(" ", "")
        for letter in plaintext:
            numberletter=ord(letter)
            numberletter=numberletter-offset
            chrletter=chr(numberletter)
            strletter=str(chrletter)
            ciphertext=""
            ciphertext=ciphertext+chrletter
        ciphertext=' '.join(ciphertext[i:i+5]for i in range(0,len(ciphertext),5))
        print ciphertext
#If the user has typed 4 it will exit the program.
    elif option == exit:
#The program will warn the user that the program is about to exit.
        print ("Exiting the program...")
#The program will wait 3 second before closing the program to give the user time to react.
        time.sleep(3)
#The program will now exit using sys.exit which will only work because I have imported the sys module at the start of the program.
        sys.exit(0)
#If the user has typed in an invalid option such as a number that is not between 1-4 it will ask the user to input another option because it is not any of the elifs above.
    else:
        print ("Invalid option, please try again.")

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).