bigint.js 55 KB

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