TheAlgorithms-Python/ciphers/transposition_cipher.py

71 lines
1.8 KiB
Python
Raw Normal View History

2016-07-30 19:40:22 +05:30
import math
"""
2020-02-03 14:30:58 +05:30
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 01:14:13 -04:00
message = input("Enter message: ")
key = int(input("Enter key [2-%s]: " % (len(message) - 1)))
mode = input("Encryption/Decryption [e/d]: ")
2016-07-30 19:40:22 +05:30
2019-10-05 01:14:13 -04:00
if mode.lower().startswith("e"):
2016-07-30 19:40:22 +05:30
text = encryptMessage(key, message)
2019-10-05 01:14:13 -04:00
elif mode.lower().startswith("d"):
2016-07-30 19:40:22 +05:30
text = decryptMessage(key, message)
# Append pipe symbol (vertical bar) to identify spaces at the end.
2019-10-05 01:14:13 -04:00
print("Output:\n%s" % (text + "|"))
2016-07-30 19:40:22 +05:30
def encryptMessage(key: int, message: str) -> str:
2016-08-02 23:16:55 +05:30
"""
>>> encryptMessage(6, 'Harshil Darji')
'Hlia rDsahrij'
"""
2019-10-05 01:14:13 -04:00
cipherText = [""] * key
2016-07-30 19:40:22 +05:30
for col in range(key):
pointer = col
while pointer < len(message):
cipherText[col] += message[pointer]
pointer += key
2019-10-05 01:14:13 -04:00
return "".join(cipherText)
2016-07-30 19:40:22 +05:30
def decryptMessage(key: int, message: str) -> str:
2016-08-02 23:16:55 +05:30
"""
>>> decryptMessage(6, 'Hlia rDsahrij')
'Harshil Darji'
"""
2016-07-30 19:40:22 +05:30
numCols = math.ceil(len(message) / key)
numRows = key
numShadedBoxes = (numCols * numRows) - len(message)
plainText = [""] * numCols
2019-10-05 01:14:13 -04:00
col = 0
row = 0
2016-07-30 19:40:22 +05:30
for symbol in message:
plainText[col] += symbol
col += 1
2019-10-05 01:14:13 -04:00
if (
(col == numCols)
or (col == numCols - 1)
and (row >= numRows - numShadedBoxes)
):
2016-07-30 19:40:22 +05:30
col = 0
row += 1
return "".join(plainText)
2019-10-05 01:14:13 -04:00
if __name__ == "__main__":
2016-08-02 23:16:55 +05:30
import doctest
2019-10-05 01:14:13 -04:00
2016-08-02 23:16:55 +05:30
doctest.testmod()
2016-07-30 19:40:22 +05:30
main()