The following program attempts to encrypt a string and save in to a text file, and open the file, decrypt and show the message.
Here is the code-
private: System::Void saveToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) {
SaveFileDialog^ dlg = gcnew SaveFileDialog();
dlg->Filter = "Text Files|*.txt";
char key = 'a';
if(dlg->ShowDialog()==Windows::Forms::DialogResult::OK)
{
String^ stream = txtOutput->Text;
char* num = new char[stream->Length];
char* xorchar = (char*)(void*)Marshal::StringToHGlobalAnsi(stream);
int i=0;
for(i=0;i<stream->Length;++i){
num[i] = *xorchar ^ key;
*xorchar++;
}
num[i] = '\0'; //add trailing NULL
//Marshal::FreeHGlobal((System::IntPtr)(void*)xorchar); THIS WAS GIVING AN ERROR, NOT SURE WHY
String^ save = gcnew String(num);
System::IO::File::WriteAllText(dlg->FileName, save);
}
}
private: System::Void openToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) {
OpenFileDialog^ dlg = gcnew OpenFileDialog();
dlg->Filter = "Text Files|*.txt";
String^ stream;
char key = 'a';
if(dlg->ShowDialog()==Windows::Forms::DialogResult::OK)
{
stream = System::IO::File::ReadAllText(dlg->FileName);
char* num = (char*)(void*)Marshal::StringToHGlobalAnsi(stream);
int i=0;
for (i=0;i<stream->Length;++i)
{
num[i] = num[i] ^ key; //DECRYPT
}
String^ orig_stream = gcnew String(num);
txtOutput->Text = orig_stream;
}
}
Now the issue is, when i input a string, it works only for characters which are not equal to the key.
Example, Let key = ‘a’
eg: INPUT: “I Like This” // This will decrypt correctly.
INPUT: “I Like apples” //Only upto ‘I Like’ will decrypt, rest doesnt show up.
ie, If it encounters the character ‘key’ (in this case ‘a’), it stops decryption.
Any help is appreciated. Thanks!
A value xor’d with itself will always produce 0. A 0
charis also called the null-terminator (0 == '\0'). Strings in C++ are null-terminated, aka they stop at the null-terminator.Simple example: