Skip to content

Instantly share code, notes, and snippets.

@kravietz
Last active November 7, 2017 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kravietz/6d587c2027d3564062c725d16e83cfca to your computer and use it in GitHub Desktop.
Save kravietz/6d587c2027d3564062c725d16e83cfca to your computer and use it in GitHub Desktop.
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