Created
March 22, 2016 17:56
-
-
Save mgeeky/d9f7d1b895c58f80d3e6 to your computer and use it in GitHub Desktop.
Very old script of mine implementing Vigenere's cipher encrypt/decrypt.
This file contains hidden or 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
#!/usr/bin/python | |
# | |
# Simple encoder/decoder of Vigenere cipher | |
# | |
#----------------------------------------- | |
from string import * | |
g_Tabula = [] | |
g_Alls = [] | |
#----------------------------------------- | |
def getindex( char): | |
for i in g_Tabula: | |
if i[0] == char: | |
return g_Tabula.index(i) | |
return -1 | |
def encode(psk, txt): | |
enc = '' | |
i = 0 | |
for a in txt: | |
i += 1 | |
if a in g_Alls: | |
id = getindex(psk[i % len(psk)]) | |
if id == -1: | |
enc += a | |
continue | |
enc += g_Tabula[id][g_Alls.find(a)] | |
else: | |
enc += a | |
return enc | |
def decode(psk, txt): | |
raw = '' | |
enc = '' | |
i = 0 | |
for a in txt: | |
i += 1 | |
if a in g_Alls: | |
id = getindex(psk[i % len(psk)]) | |
if id == -1: | |
enc += a | |
continue | |
raw += g_Alls[g_Tabula[id].find(txt[i-1])] | |
else: | |
raw += a | |
return raw | |
#----------------------------------------- | |
if __name__ == '__main__': | |
# Generating Trithemius Tabula Recta | |
g_Alls = ascii_letters + digits | |
for i in range( len( g_Alls)): | |
g_Tabula.append( g_Alls[i:] + g_Alls[0:i] ) | |
print '\n\t\tVigenere\'s cipher encoder/decoder' | |
print 'Used alphabet:\n' + g_Alls | |
opt = 0 | |
while 1: | |
o = raw_input( '\nType:\t0 for encode\t1 for decode\t') | |
if o == '1': | |
opt = 1 | |
break | |
elif o == '0': | |
break | |
psk = '' | |
while len(psk) == 0: | |
psk = raw_input( 'Input passphrase:\t') | |
txt = '' | |
file = '' | |
txt = raw_input('\nInput text to encode or "file" and filename' \ | |
'to specify file:\n') | |
if 'file ' in lower(txt) : | |
file = txt[txt.find(' ')+1:] | |
f = open( file, 'r') | |
txt = '' | |
txt = f.read() | |
f.close() | |
enc = '' | |
if opt == 1: | |
enc = decode(psk, txt) | |
else: | |
enc = encode(psk, txt) | |
if len( file) > 0: | |
s = 'encoded' | |
if opt == 1: s = 'decoded' | |
f = open( file[:file.rfind('.')]+'_' + s + \ | |
file[file.rfind('.'):] ) | |
f.write( enc) | |
f.close() | |
else: | |
s = 'Encoded' | |
if opt == 1: s = 'Decoded' | |
print '\n%s:\t***********************\n' % s | |
print enc + '\n' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment