forked from HarshCasper/Rotten-Scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubstitution_cypher.py
More file actions
92 lines (79 loc) · 2.85 KB
/
substitution_cypher.py
File metadata and controls
92 lines (79 loc) · 2.85 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
90
91
92
import string
import sys
all_letters = string.ascii_letters
i_a = {}
for i in range(0, len(all_letters)):
i_a[i] = all_letters[i]
a_i = {}
for i in range(0, len(all_letters)):
a_i[all_letters[i]] = i
def encrypt(text, key):
enc_string = ""
for i in range(0, len(text)):
if text[i] == " ":
enc_string = enc_string + " "
elif text[i].isupper():
enc_string = enc_string + i_a[(a_i[text[i].upper()] + key) % 26].upper()
else:
enc_string = enc_string + i_a[(a_i[text[i].upper()] + key) % 26].lower()
return enc_string
def decrypt(enc_text, key):
dec_string = ""
for i in range(0, len(enc_text)):
if enc_text[i] == " ":
dec_string = dec_string + " "
elif enc_text[i].isupper():
dec_string = (
dec_string + i_a[abs((a_i[enc_text[i].upper()] - key)) % 26].upper()
)
else:
dec_string = (
dec_string + i_a[abs((a_i[enc_text[i].upper()] - key)) % 26].lower()
)
return dec_string
def hasNumbers(inputString):
return any(char.isdigit() for char in inputString)
def try_again():
retry = input("Do you want to try again. Enter 1 for yes and anything for no")
if retry != "1":
sys.exit()
if __name__ == "__main__":
while True:
while True:
choice = input(
"Do you want to encrypt or decrypt a text. press 0 for encrypt and 1 for decrypt\n"
)
if choice in ["0", "1"]:
break
else:
print("Please enter only 0 or 1\n")
try_again()
if choice == "0":
while True:
text = input("Please enter a text you want to encrypt\n")
if hasNumbers(text):
print("Only alphabets from A-Z or a-z are allowed")
try_again()
else:
key = int(input("Please enter the key"))
if isinstance(key, int) is False:
print("Only integers are allowed for key")
try_again()
else:
print(encrypt(text, key))
break
if choice == "1":
while True:
text = input("Please enter a text you want to decrypt\n")
if hasNumbers(text):
print("Only alphabets from A-Z or a-z are allowed")
try_again()
else:
key = int(input("Please enter the key"))
if isinstance(key, int) is False:
print("Only integers are allowed for key")
try_again()
else:
print(decrypt(text, key))
break
try_again()