1
1
import math
2
2
3
+
3
4
def encrypt_columnar_cipher (message : str , key : str ) -> str :
4
5
"""
5
6
Encrypts a message using the Columnar Transposition Cipher.
6
-
7
+
7
8
:param message: Text to encrypt.
8
9
:param key: String key used to define column order.
9
10
:return: Encrypted message.
@@ -12,23 +13,23 @@ def encrypt_columnar_cipher(message: str, key: str) -> str:
12
13
message = message .replace (" " , "" )
13
14
num_cols = len (key )
14
15
num_rows = math .ceil (len (message ) / num_cols )
15
-
16
+
16
17
# Fill the grid with characters
17
- grid = ['' ] * num_cols
18
+ grid = ["" ] * num_cols
18
19
for i , char in enumerate (message ):
19
20
grid [i % num_cols ] += char
20
21
21
22
# Sort columns based on the key order
22
23
sorted_key_indices = sorted (range (len (key )), key = lambda k : key [k ])
23
- ciphertext = '' .join ([grid [i ] for i in sorted_key_indices ])
24
+ ciphertext = "" .join ([grid [i ] for i in sorted_key_indices ])
24
25
25
26
return ciphertext
26
27
27
28
28
29
def decrypt_columnar_cipher (ciphertext : str , key : str ) -> str :
29
30
"""
30
31
Decrypts a message encrypted with the Columnar Transposition Cipher.
31
-
32
+
32
33
:param ciphertext: Encrypted text.
33
34
:param key: String key used to define column order.
34
35
:return: Decrypted message.
@@ -41,17 +42,17 @@ def decrypt_columnar_cipher(ciphertext: str, key: str) -> str:
41
42
sorted_key_indices = sorted (range (len (key )), key = lambda k : key [k ])
42
43
col_lengths = [num_rows ] * num_cols
43
44
for i in range (num_shaded_boxes ):
44
- col_lengths [sorted_key_indices [- (i + 1 )]] -= 1
45
+ col_lengths [sorted_key_indices [- (i + 1 )]] -= 1
45
46
46
47
# Distribute ciphertext into columns based on the sorted key
47
48
grid = []
48
49
start = 0
49
50
for col_length in col_lengths :
50
- grid .append (ciphertext [start : start + col_length ])
51
+ grid .append (ciphertext [start : start + col_length ])
51
52
start += col_length
52
53
53
54
# Rebuild plaintext row by row
54
- plaintext = ''
55
+ plaintext = ""
55
56
for i in range (num_rows ):
56
57
for j in range (num_cols ):
57
58
if i < len (grid [sorted_key_indices [j ]]):
0 commit comments