Reputation: 45
I wrote some code for my cryptography class and it runs on sagemath.com terminal but not in visual studio 2013. I'm not sure what's giving me the error though. I'm thinking it has to do with the for
loops but I can't figure out what to change.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream plain1("plaintext1.txt");
ifstream cipher("ciphertext1.bin");
string line, cipherLine, key;
if(plain1.is_open() && cipher.is_open())
{
getline(plain1, line);
getline(cipher, cipherLine);
for (unsigned int x = 0; x < line.length(); x++)
{
key[x] = line[x] ^ cipherLine[x];
}
}
plain1.close();
cipher.close();
ifstream cipher2("ciphertext2.bin");
ofstream plain2("plaintext2.txt");
string line2, decrypt;
if (cipher2.is_open())
{
getline(cipher2, line2);
for (unsigned int y = 0; y < line.length(); y++)
{
decrypt[y] = key[y] ^ line2[y];
plain2 << decrypt[y];
}
}
cout << "File decrypted successfully." << endl;
cipher2.close();
plain2.close();
system("pause");
return 0;
}
Upvotes: 0
Views: 618
Reputation: 2520
operator[] doesn't add to the string length.
key[x] =
will invoke undefined behaviour, which in this case is the out of range error. What you want is append or +=.
You are also assuming (which may or may not be reasonable) that the line and cipherLine will be the same length. You should be checking this anyway.
And your second loop is getting line2
, but incrementing up to line.length()
. It should be line2.length()
Upvotes: 0
Reputation: 72044
Your code assumes that lines in the plaintext and cipher files are the same length. Especially considering that the cipher is binary, not text (judging from its .bin extension), that's not a good assumption to make. If the cipher "line" is shorter than the plaintext line, you will get the error.
In addition, the key is always zero-length, so every single write to it is out-of-bounds. You need to either use push_back
or resize the string first.
Upvotes: 1