Question

In: Computer Science

I used this code for my first draft assignment. My teacher told me not to add...

I used this code for my first draft assignment. My teacher told me not to add a decrypt function. I have the variable encryptionKey holding 16. I can simply negate encryptionKey with the - in front. Then I make one key change and all the code still works properly. How do I adjust this code?

import csv import sys #The password list - We start with it populated for testing purposes passwords = [["yahoo","XqffoZeo"],["google","CoIushujSetu"]] #The password file name to store the passwords to passwordFileName = "samplePasswordFile" #The encryption key for the caesar cypher encryptionKey=16 #Caesar Cypher Encryption def passwordEncrypt (unencryptedMessage, key): # We will start with an empty string as our encryptedMessage encryptedMessage = '' # For each symbol in the unencryptedMessage we will add an encrypted symbol into the encryptedMessage for symbol in unencryptedMessage: if symbol.isalpha(): num = ord(symbol) num += key if symbol.isupper(): if num > ord('Z'): num -= 26 elif num < ord('A'): num += 26 elif symbol.islower(): if num > ord('z'): num -= 26 elif num < ord('a'): num += 26 encryptedMessage += chr(num) else: encryptedMessage += symbol return encryptedMessage #Caesar Cypher Decryption def passwordDecrypt (encryptedMessage, key): # We will start with an empty string as our unencryptedMessage unEncryptedMessage = '' # For each symbol in the encryptedMessage we will add an unencrypted symbol into the unencryptedMessage for symbol in encryptedMessage: if symbol.isalpha(): num = ord(symbol) num -= key if symbol.isupper(): if num > ord('Z'): num -= 26 elif num < ord('A'): num += 26 elif symbol.islower(): if num > ord('z'): num -= 26 elif num < ord('a'): num += 26 unEncryptedMessage += chr(num) else: unEncryptedMessage += symbol return unEncryptedMessage def loadPasswordFile(fileName): with open(fileName, newline='') as csvfile: passwordreader = csv.reader(csvfile) passwordList = list(passwordreader) return passwordList def savePasswordFile(passwordList, fileName): with open(fileName, 'w+', newline='') as csvfile: passwordwriter = csv.writer(csvfile) passwordwriter.writerows(passwordList) while True: print("What would you like to do:") print(" 1. Open password file") print(" 2. Lookup a password") print(" 3. Add a password") print(" 4. Save password file") print(" 5. Print the encrypted password list (for testing)") print(" 6. Quit program") print("Please enter a number (1-4)") choice = input() if (choice == '1'): # Load the password list from a file passwords = loadPasswordFile(passwordFileName) if (choice == '2'): # Lookup at password print("Which website do you want to lookup the password for?") for keyvalue in passwords: print(keyvalue[0]) passwordToLookup = input() # Iterate through password list # Match it with user input # If matches, save password in a variable and break from loop # Print password # Decrypt password and print it as well for i in range(len(passwords)): if passwords[i][0]==passwordToLookup: pwd=passwords[i][1] break print(pwd) decryptedPassword=passwordDecrypt(pwd,encryptionKey) print(decryptedPassword) if (choice == '3'): print("What website is this password for?") website = input() print("What is the password?") unencryptedPassword = input() # Encrypt entered password # Create a list with website name and passsword # Add this to existing passwords list encryptedPassword = passwordEncrypt(unencryptedPassword, encryptionKey) pwdList=[website,encryptedPassword] passwords.append(pwdList) if (choice == '4'): # Save the passwords to a file savePasswordFile(passwords, passwordFileName) if (choice == '5'): # print out the password list for keyvalue in passwords: print(', '.join(keyvalue)) if (choice == '6'): # quit our program sys.exit()

Solutions

Expert Solution

I've corrected the code and it's working perfectly.

Code:

import csv
import sys

#The password list - We start with it populated for testing purposes
passwords = [["yahoo","XqffoZeo"],["google","CoIushujSetu"]]


#The password file name to store the passwords to
passwordFileName = "samplePasswordFile"

#The encryption key for the caesar cypher
encryptionKey=16

#Caesar Cypher Encryption
def passwordEncrypt (unencryptedMessage, key):

    #We will start with an empty string as our encryptedMessage
    encryptedMessage = ''

    #For each symbol in the unencryptedMessage we will add an encrypted symbol into the encryptedMessage
    for symbol in unencryptedMessage:
        if symbol.isalpha():
            num = ord(symbol)
            num += key

            if symbol.isupper():
                if num > ord('Z'):
                    num -= 26
                elif num < ord('A'):
                    num += 26
            elif symbol.islower():
                if num > ord('z'):
                    num -= 26
                elif num < ord('a'):
                    num += 26

            encryptedMessage += chr(num)
        else:
            encryptedMessage += symbol

    return encryptedMessage

#had to add this item here for the decryption to work. When trying to add it below, it didn't work.
def passwordDecrypt (encryptedMessage, key):

    decryptedMessage = ''

    for symbol in encryptedMessage:
        if symbol.isalpha():
            num = ord(symbol)
            num += key

            if symbol.isupper():
                if num > ord('Z'):
                    num -= 26
                elif num < ord('A'):
                    num += 26
            elif symbol.islower():
                if num > ord('z'):
                    num -= 26
                elif num < ord('a'):
                    num += 26

            decryptedMessage += chr(num)
        else:
            decryptedMessage += symbol

    print (decryptedMessage)
    return decryptedMessage



def loadPasswordFile(fileName):

    with open(fileName, newline='') as csvfile:
        passwordreader = csv.reader(csvfile)
        passwordList = list(passwordreader)

    return passwordList

def savePasswordFile(passwordList, fileName):

    with open(fileName, 'w+', newline='') as csvfile:
        passwordwriter = csv.writer(csvfile)
        passwordwriter.writerows(passwordList)



while True:
    print("What would you like to do:")
    print(" 1. Open password file")
    print(" 2. Lookup a password")
    print(" 3. Add a password")
    print(" 4. Save password file")
    print(" 5. Print the encrypted password list (for testing)")
    print(" 6. Quit program")
    print("Please enter a number (1-4)")
    choice = input()

    if(choice == '1'): #Load the password list from a file
        passwords = loadPasswordFile(passwordFileName)

    if (choice == '2'): # Lookup at password
        print("Which website do you want to lookup the password for?")
        for keyvalue in passwords:
            print(keyvalue[0])
        passwordToLookup = input()

        for i in range(len(passwords)):
            if passwordToLookup == passwords[i][0]:
                unencryptedMessage = passwords[i][1]
                passwordDecrypt(unencryptedMessage, -16)

    if(choice == '3'):
        print("What website is this password for?")
        website = input()
        print("What is the password?")
        unencryptedPassword = input()

        encryptedPassword = passwordEncrypt(unencryptedPassword, encryptionKey)
        passwords.append([website, encryptedPassword])
        print (passwords)

    if(choice == '4'): #Save the passwords to a file
            savePasswordFile(passwords,passwordFileName)


    if(choice == '5'): #print out the password list
        for keyvalue in passwords:
            print(', '.join(keyvalue))

    if(choice == '6'):  #quit our program
        sys.exit()

    print()
    print()

Code screenshots:

Output:

-------------------------END---------------------

Please give a thumbs up(upvote) if you liked the answer.


Related Solutions

My Teacher keeps telling me I don't have a Thesis. I thought I hada good thesis....
My Teacher keeps telling me I don't have a Thesis. I thought I hada good thesis. Please help! Bud Light in advertising             One of the most effective ways for businesses to thrive is to use effective advertising, whether the ad is on TV, magazines, social media or even movies. The goal is to create enticement for a purchase over the competitor’s product. Budweiser is great example of a billion dollar company that has always maintained a strong record of...
Hi I have a java code for my assignment and I have problem with one of...
Hi I have a java code for my assignment and I have problem with one of my methods(slice).the error is Exception in thread "main" java.lang.StackOverflowError Slice method spec: Method Name: slice Return Type: Tuple (with proper generics) Method Parameters: Start (inclusive) and stop (exclusive) indexes. Both of these parameters are "Integer" types (not "int" types). Like "get" above, indexes may be positive or negative. Indexes may be null. Description: Positive indexes work in the normal way Negative indexes are described...
Hi, I need the HTML5 code for the below. About Me **Would like to add a...
Hi, I need the HTML5 code for the below. About Me **Would like to add a image of a plane or something related to travel here. Mia Jo I am taking this class to earn my Computer programmer CL1. Things I Like to Do: Spend time with family Traveling People Watch Places I Want to Go or Have Visited: Dubai- December'18 Enjoyed shopping and the desert safari the most. Cuba- August '18 Enjoyed learning about the culture and history. China-...
How do I add the information below to my current code that I have also posted...
How do I add the information below to my current code that I have also posted below. <!DOCTYPE html> <html> <!-- The author of this code is: Ikeem Mays --> <body> <header> <h1> My Grocery Site </h1> </header> <article> This is web content about a grocery store that might be in any town. The store stocks fresh produce, as well as essential grocery items. Below are category lists of products you can find in the grocery store. </article> <div class...
Submit a draft of the first section of your Economics Module Assignment. While a “draft” your...
Submit a draft of the first section of your Economics Module Assignment. While a “draft” your submission, it must be in paragraph form, properly formatted and proofread thoroughly. I expect your draft response to each topic to be between one half and one page long. 1. INCENTIVES TO BUY HYBRID VEHICLES 2.DON’T FORGET THE COSTS OF TIME AND INVESTED FUNDS 3.LAW OF DEMAND FOR YOUNG SMOKERS
I cannot get this code to run on my python compiler. It gives me an expected...
I cannot get this code to run on my python compiler. It gives me an expected an indent block message. I do not know what is going on. #ask why this is now happenning. (Create employee description) class employee: def__init__(self, name, employee_id, department, title): self.name = name self.employee_id = employee_id self.department = department self.title = title def __str__(self): return '{} , id={}, is in {} and is a {}.'.format(self.name, self.employee_id, self.department, self.title)    def main(): # Create employee list emp1...
I have the following code for my java class assignment but i am having an issue...
I have the following code for my java class assignment but i am having an issue with this error i keep getting. On the following lines: return new Circle(color, radius); return new Rectangle(color, length, width); I am getting the following error for each line: "non-static variable this cannot be referenced from a static context" Here is the code I have: /* * ShapeDemo - simple inheritance hierarchy and dynamic binding. * * The Shape class must be compiled before the...
(Python) How would I add this input into my code? "Enter Y for Yes or N...
(Python) How would I add this input into my code? "Enter Y for Yes or N for No:" as a loop. def getMat(): mat = np.zeros((3, 3)) print("Enter your first 3 by 3 matrix:") for row in range(3): li = [int(x) for x in input().split()] mat[row,0] = li[0] mat[row,1] = li[1] mat[row,2] = li[2] print("Your first 3 by 3 matrix is :") for i in range(3): for k in range(3): print(str(int(mat[i][k]))+" ",end="") print() return mat def checkEntry(inputValue): try: float(inputValue) except...
My teacher, asked me to find the "Tangible Equity Capital Ratio" my finance book does not...
My teacher, asked me to find the "Tangible Equity Capital Ratio" my finance book does not refer to anything by this name? I have looked online and haven't been able to find anything similar. Do you have any idea what he could mean by this and how i could try calculating it?
I was wondering is someone could tell me why my code isn't compiling - Java ------------------------------------------------------------------------------------------------------------...
I was wondering is someone could tell me why my code isn't compiling - Java ------------------------------------------------------------------------------------------------------------ class Robot{ int serialNumber; boolean flies,autonomous,teleoperated; public void setCapabilities(int serialNumber, boolean flies, boolean autonomous, boolean teleoperated){ this.serialNumber = serialNumber; this.flies = flies; this.autonomous = autonomous; this.teleoperated = teleoperated; } public int getSerialNumber(){ return this.serialNumber; } public boolean canFly(){ return this.flies; } public boolean isAutonomous(){ return this.autonomous; } public boolean isTeleoperated(){ return this.teleoperated; } public String getCapabilities(){ StringBuilder str = new StringBuilder(); if(this.flies){str.append("canFly");str.append(" ");} if(this.autonomous){str.append("autonomous");str.append("...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT