Skip to content

Instantly share code, notes, and snippets.



Last active Nov 7, 2017
What would you like to do?
Vigenere cipher over Latin alphabet in Python3
#!/usr/bin/env python3
from itertools import cycle
A = [chr(x) for x in range(ord('a'), ord('z')+1)]
def encrypt(a,b):
return A[(A.index(a) + A.index(b)) % len(A)]
def decrypt(a,b):
return A[(A.index(a) - A.index(b)) % len(A)]
def vigenere(plaintext, key, op):
return ''.join([op(x,y) for x,y in list(zip(plaintext, cycle(key)))])
E = (
('aaaa', 'aaaa', 'aaaa'),
('aaaa', 'b', 'bbbb'),
('aaaa', 'y', 'yyyy'),
('aaaa', 'yh', 'yhyh'),
('dddd', 'y', 'bbbb'),
('dddd', 'yh', 'bkbk'),
('attackatdawn', 'lemon', 'lxfopvefrnhr'),
('cryptoisshortforcryptography', 'abcd', 'csastpkvsiqutgqucsastpiuaqjb'),
('therecouldyetbeanothergeographerwhowoulddisagree', 'carbon', 'vhvsspqucemrvbvbbbvhvsurqgibdugrnicjqucervuaxssr'),
for plaintext, key, expected in E:
ciphertext = vigenere(plaintext, key, encrypt)
decrypted = vigenere(ciphertext, key, decrypt)
print(plaintext, key, expected, ciphertext, ciphertext == expected, decrypted, decrypted == plaintext)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment