How to code auto key cipher in python? - python

Can somebody help me write the auto_key cipher in python. I understand the logic but don't know how to start.I wrote the code but it didn't work this is my auto_key cipher code, when I run it gives me the new
key if key is less than message. and then stops there, it doesn't work.thank you!
enter code here
ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
message = input('enter message:\n')
key = input('enter your key:\n')
mode = input('encrypt or decrypt\n')
if len(key) < len(message):
key = key[0:] + message[:100]
#print(key)
if mode == 'encrypt':
cipher = encryptMessage(message, key)
elif mode == 'decrypt':
cipher = decryptMessage(message, key)
#print(' message:', (mode.title()))
print(cipher)
def encryptMessage (keys, messages):
return cipherMessage(keys, messages, 'encrypt')
def decryptMessage(keys,messages):
return cipherMessage(keys, messages, 'decrypt')
def cipherMessage (keys, messages, mode):
cipher = []
k_index = 0
key = keys.upper()
for i in messages:
text = ALPHA.find(i.upper())
if text != -1:
if mode == 'encrypt':
text += ALPHA.find(key[k_index])
elif mode == 'decrypt':
text -= ALPHA.find(key[k_index])
text %= len(ALPHA)
k_index += -1
if k_index == len(key):
k_index = 0
else:
cipher.append(i)
return ''.join(cipher)
if __name__ == "__main__":
main()

Even though I fixed your code I recommend you start all over again.
Your code is a mess! :D
It works now, but it will still fail if the input does not fit, the logic you implemented.
Let's go:
Lines 8-9:
Useless at this point!
Note: What would happen if len(key) == 5 and len(message) == 130?
Line 16-17, 18-19 and 20:
In line 10 and 13 you call function(message, key), but here you
call:
def function((keys, messages)):
return cipherMessage((keys, messages), 'encrypt')
You switched message and key, that was the reason for the IndexError.
Line 26:
Useless in this for-loop
Line 34:
k_index must be increased!
Line 35-37:
this if is useless in this for-loop
this else: is the reason cipher.append(i) is never reached
Line 38:
To cipher you need to add the shortly encrypted/decrypted char , not the
char form message
Fixing all that, you'll get the below code.
Note: comments with ## indicate what I commented out of your code.
ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
message = input('enter message:\n')
key = input('enter your key:\n')
mode = input('encrypt or decrypt\n')
## if len(key) < len(message):
## key = key[0:] + message[:100]
#print(key)
if mode == 'encrypt':
cipher = encryptMessage(message, key)
elif mode == 'decrypt':
cipher = decryptMessage(message, key)
#print(' message:', (mode.title()))
print(cipher)
## def encryptMessage (keys, messages):
## return cipherMessage(keys, messages, 'encrypt')
def encryptMessage (messages, keys):
return cipherMessage(messages, keys, 'encrypt')
## def decryptMessage(keys,messages):
## return cipherMessage(keys, messages, 'decrypt')
def decryptMessage(messages, keys):
return cipherMessage(messages, keys, 'decrypt')
## def cipherMessage (keys, messages, mode):
def cipherMessage (messages, keys, mode):
cipher = []
k_index = 0
key = keys.upper()
for i in messages:
text = ALPHA.find(i.upper())
## if text != -1:
if mode == 'encrypt':
text += ALPHA.find(key[k_index])
key += i.upper() # add current char to keystream
elif mode == 'decrypt':
text -= ALPHA.find(key[k_index])
key += ALPHA[text] # add current char to keystream
text %= len(ALPHA)
## k_index += -1
k_index += 1
## if k_index == len(key):
## k_index = 0
## else:
cipher.append(ALPHA[text])
return ''.join(cipher)
if __name__ == "__main__":
main()

Related

How would I fix my Vigenere Cipher Decryption

I'm having an issue with Vigenere Cipher Decryption, When an encrypted message is decrypted, the decrypted message is not printed, but the encrypted is?
I cant seem to see why this dose not work. But its probably a simple issue.
I think the issue is in the main decrypt function.
Help would be much appreciated
Encryption works fine
def encrypt_key(message, key):
i = 0
empty_key = '' # empty key to append to
# turn characters into index
for characters in message:
if characters.isalpha(): # checks if character is in the alphabet
empty_key = empty_key + key[i % len(key)] # append characters to empty key
i = i + 1 # increase integer value by 1
else:
empty_key = empty_key + ' ' # if character is a space or punctuation then add empty space
return empty_key
def encrypt_decrypt(message_char, key_char, choice='encrypt'):
if message_char.isalpha():
first_alphabet_letter = 'a' # assume character is lowercase
if message_char.isupper():
first_alphabet_letter = 'A' # assume character is upper, then replace with A
original_char_position = ord(message_char) - ord(first_alphabet_letter) # difference results in position of char in alphabet
key_char_position = ord(key_char.lower()) - ord('a')
if choice == 'encrypt':
new_char_position = (original_char_position + key_char_position) % 26 # encrypts & loops back around with % 26
else: # if choice == 'decrypt':
new_char_position = (original_char_position - key_char_position + 26) % 26 # decrypts & loops back around
return chr(new_char_position + ord(first_alphabet_letter))
return message_char
def encrypt(message, key):
cipher = ''
empty_key = encrypt_key(message, key)
for message_char, key_char in zip(message, empty_key):
cipher = cipher + encrypt_decrypt(message_char, key_char)
return cipher
def decrypt(cipher, key):
message = ''
empty_key = encrypt_key(cipher, key)
for cipher_char, key_char in zip(cipher, empty_key):
message = message + encrypt_decrypt(cipher_char, key_char, 'decrypt')
return message
message = input('Enter your message to encrypt here: ')
key = input('Enter your key: ')
cipher = encrypt(message, key) # inputs message and key to encrypt function
decrypt_message = decrypt(cipher, key)# inputs message and key to decrypt function
print(f'Cipher: {cipher}')
print(f'Decrypted: {decrypt_message}')
def choice():
user_choice = int(input('''
Enter your choice (1 or 2):
1. Encrypt
2. Decrypt
> '''))
if user_choice == 1:
print(f'Cipher: {cipher}')
print('')
elif user_choice == 2:
print('')
print(f'Decrypted: {decrypt_message}')
choice()

Decipher Python Problem with One Time Pad

I am new to programming and am trying to create a program where I am given a one time pad and want to decipher a basic message file using my program. I am having trouble matching up the ASCII and pad (I can't figure out a "code" or formula for my shift in characters). Any and all help will be greatly appreciated. I have set pad = 9 because idk what or how to shift the letters. Here is the pad I was given:
(JKKIAARZLXNPWAXQCCBTMAUADQHVOLPRNYXVUHOVJWLJOSUCREEJZTHHWDFQNVGPPKJPGRXMRZSTPYLLFCRUSZRMAUVBCTTCRZTEOTDUATIBKODFRZPPNZYPJWDSVAULSEWYQEJBYEEBSSMARUMCXVCVUMJBKSGLYDNCCBODHRTKDEQOBKTJWSYDVIRXEKALETMDPJQXHDQRPQUOCLBUHUZKISBIOJPPMLIDMOXRWWHFBWFZJDCORDZLIWCPFQWXBREGAAUORPHFHYSOBTLZXCQKMEFFUKCZBYJCCDBVWJYAAOGXMITKTQNIPCVVCHXHJPEZIAHYFIHNIVBUHYNMVYACTLQSSLUHTWXHOFGDEQYXWXIVJSUVTOKOMWXFFINXVYJXJFXVVDWRZNPZIGSQGPWXZWZAEYSLGOBUAVEZRDKFPWYOZXEHZCIAQZZYZHGYKIEDXILJFZVFVZYSEZBOJQGVEDABYNHCLACUXLHHWWAWNWMGDLIIHMEBPEKGEOCDLHWUQRXNYRJLKWLMSGJJSTIEAJEYMSRQNFSFEVMBYCMXKHRZEDHIRPYDKHMJIDRFAZNOCFBVMGHPKGVEVCBYEUBTCSYMUEJWOQUQHYWOPEZEVRZXDRYWJQJDPDVVUUPWXKWZMMAVRPWPWNZGQVFKIEGGZSITTPCMAGWHQJKRZCMYKRUBVEFXGMXJRXIJJHDFMMSPSYZIVNAEMMGZCWMGSEHMDEXRMFCGJPOYTPTSHHLVFPOCNDYCJECKYTKOPZSZIVPQUPWMUBAEJIFJVQWNZTOGVTSTETFFEHMSVTDYSPFTOYPJGAVNTUBSFRWQPWFLDYXPPIBVWSKROVEEKPVKFEPFXLMGJQIBRMOPVSPNYUPAPCEWGFDGBJLVGHWWLDIOVHYUSONUTCDOMIBPLGINXSPACRYVPAJZKPOPICROFQKOWPTFTKYCJDUZZJUUSRCHCKJDUMFRUFWBNGTTDSSKTQQGHQVIUWMZCZDSBFSC)
Which I saved as a text file and then read in.
msg = "This is an amazing secret message!"
pad = open("pad.txt", "r")
shift = 9
def shift_letter(c,shift):
pad_count = 0
code = ord(c)
if (code>=65) and (code<=90):
code = ((code-shift-39)%26)+65
pad_count = pad_count + 1
elif (code>=97) and (code<=122):
code = (code-shift-71)%26+97
return chr(code)
def shift_message(msg, shift):
seq = list(msg)
for i in range(0,len(msg)):
seq[i] = shift_letter(seq[i],shift)
return "".join(seq)
def encrypt(msg):
return shift_message(msg,shift)
def decrypt(msg):
return shift_message(msg,shift)
def main ():
encrypted_message = encrypt(msg)
print(encrypted_message)
final_message = decrypt(encrypted_message)
print(final_message)
if __name__ == "__main__":
main()
You have to read the shift from your pad file:
with open("pad.txt") as f:
pad = f.read()
def letter_ord(letter):
return ord(letter.upper())-ord("A")
def shift_letter(old, shift):
old = old.upper()
new_ord = ord(old)+shift
if new_ord > ord("Z"):
new_ord -= 26
elif new_ord < ord("A"):
new_ord += 26
return chr(new_ord)
def crypt(text, mode=1): # mode is 1 for encrypt and -1 for decrypt
res = ""
for t_text, t_pad in zip(text, pad):
res += shift_letter(t_text, letter_ord(t_pad)*mode)
return res
def encrypt(text):
return crypt(text, 1)
def decrypt(text):
return crypt(text, -1)

Script stops executing once it encounters def line

So, I had 2 scripts, a Vigenere cipher and a Caesar cipher, however, when I decided to merge them into a "mainproject" file by using "import" to import the script after the wanted answer from the user is sent on the Terminal page, when I've done the code and decided to execute the mainproject, I've got the question whether to choose to use Vigenere or Caesar, once I typed caesar (1) it played the first 2-4 lines and stopped the code once I've encountered the "def" line on both of scripts, if thats the problem, I can't use imports with "def", how can I merge them both into one file that asks which script I would like to use?
Caesar:
import time
import sys
print("Welcome to Caesar Cipher")
time.sleep(3)
print("Choose the corresponding number to Encrypt or Decrypt in Caesar Cipher")
def encryption():
print("Encryption")
print("You have chose ENCRYPTION")
msg = input("Enter message: ")
key = int(input("Enter key(0-25): "))
encrypted_text = ""
for i in range(len(msg)):
if ord(msg[i]) == 32:
encrypted_text += chr(ord(msg[i]))
elif ord(msg[i]) + key > 122:
temp = (ord(msg[i]) + key) - 122
encrypted_text += chr(96+temp)
elif (ord(msg[i]) + key > 90) and (ord(msg[i]) <= 96):
temp = (ord(msg[i]) + key) - 90
encrypted_text += chr(64+temp)
else:
encrypted_text += chr(ord(msg[i]) + key)
print("Your Encrypted Message: " + encrypted_text)
def decryption():
print("Decryption")
print("You have chose DECRYPTION")
encrp_msg = input("Enter encrypted Text: ")
decrp_key = int(input("Enter key(0-25): "))
decrypted_text = ""
for i in range(len(encrp_msg)):
if ord(encrp_msg[i]) == 32:
decrypted_text += chr(ord(encrp_msg[i]))
elif ((ord(encrp_msg[i]) - decrp_key) < 97) and ((ord(encrp_msg[i]) - decrp_key) > 90):
temp = (ord(encrp_msg[i]) - decrp_key) + 26
decrypted_text += chr(temp)
elif (ord(encrp_msg[i]) - decrp_key) < 65:
temp = (ord(encrp_msg[i]) - decrp_key) + 26
decrypted_text += chr(temp)
else:
decrypted_text += chr(ord(encrp_msg[i]) - decrp_key)
print("Text has been Decrypted: " + decrypted_text)
choice = int(input("1. Encryption\n2. Decryption\nChoose(1,2): "))
if choice == 1:
encryption()
elif choice == 2:
decryption()
else:
print("Wrong Choice")
Vigenere:
import time
print("Welcome to Vigenere Cipher")
time.sleep(2)
print("Choose the corresponding number to Encrypt or Decrypt in Vigenere Cipher")
time.sleep(2.5)
def msg_and_key():
msg = input("Enter message: ").upper()
key = input("Enter key: ").upper()
key_map = ""
j=0
for i in range(len(msg)):
if ord(msg[i]) == 32:
key_map += " "
else:
if j < len(key):
key_map += key[j]
j += 1
else:
j = 0
key_map += key[j]
j += 1
return msg, key_map
def create_vigenere_table():
table = []
for i in range(26):
table.append([])
for row in range(26):
for column in range(26):
if (row + 65) + column > 90:
table[row].append(chr((row+65) + column - 26))
else:
table[row].append(chr((row+65)+column))
return table
def cipher_encryption(message, mapped_key):
table = create_vigenere_table()
encrypted_text = ""
for i in range(len(message)):
if message[i] == chr(32):
encrypted_text += " "
else:
row = ord(message[i])-65
column = ord(mapped_key[i]) - 65
encrypted_text += table[row][column]
print("Encrypted Message: {}".format(encrypted_text))
def itr_count(mapped_key, message):
counter = 0
result = ""
for i in range(26):
if mapped_key + i > 90:
result += chr(mapped_key+(i-26))
else:
result += chr(mapped_key+i)
for i in range(len(result)):
if result[i] == chr(message):
break
else:
counter += 1
return counter
def cipher_decryption(message, mapped_key):
table = create_vigenere_table()
decrypted_text = ""
for i in range(len(message)):
if message[i] == chr(32):
decrypted_text += " "
else:
decrypted_text += chr(65 + itr_count(ord(mapped_key[i]), ord(message[i])))
print("Decrypted Message: {}".format(decrypted_text))
print("Key and Message can only be alphabetic")
time.sleep(1.5)
choice = int(input("1. Encryption\n2. Decryption\nChoose(1,2): "))
if choice == 1:
print("You have chose ENCRYPTION")
message, mapped_key = msg_and_key()
cipher_encryption(message, mapped_key)
elif choice == 2:
print("You have chose DECRYPTION")
message, mapped_key = msg_and_key()
cipher_decryption(message, mapped_key)
else:
print("Wrong choice")
Any help would be appreciated!
def only defines a function. To actually execute it you need to call it.
It seems the following part should be outside of decryption function body i.e. indented to the left. It:
call be executed directly on the module level
can be a separate function e.g. main that you can call
As main:
def main():
choice = int(input("1. Encryption\n2. Decryption\nChoose(1,2): "))
if choice == 1:
encryption()
elif choice == 2:
decryption()
else:
print("Wrong Choice")
And now you can call the main function:
main()
Welcome to Stackoverflow. This answer ended up more as general advice than a specific point solution to your problem, but I hope it's helpful.
One obvious remark is that it would be nice not to have to import the code for the cypher you don't intend to use.
Imports are executable statements, so this is quite practical.
Your code is far from optimally organised. Much of the code on the two files is the same or very similar. This is not unusual for new programmers, as it takes a while to learn how to break problems down and extract the common elements. The real problem is that while it defines lots of functions, none of them actually get called (unless there's more code you haven't included).
I would recommend that you modify your code so that there's a top-level program that collects the key and data and performs the required operations, along with your two
encryption/decryption modules. The encryption and decryption routines shouldn't do any input or output at all, just deal with the data.
Let's assume you have a variable mtype that holds the type of encryption you want to use. The top-level logic could look something like this:
if mtype == "caesar":
from caesar import encrypt, decrypt
elif mtype == "vigniere":
from vigniere import encrypt, decrypt
else:
sys.exit("Unrecognised message type")
If this code succeeds you would then have an encrypt and a decrypt function from the correct module. This means that they have to have the same interface, since your logic must now be written to accommodate either.
The remainder of your logic would look something like this (untested):
operation = input("E(ncrypt) or D(ecrypt)? ")
if operation.upper().startswith("E"):
function = encrypt
elif operation.upper().startswith("D"):
function = decrypt
else:
sys.exit("Unknown operation")
message = input(...)
key = input(...)
output = function(message, key)
This will hopefully make your code clearer by separating out the I/O responsibility
from the encryption and decryption tasks.

String index not working? - Python

I'm Making a sort of cipher that requires a string to be read backwards and i get an indexing error even though the index I reference is well within range:
M = str(input("Input Message: "))
M = M.upper()
L = len(M)
A = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
def DECRYPT():
global L
global M
global A
if L%2 != 0:
POS = False
else:
POS = True
i = L-1
NM = ""
while 1:
if M[i] != " ":
INDEX = A.index(M[i])
if POS == True:
INDEX += (i + 1)
else:
INDEX -= (i)
INDEX %= 26
NM = NM+A[INDEX]
i += 1
if POS == True:
POS = False
else:
POS = True
print("\n"+NM)
def ENCRYPT():
global L
global A
global M
POS = True
M = M[::-1]
i = 0
NM = ""
while 1:
if i == L:
break
if M[i] != " ":
INDEX = A.index(M[i])
if POS == True:
INDEX += (i + 1)
else:
INDEX -= (i + 1)
INDEX %= 26
NM = NM+A[INDEX]
i += 1
if POS == True:
POS = False
else:
POS = True
print("\n"+NM)
while 1:
C = int(input("\nWhat do you want to do:\n1) Encrypt Something\n2)Decrypt Something\n\n"))
if C == 1:
ENCRYPT()
if C == 2:
DECRYPT()
where i is a placeholder value. I run it and get this:
Input Message: ABC
What do you want to do:
1) Encrypt Something
2)Decrypt Something
2
Traceback (most recent call last):
File "C:\Users\Danny\Google Drive\SHIFT.py", line 67, in <module>
DECRYPT()
File "C:\Users\Danny\Google Drive\SHIFT.py", line 19, in DECRYPT
if M[i] != " ":
IndexError: string index out of range
I have tried changing value of i to no avail.
There are multiple problems with your code: as fernand0 noted, your index runs the wrong way; your inversion of POS happens at different levels in the code, the encryptor does it on every character, the decryptor does it on every letter -- they should work the same; five of your six global declarations aren't needed; you don't deal with word breaks correctly so the decryption won't match the original; once you encrypt, there's no way to decrypt in the same session as the local NM doesn't feedback into the global M.
Below is my rework of your code addressing the above problems and some style issues. The key phrase here is 'simplify'. I've kept your odd uppercase variable names but expanded them from single characters to what they represent:
MESSAGE = input("Input Message: ").upper()
ALPHABET = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
ALPHABET_LENGTH = len(ALPHABET)
def DECRYPT(MESSAGE):
LENGTH = len(MESSAGE)
IS_NEGATIVE = True
NEW_MESSAGE = ""
for I in range(LENGTH):
if MESSAGE[I] in ALPHABET:
INDEX = ALPHABET.index(MESSAGE[I])
if IS_NEGATIVE:
INDEX -= (I + 1)
else:
INDEX += (I + 1)
INDEX %= ALPHABET_LENGTH
NEW_MESSAGE += ALPHABET[INDEX]
IS_NEGATIVE = not IS_NEGATIVE
else:
NEW_MESSAGE += MESSAGE[I]
return NEW_MESSAGE[::-1]
def ENCRYPT(MESSAGE):
MESSAGE = MESSAGE[::-1]
LENGTH = len(MESSAGE)
IS_POSITIVE = True
NEW_MESSAGE = ""
for I in range(LENGTH):
if MESSAGE[I] in ALPHABET:
INDEX = ALPHABET.index(MESSAGE[I])
if IS_POSITIVE:
INDEX += (I + 1)
else:
INDEX -= (I + 1)
INDEX %= ALPHABET_LENGTH
NEW_MESSAGE += ALPHABET[INDEX]
IS_POSITIVE = not IS_POSITIVE
else:
NEW_MESSAGE += MESSAGE[I]
return NEW_MESSAGE
while True:
print("\nWhat do you want to do:")
print("1) Encrypt Message")
print("2) Decrypt Message")
CHOICE = int(input("\n"))
if CHOICE == 1:
MESSAGE = ENCRYPT(MESSAGE)
if CHOICE == 2:
MESSAGE = DECRYPT(MESSAGE)
print("\n" + MESSAGE)
TEST
> python3 file.py
Input Message: An opportunity to teach is an opportunity to learn
What do you want to do:
1) Encrypt Message
2) Decrypt Message
1
OPDAQ HB OEWAGIBFXIU JD RI JZEZZ GC NFVBFJAGWJT KC
What do you want to do:
1) Encrypt Message
2) Decrypt Message
2
AN OPPORTUNITY TO TEACH IS AN OPPORTUNITY TO LEARN
What do you want to do:
1) Encrypt Message
2) Decrypt Message
You are starting i at the end of the string and then, you are increasing it. I think the line i += 1 should be i -= 1

UnboundLocalError: local variable 'key' referenced before assignment

I am trying to import a text file and encrypt/decrypt by two key words. I set a key variable but can't find the correct place to locate it.
Here is where it currently is:
def importFile():
importText = []
file = input('What is the text file name: ')
fileName = open(file,'r')
text = fileName.read()
fileName.close()
fileName = text
message = text
#print (text)
delete = open(file,'w')
delete.write('')
key = input ('What key do you wnat to use: ')
Here is where the key is called:
def translatedMessage(mode):
translated = []
keyIndex = 0
key = key.upper()
for symbol in message:
num =LETTERS .find(symbol.upper())
if num != -1:
if mode == 'encrypt':
num += LETTERS .find(key[keyIndex])
elif mode == 'decrypt':
num -= LETTERS .find(key[keyIndex])
num %= len(LETTERS)
if symbol.isupper():
translated.append(LETTERS[num])
elif symbol.islower():
translated.append(LETTERS[num].lower())
keyIndex += 1
if keyIndex == len(key):
keyIndex = 0
else:
translated.append(symbol)
return ''.join(translated)
if __name__ == '__main__':
main()
If you need it here is it all together:
LETTERS = 'ZABCDEFGHIJKLMNOPQRSTUVWXY'
def main():
myMode = input("Encrypt 'e' or Decrypt 'd': ")
if myMode == 'encrypt' or myMode == 'e':
translated = encryptFile()
elif myMode == 'decrypt' or myMode == 'd':
translated = decryptFile()
def importFile():
importText = []
file = input('What is the text file name: ')
fileName = open(file,'r')
text = fileName.read()
fileName.close()
fileName = text
message = text
#print (text)
delete = open(file,'w')
delete.write('')
key = input ('What key do you wnat to use: ')
def encryptFile():
textFile = input("Would you like to import a text file 'Y' or 'N': ")
if textFile.lower() == 'y' :
importFile()
return translatedMessage('encrypt')
def decryptFile():
textFile = input("Would you like to import a text file 'Y' or 'N': ")
if textFile.lower() == 'y' :
importFile()
return translatedMessage('decrypt')
def translatedMessage(mode):
translated = []
keyIndex = 0
key = key.upper()
for symbol in message:
num =LETTERS .find(symbol.upper())
if num != -1:
if mode == 'encrypt':
num += LETTERS .find(key[keyIndex])
elif mode == 'decrypt':
num -= LETTERS .find(key[keyIndex])
num %= len(LETTERS)
if symbol.isupper():
translated.append(LETTERS[num])
elif symbol.islower():
translated.append(LETTERS[num].lower())
keyIndex += 1
if keyIndex == len(key):
keyIndex = 0
else:
translated.append(symbol)
return ''.join(translated)
if __name__ == '__main__':
main()
I'm pretty new to coding and know this is pretty simple so any advice is greatly appreciated:)
The problem in your code is that you are treating key like a global variable, but it is a local one, so you need to pass it between your functions:
LETTERS = 'ZABCDEFGHIJKLMNOPQRSTUVWXY'
def main():
myMode = input("Encrypt 'e' or Decrypt 'd': ")
if myMode == 'encrypt' or myMode == 'e':
translated = encryptFile()
elif myMode == 'decrypt' or myMode == 'd':
translated = decryptFile()
def importFile():
importText = []
file = input('What is the text file name: ')
fileName = open(file,'r')
text = fileName.read()
fileName.close()
fileName = text
message = text
#print (text)
delete = open(file,'w')
delete.write('')
return input ('What key do you wnat to use: ') # Return the key
def encryptFile():
textFile = input("Would you like to import a text file 'Y' or 'N': ")
if textFile.lower() == 'y' :
key = importFile() # Get the key returned by the function
return translatedMessage('encrypt', key) # Pass the key to the function
def decryptFile():
textFile = input("Would you like to import a text file 'Y' or 'N': ")
if textFile.lower() == 'y' :
key = importFile() # Get the key returned by the function
return translatedMessage('decrypt', key) # Pass the key to the function
def translatedMessage(mode, key): # `key` is an argument
translated = []
keyIndex = 0
key = key.upper()
for symbol in message:
num =LETTERS .find(symbol.upper())
if num != -1:
if mode == 'encrypt':
num += LETTERS .find(key[keyIndex])
elif mode == 'decrypt':
num -= LETTERS .find(key[keyIndex])
num %= len(LETTERS)
if symbol.isupper():
translated.append(LETTERS[num])
elif symbol.islower():
translated.append(LETTERS[num].lower())
keyIndex += 1
if keyIndex == len(key):
keyIndex = 0
else:
translated.append(symbol)
return ''.join(translated)
if __name__ == '__main__':
main()
A simpler solution would be to define key as a global variable by adding the line global key to the importFile() function. In general however, I think using the global keyword in Python is discouraged.
This explanation of global vs. local variables in Python might be helpful: http://www.python-course.eu/global_vs_local_variables.php

Categories

Resources