-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
145 lines (106 loc) · 2.51 KB
/
main.cpp
File metadata and controls
145 lines (106 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#include <iostream>
#ifdef _DEBUG
#define printdbg(fmt, x) printf(fmt, x)
#else
#define printdbg(fmt, ...)
#endif
struct rotor {
rotor(char* x)
{
memcpy(data, x, 26);
}
char shift(char x)
{
return data[(x - 'a' + position) % 26];
}
char reverse(char x)
{
for (int i = 0; i < 26; i++) {
if (data[i] == x) {
return 'a' + i;
}
}
return 0;
}
char data[26];
unsigned char position = 0;
};
class enigma {
public:
rotor *rotors[3];
struct pair {
char swap(char x) {
if (x == A) {
return B;
}
else if (x == B) {
return A;
}
return -1;
}
char A = 0;
char B = 0;
};
pair plugboard[10];
pair reflector[13] = { {'a', 'e'},{'b', 'j'},{'c', 'm'},{'d', 'z'},{'f', 'l'},{'g', 'y'},{'h', 'x'},{'i', 'v'},{'k', 'w'},{'n','r'},{'o','q'},{'p','u'},{'s','t'} };
char type(char in)
{
in = tolower(in);
printdbg("input: %c\n", in);
/* Go through the plugboard once*/
for (pair x : plugboard) {
if (x.A == in || x.B == in)
in = x.swap(in);
}
printdbg("plug out: %c\n", in);
/* Go through the rotors */
in = rotors[2]->shift(
rotors[1]->shift(
rotors[0]->shift(in)));
printdbg("rotors: %c\n", in);
/* Get reflected*/
for (pair x : reflector) {
if(x.A == in || x.B == in)
in = x.swap(in);
}
printdbg("reflected: %c\n", in);
/* Undo what the rotors did*/
in = rotors[0]->reverse(rotors[1]->reverse(rotors[2]->reverse(in)));
printdbg("rotor out: %c\n", in);
for (pair x : plugboard) {
if (x.A == in || x.B == in)
in = x.swap(in);
}
printdbg("result: %c\n", in);
/* increment the rotors */
update_rotor();
return in;
}
void update_rotor()
{
rotors[0]->position++;
if (rotors[0]->position > 25) {
rotors[0]->position = 0;
rotors[1]->position++;
if (rotors[1]->position > 25) {
rotors[1]->position = 0;
rotors[2]->position++;
rotors[2]->position %= 26;
}
}
printf("%i,%i,%i\n", rotors[0]->position, rotors[1]->position, rotors[2]->position);
}
};
int main()
{
char in = 'a';
rotor A((char*)"ekmflgdqvzntowyhxuspaibrcj");
rotor B((char*)"ajdksiruxblhwtmcqgznpyfvoe");
rotor C((char*)"ocresmintvhlaqwfgpykjuxdbz");
rotor D((char*)"wuervdktmjzpiqasfgybclnxho");
rotor E((char*)"fnagjucolirpxtmyevwsdhqbkz");
enigma enigma_machine;
enigma_machine.rotors[0] = &A;
enigma_machine.rotors[1] = &B;
enigma_machine.rotors[2] = &C;
}