|
| 1 | +import sys, random |
| 2 | + |
| 3 | +LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' |
| 4 | + |
| 5 | +def main(): |
| 6 | +message = input('Enter message: ') |
| 7 | +key = 'LFWOAYUISVKMNXPBDCRJTQEGHZ' |
| 8 | +resp = input('Encrypt/Decrypt [e/d]: ') |
| 9 | + |
| 10 | +checkValidKey(key) |
| 11 | + |
| 12 | +if resp.lower().startswith('e'): |
| 13 | +mode = 'encrypt' |
| 14 | +translated = encryptMessage(key, message) |
| 15 | +elif resp.lower().startswith('d'): |
| 16 | +mode = 'decrypt' |
| 17 | +translated = decryptMessage(key, message) |
| 18 | + |
| 19 | +print('\n%sion: \n%s' % (mode.title(), translated)) |
| 20 | + |
| 21 | +def checkValidKey(key): |
| 22 | +keyList = list(key) |
| 23 | +lettersList = list(LETTERS) |
| 24 | +keyList.sort() |
| 25 | +lettersList.sort() |
| 26 | + |
| 27 | +if keyList != lettersList: |
| 28 | +sys.exit('Error in the key or symbol set.') |
| 29 | + |
| 30 | +def encryptMessage(key, message): |
| 31 | +return translateMessage(key, message, 'encrypt') |
| 32 | + |
| 33 | +def decryptMessage(key, message): |
| 34 | +return translateMessage(key, message, 'decrypt') |
| 35 | + |
| 36 | +def translateMessage(key, message, mode): |
| 37 | +translated = '' |
| 38 | +charsA = LETTERS |
| 39 | +charsB = key |
| 40 | + |
| 41 | +if mode == 'decrypt': |
| 42 | +charsA, charsB = charsB, charsA |
| 43 | + |
| 44 | +for symbol in message: |
| 45 | +if symbol.upper() in charsA: |
| 46 | +symIndex = charsA.find(symbol.upper()) |
| 47 | +if symbol.isupper(): |
| 48 | +translated += charsB[symIndex].upper() |
| 49 | +else: |
| 50 | +translated += charsB[symIndex].lower() |
| 51 | +else: |
| 52 | +translated += symbol |
| 53 | + |
| 54 | +return translated |
| 55 | + |
| 56 | +def getRandomKey(): |
| 57 | +key = list(LETTERS) |
| 58 | +random.shuffle(key) |
| 59 | +return ''.join(key) |
| 60 | + |
| 61 | +if __name__ == '__main__': |
| 62 | +main() |
0 commit comments