Python/ciphers/vigenere_cipher.py

66 lines
1.7 KiB
Python
Raw Permalink Normal View History

2019-10-05 05:14:13 +00:00
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2016-08-11 12:44:46 +00:00
def main() -> None:
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"
translated = encrypt_message(key, message)
2019-10-05 05:14:13 +00:00
elif mode.lower().startswith("d"):
mode = "decrypt"
translated = decrypt_message(key, message)
2016-08-11 12:44:46 +00:00
print(f"\n{mode.title()}ed message:")
2016-08-11 12:44:46 +00:00
print(translated)
2019-10-05 05:14:13 +00:00
def encrypt_message(key: str, message: str) -> str:
2019-10-05 05:14:13 +00:00
"""
>>> encrypt_message('HDarji', 'This is Harshil Darji from Dharmaj.')
2016-08-11 12:44:46 +00:00
'Akij ra Odrjqqs Gaisq muod Mphumrs.'
2019-10-05 05:14:13 +00:00
"""
return translate_message(key, message, "encrypt")
2019-10-05 05:14:13 +00:00
2016-08-11 12:44:46 +00:00
def decrypt_message(key: str, message: str) -> str:
2019-10-05 05:14:13 +00:00
"""
>>> decrypt_message('HDarji', 'Akij ra Odrjqqs Gaisq muod Mphumrs.')
2016-08-11 12:44:46 +00:00
'This is Harshil Darji from Dharmaj.'
2019-10-05 05:14:13 +00:00
"""
return translate_message(key, message, "decrypt")
2019-10-05 05:14:13 +00:00
2016-08-11 12:44:46 +00:00
def translate_message(key: str, message: str, mode: str) -> str:
2016-08-11 12:44:46 +00:00
translated = []
key_index = 0
2016-08-11 12:44:46 +00:00
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":
num += LETTERS.find(key[key_index])
2019-10-05 05:14:13 +00:00
elif mode == "decrypt":
num -= LETTERS.find(key[key_index])
2016-08-11 12:44:46 +00:00
num %= len(LETTERS)
if symbol.isupper():
translated.append(LETTERS[num])
elif symbol.islower():
translated.append(LETTERS[num].lower())
key_index += 1
if key_index == len(key):
key_index = 0
2016-08-11 12:44:46 +00:00
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()