Exemple #1
0
T CPoly<T>::errev( const int nn, const T qr[], const T qi[], const T ms, const T mp, const T are, const T mre )
   {
   int i;
   T e;

   e = cmod( qr[ 0 ], qi[ 0 ] ) * mre / ( are + mre );
   for( i = 0; i <= nn; i++ )
      e = e * ms + cmod( qr[ i ], qi[ i ] );

   return e * ( are + mre ) - mp * mre;
   }
Exemple #2
0
static double errev(int nn, double qr[], double qi[], double ms, double mp)
     /* Bounds the error in evaluating the polynomial by the Horner recurrence
	
	qr,qi    - The partial sums
	ms       - Modulus of the point
	mp       - Modulus of polynomial value
     */
{
  double e;
  int i;

  e = cmod(qr[0],qi[0])*mre/(are+mre);
  for (i=0;i<nn;i++)
    e = e*ms+cmod(qr[i],qi[i]);
  return e*(are+mre)-mp*mre;
}
Exemple #3
0
static int calct(void)
     /* Computes  t = -p(s)/h(s)
	Returns TRUE if h(s) is essentially zero 
     */
{
  double  hvr,hvi;
  int n = nn-1, boolvar;

  /* Evaluate h(s) */
  polyev(n,sr,si,hr,hi,qhr,qhi,&hvr,&hvi);
  boolvar = (cmod(hvr,hvi) <= are*10.0*cmod(hr[n-1],hi[n-1]));
  if (!boolvar) {
    cdivid(-pvr,-pvi,hvr,hvi,&tr,&ti);
  } else {
    tr = 0.0;
    ti = 0.0;
  }
  return boolvar;
}
Exemple #4
0
void CPoly<T>::noshft( const int l1 )
   {
   int i, j, jj, n, nm1;
   T xni, t1, t2;

   n = nn;
   nm1 = n - 1;
   for( i = 0; i < n; i++ )
      {
      xni = (T) (nn - i);
      hr[ i ] = xni * pr[ i ] / n;
      hi[ i ] = xni * pi[ i ] / n;
      }
   for( jj = 1; jj <= l1; jj++ )
      {
      if( cmod( hr[ n - 1 ], hi[ n - 1 ] ) > eta * 10 * cmod( pr[ n - 1 ], pi[ n - 1 ] ) )
         {
         cdivid( -pr[ nn ], -pi[ nn ], hr[ n - 1 ], hi[ n - 1 ], &tr, &ti );
         for( i = 0; i < nm1; i++ )
            {
            j = nn - i - 1;
            t1 = hr[ j - 1 ];
            t2 = hi[ j - 1 ];
            hr[ j ] = tr * t1 - ti * t2 + pr[ j ];
            hi[ j ] = tr * t2 + ti * t1 + pi[ j ];
            }
         hr[ 0 ] = pr[ 0 ];
         hi[ 0 ] = pi[ 0 ];
         }
      else
         {
         // If the constant term is essentially zero, shift H coefficients
         for( i = 0; i < nm1; i++ )
            {
            j = nn - i - 1;
            hr[ j ] = hr[ j - 1 ];
            hi[ j ] = hi[ j - 1 ];
            }
         hr[ 0 ] = 0;
         hi[ 0 ] = 0;
         }
      }
   }
Exemple #5
0
void CPoly<T>::calct( int *bol )
   {
   int n;
   T hvr, hvi;

   n = nn;

   // evaluate h(s)
   polyev( n - 1, sr, si, hr, hi, qhr, qhi, &hvr, &hvi );
   *bol = cmod( hvr, hvi ) <= are * 10 * cmod( hr[ n - 1 ], hi[ n - 1 ] ) ? 1 : 0;
   if( !*bol )
      {
      cdivid( -pvr, -pvi, hvr, hvi, &tr, &ti );
      return;
      }

   tr = 0;
   ti = 0;
   }
Exemple #6
0
static void noshft(int l1)
{
  /*  Computes the derivative polynomial as the initial h
      polynomial and computes l1 no-shift h polynomials. */

  double  xni,t1,t2;
  int i,j,jj,n = nn-1,nm1 = n-1,nm2=nm1-1;
  for (i=0;i<n;i++) {
    xni = n-i;
    hr[i] = xni*pr[i]/((double)(n));
    hi[i] = xni*pi[i]/((double)(n));
  }
  for (jj=0;jj<l1;jj++) {
    if (cmod(hr[nm2],hi[nm2]) > eta*10.0*cmod(pr[nm2],pi[nm2])) {
      cdivid(-pr[n],-pi[n],hr[nm1],hi[nm1],&tr,&ti);
      for (i=0;i<nm1;i++) {
	j = nm1-i;
	t1 = hr[j-1];
	t2 = hi[j-1];
	hr[j] = tr*t1-ti*t2+pr[j];
	hi[j] = tr*t2+ti*t1+pi[j];
      }
      hr[0] = pr[0];
      hi[0] = pi[0];
    } else {

      /*  If the constant term is essentially zero, shift h coefficients */
      for (i=0;i<nm1;i++) {
	j = nm1-i;
	hr[j] = hr[j-1];
	hi[j] = hi[j-1];
      }
      hr[0] = 0.0;
      hi[0] = 0.0;
    }
  }
}
static void feld_rx(struct trx *trx, complex z)
{
	struct feld *s = (struct feld *) trx->modem;
	double x;

	s->rxcounter += DownSampleInc;

	if (s->rxcounter < 1.0)
		return;

	s->rxcounter -= 1.0;

	x = cmod(z);

	if (x > s->agc)
		s->agc = x;
	else
		s->agc *= (1 - 0.02 / RxColumnLen);

	x = 255 * CLAMP(1.0 - x / s->agc, 0.0, 1.0);
	trx_put_rx_data((int) x);

	trx->metric = s->agc / 10.0;
}
Exemple #8
0
static int
testPack(PQ_PARAM_SET_ID id)
{
  int i;
  int T;
  int rc;
  PQ_PARAM_SET *P;
  if(!(P = pq_get_param_set_by_id(id)))
  {
    return -1;
  }

  unsigned char *scratch;
  uint16_t *iF;
  uint16_t *oF;
  uint16_t *ig;
  uint16_t *og;
  int64_t *iginv;
  int64_t *oginv;
  int64_t *ih;
  int64_t *oh;
  int64_t *isig;
  int64_t *osig;
  unsigned char *priv_blob;
  unsigned char *pub_blob;
  unsigned char *sig_blob;

  size_t prod = 2*(P->d1 + P->d2 + P->d3)*sizeof(uint16_t);
  size_t full = P->N*sizeof(int64_t);
  size_t priv_blob_len = PRIVKEY_PACKED_BYTES(P);
  size_t pub_blob_len = PUBKEY_PACKED_BYTES(P);
  size_t sig_len = SIGNATURE_BYTES(P);
  size_t offset;

  scratch = malloc(4*prod + 6*full + priv_blob_len + pub_blob_len + sig_len);

  offset = 0;
  iF = (uint16_t*)(scratch + offset); offset += prod;
  oF = (uint16_t*)(scratch + offset); offset += prod;
  ig = (uint16_t*)(scratch + offset); offset += prod;
  og = (uint16_t*)(scratch + offset); offset += prod;
  iginv = (int64_t*)(scratch + offset); offset += full;
  oginv = (int64_t*)(scratch + offset); offset += full;
  isig = (int64_t*)(scratch + offset); offset += full;
  osig = (int64_t*)(scratch + offset); offset += full;
  ih = (int64_t*)(scratch + offset); offset += full;
  oh = (int64_t*)(scratch + offset); offset += full;
  priv_blob = (unsigned char*)(scratch + offset); offset += priv_blob_len;
  pub_blob = (unsigned char*)(scratch + offset); offset += pub_blob_len;
  sig_blob = (unsigned char*)(scratch + offset); offset += sig_len;

  for(T=0; T<TIMES; T++)
  {
    fastrandombytes(scratch, 4*prod + 6*full + priv_blob_len + pub_blob_len + sig_len);
    for(i = 0; i < prod; i++)
    {
      iF[i] = iF[i] % P->N;
      ig[i] = ig[i] % P->N;
    }

    for(i=0; i < P->N; i++)
    {
      iginv[i] = cmod(iginv[i], P->p);
      ih[i] = cmod(ih[i], P->q);
      isig[i] = isig[i] % P->q;
      isig[i] = (isig[i] + P->q) % P->q;
      isig[i] -= isig[i] % P->p;
      isig[i] /= P->p;
    }

    rc = pack_private_key(P, iF, ig, iginv, priv_blob_len, priv_blob);
    if(PQNTRU_ERROR == rc) { printf("Private key pack error\n"); return -1; }

    rc = unpack_private_key(P, oF, og, oginv, priv_blob_len, priv_blob);
    if(PQNTRU_ERROR == rc) { printf("Private key unpack error\n"); return -1; }

    rc = pack_public_key(P, ih, pub_blob_len, pub_blob);
    if(PQNTRU_ERROR == rc) { printf("Public key pack error\n"); return -1; }

    rc = unpack_public_key(P, oh, pub_blob_len, pub_blob);
    if(PQNTRU_ERROR == rc) { printf("Public key unpack error\n"); return -1; }

    rc = pack_signature(P, isig, sig_len, sig_blob);
    if(PQNTRU_ERROR == rc) { printf("Signature pack error\n"); return -1; }

    rc = unpack_signature(P, osig, sig_len, sig_blob);
    if(PQNTRU_ERROR == rc) { printf("Signature unpack error\n"); return -1; }

    for(i=0; i<2*(P->d1 + P->d2 + P->d3); i++)
    {
      if(iF[i] != oF[i] || ig[i] != og[i])
      {
        printf("product form keys not equal\n");
        break;
      }
    }

    for(i=0; i<P->N; i++)
    {
      oh[i] = cmod(oh[i], P->q);
      oginv[i] = cmod(oginv[i], P->p);
      if(ih[i] != oh[i] || iginv[i] != oginv[i])
      {
        printf("%d %ld %ld %ld %ld\n", i, ih[i], oh[i], iginv[i], oginv[i]);
        printf("public key or iginv not equal\n");
        return -1;
      }

      if(isig[i] != osig[i])
      {
        printf("%d %ld %ld\n", i, isig[i], osig[i]);
        printf("signatures not equal\n");
        return -1;
      }
    }
  }
}
Exemple #9
0
static int
testKeyGen(PQ_PARAM_SET_ID id)
{
  uint16_t i;
  uint16_t j;

  PQ_PARAM_SET *P;
  size_t privkey_blob_len;
  size_t pubkey_blob_len;

  unsigned char *privkey_blob;
  unsigned char *pubkey_blob;

  unsigned char *scratch;
  size_t         scratch_len;

  int rc;

  if(!(P = pq_get_param_set_by_id(id)))
  {
    return -1;
  }

  size_t prod = 2*(P->d1 + P->d2 + P->d3)*sizeof(uint16_t);
  size_t full = POLYNOMIAL_BYTES(P);
  scratch_len = 2*prod + 6*full;
  scratch = malloc(scratch_len);
  size_t offset = 0;
  uint16_t *f = (uint16_t*)(scratch); offset += prod;
  uint16_t *g = (uint16_t*)(scratch+offset); offset += prod;
  int64_t *ginv = (int64_t*)(scratch+offset); offset += full;
  int64_t *h = (int64_t*)(scratch+offset); offset += full;
  int64_t *a1 = (int64_t*)(scratch+offset); offset += full;
  int64_t *a2 = (int64_t*)(scratch+offset); offset += 3*full;

  for(i=0; i<TIMES; i++)
  {
    memset(scratch, 0, scratch_len);

    /* Generate a key */
    pq_gen_key(P, &privkey_blob_len, NULL, &pubkey_blob_len, NULL);

    privkey_blob = malloc(privkey_blob_len);
    pubkey_blob = malloc(pubkey_blob_len);

    if(PQNTRU_ERROR == pq_gen_key(P,
               &privkey_blob_len, privkey_blob,
               &pubkey_blob_len, pubkey_blob))
    {
      fprintf(stderr, "\t fail in keygen\n");
    }

    /* Unpack the key */
    rc = unpack_private_key(P, f, g, ginv, privkey_blob_len, privkey_blob);
    if(PQNTRU_ERROR == rc) { printf("Private key unpack error\n"); return -1; }

    rc = unpack_public_key(P, h, pubkey_blob_len, pubkey_blob);
    if(PQNTRU_ERROR == rc) { printf("Public key unpack error\n"); return -1; }

    /* Multiply h by f mod q, should have g in a1 */
    pol_mul_product(a1, h, P->d1, P->d2, P->d3, f, P->N, a2);
    for(j=0; j<P->N; j++)
    {
      a1[j] = cmod(P->p * (h[j] + a1[j]), P->q);
    }

    /* Multiply a1 by g inverse mod p, should have 1 in a2 */
    pol_mul_coefficients(a2, a1, ginv, P->N, P->padded_N, P->p, a2);
    for(j=1; j<P->N; j++)
    {
      if(a2[0] != 1 || a2[j] != 0)
      {
        fprintf(stderr, "\t bad key");
        free(privkey_blob);
        free(pubkey_blob);
        free(scratch);
        return -1;
      }
    }

    free(privkey_blob);
    free(pubkey_blob);
  }
  free(scratch);

  return 0;
}
Exemple #10
0
int
pq_gen_key(
    PQ_PARAM_SET  *P,
    size_t        *privkey_blob_len,
    unsigned char *privkey_blob,
    size_t        *pubkey_blob_len,
    unsigned char *pubkey_blob)
{
  uint16_t      i;
  uint16_t      m;

  uint16_t      N;
  uint16_t      padN;
  int64_t       q;
  int8_t        p;
  uint16_t      d1;
  uint16_t      d2;
  uint16_t      d3;

  size_t        private_key_blob_len;
  size_t        public_key_blob_len;

  uint16_t      *f;
  uint16_t      *g;
  int64_t       *h;

  size_t        scratch_len;
  size_t        offset;
  unsigned char *scratch;
  int64_t       *a1;
  int64_t       *a2;
  int64_t       *tmpx3;

  if(!P || !privkey_blob_len || !pubkey_blob_len)
  {
    return PQNTRU_ERROR;
  }

  N = P->N;
  padN = P->padded_N;
  q = P->q;
  p = P->p;
  d1 = P->d1;
  d2 = P->d2;
  d3 = P->d3;

  /* TODO: Standardize packed key formats */

  private_key_blob_len = PRIVKEY_PACKED_BYTES(P);
  public_key_blob_len = PUBKEY_PACKED_BYTES(P);

  if(!privkey_blob || !pubkey_blob)
  {
    if(!privkey_blob && privkey_blob_len != NULL)
    {
      *privkey_blob_len = private_key_blob_len;
    }
    if(!pubkey_blob && pubkey_blob_len != NULL)
    {
      *pubkey_blob_len = public_key_blob_len;
    }
    return PQNTRU_OK;
  }

  if((*privkey_blob_len != private_key_blob_len)
      || (*pubkey_blob_len != public_key_blob_len))
  {
    return PQNTRU_ERROR;
  }

  scratch_len = 2 * PRODUCT_FORM_BYTES(P) + 6 * POLYNOMIAL_BYTES(P);
  if(!(scratch = malloc(scratch_len)))
  {
    return PQNTRU_ERROR;
  }
  memset(scratch, 0, scratch_len);

  offset = 0;
  f = (uint16_t*)(scratch);            offset += PRODUCT_FORM_BYTES(P);
  g = (uint16_t*)(scratch + offset);   offset += PRODUCT_FORM_BYTES(P);
  h  = (int64_t*)(scratch + offset);   offset += POLYNOMIAL_BYTES(P);
  a1 = (int64_t*)(scratch + offset);   offset += POLYNOMIAL_BYTES(P);
  a2 = (int64_t*)(scratch + offset);   offset += POLYNOMIAL_BYTES(P);
  tmpx3 = (int64_t*)(scratch + offset);


  /* Find invertible pf mod q */
  /* TODO: Better sampling of product form keys
   *       Try to avoid keys with f(1) = 0
   */
  do
  {
    pol_gen_product(f, d1, d2, d3, N);

    /* f = p * (1 + product form poly) */
    memset(a1, 0, POLYNOMIAL_BYTES(P));
    a1[0] = p;

    pol_mul_product(a1, a1, d1, d2, d3, f, N, tmpx3);
    a1[0] += p;

  } while(PQNTRU_ERROR == pol_inv_mod2(a2, a1, N));

  /* Lift from (Z/2Z)[X]/(X^N - 1) to (Z/qZ)[X]/(X^N -1) */
  for (m = 0; m < 5; ++m)   /* assumes 2^16 < q <= 2^32 */
  {
    /* a^-1 = a^-1 * (2 - a * a^-1) mod q */

    pol_mul_product(a1, a2, d1, d2, d3, f, N, tmpx3);

    for (i = 0; i < N; ++i)
    {
      a1[i] = -p*(a1[i] + a2[i]);
    }

    a1[0] = a1[0] + 2;
    pol_mul_coefficients(a2, a2, a1, N, padN, q, tmpx3);
  }


  /* Find invertible g mod p */
  do
  {
    /* Generate product form g,
     * then expand it to find inverse mod p
     */
    pol_gen_product(g, d1, d2, d3, N);

    memset(a1, 0, POLYNOMIAL_BYTES(P));
    a1[0] = 1;

    pol_mul_product(a1, a1, d1, d2, d3, g, N, tmpx3);
    a1[0] += 1;

  } while(PQNTRU_ERROR == pol_inv_modp(tmpx3, a1, N, p));

  pack_private_key(P, f, g, tmpx3, private_key_blob_len, privkey_blob);

  /* Calculate public key, h = g/f mod q */
  pol_mul_product(h, a2, d1, d2, d3, g, N, tmpx3);
  for(i=0; i<N; i++)
  {
    h[i] = cmod(h[i] + a2[i], q);
  }

/*  int j;
  for (i=0; i<d1; i++) {
	  for (j=d1; j<2*d1; j++) {
		  if (f[i] == f[j]) {
			  printf("stupid key f: %d, %d, %d!\n", i, j, f[i]);
			  break;
		  }
		  if (g[i] == g[j]) {
			  printf("stupid key g: %d, %d, %d!\n", i, j, g[i]);
			  break;
		  }
	  }
  }
  for (i=2*d1; i<2*d1+d2; i++) {
	  for (j=2*d1+d2; j<2*(d1+d2); j++) {
		  if (f[i] == f[j]) {
			  printf("stupid key f: %d, %d, %d!\n", i, j, f[i]);
			  break;
		  }
		  if (g[i] == g[j]) {
			  printf("stupid key g: %d, %d, %d!\n", i, j, g[i]);
			  break;
		  }
	  }
  }
  for (i=2*(d1+d2); i<2*(d1+d2)+d3; i++) {
	  for (j=2*(d1+d2)+d3; j<2*(d1+d2+d3); j++) {
		  if (f[i] == f[j]) {
			  printf("stupid key f: %d, %d, %d!\n", i, j, f[i]);
			  break;
		  }
		  if (g[i] == g[j]) {
			  printf("stupid key g: %d, %d, %d!\n", i, j, g[i]);
			  break;
		  }
	  }
  }*/

  pack_public_key(P, h, public_key_blob_len, pubkey_blob);

  shred(scratch, scratch_len);
  free(scratch);

  return PQNTRU_OK;
}
Exemple #11
0
void CPoly<T>::vrshft( const int l3, T *zr, T *zi, int *conv )
   {
   int b, bol;
   int i, j;
   T mp, ms, omp, relstp, r1, r2, tp;

   *conv = 0;
   b = 0;
   sr = *zr;
   si = *zi;

   // Main loop for stage three
   for( i = 1; i <= l3; i++ )
      {
      // Evaluate P at S and test for convergence
      polyev( nn, sr, si, pr, pi, qpr, qpi, &pvr, &pvi );
      mp = cmod( pvr, pvi );
      ms = cmod( sr, si );
      if( mp <= 20 * errev( nn, qpr, qpi, ms, mp, are, mre ) )
         {
         // Polynomial value is smaller in value than a bound onthe error
         // in evaluationg P, terminate the ietartion
         *conv = 1;
         *zr = sr;
         *zi = si;
         return;
         }
      if( i != 1 )
         {
         if( !( b || mp < omp || relstp >= 0.05 ) )
            {
            // Iteration has stalled. Probably a cluster of zeros. Do 5 fixed
            // shift steps into the cluster to force one zero to dominate
            tp = relstp;
            b = 1;
            if( relstp < eta ) tp = eta;
            r1 = sqrt( tp );
            r2 = sr * ( 1 + r1 ) - si * r1;
            si = sr * r1 + si * ( 1 + r1 );
            sr = r2;
            polyev( nn, sr, si, pr, pi, qpr, qpi, &pvr, &pvi );
            for( j = 1; j <= 5; j++ )
               {
               calct( &bol );
               nexth( bol );
               }
            omp = infin;
            goto _20;
            }

         // Exit if polynomial value increase significantly
         if( mp *0.1 > omp ) return;
         }

      omp = mp;

      // Calculate next iterate
_20:  calct( &bol );
      nexth( bol );
      calct( &bol );
      if( !bol )
         {
         relstp = cmod( tr, ti ) / cmod( sr, si );
         sr += tr;
         si += ti;
         }
      }
   }
Exemple #12
0
void playerfn(int frameDelta)
{
	SDL_Rect blitrect;
	SDL_Rect portalblitrect;
	SDL_Rect portalspriterect;
	int blink;
	
	if (controls.right)
	{
		player.speed_x += 1;
		
		if (player.speed_x > 5)
		{
			player.speed_x = 5;
		}
	}
	else if (controls.left)
	{
		player.speed_x -= 1;
		
		if (player.speed_x < -5)
		{
			player.speed_x = -5;
		}
	}
	else
	{
		player.speed_x *= 0.6;
	}
	
	if (controls.button1 && player.ground)
	{
		sound_synth_play(sfx_player_jump);
		
		player.speed_y = -10;
		player.jumppower = 2.5;
		player.ground = 0;
	}
	else if (controls.button1 && player.speed_y < 0 && player.jumppower > 0)
	{
		player.speed_y -= player.jumppower / 1.7;
		player.jumppower *= 0.89;
	}
	
	if (!player.shootwait && controls.button2 && player.shooting == 0)
	{
		player.shooting = 1;
		player.shootwait = 60;
		
		if (nthlevel >= 6)
		{
			player.shootwait += nthlevel;
		}
		
		player.animtime = 250;
		sound_synth_play(sfx_player_scare);
		sound_synth_play(sfx_player_scare2);
	}
	else if (player.shootwait > 0)
	{
		--player.shootwait;
	}
	
	if (player.ground == 0)
	{
		player.speed_y += gravity;
		
		if (player.speed_y > 15)
		{
			player.speed_y = 15;
		}
	}
	
	player.ground = 0;
	
	if (1/*player.speed_y > 0*/)
	{
		if (level[cmod((int)floor((player.rect.y + player.rect.h + player.speed_y) / 16), 30)][cmod((int)floor((player.rect.x) / 16), 40)] == '.')
		{
			player.rect.y = 16 * floor((player.rect.y + player.rect.h + player.speed_y) / 16) - player.rect.h;
			player.speed_y = 0;
			player.ground = 1;
			player.jumppower = 0;
		}
		else if (level[cmod((int)floor((player.rect.y + player.rect.h + player.speed_y) / 16), 30)][cmod((int)floor((player.rect.x + player.rect.w - 1) / 16), 40)] == '.')
		{
			player.rect.y = 16 * floor((player.rect.y + player.rect.h + player.speed_y) / 16) - player.rect.h;
			player.speed_y = 0;
			player.ground = 1;
			player.jumppower = 0;
		}
	}
	
	/*else */if (player.speed_y < 0)
	{
		if (level[cmod((int)floor((player.rect.y + player.speed_y) / 16), 30)][cmod((int)floor((player.rect.x) / 16), 40)] == '.')
		{
			player.rect.y = 16 + 16 * floor((player.rect.y + player.speed_y) / 16);
			player.speed_y = 0;
			player.jumppower = 0;
		}
		else if (level[cmod((int)floor((player.rect.y + player.speed_y) / 16), 30)][cmod((int)floor((player.rect.x + player.rect.w - 1) / 16), 40)] == '.')
		{
			player.rect.y = 16 + 16 * floor((player.rect.y + player.speed_y) / 16);
			player.speed_y = 0;
			player.jumppower = 0;
		}
	}
	
	if (player.speed_x > 0)
	{
		if (level[cmod((int)floor((player.rect.y) / 16), 30)][cmod((int)floor((player.rect.x + player.rect.w + player.speed_x) / 16), 40)] == '.')
		{
			player.rect.x = 16 * floor((player.rect.x + player.rect.w + player.speed_x) / 16) - player.rect.w;
			player.speed_x = 0;
		}
		else if (level[cmod((int)floor((player.rect.y + (player.rect.h / 2) - 1) / 16), 30)][cmod((int)floor((player.rect.x + player.rect.w + player.speed_x) / 16), 40)] == '.')
		{
			player.rect.x = 16 * floor((player.rect.x + player.rect.w + player.speed_x) / 16) - player.rect.w;
			player.speed_x = 0;
		}
		else if (level[cmod((int)floor((player.rect.y + player.rect.h - 1) / 16), 30)][cmod((int)floor((player.rect.x + player.rect.w + player.speed_x) / 16), 40)] == '.')
		{
			player.rect.x = 16 * floor((player.rect.x + player.rect.w + player.speed_x) / 16) - player.rect.w;
			player.speed_x = 0;
		}
	}
	else if (player.speed_x < 0)
	{
		if (level[cmod((int)floor((player.rect.y) / 16), 30)][cmod((int)floor((player.rect.x + player.speed_x) / 16), 40)] == '.')
		{
			player.rect.x = 16 + 16 * floor((player.rect.x + player.speed_x) / 16);
			player.speed_x = 0;
		}
		else if (level[cmod((int)floor((player.rect.y + (player.rect.h / 2) - 1) / 16), 30)][cmod((int)floor((player.rect.x + player.speed_x) / 16), 40)] == '.')
		{
			player.rect.x = 16 + 16 * floor((player.rect.x + player.speed_x) / 16);
			player.speed_x = 0;
		}
		else if (level[cmod((int)floor((player.rect.y + player.rect.h - 1) / 16), 30)][cmod((int)floor((player.rect.x + player.speed_x) / 16), 40)] == '.')
		{
			player.rect.x = 16 + 16 * floor((player.rect.x + player.speed_x) / 16);
			player.speed_x = 0;
		}
	}
	
	player.rect.x += round(player.speed_x);
	player.rect.y += round(player.speed_y);
	
	if (player.speed_x > 0 && player.spriterect.x == 0)
	{
		player.spriterect.x = 192;
	}
	else if (player.speed_x < 0 && player.spriterect.x == 192)
	{
		player.spriterect.x = 0;
	}
	
	if (player.shooting)
	{
		player.spriterect.y = 192;
	}
	else if (!player.ground)
	{
		player.spriterect.y = 128;
	}
	else if (player.speed_x > 0.1 || player.speed_x < -0.1)
	{
		player.spriterect.y = 64;
	}
	else
	{
		player.spriterect.y = 0;
	}
	
	if (player.animtime > 0)
	{
		player.animtime -= frameDelta;
	}
	else
	{
		player.animframe = (player.animframe + 1) % 4;
		player.animtime = 50;
		
		if (player.shooting)
		{
			player.shooting = 0;
		}
	}
	
	// SDL_FillRect(screen, &player.rect, SDL_MapRGB(screen->format, 255, 255, 0));
	
	if (player.hurting)
	{
		blink = (int)floor((float)player.hurttime / 100.0) % 2;
	}
	else
	{
		blink = 0;
	}
	
	blitrect.x = player.rect.x;
	blitrect.y = player.rect.y;
	blitrect.w = player.rect.w;
	blitrect.h = player.rect.h;
	
	player.spriterect.x += 48 * player.animframe;
	
	if (player.rect.x + player.rect.w >= 640)
	{
		if (!blink)
		{
			SDL_BlitSurface(sprite_player, &player.spriterect, screen, &blitrect);
			
			blitrect.x = player.rect.x - 640;
			SDL_BlitSurface(sprite_player, &player.spriterect, screen, &blitrect);
		}
		
		if (player.rect.x >= 640)
		{
			player.rect.x -= 640;
		}
	}
	else if (player.rect.x < 0)
	{
		if (!blink)
		{
			SDL_BlitSurface(sprite_player, &player.spriterect, screen, &blitrect);
			
			blitrect.x = player.rect.x + 640;
			SDL_BlitSurface(sprite_player, &player.spriterect, screen, &blitrect);
		}
		
		if (player.rect.x + player.rect.w <= 0)
		{
			player.rect.x += 640;
		}
	}
	else if (player.rect.y + player.rect.h >= 480)
	{
		if (!blink)
		{
			SDL_BlitSurface(sprite_player, &player.spriterect, screen, &blitrect);
			
			blitrect.y = player.rect.y - 480;
			SDL_BlitSurface(sprite_player, &player.spriterect, screen, &blitrect);
		}
		
		if (player.rect.y >= 480)
		{
			player.rect.y -= 480;
		}
	}
	else if (player.rect.y < 0)
	{
		if (!blink)
		{
			SDL_BlitSurface(sprite_player, &player.spriterect, screen, &blitrect);
			
			blitrect.y = player.rect.y + 480;
			SDL_BlitSurface(sprite_player, &player.spriterect, screen, &blitrect);
		}
		
		if (player.rect.y + player.rect.h < 0)
		{
			player.rect.y += 480;
		}
	}
	else if (!blink)
	{
		SDL_BlitSurface(sprite_player, &player.spriterect, screen, &blitrect);
	}
	
	player.spriterect.x -= 48 * player.animframe;
	
	if (player.hurting)
	{
		player.hurttime += frameDelta;
		
		if (player.hurttime >= 2000)
		{
			player.hurting = 0;
			player.hurttime = 0;
		}
	}
}
Exemple #13
0
float *bs_ave(float *images, float *win, slaveinfo l, long *index,
	      long bs_cnt, float *bsc, float *wc, float *amp, int maxk,
	      int *shifts)
{
    long i, j, k, m;		// loop & helper variables
    long i1, i2, i3;		// index variables
    double t1, t2, t3, t4;	// temporary real variables
    float ct1[2], ct2[2];	// temporary complex variables
    long nx, ny, nxh, nyh;	// half of subfield size
    long nfr, N, cnt;		// # of pixels in one image, loop variable
    double s = 0;		// mean intensity in image
    long u1, u2, v1, v2;	// bispectrum vectors
    fftw_complex *im1;		// temporary matrices
    fftw_complex *im2;
    float *bsr, *bsi;		// used for calculation of SNR
    float *origin;		// phase values around origin (needed for init)

    fftw_plan fftimage;		// plan for fourier transform

    nfr = l.nrofframes;
    nx = l.sfsizex;
    ny = l.sfsizey;
    nxh = nx / 2;
    nyh = ny / 2;
    N = nx * ny;       // subfield size in pixels

    origin = (float *) calloc(2 * maxk, sizeof(float));

    im1 = fftw_malloc(N * sizeof(fftw_complex));
    im2 = fftw_malloc(N * sizeof(fftw_complex));

    // setting up resultant matrices
    bsr = (float *) calloc(bs_cnt, sizeof(float));
    bsi = (float *) calloc(bs_cnt, sizeof(float));

    fftimage = fftw_plan_dft_2d(nx, ny, im1, im2, -1, FFTW_ESTIMATE);

	for (k = 0; k < nfr; k++) {
		// set a helper index
		m = k * N;
		// Calculate the mean of the image
		stats(&images[m], N, 0, &s, NULL);
		// store the windowed image in image1
		for (j = 0; j < ny; j++) {
			for (i = 0; i < nx; i++) {
				idx(i, j, nx, i1);
				im1[i1][0] = (double) ((images[i1 + m] - s) * win[i1] + s);  // problem here, with image
				im1[i1][1] = 0.0;

			}
		}
		// a) do FFT(imagei,-1)
		//    write the result into im2 (see fftw_plan fftimage)
		// b) shift the image, so low frequencies are in the origin
		//    write the results back into im1, scaled with
		//    1/(nx*ny) (not done by FFTW but by IDL does, thanks
		//    Alexandra Tritschler for the hint!)
		fftw_execute(fftimage);
		for (j = 0; j < ny; j++) {		// iterates through subfield pixels
			for (i = 0; i < nx; i++) {
				idx(i, j, nx, i1);		// jump to pixel position
				shift_idx(i, j, nxh, nyh, nx, ny, i2);
				im1[i1][0] = im2[i2][0] / N;		// complex part
				im1[i1][1] = im2[i2][1] / N;		// imaginary part
				amp[i1] +=
					(float) (sqrt
						 (im1[i1][0] * im1[i1][0] +			// why are these so large??
						  im1[i1][1] * im1[i1][1]) / nfr);
			}
		}
		// phase around origin
		for (cnt = 0; cnt < maxk; cnt++) {
			idx(nxh + shifts[2 * cnt], nyh + shifts[2 * cnt + 1], nx, i1);
			origin[2 * cnt] += im1[i1][0];
			origin[2 * cnt + 1] += im1[i1][1];
		}
		// calculate the mean raw bispectrum fast in non redundant matrix
		for (cnt = 0; cnt < bs_cnt; cnt++) {
			// get vectors
			u1 = index[0 + cnt * 4];
			u2 = index[1 + cnt * 4];
			v1 = index[2 + cnt * 4];
			v2 = index[3 + cnt * 4];
			// get matrix indices of vectors
			idx(nxh - u1, nyh + u2, nx, i1);
			idx(nxh - v1, nyh + v2, nx, i2);
			idx(nxh - u1 - v1, nyh + u2 + v2, nx, i3);
			// calculate bispectrum i(u)*i(v)*conj(i(u+v))
			//   (a+ib)(c+id)=((ac-bd)+i(bc+ad))
			ct1[0] = im1[i1][0] * im1[i2][0] - im1[i1][1] * im1[i2][1];
			ct1[1] = im1[i1][1] * im1[i2][0] + im1[i1][0] * im1[i2][1];
			//   (a+ib)(c-id)=((ac+bd)+i(bc-ad))
			ct2[0] = ct1[0] * im1[i3][0] + ct1[1] * im1[i3][1];
			ct2[1] = ct1[1] * im1[i3][0] - ct1[0] * im1[i3][1];
			// assign values
			bsc[2 * cnt] += ct2[0];
			//      bsc[2*cnt] += ct2[0]   // noise terms attached
			//         - ((im1[i1][0]*im1[i1][0] + im1[i1][1]*im1[i1][1])
			//           +(im1[i2][0]*im1[i2][0] + im1[i2][1]*im1[i2][1])
			//           +(im1[i3][0]*im1[i3][0] + im1[i3][1]*im1[i3][1]));
			bsc[2 * cnt + 1] += ct2[1];
			bsr[cnt] += bsc[2 * cnt] * bsc[2 * cnt];
			bsi[cnt] += bsc[2 * cnt + 1] * bsc[2 * cnt + 1];
		}
	}

    // phase around origin is averaged and normalized
    for (cnt = 0; cnt < maxk; cnt++) {
		t1 = cmod(&origin[2 * cnt]);
		origin[2 * cnt] /= t1;
		origin[2 * cnt + 1] /= t1;
    }

    // create bispectrum SNR (weights) and mean in non-redundant matrices
	for (cnt = 0; cnt < bs_cnt; cnt++) {
		// calculate SNR
		// sum of 2 normally - distributed random variables (real & imaginary part)
		t1 = bsc[2 * cnt] / nfr;
		t1 *= t1;		// (squared) mean real part
		t2 = bsc[2 * cnt + 1] / nfr;
		t2 *= t2;		// (squared) mean imaginary part
		t3 = fabs(bsr[cnt] - nfr * t1) / (nfr - 1);	// variance of real part
		t4 = fabs(bsi[cnt] - nfr * t2) / (nfr - 1);	// variance of imaginary part
		wc[cnt] = (float) sqrt(t1 + t2) * sqrt(nfr) / sqrt(t3 + t4);	// => SNR of MEAN absolute

			// make mean and normalize the phases if nonzero
		if ((bsc[2 * cnt] != 0.0) || (bsc[2 * cnt + 1] != 0.0)) {
			t1 = cmod(&bsc[2 * cnt]);
			bsc[2 * cnt] /= t1;
			bsc[2 * cnt + 1] /= t1;
		}
    }

    fftw_free(im1);
    fftw_free(im2);
    free(bsr);
    free(bsi);

    fftw_cleanup();

    return (origin);
}
Exemple #14
0
static int vrshft(int l3, double *zr, double *zi)
     /*  Carries out the third stage iteration

	 l3      - Limit of steps in stage 3
	 zr,zi   - On entry contains the initial iterate,
	           On exit, it contains the final iterate (if it converges).
	 conv    - TRUE if iteration converges 
     */
{
  double mp,ms,omp,relstp,r1,r2,tp;
  int i,j,conv,b,boolvar;

  conv = FALSE;
  b = FALSE;
  sr = *zr;
  si = *zi;

  /* Main loop for stage three */
  for (i=0; i<l3;i++) {

    /* Evaluate p at s and test for convergence */
    polyev(nn,sr,si,pr,pi,qpr,qpi,&pvr,&pvi);
    mp = cmod(pvr,pvi);
    ms = cmod(sr,si);
    if (mp <= 20.0L*errev(nn,qpr,qpi,ms,mp)) {
      /* Polynomial value is smaller in value than a bound on the error
	 in evaluating p, terminate the iteration */
      conv = TRUE;
      *zr = sr;
      *zi = si;
      return conv;
    } else {
      if (i!=0) {
	if (!b && mp>=omp && relstp < .05L) {
	  /* Iteration has stalled, probably a cluster of zeros 
	     Do 5 fixed shift steps into the cluster to force one zero 
	     to dominate */
	  b = TRUE;
	  if (relstp < eta) 
	    tp = eta;
	  else
	    tp = relstp;
	  r1 = sqrt(tp);
	  r2 = sr*(1.0L+r1)-si*r1;
	  si = sr*r1+si*(1.0L+r1);
	  sr = r2;
	  polyev(nn,sr,si,pr,pi,qpr,qpi,&pvr,&pvi);
	  for (j=0;j<5;j++) {
	    boolvar = calct();
	    nexth(boolvar);
	  }
	  omp = infin;
	} else {
	  /* Exit if polynomial value increases significantly */
          if (mp*0.1L > omp) 
	    return conv;
	  omp = mp;
	}
      } else {
	omp = mp;
      }
    }

    /* Calculate next iterate. */
    boolvar = calct();
    nexth(boolvar);
    boolvar = calct();
    if (!boolvar) {
      relstp = cmod(tr,ti)/cmod(sr,si);
      sr += tr;
      si += ti;
    }
  }
  return conv;
}
Exemple #15
0
static int fxshft(int l2, double *zr, double *zi)
     /* Computes l2 fixed-shift h polynomials and tests for convergence

	Initiates a variable-shift iteration and returns with the
	approximate zero if successful.

	l2    - Limit of fixed shift steps
	zr,zi - Approximate zero if conv is .true.
	conv  - Flag indicating convergence of stage 3 iteration 
     */
{
  double otr,oti,svsr,svsi;
  int conv,test,pasd,boolvar;
  int i,j,n = nn-1;

  /* Evaluate p at s */
  polyev(nn,sr,si,pr,pi,qpr,qpi,&pvr,&pvi);
  test = TRUE;
  pasd = FALSE;

  /* Calculate first t = -p(s)/h(s) */
  boolvar = calct();

  /* Main loop for one second stage step */
  for (j=0;j<l2;j++) {
    otr = tr;
    oti = ti;

    /* Compute next h polynomial and new t */
    nexth(boolvar);
    boolvar = calct();
    *zr = sr+tr;
    *zi = si+ti;

    /* Test for convergence unless stage 3 has failed once or 
       this is the last h polynomial */
    if (!boolvar && test && j != l2) {
      if (cmod(tr-otr,ti-oti) < .5*cmod(*zr,*zi)) {
	if (pasd) {

	  /* The weak convergence test has been passed twice, start the
	     third stage iteration, after saving the current h polynomial
	     and shift */
	  for (i=0;i<n;i++) {
	    shr[i] = hr[i];
	    shi[i] = hi[i];
	  }
	  svsr = sr;
	  svsi = si;
	  conv = vrshft(10,zr,zi);
	  if (conv) 
	    return conv;

	  /* The iteration failed to converge
	     Turn off testing and restore h,s,pv and t */
	  test = FALSE;
	  for (i=0;i<n;i++) {
	    hr[i] = shr[i];
	    hi[i] = shi[i];
	  }
	  sr = svsr;
	  si = svsi;
	  polyev(nn,sr,si,pr,pi,qpr,qpi,&pvr,&pvi);
	  boolvar = calct();
	} else {
	  pasd = TRUE;
	}
      }
    } else {
      pasd = FALSE;
    }
  }

  /* Attempt an iteration with final h polynomial from second stage */
  conv = vrshft(10,zr,zi);
  return conv;
}
Exemple #16
0
void CPoly<T>::fxshft( const int l2, T *zr, T *zi, int *conv )
   {
   int i, j, n;
   int test, pasd, bol;
   T otr, oti, svsr, svsi;

   n = nn;
   polyev( nn, sr, si, pr, pi, qpr, qpi, &pvr, &pvi );
   test = 1;
   pasd = 0;

   // Calculate first T = -P(S)/H(S)
   calct( &bol );

   // Main loop for second stage
   for( j = 1; j <= l2; j++ )
      {
      otr = tr;
      oti = ti;

      // Compute the next H Polynomial and new t
      nexth( bol );
      calct( &bol );
      *zr = sr + tr;
      *zi = si + ti;

      // Test for convergence unless stage 3 has failed once or this
      // is the last H Polynomial
      if( !( bol || !test || j == 12 ) )
         {
         if( cmod( tr - otr, ti - oti ) < 0.5 * cmod( *zr, *zi ) )
            {
            if( pasd )
               {
               // The weak convergence test has been passed twice, start the third stage
               // Iteration, after saving the current H polynomial and shift
               for( i = 0; i < n; i++ )
                  {
                  shr[ i ] = hr[ i ];
                  shi[ i ] = hi[ i ];
                  }
               svsr = sr;
               svsi = si;
               vrshft( 10, zr, zi, conv );
               if( *conv ) return;

               //The iteration failed to converge. Turn off testing and restore h,s,pv and T
               test = 0;
               for( i = 0; i < n; i++ )
                  {
                  hr[ i ] = shr[ i ];
                  hi[ i ] = shi[ i ];
                  }
               sr = svsr;
               si = svsi;
               polyev( nn, sr, si, pr, pi, qpr, qpi, &pvr, &pvi );
               calct( &bol );
               continue;
               }
            pasd = 1;
            }
         else
            pasd = 0;
         }
      }

   // Attempt an iteration with final H polynomial from second stage
   vrshft( 10, zr, zi, conv );
   }
Exemple #17
0
/*
=====================================================================
 cw_rxprocess()
 Called with a block (512 samples) of audio.
=======================================================================
*/
int cw_rxprocess(struct trx *trx, float *buf, int len)
{
	struct cw *s = (struct cw *) trx->modem;
	fftw_complex z, *zp;
	int n, i;
	double delta;
	double value;
	char *c;

	/* check if user changed filter bandwidth */
	if (trx->bandwidth != trx->cw_bandwidth) {
		fftfilt_set_freqs(s->fftfilt, 0, trx->cw_bandwidth / 2.0 / SampleRate);
		trx->bandwidth = trx->cw_bandwidth;
	}

	/* compute phase increment expected at our specific rx tone freq */
	delta = 2.0 * M_PI * trx->frequency / SampleRate;

	while (len-- > 0) {
		/* Mix with the internal NCO */
		c_re(z) = *buf * cos(s->phaseacc);
		c_im(z) = *buf * sin(s->phaseacc);
		buf++;

		s->phaseacc += delta;

		if (s->phaseacc > M_PI)
			s->phaseacc -= 2.0 * M_PI;

		n = fftfilt_run(s->fftfilt, z, &zp);

		for (i = 0; i < n; i++) {
			/* 
			 * update the basic sample counter used for 
			 * morse timing 
			 */
			s->s_ctr++;

			/* downsample by 8 */
			if (++s->dec_ctr < DEC_RATIO)
				continue;
			else
				s->dec_ctr = 0;

			/* demodulate */
			value = cmod(zp[i]);

			/* 
			 * Compute a variable threshold value for tone 
			 * detection. Fast attack and slow decay.
			 */
			if (value > s->agc_peak)
				s->agc_peak = value;
			else
				s->agc_peak = decayavg(s->agc_peak, value, SampleRate / 10);

			/*
			 * save correlation amplitude value for the 
			 * sync scope
			 */
			s->pipe[s->pipeptr] = value;
			s->pipeptr = (s->pipeptr + 1) % MaxSymLen;
			if (s->pipeptr == MaxSymLen - 1)
				update_syncscope(s);

			if (!trx->squelchon || value > trx->cw_squelch / 5000) {
				/* upward trend means tone starting */
				if ((value > 0.66 * s->agc_peak) && 
				    (s->cw_receive_state != RS_IN_TONE))
					cw_process(trx, CW_KEYDOWN_EVENT, NULL);

				/* downward trend means tone stopping */
				if ((value < 0.33 * s->agc_peak) && 
				    (s->cw_receive_state == RS_IN_TONE))
					cw_process(trx, CW_KEYUP_EVENT, NULL);
			}

			/*
			 * We could put a gear on this... we dont really
			 * need to check for new characters being ready
			 * 1000 times/sec. There does not appear to be 
			 * much overhead the way it is.
			 */
			if (cw_process(trx, CW_QUERY_EVENT, &c) == CW_SUCCESS)
				while (*c)
					trx_put_rx_char(*c++);
		}

	}
	return 0;
}
Exemple #18
0
int
pq_sign(
    size_t              *packed_sig_len,
    unsigned char       *packed_sig,
    const size_t        private_key_len,
    const unsigned char *private_key_blob,
    const size_t        public_key_len,
    const unsigned char *public_key_blob,
    const size_t        msg_len,
    const unsigned char *msg)
{

  uint16_t i;
  int error = 0;

  uint16_t  N;
  uint16_t  padN;
  int64_t   q;
  int8_t    p;
  uint16_t  d1;
  uint16_t  d2;
  uint16_t  d3;
  int64_t   m;

  size_t        scratch_len;
  unsigned char *scratch;
  size_t        offset;

  uint16_t      *f;    /* Private key product form f indices */
  uint16_t      *g;    /* .. product form g indices */
  int64_t       *ginv; /* Private key; coefficients of g^{-1} */
  int64_t       *h;    /* Public key coefficients */
  int64_t       *s0;   /* scratch space for random lattice point */
  int64_t       *t0;

  int64_t       *a;    /* scratch space for 3 polynomials */
  int64_t       *tmpx2;/* scratch space for 2 polynomials (aliased by a) */

  int8_t        *sp;   /* Document hash */
  int8_t        *tp;


  PQ_PARAM_SET  *P;

  int rc = PQNTRU_OK;

  if(!private_key_blob || !public_key_blob || !packed_sig_len)
  {
    return PQNTRU_ERROR;
  }

  rc = get_blob_params(&P, private_key_len, private_key_blob);
  if(PQNTRU_ERROR == rc)
  {
    return PQNTRU_ERROR;
  }

  if(!packed_sig) /* Return signature size in packed_sig_len */
  {
    *packed_sig_len = SIGNATURE_BYTES(P);
    return PQNTRU_OK;
  }

  if(!msg || msg_len == 0)
  {
    return PQNTRU_ERROR;
  }

  N = P->N;
  padN = P->padded_N;
  q = P->q;
  p = P->p;
  d1 = P->d1;
  d2 = P->d2;
  d3 = P->d3;

  scratch_len = 2 * PRODUCT_FORM_BYTES(P) /* f and g */
              + 7 * POLYNOMIAL_BYTES(P)   /* h, ginv, and 5 scratch polys */
              + 2 * N;                    /* sp, tp */
  if(!(scratch = malloc(scratch_len)))
  {
    return PQNTRU_ERROR;
  }
  memset(scratch, 0, scratch_len);

  offset = 0;
  f    = (uint16_t*)(scratch);          offset += PRODUCT_FORM_BYTES(P);
  g    = (uint16_t*)(scratch + offset); offset += PRODUCT_FORM_BYTES(P);
  h    =  (int64_t*)(scratch + offset); offset += POLYNOMIAL_BYTES(P);
  ginv =  (int64_t*)(scratch + offset); offset += POLYNOMIAL_BYTES(P);
  s0   =  (int64_t*)(scratch + offset); offset += POLYNOMIAL_BYTES(P);
  t0   =  (int64_t*)(scratch + offset); offset += POLYNOMIAL_BYTES(P);
  /* a is treated as 3 polynomials, aliases tmpx2 */
  a    =  (int64_t*)(scratch + offset); offset += POLYNOMIAL_BYTES(P);
  tmpx2=  (int64_t*)(scratch + offset); offset += 2* POLYNOMIAL_BYTES(P);
  sp   =   (int8_t*)(scratch + offset); offset += N;
  tp   =   (int8_t*)(scratch + offset);


  /* Unpack the keys */
  rc = unpack_private_key(P, f, g, ginv, private_key_len, private_key_blob);
  if(PQNTRU_ERROR == rc)
  {
    shred(scratch, scratch_len);
    free(scratch);
    return PQNTRU_ERROR;
  }

  rc = unpack_public_key(P, h, public_key_len, public_key_blob);
  if(PQNTRU_ERROR == rc)
  {
    shred(scratch, scratch_len);
    free(scratch);
    return PQNTRU_ERROR;
  }


  /* Generate a document hash to sign */
  challenge(sp, tp,
            public_key_len, public_key_blob,
            msg_len, msg);

  int64_t *t = (int64_t *)malloc(N*sizeof(int64_t));
  int64_t *s = (int64_t *)malloc(N*sizeof(int64_t));

  do
  {
    error = 0;

    /* Choose random s0 satisfying s0 = sp (mod p) */
    pol_unidrnd_pZ(s0, N, q, p);
    for(i=0; i<N; i++)
    {
      s0[i] += sp[i];
    }

    /* Load h into a zero padded polynomial */
    memcpy(t0, h, N*sizeof(int64_t));

    /* t0 = h*s0 */
    pol_mul_coefficients(t0, t0, s0, N, padN, q, a);

    /* t0 = tp - (s0*h) */
    for(i=0; i<N; i++)
    {
      t0[i] *= -1;
      t0[i] += tp[i];
    }

    /* a = ginv * (tp - t0) (mod p) */
    pol_mul_coefficients(a, t0, ginv, N, padN, p, a);

    /* tmpx2 = a * F = (a * (f-1)/p) */
    pol_mul_product(tmpx2, a, d1, d2, d3, f, N, tmpx2);
    for(i=0; i<N; i++)
    {
      m = p * (a[i] + tmpx2[i]);
      error |= (m > P->B_s) || (-m > P->B_s);
      s[i] = m;
      /* s0 = s0 + p*(a + tmpx2) = s0 + a*f */
      s0[i] += m;

      error |= (cmod(s0[i], p) - sp[i]); /* Not necessary to check this */
      error |= (s0[i] > P->norm_bound_s) || (-s0[i] > P->norm_bound_s);
    }

    /* tmpx2 = a * G = (a * (g - 1)) */
    pol_mul_product(tmpx2, a, d1, d2, d3, g, N, tmpx2);
    for(i=0; i<N; i++)
    {
      m = (a[i] + tmpx2[i]);
      error |= (m > P->B_t) || (-m > P->B_t);
      t[i] = m;
      /* t0 = (a + tmpx2) - t0 + tp = a*g - tp + s0*h + tp = s0*h + a*g */
      t0[i] = m - t0[i] + tp[i];
      error |= (cmod(t0[i], p) - tp[i]); /* Not necessary to check this */
      error |= (t0[i] > P->norm_bound_t) || (-t0[i] > P->norm_bound_t) ;
    }


//    attempts ++;

  } while(0 != error);

  for (i=0; i<N; i++) {
	  if (s[i] > P->B_s || -s[i] > P->B_s)
		  printf("s\tholy shit\n");
	  if (t[i] > P->B_t || -t[i] > P->B_t)
		  printf("t\tholy shit\n");
  }

  for(i=0; i<N; i++)
  {
    s0[i] = (s0[i] - sp[i])/P->p;
    s0[i] += P->q / (2*P->p);
  }

  pack_signature(P, s0, *packed_sig_len, packed_sig);

  shred(scratch, scratch_len);
  free(scratch);

  return PQNTRU_OK;
}
Exemple #19
0
int
pq_verify(
    const size_t        packed_sig_len,
    const unsigned char *packed_sig,
    const size_t        public_key_blob_len,
    const unsigned char *public_key_blob,
    const size_t        msg_len,
    const unsigned char *msg)
{
  uint16_t      i;

  PQ_PARAM_SET  *P;
  size_t        scratch_len;
  unsigned char *scratch;
  int8_t        *sp;
  int8_t        *tp;
  int64_t       *h;
  int64_t       *sig;
  int64_t       *tmpx3;

  uint16_t      N;
  uint16_t      padN;
  int64_t       q;
  int8_t        p;
  uint16_t      error = 0;
  int           result;


  result = get_blob_params(&P, public_key_blob_len, public_key_blob);
  if(PQNTRU_ERROR == result)
  {
    return PQNTRU_ERROR;
  }

  N = P->N;
  padN = P->padded_N;
  p = P->p;
  q = P->q;

  scratch_len = 2 * N + 5 * POLYNOMIAL_BYTES(P);
  if(!(scratch = malloc(scratch_len)))
  {
    return PQNTRU_ERROR;
  }
  memset(scratch, 0, scratch_len);

  sig  = (int64_t*)scratch;
  h    = (int64_t*)(scratch + POLYNOMIAL_BYTES(P));
  tmpx3 = (int64_t*)(scratch + 2*POLYNOMIAL_BYTES(P));
  sp    =  (int8_t*)(scratch + 5*POLYNOMIAL_BYTES(P));
  tp    =  (int8_t*)(scratch + 5*POLYNOMIAL_BYTES(P) + N);

  result = unpack_public_key(P, h, public_key_blob_len, public_key_blob);
  if(PQNTRU_ERROR == result)
  {
    free(scratch);
    return PQNTRU_ERROR;
  }

  challenge(sp, tp,
            public_key_blob_len, public_key_blob,
            msg_len, msg);

  result = unpack_signature(P, sig, sp, packed_sig_len, packed_sig);
  if(PQNTRU_ERROR == result)
  {
    free(scratch);
    return PQNTRU_ERROR;
  }

  for(i=0; i<N; i++)
  {
    error |= (cmod(sig[i] - sp[i], p));
    error |= (sig[i] > P->norm_bound_s) || (-sig[i] > P->norm_bound_s);
  }
  pol_mul_coefficients(tmpx3, sig, h, N, padN, q, tmpx3);

  for(i=0; i<N; i++)
  {
    error |= (cmod(tmpx3[i], p) - tp[i]);
    error |= (tmpx3[i] > P->norm_bound_t) || (-tmpx3[i] > P->norm_bound_t) ;
  }



  free(scratch);

  if(0 == error)
  {
    return PQNTRU_OK;
  }
  return PQNTRU_ERROR;
}
Exemple #20
0
int CPoly<T>::findRoots( const T *opr, const T *opi, int degree, T *zeror, T *zeroi )
   {
   int cnt1, cnt2, idnn2, i, conv;
   T xx, yy, cosr, sinr, smalno, base, xxx, zr, zi, bnd;

   mcon( &eta, &infin, &smalno, &base );
   are = eta;
   mre = (T) (2.0 * sqrt( 2.0 ) * eta);
   xx = (T) 0.70710678;
   yy = -xx;
   cosr = (T) -0.060756474;
   sinr = (T) -0.99756405;
   nn = degree;

   // Algorithm fails if the leading coefficient is zero, or degree is zero.
   if( nn < 1 || (opr[ 0 ] == 0 && opi[ 0 ] == 0) )
      return -1;


   // Remove the zeros at the origin if any
   while( opr[ nn ] == 0 && opi[ nn ] == 0 )
      {
      idnn2 = degree - nn;
      zeror[ idnn2 ] = 0;
      zeroi[ idnn2 ] = 0;
      nn--;
      }

   // sherm 20130410: If all coefficients but the leading one were zero, then
   // all solutions are zero; should be a successful (if boring) return.
   if (nn == 0)
      return degree;

   // Allocate arrays
   pr = new T [ degree+1 ];
   pi = new T [ degree+1 ];
   hr = new T [ degree+1 ];
   hi = new T [ degree+1 ];
   qpr= new T [ degree+1 ];
   qpi= new T [ degree+1 ];
   qhr= new T [ degree+1 ];
   qhi= new T [ degree+1 ];
   shr= new T [ degree+1 ];
   shi= new T [ degree+1 ];

   // Make a copy of the coefficients
   for( i = 0; i <= nn; i++ )
      {
      pr[ i ] = opr[ i ];
      pi[ i ] = opi[ i ];
      shr[ i ] = cmod( pr[ i ], pi[ i ] );
      }

   // Scale the polynomial
   bnd = scale( nn, shr, eta, infin, smalno, base );
   if( bnd != 1 )
      for( i = 0; i <= nn; i++ )
         {
         pr[ i ] *= bnd;
         pi[ i ] *= bnd;
         }

search:
   if( nn <= 1 )
      {
      cdivid( -pr[ 1 ], -pi[ 1 ], pr[ 0 ], pi[ 0 ], &zeror[ degree-1 ], &zeroi[ degree-1 ] );
      goto finish;
      }

   // Calculate bnd, alower bound on the modulus of the zeros
   for( i = 0; i<= nn; i++ )
      shr[ i ] = cmod( pr[ i ], pi[ i ] );

   cauchy( nn, shr, shi, &bnd );

   // Outer loop to control 2 Major passes with different sequences of shifts
   for( cnt1 = 1; cnt1 <= 2; cnt1++ )
      {
      // First stage  calculation , no shift
      noshft( 5 );

      // Inner loop to select a shift
      for( cnt2 = 1; cnt2 <= 9; cnt2++ )
         {
         // Shift is chosen with modulus bnd and amplitude rotated by 94 degree from the previous shif
         xxx = cosr * xx - sinr * yy;
         yy = sinr * xx + cosr * yy;
         xx = xxx;
         sr = bnd * xx;
         si = bnd * yy;

         // Second stage calculation, fixed shift
         fxshft( 10 * cnt2, &zr, &zi, &conv );
         if( conv )
            {
            // The second stage jumps directly to the third stage ieration
            // If successful the zero is stored and the polynomial deflated
            idnn2 = degree - nn;
            zeror[ idnn2 ] = zr;
            zeroi[ idnn2 ] = zi;
            nn--;
            for( i = 0; i <= nn; i++ )
               {
               pr[ i ] = qpr[ i ];
               pi[ i ] = qpi[ i ];
               }
            goto search;
            }
         // If the iteration is unsuccessful another shift is chosen
         }
      // if 9 shifts fail, the outer loop is repeated with another sequence of shifts
      }

   // The zerofinder has failed on two major passes
   // return empty handed with the number of roots found (less than the original degree)
   degree -= nn;

finish:
   // Deallocate arrays
   delete [] pr;
   delete [] pi;
   delete [] hr;
   delete [] hi;
   delete [] qpr;
   delete [] qpi;
   delete [] qhr;
   delete [] qhi;
   delete [] shr;
   delete [] shi;

   return degree;
   }
Exemple #21
0
int cpoly(double opr[], double opi[], int degree,
	   double zeror[], double zeroi[])
{
  /* Finds the zeros of a complex polynomial.

     opr, opi - double precision vectors of real and imaginary parts 
                of the coefficients in order of decreasing powers.
     degree   - integer degree of polynomial
     zeror, zeroi  
              - output double precision vectors of real and imaginary 
	        parts of the zeros.
     fail     - output logical parameter, TRUE if leading coefficient 
                is zero, if cpoly has found fewer than degree zeros,
                or if there is another internal error.

     The program has been written to reduce the chance of overflow
     occurring.  If it does occur, there is still a possibility that
     the zerofinder will work provided the overflowed quantity is
     replaced by a large number. */
  
  double xx,yy,xxx,zr,zi,bnd;
  int fail,conv;
  int cnt1,cnt2,i,idnn2;

  /* initialization of constants */
  nn = degree+1;
  if (!init(nn)) {
    fail = TRUE;
    return fail;
  }

  xx = .70710678L;
  yy = -xx;
  fail = FALSE;

  /* algorithm fails if the leading coefficient is zero. */
  if (opr[0] == 0.0 && opi[0] == 0.0) {
    fail = TRUE;
    return fail;
  }

  /* Remove the zeros at the origin if any */
  while (opr[nn-1] == 0.0 && opi[nn-1] == 0.0) {
    idnn2 = degree+1-nn;
    zeror[idnn2] = 0.0;
    zeroi[idnn2] = 0.0;
    nn--;
  }

  /* Make a copy of the coefficients */
  for (i=0;i<nn;i++) {
    pr[i] = opr[i];
    pi[i] = opi[i];
    shr[i] = cmod(pr[i],pi[i]);
  }

  /* Scale the polynomial */
  bnd = scale(nn,shr);
  if (bnd != 1.0) {
    for (i=0;i<nn;i++) {
      pr[i] *= bnd;
      pi[i] *= bnd;
    }
  }

  while (!fail) {

    /* Start the algorithm for one zero */
    if (nn < 3) {
      /* Calculate the final zero and return */
      cdivid(-pr[1],-pi[1],pr[0],pi[0],&(zeror[degree-1]),&(zeroi[degree-1]));
      return fail;
    }

    /* Calculate bnd, a lower bound on the modulus of the zeros */
    for (i=0;i<nn;i++) {
      shr[i] = cmod(pr[i],pi[i]);
    }
    bnd = cauchy(nn,shr,shi);

    /* Outer loop to control 2 major passes with different sequences
       of shifts */
    fail = TRUE;
    for(cnt1=1;fail && (cnt1<=2);cnt1++) {

      /* First stage calculation, no shift */
      noshft(5);

      /* Inner loop to select a shift. */
      for (cnt2=1;fail && (cnt2<10);cnt2++) {
	/* Shift is chosen with modulus bnd and amplitude rotated by
	   94 degrees from the previous shift */
	xxx = COSR*xx-SINR*yy;
	yy  = SINR*xx+COSR*yy;
	xx  = xxx;
	sr  = bnd*xx;
	si  = bnd*yy;

	/* Second stage calculation, fixed shift */
	conv = fxshft(10*cnt2,&zr,&zi);
	if (conv) {

	  /* The second stage jumps directly to the third stage iteration
	     If successful the zero is stored and the polynomial deflated */
	  idnn2 = degree+1-nn;
	  zeror[idnn2] = zr;
	  zeroi[idnn2] = zi;
	  nn--;
	  for(i=0;i<nn;i++) {
	    pr[i] = qpr[i];
	    pi[i] = qpi[i];
	  }
	  fail = FALSE;
	}
	/* If the iteration is unsuccessful another shift is chosen */
      }
      /* If 9 shifts fail, the outer loop is repeated with another
	 sequence of shifts */
    }
  }

  /* The zerofinder has failed on two major passes
     Return empty handed */
  return fail;
}