Hail, Caesar!
Summary of Deadlines
This assignment's practice questions on PrairieLearn are due by Tue, Oct 27 at 11:59pm.
Your solution to the project portion of this assignment is due to Gradescope by Mon, Nov 2 at 11:59 pm.
Presentations for this assignment will take place on Wed, Nov 4 and Thu, Nov 5.
Practice
This assignment features a number of practice questions available on PrairieLearn under the assignment called "HW4: Hail, Caesar!".
These questions will help you practice skills that are relevant to this assignment before you get started on the project. You must earn points on every question to receive full credit, although you are permitted to try each question as many times as you need. Some questions are static, meaning that they will not change when you retry them. Others have elements of random generation, meaning that you will get a new variant of the question on each attempt. As long as you earn points on one variant of a question, you get full credit for that question.
You are welcome to use whatever resources you want to complete these practice questions, but you should make sure you understand what you're doing. This is important for learning, and we'll also ask you to solve a variant of one of these questions as part of your Presentation in the final section of the project.
This assignment's practice questions on PrairieLearn are due by Tue, Oct 27 at 11:59pm.
Project
Navigate to HW4: Hail, Caesar! on Codio to get started.
Where: Complete on Codio, Submit on Gradescope
Summary of Deliverables
By the end of HW04, here's what you'll need to submit to Gradescope:
caesar.pycaesar_tests.pyreadme_caesar.txt
0. Getting started
There are two videos here that you can reference for help with important parts of this assignment.
A. Goals
The goal of this assignment is to practice solving difficult problems on your own by breaking them down into steps, reinforce topics covered in previous assignments, and learn a little bit about the field of cryptography. The specific goals are to:
- Practice solving a complex problem on your own
- Build familiarity writing and using functions
- To understand the benefit of splitting a program into helper functions
- Learn about string manipulation and ASCII encoding
At the end of this assignment, you will produce a program that can encrypt, decrypt and crack the Caesar cipher!
B. Background
Cryptography is the study of secure communications and secret codes. It helps you, say, send a secret message, knowing that even if the message is intercepted, it could not be read. People have been using ciphers (encrypted messages) for thousands of years, but only in the last century have computers come into the field.
One of the oldest ways to hide a message is to use a substitution cipher. One classic example of a substitution cipher is the Caesar cipher, named after the first recorded (and most famous) user, Julius Caesar. If you'd like to learn more about the Caesar cipher, you can check out the wikipedia page to read about its history and usage.
C. Understanding the Caesar Cipher
The Caesar cipher is a basic encryption technique where all letters in a message are shifted down the alphabet by a certain number (determined by the key). In order to encrypt or decrypt a message, you will need a secret key that should, in practice, be hard to find if you don’t already know it. In the Caesar cipher, the key is the number of places to shift each character. This number could be specified numerically (e.g., 4) or it could be specified as a character (e.g., 'E' -- which is 4 places over from 'A'). For simplicity, we typically convert the entire message to uppercase, and may omit punctuation.
For instance, consider the message (and famous Julius Caesar quote):
"CAESAR’S WIFE MUST BE ABOVE SUSPICION"
If we encrypt the above message with the key 'E' then we change each letter in the message to the letter four places to the right in the alphabet. For example, 'C' becomes 'G', 'A' becomes 'E', etc.
Note the letter 'W' in 'WIFE', when shifted four down, goes beyond the last letter in the alphabet 'Z'. This is handled by wrapping back to the front of the alphabet, and so 'W' becomes 'A'.
In total, if we encrypt the previous message with the key 'E', it becomes:
"GEIWEV’S AMJI QYWX FI EFSZI WYWTMGMSR"
D. Data Representation
In this assignment we need to manipulate some text that we will either encrypt, decrypt, or crack. We need to store that text somewhere in our program, and we need to choose how we represent that text. The obvious choice would be to store it as a string. This would certainly work, but may not be the easiest approach.
Consider the word 'COMRADE'. If we wanted to shift it by the letter 'B', we'd be shifting all letters up by 1.
We will represent the message 'COMRADE' by replacing each letter with its position in the alphabet. For example, 'A' becomes 0, 'B' becomes 1, 'C' becomes 2, etc. We can now represent our word 'COMRADE' with a list of integers: [2, 14, 12, 17, 0, 3, 4]. This list may be harder to read as a human, but our program can easily shift our "word" up by the letter 'B' by adding 1 to each number in the list so that it becomes [3, 15, 13, 18, 1, 4, 5].
Fortunately for us, characters are already sort of stored as numbers in the computer. These characters are usually stored following the ASCII encoding:

We do not need to memorize this table as we can easily extract the numberical encoding of a character by using the ord() function:
# get the underlying encoding of the character A
# NOTE: this function only works on a single character
encoding = ord('A')
# print the encoding, which should print 65
print(encoding)
Unfortunately for us, in ASCII the letter 'A' has the value 65. While we could use the ASCII values of characters to encode characters as integers in this program, the math is a bit easier if we instead represent 'A' as 0 instead of 65.
We will need to adjust the ASCII value so that 'A' can be converted to 0. This can easily be done by subtracting 65 from the value returned by ord(). Each uppercase letter follows in sequence (e.g. ord('B') is 66, ord('C') is 67, etc.), so we can subtract 65 to get exactly the number we need for the previously mentioned strategy:
# get the underlying encoding of the character A
our_encoding = ord('A') - 65
# should print 0
print(our_encoding)
To go in the opposite direction, use chr():
back_to_character = chr(our_encoding + 65)
# should print A
print(back_to_character)
Make sure you fully understand these operations and why we use them before moving on to the next section.
E. Your Program Requirements
By the end of this assignment, you will have a caesar.py program which takes in command line arguments that will tell it whether to:
- Encrypt a message using a particular key
- Decrypt a cipher using a particular key to get the original message, or
- Crack an encrypted message, giving us back the secret message
The message will be stored in a file, which will be read by the program.
To encrypt the message stored in plaintext.txt with a key of 'G', you would call
python caesar.py encrypt plaintext.txt G
To decrypt the message stored in cipher.txt with a key of 'G', you would call
python caesar.py decrypt cipher.txt G
To crack the message stored in cipher.txt, you would call
python caesar.py crack cipher.txt english.txt
cipher.txt and plaintext.txt are not files that we provide. You must construct them on your own. plaintext.txt can be any message whereas cipher.txt should be the result of encrypting your plaintext.txt with your program.
F. Starter Files & Background Knowledge
You should be able to go to the assignment on Codio and see a few files present already:
caesar.py: Where you will be writing all of our code in for this assignment.caesar_tests.py: Where you will be writing unit tests for your code.encrypted_message.txt: A file containing an encrypted message that we will use for evaluating the correctness of yourcrackfunctionality.english.txt: a file containing frequencies that we will use for ourcrackfunctionality.readme_caesar.txt: the readme you will submit for this assignment, similar to the ones you have done for previous assignments.
If you need to download the original files again, you can find them here.
G. Advice & Hints
Advice
- You can use unit tests to check that the functions you write are working as expected. We highly suggest starting by writing the signatures of the main functions you think you will need, and then writing corresponding unit tests for each of those functions. This will help keep you on track towards a successful solution to the problem. We have provided a file,
caesar_tests.pyin which you will write your tests. - For smaller steps, you can test parts of your program easily by adding in temporary
print()statements and function calls to the main() function. For instance, if you read in a line of text, you can print its value to check that it contains the information that you expect! When you're done testing & debugging, you should remove these temporaryprint()statements. - Run and debug frequently! Make one small change at a time, ensuring that your program works as you expect it to after each change. We especially recommend that you test each function (at least briefly) after you write it.
- If you are using print statements for testing, don't forget to remove them when you are done with the assignment!
- If you are not getting the outputs you expect, print out the values of variables at different points in the program (i.e. before a loop, inside the body of a loop, after the loop)
- Comment frequently (this helps you and others understand the code) and use descriptive variable names.
Hints
These hints are specific to the homework that may help you debug. Don't hesitate to post on Ed or go to Office hours if these do not help though!
- Don't forget to subtract or add 65 when converting a character to/from a number
- Don't forget to convert things to upper case! This includes the text we want to encrypt/decrypt/crack and the key we use for encryption/decryption
- Sometimes it may help to instead loop over a sequences by index instead of by element (e.g.
for i in range(...):instead offor elem in seq:). You can also do both at once usingenumerate(). - A big part of this assignment is utilizing helper functions. Don't forget that you should use the functions you write in one part of this assignment to implement later parts of the assignment.
- Remember that printing and returning are NOT the same thing. Printing is a side effect of your program, whereas a return statement allows your output to propogate back to the code that called that function, at which point the returned value can be saved and used for whatever you need to do.
1. Functions & main():
Recall that functions allow us to intelligently break up our program into a collection of logical units that we can develop and test independently. We can often identify these major units by considering the high level structure of our program and what we will need to do.
Our caesar program is going to have to do a lot of separate tasks to get the desired functionality. We can take note of these tasks (which we described previously in this specification) and make a function for each of them. When you open the provided caesar.py, you can see that we have provided most function declarations for you.
For example, our basic encryption/decryption process will need to:
- take in text as a string and convert each character in the string into our symbol encoding
- shift those encoded characters either right (to encrypt) or left (to decrypt)
- convert the encoded characters back into text for output (string)
Our task will then be to write functions for each of these major tasks (which we can do and test independently), and then combine those functions together into a working program.
One function that stands out from the others is the main() function. This function is special since this contains the code that we previously would have stored in our python file outside of any function. Having a main() function is not something that is always done in python, but is typically done when our program has functions that could be useful for other programs. Our main() should process command-line args, read in the text from the file we want to encrypt/decrypt/crack and call the appropriate functions for whatever task the user wants to do (encrypt/decrypt/crack).
For this assignment: all code you write should be inside a function unless we specify otherwise
2. Converting and manipulating Symbol Lists
We will first tackle the lowest-level functions to handle encoding/decoding of strings by writing two functions: one to convert from a string to our symbol representation (a list of integers), and one to convert from our symbol representation (a list of integers) back to a string.
These should be the first two functions in caesar.py, but we have copied the function declaration and docstring here for convenience:
def string_to_symbol_list(string: str) -> list[int]:
"""
Description: converts a string to a symbol list, where each element of the
list is an integer encoding of the corresponding element of
the string.
Input: the message text (stored in a string) to be converted
Output: the encoding of the message into a list of integers
"""
# TODO: implement
def symbol_list_to_string(symbol_list: list[int]) -> str:
"""
Description: converts a list of symbols to a string, where each element
of the list is an integer encoding of the corresponding
element of the string.
Input: integer encoding of the message, stored in a list of integers.
Output: the message text as a string
"""
# TODO: implement
A. Writing Unit Tests for Conversion Functions
Before we implement a new function, it is helpful to write unit tests with which we can check whether our function is working as expected once we write it.
Write at least two unit tests for each of the string_to_symbol_list() and symbol_list_to_string() functions in caesar_tests.py. Don't forget to check edge cases as well as standard cases!
Consider also how symbol_list_to_string() and string_to_symbol_list() interact with each other. What is the expected output when you call symbol_list_to_string() on the output of string_to_symbol_list()? What about if the order of function calls is reversed? Think about whether and how you can use this to your benefit while testing.
You will submit these unit tests as part of your project.
B. Implementing Our Conversion Functions
You should implement both of these functions according to their specification.
We recommend starting with string_to_symbol_list() and then move on to symbol_list_to_string().
Note: you will need to call the upper() method on a string before converting it to a symbol list. This will make a copy of the string where all alphabet characters in the string are upercase. For example:
message = 'midi'
other = message.upper()
# prints 'midi'
print(message)
# prints 'MIDI'
print(other)
Once we have implemented a function, we should make sure it passes your unit tests. You may want to add additional unit tests to caesar_tests.py to convince yourself that each of your functions work as intended.
C. Writing Unit Tests for Symbol Shifting
Write at least two unit tests for each of the shift() and unshift() functions (described below) in caesar_tests.py. Don't forget to check edge cases as well as standard cases!
Consider also how shift() and unshift() interact with each other. What is the expected output when you call shift() on the output of unshift()? Think about whether and how you can use this to your benefit while testing.
You will submit these unit tests as part of your project.
D. Shifting and Unshifting Symbols
Write two functions to handle the shifting required to encrypt and decrypt messages. We provide the signatures here for your convenience:
def shift(symbol : int, offset : int) -> int:
"""
TODO: write docstring
"""
# TODO: IMPLEMENT ME
def unshift(symbol: int, offset: int) -> int:
"""
TODO: write docstring
"""
# TODO: IMPLEMENT ME
Where symbol is an English letter (an encoded integer value between 0 and 25), and it should be shifted in the alphabet by offset amount (an integer between 0 and 25). In shift() you will want to shift forwards and in unshift() you will shift backwards. So shifting the symbol for 'B' by 1 gives you the symbol for 'C', while unshifting the symbol for 'B' by 1 gives you the symbol for 'A'.
Remember to wrap symbols that go off the alphabet; for example, 22 ('W') shifted by 4 ('E') should return 0 representing 'A'.
If symbol is not between 0 and 25, meaning it is some sort of whitespace or punctuation, then it should just be returned as is. We do this so all whitespace and punctuation is simply ignored in our encryption and decryption process.
Remember to write an appropriate docstring for your shift() and unshift() functions (as well as your other functions going forward).
Make sure each of these functions passes your unit tests. You may want to add additional unit tests to caesar_tests.py to convince yourself that each of your functions work as intended.
3. Higher Level Functions: Encrypting and Decrypting
A. Writing Unit Tests for Encrypt and Decrypt
Write at least two unit tests for each of the encrypt() and decrypt() functions (described below) in caesar_tests.py. Don't forget to check edge cases as well as standard cases!
Consider also how encrypt() and decrypt() interact with each other. What is the expected output when you call decrypt() on the output of encrypt()? Think about whether and how you can use this to your benefit while testing.
You will submit these unit tests as part of your project.
B. Encrypt
Using the functions you have already written, you should implement the function with the function signature of
def encrypt(message: str, key: int) -> str:
"""
TODO: Add function docstring
"""
# TODO: implement
# you probably want to change the return statement
return ''
This function should accept a string, message and an integer key that represents the offset we will use to encrypt. A message is considered "encrypted" once it has been encoded into integer symbols, shifted, and converted back to a string representation.
Note: It is VERY important that your program take in the numerical representation of the key, and NOT a character. If you do not do this, you will fail most of the tests we provide.
Be sure to write a comprehensive docstring for the function, and test it thoroughly with youur two written unit tests and any other tests you think woud be helpful before proceeding to the next part.
C. Decrypt
Now that you can encrypt your message, you need to be sure you can decrypt it. Write the decrypt function, which has this method header in your file:
def decrypt(cipher: str, key: int) -> str:
"""
TODO: Add function docstring
"""
# TODO: implement
# you probably want to change the return statement
return ''
The structure of this function is very similar to encrypt(), but working in the opposite direction.
Once you have written decrypt(), make sure to test it as well.
D. main() and reading from a file
Once you are confident that encrypt() and decrypt() are working, you should comment out anything you’ve written in your main(). In order to obtain the message you will be encrypting you will need to read in data (the message) from a file.
Write code in main() to:
- Handle the command line arguments
- Load the specified text file
- Call the appropriate function to encrypt/decrypt/crack the message
- Print out the result
E. Testing main
Since main makes use of command line arguments, it makes more sense to test it in our command line rather than using unit tests.
You should be able to run the following operations. For this testing, you will need to create a text file with a message of your choice (come up with your own, or take an example from elsewhere in this specification). Once you encrypt the message, add the encrypted output to the same text file or another. Call decrypt (see command line example below) with the text file containing the message you encrypted and see if you get the original message you created.
To encrypt a message in filename.txt using the symbol value of 6 (character G):
# (filename.txt is not a file we provide)
python caesar.py encrypt filename.txt G
To decrypt the message in another file filename_two.txt using the symbol value of 6 (character G):
# (filename_two.txt is not a file we provide)
python caesar.py decrypt filename_two.txt G
If you'd like a refresher on command-line arguments or reading from a file, you can look back to the Personality Quiz writeup.
You should also test that your functions "work together" before moving forward (that decrypting gets you the same message you encrypted, ignoring case).
4. Higher Level Functions: Cracking the Cipher
NOTE: This section contains a significant amount of setup and understanding before you write any code. Please read the entirety of Part 4 before you start writing code for this part.
A. Understanding the Cracking Process
Now that you have worked out encoding, decoding, encrypting, and decrypting messages, we will add one more step to reach the final goal of cracking the Caesar cipher. This final step involves letter frequency analysis. This simply means you will be taking a text and counting how often each letter in the alphabet appears throughout the text. For example, we know English text will have lots of "E"s and "A"s. If an encrypted cipher has an unusually high number of "F"s and "B"s, in that case what might that tell you about what a likely shift for this cipher might be?
B. Overview
At its core, cracking a caesar cipher using letter frequency analysis is a process of finding the frequency of each letter in the English language, finding the frequency of each letter in a given encoded message, and then finding the decryption key creates the smallest error between those values.
For example, imagine the expected (in English) and observed (in your message) frequencies of the letters A, B, C are the following:
| Letter | Expected Frequency | Observed Frequency |
|---|---|---|
| A | 0.0817 | 0.0 |
| B | 0.0149 | 0.08 |
| C | 0.0278 | 0.01 |
We can calculate a score by finding the absolute value of the difference between each letter in the observed frequencies and its corresponding letter in the English frequencies. So the score in the above case would be
abs(0.0817 - 0.0) + abs(0.0149 - 0.08) + abs(0.0278 - 0.01)
Or 0.1646.
If we shift the values back one (so we assume that the letter B in the encrypted message was originally the letter A) we would see the following case:
| Letter | Expected Frequency | Observed Frequency | Observed Frequency Shifted Back 1 |
|---|---|---|---|
| A | 0.0817 | 0.0 | 0.08 |
| B | 0.0149 | 0.08 | 0.01 |
| C | 0.0278 | 0.01 | 0.03 |
Which would give us a score of
abs(0.0817 - 0.08) + abs(0.0149 - 0.01) + abs(0.0278 - 0.03)
Or 0.0214.
This score essentially tells us how well the letter frequency in the message matches what we would expect if the message were in English, rather than encrypted. The lower the score, the closer the message is to decrypted English. We can use this later to crack the Caesar cipher by trying each different key and picking the one that gives us the lowest score!
C. Preparing to Write Crack
In order to crack a cipher with an unknown key we can guess the key via brute force until we find the correct one. You will implement this in a function called crack() which finds the decryption key that produces the smallest score. There are several correct ways to do this (using different data types), so really think about the benefits and drawbacks to different designs!
To brute force the solution, try to decrypt the cipher message with all possible keys ('A' through 'Z'). At each decryption find the frequencies of the letters in our newly "decrypted" message and use this to determine a score. You want to find which key will give us a message that looks most similar to English, so its score should be the lowest among all keys.
Note that in this process, you will be finding the frequencies of the potentially decrypted message many times. You will also be computing the score of a potential decrypted message many times. This acts as a hint to us that we might want to write those two actions as functions. We provide these function signatures for you:
get_letter_frequencies()takes as input the name of the file containing frequencies to be read, and returns a respresentation tracking each of those floating point numbers and which letter they are associated withfind_frequencies()takes as input a list of integers representing a message, and returns a representation tracking the frequency with which each letter appears in that list.
For each of these functions, the output types are not defined for you as they depend on how you want to implement crack(). Think about what type makes sense to store the information you are outputting so that you can use it in your crack() function.
D. Letter Frequency Analysis
Before you write either get_letter_frequencies() or find_frequencies(), write at least two unit tests for each of those functions in caesar_tests.py. Don't forget to check edge cases as well as standard cases!
You will submit these unit tests as part of your project.
You can then implement the function get_letter_frequencies(). It should be used to find the frequency with which the 26 letters in the alphabet appear in the English language. We have given these frequencies for each letter in english.txt. The first line will have the frequency of the letter ‘A’, the second ‘B’, and so on. You should take a look at the file, and note that it has 26 lines. get_letter_frequencies() should take the name of this file as input and return a respresentation tracking each letter of the alphabet and the frequency they are associated with.
Once you have the frequencies of characters in English, it is time to obtain the frequencies in a potentially decoded ciphertext. To find the frequency of each letter, first find the number of times each letter appears in the ciphertext. Then, divide all of these numbers by the total number of letters in the ciphertext. Ignoring any non-letter symbols. TO do so, implement the function find_frequencies(), which will get and store the frequencies of each letter in a given cipher. The input will be the int list representation of the cipher text and it should return a representation tracking the frequency with which each letter appears in that given encoded text.
Make sure to test your functions with your unit tests. (Hint: Make a simple string with a known letter frequency, encode it, and make sure your find_frequencies() gives you back the appropriate frequency counts.)
E. Scoring the Frequency
Our next step will be scoring the frequencies you found in the last step. The math behind this process is described above.
Implement the function score_frequencies() that takes in one set of expected frequencies (from English) and the observed frequencies (from a potentially decoded ciphertext) in whatever format you chose to store them, and calculates the score.
That is to say, given a set of expected frequencies for A, B, C, etc., and a set of observed frequencies that we assume are for A, B, C, etc., calculate a single score finding
abs(expected_for_A - observed_for_A) + abs(expected_for_B - observed_for_B) + ... + abs(expected_for_Z - observed_for_Z)
Test your function to make sure that it is calculating the correct absolute value.
F. Writing Crack
Once you have written your letter frequency and scoring functions, you can use them as part of crack() to decrypt any given message. Remember that crack() should try to decrypt a message with all possible keys, finding the score for each key, and return a string containing the message found using the key with the loest score. This should be the original message!
Make sure to write and submit at least one unit test for crack in caesar_tests.py. Note that crack() is likely to work better with longer messages!
5. Final touches
Once you have written crack(), you should add code to your main so that you can run caesar.py using:
python caesar.py crack cipher.txt english.txt
Note cipher.txt is not a file that we provide. It is an example of a generic cipher. See encrypted_message.txt for a test case.
This command will crack the cipher in cipher.txt, using the letter frequencies stored in english.txt, which your program must also load. It should print out the cracked message.
Once you have this working, and tested crack(), you have a program that can encrypt a message, decrypt it with the key, and break encryption. You've just cracked Caesar!
Try out your program by cracking the provided file, encrypted_message.txt. You will need the answer to this for your readme_caesar.txt.
Before you submit, make sure that you can perform decrypt, encrypt, and crack using command line arguments. In addition, make sure that all of your methods have docstrings and that your program header has all possible executions of the caesar.py file, including encrypting, decrypting, and cracking, as they may require different command line arguments. Also make sure to include all of your unit tests for each of your functions in caesar_tests.py
6. Submission
Submit caesar.py, caesar_tests.py, and readme_caesar.txt on Gradescope.
Important: Your code will automatically be tested for correctness when you submit and display a score out of 35 points. This will account for most of your grade for the assignment. We don't display details on failing tests, but please use the title of the tests as a hint for how to correct your code. If you encounter any autograder-related issues, please make a private post on Ed.