通过暴力破解凯撒密码时,无法打印正确的尝试

When decrypting caesar cipher via brute force, cannot print right attempts

我正在尝试通过暴力破解凯撒密码。我可以很容易地加密一些东西,然后我希望程序使用蛮力解密消息。我想要发生的是 python 打印出加密消息的所有 26 个移位值。这是我的代码:

message = input("What message do you want to use: ")
shiftValue = int(input("What would you like to shift the message by: "))
encryptedMsg = ""

for character in message: 
    if character.isalpha() == True: 
        if character == character.lower():
            x = ord(character) - 97 
            x += shiftValue 
            x = x % 26  
            encryptedMsg += chr(x + 97) 
        else:
            x = ord(character) - 65
            x += shiftValue
            x = x % 26
            encryptedMsg += chr(x+65)
    else: 
        encryptedMsg += character

print(encryptedMsg)

def decrypt(encryptedMsg):
    i = 0
    shiftValue = 0
    while i < 26:                  
        attempt = ""
        for char in encryptedMsg:
            if char.isalpha() == True:
                x = ord(char) - 97
                x = x + shiftValue
                x = x % 26
                attempt += chr(x+97)
            else:
                attempt += char
            print(attempt)
            i += 1
            shiftValue += 1

decrypt(encryptedMsg)

一旦我运行这个,我在pythonshell上得到以下代码。假设消息变量是 "My name is Daniel",我使用的 shiftValue 为 2。这是打印的内容:

i
ib
ib 
ib s
ib sg
ib sgt
ib sgtm
ib sgtm 
ib sgtm s
ib sgtm sd
ib sgtm sd 
ib sgtm sd k
ib sgtm sd ko
ib sgtm sd koc
ib sgtm sd kocy
ib sgtm sd kocyv
ib sgtm sd kocyvd
z
zs
zs 
zs j
zs jx
zs jxk
zs jxkd
zs jxkd 
zs jxkd j
zs jxkd ju
zs jxkd ju 
zs jxkd ju b
zs jxkd ju bf
zs jxkd ju bft
zs jxkd ju bftp
zs jxkd ju bftpm
zs jxkd ju bftpmu

decrypt() 的最后 3 行在 for char in encryptedMsg 的每次迭代中执行。这是错误的。您想在打印之前完成解密字符串的创建。

另一个问题是您的程序不能正确处理大写字符。一个快速的解决方法是在处理之前使用 lower() 将所有内容转换为小写。

试试这个:

def decrypt(encryptedMsg):
    i = 0
    shiftValue = 0
    while i < 26:                  
        attempt = ""
        for char in encryptedMsg.lower():
            if char.isalpha() == True:
                x = ord(char) - 97
                x = x + shiftValue
                x = x % 26
                attempt += chr(x+97)
            else:
                attempt += char
        i += 1
        shiftValue += 1
        print(attempt)

编辑:

一种更“pythonic”的实现循环的方法是使用像for x in range(y):这样的语法。此外,if x == True 总是可以简化为 if x:。这是带有单个迭代器变量 (shiftValue) 的代码的简化版本:

def decrypt(encryptedMsg):
    for shiftValue in range(26):
        attempt = ""
        for char in encryptedMsg.lower():
            if char.isalpha():
                x = (ord(char) - 97 + shiftValue) % 26
                attempt += chr(x+97)
            else:
                attempt += char
        print(attempt)