iabestever
iabestever

Reputation: 25

caesar cipher brute force decryption

I am trying to write my own python code to brute force a caesar cipher and I need some help. I specifically need help near the end of my code of the function. I want to know how to print specifically so that after each key tried there is a gap. I am using python 3.3 and have just started coding 3 weeks ago.

print ("The plaintext will be stripped of any formatting such as spaces.")
freqlist = []
maxkey = 26
if key > maxkey:
    raise Exception("Enter a key between 0 and 26: ")
elif key < 0:
    raise Exception("Enter a key between 0 and 26: ")
freq = []
inpt=input("Please enter the cipher text:")
inpt = inpt.upper()
inpt = inpt.replace(" ", "")
inpt = inpt.replace(",", "")
inpt = inpt.replace(".", "")
for i in range(0,27):
       key = i

def decrypt():
    for i in range(0,27):
        for a in inpt:
            b=ord(a)
            b-= i
            if b > ord("Z"):
                b -= 26
            elif b < ord("A"):
                b+=26
            freqlist.append(b)
        for a in freqlist:
           d=chr(a)
           freq.append(d)
           freq="".join(freq)
           print(freq.lower(),"\n")
decrypt()

I am trying to use a for loop and I don't think it is really working effectively.

Upvotes: 0

Views: 4605

Answers (1)

CDspace
CDspace

Reputation: 2689

Based on the error you posted, I think this should help.

In Python, you can have local and global variables of the same name. The freq in the function is local, and thus the initialization of the global freq doesn't touch the local one. To use the global freq, you have to tell the function to do so, via the global statement. This is explained a little more in the Python FAQs.

That should be enough to get you back on track.

EDIT: Below is an edit of your decrypt function, with some explanations of the changes

def decrypt():

    # we don't need the zero start value, that's the default
    # test all possible shifts
    for i in range(27):

        # initialize the array
        freqlist = []

        # shift all the letters in the input
        for a in inpt:
            b = ord(a)
            b -= i
            if b > ord("Z"):
                b -= 26
            elif b < ord("A"):
                b+=26
            freqlist.append(b)

        # now put the shifted letters back together
        shifted = ""
        for a in freqlist:
           d = chr(a)
           # append the shifted letter onto our output
           shifted += d

        # after we put the decrypted string back together, print it
        # note this is outside the letter loops, 
        # but still inside the possible shifts loop
        # thus printing all possible shifts for the given message
        print(d)

Upvotes: 2

Related Questions