Codice PHP:
#include<stdio.h>
#include<stdlib.h>
#include<gmp.h>
main (int argc, char **argv)
{
mpz_t G;
mpz_t y;
//mpz_init (y);
mpz_t p;
mpz_t temp;
mpz_t temp1;
mpz_t v1;
mpz_t k;
mpz_t k_inv;
mpz_t a;
mpz_t yrs;
mpz_t r;
mpz_t s;
mpz_t m;
mpz_t ar;
mpz_t mar;
mpz_t v2;
mpz_t yr;
mpz_t rs;
mpz_t gcd;
int compk;
int compgcd;
int verifica;
int forprimep;
gmp_randstate_t stato;
gmp_randinit_default(stato);
/*determinazione di p*/
mpz_init2(p,128);
mpz_urandomb(p, stato, 128);
/*mpz_setbit (p, 127);
mpz_setbit (p, 0);*/
forprimep = mpz_probab_prime_p (p, 1);
//while (forprimep == 0) {
// mpz_add_ui (p, p, 2);
// forprimep = mpz_probab_prime_p (p, 1);
// };
/* generazione di g */
mpz_init2(G, 64);
mpz_urandomb(G, stato, 64);
/* G */
/* generazione di a */
mpz_init2(a, 64);
mpz_urandomb(a, stato, 64);
/* a */
/* calcolo di y */
//mp_size_t new_alloc
//_mpz_realloc(y,1024);
mpz_powm(y,G,a,p);
/* y */
/* numero random k */
mpz_init2(k, 64);
mpz_urandomb(k, stato, 64);
mpz_sub_ui(temp, p, 2);
compk = mpz_cmp(k, temp);
while (compk > 0){
mpz_urandomb(k, stato, 64);
};
mpz_sub_ui(temp1, p, 1);
mpz_gcd(gcd, k, temp1);
compgcd = mpz_cmp_ui(gcd, 1);
while(compgcd != 0) {
mpz_urandomb(k, stato, 64);
};
/* k */
mpz_powm(r, G, k, p);
mpz_invert(k_inv, k, temp1);
mpz_mul(ar, a, r);
mpz_urandomb(m, stato, 64);
mpz_sub(mar, m, ar);
mpz_mul(s, k_inv, mar);
mpz_mod (s, s, temp1);
mpz_powm(yr, y, r, p);
mpz_powm(rs, r, s, p);
mpz_mul(yrs, yr, rs);
mpz_mod(v1, yrs, p);
mpz_powm(v2, G, m, p);
verifica = mpz_cmp(v1, v2);
printf("\n");
puts("ALGORITMO ELGAMAL");
printf(" \n");
printf("\n");
puts("CHIAVE PRIVATA");
printf(" \n");
puts("p =");
mpz_out_str(stdout, 10, p);
printf("\n");
puts("G = ");
mpz_out_str(stdout, 10, G);
printf("\n");
puts ("y= ");
mpz_out_str (stdout, 10, y);
printf("\n");
printf("\n");
puts ("a (CHIAVE SEGRETA) ");
mpz_out_str (stdout, 10, a);
printf("\n");
printf("\n");
puts ("m = (MESSAGGIO)");
mpz_out_str (stdout, 10, m);
printf("\n");
printf("\n");
puts ("NUMERO RANDOM = ");
mpz_out_str (stdout, 10, k);
printf("\n");
printf("\n");
puts ("FIRMA");
printf("\n");
puts ("r= ");
mpz_out_str (stdout, 10, r);
printf("\n");
puts ("s= ");
mpz_out_str (stdout, 10, s);
printf("\n");
printf("\n");
puts ("VERIFICA");
printf("\n");
puts("v1 = ");
mpz_out_str (stdout, 10, v1);
printf("\n");
puts("v2 = ");
mpz_out_str (stdout, 10, v2);
printf("\n");
printf("\n");
if(verifica == 0)
{
puts("v1 = v2 OK!");
printf("\n");
}
exit(0);
}