Python/ciphers/transposition_cipher.py

71 lines
1.8 KiB
Python
Raw Normal View History

2016-07-30 14:10:22 +00:00
import math
"""
2020-02-03 09:00:58 +00:00
In cryptography, the TRANSPOSITION cipher is a method of encryption where the
positions of plaintext are shifted a certain number(determined by the key) that
follows a regular system that results in the permuted text, known as the encrypted
text. The type of transposition cipher demonstrated under is the ROUTE cipher.
"""
def main() -> None:
2019-10-05 05:14:13 +00:00
message = input("Enter message: ")
key = int(input(f"Enter key [2-{len(message) - 1}]: "))
2019-10-05 05:14:13 +00:00
mode = input("Encryption/Decryption [e/d]: ")
2016-07-30 14:10:22 +00:00
2019-10-05 05:14:13 +00:00
if mode.lower().startswith("e"):
text = encrypt_message(key, message)
2019-10-05 05:14:13 +00:00
elif mode.lower().startswith("d"):
text = decrypt_message(key, message)
2016-07-30 14:10:22 +00:00
# Append pipe symbol (vertical bar) to identify spaces at the end.
print(f"Output:\n{text + '|'}")
2019-10-05 05:14:13 +00:00
2016-07-30 14:10:22 +00:00
def encrypt_message(key: int, message: str) -> str:
2016-08-02 17:46:55 +00:00
"""
>>> encrypt_message(6, 'Harshil Darji')
2016-08-02 17:46:55 +00:00
'Hlia rDsahrij'
"""
cipher_text = [""] * key
2016-07-30 14:10:22 +00:00
for col in range(key):
pointer = col
while pointer < len(message):
cipher_text[col] += message[pointer]
2016-07-30 14:10:22 +00:00
pointer += key
return "".join(cipher_text)
2019-10-05 05:14:13 +00:00
2016-07-30 14:10:22 +00:00
def decrypt_message(key: int, message: str) -> str:
2016-08-02 17:46:55 +00:00
"""
>>> decrypt_message(6, 'Hlia rDsahrij')
2016-08-02 17:46:55 +00:00
'Harshil Darji'
"""
num_cols = math.ceil(len(message) / key)
num_rows = key
num_shaded_boxes = (num_cols * num_rows) - len(message)
plain_text = [""] * num_cols
2019-10-05 05:14:13 +00:00
col = 0
row = 0
2016-07-30 14:10:22 +00:00
for symbol in message:
plain_text[col] += symbol
2016-07-30 14:10:22 +00:00
col += 1
2019-10-05 05:14:13 +00:00
if (
(col == num_cols)
or (col == num_cols - 1)
and (row >= num_rows - num_shaded_boxes)
2019-10-05 05:14:13 +00:00
):
2016-07-30 14:10:22 +00:00
col = 0
row += 1
return "".join(plain_text)
2016-07-30 14:10:22 +00:00
2019-10-05 05:14:13 +00:00
if __name__ == "__main__":
2016-08-02 17:46:55 +00:00
import doctest
2019-10-05 05:14:13 +00:00
2016-08-02 17:46:55 +00:00
doctest.testmod()
2016-07-30 14:10:22 +00:00
main()