comparison scripts/minifier/otr/dep/bigint.js @ 12:1596660ddf72

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