Step 9The Code: Encryption
pos_rotor3 += 1;
if(pos_rotor3 > 25)
{
pos_rotor3 = 0;
}
if(pos_rotor3 == spin_r3)
{
pos_rotor2 += 1;
if(pos_rotor2 > 25)
{
pos_rotor2 = 0;
}
if(pos_rotor2 == spin_r2)
{
pos_rotor1 += 1;
if(pos_rotor1 > 25)
{
pos_rotor1 = 0;
}
}
}
This function is basically where all the magic happens. A value is input in addition to the rotor values and the offset the rotor is currently on. It ouputs the letter that would come out of that one rotor.
This is really not a lot more than a simple character subsitution. A real Enigma machine did this with wires inside a rotor. We do this multiple times, one for each rotor going forward, then we send it through the reflector, then back through the rotors.
int get_rotor_output(int index, char rot[], char rotIndex[], int pos_rot)
{
//first thing we need to do is add the rotor position to the index to figure
//out what letter we're really on
index += pos_rot;
//If the index is more than 25 then we've wrapped around the end of the array
//so we'll subtract 26 from it to get to the real character
if(index > 25)
{
index -= 26;
}
//now we figure out the index of the letter in the alphabet
// i.e. A = 0, B = 1, C = 2, etc.
//then we grab the letter in the same position in the rotor array
//this is how we do the character substitution
char tmp_letter = rot[find_index(rotIndex, alpha[index])];
//now we get the index of the letter that was ouput in the alphabet
//same idea as above A= 0, B =1., etc
index = find_index(alpha, tmp_letter);
//Now we subtract the rotor position from the index that was output
index -= pos_rot;
//if the index is less than 0, then we've wrapped off the beginning
//of the array, so we'll add 26 to it to get back in the array
if(index < 0)
{
index += 26;
}
//now let's return the index
return index;
}
Note: The image in this step is from Wikipedia
| « Previous Step | Download PDFView All Steps | Next Step » |
![]() |
Add Comment
|
















































