summaryrefslogtreecommitdiff
path: root/frontend/delta/js/Clipperz/Crypto/BigInt.js
Unidiff
Diffstat (limited to 'frontend/delta/js/Clipperz/Crypto/BigInt.js') (more/less context) (ignore whitespace changes)
-rw-r--r--frontend/delta/js/Clipperz/Crypto/BigInt.js1754
1 files changed, 1754 insertions, 0 deletions
diff --git a/frontend/delta/js/Clipperz/Crypto/BigInt.js b/frontend/delta/js/Clipperz/Crypto/BigInt.js
new file mode 100644
index 0000000..031ed30
--- a/dev/null
+++ b/frontend/delta/js/Clipperz/Crypto/BigInt.js
@@ -0,0 +1,1754 @@
1/*
2
3Copyright 2008-2013 Clipperz Srl
4
5This file is part of Clipperz, the online password manager.
6For further information about its features and functionalities please
7refer to http://www.clipperz.com.
8
9* Clipperz is free software: you can redistribute it and/or modify it
10 under the terms of the GNU Affero General Public License as published
11 by the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
13
14* Clipperz is distributed in the hope that it will be useful, but
15 WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
17 See the GNU Affero General Public License for more details.
18
19* You should have received a copy of the GNU Affero General Public
20 License along with Clipperz. If not, see http://www.gnu.org/licenses/.
21
22*/
23
24if (typeof(Clipperz) == 'undefined') { Clipperz = {}; }
25if (typeof(Clipperz.Crypto) == 'undefined') { Clipperz.Crypto = {}; }
26
27//#############################################################################
28 //Downloaded on March 05, 2007 from http://www.leemon.com/crypto/BigInt.js
29//#############################################################################
30
31
32////////////////////////////////////////////////////////////////////////////////////////
33// Big Integer Library v. 5.0
34// Created 2000, last modified 2006
35// Leemon Baird
36// www.leemon.com
37//
38// This file is public domain. You can use it for any purpose without restriction.
39// I do not guarantee that it is correct, so use it at your own risk. If you use
40// it for something interesting, I'd appreciate hearing about it. If you find
41// any bugs or make any improvements, I'd appreciate hearing about those too.
42// It would also be nice if my name and address were left in the comments.
43// But none of that is required.
44//
45// This code defines a bigInt library for arbitrary-precision integers.
46// A bigInt is an array of integers storing the value in chunks of bpe bits,
47// little endian (buff[0] is the least significant word).
48// Negative bigInts are stored two's complement.
49// Some functions assume their parameters have at least one leading zero element.
50// Functions with an underscore at the end of the name have unpredictable behavior in case of overflow,
51// so the caller must make sure overflow won't happen.
52// For each function where a parameter is modified, that same
53// variable must not be used as another argument too.
54// So, you cannot square x by doing multMod_(x,x,n).
55// You must use squareMod_(x,n) instead, or do y=dup(x); multMod_(x,y,n).
56//
57// These functions are designed to avoid frequent dynamic memory allocation in the inner loop.
58// For most functions, if it needs a BigInt as a local variable it will actually use
59// a global, and will only allocate to it when it's not the right size. This ensures
60// that when a function is called repeatedly with same-sized parameters, it only allocates
61// memory on the first call.
62//
63// Note that for cryptographic purposes, the calls to Math.random() must
64// be replaced with calls to a better pseudorandom number generator.
65//
66// In the following, "bigInt" means a bigInt with at least one leading zero element,
67// and "integer" means a nonnegative integer less than radix. In some cases, integer
68// can be negative. Negative bigInts are 2s complement.
69//
70// The following functions do not modify their inputs, but dynamically allocate memory every time they are called:
71//
72// function bigInt2str(x,base) //convert a bigInt into a string in a given base, from base 2 up to base 95
73// function dup(x) //returns a copy of bigInt x
74// function findPrimes(n) //return array of all primes less than integer n
75// function int2bigInt(t,n,m) //convert integer t to a bigInt with at least n bits and m array elements
76// function int2bigInt(s,b,n,m) //convert string s in base b to a bigInt with at least n bits and m array elements
77// function trim(x,k) //return a copy of x with exactly k leading zero elements
78//
79// The following functions do not modify their inputs, so there is never a problem with the result being too big:
80//
81// function bitSize(x) //returns how many bits long the bigInt x is, not counting leading zeros
82// function equals(x,y) //is the bigInt x equal to the bigint y?
83// function equalsInt(x,y) //is bigint x equal to integer y?
84// function greater(x,y) //is x>y? (x and y are nonnegative bigInts)
85// function greaterShift(x,y,shift)//is (x <<(shift*bpe)) > y?
86// function isZero(x) //is the bigInt x equal to zero?
87// function millerRabin(x,b) //does one round of Miller-Rabin base integer b say that bigInt x is possibly prime (as opposed to definitely composite)?
88// function modInt(x,n) //return x mod n for bigInt x and integer n.
89// function negative(x) //is bigInt x negative?
90//
91// The following functions do not modify their inputs, but allocate memory and call functions with underscores
92//
93// function add(x,y) //return (x+y) for bigInts x and y.
94// function addInt(x,n) //return (x+n) where x is a bigInt and n is an integer.
95// function expand(x,n) //return a copy of x with at least n elements, adding leading zeros if needed
96// function inverseMod(x,n) //return (x**(-1) mod n) for bigInts x and n. If no inverse exists, it returns null
97// function mod(x,n) //return a new bigInt equal to (x mod n) for bigInts x and n.
98// function mult(x,y) //return x*y for bigInts x and y. This is faster when y<x.
99// function multMod(x,y,n) //return (x*y mod n) for bigInts x,y,n. For greater speed, let y<x.
100// function 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.
101// function randTruePrime(k) //return a new, random, k-bit, true prime using Maurer's algorithm.
102// function sub(x,y) //return (x-y) for bigInts x and y. Negative answers will be 2s complement
103//
104// The following functions write a bigInt result to one of the parameters, but
105// the result is never bigger than the original, so there can't be overflow problems:
106//
107// function divInt_(x,n) //do x=floor(x/n) for bigInt x and integer n, and return the remainder
108// function GCD_(x,y) //set x to the greatest common divisor of bigInts x and y, (y is destroyed).
109// function halve_(x) //do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement
110// function mod_(x,n) //do x=x mod n for bigInts x and n.
111// function rightShift_(x,n) //right shift bigInt x by n bits. 0 <= n < bpe.
112//
113// The following functions write a bigInt result to one of the parameters. The caller is responsible for
114// ensuring it is large enough to hold the result.
115//
116// function addInt_(x,n) //do x=x+n where x is a bigInt and n is an integer
117// function add_(x,y) //do x=x+y for bigInts x and y
118// function addShift_(x,y,ys) //do x=x+(y<<(ys*bpe))
119// function copy_(x,y) //do x=y on bigInts x and y
120// function copyInt_(x,n) //do x=n on bigInt x and integer n
121// function carry_(x) //do carries and borrows so each element of the bigInt x fits in bpe bits.
122// function divide_(x,y,q,r) //divide_ x by y giving quotient q and remainder r
123// function eGCD_(x,y,d,a,b) //sets a,b,d to positive big integers such that d = GCD_(x,y) = a*x-b*y
124// function inverseMod_(x,n) //do x=x**(-1) mod n, for bigInts x and n. Returns 1 (0) if inverse does (doesn't) exist
125// function inverseModInt_(x,n) //return x**(-1) mod n, for integers x and n. Return 0 if there is no inverse
126// function leftShift_(x,n) //left shift bigInt x by n bits. n<bpe.
127// function linComb_(x,y,a,b) //do x=a*x+b*y for bigInts x and y and integers a and b
128// function linCombShift_(x,y,b,ys) //do x=x+b*(y<<(ys*bpe)) for bigInts x and y, and integers b and ys
129// function mont_(x,y,n,np) //Montgomery multiplication (see comments where the function is defined)
130// function mult_(x,y) //do x=x*y for bigInts x and y.
131// function multInt_(x,n) //do x=x*n where x is a bigInt and n is an integer.
132// function multMod_(x,y,n) //do x=x*y mod n for bigInts x,y,n.
133// function 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.
134// function 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.
135// function randTruePrime_(ans,k) //do ans = a random k-bit true random prime (not just probable prime) with 1 in the msb.
136// function squareMod_(x,n) //do x=x*x mod n for bigInts x,n
137// function sub_(x,y) //do x=x-y for bigInts x and y. Negative answers will be 2s complement.
138// function 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
214////////////////////////////////////////////////////////////////////////////////////////
215
216//return array of all primes less than integer n
217function findPrimes(n) {
218 var i,s,p,ans;
219 s=new Array(n);
220 for (i=0;i<n;i++)
221 s[i]=0;
222 s[0]=2;
223 p=0; //first p elements of s are primes, the rest are a sieve
224 for(;s[p]<n;) { //s[p] is the pth prime
225 for(i=s[p]*s[p]; i<n; i+=s[p]) //mark multiples of s[p]
226 s[i]=1;
227 p++;
228 s[p]=s[p-1]+1;
229 for(; s[p]<n && s[s[p]]; s[p]++); //find next prime (where s[p]==0)
230 }
231 ans=new Array(p);
232 for(i=0;i<p;i++)
233 ans[i]=s[i];
234 return ans;
235}
236
237//does a single round of Miller-Rabin base b consider x to be a possible prime?
238//x is a bigInt, and b is an integer
239function millerRabin(x,b) {
240 var i,j,k,s;
241
242 if (mr_x1.length!=x.length) {
243 mr_x1=dup(x);
244 mr_r=dup(x);
245 mr_a=dup(x);
246 }
247
248 copyInt_(mr_a,b);
249 copy_(mr_r,x);
250 copy_(mr_x1,x);
251
252 addInt_(mr_r,-1);
253 addInt_(mr_x1,-1);
254
255 //s=the highest power of two that divides mr_r
256 k=0;
257 for (i=0;i<mr_r.length;i++)
258 for (j=1;j<mask;j<<=1)
259 if (x[i] & j) {
260 s=(k<mr_r.length+bpe ? k : 0);
261 i=mr_r.length;
262 j=mask;
263 } else
264 k++;
265
266 if (s)
267 rightShift_(mr_r,s);
268
269 powMod_(mr_a,mr_r,x);
270
271 if (!equalsInt(mr_a,1) && !equals(mr_a,mr_x1)) {
272 j=1;
273 while (j<=s-1 && !equals(mr_a,mr_x1)) {
274 squareMod_(mr_a,x);
275 if (equalsInt(mr_a,1)) {
276 return 0;
277 }
278 j++;
279 }
280 if (!equals(mr_a,mr_x1)) {
281 return 0;
282 }
283 }
284 return 1;
285}
286
287//returns how many bits long the bigInt is, not counting leading zeros.
288function bitSize(x) {
289 var j,z,w;
290 for (j=x.length-1; (x[j]==0) && (j>0); j--);
291 for (z=0,w=x[j]; w; (w>>=1),z++);
292 z+=bpe*j;
293 return z;
294}
295
296//return a copy of x with at least n elements, adding leading zeros if needed
297function expand(x,n) {
298 var ans=int2bigInt(0,(x.length>n ? x.length : n)*bpe,0);
299 copy_(ans,x);
300 return ans;
301}
302
303//return a k-bit true random prime using Maurer's algorithm.
304function randTruePrime(k) {
305 var ans=int2bigInt(0,k,0);
306 randTruePrime_(ans,k);
307 return trim(ans,1);
308}
309
310//return a new bigInt equal to (x mod n) for bigInts x and n.
311function mod(x,n) {
312 var ans=dup(x);
313 mod_(ans,n);
314 return trim(ans,1);
315}
316
317//return (x+n) where x is a bigInt and n is an integer.
318function addInt(x,n) {
319 var ans=expand(x,x.length+1);
320 addInt_(ans,n);
321 return trim(ans,1);
322}
323
324//return x*y for bigInts x and y. This is faster when y<x.
325function mult(x,y) {
326 var ans=expand(x,x.length+y.length);
327 mult_(ans,y);
328 return trim(ans,1);
329}
330
331//return (x**y mod n) where x,y,n are bigInts and ** is exponentiation. 0**0=1. Faster for odd n.
332function powMod(x,y,n) {
333 var ans=expand(x,n.length);
334 powMod_(ans,trim(y,2),trim(n,2),0); //this should work without the trim, but doesn't
335 return trim(ans,1);
336}
337
338//return (x-y) for bigInts x and y. Negative answers will be 2s complement
339function sub(x,y) {
340 var ans=expand(x,(x.length>y.length ? x.length+1 : y.length+1));
341 sub_(ans,y);
342 return trim(ans,1);
343}
344
345//return (x+y) for bigInts x and y.
346function add(x,y) {
347 var ans=expand(x,(x.length>y.length ? x.length+1 : y.length+1));
348 add_(ans,y);
349 return trim(ans,1);
350}
351
352//return (x**(-1) mod n) for bigInts x and n. If no inverse exists, it returns null
353function inverseMod(x,n) {
354 var ans=expand(x,n.length);
355 var s;
356 s=inverseMod_(ans,n);
357 return s ? trim(ans,1) : null;
358}
359
360//return (x*y mod n) for bigInts x,y,n. For greater speed, let y<x.
361function multMod(x,y,n) {
362 var ans=expand(x,n.length);
363 multMod_(ans,y,n);
364 return trim(ans,1);
365}
366
367//generate a k-bit true random prime using Maurer's algorithm,
368//and put it into ans. The bigInt ans must be large enough to hold it.
369function randTruePrime_(ans,k) {
370 var c,m,pm,dd,j,r,B,divisible,z,zz,recSize;
371
372 if (primes.length==0)
373 primes=findPrimes(30000); //check for divisibility by primes <=30000
374
375 if (pows.length==0) {
376 pows=new Array(512);
377 for (j=0;j<512;j++) {
378 pows[j]=Math.pow(2,j/511.-1.);
379 }
380 }
381
382 //c and m should be tuned for a particular machine and value of k, to maximize speed
383 //this was: c=primes[primes.length-1]/k/k; //check using all the small primes. (c=0.1 in HAC)
384 c=0.1;
385 m=20; //generate this k-bit number by first recursively generating a number that has between k/2 and k-m bits
386 recLimit=20; /*must be at least 2 (was 29)*/ //stop recursion when k <=recLimit
387
388 if (s_i2.length!=ans.length) {
389 s_i2=dup(ans);
390 s_R =dup(ans);
391 s_n1=dup(ans);
392 s_r2=dup(ans);
393 s_d =dup(ans);
394 s_x1=dup(ans);
395 s_x2=dup(ans);
396 s_b =dup(ans);
397 s_n =dup(ans);
398 s_i =dup(ans);
399 s_rm=dup(ans);
400 s_q =dup(ans);
401 s_a =dup(ans);
402 s_aa=dup(ans);
403 }
404
405 if (k <= recLimit) { //generate small random primes by trial division up to its square root
406 pm=(1<<((k+2)>>1))-1; //pm is binary number with all ones, just over sqrt(2^k)
407 copyInt_(ans,0);
408 for (dd=1;dd;) {
409 dd=0;
410 ans[0]= 1 | (1<<(k-1)) | Math.floor(Math.random()*(1<<k)); //random, k-bit, odd integer, with msb 1
411 for (j=1;(j<primes.length) && ((primes[j]&pm)==primes[j]);j++) { //trial division by all primes 3...sqrt(2^k)
412 if (0==(ans[0]%primes[j])) {
413 dd=1;
414 break;
415 }
416 }
417 }
418 carry_(ans);
419 return;
420 }
421
422 B=c*k*k; //try small primes up to B (or all the primes[] array if the largest is less than B).
423 if (k>2*m) //generate this k-bit number by first recursively generating a number that has between k/2 and k-m bits
424 for (r=1; k-k*r<=m; )
425 r=pows[Math.floor(Math.random()*512)]; //r=Math.pow(2,Math.random()-1);
426 else
427 r=.5;
428
429 //simulation suggests the more complex algorithm using r=.333 is only slightly faster.
430
431 recSize=Math.floor(r*k)+1;
432
433 randTruePrime_(s_q,recSize);
434 copyInt_(s_i2,0);
435 s_i2[Math.floor((k-2)/bpe)] |= (1<<((k-2)%bpe)); //s_i2=2^(k-2)
436 divide_(s_i2,s_q,s_i,s_rm); //s_i=floor((2^(k-1))/(2q))
437
438 z=bitSize(s_i);
439
440 for (;;) {
441 for (;;) { //generate z-bit numbers until one falls in the range [0,s_i-1]
442 randBigInt_(s_R,z,0);
443 if (greater(s_i,s_R))
444 break;
445 } //now s_R is in the range [0,s_i-1]
446 addInt_(s_R,1); //now s_R is in the range [1,s_i]
447 add_(s_R,s_i); //now s_R is in the range [s_i+1,2*s_i]
448
449 copy_(s_n,s_q);
450 mult_(s_n,s_R);
451 multInt_(s_n,2);
452 addInt_(s_n,1); //s_n=2*s_R*s_q+1
453
454 copy_(s_r2,s_R);
455 multInt_(s_r2,2); //s_r2=2*s_R
456
457 //check s_n for divisibility by small primes up to B
458 for (divisible=0,j=0; (j<primes.length) && (primes[j]<B); j++)
459 if (modInt(s_n,primes[j])==0) {
460 divisible=1;
461 break;
462 }
463
464 if (!divisible) //if it passes small primes check, then try a single Miller-Rabin base 2
465 if (!millerRabin(s_n,2)) //this line represents 75% of the total runtime for randTruePrime_
466 divisible=1;
467
468 if (!divisible) { //if it passes that test, continue checking s_n
469 addInt_(s_n,-3);
470 for (j=s_n.length-1;(s_n[j]==0) && (j>0); j--); //strip leading zeros
471 for (zz=0,w=s_n[j]; w; (w>>=1),zz++);
472 zz+=bpe*j; //zz=number of bits in s_n, ignoring leading zeros
473 for (;;) { //generate z-bit numbers until one falls in the range [0,s_n-1]
474 randBigInt_(s_a,zz,0);
475 if (greater(s_n,s_a))
476 break;
477 } //now s_a is in the range [0,s_n-1]
478 addInt_(s_n,3); //now s_a is in the range [0,s_n-4]
479 addInt_(s_a,2); //now s_a is in the range [2,s_n-2]
480 copy_(s_b,s_a);
481 copy_(s_n1,s_n);
482 addInt_(s_n1,-1);
483 powMod_(s_b,s_n1,s_n); //s_b=s_a^(s_n-1) modulo s_n
484 addInt_(s_b,-1);
485 if (isZero(s_b)) {
486 copy_(s_b,s_a);
487 powMod_(s_b,s_r2,s_n);
488 addInt_(s_b,-1);
489 copy_(s_aa,s_n);
490 copy_(s_d,s_b);
491 GCD_(s_d,s_n); //if s_b and s_n are relatively prime, then s_n is a prime
492 if (equalsInt(s_d,1)) {
493 copy_(ans,s_aa);
494 return; //if we've made it this far, then s_n is absolutely guaranteed to be prime
495 }
496 }
497 }
498 }
499}
500
501//set b to an n-bit random BigInt. If s=1, then nth bit (most significant bit) is set to 1.
502//array b must be big enough to hold the result. Must have n>=1
503function randBigInt_(b,n,s) {
504 var i,a;
505 for (i=0;i<b.length;i++)
506 b[i]=0;
507 a=Math.floor((n-1)/bpe)+1; //# array elements to hold the BigInt
508 for (i=0;i<a;i++) {
509 b[i]=Math.floor(Math.random()*(1<<(bpe-1)));
510 }
511 b[a-1] &= (2<<((n-1)%bpe))-1;
512 if (s)
513 b[a-1] |= (1<<((n-1)%bpe));
514}
515
516//set x to the greatest common divisor of x and y.
517//x,y are bigInts with the same number of elements. y is destroyed.
518function GCD_(x,y) {
519 var i,xp,yp,A,B,C,D,q,sing;
520 if (T.length!=x.length)
521 T=dup(x);
522
523 sing=1;
524 while (sing) { //while y has nonzero elements other than y[0]
525 sing=0;
526 for (i=1;i<y.length;i++) //check if y has nonzero elements other than 0
527 if (y[i]) {
528 sing=1;
529 break;
530 }
531 if (!sing) break; //quit when y all zero elements except possibly y[0]
532
533 for (i=x.length;!x[i] && i>=0;i--); //find most significant element of x
534 xp=x[i];
535 yp=y[i];
536 A=1; B=0; C=0; D=1;
537 while ((yp+C) && (yp+D)) {
538 q =Math.floor((xp+A)/(yp+C));
539 qp=Math.floor((xp+B)/(yp+D));
540 if (q!=qp)
541 break;
542 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)
543 t= B-q*D; B=D; D=t;
544 t=xp-q*yp; xp=yp; yp=t;
545 }
546 if (B) {
547 copy_(T,x);
548 linComb_(x,y,A,B); //x=A*x+B*y
549 linComb_(y,T,D,C); //y=D*y+C*T
550 } else {
551 mod_(x,y);
552 copy_(T,x);
553 copy_(x,y);
554 copy_(y,T);
555 }
556 }
557 if (y[0]==0)
558 return;
559 t=modInt(x,y[0]);
560 copyInt_(x,y[0]);
561 y[0]=t;
562 while (y[0]) {
563 x[0]%=y[0];
564 t=x[0]; x[0]=y[0]; y[0]=t;
565 }
566}
567
568//do x=x**(-1) mod n, for bigInts x and n.
569//If no inverse exists, it sets x to zero and returns 0, else it returns 1.
570//The x array must be at least as large as the n array.
571function inverseMod_(x,n) {
572 var k=1+2*Math.max(x.length,n.length);
573
574 if(!(x[0]&1) && !(n[0]&1)) { //if both inputs are even, then inverse doesn't exist
575 copyInt_(x,0);
576 return 0;
577 }
578
579 if (eg_u.length!=k) {
580 eg_u=new Array(k);
581 eg_v=new Array(k);
582 eg_A=new Array(k);
583 eg_B=new Array(k);
584 eg_C=new Array(k);
585 eg_D=new Array(k);
586 }
587
588 copy_(eg_u,x);
589 copy_(eg_v,n);
590 copyInt_(eg_A,1);
591 copyInt_(eg_B,0);
592 copyInt_(eg_C,0);
593 copyInt_(eg_D,1);
594 for (;;) {
595 while(!(eg_u[0]&1)) { //while eg_u is even
596 halve_(eg_u);
597 if (!(eg_A[0]&1) && !(eg_B[0]&1)) { //if eg_A==eg_B==0 mod 2
598 halve_(eg_A);
599 halve_(eg_B);
600 } else {
601 add_(eg_A,n); halve_(eg_A);
602 sub_(eg_B,x); halve_(eg_B);
603 }
604 }
605
606 while (!(eg_v[0]&1)) { //while eg_v is even
607 halve_(eg_v);
608 if (!(eg_C[0]&1) && !(eg_D[0]&1)) { //if eg_C==eg_D==0 mod 2
609 halve_(eg_C);
610 halve_(eg_D);
611 } else {
612 add_(eg_C,n); halve_(eg_C);
613 sub_(eg_D,x); halve_(eg_D);
614 }
615 }
616
617 if (!greater(eg_v,eg_u)) { //eg_v <= eg_u
618 sub_(eg_u,eg_v);
619 sub_(eg_A,eg_C);
620 sub_(eg_B,eg_D);
621 } else { //eg_v > eg_u
622 sub_(eg_v,eg_u);
623 sub_(eg_C,eg_A);
624 sub_(eg_D,eg_B);
625 }
626
627 if (equalsInt(eg_u,0)) {
628 if (negative(eg_C)) //make sure answer is nonnegative
629 add_(eg_C,n);
630 copy_(x,eg_C);
631
632 if (!equalsInt(eg_v,1)) { //if GCD_(x,n)!=1, then there is no inverse
633 copyInt_(x,0);
634 return 0;
635 }
636 return 1;
637 }
638 }
639}
640
641//return x**(-1) mod n, for integers x and n. Return 0 if there is no inverse
642function inverseModInt_(x,n) {
643 var a=1,b=0,t;
644 for (;;) {
645 if (x==1) return a;
646 if (x==0) return 0;
647 b-=a*Math.floor(n/x);
648 n%=x;
649
650 if (n==1) return b; //to avoid negatives, change this b to n-b, and each -= to +=
651 if (n==0) return 0;
652 a-=b*Math.floor(x/n);
653 x%=n;
654 }
655}
656
657//Given positive bigInts x and y, change the bigints v, a, and b to positive bigInts such that:
658// v = GCD_(x,y) = a*x-b*y
659//The bigInts v, a, b, must have exactly as many elements as the larger of x and y.
660function eGCD_(x,y,v,a,b) {
661 var g=0;
662 var k=Math.max(x.length,y.length);
663 if (eg_u.length!=k) {
664 eg_u=new Array(k);
665 eg_A=new Array(k);
666 eg_B=new Array(k);
667 eg_C=new Array(k);
668 eg_D=new Array(k);
669 }
670 while(!(x[0]&1) && !(y[0]&1)) { //while x and y both even
671 halve_(x);
672 halve_(y);
673 g++;
674 }
675 copy_(eg_u,x);
676 copy_(v,y);
677 copyInt_(eg_A,1);
678 copyInt_(eg_B,0);
679 copyInt_(eg_C,0);
680 copyInt_(eg_D,1);
681 for (;;) {
682 while(!(eg_u[0]&1)) { //while u is even
683 halve_(eg_u);
684 if (!(eg_A[0]&1) && !(eg_B[0]&1)) { //if A==B==0 mod 2
685 halve_(eg_A);
686 halve_(eg_B);
687 } else {
688 add_(eg_A,y); halve_(eg_A);
689 sub_(eg_B,x); halve_(eg_B);
690 }
691 }
692
693 while (!(v[0]&1)) { //while v is even
694 halve_(v);
695 if (!(eg_C[0]&1) && !(eg_D[0]&1)) { //if C==D==0 mod 2
696 halve_(eg_C);
697 halve_(eg_D);
698 } else {
699 add_(eg_C,y); halve_(eg_C);
700 sub_(eg_D,x); halve_(eg_D);
701 }
702 }
703
704 if (!greater(v,eg_u)) { //v<=u
705 sub_(eg_u,v);
706 sub_(eg_A,eg_C);
707 sub_(eg_B,eg_D);
708 } else { //v>u
709 sub_(v,eg_u);
710 sub_(eg_C,eg_A);
711 sub_(eg_D,eg_B);
712 }
713 if (equalsInt(eg_u,0)) {
714 if (negative(eg_C)) { //make sure a (C)is nonnegative
715 add_(eg_C,y);
716 sub_(eg_D,x);
717 }
718 multInt_(eg_D,-1); ///make sure b (D) is nonnegative
719 copy_(a,eg_C);
720 copy_(b,eg_D);
721 leftShift_(v,g);
722 return;
723 }
724 }
725}
726
727
728//is bigInt x negative?
729function negative(x) {
730 return ((x[x.length-1]>>(bpe-1))&1);
731}
732
733
734//is (x << (shift*bpe)) > y?
735//x and y are nonnegative bigInts
736//shift is a nonnegative integer
737function greaterShift(x,y,shift) {
738 var kx=x.length, ky=y.length;
739 k=((kx+shift)<ky) ? (kx+shift) : ky;
740 for (i=ky-1-shift; i<kx && i>=0; i++)
741 if (x[i]>0)
742 return 1; //if there are nonzeros in x to the left of the first column of y, then x is bigger
743 for (i=kx-1+shift; i<ky; i++)
744 if (y[i]>0)
745 return 0; //if there are nonzeros in y to the left of the first column of x, then x is not bigger
746 for (i=k-1; i>=shift; i--)
747 if (x[i-shift]>y[i]) return 1;
748 else if (x[i-shift]<y[i]) return 0;
749 return 0;
750}
751
752//is x > y? (x and y both nonnegative)
753function greater(x,y) {
754 var i;
755 var k=(x.length<y.length) ? x.length : y.length;
756
757 for (i=x.length;i<y.length;i++)
758 if (y[i])
759 return 0; //y has more digits
760
761 for (i=y.length;i<x.length;i++)
762 if (x[i])
763 return 1; //x has more digits
764
765 for (i=k-1;i>=0;i--)
766 if (x[i]>y[i])
767 return 1;
768 else if (x[i]<y[i])
769 return 0;
770 return 0;
771}
772
773//divide_ x by y giving quotient q and remainder r. (q=floor(x/y), r=x mod y). All 4 are bigints.
774//x must have at least one leading zero element.
775//y must be nonzero.
776//q and r must be arrays that are exactly the same length as x.
777//the x array must have at least as many elements as y.
778function divide_(x,y,q,r) {
779 var kx, ky;
780 var i,j,y1,y2,c,a,b;
781 copy_(r,x);
782 for (ky=y.length;y[ky-1]==0;ky--); //kx,ky is number of elements in x,y, not including leading zeros
783 for (kx=r.length;r[kx-1]==0 && kx>ky;kx--);
784
785 //normalize: ensure the most significant element of y has its highest bit set
786 b=y[ky-1];
787 for (a=0; b; a++)
788 b>>=1;
789 a=bpe-a; //a is how many bits to shift so that the high order bit of y is leftmost in its array element
790 leftShift_(y,a); //multiply both by 1<<a now, then divide_ both by that at the end
791 leftShift_(r,a);
792
793 copyInt_(q,0); // q=0
794 while (!greaterShift(y,r,kx-ky)) { // while (leftShift_(y,kx-ky) <= r) {
795 subShift_(r,y,kx-ky); // r=r-leftShift_(y,kx-ky)
796 q[kx-ky]++; // q[kx-ky]++;
797 } // }
798
799 for (i=kx-1; i>=ky; i--) {
800 if (r[i]==y[ky-1])
801 q[i-ky]=mask;
802 else
803 q[i-ky]=Math.floor((r[i]*radix+r[i-1])/y[ky-1]);
804
805 //The following for(;;) loop is equivalent to the commented while loop,
806 //except that the uncommented version avoids overflow.
807 //The commented loop comes from HAC, which assumes r[-1]==y[-1]==0
808 // while (q[i-ky]*(y[ky-1]*radix+y[ky-2]) > r[i]*radix*radix+r[i-1]*radix+r[i-2])
809 // q[i-ky]--;
810 for (;;) {
811 y2=(ky>1 ? y[ky-2] : 0)*q[i-ky];
812 c=y2>>bpe;
813 y2=y2 & mask;
814 y1=c+q[i-ky]*y[ky-1];
815 c=y1>>bpe;
816 y1=y1 & mask;
817
818 if (c==r[i] ? y1==r[i-1] ? y2>(i>1 ? r[i-2] : 0) : y1>r[i-1] : c>r[i])
819 q[i-ky]--;
820 else
821 break;
822 }
823
824 linCombShift_(r,y,-q[i-ky],i-ky); //r=r-q[i-ky]*leftShift_(y,i-ky)
825 if (negative(r)) {
826 addShift_(r,y,i-ky); //r=r+leftShift_(y,i-ky)
827 q[i-ky]--;
828 }
829 }
830
831 rightShift_(y,a); //undo the normalization step
832 rightShift_(r,a); //undo the normalization step
833}
834
835//do carries and borrows so each element of the bigInt x fits in bpe bits.
836function carry_(x) {
837 var i,k,c,b;
838 k=x.length;
839 c=0;
840 for (i=0;i<k;i++) {
841 c+=x[i];
842 b=0;
843 if (c<0) {
844 b=-(c>>bpe);
845 c+=b*radix;
846 }
847 x[i]=c & mask;
848 c=(c>>bpe)-b;
849 }
850}
851
852//return x mod n for bigInt x and integer n.
853function modInt(x,n) {
854 var i,c=0;
855 for (i=x.length-1; i>=0; i--)
856 c=(c*radix+x[i])%n;
857 return c;
858}
859
860//convert the integer t into a bigInt with at least the given number of bits.
861//the returned array stores the bigInt in bpe-bit chunks, little endian (buff[0] is least significant word)
862//Pad the array with leading zeros so that it has at least minSize elements.
863//There will always be at least one leading 0 element.
864function int2bigInt(t,bits,minSize) {
865 var i,k;
866 k=Math.ceil(bits/bpe)+1;
867 k=minSize>k ? minSize : k;
868 buff=new Array(k);
869 copyInt_(buff,t);
870 return buff;
871}
872
873//return the bigInt given a string representation in a given base.
874//Pad the array with leading zeros so that it has at least minSize elements.
875//If base=-1, then it reads in a space-separated list of array elements in decimal.
876//The array will always have at least one leading zero, unless base=-1.
877function str2bigInt(s,base,minSize) {
878 var d, i, j, x, y, kk;
879 var k=s.length;
880 if (base==-1) { //comma-separated list of array elements in decimal
881 x=new Array(0);
882 for (;;) {
883 y=new Array(x.length+1);
884 for (i=0;i<x.length;i++)
885 y[i+1]=x[i];
886 y[0]=parseInt(s,10);
887 x=y;
888 d=s.indexOf(',',0);
889 if (d<1)
890 break;
891 s=s.substring(d+1);
892 if (s.length==0)
893 break;
894 }
895 if (x.length<minSize) {
896 y=new Array(minSize);
897 copy_(y,x);
898 return y;
899 }
900 return x;
901 }
902
903 x=int2bigInt(0,base*k,0);
904 for (i=0;i<k;i++) {
905 d=digitsStr.indexOf(s.substring(i,i+1),0);
906 if (base<=36 && d>=36) //convert lowercase to uppercase if base<=36
907 d-=26;
908 if (d<base && d>=0) { //ignore illegal characters
909 multInt_(x,base);
910 addInt_(x,d);
911 }
912 }
913
914 for (k=x.length;k>0 && !x[k-1];k--); //strip off leading zeros
915 k=minSize>k+1 ? minSize : k+1;
916 y=new Array(k);
917 kk=k<x.length ? k : x.length;
918 for (i=0;i<kk;i++)
919 y[i]=x[i];
920 for (;i<k;i++)
921 y[i]=0;
922 return y;
923}
924
925//is bigint x equal to integer y?
926//y must have less than bpe bits
927function equalsInt(x,y) {
928 var i;
929 if (x[0]!=y)
930 return 0;
931 for (i=1;i<x.length;i++)
932 if (x[i])
933 return 0;
934 return 1;
935}
936
937//are bigints x and y equal?
938//this works even if x and y are different lengths and have arbitrarily many leading zeros
939function equals(x,y) {
940 var i;
941 var k=x.length<y.length ? x.length : y.length;
942 for (i=0;i<k;i++)
943 if (x[i]!=y[i])
944 return 0;
945 if (x.length>y.length) {
946 for (;i<x.length;i++)
947 if (x[i])
948 return 0;
949 } else {
950 for (;i<y.length;i++)
951 if (y[i])
952 return 0;
953 }
954 return 1;
955}
956
957//is the bigInt x equal to zero?
958function isZero(x) {
959 var i;
960 for (i=0;i<x.length;i++)
961 if (x[i])
962 return 0;
963 return 1;
964}
965
966//convert a bigInt into a string in a given base, from base 2 up to base 95.
967//Base -1 prints the contents of the array representing the number.
968function bigInt2str(x,base) {
969 var i,t,s="";
970
971 if (s6.length!=x.length)
972 s6=dup(x);
973 else
974 copy_(s6,x);
975
976 if (base==-1) { //return the list of array contents
977 for (i=x.length-1;i>0;i--)
978 s+=x[i]+',';
979 s+=x[0];
980 }
981 else { //return it in the given base
982 while (!isZero(s6)) {
983 t=divInt_(s6,base); //t=s6 % base; s6=floor(s6/base);
984 s=digitsStr.substring(t,t+1)+s;
985 }
986 }
987 if (s.length==0)
988 s="0";
989 return s;
990}
991
992//returns a duplicate of bigInt x
993function dup(x) {
994 var i;
995 buff=new Array(x.length);
996 copy_(buff,x);
997 return buff;
998}
999
1000//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).
1001function copy_(x,y) {
1002 var i;
1003 var k=x.length<y.length ? x.length : y.length;
1004 for (i=0;i<k;i++)
1005 x[i]=y[i];
1006 for (i=k;i<x.length;i++)
1007 x[i]=0;
1008}
1009
1010//do x=y on bigInt x and integer y.
1011function copyInt_(x,n) {
1012 var i,c;
1013 for (c=n,i=0;i<x.length;i++) {
1014 x[i]=c & mask;
1015 c>>=bpe;
1016 }
1017}
1018
1019//do x=x+n where x is a bigInt and n is an integer.
1020//x must be large enough to hold the result.
1021function addInt_(x,n) {
1022 var i,k,c,b;
1023 x[0]+=n;
1024 k=x.length;
1025 c=0;
1026 for (i=0;i<k;i++) {
1027 c+=x[i];
1028 b=0;
1029 if (c<0) {
1030 b=-(c>>bpe);
1031 c+=b*radix;
1032 }
1033 x[i]=c & mask;
1034 c=(c>>bpe)-b;
1035 if (!c) return; //stop carrying as soon as the carry_ is zero
1036 }
1037}
1038
1039//right shift bigInt x by n bits. 0 <= n < bpe.
1040function rightShift_(x,n) {
1041 var i;
1042 var k=Math.floor(n/bpe);
1043 if (k) {
1044 for (i=0;i<x.length-k;i++) //right shift x by k elements
1045 x[i]=x[i+k];
1046 for (;i<x.length;i++)
1047 x[i]=0;
1048 n%=bpe;
1049 }
1050 for (i=0;i<x.length-1;i++) {
1051 x[i]=mask & ((x[i+1]<<(bpe-n)) | (x[i]>>n));
1052 }
1053 x[i]>>=n;
1054}
1055
1056//do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement
1057function halve_(x) {
1058 var i;
1059 for (i=0;i<x.length-1;i++) {
1060 x[i]=mask & ((x[i+1]<<(bpe-1)) | (x[i]>>1));
1061 }
1062 x[i]=(x[i]>>1) | (x[i] & (radix>>1)); //most significant bit stays the same
1063}
1064
1065//left shift bigInt x by n bits.
1066function leftShift_(x,n) {
1067 var i;
1068 var k=Math.floor(n/bpe);
1069 if (k) {
1070 for (i=x.length; i>=k; i--) //left shift x by k elements
1071 x[i]=x[i-k];
1072 for (;i>=0;i--)
1073 x[i]=0;
1074 n%=bpe;
1075 }
1076 if (!n)
1077 return;
1078 for (i=x.length-1;i>0;i--) {
1079 x[i]=mask & ((x[i]<<n) | (x[i-1]>>(bpe-n)));
1080 }
1081 x[i]=mask & (x[i]<<n);
1082}
1083
1084//do x=x*n where x is a bigInt and n is an integer.
1085//x must be large enough to hold the result.
1086function multInt_(x,n) {
1087 var i,k,c,b;
1088 if (!n)
1089 return;
1090 k=x.length;
1091 c=0;
1092 for (i=0;i<k;i++) {
1093 c+=x[i]*n;
1094 b=0;
1095 if (c<0) {
1096 b=-(c>>bpe);
1097 c+=b*radix;
1098 }
1099 x[i]=c & mask;
1100 c=(c>>bpe)-b;
1101 }
1102}
1103
1104//do x=floor(x/n) for bigInt x and integer n, and return the remainder
1105function divInt_(x,n) {
1106 var i,r=0,s;
1107 for (i=x.length-1;i>=0;i--) {
1108 s=r*radix+x[i];
1109 x[i]=Math.floor(s/n);
1110 r=s%n;
1111 }
1112 return r;
1113}
1114
1115//do the linear combination x=a*x+b*y for bigInts x and y, and integers a and b.
1116//x must be large enough to hold the answer.
1117function linComb_(x,y,a,b) {
1118 var i,c,k,kk;
1119 k=x.length<y.length ? x.length : y.length;
1120 kk=x.length;
1121 for (c=0,i=0;i<k;i++) {
1122 c+=a*x[i]+b*y[i];
1123 x[i]=c & mask;
1124 c>>=bpe;
1125 }
1126 for (i=k;i<kk;i++) {
1127 c+=a*x[i];
1128 x[i]=c & mask;
1129 c>>=bpe;
1130 }
1131}
1132
1133//do the linear combination x=a*x+b*(y<<(ys*bpe)) for bigInts x and y, and integers a, b and ys.
1134//x must be large enough to hold the answer.
1135function linCombShift_(x,y,b,ys) {
1136 var i,c,k,kk;
1137 k=x.length<ys+y.length ? x.length : ys+y.length;
1138 kk=x.length;
1139 for (c=0,i=ys;i<k;i++) {
1140 c+=x[i]+b*y[i-ys];
1141 x[i]=c & mask;
1142 c>>=bpe;
1143 }
1144 for (i=k;c && i<kk;i++) {
1145 c+=x[i];
1146 x[i]=c & mask;
1147 c>>=bpe;
1148 }
1149}
1150
1151//do x=x+(y<<(ys*bpe)) for bigInts x and y, and integers a,b and ys.
1152//x must be large enough to hold the answer.
1153function addShift_(x,y,ys) {
1154 var i,c,k,kk;
1155 k=x.length<ys+y.length ? x.length : ys+y.length;
1156 kk=x.length;
1157 for (c=0,i=ys;i<k;i++) {
1158 c+=x[i]+y[i-ys];
1159 x[i]=c & mask;
1160 c>>=bpe;
1161 }
1162 for (i=k;c && i<kk;i++) {
1163 c+=x[i];
1164 x[i]=c & mask;
1165 c>>=bpe;
1166 }
1167}
1168
1169//do x=x-(y<<(ys*bpe)) for bigInts x and y, and integers a,b and ys.
1170//x must be large enough to hold the answer.
1171function subShift_(x,y,ys) {
1172 var i,c,k,kk;
1173 k=x.length<ys+y.length ? x.length : ys+y.length;
1174 kk=x.length;
1175 for (c=0,i=ys;i<k;i++) {
1176 c+=x[i]-y[i-ys];
1177 x[i]=c & mask;
1178 c>>=bpe;
1179 }
1180 for (i=k;c && i<kk;i++) {
1181 c+=x[i];
1182 x[i]=c & mask;
1183 c>>=bpe;
1184 }
1185}
1186
1187//do x=x-y for bigInts x and y.
1188//x must be large enough to hold the answer.
1189//negative answers will be 2s complement
1190function sub_(x,y) {
1191 var i,c,k,kk;
1192 k=x.length<y.length ? x.length : y.length;
1193 for (c=0,i=0;i<k;i++) {
1194 c+=x[i]-y[i];
1195 x[i]=c & mask;
1196 c>>=bpe;
1197 }
1198 for (i=k;c && i<x.length;i++) {
1199 c+=x[i];
1200 x[i]=c & mask;
1201 c>>=bpe;
1202 }
1203}
1204
1205//do x=x+y for bigInts x and y.
1206//x must be large enough to hold the answer.
1207function add_(x,y) {
1208 var i,c,k,kk;
1209 k=x.length<y.length ? x.length : y.length;
1210 for (c=0,i=0;i<k;i++) {
1211 c+=x[i]+y[i];
1212 x[i]=c & mask;
1213 c>>=bpe;
1214 }
1215 for (i=k;c && i<x.length;i++) {
1216 c+=x[i];
1217 x[i]=c & mask;
1218 c>>=bpe;
1219 }
1220}
1221
1222//do x=x*y for bigInts x and y. This is faster when y<x.
1223function mult_(x,y) {
1224 var i;
1225 if (ss.length!=2*x.length)
1226 ss=new Array(2*x.length);
1227 copyInt_(ss,0);
1228 for (i=0;i<y.length;i++)
1229 if (y[i])
1230 linCombShift_(ss,x,y[i],i); //ss=1*ss+y[i]*(x<<(i*bpe))
1231 copy_(x,ss);
1232}
1233
1234//do x=x mod n for bigInts x and n.
1235function mod_(x,n) {
1236 if (s4.length!=x.length)
1237 s4=dup(x);
1238 else
1239 copy_(s4,x);
1240 if (s5.length!=x.length)
1241 s5=dup(x);
1242 divide_(s4,n,s5,x); //x = remainder of s4 / n
1243}
1244
1245//do x=x*y mod n for bigInts x,y,n.
1246//for greater speed, let y<x.
1247function multMod_(x,y,n) {
1248 var i;
1249 if (s0.length!=2*x.length)
1250 s0=new Array(2*x.length);
1251 copyInt_(s0,0);
1252 for (i=0;i<y.length;i++)
1253 if (y[i])
1254 linCombShift_(s0,x,y[i],i); //s0=1*s0+y[i]*(x<<(i*bpe))
1255 mod_(s0,n);
1256 copy_(x,s0);
1257}
1258
1259//do x=x*x mod n for bigInts x,n.
1260function squareMod_(x,n) {
1261 var i,j,d,c,kx,kn,k;
1262 for (kx=x.length; kx>0 && !x[kx-1]; kx--); //ignore leading zeros in x
1263 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
1264 if (s0.length!=k)
1265 s0=new Array(k);
1266 copyInt_(s0,0);
1267 for (i=0;i<kx;i++) {
1268 c=s0[2*i]+x[i]*x[i];
1269 s0[2*i]=c & mask;
1270 c>>=bpe;
1271 for (j=i+1;j<kx;j++) {
1272 c=s0[i+j]+2*x[i]*x[j]+c;
1273 s0[i+j]=(c & mask);
1274 c>>=bpe;
1275 }
1276 s0[i+kx]=c;
1277 }
1278 mod_(s0,n);
1279 copy_(x,s0);
1280}
1281
1282//return x with exactly k leading zero elements
1283function trim(x,k) {
1284 var i,y;
1285 for (i=x.length; i>0 && !x[i-1]; i--);
1286 y=new Array(i+k);
1287 copy_(y,x);
1288 return y;
1289}
1290
1291//do x=x**y mod n, where x,y,n are bigInts and ** is exponentiation. 0**0=1.
1292//this is faster when n is odd. x usually needs to have as many elements as n.
1293function powMod_(x,y,n) {
1294 var k1,k2,kn,np;
1295 if(s7.length!=n.length)
1296 s7=dup(n);
1297
1298 //for even modulus, use a simple square-and-multiply algorithm,
1299 //rather than using the more complex Montgomery algorithm.
1300 if ((n[0]&1)==0) {
1301 copy_(s7,x);
1302 copyInt_(x,1);
1303 while(!equalsInt(y,0)) {
1304 if (y[0]&1)
1305 multMod_(x,s7,n);
1306 divInt_(y,2);
1307 squareMod_(s7,n);
1308 }
1309 return;
1310 }
1311
1312 //calculate np from n for the Montgomery multiplications
1313 copyInt_(s7,0);
1314 for (kn=n.length;kn>0 && !n[kn-1];kn--);
1315 np=radix-inverseModInt_(modInt(n,radix),radix);
1316 s7[kn]=1;
1317 multMod_(x ,s7,n); // x = x * 2**(kn*bp) mod n
1318
1319 if (s3.length!=x.length)
1320 s3=dup(x);
1321 else
1322 copy_(s3,x);
1323
1324 for (k1=y.length-1;k1>0 & !y[k1]; k1--); //k1=first nonzero element of y
1325 if (y[k1]==0) { //anything to the 0th power is 1
1326 copyInt_(x,1);
1327 return;
1328 }
1329 for (k2=1<<(bpe-1);k2 && !(y[k1] & k2); k2>>=1); //k2=position of first 1 bit in y[k1]
1330 for (;;) {
1331 if (!(k2>>=1)) { //look at next bit of y
1332 k1--;
1333 if (k1<0) {
1334 mont_(x,one,n,np);
1335 return;
1336 }
1337 k2=1<<(bpe-1);
1338 }
1339 mont_(x,x,n,np);
1340
1341 if (k2 & y[k1]) //if next bit is a 1
1342 mont_(x,s3,n,np);
1343 }
1344}
1345
1346//do x=x*y*Ri mod n for bigInts x,y,n,
1347// where Ri = 2**(-kn*bpe) mod n, and kn is the
1348// number of elements in the n array, not
1349// counting leading zeros.
1350//x must be large enough to hold the answer.
1351//It's OK if x and y are the same variable.
1352//must have:
1353// x,y < n
1354// n is odd
1355// np = -(n^(-1)) mod radix
1356function mont_(x,y,n,np) {
1357 var i,j,c,ui,t;
1358 var kn=n.length;
1359 var ky=y.length;
1360
1361 if (sa.length!=kn)
1362 sa=new Array(kn);
1363
1364 for (;kn>0 && n[kn-1]==0;kn--); //ignore leading zeros of n
1365 //this function sometimes gives wrong answers when the next line is uncommented
1366 //for (;ky>0 && y[ky-1]==0;ky--); //ignore leading zeros of y
1367
1368 copyInt_(sa,0);
1369
1370 //the following loop consumes 95% of the runtime for randTruePrime_() and powMod_() for large keys
1371 for (i=0; i<kn; i++) {
1372 t=sa[0]+x[i]*y[0];
1373 ui=((t & mask) * np) & mask; //the inner "& mask" is needed on Macintosh MSIE, but not windows MSIE
1374 c=(t+ui*n[0]) >> bpe;
1375 t=x[i];
1376
1377 //do sa=(sa+x[i]*y+ui*n)/b where b=2**bpe
1378 for (j=1;j<ky;j++) {
1379 c+=sa[j]+t*y[j]+ui*n[j];
1380 sa[j-1]=c & mask;
1381 c>>=bpe;
1382 }
1383 for (;j<kn;j++) {
1384 c+=sa[j]+ui*n[j];
1385 sa[j-1]=c & mask;
1386 c>>=bpe;
1387 }
1388 sa[j-1]=c & mask;
1389 }
1390
1391 if (!greater(n,sa))
1392 sub_(sa,n);
1393 copy_(x,sa);
1394}
1395
1396
1397
1398
1399//#############################################################################
1400//#############################################################################
1401//#############################################################################
1402//#############################################################################
1403//#############################################################################
1404//#############################################################################
1405//#############################################################################
1406
1407
1408
1409
1410
1411//#############################################################################
1412
1413Clipperz.Crypto.BigInt = function (aValue, aBase) {
1414 varbase;
1415 varvalue;
1416
1417 if (typeof(aValue) == 'object') {
1418 this._internalValue = aValue;
1419 } else {
1420 if (typeof(aValue) == 'undefined') {
1421 value = "0";
1422 } else {
1423 value = aValue + "";
1424 }
1425
1426 if (typeof(aBase) == 'undefined') {
1427 base = 10;
1428 } else {
1429 base = aBase;
1430 }
1431
1432 this._internalValue = str2bigInt(value, base, 1, 1);
1433 }
1434
1435 return this;
1436}
1437
1438//=============================================================================
1439
1440MochiKit.Base.update(Clipperz.Crypto.BigInt.prototype, {
1441
1442 'clone': function() {
1443 return new Clipperz.Crypto.BigInt(this.internalValue());
1444 },
1445
1446 //-------------------------------------------------------------------------
1447
1448 'internalValue': function () {
1449 return this._internalValue;
1450 },
1451
1452 //-------------------------------------------------------------------------
1453
1454 'isBigInt': true,
1455
1456 //-------------------------------------------------------------------------
1457
1458 'toString': function(aBase) {
1459 return this.asString(aBase);
1460 },
1461
1462 //-------------------------------------------------------------------------
1463
1464 'asString': function (aBase, minimumLength) {
1465 varresult;
1466 varbase;
1467
1468 if (typeof(aBase) == 'undefined') {
1469 base = 10;
1470 } else {
1471 base = aBase;
1472 }
1473
1474 result = bigInt2str(this.internalValue(), base).toLowerCase();
1475
1476 if ((typeof(minimumLength) != 'undefined') && (result.length < minimumLength)) {
1477 var i, c;
1478 c = (minimumLength - result.length);
1479 for (i=0; i<c; i++) {
1480 result = '0' + result;
1481 }
1482 }
1483
1484 return result;
1485 },
1486
1487 //-------------------------------------------------------------------------
1488
1489 'asByteArray': function() {
1490 return new Clipperz.ByteArray("0x" + this.asString(16), 16);
1491 },
1492
1493 //-------------------------------------------------------------------------
1494
1495 'equals': function (aValue) {
1496 var result;
1497
1498 if (aValue.isBigInt) {
1499 result = equals(this.internalValue(), aValue.internalValue());
1500 } else if (typeof(aValue) == "number") {
1501 result = equalsInt(this.internalValue(), aValue);
1502 } else {
1503 throw Clipperz.Crypt.BigInt.exception.UnknownType;
1504 }
1505
1506 return result;
1507 },
1508
1509 //-------------------------------------------------------------------------
1510
1511 'compare': function(aValue) {
1512/*
1513 var result;
1514 var thisAsString;
1515 var aValueAsString;
1516
1517 thisAsString = this.asString(10);
1518 aValueAsString = aValue.asString(10);
1519
1520 result = MochiKit.Base.compare(thisAsString.length, aValueAsString.length);
1521 if (result == 0) {
1522 result = MochiKit.Base.compare(thisAsString, aValueAsString);
1523 }
1524
1525 return result;
1526*/
1527 var result;
1528
1529 if (equals(this.internalValue(), aValue.internalValue())) {
1530 result = 0;
1531 } else if (greater(this.internalValue(), aValue.internalValue())) {
1532 result = 1;
1533 } else {
1534 result = -1;
1535 }
1536
1537 return result;
1538 },
1539
1540 //-------------------------------------------------------------------------
1541
1542 'add': function (aValue) {
1543 var result;
1544
1545 if (aValue.isBigInt) {
1546 result = add(this.internalValue(), aValue.internalValue());
1547 } else {
1548 result = addInt(this.internalValue(), aValue);
1549 }
1550
1551 return new Clipperz.Crypto.BigInt(result);
1552 },
1553
1554 //-------------------------------------------------------------------------
1555
1556 'subtract': function (aValue) {
1557 var result;
1558 var value;
1559
1560 if (aValue.isBigInt) {
1561 value = aValue;
1562 } else {
1563 value = new Clipperz.Crypto.BigInt(aValue);
1564 }
1565
1566 result = sub(this.internalValue(), value.internalValue());
1567
1568 return new Clipperz.Crypto.BigInt(result);
1569 },
1570
1571 //-------------------------------------------------------------------------
1572
1573 'multiply': function (aValue, aModule) {
1574 var result;
1575 var value;
1576
1577 if (aValue.isBigInt) {
1578 value = aValue;
1579 } else {
1580 value = new Clipperz.Crypto.BigInt(aValue);
1581 }
1582
1583 if (typeof(aModule) == 'undefined') {
1584 result = mult(this.internalValue(), value.internalValue());
1585 } else {
1586 if (greater(this.internalValue(), value.internalValue())) {
1587 result = multMod(this.internalValue(), value.internalValue(), aModule);
1588 } else {
1589 result = multMod(value.internalValue(), this.internalValue(), aModule);
1590 }
1591 }
1592
1593 return new Clipperz.Crypto.BigInt(result);
1594 },
1595
1596 //-------------------------------------------------------------------------
1597
1598 'module': function (aModule) {
1599 varresult;
1600 var module;
1601
1602 if (aModule.isBigInt) {
1603 module = aModule;
1604 } else {
1605 module = new Clipperz.Crypto.BigInt(aModule);
1606 }
1607
1608 result = mod(this.internalValue(), module.internalValue());
1609
1610 return new Clipperz.Crypto.BigInt(result);
1611 },
1612
1613 //-------------------------------------------------------------------------
1614
1615 'powerModule': function(aValue, aModule) {
1616 varresult;
1617 varvalue;
1618 var module;
1619
1620 if (aValue.isBigInt) {
1621 value = aValue;
1622 } else {
1623 value = new Clipperz.Crypto.BigInt(aValue);
1624 }
1625
1626 if (aModule.isBigInt) {
1627 module = aModule;
1628 } else {
1629 module = new Clipperz.Crypto.BigInt(aModule);
1630 }
1631
1632 if (aValue == -1) {
1633 result = inverseMod(this.internalValue(), module.internalValue());
1634 } else {
1635 result = powMod(this.internalValue(), value.internalValue(), module.internalValue());
1636 }
1637
1638 return new Clipperz.Crypto.BigInt(result);
1639 },
1640
1641 //-------------------------------------------------------------------------
1642
1643 'xor': function(aValue) {
1644 var result;
1645 varthisByteArray;
1646 var aValueByteArray;
1647 var xorArray;
1648
1649 thisByteArray = new Clipperz.ByteArray("0x" + this.asString(16), 16);
1650 aValueByteArray = new Clipperz.ByteArray("0x" + aValue.asString(16), 16);
1651 xorArray = thisByteArray.xorMergeWithBlock(aValueByteArray, 'right');
1652 result = new Clipperz.Crypto.BigInt(xorArray.toHexString(), 16);
1653
1654 return result;
1655 },
1656
1657 //-------------------------------------------------------------------------
1658
1659 'shiftLeft': function(aNumberOfBitsToShift) {
1660 var result;
1661 var internalResult;
1662 var wholeByteToShift;
1663 var bitsLeftToShift;
1664
1665 wholeByteToShift = Math.floor(aNumberOfBitsToShift / 8);
1666 bitsLeftToShift = aNumberOfBitsToShift % 8;
1667
1668 if (wholeByteToShift == 0) {
1669 internalResult = this.internalValue();
1670 } else {
1671 var hexValue;
1672 var i,c;
1673
1674 hexValue = this.asString(16);
1675 c = wholeByteToShift;
1676 for (i=0; i<c; i++) {
1677 hexValue += "00";
1678 }
1679 internalResult = str2bigInt(hexValue, 16, 1, 1);
1680 }
1681
1682 if (bitsLeftToShift > 0) {
1683 leftShift_(internalResult, bitsLeftToShift);
1684 }
1685 result = new Clipperz.Crypto.BigInt(internalResult);
1686
1687 return result;
1688 },
1689
1690 //-------------------------------------------------------------------------
1691
1692 'bitSize': function() {
1693 return bitSize(this.internalValue());
1694 },
1695
1696 //-------------------------------------------------------------------------
1697
1698 'isBitSet': function(aBitPosition) {
1699 var result;
1700
1701 if (this.asByteArray().bitAtIndex(aBitPosition) == 0) {
1702 result = false;
1703 } else {
1704 result = true;
1705 };
1706
1707 return result;
1708 },
1709
1710 //-------------------------------------------------------------------------
1711 __syntaxFix__: "syntax fix"
1712
1713});
1714
1715//#############################################################################
1716
1717Clipperz.Crypto.BigInt.randomPrime = function(aBitSize) {
1718 return new Clipperz.Crypto.BigInt(randTruePrime(aBitSize));
1719}
1720
1721//#############################################################################
1722//#############################################################################
1723
1724Clipperz.Crypto.BigInt.ZERO = new Clipperz.Crypto.BigInt(0);
1725
1726//#############################################################################
1727
1728Clipperz.Crypto.BigInt.equals = function(a, b) {
1729 return a.equals(b);
1730}
1731
1732Clipperz.Crypto.BigInt.add = function(a, b) {
1733 return a.add(b);
1734}
1735
1736Clipperz.Crypto.BigInt.subtract = function(a, b) {
1737 return a.subtract(b);
1738}
1739
1740Clipperz.Crypto.BigInt.multiply = function(a, b, module) {
1741 return a.multiply(b, module);
1742}
1743
1744Clipperz.Crypto.BigInt.module = function(a, module) {
1745 return a.module(module);
1746}
1747
1748Clipperz.Crypto.BigInt.powerModule = function(a, b, module) {
1749 return a.powerModule(b, module);
1750}
1751
1752Clipperz.Crypto.BigInt.exception = {
1753 UnknownType: new MochiKit.Base.NamedError("Clipperz.Crypto.BigInt.exception.UnknownType")
1754}