OSDN Git Service

Add PuTTY 0.61 to contrib directory.
[ffftp/ffftp.git] / contrib / putty / SSHBN.C
diff --git a/contrib/putty/SSHBN.C b/contrib/putty/SSHBN.C
new file mode 100644 (file)
index 0000000..51cecdf
--- /dev/null
@@ -0,0 +1,1918 @@
+/*\r
+ * Bignum routines for RSA and DH and stuff.\r
+ */\r
+\r
+#include <stdio.h>\r
+#include <assert.h>\r
+#include <stdlib.h>\r
+#include <string.h>\r
+\r
+#include "misc.h"\r
+\r
+/*\r
+ * Usage notes:\r
+ *  * Do not call the DIVMOD_WORD macro with expressions such as array\r
+ *    subscripts, as some implementations object to this (see below).\r
+ *  * Note that none of the division methods below will cope if the\r
+ *    quotient won't fit into BIGNUM_INT_BITS. Callers should be careful\r
+ *    to avoid this case.\r
+ *    If this condition occurs, in the case of the x86 DIV instruction,\r
+ *    an overflow exception will occur, which (according to a correspondent)\r
+ *    will manifest on Windows as something like\r
+ *      0xC0000095: Integer overflow\r
+ *    The C variant won't give the right answer, either.\r
+ */\r
+\r
+#if defined __GNUC__ && defined __i386__\r
+typedef unsigned long BignumInt;\r
+typedef unsigned long long BignumDblInt;\r
+#define BIGNUM_INT_MASK  0xFFFFFFFFUL\r
+#define BIGNUM_TOP_BIT   0x80000000UL\r
+#define BIGNUM_INT_BITS  32\r
+#define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)\r
+#define DIVMOD_WORD(q, r, hi, lo, w) \\r
+    __asm__("div %2" : \\r
+           "=d" (r), "=a" (q) : \\r
+           "r" (w), "d" (hi), "a" (lo))\r
+#elif defined _MSC_VER && defined _M_IX86\r
+typedef unsigned __int32 BignumInt;\r
+typedef unsigned __int64 BignumDblInt;\r
+#define BIGNUM_INT_MASK  0xFFFFFFFFUL\r
+#define BIGNUM_TOP_BIT   0x80000000UL\r
+#define BIGNUM_INT_BITS  32\r
+#define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)\r
+/* Note: MASM interprets array subscripts in the macro arguments as\r
+ * assembler syntax, which gives the wrong answer. Don't supply them.\r
+ * <http://msdn2.microsoft.com/en-us/library/bf1dw62z.aspx> */\r
+#define DIVMOD_WORD(q, r, hi, lo, w) do { \\r
+    __asm mov edx, hi \\r
+    __asm mov eax, lo \\r
+    __asm div w \\r
+    __asm mov r, edx \\r
+    __asm mov q, eax \\r
+} while(0)\r
+#elif defined _LP64\r
+/* 64-bit architectures can do 32x32->64 chunks at a time */\r
+typedef unsigned int BignumInt;\r
+typedef unsigned long BignumDblInt;\r
+#define BIGNUM_INT_MASK  0xFFFFFFFFU\r
+#define BIGNUM_TOP_BIT   0x80000000U\r
+#define BIGNUM_INT_BITS  32\r
+#define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)\r
+#define DIVMOD_WORD(q, r, hi, lo, w) do { \\r
+    BignumDblInt n = (((BignumDblInt)hi) << BIGNUM_INT_BITS) | lo; \\r
+    q = n / w; \\r
+    r = n % w; \\r
+} while (0)\r
+#elif defined _LLP64\r
+/* 64-bit architectures in which unsigned long is 32 bits, not 64 */\r
+typedef unsigned long BignumInt;\r
+typedef unsigned long long BignumDblInt;\r
+#define BIGNUM_INT_MASK  0xFFFFFFFFUL\r
+#define BIGNUM_TOP_BIT   0x80000000UL\r
+#define BIGNUM_INT_BITS  32\r
+#define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)\r
+#define DIVMOD_WORD(q, r, hi, lo, w) do { \\r
+    BignumDblInt n = (((BignumDblInt)hi) << BIGNUM_INT_BITS) | lo; \\r
+    q = n / w; \\r
+    r = n % w; \\r
+} while (0)\r
+#else\r
+/* Fallback for all other cases */\r
+typedef unsigned short BignumInt;\r
+typedef unsigned long BignumDblInt;\r
+#define BIGNUM_INT_MASK  0xFFFFU\r
+#define BIGNUM_TOP_BIT   0x8000U\r
+#define BIGNUM_INT_BITS  16\r
+#define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)\r
+#define DIVMOD_WORD(q, r, hi, lo, w) do { \\r
+    BignumDblInt n = (((BignumDblInt)hi) << BIGNUM_INT_BITS) | lo; \\r
+    q = n / w; \\r
+    r = n % w; \\r
+} while (0)\r
+#endif\r
+\r
+#define BIGNUM_INT_BYTES (BIGNUM_INT_BITS / 8)\r
+\r
+#define BIGNUM_INTERNAL\r
+typedef BignumInt *Bignum;\r
+\r
+#include "ssh.h"\r
+\r
+BignumInt bnZero[1] = { 0 };\r
+BignumInt bnOne[2] = { 1, 1 };\r
+\r
+/*\r
+ * The Bignum format is an array of `BignumInt'. The first\r
+ * element of the array counts the remaining elements. The\r
+ * remaining elements express the actual number, base 2^BIGNUM_INT_BITS, _least_\r
+ * significant digit first. (So it's trivial to extract the bit\r
+ * with value 2^n for any n.)\r
+ *\r
+ * All Bignums in this module are positive. Negative numbers must\r
+ * be dealt with outside it.\r
+ *\r
+ * INVARIANT: the most significant word of any Bignum must be\r
+ * nonzero.\r
+ */\r
+\r
+Bignum Zero = bnZero, One = bnOne;\r
+\r
+static Bignum newbn(int length)\r
+{\r
+    Bignum b = snewn(length + 1, BignumInt);\r
+    if (!b)\r
+       abort();                       /* FIXME */\r
+    memset(b, 0, (length + 1) * sizeof(*b));\r
+    b[0] = length;\r
+    return b;\r
+}\r
+\r
+void bn_restore_invariant(Bignum b)\r
+{\r
+    while (b[0] > 1 && b[b[0]] == 0)\r
+       b[0]--;\r
+}\r
+\r
+Bignum copybn(Bignum orig)\r
+{\r
+    Bignum b = snewn(orig[0] + 1, BignumInt);\r
+    if (!b)\r
+       abort();                       /* FIXME */\r
+    memcpy(b, orig, (orig[0] + 1) * sizeof(*b));\r
+    return b;\r
+}\r
+\r
+void freebn(Bignum b)\r
+{\r
+    /*\r
+     * Burn the evidence, just in case.\r
+     */\r
+    memset(b, 0, sizeof(b[0]) * (b[0] + 1));\r
+    sfree(b);\r
+}\r
+\r
+Bignum bn_power_2(int n)\r
+{\r
+    Bignum ret = newbn(n / BIGNUM_INT_BITS + 1);\r
+    bignum_set_bit(ret, n, 1);\r
+    return ret;\r
+}\r
+\r
+/*\r
+ * Internal addition. Sets c = a - b, where 'a', 'b' and 'c' are all\r
+ * big-endian arrays of 'len' BignumInts. Returns a BignumInt carried\r
+ * off the top.\r
+ */\r
+static BignumInt internal_add(const BignumInt *a, const BignumInt *b,\r
+                              BignumInt *c, int len)\r
+{\r
+    int i;\r
+    BignumDblInt carry = 0;\r
+\r
+    for (i = len-1; i >= 0; i--) {\r
+        carry += (BignumDblInt)a[i] + b[i];\r
+        c[i] = (BignumInt)carry;\r
+        carry >>= BIGNUM_INT_BITS;\r
+    }\r
+\r
+    return (BignumInt)carry;\r
+}\r
+\r
+/*\r
+ * Internal subtraction. Sets c = a - b, where 'a', 'b' and 'c' are\r
+ * all big-endian arrays of 'len' BignumInts. Any borrow from the top\r
+ * is ignored.\r
+ */\r
+static void internal_sub(const BignumInt *a, const BignumInt *b,\r
+                         BignumInt *c, int len)\r
+{\r
+    int i;\r
+    BignumDblInt carry = 1;\r
+\r
+    for (i = len-1; i >= 0; i--) {\r
+        carry += (BignumDblInt)a[i] + (b[i] ^ BIGNUM_INT_MASK);\r
+        c[i] = (BignumInt)carry;\r
+        carry >>= BIGNUM_INT_BITS;\r
+    }\r
+}\r
+\r
+/*\r
+ * Compute c = a * b.\r
+ * Input is in the first len words of a and b.\r
+ * Result is returned in the first 2*len words of c.\r
+ *\r
+ * 'scratch' must point to an array of BignumInt of size at least\r
+ * mul_compute_scratch(len). (This covers the needs of internal_mul\r
+ * and all its recursive calls to itself.)\r
+ */\r
+#define KARATSUBA_THRESHOLD 50\r
+static int mul_compute_scratch(int len)\r
+{\r
+    int ret = 0;\r
+    while (len > KARATSUBA_THRESHOLD) {\r
+        int toplen = len/2, botlen = len - toplen; /* botlen is the bigger */\r
+        int midlen = botlen + 1;\r
+        ret += 4*midlen;\r
+        len = midlen;\r
+    }\r
+    return ret;\r
+}\r
+static void internal_mul(const BignumInt *a, const BignumInt *b,\r
+                        BignumInt *c, int len, BignumInt *scratch)\r
+{\r
+    if (len > KARATSUBA_THRESHOLD) {\r
+        int i;\r
+\r
+        /*\r
+         * Karatsuba divide-and-conquer algorithm. Cut each input in\r
+         * half, so that it's expressed as two big 'digits' in a giant\r
+         * base D:\r
+         *\r
+         *   a = a_1 D + a_0\r
+         *   b = b_1 D + b_0\r
+         *\r
+         * Then the product is of course\r
+         *\r
+         *  ab = a_1 b_1 D^2 + (a_1 b_0 + a_0 b_1) D + a_0 b_0\r
+         *\r
+         * and we compute the three coefficients by recursively\r
+         * calling ourself to do half-length multiplications.\r
+         *\r
+         * The clever bit that makes this worth doing is that we only\r
+         * need _one_ half-length multiplication for the central\r
+         * coefficient rather than the two that it obviouly looks\r
+         * like, because we can use a single multiplication to compute\r
+         *\r
+         *   (a_1 + a_0) (b_1 + b_0) = a_1 b_1 + a_1 b_0 + a_0 b_1 + a_0 b_0\r
+         *\r
+         * and then we subtract the other two coefficients (a_1 b_1\r
+         * and a_0 b_0) which we were computing anyway.\r
+         *\r
+         * Hence we get to multiply two numbers of length N in about\r
+         * three times as much work as it takes to multiply numbers of\r
+         * length N/2, which is obviously better than the four times\r
+         * as much work it would take if we just did a long\r
+         * conventional multiply.\r
+         */\r
+\r
+        int toplen = len/2, botlen = len - toplen; /* botlen is the bigger */\r
+        int midlen = botlen + 1;\r
+        BignumDblInt carry;\r
+#ifdef KARA_DEBUG\r
+        int i;\r
+#endif\r
+\r
+        /*\r
+         * The coefficients a_1 b_1 and a_0 b_0 just avoid overlapping\r
+         * in the output array, so we can compute them immediately in\r
+         * place.\r
+         */\r
+\r
+#ifdef KARA_DEBUG\r
+        printf("a1,a0 = 0x");\r
+        for (i = 0; i < len; i++) {\r
+            if (i == toplen) printf(", 0x");\r
+            printf("%0*x", BIGNUM_INT_BITS/4, a[i]);\r
+        }\r
+        printf("\n");\r
+        printf("b1,b0 = 0x");\r
+        for (i = 0; i < len; i++) {\r
+            if (i == toplen) printf(", 0x");\r
+            printf("%0*x", BIGNUM_INT_BITS/4, b[i]);\r
+        }\r
+        printf("\n");\r
+#endif\r
+\r
+        /* a_1 b_1 */\r
+        internal_mul(a, b, c, toplen, scratch);\r
+#ifdef KARA_DEBUG\r
+        printf("a1b1 = 0x");\r
+        for (i = 0; i < 2*toplen; i++) {\r
+            printf("%0*x", BIGNUM_INT_BITS/4, c[i]);\r
+        }\r
+        printf("\n");\r
+#endif\r
+\r
+        /* a_0 b_0 */\r
+        internal_mul(a + toplen, b + toplen, c + 2*toplen, botlen, scratch);\r
+#ifdef KARA_DEBUG\r
+        printf("a0b0 = 0x");\r
+        for (i = 0; i < 2*botlen; i++) {\r
+            printf("%0*x", BIGNUM_INT_BITS/4, c[2*toplen+i]);\r
+        }\r
+        printf("\n");\r
+#endif\r
+\r
+        /* Zero padding. midlen exceeds toplen by at most 2, so just\r
+         * zero the first two words of each input and the rest will be\r
+         * copied over. */\r
+        scratch[0] = scratch[1] = scratch[midlen] = scratch[midlen+1] = 0;\r
+\r
+        for (i = 0; i < toplen; i++) {\r
+            scratch[midlen - toplen + i] = a[i]; /* a_1 */\r
+            scratch[2*midlen - toplen + i] = b[i]; /* b_1 */\r
+        }\r
+\r
+        /* compute a_1 + a_0 */\r
+        scratch[0] = internal_add(scratch+1, a+toplen, scratch+1, botlen);\r
+#ifdef KARA_DEBUG\r
+        printf("a1plusa0 = 0x");\r
+        for (i = 0; i < midlen; i++) {\r
+            printf("%0*x", BIGNUM_INT_BITS/4, scratch[i]);\r
+        }\r
+        printf("\n");\r
+#endif\r
+        /* compute b_1 + b_0 */\r
+        scratch[midlen] = internal_add(scratch+midlen+1, b+toplen,\r
+                                       scratch+midlen+1, botlen);\r
+#ifdef KARA_DEBUG\r
+        printf("b1plusb0 = 0x");\r
+        for (i = 0; i < midlen; i++) {\r
+            printf("%0*x", BIGNUM_INT_BITS/4, scratch[midlen+i]);\r
+        }\r
+        printf("\n");\r
+#endif\r
+\r
+        /*\r
+         * Now we can do the third multiplication.\r
+         */\r
+        internal_mul(scratch, scratch + midlen, scratch + 2*midlen, midlen,\r
+                     scratch + 4*midlen);\r
+#ifdef KARA_DEBUG\r
+        printf("a1plusa0timesb1plusb0 = 0x");\r
+        for (i = 0; i < 2*midlen; i++) {\r
+            printf("%0*x", BIGNUM_INT_BITS/4, scratch[2*midlen+i]);\r
+        }\r
+        printf("\n");\r
+#endif\r
+\r
+        /*\r
+         * Now we can reuse the first half of 'scratch' to compute the\r
+         * sum of the outer two coefficients, to subtract from that\r
+         * product to obtain the middle one.\r
+         */\r
+        scratch[0] = scratch[1] = scratch[2] = scratch[3] = 0;\r
+        for (i = 0; i < 2*toplen; i++)\r
+            scratch[2*midlen - 2*toplen + i] = c[i];\r
+        scratch[1] = internal_add(scratch+2, c + 2*toplen,\r
+                                  scratch+2, 2*botlen);\r
+#ifdef KARA_DEBUG\r
+        printf("a1b1plusa0b0 = 0x");\r
+        for (i = 0; i < 2*midlen; i++) {\r
+            printf("%0*x", BIGNUM_INT_BITS/4, scratch[i]);\r
+        }\r
+        printf("\n");\r
+#endif\r
+\r
+        internal_sub(scratch + 2*midlen, scratch,\r
+                     scratch + 2*midlen, 2*midlen);\r
+#ifdef KARA_DEBUG\r
+        printf("a1b0plusa0b1 = 0x");\r
+        for (i = 0; i < 2*midlen; i++) {\r
+            printf("%0*x", BIGNUM_INT_BITS/4, scratch[2*midlen+i]);\r
+        }\r
+        printf("\n");\r
+#endif\r
+\r
+        /*\r
+         * And now all we need to do is to add that middle coefficient\r
+         * back into the output. We may have to propagate a carry\r
+         * further up the output, but we can be sure it won't\r
+         * propagate right the way off the top.\r
+         */\r
+        carry = internal_add(c + 2*len - botlen - 2*midlen,\r
+                             scratch + 2*midlen,\r
+                             c + 2*len - botlen - 2*midlen, 2*midlen);\r
+        i = 2*len - botlen - 2*midlen - 1;\r
+        while (carry) {\r
+            assert(i >= 0);\r
+            carry += c[i];\r
+            c[i] = (BignumInt)carry;\r
+            carry >>= BIGNUM_INT_BITS;\r
+            i--;\r
+        }\r
+#ifdef KARA_DEBUG\r
+        printf("ab = 0x");\r
+        for (i = 0; i < 2*len; i++) {\r
+            printf("%0*x", BIGNUM_INT_BITS/4, c[i]);\r
+        }\r
+        printf("\n");\r
+#endif\r
+\r
+    } else {\r
+        int i;\r
+        BignumInt carry;\r
+        BignumDblInt t;\r
+        const BignumInt *ap, *bp;\r
+        BignumInt *cp, *cps;\r
+\r
+        /*\r
+         * Multiply in the ordinary O(N^2) way.\r
+         */\r
+\r
+        for (i = 0; i < 2 * len; i++)\r
+            c[i] = 0;\r
+\r
+        for (cps = c + 2*len, ap = a + len; ap-- > a; cps--) {\r
+            carry = 0;\r
+            for (cp = cps, bp = b + len; cp--, bp-- > b ;) {\r
+                t = (MUL_WORD(*ap, *bp) + carry) + *cp;\r
+                *cp = (BignumInt) t;\r
+                carry = (BignumInt)(t >> BIGNUM_INT_BITS);\r
+            }\r
+            *cp = carry;\r
+        }\r
+    }\r
+}\r
+\r
+/*\r
+ * Variant form of internal_mul used for the initial step of\r
+ * Montgomery reduction. Only bothers outputting 'len' words\r
+ * (everything above that is thrown away).\r
+ */\r
+static void internal_mul_low(const BignumInt *a, const BignumInt *b,\r
+                             BignumInt *c, int len, BignumInt *scratch)\r
+{\r
+    if (len > KARATSUBA_THRESHOLD) {\r
+        int i;\r
+\r
+        /*\r
+         * Karatsuba-aware version of internal_mul_low. As before, we\r
+         * express each input value as a shifted combination of two\r
+         * halves:\r
+         *\r
+         *   a = a_1 D + a_0\r
+         *   b = b_1 D + b_0\r
+         *\r
+         * Then the full product is, as before,\r
+         *\r
+         *  ab = a_1 b_1 D^2 + (a_1 b_0 + a_0 b_1) D + a_0 b_0\r
+         *\r
+         * Provided we choose D on the large side (so that a_0 and b_0\r
+         * are _at least_ as long as a_1 and b_1), we don't need the\r
+         * topmost term at all, and we only need half of the middle\r
+         * term. So there's no point in doing the proper Karatsuba\r
+         * optimisation which computes the middle term using the top\r
+         * one, because we'd take as long computing the top one as\r
+         * just computing the middle one directly.\r
+         *\r
+         * So instead, we do a much more obvious thing: we call the\r
+         * fully optimised internal_mul to compute a_0 b_0, and we\r
+         * recursively call ourself to compute the _bottom halves_ of\r
+         * a_1 b_0 and a_0 b_1, each of which we add into the result\r
+         * in the obvious way.\r
+         *\r
+         * In other words, there's no actual Karatsuba _optimisation_\r
+         * in this function; the only benefit in doing it this way is\r
+         * that we call internal_mul proper for a large part of the\r
+         * work, and _that_ can optimise its operation.\r
+         */\r
+\r
+        int toplen = len/2, botlen = len - toplen; /* botlen is the bigger */\r
+\r
+        /*\r
+         * Scratch space for the various bits and pieces we're going\r
+         * to be adding together: we need botlen*2 words for a_0 b_0\r
+         * (though we may end up throwing away its topmost word), and\r
+         * toplen words for each of a_1 b_0 and a_0 b_1. That adds up\r
+         * to exactly 2*len.\r
+         */\r
+\r
+        /* a_0 b_0 */\r
+        internal_mul(a + toplen, b + toplen, scratch + 2*toplen, botlen,\r
+                     scratch + 2*len);\r
+\r
+        /* a_1 b_0 */\r
+        internal_mul_low(a, b + len - toplen, scratch + toplen, toplen,\r
+                         scratch + 2*len);\r
+\r
+        /* a_0 b_1 */\r
+        internal_mul_low(a + len - toplen, b, scratch, toplen,\r
+                         scratch + 2*len);\r
+\r
+        /* Copy the bottom half of the big coefficient into place */\r
+        for (i = 0; i < botlen; i++)\r
+            c[toplen + i] = scratch[2*toplen + botlen + i];\r
+\r
+        /* Add the two small coefficients, throwing away the returned carry */\r
+        internal_add(scratch, scratch + toplen, scratch, toplen);\r
+\r
+        /* And add that to the large coefficient, leaving the result in c. */\r
+        internal_add(scratch, scratch + 2*toplen + botlen - toplen,\r
+                     c, toplen);\r
+\r
+    } else {\r
+        int i;\r
+        BignumInt carry;\r
+        BignumDblInt t;\r
+        const BignumInt *ap, *bp;\r
+        BignumInt *cp, *cps;\r
+\r
+        /*\r
+         * Multiply in the ordinary O(N^2) way.\r
+         */\r
+\r
+        for (i = 0; i < len; i++)\r
+            c[i] = 0;\r
+\r
+        for (cps = c + len, ap = a + len; ap-- > a; cps--) {\r
+            carry = 0;\r
+            for (cp = cps, bp = b + len; bp--, cp-- > c ;) {\r
+                t = (MUL_WORD(*ap, *bp) + carry) + *cp;\r
+                *cp = (BignumInt) t;\r
+                carry = (BignumInt)(t >> BIGNUM_INT_BITS);\r
+            }\r
+        }\r
+    }\r
+}\r
+\r
+/*\r
+ * Montgomery reduction. Expects x to be a big-endian array of 2*len\r
+ * BignumInts whose value satisfies 0 <= x < rn (where r = 2^(len *\r
+ * BIGNUM_INT_BITS) is the Montgomery base). Returns in the same array\r
+ * a value x' which is congruent to xr^{-1} mod n, and satisfies 0 <=\r
+ * x' < n.\r
+ *\r
+ * 'n' and 'mninv' should be big-endian arrays of 'len' BignumInts\r
+ * each, containing respectively n and the multiplicative inverse of\r
+ * -n mod r.\r
+ *\r
+ * 'tmp' is an array of BignumInt used as scratch space, of length at\r
+ * least 3*len + mul_compute_scratch(len).\r
+ */\r
+static void monty_reduce(BignumInt *x, const BignumInt *n,\r
+                         const BignumInt *mninv, BignumInt *tmp, int len)\r
+{\r
+    int i;\r
+    BignumInt carry;\r
+\r
+    /*\r
+     * Multiply x by (-n)^{-1} mod r. This gives us a value m such\r
+     * that mn is congruent to -x mod r. Hence, mn+x is an exact\r
+     * multiple of r, and is also (obviously) congruent to x mod n.\r
+     */\r
+    internal_mul_low(x + len, mninv, tmp, len, tmp + 3*len);\r
+\r
+    /*\r
+     * Compute t = (mn+x)/r in ordinary, non-modular, integer\r
+     * arithmetic. By construction this is exact, and is congruent mod\r
+     * n to x * r^{-1}, i.e. the answer we want.\r
+     *\r
+     * The following multiply leaves that answer in the _most_\r
+     * significant half of the 'x' array, so then we must shift it\r
+     * down.\r
+     */\r
+    internal_mul(tmp, n, tmp+len, len, tmp + 3*len);\r
+    carry = internal_add(x, tmp+len, x, 2*len);\r
+    for (i = 0; i < len; i++)\r
+        x[len + i] = x[i], x[i] = 0;\r
+\r
+    /*\r
+     * Reduce t mod n. This doesn't require a full-on division by n,\r
+     * but merely a test and single optional subtraction, since we can\r
+     * show that 0 <= t < 2n.\r
+     *\r
+     * Proof:\r
+     *  + we computed m mod r, so 0 <= m < r.\r
+     *  + so 0 <= mn < rn, obviously\r
+     *  + hence we only need 0 <= x < rn to guarantee that 0 <= mn+x < 2rn\r
+     *  + yielding 0 <= (mn+x)/r < 2n as required.\r
+     */\r
+    if (!carry) {\r
+        for (i = 0; i < len; i++)\r
+            if (x[len + i] != n[i])\r
+                break;\r
+    }\r
+    if (carry || i >= len || x[len + i] > n[i])\r
+        internal_sub(x+len, n, x+len, len);\r
+}\r
+\r
+static void internal_add_shifted(BignumInt *number,\r
+                                unsigned n, int shift)\r
+{\r
+    int word = 1 + (shift / BIGNUM_INT_BITS);\r
+    int bshift = shift % BIGNUM_INT_BITS;\r
+    BignumDblInt addend;\r
+\r
+    addend = (BignumDblInt)n << bshift;\r
+\r
+    while (addend) {\r
+       addend += number[word];\r
+       number[word] = (BignumInt) addend & BIGNUM_INT_MASK;\r
+       addend >>= BIGNUM_INT_BITS;\r
+       word++;\r
+    }\r
+}\r
+\r
+/*\r
+ * Compute a = a % m.\r
+ * Input in first alen words of a and first mlen words of m.\r
+ * Output in first alen words of a\r
+ * (of which first alen-mlen words will be zero).\r
+ * The MSW of m MUST have its high bit set.\r
+ * Quotient is accumulated in the `quotient' array, which is a Bignum\r
+ * rather than the internal bigendian format. Quotient parts are shifted\r
+ * left by `qshift' before adding into quot.\r
+ */\r
+static void internal_mod(BignumInt *a, int alen,\r
+                        BignumInt *m, int mlen,\r
+                        BignumInt *quot, int qshift)\r
+{\r
+    BignumInt m0, m1;\r
+    unsigned int h;\r
+    int i, k;\r
+\r
+    m0 = m[0];\r
+    if (mlen > 1)\r
+       m1 = m[1];\r
+    else\r
+       m1 = 0;\r
+\r
+    for (i = 0; i <= alen - mlen; i++) {\r
+       BignumDblInt t;\r
+       unsigned int q, r, c, ai1;\r
+\r
+       if (i == 0) {\r
+           h = 0;\r
+       } else {\r
+           h = a[i - 1];\r
+           a[i - 1] = 0;\r
+       }\r
+\r
+       if (i == alen - 1)\r
+           ai1 = 0;\r
+       else\r
+           ai1 = a[i + 1];\r
+\r
+       /* Find q = h:a[i] / m0 */\r
+       if (h >= m0) {\r
+           /*\r
+            * Special case.\r
+            * \r
+            * To illustrate it, suppose a BignumInt is 8 bits, and\r
+            * we are dividing (say) A1:23:45:67 by A1:B2:C3. Then\r
+            * our initial division will be 0xA123 / 0xA1, which\r
+            * will give a quotient of 0x100 and a divide overflow.\r
+            * However, the invariants in this division algorithm\r
+            * are not violated, since the full number A1:23:... is\r
+            * _less_ than the quotient prefix A1:B2:... and so the\r
+            * following correction loop would have sorted it out.\r
+            * \r
+            * In this situation we set q to be the largest\r
+            * quotient we _can_ stomach (0xFF, of course).\r
+            */\r
+           q = BIGNUM_INT_MASK;\r
+       } else {\r
+           /* Macro doesn't want an array subscript expression passed\r
+            * into it (see definition), so use a temporary. */\r
+           BignumInt tmplo = a[i];\r
+           DIVMOD_WORD(q, r, h, tmplo, m0);\r
+\r
+           /* Refine our estimate of q by looking at\r
+            h:a[i]:a[i+1] / m0:m1 */\r
+           t = MUL_WORD(m1, q);\r
+           if (t > ((BignumDblInt) r << BIGNUM_INT_BITS) + ai1) {\r
+               q--;\r
+               t -= m1;\r
+               r = (r + m0) & BIGNUM_INT_MASK;     /* overflow? */\r
+               if (r >= (BignumDblInt) m0 &&\r
+                   t > ((BignumDblInt) r << BIGNUM_INT_BITS) + ai1) q--;\r
+           }\r
+       }\r
+\r
+       /* Subtract q * m from a[i...] */\r
+       c = 0;\r
+       for (k = mlen - 1; k >= 0; k--) {\r
+           t = MUL_WORD(q, m[k]);\r
+           t += c;\r
+           c = (unsigned)(t >> BIGNUM_INT_BITS);\r
+           if ((BignumInt) t > a[i + k])\r
+               c++;\r
+           a[i + k] -= (BignumInt) t;\r
+       }\r
+\r
+       /* Add back m in case of borrow */\r
+       if (c != h) {\r
+           t = 0;\r
+           for (k = mlen - 1; k >= 0; k--) {\r
+               t += m[k];\r
+               t += a[i + k];\r
+               a[i + k] = (BignumInt) t;\r
+               t = t >> BIGNUM_INT_BITS;\r
+           }\r
+           q--;\r
+       }\r
+       if (quot)\r
+           internal_add_shifted(quot, q, qshift + BIGNUM_INT_BITS * (alen - mlen - i));\r
+    }\r
+}\r
+\r
+/*\r
+ * Compute (base ^ exp) % mod, the pedestrian way.\r
+ */\r
+Bignum modpow_simple(Bignum base_in, Bignum exp, Bignum mod)\r
+{\r
+    BignumInt *a, *b, *n, *m, *scratch;\r
+    int mshift;\r
+    int mlen, scratchlen, i, j;\r
+    Bignum base, result;\r
+\r
+    /*\r
+     * The most significant word of mod needs to be non-zero. It\r
+     * should already be, but let's make sure.\r
+     */\r
+    assert(mod[mod[0]] != 0);\r
+\r
+    /*\r
+     * Make sure the base is smaller than the modulus, by reducing\r
+     * it modulo the modulus if not.\r
+     */\r
+    base = bigmod(base_in, mod);\r
+\r
+    /* Allocate m of size mlen, copy mod to m */\r
+    /* We use big endian internally */\r
+    mlen = mod[0];\r
+    m = snewn(mlen, BignumInt);\r
+    for (j = 0; j < mlen; j++)\r
+       m[j] = mod[mod[0] - j];\r
+\r
+    /* Shift m left to make msb bit set */\r
+    for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)\r
+       if ((m[0] << mshift) & BIGNUM_TOP_BIT)\r
+           break;\r
+    if (mshift) {\r
+       for (i = 0; i < mlen - 1; i++)\r
+           m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));\r
+       m[mlen - 1] = m[mlen - 1] << mshift;\r
+    }\r
+\r
+    /* Allocate n of size mlen, copy base to n */\r
+    n = snewn(mlen, BignumInt);\r
+    i = mlen - base[0];\r
+    for (j = 0; j < i; j++)\r
+       n[j] = 0;\r
+    for (j = 0; j < (int)base[0]; j++)\r
+       n[i + j] = base[base[0] - j];\r
+\r
+    /* Allocate a and b of size 2*mlen. Set a = 1 */\r
+    a = snewn(2 * mlen, BignumInt);\r
+    b = snewn(2 * mlen, BignumInt);\r
+    for (i = 0; i < 2 * mlen; i++)\r
+       a[i] = 0;\r
+    a[2 * mlen - 1] = 1;\r
+\r
+    /* Scratch space for multiplies */\r
+    scratchlen = mul_compute_scratch(mlen);\r
+    scratch = snewn(scratchlen, BignumInt);\r
+\r
+    /* Skip leading zero bits of exp. */\r
+    i = 0;\r
+    j = BIGNUM_INT_BITS-1;\r
+    while (i < (int)exp[0] && (exp[exp[0] - i] & (1 << j)) == 0) {\r
+       j--;\r
+       if (j < 0) {\r
+           i++;\r
+           j = BIGNUM_INT_BITS-1;\r
+       }\r
+    }\r
+\r
+    /* Main computation */\r
+    while (i < (int)exp[0]) {\r
+       while (j >= 0) {\r
+           internal_mul(a + mlen, a + mlen, b, mlen, scratch);\r
+           internal_mod(b, mlen * 2, m, mlen, NULL, 0);\r
+           if ((exp[exp[0] - i] & (1 << j)) != 0) {\r
+               internal_mul(b + mlen, n, a, mlen, scratch);\r
+               internal_mod(a, mlen * 2, m, mlen, NULL, 0);\r
+           } else {\r
+               BignumInt *t;\r
+               t = a;\r
+               a = b;\r
+               b = t;\r
+           }\r
+           j--;\r
+       }\r
+       i++;\r
+       j = BIGNUM_INT_BITS-1;\r
+    }\r
+\r
+    /* Fixup result in case the modulus was shifted */\r
+    if (mshift) {\r
+       for (i = mlen - 1; i < 2 * mlen - 1; i++)\r
+           a[i] = (a[i] << mshift) | (a[i + 1] >> (BIGNUM_INT_BITS - mshift));\r
+       a[2 * mlen - 1] = a[2 * mlen - 1] << mshift;\r
+       internal_mod(a, mlen * 2, m, mlen, NULL, 0);\r
+       for (i = 2 * mlen - 1; i >= mlen; i--)\r
+           a[i] = (a[i] >> mshift) | (a[i - 1] << (BIGNUM_INT_BITS - mshift));\r
+    }\r
+\r
+    /* Copy result to buffer */\r
+    result = newbn(mod[0]);\r
+    for (i = 0; i < mlen; i++)\r
+       result[result[0] - i] = a[i + mlen];\r
+    while (result[0] > 1 && result[result[0]] == 0)\r
+       result[0]--;\r
+\r
+    /* Free temporary arrays */\r
+    for (i = 0; i < 2 * mlen; i++)\r
+       a[i] = 0;\r
+    sfree(a);\r
+    for (i = 0; i < scratchlen; i++)\r
+       scratch[i] = 0;\r
+    sfree(scratch);\r
+    for (i = 0; i < 2 * mlen; i++)\r
+       b[i] = 0;\r
+    sfree(b);\r
+    for (i = 0; i < mlen; i++)\r
+       m[i] = 0;\r
+    sfree(m);\r
+    for (i = 0; i < mlen; i++)\r
+       n[i] = 0;\r
+    sfree(n);\r
+\r
+    freebn(base);\r
+\r
+    return result;\r
+}\r
+\r
+/*\r
+ * Compute (base ^ exp) % mod. Uses the Montgomery multiplication\r
+ * technique where possible, falling back to modpow_simple otherwise.\r
+ */\r
+Bignum modpow(Bignum base_in, Bignum exp, Bignum mod)\r
+{\r
+    BignumInt *a, *b, *x, *n, *mninv, *scratch;\r
+    int len, scratchlen, i, j;\r
+    Bignum base, base2, r, rn, inv, result;\r
+\r
+    /*\r
+     * The most significant word of mod needs to be non-zero. It\r
+     * should already be, but let's make sure.\r
+     */\r
+    assert(mod[mod[0]] != 0);\r
+\r
+    /*\r
+     * mod had better be odd, or we can't do Montgomery multiplication\r
+     * using a power of two at all.\r
+     */\r
+    if (!(mod[1] & 1))\r
+        return modpow_simple(base_in, exp, mod);\r
+\r
+    /*\r
+     * Make sure the base is smaller than the modulus, by reducing\r
+     * it modulo the modulus if not.\r
+     */\r
+    base = bigmod(base_in, mod);\r
+\r
+    /*\r
+     * Compute the inverse of n mod r, for monty_reduce. (In fact we\r
+     * want the inverse of _minus_ n mod r, but we'll sort that out\r
+     * below.)\r
+     */\r
+    len = mod[0];\r
+    r = bn_power_2(BIGNUM_INT_BITS * len);\r
+    inv = modinv(mod, r);\r
+\r
+    /*\r
+     * Multiply the base by r mod n, to get it into Montgomery\r
+     * representation.\r
+     */\r
+    base2 = modmul(base, r, mod);\r
+    freebn(base);\r
+    base = base2;\r
+\r
+    rn = bigmod(r, mod);               /* r mod n, i.e. Montgomerified 1 */\r
+\r
+    freebn(r);                         /* won't need this any more */\r
+\r
+    /*\r
+     * Set up internal arrays of the right lengths, in big-endian\r
+     * format, containing the base, the modulus, and the modulus's\r
+     * inverse.\r
+     */\r
+    n = snewn(len, BignumInt);\r
+    for (j = 0; j < len; j++)\r
+       n[len - 1 - j] = mod[j + 1];\r
+\r
+    mninv = snewn(len, BignumInt);\r
+    for (j = 0; j < len; j++)\r
+       mninv[len - 1 - j] = (j < (int)inv[0] ? inv[j + 1] : 0);\r
+    freebn(inv);         /* we don't need this copy of it any more */\r
+    /* Now negate mninv mod r, so it's the inverse of -n rather than +n. */\r
+    x = snewn(len, BignumInt);\r
+    for (j = 0; j < len; j++)\r
+        x[j] = 0;\r
+    internal_sub(x, mninv, mninv, len);\r
+\r
+    /* x = snewn(len, BignumInt); */ /* already done above */\r
+    for (j = 0; j < len; j++)\r
+       x[len - 1 - j] = (j < (int)base[0] ? base[j + 1] : 0);\r
+    freebn(base);        /* we don't need this copy of it any more */\r
+\r
+    a = snewn(2*len, BignumInt);\r
+    b = snewn(2*len, BignumInt);\r
+    for (j = 0; j < len; j++)\r
+       a[2*len - 1 - j] = (j < (int)rn[0] ? rn[j + 1] : 0);\r
+    freebn(rn);\r
+\r
+    /* Scratch space for multiplies */\r
+    scratchlen = 3*len + mul_compute_scratch(len);\r
+    scratch = snewn(scratchlen, BignumInt);\r
+\r
+    /* Skip leading zero bits of exp. */\r
+    i = 0;\r
+    j = BIGNUM_INT_BITS-1;\r
+    while (i < (int)exp[0] && (exp[exp[0] - i] & (1 << j)) == 0) {\r
+       j--;\r
+       if (j < 0) {\r
+           i++;\r
+           j = BIGNUM_INT_BITS-1;\r
+       }\r
+    }\r
+\r
+    /* Main computation */\r
+    while (i < (int)exp[0]) {\r
+       while (j >= 0) {\r
+           internal_mul(a + len, a + len, b, len, scratch);\r
+            monty_reduce(b, n, mninv, scratch, len);\r
+           if ((exp[exp[0] - i] & (1 << j)) != 0) {\r
+                internal_mul(b + len, x, a, len,  scratch);\r
+                monty_reduce(a, n, mninv, scratch, len);\r
+           } else {\r
+               BignumInt *t;\r
+               t = a;\r
+               a = b;\r
+               b = t;\r
+           }\r
+           j--;\r
+       }\r
+       i++;\r
+       j = BIGNUM_INT_BITS-1;\r
+    }\r
+\r
+    /*\r
+     * Final monty_reduce to get back from the adjusted Montgomery\r
+     * representation.\r
+     */\r
+    monty_reduce(a, n, mninv, scratch, len);\r
+\r
+    /* Copy result to buffer */\r
+    result = newbn(mod[0]);\r
+    for (i = 0; i < len; i++)\r
+       result[result[0] - i] = a[i + len];\r
+    while (result[0] > 1 && result[result[0]] == 0)\r
+       result[0]--;\r
+\r
+    /* Free temporary arrays */\r
+    for (i = 0; i < scratchlen; i++)\r
+       scratch[i] = 0;\r
+    sfree(scratch);\r
+    for (i = 0; i < 2 * len; i++)\r
+       a[i] = 0;\r
+    sfree(a);\r
+    for (i = 0; i < 2 * len; i++)\r
+       b[i] = 0;\r
+    sfree(b);\r
+    for (i = 0; i < len; i++)\r
+       mninv[i] = 0;\r
+    sfree(mninv);\r
+    for (i = 0; i < len; i++)\r
+       n[i] = 0;\r
+    sfree(n);\r
+    for (i = 0; i < len; i++)\r
+       x[i] = 0;\r
+    sfree(x);\r
+\r
+    return result;\r
+}\r
+\r
+/*\r
+ * Compute (p * q) % mod.\r
+ * The most significant word of mod MUST be non-zero.\r
+ * We assume that the result array is the same size as the mod array.\r
+ */\r
+Bignum modmul(Bignum p, Bignum q, Bignum mod)\r
+{\r
+    BignumInt *a, *n, *m, *o, *scratch;\r
+    int mshift, scratchlen;\r
+    int pqlen, mlen, rlen, i, j;\r
+    Bignum result;\r
+\r
+    /* Allocate m of size mlen, copy mod to m */\r
+    /* We use big endian internally */\r
+    mlen = mod[0];\r
+    m = snewn(mlen, BignumInt);\r
+    for (j = 0; j < mlen; j++)\r
+       m[j] = mod[mod[0] - j];\r
+\r
+    /* Shift m left to make msb bit set */\r
+    for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)\r
+       if ((m[0] << mshift) & BIGNUM_TOP_BIT)\r
+           break;\r
+    if (mshift) {\r
+       for (i = 0; i < mlen - 1; i++)\r
+           m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));\r
+       m[mlen - 1] = m[mlen - 1] << mshift;\r
+    }\r
+\r
+    pqlen = (p[0] > q[0] ? p[0] : q[0]);\r
+\r
+    /* Allocate n of size pqlen, copy p to n */\r
+    n = snewn(pqlen, BignumInt);\r
+    i = pqlen - p[0];\r
+    for (j = 0; j < i; j++)\r
+       n[j] = 0;\r
+    for (j = 0; j < (int)p[0]; j++)\r
+       n[i + j] = p[p[0] - j];\r
+\r
+    /* Allocate o of size pqlen, copy q to o */\r
+    o = snewn(pqlen, BignumInt);\r
+    i = pqlen - q[0];\r
+    for (j = 0; j < i; j++)\r
+       o[j] = 0;\r
+    for (j = 0; j < (int)q[0]; j++)\r
+       o[i + j] = q[q[0] - j];\r
+\r
+    /* Allocate a of size 2*pqlen for result */\r
+    a = snewn(2 * pqlen, BignumInt);\r
+\r
+    /* Scratch space for multiplies */\r
+    scratchlen = mul_compute_scratch(pqlen);\r
+    scratch = snewn(scratchlen, BignumInt);\r
+\r
+    /* Main computation */\r
+    internal_mul(n, o, a, pqlen, scratch);\r
+    internal_mod(a, pqlen * 2, m, mlen, NULL, 0);\r
+\r
+    /* Fixup result in case the modulus was shifted */\r
+    if (mshift) {\r
+       for (i = 2 * pqlen - mlen - 1; i < 2 * pqlen - 1; i++)\r
+           a[i] = (a[i] << mshift) | (a[i + 1] >> (BIGNUM_INT_BITS - mshift));\r
+       a[2 * pqlen - 1] = a[2 * pqlen - 1] << mshift;\r
+       internal_mod(a, pqlen * 2, m, mlen, NULL, 0);\r
+       for (i = 2 * pqlen - 1; i >= 2 * pqlen - mlen; i--)\r
+           a[i] = (a[i] >> mshift) | (a[i - 1] << (BIGNUM_INT_BITS - mshift));\r
+    }\r
+\r
+    /* Copy result to buffer */\r
+    rlen = (mlen < pqlen * 2 ? mlen : pqlen * 2);\r
+    result = newbn(rlen);\r
+    for (i = 0; i < rlen; i++)\r
+       result[result[0] - i] = a[i + 2 * pqlen - rlen];\r
+    while (result[0] > 1 && result[result[0]] == 0)\r
+       result[0]--;\r
+\r
+    /* Free temporary arrays */\r
+    for (i = 0; i < scratchlen; i++)\r
+       scratch[i] = 0;\r
+    sfree(scratch);\r
+    for (i = 0; i < 2 * pqlen; i++)\r
+       a[i] = 0;\r
+    sfree(a);\r
+    for (i = 0; i < mlen; i++)\r
+       m[i] = 0;\r
+    sfree(m);\r
+    for (i = 0; i < pqlen; i++)\r
+       n[i] = 0;\r
+    sfree(n);\r
+    for (i = 0; i < pqlen; i++)\r
+       o[i] = 0;\r
+    sfree(o);\r
+\r
+    return result;\r
+}\r
+\r
+/*\r
+ * Compute p % mod.\r
+ * The most significant word of mod MUST be non-zero.\r
+ * We assume that the result array is the same size as the mod array.\r
+ * We optionally write out a quotient if `quotient' is non-NULL.\r
+ * We can avoid writing out the result if `result' is NULL.\r
+ */\r
+static void bigdivmod(Bignum p, Bignum mod, Bignum result, Bignum quotient)\r
+{\r
+    BignumInt *n, *m;\r
+    int mshift;\r
+    int plen, mlen, i, j;\r
+\r
+    /* Allocate m of size mlen, copy mod to m */\r
+    /* We use big endian internally */\r
+    mlen = mod[0];\r
+    m = snewn(mlen, BignumInt);\r
+    for (j = 0; j < mlen; j++)\r
+       m[j] = mod[mod[0] - j];\r
+\r
+    /* Shift m left to make msb bit set */\r
+    for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)\r
+       if ((m[0] << mshift) & BIGNUM_TOP_BIT)\r
+           break;\r
+    if (mshift) {\r
+       for (i = 0; i < mlen - 1; i++)\r
+           m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));\r
+       m[mlen - 1] = m[mlen - 1] << mshift;\r
+    }\r
+\r
+    plen = p[0];\r
+    /* Ensure plen > mlen */\r
+    if (plen <= mlen)\r
+       plen = mlen + 1;\r
+\r
+    /* Allocate n of size plen, copy p to n */\r
+    n = snewn(plen, BignumInt);\r
+    for (j = 0; j < plen; j++)\r
+       n[j] = 0;\r
+    for (j = 1; j <= (int)p[0]; j++)\r
+       n[plen - j] = p[j];\r
+\r
+    /* Main computation */\r
+    internal_mod(n, plen, m, mlen, quotient, mshift);\r
+\r
+    /* Fixup result in case the modulus was shifted */\r
+    if (mshift) {\r
+       for (i = plen - mlen - 1; i < plen - 1; i++)\r
+           n[i] = (n[i] << mshift) | (n[i + 1] >> (BIGNUM_INT_BITS - mshift));\r
+       n[plen - 1] = n[plen - 1] << mshift;\r
+       internal_mod(n, plen, m, mlen, quotient, 0);\r
+       for (i = plen - 1; i >= plen - mlen; i--)\r
+           n[i] = (n[i] >> mshift) | (n[i - 1] << (BIGNUM_INT_BITS - mshift));\r
+    }\r
+\r
+    /* Copy result to buffer */\r
+    if (result) {\r
+       for (i = 1; i <= (int)result[0]; i++) {\r
+           int j = plen - i;\r
+           result[i] = j >= 0 ? n[j] : 0;\r
+       }\r
+    }\r
+\r
+    /* Free temporary arrays */\r
+    for (i = 0; i < mlen; i++)\r
+       m[i] = 0;\r
+    sfree(m);\r
+    for (i = 0; i < plen; i++)\r
+       n[i] = 0;\r
+    sfree(n);\r
+}\r
+\r
+/*\r
+ * Decrement a number.\r
+ */\r
+void decbn(Bignum bn)\r
+{\r
+    int i = 1;\r
+    while (i < (int)bn[0] && bn[i] == 0)\r
+       bn[i++] = BIGNUM_INT_MASK;\r
+    bn[i]--;\r
+}\r
+\r
+Bignum bignum_from_bytes(const unsigned char *data, int nbytes)\r
+{\r
+    Bignum result;\r
+    int w, i;\r
+\r
+    w = (nbytes + BIGNUM_INT_BYTES - 1) / BIGNUM_INT_BYTES; /* bytes->words */\r
+\r
+    result = newbn(w);\r
+    for (i = 1; i <= w; i++)\r
+       result[i] = 0;\r
+    for (i = nbytes; i--;) {\r
+       unsigned char byte = *data++;\r
+       result[1 + i / BIGNUM_INT_BYTES] |= byte << (8*i % BIGNUM_INT_BITS);\r
+    }\r
+\r
+    while (result[0] > 1 && result[result[0]] == 0)\r
+       result[0]--;\r
+    return result;\r
+}\r
+\r
+/*\r
+ * Read an SSH-1-format bignum from a data buffer. Return the number\r
+ * of bytes consumed, or -1 if there wasn't enough data.\r
+ */\r
+int ssh1_read_bignum(const unsigned char *data, int len, Bignum * result)\r
+{\r
+    const unsigned char *p = data;\r
+    int i;\r
+    int w, b;\r
+\r
+    if (len < 2)\r
+       return -1;\r
+\r
+    w = 0;\r
+    for (i = 0; i < 2; i++)\r
+       w = (w << 8) + *p++;\r
+    b = (w + 7) / 8;                  /* bits -> bytes */\r
+\r
+    if (len < b+2)\r
+       return -1;\r
+\r
+    if (!result)                      /* just return length */\r
+       return b + 2;\r
+\r
+    *result = bignum_from_bytes(p, b);\r
+\r
+    return p + b - data;\r
+}\r
+\r
+/*\r
+ * Return the bit count of a bignum, for SSH-1 encoding.\r
+ */\r
+int bignum_bitcount(Bignum bn)\r
+{\r
+    int bitcount = bn[0] * BIGNUM_INT_BITS - 1;\r
+    while (bitcount >= 0\r
+          && (bn[bitcount / BIGNUM_INT_BITS + 1] >> (bitcount % BIGNUM_INT_BITS)) == 0) bitcount--;\r
+    return bitcount + 1;\r
+}\r
+\r
+/*\r
+ * Return the byte length of a bignum when SSH-1 encoded.\r
+ */\r
+int ssh1_bignum_length(Bignum bn)\r
+{\r
+    return 2 + (bignum_bitcount(bn) + 7) / 8;\r
+}\r
+\r
+/*\r
+ * Return the byte length of a bignum when SSH-2 encoded.\r
+ */\r
+int ssh2_bignum_length(Bignum bn)\r
+{\r
+    return 4 + (bignum_bitcount(bn) + 8) / 8;\r
+}\r
+\r
+/*\r
+ * Return a byte from a bignum; 0 is least significant, etc.\r
+ */\r
+int bignum_byte(Bignum bn, int i)\r
+{\r
+    if (i >= (int)(BIGNUM_INT_BYTES * bn[0]))\r
+       return 0;                      /* beyond the end */\r
+    else\r
+       return (bn[i / BIGNUM_INT_BYTES + 1] >>\r
+               ((i % BIGNUM_INT_BYTES)*8)) & 0xFF;\r
+}\r
+\r
+/*\r
+ * Return a bit from a bignum; 0 is least significant, etc.\r
+ */\r
+int bignum_bit(Bignum bn, int i)\r
+{\r
+    if (i >= (int)(BIGNUM_INT_BITS * bn[0]))\r
+       return 0;                      /* beyond the end */\r
+    else\r
+       return (bn[i / BIGNUM_INT_BITS + 1] >> (i % BIGNUM_INT_BITS)) & 1;\r
+}\r
+\r
+/*\r
+ * Set a bit in a bignum; 0 is least significant, etc.\r
+ */\r
+void bignum_set_bit(Bignum bn, int bitnum, int value)\r
+{\r
+    if (bitnum >= (int)(BIGNUM_INT_BITS * bn[0]))\r
+       abort();                       /* beyond the end */\r
+    else {\r
+       int v = bitnum / BIGNUM_INT_BITS + 1;\r
+       int mask = 1 << (bitnum % BIGNUM_INT_BITS);\r
+       if (value)\r
+           bn[v] |= mask;\r
+       else\r
+           bn[v] &= ~mask;\r
+    }\r
+}\r
+\r
+/*\r
+ * Write a SSH-1-format bignum into a buffer. It is assumed the\r
+ * buffer is big enough. Returns the number of bytes used.\r
+ */\r
+int ssh1_write_bignum(void *data, Bignum bn)\r
+{\r
+    unsigned char *p = data;\r
+    int len = ssh1_bignum_length(bn);\r
+    int i;\r
+    int bitc = bignum_bitcount(bn);\r
+\r
+    *p++ = (bitc >> 8) & 0xFF;\r
+    *p++ = (bitc) & 0xFF;\r
+    for (i = len - 2; i--;)\r
+       *p++ = bignum_byte(bn, i);\r
+    return len;\r
+}\r
+\r
+/*\r
+ * Compare two bignums. Returns like strcmp.\r
+ */\r
+int bignum_cmp(Bignum a, Bignum b)\r
+{\r
+    int amax = a[0], bmax = b[0];\r
+    int i = (amax > bmax ? amax : bmax);\r
+    while (i) {\r
+       BignumInt aval = (i > amax ? 0 : a[i]);\r
+       BignumInt bval = (i > bmax ? 0 : b[i]);\r
+       if (aval < bval)\r
+           return -1;\r
+       if (aval > bval)\r
+           return +1;\r
+       i--;\r
+    }\r
+    return 0;\r
+}\r
+\r
+/*\r
+ * Right-shift one bignum to form another.\r
+ */\r
+Bignum bignum_rshift(Bignum a, int shift)\r
+{\r
+    Bignum ret;\r
+    int i, shiftw, shiftb, shiftbb, bits;\r
+    BignumInt ai, ai1;\r
+\r
+    bits = bignum_bitcount(a) - shift;\r
+    ret = newbn((bits + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS);\r
+\r
+    if (ret) {\r
+       shiftw = shift / BIGNUM_INT_BITS;\r
+       shiftb = shift % BIGNUM_INT_BITS;\r
+       shiftbb = BIGNUM_INT_BITS - shiftb;\r
+\r
+       ai1 = a[shiftw + 1];\r
+       for (i = 1; i <= (int)ret[0]; i++) {\r
+           ai = ai1;\r
+           ai1 = (i + shiftw + 1 <= (int)a[0] ? a[i + shiftw + 1] : 0);\r
+           ret[i] = ((ai >> shiftb) | (ai1 << shiftbb)) & BIGNUM_INT_MASK;\r
+       }\r
+    }\r
+\r
+    return ret;\r
+}\r
+\r
+/*\r
+ * Non-modular multiplication and addition.\r
+ */\r
+Bignum bigmuladd(Bignum a, Bignum b, Bignum addend)\r
+{\r
+    int alen = a[0], blen = b[0];\r
+    int mlen = (alen > blen ? alen : blen);\r
+    int rlen, i, maxspot;\r
+    int wslen;\r
+    BignumInt *workspace;\r
+    Bignum ret;\r
+\r
+    /* mlen space for a, mlen space for b, 2*mlen for result,\r
+     * plus scratch space for multiplication */\r
+    wslen = mlen * 4 + mul_compute_scratch(mlen);\r
+    workspace = snewn(wslen, BignumInt);\r
+    for (i = 0; i < mlen; i++) {\r
+       workspace[0 * mlen + i] = (mlen - i <= (int)a[0] ? a[mlen - i] : 0);\r
+       workspace[1 * mlen + i] = (mlen - i <= (int)b[0] ? b[mlen - i] : 0);\r
+    }\r
+\r
+    internal_mul(workspace + 0 * mlen, workspace + 1 * mlen,\r
+                workspace + 2 * mlen, mlen, workspace + 4 * mlen);\r
+\r
+    /* now just copy the result back */\r
+    rlen = alen + blen + 1;\r
+    if (addend && rlen <= (int)addend[0])\r
+       rlen = addend[0] + 1;\r
+    ret = newbn(rlen);\r
+    maxspot = 0;\r
+    for (i = 1; i <= (int)ret[0]; i++) {\r
+       ret[i] = (i <= 2 * mlen ? workspace[4 * mlen - i] : 0);\r
+       if (ret[i] != 0)\r
+           maxspot = i;\r
+    }\r
+    ret[0] = maxspot;\r
+\r
+    /* now add in the addend, if any */\r
+    if (addend) {\r
+       BignumDblInt carry = 0;\r
+       for (i = 1; i <= rlen; i++) {\r
+           carry += (i <= (int)ret[0] ? ret[i] : 0);\r
+           carry += (i <= (int)addend[0] ? addend[i] : 0);\r
+           ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;\r
+           carry >>= BIGNUM_INT_BITS;\r
+           if (ret[i] != 0 && i > maxspot)\r
+               maxspot = i;\r
+       }\r
+    }\r
+    ret[0] = maxspot;\r
+\r
+    for (i = 0; i < wslen; i++)\r
+        workspace[i] = 0;\r
+    sfree(workspace);\r
+    return ret;\r
+}\r
+\r
+/*\r
+ * Non-modular multiplication.\r
+ */\r
+Bignum bigmul(Bignum a, Bignum b)\r
+{\r
+    return bigmuladd(a, b, NULL);\r
+}\r
+\r
+/*\r
+ * Simple addition.\r
+ */\r
+Bignum bigadd(Bignum a, Bignum b)\r
+{\r
+    int alen = a[0], blen = b[0];\r
+    int rlen = (alen > blen ? alen : blen) + 1;\r
+    int i, maxspot;\r
+    Bignum ret;\r
+    BignumDblInt carry;\r
+\r
+    ret = newbn(rlen);\r
+\r
+    carry = 0;\r
+    maxspot = 0;\r
+    for (i = 1; i <= rlen; i++) {\r
+        carry += (i <= (int)a[0] ? a[i] : 0);\r
+        carry += (i <= (int)b[0] ? b[i] : 0);\r
+        ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;\r
+        carry >>= BIGNUM_INT_BITS;\r
+        if (ret[i] != 0 && i > maxspot)\r
+            maxspot = i;\r
+    }\r
+    ret[0] = maxspot;\r
+\r
+    return ret;\r
+}\r
+\r
+/*\r
+ * Subtraction. Returns a-b, or NULL if the result would come out\r
+ * negative (recall that this entire bignum module only handles\r
+ * positive numbers).\r
+ */\r
+Bignum bigsub(Bignum a, Bignum b)\r
+{\r
+    int alen = a[0], blen = b[0];\r
+    int rlen = (alen > blen ? alen : blen);\r
+    int i, maxspot;\r
+    Bignum ret;\r
+    BignumDblInt carry;\r
+\r
+    ret = newbn(rlen);\r
+\r
+    carry = 1;\r
+    maxspot = 0;\r
+    for (i = 1; i <= rlen; i++) {\r
+        carry += (i <= (int)a[0] ? a[i] : 0);\r
+        carry += (i <= (int)b[0] ? b[i] ^ BIGNUM_INT_MASK : BIGNUM_INT_MASK);\r
+        ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;\r
+        carry >>= BIGNUM_INT_BITS;\r
+        if (ret[i] != 0 && i > maxspot)\r
+            maxspot = i;\r
+    }\r
+    ret[0] = maxspot;\r
+\r
+    if (!carry) {\r
+        freebn(ret);\r
+        return NULL;\r
+    }\r
+\r
+    return ret;\r
+}\r
+\r
+/*\r
+ * Create a bignum which is the bitmask covering another one. That\r
+ * is, the smallest integer which is >= N and is also one less than\r
+ * a power of two.\r
+ */\r
+Bignum bignum_bitmask(Bignum n)\r
+{\r
+    Bignum ret = copybn(n);\r
+    int i;\r
+    BignumInt j;\r
+\r
+    i = ret[0];\r
+    while (n[i] == 0 && i > 0)\r
+       i--;\r
+    if (i <= 0)\r
+       return ret;                    /* input was zero */\r
+    j = 1;\r
+    while (j < n[i])\r
+       j = 2 * j + 1;\r
+    ret[i] = j;\r
+    while (--i > 0)\r
+       ret[i] = BIGNUM_INT_MASK;\r
+    return ret;\r
+}\r
+\r
+/*\r
+ * Convert a (max 32-bit) long into a bignum.\r
+ */\r
+Bignum bignum_from_long(unsigned long nn)\r
+{\r
+    Bignum ret;\r
+    BignumDblInt n = nn;\r
+\r
+    ret = newbn(3);\r
+    ret[1] = (BignumInt)(n & BIGNUM_INT_MASK);\r
+    ret[2] = (BignumInt)((n >> BIGNUM_INT_BITS) & BIGNUM_INT_MASK);\r
+    ret[3] = 0;\r
+    ret[0] = (ret[2]  ? 2 : 1);\r
+    return ret;\r
+}\r
+\r
+/*\r
+ * Add a long to a bignum.\r
+ */\r
+Bignum bignum_add_long(Bignum number, unsigned long addendx)\r
+{\r
+    Bignum ret = newbn(number[0] + 1);\r
+    int i, maxspot = 0;\r
+    BignumDblInt carry = 0, addend = addendx;\r
+\r
+    for (i = 1; i <= (int)ret[0]; i++) {\r
+       carry += addend & BIGNUM_INT_MASK;\r
+       carry += (i <= (int)number[0] ? number[i] : 0);\r
+       addend >>= BIGNUM_INT_BITS;\r
+       ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;\r
+       carry >>= BIGNUM_INT_BITS;\r
+       if (ret[i] != 0)\r
+           maxspot = i;\r
+    }\r
+    ret[0] = maxspot;\r
+    return ret;\r
+}\r
+\r
+/*\r
+ * Compute the residue of a bignum, modulo a (max 16-bit) short.\r
+ */\r
+unsigned short bignum_mod_short(Bignum number, unsigned short modulus)\r
+{\r
+    BignumDblInt mod, r;\r
+    int i;\r
+\r
+    r = 0;\r
+    mod = modulus;\r
+    for (i = number[0]; i > 0; i--)\r
+       r = (r * (BIGNUM_TOP_BIT % mod) * 2 + number[i] % mod) % mod;\r
+    return (unsigned short) r;\r
+}\r
+\r
+#ifdef DEBUG\r
+void diagbn(char *prefix, Bignum md)\r
+{\r
+    int i, nibbles, morenibbles;\r
+    static const char hex[] = "0123456789ABCDEF";\r
+\r
+    debug(("%s0x", prefix ? prefix : ""));\r
+\r
+    nibbles = (3 + bignum_bitcount(md)) / 4;\r
+    if (nibbles < 1)\r
+       nibbles = 1;\r
+    morenibbles = 4 * md[0] - nibbles;\r
+    for (i = 0; i < morenibbles; i++)\r
+       debug(("-"));\r
+    for (i = nibbles; i--;)\r
+       debug(("%c",\r
+              hex[(bignum_byte(md, i / 2) >> (4 * (i % 2))) & 0xF]));\r
+\r
+    if (prefix)\r
+       debug(("\n"));\r
+}\r
+#endif\r
+\r
+/*\r
+ * Simple division.\r
+ */\r
+Bignum bigdiv(Bignum a, Bignum b)\r
+{\r
+    Bignum q = newbn(a[0]);\r
+    bigdivmod(a, b, NULL, q);\r
+    return q;\r
+}\r
+\r
+/*\r
+ * Simple remainder.\r
+ */\r
+Bignum bigmod(Bignum a, Bignum b)\r
+{\r
+    Bignum r = newbn(b[0]);\r
+    bigdivmod(a, b, r, NULL);\r
+    return r;\r
+}\r
+\r
+/*\r
+ * Greatest common divisor.\r
+ */\r
+Bignum biggcd(Bignum av, Bignum bv)\r
+{\r
+    Bignum a = copybn(av);\r
+    Bignum b = copybn(bv);\r
+\r
+    while (bignum_cmp(b, Zero) != 0) {\r
+       Bignum t = newbn(b[0]);\r
+       bigdivmod(a, b, t, NULL);\r
+       while (t[0] > 1 && t[t[0]] == 0)\r
+           t[0]--;\r
+       freebn(a);\r
+       a = b;\r
+       b = t;\r
+    }\r
+\r
+    freebn(b);\r
+    return a;\r
+}\r
+\r
+/*\r
+ * Modular inverse, using Euclid's extended algorithm.\r
+ */\r
+Bignum modinv(Bignum number, Bignum modulus)\r
+{\r
+    Bignum a = copybn(modulus);\r
+    Bignum b = copybn(number);\r
+    Bignum xp = copybn(Zero);\r
+    Bignum x = copybn(One);\r
+    int sign = +1;\r
+\r
+    while (bignum_cmp(b, One) != 0) {\r
+       Bignum t = newbn(b[0]);\r
+       Bignum q = newbn(a[0]);\r
+       bigdivmod(a, b, t, q);\r
+       while (t[0] > 1 && t[t[0]] == 0)\r
+           t[0]--;\r
+       freebn(a);\r
+       a = b;\r
+       b = t;\r
+       t = xp;\r
+       xp = x;\r
+       x = bigmuladd(q, xp, t);\r
+       sign = -sign;\r
+       freebn(t);\r
+       freebn(q);\r
+    }\r
+\r
+    freebn(b);\r
+    freebn(a);\r
+    freebn(xp);\r
+\r
+    /* now we know that sign * x == 1, and that x < modulus */\r
+    if (sign < 0) {\r
+       /* set a new x to be modulus - x */\r
+       Bignum newx = newbn(modulus[0]);\r
+       BignumInt carry = 0;\r
+       int maxspot = 1;\r
+       int i;\r
+\r
+       for (i = 1; i <= (int)newx[0]; i++) {\r
+           BignumInt aword = (i <= (int)modulus[0] ? modulus[i] : 0);\r
+           BignumInt bword = (i <= (int)x[0] ? x[i] : 0);\r
+           newx[i] = aword - bword - carry;\r
+           bword = ~bword;\r
+           carry = carry ? (newx[i] >= bword) : (newx[i] > bword);\r
+           if (newx[i] != 0)\r
+               maxspot = i;\r
+       }\r
+       newx[0] = maxspot;\r
+       freebn(x);\r
+       x = newx;\r
+    }\r
+\r
+    /* and return. */\r
+    return x;\r
+}\r
+\r
+/*\r
+ * Render a bignum into decimal. Return a malloced string holding\r
+ * the decimal representation.\r
+ */\r
+char *bignum_decimal(Bignum x)\r
+{\r
+    int ndigits, ndigit;\r
+    int i, iszero;\r
+    BignumDblInt carry;\r
+    char *ret;\r
+    BignumInt *workspace;\r
+\r
+    /*\r
+     * First, estimate the number of digits. Since log(10)/log(2)\r
+     * is just greater than 93/28 (the joys of continued fraction\r
+     * approximations...) we know that for every 93 bits, we need\r
+     * at most 28 digits. This will tell us how much to malloc.\r
+     *\r
+     * Formally: if x has i bits, that means x is strictly less\r
+     * than 2^i. Since 2 is less than 10^(28/93), this is less than\r
+     * 10^(28i/93). We need an integer power of ten, so we must\r
+     * round up (rounding down might make it less than x again).\r
+     * Therefore if we multiply the bit count by 28/93, rounding\r
+     * up, we will have enough digits.\r
+     *\r
+     * i=0 (i.e., x=0) is an irritating special case.\r
+     */\r
+    i = bignum_bitcount(x);\r
+    if (!i)\r
+       ndigits = 1;                   /* x = 0 */\r
+    else\r
+       ndigits = (28 * i + 92) / 93;  /* multiply by 28/93 and round up */\r
+    ndigits++;                        /* allow for trailing \0 */\r
+    ret = snewn(ndigits, char);\r
+\r
+    /*\r
+     * Now allocate some workspace to hold the binary form as we\r
+     * repeatedly divide it by ten. Initialise this to the\r
+     * big-endian form of the number.\r
+     */\r
+    workspace = snewn(x[0], BignumInt);\r
+    for (i = 0; i < (int)x[0]; i++)\r
+       workspace[i] = x[x[0] - i];\r
+\r
+    /*\r
+     * Next, write the decimal number starting with the last digit.\r
+     * We use ordinary short division, dividing 10 into the\r
+     * workspace.\r
+     */\r
+    ndigit = ndigits - 1;\r
+    ret[ndigit] = '\0';\r
+    do {\r
+       iszero = 1;\r
+       carry = 0;\r
+       for (i = 0; i < (int)x[0]; i++) {\r
+           carry = (carry << BIGNUM_INT_BITS) + workspace[i];\r
+           workspace[i] = (BignumInt) (carry / 10);\r
+           if (workspace[i])\r
+               iszero = 0;\r
+           carry %= 10;\r
+       }\r
+       ret[--ndigit] = (char) (carry + '0');\r
+    } while (!iszero);\r
+\r
+    /*\r
+     * There's a chance we've fallen short of the start of the\r
+     * string. Correct if so.\r
+     */\r
+    if (ndigit > 0)\r
+       memmove(ret, ret + ndigit, ndigits - ndigit);\r
+\r
+    /*\r
+     * Done.\r
+     */\r
+    sfree(workspace);\r
+    return ret;\r
+}\r
+\r
+#ifdef TESTBN\r
+\r
+#include <stdio.h>\r
+#include <stdlib.h>\r
+#include <ctype.h>\r
+\r
+/*\r
+ * gcc -g -O0 -DTESTBN -o testbn sshbn.c misc.c -I unix -I charset\r
+ *\r
+ * Then feed to this program's standard input the output of\r
+ * testdata/bignum.py .\r
+ */\r
+\r
+void modalfatalbox(char *p, ...)\r
+{\r
+    va_list ap;\r
+    fprintf(stderr, "FATAL ERROR: ");\r
+    va_start(ap, p);\r
+    vfprintf(stderr, p, ap);\r
+    va_end(ap);\r
+    fputc('\n', stderr);\r
+    exit(1);\r
+}\r
+\r
+#define fromxdigit(c) ( (c)>'9' ? ((c)&0xDF) - 'A' + 10 : (c) - '0' )\r
+\r
+int main(int argc, char **argv)\r
+{\r
+    char *buf;\r
+    int line = 0;\r
+    int passes = 0, fails = 0;\r
+\r
+    while ((buf = fgetline(stdin)) != NULL) {\r
+        int maxlen = strlen(buf);\r
+        unsigned char *data = snewn(maxlen, unsigned char);\r
+        unsigned char *ptrs[5], *q;\r
+        int ptrnum;\r
+        char *bufp = buf;\r
+\r
+        line++;\r
+\r
+        q = data;\r
+        ptrnum = 0;\r
+\r
+        while (*bufp && !isspace((unsigned char)*bufp))\r
+            bufp++;\r
+        if (bufp)\r
+            *bufp++ = '\0';\r
+\r
+        while (*bufp) {\r
+            char *start, *end;\r
+            int i;\r
+\r
+            while (*bufp && !isxdigit((unsigned char)*bufp))\r
+                bufp++;\r
+            start = bufp;\r
+\r
+            if (!*bufp)\r
+                break;\r
+\r
+            while (*bufp && isxdigit((unsigned char)*bufp))\r
+                bufp++;\r
+            end = bufp;\r
+\r
+            if (ptrnum >= lenof(ptrs))\r
+                break;\r
+            ptrs[ptrnum++] = q;\r
+            \r
+            for (i = -((end - start) & 1); i < end-start; i += 2) {\r
+                unsigned char val = (i < 0 ? 0 : fromxdigit(start[i]));\r
+                val = val * 16 + fromxdigit(start[i+1]);\r
+                *q++ = val;\r
+            }\r
+\r
+            ptrs[ptrnum] = q;\r
+        }\r
+\r
+        if (!strcmp(buf, "mul")) {\r
+            Bignum a, b, c, p;\r
+\r
+            if (ptrnum != 3) {\r
+                printf("%d: mul with %d parameters, expected 3\n", line);\r
+                exit(1);\r
+            }\r
+            a = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);\r
+            b = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);\r
+            c = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);\r
+            p = bigmul(a, b);\r
+\r
+            if (bignum_cmp(c, p) == 0) {\r
+                passes++;\r
+            } else {\r
+                char *as = bignum_decimal(a);\r
+                char *bs = bignum_decimal(b);\r
+                char *cs = bignum_decimal(c);\r
+                char *ps = bignum_decimal(p);\r
+                \r
+                printf("%d: fail: %s * %s gave %s expected %s\n",\r
+                       line, as, bs, ps, cs);\r
+                fails++;\r
+\r
+                sfree(as);\r
+                sfree(bs);\r
+                sfree(cs);\r
+                sfree(ps);\r
+            }\r
+            freebn(a);\r
+            freebn(b);\r
+            freebn(c);\r
+            freebn(p);\r
+        } else if (!strcmp(buf, "pow")) {\r
+            Bignum base, expt, modulus, expected, answer;\r
+\r
+            if (ptrnum != 4) {\r
+                printf("%d: mul with %d parameters, expected 3\n", line);\r
+                exit(1);\r
+            }\r
+\r
+            base = bignum_from_bytes(ptrs[0], ptrs[1]-ptrs[0]);\r
+            expt = bignum_from_bytes(ptrs[1], ptrs[2]-ptrs[1]);\r
+            modulus = bignum_from_bytes(ptrs[2], ptrs[3]-ptrs[2]);\r
+            expected = bignum_from_bytes(ptrs[3], ptrs[4]-ptrs[3]);\r
+            answer = modpow(base, expt, modulus);\r
+\r
+            if (bignum_cmp(expected, answer) == 0) {\r
+                passes++;\r
+            } else {\r
+                char *as = bignum_decimal(base);\r
+                char *bs = bignum_decimal(expt);\r
+                char *cs = bignum_decimal(modulus);\r
+                char *ds = bignum_decimal(answer);\r
+                char *ps = bignum_decimal(expected);\r
+                \r
+                printf("%d: fail: %s ^ %s mod %s gave %s expected %s\n",\r
+                       line, as, bs, cs, ds, ps);\r
+                fails++;\r
+\r
+                sfree(as);\r
+                sfree(bs);\r
+                sfree(cs);\r
+                sfree(ds);\r
+                sfree(ps);\r
+            }\r
+            freebn(base);\r
+            freebn(expt);\r
+            freebn(modulus);\r
+            freebn(expected);\r
+            freebn(answer);\r
+        } else {\r
+            printf("%d: unrecognised test keyword: '%s'\n", line, buf);\r
+            exit(1);\r
+        }\r
+\r
+        sfree(buf);\r
+        sfree(data);\r
+    }\r
+\r
+    printf("passed %d failed %d total %d\n", passes, fails, passes+fails);\r
+    return fails != 0;\r
+}\r
+\r
+#endif\r