Beispiel #1
0
int VNRW_GMP_GenKeys( VNAsymCryptCtx_t * ctx, int keyBits )
{
	mpz_t zrand;
	gmp_randstate_t state;
	struct vn_iovec seed;

	VNRW_GMP_Ctx_t * gmpCtx = VN_CONTAINER_OF( ctx, VNRW_GMP_Ctx_t, mCtx );
	assert( VN_TYPE_VNRWSign_GMP == ctx->mType || VN_TYPE_VNRWEnc_GMP == ctx->mType );

	keyBits = ( keyBits + 1 ) / 2;

	mpz_init( zrand );

	VNIovecGetRandomBuffer( &seed, ( keyBits / 8 + 1 ) );
	mpz_import( zrand, seed.i.iov_len, 1, 1, 0, 0, seed.i.iov_base );

	gmp_randinit_default( state );
	gmp_randseed( state, zrand );

	do {
		mpz_urandomb( zrand, state, keyBits );
	} while( keyBits != mpz_sizeinbase( zrand, 2 ) );

	mpz_set( gmpCtx->mP, zrand );
	do {
		mpz_nextprime( gmpCtx->mP, gmpCtx->mP );
	} while ( mpz_fdiv_ui( gmpCtx->mP, 8 ) != 3 );

	mpz_set( gmpCtx->mQ, gmpCtx->mP );
	do {
		mpz_nextprime( gmpCtx->mQ, gmpCtx->mQ );
	} while ( mpz_fdiv_ui( gmpCtx->mQ, 8 ) != 7 );

	/* compute public key n */
	mpz_mul( gmpCtx->mN, gmpCtx->mP, gmpCtx->mQ );

	VNRW_CalcD( ctx );

	gmp_randclear( state );
	VNIovecFreeBufferAndTail( &seed );

	mpz_clear( zrand );

	return 0;
}
void
init_rand( gmp_randstate_t rand, paillier_get_rand_t get_rand, int bytes )
{
	void* buf; 
        FILE *fp;
      	mpz_t s;

	buf = malloc(bytes);
	paillier_get_rand_devurandom(buf, bytes);

	gmp_randinit_default(rand);
	mpz_init(s);
	mpz_import(s, bytes, 1, 1, 0, 0, buf);
	gmp_randseed(rand, s);
        mpz_clear(s);

	free(buf);
}
Beispiel #3
0
void
tests_rand_start (void)
{
  gmp_randstate_ptr  rands;
  char           *seed_string;

  if (__gmp_rands_initialized)
    {
      printf ("Please let tests_start() initialize the global __gmp_rands.\n");
      printf ("ie. ensure that function is called before the first use of RANDS.\n");
      abort ();
    }

  gmp_randinit_default (__gmp_rands);
  __gmp_rands_initialized = 1;
  rands = __gmp_rands;

  seed_string = getenv ("GMP_CHECK_RANDOMIZE");
  if (seed_string != NULL)
    {
      if (strcmp (seed_string, "0") != 0 &&
	  strcmp (seed_string, "1") != 0)
        {
	  mpz_t seed;
	  mpz_init_set_str (seed, seed_string, 0);
          gmp_printf ("Re-seeding with GMP_CHECK_RANDOMIZE=%Zd\n", seed);
          gmp_randseed (rands, seed);
	  mpz_clear (seed);
        }
      else
        {
	  FILE *fs = fopen ("/dev/urandom", "r");
	  if (fs != NULL)
	    {
	      seed_from_urandom (rands, fs);
	      fclose (fs);
	    }
	  else
	    seed_from_tod (rands);
        }
      fflush (stdout);
    }
}
Beispiel #4
0
int main()
{
    mpz_t pN;
    mpz_init(pN);
    mpz_t puC;
    mpz_init(puC);
    mpz_t prU;
    mpz_init(prU);

    gmp_randstate_t state;
    gmp_randinit_default(state);

    mpz_t seed;
    mpz_init(seed);

    RSA KeyGenerator;

    KeyGenerator.randInit(seed,"ahahah");
    gmp_randseed(state,seed);

    std::cout << "état : " <<state <<std::endl;

    KeyGenerator.getKeys(pN, puC, prU, state);

    std::cout << "public keys : " <<pN <<std::endl<<puC<<std::endl;
    std::cout << "private keys : " <<pN <<std::endl<<prU<<std::endl;

    gmp_randclear(state);

    Message Chaine("s");
    mpz_t code;
    mpz_init(code);
    std::string text1 = Chaine.encryptRSA(puC,pN);

    //std::cout << "voici le texte crypté:"<<std::endl<<text1<<std::endl;

    std::string text2 = Chaine.decryptRSA(prU, pN);
    //std::cout << "voici le texte décrypté:"<<std::endl<<text2<<std::endl;

    return 0;
}
Beispiel #5
0
void ECDSA_sign_file (char * path, ptr_curve_t E, ptr_point_t G, ptr_point_t Q, bases_t d_bases, mpz_t r, mpz_t s)
{
	printf("\n\tStrat EC-DSA algo\n");
	mpz_t k_inv, r0, r1, r2, n, d, k, z, x1;
	mpz_init(k_inv);
	mpz_init(r0);
	mpz_init(r1);
	mpz_init(r2);
	mpz_init(s);
	mpz_init(k);
	mpz_init(z);
	mpz_init(x1);
	mpz_init(r);

	bases_t k_bases;
	bases_init(k_bases);

	point_t X;
	point_init(&X);

	//sha-256 de m
	char buffer[65];
	char buffer_M[40];
	mpz_init(n);
	mpz_ui_pow_ui(n,2,M);
	mpz_init(d);
	bases_to_int(d_bases,d);

	mpz_t seed;
	mpz_init_set_str(seed,"85e25bfe5c86226cdb12016f7553f9d0e693a268",16);
	gmp_randstate_t rand_stat;
	gmp_randinit_default(rand_stat);
	gmp_randseed(rand_stat,seed);
	//gmp_randseed_ui(rand_stat,time(NULL));
	//k*G=(x1,y1) (un scalaire fois un point)

	int step_3 = 0;
	while(!step_3)
	{
		mpz_urandomb(k,rand_stat,M);
		if(DEBUG)gmp_printf("%Zd\n",k);
		int_to_bases(k,k_bases);
		multiple_point_CE(E,G,k_bases,&X);

		if(DEBUG)point_print(&X,"X");

		//r=x1 mod n (x1 est transformé en integer)
		bases_to_int(X._x,x1);

		if(DEBUG)gmp_printf("%Zd\n",x1);
		mpz_mod_2exp(r,x1,M);
		if(mpz_cmp_ui(r,0)<=0)
		{
			printf("\tRestart EC-DSA algo because r = 0\n");
			continue;
		}

		if(DEBUG)gmp_printf("r = x1 mod n, r = %Zd\n", r);
		//z = Hex_to_int(sha-256(M))
		sha256_file(path,buffer);
		strncpy(buffer_M,buffer,40);
		mpz_init_set_str(z,buffer_M,16);

		//s= k^-1(z+r*d) mod n (multiplication d'integers)
		mpz_invert(k_inv,k,n);
		mpz_mul(r0,r,d);
		mpz_add(r1,z,r0);
		mpz_mul(r2,k_inv,r1);
		mpz_mod_2exp(s,r2,M);
		//if s = 0 go to step_3
		if(mpz_cmp_ui(s,0)>0)
		{
			step_3 = 1;
		}
		else
		{
			printf("\tRestart EC-DSA algo because s = 0\n");
		}
	}
	printf("\t\thash : sha-256(M) = %s\n", buffer);
	gmp_printf("\t\tz = %Zd\n",z);
	gmp_printf("\t\tr = %Zd\n",r);
	gmp_printf("\t\ts = %Zd\n",s);
	printf("\tEnd EC-DSA algo\n");
}//ECDSA_sign_file()
int main(int argc, char *argv[])
{  
   DIR *d;
   FILE  *fpub, *fciph, *fplain, *fprod, *fkey;
   paillier_pubkey_t *pub;
   paillier_plaintext_t *plain, *plain_sum, *plain_temp;
   paillier_prvkey_t *priv;
   paillier_get_rand_t get_rand;
   paillier_ciphertext_t *cipher, *cipher_prod, *cipher_total;
   int count = 0, count1=0, val = 163000, no_of_copies = 10;
   long int key_int, key_int1, key_rnd;
   struct dirent *dir;
   char* len;	
   mpz_t           rndKey, randNum, rnd,rnd_sum, rndno, sum, pl_sum;      /* Hold our random numbers */
   mpz_t           rndBnd;       /* Bound for mpz_urandomm */
   mpz_t key, key1;		//key for PRF
   mpz_t plain_total, plain_nomod;
   gmp_randstate_t gmpRandState, gmpRandState1, gmpRandState2; /* Random generator state object */
   
   mpz_init(sum); 
   mpz_init(pl_sum);
   mpz_init(rnd);
   mpz_init(rndno);
   mpz_init(rndBnd);
   mpz_init(randNum);
   mpz_init(key);
   mpz_init(key1);
   mpz_init(rnd_sum);
   mpz_init(plain_total);
   mpz_init(rnd);
   mpz_init(rndKey);
   mpz_init(plain_nomod);
   mpz_set_ui(plain_total, 0);
   
   plain = (paillier_plaintext_t*) malloc(sizeof(paillier_plaintext_t));
   plain_sum = (paillier_plaintext_t*) malloc(sizeof(paillier_plaintext_t));
   plain_temp = (paillier_plaintext_t*) malloc(sizeof(paillier_plaintext_t));
   cipher_prod = (paillier_ciphertext_t*) malloc(sizeof(paillier_ciphertext_t));
   cipher_total = (paillier_ciphertext_t*) malloc(sizeof(paillier_ciphertext_t));
   cipher = (paillier_ciphertext_t*) malloc(sizeof(paillier_ciphertext_t));
   len = (char *)malloc(2048*sizeof(char));
   //mpz_init(cipher_prod->c);
   mpz_init(cipher_total->c);
   mpz_set_ui(rnd_sum, 0);
   mpz_init_set_str(cipher_prod->c, "1", 10);
   mpz_init_set_str(cipher_total->c, "1", 10);
   mpz_init_set_str(plain_sum->m, "0", 10);
  // printf("\nloading pailler keys");
   if((fpub = fopen("pub.txt", "r")))
    {
       	pub = (paillier_pubkey_t*) malloc(sizeof(paillier_pubkey_t));
	priv = (paillier_prvkey_t*) malloc(sizeof(paillier_prvkey_t));	
	mpz_init(pub->n_squared);
	mpz_init(pub->n);
	fgets(len, 1000, fpub);
   	mpz_init_set_str(pub->p, len, 10);
	fgets(len, 1000, fpub);
   	mpz_init_set_str(pub->q, len, 10);
	fgets(len, 1000, fpub);
   	mpz_init_set_str(pub->n_plusone, len, 10);
	//printf("value of nplusone : \n");
	//mpz_out_str(stdout, 10, pub->n_plusone);
	paillier_keygen(&pub, &priv, get_rand, 0);
        pub->bits = mpz_sizeinbase(pub->n, 2);	
        fclose(fpub);
    }
    gmp_randinit_default(gmpRandState);
    mpz_set_str(rndBnd, "163000", 10); 
    mpz_set_ui(rndKey, time(NULL));
    gmp_randseed(gmpRandState, rndKey);
    fkey = fopen("prf_key.txt", "w");
    mpz_urandomm(rndno, gmpRandState, pub->n); 
    mpz_set(key, rndno);
    element_fprintf(fkey, "%Zd\n", key);
    mpz_urandomm(rndno, gmpRandState, pub->n); 
    mpz_set(key1, rndno);
    element_fprintf(fkey, "%Zd", key1);  
    fclose(fkey);
    
  	 
  gmp_randseed(gmpRandState, key);
  //mpz_out_str(stdout, 10, rnd);
   //****Opening files to read files and encrypt*****  
    int i, j;
   mpz_t rand_val[val], rand_init[no_of_copies], mpz_result[no_of_copies];
   char fileName[1000], file[1000];
   //strcpy(fileName, "./cipher/copy3/output");
  mpz_set_str(sum, "0", 10);
  mpz_set_str(pl_sum, "0", 10);
  for(j =0; j < no_of_copies; j++)
  {
    mpz_init(rand_init[j]);
    mpz_urandomm(rand_init[j], gmpRandState, pub->n); 
    mpz_add(sum, sum, rand_init[j]);
  //  mpz_mod(sum, sum, pub->n);
    //printf("\n 1st rand \n");
    //mpz_out_str(stdout, 10, rand_init[j]);
  }
 // printf("\nsum\n");
 // mpz_out_str(stdout, 10, sum);
  mpz_set_str(pl_sum, "0", 10);
  gmp_randseed(gmpRandState, key1);
  for(j =0; j < no_of_copies; j++)
  {
   mpz_set_ui(cipher_prod->c, 1);
   for(i = 0; i < val; i++)
   {
     sprintf(fileName, "./cipher/copy%d/output", (j+1));
     
     if(j == 0)
     {
      do	
        mpz_urandomm(randNum, gmpRandState, rndBnd);
      while(mpz_cmp_ui(randNum,0) ==0);
      mpz_init(rand_val[i]);
      mpz_set(rand_val[i], randNum);
      //printf("\n2ndrand\n");
      //mpz_out_str(stdout, 10, randNum);
     // printf("random\n");
     // mpz_out_str(stdout, 10, rand_val[i]);
     }
     else
     {
      mpz_set(randNum, rand_val[i]);
      }
    // sprintf(num, "output%d.txt", (j+1));
     mpz_get_str(file, 10, randNum);
     strcat(fileName, file);
     strcat(fileName,".txt");
     count = 0;
   //  printf("\n%s", fileName);
     //mpz_out_str(stdout, 10, randNum);
     if(!(fciph = fopen(fileName, "r")))
       {
         printf("\n not able to read %s", fileName);
         //  fputs("not possible to read  file!\n", stderr);
       } 
     else
       {
	fgets(len, 1000, fciph);
	mpz_init_set_str(cipher->c, len, 10);
	//if(strstr(dir->d_name, "output") != NULL)
        //{
	//  printf("\ncipher\n");
          //mpz_out_str(stdout, 10, cipher->c);
          paillier_mul(pub, cipher_prod, cipher_prod, cipher);
	  // printf("\ncipher after product\n");
          //mpz_out_str(stdout, 10, cipher_prod->c);
        //}
	fclose(fciph);
       }
     if(j == 0)
      {
       strcpy(fileName, "./split/output"); 
       strcat(fileName, file);
       strcat(fileName,".txt");
       if(!(fplain = fopen(fileName, "r")))
         {
           printf("\n not read %s", fileName);
	   count1++;
         }
        else
         {
	  fgets(len, 1000, fplain);
         // printf("\npleain sum\n");
	 // mpz_out_str(stdout, 10, plain_sum->m);
	  mpz_init_set_str(plain->m, len, 10);
	 // if(strstr(dir->d_name, "output") != NULL)
          //{
	   mpz_add(plain_sum->m, plain_sum->m, plain->m);
	   //mpz_mod(pla in_sum->m, plain_sum->m, pub->n);	
 	  //}
          fclose(fplain);
	 } 
       } 
   } 
    mpz_powm(cipher_prod->c, cipher_prod->c, rand_init[j], pub->n_squared);
    paillier_mul(pub, cipher_total, cipher_total, cipher_prod);
   
    mpz_mul(plain_temp->m, plain_sum->m, rand_init[j]);
    mpz_add(plain_total, plain_total, plain_temp->m);
    mpz_mod(plain_total, plain_total, pub->n); 
   }
   plain = paillier_dec(plain, pub, priv, cipher_total);
   printf("\n decrypt \n");
   mpz_out_str(stdout, 10, plain->m);
   // printf("\n plain total \n");
   //mpz_out_str(stdout, 10, plain_total);
   printf("\n plain text total\n");
    mpz_out_str(stdout, 10, plain_sum->m);
   mpz_mul(pl_sum, plain_sum->m, sum);
   mpz_mul(pl_sum, pl_sum, pub->n);
   mpz_mul(pl_sum, pl_sum, priv->lambda);
 //  mpz_mod(pl_sum, pl_sum, pub->n);
    printf("\n plain text * rnd\n");
    mpz_out_str(stdout, 10, pl_sum);  
   if((fprod = fopen("result/cipher_result.txt", "w")))
        {
         printf("\nWriting the result to file \n");
         gmp_fprintf(fprod, "%Zd\n", cipher_total->c);  
	 fclose(fprod);
        }
   
   return 0;
}
Beispiel #7
0
int main(void) {
	long sd = 0;
	int t = 20;
	int s,j_rab;//miller
	int result = 0; //miller
	//metavlites gia metatropi keimenou se int k tubalin
	char mystring[MAXCHARS];//my text to encrypt - decrypt hope so
    long int str_len;
    char c;
    mpz_t max_int, c_int, str_int, encrypted,decrypted;
    mpz_init(max_int); mpz_init(c_int); mpz_init(str_int);mpz_init(encrypted); mpz_init(decrypted);
	mpz_t psi, d, n_minus_one;//miller
mpz_t n_prime,n,three,two,a,one,p,q,phi,p_minus_one,q_minus_one,e,gcd,d_priv,t2;
mpz_t seed;
mpz_t ro;//for encry-decry
gmp_randinit(stat,GMP_RAND_ALG_LC,120);
mpz_init(n_prime);
mpz_init(n);//iniatialize
mpz_init(three);
mpz_init(a);
mpz_init(two);
mpz_init(one);
mpz_init(seed);
mpz_init(psi);//for miller-rabin
mpz_init(p);
mpz_init(q);
mpz_init(phi);
mpz_init(p_minus_one);
mpz_init(q_minus_one);
mpz_init(e);
mpz_init(gcd);
mpz_init(d_priv);
mpz_init(ro);
mpz_init(t2);
mpz_set_str(three, "3", 10);
mpz_set_str(two, "2", 10);
mpz_set_str(one, "1", 10);
srand((unsigned)getpid()); //initialize stat
sd = rand();
mpz_set_ui(seed,sd);
gmp_randseed(stat,seed);
int countpq=0;//0 primes pros to paron, kantous 2 (p kai q)
int i = 0;
//printf("Give a message (till %d chars):\n",MAXCHARS-1);
//fgets(mystring,MAXCHARS,stdin);
//

FILE *fp;            /* declare the file pointer */
 fp = fopen ("file.txt", "r");
 while(fgets(mystring, MAXCHARS, fp) != NULL)
    { sscanf (mystring, "%d"); }
fclose(fp);
//
do{ // mehri na vreis 2 prime

do{//RANDOM NUMBER
	mpz_urandomb(n_prime,stat,512);//create a random number
}while((mpz_even_p(n_prime))&& (n_prime<=three));//checking n to be >=3 && n be odd

mpz_init(n_minus_one); //initialize
mpz_sub_ui(n_minus_one, n_prime, 1);//n_minus_one = n-1
	s = 0;
	mpz_init_set(d, n_minus_one);
	while (mpz_even_p(d)) {// gia oso ine artios
		mpz_fdiv_q_2exp(d, d, 1); //shift right
		s++;//inc s
	}
	for (i = 0; i < t; ++i) {
		do{
		mpz_urandomb(a,stat,20);//create random number
		}while(!((a<=(n_prime-two)) && (a>=two)));//checking a must be (2<=a<=n-2)
		 mpz_powm(psi,a,d,n_prime);
		 if(mpz_cmp(psi,one)!=0 && mpz_cmp(psi,n_minus_one)){
			 j_rab=1;
			 while(j_rab<s &&  mpz_cmp(psi,n_minus_one)){
				 mpz_mul(psi,psi,psi); // y^2
				 mpz_mod(psi,psi,n_prime); //psi= psi^2 mod n
				 	 if(mpz_cmp(psi,one)==0){//if y=1
				 		  result = 1; goto exit_miller;
				 	 }
				 	 j_rab++;
			 }
		 	 if(mpz_cmp(psi,n_minus_one)!=0){//if y=n-1
		 		 result = 1; goto exit_miller;
		 	 }
		 }//end external if
}//end for

	if(result!=1){ countpq++; //an ine prime tote save
	if(countpq==1){mpz_set(p,n_prime);}//save p
	else{
		mpz_set(q,n_prime);}//save q
	}
	exit_miller: result = 0;
	if(mpz_cmp(p,q)==0){countpq=0;}//an p kai q idioi pame pali
}while(countpq<2);

	gmp_printf ("p = %Zd\n", p);
	gmp_printf ("q = %Zd\n", q);
mpz_mul(n,p,q); //calculate p*q
	gmp_printf ("n = p*q = %Zd\n", n);
mpz_sub(p_minus_one,p,one);
mpz_sub(q_minus_one,q,one);
	gmp_printf ("p-1 = %Zd\n", p_minus_one);
	gmp_printf ("q-1 = %Zd\n", q_minus_one);
mpz_mul(phi,p_minus_one,q_minus_one);
	gmp_printf ("phi = %Zd\n", phi);

	do{
	mpz_urandomm(e,stat,phi);//create random number e opou < tou phi
    mpz_add(e,e,two);//add two to be bigger the e from ena
	mpz_gcd(gcd,e,phi);
	}while((!(mpz_cmp(gcd,one)==0)));//checking..gcd=1
		gmp_printf ("e = %Zd\n", e);
		gmp_printf ("gcd = %Zd\n", gcd);
	mpz_invert(d_priv,e,phi);//ypologismos antistrofou e mod phi
		gmp_printf ("private key (d) = %Zd\n", d_priv);
			gmp_printf ("public key (n,e) = (%Zd , %Zd)\n", n,e);
////// convert myText to myIntegerText
		    str_len = strlen(mystring);
		    if(mystring[str_len - 1] == '\n')
		       mystring[str_len - 1] = '\0';
		       str_len = strlen(mystring);
		       printf("%s -> %ld \n", mystring, str_len);
		              for(i = str_len - 1; i >= 0; i--){
		                  c = mystring[i];
		                  mpz_mul_ui(ro,ro,BASE); // r=r*BASE
		                  mpz_add_ui(ro, ro, c);     // r=r+c
		              	  }//now ro is mystring as Integers
		     gmp_printf("My text is: %s and has %ld chars.\nAs Integer is:%Zd",mystring, strlen(mystring), ro);
////// encrypt text
		     mpz_powm(encrypted,ro,e,n);//
		     gmp_printf("\nEncrypted message is: %Zd",encrypted);
		     ////
//// create encrypted file
		     fp= fopen("encrypted_file.txt","w");
		     fprintf(fp, encrypted);
		     fclose(fp);
		     ////
////// decrypt text
		     mpz_powm(decrypted,encrypted,d_priv,n);//
		     gmp_printf("\nDecrypted message is: %Zd",decrypted);
////// convert myIntegerText to myText
		     mpz_set(str_int, ro);//integerText to mytext
		     mpz_set_ui(max_int, 1UL);//larger int set
		     for(i = 0; i < 10; i++){// maxlength =100
		         if(mpz_cmp(str_int, max_int) <= 0){
		        	str_len = i;
		        	break;}
		         mpz_mul_ui(max_int, max_int, BASE);}
		     for(i = 0; i < str_len; i++){
		     mpz_mod_ui(c_int, str_int,BASE);        // ekxoreitai sthn metablhth c_int=str_int mod BASE
		     mpz_sub(str_int, str_int, c_int);
		     mpz_tdiv_q_ui(str_int, str_int,BASE);
		     mystring[i] = mpz_get_ui(c_int);}
		     mystring[str_len] = '\0';
		     //printf("Num of Chars--> %ld\n", str_len);
///////plaintext
		     gmp_printf("\nPlaintext message is: %s",mystring);
mpz_clear(n_prime);
mpz_clear(n);//clear
mpz_clear(three);
mpz_clear(a);
mpz_clear(two);
mpz_clear(seed);
mpz_clear(one);
mpz_clear(d);
mpz_clear(n_minus_one);
mpz_clear(psi);
mpz_clear(p);
mpz_clear(q);
mpz_clear(phi);
mpz_clear(p_minus_one);
mpz_clear(q_minus_one);
mpz_clear(e);
mpz_clear(gcd);
	mpz_clear(d_priv);
	mpz_clear(ro);
    mpz_clear(max_int);
    mpz_clear(c_int);
    mpz_clear(str_int);
	mpz_clear(t2);
	mpz_clear(encrypted);
	mpz_clear(decrypted);
	return 0;
}