C++ AES加密C++;(无法解密加密文件)

C++ AES加密C++;(无法解密加密文件),c++,encryption,cryptography,aes,C++,Encryption,Cryptography,Aes,我在玩AES,将iv和派生密钥写入文件,以便稍后使用它进行解密 以下函数加密文件并将iv和派生密钥保存到文件中,它还将加密文本保存到单独的文件中: void MainWindow::on_button_encrypt() try { using namespace std; using namespace Gtk; using namespace CryptoPP; fstream file; file.open(m_file_name + "

我在玩AES,将iv和派生密钥写入文件,以便稍后使用它进行解密

以下函数加密文件并将iv和派生密钥保存到文件中,它还将加密文本保存到单独的文件中:

void MainWindow::on_button_encrypt() try
{
    using namespace std;
    using namespace Gtk;
    using namespace CryptoPP;

    fstream file;

    file.open(m_file_name + ".aes", std::ios::out | std::ios::trunc);
    if (file.is_open())
    {
        // get the plain password:
        SecByteBlock password;
        password_dialog get_passwd(password);
        get_passwd.run();


        // generate random salt
        const int SALT_SIZE = 32;
        SecByteBlock salt(SALT_SIZE);
        AutoSeededRandomPool prng;
        prng.GenerateBlock(salt.BytePtr(), SALT_SIZE);


        // derive a key from password and salt:
        SecByteBlock key(AES::DEFAULT_KEYLENGTH);
        PKCS5_PBKDF2_HMAC<SHA512> gen;
        gen.DeriveKey(key.BytePtr(), key.size(), 1, password.BytePtr(), password.size(), salt.BytePtr(), salt.size(), 200);


        // genereate random iv:
        SecByteBlock iv(AES::BLOCKSIZE);
        OS_GenerateRandomBlock(false, iv.BytePtr(), AES::BLOCKSIZE);


        // encrypt plain text:
        AES::Encryption enc(key.BytePtr(), AES::DEFAULT_KEYLENGTH);
        CBC_Mode_ExternalCipher::Encryption mode(enc, iv);

        string cipher_text;
        StringSink* sink = new StringSink(cipher_text);
        StreamTransformationFilter encryptor(mode, sink);

        string plain_text = m_file_buffer->get_text();
        encryptor.Put(reinterpret_cast<const byte*>(plain_text.c_str()), plain_text.length() + 1);
        encryptor.MessageEnd();

        // write the result:
        file << cipher_text.c_str();
        file.close();
        file.open(m_file_name + ".key", std::ios::out | std::ios::trunc);
        file << key << '\n' << iv;
        file.close();
   }
}
// catch ...
void主窗口::按按钮加密()试试
{
使用名称空间std;
使用名称空间Gtk;
使用名称空间CryptoPP;
流文件;
打开(m_file_name+“.aes”,std::ios::out | std::ios::trunc);
if(file.is_open())
{
//获取普通密码:
密码;
密码对话框获取密码(密码);
get_passwd.run();
//生成随机盐
const int SALT_SIZE=32;
SecByteBlock盐(盐粒度);
自动进料器和OMPOOL prng;
prng.GenerateBlock(salt.BytePtr(),salt_大小);
//从密码和salt派生密钥:
SecByteBlock密钥(AES::DEFAULT_KEYLENGTH);
PKCS5_PBKDF2_HMAC gen;
gen.DeriveKey(key.BytePtr()、key.size()、1、password.BytePtr()、password.size()、salt.BytePtr()、salt.size()、200);
//Generate random iv:
SecByteBlock iv(AES::BLOCKSIZE);
OS_GenerateRandomBlock(false,iv.BytePtr(),AES::BLOCKSIZE);
//加密纯文本:
AES::Encryption enc(key.BytePtr(),AES::DEFAULT_KEYLENGTH);
CBC_Mode_ExternalCipher::加密模式(enc,iv);
字符串密码;
StringSink*sink=新的StringSink(密码文本);
StreamTransformationFilter加密机(模式,接收器);
string plain_text=m_file_buffer->get_text();
encryptor.Put(reinterpret_cast(plain_text.c_str()),plain_text.length()+1);
encryptor.MessageEnd();
//写出结果:

文件没有guarentee密码文本将不包含像
\n
这样的转义序列,这使得
getline()
得到错误的字符串(截断)


因此,建议将密文转换为十六进制或其他形式,以避免转义序列。

问题在于
密文长度不是块大小的倍数。
(duh).阅读有关块和填充的信息-modes@deviantfan,谢谢,我做到了,正如我在上面的帖子中所说的,如果解密是在不读取文件的情况下完成的,那么就不会有这样的问题。您必须以二进制形式读取它,因为密文可能包含各种不可打印的和空白字符,如
\n
\0
。谢谢Artjom!读/写在二进制模式下,以及十六进制编码/解码输出解决了问题。谢谢,十六进制ECNOD和Artjom B建议的在二进制模式下读写解决了问题。我为将来可能遇到此类问题的其他人编辑了我的答案。
void MainWindow::on_button_decrypt()
{
    using namespace std;
    using namespace CryptoPP;
    Gtk::MessageDialog info("Info");

    fstream file;
    file.open("decrypted.txt", ios::out | ios::trunc);
    if (file.is_open())
    {
        // read the key:
        fstream stream;
        string input;

        SecByteBlock key(AES::DEFAULT_KEYLENGTH);
        SecByteBlock iv(AES::BLOCKSIZE);


        stream.open("test.txt.key", std::ios::in);

        if (stream.is_open())
        {
            getline(stream, input);
            key.Assign(reinterpret_cast<const byte*>(input.c_str()), input.size());
            input.clear();
            getline(stream, input);
            iv.Assign(reinterpret_cast<const byte*>(input.c_str()), input.size());
        }
        else
        {
            info.set_secondary_text("can't read key file");
            info.run();
            return;
        }


        // decrypt:
        AES::Decryption dec(key, AES::DEFAULT_KEYLENGTH);
        CBC_Mode_ExternalCipher::Decryption mode(dec, iv);

        string plain_text;
        StringSink* sink = new StringSink(plain_text);
        StreamTransformationFilter decryptor(mode, sink);
        
        try
        {
            // get encrypted text from buffer (obtained from other function):
            string cipher_text = m_file_buffer->get_text();
            decryptor.Put(reinterpret_cast<const byte*>(cipher_text.c_str()), cipher_text.size());
            decryptor.MessageEnd();
            file << plain_text;
            file.close();
        }
        catch (CryptoPP::Exception& ex)
        {
            info.set_secondary_text(ex.what());
            info.run();
        }
    }
}
// encrypt the file:
AES::Encryption enc(key.BytePtr(), AES::DEFAULT_KEYLENGTH);
CBC_Mode_ExternalCipher::Encryption mode(enc, iv);
    
string file = m_file_name + ".aes";
FileSink* sink = new FileSink(file.c_str());
StreamTransformationFilter encryptor(mode, sink);

string plain_text = m_file_buffer->get_text();
encryptor.Put(reinterpret_cast<const byte*>(plain_text.c_str()), plain_text.length());
encryptor.MessageEnd();


// write the key:
file = m_file_name + ".key";
FileSink* out = new FileSink(file.c_str());
Base64Encoder* base64_enc = new Base64Encoder;
base64_enc->Attach(out);
base64_enc->Put(key.BytePtr(), key.size());
base64_enc->MessageEnd();



// write the iv:
file = m_file_name + ".iv";
FileSink* out2 = new FileSink(file.c_str());
Base64Encoder* base64_enc2 = new Base64Encoder;
base64_enc2->Attach(out2);
base64_enc2->Put(iv.BytePtr(), iv.size());
base64_enc2->MessageEnd();
//
// read key
//
string store_key;
StringSink* string_key_in = new StringSink(store_key);
Base64Decoder* base64_key_dec = new Base64Decoder(string_key_in);

string file = "test.txt.key";
FileSource* file_key_in = new FileSource(file.c_str(), true, base64_key_dec);
    
SecByteBlock key(AES::DEFAULT_KEYLENGTH);
key.Assign(reinterpret_cast<const byte*>(store_key.c_str()), store_key.size());




//
// read iv
//
string store_iv;
StringSink* string_iv_in = new StringSink(store_iv);
Base64Decoder* base64_iv_dec = new Base64Decoder(string_iv_in);

file = "test.txt.iv";
FileSource* file_iv_in = new FileSource(file.c_str(), true, base64_iv_dec);

SecByteBlock iv(AES::BLOCKSIZE);
iv.Assign(reinterpret_cast<const byte*>(store_iv.c_str()), store_iv.size());



// read ciphertext:
string store_ciphertext;
StringSink* ciphertext_in = new StringSink(store_ciphertext);

file = m_file_name;
FileSource* file_ciphertext_in = new FileSource(file.c_str(), true, ciphertext_in);

SecByteBlock cipher_text;
cipher_text.Assign(reinterpret_cast<const byte*>(store_ciphertext.c_str()), store_ciphertext.size());



//
// decrypt:
//
AES::Decryption dec(key, AES::DEFAULT_KEYLENGTH);
CBC_Mode_ExternalCipher::Decryption mode(dec, iv);

file = "decrypted.txt";
FileSink* sink = new FileSink(file.c_str());
StreamTransformationFilter decryptor(mode, sink);

decryptor.Put(cipher_text.BytePtr(), cipher_text.size());
decryptor.MessageEnd();