substitution cipher python code

Solutions on MaxInterview for substitution cipher python code by the best coders in the world

showing results for - "substitution cipher python code"
Todd
31 Apr 2019
1import random, sys
2
3LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
4def main():
5   message = ''
6   if len(sys.argv) > 1:
7      with open(sys.argv[1], 'r') as f:
8         message = f.read()
9   else:
10      message = raw_input("Enter your message: ")
11   mode = raw_input("E for Encrypt, D for Decrypt: ")
12   key = ''
13   
14   while checkKey(key) is False:
15      key = raw_input("Enter 26 ALPHA key (leave blank for random key): ")
16      if key == '':
17         key = getRandomKey()
18      if checkKey(key) is False:
19		print('There is an error in the key or symbol set.')
20   translated = translateMessage(message, key, mode)
21   print('Using key: %s' % (key))
22   
23   if len(sys.argv) > 1:
24      fileOut = 'enc.' + sys.argv[1]
25      with open(fileOut, 'w') as f:
26         f.write(translated)
27      print('Success! File written to: %s' % (fileOut))
28   else: print('Result: ' + translated)
29
30# Store the key into list, sort it, convert back, compare to alphabet.
31def checkKey(key):
32   keyString = ''.join(sorted(list(key)))
33   return keyString == LETTERS
34def translateMessage(message, key, mode):
35   translated = ''
36   charsA = LETTERS
37   charsB = key
38   
39   # If decrypt mode is detected, swap A and B
40   if mode == 'D':
41      charsA, charsB = charsB, charsA
42   for symbol in message:
43      if symbol.upper() in charsA:
44         symIndex = charsA.find(symbol.upper())
45         if symbol.isupper():
46            translated += charsB[symIndex].upper()
47         else:
48            translated += charsB[symIndex].lower()
49				else:
50               translated += symbol
51         return translated
52def getRandomKey():
53   randomList = list(LETTERS)
54   random.shuffle(randomList)
55   return ''.join(randomList)
56if __name__ == '__main__':
57   main()