Loading [MathJax]/jax/output/HTML-CSS/jax.js

CPSC120A
Fundamentals of Computer Science I

Lab 18

Encryption

Use the command line to create a new directory called lab18 in your labs directory. Make sure all of the .py files that you create for this activity are in that directory.

Caesar Cipher

Cryptography is the science of hiding secrets. One very easy, and surprisingly old, cryptographic protocol is know as the Caesar cipher. It is named after Julius Caesar who would scramble documents containing strategic military information by replacing each character in the document with the character three letters later in the alphabet. In general, the Caesar cipher can shift characters by any amount in the range 0 to 25.

Details

Write a function called caesar_cipher(plaintext, key). The parameter plaintext is a string and key is an integer in the range [0, 26). The function should return a string with each character shifted forward in the alphabet by the specified amount. If shifting a character puts it outside of the range of lowercase letters, you should wrap around back to the beginning of the alphabet. Including capitalized and non-alphabetic characters in the encrypted text makes it easier to break the encryption and discover the hidden message. The function should remove non-alphabetic characters and convert all upper-case letters to lower-case.

Make sure your program handles all necessary cases gracefully. What additional test cases should you check?

Sample Test Cases

Function Parameters Expected Output
"scotty", 13 fpbggl
"bouchard", 3 erxfkdug
"The Eagle flies at midnight!", 26 theeaglefliesatmidnight

Hint

Challenge

The function you write above should be able to be used for both encryption and decryption. The only difference for decryption is that you negate the input key value. Add code to your file that prompts the user for a string of text to encrypt, an integer key, and whether they want to encrypt or decrypt the specified string. If the user wants to decrypt a message, you should negate their key, and just use the same function.

Submission

Please show your source code and run your programs for the instructor or lab assistant. Only a programs that have perfect style and flawless functionality will be accepted as complete.