This repository was archived by the owner on Dec 17, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcaesar_cipher.py
More file actions
89 lines (70 loc) · 2.82 KB
/
Copy pathcaesar_cipher.py
File metadata and controls
89 lines (70 loc) · 2.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
"""Caesar Cipher
The Caesar cipher is a shift cipher that uses addition and subtraction
to encrypt and decrypt letters.
More info at: https://en.wikipedia.org/wiki/Caesar_cipher
View this code at https://nostarch.com/big-book-small-python-projects
Tags: short, beginner, cryptography, math
"""
from typing import Literal
def main():
print("Caesar Cipher")
print("The Caesar cipher encrypts letters by shifting them over by a")
print("key number. For example, a key of 2 means the letter A is")
print("encrypted into C, the letter B encrypted into D, and so on.")
print()
# Let the user enter if they are encrypting or decrypting:
while True: # Keep asking until the user enters e or d.
print("Do you want to (e)ncrypt or (d)ecrypt?")
response = input("> ").lower()
if response.startswith("e"):
mode = "encrypt"
break
elif response.startswith("d"):
mode = "decrypt"
break
print("Please enter the letter e or d.")
# Let the user enter the key to use:
while True: # Keep asking until the user enters a valid key.
maxKey = len(SYMBOLS) - 1
print("Please enter the key (0 to {}) to use.".format(maxKey))
response = input("> ").upper()
if not response.isdecimal():
continue
if 0 <= int(response) < len(SYMBOLS):
key = int(response)
break
# Let the user enter the message to encrypt/decrypt:
print("Enter the message to {}.".format(mode))
message = input("> ")
print(get_translated_message(message, key, mode))
SYMBOLS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def get_translated_message(
message: str, key: int, mode: Literal["encrypt"] | Literal["decrypt"]
):
# Caesar cipher only works on uppercase letters:
message = message.upper()
# Stores the encrypted/decrypted form of the message:
translated = ""
# Encrypt/decrypt each symbol in the message:
for symbol in message:
if symbol in SYMBOLS:
# Get the encrypted (or decrypted) number for this symbol.
num = SYMBOLS.find(symbol) # Get the number of the symbol.
if mode == "encrypt":
num = num + key
elif mode == "decrypt":
num = num - key
# Handle the wrap-around if num is larger than the length of
# SYMBOLS or less than 0:
if num >= len(SYMBOLS):
num = num - len(SYMBOLS)
elif num < 0:
num = num + len(SYMBOLS)
# Add encrypted/decrypted number's symbol to translated:
translated = translated + SYMBOLS[num]
else:
# Just add the symbol without encrypting/decrypting:
translated = translated + symbol
return translated
if __name__ == "__main__":
main()