# Elgamal implementation problems

Sun May 1 11:05:39 CEST 2011

```Hello list!I am a student in computer science, and for a project I have to implement the Elgamal cryptosystem.What I am interested in is the additive homomorphic property of the "modified" scheme, namely:
Enc(m) = (c1, c2) = (g^k mod p , (h^k * g^message) mod p) Dec(Enc(m)) = (c2 * c1^-s)
The property is the following:
Enc(m) * Enc(m') = (c1 * c1' , c2 * c2');Dec(Enc(m) * Enc(m')) = g^(m + m');
My (maybe naive) implementation is the following:
void eg_encryption(eg_cipherText_t *cipherText, const mpz_t message, const eg_publicKey_t *publicKey){	mpz_t modMsg, k, tmp, tmp2;	mpz_inits(k,tmp2,tmp,modMsg,NULL);		//computing c1 = g^k mod p	generateRandomElGamal(k, ELGAMAL_RAND_BITS);	mpz_powm(cipherText->c1, publicKey->g, k, publicKey->p);
//computing c2 = h^k * g^M mod p	//tmp = h^k mod p	mpz_powm(tmp, publicKey->h, k, publicKey->p);		mpz_set(modMsg, message);		mpz_powm(tmp2, publicKey->g, modMsg, publicKey->p);	mpz_mul(cipherText->c2, tmp2, tmp);		//cleaning	mpz_clears(k,tmp,tmp2,modMsg,NULL);}
voideg_decryption(mpz_t message, const eg_cipherText_t *cipherText, const eg_privateKey_t *privateKey){	mpz_t tmp, ms;	mpz_inits(tmp,ms,NULL);		//computing message = (c2 * ((c1^-s)))	mpz_neg(ms, privateKey->s);	mpz_powm(tmp, cipherText->c1, ms, privateKey->p);		mpz_mul(message, cipherText->c2, tmp);	mpz_mod(message, message, privateKey->p);			//cleaning	mpz_clears(tmp,ms,NULL);}
This is working if:
m + m' > 0;
if not I receive wrong results.Am I missing/misusing something?Do you have any advices in order to improve this implementation (both in security and in efficiency)?Thank you in advance for your helpfulness!Warm regards,Angelo.

```