]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_cryptkit/lib/giantIntegers.c
Security-59754.80.3.tar.gz
[apple/security.git] / OSX / libsecurity_cryptkit / lib / giantIntegers.c
1 /* Copyright (c) 1998,2011-2014 Apple Inc. All Rights Reserved.
2 *
3 * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT
4 * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE
5 * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE
6 * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE,
7 * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL
8 * EXPOSE YOU TO LIABILITY.
9 ***************************************************************************
10
11 giantIntegers.c - library for large-integer arithmetic.
12
13 Revision History
14 ----------------
15 Fixed a==b bug in addg().
16 10/06/98 ap
17 Changed to compile with C++.
18 13 Apr 98 Fixed shiftright(1) bug in modg_via_recip.
19 09 Apr 98 at Apple
20 Major rewrite of core arithmetic routines to make this module
21 independent of size of giantDigit.
22 Removed idivg() and radixdiv().
23 20 Jan 98 at Apple
24 Deleted FFT arithmetic; simplified mulg().
25 09 Jan 98 at Apple
26 gshiftright() optimization.
27 08 Jan 98 at Apple
28 newGiant() returns NULL on malloc failure
29 24 Dec 97 at Apple
30 New grammarSquare(); optimized modg_via_recip()
31 11 Jun 97 at Apple
32 Added modg_via_recip(), divg_via_recip(), make_recip()
33 Added new multiple giant stack mechanism
34 Fixed potential packing/alignment bug in copyGiant()
35 Added profiling for borrowGiant(), returnGiant()
36 Deleted obsolete ifdef'd code
37 Deleted newgiant()
38 All calls to borrowGiant() now specify required size (no more
39 borrowGiant(0) calls)
40 08 May 97 at Apple
41 Changed size of giantstruct.n to 1 for Mac build
42 05 Feb 97 at Apple
43 newGiant() no longer modifies CurrentMaxShorts or giant stack
44 Added modg profiling
45 01 Feb 97 at NeXT
46 Added iszero() check in gcompg
47 17 Jan 97 at NeXT
48 Fixed negation bug in gmersennemod()
49 Fixed n[words-1] == 0 bug in extractbits()
50 Cleaned up lots of static declarations
51 19 Sep 96 at NeXT
52 Fixed --size underflow bug in normal_subg().
53 4 Sep 96 at NeXT
54 Fixed (b<n), (sign<0) case in gmersennemod() to allow for arbitrary n.
55 9 Aug 96 at NeXT
56 Fixed sign-extend bug in data_to_giant().
57 7 Aug 96 at NeXT
58 Changed precision in newtondivide().
59 Removed #ifdef UNUSED code.
60 24 Jul 96 at NeXT
61 Added scompg().
62 Created.
63
64 */
65
66 #include <stdio.h>
67 #include <stdlib.h>
68 #include <string.h>
69 #include "platform.h"
70 #include "giantIntegers.h"
71 #include "feeDebug.h"
72 #include "ckconfig.h"
73 #include "ellipticMeasure.h"
74 #include "falloc.h"
75 #include "giantPortCommon.h"
76
77 #ifdef FEE_DEBUG
78 #if (GIANT_LOG2_BITS_PER_DIGIT == 4)
79 #warning Compiling with two-byte giantDigits
80 #endif
81 #endif
82
83 #if 0
84 #if FEE_DEBUG
85 char printbuf1[200];
86 char printbuf2[200];
87 char printbuf3[200];
88 void printGiantBuf(giant x)
89 {
90 int i;
91
92 sprintf(printbuf2, "sign=%d cap=%d n[]=", x->sign, x->capacity);
93 for(i=0; i<abs(x->sign); i++) {
94 sprintf(printbuf3 + 10*i, "%u:", x->n[i]);
95 }
96 }
97
98 char printbuf4[200];
99 char printbuf5[200];
100 void printGiantBuf2(giant x)
101 {
102 int i;
103
104 sprintf(printbuf4, "sign=%d cap=%d n[]=", x->sign, x->capacity);
105 for(i=0; i<abs(x->sign); i++) {
106 sprintf(printbuf5 + 10*i, "%u:", x->n[i]);
107 }
108 }
109 #endif /* FEE_DEBUG */
110 #endif /* 0 */
111
112 /******** debugging flags *********/
113
114 /*
115 * Flag use of unoptimized divg, modg, binvg
116 */
117 //#define WARN_UNOPTIMIZE FEE_DEBUG
118 #define WARN_UNOPTIMIZE 0
119
120 /*
121 * Log interesting giant stack events
122 */
123 #define LOG_GIANT_STACK 0
124
125 /*
126 * Log allocation of giant larger than stack size
127 */
128 #define LOG_GIANT_STACK_OVERFLOW 1
129
130 /*
131 * Flag newGiant(0) and borrowGiant(0) calls
132 */
133 #define WARN_ZERO_GIANT_SIZE FEE_DEBUG
134
135 /* temp mac-only giant initialization debug */
136 #define GIANT_MAC_DEBUG 0
137 #if GIANT_MAC_DEBUG
138
139 #include <string.h>
140 #include <TextUtils.h>
141
142 /* this one needs a writable string */
143 static void logCom(unsigned char *str) {
144 c2pstr((char *)str);
145 DebugStr(str);
146 }
147
148 /* constant strings */
149 void dblog0(const char *str) {
150 Str255 outStr;
151 strcpy((char *)outStr, str);
152 logCom(outStr);
153 }
154
155 #else
156 #define dblog0(s)
157
158 #endif /* GIANT_MAC_DEBUG */
159
160 #ifndef min
161 #define min(a,b) ((a)<(b)? (a) : (b))
162 #endif // min
163 #ifndef max
164 #define max(a,b) ((a)>(b)? (a) : (b))
165 #endif // max
166
167 #ifndef TRUE
168 #define TRUE 1
169 #endif // TRUE
170 #ifndef FALSE
171 #define FALSE 0
172 #endif // FALSE
173
174 static void absg(giant g); /* g := |g|. */
175
176 /************** globals *******************/
177
178
179 /* ------ giant stack package ------ */
180
181 /*
182 * The giant stack package is a local cache which allows us to avoid calls
183 * to malloc() for borrowGiant(). On a 90 Mhz Pentium, enabling the
184 * giant stack package shows about a 1.35 speedup factor over an identical
185 * CryptKit without the giant stacks enabled.
186 */
187
188
189
190 giant borrowGiant(unsigned numDigits)
191 {
192 giant result;
193 result = newGiant(numDigits);
194
195 PROF_INCR(numBorrows);
196 return result;
197 }
198
199 void returnGiant(giant g)
200 {
201 freeGiant(g);
202 }
203
204 void freeGiant(giant x) {
205 ffree(x);
206 }
207
208 giant newGiant(unsigned numDigits) {
209 // giant sufficient for 2^numbits+16 sized ops
210 int size;
211 giant result;
212
213 #if WARN_ZERO_GIANT_SIZE
214 if(numDigits == 0) {
215 printf("newGiant(0)\n");
216 /* HACK */
217 numDigits = 20;
218 }
219 #endif // WARN_ZERO_GIANT_SIZE
220
221 size = (numDigits-1) * GIANT_BYTES_PER_DIGIT + sizeof(giantstruct);
222 result = (giant)fmalloc(size);
223 if(result == NULL) {
224 return NULL;
225 }
226 result->sign = 0;
227 result->capacity = numDigits;
228 return result;
229 }
230
231 giant copyGiant(giant x)
232 {
233 int bytes;
234
235 giant result = newGiant(x->capacity);
236
237 /*
238 * 13 Jun 1997
239 * NO! this assumes packed alignment
240 */
241 bytes = sizeof(giantstruct) +
242 ((x->capacity - 1) * GIANT_BYTES_PER_DIGIT);
243 bcopy(x, result, bytes);
244 return result;
245 }
246
247 /* ------ initialization and utility routines ------ */
248
249
250 unsigned bitlen(giant n) {
251 unsigned b = GIANT_BITS_PER_DIGIT;
252 giantDigit c = ((giantDigit)1) << (GIANT_BITS_PER_DIGIT - 1);
253 giantDigit w;
254
255 if (isZero(n)) {
256 return(0);
257 }
258 w = n->n[abs(n->sign) - 1];
259 if (!w) {
260 CKRaise("bitlen - no bit set!");
261 }
262 while((w&c) == 0) {
263 b--;
264 c >>= 1;
265 }
266 return(GIANT_BITS_PER_DIGIT * (abs(n->sign)-1) + b);
267 }
268
269 int bitval(giant n, int pos) {
270 int i = abs(pos) >> GIANT_LOG2_BITS_PER_DIGIT;
271 giantDigit c = ((giantDigit)1) << (pos & (GIANT_BITS_PER_DIGIT - 1));
272
273 return ((0!=((n->n[i]) & c))?1:0);
274 }
275
276 int gsign(giant g)
277 /* returns the sign of g */
278 {
279 if (isZero(g)) return(0);
280 if (g->sign > 0) return(1);
281 return(-1);
282 }
283
284 /*
285 * Adjust sign for possible leading (m.s.) zero digits
286 */
287 void gtrimSign(giant g)
288 {
289 int numDigits = abs(g->sign);
290 int i;
291
292 for(i=numDigits-1; i>=0; i--) {
293 if(g->n[i] == 0) {
294 numDigits--;
295 }
296 else {
297 break;
298 }
299 }
300 if(g->sign < 0) {
301 g->sign = -numDigits;
302 }
303 else {
304 g->sign = numDigits;
305 }
306 }
307
308
309 int isone(giant g) {
310 return((g->sign==1)&&(g->n[0]==1));
311 }
312
313 int isZero(giant thegiant) {
314 /* Returns TRUE if thegiant == 0. */
315 int count;
316 int length = abs(thegiant->sign);
317 giantDigit *numpointer;
318
319 if (length) {
320 numpointer = thegiant->n;
321
322 for(count = 0; count<length; ++count,++numpointer)
323 if (*numpointer != 0 ) return(FALSE);
324 }
325 return(TRUE);
326 }
327
328 int gcompg(giant a, giant b)
329 /* returns -1,0,1 if a<b, a=b, a>b, respectively */
330 {
331 int sa = a->sign;
332 int j;
333 int sb = b->sign;
334 giantDigit va;
335 giantDigit vb;
336 int sgn;
337
338 if(isZero(a) && isZero(b)) return 0;
339 if(sa > sb) return(1);
340 if(sa < sb) return(-1);
341 if(sa < 0) {
342 sa = -sa; /* Take absolute value of sa */
343 sgn = -1;
344 } else sgn = 1;
345 for(j = sa-1; j >= 0; j--) {
346 va = a->n[j]; vb = b->n[j];
347 if (va > vb) return(sgn);
348 if (va < vb) return(-sgn);
349 }
350 return(0);
351 }
352
353 /* destgiant becomes equal to srcgiant */
354 void gtog(giant srcgiant, giant destgiant) {
355
356 int numbytes;
357
358 CKASSERT(srcgiant != NULL);
359 numbytes = abs(srcgiant->sign) * GIANT_BYTES_PER_DIGIT;
360 if (destgiant->capacity < abs(srcgiant->sign))
361 CKRaise("gtog overflow!!");
362 memcpy((char *)destgiant->n, (char *)srcgiant->n, numbytes);
363 destgiant->sign = srcgiant->sign;
364 }
365
366 void int_to_giant(int i, giant g) {
367 /* The giant g becomes set to the integer value i. */
368 int isneg = (i<0);
369 unsigned int j = abs(i);
370 unsigned dex;
371
372 g->sign = 0;
373 if (i==0) {
374 g->n[0] = 0;
375 return;
376 }
377
378 if(GIANT_BYTES_PER_DIGIT == sizeof(int)) {
379 g->n[0] = j;
380 g->sign = 1;
381 }
382 else {
383 /* one loop per digit */
384 unsigned scnt = GIANT_BITS_PER_DIGIT; // fool compiler
385
386 for(dex=0; dex<sizeof(int); dex++) {
387 g->n[dex] = j & GIANT_DIGIT_MASK;
388 j >>= scnt;
389 g->sign++;
390 if(j == 0) {
391 break;
392 }
393 }
394 }
395 if (isneg) {
396 g->sign = -(g->sign);
397 }
398 }
399
400 /*------------- Arithmetic --------------*/
401
402 void negg(giant g) {
403 /* g becomes -g */
404 g->sign = -g->sign;
405 }
406
407 void iaddg(int i, giant g) { /* positive g becomes g + (int)i */
408 int j;
409 giantDigit carry;
410 int size = abs(g->sign);
411
412 if (isZero(g)) {
413 int_to_giant(i,g);
414 }
415 else {
416 carry = i;
417 for(j=0; ((j<size) && (carry != 0)); j++) {
418 g->n[j] = giantAddDigits(g->n[j], carry, &carry);
419 }
420 if(carry) {
421 ++g->sign;
422 // realloc
423 if (g->sign > (int)g->capacity) CKRaise("iaddg overflow!");
424 g->n[size] = carry;
425 }
426 }
427 }
428
429 /*
430 * g *= (int n)
431 *
432 * FIXME - we can improve this...
433 */
434 void imulg(unsigned n, giant g)
435 {
436 giant tmp = borrowGiant(abs(g->sign) + sizeof(int));
437
438 int_to_giant(n, tmp);
439 mulg(tmp, g);
440 returnGiant(tmp);
441 }
442
443 static void normal_addg(giant a, giant b)
444 /* b := a + b, both a,b assumed non-negative. */
445 {
446 giantDigit carry1 = 0;
447 giantDigit carry2 = 0;
448 int asize = a->sign, bsize = b->sign;
449 giantDigit *an = a->n;
450 giantDigit *bn = b->n;
451 giantDigit tmp;
452 int j;
453 int comSize;
454 int maxSize;
455
456 if(asize < bsize) {
457 comSize = asize;
458 maxSize = bsize;
459 }
460 else {
461 comSize = bsize;
462 maxSize = asize;
463 }
464
465 /* first handle the common digits */
466 for(j=0; j<comSize; j++) {
467 /*
468 * first add the carry, then an[j] - either add could result
469 * in another carry
470 */
471 if(carry1 || carry2) {
472 tmp = giantAddDigits(bn[j], (giantDigit)1, &carry1);
473 }
474 else {
475 carry1 = 0;
476 tmp = bn[j];
477 }
478 bn[j] = giantAddDigits(tmp, an[j], &carry2);
479 }
480
481 if(asize < bsize) {
482
483 /* now propagate remaining carry beyond asize */
484 if(carry2) {
485 carry1 = 1;
486 }
487 if(carry1) {
488 for(; j<bsize; j++) {
489 bn[j] = giantAddDigits(bn[j], (giantDigit)1, &carry1);
490 if(carry1 == 0) {
491 break;
492 }
493 }
494 }
495 } else {
496 /* now propagate remaining an[] and carry beyond bsize */
497 if(carry2) {
498 carry1 = 1;
499 }
500 for(; j<asize; j++) {
501 if(carry1) {
502 bn[j] = giantAddDigits(an[j], (giantDigit)1, &carry1);
503 }
504 else {
505 bn[j] = an[j];
506 carry1 = 0;
507 }
508 }
509 }
510 b->sign = maxSize;
511 if(carry1) {
512 // realloc?
513 bn[j] = 1;
514 b->sign++;
515 if (b->sign > (int)b->capacity) CKRaise("iaddg overflow!");
516 }
517
518 }
519
520 static void normal_subg(giant a, giant b)
521 /* b := b - a; requires b, a non-negative and b >= a. */
522 {
523 int j;
524 int size = b->sign;
525 giantDigit tmp;
526 giantDigit borrow1 = 0;
527 giantDigit borrow2 = 0;
528 giantDigit *an = a->n;
529 giantDigit *bn = b->n;
530
531 if(a->sign == 0) {
532 return;
533 }
534
535 for (j=0; j<a->sign; ++j) {
536 if(borrow1 || borrow2) {
537 tmp = giantSubDigits(bn[j], (giantDigit)1, &borrow1);
538 }
539 else {
540 tmp = bn[j];
541 borrow1 = 0;
542 }
543 bn[j] = giantSubDigits(tmp, an[j], &borrow2);
544 }
545 if(borrow1 || borrow2) {
546 /* propagate borrow thru remainder of bn[] */
547 borrow1 = 1;
548 for (j=a->sign; j<size; ++j) {
549 if(borrow1) {
550 bn[j] = giantSubDigits(bn[j], (giantDigit)1, &borrow1);
551 }
552 else {
553 break;
554 }
555 }
556 }
557
558 /* adjust sign for leading zero digits */
559 while((size-- > 0) && (b->n[size] == 0))
560 ;
561 b->sign = (b->n[size] == 0)? 0 : size+1;
562 }
563
564 static void reverse_subg(giant a, giant b)
565 /* b := a - b; requires b, a non-negative and a >= b. */
566 {
567 int j;
568 int size = a->sign;
569 giantDigit tmp;
570 giantDigit borrow1 = 0;
571 giantDigit borrow2 = 0;
572 giantDigit *an = a->n;
573 giantDigit *bn = b->n;
574
575 if(b->sign == 0) {
576 gtog(a, b);
577 return;
578 }
579 for (j=0; j<b->sign; ++j) {
580 if(borrow1 || borrow2) {
581 tmp = giantSubDigits(an[j], (giantDigit)1, &borrow1);
582 }
583 else {
584 tmp = an[j];
585 borrow1 = 0;
586 }
587 bn[j] = giantSubDigits(tmp, bn[j], &borrow2);
588 }
589 if(borrow1 || borrow2) {
590 /* propagate borrow thru remainder of bn[] */
591 borrow1 = 1;
592 }
593 for (j=b->sign; j<size; ++j) {
594 if(borrow1) {
595 bn[j] = giantSubDigits(an[j], (giantDigit)1, &borrow1);
596 }
597 else {
598 bn[j] = an[j];
599 borrow1 = 0;
600 }
601 }
602
603 b->sign = size; /* REC, 21 Apr 1996. */
604 while(!b->n[--size]);
605 b->sign = size+1;
606 }
607
608
609 void addg(giant a, giant b)
610 /* b := b + a, any signs any result. */
611 { int asgn = a->sign, bsgn = b->sign;
612 if(asgn == 0) return;
613 if(bsgn == 0) {
614 gtog(a,b);
615 return;
616 }
617 if((asgn < 0) == (bsgn < 0)) {
618 if(bsgn > 0) {
619 normal_addg(a,b);
620 return;
621 }
622 negg(a); if(a != b) negg(b); normal_addg(a,b); /* Fix REC 1 Dec 98. */
623 negg(a); if(a != b) negg(b); return; /* Fix REC 1 Dec 98. */
624 }
625 if(bsgn > 0) {
626 negg(a);
627 if(gcompg(b,a) >= 0) {
628 normal_subg(a,b);
629 negg(a);
630 return;
631 }
632 reverse_subg(a,b);
633 negg(a);
634 negg(b);
635 return;
636 }
637 negg(b);
638 if(gcompg(b,a) < 0) {
639 reverse_subg(a,b);
640 return;
641 }
642 normal_subg(a,b);
643 negg(b);
644 return;
645 }
646
647 void subg(giant a, giant b)
648 /* b := b - a, any signs, any result. */
649 {
650 int asgn = a->sign, bsgn = b->sign;
651 if(asgn == 0) return;
652 if(bsgn == 0) {
653 gtog(a,b);
654 negg(b);
655 return;
656 }
657 if((asgn < 0) != (bsgn < 0)) {
658 if(bsgn > 0) {
659 negg(a);
660 normal_addg(a,b);
661 negg(a);
662 return;
663 }
664 negg(b);
665 normal_addg(a,b);
666 negg(b);
667 return;
668 }
669 if(bsgn > 0) {
670 if(gcompg(b,a) >= 0) {
671 normal_subg(a,b);
672 return;
673 }
674 reverse_subg(a,b);
675 negg(b);
676 return;
677 }
678 negg(a); negg(b);
679 if(gcompg(b,a) >= 0) {
680 normal_subg(a,b);
681 negg(a);
682 negg(b);
683 return;
684 }
685 reverse_subg(a,b);
686 negg(a);
687 return;
688 }
689
690 static void bdivg(giant v, giant u)
691 /* u becomes greatest power of two not exceeding u/v. */
692 {
693 int diff = bitlen(u) - bitlen(v);
694 giant scratch7;
695
696 if (diff<0) {
697 int_to_giant(0,u);
698 return;
699 }
700 scratch7 = borrowGiant(u->capacity);
701 gtog(v, scratch7);
702 gshiftleft(diff,scratch7);
703 if(gcompg(u,scratch7) < 0) diff--;
704 if(diff<0) {
705 int_to_giant(0,u);
706 returnGiant(scratch7);
707 return;
708 }
709 int_to_giant(1,u);
710 gshiftleft(diff,u);
711 returnGiant(scratch7);
712 }
713
714 int binvaux(giant p, giant x)
715 /* Binary inverse method.
716 Returns zero if no inverse exists, in which case x becomes
717 GCD(x,p). */
718 {
719 giant scratch7;
720 giant u0;
721 giant u1;
722 giant v0;
723 giant v1;
724 int result = 1;
725 int giantSize;
726 PROF_START;
727
728 if(isone(x)) return(result);
729 giantSize = 4 * abs(p->sign);
730 scratch7 = borrowGiant(giantSize);
731 u0 = borrowGiant(giantSize);
732 u1 = borrowGiant(giantSize);
733 v0 = borrowGiant(giantSize);
734 v1 = borrowGiant(giantSize);
735 int_to_giant(1, v0); gtog(x, v1);
736 int_to_giant(0,x); gtog(p, u1);
737 while(!isZero(v1)) {
738 gtog(u1, u0); bdivg(v1, u0);
739 gtog(x, scratch7);
740 gtog(v0, x);
741 mulg(u0, v0);
742 subg(v0,scratch7);
743 gtog(scratch7, v0);
744
745 gtog(u1, scratch7);
746 gtog(v1, u1);
747 mulg(u0, v1);
748 subg(v1,scratch7);
749 gtog(scratch7, v1);
750 }
751 if (!isone(u1)) {
752 gtog(u1,x);
753 if(x->sign<0) addg(p, x);
754 result = 0;
755 goto done;
756 }
757 if (x->sign<0) addg(p, x);
758 done:
759 returnGiant(scratch7);
760 returnGiant(u0);
761 returnGiant(u1);
762 returnGiant(v0);
763 returnGiant(v1);
764 PROF_END(binvauxTime);
765 return(result);
766 }
767
768 /*
769 * Superceded by binvg_cp()
770 */
771 #if 0
772 int binvg(giant p, giant x)
773 {
774 modg(p, x);
775 return(binvaux(p,x));
776 }
777 #endif
778
779 static void absg(giant g) {
780 /* g becomes the absolute value of g */
781 if (g->sign < 0) g->sign = -g->sign;
782 }
783
784 void gshiftleft(int bits, giant g) {
785 /* shift g left bits bits. Equivalent to g = g*2^bits */
786 int rem = bits & (GIANT_BITS_PER_DIGIT - 1);
787 int crem = GIANT_BITS_PER_DIGIT - rem;
788 int digits = 1 + (bits >> GIANT_LOG2_BITS_PER_DIGIT);
789 int size = abs(g->sign);
790 int j;
791 int k;
792 int sign = gsign(g);
793 giantDigit carry;
794 giantDigit dat;
795
796 #if FEE_DEBUG
797 if(bits < 0) {
798 CKRaise("gshiftleft(-bits)\n");
799 }
800 #endif /* FEE_DEBUG */
801
802 if(!bits) return;
803 if(!size) return;
804 if((size+digits) > (int)g->capacity) {
805 CKRaise("gshiftleft overflow");
806 }
807 k = size - 1 + digits; // (MSD of result + 1)
808 carry = 0;
809
810 /* bug fix for 32-bit giantDigits; this is also an optimization for
811 * other sizes. rem=0 means we're shifting strictly by digits, no
812 * bit shifts. */
813 if(rem == 0) {
814 g->n[k] = 0; // XXX hack - for sign fixup
815 for(j=size-1; j>=0; j--) {
816 g->n[--k] = g->n[j];
817 }
818 do{
819 g->n[--k] = 0;
820 } while(k>0);
821 }
822 else {
823 /*
824 * normal unaligned case
825 * FIXME - this writes past g->n[size-1] the first time thru!
826 */
827 for(j=size-1; j>=0; j--) {
828 dat = g->n[j];
829 g->n[k--] = (dat >> crem) | carry;
830 carry = (dat << rem);
831 }
832 do{
833 g->n[k--] = carry;
834 carry = 0;
835 } while(k>=0);
836 }
837 k = size - 1 + digits;
838 if(g->n[k] == 0) --k;
839 g->sign = sign * (k+1);
840 if (abs(g->sign) > g->capacity) {
841 CKRaise("gshiftleft overflow");
842 }
843 }
844
845 void gshiftright(int bits, giant g) {
846 /* shift g right bits bits. Equivalent to g = g/2^bits */
847 int j;
848 int size=abs(g->sign);
849 giantDigit carry;
850 int digits = bits >> GIANT_LOG2_BITS_PER_DIGIT;
851 int remain = bits & (GIANT_BITS_PER_DIGIT - 1);
852 int cremain = GIANT_BITS_PER_DIGIT - remain;
853
854 #if FEE_DEBUG
855 if(bits < 0) {
856 CKRaise("gshiftright(-bits)\n");
857 }
858 #endif /* FEE_DEBUG */
859 if(bits==0) return;
860 if(isZero(g)) return;
861 if (digits >= size) {
862 g->sign = 0;
863 return;
864 }
865
866 size -= digits;
867
868 /* Begin OPT: 9 Jan 98 REC. */
869 if(remain == 0) {
870 if(g->sign > 0) {
871 g->sign = size;
872 }
873 else {
874 g->sign = -size;
875 }
876 for(j=0; j < size; j++) {
877 g->n[j] = g->n[j+digits];
878 }
879 return;
880 }
881 /* End OPT: 9 Jan 98 REC. */
882
883 for(j=0;j<size;++j) {
884 if (j==size-1) {
885 carry = 0;
886 }
887 else {
888 carry = (g->n[j+digits+1]) << cremain;
889 }
890 g->n[j] = ((g->n[j+digits]) >> remain ) | carry;
891 }
892 if (g->n[size-1] == 0) {
893 --size;
894 }
895 if(g->sign > 0) {
896 g->sign = size;
897 }
898 else {
899 g->sign = -size;
900 }
901 if (abs(g->sign) > g->capacity) {
902 CKRaise("gshiftright overflow");
903 }
904 }
905
906
907 void extractbits(unsigned n, giant src, giant dest) {
908 /* dest becomes lowermost n bits of src. Equivalent to dest = src % 2^n */
909 int digits = n >> GIANT_LOG2_BITS_PER_DIGIT;
910 int numbytes = digits * GIANT_BYTES_PER_DIGIT;
911 int bits = n & (GIANT_BITS_PER_DIGIT - 1);
912
913 if (n <= 0) {
914 return;
915 }
916 if (dest->capacity * 8 * GIANT_BYTES_PER_DIGIT < n) {
917 CKRaise("extractbits - not enough room");
918 }
919 if (digits >= abs(src->sign)) {
920 gtog(src,dest);
921 }
922 else {
923 memcpy((char *)(dest->n), (char *)(src->n), numbytes);
924 if (bits) {
925 dest->n[digits] = src->n[digits] & ((1<<bits)-1);
926 ++digits;
927 }
928 /* Next, fix by REC, 12 Jan 97. */
929 // while((dest->n[words-1] == 0) && (words > 0)) --words;
930 while((digits > 0) && (dest->n[digits-1] == 0)) {
931 --digits;
932 }
933 if(src->sign < 0) {
934 dest->sign = -digits;
935 }
936 else {
937 dest->sign = digits;
938 }
939 }
940 if (abs(dest->sign) > dest->capacity) {
941 CKRaise("extractbits overflow");
942 }
943 }
944
945 #define NEW_MERSENNE 0
946
947 /*
948 * New gmersennemod, 24 Dec 1997. This runs significantly slower than the
949 * original.
950 */
951 #if NEW_MERSENNE
952
953 void
954 gmersennemod(
955 int n,
956 giant g
957 )
958 /* g := g (mod 2^n - 1) */
959 {
960 int the_sign;
961 giant scratch3 = borrowGiant(g->capacity);
962 giant scratch4 = borrowGiant(1);
963
964 if ((the_sign = gsign(g)) < 0) absg(g);
965 while (bitlen(g) > n) {
966 gtog(g,scratch3);
967 gshiftright(n,scratch3);
968 addg(scratch3,g);
969 gshiftleft(n,scratch3);
970 subg(scratch3,g);
971 }
972 if(isZero(g)) goto out;
973 int_to_giant(1,scratch3);
974 gshiftleft(n,scratch3);
975 int_to_giant(1,scratch4);
976 subg(scratch4,scratch3);
977 if(gcompg(g,scratch3) >= 0) subg(scratch3,g);
978 if (the_sign < 0) {
979 g->sign = -g->sign;
980 addg(scratch3,g);
981 }
982 out:
983 returnGiant(scratch3);
984 returnGiant(scratch4);
985 }
986
987 #else /* NEW_MERSENNE */
988
989 void gmersennemod(int n, giant g) {
990 /* g becomes g mod ((2^n)-1)
991 31 Jul 96 modified REC.
992 17 Jan 97 modified REC.
993 */
994 unsigned bits = n & (GIANT_BITS_PER_DIGIT - 1);
995 unsigned digits = 1 + ((n-1) >> GIANT_LOG2_BITS_PER_DIGIT);
996 int isPositive = (g->sign > 0);
997 int j;
998 int b;
999 int size;
1000 int foundzero;
1001 giantDigit mask = (bits == 0) ? GIANT_DIGIT_MASK : (giantDigit)((1<<bits)-1);
1002 giant scratch1;
1003
1004 b = bitlen(g);
1005 if(b < n) {
1006 unsigned numDigits = (n + GIANT_BITS_PER_DIGIT - 1) >>
1007 GIANT_LOG2_BITS_PER_DIGIT;
1008 giantDigit lastWord = 0;
1009 giantDigit bits = 1;
1010
1011 if(g->sign >= 0) return;
1012
1013 /*
1014 * Cons up ((2**n)-1), add to g.
1015 */
1016 scratch1 = borrowGiant(numDigits + 1);
1017 scratch1->sign = numDigits;
1018 for(j=0; j<(int)(numDigits-1); j++) {
1019 scratch1->n[j] = GIANT_DIGIT_MASK;
1020 }
1021
1022 /*
1023 * Last word has lower (n & (GIANT_BITS_PER_DIGIT-1)) bits set.
1024 */
1025 for(j=0; j < (int)(n & (GIANT_BITS_PER_DIGIT-1)); j++) {
1026 lastWord |= bits;
1027 bits <<= 1;
1028 }
1029 scratch1->n[numDigits-1] = lastWord;
1030 addg(g, scratch1); /* One version. */
1031 gtog(scratch1, g);
1032 returnGiant(scratch1);
1033 return;
1034 }
1035 if(b == n) {
1036 for(foundzero=0, j=0; j<b; j++) {
1037 if(bitval(g, j)==0) {
1038 foundzero = 1;
1039 break;
1040 }
1041 }
1042 if (!foundzero) {
1043 int_to_giant(0, g);
1044 return;
1045 }
1046 }
1047
1048 absg(g);
1049 scratch1 = borrowGiant(g->capacity);
1050 while ( ((unsigned)(g->sign) > digits) ||
1051 ( ((unsigned)(g->sign)==digits) && (g->n[digits-1] > mask))) {
1052 extractbits(n, g, scratch1);
1053 gshiftright(n, g);
1054 addg(scratch1, g);
1055 }
1056 size = g->sign;
1057
1058 /* Commence new negation routine - REC 17 Jan 1997. */
1059 if (!isPositive) { /* Mersenne negation is just bitwise complement. */
1060 for(j = digits-1; j >= size; j--) {
1061 g->n[j] = GIANT_DIGIT_MASK;
1062 }
1063 for(j = size-1; j >= 0; j--) {
1064 g->n[j] = ~g->n[j];
1065 }
1066 g->n[digits-1] &= mask;
1067 j = digits-1;
1068 while((g->n[j] == 0) && (j > 0)) {
1069 --j;
1070 }
1071 size = j+1;
1072 }
1073 /* End new negation routine. */
1074
1075 g->sign = size;
1076 if (abs(g->sign) > g->capacity) {
1077 CKRaise("gmersennemod overflow");
1078 }
1079 if (size < (int)digits) {
1080 goto bye;
1081 }
1082 if (g->n[size-1] != mask) {
1083 goto bye;
1084 }
1085 mask = GIANT_DIGIT_MASK;
1086 for(j=0; j<(size-1); j++) {
1087 if (g->n[j] != mask) {
1088 goto bye;
1089 }
1090 }
1091 g->sign = 0;
1092 bye:
1093 returnGiant(scratch1);
1094 }
1095
1096 #endif /* NEW_MERSENNE */
1097
1098 void mulg(giant a, giant b) { /* b becomes a*b. */
1099
1100 int i;
1101 int asize, bsize;
1102 giantDigit *bptr = b->n;
1103 giantDigit mult;
1104 giant scratch1;
1105 giantDigit carry;
1106 giantDigit *scrPtr;
1107
1108
1109 if (isZero(b)) {
1110 return;
1111 }
1112 if (isZero(a)) {
1113 gtog(a, b);
1114 return;
1115 }
1116 if(a == b) {
1117 grammarSquare(b);
1118 return;
1119 }
1120
1121 bsize = abs(b->sign);
1122 asize = abs(a->sign);
1123 scratch1 = borrowGiant((asize+bsize));
1124 scrPtr = scratch1->n;
1125
1126 for(i=0; i<asize+bsize; ++i) {
1127 scrPtr[i]=0;
1128 }
1129
1130 for(i=0; i<bsize; ++i, scrPtr++) {
1131 mult = bptr[i];
1132 if (mult != 0) {
1133 carry = VectorMultiply(mult,
1134 a->n,
1135 asize,
1136 scrPtr);
1137 /* handle MSD carry */
1138 scrPtr[asize] += carry;
1139 }
1140 }
1141 bsize+=asize;
1142 if(scratch1->n[bsize - 1] == 0) {
1143 --bsize;
1144 }
1145 scratch1->sign = gsign(a) * gsign(b) * bsize;
1146 if (abs(scratch1->sign) > scratch1->capacity) {
1147 CKRaise("GiantGrammarMul overflow");
1148 }
1149 gtog(scratch1,b);
1150 returnGiant(scratch1);
1151
1152 #if FEE_DEBUG
1153 (void)bitlen(b); // Assertion....
1154 #endif /* FEE_DEBUG */
1155 PROF_INCR(numMulg); // for normal profiling
1156 INCR_MULGS; // for ellipticMeasure
1157 }
1158
1159 void grammarSquare(giant a) {
1160 /*
1161 * For now, we're going to match the old implementation line for
1162 * line by maintaining prod, carry, and temp as double precision
1163 * giantDigits. There is probably a much better implementation....
1164 */
1165 giantDigit prodLo;
1166 giantDigit prodHi;
1167 giantDigit carryLo = 0;
1168 giantDigit carryHi = 0;
1169 giantDigit tempLo;
1170 giantDigit tempHi;
1171 unsigned int cur_term;
1172 unsigned asize;
1173 unsigned max;
1174 giantDigit *ptr = a->n;
1175 giantDigit *ptr1;
1176 giantDigit *ptr2;
1177 giant scratch;
1178
1179 /* dmitch 11 Jan 1998 - special case for a == 0 */
1180 if(a->sign == 0) {
1181 goto end;
1182 }
1183 /* end a == 0 case */
1184 asize = abs(a->sign);
1185 max = asize * 2 - 1;
1186 scratch = borrowGiant(2 * asize);
1187 asize--;
1188
1189 /*
1190 * temp = *ptr;
1191 * temp *= temp;
1192 * scratch->n[0] = temp;
1193 * carry = temp >> 16;
1194 */
1195 giantMulDigits(*ptr, *ptr, &tempLo, &tempHi);
1196 scratch->n[0] = tempLo;
1197 carryLo = tempHi;
1198 carryHi = 0;
1199
1200 for (cur_term = 1; cur_term < max; cur_term++) {
1201 ptr1 = ptr2 = ptr;
1202 if (cur_term <= asize) {
1203 ptr2 += cur_term;
1204 } else {
1205 ptr1 += cur_term - asize;
1206 ptr2 += asize;
1207 }
1208
1209 /*
1210 * prod = carry & 0xFFFF;
1211 * carry >>= 16;
1212 */
1213 prodLo = carryLo;
1214 prodHi = 0;
1215 carryLo = carryHi;
1216 carryHi = 0;
1217 while(ptr1 < ptr2) {
1218 /*
1219 * temp = *ptr1++ * *ptr2--;
1220 */
1221 giantMulDigits(*ptr1++, *ptr2--, &tempLo, &tempHi);
1222
1223 /*
1224 * prod += (temp << 1) & 0xFFFF;
1225 */
1226 giantAddDouble(&prodLo, &prodHi, (tempLo << 1));
1227
1228 /*
1229 * carry += (temp >> 15);
1230 * use bits from both product digits..
1231 */
1232 giantAddDouble(&carryLo, &carryHi,
1233 (tempLo >> (GIANT_BITS_PER_DIGIT - 1)));
1234 giantAddDouble(&carryLo, &carryHi, (tempHi << 1));
1235
1236 /* snag the msb from that last shift */
1237 carryHi += (tempHi >> (GIANT_BITS_PER_DIGIT - 1));
1238 }
1239 if (ptr1 == ptr2) {
1240 /*
1241 * temp = *ptr1;
1242 * temp *= temp;
1243 */
1244 giantMulDigits(*ptr1, *ptr1, &tempLo, &tempHi);
1245
1246 /*
1247 * prod += temp & 0xFFFF;
1248 */
1249 giantAddDouble(&prodLo, &prodHi, tempLo);
1250
1251 /*
1252 * carry += (temp >> 16);
1253 */
1254 giantAddDouble(&carryLo, &carryHi, tempHi);
1255 }
1256
1257 /*
1258 * carry += prod >> 16;
1259 */
1260 giantAddDouble(&carryLo, &carryHi, prodHi);
1261
1262 scratch->n[cur_term] = prodLo;
1263 }
1264 if (carryLo) {
1265 scratch->n[cur_term] = carryLo;
1266 scratch->sign = cur_term+1;
1267 } else scratch->sign = cur_term;
1268
1269 gtog(scratch,a);
1270 returnGiant(scratch);
1271 end:
1272 PROF_INCR(numGsquare);
1273 }
1274
1275 /*
1276 * Clear all of a giant's data fields, for secure erasure of sensitive data.,
1277 */
1278 void clearGiant(giant g)
1279 {
1280 unsigned i;
1281
1282 for(i=0; i<g->capacity; i++) {
1283 g->n[i] = 0;
1284 }
1285 g->sign = 0;
1286 }
1287
1288 /*
1289 */
1290
1291 /*
1292 * Calculate the reciprocal of a demonimator used in divg_via_recip() and
1293 * modg_via_recip().
1294 */
1295 void
1296 make_recip(giant d, giant r)
1297 /* r becomes the steady-state reciprocal
1298 2^(2b)/d, where b = bit-length of d-1. */
1299 {
1300 int b;
1301 int giantSize = 4 * abs(d->sign);
1302 giant tmp = borrowGiant(giantSize);
1303 giant tmp2 = borrowGiant(giantSize);
1304
1305 if (isZero(d) || (d->sign < 0))
1306 {
1307 CKRaise("illegal argument to make_recip");
1308 }
1309 int_to_giant(1, r); subg(r, d); b = bitlen(d); addg(r, d);
1310 gshiftleft(b, r); gtog(r, tmp2);
1311 while(1) {
1312 gtog(r, tmp);
1313 gsquare(tmp);
1314 gshiftright(b, tmp);
1315 mulg(d, tmp);
1316 gshiftright(b, tmp);
1317 addg(r, r); subg(tmp, r);
1318 if(gcompg(r, tmp2) <= 0) break;
1319 gtog(r, tmp2);
1320 }
1321 int_to_giant(1, tmp);
1322 gshiftleft(2*b, tmp);
1323 gtog(r, tmp2); mulg(d, tmp2);
1324 subg(tmp2, tmp);
1325 int_to_giant(1, tmp2);
1326 while(tmp->sign < 0) {
1327 subg(tmp2, r);
1328 addg(d, tmp);
1329 }
1330
1331 returnGiant(tmp);
1332 returnGiant(tmp2);
1333 return;
1334 }
1335
1336 /*
1337 * Optimized divg, when reciprocal of denominator is known.
1338 */
1339 void
1340 divg_via_recip(giant d, giant r, giant n)
1341 /* n := n/d, where r is the precalculated
1342 steady-state reciprocal of d. */
1343 {
1344 int s = 2*(bitlen(r)-1), sign = gsign(n);
1345 int giantSize = (4 * abs(d->sign)) + abs(n->sign);
1346 giant tmp = borrowGiant(giantSize);
1347 giant tmp2 = borrowGiant(giantSize);
1348
1349 if (isZero(d) || (d->sign < 0))
1350 {
1351 CKRaise("illegal argument to divg_via_recip");
1352 }
1353 n->sign = abs(n->sign);
1354 int_to_giant(0, tmp2);
1355 while(1) {
1356 gtog(n, tmp);
1357 mulg(r, tmp);
1358 gshiftright(s, tmp);
1359 addg(tmp, tmp2);
1360 mulg(d, tmp);
1361 subg(tmp, n);
1362 if(gcompg(n,d) >= 0) {
1363 subg(d,n);
1364 iaddg(1, tmp2);
1365 }
1366 if(gcompg(n,d) < 0) break;
1367 }
1368 gtog(tmp2, n);
1369 n->sign *= sign;
1370 returnGiant(tmp);
1371 returnGiant(tmp2);
1372 return;
1373 }
1374
1375 /*
1376 * Optimized modg, when reciprocal of denominator is known.
1377 */
1378
1379 /* New version, 24 Dec 1997. */
1380
1381 void
1382 modg_via_recip(
1383 giant d,
1384 giant r,
1385 giant n
1386 )
1387 /* This is the fastest mod of the present collection.
1388 n := n % d, where r is the precalculated
1389 steady-state reciprocal of d. */
1390
1391 {
1392 int s = (bitlen(r)-1), sign = n->sign;
1393 int giantSize = (4 * abs(d->sign)) + abs(n->sign);
1394 giant tmp, tmp2;
1395
1396 tmp = borrowGiant(giantSize);
1397 tmp2 = borrowGiant(giantSize);
1398 if (isZero(d) || (d->sign < 0))
1399 {
1400 CKRaise("illegal argument to modg_via_recip");
1401 }
1402 n->sign = abs(n->sign);
1403 while (1)
1404 {
1405 gtog(n, tmp);
1406 /* bug fix 13 Apr 1998 */
1407 if(s == 0) {
1408 gshiftleft(1, tmp);
1409 }
1410 else {
1411 gshiftright(s-1, tmp);
1412 }
1413 /* end fix */
1414 mulg(r, tmp);
1415 gshiftright(s+1, tmp);
1416 mulg(d, tmp);
1417 subg(tmp, n);
1418 if (gcompg(n,d) >= 0)
1419 subg(d,n);
1420 if (gcompg(n,d) < 0)
1421 break;
1422 }
1423 if (sign >= 0)
1424 goto done;
1425 if (isZero(n))
1426 goto done;
1427 negg(n);
1428 addg(d,n);
1429 done:
1430 returnGiant(tmp);
1431 returnGiant(tmp2);
1432 return;
1433 }
1434
1435 /*
1436 * Unoptimized, inefficient general modg, when reciprocal of denominator
1437 * is not known.
1438 */
1439 void
1440 modg(
1441 giant d,
1442 giant n
1443 )
1444 {
1445 /* n becomes n%d. n is arbitrary, but the denominator d must be
1446 * positive! */
1447
1448 /*
1449 * 4/9/2001: seeing overflow on this recip. Alloc per
1450 * d->capacity, not d->sign.
1451 */
1452 //giant recip = borrowGiant(2 * abs(d->sign));
1453 giant recip = borrowGiant(2 * d->capacity);
1454
1455 #if WARN_UNOPTIMIZE
1456 dbgLog(("Warning: unoptimized modg!\n"));
1457 #endif // WARN_UNOPTIMIZE
1458
1459 make_recip(d, recip);
1460 modg_via_recip(d, recip, n);
1461 returnGiant(recip);
1462 }
1463
1464 /*
1465 * Unoptimized, inefficient general divg, when reciprocal of denominator
1466 * is not known.
1467 */
1468 void
1469 divg(
1470 giant d,
1471 giant n
1472 )
1473 {
1474 /* n becomes n/d. n is arbitrary, but the denominator d must be
1475 * positive!
1476 */
1477
1478 giant recip = borrowGiant(2 * abs(d->sign));
1479
1480 #if WARN_UNOPTIMIZE
1481 dbgLog(("Warning: unoptimized divg!\n"));
1482 #endif // WARN_UNOPTIMIZE
1483
1484 make_recip(d, recip);
1485 divg_via_recip(d, recip, n);
1486 returnGiant(recip);
1487 }