使用Caesar Cipher C ++进行加密

时间:2014-04-24 22:38:07

标签: c++ encryption

所以我在尝试将文件从文件转换为Caesar Cipher代码时遇到了问题。内容似乎被正确转换,但接近文件的末尾,它似乎在最后转储了一些错误。

问题:将\ FF添加到文件末尾的错误是什么?

原始文件的内容: enter image description here

加密后:

enter image description here

从图片中我可以看到,我将以下内容添加到文件\ FF

这是Caesar Cipher的以下代码...

void file_encription()
{
    std::string filename = "alpha.dat";
    ifstream inputFile( filename.c_str() );
    string plaintext;

    do
    {
      plaintext += inputFile.get();
    }
    while(inputFile);

            //string with the whole file saved...
    //string for the file plaintext

    std::string  &ciphertext = plaintext;

    std::int decipher;

    //Caesar Cipher code...
    std::cout << "please enter a number...";
        cin >> decipher;

        int shift = decipher % 26 

    for(int i = 0; i < ciphertext.size(); ++i)
    {
        if (islower(ciphertext[i]))
    {
            ciphertext[i] = (ciphertext[i] - 'a' + shift) % 26 + 'a';
    }
        else if (isupper(ciphertext[i]))
     {
            ciphertext[i] = (ciphertext[i] - 'A' + shift) % 26 + 'A';
         }
    }

        std::cout <<"your file was converted and saved as: decrypted_text.txt" << endl;
        ofstream finale("decrypted_text.txt");

            finale << ciphertext << endl;
        finale.close();
cin.get();
return BegginingPage();
}

1 个答案:

答案 0 :(得分:3)

你也在这里阅读eof(-1 / 0xFF):

do
{
  plaintext += inputFile.get();
}
while(inputFile);

使用:

std::ifstream t("file.txt");
std::string str((std::istreambuf_iterator<char>(t)),
             std::istreambuf_iterator<char>());

std::ifstream t("file.txt");
std::stringstream buffer;
buffer << t.rdbuf();
std::string str = buffer.str();

和btw你应该在加密后调用文件encrypted_text not decrypted_text;)