jsencrypt.js 170 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (factory((global.JSEncrypt = {})));
  5. }(this, (function (exports) { 'use strict';
  6. var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
  7. function int2char(n) {
  8. return BI_RM.charAt(n);
  9. }
  10. //#region BIT_OPERATIONS
  11. // (public) this & a
  12. function op_and(x, y) {
  13. return x & y;
  14. }
  15. // (public) this | a
  16. function op_or(x, y) {
  17. return x | y;
  18. }
  19. // (public) this ^ a
  20. function op_xor(x, y) {
  21. return x ^ y;
  22. }
  23. // (public) this & ~a
  24. function op_andnot(x, y) {
  25. return x & ~y;
  26. }
  27. // return index of lowest 1-bit in x, x < 2^31
  28. function lbit(x) {
  29. if (x == 0) {
  30. return -1;
  31. }
  32. var r = 0;
  33. if ((x & 0xffff) == 0) {
  34. x >>= 16;
  35. r += 16;
  36. }
  37. if ((x & 0xff) == 0) {
  38. x >>= 8;
  39. r += 8;
  40. }
  41. if ((x & 0xf) == 0) {
  42. x >>= 4;
  43. r += 4;
  44. }
  45. if ((x & 3) == 0) {
  46. x >>= 2;
  47. r += 2;
  48. }
  49. if ((x & 1) == 0) {
  50. ++r;
  51. }
  52. return r;
  53. }
  54. // return number of 1 bits in x
  55. function cbit(x) {
  56. var r = 0;
  57. while (x != 0) {
  58. x &= x - 1;
  59. ++r;
  60. }
  61. return r;
  62. }
  63. //#endregion BIT_OPERATIONS
  64. var b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  65. var b64pad = "=";
  66. function hex2b64(h) {
  67. var i;
  68. var c;
  69. var ret = "";
  70. for (i = 0; i + 3 <= h.length; i += 3) {
  71. c = parseInt(h.substring(i, i + 3), 16);
  72. ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63);
  73. }
  74. if (i + 1 == h.length) {
  75. c = parseInt(h.substring(i, i + 1), 16);
  76. ret += b64map.charAt(c << 2);
  77. }
  78. else if (i + 2 == h.length) {
  79. c = parseInt(h.substring(i, i + 2), 16);
  80. ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4);
  81. }
  82. while ((ret.length & 3) > 0) {
  83. ret += b64pad;
  84. }
  85. return ret;
  86. }
  87. // convert a base64 string to hex
  88. function b64tohex(s) {
  89. var ret = "";
  90. var i;
  91. var k = 0; // b64 state, 0-3
  92. var slop = 0;
  93. for (i = 0; i < s.length; ++i) {
  94. if (s.charAt(i) == b64pad) {
  95. break;
  96. }
  97. var v = b64map.indexOf(s.charAt(i));
  98. if (v < 0) {
  99. continue;
  100. }
  101. if (k == 0) {
  102. ret += int2char(v >> 2);
  103. slop = v & 3;
  104. k = 1;
  105. }
  106. else if (k == 1) {
  107. ret += int2char((slop << 2) | (v >> 4));
  108. slop = v & 0xf;
  109. k = 2;
  110. }
  111. else if (k == 2) {
  112. ret += int2char(slop);
  113. ret += int2char(v >> 2);
  114. slop = v & 3;
  115. k = 3;
  116. }
  117. else {
  118. ret += int2char((slop << 2) | (v >> 4));
  119. ret += int2char(v & 0xf);
  120. k = 0;
  121. }
  122. }
  123. if (k == 1) {
  124. ret += int2char(slop << 2);
  125. }
  126. return ret;
  127. }
  128. /*! *****************************************************************************
  129. Copyright (c) Microsoft Corporation. All rights reserved.
  130. Licensed under the Apache License, Version 2.0 (the "License"); you may not use
  131. this file except in compliance with the License. You may obtain a copy of the
  132. License at http://www.apache.org/licenses/LICENSE-2.0
  133. THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  134. KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
  135. WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
  136. MERCHANTABLITY OR NON-INFRINGEMENT.
  137. See the Apache Version 2.0 License for specific language governing permissions
  138. and limitations under the License.
  139. ***************************************************************************** */
  140. /* global Reflect, Promise */
  141. var extendStatics = Object.setPrototypeOf ||
  142. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  143. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  144. function __extends(d, b) {
  145. extendStatics(d, b);
  146. function __() { this.constructor = d; }
  147. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  148. }
  149. // Hex JavaScript decoder
  150. // Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it>
  151. // Permission to use, copy, modify, and/or distribute this software for any
  152. // purpose with or without fee is hereby granted, provided that the above
  153. // copyright notice and this permission notice appear in all copies.
  154. //
  155. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  156. // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  157. // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  158. // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  159. // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  160. // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  161. // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  162. /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
  163. var decoder;
  164. var Hex = {
  165. decode: function (a) {
  166. var i;
  167. if (decoder === undefined) {
  168. var hex = "0123456789ABCDEF";
  169. var ignore = " \f\n\r\t\u00A0\u2028\u2029";
  170. decoder = {};
  171. for (i = 0; i < 16; ++i) {
  172. decoder[hex.charAt(i)] = i;
  173. }
  174. hex = hex.toLowerCase();
  175. for (i = 10; i < 16; ++i) {
  176. decoder[hex.charAt(i)] = i;
  177. }
  178. for (i = 0; i < ignore.length; ++i) {
  179. decoder[ignore.charAt(i)] = -1;
  180. }
  181. }
  182. var out = [];
  183. var bits = 0;
  184. var char_count = 0;
  185. for (i = 0; i < a.length; ++i) {
  186. var c = a.charAt(i);
  187. if (c == "=") {
  188. break;
  189. }
  190. c = decoder[c];
  191. if (c == -1) {
  192. continue;
  193. }
  194. if (c === undefined) {
  195. throw new Error("Illegal character at offset " + i);
  196. }
  197. bits |= c;
  198. if (++char_count >= 2) {
  199. out[out.length] = bits;
  200. bits = 0;
  201. char_count = 0;
  202. }
  203. else {
  204. bits <<= 4;
  205. }
  206. }
  207. if (char_count) {
  208. throw new Error("Hex encoding incomplete: 4 bits missing");
  209. }
  210. return out;
  211. }
  212. };
  213. // Base64 JavaScript decoder
  214. // Copyright (c) 2008-2013 Lapo Luchini <lapo@lapo.it>
  215. // Permission to use, copy, modify, and/or distribute this software for any
  216. // purpose with or without fee is hereby granted, provided that the above
  217. // copyright notice and this permission notice appear in all copies.
  218. //
  219. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  220. // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  221. // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  222. // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  223. // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  224. // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  225. // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  226. /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
  227. var decoder$1;
  228. var Base64 = {
  229. decode: function (a) {
  230. var i;
  231. if (decoder$1 === undefined) {
  232. var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  233. var ignore = "= \f\n\r\t\u00A0\u2028\u2029";
  234. decoder$1 = Object.create(null);
  235. for (i = 0; i < 64; ++i) {
  236. decoder$1[b64.charAt(i)] = i;
  237. }
  238. for (i = 0; i < ignore.length; ++i) {
  239. decoder$1[ignore.charAt(i)] = -1;
  240. }
  241. }
  242. var out = [];
  243. var bits = 0;
  244. var char_count = 0;
  245. for (i = 0; i < a.length; ++i) {
  246. var c = a.charAt(i);
  247. if (c == "=") {
  248. break;
  249. }
  250. c = decoder$1[c];
  251. if (c == -1) {
  252. continue;
  253. }
  254. if (c === undefined) {
  255. throw new Error("Illegal character at offset " + i);
  256. }
  257. bits |= c;
  258. if (++char_count >= 4) {
  259. out[out.length] = (bits >> 16);
  260. out[out.length] = (bits >> 8) & 0xFF;
  261. out[out.length] = bits & 0xFF;
  262. bits = 0;
  263. char_count = 0;
  264. }
  265. else {
  266. bits <<= 6;
  267. }
  268. }
  269. switch (char_count) {
  270. case 1:
  271. throw new Error("Base64 encoding incomplete: at least 2 bits missing");
  272. case 2:
  273. out[out.length] = (bits >> 10);
  274. break;
  275. case 3:
  276. out[out.length] = (bits >> 16);
  277. out[out.length] = (bits >> 8) & 0xFF;
  278. break;
  279. }
  280. return out;
  281. },
  282. re: /-----BEGIN [^-]+-----([A-Za-z0-9+\/=\s]+)-----END [^-]+-----|begin-base64[^\n]+\n([A-Za-z0-9+\/=\s]+)====/,
  283. unarmor: function (a) {
  284. var m = Base64.re.exec(a);
  285. if (m) {
  286. if (m[1]) {
  287. a = m[1];
  288. }
  289. else if (m[2]) {
  290. a = m[2];
  291. }
  292. else {
  293. throw new Error("RegExp out of sync");
  294. }
  295. }
  296. return Base64.decode(a);
  297. }
  298. };
  299. // Big integer base-10 printing library
  300. // Copyright (c) 2014 Lapo Luchini <lapo@lapo.it>
  301. // Permission to use, copy, modify, and/or distribute this software for any
  302. // purpose with or without fee is hereby granted, provided that the above
  303. // copyright notice and this permission notice appear in all copies.
  304. //
  305. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  306. // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  307. // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  308. // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  309. // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  310. // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  311. // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  312. /*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */
  313. var max = 10000000000000; // biggest integer that can still fit 2^53 when multiplied by 256
  314. var Int10 = /** @class */ (function () {
  315. function Int10(value) {
  316. this.buf = [+value || 0];
  317. }
  318. Int10.prototype.mulAdd = function (m, c) {
  319. // assert(m <= 256)
  320. var b = this.buf;
  321. var l = b.length;
  322. var i;
  323. var t;
  324. for (i = 0; i < l; ++i) {
  325. t = b[i] * m + c;
  326. if (t < max) {
  327. c = 0;
  328. }
  329. else {
  330. c = 0 | (t / max);
  331. t -= c * max;
  332. }
  333. b[i] = t;
  334. }
  335. if (c > 0) {
  336. b[i] = c;
  337. }
  338. };
  339. Int10.prototype.sub = function (c) {
  340. // assert(m <= 256)
  341. var b = this.buf;
  342. var l = b.length;
  343. var i;
  344. var t;
  345. for (i = 0; i < l; ++i) {
  346. t = b[i] - c;
  347. if (t < 0) {
  348. t += max;
  349. c = 1;
  350. }
  351. else {
  352. c = 0;
  353. }
  354. b[i] = t;
  355. }
  356. while (b[b.length - 1] === 0) {
  357. b.pop();
  358. }
  359. };
  360. Int10.prototype.toString = function (base) {
  361. if ((base || 10) != 10) {
  362. throw new Error("only base 10 is supported");
  363. }
  364. var b = this.buf;
  365. var s = b[b.length - 1].toString();
  366. for (var i = b.length - 2; i >= 0; --i) {
  367. s += (max + b[i]).toString().substring(1);
  368. }
  369. return s;
  370. };
  371. Int10.prototype.valueOf = function () {
  372. var b = this.buf;
  373. var v = 0;
  374. for (var i = b.length - 1; i >= 0; --i) {
  375. v = v * max + b[i];
  376. }
  377. return v;
  378. };
  379. Int10.prototype.simplify = function () {
  380. var b = this.buf;
  381. return (b.length == 1) ? b[0] : this;
  382. };
  383. return Int10;
  384. }());
  385. // ASN.1 JavaScript decoder
  386. var ellipsis = "\u2026";
  387. var reTimeS = /^(\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)?)?$/;
  388. var reTimeL = /^(\d\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)?)?$/;
  389. function stringCut(str, len) {
  390. if (str.length > len) {
  391. str = str.substring(0, len) + ellipsis;
  392. }
  393. return str;
  394. }
  395. var Stream = /** @class */ (function () {
  396. function Stream(enc, pos) {
  397. this.hexDigits = "0123456789ABCDEF";
  398. if (enc instanceof Stream) {
  399. this.enc = enc.enc;
  400. this.pos = enc.pos;
  401. }
  402. else {
  403. // enc should be an array or a binary string
  404. this.enc = enc;
  405. this.pos = pos;
  406. }
  407. }
  408. Stream.prototype.get = function (pos) {
  409. if (pos === undefined) {
  410. pos = this.pos++;
  411. }
  412. if (pos >= this.enc.length) {
  413. throw new Error("Requesting byte offset " + pos + " on a stream of length " + this.enc.length);
  414. }
  415. return ("string" === typeof this.enc) ? this.enc.charCodeAt(pos) : this.enc[pos];
  416. };
  417. Stream.prototype.hexByte = function (b) {
  418. return this.hexDigits.charAt((b >> 4) & 0xF) + this.hexDigits.charAt(b & 0xF);
  419. };
  420. Stream.prototype.hexDump = function (start, end, raw) {
  421. var s = "";
  422. for (var i = start; i < end; ++i) {
  423. s += this.hexByte(this.get(i));
  424. if (raw !== true) {
  425. switch (i & 0xF) {
  426. case 0x7:
  427. s += " ";
  428. break;
  429. case 0xF:
  430. s += "\n";
  431. break;
  432. default:
  433. s += " ";
  434. }
  435. }
  436. }
  437. return s;
  438. };
  439. Stream.prototype.isASCII = function (start, end) {
  440. for (var i = start; i < end; ++i) {
  441. var c = this.get(i);
  442. if (c < 32 || c > 176) {
  443. return false;
  444. }
  445. }
  446. return true;
  447. };
  448. Stream.prototype.parseStringISO = function (start, end) {
  449. var s = "";
  450. for (var i = start; i < end; ++i) {
  451. s += String.fromCharCode(this.get(i));
  452. }
  453. return s;
  454. };
  455. Stream.prototype.parseStringUTF = function (start, end) {
  456. var s = "";
  457. for (var i = start; i < end;) {
  458. var c = this.get(i++);
  459. if (c < 128) {
  460. s += String.fromCharCode(c);
  461. }
  462. else if ((c > 191) && (c < 224)) {
  463. s += String.fromCharCode(((c & 0x1F) << 6) | (this.get(i++) & 0x3F));
  464. }
  465. else {
  466. s += String.fromCharCode(((c & 0x0F) << 12) | ((this.get(i++) & 0x3F) << 6) | (this.get(i++) & 0x3F));
  467. }
  468. }
  469. return s;
  470. };
  471. Stream.prototype.parseStringBMP = function (start, end) {
  472. var str = "";
  473. var hi;
  474. var lo;
  475. for (var i = start; i < end;) {
  476. hi = this.get(i++);
  477. lo = this.get(i++);
  478. str += String.fromCharCode((hi << 8) | lo);
  479. }
  480. return str;
  481. };
  482. Stream.prototype.parseTime = function (start, end, shortYear) {
  483. var s = this.parseStringISO(start, end);
  484. var m = (shortYear ? reTimeS : reTimeL).exec(s);
  485. if (!m) {
  486. return "Unrecognized time: " + s;
  487. }
  488. if (shortYear) {
  489. // to avoid querying the timer, use the fixed range [1970, 2069]
  490. // it will conform with ITU X.400 [-10, +40] sliding window until 2030
  491. m[1] = +m[1];
  492. m[1] += (+m[1] < 70) ? 2000 : 1900;
  493. }
  494. s = m[1] + "-" + m[2] + "-" + m[3] + " " + m[4];
  495. if (m[5]) {
  496. s += ":" + m[5];
  497. if (m[6]) {
  498. s += ":" + m[6];
  499. if (m[7]) {
  500. s += "." + m[7];
  501. }
  502. }
  503. }
  504. if (m[8]) {
  505. s += " UTC";
  506. if (m[8] != "Z") {
  507. s += m[8];
  508. if (m[9]) {
  509. s += ":" + m[9];
  510. }
  511. }
  512. }
  513. return s;
  514. };
  515. Stream.prototype.parseInteger = function (start, end) {
  516. var v = this.get(start);
  517. var neg = (v > 127);
  518. var pad = neg ? 255 : 0;
  519. var len;
  520. var s = "";
  521. // skip unuseful bits (not allowed in DER)
  522. while (v == pad && ++start < end) {
  523. v = this.get(start);
  524. }
  525. len = end - start;
  526. if (len === 0) {
  527. return neg ? -1 : 0;
  528. }
  529. // show bit length of huge integers
  530. if (len > 4) {
  531. s = v;
  532. len <<= 3;
  533. while (((+s ^ pad) & 0x80) == 0) {
  534. s = +s << 1;
  535. --len;
  536. }
  537. s = "(" + len + " bit)\n";
  538. }
  539. // decode the integer
  540. if (neg) {
  541. v = v - 256;
  542. }
  543. var n = new Int10(v);
  544. for (var i = start + 1; i < end; ++i) {
  545. n.mulAdd(256, this.get(i));
  546. }
  547. return s + n.toString();
  548. };
  549. Stream.prototype.parseBitString = function (start, end, maxLength) {
  550. var unusedBit = this.get(start);
  551. var lenBit = ((end - start - 1) << 3) - unusedBit;
  552. var intro = "(" + lenBit + " bit)\n";
  553. var s = "";
  554. for (var i = start + 1; i < end; ++i) {
  555. var b = this.get(i);
  556. var skip = (i == end - 1) ? unusedBit : 0;
  557. for (var j = 7; j >= skip; --j) {
  558. s += (b >> j) & 1 ? "1" : "0";
  559. }
  560. if (s.length > maxLength) {
  561. return intro + stringCut(s, maxLength);
  562. }
  563. }
  564. return intro + s;
  565. };
  566. Stream.prototype.parseOctetString = function (start, end, maxLength) {
  567. if (this.isASCII(start, end)) {
  568. return stringCut(this.parseStringISO(start, end), maxLength);
  569. }
  570. var len = end - start;
  571. var s = "(" + len + " byte)\n";
  572. maxLength /= 2; // we work in bytes
  573. if (len > maxLength) {
  574. end = start + maxLength;
  575. }
  576. for (var i = start; i < end; ++i) {
  577. s += this.hexByte(this.get(i));
  578. }
  579. if (len > maxLength) {
  580. s += ellipsis;
  581. }
  582. return s;
  583. };
  584. Stream.prototype.parseOID = function (start, end, maxLength) {
  585. var s = "";
  586. var n = new Int10();
  587. var bits = 0;
  588. for (var i = start; i < end; ++i) {
  589. var v = this.get(i);
  590. n.mulAdd(128, v & 0x7F);
  591. bits += 7;
  592. if (!(v & 0x80)) {
  593. if (s === "") {
  594. n = n.simplify();
  595. if (n instanceof Int10) {
  596. n.sub(80);
  597. s = "2." + n.toString();
  598. }
  599. else {
  600. var m = n < 80 ? n < 40 ? 0 : 1 : 2;
  601. s = m + "." + (n - m * 40);
  602. }
  603. }
  604. else {
  605. s += "." + n.toString();
  606. }
  607. if (s.length > maxLength) {
  608. return stringCut(s, maxLength);
  609. }
  610. n = new Int10();
  611. bits = 0;
  612. }
  613. }
  614. if (bits > 0) {
  615. s += ".incomplete";
  616. }
  617. return s;
  618. };
  619. return Stream;
  620. }());
  621. var ASN1 = /** @class */ (function () {
  622. function ASN1(stream, header, length, tag, sub) {
  623. if (!(tag instanceof ASN1Tag)) {
  624. throw new Error("Invalid tag value.");
  625. }
  626. this.stream = stream;
  627. this.header = header;
  628. this.length = length;
  629. this.tag = tag;
  630. this.sub = sub;
  631. }
  632. ASN1.prototype.typeName = function () {
  633. switch (this.tag.tagClass) {
  634. case 0:// universal
  635. switch (this.tag.tagNumber) {
  636. case 0x00:
  637. return "EOC";
  638. case 0x01:
  639. return "BOOLEAN";
  640. case 0x02:
  641. return "INTEGER";
  642. case 0x03:
  643. return "BIT_STRING";
  644. case 0x04:
  645. return "OCTET_STRING";
  646. case 0x05:
  647. return "NULL";
  648. case 0x06:
  649. return "OBJECT_IDENTIFIER";
  650. case 0x07:
  651. return "ObjectDescriptor";
  652. case 0x08:
  653. return "EXTERNAL";
  654. case 0x09:
  655. return "REAL";
  656. case 0x0A:
  657. return "ENUMERATED";
  658. case 0x0B:
  659. return "EMBEDDED_PDV";
  660. case 0x0C:
  661. return "UTF8String";
  662. case 0x10:
  663. return "SEQUENCE";
  664. case 0x11:
  665. return "SET";
  666. case 0x12:
  667. return "NumericString";
  668. case 0x13:
  669. return "PrintableString"; // ASCII subset
  670. case 0x14:
  671. return "TeletexString"; // aka T61String
  672. case 0x15:
  673. return "VideotexString";
  674. case 0x16:
  675. return "IA5String"; // ASCII
  676. case 0x17:
  677. return "UTCTime";
  678. case 0x18:
  679. return "GeneralizedTime";
  680. case 0x19:
  681. return "GraphicString";
  682. case 0x1A:
  683. return "VisibleString"; // ASCII subset
  684. case 0x1B:
  685. return "GeneralString";
  686. case 0x1C:
  687. return "UniversalString";
  688. case 0x1E:
  689. return "BMPString";
  690. }
  691. return "Universal_" + this.tag.tagNumber.toString();
  692. case 1:
  693. return "Application_" + this.tag.tagNumber.toString();
  694. case 2:
  695. return "[" + this.tag.tagNumber.toString() + "]"; // Context
  696. case 3:
  697. return "Private_" + this.tag.tagNumber.toString();
  698. }
  699. };
  700. ASN1.prototype.content = function (maxLength) {
  701. if (this.tag === undefined) {
  702. return null;
  703. }
  704. if (maxLength === undefined) {
  705. maxLength = Infinity;
  706. }
  707. var content = this.posContent();
  708. var len = Math.abs(this.length);
  709. if (!this.tag.isUniversal()) {
  710. if (this.sub !== null) {
  711. return "(" + this.sub.length + " elem)";
  712. }
  713. return this.stream.parseOctetString(content, content + len, maxLength);
  714. }
  715. switch (this.tag.tagNumber) {
  716. case 0x01:// BOOLEAN
  717. return (this.stream.get(content) === 0) ? "false" : "true";
  718. case 0x02:// INTEGER
  719. return this.stream.parseInteger(content, content + len);
  720. case 0x03:// BIT_STRING
  721. return this.sub ? "(" + this.sub.length + " elem)" :
  722. this.stream.parseBitString(content, content + len, maxLength);
  723. case 0x04:// OCTET_STRING
  724. return this.sub ? "(" + this.sub.length + " elem)" :
  725. this.stream.parseOctetString(content, content + len, maxLength);
  726. // case 0x05: // NULL
  727. case 0x06:// OBJECT_IDENTIFIER
  728. return this.stream.parseOID(content, content + len, maxLength);
  729. // case 0x07: // ObjectDescriptor
  730. // case 0x08: // EXTERNAL
  731. // case 0x09: // REAL
  732. // case 0x0A: // ENUMERATED
  733. // case 0x0B: // EMBEDDED_PDV
  734. case 0x10: // SEQUENCE
  735. case 0x11:// SET
  736. if (this.sub !== null) {
  737. return "(" + this.sub.length + " elem)";
  738. }
  739. else {
  740. return "(no elem)";
  741. }
  742. case 0x0C:// UTF8String
  743. return stringCut(this.stream.parseStringUTF(content, content + len), maxLength);
  744. case 0x12: // NumericString
  745. case 0x13: // PrintableString
  746. case 0x14: // TeletexString
  747. case 0x15: // VideotexString
  748. case 0x16: // IA5String
  749. // case 0x19: // GraphicString
  750. case 0x1A:// VisibleString
  751. // case 0x1B: // GeneralString
  752. // case 0x1C: // UniversalString
  753. return stringCut(this.stream.parseStringISO(content, content + len), maxLength);
  754. case 0x1E:// BMPString
  755. return stringCut(this.stream.parseStringBMP(content, content + len), maxLength);
  756. case 0x17: // UTCTime
  757. case 0x18:// GeneralizedTime
  758. return this.stream.parseTime(content, content + len, (this.tag.tagNumber == 0x17));
  759. }
  760. return null;
  761. };
  762. ASN1.prototype.toString = function () {
  763. return this.typeName() + "@" + this.stream.pos + "[header:" + this.header + ",length:" + this.length + ",sub:" + ((this.sub === null) ? "null" : this.sub.length) + "]";
  764. };
  765. ASN1.prototype.toPrettyString = function (indent) {
  766. if (indent === undefined) {
  767. indent = "";
  768. }
  769. var s = indent + this.typeName() + " @" + this.stream.pos;
  770. if (this.length >= 0) {
  771. s += "+";
  772. }
  773. s += this.length;
  774. if (this.tag.tagConstructed) {
  775. s += " (constructed)";
  776. }
  777. else if ((this.tag.isUniversal() && ((this.tag.tagNumber == 0x03) || (this.tag.tagNumber == 0x04))) && (this.sub !== null)) {
  778. s += " (encapsulates)";
  779. }
  780. s += "\n";
  781. if (this.sub !== null) {
  782. indent += " ";
  783. for (var i = 0, max = this.sub.length; i < max; ++i) {
  784. s += this.sub[i].toPrettyString(indent);
  785. }
  786. }
  787. return s;
  788. };
  789. ASN1.prototype.posStart = function () {
  790. return this.stream.pos;
  791. };
  792. ASN1.prototype.posContent = function () {
  793. return this.stream.pos + this.header;
  794. };
  795. ASN1.prototype.posEnd = function () {
  796. return this.stream.pos + this.header + Math.abs(this.length);
  797. };
  798. ASN1.prototype.toHexString = function () {
  799. return this.stream.hexDump(this.posStart(), this.posEnd(), true);
  800. };
  801. ASN1.decodeLength = function (stream) {
  802. var buf = stream.get();
  803. var len = buf & 0x7F;
  804. if (len == buf) {
  805. return len;
  806. }
  807. // no reason to use Int10, as it would be a huge buffer anyways
  808. if (len > 6) {
  809. throw new Error("Length over 48 bits not supported at position " + (stream.pos - 1));
  810. }
  811. if (len === 0) {
  812. return null;
  813. } // undefined
  814. buf = 0;
  815. for (var i = 0; i < len; ++i) {
  816. buf = (buf * 256) + stream.get();
  817. }
  818. return buf;
  819. };
  820. /**
  821. * Retrieve the hexadecimal value (as a string) of the current ASN.1 element
  822. * @returns {string}
  823. * @public
  824. */
  825. ASN1.prototype.getHexStringValue = function () {
  826. var hexString = this.toHexString();
  827. var offset = this.header * 2;
  828. var length = this.length * 2;
  829. return hexString.substr(offset, length);
  830. };
  831. ASN1.decode = function (str) {
  832. var stream;
  833. if (!(str instanceof Stream)) {
  834. stream = new Stream(str, 0);
  835. }
  836. else {
  837. stream = str;
  838. }
  839. var streamStart = new Stream(stream);
  840. var tag = new ASN1Tag(stream);
  841. var len = ASN1.decodeLength(stream);
  842. var start = stream.pos;
  843. var header = start - streamStart.pos;
  844. var sub = null;
  845. var getSub = function () {
  846. var ret = [];
  847. if (len !== null) {
  848. // definite length
  849. var end = start + len;
  850. while (stream.pos < end) {
  851. ret[ret.length] = ASN1.decode(stream);
  852. }
  853. if (stream.pos != end) {
  854. throw new Error("Content size is not correct for container starting at offset " + start);
  855. }
  856. }
  857. else {
  858. // undefined length
  859. try {
  860. for (;;) {
  861. var s = ASN1.decode(stream);
  862. if (s.tag.isEOC()) {
  863. break;
  864. }
  865. ret[ret.length] = s;
  866. }
  867. len = start - stream.pos; // undefined lengths are represented as negative values
  868. }
  869. catch (e) {
  870. throw new Error("Exception while decoding undefined length content: " + e);
  871. }
  872. }
  873. return ret;
  874. };
  875. if (tag.tagConstructed) {
  876. // must have valid content
  877. sub = getSub();
  878. }
  879. else if (tag.isUniversal() && ((tag.tagNumber == 0x03) || (tag.tagNumber == 0x04))) {
  880. // sometimes BitString and OctetString are used to encapsulate ASN.1
  881. try {
  882. if (tag.tagNumber == 0x03) {
  883. if (stream.get() != 0) {
  884. throw new Error("BIT STRINGs with unused bits cannot encapsulate.");
  885. }
  886. }
  887. sub = getSub();
  888. for (var i = 0; i < sub.length; ++i) {
  889. if (sub[i].tag.isEOC()) {
  890. throw new Error("EOC is not supposed to be actual content.");
  891. }
  892. }
  893. }
  894. catch (e) {
  895. // but silently ignore when they don't
  896. sub = null;
  897. }
  898. }
  899. if (sub === null) {
  900. if (len === null) {
  901. throw new Error("We can't skip over an invalid tag with undefined length at offset " + start);
  902. }
  903. stream.pos = start + Math.abs(len);
  904. }
  905. return new ASN1(streamStart, header, len, tag, sub);
  906. };
  907. return ASN1;
  908. }());
  909. var ASN1Tag = /** @class */ (function () {
  910. function ASN1Tag(stream) {
  911. var buf = stream.get();
  912. this.tagClass = buf >> 6;
  913. this.tagConstructed = ((buf & 0x20) !== 0);
  914. this.tagNumber = buf & 0x1F;
  915. if (this.tagNumber == 0x1F) {
  916. var n = new Int10();
  917. do {
  918. buf = stream.get();
  919. n.mulAdd(128, buf & 0x7F);
  920. } while (buf & 0x80);
  921. this.tagNumber = n.simplify();
  922. }
  923. }
  924. ASN1Tag.prototype.isUniversal = function () {
  925. return this.tagClass === 0x00;
  926. };
  927. ASN1Tag.prototype.isEOC = function () {
  928. return this.tagClass === 0x00 && this.tagNumber === 0x00;
  929. };
  930. return ASN1Tag;
  931. }());
  932. // Copyright (c) 2005 Tom Wu
  933. // Bits per digit
  934. var dbits;
  935. // JavaScript engine analysis
  936. var canary = 0xdeadbeefcafe;
  937. var j_lm = ((canary & 0xffffff) == 0xefcafe);
  938. //#region
  939. 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];
  940. var lplim = (1 << 26) / lowprimes[lowprimes.length - 1];
  941. //#endregion
  942. // (public) Constructor
  943. var BigInteger = /** @class */ (function () {
  944. function BigInteger(a, b, c) {
  945. if (a != null) {
  946. if ("number" == typeof a) {
  947. this.fromNumber(a, b, c);
  948. }
  949. else if (b == null && "string" != typeof a) {
  950. this.fromString(a, 256);
  951. }
  952. else {
  953. this.fromString(a, b);
  954. }
  955. }
  956. }
  957. //#region PUBLIC
  958. // BigInteger.prototype.toString = bnToString;
  959. // (public) return string representation in given radix
  960. BigInteger.prototype.toString = function (b) {
  961. if (this.s < 0) {
  962. return "-" + this.negate().toString(b);
  963. }
  964. var k;
  965. if (b == 16) {
  966. k = 4;
  967. }
  968. else if (b == 8) {
  969. k = 3;
  970. }
  971. else if (b == 2) {
  972. k = 1;
  973. }
  974. else if (b == 32) {
  975. k = 5;
  976. }
  977. else if (b == 4) {
  978. k = 2;
  979. }
  980. else {
  981. return this.toRadix(b);
  982. }
  983. var km = (1 << k) - 1;
  984. var d;
  985. var m = false;
  986. var r = "";
  987. var i = this.t;
  988. var p = this.DB - (i * this.DB) % k;
  989. if (i-- > 0) {
  990. if (p < this.DB && (d = this[i] >> p) > 0) {
  991. m = true;
  992. r = int2char(d);
  993. }
  994. while (i >= 0) {
  995. if (p < k) {
  996. d = (this[i] & ((1 << p) - 1)) << (k - p);
  997. d |= this[--i] >> (p += this.DB - k);
  998. }
  999. else {
  1000. d = (this[i] >> (p -= k)) & km;
  1001. if (p <= 0) {
  1002. p += this.DB;
  1003. --i;
  1004. }
  1005. }
  1006. if (d > 0) {
  1007. m = true;
  1008. }
  1009. if (m) {
  1010. r += int2char(d);
  1011. }
  1012. }
  1013. }
  1014. return m ? r : "0";
  1015. };
  1016. // BigInteger.prototype.negate = bnNegate;
  1017. // (public) -this
  1018. BigInteger.prototype.negate = function () {
  1019. var r = nbi();
  1020. BigInteger.ZERO.subTo(this, r);
  1021. return r;
  1022. };
  1023. // BigInteger.prototype.abs = bnAbs;
  1024. // (public) |this|
  1025. BigInteger.prototype.abs = function () {
  1026. return (this.s < 0) ? this.negate() : this;
  1027. };
  1028. // BigInteger.prototype.compareTo = bnCompareTo;
  1029. // (public) return + if this > a, - if this < a, 0 if equal
  1030. BigInteger.prototype.compareTo = function (a) {
  1031. var r = this.s - a.s;
  1032. if (r != 0) {
  1033. return r;
  1034. }
  1035. var i = this.t;
  1036. r = i - a.t;
  1037. if (r != 0) {
  1038. return (this.s < 0) ? -r : r;
  1039. }
  1040. while (--i >= 0) {
  1041. if ((r = this[i] - a[i]) != 0) {
  1042. return r;
  1043. }
  1044. }
  1045. return 0;
  1046. };
  1047. // BigInteger.prototype.bitLength = bnBitLength;
  1048. // (public) return the number of bits in "this"
  1049. BigInteger.prototype.bitLength = function () {
  1050. if (this.t <= 0) {
  1051. return 0;
  1052. }
  1053. return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM));
  1054. };
  1055. // BigInteger.prototype.mod = bnMod;
  1056. // (public) this mod a
  1057. BigInteger.prototype.mod = function (a) {
  1058. var r = nbi();
  1059. this.abs().divRemTo(a, null, r);
  1060. if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) {
  1061. a.subTo(r, r);
  1062. }
  1063. return r;
  1064. };
  1065. // BigInteger.prototype.modPowInt = bnModPowInt;
  1066. // (public) this^e % m, 0 <= e < 2^32
  1067. BigInteger.prototype.modPowInt = function (e, m) {
  1068. var z;
  1069. if (e < 256 || m.isEven()) {
  1070. z = new Classic(m);
  1071. }
  1072. else {
  1073. z = new Montgomery(m);
  1074. }
  1075. return this.exp(e, z);
  1076. };
  1077. // BigInteger.prototype.clone = bnClone;
  1078. // (public)
  1079. BigInteger.prototype.clone = function () {
  1080. var r = nbi();
  1081. this.copyTo(r);
  1082. return r;
  1083. };
  1084. // BigInteger.prototype.intValue = bnIntValue;
  1085. // (public) return value as integer
  1086. BigInteger.prototype.intValue = function () {
  1087. if (this.s < 0) {
  1088. if (this.t == 1) {
  1089. return this[0] - this.DV;
  1090. }
  1091. else if (this.t == 0) {
  1092. return -1;
  1093. }
  1094. }
  1095. else if (this.t == 1) {
  1096. return this[0];
  1097. }
  1098. else if (this.t == 0) {
  1099. return 0;
  1100. }
  1101. // assumes 16 < DB < 32
  1102. return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0];
  1103. };
  1104. // BigInteger.prototype.byteValue = bnByteValue;
  1105. // (public) return value as byte
  1106. BigInteger.prototype.byteValue = function () {
  1107. return (this.t == 0) ? this.s : (this[0] << 24) >> 24;
  1108. };
  1109. // BigInteger.prototype.shortValue = bnShortValue;
  1110. // (public) return value as short (assumes DB>=16)
  1111. BigInteger.prototype.shortValue = function () {
  1112. return (this.t == 0) ? this.s : (this[0] << 16) >> 16;
  1113. };
  1114. // BigInteger.prototype.signum = bnSigNum;
  1115. // (public) 0 if this == 0, 1 if this > 0
  1116. BigInteger.prototype.signum = function () {
  1117. if (this.s < 0) {
  1118. return -1;
  1119. }
  1120. else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) {
  1121. return 0;
  1122. }
  1123. else {
  1124. return 1;
  1125. }
  1126. };
  1127. // BigInteger.prototype.toByteArray = bnToByteArray;
  1128. // (public) convert to bigendian byte array
  1129. BigInteger.prototype.toByteArray = function () {
  1130. var i = this.t;
  1131. var r = [];
  1132. r[0] = this.s;
  1133. var p = this.DB - (i * this.DB) % 8;
  1134. var d;
  1135. var k = 0;
  1136. if (i-- > 0) {
  1137. if (p < this.DB && (d = this[i] >> p) != (this.s & this.DM) >> p) {
  1138. r[k++] = d | (this.s << (this.DB - p));
  1139. }
  1140. while (i >= 0) {
  1141. if (p < 8) {
  1142. d = (this[i] & ((1 << p) - 1)) << (8 - p);
  1143. d |= this[--i] >> (p += this.DB - 8);
  1144. }
  1145. else {
  1146. d = (this[i] >> (p -= 8)) & 0xff;
  1147. if (p <= 0) {
  1148. p += this.DB;
  1149. --i;
  1150. }
  1151. }
  1152. if ((d & 0x80) != 0) {
  1153. d |= -256;
  1154. }
  1155. if (k == 0 && (this.s & 0x80) != (d & 0x80)) {
  1156. ++k;
  1157. }
  1158. if (k > 0 || d != this.s) {
  1159. r[k++] = d;
  1160. }
  1161. }
  1162. }
  1163. return r;
  1164. };
  1165. // BigInteger.prototype.equals = bnEquals;
  1166. BigInteger.prototype.equals = function (a) {
  1167. return (this.compareTo(a) == 0);
  1168. };
  1169. // BigInteger.prototype.min = bnMin;
  1170. BigInteger.prototype.min = function (a) {
  1171. return (this.compareTo(a) < 0) ? this : a;
  1172. };
  1173. // BigInteger.prototype.max = bnMax;
  1174. BigInteger.prototype.max = function (a) {
  1175. return (this.compareTo(a) > 0) ? this : a;
  1176. };
  1177. // BigInteger.prototype.and = bnAnd;
  1178. BigInteger.prototype.and = function (a) {
  1179. var r = nbi();
  1180. this.bitwiseTo(a, op_and, r);
  1181. return r;
  1182. };
  1183. // BigInteger.prototype.or = bnOr;
  1184. BigInteger.prototype.or = function (a) {
  1185. var r = nbi();
  1186. this.bitwiseTo(a, op_or, r);
  1187. return r;
  1188. };
  1189. // BigInteger.prototype.xor = bnXor;
  1190. BigInteger.prototype.xor = function (a) {
  1191. var r = nbi();
  1192. this.bitwiseTo(a, op_xor, r);
  1193. return r;
  1194. };
  1195. // BigInteger.prototype.andNot = bnAndNot;
  1196. BigInteger.prototype.andNot = function (a) {
  1197. var r = nbi();
  1198. this.bitwiseTo(a, op_andnot, r);
  1199. return r;
  1200. };
  1201. // BigInteger.prototype.not = bnNot;
  1202. // (public) ~this
  1203. BigInteger.prototype.not = function () {
  1204. var r = nbi();
  1205. for (var i = 0; i < this.t; ++i) {
  1206. r[i] = this.DM & ~this[i];
  1207. }
  1208. r.t = this.t;
  1209. r.s = ~this.s;
  1210. return r;
  1211. };
  1212. // BigInteger.prototype.shiftLeft = bnShiftLeft;
  1213. // (public) this << n
  1214. BigInteger.prototype.shiftLeft = function (n) {
  1215. var r = nbi();
  1216. if (n < 0) {
  1217. this.rShiftTo(-n, r);
  1218. }
  1219. else {
  1220. this.lShiftTo(n, r);
  1221. }
  1222. return r;
  1223. };
  1224. // BigInteger.prototype.shiftRight = bnShiftRight;
  1225. // (public) this >> n
  1226. BigInteger.prototype.shiftRight = function (n) {
  1227. var r = nbi();
  1228. if (n < 0) {
  1229. this.lShiftTo(-n, r);
  1230. }
  1231. else {
  1232. this.rShiftTo(n, r);
  1233. }
  1234. return r;
  1235. };
  1236. // BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
  1237. // (public) returns index of lowest 1-bit (or -1 if none)
  1238. BigInteger.prototype.getLowestSetBit = function () {
  1239. for (var i = 0; i < this.t; ++i) {
  1240. if (this[i] != 0) {
  1241. return i * this.DB + lbit(this[i]);
  1242. }
  1243. }
  1244. if (this.s < 0) {
  1245. return this.t * this.DB;
  1246. }
  1247. return -1;
  1248. };
  1249. // BigInteger.prototype.bitCount = bnBitCount;
  1250. // (public) return number of set bits
  1251. BigInteger.prototype.bitCount = function () {
  1252. var r = 0;
  1253. var x = this.s & this.DM;
  1254. for (var i = 0; i < this.t; ++i) {
  1255. r += cbit(this[i] ^ x);
  1256. }
  1257. return r;
  1258. };
  1259. // BigInteger.prototype.testBit = bnTestBit;
  1260. // (public) true iff nth bit is set
  1261. BigInteger.prototype.testBit = function (n) {
  1262. var j = Math.floor(n / this.DB);
  1263. if (j >= this.t) {
  1264. return (this.s != 0);
  1265. }
  1266. return ((this[j] & (1 << (n % this.DB))) != 0);
  1267. };
  1268. // BigInteger.prototype.setBit = bnSetBit;
  1269. // (public) this | (1<<n)
  1270. BigInteger.prototype.setBit = function (n) {
  1271. return this.changeBit(n, op_or);
  1272. };
  1273. // BigInteger.prototype.clearBit = bnClearBit;
  1274. // (public) this & ~(1<<n)
  1275. BigInteger.prototype.clearBit = function (n) {
  1276. return this.changeBit(n, op_andnot);
  1277. };
  1278. // BigInteger.prototype.flipBit = bnFlipBit;
  1279. // (public) this ^ (1<<n)
  1280. BigInteger.prototype.flipBit = function (n) {
  1281. return this.changeBit(n, op_xor);
  1282. };
  1283. // BigInteger.prototype.add = bnAdd;
  1284. // (public) this + a
  1285. BigInteger.prototype.add = function (a) {
  1286. var r = nbi();
  1287. this.addTo(a, r);
  1288. return r;
  1289. };
  1290. // BigInteger.prototype.subtract = bnSubtract;
  1291. // (public) this - a
  1292. BigInteger.prototype.subtract = function (a) {
  1293. var r = nbi();
  1294. this.subTo(a, r);
  1295. return r;
  1296. };
  1297. // BigInteger.prototype.multiply = bnMultiply;
  1298. // (public) this * a
  1299. BigInteger.prototype.multiply = function (a) {
  1300. var r = nbi();
  1301. this.multiplyTo(a, r);
  1302. return r;
  1303. };
  1304. // BigInteger.prototype.divide = bnDivide;
  1305. // (public) this / a
  1306. BigInteger.prototype.divide = function (a) {
  1307. var r = nbi();
  1308. this.divRemTo(a, r, null);
  1309. return r;
  1310. };
  1311. // BigInteger.prototype.remainder = bnRemainder;
  1312. // (public) this % a
  1313. BigInteger.prototype.remainder = function (a) {
  1314. var r = nbi();
  1315. this.divRemTo(a, null, r);
  1316. return r;
  1317. };
  1318. // BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
  1319. // (public) [this/a,this%a]
  1320. BigInteger.prototype.divideAndRemainder = function (a) {
  1321. var q = nbi();
  1322. var r = nbi();
  1323. this.divRemTo(a, q, r);
  1324. return [q, r];
  1325. };
  1326. // BigInteger.prototype.modPow = bnModPow;
  1327. // (public) this^e % m (HAC 14.85)
  1328. BigInteger.prototype.modPow = function (e, m) {
  1329. var i = e.bitLength();
  1330. var k;
  1331. var r = nbv(1);
  1332. var z;
  1333. if (i <= 0) {
  1334. return r;
  1335. }
  1336. else if (i < 18) {
  1337. k = 1;
  1338. }
  1339. else if (i < 48) {
  1340. k = 3;
  1341. }
  1342. else if (i < 144) {
  1343. k = 4;
  1344. }
  1345. else if (i < 768) {
  1346. k = 5;
  1347. }
  1348. else {
  1349. k = 6;
  1350. }
  1351. if (i < 8) {
  1352. z = new Classic(m);
  1353. }
  1354. else if (m.isEven()) {
  1355. z = new Barrett(m);
  1356. }
  1357. else {
  1358. z = new Montgomery(m);
  1359. }
  1360. // precomputation
  1361. var g = [];
  1362. var n = 3;
  1363. var k1 = k - 1;
  1364. var km = (1 << k) - 1;
  1365. g[1] = z.convert(this);
  1366. if (k > 1) {
  1367. var g2 = nbi();
  1368. z.sqrTo(g[1], g2);
  1369. while (n <= km) {
  1370. g[n] = nbi();
  1371. z.mulTo(g2, g[n - 2], g[n]);
  1372. n += 2;
  1373. }
  1374. }
  1375. var j = e.t - 1;
  1376. var w;
  1377. var is1 = true;
  1378. var r2 = nbi();
  1379. var t;
  1380. i = nbits(e[j]) - 1;
  1381. while (j >= 0) {
  1382. if (i >= k1) {
  1383. w = (e[j] >> (i - k1)) & km;
  1384. }
  1385. else {
  1386. w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i);
  1387. if (j > 0) {
  1388. w |= e[j - 1] >> (this.DB + i - k1);
  1389. }
  1390. }
  1391. n = k;
  1392. while ((w & 1) == 0) {
  1393. w >>= 1;
  1394. --n;
  1395. }
  1396. if ((i -= n) < 0) {
  1397. i += this.DB;
  1398. --j;
  1399. }
  1400. if (is1) {
  1401. g[w].copyTo(r);
  1402. is1 = false;
  1403. }
  1404. else {
  1405. while (n > 1) {
  1406. z.sqrTo(r, r2);
  1407. z.sqrTo(r2, r);
  1408. n -= 2;
  1409. }
  1410. if (n > 0) {
  1411. z.sqrTo(r, r2);
  1412. }
  1413. else {
  1414. t = r;
  1415. r = r2;
  1416. r2 = t;
  1417. }
  1418. z.mulTo(r2, g[w], r);
  1419. }
  1420. while (j >= 0 && (e[j] & (1 << i)) == 0) {
  1421. z.sqrTo(r, r2);
  1422. t = r;
  1423. r = r2;
  1424. r2 = t;
  1425. if (--i < 0) {
  1426. i = this.DB - 1;
  1427. --j;
  1428. }
  1429. }
  1430. }
  1431. return z.revert(r);
  1432. };
  1433. // BigInteger.prototype.modInverse = bnModInverse;
  1434. // (public) 1/this % m (HAC 14.61)
  1435. BigInteger.prototype.modInverse = function (m) {
  1436. var ac = m.isEven();
  1437. if ((this.isEven() && ac) || m.signum() == 0) {
  1438. return BigInteger.ZERO;
  1439. }
  1440. var u = m.clone();
  1441. var v = this.clone();
  1442. var a = nbv(1);
  1443. var b = nbv(0);
  1444. var c = nbv(0);
  1445. var d = nbv(1);
  1446. while (u.signum() != 0) {
  1447. while (u.isEven()) {
  1448. u.rShiftTo(1, u);
  1449. if (ac) {
  1450. if (!a.isEven() || !b.isEven()) {
  1451. a.addTo(this, a);
  1452. b.subTo(m, b);
  1453. }
  1454. a.rShiftTo(1, a);
  1455. }
  1456. else if (!b.isEven()) {
  1457. b.subTo(m, b);
  1458. }
  1459. b.rShiftTo(1, b);
  1460. }
  1461. while (v.isEven()) {
  1462. v.rShiftTo(1, v);
  1463. if (ac) {
  1464. if (!c.isEven() || !d.isEven()) {
  1465. c.addTo(this, c);
  1466. d.subTo(m, d);
  1467. }
  1468. c.rShiftTo(1, c);
  1469. }
  1470. else if (!d.isEven()) {
  1471. d.subTo(m, d);
  1472. }
  1473. d.rShiftTo(1, d);
  1474. }
  1475. if (u.compareTo(v) >= 0) {
  1476. u.subTo(v, u);
  1477. if (ac) {
  1478. a.subTo(c, a);
  1479. }
  1480. b.subTo(d, b);
  1481. }
  1482. else {
  1483. v.subTo(u, v);
  1484. if (ac) {
  1485. c.subTo(a, c);
  1486. }
  1487. d.subTo(b, d);
  1488. }
  1489. }
  1490. if (v.compareTo(BigInteger.ONE) != 0) {
  1491. return BigInteger.ZERO;
  1492. }
  1493. if (d.compareTo(m) >= 0) {
  1494. return d.subtract(m);
  1495. }
  1496. if (d.signum() < 0) {
  1497. d.addTo(m, d);
  1498. }
  1499. else {
  1500. return d;
  1501. }
  1502. if (d.signum() < 0) {
  1503. return d.add(m);
  1504. }
  1505. else {
  1506. return d;
  1507. }
  1508. };
  1509. // BigInteger.prototype.pow = bnPow;
  1510. // (public) this^e
  1511. BigInteger.prototype.pow = function (e) {
  1512. return this.exp(e, new NullExp());
  1513. };
  1514. // BigInteger.prototype.gcd = bnGCD;
  1515. // (public) gcd(this,a) (HAC 14.54)
  1516. BigInteger.prototype.gcd = function (a) {
  1517. var x = (this.s < 0) ? this.negate() : this.clone();
  1518. var y = (a.s < 0) ? a.negate() : a.clone();
  1519. if (x.compareTo(y) < 0) {
  1520. var t = x;
  1521. x = y;
  1522. y = t;
  1523. }
  1524. var i = x.getLowestSetBit();
  1525. var g = y.getLowestSetBit();
  1526. if (g < 0) {
  1527. return x;
  1528. }
  1529. if (i < g) {
  1530. g = i;
  1531. }
  1532. if (g > 0) {
  1533. x.rShiftTo(g, x);
  1534. y.rShiftTo(g, y);
  1535. }
  1536. while (x.signum() > 0) {
  1537. if ((i = x.getLowestSetBit()) > 0) {
  1538. x.rShiftTo(i, x);
  1539. }
  1540. if ((i = y.getLowestSetBit()) > 0) {
  1541. y.rShiftTo(i, y);
  1542. }
  1543. if (x.compareTo(y) >= 0) {
  1544. x.subTo(y, x);
  1545. x.rShiftTo(1, x);
  1546. }
  1547. else {
  1548. y.subTo(x, y);
  1549. y.rShiftTo(1, y);
  1550. }
  1551. }
  1552. if (g > 0) {
  1553. y.lShiftTo(g, y);
  1554. }
  1555. return y;
  1556. };
  1557. // BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
  1558. // (public) test primality with certainty >= 1-.5^t
  1559. BigInteger.prototype.isProbablePrime = function (t) {
  1560. var i;
  1561. var x = this.abs();
  1562. if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) {
  1563. for (i = 0; i < lowprimes.length; ++i) {
  1564. if (x[0] == lowprimes[i]) {
  1565. return true;
  1566. }
  1567. }
  1568. return false;
  1569. }
  1570. if (x.isEven()) {
  1571. return false;
  1572. }
  1573. i = 1;
  1574. while (i < lowprimes.length) {
  1575. var m = lowprimes[i];
  1576. var j = i + 1;
  1577. while (j < lowprimes.length && m < lplim) {
  1578. m *= lowprimes[j++];
  1579. }
  1580. m = x.modInt(m);
  1581. while (i < j) {
  1582. if (m % lowprimes[i++] == 0) {
  1583. return false;
  1584. }
  1585. }
  1586. }
  1587. return x.millerRabin(t);
  1588. };
  1589. //#endregion PUBLIC
  1590. //#region PROTECTED
  1591. // BigInteger.prototype.copyTo = bnpCopyTo;
  1592. // (protected) copy this to r
  1593. BigInteger.prototype.copyTo = function (r) {
  1594. for (var i = this.t - 1; i >= 0; --i) {
  1595. r[i] = this[i];
  1596. }
  1597. r.t = this.t;
  1598. r.s = this.s;
  1599. };
  1600. // BigInteger.prototype.fromInt = bnpFromInt;
  1601. // (protected) set from integer value x, -DV <= x < DV
  1602. BigInteger.prototype.fromInt = function (x) {
  1603. this.t = 1;
  1604. this.s = (x < 0) ? -1 : 0;
  1605. if (x > 0) {
  1606. this[0] = x;
  1607. }
  1608. else if (x < -1) {
  1609. this[0] = x + this.DV;
  1610. }
  1611. else {
  1612. this.t = 0;
  1613. }
  1614. };
  1615. // BigInteger.prototype.fromString = bnpFromString;
  1616. // (protected) set from string and radix
  1617. BigInteger.prototype.fromString = function (s, b) {
  1618. var k;
  1619. if (b == 16) {
  1620. k = 4;
  1621. }
  1622. else if (b == 8) {
  1623. k = 3;
  1624. }
  1625. else if (b == 256) {
  1626. k = 8;
  1627. /* byte array */
  1628. }
  1629. else if (b == 2) {
  1630. k = 1;
  1631. }
  1632. else if (b == 32) {
  1633. k = 5;
  1634. }
  1635. else if (b == 4) {
  1636. k = 2;
  1637. }
  1638. else {
  1639. this.fromRadix(s, b);
  1640. return;
  1641. }
  1642. this.t = 0;
  1643. this.s = 0;
  1644. var i = s.length;
  1645. var mi = false;
  1646. var sh = 0;
  1647. while (--i >= 0) {
  1648. var x = (k == 8) ? (+s[i]) & 0xff : intAt(s, i);
  1649. if (x < 0) {
  1650. if (s.charAt(i) == "-") {
  1651. mi = true;
  1652. }
  1653. continue;
  1654. }
  1655. mi = false;
  1656. if (sh == 0) {
  1657. this[this.t++] = x;
  1658. }
  1659. else if (sh + k > this.DB) {
  1660. this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh;
  1661. this[this.t++] = (x >> (this.DB - sh));
  1662. }
  1663. else {
  1664. this[this.t - 1] |= x << sh;
  1665. }
  1666. sh += k;
  1667. if (sh >= this.DB) {
  1668. sh -= this.DB;
  1669. }
  1670. }
  1671. if (k == 8 && ((+s[0]) & 0x80) != 0) {
  1672. this.s = -1;
  1673. if (sh > 0) {
  1674. this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh;
  1675. }
  1676. }
  1677. this.clamp();
  1678. if (mi) {
  1679. BigInteger.ZERO.subTo(this, this);
  1680. }
  1681. };
  1682. // BigInteger.prototype.clamp = bnpClamp;
  1683. // (protected) clamp off excess high words
  1684. BigInteger.prototype.clamp = function () {
  1685. var c = this.s & this.DM;
  1686. while (this.t > 0 && this[this.t - 1] == c) {
  1687. --this.t;
  1688. }
  1689. };
  1690. // BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
  1691. // (protected) r = this << n*DB
  1692. BigInteger.prototype.dlShiftTo = function (n, r) {
  1693. var i;
  1694. for (i = this.t - 1; i >= 0; --i) {
  1695. r[i + n] = this[i];
  1696. }
  1697. for (i = n - 1; i >= 0; --i) {
  1698. r[i] = 0;
  1699. }
  1700. r.t = this.t + n;
  1701. r.s = this.s;
  1702. };
  1703. // BigInteger.prototype.drShiftTo = bnpDRShiftTo;
  1704. // (protected) r = this >> n*DB
  1705. BigInteger.prototype.drShiftTo = function (n, r) {
  1706. for (var i = n; i < this.t; ++i) {
  1707. r[i - n] = this[i];
  1708. }
  1709. r.t = Math.max(this.t - n, 0);
  1710. r.s = this.s;
  1711. };
  1712. // BigInteger.prototype.lShiftTo = bnpLShiftTo;
  1713. // (protected) r = this << n
  1714. BigInteger.prototype.lShiftTo = function (n, r) {
  1715. var bs = n % this.DB;
  1716. var cbs = this.DB - bs;
  1717. var bm = (1 << cbs) - 1;
  1718. var ds = Math.floor(n / this.DB);
  1719. var c = (this.s << bs) & this.DM;
  1720. for (var i = this.t - 1; i >= 0; --i) {
  1721. r[i + ds + 1] = (this[i] >> cbs) | c;
  1722. c = (this[i] & bm) << bs;
  1723. }
  1724. for (var i = ds - 1; i >= 0; --i) {
  1725. r[i] = 0;
  1726. }
  1727. r[ds] = c;
  1728. r.t = this.t + ds + 1;
  1729. r.s = this.s;
  1730. r.clamp();
  1731. };
  1732. // BigInteger.prototype.rShiftTo = bnpRShiftTo;
  1733. // (protected) r = this >> n
  1734. BigInteger.prototype.rShiftTo = function (n, r) {
  1735. r.s = this.s;
  1736. var ds = Math.floor(n / this.DB);
  1737. if (ds >= this.t) {
  1738. r.t = 0;
  1739. return;
  1740. }
  1741. var bs = n % this.DB;
  1742. var cbs = this.DB - bs;
  1743. var bm = (1 << bs) - 1;
  1744. r[0] = this[ds] >> bs;
  1745. for (var i = ds + 1; i < this.t; ++i) {
  1746. r[i - ds - 1] |= (this[i] & bm) << cbs;
  1747. r[i - ds] = this[i] >> bs;
  1748. }
  1749. if (bs > 0) {
  1750. r[this.t - ds - 1] |= (this.s & bm) << cbs;
  1751. }
  1752. r.t = this.t - ds;
  1753. r.clamp();
  1754. };
  1755. // BigInteger.prototype.subTo = bnpSubTo;
  1756. // (protected) r = this - a
  1757. BigInteger.prototype.subTo = function (a, r) {
  1758. var i = 0;
  1759. var c = 0;
  1760. var m = Math.min(a.t, this.t);
  1761. while (i < m) {
  1762. c += this[i] - a[i];
  1763. r[i++] = c & this.DM;
  1764. c >>= this.DB;
  1765. }
  1766. if (a.t < this.t) {
  1767. c -= a.s;
  1768. while (i < this.t) {
  1769. c += this[i];
  1770. r[i++] = c & this.DM;
  1771. c >>= this.DB;
  1772. }
  1773. c += this.s;
  1774. }
  1775. else {
  1776. c += this.s;
  1777. while (i < a.t) {
  1778. c -= a[i];
  1779. r[i++] = c & this.DM;
  1780. c >>= this.DB;
  1781. }
  1782. c -= a.s;
  1783. }
  1784. r.s = (c < 0) ? -1 : 0;
  1785. if (c < -1) {
  1786. r[i++] = this.DV + c;
  1787. }
  1788. else if (c > 0) {
  1789. r[i++] = c;
  1790. }
  1791. r.t = i;
  1792. r.clamp();
  1793. };
  1794. // BigInteger.prototype.multiplyTo = bnpMultiplyTo;
  1795. // (protected) r = this * a, r != this,a (HAC 14.12)
  1796. // "this" should be the larger one if appropriate.
  1797. BigInteger.prototype.multiplyTo = function (a, r) {
  1798. var x = this.abs();
  1799. var y = a.abs();
  1800. var i = x.t;
  1801. r.t = i + y.t;
  1802. while (--i >= 0) {
  1803. r[i] = 0;
  1804. }
  1805. for (i = 0; i < y.t; ++i) {
  1806. r[i + x.t] = x.am(0, y[i], r, i, 0, x.t);
  1807. }
  1808. r.s = 0;
  1809. r.clamp();
  1810. if (this.s != a.s) {
  1811. BigInteger.ZERO.subTo(r, r);
  1812. }
  1813. };
  1814. // BigInteger.prototype.squareTo = bnpSquareTo;
  1815. // (protected) r = this^2, r != this (HAC 14.16)
  1816. BigInteger.prototype.squareTo = function (r) {
  1817. var x = this.abs();
  1818. var i = r.t = 2 * x.t;
  1819. while (--i >= 0) {
  1820. r[i] = 0;
  1821. }
  1822. for (i = 0; i < x.t - 1; ++i) {
  1823. var c = x.am(i, x[i], r, 2 * i, 0, 1);
  1824. if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) {
  1825. r[i + x.t] -= x.DV;
  1826. r[i + x.t + 1] = 1;
  1827. }
  1828. }
  1829. if (r.t > 0) {
  1830. r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1);
  1831. }
  1832. r.s = 0;
  1833. r.clamp();
  1834. };
  1835. // BigInteger.prototype.divRemTo = bnpDivRemTo;
  1836. // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
  1837. // r != q, this != m. q or r may be null.
  1838. BigInteger.prototype.divRemTo = function (m, q, r) {
  1839. var pm = m.abs();
  1840. if (pm.t <= 0) {
  1841. return;
  1842. }
  1843. var pt = this.abs();
  1844. if (pt.t < pm.t) {
  1845. if (q != null) {
  1846. q.fromInt(0);
  1847. }
  1848. if (r != null) {
  1849. this.copyTo(r);
  1850. }
  1851. return;
  1852. }
  1853. if (r == null) {
  1854. r = nbi();
  1855. }
  1856. var y = nbi();
  1857. var ts = this.s;
  1858. var ms = m.s;
  1859. var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus
  1860. if (nsh > 0) {
  1861. pm.lShiftTo(nsh, y);
  1862. pt.lShiftTo(nsh, r);
  1863. }
  1864. else {
  1865. pm.copyTo(y);
  1866. pt.copyTo(r);
  1867. }
  1868. var ys = y.t;
  1869. var y0 = y[ys - 1];
  1870. if (y0 == 0) {
  1871. return;
  1872. }
  1873. var yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0);
  1874. var d1 = this.FV / yt;
  1875. var d2 = (1 << this.F1) / yt;
  1876. var e = 1 << this.F2;
  1877. var i = r.t;
  1878. var j = i - ys;
  1879. var t = (q == null) ? nbi() : q;
  1880. y.dlShiftTo(j, t);
  1881. if (r.compareTo(t) >= 0) {
  1882. r[r.t++] = 1;
  1883. r.subTo(t, r);
  1884. }
  1885. BigInteger.ONE.dlShiftTo(ys, t);
  1886. t.subTo(y, y); // "negative" y so we can replace sub with am later
  1887. while (y.t < ys) {
  1888. y[y.t++] = 0;
  1889. }
  1890. while (--j >= 0) {
  1891. // Estimate quotient digit
  1892. var qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2);
  1893. if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) {
  1894. y.dlShiftTo(j, t);
  1895. r.subTo(t, r);
  1896. while (r[i] < --qd) {
  1897. r.subTo(t, r);
  1898. }
  1899. }
  1900. }
  1901. if (q != null) {
  1902. r.drShiftTo(ys, q);
  1903. if (ts != ms) {
  1904. BigInteger.ZERO.subTo(q, q);
  1905. }
  1906. }
  1907. r.t = ys;
  1908. r.clamp();
  1909. if (nsh > 0) {
  1910. r.rShiftTo(nsh, r);
  1911. } // Denormalize remainder
  1912. if (ts < 0) {
  1913. BigInteger.ZERO.subTo(r, r);
  1914. }
  1915. };
  1916. // BigInteger.prototype.invDigit = bnpInvDigit;
  1917. // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
  1918. // justification:
  1919. // xy == 1 (mod m)
  1920. // xy = 1+km
  1921. // xy(2-xy) = (1+km)(1-km)
  1922. // x[y(2-xy)] = 1-k^2m^2
  1923. // x[y(2-xy)] == 1 (mod m^2)
  1924. // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
  1925. // should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
  1926. // JS multiply "overflows" differently from C/C++, so care is needed here.
  1927. BigInteger.prototype.invDigit = function () {
  1928. if (this.t < 1) {
  1929. return 0;
  1930. }
  1931. var x = this[0];
  1932. if ((x & 1) == 0) {
  1933. return 0;
  1934. }
  1935. var y = x & 3; // y == 1/x mod 2^2
  1936. y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4
  1937. y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8
  1938. y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16
  1939. // last step - calculate inverse mod DV directly;
  1940. // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
  1941. y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits
  1942. // we really want the negative inverse, and -DV < y < DV
  1943. return (y > 0) ? this.DV - y : -y;
  1944. };
  1945. // BigInteger.prototype.isEven = bnpIsEven;
  1946. // (protected) true iff this is even
  1947. BigInteger.prototype.isEven = function () {
  1948. return ((this.t > 0) ? (this[0] & 1) : this.s) == 0;
  1949. };
  1950. // BigInteger.prototype.exp = bnpExp;
  1951. // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
  1952. BigInteger.prototype.exp = function (e, z) {
  1953. if (e > 0xffffffff || e < 1) {
  1954. return BigInteger.ONE;
  1955. }
  1956. var r = nbi();
  1957. var r2 = nbi();
  1958. var g = z.convert(this);
  1959. var i = nbits(e) - 1;
  1960. g.copyTo(r);
  1961. while (--i >= 0) {
  1962. z.sqrTo(r, r2);
  1963. if ((e & (1 << i)) > 0) {
  1964. z.mulTo(r2, g, r);
  1965. }
  1966. else {
  1967. var t = r;
  1968. r = r2;
  1969. r2 = t;
  1970. }
  1971. }
  1972. return z.revert(r);
  1973. };
  1974. // BigInteger.prototype.chunkSize = bnpChunkSize;
  1975. // (protected) return x s.t. r^x < DV
  1976. BigInteger.prototype.chunkSize = function (r) {
  1977. return Math.floor(Math.LN2 * this.DB / Math.log(r));
  1978. };
  1979. // BigInteger.prototype.toRadix = bnpToRadix;
  1980. // (protected) convert to radix string
  1981. BigInteger.prototype.toRadix = function (b) {
  1982. if (b == null) {
  1983. b = 10;
  1984. }
  1985. if (this.signum() == 0 || b < 2 || b > 36) {
  1986. return "0";
  1987. }
  1988. var cs = this.chunkSize(b);
  1989. var a = Math.pow(b, cs);
  1990. var d = nbv(a);
  1991. var y = nbi();
  1992. var z = nbi();
  1993. var r = "";
  1994. this.divRemTo(d, y, z);
  1995. while (y.signum() > 0) {
  1996. r = (a + z.intValue()).toString(b).substr(1) + r;
  1997. y.divRemTo(d, y, z);
  1998. }
  1999. return z.intValue().toString(b) + r;
  2000. };
  2001. // BigInteger.prototype.fromRadix = bnpFromRadix;
  2002. // (protected) convert from radix string
  2003. BigInteger.prototype.fromRadix = function (s, b) {
  2004. this.fromInt(0);
  2005. if (b == null) {
  2006. b = 10;
  2007. }
  2008. var cs = this.chunkSize(b);
  2009. var d = Math.pow(b, cs);
  2010. var mi = false;
  2011. var j = 0;
  2012. var w = 0;
  2013. for (var i = 0; i < s.length; ++i) {
  2014. var x = intAt(s, i);
  2015. if (x < 0) {
  2016. if (s.charAt(i) == "-" && this.signum() == 0) {
  2017. mi = true;
  2018. }
  2019. continue;
  2020. }
  2021. w = b * w + x;
  2022. if (++j >= cs) {
  2023. this.dMultiply(d);
  2024. this.dAddOffset(w, 0);
  2025. j = 0;
  2026. w = 0;
  2027. }
  2028. }
  2029. if (j > 0) {
  2030. this.dMultiply(Math.pow(b, j));
  2031. this.dAddOffset(w, 0);
  2032. }
  2033. if (mi) {
  2034. BigInteger.ZERO.subTo(this, this);
  2035. }
  2036. };
  2037. // BigInteger.prototype.fromNumber = bnpFromNumber;
  2038. // (protected) alternate constructor
  2039. BigInteger.prototype.fromNumber = function (a, b, c) {
  2040. if ("number" == typeof b) {
  2041. // new BigInteger(int,int,RNG)
  2042. if (a < 2) {
  2043. this.fromInt(1);
  2044. }
  2045. else {
  2046. this.fromNumber(a, c);
  2047. if (!this.testBit(a - 1)) {
  2048. // force MSB set
  2049. this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this);
  2050. }
  2051. if (this.isEven()) {
  2052. this.dAddOffset(1, 0);
  2053. } // force odd
  2054. while (!this.isProbablePrime(b)) {
  2055. this.dAddOffset(2, 0);
  2056. if (this.bitLength() > a) {
  2057. this.subTo(BigInteger.ONE.shiftLeft(a - 1), this);
  2058. }
  2059. }
  2060. }
  2061. }
  2062. else {
  2063. // new BigInteger(int,RNG)
  2064. var x = [];
  2065. var t = a & 7;
  2066. x.length = (a >> 3) + 1;
  2067. b.nextBytes(x);
  2068. if (t > 0) {
  2069. x[0] &= ((1 << t) - 1);
  2070. }
  2071. else {
  2072. x[0] = 0;
  2073. }
  2074. this.fromString(x, 256);
  2075. }
  2076. };
  2077. // BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
  2078. // (protected) r = this op a (bitwise)
  2079. BigInteger.prototype.bitwiseTo = function (a, op, r) {
  2080. var i;
  2081. var f;
  2082. var m = Math.min(a.t, this.t);
  2083. for (i = 0; i < m; ++i) {
  2084. r[i] = op(this[i], a[i]);
  2085. }
  2086. if (a.t < this.t) {
  2087. f = a.s & this.DM;
  2088. for (i = m; i < this.t; ++i) {
  2089. r[i] = op(this[i], f);
  2090. }
  2091. r.t = this.t;
  2092. }
  2093. else {
  2094. f = this.s & this.DM;
  2095. for (i = m; i < a.t; ++i) {
  2096. r[i] = op(f, a[i]);
  2097. }
  2098. r.t = a.t;
  2099. }
  2100. r.s = op(this.s, a.s);
  2101. r.clamp();
  2102. };
  2103. // BigInteger.prototype.changeBit = bnpChangeBit;
  2104. // (protected) this op (1<<n)
  2105. BigInteger.prototype.changeBit = function (n, op) {
  2106. var r = BigInteger.ONE.shiftLeft(n);
  2107. this.bitwiseTo(r, op, r);
  2108. return r;
  2109. };
  2110. // BigInteger.prototype.addTo = bnpAddTo;
  2111. // (protected) r = this + a
  2112. BigInteger.prototype.addTo = function (a, r) {
  2113. var i = 0;
  2114. var c = 0;
  2115. var m = Math.min(a.t, this.t);
  2116. while (i < m) {
  2117. c += this[i] + a[i];
  2118. r[i++] = c & this.DM;
  2119. c >>= this.DB;
  2120. }
  2121. if (a.t < this.t) {
  2122. c += a.s;
  2123. while (i < this.t) {
  2124. c += this[i];
  2125. r[i++] = c & this.DM;
  2126. c >>= this.DB;
  2127. }
  2128. c += this.s;
  2129. }
  2130. else {
  2131. c += this.s;
  2132. while (i < a.t) {
  2133. c += a[i];
  2134. r[i++] = c & this.DM;
  2135. c >>= this.DB;
  2136. }
  2137. c += a.s;
  2138. }
  2139. r.s = (c < 0) ? -1 : 0;
  2140. if (c > 0) {
  2141. r[i++] = c;
  2142. }
  2143. else if (c < -1) {
  2144. r[i++] = this.DV + c;
  2145. }
  2146. r.t = i;
  2147. r.clamp();
  2148. };
  2149. // BigInteger.prototype.dMultiply = bnpDMultiply;
  2150. // (protected) this *= n, this >= 0, 1 < n < DV
  2151. BigInteger.prototype.dMultiply = function (n) {
  2152. this[this.t] = this.am(0, n - 1, this, 0, 0, this.t);
  2153. ++this.t;
  2154. this.clamp();
  2155. };
  2156. // BigInteger.prototype.dAddOffset = bnpDAddOffset;
  2157. // (protected) this += n << w words, this >= 0
  2158. BigInteger.prototype.dAddOffset = function (n, w) {
  2159. if (n == 0) {
  2160. return;
  2161. }
  2162. while (this.t <= w) {
  2163. this[this.t++] = 0;
  2164. }
  2165. this[w] += n;
  2166. while (this[w] >= this.DV) {
  2167. this[w] -= this.DV;
  2168. if (++w >= this.t) {
  2169. this[this.t++] = 0;
  2170. }
  2171. ++this[w];
  2172. }
  2173. };
  2174. // BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
  2175. // (protected) r = lower n words of "this * a", a.t <= n
  2176. // "this" should be the larger one if appropriate.
  2177. BigInteger.prototype.multiplyLowerTo = function (a, n, r) {
  2178. var i = Math.min(this.t + a.t, n);
  2179. r.s = 0; // assumes a,this >= 0
  2180. r.t = i;
  2181. while (i > 0) {
  2182. r[--i] = 0;
  2183. }
  2184. for (var j = r.t - this.t; i < j; ++i) {
  2185. r[i + this.t] = this.am(0, a[i], r, i, 0, this.t);
  2186. }
  2187. for (var j = Math.min(a.t, n); i < j; ++i) {
  2188. this.am(0, a[i], r, i, 0, n - i);
  2189. }
  2190. r.clamp();
  2191. };
  2192. // BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
  2193. // (protected) r = "this * a" without lower n words, n > 0
  2194. // "this" should be the larger one if appropriate.
  2195. BigInteger.prototype.multiplyUpperTo = function (a, n, r) {
  2196. --n;
  2197. var i = r.t = this.t + a.t - n;
  2198. r.s = 0; // assumes a,this >= 0
  2199. while (--i >= 0) {
  2200. r[i] = 0;
  2201. }
  2202. for (i = Math.max(n - this.t, 0); i < a.t; ++i) {
  2203. r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n);
  2204. }
  2205. r.clamp();
  2206. r.drShiftTo(1, r);
  2207. };
  2208. // BigInteger.prototype.modInt = bnpModInt;
  2209. // (protected) this % n, n < 2^26
  2210. BigInteger.prototype.modInt = function (n) {
  2211. if (n <= 0) {
  2212. return 0;
  2213. }
  2214. var d = this.DV % n;
  2215. var r = (this.s < 0) ? n - 1 : 0;
  2216. if (this.t > 0) {
  2217. if (d == 0) {
  2218. r = this[0] % n;
  2219. }
  2220. else {
  2221. for (var i = this.t - 1; i >= 0; --i) {
  2222. r = (d * r + this[i]) % n;
  2223. }
  2224. }
  2225. }
  2226. return r;
  2227. };
  2228. // BigInteger.prototype.millerRabin = bnpMillerRabin;
  2229. // (protected) true if probably prime (HAC 4.24, Miller-Rabin)
  2230. BigInteger.prototype.millerRabin = function (t) {
  2231. var n1 = this.subtract(BigInteger.ONE);
  2232. var k = n1.getLowestSetBit();
  2233. if (k <= 0) {
  2234. return false;
  2235. }
  2236. var r = n1.shiftRight(k);
  2237. t = (t + 1) >> 1;
  2238. if (t > lowprimes.length) {
  2239. t = lowprimes.length;
  2240. }
  2241. var a = nbi();
  2242. for (var i = 0; i < t; ++i) {
  2243. // Pick bases at random, instead of starting at 2
  2244. a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]);
  2245. var y = a.modPow(r, this);
  2246. if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
  2247. var j = 1;
  2248. while (j++ < k && y.compareTo(n1) != 0) {
  2249. y = y.modPowInt(2, this);
  2250. if (y.compareTo(BigInteger.ONE) == 0) {
  2251. return false;
  2252. }
  2253. }
  2254. if (y.compareTo(n1) != 0) {
  2255. return false;
  2256. }
  2257. }
  2258. }
  2259. return true;
  2260. };
  2261. // BigInteger.prototype.square = bnSquare;
  2262. // (public) this^2
  2263. BigInteger.prototype.square = function () {
  2264. var r = nbi();
  2265. this.squareTo(r);
  2266. return r;
  2267. };
  2268. //#region ASYNC
  2269. // Public API method
  2270. BigInteger.prototype.gcda = function (a, callback) {
  2271. var x = (this.s < 0) ? this.negate() : this.clone();
  2272. var y = (a.s < 0) ? a.negate() : a.clone();
  2273. if (x.compareTo(y) < 0) {
  2274. var t = x;
  2275. x = y;
  2276. y = t;
  2277. }
  2278. var i = x.getLowestSetBit();
  2279. var g = y.getLowestSetBit();
  2280. if (g < 0) {
  2281. callback(x);
  2282. return;
  2283. }
  2284. if (i < g) {
  2285. g = i;
  2286. }
  2287. if (g > 0) {
  2288. x.rShiftTo(g, x);
  2289. y.rShiftTo(g, y);
  2290. }
  2291. // Workhorse of the algorithm, gets called 200 - 800 times per 512 bit keygen.
  2292. var gcda1 = function () {
  2293. if ((i = x.getLowestSetBit()) > 0) {
  2294. x.rShiftTo(i, x);
  2295. }
  2296. if ((i = y.getLowestSetBit()) > 0) {
  2297. y.rShiftTo(i, y);
  2298. }
  2299. if (x.compareTo(y) >= 0) {
  2300. x.subTo(y, x);
  2301. x.rShiftTo(1, x);
  2302. }
  2303. else {
  2304. y.subTo(x, y);
  2305. y.rShiftTo(1, y);
  2306. }
  2307. if (!(x.signum() > 0)) {
  2308. if (g > 0) {
  2309. y.lShiftTo(g, y);
  2310. }
  2311. setTimeout(function () { callback(y); }, 0); // escape
  2312. }
  2313. else {
  2314. setTimeout(gcda1, 0);
  2315. }
  2316. };
  2317. setTimeout(gcda1, 10);
  2318. };
  2319. // (protected) alternate constructor
  2320. BigInteger.prototype.fromNumberAsync = function (a, b, c, callback) {
  2321. if ("number" == typeof b) {
  2322. if (a < 2) {
  2323. this.fromInt(1);
  2324. }
  2325. else {
  2326. this.fromNumber(a, c);
  2327. if (!this.testBit(a - 1)) {
  2328. this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this);
  2329. }
  2330. if (this.isEven()) {
  2331. this.dAddOffset(1, 0);
  2332. }
  2333. var bnp_1 = this;
  2334. var bnpfn1_1 = function () {
  2335. bnp_1.dAddOffset(2, 0);
  2336. if (bnp_1.bitLength() > a) {
  2337. bnp_1.subTo(BigInteger.ONE.shiftLeft(a - 1), bnp_1);
  2338. }
  2339. if (bnp_1.isProbablePrime(b)) {
  2340. setTimeout(function () { callback(); }, 0); // escape
  2341. }
  2342. else {
  2343. setTimeout(bnpfn1_1, 0);
  2344. }
  2345. };
  2346. setTimeout(bnpfn1_1, 0);
  2347. }
  2348. }
  2349. else {
  2350. var x = [];
  2351. var t = a & 7;
  2352. x.length = (a >> 3) + 1;
  2353. b.nextBytes(x);
  2354. if (t > 0) {
  2355. x[0] &= ((1 << t) - 1);
  2356. }
  2357. else {
  2358. x[0] = 0;
  2359. }
  2360. this.fromString(x, 256);
  2361. }
  2362. };
  2363. return BigInteger;
  2364. }());
  2365. //#region REDUCERS
  2366. //#region NullExp
  2367. var NullExp = /** @class */ (function () {
  2368. function NullExp() {
  2369. }
  2370. // NullExp.prototype.convert = nNop;
  2371. NullExp.prototype.convert = function (x) {
  2372. return x;
  2373. };
  2374. // NullExp.prototype.revert = nNop;
  2375. NullExp.prototype.revert = function (x) {
  2376. return x;
  2377. };
  2378. // NullExp.prototype.mulTo = nMulTo;
  2379. NullExp.prototype.mulTo = function (x, y, r) {
  2380. x.multiplyTo(y, r);
  2381. };
  2382. // NullExp.prototype.sqrTo = nSqrTo;
  2383. NullExp.prototype.sqrTo = function (x, r) {
  2384. x.squareTo(r);
  2385. };
  2386. return NullExp;
  2387. }());
  2388. // Modular reduction using "classic" algorithm
  2389. var Classic = /** @class */ (function () {
  2390. function Classic(m) {
  2391. this.m = m;
  2392. }
  2393. // Classic.prototype.convert = cConvert;
  2394. Classic.prototype.convert = function (x) {
  2395. if (x.s < 0 || x.compareTo(this.m) >= 0) {
  2396. return x.mod(this.m);
  2397. }
  2398. else {
  2399. return x;
  2400. }
  2401. };
  2402. // Classic.prototype.revert = cRevert;
  2403. Classic.prototype.revert = function (x) {
  2404. return x;
  2405. };
  2406. // Classic.prototype.reduce = cReduce;
  2407. Classic.prototype.reduce = function (x) {
  2408. x.divRemTo(this.m, null, x);
  2409. };
  2410. // Classic.prototype.mulTo = cMulTo;
  2411. Classic.prototype.mulTo = function (x, y, r) {
  2412. x.multiplyTo(y, r);
  2413. this.reduce(r);
  2414. };
  2415. // Classic.prototype.sqrTo = cSqrTo;
  2416. Classic.prototype.sqrTo = function (x, r) {
  2417. x.squareTo(r);
  2418. this.reduce(r);
  2419. };
  2420. return Classic;
  2421. }());
  2422. //#endregion
  2423. //#region Montgomery
  2424. // Montgomery reduction
  2425. var Montgomery = /** @class */ (function () {
  2426. function Montgomery(m) {
  2427. this.m = m;
  2428. this.mp = m.invDigit();
  2429. this.mpl = this.mp & 0x7fff;
  2430. this.mph = this.mp >> 15;
  2431. this.um = (1 << (m.DB - 15)) - 1;
  2432. this.mt2 = 2 * m.t;
  2433. }
  2434. // Montgomery.prototype.convert = montConvert;
  2435. // xR mod m
  2436. Montgomery.prototype.convert = function (x) {
  2437. var r = nbi();
  2438. x.abs().dlShiftTo(this.m.t, r);
  2439. r.divRemTo(this.m, null, r);
  2440. if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) {
  2441. this.m.subTo(r, r);
  2442. }
  2443. return r;
  2444. };
  2445. // Montgomery.prototype.revert = montRevert;
  2446. // x/R mod m
  2447. Montgomery.prototype.revert = function (x) {
  2448. var r = nbi();
  2449. x.copyTo(r);
  2450. this.reduce(r);
  2451. return r;
  2452. };
  2453. // Montgomery.prototype.reduce = montReduce;
  2454. // x = x/R mod m (HAC 14.32)
  2455. Montgomery.prototype.reduce = function (x) {
  2456. while (x.t <= this.mt2) {
  2457. // pad x so am has enough room later
  2458. x[x.t++] = 0;
  2459. }
  2460. for (var i = 0; i < this.m.t; ++i) {
  2461. // faster way of calculating u0 = x[i]*mp mod DV
  2462. var j = x[i] & 0x7fff;
  2463. var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM;
  2464. // use am to combine the multiply-shift-add into one call
  2465. j = i + this.m.t;
  2466. x[j] += this.m.am(0, u0, x, i, 0, this.m.t);
  2467. // propagate carry
  2468. while (x[j] >= x.DV) {
  2469. x[j] -= x.DV;
  2470. x[++j]++;
  2471. }
  2472. }
  2473. x.clamp();
  2474. x.drShiftTo(this.m.t, x);
  2475. if (x.compareTo(this.m) >= 0) {
  2476. x.subTo(this.m, x);
  2477. }
  2478. };
  2479. // Montgomery.prototype.mulTo = montMulTo;
  2480. // r = "xy/R mod m"; x,y != r
  2481. Montgomery.prototype.mulTo = function (x, y, r) {
  2482. x.multiplyTo(y, r);
  2483. this.reduce(r);
  2484. };
  2485. // Montgomery.prototype.sqrTo = montSqrTo;
  2486. // r = "x^2/R mod m"; x != r
  2487. Montgomery.prototype.sqrTo = function (x, r) {
  2488. x.squareTo(r);
  2489. this.reduce(r);
  2490. };
  2491. return Montgomery;
  2492. }());
  2493. //#endregion Montgomery
  2494. //#region Barrett
  2495. // Barrett modular reduction
  2496. var Barrett = /** @class */ (function () {
  2497. function Barrett(m) {
  2498. this.m = m;
  2499. // setup Barrett
  2500. this.r2 = nbi();
  2501. this.q3 = nbi();
  2502. BigInteger.ONE.dlShiftTo(2 * m.t, this.r2);
  2503. this.mu = this.r2.divide(m);
  2504. }
  2505. // Barrett.prototype.convert = barrettConvert;
  2506. Barrett.prototype.convert = function (x) {
  2507. if (x.s < 0 || x.t > 2 * this.m.t) {
  2508. return x.mod(this.m);
  2509. }
  2510. else if (x.compareTo(this.m) < 0) {
  2511. return x;
  2512. }
  2513. else {
  2514. var r = nbi();
  2515. x.copyTo(r);
  2516. this.reduce(r);
  2517. return r;
  2518. }
  2519. };
  2520. // Barrett.prototype.revert = barrettRevert;
  2521. Barrett.prototype.revert = function (x) {
  2522. return x;
  2523. };
  2524. // Barrett.prototype.reduce = barrettReduce;
  2525. // x = x mod m (HAC 14.42)
  2526. Barrett.prototype.reduce = function (x) {
  2527. x.drShiftTo(this.m.t - 1, this.r2);
  2528. if (x.t > this.m.t + 1) {
  2529. x.t = this.m.t + 1;
  2530. x.clamp();
  2531. }
  2532. this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3);
  2533. this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2);
  2534. while (x.compareTo(this.r2) < 0) {
  2535. x.dAddOffset(1, this.m.t + 1);
  2536. }
  2537. x.subTo(this.r2, x);
  2538. while (x.compareTo(this.m) >= 0) {
  2539. x.subTo(this.m, x);
  2540. }
  2541. };
  2542. // Barrett.prototype.mulTo = barrettMulTo;
  2543. // r = x*y mod m; x,y != r
  2544. Barrett.prototype.mulTo = function (x, y, r) {
  2545. x.multiplyTo(y, r);
  2546. this.reduce(r);
  2547. };
  2548. // Barrett.prototype.sqrTo = barrettSqrTo;
  2549. // r = x^2 mod m; x != r
  2550. Barrett.prototype.sqrTo = function (x, r) {
  2551. x.squareTo(r);
  2552. this.reduce(r);
  2553. };
  2554. return Barrett;
  2555. }());
  2556. //#endregion
  2557. //#endregion REDUCERS
  2558. // return new, unset BigInteger
  2559. function nbi() { return new BigInteger(null); }
  2560. function parseBigInt(str, r) {
  2561. return new BigInteger(str, r);
  2562. }
  2563. // am: Compute w_j += (x*this_i), propagate carries,
  2564. // c is initial carry, returns final carry.
  2565. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue
  2566. // We need to select the fastest one that works in this environment.
  2567. // am1: use a single mult and divide to get the high bits,
  2568. // max digit bits should be 26 because
  2569. // max internal value = 2*dvalue^2-2*dvalue (< 2^53)
  2570. function am1(i, x, w, j, c, n) {
  2571. while (--n >= 0) {
  2572. var v = x * this[i++] + w[j] + c;
  2573. c = Math.floor(v / 0x4000000);
  2574. w[j++] = v & 0x3ffffff;
  2575. }
  2576. return c;
  2577. }
  2578. // am2 avoids a big mult-and-extract completely.
  2579. // Max digit bits should be <= 30 because we do bitwise ops
  2580. // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
  2581. function am2(i, x, w, j, c, n) {
  2582. var xl = x & 0x7fff;
  2583. var xh = x >> 15;
  2584. while (--n >= 0) {
  2585. var l = this[i] & 0x7fff;
  2586. var h = this[i++] >> 15;
  2587. var m = xh * l + h * xl;
  2588. l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff);
  2589. c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30);
  2590. w[j++] = l & 0x3fffffff;
  2591. }
  2592. return c;
  2593. }
  2594. // Alternately, set max digit bits to 28 since some
  2595. // browsers slow down when dealing with 32-bit numbers.
  2596. function am3(i, x, w, j, c, n) {
  2597. var xl = x & 0x3fff;
  2598. var xh = x >> 14;
  2599. while (--n >= 0) {
  2600. var l = this[i] & 0x3fff;
  2601. var h = this[i++] >> 14;
  2602. var m = xh * l + h * xl;
  2603. l = xl * l + ((m & 0x3fff) << 14) + w[j] + c;
  2604. c = (l >> 28) + (m >> 14) + xh * h;
  2605. w[j++] = l & 0xfffffff;
  2606. }
  2607. return c;
  2608. }
  2609. if (j_lm && (navigator.appName == "Microsoft Internet Explorer")) {
  2610. BigInteger.prototype.am = am2;
  2611. dbits = 30;
  2612. }
  2613. else if (j_lm && (navigator.appName != "Netscape")) {
  2614. BigInteger.prototype.am = am1;
  2615. dbits = 26;
  2616. }
  2617. else {
  2618. BigInteger.prototype.am = am3;
  2619. dbits = 28;
  2620. }
  2621. BigInteger.prototype.DB = dbits;
  2622. BigInteger.prototype.DM = ((1 << dbits) - 1);
  2623. BigInteger.prototype.DV = (1 << dbits);
  2624. var BI_FP = 52;
  2625. BigInteger.prototype.FV = Math.pow(2, BI_FP);
  2626. BigInteger.prototype.F1 = BI_FP - dbits;
  2627. BigInteger.prototype.F2 = 2 * dbits - BI_FP;
  2628. // Digit conversions
  2629. var BI_RC = [];
  2630. var rr;
  2631. var vv;
  2632. rr = "0".charCodeAt(0);
  2633. for (vv = 0; vv <= 9; ++vv) {
  2634. BI_RC[rr++] = vv;
  2635. }
  2636. rr = "a".charCodeAt(0);
  2637. for (vv = 10; vv < 36; ++vv) {
  2638. BI_RC[rr++] = vv;
  2639. }
  2640. rr = "A".charCodeAt(0);
  2641. for (vv = 10; vv < 36; ++vv) {
  2642. BI_RC[rr++] = vv;
  2643. }
  2644. function intAt(s, i) {
  2645. var c = BI_RC[s.charCodeAt(i)];
  2646. return (c == null) ? -1 : c;
  2647. }
  2648. // return bigint initialized to value
  2649. function nbv(i) {
  2650. var r = nbi();
  2651. r.fromInt(i);
  2652. return r;
  2653. }
  2654. // returns bit length of the integer x
  2655. function nbits(x) {
  2656. var r = 1;
  2657. var t;
  2658. if ((t = x >>> 16) != 0) {
  2659. x = t;
  2660. r += 16;
  2661. }
  2662. if ((t = x >> 8) != 0) {
  2663. x = t;
  2664. r += 8;
  2665. }
  2666. if ((t = x >> 4) != 0) {
  2667. x = t;
  2668. r += 4;
  2669. }
  2670. if ((t = x >> 2) != 0) {
  2671. x = t;
  2672. r += 2;
  2673. }
  2674. if ((t = x >> 1) != 0) {
  2675. x = t;
  2676. r += 1;
  2677. }
  2678. return r;
  2679. }
  2680. // "constants"
  2681. BigInteger.ZERO = nbv(0);
  2682. BigInteger.ONE = nbv(1);
  2683. // prng4.js - uses Arcfour as a PRNG
  2684. var Arcfour = /** @class */ (function () {
  2685. function Arcfour() {
  2686. this.i = 0;
  2687. this.j = 0;
  2688. this.S = [];
  2689. }
  2690. // Arcfour.prototype.init = ARC4init;
  2691. // Initialize arcfour context from key, an array of ints, each from [0..255]
  2692. Arcfour.prototype.init = function (key) {
  2693. var i;
  2694. var j;
  2695. var t;
  2696. for (i = 0; i < 256; ++i) {
  2697. this.S[i] = i;
  2698. }
  2699. j = 0;
  2700. for (i = 0; i < 256; ++i) {
  2701. j = (j + this.S[i] + key[i % key.length]) & 255;
  2702. t = this.S[i];
  2703. this.S[i] = this.S[j];
  2704. this.S[j] = t;
  2705. }
  2706. this.i = 0;
  2707. this.j = 0;
  2708. };
  2709. // Arcfour.prototype.next = ARC4next;
  2710. Arcfour.prototype.next = function () {
  2711. var t;
  2712. this.i = (this.i + 1) & 255;
  2713. this.j = (this.j + this.S[this.i]) & 255;
  2714. t = this.S[this.i];
  2715. this.S[this.i] = this.S[this.j];
  2716. this.S[this.j] = t;
  2717. return this.S[(t + this.S[this.i]) & 255];
  2718. };
  2719. return Arcfour;
  2720. }());
  2721. // Plug in your RNG constructor here
  2722. function prng_newstate() {
  2723. return new Arcfour();
  2724. }
  2725. // Pool size must be a multiple of 4 and greater than 32.
  2726. // An array of bytes the size of the pool will be passed to init()
  2727. var rng_psize = 256;
  2728. // Random number generator - requires a PRNG backend, e.g. prng4.js
  2729. var rng_state;
  2730. var rng_pool = null;
  2731. var rng_pptr;
  2732. // Initialize the pool with junk if needed.
  2733. if (rng_pool == null) {
  2734. rng_pool = [];
  2735. rng_pptr = 0;
  2736. var t = void 0;
  2737. if (window.crypto && window.crypto.getRandomValues) {
  2738. // Extract entropy (2048 bits) from RNG if available
  2739. var z = new Uint32Array(256);
  2740. window.crypto.getRandomValues(z);
  2741. for (t = 0; t < z.length; ++t) {
  2742. rng_pool[rng_pptr++] = z[t] & 255;
  2743. }
  2744. }
  2745. // Use mouse events for entropy, if we do not have enough entropy by the time
  2746. // we need it, entropy will be generated by Math.random.
  2747. var onMouseMoveListener_1 = function (ev) {
  2748. this.count = this.count || 0;
  2749. if (this.count >= 256 || rng_pptr >= rng_psize) {
  2750. if (window.removeEventListener) {
  2751. window.removeEventListener("mousemove", onMouseMoveListener_1, false);
  2752. }
  2753. else if (window.detachEvent) {
  2754. window.detachEvent("onmousemove", onMouseMoveListener_1);
  2755. }
  2756. return;
  2757. }
  2758. try {
  2759. var mouseCoordinates = ev.x + ev.y;
  2760. rng_pool[rng_pptr++] = mouseCoordinates & 255;
  2761. this.count += 1;
  2762. }
  2763. catch (e) {
  2764. // Sometimes Firefox will deny permission to access event properties for some reason. Ignore.
  2765. }
  2766. };
  2767. if (window.addEventListener) {
  2768. window.addEventListener("mousemove", onMouseMoveListener_1, false);
  2769. }
  2770. else if (window.attachEvent) {
  2771. window.attachEvent("onmousemove", onMouseMoveListener_1);
  2772. }
  2773. }
  2774. function rng_get_byte() {
  2775. if (rng_state == null) {
  2776. rng_state = prng_newstate();
  2777. // At this point, we may not have collected enough entropy. If not, fall back to Math.random
  2778. while (rng_pptr < rng_psize) {
  2779. var random = Math.floor(65536 * Math.random());
  2780. rng_pool[rng_pptr++] = random & 255;
  2781. }
  2782. rng_state.init(rng_pool);
  2783. for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) {
  2784. rng_pool[rng_pptr] = 0;
  2785. }
  2786. rng_pptr = 0;
  2787. }
  2788. // TODO: allow reseeding after first request
  2789. return rng_state.next();
  2790. }
  2791. var SecureRandom = /** @class */ (function () {
  2792. function SecureRandom() {
  2793. }
  2794. SecureRandom.prototype.nextBytes = function (ba) {
  2795. for (var i = 0; i < ba.length; ++i) {
  2796. ba[i] = rng_get_byte();
  2797. }
  2798. };
  2799. return SecureRandom;
  2800. }());
  2801. // Depends on jsbn.js and rng.js
  2802. // function linebrk(s,n) {
  2803. // var ret = "";
  2804. // var i = 0;
  2805. // while(i + n < s.length) {
  2806. // ret += s.substring(i,i+n) + "\n";
  2807. // i += n;
  2808. // }
  2809. // return ret + s.substring(i,s.length);
  2810. // }
  2811. // function byte2Hex(b) {
  2812. // if(b < 0x10)
  2813. // return "0" + b.toString(16);
  2814. // else
  2815. // return b.toString(16);
  2816. // }
  2817. // PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint
  2818. function pkcs1pad2(s, n) {
  2819. if (n < s.length + 11) {
  2820. console.error("Message too long for RSA");
  2821. return null;
  2822. }
  2823. var ba = [];
  2824. var i = s.length - 1;
  2825. while (i >= 0 && n > 0) {
  2826. var c = s.charCodeAt(i--);
  2827. if (c < 128) {
  2828. ba[--n] = c;
  2829. }
  2830. else if ((c > 127) && (c < 2048)) {
  2831. ba[--n] = (c & 63) | 128;
  2832. ba[--n] = (c >> 6) | 192;
  2833. }
  2834. else {
  2835. ba[--n] = (c & 63) | 128;
  2836. ba[--n] = ((c >> 6) & 63) | 128;
  2837. ba[--n] = (c >> 12) | 224;
  2838. }
  2839. }
  2840. ba[--n] = 0;
  2841. var rng = new SecureRandom();
  2842. var x = [];
  2843. while (n > 2) {
  2844. x[0] = 0;
  2845. while (x[0] == 0) {
  2846. rng.nextBytes(x);
  2847. }
  2848. ba[--n] = x[0];
  2849. }
  2850. ba[--n] = 2;
  2851. ba[--n] = 0;
  2852. return new BigInteger(ba);
  2853. }
  2854. // "empty" RSA key constructor
  2855. var RSAKey = /** @class */ (function () {
  2856. function RSAKey() {
  2857. this.n = null;
  2858. this.e = 0;
  2859. this.d = null;
  2860. this.p = null;
  2861. this.q = null;
  2862. this.dmp1 = null;
  2863. this.dmq1 = null;
  2864. this.coeff = null;
  2865. }
  2866. //#region PROTECTED
  2867. // protected
  2868. // RSAKey.prototype.doPublic = RSADoPublic;
  2869. // Perform raw public operation on "x": return x^e (mod n)
  2870. RSAKey.prototype.doPublic = function (x) {
  2871. return x.modPowInt(this.e, this.n);
  2872. };
  2873. // RSAKey.prototype.doPrivate = RSADoPrivate;
  2874. // Perform raw private operation on "x": return x^d (mod n)
  2875. RSAKey.prototype.doPrivate = function (x) {
  2876. if (this.p == null || this.q == null) {
  2877. return x.modPow(this.d, this.n);
  2878. }
  2879. // TODO: re-calculate any missing CRT params
  2880. var xp = x.mod(this.p).modPow(this.dmp1, this.p);
  2881. var xq = x.mod(this.q).modPow(this.dmq1, this.q);
  2882. while (xp.compareTo(xq) < 0) {
  2883. xp = xp.add(this.p);
  2884. }
  2885. return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq);
  2886. };
  2887. //#endregion PROTECTED
  2888. //#region PUBLIC
  2889. // RSAKey.prototype.setPublic = RSASetPublic;
  2890. // Set the public key fields N and e from hex strings
  2891. RSAKey.prototype.setPublic = function (N, E) {
  2892. if (N != null && E != null && N.length > 0 && E.length > 0) {
  2893. this.n = parseBigInt(N, 16);
  2894. this.e = parseInt(E, 16);
  2895. }
  2896. else {
  2897. console.error("Invalid RSA public key");
  2898. }
  2899. };
  2900. // RSAKey.prototype.encrypt = RSAEncrypt;
  2901. // Return the PKCS#1 RSA encryption of "text" as an even-length hex string
  2902. RSAKey.prototype.encrypt = function (text) {
  2903. var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3);
  2904. if (m == null) {
  2905. return null;
  2906. }
  2907. var c = this.doPublic(m);
  2908. if (c == null) {
  2909. return null;
  2910. }
  2911. var h = c.toString(16);
  2912. if ((h.length & 1) == 0) {
  2913. return h;
  2914. }
  2915. else {
  2916. return "0" + h;
  2917. }
  2918. };
  2919. // RSAKey.prototype.setPrivate = RSASetPrivate;
  2920. // Set the private key fields N, e, and d from hex strings
  2921. RSAKey.prototype.setPrivate = function (N, E, D) {
  2922. if (N != null && E != null && N.length > 0 && E.length > 0) {
  2923. this.n = parseBigInt(N, 16);
  2924. this.e = parseInt(E, 16);
  2925. this.d = parseBigInt(D, 16);
  2926. }
  2927. else {
  2928. console.error("Invalid RSA private key");
  2929. }
  2930. };
  2931. // RSAKey.prototype.setPrivateEx = RSASetPrivateEx;
  2932. // Set the private key fields N, e, d and CRT params from hex strings
  2933. RSAKey.prototype.setPrivateEx = function (N, E, D, P, Q, DP, DQ, C) {
  2934. if (N != null && E != null && N.length > 0 && E.length > 0) {
  2935. this.n = parseBigInt(N, 16);
  2936. this.e = parseInt(E, 16);
  2937. this.d = parseBigInt(D, 16);
  2938. this.p = parseBigInt(P, 16);
  2939. this.q = parseBigInt(Q, 16);
  2940. this.dmp1 = parseBigInt(DP, 16);
  2941. this.dmq1 = parseBigInt(DQ, 16);
  2942. this.coeff = parseBigInt(C, 16);
  2943. }
  2944. else {
  2945. console.error("Invalid RSA private key");
  2946. }
  2947. };
  2948. // RSAKey.prototype.generate = RSAGenerate;
  2949. // Generate a new random private key B bits long, using public expt E
  2950. RSAKey.prototype.generate = function (B, E) {
  2951. var rng = new SecureRandom();
  2952. var qs = B >> 1;
  2953. this.e = parseInt(E, 16);
  2954. var ee = new BigInteger(E, 16);
  2955. for (;;) {
  2956. for (;;) {
  2957. this.p = new BigInteger(B - qs, 1, rng);
  2958. if (this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.p.isProbablePrime(10)) {
  2959. break;
  2960. }
  2961. }
  2962. for (;;) {
  2963. this.q = new BigInteger(qs, 1, rng);
  2964. if (this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) == 0 && this.q.isProbablePrime(10)) {
  2965. break;
  2966. }
  2967. }
  2968. if (this.p.compareTo(this.q) <= 0) {
  2969. var t = this.p;
  2970. this.p = this.q;
  2971. this.q = t;
  2972. }
  2973. var p1 = this.p.subtract(BigInteger.ONE);
  2974. var q1 = this.q.subtract(BigInteger.ONE);
  2975. var phi = p1.multiply(q1);
  2976. if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
  2977. this.n = this.p.multiply(this.q);
  2978. this.d = ee.modInverse(phi);
  2979. this.dmp1 = this.d.mod(p1);
  2980. this.dmq1 = this.d.mod(q1);
  2981. this.coeff = this.q.modInverse(this.p);
  2982. break;
  2983. }
  2984. }
  2985. };
  2986. // RSAKey.prototype.decrypt = RSADecrypt;
  2987. // Return the PKCS#1 RSA decryption of "ctext".
  2988. // "ctext" is an even-length hex string and the output is a plain string.
  2989. RSAKey.prototype.decrypt = function (ctext) {
  2990. var c = parseBigInt(ctext, 16);
  2991. var m = this.doPrivate(c);
  2992. if (m == null) {
  2993. return null;
  2994. }
  2995. return pkcs1unpad2(m, (this.n.bitLength() + 7) >> 3);
  2996. };
  2997. // Generate a new random private key B bits long, using public expt E
  2998. RSAKey.prototype.generateAsync = function (B, E, callback) {
  2999. var rng = new SecureRandom();
  3000. var qs = B >> 1;
  3001. this.e = parseInt(E, 16);
  3002. var ee = new BigInteger(E, 16);
  3003. var rsa = this;
  3004. // These functions have non-descript names because they were originally for(;;) loops.
  3005. // I don't know about cryptography to give them better names than loop1-4.
  3006. var loop1 = function () {
  3007. var loop4 = function () {
  3008. if (rsa.p.compareTo(rsa.q) <= 0) {
  3009. var t = rsa.p;
  3010. rsa.p = rsa.q;
  3011. rsa.q = t;
  3012. }
  3013. var p1 = rsa.p.subtract(BigInteger.ONE);
  3014. var q1 = rsa.q.subtract(BigInteger.ONE);
  3015. var phi = p1.multiply(q1);
  3016. if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
  3017. rsa.n = rsa.p.multiply(rsa.q);
  3018. rsa.d = ee.modInverse(phi);
  3019. rsa.dmp1 = rsa.d.mod(p1);
  3020. rsa.dmq1 = rsa.d.mod(q1);
  3021. rsa.coeff = rsa.q.modInverse(rsa.p);
  3022. setTimeout(function () { callback(); }, 0); // escape
  3023. }
  3024. else {
  3025. setTimeout(loop1, 0);
  3026. }
  3027. };
  3028. var loop3 = function () {
  3029. rsa.q = nbi();
  3030. rsa.q.fromNumberAsync(qs, 1, rng, function () {
  3031. rsa.q.subtract(BigInteger.ONE).gcda(ee, function (r) {
  3032. if (r.compareTo(BigInteger.ONE) == 0 && rsa.q.isProbablePrime(10)) {
  3033. setTimeout(loop4, 0);
  3034. }
  3035. else {
  3036. setTimeout(loop3, 0);
  3037. }
  3038. });
  3039. });
  3040. };
  3041. var loop2 = function () {
  3042. rsa.p = nbi();
  3043. rsa.p.fromNumberAsync(B - qs, 1, rng, function () {
  3044. rsa.p.subtract(BigInteger.ONE).gcda(ee, function (r) {
  3045. if (r.compareTo(BigInteger.ONE) == 0 && rsa.p.isProbablePrime(10)) {
  3046. setTimeout(loop3, 0);
  3047. }
  3048. else {
  3049. setTimeout(loop2, 0);
  3050. }
  3051. });
  3052. });
  3053. };
  3054. setTimeout(loop2, 0);
  3055. };
  3056. setTimeout(loop1, 0);
  3057. };
  3058. return RSAKey;
  3059. }());
  3060. // Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext
  3061. function pkcs1unpad2(d, n) {
  3062. var b = d.toByteArray();
  3063. var i = 0;
  3064. while (i < b.length && b[i] == 0) {
  3065. ++i;
  3066. }
  3067. if (b.length - i != n - 1 || b[i] != 2) {
  3068. return null;
  3069. }
  3070. ++i;
  3071. while (b[i] != 0) {
  3072. if (++i >= b.length) {
  3073. return null;
  3074. }
  3075. }
  3076. var ret = "";
  3077. while (++i < b.length) {
  3078. var c = b[i] & 255;
  3079. if (c < 128) {
  3080. ret += String.fromCharCode(c);
  3081. }
  3082. else if ((c > 191) && (c < 224)) {
  3083. ret += String.fromCharCode(((c & 31) << 6) | (b[i + 1] & 63));
  3084. ++i;
  3085. }
  3086. else {
  3087. ret += String.fromCharCode(((c & 15) << 12) | ((b[i + 1] & 63) << 6) | (b[i + 2] & 63));
  3088. i += 2;
  3089. }
  3090. }
  3091. return ret;
  3092. }
  3093. // Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string
  3094. // function RSAEncryptB64(text) {
  3095. // var h = this.encrypt(text);
  3096. // if(h) return hex2b64(h); else return null;
  3097. // }
  3098. // public
  3099. // RSAKey.prototype.encrypt_b64 = RSAEncryptB64;
  3100. /*!
  3101. Copyright (c) 2011, Yahoo! Inc. All rights reserved.
  3102. Code licensed under the BSD License:
  3103. http://developer.yahoo.com/yui/license.html
  3104. version: 2.9.0
  3105. */
  3106. var YAHOO = {};
  3107. YAHOO.lang = {
  3108. /**
  3109. * Utility to set up the prototype, constructor and superclass properties to
  3110. * support an inheritance strategy that can chain constructors and methods.
  3111. * Static members will not be inherited.
  3112. *
  3113. * @method extend
  3114. * @static
  3115. * @param {Function} subc the object to modify
  3116. * @param {Function} superc the object to inherit
  3117. * @param {Object} overrides additional properties/methods to add to the
  3118. * subclass prototype. These will override the
  3119. * matching items obtained from the superclass
  3120. * if present.
  3121. */
  3122. extend: function(subc, superc, overrides) {
  3123. if (! superc || ! subc) {
  3124. throw new Error("YAHOO.lang.extend failed, please check that " +
  3125. "all dependencies are included.");
  3126. }
  3127. var F = function() {};
  3128. F.prototype = superc.prototype;
  3129. subc.prototype = new F();
  3130. subc.prototype.constructor = subc;
  3131. subc.superclass = superc.prototype;
  3132. if (superc.prototype.constructor == Object.prototype.constructor) {
  3133. superc.prototype.constructor = superc;
  3134. }
  3135. if (overrides) {
  3136. var i;
  3137. for (i in overrides) {
  3138. subc.prototype[i] = overrides[i];
  3139. }
  3140. /*
  3141. * IE will not enumerate native functions in a derived object even if the
  3142. * function was overridden. This is a workaround for specific functions
  3143. * we care about on the Object prototype.
  3144. * @property _IEEnumFix
  3145. * @param {Function} r the object to receive the augmentation
  3146. * @param {Function} s the object that supplies the properties to augment
  3147. * @static
  3148. * @private
  3149. */
  3150. var _IEEnumFix = function() {},
  3151. ADD = ["toString", "valueOf"];
  3152. try {
  3153. if (/MSIE/.test(navigator.userAgent)) {
  3154. _IEEnumFix = function(r, s) {
  3155. for (i = 0; i < ADD.length; i = i + 1) {
  3156. var fname = ADD[i], f = s[fname];
  3157. if (typeof f === 'function' && f != Object.prototype[fname]) {
  3158. r[fname] = f;
  3159. }
  3160. }
  3161. };
  3162. }
  3163. } catch (ex) {} _IEEnumFix(subc.prototype, overrides);
  3164. }
  3165. }
  3166. };
  3167. /* asn1-1.0.13.js (c) 2013-2017 Kenji Urushima | kjur.github.com/jsrsasign/license
  3168. */
  3169. /**
  3170. * @fileOverview
  3171. * @name asn1-1.0.js
  3172. * @author Kenji Urushima kenji.urushima@gmail.com
  3173. * @version asn1 1.0.13 (2017-Jun-02)
  3174. * @since jsrsasign 2.1
  3175. * @license <a href="https://kjur.github.io/jsrsasign/license/">MIT License</a>
  3176. */
  3177. /**
  3178. * kjur's class library name space
  3179. * <p>
  3180. * This name space provides following name spaces:
  3181. * <ul>
  3182. * <li>{@link KJUR.asn1} - ASN.1 primitive hexadecimal encoder</li>
  3183. * <li>{@link KJUR.asn1.x509} - ASN.1 structure for X.509 certificate and CRL</li>
  3184. * <li>{@link KJUR.crypto} - Java Cryptographic Extension(JCE) style MessageDigest/Signature
  3185. * class and utilities</li>
  3186. * </ul>
  3187. * </p>
  3188. * NOTE: Please ignore method summary and document of this namespace. This caused by a bug of jsdoc2.
  3189. * @name KJUR
  3190. * @namespace kjur's class library name space
  3191. */
  3192. var KJUR = {};
  3193. /**
  3194. * kjur's ASN.1 class library name space
  3195. * <p>
  3196. * This is ITU-T X.690 ASN.1 DER encoder class library and
  3197. * class structure and methods is very similar to
  3198. * org.bouncycastle.asn1 package of
  3199. * well known BouncyCaslte Cryptography Library.
  3200. * <h4>PROVIDING ASN.1 PRIMITIVES</h4>
  3201. * Here are ASN.1 DER primitive classes.
  3202. * <ul>
  3203. * <li>0x01 {@link KJUR.asn1.DERBoolean}</li>
  3204. * <li>0x02 {@link KJUR.asn1.DERInteger}</li>
  3205. * <li>0x03 {@link KJUR.asn1.DERBitString}</li>
  3206. * <li>0x04 {@link KJUR.asn1.DEROctetString}</li>
  3207. * <li>0x05 {@link KJUR.asn1.DERNull}</li>
  3208. * <li>0x06 {@link KJUR.asn1.DERObjectIdentifier}</li>
  3209. * <li>0x0a {@link KJUR.asn1.DEREnumerated}</li>
  3210. * <li>0x0c {@link KJUR.asn1.DERUTF8String}</li>
  3211. * <li>0x12 {@link KJUR.asn1.DERNumericString}</li>
  3212. * <li>0x13 {@link KJUR.asn1.DERPrintableString}</li>
  3213. * <li>0x14 {@link KJUR.asn1.DERTeletexString}</li>
  3214. * <li>0x16 {@link KJUR.asn1.DERIA5String}</li>
  3215. * <li>0x17 {@link KJUR.asn1.DERUTCTime}</li>
  3216. * <li>0x18 {@link KJUR.asn1.DERGeneralizedTime}</li>
  3217. * <li>0x30 {@link KJUR.asn1.DERSequence}</li>
  3218. * <li>0x31 {@link KJUR.asn1.DERSet}</li>
  3219. * </ul>
  3220. * <h4>OTHER ASN.1 CLASSES</h4>
  3221. * <ul>
  3222. * <li>{@link KJUR.asn1.ASN1Object}</li>
  3223. * <li>{@link KJUR.asn1.DERAbstractString}</li>
  3224. * <li>{@link KJUR.asn1.DERAbstractTime}</li>
  3225. * <li>{@link KJUR.asn1.DERAbstractStructured}</li>
  3226. * <li>{@link KJUR.asn1.DERTaggedObject}</li>
  3227. * </ul>
  3228. * <h4>SUB NAME SPACES</h4>
  3229. * <ul>
  3230. * <li>{@link KJUR.asn1.cades} - CAdES long term signature format</li>
  3231. * <li>{@link KJUR.asn1.cms} - Cryptographic Message Syntax</li>
  3232. * <li>{@link KJUR.asn1.csr} - Certificate Signing Request (CSR/PKCS#10)</li>
  3233. * <li>{@link KJUR.asn1.tsp} - RFC 3161 Timestamping Protocol Format</li>
  3234. * <li>{@link KJUR.asn1.x509} - RFC 5280 X.509 certificate and CRL</li>
  3235. * </ul>
  3236. * </p>
  3237. * NOTE: Please ignore method summary and document of this namespace.
  3238. * This caused by a bug of jsdoc2.
  3239. * @name KJUR.asn1
  3240. * @namespace
  3241. */
  3242. if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) KJUR.asn1 = {};
  3243. /**
  3244. * ASN1 utilities class
  3245. * @name KJUR.asn1.ASN1Util
  3246. * @class ASN1 utilities class
  3247. * @since asn1 1.0.2
  3248. */
  3249. KJUR.asn1.ASN1Util = new function() {
  3250. this.integerToByteHex = function(i) {
  3251. var h = i.toString(16);
  3252. if ((h.length % 2) == 1) h = '0' + h;
  3253. return h;
  3254. };
  3255. this.bigIntToMinTwosComplementsHex = function(bigIntegerValue) {
  3256. var h = bigIntegerValue.toString(16);
  3257. if (h.substr(0, 1) != '-') {
  3258. if (h.length % 2 == 1) {
  3259. h = '0' + h;
  3260. } else {
  3261. if (! h.match(/^[0-7]/)) {
  3262. h = '00' + h;
  3263. }
  3264. }
  3265. } else {
  3266. var hPos = h.substr(1);
  3267. var xorLen = hPos.length;
  3268. if (xorLen % 2 == 1) {
  3269. xorLen += 1;
  3270. } else {
  3271. if (! h.match(/^[0-7]/)) {
  3272. xorLen += 2;
  3273. }
  3274. }
  3275. var hMask = '';
  3276. for (var i = 0; i < xorLen; i++) {
  3277. hMask += 'f';
  3278. }
  3279. var biMask = new BigInteger(hMask, 16);
  3280. var biNeg = biMask.xor(bigIntegerValue).add(BigInteger.ONE);
  3281. h = biNeg.toString(16).replace(/^-/, '');
  3282. }
  3283. return h;
  3284. };
  3285. /**
  3286. * get PEM string from hexadecimal data and header string
  3287. * @name getPEMStringFromHex
  3288. * @memberOf KJUR.asn1.ASN1Util
  3289. * @function
  3290. * @param {String} dataHex hexadecimal string of PEM body
  3291. * @param {String} pemHeader PEM header string (ex. 'RSA PRIVATE KEY')
  3292. * @return {String} PEM formatted string of input data
  3293. * @description
  3294. * This method converts a hexadecimal string to a PEM string with
  3295. * a specified header. Its line break will be CRLF("\r\n").
  3296. * @example
  3297. * var pem = KJUR.asn1.ASN1Util.getPEMStringFromHex('616161', 'RSA PRIVATE KEY');
  3298. * // value of pem will be:
  3299. * -----BEGIN PRIVATE KEY-----
  3300. * YWFh
  3301. * -----END PRIVATE KEY-----
  3302. */
  3303. this.getPEMStringFromHex = function(dataHex, pemHeader) {
  3304. return hextopem(dataHex, pemHeader);
  3305. };
  3306. /**
  3307. * generate ASN1Object specifed by JSON parameters
  3308. * @name newObject
  3309. * @memberOf KJUR.asn1.ASN1Util
  3310. * @function
  3311. * @param {Array} param JSON parameter to generate ASN1Object
  3312. * @return {KJUR.asn1.ASN1Object} generated object
  3313. * @since asn1 1.0.3
  3314. * @description
  3315. * generate any ASN1Object specified by JSON param
  3316. * including ASN.1 primitive or structured.
  3317. * Generally 'param' can be described as follows:
  3318. * <blockquote>
  3319. * {TYPE-OF-ASNOBJ: ASN1OBJ-PARAMETER}
  3320. * </blockquote>
  3321. * 'TYPE-OF-ASN1OBJ' can be one of following symbols:
  3322. * <ul>
  3323. * <li>'bool' - DERBoolean</li>
  3324. * <li>'int' - DERInteger</li>
  3325. * <li>'bitstr' - DERBitString</li>
  3326. * <li>'octstr' - DEROctetString</li>
  3327. * <li>'null' - DERNull</li>
  3328. * <li>'oid' - DERObjectIdentifier</li>
  3329. * <li>'enum' - DEREnumerated</li>
  3330. * <li>'utf8str' - DERUTF8String</li>
  3331. * <li>'numstr' - DERNumericString</li>
  3332. * <li>'prnstr' - DERPrintableString</li>
  3333. * <li>'telstr' - DERTeletexString</li>
  3334. * <li>'ia5str' - DERIA5String</li>
  3335. * <li>'utctime' - DERUTCTime</li>
  3336. * <li>'gentime' - DERGeneralizedTime</li>
  3337. * <li>'seq' - DERSequence</li>
  3338. * <li>'set' - DERSet</li>
  3339. * <li>'tag' - DERTaggedObject</li>
  3340. * </ul>
  3341. * @example
  3342. * newObject({'prnstr': 'aaa'});
  3343. * newObject({'seq': [{'int': 3}, {'prnstr': 'aaa'}]})
  3344. * // ASN.1 Tagged Object
  3345. * newObject({'tag': {'tag': 'a1',
  3346. * 'explicit': true,
  3347. * 'obj': {'seq': [{'int': 3}, {'prnstr': 'aaa'}]}}});
  3348. * // more simple representation of ASN.1 Tagged Object
  3349. * newObject({'tag': ['a1',
  3350. * true,
  3351. * {'seq': [
  3352. * {'int': 3},
  3353. * {'prnstr': 'aaa'}]}
  3354. * ]});
  3355. */
  3356. this.newObject = function(param) {
  3357. var _KJUR = KJUR,
  3358. _KJUR_asn1 = _KJUR.asn1,
  3359. _DERBoolean = _KJUR_asn1.DERBoolean,
  3360. _DERInteger = _KJUR_asn1.DERInteger,
  3361. _DERBitString = _KJUR_asn1.DERBitString,
  3362. _DEROctetString = _KJUR_asn1.DEROctetString,
  3363. _DERNull = _KJUR_asn1.DERNull,
  3364. _DERObjectIdentifier = _KJUR_asn1.DERObjectIdentifier,
  3365. _DEREnumerated = _KJUR_asn1.DEREnumerated,
  3366. _DERUTF8String = _KJUR_asn1.DERUTF8String,
  3367. _DERNumericString = _KJUR_asn1.DERNumericString,
  3368. _DERPrintableString = _KJUR_asn1.DERPrintableString,
  3369. _DERTeletexString = _KJUR_asn1.DERTeletexString,
  3370. _DERIA5String = _KJUR_asn1.DERIA5String,
  3371. _DERUTCTime = _KJUR_asn1.DERUTCTime,
  3372. _DERGeneralizedTime = _KJUR_asn1.DERGeneralizedTime,
  3373. _DERSequence = _KJUR_asn1.DERSequence,
  3374. _DERSet = _KJUR_asn1.DERSet,
  3375. _DERTaggedObject = _KJUR_asn1.DERTaggedObject,
  3376. _newObject = _KJUR_asn1.ASN1Util.newObject;
  3377. var keys = Object.keys(param);
  3378. if (keys.length != 1)
  3379. throw "key of param shall be only one.";
  3380. var key = keys[0];
  3381. if (":bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:seq:set:tag:".indexOf(":" + key + ":") == -1)
  3382. throw "undefined key: " + key;
  3383. if (key == "bool") return new _DERBoolean(param[key]);
  3384. if (key == "int") return new _DERInteger(param[key]);
  3385. if (key == "bitstr") return new _DERBitString(param[key]);
  3386. if (key == "octstr") return new _DEROctetString(param[key]);
  3387. if (key == "null") return new _DERNull(param[key]);
  3388. if (key == "oid") return new _DERObjectIdentifier(param[key]);
  3389. if (key == "enum") return new _DEREnumerated(param[key]);
  3390. if (key == "utf8str") return new _DERUTF8String(param[key]);
  3391. if (key == "numstr") return new _DERNumericString(param[key]);
  3392. if (key == "prnstr") return new _DERPrintableString(param[key]);
  3393. if (key == "telstr") return new _DERTeletexString(param[key]);
  3394. if (key == "ia5str") return new _DERIA5String(param[key]);
  3395. if (key == "utctime") return new _DERUTCTime(param[key]);
  3396. if (key == "gentime") return new _DERGeneralizedTime(param[key]);
  3397. if (key == "seq") {
  3398. var paramList = param[key];
  3399. var a = [];
  3400. for (var i = 0; i < paramList.length; i++) {
  3401. var asn1Obj = _newObject(paramList[i]);
  3402. a.push(asn1Obj);
  3403. }
  3404. return new _DERSequence({'array': a});
  3405. }
  3406. if (key == "set") {
  3407. var paramList = param[key];
  3408. var a = [];
  3409. for (var i = 0; i < paramList.length; i++) {
  3410. var asn1Obj = _newObject(paramList[i]);
  3411. a.push(asn1Obj);
  3412. }
  3413. return new _DERSet({'array': a});
  3414. }
  3415. if (key == "tag") {
  3416. var tagParam = param[key];
  3417. if (Object.prototype.toString.call(tagParam) === '[object Array]' &&
  3418. tagParam.length == 3) {
  3419. var obj = _newObject(tagParam[2]);
  3420. return new _DERTaggedObject({tag: tagParam[0],
  3421. explicit: tagParam[1],
  3422. obj: obj});
  3423. } else {
  3424. var newParam = {};
  3425. if (tagParam.explicit !== undefined)
  3426. newParam.explicit = tagParam.explicit;
  3427. if (tagParam.tag !== undefined)
  3428. newParam.tag = tagParam.tag;
  3429. if (tagParam.obj === undefined)
  3430. throw "obj shall be specified for 'tag'.";
  3431. newParam.obj = _newObject(tagParam.obj);
  3432. return new _DERTaggedObject(newParam);
  3433. }
  3434. }
  3435. };
  3436. /**
  3437. * get encoded hexadecimal string of ASN1Object specifed by JSON parameters
  3438. * @name jsonToASN1HEX
  3439. * @memberOf KJUR.asn1.ASN1Util
  3440. * @function
  3441. * @param {Array} param JSON parameter to generate ASN1Object
  3442. * @return hexadecimal string of ASN1Object
  3443. * @since asn1 1.0.4
  3444. * @description
  3445. * As for ASN.1 object representation of JSON object,
  3446. * please see {@link newObject}.
  3447. * @example
  3448. * jsonToASN1HEX({'prnstr': 'aaa'});
  3449. */
  3450. this.jsonToASN1HEX = function(param) {
  3451. var asn1Obj = this.newObject(param);
  3452. return asn1Obj.getEncodedHex();
  3453. };
  3454. };
  3455. /**
  3456. * get dot noted oid number string from hexadecimal value of OID
  3457. * @name oidHexToInt
  3458. * @memberOf KJUR.asn1.ASN1Util
  3459. * @function
  3460. * @param {String} hex hexadecimal value of object identifier
  3461. * @return {String} dot noted string of object identifier
  3462. * @since jsrsasign 4.8.3 asn1 1.0.7
  3463. * @description
  3464. * This static method converts from hexadecimal string representation of
  3465. * ASN.1 value of object identifier to oid number string.
  3466. * @example
  3467. * KJUR.asn1.ASN1Util.oidHexToInt('550406') &rarr; "2.5.4.6"
  3468. */
  3469. KJUR.asn1.ASN1Util.oidHexToInt = function(hex) {
  3470. var s = "";
  3471. var i01 = parseInt(hex.substr(0, 2), 16);
  3472. var i0 = Math.floor(i01 / 40);
  3473. var i1 = i01 % 40;
  3474. var s = i0 + "." + i1;
  3475. var binbuf = "";
  3476. for (var i = 2; i < hex.length; i += 2) {
  3477. var value = parseInt(hex.substr(i, 2), 16);
  3478. var bin = ("00000000" + value.toString(2)).slice(- 8);
  3479. binbuf = binbuf + bin.substr(1, 7);
  3480. if (bin.substr(0, 1) == "0") {
  3481. var bi = new BigInteger(binbuf, 2);
  3482. s = s + "." + bi.toString(10);
  3483. binbuf = "";
  3484. }
  3485. }
  3486. return s;
  3487. };
  3488. /**
  3489. * get hexadecimal value of object identifier from dot noted oid value
  3490. * @name oidIntToHex
  3491. * @memberOf KJUR.asn1.ASN1Util
  3492. * @function
  3493. * @param {String} oidString dot noted string of object identifier
  3494. * @return {String} hexadecimal value of object identifier
  3495. * @since jsrsasign 4.8.3 asn1 1.0.7
  3496. * @description
  3497. * This static method converts from object identifier value string.
  3498. * to hexadecimal string representation of it.
  3499. * @example
  3500. * KJUR.asn1.ASN1Util.oidIntToHex("2.5.4.6") &rarr; "550406"
  3501. */
  3502. KJUR.asn1.ASN1Util.oidIntToHex = function(oidString) {
  3503. var itox = function(i) {
  3504. var h = i.toString(16);
  3505. if (h.length == 1) h = '0' + h;
  3506. return h;
  3507. };
  3508. var roidtox = function(roid) {
  3509. var h = '';
  3510. var bi = new BigInteger(roid, 10);
  3511. var b = bi.toString(2);
  3512. var padLen = 7 - b.length % 7;
  3513. if (padLen == 7) padLen = 0;
  3514. var bPad = '';
  3515. for (var i = 0; i < padLen; i++) bPad += '0';
  3516. b = bPad + b;
  3517. for (var i = 0; i < b.length - 1; i += 7) {
  3518. var b8 = b.substr(i, 7);
  3519. if (i != b.length - 7) b8 = '1' + b8;
  3520. h += itox(parseInt(b8, 2));
  3521. }
  3522. return h;
  3523. };
  3524. if (! oidString.match(/^[0-9.]+$/)) {
  3525. throw "malformed oid string: " + oidString;
  3526. }
  3527. var h = '';
  3528. var a = oidString.split('.');
  3529. var i0 = parseInt(a[0]) * 40 + parseInt(a[1]);
  3530. h += itox(i0);
  3531. a.splice(0, 2);
  3532. for (var i = 0; i < a.length; i++) {
  3533. h += roidtox(a[i]);
  3534. }
  3535. return h;
  3536. };
  3537. // ********************************************************************
  3538. // Abstract ASN.1 Classes
  3539. // ********************************************************************
  3540. // ********************************************************************
  3541. /**
  3542. * base class for ASN.1 DER encoder object
  3543. * @name KJUR.asn1.ASN1Object
  3544. * @class base class for ASN.1 DER encoder object
  3545. * @property {Boolean} isModified flag whether internal data was changed
  3546. * @property {String} hTLV hexadecimal string of ASN.1 TLV
  3547. * @property {String} hT hexadecimal string of ASN.1 TLV tag(T)
  3548. * @property {String} hL hexadecimal string of ASN.1 TLV length(L)
  3549. * @property {String} hV hexadecimal string of ASN.1 TLV value(V)
  3550. * @description
  3551. */
  3552. KJUR.asn1.ASN1Object = function() {
  3553. var hV = '';
  3554. /**
  3555. * get hexadecimal ASN.1 TLV length(L) bytes from TLV value(V)
  3556. * @name getLengthHexFromValue
  3557. * @memberOf KJUR.asn1.ASN1Object#
  3558. * @function
  3559. * @return {String} hexadecimal string of ASN.1 TLV length(L)
  3560. */
  3561. this.getLengthHexFromValue = function() {
  3562. if (typeof this.hV == "undefined" || this.hV == null) {
  3563. throw "this.hV is null or undefined.";
  3564. }
  3565. if (this.hV.length % 2 == 1) {
  3566. throw "value hex must be even length: n=" + hV.length + ",v=" + this.hV;
  3567. }
  3568. var n = this.hV.length / 2;
  3569. var hN = n.toString(16);
  3570. if (hN.length % 2 == 1) {
  3571. hN = "0" + hN;
  3572. }
  3573. if (n < 128) {
  3574. return hN;
  3575. } else {
  3576. var hNlen = hN.length / 2;
  3577. if (hNlen > 15) {
  3578. throw "ASN.1 length too long to represent by 8x: n = " + n.toString(16);
  3579. }
  3580. var head = 128 + hNlen;
  3581. return head.toString(16) + hN;
  3582. }
  3583. };
  3584. /**
  3585. * get hexadecimal string of ASN.1 TLV bytes
  3586. * @name getEncodedHex
  3587. * @memberOf KJUR.asn1.ASN1Object#
  3588. * @function
  3589. * @return {String} hexadecimal string of ASN.1 TLV
  3590. */
  3591. this.getEncodedHex = function() {
  3592. if (this.hTLV == null || this.isModified) {
  3593. this.hV = this.getFreshValueHex();
  3594. this.hL = this.getLengthHexFromValue();
  3595. this.hTLV = this.hT + this.hL + this.hV;
  3596. this.isModified = false;
  3597. //alert("first time: " + this.hTLV);
  3598. }
  3599. return this.hTLV;
  3600. };
  3601. /**
  3602. * get hexadecimal string of ASN.1 TLV value(V) bytes
  3603. * @name getValueHex
  3604. * @memberOf KJUR.asn1.ASN1Object#
  3605. * @function
  3606. * @return {String} hexadecimal string of ASN.1 TLV value(V) bytes
  3607. */
  3608. this.getValueHex = function() {
  3609. this.getEncodedHex();
  3610. return this.hV;
  3611. };
  3612. this.getFreshValueHex = function() {
  3613. return '';
  3614. };
  3615. };
  3616. // == BEGIN DERAbstractString ================================================
  3617. /**
  3618. * base class for ASN.1 DER string classes
  3619. * @name KJUR.asn1.DERAbstractString
  3620. * @class base class for ASN.1 DER string classes
  3621. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  3622. * @property {String} s internal string of value
  3623. * @extends KJUR.asn1.ASN1Object
  3624. * @description
  3625. * <br/>
  3626. * As for argument 'params' for constructor, you can specify one of
  3627. * following properties:
  3628. * <ul>
  3629. * <li>str - specify initial ASN.1 value(V) by a string</li>
  3630. * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  3631. * </ul>
  3632. * NOTE: 'params' can be omitted.
  3633. */
  3634. KJUR.asn1.DERAbstractString = function(params) {
  3635. KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
  3636. /**
  3637. * get string value of this string object
  3638. * @name getString
  3639. * @memberOf KJUR.asn1.DERAbstractString#
  3640. * @function
  3641. * @return {String} string value of this string object
  3642. */
  3643. this.getString = function() {
  3644. return this.s;
  3645. };
  3646. /**
  3647. * set value by a string
  3648. * @name setString
  3649. * @memberOf KJUR.asn1.DERAbstractString#
  3650. * @function
  3651. * @param {String} newS value by a string to set
  3652. */
  3653. this.setString = function(newS) {
  3654. this.hTLV = null;
  3655. this.isModified = true;
  3656. this.s = newS;
  3657. this.hV = stohex(this.s);
  3658. };
  3659. /**
  3660. * set value by a hexadecimal string
  3661. * @name setStringHex
  3662. * @memberOf KJUR.asn1.DERAbstractString#
  3663. * @function
  3664. * @param {String} newHexString value by a hexadecimal string to set
  3665. */
  3666. this.setStringHex = function(newHexString) {
  3667. this.hTLV = null;
  3668. this.isModified = true;
  3669. this.s = null;
  3670. this.hV = newHexString;
  3671. };
  3672. this.getFreshValueHex = function() {
  3673. return this.hV;
  3674. };
  3675. if (typeof params != "undefined") {
  3676. if (typeof params == "string") {
  3677. this.setString(params);
  3678. } else if (typeof params['str'] != "undefined") {
  3679. this.setString(params['str']);
  3680. } else if (typeof params['hex'] != "undefined") {
  3681. this.setStringHex(params['hex']);
  3682. }
  3683. }
  3684. };
  3685. YAHOO.lang.extend(KJUR.asn1.DERAbstractString, KJUR.asn1.ASN1Object);
  3686. // == END DERAbstractString ================================================
  3687. // == BEGIN DERAbstractTime ==================================================
  3688. /**
  3689. * base class for ASN.1 DER Generalized/UTCTime class
  3690. * @name KJUR.asn1.DERAbstractTime
  3691. * @class base class for ASN.1 DER Generalized/UTCTime class
  3692. * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'})
  3693. * @extends KJUR.asn1.ASN1Object
  3694. * @description
  3695. * @see KJUR.asn1.ASN1Object - superclass
  3696. */
  3697. KJUR.asn1.DERAbstractTime = function(params) {
  3698. KJUR.asn1.DERAbstractTime.superclass.constructor.call(this);
  3699. // --- PRIVATE METHODS --------------------
  3700. this.localDateToUTC = function(d) {
  3701. utc = d.getTime() + (d.getTimezoneOffset() * 60000);
  3702. var utcDate = new Date(utc);
  3703. return utcDate;
  3704. };
  3705. /*
  3706. * format date string by Data object
  3707. * @name formatDate
  3708. * @memberOf KJUR.asn1.AbstractTime;
  3709. * @param {Date} dateObject
  3710. * @param {string} type 'utc' or 'gen'
  3711. * @param {boolean} withMillis flag for with millisections or not
  3712. * @description
  3713. * 'withMillis' flag is supported from asn1 1.0.6.
  3714. */
  3715. this.formatDate = function(dateObject, type, withMillis) {
  3716. var pad = this.zeroPadding;
  3717. var d = this.localDateToUTC(dateObject);
  3718. var year = String(d.getFullYear());
  3719. if (type == 'utc') year = year.substr(2, 2);
  3720. var month = pad(String(d.getMonth() + 1), 2);
  3721. var day = pad(String(d.getDate()), 2);
  3722. var hour = pad(String(d.getHours()), 2);
  3723. var min = pad(String(d.getMinutes()), 2);
  3724. var sec = pad(String(d.getSeconds()), 2);
  3725. var s = year + month + day + hour + min + sec;
  3726. if (withMillis === true) {
  3727. var millis = d.getMilliseconds();
  3728. if (millis != 0) {
  3729. var sMillis = pad(String(millis), 3);
  3730. sMillis = sMillis.replace(/[0]+$/, "");
  3731. s = s + "." + sMillis;
  3732. }
  3733. }
  3734. return s + "Z";
  3735. };
  3736. this.zeroPadding = function(s, len) {
  3737. if (s.length >= len) return s;
  3738. return new Array(len - s.length + 1).join('0') + s;
  3739. };
  3740. // --- PUBLIC METHODS --------------------
  3741. /**
  3742. * get string value of this string object
  3743. * @name getString
  3744. * @memberOf KJUR.asn1.DERAbstractTime#
  3745. * @function
  3746. * @return {String} string value of this time object
  3747. */
  3748. this.getString = function() {
  3749. return this.s;
  3750. };
  3751. /**
  3752. * set value by a string
  3753. * @name setString
  3754. * @memberOf KJUR.asn1.DERAbstractTime#
  3755. * @function
  3756. * @param {String} newS value by a string to set such like "130430235959Z"
  3757. */
  3758. this.setString = function(newS) {
  3759. this.hTLV = null;
  3760. this.isModified = true;
  3761. this.s = newS;
  3762. this.hV = stohex(newS);
  3763. };
  3764. /**
  3765. * set value by a Date object
  3766. * @name setByDateValue
  3767. * @memberOf KJUR.asn1.DERAbstractTime#
  3768. * @function
  3769. * @param {Integer} year year of date (ex. 2013)
  3770. * @param {Integer} month month of date between 1 and 12 (ex. 12)
  3771. * @param {Integer} day day of month
  3772. * @param {Integer} hour hours of date
  3773. * @param {Integer} min minutes of date
  3774. * @param {Integer} sec seconds of date
  3775. */
  3776. this.setByDateValue = function(year, month, day, hour, min, sec) {
  3777. var dateObject = new Date(Date.UTC(year, month - 1, day, hour, min, sec, 0));
  3778. this.setByDate(dateObject);
  3779. };
  3780. this.getFreshValueHex = function() {
  3781. return this.hV;
  3782. };
  3783. };
  3784. YAHOO.lang.extend(KJUR.asn1.DERAbstractTime, KJUR.asn1.ASN1Object);
  3785. // == END DERAbstractTime ==================================================
  3786. // == BEGIN DERAbstractStructured ============================================
  3787. /**
  3788. * base class for ASN.1 DER structured class
  3789. * @name KJUR.asn1.DERAbstractStructured
  3790. * @class base class for ASN.1 DER structured class
  3791. * @property {Array} asn1Array internal array of ASN1Object
  3792. * @extends KJUR.asn1.ASN1Object
  3793. * @description
  3794. * @see KJUR.asn1.ASN1Object - superclass
  3795. */
  3796. KJUR.asn1.DERAbstractStructured = function(params) {
  3797. KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
  3798. /**
  3799. * set value by array of ASN1Object
  3800. * @name setByASN1ObjectArray
  3801. * @memberOf KJUR.asn1.DERAbstractStructured#
  3802. * @function
  3803. * @param {array} asn1ObjectArray array of ASN1Object to set
  3804. */
  3805. this.setByASN1ObjectArray = function(asn1ObjectArray) {
  3806. this.hTLV = null;
  3807. this.isModified = true;
  3808. this.asn1Array = asn1ObjectArray;
  3809. };
  3810. /**
  3811. * append an ASN1Object to internal array
  3812. * @name appendASN1Object
  3813. * @memberOf KJUR.asn1.DERAbstractStructured#
  3814. * @function
  3815. * @param {ASN1Object} asn1Object to add
  3816. */
  3817. this.appendASN1Object = function(asn1Object) {
  3818. this.hTLV = null;
  3819. this.isModified = true;
  3820. this.asn1Array.push(asn1Object);
  3821. };
  3822. this.asn1Array = new Array();
  3823. if (typeof params != "undefined") {
  3824. if (typeof params['array'] != "undefined") {
  3825. this.asn1Array = params['array'];
  3826. }
  3827. }
  3828. };
  3829. YAHOO.lang.extend(KJUR.asn1.DERAbstractStructured, KJUR.asn1.ASN1Object);
  3830. // ********************************************************************
  3831. // ASN.1 Object Classes
  3832. // ********************************************************************
  3833. // ********************************************************************
  3834. /**
  3835. * class for ASN.1 DER Boolean
  3836. * @name KJUR.asn1.DERBoolean
  3837. * @class class for ASN.1 DER Boolean
  3838. * @extends KJUR.asn1.ASN1Object
  3839. * @description
  3840. * @see KJUR.asn1.ASN1Object - superclass
  3841. */
  3842. KJUR.asn1.DERBoolean = function() {
  3843. KJUR.asn1.DERBoolean.superclass.constructor.call(this);
  3844. this.hT = "01";
  3845. this.hTLV = "0101ff";
  3846. };
  3847. YAHOO.lang.extend(KJUR.asn1.DERBoolean, KJUR.asn1.ASN1Object);
  3848. // ********************************************************************
  3849. /**
  3850. * class for ASN.1 DER Integer
  3851. * @name KJUR.asn1.DERInteger
  3852. * @class class for ASN.1 DER Integer
  3853. * @extends KJUR.asn1.ASN1Object
  3854. * @description
  3855. * <br/>
  3856. * As for argument 'params' for constructor, you can specify one of
  3857. * following properties:
  3858. * <ul>
  3859. * <li>int - specify initial ASN.1 value(V) by integer value</li>
  3860. * <li>bigint - specify initial ASN.1 value(V) by BigInteger object</li>
  3861. * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  3862. * </ul>
  3863. * NOTE: 'params' can be omitted.
  3864. */
  3865. KJUR.asn1.DERInteger = function(params) {
  3866. KJUR.asn1.DERInteger.superclass.constructor.call(this);
  3867. this.hT = "02";
  3868. /**
  3869. * set value by Tom Wu's BigInteger object
  3870. * @name setByBigInteger
  3871. * @memberOf KJUR.asn1.DERInteger#
  3872. * @function
  3873. * @param {BigInteger} bigIntegerValue to set
  3874. */
  3875. this.setByBigInteger = function(bigIntegerValue) {
  3876. this.hTLV = null;
  3877. this.isModified = true;
  3878. this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
  3879. };
  3880. /**
  3881. * set value by integer value
  3882. * @name setByInteger
  3883. * @memberOf KJUR.asn1.DERInteger
  3884. * @function
  3885. * @param {Integer} integer value to set
  3886. */
  3887. this.setByInteger = function(intValue) {
  3888. var bi = new BigInteger(String(intValue), 10);
  3889. this.setByBigInteger(bi);
  3890. };
  3891. /**
  3892. * set value by integer value
  3893. * @name setValueHex
  3894. * @memberOf KJUR.asn1.DERInteger#
  3895. * @function
  3896. * @param {String} hexadecimal string of integer value
  3897. * @description
  3898. * <br/>
  3899. * NOTE: Value shall be represented by minimum octet length of
  3900. * two's complement representation.
  3901. * @example
  3902. * new KJUR.asn1.DERInteger(123);
  3903. * new KJUR.asn1.DERInteger({'int': 123});
  3904. * new KJUR.asn1.DERInteger({'hex': '1fad'});
  3905. */
  3906. this.setValueHex = function(newHexString) {
  3907. this.hV = newHexString;
  3908. };
  3909. this.getFreshValueHex = function() {
  3910. return this.hV;
  3911. };
  3912. if (typeof params != "undefined") {
  3913. if (typeof params['bigint'] != "undefined") {
  3914. this.setByBigInteger(params['bigint']);
  3915. } else if (typeof params['int'] != "undefined") {
  3916. this.setByInteger(params['int']);
  3917. } else if (typeof params == "number") {
  3918. this.setByInteger(params);
  3919. } else if (typeof params['hex'] != "undefined") {
  3920. this.setValueHex(params['hex']);
  3921. }
  3922. }
  3923. };
  3924. YAHOO.lang.extend(KJUR.asn1.DERInteger, KJUR.asn1.ASN1Object);
  3925. // ********************************************************************
  3926. /**
  3927. * class for ASN.1 DER encoded BitString primitive
  3928. * @name KJUR.asn1.DERBitString
  3929. * @class class for ASN.1 DER encoded BitString primitive
  3930. * @extends KJUR.asn1.ASN1Object
  3931. * @description
  3932. * <br/>
  3933. * As for argument 'params' for constructor, you can specify one of
  3934. * following properties:
  3935. * <ul>
  3936. * <li>bin - specify binary string (ex. '10111')</li>
  3937. * <li>array - specify array of boolean (ex. [true,false,true,true])</li>
  3938. * <li>hex - specify hexadecimal string of ASN.1 value(V) including unused bits</li>
  3939. * <li>obj - specify {@link KJUR.asn1.ASN1Util.newObject}
  3940. * argument for "BitString encapsulates" structure.</li>
  3941. * </ul>
  3942. * NOTE1: 'params' can be omitted.<br/>
  3943. * NOTE2: 'obj' parameter have been supported since
  3944. * asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25).<br/>
  3945. * @example
  3946. * // default constructor
  3947. * o = new KJUR.asn1.DERBitString();
  3948. * // initialize with binary string
  3949. * o = new KJUR.asn1.DERBitString({bin: "1011"});
  3950. * // initialize with boolean array
  3951. * o = new KJUR.asn1.DERBitString({array: [true,false,true,true]});
  3952. * // initialize with hexadecimal string (04 is unused bits)
  3953. * o = new KJUR.asn1.DEROctetString({hex: "04bac0"});
  3954. * // initialize with ASN1Util.newObject argument for encapsulated
  3955. * o = new KJUR.asn1.DERBitString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}});
  3956. * // above generates a ASN.1 data like this:
  3957. * // BIT STRING, encapsulates {
  3958. * // SEQUENCE {
  3959. * // INTEGER 3
  3960. * // PrintableString 'aaa'
  3961. * // }
  3962. * // }
  3963. */
  3964. KJUR.asn1.DERBitString = function(params) {
  3965. if (params !== undefined && typeof params.obj !== "undefined") {
  3966. var o = KJUR.asn1.ASN1Util.newObject(params.obj);
  3967. params.hex = "00" + o.getEncodedHex();
  3968. }
  3969. KJUR.asn1.DERBitString.superclass.constructor.call(this);
  3970. this.hT = "03";
  3971. /**
  3972. * set ASN.1 value(V) by a hexadecimal string including unused bits
  3973. * @name setHexValueIncludingUnusedBits
  3974. * @memberOf KJUR.asn1.DERBitString#
  3975. * @function
  3976. * @param {String} newHexStringIncludingUnusedBits
  3977. */
  3978. this.setHexValueIncludingUnusedBits = function(newHexStringIncludingUnusedBits) {
  3979. this.hTLV = null;
  3980. this.isModified = true;
  3981. this.hV = newHexStringIncludingUnusedBits;
  3982. };
  3983. /**
  3984. * set ASN.1 value(V) by unused bit and hexadecimal string of value
  3985. * @name setUnusedBitsAndHexValue
  3986. * @memberOf KJUR.asn1.DERBitString#
  3987. * @function
  3988. * @param {Integer} unusedBits
  3989. * @param {String} hValue
  3990. */
  3991. this.setUnusedBitsAndHexValue = function(unusedBits, hValue) {
  3992. if (unusedBits < 0 || 7 < unusedBits) {
  3993. throw "unused bits shall be from 0 to 7: u = " + unusedBits;
  3994. }
  3995. var hUnusedBits = "0" + unusedBits;
  3996. this.hTLV = null;
  3997. this.isModified = true;
  3998. this.hV = hUnusedBits + hValue;
  3999. };
  4000. /**
  4001. * set ASN.1 DER BitString by binary string<br/>
  4002. * @name setByBinaryString
  4003. * @memberOf KJUR.asn1.DERBitString#
  4004. * @function
  4005. * @param {String} binaryString binary value string (i.e. '10111')
  4006. * @description
  4007. * Its unused bits will be calculated automatically by length of
  4008. * 'binaryValue'. <br/>
  4009. * NOTE: Trailing zeros '0' will be ignored.
  4010. * @example
  4011. * o = new KJUR.asn1.DERBitString();
  4012. * o.setByBooleanArray("01011");
  4013. */
  4014. this.setByBinaryString = function(binaryString) {
  4015. binaryString = binaryString.replace(/0+$/, '');
  4016. var unusedBits = 8 - binaryString.length % 8;
  4017. if (unusedBits == 8) unusedBits = 0;
  4018. for (var i = 0; i <= unusedBits; i++) {
  4019. binaryString += '0';
  4020. }
  4021. var h = '';
  4022. for (var i = 0; i < binaryString.length - 1; i += 8) {
  4023. var b = binaryString.substr(i, 8);
  4024. var x = parseInt(b, 2).toString(16);
  4025. if (x.length == 1) x = '0' + x;
  4026. h += x;
  4027. }
  4028. this.hTLV = null;
  4029. this.isModified = true;
  4030. this.hV = '0' + unusedBits + h;
  4031. };
  4032. /**
  4033. * set ASN.1 TLV value(V) by an array of boolean<br/>
  4034. * @name setByBooleanArray
  4035. * @memberOf KJUR.asn1.DERBitString#
  4036. * @function
  4037. * @param {array} booleanArray array of boolean (ex. [true, false, true])
  4038. * @description
  4039. * NOTE: Trailing falses will be ignored in the ASN.1 DER Object.
  4040. * @example
  4041. * o = new KJUR.asn1.DERBitString();
  4042. * o.setByBooleanArray([false, true, false, true, true]);
  4043. */
  4044. this.setByBooleanArray = function(booleanArray) {
  4045. var s = '';
  4046. for (var i = 0; i < booleanArray.length; i++) {
  4047. if (booleanArray[i] == true) {
  4048. s += '1';
  4049. } else {
  4050. s += '0';
  4051. }
  4052. }
  4053. this.setByBinaryString(s);
  4054. };
  4055. /**
  4056. * generate an array of falses with specified length<br/>
  4057. * @name newFalseArray
  4058. * @memberOf KJUR.asn1.DERBitString
  4059. * @function
  4060. * @param {Integer} nLength length of array to generate
  4061. * @return {array} array of boolean falses
  4062. * @description
  4063. * This static method may be useful to initialize boolean array.
  4064. * @example
  4065. * o = new KJUR.asn1.DERBitString();
  4066. * o.newFalseArray(3) &rarr; [false, false, false]
  4067. */
  4068. this.newFalseArray = function(nLength) {
  4069. var a = new Array(nLength);
  4070. for (var i = 0; i < nLength; i++) {
  4071. a[i] = false;
  4072. }
  4073. return a;
  4074. };
  4075. this.getFreshValueHex = function() {
  4076. return this.hV;
  4077. };
  4078. if (typeof params != "undefined") {
  4079. if (typeof params == "string" && params.toLowerCase().match(/^[0-9a-f]+$/)) {
  4080. this.setHexValueIncludingUnusedBits(params);
  4081. } else if (typeof params['hex'] != "undefined") {
  4082. this.setHexValueIncludingUnusedBits(params['hex']);
  4083. } else if (typeof params['bin'] != "undefined") {
  4084. this.setByBinaryString(params['bin']);
  4085. } else if (typeof params['array'] != "undefined") {
  4086. this.setByBooleanArray(params['array']);
  4087. }
  4088. }
  4089. };
  4090. YAHOO.lang.extend(KJUR.asn1.DERBitString, KJUR.asn1.ASN1Object);
  4091. // ********************************************************************
  4092. /**
  4093. * class for ASN.1 DER OctetString<br/>
  4094. * @name KJUR.asn1.DEROctetString
  4095. * @class class for ASN.1 DER OctetString
  4096. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  4097. * @extends KJUR.asn1.DERAbstractString
  4098. * @description
  4099. * This class provides ASN.1 OctetString simple type.<br/>
  4100. * Supported "params" attributes are:
  4101. * <ul>
  4102. * <li>str - to set a string as a value</li>
  4103. * <li>hex - to set a hexadecimal string as a value</li>
  4104. * <li>obj - to set a encapsulated ASN.1 value by JSON object
  4105. * which is defined in {@link KJUR.asn1.ASN1Util.newObject}</li>
  4106. * </ul>
  4107. * NOTE: A parameter 'obj' have been supported
  4108. * for "OCTET STRING, encapsulates" structure.
  4109. * since asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25).
  4110. * @see KJUR.asn1.DERAbstractString - superclass
  4111. * @example
  4112. * // default constructor
  4113. * o = new KJUR.asn1.DEROctetString();
  4114. * // initialize with string
  4115. * o = new KJUR.asn1.DEROctetString({str: "aaa"});
  4116. * // initialize with hexadecimal string
  4117. * o = new KJUR.asn1.DEROctetString({hex: "616161"});
  4118. * // initialize with ASN1Util.newObject argument
  4119. * o = new KJUR.asn1.DEROctetString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}});
  4120. * // above generates a ASN.1 data like this:
  4121. * // OCTET STRING, encapsulates {
  4122. * // SEQUENCE {
  4123. * // INTEGER 3
  4124. * // PrintableString 'aaa'
  4125. * // }
  4126. * // }
  4127. */
  4128. KJUR.asn1.DEROctetString = function(params) {
  4129. if (params !== undefined && typeof params.obj !== "undefined") {
  4130. var o = KJUR.asn1.ASN1Util.newObject(params.obj);
  4131. params.hex = o.getEncodedHex();
  4132. }
  4133. KJUR.asn1.DEROctetString.superclass.constructor.call(this, params);
  4134. this.hT = "04";
  4135. };
  4136. YAHOO.lang.extend(KJUR.asn1.DEROctetString, KJUR.asn1.DERAbstractString);
  4137. // ********************************************************************
  4138. /**
  4139. * class for ASN.1 DER Null
  4140. * @name KJUR.asn1.DERNull
  4141. * @class class for ASN.1 DER Null
  4142. * @extends KJUR.asn1.ASN1Object
  4143. * @description
  4144. * @see KJUR.asn1.ASN1Object - superclass
  4145. */
  4146. KJUR.asn1.DERNull = function() {
  4147. KJUR.asn1.DERNull.superclass.constructor.call(this);
  4148. this.hT = "05";
  4149. this.hTLV = "0500";
  4150. };
  4151. YAHOO.lang.extend(KJUR.asn1.DERNull, KJUR.asn1.ASN1Object);
  4152. // ********************************************************************
  4153. /**
  4154. * class for ASN.1 DER ObjectIdentifier
  4155. * @name KJUR.asn1.DERObjectIdentifier
  4156. * @class class for ASN.1 DER ObjectIdentifier
  4157. * @param {Array} params associative array of parameters (ex. {'oid': '2.5.4.5'})
  4158. * @extends KJUR.asn1.ASN1Object
  4159. * @description
  4160. * <br/>
  4161. * As for argument 'params' for constructor, you can specify one of
  4162. * following properties:
  4163. * <ul>
  4164. * <li>oid - specify initial ASN.1 value(V) by a oid string (ex. 2.5.4.13)</li>
  4165. * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  4166. * </ul>
  4167. * NOTE: 'params' can be omitted.
  4168. */
  4169. KJUR.asn1.DERObjectIdentifier = function(params) {
  4170. var itox = function(i) {
  4171. var h = i.toString(16);
  4172. if (h.length == 1) h = '0' + h;
  4173. return h;
  4174. };
  4175. var roidtox = function(roid) {
  4176. var h = '';
  4177. var bi = new BigInteger(roid, 10);
  4178. var b = bi.toString(2);
  4179. var padLen = 7 - b.length % 7;
  4180. if (padLen == 7) padLen = 0;
  4181. var bPad = '';
  4182. for (var i = 0; i < padLen; i++) bPad += '0';
  4183. b = bPad + b;
  4184. for (var i = 0; i < b.length - 1; i += 7) {
  4185. var b8 = b.substr(i, 7);
  4186. if (i != b.length - 7) b8 = '1' + b8;
  4187. h += itox(parseInt(b8, 2));
  4188. }
  4189. return h;
  4190. };
  4191. KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this);
  4192. this.hT = "06";
  4193. /**
  4194. * set value by a hexadecimal string
  4195. * @name setValueHex
  4196. * @memberOf KJUR.asn1.DERObjectIdentifier#
  4197. * @function
  4198. * @param {String} newHexString hexadecimal value of OID bytes
  4199. */
  4200. this.setValueHex = function(newHexString) {
  4201. this.hTLV = null;
  4202. this.isModified = true;
  4203. this.s = null;
  4204. this.hV = newHexString;
  4205. };
  4206. /**
  4207. * set value by a OID string<br/>
  4208. * @name setValueOidString
  4209. * @memberOf KJUR.asn1.DERObjectIdentifier#
  4210. * @function
  4211. * @param {String} oidString OID string (ex. 2.5.4.13)
  4212. * @example
  4213. * o = new KJUR.asn1.DERObjectIdentifier();
  4214. * o.setValueOidString("2.5.4.13");
  4215. */
  4216. this.setValueOidString = function(oidString) {
  4217. if (! oidString.match(/^[0-9.]+$/)) {
  4218. throw "malformed oid string: " + oidString;
  4219. }
  4220. var h = '';
  4221. var a = oidString.split('.');
  4222. var i0 = parseInt(a[0]) * 40 + parseInt(a[1]);
  4223. h += itox(i0);
  4224. a.splice(0, 2);
  4225. for (var i = 0; i < a.length; i++) {
  4226. h += roidtox(a[i]);
  4227. }
  4228. this.hTLV = null;
  4229. this.isModified = true;
  4230. this.s = null;
  4231. this.hV = h;
  4232. };
  4233. /**
  4234. * set value by a OID name
  4235. * @name setValueName
  4236. * @memberOf KJUR.asn1.DERObjectIdentifier#
  4237. * @function
  4238. * @param {String} oidName OID name (ex. 'serverAuth')
  4239. * @since 1.0.1
  4240. * @description
  4241. * OID name shall be defined in 'KJUR.asn1.x509.OID.name2oidList'.
  4242. * Otherwise raise error.
  4243. * @example
  4244. * o = new KJUR.asn1.DERObjectIdentifier();
  4245. * o.setValueName("serverAuth");
  4246. */
  4247. this.setValueName = function(oidName) {
  4248. var oid = KJUR.asn1.x509.OID.name2oid(oidName);
  4249. if (oid !== '') {
  4250. this.setValueOidString(oid);
  4251. } else {
  4252. throw "DERObjectIdentifier oidName undefined: " + oidName;
  4253. }
  4254. };
  4255. this.getFreshValueHex = function() {
  4256. return this.hV;
  4257. };
  4258. if (params !== undefined) {
  4259. if (typeof params === "string") {
  4260. if (params.match(/^[0-2].[0-9.]+$/)) {
  4261. this.setValueOidString(params);
  4262. } else {
  4263. this.setValueName(params);
  4264. }
  4265. } else if (params.oid !== undefined) {
  4266. this.setValueOidString(params.oid);
  4267. } else if (params.hex !== undefined) {
  4268. this.setValueHex(params.hex);
  4269. } else if (params.name !== undefined) {
  4270. this.setValueName(params.name);
  4271. }
  4272. }
  4273. };
  4274. YAHOO.lang.extend(KJUR.asn1.DERObjectIdentifier, KJUR.asn1.ASN1Object);
  4275. // ********************************************************************
  4276. /**
  4277. * class for ASN.1 DER Enumerated
  4278. * @name KJUR.asn1.DEREnumerated
  4279. * @class class for ASN.1 DER Enumerated
  4280. * @extends KJUR.asn1.ASN1Object
  4281. * @description
  4282. * <br/>
  4283. * As for argument 'params' for constructor, you can specify one of
  4284. * following properties:
  4285. * <ul>
  4286. * <li>int - specify initial ASN.1 value(V) by integer value</li>
  4287. * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  4288. * </ul>
  4289. * NOTE: 'params' can be omitted.
  4290. * @example
  4291. * new KJUR.asn1.DEREnumerated(123);
  4292. * new KJUR.asn1.DEREnumerated({int: 123});
  4293. * new KJUR.asn1.DEREnumerated({hex: '1fad'});
  4294. */
  4295. KJUR.asn1.DEREnumerated = function(params) {
  4296. KJUR.asn1.DEREnumerated.superclass.constructor.call(this);
  4297. this.hT = "0a";
  4298. /**
  4299. * set value by Tom Wu's BigInteger object
  4300. * @name setByBigInteger
  4301. * @memberOf KJUR.asn1.DEREnumerated#
  4302. * @function
  4303. * @param {BigInteger} bigIntegerValue to set
  4304. */
  4305. this.setByBigInteger = function(bigIntegerValue) {
  4306. this.hTLV = null;
  4307. this.isModified = true;
  4308. this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
  4309. };
  4310. /**
  4311. * set value by integer value
  4312. * @name setByInteger
  4313. * @memberOf KJUR.asn1.DEREnumerated#
  4314. * @function
  4315. * @param {Integer} integer value to set
  4316. */
  4317. this.setByInteger = function(intValue) {
  4318. var bi = new BigInteger(String(intValue), 10);
  4319. this.setByBigInteger(bi);
  4320. };
  4321. /**
  4322. * set value by integer value
  4323. * @name setValueHex
  4324. * @memberOf KJUR.asn1.DEREnumerated#
  4325. * @function
  4326. * @param {String} hexadecimal string of integer value
  4327. * @description
  4328. * <br/>
  4329. * NOTE: Value shall be represented by minimum octet length of
  4330. * two's complement representation.
  4331. */
  4332. this.setValueHex = function(newHexString) {
  4333. this.hV = newHexString;
  4334. };
  4335. this.getFreshValueHex = function() {
  4336. return this.hV;
  4337. };
  4338. if (typeof params != "undefined") {
  4339. if (typeof params['int'] != "undefined") {
  4340. this.setByInteger(params['int']);
  4341. } else if (typeof params == "number") {
  4342. this.setByInteger(params);
  4343. } else if (typeof params['hex'] != "undefined") {
  4344. this.setValueHex(params['hex']);
  4345. }
  4346. }
  4347. };
  4348. YAHOO.lang.extend(KJUR.asn1.DEREnumerated, KJUR.asn1.ASN1Object);
  4349. // ********************************************************************
  4350. /**
  4351. * class for ASN.1 DER UTF8String
  4352. * @name KJUR.asn1.DERUTF8String
  4353. * @class class for ASN.1 DER UTF8String
  4354. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  4355. * @extends KJUR.asn1.DERAbstractString
  4356. * @description
  4357. * @see KJUR.asn1.DERAbstractString - superclass
  4358. */
  4359. KJUR.asn1.DERUTF8String = function(params) {
  4360. KJUR.asn1.DERUTF8String.superclass.constructor.call(this, params);
  4361. this.hT = "0c";
  4362. };
  4363. YAHOO.lang.extend(KJUR.asn1.DERUTF8String, KJUR.asn1.DERAbstractString);
  4364. // ********************************************************************
  4365. /**
  4366. * class for ASN.1 DER NumericString
  4367. * @name KJUR.asn1.DERNumericString
  4368. * @class class for ASN.1 DER NumericString
  4369. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  4370. * @extends KJUR.asn1.DERAbstractString
  4371. * @description
  4372. * @see KJUR.asn1.DERAbstractString - superclass
  4373. */
  4374. KJUR.asn1.DERNumericString = function(params) {
  4375. KJUR.asn1.DERNumericString.superclass.constructor.call(this, params);
  4376. this.hT = "12";
  4377. };
  4378. YAHOO.lang.extend(KJUR.asn1.DERNumericString, KJUR.asn1.DERAbstractString);
  4379. // ********************************************************************
  4380. /**
  4381. * class for ASN.1 DER PrintableString
  4382. * @name KJUR.asn1.DERPrintableString
  4383. * @class class for ASN.1 DER PrintableString
  4384. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  4385. * @extends KJUR.asn1.DERAbstractString
  4386. * @description
  4387. * @see KJUR.asn1.DERAbstractString - superclass
  4388. */
  4389. KJUR.asn1.DERPrintableString = function(params) {
  4390. KJUR.asn1.DERPrintableString.superclass.constructor.call(this, params);
  4391. this.hT = "13";
  4392. };
  4393. YAHOO.lang.extend(KJUR.asn1.DERPrintableString, KJUR.asn1.DERAbstractString);
  4394. // ********************************************************************
  4395. /**
  4396. * class for ASN.1 DER TeletexString
  4397. * @name KJUR.asn1.DERTeletexString
  4398. * @class class for ASN.1 DER TeletexString
  4399. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  4400. * @extends KJUR.asn1.DERAbstractString
  4401. * @description
  4402. * @see KJUR.asn1.DERAbstractString - superclass
  4403. */
  4404. KJUR.asn1.DERTeletexString = function(params) {
  4405. KJUR.asn1.DERTeletexString.superclass.constructor.call(this, params);
  4406. this.hT = "14";
  4407. };
  4408. YAHOO.lang.extend(KJUR.asn1.DERTeletexString, KJUR.asn1.DERAbstractString);
  4409. // ********************************************************************
  4410. /**
  4411. * class for ASN.1 DER IA5String
  4412. * @name KJUR.asn1.DERIA5String
  4413. * @class class for ASN.1 DER IA5String
  4414. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  4415. * @extends KJUR.asn1.DERAbstractString
  4416. * @description
  4417. * @see KJUR.asn1.DERAbstractString - superclass
  4418. */
  4419. KJUR.asn1.DERIA5String = function(params) {
  4420. KJUR.asn1.DERIA5String.superclass.constructor.call(this, params);
  4421. this.hT = "16";
  4422. };
  4423. YAHOO.lang.extend(KJUR.asn1.DERIA5String, KJUR.asn1.DERAbstractString);
  4424. // ********************************************************************
  4425. /**
  4426. * class for ASN.1 DER UTCTime
  4427. * @name KJUR.asn1.DERUTCTime
  4428. * @class class for ASN.1 DER UTCTime
  4429. * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'})
  4430. * @extends KJUR.asn1.DERAbstractTime
  4431. * @description
  4432. * <br/>
  4433. * As for argument 'params' for constructor, you can specify one of
  4434. * following properties:
  4435. * <ul>
  4436. * <li>str - specify initial ASN.1 value(V) by a string (ex.'130430235959Z')</li>
  4437. * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  4438. * <li>date - specify Date object.</li>
  4439. * </ul>
  4440. * NOTE: 'params' can be omitted.
  4441. * <h4>EXAMPLES</h4>
  4442. * @example
  4443. * d1 = new KJUR.asn1.DERUTCTime();
  4444. * d1.setString('130430125959Z');
  4445. *
  4446. * d2 = new KJUR.asn1.DERUTCTime({'str': '130430125959Z'});
  4447. * d3 = new KJUR.asn1.DERUTCTime({'date': new Date(Date.UTC(2015, 0, 31, 0, 0, 0, 0))});
  4448. * d4 = new KJUR.asn1.DERUTCTime('130430125959Z');
  4449. */
  4450. KJUR.asn1.DERUTCTime = function(params) {
  4451. KJUR.asn1.DERUTCTime.superclass.constructor.call(this, params);
  4452. this.hT = "17";
  4453. /**
  4454. * set value by a Date object<br/>
  4455. * @name setByDate
  4456. * @memberOf KJUR.asn1.DERUTCTime#
  4457. * @function
  4458. * @param {Date} dateObject Date object to set ASN.1 value(V)
  4459. * @example
  4460. * o = new KJUR.asn1.DERUTCTime();
  4461. * o.setByDate(new Date("2016/12/31"));
  4462. */
  4463. this.setByDate = function(dateObject) {
  4464. this.hTLV = null;
  4465. this.isModified = true;
  4466. this.date = dateObject;
  4467. this.s = this.formatDate(this.date, 'utc');
  4468. this.hV = stohex(this.s);
  4469. };
  4470. this.getFreshValueHex = function() {
  4471. if (typeof this.date == "undefined" && typeof this.s == "undefined") {
  4472. this.date = new Date();
  4473. this.s = this.formatDate(this.date, 'utc');
  4474. this.hV = stohex(this.s);
  4475. }
  4476. return this.hV;
  4477. };
  4478. if (params !== undefined) {
  4479. if (params.str !== undefined) {
  4480. this.setString(params.str);
  4481. } else if (typeof params == "string" && params.match(/^[0-9]{12}Z$/)) {
  4482. this.setString(params);
  4483. } else if (params.hex !== undefined) {
  4484. this.setStringHex(params.hex);
  4485. } else if (params.date !== undefined) {
  4486. this.setByDate(params.date);
  4487. }
  4488. }
  4489. };
  4490. YAHOO.lang.extend(KJUR.asn1.DERUTCTime, KJUR.asn1.DERAbstractTime);
  4491. // ********************************************************************
  4492. /**
  4493. * class for ASN.1 DER GeneralizedTime
  4494. * @name KJUR.asn1.DERGeneralizedTime
  4495. * @class class for ASN.1 DER GeneralizedTime
  4496. * @param {Array} params associative array of parameters (ex. {'str': '20130430235959Z'})
  4497. * @property {Boolean} withMillis flag to show milliseconds or not
  4498. * @extends KJUR.asn1.DERAbstractTime
  4499. * @description
  4500. * <br/>
  4501. * As for argument 'params' for constructor, you can specify one of
  4502. * following properties:
  4503. * <ul>
  4504. * <li>str - specify initial ASN.1 value(V) by a string (ex.'20130430235959Z')</li>
  4505. * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  4506. * <li>date - specify Date object.</li>
  4507. * <li>millis - specify flag to show milliseconds (from 1.0.6)</li>
  4508. * </ul>
  4509. * NOTE1: 'params' can be omitted.
  4510. * NOTE2: 'withMillis' property is supported from asn1 1.0.6.
  4511. */
  4512. KJUR.asn1.DERGeneralizedTime = function(params) {
  4513. KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this, params);
  4514. this.hT = "18";
  4515. this.withMillis = false;
  4516. /**
  4517. * set value by a Date object
  4518. * @name setByDate
  4519. * @memberOf KJUR.asn1.DERGeneralizedTime#
  4520. * @function
  4521. * @param {Date} dateObject Date object to set ASN.1 value(V)
  4522. * @example
  4523. * When you specify UTC time, use 'Date.UTC' method like this:<br/>
  4524. * o1 = new DERUTCTime();
  4525. * o1.setByDate(date);
  4526. *
  4527. * date = new Date(Date.UTC(2015, 0, 31, 23, 59, 59, 0)); #2015JAN31 23:59:59
  4528. */
  4529. this.setByDate = function(dateObject) {
  4530. this.hTLV = null;
  4531. this.isModified = true;
  4532. this.date = dateObject;
  4533. this.s = this.formatDate(this.date, 'gen', this.withMillis);
  4534. this.hV = stohex(this.s);
  4535. };
  4536. this.getFreshValueHex = function() {
  4537. if (this.date === undefined && this.s === undefined) {
  4538. this.date = new Date();
  4539. this.s = this.formatDate(this.date, 'gen', this.withMillis);
  4540. this.hV = stohex(this.s);
  4541. }
  4542. return this.hV;
  4543. };
  4544. if (params !== undefined) {
  4545. if (params.str !== undefined) {
  4546. this.setString(params.str);
  4547. } else if (typeof params == "string" && params.match(/^[0-9]{14}Z$/)) {
  4548. this.setString(params);
  4549. } else if (params.hex !== undefined) {
  4550. this.setStringHex(params.hex);
  4551. } else if (params.date !== undefined) {
  4552. this.setByDate(params.date);
  4553. }
  4554. if (params.millis === true) {
  4555. this.withMillis = true;
  4556. }
  4557. }
  4558. };
  4559. YAHOO.lang.extend(KJUR.asn1.DERGeneralizedTime, KJUR.asn1.DERAbstractTime);
  4560. // ********************************************************************
  4561. /**
  4562. * class for ASN.1 DER Sequence
  4563. * @name KJUR.asn1.DERSequence
  4564. * @class class for ASN.1 DER Sequence
  4565. * @extends KJUR.asn1.DERAbstractStructured
  4566. * @description
  4567. * <br/>
  4568. * As for argument 'params' for constructor, you can specify one of
  4569. * following properties:
  4570. * <ul>
  4571. * <li>array - specify array of ASN1Object to set elements of content</li>
  4572. * </ul>
  4573. * NOTE: 'params' can be omitted.
  4574. */
  4575. KJUR.asn1.DERSequence = function(params) {
  4576. KJUR.asn1.DERSequence.superclass.constructor.call(this, params);
  4577. this.hT = "30";
  4578. this.getFreshValueHex = function() {
  4579. var h = '';
  4580. for (var i = 0; i < this.asn1Array.length; i++) {
  4581. var asn1Obj = this.asn1Array[i];
  4582. h += asn1Obj.getEncodedHex();
  4583. }
  4584. this.hV = h;
  4585. return this.hV;
  4586. };
  4587. };
  4588. YAHOO.lang.extend(KJUR.asn1.DERSequence, KJUR.asn1.DERAbstractStructured);
  4589. // ********************************************************************
  4590. /**
  4591. * class for ASN.1 DER Set
  4592. * @name KJUR.asn1.DERSet
  4593. * @class class for ASN.1 DER Set
  4594. * @extends KJUR.asn1.DERAbstractStructured
  4595. * @description
  4596. * <br/>
  4597. * As for argument 'params' for constructor, you can specify one of
  4598. * following properties:
  4599. * <ul>
  4600. * <li>array - specify array of ASN1Object to set elements of content</li>
  4601. * <li>sortflag - flag for sort (default: true). ASN.1 BER is not sorted in 'SET OF'.</li>
  4602. * </ul>
  4603. * NOTE1: 'params' can be omitted.<br/>
  4604. * NOTE2: sortflag is supported since 1.0.5.
  4605. */
  4606. KJUR.asn1.DERSet = function(params) {
  4607. KJUR.asn1.DERSet.superclass.constructor.call(this, params);
  4608. this.hT = "31";
  4609. this.sortFlag = true; // item shall be sorted only in ASN.1 DER
  4610. this.getFreshValueHex = function() {
  4611. var a = new Array();
  4612. for (var i = 0; i < this.asn1Array.length; i++) {
  4613. var asn1Obj = this.asn1Array[i];
  4614. a.push(asn1Obj.getEncodedHex());
  4615. }
  4616. if (this.sortFlag == true) a.sort();
  4617. this.hV = a.join('');
  4618. return this.hV;
  4619. };
  4620. if (typeof params != "undefined") {
  4621. if (typeof params.sortflag != "undefined" &&
  4622. params.sortflag == false)
  4623. this.sortFlag = false;
  4624. }
  4625. };
  4626. YAHOO.lang.extend(KJUR.asn1.DERSet, KJUR.asn1.DERAbstractStructured);
  4627. // ********************************************************************
  4628. /**
  4629. * class for ASN.1 DER TaggedObject
  4630. * @name KJUR.asn1.DERTaggedObject
  4631. * @class class for ASN.1 DER TaggedObject
  4632. * @extends KJUR.asn1.ASN1Object
  4633. * @description
  4634. * <br/>
  4635. * Parameter 'tagNoNex' is ASN.1 tag(T) value for this object.
  4636. * For example, if you find '[1]' tag in a ASN.1 dump,
  4637. * 'tagNoHex' will be 'a1'.
  4638. * <br/>
  4639. * As for optional argument 'params' for constructor, you can specify *ANY* of
  4640. * following properties:
  4641. * <ul>
  4642. * <li>explicit - specify true if this is explicit tag otherwise false
  4643. * (default is 'true').</li>
  4644. * <li>tag - specify tag (default is 'a0' which means [0])</li>
  4645. * <li>obj - specify ASN1Object which is tagged</li>
  4646. * </ul>
  4647. * @example
  4648. * d1 = new KJUR.asn1.DERUTF8String({'str':'a'});
  4649. * d2 = new KJUR.asn1.DERTaggedObject({'obj': d1});
  4650. * hex = d2.getEncodedHex();
  4651. */
  4652. KJUR.asn1.DERTaggedObject = function(params) {
  4653. KJUR.asn1.DERTaggedObject.superclass.constructor.call(this);
  4654. this.hT = "a0";
  4655. this.hV = '';
  4656. this.isExplicit = true;
  4657. this.asn1Object = null;
  4658. /**
  4659. * set value by an ASN1Object
  4660. * @name setString
  4661. * @memberOf KJUR.asn1.DERTaggedObject#
  4662. * @function
  4663. * @param {Boolean} isExplicitFlag flag for explicit/implicit tag
  4664. * @param {Integer} tagNoHex hexadecimal string of ASN.1 tag
  4665. * @param {ASN1Object} asn1Object ASN.1 to encapsulate
  4666. */
  4667. this.setASN1Object = function(isExplicitFlag, tagNoHex, asn1Object) {
  4668. this.hT = tagNoHex;
  4669. this.isExplicit = isExplicitFlag;
  4670. this.asn1Object = asn1Object;
  4671. if (this.isExplicit) {
  4672. this.hV = this.asn1Object.getEncodedHex();
  4673. this.hTLV = null;
  4674. this.isModified = true;
  4675. } else {
  4676. this.hV = null;
  4677. this.hTLV = asn1Object.getEncodedHex();
  4678. this.hTLV = this.hTLV.replace(/^../, tagNoHex);
  4679. this.isModified = false;
  4680. }
  4681. };
  4682. this.getFreshValueHex = function() {
  4683. return this.hV;
  4684. };
  4685. if (typeof params != "undefined") {
  4686. if (typeof params['tag'] != "undefined") {
  4687. this.hT = params['tag'];
  4688. }
  4689. if (typeof params['explicit'] != "undefined") {
  4690. this.isExplicit = params['explicit'];
  4691. }
  4692. if (typeof params['obj'] != "undefined") {
  4693. this.asn1Object = params['obj'];
  4694. this.setASN1Object(this.isExplicit, this.hT, this.asn1Object);
  4695. }
  4696. }
  4697. };
  4698. YAHOO.lang.extend(KJUR.asn1.DERTaggedObject, KJUR.asn1.ASN1Object);
  4699. /**
  4700. * Create a new JSEncryptRSAKey that extends Tom Wu's RSA key object.
  4701. * This object is just a decorator for parsing the key parameter
  4702. * @param {string|Object} key - The key in string format, or an object containing
  4703. * the parameters needed to build a RSAKey object.
  4704. * @constructor
  4705. */
  4706. var JSEncryptRSAKey = /** @class */ (function (_super) {
  4707. __extends(JSEncryptRSAKey, _super);
  4708. function JSEncryptRSAKey(key) {
  4709. var _this = _super.call(this) || this;
  4710. // Call the super constructor.
  4711. // RSAKey.call(this);
  4712. // If a key key was provided.
  4713. if (key) {
  4714. // If this is a string...
  4715. if (typeof key === "string") {
  4716. _this.parseKey(key);
  4717. }
  4718. else if (JSEncryptRSAKey.hasPrivateKeyProperty(key) ||
  4719. JSEncryptRSAKey.hasPublicKeyProperty(key)) {
  4720. // Set the values for the key.
  4721. _this.parsePropertiesFrom(key);
  4722. }
  4723. }
  4724. return _this;
  4725. }
  4726. /**
  4727. * Method to parse a pem encoded string containing both a public or private key.
  4728. * The method will translate the pem encoded string in a der encoded string and
  4729. * will parse private key and public key parameters. This method accepts public key
  4730. * in the rsaencryption pkcs #1 format (oid: 1.2.840.113549.1.1.1).
  4731. *
  4732. * @todo Check how many rsa formats use the same format of pkcs #1.
  4733. *
  4734. * The format is defined as:
  4735. * PublicKeyInfo ::= SEQUENCE {
  4736. * algorithm AlgorithmIdentifier,
  4737. * PublicKey BIT STRING
  4738. * }
  4739. * Where AlgorithmIdentifier is:
  4740. * AlgorithmIdentifier ::= SEQUENCE {
  4741. * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm
  4742. * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1)
  4743. * }
  4744. * and PublicKey is a SEQUENCE encapsulated in a BIT STRING
  4745. * RSAPublicKey ::= SEQUENCE {
  4746. * modulus INTEGER, -- n
  4747. * publicExponent INTEGER -- e
  4748. * }
  4749. * it's possible to examine the structure of the keys obtained from openssl using
  4750. * an asn.1 dumper as the one used here to parse the components: http://lapo.it/asn1js/
  4751. * @argument {string} pem the pem encoded string, can include the BEGIN/END header/footer
  4752. * @private
  4753. */
  4754. JSEncryptRSAKey.prototype.parseKey = function (pem) {
  4755. try {
  4756. var modulus = 0;
  4757. var public_exponent = 0;
  4758. var reHex = /^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/;
  4759. var der = reHex.test(pem) ? Hex.decode(pem) : Base64.unarmor(pem);
  4760. var asn1 = ASN1.decode(der);
  4761. // Fixes a bug with OpenSSL 1.0+ private keys
  4762. if (asn1.sub.length === 3) {
  4763. asn1 = asn1.sub[2].sub[0];
  4764. }
  4765. if (asn1.sub.length === 9) {
  4766. // Parse the private key.
  4767. modulus = asn1.sub[1].getHexStringValue(); // bigint
  4768. this.n = parseBigInt(modulus, 16);
  4769. public_exponent = asn1.sub[2].getHexStringValue(); // int
  4770. this.e = parseInt(public_exponent, 16);
  4771. var private_exponent = asn1.sub[3].getHexStringValue(); // bigint
  4772. this.d = parseBigInt(private_exponent, 16);
  4773. var prime1 = asn1.sub[4].getHexStringValue(); // bigint
  4774. this.p = parseBigInt(prime1, 16);
  4775. var prime2 = asn1.sub[5].getHexStringValue(); // bigint
  4776. this.q = parseBigInt(prime2, 16);
  4777. var exponent1 = asn1.sub[6].getHexStringValue(); // bigint
  4778. this.dmp1 = parseBigInt(exponent1, 16);
  4779. var exponent2 = asn1.sub[7].getHexStringValue(); // bigint
  4780. this.dmq1 = parseBigInt(exponent2, 16);
  4781. var coefficient = asn1.sub[8].getHexStringValue(); // bigint
  4782. this.coeff = parseBigInt(coefficient, 16);
  4783. }
  4784. else if (asn1.sub.length === 2) {
  4785. // Parse the public key.
  4786. var bit_string = asn1.sub[1];
  4787. var sequence = bit_string.sub[0];
  4788. modulus = sequence.sub[0].getHexStringValue();
  4789. this.n = parseBigInt(modulus, 16);
  4790. public_exponent = sequence.sub[1].getHexStringValue();
  4791. this.e = parseInt(public_exponent, 16);
  4792. }
  4793. else {
  4794. return false;
  4795. }
  4796. return true;
  4797. }
  4798. catch (ex) {
  4799. return false;
  4800. }
  4801. };
  4802. /**
  4803. * Translate rsa parameters in a hex encoded string representing the rsa key.
  4804. *
  4805. * The translation follow the ASN.1 notation :
  4806. * RSAPrivateKey ::= SEQUENCE {
  4807. * version Version,
  4808. * modulus INTEGER, -- n
  4809. * publicExponent INTEGER, -- e
  4810. * privateExponent INTEGER, -- d
  4811. * prime1 INTEGER, -- p
  4812. * prime2 INTEGER, -- q
  4813. * exponent1 INTEGER, -- d mod (p1)
  4814. * exponent2 INTEGER, -- d mod (q-1)
  4815. * coefficient INTEGER, -- (inverse of q) mod p
  4816. * }
  4817. * @returns {string} DER Encoded String representing the rsa private key
  4818. * @private
  4819. */
  4820. JSEncryptRSAKey.prototype.getPrivateBaseKey = function () {
  4821. var options = {
  4822. array: [
  4823. new KJUR.asn1.DERInteger({ int: 0 }),
  4824. new KJUR.asn1.DERInteger({ bigint: this.n }),
  4825. new KJUR.asn1.DERInteger({ int: this.e }),
  4826. new KJUR.asn1.DERInteger({ bigint: this.d }),
  4827. new KJUR.asn1.DERInteger({ bigint: this.p }),
  4828. new KJUR.asn1.DERInteger({ bigint: this.q }),
  4829. new KJUR.asn1.DERInteger({ bigint: this.dmp1 }),
  4830. new KJUR.asn1.DERInteger({ bigint: this.dmq1 }),
  4831. new KJUR.asn1.DERInteger({ bigint: this.coeff })
  4832. ]
  4833. };
  4834. var seq = new KJUR.asn1.DERSequence(options);
  4835. return seq.getEncodedHex();
  4836. };
  4837. /**
  4838. * base64 (pem) encoded version of the DER encoded representation
  4839. * @returns {string} pem encoded representation without header and footer
  4840. * @public
  4841. */
  4842. JSEncryptRSAKey.prototype.getPrivateBaseKeyB64 = function () {
  4843. return hex2b64(this.getPrivateBaseKey());
  4844. };
  4845. /**
  4846. * Translate rsa parameters in a hex encoded string representing the rsa public key.
  4847. * The representation follow the ASN.1 notation :
  4848. * PublicKeyInfo ::= SEQUENCE {
  4849. * algorithm AlgorithmIdentifier,
  4850. * PublicKey BIT STRING
  4851. * }
  4852. * Where AlgorithmIdentifier is:
  4853. * AlgorithmIdentifier ::= SEQUENCE {
  4854. * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm
  4855. * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1)
  4856. * }
  4857. * and PublicKey is a SEQUENCE encapsulated in a BIT STRING
  4858. * RSAPublicKey ::= SEQUENCE {
  4859. * modulus INTEGER, -- n
  4860. * publicExponent INTEGER -- e
  4861. * }
  4862. * @returns {string} DER Encoded String representing the rsa public key
  4863. * @private
  4864. */
  4865. JSEncryptRSAKey.prototype.getPublicBaseKey = function () {
  4866. var first_sequence = new KJUR.asn1.DERSequence({
  4867. array: [
  4868. new KJUR.asn1.DERObjectIdentifier({ oid: "1.2.840.113549.1.1.1" }),
  4869. new KJUR.asn1.DERNull()
  4870. ]
  4871. });
  4872. var second_sequence = new KJUR.asn1.DERSequence({
  4873. array: [
  4874. new KJUR.asn1.DERInteger({ bigint: this.n }),
  4875. new KJUR.asn1.DERInteger({ int: this.e })
  4876. ]
  4877. });
  4878. var bit_string = new KJUR.asn1.DERBitString({
  4879. hex: "00" + second_sequence.getEncodedHex()
  4880. });
  4881. var seq = new KJUR.asn1.DERSequence({
  4882. array: [
  4883. first_sequence,
  4884. bit_string
  4885. ]
  4886. });
  4887. return seq.getEncodedHex();
  4888. };
  4889. /**
  4890. * base64 (pem) encoded version of the DER encoded representation
  4891. * @returns {string} pem encoded representation without header and footer
  4892. * @public
  4893. */
  4894. JSEncryptRSAKey.prototype.getPublicBaseKeyB64 = function () {
  4895. return hex2b64(this.getPublicBaseKey());
  4896. };
  4897. /**
  4898. * wrap the string in block of width chars. The default value for rsa keys is 64
  4899. * characters.
  4900. * @param {string} str the pem encoded string without header and footer
  4901. * @param {Number} [width=64] - the length the string has to be wrapped at
  4902. * @returns {string}
  4903. * @private
  4904. */
  4905. JSEncryptRSAKey.wordwrap = function (str, width) {
  4906. width = width || 64;
  4907. if (!str) {
  4908. return str;
  4909. }
  4910. var regex = "(.{1," + width + "})( +|$\n?)|(.{1," + width + "})";
  4911. return str.match(RegExp(regex, "g")).join("\n");
  4912. };
  4913. /**
  4914. * Retrieve the pem encoded private key
  4915. * @returns {string} the pem encoded private key with header/footer
  4916. * @public
  4917. */
  4918. JSEncryptRSAKey.prototype.getPrivateKey = function () {
  4919. var key = "-----BEGIN RSA PRIVATE KEY-----\n";
  4920. key += JSEncryptRSAKey.wordwrap(this.getPrivateBaseKeyB64()) + "\n";
  4921. key += "-----END RSA PRIVATE KEY-----";
  4922. return key;
  4923. };
  4924. /**
  4925. * Retrieve the pem encoded public key
  4926. * @returns {string} the pem encoded public key with header/footer
  4927. * @public
  4928. */
  4929. JSEncryptRSAKey.prototype.getPublicKey = function () {
  4930. var key = "-----BEGIN PUBLIC KEY-----\n";
  4931. key += JSEncryptRSAKey.wordwrap(this.getPublicBaseKeyB64()) + "\n";
  4932. key += "-----END PUBLIC KEY-----";
  4933. return key;
  4934. };
  4935. /**
  4936. * Check if the object contains the necessary parameters to populate the rsa modulus
  4937. * and public exponent parameters.
  4938. * @param {Object} [obj={}] - An object that may contain the two public key
  4939. * parameters
  4940. * @returns {boolean} true if the object contains both the modulus and the public exponent
  4941. * properties (n and e)
  4942. * @todo check for types of n and e. N should be a parseable bigInt object, E should
  4943. * be a parseable integer number
  4944. * @private
  4945. */
  4946. JSEncryptRSAKey.hasPublicKeyProperty = function (obj) {
  4947. obj = obj || {};
  4948. return (obj.hasOwnProperty("n") &&
  4949. obj.hasOwnProperty("e"));
  4950. };
  4951. /**
  4952. * Check if the object contains ALL the parameters of an RSA key.
  4953. * @param {Object} [obj={}] - An object that may contain nine rsa key
  4954. * parameters
  4955. * @returns {boolean} true if the object contains all the parameters needed
  4956. * @todo check for types of the parameters all the parameters but the public exponent
  4957. * should be parseable bigint objects, the public exponent should be a parseable integer number
  4958. * @private
  4959. */
  4960. JSEncryptRSAKey.hasPrivateKeyProperty = function (obj) {
  4961. obj = obj || {};
  4962. return (obj.hasOwnProperty("n") &&
  4963. obj.hasOwnProperty("e") &&
  4964. obj.hasOwnProperty("d") &&
  4965. obj.hasOwnProperty("p") &&
  4966. obj.hasOwnProperty("q") &&
  4967. obj.hasOwnProperty("dmp1") &&
  4968. obj.hasOwnProperty("dmq1") &&
  4969. obj.hasOwnProperty("coeff"));
  4970. };
  4971. /**
  4972. * Parse the properties of obj in the current rsa object. Obj should AT LEAST
  4973. * include the modulus and public exponent (n, e) parameters.
  4974. * @param {Object} obj - the object containing rsa parameters
  4975. * @private
  4976. */
  4977. JSEncryptRSAKey.prototype.parsePropertiesFrom = function (obj) {
  4978. this.n = obj.n;
  4979. this.e = obj.e;
  4980. if (obj.hasOwnProperty("d")) {
  4981. this.d = obj.d;
  4982. this.p = obj.p;
  4983. this.q = obj.q;
  4984. this.dmp1 = obj.dmp1;
  4985. this.dmq1 = obj.dmq1;
  4986. this.coeff = obj.coeff;
  4987. }
  4988. };
  4989. return JSEncryptRSAKey;
  4990. }(RSAKey));
  4991. /**
  4992. *
  4993. * @param {Object} [options = {}] - An object to customize JSEncrypt behaviour
  4994. * possible parameters are:
  4995. * - default_key_size {number} default: 1024 the key size in bit
  4996. * - default_public_exponent {string} default: '010001' the hexadecimal representation of the public exponent
  4997. * - log {boolean} default: false whether log warn/error or not
  4998. * @constructor
  4999. */
  5000. var JSEncrypt = /** @class */ (function () {
  5001. function JSEncrypt(options) {
  5002. options = options || {};
  5003. this.default_key_size = parseInt(options.default_key_size, 10) || 1024;
  5004. this.default_public_exponent = options.default_public_exponent || "010001"; // 65537 default openssl public exponent for rsa key type
  5005. this.log = options.log || false;
  5006. // The private and public key.
  5007. this.key = null;
  5008. }
  5009. /**
  5010. * Method to set the rsa key parameter (one method is enough to set both the public
  5011. * and the private key, since the private key contains the public key paramenters)
  5012. * Log a warning if logs are enabled
  5013. * @param {Object|string} key the pem encoded string or an object (with or without header/footer)
  5014. * @public
  5015. */
  5016. JSEncrypt.prototype.setKey = function (key) {
  5017. if (this.log && this.key) {
  5018. console.warn("A key was already set, overriding existing.");
  5019. }
  5020. this.key = new JSEncryptRSAKey(key);
  5021. };
  5022. /**
  5023. * Proxy method for setKey, for api compatibility
  5024. * @see setKey
  5025. * @public
  5026. */
  5027. JSEncrypt.prototype.setPrivateKey = function (privkey) {
  5028. // Create the key.
  5029. this.setKey(privkey);
  5030. };
  5031. /**
  5032. * Proxy method for setKey, for api compatibility
  5033. * @see setKey
  5034. * @public
  5035. */
  5036. JSEncrypt.prototype.setPublicKey = function (pubkey) {
  5037. // Sets the public key.
  5038. this.setKey(pubkey);
  5039. };
  5040. /**
  5041. * Proxy method for RSAKey object's decrypt, decrypt the string using the private
  5042. * components of the rsa key object. Note that if the object was not set will be created
  5043. * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor
  5044. * @param {string} str base64 encoded crypted string to decrypt
  5045. * @return {string} the decrypted string
  5046. * @public
  5047. */
  5048. JSEncrypt.prototype.decrypt = function (str) {
  5049. // Return the decrypted string.
  5050. try {
  5051. return this.getKey().decrypt(b64tohex(str));
  5052. }
  5053. catch (ex) {
  5054. return false;
  5055. }
  5056. };
  5057. /**
  5058. * Proxy method for RSAKey object's encrypt, encrypt the string using the public
  5059. * components of the rsa key object. Note that if the object was not set will be created
  5060. * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor
  5061. * @param {string} str the string to encrypt
  5062. * @return {string} the encrypted string encoded in base64
  5063. * @public
  5064. */
  5065. JSEncrypt.prototype.encrypt = function (str) {
  5066. // Return the encrypted string.
  5067. try {
  5068. return hex2b64(this.getKey().encrypt(str));
  5069. }
  5070. catch (ex) {
  5071. return false;
  5072. }
  5073. };
  5074. /**
  5075. * Getter for the current JSEncryptRSAKey object. If it doesn't exists a new object
  5076. * will be created and returned
  5077. * @param {callback} [cb] the callback to be called if we want the key to be generated
  5078. * in an async fashion
  5079. * @returns {JSEncryptRSAKey} the JSEncryptRSAKey object
  5080. * @public
  5081. */
  5082. JSEncrypt.prototype.getKey = function (cb) {
  5083. // Only create new if it does not exist.
  5084. if (!this.key) {
  5085. // Get a new private key.
  5086. this.key = new JSEncryptRSAKey();
  5087. if (cb && {}.toString.call(cb) === "[object Function]") {
  5088. this.key.generateAsync(this.default_key_size, this.default_public_exponent, cb);
  5089. return;
  5090. }
  5091. // Generate the key.
  5092. this.key.generate(this.default_key_size, this.default_public_exponent);
  5093. }
  5094. return this.key;
  5095. };
  5096. /**
  5097. * Returns the pem encoded representation of the private key
  5098. * If the key doesn't exists a new key will be created
  5099. * @returns {string} pem encoded representation of the private key WITH header and footer
  5100. * @public
  5101. */
  5102. JSEncrypt.prototype.getPrivateKey = function () {
  5103. // Return the private representation of this key.
  5104. return this.getKey().getPrivateKey();
  5105. };
  5106. /**
  5107. * Returns the pem encoded representation of the private key
  5108. * If the key doesn't exists a new key will be created
  5109. * @returns {string} pem encoded representation of the private key WITHOUT header and footer
  5110. * @public
  5111. */
  5112. JSEncrypt.prototype.getPrivateKeyB64 = function () {
  5113. // Return the private representation of this key.
  5114. return this.getKey().getPrivateBaseKeyB64();
  5115. };
  5116. /**
  5117. * Returns the pem encoded representation of the public key
  5118. * If the key doesn't exists a new key will be created
  5119. * @returns {string} pem encoded representation of the public key WITH header and footer
  5120. * @public
  5121. */
  5122. JSEncrypt.prototype.getPublicKey = function () {
  5123. // Return the private representation of this key.
  5124. return this.getKey().getPublicKey();
  5125. };
  5126. /**
  5127. * Returns the pem encoded representation of the public key
  5128. * If the key doesn't exists a new key will be created
  5129. * @returns {string} pem encoded representation of the public key WITHOUT header and footer
  5130. * @public
  5131. */
  5132. JSEncrypt.prototype.getPublicKeyB64 = function () {
  5133. // Return the private representation of this key.
  5134. return this.getKey().getPublicBaseKeyB64();
  5135. };
  5136. JSEncrypt.version = "3.0.0-beta.1";
  5137. return JSEncrypt;
  5138. }());
  5139. window.JSEncrypt = JSEncrypt;
  5140. exports.JSEncrypt = JSEncrypt;
  5141. exports.default = JSEncrypt;
  5142. Object.defineProperty(exports, '__esModule', { value: true });
  5143. })));