コード例 #1
0
ファイル: pk.c プロジェクト: randombit/hacrypto
static int
wrap_nettle_pk_verify_params(gnutls_pk_algorithm_t algo,
			     const gnutls_pk_params_st * params)
{
	int ret;

	switch (algo) {
	case GNUTLS_PK_RSA:
		{
			bigint_t t1 = NULL, t2 = NULL;

			if (params->params_nr != RSA_PRIVATE_PARAMS)
				return
				    gnutls_assert_val
				    (GNUTLS_E_INVALID_REQUEST);

			t1 = _gnutls_mpi_new(256);
			if (t1 == NULL)
				return
				    gnutls_assert_val
				    (GNUTLS_E_MEMORY_ERROR);

			_gnutls_mpi_mulm(t1, params->params[RSA_PRIME1],
					 params->params[RSA_PRIME2],
					 params->params[RSA_MODULUS]);
			if (_gnutls_mpi_cmp_ui(t1, 0) != 0) {
				ret =
				    gnutls_assert_val
				    (GNUTLS_E_ILLEGAL_PARAMETER);
				goto rsa_cleanup;
			}

			mpz_invert(TOMPZ(t1),
				   TOMPZ(params->params[RSA_PRIME2]),
				   TOMPZ(params->params[RSA_PRIME1]));
			if (_gnutls_mpi_cmp(t1, params->params[RSA_COEF])
			    != 0) {
				ret =
				    gnutls_assert_val
				    (GNUTLS_E_ILLEGAL_PARAMETER);
				goto rsa_cleanup;
			}

			/* [RSA_PRIME1] = d % p-1, [RSA_PRIME2] = d % q-1 */
			_gnutls_mpi_sub_ui(t1, params->params[RSA_PRIME1],
					   1);
			t2 = _gnutls_mpi_mod(params->params[RSA_PRIV], t1);
			if (t2 == NULL) {
				ret =
				    gnutls_assert_val
				    (GNUTLS_E_MEMORY_ERROR);
				goto rsa_cleanup;
			}

			if (_gnutls_mpi_cmp(params->params[RSA_E1], t2) !=
			    0) {
				ret =
				    gnutls_assert_val
				    (GNUTLS_E_ILLEGAL_PARAMETER);
				goto rsa_cleanup;
			}

			_gnutls_mpi_sub_ui(t1, params->params[RSA_PRIME2],
					   1);
			_gnutls_mpi_release(&t2);

			t2 = _gnutls_mpi_mod(params->params[RSA_PRIV], t1);
			if (t2 == NULL) {
				ret =
				    gnutls_assert_val
				    (GNUTLS_E_MEMORY_ERROR);
				goto rsa_cleanup;
			}

			if (_gnutls_mpi_cmp(params->params[RSA_E2], t2) !=
			    0) {
				ret =
				    gnutls_assert_val
				    (GNUTLS_E_ILLEGAL_PARAMETER);
				goto rsa_cleanup;
			}

			ret = 0;

		      rsa_cleanup:
			_gnutls_mpi_release(&t1);
			_gnutls_mpi_release(&t2);
		}

		break;
	case GNUTLS_PK_DSA:
		{
			bigint_t t1 = NULL;

			if (params->params_nr != DSA_PRIVATE_PARAMS)
				return
				    gnutls_assert_val
				    (GNUTLS_E_INVALID_REQUEST);

			t1 = _gnutls_mpi_new(256);
			if (t1 == NULL)
				return
				    gnutls_assert_val
				    (GNUTLS_E_MEMORY_ERROR);

			_gnutls_mpi_powm(t1, params->params[DSA_G],
					 params->params[DSA_X],
					 params->params[DSA_P]);

			if (_gnutls_mpi_cmp(t1, params->params[DSA_Y]) !=
			    0) {
				ret =
				    gnutls_assert_val
				    (GNUTLS_E_ILLEGAL_PARAMETER);
				goto dsa_cleanup;
			}

			ret = 0;

		      dsa_cleanup:
			_gnutls_mpi_release(&t1);
		}

		break;
	case GNUTLS_PK_EC:
		{
			struct ecc_point r, pub;
			struct ecc_scalar priv;
			mpz_t x1, y1, x2, y2;
			const struct ecc_curve *curve;

			if (params->params_nr != ECC_PRIVATE_PARAMS)
				return
				    gnutls_assert_val
				    (GNUTLS_E_INVALID_REQUEST);

			curve = get_supported_curve(params->flags);
			if (curve == NULL)
				return
				    gnutls_assert_val
				    (GNUTLS_E_ECC_UNSUPPORTED_CURVE);

			ret = _ecc_params_to_pubkey(params, &pub, curve);
			if (ret < 0)
				return gnutls_assert_val(ret);

			ret = _ecc_params_to_privkey(params, &priv, curve);
			if (ret < 0) {
				ecc_point_clear(&pub);
				return gnutls_assert_val(ret);
			}

			ecc_point_init(&r, curve);
			/* verify that x,y lie on the curve */
			ret =
			    ecc_point_set(&r, TOMPZ(params->params[ECC_X]),
					  TOMPZ(params->params[ECC_Y]));
			if (ret == 0) {
				ret =
				    gnutls_assert_val
				    (GNUTLS_E_ILLEGAL_PARAMETER);
				goto ecc_cleanup;
			}
			ecc_point_clear(&r);

			ecc_point_init(&r, curve);
			ecc_point_mul_g(&r, &priv);

			mpz_init(x1);
			mpz_init(y1);
			ecc_point_get(&r, x1, y1);
			ecc_point_clear(&r);

			mpz_init(x2);
			mpz_init(y2);
			ecc_point_get(&pub, x2, y2);

			/* verify that k*(Gx,Gy)=(x,y) */
			if (mpz_cmp(x1, x2) != 0 || mpz_cmp(y1, y2) != 0) {
				ret =
				    gnutls_assert_val
				    (GNUTLS_E_ILLEGAL_PARAMETER);
				goto ecc_cleanup;
			}

			ret = 0;

		      ecc_cleanup:
			ecc_scalar_clear(&priv);
			ecc_point_clear(&pub);
		}
		break;
	default:
		ret = gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);
	}

	return ret;
}
コード例 #2
0
void miller_rabin(mpz_t n)
{
	if(mpz_cmp_ui(n , 2) == 0)
    {
    	gmp_printf("\n%Zd is a prime number\n" , n);
    	exit(2);
    } 

    mpz_t rem;
    mpz_init(rem);

    mpz_mmod_ui(rem , n , 2);
   
    if(mpz_cmp_ui(rem , 0) == 0)
    {
    	gmp_printf("\n%Zd is not a prime number\n" , n);
    	exit(2);
    }


    mpz_t n_minus_1;
    mpz_init(n_minus_1);
    mpz_sub_ui(n_minus_1 , n , 1);


	mpz_t r , s ;
	mpz_inits(r , s , NULL);

	mpz_set(s , n_minus_1);
	

    mpz_mmod_ui(rem , s , 2);
	while(mpz_cmp_ui(rem , 0) == 0)
	{
         mpz_add_ui(r , r , 1);
         mpz_div_ui(s , s , 2);
         mpz_mmod_ui(rem , s , 2);
	}

    mpz_t a;
    mpz_init(a);

    gmp_randstate_t state;
    gmp_randinit_default(state);
    
    int seed;
    //struct timeval* t;
    //gettimeofday(t , NULL);
    //seed = t->tv_usec;
    //seed = 4546;
    //printf("\nEnter seed - ");
    //scanf("%d" , &seed);

    gmp_randseed_ui (state , seed );

    mpz_urandomm (a , state , n_minus_1);
    mpz_add_ui(a , a , 1);
    gmp_printf("\na is - %Zd\n" , a);

    mpz_t a_pow_s;
    mpz_init(a_pow_s);

    
 
    mpz_powm(rem , a , s , n);

    
    if(mpz_cmp_ui(rem , 1) == 0)
    {
    	gmp_printf("\nThe given number %Zd is a prime number \n" , n);
    	exit(0);
    }

    mpz_t two_pow_j;
    mpz_init(two_pow_j);
    mpz_set_ui(two_pow_j , 1);

    mpz_t j;;
    mpz_init(j);

    mpz_set_ui(j , 0);

    mpz_t product;
    mpz_init(product);

    while(mpz_cmp(j , r) != 0)
    {
    	
        mpz_mul(product , two_pow_j , s);    
    
        mpz_powm(rem , a , product , n);

        if(mpz_cmp(rem , n_minus_1) == 0)
        {
        	gmp_printf("\nThe given number %Zd is a prime number \n" , n);
        	exit(1);
        }

        mpz_mul_ui(two_pow_j , two_pow_j , 2);
    	mpz_add_ui(j , j , 1);
    }

    gmp_printf("\nThe given number %Zd is   NOT   a prime number \n" , n);
}
コード例 #3
0
int main(int argc, char **argv)
{
	mpz_t g, gMul, s, u, v, uMinusV;
	mpz_t nMinus3, nMinus1;

	gmp_randstate_t rnd_state;
	int found=0, finished=0;
	double start, end;

	mpz_init(n); mpz_init(xSquared);

	if(argc < 2)
	{
		printf("Use %s N\n", argv[0]);
		exit(2);
	}

    //if p q are provided
	if(argc == 3)
	{
		mpz_t p, q;
		mpz_init_set_str(p, argv[1], 10);
		mpz_init_set_str(q, argv[2], 10);

		mpz_addmul(n, p, q);
	}
	else if(mpz_set_str(n, argv[1], 10) == -1)
	{
		printf("Cannot load %s\n", argv[1]);
		exit(2);
	}

	printf("Factorizing %s ..\n", mpz_get_str(NULL, 10, n));

	//a belongs to [1, n-2]
	//u, v <-> s belongs to [0, n-1]
	mpz_init_set(nMinus3, n);
	mpz_sub_ui(nMinus3, nMinus3, 4);

	mpz_init_set(nMinus1, n);
	mpz_sub_ui(nMinus1, nMinus1, 1);

//[1 choose seeds]
	gmp_randinit_default(rnd_state);
	mpz_init(a); mpz_init(s);

	//mpz_urandomm(a, rnd_state, nMinus3);
	//mpz_add_ui(a, a, 1);

	//a is set to 1, comment this if you want it random
	mpz_set_ui(a, 1);
	mpz_urandomm(s, rnd_state, nMinus1);

	mpz_init_set(u, s);
	mpz_init_set(v, s);

	mpz_init(uMinusV); mpz_init(g); mpz_init_set_ui(gMul, 1);

	//Pollard's rho cannot tell if a number is prime, test before getting into an infinite loop
	if(mpz_probab_prime_p(n, 5) > 0)
	{
		printf("%s is prime\n", mpz_get_str(NULL, 10, n));
		exit(0);
	}

	unsigned long steps = 0;
	start = my_gettimeofday();

	while(!finished)
	{
//[Factor search]
	while(!found)
	{
		f(u);
		f(v);
		f(v);

		mpz_set(uMinusV, u);
		mpz_sub(uMinusV, uMinusV, v);
		mpz_abs(uMinusV, uMinusV);

		//We don't calculate gcd everytime, we do 100 multiplications and use the result to
		//extract the gcd, since it must be among the product
		mpz_mul(gMul, gMul, uMinusV);

		if(steps%100 == 0)
		{
			mpz_gcd(g, gMul, n);

			if(mpz_cmp_ui(g, 1) != 0)
			{
				found = 1;
			}

			mpz_set_ui(gMul, 1);
		}

		steps++;
	}

	printf("Testing GCD: %s\n", mpz_get_str(NULL, 10, g));

//[Bad seed]
	if(mpz_cmp(g, n) != 0)
		finished = 1;
	}

	end = my_gettimeofday();

	printf("Found divisor g = %s in %lu steps [%.3f s]\n", mpz_get_str(NULL, 0, g), steps,
			end - start);
}
コード例 #4
0
ファイル: data.c プロジェクト: LihuaWu/gcc
bool
gfc_assign_data_value (gfc_expr *lvalue, gfc_expr *rvalue, mpz_t index,
		       mpz_t *repeat)
{
  gfc_ref *ref;
  gfc_expr *init;
  gfc_expr *expr = NULL;
  gfc_constructor *con;
  gfc_constructor *last_con;
  gfc_symbol *symbol;
  gfc_typespec *last_ts;
  mpz_t offset;

  symbol = lvalue->symtree->n.sym;
  init = symbol->value;
  last_ts = &symbol->ts;
  last_con = NULL;
  mpz_init_set_si (offset, 0);

  /* Find/create the parent expressions for subobject references.  */
  for (ref = lvalue->ref; ref; ref = ref->next)
    {
      /* Break out of the loop if we find a substring.  */
      if (ref->type == REF_SUBSTRING)
	{
	  /* A substring should always be the last subobject reference.  */
	  gcc_assert (ref->next == NULL);
	  break;
	}

      /* Use the existing initializer expression if it exists.  Otherwise
	 create a new one.  */
      if (init == NULL)
	expr = gfc_get_expr ();
      else
	expr = init;

      /* Find or create this element.  */
      switch (ref->type)
	{
	case REF_ARRAY:
	  if (ref->u.ar.as->rank == 0)
	    {
	      gcc_assert (ref->u.ar.as->corank > 0);
	      if (init == NULL)
		free (expr);
	      continue;
	    }

	  if (init && expr->expr_type != EXPR_ARRAY)
	    {
	      gfc_error_1 ("'%s' at %L already is initialized at %L",
			   lvalue->symtree->n.sym->name, &lvalue->where,
			   &init->where);
	      goto abort;
	    }

	  if (init == NULL)
	    {
	      /* The element typespec will be the same as the array
		 typespec.  */
	      expr->ts = *last_ts;
	      /* Setup the expression to hold the constructor.  */
	      expr->expr_type = EXPR_ARRAY;
	      expr->rank = ref->u.ar.as->rank;
	    }

	  if (ref->u.ar.type == AR_ELEMENT)
	    get_array_index (&ref->u.ar, &offset);
	  else
	    mpz_set (offset, index);

	  /* Check the bounds.  */
	  if (mpz_cmp_si (offset, 0) < 0)
	    {
	      gfc_error ("Data element below array lower bound at %L",
			 &lvalue->where);
	      goto abort;
	    }
	  else if (repeat != NULL
		   && ref->u.ar.type != AR_ELEMENT)
	    {
	      mpz_t size, end;
	      gcc_assert (ref->u.ar.type == AR_FULL
			  && ref->next == NULL);
	      mpz_init_set (end, offset);
	      mpz_add (end, end, *repeat);
	      if (spec_size (ref->u.ar.as, &size))
		{
		  if (mpz_cmp (end, size) > 0)
		    {
		      mpz_clear (size);
		      gfc_error ("Data element above array upper bound at %L",
				 &lvalue->where);
		      goto abort;
		    }
		  mpz_clear (size);
		}

	      con = gfc_constructor_lookup (expr->value.constructor,
					    mpz_get_si (offset));
	      if (!con)
		{
		  con = gfc_constructor_lookup_next (expr->value.constructor,
						     mpz_get_si (offset));
		  if (con != NULL && mpz_cmp (con->offset, end) >= 0)
		    con = NULL;
		}

	      /* Overwriting an existing initializer is non-standard but
		 usually only provokes a warning from other compilers.  */
	      if (con != NULL && con->expr != NULL)
		{
		  /* Order in which the expressions arrive here depends on
		     whether they are from data statements or F95 style
		     declarations.  Therefore, check which is the most
		     recent.  */
		  gfc_expr *exprd;
		  exprd = (LOCATION_LINE (con->expr->where.lb->location)
			   > LOCATION_LINE (rvalue->where.lb->location))
			  ? con->expr : rvalue;
		  if (gfc_notify_std (GFC_STD_GNU,
				      "re-initialization of %qs at %L",
				      symbol->name, &exprd->where) == false)
		    return false;
		}

	      while (con != NULL)
		{
		  gfc_constructor *next_con = gfc_constructor_next (con);

		  if (mpz_cmp (con->offset, end) >= 0)
		    break;
		  if (mpz_cmp (con->offset, offset) < 0)
		    {
		      gcc_assert (mpz_cmp_si (con->repeat, 1) > 0);
		      mpz_sub (con->repeat, offset, con->offset);
		    }
		  else if (mpz_cmp_si (con->repeat, 1) > 0
			   && mpz_get_si (con->offset)
			      + mpz_get_si (con->repeat) > mpz_get_si (end))
		    {
		      int endi;
		      splay_tree_node node
			= splay_tree_lookup (con->base,
					     mpz_get_si (con->offset));
		      gcc_assert (node
				  && con == (gfc_constructor *) node->value
				  && node->key == (splay_tree_key)
						  mpz_get_si (con->offset));
		      endi = mpz_get_si (con->offset)
			     + mpz_get_si (con->repeat);
		      if (endi > mpz_get_si (end) + 1)
			mpz_set_si (con->repeat, endi - mpz_get_si (end));
		      else
			mpz_set_si (con->repeat, 1);
		      mpz_set (con->offset, end);
		      node->key = (splay_tree_key) mpz_get_si (end);
		      break;
		    }
		  else
		    gfc_constructor_remove (con);
		  con = next_con;
		}

	      con = gfc_constructor_insert_expr (&expr->value.constructor,
						 NULL, &rvalue->where,
						 mpz_get_si (offset));
	      mpz_set (con->repeat, *repeat);
	      repeat = NULL;
	      mpz_clear (end);
	      break;
	    }
	  else
	    {
	      mpz_t size;
	      if (spec_size (ref->u.ar.as, &size))
		{
		  if (mpz_cmp (offset, size) >= 0)
		    {
		      mpz_clear (size);
		      gfc_error ("Data element above array upper bound at %L",
		                 &lvalue->where);
		      goto abort;
		    }
		  mpz_clear (size);
		}
	    }

	  con = gfc_constructor_lookup (expr->value.constructor,
					mpz_get_si (offset));
	  if (!con)
	    {
	      con = gfc_constructor_insert_expr (&expr->value.constructor,
						 NULL, &rvalue->where,
						 mpz_get_si (offset));
	    }
	  else if (mpz_cmp_si (con->repeat, 1) > 0)
	    {
	      /* Need to split a range.  */
	      if (mpz_cmp (con->offset, offset) < 0)
		{
		  gfc_constructor *pred_con = con;
		  con = gfc_constructor_insert_expr (&expr->value.constructor,
						     NULL, &con->where,
						     mpz_get_si (offset));
		  con->expr = gfc_copy_expr (pred_con->expr);
		  mpz_add (con->repeat, pred_con->offset, pred_con->repeat);
		  mpz_sub (con->repeat, con->repeat, offset);
		  mpz_sub (pred_con->repeat, offset, pred_con->offset);
		}
	      if (mpz_cmp_si (con->repeat, 1) > 0)
		{
		  gfc_constructor *succ_con;
		  succ_con
		    = gfc_constructor_insert_expr (&expr->value.constructor,
						   NULL, &con->where,
						   mpz_get_si (offset) + 1);
		  succ_con->expr = gfc_copy_expr (con->expr);
		  mpz_sub_ui (succ_con->repeat, con->repeat, 1);
		  mpz_set_si (con->repeat, 1);
		}
	    }
	  break;

	case REF_COMPONENT:
	  if (init == NULL)
	    {
	      /* Setup the expression to hold the constructor.  */
	      expr->expr_type = EXPR_STRUCTURE;
	      expr->ts.type = BT_DERIVED;
	      expr->ts.u.derived = ref->u.c.sym;
	    }
	  else
	    gcc_assert (expr->expr_type == EXPR_STRUCTURE);
	  last_ts = &ref->u.c.component->ts;

	  /* Find the same element in the existing constructor.  */
	  con = find_con_by_component (ref->u.c.component,
				       expr->value.constructor);

	  if (con == NULL)
	    {
	      /* Create a new constructor.  */
	      con = gfc_constructor_append_expr (&expr->value.constructor,
						 NULL, NULL);
	      con->n.component = ref->u.c.component;
	    }
	  break;

	default:
	  gcc_unreachable ();
	}

      if (init == NULL)
	{
	  /* Point the container at the new expression.  */
	  if (last_con == NULL)
	    symbol->value = expr;
	  else
	    last_con->expr = expr;
	}
      init = con->expr;
      last_con = con;
    }

  mpz_clear (offset);
  gcc_assert (repeat == NULL);

  if (ref || last_ts->type == BT_CHARACTER)
    {
      if (lvalue->ts.u.cl->length == NULL && !(ref && ref->u.ss.length != NULL))
	return false;
      expr = create_character_initializer (init, last_ts, ref, rvalue);
    }
  else
    {
      /* Overwriting an existing initializer is non-standard but usually only
	 provokes a warning from other compilers.  */
      if (init != NULL)
	{
	  /* Order in which the expressions arrive here depends on whether
	     they are from data statements or F95 style declarations.
	     Therefore, check which is the most recent.  */
	  expr = (LOCATION_LINE (init->where.lb->location)
		  > LOCATION_LINE (rvalue->where.lb->location))
	       ? init : rvalue;
	  if (gfc_notify_std (GFC_STD_GNU,
			      "re-initialization of %qs at %L",
			      symbol->name, &expr->where) == false)
	    return false;
	}

      expr = gfc_copy_expr (rvalue);
      if (!gfc_compare_types (&lvalue->ts, &expr->ts))
	gfc_convert_type (expr, &lvalue->ts, 0);
    }

  if (last_con == NULL)
    symbol->value = expr;
  else
    last_con->expr = expr;

  return true;

abort:
  if (!init)
    gfc_free_expr (expr);
  mpz_clear (offset);
  return false;
}
コード例 #5
0
ファイル: comparison.cpp プロジェクト: kolhagen/bitvoting
bool mpz_less(const mpz_t first, const mpz_t second)
{
    return (mpz_cmp(first, second) < 0);
}
コード例 #6
0
ファイル: t-mfac_uiui.c プロジェクト: Sciumo/mlton
int
main (int argc, char *argv[])
{
  mpz_t ref[MULTIFAC_WHEEL], ref2[MULTIFAC_WHEEL2], res;
  unsigned long n, j, m, m2;
  unsigned long limit = 2222, step = 1;

  tests_start ();

  if (argc > 1 && argv[1][0] == 'x')
    limit = ULONG_MAX;
  else if (argc > 1)
    limit = atoi (argv[1]);

  /* for small limb testing */
  limit = MIN (limit, MP_LIMB_T_MAX);

  for (m = 0; m < MULTIFAC_WHEEL; m++)
    mpz_init_set_ui(ref [m],1);
  for (m2 = 0; m2 < MULTIFAC_WHEEL2; m2++)
    mpz_init_set_ui(ref2 [m2],1);

  mpz_init (res);

  m = 0;
  m2 = 0;
  for (n = 0; n <= limit;)
    {
      mpz_mfac_uiui (res, n, MULTIFAC_WHEEL);
      MPZ_CHECK_FORMAT (res);
      if (mpz_cmp (ref[m], res) != 0)
        {
          printf ("mpz_mfac_uiui(%lu,&i) wrong\n", n, MULTIFAC_WHEEL);
          printf ("  got  "); mpz_out_str (stdout, 10, res); printf("\n");
          printf ("  want "); mpz_out_str (stdout, 10, ref[m]); printf("\n");
          abort ();
        }
      mpz_mfac_uiui (res, n, MULTIFAC_WHEEL2);
      MPZ_CHECK_FORMAT (res);
      if (mpz_cmp (ref2[m2], res) != 0)
        {
          printf ("mpz_mfac_uiui(%lu,&i) wrong\n", n, MULTIFAC_WHEEL2);
          printf ("  got  "); mpz_out_str (stdout, 10, res); printf("\n");
          printf ("  want "); mpz_out_str (stdout, 10, ref2[m2]); printf("\n");
          abort ();
        }
      if (n + step <= limit)
	for (j = 0; j < step; j++) {
	  n++; m++; m2++;
	  if (m >= MULTIFAC_WHEEL) m -= MULTIFAC_WHEEL;
	  if (m2 >= MULTIFAC_WHEEL2) m2 -= MULTIFAC_WHEEL2;
	  mpz_mul_ui (ref[m], ref[m], n); /* Compute a reference, with current library */
	  mpz_mul_ui (ref2[m2], ref2[m2], n); /* Compute a reference, with current library */
	}
      else n += step;
    }
  mpz_fac_ui (ref[0], n);
  mpz_mfac_uiui (res, n, 1);
  MPZ_CHECK_FORMAT (res);
  if (mpz_cmp (ref[0], res) != 0)
    {
      printf ("mpz_mfac_uiui(%lu,1) wrong\n", n);
      printf ("  got  "); mpz_out_str (stdout, 10, res); printf("\n");
      printf ("  want "); mpz_out_str (stdout, 10, ref[0]); printf("\n");
      abort ();
    }

  mpz_2fac_ui (ref[0], n);
  mpz_mfac_uiui (res, n, 2);
  MPZ_CHECK_FORMAT (res);
  if (mpz_cmp (ref[0], res) != 0)
    {
      printf ("mpz_mfac_uiui(%lu,1) wrong\n", n);
      printf ("  got  "); mpz_out_str (stdout, 10, res); printf("\n");
      printf ("  want "); mpz_out_str (stdout, 10, ref[0]); printf("\n");
      abort ();
    }

  n++;
  mpz_2fac_ui (ref[0], n);
  mpz_mfac_uiui (res, n, 2);
  MPZ_CHECK_FORMAT (res);
  if (mpz_cmp (ref[0], res) != 0)
    {
      printf ("mpz_mfac_uiui(%lu,2) wrong\n", n);
      printf ("  got  "); mpz_out_str (stdout, 10, res); printf("\n");
      printf ("  want "); mpz_out_str (stdout, 10, ref[0]); printf("\n");
      abort ();
    }

  for (m = 0; m < MULTIFAC_WHEEL; m++)
    mpz_clear (ref[m]);
  for (m2 = 0; m2 < MULTIFAC_WHEEL2; m2++)
    mpz_clear (ref2[m2]);
  mpz_clear (res);

  tests_end ();

  exit (0);
}
コード例 #7
0
ファイル: t-sub_ui.c プロジェクト: clear731/lattice
int
main(void)
{
    int i, result;
    FLINT_TEST_INIT(state);

    flint_printf("sub_ui....");
    fflush(stdout);

    

    for (i = 0; i < 10000 * flint_test_multiplier(); i++)
    {
        fmpz_t a, b;
        mpz_t d, e, f;
        ulong x;

        fmpz_init(a);
        fmpz_init(b);

        mpz_init(d);
        mpz_init(e);
        mpz_init(f);

        fmpz_randtest(a, state, 200);

        fmpz_get_mpz(d, a);
        x = n_randtest(state);

        fmpz_sub_ui(b, a, x);
        flint_mpz_sub_ui(e, d, x);

        fmpz_get_mpz(f, b);

        result = (mpz_cmp(e, f) == 0);
        if (!result)
        {
            flint_printf("FAIL:\n");
            gmp_printf("d = %Zd, e = %Zd, f = %Zd, x = %wu\n", d, e, f, x);
            abort();
        }

        fmpz_clear(a);
        fmpz_clear(b);

        mpz_clear(d);
        mpz_clear(e);
        mpz_clear(f);
    }

    /* Check aliasing of a and b */
    for (i = 0; i < 10000 * flint_test_multiplier(); i++)
    {
        fmpz_t a;
        mpz_t d, e, f;
        ulong x;

        fmpz_init(a);

        mpz_init(d);
        mpz_init(e);
        mpz_init(f);

        fmpz_randtest(a, state, 200);

        fmpz_get_mpz(d, a);
        x = n_randtest(state);

        fmpz_sub_ui(a, a, x);
        flint_mpz_sub_ui(e, d, x);

        fmpz_get_mpz(f, a);

        result = (mpz_cmp(e, f) == 0);
        if (!result)
        {
            flint_printf("FAIL:\n");
            gmp_printf("d = %Zd, e = %Zd, f = %Zd, x = %wu\n", d, e, f, x);
            abort();
        }

        fmpz_clear(a);

        mpz_clear(d);
        mpz_clear(e);
        mpz_clear(f);
    }

    FLINT_TEST_CLEANUP(state);
    
    flint_printf("PASS\n");
    return 0;
}
コード例 #8
0
bool BigInt::operator >= (const BigInt &b) const
{
	return mpz_cmp(mImpl,b.mImpl) >= 0;
}
コード例 #9
0
ファイル: bit.c プロジェクト: mahdiz/mpclib
void
check_random (int argc, char *argv[])
{
  mpz_t x, s0, s1, s2, s3, m;
  mp_size_t xsize;
  int i;
  int reps = 100000;
  int bit0, bit1, bit2, bit3;
  unsigned long int bitindex;
  const char  *s = "";

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

  mpz_init (x);
  mpz_init (s0);
  mpz_init (s1);
  mpz_init (s2);
  mpz_init (s3);
  mpz_init (m);

  for (i = 0; i < reps; i++)
    {
      xsize = urandom () % (2 * SIZE) - SIZE;
      mpz_random2 (x, xsize);
      bitindex = urandom () % SIZE;

      mpz_set (s0, x);
      bit0 = mpz_tstbit (x, bitindex);
      mpz_setbit (x, bitindex);
      MPZ_CHECK_FORMAT (x);

      mpz_set (s1, x);
      bit1 = mpz_tstbit (x, bitindex);
      mpz_clrbit (x, bitindex);
      MPZ_CHECK_FORMAT (x);

      mpz_set (s2, x);
      bit2 = mpz_tstbit (x, bitindex);
      mpz_setbit (x, bitindex);
      MPZ_CHECK_FORMAT (x);

      mpz_set (s3, x);
      bit3 = mpz_tstbit (x, bitindex);

#define FAIL(str) do { s = str; goto fail; } while (0)

      if (bit1 != 1)  FAIL ("bit1 != 1");
      if (bit2 != 0)  FAIL ("bit2 != 0");
      if (bit3 != 1)  FAIL ("bit3 != 1");

      if (bit0 == 0)
	{
	  if (mpz_cmp (s0, s1) == 0 || mpz_cmp (s0, s2) != 0 || mpz_cmp (s0, s3) == 0)
	    abort ();
	}
      else
	{
	  if (mpz_cmp (s0, s1) != 0 || mpz_cmp (s0, s2) == 0 || mpz_cmp (s0, s3) != 0)
	    abort ();
	}

      if (mpz_cmp (s1, s2) == 0 || mpz_cmp (s1, s3) != 0)
	abort ();
      if (mpz_cmp (s2, s3) == 0)
	abort ();

      mpz_ui_pow_ui (m, 2L, bitindex);
      MPZ_CHECK_FORMAT (m);
      mpz_ior (x, s2, m);
      MPZ_CHECK_FORMAT (x);
      if (mpz_cmp (x, s3) != 0)
	abort ();

      mpz_com (m, m);
      MPZ_CHECK_FORMAT (m);
      mpz_and (x, s1, m);
      MPZ_CHECK_FORMAT (x);
      if (mpz_cmp (x, s2) != 0)
	abort ();
    }

  mpz_clear (x);
  mpz_clear (s0);
  mpz_clear (s1);
  mpz_clear (s2);
  mpz_clear (s3);
  mpz_clear (m);
  return;


 fail:
  printf ("%s\n", s);
  printf ("bitindex = %lu\n", bitindex);
  printf ("x = "); mpz_out_str (stdout, -16, x); printf (" hex\n");
  exit (1);
}
コード例 #10
0
ファイル: gmp++_int_compare.C プロジェクト: d-torrance/givaro
	int32_t compare(const Integer &a, const Integer& b)
	{
		return mpz_cmp ( (mpz_srcptr)&a.gmp_rep, (mpz_srcptr)&b.gmp_rep );
	}
コード例 #11
0
ファイル: gmp++_int_compare.C プロジェクト: d-torrance/givaro
	// Operator !=
	int32_t Integer::operator != (const Integer & l) const
	{
		return mpz_cmp((mpz_srcptr)&gmp_rep,  (mpz_srcptr)l.get_mpz_const()) != 0;
	}
コード例 #12
0
int
ecc_make_key_ex (void *random_ctx, nettle_random_func random, ecc_key * key,
                 mpz_t prime, mpz_t order, mpz_t A, mpz_t B, mpz_t Gx, mpz_t Gy,
                 gnutls_ecc_curve_t curve_id, int timing_res)
{
  int err;
  ecc_point *base;
  unsigned char *buf;
  int keysize;

  if (key == NULL || random == NULL)
    return -1;

  keysize = nettle_mpz_sizeinbase_256_u (order);

  /* allocate ram */
  base = NULL;
  buf = malloc (keysize);
  if (buf == NULL)
    return -1;

  /* make up random string */
  random (random_ctx, keysize, buf);

  /* setup the key variables */
  if ((err =
       mp_init_multi (&key->pubkey.x, &key->pubkey.y, &key->pubkey.z, &key->k,
                      &key->prime, &key->order, &key->A, &key->B, &key->Gx, &key->Gy,
                      NULL)) != 0)
    {
      goto ERR_BUF;
    }
  base = ecc_new_point ();
  if (base == NULL)
    {
      err = -1;
      goto errkey;
    }

  /* read in the specs for this key */
  mpz_set (key->prime, prime);
  mpz_set (key->order, order);
  mpz_set (key->Gx, Gx);
  mpz_set (key->Gy, Gy);
  mpz_set (key->A, A);
  mpz_set (key->B, B);

  mpz_set (base->x, key->Gx);
  mpz_set (base->y, key->Gy);
  mpz_set_ui (base->z, 1);

  nettle_mpz_set_str_256_u (key->k, keysize, buf);

  /* the key should be smaller than the order of base point */
  if (mpz_cmp (key->k, key->order) >= 0)
    {
      mpz_mod (key->k, key->k, key->order);
    }
  /* make the public key */
  if (timing_res)
    err = ecc_mulmod_wmnaf_cached_timing (key->k, curve_id, &key->pubkey, key->A, key->prime, 1);
  else
    err = ecc_mulmod_wmnaf_cached (key->k, curve_id, &key->pubkey, key->A, key->prime, 1);

  if (err != 0)
    goto errkey;

  key->type = PK_PRIVATE;

  /* free up ram */
  err = 0;
  goto cleanup;
errkey:
  mp_clear_multi (&key->pubkey.x, &key->pubkey.y, &key->pubkey.z, &key->k,
                  &key->order, &key->prime, &key->Gx, &key->Gy, &key->A, &key->B,
                  NULL);
cleanup:
  ecc_del_point (base);
ERR_BUF:
  free (buf);
  return err;
}
コード例 #13
0
int
main (int argc, char **argv)
{
    mpz_t x2;
    mpz_t x, rem;
    mpz_t temp, temp2;
    mp_size_t x2_size;
    int i;
    int reps = 20000;
    gmp_randstate_ptr rands;
    mpz_t bs;
    unsigned long size_range;

    tests_start ();
    rands = RANDS;

    mpz_init (bs);

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

    mpz_init (x2);
    mpz_init (x);
    mpz_init (rem);
    mpz_init (temp);
    mpz_init (temp2);

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

        mpz_urandomb (bs, rands, size_range);
        x2_size = mpz_get_ui (bs);
        mpz_rrandomb (x2, rands, x2_size);

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

        mpz_sqrtrem (x, rem, x2);
        mpz_mul (temp, x, x);

        /* Is square of result > argument?  */
        if (mpz_cmp (temp, x2) > 0)
            dump_abort (x2, x, rem);

        mpz_add_ui (temp2, x, 1);
        mpz_mul (temp2, temp2, temp2);

        /* Is square of (result + 1) <= argument?  */
        if (mpz_cmp (temp2, x2) <= 0)
            dump_abort (x2, x, rem);

        mpz_add (temp2, temp, rem);

        /* Is the remainder wrong?  */
        if (mpz_cmp (x2, temp2) != 0)
            dump_abort (x2, x, rem);
    }

    mpz_clear (bs);
    mpz_clear (x2);
    mpz_clear (x);
    mpz_clear (rem);
    mpz_clear (temp);
    mpz_clear (temp2);

    tests_end ();
    exit (0);
}
コード例 #14
0
ファイル: t-root.c プロジェクト: RodneyBates/M3Devel
void
check_one (mpz_t root1, mpz_t x2, unsigned long nth, int i)
{
  mpz_t temp, temp2;
  mpz_t root2, rem2;

  mpz_init (root2);
  mpz_init (rem2);
  mpz_init (temp);
  mpz_init (temp2);

  MPZ_CHECK_FORMAT (root1);

  mpz_rootrem (root2, rem2, x2, nth);
  MPZ_CHECK_FORMAT (root2);
  MPZ_CHECK_FORMAT (rem2);

  mpz_pow_ui (temp, root1, nth);
  MPZ_CHECK_FORMAT (temp);

  mpz_add (temp2, temp, rem2);

  /* Is power of result > argument?  */
  if (mpz_cmp (root1, root2) != 0 || mpz_cmp (x2, temp2) != 0 || mpz_cmp (temp, x2) > 0)
    {
      fprintf (stderr, "ERROR after test %d\n", i);
      debug_mp (x2, 10);
      debug_mp (root1, 10);
      debug_mp (root2, 10);
      fprintf (stderr, "nth: %lu\n", nth);
      abort ();
    }

  if (nth > 1 && mpz_cmp_ui (temp, 1L) > 0 && ! mpz_perfect_power_p (temp))
    {
      fprintf (stderr, "ERROR in mpz_perfect_power_p after test %d\n", i);
      debug_mp (temp, 10);
      debug_mp (root1, 10);
      fprintf (stderr, "nth: %lu\n", nth);
      abort ();
    }

  if (nth <= 10000)		/* skip too expensive test */
    {
      mpz_add_ui (temp2, root1, 1L);
      mpz_pow_ui (temp2, temp2, nth);
      MPZ_CHECK_FORMAT (temp2);

      /* Is square of (result + 1) <= argument?  */
      if (mpz_cmp (temp2, x2) <= 0)
	{
	  fprintf (stderr, "ERROR after test %d\n", i);
	  debug_mp (x2, 10);
	  debug_mp (root1, 10);
	  fprintf (stderr, "nth: %lu\n", nth);
	  abort ();
	}
    }

  mpz_clear (root2);
  mpz_clear (rem2);
  mpz_clear (temp);
  mpz_clear (temp2);
}
コード例 #15
0
ファイル: mpi.c プロジェクト: gnutls/gnutls
static int wrap_nettle_mpi_cmp(const bigint_t u, const bigint_t v)
{
	mpz_t *i1 = u, *i2 = v;

	return mpz_cmp(*i1, *i2);
}
/**
 * <p>Factorises a big integer using Pollard's rho method and some tweaks</a>
 * <p>
 *   Pollard's rho (ρ) method is a special-purpose integer factorisation algorithm used
 *   for factoring integers with small factors. As you know, they are not that unusual.
 * </p>
 *
 * @param   n                 The big integer
 * @param   c                 The seed index, 0 for autoselection of seed value
 * @param   output            The buffer to which to add [probable] prime factors
 * @param   outputPtr         The buffer's pointer
 * @param   initialRootOrder  The initial root order
 * @return                    Whether the factorisation was successful
 */
boolean factorisePollardsRho(Bignum n, llong c, Buffer output, long* outputPtr, int initialRootOrder)
{
    if (c > SEED_LIMIT)
        return false;

    llong cc = *(seeds + c);
    if (c == 0)
        { selectSeed(cc, n); }

    int i, m, cd;
    String prime;
    int itr;

    int rootOrder = initialRootOrder, pRootOrder = 1, r;

    #define f(X)  mpz_mul(X, X, X);  mpz_add_ui(X, X, cc)

    Bignum factor; mpz_init_set(factor, n);
    Bignum d; mpz_init(d);
    Bignum x; mpz_init_set_ui(x, cc);
    Bignum y; mpz_init_set_ui(y, cc);
    Bignum conjA; mpz_init(conjA);
    Bignum conjB; mpz_init(conjB);


    #define recursion(X, Y)  factorisePollardsRho(X, c + 1, output, outputPtr, Y)


    for (;;)
    {
        pRootOrder = maxRoot(factor);
	if (pRootOrder != 1)
	{
	    rootOrder *= pRootOrder;
	    mpz_root(factor, factor, pRootOrder);
	}
	else
	{
	    //There may exist a number b = (A = ⌊√n⌋ + 1)² − n such that B = √b is an integer
	    //in which case n = (A − B)(A + B)  [n is(!) odd composite]. If not, the only the
	    //trivial iteration of A (A += 1) seems to be the one not consuming your entire
	    //CPU and it is also guaranteed to find the factors, but it is just so slow.

	    mpz_sqrt(conjA, factor);
	    mpz_add_ui(conjA, conjA, 1);
	    mpz_mul(conjB, conjA, conjA);
	    mpz_sub(conjB, conjB, factor);

	    if (mpz_root(conjB, conjB, 2))
	    {
		mpz_sub(factor, conjA, conjB);
	        if (recursion(factor, rootOrder) == false)
		    return false;

		mpz_add(factor, conjA, conjB);
		return recursion(factor, rootOrder);
	    }
	}


        itr = 0;
	do // Pollard  //                  http://en.wikipedia.org/wiki/Pollard's_rho_algorithm#Variants
	{
	    if (c)
	    {
	        if (itr++ > MAX_ITERATIONS_C)
		    return false;
	    }
	    else if (cc >= 10000)
	        if (itr++ > MAX_ITERATIONS)
	            return recursion(factor, rootOrder);

	    //Floyd
	    f(x); f(y); f(y);
	    mpz_mod(x, x, factor);
	    mpz_mod(y, y, factor);

	    mpz_sub(d, x, y);
	    mpz_abs(d, d);
	    mpz_gcd(d, d, factor);
	}
	  while (equals(d, 1));


	if (mpz_cmp(factor, d) == 0)
	{
	    if (isPrime(factor))
	    {
	        String strFactor = bignumToString(factor);
	        for (r = 0; r < rootOrder; r++)
		{
		    appendToBuffer(output, *outputPtr, strFactor);
		    appendToBuffer(output, (*outputPtr) + 1, "\n");
		    (*outputPtr) += 2;
		}
	        return true;
	    }
	    return recursion(factor, rootOrder);
	}

	if (isNotPrime(d))
	{
	    cd = contDiv(factor, factor, d, null, null, 0);

            if (recursion(d, rootOrder * cd) == false)
	        return false;

	    if (equals(factor, 1))
	        return true;
	}
	else
	{
	    contDiv(factor, factor, d, output, outputPtr, rootOrder);

	    if (equals(factor, 1))
	        return true;
	}
        
	if (isPrime(factor))
	{
	    String strFactor = bignumToString(factor);
	    for (r = 0; r < rootOrder; r++)
	    {
	        appendToBuffer(output, *outputPtr, strFactor);
		appendToBuffer(output, (*outputPtr) + 1, "\n");
		(*outputPtr) += 2;
	    }
	    return true;
	}
    }

    return true;
}
コード例 #17
0
ファイル: strutils.c プロジェクト: GPtpvWKrrZWERTEg/mccp
static inline bool
s_mpz_le(MP_INT *z1, MP_INT *z2) {
  return ((mpz_cmp(z1, z2) < 0) || (mpz_cmp(z1, z2) == 0)) ?
         true : false;
}
コード例 #18
0
ファイル: t-tdiv.c プロジェクト: mahdiz/mpclib
int
main (int argc, char **argv)
{
  mpz_t dividend, divisor;
  mpz_t quotient, remainder;
  mpz_t quotient2, remainder2;
  mpz_t temp;
  mp_size_t dividend_size, divisor_size;
  int i;
  int reps = 200;
  gmp_randstate_ptr rands;
  mpz_t bs;
  unsigned long bsi, size_range;

  tests_start ();
  rands = RANDS;

  mpz_init (bs);

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

  mpz_init (dividend);
  mpz_init (divisor);
  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) % 16 + 2; /* 0..131071 bit operands */

      do
	{
	  mpz_urandomb (bs, rands, size_range);
	  divisor_size = mpz_get_ui (bs);
	  mpz_rrandomb (divisor, rands, divisor_size);
	}
      while (mpz_sgn (divisor) == 0);

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

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

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

      mpz_tdiv_qr (quotient, remainder, dividend, divisor);
      mpz_tdiv_q (quotient2, dividend, divisor);
      mpz_tdiv_r (remainder2, dividend, divisor);

      /* First determine that the quotients and remainders computed
	 with different functions are equal.  */
      if (mpz_cmp (quotient, quotient2) != 0)
	dump_abort (dividend, divisor);
      if (mpz_cmp (remainder, remainder2) != 0)
	dump_abort (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) ^ mpz_cmp_ui (divisor, 0)) < 0))
	dump_abort (dividend, divisor);

      /* Check if the remainder has the same sign as the dividend
	 (quotient rounded towards 0).  */
      if (mpz_cmp_ui (remainder, 0) != 0)
	if ((mpz_cmp_ui (remainder, 0) < 0) != (mpz_cmp_ui (dividend, 0) < 0))
	  dump_abort (dividend, divisor);

      mpz_mul (temp, quotient, divisor);
      mpz_add (temp, temp, remainder);
      if (mpz_cmp (temp, dividend) != 0)
	dump_abort (dividend, divisor);

      mpz_abs (temp, divisor);
      mpz_abs (remainder, remainder);
      if (mpz_cmp (remainder, temp) >= 0)
	dump_abort (dividend, divisor);
    }

  mpz_clear (bs);
  mpz_clear (dividend);
  mpz_clear (divisor);
  mpz_clear (quotient);
  mpz_clear (remainder);
  mpz_clear (quotient2);
  mpz_clear (remainder2);
  mpz_clear (temp);

  tests_end ();
  exit (0);
}
コード例 #19
0
ファイル: dive.c プロジェクト: AllardJ/Tomato
int
main (int argc, char **argv)
{
  mpz_t op1, op2;
  mpz_t prod, quot;
  mp_size_t size;
  int i;
  int reps = 5000;
  gmp_randstate_ptr rands;
  mpz_t bs;
  unsigned long bsi, size_range;

  tests_start ();
  TESTS_REPS (reps, argv, argc);

  rands = RANDS;

  mp_trace_base = -16;

  mpz_init (bs);

  mpz_init (op1);
  mpz_init (op2);
  mpz_init (prod);
  mpz_init (quot);

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

      mpz_urandomb (bs, rands, size_range);
      size = mpz_get_ui (bs);
      mpz_rrandomb (op1, rands, size);

      do
	{
	  mpz_urandomb (bs, rands, size_range);
	  size = mpz_get_ui (bs);
	  mpz_rrandomb (op2, rands, size);
	}
      while (mpz_sgn (op2) == 0);

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

      mpz_mul (prod, op1, op2);

      mpz_divexact (quot, prod, op2);
      MPZ_CHECK_FORMAT (quot);

      if (mpz_cmp (quot, op1) != 0)
        {
          printf ("Wrong results:\n");
          mpz_trace ("  got     ", quot);
          mpz_trace ("  want    ", op1);
          mpz_trace ("  dividend", prod);
          mpz_trace ("  divisor ", op2);
          abort ();
        }
    }

  mpz_clear (bs);
  mpz_clear (op1);
  mpz_clear (op2);
  mpz_clear (prod);
  mpz_clear (quot);

  tests_end ();
  exit (0);
}
コード例 #20
0
ファイル: rsa-gmp.c プロジェクト: Kendra123/heimdal
static int
gmp_rsa_public_decrypt(int flen, const unsigned char* from,
			 unsigned char* to, RSA* rsa, int padding)
{
    unsigned char *p;
    size_t size;
    mpz_t s, us, n, e;

    if (padding != RSA_PKCS1_PADDING)
	return -1;

    if (flen > RSA_size(rsa))
	return -2;

    BN2mpz(n, rsa->n);
    BN2mpz(e, rsa->e);

#if 0
    /* Check that the exponent is larger then 3 */
    if (mp_int_compare_value(&e, 3) <= 0) {
	mp_int_clear(&n);
	mp_int_clear(&e);
	return -3;
    }
#endif

    mpz_init(s);
    mpz_init(us);
    mpz_import(s, flen, 1, 1, 1, 0, rk_UNCONST(from));

    if (mpz_cmp(s, n) >= 0) {
	mpz_clear(n);
	mpz_clear(e);
	return -4;
    }

    mpz_powm(us, s, e, n);

    mpz_clear(s);
    mpz_clear(n);
    mpz_clear(e);

    p = to;

    mpz_export(p, &size, 1, 1, 1, 0, us);
    assert(size <= RSA_size(rsa));

    mpz_clear(us);

    /* head zero was skipped by mp_int_to_unsigned */
    if (*p == 0)
	return -6;
    if (*p != 1)
	return -7;
    size--; p++;
    while (size && *p == 0xff) {
	size--; p++;
    }
    if (size == 0 || *p != 0)
	return -8;
    size--; p++;

    memmove(to, p, size);

    return size;
}
コード例 #21
0
ファイル: factor.c プロジェクト: PhilGabardo/RSA-Decryption
int main(int argc, char *argv[])
{

	// declare mpz structs
	mpz_t n; 
	mpz_t zero;
	mpz_t r;
	mpz_t d;
	mpz_t start;
	mpz_t end;
	mpz_t temp;
	mpz_t my_rank_mpz;
	mpz_t local_end;
	mpz_t current_prime;

	mpz_t global_end;

	mpz_init_set_ui(zero, 0);
	mpz_init(d);

	double t1, t2, totaltime;

	int tag = 0;
	int my_rank, p;
	int source, dest, i;

	mpz_init_set_str(n, argv[1], 10); // initialize the key (n)

	mpz_init(global_end);
	mpz_sqrt(global_end, n);

	// MPI boilerplate
	MPI_Status status;
	MPI_Request request;
	MPI_Init(&argc, &argv);
	MPI_Comm_size(MPI_COMM_WORLD, &p);
	MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);

	t1 = MPI_Wtime();

	// initialize mpz structs
	mpz_init(r);
	mpz_init(start);
	mpz_init(local_end);
	mpz_init(end);
	mpz_init(temp);
	mpz_init(current_prime);
	mpz_init(my_rank_mpz);
	mpz_init_set_ui(start, 2);
	mpz_set(temp, start);

	size_t temp_window_size = mpz_sizeinbase(temp, 2);

	mpz_add_ui(temp, temp, temp_window_size);

	for (i = 0; i < my_rank; i++){
		temp_window_size = mpz_sizeinbase(temp, 2);
		mpz_add_ui(temp, temp, temp_window_size);	
	}

	mpz_set(start, temp);
	size_t window_size =  mpz_sizeinbase(start, 2);
	mpz_add_ui(local_end, start, window_size);	


	mpz_init_set_ui(my_rank_mpz, my_rank);
	mpz_init_set(end, global_end);
	mpz_nextprime(current_prime, start);
	mpz_init_set_str(n, argv[1], 10);

	int check = 0;
	int flag = 0;
	int found = 0;

	MPI_Irecv(&found, 1, MPI_INTEGER, MPI_ANY_SOURCE, tag, MPI_COMM_WORLD, &request);
	MPI_Barrier(MPI_COMM_WORLD);

	while (mpz_cmp(start, end) <= 0){
		while(mpz_cmp(current_prime, local_end) <= 0 && mpz_cmp(current_prime, end) <= 0){
			mpz_mod(r, n, current_prime);
			if (mpz_cmp(zero, r) == 0){
				mpz_divexact(d, n, current_prime);
				gmp_printf("%Zd %Zd\n", d, current_prime);
				found = 1;
				for (dest = 0; dest < p; dest++){
					MPI_Isend(&found, 1, MPI_INTEGER, dest, tag, MPI_COMM_WORLD, &request);
				}
				break;		
			}
			check++;
			if (check == 500){
				check = 0;
				MPI_Test(&request, &flag, &status);
				if (flag){
					found = 1;
					break;
				}
			}
			mpz_nextprime(current_prime, current_prime);	
		}
		if( found == 1){
			break;
		}

		// calculate new start index

		mpz_set(temp, start);
		size_t temp_window_size = mpz_sizeinbase(start, 2);
		mpz_add_ui(temp, temp, temp_window_size);
		mpz_set(start, local_end);
		for (i = my_rank + 1; i < p; i++){
			temp_window_size = mpz_sizeinbase(temp, 2);
			mpz_add_ui(temp, temp, temp_window_size);
		}

		for (i = 0; i < my_rank; i++){
			temp_window_size = mpz_sizeinbase(temp, 2);
			mpz_add_ui(temp, temp, temp_window_size);
		}

		mpz_set(start, temp);

		temp_window_size = mpz_sizeinbase(start, 2);
		mpz_add_ui(local_end, start, temp_window_size);	

		mpz_nextprime(current_prime, start);
	}

	t2 = MPI_Wtime();
	totaltime = t2 - t1;
	MPI_Barrier(MPI_COMM_WORLD);
	if (my_rank == 0){
		char buf[0x1000];
		snprintf(buf, sizeof(buf), "time_%s", argv[1]);
		FILE *f = fopen(buf, "w");
		double other_totaltime = 0;
		fprintf(f, "0\t%1.2e\n", totaltime);
		for (source = 1; source < p; source++){
			MPI_Recv(&other_totaltime, 1, MPI_DOUBLE, source, tag, MPI_COMM_WORLD, &status);
			fprintf(f, "%d\t%1.2e\n", source, other_totaltime);
		}	
		fclose(f); 
	}
	else{
		MPI_Send(&totaltime, 1, MPI_DOUBLE, 0, tag, MPI_COMM_WORLD);
	}	
	MPI_Finalize();
	return 0;
}
コード例 #22
0
ファイル: rsa-gmp.c プロジェクト: Kendra123/heimdal
static int
gmp_rsa_private_decrypt(int flen, const unsigned char* from,
			  unsigned char* to, RSA* rsa, int padding)
{
    unsigned char *ptr;
    size_t size;
    mpz_t in, out, n, e;

    if (padding != RSA_PKCS1_PADDING)
	return -1;

    size = RSA_size(rsa);
    if (flen > size)
	return -2;

    mpz_init(in);
    mpz_init(out);

    BN2mpz(n, rsa->n);
    BN2mpz(e, rsa->e);

    mpz_import(in, flen, 1, 1, 1, 0, from);

    if(mpz_cmp_ui(in, 0) < 0 ||
       mpz_cmp(in, n) >= 0) {
	size = 0;
	goto out;
    }

    if (rsa->p && rsa->q && rsa->dmp1 && rsa->dmq1 && rsa->iqmp) {
	mpz_t p, q, dmp1, dmq1, iqmp;

	BN2mpz(p, rsa->p);
	BN2mpz(q, rsa->q);
	BN2mpz(dmp1, rsa->dmp1);
	BN2mpz(dmq1, rsa->dmq1);
	BN2mpz(iqmp, rsa->iqmp);

	rsa_private_calculate(in, p, q, dmp1, dmq1, iqmp, out);

	mpz_clear(p);
	mpz_clear(q);
	mpz_clear(dmp1);
	mpz_clear(dmq1);
	mpz_clear(iqmp);
    } else {
	mpz_t d;

#if 0
	if(mp_int_compare_zero(&in) < 0 ||
	   mp_int_compare(&in, &n) >= 0)
	    return MP_RANGE;
#endif

	BN2mpz(d, rsa->d);
	mpz_powm(out, in, d, n);
	mpz_clear(d);
    }

    ptr = to;
    {
	size_t ssize;
	mpz_export(ptr, &ssize, 1, 1, 1, 0, out);
	assert(size >= ssize);
	size = ssize;
    }

    /* head zero was skipped by mp_int_to_unsigned */
    if (*ptr != 2)
	return -3;
    size--; ptr++;
    while (size && *ptr != 0) {
	size--; ptr++;
    }
    if (size == 0)
	return -4;
    size--; ptr++;

    memmove(to, ptr, size);

out:
    mpz_clear(e);
    mpz_clear(n);
    mpz_clear(in);
    mpz_clear(out);

    return size;
}
コード例 #23
0
ファイル: data.c プロジェクト: LihuaWu/gcc
void 
gfc_advance_section (mpz_t *section_index, gfc_array_ref *ar,
		     mpz_t *offset_ret)
{
  int i;
  mpz_t delta;
  mpz_t tmp; 
  bool forwards;
  int cmp;

  for (i = 0; i < ar->dimen; i++)
    {
      if (ar->dimen_type[i] != DIMEN_RANGE)
	continue;

      if (ar->stride[i])
	{
	  mpz_add (section_index[i], section_index[i],
		   ar->stride[i]->value.integer);
	if (mpz_cmp_si (ar->stride[i]->value.integer, 0) >= 0)
	  forwards = true;
	else
	  forwards = false;
	}
      else
	{
	  mpz_add_ui (section_index[i], section_index[i], 1);
	  forwards = true;
	}
      
      if (ar->end[i])
	cmp = mpz_cmp (section_index[i], ar->end[i]->value.integer);
      else
	cmp = mpz_cmp (section_index[i], ar->as->upper[i]->value.integer);

      if ((cmp > 0 && forwards) || (cmp < 0 && !forwards))
	{
	  /* Reset index to start, then loop to advance the next index.  */
	  if (ar->start[i])
	    mpz_set (section_index[i], ar->start[i]->value.integer);
	  else
	    mpz_set (section_index[i], ar->as->lower[i]->value.integer);
	}
      else
	break;
    }

  mpz_set_si (*offset_ret, 0);
  mpz_init_set_si (delta, 1);
  mpz_init (tmp);
  for (i = 0; i < ar->dimen; i++)
    {
      mpz_sub (tmp, section_index[i], ar->as->lower[i]->value.integer);
      mpz_mul (tmp, tmp, delta);
      mpz_add (*offset_ret, tmp, *offset_ret);

      mpz_sub (tmp, ar->as->upper[i]->value.integer, 
	       ar->as->lower[i]->value.integer);
      mpz_add_ui (tmp, tmp, 1);
      mpz_mul (delta, tmp, delta);
    }
  mpz_clear (tmp);
  mpz_clear (delta);
}
コード例 #24
0
ファイル: rsa-gmp.c プロジェクト: Kendra123/heimdal
static int
gmp_rsa_generate_key(RSA *rsa, int bits, BIGNUM *e, BN_GENCB *cb)
{
    mpz_t el, p, q, n, d, dmp1, dmq1, iqmp, t1, t2, t3;
    int counter, ret;

    if (bits < 789)
	return -1;

    ret = -1;

    mpz_init(el);
    mpz_init(p);
    mpz_init(q);
    mpz_init(n);
    mpz_init(d);
    mpz_init(dmp1);
    mpz_init(dmq1);
    mpz_init(iqmp);
    mpz_init(t1);
    mpz_init(t2);
    mpz_init(t3);

    BN2mpz(el, e);

    /* generate p and q so that p != q and bits(pq) ~ bits */

    counter = 0;
    do {
	BN_GENCB_call(cb, 2, counter++);
	random_num(p, bits / 2 + 1);
	mpz_nextprime(p, p);

	mpz_sub_ui(t1, p, 1);
	mpz_gcd(t2, t1, el);
    } while(mpz_cmp_ui(t2, 1) != 0);

    BN_GENCB_call(cb, 3, 0);

    counter = 0;
    do {
	BN_GENCB_call(cb, 2, counter++);
	random_num(q, bits / 2 + 1);
	mpz_nextprime(q, q);

	mpz_sub_ui(t1, q, 1);
	mpz_gcd(t2, t1, el);
    } while(mpz_cmp_ui(t2, 1) != 0);

    /* make p > q */
    if (mpz_cmp(p, q) < 0)
	mpz_swap(p, q);

    BN_GENCB_call(cb, 3, 1);

    /* calculate n,  		n = p * q */
    mpz_mul(n, p, q);

    /* calculate d, 		d = 1/e mod (p - 1)(q - 1) */
    mpz_sub_ui(t1, p, 1);
    mpz_sub_ui(t2, q, 1);
    mpz_mul(t3, t1, t2);
    mpz_invert(d, el, t3);

    /* calculate dmp1		dmp1 = d mod (p-1) */
    mpz_mod(dmp1, d, t1);
    /* calculate dmq1		dmq1 = d mod (q-1) */
    mpz_mod(dmq1, d, t2);
    /* calculate iqmp 		iqmp = 1/q mod p */
    mpz_invert(iqmp, q, p);

    /* fill in RSA key */

    rsa->e = mpz2BN(el);
    rsa->p = mpz2BN(p);
    rsa->q = mpz2BN(q);
    rsa->n = mpz2BN(n);
    rsa->d = mpz2BN(d);
    rsa->dmp1 = mpz2BN(dmp1);
    rsa->dmq1 = mpz2BN(dmq1);
    rsa->iqmp = mpz2BN(iqmp);

    ret = 1;

    mpz_clear(el);
    mpz_clear(p);
    mpz_clear(q);
    mpz_clear(n);
    mpz_clear(d);
    mpz_clear(dmp1);
    mpz_clear(dmq1);
    mpz_clear(iqmp);
    mpz_clear(t1);
    mpz_clear(t2);
    mpz_clear(t3);

    return ret;
}
コード例 #25
0
ファイル: comparison.cpp プロジェクト: kolhagen/bitvoting
bool mpz_equal(const mpz_t first, const mpz_t second)
{
    return (mpz_cmp(first, second) == 0);
}
コード例 #26
0
ファイル: hector_sig.c プロジェクト: JacobBarthelmeh/supercop
int shortmessagesigned(
		unsigned char *m,
		unsigned long long *mlen,
		const unsigned char *sm,
		unsigned long long smlen,
		const unsigned char *pk,
		unsigned long long pklen
		)
{
	/* See Handbook of Elliptic and Hyperelliptic Curve Cryptography, page 571 */

	init_all();

	int i, ret;
	unsigned char b[SECRETKEY_BYTES];

	mpz_t hm;
	mpz_t u;
	mpz_t s;
	mpz_t u1;
	mpz_t u2;
	mpz_t w;
	mpz_t fhash;

	mpz_init(hm);
	mpz_init(u);
	mpz_init(s);
	mpz_init(u1);
	mpz_init(u2);
	mpz_init(w);
	mpz_init(fhash);

	divclass key;
	divclass_init(key);

	bytearray_to_mpz_t(hm, sm, SHORTMESSAGE_BYTES);
	bytearray_to_mpz_t(u, sm + SHORTMESSAGE_BYTES, SECRETKEY_BYTES);
	bytearray_to_mpz_t(s, sm + SHORTMESSAGE_BYTES + SECRETKEY_BYTES, SECRETKEY_BYTES);
	bytearray_to_divclass(key, pk);

	/* TODO: Test whether u,s \in [1,l-1] */
	mpz_invert(w, s, p);

	mpz_mul(u1, hm, w);
	mpz_mod(u1, u1, p);

	mpz_mul(u2, u, w);
	mpz_mod(u2, u2, p);


	divclass fbar;
	divclass dummy;
	divclass_init(fbar);
	divclass_init(dummy);

	mpz_t_to_scrambled_bytearray(b, SECRETKEY_BYTES, u1);
	generator_multiply(fbar, b);
	/* divclass_multiply(fbar, GENERATOR, u1); */

	divclass_multiply(dummy, key, u2);

	divclass_make_affine(dummy, dummy);

	divclass_make_affine(fbar, fbar);

	divclass_mixadd(fbar, fbar, dummy);
	divclass_make_affine(fbar, fbar);

	//DEBUG
	divclass_hash(fhash, fbar);

	if(!mpz_cmp(u, fhash)) 
	{
		for(i = 0; i < SHORTMESSAGE_BYTES; i++)
			m[i] = sm[i];
		*mlen = SHORTMESSAGE_BYTES;
		ret = 0;
	}
	else
	{
		ret = -100;
		/* fprintf(stderr, "Signature forgery or stupid programming error!"); */
	}

	mpz_clear(hm);
	mpz_clear(u);
	mpz_clear(s);
	mpz_clear(u1);
	mpz_clear(u2);
	mpz_clear(w);
	mpz_clear(fhash);

	clear_all();
	return ret ;
}
コード例 #27
0
ファイル: number.c プロジェクト: Liutos/LiutCL
BOOL bignum_eq(Bignum n, Bignum m)
{
    return mpz_cmp(theBIGNUM(n), theBIGNUM(m)) == 0;
}
コード例 #28
0
ファイル: problem29.c プロジェクト: 99plus2/project-euler-c
int compare(const void *a, const void *b)
{
  return mpz_cmp(*(const mpz_t *)a, *(mpz_t const *)b);
}
コード例 #29
0
int main()
{
	int i, z;

	/* Initialize constants */
	mpz_init_set_str(c[0], "1", 10);
	mpz_init_set_str(c[1], "5", 10);

	/* Initialize variables */
	for (i = 0; i < VARS; i++) {
		mpz_init(v[i]);
	}

	/* Goal: ? a^5H */
	mpz_add(v[1], v[1], c[1]);
	mpz_add(v[35], v[35], c[0]);

	while (1) {
		if (0) {
		} else if (mpz_cmp(v[35], c[0]) >= 0) {
			/* H => mZ */
			mpz_sub(v[35], v[35], c[0]);
			mpz_add(v[12], v[12], c[0]);
			mpz_add(v[0], v[0], c[0]);
		} else if (mpz_cmp(v[1], c[0]) >= 0 && mpz_cmp(v[12], c[0]) >= 0) {
			/* am => af */
			mpz_sub(v[1], v[1], c[0]);
			mpz_sub(v[12], v[12], c[0]);
			mpz_add(v[1], v[1], c[0]);
			mpz_add(v[7], v[7], c[0]);
		} else if (mpz_cmp(v[12], c[0]) >= 0) {
			/* m => J */
			mpz_sub(v[12], v[12], c[0]);
			mpz_add(v[37], v[37], c[0]);
		} else if (mpz_cmp(v[1], c[0]) >= 0 && mpz_cmp(v[7], c[0]) >= 0) {
			/* af => aB */
			mpz_sub(v[1], v[1], c[0]);
			mpz_sub(v[7], v[7], c[0]);
			mpz_add(v[1], v[1], c[0]);
			mpz_add(v[15], v[15], c[0]);
		} else if (mpz_cmp(v[7], c[0]) >= 0) {
			/* f => k */
			mpz_sub(v[7], v[7], c[0]);
			mpz_add(v[10], v[10], c[0]);
		} else if (mpz_cmp(v[1], c[0]) >= 0 && mpz_cmp(v[15], c[0]) >= 0) {
			/* aB => u */
			mpz_sub(v[1], v[1], c[0]);
			mpz_sub(v[15], v[15], c[0]);
			mpz_add(v[22], v[22], c[0]);
		} else if (mpz_cmp(v[15], c[0]) >= 0) {
			/* B => u */
			mpz_sub(v[15], v[15], c[0]);
			mpz_add(v[22], v[22], c[0]);
		} else if (mpz_cmp(v[22], c[0]) >= 0) {
			/* u => cL */
			mpz_sub(v[22], v[22], c[0]);
			mpz_add(v[3], v[3], c[0]);
			mpz_add(v[38], v[38], c[0]);
		} else if (mpz_cmp(v[38], c[0]) >= 0) {
			/* L => eG */
			mpz_sub(v[38], v[38], c[0]);
			mpz_add(v[4], v[4], c[0]);
			mpz_add(v[32], v[32], c[0]);
		} else if (mpz_cmp(v[32], c[0]) >= 0) {
			/* G => f */
			mpz_sub(v[32], v[32], c[0]);
			mpz_add(v[7], v[7], c[0]);
		} else if (mpz_cmp(v[3], c[0]) >= 0 && mpz_cmp(v[10], c[0]) >= 0) {
			/* ck => cr */
			mpz_sub(v[3], v[3], c[0]);
			mpz_sub(v[10], v[10], c[0]);
			mpz_add(v[3], v[3], c[0]);
			mpz_add(v[21], v[21], c[0]);
		} else if (mpz_cmp(v[10], c[0]) >= 0) {
			/* k => d */
			mpz_sub(v[10], v[10], c[0]);
			mpz_add(v[5], v[5], c[0]);
		} else if (mpz_cmp(v[3], c[0]) >= 0 && mpz_cmp(v[21], c[0]) >= 0) {
			/* cr => b */
			mpz_sub(v[3], v[3], c[0]);
			mpz_sub(v[21], v[21], c[0]);
			mpz_add(v[2], v[2], c[0]);
		} else if (mpz_cmp(v[21], c[0]) >= 0) {
			/* r => b */
			mpz_sub(v[21], v[21], c[0]);
			mpz_add(v[2], v[2], c[0]);
		} else if (mpz_cmp(v[2], c[0]) >= 0 && mpz_cmp(v[0], c[0]) >= 0) {
			/* bZ => yZ */
			mpz_sub(v[2], v[2], c[0]);
			mpz_sub(v[0], v[0], c[0]);
			mpz_add(v[26], v[26], c[0]);
			mpz_add(v[0], v[0], c[0]);
		} else if (mpz_cmp(v[2], c[0]) >= 0) {
			/* b => j */
			mpz_sub(v[2], v[2], c[0]);
			mpz_add(v[11], v[11], c[0]);
		} else if (mpz_cmp(v[26], c[0]) >= 0 && mpz_cmp(v[0], c[0]) >= 0) {
			/* yZ => t */
			mpz_sub(v[26], v[26], c[0]);
			mpz_sub(v[0], v[0], c[0]);
			mpz_add(v[23], v[23], c[0]);
		} else if (mpz_cmp(v[26], c[0]) >= 0) {
			/* y => t */
			mpz_sub(v[26], v[26], c[0]);
			mpz_add(v[23], v[23], c[0]);
		} else if (mpz_cmp(v[23], c[0]) >= 0) {
			/* t => iK */
			mpz_sub(v[23], v[23], c[0]);
			mpz_add(v[8], v[8], c[0]);
			mpz_add(v[36], v[36], c[0]);
		} else if (mpz_cmp(v[36], c[0]) >= 0) {
			/* K => lE */
			mpz_sub(v[36], v[36], c[0]);
			mpz_add(v[13], v[13], c[0]);
			mpz_add(v[30], v[30], c[0]);
		} else if (mpz_cmp(v[30], c[0]) >= 0) {
			/* E => b */
			mpz_sub(v[30], v[30], c[0]);
			mpz_add(v[2], v[2], c[0]);
		} else if (mpz_cmp(v[8], c[0]) >= 0 && mpz_cmp(v[11], c[0]) >= 0) {
			/* ij => is */
			mpz_sub(v[8], v[8], c[0]);
			mpz_sub(v[11], v[11], c[0]);
			mpz_add(v[8], v[8], c[0]);
			mpz_add(v[20], v[20], c[0]);
		} else if (mpz_cmp(v[11], c[0]) >= 0) {
			/* j => I */
			mpz_sub(v[11], v[11], c[0]);
			mpz_add(v[34], v[34], c[0]);
		} else if (mpz_cmp(v[8], c[0]) >= 0 && mpz_cmp(v[20], c[0]) >= 0) {
			/* is => x */
			mpz_sub(v[8], v[8], c[0]);
			mpz_sub(v[20], v[20], c[0]);
			mpz_add(v[27], v[27], c[0]);
		} else if (mpz_cmp(v[20], c[0]) >= 0) {
			/* s => x */
			mpz_sub(v[20], v[20], c[0]);
			mpz_add(v[27], v[27], c[0]);
		} else if (mpz_cmp(v[27], c[0]) >= 0) {
			/* x => DZ */
			mpz_sub(v[27], v[27], c[0]);
			mpz_add(v[31], v[31], c[0]);
			mpz_add(v[0], v[0], c[0]);
		} else if (mpz_cmp(v[31], c[0]) >= 0) {
			/* D => j */
			mpz_sub(v[31], v[31], c[0]);
			mpz_add(v[11], v[11], c[0]);
		} else if (mpz_cmp(v[34], c[0]) >= 0) {
			/* I => k */
			mpz_sub(v[34], v[34], c[0]);
			mpz_add(v[10], v[10], c[0]);
		} else if (mpz_cmp(v[5], c[0]) >= 0 && mpz_cmp(v[0], c[0]) >= 0) {
			/* dZ => wZ */
			mpz_sub(v[5], v[5], c[0]);
			mpz_sub(v[0], v[0], c[0]);
			mpz_add(v[24], v[24], c[0]);
			mpz_add(v[0], v[0], c[0]);
		} else if (mpz_cmp(v[5], c[0]) >= 0) {
			/* d => h */
			mpz_sub(v[5], v[5], c[0]);
			mpz_add(v[9], v[9], c[0]);
		} else if (mpz_cmp(v[24], c[0]) >= 0 && mpz_cmp(v[0], c[0]) >= 0) {
			/* wZ => o */
			mpz_sub(v[24], v[24], c[0]);
			mpz_sub(v[0], v[0], c[0]);
			mpz_add(v[16], v[16], c[0]);
		} else if (mpz_cmp(v[24], c[0]) >= 0) {
			/* w => o */
			mpz_sub(v[24], v[24], c[0]);
			mpz_add(v[16], v[16], c[0]);
		} else if (mpz_cmp(v[16], c[0]) >= 0) {
			/* o => d */
			mpz_sub(v[16], v[16], c[0]);
			mpz_add(v[5], v[5], c[0]);
		} else if (mpz_cmp(v[9], c[0]) >= 0 && mpz_cmp(v[13], c[0]) >= 0) {
			/* hl => lp */
			mpz_sub(v[9], v[9], c[0]);
			mpz_sub(v[13], v[13], c[0]);
			mpz_add(v[13], v[13], c[0]);
			mpz_add(v[19], v[19], c[0]);
		} else if (mpz_cmp(v[9], c[0]) >= 0) {
			/* h => g */
			mpz_sub(v[9], v[9], c[0]);
			mpz_add(v[6], v[6], c[0]);
		} else if (mpz_cmp(v[13], c[0]) >= 0 && mpz_cmp(v[19], c[0]) >= 0) {
			/* lp => v */
			mpz_sub(v[13], v[13], c[0]);
			mpz_sub(v[19], v[19], c[0]);
			mpz_add(v[25], v[25], c[0]);
		} else if (mpz_cmp(v[19], c[0]) >= 0) {
			/* p => v */
			mpz_sub(v[19], v[19], c[0]);
			mpz_add(v[25], v[25], c[0]);
		} else if (mpz_cmp(v[25], c[0]) >= 0) {
			/* v => CZ */
			mpz_sub(v[25], v[25], c[0]);
			mpz_add(v[29], v[29], c[0]);
			mpz_add(v[0], v[0], c[0]);
		} else if (mpz_cmp(v[29], c[0]) >= 0) {
			/* C => h */
			mpz_sub(v[29], v[29], c[0]);
			mpz_add(v[9], v[9], c[0]);
		} else if (mpz_cmp(v[4], c[0]) >= 0 && mpz_cmp(v[6], c[0]) >= 0) {
			/* eg => en */
			mpz_sub(v[4], v[4], c[0]);
			mpz_sub(v[6], v[6], c[0]);
			mpz_add(v[4], v[4], c[0]);
			mpz_add(v[17], v[17], c[0]);
		} else if (mpz_cmp(v[6], c[0]) >= 0) {
			/* g => q */
			mpz_sub(v[6], v[6], c[0]);
			mpz_add(v[18], v[18], c[0]);
		} else if (mpz_cmp(v[4], c[0]) >= 0 && mpz_cmp(v[17], c[0]) >= 0) {
			/* en => z */
			mpz_sub(v[4], v[4], c[0]);
			mpz_sub(v[17], v[17], c[0]);
			mpz_add(v[28], v[28], c[0]);
		} else if (mpz_cmp(v[17], c[0]) >= 0) {
			/* n => z */
			mpz_sub(v[17], v[17], c[0]);
			mpz_add(v[28], v[28], c[0]);
		} else if (mpz_cmp(v[28], c[0]) >= 0) {
			/* z => aF */
			mpz_sub(v[28], v[28], c[0]);
			mpz_add(v[1], v[1], c[0]);
			mpz_add(v[33], v[33], c[0]);
		} else if (mpz_cmp(v[33], c[0]) >= 0) {
			/* F => g */
			mpz_sub(v[33], v[33], c[0]);
			mpz_add(v[6], v[6], c[0]);
		} else if (mpz_cmp(v[1], c[0]) >= 0 && mpz_cmp(v[18], c[0]) >= 0) {
			/* aq => A */
			mpz_sub(v[1], v[1], c[0]);
			mpz_sub(v[18], v[18], c[0]);
			mpz_add(v[14], v[14], c[0]);
		} else if (mpz_cmp(v[18], c[0]) >= 0) {
			/* q => A */
			mpz_sub(v[18], v[18], c[0]);
			mpz_add(v[14], v[14], c[0]);
		} else if (mpz_cmp(v[14], c[0]) >= 0) {
			/* A => m */
			mpz_sub(v[14], v[14], c[0]);
			mpz_add(v[12], v[12], c[0]);
		} else if (mpz_cmp(v[37], c[0]) >= 0) {
			/* J */
			mpz_sub(v[37], v[37], c[0]);
		} else {
			break;
		}
	}

	z = 1;
	for (i = 0; i < VARS; i++) {
		if (mpz_cmp_ui(v[i], 0) > 0) {
			if (!z) {
				printf(" ");
			}
			z = 0;
			printf("%s", n[i]);
			if (mpz_cmp_ui(v[i], 1) > 0) {
				printf("^");
				mpz_out_str(stdout, 10, v[i]);
			}
		}
	}
	if (z) {
		printf("1");
	}
	printf("\n");

	return 0;
}
コード例 #30
0
int main(int argc, char *argv[])
{  
  ///list all the files in the directory///
   DIR *d;
   FILE  *fpub, *fpriv, *fciph, *fplain, *ftag, *fpairing, *ftemp, *frand;//, *fp6, *fp7;
   paillier_pubkey_t *pub;
   paillier_prvkey_t *priv;
   paillier_get_rand_t get_rand;
   paillier_plaintext_t *plain;
   paillier_ciphertext_t *cipher, *cipher_copy;
   paillier_tag* tag;
   mpz_t tag_sig, *rand_prf;
   gmp_randstate_t rand;
   char *len;
   struct stat st= {0};
   unsigned char *data;
   int count=0, count1=0, gbytes, n, no_copies=10;
   struct dirent *dir;
   ///pairing parameters
   pairing_t pairing;
   //pairing_t p;
    //printf("setting pairing parameters\n");
    //pairing_init_set_str(pairing, param_str);
  // printf("after pairing setup\n");
   element_t g, h, u, temp_pow, test1, test2;
   element_t public_key, sig;
   element_t secret_key;
   ///end of pairing parameters
   //initialize pairing parametrs
   pbc_demo_pairing_init(pairing, argc, argv);
   element_init_G2(g, pairing);
   element_init_G1(u, pairing);
   element_init_G1(test1, pairing);
   element_init_G2(test2, pairing);
   element_init_G1(temp_pow, pairing);
   element_init_G2(public_key, pairing);
  // element_from_hash(h, "hashofmessage", 13);
   element_init_G1(h, pairing);
   element_init_G1(sig, pairing);
   element_init_Zr(secret_key, pairing);
   //end of pairing parameters initialization
   //set up pairing parameters
   //generate system parameters
   element_random(g);
  // n = pairing_length_in_bytes_x_only_G1(pairing);
  // data = pbc_malloc(n);
  // gbytes = pairing_length_in_bytes_G2(pairing);
  // printf(" \n g in bytes %d \n", gbytes);
  // element_printf("system parameter g = %B\n", g);
   //generate private key
   element_random(secret_key);
   //generate u
   element_random(u);
   //calculating hash of a file name and mapping it to element in group G1
  // element_from_hash(h, "FileName", 8);	
   element_random(h);
   //element_printf("private key = %B\n", secret_key);
   //compute corresponding public key
   element_pow_zn(public_key, g, secret_key);
   //element_printf("public key = %B\n", public_key);
   //end of setup
   tag = (paillier_tag*) malloc(sizeof(paillier_tag));
   plain = (paillier_plaintext_t*) malloc(sizeof(paillier_plaintext_t));
   cipher = (paillier_ciphertext_t*) malloc(sizeof(paillier_ciphertext_t));
   mpz_init(plain->m);
   mpz_init(tag->t);	
   mpz_init(cipher->c);
   mpz_init(tag_sig);	
   rand_prf = (mpz_t*) malloc(n*sizeof(mpz_t));
   
   len = (char *)malloc(2048*sizeof(char));
  //****paillier key generation****
   if(!(fpub = fopen("pub.txt", "r")))
    {
       //fputs("Not able to read public key file!\n", stderr);
       paillier_keygen(&pub, &priv, get_rand,450);
       //fclose(fpub);	
       fpub = fopen("pub.txt", "w");
       gmp_fprintf(fpub, "%Zd\n", pub->p); 
       gmp_fprintf(fpub, "%Zd\n", pub->q);	
       gmp_fprintf(fpub, "%Zd\n", pub->n_plusone);
       //***Writing private keys into a file***
       fpriv = fopen("priv.txt", "w"); 	
       gmp_fprintf(fpriv, "%Zd\n", priv->lambda);  		
       gmp_fprintf(fpriv, "%Zd\n", priv->x);  		
       fclose(fpriv);
       //****End of writing private key in a file***	
    }
   else
    {
        printf("\n in else");
	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);
  //****end of paillier key generation****
  //printf("writing pairing parameters to a file\n");
  //writing pairing keys to file
  fpairing = fopen("pairing.txt", "w"); 
  
 /* n = pairing_length_in_bytes_compressed_G2(pairing);
  data = pbc_malloc(n);

  element_to_bytes_compressed(data, g);	
  element_printf(" decomp g %B\n", g);
  element_from_bytes_compressed(test2, data);
  element_printf(" decomp g %B\n", test2); */
  //writing compressed g to file
  element_fprintf(fpairing, "%B\n", g); 
//  element_printf(" g = %B\n", g);
  /*n = pairing_length_in_bytes_compressed_G1(pairing);
  data = pbc_malloc(n);
  element_to_bytes_compressed(data, u);	
  element_printf(" decomp g %B\n", u);
  element_from_bytes_compressed(test1, data);
  element_printf(" decomp g %B\n", test1);  
  //writing compressed u to file */
  element_fprintf(fpairing, "%B\n", u);
  //element_printf(" u = %B\n", u);
  //writing secret key to file
  element_fprintf(fpairing, "%B\n", secret_key); 
  //element_printf(" sk = %B\n", secret_key);
//  printf("secret key = %s\n",secret_key);	
 /* n = pairing_length_in_bytes_compressed_G2(pairing);
  data = pbc_malloc(n);
  element_to_bytes_compressed(data, public_key); 
  //writing compressed public key to file	*/ 
  element_fprintf(fpairing, "%B\n", public_key); 
  //element_printf("pk = %B\n", public_key);	
 /* n = pairing_length_in_bytes_compressed_G1(pairing);
  data = pbc_malloc(n);
  element_to_bytes_compressed(data, h);	
  element_printf(" decomp g %B\n", h);
  element_from_bytes_compressed(test1, data);
  element_printf(" decomp g %B\n", test1);  
  //writing compressed h to file */
  element_fprintf(fpairing, "%B\n", h);
  //element_printf("h = %B\n", h);
  //writing n to file
  gmp_fprintf(fpairing, "%Zd\n", pub->n);  		
  fclose(fpairing);
  //end of writing pairing keys to file  
  cipher_copy = (paillier_ciphertext_t*)malloc(no_copies*sizeof(paillier_ciphertext_t));
  frand = fopen("rand.txt","w");
  int i;
   init_rand(rand, get_rand, pub->bits / 8 + 1);
   for(i = 0; i< no_copies; i++)
   {
	mpz_init(rand_prf[i]);
	do
		mpz_urandomb(rand_prf[i], rand, pub->bits);
	while( mpz_cmp(rand_prf[i], pub->n) >= 0 );
	gmp_fprintf(frand, "%Zd\n", rand_prf[i]); 
	//printf("\nrandom : \n");
        //mpz_out_str(stdout, 10, rand_prf[i]);
   }
  fclose(frand);
  //****Opening files to read files and encrypt***** 
  d = opendir("./split");
   if (d)
   {
    while ((dir = readdir(d)) != NULL)
    {
     //printf("%s\n", dir->d_name);
     char fileName[1000], copy[1000];
     strcpy(fileName, "./split/");
     strcat(fileName,dir->d_name);	
     //printf("\nfile name %s", fileName);
     if(!(fplain = fopen(fileName, "r")))
      {
        printf("\n not able to read %s", fileName);
      //  fputs("not possible to read  file!\n", stderr);
	 count1++;
      }
      else
      {
	//printf("\n able to read %s", fileName);
	fgets(len, 2048, fplain);
        mpz_init_set_str(plain->m, len, 10);	
       // mpz_out_str(stdout, 10, plain->m);
	fclose(fplain);	
	//Writing cipher text to files
	strcpy(fileName, "./cipher/");
        //strcat(fileName,dir->d_name);	
        //printf("\nfilename %s",fileName);
        
         paillier_enc(tag, cipher_copy, pub,plain, get_rand, no_copies, rand_prf);
	// mpz_out_str(stdout, 10, tag->t);
	 int j;
         for(j=0;j < no_copies; j++)
         {
	    char num[20];
	    strcpy(copy, fileName);

	    sprintf(num, "copy%d/", (j+1));
	   // strcat(copy, );
	    strcat(copy, num);
	   if(stat(copy, &st) == -1)
	      mkdir(copy,0777);

            strcat(copy,dir->d_name);
            if(!(fciph = fopen(copy, "w")))
            {
	         printf("\nnot able to open file for writing cipher text %s", copy);
	    }
            else
            {
		// printf("\nbefore enc");
		
	        gmp_fprintf(fciph, "%Zd\n", cipher_copy[j].c); 	
                fclose(fciph); 	
	    }
         }	
	//writing tags to files
	strcpy(fileName, "./tag/");
        strcat(fileName,dir->d_name);	
        //printf("\nfilename %s",fileName);
        if(!(ftag = fopen(fileName, "w")))
        {
         printf("not able to open file for writing tag  %s", fileName);
        }
        else
        {
	
	 element_pow_mpz(temp_pow,u, tag->t);
	 element_mul(temp_pow, temp_pow, h);
	 element_pow_zn(sig, temp_pow, secret_key);
	 element_fprintf(ftag, "%B", sig);
	 fclose(ftag); 
        } 	
      }	
	count++;
    }	
   
    closedir(d);
   }
   
   printf("\nTotal number of files : %d, unreadable files %d", count, count1);
  
   return 0;
}