secret
Last active

  • Download Gist
vigen.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
#!/usr/bin/env python
# -*- 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()

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.