I'm trying to create a very simple enigma machine cipher. But mine doesn't decrypt the data correcly.
#include <iostream>
#include <string>
using namespace std;
const char alphabet[27] = { "ABCDEFGHIJKLMNOPQRSTUVWXYZ" };
const char reflector[27] = { "WSXRFVYHNIKPQAZEDCTGBUJMOL" };
const char rotors[27] = { "QWERTYUIOPASDFGHJKLZXCVBNM" };
/* Get the position of a character in the alphabet. */
int GetPos(char _char)
{
return int(_char) - int('A');
}
void Encrypt(char *message, char *returnMessage, size_t size)
{
char set1;
char set1_r;
char reflect;
char letter;
int position;
for (int i = 0; i < size; i++)
{
letter = message[i];
// Pass the character through the rotors.
position = GetPos(letter);
set1 = rotors[position];
// Pass the character through the reflector.
position = GetPos(set1);
reflect = reflector[position];
// Pass the character through the rotors in reverse.
position = GetPos(reflect);
set1_r = rotors[position];
returnMessage[i] = set1_r;
}
}
void Decrypt(char *message, char *returnMessage, size_t size)
{
char set1;
char set1_r;
char reflect;
char letter;
int position;
for (int i = 0; i < size; i++)
{
letter = message[i];
// Pass the character through the rotors in reverse.
position = GetPos(letter);
set1 = rotors[position];
// Pass the character through the reflector.
position = GetPos(set1);
reflect = reflector[position];
// Pass the character through the rotors in reverse.
position = GetPos(reflect);
set1_r = rotors[position];
returnMessage[i] = set1_r;
char p = alphabet[position];
returnMessage[i] = p;
}
}
int main(int argc, char *argv[])
{
char *message = "H";
size_t size = strlen(message);
char *retMessage = new char[size];
char *retMessage2 = new char[size];
if ((retMessage == nullptr) || (retMessage2 == nullptr))
{
cout << "Error allocating memory." << endl;
return -1;
}
cout << "Original message: " << message << endl;
Encrypt(message, retMessage, size);
cout << "Encrypted message: ";
for (int i = 0; i < size; i++)
cout << retMessage[i];
cout << endl;
Decrypt(retMessage, retMessage2, size);
cout << "Decrypted message: ";
for (int i = 0; i < size; i++)
cout << retMessage2[i];
delete[] retMessage;
delete[] retMessage2;
cin.get();
return 0;
}
As you can see it takes the letter H
. It then encrypts the letter, and I get F
, when I decrypt F
then I get O
. Clearly there is something wrong with my decryption stage or my encryption, but I suspect it is the decryption that is faulty.
What is wrong and how do I fix it?