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);
}
I've been able to decrypt it with:
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 it to disk?
I'm downloading the encrypted file from my repo, i also tried decrypting it with:
std::string data;
FileDownload(data, "https://github.com/..."));
//...
std::string dec;
try {
CTR_Mode< AES >::Decryption d;
d.SetKeyWithIV(key, strlen((char*)key), iv, strlen((char*)iv));
StringSource s(data, true,
new StreamTransformationFilter(d,
new StringSink(dec)));
}
catch (const CryptoPP::Exception& e)
{
std::cerr << e.what() << std::endl;
}
But dec
isn't returning the decrypted file correctly.
CodePudding user response:
I'm not familiar with crypto , but according to their docs, you're probably interested in using the StringSink
class in place of FileSink
. Note that then the output variable should be an std::string
instead of an std::ofstream
.
CodePudding user response:
I have been able to decode the file with:
std::string dec;
StringSource s((byte*)data.data(), raw.size(), true,
new StreamTransformationFilter(cipher,
new StringSink{ dec }));