0

I am trying to encrypt and decrypt an image file with ElGamal in C++. It has to use ElGamal encryption. I want to save both the encrypted file and recovered file. I am using Crypto++ libraries for the encryption/decryption part. Here is what I have so far.

AutoSeededRandomPool prng;

ElGamal::Decryptor decryptor;
decryptor.AccessKey().GenerateRandomWithKeySize(prng, 2048);
const ElGamalKeys::PrivateKey& privateKey = decryptor.AccessKey();

ElGamal::Encryptor encryptor(decryptor);
const PublicKey& publicKey = encryptor.AccessKey();

string ofilename = "test.bmp";
string efilename = "test.enc";
string rfilename = "test-recovered.bmp";

FileSource fs1(ofilename.c_str(), true, encryptor.CreateEncryptionFilter(encryptor.Encrypt, new FileSink(efilename.c_str())));

FileSource fs2(efilename.c_str(), true, decryptor.CreateDecryptionFilter(decryptor.Decrypt, new FileSink(rfilename.c_str())));

I am stuck at the encryption and decryption part. Any help would be greatly appreciated!

1 Answers1

0

Your problem is that you're trying to encrypt arbitrarily large data using an asymmetric cryptosystem. Asymmetric cryptosystems cannot encrypt data which length is larger than the size of their modulus. (See Why doesn't my implementation of ElGamal work for long text strings?)

The typical workaround to this limitation is to perform a symmetric transformation to the input using a standard symmetric algorithm (e.g. AES) and then encrypt the symmetric key using the asymmetric public key. The decryption then reverses the operation by first decrypting the symmetric key and then use the symmetric key to decrypt the encrypted content.

Crypto++ ElGamal objects offer SymmetricEncrypt and SymmetricDecrypt. The functions will encrypt and decrypt arbitrary length text under a symmertic key, and then encrypt the symmetric key under the ElGamal public key. (See Crypto++ Wiki - ElGamal)

Community
  • 1
  • 1
Timothy Ghanem
  • 1,606
  • 11
  • 20