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

时间:2017-06-01 12:38:05

标签: python-3.x encryption brute-force caesar-cipher

我试图通过蛮力解密凯撒密码。我可以相当容易地加密一些东西,然后我希望程序使用强力解密消息。我想要发生的是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)

一旦我运行它,我在python shell上获得以下代码。让我们说消息变量是&#34;我的名字是Daniel&#34;我使用的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

1 个答案:

答案 0 :(得分:1)

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)