示例#1
0
int main(int argc, const char * argv[]){
	clock_t begin = clock();

    if(argc == 1){
		// standard mode
		mpz_t numbers[NUMBERS];
		list * calculatedFactors[NUMBERS];
		int i;
		mpz_t y;
		mpz_init_set_ui(y, 1);

		for (i = 0; i < NUMBERS; i++){
			mpz_init(numbers[i]);
			mpz_inp_str(numbers[i], stdin, 10);
		}

		for (i = 0; i < NUMBERS; i++) {
			reset_timer();
			list* factors = createList();
			factorize(factors, numbers[i],1, y);
			
			calculatedFactors[i] = factors;
		}

		for (i = 0; i < NUMBERS; i++){
			printFactors(calculatedFactors[i]);
		}

		clock_t end = clock();
		double tdiff = (((double) end) - ((double)begin)) / CLOCKS_PER_SEC;
		printf(", %f\n", tdiff);
		
		return 0;
		
	} else if(strcmp(argv[1], "interactive") == 0){
		// interactive mode
		fprintf(stderr, "Interactive mode!\n");
		
		mpz_t number;
		mpz_init(number);
		list * factors = NULL;
		mpz_t y;
		mpz_init_set_ui(y, 1);

		while (1) {
			mpz_inp_str(number, stdin, 10);
			reset_timer();
			factors = createList();
			factorize(factors, number, 1, y);

			TRACE("PRINTING FACTORS:\n");
			printFactors(factors);
		}

		return 0;
	}
    
    return 1;
}
示例#2
0
文件: omega.c 项目: ramos/omega
void 
readfac (mpf_t *factoriales) {

  FILE *fichero;
  char *filename;
  int i;
  
  mpz_t intfac;


  filename = (char *) malloc(50*sizeof(char));
  mpz_init(intfac);

  mpf_init_set_ui(factoriales[0], 1);
  for (i=1; i<=NFAC; i++) {
	 sprintf(filename, "factoriales/%4.4d.dat", i);
	 fichero = fopen(filename, "r");

	 mpz_inp_str(intfac, fichero, 10);
	 /* printf("Ahi va: %d\n", i);
	  * mpz_out_str(stdout, 10, intfac);
	  * printf("\n\n");
	  */

	 mpf_init(factoriales[i]);
	 mpf_set_z(factoriales[i], intfac);

	 fclose(fichero);
  }
  
  
}
示例#3
0
int main(void)
{
	calculateSmallPrimes(); // Calculate primes smaller than 10^6 to speed up primality test.
#ifdef TEST
	FILE *fp;
	fp = freopen("solovay_strassen_stats.dat", "w", stdout);

	long long bit_count, rep;
	for (bit_count = 1; bit_count <= 9; bit_count++) { // Test bit counts of 2, 4, ..., 256, 512
		printf("%d", 1 << bit_count);
		for (rep = 10; rep <= 100; rep += 10) {
			long long time = testPerformance(1000, 1 << bit_count, rep);
			printf(" %lld", time);
		}
		printf("\n");
	}
	fclose(fp);

	return 0;
#else
	mpz_t n;
	mpz_init(n);

	printf("N: ");
	if (mpz_inp_str(n, NULL, BASE) == 0) {
		printf("ERROR\n");
		return -1;
	}

	int probably_prime = solovay_strassen(n, REPETITIONS);
	printf("%s\n", probably_prime? "It's probably prime." : "It's composite.");

	return 0;
#endif
}
示例#4
0
int main(void)
{
    int i, num_factors;
    mpz_t n, d, tmp, x_1, x_2;
    mpz_init(n);
    mpz_init(d);
    mpz_init(tmp);
    mpz_init(x_1);
    mpz_init(x_2);
    mpz_init(cp);

    srand(1337);

    mpz_t *factors = malloc(sizeof(mpz_t) * MAX_FACTORS);

    for(i = 0; i < MAX_FACTORS; ++i) {
        mpz_init(factors[i]);
    }

    for (i = 0; i < NUM_INPUT; ++i) {
        mpz_inp_str(n, stdin, 10);
        num_factors = factor(x_1, x_2, d, n, tmp, factors);
        print_factors(factors, num_factors);
    }

    return 0;
}
示例#5
0
/* return EOF if end-of-file or error, 0 otherwise */
int
read_partial2 (relation r, FILE *fp, unsigned long *pp)
{
  unsigned long q;
  unsigned int n = 0, e;
  int p;

  if (fscanf (fp, "%lu", pp) == EOF)
    return EOF;
  if (fscanf (fp, "%lu", &q) == EOF)
    return EOF;
  r->q = q;
  if (mpz_inp_str (r->x, fp, 10) == 0)
    return EOF;

  while (!feof (fp))
    {
      if (fscanf (fp, "%d", &p) == EOF)
        return EOF;
      if (p == 0) /* end of line */
        return 0;
      if (fscanf (fp, "%u", &e) == EOF)
        return EOF;
      realloc_relation (r, n + 1);
      r->p[n] = p;
      r->e[n] = e;
      r->n = ++ n;
    }
  return EOF;
}
示例#6
0
/* return EOF if end-of-file or error, 0 otherwise */
int
read_full (relation r, FILE *fp, unsigned long fbn)
{
  unsigned int n = 0, e;
  int p;

  r->q = 0;
  if (mpz_inp_str (r->x, fp, 10) == 0)
    return EOF;

  while (!feof (fp))
    {
      if (fscanf (fp, "%d", &p) == EOF)
        return EOF;
      if (p == 0) /* end of line */
        return 0;
      /* check prime index */
      if (p != -1 && (p <= 0 || fbn < (unsigned long) p))
        {
          fprintf (stderr, "Error, wrong prime index in full: %d\n", p);
          exit (1);
        }
      if (fscanf (fp, "%u", &e) == EOF)
        return EOF;
      realloc_relation (r, n + 1);
      r->p[n] = p;
      r->e[n] = e;
      r->n = ++ n;
    }
  return EOF;
}
示例#7
0
void load_txt_scalar(mpz_t q, const char *scalar_name, const char *folder_name) {
  FILE *fp;
  open_file(&fp, scalar_name, (char *)"rb", folder_name);
  if (fp == NULL) return;
  mpz_inp_str(q, fp, 10);
  fclose(fp);
}
示例#8
0
int main()
{
	mpz_t a , b , gcd;
	mpz_inits(a , b , gcd , NULL);
    
	printf("Enter first number : ");
	mpz_inp_str (a , stdin , 10 );

	printf("\nEnter second number : ");
	mpz_inp_str (b , stdin , 10 );

    find_gcd(gcd , a , b);

    printf("\nGCD of the given two numbers is : ");
    mpz_out_str (stdout , 10 , gcd);

    printf("\n");
}
int main()
{
	mpz_t n;
	mpz_init(n);
	printf("Enter a number - ");
	mpz_inp_str(n , NULL , 10);

    miller_rabin(n);
}
示例#10
0
int gmp_pbs_import_parameters(gmp_pbs_parameters *parameters, char *filename) {
	FILE *fp;

	/* get public curve parameters */
	fp = fopen(filename, "rt");
	if (fp == NULL) {
		printf("file %s does not exist\n", filename);
		return 0;
	}

	/* import parameters in base 16 (hex)  */
	mpz_inp_str(parameters->p, fp, 16);
	mpz_inp_str(parameters->q, fp, 16);
	mpz_inp_str(parameters->g, fp, 16);

	fclose(fp);
	return 1;
}
示例#11
0
int main(int argc, char const *argv[])
{
    gmp_randstate_t state;
    unsigned long int i, seed;
    // Get a timestamp and use it as our seed
    // (this is generally regarded as a 'bad idea')
    time_t nowTime = time(0);
    seed = (unsigned long int) nowTime;

    // Initiate random state
    gmp_randinit_default(state);
    gmp_randseed_ui(state, seed);

    // Generate p, q, and n
    mpz_t p; mpz_init(p); stupidPrimeGenerator(p, BIT_LENGTH, state);
    mpz_t q; mpz_init(q); stupidPrimeGenerator(q, BIT_LENGTH, state);
    mpz_t n; mpz_init(n); mpz_mul(n, p, q);

    // Generate e and totient
    mpz_sub_ui(p, p, 1);
    mpz_sub_ui(q, q, 1);
    mpz_t e; mpz_init(e); mpz_set_ui(e, 65537);
    mpz_t totient; mpz_init(totient); mpz_mul(totient, p, q);

    // Debug:
    // gmp_printf("p=%Zd\n\nq=%Zd\n\ne=%Zd\n\n", p, q, e);
    
    // Calculate d
    mpz_t negativeOne; mpz_init(negativeOne); mpz_set_si(negativeOne, -1);
    mpz_t d; mpz_init(d);
    mpz_powm(d, e, negativeOne, totient);

    // Debug:
    // gmp_printf("d=%Zd\n\nn=%Zd\n\n", d, n);

    mpz_t inputMessage;     mpz_init(inputMessage);
    mpz_t encryptedMessage; mpz_init(encryptedMessage);
    mpz_t decryptedMessage; mpz_init(decryptedMessage);

    // Read in message
    printf("Input message: ");
    mpz_inp_str(inputMessage, stdin, 10);

    // Encrpyt message
    mpz_powm(encryptedMessage, inputMessage, e, n);
    gmp_printf("\nEncrypted message: %Zd\n\n", encryptedMessage);

    // Decrypt message
    mpz_powm(decryptedMessage, encryptedMessage, d, n);
    gmp_printf("Decrypted message: %Zd\n\n", decryptedMessage);

    // size_t count = 1024;
    // char *outputMessage = (char*) calloc(count, sizeof(char));
    // mpz_export(outputMessage, &count, 1, sizeof(char), 1, 0, decryptedMessage);
    // gmp_printf("Decrypted message:%d\n", outputMessage);
}
示例#12
0
int fib_input (mpz_t term)
{
	fputs ("Enter a non-negative integer `n` to get the `nth` term: ", stdout);

	if (mpz_inp_str (term, stdin, 10)) {
		return mpz_sgn (term) != -1;
	}

	return 0;
}
ats_void_type
atslib_mpz_inp_str_exn (
  ats_mpz_ptr_type x
, ats_ptr_type file
, ats_int_type base
) {
  size_t n = mpz_inp_str(x, (FILE*)file, base) ;
  if (n == 0) {
    ats_exit_errmsg (1, "exit(ATS): [mpz_inp_str] failed.\n") ;
  } // end of [if]
  return ;
} // end of [atslib_mpz_inp_str_exn]
示例#14
0
文件: read.c 项目: clear731/lattice
int 
fmpz_read(fmpz_t f)
{
    mpz_t t;
    size_t r;

    mpz_init(t);
    r = mpz_inp_str(t, stdin, 10);
    fmpz_set_mpz(f, t);
    mpz_clear(t);

    return (r > 0) ? 1 : 0;
}
示例#15
0
/* read number to factor from 'params' file */
void
read_params (mpz_t N, unsigned long *B, unsigned long *LP, char *params)
{
  FILE *fp;
  mpz_t lp, bb;

  fp = fopen (params, "r");
  if (mpz_inp_str (N, fp, 10) == 0)
    {
      fprintf (stderr, "Error, cannot read number to factor\n");
      exit (1);
    }
  if (fscanf (fp, "%lu", B) == EOF)
    {
      fprintf (stderr, "Error, cannot read factor base bound\n");
      exit (1);
    }
  mpz_init (lp);
  mpz_init (bb);
  if (mpz_inp_str (lp, fp, 10) == 0)
    {
      mpz_set_ui (lp, *B);
      mpz_mul_ui (lp, lp, 128); 
    }
  /* LP must fit in a "unsigned long" (so that large primes can be
     represented by this type), and be less than B^2 (so that when
     a residue is less than LP, it is necessarily prime */
  mpz_ui_pow_ui (bb, *B, 2);
  if (mpz_fits_ulong_p (lp) == 0 || mpz_cmp (lp, bb) > 0)
    {
      fprintf (stderr, "Error, large prime bound is too large\n");
      exit (1);
    }
  *LP = mpz_get_ui (lp);
  mpz_clear (lp);
  mpz_clear (bb);
  fclose (fp);
}
示例#16
0
int gmp_pbs_import_key(gmp_pbs_key *key, char *filename) {
	FILE *fp;

	fp = fopen(filename, "rt");
	if (fp == NULL) {
		printf("file %s does not exist\n", filename);
		return 0;
	}

	/* import key in base 16 (hex) */
	mpz_inp_str(key->key, fp, 16);

	fclose(fp);
	return 1;
}
示例#17
0
size_t
mpq_inp_str (mpq_ptr q, FILE *fp, int base)
{
  size_t  nread;
  int     c;

  if (fp == NULL)
    fp = stdin;

  SIZ(DEN(q)) = 1;
  PTR(DEN(q))[0] = 1;

  nread = mpz_inp_str (mpq_numref(q), fp, base);
  if (nread == 0)
    return 0;

  c = getc (fp);
  nread++;

  if (c == '/')
    {
      c = getc (fp);
      nread++;

      nread = mpz_inp_str_nowhite (mpq_denref(q), fp, base, c, nread);
      if (nread == 0)
	{
	  SIZ(NUM(q)) = 0;
	  SIZ(DEN(q)) = 1;
	  PTR(DEN(q))[0] = 1;
	}
    }
  else
    {
      ungetc (c, fp);
      nread--;
    }

  return nread;
}
示例#18
0
int get_n_and_d_from_file()
{
	FILE *key_fp = NULL;
	int count=1, err=-1;
	mpz_t temp;

	mpz_init(temp);

	if ( (key_fp = fopen(g_key_file_name, "r"))==NULL )
	{
		fprintf(stderr, "File:%s for key not present", g_key_file_name);
		err = errno;
	}


	while ( mpz_inp_str(temp, key_fp, 10) != 0  )
	{
		//ignore p, q and n+1
		if ( count==3 )
		{
			// read n
			mpz_set(n, temp);
		}
		else if ( count==5 )
		{
			//read d
			mpz_set(d, temp);
		}
		count++;
	}

	mpz_clear(temp);
	if ( key_fp )
	{
		fclose(key_fp);
	}
	err = 0;
	return err;
}
示例#19
0
void isom_options (int format, struct pcp_vars *pcp)
{
   register int *y = y_address;

   FILE *Status;
   FILE *FileName;
   FILE *Subgroup;

   struct pga_vars pga;

   Logical user_supplied = FALSE;
   Logical group_present = FALSE;
   Logical identity_map;
   Logical finished;
   Logical valid;
   Logical equal;

   int output = DEFAULT_STANDARD_PRINT;
   int start_class, final_class;
   int option;
   int t;
   int status;
   int complete;
   int iteration;
   int *seq1;
   int *seq2;
   int len1, len2;
   int nmr_items;
   int ***auts;
   int x_dim, y_dim;
   FILE * GAP_library;
   char *name;
   int nmr_of_exponents;

   StandardPresentation = TRUE;
   pga.nmr_soluble = 0;

   list_isom_menu ();

   do {
      option = read_option (MAXOPTION);      
      switch (option) {

      case -1:
	 list_isom_menu ();
	 break;

      case START_INFO:
	 t = runTime ();
	 group_present = setup_start_info (FALSE, 0, stdin, format, &pga, pcp);
	 handle_error (group_present);
	 user_supplied = TRUE;
	 t = runTime () - t;
	 /* it is possible that the p-quotient is trivial */
	 if (pcp->cc == 0) {
	    group_present = FALSE; 
	    break; 
	 }
	 printf ("Class %d %d-quotient and its %d-covering group computed in %.2f seconds\n", 
		 pcp->cc - 1, pcp->p, pcp->p, t * CLK_SCALE);
	 break;

      case CONSTRUCT:
	 if (!user_supplied) {
	    name = GetString ("Enter input file name for group information: ");
	    FileName = OpenFile (name, "r");
	    if (FileName == NULL) break;
	 }
            
	 name = GetString ("Enter output file name for group information: ");

	 read_value (TRUE, "Standardise presentation to what class? ",
		     &final_class, 0);
	 if (user_supplied && final_class < pcp->cc) { 
	    printf ("Value supplied for end class must be at least %d\n", 
		    pcp->cc);
	 }

	 /* read in data from file and set up group to end of start_class 
	    and compute its p-covering group */

	 if (!user_supplied) {
	    group_present = setup_start_info (FALSE, 0, FileName, 
					      FILE_INPUT, &pga, pcp);
	    handle_error (group_present);
	    if (final_class < pcp->cc) {
	       CloseFile (FileName);
	       printf ("Value supplied for end class must be at least %d\n", 
		       pcp->cc);
	    }
	 }

	 if (pcp->cc == 0) { 
	    printf ("%d-quotient is trivial\n", pcp->p); 
	    break;
	 }

	 complete = (pcp->newgen == 0) ? TERMINAL : CAPABLE; 
	 iteration = 0;

	 for (start_class = pcp->cc; start_class <= final_class && 
		 complete != TERMINAL; ++start_class) {

	    t = runTime ();

	    identity_map = FALSE;
	    Subgroup = OpenFile ("ISOM_Subgroup", "w");

	    do {
	       ++iteration;
	       set_defaults (&pga);
	       /*
		 pga.space_efficient = TRUE;
		 */

	       /* either prompt for information or read it from file */
	       if (user_supplied) {
		  auts = read_auts (STANDARDISE, &pga.m, &nmr_of_exponents, pcp)
		     ;
		  pga.fixed = 0;
		  query_solubility (&pga);
		  user_supplied = FALSE;
#ifdef HAVE_GMP
		  autgp_order (&pga, pcp);
#endif 
	       }
	       else {
		  auts = read_auts_from_file (FileName, &pga.m, pcp);
		  nmr_items = fscanf (FileName, "%d", &pga.fixed);
		  verify_read (nmr_items, 1);
		  nmr_items = fscanf (FileName, "%d", &pga.soluble);
		  verify_read (nmr_items, 1);

#ifdef HAVE_GMP
		  fscanf (FileName, "\n");
		  mpz_init (&pga.aut_order);
		  mpz_inp_str (&pga.aut_order, FileName, 10);
#endif
		  CloseFile (FileName);
	       }
	       x_dim = pga.m; y_dim = pcp->lastg;

	       /* construct standard presentation relative to smallest 
		  permissible characteristic subgroup in p-multiplicator */

	       standard_presentation (&identity_map, output, auts, &pga, pcp);

	       free_array (auts, x_dim, y_dim, 1);

	       /* was the characteristic subgroup chosen in this iteration
		  the whole of the p-multiplicator? */

	       Status = OpenFile ("ISOM_Status", "r");
	       fscanf (Status, "%d", &status);
	       fscanf (Status, "%d", &complete);
	       CloseFile (Status);
                 
	       /* have we finished the construction? */
	       finished = (status == END_OF_CLASS && 
			   (start_class == final_class || complete == TERMINAL));

	       /* organise to write modified presentation + automorphisms 
		  to file ISOM_PP */
              
	       if (!identity_map || finished)  
	       {
		  copy_file( "ISOM_present", "ISOM_PP" );
		  append_file( "ISOM_NextClass", "ISOM_PP" );
	       }
	       else
		  copy_file( "ISOM_NextClass", "ISOM_PP" );

	       if (finished) break;

	       /* if necessary, set up new presentation + other information */
	       FileName = OpenFile ("ISOM_PP", "r");
	       group_present = setup_start_info (identity_map, status, 
						 FileName, FILE_INPUT, &pga, pcp);

	       handle_error (group_present);

	       /* if appropriate, factor subgroup from p-multiplicator */
	       if (status != END_OF_CLASS) 
		  factor_subgroup (pcp);

	       /* reinitialise pga structure */
	       initialise_pga (&pga, pcp);
	       pga.m = 0;
	       pga.ndgen = y[pcp->clend + 1];
	       set_values (&pga, pcp);

	    } while (status != END_OF_CLASS && complete != TERMINAL);

	    CloseFile (Subgroup);

	    /* the group may have completed only when relations are enforced;
	       this is an attempt to determine this case */
	    if (pga.nuclear_rank != 0 && pcp->complete) 
	       break;
            
	    t = runTime () - t;
	    printf ("Computing standard presentation for class %d took %.2f seconds\n", 
		    start_class, t * CLK_SCALE);
	 }

	 /* we currently may have presentation for p-covering group;
	    or is the starting group terminal? if so, we may want to 
	    use last_class to revert to group presentation */

	 if (!user_supplied && iteration == 0 && !pcp->complete)
	    last_class (pcp);

	 /* is the group terminal? */
	 if (complete == TERMINAL) 
	    printf ("The largest %d-quotient of the group has class %d\n", 
		    pcp->p, pcp->cc);

	 if (iteration == 0) break;

	 /* rename file ISOM_PP containing iteration info to nominated file */
	 rename( "ISOM_PP", name );

	 break;

      case PRINT_PCP:
	 if (group_present) 
	    print_presentation (TRUE, pcp);
	 break;

      case SAVE_PRES:
	 name = GetString ("Enter output file name: ");
	 FileName = OpenFileOutput (name);
	 if (group_present && FileName != NULL) {
	    save_pcp (FileName, pcp);
	    CloseFile (FileName);
	    printf ("Presentation written to file\n");
	 }
	 break;
 
      case COMPARE:
	 valid = get_description ("Enter file name storing first presentation: ",
				  &len1, &seq1, pcp);
	 if (!valid) break;
	 valid = get_description ("Enter file name storing second presentation: ", 
				  &len2, &seq2, pcp);

	 if (!valid) break;
	 equal = (len1 == len2) ? compare_sequences (seq1, seq2, len1): FALSE;

	 printf ("Identical presentations? %s\n", equal == TRUE ? 
		 "True" : "False");
	 free_vector (seq1, 1);
	 free_vector (seq2, 1);
	 break;

      case STANDARD_PRINT_LEVEL: 
	 read_value (TRUE, "Input print level for construction (0-2): ",
		     &output, 0);
	 /* allow user to supply same max print level as for 
	    p-quotient calculations */
	 if (output == MAX_STANDARD_PRINT + 1)
	    --output; 
	 if (output > MAX_STANDARD_PRINT) {
	    printf ("Print level must lie between %d and %d\n",
		    MIN_STANDARD_PRINT, MAX_STANDARD_PRINT);
	    output = DEFAULT_STANDARD_PRINT;
	 }
	 break;

      case PQ_MENU:
	 options (ISOM_MENU, format, pcp);
	 break;

      case ISOM_OPTION:
	 FileName = OpenFile (name, "r");
	 group_present = setup_start_info (FALSE, 0, FileName, 
					   FILE_INPUT, &pga, pcp);
         pcp->multiplicator_rank = pcp->lastg - y[pcp->clend + pcp->cc-1];
	 last_class (pcp);
	 auts = read_auts_from_file (FileName, &pga.m, pcp);
	 nmr_items = fscanf (FileName, "%d", &pga.fixed);
	 verify_read (nmr_items, 1);
	 nmr_items = fscanf (FileName, "%d", &pga.soluble);
	 verify_read (nmr_items, 1);
        
	 printf ("Images of user-supplied generators are listed last below\n"); 
	 print_map (pcp);
#ifdef HAVE_GMP
	 fscanf (FileName, "\n");
	 mpz_init (&pga.aut_order);
	 mpz_inp_str (&pga.aut_order, FileName, 10);
#endif
	 CloseFile (FileName);
	 GAP_library = OpenFile ("GAP_library", "a+");
	 write_GAP_library (GAP_library, pcp);
	 pga.nmr_centrals = pga.m;
	 pga.nmr_stabilisers = 0;

	 GAP_auts (GAP_library, auts, auts, &pga, pcp);
	 CloseFile (GAP_library);
	 printf ("Presentation listing images of user-supplied generators written to GAP_library\n");
	 break;

      case EXIT: case MAXOPTION:
	 unlink( "ISOM_present" );
	 unlink( "ISOM_Subgroup" );
	 unlink( "ISOM_cover_file" );
	 unlink( "ISOM_group_file" );
	 unlink( "ISOM_XX" );
	 unlink( "ISOM_NextClass" );
	 unlink( "ISOM_Status" );
	 printf ("Exiting from ANU p-Quotient Program\n");
	 break;

      }                         /* switch */
   } while (option != 0 && option != MAXOPTION);      
}
示例#20
0
int main(int argc, char** argv) {
  FILE* ifp;
  FILE* ofp;

  char* nstr;

  mpz_t e, d, n;
  mpz_t p, q, t, phi;
  mpz_t one, two;
  mpz_t p2, q2;

  int l1, l2;

  l1 = 1;
  clock();

  mpz_init(e);
  mpz_init(d);
  mpz_init(n);
  mpz_init(p);
  mpz_init(q);
  mpz_init(phi);
  mpz_init(t);
  mpz_init_set_si(one, 1);
  mpz_init_set_si(two, 2);
  mpz_init(p2);
  mpz_init(q2);

  if (argc != 3) {
    printf("Bad command line.\n");
    exit(1);
  }

  ifp = fopen(argv[1], "r");
  ofp = fopen(argv[2], "w");

  mpz_inp_str(e, ifp, 10);
  mpz_inp_str(n, ifp, 10);

  mpz_set(p, two);
  while (true) {
    nstr = mpz_get_str(NULL, 10, p);
    l2 = strlen(nstr);
    if (l2 > l1) {
      printf("%d digits: %f seconds.\n", l1, clock() / ((double)CLOCKS_PER_SEC));
      l1 = l2;
    }
    free((void*)nstr);

    mpz_div(q, n, p);
    mpz_mul(t, q, p);
    if (mpz_cmp(t, n)==0)
      break;
    mpz_add(p, p, one);
  }

  mpz_sub(p2, p, one);
  mpz_sub(q2, q, one);
  mpz_mul(phi, p2, q2);
  mpz_invert(d, e, phi);

  mpz_out_str(ofp, 10, d);
  fprintf(ofp, "\n\n");
  mpz_out_str(ofp, 10, n);

  return 0;
}
示例#21
0
文件: client.c 项目: bchanthyra/TSL
int main(int argc, char **argv) {
  int err, option_index, c, clientlen, counter;
  unsigned char rcv_plaintext[AES_BLOCK_SIZE];
  unsigned char rcv_ciphertext[AES_BLOCK_SIZE];
  unsigned char send_plaintext[AES_BLOCK_SIZE];
  unsigned char send_ciphertext[AES_BLOCK_SIZE];
  aes_context enc_ctx, dec_ctx;
  in_addr_t ip_addr;
  struct sockaddr_in server_addr;
  FILE *c_file, *d_file, *m_file;
  ssize_t read_size, write_size;
  struct sockaddr_in client_addr;
  tls_msg err_msg, send_msg, rcv_msg;
  mpz_t client_exp, client_mod;
  fd_set readfds;
  struct timeval tv;

  c_file = d_file = m_file = NULL;

  mpz_init(client_exp);
  mpz_init(client_mod);

  /*
   * This section is networking code that you don't need to worry about.
   * Look further down in the function for your part.
   */

  memset(&ip_addr, 0, sizeof(in_addr_t));

  option_index = 0;
  err = 0;

  static struct option long_options[] = {
    {"ip", required_argument, 0, 'i'},
    {"cert", required_argument, 0, 'c'},
    {"exponent", required_argument, 0, 'd'},
    {"modulus", required_argument, 0, 'm'},
    {0, 0, 0, 0},
  };

  while (1) {
    c = getopt_long(argc, argv, "c:i:d:m:", long_options, &option_index);
    if (c < 0) {
      break;
    }
    switch(c) {
    case 0:
      usage();
      break;
    case 'c':
      c_file = fopen(optarg, "r");
      if (c_file == NULL) {
	perror("Certificate file error");
	exit(1);
      }
      break;
    case 'd':
      d_file = fopen(optarg, "r");
      if (d_file == NULL) {
	perror("Exponent file error");
	exit(1);
      }
      break;
    case 'i':
      ip_addr = inet_addr(optarg);
      break;
    case 'm':
      m_file = fopen(optarg, "r");
      if (m_file == NULL) {
	perror("Modulus file error");
	exit(1);
      }
      break;
    case '?':
      usage();
      break;
    default:
      usage();
      break;
    }
  }

  if (d_file == NULL || c_file == NULL || m_file == NULL) {
    usage();
  }
  if (argc != 9) {
    usage();
  }

  mpz_inp_str(client_exp, d_file, 0);
  mpz_inp_str(client_mod, m_file, 0);

  signal(SIGTERM, kill_handler);

  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if (sockfd < 0) {
    perror("Could not open socket");
    exit(1);
  }

  memset(&server_addr, 0, sizeof(struct sockaddr_in));
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = ip_addr;
  server_addr.sin_port = htons(HANDSHAKE_PORT);
  err = connect(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr));
  if (err < 0) {
    perror("Could not bind socket");
    cleanup();
  }

  // YOUR CODE HERE
  // IMPLEMENT THE TLS HANDSHAKE

  /*
   * START ENCRYPTED MESSAGES
   */

  memset(send_plaintext, 0, AES_BLOCK_SIZE);
  memset(send_ciphertext, 0, AES_BLOCK_SIZE);
  memset(rcv_plaintext, 0, AES_BLOCK_SIZE);
  memset(rcv_ciphertext, 0, AES_BLOCK_SIZE);

  memset(&rcv_msg, 0, TLS_MSG_SIZE);

  aes_init(&enc_ctx);
  aes_init(&dec_ctx);
  
  // YOUR CODE HERE
  // SET AES KEYS

  fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
  /* Send and receive data. */
  while (1) {
    FD_ZERO(&readfds);
    FD_SET(STDIN_FILENO, &readfds);
    FD_SET(sockfd, &readfds);
    tv.tv_sec = 2;
    tv.tv_usec = 10;

    select(sockfd+1, &readfds, NULL, NULL, &tv);
    if (FD_ISSET(STDIN_FILENO, &readfds)) {
      counter = 0;
      memset(&send_msg, 0, TLS_MSG_SIZE);
      send_msg.type = ENCRYPTED_MESSAGE;
      memset(send_plaintext, 0, AES_BLOCK_SIZE);
      read_size = read(STDIN_FILENO, send_plaintext, AES_BLOCK_SIZE);
      while (read_size > 0 && counter + AES_BLOCK_SIZE < TLS_MSG_SIZE - INT_SIZE) {
	if (read_size > 0) {
	  err = aes_crypt_ecb(&enc_ctx, AES_ENCRYPT, send_plaintext, send_ciphertext);
	  memcpy(send_msg.msg + counter, send_ciphertext, AES_BLOCK_SIZE);
	  counter += AES_BLOCK_SIZE;
	}
	memset(send_plaintext, 0, AES_BLOCK_SIZE);
	read_size = read(STDIN_FILENO, send_plaintext, AES_BLOCK_SIZE);
      }
      write_size = write(sockfd, &send_msg, INT_SIZE+counter+AES_BLOCK_SIZE);
      if (write_size < 0) {
	perror("Could not write to socket");
	cleanup();
      }
    } else if (FD_ISSET(sockfd, &readfds)) {
      memset(&rcv_msg, 0, TLS_MSG_SIZE);
      memset(rcv_ciphertext, 0, AES_BLOCK_SIZE);
      read_size = read(sockfd, &rcv_msg, TLS_MSG_SIZE);
      if (read_size > 0) {
	if (rcv_msg.type != ENCRYPTED_MESSAGE) {
	  goto out;
	}
	memcpy(rcv_ciphertext, rcv_msg.msg, AES_BLOCK_SIZE);
	counter = 0;
	while (counter < read_size - INT_SIZE - AES_BLOCK_SIZE) {
	  aes_crypt_ecb(&dec_ctx, AES_DECRYPT, rcv_ciphertext, rcv_plaintext);
	  printf("%s", rcv_plaintext);
	  counter += AES_BLOCK_SIZE;
	  memcpy(rcv_ciphertext, rcv_msg.msg+counter, AES_BLOCK_SIZE);
	}
      }
    }

  }

 out:
  close(sockfd);
  return 0;
}
示例#22
0
void input_poly(mpz_t N, mpz_t ** A, i32_t * adeg_ptr, mpz_t ** B,
                i32_t * bdeg_ptr, mpz_t m, FILE * input_file)
/*******************************************************/
{
  char *input_line = NULL;
  size_t input_line_alloc = 0;
  i32_t have_m = 0;

  if (mpz_inp_str(N, input_file, 10) == 0)
    complain("Cannot read number which is to be factored: %m\n");

  *adeg_ptr = -1;
  *bdeg_ptr = -1;
  while (have_m == 0) {
    i32_t grad;
    char *field;

    if (skip_blanks_comments(&input_line, &input_line_alloc, input_file) <= 0)
      complain
        ("Cannot read common root of NFS polynomials from input file\n");
    switch (*input_line) {
      case 'X':
        if (sscanf(input_line + 1, "%d", &grad) == 0)
          complain("Cannot understand input line %s\n", input_line);
        if (grad > *adeg_ptr) {
          i32_t i;

          if (*adeg_ptr >= 0)
            *A = xrealloc(*A, (grad + 1) * sizeof(**A));
          else
            *A = xmalloc((grad + 1) * sizeof(**A));
          for (i = *adeg_ptr + 1; i <= grad; i++)
            mpz_init_set_ui((*A)[i], 0);
          *adeg_ptr = grad;
        }
        strtok(input_line, " \t");
        field = strtok(NULL, " \t");
        if (string2mpz((*A)[grad], field, 10) != 0)
          complain("Cannot understand number %s\n", field);
        break;
      case 'Y':
        if (sscanf(input_line + 1, "%d", &grad) == 0)
          complain("Cannot understand input line %s\n", input_line);
        if (grad > *bdeg_ptr) {
          i32_t i;

          if (*bdeg_ptr >= 0)
            *B = xrealloc(*B, (grad + 1) * sizeof(**B));
          else
            *B = xmalloc((grad + 1) * sizeof(**B));
          for (i = *bdeg_ptr + 1; i <= grad; i++)
            mpz_init_set_ui((*B)[i], 0);
          *bdeg_ptr = grad;
        }
        strtok(input_line, " \t");
        field = strtok(NULL, " \t");
        if (string2mpz((*B)[grad], field, 10) != 0)
          complain("Cannot understand number %s\n", field);
        break;
      case 'M':
        strtok(input_line, " \t");
        field = strtok(NULL, " \t");
        if (string2mpz(m, field, 10) != 0)
          complain("Cannot understand number %s\n", field);
        have_m = 1;
        break;
    }
  }
  if (*adeg_ptr == -1) {
    *adeg_ptr = 1;
    *A = xmalloc(2 * sizeof(**A));
    mpz_init_set_ui((*A)[1], 1);
    mpz_init((*A)[0]);
    mpz_neg((*A)[0], m);
  }
  if (*bdeg_ptr == -1) {
    *bdeg_ptr = 1;
    *B = xmalloc(2 * sizeof(**B));
    mpz_init_set_ui((*B)[1], 1);
    mpz_init((*B)[0]);
    mpz_neg((*B)[0], m);
  }
  if (*adeg_ptr == 0 || *bdeg_ptr == 0)
    complain("Polynomials of degree zero are not allowed\n");

  {
    mpz_t x;
    i32_t i;

    if (mpz_sgn(*(*A + *adeg_ptr)) == 0) {
      complain("Leading coefficient (degree %u) vanishes\n", *adeg_ptr);
    }
    if (mpz_sgn(*(*B + *bdeg_ptr)) == 0) {
      complain("Leading coefficient (degree %u) vanishes\n", *bdeg_ptr);
    }
    for (i = 1, mpz_init_set(x, (*A)[*adeg_ptr]); i <= *adeg_ptr; i++) {
      mpz_mul(x, x, m);
      mpz_add(x, x, (*A)[*adeg_ptr - i]);
    }
    mpz_fdiv_r(x, x, N);
    if (mpz_sgn(x) != 0) {
      mpz_out_str(stderr, 10, m);
      complain(" not a root of first poly\n");
    }
    for (i = 1, mpz_set(x, (*B)[*bdeg_ptr]); i <= *bdeg_ptr; i++) {
      mpz_mul(x, x, m);
      mpz_add(x, x, (*B)[*bdeg_ptr - i]);
    }
    mpz_fdiv_r(x, x, N);
    if (mpz_sgn(x) != 0) {
      mpz_out_str(stderr, 10, m);
      complain(" not a root of second poly\n");
    }
    mpz_clear(x);
  }

  free(input_line);
}
int main(int argc, char **argv) {
	int err, option_index, c, clientlen, counter;
	unsigned char rcv_plaintext[AES_BLOCK_SIZE];
	unsigned char rcv_ciphertext[AES_BLOCK_SIZE];
	unsigned char send_plaintext[AES_BLOCK_SIZE];
	unsigned char send_ciphertext[AES_BLOCK_SIZE];
	aes_context enc_ctx, dec_ctx;
	in_addr_t ip_addr;
	struct sockaddr_in server_addr;
	FILE *c_file, *d_file, *m_file;
	ssize_t read_size, write_size;
	struct sockaddr_in client_addr;
	tls_msg err_msg, send_msg, rcv_msg;
	mpz_t client_exp, client_mod;
	fd_set readfds;
	struct timeval tv;

	c_file = d_file = m_file = NULL;

	mpz_init(client_exp);
	mpz_init(client_mod);


	/*
	 * This section is networking code that you don't need to worry about.
	 * Look further down in the function for your part.
	 */

	memset(&ip_addr, 0, sizeof(in_addr_t));

	option_index = 0;
	err = 0;

	static struct option long_options[] = {
		{"ip", required_argument, 0, 'i'},
		{"cert", required_argument, 0, 'c'},
		{"exponent", required_argument, 0, 'd'},
		{"modulus", required_argument, 0, 'm'},
		{0, 0, 0, 0},
	};

	while (1) {
		c = getopt_long(argc, argv, "c:i:d:m:", long_options, &option_index);
		if (c < 0) {
			break;
		}
		switch(c) {
		case 0:
			usage();
			break;
		case 'c':
			c_file = fopen(optarg, "r");
			if (c_file == NULL) {
				perror("Certificate file error");
				exit(1);
			}
			break;
		case 'd':
			d_file = fopen(optarg, "r");
			if (d_file == NULL) {
				perror("Exponent file error");
				exit(1);
			}
			break;
		case 'i':
			ip_addr = inet_addr(optarg);
			break;
		case 'm':
			m_file = fopen(optarg, "r");
			if (m_file == NULL) {
				perror("Modulus file error");
				exit(1);
			}
			break;
		case '?':
			usage();
			break;
		default:
			usage();
			break;
		}
	}

	if (d_file == NULL || c_file == NULL || m_file == NULL) {
		usage();
	}
	if (argc != 9) {
		usage();
	}

	mpz_inp_str(client_exp, d_file, 0);
	mpz_inp_str(client_mod, m_file, 0);

	signal(SIGTERM, kill_handler);

	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (sockfd < 0) {
		perror("Could not open socket");
		exit(1);
	}


	memset(&server_addr, 0, sizeof(struct sockaddr_in));
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = ip_addr;
	server_addr.sin_port = htons(HANDSHAKE_PORT);
	err = connect(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr));
	if (err < 0) {
		perror("Could not bind socket");
		cleanup();
	}

	// YOUR CODE HERE
	// IMPLEMENT THE TLS HANDSHAKE
	int send_message_int, receive_messge_int;
	/* error handling (To be continued) */
	// ********************************************************************
	// ********************************************************************
	// ********************************************************************
	
	// Whenever send or receive, need to check this feedback
	int feedback;
	//  =============== [Send] Client Hello =======================
	hello_message client_hello_message;
	int client_random;
	int server_random;
	memset(&client_hello_message, 0, sizeof(hello_message));

	client_random = random_int();
	printf("client_random: %d\n", client_random);
	client_hello_message.type = CLIENT_HELLO;
	client_hello_message.random = client_random;
	client_hello_message.cipher_suite = TLS_RSA_WITH_AES_128_ECB_SHA256;
	feedback = send_tls_message(sockfd, &client_hello_message, sizeof(hello_message));
	if (feedback != ERR_OK){
		perror("[CLIENT_HELLO]: can't send tls message");
		cleanup();	
	}

	//  =============== [Receive] Sever Hello =======================
	hello_message server_hello_message;
	memset(&server_hello_message, 0, sizeof(hello_message));
	feedback = receive_tls_message(sockfd, &server_hello_message, sizeof(hello_message), SERVER_HELLO);
	if (feedback != ERR_OK){
		perror("[SERVER_HELLO]: can't receive tls message");
		cleanup();		
	}
	server_random = server_hello_message.random;
	printf("server_random: %d\n", server_random);

	//  =============== [Send] Client Certificate ================
	mpz_t client_certificate_mpz;
	cert_message client_certificate;
	int byte_read;
	mpz_init(client_certificate_mpz);
	// May need to verify whether we connect to the correct server(i.e.torus.ce.berkeley.edu).
	memset(&client_certificate, 0, sizeof(cert_message));
	client_certificate.type = CLIENT_CERTIFICATE;
	fread(client_certificate.cert, RSA_MAX_LEN, 1, c_file);
	//printf("Client Certificate: %s\n", client_certificate.cert);
	feedback = send_tls_message(sockfd, &client_certificate, CERT_MSG_SIZE);
	if (feedback != ERR_OK){
		perror("[CLIENT CERTIFICATE]: can't send tls message");
		cleanup();
	}

	//  =============== [Receive] Server Certificate ================
	cert_message server_certificate;
	mpz_t decrypted_sever_cert_mpz;
	mpz_t ca_exponent;
	mpz_t ca_modulus;
	mpz_t server_public_key_exponent;
	mpz_t server_public_key_modulus;
	char decrypted_server_cert [RSA_MAX_LEN];

	memset(&server_certificate, 0, sizeof(cert_message));
	mpz_init(decrypted_sever_cert_mpz);
	mpz_init(ca_exponent);
	mpz_init(ca_modulus);
	mpz_init(server_public_key_exponent);
	mpz_init(server_public_key_modulus);
	memset(decrypted_server_cert, 0, RSA_MAX_LEN);

	feedback = receive_tls_message(sockfd, &server_certificate, sizeof(cert_message), SERVER_CERTIFICATE);
	if (feedback != ERR_OK){
		perror("[SERVER CERTIFICATE]: can't receive tls message");
		cleanup();
	}
	// May need to verify whether we connect to the correct server(i.e.torus.ce.berkeley.edu).
	// Decrypt Server Certificate
	mpz_set_str(ca_exponent, CA_EXPONENT, 0);
	mpz_set_str(ca_modulus, CA_MODULUS, 0);
	decrypt_cert(decrypted_sever_cert_mpz, &server_certificate, ca_exponent, ca_modulus);
	mpz_get_ascii(decrypted_server_cert, decrypted_sever_cert_mpz);                       // Convert mpz to char array
	//printf("decrypted_server_cert: %s\n", decrypted_server_cert);
	get_cert_exponent(server_public_key_exponent, decrypted_server_cert);
	get_cert_modulus(server_public_key_modulus, decrypted_server_cert);


	//  =============== [Send] E_server_public_key (Premaster Secret) ================
	// Construct encrypted(premaster secret)
	mpz_t premaster_secret_encrypted, premaster_secret_mpz;
	int premaster_secret;
	char premaster[16];
	ps_msg encrypted_ps_message;
	mpz_init(premaster_secret_encrypted);
	mpz_init(premaster_secret_mpz);	
	memset(&encrypted_ps_message, 0, sizeof(ps_msg));
	
	// Generate and Covert Premaster Secret to mpz
	sleep(3);
	premaster_secret = random_int();
	printf("premaster_secret: %d\n", premaster_secret);
	sprintf(premaster, "%d", premaster_secret);
	mpz_set_str(premaster_secret_mpz, premaster, 10);
	// perform_rsa(premaster_secret_encrypted, premaster_secret_mpz, server_public_key_exponent, server_public_key_modulus);
	// ps_msg *encrypted_ps_message;
	// encrypted_ps_message = (ps_msg*) malloc(sizeof(ps_msg));
	// encrypted_ps_message->type = PREMASTER_SECRET;
	// mpz_get_ascii(encrypted_ps_message->ps, premaster_secret_encrypted);
	// send_tls_message(sockfd, encrypted_ps_message, sizeof(ps_msg));
	// ps_msg encrypted_server_ms_message;
	// memset(&encrypted_server_ms_message, 0, sizeof(ps_msg));
	// receive_messge_int = receive_tls_message(sockfd, &encrypted_server_ms_message, sizeof(ps_msg), PREMASTER_SECRET);
	// if (receive_messge_int == ERR_FAILURE) {
	// 	perror("Could not get the master secret");
	// 	cleanup();
	// }
	// gmp_printf("premaster_secret_mpz: %Zd\n", premaster_secret_mpz);
	// gmp_printf("server_public_key_exponent: %Zx\n", server_public_key_exponent);
	// gmp_printf("server_public_key_modulus: %Zx\n", server_public_key_modulus);
	perform_rsa(premaster_secret_encrypted, premaster_secret_mpz, server_public_key_exponent, server_public_key_modulus);
	encrypted_ps_message.type = PREMASTER_SECRET;
	mpz_get_str(encrypted_ps_message.ps, 16, premaster_secret_encrypted);
	feedback = send_tls_message(sockfd, &encrypted_ps_message, sizeof(ps_msg));
	if (feedback != ERR_OK) {
		perror("[E_server_public_key (Premaster secret)]: can't send tls message");
		cleanup();
	}
	
	//  =============== [Receive] E_client_public_key (Master Secret) ================
	ps_msg encrypted_server_ms_message;
	mpz_t decrypted_ms;
	mpz_t master_secret_mpz;
	unsigned long long master_secret_long;
	unsigned char master_secret[SHA_BLOCK_SIZE];
	int result;
	memset(&encrypted_server_ms_message, 0, sizeof(ps_msg));
	mpz_init(decrypted_ms);
	memset(master_secret, 0, SHA_BLOCK_SIZE);
	mpz_init(master_secret_mpz);
	feedback = receive_tls_message(sockfd, &encrypted_server_ms_message, sizeof(ps_msg), VERIFY_MASTER_SECRET);
	if (feedback != ERR_OK) {
		perror("[E_client_public_key (master secret)]: can't receive tls message");
		cleanup();
	}

	decrypt_verify_master_secret(decrypted_ms, &encrypted_server_ms_message, client_exp, client_mod);
	compute_master_secret(premaster_secret, client_random, server_random, master_secret);
	char* master_secret_str = hex_to_str(master_secret, SHA_BLOCK_SIZE);
	mpz_set_str(master_secret_mpz, master_secret_str, 16);
	result = mpz_cmp(master_secret_mpz, decrypted_ms);
	printf("%d", result);
	if (result != 0) {
		perror("Decrypted server master secret doesn't match computed master secret!");
		cleanup();
	}
	if (client_random != premaster_secret && server_random != premaster_secret){
		//printf("1\n");
	}else{
		//printf("0\n");
	}
	//printf("result: %d\n", result);
	free(master_secret_str);
	close(sockfd);
	mpz_clear(client_exp);
	mpz_clear(client_mod);
	mpz_clear(client_certificate_mpz);
	mpz_clear(decrypted_sever_cert_mpz);
	mpz_clear(ca_exponent);
	mpz_clear(ca_modulus);
	mpz_clear(premaster_secret_encrypted);
	mpz_clear(server_public_key_exponent);
	mpz_clear(server_public_key_modulus);
	mpz_clear(premaster_secret_mpz);
	mpz_clear(decrypted_ms);
	mpz_clear(master_secret_mpz);
	cleanup();
	return 0;
}
示例#24
0
void
check_data (void)
{
  static const struct {
    const char  *inp;
    int         base;
    const char  *want;
    int         want_nread;

  } data[] = {

    { "0",   10, "0", 1 },

    { "abc", 10, "0", 0 },
    { "0xf", 10, "0", 1 },
    { "ghi", 16, "0", 0 },
    { "100", 90, "0", 0 },

    {  "ff", 16,  "255", 2 },
    { "-ff", 16, "-255", 3 },
    {  "FF", 16,  "255", 2 },
    { "-FF", 16, "-255", 3 },

    {  "z", 36, "35", 1 },
    {  "Z", 36, "35", 1 },
    { "1B", 59, "70", 2 },
    {  "a", 60, "36", 1 },
    {  "A", 61, "10", 1 },

    {  "0x0",    0,   "0", 3 },
    {  "0X10",   0,  "16", 4 },
    { "-0X0",    0,   "0", 4 },
    { "-0x10",   0, "-16", 5 },

    {  "0b0",    0,  "0", 3 },
    {  "0B10",   0,  "2", 4 },
    { "-0B0",    0,  "0", 4 },
    { "-0b10",   0, "-2", 5 },

    {  "00",   0,  "0", 2 },
    {  "010",  0,  "8", 3 },
    { "-00",   0,  "0", 3 },
    { "-010",  0, "-8", 4 },

    {  "0x",     0,   "0", 2 },
    {  "0",      0,   "0", 1 },
    { " 030",   10,  "30", 4 },
  };

  mpz_t  got, want;
  long   ftell_nread;
  int    i, pre, post, j, got_nread, want_nread;
  FILE   *fp;

  mpz_init (got);
  mpz_init (want);

  for (i = 0; i < numberof (data); i++)
    {
      for (pre = 0; pre <= 3; pre++)
	{
	  for (post = 0; post <= 2; post++)
	    {
	      mpz_set_str_or_abort (want, data[i].want, 0);
	      MPZ_CHECK_FORMAT (want);

	      /* create the file new each time to ensure its length is what
		 we want */
	      fp = fopen (FILENAME, "w+");
	      ASSERT_ALWAYS (fp != NULL);
	      for (j = 0; j < pre; j++)
		putc (' ', fp);
	      fputs (data[i].inp, fp);
	      for (j = 0; j < post; j++)
		putc (' ', fp);
	      fflush (fp);
	      ASSERT_ALWAYS (! ferror(fp));

	      rewind (fp);
	      got_nread = mpz_inp_str (got, fp, data[i].base);

	      if (got_nread != 0)
		{
		  ftell_nread = ftell (fp);
		  if (got_nread != ftell_nread)
		    {
		      printf ("mpz_inp_str nread wrong\n");
		      printf ("  inp          \"%s\"\n", data[i].inp);
		      printf ("  base         %d\n", data[i].base);
		      printf ("  pre          %d\n", pre);
		      printf ("  post         %d\n", post);
		      printf ("  got_nread    %d\n", got_nread);
		      printf ("  ftell_nread  %ld\n", ftell_nread);
		      abort ();
		    }
		}

	      /* if data[i].inp is a whole string to read and there's no post
		 whitespace then expect to have EOF */
	      if (post == 0 && data[i].want_nread == strlen(data[i].inp))
		{
		  int  c = getc(fp);
		  if (c != EOF)
		    {
		      printf ("mpz_inp_str didn't read to EOF\n");
		      printf ("  inp   \"%s\"\n", data[i].inp);
		      printf ("  base  %d\n", data[i].base);
		      printf ("  pre   %d\n", pre);
		      printf ("  post  %d\n", post);
		      printf ("  c     '%c' %#x\n", c, c);
		      abort ();
		    }
		}

	      /* only expect "pre" included in the count when non-zero */
	      want_nread = data[i].want_nread;
	      if (want_nread != 0)
		want_nread += pre;

	      if (got_nread != want_nread)
		{
		  printf ("mpz_inp_str nread wrong\n");
		  printf ("  inp         \"%s\"\n", data[i].inp);
		  printf ("  base        %d\n", data[i].base);
		  printf ("  pre         %d\n", pre);
		  printf ("  post        %d\n", post);
		  printf ("  got_nread   %d\n", got_nread);
		  printf ("  want_nread  %d\n", want_nread);
		  abort ();
		}

	      MPZ_CHECK_FORMAT (got);

	      if (mpz_cmp (got, want) != 0)
		{
		  printf ("mpz_inp_str wrong result\n");
		  printf ("  inp   \"%s\"\n", data[i].inp);
		  printf ("  base  %d\n", data[i].base);
		  mpz_trace ("  got ",  got);
		  mpz_trace ("  want", want);
		  abort ();
		}

	      ASSERT_ALWAYS (fclose (fp) == 0);
	    }
	}
    }

  mpz_clear (got);
  mpz_clear (want);
}
示例#25
0
文件: io.c 项目: AllardJ/Tomato
int
main (int argc, char **argv)
{
  mpz_t  op1, op2;
  mp_size_t size;
  int i;
  int reps = 10000;
  FILE *fp;
  int base, base_out;
  gmp_randstate_ptr rands;
  mpz_t bs;
  unsigned long bsi, size_range;
  size_t nread;

  tests_start ();
  rands = RANDS;

  mpz_init (bs);

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

  mpz_init (op1);
  mpz_init (op2);

  fp = fopen (FILENAME, "w+");

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

      mpz_urandomb (bs, rands, size_range);
      size = mpz_get_ui (bs);
      mpz_rrandomb (op1, rands, size);
      mpz_urandomb (bs, rands, 1);
      bsi = mpz_get_ui (bs);
      if ((bsi & 1) != 0)
	mpz_neg (op1, op1);

      mpz_urandomb (bs, rands, 16);
      bsi = mpz_get_ui (bs);
      base = bsi % 62 + 1;
      if (base == 1)
	base = 0;

      if (i % 2 == 0 && base <= 36)
	base_out = -base;
      else
	base_out = base;

      rewind (fp);
      if (mpz_out_str (fp, base_out, op1) == 0
	  || putc (' ', fp) == EOF
	  || fflush (fp) != 0)
	{
	  printf ("mpz_out_str write error\n");
	  abort ();
	}

      rewind (fp);
      nread = mpz_inp_str (op2, fp, base);
      if (nread == 0)
	{
	  if (ferror (fp))
	    printf ("mpz_inp_str stream read error\n");
	  else
	    printf ("mpz_inp_str data conversion error\n");
	  abort ();
	}

      if (nread != ftell(fp))
	{
	  printf ("mpz_inp_str nread doesn't match ftell\n");
	  printf ("  nread  %lu\n", (unsigned long) nread);
	  printf ("  ftell  %ld\n", ftell(fp));
	  abort ();
	}

      if (mpz_cmp (op1, op2))
	{
	  printf ("ERROR\n");
	  printf ("op1  = "); debug_mp (op1, -16);
	  printf ("op2  = "); debug_mp (op2, -16);
	  printf ("base = %d\n", base);
	  abort ();
	}
    }

  fclose (fp);

  unlink (FILENAME);

  mpz_clear (bs);
  mpz_clear (op1);
  mpz_clear (op2);

  tests_end ();
  exit (0);
}
示例#26
0
int main(int argc, char **argv) {
  int err, option_index, c, clientlen, counter;
  unsigned char rcv_plaintext[AES_BLOCK_SIZE];
  unsigned char rcv_ciphertext[AES_BLOCK_SIZE];
  unsigned char send_plaintext[AES_BLOCK_SIZE];
  unsigned char send_ciphertext[AES_BLOCK_SIZE];
  aes_context enc_ctx, dec_ctx;
  in_addr_t ip_addr;
  struct sockaddr_in server_addr;
  FILE *c_file, *d_file, *m_file;
  ssize_t read_size, write_size;
  struct sockaddr_in client_addr;
  tls_msg err_msg, send_msg, rcv_msg;
  mpz_t client_exp, client_mod;
  fd_set readfds;
  struct timeval tv;

  c_file = d_file = m_file = NULL;

  mpz_init(client_exp);
  mpz_init(client_mod);

  /*
   * This section is networking code that you don't need to worry about.
   * Look further down in the function for your part.
   */

  memset(&ip_addr, 0, sizeof(in_addr_t));

  option_index = 0;
  err = 0;

  static struct option long_options[] = {
    {"ip", required_argument, 0, 'i'},
    {"cert", required_argument, 0, 'c'},
    {"exponent", required_argument, 0, 'd'},
    {"modulus", required_argument, 0, 'm'},
    {0, 0, 0, 0},
  };

  while (1) {
    c = getopt_long(argc, argv, "c:i:d:m:", long_options, &option_index);
    if (c < 0) {
      break;
    }
    switch(c) {
    case 0:
      usage();
      break;
    case 'c':
      c_file = fopen(optarg, "r");
      if (c_file == NULL) {
	perror("Certificate file error");
	exit(1);
      }
      break;
    case 'd':
      d_file = fopen(optarg, "r");
      if (d_file == NULL) {
	perror("Exponent file error");
	exit(1);
      }
      break;
    case 'i':
      ip_addr = inet_addr(optarg);
      break;
    case 'm':
      m_file = fopen(optarg, "r");
      if (m_file == NULL) {
	perror("Modulus file error");
	exit(1);
      }
      break;
    case '?':
      usage();
      break;
    default:
      usage();
      break;
    }
  }

  if (d_file == NULL || c_file == NULL || m_file == NULL) {
    usage();
  }
  if (argc != 9) {
    usage();
  }

  mpz_inp_str(client_exp, d_file, 0);
  mpz_inp_str(client_mod, m_file, 0);

  signal(SIGTERM, kill_handler);

  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if (sockfd < 0) {
    perror("Could not open socket");
    exit(1);
  }

  memset(&server_addr, 0, sizeof(struct sockaddr_in));
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = ip_addr;
  server_addr.sin_port = htons(HANDSHAKE_PORT);
  err = connect(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr));
  if (err < 0) {
    perror("Could not bind socket");
    cleanup();
  }

  // YOUR CODE HERE
  // IMPLEMENT THE TLS HANDSHAKE


  // send client hello
  hello_message client_hello_msg = {CLIENT_HELLO, random_int(), TLS_RSA_WITH_AES_128_ECB_SHA256};
  err = send_tls_message(sockfd, &client_hello_msg, HELLO_MSG_SIZE);
  if (err == ERR_FAILURE) {
    exit(1);
  }


  // receive server hello
  hello_message server_hello_msg;
  err = receive_tls_message(sockfd, &server_hello_msg, HELLO_MSG_SIZE, SERVER_HELLO);
  if (err == ERR_FAILURE) {
    exit(1);
  }

  // send client certificate
  cert_message client_cert_msg;
  client_cert_msg.type = CLIENT_CERTIFICATE;
  fgets(client_cert_msg.cert, RSA_MAX_LEN, c_file);
  err = send_tls_message(sockfd, &client_cert_msg, CERT_MSG_SIZE);
  if (err == ERR_FAILURE) {
    exit(1);
  }

  //receive server certificate

  cert_message server_cert_msg;

  err = receive_tls_message(sockfd, &server_cert_msg, CERT_MSG_SIZE, SERVER_CERTIFICATE);
  if (err == ERR_FAILURE) {
    exit(1);
  }

  mpz_t cert_plaintext;
  mpz_init(cert_plaintext);

  mpz_t ca_key_exp;
  mpz_init(ca_key_exp);

  mpz_t ca_key_mod;
  mpz_init(ca_key_mod);

  mpz_set_str(ca_key_exp, CA_EXPONENT, 0);
  mpz_set_str(ca_key_mod, CA_MODULUS, 0);

  decrypt_cert(cert_plaintext, &server_cert_msg, ca_key_exp, ca_key_mod);

  char cert_plaintext_string[RSA_MAX_LEN];
  mpz_get_ascii(cert_plaintext_string, cert_plaintext);


  mpz_t exponentNum;
  mpz_init(exponentNum);
  mpz_t modNum;
  mpz_init(modNum);
  get_cert_exponent(exponentNum, cert_plaintext_string);
  get_cert_modulus(modNum, cert_plaintext_string);


  mpz_t premaster_secret_int;
  mpz_init(premaster_secret_int);
  
  int p_secret_int = random_int();
  mpz_t p_secret;
  mpz_init(p_secret);
  mpz_add_ui(p_secret, p_secret, p_secret_int);

  perform_rsa(premaster_secret_int, p_secret, exponentNum, modNum);

  ps_msg premaster_secret;
  premaster_secret.type = PREMASTER_SECRET;
  mpz_get_str(premaster_secret.ps, 16, premaster_secret_int);


  // send premaster secret
  err = send_tls_message(sockfd, &premaster_secret, PS_MSG_SIZE);
  if (err == ERR_FAILURE) {
    exit(1);
  }

 
  ps_msg master_secret;

  // receive master secret
  err = receive_tls_message(sockfd, &master_secret, PS_MSG_SIZE, VERIFY_MASTER_SECRET);
  if (err == ERR_FAILURE) {
    exit(1);
  }


  mpz_t decrypted_master_secret;
  mpz_init(decrypted_master_secret);

  mpz_t key_exp;
  mpz_init(key_exp);

  mpz_t key_mod;
  mpz_init(key_mod);

  

  fseek (d_file, 0, SEEK_END);
  long length = ftell (d_file);
  fseek (d_file, 0, SEEK_SET);

  char private_key[length];
  fgets(private_key, length, d_file);
  mpz_set_str(key_exp, private_key, 0);

  fseek (m_file, 0, SEEK_END);
  length = ftell (m_file);
  fseek (m_file, 0, SEEK_SET);

  char modulus[length];
  fgets(modulus, length, m_file);
  mpz_set_str(key_mod, modulus, 0);


  decrypt_verify_master_secret(decrypted_master_secret, &master_secret, key_exp, key_mod);

  char decrypted_master_secret_char[16];

  mpz_get_str(decrypted_master_secret_char, 16, decrypted_master_secret);

  unsigned char computed_master_secret[16];

  compute_master_secret(p_secret_int, client_hello_msg.random, server_hello_msg.random, computed_master_secret);

  
  if (strcasecmp(decrypted_master_secret_char, hex_to_str(computed_master_secret, 16)) == 0) {
    printf("Begin messages.\n");
  } 

  /*
   * START ENCRYPTED MESSAGES
   */

  memset(send_plaintext, 0, AES_BLOCK_SIZE);
  memset(send_ciphertext, 0, AES_BLOCK_SIZE);
  memset(rcv_plaintext, 0, AES_BLOCK_SIZE);
  memset(rcv_ciphertext, 0, AES_BLOCK_SIZE);

  memset(&rcv_msg, 0, TLS_MSG_SIZE);

  aes_init(&enc_ctx);
  aes_init(&dec_ctx);
  
  // YOUR CODE HERE
  // SET AES KEYS

  if (aes_setkey_enc (&enc_ctx, computed_master_secret, 128)){
    printf("setting key didn't work n***a\n");
  }

  if (aes_setkey_dec (&dec_ctx, computed_master_secret, 128)){
    printf("setting key didn't work n***a\n");
  }

  fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
  /* Send and receive data. */
  while (1) {
    FD_ZERO(&readfds);
    FD_SET(STDIN_FILENO, &readfds);
    FD_SET(sockfd, &readfds);
    tv.tv_sec = 2;
    tv.tv_usec = 10;

    select(sockfd+1, &readfds, NULL, NULL, &tv);
    if (FD_ISSET(STDIN_FILENO, &readfds)) {
      counter = 0;
      memset(&send_msg, 0, TLS_MSG_SIZE);
      send_msg.type = ENCRYPTED_MESSAGE;
      memset(send_plaintext, 0, AES_BLOCK_SIZE);
      read_size = read(STDIN_FILENO, send_plaintext, AES_BLOCK_SIZE);
      while (read_size > 0 && counter + AES_BLOCK_SIZE < TLS_MSG_SIZE - INT_SIZE) {
	if (read_size > 0) {
	  err = aes_crypt_ecb(&enc_ctx, AES_ENCRYPT, send_plaintext, send_ciphertext);
	  memcpy(send_msg.msg + counter, send_ciphertext, AES_BLOCK_SIZE);
	  counter += AES_BLOCK_SIZE;
	}
	memset(send_plaintext, 0, AES_BLOCK_SIZE);
	read_size = read(STDIN_FILENO, send_plaintext, AES_BLOCK_SIZE);
      }
      write_size = write(sockfd, &send_msg, INT_SIZE+counter+AES_BLOCK_SIZE);
      if (write_size < 0) {
	perror("Could not write to socket");
	cleanup();
      }
    } else if (FD_ISSET(sockfd, &readfds)) {
      memset(&rcv_msg, 0, TLS_MSG_SIZE);
      memset(rcv_ciphertext, 0, AES_BLOCK_SIZE);
      read_size = read(sockfd, &rcv_msg, TLS_MSG_SIZE);
      if (read_size > 0) {
	if (rcv_msg.type != ENCRYPTED_MESSAGE) {
	  goto out;
	}
	memcpy(rcv_ciphertext, rcv_msg.msg, AES_BLOCK_SIZE);
	counter = 0;
	while (counter < read_size - INT_SIZE - AES_BLOCK_SIZE) {
	  aes_crypt_ecb(&dec_ctx, AES_DECRYPT, rcv_ciphertext, rcv_plaintext);
	  printf("%s", rcv_plaintext);
	  counter += AES_BLOCK_SIZE;
	  memcpy(rcv_ciphertext, rcv_msg.msg+counter, AES_BLOCK_SIZE);
	}
	printf("\n");
      }
    }

  }

 out:
  close(sockfd);
  return 0;
}
示例#27
0
int main(int argc, char**argv) {
  printf("Checking RSA keys...\n");
  FILE *keys_file = fopen("../keys.txt", "r");

  mpz_t rop;
  mpz_init(rop);

  mpz_t arr[NUM_KEYS];
  int j, i = 0;
  
  // initialize array
  while(mpz_inp_str(rop, keys_file, BASE_10) && i < NUM_KEYS) {
    mpz_init(arr[i]);
    mpz_set(arr[i], rop);
    i++;
//    mpz_init(rop);
  }
  fclose(keys_file);

  mpz_t gcd, p, q, privateKey, publicKey;
  mpz_init(gcd);
//  int matches[NUM_KEYS][NUM_KEYS];
  int count = 0;
  mpz_init(privateKey);
  mpz_init(publicKey);
  //set public key
  mpz_set_ui(publicKey, E);
  FILE *badkeys = fopen("20k-cpu-badkeys.txt", "w");


  mpz_init(p);
  mpz_init(q);
  time_t start = time(NULL);
  time_t end;
  for (i=0; i < NUM_KEYS-1; i++) {
    for (j=i+1; j < NUM_KEYS; j++) {
      mpz_gcd (gcd, arr[i], arr[j]);
        if (mpz_cmp_ui(gcd, 1) > 0) {
           count++;
           mpz_set(p, gcd);
           outputPrivateKey(arr[i], badkeys);
           getPrivateKey(p, q, arr[i], publicKey, privateKey);
           fprintf(badkeys, ":");
           outputPrivateKey(privateKey, badkeys);
           fprintf(badkeys, "\n");


           outputPrivateKey(arr[j], badkeys);
           fprintf(badkeys, ":");
           getPrivateKey(p, q, arr[j], publicKey, privateKey);
           outputPrivateKey(privateKey, badkeys);
           fprintf(badkeys, "\n");
        } 
    }
    if (i%100 == 0) {
      end = time(NULL);
      printf("reached %d modulii at %d time\n", i, (int)end-(int)start);
      start = time(NULL);
    }
  }
  fclose(badkeys);
  printf("done.\n");

  printf("Keys that match...\n");
  printf("   Percent of matches: %.4f%%, %d/%d\n", ((double)count)/NUM_KEYS, count, NUM_KEYS);

  return 0;
}
示例#28
0
int initv(void)
{
    int i,d,pak,k,maxp;
    double dp;

    mpz_inits(N, TA, D, R, V, P, X, Y, DG, IG, A, B, TB, TC, TD, NULL);

    nbts=8*sizeof(int);

    printf("Input N= \n");
    d=mpz_inp_str(N, stdin, 10); //待分解的整数
    if((mpz_probab_prime_p(N, qsieve->NTRY) ? TRUE : FALSE))
    {
        printf("N is prime!\n");
        return (-1);
    }

    if(d<8) mm=d; // 分解基的理想大小
    else if(d>20) mm=(d*d*d*d)/4096; 
    else mm=25;

    dp=(double)2*(double)(mm+100); // dp:生成素数的数量 +100 *2均是为了更加保险
    maxp=(int)(dp*(log(dp*log(dp)))); // 罗素上界 maxp
    qsieve_gprime(maxp);

    epr=(int *)qsieve_alloc(mm+1,sizeof(int));

    k=knuth(mm,epr,N,D);

    if(mpz_root(R, D, 2)) //检查完全平方数
    {
        printf("Factors are\n");
        qsieve_outnum(R,stdout);
        qsieve_divide(N,R,N);
        qsieve_outnum(N,stdout);
        return -1;
    }

    qsieve_gprime(0);

    mlf=2*mm;
//各种开空间,初始化
    r1=(int *)qsieve_alloc((mm+1),sizeof(int));
    r2=(int *)qsieve_alloc((mm+1),sizeof(int));
    rp=(int *)qsieve_alloc((mm+1),sizeof(int));
    b=(int *)qsieve_alloc((mm+1),sizeof(int));
    e=(int *)qsieve_alloc((mm+1),sizeof(int));

    logp=(unsigned char *)qsieve_alloc(mm+1,1);

    pr=(int *)qsieve_alloc((mlf+1),sizeof(int));
    hash=(int *)qsieve_alloc((2*mlf+1),sizeof(int));

    sieve=(unsigned char *)qsieve_alloc(SSIZE+1,1);

    x=(mpz_t *)qsieve_alloc(mm+1,sizeof(mpz_t));
    y=(mpz_t *)qsieve_alloc(mm+1,sizeof(mpz_t));
    z=(mpz_t *)qsieve_alloc(mlf+1,sizeof(mpz_t));
    w=(mpz_t *)qsieve_alloc(mlf+1,sizeof(mpz_t));

    for(i=0;i<=mm;i++)
    {
        mpz_init(x[i]);
        mpz_init(y[i]);
    }
    for(i=0;i<=mlf;i++)
    {
        mpz_init(z[i]);
        mpz_init(w[i]);
    }

    EE=(unsigned int **)qsieve_alloc(mm+1,sizeof(unsigned int *));
    G=(unsigned int **)qsieve_alloc(mlf+1,sizeof(unsigned int *));

    pak=1+mm/(8*sizeof(int));
    for(i=0;i<=mm;i++)
    {
        b[i]=(-1);
        EE[i]=(unsigned int *)qsieve_alloc(pak,sizeof(int));
    }

    for(i=0;i<=mlf;i++) G[i]=(unsigned int *)qsieve_alloc(pak,sizeof(int));
    return 1;
}
示例#29
0
int main(int argc, char **argv) {
  int err, option_index, c, clientlen, counter;
  unsigned char rcv_plaintext[AES_BLOCK_SIZE];
  unsigned char rcv_ciphertext[AES_BLOCK_SIZE];
  unsigned char send_plaintext[AES_BLOCK_SIZE];
  unsigned char send_ciphertext[AES_BLOCK_SIZE];
  aes_context enc_ctx, dec_ctx;
  in_addr_t ip_addr;
  struct sockaddr_in server_addr;
  FILE *c_file, *d_file, *m_file;
  ssize_t read_size, write_size;
  struct sockaddr_in client_addr;
  tls_msg err_msg, send_msg, rcv_msg;
  mpz_t client_exp, client_mod; 
  fd_set readfds;
  struct timeval tv;

  c_file = d_file = m_file = NULL;

  mpz_init(client_exp);
  mpz_init(client_mod);

  /*
   * This section is networking code that you don't need to worry about.
   * Look further down in the function for your part.
   */

  memset(&ip_addr, 0, sizeof(in_addr_t));

  option_index = 0;
  err = 0;

  static struct option long_options[] = {
    {"ip", required_argument, 0, 'i'},
    {"cert", required_argument, 0, 'c'},
    {"exponent", required_argument, 0, 'd'},
    {"modulus", required_argument, 0, 'm'},
    {0, 0, 0, 0},
  };

  while (1) {
    c = getopt_long(argc, argv, "c:i:d:m:", long_options, &option_index);
    if (c < 0) {
      break;
    }
    switch(c) {
    case 0:
      usage();
      break;
    case 'c':
      c_file = fopen(optarg, "r");
      if (c_file == NULL) {
	perror("Certificate file error");
	exit(1);
      }
      break;
    case 'd':
      d_file = fopen(optarg, "r");
      if (d_file == NULL) {
	perror("Exponent file error");
	exit(1);
      }
      break;
    case 'i':
      ip_addr = inet_addr(optarg);
      break;
    case 'm':
      m_file = fopen(optarg, "r");
      if (m_file == NULL) {
	perror("Modulus file error");
	exit(1);
      }
      break;
    case '?':
      usage();
      break;
    default:
      usage();
      break;
    }
  }

  if (d_file == NULL || c_file == NULL || m_file == NULL) {
    usage();
  }
  if (argc != 9) {
    usage();
  }

  mpz_inp_str(client_exp, d_file, 0);
  mpz_inp_str(client_mod, m_file, 0);

  signal(SIGTERM, kill_handler);

  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if (sockfd < 0) {
    perror("Could not open socket");
    exit(1);
  }

  memset(&server_addr, 0, sizeof(struct sockaddr_in));
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = ip_addr;
  server_addr.sin_port = htons(HANDSHAKE_PORT);
  err = connect(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr));
  if (err < 0) {
    perror("Could not bind socket");
    cleanup();
  }

  // YOUR CODE HERE

  // IMPLEMENT THE TLS HANDSHAKE
  // Client Hello and Setup
  hello_message client_hello_send[HELLO_MSG_SIZE];
  (*client_hello_send).type = CLIENT_HELLO;
  (*client_hello_send).random = random_int();
  (*client_hello_send).cipher_suite = TLS_RSA_WITH_AES_128_ECB_SHA256;
  send_tls_message(sockfd, client_hello_send, HELLO_MSG_SIZE);
 
  // Server Hello & Setup
  hello_message server_hello_rcv[HELLO_MSG_SIZE];
  receive_tls_message(sockfd, server_hello_rcv, HELLO_MSG_SIZE, SERVER_HELLO);
    
  // Client Certificate
  cert_message client_cert_send[CERT_MSG_SIZE];
  (*client_cert_send).type = CLIENT_CERTIFICATE;
  fread((*client_cert_send).cert, RSA_MAX_LEN, 1, c_file);

  //Printing the client certificate message
  //printf("%s\n",(*client_cert_send).cert);
  send_tls_message(sockfd, client_cert_send, CERT_MSG_SIZE);

  // Server Certificate
  cert_message server_cert_rcv[CERT_MSG_SIZE];
  receive_tls_message(sockfd, server_cert_rcv, CERT_MSG_SIZE, SERVER_CERTIFICATE);

  mpz_t decrypted_cert;
  mpz_t ca_exp;
  mpz_t ca_mod;
  mpz_init(decrypted_cert);
  mpz_init(ca_exp);
  mpz_init(ca_mod);

  mpz_set_str(ca_exp, CA_EXPONENT, 0);
  mpz_set_str(ca_mod, CA_MODULUS, 0);

  // Decrypt Server Certificate
  decrypt_cert(decrypted_cert, server_cert_rcv, ca_exp, ca_mod); 
  char output_str[CERT_MSG_SIZE];
  mpz_get_ascii(output_str, decrypted_cert);

  // Extracting keys from certificate 
  mpz_t public_exp;
  mpz_t public_mod;
  mpz_init(public_exp);
  mpz_init(public_mod);
  get_cert_exponent(public_exp, output_str);
  get_cert_modulus(public_mod, output_str);
<<<<<<< HEAD