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;
}
Example #2
0
int main(int argc, char* argv[]) {
  int i;
  u8 ecount_buf[0x10], iv[0x10];
  size_t countp;
  int num;
  Self_Segment* segment_ptr;

  memset(zero_padding, 0, sizeof(zero_padding));

#ifdef NPDRM
  if(argc < 4) {
    printf("usage: %s input.elf output.self <content_id>\n", argv[0]);
    printf("  warning NPDRM cares about the output file name, do not rename\n");
    return 1;
  }
#else
  if(argc < 3) {
    printf("usage: %s input.elf output.self\n", argv[0]);
    return 1;
  }
#endif

// init randomness
  gmp_randinit_default(r_state);
  gmp_randseed_ui(r_state, time(NULL));

// read elf file
  read_elf_file(argv[1]);
  input_elf_header = (Elf64_Ehdr*)input_elf_data;

  printf("ELF header size @ %x\n", get_u16(&(input_elf_header->e_ehsize)) );
  printf("%d program headers @ %llx\n", get_u16(&(input_elf_header->e_phnum)), get_u64(&(input_elf_header->e_phoff)));
  printf("%d section headers @ %llx\n", get_u16(&(input_elf_header->e_shnum)), get_u64(&(input_elf_header->e_shoff)));

// loop through the segments
  enumerate_segments();
  printf("segments enumerated\n");

// setup self headers
  Self_Shdr output_self_header; memset(&output_self_header, 0, sizeof(output_self_header));
  Self_Ehdr output_extended_self_header; memset(&output_extended_self_header, 0, sizeof(output_extended_self_header));
  Self_Ihdr output_self_info_header; memset(&output_self_info_header, 0, sizeof(output_self_info_header));
  
  init_Self_Shdr(&output_self_header);
  init_Self_Ehdr(&output_extended_self_header);
  init_Self_Ihdr(&output_self_info_header);

  set_u64(&output_self_header.s_exsize, input_elf_len);

// setup segment header
  segment_certification_header segment_header; memset(&segment_header, 0, sizeof(segment_header));
  set_u32(&(segment_header.version), 1);

// NPDRM
#ifdef NPDRM
  Self_NPDRM npdrm; memset(&npdrm, 0, sizeof(npdrm));
  init_Self_NPDRM(&npdrm, argv[3], argv[2]);
#endif
// useless bullshit
  Self_SDKversion sdkversion;
  Self_Cflags cflags;
  memcpy(&sdkversion, sdkversion_static, sizeof(Self_SDKversion));
  memcpy(&cflags, cflags_static, sizeof(Self_Cflags));

// generate metadata encryption keys
  metadata_crypt_header md_header; memset(&md_header, 0, sizeof(md_header));
  memcpy(&md_header, KEY(keypair_d), sizeof(md_header));

// can't generate random without symmetric keys
/*mpz_t bigriv, bigerk;
  mpz_init(bigriv); mpz_init(bigerk);
  mpz_urandomb(bigerk, r_state, 128);
  mpz_urandomb(bigriv, r_state, 128);

  mpz_export(md_header.erk, &countp, 1, 0x10, 1, 0, bigerk);
  mpz_export(md_header.riv, &countp, 1, 0x10, 1, 0, bigriv);*/

// init signing shit
  mpz_t n,k,da,kinv,r,cs,z;
  mpz_init(n); mpz_init(k); mpz_init(da); mpz_init(r); mpz_init(cs); mpz_init(z); mpz_init(kinv);
  mpz_import(r, 0x14, 1, 1, 0, 0, KEY(R));
  mpz_import(n, 0x14, 1, 1, 0, 0, KEY(n));
  mpz_import(k, 0x14, 1, 1, 0, 0, KEY(K));
  mpz_import(da, 0x14, 1, 1, 0, 0, KEY(Da));
  mpz_invert(kinv, k, n);
  segment_certification_sign all_signed; memset(&all_signed, 0, sizeof(all_signed));
  mpz_export(all_signed.R, &countp, 1, 0x14, 1, 0, r);

// **** everything here is still length independent ***
  build_segment_crypt_data();
  set_u32(&(segment_header.crypt_len), (segment_crypt_data_len)/0x10);
  set_u32(&(segment_header.unknown2), 0x30);    // needed??
  printf("built crypt data\n");

// start building metadata in theory, ordering is fixed now
  memset(&start_file, 0, sizeof(file_ll));
  running_size = 0;
  // 0x000 -- Self_Shdr
  add_file_section(&output_self_header, sizeof(output_self_header));
  // 0x020 -- Self_Ehdr
  add_file_section(&output_extended_self_header, sizeof(output_extended_self_header));
  // 0x070 -- Self_Ihdr
  set_u64(&(output_extended_self_header.e_ihoff), running_size);
  add_file_section(&output_self_info_header, sizeof(output_self_info_header));
  // 0x090 -- elf data
  set_u64(&(output_extended_self_header.e_ehoff), running_size);
  set_u64(&(output_extended_self_header.e_phoff), running_size+get_u64(&(input_elf_header->e_phoff)));
  add_file_section(input_elf_data, get_u64(&(input_elf_header->e_phoff)) + get_u16(&(input_elf_header->e_phnum)) * sizeof(Elf64_Phdr));
  add_file_section(zero_padding, (0x10-(running_size&0xF))&0xF);
  // 0x*** -- all Self_PMhdr(including not in crypt)
  set_u64(&(output_extended_self_header.e_pmoff), running_size);
  segment_ptr = &first_segment;
  while(segment_ptr != NULL) {
    add_file_section(&(segment_ptr->pmhdr), sizeof(segment_ptr->pmhdr));
    segment_ptr = segment_ptr->next_segment;
  }
  // 0x*** -- Self_SDKversion
  set_u64(&(output_extended_self_header.e_svoff), running_size);
  add_file_section(&sdkversion, sizeof(sdkversion));
  // 0x*** -- Self_Cflags
  set_u64(&(output_extended_self_header.e_cfoff), running_size);
  add_file_section(&cflags, sizeof(cflags));
#ifdef NPDRM
  // 0x*** -- npdrm data
  add_file_section(&npdrm, sizeof(npdrm));
#endif
  // 0x*** -- metadata_crypt_header
  set_u32(&(output_self_header.s_esize), running_size - sizeof(output_self_header));
  add_file_section(&md_header, sizeof(md_header));
  // 0x*** -- segment_certification_header
  add_file_section(&segment_header, sizeof(segment_header));
  // 0x*** -- all segment_certification_segment incrypt
  int incrypt_count = 0;
  segment_ptr = &first_segment;
  while(segment_ptr != NULL) {
    if(segment_ptr->incrypt) {
      add_file_section(&(segment_ptr->enc_segment), sizeof(segment_ptr->enc_segment));
      incrypt_count++;
    }
    segment_ptr = segment_ptr->next_segment;
  }
  set_u32(&(segment_header.segment_count), incrypt_count);
  // 0x*** -- segment_crypt_data
  add_file_section(segment_crypt_data, segment_crypt_data_len);
  // 0x*** -- nubpadding_static
  add_file_section(nubpadding_static, sizeof(nubpadding_static));
  // 0x*** -- segment_certification_sign
  set_u64(&(segment_header.signature_offset), running_size);
  add_file_section(&all_signed, sizeof(all_signed));
  // 0x*** -- data must be 0x80 aligned
  if((running_size%0x80) != 0) {
    add_file_section(zero_padding, 0x80-(running_size%0x80));
  }
  // 0x*** -- data
  set_u64(&(output_self_header.s_shsize), running_size);
  // ...data...
  segment_ptr = &first_segment;
  while(segment_ptr != NULL) {
    set_u64(&(segment_ptr->enc_segment.segment_offset), running_size);
    set_u64(&(segment_ptr->pmhdr.pm_offset), running_size);
    add_file_section(segment_ptr->data, segment_ptr->len);
    add_file_section(zero_padding, segment_ptr->padding);
    segment_ptr = segment_ptr->next_segment;
  }
  // 0x*** -- section table
#ifndef SPRX
  set_u64(&(output_extended_self_header.e_shoff), running_size);
  add_file_section(input_elf_data+get_u64(&(input_elf_header->e_shoff)), get_u16(&(input_elf_header->e_shnum)) * sizeof(Elf64_Shdr));
#endif
  // ***DONE***

  printf("file built\n");

// write self file in memory <-- useful comment
  write_self_file_in_memory();
  printf("self written in memory\n");

// sign shit
  u8 digest[0x14];
  SHA1(output_self_data, get_u64(&(segment_header.signature_offset)), digest);

  mpz_import(z, 0x14, 1, 1, 0, 0, digest);
  mpz_mul(cs, r, da); mpz_mod(cs, cs, n);
  mpz_add(cs, cs, z); mpz_mod(cs, cs, n);
  mpz_mul(cs, cs, kinv); mpz_mod(cs, cs, n);
 
  //mpz_export(all_signed.S, &countp, 1, 0x14, 1, 0, cs);
  mpz_export(&output_self_data[get_u64(&output_self_data[get_u32(output_self_data+0xC)+0x60])+0x16], &countp, 1, 0x14, 1, 0, cs);

// encrypt metadata
  int metadata_offset = get_u32(&(output_self_header.s_esize)) + sizeof(Self_Shdr);

#ifndef NO_CRYPT
  memset(ecount_buf, 0, 16); num=0;
  AES_set_encrypt_key(&output_self_data[metadata_offset], 128, &aes_key);
  memcpy(iv, &output_self_data[metadata_offset+0x20], 16);
  AES_ctr128_encrypt(&output_self_data[0x40+metadata_offset], &output_self_data[0x40+metadata_offset], get_u64(&(output_self_header.s_shsize))-metadata_offset-0x40, &aes_key, iv, ecount_buf, &num);
  memcpy(&output_self_data[metadata_offset], KEY(keypair_e), sizeof(md_header));
  /*AES_set_encrypt_key(KEY(erk), 256, &aes_key);
  AES_cbc_encrypt(&output_self_data[metadata_offset], &output_self_data[metadata_offset], 0x40, &aes_key, iv, AES_ENCRYPT);*/
#else
  printf("NO_CRYPT is enabled...self is broken\n");
#endif
  
// write the output self
  FILE *output_self_file = fopen(argv[2], "wb");
  fwrite(output_self_data, 1, running_size, output_self_file);
  fclose(output_self_file);
  return 0;
}
Example #3
0
void
check_rand (void)
{
  gmp_randstate_t rands;
  int            rep, i;
  unsigned long  mant_bits;
  long           exp, exp_min, exp_max;
  double         got, want, d;
  mp_size_t      nalloc, nsize, sign;
  mp_limb_t      nhigh_mask;
  mp_ptr         np;
  
  gmp_randinit_default(rands);
  
  mant_bits = tests_dbl_mant_bits ();
  if (mant_bits == 0)
    return;

  /* Allow for vax D format with exponent 127 to -128 only.
     FIXME: Do something to probe for a valid exponent range.  */
  exp_min = -100 - mant_bits;
  exp_max =  100 - mant_bits;

  /* space for mant_bits */
  nalloc = BITS_TO_LIMBS (mant_bits);
  np = refmpn_malloc_limbs (nalloc);
  nhigh_mask = MP_LIMB_T_MAX
    >> (GMP_NAIL_BITS + nalloc * GMP_NUMB_BITS - mant_bits);

  for (rep = 0; rep < 200; rep++)
    {
      /* random exp_min to exp_max, inclusive */
      exp = exp_min + (long) gmp_urandomm_ui (rands, exp_max - exp_min + 1);

      /* mant_bits worth of random at np */
      if (rep & 1)
        mpn_randomb (np, rands, nalloc);
      else
        mpn_rrandom (np, rands,nalloc);
      nsize = nalloc;
      np[nsize-1] &= nhigh_mask;
      MPN_NORMALIZE (np, nsize);
      if (nsize == 0)
        continue;

      sign = (mp_size_t) gmp_urandomb_ui (rands, 1L) - 1;

      /* want = {np,nsize}, converting one bit at a time */
      want = 0.0;
      for (i = 0, d = 1.0; i < mant_bits; i++, d *= 2.0)
        if (np[i/GMP_NUMB_BITS] & (CNST_LIMB(1) << (i%GMP_NUMB_BITS)))
          want += d;
      if (sign < 0)
        want = -want;

      /* want = want * 2^exp */
      for (i = 0; i < exp; i++)
        want *= 2.0;
      for (i = 0; i > exp; i--)
        want *= 0.5;

      got = mpn_get_d (np, nsize, sign, exp);

      if (got != want)
        {
          printf    ("mpn_get_d wrong on random data\n");
          printf    ("   sign     %ld\n", (long) sign);
          mpn_trace ("   n        ", np, nsize);
          printf    ("   nsize    %ld\n", (long) nsize);
          printf    ("   exp      %ld\n", exp);
          d_trace   ("   want     ", want);
          d_trace   ("   got      ", got);
          abort();
        }
    }

  free (np);
  gmp_randclear(rands);
}
int
main(void)
{
    mp_bitcnt_t depth, w;
    
    gmp_randstate_t state;

    tests_start();
    fflush(stdout);

    gmp_randinit_default(state);

    for (depth = 6; depth <= 12; depth++)
    {
        for (w = 1; w <= 5; w++)
        {
            mp_size_t n = (((mp_limb_t)1)<<depth);
            mp_limb_t trunc;
            mp_size_t limbs = (n*w)/GMP_LIMB_BITS;
            mp_size_t size = limbs + 1;
            mp_size_t i;
            mp_limb_t * ptr;
            mp_limb_t ** ii, ** jj, * t1, * t2, * s1;
        
            mpn_rrandom(&trunc, state, 1);
            trunc = 2*n + trunc % (2 * n) + 1;
            trunc = 2*((trunc + 1)/2);

            ii = malloc((4*(n + n*size) + 3*size)*sizeof(mp_limb_t));
            for (i = 0, ptr = (mp_limb_t *) ii + 4*n; i < 4*n; i++, ptr += size) 
            {
                ii[i] = ptr;
                mpir_random_fermat(ii[i], state, limbs);
            }
            t1 = ptr;
            t2 = t1 + size;
            s1 = t2 + size;
   
            for (i = 0; i < 4*n; i++)
               mpn_normmod_2expp1(ii[i], limbs);
    
            jj = malloc(4*(n + n*size)*sizeof(mp_limb_t));
            for (i = 0, ptr = (mp_limb_t *) jj + 4*n; i < 4*n; i++, ptr += size) 
            {
                jj[i] = ptr;
                mpn_copyi(jj[i], ii[i], size);
            }
   
            mpir_fft_trunc_sqrt2(ii, n, w, &t1, &t2, &s1, trunc);
            mpir_ifft_trunc_sqrt2(ii, n, w, &t1, &t2, &s1, trunc);
            for (i = 0; i < trunc; i++)
            {
                mpn_div_2expmod_2expp1(ii[i], ii[i], limbs, depth + 2);
                mpn_normmod_2expp1(ii[i], limbs);
            }

            for (i = 0; i < trunc; i++)
            {
                if (mpn_cmp(ii[i], jj[i], size) != 0)
                {
                    printf("FAIL:\n");
                    printf("n = %ld, trunc = %ld\n", n, trunc);
                    printf("Error in entry %ld\n", i);
                    abort();
                }
            }

            free(ii);
            free(jj);
        }
    }

    gmp_randclear(state);
    
    tests_end();
    return 0;
}
Example #5
0
/* Check divide and conquer division routine. */
void
check_dc_divappr_q_n (void)
{
   mp_limb_t tp[DC_DIVAPPR_Q_N_ITCH(MAX_LIMBS)];
   mp_limb_t np[2*MAX_LIMBS];
   mp_limb_t np2[2*MAX_LIMBS];
   mp_limb_t rp[2*MAX_LIMBS];
   mp_limb_t dp[MAX_LIMBS];
   mp_limb_t qp[MAX_LIMBS];
   mp_limb_t dip, d1ip;

   mp_size_t nn, rn, dn, qn;

   gmp_randstate_t rands;

   int i, j, s;
   gmp_randinit_default(rands);
  
   for (i = 0; i < ITERS; i++)
   {
      dn = (random() % (MAX_LIMBS - 6)) + 6;
      nn = 2*dn;
         
      mpn_rrandom (np, rands, nn);
      mpn_rrandom (dp, rands, dn);
      dp[dn-1] |= GMP_LIMB_HIGHBIT;

      MPN_COPY(np2, np, nn);
      
      mpir_invert_pi2(dip, d1ip, dp[dn - 1], dp[dn - 2]);
      
      qn = nn - dn + 1;
         
      qp[qn - 1] = mpn_dc_divappr_q_n(qp, np, dp, dn, dip, d1ip, tp);
      
      MPN_NORMALIZE(qp, qn);

      if (qn)
      {
         if (qn >= dn) mpn_mul(rp, qp, qn, dp, dn);
         else mpn_mul(rp, dp, dn, qp, qn);

         rn = dn + qn;
         MPN_NORMALIZE(rp, rn);

         s = (rn < nn) ? -1 : (rn > nn) ? 1 : mpn_cmp(rp, np2, nn);
         if (s <= 0) 
         {
            mpn_sub(rp, np2, nn, rp, rn);
            rn = nn;
            MPN_NORMALIZE(rp, rn);
         } else 
         {
            mpn_sub(rp, rp, rn, np2, nn);
            MPN_NORMALIZE(rp, rn);
         }
      } else
      {
         rn = nn;
         MPN_COPY(rp, np, nn);
      }
      
      s = (rn < dn) ? -1 : (rn > dn) ? 1 : mpn_cmp(rp, dp, dn);
      if (s >= 0)
      {
         printf ("failed:\n");
         printf ("nn = %lu, dn = %lu, qn = %lu, rn = %lu\n\n", nn, dn, qn, rn);
         gmp_printf (" np: %Nx\n\n", np2, nn);
         gmp_printf (" dp: %Nx\n\n", dp, dn);
         gmp_printf (" qp: %Nx\n\n", qp, qn);
         gmp_printf (" rp: %Nx\n\n", rp, rn);
         abort ();
      }
   }

   gmp_randclear(rands);
}
Example #6
0
/* Check divide and conquer division routine. */
void
check_dc_div_qr (void)
{
    mp_limb_t np[2*MAX_LIMBS];
    mp_limb_t np2[2*MAX_LIMBS];
    mp_limb_t rp[2*MAX_LIMBS+1];
    mp_limb_t dp[MAX_LIMBS];
    mp_limb_t qp[2*MAX_LIMBS];
    mp_limb_t dip, d1ip, cy;

    mp_size_t nn, rn, dn, qn;

    gmp_randstate_t rands;

    int i, j, s;
    gmp_randinit_default(rands);

    for (i = 0; i < ITERS; i++)
    {
        dn = (random() % (MAX_LIMBS - 5)) + 6;
        nn = (random() % (MAX_LIMBS - 3)) + dn + 3;

        mpn_rrandom (np, rands, nn);
        mpn_rrandom (dp, rands, dn);
        dp[dn-1] |= GMP_LIMB_HIGHBIT;

        MPN_COPY(np2, np, nn);

        mpir_invert_pi2(dip, d1ip, dp[dn - 1], dp[dn - 2]);

        qn = nn - dn + 1;

        qp[qn - 1] = mpn_dc_div_qr(qp, np, nn, dp, dn, dip, d1ip);

        MPN_NORMALIZE(qp, qn);

        if (qn)
        {
            if (qn >= dn) mpn_mul(rp, qp, qn, dp, dn);
            else mpn_mul(rp, dp, dn, qp, qn);

            rn = dn + qn;
            MPN_NORMALIZE(rp, rn);

            if (rn > nn)
            {
                printf("failed: q*d has too many limbs\n");
                abort();
            }

            if (mpn_cmp(rp, np2, nn) > 0)
            {
                printf("failed: remainder negative\n");
                abort();
            }

            mpn_sub(rp, np2, nn, rp, rn);
            rn = nn;
            MPN_NORMALIZE(rp, rn);
        } else
        {
            rn = nn;
            MPN_COPY(rp, np, nn);
        }

        s = (rn < dn) ? -1 : (rn > dn) ? 1 : mpn_cmp(rp, dp, dn);
        if (s >= 0)
        {
            printf ("failed:\n");
            printf ("nn = %lu, dn = %lu, qn = %lu, rn = %lu\n\n", nn, dn, qn, rn);
            gmp_printf (" np: %Nx\n\n", np2, nn);
            gmp_printf (" dp: %Nx\n\n", dp, dn);
            gmp_printf (" qp: %Nx\n\n", qp, qn);
            gmp_printf (" rp: %Nx\n\n", rp, rn);
            abort ();
        }

        if (mpn_cmp(rp, np, rn) != 0)
        {
            printf("failed: remainder does not match\n");
            gmp_printf (" np: %Nx\n\n", np2, nn);
            gmp_printf (" dp: %Nx\n\n", dp, dn);
            gmp_printf (" qp: %Nx\n\n", qp, qn);
            gmp_printf (" rp: %Nx\n\n", rp, rn);
            gmp_printf (" rp2: %Nx\n\n", np, rn);
        }
    }

    gmp_randclear(rands);
}
Example #7
0
int
main (int argc, char **argv)
{
  mpz_t dividend;
  mpz_t quotient, remainder;
  mpz_t quotient2, remainder2;
  mpz_t temp;
  mp_size_t dividend_size;
  mpir_ui divisor;
  int i;
  int reps = 10000;
  gmp_randstate_t rands;
  mpz_t bs;
  mpir_ui bsi, size_range;
  mpir_ui r_rq, r_q, r_r, r;

  tests_start ();
  gmp_randinit_default(rands);

  mpz_init (bs);

  if (argc == 2)
     reps = atoi (argv[1]);

  mpz_init (dividend);
  mpz_init (quotient);
  mpz_init (remainder);
  mpz_init (quotient2);
  mpz_init (remainder2);
  mpz_init (temp);

  for (i = 0; i < reps; i++)
    {
      mpz_urandomb (bs, rands, 32);
      size_range = mpz_get_ui (bs) % 10 + 2; /* 0..2047 bit operands */

      do
	{
	  mpz_rrandomb (bs, rands, 64);
	  divisor = mpz_get_ui (bs);
	}
      while (divisor == 0);

      mpz_urandomb (bs, rands, size_range);
      dividend_size = mpz_get_ui (bs);
      mpz_rrandomb (dividend, rands, dividend_size);

      mpz_urandomb (bs, rands, 2);
      bsi = mpz_get_ui (bs);
      if ((bsi & 1) != 0)
	mpz_neg (dividend, dividend);

      /* printf ("%ld\n", SIZ (dividend)); */

      r_rq = mpz_cdiv_qr_ui (quotient, remainder, dividend, divisor);
      r_q = mpz_cdiv_q_ui (quotient2, dividend, divisor);
      r_r = mpz_cdiv_r_ui (remainder2, dividend, divisor);
      r = mpz_cdiv_ui (dividend, divisor);

      /* First determine that the quotients and remainders computed
	 with different functions are equal.  */
      if (mpz_cmp (quotient, quotient2) != 0)
	dump_abort ("quotients from mpz_cdiv_qr_ui and mpz_cdiv_q_ui differ",
		    dividend, divisor);
      if (mpz_cmp (remainder, remainder2) != 0)
	dump_abort ("remainders from mpz_cdiv_qr_ui and mpz_cdiv_r_ui differ",
		    dividend, divisor);

      /* Check if the sign of the quotient is correct.  */
      if (mpz_cmp_ui (quotient, 0) != 0)
	if ((mpz_cmp_ui (quotient, 0) < 0)
	    != (mpz_cmp_ui (dividend, 0) < 0))
	dump_abort ("quotient sign wrong", dividend, divisor);

      /* Check if the remainder has the opposite sign as the (positive) divisor
	 (quotient rounded towards minus infinity).  */
      if (mpz_cmp_ui (remainder, 0) != 0)
	if (mpz_cmp_ui (remainder, 0) > 0)
	  dump_abort ("remainder sign wrong", dividend, divisor);

      mpz_mul_ui (temp, quotient, divisor);
      mpz_add (temp, temp, remainder);
      if (mpz_cmp (temp, dividend) != 0)
	dump_abort ("n mod d != n - [n/d]*d", dividend, divisor);

      mpz_abs (remainder, remainder);
      if (mpz_cmp_ui (remainder, divisor) >= 0)
	dump_abort ("remainder greater than divisor", dividend, divisor);

      if (mpz_cmp_ui (remainder, r_rq) != 0)
	dump_abort ("remainder returned from mpz_cdiv_qr_ui is wrong",
		    dividend, divisor);
      if (mpz_cmp_ui (remainder, r_q) != 0)
	dump_abort ("remainder returned from mpz_cdiv_q_ui is wrong",
		    dividend, divisor);
      if (mpz_cmp_ui (remainder, r_r) != 0)
	dump_abort ("remainder returned from mpz_cdiv_r_ui is wrong",
		    dividend, divisor);
      if (mpz_cmp_ui (remainder, r) != 0)
	dump_abort ("remainder returned from mpz_cdiv_ui is wrong",
		    dividend, divisor);
    }

  mpz_clear (bs);
  mpz_clear (dividend);
  mpz_clear (quotient);
  mpz_clear (remainder);
  mpz_clear (quotient2);
  mpz_clear (remainder2);
  mpz_clear (temp);
  gmp_randclear(rands);
  tests_end ();
  exit (0);
}
Example #8
0
int
main (void)
{
    gmp_randstate_t rands;
    int j, n;
    mp_limb_t cp1[1000], cp2[1000], mp[1000], tp1[1000], tp2[1000], inv;

    tests_start ();
    gmp_randinit_default (rands);

    for (n = 1; n < 100; n++)
    {
        for (j = 1; j < 100; j++)
        {
            mpn_randomb (mp, rands, n);
            mp[0] |= 1;
            modlimb_invert (inv, mp[0]);
            inv = -inv;
            mpn_randomb (tp1, rands, 2 * n);
            MPN_COPY (tp2, tp1, 2 * n);
            ref_redc_1 (cp1, tp1, mp, n, inv);
            mpn_redc_1 (cp2, tp2, mp, n, inv);
            if (mpn_cmp (cp1, cp2, n) != 0)
            {
                printf ("mpn_redc_1 error %d\n", n);
                abort ();
            }
            if (n != 1 && mpn_cmp (tp1, tp2, 2 * n) != 0)
            {
                printf ("mpn_redc_1 possible error\n");
                abort ();
            }
            /* we dont require the above to be the same but it could be a useful test */
        }
    }
    for (n = 1; n < 100; n++)
    {
        for (j = 1; j < 100; j++)
        {
            mpn_rrandom (mp, rands, n);
            mp[0] |= 1;
            modlimb_invert (inv, mp[0]);
            inv = -inv;
            mpn_rrandom (tp1, rands, 2 * n);
            MPN_COPY (tp2, tp1, 2 * n);
            ref_redc_1 (cp1, tp1, mp, n, inv);
            mpn_redc_1 (cp2, tp2, mp, n, inv);
            if (mpn_cmp (cp1, cp2, n) != 0)
            {
                printf ("mpn_redc_1 error %d\n", n);
                abort ();
            }
            if (n != 1 && mpn_cmp (tp1, tp2, 2 * n) != 0)
            {
                printf ("mpn_redc_1 possible error\n");
                abort ();
            }
            /* we dont require the above to be the same but it could be a useful test */
        }
    }

    gmp_randclear (rands);
    tests_end ();
    exit (0);
}
Example #9
0
int
main (int argc, char *argv[])
{
  gmp_randstate_t rs;
  mpz_t p, q, pq, pm1, qm1, phi, e, d, p_i_q, dp, dq, msg[1024], smsg;
  unsigned long int n, i, niter, t0, ti;
  double t, f, ops_per_sec;
  int decimals;

  if (argc != 2)
    {
      fprintf (stderr, "usage: %s n\n", argv[0]);
      fprintf (stderr, "  where n is number of bits in numbers tested\n");
      return -1;
    }

  if (argc == 2)
    n = atoi (argv[1]);

  gmp_randinit_default (rs);
  mpz_init (p);
  mpz_init (q);
  mpz_init (pq);

  printf ("Generating p, q, d..."); fflush (stdout);

#if 0
  mpz_urandomb (p, rs, n/2);
  mpz_setbit (p, n / 2 - 1);
  mpz_setbit (p, n / 2 - 2);
  mpz_nextprime (p, p);

  mpz_urandomb (q, rs, n/2);
  mpz_setbit (q, n / 2 - 1);
  mpz_setbit (q, n / 2 - 2);
  mpz_nextprime (q, q);
#else
  do
    {
      mpz_urandomb (p, rs, n/2);
      mpz_setbit (p, n / 2 - 1);
      mpz_setbit (p, n / 2 - 2);
      mpz_setbit (p, 0);

      mpz_urandomb (q, rs, n/2);
      mpz_setbit (q, n / 2 - 1);
      mpz_setbit (q, n / 2 - 2);
      mpz_setbit (q, 0);

      mpz_gcd (pq, p, q);
    }
  while (mpz_cmp_ui (pq, 1) != 0);
#endif

  mpz_mul (pq, p, q);

  mpz_init_set_ui (e, RSA_EXP);
  mpz_init (d);
  mpz_init (pm1);
  mpz_init (qm1);
  mpz_init (phi);

  mpz_sub_ui (pm1, p, 1);
  mpz_sub_ui (qm1, q, 1);
  mpz_mul (phi, pm1, qm1);
  if (mpz_invert (d, e, phi) == 0)
    abort ();

  printf ("done; pq is %d bits\n", (int) mpz_sizeinbase (pq, 2));

  printf ("Precomputing CRT constants\n");

  mpz_init (p_i_q);
  if (mpz_invert (p_i_q, p, q) == 0)
    abort ();

  mpz_init (dp);
  mpz_init (dq);
  mpz_mod (dp, d, pm1);
  mpz_mod (dq, d, qm1);

  printf ("Generating random messages\n");

  for (i = 0; i < 1024; i++)
    {
      mpz_init (msg[i]);
      mpz_urandomb (msg[i], rs, n);
    }
  mpz_init (smsg);

  printf ("Calibrating CPU speed...");  fflush (stdout);
  TIME (t, rsa_sign (smsg, msg[0], p, q, pq, p_i_q, dp, dq));
  printf ("done\n");

  niter = (unsigned long) (1e4 / t);
  if (niter == 0)
    niter = 1;
  printf ("Signing random messages %lu times...", niter);  fflush (stdout);
  t0 = cputime ();
  for (i = niter; i > 0; i--)
    {
      rsa_sign (smsg, msg[i % 1024], p, q, pq, p_i_q, dp, dq);
    }
  ti = cputime () - t0;
  printf ("done!\n");

  ops_per_sec = 1000.0 * niter / ti;
  f = 100.0;
  for (decimals = 0;; decimals++)
    {
      if (ops_per_sec > f)
	break;
      f = f * 0.1;
    }

  printf ("RESULT: %.*f operations per second\n", decimals, ops_per_sec);
  return 0;
}
Example #10
0
int
main (int argc, char *argv[])
{
  int  i;
  int  opt;

  /* Unbuffered so output goes straight out when directed to a pipe or file
     and isn't lost on killing the program half way.  */
  setbuf (stdout, NULL);

  for (;;)
    {
      opt = getopt(argc, argv, "a:CcDdEFf:o:p:P:rRs:t:ux:y:w:W:z");
      if (opt == EOF)
        break;

      switch (opt) {
      case 'a':
        if (strcmp (optarg, "random") == 0)       option_data = DATA_RANDOM;
        else if (strcmp (optarg, "random2") == 0) option_data = DATA_RANDOM2;
        else if (strcmp (optarg, "zeros") == 0)   option_data = DATA_ZEROS;
        else if (strcmp (optarg, "aas") == 0)     option_data = DATA_AAS;
        else if (strcmp (optarg, "ffs") == 0)     option_data = DATA_FFS;
        else if (strcmp (optarg, "2fd") == 0)     option_data = DATA_2FD;
        else
          {
            fprintf (stderr, "unrecognised data option: %s\n", optarg);
            exit (1);
          }
        break;
      case 'C':
        if (option_unit  != UNIT_SECONDS) goto bad_unit;
        option_unit = UNIT_CYCLESPERLIMB;
        break;
      case 'c':
        if (option_unit != UNIT_SECONDS)
          {
          bad_unit:
            fprintf (stderr, "cannot use more than one of -c, -C\n");
            exit (1);
          }
        option_unit = UNIT_CYCLES;
        break;
      case 'D':
        if (option_cmp != CMP_ABSOLUTE) goto bad_cmp;
        option_cmp = CMP_DIFFPREV;
        break;
      case 'd':
        if (option_cmp != CMP_ABSOLUTE)
          {
          bad_cmp:
            fprintf (stderr, "cannot use more than one of -d, -D, -r\n");
            exit (1);
          }
        option_cmp = CMP_DIFFERENCE;
        break;
      case 'E':
        option_square = 1;
        break;
      case 'F':
        option_square = 2;
        break;
      case 'f':
        option_factor = atof (optarg);
        if (option_factor <= 1.0)
          {
            fprintf (stderr, "-f factor must be > 1.0\n");
            exit (1);
          }
        break;
      case 'o':
        speed_option_set (optarg);
        break;
      case 'P':
        option_gnuplot = 1;
        option_gnuplot_basename = optarg;
        break;
      case 'p':
        speed_precision = atoi (optarg);
        break;
      case 'R':
        option_seed = time (NULL);
        break;
      case 'r':
        if (option_cmp != CMP_ABSOLUTE)
          goto bad_cmp;
        option_cmp = CMP_RATIO;
        break;
      case 's':
        {
          char  *s;
          for (s = strtok (optarg, ","); s != NULL; s = strtok (NULL, ","))
            {
              if (size_num == size_allocnum)
                {
                  size_array = (struct size_array_t *)
                    __gmp_allocate_or_reallocate
                    (size_array,
                     size_allocnum * sizeof(size_array[0]),
                     (size_allocnum+10) * sizeof(size_array[0]));
                  size_allocnum += 10;
                }
              if (sscanf (s, "%ld-%ld",
                          &size_array[size_num].start,
                          &size_array[size_num].end) != 2)
                {
                  size_array[size_num].start = size_array[size_num].end
                    = atol (s);
                }

              if (size_array[size_num].start < 0
                  || size_array[size_num].end < 0
                  || size_array[size_num].start > size_array[size_num].end)
                {
                  fprintf (stderr, "invalid size parameter: %s\n", s);
                  exit (1);
                }

              size_num++;
            }
        }
        break;
      case 't':
        option_step = atol (optarg);
        if (option_step < 1)
          {
            fprintf (stderr, "-t step must be >= 1\n");
            exit (1);
          }
        break;
      case 'u':
        option_resource_usage = 1;
        break;
      case 'z':
        sp.cache = 1;
        break;
      case 'x':
        sp.align_xp = atol (optarg);
        check_align_option ("-x", sp.align_xp);
        break;
      case 'y':
        sp.align_yp = atol (optarg);
        check_align_option ("-y", sp.align_yp);
        break;
      case 'w':
        sp.align_wp = atol (optarg);
        check_align_option ("-w", sp.align_wp);
        break;
      case 'W':
        sp.align_wp2 = atol (optarg);
        check_align_option ("-W", sp.align_wp2);
        break;
      case '?':
        exit(1);
      }
    }

  if (optind >= argc)
    {
      usage ();
      exit (1);
    }

  if (size_num == 0)
    {
      fprintf (stderr, "-s <size> must be specified\n");
      exit (1);
    }

  gmp_randinit_default (__gmp_rands);
  __gmp_rands_initialized = 1;
  gmp_randseed_ui (__gmp_rands, option_seed);

  choice = (struct choice_t *) (*__gmp_allocate_func)
    ((argc - optind) * sizeof(choice[0]));
  for ( ; optind < argc; optind++)
    {
      struct choice_t  c;
      routine_find (&c, argv[optind]);
      choice[num_choices] = c;
      num_choices++;
    }

  if ((option_cmp == CMP_RATIO || option_cmp == CMP_DIFFERENCE) &&
      num_choices < 2)
    {
      fprintf (stderr, "WARNING, -d or -r does nothing when only one routine requested\n");
    }

  speed_time_init ();
  if (option_unit == UNIT_CYCLES || option_unit == UNIT_CYCLESPERLIMB)
    speed_cycletime_need_cycles ();
  else
    speed_cycletime_need_seconds ();

  if (option_gnuplot)
    {
      run_gnuplot (argc, argv);
    }
  else
    {
      if (option_unit == UNIT_SECONDS)
        printf ("overhead %.9f secs", speed_measure (speed_noop, NULL));
      else
        printf ("overhead %.2f cycles",
                speed_measure (speed_noop, NULL) / speed_cycletime);
      printf (", precision %d units of %.2e secs",
              speed_precision, speed_unittime);

      if (speed_cycletime == 1.0 || speed_cycletime == 0.0)
        printf (", CPU freq unknown\n");
      else
        printf (", CPU freq %.2f MHz\n", 1e-6/speed_cycletime);

      printf ("       ");
      for (i = 0; i < num_choices; i++)
        printf (" %*s", COLUMN_WIDTH, choice[i].name);
      printf ("\n");

      run_all (stdout);
    }

  if (option_resource_usage)
    {
#if HAVE_GETRUSAGE
      {
        /* This doesn't give data sizes on linux 2.0.x, only utime. */
        struct rusage  r;
        if (getrusage (RUSAGE_SELF, &r) != 0)
          perror ("getrusage");
        else
          printf ("getrusage(): utime %ld.%06ld data %ld stack %ld maxresident %ld\n",
                  r.ru_utime.tv_sec, r.ru_utime.tv_usec,
                  r.ru_idrss, r.ru_isrss, r.ru_ixrss);
      }
#else
      printf ("getrusage() not available\n");
#endif

      /* Linux kernel. */
      {
        char  buf[128];
        sprintf (buf, "/proc/%d/status", getpid());
        if (access (buf, R_OK) == 0)
          {
            sprintf (buf, "cat /proc/%d/status", getpid());
            system (buf);
          }

      }
    }

  return 0;
}
Example #11
0
srp_t *srp_init_l(const gchar *username, guint32 username_length,
        const gchar *password, guint32 password_length)
{
    guint16 i;
    gchar *d; /* destination */
    gchar *du; /* destination; uppercase */
    const gchar *o; /* original */
    srp_t *srp;
    
    srp = g_new0(srp_t, 1);
    if (!srp)
        return NULL;
    
    srp->username_len = username_length;
    srp->password_len = password_length;
    
    srp->username = (gchar *) g_malloc(srp->username_len + 1);
    srp->username_upper = (gchar *) g_malloc(srp->username_len + 1);
    srp->password_upper = (gchar *) g_malloc(srp->password_len + 1);
    if (!srp->username || !srp->username_upper || !srp->password_upper) {
        g_free(srp);
        return NULL;
    }
    
    d = (gchar *) srp->username;
    du = (gchar *) srp->username_upper;
    o = username;
    for (i = 0; i < srp->username_len; i++) {
        *d = *o;
        *du = (gchar) g_ascii_toupper(*o);
        d++;
        du++;
        o++;
    }
    
    d = (gchar *) srp->password_upper;
    o = password;
    for (i = 0; i < srp->password_len; i++) {
        *d = (gchar) g_ascii_toupper(*o);
        d++;
        o++;
    }
    
    *((gchar *) srp->username + username_length) = 0;
    *((gchar *) srp->username_upper + username_length) = 0;
    *((gchar *) srp->password_upper + password_length) = 0;
    
    mpz_init_set_str(srp->n, SRP_VAR_N_STR, 16);
    
    gmp_randinit_default(srp->rand);
    gmp_randseed_ui(srp->rand, srp_pre_seed());
    mpz_init2(srp->a, 256);
    mpz_urandomm(srp->a, srp->rand, srp->n); /* generates the private key */

    /* The following line replaces preceding 2 lines during testing. */
    /*mpz_init_set_str(srp->a, "1234", 10); */

    srp->A = NULL;
    srp->S = NULL;
    srp->K = NULL;
    srp->M1 = NULL;
    srp->M2 = NULL;
    srp->salt = NULL;
    srp->B = NULL;
    
    return srp;
}
Example #12
0
int
main(void)
{
    mp_bitcnt_t depth, w, depth1, w1;
    clock_t start, end;
    double elapsed;
    double best = 0.0;
    mp_size_t best_off, off, best_d, best_w;

    gmp_randstate_t state;

    printf("/* fft_tuning.h -- autogenerated by tune-fft */\n\n");
    printf("#ifndef FFT_TUNING_H\n");
    printf("#define FFT_TUNING_H\n\n");
    printf("#include \"mpir.h\"\n\n");
    printf("#define FFT_TAB \\\n");
    fflush(stdout);

    gmp_randinit_default(state);

    printf("   { "); fflush(stdout);
    for (depth = 6; depth <= 10; depth++)
    {
        printf("{ "); fflush(stdout);
        for (w = 1; w <= 2; w++)
        {
            int iters = 100*((mp_size_t) 1 << (3*(10 - depth)/2)), i;
            
            mp_size_t n = ((mp_limb_t)1<<depth);
            mp_bitcnt_t bits1 = (n*w - (depth + 1))/2; 
            mp_size_t len1 = 2*n;
            mp_size_t len2 = 2*n;

            mp_bitcnt_t b1 = len1*bits1, b2 = len2*bits1;
            mp_size_t n1, n2;
            mp_size_t j;
            mp_limb_t * i1, *i2, *r1;
   
            n1 = (b1 - 1)/GMP_LIMB_BITS + 1;
            n2 = (b2 - 1)/GMP_LIMB_BITS + 1;
                    
            i1 = malloc(2*(n1 + n2)*sizeof(mp_limb_t));
            i2 = i1 + n1;
            r1 = i2 + n2;
   
            mpn_urandomb(i1, state, b1);
            mpn_urandomb(i2, state, b2);
  
            best_off = -1;
            
            for (off = 0; off <= 4; off++)
            {
               start = clock();
               for (i = 0; i < iters; i++)
                  mpn_mul_trunc_sqrt2(r1, i1, n1, i2, n2, depth - off, w*((mp_size_t)1 << (off*2)));
               end = clock();
               
               elapsed = ((double) (end - start)) / CLOCKS_PER_SEC;
               
               if (elapsed < best || best_off == -1)
               {
                  best_off = off;
                  best = elapsed;
               }
            }
           
            printf("%ld", best_off); 
            if (w != 2) printf(",");
            printf(" "); fflush(stdout);

            free(i1);
        }
        printf("}");
        if (depth != 10) printf(",");
        printf(" "); fflush(stdout);
    }

    printf("}\n\n");
    
    best_d = 12;
    best_w = 1;
    best_off = -1;

    printf("#define MULMOD_TAB \\\n");
    fflush(stdout);
    printf("   { "); fflush(stdout);
    for (depth = 12; best_off != 1 ; depth++)
    {
        for (w = 1; w <= 2; w++)
        {
            int iters = 100*((mp_size_t) 1 << (3*(18 - depth)/2)), i;
            mp_size_t n = ((mp_limb_t)1<<depth);
            mp_bitcnt_t bits = n*w;
            mp_size_t int_limbs = (bits - 1)/GMP_LIMB_BITS + 1;
            mp_size_t j;
            mp_limb_t c, * i1, * i2, * r1, * tt;
        
            if (depth <= 21) iters = 32*((mp_size_t) 1 << (21 - depth));
            else iters = MAX(32/((mp_size_t) 1 << (depth - 21)), 1);

            i1 = malloc(6*(int_limbs+1)*sizeof(mp_limb_t));
            i2 = i1 + int_limbs + 1;
            r1 = i2 + int_limbs + 1;
            tt = r1 + 2*(int_limbs + 1);
                
            mpn_urandomb(i1, state, int_limbs*GMP_LIMB_BITS);
            mpn_urandomb(i2, state, int_limbs*GMP_LIMB_BITS);
            i1[int_limbs] = 0;
            i2[int_limbs] = 0;

            depth1 = 1;
            while ((((mp_limb_t)1)<<depth1) < bits) depth1++;
            depth1 = depth1/2;

            w1 = bits/(((mp_limb_t)1)<<(2*depth1));

            best_off = -1;
            
            for (off = 0; off <= 4; off++)
            {
               start = clock();
               for (i = 0; i < iters; i++)
                  mpir_fft_mulmod_2expp1(r1, i1, i2, int_limbs, depth1 - off, w1*((mp_size_t)1 << (off*2)));
               end = clock();
               
               elapsed = ((double) (end - start)) / CLOCKS_PER_SEC;
               
               if (best_off == -1 || elapsed < best)
               {
                  best_off = off;
                  best = elapsed;
               }
            }
           
            start = clock();
            for (i = 0; i < iters; i++)
                mpn_mulmod_2expp1_basecase(r1, i1, i2, 0, bits, tt);
            end = clock();
               
            elapsed = ((double) (end - start)) / CLOCKS_PER_SEC;
            if (elapsed < best)
            {
                best_d = depth + (w == 2);
                best_w = w + 1 - 2*(w == 2);
            }

            printf("%ld", best_off); 
            if (w != 2) printf(", "); fflush(stdout);

            free(i1);
        }
        printf(", "); fflush(stdout);
    }
    printf("1 }\n\n");
    
    printf("#define FFT_N_NUM %ld\n\n", 2*(depth - 12) + 1);
    
    printf("#define FFT_MULMOD_2EXPP1_CUTOFF %ld\n\n", ((mp_limb_t) 1 << best_d)*best_w/(2*GMP_LIMB_BITS));
    
    gmp_randclear(state);
    
    printf("#endif\n");
    return 0;
}
Example #13
0
/*
*   It is a function that performs Miller Rabin Primality test
*   input: number(mpz_t) to be tested and number of iterations(int) to run the test
*   output: int 1 and 0 which represents pass and fail the test respectively
*/
int Miller(mpz_t p, int iterations){
    mpz_t a;
    mpz_init(a);
    mpz_t p4;
    mpz_init(p4);
    mpz_sub_ui(p4, p, 4);
    mpz_t p1;
    mpz_init(p1);
    mpz_sub_ui(p1, p, 1);
    mpz_t x;
    mpz_init(x);
    mpz_t m;
    mpz_init_set_str(m, "1", 10);
    mpz_t val;
    mpz_init(val);

    gmp_randstate_t state;
    srand(time(NULL));
    int seed = rand();
    gmp_randinit_default (state);
    gmp_randseed_ui(state, seed);

    //find t and m
    int check = 0;
    int t = 1;
    while(check != 1){
        mpz_ui_pow_ui(val, 2, t);
        mpz_cdiv_r(m,p1,val);
        if(mpz_cmp_ui(m,0) == 0){
            mpz_cdiv_q(m,p1,val);
            check = 1;
        }
        else{
            t++;
        }
    }

    //step 1
    mpz_urandomb(a,state,64);
    mpz_mod(a, a, p4);
    mpz_add_ui(a, a, 2); //base must not be bigger than p - 2
    //gmp_printf("a = %Zd\n", a);

    //step 2
    mpz_powm(x, a, m, p);
    //gmp_printf("x = %Zd\n", x);
    if(mpz_cmp_ui(x, 1) == 0 || mpz_cmp(x, p1) == 0) return 1;
    else if(t == 1) return 0;
    int j = 1;

    //step 3 & 4
    int capture;
    do
    {
        printf("what is t, %d\n", t);
        capture = step3(j,m,x,a,p,p1);
        printf("capture = %d\n", capture);
        if(capture == 0) return 0;
        else if(capture == 1) return 1;
        else{
            j = capture;
            printf("here when j = %d\n", j);
        }
    }while(j < (t-1));

    //step 5
    capture = step3(j+1, m, x, a, p, p1);
    if(capture == 1) return 1;
    else return 0;

}
int main(int argc, char **argv) {

  //operands
    mpz_t x; mpz_init(x);
    mpz_t y; mpz_init(y);
    mpz_t xsize_z; mpz_init(xsize_z); //for random number generation
    mpz_t ysize_z; mpz_init(ysize_z); //for random number generation

    //GMP random state
    gmp_randstate_t randstate; gmp_randinit_default(randstate);
    gmp_randseed_ui(randstate, time(NULL));

    srand(time(NULL)); //for non-GMP random numbers

    int number_of_bits = 3200;
    int xbits, ybits; //used for generating numbers
    int number_of_tests = 100;
    int printing=0; // whether to print, and the base to print in
    int truncation=0; // whether to use random truncation
    int i,j;  // loop variables

    if(argc >=2)  // recall that first 'argument' is the program name
      number_of_bits = atoi(argv[1]);
    if(argc >=3)
      number_of_tests = atoi(argv[2]);
    if(argc >=4)
      printing=atoi(argv[3]);
    if(argc >=5)
      truncation=atoi(argv[4]);

    double start, finish, elapsed, elapsed_gmp = 0; //timing
    int num_correct = 0, num_wrong = 0; //correctness

    //allocate memory for printing to avoid memory leaks.  Use of
    //number_of_bits is enough to print in binary.
    char *x_str = (char *) malloc((1 + number_of_bits)*sizeof(char));
    char *y_str = (char *) malloc((1 + number_of_bits)*sizeof(char));
    char *z_str = (char *) malloc((1 + 2*number_of_bits)*sizeof(char));
    char *res_str = (char *) malloc((1 + 2*number_of_bits)*sizeof(char));

      void *x_address;
      void *y_address;
      size_t *x_size = malloc(sizeof(size_t));
      size_t *y_size = malloc(sizeof(size_t));
      size_t *z_size = malloc(sizeof(size_t));
      size_t x_bits, y_bits; //used for size of final operands from GMP
      size_t *z_bits = malloc(sizeof(size_t));

    for(j = 0; j < number_of_tests; j++){

      xbits = number_of_bits;
      ybits = number_of_bits;
      if (truncation)
        if (rand() %2) {  // half the time the numbers are about the same size
          ; //do nothing
        } else if (rand() % 2) { // 1/4 the time y is randomly smaller
        ybits = rand() % number_of_bits;
      } else {  // else x is smaller
        xbits = rand() % number_of_bits;
      }
      mpz_ui_pow_ui(xsize_z, 2, xbits); //numsize = 2^numbits
      mpz_ui_pow_ui(ysize_z, 2, ybits); //numsize = 2^numbits
      mpz_urandomm(x, randstate, xsize_z); //actually makes x and y
      mpz_urandomm(y, randstate, ysize_z);
      if (printing)
        printf("x %s\ny %s\n",mpz_get_str(x_str,printing,x),
            mpz_get_str(y_str,printing,y));

      x_address = mpz_export(NULL, x_size, ORDER, WORDBYTES, ENDIAN, NAILS, x);
      y_address = mpz_export(NULL, y_size, ORDER, WORDBYTES, ENDIAN, NAILS, y);

      void *z_address = malloc((*x_size + *y_size)*WORDBYTES);

      x_bits=mynbits(x);
      y_bits=mynbits(y);
      start = mytime();
      Product16(x_address, y_address, z_address, *x_size, x_bits,
          *y_size, y_bits, z_size, z_bits);
      finish = mytime();
      elapsed += finish-start;
//      printf("%g %g %g\n",start, finish, elapsed);

      mpz_t z;
      mpz_init(z);

      mpz_import(z, *z_size, ORDER, WORDBYTES, ENDIAN, NAILS, z_address);
      if (printing)
        printf("code x*y %s\n", mpz_get_str(z_str,printing,z));

      mpz_t result;
      mpz_init(result);
      start = mytime();
      mpz_mul(result,x,y);
      finish = mytime();
      elapsed_gmp += finish-start;
      if (printing)
        printf("GMP  x*y %s\n", mpz_get_str(res_str,printing,result));

      if(mpz_cmp(result,z) == 0)
        num_correct ++;
      else
        num_wrong ++;

      mpz_clear(z);
      mpz_clear(result);
      free(x_address);
      free(y_address);
      free(z_address);
    }

    printf("============================================================\n");
    printf("\n\n");
    printf("Number of bits per number: %d\n", number_of_bits);
    printf("Number of multiplications done: %d\n", number_of_tests);
    printf("Number of correct multiplication: %d\n", num_correct);
    printf("Number of wrong multiplication: %d\n", num_wrong);
    printf("Total time elapsed (code):  %lf seconds\n", ((double) (elapsed)));
    printf("Total time elapsed (GMP):  %lf seconds\n", ((double)
          (elapsed_gmp)));
    printf("Total time ratio (code/GMP):  %lf \n",
        elapsed/elapsed_gmp);
    printf("\n\n");
    printf("============================================================\n");
    return 0;
}
Example #15
0
File: t-mul.c Project: HRF92/mpir
int
main (int argc, char **argv)
{
  mpz_t op1, op2;
  int i;

  gmp_randstate_t rands;
  mpz_t bs;
  unsigned long bsi, size_range, fsize_range;

  tests_start ();
  gmp_randinit_default(rands);

  extra_fft = getenv ("GMP_CHECK_FFT");

  mpz_init (bs);
  mpz_init (op1);
  mpz_init (op2);

  fsize_range = 4 << 8;		/* a fraction 1/256 of size_range */
  for (i = 0; fsize_range >> 8 < (extra_fft ? 27 : 22); i++)
    {
      size_range = fsize_range >> 8;
      fsize_range = fsize_range * 33 / 32;

      mpz_urandomb (bs, rands, size_range);
      mpz_rrandomb (op1, rands, mpz_get_ui (bs));
      mpz_urandomb (bs, rands, size_range);
      mpz_rrandomb (op2, rands, mpz_get_ui (bs));

      mpz_urandomb (bs, rands, 4);
      bsi = mpz_get_ui (bs);
      if ((bsi & 0x3) == 0)
	mpz_neg (op1, op1);
      if ((bsi & 0xC) == 0)
	mpz_neg (op2, op2);

      /* printf ("%d %d\n", SIZ (op1), SIZ (op2)); */
      one (i, op2, op1);
    }

  if (extra_fft)
    for (i = -50; i < 0; i++)
      {
	mpz_urandomb (bs, rands, 32);
	size_range = mpz_get_ui (bs) % 27;

	mpz_urandomb (bs, rands, size_range);
	mpz_rrandomb (op1, rands, mpz_get_ui (bs) + FFT_MIN_BITSIZE);
	mpz_urandomb (bs, rands, size_range);
	mpz_rrandomb (op2, rands, mpz_get_ui (bs) + FFT_MIN_BITSIZE);

	/* printf ("%d: %d %d\n", i, SIZ (op1), SIZ (op2)); */
	fflush (stdout);
	one (-1, op2, op1);
      }

  mpz_clear (bs);
  mpz_clear (op1);
  mpz_clear (op2);
  gmp_randclear(rands);
  tests_end ();
  exit (0);
}
Example #16
0
int
main (int argc, char **argv)
{
  mpz_t base, exp, mod;
  mpz_t r1, r2, base2;
  mp_size_t base_size, exp_size, mod_size;
  unsigned long int exp2;
  int i;
  int reps = 200;
  gmp_randstate_t rands;
  mpz_t bs;
  unsigned long bsi, size_range;

  tests_start ();
  gmp_randinit_default(rands);

  mpz_init (bs);

  if (argc == 2)
     reps = atoi (argv[1]);

  mpz_init (base);
  mpz_init (exp);
  mpz_init (mod);
  mpz_init (r1);
  mpz_init (r2);
  mpz_init (base2);

  for (i = 0; i < reps; i++)
    {
      mpz_urandomb (bs, rands, 32);
      size_range = mpz_get_ui (bs) % 13 + 2;

      do  /* Loop until mathematically well-defined.  */
	{
	  mpz_urandomb (bs, rands, size_range);
	  base_size = mpz_get_ui (bs);
	  mpz_rrandomb (base, rands, base_size);

	  mpz_urandomb (bs, rands, 6L);
	  exp_size = mpz_get_ui (bs);
	  mpz_rrandomb (exp, rands, exp_size);
	  exp2 = mpz_getlimbn (exp, (mp_size_t) 0);
	}
      while (mpz_cmp_ui (base, 0) == 0 && exp2 == 0);

      do
        {
	  mpz_urandomb (bs, rands, size_range);
	  mod_size = mpz_get_ui (bs);
	  mpz_rrandomb (mod, rands, mod_size);
	}
      while (mpz_cmp_ui (mod, 0) == 0);

      mpz_urandomb (bs, rands, 2);
      bsi = mpz_get_ui (bs);
      if ((bsi & 1) != 0)
	mpz_neg (base, base);

      /* printf ("%ld %ld\n", SIZ (base), SIZ (mod)); */

#if 0
      putc ('\n', stderr);
      debug_mp (base, -16);
      debug_mp (mod, -16);
#endif

      mpz_powm_ui (r1, base, exp2, mod);

      mpz_set_ui (r2, 1);
      mpz_set (base2, base);

      mpz_mod (r2, r2, mod);	/* needed when exp==0 and mod==1 */
      while (exp2 != 0)
	{
	  if (exp2 % 2 != 0)
	    {
	      mpz_mul (r2, r2, base2);
	      mpz_mod (r2, r2, mod);
	    }
	  mpz_mul (base2, base2, base2);
	  mpz_mod (base2, base2, mod);
	  exp2 = exp2 / 2;
	}

#if 0
      debug_mp (r1, -16);
      debug_mp (r2, -16);
#endif

      if (mpz_cmp (r1, r2) != 0)
	{
	  fprintf (stderr, "\ntest %d: Incorrect results for operands:\n", i);
	  debug_mp (base, -16);
	  debug_mp (exp, -16);
	  debug_mp (mod, -16);
	  fprintf (stderr, "mpz_powm_ui result:\n");
	  debug_mp (r1, -16);
	  fprintf (stderr, "reference result:\n");
	  debug_mp (r2, -16);
	  abort ();
	}
    }

  mpz_clear (bs);
  mpz_clear (base);
  mpz_clear (exp);
  mpz_clear (mod);
  mpz_clear (r1);
  mpz_clear (r2);
  mpz_clear (base2);
  gmp_randclear(rands);
  tests_end ();
  exit (0);
}
Example #17
0
int main(int argc, const char *argv[])
{
	int res;
	char *str;
	mpz_t largenum;

	if (argc <= 0) {
		fprintf(stderr, "usage: %s\n", argv[0]);
		exit(EXIT_SUCCESS);
	}

	fprintf(stderr, "setting pitch\n");
	orient_range.orient.pitch   = 180;
	orient_range.pitch_range    = 10;

	fprintf(stderr, "setting roll\n");
	orient_range.orient.roll    = 0;
	orient_range.roll_range     = 10;

	fprintf(stderr, "setting azimuth\n");
	orient_range.orient.azimuth = 0;
	orient_range.azimuth_range  = 0;

	mpz_init_set_str(one, "1", 10);
	mpz_init_set_str(two, "2", 10);

	gmp_randinit_default(randstate);

	sleep(1);

	if (syscall(__NR_orientlock_read, &orient_range) == -1) {
		fprintf(stderr, "error: Unable to obtain lock\n");
		exit(EXIT_FAILURE);
	}

	fp = fopen("./integer", "r");

	if ((fgets(integer, INTEGER_BUF_SIZE, fp)) == NULL) {
			fprintf(stderr, "error: Unable to read from file");
			exit(EXIT_FAILURE);
	}
	chomp_line(integer);

	mpz_init(largenum);
	mpz_init_set_str(largenum, integer, 10);

	str = mpz_to_str(largenum);
	if (!str)
		return EXIT_FAILURE;

	/*
	 * We simply return the prime number itself if the base is prime.
	 * (We use the GMP probabilistic function with 10 repetitions).
	 */
	res = mpz_probab_prime_p(largenum, 10);
	if (res) {
		printf("%s is a prime number\n", str);
		free(str);
		mpz_add(largenum, largenum, one);
	}

	printf("Prime factors for %s are:  ", str);
	free(str);

	factor(largenum);
	printf("\n");

	fclose(fp);

	if (syscall(__NR_orientunlock_read, &orient_range) == -1) {
		fprintf(stderr, "error: Unable to unlock\n");
		exit(EXIT_FAILURE);
	}

	return EXIT_SUCCESS;
}
void go(SGLVData *data, int nbiter){
	int i;
	mpz_t  k_rd, ZZ, tmp;
	mpz_inits (k_rd, ZZ, tmp, NULL);
	
	gmp_randstate_t rand_gen;
	unsigned long seed = time(NULL); 
	gmp_randinit_default(rand_gen);
	gmp_randseed_ui(rand_gen, seed);
	
	
	SGLVScalar k;
	JacPoint jp;
	
	struct timespec start1,start2;
    struct timespec end1,end2;
    uint64_t diff1,diff2, diff3;
	
	
	printf("\nSGLV 256 bits benchmark, running...\n\n");
	
	
	diff1 = 0;
	diff2 = 0;
	
	init_jacPoint(&jp);
	
	
	
	for (i = 0; i < nbiter; i++) {
		
		mpz_urandomb (k_rd, rand_gen, BIT_SIZE);
		mpz_mod (k_rd, k_rd,  data->efp);
		
		
		apply_endo(((data->PP)+1), (data->PP), beta); /* Point PHI_P */
		add_aff_aff(((data->PP)+1), (data->PP));      /* Point P+PHI_P */
		
		
		clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start1);
		
		init_glvScalar(&k);
		build_glvScalar(&k, k_rd, data->aa, data->bb, data->Na);
		
		clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end1);
		diff1 += BILLION * (end1.tv_sec - start1.tv_sec) + end1.tv_nsec - start1.tv_nsec; 
		
		clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start1);
		
		point_from_SGLVScalar(&jp, &k, data->PP);
		
		clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end1);
		diff2 += BILLION * (end1.tv_sec - start1.tv_sec) + end1.tv_nsec - start1.tv_nsec; 
		
		mpz_invert (ZZ, jp.Z, p);
		mpz_mul (tmp, ZZ, ZZ); // tmp = ZZ^2
		//~ P is transformed in affine coordinates for next iteration
		mpz_mul (data->PP[0].X, jp.X, tmp);
		mpz_mod (data->PP[0].X, data->PP[0].X, p);
		
		mpz_mul (data->PP[0].Y, jp.Y, tmp);
		mpz_mul (data->PP[0].Y, data->PP[0].Y, ZZ);
		mpz_mod (data->PP[0].Y, data->PP[0].Y, p);
	}
	diff3 = diff1 + diff2;
	
	
	if (is_on_curve_jac(&jp, ca, cb)){ 
		printf("\nMULT: kP OK\n");
		print_jacPoint(&jp);
		printf("Elapsed time = %llu %llu %llu nanoseconds\n", (long long unsigned int) diff1, (long long unsigned int) diff2, (long long unsigned int) diff3);
	}
	else
		printf("MULT: kP non OK\n");
	
	
	mpz_clears (k_rd, ZZ, tmp, NULL);
	free_jacPoint(&jp);
	gmp_randclear(rand_gen);
}