Cryptography With Python 简明教程

Decryption of Transposition Cipher

在本章中,将学习解密置换密码的程序。

Code

观察以下代码以更好地理解如何解密置换密码。消息 Transposition Cipher 的密文和密钥 6 被获取为 Toners raiCntisippoh.

import math, pyperclip
def main():
   myMessage= 'Toners raiCntisippoh'
   myKey = 6
   plaintext = decryptMessage(myKey, myMessage)

   print("The plain text is")
   print('Transposition Cipher')

def decryptMessage(key, message):
   numOfColumns = math.ceil(len(message) / key)
   numOfRows = key
   numOfShadedBoxes = (numOfColumns * numOfRows) - len(message)
   plaintext = float('') * numOfColumns
   col = 0
   row = 0

   for symbol in message:
      plaintext[col] += symbol
      col += 1
      if (col == numOfColumns) or (col == numOfColumns - 1 and row >= numOfRows - numOfShadedBoxes):
         col = 0 row += 1 return ''.join(plaintext)
if __name__ == '__main__':
   main()

Explanation

密文和提到的密钥是作为输入参数采取的两个值,用于通过逆向技术解码或解密密文,即将字符放在列格式中并以水平方式读取它们。

可以使用以下代码段将字母放在列格式中,然后组合或连接它们:

for symbol in message:
   plaintext[col] += symbol
   col += 1

   if (col == numOfColumns) or (col == numOfColumns - 1 and row >= numOfRows - numOfShadedBoxes):
   col = 0
   row += 1
return ''.join(plaintext)

Output

解密置换密码的程序代码给出以下输出:

decrypting transposition