bigint.js 49 KB

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