コード例 #1
0
def find_rotor_start(rotor_choice, ciphertext, cribtext, ring_choice):
    from enigma.machine import EnigmaMachine

    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    machine = EnigmaMachine.from_key_sheet(
        rotors=rotor_choice,
        reflector='B',
        ring_settings=ring_choice,
        plugboard_settings='AV BS CG DL FU HZ IN KM OW RX')

    # Do a search over all possible rotor starting positions
    for rotor1 in alphabet:  # Search for rotor 1 start position
        for rotor2 in alphabet:  # Search for rotor 2 start position
            for rotor3 in alphabet:  # Search for rotor 3 start position

                # Generate a possible rotor start position
                start_pos = rotor1 + rotor2 + rotor3

                # Set the starting position
                machine.set_display(start_pos)

                # Attempt to decrypt the plaintext
                plaintext = machine.process_text(ciphertext)
                print(plaintext)

                # Check if decrypted version is the same as the crib text
                if plaintext == cribtext:
                    print("Valid settings found!")
                    return rotor_choice, ring_choice, start_pos

    # If we didn't manage to successfully decrypt the message
    return rotor_choice, ring_choice, "Cannot find settings"
コード例 #2
0
def run_enigma_task(num):
    print("Started worker #{}".format(num))
    while not stop_event.is_set():
        while data_queue.empty():
            if stop_event.is_set():
                return
            time.sleep(0.05)
        d = data_queue.get()

        machine = EnigmaMachine.from_key_sheet(rotors=d["rotor"],
                                               reflector=d["ref"],
                                               ring_settings=d["ring"],
                                               plugboard_settings=d["plug"])

        print("Created enigma from settings: ")
        print(d)
        # <-- 17576 iterations -->
        for r in generate_rotor_positions():
            machine.set_display(r)

            for cipher, char in zip(CIPHERTEXT, PLAINTEXT):
                output = machine.process_text(cipher)
                if output != char:
                    break
            else:
                d["display"] = r
                solution_queue.put(d)
                stop_event.set()
                return
コード例 #3
0
def saveBtn():
    '''Get roters, rings and plugboard settings and pass to enigma machine, print all settings'''
    roter1 = ro1.get()
    roter2 = ro2.get()
    roter3 = ro3.get()
    global roters_package
    roters = roter1 + ' ' + roter2 + ' ' + roter3

    ring_seting1 = roi1.get()
    ring_seting2 = roi2.get()
    ring_seting3 = roi3.get()

    global ring_settings
    ring_settings = []
    ring_settings.clear()
    ring_settings.append(ring_seting1)
    ring_settings.append(ring_seting2)
    ring_settings.append(ring_seting3)

    plugboard_settings = plugb.get()

    global machine
    machine = EnigmaMachine.from_key_sheet(
        rotors=roters,
        reflector='B',
        ring_settings=ring_settings,
        plugboard_settings=plugboard_settings)
    machine.set_display('WXC')
    msg_key = machine.process_text('KCH')
    machine.set_display(msg_key)

    print(
        f"{bcolors['OKCYAN']}Roters: {roters} \t Ring Setting: {ring_settings} \t Plug Setting: {plugboard_settings}{bcolors['ENDC']}"
    )
コード例 #4
0
def find_rotor_start( rotor_choice, ciphertext, cribtext ):

    from enigma.machine import EnigmaMachine

    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    machine = EnigmaMachine.from_key_sheet(
       rotors=rotor_choice,
       reflector='B',
       ring_settings='1 1 1',					# no ring setting
       plugboard_settings='AV BS CG DL FU HZ IN KM OW RX')	# plugboard known


    # do an exhaust search over all possible rotor starting positions
    for i in range(len(alphabet)):            # search for rotor 1 start position
        for j in range(len(alphabet)):        # search for rotor 2 start position
            for k in range(len(alphabet)):    # search for rotor 3 start position
                # generate a possible rotor start position
                start_pos = alphabet[i] + alphabet[j] + alphabet[k]

                # set machine initial starting position and attempt decrypt
                machine.set_display(start_pos)
                plaintext = machine.process_text(ciphertext)

                # check if decrypt is the same as the crib text
                if (plaintext == cribtext):
                    # print( start_pos, plaintext, cribtext )
                    return( rotor_choice, start_pos )

    return( rotor_choice, "null" )
コード例 #5
0
    def __init__(self):
        pygame.init()
        self.font = pygame.font.SysFont('Arial', 25)
        pygame.display.set_caption("Enigma")
        self.screen = pygame.display.set_mode((0, 0), pygame.RESIZABLE)
        self.r1Count = self.r2Count = self.r3Count = 1
        #Adding hooks
        pygame.draw.lines(self.screen, yellow, False, [(620, 260), (650, 260)],
                          5)
        pygame.draw.lines(self.screen, yellow, False, [(310, 260), (340, 260)],
                          5)
        #border lines
        pygame.draw.lines(self.screen, white, False, [(0, 500), (1600, 500)],
                          5)
        pygame.draw.lines(self.screen, white, False, [(750, 0), (750, 1500)],
                          5)
        #Initalizing enigma
        self.machine = EnigmaMachine.from_key_sheet(
            rotors='II IV V',
            reflector='B',
            ring_settings=[1, 20, 11],
            plugboard_settings='AV BS CG DL FU HZ IN KM OW RX')
        self.f = open("output.txt", "a")
        self.x = 850
        self.y = 100
        self.count = 0

        #Output screen
        pygame.draw.rect(self.screen, white, (850, 100, 600, 300))
        #Reset button
        pygame.draw.rect(self.screen, white, (440, 400, 70, 40))
        self.reset = self.screen.blit(self.font.render("RESET", True, black),
                                      (440, 400))
コード例 #6
0
def find_rotor_start( rotor_choice, ciphertext, cribtext ):

    from enigma.machine import EnigmaMachine

    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    machine = EnigmaMachine.from_key_sheet(
       rotors=rotor_choice,
       reflector='B',
       ring_settings='21 15 16',					
       plugboard_settings='KL IT PQ MY XC NF VZ JB SH OG')	


    # Search over all possible rotor starting positions
    for i in range(len(alphabet)):            # search for rotor 1 start position
        for j in range(len(alphabet)):        # search for rotor 2 start position
            for k in range(len(alphabet)):    # search for rotor 3 start position

                # Generate a possible rotor start position
                start_pos = alphabet[i] + alphabet[j] + alphabet[k]

                # Set machine initial starting position and attempt to decrypt
                machine.set_display(start_pos)
                plaintext = machine.process_text(ciphertext)

                #print("Plain: " + plaintext + ", Crib: " + cribtext)

                # Check if decrypted text is the same as the crib text
                if (plaintext == cribtext):
                    return( rotor_choice, start_pos )

    return( rotor_choice, "null" )
コード例 #7
0
ファイル: procscript.py プロジェクト: FSUMitch/miscctfs
def enigma_thang(rGuessIn, reflect_In, pairG_In, rSettings):
    #we are given these settings
    initkey = 'GQT'
    messagekey = 'UKJ'
    ciphertext = 'GCXSSBPPIUDNWXJZGIICUEFYGISQOCGLLGMMKYHJ'

    rguess = rGuessIn
    pairguess = pairG_In

    #initiate machine with known quantities and guesses
    machine = EnigmaMachine.from_key_sheet(
        rotors="{} {} {}".format(rguess[0], rguess[1], rguess[2]),
        reflector=reflect_In,
        ring_settings=rSettings,
        plugboard_settings='BF CM DR HQ JK LU OY PW ST {}'.format(pairguess),
    )

    #encrypt the message key so we can use decrypted key as display for next round
    machine.set_display(initkey)
    msg_key = machine.process_text(messagekey)

    #finally decrypt with all settings set up
    machine.set_display(msg_key)
    plaintext = machine.process_text(ciphertext)

    #check if we are close to correct so we don't wait 10 minutes to figure out code is wrong
    if "ELADE" in plaintext:
        print(plaintext, rGuessIn, reflect_In, pairG_In, rSettings)
        print("THIS ONE!!!!!!!!!!!!!!!!!!!!")
コード例 #8
0
    def __init__(self, codebuch_path, day=datetime.now().day):
        """Set up an operator with a copy of this month's codebuch."""
        # Get today's rotor settings.
        with open(codebuch_path) as f:
            self.machine = EnigmaMachine.from_key_file(f, day=day)

        # Generate operator grundstellung.
        self.grundstellung = random_letters(3)
コード例 #9
0
def encryptResult():
    message = request.form['message']
    reflector = request.form['reflector'].upper()
    rotor1 = int(request.form['rotor1'])
    rotor2 = int(request.form['rotor2'])
    rotor3 = int(request.form['rotor3'])
    ringSetting1 = int(request.form['ringSetting1'])
    ringSetting2 = int(request.form['ringSetting2'])
    ringSetting3 = int(request.form['ringSetting3'])
    startingPosition1 = request.form['startingPosition1']
    startingPosition2 = request.form['startingPosition2']
    startingPosition3 = request.form['startingPosition3']
    messageKey = request.form['messageKey1'] + request.form[
        'messageKey2'] + request.form['messageKey3']

    setDisplay = startingPosition1 + startingPosition2 + startingPosition3

    machine = EnigmaMachine.from_key_sheet(
        rotors=getRotor(rotor1, rotor2, rotor3),
        reflector=request.form['reflector'].upper(),
        ring_settings=[ringSetting1, ringSetting2, ringSetting3])

    # set machine initial starting position of rotors
    machine.set_display(setDisplay)

    #encrypt the key
    enc_key = machine.process_text(messageKey)

    # use message key
    machine.set_display(messageKey)

    cipherText = machine.process_text(message)

    html = "<!DOCTYPE html>\n"
    html += "<html lang='en'>\n"
    html += "<head>\n"
    html += "<meta charset='UTF-8'>\n"
    html += "<title>Encrypted</title>\n"
    html += "</head>\n"
    html += "<body style='background-color:powderblue;'>\n"
    html += "<div>\n"
    html += "<p style='font-family: Courier;'>Cipher Text: " + cipherText + "</p>"
    html += "</div>\n"
    html += "<div>\n"
    html += "<p style='font-family: Courier;'>Message Key: " + enc_key + "</p>"
    html += "</div>\n"
    html += "<div>\n"
    html += "<form method='POST' action='encryptSimulator'>\n"
    html += "<input style='width:150px; height:150px; font-size:100px;' type='submit' value='Encrypt'/>\n"
    html += "</form>\n"
    html += "<br/>\n"
    html += "<form method='POST' action='decryptSimulator'>\n"
    html += "<input style='width:150px; height:150px; font-size:100px;' type='submit' value='Decrypt'/>\n"
    html += "</form>\n"
    html += "</div>\n"
    html += "</body>"
    html += "</html>"
    return html
コード例 #10
0
def testAllVars(r1_0, r1_1, r2_0, r2_1, r3_0, r3_1):
    rs = ' '.join([r1_0, r2_0, r3_0])
    machine = EnigmaMachine.from_key_sheet(rotors='III II IV',
                                           reflector='B',
                                           ring_settings=rs,
                                           plugboard_settings='CT EW JL QX')
    machine.set_display(''.join([r1_1, r2_1, r3_1]))
    c = machine.process_text('JGYJZ NOXZX QZRUQ KNTDN UJWIA',
                             replace_char=None)
    return c
コード例 #11
0
def testRot1(var1, var2):
    rs = var1 + ' A A'
    machine = EnigmaMachine.from_key_sheet(rotors='III II IV',
                                           reflector='B',
                                           ring_settings=rs,
                                           plugboard_settings='CT EW JL QX')
    machine.set_display(var2 + 'EP')
    c = machine.process_text('JGYJZ NOXZX QZRUQ KNTDN UJWIA',
                             replace_char=None)
    return c
コード例 #12
0
def configure_enigma_machine(rotors_pos, rotor_start_conf):
	machine = EnigmaMachine.from_key_sheet(
		rotors = rotors_pos,
		reflector='B',
		ring_settings=[0, 0, 0],
		plugboard_settings='')

	machine.set_display( rotor_start_conf )

	return machine
コード例 #13
0
def testVarsSb(r1_0, r1_1, r2_0, r2_1, r3_0, r3_1, pb, cip=None):
    if cip is None:
        cip = 'JGYJZ NOXZX QZRUQ KNTDN UJWIA'
    rs = ' '.join([r1_0, r2_0, r3_0])
    machine = EnigmaMachine.from_key_sheet(rotors='III II IV',
                                           reflector='B',
                                           ring_settings=rs,
                                           plugboard_settings=pb)
    machine.set_display(''.join([r1_1, r2_1, r3_1]))
    c = machine.process_text(cip, replace_char=None)
    return c
コード例 #14
0
ファイル: gamescreen.py プロジェクト: trinoculars/code-jam-6
def get_encrypted_text(text: str, rotor_settings: str,
                       plug_settings: str) -> str:
    """Gives encrypted text based on the param settings"""
    machine = EnigmaMachine.from_key_sheet(
        rotors="I II III",
        reflector="B",
        ring_settings=[1, 20, 11],
        plugboard_settings=plug_settings,
    )
    machine.set_display(rotor_settings)
    return machine.process_text(text)
コード例 #15
0
def get_setting():
    test = ""
    ring_setting = [1, 1, 1]
    ciphertext = 'IPUXZGICZWASMJFGLFVIHCAYEG'
    plaintext = "HOWDYAGGIESTHEWEATHERISFINE"
    while 'HOWDYAGGIES' not in test:
        ring_setting = next_position(ring_setting)
        machine = EnigmaMachine.from_key_sheet(
            rotors='I II III',
            reflector='B',
            ring_settings=ring_setting,
            plugboard_settings='AV BS CG DL FU HZ IN KM OW RX')
        test = machine.process_text(ciphertext)
    return ring_setting
コード例 #16
0
def brute_ring_settings(ciphertext):
    for a in range(1, 26):
        for b in range(1, 26):
            for c in range(1, 26):
                machine = EnigmaMachine.from_key_sheet(
                    rotors='I II III',
                    reflector='B',
                    ring_settings=[a, b, c],
                    plugboard_settings='AV BS CG DL FU HZ IN KM OW RX')
                plaintext = machine.process_text(ciphertext)
                if plaintext.startswith('HOWDY'):
                    print('[+] Ring settings: {}, {}, {}'.format(a, b, c))
                    return a, b, c
    return -1, -1, -1
コード例 #17
0
def find_rotor_start(ciphertext, a, rotor):
    from enigma.machine import EnigmaMachine
    alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    machine = EnigmaMachine.from_key_sheet(
        rotors=['Gamma', 'II', 'IV', rotor],
        reflector='C',
        ring_settings=[3, 5, a, 20],
        plugboard_settings='fv cd hu ik es op yl wq jm')

    for rotor3 in alphabets:
        start_pos = 'F' + 'J' + rotor3 + 'O'
        machine.set_display(start_pos)
        plaintext = machine.process_text(ciphertext)
        print(plaintext)
コード例 #18
0
def test(li, deb=False):
    rs = ' '.join([str(i) for i in li])
    #print rs
    try:
        machine = EnigmaMachine.from_key_sheet(
            rotors='III II IV',
            reflector='B',
            ring_settings=rs,
            plugboard_settings='DE AH CO GZ LQ NY PS TW IJ KM')

        machine.set_display('EFM')
        c = machine.process_text('XTSYN WAEUG EZALY NRQIM', replace_char=None)
        if deb:
            print c
        if 'HELLO' in c:
            print i, j, k
    except Exception as e:
        pass
コード例 #19
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # NOTE This is essentially a singleton
        # All global variables go here.
        self.machine = EnigmaMachine.from_key_sheet(
            rotors="I II III",
            reflector="B",
            ring_settings=[1, 20, 11],
            plugboard_settings="",
        )  # Begin instantiation. Change onload
        self.machine.set_display("AAA")
        self.game_id = None
        self.APP_DIR = os.path.dirname(os.path.abspath(__file__))

        self.keys = [
            "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",
        ]
コード例 #20
0
def find_rotor_start(rotor_choice, ring_choice, ciphertext, cribtext):
    alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

    machine = EnigmaMachine.from_key_sheet(rotors=rotor_choice,
                                           reflector='B',
                                           ring_settings=ring_choice,
                                           plugboard_settings='BU GE VL')

    for rotor1 in alphabet:
        for rotor2 in alphabet:
            for rotor3 in alphabet:
                start_pos = rotor1 + rotor2 + rotor3
                machine.set_display(start_pos)
                plaintext = machine.process_text(ciphertext)
                # print(plaintext)
                if cribtext in plaintext:
                    print('Valid settings found!')
                    logging.info('Valid settings found!')
                    logging.info(plaintext)
                    return rotor_choice, ring_choice, start_pos
    return rotor_choice, ring_choice, "Cannot find settings"
コード例 #21
0
ファイル: save_game.py プロジェクト: trinoculars/code-jam-6
def on_config_change():
    """
    After you change the JSON data w/ JSONStore, call this function
    This should only be called for rotor or plug changes
    """
    store = JsonStore(DATA_DIR)
    game_id = str(App.get_running_app().game_id)
    plugs = store.get(game_id)["current_state"]["plugs"]
    plug_settings = " ".join(x for x in plugs)
    App.get_running_app().machine = EnigmaMachine.from_key_sheet(
        rotors="I II III",
        reflector="B",
        ring_settings=[1, 20, 11],
        plugboard_settings=plug_settings,
    )
    rotors = ""
    for x in store.get(game_id)["current_state"]["rotors"]:
        if x is None:
            continue
        rotors += x
    App.get_running_app().machine.set_display(rotors)
コード例 #22
0
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect the socket to the port where the server is listening
server_address = (TCP_IP, TCP_PORT)
print('connecting to {} port {}'.format(*server_address))
sock.connect(server_address)

#messages that are to be sent
queue = deque([
    "She made the room dark and slept; she awoke and made the room light; she ate and exchanged ideas with her friends, and listened to music and attended lectures; she make the room dark and slept. Above her, beneath her, and around her, the Machine hummed eternally; she did not notice the noise, for she had been born with it in her ears. The earth, carrying her, hummed as it sped through silence, turning her now to the invisible sun, now to the invisible stars. She awoke and made the room light. The Secret word is electroboom."
])

#setup machine according to specs from a daily key sheet:
#medium-hard, army level, only initial three rotors
machine = EnigmaMachine.from_key_sheet(rotors='II I III',
                                       reflector='B',
                                       plugboard_settings='KE JD MN LS OW')

while 1:

    #set machine to todays setting
    machine.set_display('ABC')

    #write info to log
    f.write(str(datetime.datetime.now()) + "\n")
    f.write(str(machine.get_display()) + "\n")
    fx.write("Rotor position: " + str(machine.get_display()) + "\n")

    #pick a message and encrypt it
    MESSAGE = queue.popleft()
    EM = machine.process_text(MESSAGE)
コード例 #23
0
ファイル: enigma2.py プロジェクト: jackfoil/Team-Hydra
#X is not in use, to make your life easier
ALPHABET = [
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
    'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'Y', 'Z'
]

#there are more reflectors, but this will be bad enough for you to deal with.
LIST_OF_REFLECTORS = ['B', 'C']

message = stdin.read().rstrip("\n")

for i in list(permutations(LIST_OF_REFLECTORS)):
    reflector = i[0]
    for j in list(permutations(LIST_OF_ROTORS)):
        rotor = " ".join(j)
        for k in list(permutations(RING_SETTINGS)):
            ring_settings = " ".join(k)
            print("{} {} {}".format(reflector, rotor, ring_settings))

            #This is one way to create an enigma machine, there are others ;)
            machine = EnigmaMachine.from_key_sheet(
                rotors=rotor,
                reflector=reflector,
                ring_settings=ring_settings,
                plugboard_settings='QZ WG EC RV TB YN UM IK OL PA')

            decrypted_message = machine.process_text(message)
            decrypted_message = decrypted_message.split("X")
            decrypted_message = " ".join(decrypted_message)
            print(decrypted_message)
コード例 #24
0
ファイル: decrypt.py プロジェクト: LisaCaissy/Enigma
           'AJDKSIRUXBLHWTMCQGZNPYFVOE',
           ring_setting=5,
           stepping='E')
r3 = Rotor('my rotor3',
           'BDFHJLCPRTXVZNYEIWGAKMUSQO',
           ring_setting=15,
           stepping='V')

#Reflector
reflector = Rotor('my reflector', 'FVPJIAOYEDRZXWGCTKUQSBNMHL')

#Plugboard
pb = Plugboard.from_key_sheet('PO ML IU KJ NH YT GB VF RE DC')

#Machine
machine_encrypt = EnigmaMachine([r1, r2, r3], reflector, pb)
machine_decrypt = EnigmaMachine([r1, r2, r3], reflector, pb)


def encrypter():

    global message
    global ciphertext_encrypt
    # Set the initial position of the Enigma rotors
    machine_encrypt.set_display('AFP')
    print("AFP")

    # Encrypt the text 'BFR' and sotre it as msg_key
    msg_key = machine_encrypt.process_text('OMH')
    print(msg_key)
コード例 #25
0
message = stdin.read().rstrip("\n")

for i in list(permutations(LIST_OF_REFLECTORS)):
    reflector = i[0]
    for j in list(permutations(LIST_OF_ROTORS)):
        rotor = " ".join(j)
        for k in list(permutations(RING_SETTINGS)):
            ring_settings = " ".join(k)
            for combo in combinations(ALPHABET,
                                      2):  # 2 for pairs, 3 for triplets, etc
                for l in list(permutations(combo)):
                    #print combo
                    try:
                        #This is one way to create an enigma machine, there are others ;)
                        machine = EnigmaMachine.from_key_sheet(
                            rotors="III I II",
                            reflector="B",
                            ring_settings="B D J",
                            plugboard_settings='LO KI JU HY GT FR DE SW QA {}'.
                            format("".join(l)))

                        decrypted_message = machine.process_text(message)
                        decrypted_message = decrypted_message.split("X")
                        decrypted_message = " ".join(decrypted_message)
                        print("{} {} {} LO KI JU HY GT FR DE SW QA {}".format(
                            reflector, rotor, ring_settings, "".join(l)))
                        #print("{} {} {}".format(reflector, rotor, ring_settings))
                        print(decrypted_message)
                    except:
                        pass
コード例 #26
0
ファイル: enigmaExemplo.py プロジェクト: felipeband/hal9000
from enigma.machine import EnigmaMachine

machine  = EnigmaMachine.from_key_sheet(
            rotors = 'II IV V',
            reflector = 'B',
            ring_settings = [1, 20, 11],
            plugboard_settings = 'AV BS CG DL FU HZ IN KM OW RX')

machine.set_display('WXC')
msg_key = machine.process_text('KCH')
machine.set_display(msg_key)
chiphertext = 'NIBLFMYMLLUFWCASCSSNVHAZ'
plaintext = machine.process_text(chiphertext)

print plaintext

コード例 #27
0
#!/usr/bin/env python
import copy
from enigma.machine import EnigmaMachine
from sys import stdin, stderr

#print("Starting up machine...")

#D = int(input("What is the day for this message? :"))

with open('Schlusselblatt', 'r') as f:
    #    machine = EnigmaMachine.from_key_file(f, day=D)
    machine = EnigmaMachine.from_key_file(f, day=20)
    machine1 = copy.deepcopy(machine)

    #pick a message and encrypt it
    #MESSAGE = input("What is the message? :")
    MESSAGE = stdin.read().rstrip("\n")

    EM = machine.process_text(MESSAGE)
    print("Output message = ", EM, "\n")

    #decrypt message, just to double check
    #we are using a copy of the machine, with the original configurations, to check the message to ensure it is functioning.
    ED = machine1.process_text(EM)
    print("Input message = ", ED, "\n")

print('Completed')
コード例 #28
0
#

# Reflector names   |  Enigma Models
# ------------------------------------
# B, C              |  All Wehrmacht models
# B-Thin, C-Thin    |  Kriegsmarine M4 (with Beta & Gamma rotors)
#
# Ring settings
# 3 numbers between [0;25]
#
# Plugboard settings
# Pairs of letters between A-Z up to 10 pairs
# Ref:https://py-enigma.readthedocs.io/en/latest/reference.html#rotor-table-label

machine = EnigmaMachine.from_key_sheet(rotors='I II III',
                                       reflector='B',
                                       ring_settings=[0, 0, 0],
                                       plugboard_settings='')

# set machine initial starting position
machine.set_display('AAA')
# get machine initial starting position
position = machine.get_display()

# cipher/decrypt the message key
msg_key = machine.process_text(
    'AAA', replace_char='X'
)  # replace_char serve para substituir os caracteres especiais por X

print(msg_key)
ciphertext = 'NIBLFMYMLLUFWCASCSSNVHAZ'
plaintext = machine.process_text(ciphertext)
コード例 #29
0
reflectors = ['B-Thin', 'C-Thin']
rotor_combs = []
for num_1 in num_rotors:
    for num_2 in num_rotors:
        for num_3 in num_rotors:
            for sym in sym_rotors:
                rotor_combs.append(' '.join([sym, num_1, num_2, num_3]))

# Given settings
ring_setting = ' '.join([chr(ord('a') + i - 1) for i in [4, 9, 3, 20]])
plugboard_setting = 'fv cd hu ik es op yl wq jm'
start_positions = ''.join([chr(ord('a') + i - 1) for i in [2, 5, 14, 5]])

for rotor_comb in rotor_combs:
    for reflector in reflectors:

        # Create an enigma machine object from py-enigma
        machine = EnigmaMachine.from_key_sheet(
            rotors=rotor_comb,
            reflector=reflector,
            ring_settings=ring_setting,
            plugboard_settings=plugboard_setting)

        machine.set_display(start_positions)
        decipheredtext = machine.process_text(ciphertext)

        # Look for flag format:
        if (decipheredtext[:6] == "CSICTF"):
            print(decipheredtext)
コード例 #30
0
RZNSZNCTWMEHMTSXRYMANXPMCURNGDERSIPVLLOUPYXECS
LGBYFDXIEPLBHIRJTOYMCYCADOFBHNTODPTCWPMKJXKVSWH
TINWJKPHLXDSPRMYGIEDVJWKTDCOGTTLGTHZFWBEXZLECRTI
HANJQBDFCLJYRHLLHUJZLFMFLQTHJHZDAKDHBOAVBANINGRK
BDNEOTULNIDOZWLRCENSRHROXCYFPSFQMONHBQAEELLOH
GUEYKNARFYJJOURVGONUMGZNGYOTSZLIODFTGIHVPULLLH
RYCFLORWZK""".replace('\n', '').replace('\r', '').replace(' ', '')

ansData = []
for i in keyData:
    ansData.append(int(i, 2) ^ int("11111111", 2))

ansData[0] = ansData[0] + 1
ansData[1] = ansData[1] + 1
ansData[3] = ansData[3] + 1

myString = ""
for i in ansData:
    myString += chr(i)

machine = EnigmaMachine.from_key_sheet(
               rotors=myString[0:7],
               reflector=myString[8],
               ring_settings=[int(myString[10], 10), int(myString[11:14], 10), int(myString[14:17], 10)],
               plugboard_settings=myString[18:47])

machine.set_display(myString[48:])

plaintext = machine.process_text(message).replace('X', ' ')

コード例 #31
0
async def enigma_act():
    estat_id, command, letter = context2.update.callback_query.data.split()[1:]

    estat = enigmas.get(estat_id)

    if estat is None:
        await EditMessageReplyMarkup(chat_id=context2.update.callback_query.message.chat.chat_id,
                                     message_id=context2.update.callback_query.message.message_id).send()
        AnswerCallbackQuery(context2.update.callback_query.query_id, MSG.expired).webhook()
        return

    AnswerCallbackQuery(context2.update.callback_query.query_id).webhook()

    if command == 'set':
        estat.input = ''

        m = MSG.setup.format(setting=MSG.setup_display,
                             display=' '.join(estat.display),
                             reflector=estat.reflector,
                             rotors=' '.join(estat.rotors_list),
                             rings=' '.join(estat.rings_list),
                             plugboard=' '.join(estat.plugboard) if len(
                                 estat.plugboard) else MSG.plugboard_empty,
                             idisplay=' '.join(estat.display))

        kb = enigma_kb(estat_id, 'enigma-display')
        await EditMessageText(chat_id=context2.update.callback_query.message.chat.chat_id,
                              message_id=context2.update.callback_query.message.message_id, text=m,
                              reply_markup=kb).send()
        return

    machine = EnigmaMachine.from_key_sheet(
        rotors=estat.rotors_list,
        reflector=estat.reflector,
        ring_settings=' '.join(estat.rings_list),
        plugboard_settings=' '.join(estat.plugboard))

    machine.set_display(''.join(estat.display))

    if command == 'bksp':
        if not len(estat.input):
            return
        estat.input = estat.input[:-1]
    else:
        estat.input += letter

    inp = ''.join([l if (n + 1) % 5 else l + ' ' for n, l in enumerate(estat.input)])
    out = ''.join([l if (n + 1) % 5 else l + ' ' for n, l in enumerate(machine.process_text(estat.input))])

    display = list(machine.get_display())
    if len(display) < 4 and estat.rotors == 4:
        display.insert(0, estat.display[0])
    display = ' '.join(display)

    m = MSG.enigma.format(display=display,
                          input=inp,
                          output=out,
                          reflector=estat.reflector,
                          rotors=' '.join(estat.rotors_list),
                          rings=' '.join(estat.rings_list),
                          plugboard=' '.join(estat.plugboard) if len(estat.plugboard) else MSG.plugboard_empty,
                          idisplay=' '.join(estat.display))

    await EditMessageText(chat_id=context2.update.callback_query.message.chat.chat_id,
                          message_id=context2.update.callback_query.message.message_id, text=m,
                          reply_markup=enigma_kb(estat_id)).send()
コード例 #32
0
from enigma.machine import EnigmaMachine

machine = EnigmaMachine.from_key_sheet(
    rotors='II V I',
    reflector='B',
    ring_settings='07 19 02',
    plugboard_settings='HR NC IU DM TW GV FB ZL EQ OX')

init_rot_pos = 'EHC'
machine.set_display(init_rot_pos)
enc_key = machine.process_text('CTF')
print("Initial Rotor Positions: %s" % init_rot_pos)
print("Three letter message key: %s" % enc_key)

secret_key = 'CTF'
machine.set_display(secret_key)
print("Secret Key: %s" % secret_key)

#user_input = input("Please enter string to be encoded: ")
#user_input ='AGLARRUZRQGCLHVATCAKXHBLIPFWMRCGHNCYCVUNCSJWAPSNUKBRODCFVBYHKAQ'
user_input = 'Riddle me this what is always on its way here but never arrives'
enc = machine.process_text(user_input)

print("Original Message: %s" % user_input)
print("Encoded text: %s" % enc)
コード例 #33
0
#!/bin/env python3

from string import ascii_uppercase as UC
from random import SystemRandom
from enigma.machine import EnigmaMachine
from secretstuff import FLAG, PLUGBOARD_SETTINGS

assert FLAG.isupper() # Without pbcft{...}
random = SystemRandom()

for _ in range(50):
    ROTORS = [random.choice(("I","II","III","IV","V","VI","VII","VIII")) for _ in range(3)]
    REFLECTOR = random.choice(("B", "C", "B-Thin", "C-Thin"))
    RING_SETTINGS = [random.randrange(26) for _ in range(3)]

    machine = EnigmaMachine.from_key_sheet(
           rotors=ROTORS,
           reflector=REFLECTOR,
           ring_settings=RING_SETTINGS,
           plugboard_settings=PLUGBOARD_SETTINGS)

    machine.set_display(''.join(random.sample(UC, 3)))

    ciphertext = machine.process_text(FLAG)

    print(ciphertext)