Spaces:
Runtime error
Runtime error
Create engima_machine.py
Browse files- engima_machine.py +56 -0
engima_machine.py
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# CREDIT: generated by GPT-4
|
2 |
+
import string
|
3 |
+
|
4 |
+
class EnigmaMachine:
|
5 |
+
def __init__(self, rotor_settings):
|
6 |
+
self.alphabet = string.ascii_uppercase
|
7 |
+
self.rotors = [list(self.alphabet) for _ in range(3)] # Create 3 rotors
|
8 |
+
self.reflector = list(self.alphabet) # Create reflector
|
9 |
+
|
10 |
+
# Initialize rotors based on the given rotor settings
|
11 |
+
for i, setting in enumerate(rotor_settings):
|
12 |
+
self.rotate_rotor(i, setting)
|
13 |
+
|
14 |
+
def rotate_rotor(self, rotor_index, positions):
|
15 |
+
# Rotate the specified rotor by the given number of positions
|
16 |
+
self.rotors[rotor_index] = self.rotors[rotor_index][positions:] + self.rotors[rotor_index][:positions]
|
17 |
+
|
18 |
+
def encode_character(self, char):
|
19 |
+
# For simplicity, this method only encodes a character (not full encoding process)
|
20 |
+
index = self.alphabet.index(char)
|
21 |
+
|
22 |
+
# Pass through rotors
|
23 |
+
for rotor in self.rotors:
|
24 |
+
index = self.alphabet.index(rotor[index])
|
25 |
+
|
26 |
+
# Pass through reflector
|
27 |
+
reflected = self.reflector[index]
|
28 |
+
|
29 |
+
# Inverse pass through rotors
|
30 |
+
# for rotor in reversed(self.rotors):
|
31 |
+
# index = rotor.index(reflected)
|
32 |
+
# reflected = self.alphabet[index]
|
33 |
+
|
34 |
+
return reflected
|
35 |
+
|
36 |
+
def encode_message(self, message):
|
37 |
+
encoded = ''
|
38 |
+
for char in message:
|
39 |
+
if char.upper() in self.alphabet:
|
40 |
+
# Rotate the first rotor by 1 for each character
|
41 |
+
self.rotate_rotor(0, 1)
|
42 |
+
encoded += self.encode_character(char.upper())
|
43 |
+
else:
|
44 |
+
encoded += char # For non-alphabetic characters, we keep the original
|
45 |
+
|
46 |
+
return encoded
|
47 |
+
|
48 |
+
# Using the enigma machine to encode a message
|
49 |
+
rotor_settings = [0, 0, 0] # Starting positions for the rotors
|
50 |
+
enigma = EnigmaMachine(rotor_settings)
|
51 |
+
|
52 |
+
original_message = "HELLO"
|
53 |
+
encoded_message = enigma.encode_message(original_message)
|
54 |
+
|
55 |
+
# print(f"Original: {original_message}")
|
56 |
+
# print(f"Encoded: {encoded_message}")
|