jquery.jcryption.3.0.1.js 162 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632
  1. /*
  2. * jCryption JavaScript data encryption v3.0.1
  3. * http://www.jcryption.org/
  4. *
  5. * Copyright (c) 2013 Daniel Griesser
  6. * MIT license.
  7. * http://www.opensource.org/licenses/mit-license.php
  8. *
  9. * If you need any further information about this plugin please
  10. * visit my homepage or contact me under daniel.griesser@jcryption.org
  11. */
  12. (function($) {
  13. $.jCryption = function(el, options) {
  14. var base = this;
  15. base.$el = $(el);
  16. base.el = el;
  17. base.$el.data("jCryption", base);
  18. base.$el.data("salt", null);
  19. base.$el.data("key", null);
  20. base.init = function() {
  21. base.options = $.extend({}, $.jCryption.defaultOptions, options);
  22. // Making a good random salt
  23. base.$el.bind('mousemove', function(e) {
  24. if (base.$el.data("salt") === null) {
  25. base.$el.data("salt", (e.pageX + e.pageY) * Math.random() + "");
  26. } else {
  27. base.$el.unbind('mousemove');
  28. }
  29. });
  30. $encryptedElement = $("<input />",{
  31. type:'hidden',
  32. name:base.options.postVariable
  33. });
  34. if (base.options.submitElement !== false) {
  35. var $submitElement = base.options.submitElement;
  36. } else {
  37. var $submitElement = base.$el.find(":input:submit");
  38. }
  39. $submitElement.bind(base.options.submitEvent, function() {
  40. $(this).attr("disabled", true);
  41. if (base.options.beforeEncryption()) {
  42. base.authenticate(
  43. function(AESEncryptionKey) {
  44. var toEncrypt = base.$el.serialize();
  45. if ($submitElement.is(":submit")) {
  46. toEncrypt = toEncrypt + "&" + $submitElement.attr("name") + "=" + $submitElement.val();
  47. }
  48. $encryptedElement.val($.jCryption.encrypt(toEncrypt, AESEncryptionKey));
  49. $(base.$el).find(base.options.formFieldSelector)
  50. .attr("disabled", true).end()
  51. .append($encryptedElement).submit();
  52. },
  53. function() {
  54. // Authentication with AES Failed ... sending form without protection
  55. confirm("Authentication with Server failed, are you sure you want to submit this form unencrypted?", function() {
  56. $(base.$el).submit();
  57. });
  58. }
  59. );
  60. }
  61. return false;
  62. });
  63. };
  64. base.init();
  65. /**
  66. * Creates a random string(key) for use in the AES algorithm
  67. */
  68. base.getKey = function() {
  69. if (base.$el.data("key") !== null) {
  70. return base.$el.data("key");
  71. }
  72. // no good salt available
  73. var seed = base.$el.data("salt");
  74. if (seed === null) {
  75. // generating weak seed
  76. seed = Math.random() + "";
  77. }
  78. var salt = CryptoJS.lib.WordArray.random(16);
  79. var key128Bits = CryptoJS.PBKDF2(seed, salt, { keySize: 4 });
  80. base.$el.data("key", CryptoJS.SHA1(key128Bits).toString());
  81. return base.getKey();
  82. };
  83. /**
  84. * Authenticate with the server (One way)
  85. * @param {function} success The function to call if the operation was successfull
  86. * @param {function} failure The function to call if an error has occurred
  87. */
  88. base.authenticate = function(success, failure) {
  89. var key = base.getKey();
  90. $.jCryption.authenticate(key, base.options.getKeysURL, base.options.handshakeURL, success, failure);
  91. };
  92. };
  93. /**
  94. * Authenticates with the server
  95. * @param {string} AESEncryptionKey The AES key
  96. * @param {string} publicKeyURL The public key URL
  97. * @param {string} handshakeURL The handshake URL
  98. * @param {function} success The function to call if the operation was successfull
  99. * @param {function} failure The function to call if an error has occurred
  100. */
  101. $.jCryption.authenticate = function(AESEncryptionKey, publicKeyURL, handshakeURL, success, failure) {
  102. $.jCryption.getPublicKey(publicKeyURL, function() {
  103. $.jCryption.encryptKey(AESEncryptionKey, function(encryptedKey) {
  104. $.jCryption.handshake(handshakeURL, encryptedKey, function(response) {
  105. if ($.jCryption.challenge(response.challenge, AESEncryptionKey)) {
  106. success.call(this, AESEncryptionKey);
  107. } else {
  108. failure.call(this);
  109. }
  110. });
  111. });
  112. });
  113. };
  114. /**
  115. * Gets the RSA keys from the specified url, and saves it into a RSA keypair
  116. * @param {string} url The url to contact
  117. * @param {function} callback The function to call when the operation has finshed
  118. */
  119. $.jCryption.getPublicKey = function(url, callback) {
  120. $.getJSON(url, function(data) {
  121. $.jCryption.crypt.setKey(data.publickey);
  122. if($.isFunction(callback)) {
  123. callback.call(this);
  124. }
  125. });
  126. };
  127. /**
  128. * Decrypts data using AES 256
  129. * @param {string} data The data to decrypt(Ciphertext)
  130. * @param {string} secret The AES secret
  131. * @returns {string} The result of the decryption(Plaintext)
  132. */
  133. $.jCryption.decrypt = function(data, secret) {
  134. return $.jCryption.hex2string(CryptoJS.AES.decrypt(data, secret) + "");
  135. };
  136. /**
  137. * Encrypts data using AES 256
  138. * @param {string} data The data to encrypt(Plaintext)
  139. * @param {string} secret The AES secret
  140. * @returns {string} The result of the encryption(Ciphertext)
  141. */
  142. $.jCryption.encrypt = function(data, secret) {
  143. return CryptoJS.AES.encrypt(data, secret) + "";
  144. };
  145. /**
  146. * Makes sure that the challenge the client sent, is correct
  147. * @param {string} challenge The challenge string
  148. * @param {string} secret The AES secret
  149. */
  150. $.jCryption.challenge = function(challenge, secret) {
  151. var decrypt = $.jCryption.decrypt(challenge, secret);
  152. if (decrypt == secret) {
  153. return true;
  154. }
  155. return false;
  156. };
  157. /**
  158. * Converts a hex into a string
  159. * @param {hex} string representing a hex number
  160. * @returns {string} ASCII sting of input hex
  161. */
  162. $.jCryption.hex2string = function(hex) {
  163. var str = '';
  164. for (var i = 0; i < hex.length; i += 2) {
  165. str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
  166. }
  167. return str;
  168. };
  169. /**
  170. * Executes a handshake with the server
  171. * @param {string} url The url to connect to
  172. * @param {string} ecrypted The encrypted AES secret
  173. * @param {function} callback The function to call when the handshaking has finished
  174. */
  175. $.jCryption.handshake = function(url, ecrypted, callback) {
  176. $.ajax({
  177. url: url,
  178. dataType: "json",
  179. type: "POST",
  180. data: {
  181. handshake: "true",
  182. key: ecrypted
  183. },
  184. success: function(response) {
  185. callback.call(this, response);
  186. }
  187. });
  188. };
  189. /**
  190. * Encrypts the AES secret using RSA
  191. * @param {string} secret The AES secret
  192. * @param {function} callback The function to call when the encryption has finished
  193. */
  194. $.jCryption.encryptKey = function(secret, callback) {
  195. var encryptedString = $.jCryption.crypt.encrypt(secret);
  196. if($.isFunction(callback)) {
  197. callback(encryptedString);
  198. } else {
  199. return encryptedString;
  200. }
  201. };
  202. $.jCryption.defaultOptions = {
  203. submitElement: false,
  204. submitEvent: "click",
  205. getKeysURL: "jcryption.cgi?getPublicKey=true",
  206. handshakeURL: "jcryption.cgi",
  207. beforeEncryption: function() { return true },
  208. postVariable: "jCryption",
  209. formFieldSelector: ":input"
  210. };
  211. $.fn.jCryption = function(options) {
  212. return this.each(function(){
  213. (new $.jCryption(this, options));
  214. });
  215. };
  216. })(jQuery);
  217. var JSEncryptExports = {};
  218. (function(exports) {
  219. // Copyright (c) 2005 Tom Wu
  220. // All Rights Reserved.
  221. // See "LICENSE" for details.
  222. // Basic JavaScript BN library - subset useful for RSA encryption.
  223. // Bits per digit
  224. var dbits;
  225. // JavaScript engine analysis
  226. var canary = 0xdeadbeefcafe;
  227. var j_lm = ((canary&0xffffff)==0xefcafe);
  228. // (public) Constructor
  229. function BigInteger(a,b,c) {
  230. if(a != null)
  231. if("number" == typeof a) this.fromNumber(a,b,c);
  232. else if(b == null && "string" != typeof a) this.fromString(a,256);
  233. else this.fromString(a,b);
  234. }
  235. // return new, unset BigInteger
  236. function nbi() { return new BigInteger(null); }
  237. // am: Compute w_j += (x*this_i), propagate carries,
  238. // c is initial carry, returns final carry.
  239. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue
  240. // We need to select the fastest one that works in this environment.
  241. // am1: use a single mult and divide to get the high bits,
  242. // max digit bits should be 26 because
  243. // max internal value = 2*dvalue^2-2*dvalue (< 2^53)
  244. function am1(i,x,w,j,c,n) {
  245. while(--n >= 0) {
  246. var v = x*this[i++]+w[j]+c;
  247. c = Math.floor(v/0x4000000);
  248. w[j++] = v&0x3ffffff;
  249. }
  250. return c;
  251. }
  252. // am2 avoids a big mult-and-extract completely.
  253. // Max digit bits should be <= 30 because we do bitwise ops
  254. // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
  255. function am2(i,x,w,j,c,n) {
  256. var xl = x&0x7fff, xh = x>>15;
  257. while(--n >= 0) {
  258. var l = this[i]&0x7fff;
  259. var h = this[i++]>>15;
  260. var m = xh*l+h*xl;
  261. l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff);
  262. c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);
  263. w[j++] = l&0x3fffffff;
  264. }
  265. return c;
  266. }
  267. // Alternately, set max digit bits to 28 since some
  268. // browsers slow down when dealing with 32-bit numbers.
  269. function am3(i,x,w,j,c,n) {
  270. var xl = x&0x3fff, xh = x>>14;
  271. while(--n >= 0) {
  272. var l = this[i]&0x3fff;
  273. var h = this[i++]>>14;
  274. var m = xh*l+h*xl;
  275. l = xl*l+((m&0x3fff)<<14)+w[j]+c;
  276. c = (l>>28)+(m>>14)+xh*h;
  277. w[j++] = l&0xfffffff;
  278. }
  279. return c;
  280. }
  281. if(j_lm && (navigator.appName == "Microsoft Internet Explorer")) {
  282. BigInteger.prototype.am = am2;
  283. dbits = 30;
  284. }
  285. else if(j_lm && (navigator.appName != "Netscape")) {
  286. BigInteger.prototype.am = am1;
  287. dbits = 26;
  288. }
  289. else { // Mozilla/Netscape seems to prefer am3
  290. BigInteger.prototype.am = am3;
  291. dbits = 28;
  292. }
  293. BigInteger.prototype.DB = dbits;
  294. BigInteger.prototype.DM = ((1<<dbits)-1);
  295. BigInteger.prototype.DV = (1<<dbits);
  296. var BI_FP = 52;
  297. BigInteger.prototype.FV = Math.pow(2,BI_FP);
  298. BigInteger.prototype.F1 = BI_FP-dbits;
  299. BigInteger.prototype.F2 = 2*dbits-BI_FP;
  300. // Digit conversions
  301. var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
  302. var BI_RC = new Array();
  303. var rr,vv;
  304. rr = "0".charCodeAt(0);
  305. for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv;
  306. rr = "a".charCodeAt(0);
  307. for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
  308. rr = "A".charCodeAt(0);
  309. for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
  310. function int2char(n) { return BI_RM.charAt(n); }
  311. function intAt(s,i) {
  312. var c = BI_RC[s.charCodeAt(i)];
  313. return (c==null)?-1:c;
  314. }
  315. // (protected) copy this to r
  316. function bnpCopyTo(r) {
  317. for(var i = this.t-1; i >= 0; --i) r[i] = this[i];
  318. r.t = this.t;
  319. r.s = this.s;
  320. }
  321. // (protected) set from integer value x, -DV <= x < DV
  322. function bnpFromInt(x) {
  323. this.t = 1;
  324. this.s = (x<0)?-1:0;
  325. if(x > 0) this[0] = x;
  326. else if(x < -1) this[0] = x+DV;
  327. else this.t = 0;
  328. }
  329. // return bigint initialized to value
  330. function nbv(i) { var r = nbi(); r.fromInt(i); return r; }
  331. // (protected) set from string and radix
  332. function bnpFromString(s,b) {
  333. var k;
  334. if(b == 16) k = 4;
  335. else if(b == 8) k = 3;
  336. else if(b == 256) k = 8; // byte array
  337. else if(b == 2) k = 1;
  338. else if(b == 32) k = 5;
  339. else if(b == 4) k = 2;
  340. else { this.fromRadix(s,b); return; }
  341. this.t = 0;
  342. this.s = 0;
  343. var i = s.length, mi = false, sh = 0;
  344. while(--i >= 0) {
  345. var x = (k==8)?s[i]&0xff:intAt(s,i);
  346. if(x < 0) {
  347. if(s.charAt(i) == "-") mi = true;
  348. continue;
  349. }
  350. mi = false;
  351. if(sh == 0)
  352. this[this.t++] = x;
  353. else if(sh+k > this.DB) {
  354. this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh;
  355. this[this.t++] = (x>>(this.DB-sh));
  356. }
  357. else
  358. this[this.t-1] |= x<<sh;
  359. sh += k;
  360. if(sh >= this.DB) sh -= this.DB;
  361. }
  362. if(k == 8 && (s[0]&0x80) != 0) {
  363. this.s = -1;
  364. if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh;
  365. }
  366. this.clamp();
  367. if(mi) BigInteger.ZERO.subTo(this,this);
  368. }
  369. // (protected) clamp off excess high words
  370. function bnpClamp() {
  371. var c = this.s&this.DM;
  372. while(this.t > 0 && this[this.t-1] == c) --this.t;
  373. }
  374. // (public) return string representation in given radix
  375. function bnToString(b) {
  376. if(this.s < 0) return "-"+this.negate().toString(b);
  377. var k;
  378. if(b == 16) k = 4;
  379. else if(b == 8) k = 3;
  380. else if(b == 2) k = 1;
  381. else if(b == 32) k = 5;
  382. else if(b == 4) k = 2;
  383. else return this.toRadix(b);
  384. var km = (1<<k)-1, d, m = false, r = "", i = this.t;
  385. var p = this.DB-(i*this.DB)%k;
  386. if(i-- > 0) {
  387. if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); }
  388. while(i >= 0) {
  389. if(p < k) {
  390. d = (this[i]&((1<<p)-1))<<(k-p);
  391. d |= this[--i]>>(p+=this.DB-k);
  392. }
  393. else {
  394. d = (this[i]>>(p-=k))&km;
  395. if(p <= 0) { p += this.DB; --i; }
  396. }
  397. if(d > 0) m = true;
  398. if(m) r += int2char(d);
  399. }
  400. }
  401. return m?r:"0";
  402. }
  403. // (public) -this
  404. function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }
  405. // (public) |this|
  406. function bnAbs() { return (this.s<0)?this.negate():this; }
  407. // (public) return + if this > a, - if this < a, 0 if equal
  408. function bnCompareTo(a) {
  409. var r = this.s-a.s;
  410. if(r != 0) return r;
  411. var i = this.t;
  412. r = i-a.t;
  413. if(r != 0) return (this.s<0)?-r:r;
  414. while(--i >= 0) if((r=this[i]-a[i]) != 0) return r;
  415. return 0;
  416. }
  417. // returns bit length of the integer x
  418. function nbits(x) {
  419. var r = 1, t;
  420. if((t=x>>>16) != 0) { x = t; r += 16; }
  421. if((t=x>>8) != 0) { x = t; r += 8; }
  422. if((t=x>>4) != 0) { x = t; r += 4; }
  423. if((t=x>>2) != 0) { x = t; r += 2; }
  424. if((t=x>>1) != 0) { x = t; r += 1; }
  425. return r;
  426. }
  427. // (public) return the number of bits in "this"
  428. function bnBitLength() {
  429. if(this.t <= 0) return 0;
  430. return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM));
  431. }
  432. // (protected) r = this << n*DB
  433. function bnpDLShiftTo(n,r) {
  434. var i;
  435. for(i = this.t-1; i >= 0; --i) r[i+n] = this[i];
  436. for(i = n-1; i >= 0; --i) r[i] = 0;
  437. r.t = this.t+n;
  438. r.s = this.s;
  439. }
  440. // (protected) r = this >> n*DB
  441. function bnpDRShiftTo(n,r) {
  442. for(var i = n; i < this.t; ++i) r[i-n] = this[i];
  443. r.t = Math.max(this.t-n,0);
  444. r.s = this.s;
  445. }
  446. // (protected) r = this << n
  447. function bnpLShiftTo(n,r) {
  448. var bs = n%this.DB;
  449. var cbs = this.DB-bs;
  450. var bm = (1<<cbs)-1;
  451. var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i;
  452. for(i = this.t-1; i >= 0; --i) {
  453. r[i+ds+1] = (this[i]>>cbs)|c;
  454. c = (this[i]&bm)<<bs;
  455. }
  456. for(i = ds-1; i >= 0; --i) r[i] = 0;
  457. r[ds] = c;
  458. r.t = this.t+ds+1;
  459. r.s = this.s;
  460. r.clamp();
  461. }
  462. // (protected) r = this >> n
  463. function bnpRShiftTo(n,r) {
  464. r.s = this.s;
  465. var ds = Math.floor(n/this.DB);
  466. if(ds >= this.t) { r.t = 0; return; }
  467. var bs = n%this.DB;
  468. var cbs = this.DB-bs;
  469. var bm = (1<<bs)-1;
  470. r[0] = this[ds]>>bs;
  471. for(var i = ds+1; i < this.t; ++i) {
  472. r[i-ds-1] |= (this[i]&bm)<<cbs;
  473. r[i-ds] = this[i]>>bs;
  474. }
  475. if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<<cbs;
  476. r.t = this.t-ds;
  477. r.clamp();
  478. }
  479. // (protected) r = this - a
  480. function bnpSubTo(a,r) {
  481. var i = 0, c = 0, m = Math.min(a.t,this.t);
  482. while(i < m) {
  483. c += this[i]-a[i];
  484. r[i++] = c&this.DM;
  485. c >>= this.DB;
  486. }
  487. if(a.t < this.t) {
  488. c -= a.s;
  489. while(i < this.t) {
  490. c += this[i];
  491. r[i++] = c&this.DM;
  492. c >>= this.DB;
  493. }
  494. c += this.s;
  495. }
  496. else {
  497. c += this.s;
  498. while(i < a.t) {
  499. c -= a[i];
  500. r[i++] = c&this.DM;
  501. c >>= this.DB;
  502. }
  503. c -= a.s;
  504. }
  505. r.s = (c<0)?-1:0;
  506. if(c < -1) r[i++] = this.DV+c;
  507. else if(c > 0) r[i++] = c;
  508. r.t = i;
  509. r.clamp();
  510. }
  511. // (protected) r = this * a, r != this,a (HAC 14.12)
  512. // "this" should be the larger one if appropriate.
  513. function bnpMultiplyTo(a,r) {
  514. var x = this.abs(), y = a.abs();
  515. var i = x.t;
  516. r.t = i+y.t;
  517. while(--i >= 0) r[i] = 0;
  518. for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t);
  519. r.s = 0;
  520. r.clamp();
  521. if(this.s != a.s) BigInteger.ZERO.subTo(r,r);
  522. }
  523. // (protected) r = this^2, r != this (HAC 14.16)
  524. function bnpSquareTo(r) {
  525. var x = this.abs();
  526. var i = r.t = 2*x.t;
  527. while(--i >= 0) r[i] = 0;
  528. for(i = 0; i < x.t-1; ++i) {
  529. var c = x.am(i,x[i],r,2*i,0,1);
  530. if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) {
  531. r[i+x.t] -= x.DV;
  532. r[i+x.t+1] = 1;
  533. }
  534. }
  535. if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1);
  536. r.s = 0;
  537. r.clamp();
  538. }
  539. // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
  540. // r != q, this != m. q or r may be null.
  541. function bnpDivRemTo(m,q,r) {
  542. var pm = m.abs();
  543. if(pm.t <= 0) return;
  544. var pt = this.abs();
  545. if(pt.t < pm.t) {
  546. if(q != null) q.fromInt(0);
  547. if(r != null) this.copyTo(r);
  548. return;
  549. }
  550. if(r == null) r = nbi();
  551. var y = nbi(), ts = this.s, ms = m.s;
  552. var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus
  553. if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); }
  554. else { pm.copyTo(y); pt.copyTo(r); }
  555. var ys = y.t;
  556. var y0 = y[ys-1];
  557. if(y0 == 0) return;
  558. var yt = y0*(1<<this.F1)+((ys>1)?y[ys-2]>>this.F2:0);
  559. var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2;
  560. var i = r.t, j = i-ys, t = (q==null)?nbi():q;
  561. y.dlShiftTo(j,t);
  562. if(r.compareTo(t) >= 0) {
  563. r[r.t++] = 1;
  564. r.subTo(t,r);
  565. }
  566. BigInteger.ONE.dlShiftTo(ys,t);
  567. t.subTo(y,y); // "negative" y so we can replace sub with am later
  568. while(y.t < ys) y[y.t++] = 0;
  569. while(--j >= 0) {
  570. // Estimate quotient digit
  571. var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2);
  572. if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out
  573. y.dlShiftTo(j,t);
  574. r.subTo(t,r);
  575. while(r[i] < --qd) r.subTo(t,r);
  576. }
  577. }
  578. if(q != null) {
  579. r.drShiftTo(ys,q);
  580. if(ts != ms) BigInteger.ZERO.subTo(q,q);
  581. }
  582. r.t = ys;
  583. r.clamp();
  584. if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder
  585. if(ts < 0) BigInteger.ZERO.subTo(r,r);
  586. }
  587. // (public) this mod a
  588. function bnMod(a) {
  589. var r = nbi();
  590. this.abs().divRemTo(a,null,r);
  591. if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r);
  592. return r;
  593. }
  594. // Modular reduction using "classic" algorithm
  595. function Classic(m) { this.m = m; }
  596. function cConvert(x) {
  597. if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);
  598. else return x;
  599. }
  600. function cRevert(x) { return x; }
  601. function cReduce(x) { x.divRemTo(this.m,null,x); }
  602. function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
  603. function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
  604. Classic.prototype.convert = cConvert;
  605. Classic.prototype.revert = cRevert;
  606. Classic.prototype.reduce = cReduce;
  607. Classic.prototype.mulTo = cMulTo;
  608. Classic.prototype.sqrTo = cSqrTo;
  609. // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
  610. // justification:
  611. // xy == 1 (mod m)
  612. // xy = 1+km
  613. // xy(2-xy) = (1+km)(1-km)
  614. // x[y(2-xy)] = 1-k^2m^2
  615. // x[y(2-xy)] == 1 (mod m^2)
  616. // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
  617. // should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
  618. // JS multiply "overflows" differently from C/C++, so care is needed here.
  619. function bnpInvDigit() {
  620. if(this.t < 1) return 0;
  621. var x = this[0];
  622. if((x&1) == 0) return 0;
  623. var y = x&3; // y == 1/x mod 2^2
  624. y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4
  625. y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8
  626. y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16
  627. // last step - calculate inverse mod DV directly;
  628. // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
  629. y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits
  630. // we really want the negative inverse, and -DV < y < DV
  631. return (y>0)?this.DV-y:-y;
  632. }
  633. // Montgomery reduction
  634. function Montgomery(m) {
  635. this.m = m;
  636. this.mp = m.invDigit();
  637. this.mpl = this.mp&0x7fff;
  638. this.mph = this.mp>>15;
  639. this.um = (1<<(m.DB-15))-1;
  640. this.mt2 = 2*m.t;
  641. }
  642. // xR mod m
  643. function montConvert(x) {
  644. var r = nbi();
  645. x.abs().dlShiftTo(this.m.t,r);
  646. r.divRemTo(this.m,null,r);
  647. if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);
  648. return r;
  649. }
  650. // x/R mod m
  651. function montRevert(x) {
  652. var r = nbi();
  653. x.copyTo(r);
  654. this.reduce(r);
  655. return r;
  656. }
  657. // x = x/R mod m (HAC 14.32)
  658. function montReduce(x) {
  659. while(x.t <= this.mt2) // pad x so am has enough room later
  660. x[x.t++] = 0;
  661. for(var i = 0; i < this.m.t; ++i) {
  662. // faster way of calculating u0 = x[i]*mp mod DV
  663. var j = x[i]&0x7fff;
  664. var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM;
  665. // use am to combine the multiply-shift-add into one call
  666. j = i+this.m.t;
  667. x[j] += this.m.am(0,u0,x,i,0,this.m.t);
  668. // propagate carry
  669. while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; }
  670. }
  671. x.clamp();
  672. x.drShiftTo(this.m.t,x);
  673. if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
  674. }
  675. // r = "x^2/R mod m"; x != r
  676. function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
  677. // r = "xy/R mod m"; x,y != r
  678. function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
  679. Montgomery.prototype.convert = montConvert;
  680. Montgomery.prototype.revert = montRevert;
  681. Montgomery.prototype.reduce = montReduce;
  682. Montgomery.prototype.mulTo = montMulTo;
  683. Montgomery.prototype.sqrTo = montSqrTo;
  684. // (protected) true iff this is even
  685. function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; }
  686. // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
  687. function bnpExp(e,z) {
  688. if(e > 0xffffffff || e < 1) return BigInteger.ONE;
  689. var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;
  690. g.copyTo(r);
  691. while(--i >= 0) {
  692. z.sqrTo(r,r2);
  693. if((e&(1<<i)) > 0) z.mulTo(r2,g,r);
  694. else { var t = r; r = r2; r2 = t; }
  695. }
  696. return z.revert(r);
  697. }
  698. // (public) this^e % m, 0 <= e < 2^32
  699. function bnModPowInt(e,m) {
  700. var z;
  701. if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);
  702. return this.exp(e,z);
  703. }
  704. // protected
  705. BigInteger.prototype.copyTo = bnpCopyTo;
  706. BigInteger.prototype.fromInt = bnpFromInt;
  707. BigInteger.prototype.fromString = bnpFromString;
  708. BigInteger.prototype.clamp = bnpClamp;
  709. BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
  710. BigInteger.prototype.drShiftTo = bnpDRShiftTo;
  711. BigInteger.prototype.lShiftTo = bnpLShiftTo;
  712. BigInteger.prototype.rShiftTo = bnpRShiftTo;
  713. BigInteger.prototype.subTo = bnpSubTo;
  714. BigInteger.prototype.multiplyTo = bnpMultiplyTo;
  715. BigInteger.prototype.squareTo = bnpSquareTo;
  716. BigInteger.prototype.divRemTo = bnpDivRemTo;
  717. BigInteger.prototype.invDigit = bnpInvDigit;
  718. BigInteger.prototype.isEven = bnpIsEven;
  719. BigInteger.prototype.exp = bnpExp;
  720. // public
  721. BigInteger.prototype.toString = bnToString;
  722. BigInteger.prototype.negate = bnNegate;
  723. BigInteger.prototype.abs = bnAbs;
  724. BigInteger.prototype.compareTo = bnCompareTo;
  725. BigInteger.prototype.bitLength = bnBitLength;
  726. BigInteger.prototype.mod = bnMod;
  727. BigInteger.prototype.modPowInt = bnModPowInt;
  728. // "constants"
  729. BigInteger.ZERO = nbv(0);
  730. BigInteger.ONE = nbv(1);
  731. // Copyright (c) 2005-2009 Tom Wu
  732. // All Rights Reserved.
  733. // See "LICENSE" for details.
  734. // Extended JavaScript BN functions, required for RSA private ops.
  735. // Version 1.1: new BigInteger("0", 10) returns "proper" zero
  736. // Version 1.2: square() API, isProbablePrime fix
  737. // (public)
  738. function bnClone() { var r = nbi(); this.copyTo(r); return r; }
  739. // (public) return value as integer
  740. function bnIntValue() {
  741. if(this.s < 0) {
  742. if(this.t == 1) return this[0]-this.DV;
  743. else if(this.t == 0) return -1;
  744. }
  745. else if(this.t == 1) return this[0];
  746. else if(this.t == 0) return 0;
  747. // assumes 16 < DB < 32
  748. return ((this[1]&((1<<(32-this.DB))-1))<<this.DB)|this[0];
  749. }
  750. // (public) return value as byte
  751. function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }
  752. // (public) return value as short (assumes DB>=16)
  753. function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; }
  754. // (protected) return x s.t. r^x < DV
  755. function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); }
  756. // (public) 0 if this == 0, 1 if this > 0
  757. function bnSigNum() {
  758. if(this.s < 0) return -1;
  759. else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0;
  760. else return 1;
  761. }
  762. // (protected) convert to radix string
  763. function bnpToRadix(b) {
  764. if(b == null) b = 10;
  765. if(this.signum() == 0 || b < 2 || b > 36) return "0";
  766. var cs = this.chunkSize(b);
  767. var a = Math.pow(b,cs);
  768. var d = nbv(a), y = nbi(), z = nbi(), r = "";
  769. this.divRemTo(d,y,z);
  770. while(y.signum() > 0) {
  771. r = (a+z.intValue()).toString(b).substr(1) + r;
  772. y.divRemTo(d,y,z);
  773. }
  774. return z.intValue().toString(b) + r;
  775. }
  776. // (protected) convert from radix string
  777. function bnpFromRadix(s,b) {
  778. this.fromInt(0);
  779. if(b == null) b = 10;
  780. var cs = this.chunkSize(b);
  781. var d = Math.pow(b,cs), mi = false, j = 0, w = 0;
  782. for(var i = 0; i < s.length; ++i) {
  783. var x = intAt(s,i);
  784. if(x < 0) {
  785. if(s.charAt(i) == "-" && this.signum() == 0) mi = true;
  786. continue;
  787. }
  788. w = b*w+x;
  789. if(++j >= cs) {
  790. this.dMultiply(d);
  791. this.dAddOffset(w,0);
  792. j = 0;
  793. w = 0;
  794. }
  795. }
  796. if(j > 0) {
  797. this.dMultiply(Math.pow(b,j));
  798. this.dAddOffset(w,0);
  799. }
  800. if(mi) BigInteger.ZERO.subTo(this,this);
  801. }
  802. // (protected) alternate constructor
  803. function bnpFromNumber(a,b,c) {
  804. if("number" == typeof b) {
  805. // new BigInteger(int,int,RNG)
  806. if(a < 2) this.fromInt(1);
  807. else {
  808. this.fromNumber(a,c);
  809. if(!this.testBit(a-1)) // force MSB set
  810. this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);
  811. if(this.isEven()) this.dAddOffset(1,0); // force odd
  812. while(!this.isProbablePrime(b)) {
  813. this.dAddOffset(2,0);
  814. if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this);
  815. }
  816. }
  817. }
  818. else {
  819. // new BigInteger(int,RNG)
  820. var x = new Array(), t = a&7;
  821. x.length = (a>>3)+1;
  822. b.nextBytes(x);
  823. if(t > 0) x[0] &= ((1<<t)-1); else x[0] = 0;
  824. this.fromString(x,256);
  825. }
  826. }
  827. // (public) convert to bigendian byte array
  828. function bnToByteArray() {
  829. var i = this.t, r = new Array();
  830. r[0] = this.s;
  831. var p = this.DB-(i*this.DB)%8, d, k = 0;
  832. if(i-- > 0) {
  833. if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p)
  834. r[k++] = d|(this.s<<(this.DB-p));
  835. while(i >= 0) {
  836. if(p < 8) {
  837. d = (this[i]&((1<<p)-1))<<(8-p);
  838. d |= this[--i]>>(p+=this.DB-8);
  839. }
  840. else {
  841. d = (this[i]>>(p-=8))&0xff;
  842. if(p <= 0) { p += this.DB; --i; }
  843. }
  844. if((d&0x80) != 0) d |= -256;
  845. if(k == 0 && (this.s&0x80) != (d&0x80)) ++k;
  846. if(k > 0 || d != this.s) r[k++] = d;
  847. }
  848. }
  849. return r;
  850. }
  851. function bnEquals(a) { return(this.compareTo(a)==0); }
  852. function bnMin(a) { return(this.compareTo(a)<0)?this:a; }
  853. function bnMax(a) { return(this.compareTo(a)>0)?this:a; }
  854. // (protected) r = this op a (bitwise)
  855. function bnpBitwiseTo(a,op,r) {
  856. var i, f, m = Math.min(a.t,this.t);
  857. for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]);
  858. if(a.t < this.t) {
  859. f = a.s&this.DM;
  860. for(i = m; i < this.t; ++i) r[i] = op(this[i],f);
  861. r.t = this.t;
  862. }
  863. else {
  864. f = this.s&this.DM;
  865. for(i = m; i < a.t; ++i) r[i] = op(f,a[i]);
  866. r.t = a.t;
  867. }
  868. r.s = op(this.s,a.s);
  869. r.clamp();
  870. }
  871. // (public) this & a
  872. function op_and(x,y) { return x&y; }
  873. function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }
  874. // (public) this | a
  875. function op_or(x,y) { return x|y; }
  876. function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }
  877. // (public) this ^ a
  878. function op_xor(x,y) { return x^y; }
  879. function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }
  880. // (public) this & ~a
  881. function op_andnot(x,y) { return x&~y; }
  882. function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; }
  883. // (public) ~this
  884. function bnNot() {
  885. var r = nbi();
  886. for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i];
  887. r.t = this.t;
  888. r.s = ~this.s;
  889. return r;
  890. }
  891. // (public) this << n
  892. function bnShiftLeft(n) {
  893. var r = nbi();
  894. if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r);
  895. return r;
  896. }
  897. // (public) this >> n
  898. function bnShiftRight(n) {
  899. var r = nbi();
  900. if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r);
  901. return r;
  902. }
  903. // return index of lowest 1-bit in x, x < 2^31
  904. function lbit(x) {
  905. if(x == 0) return -1;
  906. var r = 0;
  907. if((x&0xffff) == 0) { x >>= 16; r += 16; }
  908. if((x&0xff) == 0) { x >>= 8; r += 8; }
  909. if((x&0xf) == 0) { x >>= 4; r += 4; }
  910. if((x&3) == 0) { x >>= 2; r += 2; }
  911. if((x&1) == 0) ++r;
  912. return r;
  913. }
  914. // (public) returns index of lowest 1-bit (or -1 if none)
  915. function bnGetLowestSetBit() {
  916. for(var i = 0; i < this.t; ++i)
  917. if(this[i] != 0) return i*this.DB+lbit(this[i]);
  918. if(this.s < 0) return this.t*this.DB;
  919. return -1;
  920. }
  921. // return number of 1 bits in x
  922. function cbit(x) {
  923. var r = 0;
  924. while(x != 0) { x &= x-1; ++r; }
  925. return r;
  926. }
  927. // (public) return number of set bits
  928. function bnBitCount() {
  929. var r = 0, x = this.s&this.DM;
  930. for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x);
  931. return r;
  932. }
  933. // (public) true iff nth bit is set
  934. function bnTestBit(n) {
  935. var j = Math.floor(n/this.DB);
  936. if(j >= this.t) return(this.s!=0);
  937. return((this[j]&(1<<(n%this.DB)))!=0);
  938. }
  939. // (protected) this op (1<<n)
  940. function bnpChangeBit(n,op) {
  941. var r = BigInteger.ONE.shiftLeft(n);
  942. this.bitwiseTo(r,op,r);
  943. return r;
  944. }
  945. // (public) this | (1<<n)
  946. function bnSetBit(n) { return this.changeBit(n,op_or); }
  947. // (public) this & ~(1<<n)
  948. function bnClearBit(n) { return this.changeBit(n,op_andnot); }
  949. // (public) this ^ (1<<n)
  950. function bnFlipBit(n) { return this.changeBit(n,op_xor); }
  951. // (protected) r = this + a
  952. function bnpAddTo(a,r) {
  953. var i = 0, c = 0, m = Math.min(a.t,this.t);
  954. while(i < m) {
  955. c += this[i]+a[i];
  956. r[i++] = c&this.DM;
  957. c >>= this.DB;
  958. }
  959. if(a.t < this.t) {
  960. c += a.s;
  961. while(i < this.t) {
  962. c += this[i];
  963. r[i++] = c&this.DM;
  964. c >>= this.DB;
  965. }
  966. c += this.s;
  967. }
  968. else {
  969. c += this.s;
  970. while(i < a.t) {
  971. c += a[i];
  972. r[i++] = c&this.DM;
  973. c >>= this.DB;
  974. }
  975. c += a.s;
  976. }
  977. r.s = (c<0)?-1:0;
  978. if(c > 0) r[i++] = c;
  979. else if(c < -1) r[i++] = this.DV+c;
  980. r.t = i;
  981. r.clamp();
  982. }
  983. // (public) this + a
  984. function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }
  985. // (public) this - a
  986. function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }
  987. // (public) this * a
  988. function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }
  989. // (public) this^2
  990. function bnSquare() { var r = nbi(); this.squareTo(r); return r; }
  991. // (public) this / a
  992. function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }
  993. // (public) this % a
  994. function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; }
  995. // (public) [this/a,this%a]
  996. function bnDivideAndRemainder(a) {
  997. var q = nbi(), r = nbi();
  998. this.divRemTo(a,q,r);
  999. return new Array(q,r);
  1000. }
  1001. // (protected) this *= n, this >= 0, 1 < n < DV
  1002. function bnpDMultiply(n) {
  1003. this[this.t] = this.am(0,n-1,this,0,0,this.t);
  1004. ++this.t;
  1005. this.clamp();
  1006. }
  1007. // (protected) this += n << w words, this >= 0
  1008. function bnpDAddOffset(n,w) {
  1009. if(n == 0) return;
  1010. while(this.t <= w) this[this.t++] = 0;
  1011. this[w] += n;
  1012. while(this[w] >= this.DV) {
  1013. this[w] -= this.DV;
  1014. if(++w >= this.t) this[this.t++] = 0;
  1015. ++this[w];
  1016. }
  1017. }
  1018. // A "null" reducer
  1019. function NullExp() {}
  1020. function nNop(x) { return x; }
  1021. function nMulTo(x,y,r) { x.multiplyTo(y,r); }
  1022. function nSqrTo(x,r) { x.squareTo(r); }
  1023. NullExp.prototype.convert = nNop;
  1024. NullExp.prototype.revert = nNop;
  1025. NullExp.prototype.mulTo = nMulTo;
  1026. NullExp.prototype.sqrTo = nSqrTo;
  1027. // (public) this^e
  1028. function bnPow(e) { return this.exp(e,new NullExp()); }
  1029. // (protected) r = lower n words of "this * a", a.t <= n
  1030. // "this" should be the larger one if appropriate.
  1031. function bnpMultiplyLowerTo(a,n,r) {
  1032. var i = Math.min(this.t+a.t,n);
  1033. r.s = 0; // assumes a,this >= 0
  1034. r.t = i;
  1035. while(i > 0) r[--i] = 0;
  1036. var j;
  1037. for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t);
  1038. for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i);
  1039. r.clamp();
  1040. }
  1041. // (protected) r = "this * a" without lower n words, n > 0
  1042. // "this" should be the larger one if appropriate.
  1043. function bnpMultiplyUpperTo(a,n,r) {
  1044. --n;
  1045. var i = r.t = this.t+a.t-n;
  1046. r.s = 0; // assumes a,this >= 0
  1047. while(--i >= 0) r[i] = 0;
  1048. for(i = Math.max(n-this.t,0); i < a.t; ++i)
  1049. r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n);
  1050. r.clamp();
  1051. r.drShiftTo(1,r);
  1052. }
  1053. // Barrett modular reduction
  1054. function Barrett(m) {
  1055. // setup Barrett
  1056. this.r2 = nbi();
  1057. this.q3 = nbi();
  1058. BigInteger.ONE.dlShiftTo(2*m.t,this.r2);
  1059. this.mu = this.r2.divide(m);
  1060. this.m = m;
  1061. }
  1062. function barrettConvert(x) {
  1063. if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m);
  1064. else if(x.compareTo(this.m) < 0) return x;
  1065. else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }
  1066. }
  1067. function barrettRevert(x) { return x; }
  1068. // x = x mod m (HAC 14.42)
  1069. function barrettReduce(x) {
  1070. x.drShiftTo(this.m.t-1,this.r2);
  1071. if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }
  1072. this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);
  1073. this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);
  1074. while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1);
  1075. x.subTo(this.r2,x);
  1076. while(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
  1077. }
  1078. // r = x^2 mod m; x != r
  1079. function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
  1080. // r = x*y mod m; x,y != r
  1081. function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
  1082. Barrett.prototype.convert = barrettConvert;
  1083. Barrett.prototype.revert = barrettRevert;
  1084. Barrett.prototype.reduce = barrettReduce;
  1085. Barrett.prototype.mulTo = barrettMulTo;
  1086. Barrett.prototype.sqrTo = barrettSqrTo;
  1087. // (public) this^e % m (HAC 14.85)
  1088. function bnModPow(e,m) {
  1089. var i = e.bitLength(), k, r = nbv(1), z;
  1090. if(i <= 0) return r;
  1091. else if(i < 18) k = 1;
  1092. else if(i < 48) k = 3;
  1093. else if(i < 144) k = 4;
  1094. else if(i < 768) k = 5;
  1095. else k = 6;
  1096. if(i < 8)
  1097. z = new Classic(m);
  1098. else if(m.isEven())
  1099. z = new Barrett(m);
  1100. else
  1101. z = new Montgomery(m);
  1102. // precomputation
  1103. var g = new Array(), n = 3, k1 = k-1, km = (1<<k)-1;
  1104. g[1] = z.convert(this);
  1105. if(k > 1) {
  1106. var g2 = nbi();
  1107. z.sqrTo(g[1],g2);
  1108. while(n <= km) {
  1109. g[n] = nbi();
  1110. z.mulTo(g2,g[n-2],g[n]);
  1111. n += 2;
  1112. }
  1113. }
  1114. var j = e.t-1, w, is1 = true, r2 = nbi(), t;
  1115. i = nbits(e[j])-1;
  1116. while(j >= 0) {
  1117. if(i >= k1) w = (e[j]>>(i-k1))&km;
  1118. else {
  1119. w = (e[j]&((1<<(i+1))-1))<<(k1-i);
  1120. if(j > 0) w |= e[j-1]>>(this.DB+i-k1);
  1121. }
  1122. n = k;
  1123. while((w&1) == 0) { w >>= 1; --n; }
  1124. if((i -= n) < 0) { i += this.DB; --j; }
  1125. if(is1) { // ret == 1, don't bother squaring or multiplying it
  1126. g[w].copyTo(r);
  1127. is1 = false;
  1128. }
  1129. else {
  1130. while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; }
  1131. if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; }
  1132. z.mulTo(r2,g[w],r);
  1133. }
  1134. while(j >= 0 && (e[j]&(1<<i)) == 0) {
  1135. z.sqrTo(r,r2); t = r; r = r2; r2 = t;
  1136. if(--i < 0) { i = this.DB-1; --j; }
  1137. }
  1138. }
  1139. return z.revert(r);
  1140. }
  1141. // (public) gcd(this,a) (HAC 14.54)
  1142. function bnGCD(a) {
  1143. var x = (this.s<0)?this.negate():this.clone();
  1144. var y = (a.s<0)?a.negate():a.clone();
  1145. if(x.compareTo(y) < 0) { var t = x; x = y; y = t; }
  1146. var i = x.getLowestSetBit(), g = y.getLowestSetBit();
  1147. if(g < 0) return x;
  1148. if(i < g) g = i;
  1149. if(g > 0) {
  1150. x.rShiftTo(g,x);
  1151. y.rShiftTo(g,y);
  1152. }
  1153. while(x.signum() > 0) {
  1154. if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x);
  1155. if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y);
  1156. if(x.compareTo(y) >= 0) {
  1157. x.subTo(y,x);
  1158. x.rShiftTo(1,x);
  1159. }
  1160. else {
  1161. y.subTo(x,y);
  1162. y.rShiftTo(1,y);
  1163. }
  1164. }
  1165. if(g > 0) y.lShiftTo(g,y);
  1166. return y;
  1167. }
  1168. // (protected) this % n, n < 2^26
  1169. function bnpModInt(n) {
  1170. if(n <= 0) return 0;
  1171. var d = this.DV%n, r = (this.s<0)?n-1:0;
  1172. if(this.t > 0)
  1173. if(d == 0) r = this[0]%n;
  1174. else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n;
  1175. return r;
  1176. }
  1177. // (public) 1/this % m (HAC 14.61)
  1178. function bnModInverse(m) {
  1179. var ac = m.isEven();
  1180. if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO;
  1181. var u = m.clone(), v = this.clone();
  1182. var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);
  1183. while(u.signum() != 0) {
  1184. while(u.isEven()) {
  1185. u.rShiftTo(1,u);
  1186. if(ac) {
  1187. if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); }
  1188. a.rShiftTo(1,a);
  1189. }
  1190. else if(!b.isEven()) b.subTo(m,b);
  1191. b.rShiftTo(1,b);
  1192. }
  1193. while(v.isEven()) {
  1194. v.rShiftTo(1,v);
  1195. if(ac) {
  1196. if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); }
  1197. c.rShiftTo(1,c);
  1198. }
  1199. else if(!d.isEven()) d.subTo(m,d);
  1200. d.rShiftTo(1,d);
  1201. }
  1202. if(u.compareTo(v) >= 0) {
  1203. u.subTo(v,u);
  1204. if(ac) a.subTo(c,a);
  1205. b.subTo(d,b);
  1206. }
  1207. else {
  1208. v.subTo(u,v);
  1209. if(ac) c.subTo(a,c);
  1210. d.subTo(b,d);
  1211. }
  1212. }
  1213. if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;
  1214. if(d.compareTo(m) >= 0) return d.subtract(m);
  1215. if(d.signum() < 0) d.addTo(m,d); else return d;
  1216. if(d.signum() < 0) return d.add(m); else return d;
  1217. }
  1218. 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,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997];
  1219. var lplim = (1<<26)/lowprimes[lowprimes.length-1];
  1220. // (public) test primality with certainty >= 1-.5^t
  1221. function bnIsProbablePrime(t) {
  1222. var i, x = this.abs();
  1223. if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) {
  1224. for(i = 0; i < lowprimes.length; ++i)
  1225. if(x[0] == lowprimes[i]) return true;
  1226. return false;
  1227. }
  1228. if(x.isEven()) return false;
  1229. i = 1;
  1230. while(i < lowprimes.length) {
  1231. var m = lowprimes[i], j = i+1;
  1232. while(j < lowprimes.length && m < lplim) m *= lowprimes[j++];
  1233. m = x.modInt(m);
  1234. while(i < j) if(m%lowprimes[i++] == 0) return false;
  1235. }
  1236. return x.millerRabin(t);
  1237. }
  1238. // (protected) true if probably prime (HAC 4.24, Miller-Rabin)
  1239. function bnpMillerRabin(t) {
  1240. var n1 = this.subtract(BigInteger.ONE);
  1241. var k = n1.getLowestSetBit();
  1242. if(k <= 0) return false;
  1243. var r = n1.shiftRight(k);
  1244. t = (t+1)>>1;
  1245. if(t > lowprimes.length) t = lowprimes.length;
  1246. var a = nbi();
  1247. for(var i = 0; i < t; ++i) {
  1248. //Pick bases at random, instead of starting at 2
  1249. a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]);
  1250. var y = a.modPow(r,this);
  1251. if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
  1252. var j = 1;
  1253. while(j++ < k && y.compareTo(n1) != 0) {
  1254. y = y.modPowInt(2,this);
  1255. if(y.compareTo(BigInteger.ONE) == 0) return false;
  1256. }
  1257. if(y.compareTo(n1) != 0) return false;
  1258. }
  1259. }
  1260. return true;
  1261. }
  1262. // protected
  1263. BigInteger.prototype.chunkSize = bnpChunkSize;
  1264. BigInteger.prototype.toRadix = bnpToRadix;
  1265. BigInteger.prototype.fromRadix = bnpFromRadix;
  1266. BigInteger.prototype.fromNumber = bnpFromNumber;
  1267. BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
  1268. BigInteger.prototype.changeBit = bnpChangeBit;
  1269. BigInteger.prototype.addTo = bnpAddTo;
  1270. BigInteger.prototype.dMultiply = bnpDMultiply;
  1271. BigInteger.prototype.dAddOffset = bnpDAddOffset;
  1272. BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
  1273. BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
  1274. BigInteger.prototype.modInt = bnpModInt;
  1275. BigInteger.prototype.millerRabin = bnpMillerRabin;
  1276. // public
  1277. BigInteger.prototype.clone = bnClone;
  1278. BigInteger.prototype.intValue = bnIntValue;
  1279. BigInteger.prototype.byteValue = bnByteValue;
  1280. BigInteger.prototype.shortValue = bnShortValue;
  1281. BigInteger.prototype.signum = bnSigNum;
  1282. BigInteger.prototype.toByteArray = bnToByteArray;
  1283. BigInteger.prototype.equals = bnEquals;
  1284. BigInteger.prototype.min = bnMin;
  1285. BigInteger.prototype.max = bnMax;
  1286. BigInteger.prototype.and = bnAnd;
  1287. BigInteger.prototype.or = bnOr;
  1288. BigInteger.prototype.xor = bnXor;
  1289. BigInteger.prototype.andNot = bnAndNot;
  1290. BigInteger.prototype.not = bnNot;
  1291. BigInteger.prototype.shiftLeft = bnShiftLeft;
  1292. BigInteger.prototype.shiftRight = bnShiftRight;
  1293. BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
  1294. BigInteger.prototype.bitCount = bnBitCount;
  1295. BigInteger.prototype.testBit = bnTestBit;
  1296. BigInteger.prototype.setBit = bnSetBit;
  1297. BigInteger.prototype.clearBit = bnClearBit;
  1298. BigInteger.prototype.flipBit = bnFlipBit;
  1299. BigInteger.prototype.add = bnAdd;
  1300. BigInteger.prototype.subtract = bnSubtract;
  1301. BigInteger.prototype.multiply = bnMultiply;
  1302. BigInteger.prototype.divide = bnDivide;
  1303. BigInteger.prototype.remainder = bnRemainder;
  1304. BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
  1305. BigInteger.prototype.modPow = bnModPow;
  1306. BigInteger.prototype.modInverse = bnModInverse;
  1307. BigInteger.prototype.pow = bnPow;
  1308. BigInteger.prototype.gcd = bnGCD;
  1309. BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
  1310. // JSBN-specific extension
  1311. BigInteger.prototype.square = bnSquare;
  1312. // BigInteger interfaces not implemented in jsbn:
  1313. // BigInteger(int signum, byte[] magnitude)
  1314. // double doubleValue()
  1315. // float floatValue()
  1316. // int hashCode()
  1317. // long longValue()
  1318. // static BigInteger valueOf(long val)
  1319. // prng4.js - uses Arcfour as a PRNG
  1320. function Arcfour() {
  1321. this.i = 0;
  1322. this.j = 0;
  1323. this.S = new Array();
  1324. }
  1325. // Initialize arcfour context from key, an array of ints, each from [0..255]
  1326. function ARC4init(key) {
  1327. var i, j, t;
  1328. for(i = 0; i < 256; ++i)
  1329. this.S[i] = i;
  1330. j = 0;
  1331. for(i = 0; i < 256; ++i) {
  1332. j = (j + this.S[i] + key[i % key.length]) & 255;
  1333. t = this.S[i];
  1334. this.S[i] = this.S[j];
  1335. this.S[j] = t;
  1336. }
  1337. this.i = 0;
  1338. this.j = 0;
  1339. }
  1340. function ARC4next() {
  1341. var t;
  1342. this.i = (this.i + 1) & 255;
  1343. this.j = (this.j + this.S[this.i]) & 255;
  1344. t = this.S[this.i];
  1345. this.S[this.i] = this.S[this.j];
  1346. this.S[this.j] = t;
  1347. return this.S[(t + this.S[this.i]) & 255];
  1348. }
  1349. Arcfour.prototype.init = ARC4init;
  1350. Arcfour.prototype.next = ARC4next;
  1351. // Plug in your RNG constructor here
  1352. function prng_newstate() {
  1353. return new Arcfour();
  1354. }
  1355. // Pool size must be a multiple of 4 and greater than 32.
  1356. // An array of bytes the size of the pool will be passed to init()
  1357. var rng_psize = 256;
  1358. // Random number generator - requires a PRNG backend, e.g. prng4.js
  1359. // For best results, put code like
  1360. // <body onClick='rng_seed_time();' onKeyPress='rng_seed_time();'>
  1361. // in your main HTML document.
  1362. var rng_state;
  1363. var rng_pool;
  1364. var rng_pptr;
  1365. // Mix in a 32-bit integer into the pool
  1366. function rng_seed_int(x) {
  1367. rng_pool[rng_pptr++] ^= x & 255;
  1368. rng_pool[rng_pptr++] ^= (x >> 8) & 255;
  1369. rng_pool[rng_pptr++] ^= (x >> 16) & 255;
  1370. rng_pool[rng_pptr++] ^= (x >> 24) & 255;
  1371. if(rng_pptr >= rng_psize) rng_pptr -= rng_psize;
  1372. }
  1373. // Mix in the current time (w/milliseconds) into the pool
  1374. function rng_seed_time() {
  1375. rng_seed_int(new Date().getTime());
  1376. }
  1377. // Initialize the pool with junk if needed.
  1378. if(rng_pool == null) {
  1379. rng_pool = new Array();
  1380. rng_pptr = 0;
  1381. var t;
  1382. if(navigator.appName == "Netscape" && navigator.appVersion < "5" && window.crypto) {
  1383. // Extract entropy (256 bits) from NS4 RNG if available
  1384. var z = window.crypto.random(32);
  1385. for(t = 0; t < z.length; ++t)
  1386. rng_pool[rng_pptr++] = z.charCodeAt(t) & 255;
  1387. }
  1388. while(rng_pptr < rng_psize) { // extract some randomness from Math.random()
  1389. t = Math.floor(65536 * Math.random());
  1390. rng_pool[rng_pptr++] = t >>> 8;
  1391. rng_pool[rng_pptr++] = t & 255;
  1392. }
  1393. rng_pptr = 0;
  1394. rng_seed_time();
  1395. //rng_seed_int(window.screenX);
  1396. //rng_seed_int(window.screenY);
  1397. }
  1398. function rng_get_byte() {
  1399. if(rng_state == null) {
  1400. rng_seed_time();
  1401. rng_state = prng_newstate();
  1402. rng_state.init(rng_pool);
  1403. for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr)
  1404. rng_pool[rng_pptr] = 0;
  1405. rng_pptr = 0;
  1406. //rng_pool = null;
  1407. }
  1408. // TODO: allow reseeding after first request
  1409. return rng_state.next();
  1410. }
  1411. function rng_get_bytes(ba) {
  1412. var i;
  1413. for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte();
  1414. }
  1415. function SecureRandom() {}
  1416. SecureRandom.prototype.nextBytes = rng_get_bytes;
  1417. // Depends on jsbn.js and rng.js
  1418. // Version 1.1: support utf-8 encoding in pkcs1pad2
  1419. // convert a (hex) string to a bignum object
  1420. function parseBigInt(str,r) {
  1421. return new BigInteger(str,r);
  1422. }
  1423. function linebrk(s,n) {
  1424. var ret = "";
  1425. var i = 0;
  1426. while(i + n < s.length) {
  1427. ret += s.substring(i,i+n) + "\n";
  1428. i += n;
  1429. }
  1430. return ret + s.substring(i,s.length);
  1431. }
  1432. function byte2Hex(b) {
  1433. if(b < 0x10)
  1434. return "0" + b.toString(16);
  1435. else
  1436. return b.toString(16);
  1437. }
  1438. // PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint
  1439. function pkcs1pad2(s,n) {
  1440. if(n < s.length + 11) { // TODO: fix for utf-8
  1441. console.error("Message too long for RSA");
  1442. return null;
  1443. }
  1444. var ba = new Array();
  1445. var i = s.length - 1;
  1446. while(i >= 0 && n > 0) {
  1447. var c = s.charCodeAt(i--);
  1448. if(c < 128) { // encode using utf-8
  1449. ba[--n] = c;
  1450. }
  1451. else if((c > 127) && (c < 2048)) {
  1452. ba[--n] = (c & 63) | 128;
  1453. ba[--n] = (c >> 6) | 192;
  1454. }
  1455. else {
  1456. ba[--n] = (c & 63) | 128;
  1457. ba[--n] = ((c >> 6) & 63) | 128;
  1458. ba[--n] = (c >> 12) | 224;
  1459. }
  1460. }
  1461. ba[--n] = 0;
  1462. var rng = new SecureRandom();
  1463. var x = new Array();
  1464. while(n > 2) { // random non-zero pad
  1465. x[0] = 0;
  1466. while(x[0] == 0) rng.nextBytes(x);
  1467. ba[--n] = x[0];
  1468. }
  1469. ba[--n] = 2;
  1470. ba[--n] = 0;
  1471. return new BigInteger(ba);
  1472. }
  1473. // "empty" RSA key constructor
  1474. function RSAKey() {
  1475. this.n = null;
  1476. this.e = 0;
  1477. this.d = null;
  1478. this.p = null;
  1479. this.q = null;
  1480. this.dmp1 = null;
  1481. this.dmq1 = null;
  1482. this.coeff = null;
  1483. }
  1484. // Set the public key fields N and e from hex strings
  1485. function RSASetPublic(N,E) {
  1486. if(N != null && E != null && N.length > 0 && E.length > 0) {
  1487. this.n = parseBigInt(N,16);
  1488. this.e = parseInt(E,16);
  1489. }
  1490. else
  1491. console.error("Invalid RSA public key");
  1492. }
  1493. // Perform raw public operation on "x": return x^e (mod n)
  1494. function RSADoPublic(x) {
  1495. return x.modPowInt(this.e, this.n);
  1496. }
  1497. // Return the PKCS#1 RSA encryption of "text" as an even-length hex string
  1498. function RSAEncrypt(text) {
  1499. var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3);
  1500. if(m == null) return null;
  1501. var c = this.doPublic(m);
  1502. if(c == null) return null;
  1503. var h = c.toString(16);
  1504. if((h.length & 1) == 0) return h; else return "0" + h;
  1505. }
  1506. // Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string
  1507. //function RSAEncryptB64(text) {
  1508. // var h = this.encrypt(text);
  1509. // if(h) return hex2b64(h); else return null;
  1510. //}
  1511. // protected
  1512. RSAKey.prototype.doPublic = RSADoPublic;
  1513. // public
  1514. RSAKey.prototype.setPublic = RSASetPublic;
  1515. RSAKey.prototype.encrypt = RSAEncrypt;
  1516. //RSAKey.prototype.encrypt_b64 = RSAEncryptB64;
  1517. // Depends on rsa.js and jsbn2.js
  1518. // Version 1.1: support utf-8 decoding in pkcs1unpad2
  1519. // Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext
  1520. function pkcs1unpad2(d,n) {
  1521. var b = d.toByteArray();
  1522. var i = 0;
  1523. while(i < b.length && b[i] == 0) ++i;
  1524. if(b.length-i != n-1 || b[i] != 2)
  1525. return null;
  1526. ++i;
  1527. while(b[i] != 0)
  1528. if(++i >= b.length) return null;
  1529. var ret = "";
  1530. while(++i < b.length) {
  1531. var c = b[i] & 255;
  1532. if(c < 128) { // utf-8 decode
  1533. ret += String.fromCharCode(c);
  1534. }
  1535. else if((c > 191) && (c < 224)) {
  1536. ret += String.fromCharCode(((c & 31) << 6) | (b[i+1] & 63));
  1537. ++i;
  1538. }
  1539. else {
  1540. ret += String.fromCharCode(((c & 15) << 12) | ((b[i+1] & 63) << 6) | (b[i+2] & 63));
  1541. i += 2;
  1542. }
  1543. }
  1544. return ret;
  1545. }
  1546. // Set the private key fields N, e, and d from hex strings
  1547. function RSASetPrivate(N,E,D) {
  1548. if(N != null && E != null && N.length > 0 && E.length > 0) {
  1549. this.n = parseBigInt(N,16);
  1550. this.e = parseInt(E,16);
  1551. this.d = parseBigInt(D,16);
  1552. }
  1553. else
  1554. console.error("Invalid RSA private key");
  1555. }
  1556. // Set the private key fields N, e, d and CRT params from hex strings
  1557. function RSASetPrivateEx(N,E,D,P,Q,DP,DQ,C) {
  1558. if(N != null && E != null && N.length > 0 && E.length > 0) {
  1559. this.n = parseBigInt(N,16);
  1560. this.e = parseInt(E,16);
  1561. this.d = parseBigInt(D,16);
  1562. this.p = parseBigInt(P,16);
  1563. this.q = parseBigInt(Q,16);
  1564. this.dmp1 = parseBigInt(DP,16);
  1565. this.dmq1 = parseBigInt(DQ,16);
  1566. this.coeff = parseBigInt(C,16);
  1567. }
  1568. else
  1569. console.error("Invalid RSA private key");
  1570. }
  1571. // Generate a new random private key B bits long, using public expt E
  1572. function RSAGenerate(B,E) {
  1573. var rng = new SecureRandom();
  1574. var qs = B>>1;
  1575. this.e = parseInt(E,16);
  1576. var ee = new BigInteger(E,16);
  1577. for(;;) {
  1578. for(;;) {
  1579. this.p = new BigInteger(B-qs,1,rng);
  1580. if(this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) break;
  1581. }
  1582. for(;;) {
  1583. this.q = new BigInteger(qs,1,rng);
  1584. if(this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) break;
  1585. }
  1586. if(this.p.compareTo(this.q) <= 0) {
  1587. var t = this.p;
  1588. this.p = this.q;
  1589. this.q = t;
  1590. }
  1591. var p1 = this.p.subtract(BigInteger.ONE);
  1592. var q1 = this.q.subtract(BigInteger.ONE);
  1593. var phi = p1.multiply(q1);
  1594. if(phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
  1595. this.n = this.p.multiply(this.q);
  1596. this.d = ee.modInverse(phi);
  1597. this.dmp1 = this.d.mod(p1);
  1598. this.dmq1 = this.d.mod(q1);
  1599. this.coeff = this.q.modInverse(this.p);
  1600. break;
  1601. }
  1602. }
  1603. }
  1604. // Perform raw private operation on "x": return x^d (mod n)
  1605. function RSADoPrivate(x) {
  1606. if(this.p == null || this.q == null)
  1607. return x.modPow(this.d, this.n);
  1608. // TODO: re-calculate any missing CRT params
  1609. var xp = x.mod(this.p).modPow(this.dmp1, this.p);
  1610. var xq = x.mod(this.q).modPow(this.dmq1, this.q);
  1611. while(xp.compareTo(xq) < 0)
  1612. xp = xp.add(this.p);
  1613. return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq);
  1614. }
  1615. // Return the PKCS#1 RSA decryption of "ctext".
  1616. // "ctext" is an even-length hex string and the output is a plain string.
  1617. function RSADecrypt(ctext) {
  1618. var c = parseBigInt(ctext, 16);
  1619. var m = this.doPrivate(c);
  1620. if(m == null) return null;
  1621. return pkcs1unpad2(m, (this.n.bitLength()+7)>>3);
  1622. }
  1623. // Return the PKCS#1 RSA decryption of "ctext".
  1624. // "ctext" is a Base64-encoded string and the output is a plain string.
  1625. //function RSAB64Decrypt(ctext) {
  1626. // var h = b64tohex(ctext);
  1627. // if(h) return this.decrypt(h); else return null;
  1628. //}
  1629. // protected
  1630. RSAKey.prototype.doPrivate = RSADoPrivate;
  1631. // public
  1632. RSAKey.prototype.setPrivate = RSASetPrivate;
  1633. RSAKey.prototype.setPrivateEx = RSASetPrivateEx;
  1634. RSAKey.prototype.generate = RSAGenerate;
  1635. RSAKey.prototype.decrypt = RSADecrypt;
  1636. //RSAKey.prototype.b64_decrypt = RSAB64Decrypt;
  1637. // Copyright (c) 2011 Kevin M Burns Jr.
  1638. // All Rights Reserved.
  1639. // See "LICENSE" for details.
  1640. //
  1641. // Extension to jsbn which adds facilities for asynchronous RSA key generation
  1642. // Primarily created to avoid execution timeout on mobile devices
  1643. //
  1644. // http://www-cs-students.stanford.edu/~tjw/jsbn/
  1645. //
  1646. // ---
  1647. (function(){
  1648. // Generate a new random private key B bits long, using public expt E
  1649. var RSAGenerateAsync = function (B, E, callback) {
  1650. //var rng = new SeededRandom();
  1651. var rng = new SecureRandom();
  1652. var qs = B >> 1;
  1653. this.e = parseInt(E, 16);
  1654. var ee = new BigInteger(E, 16);
  1655. var rsa = this;
  1656. // These functions have non-descript names because they were originally for(;;) loops.
  1657. // I don't know about cryptography to give them better names than loop1-4.
  1658. var loop1 = function() {
  1659. var loop4 = function() {
  1660. if (rsa.p.compareTo(rsa.q) <= 0) {
  1661. var t = rsa.p;
  1662. rsa.p = rsa.q;
  1663. rsa.q = t;
  1664. }
  1665. var p1 = rsa.p.subtract(BigInteger.ONE);
  1666. var q1 = rsa.q.subtract(BigInteger.ONE);
  1667. var phi = p1.multiply(q1);
  1668. if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
  1669. rsa.n = rsa.p.multiply(rsa.q);
  1670. rsa.d = ee.modInverse(phi);
  1671. rsa.dmp1 = rsa.d.mod(p1);
  1672. rsa.dmq1 = rsa.d.mod(q1);
  1673. rsa.coeff = rsa.q.modInverse(rsa.p);
  1674. setTimeout(function(){callback()},0); // escape
  1675. } else {
  1676. setTimeout(loop1,0);
  1677. }
  1678. };
  1679. var loop3 = function() {
  1680. rsa.q = nbi();
  1681. rsa.q.fromNumberAsync(qs, 1, rng, function(){
  1682. rsa.q.subtract(BigInteger.ONE).gcda(ee, function(r){
  1683. if (r.compareTo(BigInteger.ONE) == 0 && rsa.q.isProbablePrime(10)) {
  1684. setTimeout(loop4,0);
  1685. } else {
  1686. setTimeout(loop3,0);
  1687. }
  1688. });
  1689. });
  1690. };
  1691. var loop2 = function() {
  1692. rsa.p = nbi();
  1693. rsa.p.fromNumberAsync(B - qs, 1, rng, function(){
  1694. rsa.p.subtract(BigInteger.ONE).gcda(ee, function(r){
  1695. if (r.compareTo(BigInteger.ONE) == 0 && rsa.p.isProbablePrime(10)) {
  1696. setTimeout(loop3,0);
  1697. } else {
  1698. setTimeout(loop2,0);
  1699. }
  1700. });
  1701. });
  1702. };
  1703. setTimeout(loop2,0);
  1704. };
  1705. setTimeout(loop1,0);
  1706. };
  1707. RSAKey.prototype.generateAsync = RSAGenerateAsync;
  1708. // Public API method
  1709. var bnGCDAsync = function (a, callback) {
  1710. var x = (this.s < 0) ? this.negate() : this.clone();
  1711. var y = (a.s < 0) ? a.negate() : a.clone();
  1712. if (x.compareTo(y) < 0) {
  1713. var t = x;
  1714. x = y;
  1715. y = t;
  1716. }
  1717. var i = x.getLowestSetBit(),
  1718. g = y.getLowestSetBit();
  1719. if (g < 0) {
  1720. callback(x);
  1721. return;
  1722. }
  1723. if (i < g) g = i;
  1724. if (g > 0) {
  1725. x.rShiftTo(g, x);
  1726. y.rShiftTo(g, y);
  1727. }
  1728. // Workhorse of the algorithm, gets called 200 - 800 times per 512 bit keygen.
  1729. var gcda1 = function() {
  1730. if ((i = x.getLowestSetBit()) > 0){ x.rShiftTo(i, x); }
  1731. if ((i = y.getLowestSetBit()) > 0){ y.rShiftTo(i, y); }
  1732. if (x.compareTo(y) >= 0) {
  1733. x.subTo(y, x);
  1734. x.rShiftTo(1, x);
  1735. } else {
  1736. y.subTo(x, y);
  1737. y.rShiftTo(1, y);
  1738. }
  1739. if(!(x.signum() > 0)) {
  1740. if (g > 0) y.lShiftTo(g, y);
  1741. setTimeout(function(){callback(y)},0); // escape
  1742. } else {
  1743. setTimeout(gcda1,0);
  1744. }
  1745. };
  1746. setTimeout(gcda1,10);
  1747. };
  1748. BigInteger.prototype.gcda = bnGCDAsync;
  1749. // (protected) alternate constructor
  1750. var bnpFromNumberAsync = function (a,b,c,callback) {
  1751. if("number" == typeof b) {
  1752. if(a < 2) {
  1753. this.fromInt(1);
  1754. } else {
  1755. this.fromNumber(a,c);
  1756. if(!this.testBit(a-1)){
  1757. this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);
  1758. }
  1759. if(this.isEven()) {
  1760. this.dAddOffset(1,0);
  1761. }
  1762. var bnp = this;
  1763. var bnpfn1 = function(){
  1764. bnp.dAddOffset(2,0);
  1765. if(bnp.bitLength() > a) bnp.subTo(BigInteger.ONE.shiftLeft(a-1),bnp);
  1766. if(bnp.isProbablePrime(b)) {
  1767. setTimeout(function(){callback()},0); // escape
  1768. } else {
  1769. setTimeout(bnpfn1,0);
  1770. }
  1771. };
  1772. setTimeout(bnpfn1,0);
  1773. }
  1774. } else {
  1775. var x = new Array(), t = a&7;
  1776. x.length = (a>>3)+1;
  1777. b.nextBytes(x);
  1778. if(t > 0) x[0] &= ((1<<t)-1); else x[0] = 0;
  1779. this.fromString(x,256);
  1780. }
  1781. };
  1782. BigInteger.prototype.fromNumberAsync = bnpFromNumberAsync;
  1783. })();var b64map="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  1784. var b64pad="=";
  1785. function hex2b64(h) {
  1786. var i;
  1787. var c;
  1788. var ret = "";
  1789. for(i = 0; i+3 <= h.length; i+=3) {
  1790. c = parseInt(h.substring(i,i+3),16);
  1791. ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63);
  1792. }
  1793. if(i+1 == h.length) {
  1794. c = parseInt(h.substring(i,i+1),16);
  1795. ret += b64map.charAt(c << 2);
  1796. }
  1797. else if(i+2 == h.length) {
  1798. c = parseInt(h.substring(i,i+2),16);
  1799. ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4);
  1800. }
  1801. while((ret.length & 3) > 0) ret += b64pad;
  1802. return ret;
  1803. }
  1804. // convert a base64 string to hex
  1805. function b64tohex(s) {
  1806. var ret = ""
  1807. var i;
  1808. var k = 0; // b64 state, 0-3
  1809. var slop;
  1810. for(i = 0; i < s.length; ++i) {
  1811. if(s.charAt(i) == b64pad) break;
  1812. v = b64map.indexOf(s.charAt(i));
  1813. if(v < 0) continue;
  1814. if(k == 0) {
  1815. ret += int2char(v >> 2);
  1816. slop = v & 3;
  1817. k = 1;
  1818. }
  1819. else if(k == 1) {
  1820. ret += int2char((slop << 2) | (v >> 4));
  1821. slop = v & 0xf;
  1822. k = 2;
  1823. }
  1824. else if(k == 2) {
  1825. ret += int2char(slop);
  1826. ret += int2char(v >> 2);
  1827. slop = v & 3;
  1828. k = 3;
  1829. }
  1830. else {
  1831. ret += int2char((slop << 2) | (v >> 4));
  1832. ret += int2char(v & 0xf);
  1833. k = 0;
  1834. }
  1835. }
  1836. if(k == 1)
  1837. ret += int2char(slop << 2);
  1838. return ret;
  1839. }
  1840. // convert a base64 string to a byte/number array
  1841. function b64toBA(s) {
  1842. //piggyback on b64tohex for now, optimize later
  1843. var h = b64tohex(s);
  1844. var i;
  1845. var a = new Array();
  1846. for(i = 0; 2*i < h.length; ++i) {
  1847. a[i] = parseInt(h.substring(2*i,2*i+2),16);
  1848. }
  1849. return a;
  1850. }
  1851. /*! asn1-1.0.2.js (c) 2013 Kenji Urushima | kjur.github.com/jsrsasign/license
  1852. */
  1853. var JSX = JSX || {};
  1854. JSX.env = JSX.env || {};
  1855. var L = JSX, OP = Object.prototype, FUNCTION_TOSTRING = '[object Function]',ADD = ["toString", "valueOf"];
  1856. JSX.env.parseUA = function(agent) {
  1857. var numberify = function(s) {
  1858. var c = 0;
  1859. return parseFloat(s.replace(/\./g, function() {
  1860. return (c++ == 1) ? '' : '.';
  1861. }));
  1862. },
  1863. nav = navigator,
  1864. o = {
  1865. ie: 0,
  1866. opera: 0,
  1867. gecko: 0,
  1868. webkit: 0,
  1869. chrome: 0,
  1870. mobile: null,
  1871. air: 0,
  1872. ipad: 0,
  1873. iphone: 0,
  1874. ipod: 0,
  1875. ios: null,
  1876. android: 0,
  1877. webos: 0,
  1878. caja: nav && nav.cajaVersion,
  1879. secure: false,
  1880. os: null
  1881. },
  1882. ua = agent || (navigator && navigator.userAgent),
  1883. loc = window && window.location,
  1884. href = loc && loc.href,
  1885. m;
  1886. o.secure = href && (href.toLowerCase().indexOf("https") === 0);
  1887. if (ua) {
  1888. if ((/windows|win32/i).test(ua)) {
  1889. o.os = 'windows';
  1890. } else if ((/macintosh/i).test(ua)) {
  1891. o.os = 'macintosh';
  1892. } else if ((/rhino/i).test(ua)) {
  1893. o.os = 'rhino';
  1894. }
  1895. if ((/KHTML/).test(ua)) {
  1896. o.webkit = 1;
  1897. }
  1898. m = ua.match(/AppleWebKit\/([^\s]*)/);
  1899. if (m && m[1]) {
  1900. o.webkit = numberify(m[1]);
  1901. if (/ Mobile\//.test(ua)) {
  1902. o.mobile = 'Apple'; // iPhone or iPod Touch
  1903. m = ua.match(/OS ([^\s]*)/);
  1904. if (m && m[1]) {
  1905. m = numberify(m[1].replace('_', '.'));
  1906. }
  1907. o.ios = m;
  1908. o.ipad = o.ipod = o.iphone = 0;
  1909. m = ua.match(/iPad|iPod|iPhone/);
  1910. if (m && m[0]) {
  1911. o[m[0].toLowerCase()] = o.ios;
  1912. }
  1913. } else {
  1914. m = ua.match(/NokiaN[^\/]*|Android \d\.\d|webOS\/\d\.\d/);
  1915. if (m) {
  1916. o.mobile = m[0];
  1917. }
  1918. if (/webOS/.test(ua)) {
  1919. o.mobile = 'WebOS';
  1920. m = ua.match(/webOS\/([^\s]*);/);
  1921. if (m && m[1]) {
  1922. o.webos = numberify(m[1]);
  1923. }
  1924. }
  1925. if (/ Android/.test(ua)) {
  1926. o.mobile = 'Android';
  1927. m = ua.match(/Android ([^\s]*);/);
  1928. if (m && m[1]) {
  1929. o.android = numberify(m[1]);
  1930. }
  1931. }
  1932. }
  1933. m = ua.match(/Chrome\/([^\s]*)/);
  1934. if (m && m[1]) {
  1935. o.chrome = numberify(m[1]); // Chrome
  1936. } else {
  1937. m = ua.match(/AdobeAIR\/([^\s]*)/);
  1938. if (m) {
  1939. o.air = m[0]; // Adobe AIR 1.0 or better
  1940. }
  1941. }
  1942. }
  1943. if (!o.webkit) {
  1944. m = ua.match(/Opera[\s\/]([^\s]*)/);
  1945. if (m && m[1]) {
  1946. o.opera = numberify(m[1]);
  1947. m = ua.match(/Version\/([^\s]*)/);
  1948. if (m && m[1]) {
  1949. o.opera = numberify(m[1]); // opera 10+
  1950. }
  1951. m = ua.match(/Opera Mini[^;]*/);
  1952. if (m) {
  1953. o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316
  1954. }
  1955. } else { // not opera or webkit
  1956. m = ua.match(/MSIE\s([^;]*)/);
  1957. if (m && m[1]) {
  1958. o.ie = numberify(m[1]);
  1959. } else { // not opera, webkit, or ie
  1960. m = ua.match(/Gecko\/([^\s]*)/);
  1961. if (m) {
  1962. o.gecko = 1; // Gecko detected, look for revision
  1963. m = ua.match(/rv:([^\s\)]*)/);
  1964. if (m && m[1]) {
  1965. o.gecko = numberify(m[1]);
  1966. }
  1967. }
  1968. }
  1969. }
  1970. }
  1971. }
  1972. return o;
  1973. };
  1974. JSX.env.ua = JSX.env.parseUA();
  1975. JSX.isFunction = function(o) {
  1976. return (typeof o === 'function') || OP.toString.apply(o) === FUNCTION_TOSTRING;
  1977. };
  1978. JSX._IEEnumFix = (JSX.env.ua.ie) ? function(r, s) {
  1979. var i, fname, f;
  1980. for (i=0;i<ADD.length;i=i+1) {
  1981. fname = ADD[i];
  1982. f = s[fname];
  1983. if (L.isFunction(f) && f!=OP[fname]) {
  1984. r[fname]=f;
  1985. }
  1986. }
  1987. } : function(){};
  1988. JSX.extend = function(subc, superc, overrides) {
  1989. if (!superc||!subc) {
  1990. throw new Error("extend failed, please check that " +
  1991. "all dependencies are included.");
  1992. }
  1993. var F = function() {}, i;
  1994. F.prototype=superc.prototype;
  1995. subc.prototype=new F();
  1996. subc.prototype.constructor=subc;
  1997. subc.superclass=superc.prototype;
  1998. if (superc.prototype.constructor == OP.constructor) {
  1999. superc.prototype.constructor=superc;
  2000. }
  2001. if (overrides) {
  2002. for (i in overrides) {
  2003. if (L.hasOwnProperty(overrides, i)) {
  2004. subc.prototype[i]=overrides[i];
  2005. }
  2006. }
  2007. L._IEEnumFix(subc.prototype, overrides);
  2008. }
  2009. };
  2010. /*
  2011. * asn1.js - ASN.1 DER encoder classes
  2012. *
  2013. * Copyright (c) 2013 Kenji Urushima (kenji.urushima@gmail.com)
  2014. *
  2015. * This software is licensed under the terms of the MIT License.
  2016. * http://kjur.github.com/jsrsasign/license
  2017. *
  2018. * The above copyright and license notice shall be
  2019. * included in all copies or substantial portions of the Software.
  2020. */
  2021. /**
  2022. * @fileOverview
  2023. * @name asn1-1.0.js
  2024. * @author Kenji Urushima kenji.urushima@gmail.com
  2025. * @version 1.0.2 (2013-May-30)
  2026. * @since 2.1
  2027. * @license <a href="http://kjur.github.io/jsrsasign/license/">MIT License</a>
  2028. */
  2029. /**
  2030. * kjur's class library name space
  2031. * <p>
  2032. * This name space provides following name spaces:
  2033. * <ul>
  2034. * <li>{@link KJUR.asn1} - ASN.1 primitive hexadecimal encoder</li>
  2035. * <li>{@link KJUR.asn1.x509} - ASN.1 structure for X.509 certificate and CRL</li>
  2036. * <li>{@link KJUR.crypto} - Java Cryptographic Extension(JCE) style MessageDigest/Signature
  2037. * class and utilities</li>
  2038. * </ul>
  2039. * </p>
  2040. * NOTE: Please ignore method summary and document of this namespace. This caused by a bug of jsdoc2.
  2041. * @name KJUR
  2042. * @namespace kjur's class library name space
  2043. */
  2044. if (typeof KJUR == "undefined" || !KJUR) KJUR = {};
  2045. /**
  2046. * kjur's ASN.1 class library name space
  2047. * <p>
  2048. * This is ITU-T X.690 ASN.1 DER encoder class library and
  2049. * class structure and methods is very similar to
  2050. * org.bouncycastle.asn1 package of
  2051. * well known BouncyCaslte Cryptography Library.
  2052. *
  2053. * <h4>PROVIDING ASN.1 PRIMITIVES</h4>
  2054. * Here are ASN.1 DER primitive classes.
  2055. * <ul>
  2056. * <li>{@link KJUR.asn1.DERBoolean}</li>
  2057. * <li>{@link KJUR.asn1.DERInteger}</li>
  2058. * <li>{@link KJUR.asn1.DERBitString}</li>
  2059. * <li>{@link KJUR.asn1.DEROctetString}</li>
  2060. * <li>{@link KJUR.asn1.DERNull}</li>
  2061. * <li>{@link KJUR.asn1.DERObjectIdentifier}</li>
  2062. * <li>{@link KJUR.asn1.DERUTF8String}</li>
  2063. * <li>{@link KJUR.asn1.DERNumericString}</li>
  2064. * <li>{@link KJUR.asn1.DERPrintableString}</li>
  2065. * <li>{@link KJUR.asn1.DERTeletexString}</li>
  2066. * <li>{@link KJUR.asn1.DERIA5String}</li>
  2067. * <li>{@link KJUR.asn1.DERUTCTime}</li>
  2068. * <li>{@link KJUR.asn1.DERGeneralizedTime}</li>
  2069. * <li>{@link KJUR.asn1.DERSequence}</li>
  2070. * <li>{@link KJUR.asn1.DERSet}</li>
  2071. * </ul>
  2072. *
  2073. * <h4>OTHER ASN.1 CLASSES</h4>
  2074. * <ul>
  2075. * <li>{@link KJUR.asn1.ASN1Object}</li>
  2076. * <li>{@link KJUR.asn1.DERAbstractString}</li>
  2077. * <li>{@link KJUR.asn1.DERAbstractTime}</li>
  2078. * <li>{@link KJUR.asn1.DERAbstractStructured}</li>
  2079. * <li>{@link KJUR.asn1.DERTaggedObject}</li>
  2080. * </ul>
  2081. * </p>
  2082. * NOTE: Please ignore method summary and document of this namespace. This caused by a bug of jsdoc2.
  2083. * @name KJUR.asn1
  2084. * @namespace
  2085. */
  2086. if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) KJUR.asn1 = {};
  2087. /**
  2088. * ASN1 utilities class
  2089. * @name KJUR.asn1.ASN1Util
  2090. * @classs ASN1 utilities class
  2091. * @since asn1 1.0.2
  2092. */
  2093. KJUR.asn1.ASN1Util = new function() {
  2094. this.integerToByteHex = function(i) {
  2095. var h = i.toString(16);
  2096. if ((h.length % 2) == 1) h = '0' + h;
  2097. return h;
  2098. };
  2099. this.bigIntToMinTwosComplementsHex = function(bigIntegerValue) {
  2100. var h = bigIntegerValue.toString(16);
  2101. if (h.substr(0, 1) != '-') {
  2102. if (h.length % 2 == 1) {
  2103. h = '0' + h;
  2104. } else {
  2105. if (! h.match(/^[0-7]/)) {
  2106. h = '00' + h;
  2107. }
  2108. }
  2109. } else {
  2110. var hPos = h.substr(1);
  2111. var xorLen = hPos.length;
  2112. if (xorLen % 2 == 1) {
  2113. xorLen += 1;
  2114. } else {
  2115. if (! h.match(/^[0-7]/)) {
  2116. xorLen += 2;
  2117. }
  2118. }
  2119. var hMask = '';
  2120. for (var i = 0; i < xorLen; i++) {
  2121. hMask += 'f';
  2122. }
  2123. var biMask = new BigInteger(hMask, 16);
  2124. var biNeg = biMask.xor(bigIntegerValue).add(BigInteger.ONE);
  2125. h = biNeg.toString(16).replace(/^-/, '');
  2126. }
  2127. return h;
  2128. };
  2129. /**
  2130. * get PEM string from hexadecimal data and header string
  2131. * @name getPEMStringFromHex
  2132. * @memberOf KJUR.asn1.ASN1Util
  2133. * @function
  2134. * @param {String} dataHex hexadecimal string of PEM body
  2135. * @param {String} pemHeader PEM header string (ex. 'RSA PRIVATE KEY')
  2136. * @return {String} PEM formatted string of input data
  2137. * @description
  2138. * @example
  2139. * var pem = KJUR.asn1.ASN1Util.getPEMStringFromHex('616161', 'RSA PRIVATE KEY');
  2140. * // value of pem will be:
  2141. * -----BEGIN PRIVATE KEY-----
  2142. * YWFh
  2143. * -----END PRIVATE KEY-----
  2144. */
  2145. this.getPEMStringFromHex = function(dataHex, pemHeader) {
  2146. var dataWA = CryptoJS.enc.Hex.parse(dataHex);
  2147. var dataB64 = CryptoJS.enc.Base64.stringify(dataWA);
  2148. var pemBody = dataB64.replace(/(.{64})/g, "$1\r\n");
  2149. pemBody = pemBody.replace(/\r\n$/, '');
  2150. return "-----BEGIN " + pemHeader + "-----\r\n" +
  2151. pemBody +
  2152. "\r\n-----END " + pemHeader + "-----\r\n";
  2153. };
  2154. };
  2155. // ********************************************************************
  2156. // Abstract ASN.1 Classes
  2157. // ********************************************************************
  2158. // ********************************************************************
  2159. /**
  2160. * base class for ASN.1 DER encoder object
  2161. * @name KJUR.asn1.ASN1Object
  2162. * @class base class for ASN.1 DER encoder object
  2163. * @property {Boolean} isModified flag whether internal data was changed
  2164. * @property {String} hTLV hexadecimal string of ASN.1 TLV
  2165. * @property {String} hT hexadecimal string of ASN.1 TLV tag(T)
  2166. * @property {String} hL hexadecimal string of ASN.1 TLV length(L)
  2167. * @property {String} hV hexadecimal string of ASN.1 TLV value(V)
  2168. * @description
  2169. */
  2170. KJUR.asn1.ASN1Object = function() {
  2171. var isModified = true;
  2172. var hTLV = null;
  2173. var hT = '00'
  2174. var hL = '00';
  2175. var hV = '';
  2176. /**
  2177. * get hexadecimal ASN.1 TLV length(L) bytes from TLV value(V)
  2178. * @name getLengthHexFromValue
  2179. * @memberOf KJUR.asn1.ASN1Object
  2180. * @function
  2181. * @return {String} hexadecimal string of ASN.1 TLV length(L)
  2182. */
  2183. this.getLengthHexFromValue = function() {
  2184. if (typeof this.hV == "undefined" || this.hV == null) {
  2185. throw "this.hV is null or undefined.";
  2186. }
  2187. if (this.hV.length % 2 == 1) {
  2188. throw "value hex must be even length: n=" + hV.length + ",v=" + this.hV;
  2189. }
  2190. var n = this.hV.length / 2;
  2191. var hN = n.toString(16);
  2192. if (hN.length % 2 == 1) {
  2193. hN = "0" + hN;
  2194. }
  2195. if (n < 128) {
  2196. return hN;
  2197. } else {
  2198. var hNlen = hN.length / 2;
  2199. if (hNlen > 15) {
  2200. throw "ASN.1 length too long to represent by 8x: n = " + n.toString(16);
  2201. }
  2202. var head = 128 + hNlen;
  2203. return head.toString(16) + hN;
  2204. }
  2205. };
  2206. /**
  2207. * get hexadecimal string of ASN.1 TLV bytes
  2208. * @name getEncodedHex
  2209. * @memberOf KJUR.asn1.ASN1Object
  2210. * @function
  2211. * @return {String} hexadecimal string of ASN.1 TLV
  2212. */
  2213. this.getEncodedHex = function() {
  2214. if (this.hTLV == null || this.isModified) {
  2215. this.hV = this.getFreshValueHex();
  2216. this.hL = this.getLengthHexFromValue();
  2217. this.hTLV = this.hT + this.hL + this.hV;
  2218. this.isModified = false;
  2219. //console.error("first time: " + this.hTLV);
  2220. }
  2221. return this.hTLV;
  2222. };
  2223. /**
  2224. * get hexadecimal string of ASN.1 TLV value(V) bytes
  2225. * @name getValueHex
  2226. * @memberOf KJUR.asn1.ASN1Object
  2227. * @function
  2228. * @return {String} hexadecimal string of ASN.1 TLV value(V) bytes
  2229. */
  2230. this.getValueHex = function() {
  2231. this.getEncodedHex();
  2232. return this.hV;
  2233. }
  2234. this.getFreshValueHex = function() {
  2235. return '';
  2236. };
  2237. };
  2238. // == BEGIN DERAbstractString ================================================
  2239. /**
  2240. * base class for ASN.1 DER string classes
  2241. * @name KJUR.asn1.DERAbstractString
  2242. * @class base class for ASN.1 DER string classes
  2243. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  2244. * @property {String} s internal string of value
  2245. * @extends KJUR.asn1.ASN1Object
  2246. * @description
  2247. * <br/>
  2248. * As for argument 'params' for constructor, you can specify one of
  2249. * following properties:
  2250. * <ul>
  2251. * <li>str - specify initial ASN.1 value(V) by a string</li>
  2252. * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  2253. * </ul>
  2254. * NOTE: 'params' can be omitted.
  2255. */
  2256. KJUR.asn1.DERAbstractString = function(params) {
  2257. KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
  2258. var s = null;
  2259. var hV = null;
  2260. /**
  2261. * get string value of this string object
  2262. * @name getString
  2263. * @memberOf KJUR.asn1.DERAbstractString
  2264. * @function
  2265. * @return {String} string value of this string object
  2266. */
  2267. this.getString = function() {
  2268. return this.s;
  2269. };
  2270. /**
  2271. * set value by a string
  2272. * @name setString
  2273. * @memberOf KJUR.asn1.DERAbstractString
  2274. * @function
  2275. * @param {String} newS value by a string to set
  2276. */
  2277. this.setString = function(newS) {
  2278. this.hTLV = null;
  2279. this.isModified = true;
  2280. this.s = newS;
  2281. this.hV = stohex(this.s);
  2282. };
  2283. /**
  2284. * set value by a hexadecimal string
  2285. * @name setStringHex
  2286. * @memberOf KJUR.asn1.DERAbstractString
  2287. * @function
  2288. * @param {String} newHexString value by a hexadecimal string to set
  2289. */
  2290. this.setStringHex = function(newHexString) {
  2291. this.hTLV = null;
  2292. this.isModified = true;
  2293. this.s = null;
  2294. this.hV = newHexString;
  2295. };
  2296. this.getFreshValueHex = function() {
  2297. return this.hV;
  2298. };
  2299. if (typeof params != "undefined") {
  2300. if (typeof params['str'] != "undefined") {
  2301. this.setString(params['str']);
  2302. } else if (typeof params['hex'] != "undefined") {
  2303. this.setStringHex(params['hex']);
  2304. }
  2305. }
  2306. };
  2307. JSX.extend(KJUR.asn1.DERAbstractString, KJUR.asn1.ASN1Object);
  2308. // == END DERAbstractString ================================================
  2309. // == BEGIN DERAbstractTime ==================================================
  2310. /**
  2311. * base class for ASN.1 DER Generalized/UTCTime class
  2312. * @name KJUR.asn1.DERAbstractTime
  2313. * @class base class for ASN.1 DER Generalized/UTCTime class
  2314. * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'})
  2315. * @extends KJUR.asn1.ASN1Object
  2316. * @description
  2317. * @see KJUR.asn1.ASN1Object - superclass
  2318. */
  2319. KJUR.asn1.DERAbstractTime = function(params) {
  2320. KJUR.asn1.DERAbstractTime.superclass.constructor.call(this);
  2321. var s = null;
  2322. var date = null;
  2323. // --- PRIVATE METHODS --------------------
  2324. this.localDateToUTC = function(d) {
  2325. utc = d.getTime() + (d.getTimezoneOffset() * 60000);
  2326. var utcDate = new Date(utc);
  2327. return utcDate;
  2328. };
  2329. this.formatDate = function(dateObject, type) {
  2330. var pad = this.zeroPadding;
  2331. var d = this.localDateToUTC(dateObject);
  2332. var year = String(d.getFullYear());
  2333. if (type == 'utc') year = year.substr(2, 2);
  2334. var month = pad(String(d.getMonth() + 1), 2);
  2335. var day = pad(String(d.getDate()), 2);
  2336. var hour = pad(String(d.getHours()), 2);
  2337. var min = pad(String(d.getMinutes()), 2);
  2338. var sec = pad(String(d.getSeconds()), 2);
  2339. return year + month + day + hour + min + sec + 'Z';
  2340. };
  2341. this.zeroPadding = function(s, len) {
  2342. if (s.length >= len) return s;
  2343. return new Array(len - s.length + 1).join('0') + s;
  2344. };
  2345. // --- PUBLIC METHODS --------------------
  2346. /**
  2347. * get string value of this string object
  2348. * @name getString
  2349. * @memberOf KJUR.asn1.DERAbstractTime
  2350. * @function
  2351. * @return {String} string value of this time object
  2352. */
  2353. this.getString = function() {
  2354. return this.s;
  2355. };
  2356. /**
  2357. * set value by a string
  2358. * @name setString
  2359. * @memberOf KJUR.asn1.DERAbstractTime
  2360. * @function
  2361. * @param {String} newS value by a string to set such like "130430235959Z"
  2362. */
  2363. this.setString = function(newS) {
  2364. this.hTLV = null;
  2365. this.isModified = true;
  2366. this.s = newS;
  2367. this.hV = stohex(this.s);
  2368. };
  2369. /**
  2370. * set value by a Date object
  2371. * @name setByDateValue
  2372. * @memberOf KJUR.asn1.DERAbstractTime
  2373. * @function
  2374. * @param {Integer} year year of date (ex. 2013)
  2375. * @param {Integer} month month of date between 1 and 12 (ex. 12)
  2376. * @param {Integer} day day of month
  2377. * @param {Integer} hour hours of date
  2378. * @param {Integer} min minutes of date
  2379. * @param {Integer} sec seconds of date
  2380. */
  2381. this.setByDateValue = function(year, month, day, hour, min, sec) {
  2382. var dateObject = new Date(Date.UTC(year, month - 1, day, hour, min, sec, 0));
  2383. this.setByDate(dateObject);
  2384. };
  2385. this.getFreshValueHex = function() {
  2386. return this.hV;
  2387. };
  2388. };
  2389. JSX.extend(KJUR.asn1.DERAbstractTime, KJUR.asn1.ASN1Object);
  2390. // == END DERAbstractTime ==================================================
  2391. // == BEGIN DERAbstractStructured ============================================
  2392. /**
  2393. * base class for ASN.1 DER structured class
  2394. * @name KJUR.asn1.DERAbstractStructured
  2395. * @class base class for ASN.1 DER structured class
  2396. * @property {Array} asn1Array internal array of ASN1Object
  2397. * @extends KJUR.asn1.ASN1Object
  2398. * @description
  2399. * @see KJUR.asn1.ASN1Object - superclass
  2400. */
  2401. KJUR.asn1.DERAbstractStructured = function(params) {
  2402. KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
  2403. var asn1Array = null;
  2404. /**
  2405. * set value by array of ASN1Object
  2406. * @name setByASN1ObjectArray
  2407. * @memberOf KJUR.asn1.DERAbstractStructured
  2408. * @function
  2409. * @param {array} asn1ObjectArray array of ASN1Object to set
  2410. */
  2411. this.setByASN1ObjectArray = function(asn1ObjectArray) {
  2412. this.hTLV = null;
  2413. this.isModified = true;
  2414. this.asn1Array = asn1ObjectArray;
  2415. };
  2416. /**
  2417. * append an ASN1Object to internal array
  2418. * @name appendASN1Object
  2419. * @memberOf KJUR.asn1.DERAbstractStructured
  2420. * @function
  2421. * @param {ASN1Object} asn1Object to add
  2422. */
  2423. this.appendASN1Object = function(asn1Object) {
  2424. this.hTLV = null;
  2425. this.isModified = true;
  2426. this.asn1Array.push(asn1Object);
  2427. };
  2428. this.asn1Array = new Array();
  2429. if (typeof params != "undefined") {
  2430. if (typeof params['array'] != "undefined") {
  2431. this.asn1Array = params['array'];
  2432. }
  2433. }
  2434. };
  2435. JSX.extend(KJUR.asn1.DERAbstractStructured, KJUR.asn1.ASN1Object);
  2436. // ********************************************************************
  2437. // ASN.1 Object Classes
  2438. // ********************************************************************
  2439. // ********************************************************************
  2440. /**
  2441. * class for ASN.1 DER Boolean
  2442. * @name KJUR.asn1.DERBoolean
  2443. * @class class for ASN.1 DER Boolean
  2444. * @extends KJUR.asn1.ASN1Object
  2445. * @description
  2446. * @see KJUR.asn1.ASN1Object - superclass
  2447. */
  2448. KJUR.asn1.DERBoolean = function() {
  2449. KJUR.asn1.DERBoolean.superclass.constructor.call(this);
  2450. this.hT = "01";
  2451. this.hTLV = "0101ff";
  2452. };
  2453. JSX.extend(KJUR.asn1.DERBoolean, KJUR.asn1.ASN1Object);
  2454. // ********************************************************************
  2455. /**
  2456. * class for ASN.1 DER Integer
  2457. * @name KJUR.asn1.DERInteger
  2458. * @class class for ASN.1 DER Integer
  2459. * @extends KJUR.asn1.ASN1Object
  2460. * @description
  2461. * <br/>
  2462. * As for argument 'params' for constructor, you can specify one of
  2463. * following properties:
  2464. * <ul>
  2465. * <li>int - specify initial ASN.1 value(V) by integer value</li>
  2466. * <li>bigint - specify initial ASN.1 value(V) by BigInteger object</li>
  2467. * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  2468. * </ul>
  2469. * NOTE: 'params' can be omitted.
  2470. */
  2471. KJUR.asn1.DERInteger = function(params) {
  2472. KJUR.asn1.DERInteger.superclass.constructor.call(this);
  2473. this.hT = "02";
  2474. /**
  2475. * set value by Tom Wu's BigInteger object
  2476. * @name setByBigInteger
  2477. * @memberOf KJUR.asn1.DERInteger
  2478. * @function
  2479. * @param {BigInteger} bigIntegerValue to set
  2480. */
  2481. this.setByBigInteger = function(bigIntegerValue) {
  2482. this.hTLV = null;
  2483. this.isModified = true;
  2484. this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
  2485. };
  2486. /**
  2487. * set value by integer value
  2488. * @name setByInteger
  2489. * @memberOf KJUR.asn1.DERInteger
  2490. * @function
  2491. * @param {Integer} integer value to set
  2492. */
  2493. this.setByInteger = function(intValue) {
  2494. var bi = new BigInteger(String(intValue), 10);
  2495. this.setByBigInteger(bi);
  2496. };
  2497. /**
  2498. * set value by integer value
  2499. * @name setValueHex
  2500. * @memberOf KJUR.asn1.DERInteger
  2501. * @function
  2502. * @param {String} hexadecimal string of integer value
  2503. * @description
  2504. * <br/>
  2505. * NOTE: Value shall be represented by minimum octet length of
  2506. * two's complement representation.
  2507. */
  2508. this.setValueHex = function(newHexString) {
  2509. this.hV = newHexString;
  2510. };
  2511. this.getFreshValueHex = function() {
  2512. return this.hV;
  2513. };
  2514. if (typeof params != "undefined") {
  2515. if (typeof params['bigint'] != "undefined") {
  2516. this.setByBigInteger(params['bigint']);
  2517. } else if (typeof params['int'] != "undefined") {
  2518. this.setByInteger(params['int']);
  2519. } else if (typeof params['hex'] != "undefined") {
  2520. this.setValueHex(params['hex']);
  2521. }
  2522. }
  2523. };
  2524. JSX.extend(KJUR.asn1.DERInteger, KJUR.asn1.ASN1Object);
  2525. // ********************************************************************
  2526. /**
  2527. * class for ASN.1 DER encoded BitString primitive
  2528. * @name KJUR.asn1.DERBitString
  2529. * @class class for ASN.1 DER encoded BitString primitive
  2530. * @extends KJUR.asn1.ASN1Object
  2531. * @description
  2532. * <br/>
  2533. * As for argument 'params' for constructor, you can specify one of
  2534. * following properties:
  2535. * <ul>
  2536. * <li>bin - specify binary string (ex. '10111')</li>
  2537. * <li>array - specify array of boolean (ex. [true,false,true,true])</li>
  2538. * <li>hex - specify hexadecimal string of ASN.1 value(V) including unused bits</li>
  2539. * </ul>
  2540. * NOTE: 'params' can be omitted.
  2541. */
  2542. KJUR.asn1.DERBitString = function(params) {
  2543. KJUR.asn1.DERBitString.superclass.constructor.call(this);
  2544. this.hT = "03";
  2545. /**
  2546. * set ASN.1 value(V) by a hexadecimal string including unused bits
  2547. * @name setHexValueIncludingUnusedBits
  2548. * @memberOf KJUR.asn1.DERBitString
  2549. * @function
  2550. * @param {String} newHexStringIncludingUnusedBits
  2551. */
  2552. this.setHexValueIncludingUnusedBits = function(newHexStringIncludingUnusedBits) {
  2553. this.hTLV = null;
  2554. this.isModified = true;
  2555. this.hV = newHexStringIncludingUnusedBits;
  2556. };
  2557. /**
  2558. * set ASN.1 value(V) by unused bit and hexadecimal string of value
  2559. * @name setUnusedBitsAndHexValue
  2560. * @memberOf KJUR.asn1.DERBitString
  2561. * @function
  2562. * @param {Integer} unusedBits
  2563. * @param {String} hValue
  2564. */
  2565. this.setUnusedBitsAndHexValue = function(unusedBits, hValue) {
  2566. if (unusedBits < 0 || 7 < unusedBits) {
  2567. throw "unused bits shall be from 0 to 7: u = " + unusedBits;
  2568. }
  2569. var hUnusedBits = "0" + unusedBits;
  2570. this.hTLV = null;
  2571. this.isModified = true;
  2572. this.hV = hUnusedBits + hValue;
  2573. };
  2574. /**
  2575. * set ASN.1 DER BitString by binary string
  2576. * @name setByBinaryString
  2577. * @memberOf KJUR.asn1.DERBitString
  2578. * @function
  2579. * @param {String} binaryString binary value string (i.e. '10111')
  2580. * @description
  2581. * Its unused bits will be calculated automatically by length of
  2582. * 'binaryValue'. <br/>
  2583. * NOTE: Trailing zeros '0' will be ignored.
  2584. */
  2585. this.setByBinaryString = function(binaryString) {
  2586. binaryString = binaryString.replace(/0+$/, '');
  2587. var unusedBits = 8 - binaryString.length % 8;
  2588. if (unusedBits == 8) unusedBits = 0;
  2589. for (var i = 0; i <= unusedBits; i++) {
  2590. binaryString += '0';
  2591. }
  2592. var h = '';
  2593. for (var i = 0; i < binaryString.length - 1; i += 8) {
  2594. var b = binaryString.substr(i, 8);
  2595. var x = parseInt(b, 2).toString(16);
  2596. if (x.length == 1) x = '0' + x;
  2597. h += x;
  2598. }
  2599. this.hTLV = null;
  2600. this.isModified = true;
  2601. this.hV = '0' + unusedBits + h;
  2602. };
  2603. /**
  2604. * set ASN.1 TLV value(V) by an array of boolean
  2605. * @name setByBooleanArray
  2606. * @memberOf KJUR.asn1.DERBitString
  2607. * @function
  2608. * @param {array} booleanArray array of boolean (ex. [true, false, true])
  2609. * @description
  2610. * NOTE: Trailing falses will be ignored.
  2611. */
  2612. this.setByBooleanArray = function(booleanArray) {
  2613. var s = '';
  2614. for (var i = 0; i < booleanArray.length; i++) {
  2615. if (booleanArray[i] == true) {
  2616. s += '1';
  2617. } else {
  2618. s += '0';
  2619. }
  2620. }
  2621. this.setByBinaryString(s);
  2622. };
  2623. /**
  2624. * generate an array of false with specified length
  2625. * @name newFalseArray
  2626. * @memberOf KJUR.asn1.DERBitString
  2627. * @function
  2628. * @param {Integer} nLength length of array to generate
  2629. * @return {array} array of boolean faluse
  2630. * @description
  2631. * This static method may be useful to initialize boolean array.
  2632. */
  2633. this.newFalseArray = function(nLength) {
  2634. var a = new Array(nLength);
  2635. for (var i = 0; i < nLength; i++) {
  2636. a[i] = false;
  2637. }
  2638. return a;
  2639. };
  2640. this.getFreshValueHex = function() {
  2641. return this.hV;
  2642. };
  2643. if (typeof params != "undefined") {
  2644. if (typeof params['hex'] != "undefined") {
  2645. this.setHexValueIncludingUnusedBits(params['hex']);
  2646. } else if (typeof params['bin'] != "undefined") {
  2647. this.setByBinaryString(params['bin']);
  2648. } else if (typeof params['array'] != "undefined") {
  2649. this.setByBooleanArray(params['array']);
  2650. }
  2651. }
  2652. };
  2653. JSX.extend(KJUR.asn1.DERBitString, KJUR.asn1.ASN1Object);
  2654. // ********************************************************************
  2655. /**
  2656. * class for ASN.1 DER OctetString
  2657. * @name KJUR.asn1.DEROctetString
  2658. * @class class for ASN.1 DER OctetString
  2659. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  2660. * @extends KJUR.asn1.DERAbstractString
  2661. * @description
  2662. * @see KJUR.asn1.DERAbstractString - superclass
  2663. */
  2664. KJUR.asn1.DEROctetString = function(params) {
  2665. KJUR.asn1.DEROctetString.superclass.constructor.call(this, params);
  2666. this.hT = "04";
  2667. };
  2668. JSX.extend(KJUR.asn1.DEROctetString, KJUR.asn1.DERAbstractString);
  2669. // ********************************************************************
  2670. /**
  2671. * class for ASN.1 DER Null
  2672. * @name KJUR.asn1.DERNull
  2673. * @class class for ASN.1 DER Null
  2674. * @extends KJUR.asn1.ASN1Object
  2675. * @description
  2676. * @see KJUR.asn1.ASN1Object - superclass
  2677. */
  2678. KJUR.asn1.DERNull = function() {
  2679. KJUR.asn1.DERNull.superclass.constructor.call(this);
  2680. this.hT = "05";
  2681. this.hTLV = "0500";
  2682. };
  2683. JSX.extend(KJUR.asn1.DERNull, KJUR.asn1.ASN1Object);
  2684. // ********************************************************************
  2685. /**
  2686. * class for ASN.1 DER ObjectIdentifier
  2687. * @name KJUR.asn1.DERObjectIdentifier
  2688. * @class class for ASN.1 DER ObjectIdentifier
  2689. * @param {Array} params associative array of parameters (ex. {'oid': '2.5.4.5'})
  2690. * @extends KJUR.asn1.ASN1Object
  2691. * @description
  2692. * <br/>
  2693. * As for argument 'params' for constructor, you can specify one of
  2694. * following properties:
  2695. * <ul>
  2696. * <li>oid - specify initial ASN.1 value(V) by a oid string (ex. 2.5.4.13)</li>
  2697. * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  2698. * </ul>
  2699. * NOTE: 'params' can be omitted.
  2700. */
  2701. KJUR.asn1.DERObjectIdentifier = function(params) {
  2702. var itox = function(i) {
  2703. var h = i.toString(16);
  2704. if (h.length == 1) h = '0' + h;
  2705. return h;
  2706. };
  2707. var roidtox = function(roid) {
  2708. var h = '';
  2709. var bi = new BigInteger(roid, 10);
  2710. var b = bi.toString(2);
  2711. var padLen = 7 - b.length % 7;
  2712. if (padLen == 7) padLen = 0;
  2713. var bPad = '';
  2714. for (var i = 0; i < padLen; i++) bPad += '0';
  2715. b = bPad + b;
  2716. for (var i = 0; i < b.length - 1; i += 7) {
  2717. var b8 = b.substr(i, 7);
  2718. if (i != b.length - 7) b8 = '1' + b8;
  2719. h += itox(parseInt(b8, 2));
  2720. }
  2721. return h;
  2722. }
  2723. KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this);
  2724. this.hT = "06";
  2725. /**
  2726. * set value by a hexadecimal string
  2727. * @name setValueHex
  2728. * @memberOf KJUR.asn1.DERObjectIdentifier
  2729. * @function
  2730. * @param {String} newHexString hexadecimal value of OID bytes
  2731. */
  2732. this.setValueHex = function(newHexString) {
  2733. this.hTLV = null;
  2734. this.isModified = true;
  2735. this.s = null;
  2736. this.hV = newHexString;
  2737. };
  2738. /**
  2739. * set value by a OID string
  2740. * @name setValueOidString
  2741. * @memberOf KJUR.asn1.DERObjectIdentifier
  2742. * @function
  2743. * @param {String} oidString OID string (ex. 2.5.4.13)
  2744. */
  2745. this.setValueOidString = function(oidString) {
  2746. if (! oidString.match(/^[0-9.]+$/)) {
  2747. throw "malformed oid string: " + oidString;
  2748. }
  2749. var h = '';
  2750. var a = oidString.split('.');
  2751. var i0 = parseInt(a[0]) * 40 + parseInt(a[1]);
  2752. h += itox(i0);
  2753. a.splice(0, 2);
  2754. for (var i = 0; i < a.length; i++) {
  2755. h += roidtox(a[i]);
  2756. }
  2757. this.hTLV = null;
  2758. this.isModified = true;
  2759. this.s = null;
  2760. this.hV = h;
  2761. };
  2762. /**
  2763. * set value by a OID name
  2764. * @name setValueName
  2765. * @memberOf KJUR.asn1.DERObjectIdentifier
  2766. * @function
  2767. * @param {String} oidName OID name (ex. 'serverAuth')
  2768. * @since 1.0.1
  2769. * @description
  2770. * OID name shall be defined in 'KJUR.asn1.x509.OID.name2oidList'.
  2771. * Otherwise raise error.
  2772. */
  2773. this.setValueName = function(oidName) {
  2774. if (typeof KJUR.asn1.x509.OID.name2oidList[oidName] != "undefined") {
  2775. var oid = KJUR.asn1.x509.OID.name2oidList[oidName];
  2776. this.setValueOidString(oid);
  2777. } else {
  2778. throw "DERObjectIdentifier oidName undefined: " + oidName;
  2779. }
  2780. };
  2781. this.getFreshValueHex = function() {
  2782. return this.hV;
  2783. };
  2784. if (typeof params != "undefined") {
  2785. if (typeof params['oid'] != "undefined") {
  2786. this.setValueOidString(params['oid']);
  2787. } else if (typeof params['hex'] != "undefined") {
  2788. this.setValueHex(params['hex']);
  2789. } else if (typeof params['name'] != "undefined") {
  2790. this.setValueName(params['name']);
  2791. }
  2792. }
  2793. };
  2794. JSX.extend(KJUR.asn1.DERObjectIdentifier, KJUR.asn1.ASN1Object);
  2795. // ********************************************************************
  2796. /**
  2797. * class for ASN.1 DER UTF8String
  2798. * @name KJUR.asn1.DERUTF8String
  2799. * @class class for ASN.1 DER UTF8String
  2800. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  2801. * @extends KJUR.asn1.DERAbstractString
  2802. * @description
  2803. * @see KJUR.asn1.DERAbstractString - superclass
  2804. */
  2805. KJUR.asn1.DERUTF8String = function(params) {
  2806. KJUR.asn1.DERUTF8String.superclass.constructor.call(this, params);
  2807. this.hT = "0c";
  2808. };
  2809. JSX.extend(KJUR.asn1.DERUTF8String, KJUR.asn1.DERAbstractString);
  2810. // ********************************************************************
  2811. /**
  2812. * class for ASN.1 DER NumericString
  2813. * @name KJUR.asn1.DERNumericString
  2814. * @class class for ASN.1 DER NumericString
  2815. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  2816. * @extends KJUR.asn1.DERAbstractString
  2817. * @description
  2818. * @see KJUR.asn1.DERAbstractString - superclass
  2819. */
  2820. KJUR.asn1.DERNumericString = function(params) {
  2821. KJUR.asn1.DERNumericString.superclass.constructor.call(this, params);
  2822. this.hT = "12";
  2823. };
  2824. JSX.extend(KJUR.asn1.DERNumericString, KJUR.asn1.DERAbstractString);
  2825. // ********************************************************************
  2826. /**
  2827. * class for ASN.1 DER PrintableString
  2828. * @name KJUR.asn1.DERPrintableString
  2829. * @class class for ASN.1 DER PrintableString
  2830. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  2831. * @extends KJUR.asn1.DERAbstractString
  2832. * @description
  2833. * @see KJUR.asn1.DERAbstractString - superclass
  2834. */
  2835. KJUR.asn1.DERPrintableString = function(params) {
  2836. KJUR.asn1.DERPrintableString.superclass.constructor.call(this, params);
  2837. this.hT = "13";
  2838. };
  2839. JSX.extend(KJUR.asn1.DERPrintableString, KJUR.asn1.DERAbstractString);
  2840. // ********************************************************************
  2841. /**
  2842. * class for ASN.1 DER TeletexString
  2843. * @name KJUR.asn1.DERTeletexString
  2844. * @class class for ASN.1 DER TeletexString
  2845. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  2846. * @extends KJUR.asn1.DERAbstractString
  2847. * @description
  2848. * @see KJUR.asn1.DERAbstractString - superclass
  2849. */
  2850. KJUR.asn1.DERTeletexString = function(params) {
  2851. KJUR.asn1.DERTeletexString.superclass.constructor.call(this, params);
  2852. this.hT = "14";
  2853. };
  2854. JSX.extend(KJUR.asn1.DERTeletexString, KJUR.asn1.DERAbstractString);
  2855. // ********************************************************************
  2856. /**
  2857. * class for ASN.1 DER IA5String
  2858. * @name KJUR.asn1.DERIA5String
  2859. * @class class for ASN.1 DER IA5String
  2860. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  2861. * @extends KJUR.asn1.DERAbstractString
  2862. * @description
  2863. * @see KJUR.asn1.DERAbstractString - superclass
  2864. */
  2865. KJUR.asn1.DERIA5String = function(params) {
  2866. KJUR.asn1.DERIA5String.superclass.constructor.call(this, params);
  2867. this.hT = "16";
  2868. };
  2869. JSX.extend(KJUR.asn1.DERIA5String, KJUR.asn1.DERAbstractString);
  2870. // ********************************************************************
  2871. /**
  2872. * class for ASN.1 DER UTCTime
  2873. * @name KJUR.asn1.DERUTCTime
  2874. * @class class for ASN.1 DER UTCTime
  2875. * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'})
  2876. * @extends KJUR.asn1.DERAbstractTime
  2877. * @description
  2878. * <br/>
  2879. * As for argument 'params' for constructor, you can specify one of
  2880. * following properties:
  2881. * <ul>
  2882. * <li>str - specify initial ASN.1 value(V) by a string (ex.'130430235959Z')</li>
  2883. * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  2884. * <li>date - specify Date object.</li>
  2885. * </ul>
  2886. * NOTE: 'params' can be omitted.
  2887. * <h4>EXAMPLES</h4>
  2888. * @example
  2889. * var d1 = new KJUR.asn1.DERUTCTime();
  2890. * d1.setString('130430125959Z');
  2891. *
  2892. * var d2 = new KJUR.asn1.DERUTCTime({'str': '130430125959Z'});
  2893. *
  2894. * var d3 = new KJUR.asn1.DERUTCTime({'date': new Date(Date.UTC(2015, 0, 31, 0, 0, 0, 0))});
  2895. */
  2896. KJUR.asn1.DERUTCTime = function(params) {
  2897. KJUR.asn1.DERUTCTime.superclass.constructor.call(this, params);
  2898. this.hT = "17";
  2899. /**
  2900. * set value by a Date object
  2901. * @name setByDate
  2902. * @memberOf KJUR.asn1.DERUTCTime
  2903. * @function
  2904. * @param {Date} dateObject Date object to set ASN.1 value(V)
  2905. */
  2906. this.setByDate = function(dateObject) {
  2907. this.hTLV = null;
  2908. this.isModified = true;
  2909. this.date = dateObject;
  2910. this.s = this.formatDate(this.date, 'utc');
  2911. this.hV = stohex(this.s);
  2912. };
  2913. if (typeof params != "undefined") {
  2914. if (typeof params['str'] != "undefined") {
  2915. this.setString(params['str']);
  2916. } else if (typeof params['hex'] != "undefined") {
  2917. this.setStringHex(params['hex']);
  2918. } else if (typeof params['date'] != "undefined") {
  2919. this.setByDate(params['date']);
  2920. }
  2921. }
  2922. };
  2923. JSX.extend(KJUR.asn1.DERUTCTime, KJUR.asn1.DERAbstractTime);
  2924. // ********************************************************************
  2925. /**
  2926. * class for ASN.1 DER GeneralizedTime
  2927. * @name KJUR.asn1.DERGeneralizedTime
  2928. * @class class for ASN.1 DER GeneralizedTime
  2929. * @param {Array} params associative array of parameters (ex. {'str': '20130430235959Z'})
  2930. * @extends KJUR.asn1.DERAbstractTime
  2931. * @description
  2932. * <br/>
  2933. * As for argument 'params' for constructor, you can specify one of
  2934. * following properties:
  2935. * <ul>
  2936. * <li>str - specify initial ASN.1 value(V) by a string (ex.'20130430235959Z')</li>
  2937. * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  2938. * <li>date - specify Date object.</li>
  2939. * </ul>
  2940. * NOTE: 'params' can be omitted.
  2941. */
  2942. KJUR.asn1.DERGeneralizedTime = function(params) {
  2943. KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this, params);
  2944. this.hT = "18";
  2945. /**
  2946. * set value by a Date object
  2947. * @name setByDate
  2948. * @memberOf KJUR.asn1.DERGeneralizedTime
  2949. * @function
  2950. * @param {Date} dateObject Date object to set ASN.1 value(V)
  2951. * @example
  2952. * When you specify UTC time, use 'Date.UTC' method like this:<br/>
  2953. * var o = new DERUTCTime();
  2954. * var date = new Date(Date.UTC(2015, 0, 31, 23, 59, 59, 0)); #2015JAN31 23:59:59
  2955. * o.setByDate(date);
  2956. */
  2957. this.setByDate = function(dateObject) {
  2958. this.hTLV = null;
  2959. this.isModified = true;
  2960. this.date = dateObject;
  2961. this.s = this.formatDate(this.date, 'gen');
  2962. this.hV = stohex(this.s);
  2963. };
  2964. if (typeof params != "undefined") {
  2965. if (typeof params['str'] != "undefined") {
  2966. this.setString(params['str']);
  2967. } else if (typeof params['hex'] != "undefined") {
  2968. this.setStringHex(params['hex']);
  2969. } else if (typeof params['date'] != "undefined") {
  2970. this.setByDate(params['date']);
  2971. }
  2972. }
  2973. };
  2974. JSX.extend(KJUR.asn1.DERGeneralizedTime, KJUR.asn1.DERAbstractTime);
  2975. // ********************************************************************
  2976. /**
  2977. * class for ASN.1 DER Sequence
  2978. * @name KJUR.asn1.DERSequence
  2979. * @class class for ASN.1 DER Sequence
  2980. * @extends KJUR.asn1.DERAbstractStructured
  2981. * @description
  2982. * <br/>
  2983. * As for argument 'params' for constructor, you can specify one of
  2984. * following properties:
  2985. * <ul>
  2986. * <li>array - specify array of ASN1Object to set elements of content</li>
  2987. * </ul>
  2988. * NOTE: 'params' can be omitted.
  2989. */
  2990. KJUR.asn1.DERSequence = function(params) {
  2991. KJUR.asn1.DERSequence.superclass.constructor.call(this, params);
  2992. this.hT = "30";
  2993. this.getFreshValueHex = function() {
  2994. var h = '';
  2995. for (var i = 0; i < this.asn1Array.length; i++) {
  2996. var asn1Obj = this.asn1Array[i];
  2997. h += asn1Obj.getEncodedHex();
  2998. }
  2999. this.hV = h;
  3000. return this.hV;
  3001. };
  3002. };
  3003. JSX.extend(KJUR.asn1.DERSequence, KJUR.asn1.DERAbstractStructured);
  3004. // ********************************************************************
  3005. /**
  3006. * class for ASN.1 DER Set
  3007. * @name KJUR.asn1.DERSet
  3008. * @class class for ASN.1 DER Set
  3009. * @extends KJUR.asn1.DERAbstractStructured
  3010. * @description
  3011. * <br/>
  3012. * As for argument 'params' for constructor, you can specify one of
  3013. * following properties:
  3014. * <ul>
  3015. * <li>array - specify array of ASN1Object to set elements of content</li>
  3016. * </ul>
  3017. * NOTE: 'params' can be omitted.
  3018. */
  3019. KJUR.asn1.DERSet = function(params) {
  3020. KJUR.asn1.DERSet.superclass.constructor.call(this, params);
  3021. this.hT = "31";
  3022. this.getFreshValueHex = function() {
  3023. var a = new Array();
  3024. for (var i = 0; i < this.asn1Array.length; i++) {
  3025. var asn1Obj = this.asn1Array[i];
  3026. a.push(asn1Obj.getEncodedHex());
  3027. }
  3028. a.sort();
  3029. this.hV = a.join('');
  3030. return this.hV;
  3031. };
  3032. };
  3033. JSX.extend(KJUR.asn1.DERSet, KJUR.asn1.DERAbstractStructured);
  3034. // ********************************************************************
  3035. /**
  3036. * class for ASN.1 DER TaggedObject
  3037. * @name KJUR.asn1.DERTaggedObject
  3038. * @class class for ASN.1 DER TaggedObject
  3039. * @extends KJUR.asn1.ASN1Object
  3040. * @description
  3041. * <br/>
  3042. * Parameter 'tagNoNex' is ASN.1 tag(T) value for this object.
  3043. * For example, if you find '[1]' tag in a ASN.1 dump,
  3044. * 'tagNoHex' will be 'a1'.
  3045. * <br/>
  3046. * As for optional argument 'params' for constructor, you can specify *ANY* of
  3047. * following properties:
  3048. * <ul>
  3049. * <li>explicit - specify true if this is explicit tag otherwise false
  3050. * (default is 'true').</li>
  3051. * <li>tag - specify tag (default is 'a0' which means [0])</li>
  3052. * <li>obj - specify ASN1Object which is tagged</li>
  3053. * </ul>
  3054. * @example
  3055. * d1 = new KJUR.asn1.DERUTF8String({'str':'a'});
  3056. * d2 = new KJUR.asn1.DERTaggedObject({'obj': d1});
  3057. * hex = d2.getEncodedHex();
  3058. */
  3059. KJUR.asn1.DERTaggedObject = function(params) {
  3060. KJUR.asn1.DERTaggedObject.superclass.constructor.call(this);
  3061. this.hT = "a0";
  3062. this.hV = '';
  3063. this.isExplicit = true;
  3064. this.asn1Object = null;
  3065. /**
  3066. * set value by an ASN1Object
  3067. * @name setString
  3068. * @memberOf KJUR.asn1.DERTaggedObject
  3069. * @function
  3070. * @param {Boolean} isExplicitFlag flag for explicit/implicit tag
  3071. * @param {Integer} tagNoHex hexadecimal string of ASN.1 tag
  3072. * @param {ASN1Object} asn1Object ASN.1 to encapsulate
  3073. */
  3074. this.setASN1Object = function(isExplicitFlag, tagNoHex, asn1Object) {
  3075. this.hT = tagNoHex;
  3076. this.isExplicit = isExplicitFlag;
  3077. this.asn1Object = asn1Object;
  3078. if (this.isExplicit) {
  3079. this.hV = this.asn1Object.getEncodedHex();
  3080. this.hTLV = null;
  3081. this.isModified = true;
  3082. } else {
  3083. this.hV = null;
  3084. this.hTLV = asn1Object.getEncodedHex();
  3085. this.hTLV = this.hTLV.replace(/^../, tagNoHex);
  3086. this.isModified = false;
  3087. }
  3088. };
  3089. this.getFreshValueHex = function() {
  3090. return this.hV;
  3091. };
  3092. if (typeof params != "undefined") {
  3093. if (typeof params['tag'] != "undefined") {
  3094. this.hT = params['tag'];
  3095. }
  3096. if (typeof params['explicit'] != "undefined") {
  3097. this.isExplicit = params['explicit'];
  3098. }
  3099. if (typeof params['obj'] != "undefined") {
  3100. this.asn1Object = params['obj'];
  3101. this.setASN1Object(this.isExplicit, this.hT, this.asn1Object);
  3102. }
  3103. }
  3104. };
  3105. JSX.extend(KJUR.asn1.DERTaggedObject, KJUR.asn1.ASN1Object);// Hex JavaScript decoder
  3106. // Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it>
  3107. // Permission to use, copy, modify, and/or distribute this software for any
  3108. // purpose with or without fee is hereby granted, provided that the above
  3109. // copyright notice and this permission notice appear in all copies.
  3110. //
  3111. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  3112. // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  3113. // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  3114. // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  3115. // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  3116. // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  3117. // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  3118. /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
  3119. (function (undefined) {
  3120. "use strict";
  3121. var Hex = {},
  3122. decoder;
  3123. Hex.decode = function(a) {
  3124. var i;
  3125. if (decoder === undefined) {
  3126. var hex = "0123456789ABCDEF",
  3127. ignore = " \f\n\r\t\u00A0\u2028\u2029";
  3128. decoder = [];
  3129. for (i = 0; i < 16; ++i)
  3130. decoder[hex.charAt(i)] = i;
  3131. hex = hex.toLowerCase();
  3132. for (i = 10; i < 16; ++i)
  3133. decoder[hex.charAt(i)] = i;
  3134. for (i = 0; i < ignore.length; ++i)
  3135. decoder[ignore.charAt(i)] = -1;
  3136. }
  3137. var out = [],
  3138. bits = 0,
  3139. char_count = 0;
  3140. for (i = 0; i < a.length; ++i) {
  3141. var c = a.charAt(i);
  3142. if (c == '=')
  3143. break;
  3144. c = decoder[c];
  3145. if (c == -1)
  3146. continue;
  3147. if (c === undefined)
  3148. throw 'Illegal character at offset ' + i;
  3149. bits |= c;
  3150. if (++char_count >= 2) {
  3151. out[out.length] = bits;
  3152. bits = 0;
  3153. char_count = 0;
  3154. } else {
  3155. bits <<= 4;
  3156. }
  3157. }
  3158. if (char_count)
  3159. throw "Hex encoding incomplete: 4 bits missing";
  3160. return out;
  3161. };
  3162. // export globals
  3163. window.Hex = Hex;
  3164. })();// Base64 JavaScript decoder
  3165. // Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it>
  3166. // Permission to use, copy, modify, and/or distribute this software for any
  3167. // purpose with or without fee is hereby granted, provided that the above
  3168. // copyright notice and this permission notice appear in all copies.
  3169. //
  3170. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  3171. // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  3172. // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  3173. // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  3174. // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  3175. // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  3176. // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  3177. /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
  3178. (function (undefined) {
  3179. "use strict";
  3180. var Base64 = {},
  3181. decoder;
  3182. Base64.decode = function (a) {
  3183. var i;
  3184. if (decoder === undefined) {
  3185. var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
  3186. ignore = "= \f\n\r\t\u00A0\u2028\u2029";
  3187. decoder = [];
  3188. for (i = 0; i < 64; ++i)
  3189. decoder[b64.charAt(i)] = i;
  3190. for (i = 0; i < ignore.length; ++i)
  3191. decoder[ignore.charAt(i)] = -1;
  3192. }
  3193. var out = [];
  3194. var bits = 0, char_count = 0;
  3195. for (i = 0; i < a.length; ++i) {
  3196. var c = a.charAt(i);
  3197. if (c == '=')
  3198. break;
  3199. c = decoder[c];
  3200. if (c == -1)
  3201. continue;
  3202. if (c === undefined)
  3203. throw 'Illegal character at offset ' + i;
  3204. bits |= c;
  3205. if (++char_count >= 4) {
  3206. out[out.length] = (bits >> 16);
  3207. out[out.length] = (bits >> 8) & 0xFF;
  3208. out[out.length] = bits & 0xFF;
  3209. bits = 0;
  3210. char_count = 0;
  3211. } else {
  3212. bits <<= 6;
  3213. }
  3214. }
  3215. switch (char_count) {
  3216. case 1:
  3217. throw "Base64 encoding incomplete: at least 2 bits missing";
  3218. case 2:
  3219. out[out.length] = (bits >> 10);
  3220. break;
  3221. case 3:
  3222. out[out.length] = (bits >> 16);
  3223. out[out.length] = (bits >> 8) & 0xFF;
  3224. break;
  3225. }
  3226. return out;
  3227. };
  3228. Base64.re = /-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/;
  3229. Base64.unarmor = function (a) {
  3230. var m = Base64.re.exec(a);
  3231. if (m) {
  3232. if (m[1])
  3233. a = m[1];
  3234. else if (m[2])
  3235. a = m[2];
  3236. else
  3237. throw "RegExp out of sync";
  3238. }
  3239. return Base64.decode(a);
  3240. };
  3241. // export globals
  3242. window.Base64 = Base64;
  3243. })();// ASN.1 JavaScript decoder
  3244. // Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it>
  3245. // Permission to use, copy, modify, and/or distribute this software for any
  3246. // purpose with or without fee is hereby granted, provided that the above
  3247. // copyright notice and this permission notice appear in all copies.
  3248. //
  3249. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  3250. // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  3251. // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  3252. // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  3253. // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  3254. // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  3255. // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  3256. /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
  3257. /*global oids */
  3258. (function (undefined) {
  3259. "use strict";
  3260. var hardLimit = 100,
  3261. ellipsis = "\u2026",
  3262. DOM = {
  3263. tag: function (tagName, className) {
  3264. var t = document.createElement(tagName);
  3265. t.className = className;
  3266. return t;
  3267. },
  3268. text: function (str) {
  3269. return document.createTextNode(str);
  3270. }
  3271. };
  3272. function Stream(enc, pos) {
  3273. if (enc instanceof Stream) {
  3274. this.enc = enc.enc;
  3275. this.pos = enc.pos;
  3276. } else {
  3277. this.enc = enc;
  3278. this.pos = pos;
  3279. }
  3280. }
  3281. Stream.prototype.get = function (pos) {
  3282. if (pos === undefined)
  3283. pos = this.pos++;
  3284. if (pos >= this.enc.length)
  3285. throw 'Requesting byte offset ' + pos + ' on a stream of length ' + this.enc.length;
  3286. return this.enc[pos];
  3287. };
  3288. Stream.prototype.hexDigits = "0123456789ABCDEF";
  3289. Stream.prototype.hexByte = function (b) {
  3290. return this.hexDigits.charAt((b >> 4) & 0xF) + this.hexDigits.charAt(b & 0xF);
  3291. };
  3292. Stream.prototype.hexDump = function (start, end, raw) {
  3293. var s = "";
  3294. for (var i = start; i < end; ++i) {
  3295. s += this.hexByte(this.get(i));
  3296. if (raw !== true)
  3297. switch (i & 0xF) {
  3298. case 0x7: s += " "; break;
  3299. case 0xF: s += "\n"; break;
  3300. default: s += " ";
  3301. }
  3302. }
  3303. return s;
  3304. };
  3305. Stream.prototype.parseStringISO = function (start, end) {
  3306. var s = "";
  3307. for (var i = start; i < end; ++i)
  3308. s += String.fromCharCode(this.get(i));
  3309. return s;
  3310. };
  3311. Stream.prototype.parseStringUTF = function (start, end) {
  3312. var s = "";
  3313. for (var i = start; i < end; ) {
  3314. var c = this.get(i++);
  3315. if (c < 128)
  3316. s += String.fromCharCode(c);
  3317. else if ((c > 191) && (c < 224))
  3318. s += String.fromCharCode(((c & 0x1F) << 6) | (this.get(i++) & 0x3F));
  3319. else
  3320. s += String.fromCharCode(((c & 0x0F) << 12) | ((this.get(i++) & 0x3F) << 6) | (this.get(i++) & 0x3F));
  3321. }
  3322. return s;
  3323. };
  3324. Stream.prototype.parseStringBMP = function (start, end) {
  3325. var str = ""
  3326. for (var i = start; i < end; i += 2) {
  3327. var high_byte = this.get(i);
  3328. var low_byte = this.get(i + 1);
  3329. str += String.fromCharCode( (high_byte << 8) + low_byte );
  3330. }
  3331. return str;
  3332. };
  3333. Stream.prototype.reTime = /^((?:1[89]|2\d)?\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/;
  3334. Stream.prototype.parseTime = function (start, end) {
  3335. var s = this.parseStringISO(start, end),
  3336. m = this.reTime.exec(s);
  3337. if (!m)
  3338. return "Unrecognized time: " + s;
  3339. s = m[1] + "-" + m[2] + "-" + m[3] + " " + m[4];
  3340. if (m[5]) {
  3341. s += ":" + m[5];
  3342. if (m[6]) {
  3343. s += ":" + m[6];
  3344. if (m[7])
  3345. s += "." + m[7];
  3346. }
  3347. }
  3348. if (m[8]) {
  3349. s += " UTC";
  3350. if (m[8] != 'Z') {
  3351. s += m[8];
  3352. if (m[9])
  3353. s += ":" + m[9];
  3354. }
  3355. }
  3356. return s;
  3357. };
  3358. Stream.prototype.parseInteger = function (start, end) {
  3359. //TODO support negative numbers
  3360. var len = end - start;
  3361. if (len > 4) {
  3362. len <<= 3;
  3363. var s = this.get(start);
  3364. if (s === 0)
  3365. len -= 8;
  3366. else
  3367. while (s < 128) {
  3368. s <<= 1;
  3369. --len;
  3370. }
  3371. return "(" + len + " bit)";
  3372. }
  3373. var n = 0;
  3374. for (var i = start; i < end; ++i)
  3375. n = (n << 8) | this.get(i);
  3376. return n;
  3377. };
  3378. Stream.prototype.parseBitString = function (start, end) {
  3379. var unusedBit = this.get(start),
  3380. lenBit = ((end - start - 1) << 3) - unusedBit,
  3381. s = "(" + lenBit + " bit)";
  3382. if (lenBit <= 20) {
  3383. var skip = unusedBit;
  3384. s += " ";
  3385. for (var i = end - 1; i > start; --i) {
  3386. var b = this.get(i);
  3387. for (var j = skip; j < 8; ++j)
  3388. s += (b >> j) & 1 ? "1" : "0";
  3389. skip = 0;
  3390. }
  3391. }
  3392. return s;
  3393. };
  3394. Stream.prototype.parseOctetString = function (start, end) {
  3395. var len = end - start,
  3396. s = "(" + len + " byte) ";
  3397. if (len > hardLimit)
  3398. end = start + hardLimit;
  3399. for (var i = start; i < end; ++i)
  3400. s += this.hexByte(this.get(i)); //TODO: also try Latin1?
  3401. if (len > hardLimit)
  3402. s += ellipsis;
  3403. return s;
  3404. };
  3405. Stream.prototype.parseOID = function (start, end) {
  3406. var s = '',
  3407. n = 0,
  3408. bits = 0;
  3409. for (var i = start; i < end; ++i) {
  3410. var v = this.get(i);
  3411. n = (n << 7) | (v & 0x7F);
  3412. bits += 7;
  3413. if (!(v & 0x80)) { // finished
  3414. if (s === '') {
  3415. var m = n < 80 ? n < 40 ? 0 : 1 : 2;
  3416. s = m + "." + (n - m * 40);
  3417. } else
  3418. s += "." + ((bits >= 31) ? "bigint" : n);
  3419. n = bits = 0;
  3420. }
  3421. }
  3422. return s;
  3423. };
  3424. function ASN1(stream, header, length, tag, sub) {
  3425. this.stream = stream;
  3426. this.header = header;
  3427. this.length = length;
  3428. this.tag = tag;
  3429. this.sub = sub;
  3430. }
  3431. ASN1.prototype.typeName = function () {
  3432. if (this.tag === undefined)
  3433. return "unknown";
  3434. var tagClass = this.tag >> 6,
  3435. tagConstructed = (this.tag >> 5) & 1,
  3436. tagNumber = this.tag & 0x1F;
  3437. switch (tagClass) {
  3438. case 0: // universal
  3439. switch (tagNumber) {
  3440. case 0x00: return "EOC";
  3441. case 0x01: return "BOOLEAN";
  3442. case 0x02: return "INTEGER";
  3443. case 0x03: return "BIT_STRING";
  3444. case 0x04: return "OCTET_STRING";
  3445. case 0x05: return "NULL";
  3446. case 0x06: return "OBJECT_IDENTIFIER";
  3447. case 0x07: return "ObjectDescriptor";
  3448. case 0x08: return "EXTERNAL";
  3449. case 0x09: return "REAL";
  3450. case 0x0A: return "ENUMERATED";
  3451. case 0x0B: return "EMBEDDED_PDV";
  3452. case 0x0C: return "UTF8String";
  3453. case 0x10: return "SEQUENCE";
  3454. case 0x11: return "SET";
  3455. case 0x12: return "NumericString";
  3456. case 0x13: return "PrintableString"; // ASCII subset
  3457. case 0x14: return "TeletexString"; // aka T61String
  3458. case 0x15: return "VideotexString";
  3459. case 0x16: return "IA5String"; // ASCII
  3460. case 0x17: return "UTCTime";
  3461. case 0x18: return "GeneralizedTime";
  3462. case 0x19: return "GraphicString";
  3463. case 0x1A: return "VisibleString"; // ASCII subset
  3464. case 0x1B: return "GeneralString";
  3465. case 0x1C: return "UniversalString";
  3466. case 0x1E: return "BMPString";
  3467. default: return "Universal_" + tagNumber.toString(16);
  3468. }
  3469. case 1: return "Application_" + tagNumber.toString(16);
  3470. case 2: return "[" + tagNumber + "]"; // Context
  3471. case 3: return "Private_" + tagNumber.toString(16);
  3472. }
  3473. };
  3474. ASN1.prototype.reSeemsASCII = /^[ -~]+$/;
  3475. ASN1.prototype.content = function () {
  3476. if (this.tag === undefined)
  3477. return null;
  3478. var tagClass = this.tag >> 6,
  3479. tagNumber = this.tag & 0x1F,
  3480. content = this.posContent(),
  3481. len = Math.abs(this.length);
  3482. if (tagClass !== 0) { // universal
  3483. if (this.sub !== null)
  3484. return "(" + this.sub.length + " elem)";
  3485. //TODO: TRY TO PARSE ASCII STRING
  3486. var s = this.stream.parseStringISO(content, content + Math.min(len, hardLimit));
  3487. if (this.reSeemsASCII.test(s))
  3488. return s.substring(0, 2 * hardLimit) + ((s.length > 2 * hardLimit) ? ellipsis : "");
  3489. else
  3490. return this.stream.parseOctetString(content, content + len);
  3491. }
  3492. switch (tagNumber) {
  3493. case 0x01: // BOOLEAN
  3494. return (this.stream.get(content) === 0) ? "false" : "true";
  3495. case 0x02: // INTEGER
  3496. return this.stream.parseInteger(content, content + len);
  3497. case 0x03: // BIT_STRING
  3498. return this.sub ? "(" + this.sub.length + " elem)" :
  3499. this.stream.parseBitString(content, content + len);
  3500. case 0x04: // OCTET_STRING
  3501. return this.sub ? "(" + this.sub.length + " elem)" :
  3502. this.stream.parseOctetString(content, content + len);
  3503. //case 0x05: // NULL
  3504. case 0x06: // OBJECT_IDENTIFIER
  3505. return this.stream.parseOID(content, content + len);
  3506. //case 0x07: // ObjectDescriptor
  3507. //case 0x08: // EXTERNAL
  3508. //case 0x09: // REAL
  3509. //case 0x0A: // ENUMERATED
  3510. //case 0x0B: // EMBEDDED_PDV
  3511. case 0x10: // SEQUENCE
  3512. case 0x11: // SET
  3513. return "(" + this.sub.length + " elem)";
  3514. case 0x0C: // UTF8String
  3515. return this.stream.parseStringUTF(content, content + len);
  3516. case 0x12: // NumericString
  3517. case 0x13: // PrintableString
  3518. case 0x14: // TeletexString
  3519. case 0x15: // VideotexString
  3520. case 0x16: // IA5String
  3521. //case 0x19: // GraphicString
  3522. case 0x1A: // VisibleString
  3523. //case 0x1B: // GeneralString
  3524. //case 0x1C: // UniversalString
  3525. return this.stream.parseStringISO(content, content + len);
  3526. case 0x1E: // BMPString
  3527. return this.stream.parseStringBMP(content, content + len);
  3528. case 0x17: // UTCTime
  3529. case 0x18: // GeneralizedTime
  3530. return this.stream.parseTime(content, content + len);
  3531. }
  3532. return null;
  3533. };
  3534. ASN1.prototype.toString = function () {
  3535. return this.typeName() + "@" + this.stream.pos + "[header:" + this.header + ",length:" + this.length + ",sub:" + ((this.sub === null) ? 'null' : this.sub.length) + "]";
  3536. };
  3537. ASN1.prototype.print = function (indent) {
  3538. if (indent === undefined) indent = '';
  3539. document.writeln(indent + this);
  3540. if (this.sub !== null) {
  3541. indent += ' ';
  3542. for (var i = 0, max = this.sub.length; i < max; ++i)
  3543. this.sub[i].print(indent);
  3544. }
  3545. };
  3546. ASN1.prototype.toPrettyString = function (indent) {
  3547. if (indent === undefined) indent = '';
  3548. var s = indent + this.typeName() + " @" + this.stream.pos;
  3549. if (this.length >= 0)
  3550. s += "+";
  3551. s += this.length;
  3552. if (this.tag & 0x20)
  3553. s += " (constructed)";
  3554. else if (((this.tag == 0x03) || (this.tag == 0x04)) && (this.sub !== null))
  3555. s += " (encapsulates)";
  3556. s += "\n";
  3557. if (this.sub !== null) {
  3558. indent += ' ';
  3559. for (var i = 0, max = this.sub.length; i < max; ++i)
  3560. s += this.sub[i].toPrettyString(indent);
  3561. }
  3562. return s;
  3563. };
  3564. ASN1.prototype.toDOM = function () {
  3565. var node = DOM.tag("div", "node");
  3566. node.asn1 = this;
  3567. var head = DOM.tag("div", "head");
  3568. var s = this.typeName().replace(/_/g, " ");
  3569. head.innerHTML = s;
  3570. var content = this.content();
  3571. if (content !== null) {
  3572. content = String(content).replace(/</g, "&lt;");
  3573. var preview = DOM.tag("span", "preview");
  3574. preview.appendChild(DOM.text(content));
  3575. head.appendChild(preview);
  3576. }
  3577. node.appendChild(head);
  3578. this.node = node;
  3579. this.head = head;
  3580. var value = DOM.tag("div", "value");
  3581. s = "Offset: " + this.stream.pos + "<br/>";
  3582. s += "Length: " + this.header + "+";
  3583. if (this.length >= 0)
  3584. s += this.length;
  3585. else
  3586. s += (-this.length) + " (undefined)";
  3587. if (this.tag & 0x20)
  3588. s += "<br/>(constructed)";
  3589. else if (((this.tag == 0x03) || (this.tag == 0x04)) && (this.sub !== null))
  3590. s += "<br/>(encapsulates)";
  3591. //TODO if (this.tag == 0x03) s += "Unused bits: "
  3592. if (content !== null) {
  3593. s += "<br/>Value:<br/><b>" + content + "</b>";
  3594. if ((typeof oids === 'object') && (this.tag == 0x06)) {
  3595. var oid = oids[content];
  3596. if (oid) {
  3597. if (oid.d) s += "<br/>" + oid.d;
  3598. if (oid.c) s += "<br/>" + oid.c;
  3599. if (oid.w) s += "<br/>(warning!)";
  3600. }
  3601. }
  3602. }
  3603. value.innerHTML = s;
  3604. node.appendChild(value);
  3605. var sub = DOM.tag("div", "sub");
  3606. if (this.sub !== null) {
  3607. for (var i = 0, max = this.sub.length; i < max; ++i)
  3608. sub.appendChild(this.sub[i].toDOM());
  3609. }
  3610. node.appendChild(sub);
  3611. head.onclick = function () {
  3612. node.className = (node.className == "node collapsed") ? "node" : "node collapsed";
  3613. };
  3614. return node;
  3615. };
  3616. ASN1.prototype.posStart = function () {
  3617. return this.stream.pos;
  3618. };
  3619. ASN1.prototype.posContent = function () {
  3620. return this.stream.pos + this.header;
  3621. };
  3622. ASN1.prototype.posEnd = function () {
  3623. return this.stream.pos + this.header + Math.abs(this.length);
  3624. };
  3625. ASN1.prototype.fakeHover = function (current) {
  3626. this.node.className += " hover";
  3627. if (current)
  3628. this.head.className += " hover";
  3629. };
  3630. ASN1.prototype.fakeOut = function (current) {
  3631. var re = / ?hover/;
  3632. this.node.className = this.node.className.replace(re, "");
  3633. if (current)
  3634. this.head.className = this.head.className.replace(re, "");
  3635. };
  3636. ASN1.prototype.toHexDOM_sub = function (node, className, stream, start, end) {
  3637. if (start >= end)
  3638. return;
  3639. var sub = DOM.tag("span", className);
  3640. sub.appendChild(DOM.text(
  3641. stream.hexDump(start, end)));
  3642. node.appendChild(sub);
  3643. };
  3644. ASN1.prototype.toHexDOM = function (root) {
  3645. var node = DOM.tag("span", "hex");
  3646. if (root === undefined) root = node;
  3647. this.head.hexNode = node;
  3648. this.head.onmouseover = function () { this.hexNode.className = "hexCurrent"; };
  3649. this.head.onmouseout = function () { this.hexNode.className = "hex"; };
  3650. node.asn1 = this;
  3651. node.onmouseover = function () {
  3652. var current = !root.selected;
  3653. if (current) {
  3654. root.selected = this.asn1;
  3655. this.className = "hexCurrent";
  3656. }
  3657. this.asn1.fakeHover(current);
  3658. };
  3659. node.onmouseout = function () {
  3660. var current = (root.selected == this.asn1);
  3661. this.asn1.fakeOut(current);
  3662. if (current) {
  3663. root.selected = null;
  3664. this.className = "hex";
  3665. }
  3666. };
  3667. this.toHexDOM_sub(node, "tag", this.stream, this.posStart(), this.posStart() + 1);
  3668. this.toHexDOM_sub(node, (this.length >= 0) ? "dlen" : "ulen", this.stream, this.posStart() + 1, this.posContent());
  3669. if (this.sub === null)
  3670. node.appendChild(DOM.text(
  3671. this.stream.hexDump(this.posContent(), this.posEnd())));
  3672. else if (this.sub.length > 0) {
  3673. var first = this.sub[0];
  3674. var last = this.sub[this.sub.length - 1];
  3675. this.toHexDOM_sub(node, "intro", this.stream, this.posContent(), first.posStart());
  3676. for (var i = 0, max = this.sub.length; i < max; ++i)
  3677. node.appendChild(this.sub[i].toHexDOM(root));
  3678. this.toHexDOM_sub(node, "outro", this.stream, last.posEnd(), this.posEnd());
  3679. }
  3680. return node;
  3681. };
  3682. ASN1.prototype.toHexString = function (root) {
  3683. return this.stream.hexDump(this.posStart(), this.posEnd(), true);
  3684. };
  3685. ASN1.decodeLength = function (stream) {
  3686. var buf = stream.get(),
  3687. len = buf & 0x7F;
  3688. if (len == buf)
  3689. return len;
  3690. if (len > 3)
  3691. throw "Length over 24 bits not supported at position " + (stream.pos - 1);
  3692. if (len === 0)
  3693. return -1; // undefined
  3694. buf = 0;
  3695. for (var i = 0; i < len; ++i)
  3696. buf = (buf << 8) | stream.get();
  3697. return buf;
  3698. };
  3699. ASN1.hasContent = function (tag, len, stream) {
  3700. if (tag & 0x20) // constructed
  3701. return true;
  3702. if ((tag < 0x03) || (tag > 0x04))
  3703. return false;
  3704. var p = new Stream(stream);
  3705. if (tag == 0x03) p.get(); // BitString unused bits, must be in [0, 7]
  3706. var subTag = p.get();
  3707. if ((subTag >> 6) & 0x01) // not (universal or context)
  3708. return false;
  3709. try {
  3710. var subLength = ASN1.decodeLength(p);
  3711. return ((p.pos - stream.pos) + subLength == len);
  3712. } catch (exception) {
  3713. return false;
  3714. }
  3715. };
  3716. ASN1.decode = function (stream) {
  3717. if (!(stream instanceof Stream))
  3718. stream = new Stream(stream, 0);
  3719. var streamStart = new Stream(stream),
  3720. tag = stream.get(),
  3721. len = ASN1.decodeLength(stream),
  3722. header = stream.pos - streamStart.pos,
  3723. sub = null;
  3724. if (ASN1.hasContent(tag, len, stream)) {
  3725. // it has content, so we decode it
  3726. var start = stream.pos;
  3727. if (tag == 0x03) stream.get(); // skip BitString unused bits, must be in [0, 7]
  3728. sub = [];
  3729. if (len >= 0) {
  3730. // definite length
  3731. var end = start + len;
  3732. while (stream.pos < end)
  3733. sub[sub.length] = ASN1.decode(stream);
  3734. if (stream.pos != end)
  3735. throw "Content size is not correct for container starting at offset " + start;
  3736. } else {
  3737. // undefined length
  3738. try {
  3739. for (;;) {
  3740. var s = ASN1.decode(stream);
  3741. if (s.tag === 0)
  3742. break;
  3743. sub[sub.length] = s;
  3744. }
  3745. len = start - stream.pos;
  3746. } catch (e) {
  3747. throw "Exception while decoding undefined length content: " + e;
  3748. }
  3749. }
  3750. } else
  3751. stream.pos += len; // skip content
  3752. return new ASN1(streamStart, header, len, tag, sub);
  3753. };
  3754. ASN1.test = function () {
  3755. var test = [
  3756. { value: [0x27], expected: 0x27 },
  3757. { value: [0x81, 0xC9], expected: 0xC9 },
  3758. { value: [0x83, 0xFE, 0xDC, 0xBA], expected: 0xFEDCBA }
  3759. ];
  3760. for (var i = 0, max = test.length; i < max; ++i) {
  3761. var pos = 0,
  3762. stream = new Stream(test[i].value, 0),
  3763. res = ASN1.decodeLength(stream);
  3764. if (res != test[i].expected)
  3765. document.write("In test[" + i + "] expected " + test[i].expected + " got " + res + "\n");
  3766. }
  3767. };
  3768. // export globals
  3769. window.ASN1 = ASN1;
  3770. })();/**
  3771. * Retrieve the hexadecimal value (as a string) of the current ASN.1 element
  3772. * @returns {string}
  3773. * @public
  3774. */
  3775. ASN1.prototype.getHexStringValue = function(){
  3776. var hexString = this.toHexString();
  3777. var offset = this.header * 2;
  3778. var length = this.length * 2;
  3779. return hexString.substr(offset,length);
  3780. };
  3781. /**
  3782. * Method to parse a pem encoded string containing both a public or private key.
  3783. * The method will translate the pem encoded string in a der encoded string and
  3784. * will parse private key and public key parameters. This method accepts public key
  3785. * in the rsaencryption pkcs #1 format (oid: 1.2.840.113549.1.1.1).
  3786. * @todo Check how many rsa formats use the same format of pkcs #1. The format is defined as:
  3787. * PublicKeyInfo ::= SEQUENCE {
  3788. * algorithm AlgorithmIdentifier,
  3789. * PublicKey BIT STRING
  3790. * }
  3791. * Where AlgorithmIdentifier is:
  3792. * AlgorithmIdentifier ::= SEQUENCE {
  3793. * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm
  3794. * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1)
  3795. * }
  3796. * and PublicKey is a SEQUENCE encapsulated in a BIT STRING
  3797. * RSAPublicKey ::= SEQUENCE {
  3798. * modulus INTEGER, -- n
  3799. * publicExponent INTEGER -- e
  3800. * }
  3801. * it's possible to examine the structure of the keys obtained from openssl using
  3802. * an asn.1 dumper as the one used here to parse the components: http://lapo.it/asn1js/
  3803. * @argument {string} pem the pem encoded string, can include the BEGIN/END header/footer
  3804. * @private
  3805. */
  3806. RSAKey.prototype.parseKey = function(pem) {
  3807. try{
  3808. var reHex = /^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/;
  3809. var der = reHex.test(pem) ? Hex.decode(pem) : Base64.unarmor(pem);
  3810. var asn1 = ASN1.decode(der);
  3811. if (asn1.sub.length === 9){
  3812. // the data is a Private key
  3813. //in order
  3814. //Algorithm version, n, e, d, p, q, dmp1, dmq1, coeff
  3815. //Alg version, modulus, public exponent, private exponent, prime 1, prime 2, exponent 1, exponent 2, coefficient
  3816. var modulus = asn1.sub[1].getHexStringValue(); //bigint
  3817. this.n = parseBigInt(modulus, 16);
  3818. var public_exponent = asn1.sub[2].getHexStringValue(); //int
  3819. this.e = parseInt(public_exponent, 16);
  3820. var private_exponent = asn1.sub[3].getHexStringValue(); //bigint
  3821. this.d = parseBigInt(private_exponent, 16);
  3822. var prime1 = asn1.sub[4].getHexStringValue(); //bigint
  3823. this.p = parseBigInt(prime1, 16);
  3824. var prime2 = asn1.sub[5].getHexStringValue(); //bigint
  3825. this.q = parseBigInt(prime2, 16);
  3826. var exponent1 = asn1.sub[6].getHexStringValue(); //bigint
  3827. this.dmp1 = parseBigInt(exponent1, 16);
  3828. var exponent2 = asn1.sub[7].getHexStringValue(); //bigint
  3829. this.dmq1 = parseBigInt(exponent2, 16);
  3830. var coefficient = asn1.sub[8].getHexStringValue(); //bigint
  3831. this.coeff = parseBigInt(coefficient, 16);
  3832. }else if (asn1.sub.length === 2){
  3833. //Public key
  3834. //The data PROBABLY is a public key
  3835. var bit_string = asn1.sub[1];
  3836. var sequence = bit_string.sub[0];
  3837. var modulus = sequence.sub[0].getHexStringValue();
  3838. this.n = parseBigInt(modulus, 16);
  3839. var public_exponent = sequence.sub[1].getHexStringValue();
  3840. this.e = parseInt(public_exponent, 16);
  3841. }else{
  3842. return false;
  3843. }
  3844. return true;
  3845. }catch(ex){
  3846. return false;
  3847. }
  3848. };
  3849. /**
  3850. * Translate rsa parameters in a hex encoded string representing the rsa key.
  3851. * The translation follow the ASN.1 notation :
  3852. * RSAPrivateKey ::= SEQUENCE {
  3853. * version Version,
  3854. * modulus INTEGER, -- n
  3855. * publicExponent INTEGER, -- e
  3856. * privateExponent INTEGER, -- d
  3857. * prime1 INTEGER, -- p
  3858. * prime2 INTEGER, -- q
  3859. * exponent1 INTEGER, -- d mod (p1)
  3860. * exponent2 INTEGER, -- d mod (q-1)
  3861. * coefficient INTEGER, -- (inverse of q) mod p
  3862. * }
  3863. * @returns {string} DER Encoded String representing the rsa private key
  3864. * @private
  3865. */
  3866. RSAKey.prototype.getPrivateBaseKey = function() {
  3867. //Algorithm version, n, e, d, p, q, dmp1, dmq1, coeff
  3868. //Alg version, modulus, public exponent, private exponent, prime 1, prime 2, exponent 1, exponent 2, coefficient
  3869. var options = {
  3870. 'array' : [
  3871. new KJUR.asn1.DERInteger({'int' : 0}),
  3872. new KJUR.asn1.DERInteger({'bigint' : this.n}),
  3873. new KJUR.asn1.DERInteger({'int' : this.e}),
  3874. new KJUR.asn1.DERInteger({'bigint' : this.d}),
  3875. new KJUR.asn1.DERInteger({'bigint' : this.p}),
  3876. new KJUR.asn1.DERInteger({'bigint' : this.q}),
  3877. new KJUR.asn1.DERInteger({'bigint' : this.dmp1}),
  3878. new KJUR.asn1.DERInteger({'bigint' : this.dmq1}),
  3879. new KJUR.asn1.DERInteger({'bigint' : this.coeff})
  3880. ]
  3881. };
  3882. var seq = new KJUR.asn1.DERSequence(options);
  3883. return seq.getEncodedHex();
  3884. };
  3885. /**
  3886. * base64 (pem) encoded version of the DER encoded representation
  3887. * @returns {string} pem encoded representation without header and footer
  3888. * @public
  3889. */
  3890. RSAKey.prototype.getPrivateBaseKeyB64 = function (){
  3891. return hex2b64(this.getPrivateBaseKey());
  3892. };
  3893. /**
  3894. * Translate rsa parameters in a hex encoded string representing the rsa public key.
  3895. * The representation follow the ASN.1 notation :
  3896. * PublicKeyInfo ::= SEQUENCE {
  3897. * algorithm AlgorithmIdentifier,
  3898. * PublicKey BIT STRING
  3899. * }
  3900. * Where AlgorithmIdentifier is:
  3901. * AlgorithmIdentifier ::= SEQUENCE {
  3902. * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm
  3903. * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1)
  3904. * }
  3905. * and PublicKey is a SEQUENCE encapsulated in a BIT STRING
  3906. * RSAPublicKey ::= SEQUENCE {
  3907. * modulus INTEGER, -- n
  3908. * publicExponent INTEGER -- e
  3909. * }
  3910. * @returns {string} DER Encoded String representing the rsa public key
  3911. * @private
  3912. */
  3913. RSAKey.prototype.getPublicBaseKey = function() {
  3914. var options = {
  3915. 'array' : [
  3916. new KJUR.asn1.DERObjectIdentifier({'oid':'1.2.840.113549.1.1.1'}), //RSA Encryption pkcs #1 oid
  3917. new KJUR.asn1.DERNull()
  3918. ]
  3919. };
  3920. var first_sequence = new KJUR.asn1.DERSequence(options);
  3921. options = {
  3922. 'array' : [
  3923. new KJUR.asn1.DERInteger({'bigint' : this.n}),
  3924. new KJUR.asn1.DERInteger({'int' : this.e})
  3925. ]
  3926. };
  3927. var second_sequence = new KJUR.asn1.DERSequence(options);
  3928. options = {
  3929. 'hex' : '00'+second_sequence.getEncodedHex()
  3930. };
  3931. var bit_string = new KJUR.asn1.DERBitString(options);
  3932. options = {
  3933. 'array' : [
  3934. first_sequence,
  3935. bit_string
  3936. ]
  3937. };
  3938. var seq = new KJUR.asn1.DERSequence(options);
  3939. return seq.getEncodedHex();
  3940. };
  3941. /**
  3942. * base64 (pem) encoded version of the DER encoded representation
  3943. * @returns {string} pem encoded representation without header and footer
  3944. * @public
  3945. */
  3946. RSAKey.prototype.getPublicBaseKeyB64 = function (){
  3947. return hex2b64(this.getPublicBaseKey());
  3948. };
  3949. /**
  3950. * wrap the string in block of width chars. The default value for rsa keys is 64
  3951. * characters.
  3952. * @param {string} str the pem encoded string without header and footer
  3953. * @param {Number} [width=64] - the length the string has to be wrapped at
  3954. * @returns {string}
  3955. * @private
  3956. */
  3957. RSAKey.prototype.wordwrap = function(str, width) {
  3958. width = width || 64;
  3959. if (!str)
  3960. return str;
  3961. var regex = '(.{1,' + width + '})( +|$\n?)|(.{1,' + width + '})';
  3962. return str.match(RegExp(regex, 'g')).join('\n');
  3963. };
  3964. /**
  3965. * Retrieve the pem encoded private key
  3966. * @returns {string} the pem encoded private key with header/footer
  3967. * @public
  3968. */
  3969. RSAKey.prototype.getPrivateKey = function() {
  3970. var key = "-----BEGIN RSA PRIVATE KEY-----\n";
  3971. key += this.wordwrap(this.getPrivateBaseKeyB64()) + "\n";
  3972. key += "-----END RSA PRIVATE KEY-----";
  3973. return key;
  3974. };
  3975. /**
  3976. * Retrieve the pem encoded public key
  3977. * @returns {string} the pem encoded public key with header/footer
  3978. * @public
  3979. */
  3980. RSAKey.prototype.getPublicKey = function() {
  3981. var key = "-----BEGIN PUBLIC KEY-----\n";
  3982. key += this.wordwrap(this.getPublicBaseKeyB64()) + "\n";
  3983. key += "-----END PUBLIC KEY-----";
  3984. return key;
  3985. };
  3986. /**
  3987. * Check if the object contains the necessary parameters to populate the rsa modulus
  3988. * and public exponent parameters.
  3989. * @param {Object} [obj={}] - An object that may contain the two public key
  3990. * parameters
  3991. * @returns {boolean} true if the object contains both the modulus and the public exponent
  3992. * properties (n and e)
  3993. * @todo check for types of n and e. N should be a parseable bigInt object, E should
  3994. * be a parseable integer number
  3995. * @private
  3996. */
  3997. RSAKey.prototype.hasPublicKeyProperty = function(obj){
  3998. obj = obj || {};
  3999. return obj.hasOwnProperty('n') &&
  4000. obj.hasOwnProperty('e');
  4001. };
  4002. /**
  4003. * Check if the object contains ALL the parameters of an RSA key.
  4004. * @param {Object} [obj={}] - An object that may contain nine rsa key
  4005. * parameters
  4006. * @returns {boolean} true if the object contains all the parameters needed
  4007. * @todo check for types of the parameters all the parameters but the public exponent
  4008. * should be parseable bigint objects, the public exponent should be a parseable integer number
  4009. * @private
  4010. */
  4011. RSAKey.prototype.hasPrivateKeyProperty = function(obj){
  4012. obj = obj || {};
  4013. return obj.hasOwnProperty('n') &&
  4014. obj.hasOwnProperty('e') &&
  4015. obj.hasOwnProperty('d') &&
  4016. obj.hasOwnProperty('p') &&
  4017. obj.hasOwnProperty('q') &&
  4018. obj.hasOwnProperty('dmp1') &&
  4019. obj.hasOwnProperty('dmq1') &&
  4020. obj.hasOwnProperty('coeff');
  4021. };
  4022. /**
  4023. * Parse the properties of obj in the current rsa object. Obj should AT LEAST
  4024. * include the modulus and public exponent (n, e) parameters.
  4025. * @param {Object} obj - the object containing rsa parameters
  4026. * @private
  4027. */
  4028. RSAKey.prototype.parsePropertiesFrom = function(obj){
  4029. this.n = obj.n;
  4030. this.e = obj.e;
  4031. if (obj.hasOwnProperty('d')){
  4032. this.d = obj.d;
  4033. this.p = obj.p;
  4034. this.q = obj.q;
  4035. this.dmp1 = obj.dmp1;
  4036. this.dmq1 = obj.dmq1;
  4037. this.coeff = obj.coeff;
  4038. }
  4039. };
  4040. /**
  4041. * Create a new JSEncryptRSAKey that extends Tom Wu's RSA key object.
  4042. * This object is just a decorator for parsing the key parameter
  4043. * @param {string|Object} key - The key in string format, or an object containing
  4044. * the parameters needed to build a RSAKey object.
  4045. * @constructor
  4046. */
  4047. var JSEncryptRSAKey = function(key) {
  4048. // Call the super constructor.
  4049. RSAKey.call(this);
  4050. // If a key key was provided.
  4051. if (key) {
  4052. // If this is a string...
  4053. if (typeof key === 'string') {
  4054. this.parseKey(key);
  4055. }else if (this.hasPrivateKeyProperty(key)||this.hasPublicKeyProperty(key)) {
  4056. // Set the values for the key.
  4057. this.parsePropertiesFrom(key);
  4058. }
  4059. }
  4060. };
  4061. // Derive from RSAKey.
  4062. JSEncryptRSAKey.prototype = new RSAKey();
  4063. // Reset the contructor.
  4064. JSEncryptRSAKey.prototype.constructor = JSEncryptRSAKey;
  4065. /**
  4066. *
  4067. * @param {Object} [options = {}] - An object to customize JSEncrypt behaviour
  4068. * possible parameters are:
  4069. * - default_key_size {number} default: 1024 the key size in bit
  4070. * - default_public_exponent {string} default: '010001' the hexadecimal representation of the public exponent
  4071. * - log {boolean} default: false whether log warn/error or not
  4072. * @constructor
  4073. */
  4074. var JSEncrypt = function(options) {
  4075. options = options || {};
  4076. this.default_key_size = parseInt(options.default_key_size) || 1024;
  4077. this.default_public_exponent = options.default_public_exponent || '010001'; //65537 default openssl public exponent for rsa key type
  4078. this.log = options.log || false;
  4079. // The private and public key.
  4080. this.key = null;
  4081. };
  4082. /**
  4083. * Method to set the rsa key parameter (one method is enough to set both the public
  4084. * and the private key, since the private key contains the public key paramenters)
  4085. * Log a warning if logs are enabled
  4086. * @param {Object|string} key the pem encoded string or an object (with or without header/footer)
  4087. * @public
  4088. */
  4089. JSEncrypt.prototype.setKey = function(key){
  4090. if (this.log && this.key)
  4091. console.warn('A key was already set, overriding existing.');
  4092. this.key = new JSEncryptRSAKey(key);
  4093. };
  4094. /**
  4095. * Proxy method for setKey, for api compatibility
  4096. * @see setKey
  4097. * @public
  4098. */
  4099. JSEncrypt.prototype.setPrivateKey = function(privkey) {
  4100. // Create the key.
  4101. this.setKey(privkey);
  4102. };
  4103. /**
  4104. * Proxy method for setKey, for api compatibility
  4105. * @see setKey
  4106. * @public
  4107. */
  4108. JSEncrypt.prototype.setPublicKey = function(pubkey) {
  4109. // Sets the public key.
  4110. this.setKey(pubkey);
  4111. };
  4112. /**
  4113. * Proxy method for RSAKey object's decrypt, decrypt the string using the private
  4114. * components of the rsa key object. Note that if the object was not set will be created
  4115. * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor
  4116. * @param {string} string base64 encoded crypted string to decrypt
  4117. * @return {string} the decrypted string
  4118. * @public
  4119. */
  4120. JSEncrypt.prototype.decrypt = function(string) {
  4121. // Return the decrypted string.
  4122. try{
  4123. return this.getKey().decrypt(b64tohex(string));
  4124. }catch(ex){
  4125. return false;
  4126. }
  4127. };
  4128. /**
  4129. * Proxy method for RSAKey object's encrypt, encrypt the string using the public
  4130. * components of the rsa key object. Note that if the object was not set will be created
  4131. * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor
  4132. * @param {string} string the string to encrypt
  4133. * @return {string} the encrypted string encoded in base64
  4134. * @public
  4135. */
  4136. JSEncrypt.prototype.encrypt = function(string) {
  4137. // Return the encrypted string.
  4138. try{
  4139. return hex2b64(this.getKey().encrypt(string));
  4140. }catch(ex){
  4141. return false;
  4142. }
  4143. };
  4144. /**
  4145. * Getter for the current JSEncryptRSAKey object. If it doesn't exists a new object
  4146. * will be created and returned
  4147. * @param {callback} [cb] the callback to be called if we want the key to be generated
  4148. * in an async fashion
  4149. * @returns {JSEncryptRSAKey} the JSEncryptRSAKey object
  4150. * @public
  4151. */
  4152. JSEncrypt.prototype.getKey = function(cb){
  4153. // Only create new if it does not exist.
  4154. if (!this.key) {
  4155. // Get a new private key.
  4156. this.key = new JSEncryptRSAKey();
  4157. if (cb && {}.toString.call(cb) === '[object Function]'){
  4158. this.key.generateAsync(this.default_key_size, this.default_public_exponent,cb);
  4159. return;
  4160. }
  4161. // Generate the key.
  4162. this.key.generate(this.default_key_size, this.default_public_exponent);
  4163. }
  4164. return this.key;
  4165. };
  4166. /**
  4167. * Returns the pem encoded representation of the private key
  4168. * If the key doesn't exists a new key will be created
  4169. * @returns {string} pem encoded representation of the private key WITH header and footer
  4170. * @public
  4171. */
  4172. JSEncrypt.prototype.getPrivateKey = function() {
  4173. // Return the private representation of this key.
  4174. return this.getKey().getPrivateKey();
  4175. };
  4176. /**
  4177. * Returns the pem encoded representation of the private key
  4178. * If the key doesn't exists a new key will be created
  4179. * @returns {string} pem encoded representation of the private key WITHOUT header and footer
  4180. * @public
  4181. */
  4182. JSEncrypt.prototype.getPrivateKeyB64 = function() {
  4183. // Return the private representation of this key.
  4184. return this.getKey().getPrivateBaseKeyB64();
  4185. };
  4186. /**
  4187. * Returns the pem encoded representation of the public key
  4188. * If the key doesn't exists a new key will be created
  4189. * @returns {string} pem encoded representation of the public key WITH header and footer
  4190. * @public
  4191. */
  4192. JSEncrypt.prototype.getPublicKey = function() {
  4193. // Return the private representation of this key.
  4194. return this.getKey().getPublicKey();
  4195. };
  4196. /**
  4197. * Returns the pem encoded representation of the public key
  4198. * If the key doesn't exists a new key will be created
  4199. * @returns {string} pem encoded representation of the public key WITHOUT header and footer
  4200. * @public
  4201. */
  4202. JSEncrypt.prototype.getPublicKeyB64 = function() {
  4203. // Return the private representation of this key.
  4204. return this.getKey().getPublicBaseKeyB64();
  4205. };
  4206. exports.JSEncrypt = JSEncrypt;
  4207. })(JSEncryptExports);
  4208. var JSEncrypt = JSEncryptExports.JSEncrypt;
  4209. // Important call
  4210. $.jCryption.crypt = new JSEncrypt();
  4211. /*
  4212. CryptoJS v3.1.2
  4213. code.google.com/p/crypto-js
  4214. (c) 2009-2013 by Jeff Mott. All rights reserved.
  4215. code.google.com/p/crypto-js/wiki/License
  4216. */
  4217. var CryptoJS=CryptoJS||function(u,p){var d={},l=d.lib={},s=function(){},t=l.Base={extend:function(a){s.prototype=this;var c=new s;a&&c.mixIn(a);c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}},
  4218. r=l.WordArray=t.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=p?c:4*a.length},toString:function(a){return(a||v).stringify(this)},concat:function(a){var c=this.words,e=a.words,j=this.sigBytes;a=a.sigBytes;this.clamp();if(j%4)for(var k=0;k<a;k++)c[j+k>>>2]|=(e[k>>>2]>>>24-8*(k%4)&255)<<24-8*((j+k)%4);else if(65535<e.length)for(k=0;k<a;k+=4)c[j+k>>>2]=e[k>>>2];else c.push.apply(c,e);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<<
  4219. 32-8*(c%4);a.length=u.ceil(c/4)},clone:function(){var a=t.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],e=0;e<a;e+=4)c.push(4294967296*u.random()|0);return new r.init(c,a)}}),w=d.enc={},v=w.Hex={stringify:function(a){var c=a.words;a=a.sigBytes;for(var e=[],j=0;j<a;j++){var k=c[j>>>2]>>>24-8*(j%4)&255;e.push((k>>>4).toString(16));e.push((k&15).toString(16))}return e.join("")},parse:function(a){for(var c=a.length,e=[],j=0;j<c;j+=2)e[j>>>3]|=parseInt(a.substr(j,
  4220. 2),16)<<24-4*(j%8);return new r.init(e,c/2)}},b=w.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var e=[],j=0;j<a;j++)e.push(String.fromCharCode(c[j>>>2]>>>24-8*(j%4)&255));return e.join("")},parse:function(a){for(var c=a.length,e=[],j=0;j<c;j++)e[j>>>2]|=(a.charCodeAt(j)&255)<<24-8*(j%4);return new r.init(e,c)}},x=w.Utf8={stringify:function(a){try{return decodeURIComponent(escape(b.stringify(a)))}catch(c){throw Error("Malformed UTF-8 data");}},parse:function(a){return b.parse(unescape(encodeURIComponent(a)))}},
  4221. q=l.BufferedBlockAlgorithm=t.extend({reset:function(){this._data=new r.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=x.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var c=this._data,e=c.words,j=c.sigBytes,k=this.blockSize,b=j/(4*k),b=a?u.ceil(b):u.max((b|0)-this._minBufferSize,0);a=b*k;j=u.min(4*a,j);if(a){for(var q=0;q<a;q+=k)this._doProcessBlock(e,q);q=e.splice(0,a);c.sigBytes-=j}return new r.init(q,j)},clone:function(){var a=t.clone.call(this);
  4222. a._data=this._data.clone();return a},_minBufferSize:0});l.Hasher=q.extend({cfg:t.extend(),init:function(a){this.cfg=this.cfg.extend(a);this.reset()},reset:function(){q.reset.call(this);this._doReset()},update:function(a){this._append(a);this._process();return this},finalize:function(a){a&&this._append(a);return this._doFinalize()},blockSize:16,_createHelper:function(a){return function(b,e){return(new a.init(e)).finalize(b)}},_createHmacHelper:function(a){return function(b,e){return(new n.HMAC.init(a,
  4223. e)).finalize(b)}}});var n=d.algo={};return d}(Math);
  4224. (function(){var u=CryptoJS,p=u.lib.WordArray;u.enc.Base64={stringify:function(d){var l=d.words,p=d.sigBytes,t=this._map;d.clamp();d=[];for(var r=0;r<p;r+=3)for(var w=(l[r>>>2]>>>24-8*(r%4)&255)<<16|(l[r+1>>>2]>>>24-8*((r+1)%4)&255)<<8|l[r+2>>>2]>>>24-8*((r+2)%4)&255,v=0;4>v&&r+0.75*v<p;v++)d.push(t.charAt(w>>>6*(3-v)&63));if(l=t.charAt(64))for(;d.length%4;)d.push(l);return d.join("")},parse:function(d){var l=d.length,s=this._map,t=s.charAt(64);t&&(t=d.indexOf(t),-1!=t&&(l=t));for(var t=[],r=0,w=0;w<
  4225. l;w++)if(w%4){var v=s.indexOf(d.charAt(w-1))<<2*(w%4),b=s.indexOf(d.charAt(w))>>>6-2*(w%4);t[r>>>2]|=(v|b)<<24-8*(r%4);r++}return p.create(t,r)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}})();
  4226. (function(u){function p(b,n,a,c,e,j,k){b=b+(n&a|~n&c)+e+k;return(b<<j|b>>>32-j)+n}function d(b,n,a,c,e,j,k){b=b+(n&c|a&~c)+e+k;return(b<<j|b>>>32-j)+n}function l(b,n,a,c,e,j,k){b=b+(n^a^c)+e+k;return(b<<j|b>>>32-j)+n}function s(b,n,a,c,e,j,k){b=b+(a^(n|~c))+e+k;return(b<<j|b>>>32-j)+n}for(var t=CryptoJS,r=t.lib,w=r.WordArray,v=r.Hasher,r=t.algo,b=[],x=0;64>x;x++)b[x]=4294967296*u.abs(u.sin(x+1))|0;r=r.MD5=v.extend({_doReset:function(){this._hash=new w.init([1732584193,4023233417,2562383102,271733878])},
  4227. _doProcessBlock:function(q,n){for(var a=0;16>a;a++){var c=n+a,e=q[c];q[c]=(e<<8|e>>>24)&16711935|(e<<24|e>>>8)&4278255360}var a=this._hash.words,c=q[n+0],e=q[n+1],j=q[n+2],k=q[n+3],z=q[n+4],r=q[n+5],t=q[n+6],w=q[n+7],v=q[n+8],A=q[n+9],B=q[n+10],C=q[n+11],u=q[n+12],D=q[n+13],E=q[n+14],x=q[n+15],f=a[0],m=a[1],g=a[2],h=a[3],f=p(f,m,g,h,c,7,b[0]),h=p(h,f,m,g,e,12,b[1]),g=p(g,h,f,m,j,17,b[2]),m=p(m,g,h,f,k,22,b[3]),f=p(f,m,g,h,z,7,b[4]),h=p(h,f,m,g,r,12,b[5]),g=p(g,h,f,m,t,17,b[6]),m=p(m,g,h,f,w,22,b[7]),
  4228. f=p(f,m,g,h,v,7,b[8]),h=p(h,f,m,g,A,12,b[9]),g=p(g,h,f,m,B,17,b[10]),m=p(m,g,h,f,C,22,b[11]),f=p(f,m,g,h,u,7,b[12]),h=p(h,f,m,g,D,12,b[13]),g=p(g,h,f,m,E,17,b[14]),m=p(m,g,h,f,x,22,b[15]),f=d(f,m,g,h,e,5,b[16]),h=d(h,f,m,g,t,9,b[17]),g=d(g,h,f,m,C,14,b[18]),m=d(m,g,h,f,c,20,b[19]),f=d(f,m,g,h,r,5,b[20]),h=d(h,f,m,g,B,9,b[21]),g=d(g,h,f,m,x,14,b[22]),m=d(m,g,h,f,z,20,b[23]),f=d(f,m,g,h,A,5,b[24]),h=d(h,f,m,g,E,9,b[25]),g=d(g,h,f,m,k,14,b[26]),m=d(m,g,h,f,v,20,b[27]),f=d(f,m,g,h,D,5,b[28]),h=d(h,f,
  4229. m,g,j,9,b[29]),g=d(g,h,f,m,w,14,b[30]),m=d(m,g,h,f,u,20,b[31]),f=l(f,m,g,h,r,4,b[32]),h=l(h,f,m,g,v,11,b[33]),g=l(g,h,f,m,C,16,b[34]),m=l(m,g,h,f,E,23,b[35]),f=l(f,m,g,h,e,4,b[36]),h=l(h,f,m,g,z,11,b[37]),g=l(g,h,f,m,w,16,b[38]),m=l(m,g,h,f,B,23,b[39]),f=l(f,m,g,h,D,4,b[40]),h=l(h,f,m,g,c,11,b[41]),g=l(g,h,f,m,k,16,b[42]),m=l(m,g,h,f,t,23,b[43]),f=l(f,m,g,h,A,4,b[44]),h=l(h,f,m,g,u,11,b[45]),g=l(g,h,f,m,x,16,b[46]),m=l(m,g,h,f,j,23,b[47]),f=s(f,m,g,h,c,6,b[48]),h=s(h,f,m,g,w,10,b[49]),g=s(g,h,f,m,
  4230. E,15,b[50]),m=s(m,g,h,f,r,21,b[51]),f=s(f,m,g,h,u,6,b[52]),h=s(h,f,m,g,k,10,b[53]),g=s(g,h,f,m,B,15,b[54]),m=s(m,g,h,f,e,21,b[55]),f=s(f,m,g,h,v,6,b[56]),h=s(h,f,m,g,x,10,b[57]),g=s(g,h,f,m,t,15,b[58]),m=s(m,g,h,f,D,21,b[59]),f=s(f,m,g,h,z,6,b[60]),h=s(h,f,m,g,C,10,b[61]),g=s(g,h,f,m,j,15,b[62]),m=s(m,g,h,f,A,21,b[63]);a[0]=a[0]+f|0;a[1]=a[1]+m|0;a[2]=a[2]+g|0;a[3]=a[3]+h|0},_doFinalize:function(){var b=this._data,n=b.words,a=8*this._nDataBytes,c=8*b.sigBytes;n[c>>>5]|=128<<24-c%32;var e=u.floor(a/
  4231. 4294967296);n[(c+64>>>9<<4)+15]=(e<<8|e>>>24)&16711935|(e<<24|e>>>8)&4278255360;n[(c+64>>>9<<4)+14]=(a<<8|a>>>24)&16711935|(a<<24|a>>>8)&4278255360;b.sigBytes=4*(n.length+1);this._process();b=this._hash;n=b.words;for(a=0;4>a;a++)c=n[a],n[a]=(c<<8|c>>>24)&16711935|(c<<24|c>>>8)&4278255360;return b},clone:function(){var b=v.clone.call(this);b._hash=this._hash.clone();return b}});t.MD5=v._createHelper(r);t.HmacMD5=v._createHmacHelper(r)})(Math);
  4232. (function(){var u=CryptoJS,p=u.lib,d=p.Base,l=p.WordArray,p=u.algo,s=p.EvpKDF=d.extend({cfg:d.extend({keySize:4,hasher:p.MD5,iterations:1}),init:function(d){this.cfg=this.cfg.extend(d)},compute:function(d,r){for(var p=this.cfg,s=p.hasher.create(),b=l.create(),u=b.words,q=p.keySize,p=p.iterations;u.length<q;){n&&s.update(n);var n=s.update(d).finalize(r);s.reset();for(var a=1;a<p;a++)n=s.finalize(n),s.reset();b.concat(n)}b.sigBytes=4*q;return b}});u.EvpKDF=function(d,l,p){return s.create(p).compute(d,
  4233. l)}})();
  4234. CryptoJS.lib.Cipher||function(u){var p=CryptoJS,d=p.lib,l=d.Base,s=d.WordArray,t=d.BufferedBlockAlgorithm,r=p.enc.Base64,w=p.algo.EvpKDF,v=d.Cipher=t.extend({cfg:l.extend(),createEncryptor:function(e,a){return this.create(this._ENC_XFORM_MODE,e,a)},createDecryptor:function(e,a){return this.create(this._DEC_XFORM_MODE,e,a)},init:function(e,a,b){this.cfg=this.cfg.extend(b);this._xformMode=e;this._key=a;this.reset()},reset:function(){t.reset.call(this);this._doReset()},process:function(e){this._append(e);return this._process()},
  4235. finalize:function(e){e&&this._append(e);return this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(e){return{encrypt:function(b,k,d){return("string"==typeof k?c:a).encrypt(e,b,k,d)},decrypt:function(b,k,d){return("string"==typeof k?c:a).decrypt(e,b,k,d)}}}});d.StreamCipher=v.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var b=p.mode={},x=function(e,a,b){var c=this._iv;c?this._iv=u:c=this._prevBlock;for(var d=0;d<b;d++)e[a+d]^=
  4236. c[d]},q=(d.BlockCipherMode=l.extend({createEncryptor:function(e,a){return this.Encryptor.create(e,a)},createDecryptor:function(e,a){return this.Decryptor.create(e,a)},init:function(e,a){this._cipher=e;this._iv=a}})).extend();q.Encryptor=q.extend({processBlock:function(e,a){var b=this._cipher,c=b.blockSize;x.call(this,e,a,c);b.encryptBlock(e,a);this._prevBlock=e.slice(a,a+c)}});q.Decryptor=q.extend({processBlock:function(e,a){var b=this._cipher,c=b.blockSize,d=e.slice(a,a+c);b.decryptBlock(e,a);x.call(this,
  4237. e,a,c);this._prevBlock=d}});b=b.CBC=q;q=(p.pad={}).Pkcs7={pad:function(a,b){for(var c=4*b,c=c-a.sigBytes%c,d=c<<24|c<<16|c<<8|c,l=[],n=0;n<c;n+=4)l.push(d);c=s.create(l,c);a.concat(c)},unpad:function(a){a.sigBytes-=a.words[a.sigBytes-1>>>2]&255}};d.BlockCipher=v.extend({cfg:v.cfg.extend({mode:b,padding:q}),reset:function(){v.reset.call(this);var a=this.cfg,b=a.iv,a=a.mode;if(this._xformMode==this._ENC_XFORM_MODE)var c=a.createEncryptor;else c=a.createDecryptor,this._minBufferSize=1;this._mode=c.call(a,
  4238. this,b&&b.words)},_doProcessBlock:function(a,b){this._mode.processBlock(a,b)},_doFinalize:function(){var a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){a.pad(this._data,this.blockSize);var b=this._process(!0)}else b=this._process(!0),a.unpad(b);return b},blockSize:4});var n=d.CipherParams=l.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}}),b=(p.format={}).OpenSSL={stringify:function(a){var b=a.ciphertext;a=a.salt;return(a?s.create([1398893684,
  4239. 1701076831]).concat(a).concat(b):b).toString(r)},parse:function(a){a=r.parse(a);var b=a.words;if(1398893684==b[0]&&1701076831==b[1]){var c=s.create(b.slice(2,4));b.splice(0,4);a.sigBytes-=16}return n.create({ciphertext:a,salt:c})}},a=d.SerializableCipher=l.extend({cfg:l.extend({format:b}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var l=a.createEncryptor(c,d);b=l.finalize(b);l=l.cfg;return n.create({ciphertext:b,key:c,iv:l.iv,algorithm:a,mode:l.mode,padding:l.padding,blockSize:a.blockSize,formatter:d.format})},
  4240. decrypt:function(a,b,c,d){d=this.cfg.extend(d);b=this._parse(b,d.format);return a.createDecryptor(c,d).finalize(b.ciphertext)},_parse:function(a,b){return"string"==typeof a?b.parse(a,this):a}}),p=(p.kdf={}).OpenSSL={execute:function(a,b,c,d){d||(d=s.random(8));a=w.create({keySize:b+c}).compute(a,d);c=s.create(a.words.slice(b),4*c);a.sigBytes=4*b;return n.create({key:a,iv:c,salt:d})}},c=d.PasswordBasedCipher=a.extend({cfg:a.cfg.extend({kdf:p}),encrypt:function(b,c,d,l){l=this.cfg.extend(l);d=l.kdf.execute(d,
  4241. b.keySize,b.ivSize);l.iv=d.iv;b=a.encrypt.call(this,b,c,d.key,l);b.mixIn(d);return b},decrypt:function(b,c,d,l){l=this.cfg.extend(l);c=this._parse(c,l.format);d=l.kdf.execute(d,b.keySize,b.ivSize,c.salt);l.iv=d.iv;return a.decrypt.call(this,b,c,d.key,l)}})}();
  4242. (function(){for(var u=CryptoJS,p=u.lib.BlockCipher,d=u.algo,l=[],s=[],t=[],r=[],w=[],v=[],b=[],x=[],q=[],n=[],a=[],c=0;256>c;c++)a[c]=128>c?c<<1:c<<1^283;for(var e=0,j=0,c=0;256>c;c++){var k=j^j<<1^j<<2^j<<3^j<<4,k=k>>>8^k&255^99;l[e]=k;s[k]=e;var z=a[e],F=a[z],G=a[F],y=257*a[k]^16843008*k;t[e]=y<<24|y>>>8;r[e]=y<<16|y>>>16;w[e]=y<<8|y>>>24;v[e]=y;y=16843009*G^65537*F^257*z^16843008*e;b[k]=y<<24|y>>>8;x[k]=y<<16|y>>>16;q[k]=y<<8|y>>>24;n[k]=y;e?(e=z^a[a[a[G^z]]],j^=a[a[j]]):e=j=1}var H=[0,1,2,4,8,
  4243. 16,32,64,128,27,54],d=d.AES=p.extend({_doReset:function(){for(var a=this._key,c=a.words,d=a.sigBytes/4,a=4*((this._nRounds=d+6)+1),e=this._keySchedule=[],j=0;j<a;j++)if(j<d)e[j]=c[j];else{var k=e[j-1];j%d?6<d&&4==j%d&&(k=l[k>>>24]<<24|l[k>>>16&255]<<16|l[k>>>8&255]<<8|l[k&255]):(k=k<<8|k>>>24,k=l[k>>>24]<<24|l[k>>>16&255]<<16|l[k>>>8&255]<<8|l[k&255],k^=H[j/d|0]<<24);e[j]=e[j-d]^k}c=this._invKeySchedule=[];for(d=0;d<a;d++)j=a-d,k=d%4?e[j]:e[j-4],c[d]=4>d||4>=j?k:b[l[k>>>24]]^x[l[k>>>16&255]]^q[l[k>>>
  4244. 8&255]]^n[l[k&255]]},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._keySchedule,t,r,w,v,l)},decryptBlock:function(a,c){var d=a[c+1];a[c+1]=a[c+3];a[c+3]=d;this._doCryptBlock(a,c,this._invKeySchedule,b,x,q,n,s);d=a[c+1];a[c+1]=a[c+3];a[c+3]=d},_doCryptBlock:function(a,b,c,d,e,j,l,f){for(var m=this._nRounds,g=a[b]^c[0],h=a[b+1]^c[1],k=a[b+2]^c[2],n=a[b+3]^c[3],p=4,r=1;r<m;r++)var q=d[g>>>24]^e[h>>>16&255]^j[k>>>8&255]^l[n&255]^c[p++],s=d[h>>>24]^e[k>>>16&255]^j[n>>>8&255]^l[g&255]^c[p++],t=
  4245. d[k>>>24]^e[n>>>16&255]^j[g>>>8&255]^l[h&255]^c[p++],n=d[n>>>24]^e[g>>>16&255]^j[h>>>8&255]^l[k&255]^c[p++],g=q,h=s,k=t;q=(f[g>>>24]<<24|f[h>>>16&255]<<16|f[k>>>8&255]<<8|f[n&255])^c[p++];s=(f[h>>>24]<<24|f[k>>>16&255]<<16|f[n>>>8&255]<<8|f[g&255])^c[p++];t=(f[k>>>24]<<24|f[n>>>16&255]<<16|f[g>>>8&255]<<8|f[h&255])^c[p++];n=(f[n>>>24]<<24|f[g>>>16&255]<<16|f[h>>>8&255]<<8|f[k&255])^c[p++];a[b]=q;a[b+1]=s;a[b+2]=t;a[b+3]=n},keySize:8});u.AES=p._createHelper(d)})();
  4246. /*
  4247. CryptoJS v3.1.2
  4248. code.google.com/p/crypto-js
  4249. (c) 2009-2013 by Jeff Mott. All rights reserved.
  4250. code.google.com/p/crypto-js/wiki/License
  4251. */
  4252. var CryptoJS=CryptoJS||function(a,m){var r={},f=r.lib={},g=function(){},l=f.Base={extend:function(a){g.prototype=this;var b=new g;a&&b.mixIn(a);b.hasOwnProperty("init")||(b.init=function(){b.$super.init.apply(this,arguments)});b.init.prototype=b;b.$super=this;return b},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var b in a)a.hasOwnProperty(b)&&(this[b]=a[b]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}},
  4253. p=f.WordArray=l.extend({init:function(a,b){a=this.words=a||[];this.sigBytes=b!=m?b:4*a.length},toString:function(a){return(a||q).stringify(this)},concat:function(a){var b=this.words,d=a.words,c=this.sigBytes;a=a.sigBytes;this.clamp();if(c%4)for(var j=0;j<a;j++)b[c+j>>>2]|=(d[j>>>2]>>>24-8*(j%4)&255)<<24-8*((c+j)%4);else if(65535<d.length)for(j=0;j<a;j+=4)b[c+j>>>2]=d[j>>>2];else b.push.apply(b,d);this.sigBytes+=a;return this},clamp:function(){var n=this.words,b=this.sigBytes;n[b>>>2]&=4294967295<<
  4254. 32-8*(b%4);n.length=a.ceil(b/4)},clone:function(){var a=l.clone.call(this);a.words=this.words.slice(0);return a},random:function(n){for(var b=[],d=0;d<n;d+=4)b.push(4294967296*a.random()|0);return new p.init(b,n)}}),y=r.enc={},q=y.Hex={stringify:function(a){var b=a.words;a=a.sigBytes;for(var d=[],c=0;c<a;c++){var j=b[c>>>2]>>>24-8*(c%4)&255;d.push((j>>>4).toString(16));d.push((j&15).toString(16))}return d.join("")},parse:function(a){for(var b=a.length,d=[],c=0;c<b;c+=2)d[c>>>3]|=parseInt(a.substr(c,
  4255. 2),16)<<24-4*(c%8);return new p.init(d,b/2)}},G=y.Latin1={stringify:function(a){var b=a.words;a=a.sigBytes;for(var d=[],c=0;c<a;c++)d.push(String.fromCharCode(b[c>>>2]>>>24-8*(c%4)&255));return d.join("")},parse:function(a){for(var b=a.length,d=[],c=0;c<b;c++)d[c>>>2]|=(a.charCodeAt(c)&255)<<24-8*(c%4);return new p.init(d,b)}},fa=y.Utf8={stringify:function(a){try{return decodeURIComponent(escape(G.stringify(a)))}catch(b){throw Error("Malformed UTF-8 data");}},parse:function(a){return G.parse(unescape(encodeURIComponent(a)))}},
  4256. h=f.BufferedBlockAlgorithm=l.extend({reset:function(){this._data=new p.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=fa.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(n){var b=this._data,d=b.words,c=b.sigBytes,j=this.blockSize,l=c/(4*j),l=n?a.ceil(l):a.max((l|0)-this._minBufferSize,0);n=l*j;c=a.min(4*n,c);if(n){for(var h=0;h<n;h+=j)this._doProcessBlock(d,h);h=d.splice(0,n);b.sigBytes-=c}return new p.init(h,c)},clone:function(){var a=l.clone.call(this);
  4257. a._data=this._data.clone();return a},_minBufferSize:0});f.Hasher=h.extend({cfg:l.extend(),init:function(a){this.cfg=this.cfg.extend(a);this.reset()},reset:function(){h.reset.call(this);this._doReset()},update:function(a){this._append(a);this._process();return this},finalize:function(a){a&&this._append(a);return this._doFinalize()},blockSize:16,_createHelper:function(a){return function(b,d){return(new a.init(d)).finalize(b)}},_createHmacHelper:function(a){return function(b,d){return(new ga.HMAC.init(a,
  4258. d)).finalize(b)}}});var ga=r.algo={};return r}(Math);
  4259. (function(a){var m=CryptoJS,r=m.lib,f=r.Base,g=r.WordArray,m=m.x64={};m.Word=f.extend({init:function(a,p){this.high=a;this.low=p}});m.WordArray=f.extend({init:function(l,p){l=this.words=l||[];this.sigBytes=p!=a?p:8*l.length},toX32:function(){for(var a=this.words,p=a.length,f=[],q=0;q<p;q++){var G=a[q];f.push(G.high);f.push(G.low)}return g.create(f,this.sigBytes)},clone:function(){for(var a=f.clone.call(this),p=a.words=this.words.slice(0),g=p.length,q=0;q<g;q++)p[q]=p[q].clone();return a}})})();
  4260. (function(){function a(){return g.create.apply(g,arguments)}for(var m=CryptoJS,r=m.lib.Hasher,f=m.x64,g=f.Word,l=f.WordArray,f=m.algo,p=[a(1116352408,3609767458),a(1899447441,602891725),a(3049323471,3964484399),a(3921009573,2173295548),a(961987163,4081628472),a(1508970993,3053834265),a(2453635748,2937671579),a(2870763221,3664609560),a(3624381080,2734883394),a(310598401,1164996542),a(607225278,1323610764),a(1426881987,3590304994),a(1925078388,4068182383),a(2162078206,991336113),a(2614888103,633803317),
  4261. a(3248222580,3479774868),a(3835390401,2666613458),a(4022224774,944711139),a(264347078,2341262773),a(604807628,2007800933),a(770255983,1495990901),a(1249150122,1856431235),a(1555081692,3175218132),a(1996064986,2198950837),a(2554220882,3999719339),a(2821834349,766784016),a(2952996808,2566594879),a(3210313671,3203337956),a(3336571891,1034457026),a(3584528711,2466948901),a(113926993,3758326383),a(338241895,168717936),a(666307205,1188179964),a(773529912,1546045734),a(1294757372,1522805485),a(1396182291,
  4262. 2643833823),a(1695183700,2343527390),a(1986661051,1014477480),a(2177026350,1206759142),a(2456956037,344077627),a(2730485921,1290863460),a(2820302411,3158454273),a(3259730800,3505952657),a(3345764771,106217008),a(3516065817,3606008344),a(3600352804,1432725776),a(4094571909,1467031594),a(275423344,851169720),a(430227734,3100823752),a(506948616,1363258195),a(659060556,3750685593),a(883997877,3785050280),a(958139571,3318307427),a(1322822218,3812723403),a(1537002063,2003034995),a(1747873779,3602036899),
  4263. a(1955562222,1575990012),a(2024104815,1125592928),a(2227730452,2716904306),a(2361852424,442776044),a(2428436474,593698344),a(2756734187,3733110249),a(3204031479,2999351573),a(3329325298,3815920427),a(3391569614,3928383900),a(3515267271,566280711),a(3940187606,3454069534),a(4118630271,4000239992),a(116418474,1914138554),a(174292421,2731055270),a(289380356,3203993006),a(460393269,320620315),a(685471733,587496836),a(852142971,1086792851),a(1017036298,365543100),a(1126000580,2618297676),a(1288033470,
  4264. 3409855158),a(1501505948,4234509866),a(1607167915,987167468),a(1816402316,1246189591)],y=[],q=0;80>q;q++)y[q]=a();f=f.SHA512=r.extend({_doReset:function(){this._hash=new l.init([new g.init(1779033703,4089235720),new g.init(3144134277,2227873595),new g.init(1013904242,4271175723),new g.init(2773480762,1595750129),new g.init(1359893119,2917565137),new g.init(2600822924,725511199),new g.init(528734635,4215389547),new g.init(1541459225,327033209)])},_doProcessBlock:function(a,f){for(var h=this._hash.words,
  4265. g=h[0],n=h[1],b=h[2],d=h[3],c=h[4],j=h[5],l=h[6],h=h[7],q=g.high,m=g.low,r=n.high,N=n.low,Z=b.high,O=b.low,$=d.high,P=d.low,aa=c.high,Q=c.low,ba=j.high,R=j.low,ca=l.high,S=l.low,da=h.high,T=h.low,v=q,s=m,H=r,E=N,I=Z,F=O,W=$,J=P,w=aa,t=Q,U=ba,K=R,V=ca,L=S,X=da,M=T,x=0;80>x;x++){var B=y[x];if(16>x)var u=B.high=a[f+2*x]|0,e=B.low=a[f+2*x+1]|0;else{var u=y[x-15],e=u.high,z=u.low,u=(e>>>1|z<<31)^(e>>>8|z<<24)^e>>>7,z=(z>>>1|e<<31)^(z>>>8|e<<24)^(z>>>7|e<<25),D=y[x-2],e=D.high,k=D.low,D=(e>>>19|k<<13)^
  4266. (e<<3|k>>>29)^e>>>6,k=(k>>>19|e<<13)^(k<<3|e>>>29)^(k>>>6|e<<26),e=y[x-7],Y=e.high,C=y[x-16],A=C.high,C=C.low,e=z+e.low,u=u+Y+(e>>>0<z>>>0?1:0),e=e+k,u=u+D+(e>>>0<k>>>0?1:0),e=e+C,u=u+A+(e>>>0<C>>>0?1:0);B.high=u;B.low=e}var Y=w&U^~w&V,C=t&K^~t&L,B=v&H^v&I^H&I,ha=s&E^s&F^E&F,z=(v>>>28|s<<4)^(v<<30|s>>>2)^(v<<25|s>>>7),D=(s>>>28|v<<4)^(s<<30|v>>>2)^(s<<25|v>>>7),k=p[x],ia=k.high,ea=k.low,k=M+((t>>>14|w<<18)^(t>>>18|w<<14)^(t<<23|w>>>9)),A=X+((w>>>14|t<<18)^(w>>>18|t<<14)^(w<<23|t>>>9))+(k>>>0<M>>>
  4267. 0?1:0),k=k+C,A=A+Y+(k>>>0<C>>>0?1:0),k=k+ea,A=A+ia+(k>>>0<ea>>>0?1:0),k=k+e,A=A+u+(k>>>0<e>>>0?1:0),e=D+ha,B=z+B+(e>>>0<D>>>0?1:0),X=V,M=L,V=U,L=K,U=w,K=t,t=J+k|0,w=W+A+(t>>>0<J>>>0?1:0)|0,W=I,J=F,I=H,F=E,H=v,E=s,s=k+e|0,v=A+B+(s>>>0<k>>>0?1:0)|0}m=g.low=m+s;g.high=q+v+(m>>>0<s>>>0?1:0);N=n.low=N+E;n.high=r+H+(N>>>0<E>>>0?1:0);O=b.low=O+F;b.high=Z+I+(O>>>0<F>>>0?1:0);P=d.low=P+J;d.high=$+W+(P>>>0<J>>>0?1:0);Q=c.low=Q+t;c.high=aa+w+(Q>>>0<t>>>0?1:0);R=j.low=R+K;j.high=ba+U+(R>>>0<K>>>0?1:0);S=l.low=
  4268. S+L;l.high=ca+V+(S>>>0<L>>>0?1:0);T=h.low=T+M;h.high=da+X+(T>>>0<M>>>0?1:0)},_doFinalize:function(){var a=this._data,f=a.words,h=8*this._nDataBytes,g=8*a.sigBytes;f[g>>>5]|=128<<24-g%32;f[(g+128>>>10<<5)+30]=Math.floor(h/4294967296);f[(g+128>>>10<<5)+31]=h;a.sigBytes=4*f.length;this._process();return this._hash.toX32()},clone:function(){var a=r.clone.call(this);a._hash=this._hash.clone();return a},blockSize:32});m.SHA512=r._createHelper(f);m.HmacSHA512=r._createHmacHelper(f)})();
  4269. /*
  4270. CryptoJS v3.1.2
  4271. code.google.com/p/crypto-js
  4272. (c) 2009-2013 by Jeff Mott. All rights reserved.
  4273. code.google.com/p/crypto-js/wiki/License
  4274. */
  4275. var CryptoJS=CryptoJS||function(g,j){var e={},d=e.lib={},m=function(){},n=d.Base={extend:function(a){m.prototype=this;var c=new m;a&&c.mixIn(a);c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)});c.init.prototype=c;c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}},
  4276. q=d.WordArray=n.extend({init:function(a,c){a=this.words=a||[];this.sigBytes=c!=j?c:4*a.length},toString:function(a){return(a||l).stringify(this)},concat:function(a){var c=this.words,p=a.words,f=this.sigBytes;a=a.sigBytes;this.clamp();if(f%4)for(var b=0;b<a;b++)c[f+b>>>2]|=(p[b>>>2]>>>24-8*(b%4)&255)<<24-8*((f+b)%4);else if(65535<p.length)for(b=0;b<a;b+=4)c[f+b>>>2]=p[b>>>2];else c.push.apply(c,p);this.sigBytes+=a;return this},clamp:function(){var a=this.words,c=this.sigBytes;a[c>>>2]&=4294967295<<
  4277. 32-8*(c%4);a.length=g.ceil(c/4)},clone:function(){var a=n.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var c=[],b=0;b<a;b+=4)c.push(4294967296*g.random()|0);return new q.init(c,a)}}),b=e.enc={},l=b.Hex={stringify:function(a){var c=a.words;a=a.sigBytes;for(var b=[],f=0;f<a;f++){var d=c[f>>>2]>>>24-8*(f%4)&255;b.push((d>>>4).toString(16));b.push((d&15).toString(16))}return b.join("")},parse:function(a){for(var c=a.length,b=[],f=0;f<c;f+=2)b[f>>>3]|=parseInt(a.substr(f,
  4278. 2),16)<<24-4*(f%8);return new q.init(b,c/2)}},k=b.Latin1={stringify:function(a){var c=a.words;a=a.sigBytes;for(var b=[],f=0;f<a;f++)b.push(String.fromCharCode(c[f>>>2]>>>24-8*(f%4)&255));return b.join("")},parse:function(a){for(var c=a.length,b=[],f=0;f<c;f++)b[f>>>2]|=(a.charCodeAt(f)&255)<<24-8*(f%4);return new q.init(b,c)}},h=b.Utf8={stringify:function(a){try{return decodeURIComponent(escape(k.stringify(a)))}catch(b){throw Error("Malformed UTF-8 data");}},parse:function(a){return k.parse(unescape(encodeURIComponent(a)))}},
  4279. u=d.BufferedBlockAlgorithm=n.extend({reset:function(){this._data=new q.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=h.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var b=this._data,d=b.words,f=b.sigBytes,l=this.blockSize,e=f/(4*l),e=a?g.ceil(e):g.max((e|0)-this._minBufferSize,0);a=e*l;f=g.min(4*a,f);if(a){for(var h=0;h<a;h+=l)this._doProcessBlock(d,h);h=d.splice(0,a);b.sigBytes-=f}return new q.init(h,f)},clone:function(){var a=n.clone.call(this);
  4280. a._data=this._data.clone();return a},_minBufferSize:0});d.Hasher=u.extend({cfg:n.extend(),init:function(a){this.cfg=this.cfg.extend(a);this.reset()},reset:function(){u.reset.call(this);this._doReset()},update:function(a){this._append(a);this._process();return this},finalize:function(a){a&&this._append(a);return this._doFinalize()},blockSize:16,_createHelper:function(a){return function(b,d){return(new a.init(d)).finalize(b)}},_createHmacHelper:function(a){return function(b,d){return(new w.HMAC.init(a,
  4281. d)).finalize(b)}}});var w=e.algo={};return e}(Math);
  4282. (function(){var g=CryptoJS,j=g.lib,e=j.WordArray,d=j.Hasher,m=[],j=g.algo.SHA1=d.extend({_doReset:function(){this._hash=new e.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(d,e){for(var b=this._hash.words,l=b[0],k=b[1],h=b[2],g=b[3],j=b[4],a=0;80>a;a++){if(16>a)m[a]=d[e+a]|0;else{var c=m[a-3]^m[a-8]^m[a-14]^m[a-16];m[a]=c<<1|c>>>31}c=(l<<5|l>>>27)+j+m[a];c=20>a?c+((k&h|~k&g)+1518500249):40>a?c+((k^h^g)+1859775393):60>a?c+((k&h|k&g|h&g)-1894007588):c+((k^h^
  4283. g)-899497514);j=g;g=h;h=k<<30|k>>>2;k=l;l=c}b[0]=b[0]+l|0;b[1]=b[1]+k|0;b[2]=b[2]+h|0;b[3]=b[3]+g|0;b[4]=b[4]+j|0},_doFinalize:function(){var d=this._data,e=d.words,b=8*this._nDataBytes,l=8*d.sigBytes;e[l>>>5]|=128<<24-l%32;e[(l+64>>>9<<4)+14]=Math.floor(b/4294967296);e[(l+64>>>9<<4)+15]=b;d.sigBytes=4*e.length;this._process();return this._hash},clone:function(){var e=d.clone.call(this);e._hash=this._hash.clone();return e}});g.SHA1=d._createHelper(j);g.HmacSHA1=d._createHmacHelper(j)})();
  4284. (function(){var g=CryptoJS,j=g.enc.Utf8;g.algo.HMAC=g.lib.Base.extend({init:function(e,d){e=this._hasher=new e.init;"string"==typeof d&&(d=j.parse(d));var g=e.blockSize,n=4*g;d.sigBytes>n&&(d=e.finalize(d));d.clamp();for(var q=this._oKey=d.clone(),b=this._iKey=d.clone(),l=q.words,k=b.words,h=0;h<g;h++)l[h]^=1549556828,k[h]^=909522486;q.sigBytes=b.sigBytes=n;this.reset()},reset:function(){var e=this._hasher;e.reset();e.update(this._iKey)},update:function(e){this._hasher.update(e);return this},finalize:function(e){var d=
  4285. this._hasher;e=d.finalize(e);d.reset();return d.finalize(this._oKey.clone().concat(e))}})})();
  4286. (function(){var g=CryptoJS,j=g.lib,e=j.Base,d=j.WordArray,j=g.algo,m=j.HMAC,n=j.PBKDF2=e.extend({cfg:e.extend({keySize:4,hasher:j.SHA1,iterations:1}),init:function(d){this.cfg=this.cfg.extend(d)},compute:function(e,b){for(var g=this.cfg,k=m.create(g.hasher,e),h=d.create(),j=d.create([1]),n=h.words,a=j.words,c=g.keySize,g=g.iterations;n.length<c;){var p=k.update(b).finalize(j);k.reset();for(var f=p.words,v=f.length,s=p,t=1;t<g;t++){s=k.finalize(s);k.reset();for(var x=s.words,r=0;r<v;r++)f[r]^=x[r]}h.concat(p);
  4287. a[0]++}h.sigBytes=4*c;return h}});g.PBKDF2=function(d,b,e){return n.create(e).compute(d,b)}})();