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