sam thornton sam thornton - 1 year ago 78
C++ Question

C++ : Mini Project on Cryptography

I need to encrypt and decrypt files using C++ with XOR Encryption. I need to know where I can make a GUI for it.

Is there a way to do this (possibly through C++ alone) ?

Answer Source

There is a quite simple answer to how to encrypt files. This script uses the XOR encryption to encrypt files. Encrypt the file a second time to decrypt it.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

void encrypt (string &key,string &data){
float percent;
for (int i = 0;i < data.size();i++){
percent = (100*i)/key.size();              //progress of encryption
data[i] = data.c_str()[i]^key[i%key.size()];
if (percent < 100){                        
    cout << percent << "%\r";              //outputs percent, \r makes
}else{                                     //cout to overwrite the
    cout<< "100%\r";                       //last line.

int main()
string data;
string key = "This_is_the_key";
ifstream in ("File",ios::binary); // this input stream opens the 
                                  // the file and ...
data.reserve (1000);
in >> data;                       // ... reads the data in it.
ofstream out("File",ios::binary);//opens the output stream and ...
out << data;                     //... writes encrypted data to file.

return 0;

This line of code is where the encryption happens:

data[i] = data.c_str()[i]^key[i%key.size()];

it encrypts each byte individually. Each byte is encrypted with a char that changes during the encryption because of this:


But there are a lot of encryption methods, for example you could add 1 to each byte(encryption) and subtract 1 from each byte(decryption):

for (int i = 0;i < data.size();i++){
    data[i] = data.c_str()[i]+1;
for (int i = 0;i < data.size();i++){
    data[i] = data.c_str()[i]-1;

I think the it's not very useful to show the progress because it is to fast.

If you really want to make a GUI I would recommend Visual Studio.

Hope that was helpful.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download