Pollard's rho algorithm for computing discrete logs.
[u/mdw/catacomb] / mp-arith.c
1 /* -*-c-*-
2 *
3 * $Id: mp-arith.c,v 1.7 2000/06/22 19:02:53 mdw Exp $
4 *
5 * Basic arithmetic on multiprecision integers
6 *
7 * (c) 1999 Straylight/Edgeware
8 */
9
10 /*----- Licensing notice --------------------------------------------------*
11 *
12 * This file is part of Catacomb.
13 *
14 * Catacomb is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU Library General Public License as
16 * published by the Free Software Foundation; either version 2 of the
17 * License, or (at your option) any later version.
18 *
19 * Catacomb is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU Library General Public License for more details.
23 *
24 * You should have received a copy of the GNU Library General Public
25 * License along with Catacomb; if not, write to the Free
26 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
27 * MA 02111-1307, USA.
28 */
29
30 /*----- Revision history --------------------------------------------------*
31 *
32 * $Log: mp-arith.c,v $
33 * Revision 1.7 2000/06/22 19:02:53 mdw
34 * New function @mp_odd@ to extract powers of two from an integer. This is
35 * common code from the Rabin-Miller test, RSA key recovery and modular
36 * square-root extraction.
37 *
38 * Revision 1.6 2000/06/17 11:45:09 mdw
39 * Major memory management overhaul. Added arena support. Use the secure
40 * arena for secret integers. Replace and improve the MP management macros
41 * (e.g., replace MP_MODIFY by MP_DEST).
42 *
43 * Revision 1.5 1999/12/22 15:54:41 mdw
44 * Adjust Karatsuba parameters. Calculate destination size better.
45 *
46 * Revision 1.4 1999/12/13 15:35:16 mdw
47 * Slightly different rules on memory allocation.
48 *
49 * Revision 1.3 1999/12/11 10:57:43 mdw
50 * Karatsuba squaring algorithm.
51 *
52 * Revision 1.2 1999/12/10 23:18:39 mdw
53 * Change interface for suggested destinations.
54 *
55 * Revision 1.1 1999/11/17 18:02:16 mdw
56 * New multiprecision integer arithmetic suite.
57 *
58 */
59
60 /*----- Header files ------------------------------------------------------*/
61
62 #include "mp.h"
63
64 /*----- Macros ------------------------------------------------------------*/
65
66 #define MAX(x, y) ((x) >= (y) ? (x) : (y))
67
68 /*----- Main code ---------------------------------------------------------*/
69
70 /* --- @mp_2c@ --- *
71 *
72 * Arguments: @mp *a@ = source
73 *
74 * Returns: Result, @a@ converted to two's complement notation.
75 */
76
77 mp *mp_2c(mp *d, mp *a)
78 {
79 if (!(a->f & MP_NEG))
80 return (MP_COPY(a));
81
82 MP_DEST(d, MP_LEN(a), a->f);
83 mpx_2c(d->v, d->vl, a->v, a->vl);
84 d->f = a->f & MP_BURN;
85 MP_SHRINK(d);
86 return (d);
87 }
88
89 /* --- @mp_sm@ --- *
90 *
91 * Arguments: @mp *d@ = destination
92 * @mp *a@ = source
93 *
94 * Returns: Result, @a@ converted to the native signed-magnitude
95 * notation.
96 */
97
98 mp *mp_sm(mp *d, mp *a)
99 {
100 if (!MP_LEN(a) || a->vl[-1] < MPW_MAX / 2)
101 return (MP_COPY(a));
102
103 MP_DEST(d, MP_LEN(a), a->f);
104 mpx_2c(d->v, d->vl, a->v, a->vl);
105 d->f = (a->f & (MP_BURN | MP_NEG)) ^ MP_NEG;
106 MP_SHRINK(d);
107 return (d);
108 }
109
110 /* --- @mp_lsl@ --- *
111 *
112 * Arguments: @mp *d@ = destination
113 * @mp *a@ = source
114 * @size_t n@ = number of bits to move
115 *
116 * Returns: Result, @a@ shifted left by @n@.
117 */
118
119 mp *mp_lsl(mp *d, mp *a, size_t n)
120 {
121 MP_DEST(d, MP_LEN(a) + (n + MPW_BITS - 1) / MPW_BITS, a->f);
122 mpx_lsl(d->v, d->vl, a->v, a->vl, n);
123 d->f = a->f & (MP_NEG | MP_BURN);
124 MP_SHRINK(d);
125 return (d);
126 }
127
128 /* --- @mp_lsr@ --- *
129 *
130 * Arguments: @mp *d@ = destination
131 * @mp *a@ = source
132 * @size_t n@ = number of bits to move
133 *
134 * Returns: Result, @a@ shifted left by @n@.
135 */
136
137 mp *mp_lsr(mp *d, mp *a, size_t n)
138 {
139 MP_DEST(d, MP_LEN(a), a->f);
140 mpx_lsr(d->v, d->vl, a->v, a->vl, n);
141 d->f = a->f & (MP_NEG | MP_BURN);
142 MP_SHRINK(d);
143 return (d);
144 }
145
146 /* --- @mp_cmp@ --- *
147 *
148 * Arguments: @const mp *a, *b@ = two numbers
149 *
150 * Returns: Less than, equal to or greater than zero, according to
151 * whether @a@ is less than, equal to or greater than @b@.
152 */
153
154 int mp_cmp(const mp *a, const mp *b)
155 {
156 if (!((a->f ^ b->f) & MP_NEG))
157 return (mpx_ucmp(a->v, a->vl, b->v, b->vl));
158 else if (a->f & MP_NEG)
159 return (-1);
160 else
161 return (+1);
162 }
163
164 /* --- @mp_add@ --- *
165 *
166 * Arguments: @mp *d@ = destination
167 * @mp *a, *b@ = sources
168 *
169 * Returns: Result, @a@ added to @b@.
170 */
171
172 mp *mp_add(mp *d, mp *a, mp *b)
173 {
174 MP_DEST(d, MAX(MP_LEN(a), MP_LEN(b)) + 1, a->f | b->f);
175 if (!((a->f ^ b->f) & MP_NEG))
176 mpx_uadd(d->v, d->vl, a->v, a->vl, b->v, b->vl);
177 else {
178 if (MPX_UCMP(a->v, a->vl, <, b->v, b->vl)) {
179 mp *t = a; a = b; b = t;
180 }
181 mpx_usub(d->v, d->vl, a->v, a->vl, b->v, b->vl);
182 }
183 d->f = ((a->f | b->f) & MP_BURN) | (a->f & MP_NEG);
184 MP_SHRINK(d);
185 return (d);
186 }
187
188 /* --- @mp_sub@ --- *
189 *
190 * Arguments: @mp *d@ = destination
191 * @mp *a, *b@ = sources
192 *
193 * Returns: Result, @b@ subtracted from @a@.
194 */
195
196 mp *mp_sub(mp *d, mp *a, mp *b)
197 {
198 unsigned sgn = 0;
199 MP_DEST(d, MAX(MP_LEN(a), MP_LEN(b)) + 1, a->f | b->f);
200 if ((a->f ^ b->f) & MP_NEG)
201 mpx_uadd(d->v, d->vl, a->v, a->vl, b->v, b->vl);
202 else {
203 if (MPX_UCMP(a->v, a->vl, <, b->v, b->vl)) {
204 mp *t = a; a = b; b = t;
205 sgn = MP_NEG;
206 }
207 mpx_usub(d->v, d->vl, a->v, a->vl, b->v, b->vl);
208 }
209 d->f = ((a->f | b->f) & MP_BURN) | ((a->f ^ sgn) & MP_NEG);
210 MP_SHRINK(d);
211 return (d);
212 }
213
214 /* --- @mp_mul@ --- *
215 *
216 * Arguments: @mp *d@ = destination
217 * @mp *a, *b@ = sources
218 *
219 * Returns: Result, @a@ multiplied by @b@.
220 */
221
222 mp *mp_mul(mp *d, mp *a, mp *b)
223 {
224 a = MP_COPY(a);
225 b = MP_COPY(b);
226
227 if (MP_LEN(a) <= KARATSUBA_CUTOFF || MP_LEN(b) <= KARATSUBA_CUTOFF) {
228 MP_DEST(d, MP_LEN(a) + MP_LEN(b), a->f | b->f | MP_UNDEF);
229 mpx_umul(d->v, d->vl, a->v, a->vl, b->v, b->vl);
230 } else {
231 size_t m = 2 * MAX(MP_LEN(a), MP_LEN(b)) + 2;
232 mpw *s;
233 MP_DEST(d, m, a->f | b->f | MP_UNDEF);
234 m += KARATSUBA_SLOP;
235 s = mpalloc(d->a, m);
236 mpx_kmul(d->v, d->vl, a->v, a->vl, b->v, b->vl, s, s + m);
237 mpfree(d->a, s);
238 }
239
240 d->f = ((a->f | b->f) & MP_BURN) | ((a->f ^ b->f) & MP_NEG);
241 MP_SHRINK(d);
242 MP_DROP(a);
243 MP_DROP(b);
244 return (d);
245 }
246
247 /* --- @mp_sqr@ --- *
248 *
249 * Arguments: @mp *d@ = destination
250 * @mp *a@ = source
251 *
252 * Returns: Result, @a@ squared.
253 */
254
255 mp *mp_sqr(mp *d, mp *a)
256 {
257 size_t m = MP_LEN(a);
258
259 a = MP_COPY(a);
260 MP_DEST(d, 2 * m + 2, a->f | MP_UNDEF);
261 if (m > KARATSUBA_CUTOFF) {
262 mpw *s;
263 m = 2 * (m + 1) + KARATSUBA_SLOP;
264 s = mpalloc(d->a, m);
265 mpx_ksqr(d->v, d->vl, a->v, a->vl, s, s + m);
266 mpfree(d->a, s);
267 } else
268 mpx_usqr(d->v, d->vl, a->v, a->vl);
269 d->f = a->f & MP_BURN;
270 MP_SHRINK(d);
271 MP_DROP(a);
272 return (d);
273 }
274
275 /* --- @mp_div@ --- *
276 *
277 * Arguments: @mp **qq, **rr@ = destination, quotient and remainder
278 * @mp *a, *b@ = sources
279 *
280 * Use: Calculates the quotient and remainder when @a@ is divided by
281 * @b@. The destinations @*qq@ and @*rr@ must be distinct.
282 * Either of @qq@ or @rr@ may be null to indicate that the
283 * result is irrelevant. (Discarding both results is silly.)
284 * There is a performance advantage if @a == *rr@.
285 *
286 * The behaviour when @a@ and @b@ have the same sign is
287 * straightforward. When the signs differ, this implementation
288 * chooses @r@ to have the same sign as @b@, rather than the
289 * more normal choice that the remainder has the same sign as
290 * the dividend. This makes modular arithmetic a little more
291 * straightforward.
292 */
293
294 void mp_div(mp **qq, mp **rr, mp *a, mp *b)
295 {
296 mp *r = rr ? *rr : MP_NEW;
297 mp *q = qq ? *qq : MP_NEW;
298 mpw *sv, *svl;
299
300 /* --- Set the remainder up right --- *
301 *
302 * Just in case the divisor is larger, be able to cope with this. It's not
303 * important in @mpx_udiv@, but it is here because of the sign correction.
304 */
305
306 b = MP_COPY(b);
307 a = MP_COPY(a);
308 if (r)
309 MP_DROP(r);
310 r = a;
311 MP_DEST(r, MP_LEN(a) + 2, a->f | b->f);
312
313 /* --- Fix up the quotient too --- */
314
315 r = MP_COPY(r);
316 MP_DEST(q, MP_LEN(r), r->f | MP_UNDEF);
317 MP_DROP(r);
318
319 /* --- Set up some temporary workspace --- */
320
321 {
322 size_t rq = MP_LEN(b) + 1;
323 sv = mpalloc(r->a, rq);
324 svl = sv + rq;
325 }
326
327 /* --- Perform the calculation --- */
328
329 mpx_udiv(q->v, q->vl, r->v, r->vl, b->v, b->vl, sv, svl);
330
331 /* --- Sort out the sign of the results --- *
332 *
333 * If the signs of the arguments differ, and the remainder is nonzero, I
334 * must add one to the absolute value of the quotient and subtract the
335 * remainder from @b@.
336 */
337
338 q->f = ((r->f | b->f) & MP_BURN) | ((r->f ^ b->f) & MP_NEG);
339 if (q->f & MP_NEG) {
340 mpw *v;
341 for (v = r->v; v < r->vl; v++) {
342 if (*v) {
343 MPX_UADDN(q->v, q->vl, 1);
344 mpx_usub(r->v, r->vl, b->v, b->vl, r->v, r->vl);
345 break;
346 }
347 }
348 }
349
350 r->f = ((r->f | b->f) & MP_BURN) | (b->f & MP_NEG);
351
352 /* --- Store the return values --- */
353
354 mpfree(r->a, sv);
355 MP_DROP(b);
356
357 if (!qq)
358 MP_DROP(q);
359 else {
360 MP_SHRINK(q);
361 *qq = q;
362 }
363
364 if (!rr)
365 MP_DROP(r);
366 else {
367 MP_SHRINK(r);
368 *rr = r;
369 }
370 }
371
372 /* --- @mp_odd@ --- *
373 *
374 * Arguments: @mp *d@ = pointer to destination integer
375 * @mp *m@ = pointer to source integer
376 * @size_t *s@ = where to store the power of 2
377 *
378 * Returns: An odd integer integer %$t$% such that %$m = 2^s t$%.
379 *
380 * Use: Computes a power of two and an odd integer which, when
381 * multiplied, give a specified result. This sort of thing is
382 * useful in number theory quite often.
383 */
384
385 mp *mp_odd(mp *d, mp *m, size_t *s)
386 {
387 size_t ss = 0;
388 const mpw *v, *vl;
389
390 v = m->v;
391 vl = m->vl;
392 for (; !*v && v < vl; v++)
393 ss += MPW_BITS;
394 if (v >= vl)
395 ss = 0;
396 else {
397 mpw x = *v;
398 mpw mask = MPW_MAX;
399 unsigned z = MPW_BITS / 2;
400
401 while (z) {
402 mask >>= z;
403 if (!(x & mask)) {
404 x >>= z;
405 ss += z;
406 }
407 z >>= 1;
408 }
409 }
410
411 *s = ss;
412 return (mp_lsr(d, m, ss));
413 }
414
415 /*----- Test rig ----------------------------------------------------------*/
416
417 #ifdef TEST_RIG
418
419 static int verify(const char *op, mp *expect, mp *result, mp *a, mp *b)
420 {
421 if (MP_CMP(expect, !=, result)) {
422 fprintf(stderr, "\n*** %s failed", op);
423 fputs("\n*** a = ", stderr); mp_writefile(a, stderr, 10);
424 fputs("\n*** b = ", stderr); mp_writefile(b, stderr, 10);
425 fputs("\n*** result = ", stderr); mp_writefile(result, stderr, 10);
426 fputs("\n*** expect = ", stderr); mp_writefile(expect, stderr, 10);
427 fputc('\n', stderr);
428 return (0);
429 }
430 return (1);
431 }
432
433 #define RIG(name, op) \
434 static int t##name(dstr *v) \
435 { \
436 mp *a = *(mp **)v[0].buf; \
437 mpw n = *(int *)v[1].buf; \
438 mp b; \
439 mp *r = *(mp **)v[2].buf; \
440 mp *c = op(MP_NEW, a, n); \
441 int ok; \
442 mp_build(&b, &n, &n + 1); \
443 ok = verify(#name, r, c, a, &b); \
444 mp_drop(a); mp_drop(c); mp_drop(r); \
445 assert(mparena_count(MPARENA_GLOBAL) == 0); \
446 return (ok); \
447 }
448
449 RIG(lsl, mp_lsl)
450 RIG(lsr, mp_lsr)
451
452 #undef RIG
453
454 #define RIG(name, op) \
455 static int t##name(dstr *v) \
456 { \
457 mp *a = *(mp **)v[0].buf; \
458 mp *b = *(mp **)v[1].buf; \
459 mp *r = *(mp **)v[2].buf; \
460 mp *c = op(MP_NEW, a, b); \
461 int ok = verify(#name, r, c, a, b); \
462 mp_drop(a); mp_drop(b); mp_drop(c); mp_drop(r); \
463 assert(mparena_count(MPARENA_GLOBAL) == 0); \
464 return (ok); \
465 }
466
467 RIG(add, mp_add)
468 RIG(sub, mp_sub)
469 RIG(mul, mp_mul)
470
471 #undef RIG
472
473 static int tdiv(dstr *v)
474 {
475 mp *a = *(mp **)v[0].buf;
476 mp *b = *(mp **)v[1].buf;
477 mp *q = *(mp **)v[2].buf;
478 mp *r = *(mp **)v[3].buf;
479 mp *c = MP_NEW, *d = MP_NEW;
480 int ok = 1;
481 mp_div(&c, &d, a, b);
482 ok &= verify("div(quotient)", q, c, a, b);
483 ok &= verify("div(remainder)", r, d, a, b);
484 mp_drop(a); mp_drop(b); mp_drop(c); mp_drop(d); mp_drop(r); mp_drop(q);
485 assert(mparena_count(MPARENA_GLOBAL) == 0);
486 return (ok);
487 }
488
489 static int todd(dstr *v)
490 {
491 mp *a = *(mp **)v[0].buf;
492 size_t rs = *(uint32 *)v[1].buf;
493 mp *rt = *(mp **)v[2].buf;
494 int ok = 1;
495 mp *t;
496 size_t s;
497 t = mp_odd(MP_NEW, a, &s);
498 if (s != rs || MP_CMP(t, !=, rt)) {
499 ok = 0;
500 fprintf(stderr, "\n*** odd failed");
501 fputs("\n*** a = ", stderr); mp_writefile(a, stderr, 10);
502 fprintf(stderr, "\n*** s = %lu", (unsigned long)s);
503 fputs("\n*** t = ", stderr); mp_writefile(t, stderr, 10);
504 fprintf(stderr, "\n*** rs = %lu", (unsigned long)rs);
505 fputs("\n*** rt = ", stderr); mp_writefile(rt, stderr, 10);
506 fputc('\n', stderr);
507 }
508 mp_drop(a);
509 mp_drop(rt);
510 mp_drop(t);
511 return (ok);
512 }
513
514 static test_chunk tests[] = {
515 { "lsl", tlsl, { &type_mp, &type_mp, &type_mp, 0 } },
516 { "lsr", tlsr, { &type_mp, &type_mp, &type_mp, 0 } },
517 { "add", tadd, { &type_mp, &type_mp, &type_mp, 0 } },
518 { "sub", tsub, { &type_mp, &type_mp, &type_mp, 0 } },
519 { "mul", tmul, { &type_mp, &type_mp, &type_mp, 0 } },
520 { "div", tdiv, { &type_mp, &type_mp, &type_mp, &type_mp, 0 } },
521 { "odd", todd, { &type_mp, &type_uint32, &type_mp, 0 } },
522 { 0, 0, { 0 } },
523 };
524
525 int main(int argc, char *argv[])
526 {
527 sub_init();
528 test_run(argc, argv, tests, SRCDIR "/tests/mp");
529 return (0);
530 }
531
532 #endif
533
534 /*----- That's all, folks -------------------------------------------------*/