Python/ciphers/simple_substitution_cipher.py

78 lines
1.7 KiB
Python
Raw Normal View History

2016-08-01 07:26:52 +00:00
import sys, random
2019-10-05 05:14:13 +00:00
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2016-08-01 07:26:52 +00:00
def main():
2019-10-05 05:14:13 +00:00
message = input("Enter message: ")
key = "LFWOAYUISVKMNXPBDCRJTQEGHZ"
resp = input("Encrypt/Decrypt [e/d]: ")
2016-08-01 07:26:52 +00:00
checkValidKey(key)
2019-10-05 05:14:13 +00:00
if resp.lower().startswith("e"):
mode = "encrypt"
2016-08-01 07:26:52 +00:00
translated = encryptMessage(key, message)
2019-10-05 05:14:13 +00:00
elif resp.lower().startswith("d"):
mode = "decrypt"
2016-08-01 07:26:52 +00:00
translated = decryptMessage(key, message)
2019-10-05 05:14:13 +00:00
print("\n%sion: \n%s" % (mode.title(), translated))
2016-08-01 07:26:52 +00:00
def checkValidKey(key):
keyList = list(key)
lettersList = list(LETTERS)
keyList.sort()
lettersList.sort()
if keyList != lettersList:
2019-10-05 05:14:13 +00:00
sys.exit("Error in the key or symbol set.")
2016-08-01 07:26:52 +00:00
def encryptMessage(key, message):
2016-08-02 17:46:55 +00:00
"""
>>> encryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Harshil Darji')
'Ilcrism Olcvs'
"""
2019-10-05 05:14:13 +00:00
return translateMessage(key, message, "encrypt")
2016-08-01 07:26:52 +00:00
def decryptMessage(key, message):
2016-08-02 17:46:55 +00:00
"""
>>> decryptMessage('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Ilcrism Olcvs')
'Harshil Darji'
"""
2019-10-05 05:14:13 +00:00
return translateMessage(key, message, "decrypt")
2016-08-01 07:26:52 +00:00
def translateMessage(key, message, mode):
2019-10-05 05:14:13 +00:00
translated = ""
2016-08-01 07:26:52 +00:00
charsA = LETTERS
charsB = key
2019-10-05 05:14:13 +00:00
if mode == "decrypt":
2016-08-01 07:26:52 +00:00
charsA, charsB = charsB, charsA
2016-08-01 07:26:52 +00:00
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
2019-10-05 05:14:13 +00:00
2016-08-01 07:26:52 +00:00
def getRandomKey():
key = list(LETTERS)
random.shuffle(key)
2019-10-05 05:14:13 +00:00
return "".join(key)
2016-08-01 07:26:52 +00:00
2019-10-05 05:14:13 +00:00
if __name__ == "__main__":
2016-08-01 07:26:52 +00:00
main()