使用Python转置密码解密错误 - Python

时间:2017-12-14 14:27:24

标签: python encryption

我遇到了本书提供的代码问题(可以在线轻松访问 - 使用Python发明,转置解密)。奇怪的是,我无法在网上找到有关此错误的任何信息。我想如果这样的公共书中出现错误,至少还有一个人会提到它。

所以我想知道我是否以某种方式打破了它,即使我真正做的只是注释了代码中包含的'pyperclip'脚本的引用。

原始错误是在行“numOfColumns = int(math.ceil(len(message)/ key))”以及后来的“plaintext = [''] * numOfColumns”,因为它试图乘以浮点数类型错误不喜欢这样。我也认为这个解决方案可能会破坏它。

作为参考,此代码的输出旨在打印“常识不常见。|”

# Transposition Cipher Decryption
# http://inventwithpython.com/hacking (BSD Licensed)

import math

def main():
    myMessage = 'Cenoonommstmme oo snnio. s s c'
    myKey = 8

    plaintext = transpositionDecryptMessage(myKey, myMessage)

    # Print with a | (called "pipe" character) after it in case
    # there are spaces at the end of the decrypted message.
    print(plaintext + '|')

    #pyperclip.copy(plaintext)


def transpositionDecryptMessage(key, message):
    # The transposition decrypt function will simulate the "columns" and
    # "rows" of the grid that the plaintext is written on by using a list
    # of strings. First, we need to calculate a few values.

    # The number of "columns" in our transposition grid:
    numOfColumns = int(math.ceil(len(message) / key))
    # The number of "rows" in our grid will need:
    numOfRows = key
    # The number of "shaded boxes" in the last "column" of the grid:
    numOfShadedBoxes = (numOfColumns * numOfRows) - len(message)

    # Each string in plaintext represents a column in the grid.
    plaintext = [''] * numOfColumns

    # The col and row variables point to where in the grid the next
    # character in the encrypted message will go.
    col = 0
    row = 0

    for symbol in message:
        plaintext[col] += symbol
        col += 1 # point to next column

        # If there are no more columns OR we're at a shaded box, go back to
        # the first column and the next row.
        if (col == numOfColumns) or (col == numOfColumns - 1 and row >= numOfRows - numOfShadedBoxes):
            col = 0
            row += 1

    return ''.join(plaintext)


# If transpositionDecrypt.py is run (instead of imported as a module) call
# the main() function.
if __name__ == '__main__':
    main()

0 个答案:

没有答案