In: Computer Science
Vigenère Cipher
The Vigenère Cipher was more or less completely unbreakable from its introduction sometime in the 1500s until well into the 1800s.
The key in Vigenère is a key word that is used over and over again to give a different key to the Caesar cipher for each letter of the encryption (and decryption), with 'A', in good Python form, representing a rotation of 0. (We Pythonistas start at 0, not 1!)
So if the key is ABACUS, then we encrypt:
Back in the 1800s people wanting to use this system would make use of a Vigenère square, also known as the tabula recta, shown in the middle of the Wikipedia entry for the Vigenère cipher, but we can use Python.
Vigenère part of the homework: Write vig_encrypt() and vig_decrypt() functions. Each takes two strings as inputs, with the first being the plaintext/ciphertext, and the second being the key. Both should be calling functions you wrote earlier to help make the work easier.
The key will be a string consisting only of letters, but the letters might be in upper, lower, or mixed case. Important: If the plaintext to be encrypted has non-alphabetic characters (e.g., spaces or punctuation):
One check on your work: vig_encrypt('ATTACKATDAWN', 'LEMON') should return the string LXFOPVEFRNHR; another is that vig_encrypt('Hi Mom!', 'LEMON') should return the string SM YCZ!
from itertools import starmap, cycle
def main():
plain = 'ATTACKATDAWN'
key = 'LEMON'
cipher = vig_encrypt(plain, key)
plain = vig_decrypt(cipher, key)
print("Plain text : ",plain)
print("Encrypted Text: ",cipher)
print("Decrypted Text:",plain)
def vig_encrypt(pt, key):
pt = filter(str.isalpha, pt.upper())
def encr(c, k):
return chr(((ord(k) +
ord(c) - 2 * ord('A')) % 26) + ord('A'))
return ''.join(starmap(encr, zip(pt,
cycle(key))))
def vig_decrypt(pt, key):
def decr(c, k):
return chr(((ord(c) -
ord(k) - 2 * ord('A')) % 26) + ord('A'))
return ''.join(starmap(decr, zip(pt,
cycle(key))))
if __name__ == '__main__':
main()