I was wondering how I would implement the vigenere cipher in python
Question: I was tasked to create a caesar cipher in the past and now I am trying to
implement the viginere cipher in python. I want to know how I would go about
doing this. I have a basic idea of using variables from the user as
'plaintext' and the alphabet as its own variable and then adding them to
create its own variable and using the index from these in the alphabet and the
line of code:

    
    
    cipher += alphabet[(alphabet.index(c)+key) % (len(alphabet))
    

This perhaps may be wrong. If there's anything anyone can help with that would
be appreciated.


Answer: The following comes from [Rosetta
Code](http://rosettacode.org/wiki/Vigen%C3%A8re_cipher#Python)'s web site:

    
    
    from itertools import starmap, cycle
    
    def encrypt(message, key):
    
        # convert to uppercase.
        # strip out non-alpha characters.
        message = filter(lambda _: _.isalpha(), message.upper())
    
        # single letter encrpytion.
        def enc(c,k): return chr(((ord(k) + ord(c)) % 26) + ord('A'))
    
        return "".join(starmap(enc, zip(message, cycle(key))))
    
    def decrypt(message, key):
    
        # single letter decryption.
        def dec(c,k): return chr(((ord(c) - ord(k)) % 26) + ord('A'))
    
        return "".join(starmap(dec, zip(message, cycle(key))))
    

An example showing how to use the code is included:

    
    
    text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"
    key = "VIGENERECIPHER"
    
    encr = encrypt(text, key)
    decr = decrypt(encr, key)
    
    print text
    print encr
    print decr
    

Finally, we can see what output of running the code should be:

    
    
    Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
    WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
    BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH
    

