Bottom Page

Thread Rating:
  • 3 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Enigma Machine, I need help!
#1

Here is the code I have:

from tkinter import *
import tkinter

#create window
Start = Tk()
Start.title("Enigma Machine")
Start.geometry("400x360+500+200")
Start.resizable(width=False, height=False)

def base():
    """Machine module opening a window with Tk inter to recreate the
    Enigma Machine which was used in WWII by the german army."""
    global PAD1,PAD2,PAD3,text,counter,ecounter,enclist
    Rotors = Frame(bg='dark grey')
    Rotors.pack(side=TOP)

    #in these Frames we will pack the keys for each key of the Keyboard
    Keyrow1 = Frame(pady=5)
    Keyrow1.pack(side=TOP)
    Keyrow2 = Frame(pady=3)
    Keyrow2.pack(side=TOP)
    Keyrow3 = Frame()
    Keyrow3.pack(side=TOP)
    Keyrow4 = Frame(pady=10)
    Keyrow4.pack(side=TOP)

    #this will be the first text field, containing the entered message
    NONEncryptF = Frame()
    NONEncryptF.pack(side=TOP)
    #This Frame contains the second text field with the encripted message
    EncryptF = Frame()
    EncryptF.pack(side=TOP)

    #First text field, M being Message, T for text and L for label
    NONEncryptM = "Inputted Text will be written here."
    NONEncryptT = StringVar()
    NONEncryptL = Label(NONEncryptF,width=50,height=4,textvariable=NONEncryptT,bg="black",fg="white")
    NONEncryptL.pack()
    NONEncryptT.set(str(NONEncryptM))

    #same is done for the encripted text box
    EncryptM = "Encrypted Text will be written here."
    EncryptT = StringVar()
    EncryptL = Label(EncryptF,width=50,height=4,textvariable=EncryptT,bg="grey55",fg="black")
    EncryptL.pack()
    EncryptT.set(str(EncryptM))

    #these are the three rotors, counters for us
    PAD1=1
    PAD2=1
    PAD3=1

    #these btoh counters add a paragraph if the line exceeds 40 characters (see later)
    counter = 0
    ecounter = 0

    #Keyboard
    LR1 = ["q","w","e","r","t","z","u","i","o","p"]
    LR2 = ["a","s","d","f","g","h","j","k","l"]
    LR3 = ["y","x","c","v","b","n","m",".",]
    LR4 = ["space"]

    #these lists will be the containers for the both texts
    text=[]
    enclist = []

    #First Part: having the GUI of the machine work
    def GUI():
        def ROTORMOVER():
            """for each pressed key, we will augment the counter,
            counter moves back to 0 if it reaches 26,
            moving the one to its right"""
            global PAD1,PAD2,PAD3,counter,ecounter
            if PAD3==26:
                PAD3=1
                if PAD2==26:
                    PAD2=1
                    if PAD1==26:
                        PAD1=1
                        PAD2=1
                        PAD3=1
                    else:
                        PAD1+=1
                else:
                    PAD2+=1
            else:
                PAD3+=1
            #increases counters
            counter+=1
            ecounter+=1
            ROTOR3.set(str(PAD3))
            ROTOR2.set(str(PAD2))
            ROTOR1.set(str(PAD1))

        def printer(l):
            """this pastes the normal, inputted text in the Message"""
            global text,NONEncryptM,counter
            ROTORMOVER()
            text+=[l]
            if counter==40:         # if characters exceed 40, we append a paragraph
                text.append("\n")
                counter=0
            NONEncryptM = "".join(text)
            NONEncryptT.set(str(NONEncryptM))
            #we launch encrypt() to encript the message that was just given
            encrypt()

        #We create Labels and Stringvars for each row of keys in the keyboard
        ROTOR1 = StringVar()
        ROTOR2 = StringVar()
        ROTOR3 = StringVar()
        LabelPad1 = Label(Rotors, textvariable = ROTOR1 , bg ="grey")
        ROTOR1.set(str(PAD1))
        LabelPad1.pack(padx=5,pady=10,side=LEFT)
        LabelPad2 = Label(Rotors,textvariable = ROTOR2, bg = "grey")
        ROTOR2.set(str(PAD2))
        LabelPad2.pack(padx=5,pady=10,side=LEFT)
        LabelPad3 = Label(Rotors, textvariable = ROTOR3 , bg ="grey")
        ROTOR3.set(str(PAD3))
        LabelPad3.pack(padx=5,pady=10)

        #creating the keyboard
        for char in LR1:
            Button(Keyrow1,text=char,width=3,pady=5,command=lambda q=char:printer(q)).pack(side=LEFT)
        for char in LR2:
            Button(Keyrow2,text=char,width=3,pady=5,command=lambda q=char:printer(q)).pack(side=LEFT)
        for char in LR3:
            Button(Keyrow3,text=char,width=3,pady=5,command=lambda q=char:printer(q)).pack(side=LEFT)
        Button(Keyrow4,text="Space",width=3,padx=85,pady=5,command=lambda:printer(" ")).pack()
    #Executing code above
    GUI()

    def encrypt():
        # In this second section, we take what was written in the text field and let it "pass through" the rotors
        global EncryptM,text,PAD3,PAD2,PAD1,enclist,c,d,e,ENCMESS,x,ecounter,Rotor1,Rotor2,Rotor3,Mirror
        char = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"," "]
        #c,d,e are variables that act as counters: for each pressed key they increase, meaning pressing twice 'a' will not exit the same key
        c = PAD3-2
        if c==-1:c=26
        d = PAD2-1
        e = PAD1-1
        ENCMESS=0

        #The modifications for the 3 rotors and mirror, I did not insert a plugboard yet in the program
        Rotor1 = [7,13,1,23,6,17,14,10,26,2,5,19,12,18,21,3,25,9,15,24,4,11,20,8,22,16]
        Rotor2 = [19,17,6,3,25,16,7,11,23,4,1,20,9,5,26,22,14,2,18,10,24,15,8,12,21,13]
        Rotor3 = [24,13,9,21,10,5,17,2,12,25,4,11,15,18,7,20,1,14,23,6,16,19,22,3,26,8]
        Mirror = [21,7,17,18,11,3,1,23,15,12,8,25,13,16,9,22,2,26,20,14,6,19,24,4,10,5]

        def starter():
            """Converts our last character of the inputted text into a cipher"""
            global ENCMESS,c,text,x,Rotor1
            x = text[len(text)-1]
            for cha in char:
                ENCMESS+=1
                if x==cha: break

        def coder(seq,rev,m):
            """Acts as our rotors"""
            global ENCMESS
            if rev==0:ENCMESS+=m
            while ENCMESS>26:ENCMESS-=26
            ENCMESS = seq[ENCMESS-1]

        def letters():
            """Converts the ciher back to a letter"""
            global ENCMESS
            ENCMESS = char[ENCMESS-1]

        starter()
        coder(Rotor1,0,c)
        coder(Rotor2,0,d)
        coder(Rotor3,0,e)
        coder(Mirror,2,c)
        coder(Rotor3,1,e)
        coder(Rotor2,1,d)
        coder(Rotor1,1,c)
        #appends parapgraph if the characters are over 40
        for l in enclist:
            if ecounter==40:
                enclist.append("\n")
                ecounter=0
        #If the last charcater (a.k.a. inputted charcter is a space or dot, it inserts respectively space or dot)
        if x==" ": enclist.append(" ")
        elif x==".":enclist.append(".")
        elif x=="\n":pass
        else:       # If not, it appends our encripted character
            letters()
            enclist.append(ENCMESS)
        EncryptM = "".join(enclist)
        EncryptT.set(str(EncryptM))

base()
#keeps the window open
Start.mainloop()
The code works, no errors are summoned or anything. I'm only 16 years old, found out about programming barely a year ago, and love it. I am trying to recreate the "Enigma machine". IT's a coding/decoding machine used by the germans in WWII. My model does not have the plugboard yet, but it is not necessary. When entering a text, I get my text, and my encripted text, perfect? not quite..

My Problem:
The outputted (encripted) text I get, will not retranslate back into to the text if I re-enter it.
What should happen:
The outputted text (for example from hello it is: vepou) will not decode into the text I first entered (if "vepou" is entered, you get "hejjs").
My guess is that one of the counters (probably variable c, defined in encrypt() ) moves my input too far or not far enough..
If anyone has any idea where the problem is and with what to fix it, I would be very grateful.. UNtil then I'm blocked.. (passed the last week trying to figure out what the problem was with 3-4 others simpler programs"..)

I am open to any sort of questions and improvements!
Thank you very very much!
Quote
#2
I saw the display at Ft. Meade when I lived in Virginia at the cryptography Museum.
Know all about it. That machine was used only a few years before I was born,
(Yes, I was born in the first half of the last century (My grandchildren ask what the civil
war was like, and I have to remind that that it was nearly 100 years before my birth).
and is probably why WWII was not one by Germany. One was captured early on,
and decoded by Alan Turing, the Germans never knew, and continues to use them. Most
all messages were intercepted by the British.

If you don't have an answer by tomorrow A.M., I'll give it a go. Right now, I'm getting ready
to watch football, drink coke and eat Twinkies.
Quote
#3
I dont fully understand the enigma machine however i did create a working version in python
there are 3 keys which represent the encoder used
to use the file, save it and run 'python file.py inputstring 0 0 0 encrypt'
That should create you a random key, encrypt the inputstring with that key, the print the output and key into the terminal
'input is input k1 = 3 k2 = 19 k3 = 1 and output is ['n', 'l', 'g', 'e', 'w']'
to decrypt simply put the encrpted text and key into the same process and set it to decrypt mode
'python file.py nlgew 3 19 1 decrypt'
input is nlgew k1 = 3 k2 = 19 k3 = 1 and output is ['i', 'n', 'p', 'u', 't']

the way to encrypt and decrypt is the exact same almost to a point. 
I and taking the value from key1 * key2 * key3 and then using modulo to find the letters offset.

#aplah is a list of the alphabet
# keys are a global variable
    encryption = key3 * key2 * key1 # creates a number between 0 and 15625
    pos = alpha.index(L) # finds the position of the letter in the alphabet
    eL = alpha[(pos + encryption)%26] # adds the result of the keys to the position of the letter while looping arround the alphabet
    key_increment() #increments the key by 1
full code:
https://pastebin.com/XzbhFJSF

the only difference between encrypting the data and encrypting it is as simple as + or -
additional, if you mix the alphabet up you will get a completely different key that should still work in reverse

Edit:
Also, Thanks this was a pretty fun project to work on.
Quote
#4
(Nov-13-2017, 05:00 AM)AceScottie Wrote: I dont fully understand the enigma machine however i did create a working version in python
there are 3 keys which represent the encoder used
to use the file, save it and run 'python file.py inputstring 0 0 0 encrypt'
That should create you a random key, encrypt the inputstring with that key, the print the output and key into the terminal
'input is input k1 = 3 k2 = 19 k3 = 1 and output is ['n', 'l', 'g', 'e', 'w']'
to decrypt simply put the encrpted text and key into the same process and set it to decrypt mode
'python file.py nlgew 3 19 1 decrypt'
input is nlgew k1 = 3 k2 = 19 k3 = 1 and output is ['i', 'n', 'p', 'u', 't']

the way to encrypt and decrypt is the exact same almost to a point. 
I and taking the value from key1 * key2 * key3 and then using modulo to find the letters offset.

#aplah is a list of the alphabet
# keys are a global variable
    encryption = key3 * key2 * key1 # creates a number between 0 and 15625
    pos = alpha.index(L) # finds the position of the letter in the alphabet
    eL = alpha[(pos + encryption)%26] # adds the result of the keys to the position of the letter while looping arround the alphabet
    key_increment() #increments the key by 1
full code:
https://pastebin.com/XzbhFJSF

the only difference between encrypting the data and encrypting it is as simple as + or -
additional, if you mix the alphabet up you will get a completely different key that should still work in reverse

Edit:
Also, Thanks this was a pretty fun project to work on.

Thank you very much for your support and help with the program! Sadly, it doesn't answer the problem I have.. I am searching a program, that uses the principles of encription that resembles mine, so the enigma machine.. The letter has to go through rotor 1, then rotor 2, rotor 3, the through mirror and then back through rotor 3,2 and 1.

I hope you still have time and understand what I mean.. If possible, I need my program, just improved so the decription works. Thank you a lot!

(Nov-12-2017, 10:37 PM)Larz60+ Wrote: I saw the display at Ft. Meade when I lived in Virginia at the cryptography Museum.
Know all about it. That machine was used only a few years before I was born,
(Yes, I was born in the first half of the last century (My grandchildren ask what the civil
war was like, and I have to remind that that it was nearly 100 years before my birth).
and is probably why WWII was not one by Germany. One was captured early on,
and decoded by Alan Turing, the Germans never knew, and continues to use them. Most
all messages were intercepted by the British.

If you don't have an answer by tomorrow A.M., I'll give it a go. Right now, I'm getting ready
to watch football, drink coke and eat Twinkies.

Thank you a lot for your help! I very much appreciate it! :) the help that was sent to me, which you can see in y reply above, isn't sufficient to me sadly.. I require the same encription method as I used. If it possible for you, I would greatly appreciate it if you find a way to decrypt the message properly!

Thank you very much for your help!
Quote
#5
There is a package written to use enigma code,
you can read about it here: https://python-forum.io/Thread-Enigma-Ma...-need-help
nad here: https://pypi.python.org/pypi/py-enigma/0.1
and import the package using:
pip install py-enigma
You can download the source code to look under the covers
Quote
#6
(Nov-13-2017, 06:36 PM)Larz60+ Wrote: There is a package written to use enigma code,
you can read about it here: https://python-forum.io/Thread-Enigma-Ma...-need-help
nad here: https://pypi.python.org/pypi/py-enigma/0.1
and import the package using:
pip install py-enigma
You can download the source code to look under the covers

I noticed this during my programming. But it seems lame, to just go and use it, seen as I am this close to completing my program.. Is there any possible way that you could look into the program to see where the problem lies?

It would be a great help! And I am not the kind of person that just takes the program because I'm lazy. Of course in many cases it is much easier, but I am only 16, and prefer lerning the further I go. So I would need to know where the problem lies..
Quote
#7
If i were writing it, I'd take a peek at their code.
I've learned a lot over the past 50 years this way, and I'm only in my 70's.
But, that's just me.
Quote
#8
(Nov-13-2017, 06:45 PM)Larz60+ Wrote: If i were writing it, I'd take a peek at their code.
I've learned a lot over the past 50 years this way, and I'm only in my 70's.
But, that's just me.

I can imagine.. But at the moment, I still cant find the error.. I am using the method they use to let the charcter pass back thorugh in reverse, but it won't aply to my code.. Would it be possible for you to check an eye on it?
Quote
#9
OK, I'll print out the algorithm from a crypto site, and see if I can follow your code
to find the error.

I'll work on this after dinner tonight, but probably will not have an answer until tomorrow.

One suggestion. I don't don't know if you use an IDE for editing your code, but if so and
it has a debugger, you can run your code step by step, watching selected variables as they change.

I use PyCharm and it has a very good debugger. Most IDE's do.

By the way, your code is very neat and well organized,
perhaps you have found your career.
Quote
#10
(Nov-13-2017, 09:27 PM)Larz60+ Wrote: OK, I'll print out the algorithm from a crypto site, and see if I can follow your code
to find the error.

I'll work on this after dinner tonight, but probably will not have an answer until tomorrow.

One suggestion. I don't don't know if you use an IDE for editing your code, but if so and
it has a debugger, you can run your code step by step, watching selected variables as they change.

I use PyCharm and it has a very good debugger. Most IDE's do.

By the way, your code is very neat and well organized,
perhaps you have found your career.

Thank you very much for your help, and also your remark! Yes, I hope I may be able to start a career with programing, just dont know really where to start... Summer jobs would be complicated/boring seen as I dont have the level..

But back to our code: I use PyScripter for programming and it does and a debugger. I used it a couple of times until now, but dont think it can help much, because the error isn't in the code, but in the philosophy...
I do get a decripted message, but it does not correspond with my input... Here is my problem.

I am guessing I have to find the right list for eversing the process, but it didn't work out so far..
What I have done until now, which I copied from the library you sent me is:
def starter():
            """Converts our last character of the inputted text into a cipher"""
            global ENCMESS,c,text,x,Rotor1
            x = text[len(text)-1]
            for cha in char:
                ENCMESS+=1
                if x==cha: break

        def coder(seq,rev,m):
            """Acts as our rotors"""
            global ENCMESS

            if rev==0 or rev==2:
                ENCMESS =(ENCMESS+m)%26
                ENCMESS = seq[ENCMESS-1]%26
                ENCMESS =(ENCMESS-m)%26
            elif rev==1:
                lst=["empty"]*26
                ENCMESS =(ENCMESS+m)%26
                for i,v in enumerate(seq):
                    lst[v-1] = i
                ENCMESS = lst[ENCMESS-1]%26
                ENCMESS =(ENCMESS-m)%26

        def letters():
            """Converts the ciher back to a letter"""
            global ENCMESS
            ENCMESS = char[ENCMESS-1]

        starter()
        coder(Rotor1,0,c)
        coder(Rotor2,0,d)
        coder(Rotor3,0,e)
        coder(Mirror,2,c)
        coder(Rotor3,1,e)
        coder(Rotor2,1,d)
        coder(Rotor1,1,c)
It still doesn't print the right output.. M< supposition from the beginning is still up, while Ia m thinking that it could be the counter switching letters one too much or not enough.. But I'll see and hopoe what you can find out!
Thank you!
Quote

Top Page

Forum Jump:


Users browsing this thread: 1 Guest(s)