【问题标题】:C++ Encrypt a text file, allow use of decrypt via ifstreamC++ 加密文本文件,允许通过 ifstream 使用解密
【发布时间】:2026-01-15 03:25:01
【问题描述】:

我正在寻找一种使用密码加密文本文件(在我的示例中是 .data 文件)并保存加密文件的非常简单的方法。

然后将保存的文件加载到我的应用程序中并使用相同的密码解密。然后我需要一种方法来以某种方式获取解密数据的句柄,而无需将其保存到文件中(我不希望用户看到解密的数据,只有程序会拥有它并处理它,然后它将被丢弃在程序结束时)。

检索数据后,我应该能够获得某种数据句柄并在 ifstream 中使用它,我现在使用它来解析我的文本数据文件,如下所示:

string line;
string filename = "hello.data";
ifstream myfile(filename); // <-- instead of providing filename directly,
//^^I'd need a handle to the decrypted data.

while ( getline (myfile,line) ){
    parse_line(line);
}

myfile.close();

在 C++ 中快速完成此任务的最佳和最简单的方法是什么?可以在没有任何外部库的情况下完成吗?只需使用 Windows Visual Express C++ 中可用的标准 C++ 工具即可完成,无需链接任何新库。但是,如果您确实知道需要第三方代码的代码,如果您觉得它易于快速学习,请发布它。

【问题讨论】:

  • 好吧,除非你想实现流或分组密码,否则我建议你只能做一些混淆。没有任何加密方法库直接作用于文件,所以从这个意义上说你很幸运。如果您不想包含一个库并且仍然有一个安全算法,那么复制它

标签: c++ file encryption text


【解决方案1】:

一种非常简单(而且非常不安全)的加密方法就是将密码短语与您的文本数据进行异或。解密是另一个具有相同密码的 XOR。您需要重复密码,直到文本数据结束。

请注意,这很容易被破解,但它提供了一个基本的加密层。

【讨论】:

    【解决方案2】:

    使用 POCO 库进行 RSA 加密比对数据进行 XORing 密码更安全。

    RSA 密钥可以这样生成:

    //generate private key: 
    openssl genrsa -des3 -out private_rsa.pem 1024
    // generate public key: 
    openssl rsa -in private_rsa.pem -pubout -out public_rsa.pem
    

    公钥将用于加密数据,然后加密存储在文件中的数据:

    void encrypt_file()
    {
        Poco::Crypto::CipherFactory &factory = Poco::Crypto::CipherFactory::defaultFactory();
        Poco::Crypto::Cipher* pCipher = factory.createCipher(Poco::Crypto::RSAKey("./public_rsa.pem"));
    
    
        Poco::Crypto::CryptoTransform *pEncryptor = NULL;
        pEncryptor = pCipher->createEncryptor();
    
        Poco::FileOutputStream sink("./encrypted.bin");
        Poco::Crypto::CryptoOutputStream encryptor(sink, pEncryptor);
    
        Poco::FileInputStream source("input.txt");
        Poco::StreamCopier::copyStream(source, encryptor);
    
        // Always close output streams to flush all internal buffers
        encryptor.close();
        sink.close();
    }
    

    私钥可以从文件中读取或硬编码:

    void decrypt_file()
    {
        std::istringstream is("-----BEGIN RSA PRIVATE KEY-----\n"
        "Proc-Type: 4,ENCRYPTED\n"
        "DEK-Info: DES-EDE3-CBC,0F9006C4519B55C8\n"
        "\n"
        "rRLQeGPaa8iqc4ke+fxDmCvgfdsgfdsgf55343ggynqDpmhGd29iBed4N1Xovdiw\n"
        "G87l0Uco+ZhsriLPjWBdTmr14HrBxJEJybXucjx1h4WLqMd1ro0QY2QlojJ337Sq\n"
        "LFqcLc1nSW3levjkFIDSpFjnPbaDk/t/1xQEh3VHWOGHa+IVSDKTkw2uyiKO7bh+\n"
        "W6MCbXnaJIS0/6ouoJgnK7COrS/0Hqo5z0wLY9ZCarLeVOYMK+YamhXrSz5sLElI\n"
        "2ysC5kLxhWBZOTiGOc1aPh6svWmFg0I1Eil+PVTR3XR6L/b8LY/BQMh0OJ6uwdvp\n"
        "YfgzdvxqDVbCjw1dNJjgfvegfdgdDDlzQfFsXGf1p9OY0jElL/egVTGP1YLHgMb6\n"
        "zJDUZmgC2PJBOB/KWJF09k0vDfdr/t32OXE9vMPAJeJ2TwecnmvYiLbA5uu93bvi\n"
        "DEo9V+F7ltMS2XQld9kal4dHPE1NdCMBx5oY8Bi+Qf9rXUdO/0JxZIY0j+0pWGZa\n"
        "7iZWriyme4zxGFQJXD8hV4AW7NNUUff3bCkkmYyYOyV11ybWJGGOBk6IJCcuzFoq\n"
        "S94LfFMBtcmXQmUXcQwacIDzAEivmk0Uxz1bMmcu+wNEIquLx9wEZWlll6P88JPv\n"
        "E58HIXKB9AVEJZ5gfdgfdfgregd4345grgdgfs0qbR3v4qcNCKWlihd36MT+0QD+\n"
        "HCoakmTbbPXdUC8HcppB7D9nhjmbuXcneu8sf/zUrDHcwBbHR7T0U63LE2gdzfOc\n"
        "vg6XAhXMRApLYydfsf44sgg4w4wsAcXMJpxNcz+JXG14QcBGJ1Ot4dGbTCVoww==\n"
        "-----END RSA PRIVATE KEY-----\n"
        "\n");
    
        Poco::Crypto::CipherFactory &factory = Poco::Crypto::CipherFactory::defaultFactory();
        Poco::Crypto::Cipher* pCipher = factory.createCipher(Poco::Crypto::RSAKey(NULL, &is, "my password"));
    
        // uncomment to read private key from the file
        //Poco::Crypto::Cipher* pCipher = factory.createCipher(Poco::Crypto::RSAKey("", "./private_rsa.pem", "my password"));
    
        std::ifstream in("./encrypted.bin", std::ios::binary|std::ios::in);
        if(!in.is_open())
            return;
    
        std::string data;
        data.append(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
        in.close();
    
        const std::string decrypted_string(pCipher->decryptString(data));
        std::cout << "decrypted string: " << decrypted_string << std::endl;
    }
    

    【讨论】: