-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathCaesar_cipher.py
More file actions
67 lines (58 loc) · 2.28 KB
/
Copy pathCaesar_cipher.py
File metadata and controls
67 lines (58 loc) · 2.28 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
class CaesarCipher:
"""
A class used to encrypt and decrypt strings using a substitution cipher key dictionary.
"""
def __init__(self, key: dict) -> None:
"""
Initializes the cipher with a key mapping dictionary.
:param key: dict mapping input characters to their encrypted output characters.
"""
self.key = key
def get_input(self) -> None:
"""
Prompts the user for alphabetic text input and converts it to lowercase.
"""
while True:
blank_string = str(input("Enter string to encrypt/decrypt: "))
if blank_string.isalpha():
self.blank_string = blank_string.lower()
break
else:
print("Input is not valid. Please enter alphabetic characters only.")
continue
def encrypt_string(self) -> str:
"""
Encrypts self.blank_string using the instance key dictionary.
:return: Encrypted string
"""
output = ""
for c in self.blank_string:
if c in self.key:
output += self.key[c]
self.encrypted_string = output
return output
def decrypt_string(self, string: str = "") -> str:
"""
Decrypts a given string (or self.blank_string) using the inverse key dictionary.
:param string: Encrypted input string to decode.
:return: Decrypted original string
"""
output = ""
target_string = string.lower().strip() if string else self.blank_string
# Create inverse lookup map (v -> k)
inverse_key = {v: k for k, v in self.key.items()}
for c in target_string:
if c in inverse_key:
output += inverse_key[c]
return output
if __name__ == "__main__":
key = {
"a": "d", "b": "e", "c": "f", "d": "g", "e": "h", "f": "i", "g": "j",
"h": "k", "i": "l", "j": "m", "k": "n", "l": "o", "m": "p", "n": "q",
"o": "r", "p": "s", "q": "t", "r": "u", "s": "v", "t": "w", "u": "x",
"v": "y", "w": "z", "x": "a", "y": "b", "z": "c"
}
cipher = CaesarCipher(key=key)
cipher.get_input()
encrypted = cipher.encrypt_string()
print(f"Encrypted Output: {encrypted}")