-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP5-File-Encryption.cpp
More file actions
88 lines (76 loc) · 2.23 KB
/
P5-File-Encryption.cpp
File metadata and controls
88 lines (76 loc) · 2.23 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
83
84
85
86
87
88
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void encryptFile(const string &filename, int key) {
ifstream inputFile(filename, ios::binary);
if (!inputFile) {
cout << "Error: Unable to open file!\n";
return;
}
string encryptedFilename = filename + ".enc";
ofstream outputFile(encryptedFilename, ios::binary);
if (!outputFile) {
cout << "Error: Unable to create encrypted file!\n";
return;
}
char ch;
while (inputFile.get(ch)) {
ch = ch ^ key;
outputFile.put(ch);
}
inputFile.close();
outputFile.close();
cout << "File encrypted successfully! Saved as " << encryptedFilename << endl;
}
void decryptFile(const string &filename, int key) {
ifstream inputFile(filename, ios::binary);
if (!inputFile) {
cout << "Error: Unable to open file!\n";
return;
}
string decryptedFilename = "decrypted_" + filename;
ofstream outputFile(decryptedFilename, ios::binary);
if (!outputFile) {
cout << "Error: Unable to create decrypted file!\n";
return;
}
char ch;
while (inputFile.get(ch)) {
ch = ch ^ key;
outputFile.put(ch);
}
inputFile.close();
outputFile.close();
cout << "File decrypted successfully! Saved as " << decryptedFilename << endl;
}
int main() {
int choice;
string filename;
int key;
while (true) {
cout << "\n1. Encrypt File\n2. Decrypt File\n3. Exit\n";
cout << "Enter choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter file name to encrypt: ";
cin >> filename;
cout << "Enter encryption key (numeric): ";
cin >> key;
encryptFile(filename, key);
break;
case 2:
cout << "Enter file name to decrypt: ";
cin >> filename;
cout << "Enter decryption key (same as encryption key): ";
cin >> key;
decryptFile(filename, key);
break;
case 3:
return 0;
default:
cout << "Invalid choice! Try again.\n";
}
}
}