Vigenère Encryption¶
The Vigenère cipher is a variant of the Caesar cipher whose key is a sequence of integers from 0 through 25. The integers often correspond to the letters of a keyword; for example,
To encrypt a message using the key KEY, shift the first letter of the message by 10 positions, the second by 4, and the third by 24.
Repeat these shifts for the rest of the message: shift the fourth letter by 10, the fifth by 4, the sixth by 24, and so on.
As in the Caesar cipher, reduce each resulting value modulo 26 so that it lies between 0 and 25, then translate the values back into letters to produce the ciphertext.
The following example encrypts “THISISAMESSAGE” with the key KEY.
T H I S I S A M E S S A G E
19 7 8 18 8 18 0 12 4 18 18 0 6 4
+ + + + + + + + + + + + + + (addition mod 26)
K E Y K E Y K E Y K E Y K E
10 4 24 10 4 24 10 4 24 10 4 24 10 4
= = = = = = = = = = = = = =
D L G C M Q K Q C C W Y Q I
3 11 6 2 12 16 10 16 2 2 22 24 16 8
Problem 1
Write a function named vigenere_encrypt() that accepts a plaintext string and a keyword (written as a string of capital letters).
Encrypt the message using the keyword.
You may assume that the plaintext and keyword each contain only uppercase letters A–Z.
Hint: itertools.cycle() may be helpful (but there are several ways to do this).
Reminder: string.ascii_uppercase is the string containing all uppercase letters in order.
Test Cases
print(vigenere_encrypt("THISISAMESSAGE", "K"))
print(vigenere_encrypt("THISISAMESSAGE", "KEY"))
print(vigenere_encrypt("THISISAMESSAGE", "SECRET"))
DRSCSCKWOCCKQO
DLGCMQKQCCWYQI
LLKJMLSQGJWTYI
Problem 2
Write a function named vigenere_decrypt() that accepts a ciphertext string and a keyword (written as a string of capital letters).
Decrypt the message using the keyword.
You may assume that the plaintext and keyword each contain only capital letters A–Z.
Hint: Can you do this by modifying vigenere_encrypt() slightly?
Test Cases
print(vigenere_decrypt("DRSCSCKWOCCKQO", "K"))
print(vigenere_decrypt("DLGCMQKQCCWYQI", "KEY"))
print(vigenere_decrypt("LLKJMLSQGJWTYI", "SECRET"))
THISISAMESSAGE
THISISAMESSAGE
THISISAMESSAGE
Problem 3
The coded message
was encrypted using a Vigenère cipher with one of the following keys.
Decrypt the ciphertext using each of the possible keys and determine which one decrypts to readable English.
Store the resulting plaintext in a variable named problem3_plaintext.