SSHBN.C 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104
  1. /*
  2. * Bignum routines for RSA and DH and stuff.
  3. */
  4. #include <stdio.h>
  5. #include <assert.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include "misc.h"
  9. /*
  10. * Usage notes:
  11. * * Do not call the DIVMOD_WORD macro with expressions such as array
  12. * subscripts, as some implementations object to this (see below).
  13. * * Note that none of the division methods below will cope if the
  14. * quotient won't fit into BIGNUM_INT_BITS. Callers should be careful
  15. * to avoid this case.
  16. * If this condition occurs, in the case of the x86 DIV instruction,
  17. * an overflow exception will occur, which (according to a correspondent)
  18. * will manifest on Windows as something like
  19. * 0xC0000095: Integer overflow
  20. * The C variant won't give the right answer, either.
  21. */
  22. #if defined __GNUC__ && defined __i386__
  23. typedef unsigned long BignumInt;
  24. typedef unsigned long long BignumDblInt;
  25. #define BIGNUM_INT_MASK 0xFFFFFFFFUL
  26. #define BIGNUM_TOP_BIT 0x80000000UL
  27. #define BIGNUM_INT_BITS 32
  28. #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
  29. #define DIVMOD_WORD(q, r, hi, lo, w) \
  30. __asm__("div %2" : \
  31. "=d" (r), "=a" (q) : \
  32. "r" (w), "d" (hi), "a" (lo))
  33. // Borland does not support inline assembly in IDE
  34. #elif (defined _MSC_VER && defined _M_IX86) || (defined(MPEXT) && !defined(IDE))
  35. typedef unsigned __int32 BignumInt;
  36. typedef unsigned __int64 BignumDblInt;
  37. #define BIGNUM_INT_MASK 0xFFFFFFFFUL
  38. #define BIGNUM_TOP_BIT 0x80000000UL
  39. #define BIGNUM_INT_BITS 32
  40. #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
  41. /* Note: MASM interprets array subscripts in the macro arguments as
  42. * assembler syntax, which gives the wrong answer. Don't supply them.
  43. * <http://msdn2.microsoft.com/en-us/library/bf1dw62z.aspx> */
  44. #ifdef MPEXT
  45. // BCC requires semicolons
  46. #define DIVMOD_WORD(q, r, hi, lo, w) do { \
  47. __asm mov edx, hi; \
  48. __asm mov eax, lo; \
  49. __asm div w; \
  50. __asm mov r, edx; \
  51. __asm mov q, eax; \
  52. } while(0)
  53. #else
  54. #define DIVMOD_WORD(q, r, hi, lo, w) do { \
  55. __asm mov edx, hi \
  56. __asm mov eax, lo \
  57. __asm div w \
  58. __asm mov r, edx \
  59. __asm mov q, eax \
  60. } while(0)
  61. #endif
  62. #else
  63. typedef unsigned short BignumInt;
  64. typedef unsigned long BignumDblInt;
  65. #define BIGNUM_INT_MASK 0xFFFFU
  66. #define BIGNUM_TOP_BIT 0x8000U
  67. #define BIGNUM_INT_BITS 16
  68. #define MUL_WORD(w1, w2) ((BignumDblInt)w1 * w2)
  69. #define DIVMOD_WORD(q, r, hi, lo, w) do { \
  70. BignumDblInt n = (((BignumDblInt)hi) << BIGNUM_INT_BITS) | lo; \
  71. q = n / w; \
  72. r = n % w; \
  73. } while (0)
  74. #endif
  75. #define BIGNUM_INT_BYTES (BIGNUM_INT_BITS / 8)
  76. #define BIGNUM_INTERNAL
  77. typedef BignumInt *Bignum;
  78. #include "ssh.h"
  79. BignumInt bnZero[1] = { 0 };
  80. BignumInt bnOne[2] = { 1, 1 };
  81. /*
  82. * The Bignum format is an array of `BignumInt'. The first
  83. * element of the array counts the remaining elements. The
  84. * remaining elements express the actual number, base 2^BIGNUM_INT_BITS, _least_
  85. * significant digit first. (So it's trivial to extract the bit
  86. * with value 2^n for any n.)
  87. *
  88. * All Bignums in this module are positive. Negative numbers must
  89. * be dealt with outside it.
  90. *
  91. * INVARIANT: the most significant word of any Bignum must be
  92. * nonzero.
  93. */
  94. Bignum Zero = bnZero, One = bnOne;
  95. static Bignum newbn(int length)
  96. {
  97. Bignum b = snewn(length + 1, BignumInt);
  98. if (!b)
  99. abort(); /* FIXME */
  100. memset(b, 0, (length + 1) * sizeof(*b));
  101. b[0] = length;
  102. return b;
  103. }
  104. void bn_restore_invariant(Bignum b)
  105. {
  106. while (b[0] > 1 && b[b[0]] == 0)
  107. b[0]--;
  108. }
  109. Bignum copybn(Bignum orig)
  110. {
  111. Bignum b = snewn(orig[0] + 1, BignumInt);
  112. if (!b)
  113. abort(); /* FIXME */
  114. memcpy(b, orig, (orig[0] + 1) * sizeof(*b));
  115. return b;
  116. }
  117. void freebn(Bignum b)
  118. {
  119. /*
  120. * Burn the evidence, just in case.
  121. */
  122. memset(b, 0, sizeof(b[0]) * (b[0] + 1));
  123. sfree(b);
  124. }
  125. Bignum bn_power_2(int n)
  126. {
  127. Bignum ret = newbn(n / BIGNUM_INT_BITS + 1);
  128. bignum_set_bit(ret, n, 1);
  129. return ret;
  130. }
  131. /*
  132. * Compute c = a * b.
  133. * Input is in the first len words of a and b.
  134. * Result is returned in the first 2*len words of c.
  135. */
  136. static void internal_mul(BignumInt *a, BignumInt *b,
  137. BignumInt *c, int len)
  138. {
  139. int i, j;
  140. BignumDblInt t;
  141. for (j = 0; j < 2 * len; j++)
  142. c[j] = 0;
  143. for (i = len - 1; i >= 0; i--) {
  144. t = 0;
  145. for (j = len - 1; j >= 0; j--) {
  146. t += MUL_WORD(a[i], (BignumDblInt) b[j]);
  147. t += (BignumDblInt) c[i + j + 1];
  148. c[i + j + 1] = (BignumInt) t;
  149. t = t >> BIGNUM_INT_BITS;
  150. }
  151. c[i] = (BignumInt) t;
  152. }
  153. }
  154. static void internal_add_shifted(BignumInt *number,
  155. unsigned n, int shift)
  156. {
  157. int word = 1 + (shift / BIGNUM_INT_BITS);
  158. int bshift = shift % BIGNUM_INT_BITS;
  159. BignumDblInt addend;
  160. addend = (BignumDblInt)n << bshift;
  161. while (addend) {
  162. addend += number[word];
  163. number[word] = (BignumInt) addend & BIGNUM_INT_MASK;
  164. addend >>= BIGNUM_INT_BITS;
  165. word++;
  166. }
  167. }
  168. /*
  169. * Compute a = a % m.
  170. * Input in first alen words of a and first mlen words of m.
  171. * Output in first alen words of a
  172. * (of which first alen-mlen words will be zero).
  173. * The MSW of m MUST have its high bit set.
  174. * Quotient is accumulated in the `quotient' array, which is a Bignum
  175. * rather than the internal bigendian format. Quotient parts are shifted
  176. * left by `qshift' before adding into quot.
  177. */
  178. static void internal_mod(BignumInt *a, int alen,
  179. BignumInt *m, int mlen,
  180. BignumInt *quot, int qshift)
  181. {
  182. BignumInt m0, m1;
  183. unsigned int h;
  184. int i, k;
  185. m0 = m[0];
  186. if (mlen > 1)
  187. m1 = m[1];
  188. else
  189. m1 = 0;
  190. for (i = 0; i <= alen - mlen; i++) {
  191. BignumDblInt t;
  192. unsigned int q, r, c, ai1;
  193. if (i == 0) {
  194. h = 0;
  195. } else {
  196. h = a[i - 1];
  197. a[i - 1] = 0;
  198. }
  199. if (i == alen - 1)
  200. ai1 = 0;
  201. else
  202. ai1 = a[i + 1];
  203. /* Find q = h:a[i] / m0 */
  204. if (h >= m0) {
  205. /*
  206. * Special case.
  207. *
  208. * To illustrate it, suppose a BignumInt is 8 bits, and
  209. * we are dividing (say) A1:23:45:67 by A1:B2:C3. Then
  210. * our initial division will be 0xA123 / 0xA1, which
  211. * will give a quotient of 0x100 and a divide overflow.
  212. * However, the invariants in this division algorithm
  213. * are not violated, since the full number A1:23:... is
  214. * _less_ than the quotient prefix A1:B2:... and so the
  215. * following correction loop would have sorted it out.
  216. *
  217. * In this situation we set q to be the largest
  218. * quotient we _can_ stomach (0xFF, of course).
  219. */
  220. q = BIGNUM_INT_MASK;
  221. } else {
  222. /* Macro doesn't want an array subscript expression passed
  223. * into it (see definition), so use a temporary. */
  224. BignumInt tmplo = a[i];
  225. DIVMOD_WORD(q, r, h, tmplo, m0);
  226. /* Refine our estimate of q by looking at
  227. h:a[i]:a[i+1] / m0:m1 */
  228. t = MUL_WORD(m1, q);
  229. if (t > ((BignumDblInt) r << BIGNUM_INT_BITS) + ai1) {
  230. q--;
  231. t -= m1;
  232. r = (r + m0) & BIGNUM_INT_MASK; /* overflow? */
  233. if (r >= (BignumDblInt) m0 &&
  234. t > ((BignumDblInt) r << BIGNUM_INT_BITS) + ai1) q--;
  235. }
  236. }
  237. /* Subtract q * m from a[i...] */
  238. c = 0;
  239. for (k = mlen - 1; k >= 0; k--) {
  240. t = MUL_WORD(q, m[k]);
  241. t += c;
  242. c = (unsigned)(t >> BIGNUM_INT_BITS);
  243. if ((BignumInt) t > a[i + k])
  244. c++;
  245. a[i + k] -= (BignumInt) t;
  246. }
  247. /* Add back m in case of borrow */
  248. if (c != h) {
  249. t = 0;
  250. for (k = mlen - 1; k >= 0; k--) {
  251. t += m[k];
  252. t += a[i + k];
  253. a[i + k] = (BignumInt) t;
  254. t = t >> BIGNUM_INT_BITS;
  255. }
  256. q--;
  257. }
  258. if (quot)
  259. internal_add_shifted(quot, q, qshift + BIGNUM_INT_BITS * (alen - mlen - i));
  260. }
  261. }
  262. /*
  263. * Compute (base ^ exp) % mod.
  264. */
  265. Bignum modpow(Bignum base_in, Bignum exp, Bignum mod)
  266. {
  267. BignumInt *a, *b, *n, *m;
  268. int mshift;
  269. int mlen, i, j;
  270. Bignum base, result;
  271. /*
  272. * The most significant word of mod needs to be non-zero. It
  273. * should already be, but let's make sure.
  274. */
  275. assert(mod[mod[0]] != 0);
  276. /*
  277. * Make sure the base is smaller than the modulus, by reducing
  278. * it modulo the modulus if not.
  279. */
  280. base = bigmod(base_in, mod);
  281. /* Allocate m of size mlen, copy mod to m */
  282. /* We use big endian internally */
  283. mlen = mod[0];
  284. m = snewn(mlen, BignumInt);
  285. for (j = 0; j < mlen; j++)
  286. m[j] = mod[mod[0] - j];
  287. /* Shift m left to make msb bit set */
  288. for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
  289. if ((m[0] << mshift) & BIGNUM_TOP_BIT)
  290. break;
  291. if (mshift) {
  292. for (i = 0; i < mlen - 1; i++)
  293. m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
  294. m[mlen - 1] = m[mlen - 1] << mshift;
  295. }
  296. /* Allocate n of size mlen, copy base to n */
  297. n = snewn(mlen, BignumInt);
  298. i = mlen - base[0];
  299. for (j = 0; j < i; j++)
  300. n[j] = 0;
  301. for (j = 0; j < (int)base[0]; j++)
  302. n[i + j] = base[base[0] - j];
  303. /* Allocate a and b of size 2*mlen. Set a = 1 */
  304. a = snewn(2 * mlen, BignumInt);
  305. b = snewn(2 * mlen, BignumInt);
  306. for (i = 0; i < 2 * mlen; i++)
  307. a[i] = 0;
  308. a[2 * mlen - 1] = 1;
  309. /* Skip leading zero bits of exp. */
  310. i = 0;
  311. j = BIGNUM_INT_BITS-1;
  312. while (i < (int)exp[0] && (exp[exp[0] - i] & (1 << j)) == 0) {
  313. j--;
  314. if (j < 0) {
  315. i++;
  316. j = BIGNUM_INT_BITS-1;
  317. }
  318. }
  319. /* Main computation */
  320. while (i < (int)exp[0]) {
  321. while (j >= 0) {
  322. internal_mul(a + mlen, a + mlen, b, mlen);
  323. internal_mod(b, mlen * 2, m, mlen, NULL, 0);
  324. if ((exp[exp[0] - i] & (1 << j)) != 0) {
  325. internal_mul(b + mlen, n, a, mlen);
  326. internal_mod(a, mlen * 2, m, mlen, NULL, 0);
  327. } else {
  328. BignumInt *t;
  329. t = a;
  330. a = b;
  331. b = t;
  332. }
  333. j--;
  334. }
  335. i++;
  336. j = BIGNUM_INT_BITS-1;
  337. }
  338. /* Fixup result in case the modulus was shifted */
  339. if (mshift) {
  340. for (i = mlen - 1; i < 2 * mlen - 1; i++)
  341. a[i] = (a[i] << mshift) | (a[i + 1] >> (BIGNUM_INT_BITS - mshift));
  342. a[2 * mlen - 1] = a[2 * mlen - 1] << mshift;
  343. internal_mod(a, mlen * 2, m, mlen, NULL, 0);
  344. for (i = 2 * mlen - 1; i >= mlen; i--)
  345. a[i] = (a[i] >> mshift) | (a[i - 1] << (BIGNUM_INT_BITS - mshift));
  346. }
  347. /* Copy result to buffer */
  348. result = newbn(mod[0]);
  349. for (i = 0; i < mlen; i++)
  350. result[result[0] - i] = a[i + mlen];
  351. while (result[0] > 1 && result[result[0]] == 0)
  352. result[0]--;
  353. /* Free temporary arrays */
  354. for (i = 0; i < 2 * mlen; i++)
  355. a[i] = 0;
  356. sfree(a);
  357. for (i = 0; i < 2 * mlen; i++)
  358. b[i] = 0;
  359. sfree(b);
  360. for (i = 0; i < mlen; i++)
  361. m[i] = 0;
  362. sfree(m);
  363. for (i = 0; i < mlen; i++)
  364. n[i] = 0;
  365. sfree(n);
  366. freebn(base);
  367. return result;
  368. }
  369. /*
  370. * Compute (p * q) % mod.
  371. * The most significant word of mod MUST be non-zero.
  372. * We assume that the result array is the same size as the mod array.
  373. */
  374. Bignum modmul(Bignum p, Bignum q, Bignum mod)
  375. {
  376. BignumInt *a, *n, *m, *o;
  377. int mshift;
  378. int pqlen, mlen, rlen, i, j;
  379. Bignum result;
  380. /* Allocate m of size mlen, copy mod to m */
  381. /* We use big endian internally */
  382. mlen = mod[0];
  383. m = snewn(mlen, BignumInt);
  384. for (j = 0; j < mlen; j++)
  385. m[j] = mod[mod[0] - j];
  386. /* Shift m left to make msb bit set */
  387. for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
  388. if ((m[0] << mshift) & BIGNUM_TOP_BIT)
  389. break;
  390. if (mshift) {
  391. for (i = 0; i < mlen - 1; i++)
  392. m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
  393. m[mlen - 1] = m[mlen - 1] << mshift;
  394. }
  395. pqlen = (p[0] > q[0] ? p[0] : q[0]);
  396. /* Allocate n of size pqlen, copy p to n */
  397. n = snewn(pqlen, BignumInt);
  398. i = pqlen - p[0];
  399. for (j = 0; j < i; j++)
  400. n[j] = 0;
  401. for (j = 0; j < (int)p[0]; j++)
  402. n[i + j] = p[p[0] - j];
  403. /* Allocate o of size pqlen, copy q to o */
  404. o = snewn(pqlen, BignumInt);
  405. i = pqlen - q[0];
  406. for (j = 0; j < i; j++)
  407. o[j] = 0;
  408. for (j = 0; j < (int)q[0]; j++)
  409. o[i + j] = q[q[0] - j];
  410. /* Allocate a of size 2*pqlen for result */
  411. a = snewn(2 * pqlen, BignumInt);
  412. /* Main computation */
  413. internal_mul(n, o, a, pqlen);
  414. internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
  415. /* Fixup result in case the modulus was shifted */
  416. if (mshift) {
  417. for (i = 2 * pqlen - mlen - 1; i < 2 * pqlen - 1; i++)
  418. a[i] = (a[i] << mshift) | (a[i + 1] >> (BIGNUM_INT_BITS - mshift));
  419. a[2 * pqlen - 1] = a[2 * pqlen - 1] << mshift;
  420. internal_mod(a, pqlen * 2, m, mlen, NULL, 0);
  421. for (i = 2 * pqlen - 1; i >= 2 * pqlen - mlen; i--)
  422. a[i] = (a[i] >> mshift) | (a[i - 1] << (BIGNUM_INT_BITS - mshift));
  423. }
  424. /* Copy result to buffer */
  425. rlen = (mlen < pqlen * 2 ? mlen : pqlen * 2);
  426. result = newbn(rlen);
  427. for (i = 0; i < rlen; i++)
  428. result[result[0] - i] = a[i + 2 * pqlen - rlen];
  429. while (result[0] > 1 && result[result[0]] == 0)
  430. result[0]--;
  431. /* Free temporary arrays */
  432. for (i = 0; i < 2 * pqlen; i++)
  433. a[i] = 0;
  434. sfree(a);
  435. for (i = 0; i < mlen; i++)
  436. m[i] = 0;
  437. sfree(m);
  438. for (i = 0; i < pqlen; i++)
  439. n[i] = 0;
  440. sfree(n);
  441. for (i = 0; i < pqlen; i++)
  442. o[i] = 0;
  443. sfree(o);
  444. return result;
  445. }
  446. /*
  447. * Compute p % mod.
  448. * The most significant word of mod MUST be non-zero.
  449. * We assume that the result array is the same size as the mod array.
  450. * We optionally write out a quotient if `quotient' is non-NULL.
  451. * We can avoid writing out the result if `result' is NULL.
  452. */
  453. static void bigdivmod(Bignum p, Bignum mod, Bignum result, Bignum quotient)
  454. {
  455. BignumInt *n, *m;
  456. int mshift;
  457. int plen, mlen, i, j;
  458. /* Allocate m of size mlen, copy mod to m */
  459. /* We use big endian internally */
  460. mlen = mod[0];
  461. m = snewn(mlen, BignumInt);
  462. for (j = 0; j < mlen; j++)
  463. m[j] = mod[mod[0] - j];
  464. /* Shift m left to make msb bit set */
  465. for (mshift = 0; mshift < BIGNUM_INT_BITS-1; mshift++)
  466. if ((m[0] << mshift) & BIGNUM_TOP_BIT)
  467. break;
  468. if (mshift) {
  469. for (i = 0; i < mlen - 1; i++)
  470. m[i] = (m[i] << mshift) | (m[i + 1] >> (BIGNUM_INT_BITS - mshift));
  471. m[mlen - 1] = m[mlen - 1] << mshift;
  472. }
  473. plen = p[0];
  474. /* Ensure plen > mlen */
  475. if (plen <= mlen)
  476. plen = mlen + 1;
  477. /* Allocate n of size plen, copy p to n */
  478. n = snewn(plen, BignumInt);
  479. for (j = 0; j < plen; j++)
  480. n[j] = 0;
  481. for (j = 1; j <= (int)p[0]; j++)
  482. n[plen - j] = p[j];
  483. /* Main computation */
  484. internal_mod(n, plen, m, mlen, quotient, mshift);
  485. /* Fixup result in case the modulus was shifted */
  486. if (mshift) {
  487. for (i = plen - mlen - 1; i < plen - 1; i++)
  488. n[i] = (n[i] << mshift) | (n[i + 1] >> (BIGNUM_INT_BITS - mshift));
  489. n[plen - 1] = n[plen - 1] << mshift;
  490. internal_mod(n, plen, m, mlen, quotient, 0);
  491. for (i = plen - 1; i >= plen - mlen; i--)
  492. n[i] = (n[i] >> mshift) | (n[i - 1] << (BIGNUM_INT_BITS - mshift));
  493. }
  494. /* Copy result to buffer */
  495. if (result) {
  496. for (i = 1; i <= (int)result[0]; i++) {
  497. int j = plen - i;
  498. result[i] = j >= 0 ? n[j] : 0;
  499. }
  500. }
  501. /* Free temporary arrays */
  502. for (i = 0; i < mlen; i++)
  503. m[i] = 0;
  504. sfree(m);
  505. for (i = 0; i < plen; i++)
  506. n[i] = 0;
  507. sfree(n);
  508. }
  509. /*
  510. * Decrement a number.
  511. */
  512. void decbn(Bignum bn)
  513. {
  514. int i = 1;
  515. while (i < (int)bn[0] && bn[i] == 0)
  516. bn[i++] = BIGNUM_INT_MASK;
  517. bn[i]--;
  518. }
  519. Bignum bignum_from_bytes(const unsigned char *data, int nbytes)
  520. {
  521. Bignum result;
  522. int w, i;
  523. w = (nbytes + BIGNUM_INT_BYTES - 1) / BIGNUM_INT_BYTES; /* bytes->words */
  524. result = newbn(w);
  525. for (i = 1; i <= w; i++)
  526. result[i] = 0;
  527. for (i = nbytes; i--;) {
  528. unsigned char byte = *data++;
  529. result[1 + i / BIGNUM_INT_BYTES] |= byte << (8*i % BIGNUM_INT_BITS);
  530. }
  531. while (result[0] > 1 && result[result[0]] == 0)
  532. result[0]--;
  533. return result;
  534. }
  535. /*
  536. * Read an SSH-1-format bignum from a data buffer. Return the number
  537. * of bytes consumed, or -1 if there wasn't enough data.
  538. */
  539. int ssh1_read_bignum(const unsigned char *data, int len, Bignum * result)
  540. {
  541. const unsigned char *p = data;
  542. int i;
  543. int w, b;
  544. if (len < 2)
  545. return -1;
  546. w = 0;
  547. for (i = 0; i < 2; i++)
  548. w = (w << 8) + *p++;
  549. b = (w + 7) / 8; /* bits -> bytes */
  550. if (len < b+2)
  551. return -1;
  552. if (!result) /* just return length */
  553. return b + 2;
  554. *result = bignum_from_bytes(p, b);
  555. return p + b - data;
  556. }
  557. /*
  558. * Return the bit count of a bignum, for SSH-1 encoding.
  559. */
  560. int bignum_bitcount(Bignum bn)
  561. {
  562. int bitcount = bn[0] * BIGNUM_INT_BITS - 1;
  563. while (bitcount >= 0
  564. && (bn[bitcount / BIGNUM_INT_BITS + 1] >> (bitcount % BIGNUM_INT_BITS)) == 0) bitcount--;
  565. return bitcount + 1;
  566. }
  567. /*
  568. * Return the byte length of a bignum when SSH-1 encoded.
  569. */
  570. int ssh1_bignum_length(Bignum bn)
  571. {
  572. return 2 + (bignum_bitcount(bn) + 7) / 8;
  573. }
  574. /*
  575. * Return the byte length of a bignum when SSH-2 encoded.
  576. */
  577. int ssh2_bignum_length(Bignum bn)
  578. {
  579. return 4 + (bignum_bitcount(bn) + 8) / 8;
  580. }
  581. /*
  582. * Return a byte from a bignum; 0 is least significant, etc.
  583. */
  584. int bignum_byte(Bignum bn, int i)
  585. {
  586. if (i >= (int)(BIGNUM_INT_BYTES * bn[0]))
  587. return 0; /* beyond the end */
  588. else
  589. return (bn[i / BIGNUM_INT_BYTES + 1] >>
  590. ((i % BIGNUM_INT_BYTES)*8)) & 0xFF;
  591. }
  592. /*
  593. * Return a bit from a bignum; 0 is least significant, etc.
  594. */
  595. int bignum_bit(Bignum bn, int i)
  596. {
  597. if (i >= (int)(BIGNUM_INT_BITS * bn[0]))
  598. return 0; /* beyond the end */
  599. else
  600. return (bn[i / BIGNUM_INT_BITS + 1] >> (i % BIGNUM_INT_BITS)) & 1;
  601. }
  602. /*
  603. * Set a bit in a bignum; 0 is least significant, etc.
  604. */
  605. void bignum_set_bit(Bignum bn, int bitnum, int value)
  606. {
  607. if (bitnum >= (int)(BIGNUM_INT_BITS * bn[0]))
  608. abort(); /* beyond the end */
  609. else {
  610. int v = bitnum / BIGNUM_INT_BITS + 1;
  611. int mask = 1 << (bitnum % BIGNUM_INT_BITS);
  612. if (value)
  613. bn[v] |= mask;
  614. else
  615. bn[v] &= ~mask;
  616. }
  617. }
  618. /*
  619. * Write a SSH-1-format bignum into a buffer. It is assumed the
  620. * buffer is big enough. Returns the number of bytes used.
  621. */
  622. int ssh1_write_bignum(void *data, Bignum bn)
  623. {
  624. unsigned char *p = data;
  625. int len = ssh1_bignum_length(bn);
  626. int i;
  627. int bitc = bignum_bitcount(bn);
  628. *p++ = (bitc >> 8) & 0xFF;
  629. *p++ = (bitc) & 0xFF;
  630. for (i = len - 2; i--;)
  631. *p++ = bignum_byte(bn, i);
  632. return len;
  633. }
  634. /*
  635. * Compare two bignums. Returns like strcmp.
  636. */
  637. int bignum_cmp(Bignum a, Bignum b)
  638. {
  639. int amax = a[0], bmax = b[0];
  640. int i = (amax > bmax ? amax : bmax);
  641. while (i) {
  642. BignumInt aval = (i > amax ? 0 : a[i]);
  643. BignumInt bval = (i > bmax ? 0 : b[i]);
  644. if (aval < bval)
  645. return -1;
  646. if (aval > bval)
  647. return +1;
  648. i--;
  649. }
  650. return 0;
  651. }
  652. /*
  653. * Right-shift one bignum to form another.
  654. */
  655. Bignum bignum_rshift(Bignum a, int shift)
  656. {
  657. Bignum ret;
  658. int i, shiftw, shiftb, shiftbb, bits;
  659. BignumInt ai, ai1;
  660. bits = bignum_bitcount(a) - shift;
  661. ret = newbn((bits + BIGNUM_INT_BITS - 1) / BIGNUM_INT_BITS);
  662. if (ret) {
  663. shiftw = shift / BIGNUM_INT_BITS;
  664. shiftb = shift % BIGNUM_INT_BITS;
  665. shiftbb = BIGNUM_INT_BITS - shiftb;
  666. ai1 = a[shiftw + 1];
  667. for (i = 1; i <= (int)ret[0]; i++) {
  668. ai = ai1;
  669. ai1 = (i + shiftw + 1 <= (int)a[0] ? a[i + shiftw + 1] : 0);
  670. ret[i] = ((ai >> shiftb) | (ai1 << shiftbb)) & BIGNUM_INT_MASK;
  671. }
  672. }
  673. return ret;
  674. }
  675. /*
  676. * Non-modular multiplication and addition.
  677. */
  678. Bignum bigmuladd(Bignum a, Bignum b, Bignum addend)
  679. {
  680. int alen = a[0], blen = b[0];
  681. int mlen = (alen > blen ? alen : blen);
  682. int rlen, i, maxspot;
  683. BignumInt *workspace;
  684. Bignum ret;
  685. /* mlen space for a, mlen space for b, 2*mlen for result */
  686. workspace = snewn(mlen * 4, BignumInt);
  687. for (i = 0; i < mlen; i++) {
  688. workspace[0 * mlen + i] = (mlen - i <= (int)a[0] ? a[mlen - i] : 0);
  689. workspace[1 * mlen + i] = (mlen - i <= (int)b[0] ? b[mlen - i] : 0);
  690. }
  691. internal_mul(workspace + 0 * mlen, workspace + 1 * mlen,
  692. workspace + 2 * mlen, mlen);
  693. /* now just copy the result back */
  694. rlen = alen + blen + 1;
  695. if (addend && rlen <= (int)addend[0])
  696. rlen = addend[0] + 1;
  697. ret = newbn(rlen);
  698. maxspot = 0;
  699. for (i = 1; i <= (int)ret[0]; i++) {
  700. ret[i] = (i <= 2 * mlen ? workspace[4 * mlen - i] : 0);
  701. if (ret[i] != 0)
  702. maxspot = i;
  703. }
  704. ret[0] = maxspot;
  705. /* now add in the addend, if any */
  706. if (addend) {
  707. BignumDblInt carry = 0;
  708. for (i = 1; i <= rlen; i++) {
  709. carry += (i <= (int)ret[0] ? ret[i] : 0);
  710. carry += (i <= (int)addend[0] ? addend[i] : 0);
  711. ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
  712. carry >>= BIGNUM_INT_BITS;
  713. if (ret[i] != 0 && i > maxspot)
  714. maxspot = i;
  715. }
  716. }
  717. ret[0] = maxspot;
  718. sfree(workspace);
  719. return ret;
  720. }
  721. /*
  722. * Non-modular multiplication.
  723. */
  724. Bignum bigmul(Bignum a, Bignum b)
  725. {
  726. return bigmuladd(a, b, NULL);
  727. }
  728. /*
  729. * Create a bignum which is the bitmask covering another one. That
  730. * is, the smallest integer which is >= N and is also one less than
  731. * a power of two.
  732. */
  733. Bignum bignum_bitmask(Bignum n)
  734. {
  735. Bignum ret = copybn(n);
  736. int i;
  737. BignumInt j;
  738. i = ret[0];
  739. while (n[i] == 0 && i > 0)
  740. i--;
  741. if (i <= 0)
  742. return ret; /* input was zero */
  743. j = 1;
  744. while (j < n[i])
  745. j = 2 * j + 1;
  746. ret[i] = j;
  747. while (--i > 0)
  748. ret[i] = BIGNUM_INT_MASK;
  749. return ret;
  750. }
  751. /*
  752. * Convert a (max 32-bit) long into a bignum.
  753. */
  754. Bignum bignum_from_long(unsigned long nn)
  755. {
  756. Bignum ret;
  757. BignumDblInt n = nn;
  758. ret = newbn(3);
  759. ret[1] = (BignumInt)(n & BIGNUM_INT_MASK);
  760. ret[2] = (BignumInt)((n >> BIGNUM_INT_BITS) & BIGNUM_INT_MASK);
  761. ret[3] = 0;
  762. ret[0] = (ret[2] ? 2 : 1);
  763. return ret;
  764. }
  765. /*
  766. * Add a long to a bignum.
  767. */
  768. Bignum bignum_add_long(Bignum number, unsigned long addendx)
  769. {
  770. Bignum ret = newbn(number[0] + 1);
  771. int i, maxspot = 0;
  772. BignumDblInt carry = 0, addend = addendx;
  773. for (i = 1; i <= (int)ret[0]; i++) {
  774. carry += addend & BIGNUM_INT_MASK;
  775. carry += (i <= (int)number[0] ? number[i] : 0);
  776. addend >>= BIGNUM_INT_BITS;
  777. ret[i] = (BignumInt) carry & BIGNUM_INT_MASK;
  778. carry >>= BIGNUM_INT_BITS;
  779. if (ret[i] != 0)
  780. maxspot = i;
  781. }
  782. ret[0] = maxspot;
  783. return ret;
  784. }
  785. /*
  786. * Compute the residue of a bignum, modulo a (max 16-bit) short.
  787. */
  788. unsigned short bignum_mod_short(Bignum number, unsigned short modulus)
  789. {
  790. BignumDblInt mod, r;
  791. int i;
  792. r = 0;
  793. mod = modulus;
  794. for (i = number[0]; i > 0; i--)
  795. r = (r * (BIGNUM_TOP_BIT % mod) * 2 + number[i] % mod) % mod;
  796. return (unsigned short) r;
  797. }
  798. #ifdef DEBUG
  799. void diagbn(char *prefix, Bignum md)
  800. {
  801. int i, nibbles, morenibbles;
  802. static const char hex[] = "0123456789ABCDEF";
  803. debug(("%s0x", prefix ? prefix : ""));
  804. nibbles = (3 + bignum_bitcount(md)) / 4;
  805. if (nibbles < 1)
  806. nibbles = 1;
  807. morenibbles = 4 * md[0] - nibbles;
  808. for (i = 0; i < morenibbles; i++)
  809. debug(("-"));
  810. for (i = nibbles; i--;)
  811. debug(("%c",
  812. hex[(bignum_byte(md, i / 2) >> (4 * (i % 2))) & 0xF]));
  813. if (prefix)
  814. debug(("\n"));
  815. }
  816. #endif
  817. /*
  818. * Simple division.
  819. */
  820. Bignum bigdiv(Bignum a, Bignum b)
  821. {
  822. Bignum q = newbn(a[0]);
  823. bigdivmod(a, b, NULL, q);
  824. return q;
  825. }
  826. /*
  827. * Simple remainder.
  828. */
  829. Bignum bigmod(Bignum a, Bignum b)
  830. {
  831. Bignum r = newbn(b[0]);
  832. bigdivmod(a, b, r, NULL);
  833. return r;
  834. }
  835. /*
  836. * Greatest common divisor.
  837. */
  838. Bignum biggcd(Bignum av, Bignum bv)
  839. {
  840. Bignum a = copybn(av);
  841. Bignum b = copybn(bv);
  842. while (bignum_cmp(b, Zero) != 0) {
  843. Bignum t = newbn(b[0]);
  844. bigdivmod(a, b, t, NULL);
  845. while (t[0] > 1 && t[t[0]] == 0)
  846. t[0]--;
  847. freebn(a);
  848. a = b;
  849. b = t;
  850. }
  851. freebn(b);
  852. return a;
  853. }
  854. /*
  855. * Modular inverse, using Euclid's extended algorithm.
  856. */
  857. Bignum modinv(Bignum number, Bignum modulus)
  858. {
  859. Bignum a = copybn(modulus);
  860. Bignum b = copybn(number);
  861. Bignum xp = copybn(Zero);
  862. Bignum x = copybn(One);
  863. int sign = +1;
  864. while (bignum_cmp(b, One) != 0) {
  865. Bignum t = newbn(b[0]);
  866. Bignum q = newbn(a[0]);
  867. bigdivmod(a, b, t, q);
  868. while (t[0] > 1 && t[t[0]] == 0)
  869. t[0]--;
  870. freebn(a);
  871. a = b;
  872. b = t;
  873. t = xp;
  874. xp = x;
  875. x = bigmuladd(q, xp, t);
  876. sign = -sign;
  877. freebn(t);
  878. freebn(q);
  879. }
  880. freebn(b);
  881. freebn(a);
  882. freebn(xp);
  883. /* now we know that sign * x == 1, and that x < modulus */
  884. if (sign < 0) {
  885. /* set a new x to be modulus - x */
  886. Bignum newx = newbn(modulus[0]);
  887. BignumInt carry = 0;
  888. int maxspot = 1;
  889. int i;
  890. for (i = 1; i <= (int)newx[0]; i++) {
  891. BignumInt aword = (i <= (int)modulus[0] ? modulus[i] : 0);
  892. BignumInt bword = (i <= (int)x[0] ? x[i] : 0);
  893. newx[i] = aword - bword - carry;
  894. bword = ~bword;
  895. carry = carry ? (newx[i] >= bword) : (newx[i] > bword);
  896. if (newx[i] != 0)
  897. maxspot = i;
  898. }
  899. newx[0] = maxspot;
  900. freebn(x);
  901. x = newx;
  902. }
  903. /* and return. */
  904. return x;
  905. }
  906. /*
  907. * Render a bignum into decimal. Return a malloced string holding
  908. * the decimal representation.
  909. */
  910. char *bignum_decimal(Bignum x)
  911. {
  912. int ndigits, ndigit;
  913. int i, iszero;
  914. BignumDblInt carry;
  915. char *ret;
  916. BignumInt *workspace;
  917. /*
  918. * First, estimate the number of digits. Since log(10)/log(2)
  919. * is just greater than 93/28 (the joys of continued fraction
  920. * approximations...) we know that for every 93 bits, we need
  921. * at most 28 digits. This will tell us how much to malloc.
  922. *
  923. * Formally: if x has i bits, that means x is strictly less
  924. * than 2^i. Since 2 is less than 10^(28/93), this is less than
  925. * 10^(28i/93). We need an integer power of ten, so we must
  926. * round up (rounding down might make it less than x again).
  927. * Therefore if we multiply the bit count by 28/93, rounding
  928. * up, we will have enough digits.
  929. *
  930. * i=0 (i.e., x=0) is an irritating special case.
  931. */
  932. i = bignum_bitcount(x);
  933. if (!i)
  934. ndigits = 1; /* x = 0 */
  935. else
  936. ndigits = (28 * i + 92) / 93; /* multiply by 28/93 and round up */
  937. ndigits++; /* allow for trailing \0 */
  938. ret = snewn(ndigits, char);
  939. /*
  940. * Now allocate some workspace to hold the binary form as we
  941. * repeatedly divide it by ten. Initialise this to the
  942. * big-endian form of the number.
  943. */
  944. workspace = snewn(x[0], BignumInt);
  945. for (i = 0; i < (int)x[0]; i++)
  946. workspace[i] = x[x[0] - i];
  947. /*
  948. * Next, write the decimal number starting with the last digit.
  949. * We use ordinary short division, dividing 10 into the
  950. * workspace.
  951. */
  952. ndigit = ndigits - 1;
  953. ret[ndigit] = '\0';
  954. do {
  955. iszero = 1;
  956. carry = 0;
  957. for (i = 0; i < (int)x[0]; i++) {
  958. carry = (carry << BIGNUM_INT_BITS) + workspace[i];
  959. workspace[i] = (BignumInt) (carry / 10);
  960. if (workspace[i])
  961. iszero = 0;
  962. carry %= 10;
  963. }
  964. ret[--ndigit] = (char) (carry + '0');
  965. } while (!iszero);
  966. /*
  967. * There's a chance we've fallen short of the start of the
  968. * string. Correct if so.
  969. */
  970. if (ndigit > 0)
  971. memmove(ret, ret + ndigit, ndigits - ndigit);
  972. /*
  973. * Done.
  974. */
  975. sfree(workspace);
  976. return ret;
  977. }