A class encdec is defined with two member functions: encrypt() and decrypt().
The name of the file to be encrypted is the member variable of the class.
encrypt() function is used to handle the encryption of the input file.
The file handling code is included in the encrypt() function to read the file and
write to the file. A new encrypted file called encrypt.txt is generated with all
the encrypted data in it. The encrypted file is encrypted using a key that is being
inputted by the user.
decrypt() function is used to read the encrypted file and decrypt the data and
generate a new file decrypt.txt. To decrypt a file, a key is requested from the user.
If the correct key is entered, then the file is successfully decrypted.
#include<bits/stdc++.h>
#include <fstream>
using namespace std;
// encdec class with encrypt() and
// decrypt() member functions
class encdec {
int key;
// File name to be encrypt
string file = "geeksforgeeks.txt";
char c;
public:
void encrypt();
void decrypt();
};
// Definition of encryption function
void encdec::encrypt()
{
// Key to be used for encryption
cout << "key: ";
cin >> key;
// Input stream
fstream fin, fout;
// Open input file
// ios::binary- reading file
// character by character
fin.open(file, fstream::in);
fout.open("encrypt.txt", fstream::out);
// Reading original file till
// end of file
while (fin >> noskipws >> c) {
int temp = (c + key);
// Write temp as char in
// output file
fout << (char)temp;
}
// Closing both files
fin.close();
fout.close();
}
// Definition of decryption function
void encdec::decrypt()
{
cout << "key: ";
cin >> key;
fstream fin;
fstream fout;
fin.open("encrypt.txt", fstream::in);
fout.open("decrypt.txt", fstream::out);
while (fin >> noskipws >> c) {
// Remove the key from the
// character
int temp = (c - key);
fout << (char)temp;
}
fin.close();
fout.close();
}
int main()
{
encdec enc;
char c;
cout << "\n";
cout << "Enter Your Choice : -> \n";
cout << "1. encrypt \n";
cout << "2. decrypt \n";
cin >> c;
cin.ignore();
switch (c) {
case '1': {
enc.encrypt();
break;
}
case '2': {
enc.decrypt();
break;
}
}
}