Beispiel #1
0
static void mympz_from_hash(mpz_t x, mpz_t limit, byte_string_t hash)
//let z = number represented in c
//x = z || 1 || z || 2 || z || 3 ...
//until there are enough bits
//should be rewritten more efficiently?
{
    mpz_t z;
    int countlen;
    mpz_t count;
    int i = 0, j;
    int bits = mpz_sizeinbase(limit, 2);
    int zbits;
    char *c = hash->data;
    int len = hash->len;

    mpz_init(z);
    mpz_init(count);
    mpz_set_ui(count, 1);

    mympz_inp_raw(z, c, len);
    zbits = mpz_sizeinbase(z, 2);

    mpz_set_ui(x, 0);
    do {
	for (j=0; j<zbits; j++) {
	    if (mpz_tstbit(z, j)) {
		mpz_setbit(x, i);
	    }
	    i++;
	}
	bits -= zbits;
	if (bits <= 0) break;

	countlen = mpz_sizeinbase(count, 2);
	for (j=0; j<countlen; j++) {
	    if (mpz_tstbit(count, j)) {
		mpz_setbit(x, i);
	    }
	    i++;
	}
	bits -= countlen;
	mpz_add_ui(count, count, 1);
    } while (bits > 0);
    /*
    printf("hash: ");
    mpz_out_str(NULL, 0, x);
    printf("\n");
    */
    while (mpz_cmp(x, limit) > 0) {
	mpz_clrbit(x, mpz_sizeinbase(x, 2) - 1);
    }

    mpz_clear(z);
    mpz_clear(count);
}
Beispiel #2
0
void alder_gmp_test()
{
    mpz_t integ1, integ2;
    mpz_init2 (integ1, 54);
    mpz_init2 (integ2, 54);
    
    mpz_set_ui(integ1, 1);
    mpz_mul_2exp(integ1, integ1, 65);
    mpz_out_str (stdout, 2, integ1);
    printf("\n");
//    mpz_add_ui(integ1,integ1,1);
    
    mpz_out_str (stdout, 10, integ1); printf("\n");
//    mpz_mul_2exp(integ1, integ1, 2);
//    mpz_out_str (stdout, 2, integ1); printf("\n");
    
    uint64_t x2[2];
    x2[0] = 0; x2[1] = 0;
    uint64_t x = 0;
    size_t countp = 0;
    mpz_export(x2, &countp, -1, 8, 0, 0, integ1);
    printf("x[0]: %llu\n", x2[0]);
    printf("x[1]: %llu\n", x2[1]);
    x = UINT64_MAX;
    printf("x: %llu\n", x);
    
    mpz_set_ui(integ1,0);
    
    
//    mpz_mul_2exp(integ1, integ1, );
//    mpz_import(b, 1, 1, sizeof(a), 0, 0, &a);
    // mpz_export
    mpz_out_str (stdout, 2, integ1); printf("\n");
    
    
    mpz_out_str (stdout, 2, integ2);
    printf("\n");
    mpz_swap(integ1, integ2);
    mpz_mul_2exp(integ2, integ1, 2);
    
    mpz_setbit(integ2,0);
    mpz_setbit(integ2,1);
    mpz_out_str (stdout, 2, integ2);
    printf("\n");
    
    mpz_clear (integ1);
    mpz_clear (integ2);
    
}
Beispiel #3
0
int main(int argc, char **argv) {
    mp_bitcnt_t bit_width = 0;
    int base = kDefaultBase;

    static const struct option long_options[] = {
        { "help", no_argument, NULL, 'h' },
        { "use-random", no_argument, NULL, 'r' },
        { "base", required_argument, NULL, 'b' },
        { "bit-width", required_argument, NULL, 's' },
        { NULL, 0, NULL, 0 }
    };
    for (;;) {
        int opt = getopt_long(argc, argv, "hrb:s:", long_options, NULL);
        if (opt == -1)
            break;

        switch (opt) {
        case 'r':
            gRNGFilename = "/dev/random";
            break;
        case 'b':
            if (simple_strtoi(&base, optarg, 10) < 0 ||
                (base > -2 && base < 2) || base < -36 || base > 62)
                fatal("invalid base: '%s'", optarg);
            break;
        case 's':
            if (simple_strtoul(&bit_width, optarg, 10) < 0 || bit_width == 0)
                fatal("invalid bit width: '%s'", optarg);
            break;
        case 'h':
            print_usage();
            return EXIT_SUCCESS;
        default:
            return EXIT_FAILURE;
        }
    }
    argv += optind;
    argc -= optind;
    if (argc > 2 || (bit_width != 0 && argc > 0))
        fatal("too many arguments");

    mpz_t low, high, result;
    mpz_inits(low, high, result, NULL);
    if (argc == 2) {
        arg_to_mpz(low, argv[0]);
        arg_to_mpz(high, argv[1]);
    } else if (argc == 1) {
        arg_to_mpz(high, argv[0]);
    } else if (bit_width != 0) {
        mpz_setbit(high, bit_width);
    } else {
        mpz_set_ui(high, kDefaultUpperBound);
    }

    get_random_mpz(result, low, high);
    mpz_out_str(stdout, base, result);
    putchar('\n');
    mpz_clears(low, high, result, NULL);
    return EXIT_SUCCESS;
}
Beispiel #4
0
/* SmallestRangeToHoldValue : Returns the number of bits required to represent
   a given value. (-ve result for signed constants)
   NB: For an input value of 0, the output type is unsigned, 0 bits. 
   This allows 0's to be compiled out easily.
 */
SignedBits SmallestRangeToHoldValue (PtrMP_INT value)
{
    Bits unsignedLength = mpz_sizeinbase (value, 2);
    bool isNegative = mpz_sgn (value) < 0;
    SignedBits ret = unsignedLength;

    /* Zero */
    if (mpz_sgn (value) == 0)
        ret = 1;
    else if (isNegative)
    {
        mpz_t negativeLimit;

        /* Make negativeLimit equal to -(1 << (unsignedLength-1))
           is the most negative number that can be represented
           without an extra sign bit */
        mpz_init (negativeLimit);

        /* for unsigned length         XXXXXXXX */
        mpz_setbit (negativeLimit, unsignedLength - 1); /* eg 00000000 10000000 */
        mpz_neg (negativeLimit, negativeLimit); /* eg 11111111 10000000 */

        if (mpz_cmp (value, negativeLimit) < 0)
            ret++;              /* Add sign bit */

        mpz_clear (negativeLimit);

        return -ret;
    }
    return ret;
}
Beispiel #5
0
mpz_class computeRandomPrime(gmp_randclass& randomGenerator, unsigned int security)
{
    mpz_class prime = randomGenerator.get_z_bits(security - 1);
    mpz_setbit(prime.get_mpz_t(), security - 1);
    mpz_nextprime(prime.get_mpz_t(), prime.get_mpz_t());
    return prime;
}
Beispiel #6
0
void	test_big_num(){
	bj_big_int_t a, b, c, d;

	a = 0;
	mpz_setbit(a.get_mpz_t(), 6);
	mpz_setbit(a.get_mpz_t(), 12);
	mpz_setbit(a.get_mpz_t(), 17);
	//mpz_setbit(a.get_mpz_t(), 112);
	bj_out << "a is " << a << "\n";

	ch_string s1 = a.get_str(2);
	bj_out << "s1 is " << s1 << bj_eol;

	//long cm1 = mpz_cmp(nu1.get_mpz_t(), nu2.get_mpz_t());

}
Beispiel #7
0
/* These wrapped because they're in-place whereas MPEXPR_TYPE_BINARY_UI
   expects a separate source and destination.  Actually the parser will
   normally pass w==x anyway.  */
static void
e_mpz_setbit (mpz_ptr w, mpz_srcptr x, unsigned long n)
{
  if (w != x)
    mpz_set (w, x);
  mpz_setbit (w, n);
}
Beispiel #8
0
void
mpi_set_highbit( MPI a, unsigned n )
{
    /* This seems whacky, but what do I know. */
    mpz_fdiv_r_2exp(a, a, n+1);
    mpz_setbit(a, n);
}
Beispiel #9
0
static PyObject *
GMPy_MPZ_bit_set_function(PyObject *self, PyObject *args)
{
    mp_bitcnt_t bit_index;
    MPZ_Object *result = NULL, *tempx = NULL;

    if (PyTuple_GET_SIZE(args) != 2)
        goto err;

    if (!(result = GMPy_MPZ_New(NULL)))
        return NULL;

    if (!(tempx = GMPy_MPZ_From_Integer(PyTuple_GET_ITEM(args, 0), NULL)))
        goto err;

    bit_index = mp_bitcnt_t_From_Integer(PyTuple_GET_ITEM(args, 1));
    if (bit_index == (mp_bitcnt_t)(-1) && PyErr_Occurred())
        goto err_index;

    mpz_set(result->z, tempx->z);
    mpz_setbit(result->z, bit_index);

    Py_DECREF((PyObject*)tempx);
    return (PyObject*)result;

  err:
    TYPE_ERROR("bit_set() requires 'mpz','int' arguments");
  err_index:
    Py_XDECREF((PyObject*)result);
    Py_XDECREF((PyObject*)tempx);
    return NULL;
}
Beispiel #10
0
void
fips186_gen::gen_q (bigint *q)
{
  bigint u1, u2;
  char digest[HASHSIZE];
  do {
    sha1_hash (digest, seed, seedsize << 3); // seedsize * 8
    mpz_set_rawmag_le (&u1, digest, HASHSIZE);
    seed[3]++;
    sha1_hash (digest, seed, seedsize << 3); // seedsize * 8
    mpz_set_rawmag_le (&u2, digest, HASHSIZE);
    mpz_xor (q, &u1, &u2);
    mpz_setbit (q, (HASHSIZE << 3) - 1);     // set high bit
    mpz_setbit (q, 0);                       // set low bit
  } while (!q->probab_prime (5));
}
Beispiel #11
0
void mpz_fixed_one(mpz_t x, int prec)
{
    //mpz_set_ui(x, 1);
    //mpz_mul_2exp(x, x, prec);
    mpz_set_ui(x, 0);
    mpz_setbit(x, prec);
}
Beispiel #12
0
static struct error_record *ct_label_type_parse(const struct expr *sym,
						struct expr **res)
{
	const struct symbolic_constant *s;
	const struct datatype *dtype;
	uint8_t data[CT_LABEL_BIT_SIZE];
	mpz_t value;

	for (s = ct_label_tbl->symbols; s->identifier != NULL; s++) {
		if (!strcmp(sym->identifier, s->identifier))
			break;
	}

	dtype = sym->dtype;
	if (s->identifier == NULL)
		return error(&sym->location, "Could not parse %s", dtype->desc);

	if (s->value >= CT_LABEL_BIT_SIZE)
		return error(&sym->location, "%s: out of range (%u max)",
			     s->identifier, s->value, CT_LABEL_BIT_SIZE);

	mpz_init2(value, dtype->size);
	mpz_setbit(value, s->value);
	mpz_export_data(data, value, BYTEORDER_HOST_ENDIAN, sizeof(data));

	*res = constant_expr_alloc(&sym->location, dtype,
				   dtype->byteorder, sizeof(data),
				   data);
	mpz_clear(value);
	return NULL;
}
Beispiel #13
0
/* Calculate r satisfying r*d == 1 mod 2^n. */
void
mpz_invert_2exp (mpz_t r, mpz_t a, unsigned long n)
{
  unsigned long  i;
  mpz_t  inv, prod;

  //ASSERT (mpz_odd_p (a));

  mpz_init_set_ui (inv, 1L);
  mpz_init (prod);

  for (i = 1; i < n; i++)
    {
      mpz_mul (prod, inv, a);
      if (mpz_tstbit (prod, i) != 0)
        mpz_setbit (inv, i);
    }

  mpz_mul (prod, inv, a);
  mpz_tdiv_r_2exp (prod, prod, n);
  //ASSERT (mpz_cmp_ui (prod, 1L) == 0);

  mpz_set (r, inv);

  mpz_clear (inv);
  mpz_clear (prod);
}
Beispiel #14
0
extern "C" PyObject* _PyLong_FromByteArray(const unsigned char* bytes, size_t n, int little_endian,
                                           int is_signed) noexcept {
    if (n == 0)
        return PyLong_FromLong(0);

    if (!little_endian) {
        // TODO: check if the behaviour of mpz_import is right when big endian is specified.
        Py_FatalError("unimplemented");
        return 0;
    }

    BoxedLong* rtn = new BoxedLong();
    mpz_init(rtn->n);
    mpz_import(rtn->n, 1, 1, n, little_endian ? -1 : 1, 0, &bytes[0]);


    RELEASE_ASSERT(little_endian, "");
    if (is_signed && bytes[n - 1] >= 0x80) { // todo add big endian support
        mpz_t t;
        mpz_init(t);
        mpz_setbit(t, n * 8);
        mpz_sub(rtn->n, rtn->n, t);
        mpz_clear(t);
    }

    return rtn;
}
static int twoexpt(void *a, int n)
{
   LTC_ARGCHK(a != NULL);
   mpz_set_ui(a, 0);
   mpz_setbit(a, n);
   return CRYPT_OK;
}
Beispiel #16
0
void
makeprime( mpz_t out, int bits )
{
    mpz_urandomb( out, random_state, bits );
    mpz_setbit( out, bits-1 );
    mpz_nextprime( out, out );
}
Beispiel #17
0
void
check_twobits (void)
{
  unsigned long  i, j, got, want;
  mpz_t  x, y;

  mpz_init (x);
  mpz_init (y);
  for (i = 0; i < 5 * GMP_NUMB_BITS; i++)
    {
      for (j = 0; j < 5 * GMP_NUMB_BITS; j++)
        {
          mpz_set_ui (x, 0L);
          mpz_setbit (x, i);
          mpz_set_ui (y, 0L);
          mpz_setbit (y, j);

          want = 2 * (i != j);
          got = mpz_hamdist (x, y);
          if (got != want)
            {
              printf    ("mpz_hamdist wrong on 2 bits pos/pos\n");
            wrong:
              printf    ("  i    %lu\n", i);
              printf    ("  j    %lu\n", j);
              printf    ("  got  %lu\n", got);
              printf    ("  want %lu\n", want);
              mpz_trace ("  x   ", x);
              mpz_trace ("  y   ", y);
              abort();
            }

          mpz_neg (x, x);
          mpz_neg (y, y);
          want = ABS ((long) (i-j));
          got = mpz_hamdist (x, y);
          if (got != want)
            {
              printf    ("mpz_hamdist wrong on 2 bits neg/neg\n");
              goto wrong;
            }
        }

    }
  mpz_clear (x);
  mpz_clear (y);
}
Beispiel #18
0
void pbc_mpz_urandomb(mpz_t z, unsigned int bits)
{
    mpz_t limit;
    mpz_init(limit);
    mpz_setbit(limit, bits);
    pbc_mpz_random(z, limit);
    mpz_clear(limit);
}
Beispiel #19
0
/* Missing in current gmp */
static void
mpz_togglebit (mpz_t x, unsigned long int bit)
{
  if (mpz_tstbit(x, bit))
    mpz_clrbit(x, bit);
  else
    mpz_setbit(x, bit);
}
Beispiel #20
0
void
mpz_flipbit (mpz_ptr r, unsigned long bit)
{
  if (mpz_tstbit (r, bit))
    mpz_clrbit (r, bit);
  else
    mpz_setbit (r, bit);
}
Beispiel #21
0
void gen_prime(unsigned int b_size, mpz_t res) {

    gmp_randstate_t state;
    struct timeval r_time;

    gettimeofday(&r_time,NULL);
    gmp_randinit_default(state);
    gmp_randseed_ui(state,(r_time.tv_sec * 1000) + (r_time.tv_usec / 1000));

    do {
        mpz_urandomb(res,state,b_size);
        mpz_setbit(res,0);
        mpz_setbit(res,b_size - 1);
        mpz_setbit(res,b_size - 2);
    } while(rabin_miller(res,20,state) == 0);

    gmp_randclear(state);
}
Beispiel #22
0
	void LNSMul::emulate(TestCase * tc)
	{
		mpz_class a = tc->getInputValue("nA");
		mpz_class b = tc->getInputValue("nB");
		
		bool sr = mpz_tstbit(a.get_mpz_t(), wE+wF) ^ mpz_tstbit(b.get_mpz_t(), wE+wF);
		bool xa0 = mpz_tstbit(a.get_mpz_t(), wE+wF+1);
		bool xa1 = mpz_tstbit(a.get_mpz_t(), wE+wF+2);
		bool xb0 = mpz_tstbit(b.get_mpz_t(), wE+wF+1);
		bool xb1 = mpz_tstbit(b.get_mpz_t(), wE+wF+2);
		bool xr0,xr1;
		
		bool nan = (xa0 & xa1) | (xb0 & xb1);		// 11
		bool zero = !(xa0 | xa1) | !(xb0 | xb1);	// 00
		bool inf = (xa1 & !xa0) | (xb1 & !xb0);		// 10
		
		mpz_class r = a + b;
		bool ovf = (mpz_sizeinbase(r.get_mpz_t(), 2) > unsigned(wE+wF)) && (sgn(r) > 0);
		bool udf = (mpz_sizeinbase(r.get_mpz_t(), 2) > unsigned(wE+wF)) && (sgn(r) < 0);

		if(nan | (zero & inf)) {
			xr0 = xr1 = 1;
		}
		else if(zero) {
			xr1 = xr0 = 0;
		}
		else if(inf | ovf) {
			xr1 = 1;
			xr0 = 0;
		}
		else if(udf) {
			xr1 = xr0 = 0;
		}
		else {
			xr1 = 0;
			xr0 = 1;
		}
		if(sr) mpz_setbit(r.get_mpz_t(), wE+wF); else mpz_clrbit(r.get_mpz_t(), wE+wF);
		if(xr0) mpz_setbit(r.get_mpz_t(), wE+wF+1); else mpz_clrbit(r.get_mpz_t(), wE+wF+1);
		if(xr1) mpz_setbit(r.get_mpz_t(), wE+wF+2); else mpz_clrbit(r.get_mpz_t(), wE+wF+2);
		r &= mpzpow2(wE+wF+3)-1;	// Discard overflowing bits
		
		tc->addExpectedOutput("nR", r);
	}
Beispiel #23
0
void
mpz_nextprime (mpz_ptr p, mpz_srcptr n)
{
  mpz_t tmp;
  unsigned short *moduli;
  unsigned long difference;
  int i;
  int composite;

  /* First handle tiny numbers */
  if (mpz_cmp_ui (n, 2) < 0)
    {
      mpz_set_ui (p, 2);
      return;
    }
  mpz_add_ui (p, n, 1);
  mpz_setbit (p, 0);

  if (mpz_cmp_ui (p, 7) <= 0)
    return;

  prime_limit = NUMBER_OF_PRIMES - 1;
  if (mpz_cmp_ui (p, primes[prime_limit]) <= 0)
    /* Just use first three entries (3,5,7) of table for small numbers */
    prime_limit = 3;
  if (prime_limit)
    {
      /* Compute residues modulo small odd primes */
      moduli = (unsigned short *) TMP_ALLOC (prime_limit * sizeof moduli[0]);
      for (i = 0; i < prime_limit; i++)
	moduli[i] = mpz_fdiv_ui (p, primes[i]);
    }
  for (difference = 0; ; difference += 2)
    {
      composite = 0;

      /* First check residues */
      for (i = 0; i < prime_limit; i++)
	{
	  int acc, pr;
	  composite |= (moduli[i] == 0);
	  acc = moduli[i] + 2;
	  pr = primes[i];
	  moduli[i] = acc >= pr ? acc - pr : acc;
	}
      if (composite)
	continue;

      mpz_add_ui (p, p, difference);
      difference = 0;

      /* Miller-Rabin test */
      if (mpz_millerrabin (p, 2))
	break;
    }
}
Beispiel #24
0
void	test_big2(){
	mpz_t v1;
	mpz_t v2;
	bj_big_int_t a, b, c, d;

	//mpz_setbit(d, 6);

	mpz_init_set_ui(v1, 0);
	mpz_init_set_ui(v2, 0);

	mpz_setbit(v1, 6);

	//std::ios_base::showbase = 2;
	bj_out << "v1 is " << v1 << "\n";

	d = bj_big_int_t(v1);
	bj_out << "d is " << d << "\n";

	ch_string s_d;
	d.set_str(s_d, 2);
	bj_out << "s_d is " << d << "\n";

	//ch_string s_v1 = mpz_get_str(NULL, 2, v1);
	//bj_out << "s_v1 is " << s_v1 << "\n";
	ch_string s2_d = mpz_get_str(NULL, 2, d.get_mpz_t());
	bj_out << "s2_d is " << s2_d << "\n";
	//v2 = d.get_mpz_t();

	mpz_clear(v1);
	mpz_clear(v2);

	/*
	a = 1234;
	b = "-5678";
	c = a+b;
	bj_out << "sum is " << c << "\n";
	bj_out << "absolute value is " << abs(c) << "\n";

	mpq_class a2, b2, c2, d2, e2, f2;

	//a2 = 130;
	a2 = 23;
	b2 = 5;
	c2 = a2 / b2;
	d2 = b2 / a2;
	e2 = c2 * d2;
	f2 = c2 + d2;
	//d2 = a2 % b2;
	bj_out << a2 << " div " << b2 << " is " << c2 << "\n";
	bj_out << b2 << " div " << a2 << " is " << d2 << "\n";
	bj_out << c2 << " mul " << d2 << " is " << e2 << "\n";
	bj_out << c2 << " + " << d2 << " = " << f2 << "\n";
	//bj_out << a2 << " mod " << b2 << " is " << d2 << "\n";
	*/
}
Beispiel #25
0
/* Asignar posiciones iniciales para los adversarios en el bitset de usuarios.
 * Las posiciones se asignan aleatoriamente dentro de todo el conjunto */
void asignar_adversarios(mpz_t usuarios, const int &n, const int &k) {
    for (int i = 0; i < k; i++) {
        while (true) {
            int adv_index = rand() % n;
            if (!mpz_tstbit(usuarios, adv_index)) {
                mpz_setbit(usuarios, adv_index);
                break;
            }
        }
    }
}
Beispiel #26
0
static PyObject *
GMPy_XMPZ_Method_SubScript(XMPZ_Object* self, PyObject* item)
{
    CTXT_Object *context = NULL;

    CHECK_CONTEXT(context);

    if (PyIndex_Check(item)) {
        Py_ssize_t i;

        i = PyIntOrLong_AsSsize_t(item);
        if (i == -1 && PyErr_Occurred()) {
            INDEX_ERROR("argument too large to be converted to an index");
            return NULL;
        }
        if (i < 0) {
            i += mpz_sizeinbase(self->z, 2);
        }
        return PyIntOrLong_FromLong(mpz_tstbit(self->z, i));
    }
    else if (PySlice_Check(item)) {
        Py_ssize_t start, stop, step, slicelength, cur, i;
        MPZ_Object *result;

#if PY_VERSION_HEX > 0x030200A4
        if (PySlice_GetIndicesEx(item,
#else
        if (PySlice_GetIndicesEx((PySliceObject*)item,
#endif
                         mpz_sizeinbase(self->z, 2),
                         &start, &stop, &step, &slicelength) < 0) {
            return NULL;
        }

        if ((step < 0 && start < stop) || (step > 0 && start > stop)) {
            stop = start;
        }

        if (!(result = GMPy_MPZ_New(context))) {
            return NULL;
        }

        mpz_set_ui(result->z, 0);
        if (slicelength > 0) {
            for (cur = start, i = 0; i < slicelength; cur += step, i++) {
                if (mpz_tstbit(self->z, cur)) {
                    mpz_setbit(result->z, i);
                }
            }
        }
        return (PyObject*)result;
    }
    else {
int root(mpz_class& result, const mpz_class arg, const mpz_class prime)
{
	mpz_class y, b, t;
	unsigned int r, m;

	if (arg % prime == 0) {
		result = 0;
		return 1;
	}
	if (mpz_legendre(arg.get_mpz_t(), prime.get_mpz_t()) == -1)
		return -1;

	b = 0;
	t = 0;
	y = 2;
	while(mpz_legendre(y.get_mpz_t(), prime.get_mpz_t()) != -1)
	{
		y++;
	}

	result = prime - 1;
	r = mpz_scan1(result.get_mpz_t(), 0);
	mpz_rshift(result.get_mpz_t(), result.get_mpz_t(), r);

	mpz_powm(y.get_mpz_t(), y.get_mpz_t(), result.get_mpz_t(), prime.get_mpz_t());

	mpz_rshift(result.get_mpz_t(), result.get_mpz_t(), 1);
	mpz_powm(b.get_mpz_t(), arg.get_mpz_t(), result.get_mpz_t(), prime.get_mpz_t());

	result = (arg * b) % prime;

	b = (result * b) % prime;

	while(b != 1) {
		t = (b * b) % prime;
		for(m = 1; t != 1; m++) {
			t = (t * t) % prime;
		}

		t = 0;
		mpz_setbit(t.get_mpz_t(), r - m - 1);
		mpz_powm(t.get_mpz_t(), y.get_mpz_t(), t.get_mpz_t(), prime.get_mpz_t());

		y = t * t;

		r = m;

		result = (result * t) % prime;

		b = (b * y) % prime;
	}
	return 1;
}
void Element::multiply(Element& A, Element& B) {
	// Emulate hardware implementation.
	
	// Set result to 0
	mpz_t result;
	mpz_init(result);
	
	// Modulus: x^163 + x^7 + x^6 + x^3 + 1 (wordlength 163)
	mpz_t mod;
	mpz_init(mod);
	mpz_set_str(mod, "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000011001001", 2);
	
	//gmp_printf("Mod = %Zx\n", mod);
	
	// Length of modulus in base 2
	int mod_len = 163;
	
	//printf("Len = %d\n", mod_len);
	
	int m = 0;
	for (long i = (long) mod_len; i > 0; i--) {
		if (mpz_tstbit(A.getMP(), i - 1) == 1) {
			mpz_xor(result, result, B.getMP());
		}
		
		if (m == 1) {
			mpz_xor(result, result, mod);
		}
		
		// Set m & T for next round
		m = mpz_tstbit(result, mod_len - 1);
		
		// Shift T by 1 bit to the left and clear MSB bit
		mpz_clrbit(result, mod_len - 1);
		mpz_mul_2exp(result, result, 1);
		
		/*printf("[Mult] i = %d - T = ", mod_len - i + 2);
		gmp_printf("0x%Zx\n", result);*/
	}
	
	// Shift result back 1 place & place m back in front
	mpz_tdiv_q_2exp(result, result, 1);
	if (m == 1) {
		mpz_setbit(result, 162);
	}
	
	/*printf("[Mult] i = 0 - T = ");
	gmp_printf("0x%Zx\n", result);*/
	
	// Set result
	mpz_set(this->a, result);
}
Beispiel #29
0
// -----------------------------------------------------------------------------
// Generate a random prime number and store the result in @n.
//
// urfd: a file descriptor opened to a random source
// size: the (approx) size in bits for the resulting prime
// mod8: the prime, mod 8, shall be equal to this
// -----------------------------------------------------------------------------
static void
init_random_prime(mpz_t n, int urfd, unsigned size, unsigned mod8) {
  uint8_t buffer[2048];
  const unsigned bytes = size >> 3;

  if (bytes > sizeof(buffer))
    abort();

  mpz_init2(n, bytes);

  for (;;) {
    ssize_t r;

    do {
      r = read(urfd, buffer, bytes);
    } while (r == -1 && errno == EINTR);

    if (r != bytes)
      abort();

    mpz_import(n, bytes, 1, 1, 0, 0, buffer);
    mpz_setbit(n, 0);

    if (mod8 & 2) {
      mpz_setbit(n, 1);
    } else {
      mpz_clrbit(n, 1);
    }

    if (mod8 & 4) {
      mpz_setbit(n, 2);
    } else {
      mpz_clrbit(n, 2);
    }

    if (mpz_probab_prime_p(n, 10))
      break;
  }
}
Beispiel #30
0
int
main(void)
{
    int i, result;
    flint_rand_t state;

    printf("setbit....");
    fflush(stdout);

    flint_randinit(state);

    for (i = 0; i < 100000; i++)
    {
        ulong j;
        fmpz_t a, c;
        mpz_t b;

        fmpz_init(a);
        fmpz_init(c);
        mpz_init(b);

        fmpz_randtest(a, state, 2 * FLINT_BITS);
        fmpz_get_mpz(b, a);
        j = n_randint(state, 3 * FLINT_BITS);

        fmpz_setbit(a, j);
        mpz_setbit(b, j);
        fmpz_set_mpz(c, b);

        result = (fmpz_equal(a, c));

        if (!result)
        {
            printf("FAIL:\n");
            printf("a = "), fmpz_print(a), printf("\n");
            gmp_printf("b = %Zd\n", b);
            printf("c = "), fmpz_print(c), printf("\n");
            printf("j = %ld\n", j);
            abort();
        }

        fmpz_clear(a);
        fmpz_clear(c);
        mpz_clear(b);
    }

    flint_randclear(state);
    _fmpz_cleanup();
    printf("PASS\n");
    return 0;
}