I'm trying to implement simple symmetric key cryptography algorithm. In which provided a key and message stream it just XORs the character of key and message one by one and encrypts them and similarly for decryption.
In my code while reading the file, after the all characters are read from the file provided as input an extra last character is read (this is before EOF as I've used while(fp) //fp is the file stream to detect EOF) which gets XOR with the key element.
Because of this when I decrypt using the same logic the extra character again gets XOR and gives me a junk character at the end of the message.
How do I remove this last character from getting XORed?
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main()
{
int opt;
string key="asdfghjklpo"; //Key for encryption/decryption
cout<<"Enter your option"<<endl;
cout<<"1. Encrypt\n2. Decrypt"<<endl;
cin>>opt;
cin.ignore(); //To flush the '\n' fron the stream
char ch;
switch(opt)
{
case 1:
{
cout<<"Enter the file name containing message stream : ";
string ifn,ofn;
getline(cin,ifn);
ofn=ifn;
ofn.append("_enc"); //new file name with _enc at the end
fstream msg,op;
msg.open(ifn.c_str(),ios::in); //converting string to (char *) using c_str()
op.open(ofn.c_str(),ios::out); //converting string to (char *) using c_str()
int i=0;
while(msg)
{
msg.get(ch);
ch=char(int(ch)^int(key[i])); //key XOR message
op.put(ch);
i=(++i)%key.size(); //The key rotates if message is greater than
//key size
}
msg.close();
op.close();
break;
}
case 2:
{
string k;
cout<<"Enter the key"<<endl;
getline(cin,k);
if(!key.compare(k)) //Key Authentication
{
cout<<"Enter the file name containing encrypted message stream : ";
string ifn,ofn;
getline(cin,ifn);
ofn=ifn;
ofn.append("_dec"); //new file name with _dec at the end
fstream msg,op;
msg.open(ifn.c_str(),ios::in); //converting string to (char *) using c_str()
op.open(ofn.c_str(),ios::out); //converting string to (char *) using c_str()
int i=0;
while(msg)
{
msg.get(ch);
ch=char(int(ch)^int(key[i])); //encrypted_message XOR key
op.put(ch);
i=(i+1)%key.size(); //The key rotates if message is greater than
//key size
}
msg.close();
op.close();
}
else
cout<<endl<<"Entered key not valid........."<<endl;
break;
}
}
}
I tried to debug the code and found that the extra character was \b (ASCII 8) on the encryption side, so i tried for an if condition to check the same but even then it didn't work.