jsencrypt.js 151 KB

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