From f875a1ba5bef6feb837e55bbe3e32e2d21382758 Mon Sep 17 00:00:00 2001 From: Harshil Darji Date: Mon, 1 Aug 2016 12:56:52 +0530 Subject: [PATCH] Cryptography Algorithm --- Simple Substitution Cipher.py | 62 +++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Simple Substitution Cipher.py diff --git a/Simple Substitution Cipher.py b/Simple Substitution Cipher.py new file mode 100644 index 000000000..4244434f2 --- /dev/null +++ b/Simple Substitution Cipher.py @@ -0,0 +1,62 @@ +import sys, random + +LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + +def main(): + message = input('Enter message: ') + key = 'LFWOAYUISVKMNXPBDCRJTQEGHZ' + resp = input('Encrypt/Decrypt [e/d]: ') + + checkValidKey(key) + + if resp.lower().startswith('e'): + mode = 'encrypt' + translated = encryptMessage(key, message) + elif resp.lower().startswith('d'): + mode = 'decrypt' + translated = decryptMessage(key, message) + + print('\n%sion: \n%s' % (mode.title(), translated)) + +def checkValidKey(key): + keyList = list(key) + lettersList = list(LETTERS) + keyList.sort() + lettersList.sort() + + if keyList != lettersList: + sys.exit('Error in the key or symbol set.') + +def encryptMessage(key, message): + return translateMessage(key, message, 'encrypt') + +def decryptMessage(key, message): + return translateMessage(key, message, 'decrypt') + +def translateMessage(key, message, mode): + translated = '' + charsA = LETTERS + charsB = key + + if mode == 'decrypt': + charsA, charsB = charsB, charsA + + for symbol in message: + if symbol.upper() in charsA: + symIndex = charsA.find(symbol.upper()) + if symbol.isupper(): + translated += charsB[symIndex].upper() + else: + translated += charsB[symIndex].lower() + else: + translated += symbol + + return translated + +def getRandomKey(): + key = list(LETTERS) + random.shuffle(key) + return ''.join(key) + +if __name__ == '__main__': + main()