bigint.js 55 KB

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