Created
January 4, 2018 00:00
-
-
Save flipperbw/8c93cc6c24db1a6c72953c38c385ab36 to your computer and use it in GitHub Desktop.
Vigenere Cipher in Python for all printable ASCII characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
universe = [c for c in (chr(i) for i in range(32,127))] | |
uni_len = len(universe) | |
def vign(txt='', key='', typ='d'): | |
if not txt: | |
print 'Needs text.' | |
return | |
if not key: | |
print 'Needs key.' | |
return | |
if typ not in ('d', 'e'): | |
print 'Type must be "d" or "e".' | |
return | |
if any(t not in universe for t in key): | |
print 'Invalid characters in the key. Must only use ASCII symbols.' | |
return | |
ret_txt = '' | |
k_len = len(key) | |
for i, l in enumerate(txt): | |
if l not in universe: | |
ret_txt += l | |
else: | |
txt_idx = universe.index(l) | |
k = key[i % k_len] | |
key_idx = universe.index(k) | |
if typ == 'd': | |
key_idx *= -1 | |
code = universe[(txt_idx + key_idx) % uni_len] | |
ret_txt += code | |
print ret_txt | |
return ret_txt |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment