Question: The following program in C + + is able to encrypt a file using the Vigen re cypher, and writes the file to encrypted.txt file,

The following program in C++ is able to encrypt a file using the Vigenre cypher, and writes the file to encrypted.txt file, but it is not able to decrypt the file again. Please modify the program so that it can decrypt the file back to the original as well as encrypt. This is due by tomorrow. Thanks!
Code:
#include
#include
#include
#include
using namespace std;
char encryptChar(char ch, char key){
if (isalpha(ch)){
bool isUpper = isupper(ch);
char base = isUpper ?'A' : 'a';
return base +(ch + key -2* base)%26;
}
else {
return ch;
}
}
char decryptChar(char ch, char key){
if (isalpha(ch)){
bool isUpper = isupper(ch);
char base = isUpper ?'A' : 'a';
return base +(ch - key +26- base)%26;
}
else {
return ch;
}
}
void processFile(string filename, string key, bool encrypt){
ifstream inFile(filename);
ofstream outFile(encrypt ? "encrypted.txt" : "decrypted.txt");
if (!inFile.is_open()||!outFile.is_open()){
cerr << "Error opening file." << endl;
return;
}
char ch;
int keyIndex =0;
while (inFile.get(ch)){
char encryptedChar = encrypt ? encryptChar(ch, key[keyIndex]) : decryptChar(ch, key[keyIndex]);
outFile << encryptedChar;
cout << encryptedChar;
keyIndex =(keyIndex +1)% key.length();
}
inFile.close();
outFile.close();
}
int main(){
string choice, key, filename;
while (true){
cout << "Encrypt or decrypt (e/d)?(q to quit): ";
cin >> choice;
if (choice =="e"){
cout << "Enter key: ";
cin >> key;
cout << "Enter plaintext filename: ";
cin >> filename;
processFile(filename, key, true);
}
else if (choice =="d"){
cout << "Enter key: ";
cin >> key;
cout << "Enter encrypted filename: ";
cin >> filename;
processFile(filename, key, false);
}
else if (choice =="q"){
break;
}
else {
cout << "Invalid choice." << endl;
}
}
return 0;
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!