source: trunk/phpgwapi/js/expressoAjax/bigInt.js @ 2847

Revision 2847, 47.7 KB checked in by amuller, 14 years ago (diff)

Ticket #1086 - Implementando a classe rsa com passagem entre php e js

Line 
1////////////////////////////////////////////////////////////////////////////////////////
2// Big Integer Library v. 5.4
3// Created 2000, last modified 2009
4// Leemon Baird
5// www.leemon.com
6//
7// Version history:
8// v 5.4  3 Oct 2009
9//   - added "var i" to greaterShift() so i is not global. (Thanks to Pr Szabor finding that bug)
10//
11// v 5.3  21 Sep 2009
12//   - added randProbPrime(k) for probable primes
13//   - unrolled loop in mont_ (slightly faster)
14//   - millerRabin now takes a bigInt parameter rather than an int
15//
16// v 5.2  15 Sep 2009
17//   - fixed capitalization in call to int2bigInt in randBigInt
18//     (thanks to Emili Evripidou, Reinhold Behringer, and Samuel Macaleese for finding that bug)
19//
20// v 5.1  8 Oct 2007
21//   - renamed inverseModInt_ to inverseModInt since it doesn't change its parameters
22//   - added functions GCD and randBigInt, which call GCD_ and randBigInt_
23//   - fixed a bug found by Rob Visser (see comment with his name below)
24//   - improved comments
25//
26// This file is public domain.   You can use it for any purpose without restriction.
27// I do not guarantee that it is correct, so use it at your own risk.  If you use
28// it for something interesting, I'd appreciate hearing about it.  If you find
29// any bugs or make any improvements, I'd appreciate hearing about those too.
30// It would also be nice if my name and URL were left in the comments.  But none
31// of that is required.
32//
33// This code defines a bigInt library for arbitrary-precision integers.
34// A bigInt is an array of integers storing the value in chunks of bpe bits,
35// little endian (buff[0] is the least significant word).
36// Negative bigInts are stored two's complement.  Almost all the functions treat
37// bigInts as nonnegative.  The few that view them as two's complement say so
38// in their comments.  Some functions assume their parameters have at least one
39// leading zero element. Functions with an underscore at the end of the name put
40// their answer into one of the arrays passed in, and have unpredictable behavior
41// in case of overflow, so the caller must make sure the arrays are big enough to
42// hold the answer.  But the average user should never have to call any of the
43// underscored functions.  Each important underscored function has a wrapper function
44// of the same name without the underscore that takes care of the details for you. 
45// For each underscored function where a parameter is modified, that same variable
46// must not be used as another argument too.  So, you cannot square x by doing
47// multMod_(x,x,n).  You must use squareMod_(x,n) instead, or do y=dup(x); multMod_(x,y,n).
48// Or simply use the multMod(x,x,n) function without the underscore, where
49// such issues never arise, because non-underscored functions never change
50// their parameters; they always allocate new memory for the answer that is returned.
51//
52// These functions are designed to avoid frequent dynamic memory allocation in the inner loop.
53// For most functions, if it needs a BigInt as a local variable it will actually use
54// a global, and will only allocate to it only when it's not the right size.  This ensures
55// that when a function is called repeatedly with same-sized parameters, it only allocates
56// memory on the first call.
57//
58// Note that for cryptographic purposes, the calls to Math.random() must
59// be replaced with calls to a better pseudorandom number generator.
60//
61// In the following, "bigInt" means a bigInt with at least one leading zero element,
62// and "integer" means a nonnegative integer less than radix.  In some cases, integer
63// can be negative.  Negative bigInts are 2s complement.
64//
65// The following functions do not modify their inputs.
66// Those returning a bigInt, string, or Array will dynamically allocate memory for that value.
67// Those returning a boolean will return the integer 0 (false) or 1 (true).
68// Those returning boolean or int will not allocate memory except possibly on the first
69// time they're called with a given parameter size.
70//
71// bigInt  add(x,y)               //return (x+y) for bigInts x and y. 
72// bigInt  addInt(x,n)            //return (x+n) where x is a bigInt and n is an integer.
73// string  bigInt2str(x,base)     //return a string form of bigInt x in a given base, with 2 <= base <= 95
74// int     bitSize(x)             //return how many bits long the bigInt x is, not counting leading zeros
75// bigInt  dup(x)                 //return a copy of bigInt x
76// boolean equals(x,y)            //is the bigInt x equal to the bigint y?
77// boolean equalsInt(x,y)         //is bigint x equal to integer y?
78// bigInt  expand(x,n)            //return a copy of x with at least n elements, adding leading zeros if needed
79// Array   findPrimes(n)          //return array of all primes less than integer n
80// bigInt  GCD(x,y)               //return greatest common divisor of bigInts x and y (each with same number of elements).
81// boolean greater(x,y)           //is x>y?  (x and y are nonnegative bigInts)
82// boolean greaterShift(x,y,shift)//is (x <<(shift*bpe)) > y?
83// bigInt  int2bigInt(t,n,m)      //return a bigInt equal to integer t, with at least n bits and m array elements
84// bigInt  inverseMod(x,n)        //return (x**(-1) mod n) for bigInts x and n.  If no inverse exists, it returns null
85// int     inverseModInt(x,n)     //return x**(-1) mod n, for integers x and n.  Return 0 if there is no inverse
86// boolean isZero(x)              //is the bigInt x equal to zero?
87// boolean millerRabin(x,b)       //does one round of Miller-Rabin base integer b say that bigInt x is possibly prime? (b is bigInt, 1<b<x)
88// boolean millerRabinInt(x,b)    //does one round of Miller-Rabin base integer b say that bigInt x is possibly prime? (b is int,    1<b<x)
89// bigInt  mod(x,n)               //return a new bigInt equal to (x mod n) for bigInts x and n.
90// int     modInt(x,n)            //return x mod n for bigInt x and integer n.
91// bigInt  mult(x,y)              //return x*y for bigInts x and y. This is faster when y<x.
92// bigInt  multMod(x,y,n)         //return (x*y mod n) for bigInts x,y,n.  For greater speed, let y<x.
93// boolean negative(x)            //is bigInt x negative?
94// bigInt  powMod(x,y,n)          //return (x**y mod n) where x,y,n are bigInts and ** is exponentiation.  0**0=1. Faster for odd n.
95// bigInt  randBigInt(n,s)        //return an n-bit random BigInt (n>=1).  If s=1, then the most significant of those n bits is set to 1.
96// bigInt  randTruePrime(k)       //return a new, random, k-bit, true prime bigInt using Maurer's algorithm.
97// bigInt  randProbPrime(k)       //return a new, random, k-bit, probable prime bigInt (probability it's composite less than 2^-80).
98// bigInt  str2bigInt(s,b,n,m)    //return a bigInt for number represented in string s in base b with at least n bits and m array elements
99// bigInt  sub(x,y)               //return (x-y) for bigInts x and y.  Negative answers will be 2s complement
100// bigInt  trim(x,k)              //return a copy of x with exactly k leading zero elements
101//
102//
103// The following functions each have a non-underscored version, which most users should call instead.
104// These functions each write to a single parameter, and the caller is responsible for ensuring the array
105// passed in is large enough to hold the result.
106//
107// void    addInt_(x,n)          //do x=x+n where x is a bigInt and n is an integer
108// void    add_(x,y)             //do x=x+y for bigInts x and y
109// void    copy_(x,y)            //do x=y on bigInts x and y
110// void    copyInt_(x,n)         //do x=n on bigInt x and integer n
111// void    GCD_(x,y)             //set x to the greatest common divisor of bigInts x and y, (y is destroyed).  (This never overflows its array).
112// boolean inverseMod_(x,n)      //do x=x**(-1) mod n, for bigInts x and n. Returns 1 (0) if inverse does (doesn't) exist
113// void    mod_(x,n)             //do x=x mod n for bigInts x and n. (This never overflows its array).
114// void    mult_(x,y)            //do x=x*y for bigInts x and y.
115// void    multMod_(x,y,n)       //do x=x*y  mod n for bigInts x,y,n.
116// void    powMod_(x,y,n)        //do x=x**y mod n, where x,y,n are bigInts (n is odd) and ** is exponentiation.  0**0=1.
117// void    randBigInt_(b,n,s)    //do b = an n-bit random BigInt. if s=1, then nth bit (most significant bit) is set to 1. n>=1.
118// void    randTruePrime_(ans,k) //do ans = a random k-bit true random prime (not just probable prime) with 1 in the msb.
119// void    sub_(x,y)             //do x=x-y for bigInts x and y. Negative answers will be 2s complement.
120//
121// The following functions do NOT have a non-underscored version.
122// They each write a bigInt result to one or more parameters.  The caller is responsible for
123// ensuring the arrays passed in are large enough to hold the results.
124//
125// void addShift_(x,y,ys)       //do x=x+(y<<(ys*bpe))
126// void carry_(x)               //do carries and borrows so each element of the bigInt x fits in bpe bits.
127// void divide_(x,y,q,r)        //divide x by y giving quotient q and remainder r
128// int  divInt_(x,n)            //do x=floor(x/n) for bigInt x and integer n, and return the remainder. (This never overflows its array).
129// int  eGCD_(x,y,d,a,b)        //sets a,b,d to positive bigInts such that d = GCD_(x,y) = a*x-b*y
130// void halve_(x)               //do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement.  (This never overflows its array).
131// void leftShift_(x,n)         //left shift bigInt x by n bits.  n<bpe.
132// void linComb_(x,y,a,b)       //do x=a*x+b*y for bigInts x and y and integers a and b
133// void linCombShift_(x,y,b,ys) //do x=x+b*(y<<(ys*bpe)) for bigInts x and y, and integers b and ys
134// void mont_(x,y,n,np)         //Montgomery multiplication (see comments where the function is defined)
135// void multInt_(x,n)           //do x=x*n where x is a bigInt and n is an integer.
136// void rightShift_(x,n)        //right shift bigInt x by n bits.  0 <= n < bpe. (This never overflows its array).
137// void squareMod_(x,n)         //do x=x*x  mod n for bigInts x,n
138// void subShift_(x,y,ys)       //do x=x-(y<<(ys*bpe)). Negative answers will be 2s complement.
139//
140// The following functions are based on algorithms from the _Handbook of Applied Cryptography_
141//    powMod_()           = algorithm 14.94, Montgomery exponentiation
142//    eGCD_,inverseMod_() = algorithm 14.61, Binary extended GCD_
143//    GCD_()              = algorothm 14.57, Lehmer's algorithm
144//    mont_()             = algorithm 14.36, Montgomery multiplication
145//    divide_()           = algorithm 14.20  Multiple-precision division
146//    squareMod_()        = algorithm 14.16  Multiple-precision squaring
147//    randTruePrime_()    = algorithm  4.62, Maurer's algorithm
148//    millerRabin()       = algorithm  4.24, Miller-Rabin algorithm
149//
150// Profiling shows:
151//     randTruePrime_() spends:
152//         10% of its time in calls to powMod_()
153//         85% of its time in calls to millerRabin()
154//     millerRabin() spends:
155//         99% of its time in calls to powMod_()   (always with a base of 2)
156//     powMod_() spends:
157//         94% of its time in calls to mont_()  (almost always with x==y)
158//
159// This suggests there are several ways to speed up this library slightly:
160//     - convert powMod_ to use a Montgomery form of k-ary window (or maybe a Montgomery form of sliding window)
161//         -- this should especially focus on being fast when raising 2 to a power mod n
162//     - convert randTruePrime_() to use a minimum r of 1/3 instead of 1/2 with the appropriate change to the test
163//     - tune the parameters in randTruePrime_(), including c, m, and recLimit
164//     - speed up the single loop in mont_() that takes 95% of the runtime, perhaps by reducing checking
165//       within the loop when all the parameters are the same length.
166//
167// There are several ideas that look like they wouldn't help much at all:
168//     - replacing trial division in randTruePrime_() with a sieve (that speeds up something taking almost no time anyway)
169//     - increase bpe from 15 to 30 (that would help if we had a 32*32->64 multiplier, but not with JavaScript's 32*32->32)
170//     - speeding up mont_(x,y,n,np) when x==y by doing a non-modular, non-Montgomery square
171//       followed by a Montgomery reduction.  The intermediate answer will be twice as long as x, so that
172//       method would be slower.  This is unfortunate because the code currently spends almost all of its time
173//       doing mont_(x,x,...), both for randTruePrime_() and powMod_().  A faster method for Montgomery squaring
174//       would have a large impact on the speed of randTruePrime_() and powMod_().  HAC has a couple of poorly-worded
175//       sentences that seem to imply it's faster to do a non-modular square followed by a single
176//       Montgomery reduction, but that's obviously wrong.
177////////////////////////////////////////////////////////////////////////////////////////
178
179//globals
180bpe=0;         //bits stored per array element
181mask=0;        //AND this with an array element to chop it down to bpe bits
182radix=mask+1;  //equals 2^bpe.  A single 1 bit to the left of the last bit of mask.
183
184//the digits for converting to different bases
185digitsStr='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_=!@#$%^&*()[]{}|;:,.<>/?`~ \\\'\"+-';
186
187//initialize the global variables
188for (bpe=0; (1<<(bpe+1)) > (1<<bpe); bpe++);  //bpe=number of bits in the mantissa on this platform
189bpe>>=1;                   //bpe=number of bits in one element of the array representing the bigInt
190mask=(1<<bpe)-1;           //AND the mask with an integer to get its bpe least significant bits
191radix=mask+1;              //2^bpe.  a single 1 bit to the left of the first bit of mask
192one=int2bigInt(1,1,1);     //constant used in powMod_()
193
194//the following global variables are scratchpad memory to
195//reduce dynamic memory allocation in the inner loop
196t=new Array(0);
197ss=t;       //used in mult_()
198s0=t;       //used in multMod_(), squareMod_()
199s1=t;       //used in powMod_(), multMod_(), squareMod_()
200s2=t;       //used in powMod_(), multMod_()
201s3=t;       //used in powMod_()
202s4=t; s5=t; //used in mod_()
203s6=t;       //used in bigInt2str()
204s7=t;       //used in powMod_()
205T=t;        //used in GCD_()
206sa=t;       //used in mont_()
207mr_x1=t; mr_r=t; mr_a=t;                                      //used in millerRabin()
208eg_v=t; eg_u=t; eg_A=t; eg_B=t; eg_C=t; eg_D=t;               //used in eGCD_(), inverseMod_()
209md_q1=t; md_q2=t; md_q3=t; md_r=t; md_r1=t; md_r2=t; md_tt=t; //used in mod_()
210
211primes=t; pows=t; s_i=t; s_i2=t; s_R=t; s_rm=t; s_q=t; s_n1=t;
212  s_a=t; s_r2=t; s_n=t; s_b=t; s_d=t; s_x1=t; s_x2=t, s_aa=t; //used in randTruePrime_()
213 
214rpprb=t; //used in randProbPrimeRounds() (which also uses "primes")
215
216////////////////////////////////////////////////////////////////////////////////////////
217
218
219//return array of all primes less than integer n
220function findPrimes(n) {
221  var i,s,p,ans;
222  s=new Array(n);
223  for (i=0;i<n;i++)
224    s[i]=0;
225  s[0]=2;
226  p=0;    //first p elements of s are primes, the rest are a sieve
227  for(;s[p]<n;) {                  //s[p] is the pth prime
228    for(i=s[p]*s[p]; i<n; i+=s[p]) //mark multiples of s[p]
229      s[i]=1;
230    p++;
231    s[p]=s[p-1]+1;
232    for(; s[p]<n && s[s[p]]; s[p]++); //find next prime (where s[p]==0)
233  }
234  ans=new Array(p);
235  for(i=0;i<p;i++)
236    ans[i]=s[i];
237  return ans;
238}
239
240
241//does a single round of Miller-Rabin base b consider x to be a possible prime?
242//x is a bigInt, and b is an integer, with b<x
243function millerRabinInt(x,b) {
244  if (mr_x1.length!=x.length) {
245    mr_x1=dup(x);
246    mr_r=dup(x);
247    mr_a=dup(x);
248  }
249
250  copyInt_(mr_a,b);
251  return millerRabin(x,mr_a);
252}
253
254//does a single round of Miller-Rabin base b consider x to be a possible prime?
255//x and b are bigInts with b<x
256function millerRabin(x,b) {
257  var i,j,k,s;
258
259  if (mr_x1.length!=x.length) {
260    mr_x1=dup(x);
261    mr_r=dup(x);
262    mr_a=dup(x);
263  }
264
265  copy_(mr_a,b);
266  copy_(mr_r,x);
267  copy_(mr_x1,x);
268
269  addInt_(mr_r,-1);
270  addInt_(mr_x1,-1);
271
272  //s=the highest power of two that divides mr_r
273  k=0;
274  for (i=0;i<mr_r.length;i++)
275    for (j=1;j<mask;j<<=1)
276      if (x[i] & j) {
277        s=(k<mr_r.length+bpe ? k : 0);
278         i=mr_r.length;
279         j=mask;
280      } else
281        k++;
282
283  if (s)               
284    rightShift_(mr_r,s);
285
286  powMod_(mr_a,mr_r,x);
287
288  if (!equalsInt(mr_a,1) && !equals(mr_a,mr_x1)) {
289    j=1;
290    while (j<=s-1 && !equals(mr_a,mr_x1)) {
291      squareMod_(mr_a,x);
292      if (equalsInt(mr_a,1)) {
293        return 0;
294      }
295      j++;
296    }
297    if (!equals(mr_a,mr_x1)) {
298      return 0;
299    }
300  }
301  return 1; 
302}
303
304//returns how many bits long the bigInt is, not counting leading zeros.
305function bitSize(x) {
306  var j,z,w;
307  for (j=x.length-1; (x[j]==0) && (j>0); j--);
308  for (z=0,w=x[j]; w; (w>>=1),z++);
309  z+=bpe*j;
310  return z;
311}
312
313//return a copy of x with at least n elements, adding leading zeros if needed
314function expand(x,n) {
315  var ans=int2bigInt(0,(x.length>n ? x.length : n)*bpe,0);
316  copy_(ans,x);
317  return ans;
318}
319
320//return a k-bit true random prime using Maurer's algorithm.
321function randTruePrime(k) {
322  var ans=int2bigInt(0,k,0);
323  randTruePrime_(ans,k);
324  return trim(ans,1);
325}
326
327//return a k-bit random probable prime with probability of error < 2^-80
328function randProbPrime(k) {
329  if (k>=600) return randProbPrimeRounds(k,2); //numbers from HAC table 4.3
330  if (k>=550) return randProbPrimeRounds(k,4);
331  if (k>=500) return randProbPrimeRounds(k,5);
332  if (k>=400) return randProbPrimeRounds(k,6);
333  if (k>=350) return randProbPrimeRounds(k,7);
334  if (k>=300) return randProbPrimeRounds(k,9);
335  if (k>=250) return randProbPrimeRounds(k,12); //numbers from HAC table 4.4
336  if (k>=200) return randProbPrimeRounds(k,15);
337  if (k>=150) return randProbPrimeRounds(k,18);
338  if (k>=100) return randProbPrimeRounds(k,27);
339              return randProbPrimeRounds(k,40); //number from HAC remark 4.26 (only an estimate)
340}
341
342//return a k-bit probable random prime using n rounds of Miller Rabin (after trial division with small primes) 
343function randProbPrimeRounds(k,n) {
344  var ans, i, divisible, B;
345  B=30000;  //B is largest prime to use in trial division
346  ans=int2bigInt(0,k,0);
347 
348  //optimization: try larger and smaller B to find the best limit.
349 
350  if (primes.length==0)
351    primes=findPrimes(30000);  //check for divisibility by primes <=30000
352
353  if (rpprb.length!=ans.length)
354    rpprb=dup(ans);
355
356  for (;;) { //keep trying random values for ans until one appears to be prime
357    //optimization: pick a random number times L=2*3*5*...*p, plus a
358    //   random element of the list of all numbers in [0,L) not divisible by any prime up to p.
359    //   This can reduce the amount of random number generation.
360   
361    randBigInt_(ans,k,0); //ans = a random odd number to check
362    ans[0] |= 1;
363    divisible=0;
364 
365    //check ans for divisibility by small primes up to B
366    for (i=0; (i<primes.length) && (primes[i]<=B); i++)
367      if (modInt(ans,primes[i])==0 && !equalsInt(ans,primes[i])) {
368        divisible=1;
369        break;
370      }     
371   
372    //optimization: change millerRabin so the base can be bigger than the number being checked, then eliminate the while here.
373   
374    //do n rounds of Miller Rabin, with random bases less than ans
375    for (i=0; i<n && !divisible; i++) {
376      randBigInt_(rpprb,k,0);
377      while(!greater(ans,rpprb)) //pick a random rpprb that's < ans
378        randBigInt_(rpprb,k,0);
379      if (!millerRabin(ans,rpprb))
380        divisible=1;
381    }
382   
383    if(!divisible)
384      return ans;
385  } 
386}
387
388//return a new bigInt equal to (x mod n) for bigInts x and n.
389function mod(x,n) {
390  var ans=dup(x);
391  mod_(ans,n);
392  return trim(ans,1);
393}
394
395//return (x+n) where x is a bigInt and n is an integer.
396function addInt(x,n) {
397  var ans=expand(x,x.length+1);
398  addInt_(ans,n);
399  return trim(ans,1);
400}
401
402//return x*y for bigInts x and y. This is faster when y<x.
403function mult(x,y) {
404  var ans=expand(x,x.length+y.length);
405  mult_(ans,y);
406  return trim(ans,1);
407}
408
409//return (x**y mod n) where x,y,n are bigInts and ** is exponentiation.  0**0=1. Faster for odd n.
410function powMod(x,y,n) {
411  var ans=expand(x,n.length); 
412  powMod_(ans,trim(y,2),trim(n,2),0);  //this should work without the trim, but doesn't
413  return trim(ans,1);
414}
415
416//return (x-y) for bigInts x and y.  Negative answers will be 2s complement
417function sub(x,y) {
418  var ans=expand(x,(x.length>y.length ? x.length+1 : y.length+1));
419  sub_(ans,y);
420  return trim(ans,1);
421}
422
423//return (x+y) for bigInts x and y. 
424function add(x,y) {
425  var ans=expand(x,(x.length>y.length ? x.length+1 : y.length+1));
426  add_(ans,y);
427  return trim(ans,1);
428}
429
430//return (x**(-1) mod n) for bigInts x and n.  If no inverse exists, it returns null
431function inverseMod(x,n) {
432  var ans=expand(x,n.length);
433  var s;
434  s=inverseMod_(ans,n);
435  return s ? trim(ans,1) : null;
436}
437
438//return (x*y mod n) for bigInts x,y,n.  For greater speed, let y<x.
439function multMod(x,y,n) {
440  var ans=expand(x,n.length);
441  multMod_(ans,y,n);
442  return trim(ans,1);
443}
444
445//generate a k-bit true random prime using Maurer's algorithm,
446//and put it into ans.  The bigInt ans must be large enough to hold it.
447function randTruePrime_(ans,k) {
448  var c,m,pm,dd,j,r,B,divisible,z,zz,recSize;
449
450  if (primes.length==0)
451    primes=findPrimes(30000);  //check for divisibility by primes <=30000
452
453  if (pows.length==0) {
454    pows=new Array(512);
455    for (j=0;j<512;j++) {
456      pows[j]=Math.pow(2,j/511.-1.);
457    }
458  }
459
460  //c and m should be tuned for a particular machine and value of k, to maximize speed
461  c=0.1;  //c=0.1 in HAC
462  m=20;   //generate this k-bit number by first recursively generating a number that has between k/2 and k-m bits
463  recLimit=20; //stop recursion when k <=recLimit.  Must have recLimit >= 2
464
465  if (s_i2.length!=ans.length) {
466    s_i2=dup(ans);
467    s_R =dup(ans);
468    s_n1=dup(ans);
469    s_r2=dup(ans);
470    s_d =dup(ans);
471    s_x1=dup(ans);
472    s_x2=dup(ans);
473    s_b =dup(ans);
474    s_n =dup(ans);
475    s_i =dup(ans);
476    s_rm=dup(ans);
477    s_q =dup(ans);
478    s_a =dup(ans);
479    s_aa=dup(ans);
480  }
481
482  if (k <= recLimit) {  //generate small random primes by trial division up to its square root
483    pm=(1<<((k+2)>>1))-1; //pm is binary number with all ones, just over sqrt(2^k)
484    copyInt_(ans,0);
485    for (dd=1;dd;) {
486      dd=0;
487      ans[0]= 1 | (1<<(k-1)) | Math.floor(Math.random()*(1<<k));  //random, k-bit, odd integer, with msb 1
488      for (j=1;(j<primes.length) && ((primes[j]&pm)==primes[j]);j++) { //trial division by all primes 3...sqrt(2^k)
489        if (0==(ans[0]%primes[j])) {
490          dd=1;
491          break;
492        }
493      }
494    }
495    carry_(ans);
496    return;
497  }
498
499  B=c*k*k;    //try small primes up to B (or all the primes[] array if the largest is less than B).
500  if (k>2*m)  //generate this k-bit number by first recursively generating a number that has between k/2 and k-m bits
501    for (r=1; k-k*r<=m; )
502      r=pows[Math.floor(Math.random()*512)];   //r=Math.pow(2,Math.random()-1);
503  else
504    r=.5;
505
506  //simulation suggests the more complex algorithm using r=.333 is only slightly faster.
507
508  recSize=Math.floor(r*k)+1;
509
510  randTruePrime_(s_q,recSize);
511  copyInt_(s_i2,0);
512  s_i2[Math.floor((k-2)/bpe)] |= (1<<((k-2)%bpe));   //s_i2=2^(k-2)
513  divide_(s_i2,s_q,s_i,s_rm);                        //s_i=floor((2^(k-1))/(2q))
514
515  z=bitSize(s_i);
516
517  for (;;) {
518    for (;;) {  //generate z-bit numbers until one falls in the range [0,s_i-1]
519      randBigInt_(s_R,z,0);
520      if (greater(s_i,s_R))
521        break;
522    }                //now s_R is in the range [0,s_i-1]
523    addInt_(s_R,1);  //now s_R is in the range [1,s_i]
524    add_(s_R,s_i);   //now s_R is in the range [s_i+1,2*s_i]
525
526    copy_(s_n,s_q);
527    mult_(s_n,s_R);
528    multInt_(s_n,2);
529    addInt_(s_n,1);    //s_n=2*s_R*s_q+1
530   
531    copy_(s_r2,s_R);
532    multInt_(s_r2,2);  //s_r2=2*s_R
533
534    //check s_n for divisibility by small primes up to B
535    for (divisible=0,j=0; (j<primes.length) && (primes[j]<B); j++)
536      if (modInt(s_n,primes[j])==0 && !equalsInt(s_n,primes[j])) {
537        divisible=1;
538        break;
539      }     
540
541    if (!divisible)    //if it passes small primes check, then try a single Miller-Rabin base 2
542      if (!millerRabinInt(s_n,2)) //this line represents 75% of the total runtime for randTruePrime_
543        divisible=1;
544
545    if (!divisible) {  //if it passes that test, continue checking s_n
546      addInt_(s_n,-3);
547      for (j=s_n.length-1;(s_n[j]==0) && (j>0); j--);  //strip leading zeros
548      for (zz=0,w=s_n[j]; w; (w>>=1),zz++);
549      zz+=bpe*j;                             //zz=number of bits in s_n, ignoring leading zeros
550      for (;;) {  //generate z-bit numbers until one falls in the range [0,s_n-1]
551        randBigInt_(s_a,zz,0);
552        if (greater(s_n,s_a))
553          break;
554      }                //now s_a is in the range [0,s_n-1]
555      addInt_(s_n,3);  //now s_a is in the range [0,s_n-4]
556      addInt_(s_a,2);  //now s_a is in the range [2,s_n-2]
557      copy_(s_b,s_a);
558      copy_(s_n1,s_n);
559      addInt_(s_n1,-1);
560      powMod_(s_b,s_n1,s_n);   //s_b=s_a^(s_n-1) modulo s_n
561      addInt_(s_b,-1);
562      if (isZero(s_b)) {
563        copy_(s_b,s_a);
564        powMod_(s_b,s_r2,s_n);
565        addInt_(s_b,-1);
566        copy_(s_aa,s_n);
567        copy_(s_d,s_b);
568        GCD_(s_d,s_n);  //if s_b and s_n are relatively prime, then s_n is a prime
569        if (equalsInt(s_d,1)) {
570          copy_(ans,s_aa);
571          return;     //if we've made it this far, then s_n is absolutely guaranteed to be prime
572        }
573      }
574    }
575  }
576}
577
578//Return an n-bit random BigInt (n>=1).  If s=1, then the most significant of those n bits is set to 1.
579function randBigInt(n,s) {
580  var a,b;
581  a=Math.floor((n-1)/bpe)+2; //# array elements to hold the BigInt with a leading 0 element
582  b=int2bigInt(0,0,a);
583  randBigInt_(b,n,s);
584  return b;
585}
586
587//Set b to an n-bit random BigInt.  If s=1, then the most significant of those n bits is set to 1.
588//Array b must be big enough to hold the result. Must have n>=1
589function randBigInt_(b,n,s) {
590  var i,a;
591  for (i=0;i<b.length;i++)
592    b[i]=0;
593  a=Math.floor((n-1)/bpe)+1; //# array elements to hold the BigInt
594  for (i=0;i<a;i++) {
595    b[i]=Math.floor(Math.random()*(1<<(bpe-1)));
596  }
597  b[a-1] &= (2<<((n-1)%bpe))-1;
598  if (s==1)
599    b[a-1] |= (1<<((n-1)%bpe));
600}
601
602//Return the greatest common divisor of bigInts x and y (each with same number of elements).
603function GCD(x,y) {
604  var xc,yc;
605  xc=dup(x);
606  yc=dup(y);
607  GCD_(xc,yc);
608  return xc;
609}
610
611//set x to the greatest common divisor of bigInts x and y (each with same number of elements).
612//y is destroyed.
613function GCD_(x,y) {
614  var i,xp,yp,A,B,C,D,q,sing;
615  if (T.length!=x.length)
616    T=dup(x);
617
618  sing=1;
619  while (sing) { //while y has nonzero elements other than y[0]
620    sing=0;
621    for (i=1;i<y.length;i++) //check if y has nonzero elements other than 0
622      if (y[i]) {
623        sing=1;
624        break;
625      }
626    if (!sing) break; //quit when y all zero elements except possibly y[0]
627
628    for (i=x.length;!x[i] && i>=0;i--);  //find most significant element of x
629    xp=x[i];
630    yp=y[i];
631    A=1; B=0; C=0; D=1;
632    while ((yp+C) && (yp+D)) {
633      q =Math.floor((xp+A)/(yp+C));
634      qp=Math.floor((xp+B)/(yp+D));
635      if (q!=qp)
636        break;
637      t= A-q*C;   A=C;   C=t;    //  do (A,B,xp, C,D,yp) = (C,D,yp, A,B,xp) - q*(0,0,0, C,D,yp)     
638      t= B-q*D;   B=D;   D=t;
639      t=xp-q*yp; xp=yp; yp=t;
640    }
641    if (B) {
642      copy_(T,x);
643      linComb_(x,y,A,B); //x=A*x+B*y
644      linComb_(y,T,D,C); //y=D*y+C*T
645    } else {
646      mod_(x,y);
647      copy_(T,x);
648      copy_(x,y);
649      copy_(y,T);
650    }
651  }
652  if (y[0]==0)
653    return;
654  t=modInt(x,y[0]);
655  copyInt_(x,y[0]);
656  y[0]=t;
657  while (y[0]) {
658    x[0]%=y[0];
659    t=x[0]; x[0]=y[0]; y[0]=t;
660  }
661}
662
663//do x=x**(-1) mod n, for bigInts x and n.
664//If no inverse exists, it sets x to zero and returns 0, else it returns 1.
665//The x array must be at least as large as the n array.
666function inverseMod_(x,n) {
667  var k=1+2*Math.max(x.length,n.length);
668
669  if(!(x[0]&1)  && !(n[0]&1)) {  //if both inputs are even, then inverse doesn't exist
670    copyInt_(x,0);
671    return 0;
672  }
673
674  if (eg_u.length!=k) {
675    eg_u=new Array(k);
676    eg_v=new Array(k);
677    eg_A=new Array(k);
678    eg_B=new Array(k);
679    eg_C=new Array(k);
680    eg_D=new Array(k);
681  }
682
683  copy_(eg_u,x);
684  copy_(eg_v,n);
685  copyInt_(eg_A,1);
686  copyInt_(eg_B,0);
687  copyInt_(eg_C,0);
688  copyInt_(eg_D,1);
689  for (;;) {
690    while(!(eg_u[0]&1)) {  //while eg_u is even
691      halve_(eg_u);
692      if (!(eg_A[0]&1) && !(eg_B[0]&1)) { //if eg_A==eg_B==0 mod 2
693        halve_(eg_A);
694        halve_(eg_B);     
695      } else {
696        add_(eg_A,n);  halve_(eg_A);
697        sub_(eg_B,x);  halve_(eg_B);
698      }
699    }
700
701    while (!(eg_v[0]&1)) {  //while eg_v is even
702      halve_(eg_v);
703      if (!(eg_C[0]&1) && !(eg_D[0]&1)) { //if eg_C==eg_D==0 mod 2
704        halve_(eg_C);
705        halve_(eg_D);     
706      } else {
707        add_(eg_C,n);  halve_(eg_C);
708        sub_(eg_D,x);  halve_(eg_D);
709      }
710    }
711
712    if (!greater(eg_v,eg_u)) { //eg_v <= eg_u
713      sub_(eg_u,eg_v);
714      sub_(eg_A,eg_C);
715      sub_(eg_B,eg_D);
716    } else {                   //eg_v > eg_u
717      sub_(eg_v,eg_u);
718      sub_(eg_C,eg_A);
719      sub_(eg_D,eg_B);
720    }
721 
722    if (equalsInt(eg_u,0)) {
723      if (negative(eg_C)) //make sure answer is nonnegative
724        add_(eg_C,n);
725      copy_(x,eg_C);
726
727      if (!equalsInt(eg_v,1)) { //if GCD_(x,n)!=1, then there is no inverse
728        copyInt_(x,0);
729        return 0;
730      }
731      return 1;
732    }
733  }
734}
735
736//return x**(-1) mod n, for integers x and n.  Return 0 if there is no inverse
737function inverseModInt(x,n) {
738  var a=1,b=0,t;
739  for (;;) {
740    if (x==1) return a;
741    if (x==0) return 0;
742    b-=a*Math.floor(n/x);
743    n%=x;
744
745    if (n==1) return b; //to avoid negatives, change this b to n-b, and each -= to +=
746    if (n==0) return 0;
747    a-=b*Math.floor(x/n);
748    x%=n;
749  }
750}
751
752//this deprecated function is for backward compatibility only.
753function inverseModInt_(x,n) {
754   return inverseModInt(x,n);
755}
756
757
758//Given positive bigInts x and y, change the bigints v, a, and b to positive bigInts such that:
759//     v = GCD_(x,y) = a*x-b*y
760//The bigInts v, a, b, must have exactly as many elements as the larger of x and y.
761function eGCD_(x,y,v,a,b) {
762  var g=0;
763  var k=Math.max(x.length,y.length);
764  if (eg_u.length!=k) {
765    eg_u=new Array(k);
766    eg_A=new Array(k);
767    eg_B=new Array(k);
768    eg_C=new Array(k);
769    eg_D=new Array(k);
770  }
771  while(!(x[0]&1)  && !(y[0]&1)) {  //while x and y both even
772    halve_(x);
773    halve_(y);
774    g++;
775  }
776  copy_(eg_u,x);
777  copy_(v,y);
778  copyInt_(eg_A,1);
779  copyInt_(eg_B,0);
780  copyInt_(eg_C,0);
781  copyInt_(eg_D,1);
782  for (;;) {
783    while(!(eg_u[0]&1)) {  //while u is even
784      halve_(eg_u);
785      if (!(eg_A[0]&1) && !(eg_B[0]&1)) { //if A==B==0 mod 2
786        halve_(eg_A);
787        halve_(eg_B);     
788      } else {
789        add_(eg_A,y);  halve_(eg_A);
790        sub_(eg_B,x);  halve_(eg_B);
791      }
792    }
793
794    while (!(v[0]&1)) {  //while v is even
795      halve_(v);
796      if (!(eg_C[0]&1) && !(eg_D[0]&1)) { //if C==D==0 mod 2
797        halve_(eg_C);
798        halve_(eg_D);     
799      } else {
800        add_(eg_C,y);  halve_(eg_C);
801        sub_(eg_D,x);  halve_(eg_D);
802      }
803    }
804
805    if (!greater(v,eg_u)) { //v<=u
806      sub_(eg_u,v);
807      sub_(eg_A,eg_C);
808      sub_(eg_B,eg_D);
809    } else {                //v>u
810      sub_(v,eg_u);
811      sub_(eg_C,eg_A);
812      sub_(eg_D,eg_B);
813    }
814    if (equalsInt(eg_u,0)) {
815      if (negative(eg_C)) {   //make sure a (C)is nonnegative
816        add_(eg_C,y);
817        sub_(eg_D,x);
818      }
819      multInt_(eg_D,-1);  ///make sure b (D) is nonnegative
820      copy_(a,eg_C);
821      copy_(b,eg_D);
822      leftShift_(v,g);
823      return;
824    }
825  }
826}
827
828
829//is bigInt x negative?
830function negative(x) {
831  return ((x[x.length-1]>>(bpe-1))&1);
832}
833
834
835//is (x << (shift*bpe)) > y?
836//x and y are nonnegative bigInts
837//shift is a nonnegative integer
838function greaterShift(x,y,shift) {
839  var i, kx=x.length, ky=y.length;
840  k=((kx+shift)<ky) ? (kx+shift) : ky;
841  for (i=ky-1-shift; i<kx && i>=0; i++)
842    if (x[i]>0)
843      return 1; //if there are nonzeros in x to the left of the first column of y, then x is bigger
844  for (i=kx-1+shift; i<ky; i++)
845    if (y[i]>0)
846      return 0; //if there are nonzeros in y to the left of the first column of x, then x is not bigger
847  for (i=k-1; i>=shift; i--)
848    if      (x[i-shift]>y[i]) return 1;
849    else if (x[i-shift]<y[i]) return 0;
850  return 0;
851}
852
853//is x > y? (x and y both nonnegative)
854function greater(x,y) {
855  var i;
856  var k=(x.length<y.length) ? x.length : y.length;
857
858  for (i=x.length;i<y.length;i++)
859    if (y[i])
860      return 0;  //y has more digits
861
862  for (i=y.length;i<x.length;i++)
863    if (x[i])
864      return 1;  //x has more digits
865
866  for (i=k-1;i>=0;i--)
867    if (x[i]>y[i])
868      return 1;
869    else if (x[i]<y[i])
870      return 0;
871  return 0;
872}
873
874//divide x by y giving quotient q and remainder r.  (q=floor(x/y),  r=x mod y).  All 4 are bigints.
875//x must have at least one leading zero element.
876//y must be nonzero.
877//q and r must be arrays that are exactly the same length as x. (Or q can have more).
878//Must have x.length >= y.length >= 2.
879function divide_(x,y,q,r) {
880  var kx, ky;
881  var i,j,y1,y2,c,a,b;
882  copy_(r,x);
883  for (ky=y.length;y[ky-1]==0;ky--); //ky is number of elements in y, not including leading zeros
884
885  //normalize: ensure the most significant element of y has its highest bit set 
886  b=y[ky-1];
887  for (a=0; b; a++)
888    b>>=1; 
889  a=bpe-a;  //a is how many bits to shift so that the high order bit of y is leftmost in its array element
890  leftShift_(y,a);  //multiply both by 1<<a now, then divide both by that at the end
891  leftShift_(r,a);
892
893  //Rob Visser discovered a bug: the following line was originally just before the normalization.
894  for (kx=r.length;r[kx-1]==0 && kx>ky;kx--); //kx is number of elements in normalized x, not including leading zeros
895
896  copyInt_(q,0);                      // q=0
897  while (!greaterShift(y,r,kx-ky)) {  // while (leftShift_(y,kx-ky) <= r) {
898    subShift_(r,y,kx-ky);             //   r=r-leftShift_(y,kx-ky)
899    q[kx-ky]++;                       //   q[kx-ky]++;
900  }                                   // }
901
902  for (i=kx-1; i>=ky; i--) {
903    if (r[i]==y[ky-1])
904      q[i-ky]=mask;
905    else
906      q[i-ky]=Math.floor((r[i]*radix+r[i-1])/y[ky-1]); 
907
908    //The following for(;;) loop is equivalent to the commented while loop,
909    //except that the uncommented version avoids overflow.
910    //The commented loop comes from HAC, which assumes r[-1]==y[-1]==0
911    //  while (q[i-ky]*(y[ky-1]*radix+y[ky-2]) > r[i]*radix*radix+r[i-1]*radix+r[i-2])
912    //    q[i-ky]--;   
913    for (;;) {
914      y2=(ky>1 ? y[ky-2] : 0)*q[i-ky];
915      c=y2>>bpe;
916      y2=y2 & mask;
917      y1=c+q[i-ky]*y[ky-1];
918      c=y1>>bpe;
919      y1=y1 & mask;
920
921      if (c==r[i] ? y1==r[i-1] ? y2>(i>1 ? r[i-2] : 0) : y1>r[i-1] : c>r[i])
922        q[i-ky]--;
923      else
924        break;
925    }
926
927    linCombShift_(r,y,-q[i-ky],i-ky);    //r=r-q[i-ky]*leftShift_(y,i-ky)
928    if (negative(r)) {
929      addShift_(r,y,i-ky);         //r=r+leftShift_(y,i-ky)
930      q[i-ky]--;
931    }
932  }
933
934  rightShift_(y,a);  //undo the normalization step
935  rightShift_(r,a);  //undo the normalization step
936}
937
938//do carries and borrows so each element of the bigInt x fits in bpe bits.
939function carry_(x) {
940  var i,k,c,b;
941  k=x.length;
942  c=0;
943  for (i=0;i<k;i++) {
944    c+=x[i];
945    b=0;
946    if (c<0) {
947      b=-(c>>bpe);
948      c+=b*radix;
949    }
950    x[i]=c & mask;
951    c=(c>>bpe)-b;
952  }
953}
954
955//return x mod n for bigInt x and integer n.
956function modInt(x,n) {
957  var i,c=0;
958  for (i=x.length-1; i>=0; i--)
959    c=(c*radix+x[i])%n;
960  return c;
961}
962
963//convert the integer t into a bigInt with at least the given number of bits.
964//the returned array stores the bigInt in bpe-bit chunks, little endian (buff[0] is least significant word)
965//Pad the array with leading zeros so that it has at least minSize elements.
966//There will always be at least one leading 0 element.
967function int2bigInt(t,bits,minSize) {   
968  var i,k;
969  k=Math.ceil(bits/bpe)+1;
970  k=minSize>k ? minSize : k;
971  buff=new Array(k);
972  copyInt_(buff,t);
973  return buff;
974}
975
976//return the bigInt given a string representation in a given base. 
977//Pad the array with leading zeros so that it has at least minSize elements.
978//If base=-1, then it reads in a space-separated list of array elements in decimal.
979//The array will always have at least one leading zero, unless base=-1.
980function str2bigInt(s,base,minSize) {
981  var d, i, j, x, y, kk;
982  var k=s.length;
983  if (base==-1) { //comma-separated list of array elements in decimal
984    x=new Array(0);
985    for (;;) {
986      y=new Array(x.length+1);
987      for (i=0;i<x.length;i++)
988        y[i+1]=x[i];
989      y[0]=parseInt(s,10);
990      x=y;
991      d=s.indexOf(',',0);
992      if (d<1)
993        break;
994      s=s.substring(d+1);
995      if (s.length==0)
996        break;
997    }
998    if (x.length<minSize) {
999      y=new Array(minSize);
1000      copy_(y,x);
1001      return y;
1002    }
1003    return x;
1004  }
1005
1006  x=int2bigInt(0,base*k,0);
1007  for (i=0;i<k;i++) {
1008    d=digitsStr.indexOf(s.substring(i,i+1),0);
1009    if (base<=36 && d>=36)  //convert lowercase to uppercase if base<=36
1010      d-=26;
1011    if (d>=base || d<0) {   //stop at first illegal character
1012      break;
1013    }
1014    multInt_(x,base);
1015    addInt_(x,d);
1016  }
1017
1018  for (k=x.length;k>0 && !x[k-1];k--); //strip off leading zeros
1019  k=minSize>k+1 ? minSize : k+1;
1020  y=new Array(k);
1021  kk=k<x.length ? k : x.length;
1022  for (i=0;i<kk;i++)
1023    y[i]=x[i];
1024  for (;i<k;i++)
1025    y[i]=0;
1026  return y;
1027}
1028
1029//is bigint x equal to integer y?
1030//y must have less than bpe bits
1031function equalsInt(x,y) {
1032  var i;
1033  if (x[0]!=y)
1034    return 0;
1035  for (i=1;i<x.length;i++)
1036    if (x[i])
1037      return 0;
1038  return 1;
1039}
1040
1041//are bigints x and y equal?
1042//this works even if x and y are different lengths and have arbitrarily many leading zeros
1043function equals(x,y) {
1044  var i;
1045  var k=x.length<y.length ? x.length : y.length;
1046  for (i=0;i<k;i++)
1047    if (x[i]!=y[i])
1048      return 0;
1049  if (x.length>y.length) {
1050    for (;i<x.length;i++)
1051      if (x[i])
1052        return 0;
1053  } else {
1054    for (;i<y.length;i++)
1055      if (y[i])
1056        return 0;
1057  }
1058  return 1;
1059}
1060
1061//is the bigInt x equal to zero?
1062function isZero(x) {
1063  var i;
1064  for (i=0;i<x.length;i++)
1065    if (x[i])
1066      return 0;
1067  return 1;
1068}
1069
1070//convert a bigInt into a string in a given base, from base 2 up to base 95.
1071//Base -1 prints the contents of the array representing the number.
1072function bigInt2str(x,base) {
1073  var i,t,s="";
1074
1075  if (s6.length!=x.length)
1076    s6=dup(x);
1077  else
1078    copy_(s6,x);
1079
1080  if (base==-1) { //return the list of array contents
1081    for (i=x.length-1;i>0;i--)
1082      s+=x[i]+',';
1083    s+=x[0];
1084  }
1085  else { //return it in the given base
1086    while (!isZero(s6)) {
1087      t=divInt_(s6,base);  //t=s6 % base; s6=floor(s6/base);
1088      s=digitsStr.substring(t,t+1)+s;
1089    }
1090  }
1091  if (s.length==0)
1092    s="0";
1093  return s;
1094}
1095
1096//returns a duplicate of bigInt x
1097function dup(x) {
1098  var i;
1099  buff=new Array(x.length);
1100  copy_(buff,x);
1101  return buff;
1102}
1103
1104//do x=y on bigInts x and y.  x must be an array at least as big as y (not counting the leading zeros in y).
1105function copy_(x,y) {
1106  var i;
1107  var k=x.length<y.length ? x.length : y.length;
1108  for (i=0;i<k;i++)
1109    x[i]=y[i];
1110  for (i=k;i<x.length;i++)
1111    x[i]=0;
1112}
1113
1114//do x=y on bigInt x and integer y. 
1115function copyInt_(x,n) {
1116  var i,c;
1117  for (c=n,i=0;i<x.length;i++) {
1118    x[i]=c & mask;
1119    c>>=bpe;
1120  }
1121}
1122
1123//do x=x+n where x is a bigInt and n is an integer.
1124//x must be large enough to hold the result.
1125function addInt_(x,n) {
1126  var i,k,c,b;
1127  x[0]+=n;
1128  k=x.length;
1129  c=0;
1130  for (i=0;i<k;i++) {
1131    c+=x[i];
1132    b=0;
1133    if (c<0) {
1134      b=-(c>>bpe);
1135      c+=b*radix;
1136    }
1137    x[i]=c & mask;
1138    c=(c>>bpe)-b;
1139    if (!c) return; //stop carrying as soon as the carry is zero
1140  }
1141}
1142
1143//right shift bigInt x by n bits.  0 <= n < bpe.
1144function rightShift_(x,n) {
1145  var i;
1146  var k=Math.floor(n/bpe);
1147  if (k) {
1148    for (i=0;i<x.length-k;i++) //right shift x by k elements
1149      x[i]=x[i+k];
1150    for (;i<x.length;i++)
1151      x[i]=0;
1152    n%=bpe;
1153  }
1154  for (i=0;i<x.length-1;i++) {
1155    x[i]=mask & ((x[i+1]<<(bpe-n)) | (x[i]>>n));
1156  }
1157  x[i]>>=n;
1158}
1159
1160//do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement
1161function halve_(x) {
1162  var i;
1163  for (i=0;i<x.length-1;i++) {
1164    x[i]=mask & ((x[i+1]<<(bpe-1)) | (x[i]>>1));
1165  }
1166  x[i]=(x[i]>>1) | (x[i] & (radix>>1));  //most significant bit stays the same
1167}
1168
1169//left shift bigInt x by n bits.
1170function leftShift_(x,n) {
1171  var i;
1172  var k=Math.floor(n/bpe);
1173  if (k) {
1174    for (i=x.length; i>=k; i--) //left shift x by k elements
1175      x[i]=x[i-k];
1176    for (;i>=0;i--)
1177      x[i]=0; 
1178    n%=bpe;
1179  }
1180  if (!n)
1181    return;
1182  for (i=x.length-1;i>0;i--) {
1183    x[i]=mask & ((x[i]<<n) | (x[i-1]>>(bpe-n)));
1184  }
1185  x[i]=mask & (x[i]<<n);
1186}
1187
1188//do x=x*n where x is a bigInt and n is an integer.
1189//x must be large enough to hold the result.
1190function multInt_(x,n) {
1191  var i,k,c,b;
1192  if (!n)
1193    return;
1194  k=x.length;
1195  c=0;
1196  for (i=0;i<k;i++) {
1197    c+=x[i]*n;
1198    b=0;
1199    if (c<0) {
1200      b=-(c>>bpe);
1201      c+=b*radix;
1202    }
1203    x[i]=c & mask;
1204    c=(c>>bpe)-b;
1205  }
1206}
1207
1208//do x=floor(x/n) for bigInt x and integer n, and return the remainder
1209function divInt_(x,n) {
1210  var i,r=0,s;
1211  for (i=x.length-1;i>=0;i--) {
1212    s=r*radix+x[i];
1213    x[i]=Math.floor(s/n);
1214    r=s%n;
1215  }
1216  return r;
1217}
1218
1219//do the linear combination x=a*x+b*y for bigInts x and y, and integers a and b.
1220//x must be large enough to hold the answer.
1221function linComb_(x,y,a,b) {
1222  var i,c,k,kk;
1223  k=x.length<y.length ? x.length : y.length;
1224  kk=x.length;
1225  for (c=0,i=0;i<k;i++) {
1226    c+=a*x[i]+b*y[i];
1227    x[i]=c & mask;
1228    c>>=bpe;
1229  }
1230  for (i=k;i<kk;i++) {
1231    c+=a*x[i];
1232    x[i]=c & mask;
1233    c>>=bpe;
1234  }
1235}
1236
1237//do the linear combination x=a*x+b*(y<<(ys*bpe)) for bigInts x and y, and integers a, b and ys.
1238//x must be large enough to hold the answer.
1239function linCombShift_(x,y,b,ys) {
1240  var i,c,k,kk;
1241  k=x.length<ys+y.length ? x.length : ys+y.length;
1242  kk=x.length;
1243  for (c=0,i=ys;i<k;i++) {
1244    c+=x[i]+b*y[i-ys];
1245    x[i]=c & mask;
1246    c>>=bpe;
1247  }
1248  for (i=k;c && i<kk;i++) {
1249    c+=x[i];
1250    x[i]=c & mask;
1251    c>>=bpe;
1252  }
1253}
1254
1255//do x=x+(y<<(ys*bpe)) for bigInts x and y, and integers a,b and ys.
1256//x must be large enough to hold the answer.
1257function addShift_(x,y,ys) {
1258  var i,c,k,kk;
1259  k=x.length<ys+y.length ? x.length : ys+y.length;
1260  kk=x.length;
1261  for (c=0,i=ys;i<k;i++) {
1262    c+=x[i]+y[i-ys];
1263    x[i]=c & mask;
1264    c>>=bpe;
1265  }
1266  for (i=k;c && i<kk;i++) {
1267    c+=x[i];
1268    x[i]=c & mask;
1269    c>>=bpe;
1270  }
1271}
1272
1273//do x=x-(y<<(ys*bpe)) for bigInts x and y, and integers a,b and ys.
1274//x must be large enough to hold the answer.
1275function subShift_(x,y,ys) {
1276  var i,c,k,kk;
1277  k=x.length<ys+y.length ? x.length : ys+y.length;
1278  kk=x.length;
1279  for (c=0,i=ys;i<k;i++) {
1280    c+=x[i]-y[i-ys];
1281    x[i]=c & mask;
1282    c>>=bpe;
1283  }
1284  for (i=k;c && i<kk;i++) {
1285    c+=x[i];
1286    x[i]=c & mask;
1287    c>>=bpe;
1288  }
1289}
1290
1291//do x=x-y for bigInts x and y.
1292//x must be large enough to hold the answer.
1293//negative answers will be 2s complement
1294function sub_(x,y) {
1295  var i,c,k,kk;
1296  k=x.length<y.length ? x.length : y.length;
1297  for (c=0,i=0;i<k;i++) {
1298    c+=x[i]-y[i];
1299    x[i]=c & mask;
1300    c>>=bpe;
1301  }
1302  for (i=k;c && i<x.length;i++) {
1303    c+=x[i];
1304    x[i]=c & mask;
1305    c>>=bpe;
1306  }
1307}
1308
1309//do x=x+y for bigInts x and y.
1310//x must be large enough to hold the answer.
1311function add_(x,y) {
1312  var i,c,k,kk;
1313  k=x.length<y.length ? x.length : y.length;
1314  for (c=0,i=0;i<k;i++) {
1315    c+=x[i]+y[i];
1316    x[i]=c & mask;
1317    c>>=bpe;
1318  }
1319  for (i=k;c && i<x.length;i++) {
1320    c+=x[i];
1321    x[i]=c & mask;
1322    c>>=bpe;
1323  }
1324}
1325
1326//do x=x*y for bigInts x and y.  This is faster when y<x.
1327function mult_(x,y) {
1328  var i;
1329  if (ss.length!=2*x.length)
1330    ss=new Array(2*x.length);
1331  copyInt_(ss,0);
1332  for (i=0;i<y.length;i++)
1333    if (y[i])
1334      linCombShift_(ss,x,y[i],i);   //ss=1*ss+y[i]*(x<<(i*bpe))
1335  copy_(x,ss);
1336}
1337
1338//do x=x mod n for bigInts x and n.
1339function mod_(x,n) {
1340  if (s4.length!=x.length)
1341    s4=dup(x);
1342  else
1343    copy_(s4,x);
1344  if (s5.length!=x.length)
1345    s5=dup(x); 
1346  divide_(s4,n,s5,x);  //x = remainder of s4 / n
1347}
1348
1349//do x=x*y mod n for bigInts x,y,n.
1350//for greater speed, let y<x.
1351function multMod_(x,y,n) {
1352  var i;
1353  if (s0.length!=2*x.length)
1354    s0=new Array(2*x.length);
1355  copyInt_(s0,0);
1356  for (i=0;i<y.length;i++)
1357    if (y[i])
1358      linCombShift_(s0,x,y[i],i);   //s0=1*s0+y[i]*(x<<(i*bpe))
1359  mod_(s0,n);
1360  copy_(x,s0);
1361}
1362
1363//do x=x*x mod n for bigInts x,n.
1364function squareMod_(x,n) {
1365  var i,j,d,c,kx,kn,k;
1366  for (kx=x.length; kx>0 && !x[kx-1]; kx--);  //ignore leading zeros in x
1367  k=kx>n.length ? 2*kx : 2*n.length; //k=# elements in the product, which is twice the elements in the larger of x and n
1368  if (s0.length!=k)
1369    s0=new Array(k);
1370  copyInt_(s0,0);
1371  for (i=0;i<kx;i++) {
1372    c=s0[2*i]+x[i]*x[i];
1373    s0[2*i]=c & mask;
1374    c>>=bpe;
1375    for (j=i+1;j<kx;j++) {
1376      c=s0[i+j]+2*x[i]*x[j]+c;
1377      s0[i+j]=(c & mask);
1378      c>>=bpe;
1379    }
1380    s0[i+kx]=c;
1381  }
1382  mod_(s0,n);
1383  copy_(x,s0);
1384}
1385
1386//return x with exactly k leading zero elements
1387function trim(x,k) {
1388  var i,y;
1389  for (i=x.length; i>0 && !x[i-1]; i--);
1390  y=new Array(i+k);
1391  copy_(y,x);
1392  return y;
1393}
1394
1395//do x=x**y mod n, where x,y,n are bigInts and ** is exponentiation.  0**0=1.
1396//this is faster when n is odd.  x usually needs to have as many elements as n.
1397function powMod_(x,y,n) {
1398  var k1,k2,kn,np;
1399  if(s7.length!=n.length)
1400    s7=dup(n);
1401
1402  //for even modulus, use a simple square-and-multiply algorithm,
1403  //rather than using the more complex Montgomery algorithm.
1404  if ((n[0]&1)==0) {
1405    copy_(s7,x);
1406    copyInt_(x,1);
1407    while(!equalsInt(y,0)) {
1408      if (y[0]&1)
1409        multMod_(x,s7,n);
1410      divInt_(y,2);
1411      squareMod_(s7,n);
1412    }
1413    return;
1414  }
1415
1416  //calculate np from n for the Montgomery multiplications
1417  copyInt_(s7,0);
1418  for (kn=n.length;kn>0 && !n[kn-1];kn--);
1419  np=radix-inverseModInt(modInt(n,radix),radix);
1420  s7[kn]=1;
1421  multMod_(x ,s7,n);   // x = x * 2**(kn*bp) mod n
1422
1423  if (s3.length!=x.length)
1424    s3=dup(x);
1425  else
1426    copy_(s3,x);
1427
1428  for (k1=y.length-1;k1>0 & !y[k1]; k1--);  //k1=first nonzero element of y
1429  if (y[k1]==0) {  //anything to the 0th power is 1
1430    copyInt_(x,1);
1431    return;
1432  }
1433  for (k2=1<<(bpe-1);k2 && !(y[k1] & k2); k2>>=1);  //k2=position of first 1 bit in y[k1]
1434  for (;;) {
1435    if (!(k2>>=1)) {  //look at next bit of y
1436      k1--;
1437      if (k1<0) {
1438        mont_(x,one,n,np);
1439        return;
1440      }
1441      k2=1<<(bpe-1);
1442    }   
1443    mont_(x,x,n,np);
1444
1445    if (k2 & y[k1]) //if next bit is a 1
1446      mont_(x,s3,n,np);
1447  }
1448}
1449
1450
1451//do x=x*y*Ri mod n for bigInts x,y,n,
1452//  where Ri = 2**(-kn*bpe) mod n, and kn is the
1453//  number of elements in the n array, not
1454//  counting leading zeros. 
1455//x array must have at least as many elemnts as the n array
1456//It's OK if x and y are the same variable.
1457//must have:
1458//  x,y < n
1459//  n is odd
1460//  np = -(n^(-1)) mod radix
1461function mont_(x,y,n,np) {
1462  var i,j,c,ui,t,ks;
1463  var kn=n.length;
1464  var ky=y.length;
1465
1466  if (sa.length!=kn)
1467    sa=new Array(kn);
1468   
1469  copyInt_(sa,0);
1470
1471  for (;kn>0 && n[kn-1]==0;kn--); //ignore leading zeros of n
1472  for (;ky>0 && y[ky-1]==0;ky--); //ignore leading zeros of y
1473  ks=sa.length-1; //sa will never have more than this many nonzero elements. 
1474
1475  //the following loop consumes 95% of the runtime for randTruePrime_() and powMod_() for large numbers
1476  for (i=0; i<kn; i++) {
1477    t=sa[0]+x[i]*y[0];
1478    ui=((t & mask) * np) & mask;  //the inner "& mask" was needed on Safari (but not MSIE) at one time
1479    c=(t+ui*n[0]) >> bpe;
1480    t=x[i];
1481   
1482    //do sa=(sa+x[i]*y+ui*n)/b   where b=2**bpe.  Loop is unrolled 5-fold for speed
1483    j=1;
1484    for (;j<ky-4;) { c+=sa[j]+ui*n[j]+t*y[j];   sa[j-1]=c & mask;   c>>=bpe;   j++;
1485                     c+=sa[j]+ui*n[j]+t*y[j];   sa[j-1]=c & mask;   c>>=bpe;   j++;
1486                     c+=sa[j]+ui*n[j]+t*y[j];   sa[j-1]=c & mask;   c>>=bpe;   j++;
1487                     c+=sa[j]+ui*n[j]+t*y[j];   sa[j-1]=c & mask;   c>>=bpe;   j++;
1488                     c+=sa[j]+ui*n[j]+t*y[j];   sa[j-1]=c & mask;   c>>=bpe;   j++; }   
1489    for (;j<ky;)   { c+=sa[j]+ui*n[j]+t*y[j];   sa[j-1]=c & mask;   c>>=bpe;   j++; }
1490    for (;j<kn-4;) { c+=sa[j]+ui*n[j];          sa[j-1]=c & mask;   c>>=bpe;   j++;
1491                     c+=sa[j]+ui*n[j];          sa[j-1]=c & mask;   c>>=bpe;   j++;
1492                     c+=sa[j]+ui*n[j];          sa[j-1]=c & mask;   c>>=bpe;   j++;
1493                     c+=sa[j]+ui*n[j];          sa[j-1]=c & mask;   c>>=bpe;   j++;
1494                     c+=sa[j]+ui*n[j];          sa[j-1]=c & mask;   c>>=bpe;   j++; } 
1495    for (;j<kn;)   { c+=sa[j]+ui*n[j];          sa[j-1]=c & mask;   c>>=bpe;   j++; }   
1496    for (;j<ks;)   { c+=sa[j];                  sa[j-1]=c & mask;   c>>=bpe;   j++; } 
1497    sa[j-1]=c & mask;
1498  }
1499
1500  if (!greater(n,sa))
1501    sub_(sa,n);
1502  copy_(x,sa);
1503}
1504
1505
Note: See TracBrowser for help on using the repository browser.