Python/ciphers/transposition_cipher.py

55 lines
1.4 KiB
Python
Raw Normal View History

from __future__ import print_function
2016-07-30 14:10:22 +00:00
import math
def main():
message = raw_input('Enter message: ')
key = int(raw_input('Enter key [2-%s]: ' % (len(message) - 1)))
mode = raw_input('Encryption/Decryption [e/d]: ')
2016-07-30 14:10:22 +00:00
if mode.lower().startswith('e'):
text = encryptMessage(key, message)
elif mode.lower().startswith('d'):
text = decryptMessage(key, message)
# Append pipe symbol (vertical bar) to identify spaces at the end.
print('Output:\n%s' %(text + '|'))
def encryptMessage(key, message):
2016-08-02 17:46:55 +00:00
"""
>>> encryptMessage(6, 'Harshil Darji')
'Hlia rDsahrij'
"""
2016-07-30 14:10:22 +00:00
cipherText = [''] * key
for col in range(key):
pointer = col
while pointer < len(message):
cipherText[col] += message[pointer]
pointer += key
return ''.join(cipherText)
def decryptMessage(key, message):
2016-08-02 17:46:55 +00:00
"""
>>> decryptMessage(6, 'Hlia rDsahrij')
'Harshil Darji'
"""
2016-07-30 14:10:22 +00:00
numCols = math.ceil(len(message) / key)
numRows = key
numShadedBoxes = (numCols * numRows) - len(message)
plainText = [""] * numCols
col = 0; row = 0;
for symbol in message:
plainText[col] += symbol
col += 1
if (col == numCols) or (col == numCols - 1) and (row >= numRows - numShadedBoxes):
col = 0
row += 1
return "".join(plainText)
if __name__ == '__main__':
2016-08-02 17:46:55 +00:00
import doctest
doctest.testmod()
2016-07-30 14:10:22 +00:00
main()