crypto.js 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133
  1. ////////////////////////////////////////////////////////////////////////////////
  2. // base.js
  3. ////////////////////////////////////////////////////////////////////////////////
  4. // Copyright 2013 the V8 project authors. All rights reserved.
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following
  13. // disclaimer in the documentation and/or other materials provided
  14. // with the distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived
  17. // from this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. if(typeof(WScript) === "undefined")
  31. {
  32. var WScript = {
  33. Echo: print
  34. }
  35. }
  36. // Performance.now is used in latency benchmarks, the fallback is Date.now.
  37. var performance = performance || {};
  38. performance.now = (function() {
  39. return performance.now ||
  40. performance.mozNow ||
  41. performance.msNow ||
  42. performance.oNow ||
  43. performance.webkitNow ||
  44. Date.now;
  45. })();
  46. // Simple framework for running the benchmark suites and
  47. // computing a score based on the timing measurements.
  48. // A benchmark has a name (string) and a function that will be run to
  49. // do the performance measurement. The optional setup and tearDown
  50. // arguments are functions that will be invoked before and after
  51. // running the benchmark, but the running time of these functions will
  52. // not be accounted for in the benchmark score.
  53. function Benchmark(name, doWarmup, doDeterministic, deterministicIterations,
  54. run, setup, tearDown, rmsResult, minIterations) {
  55. this.name = name;
  56. this.doWarmup = doWarmup;
  57. this.doDeterministic = doDeterministic;
  58. this.deterministicIterations = deterministicIterations;
  59. this.run = run;
  60. this.Setup = setup ? setup : function() { };
  61. this.TearDown = tearDown ? tearDown : function() { };
  62. this.rmsResult = rmsResult ? rmsResult : null;
  63. this.minIterations = minIterations ? minIterations : 32;
  64. }
  65. // Benchmark results hold the benchmark and the measured time used to
  66. // run the benchmark. The benchmark score is computed later once a
  67. // full benchmark suite has run to completion. If latency is set to 0
  68. // then there is no latency score for this benchmark.
  69. function BenchmarkResult(benchmark, time, latency) {
  70. this.benchmark = benchmark;
  71. this.time = time;
  72. this.latency = latency;
  73. }
  74. // Automatically convert results to numbers. Used by the geometric
  75. // mean computation.
  76. BenchmarkResult.prototype.valueOf = function() {
  77. return this.time;
  78. }
  79. // Suites of benchmarks consist of a name and the set of benchmarks in
  80. // addition to the reference timing that the final score will be based
  81. // on. This way, all scores are relative to a reference run and higher
  82. // scores implies better performance.
  83. function BenchmarkSuite(name, reference, benchmarks) {
  84. this.name = name;
  85. this.reference = reference;
  86. this.benchmarks = benchmarks;
  87. BenchmarkSuite.suites.push(this);
  88. }
  89. // Keep track of all declared benchmark suites.
  90. BenchmarkSuite.suites = [];
  91. // Scores are not comparable across versions. Bump the version if
  92. // you're making changes that will affect that scores, e.g. if you add
  93. // a new benchmark or change an existing one.
  94. BenchmarkSuite.version = '9';
  95. // Defines global benchsuite running mode that overrides benchmark suite
  96. // behavior. Intended to be set by the benchmark driver. Undefined
  97. // values here allow a benchmark to define behaviour itself.
  98. BenchmarkSuite.config = {
  99. doWarmup: undefined,
  100. doDeterministic: undefined
  101. };
  102. // Override the alert function to throw an exception instead.
  103. alert = function(s) {
  104. throw "Alert called with argument: " + s;
  105. };
  106. // To make the benchmark results predictable, we replace Math.random
  107. // with a 100% deterministic alternative.
  108. BenchmarkSuite.ResetRNG = function() {
  109. Math.random = (function() {
  110. var seed = 49734321;
  111. return function() {
  112. // Robert Jenkins' 32 bit integer hash function.
  113. seed = ((seed + 0x7ed55d16) + (seed << 12)) & 0xffffffff;
  114. seed = ((seed ^ 0xc761c23c) ^ (seed >>> 19)) & 0xffffffff;
  115. seed = ((seed + 0x165667b1) + (seed << 5)) & 0xffffffff;
  116. seed = ((seed + 0xd3a2646c) ^ (seed << 9)) & 0xffffffff;
  117. seed = ((seed + 0xfd7046c5) + (seed << 3)) & 0xffffffff;
  118. seed = ((seed ^ 0xb55a4f09) ^ (seed >>> 16)) & 0xffffffff;
  119. return (seed & 0xfffffff) / 0x10000000;
  120. };
  121. })();
  122. }
  123. // Runs all registered benchmark suites and optionally yields between
  124. // each individual benchmark to avoid running for too long in the
  125. // context of browsers. Once done, the final score is reported to the
  126. // runner.
  127. BenchmarkSuite.RunSuites = function(runner, skipBenchmarks) {
  128. skipBenchmarks = typeof skipBenchmarks === 'undefined' ? [] : skipBenchmarks;
  129. var continuation = null;
  130. var suites = BenchmarkSuite.suites;
  131. var length = suites.length;
  132. BenchmarkSuite.scores = [];
  133. var index = 0;
  134. function RunStep() {
  135. while (continuation || index < length) {
  136. if (continuation) {
  137. continuation = continuation();
  138. } else {
  139. var suite = suites[index++];
  140. if (runner.NotifyStart) runner.NotifyStart(suite.name);
  141. if (skipBenchmarks.indexOf(suite.name) > -1) {
  142. suite.NotifySkipped(runner);
  143. } else {
  144. continuation = suite.RunStep(runner);
  145. }
  146. }
  147. if (continuation && typeof window != 'undefined' && window.setTimeout) {
  148. window.setTimeout(RunStep, 25);
  149. return;
  150. }
  151. }
  152. // show final result
  153. if (runner.NotifyScore) {
  154. var score = BenchmarkSuite.GeometricMean(BenchmarkSuite.scores);
  155. var formatted = BenchmarkSuite.FormatScore(100 * score);
  156. runner.NotifyScore(formatted);
  157. }
  158. }
  159. RunStep();
  160. }
  161. // Counts the total number of registered benchmarks. Useful for
  162. // showing progress as a percentage.
  163. BenchmarkSuite.CountBenchmarks = function() {
  164. var result = 0;
  165. var suites = BenchmarkSuite.suites;
  166. for (var i = 0; i < suites.length; i++) {
  167. result += suites[i].benchmarks.length;
  168. }
  169. return result;
  170. }
  171. // Computes the geometric mean of a set of numbers.
  172. BenchmarkSuite.GeometricMean = function(numbers) {
  173. var log = 0;
  174. for (var i = 0; i < numbers.length; i++) {
  175. log += Math.log(numbers[i]);
  176. }
  177. return Math.pow(Math.E, log / numbers.length);
  178. }
  179. // Computes the geometric mean of a set of throughput time measurements.
  180. BenchmarkSuite.GeometricMeanTime = function(measurements) {
  181. var log = 0;
  182. for (var i = 0; i < measurements.length; i++) {
  183. log += Math.log(measurements[i].time);
  184. }
  185. return Math.pow(Math.E, log / measurements.length);
  186. }
  187. // Computes the geometric mean of a set of rms measurements.
  188. BenchmarkSuite.GeometricMeanLatency = function(measurements) {
  189. var log = 0;
  190. var hasLatencyResult = false;
  191. for (var i = 0; i < measurements.length; i++) {
  192. if (measurements[i].latency != 0) {
  193. log += Math.log(measurements[i].latency);
  194. hasLatencyResult = true;
  195. }
  196. }
  197. if (hasLatencyResult) {
  198. return Math.pow(Math.E, log / measurements.length);
  199. } else {
  200. return 0;
  201. }
  202. }
  203. // Converts a score value to a string with at least three significant
  204. // digits.
  205. BenchmarkSuite.FormatScore = function(value) {
  206. if (value > 100) {
  207. return value.toFixed(0);
  208. } else {
  209. return value.toPrecision(3);
  210. }
  211. }
  212. // Notifies the runner that we're done running a single benchmark in
  213. // the benchmark suite. This can be useful to report progress.
  214. BenchmarkSuite.prototype.NotifyStep = function(result) {
  215. this.results.push(result);
  216. if (this.runner.NotifyStep) this.runner.NotifyStep(result.benchmark.name);
  217. }
  218. // Notifies the runner that we're done with running a suite and that
  219. // we have a result which can be reported to the user if needed.
  220. BenchmarkSuite.prototype.NotifyResult = function() {
  221. var mean = BenchmarkSuite.GeometricMeanTime(this.results);
  222. var score = this.reference[0] / mean;
  223. BenchmarkSuite.scores.push(score);
  224. if (this.runner.NotifyResult) {
  225. var formatted = BenchmarkSuite.FormatScore(100 * score);
  226. this.runner.NotifyResult(this.name, formatted);
  227. }
  228. if (this.reference.length == 2) {
  229. var meanLatency = BenchmarkSuite.GeometricMeanLatency(this.results);
  230. if (meanLatency != 0) {
  231. var scoreLatency = this.reference[1] / meanLatency;
  232. BenchmarkSuite.scores.push(scoreLatency);
  233. if (this.runner.NotifyResult) {
  234. var formattedLatency = BenchmarkSuite.FormatScore(100 * scoreLatency)
  235. this.runner.NotifyResult(this.name + "Latency", formattedLatency);
  236. }
  237. }
  238. }
  239. }
  240. BenchmarkSuite.prototype.NotifySkipped = function(runner) {
  241. BenchmarkSuite.scores.push(1); // push default reference score.
  242. if (runner.NotifyResult) {
  243. runner.NotifyResult(this.name, "Skipped");
  244. }
  245. }
  246. // Notifies the runner that running a benchmark resulted in an error.
  247. BenchmarkSuite.prototype.NotifyError = function(error) {
  248. if (this.runner.NotifyError) {
  249. this.runner.NotifyError(this.name, error);
  250. }
  251. if (this.runner.NotifyStep) {
  252. this.runner.NotifyStep(this.name);
  253. }
  254. }
  255. // Runs a single benchmark for at least a second and computes the
  256. // average time it takes to run a single iteration.
  257. BenchmarkSuite.prototype.RunSingleBenchmark = function(benchmark, data) {
  258. var config = BenchmarkSuite.config;
  259. var doWarmup = config.doWarmup !== undefined
  260. ? config.doWarmup
  261. : benchmark.doWarmup;
  262. var doDeterministic = config.doDeterministic !== undefined
  263. ? config.doDeterministic
  264. : benchmark.doDeterministic;
  265. function Measure(data) {
  266. var elapsed = 0;
  267. var start = new Date();
  268. // Run either for 1 second or for the number of iterations specified
  269. // by minIterations, depending on the config flag doDeterministic.
  270. for (var i = 0; (doDeterministic ?
  271. i<benchmark.deterministicIterations : elapsed < 1000); i++) {
  272. benchmark.run();
  273. elapsed = new Date() - start;
  274. }
  275. if (data != null) {
  276. data.runs += i;
  277. data.elapsed += elapsed;
  278. }
  279. }
  280. // Sets up data in order to skip or not the warmup phase.
  281. if (!doWarmup && data == null) {
  282. data = { runs: 0, elapsed: 0 };
  283. }
  284. if (data == null) {
  285. Measure(null);
  286. return { runs: 0, elapsed: 0 };
  287. } else {
  288. Measure(data);
  289. // If we've run too few iterations, we continue for another second.
  290. if (data.runs < benchmark.minIterations) return data;
  291. var usec = (data.elapsed * 1000) / data.runs;
  292. var rms = (benchmark.rmsResult != null) ? benchmark.rmsResult() : 0;
  293. this.NotifyStep(new BenchmarkResult(benchmark, usec, rms));
  294. return null;
  295. }
  296. }
  297. // This function starts running a suite, but stops between each
  298. // individual benchmark in the suite and returns a continuation
  299. // function which can be invoked to run the next benchmark. Once the
  300. // last benchmark has been executed, null is returned.
  301. BenchmarkSuite.prototype.RunStep = function(runner) {
  302. BenchmarkSuite.ResetRNG();
  303. this.results = [];
  304. this.runner = runner;
  305. var length = this.benchmarks.length;
  306. var index = 0;
  307. var suite = this;
  308. var data;
  309. // Run the setup, the actual benchmark, and the tear down in three
  310. // separate steps to allow the framework to yield between any of the
  311. // steps.
  312. function RunNextSetup() {
  313. if (index < length) {
  314. try {
  315. suite.benchmarks[index].Setup();
  316. } catch (e) {
  317. suite.NotifyError(e);
  318. return null;
  319. }
  320. return RunNextBenchmark;
  321. }
  322. suite.NotifyResult();
  323. return null;
  324. }
  325. function RunNextBenchmark() {
  326. try {
  327. data = suite.RunSingleBenchmark(suite.benchmarks[index], data);
  328. } catch (e) {
  329. suite.NotifyError(e);
  330. return null;
  331. }
  332. // If data is null, we're done with this benchmark.
  333. return (data == null) ? RunNextTearDown : RunNextBenchmark();
  334. }
  335. function RunNextTearDown() {
  336. try {
  337. suite.benchmarks[index++].TearDown();
  338. } catch (e) {
  339. suite.NotifyError(e);
  340. return null;
  341. }
  342. return RunNextSetup;
  343. }
  344. // Start out running the setup.
  345. return RunNextSetup();
  346. }
  347. /////////////////////////////////////////////////////////////
  348. // crypto.js
  349. /////////////////////////////////////////////////////////////
  350. /*
  351. * Copyright (c) 2003-2005 Tom Wu
  352. * All Rights Reserved.
  353. *
  354. * Permission is hereby granted, free of charge, to any person obtaining
  355. * a copy of this software and associated documentation files (the
  356. * "Software"), to deal in the Software without restriction, including
  357. * without limitation the rights to use, copy, modify, merge, publish,
  358. * distribute, sublicense, and/or sell copies of the Software, and to
  359. * permit persons to whom the Software is furnished to do so, subject to
  360. * the following conditions:
  361. *
  362. * The above copyright notice and this permission notice shall be
  363. * included in all copies or substantial portions of the Software.
  364. *
  365. * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
  366. * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
  367. * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
  368. *
  369. * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
  370. * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER
  371. * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF
  372. * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT
  373. * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  374. *
  375. * In addition, the following condition applies:
  376. *
  377. * All redistributions must retain an intact copy of this copyright notice
  378. * and disclaimer.
  379. */
  380. // The code has been adapted for use as a benchmark by Google.
  381. var Crypto = new BenchmarkSuite('Crypto', [266181], [
  382. new Benchmark("Encrypt", true, false, 3900, encrypt),
  383. new Benchmark("Decrypt", true, false, 220, decrypt)
  384. ]);
  385. // Basic JavaScript BN library - subset useful for RSA encryption.
  386. // Bits per digit
  387. var dbits;
  388. var BI_DB;
  389. var BI_DM;
  390. var BI_DV;
  391. var BI_FP;
  392. var BI_FV;
  393. var BI_F1;
  394. var BI_F2;
  395. // JavaScript engine analysis
  396. var canary = 0xdeadbeefcafe;
  397. var j_lm = ((canary&0xffffff)==0xefcafe);
  398. // (public) Constructor
  399. function BigInteger(a,b,c) {
  400. this.array = new Array();
  401. if(a != null)
  402. if("number" == typeof a) this.fromNumber(a,b,c);
  403. else if(b == null && "string" != typeof a) this.fromString(a,256);
  404. else this.fromString(a,b);
  405. }
  406. // return new, unset BigInteger
  407. function nbi() { return new BigInteger(null); }
  408. // am: Compute w_j += (x*this_i), propagate carries,
  409. // c is initial carry, returns final carry.
  410. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue
  411. // We need to select the fastest one that works in this environment.
  412. // am1: use a single mult and divide to get the high bits,
  413. // max digit bits should be 26 because
  414. // max internal value = 2*dvalue^2-2*dvalue (< 2^53)
  415. function am1(i,x,w,j,c,n) {
  416. var this_array = this.array;
  417. var w_array = w.array;
  418. while(--n >= 0) {
  419. var v = x*this_array[i++]+w_array[j]+c;
  420. c = Math.floor(v/0x4000000);
  421. w_array[j++] = v&0x3ffffff;
  422. }
  423. return c;
  424. }
  425. // am2 avoids a big mult-and-extract completely.
  426. // Max digit bits should be <= 30 because we do bitwise ops
  427. // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
  428. function am2(i,x,w,j,c,n) {
  429. var this_array = this.array;
  430. var w_array = w.array;
  431. var xl = x&0x7fff, xh = x>>15;
  432. while(--n >= 0) {
  433. var l = this_array[i]&0x7fff;
  434. var h = this_array[i++]>>15;
  435. var m = xh*l+h*xl;
  436. l = xl*l+((m&0x7fff)<<15)+w_array[j]+(c&0x3fffffff);
  437. c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);
  438. w_array[j++] = l&0x3fffffff;
  439. }
  440. return c;
  441. }
  442. // Alternately, set max digit bits to 28 since some
  443. // browsers slow down when dealing with 32-bit numbers.
  444. function am3(i,x,w,j,c,n) {
  445. var this_array = this.array;
  446. var w_array = w.array;
  447. var xl = x&0x3fff, xh = x>>14;
  448. while(--n >= 0) {
  449. var l = this_array[i]&0x3fff;
  450. var h = this_array[i++]>>14;
  451. var m = xh*l+h*xl;
  452. l = xl*l+((m&0x3fff)<<14)+w_array[j]+c;
  453. c = (l>>28)+(m>>14)+xh*h;
  454. w_array[j++] = l&0xfffffff;
  455. }
  456. return c;
  457. }
  458. // This is tailored to VMs with 2-bit tagging. It makes sure
  459. // that all the computations stay within the 29 bits available.
  460. function am4(i,x,w,j,c,n) {
  461. var this_array = this.array;
  462. var w_array = w.array;
  463. var xl = x&0x1fff, xh = x>>13;
  464. while(--n >= 0) {
  465. var l = this_array[i]&0x1fff;
  466. var h = this_array[i++]>>13;
  467. var m = xh*l+h*xl;
  468. l = xl*l+((m&0x1fff)<<13)+w_array[j]+c;
  469. c = (l>>26)+(m>>13)+xh*h;
  470. w_array[j++] = l&0x3ffffff;
  471. }
  472. return c;
  473. }
  474. // am3/28 is best for SM, Rhino, but am4/26 is best for v8.
  475. // Kestrel (Opera 9.5) gets its best result with am4/26.
  476. // IE7 does 9% better with am3/28 than with am4/26.
  477. // Firefox (SM) gets 10% faster with am3/28 than with am4/26.
  478. setupEngine = function(fn, bits) {
  479. BigInteger.prototype.am = fn;
  480. dbits = bits;
  481. BI_DB = dbits;
  482. BI_DM = ((1<<dbits)-1);
  483. BI_DV = (1<<dbits);
  484. BI_FP = 52;
  485. BI_FV = Math.pow(2,BI_FP);
  486. BI_F1 = BI_FP-dbits;
  487. BI_F2 = 2*dbits-BI_FP;
  488. }
  489. // Digit conversions
  490. var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
  491. var BI_RC = new Array();
  492. var rr,vv;
  493. rr = "0".charCodeAt(0);
  494. for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv;
  495. rr = "a".charCodeAt(0);
  496. for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
  497. rr = "A".charCodeAt(0);
  498. for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
  499. function int2char(n) { return BI_RM.charAt(n); }
  500. function intAt(s,i) {
  501. var c = BI_RC[s.charCodeAt(i)];
  502. return (c==null)?-1:c;
  503. }
  504. // (protected) copy this to r
  505. function bnpCopyTo(r) {
  506. var this_array = this.array;
  507. var r_array = r.array;
  508. for(var i = this.t-1; i >= 0; --i) r_array[i] = this_array[i];
  509. r.t = this.t;
  510. r.s = this.s;
  511. }
  512. // (protected) set from integer value x, -DV <= x < DV
  513. function bnpFromInt(x) {
  514. var this_array = this.array;
  515. this.t = 1;
  516. this.s = (x<0)?-1:0;
  517. if(x > 0) this_array[0] = x;
  518. else if(x < -1) this_array[0] = x+DV;
  519. else this.t = 0;
  520. }
  521. // return bigint initialized to value
  522. function nbv(i) { var r = nbi(); r.fromInt(i); return r; }
  523. // (protected) set from string and radix
  524. function bnpFromString(s,b) {
  525. var this_array = this.array;
  526. var k;
  527. if(b == 16) k = 4;
  528. else if(b == 8) k = 3;
  529. else if(b == 256) k = 8; // byte array
  530. else if(b == 2) k = 1;
  531. else if(b == 32) k = 5;
  532. else if(b == 4) k = 2;
  533. else { this.fromRadix(s,b); return; }
  534. this.t = 0;
  535. this.s = 0;
  536. var i = s.length, mi = false, sh = 0;
  537. while(--i >= 0) {
  538. var x = (k==8)?s[i]&0xff:intAt(s,i);
  539. if(x < 0) {
  540. if(s.charAt(i) == "-") mi = true;
  541. continue;
  542. }
  543. mi = false;
  544. if(sh == 0)
  545. this_array[this.t++] = x;
  546. else if(sh+k > BI_DB) {
  547. this_array[this.t-1] |= (x&((1<<(BI_DB-sh))-1))<<sh;
  548. this_array[this.t++] = (x>>(BI_DB-sh));
  549. }
  550. else
  551. this_array[this.t-1] |= x<<sh;
  552. sh += k;
  553. if(sh >= BI_DB) sh -= BI_DB;
  554. }
  555. if(k == 8 && (s[0]&0x80) != 0) {
  556. this.s = -1;
  557. if(sh > 0) this_array[this.t-1] |= ((1<<(BI_DB-sh))-1)<<sh;
  558. }
  559. this.clamp();
  560. if(mi) BigInteger.ZERO.subTo(this,this);
  561. }
  562. // (protected) clamp off excess high words
  563. function bnpClamp() {
  564. var this_array = this.array;
  565. var c = this.s&BI_DM;
  566. while(this.t > 0 && this_array[this.t-1] == c) --this.t;
  567. }
  568. // (public) return string representation in given radix
  569. function bnToString(b) {
  570. var this_array = this.array;
  571. if(this.s < 0) return "-"+this.negate().toString(b);
  572. var k;
  573. if(b == 16) k = 4;
  574. else if(b == 8) k = 3;
  575. else if(b == 2) k = 1;
  576. else if(b == 32) k = 5;
  577. else if(b == 4) k = 2;
  578. else return this.toRadix(b);
  579. var km = (1<<k)-1, d, m = false, r = "", i = this.t;
  580. var p = BI_DB-(i*BI_DB)%k;
  581. if(i-- > 0) {
  582. if(p < BI_DB && (d = this_array[i]>>p) > 0) { m = true; r = int2char(d); }
  583. while(i >= 0) {
  584. if(p < k) {
  585. d = (this_array[i]&((1<<p)-1))<<(k-p);
  586. d |= this_array[--i]>>(p+=BI_DB-k);
  587. }
  588. else {
  589. d = (this_array[i]>>(p-=k))&km;
  590. if(p <= 0) { p += BI_DB; --i; }
  591. }
  592. if(d > 0) m = true;
  593. if(m) r += int2char(d);
  594. }
  595. }
  596. return m?r:"0";
  597. }
  598. // (public) -this
  599. function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }
  600. // (public) |this|
  601. function bnAbs() { return (this.s<0)?this.negate():this; }
  602. // (public) return + if this > a, - if this < a, 0 if equal
  603. function bnCompareTo(a) {
  604. var this_array = this.array;
  605. var a_array = a.array;
  606. var r = this.s-a.s;
  607. if(r != 0) return r;
  608. var i = this.t;
  609. r = i-a.t;
  610. if(r != 0) return r;
  611. while(--i >= 0) if((r=this_array[i]-a_array[i]) != 0) return r;
  612. return 0;
  613. }
  614. // returns bit length of the integer x
  615. function nbits(x) {
  616. var r = 1, t;
  617. if((t=x>>>16) != 0) { x = t; r += 16; }
  618. if((t=x>>8) != 0) { x = t; r += 8; }
  619. if((t=x>>4) != 0) { x = t; r += 4; }
  620. if((t=x>>2) != 0) { x = t; r += 2; }
  621. if((t=x>>1) != 0) { x = t; r += 1; }
  622. return r;
  623. }
  624. // (public) return the number of bits in "this"
  625. function bnBitLength() {
  626. var this_array = this.array;
  627. if(this.t <= 0) return 0;
  628. return BI_DB*(this.t-1)+nbits(this_array[this.t-1]^(this.s&BI_DM));
  629. }
  630. // (protected) r = this << n*DB
  631. function bnpDLShiftTo(n,r) {
  632. var this_array = this.array;
  633. var r_array = r.array;
  634. var i;
  635. for(i = this.t-1; i >= 0; --i) r_array[i+n] = this_array[i];
  636. for(i = n-1; i >= 0; --i) r_array[i] = 0;
  637. r.t = this.t+n;
  638. r.s = this.s;
  639. }
  640. // (protected) r = this >> n*DB
  641. function bnpDRShiftTo(n,r) {
  642. var this_array = this.array;
  643. var r_array = r.array;
  644. for(var i = n; i < this.t; ++i) r_array[i-n] = this_array[i];
  645. r.t = Math.max(this.t-n,0);
  646. r.s = this.s;
  647. }
  648. // (protected) r = this << n
  649. function bnpLShiftTo(n,r) {
  650. var this_array = this.array;
  651. var r_array = r.array;
  652. var bs = n%BI_DB;
  653. var cbs = BI_DB-bs;
  654. var bm = (1<<cbs)-1;
  655. var ds = Math.floor(n/BI_DB), c = (this.s<<bs)&BI_DM, i;
  656. for(i = this.t-1; i >= 0; --i) {
  657. r_array[i+ds+1] = (this_array[i]>>cbs)|c;
  658. c = (this_array[i]&bm)<<bs;
  659. }
  660. for(i = ds-1; i >= 0; --i) r_array[i] = 0;
  661. r_array[ds] = c;
  662. r.t = this.t+ds+1;
  663. r.s = this.s;
  664. r.clamp();
  665. }
  666. // (protected) r = this >> n
  667. function bnpRShiftTo(n,r) {
  668. var this_array = this.array;
  669. var r_array = r.array;
  670. r.s = this.s;
  671. var ds = Math.floor(n/BI_DB);
  672. if(ds >= this.t) { r.t = 0; return; }
  673. var bs = n%BI_DB;
  674. var cbs = BI_DB-bs;
  675. var bm = (1<<bs)-1;
  676. r_array[0] = this_array[ds]>>bs;
  677. for(var i = ds+1; i < this.t; ++i) {
  678. r_array[i-ds-1] |= (this_array[i]&bm)<<cbs;
  679. r_array[i-ds] = this_array[i]>>bs;
  680. }
  681. if(bs > 0) r_array[this.t-ds-1] |= (this.s&bm)<<cbs;
  682. r.t = this.t-ds;
  683. r.clamp();
  684. }
  685. // (protected) r = this - a
  686. function bnpSubTo(a,r) {
  687. var this_array = this.array;
  688. var r_array = r.array;
  689. var a_array = a.array;
  690. var i = 0, c = 0, m = Math.min(a.t,this.t);
  691. while(i < m) {
  692. c += this_array[i]-a_array[i];
  693. r_array[i++] = c&BI_DM;
  694. c >>= BI_DB;
  695. }
  696. if(a.t < this.t) {
  697. c -= a.s;
  698. while(i < this.t) {
  699. c += this_array[i];
  700. r_array[i++] = c&BI_DM;
  701. c >>= BI_DB;
  702. }
  703. c += this.s;
  704. }
  705. else {
  706. c += this.s;
  707. while(i < a.t) {
  708. c -= a_array[i];
  709. r_array[i++] = c&BI_DM;
  710. c >>= BI_DB;
  711. }
  712. c -= a.s;
  713. }
  714. r.s = (c<0)?-1:0;
  715. if(c < -1) r_array[i++] = BI_DV+c;
  716. else if(c > 0) r_array[i++] = c;
  717. r.t = i;
  718. r.clamp();
  719. }
  720. // (protected) r = this * a, r != this,a (HAC 14.12)
  721. // "this" should be the larger one if appropriate.
  722. function bnpMultiplyTo(a,r) {
  723. var this_array = this.array;
  724. var r_array = r.array;
  725. var x = this.abs(), y = a.abs();
  726. var y_array = y.array;
  727. var i = x.t;
  728. r.t = i+y.t;
  729. while(--i >= 0) r_array[i] = 0;
  730. for(i = 0; i < y.t; ++i) r_array[i+x.t] = x.am(0,y_array[i],r,i,0,x.t);
  731. r.s = 0;
  732. r.clamp();
  733. if(this.s != a.s) BigInteger.ZERO.subTo(r,r);
  734. }
  735. // (protected) r = this^2, r != this (HAC 14.16)
  736. function bnpSquareTo(r) {
  737. var x = this.abs();
  738. var x_array = x.array;
  739. var r_array = r.array;
  740. var i = r.t = 2*x.t;
  741. while(--i >= 0) r_array[i] = 0;
  742. for(i = 0; i < x.t-1; ++i) {
  743. var c = x.am(i,x_array[i],r,2*i,0,1);
  744. if((r_array[i+x.t]+=x.am(i+1,2*x_array[i],r,2*i+1,c,x.t-i-1)) >= BI_DV) {
  745. r_array[i+x.t] -= BI_DV;
  746. r_array[i+x.t+1] = 1;
  747. }
  748. }
  749. if(r.t > 0) r_array[r.t-1] += x.am(i,x_array[i],r,2*i,0,1);
  750. r.s = 0;
  751. r.clamp();
  752. }
  753. // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
  754. // r != q, this != m. q or r may be null.
  755. function bnpDivRemTo(m,q,r) {
  756. var pm = m.abs();
  757. if(pm.t <= 0) return;
  758. var pt = this.abs();
  759. if(pt.t < pm.t) {
  760. if(q != null) q.fromInt(0);
  761. if(r != null) this.copyTo(r);
  762. return;
  763. }
  764. if(r == null) r = nbi();
  765. var y = nbi(), ts = this.s, ms = m.s;
  766. var pm_array = pm.array;
  767. var nsh = BI_DB-nbits(pm_array[pm.t-1]); // normalize modulus
  768. if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); }
  769. else { pm.copyTo(y); pt.copyTo(r); }
  770. var ys = y.t;
  771. var y_array = y.array;
  772. var y0 = y_array[ys-1];
  773. if(y0 == 0) return;
  774. var yt = y0*(1<<BI_F1)+((ys>1)?y_array[ys-2]>>BI_F2:0);
  775. var d1 = BI_FV/yt, d2 = (1<<BI_F1)/yt, e = 1<<BI_F2;
  776. var i = r.t, j = i-ys, t = (q==null)?nbi():q;
  777. y.dlShiftTo(j,t);
  778. var r_array = r.array;
  779. if(r.compareTo(t) >= 0) {
  780. r_array[r.t++] = 1;
  781. r.subTo(t,r);
  782. }
  783. BigInteger.ONE.dlShiftTo(ys,t);
  784. t.subTo(y,y); // "negative" y so we can replace sub with am later
  785. while(y.t < ys) y_array[y.t++] = 0;
  786. while(--j >= 0) {
  787. // Estimate quotient digit
  788. var qd = (r_array[--i]==y0)?BI_DM:Math.floor(r_array[i]*d1+(r_array[i-1]+e)*d2);
  789. if((r_array[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out
  790. y.dlShiftTo(j,t);
  791. r.subTo(t,r);
  792. while(r_array[i] < --qd) r.subTo(t,r);
  793. }
  794. }
  795. if(q != null) {
  796. r.drShiftTo(ys,q);
  797. if(ts != ms) BigInteger.ZERO.subTo(q,q);
  798. }
  799. r.t = ys;
  800. r.clamp();
  801. if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder
  802. if(ts < 0) BigInteger.ZERO.subTo(r,r);
  803. }
  804. // (public) this mod a
  805. function bnMod(a) {
  806. var r = nbi();
  807. this.abs().divRemTo(a,null,r);
  808. if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r);
  809. return r;
  810. }
  811. // Modular reduction using "classic" algorithm
  812. function Classic(m) { this.m = m; }
  813. function cConvert(x) {
  814. if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);
  815. else return x;
  816. }
  817. function cRevert(x) { return x; }
  818. function cReduce(x) { x.divRemTo(this.m,null,x); }
  819. function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
  820. function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
  821. Classic.prototype.convert = cConvert;
  822. Classic.prototype.revert = cRevert;
  823. Classic.prototype.reduce = cReduce;
  824. Classic.prototype.mulTo = cMulTo;
  825. Classic.prototype.sqrTo = cSqrTo;
  826. // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
  827. // justification:
  828. // xy == 1 (mod m)
  829. // xy = 1+km
  830. // xy(2-xy) = (1+km)(1-km)
  831. // x[y(2-xy)] = 1-k^2m^2
  832. // x[y(2-xy)] == 1 (mod m^2)
  833. // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
  834. // should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
  835. // JS multiply "overflows" differently from C/C++, so care is needed here.
  836. function bnpInvDigit() {
  837. var this_array = this.array;
  838. if(this.t < 1) return 0;
  839. var x = this_array[0];
  840. if((x&1) == 0) return 0;
  841. var y = x&3; // y == 1/x mod 2^2
  842. y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4
  843. y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8
  844. y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16
  845. // last step - calculate inverse mod DV directly;
  846. // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
  847. y = (y*(2-x*y%BI_DV))%BI_DV; // y == 1/x mod 2^dbits
  848. // we really want the negative inverse, and -DV < y < DV
  849. return (y>0)?BI_DV-y:-y;
  850. }
  851. // Montgomery reduction
  852. function Montgomery(m) {
  853. this.m = m;
  854. this.mp = m.invDigit();
  855. this.mpl = this.mp&0x7fff;
  856. this.mph = this.mp>>15;
  857. this.um = (1<<(BI_DB-15))-1;
  858. this.mt2 = 2*m.t;
  859. }
  860. // xR mod m
  861. function montConvert(x) {
  862. var r = nbi();
  863. x.abs().dlShiftTo(this.m.t,r);
  864. r.divRemTo(this.m,null,r);
  865. if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);
  866. return r;
  867. }
  868. // x/R mod m
  869. function montRevert(x) {
  870. var r = nbi();
  871. x.copyTo(r);
  872. this.reduce(r);
  873. return r;
  874. }
  875. // x = x/R mod m (HAC 14.32)
  876. function montReduce(x) {
  877. var x_array = x.array;
  878. while(x.t <= this.mt2) // pad x so am has enough room later
  879. x_array[x.t++] = 0;
  880. for(var i = 0; i < this.m.t; ++i) {
  881. // faster way of calculating u0 = x[i]*mp mod DV
  882. var j = x_array[i]&0x7fff;
  883. var u0 = (j*this.mpl+(((j*this.mph+(x_array[i]>>15)*this.mpl)&this.um)<<15))&BI_DM;
  884. // use am to combine the multiply-shift-add into one call
  885. j = i+this.m.t;
  886. x_array[j] += this.m.am(0,u0,x,i,0,this.m.t);
  887. // propagate carry
  888. while(x_array[j] >= BI_DV) { x_array[j] -= BI_DV; x_array[++j]++; }
  889. }
  890. x.clamp();
  891. x.drShiftTo(this.m.t,x);
  892. if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
  893. }
  894. // r = "x^2/R mod m"; x != r
  895. function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
  896. // r = "xy/R mod m"; x,y != r
  897. function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
  898. Montgomery.prototype.convert = montConvert;
  899. Montgomery.prototype.revert = montRevert;
  900. Montgomery.prototype.reduce = montReduce;
  901. Montgomery.prototype.mulTo = montMulTo;
  902. Montgomery.prototype.sqrTo = montSqrTo;
  903. // (protected) true iff this is even
  904. function bnpIsEven() {
  905. var this_array = this.array;
  906. return ((this.t>0)?(this_array[0]&1):this.s) == 0;
  907. }
  908. // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
  909. function bnpExp(e,z) {
  910. if(e > 0xffffffff || e < 1) return BigInteger.ONE;
  911. var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;
  912. g.copyTo(r);
  913. while(--i >= 0) {
  914. z.sqrTo(r,r2);
  915. if((e&(1<<i)) > 0) z.mulTo(r2,g,r);
  916. else { var t = r; r = r2; r2 = t; }
  917. }
  918. return z.revert(r);
  919. }
  920. // (public) this^e % m, 0 <= e < 2^32
  921. function bnModPowInt(e,m) {
  922. var z;
  923. if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);
  924. return this.exp(e,z);
  925. }
  926. // protected
  927. BigInteger.prototype.copyTo = bnpCopyTo;
  928. BigInteger.prototype.fromInt = bnpFromInt;
  929. BigInteger.prototype.fromString = bnpFromString;
  930. BigInteger.prototype.clamp = bnpClamp;
  931. BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
  932. BigInteger.prototype.drShiftTo = bnpDRShiftTo;
  933. BigInteger.prototype.lShiftTo = bnpLShiftTo;
  934. BigInteger.prototype.rShiftTo = bnpRShiftTo;
  935. BigInteger.prototype.subTo = bnpSubTo;
  936. BigInteger.prototype.multiplyTo = bnpMultiplyTo;
  937. BigInteger.prototype.squareTo = bnpSquareTo;
  938. BigInteger.prototype.divRemTo = bnpDivRemTo;
  939. BigInteger.prototype.invDigit = bnpInvDigit;
  940. BigInteger.prototype.isEven = bnpIsEven;
  941. BigInteger.prototype.exp = bnpExp;
  942. // public
  943. BigInteger.prototype.toString = bnToString;
  944. BigInteger.prototype.negate = bnNegate;
  945. BigInteger.prototype.abs = bnAbs;
  946. BigInteger.prototype.compareTo = bnCompareTo;
  947. BigInteger.prototype.bitLength = bnBitLength;
  948. BigInteger.prototype.mod = bnMod;
  949. BigInteger.prototype.modPowInt = bnModPowInt;
  950. // "constants"
  951. BigInteger.ZERO = nbv(0);
  952. BigInteger.ONE = nbv(1);
  953. // Copyright (c) 2005 Tom Wu
  954. // All Rights Reserved.
  955. // See "LICENSE" for details.
  956. // Extended JavaScript BN functions, required for RSA private ops.
  957. // (public)
  958. function bnClone() { var r = nbi(); this.copyTo(r); return r; }
  959. // (public) return value as integer
  960. function bnIntValue() {
  961. var this_array = this.array;
  962. if(this.s < 0) {
  963. if(this.t == 1) return this_array[0]-BI_DV;
  964. else if(this.t == 0) return -1;
  965. }
  966. else if(this.t == 1) return this_array[0];
  967. else if(this.t == 0) return 0;
  968. // assumes 16 < DB < 32
  969. return ((this_array[1]&((1<<(32-BI_DB))-1))<<BI_DB)|this_array[0];
  970. }
  971. // (public) return value as byte
  972. function bnByteValue() {
  973. var this_array = this.array;
  974. return (this.t==0)?this.s:(this_array[0]<<24)>>24;
  975. }
  976. // (public) return value as short (assumes DB>=16)
  977. function bnShortValue() {
  978. var this_array = this.array;
  979. return (this.t==0)?this.s:(this_array[0]<<16)>>16;
  980. }
  981. // (protected) return x s.t. r^x < DV
  982. function bnpChunkSize(r) { return Math.floor(Math.LN2*BI_DB/Math.log(r)); }
  983. // (public) 0 if this == 0, 1 if this > 0
  984. function bnSigNum() {
  985. var this_array = this.array;
  986. if(this.s < 0) return -1;
  987. else if(this.t <= 0 || (this.t == 1 && this_array[0] <= 0)) return 0;
  988. else return 1;
  989. }
  990. // (protected) convert to radix string
  991. function bnpToRadix(b) {
  992. if(b == null) b = 10;
  993. if(this.signum() == 0 || b < 2 || b > 36) return "0";
  994. var cs = this.chunkSize(b);
  995. var a = Math.pow(b,cs);
  996. var d = nbv(a), y = nbi(), z = nbi(), r = "";
  997. this.divRemTo(d,y,z);
  998. while(y.signum() > 0) {
  999. r = (a+z.intValue()).toString(b).substr(1) + r;
  1000. y.divRemTo(d,y,z);
  1001. }
  1002. return z.intValue().toString(b) + r;
  1003. }
  1004. // (protected) convert from radix string
  1005. function bnpFromRadix(s,b) {
  1006. this.fromInt(0);
  1007. if(b == null) b = 10;
  1008. var cs = this.chunkSize(b);
  1009. var d = Math.pow(b,cs), mi = false, j = 0, w = 0;
  1010. for(var i = 0; i < s.length; ++i) {
  1011. var x = intAt(s,i);
  1012. if(x < 0) {
  1013. if(s.charAt(i) == "-" && this.signum() == 0) mi = true;
  1014. continue;
  1015. }
  1016. w = b*w+x;
  1017. if(++j >= cs) {
  1018. this.dMultiply(d);
  1019. this.dAddOffset(w,0);
  1020. j = 0;
  1021. w = 0;
  1022. }
  1023. }
  1024. if(j > 0) {
  1025. this.dMultiply(Math.pow(b,j));
  1026. this.dAddOffset(w,0);
  1027. }
  1028. if(mi) BigInteger.ZERO.subTo(this,this);
  1029. }
  1030. // (protected) alternate constructor
  1031. function bnpFromNumber(a,b,c) {
  1032. if("number" == typeof b) {
  1033. // new BigInteger(int,int,RNG)
  1034. if(a < 2) this.fromInt(1);
  1035. else {
  1036. this.fromNumber(a,c);
  1037. if(!this.testBit(a-1)) // force MSB set
  1038. this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);
  1039. if(this.isEven()) this.dAddOffset(1,0); // force odd
  1040. while(!this.isProbablePrime(b)) {
  1041. this.dAddOffset(2,0);
  1042. if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this);
  1043. }
  1044. }
  1045. }
  1046. else {
  1047. // new BigInteger(int,RNG)
  1048. var x = new Array(), t = a&7;
  1049. x.length = (a>>3)+1;
  1050. b.nextBytes(x);
  1051. if(t > 0) x[0] &= ((1<<t)-1); else x[0] = 0;
  1052. this.fromString(x,256);
  1053. }
  1054. }
  1055. // (public) convert to bigendian byte array
  1056. function bnToByteArray() {
  1057. var this_array = this.array;
  1058. var i = this.t, r = new Array();
  1059. r[0] = this.s;
  1060. var p = BI_DB-(i*BI_DB)%8, d, k = 0;
  1061. if(i-- > 0) {
  1062. if(p < BI_DB && (d = this_array[i]>>p) != (this.s&BI_DM)>>p)
  1063. r[k++] = d|(this.s<<(BI_DB-p));
  1064. while(i >= 0) {
  1065. if(p < 8) {
  1066. d = (this_array[i]&((1<<p)-1))<<(8-p);
  1067. d |= this_array[--i]>>(p+=BI_DB-8);
  1068. }
  1069. else {
  1070. d = (this_array[i]>>(p-=8))&0xff;
  1071. if(p <= 0) { p += BI_DB; --i; }
  1072. }
  1073. if((d&0x80) != 0) d |= -256;
  1074. if(k == 0 && (this.s&0x80) != (d&0x80)) ++k;
  1075. if(k > 0 || d != this.s) r[k++] = d;
  1076. }
  1077. }
  1078. return r;
  1079. }
  1080. function bnEquals(a) { return(this.compareTo(a)==0); }
  1081. function bnMin(a) { return(this.compareTo(a)<0)?this:a; }
  1082. function bnMax(a) { return(this.compareTo(a)>0)?this:a; }
  1083. // (protected) r = this op a (bitwise)
  1084. function bnpBitwiseTo(a,op,r) {
  1085. var this_array = this.array;
  1086. var a_array = a.array;
  1087. var r_array = r.array;
  1088. var i, f, m = Math.min(a.t,this.t);
  1089. for(i = 0; i < m; ++i) r_array[i] = op(this_array[i],a_array[i]);
  1090. if(a.t < this.t) {
  1091. f = a.s&BI_DM;
  1092. for(i = m; i < this.t; ++i) r_array[i] = op(this_array[i],f);
  1093. r.t = this.t;
  1094. }
  1095. else {
  1096. f = this.s&BI_DM;
  1097. for(i = m; i < a.t; ++i) r_array[i] = op(f,a_array[i]);
  1098. r.t = a.t;
  1099. }
  1100. r.s = op(this.s,a.s);
  1101. r.clamp();
  1102. }
  1103. // (public) this & a
  1104. function op_and(x,y) { return x&y; }
  1105. function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }
  1106. // (public) this | a
  1107. function op_or(x,y) { return x|y; }
  1108. function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }
  1109. // (public) this ^ a
  1110. function op_xor(x,y) { return x^y; }
  1111. function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }
  1112. // (public) this & ~a
  1113. function op_andnot(x,y) { return x&~y; }
  1114. function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; }
  1115. // (public) ~this
  1116. function bnNot() {
  1117. var this_array = this.array;
  1118. var r = nbi();
  1119. var r_array = r.array;
  1120. for(var i = 0; i < this.t; ++i) r_array[i] = BI_DM&~this_array[i];
  1121. r.t = this.t;
  1122. r.s = ~this.s;
  1123. return r;
  1124. }
  1125. // (public) this << n
  1126. function bnShiftLeft(n) {
  1127. var r = nbi();
  1128. if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r);
  1129. return r;
  1130. }
  1131. // (public) this >> n
  1132. function bnShiftRight(n) {
  1133. var r = nbi();
  1134. if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r);
  1135. return r;
  1136. }
  1137. // return index of lowest 1-bit in x, x < 2^31
  1138. function lbit(x) {
  1139. if(x == 0) return -1;
  1140. var r = 0;
  1141. if((x&0xffff) == 0) { x >>= 16; r += 16; }
  1142. if((x&0xff) == 0) { x >>= 8; r += 8; }
  1143. if((x&0xf) == 0) { x >>= 4; r += 4; }
  1144. if((x&3) == 0) { x >>= 2; r += 2; }
  1145. if((x&1) == 0) ++r;
  1146. return r;
  1147. }
  1148. // (public) returns index of lowest 1-bit (or -1 if none)
  1149. function bnGetLowestSetBit() {
  1150. var this_array = this.array;
  1151. for(var i = 0; i < this.t; ++i)
  1152. if(this_array[i] != 0) return i*BI_DB+lbit(this_array[i]);
  1153. if(this.s < 0) return this.t*BI_DB;
  1154. return -1;
  1155. }
  1156. // return number of 1 bits in x
  1157. function cbit(x) {
  1158. var r = 0;
  1159. while(x != 0) { x &= x-1; ++r; }
  1160. return r;
  1161. }
  1162. // (public) return number of set bits
  1163. function bnBitCount() {
  1164. var r = 0, x = this.s&BI_DM;
  1165. for(var i = 0; i < this.t; ++i) r += cbit(this_array[i]^x);
  1166. return r;
  1167. }
  1168. // (public) true iff nth bit is set
  1169. function bnTestBit(n) {
  1170. var this_array = this.array;
  1171. var j = Math.floor(n/BI_DB);
  1172. if(j >= this.t) return(this.s!=0);
  1173. return((this_array[j]&(1<<(n%BI_DB)))!=0);
  1174. }
  1175. // (protected) this op (1<<n)
  1176. function bnpChangeBit(n,op) {
  1177. var r = BigInteger.ONE.shiftLeft(n);
  1178. this.bitwiseTo(r,op,r);
  1179. return r;
  1180. }
  1181. // (public) this | (1<<n)
  1182. function bnSetBit(n) { return this.changeBit(n,op_or); }
  1183. // (public) this & ~(1<<n)
  1184. function bnClearBit(n) { return this.changeBit(n,op_andnot); }
  1185. // (public) this ^ (1<<n)
  1186. function bnFlipBit(n) { return this.changeBit(n,op_xor); }
  1187. // (protected) r = this + a
  1188. function bnpAddTo(a,r) {
  1189. var this_array = this.array;
  1190. var a_array = a.array;
  1191. var r_array = r.array;
  1192. var i = 0, c = 0, m = Math.min(a.t,this.t);
  1193. while(i < m) {
  1194. c += this_array[i]+a_array[i];
  1195. r_array[i++] = c&BI_DM;
  1196. c >>= BI_DB;
  1197. }
  1198. if(a.t < this.t) {
  1199. c += a.s;
  1200. while(i < this.t) {
  1201. c += this_array[i];
  1202. r_array[i++] = c&BI_DM;
  1203. c >>= BI_DB;
  1204. }
  1205. c += this.s;
  1206. }
  1207. else {
  1208. c += this.s;
  1209. while(i < a.t) {
  1210. c += a_array[i];
  1211. r_array[i++] = c&BI_DM;
  1212. c >>= BI_DB;
  1213. }
  1214. c += a.s;
  1215. }
  1216. r.s = (c<0)?-1:0;
  1217. if(c > 0) r_array[i++] = c;
  1218. else if(c < -1) r_array[i++] = BI_DV+c;
  1219. r.t = i;
  1220. r.clamp();
  1221. }
  1222. // (public) this + a
  1223. function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }
  1224. // (public) this - a
  1225. function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }
  1226. // (public) this * a
  1227. function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }
  1228. // (public) this / a
  1229. function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }
  1230. // (public) this % a
  1231. function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; }
  1232. // (public) [this/a,this%a]
  1233. function bnDivideAndRemainder(a) {
  1234. var q = nbi(), r = nbi();
  1235. this.divRemTo(a,q,r);
  1236. return new Array(q,r);
  1237. }
  1238. // (protected) this *= n, this >= 0, 1 < n < DV
  1239. function bnpDMultiply(n) {
  1240. var this_array = this.array;
  1241. this_array[this.t] = this.am(0,n-1,this,0,0,this.t);
  1242. ++this.t;
  1243. this.clamp();
  1244. }
  1245. // (protected) this += n << w words, this >= 0
  1246. function bnpDAddOffset(n,w) {
  1247. var this_array = this.array;
  1248. while(this.t <= w) this_array[this.t++] = 0;
  1249. this_array[w] += n;
  1250. while(this_array[w] >= BI_DV) {
  1251. this_array[w] -= BI_DV;
  1252. if(++w >= this.t) this_array[this.t++] = 0;
  1253. ++this_array[w];
  1254. }
  1255. }
  1256. // A "null" reducer
  1257. function NullExp() {}
  1258. function nNop(x) { return x; }
  1259. function nMulTo(x,y,r) { x.multiplyTo(y,r); }
  1260. function nSqrTo(x,r) { x.squareTo(r); }
  1261. NullExp.prototype.convert = nNop;
  1262. NullExp.prototype.revert = nNop;
  1263. NullExp.prototype.mulTo = nMulTo;
  1264. NullExp.prototype.sqrTo = nSqrTo;
  1265. // (public) this^e
  1266. function bnPow(e) { return this.exp(e,new NullExp()); }
  1267. // (protected) r = lower n words of "this * a", a.t <= n
  1268. // "this" should be the larger one if appropriate.
  1269. function bnpMultiplyLowerTo(a,n,r) {
  1270. var r_array = r.array;
  1271. var a_array = a.array;
  1272. var i = Math.min(this.t+a.t,n);
  1273. r.s = 0; // assumes a,this >= 0
  1274. r.t = i;
  1275. while(i > 0) r_array[--i] = 0;
  1276. var j;
  1277. for(j = r.t-this.t; i < j; ++i) r_array[i+this.t] = this.am(0,a_array[i],r,i,0,this.t);
  1278. for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a_array[i],r,i,0,n-i);
  1279. r.clamp();
  1280. }
  1281. // (protected) r = "this * a" without lower n words, n > 0
  1282. // "this" should be the larger one if appropriate.
  1283. function bnpMultiplyUpperTo(a,n,r) {
  1284. var r_array = r.array;
  1285. var a_array = a.array;
  1286. --n;
  1287. var i = r.t = this.t+a.t-n;
  1288. r.s = 0; // assumes a,this >= 0
  1289. while(--i >= 0) r_array[i] = 0;
  1290. for(i = Math.max(n-this.t,0); i < a.t; ++i)
  1291. r_array[this.t+i-n] = this.am(n-i,a_array[i],r,0,0,this.t+i-n);
  1292. r.clamp();
  1293. r.drShiftTo(1,r);
  1294. }
  1295. // Barrett modular reduction
  1296. function Barrett(m) {
  1297. // setup Barrett
  1298. this.r2 = nbi();
  1299. this.q3 = nbi();
  1300. BigInteger.ONE.dlShiftTo(2*m.t,this.r2);
  1301. this.mu = this.r2.divide(m);
  1302. this.m = m;
  1303. }
  1304. function barrettConvert(x) {
  1305. if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m);
  1306. else if(x.compareTo(this.m) < 0) return x;
  1307. else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }
  1308. }
  1309. function barrettRevert(x) { return x; }
  1310. // x = x mod m (HAC 14.42)
  1311. function barrettReduce(x) {
  1312. x.drShiftTo(this.m.t-1,this.r2);
  1313. if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }
  1314. this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);
  1315. this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);
  1316. while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1);
  1317. x.subTo(this.r2,x);
  1318. while(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
  1319. }
  1320. // r = x^2 mod m; x != r
  1321. function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
  1322. // r = x*y mod m; x,y != r
  1323. function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
  1324. Barrett.prototype.convert = barrettConvert;
  1325. Barrett.prototype.revert = barrettRevert;
  1326. Barrett.prototype.reduce = barrettReduce;
  1327. Barrett.prototype.mulTo = barrettMulTo;
  1328. Barrett.prototype.sqrTo = barrettSqrTo;
  1329. // (public) this^e % m (HAC 14.85)
  1330. function bnModPow(e,m) {
  1331. var e_array = e.array;
  1332. var i = e.bitLength(), k, r = nbv(1), z;
  1333. if(i <= 0) return r;
  1334. else if(i < 18) k = 1;
  1335. else if(i < 48) k = 3;
  1336. else if(i < 144) k = 4;
  1337. else if(i < 768) k = 5;
  1338. else k = 6;
  1339. if(i < 8)
  1340. z = new Classic(m);
  1341. else if(m.isEven())
  1342. z = new Barrett(m);
  1343. else
  1344. z = new Montgomery(m);
  1345. // precomputation
  1346. var g = new Array(), n = 3, k1 = k-1, km = (1<<k)-1;
  1347. g[1] = z.convert(this);
  1348. if(k > 1) {
  1349. var g2 = nbi();
  1350. z.sqrTo(g[1],g2);
  1351. while(n <= km) {
  1352. g[n] = nbi();
  1353. z.mulTo(g2,g[n-2],g[n]);
  1354. n += 2;
  1355. }
  1356. }
  1357. var j = e.t-1, w, is1 = true, r2 = nbi(), t;
  1358. i = nbits(e_array[j])-1;
  1359. while(j >= 0) {
  1360. if(i >= k1) w = (e_array[j]>>(i-k1))&km;
  1361. else {
  1362. w = (e_array[j]&((1<<(i+1))-1))<<(k1-i);
  1363. if(j > 0) w |= e_array[j-1]>>(BI_DB+i-k1);
  1364. }
  1365. n = k;
  1366. while((w&1) == 0) { w >>= 1; --n; }
  1367. if((i -= n) < 0) { i += BI_DB; --j; }
  1368. if(is1) { // ret == 1, don't bother squaring or multiplying it
  1369. g[w].copyTo(r);
  1370. is1 = false;
  1371. }
  1372. else {
  1373. while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; }
  1374. if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; }
  1375. z.mulTo(r2,g[w],r);
  1376. }
  1377. while(j >= 0 && (e_array[j]&(1<<i)) == 0) {
  1378. z.sqrTo(r,r2); t = r; r = r2; r2 = t;
  1379. if(--i < 0) { i = BI_DB-1; --j; }
  1380. }
  1381. }
  1382. return z.revert(r);
  1383. }
  1384. // (public) gcd(this,a) (HAC 14.54)
  1385. function bnGCD(a) {
  1386. var x = (this.s<0)?this.negate():this.clone();
  1387. var y = (a.s<0)?a.negate():a.clone();
  1388. if(x.compareTo(y) < 0) { var t = x; x = y; y = t; }
  1389. var i = x.getLowestSetBit(), g = y.getLowestSetBit();
  1390. if(g < 0) return x;
  1391. if(i < g) g = i;
  1392. if(g > 0) {
  1393. x.rShiftTo(g,x);
  1394. y.rShiftTo(g,y);
  1395. }
  1396. while(x.signum() > 0) {
  1397. if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x);
  1398. if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y);
  1399. if(x.compareTo(y) >= 0) {
  1400. x.subTo(y,x);
  1401. x.rShiftTo(1,x);
  1402. }
  1403. else {
  1404. y.subTo(x,y);
  1405. y.rShiftTo(1,y);
  1406. }
  1407. }
  1408. if(g > 0) y.lShiftTo(g,y);
  1409. return y;
  1410. }
  1411. // (protected) this % n, n < 2^26
  1412. function bnpModInt(n) {
  1413. var this_array = this.array;
  1414. if(n <= 0) return 0;
  1415. var d = BI_DV%n, r = (this.s<0)?n-1:0;
  1416. if(this.t > 0)
  1417. if(d == 0) r = this_array[0]%n;
  1418. else for(var i = this.t-1; i >= 0; --i) r = (d*r+this_array[i])%n;
  1419. return r;
  1420. }
  1421. // (public) 1/this % m (HAC 14.61)
  1422. function bnModInverse(m) {
  1423. var ac = m.isEven();
  1424. if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO;
  1425. var u = m.clone(), v = this.clone();
  1426. var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);
  1427. while(u.signum() != 0) {
  1428. while(u.isEven()) {
  1429. u.rShiftTo(1,u);
  1430. if(ac) {
  1431. if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); }
  1432. a.rShiftTo(1,a);
  1433. }
  1434. else if(!b.isEven()) b.subTo(m,b);
  1435. b.rShiftTo(1,b);
  1436. }
  1437. while(v.isEven()) {
  1438. v.rShiftTo(1,v);
  1439. if(ac) {
  1440. if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); }
  1441. c.rShiftTo(1,c);
  1442. }
  1443. else if(!d.isEven()) d.subTo(m,d);
  1444. d.rShiftTo(1,d);
  1445. }
  1446. if(u.compareTo(v) >= 0) {
  1447. u.subTo(v,u);
  1448. if(ac) a.subTo(c,a);
  1449. b.subTo(d,b);
  1450. }
  1451. else {
  1452. v.subTo(u,v);
  1453. if(ac) c.subTo(a,c);
  1454. d.subTo(b,d);
  1455. }
  1456. }
  1457. if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;
  1458. if(d.compareTo(m) >= 0) return d.subtract(m);
  1459. if(d.signum() < 0) d.addTo(m,d); else return d;
  1460. if(d.signum() < 0) return d.add(m); else return d;
  1461. }
  1462. var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509];
  1463. var lplim = (1<<26)/lowprimes[lowprimes.length-1];
  1464. // (public) test primality with certainty >= 1-.5^t
  1465. function bnIsProbablePrime(t) {
  1466. var i, x = this.abs();
  1467. var x_array = x.array;
  1468. if(x.t == 1 && x_array[0] <= lowprimes[lowprimes.length-1]) {
  1469. for(i = 0; i < lowprimes.length; ++i)
  1470. if(x_array[0] == lowprimes[i]) return true;
  1471. return false;
  1472. }
  1473. if(x.isEven()) return false;
  1474. i = 1;
  1475. while(i < lowprimes.length) {
  1476. var m = lowprimes[i], j = i+1;
  1477. while(j < lowprimes.length && m < lplim) m *= lowprimes[j++];
  1478. m = x.modInt(m);
  1479. while(i < j) if(m%lowprimes[i++] == 0) return false;
  1480. }
  1481. return x.millerRabin(t);
  1482. }
  1483. // (protected) true if probably prime (HAC 4.24, Miller-Rabin)
  1484. function bnpMillerRabin(t) {
  1485. var n1 = this.subtract(BigInteger.ONE);
  1486. var k = n1.getLowestSetBit();
  1487. if(k <= 0) return false;
  1488. var r = n1.shiftRight(k);
  1489. t = (t+1)>>1;
  1490. if(t > lowprimes.length) t = lowprimes.length;
  1491. var a = nbi();
  1492. for(var i = 0; i < t; ++i) {
  1493. a.fromInt(lowprimes[i]);
  1494. var y = a.modPow(r,this);
  1495. if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
  1496. var j = 1;
  1497. while(j++ < k && y.compareTo(n1) != 0) {
  1498. y = y.modPowInt(2,this);
  1499. if(y.compareTo(BigInteger.ONE) == 0) return false;
  1500. }
  1501. if(y.compareTo(n1) != 0) return false;
  1502. }
  1503. }
  1504. return true;
  1505. }
  1506. // protected
  1507. BigInteger.prototype.chunkSize = bnpChunkSize;
  1508. BigInteger.prototype.toRadix = bnpToRadix;
  1509. BigInteger.prototype.fromRadix = bnpFromRadix;
  1510. BigInteger.prototype.fromNumber = bnpFromNumber;
  1511. BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
  1512. BigInteger.prototype.changeBit = bnpChangeBit;
  1513. BigInteger.prototype.addTo = bnpAddTo;
  1514. BigInteger.prototype.dMultiply = bnpDMultiply;
  1515. BigInteger.prototype.dAddOffset = bnpDAddOffset;
  1516. BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
  1517. BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
  1518. BigInteger.prototype.modInt = bnpModInt;
  1519. BigInteger.prototype.millerRabin = bnpMillerRabin;
  1520. // public
  1521. BigInteger.prototype.clone = bnClone;
  1522. BigInteger.prototype.intValue = bnIntValue;
  1523. BigInteger.prototype.byteValue = bnByteValue;
  1524. BigInteger.prototype.shortValue = bnShortValue;
  1525. BigInteger.prototype.signum = bnSigNum;
  1526. BigInteger.prototype.toByteArray = bnToByteArray;
  1527. BigInteger.prototype.equals = bnEquals;
  1528. BigInteger.prototype.min = bnMin;
  1529. BigInteger.prototype.max = bnMax;
  1530. BigInteger.prototype.and = bnAnd;
  1531. BigInteger.prototype.or = bnOr;
  1532. BigInteger.prototype.xor = bnXor;
  1533. BigInteger.prototype.andNot = bnAndNot;
  1534. BigInteger.prototype.not = bnNot;
  1535. BigInteger.prototype.shiftLeft = bnShiftLeft;
  1536. BigInteger.prototype.shiftRight = bnShiftRight;
  1537. BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
  1538. BigInteger.prototype.bitCount = bnBitCount;
  1539. BigInteger.prototype.testBit = bnTestBit;
  1540. BigInteger.prototype.setBit = bnSetBit;
  1541. BigInteger.prototype.clearBit = bnClearBit;
  1542. BigInteger.prototype.flipBit = bnFlipBit;
  1543. BigInteger.prototype.add = bnAdd;
  1544. BigInteger.prototype.subtract = bnSubtract;
  1545. BigInteger.prototype.multiply = bnMultiply;
  1546. BigInteger.prototype.divide = bnDivide;
  1547. BigInteger.prototype.remainder = bnRemainder;
  1548. BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
  1549. BigInteger.prototype.modPow = bnModPow;
  1550. BigInteger.prototype.modInverse = bnModInverse;
  1551. BigInteger.prototype.pow = bnPow;
  1552. BigInteger.prototype.gcd = bnGCD;
  1553. BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
  1554. // BigInteger interfaces not implemented in jsbn:
  1555. // BigInteger(int signum, byte[] magnitude)
  1556. // double doubleValue()
  1557. // float floatValue()
  1558. // int hashCode()
  1559. // long longValue()
  1560. // static BigInteger valueOf(long val)
  1561. // prng4.js - uses Arcfour as a PRNG
  1562. function Arcfour() {
  1563. this.i = 0;
  1564. this.j = 0;
  1565. this.S = new Array();
  1566. }
  1567. // Initialize arcfour context from key, an array of ints, each from [0..255]
  1568. function ARC4init(key) {
  1569. var i, j, t;
  1570. for(i = 0; i < 256; ++i)
  1571. this.S[i] = i;
  1572. j = 0;
  1573. for(i = 0; i < 256; ++i) {
  1574. j = (j + this.S[i] + key[i % key.length]) & 255;
  1575. t = this.S[i];
  1576. this.S[i] = this.S[j];
  1577. this.S[j] = t;
  1578. }
  1579. this.i = 0;
  1580. this.j = 0;
  1581. }
  1582. function ARC4next() {
  1583. var t;
  1584. this.i = (this.i + 1) & 255;
  1585. this.j = (this.j + this.S[this.i]) & 255;
  1586. t = this.S[this.i];
  1587. this.S[this.i] = this.S[this.j];
  1588. this.S[this.j] = t;
  1589. return this.S[(t + this.S[this.i]) & 255];
  1590. }
  1591. Arcfour.prototype.init = ARC4init;
  1592. Arcfour.prototype.next = ARC4next;
  1593. // Plug in your RNG constructor here
  1594. function prng_newstate() {
  1595. return new Arcfour();
  1596. }
  1597. // Pool size must be a multiple of 4 and greater than 32.
  1598. // An array of bytes the size of the pool will be passed to init()
  1599. var rng_psize = 256;
  1600. // Random number generator - requires a PRNG backend, e.g. prng4.js
  1601. // For best results, put code like
  1602. // <body onClick='rng_seed_time();' onKeyPress='rng_seed_time();'>
  1603. // in your main HTML document.
  1604. var rng_state;
  1605. var rng_pool;
  1606. var rng_pptr;
  1607. // Mix in a 32-bit integer into the pool
  1608. function rng_seed_int(x) {
  1609. rng_pool[rng_pptr++] ^= x & 255;
  1610. rng_pool[rng_pptr++] ^= (x >> 8) & 255;
  1611. rng_pool[rng_pptr++] ^= (x >> 16) & 255;
  1612. rng_pool[rng_pptr++] ^= (x >> 24) & 255;
  1613. if(rng_pptr >= rng_psize) rng_pptr -= rng_psize;
  1614. }
  1615. // Mix in the current time (w/milliseconds) into the pool
  1616. function rng_seed_time() {
  1617. // Use pre-computed date to avoid making the benchmark
  1618. // results dependent on the current date.
  1619. rng_seed_int(1122926989487);
  1620. }
  1621. // Initialize the pool with junk if needed.
  1622. if(rng_pool == null) {
  1623. rng_pool = new Array();
  1624. rng_pptr = 0;
  1625. var t;
  1626. while(rng_pptr < rng_psize) { // extract some randomness from Math.random()
  1627. t = Math.floor(65536 * Math.random());
  1628. rng_pool[rng_pptr++] = t >>> 8;
  1629. rng_pool[rng_pptr++] = t & 255;
  1630. }
  1631. rng_pptr = 0;
  1632. rng_seed_time();
  1633. //rng_seed_int(window.screenX);
  1634. //rng_seed_int(window.screenY);
  1635. }
  1636. function rng_get_byte() {
  1637. if(rng_state == null) {
  1638. rng_seed_time();
  1639. rng_state = prng_newstate();
  1640. rng_state.init(rng_pool);
  1641. for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr)
  1642. rng_pool[rng_pptr] = 0;
  1643. rng_pptr = 0;
  1644. //rng_pool = null;
  1645. }
  1646. // TODO: allow reseeding after first request
  1647. return rng_state.next();
  1648. }
  1649. function rng_get_bytes(ba) {
  1650. var i;
  1651. for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte();
  1652. }
  1653. function SecureRandom() {}
  1654. SecureRandom.prototype.nextBytes = rng_get_bytes;
  1655. // Depends on jsbn.js and rng.js
  1656. // convert a (hex) string to a bignum object
  1657. function parseBigInt(str,r) {
  1658. return new BigInteger(str,r);
  1659. }
  1660. function linebrk(s,n) {
  1661. var ret = "";
  1662. var i = 0;
  1663. while(i + n < s.length) {
  1664. ret += s.substring(i,i+n) + "\n";
  1665. i += n;
  1666. }
  1667. return ret + s.substring(i,s.length);
  1668. }
  1669. function byte2Hex(b) {
  1670. if(b < 0x10)
  1671. return "0" + b.toString(16);
  1672. else
  1673. return b.toString(16);
  1674. }
  1675. // PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint
  1676. function pkcs1pad2(s,n) {
  1677. if(n < s.length + 11) {
  1678. alert("Message too long for RSA");
  1679. return null;
  1680. }
  1681. var ba = new Array();
  1682. var i = s.length - 1;
  1683. while(i >= 0 && n > 0) ba[--n] = s.charCodeAt(i--);
  1684. ba[--n] = 0;
  1685. var rng = new SecureRandom();
  1686. var x = new Array();
  1687. while(n > 2) { // random non-zero pad
  1688. x[0] = 0;
  1689. while(x[0] == 0) rng.nextBytes(x);
  1690. ba[--n] = x[0];
  1691. }
  1692. ba[--n] = 2;
  1693. ba[--n] = 0;
  1694. return new BigInteger(ba);
  1695. }
  1696. // "empty" RSA key constructor
  1697. function RSAKey() {
  1698. this.n = null;
  1699. this.e = 0;
  1700. this.d = null;
  1701. this.p = null;
  1702. this.q = null;
  1703. this.dmp1 = null;
  1704. this.dmq1 = null;
  1705. this.coeff = null;
  1706. }
  1707. // Set the public key fields N and e from hex strings
  1708. function RSASetPublic(N,E) {
  1709. if(N != null && E != null && N.length > 0 && E.length > 0) {
  1710. this.n = parseBigInt(N,16);
  1711. this.e = parseInt(E,16);
  1712. }
  1713. else
  1714. alert("Invalid RSA public key");
  1715. }
  1716. // Perform raw public operation on "x": return x^e (mod n)
  1717. function RSADoPublic(x) {
  1718. return x.modPowInt(this.e, this.n);
  1719. }
  1720. // Return the PKCS#1 RSA encryption of "text" as an even-length hex string
  1721. function RSAEncrypt(text) {
  1722. var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3);
  1723. if(m == null) return null;
  1724. var c = this.doPublic(m);
  1725. if(c == null) return null;
  1726. var h = c.toString(16);
  1727. if((h.length & 1) == 0) return h; else return "0" + h;
  1728. }
  1729. // Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string
  1730. //function RSAEncryptB64(text) {
  1731. // var h = this.encrypt(text);
  1732. // if(h) return hex2b64(h); else return null;
  1733. //}
  1734. // protected
  1735. RSAKey.prototype.doPublic = RSADoPublic;
  1736. // public
  1737. RSAKey.prototype.setPublic = RSASetPublic;
  1738. RSAKey.prototype.encrypt = RSAEncrypt;
  1739. //RSAKey.prototype.encrypt_b64 = RSAEncryptB64;
  1740. // Depends on rsa.js and jsbn2.js
  1741. // Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext
  1742. function pkcs1unpad2(d,n) {
  1743. var b = d.toByteArray();
  1744. var i = 0;
  1745. while(i < b.length && b[i] == 0) ++i;
  1746. if(b.length-i != n-1 || b[i] != 2)
  1747. return null;
  1748. ++i;
  1749. while(b[i] != 0)
  1750. if(++i >= b.length) return null;
  1751. var ret = "";
  1752. while(++i < b.length)
  1753. ret += String.fromCharCode(b[i]);
  1754. return ret;
  1755. }
  1756. // Set the private key fields N, e, and d from hex strings
  1757. function RSASetPrivate(N,E,D) {
  1758. if(N != null && E != null && N.length > 0 && E.length > 0) {
  1759. this.n = parseBigInt(N,16);
  1760. this.e = parseInt(E,16);
  1761. this.d = parseBigInt(D,16);
  1762. }
  1763. else
  1764. alert("Invalid RSA private key");
  1765. }
  1766. // Set the private key fields N, e, d and CRT params from hex strings
  1767. function RSASetPrivateEx(N,E,D,P,Q,DP,DQ,C) {
  1768. if(N != null && E != null && N.length > 0 && E.length > 0) {
  1769. this.n = parseBigInt(N,16);
  1770. this.e = parseInt(E,16);
  1771. this.d = parseBigInt(D,16);
  1772. this.p = parseBigInt(P,16);
  1773. this.q = parseBigInt(Q,16);
  1774. this.dmp1 = parseBigInt(DP,16);
  1775. this.dmq1 = parseBigInt(DQ,16);
  1776. this.coeff = parseBigInt(C,16);
  1777. }
  1778. else
  1779. alert("Invalid RSA private key");
  1780. }
  1781. // Generate a new random private key B bits long, using public expt E
  1782. function RSAGenerate(B,E) {
  1783. var rng = new SecureRandom();
  1784. var qs = B>>1;
  1785. this.e = parseInt(E,16);
  1786. var ee = new BigInteger(E,16);
  1787. for(;;) {
  1788. for(;;) {
  1789. this.p = new BigInteger(B-qs,1,rng);
  1790. if(this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) break;
  1791. }
  1792. for(;;) {
  1793. this.q = new BigInteger(qs,1,rng);
  1794. if(this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) break;
  1795. }
  1796. if(this.p.compareTo(this.q) <= 0) {
  1797. var t = this.p;
  1798. this.p = this.q;
  1799. this.q = t;
  1800. }
  1801. var p1 = this.p.subtract(BigInteger.ONE);
  1802. var q1 = this.q.subtract(BigInteger.ONE);
  1803. var phi = p1.multiply(q1);
  1804. if(phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
  1805. this.n = this.p.multiply(this.q);
  1806. this.d = ee.modInverse(phi);
  1807. this.dmp1 = this.d.mod(p1);
  1808. this.dmq1 = this.d.mod(q1);
  1809. this.coeff = this.q.modInverse(this.p);
  1810. break;
  1811. }
  1812. }
  1813. }
  1814. // Perform raw private operation on "x": return x^d (mod n)
  1815. function RSADoPrivate(x) {
  1816. if(this.p == null || this.q == null)
  1817. return x.modPow(this.d, this.n);
  1818. // TODO: re-calculate any missing CRT params
  1819. var xp = x.mod(this.p).modPow(this.dmp1, this.p);
  1820. var xq = x.mod(this.q).modPow(this.dmq1, this.q);
  1821. while(xp.compareTo(xq) < 0)
  1822. xp = xp.add(this.p);
  1823. return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq);
  1824. }
  1825. // Return the PKCS#1 RSA decryption of "ctext".
  1826. // "ctext" is an even-length hex string and the output is a plain string.
  1827. function RSADecrypt(ctext) {
  1828. var c = parseBigInt(ctext, 16);
  1829. var m = this.doPrivate(c);
  1830. if(m == null) return null;
  1831. return pkcs1unpad2(m, (this.n.bitLength()+7)>>3);
  1832. }
  1833. // Return the PKCS#1 RSA decryption of "ctext".
  1834. // "ctext" is a Base64-encoded string and the output is a plain string.
  1835. //function RSAB64Decrypt(ctext) {
  1836. // var h = b64tohex(ctext);
  1837. // if(h) return this.decrypt(h); else return null;
  1838. //}
  1839. // protected
  1840. RSAKey.prototype.doPrivate = RSADoPrivate;
  1841. // public
  1842. RSAKey.prototype.setPrivate = RSASetPrivate;
  1843. RSAKey.prototype.setPrivateEx = RSASetPrivateEx;
  1844. RSAKey.prototype.generate = RSAGenerate;
  1845. RSAKey.prototype.decrypt = RSADecrypt;
  1846. //RSAKey.prototype.b64_decrypt = RSAB64Decrypt;
  1847. nValue="a5261939975948bb7a58dffe5ff54e65f0498f9175f5a09288810b8975871e99af3b5dd94057b0fc07535f5f97444504fa35169d461d0d30cf0192e307727c065168c788771c561a9400fb49175e9e6aa4e23fe11af69e9412dd23b0cb6684c4c2429bce139e848ab26d0829073351f4acd36074eafd036a5eb83359d2a698d3";
  1848. eValue="10001";
  1849. dValue="8e9912f6d3645894e8d38cb58c0db81ff516cf4c7e5a14c7f1eddb1459d2cded4d8d293fc97aee6aefb861859c8b6a3d1dfe710463e1f9ddc72048c09751971c4a580aa51eb523357a3cc48d31cfad1d4a165066ed92d4748fb6571211da5cb14bc11b6e2df7c1a559e6d5ac1cd5c94703a22891464fba23d0d965086277a161";
  1850. pValue="d090ce58a92c75233a6486cb0a9209bf3583b64f540c76f5294bb97d285eed33aec220bde14b2417951178ac152ceab6da7090905b478195498b352048f15e7d";
  1851. qValue="cab575dc652bb66df15a0359609d51d1db184750c00c6698b90ef3465c99655103edbf0d54c56aec0ce3c4d22592338092a126a0cc49f65a4a30d222b411e58f";
  1852. dmp1Value="1a24bca8e273df2f0e47c199bbf678604e7df7215480c77c8db39f49b000ce2cf7500038acfff5433b7d582a01f1826e6f4d42e1c57f5e1fef7b12aabc59fd25";
  1853. dmq1Value="3d06982efbbe47339e1f6d36b1216b8a741d410b0c662f54f7118b27b9a4ec9d914337eb39841d8666f3034408cf94f5b62f11c402fc994fe15a05493150d9fd";
  1854. coeffValue="3a3e731acd8960b7ff9eb81a7ff93bd1cfa74cbd56987db58b4594fb09c09084db1734c8143f98b602b981aaa9243ca28deb69b5b280ee8dcee0fd2625e53250";
  1855. setupEngine(am3, 28);
  1856. var TEXT = "The quick brown fox jumped over the extremely lazy frog! " +
  1857. "Now is the time for all good men to come to the party.";
  1858. var encrypted;
  1859. function encrypt() {
  1860. var RSA = new RSAKey();
  1861. RSA.setPublic(nValue, eValue);
  1862. RSA.setPrivateEx(nValue, eValue, dValue, pValue, qValue, dmp1Value, dmq1Value, coeffValue);
  1863. encrypted = RSA.encrypt(TEXT);
  1864. }
  1865. function decrypt() {
  1866. var RSA = new RSAKey();
  1867. RSA.setPublic(nValue, eValue);
  1868. RSA.setPrivateEx(nValue, eValue, dValue, pValue, qValue, dmp1Value, dmq1Value, coeffValue);
  1869. var decrypted = RSA.decrypt(encrypted);
  1870. if (decrypted != TEXT) {
  1871. throw new Error("Crypto operation failed");
  1872. }
  1873. }
  1874. ////////////////////////////////////////////////////////////////////////////////
  1875. // Runner
  1876. ////////////////////////////////////////////////////////////////////////////////
  1877. var success = true;
  1878. function NotifyStart(name) {
  1879. }
  1880. function NotifyError(name, error) {
  1881. WScript.Echo(name + " : ERROR : " +error.stack);
  1882. success = false;
  1883. }
  1884. function NotifyResult(name, score) {
  1885. if (success) {
  1886. WScript.Echo("### SCORE:", score);
  1887. }
  1888. }
  1889. function NotifyScore(score) {
  1890. }
  1891. BenchmarkSuite.RunSuites({
  1892. NotifyStart : NotifyStart,
  1893. NotifyError : NotifyError,
  1894. NotifyResult : NotifyResult,
  1895. NotifyScore : NotifyScore
  1896. });