-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCode.py
More file actions
58 lines (45 loc) · 1.63 KB
/
Code.py
File metadata and controls
58 lines (45 loc) · 1.63 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
def caeser_cipher(text, shift, encrypt):
result = ""
max_shift = 26 # As English letters are only 26
shift %= max_shift # Normalize the shift key value (0 - 25)
if shift == 0:
shift = max_shift
if not encrypt:
shift = -shift
for ch in text:
if ch.isalpha():
start = ord('A') if ch.isupper() else ord('a') # To determine ASCII value
ch_ASCII = ord(ch) - start
# Apply the Caesar Cipher formula: C = (P + K) mod 26
result += chr((ch_ASCII + shift) % 26 + start)
else:
result += ch
return result
def get_valid_shift():
while True:
try:
shift = int(input("Enter the shift key (From 1 to 26): "))
if 1 <= shift <= 26:
return shift
else:
raise ValueError("Shift must be between 1 and 26.")
except ValueError as e:
print(f"Invalid input! {e}")
def get_operation():
while True:
print("Do you want to encrypt a plaintext or decrypt a ciphertext?")
operation = input("1: Encrypt\n2: Decrypt\nChoice: ").strip()
if operation == "1":
return True
elif operation == "2":
return False
else:
print("Invalid choice. Please choose 1 for Encrypt or 2 for Decrypt!")
def main():
print("------ Welcome to Caesar Cipher Program! ------\n")
text = input("Enter the text you want to encrypt or decrypt: ")
shift = get_valid_shift()
encrypt = get_operation()
print("\nResult:", caeser_cipher(text, shift, encrypt))
if __name__ == "__main__":
main()