CS 100

Logo

Scientific Computing

Activity 15 - Ciphers

  1. Create python file ciphers.py in your cs100/ch3 folder.

  2. What do the following lines of code accomplish? Test and write your answer in comments above it.

    m = "This is a message."
    for i in range(len(m)):
        print( ord(m[i]) ) 
    
  3. Here is an message encrypted by the transposition cipher described in your book. The original message was separated into odd/even characters, and all odd characters were put before all even characters. The encrypted message is: "o r ue wsmyuaespraeoe". Write a function to decrypt the message and return the decrypted plain text (check your book for hints). Call your function print the secret message! What does it say?

  4. Now add the following lines of code. Run it and understand what the code does inside.
    def substitutionEncrypt(plainText, key):
        alphabet = "abcdefghijklmnopqrstuvwxyz "
        plainText = plainText.lower()
        cipherText = ""
        for ch in plainText:
            idx = alphabet.find(ch)
            cipherText = cipherText + key[idx]
        return cipherText
       
    # add code here - decrypt() function
       
       
    key = 'zyxwvutsrqponmlkjihgfedcba '
    plainText = 'the quick brown fox'
       
    encryptMsg = substitutionEncrypt(plainText,key)
    print( "Encrypted message: " + encryptMsg )
       
    # call your function here to decrypt and test
    
  5. Add a decrypt function that takes two parameters (an encrypted message and a key) and returns the decrypted message.

  6. Add code that calls/invokes the decrypt function and displays the result of the message held in encryptMsg after it is decrypted.

If you finish early

  1. Here is a new message encrypted with the substitution cipher: "xsflsklau bgt qgm sjw xstmdgmk". It was encrypted using the key: "stuvwxyzabcdefghijklmnopqr ". Use your decryption function to print out what it says. What’s the secret message?

  2. Add code that asks the user for a message to be encrypted, encrypts that message, then decrypts it. Use print statements after each step to visualize your progress.