forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplayfair_cipher.py
More file actions
Latest commit
159 lines (119 loc) · 4.41 KB
/
Copy pathplayfair_cipher.py
File metadata and controls
159 lines (119 loc) · 4.41 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
"""
https://en.wikipedia.org/wiki/Playfair_cipher#Description
The Playfair cipher was developed by Charles Wheatstone in 1854
It's use was heavily promotedby Lord Playfair, hence its name
Some features of the Playfair cipher are:
1) It was the first literal diagram substitution cipher
2) It is a manual symmetric encryption technique
3) It is a multiple letter encryption cipher
The implementation in the code below encodes alphabets only.
It removes spaces, special characters and numbers from the
code.
Playfair is no longer used by military forces because of known
insecurities and of the advent of automated encryption devices.
This cipher is regarded as insecure since before World War I.
"""
importitertools
importstring
fromcollections.abcimportGenerator, Iterable
defchunker(seq: Iterable[str], size: int) ->Generator[tuple[str, ...], None, None]:
it=iter(seq)
whileTrue:
chunk=tuple(itertools.islice(it, size))
ifnotchunk:
return
yieldchunk
defprepare_input(dirty: str) ->str:
"""
Prepare the plaintext by up-casing it
and separating repeated letters with X's
"""
dirty="".join([c.upper() forcindirtyifcinstring.ascii_letters])
clean=""
iflen(dirty) <2:
returndirty
foriinrange(len(dirty) -1):
clean+=dirty[i]
ifdirty[i] ==dirty[i+1]:
clean+="X"
clean+=dirty[-1]
iflen(clean) &1:
clean+="X"
returnclean
defgenerate_table(key: str) ->list[str]:
# I and J are used interchangeably to allow
# us to use a 5x5 table (25 letters)
alphabet="ABCDEFGHIKLMNOPQRSTUVWXYZ"
# we're using a list instead of a '2d' array because it makes the math
# for setting up the table and doing the actual encoding/decoding simpler
table= []
# copy key chars into the table if they are in `alphabet` ignoring duplicates
forcharinkey.upper():
ifcharnotintableandcharinalphabet:
table.append(char)
# fill the rest of the table in with the remaining alphabet chars
forcharinalphabet:
ifcharnotintable:
table.append(char)
returntable
defencode(plaintext: str, key: str) ->str:
"""
Encode the given plaintext using the Playfair cipher.
Takes the plaintext and the key as input and returns the encoded string.
>>> encode("Hello", "MONARCHY")
'CFSUPM'
>>> encode("attack on the left flank", "EMERGENCY")
'DQZSBYFSDZFMFNLOHFDRSG'
>>> encode("Sorry!", "SPECIAL")
'AVXETX'
>>> encode("Number 1", "NUMBER")
'UMBENF'
>>> encode("Photosynthesis!", "THE SUN")
'OEMHQHVCHESUKE'
"""
table=generate_table(key)
plaintext=prepare_input(plaintext)
ciphertext=""
forchar1, char2inchunker(plaintext, 2):
row1, col1=divmod(table.index(char1), 5)
row2, col2=divmod(table.index(char2), 5)
ifrow1==row2:
ciphertext+=table[row1*5+ (col1+1) %5]
ciphertext+=table[row2*5+ (col2+1) %5]
elifcol1==col2:
ciphertext+=table[((row1+1) %5) *5+col1]
ciphertext+=table[((row2+1) %5) *5+col2]
else: # rectangle
ciphertext+=table[row1*5+col2]
ciphertext+=table[row2*5+col1]
returnciphertext
defdecode(ciphertext: str, key: str) ->str:
"""
Decode the input string using the provided key.
>>> decode("BMZFAZRZDH", "HAZARD")
'FIREHAZARD'
>>> decode("HNBWBPQT", "AUTOMOBILE")
'DRIVINGX'
>>> decode("SLYSSAQS", "CASTLE")
'ATXTACKX'
"""
table=generate_table(key)
plaintext=""
forchar1, char2inchunker(ciphertext, 2):
row1, col1=divmod(table.index(char1), 5)
row2, col2=divmod(table.index(char2), 5)
ifrow1==row2:
plaintext+=table[row1*5+ (col1-1) %5]
plaintext+=table[row2*5+ (col2-1) %5]
elifcol1==col2:
plaintext+=table[((row1-1) %5) *5+col1]
plaintext+=table[((row2-1) %5) *5+col2]
else: # rectangle
plaintext+=table[row1*5+col2]
plaintext+=table[row2*5+col1]
returnplaintext
if__name__=="__main__":
importdoctest
doctest.testmod()
print("Encoded:", encode("BYE AND THANKS", "GREETING"))
print("Decoded:", decode("CXRBANRLBALQ", "GREETING"))