In: Computer Science
Background:
You can create a simple form of encryption using
the xor Boolean operator. For example, if you want
to encrypt the letter 'A':
Your
task:
Write a C++ program that meets the following requirements:
Submit:
Documentation should include:
// C++ program to implement XOR encryption and decryption
#include <iostream>
#include <fstream>
#include <cctype>
using namespace std;
string encrypt(string line, char key);
string decrypt(string line, char key);
int main() {
char key;
string filename;
ifstream fin;
cout<<"Enter the filename : ";
getline(cin,filename); // provide full path to file
filename = filename.substr(0,filename.length()-1);
cout<<"Enter the key character : ";
cin>>key;
fin.open(filename.c_str());
if(fin.is_open())
{
string outFile = filename.substr(0,filename.find('.'))+".xor";
ofstream fout(outFile.c_str());
string line;
char option;
while(!fin.eof())
{
getline(fin,line);
fout<<encrypt(line,key);
}
fin.close();
fout.close();
cout<<"Do you want to decrypt the file (y/n) ? ";
cin>>option;
if(tolower(option) == 'y')
{
cout<<"Decrypted file : "<<endl;
fin.open(outFile.c_str());
if(fin.is_open())
{
while(!fin.eof())
{
getline(fin,line);
cout<<decrypt(line,key);
}
}
fin.close();
}
}else
cout<<"Unable to open file : "<<filename<<endl;
return 0;
}
// function to encrypt a line using XOR
// Pre-condition : line is not null and key is not empty
// Post-condition : line and key is unchanged
// Returns : string which is obtained by XOR encryption of the standard alphanumeric characters and key
string encrypt(string line, char key)
{
string encryptedLine="";
for(size_t i=0;i<line.length();i++)
{
encryptedLine += line.at(i)^key;
}
return encryptedLine;
}
// function to decrypt a line using XOR
// Pre-condition : line is not null and key is not empty
// Post-condition : line and key is unchanged
// Returns : string which is obtained by XOR decryption of the standard alphanumeric characters and key
string decrypt(string line, char key)
{
string decryptedLine="";
for(size_t i=0;i<line.length();i++)
{
decryptedLine += (line.at(i)^key);
}
return decryptedLine;
}
//end of program
Output:
Input file:
Output file:
Console: