Untitled
unknown
python
10 months ago
2.6 kB
11
Indexable
class EncryptTran:
def __init__(self, plaintext, keyword):
# self.plaintext = plaintext.replace(" ", "#")
self.plaintext = plaintext
self.keyword = keyword
self.columns = len(keyword)
def _get_column_order(self):
""" Returns the order in which to read columns based on sorted keyword positions. """
return sorted(range(len(self.keyword)), key=lambda k: self.keyword[k])
def encrypt(self):
""" Encrypts the plaintext using columnar transposition. """
# We create the grid
# for using the
# transposition method
grid = [self.plaintext[i : i + self.columns] for i in range(0, len(self.plaintext), self.columns)]
last_row_length = len(grid[-1])
# We add placeholder cipher
# if last row isn't completed
if last_row_length < self.columns:
grid[-1] += "_" * (self.columns - last_row_length)
# Get the column order based
# on the keyword
col_order = self._get_column_order()
# Then we construct the ciphertext
# by reading the columns in the specific
# order.
ciphertext = "".join("".join(row[i] for row in grid) for i in col_order)
self.plaintext = ciphertext
def decrypt(self):
""" Decrypts the message using columnar transposition. """
# Calc number of rows.
num_rows = -(-len(self.plaintext) // self.columns)
# Calc number of whole rows.
num_full_cols = len(self.plaintext) % self.columns
# Construct an empty grid for the decryption
grid = [list("_" * self.columns) for _ in range(num_rows)]
# Again we fetch the column order
col_order = self._get_column_order()
index = 0
# Then we insert all the
# elements based on the
# columnar order
for i in col_order:
for row in range(num_rows):
# We need to manually construct the last row
if row == num_rows - 1 and i >= num_full_cols and num_full_cols != 0:
continue
grid[row][i] = self.plaintext[index]
index += 1
# We join the newly plaintext, replace the padding.
# Then set self.plaintext
self.plaintext = "".join("".join(row) for row in grid).rstrip("_")
def show_message(self):
# Simply return plaintext for writing to file
# and read file method in app.run()
return self.plaintext
Editor is loading...
Leave a Comment