Add cyclic group abstraction, with test code. Separate off exponentation
[u/mdw/catacomb] / mpbarrett-mexp.c
index e97c064..68917aa 100644 (file)
@@ -1,6 +1,6 @@
 /* -*-c-*-
  *
- * $Id: mpbarrett-mexp.c,v 1.1 2001/06/16 12:58:34 mdw Exp $
+ * $Id: mpbarrett-mexp.c,v 1.2 2004/04/01 12:50:09 mdw Exp $
  *
  * Multiple simultaneous exponentiations
  *
 /*----- Revision history --------------------------------------------------* 
  *
  * $Log: mpbarrett-mexp.c,v $
+ * Revision 1.2  2004/04/01 12:50:09  mdw
+ * Add cyclic group abstraction, with test code.  Separate off exponentation
+ * functions for better static linking.  Fix a buttload of bugs on the way.
+ * Generally ensure that negative exponents do inversion correctly.  Add
+ * table of standard prime-field subgroups.  (Binary field subgroups are
+ * currently unimplemented but easy to add if anyone ever finds a good one.)
+ *
  * Revision 1.1  2001/06/16 12:58:34  mdw
  * Added simultaneous exponentiation with Barrett reduction.
  *
@@ -49,7 +56,7 @@
  *
  * Arguments:  @mpbarrett *mb@ = pointer to Barrett reduction context
  *             @mp *d@ = fake destination
- *             @mp_expfactor *f@ = pointer to array of factors
+ *             @const mp_expfactor *f@ = pointer to array of factors
  *             @size_t n@ = number of factors supplied
  *
  * Returns:    If the bases are %$g_0, g_1, \ldots, g_{n-1}$% and the
  *             %$g_0^{e_0} g_1^{e_1} \ldots g_{n-1}^{e_{n-1}} \bmod m$%
  */
 
-mp *mpbarrett_mexp(mpbarrett *mb, mp *d, mp_expfactor *f, size_t n)
+mp *mpbarrett_mexp(mpbarrett *mb, mp *d, const mp_expfactor *f, size_t n)
 {
+  mp_expfactor *ff = xmalloc(n * sizeof(mp_expfactor));
   mp *a = MP_ONE;
   mp *spare;
+  mp *g = MP_NEW;
   size_t i;
 
   spare = MP_NEW;
   for (i = 0; i < n; i++) {
-    if (f[i].exp->f & MP_BURN) {
+    if (f[i].exp->f & MP_BURN)
       spare = MP_NEWSEC;
-      break;
+    if (!(f[i].exp->f & MP_NEG))
+      ff[i].base = MP_COPY(f[i].base);
+    else {
+      ff[i].base = MP_NEW;
+      mp_gcd(&g, 0, &ff[i].base, mb->m, f[i].base);
+      assert(MP_EQ(g, MP_ONE));
     }
+    ff[i].exp = f[i].exp;
   }
-
-  EXP_SIMUL(a, f, n);
+  mp_drop(g);
+  EXP_SIMUL(a, ff, n);
   mp_drop(d);
   mp_drop(spare);
+  for (i = 0; i < n; i++)
+    mp_drop(ff[i].base);
+  xfree(ff);
   return (a);
 }