I need to do XOR file encryption (in any format), for this I must read from the file one by one group of bytes, encrypt them, and then write the result to the output file.
How can I organize reading and writing bytes?
I need to do XOR file encryption (in any format), for this I must read from the file one by one group of bytes, encrypt them, and then write the result to the output file.
How can I organize reading and writing bytes?
You could read one by one but i recommend read and write block of byte. Performance wise is much better accessing the file as little as needed, it's and slow operation. According to the memory constrain you could increase the block size of the second sample code (actual 1024, to the number of byte you want).
Sample code, one-by-one encryption:
#include <iostream>
#include <fstream>
#include <vector>
int main(int argc, char* argv[]) {
char bytes;
std::ifstream ifs("ficheroentrada", std::ios_base::binary);
std::ofstream ofs("ficherosalida", std::ios_base::binary);
while (!ifs.eof()) {
ifs.get(bytes);
bytes ^= 0xAA; // xor constant or variable
ofs.put(bytes);
}
ifs.close();
ofs.close();
return 0;
}
Code for Block encryption using XOR (This one is more recommended)
#include <iostream>
#include <fstream>
#include <vector>
int main(int argc, char* argv[]) {
std::vector<char> bytes(1024); // change the block size
std::ifstream ifs("e:\\save_out.txt", std::ios_base::binary);
std::ofstream ofs("e:\\save_out2.txt", std::ios_base::binary);
while (!ifs.eof()) {
ifs.read((char*)&bytes[0], bytes.size());
unsigned int size_read = ifs.gcount();
for (unsigned int idx = 0; idx < size_read; idx++) {
bytes[idx] ^= 0xAA; // xor constant or variable
}
ofs.write((char*)&bytes[0], size_read);
}
ifs.close();
ofs.close();
return 0;
}