凯撒密码蛮力攻击无法解密 - Python

Caeser Cipher Brute Force Attack Won't Decrypt - Python

我试图制作一个用于暴力攻击的程序,它将接受凯撒加密消息的输入并尝试在没有旋转因子的情况下破解它。输出应该是所有 26 个旋转因子的列表以及相应的消息(例如:KEY # 01 :(将输入字符移动 1,等等))并且其中一个应该包含解密的消息。该消息的轮换编号将成为关键(我希望这不会太混乱)。这是我的代码:

message = input("Enter a message: ") # user inputs message
    offset = 0

    while offset < 26:
        for char in message:
            decrypt = " "

            if not char.isalpha(): # to keep punctuation unchanged
                decrypt = decrypt + char

            elif char.isupper():
                decrypt = decrypt + chr((ord(char) - offset - 65) % 26 + 65) # -65 +65 for uppercase Z

            else:
                decrypt = decrypt + chr((ord(char) - offset - 97) % 26 + 97) # -97 +97 for lowercase z

            offset = offset + 1
            print ("KEY #:", offset, message)

该程序不会解密输入,并且出于某种原因它会打印相同的输入 41 次...我不是一个非常熟练的程序员,所以如果有人能帮助我就太好了。

您的脚本存在三个问题:offset = offset + 1 在您的 for 循环中,因此每个字符的 offset 都会增加,这是您不想要的。 decrypt 变量的初始化也在循环内。最后,您要打印 message,而不是 decrypt 结果。

这确实有效:

message = input("Enter a message: ")  # user inputs message
offset = 0

while offset < 26:
    decrypt = ""
    for char in message:
        if not char.isalpha():  # to keep punctuation unchanged
            decrypt = decrypt + char

        elif char.isupper():
            decrypt = decrypt + chr((ord(char) - offset - 65) % 26 + 65)  # -65 +65 for uppercase Z

        else:
            decrypt = decrypt + chr((ord(char) - offset - 97) % 26 + 97)  # -97 +97 for lowercase z

    offset = offset + 1
    print("KEY #:", offset, decrypt)
message = input("Enter a message: ") # user inputs message
    offset = 0 # setting offset to 0

    for offset in range(len(message)): # for loop to run as many times as length of message

        decrypt = " "
        for char in message:

            if not char.isalpha(): # to keep punctuation unchanged
                decrypt = decrypt + char

            elif char.isupper():
                decrypt = decrypt + chr((ord(char) - offset - 65) % 26 + 65) # -65 +65 for uppercase Z

            else:
                decrypt = decrypt + chr((ord(char) - offset - 97) % 26 + 97) # -97 +97 for lowercase z

        print ("KEY #:", offset, decrypt)