# Vigenere Cipher Program # #import everything import os, os.path, string #Pretty Title print "*************************************" print "* Vigenere Coder / Decoder *" print "*************************************" print # Get input directory, see if it exists, and change into it def get_dir(): directory = raw_input("Path to text file directory: ") if not os.path.isdir(directory): print "Invalid directory" directory = get_dir() return directory directory = get_dir() os.chdir(directory) #Get filename, test for file def get_file(): input_file = raw_input("Name of text file: ") if not os.path.isfile(input_file): print "Invalid file name." input_file = get_file() return input_file in_file = get_file() # Open and read input text source = open(in_file, "r") source_txt = source.read() source.close() #put in standard case to make encode easier item = string.lower(source_txt) #Encode or decode? cypher = raw_input("[E]ncode or [D]ecode: ") cypher = string.upper(cypher) #prepare outfile out_name = raw_input("Name of Output File: ") outfile = open(out_name, "a") out_text = [] #Request Code / Decode Key key = raw_input("Cypher Key: ") key = string.lower(key) #make len(keyword) equal len(item) padded_key = key while len(padded_key) < len(source_txt): padded_key = padded_key + key #convert padded_key to ascii number num_key = [] for p in padded_key: num_p = ord(p) num_key.append(num_p) #convert source_txt to ascii number num_source = [] for i in source_txt: num_i = ord(i) num_source.append(num_i) #add num values together num_cypher = [] index = 0 for num in num_source: if cypher == "E": new_num = num_source[index] + num_key[index] elif cypher == "D": new_num = num_source[index] - num_key[index] else: pass #Adjust for numbers too big if new_num > 255: new_num = (new_num - 255) elif new_num < 0: new_num = (new_num + 255) else: pass num_cypher.append(new_num) index = index + 1 #convert ascii num to letters cypher_chr = "" for nc in num_cypher: cypher_chr = cypher_chr + chr(nc) #Write new text to out file outfile.write(cypher_chr) outfile.close() #Tell them we are all done now if cypher == "E": print "Text encrypted." elif cypher =="D": print "Text decoded." else: print "I don't know what happened. Probably nothing."