Search code examples
pythonpython-2.7caesar-cipher

Caeser Cipher Cracking Python


I am running this using 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()

This is what I have thus far, I am currently looking to get this to loop multiple times, prefferably 26 (1 for each number/letter of the alphabet).

I feel as though what I have should work just fine but I'm almost certain that what I have should work but upon running it will only run once eg newkey = 0 and i = 0 but will increment to the next value newkey = 1 and i = 1 but will not then rerun.

Can anyone spot the fatal flaw that I'm missing? Or any tips as to how to make it run more efficiently, all would be appreciated.


Solution

  • just move the indentation of

    return plaintext
    

    one step to left

    that will resolve the looping issue and it will go through all 26 numbers

    didnt check the remaining of the program if it is good