Question

In: Computer Science

I was given an assignment to write three sections of Code. 1. Look up password 2....

I was given an assignment to write three sections of Code.

1. Look up password

2. Decrypt a password.

3. What website is this password for?

Here's the base 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

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()

        ####### YOUR CODE HERE ######
        #You will need to find the password that matches the website
        #You will then need to decrypt the password

        #
        #1. Create a loop that goes through each item in the password list
        #  You can consult the reading on lists in Week 5 for ways to loop through a list
        #
        #2. Check if the name is found.  To index a list of lists you use 2 square backet sets
        #   So passwords[0][1] would mean for the first item in the list get it's 2nd item (remember, lists start at 0)
        #   So this would be 'XqffoZeo' in the password list given what is predefined at the top of the page.
        #   If you created a loop using the syntax described in step 1, then i is your 'iterator' in the list so you
        #   will want to use i in your first set of brackets.
        #
        #3. If the name is found then decrypt it.  Decrypting is that exact reverse operation from encrypting.  Take a look at the
        # caesar cypher lecture as a reference.  You do not need to write your own decryption function, you can reuse passwordEncrypt
        #
        #  Write the above one step at a time.  By this I mean, write step 1...  but in your loop print out every item in the list
        #  for testing purposes.  Then write step 2, and print out the password but not decrypted.  Then write step 3.  This way
        #  you can test easily along the way.
        #


        ####### YOUR CODE HERE ######


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

        ####### YOUR CODE HERE ######
        #You will need to encrypt the password and store it in the list of passwords

        #The encryption function is already written for you
        #Step 1: You can say encryptedPassword = passwordEncrypt(unencryptedPassword,encryptionKey)]
        #the encryptionKey variable is defined already as 16, don't change this
        #Step 2: create a list of size 2, first item the website name and the second item the password.
        #Step 3: append the list from Step 2 to the password list


        ####### YOUR CODE HERE ######

    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()

Solutions

Expert Solution

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

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 passwords:# loop in passwords list
if i[0]==passwordToLookup:# if website name matches then password found
print("Password found: "+i[1])
break
s=26-encryptionKey;# decrypting password using passwordEncrypt function by changing the encryptionKey
decryptedPassword=passwordEncrypt(i[1],s)
print("Decrypted password: "+decryptedPassword)

if(choice == '3'):
print("What website is this password for?")
website = input()
print("What is the password?")
unencryptedPassword = input()
  
encryptedPassword = passwordEncrypt(unencryptedPassword,encryptionKey)
l=[]
l.append(website)# add website name to list
l.append(encryptedPassword)# add password to list
passwords.append(l)# then append list to passwords list

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()


Related Solutions

Language for this question is Java write the code for the given assignment Given an n...
Language for this question is Java write the code for the given assignment Given an n x n matrix, where every row and column is sorted in non-decreasing order. Print all elements of matrix in sorted order.Input: The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains an integer n denoting the size of the matrix. Then the next line contains the n x n elements...
PROGRAM INSTRUCTIONS: 1. Code an application that asks the customer for a log-in and password. 2....
PROGRAM INSTRUCTIONS: 1. Code an application that asks the customer for a log-in and password. 2. The real log-in is "Buffet2011" and the real password is "Rank1Bill2008". 3. Allow the customer two (2) attempts to type either. a. Each time the customer enters an invalid log-in or password issue an error message. b. If the customer fails all two (2) log-in attempts, issue another error message and exit the program. c. If the log-in is successful, the customer can calculate...
Given the following code: for (i=2;i<100;i=i+1) { a[i] = b[i] + a[i]; /* S1 */ c[i-1]...
Given the following code: for (i=2;i<100;i=i+1) { a[i] = b[i] + a[i]; /* S1 */ c[i-1] = a[i] + d[i]; /* S2 */ a[i-1] = 2 * b[i]; /* S3 */ b[i+1] = 2 * b[i]; /* S4 */ } a. List all the dependencies by their types (TD: true-data, AD: anti-data, OD: output-data dependencies). b. Show how Software Pipelining can exploit parallelism in this code to its fullest potential. How many functional units would be sufficient to achieve the...
C Code! I need all of the \*TODO*\ sections of this code completed. For this dictionary.c...
C Code! I need all of the \*TODO*\ sections of this code completed. For this dictionary.c program, you should end up with a simple English-French and French-English dictionary with a couple of about 350 words(I've provided 5 of each don't worry about this part). I just need a way to look up a word in a sorted array. You simply need to find a way to identify at which index i a certain word appears in an array of words...
I have the following assignment for probability class: I am supposed to write a routine (code)...
I have the following assignment for probability class: I am supposed to write a routine (code) in MATLAB that does solve the following problem for me: a) Generate N=10000 samples of a Uniform random variable (X) using the rand () command. This Uniform RV should have a range of -1 to +3. b) Generate (Estimate) and plot the PDF of X from the samples. You are not allowed to use the Histogram () command, any commands from the Matlab Statistics...
Write C++ code that prompts the user for a username and password (strings), and it calls...
Write C++ code that prompts the user for a username and password (strings), and it calls the login() function with the username and password as arguments. You may assume that username and password have been declared elsewhere. Your code should print error messages if login() generates an exception: LoginException: "Username not found or password incorrect" ServerException: "The login server is busy and you cannot log in" AccessException: "Your account is forbidden from logging into this server" Any other exception: "Unknown...
Write C++ code that prompts the user for a username and password (strings), and it calls...
Write C++ code that prompts the user for a username and password (strings), and it calls the login() function with the username and password as arguments. You may assume that username and password have been declared elsewhere. Use virtual functions, pure virtual functions, templates, and exceptions wherever possible. Please explain the code. Your code should print error messages if login() generates an exception: LoginException: "Username not found or password incorrect" ServerException: "The login server is busy and you cannot log...
This assignment will ask you to look at your own finances. For this assignment, write a...
This assignment will ask you to look at your own finances. For this assignment, write a paragraph showing your percentages. I DO NOT want to know how much money you spend or have as income, I am only looking at the percentages. Describe for me what the effect of inflation is on you personally given what you found out. Look at a typical month of your expenditures and income. Create a list of your expenses by category (see below). Create...
Chapter 2 Exercise is divided in to 2 sections A and B. Data for this assignment...
Chapter 2 Exercise is divided in to 2 sections A and B. Data for this assignment is under Data files in module Ex2-30-e8.xls (for A) and Ex2-34-e8.xls (for B). See data under modules. A) The following data give the weekly amounts spent on groceries for a sample of households. $271 $363 $159 $ 76 $227 $337 $295 $319 $250 279 205 279 266 199 177 162 232 303 192 181 321 309 246 278 50 41 335 116 100 151...
CODE IN JAVA** I(a). Given a pointer to the root of a binary tree write a...
CODE IN JAVA** I(a). Given a pointer to the root of a binary tree write a routine that will mark (use a negative number like -999 for the info field) every node in the tree that currently has only a left son. You can assume the root of the tree has both a right and left son. When finished tell me how many nodes had only a left son as well as how many nodes are in the tree in...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT