Reputation: 55
I have to code the enigma algorithm used by Nazi-Germany to encrypt messages sent over radio, you can read how it works right here
As of right now i am only coding the rotors, i didn't code the Plugboard or the rotor initial position yet, since i seem to have problems with this already.
This is what i wrote:
for (int i=0; i<strlen(sentence);i++){
sentence[i]=toupper(sentence[i]);
temp=rs1[0];
for(int s=0;s<26-1;s++)
{
rs1[s]=rs1[s+1];
}
rs1[26-1]=temp;
j++;
if (j==26){
j=0;
temp=rs2[0];
for(int s=0;s<26-1;s++)
{
rs2[s]=rs2[s+1];
}
rs2[26-1]=temp;
z++;
}
if (z==26){
z=0;
temp=rs2[0];
for(int s=0;s<26-1;s++)
{
rs2[s]=rs2[s+1];
}
rs2[26-1]=temp;
}
q=(sentence[i]-65);
//this cant decrypt
sentence[i]=encrypt(sentence[i],rs1);
//printf("%s\n",sentence);
sentence[i]=encrypt(sentence[i],rs2);
//printf("%s\n",sentence);
sentence[i]=encrypt(sentence[i],rs3);
//printf("%s\n",sentence);
sentence[i]=reflect(sentence[i]);
//printf("%s\n",sentence);
sentence[i]=encrypt(sentence[i],rs3);
//printf("%s\n",sentence);
sentence[i]=encrypt(sentence[i],rs2);
//printf("%s\n",sentence);
sentence[i]=encrypt(sentence[i],rs1);
//printf("%s\n",sentence);
}
the functions are:
char encrypt(char c, char r[]){
int num=(int)c-65;
char newc;
newc=r[num];
return newc;
}
char relfect(char c){
char reflector[27]={'A','Q','W','S','E','D','R','F','T','G','Y','H','U','J','O','K','I','L','P','Z','V','C','X','B','N','M'};
int num=(int)c-65;
char newc;
newc=reflector[num];
return newc;
}
When I compile and execute my code I manage to encrypt the word i input, but when I reset the program and insert the encrypted word it doesnt decrypt it, which seems odd.
EXAMPLE: If I input Hello I get QOBAJ but in I restart the program and enter QOBAJ I get MWCJC instead of Hello and i can't figure out why.
The rotors i use are:
1- EKMFLGDQVZNTOWYHXUSPAIBRCJ
2- AJDKSIRUXBLHWTMCQGZNPYFVOE
3- BDFHJLCPRTXVZNYEIWGAKMUSQO
Thank you for helping me.
Lorenzo.
Upvotes: 3
Views: 241
Reputation: 5095
First of all, I don't see where you initialize the variables j
or z
and you never use the variable q
after assigning a value to it. Assuming that you do initialize everything, that you don't need the variable q
and that your code is otherwise correct then the problem is here:
if (z==26){
z=0;
temp=rs2[0];
for(int s=0;s<26-1;s++)
{
rs2[s]=rs2[s+1];
}
rs2[26-1]=temp;
}
In this block of code you should be working with rs3
not rs2
. It looks like you did a copy and paste but did not change all of the names.
EDIT:
You must reverse the lookup mechanism for decryption and you do not need a reflect
function. Replace
sentence[i]=reflect(sentence[i]);
with:
sentence[i]=encrypt(sentence[i],reflector);
The decrypt
function will look like this:
char decrypt(char c, char r[])
{
for ( int num = 0; num < 26; ++num )
{
if ( r[num] == c )
{
return((char)(65 + num));
}
}
return(c); // Should never get here
}
Then to perform decryption, call decrypt
instead of encrypt
.
Upvotes: 3