Skip to content

Instantly share code, notes, and snippets.

@flipperbw
Created January 4, 2018 00:00
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 flipperbw/8c93cc6c24db1a6c72953c38c385ab36 to your computer and use it in GitHub Desktop.
Save flipperbw/8c93cc6c24db1a6c72953c38c385ab36 to your computer and use it in GitHub Desktop.
Vigenere Cipher in Python for all printable ASCII 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