Reputation: 83
I have a simple application which takes a text and password, generates a text writes it in a file then tries to retrieve it and decrypt it. Before the encryption the 'pad' is generated which is a string generated from the password with the length of the text. The problem comes in when I try to retrieve the text, because no matter how I try I keep retrieving wrong text because it does not match the length of the password.
cout << " !!! DEBUG ONLY. CHANGE MAIN CODE BEFORE RELEASE !!!\n";
string text, password, file;
cout << "Please enter the text you would like encrypted: ";
getline(cin, text);
cout << "Please enter the password for creating the cipher: ";
getline(cin, password);
cout << "Please enter the file path: ";
getline(cin, file);
password = GeneratePad(password, text.size());
string separator = "30436f4a57e831406e8c0ef203923fe3ba9d0ac4TB5Mi4b33A";
ofstream mann(file.c_str(), ios::app);
mann << "\n" << separator << CryptText(text, password);
mann.close();
cout << " !!! DEBUG ONLY. CHANGE MAIN CODE BEFORE RELEASE !!!\n";
ifstream frau(file.c_str(), ios::binary);
string foobar;
bool barfoo = false;
string decrypted;
while (!barfoo)
{
getline(frau, foobar);
if(foobar.find(separator) != string::npos){
decrypted += foobar.substr(separator.length() + 1);
cout << "SUBSTR " << foobar.substr(separator.length() + 1);
barfoo = true; } }
while (getline(frau, foobar))
{
decrypted += foobar;
}
string decrypted2;
cout << " LEN " << decrypted.length() << " !!!!! " << decrypted << endl;
decrypted2 = CryptText(decrypted, password);
cout << decrypted2 << endl;
system("PAUSE");
The things that appear not to be necesarry are purely for debugging (like outputting the raw encrypted text, etc.). Any ideas as to why this happens ?
Upvotes: 1
Views: 130
Reputation: 7939
Problem 1: you open the output file in text mode, but the read it back in binary mode.
std::ofstream mann(file.c_str(), std::ios::app|std::ios::binary);
Problem 2: your encrypted data is probably not ASCII text any more. It may contain special characters like '\n' or ^Z or even embedded '\0' characters. You should use unformatted i/o like read() and write() instead of getline() and <<.
Additional comments:
Don't use system("PAUSE");. It is poor style and makes the program unnecessarily system dependent. Just use regular C++ i/o to write a pause message and wait for a return to be pressed.
std::cout << "Press return to continue" << std::endl;
std::getline();
I recommend not having "using namespace std", but just using the std:: qualifier when needed. It keeps things a little cleaner.
Upvotes: 2
Reputation: 83
I made the following 2 edits:
ofstream mann(file.c_str(), ios::app|ios::binary);
while (getline(frau, foobar))
{
decrypted += foobar;
decrypted += "\n";
}
When I opened the file for reading I also added ios::binary and when I was adding to the decrypted string I added the "\n" which was being removed by the 'getline'. It works perfectly now.
Upvotes: 0