-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcaesar_cipher.py
More file actions
79 lines (64 loc) · 2.35 KB
/
caesar_cipher.py
File metadata and controls
79 lines (64 loc) · 2.35 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
'''
The Caesar cipher is an ancient encryption algorithm used by Julius Caesar. It
encrypts letters by shifting them over by a
certain number of places in the alphabet. We
call the length of shift the key. For example, if the
key is 3, then A becomes D, B becomes E, C becomes
F, and so on. To decrypt the message, you must shift
the encrypted letters in the opposite direction. This
program lets the user encrypt and decrypt messages
according to this algorithm.
When you run the code, the output will look like this:
Do you want to (e)ncrypt or (d)ecrypt?
> e
Please enter the key (0 to 25) to use.
> 4
Enter the message to encrypt.
> Meet me by the rose bushes tonight.
QIIX QI FC XLI VSWI FYWLIW XSRMKLX.
Do you want to (e)ncrypt or (d)ecrypt?
> d
Please enter the key (0 to 26) to use.
> 4
Enter the message to decrypt.
> QIIX QI FC XLI VSWI FYWLIW XSRMKLX.
MEET ME BY THE ROSE BUSHES TONIGHT.
'''
# Import the string module.
import string
choice=input("Do you want to (e)ncrypt or (d)ecrypt?\n> ")
choice=choice.lower()
def encode(message, key):
'''
This function takes a message and a key and returns the encrypted message.
'''
for i in message:
if i in string.ascii_letters:
if i.isupper():
print(chr((ord(i)+key-65)%26+65),end="")
else:
print(chr((ord(i)+key-97)%26+97),end="")
else:
print(i,end="")
def decode(message, key):
'''
This function takes a message and a key and returns the decrypted message.
'''
for i in message:
if i in string.ascii_letters:
if i.isupper():
print(chr((ord(i)-key-65)%26+65),end="")
else:
print(chr((ord(i)-key-97)%26+97),end="")
else:
print(i,end="")
if choice=="e":
input_key=int(input("Please enter the key (0 to 25) to use.\n> "))
input_message=input("Enter the message to encrypt.\n> ")
input_message=input_message.upper()
encode(input_message, input_key)
elif choice=="d":
input_key=int(input("Please enter the key (0 to 26) to use.\n> "))
input_message=input("Enter the input_message to decrypt.\n> ")
input_message=input_message.upper()
decode(input_message, input_key)