c++ - 从文件末尾检索字符串时失败

标签 c++ string file encryption

我有一个简单的应用程序,它接受一个文本和密码,生成一个文本并将其写入一个文件,然后尝试检索它并解密它。在加密之前生成“pad”,它是从密码生成的具有文本长度的字符串。当我尝试检索文本时,问题就出现了,因为无论我如何尝试,我总是检索到错误的文本,因为它与密码的长度不匹配。

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");

看似不必要的东西纯粹是为了调试(如输出原始加密文本等)。关于为什么会发生这种情况的任何想法?

最佳答案

问题 1:您以文本模式打开输出文件,但以二进制模式读回。

std::ofstream mann(file.c_str(), std::ios::app|std::ios::binary);

问题 2:您的加密数据可能不再是 ASCII 文本。它可能包含特殊字符,如 '\n' 或 ^Z 甚至嵌入的 '\0' 字符。你应该使用像 read() 和 write() 这样的未格式化的 i/o 而不是 getline() 和 <<。

补充说明:
不要使用系统(“暂停”);。这是一种糟糕的风格,使程序不必要地依赖于系统。只需使用常规 C++ i/o 编写暂停消息并等待按下返回即可。

std::cout << "Press return to continue" << std::endl;
std::getline();

我建议不要使用“using namespace std”,而是在需要时使用 std::限定符。它使事情变得更干净。

关于c++ - 从文件末尾检索字符串时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3536377/

相关文章:

javascript - 如何使用浏览器或 Adob​​e Build 测试 PhoneGap API?

c++ - 列表插入迭代器超出范围 (C++)

c++ - 从非成员静态函数发出信号

python - 使用大写字母和数字生成随机字符串

java - 在Java中比较字符串数组中的元素

Android读取多个文件最快的方法?

c++ - 如何写一个无符号的短整型文字?

c++ - 通过 reinterpret_cast 的非对齐访问

java - (我不知道如何比较字符串)用 while 循环写入文件

无法从 C 中的文本文件中读取所有名称