コード例 #1
0
/* Generate random moduli and check gcd */
int openSSLGenTest(mpz_t *n)
{
	mpz_t myN, genN, tmp;
	long counter = 0;
	int status = FAIL;

	printf("[INFO ] Trying OpenSSL generating\n");

	mpz_init_set(myN, *n);	mpz_init(genN);		mpz_init(tmp);

	BIGNUM *e = NULL;
	RSA *rsa = NULL;

	rsa = RSA_new();
	e = BN_new();
	BN_set_word(e, OPENSSLGENEXPONENT);

	while (counter < OPENSSLGENMAX)
	{

		if (RSA_generate_key_ex(rsa, OPENSSLGENBITS, e, NULL) == 0)
			break;

		mpz_set_str(genN, BN_bn2dec(rsa->n), 10);

		mpz_gcd(tmp, myN, genN);

		if (mpz_cmp_ui(tmp, 1) != 0)
		{
			printWin(&tmp, "OpenSSL gen");
			status = WIN;
			break;
		}

		counter += 1;
	}


	BN_free(e);
	RSA_free(rsa);

	mpz_clear(myN);		mpz_clear(genN);

	return status;
}
コード例 #2
0
/* Return the public key exponent given the decrypted certificate as string. */
void
get_cert_exponent(mpz_t result, char *cert)
{
	char *srch, *srch2;
	char exponent[RSA_MAX_LEN/2];
	memset(exponent, 0, RSA_MAX_LEN/2);
	srch = strchr(cert, '\n');
	srch += 1;
	srch = strchr(srch, '\n');
	srch += 1;
	srch = strchr(srch, '\n');
	srch += 1;
	srch = strchr(srch, ':');
	srch += 2;
	srch2 = strchr(srch, '\n');
	strncpy(exponent, srch, srch2-srch);
	mpz_set_str(result, exponent, 0);
}
コード例 #3
0
ファイル: gmp_test.c プロジェクト: PickXu/pantry
int compute(struct In* input, struct Out* output){
  mpz_t a, b, c;
  mpz_init(a);
  mpz_init(b);
  mpz_init(c);
  mpz_set_si(a, input->data[0]);
  //mpz_set_si(b, input->data[1]);
  mpz_set_str(b,
  "2102938470192837410982374019283471029837401298347120984710298347109283471029847102983741029384710293841023874601892364018236409182634098126304816203948612093461029386401928364019286340918263049182630941862039486120394861209348610293846102938461092836401928364019283460192836409132861029837410928374019283741092837410928371092837401298374019823740192837401982374019283740192837401923874102938740192837410928374109283471092387401928374109238741092384710923874102938741092387401298374019283740192837401928374019283741029387410293874102938471209384710923874019283741092837401923874102983740192387410983874019283740923874829581123948653282398625", 10);
  //mpz_add(c, a, b);
  mpz_mul(c, a, b);
  //mpz_sub(c, c, c);
  //mpz_neg(c, c);
  mpz_set(output->b, c);
  mpz_clear(a);
  mpz_clear(b);
  mpz_clear(c);
}
コード例 #4
0
ファイル: solution.c プロジェクト: dougsko/projecteuler.net
gint
main()
{
    //gint i = 11;
    mpz_t i, power, sum;
    gint count = 0;
    gint j;
    GPtrArray *special;
    gchar *foo, *bar, *baz;

    mpz_init_set_ui(i, 11);
    mpz_init(power);
    mpz_init(sum);

    special = g_ptr_array_new();

    while(special->len < 30)
    {

        baz = mpz_get_str(NULL, 10, i);
        foo = add_digits_str(baz);
        mpz_set_str(sum, foo, 10);
        free(foo);
        free(baz);
        for(j = 1; j <= 100; j++)
        {
            mpz_pow_ui(power, sum, j);
            if(mpz_cmp(power, i) > 0)
                break;
            if(mpz_cmp(power, i) == 0)
            {
                bar = mpz_get_str(NULL, 10, i);
                g_ptr_array_add(special, bar);
                g_print("%d: %s\t%d\n", special->len, bar, j);
                free(bar);
            }
        }
        mpz_add_ui(i, i, 1);
    }
    mpz_clear(i);
    printf("%s\n", g_ptr_array_index(special, special->len-1));
    g_ptr_array_free(special, TRUE);
    return 0;
}
コード例 #5
0
ファイル: hec.c プロジェクト: fason/stigmergy
static PyObject *
hec_inc (PyObject *self, PyObject *args)
{
    const char* s_in;
    unsigned long i_inc;
    if (!PyArg_ParseTuple(args, "sk", &s_in, &i_inc))
        return NULL;

    mpz_t v_in, v_out;
    mpz_init (v_in);
    mpz_init (v_out);
    mpz_set_str (v_in, s_in, 10);
    _hec_inc (v_out, v_in, i_inc);
    const char* s_val = mpz_get_str (NULL, 10, v_out);
    mpz_clear (v_in);
    mpz_clear (v_out);
        
    return Py_BuildValue ("s", s_val);
}
コード例 #6
0
ファイル: rsa.cpp プロジェクト: dreamsxin/ultimatepp
void rsa_random_integer(MP_INT *ret, RandomState *state, unsigned int bits)

{

  unsigned int bytes = (bits + 7) / 8;

  char *str = xmalloc(bytes * 2 + 1);

  unsigned int i;



  /* We first create a random hex number of the desired size, and then

     convert it to a mp-int. */

  for (i = 0; i < bytes; i++)

    sprintf(str + 2 * i, "%02x", random_get_byte(state));



  /* Convert it to the internal representation. */

  if (mpz_set_str(ret, str, 16) < 0)

    fatal("Intenal error, mpz_set_str returned error");



  /* Clear extra data. */

  memset(str, 0, 2 * bytes);

  xfree(str);



  /* Reduce it to the desired number of bits. */

  mpz_mod_2exp(ret, ret, bits);

}
コード例 #7
0
ファイル: bbs_pseudo.c プロジェクト: cpsource/dibit
// create an mpz_t from a char array of size array_cnt
static void bbs_pseudo_cvt_bytes_to_mpz ( unsigned char *array, int array_cnt , mpz_t result )
{
  char *v_buf;
  char *c;
  int i;

  c = v_buf = alloca ( array_cnt*2 + 1 );
  v_buf [ array_cnt*2 ] = 0;

  for ( i = array_cnt - 1 ; i >= 0 ; i--, c += 2 ) {
    sprintf(c,"%02x",array[i]&0xff);
  }

#if 0 && defined(CP_TEST)
  printf("%s\n",v_buf);
#endif

  mpz_set_str(result,v_buf,16);
}
コード例 #8
0
ファイル: naif.c プロジェクト: hippunk/Etudes
int first_test(mpz_t n){

	int test = 1;
	int sortie = 0;
	mpz_t nb, max,mod;

       	mpz_init (nb);
       	mpz_init (max);
	mpz_init (mod);

	mpz_root(max, n, 2); //need debug
	//gmp_printf ("\nDebug racine carré : %Zd\n", max);
	//mpz_out_str(stdout, 10, max);

	mpz_set_str(nb,"2",10);
	//gmp_printf ("\nDebug compteur : %Zd\n", nb);

	if(mpz_cmp_si(n,0)== 0 || mpz_cmp_si(n,1)== 0){
		test = 0;
		sortie = 1;
	}

	for(sortie = 0;sortie!=1 && mpz_cmp(nb,max)<=0;mpz_add_ui(nb,nb,1)){

		//printf("test : %i\n", test);
		mpz_mod(mod,n,nb);
		//gmp_printf("Debug tour num %Zd : n = %Zd, nb = %Zd, n mod nb = %Zd\n",nb,n,nb,mod);

		if(mpz_cmp_si(mod,0)== 0){
			//printf("Debug : Sortie\n");
			test = 0;
			sortie = 1;
		}
	}


	mpz_clear(nb);
	mpz_clear(max);
	mpz_clear(mod);
	//printf("test : %i\n", test);
	return test;

}
コード例 #9
0
ファイル: client.c プロジェクト: bchanthyra/TSL
/*
 * \brief                Encrypts/decrypts a message using the RSA algorithm.
 *
 * \param result         a field to populate with the result of your RSA calculation.
 * \param message        the message to perform RSA on. (probably a cert in this case)
 * \param e              the encryption key from the key_file passed in through the
 *                       command-line arguments
 * \param n              the modulus for RSA from the modulus_file passed in through
 *                       the command-line arguments
 *
 * Fill in this function with your proj0 solution or see staff solutions.
 */
static void
perform_rsa(mpz_t result, mpz_t message, mpz_t e, mpz_t n)
{
  int odd_num;

  mpz_set_str(result, "1", 10);
  odd_num = mpz_odd_p(e);
  while (mpz_cmp_ui(e, 0) > 0) {
    if (odd_num) {
      mpz_mul(result, result, message);
      mpz_mod(result, result, n);
      mpz_sub_ui(e, e, 1);
    }
    mpz_mul(message, message, message);
    mpz_mod(message, message, n);
    mpz_div_ui(e, e, 2);
    odd_num = mpz_odd_p(e);
  }
}
コード例 #10
0
int main (int argc, char const *argv[])
{
    mpz_t n;
    mpz_init( n );

#if 0
    /* set up 7th Fermat number */
    mpz_ui_pow_ui( n, 2, 128 );
    mpz_add_ui( n, n, 1);
#else
    /*mpz_set_ui( n, 3248523672894567297 );*/
    mpz_set_str( n, "3248523672894567297", 10 );
#endif

    /* try to factor it */
    fast_fermat_alg( n );

    return 0;
}
コード例 #11
0
ファイル: crypt.c プロジェクト: MFreeze/m2moca
/* 
 * ===  FUNCTION  ======================================================================
 *         Name:  convertToCryptInt
 *  Description:  
 * =====================================================================================
 */
mpz_t *convertToCryptInt(char *str, int str_size, int *ret_size) {
    mpz_t *result;

    int count = 0, i = 0, j = 0;
    char *tmp = 0;

    while (str[i] != '\0') {
        if (str[i] == ' ')
            count ++;
        i++;
    }

    if (str[strlen(str) - 1] != ' ')
        count ++;

    result = (mpz_t *) malloc (sizeof(mpz_t) * count);

    i = 0;

    while (str[i] != '\0') {
        int nsize = 32, csize = 1;
        tmp = (char *) malloc (sizeof(char) * nsize);
        while(str[i] != ' ' && str[i] != '\0') {
            if (csize == nsize) {
                nsize = nsize << 2;
                tmp = (char *) realloc (tmp, nsize * sizeof(char));
            }
            tmp[csize - 1] = str[i];
            csize ++; i ++;
        }
        tmp[csize - 1] = '\0';
        i ++; 
        mpz_init(result[j]);
        mpz_set_str(result[j], tmp, 10);
        j++;

        free(tmp);
    }

    *ret_size = j;
    return result;
} /* -----  end of function convertToCryptInt  ----- */
コード例 #12
0
ファイル: GmpIO.cpp プロジェクト: swarbhanu/CGAL-Mesh
istream &
//operator>> (istream &i, mpz_ptr z)
io_read (istream &i, mpz_ptr z)
{
  int base;
  char c = 0;
  string s;
  bool ok = false, zero, showbase;

  i.get(c); // start reading

  if (i.flags() & ios::skipws) // skip initial whitespace
    while (isspace(c) && i.get(c))
      ;

  if (c == '-' || c == '+') // sign
    {
      if (c == '-') // mpz_set_str doesn't accept '+'
	s = "-";
      i.get(c);
    }

  while (isspace(c) && i.get(c)) // skip whitespace
    ;

  base = __gmp_istream_set_base(i, c, zero, showbase); // select the base
  __gmp_istream_set_digits(s, i, c, ok, base);         // read the number

  if (i.good()) // last character read was non-numeric
    i.putback(c);
  else if (i.eof() && (ok || zero)) // stopped just before eof
    i.clear();

  if (ok)
    mpz_set_str(z, s.c_str(), base); // extract the number
  else if (zero)
    mpz_set_ui(z, 0);
  else
    i.setstate(ios::failbit); // read failed

  return i;
}
コード例 #13
0
ファイル: djcs.c プロジェクト: tiehuis/libhcs
int djcs_import_public_key(djcs_public_key *pk, const char *json)
{
    JSON_Value *root = json_parse_string(json);
    JSON_Object *obj = json_value_get_object(root);
    pk->s = json_object_get_number(obj, "s");
    pk->n = malloc(sizeof(mpz_t) * (pk->s + 1));

    mpz_init(pk->n[0]);
    mpz_set_str(pk->n[0], json_object_get_string(obj, "n"), HCS_INTERNAL_BASE);
    json_value_free(root);

    /* Calculate remaining values */
    mpz_add_ui(pk->g, pk->n[0], 1);
    for (unsigned long i = 1; i <= pk->s; ++i) {
        mpz_init_set(pk->n[i], pk->n[i-1]);
        mpz_mul(pk->n[i], pk->n[i], pk->n[0]);
    }

    return 0;
}
コード例 #14
0
ファイル: gmp_mpi.c プロジェクト: jsbronder/p_aks
int mpi_mpz_recv(mpz_t z, int src, int tag, MPI_Comm comm, MPI_Status *status) {
    int buf_size;
    int rc = 0;
    void *buf;

    MPI_Recv(&buf_size, 1, MPI_INT, src, tag, comm, status);

    buf = (void *)malloc(sizeof(unsigned char) * buf_size);
    MPI_Recv(buf, buf_size, MPI_BYTE, src, tag, comm, status);

    rc = mpz_set_str(z, buf, 10);
    if (rc) {
        fprintf(stderr, "mpi_mpz_bcast:  mpz_set_str(%s) failed.\n",
            (char*)buf);
        return 0;
    }
 
    recv_cnt++;
    return 1;
}
コード例 #15
0
ファイル: idris_gmp.c プロジェクト: adamsmd/Idris-dev
VAL MKBIGC(VM* vm, char* val) {
    if (*val == '\0') {
        return MKBIGI(0);
    }
    else {
        idris_requireAlloc(IDRIS_MAXGMP);
        mpz_t* bigint;
        
        VAL cl = allocate(sizeof(Closure) + sizeof(mpz_t), 0);
        idris_doneAlloc();
        bigint = (mpz_t*)(((char*)cl) + sizeof(Closure));
        
        mpz_init(*bigint);
        mpz_set_str(*bigint, val, 10);

        SETTY(cl, CT_BIGINT);
        cl -> info.ptr = (void*)bigint;

        return cl;
    }
}
コード例 #16
0
ファイル: rsa.cpp プロジェクト: pbanaszkiewicz/Khrypto
/* void RSA_decrypt(string, list<string>, RSA_PRIVATE)
 * decrypts every single item from the list and appends the result to the message
 */
void RSA_decrypt(string &message, list<string> &cipher, RSA_PRIVATE &priv) {
    message.clear();

    list<string>::iterator iter1 = cipher.begin();

    string c_str;

    mpz_t c;
    mpz_init(c);

    // do while there are some items in the list
    while ( iter1 != cipher.end() ) {
        c_str = *iter1;
        mpz_set_str(c, c_str.c_str(), 16); // reading the encrypted chunk
        RSA_decrypt_chunk(c_str, c, priv); // decrypting the chunk
        message.append(c_str); // appending the chunk to the message
        iter1++;
    }

    mpz_clear(c); // tidying
}
コード例 #17
0
ファイル: reesa.c プロジェクト: hylje/tira-reesa
int encrypt(struct reesa_privkey* priv,
	     const char* plaintext,
	     char* ciphertext,
	     int buflen) {
  /*
     Encrypts the given plaintext (of length buflen) and writes it to
     ciphertext (length buflen)

     We expect the plaintext to be a base16 number. We'll also write a
     base16 number into ciphertext.

     Buflen should be enough to contain the key modulus encoded in
     base16. With 128 bit q and p that should be at least 129/4 => 33
   */

  mpz_t plainnum;
  mpz_init2(plainnum, buflen*8);
  mpz_set_str(plainnum, plaintext, 16);

  if(mpz_cmp(plainnum, priv->modulus) > 0) {
    mpz_clear(plainnum);
    return 1;
  }

  mpz_t ciphernum;
  mpz_init2(ciphernum, buflen*8);

  exp_modulo(ciphernum, plainnum, priv->public_exponent, priv->modulus);

  if(mpz_cmp(ciphernum, priv->modulus) > 0) {
    return 2;
  }

  mpz_get_str(ciphertext, 16, ciphernum);

  mpz_clear(plainnum);
  mpz_clear(ciphernum);

  return 0;
}
コード例 #18
0
ファイル: algorithms.cpp プロジェクト: max1234/ELGAMAL
void Algorithms::GeneratePrime(mpz_t number, unsigned int numBits, unsigned int randomaiser)
{
    unsigned int i;
    bool isComposite;
    char *prime_str = new char[numBits + 1];

    mpz_t buf;
    mpz_init(buf);

    srand(randomaiser);
    prime_str[0] = '1';

    while(true)
    {

        for(i = 1; i < numBits - 1; i++)
            prime_str[i] = (int)(2.0 * rand() / (RAND_MAX + 1.0)) + '0';
        prime_str[numBits - 1] = '1';
        prime_str[numBits] = '\0';
        mpz_set_str(number,prime_str,2);
        for(isComposite = false, i = 0; i <= maxPrimeIndex; i++)
        {
            if(mpz_cmp_ui(number,shortPrimes[i]) <= 0)//////////////////
                break;
            mpz_mod_ui(buf, number, shortPrimes[i]);/////////////////////
            if(mpz_cmp_ui(buf,(unsigned long int)0) == 0)////////////////////
            {
                isComposite = true;
                break;
            }
        }
        if(isComposite)
            continue;
            if(MillerRabin(number, numBits, 10))
                break;
    }

    mpz_clear(buf);
    free(prime_str);
}
コード例 #19
0
ファイル: main.c プロジェクト: cvpcs/project_euler
int main(int argc, char* argv[]) {
	mpz_t n;
	mpz_t m;
	char* str;

	mpz_init(n);
	mpz_init(m);
	mpz_set_ui(n, 0);

	while(1) {
		str = (char*)malloc(256 * sizeof(char));
		gets_s(str, 255);
		printf("Found number: \"%s\"\n", str);

		if(strlen(str) == 0) {
			break;
		} else {
			mpz_set_str(m, str, 10);
			mpz_add(n, n, m);
		}

		free(str);
	}

	str = mpz_get_str(NULL, 10, n);

	printf("Sum of digits: %s\n", str);

	if (strlen(str) > 10)
		str[10] = '\0';

	printf("First 10 digits: %s\n", str);

	free(str);

	mpz_clear(n);
	mpz_clear(m);

	return 0;
}
コード例 #20
0
ファイル: main.c プロジェクト: cvpcs/project_euler
int main(int argc, char* argv[]) {
	mpz_t n;
	mpz_t m;
	char* str;
	char* buf;

	mpz_init(n);
	mpz_init(m);
	mpz_ui_pow_ui(n, 2, 1000);

	str = mpz_get_str(NULL, 10, n);

	printf("Number we are adding the digits of: %s\n", str);

	mpz_set_ui(n, 0);

	buf = (char*)malloc(2 * sizeof(char));

	for(unsigned int i = 0; i < strlen(str); ++i) {
		buf[0] = str[i];
		buf[1] = '\0';
		mpz_set_str(m, buf, 10);
		mpz_add(n, n, m);
	}

	free(buf);
	free(str);

	str = mpz_get_str(NULL, 10, n);	

	printf("Sum of digits: %s\n", str);

	free(str);

	mpz_clear(n);
	mpz_clear(m);

	return 0;
}
コード例 #21
0
ファイル: 13.c プロジェクト: lijiansysu/project_euler
int main()
{
    FILE *fp = fopen("13_number", "r");
    char s[60];
    mpz_t number, result;
    mpz_init(number);
    mpz_init(result);

    int i;
    for (i = 0; i < 100; i++) {
	fgets(s, 60, fp);
	mpz_set_str(number, s, 10);
	mpz_add(result, result, number);
    }

    fclose(fp);
    mpz_out_str(stdout, 10, result);
    putchar('\n');
    mpz_clear(number);
    mpz_clear(result);
    return 0;
}
コード例 #22
0
ファイル: client.c プロジェクト: michellelinggg/tlsProject
/* Return the public key exponent given the decrypted certificate as string. */
int
get_cert_exponent(mpz_t result, char *cert)
{
  int err;
  char *srch, *srch2;
  char exponent[RSA_MAX_LEN/2];
  memset(exponent, 0, RSA_MAX_LEN/2);
  srch = strchr(cert, '\n');
  if (srch == NULL) {
    return ERR_FAILURE;
  }
  srch += 1;
  srch = strchr(srch, '\n');
  if (srch == NULL) {
    return ERR_FAILURE;
  }
  srch += 1;
  srch = strchr(srch, '\n');
  if (srch == NULL) {
    return ERR_FAILURE;
  }
  srch += 1;
  srch = strchr(srch, ':');
  if (srch == NULL) {
    return ERR_FAILURE;
  }
  srch += 2;
  srch2 = strchr(srch, '\n');
  if (srch2 == NULL) {
    return ERR_FAILURE;
  }
  strncpy(exponent, srch, srch2-srch);
  err = mpz_set_str(result, exponent, 0);
  if (err == -1) {
    return ERR_FAILURE;
  }
  return ERR_OK;
}
コード例 #23
0
ファイル: e_gmp.c プロジェクト: 375670450/openssl
/*
 * Most often limb sizes will be the same. If not, we use hex conversion
 * which is neat, but extremely inefficient.
 */
static int bn2gmp(const BIGNUM *bn, mpz_t g)
{
    bn_check_top(bn);
    if (((sizeof(bn->d[0]) * 8) == GMP_NUMB_BITS) &&
        (BN_BITS2 == GMP_NUMB_BITS)) {
        /* The common case */
        if (!_mpz_realloc(g, bn->top))
            return 0;
        memcpy(&g->_mp_d[0], &bn->d[0], bn->top * sizeof(bn->d[0]));
        g->_mp_size = bn->top;
        if (bn->neg)
            g->_mp_size = -g->_mp_size;
        return 1;
    } else {
        int toret;
        char *tmpchar = BN_bn2hex(bn);
        if (!tmpchar)
            return 0;
        toret = (mpz_set_str(g, tmpchar, 16) == 0 ? 1 : 0);
        OPENSSL_free(tmpchar);
        return toret;
    }
}
コード例 #24
0
ファイル: reesa.c プロジェクト: hylje/tira-reesa
struct reesa_privkey* readpriv(
	     char* p,
	     char* q,
	     char* public_exponent,
	     char* private_exponent,
	     char* modulus,
	     char* totient_modulus) {
  /* Read the given integers (as strings) into the internal GMP data
     structure.

     The caller is responsible for deallocating the strings we are
     given.

     If any of the given strings are invalid (not base 10 integers),
     returns NULL deallocating the struct.
  */

  struct reesa_privkey* priv = malloc(sizeof(struct reesa_privkey));
  _Bool fail = false;

  mpz_init(priv->p);
  fail |= mpz_set_str(priv->p, p, 10) == -1;

  mpz_init(priv->q);
  fail |= mpz_set_str(priv->q, q, 10) == -1;

  mpz_init(priv->public_exponent);
  fail |= mpz_set_str(priv->public_exponent, public_exponent, 10) == -1;

  mpz_init(priv->private_exponent);
  fail |= mpz_set_str(priv->private_exponent, private_exponent, 10) == -1;

  mpz_init(priv->modulus);
  fail |= mpz_set_str(priv->modulus, modulus, 10) == -1;

  mpz_init(priv->totient_modulus);
  fail |= mpz_set_str(priv->totient_modulus, totient_modulus, 10) == -1;

  if (fail) {
    free(priv);
    return NULL;
  }

  return priv;
}
コード例 #25
0
ファイル: reesa.c プロジェクト: hylje/tira-reesa
int decrypt(struct reesa_privkey* priv,
	     const char* ciphertext,
	     char* plaintext,
	     int buflen) {
  /*
     Decrypts the given ciphertext (of length buflen) and writes it to
     plaintext (length buflen)

     We expect the plaintext to be a base16 number. We'll also write a
     base16 number into ciphertext.
  */

  mpz_t ciphernum;
  mpz_init2(ciphernum, buflen*8);
  mpz_set_str(ciphernum, ciphertext, 16);

  if(mpz_cmp(ciphernum, priv->modulus) > 0) {
    mpz_clear(ciphernum);
    return 1;
  }

  mpz_t plainnum;
  mpz_init2(plainnum, buflen*8);

  exp_modulo(plainnum, ciphernum, priv->private_exponent, priv->modulus);

  if(mpz_cmp(plainnum, priv->modulus) > 0) {
    return 2;
  }

  mpz_get_str(plaintext, 16, plainnum);

  mpz_clear(ciphernum);
  mpz_clear(plainnum);

  return 0;
}
コード例 #26
0
ファイル: t-perfpow.c プロジェクト: AllardJ/Tomato
void
check_tests ()
{
  mpz_t x;
  int i;
  int got, want;

  mpz_init (x);

  for (i = 0; tests[i].num_as_str != NULL; i++)
    {
      mpz_set_str (x, tests[i].num_as_str, 0);
      got = mpz_perfect_power_p (x);
      want = tests[i].want;
      if (got != want)
	{
	  fprintf (stderr, "mpz_perfect_power_p returns %d when %d was expected\n", got, want);
	  fprintf (stderr, "fault operand: %s\n", tests[i].num_as_str);
	  abort ();
	}
    }

  mpz_clear (x);
}
コード例 #27
0
static int
my_main (int argc, char **argv)
{
  setlocale (LC_ALL, "");

  int rows = atoi (argv[1]);
  int cols = atoi (argv[2]);
  int i1 = atoi (argv[3]);
  int i2 = atoi (argv[4]);

  mpz_t A[rows][cols];

  mpz_matrix_init (rows, cols, A);

  unsigned int i_argv = 5;

  for (unsigned int i = 0; i < rows; i++)
    for (unsigned int j = 0; j < cols; j++)
      {
        mpz_set_str (A[i][j], argv[i_argv], 0);
        i_argv++;
      }

  mpz_matrix_swap_rows (rows, cols, A, i1, i2);

  for (unsigned int i = 0; i < rows; i++)
    {
      for (unsigned int j = 0; j < cols; j++)
        gmp_printf (" %Zd", A[i][j]);
      printf (" |");
    }

  mpz_matrix_clear (rows, cols, A);

  return 0;
}
コード例 #28
0
ファイル: main.c プロジェクト: kevinmel2000/Simple-ECC
int main() {
	/** Fm, where modulo = m */
	mpz_t a, b, k, r, modulo;
	int i = 0; // loop variable
	Point p, next_p;
	p = init_point(p);
	mpz_init(a);
	mpz_init(b);
	mpz_init(k);
	mpz_init(r); // order
	mpz_init(modulo);

	/** Initialize parameters of ECC (F2p) */
	mpz_set_str(a, a_v, 10);
	mpz_set_str(b, b_v, 16);
	mpz_set_str(modulo, p_v, 10);
	mpz_set_str(r, r_v, 10);
	mpz_set_str(p.x, gx_v, 16);
	mpz_set_str(p.y, gy_v, 16);

	mpz_t zero_value, k2;
	mpz_init(zero_value);
	mpz_init(k2);

	RDTSC_START(t1);
	sleep(1); // sleep for 1 second
	RDTSC_STOP(t2);
	uint64_t one_second = t2 - t1 - rdtscp_cycle;
	printf("Approximate number of cycles in 1 second: %lld\n\n", one_second);
	uint64_t one_us = one_second / 1e6;

	while (mpz_cmp(k, zero_value) == 0) {
		get_random(k, 32); // generate random test (256 bits)
		positive_modulo(k, k, modulo);
	}
	printf("Random k (in Binary): ");
	mpz_out_str(stdout, 2, k);
	printf("\n");

	while (mpz_cmp(k2, zero_value) == 0) {
		get_random(k2, 32); // generate random test (256 bits)
		positive_modulo(k2, k2, modulo);
	}
	printf("Random k2 (in Binary): ");
	mpz_out_str(stdout, 2, k2);
	printf("\n");

	/** Compare ADDITION, SHIFTING, MULTIPLICATION, and INVERSION */
	if (TEST_MODULAR_OPERATION) {
		max_iteration = 10000;

		/** Addition */
		i = 0;
		uint64_t total = 0;
		while (i < max_iteration) {
			RDTSC_START(t1); // start operation
			mpz_add(k, k, k2);
			positive_modulo(k, k, modulo);
			RDTSC_STOP(t2); // stop operation
			total += t2 - t1 - rdtscp_cycle;
			i++;
		}
		printf("--[ADDITION]--\n");
		print_result(total, one_us);
		

		/** Shifting */
		i = 0;
		uint64_t total2 = 0;
		mpz_t two;
		mpz_init(two);
		mpz_set_si(two, 2);
		while (i < max_iteration) {
			RDTSC_START(t1); // start operation
			mpz_mul_2exp(k, k, 1); // left shift
			positive_modulo(k, k, modulo);
			RDTSC_STOP(t2); // stop operation
			total2 += t2 - t1 - rdtscp_cycle;
			i++;
		}
		printf("--[SHIFTING 2 * k]--\n");
		print_result(total2, one_us);

		/** Multiplication */
		i = 0;
		uint64_t total3 = 0;
		while (i < max_iteration) {
			RDTSC_START(t1); // start operation
			mpz_mul(k, k, k2);
			positive_modulo(k, k, modulo);
			RDTSC_STOP(t2); // stop operation
			total3 += t2 - t1 - rdtscp_cycle;
			i++;
		}
		printf("--[MULTIPLICATION k * k2]--\n");
		print_result(total3, one_us);

		/** Inversion */
		i = 0;
		uint64_t total4 = 0;
		while (i < max_iteration) {
			RDTSC_START(t1); // start operation
			mpz_invert(k, k, modulo);
			RDTSC_STOP(t2); // stop operation
			total4 += t2 - t1 - rdtscp_cycle;
			i++;
		}
		printf("--[INVERSION]--\n");
		print_result(total4, one_us);
	}

	/** -------------------------------------------------------------------------*/
	// Convert Affine coordinate to Jacobian coordinate
	J_Point j_p, j_next_p;
	j_next_p = init_j_point(j_next_p);
	j_p = affine_to_jacobian(p); // Generator point

	if (TEST_SCALAR_OPERATION) {
		max_iteration = 100;
		Point p1, p2, p3;
		J_Point j_p1, j_p2, j_p3;

		/** Point preparation */
		p1 = init_point(p1); p2 = init_point(p2);
		j_p1 = init_j_point(j_p1); j_p2 = init_j_point(j_p2);
		j_p1 = jacobian_affine_sliding_NAF(j_p, p, a, k, modulo, 4);
		j_p2 = jacobian_affine_sliding_NAF(j_p, p, a, k2, modulo, 4);
		p1 = jacobian_to_affine(j_p1, modulo);
		p2 = jacobian_to_affine(j_p2, modulo);

		/** Affine addition */
		i = 0;
		uint64_t total = 0;
		while (i < max_iteration) {
			RDTSC_START(t1); // start operation
			p3 = affine_curve_addition(p1, p2, a, modulo);
			RDTSC_STOP(t2); // stop operation
			total += t2 - t1 - rdtscp_cycle;
			i++;
		}
		printf("--[ADDITION in AFFINE]--\n");
		print_result(total, one_us);

		/** Affine doubling */
		i = 0;
		uint64_t total2 = 0;
		while (i < max_iteration) {
			RDTSC_START(t1); // start operation
			p3 = affine_curve_doubling(p1, a, modulo);
			RDTSC_STOP(t2); // stop operation
			total2 += t2 - t1 - rdtscp_cycle;
			i++;
		}
		printf("--[DOUBLING in AFFINE]--\n");
		print_result(total2, one_us);

		/** Jacobian addition */
		i = 0;
		uint64_t total3 = 0;
		while (i < max_iteration) {
			RDTSC_START(t1); // start operation
			j_p3 = jacobian_curve_addition(j_p1, j_p2, a, modulo);
			RDTSC_STOP(t2); // stop operation
			total3 += t2 - t1 - rdtscp_cycle;
			i++;
		}
		printf("--[ADDITION in JACOBIAN]--\n");
		print_result(total3, one_us);

		/** Jacobian doubling */
		i = 0;
		uint64_t total4 = 0;
		while (i < max_iteration) {
			RDTSC_START(t1); // start operation
			j_p3 = jacobian_curve_doubling(j_p1, a, modulo);
			RDTSC_STOP(t2); // stop operation
			total4 += t2 - t1 - rdtscp_cycle;
			i++;
		}
		printf("--[DOUBLING in JACOBIAN]--\n");
		print_result(total4, one_us);

		/** Affine-Jacobian addition */
		i = 0;
		uint64_t total5 = 0;
		while (i < max_iteration) {
			RDTSC_START(t1); // start operation
			j_p3 = jacobian_affine_curve_addition(j_p1, p2, a, modulo);
			RDTSC_STOP(t2); // stop operation
			total5 += t2 - t1 - rdtscp_cycle;
			i++;
		}
		printf("--[ADDITION in JACOBIAN-AFFINE]--\n");
		print_result(total5, one_us);
	}

	/** -------------------------------------------------------------------------*/
	if (TEST_SCALAR_ALGORITHM) {
		max_iteration = 100;

		/** Test Left-to-right binary algorithm */
		i = 0;
		uint64_t total = 0;
		while (i < max_iteration) {
			RDTSC_START(t1); // start operation
			next_p = affine_left_to_right_binary(p, a, k, modulo); // Q = [k]P
			// gmp_printf("%Zd %Zd\n", next_p.x, next_p.y);
			RDTSC_STOP(t2); // stop operation
			total += t2 - t1 - rdtscp_cycle;
			i++;
		}
		printf("--[AFFINE] Left to right binary algorithm--\n");
		print_result(total, one_us);

		i = 0;
		uint64_t total2 = 0;
		while (i < max_iteration) {
			RDTSC_START(t1); // start operation
			j_next_p = jacobian_left_to_right_binary(j_p, a, k, modulo); // Q = [k]P
			// gmp_printf("%Zd %Zd\n", j_next_p.X, j_next_p.Y);
			next_p = jacobian_to_affine(j_next_p, modulo);
			// gmp_printf("%Zd %Zd\n", next_p.x, next_p.y);
			RDTSC_STOP(t2); // stop operation
			total2 += t2 - t1 - rdtscp_cycle;
			i++;
		}
		printf("--[JACOBIAN] Left to right binary algorithm--\n");
		print_result(total2, one_us);

		i = 0;
		uint64_t total3 = 0;
		while (i < max_iteration) {
			RDTSC_START(t1); // start operation
			j_next_p = jacobian_affine_left_to_right_binary(j_p, p, a, k, modulo); // Q = [k]P
			// gmp_printf("%Zd %Zd\n", j_next_p.X, j_next_p.Y);
			next_p = jacobian_to_affine(j_next_p, modulo);
			// gmp_printf("%Zd %Zd\n", next_p.x, next_p.y);
			RDTSC_STOP(t2); // stop operation
			total3 += t2 - t1 - rdtscp_cycle;
			i++;
		}
		printf("--[JACOBIAN-AFFINE] Left to right binary algorithm--\n");
		print_result(total3, one_us);

		int w = 4; // windows size
		i = 0;
		uint64_t total4 = 0;
		while (i < max_iteration) {
			RDTSC_START(t1); // start operation
			j_next_p = jacobian_affine_sliding_NAF(j_p, p, a, k, modulo, w); // Q = [k]P
			// gmp_printf("%Zd %Zd\n", j_next_p.X, j_next_p.Y);
			next_p = jacobian_to_affine(j_next_p, modulo);
			// gmp_printf("%Zd %Zd\n", next_p.x, next_p.y);
			RDTSC_STOP(t2); // stop operation
			total4 += t2 - t1 - rdtscp_cycle;
			i++;
		}
		printf("--[JACOBIAN-AFFINE] Sliding NAF Left to right binary algorithm (w = 4)--\n");
		print_result(total4, one_us);

		w = 5; // windows size
		i = 0;
		uint64_t total5 = 0;
		while (i < max_iteration) {
			RDTSC_START(t1); // start operation
			j_next_p = jacobian_affine_sliding_NAF(j_p, p, a, k, modulo, w); // Q = [k]P
			// gmp_printf("%Zd %Zd\n", j_next_p.X, j_next_p.Y);
			next_p = jacobian_to_affine(j_next_p, modulo);
			// gmp_printf("%Zd %Zd\n", next_p.x, next_p.y);
			RDTSC_STOP(t2); // stop operation
			total5 += t2 - t1 - rdtscp_cycle;
			i++;
		}
		printf("--[JACOBIAN-AFFINE] Sliding NAF Left to right binary algorithm (w = 5)--\n");
		print_result(total5, one_us);

		/** Test Right-to-left binary algorithm */
		i = 0;
		uint64_t total6 = 0;
		while (i < max_iteration) {
			RDTSC_START(t1); // start operation
			next_p = affine_right_to_left_binary(p, a, k, modulo); // Q = [k]P
			// gmp_printf("%Zd %Zd\n", next_p.x, next_p.y);
			RDTSC_STOP(t2); // stop operation
			total6 += t2 - t1 - rdtscp_cycle;
			i++;
		}
		printf("--[AFFINE] Right to left binary algorithm--\n");
		print_result(total6, one_us);

		/** Test Montgomery ladder algorithm (Against time-based attack) */
		i = 0;
		uint64_t total7 = 0;
		while (i < max_iteration) {
			RDTSC_START(t1); // start operation
			j_next_p = jacobian_montgomery_ladder(j_p, a, k, modulo); // Q = [k]P
			// gmp_printf("%Zd %Zd\n", j_next_p.X, j_next_p.Y);
			next_p = jacobian_to_affine(j_next_p, modulo);
			// gmp_printf("%Zd %Zd\n", next_p.x, next_p.y);
			RDTSC_STOP(t2); // stop operation
			total7 += t2 - t1 - rdtscp_cycle;
			i++;
		}
		printf("--[JACOBIAN] Montgomery ladder algorithm--\n");
		print_result(total7, one_us);
	}

	/** -------------------------------------------------------------------------*/
	J_Point public_key_1, public_key_2, shared_key;
	mpz_t private_key_1, private_key_2;
	mpz_init(private_key_1); mpz_init(private_key_2);
	// TODO : Key should be padded to fixed size (serializable)
	// Note: (2^-256 chance of failure, can be ignored)
	while (mpz_cmp(private_key_1, zero_value) == 0) {
		get_random(private_key_1, 32); // 256 bit
		positive_modulo(private_key_1, private_key_1, modulo);
	}
	while (mpz_cmp(private_key_2, zero_value) == 0) {
		get_random(private_key_2, 32); // 256 bit
		positive_modulo(private_key_2, private_key_2, modulo);
	}

	gmp_printf("Private key [A B]: %Zd %Zd\n\n", private_key_1, private_key_2);
	public_key_1 = jacobian_left_to_right_binary(j_p, a, private_key_1, modulo);
	public_key_2 = jacobian_left_to_right_binary(j_p, a, private_key_2, modulo);

	gmp_printf("Public key 1 - Jacobian [X Y Z]: %Zd %Zd %Zd\n", public_key_1.X, public_key_1.Y, public_key_1.Z);
	gmp_printf("Public key 2 - Jacobian [X Y Z]: %Zd %Zd %Zd\n", public_key_2.X, public_key_2.Y, public_key_2.Z);

	Point public_key_1_decoded = jacobian_to_affine(public_key_1, modulo);
	Point public_key_2_decoded = jacobian_to_affine(public_key_2, modulo);

	gmp_printf("Public key 1 - Affine [X Y]: %Zd %Zd\n", public_key_1_decoded.x, public_key_1_decoded.y);
	gmp_printf("Public key 2 - Affine [X Y]: %Zd %Zd\n\n", public_key_2_decoded.x, public_key_2_decoded.y);

	/** -------------------------------------------------------------------------*/
	if (TEST_ENCRYPT_DECRYPT) {
		// ElGamal Encrypt - Decrypt (Map message to chunk of points in EC)
		J_Point message, chosen_point, encoded_point, decoded_point;
		mpz_t k_message;
		mpz_init(k_message);
		mpz_set_ui(k_message, 123456789);
		message = jacobian_left_to_right_binary(j_p, a, k_message, modulo);

		Point message_decoded = jacobian_to_affine(message, modulo);
		gmp_printf("[Encrypt] Message - Affine [X Y] %Zd %Zd\n", message_decoded.x, message_decoded.y);
		gmp_printf("[Encrypt] Message - Jacobian [X Y Z]: %Zd %Zd %Zd\n", message.X, message.Y, message.Z);
		while (mpz_cmp(k_message, zero_value) == 0) {
			get_random(k_message, 32);
			positive_modulo(k_message, k_message, modulo);
		}
		// Encrypt example
		chosen_point = jacobian_left_to_right_binary(j_p, a, k_message, modulo); // chosen point (r)
		gmp_printf("[Encrypt] Chosen point - Jacobian [X Y Z]: %Zd %Zd %Zd\n", chosen_point.X, chosen_point.Y, chosen_point.Z);
		encoded_point = jacobian_left_to_right_binary(public_key_2, a, k_message, modulo); // r * Pu2
		encoded_point = jacobian_curve_addition(message, encoded_point, a, modulo);
		// TODO : chosen_point & encoded_point should be padded to P-bit
		gmp_printf("[Decrypt] Encoded point - Jacobian [X Y Z]: %Zd %Zd %Zd\n", encoded_point.X, encoded_point.Y, encoded_point.Z);
	
		// Decrypt example (encoded_point - private_key * chosen_point)
		decoded_point = jacobian_left_to_right_binary(chosen_point, a, private_key_2, modulo);
		decoded_point = jacobian_curve_subtraction(encoded_point, decoded_point, a, modulo);
		gmp_printf("[Decrypt] Original message - Jacobian [X Y Z]: %Zd %Zd %Zd\n", decoded_point.X, decoded_point.Y, decoded_point.Z);
		message_decoded = jacobian_to_affine(decoded_point, modulo);
		gmp_printf("[Decrypt] Original message - Affine [X Y] %Zd %Zd\n\n", message_decoded.x, message_decoded.y);
	}
	/** -------------------------------------------------------------------------*/
	if (TEST_SIMPLIFIED_ECIES) {
		// Simplified ECIES (Ref: Page 256 Cryptography Theory & Practice 2nd Ed. - Douglas)
		char* message_string = "hello"; // 0..9, a..z (base 36)
		mpz_t encrypted_message;
		mpz_init(encrypted_message);

		int partition = strlen(message_string) / 24;
		int partition_modulo = strlen(message_string) % 24;
		if (partition_modulo != 0) partition++;

		for (i = 0; i < partition; i++) {
			// 24 characters from message_string + 1 null-terminate
			char* chunked_message_string = (char*) malloc(25 * sizeof(char));
			int size = 24;
			if ((i == partition - 1) && (partition_modulo != 0)) size = partition_modulo;
			strncpy(chunked_message_string, message_string + i*24, size);
			chunked_message_string[size] = '\0'; // null-terminate

			Point c_point = encrypt_ECIES(encrypted_message, chunked_message_string, public_key_2_decoded, p, a, modulo);
			gmp_printf("[SIMPLIFIED ECIES] Encrypted message: %Zd\n", encrypted_message);
			decrypt_ECIES(encrypted_message, c_point, private_key_2, p, a, modulo);
		}
	}
	/**-------------------------------------------------------------------------*/
	// TODO : Public key validation!
	// Shared key (ECDH) - key secure exchange
	shared_key = jacobian_left_to_right_binary(public_key_2, a, private_key_1, modulo);
	gmp_printf("Shared key - Jacobian [X Y Z]: %Zd %Zd %Zd\n", shared_key.X, shared_key.Y, shared_key.Z);
	Point shared_key_decoded = jacobian_to_affine(shared_key, modulo);
	gmp_printf("Shared key - Affine [X Y]: %Zd %Zd\n", shared_key_decoded.x, shared_key_decoded.y);

	// TODO : ECDSA - digital signature algorithm

	/** Cleaning up */
	mpz_clear(a);
	mpz_clear(b);
	mpz_clear(k);
	mpz_clear(r);
	mpz_clear(modulo);
	mpz_clear(private_key_1);
	mpz_clear(private_key_2);

	return EXIT_SUCCESS;
}
コード例 #29
0
ファイル: adwhy.c プロジェクト: summerxyt/fastrie
int main(int argc, char **argv)
{
    mpz_t min, rop, sievesize;
    unsigned long r;
    unsigned long loop_count = 0;
    FILE *fp = stdout;
    bool *sieve[128];
    int *primes, *primes_start, *sieve_loc;
    size_t prime_size, loc_size;

    mpz_init(min);
    mpz_init(rop);
    mpz_init(sievesize);

    mpz_set_str(min, argv[1], 0);
    mpz_set_ui(sievesize, SIEVESIZE);

    r = mpz_fdiv_ui(min, PRIMORAL);
    r = (97 - r + PRIMORAL) % PRIMORAL;

    mpz_add_ui(rop, min, r);

    primes_start =
	(int *) primesieve_generate_primes(0, MAX_SIEVE_PRIME, &prime_size,
					   INT_PRIMES);
    for (primes = primes_start; *primes <= 7; primes++);
    prime_size -= (primes - primes_start);
    //loc_size = 6 * prime_size;
    loc_size = 8 * prime_size;	//padding
    sieve_loc = (int *) malloc(sizeof(int) * loc_size);

    struct timeval start_t;
    struct timeval end_t;
    gettimeofday(&start_t, NULL);
#pragma omp parallel
    {
	mpz_t candidate_plus;
	mpz_init(candidate_plus);
	int tid = omp_get_thread_num();
	sieve[tid] = (bool *) malloc(sizeof(bool) * SIEVESIZE);
	if(sieve[tid]==NULL)
	  printf("%d nil\n", tid);
	memset(sieve[tid], true, SIEVESIZE);
#pragma omp for schedule(static, 16)
	for (int i = 0; i < prime_size; i++) {
	    //printf("%d:%d\n",tid,i);
	    int p = primes[i];
	    int inv = modinv_i(PRIMORAL, p);
	    for (int j = 0; j < 6; j++) {
		mpz_add_ui(candidate_plus, rop, offsets[j]);
		unsigned long cmodp = mpz_fdiv_ui(candidate_plus, p);
		int index = ((p - cmodp) * inv) % p;
		sieve_loc[i * 8 + j] = index;
	    }
	}
	mpz_clear(candidate_plus);
    }
    gettimeofday(&end_t, NULL);
    float duration =
	(end_t.tv_sec - start_t.tv_sec) * 1E6 + (end_t.tv_usec -
						 start_t.tv_usec);
    printf("running time:%f\n", duration);

	    mpz_t tmp[4];
	    mpz_t candidate[4];
	    mpz_init(tmp[0]);
	    mpz_init(tmp[1]);
	    mpz_init(tmp[2]);
	    mpz_init(tmp[3]);
	    mpz_init(candidate[0]);
	    mpz_init(candidate[1]);
	    mpz_init(candidate[2]);
	    mpz_init(candidate[3]);
    while (1) {
	//step 1
	//printf("Sieving\n");

	gettimeofday(&start_t, NULL);
	    for (int i = 0; i < prime_size; i++) {
		    //printf("thread %d:prime%d\n", tid, primes[i]);
		for (int j = 0; j < 6; j++) {
		    //o = sieve_loc[sieve_loc_index];
		    unsigned int o = sieve_loc[8 * i + j];
		    while (o < SIEVESIZE) {
			sieve[0][o] = false;
			o += primes[i];
		    }
		    sieve_loc[8 * i + j] = o - SIEVESIZE;
		}
	    }
/*for(int i=0;i<SIEVESIZE;i++)
  if(sieve[0][i])
    printf("1\n");
  else
    printf("0\n");

for(int i=0;i<prime_size;i++){
  for(int j=0;j<6;j++)
    printf("%d:%d\n",primes[i], sieve_loc[8*i+j]);
}
break;*/
    gettimeofday(&end_t, NULL);
    duration =
	(end_t.tv_sec - start_t.tv_sec) * 1E6 + (end_t.tv_usec -
						 start_t.tv_usec);
    printf("running time1:%f\n", duration);

	gettimeofday(&start_t, NULL);
	#pragma omp parallel
	{
	    int tid = omp_get_thread_num();
	    //int num = omp_get_num_threads();
	    /*#pragma omp for
	    for (int i = 0; i < prime_size; i++) {
		    //printf("thread %d:prime%d\n", tid, primes[i]);
		for (int j = 0; j < 6; j++) {
		    //o = sieve_loc[sieve_loc_index];
		    unsigned int o = sieve_loc[8 * i + j];
		    while (o < SIEVESIZE) {
			sieve[tid][o] = false;
			o += primes[i];
		    }
		    sieve_loc[8 * i + j] = o - SIEVESIZE;
		}
	    }*/
	//#pragma omp barrier
	    #pragma omp for
	    for (int i = 0; i < SIEVESIZE; i++) {
		/*bool flag = true;
		for (int j = 0; j < num; j++) {
		    flag = flag && sieve[j][i];
		    sieve[j][i] = true;
		}*/
		if (sieve[0][i]) {
		    mpz_set_ui(tmp[tid], i);
		    mpz_addmul_ui(tmp[tid], sievesize, loop_count);
		    mpz_set(candidate[tid], rop);
		    mpz_addmul_ui(candidate[tid], tmp[tid], PRIMORAL);
		    if (is_fermat_valid(candidate[tid])) {
			mpz_out_str(fp, 16, candidate[tid]);
			exit(0);
		    }
		}
		//printf("thread %d:i%d\n", tid, i);
		if(!sieve[0][i])
		  sieve[0][i] = true;
	    }
	/*#pragma omp barrier
	    #pragma omp for
	    for (int i = 0; i < prime_size; i++) {
		for (int j = 0; j < 6; j++)
		  sieve[tid][i*8+j]=true;
	    }*/

	}
    gettimeofday(&end_t, NULL);
    duration =
	(end_t.tv_sec - start_t.tv_sec) * 1E6 + (end_t.tv_usec -
						 start_t.tv_usec);
    printf("running time2:%f\n", duration);
	loop_count++;
    }

    return 0;
}
コード例 #30
0
int main(int argc, char **argv) {
  
  FILE  *fpairing, *ftag, *fdata, *fresult, *fplain, *fkey, *fcipher, *fpub;
  pairing_t pairing;
  paillier_pubkey_t *pub;
  paillier_prvkey_t *priv;
  element_t g, h, u, sig1, sig2, sig3, temp_pow, m, g1, g2;
  element_t public_key, tag, tag_prod;
  element_t secret_key;
  paillier_get_rand_t get_rand;
  paillier_ciphertext_t *cipher1, *cipher2;
  paillier_plaintext_t *plain1, *plain2;
 
  mpz_t pub_n, a, b, data2, nsquare;
  

  int count = 0, val=5;
  pairing_init_set_str(pairing, param_str);
  //mpz_init_set_str(data_sum, "0", 10);

  plain1 = (paillier_plaintext_t*) malloc(sizeof(paillier_plaintext_t));
  plain2 = (paillier_plaintext_t*) malloc(sizeof(paillier_plaintext_t));
  cipher1 = (paillier_ciphertext_t*) malloc(sizeof(paillier_ciphertext_t));
  cipher2 = (paillier_ciphertext_t*) malloc(sizeof(paillier_ciphertext_t));

  //pbc_demo_pairing_init(pairing, argc, argv);
  element_init_G1(g1, pairing);
  element_init_G1(g2, pairing);
  element_init_G2(g, pairing);
  element_init_G2(public_key, pairing);
  element_init_G1(u, pairing);
  element_init_G1(temp_pow, pairing);
  element_init_G2(public_key, pairing);
  element_init_G1(h, pairing);
  element_init_G1(m, pairing);
  element_init_G1(sig1, pairing);
  element_init_G1(sig2, pairing);
  element_init_G1(sig3, pairing); 
  element_init_G1(tag, pairing); 
  element_init_G1(tag_prod, pairing);
  element_init_Zr(secret_key, pairing);
//  mpz_init(pub_n);
  char *len;
  mpz_init(a);
  mpz_init(b);
  mpz_init(data2);
  printf("Short signature test\n");
  len = (char *)malloc(2048*sizeof(char));

 if((fpub = fopen("pub.txt", "r")))
    {
       	pub = (paillier_pubkey_t*) malloc(sizeof(paillier_pubkey_t));
	priv = (paillier_prvkey_t*) malloc(sizeof(paillier_prvkey_t));	
	mpz_init(pub->n_squared);
	mpz_init(pub->n);
	fgets(len, 1000, fpub);
   	mpz_init_set_str(pub->p, len, 10);
	fgets(len, 1000, fpub);
   	mpz_init_set_str(pub->q, len, 10);
	fgets(len, 1000, fpub);
   	mpz_init_set_str(pub->n_plusone, len, 10);
	//printf("value of nplusone : \n");
	//mpz_out_str(stdout, 10, pub->n_plusone);
	paillier_keygen(&pub, &priv, get_rand, 0);
        pub->bits = mpz_sizeinbase(pub->n, 2);	
        fclose(fpub);
    }  

  
//setting already known pairing parameters
  if((fpairing = fopen("pairing.txt", "r")))
    {
	fgets(len, 1000, fpairing);
	//printf("\n %s\n", len);
   	element_set_str(g, len, 10);
	//element_printf(" g = %B\n", g);
	fgets(len, 1000, fpairing);
	//printf("\n %s\n", len);
   	element_set_str(u, len, 10);
	//element_printf("\n u= %B\n", u);
	fgets(len, 1000, fpairing);
	element_set_str(secret_key, len, 10);
	//element_printf(" secretkey %B\n",secret_key);
	fgets(len, 1000, fpairing);
	element_set_str(public_key, len, 10);
        //element_printf(" publickey %B\n", public_key);
	fgets(len, 1000, fpairing);
	element_set_str(h, len, 10);
        //element_printf(" \nh = %B\n", h);
	fgets(len, 1000, fpairing);
	mpz_init_set_str(pub_n, len, 10);
	//printf("\n n = ");
	//mpz_out_str(stdout, 10, pub_n);
	fclose(fpairing);
    }
   
  element_set1(tag_prod);
 
   ftag = fopen("./tag/output5.txt", "r");
   fgets(len, 1000, ftag);
   element_set_str(g1, len, 10);
   element_printf("\ng1 = %B\n", g1);
   fclose(ftag);  
 
   ftag = fopen("./tag/output6.txt", "r");
   fgets(len, 1000, ftag);
   element_set_str(g2, len, 10);
   element_printf("\ng2 = %B\n", g2);
   fclose(ftag);

   fplain = fopen("./split/output5.txt", "r");
   fgets(len, 1000, fplain);
//   printf("\nlen %s", len);
   mpz_set_str(a, len, 10);
   //element_printf("\na = %Zd\n", a);
   fclose(fplain);
  fplain = fopen("./split/output6.txt", "r");
   fgets(len, 1000, fplain);
   mpz_set_str(b, len, 10);

  fcipher = fopen("./cipher/copy1/output5.txt", "r");
   fgets(len, 1000, fcipher);
   mpz_init_set_str(cipher1->c, len, 10);
  fclose(fcipher);

   fcipher = fopen("./cipher/copy1/output6.txt", "r");
   fgets(len, 1000, fcipher);
   mpz_init_set_str(cipher2->c, len, 10);
   fclose(fcipher);
  
   paillier_mul(pub, cipher2, cipher2, cipher1);
   plain1 = paillier_dec(plain1, pub, priv, cipher2);
  //tag
    mpz_t an;
    mpz_init(an);
    mpz_init(nsquare);
   // mpz_mul(an, a, pub_n);
    mpz_mul(nsquare, pub_n, pub_n);
    element_pow_mpz(temp_pow,u, plain1->m); 
    element_mul(temp_pow, temp_pow, h);
    element_pow_zn(sig1, temp_pow, secret_key);
    element_printf("\n signature of plain = %B\n", sig1);  

    //mpz_mul(an, b, pub_n);
   // mpz_mul(nsquare, pub_n, pub_n);
    element_pow_mpz(temp_pow,u, b); 
    element_mul(temp_pow, temp_pow, h);
    element_pow_zn(sig2, temp_pow, secret_key);
    element_printf("\n signature of b = %B\n", sig2);  
   
   //element_printf("\nb = %Zd\n", b);
   fclose(fplain);
     mpz_add(a, a, b);
   //  mpz_mod(a, a, pub_n);
  // mpz_mul(a, a, pub_n);
  // mpz_mod(a, a, nsquare);
   count = 2;
   element_pow_mpz(temp_pow,u, a);
   mpz_set_ui(data2, count);
  //  itoa(count, len, 10);+
    //element_printf(" \nh = %B\n", h);
    element_pow_mpz(h, h, data2);
    element_mul(temp_pow, temp_pow, h);
    //element_printf("\n h. u^bN = %B\n", temp_pow);
    element_pow_zn(sig3, temp_pow, secret_key);
    element_printf("\n sig 3 %B\n", sig3); 
    element_mul(g2, g2, g1);
    element_printf("\n Direct Product %B\n", g2); 
    element_mul(sig2, sig1, sig2);
    element_printf("\n Direct Product %B\n", sig2); 
   
 return 0;
}