Question

In: Computer Science

Revise the substitutionEncrypt function from section 3.5 (p. 102) of the textbook to (1) remove all...

Revise the substitutionEncrypt function from section 3.5 (p. 102) of the textbook to (1) remove all spaces from the plaintext message before it is encrypted and (2) generate the substitution cipher key from a password. (substitutionEncrypt will call genKeyFromPass to do this.) The password should be a parameter, psw, which will replace key as a parameter in the function header.

Write function substitutionDecrypt, which will have two parameters, cipherText, a string, a message encrypted by substitutionEncrypt, and psw, the password used to generate the encryption key, also a string. substitutionDecrypt should return the original plaintext message with spaces removed (a string).

Finally, write a top-level function, main. main should (a) use Python’s built-in input function to get a string to encrypt and a password; (b) call substitutionEncrypt to encrypt the input string; (c) print the value returned by substitutionEncrypt; (d) call substitutionDecrypt to convert the value returned by substitutionEncrypt back to plaintext; (e) print the value returned by substitutionDecrypt.

Use doctest.testmod to check the simple examples included in the function docstrings. The functions should also return correct values for the test cases given here:

>>>subEncrypt('the quick brown fox', 'ajax')

'qdznrexgjoltkblu'

>>>subDecrypt('qdznrexgjoltkblu', 'ajax')

'thequickbrownfox'

Finally, include code in your .py file to call the main function, to check results for additional strings and passwords.

Please revise this code to meet the requirements:

"""


def SubstitutionEncrypt(plainText, psw):
"""
>>> SubstitutionEncrypt('the quick brown fox','ajax')
'qdznrexgjoltkblu'

:param plainText:
:param psw:
:return:
"""
alphabet = "abcdefghijklmnopqrstuvwxyz "
  
# removing spaces from text
plainText = removeMatches(plainText.lower(), " ")

# Generating key from password
generated_key = genKeyFromPass(psw)
cipherText = ""
for ch in plainText:
idx = alphabet.find(ch)
cipherText = cipherText + generated_key[idx]
return cipherText


def removeDupes(myString):
"""

:param myString:
:return:
"""
newStr = ""
for ch in myString:
if ch not in newStr:
newStr = newStr + ch
return newStr


def removeMatches(myString, removeString):
"""

:param myString:
:param removeString:
:return:
"""
newStr = ""
for ch in myString:
if ch not in removeString:
newStr = newStr + ch
return newStr


def genKeyFromPass(password):
"""

:param password:
:return:
"""
key = 'abcdefghijklmnopqrstuvwxyz'
password = removeDupes(password)
lastChar = password[-1]
lastIdx = key.find(lastChar)
afterString = removeMatches(key[lastIdx + 1:], password)

beforeString = removeMatches(key[:lastIdx], password)
key = password + afterString + beforeString
return key


def SubstitutionDecrypt(cipherText, psw):
"""
>>> SubstitutionDecrypt('qdznrexgjoltkblu','ajax')
'thequickbrownfox'

:param cipherText:
:param psw:
:return:
"""
alphabet = "abcdefghijklmnopqrstuvwxyz "

# Generating key from password
generated_key = genKeyFromPass(psw)
plain_text = ""
for ch in cipherText:
idx = generated_key.find(ch)
plain_text += alphabet[idx]
return plain_text


def main():
text = input("Enter String to Encrypt:")
password = input("Enter password:")
encrypted_text = SubstitutionEncrypt(text, password)
print("encrypted_text:", encrypted_text)
decrypted_text = SubstitutionDecrypt(encrypted_text, "ajax")
print("decrypted_text:", decrypted_text)


if __name__ == "__main__":
# import doctest
# doctest.testmod()

main()

Solutions

Expert Solution

 File Name : main.py Author : Date : 7/2/18 Description :  
"""


def SubstitutionEncrypt(plainText, psw):
    """
    >>> SubstitutionEncrypt('the quick brown fox','ajax')
    'qdznrexgjoltkblu'

    :param plainText:
    :param psw:
    :return:
    """
    alphabet = "abcdefghijklmnopqrstuvwxyz "   # removing spaces from text
    plainText = removeMatches(plainText.lower(), " ")

    # Generating key from password
    generated_key = genKeyFromPass(psw)
    cipherText = ""  for ch in plainText:
        idx = alphabet.find(ch)
        cipherText = cipherText + generated_key[idx]
    return cipherText


def removeDupes(myString):
    """

    :param myString:
    :return:
    """
    newStr = ""  for ch in myString:
        if ch not in newStr:
            newStr = newStr + ch
    return newStr


def removeMatches(myString, removeString):
    """

    :param myString:
    :param removeString:
    :return:
    """
    newStr = ""  for ch in myString:
        if ch not in removeString:
            newStr = newStr + ch
    return newStr


def genKeyFromPass(password):
    """

    :param password:
    :return:
    """
    key = 'abcdefghijklmnopqrstuvwxyz'  password = removeDupes(password)
    lastChar = password[-1]
    lastIdx = key.find(lastChar)
    afterString = removeMatches(key[lastIdx + 1:], password)

    beforeString = removeMatches(key[:lastIdx], password)
    key = password + afterString + beforeString
    return key


def SubstitutionDecrypt(cipherText, psw):
    """
    >>> SubstitutionDecrypt('qdznrexgjoltkblu','ajax')
    'thequickbrownfox'

    :param cipherText:
    :param psw:
    :return:
    """
    alphabet = "abcdefghijklmnopqrstuvwxyz " 
 # Generating key from password
    generated_key = genKeyFromPass(psw)
    plain_text = ""  for ch in cipherText:
        idx = generated_key.find(ch)
        plain_text += alphabet[idx]
    return plain_text


def main():
    text = input("Enter String to Encrypt:")
    password = input("Enter password:")
    encrypted_text = SubstitutionEncrypt(text, password)
    print("encrypted_text:", encrypted_text)
    decrypted_text = SubstitutionDecrypt(encrypted_text, "ajax")
    print("decrypted_text:", decrypted_text)


if __name__ == "__main__":
    # import doctest
    # doctest.testmod()

    main()

output:


Related Solutions

3.5          Drop/remove the insignificant independent variable from the regression model, and develop and show an updated...
3.5          Drop/remove the insignificant independent variable from the regression model, and develop and show an updated estimated regression equation that can be used to predict the average annual salary for salaried employees given the average annual salary for hourly employees and the size of the company. Again, use the F test and α = 0.05 to test for overall significance. Also use the t test and α = 0.05 to determine the significance of the independent variables in this updated...
Use the procedure outlined in Section 11.6.2 on p.262 of textbook and the annual percentage default...
Use the procedure outlined in Section 11.6.2 on p.262 of textbook and the annual percentage default rate for all rated companies in Table 11.6 on p.259, a. Estimate the probability of default (PD) and default correlation (ρ) for the period 1970-1993, and for the period 1994-2016 separately. b. Plot the probability distribution of default rate (similar to Figure 11.6 on p.263) for the time period 1970-1993 and 1994-2016 together on the same graph. 970 2.631 1971 0.286 1972 0.453 1973...
Task 1: Remove Number Complete the function remove number such that given a list of integers...
Task 1: Remove Number Complete the function remove number such that given a list of integers and an integer n, the function removes every instance of n from the list. Remember that this function needs to modify the list, not return a new list. Task 2: Logged List The log2() function is one of an algorithm designer’s favourite functions. You’ll learn more about this later, but briefly – if your input size is 1048576 elements, but you only look at...
This function will be given a list of strings and a character. You must remove all...
This function will be given a list of strings and a character. You must remove all occurrences of the character from each string in the list. The function should return the list of strings with the character removed. Signature: public static ArrayList<String> removeChar(String pattern, ArrayList<String> list)
# 3) Problem 3.5 from the textbook asks you to do and interpret a principal components...
# 3) Problem 3.5 from the textbook asks you to do and interpret a principal components analysis on the given correlation matrix, which can be entered into R with the following code: my.cor.mat <- matrix(c(1,.402,.396,.301,.305,.339,.340, .402,1,.618,.150,.135,.206,.183, .396,.618,1,.321,.289,.363,.345, .301,.150,.321,1,.846,.759,.661, .305,.135,.289,.846,1,.797,.800, .339,.206,.363,.759,.797,1,.736, .340,.183,.345,.661,.800,.736,1), ncol=7, nrow=7, byrow=T); As mentioned in the book, the 7 variables are 'head length', 'head breadth', 'face breadth', 'left finger length', 'left forearm length', 'left foot length','height'. Obtain the principal components (including choosing an appropriate number of PCs). Also...
In section 7.4, the textbook states that in virtually all cases, reaction rates increase with increasing...
In section 7.4, the textbook states that in virtually all cases, reaction rates increase with increasing temperature. The rule of thumb is that for every 10°C increase in temperature, the reaction rate doubles. Consider if this is true in an enzyme-catalyzed reaction. In an enzyme-catalyzed reaction, if the temperature is increased by 10°C, what would you expect to happen? The reaction rate slows because the enzyme partially or completely denatures at the increased temperature. The reaction rate doubles, in accordance...
This all has to be in javascript A common way to remove duplicates from an array...
This all has to be in javascript A common way to remove duplicates from an array is to convert it to a set and then convert it back to an array. We will do that here. Please use these variables and data structures: var input = [3, 4, 2, 2, 4, 5, 3, 1, 3, 6]; var set = new Set(); 1. Get each element from the input array and add it to the set. 2. Get the elements from...
capacity of a 1-km section of northbound Highway 3 located on a 3.5% upgrade. The highway...
capacity of a 1-km section of northbound Highway 3 located on a 3.5% upgrade. The highway has three 3.5m-wide lanes in one direction with no lateral obstruction within 5m of the pavement edges. The ideal (base) free-flow speed is 100 km/hour. You observed that percentages of cars and truck are 90% and 10%, respectively (no RVs). A weekday peak hour volume is 4320 vehicles, with 1200 vehicles arriving in the most congested 15-minute period. Since a majority of drivers are...
Description of the problem: 1. Construct the recursive diagram of the Remove function that invokes the...
Description of the problem: 1. Construct the recursive diagram of the Remove function that invokes the function recursive getIndexOf using the main program described in your module. 2. Construct the recursive diagram of the getFrequencyOf function that invokes the function recursive countFrequency using the main program described in your module. C++ Code of getIndex and getFrequency template void ArrayBag::display() const{ cout int ArrayBag::getFrequencyOf(const ItemType& anEntry) const { return countFrequency(anEntry, 0); } // end getFrequencyOf template int ArrayBag::countFrequency(const ItemType& target,int sear...
From information in the “Data section” of your textbook, calculate the standard Gibbs free energy and...
From information in the “Data section” of your textbook, calculate the standard Gibbs free energy and the equilibrium constant at (a) 25°C and (b) 50°C for the reaction CH4(g) + 3 Cl2(g) <--> CHCl3(l) + 3 HCl (g). Assume that the reactionenthalpy isindependent of temperature. ΔG°f (CHCl3, l) =-­71.8 kJ/mol, ΔH°f(CHCl3, l) =‐132.2 kJ/mol Which extra DATA can i provide from the textbook. What values should I look for?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT