Dark Sorrow
Dark Sorrow

Reputation: 1937

Possible Memory Leak in CryptoPP::StreamTransformationFilter

I'm referring to the following links :https://www.cryptopp.com/wiki/StreamTransformationFilter and https://www.cryptopp.com/wiki/CBC_Mode

In line StringSource string_source(encypted_data, true, new StreamTransformationFilter(decryption, new StringSink(plain_data))); we are creating the objects of class StreamTransformationFilter and StringSink on heap using new operator; however we are not deleting them. Shouldn't it cause memory leak as their is no delete operation.

Should I replace

StringSource string_source(plain_data, true, new StreamTransformationFilter(encryption, new StringSink(encypted_data)));

with the following code

try
{
    CryptoPP::CBC_Mode<CryptoPP::AES>::Encryption   encryption(this->aes_key.data(), this->aes_key.size(), this->aes_iv.data(), this->aes_iv.size())
    CryptoPP::StringSink                            string_sink(encypted_data);
    CryptoPP::StreamTransformationFilter            stf_encryptor(encryption, string_sink);
    CryptoPP::StringSource                          string_source(plain_data, true, stf_encryptor);
}

to avoid memory link; so that as soon as the try block is exited destructor on classes CryptoPP::StringSink, CryptoPP::StreamTransformationFilter and CryptoPP::StringSource will be called.

Program :

std::optional<std::string> Cryptography::decrypt_data(const std::string& encypted_data)
{
    std::optional<std::string> plain_data { std::nullopt };
    try
    {
        CryptoPP::CBC_Mode<CryptoPP::AES>::Decryption   decryption(this->aes_key.data(), this->aes_key.size(), this->aes_iv.data(), this->aes_iv.size())
        StringSource string_source(encypted_data, true, new StreamTransformationFilter(decryption, new StringSink(plain_data)));
    }
    catch(const CryptoPP::Exception& e)
    {
#ifdef _DEBUG
        spdlog::error("CryptoPP Exception in Cryptography::decrypt_data : {}", ex.what());
#endif
        PLOG_ERROR << ex.what();
    }
    catch(const std::exception& ex)
    {
#ifdef _DEBUG
        spdlog::error("Exception in Cryptography::decrypt_data : {}", ex.what());
#endif
        PLOG_ERROR << ex.what();
    }
    return plain_data;
}

Upvotes: 0

Views: 411

Answers (1)

Alan Birtles
Alan Birtles

Reputation: 36469

When you pass a filter/sink to the constructor of a filer/source it takes ownership of the pointer and will delete it on destruction.

In your example StringSource deletes the StreamTransformationFilter which in turn deletes the StringSink

Upvotes: 1

Related Questions