- Notifications
You must be signed in to change notification settings - Fork 46.7k
/
Copy pathbeaufort_cipher.py
82 lines (69 loc) · 1.89 KB
/
beaufort_cipher.py
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
"""
Author: Mohit Radadiya
"""
fromstringimportascii_uppercase
dict1= {char: ifori, charinenumerate(ascii_uppercase)}
dict2=dict(enumerate(ascii_uppercase))
# This function generates the key in
# a cyclic manner until it's length isn't
# equal to the length of original text
defgenerate_key(message: str, key: str) ->str:
"""
>>> generate_key("THE GERMAN ATTACK","SECRET")
'SECRETSECRETSECRE'
"""
x=len(message)
i=0
whileTrue:
ifx==i:
i=0
iflen(key) ==len(message):
break
key+=key[i]
i+=1
returnkey
# This function returns the encrypted text
# generated with the help of the key
defcipher_text(message: str, key_new: str) ->str:
"""
>>> cipher_text("THE GERMAN ATTACK","SECRETSECRETSECRE")
'BDC PAYUWL JPAIYI'
"""
cipher_text=""
i=0
forletterinmessage:
ifletter==" ":
cipher_text+=" "
else:
x= (dict1[letter] -dict1[key_new[i]]) %26
i+=1
cipher_text+=dict2[x]
returncipher_text
# This function decrypts the encrypted text
# and returns the original text
deforiginal_text(cipher_text: str, key_new: str) ->str:
"""
>>> original_text("BDC PAYUWL JPAIYI","SECRETSECRETSECRE")
'THE GERMAN ATTACK'
"""
or_txt=""
i=0
forletterincipher_text:
ifletter==" ":
or_txt+=" "
else:
x= (dict1[letter] +dict1[key_new[i]] +26) %26
i+=1
or_txt+=dict2[x]
returnor_txt
defmain() ->None:
message="THE GERMAN ATTACK"
key="SECRET"
key_new=generate_key(message, key)
s=cipher_text(message, key_new)
print(f"Encrypted Text = {s}")
print(f"Original Text = {original_text(s, key_new)}")
if__name__=="__main__":
importdoctest
doctest.testmod()
main()