-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcaesar_cipher.py
More file actions
85 lines (64 loc) · 2.57 KB
/
Copy pathcaesar_cipher.py
File metadata and controls
85 lines (64 loc) · 2.57 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
"""
Caesar Cipher — Basic Encryption & Decryption
-----------------------------------------------
Project 2 | Cyber Security Track | DecodeLabs Industrial Training Kit
Implements the classic Caesar (shift) cipher using the IPO model:
INPUT -> Plaintext
PROCESS -> Algorithm (shift) + Key (n)
OUTPUT -> Ciphertext
Formulas:
Encryption: E(x) = (x + n) % 26
Decryption: D(x) = (x - n) % 26
Handles:
- Uppercase and lowercase letters independently
- Spaces, punctuation, and digits (left unchanged)
- Negative / large shift keys via modulo wraparound
"""
def encrypt(text: str, shift: int) -> str:
"""Encrypt plaintext using a Caesar cipher with the given shift key."""
result = []
shift = shift % 26 # normalize shift so it always falls in [0, 25]
for char in text:
if char.isupper():
result.append(chr((ord(char) - 65 + shift) % 26 + 65))
elif char.islower():
result.append(chr((ord(char) - 97 + shift) % 26 + 97))
else:
# Non-alphabetic characters (spaces, punctuation, digits) stay as-is
result.append(char)
return "".join(result)
def decrypt(text: str, shift: int) -> str:
"""Decrypt ciphertext using a Caesar cipher with the given shift key."""
# Decryption is just encryption with the inverse shift
return encrypt(text, -shift)
def brute_force(text: str) -> None:
"""Bonus: demonstrate why Caesar cipher is a lockbox, not a vault.
Tries all 25 possible shifts (frequency-analysis style attack)."""
print("\n--- Brute Force: All Possible Shifts ---")
for key in range(1, 26):
print(f"Shift {key:2d}: {decrypt(text, key)}")
def main():
print("=" * 50)
print(" CAESAR CIPHER — ENCRYPTION & DECRYPTION")
print("=" * 50)
message = input("\nEnter the text to encrypt: ")
while True:
try:
shift_key = int(input("Enter the shift key (e.g. 3): "))
break
except ValueError:
print("Please enter a valid integer for the shift key.")
encrypted = encrypt(message, shift_key)
decrypted = decrypt(encrypted, shift_key)
print("\n--- Results ---")
print(f"Plaintext : {message}")
print(f"Shift Key : {shift_key}")
print(f"Encrypted : {encrypted}")
print(f"Decrypted : {decrypted}")
verify = "PASSED ✅" if decrypted == message else "FAILED ❌"
print(f"Round-trip Check: {verify}")
show_bf = input("\nRun brute-force demo on the ciphertext? (y/n): ").strip().lower()
if show_bf == "y":
brute_force(encrypted)
if __name__ == "__main__":
main()