-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathcolumnar_transposition_encryption.py
72 lines (63 loc) · 2.06 KB
/
columnar_transposition_encryption.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
import math
def row(s,key):
# to remove repeated alphabets in key
temp=[]
for i in key:
if i not in temp:
temp.append(i)
k=""
for i in temp:
k+=i
print("The key used for encryption is: ",k)
# ceil is used to adjust the count of
# rows according to length of message
b=math.ceil(len(s)/len(k))
# if b is less than length of key, then it will not form square matrix when
# length of meessage not equal to rowsize*columnsize of square matrix
if(b<len(k)):
b=b+(len(k)-b)
# if b is greater than length of key, then it will not from a
# square matrix, but if less then length of key, we have to add padding
arr=[['_' for i in range(len(k))]
for j in range(b)]
i=0
j=0
# arranging the message into matrix
for h in range(len(s)):
arr[i][j]=s[h]
j+=1
if(j>len(k)-1):
j=0
i+=1
print("The message matrix is: ")
for i in arr:
print(i)
cipher_text=""
# To get indices as the key numbers instead of alphabets in the key, according
# to algorithm, for appending the elementsof matrix formed earlier, column wise.
kk=sorted(k)
for i in kk:
# gives the column index
h=k.index(i)
for j in range(len(arr)):
cipher_text+=arr[j][h]
print("The cipher text is: ",cipher_text)
msg=input("Enter the message: ")
key=input("Enter the key in alphabets: ")
row(msg,key)
'''
----------OUTPUT----------
Enter the message: My computer is owned by me
Enter the key in alphabets: expensive
The key used for encryption is: expnsiv
The message matrix is:
['M', 'y', ' ', 'c', 'o', 'm', 'p']
['u', 't', 'e', 'r', ' ', 'i', 's']
[' ', 'o', 'w', 'n', 'e', 'd', ' ']
['b', 'y', ' ', 'm', 'e', '_', '_']
['_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_']
['_', '_', '_', '_', '_', '_', '_']
The cipher text is: Mu b___mid____crnm___ ew ___o ee___ps ____ytoy___
>>>
'''