Skip to content

Instantly share code, notes, and snippets.

@beoliver
Last active December 10, 2015 23:48
Show Gist options
  • Save beoliver/4511562 to your computer and use it in GitHub Desktop.
Save beoliver/4511562 to your computer and use it in GitHub Desktop.
a (functional) python 3.x vigenere encoder / decoder.
# ben oliver 11.01.2013
# a (functional) python 3.x vigenere encoder / decoder.
# encode and decode functions are mathematical, no dictionary lookups.
from itertools import cycle
from functools import partial
from string import ascii_uppercase
def transform(crypt_function,k,s):
""" (Int -> Int -> Int) -> Char -> Char -> Char """
return chr(crypt_function(ord(k), ord(s)))
def encode26(a,b):
""" Int -> Int -> Int """
return (((a + b) - 130) % 26) + 65
def decode26(a,b):
""" Int -> Int -> Int """
return (((b - a) - 130) % 26) + 65
def cipher(crypt_function,key,string):
""" (Int -> Int -> Int) -> String -> String -> String """
transform_function = partial(transform, crypt_function)
mapped_transform = map(transform_function, cycle(key), string)
return ''.join(mapped_transform)
def safe_cipher(crypt_function,key,string):
""" (Int -> Int -> Int) -> String -> String -> (String,String)
converts lowercase to uppercase , removing digits, whitespace & punctuation"""
k = ''.join(filter(lambda k: k in ascii_uppercase, key.upper()))
s = ''.join(filter(lambda s: s in ascii_uppercase, string.upper()))
return (k, cipher(crypt_function,k,s))
### example ##################################################################################
# >>> (password,encoded) = safe_cipher( encode26, "password", "This... is the string to encode!!!" )
# >>> cipher(decode26,password,encoded)
# 'THISISTHESTRINGTOENCODE'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment