Python/ciphers/vigenere_cipher.py

66 lines
1.7 KiB
Python
Raw Normal View History

2019-10-05 05:14:13 +00:00
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2016-08-11 12:44:46 +00:00
def main():
2019-10-05 05:14:13 +00:00
message = input("Enter message: ")
key = input("Enter key [alphanumeric]: ")
mode = input("Encrypt/Decrypt [e/d]: ")
2016-08-11 12:44:46 +00:00
2019-10-05 05:14:13 +00:00
if mode.lower().startswith("e"):
mode = "encrypt"
2016-08-11 12:44:46 +00:00
translated = encryptMessage(key, message)
2019-10-05 05:14:13 +00:00
elif mode.lower().startswith("d"):
mode = "decrypt"
2016-08-11 12:44:46 +00:00
translated = decryptMessage(key, message)
2019-10-05 05:14:13 +00:00
print("\n%sed message:" % mode.title())
2016-08-11 12:44:46 +00:00
print(translated)
2019-10-05 05:14:13 +00:00
def encryptMessage(key: str, message: str) -> str:
2019-10-05 05:14:13 +00:00
"""
2016-08-11 12:44:46 +00:00
>>> encryptMessage('HDarji', 'This is Harshil Darji from Dharmaj.')
'Akij ra Odrjqqs Gaisq muod Mphumrs.'
2019-10-05 05:14:13 +00:00
"""
return translateMessage(key, message, "encrypt")
2016-08-11 12:44:46 +00:00
def decryptMessage(key: str, message: str) -> str:
2019-10-05 05:14:13 +00:00
"""
2016-08-11 12:44:46 +00:00
>>> decryptMessage('HDarji', 'Akij ra Odrjqqs Gaisq muod Mphumrs.')
'This is Harshil Darji from Dharmaj.'
2019-10-05 05:14:13 +00:00
"""
return translateMessage(key, message, "decrypt")
2016-08-11 12:44:46 +00:00
def translateMessage(key: str, message: str, mode: str) -> str:
2016-08-11 12:44:46 +00:00
translated = []
keyIndex = 0
key = key.upper()
for symbol in message:
num = LETTERS.find(symbol.upper())
if num != -1:
2019-10-05 05:14:13 +00:00
if mode == "encrypt":
2016-08-11 12:44:46 +00:00
num += LETTERS.find(key[keyIndex])
2019-10-05 05:14:13 +00:00
elif mode == "decrypt":
2016-08-11 12:44:46 +00:00
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)
2019-10-05 05:14:13 +00:00
return "".join(translated)
2016-08-11 12:44:46 +00:00
2019-10-05 05:14:13 +00:00
if __name__ == "__main__":
2016-08-11 12:44:46 +00:00
main()