How to decrypt a file in memory?

31 views
Skip to first unread message

Karine Alves

unread,
Sep 21, 2022, 1:59:54 PM9/21/22
to Crypto++ Users
I'm encrypting a file this way:


    #include <cryptopp/files.h>
    #include <cryptopp/modes.h>
    #include <cryptopp/osrng.h>
    #include <cryptopp/base64.h>
    #include <cryptopp/hex.h>
    #include <Windows.h>
    #include <iostream>
    #include <fstream>
   
   
    void FileEncrypt(byte key[], byte iv[]
                   , const std::string& file, const std::string& dest)
    {
        CTR_Mode< AES >::Encryption cipher;
        cipher.SetKeyWithIV(key, strlen((char*)key), iv, strlen((char*)iv));
   
        std::ifstream in{file, std::ios::binary};
        std::ofstream out{dest, std::ios::binary};
   
        CryptoPP::FileSource{in, true,
                new CryptoPP::StreamTransformationFilter{
                cipher, new CryptoPP::FileSink{out}}};
    }
   
    INT main(INT argc, PCHAR* argv)
    {
        std::string file = "...";
        std::string dest = "...";
   
        unsigned char* key[] = "p3s6v9y$B&E)H@Mc";
        unsigned char* iv[] = "VkXp2s5v8y/B?E(H";
   
        FileEncrypt(key, iv, file, dest);
        FileDecrypt(key, iv, file, dest);
    }


Then when needed i'm downloading the encrypted file from my repo.

I've been able to decrypt it with:

```c++
    void FileDecrypt(byte key[], byte iv[]
                   , const std::string& file, const std::string& dest)
    {
         CTR_Mode< AES >::Decryption cipher;
         cipher.SetKeyWithIV(key, strlen((char*)key), iv, strlen((char*)iv));
         
         std::ifstream in{file, std::ios::binary};
         std::ofstream out{dest, std::ios::binary};
   
         CryptoPP::FileSource{in, true,
                              new CryptoPP::StreamTransformationFilter{
                                  cipher, new CryptoPP::FileSink{out}}};
    }
```
But this way the decrypted file is saved to disk, how could i decrypt it on memory without saving to disk?

Anton Schmidt

unread,
Sep 22, 2022, 5:01:18 AM9/22/22
to Crypto++ Users
Just load file data into memory buffer (std::vector<CryptoPP::byte>) and use filter pipeline with VectorSource and VectorSink.
https://cryptopp.com/docs/ref/class_vector_source.html
https://cryptopp.com/docs/ref/class_vector_sink.html

четверг, 22 сентября 2022 г. в 00:59:54 UTC+7, kakaa...@gmail.com:
Message has been deleted

Jeffrey Walton

unread,
Sep 22, 2022, 11:36:54 AM9/22/22
to Crypto++ Users
Reply all
Reply to author
Forward
0 new messages