示例#1
0
文件: monty.c 项目: DarkenCode/yafu
void monty_init(z *n)
{
	//for a input modulus n, initialize constants for 
	//montogomery representation
	//this assumes that n is relatively prime to 2, i.e. is odd.
	z g, b, q, r;

	//global montyconst structure
	zInit(&montyconst.nhat);
	zInit(&montyconst.r);
	zInit(&montyconst.rhat);
	zInit(&montyconst.one);

	
	if (abs(n->size) <= 16) 
	{
		fp_montgomery_setup(n,&montyconst.nhat.val[0]);
		fp_montgomery_calc_normalization(&montyconst.r,n);
		montyconst.one.val[0] = 1;
		montyconst.one.size = 1;
		to_monty(&montyconst.one,n);
		TFM_MONTY = 1;
		return;
	}
	else
		TFM_MONTY = 0;

	zInit(&g);
	zInit(&b);
	zInit(&q);
	zInit(&r);

	b.val[1]=1; b.size=2;

	//find r = b^t > N, where b = 2 ^32
	if (montyconst.r.alloc < n->size + 1)
		zGrow(&montyconst.r,n->size + 1);

	zClear(&montyconst.r);
	montyconst.r.size = n->size + 1;
	montyconst.r.val[montyconst.r.size - 1] = 1;

	//find nhat = -n^-1 mod b
	//nhat = -(n^-1 mod b) mod b = b - n^-1 mod b
	//since b is 2^32, this can be simplified, and made faster.
	xGCD(n,&b,&montyconst.nhat,&montyconst.rhat,&g);
	zSub(&b,&montyconst.nhat,&q);
	zCopy(&q,&montyconst.nhat);

	zCopy(&zOne,&montyconst.one);
	to_monty(&montyconst.one,n);

	zFree(&g);
	zFree(&b);
	zFree(&q);
	zFree(&r);
	return;
}
示例#2
0
/* setup */
static int montgomery_setup(void *a, void **b)
{
   int err;
   LTC_ARGCHK(a != NULL);
   LTC_ARGCHK(b != NULL);
   *b = XCALLOC(1, sizeof(fp_digit));
   if (*b == NULL) {
      return CRYPT_MEM;
   }
   if ((err = tfm_to_ltc_error(fp_montgomery_setup(a, (fp_digit *)*b))) != CRYPT_OK) {
      XFREE(*b);
   }
   return err;
}