Repository navigation
Expand file tree
/
Copy pathEncrypt.cpp
More file actions
82 lines (76 loc) · 2.09 KB
/
Copy pathEncrypt.cpp
File metadata and controls
82 lines (76 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class FileEncryptor {
private:
string filename;
int encryptionKey;
char encryptChar(char c){
if(isalpha(c)){
char base = islower(c) ? 'a' : 'A';
return (c - base + encryptionKey) % 26 + base;
}
return c;
}
char decryptChar(char c) {
if (isalpha(c)) {
char base = islower(c) ? 'a' : 'A';
return (c - base - encryptionKey + 26) % 26 + base;
}
return c;
}
public:
FileEncryptor(string fname, int key) : filename(fname), encryptionKey(key) {}
void encryptAndWrite(string message) {
ofstream file(filename);
if (!file.is_open()) {
cerr << "Error opening file for writing.\n";
return;
}
for (char c : message) {
file << encryptChar(c);
}
file.close();
cout << "Message successfully encrypted and stored in " << filename << "\n";
}
string readAndDecrypt() {
ifstream file(filename);
if (!file.is_open()) {
cerr << "Error opening file for reading.\n";
return "";
}
string decryptedMessage = "";
char c;
while (file.get(c)) {
decryptedMessage += decryptChar(c);
}
file.close();
return decryptedMessage;
}
void displayFileContents() {
string message = readAndDecrypt();
cout << "Decrypted Message: " << message << "\n";
}
};
int main() {
FileEncryptor fe("data.txt", 3);
int choice;
string message;
cout << "1. Encrypt and Write Message\n";
cout << "2. Read and Decrypt Message\n";
cout << "Enter your choice: ";
cin >> choice;
cin.ignore();
if (choice == 1) {
cout << "Enter a message to encrypt: ";
getline(cin, message);
fe.encryptAndWrite(message);
} else if (choice == 2) {
cout << "\nReading and decrypting file...\n";
fe.displayFileContents();
} else {
cout << "Invalid choice.\n";
}
return 0;
}