Encrypting and decrypting

What does the c++ code look like for trying to use a plain.txt and a key.txt file to do encryption and decryption? When I look at this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 string original = "super flying monkeys are aweseome, aren't they?";
 cout << "Original data = " << original;
 string encrypted = "";
 string unencrypt = "";
 char key = 'x';

 for (int temp = 0; temp < original.size(); temp++){
  encrypted += original[temp] ^ (int(key) + temp) % 255;
 }
 cout << "nEncrypted data = " << encrypted;

 for (int temp = 0; temp < original.size(); temp++){
  unencrypted += encrypted[temp] ^ (int(key) + temp) % 255;
 }
 cout << "nUnencrypted data = " << unencrypt;


It just takes the string.. simple enough. The book I bought from the book store doesn't really show any examples of taking words from a file, using another file , and then encrypting it into a third file.
Here is a fairly simple sample of reading data:

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
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
  // Create an input file stream named input
  ifstream input;

  // Open a file
  input.open("numbers.txt");

  int score1, score2, score3;

  // Read data
  input >> score1;
  input >> score2;
  input >> score3;

  cout << "Total score is " << score1 + score2 + score3 << endl;

  // Close file
  input.close();

  cout << "Done" << endl;
  return 0;
}


and here is one for file output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
  // Create an output file stream named output
  ofstream output;

  // Create a file
  output.open("numbers.txt");

  // Write numbers
  output << 95 << " " << 56 << " " << 34;

  // close file
  output.close();

  cout << "Done" << endl;
  return 0;
}


You will definitely want to check out the IOstream library here on the website to get more familiar with file input and output.
Last edited on
Topic archived. No new replies allowed.