lbn16.c
上传用户:zbbssh
上传日期:2007-01-08
资源大小:196k
文件大小:98k
源码类别:

CA认证

开发平台:

C/C++

  1. /*
  2.  * lbn16.c - Low-level bignum routines, 16-bit version.
  3.  *
  4.  * Copyright (c) 1995  Colin Plumb.  All rights reserved.
  5.  * For licensing and other legal details, see the file legal.c.
  6.  *
  7.  * NOTE: the magic constants "16" and "32" appear in many places in this
  8.  * file, including inside identifiers.  Because it is not possible to
  9.  * ask "#ifdef" of a macro expansion, it is not possible to use the
  10.  * preprocessor to conditionalize these properly.  Thus, this file is
  11.  * intended to be edited with textual search and replace to produce
  12.  * alternate word size versions.  Any reference to the number of bits
  13.  * in a word must be the string "16", and that string must not appear
  14.  * otherwise.  Any reference to twice this number must appear as "32",
  15.  * which likewise must not appear otherwise.  Is that clear?
  16.  *
  17.  * Remember, when doubling the bit size replace the larger number (32)
  18.  * first, then the smaller (16).  When halving the bit size, do the
  19.  * opposite.  Otherwise, things will get wierd.  Also, be sure to replace
  20.  * every instance that appears.  (:%s/foo/bar/g in vi)
  21.  *
  22.  * These routines work with a pointer to the least-significant end of
  23.  * an array of WORD16s.  The BIG(x), LITTLE(y) and BIGLTTLE(x,y) macros
  24.  * defined in lbn.h (which expand to x on a big-edian machine and y on a
  25.  * little-endian machine) are used to conditionalize the code to work
  26.  * either way.  If you have no assembly primitives, it doesn't matter.
  27.  * Note that on a big-endian machine, the least-significant-end pointer
  28.  * is ONE PAST THE END.  The bytes are ptr[-1] through ptr[-len].
  29.  * On little-endian, they are ptr[0] through ptr[len-1].  This makes
  30.  * perfect sense if you consider pointers to point *between* bytes rather
  31.  * than at them.
  32.  *
  33.  * Because the array index values are unsigned integers, ptr[-i]
  34.  * may not work properly, since the index -i is evaluated as an unsigned,
  35.  * and if pointers are wider, zero-extension will produce a positive
  36.  * number rahter than the needed negative.  The expression used in this
  37.  * code, *(ptr-i) will, however, work.  (The array syntax is equivalent
  38.  * to *(ptr+-i), which is a pretty subtle difference.)
  39.  *
  40.  * Many of these routines will get very unhappy if fed zero-length inputs.
  41.  * They use assert() to enforce this.  An higher layer of code must make
  42.  * sure that these aren't called with zero-length inputs.
  43.  *
  44.  * Any of these routines can be replaced with more efficient versions
  45.  * elsewhere, by just #defining their names.  If one of the names
  46.  * is #defined, the C code is not compiled in and no declaration is
  47.  * made.  Use the BNINCLUDE file to do that.  Typically, you compile
  48.  * asm subroutines with the same name and just, e.g.
  49.  * #define lbnMulAdd1_16 lbnMulAdd1_16
  50.  *
  51.  * If you want to write asm routines, start with lbnMulAdd1_16().
  52.  * This is the workhorse of modular exponentiation.  lbnMulN1_16() is
  53.  * also used a fair bit, although not as much and it's defined in terms
  54.  * of lbnMulAdd1_16 if that has a custom version.  lbnMulSub1_16 and
  55.  * lbnDiv21_16 are used in the usual division and remainder finding.
  56.  * (Not the Montgomery reduction used in modular exponentiation, though.)
  57.  * Once you have lbnMulAdd1_16 defined, writing the other two should
  58.  * be pretty easy.  (Just make sure you get the sign of the subtraction
  59.  * in lbnMulSub1_16 right - it's dest = dest - source * k.)
  60.  *
  61.  * The only definitions that absolutely need a double-word (BNWORD32)
  62.  * type are lbnMulAdd1_16 and lbnMulSub1_16; if those are provided,
  63.  * the rest follows.  lbnDiv21_16, however, is a lot slower unless you
  64.  * have them, and lbnModQ_16 takes after it.  That one is used quite a
  65.  * bit for prime sieving.
  66.  */
  67. #if HAVE_CONFIG_H
  68. #include "config.h"
  69. #endif
  70. #if !NO_ASSERT_H
  71. #include <assert.h>
  72. #else
  73. #define assert(x) (void)0
  74. #endif
  75. #if !NO_STRING_H
  76. #include <string.h> /* For memcpy */
  77. #elif HAVE_STRINGS_H
  78. #include <strings.h>
  79. #endif
  80. #if NEED_MEMORY_H
  81. #include <memory.h>
  82. #endif
  83. #include "lbn.h"
  84. #include "lbn16.h"
  85. #include "lbnmem.h"
  86. #include "legal.h"
  87. #include "kludge.h"
  88. #ifndef BNWORD16
  89. #error 16-bit bignum library requires a 16-bit data type
  90. #endif
  91. /* Make sure the copyright notice gets included */
  92. volatile const char * volatile const lbnCopyright = bnCopyright;
  93. /*
  94.  * Most of the multiply (and Montgomery reduce) routines use an outer
  95.  * loop that iterates over one of the operands - a so-called operand
  96.  * scanning approach.  One big advantage of this is that the assembly
  97.  * support routines are simpler.  The loops can be rearranged to have
  98.  * an outer loop that iterates over the product, a so-called product
  99.  * scanning approach.  This has the advantage of writing less data
  100.  * and doing fewer adds to memory, so is supposedly faster.  Some
  101.  * code has been written using a product-scanning approach, but
  102.  * it appears to be slower, so it is turned off by default.  Some
  103.  * experimentation would be appreciated.
  104.  *
  105.  * (The code is also annoying to get right and not very well commented,
  106.  * one of my pet peeves about math libraries.  I'm sorry.)
  107.  */
  108. #ifndef PRODUCT_SCAN
  109. #define PRODUCT_SCAN 0
  110. #endif
  111. /*
  112.  * Copy an array of words.  <Marvin mode on>  Thrilling, isn't it? </Marvin>
  113.  * This is a good example of how the byte offsets and BIGLITTLE() macros work.
  114.  * Another alternative would have been
  115.  * memcpy(dest BIG(-len), src BIG(-len), len*sizeof(BNWORD16)), but I find that
  116.  * putting operators into conditional macros is confusing.
  117.  */
  118. #ifndef lbnCopy_16
  119. void
  120. lbnCopy_16(BNWORD16 *dest, BNWORD16 const *src, unsigned len)
  121. {
  122. memcpy(BIGLITTLE(dest-len,dest), BIGLITTLE(src-len,src),
  123.        len * sizeof(*src));
  124. }
  125. #endif /* !lbnCopy_16 */
  126. /*
  127.  * Fill n words with zero.  This does it manually rather than calling
  128.  * memset because it can assume alignment to make things faster while
  129.  * memset can't.  Note how big-endian numbers are naturally addressed
  130.  * using predecrement, while little-endian is postincrement.
  131.  */
  132. #ifndef lbnZero_16
  133. void
  134. lbnZero_16(BNWORD16 *num, unsigned len)
  135. {
  136. while (len--)
  137. BIGLITTLE(*--num,*num++) = 0;
  138. }
  139. #endif /* !lbnZero_16 */
  140. /*
  141.  * Negate an array of words.
  142.  * Negation is subtraction from zero.  Negating low-order words
  143.  * entails doing nothing until a non-zero word is hit.  Once that
  144.  * is negated, a borrow is generated and never dies until the end
  145.  * of the number is hit.  Negation with borrow, -x-1, is the same as ~x.
  146.  * Repeat that until the end of the number.
  147.  *
  148.  * Doesn't return borrow out because that's pretty useless - it's
  149.  * always set unless the input is 0, which is easy to notice in
  150.  * normalized form.
  151.  */
  152. #ifndef lbnNeg_16
  153. void
  154. lbnNeg_16(BNWORD16 *num, unsigned len)
  155. {
  156. assert(len);
  157. /* Skip low-order zero words */
  158. while (BIGLITTLE(*--num,*num) == 0) {
  159. if (!--len)
  160. return;
  161. LITTLE(num++;)
  162. }
  163. /* Negate the lowest-order non-zero word */
  164. *num = -*num;
  165. /* Complement all the higher-order words */
  166. while (--len) {
  167. BIGLITTLE(--num,++num);
  168. *num = ~*num;
  169. }
  170. }
  171. #endif /* !lbnNeg_16 */
  172. /*
  173.  * lbnAdd1_16: add the single-word "carry" to the given number.
  174.  * Used for minor increments and propagating the carry after
  175.  * adding in a shorter bignum.
  176.  *
  177.  * Technique: If we have a double-width word, presumably the compiler
  178.  * can add using its carry in inline code, so we just use a larger
  179.  * accumulator to compute the carry from the first addition.
  180.  * If not, it's more complex.  After adding the first carry, which may
  181.  * be > 1, compare the sum and the carry.  If the sum wraps (causing a
  182.  * carry out from the addition), the result will be less than each of the
  183.  * inputs, since the wrap subtracts a number (2^16) which is larger than
  184.  * the other input can possibly be.  If the sum is >= the carry input,
  185.  * return success immediately.
  186.  * In either case, if there is a carry, enter a loop incrementing words
  187.  * until one does not wrap.  Since we are adding 1 each time, the wrap
  188.  * will be to 0 and we can test for equality.
  189.  */
  190. #ifndef lbnAdd1_16 /* If defined, it's provided as an asm subroutine */
  191. #ifdef BNWORD32
  192. BNWORD16
  193. lbnAdd1_16(BNWORD16 *num, unsigned len, BNWORD16 carry)
  194. {
  195. BNWORD32 t;
  196. assert(len > 0); /* Alternative: if (!len) return carry */
  197. t = (BNWORD32)BIGLITTLE(*--num,*num) + carry;
  198. BIGLITTLE(*num,*num++) = (BNWORD16)t;
  199. if ((t >> 16) == 0)
  200. return 0;
  201. while (--len) {
  202. if (++BIGLITTLE(*--num,*num++) != 0)
  203. return 0;
  204. }
  205. return 1;
  206. }
  207. #else /* no BNWORD32 */
  208. BNWORD16
  209. lbnAdd1_16(BNWORD16 *num, unsigned len, BNWORD16 carry)
  210. {
  211. assert(len > 0); /* Alternative: if (!len) return carry */
  212. if ((BIGLITTLE(*--num,*num++) += carry) >= carry)
  213. return 0;
  214. while (--len) {
  215. if (++BIGLITTLE(*--num,*num++) != 0)
  216. return 0;
  217. }
  218. return 1;
  219. }
  220. #endif
  221. #endif/* !lbnAdd1_16 */
  222. /*
  223.  * lbnSub1_16: subtract the single-word "borrow" from the given number.
  224.  * Used for minor decrements and propagating the borrow after
  225.  * subtracting a shorter bignum.
  226.  *
  227.  * Technique: Similar to the add, above.  If there is a double-length type,
  228.  * use that to generate the first borrow.
  229.  * If not, after subtracting the first borrow, which may be > 1, compare
  230.  * the difference and the *negative* of the carry.  If the subtract wraps
  231.  * (causing a borrow out from the subtraction), the result will be at least
  232.  * as large as -borrow.  If the result < -borrow, then no borrow out has
  233.  * appeared and we may return immediately, except when borrow == 0.  To
  234.  * deal with that case, use the identity that -x = ~x+1, and instead of
  235.  * comparing < -borrow, compare for <= ~borrow.
  236.  * Either way, if there is a borrow out, enter a loop decrementing words
  237.  * until a non-zero word is reached.
  238.  *
  239.  * Note the cast of ~borrow to (BNWORD16).  If the size of an int is larger
  240.  * than BNWORD16, C rules say the number is expanded for the arithmetic, so
  241.  * the inversion will be done on an int and the valie won't be quite what
  242.  * is expected.
  243.  */
  244. #ifndef lbnSub1_16 /* If defined, it's provided as an asm subroutine */
  245. #ifdef BNWORD32
  246. BNWORD16
  247. lbnSub1_16(BNWORD16 *num, unsigned len, BNWORD16 borrow)
  248. {
  249. BNWORD32 t;
  250. assert(len > 0); /* Alternative: if (!len) return borrow */
  251. t = (BNWORD32)BIGLITTLE(*--num,*num) - borrow;
  252. BIGLITTLE(*num,*num++) = (BNWORD16)t;
  253. if ((t >> 16) == 0)
  254. return 0;
  255. while (--len) {
  256. if ((BIGLITTLE(*--num,*num++))-- != 0)
  257. return 0;
  258. }
  259. return 1;
  260. }
  261. #else /* no BNWORD32 */
  262. BNWORD16
  263. lbnSub1_16(BNWORD16 *num, unsigned len, BNWORD16 borrow)
  264. {
  265. assert(len > 0); /* Alternative: if (!len) return borrow */
  266. if ((BIGLITTLE(*--num,*num++) -= borrow) <= (BNWORD16)~borrow)
  267. return 0;
  268. while (--len) {
  269. if ((BIGLITTLE(*--num,*num++))-- != 0)
  270. return 0;
  271. }
  272. return 1;
  273. }
  274. #endif
  275. #endif /* !lbnSub1_16 */
  276. /*
  277.  * lbnAddN_16: add two bignums of the same length, returning the carry (0 or 1).
  278.  * One of the building blocks, along with addn1, of adding two bignums of
  279.  * differing lengths.
  280.  *
  281.  * Technique: Maintain a word of carry.  If there is no double-width type,
  282.  * use the same technique as in addn1, above, to maintain the carry by
  283.  * comparing the inputs.  Adding the carry sources is used as an OR operator;
  284.  * at most one of the two comparisons can possibly be true.  The first can
  285.  * only be true if carry == 1 and x, the result, is 0.  In that case the
  286.  * second can't possibly be true.
  287.  */
  288. #ifndef lbnAddN_16
  289. #ifdef BNWORD32
  290. BNWORD16
  291. lbnAddN_16(BNWORD16 *num1, BNWORD16 const *num2, unsigned len)
  292. {
  293. BNWORD32 t;
  294. assert(len > 0); /* Alternative: change loop to test at start */
  295. t = (BNWORD32)BIGLITTLE(*--num1,*num1) + BIGLITTLE(*--num2,*num2++);
  296. BIGLITTLE(*num1,*num1++) = (BNWORD16)t;
  297. while (--len) {
  298. t = (BNWORD32)BIGLITTLE(*--num1,*num1) +
  299.     (BNWORD32)BIGLITTLE(*--num2,*num2++) + (t >> 16);
  300. BIGLITTLE(*num1,*num1++) = (BNWORD16)t;
  301. }
  302. return (BNWORD16)(t>>16);
  303. }
  304. #else /* no BNWORD32 */
  305. BNWORD16
  306. lbnAddN_16(BNWORD16 *num1, BNWORD16 const *num2, unsigned len)
  307. {
  308. BNWORD16 x, carry = 0;
  309. assert(len > 0); /* Alternative: change loop to test at start */
  310. do {
  311. x = BIGLITTLE(*--num2,*num2++);
  312. carry = (x += carry) < carry;
  313. carry += (BIGLITTLE(*--num1,*num1++) += x) < x;
  314. } while (--len);
  315. return carry;
  316. }
  317. #endif
  318. #endif /* !lbnAddN_16 */
  319. /*
  320.  * lbnSubN_16: add two bignums of the same length, returning the carry (0 or 1).
  321.  * One of the building blocks, along with subn1, of subtracting two bignums of
  322.  * differing lengths.
  323.  *
  324.  * Technique: If no double-width type is availble, maintain a word of borrow.
  325.  * First, add the borrow to the subtrahend (did you have to learn all those
  326.  * awful words in elementary school, too?), and if it overflows, set the
  327.  * borrow again.  Then subtract the modified subtrahend from the next word
  328.  * of input, using the same technique as in subn1, above.
  329.  * Adding the borrows is used as an OR operator; at most one of the two
  330.  * comparisons can possibly be true.  The first can only be true if
  331.  * borrow == 1 and x, the result, is 0.  In that case the second can't
  332.  * possibly be true.
  333.  *
  334.  * In the double-word case, (BNWORD16)-(t>>16) is subtracted, rather than
  335.  * adding t>>16, because the shift would need to sign-extend and that's
  336.  * not guaranteed to happen in ANSI C, even with signed types.
  337.  */
  338. #ifndef lbnSubN_16
  339. #ifdef BNWORD32
  340. BNWORD16
  341. lbnSubN_16(BNWORD16 *num1, BNWORD16 const *num2, unsigned len)
  342. {
  343. BNWORD32 t;
  344. assert(len > 0); /* Alternative: change loop to test at start */
  345. t = (BNWORD32)BIGLITTLE(*--num1,*num1) - BIGLITTLE(*--num2,*num2++);
  346. BIGLITTLE(*num1,*num1++) = (BNWORD16)t;
  347. while (--len) {
  348. t = (BNWORD32)BIGLITTLE(*--num1,*num1) -
  349.     (BNWORD32)BIGLITTLE(*--num2,*num2++) - (BNWORD16)-(t >> 16);
  350. BIGLITTLE(*num1,*num1++) = (BNWORD16)t;
  351. }
  352. return -(BNWORD16)(t>>16);
  353. }
  354. #else
  355. BNWORD16
  356. lbnSubN_16(BNWORD16 *num1, BNWORD16 const *num2, unsigned len)
  357. {
  358. BNWORD16 x, borrow = 0;
  359. assert(len > 0); /* Alternative: change loop to test at start */
  360. do {
  361. x = BIGLITTLE(*--num2,*num2++);
  362. borrow = (x += borrow) < borrow;
  363. borrow += (BIGLITTLE(*--num1,*num1++) -= x) > (BNWORD16)~x;
  364. } while (--len);
  365. return borrow;
  366. }
  367. #endif
  368. #endif /* !lbnSubN_16 */
  369. #ifndef lbnCmp_16
  370. /*
  371.  * lbnCmp_16: compare two bignums of equal length, returning the sign of
  372.  * num1 - num2. (-1, 0 or +1).
  373.  * 
  374.  * Technique: Change the little-endian pointers to big-endian pointers
  375.  * and compare from the most-significant end until a difference if found.
  376.  * When it is, figure out the sign of the difference and return it.
  377.  */
  378. int
  379. lbnCmp_16(BNWORD16 const *num1, BNWORD16 const *num2, unsigned len)
  380. {
  381. BIGLITTLE(num1 -= len, num1 += len);
  382. BIGLITTLE(num2 -= len, num2 += len);
  383. while (len--) {
  384. if (BIGLITTLE(*num1++ != *num2++, *--num1 != *--num2)) {
  385. if (BIGLITTLE(num1[-1] < num2[-1], *num1 < *num2))
  386. return -1;
  387. else
  388. return 1;
  389. }
  390. }
  391. return 0;
  392. }
  393. #endif /* !lbnCmp_16 */
  394. /*
  395.  * mul16_ppmmaa(ph,pl,x,y,a,b) is an optional routine that
  396.  * computes (ph,pl) = x * y + a + b.  mul16_ppmma and mul16_ppmm
  397.  * are simpler versions.  If you want to be lazy, all of these
  398.  * can be defined in terms of the others, so here we create any
  399.  * that have not been defined in terms of the ones that have been.
  400.  */
  401. /* Define ones with fewer a's in terms of ones with more a's */
  402. #if !defined(mul16_ppmma) && defined(mul16_ppmmaa)
  403. #define mul16_ppmma(ph,pl,x,y,a) mul16_ppmmaa(ph,pl,x,y,a,0)
  404. #endif
  405. #if !defined(mul16_ppmm) && defined(mul16_ppmma)
  406. #define mul16_ppmm(ph,pl,x,y) mul16_ppmma(ph,pl,x,y,0)
  407. #endif
  408. /*
  409.  * Use this definition to test the mul16_ppmm-based operations on machines
  410.  * that do not provide mul16_ppmm.  Change the final "0" to a "1" to
  411.  * enable it.
  412.  */
  413. #if !defined(mul16_ppmm) && defined(BNWORD32) && 0 /* Debugging */
  414. #define mul16_ppmm(ph,pl,x,y) 
  415. ({BNWORD32 _ = (BNWORD32)(x)*(y); (pl) = _; (ph) = _>>16;})
  416. #endif
  417. #if defined(mul16_ppmm) && !defined(mul16_ppmma)
  418. #define mul16_ppmma(ph,pl,x,y,a) 
  419. (mul16_ppmm(ph,pl,x,y), (ph) += ((pl) += (a)) < (a))
  420. #endif
  421. #if defined(mul16_ppmma) && !defined(mul16_ppmmaa)
  422. #define mul16_ppmmaa(ph,pl,x,y,a,b) 
  423. (mul16_ppmma(ph,pl,x,y,a), (ph) += ((pl) += (b)) < (b))
  424. #endif
  425. /*
  426.  * lbnMulN1_16: Multiply an n-word input by a 1-word input and store the
  427.  * n+1-word product.  This uses either the umul16_ppmm and umul16_ppmma
  428.  * macros, or C multiplication with the BNWORD32 type.  This uses mul16_ppmma
  429.  * if available, assuming you won't bother defining it unless you can do
  430.  * better than the normal multiplication.
  431.  */
  432. #ifndef lbnMulN1_16
  433. #ifdef lbnMulAdd1_16 /* If we have this asm primitive, use it. */
  434. void
  435. lbnMulN1_16(BNWORD16 *out, BNWORD16 const *in, unsigned len, BNWORD16 k)
  436. {
  437. lbnZero_16(out, len);
  438. BIGLITTLE(*(out-len),*(out+len)) = lbnMulAdd1_16(out, in, len, k);
  439. }
  440. #elif defined(umul16_ppmm)
  441. void
  442. lbnMulN1_16(BNWORD16 *out, BNWORD16 const *in, unsigned len, BNWORD16 k)
  443. {
  444. BNWORD16 prod, carry, carryin;
  445. assert(len > 0);
  446. BIG(--out;--in;);
  447. mul16_ppmm(carry, *out, *in, k);
  448. LITTLE(out++;in++;)
  449. while (--len) {
  450. BIG(--out;--in;)
  451. carryin = carry;
  452. mul16_ppmma(carry, *out, *in, k, carryin);
  453. LITTLE(out++;in++;)
  454. }
  455. BIGLITTLE(*--out,*out) = carry;
  456. }
  457. #elif defined(BNWORD32)
  458. void
  459. lbnMulN1_16(BNWORD16 *out, BNWORD16 const *in, unsigned len, BNWORD16 k)
  460. {
  461. BNWORD32 p;
  462. assert(len > 0);
  463. p = (BNWORD32)BIGLITTLE(*--in,*in++) * k;
  464. BIGLITTLE(*--out,*out++) = (BNWORD16)p;
  465. while (--len) {
  466. p = (BNWORD32)BIGLITTLE(*--in,*in++) * k + (BNWORD16)(p >> 16);
  467. BIGLITTLE(*--out,*out++) = (BNWORD16)p;
  468. }
  469. BIGLITTLE(*--out,*out) = (BNWORD16)(p >> 16);
  470. }
  471. #else
  472. #error No 16x16 -> 32 multiply available for 16-bit bignum package
  473. #endif
  474. #endif /* lbnMulN1_16 */
  475. /*
  476.  * lbnMulAdd1_16: Multiply an n-word input by a 1-word input and add the
  477.  * low n words of the product to the destination.  *Returns the n+1st word
  478.  * of the product.*  (That turns out to be more convenient than adding
  479.  * it into the destination and dealing with a possible unit carry out
  480.  * of *that*.)  This uses either the umul16_ppmma and umul16_ppmmaa macros,
  481.  * or C multiplication with the BNWORD32 type.
  482.  *
  483.  * If you're going to write assembly primitives, this is the one to
  484.  * start with.  It is by far the most commonly called function.
  485.  */
  486. #ifndef lbnMulAdd1_16
  487. #if defined(mul16_ppmm)
  488. BNWORD16
  489. lbnMulAdd1_16(BNWORD16 *out, BNWORD16 const *in, unsigned len, BNWORD16 k)
  490. {
  491. BNWORD16 prod, carry, carryin;
  492. assert(len > 0);
  493. BIG(--out;--in;);
  494. carryin = *out;
  495. mul16_ppmma(carry, *out, *in, k, carryin);
  496. LITTLE(out++;in++;)
  497. while (--len) {
  498. BIG(--out;--in;);
  499. carryin = carry;
  500. mul16_ppmmaa(carry, prod, *in, k, carryin, *out);
  501. *out = prod;
  502. LITTLE(out++;in++;)
  503. }
  504. return carry;
  505. }
  506. #elif defined(BNWORD32)
  507. BNWORD16
  508. lbnMulAdd1_16(BNWORD16 *out, BNWORD16 const *in, unsigned len, BNWORD16 k)
  509. {
  510. BNWORD32 p;
  511. assert(len > 0);
  512. p = (BNWORD32)BIGLITTLE(*--in,*in++) * k + BIGLITTLE(*--out,*out);
  513. BIGLITTLE(*out,*out++) = (BNWORD16)p;
  514. while (--len) {
  515. p = (BNWORD32)BIGLITTLE(*--in,*in++) * k +
  516.     (BNWORD16)(p >> 16) + BIGLITTLE(*--out,*out);
  517. BIGLITTLE(*out,*out++) = (BNWORD16)p;
  518. }
  519. return (BNWORD16)(p >> 16);
  520. }
  521. #else
  522. #error No 16x16 -> 32 multiply available for 16-bit bignum package
  523. #endif
  524. #endif /* lbnMulAdd1_16 */
  525. /*
  526.  * lbnMulSub1_16: Multiply an n-word input by a 1-word input and subtract the
  527.  * n-word product from the destination.  Returns the n+1st word of the product.
  528.  * This uses either the umul16_ppmm and umul16_ppmma macros, or
  529.  * C multiplication with the BNWORD32 type.
  530.  *
  531.  * This is rather uglier than adding, but fortunately it's only used in
  532.  * division which is not used too heavily.
  533.  */
  534. #ifndef lbnMulN1_16
  535. #if defined(mul16_ppmm)
  536. BNWORD16
  537. lbnMulSub1_16(BNWORD16 *out, BNWORD16 const *in, unsigned len, BNWORD16 k)
  538. {
  539. BNWORD16 prod, carry, carryin;
  540. assert(len > 0);
  541. BIG(--in;)
  542. mul16_ppmm(carry, prod, *in, k);
  543. LITTLE(in++;)
  544. carry += (BIGLITTLE(*--out,*out++) -= prod) > (BNWORD16)~prod;
  545. while (--len) {
  546. BIG(--in;);
  547. carryin = carry;
  548. mul16_ppmma(carry, prod, *in, k, carryin);
  549. LITTLE(in++;)
  550. carry += (BIGLITTLE(*--out,*out++) -= prod) > (BNWORD16)~prod;
  551. }
  552. return carry;
  553. }
  554. #elif defined(BNWORD32)
  555. BNWORD16
  556. lbnMulSub1_16(BNWORD16 *out, BNWORD16 const *in, unsigned len, BNWORD16 k)
  557. {
  558. BNWORD32 p;
  559. BNWORD16 carry, t;
  560. assert(len > 0);
  561. p = (BNWORD32)BIGLITTLE(*--in,*in++) * k;
  562. t = BIGLITTLE(*--out,*out);
  563. carry = (BNWORD16)(p>>16) + ((BIGLITTLE(*out,*out++)=t-(BNWORD16)p) > t);
  564. while (--len) {
  565. p = (BNWORD32)BIGLITTLE(*--in,*in++) * k + carry;
  566. t = BIGLITTLE(*--out,*out);
  567. carry = (BNWORD16)(p>>16) +
  568. ( (BIGLITTLE(*out,*out++)=t-(BNWORD16)p) > t );
  569. }
  570. return carry;
  571. }
  572. #else
  573. #error No 16x16 -> 32 multiply available for 16-bit bignum package
  574. #endif
  575. #endif /* !lbnMulSub1_16 */
  576. /*
  577.  * Shift n words left "shift" bits.  0 < shift < 16.  Returns the
  578.  * carry, any bits shifted off the left-hand side (0 <= carry < 2^shift).
  579.  */
  580. #ifndef lbnLshift_16
  581. BNWORD16
  582. lbnLshift_16(BNWORD16 *num, unsigned len, unsigned shift)
  583. {
  584. BNWORD16 x, carry;
  585. assert(shift > 0);
  586. assert(shift < 16);
  587. carry = 0;
  588. while (len--) {
  589. BIG(--num;)
  590. x = *num;
  591. *num = x<<shift | carry;
  592. LITTLE(num++;)
  593. carry = x >> (16-shift);
  594. }
  595. return carry;
  596. }
  597. #endif /* !lbnLshift_16 */
  598. /*
  599.  * An optimized version of the above, for shifts of 1.
  600.  * Some machines can use add-with-carry tricks for this.
  601.  */
  602. #ifndef lbnDouble_16
  603. BNWORD16
  604. lbnDouble_16(BNWORD16 *num, unsigned len)
  605. {
  606. BNWORD16 x, carry;
  607. carry = 0;
  608. while (len--) {
  609. BIG(--num;)
  610. x = *num;
  611. *num = x<<1 | carry;
  612. LITTLE(num++;)
  613. carry = x >> (16-1);
  614. }
  615. return carry;
  616. }
  617. #endif /* !lbnDouble_16 */
  618. /*
  619.  * Shift n words right "shift" bits.  0 < shift < 16.  Returns the
  620.  * carry, any bits shifted off the right-hand side (0 <= carry < 2^shift).
  621.  */
  622. #ifndef lbnRshift_16
  623. BNWORD16
  624. lbnRshift_16(BNWORD16 *num, unsigned len, unsigned shift)
  625. {
  626. BNWORD16 x, carry = 0;
  627. assert(shift > 0);
  628. assert(shift < 16);
  629. BIGLITTLE(num -= len, num += len);
  630. while (len--) {
  631. LITTLE(--num;)
  632. x = *num;
  633. *num = x>>shift | carry;
  634. BIG(num++;)
  635. carry = x << (16-shift);
  636. }
  637. return carry >> (16-shift);
  638. }
  639. #endif /* !lbnRshift_16 */
  640. /* 
  641.  * Multiply two numbers of the given lengths.  prod and num2 may overlap,
  642.  * provided that the low len1 bits of prod are free.  (This corresponds
  643.  * nicely to the place the result is returned from lbnMontReduce_16.)
  644.  *
  645.  * TODO: Use Karatsuba multiply.  The overlap constraints may have
  646.  * to get rewhacked.
  647.  */
  648. #ifndef lbnMul_16
  649. void
  650. lbnMul_16(BNWORD16 *prod, BNWORD16 const *num1, unsigned len1,
  651.                           BNWORD16 const *num2, unsigned len2)
  652. {
  653. /* Special case of zero */
  654. if (!len1 || !len2) {
  655. lbnZero_16(prod, len1+len2);
  656. return;
  657. }
  658. /* Multiply first word */
  659. lbnMulN1_16(prod, num1, len1, BIGLITTLE(*--num2,*num2++));
  660. /*
  661.  * Add in subsequent words, storing the most significant word,
  662.  * which is new each time.
  663.  */
  664. while (--len2) {
  665. BIGLITTLE(--prod,prod++);
  666. BIGLITTLE(*(prod-len1-1),*(prod+len1)) =
  667.     lbnMulAdd1_16(prod, num1, len1, BIGLITTLE(*--num2,*num2++));
  668. }
  669. }
  670. #endif /* !lbnMul_16 */
  671. /*
  672.  * lbnMulX_16 is a square multiply - both inputs are the same length.
  673.  * It's normally just a macro wrapper around the general multiply,
  674.  * but might be implementable in assembly more efficiently (such as
  675.  * in product scanning).
  676.  */
  677. #if defined(BNWORD32) && PRODUCT_SCAN
  678. /*
  679.  * Test code to see whether product scanning is any faster.  It seems
  680.  * to make the C code slower, so PRODUCT_SCAN is not defined.
  681.  */
  682. static void
  683. lbnMulX_16(BNWORD16 *prod, BNWORD16 const *num1, BNWORD16 const *num2,
  684. unsigned len)
  685. {
  686. BNWORD32 x, y;
  687. BNWORD16 const *p1, *p2;
  688. unsigned carry;
  689. unsigned i, j;
  690. /* Special case of zero */
  691. if (!len)
  692. return;
  693. x = (BNWORD32)BIGLITTLE(num1[-1] * num2[-1], num1[0] * num2[0]);
  694. BIGLITTLE(*--prod, *prod++) = (BNWORD16)x;
  695. x >>= 16;
  696. for (i = 1; i < len; i++) {
  697. carry = 0;
  698. p1 = num1;
  699. p2 = BIGLITTLE(num2-i-1,num2+i+1);
  700. for (j = 0; j <= i; j++) {
  701. BIG(y = (BNWORD32)*--p1 * *p2++;)
  702. LITTLE(y = (BNWORD32)*p1++ * *--p2;)
  703. x += y;
  704. carry += (x < y);
  705. }
  706. BIGLITTLE(*--prod,*prod++) = (BNWORD16)x;
  707. x = (x >> 16) | (BNWORD32)carry << 16;
  708. }
  709. for (i = 1; i < len; i++) {
  710. carry = 0;
  711. p1 = BIGLITTLE(num1-i,num1+i);
  712. p2 = BIGLITTLE(num2-len,num2+len);
  713. for (j = i; j < len; j++) {
  714. BIG(y = (BNWORD32)*--p1 * *p2++;)
  715. LITTLE(y = (BNWORD32)*p1++ * *--p2;)
  716. x += y;
  717. carry += (x < y);
  718. }
  719. BIGLITTLE(*--prod,*prod++) = (BNWORD16)x;
  720. x = (x >> 16) | (BNWORD32)carry << 16;
  721. }
  722. BIGLITTLE(*--prod,*prod) = (BNWORD16)x;
  723. }
  724. #else
  725. /* Default trivial macro definition */
  726. #define lbnMulX_16(prod, num1, num2, len) lbnMul_16(prod, num1, len, num2, len)
  727. #endif
  728. #if !defined(lbnMontMul) && defined(BNWORD32) && PRODUCT_SCAN
  729. /*
  730.  * Test code for product-scanning multiply.  This seems to slow the C
  731.  * code down rather than speed it up.
  732.  * This does a multiply and Montgomery reduction together, using the
  733.  * same loops.  The outer loop scans across the product, twice.
  734.  * The first pass computes the low half of the product and the
  735.  * Montgomery multipliers.  These are stored in the product array,
  736.  * which contains no data as of yet.  x and carry add up the columns
  737.  * and propagate carries forward.
  738.  *
  739.  * The second half multiplies the upper half, adding in the modulus
  740.  * times the Montgomery multipliers.  The results of this multiply
  741.  * are stored.
  742.  */
  743. static void
  744. lbnMontMul_16(BNWORD16 *prod, BNWORD16 const *num1, BNWORD16 const *num2,
  745. BNWORD16 const *mod, unsigned len, BNWORD16 inv)
  746. {
  747. BNWORD32 x, y;
  748. BNWORD16 const *p1, *p2, *pm;
  749. BNWORD16 *pp;
  750. BNWORD16 t;
  751. unsigned carry;
  752. unsigned i, j;
  753. /* Special case of zero */
  754. if (!len)
  755. return;
  756. /*
  757.  * This computes directly into the high half of prod, so just
  758.  * shift the pointer and consider prod only "len" elements long
  759.  * for the rest of the code.
  760.  */
  761. BIGLITTLE(prod -= len, prod += len);
  762. /* Pass 1 - compute Montgomery multipliers */
  763. /* First iteration can have certain simplifications. */
  764. x = (BNWORD32)BIGLITTLE(num1[-1] * num2[-1], num1[0] * num2[0]);
  765. BIGLITTLE(prod[-1], prod[0]) = t = inv * (BNWORD16)x;
  766. y = (BNWORD32)t * BIGLITTLE(mod[-1],mod[0]);
  767. x += y;
  768. /* Note: GCC 2.6.3 has a bug if you try to eliminate "carry" */
  769. carry = (x < y);
  770. assert((BNWORD16)x == 0);
  771. x = x >> 16 | (BNWORD32)carry << 16;
  772. for (i = 1; i < len; i++) {
  773. carry = 0;
  774. p1 = num1;
  775. p2 = BIGLITTLE(num2-i-1,num2+i+1);
  776. pp = prod;
  777. pm = BIGLITTLE(mod-i-1,mod+i+1);
  778. for (j = 0; j < i; j++) {
  779. y = (BNWORD32)BIGLITTLE(*--p1 * *p2++, *p1++ * *--p2);
  780. x += y;
  781. carry += (x < y);
  782. y = (BNWORD32)BIGLITTLE(*--pp * *pm++, *pp++ * *--pm);
  783. x += y;
  784. carry += (x < y);
  785. }
  786. y = (BNWORD32)BIGLITTLE(p1[-1] * p2[0], p1[0] * p2[-1]);
  787. x += y;
  788. carry += (x < y);
  789. assert(BIGLITTLE(pp == prod-i, pp == prod+i));
  790. BIGLITTLE(pp[-1], pp[0]) = t = inv * (BNWORD16)x;
  791. assert(BIGLITTLE(pm == mod-1, pm == mod+1));
  792. y = (BNWORD32)t * BIGLITTLE(pm[0],pm[-1]);
  793. x += y;
  794. carry += (x < y);
  795. assert((BNWORD16)x == 0);
  796. x = x >> 16 | (BNWORD32)carry << 16;
  797. }
  798. /* Pass 2 - compute reduced product and store */
  799. for (i = 1; i < len; i++) {
  800. carry = 0;
  801. p1 = BIGLITTLE(num1-i,num1+i);
  802. p2 = BIGLITTLE(num2-len,num2+len);
  803. pm = BIGLITTLE(mod-i,mod+i);
  804. pp = BIGLITTLE(prod-len,prod+len);
  805. for (j = i; j < len; j++) {
  806. y = (BNWORD32)BIGLITTLE(*--p1 * *p2++, *p1++ * *--p2);
  807. x += y;
  808. carry += (x < y);
  809. y = (BNWORD32)BIGLITTLE(*--pm * *pp++, *pm++ * *--pp);
  810. x += y;
  811. carry += (x < y);
  812. }
  813. assert(BIGLITTLE(pm == mod-len, pm == mod+len));
  814. assert(BIGLITTLE(pp == prod-i, pp == prod+i));
  815. BIGLITTLE(pp[0],pp[-1]) = (BNWORD16)x;
  816. x = (x >> 16) | (BNWORD32)carry << 16;
  817. }
  818. /* Last round of second half, simplified. */
  819. BIGLITTLE(*(prod-len),*(prod+len-1)) = (BNWORD16)x;
  820. carry = (x >> 16);
  821. while (carry)
  822. carry -= lbnSubN_16(prod, mod, len);
  823. while (lbnCmp_16(prod, mod, len) >= 0)
  824. (void)lbnSubN_16(prod, mod, len);
  825. }
  826. #define lbnMontMul_16 lbnMontMul_16
  827. #endif
  828. #if defined(BNWORD32) && PRODUCT_SCAN
  829. /*
  830.  * Trial code for product-scanning squaring.  This seems to slow the C
  831.  * code down rather than speed it up.
  832.  */
  833. void
  834. lbnSquare_16(BNWORD16 *prod, BNWORD16 const *num, unsigned len)
  835. {
  836. BNWORD32 x, y, z;
  837. BNWORD16 const *p1, *p2;
  838. unsigned carry;
  839. unsigned i, j;
  840. /* Special case of zero */
  841. if (!len)
  842. return;
  843. /* Word 0 of product */
  844. x = (BNWORD32)BIGLITTLE(num[-1] * num[-1], num[0] * num[0]);
  845. BIGLITTLE(*--prod, *prod++) = (BNWORD16)x;
  846. x >>= 16;
  847. /* Words 1 through len-1 */
  848. for (i = 1; i < len; i++) {
  849. carry = 0;
  850. y = 0;
  851. p1 = num;
  852. p2 = BIGLITTLE(num-i-1,num+i+1);
  853. for (j = 0; j < (i+1)/2; j++) {
  854. BIG(z = (BNWORD32)*--p1 * *p2++;)
  855. LITTLE(z = (BNWORD32)*p1++ * *--p2;)
  856. y += z;
  857. carry += (y < z);
  858. }
  859. y += z = y;
  860. carry += carry + (y < z);
  861. if ((i & 1) == 0) {
  862. assert(BIGLITTLE(--p1 == p2, p1 == --p2));
  863. BIG(z = (BNWORD32)*p2 * *p2;)
  864. LITTLE(z = (BNWORD32)*p1 * *p1;)
  865. y += z;
  866. carry += (y < z);
  867. }
  868. x += y;
  869. carry += (x < y);
  870. BIGLITTLE(*--prod,*prod++) = (BNWORD16)x;
  871. x = (x >> 16) | (BNWORD32)carry << 16;
  872. }
  873. /* Words len through 2*len-2 */
  874. for (i = 1; i < len; i++) {
  875. carry = 0;
  876. y = 0;
  877. p1 = BIGLITTLE(num-i,num+i);
  878. p2 = BIGLITTLE(num-len,num+len);
  879. for (j = 0; j < (len-i)/2; j++) {
  880. BIG(z = (BNWORD32)*--p1 * *p2++;)
  881. LITTLE(z = (BNWORD32)*p1++ * *--p2;)
  882. y += z;
  883. carry += (y < z);
  884. }
  885. y += z = y;
  886. carry += carry + (y < z);
  887. if ((len-i) & 1) {
  888. assert(BIGLITTLE(--p1 == p2, p1 == --p2));
  889. BIG(z = (BNWORD32)*p2 * *p2;)
  890. LITTLE(z = (BNWORD32)*p1 * *p1;)
  891. y += z;
  892. carry += (y < z);
  893. }
  894. x += y;
  895. carry += (x < y);
  896. BIGLITTLE(*--prod,*prod++) = (BNWORD16)x;
  897. x = (x >> 16) | (BNWORD32)carry << 16;
  898. }
  899. /* Word 2*len-1 */
  900. BIGLITTLE(*--prod,*prod) = (BNWORD16)x;
  901. }
  902. #define lbnSquare_16 lbnSquare_16
  903. #endif
  904. /*
  905.  * Square a number, using optimized squaring to reduce the number of
  906.  * primitive multiples that are executed.  There may not be any
  907.  * overlap of the input and output.
  908.  *
  909.  * Technique: Consider the partial products in the multiplication
  910.  * of "abcde" by itself:
  911.  *
  912.  *               a  b  c  d  e
  913.  *            *  a  b  c  d  e
  914.  *          ==================
  915.  *              ae be ce de ee
  916.  *           ad bd cd dd de
  917.  *        ac bc cc cd ce
  918.  *     ab bb bc bd be
  919.  *  aa ab ac ad ae
  920.  *
  921.  * Note that everything above the main diagonal:
  922.  *              ae be ce de = (abcd) * e
  923.  *           ad bd cd       = (abc) * d
  924.  *        ac bc             = (ab) * c
  925.  *     ab                   = (a) * b
  926.  *
  927.  * is a copy of everything below the main diagonal:
  928.  *                       de
  929.  *                 cd ce
  930.  *           bc bd be
  931.  *     ab ac ad ae
  932.  *
  933.  * Thus, the sum is 2 * (off the diagonal) + diagonal.
  934.  *
  935.  * This is accumulated beginning with the diagonal (which
  936.  * consist of the squares of the digits of the input), which is then
  937.  * divided by two, the off-diagonal added, and multiplied by two
  938.  * again.  The low bit is simply a copy of the low bit of the
  939.  * input, so it doesn't need special care.
  940.  *
  941.  * TODO: Merge the shift by 1 with the squaring loop.
  942.  * TODO: Use Karatsuba.  (a*W+b)^2 = a^2 * (W^2+W) + b^2 * (W+1) - (a-b)^2 * W.
  943.  */
  944. #ifndef lbnSquare_16
  945. void
  946. lbnSquare_16(BNWORD16 *prod, BNWORD16 const *num, unsigned len)
  947. {
  948. BNWORD16 t;
  949. BNWORD16 *prodx = prod; /* Working copy of the argument */
  950. BNWORD16 const *numx = num; /* Working copy of the argument */
  951. unsigned lenx = len; /* Working copy of the argument */
  952. if (!len)
  953. return;
  954. /* First, store all the squares */
  955. while (lenx--) {
  956. #ifdef mul16_ppmm
  957. BNWORD16 ph, pl;
  958. t = BIGLITTLE(*--numx,*numx++);
  959. mul16_ppmm(ph,pl,t,t);
  960. BIGLITTLE(*--prodx,*prodx++) = pl;
  961. BIGLITTLE(*--prodx,*prodx++) = ph;
  962. #elif defined(BNWORD32) /* use BNWORD32 */
  963. BNWORD32 p;
  964. t = BIGLITTLE(*--numx,*numx++);
  965. p = (BNWORD32)t * t;
  966. BIGLITTLE(*--prodx,*prodx++) = (BNWORD16)p;
  967. BIGLITTLE(*--prodx,*prodx++) = (BNWORD16)(p>>16);
  968. #else /* Use lbnMulN1_16 */
  969. t = BIGLITTLE(numx[-1],*numx);
  970. lbnMulN1_16(prodx, numx, 1, t);
  971. BIGLITTLE(--numx,numx++);
  972. BIGLITTLE(prodx -= 2, prodx += 2);
  973. #endif
  974. }
  975. /* Then, shift right 1 bit */
  976. (void)lbnRshift_16(prod, 2*len, 1);
  977. /* Then, add in the off-diagonal sums */
  978. lenx = len;
  979. numx = num;
  980. prodx = prod;
  981. while (--lenx) {
  982. t = BIGLITTLE(*--numx,*numx++);
  983. BIGLITTLE(--prodx,prodx++);
  984. t = lbnMulAdd1_16(prodx, numx, lenx, t);
  985. lbnAdd1_16(BIGLITTLE(prodx-lenx,prodx+lenx), lenx+1, t);
  986. BIGLITTLE(--prodx,prodx++);
  987. }
  988. /* Shift it back up */
  989. lbnDouble_16(prod, 2*len);
  990. /* And set the low bit appropriately */
  991. BIGLITTLE(prod[-1],prod[0]) |= BIGLITTLE(num[-1],num[0]) & 1;
  992. }
  993. #endif /* !lbnSquare_16 */
  994. /*
  995.  * lbnNorm_16 - given a number, return a modified length such that the
  996.  * most significant digit is non-zero.  Zero-length input is okay.
  997.  */
  998. #ifndef lbnNorm_16
  999. unsigned
  1000. lbnNorm_16(BNWORD16 const *num, unsigned len)
  1001. {
  1002. BIGLITTLE(num -= len,num += len);
  1003. while (len && BIGLITTLE(*num++,*--num) == 0)
  1004. --len;
  1005. return len;
  1006. }
  1007. #endif /* lbnNorm_16 */
  1008. /*
  1009.  * lbnBits_16 - return the number of significant bits in the array.
  1010.  * It starts by normalizing the array.  Zero-length input is okay.
  1011.  * Then assuming there's anything to it, it fetches the high word,
  1012.  * generates a bit length by multiplying the word length by 16, and
  1013.  * subtracts off 16/2, 16/4, 16/8, ... bits if the high bits are clear.
  1014.  */
  1015. #ifndef lbnBits_16
  1016. unsigned
  1017. lbnBits_16(BNWORD16 const *num, unsigned len)
  1018. {
  1019. BNWORD16 t;
  1020. unsigned i;
  1021. len = lbnNorm_16(num, len);
  1022. if (len) {
  1023. t = BIGLITTLE(*(num-len),*(num+(len-1)));
  1024. assert(t);
  1025. len *= 16;
  1026. i = 16;
  1027. while (i /= 2) {
  1028. if (t >> i)
  1029. t >>= i;
  1030. else
  1031. len -= i;
  1032. }
  1033. }
  1034. return len;
  1035. }
  1036. #endif /* lbnBits_16 */
  1037. /*
  1038.  * If defined, use hand-rolled divide rather than compiler's native.
  1039.  * If the machine doesn't do it in line, the manual code is probably
  1040.  * faster, since it can assume normalization.
  1041.  */
  1042. #ifndef BN_SLOW_DIVIDE_32
  1043. #define BN_SLOW_DIVIDE_32 1
  1044. #endif
  1045. /*
  1046.  * Return (nh<<16|nl) % d, and place the quotient digit into *q.
  1047.  * It is guaranteed that nh < d, and that d is normalized (with its high
  1048.  * bit set).  If we have a double-width type, it's easy.  If not, ooh,
  1049.  * yuk!
  1050.  */
  1051. #ifndef lbnDiv21_16
  1052. #if defined(BNWORD32) && !BN_SLOW_DIVIDE_32
  1053. BNWORD16
  1054. lbnDiv21_16(BNWORD16 *q, BNWORD16 nh, BNWORD16 nl, BNWORD16 d)
  1055. {
  1056. BNWORD32 n = (BNWORD32)nh << 16 | nl;
  1057. /* Divisor must be normalized */
  1058. assert(d >> (16-1) == 1);
  1059. *q = n / d;
  1060. return n % d;
  1061. }
  1062. #else
  1063. /*
  1064.  * This is where it gets ugly.
  1065.  *
  1066.  * Do the division in two halves, using Algorithm D from section 4.3.1
  1067.  * of Knuth.  Note Theorem B from that section, that the quotient estimate
  1068.  * is never more than the true quotient, and is never more than two
  1069.  * too low.
  1070.  *
  1071.  * The mapping onto conventional long division is (everything a half word):
  1072.  *        _____________qh___ql_
  1073.  * dh dl ) nh.h nh.l nl.h nl.l
  1074.  *       -     (implicit)
  1075.  *            -----------
  1076.  *              rrrrrrrrr nl.l
  1077.  *            -    (implicit)
  1078.  *                -----------
  1079.  *                  rrrrrrrrr
  1080.  *
  1081.  * The implicit 3/2-digit d*qh and d*ql subtractors are computed this way:
  1082.  *   First, estimate a q digit so that nh/dh works.  Subtracting q*dh from
  1083.  *   the (nh.h nh.l) list leaves a 1/2-word remainder r.  Then compute the
  1084.  *   low part of the subtractor, q * dl.   This also needs to be subtracted
  1085.  *   from (nh.h nh.l nl.h) to get the final remainder.  So we take the
  1086.  *   remainder, which is (nh.h nh.l) - q*dl, shift it and add in nl.h, and
  1087.  *   try to subtract q * dl from that.
  1088.  *   It is possible that the remainder we're working with, r, is less than
  1089.  *   the product q * d1, due to an error in estimating q.  The estimation
  1090.  *   technique can produce a q that is too large (never too small), leading
  1091.  *   to r which is too small.  In that case, decrement the digit q, add
  1092.  *   shifted dh to r (to correct for that error), and subtract dl from the
  1093.  *   product we're comparing r with.  That's the "correct" way to do it, but
  1094.  *   just adding dl to r instead of subtracting it from the product is
  1095.  *   equivalent and a lot simpler.  You just have to watch out for overflow.
  1096.  *
  1097.  *   The process is repeated with (rrrr rrrr nl.l) for the low digit of the
  1098.  *   quotient.
  1099.  *
  1100.  * The various uses of 16/2 for shifts are because of the note about
  1101.  * automatic editing of this file at the very top of the file.
  1102.  */
  1103. #define highhalf(x) ( (x) >> 16/2 )
  1104. #define lowhalf(x) ( (x) & (((BNWORD16)1 << 16/2)-1) )
  1105. BNWORD16
  1106. lbnDiv21_16(BNWORD16 *q, BNWORD16 nh, BNWORD16 nl, BNWORD16 d)
  1107. {
  1108. BNWORD16 dh = highhalf(d), dl = lowhalf(d);
  1109. BNWORD16 qh, ql, prod, r;
  1110. /* Divisor must be normalized */
  1111. assert(d >> (16-1) == 1);
  1112. /* Do first half-word of division */
  1113. qh = nh / dh;
  1114. r = nh % dh;
  1115. prod = qh * dl;
  1116. /*
  1117.  * Add next half-word of numerator to remainder and correct.
  1118.  * qh may be up to two too large.
  1119.  * 
  1120.  */
  1121. r = r << (16/2) | highhalf(nl);
  1122. if (r < prod) {
  1123. --qh; r += d;
  1124. if (r >= d && r < prod) {
  1125. --qh; r += d; 
  1126. }
  1127. }
  1128. r -= prod;
  1129. /* Do second half-word of division */
  1130. ql = r / dh;
  1131. r = r % dh;
  1132. prod = ql * dl;
  1133. r = r << (16/2) | lowhalf(nl);
  1134. if (r < prod) {
  1135. --ql; r += d;
  1136. if (r >= d && r < prod) {
  1137. --ql; r += d;
  1138. }
  1139. }
  1140. r -= prod;
  1141. *q = qh << (16/2) | ql;
  1142. return r;
  1143. }
  1144. #endif
  1145. #endif /* lbnDiv21_16 */
  1146. /*
  1147.  * In the division functions, the dividend and divisor are referred to
  1148.  * as "n" and "d", which stand for "numerator" and "denominator".
  1149.  *
  1150.  * The quotient is (nlen-dlen+1) digits long.  It may be overlapped with
  1151.  * the high (nlen-dlen) words of the dividend, but one extra word is needed
  1152.  * on top to hold the top word.
  1153.  */
  1154. /*
  1155.  * Divide an n-word number by a 1-word number, storing the remainder
  1156.  * and n-1 words of the n-word quotient.  The high word is returned.
  1157.  * It IS legal for rem to point to the same address as n, and for
  1158.  * q to point one word higher.
  1159.  *
  1160.  * TODO: If BN_SLOW_DIVIDE_32, add a divnhalf_16 which uses 16-bit
  1161.  *       dividends if the divisor is half that long.
  1162.  * TODO: Shift the dividend on the fly to avoid the last division and
  1163.  *       instead have a remainder that needs shifting.
  1164.  * TODO: Use reciprocals rather than dividing.
  1165.  */
  1166. #ifndef lbnDiv1_16
  1167. BNWORD16
  1168. lbnDiv1_16(BNWORD16 *q, BNWORD16 *rem, BNWORD16 const *n, unsigned len,
  1169. BNWORD16 d)
  1170. {
  1171. unsigned shift;
  1172. unsigned xlen;
  1173. BNWORD16 r;
  1174. BNWORD16 qhigh;
  1175. assert(len > 0);
  1176. assert(d);
  1177. if (len == 1) {
  1178. r = *n;
  1179. *rem = r%d;
  1180. return r/d;
  1181. }
  1182. shift = 0;
  1183. r = d;
  1184. xlen = 16;
  1185. while (xlen /= 2) {
  1186. if (r >> xlen)
  1187. r >>= xlen;
  1188. else
  1189. shift += xlen;
  1190. }
  1191. assert(d >> (16-1-shift) == 1);
  1192. d <<= shift;
  1193. BIGLITTLE(q -= len-1,q += len-1);
  1194. BIGLITTLE(n -= len,n += len);
  1195. r = BIGLITTLE(*n++,*--n);
  1196. if (r < d) {
  1197. qhigh = 0;
  1198. } else {
  1199. qhigh = r/d;
  1200. r %= d;
  1201. }
  1202. xlen = len;
  1203. while (--xlen)
  1204. r = lbnDiv21_16(BIGLITTLE(q++,--q), r, BIGLITTLE(*n++,*--n), d);
  1205. /*
  1206.  * Final correction for shift - shift the quotient up "shift"
  1207.  * bits, and merge in the extra bits of quotient.  Then reduce
  1208.  * the final remainder mod the real d.
  1209.  */
  1210. if (shift) {
  1211. d >>= shift;
  1212. qhigh = (qhigh << shift) | lbnLshift_16(q, len-1, shift);
  1213. BIGLITTLE(q[-1],*q) |= r/d;
  1214. r %= d;
  1215. }
  1216. *rem = r;
  1217. return qhigh;
  1218. }
  1219. #endif
  1220. /*
  1221.  * This function performs a "quick" modulus of a number with a divisor
  1222.  * d which is guaranteed to be at most sixteen bits, i.e. less than 65536.
  1223.  * This applies regardless of the word size the library is compiled with.
  1224.  *
  1225.  * This function is important to prime generation, for sieving.
  1226.  */
  1227. #ifndef lbnModQ_16
  1228. #if defined(BNWORD32) || !BN_SLOW_DIVIDE_32
  1229. unsigned
  1230. lbnModQ_16(BNWORD16 const *n, unsigned len, unsigned d)
  1231. {
  1232. BNWORD16 r;
  1233. if (!--len)
  1234. return BIGLITTLE(n[-1],n[0]) % d;
  1235. BIGLITTLE(n -= len,n += len);
  1236. r = BIGLITTLE(n[-1],n[0]);
  1237. do {
  1238. r = (BNWORD16)(((BNWORD32)r<<16 | BIGLITTLE(*n++,*--n)) % d);
  1239. } while (--len);
  1240. return r;
  1241. }
  1242. #elif 16 >= 0x20
  1243. /*
  1244.  * If the single word size can hold 65535*65536, then this function
  1245.  * is avilable.
  1246.  */
  1247. #ifndef highhalf
  1248. #define highhalf(x) ( (x) >> 16/2 )
  1249. #define lowhalf(x) ( (x) & ((1 << 16/2)-1) )
  1250. #endif
  1251. unsigned
  1252. lbnModQ_16(BNWORD16 const *n, unsigned len, unsigned d)
  1253. {
  1254. BNWORD16 r, x;
  1255. BIGLITTLE(n -= len,n += len);
  1256. r = BIGLITTLE(*n++,*--n);
  1257. while (--len) {
  1258. x = BIGLITTLE(*n++,*--n);
  1259. r = (r%d << 16/2) | highhalf(x);
  1260. r = (r%d << 16/2) | lowhalf(x);
  1261. }
  1262. return r%d;
  1263. }
  1264. #else
  1265. /* Default case - use lbnDiv21_16 */
  1266. unsigned
  1267. lbnModQ_16(BNWORD16 const *n, unsigned len, unsigned d)
  1268. {
  1269. unsigned i, shift;
  1270. BNWORD16 r;
  1271. BNWORD16 q;
  1272. assert(len > 0);
  1273. shift = 0;
  1274. r = d;
  1275. i = 16;
  1276. while (i /= 2) {
  1277. if (r >> i)
  1278. r >>= i;
  1279. else
  1280. shift += i;
  1281. }
  1282. assert(d >> (16-1-shift) == 1);
  1283. d <<= shift;
  1284. BIGLITTLE(n -= len,n += len);
  1285. r = BIGLITTLE(*n++,*--n);
  1286. if (r >= d)
  1287. r %= d;
  1288. while (--len)
  1289. r = lbnDiv21_16(&q, r, BIGLITTLE(*n++,*--n), d);
  1290. /*
  1291.  * Final correction for shift - shift the quotient up "shift"
  1292.  * bits, and merge in the extra bits of quotient.  Then reduce
  1293.  * the final remainder mod the real d.
  1294.  */
  1295. if (shift)
  1296. r %= d >> shift;
  1297. return r;
  1298. }
  1299. #endif
  1300. #endif /* lbnModQ_16 */
  1301. /*
  1302.  * Reduce n mod d and return the quotient.  That is, find:
  1303.  * q = n / d;
  1304.  * n = n % d;
  1305.  * d is altered during the execution of this subroutine by normalizing it.
  1306.  * It must already have its most significant word non-zero; it is shifted
  1307.  * so its most significant bit is non-zero.
  1308.  *
  1309.  * The quotient q is nlen-dlen+1 words long.  To make it possible to
  1310.  * overlap the quptient with the input (you can store it in the high dlen
  1311.  * words), the high word of the quotient is *not* stored, but is returned.
  1312.  * (If all you want is the remainder, you don't care about it, anyway.)
  1313.  *
  1314.  * This uses algorithm D from Knuth (4.3.1), except that we do binary
  1315.  * (shift) normalization of the divisor.  This is hairy!
  1316.  *
  1317.  * The overall operation is as follows ("top" and "up" refer to the
  1318.  * most significant end of the number; "bottom" and "down", the least):
  1319.  *
  1320.  * - Shift the divisor up until the most significant bit is set.
  1321.  * - Shift the dividend up the same amount.  This will produce the
  1322.  *   correct quotient, and the remainder can be recovered by shifting
  1323.  *   it back down the same number of bits.  This may produce an overflow
  1324.  *   word, but the word is always strictly less than the most significant
  1325.  *   divisor word.
  1326.  * - Estimate the first quotient digit qhat:
  1327.  *   - First take the top two words (one of which is the overflow) of the
  1328.  *     dividend and divide by the top word of the divisor:
  1329.  *     qhat = (nh,nm)/dh.  This qhat is >= the correct quotient digit
  1330.  *     and, since dh is normalized, it is at most two over.
  1331.  *   - Second, correct by comparing the top three words.  If
  1332.  *     (dh,dl) * qhat > (nh,nm,ml), decrease qhat and try again.
  1333.  *     The second iteration can be simpler because there can't be a third.
  1334.  *     The computation can be simplified by subtracting dh*qhat from
  1335.  *     both sides, suitably shifted.  This reduces the left side to
  1336.  *     dl*qhat.  On the right, (nh,nm)-dh*qhat is simply the
  1337.  *     remainder r from (nh,nm)%dh, so the right is (r,nl).
  1338.  *     This produces qhat that is almost always correct and at
  1339.  *     most (prob ~ 2/2^16) one too high.
  1340.  * - Subtract qhat times the divisor (suitably shifted) from the dividend.
  1341.  *   If there is a borrow, qhat was wrong, so decrement it
  1342.  *   and add the divisor back in (once).
  1343.  * - Store the final quotient digit qhat in the quotient array q.
  1344.  *
  1345.  * Repeat the quotient digit computation for successive digits of the
  1346.  * quotient until the whole quotient has been computed.  Then shift the
  1347.  * divisor and the remainder down to correct for the normalization.
  1348.  *
  1349.  * TODO: Special case 2-word divisors.
  1350.  * TODO: Use reciprocals rather than dividing.
  1351.  */
  1352. #ifndef divn_16
  1353. BNWORD16
  1354. lbnDiv_16(BNWORD16 *q, BNWORD16 *n, unsigned nlen, BNWORD16 *d, unsigned dlen)
  1355. {
  1356. BNWORD16 nh,nm,nl; /* Top three words of the dividend */
  1357. BNWORD16 dh,dl; /* Top two words of the divisor */
  1358. BNWORD16 qhat; /* Extimate of quotient word */
  1359. BNWORD16 r; /* Remainder from quotient estimate division */
  1360. BNWORD16 qhigh; /* High word of quotient */
  1361. unsigned i; /* Temp */
  1362. unsigned shift; /* Bits shifted by normalization */
  1363. unsigned qlen = nlen-dlen; /* Size of quotient (less 1) */
  1364. #ifdef mul16_ppmm
  1365. BNWORD16 t16;
  1366. #elif defined(BNWORD32)
  1367. BNWORD32 t32;
  1368. #else /* use lbnMulN1_16 */
  1369. BNWORD16 t2[2];
  1370. #define t2high BIGLITTLE(t2[0],t2[1])
  1371. #define t2low BIGLITTLE(t2[1],t2[0])
  1372. #endif
  1373. assert(dlen);
  1374. assert(nlen >= dlen);
  1375. /*
  1376.  * Special cases for short divisors.  The general case uses the
  1377.  * top top 2 digits of the divisor (d) to estimate a quotient digit,
  1378.  * so it breaks if there are fewer digits available.  Thus, we need
  1379.  * special cases for a divisor of length 1.  A divisor of length
  1380.  * 2 can have a *lot* of administrivia overhead removed removed,
  1381.  * so it's probably worth special-casing that case, too.
  1382.  */
  1383. if (dlen == 1)
  1384. return lbnDiv1_16(q, BIGLITTLE(n-1,n), n, nlen,
  1385.                   BIGLITTLE(d[-1],d[0]));
  1386. #if 0
  1387. /*
  1388.  * @@@ This is not yet written...  The general loop will do,
  1389.  * albeit less efficiently
  1390.  */
  1391. if (dlen == 2) {
  1392. /*
  1393.  * divisor two digits long:
  1394.  * use the 3/2 technique from Knuth, but we know
  1395.  * it's exact.
  1396.  */
  1397. dh = BIGLITTLE(d[-1],d[0]);
  1398. dl = BIGLITTLE(d[-2],d[1]);
  1399. shift = 0;
  1400. if ((sh & ((BNWORD16)1 << 16-1-shift)) == 0) {
  1401. do {
  1402. shift++;
  1403. } while (dh & (BNWORD16)1<<16-1-shift) == 0);
  1404. dh = dh << shift | dl >> (16-shift);
  1405. dl <<= shift;
  1406. }
  1407. for (shift = 0; (dh & (BNWORD16)1 << 16-1-shift)) == 0; shift++)
  1408. ;
  1409. if (shift) {
  1410. }
  1411. dh = dh << shift | dl >> (16-shift);
  1412. shift = 0;
  1413. while (dh 
  1414. }
  1415. #endif
  1416. dh = BIGLITTLE(*(d-dlen),*(d+(dlen-1)));
  1417. assert(dh);
  1418. /* Normalize the divisor */
  1419. shift = 0;
  1420. r = dh;
  1421. i = 16;
  1422. while (i /= 2) {
  1423. if (r >> i)
  1424. r >>= i;
  1425. else
  1426. shift += i;
  1427. }
  1428. nh = 0;
  1429. if (shift) {
  1430. lbnLshift_16(d, dlen, shift);
  1431. dh = BIGLITTLE(*(d-dlen),*(d+(dlen-1)));
  1432. nh = lbnLshift_16(n, nlen, shift);
  1433. }
  1434. /* Assert that dh is now normalized */
  1435. assert(dh >> (16-1));
  1436. /* Also get the second-most significant word of the divisor */
  1437. dl = BIGLITTLE(*(d-(dlen-1)),*(d+(dlen-2)));
  1438. /*
  1439.  * Adjust pointers: n to point to least significant end of first
  1440.  * first subtract, and q to one the most-significant end of the
  1441.  * quotient array.
  1442.  */
  1443. BIGLITTLE(n -= qlen,n += qlen);
  1444. BIGLITTLE(q -= qlen,q += qlen);
  1445. /* Fetch the most significant stored word of the dividend */
  1446. nm = BIGLITTLE(*(n-dlen),*(n+(dlen-1)));
  1447. /*
  1448.  * Compute the first digit of the quotient, based on the
  1449.  * first two words of the dividend (the most significant of which
  1450.  * is the overflow word h).
  1451.  */
  1452. if (nh) {
  1453. assert(nh < dh);
  1454. r = lbnDiv21_16(&qhat, nh, nm, dh);
  1455. } else if (nm >= dh) {
  1456. qhat = nm/dh;
  1457. r = nm % dh;
  1458. } else { /* Quotient is zero */
  1459. qhigh = 0;
  1460. goto divloop;
  1461. }
  1462. /* Now get the third most significant word of the dividend */
  1463. nl = BIGLITTLE(*(n-(dlen-1)),*(n+(dlen-2)));
  1464. /*
  1465.  * Correct qhat, the estimate of quotient digit.
  1466.  * qhat can only be high, and at most two words high,
  1467.  * so the loop can be unrolled and abbreviated.
  1468.  */
  1469. #ifdef mul16_ppmm
  1470. mul16_ppmm(nm, t16, qhat, dl);
  1471. if (nm > r || (nm == r && t16 > nl)) {
  1472. /* Decrement qhat and adjust comparison parameters */
  1473. qhat--;
  1474. if ((r += dh) >= dh) {
  1475. nm -= (t16 < dl);
  1476. t16 -= dl;
  1477. if (nm > r || (nm == r && t16 > nl))
  1478. qhat--;
  1479. }
  1480. }
  1481. #elif defined(BNWORD32)
  1482. t32 = (BNWORD32)qhat * dl;
  1483. if (t32 > ((BNWORD32)r << 16) + nl) {
  1484. /* Decrement qhat and adjust comparison parameters */
  1485. qhat--;
  1486. if ((r += dh) > dh) {
  1487. t32 -= dl;
  1488. if (t32 > ((BNWORD32)r << 16) + nl)
  1489. qhat--;
  1490. }
  1491. }
  1492. #else /* Use lbnMulN1_16 */
  1493. lbnMulN1_16(BIGLITTLE(t2+2,t2), &dl, 1, qhat);
  1494. if (t2high > r || (t2high == r && t2low > nl)) {
  1495. /* Decrement qhat and adjust comparison parameters */
  1496. qhat--;
  1497. if ((r += dh) >= dh) {
  1498. t2high -= (t2low < dl);
  1499. t2low -= dl;
  1500. if (t2high > r || (t2high == r && t2low > nl))
  1501. qhat--;
  1502. }
  1503. }
  1504. #endif
  1505. /* Do the multiply and subtract */
  1506. r = lbnMulSub1_16(n, d, dlen, qhat);
  1507. /* If there was a borrow, add back once. */
  1508. if (r > nh) { /* Borrow? */
  1509. (void)lbnAddN_16(n, d, dlen);
  1510. qhat--;
  1511. }
  1512. /* Remember the first quotient digit. */
  1513. qhigh = qhat;
  1514. /* Now, the main division loop: */
  1515. divloop:
  1516. while (qlen--) {
  1517. /* Advance n */
  1518. nh = BIGLITTLE(*(n-dlen),*(n+(dlen-1)));
  1519. BIGLITTLE(++n,--n);
  1520. nm = BIGLITTLE(*(n-dlen),*(n+(dlen-1)));
  1521. if (nh == dh) {
  1522. qhat = ~(BNWORD16)0;
  1523. /* Optimized computation of r = (nh,nm) - qhat * dh */
  1524. r = nh + nm;
  1525. if (r < nh)
  1526. goto subtract;
  1527. } else {
  1528. assert(nh < dh);
  1529. r = lbnDiv21_16(&qhat, nh, nm, dh);
  1530. }
  1531. nl = BIGLITTLE(*(n-(dlen-1)),*(n+(dlen-2)));
  1532. #ifdef mul16_ppmm
  1533. mul16_ppmm(nm, t16, qhat, dl);
  1534. if (nm > r || (nm == r && t16 > nl)) {
  1535. /* Decrement qhat and adjust comparison parameters */
  1536. qhat--;
  1537. if ((r += dh) >= dh) {
  1538. nm -= (t16 < dl);
  1539. t16 -= dl;
  1540. if (nm > r || (nm == r && t16 > nl))
  1541. qhat--;
  1542. }
  1543. }
  1544. #elif defined(BNWORD32)
  1545. t32 = (BNWORD32)qhat * dl;
  1546. if (t32 > ((BNWORD32)r<<16) + nl) {
  1547. /* Decrement qhat and adjust comparison parameters */
  1548. qhat--;
  1549. if ((r += dh) >= dh) {
  1550. t32 -= dl;
  1551. if (t32 > ((BNWORD32)r << 16) + nl)
  1552. qhat--;
  1553. }
  1554. }
  1555. #else /* Use lbnMulN1_16 */
  1556. lbnMulN1_16(BIGLITTLE(t2+2,t2), &dl, 1, qhat);
  1557. if (t2high > r || (t2high == r && t2low > nl)) {
  1558. /* Decrement qhat and adjust comparison parameters */
  1559. qhat--;
  1560. if ((r += dh) >= dh) {
  1561. t2high -= (t2low < dl);
  1562. t2low -= dl;
  1563. if (t2high > r || (t2high == r && t2low > nl))
  1564. qhat--;
  1565. }
  1566. }
  1567. #endif
  1568. /*
  1569.  * As a point of interest, note that it is not worth checking
  1570.  * for qhat of 0 or 1 and installing special-case code.  These
  1571.  * occur with probability 2^-16, so spending 1 cycle to check
  1572.  * for them is only worth it if we save more than 2^15 cycles,
  1573.  * and a multiply-and-subtract for numbers in the 1024-bit
  1574.  * range just doesn't take that long.
  1575.  */
  1576. subtract:
  1577. /*
  1578.  * n points to the least significant end of the substring
  1579.  * of n to be subtracted from.  qhat is either exact or
  1580.  * one too large.  If the subtract gets a borrow, it was
  1581.  * one too large and the divisor is added back in.  It's
  1582.  * a dlen+1 word add which is guaranteed to produce a
  1583.  * carry out, so it can be done very simply.
  1584.  */
  1585. r = lbnMulSub1_16(n, d, dlen, qhat);
  1586. if (r > nh) { /* Borrow? */
  1587. (void)lbnAddN_16(n, d, dlen);
  1588. qhat--;
  1589. }
  1590. /* Store the quotient digit */
  1591. BIGLITTLE(*q++,*--q) = qhat;
  1592. }
  1593. /* Tah dah! */
  1594. if (shift) {
  1595. lbnRshift_16(d, dlen, shift);
  1596. lbnRshift_16(n, dlen, shift);
  1597. }
  1598. return qhigh;
  1599. }
  1600. #endif
  1601. /*
  1602.  * Find the negative multiplicative inverse of x (x must be odd!) modulo 2^16.
  1603.  *
  1604.  * This just performs Newton's iteration until it gets the
  1605.  * inverse.  The initial estimate is always correct to 3 bits, and
  1606.  * sometimes 4.  The number of valid bits doubles each iteration.
  1607.  * (To prove it, assume x * y == 1 (mod 2^n), and introduce a variable
  1608.  * for the error mod 2^2n.  x * y == 1 + k*2^n (mod 2^2n) and follow
  1609.  * the iteration through.)
  1610.  */
  1611. #ifndef lbnMontInv1_16
  1612. BNWORD16
  1613. lbnMontInv1_16(BNWORD16 const x)
  1614. {
  1615.         BNWORD16 y = x, z;
  1616. assert(x & 1);
  1617.  
  1618.         while ((z = x*y) != 1)
  1619.                 y *= 2 - z;
  1620.         return -y;
  1621. }
  1622. #endif /* !lbnMontInv1_16 */
  1623. #if defined(BNWORD32) && PRODUCT_SCAN
  1624. /*
  1625.  * Test code for product-scanning Montgomery reduction.
  1626.  * This seems to slow the C code down rather than speed it up.
  1627.  *
  1628.  * The first loop computes the Montgomery multipliers, storing them over
  1629.  * the low half of the number n.
  1630.  *
  1631.  * The second half multiplies the upper half, adding in the modulus
  1632.  * times the Montgomery multipliers.  The results of this multiply
  1633.  * are stored.
  1634.  */
  1635. void
  1636. lbnMontReduce_16(BNWORD16 *n, BNWORD16 const *mod, unsigned mlen, BNWORD16 inv)
  1637. {
  1638. BNWORD32 x, y;
  1639. BNWORD16 const *pm;
  1640. BNWORD16 *pn;
  1641. BNWORD16 t;
  1642. unsigned carry;
  1643. unsigned i, j;
  1644. /* Special case of zero */
  1645. if (!mlen)
  1646. return;
  1647. /* Pass 1 - compute Montgomery multipliers */
  1648. /* First iteration can have certain simplifications. */
  1649. t = BIGLITTLE(n[-1],n[0]);
  1650. x = t;
  1651. t *= inv;
  1652. BIGLITTLE(n[-1], n[0]) = t;
  1653. x += (BNWORD32)t * BIGLITTLE(mod[-1],mod[0]); /* Can't overflow */
  1654. assert((BNWORD16)x == 0);
  1655. x = x >> 16;
  1656. for (i = 1; i < mlen; i++) {
  1657. carry = 0;
  1658. pn = n;
  1659. pm = BIGLITTLE(mod-i-1,mod+i+1);
  1660. for (j = 0; j < i; j++) {
  1661. y = (BNWORD32)BIGLITTLE(*--pn * *pm++, *pn++ * *--pm);
  1662. x += y;
  1663. carry += (x < y);
  1664. }
  1665. assert(BIGLITTLE(pn == n-i, pn == n+i));
  1666. y = t = BIGLITTLE(pn[-1], pn[0]);
  1667. x += y;
  1668. carry += (x < y);
  1669. BIGLITTLE(pn[-1], pn[0]) = t = inv * (BNWORD16)x;
  1670. assert(BIGLITTLE(pm == mod-1, pm == mod+1));
  1671. y = (BNWORD32)t * BIGLITTLE(pm[0],pm[-1]);
  1672. x += y;
  1673. carry += (x < y);
  1674. assert((BNWORD16)x == 0);
  1675. x = x >> 16 | (BNWORD32)carry << 16;
  1676. }
  1677. BIGLITTLE(n -= mlen, n += mlen);
  1678. /* Pass 2 - compute upper words and add to n */
  1679. for (i = 1; i < mlen; i++) {
  1680. carry = 0;
  1681. pm = BIGLITTLE(mod-i,mod+i);
  1682. pn = n;
  1683. for (j = i; j < mlen; j++) {
  1684. y = (BNWORD32)BIGLITTLE(*--pm * *pn++, *pm++ * *--pn);
  1685. x += y;
  1686. carry += (x < y);
  1687. }
  1688. assert(BIGLITTLE(pm == mod-mlen, pm == mod+mlen));
  1689. assert(BIGLITTLE(pn == n+mlen-i, pn == n-mlen+i));
  1690. y = t = BIGLITTLE(*(n-i),*(n+i-1));
  1691. x += y;
  1692. carry += (x < y);
  1693. BIGLITTLE(*(n-i),*(n+i-1)) = (BNWORD16)x;
  1694. x = (x >> 16) | (BNWORD32)carry << 16;
  1695. }
  1696. /* Last round of second half, simplified. */
  1697. t = BIGLITTLE(*(n-mlen),*(n+mlen-1));
  1698. x += t;
  1699. BIGLITTLE(*(n-mlen),*(n+mlen-1)) = (BNWORD16)x;
  1700. carry = (unsigned)(x >> 16);
  1701. while (carry)
  1702. carry -= lbnSubN_16(n, mod, mlen);
  1703. while (lbnCmp_16(n, mod, mlen) >= 0)
  1704. (void)lbnSubN_16(n, mod, mlen);
  1705. }
  1706. #define lbnMontReduce_16 lbnMontReduce_16
  1707. #endif
  1708. /*
  1709.  * Montgomery reduce n, modulo mod.  This reduces modulo mod and divides
  1710.  * by 2^(16*mlen).  I'll fill in an explanation of Montgomery representation
  1711.  * later.  Returns the result in the *top* n words of the argument n.
  1712.  * This is ready for another multiplication using mulnn.
  1713.  * 
  1714.  * TODO: Change to a full inverse and use Karatsuba's multiplication
  1715.  * rather than this word-at-a-time.
  1716.  */
  1717. #ifndef lbnMontReduce_16
  1718. void
  1719. lbnMontReduce_16(BNWORD16 *n, BNWORD16 const *mod, unsigned const mlen,
  1720.                 BNWORD16 inv)
  1721. {
  1722. BNWORD16 t;
  1723. BNWORD16 c = 0;
  1724. unsigned len = mlen;
  1725. /* inv must be the negative inverse of mod's least significant word */
  1726. assert((BNWORD16)(inv * BIGLITTLE(mod[-1],mod[0])) == (BNWORD16)-1);
  1727. assert(len);
  1728. do {
  1729. t = lbnMulAdd1_16(n, mod, mlen, inv * BIGLITTLE(n[-1],n[0]));
  1730. c += lbnAdd1_16(BIGLITTLE(n-mlen,n+mlen), len, t);
  1731. BIGLITTLE(--n,++n);
  1732. } while (--len);
  1733. /*
  1734.  * All that adding can cause an overflow past the modulus size,
  1735.  * but it's unusual, and never by much, so a subtraction loop
  1736.  * is the right way to deal with it.
  1737.  * This subtraction happens infrequently - I've only ever seen it
  1738.  * invoked once per reduction, and then just under 22.5% of the time.
  1739.  */
  1740. while (c)
  1741. c -= lbnSubN_16(n, mod, mlen);
  1742. while (lbnCmp_16(n, mod, mlen) >= 0)
  1743. (void)lbnSubN_16(n, mod, mlen);
  1744. }
  1745. #endif /* !lbnMontReduce_16 */
  1746. /*
  1747.  * A couple of helpers that you might want to implement atomically
  1748.  * in asm sometime.
  1749.  */
  1750. #ifndef lbnMontMul_16
  1751. /*
  1752.  * Multiply "num1" by "num2", modulo "mod", all of length "len", and
  1753.  * place the result in the high half of "prod".  "inv" is the inverse
  1754.  * of the least-significant word of the modulus, modulo 2^16.
  1755.  * This uses numbers in Montgomery form.  Reduce using "len" and "inv".
  1756.  *
  1757.  * This is implemented as a macro to win on compilers that don't do
  1758.  * inlining, since it's so trivial.
  1759.  */
  1760. #define lbnMontMul_16(prod, n1, n2, mod, len, inv) 
  1761. (lbnMulX_16(prod, n1, n2, len), lbnMontReduce_16(prod, mod, len, inv))
  1762. #endif /* !lbnMontMul_16 */
  1763. #ifndef lbnMontSquare_16
  1764. /*
  1765.  * Square "num", modulo "mod", both of length "len", and place the result
  1766.  * in the high half of "prod".  "inv" is the inverse of the least-significant
  1767.  * word of the modulus, modulo 2^16.
  1768.  * This uses numbers in Montgomery form.  Reduce using "len" and "inv".
  1769.  *
  1770.  * This is implemented as a macro to win on compilers that don't do
  1771.  * inlining, since it's so trivial.
  1772.  */
  1773. #define lbnMontSquare_16(prod, n, mod, len, inv) 
  1774. (lbnSquare_16(prod, n, len), lbnMontReduce_16(prod, mod, len, inv))
  1775. #endif /* !lbnMontSquare_16 */
  1776. /*
  1777.  * Convert a number to Montgomery form - requires mlen + nlen + 1 words
  1778.  * of memory in "n".
  1779.  */
  1780. void
  1781. lbnToMont_16(BNWORD16 *n, unsigned nlen, BNWORD16 *mod, unsigned mlen)
  1782. {
  1783. /* Move n up "mlen" words */
  1784. lbnCopy_16(BIGLITTLE(n-mlen,n+mlen), n, nlen);
  1785. lbnZero_16(n, mlen);
  1786. /* Do the division - dump the quotient in the high-order words */
  1787. (void)lbnDiv_16(BIGLITTLE(n-mlen,n+mlen), n, mlen+nlen, mod, mlen);
  1788. }
  1789. /*
  1790.  * Convert from Montgomery form.  Montgomery reduction is all that is
  1791.  * needed.
  1792.  */
  1793. void
  1794. lbnFromMont_16(BNWORD16 *n, BNWORD16 *mod, unsigned len)
  1795. {
  1796. /* Zero the high words of n */
  1797. lbnZero_16(BIGLITTLE(n-len,n+len), len);
  1798. lbnMontReduce_16(n, mod, len, lbnMontInv1_16(BIGLITTLE(mod[-1],mod[0])));
  1799. /* Move n down len words */
  1800. lbnCopy_16(n, BIGLITTLE(n-len,n+len), len);
  1801. }
  1802. /*
  1803.  * The windowed exponentiation algorithm, precomputes a table of odd
  1804.  * powers of n up to 2^k.  It takes 2^(k-1)-1 multiplies to compute
  1805.  * the table, and (e-1)/(k+1) multiplies (on average) to perform the
  1806.  * exponentiation.  To minimize the sum, k must vary with e.
  1807.  * The optimal window sizes vary with the exponent length.  Here are
  1808.  * some selected values and the boundary cases.
  1809.  * (An underscore _ has been inserted into some of the numbers to ensure
  1810.  * that magic strings like 16 do not appear in this table.  It should be
  1811.  * ignored.)
  1812.  *
  1813.  * At e =    1 bits, k= 1 (0.000000) is best.
  1814.  * At e =    2 bits, k= 1 (0.500000) is best.
  1815.  * At e =    4 bits, k= 1 (1.500000) is best.
  1816.  * At e =    8 bits, k= 2 (3.333333) < k =  1 (3.500000)
  1817.  * At e =  1_6 bits, k= 2 (6.000000) is best.
  1818.  * At e =   26 bits, k= 3 (9.250000) < k =  2 (9.333333)
  1819.  * At e =  3_2 bits, k= 3 (10.750000) is best.
  1820.  * At e =  6_4 bits, k= 3 (18.750000) is best.
  1821.  * At e =   82 bits, k= 4 (23.200000) < k =  3 (23.250000)
  1822.  * At e =  128 bits, k= 4 (3_2.400000) is best.
  1823.  * At e =  242 bits, k= 5 (55.1_66667) < k =  4 (55.200000)
  1824.  * At e =  256 bits, k= 5 (57.500000) is best.
  1825.  * At e =  512 bits, k= 5 (100.1_66667) is best.
  1826.  * At e =  674 bits, k= 6 (127.142857) < k =  5 (127.1_66667)
  1827.  * At e = 1024 bits, k= 6 (177.142857) is best.
  1828.  * At e = 1794 bits, k= 7 (287.125000) < k =  6 (287.142857)
  1829.  * At e = 2048 bits, k= 7 (318.875000) is best.
  1830.  * At e = 4096 bits, k= 7 (574.875000) is best.
  1831.  *
  1832.  * The numbers in parentheses are the expected number of multiplications
  1833.  * needed to do the computation.  The normal russian-peasant modular
  1834.  * exponentiation technique always uses (e-1)/2.  For exponents as
  1835.  * small as 192 bits (below the range of current factoring algorithms),
  1836.  * half of the multiplies are eliminated, 45.2 as opposed to the naive
  1837.  * 95.5.  Counting the 191 squarings as 3/4 a multiply each (squaring
  1838.  * proper is just over half of multiplying, but the Montgomery
  1839.  * reduction in each case is also a multiply), that's 143.25
  1840.  * multiplies, for totals of 188.45 vs. 238.75 - a 21% savings.
  1841.  * For larger exponents (like 512 bits), it's 483.92 vs. 639.25, a
  1842.  * 24.3% savings.  It asymptotically approaches 25%.
  1843.  *
  1844.  * Given that exponents for which k>7 are useful are uncommon,
  1845.  * a fixed size table for k <= 7 is used for simplicity.
  1846.  * k = 8 is uzeful at 4610 bits, k = 9 at 11522 bits.
  1847.  *
  1848.  * The basic number of squarings needed is e-1, although a k-bit
  1849.  * window (for k > 1) can save, on average, k-2 of those, too.
  1850.  * That savings currently isn't counted here.  It would drive the
  1851.  * crossover points slightly lower.
  1852.  * (Actually, this win is also reduced in the DoubleExpMod case,
  1853.  * meaning we'd have to split the tables.  Except for that, the
  1854.  * multiples by powers of the two bases are independent, so
  1855.  * the same logic applies to each as the single case.)
  1856.  *
  1857.  * Table entry i is the largest number of bits in an exponent to
  1858.  * process with a window size of i+1.  So the window never goes above 7
  1859.  * bits, requiring 2^(7-1) = 0x40 precomputed multiples.
  1860.  */
  1861. #define BNEXPMOD_MAX_WINDOW 7
  1862. static unsigned const bnExpModThreshTable[BNEXPMOD_MAX_WINDOW] = {
  1863. 7, 25, 81, 241, 673, 1793, (unsigned)-1
  1864. };
  1865. /*
  1866.  * Perform modular exponentiation, as fast as possible!  This uses
  1867.  * Montgomery reduction, optimized squaring, and windowed exponentiation.
  1868.  * The modulus "mod" MUST be odd!
  1869.  *
  1870.  * This returns 0 on success, -1 on out of memory.
  1871.  *
  1872.  * The window algorithm:
  1873.  * The idea is to keep a running product of b1 = n^(high-order bits of exp),
  1874.  * and then keep appending exponent bits to it.  The following patterns
  1875.  * apply to a 3-bit window (k = 3):
  1876.  * To append   0: square
  1877.  * To append   1: square, multiply by n^1
  1878.  * To append  10: square, multiply by n^1, square
  1879.  * To append  11: square, square, multiply by n^3
  1880.  * To append 100: square, multiply by n^1, square, square
  1881.  * To append 101: square, square, square, multiply by n^5
  1882.  * To append 110: square, square, multiply by n^3, square
  1883.  * To append 111: square, square, square, multiply by n^7
  1884.  *
  1885.  * Since each pattern involves only one multiply, the longer the pattern
  1886.  * the better, except that a 0 (no multiplies) can be appended directly.
  1887.  * We precompute a table of odd powers of n, up to 2^k, and can then
  1888.  * multiply k bits of exponent at a time.  Actually, assuming random
  1889.  * exponents, there is on average one zero bit between needs to
  1890.  * multiply (1/2 of the time there's none, 1/4 of the time there's 1,
  1891.  * 1/8 of the time, there's 2, 1/16 of the time, there's 3, etc.), so
  1892.  * you have to do one multiply per k+1 bits of exponent.
  1893.  *
  1894.  * The loop walks down the exponent, squaring the result buffer as
  1895.  * it goes.  There is a wbits+1 bit lookahead buffer, buf, that is
  1896.  * filled with the upcoming exponent bits.  (What is read after the
  1897.  * end of the exponent is unimportant, but it is filled with zero here.)
  1898.  * When the most-significant bit of this buffer becomes set, i.e.
  1899.  * (buf & tblmask) != 0, we have to decide what pattern to multiply
  1900.  * by, and when to do it.  We decide, remember to do it in future
  1901.  * after a suitable number of squarings have passed (e.g. a pattern
  1902.  * of "100" in the buffer requires that we multiply by n^1 immediately;
  1903.  * a pattern of "110" calls for multiplying by n^3 after one more
  1904.  * squaring), clear the buffer, and continue.
  1905.  *
  1906.  * When we start, there is one more optimization: the result buffer
  1907.  * is implcitly one, so squaring it or multiplying by it can be
  1908.  * optimized away.  Further, if we start with a pattern like "100"
  1909.  * in the lookahead window, rather than placing n into the buffer
  1910.  * and then starting to square it, we have already computed n^2
  1911.  * to compute the odd-powers table, so we can place that into
  1912.  * the buffer and save a squaring.
  1913.  *
  1914.  * This means that if you have a k-bit window, to compute n^z,
  1915.  * where z is the high k bits of the exponent, 1/2 of the time
  1916.  * it requires no squarings.  1/4 of the time, it requires 1
  1917.  * squaring, ... 1/2^(k-1) of the time, it reqires k-2 squarings.
  1918.  * And the remaining 1/2^(k-1) of the time, the top k bits are a
  1919.  * 1 followed by k-1 0 bits, so it again only requires k-2
  1920.  * squarings, not k-1.  The average of these is 1.  Add that
  1921.  * to the one squaring we have to do to compute the table,
  1922.  * and you'll see that a k-bit window saves k-2 squarings
  1923.  * as well as reducing the multiplies.  (It actually doesn't
  1924.  * hurt in the case k = 1, either.)
  1925.  *
  1926.  * n must have mlen words allocated.  Although fewer may be in use
  1927.  * when n is passed in, all are in use on exit.
  1928.  */
  1929. int
  1930. lbnExpMod_16(BNWORD16 *result, BNWORD16 const *n, unsigned nlen,
  1931. BNWORD16 const *e, unsigned elen, BNWORD16 *mod, unsigned mlen)
  1932. {
  1933. BNWORD16 *table[1 << (BNEXPMOD_MAX_WINDOW-1)];
  1934. /* Table of odd powers of n */
  1935. unsigned ebits; /* Exponent bits */
  1936. unsigned wbits; /* Window size */
  1937. unsigned tblmask; /* Mask of exponentiation window */
  1938. BNWORD16 bitpos; /* Mask of current look-ahead bit */
  1939. unsigned buf; /* Buffer of exponent bits */
  1940. unsigned multpos; /* Where to do pending multiply */
  1941. BNWORD16 const *mult; /* What to multiply by */
  1942. unsigned i; /* Loop counter */
  1943. int isone; /* Flag: accum. is implicitly one */
  1944. BNWORD16 *a, *b; /* Working buffers/accumulators */
  1945. BNWORD16 *t; /* Pointer into the working buffers */
  1946. BNWORD16 inv; /* mod^-1 modulo 2^16 */
  1947. assert(mlen);
  1948. assert(nlen <= mlen);
  1949. /* First, a couple of trivial cases. */
  1950. elen = lbnNorm_16(e, elen);
  1951. if (!elen) {
  1952. /* x ^ 0 == 1 */
  1953. lbnZero_16(result, mlen);
  1954. BIGLITTLE(result[-1],result[0]) = 1;
  1955. return 0;
  1956. }
  1957. ebits = lbnBits_16(e, elen);
  1958. if (ebits == 1) {
  1959. /* x ^ 1 == x */
  1960. if (n != result)
  1961. lbnCopy_16(result, n, nlen);
  1962. if (mlen > nlen)
  1963. lbnZero_16(BIGLITTLE(result-nlen,result+nlen),
  1964.            mlen-nlen);
  1965. return 0;
  1966. }
  1967. /* Okay, now move the exponent pointer to the most-significant word */
  1968. e = BIGLITTLE(e-elen, e+elen-1);
  1969. /* Look up appropriate k-1 for the exponent - tblmask = 1<<(k-1) */
  1970. wbits = 0;
  1971. while (ebits > bnExpModThreshTable[wbits])
  1972. wbits++;
  1973. /* Allocate working storage: two product buffers and the tables. */
  1974. LBNALLOC(a, 2*mlen);
  1975. if (!a)
  1976. return -1;
  1977. LBNALLOC(b, 2*mlen);
  1978. if (!b) {
  1979. LBNFREE(a, 2*mlen);
  1980. return -1;
  1981. }
  1982. /* Convert to the appropriate table size: tblmask = 1<<(k-1) */
  1983. tblmask = 1u << wbits;
  1984. LBNALLOC(t, mlen);
  1985. if (!t) {
  1986. LBNFREE(b, 2*mlen);
  1987. LBNFREE(a, 2*mlen);
  1988. return -1;
  1989. }
  1990. /* We have the result buffer available, so use it. */
  1991. table[0] = result;
  1992. /*
  1993.  * Okay, we now have a minimal-sized table - expand it.
  1994.  * This is allowed to fail!  If so, scale back the table size
  1995.  * and proceed.
  1996.  */
  1997. for (i = 1; i < tblmask; i++) {
  1998. LBNALLOC(t, mlen);
  1999. if (!t) /* Out of memory!  Quit the loop. */
  2000. break;
  2001. table[i] = t;
  2002. }
  2003. /* If we stopped, with i < tblmask, shrink the tables appropriately */
  2004. while (tblmask > i) {
  2005. wbits--;
  2006. tblmask >>= 1;
  2007. }
  2008. /* Free up our overallocations */
  2009. while (--i > tblmask)
  2010. LBNFREE(table[i], mlen);
  2011. /* Okay, fill in the table */
  2012. /* Compute the necessary modular inverse */
  2013. inv = lbnMontInv1_16(mod[BIGLITTLE(-1,0)]); /* LSW of modulus */
  2014. /* Convert n to Montgomery form */
  2015. /* Move n up "mlen" words into a */
  2016. t = BIGLITTLE(a-mlen, a+mlen);
  2017. lbnCopy_16(t, n, nlen);
  2018. lbnZero_16(a, mlen);
  2019. /* Do the division - lose the quotient into the high-order words */
  2020. (void)lbnDiv_16(t, a, mlen+nlen, mod, mlen);
  2021. /* Copy into first table entry */
  2022. lbnCopy_16(table[0], a, mlen);
  2023. /* Square a into b */
  2024. lbnMontSquare_16(b, a, mod, mlen, inv);
  2025. /* Use high half of b to initialize the table */
  2026. t = BIGLITTLE(b-mlen, b+mlen);
  2027. for (i = 1; i < tblmask; i++) {
  2028. lbnMontMul_16(a, t, table[i-1], mod, mlen, inv);
  2029. lbnCopy_16(table[i], BIGLITTLE(a-mlen, a+mlen), mlen);
  2030. }
  2031. /* We might use b = n^2 later... */
  2032. /* Initialze the fetch pointer */
  2033. bitpos = (BNWORD16)1 << ((ebits-1) & (16-1)); /* Initialize mask */
  2034. /* This should point to the msbit of e */
  2035. assert((*e & bitpos) != 0);
  2036. /*
  2037.  * Pre-load the window.  Becuase the window size is
  2038.  * never larger than the exponent size, there is no need to
  2039.  * detect running off the end of e in here.
  2040.  *
  2041.  * The read-ahead is controlled by elen and the bitpos mask.
  2042.  * Note that this is *ahead* of ebits, which tracks the
  2043.  * most significant end of the window.  The purpose of this
  2044.  * initialization is to get the two wbits+1 bits apart,
  2045.  * like they should be.
  2046.  *
  2047.  * Note that bitpos and e1len together keep track of the
  2048.  * lookahead read pointer in the exponent that is used here.
  2049.  */
  2050. buf = 0;
  2051. for (i = 0; i <= wbits; i++) {
  2052. buf = (buf << 1) | ((*e & bitpos) != 0);
  2053. bitpos >>= 1;
  2054. if (!bitpos) {
  2055. BIGLITTLE(e++,e--);
  2056. bitpos = (BNWORD16)1 << (16-1);
  2057. elen--;
  2058. }
  2059. }
  2060. assert(buf & tblmask);
  2061. /*
  2062.  * Set the pending multiply positions to a location that will
  2063.  * never be encountered, thus ensuring that nothing will happen
  2064.  * until the need for a multiply appears and one is scheduled.
  2065.  */
  2066. multpos = ebits; /* A NULL value */
  2067. mult = 0; /* Force a crash if we use these */
  2068. /*
  2069.  * Okay, now begins the real work.  The first step is
  2070.  * slightly magic, so it's done outside the main loop,
  2071.  * but it's very similar to what's inside.
  2072.  */
  2073. ebits--; /* Start processing the first bit... */
  2074. isone = 1;
  2075. /*
  2076.  * This is just like the multiply in the loop, except that
  2077.  * - We know the msbit of buf is set, and
  2078.  * - We have the extra value n^2 floating around.
  2079.  * So, do the usual computation, and if the result is that
  2080.  * the buffer should be multiplied by n^1 immediately
  2081.  * (which we'd normally then square), we multiply it
  2082.  * (which reduces to a copy, which reduces to setting a flag)
  2083.  * by n^2 and skip the squaring.  Thus, we do the
  2084.  * multiply and the squaring in one step.
  2085.  */
  2086. assert(buf & tblmask);
  2087. multpos = ebits - wbits;
  2088. while ((buf & 1) == 0) {
  2089. buf >>= 1;
  2090. multpos++;
  2091. }
  2092. /* Intermediates can wrap, but final must NOT */
  2093. assert(multpos <= ebits);
  2094. mult = table[buf>>1];
  2095. buf = 0;
  2096. /* Special case: use already-computed value sitting in buffer */
  2097. if (multpos == ebits)
  2098. isone = 0;
  2099. /*
  2100.  * At this point, the buffer (which is the high half of b) holds
  2101.  * either 1 (implicitly, as the "isone" flag is set), or n^2.
  2102.  */
  2103. /*
  2104.  * The main loop.  The procedure is:
  2105.  * - Advance the window
  2106.  * - If the most-significant bit of the window is set,
  2107.  *   schedule a multiply for the appropriate time in the
  2108.  *   future (may be immediately)
  2109.  * - Perform any pending multiples
  2110.  * - Check for termination
  2111.  * - Square the buffer
  2112.  *
  2113.  * At any given time, the acumulated product is held in
  2114.  * the high half of b.
  2115.  */
  2116. for (;;) {
  2117. ebits--;
  2118. /* Advance the window */
  2119. assert(buf < tblmask);
  2120. buf <<= 1;
  2121. /*
  2122.  * This reads ahead of the current exponent position
  2123.  * (controlled by ebits), so we have to be able to read
  2124.  * past the lsb of the exponents without error.
  2125.  */
  2126. if (elen) {
  2127. buf |= ((*e & bitpos) != 0);
  2128. bitpos >>= 1;
  2129. if (!bitpos) {
  2130. BIGLITTLE(e++,e--);
  2131. bitpos = (BNWORD16)1 << (16-1);
  2132. elen--;
  2133. }
  2134. }
  2135. /* Examine the window for pending multiplies */
  2136. if (buf & tblmask) {
  2137. multpos = ebits - wbits;
  2138. while ((buf & 1) == 0) {
  2139. buf >>= 1;
  2140. multpos++;
  2141. }
  2142. /* Intermediates can wrap, but final must NOT */
  2143. assert(multpos <= ebits);
  2144. mult = table[buf>>1];
  2145. buf = 0;
  2146. }
  2147. /* If we have a pending multiply, do it */
  2148. if (ebits == multpos) {
  2149. /* Multiply by the table entry remembered previously */
  2150. t = BIGLITTLE(b-mlen, b+mlen);
  2151. if (isone) {
  2152. /* Multiply by 1 is a trivial case */
  2153. lbnCopy_16(t, mult, mlen);
  2154. isone = 0;
  2155. } else {
  2156. lbnMontMul_16(a, t, mult, mod, mlen, inv);
  2157. /* Swap a and b */
  2158. t = a; a = b; b = t;
  2159. }
  2160. }
  2161. /* Are we done? */
  2162. if (!ebits)
  2163. break;
  2164. /* Square the input */
  2165. if (!isone) {
  2166. t = BIGLITTLE(b-mlen, b+mlen);
  2167. lbnMontSquare_16(a, t, mod, mlen, inv);
  2168. /* Swap a and b */
  2169. t = a; a = b; b = t;
  2170. }
  2171. } /* for (;;) */
  2172. assert(!isone);
  2173. assert(!buf);
  2174. /* DONE! */
  2175. /* Convert result out of Montgomery form */
  2176. t = BIGLITTLE(b-mlen, b+mlen);
  2177. lbnCopy_16(b, t, mlen);
  2178. lbnZero_16(t, mlen);
  2179. lbnMontReduce_16(b, mod, mlen, inv);
  2180. lbnCopy_16(result, t, mlen);
  2181. /*
  2182.  * Clean up - free intermediate storage.
  2183.  * Do NOT free table[0], which is the result
  2184.  * buffer.
  2185.  */
  2186. while (--tblmask)
  2187. LBNFREE(table[tblmask], mlen);
  2188. LBNFREE(b, 2*mlen);
  2189. LBNFREE(a, 2*mlen);
  2190. return 0; /* Success */
  2191. }
  2192. /*
  2193.  * Compute and return n1^e1 * n2^e2 mod "mod".
  2194.  * result may be either input buffer, or something separate.
  2195.  * It must be "mlen" words long.
  2196.  *
  2197.  * There is a current position in the exponents, which is kept in e1bits.
  2198.  * (The exponents are swapped if necessary so e1 is the longer of the two.)
  2199.  * At any given time, the value in the accumulator is
  2200.  * n1^(e1>>e1bits) * n2^(e2>>e1bits) mod "mod".
  2201.  * As e1bits is counted down, this is updated, by squaring it and doing
  2202.  * any necessary multiplies.
  2203.  * To decide on the necessary multiplies, two windows, each w1bits+1 bits
  2204.  * wide, are maintained in buf1 and buf2, which read *ahead* of the
  2205.  * e1bits position (with appropriate handling of the case when e1bits
  2206.  * drops below w1bits+1).  When the most-significant bit of each windows
  2207.  * becomes set, indicating that something needs to be multiplied by
  2208.  * the accumulator or it will get out of sync, the window is examined
  2209.  * to see which power of n1 or n2 to multiply by, and when (possibly
  2210.  * later, if the power is greater than 1) the multiply should take
  2211.  * place.  Then the multiply and its location are remembered and the
  2212.  * window is cleared.
  2213.  *
  2214.  * If we had every power of n1 in the table, the multiply would always
  2215.  * be w1bits steps in the future.  But we only keep the odd powers,
  2216.  * so instead of waiting w1bits squarings and then multiplying
  2217.  * by n1^k, we wait w1bits-k squarings and multiply by n1.
  2218.  *
  2219.  * Actually, w2bits can be less than w1bits, but the window is the same
  2220.  * size, to make it easier to keep track of where we're reading.  The
  2221.  * appropriate number of low-order bits of the window are just ignored.
  2222.  */
  2223. int
  2224. lbnDoubleExpMod_16(BNWORD16 *result,
  2225.                    BNWORD16 const *n1, unsigned n1len,
  2226.                    BNWORD16 const *e1, unsigned e1len,
  2227.                    BNWORD16 const *n2, unsigned n2len,
  2228.                    BNWORD16 const *e2, unsigned e2len,
  2229.                    BNWORD16 *mod, unsigned mlen)
  2230. {
  2231. BNWORD16 *table1[1 << (BNEXPMOD_MAX_WINDOW-1)];
  2232. /* Table of odd powers of n1 */
  2233. BNWORD16 *table2[1 << (BNEXPMOD_MAX_WINDOW-1)];
  2234. /* Table of odd powers of n2 */
  2235. unsigned e1bits, e2bits; /* Exponent bits */
  2236. unsigned w1bits, w2bits; /* Window sizes */
  2237. unsigned tblmask; /* Mask of exponentiation window */
  2238. BNWORD16 bitpos; /* Mask of current look-ahead bit */
  2239. unsigned buf1, buf2; /* Buffer of exponent bits */
  2240. unsigned mult1pos, mult2pos; /* Where to do pending multiply */
  2241. BNWORD16 const *mult1, *mult2; /* What to multiply by */
  2242. unsigned i; /* Loop counter */
  2243. int isone; /* Flag: accum. is implicitly one */
  2244. BNWORD16 *a, *b; /* Working buffers/accumulators */
  2245. BNWORD16 *t; /* Pointer into the working buffers */
  2246. BNWORD16 inv; /* mod^-1 modulo 2^16 */
  2247. assert(mlen);
  2248. assert(n1len <= mlen);
  2249. assert(n2len <= mlen);
  2250. /* First, a couple of trivial cases. */
  2251. e1len = lbnNorm_16(e1, e1len);
  2252. e2len = lbnNorm_16(e2, e2len);
  2253. /* Ensure that the first exponent is the longer */
  2254. e1bits = lbnBits_16(e1, e1len);
  2255. e2bits = lbnBits_16(e2, e2len);
  2256. if (e1bits < e2bits) {
  2257. i = e1len; e1len = e2len; e2len = i;
  2258. i = e1bits; e1bits = e2bits; e2bits = i;
  2259. t = (BNWORD16 *)n1; n1 = n2; n2 = t; 
  2260. t = (BNWORD16 *)e1; e1 = e2; e2 = t; 
  2261. }
  2262. assert(e1bits >= e2bits);
  2263. /* Handle a trivial case */
  2264. if (!e2len)
  2265. return lbnExpMod_16(result, n1, n1len, e1, e1len, mod, mlen);
  2266. assert(e2bits);
  2267. /* The code below fucks up if the exponents aren't at least 2 bits */
  2268. if (e1bits == 1) {
  2269. assert(e2bits == 1);
  2270. LBNALLOC(a, n1len+n2len);
  2271. if (!a)
  2272. return -1;
  2273. lbnMul_16(a, n1, n1len, n2, n2len);
  2274. /* Do a direct modular reduction */
  2275. if (n1len + n2len >= mlen)
  2276. (void)lbnDiv_16(a+mlen, a, n1len+n2len, mod, mlen);
  2277. lbnCopy_16(result, a, mlen);
  2278. LBNFREE(a, n1len+n2len);
  2279. return 0;
  2280. }
  2281. /* Okay, now move the exponent pointers to the most-significant word */
  2282. e1 = BIGLITTLE(e1-e1len, e1+e1len-1);
  2283. e2 = BIGLITTLE(e2-e2len, e2+e2len-1);
  2284. /* Look up appropriate k-1 for the exponent - tblmask = 1<<(k-1) */
  2285. w1bits = 0;
  2286. while (e1bits > bnExpModThreshTable[w1bits])
  2287. w1bits++;
  2288. w2bits = 0;
  2289. while (e2bits > bnExpModThreshTable[w2bits])
  2290. w2bits++;
  2291. assert(w1bits >= w2bits);
  2292. /* Allocate working storage: two product buffers and the tables. */
  2293. LBNALLOC(a, 2*mlen);
  2294. if (!a)
  2295. return -1;
  2296. LBNALLOC(b, 2*mlen);
  2297. if (!b) {
  2298. LBNFREE(a, 2*mlen);
  2299. return -1;
  2300. }
  2301. /* Convert to the appropriate table size: tblmask = 1<<(k-1) */
  2302. tblmask = 1u << w1bits;
  2303. /* Use buf2 for its size, temporarily */
  2304. buf2 = 1u << w2bits;
  2305. LBNALLOC(t, mlen);
  2306. if (!t) {
  2307. LBNFREE(b, 2*mlen);
  2308. LBNFREE(a, 2*mlen);
  2309. return -1;
  2310. }
  2311. table1[0] = t;
  2312. table2[0] = result;
  2313. /*
  2314.  * Okay, we now have some minimal-sized tables - expand them.
  2315.  * This is allowed to fail!  If so, scale back the table sizes
  2316.  * and proceed.  We allocate both tables at the same time
  2317.  * so if it fails partway through, they'll both be a reasonable
  2318.  * size rather than one huge and one tiny.
  2319.  * When i passes buf2 (the number of entries in the e2 window,
  2320.  * which may be less than the number of entries in the e1 window),
  2321.  * stop allocating e2 space.
  2322.  */
  2323. for (i = 1; i < tblmask; i++) {
  2324. LBNALLOC(t, mlen);
  2325. if (!t) /* Out of memory!  Quit the loop. */
  2326. break;
  2327. table1[i] = t;
  2328. if (i < buf2) {
  2329. LBNALLOC(t, mlen);
  2330. if (!t) {
  2331. LBNFREE(table1[i], mlen);
  2332. break;
  2333. }
  2334. table2[i] = t;
  2335. }
  2336. }
  2337. /* If we stopped, with i < tblmask, shrink the tables appropriately */
  2338. while (tblmask > i) {
  2339. w1bits--;
  2340. tblmask >>= 1;
  2341. }
  2342. /* Free up our overallocations */
  2343. while (--i > tblmask) {
  2344. if (i < buf2)
  2345. LBNFREE(table2[i], mlen);
  2346. LBNFREE(table1[i], mlen);
  2347. }
  2348. /* And shrink the second window too, if needed */
  2349. if (w2bits > w1bits) {
  2350. w2bits = w1bits;
  2351. buf2 = tblmask;
  2352. }
  2353. /*
  2354.  * From now on, use the w2bits variable for the difference
  2355.  * between w1bits and w2bits.
  2356.  */
  2357. w2bits = w1bits-w2bits;
  2358. /* Okay, fill in the tables */
  2359. /* Compute the necessary modular inverse */
  2360. inv = lbnMontInv1_16(mod[BIGLITTLE(-1,0)]); /* LSW of modulus */
  2361. /* Convert n1 to Montgomery form */
  2362. /* Move n1 up "mlen" words into a */
  2363. t = BIGLITTLE(a-mlen, a+mlen);
  2364. lbnCopy_16(t, n1, n1len);
  2365. lbnZero_16(a, mlen);
  2366. /* Do the division - lose the quotient into the high-order words */
  2367. (void)lbnDiv_16(t, a, mlen+n1len, mod, mlen);
  2368. /* Copy into first table entry */
  2369. lbnCopy_16(table1[0], a, mlen);
  2370. /* Square a into b */
  2371. lbnMontSquare_16(b, a, mod, mlen, inv);
  2372. /* Use high half of b to initialize the first table */
  2373. t = BIGLITTLE(b-mlen, b+mlen);
  2374. for (i = 1; i < tblmask; i++) {
  2375. lbnMontMul_16(a, t, table1[i-1], mod, mlen, inv);
  2376. lbnCopy_16(table1[i], BIGLITTLE(a-mlen, a+mlen), mlen);
  2377. }
  2378. /* Convert n2 to Montgomery form */
  2379. t = BIGLITTLE(a-mlen, a+mlen);
  2380. /* Move n2 up "mlen" words into a */
  2381. lbnCopy_16(t, n2, n2len);
  2382. lbnZero_16(a, mlen);
  2383. /* Do the division - lose the quotient into the high-order words */
  2384. (void)lbnDiv_16(t, a, mlen+n2len, mod, mlen);
  2385. /* Copy into first table entry */
  2386. lbnCopy_16(table2[0], a, mlen);
  2387. /* Square it into a */
  2388. lbnMontSquare_16(a, table2[0], mod, mlen, inv);
  2389. /* Copy to b, low half */
  2390. lbnCopy_16(b, t, mlen);
  2391. /* Use b to initialize the second table */
  2392. for (i = 1; i < buf2; i++) {
  2393. lbnMontMul_16(a, b, table2[i-1], mod, mlen, inv);
  2394. lbnCopy_16(table2[i], t, mlen);
  2395. }
  2396. /*
  2397.  * Okay, a recap: at this point, the low part of b holds
  2398.  * n2^2, the high part holds n1^2, and the tables are
  2399.  * initialized with the odd powers of n1 and n2 from 1
  2400.  * through 2*tblmask-1 and 2*buf2-1.
  2401.  *
  2402.  * We might use those squares in b later, or we might not.
  2403.  */
  2404. /* Initialze the fetch pointer */
  2405. bitpos = (BNWORD16)1 << ((e1bits-1) & (16-1)); /* Initialize mask */
  2406. /* This should point to the msbit of e1 */
  2407. assert((*e1 & bitpos) != 0);
  2408. /*
  2409.  * Pre-load the windows.  Becuase the window size is
  2410.  * never larger than the exponent size, there is no need to
  2411.  * detect running off the end of e1 in here.
  2412.  *
  2413.  * The read-ahead is controlled by e1len and the bitpos mask.
  2414.  * Note that this is *ahead* of e1bits, which tracks the
  2415.  * most significant end of the window.  The purpose of this
  2416.  * initialization is to get the two w1bits+1 bits apart,
  2417.  * like they should be.
  2418.  *
  2419.  * Note that bitpos and e1len together keep track of the
  2420.  * lookahead read pointer in the exponent that is used here.
  2421.  * e2len is not decremented, it is only ever compared with
  2422.  * e1len as *that* is decremented.
  2423.  */
  2424. buf1 = buf2 = 0;
  2425. for (i = 0; i <= w1bits; i++) {
  2426. buf1 = (buf1 << 1) | ((*e1 & bitpos) != 0);
  2427. if (e1len <= e2len)
  2428. buf2 = (buf2 << 1) | ((*e2 & bitpos) != 0);
  2429. bitpos >>= 1;
  2430. if (!bitpos) {
  2431. BIGLITTLE(e1++,e1--);
  2432. if (e1len <= e2len)
  2433. BIGLITTLE(e2++,e2--);
  2434. bitpos = (BNWORD16)1 << (16-1);
  2435. e1len--;
  2436. }
  2437. }
  2438. assert(buf1 & tblmask);
  2439. /*
  2440.  * Set the pending multiply positions to a location that will
  2441.  * never be encountered, thus ensuring that nothing will happen
  2442.  * until the need for a multiply appears and one is scheduled.
  2443.  */
  2444. mult1pos = mult2pos = e1bits; /* A NULL value */
  2445. mult1 = mult2 = 0; /* Force a crash if we use these */
  2446. /*
  2447.  * Okay, now begins the real work.  The first step is
  2448.  * slightly magic, so it's done outside the main loop,
  2449.  * but it's very similar to what's inside.
  2450.  */
  2451. isone = 1; /* Buffer is implicitly 1, so replace * by copy */
  2452. e1bits--; /* Start processing the first bit... */
  2453. /*
  2454.  * This is just like the multiply in the loop, except that
  2455.  * - We know the msbit of buf1 is set, and
  2456.  * - We have the extra value n1^2 floating around.
  2457.  * So, do the usual computation, and if the result is that
  2458.  * the buffer should be multiplied by n1^1 immediately
  2459.  * (which we'd normally then square), we multiply it
  2460.  * (which reduces to a copy, which reduces to setting a flag)
  2461.  * by n1^2 and skip the squaring.  Thus, we do the
  2462.  * multiply and the squaring in one step.
  2463.  */
  2464. assert(buf1 & tblmask);
  2465. mult1pos = e1bits - w1bits;
  2466. while ((buf1 & 1) == 0) {
  2467. buf1 >>= 1;
  2468. mult1pos++;
  2469. }
  2470. /* Intermediates can wrap, but final must NOT */
  2471. assert(mult1pos <= e1bits);
  2472. mult1 = table1[buf1>>1];
  2473. buf1 = 0;
  2474. /* Special case: use already-computed value sitting in buffer */
  2475. if (mult1pos == e1bits)
  2476. isone = 0;
  2477. /*
  2478.  * The first multiply by a power of n2.  Similar, but
  2479.  * we might not even want to schedule a multiply if e2 is
  2480.  * shorter than e1, and the window might be shorter so
  2481.  * we have to leave the low w2bits bits alone.
  2482.  */
  2483. if (buf2 & tblmask) {
  2484. /* Remember low-order bits for later */
  2485. i = buf2 & ((1u << w2bits) - 1);
  2486. buf2 >>= w2bits;
  2487. mult2pos = e1bits - w1bits + w2bits;
  2488. while ((buf2 & 1) == 0) {
  2489. buf2 >>= 1;
  2490. mult2pos++;
  2491. }
  2492. assert(mult2pos <= e1bits);
  2493. mult2 = table2[buf2>>1];
  2494. buf2 = i;
  2495. if (mult2pos == e1bits) {
  2496. t = BIGLITTLE(b-mlen, b+mlen);
  2497. if (isone) {
  2498. lbnCopy_16(t, b, mlen); /* Copy low to high */
  2499. isone = 0;
  2500. } else {
  2501. lbnMontMul_16(a, t, b, mod, mlen, inv);
  2502. t = a; a = b; b = t;
  2503. }
  2504. }
  2505. }
  2506. /*
  2507.  * At this point, the buffer (which is the high half of b)
  2508.  * holds either 1 (implicitly, as the "isone" flag is set),
  2509.  * n1^2, n2^2 or n1^2 * n2^2.
  2510.  */
  2511. /*
  2512.  * The main loop.  The procedure is:
  2513.  * - Advance the windows
  2514.  * - If the most-significant bit of a window is set,
  2515.  *   schedule a multiply for the appropriate time in the
  2516.  *   future (may be immediately)
  2517.  * - Perform any pending multiples
  2518.  * - Check for termination
  2519.  * - Square the buffers
  2520.  *
  2521.  * At any given time, the acumulated product is held in
  2522.  * the high half of b.
  2523.  */
  2524. for (;;) {
  2525. e1bits--;
  2526. /* Advance the windows */
  2527. assert(buf1 < tblmask);
  2528. buf1 <<= 1;
  2529. assert(buf2 < tblmask);
  2530. buf2 <<= 1;
  2531. /*
  2532.  * This reads ahead of the current exponent position
  2533.  * (controlled by e1bits), so we have to be able to read
  2534.  * past the lsb of the exponents without error.
  2535.  */
  2536. if (e1len) {
  2537. buf1 |= ((*e1 & bitpos) != 0);
  2538. if (e1len <= e2len)
  2539. buf2 |= ((*e2 & bitpos) != 0);
  2540. bitpos >>= 1;
  2541. if (!bitpos) {
  2542. BIGLITTLE(e1++,e1--);
  2543. if (e1len <= e2len)
  2544. BIGLITTLE(e2++,e2--);
  2545. bitpos = (BNWORD16)1 << (16-1);
  2546. e1len--;
  2547. }
  2548. }
  2549. /* Examine the first window for pending multiplies */
  2550. if (buf1 & tblmask) {
  2551. mult1pos = e1bits - w1bits;
  2552. while ((buf1 & 1) == 0) {
  2553. buf1 >>= 1;
  2554. mult1pos++;
  2555. }
  2556. /* Intermediates can wrap, but final must NOT */
  2557. assert(mult1pos <= e1bits);
  2558. mult1 = table1[buf1>>1];
  2559. buf1 = 0;
  2560. }
  2561. /*
  2562.  * Examine the second window for pending multiplies.
  2563.  * Window 2 can be smaller than window 1, but we
  2564.  * keep the same number of bits in buf2, so we need
  2565.  * to ignore any low-order bits in the buffer when
  2566.  * computing what to multiply by, and recompute them
  2567.  * later.
  2568.  */
  2569. if (buf2 & tblmask) {
  2570. /* Remember low-order bits for later */
  2571. i = buf2 & ((1u << w2bits) - 1);
  2572. buf2 >>= w2bits;
  2573. mult2pos = e1bits - w1bits + w2bits;
  2574. while ((buf2 & 1) == 0) {
  2575. buf2 >>= 1;
  2576. mult2pos++;
  2577. }
  2578. assert(mult2pos <= e1bits);
  2579. mult2 = table2[buf2>>1];
  2580. buf2 = i;
  2581. }
  2582. /* If we have a pending multiply for e1, do it */
  2583. if (e1bits == mult1pos) {
  2584. /* Multiply by the table entry remembered previously */
  2585. t = BIGLITTLE(b-mlen, b+mlen);
  2586. if (isone) {
  2587. /* Multiply by 1 is a trivial case */
  2588. lbnCopy_16(t, mult1, mlen);
  2589. isone = 0;
  2590. } else {
  2591. lbnMontMul_16(a, t, mult1, mod, mlen, inv);
  2592. /* Swap a and b */
  2593. t = a; a = b; b = t;
  2594. }
  2595. }
  2596. /* If we have a pending multiply for e2, do it */
  2597. if (e1bits == mult2pos) {
  2598. /* Multiply by the table entry remembered previously */
  2599. t = BIGLITTLE(b-mlen, b+mlen);
  2600. if (isone) {
  2601. /* Multiply by 1 is a trivial case */
  2602. lbnCopy_16(t, mult2, mlen);
  2603. isone = 0;
  2604. } else {
  2605. lbnMontMul_16(a, t, mult2, mod, mlen, inv);
  2606. /* Swap a and b */
  2607. t = a; a = b; b = t;
  2608. }
  2609. }
  2610. /* Are we done? */
  2611. if (!e1bits)
  2612. break;
  2613. /* Square the buffer */
  2614. if (!isone) {
  2615. t = BIGLITTLE(b-mlen, b+mlen);
  2616. lbnMontSquare_16(a, t, mod, mlen, inv);
  2617. /* Swap a and b */
  2618. t = a; a = b; b = t;
  2619. }
  2620. } /* for (;;) */
  2621. assert(!isone);
  2622. assert(!buf1);
  2623. assert(!buf2);
  2624. /* DONE! */
  2625. /* Convert result out of Montgomery form */
  2626. t = BIGLITTLE(b-mlen, b+mlen);
  2627. lbnCopy_16(b, t, mlen);
  2628. lbnZero_16(t, mlen);
  2629. lbnMontReduce_16(b, mod, mlen, inv);
  2630. lbnCopy_16(result, t, mlen);
  2631. /* Clean up - free intermediate storage */
  2632. buf2 = tblmask >> w2bits;
  2633. while (--tblmask) {
  2634. if (tblmask < buf2)
  2635. LBNFREE(table2[tblmask], mlen);
  2636. LBNFREE(table1[tblmask], mlen);
  2637. }
  2638. t = table1[0];
  2639. LBNFREE(t, mlen);
  2640. LBNFREE(b, 2*mlen);
  2641. LBNFREE(a, 2*mlen);
  2642. return 0; /* Success */
  2643. }
  2644. /*
  2645.  * 2^exp (mod mod).  This is an optimized version for use in Fermat
  2646.  * tests.  The input value of n is ignored; it is returned with
  2647.  * "mlen" words valid.
  2648.  */
  2649. int
  2650. lbnTwoExpMod_16(BNWORD16 *n, BNWORD16 const *exp, unsigned elen,
  2651. BNWORD16 *mod, unsigned mlen)
  2652. {
  2653. unsigned e; /* Copy of high words of the exponent */
  2654. unsigned bits; /* Assorted counter of bits */
  2655. BNWORD16 const *bitptr;
  2656. BNWORD16 bitword, bitpos;
  2657. BNWORD16 *a, *b, *a1;
  2658. BNWORD16 inv;
  2659. assert(mlen);
  2660. bitptr = BIGLITTLE(exp-elen, exp+elen-1);
  2661. bitword = *bitptr;
  2662. assert(bitword);
  2663. /* Clear n for future use. */
  2664. lbnZero_16(n, mlen);
  2665. bits = lbnBits_16(exp, elen);
  2666. /* First, a couple of trivial cases. */
  2667. if (bits <= 1) {
  2668. /* 2 ^ 0 == 1,  2 ^ 1 == 2 */
  2669. BIGLITTLE(n[-1],n[0]) = (BNWORD16)1<<elen;
  2670. return 0;
  2671. }
  2672. /* Set bitpos to the most significant bit */
  2673. bitpos = (BNWORD16)1 << ((bits-1) & (16-1));
  2674. /* Now, count the bits in the modulus. */
  2675. bits = lbnBits_16(mod, mlen);
  2676. assert(bits > 1); /* a 1-bit modulus is just stupid... */
  2677. /*
  2678.  * We start with 1<<e, where "e" is as many high bits of the
  2679.  * exponent as we can manage without going over the modulus.
  2680.  * This first loop finds "e".
  2681.  */
  2682. e = 1;
  2683. while (elen) {
  2684. /* Consume the first bit */
  2685. bitpos >>= 1;
  2686. if (!bitpos) {
  2687. if (!--elen)
  2688. break;
  2689. bitword = BIGLITTLE(*++bitptr,*--bitptr);
  2690. bitpos = (BNWORD16)1<<(16-1);
  2691. }
  2692. e = e << 1 | ((bitpos & bitword) != 0);
  2693. if (e >= bits) { /* Overflow!  Back out. */
  2694. e >>= 1;
  2695. break;
  2696. }
  2697. }
  2698. /*
  2699.  * The bit in "bitpos" being examined by the bit buffer has NOT
  2700.  * been consumed yet.  This may be past the end of the exponent,
  2701.  * in which case elen == 1.
  2702.  */
  2703. /* Okay, now, set bit "e" in n.  n is already zero. */
  2704. inv = (BNWORD16)1 << (e & (16-1));
  2705. e /= 16;
  2706. BIGLITTLE(n[-e-1],n[e]) = inv;
  2707. /*
  2708.  * The effective length of n in words is now "e+1".
  2709.  * This is used a little bit later.
  2710.  */
  2711. if (!elen)
  2712. return 0; /* That was easy! */
  2713. /*
  2714.  * We have now processed the first few bits.  The next step
  2715.  * is to convert this to Montgomery form for further squaring.
  2716.  */
  2717. /* Allocate working storage: two product buffers */
  2718. LBNALLOC(a, 2*mlen);
  2719. if (!a)
  2720. return -1;
  2721. LBNALLOC(b, 2*mlen);
  2722. if (!b) {
  2723. LBNFREE(a, 2*mlen);
  2724. return -1;
  2725. }
  2726. /* Convert n to Montgomery form */
  2727. inv = BIGLITTLE(mod[-1],mod[0]); /* LSW of modulus */
  2728. assert(inv & 1); /* Modulus must be odd */
  2729. inv = lbnMontInv1_16(inv);
  2730. /* Move n (length e+1, remember?) up "mlen" words into b */
  2731. /* Note that we lie about a1 for a bit - it's pointing to b */
  2732. a1 = BIGLITTLE(b-mlen,b+mlen);
  2733. lbnCopy_16(a1, n, e+1);
  2734. lbnZero_16(b, mlen);
  2735. /* Do the division - dump the quotient into the high-order words */
  2736. (void)lbnDiv_16(a1, b, mlen+e+1, mod, mlen);
  2737. /*
  2738.  * Now do the first squaring and modular reduction to put
  2739.  * the number up in a1 where it belongs.
  2740.  */
  2741. lbnMontSquare_16(a, b, mod, mlen, inv);
  2742. /* Fix up a1 to point to where it should go. */
  2743. a1 = BIGLITTLE(a-mlen,a+mlen);
  2744. /*
  2745.  * Okay, now, a1 holds the number being accumulated, and
  2746.  * b is a scratch register.  Start working:
  2747.  */
  2748. for (;;) {
  2749. /*
  2750.  * Is the bit set?  If so, double a1 as well.
  2751.  * A modular doubling like this is very cheap.
  2752.  */
  2753. if (bitpos & bitword) {
  2754. /*
  2755.  * Double the number.  If there was a carry out OR
  2756.  * the result is greater than the modulus, subract
  2757.  * the modulus.
  2758.  */
  2759. if (lbnDouble_16(a1, mlen) ||
  2760.     lbnCmp_16(a1, mod, mlen) > 0)
  2761. (void)lbnSubN_16(a1, mod, mlen);
  2762. }
  2763. /* Advance to the next exponent bit */
  2764. bitpos >>= 1;
  2765. if (!bitpos) {
  2766. if (!--elen)
  2767. break; /* Done! */
  2768. bitword = BIGLITTLE(*++bitptr,*--bitptr);
  2769. bitpos = (BNWORD16)1<<(16-1);
  2770. }
  2771. /*
  2772.  * The elen/bitword/bitpos bit buffer is known to be
  2773.  * non-empty, i.e. there is at least one more unconsumed bit.
  2774.  * Thus, it's safe to square the number.
  2775.  */
  2776. lbnMontSquare_16(b, a1, mod, mlen, inv);
  2777. /* Rename result (in b) back to a (a1, really). */
  2778. a1 = b; b = a; a = a1;
  2779. a1 = BIGLITTLE(a-mlen,a+mlen);
  2780. }
  2781. /* DONE!  Just a little bit of cleanup... */
  2782. /*
  2783.  * Convert result out of Montgomery form... this is
  2784.  * just a Montgomery reduction.
  2785.  */
  2786. lbnCopy_16(a, a1, mlen);
  2787. lbnZero_16(a1, mlen);
  2788. lbnMontReduce_16(a, mod, mlen, inv);
  2789. lbnCopy_16(n, a1, mlen);
  2790. /* Clean up - free intermediate storage */
  2791. LBNFREE(b, 2*mlen);
  2792. LBNFREE(a, 2*mlen);
  2793. return 0; /* Success */
  2794. }
  2795. /*
  2796.  * Returns a substring of the big-endian array of bytes representation
  2797.  * of the bignum array based on two parameters, the least significant
  2798.  * byte number (0 to start with the least significant byte) and the
  2799.  * length.  I.e. the number returned is a representation of
  2800.  * (bn / 2^(8*lsbyte)) % 2 ^ (8*buflen).
  2801.  *
  2802.  * It is an error if the bignum is not at least buflen + lsbyte bytes
  2803.  * long.
  2804.  *
  2805.  * This code assumes that the compiler has the minimal intelligence 
  2806.  * neded to optimize divides and modulo operations on an unsigned data
  2807.  * type with a power of two.
  2808.  */
  2809. void
  2810. lbnExtractBigBytes_16(BNWORD16 const *n, unsigned char *buf,
  2811. unsigned lsbyte, unsigned buflen)
  2812. {
  2813. BNWORD16 t = 0; /* Needed to shut up uninitialized var warnings */
  2814. unsigned shift;
  2815. lsbyte += buflen;
  2816. shift = (8 * lsbyte) % 16;
  2817. lsbyte /= (16/8); /* Convert to word offset */
  2818. BIGLITTLE(n -= lsbyte, n += lsbyte);
  2819. if (shift)
  2820. t = BIGLITTLE(n[-1],n[0]);
  2821. while (buflen--) {
  2822. if (!shift) {
  2823. t = BIGLITTLE(*n++,*--n);
  2824. shift = 16;
  2825. }
  2826. shift -= 8;
  2827. *buf++ = (unsigned char)(t>>shift);
  2828. }
  2829. }
  2830. /*
  2831.  * Merge a big-endian array of bytes into a bignum array.
  2832.  * The array had better be big enough.  This is
  2833.  * equivalent to extracting the entire bignum into a
  2834.  * large byte array, copying the input buffer into the
  2835.  * middle of it, and converting back to a bignum.
  2836.  *
  2837.  * The buf is "len" bytes long, and its *last* byte is at
  2838.  * position "lsbyte" from the end of the bignum.
  2839.  *
  2840.  * Note that this is a pain to get right.  Fortunately, it's hardly
  2841.  * critical for efficiency.
  2842.  */
  2843. void
  2844. lbnInsertBigBytes_16(BNWORD16 *n, unsigned char const *buf,
  2845.                   unsigned lsbyte,  unsigned buflen)
  2846. {
  2847. BNWORD16 t = 0; /* Shut up uninitialized varibale warnings */
  2848. lsbyte += buflen;
  2849. BIGLITTLE(n -= lsbyte/(16/8), n += lsbyte/(16/8));
  2850. /* Load up leading odd bytes */
  2851. if (lsbyte % (16/8)) {
  2852. t = BIGLITTLE(*--n,*n++);
  2853. t >>= (lsbyte * 8) % 16;
  2854. }
  2855. /* The main loop - merge into t, storing at each word boundary. */
  2856. while (buflen--) {
  2857. t = (t << 8) | *buf++;
  2858. if ((--lsbyte % (16/8)) == 0)
  2859. BIGLITTLE(*n++,*--n) = t;
  2860. }
  2861. /* Merge odd bytes in t into last word */
  2862. lsbyte = (lsbyte * 8) % 16;
  2863. if (lsbyte) {
  2864. t <<= lsbyte;
  2865. t |= (((BNWORD16)1 << lsbyte) - 1) & BIGLITTLE(n[0],n[-1]);
  2866. BIGLITTLE(n[0],n[-1]) = t;
  2867. }
  2868. return;
  2869. }
  2870. /*
  2871.  * Returns a substring of the little-endian array of bytes representation
  2872.  * of the bignum array based on two parameters, the least significant
  2873.  * byte number (0 to start with the least significant byte) and the
  2874.  * length.  I.e. the number returned is a representation of
  2875.  * (bn / 2^(8*lsbyte)) % 2 ^ (8*buflen).
  2876.  *
  2877.  * It is an error if the bignum is not at least buflen + lsbyte bytes
  2878.  * long.
  2879.  *
  2880.  * This code assumes that the compiler has the minimal intelligence 
  2881.  * neded to optimize divides and modulo operations on an unsigned data
  2882.  * type with a power of two.
  2883.  */
  2884. void
  2885. lbnExtractLittleBytes_16(BNWORD16 const *n, unsigned char *buf,
  2886. unsigned lsbyte, unsigned buflen)
  2887. {
  2888. BNWORD16 t = 0; /* Needed to shut up uninitialized var warnings */
  2889. BIGLITTLE(n -= lsbyte/(16/8), n += lsbyte/(16/8));
  2890. if (lsbyte % (16/8)) {
  2891. t = BIGLITTLE(*--n,*n++);
  2892. t >>= (lsbyte % (16/8)) * 8 ;
  2893. }
  2894. while (buflen--) {
  2895. if ((lsbyte++ % (16/8)) == 0)
  2896. t = BIGLITTLE(*--n,*n++);
  2897. *buf++ = (unsigned char)t;
  2898. t >>= 8;
  2899. }
  2900. }
  2901. /*
  2902.  * Merge a little-endian array of bytes into a bignum array.
  2903.  * The array had better be big enough.  This is
  2904.  * equivalent to extracting the entire bignum into a
  2905.  * large byte array, copying the input buffer into the
  2906.  * middle of it, and converting back to a bignum.
  2907.  *
  2908.  * The buf is "len" bytes long, and its first byte is at
  2909.  * position "lsbyte" from the end of the bignum.
  2910.  *
  2911.  * Note that this is a pain to get right.  Fortunately, it's hardly
  2912.  * critical for efficiency.
  2913.  */
  2914. void
  2915. lbnInsertLittleBytes_16(BNWORD16 *n, unsigned char const *buf,
  2916.                   unsigned lsbyte,  unsigned buflen)
  2917. {
  2918. BNWORD16 t = 0; /* Shut up uninitialized varibale warnings */
  2919. /* Move to most-significant end */
  2920. lsbyte += buflen;
  2921. buf += buflen;
  2922. BIGLITTLE(n -= lsbyte/(16/8), n += lsbyte/(16/8));
  2923. /* Load up leading odd bytes */
  2924. if (lsbyte % (16/8)) {
  2925. t = BIGLITTLE(*--n,*n++);
  2926. t >>= (lsbyte * 8) % 16;
  2927. }
  2928. /* The main loop - merge into t, storing at each word boundary. */
  2929. while (buflen--) {
  2930. t = (t << 8) | *--buf;
  2931. if ((--lsbyte % (16/8)) == 0)
  2932. BIGLITTLE(*n++,*--n) = t;
  2933. }
  2934. /* Merge odd bytes in t into last word */
  2935. lsbyte = (lsbyte * 8) % 16;
  2936. if (lsbyte) {
  2937. t <<= lsbyte;
  2938. t |= (((BNWORD16)1 << lsbyte) - 1) & BIGLITTLE(n[0],n[-1]);
  2939. BIGLITTLE(n[0],n[-1]) = t;
  2940. }
  2941. return;
  2942. }
  2943. #ifdef DEADCODE /* This was a precursor to the more flexible lbnExtractBytes */
  2944. /*
  2945.  * Convert a big-endian array of bytes to a bignum.
  2946.  * Returns the number of words in the bignum.
  2947.  * Note the expression "16/8" for the number of bytes per word.
  2948.  * This is so the word-size adjustment will work.
  2949.  */
  2950. unsigned
  2951. lbnFromBytes_16(BNWORD16 *a, unsigned char const *b, unsigned blen)
  2952. {
  2953. BNWORD16 t;
  2954. unsigned alen = (blen + (16/8-1))/(16/8);
  2955. BIGLITTLE(a -= alen, a += alen);
  2956. while (blen) {
  2957. t = 0;
  2958. do {
  2959. t = t << 8 | *b++;
  2960. } while (--blen & (16/8-1));
  2961. BIGLITTLE(*a++,*--a) = t;
  2962. }
  2963. return alen;
  2964. }
  2965. #endif
  2966. /*
  2967.  * Computes the GCD of a and b.  Modifies both arguments;
  2968.  * when it returns, one of them is the GCD and the other is trash.
  2969.  * The return value is the length of the GCD, with the sign telling
  2970.  * whether it is in a (+ve) or b (-ve).  Both inputs must have
  2971.  * one extra word of precision.  alen must be >= blen.
  2972.  *
  2973.  * TODO: use the binary algorithm (Knuth section 4.5.2, algorithm B).
  2974.  * This is based on taking out common powers of 2, then repeatedly:
  2975.  * gcd(2*u,v) = gcd(u,2*v) = gcd(u,v) - isolated powers of 2 can be deleted.
  2976.  * gcd(u,v) = gcd(u-v,v) - the numbers can be easily reduced.
  2977.  * It gets less reduction per step, but the steps are much faster than
  2978.  * the division case.
  2979.  */
  2980. int
  2981. lbnGcd_16(BNWORD16 *a, unsigned alen, BNWORD16 *b, unsigned blen)
  2982. {
  2983. assert(alen >= blen);
  2984. while (blen != 0) {
  2985. (void)lbnDiv_16(BIGLITTLE(a-blen,a+blen), a, alen, b, blen);
  2986. alen = lbnNorm_16(a, blen);
  2987. if (alen == 0)
  2988. return -(int)blen;
  2989. (void)lbnDiv_16(BIGLITTLE(b-alen,b+alen), b, blen, a, alen);
  2990. blen = lbnNorm_16(b, alen);
  2991. }
  2992. return alen;
  2993. }
  2994. /*
  2995.  * Invert "a" modulo "mod" using the extended Euclidean algorithm.
  2996.  * Note that this only computes one of the cosequences, and uses the
  2997.  * theorem that the signs flip every step and the absolute value of
  2998.  * the cosequence values are always bounded by the modulus to avoid
  2999.  * having to work with negative numbers.
  3000.  * gcd(a,mod) had better equal 1.  Returns 1 if the GCD is NOT 1.
  3001.  * a must be one word longer than "mod".  It is overwritten with the
  3002.  * result.
  3003.  * TODO: Use Lehmer's high-precision GCD algorithm (Knuth 4.5.2, Algorithm L).
  3004.  */
  3005. int
  3006. lbnInv_16(BNWORD16 *a, unsigned alen, BNWORD16 const *mod, unsigned mlen)
  3007. {
  3008. BNWORD16 *b; /* Hold a copy of mod during GCD reduction */
  3009. BNWORD16 *p; /* Temporary for products added to t0 and t1 */
  3010. BNWORD16 *t0, *t1; /* Inverse accumulators */
  3011. BNWORD16 cy;
  3012. unsigned blen, t0len, t1len, plen;
  3013. alen = lbnNorm_16(a, alen);
  3014. if (!alen)
  3015. return 1; /* No inverse */
  3016. mlen = lbnNorm_16(mod, mlen);
  3017. assert (alen <= mlen);
  3018. /* Inverse of 1 is 1 */
  3019. if (alen == 1 && BIGLITTLE(a[-1],a[0]) == 1) {
  3020. lbnZero_16(BIGLITTLE(a-alen,a+alen), mlen-alen);
  3021. return 0;
  3022. }
  3023. /* Allocate a pile of space */
  3024. LBNALLOC(b, mlen+1);
  3025. if (b) {
  3026. /*
  3027.  * Although products are guaranteed to always be less than the
  3028.  * modulus, it can involve multiplying two 3-word numbers to
  3029.  * get a 5-word result, requiring a 6th word to store a 0
  3030.  * temporarily.  Thus, mlen + 1.
  3031.  */
  3032. LBNALLOC(p, mlen+1);
  3033. if (p) {
  3034. LBNALLOC(t0, mlen);
  3035. if (t0) {
  3036. LBNALLOC(t1, mlen);
  3037. if (t1)
  3038. goto allocated;
  3039. LBNFREE(t1, mlen);
  3040. }
  3041. LBNFREE(p, mlen+1);
  3042. }
  3043. LBNFREE(b, mlen+1);
  3044. }
  3045. return -1;
  3046. allocated:
  3047. /* Set t0 to 1 */
  3048. t0len = 1;
  3049. BIGLITTLE(t0[-1],t0[0]) = 1;
  3050. /* b = mod */
  3051. lbnCopy_16(b, mod, mlen);
  3052. /* blen = mlen (implicitly) */
  3053. /* t1 = b / a; b = b % a */
  3054. cy = lbnDiv_16(t1, b, mlen, a, alen);
  3055. *(BIGLITTLE(t1-(mlen-alen)-1,t1+(mlen-alen))) = cy;
  3056. t1len = lbnNorm_16(t1, mlen-alen+1);
  3057. blen = lbnNorm_16(b, alen);
  3058. /* while (b > 1) */
  3059. while (blen > 1 || BIGLITTLE(b[-1],b[0]) != (BNWORD16)1) {
  3060. /* q = a / b; a = a % b; */
  3061. if (alen < blen || (alen == blen && lbnCmp_16(a, a, alen) < 0))
  3062. assert(0);
  3063. cy = lbnDiv_16(BIGLITTLE(a-blen,a+blen), a, alen, b, blen);
  3064. *(BIGLITTLE(a-alen-1,a+alen)) = cy;
  3065. plen = lbnNorm_16(BIGLITTLE(a-blen,a+blen), alen-blen+1);
  3066. assert(plen);
  3067. alen = lbnNorm_16(a, blen);
  3068. if (!alen)
  3069. goto failure; /* GCD not 1 */
  3070. /* t0 += q * t1; */
  3071. assert(plen+t1len <= mlen+1);
  3072. lbnMul_16(p, BIGLITTLE(a-blen,a+blen), plen, t1, t1len);
  3073. plen = lbnNorm_16(p, plen + t1len);
  3074. assert(plen <= mlen);
  3075. if (plen > t0len) {
  3076. lbnZero_16(BIGLITTLE(t0-t0len,t0+t0len), plen-t0len);
  3077. t0len = plen;
  3078. }
  3079. cy = lbnAddN_16(t0, p, plen);
  3080. if (cy) {
  3081. if (t0len > plen) {
  3082. cy = lbnAdd1_16(BIGLITTLE(t0-plen,t0+plen),
  3083. t0len-plen, cy);
  3084. }
  3085. if (cy) {
  3086. BIGLITTLE(t0[-t0len-1],t0[t0len]) = cy;
  3087. t0len++;
  3088. }
  3089. }
  3090. /* if (a <= 1) return a ? t0 : FAIL; */
  3091. if (alen <= 1 && BIGLITTLE(a[-1],a[0]) == (BNWORD16)1) {
  3092. if (alen == 0)
  3093. goto failure; /* FAIL */
  3094. assert(t0len <= mlen);
  3095. lbnCopy_16(a, t0, t0len);
  3096. lbnZero_16(BIGLITTLE(a-t0len, a+t0len), mlen-t0len);
  3097. goto success;
  3098. }
  3099. /* q = b / a; b = b % a; */
  3100. if (blen < alen || (blen == alen && lbnCmp_16(b, a, alen) < 0))
  3101. assert(0);
  3102. cy = lbnDiv_16(BIGLITTLE(b-alen,b+alen), b, blen, a, alen);
  3103. *(BIGLITTLE(b-blen-1,b+blen)) = cy;
  3104. plen = lbnNorm_16(BIGLITTLE(b-alen,b+alen), blen-alen+1);
  3105. assert(plen);
  3106. blen = lbnNorm_16(b, alen);
  3107. if (!blen)
  3108. goto failure; /* GCD not 1 */
  3109. /* t1 += q * t0; */
  3110. assert(plen+t0len <= mlen+1);
  3111. lbnMul_16(p, BIGLITTLE(b-alen,b+alen), plen, t0, t0len);
  3112. plen = lbnNorm_16(p, plen + t0len);
  3113. assert(plen <= mlen);
  3114. if (plen > t1len) {
  3115. lbnZero_16(BIGLITTLE(t1-t1len,t1+t1len), plen-t1len);
  3116. t1len = plen;
  3117. }
  3118. cy = lbnAddN_16(t1, p, plen);
  3119. if (cy) {
  3120. if (t1len > plen) {
  3121. cy = lbnAdd1_16(BIGLITTLE(t1-plen,t0+plen),
  3122. t1len-plen, cy);
  3123. }
  3124. if (cy) {
  3125. BIGLITTLE(t1[-t1len-1],t1[t1len]) = cy;
  3126. t1len++;
  3127. }
  3128. }
  3129. }
  3130. if (!blen)
  3131. goto failure; /* gcd(a, mod) != 1 -- FAIL */
  3132. /* return mod-t1 */
  3133. lbnCopy_16(a, mod, mlen);
  3134. assert(t1len <= mlen);
  3135. cy = lbnSubN_16(a, t1, t1len);
  3136. if (cy) {
  3137. assert(mlen > t1len);
  3138. cy = lbnSub1_16(BIGLITTLE(a-t1len, a+t1len), mlen-t1len, cy);
  3139. assert(!cy);
  3140. }
  3141. success:
  3142. LBNFREE(t1, mlen);
  3143. LBNFREE(t0, mlen);
  3144. LBNFREE(p, mlen+1);
  3145. LBNFREE(b, mlen+1);
  3146. return 0;
  3147. failure:
  3148. LBNFREE(t1, mlen);
  3149. LBNFREE(t0, mlen);
  3150. LBNFREE(p, mlen+1);
  3151. LBNFREE(b, mlen+1);
  3152. return 1;
  3153. }