C++ Encrypting a File\'s Data (You may only use the headers #include<algorithm>
ID: 3889851 • Letter: C
Question
C++ Encrypting a File's Data (You may only use the headers #include<algorithm> #include<fstream> and #include<string>)
4) Required function: void encrypt_file(const std::string& filename, const std:string& password) You realized that someone else might see through your idea to "unzip" a file and determine it is not secure enough to transmit these files, so you thought encryption might be a better way to secure your pictures. To do some basic encryption, you have decided to take a password as an encryption key and then repeatedly XOR the file data with the password and write out this data as a new file. To accomplish this, we have to understand first how XOR works. The bitwise operation in C++ is computed using the A operator works on all primitive types. The XOR operation behaves as follows: Table 1: Truth table for XOR (source: http://www.cplusplus.com/doc/boolean/) aba b 011 00 1 !) A "bitwise" operator takes two variables and evaluates a logical operator on respective bits of the variables. Consider the following code:Explanation / Answer
#include <iostream>
#include <fstream>
using namespace std;
void encrypt_file(const std::string& filename, const std::string password){
streampos size;
char * memblock;
string in;
string out;
in = filename;
out = filename + "-encrypted";
ifstream file (in.c_str(), ios::in|ios::binary);
ofstream ofile (out.c_str(), ios::out|ios::binary);
if (file)
{
file.seekg (0, ios::end);
size = file.tellg();
memblock = new char [size];
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
int j = 0;
for (int i = 0; i<size; i = i++){
memblock[i] = memblock[i] ^ password[j];
j = (j + 1) % password.size();
}
for (int i = 0; i<size; i = i++){
ofile.write(&memblock[i],1);
}
ofile.close();
delete[] memblock;
}
}
int main () {
string filename;
cout << "Enter file name :" << endl;
cin >> filename;
encrypt_file(filename, "cse250cse250cse2");
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.