-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecryptTranspositionCipher.py
More file actions
63 lines (50 loc) · 1.72 KB
/
decryptTranspositionCipher.py
File metadata and controls
63 lines (50 loc) · 1.72 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
# =================================
# Columnar Transposition Decryption
# =================================
# Assumption: Encryption key known
# ^^^^^^^^^^ -> Won't work without assumption
# PT: Plaintext, CT: Ciphertext
# ^^ ^^
# Decryption Process
# ^^^^^^^^^^^^^^^^^^
# Calculate grid:
# No. of rows = key
# No. of columns = Ceil(CT Length / Key)
# No. of boxes to shade in = grid size - CT length
# => Do this in the bottom of rightmost column
# Fill rows from left to right with CT
# Read the columns from left to right for PT
import math
def main():
ciphertext = 'Atniy, hsso doh unauil iytnikg eknhws,eotiu w.'
key = 8 # see assumption above
plaintext = decryptMessage(key, ciphertext)
print(plaintext)
# decrypt a given columnar transpositional CT
def decryptMessage(key, ciphertext):
ciphertextLen = len(ciphertext)
# calculate no. of columns in grid
numCols = int(math.ceil(ciphertextLen / float(key)))
# calculate no. of rows
numRows = key
# calculate no. of shaded boxes
numShaded = (numCols * numRows) - ciphertextLen
# each string in plaintext represents a column in the grid
plaintext = [''] * numCols
# initialization
col = 0
row = 0
# main logic for decryption
for symbol in ciphertext:
plaintext[col] += symbol # add next plaintext symbol
col +=1 # iterate to next column
# if there are no more columns or we are at a shaded box
# start again from column 0 and next row
if (col == numCols) or (col == numCols - 1 and row >= numRows - numShaded):
col = 0
row += 1
# join plaintext
return ''.join(plaintext)
# if run directly
if __name__ == '__main__':
main()