mirror of
https://hub.njuu.cf/TheAlgorithms/Python.git
synced 2023-10-11 13:06:12 +08:00
2d5dd6f132
* MAINT: Used f-string method Updated the code with f-string methods wherever required for a better and cleaner understanding of the code. * Updated files with f-string method * Update rsa_key_generator.py * Update rsa_key_generator.py * Update elgamal_key_generator.py * Update lru_cache.py I don't think this change is efficient but it might tackle the error as the error was due to using long character lines. * Update lru_cache.py * Update lru_cache.py Co-authored-by: cyai <seriesscar@gmail.com> Co-authored-by: Christian Clauss <cclauss@me.com>
66 lines
1.7 KiB
Python
66 lines
1.7 KiB
Python
LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
|
|
|
|
def main() -> None:
|
|
message = input("Enter message: ")
|
|
key = input("Enter key [alphanumeric]: ")
|
|
mode = input("Encrypt/Decrypt [e/d]: ")
|
|
|
|
if mode.lower().startswith("e"):
|
|
mode = "encrypt"
|
|
translated = encryptMessage(key, message)
|
|
elif mode.lower().startswith("d"):
|
|
mode = "decrypt"
|
|
translated = decryptMessage(key, message)
|
|
|
|
print(f"\n{mode.title()}ed message:")
|
|
print(translated)
|
|
|
|
|
|
def encryptMessage(key: str, message: str) -> str:
|
|
"""
|
|
>>> encryptMessage('HDarji', 'This is Harshil Darji from Dharmaj.')
|
|
'Akij ra Odrjqqs Gaisq muod Mphumrs.'
|
|
"""
|
|
return translateMessage(key, message, "encrypt")
|
|
|
|
|
|
def decryptMessage(key: str, message: str) -> str:
|
|
"""
|
|
>>> decryptMessage('HDarji', 'Akij ra Odrjqqs Gaisq muod Mphumrs.')
|
|
'This is Harshil Darji from Dharmaj.'
|
|
"""
|
|
return translateMessage(key, message, "decrypt")
|
|
|
|
|
|
def translateMessage(key: str, message: str, mode: str) -> str:
|
|
translated = []
|
|
keyIndex = 0
|
|
key = key.upper()
|
|
|
|
for symbol in message:
|
|
num = LETTERS.find(symbol.upper())
|
|
if num != -1:
|
|
if mode == "encrypt":
|
|
num += LETTERS.find(key[keyIndex])
|
|
elif mode == "decrypt":
|
|
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)
|
|
return "".join(translated)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|