Caeser Cipher Cracking Python

时间:2016-10-07 16:15:47

标签: python python-2.7 caesar-cipher

我使用Python 2.7.12运行它

charset="ABCDEFGHIJKLMNOPQRSTUVWXYZ" # The list of characters to be    encrypted
numchars=len(charset) # number of characters that are in the list for encryption

 def caesar_crack(crackme,i,newkey):

    print '[*] CRACKING - key: %d; ciphertext: %s' % (i,crackme)
    crackme=crackme.upper()
    plaintext='' #initialise plaintext as an empty string

    while i <= 26:
        for ch in crackme:   #'for' will check each character in plaintext against charset
            if ch in charset:
                pos=charset.find(ch)    #finds the position of the current character
                pos=pos-newkey
            else:
                new='' # do nothing with characters not in charet
            if pos>=len(charset):   #if the pos of the character is more or equal to the charset e.g -22 it will add 26 to get the correct letter positioning/value
                pos=pos+26
            else:
                new=charset[pos]
            plaintext=plaintext+new
        print '[*] plaintext: ' + plaintext

        if i <= 27:
                newkey=newkey+1
                i=i+1
        return plaintext

def main():
    # test cases
    newkey=0
    i=0
    crackme = 'PBATENGHYNGVBAFLBHUNIRPENPXRQGURPBQRNAQGURFUVSGJNFGUVEGRRA' 
    # call functions with text cases
    caesar_crack(crackme,i,newkey)

# boilerplate
if __name__ == '__main__':
    main()

这就是我到目前为止所做的,我目前正在寻找多次循环,最好是26次(每个数字/字母表中有1个)。

我觉得我拥有的东西应该运作得很好,但我几乎可以肯定我所拥有的东西应该有效但运行它只会运行一次,例如newkey = 0i = 0但是递增到下一个值newkey = 1i = 1但不会重新运行。

有人能发现我失踪的致命缺陷吗?或者有关如何使其更有效地运行的任何提示,都将不胜感激。

1 个答案:

答案 0 :(得分:0)

只需移动

的缩进
return plaintext

离开一步

将解决循环问题,它将遍历所有26个数字

如果好的话,没有检查剩余的程序