1- // Encryption-Program.cpp : Defines the entry point for the application.
2- //
1+ // Date: 7/27/2024
2+ // By: 53142
33
44#include < iostream>
55#include < fstream>
6+ #include < string>
67
7- #include " Encryption-Program.h"
88
9- using namespace std ;
9+ // Function for encrypting the data
10+ void encrypt () {
11+ std::fstream file;
12+ std::string input = " " ;
13+ int key;
1014
1115
16+ std::cout << " Opening file..." << std::endl;
17+ file.open (" file.dat" , std::ios::in | std::ios::out | std::ios::binary | std::ios::trunc);
18+ if (!file.is_open ()) {
19+ std::cout << " Error opening the file!" << std::endl;
20+ throw new std::exception (" Error opening the file!" );
21+ }
22+
23+ std::cout << " What is the encryption key?" << std::endl;
24+ std::cin >> key;
25+
26+ std::cout << " What should the file contain?" << std::endl;
27+ std::cin >> input;
1228
13- void encrypt () {
14- fstream file;
15- string input = " " ;
1629
17- cout << " Opening file..." << endl;
18- file.open (" file.dat" , ios::in | ios::out | ios::binary | ios::trunc);
30+ for (int i = 0 ; i < input.length (); i++) {
31+ input[i] = input[i] + key;
32+ }
1933
20- cout << " What should the file contain?" << endl;
21- cin >> input;
2234
23- cout << " Writing file..." << endl;
24- cout << " input: " << input << endl;
25- file.write (new char [input.length () + 1 ], input.length ());
35+ std::cout << " Writing file..." << std::endl;
36+ file.write (input.c_str (), input.length ());
2637}
2738
2839
40+ // Function for decrypting the data
41+ void decrypt () {
42+ std::string input = " " ;
43+ int key;
44+
45+
46+ std::cout << " Opening file..." << std::endl;
47+
48+ std::fstream file (" file.dat" );
49+ if (!file.is_open ()) {
50+ std::cout << " Error opening the file!" << std::endl;
51+ throw new std::exception (" Error opening the file!" );
52+ }
2953
54+ std::cout << " What is the encryption key?" << std::endl;
55+ std::cin >> key;
56+
57+ file >> input;
58+
59+ for (int i = 0 ; i < input.length (); i++) {
60+ input[i] = input[i] - key;
61+ }
62+
63+ std::cout << " Decrypted: " << input << std::endl;
64+ }
65+
66+
67+ // Main function
3068int main () {
3169 int choice;
32- cout << " Press 1 to encrypt. Press 2 to decrypt." << endl;
33-
34- cin >> choice;
70+ std::cout << " Press 1 to encrypt. Press 2 to decrypt." << std::endl;
71+ std::cin >> choice;
3572
3673 switch (choice) {
3774 case 1 :
3875 encrypt ();
3976 break ;
4077 case 2 :
41- // decrypt();
78+ decrypt ();
4279 break ;
4380 default :
44- cout << " Invalid input. Please enter 1 or 2." << endl;
81+ std:: cout << " Invalid input. Please enter 1 or 2." << std:: endl;
4582 break ;
4683 }
4784 return 0 ;
48- }
85+ }
0 commit comments