-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
70 lines (49 loc) · 1.57 KB
/
Copy pathapp.py
File metadata and controls
70 lines (49 loc) · 1.57 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
import math
def get_column_order(key):
sorted_key = sorted(list(key))
order = []
for char in key:
order.append(sorted_key.index(char))
sorted_key[sorted_key.index(char)] = None
return order
def row_column_encrypt(text, key):
text = text.replace(" ", "")
cols = len(key)
rows = math.ceil(len(text) / cols)
# Padding text
text += "X" * (rows * cols - len(text))
matrix = []
index = 0
for r in range(rows):
row = []
for c in range(cols):
row.append(text[index])
index += 1
matrix.append(row)
order = get_column_order(key)
cipher = ""
for num in sorted(range(cols), key=lambda x: order[x]):
for r in range(rows):
cipher += matrix[r][num]
return cipher
def row_column_decrypt(cipher, key):
cols = len(key)
rows = math.ceil(len(cipher) / cols)
order = get_column_order(key)
matrix = [["" for _ in range(cols)] for _ in range(rows)]
index = 0
for num in sorted(range(cols), key=lambda x: order[x]):
for r in range(rows):
matrix[r][num] = cipher[index]
index += 1
return "".join("".join(row) for row in matrix)
print("\n--- Row-Column Transposition Cipher ---\n")
choice = input("Encrypt or Decrypt (E/D): ").upper()
message = input("Enter message: ")
key = input("Enter keyword: ")
if choice == "E":
print("Encrypted message:", row_column_encrypt(message, key))
elif choice == "D":
print("Decrypted message:", row_column_decrypt(message, key))
else:
print("Invalid choice!")