As usual, create a directory to hold today's files. All programs that you write today should be stored in this directory.
$ cd ~/cs120/labs $ mkdir lab18 $ cd lab18
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.
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?
Function Parameters | Expected Output |
---|---|
"scotty", 13 | fpbggl |
"bouchard", 3 | erxfkdug |
"The Eagle flies at midnight!", 26 | theeaglefliesatmidnight |
Your first step should be to take a character and convert it
to an integer in the range \([0, 26)\). If you have an
arbitrary lowercase character ch, you can convert
this to an integer by subtracting the ord
of
the lowercase 'a' character from the ord
value
of ch.
For some key and character combinations, it is very likely
that you will get pushed outside the range of lowercase
characters. You can use modular arithmetic to make sure you
stay in the range, and accomplish the cycling around described
above. Just mod (%
) the result of adding the
key by 26 to make sure you get an integer still in the
necessary range.
After you have performed the key shifting, you can use
the chr
function to convert your integer back
to a character. You will want to add
the ord('a')
value back to your integer, to
make sure you get a lowercase character as opposed to an
unprintable one.
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.