forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_substitution_cipher.py
More file actions
Latest commit
78 lines (56 loc) · 1.83 KB
/
Copy pathsimple_substitution_cipher.py
File metadata and controls
78 lines (56 loc) · 1.83 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
importrandom
importsys
LETTERS="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
defmain() ->None:
message=input("Enter message: ")
key="LFWOAYUISVKMNXPBDCRJTQEGHZ"
resp=input("Encrypt/Decrypt [e/d]: ")
check_valid_key(key)
ifresp.lower().startswith("e"):
mode="encrypt"
translated=encrypt_message(key, message)
elifresp.lower().startswith("d"):
mode="decrypt"
translated=decrypt_message(key, message)
print(f"\n{mode.title()}ion: \n{translated}")
defcheck_valid_key(key: str) ->None:
key_list=list(key)
letters_list=list(LETTERS)
key_list.sort()
letters_list.sort()
ifkey_list!=letters_list:
sys.exit("Error in the key or symbol set.")
defencrypt_message(key: str, message: str) ->str:
"""
>>> encrypt_message('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Harshil Darji')
'Ilcrism Olcvs'
"""
returntranslate_message(key, message, "encrypt")
defdecrypt_message(key: str, message: str) ->str:
"""
>>> decrypt_message('LFWOAYUISVKMNXPBDCRJTQEGHZ', 'Ilcrism Olcvs')
'Harshil Darji'
"""
returntranslate_message(key, message, "decrypt")
deftranslate_message(key: str, message: str, mode: str) ->str:
translated=""
chars_a=LETTERS
chars_b=key
ifmode=="decrypt":
chars_a, chars_b=chars_b, chars_a
forsymbolinmessage:
ifsymbol.upper() inchars_a:
sym_index=chars_a.find(symbol.upper())
ifsymbol.isupper():
translated+=chars_b[sym_index].upper()
else:
translated+=chars_b[sym_index].lower()
else:
translated+=symbol
returntranslated
defget_random_key() ->str:
key=list(LETTERS)
random.shuffle(key)
return"".join(key)
if__name__=="__main__":
main()