Skip to content

Instantly share code, notes, and snippets.

@myano

myano/vigen.py Secret

Last active December 15, 2015 14:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myano/7e36d1a78b9a0aea03b4 to your computer and use it in GitHub Desktop.
Save myano/7e36d1a78b9a0aea03b4 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# vim: set fileencoding=UTF-8 :
'''
Vigenère Cipher implementation by Michael Yanovich (aka: yano)
Copyright 2013 - Licensed under the Eiffel Forum License v2
USAGE:
./vigen.py KEY
Enter text to be mangled: I LIKE CHEESE
Offset: 0
Encrypted: S PGUI ARICCI
'''
import math
import sys
import string
alpha = string.lowercase
try:
KEY = sys.argv[1]
except:
print 'Please run as ./vigen.py KEY_HERE'
sys.exit(1)
incoming = raw_input('Enter text to be mangled: ')
try:
offset = int(raw_input('Offset: '))
except:
print 'The offset was not a number!'
sys.exit(1)
## default to an offset of 1 if none provided
if not offset:
offset = 1
## subtract 1 so it works with python's 0's index for lists
## this part actually broke it, and ended up making it a ROT12
## when it should have been a ROT13
#offset -= 1
## generate the Vigenère square shading
chart = dict()
k = 0
for letter in alpha:
if k + offset >= len(alpha):
## rotation won't go beyond end of row
sanit = k + offset - len(alpha)
chart[letter] = alpha[sanit:] + alpha[:sanit]
else:
## rotation goes beyond the end of the row
chart[letter] = alpha[k + offset:] + alpha[:k + offset]
k += 1
## display the chart to stdout
ordered_rows = chart.keys()
ordered_rows.sort()
for x in ordered_rows:
print x, chart[x]
print ''
## pad the key with the length of the incoming text
multi = math.ceil(len(incoming) / float(len(KEY)))
long_key = KEY * int(multi)
## encrypted the incoming text
j = 0
output_encrypted = str()
for x in incoming:
y = x.lower()
if y in chart:
row = chart[y]
idx = (string.lowercase).find(long_key[j].lower())
output_encrypted += chart[y][idx]
j += 1
else:
output_encrypted += y
## decrypt the incoming text
p = 0
output_decrypted = str()
for x in incoming:
y = x.lower()
stop = False
before = len(output_decrypted)
for letter in chart:
row = chart[letter]
if not stop and y in chart:
idx = (string.lowercase).find(long_key[p].lower())
if row[idx] == y:
output_decrypted += letter
p += 1
stop = True
after = len(output_decrypted)
if before == after:
output_decrypted += y
print 'Encrypted:', output_encrypted.upper()
print 'Decrypted:', output_decrypted.upper()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment