jsencrypt.js 151 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379
  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. console.log(arguments)
  1345. var i = e.bitLength();
  1346. var k;
  1347. var r = nbv(1);
  1348. var z;
  1349. if (i <= 0) {
  1350. return r;
  1351. } else if (i < 18) {
  1352. k = 1;
  1353. } else if (i < 48) {
  1354. k = 3;
  1355. } else if (i < 144) {
  1356. k = 4;
  1357. } else if (i < 768) {
  1358. k = 5;
  1359. } else {
  1360. k = 6;
  1361. }
  1362. if (i < 8) {
  1363. z = new Classic(m);
  1364. } else if (m.isEven()) {
  1365. z = new Barrett(m);
  1366. } else {
  1367. z = new Montgomery(m);
  1368. }
  1369. // precomputation
  1370. var g = [];
  1371. var n = 3;
  1372. var k1 = k - 1;
  1373. var km = (1 << k) - 1;
  1374. g[1] = z.convert(this);
  1375. if (k > 1) {
  1376. var g2 = nbi();
  1377. z.sqrTo(g[1], g2);
  1378. while (n <= km) {
  1379. g[n] = nbi();
  1380. z.mulTo(g2, g[n - 2], g[n]);
  1381. n += 2;
  1382. }
  1383. }
  1384. var j = e.t - 1;
  1385. var w;
  1386. var is1 = true;
  1387. var r2 = nbi();
  1388. var t;
  1389. i = nbits(e[j]) - 1;
  1390. while (j >= 0) {
  1391. if (i >= k1) {
  1392. w = (e[j] >> (i - k1)) & km;
  1393. } else {
  1394. w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i);
  1395. if (j > 0) {
  1396. w |= e[j - 1] >> (this.DB + i - k1);
  1397. }
  1398. }
  1399. n = k;
  1400. while ((w & 1) == 0) {
  1401. w >>= 1;
  1402. --n;
  1403. }
  1404. if ((i -= n) < 0) {
  1405. i += this.DB;
  1406. --j;
  1407. }
  1408. if (is1) { // ret == 1, don't bother squaring or multiplying it
  1409. g[w].copyTo(r);
  1410. is1 = false;
  1411. } else {
  1412. while (n > 1) {
  1413. z.sqrTo(r, r2);
  1414. z.sqrTo(r2, r);
  1415. n -= 2;
  1416. }
  1417. if (n > 0) {
  1418. z.sqrTo(r, r2);
  1419. } else {
  1420. t = r;
  1421. r = r2;
  1422. r2 = t;
  1423. }
  1424. z.mulTo(r2, g[w], r);
  1425. }
  1426. while (j >= 0 && (e[j] & (1 << i)) == 0) {
  1427. z.sqrTo(r, r2);
  1428. t = r;
  1429. r = r2;
  1430. r2 = t;
  1431. if (--i < 0) {
  1432. i = this.DB - 1;
  1433. --j;
  1434. }
  1435. }
  1436. }
  1437. return z.revert(r);
  1438. };
  1439. // BigInteger.prototype.modInverse = bnModInverse;
  1440. // (public) 1/this % m (HAC 14.61)
  1441. BigInteger.prototype.modInverse = function(m) {
  1442. var ac = m.isEven();
  1443. if ((this.isEven() && ac) || m.signum() == 0) {
  1444. return BigInteger.ZERO;
  1445. }
  1446. var u = m.clone();
  1447. var v = this.clone();
  1448. var a = nbv(1);
  1449. var b = nbv(0);
  1450. var c = nbv(0);
  1451. var d = nbv(1);
  1452. while (u.signum() != 0) {
  1453. while (u.isEven()) {
  1454. u.rShiftTo(1, u);
  1455. if (ac) {
  1456. if (!a.isEven() || !b.isEven()) {
  1457. a.addTo(this, a);
  1458. b.subTo(m, b);
  1459. }
  1460. a.rShiftTo(1, a);
  1461. } else if (!b.isEven()) {
  1462. b.subTo(m, b);
  1463. }
  1464. b.rShiftTo(1, b);
  1465. }
  1466. while (v.isEven()) {
  1467. v.rShiftTo(1, v);
  1468. if (ac) {
  1469. if (!c.isEven() || !d.isEven()) {
  1470. c.addTo(this, c);
  1471. d.subTo(m, d);
  1472. }
  1473. c.rShiftTo(1, c);
  1474. } else if (!d.isEven()) {
  1475. d.subTo(m, d);
  1476. }
  1477. d.rShiftTo(1, d);
  1478. }
  1479. if (u.compareTo(v) >= 0) {
  1480. u.subTo(v, u);
  1481. if (ac) {
  1482. a.subTo(c, a);
  1483. }
  1484. b.subTo(d, b);
  1485. } else {
  1486. v.subTo(u, v);
  1487. if (ac) {
  1488. c.subTo(a, c);
  1489. }
  1490. d.subTo(b, d);
  1491. }
  1492. }
  1493. if (v.compareTo(BigInteger.ONE) != 0) {
  1494. return BigInteger.ZERO;
  1495. }
  1496. if (d.compareTo(m) >= 0) {
  1497. return d.subtract(m);
  1498. }
  1499. if (d.signum() < 0) {
  1500. d.addTo(m, d);
  1501. } else {
  1502. return d;
  1503. }
  1504. if (d.signum() < 0) {
  1505. return d.add(m);
  1506. } else {
  1507. return d;
  1508. }
  1509. };
  1510. // BigInteger.prototype.pow = bnPow;
  1511. // (public) this^e
  1512. BigInteger.prototype.pow = function(e) {
  1513. return this.exp(e, new NullExp());
  1514. };
  1515. // BigInteger.prototype.gcd = bnGCD;
  1516. // (public) gcd(this,a) (HAC 14.54)
  1517. BigInteger.prototype.gcd = function(a) {
  1518. var x = (this.s < 0) ? this.negate() : this.clone();
  1519. var y = (a.s < 0) ? a.negate() : a.clone();
  1520. if (x.compareTo(y) < 0) {
  1521. var t = x;
  1522. x = y;
  1523. y = t;
  1524. }
  1525. var i = x.getLowestSetBit();
  1526. var g = y.getLowestSetBit();
  1527. if (g < 0) {
  1528. return x;
  1529. }
  1530. if (i < g) {
  1531. g = i;
  1532. }
  1533. if (g > 0) {
  1534. x.rShiftTo(g, x);
  1535. y.rShiftTo(g, y);
  1536. }
  1537. while (x.signum() > 0) {
  1538. if ((i = x.getLowestSetBit()) > 0) {
  1539. x.rShiftTo(i, x);
  1540. }
  1541. if ((i = y.getLowestSetBit()) > 0) {
  1542. y.rShiftTo(i, y);
  1543. }
  1544. if (x.compareTo(y) >= 0) {
  1545. x.subTo(y, x);
  1546. x.rShiftTo(1, x);
  1547. } else {
  1548. y.subTo(x, y);
  1549. y.rShiftTo(1, y);
  1550. }
  1551. }
  1552. if (g > 0) {
  1553. y.lShiftTo(g, y);
  1554. }
  1555. return y;
  1556. };
  1557. // BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
  1558. // (public) test primality with certainty >= 1-.5^t
  1559. BigInteger.prototype.isProbablePrime = function(t) {
  1560. var i;
  1561. var x = this.abs();
  1562. if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) {
  1563. for (i = 0; i < lowprimes.length; ++i) {
  1564. if (x[0] == lowprimes[i]) {
  1565. return true;
  1566. }
  1567. }
  1568. return false;
  1569. }
  1570. if (x.isEven()) {
  1571. return false;
  1572. }
  1573. i = 1;
  1574. while (i < lowprimes.length) {
  1575. var m = lowprimes[i];
  1576. var j = i + 1;
  1577. while (j < lowprimes.length && m < lplim) {
  1578. m *= lowprimes[j++];
  1579. }
  1580. m = x.modInt(m);
  1581. while (i < j) {
  1582. if (m % lowprimes[i++] == 0) {
  1583. return false;
  1584. }
  1585. }
  1586. }
  1587. return x.millerRabin(t);
  1588. };
  1589. //#endregion PUBLIC
  1590. //#region PROTECTED
  1591. // BigInteger.prototype.copyTo = bnpCopyTo;
  1592. // (protected) copy this to r
  1593. BigInteger.prototype.copyTo = function(r) {
  1594. for (var i = this.t - 1; i >= 0; --i) {
  1595. r[i] = this[i];
  1596. }
  1597. r.t = this.t;
  1598. r.s = this.s;
  1599. };
  1600. // BigInteger.prototype.fromInt = bnpFromInt;
  1601. // (protected) set from integer value x, -DV <= x < DV
  1602. BigInteger.prototype.fromInt = function(x) {
  1603. this.t = 1;
  1604. this.s = (x < 0) ? -1 : 0;
  1605. if (x > 0) {
  1606. this[0] = x;
  1607. } else if (x < -1) {
  1608. this[0] = x + this.DV;
  1609. } else {
  1610. this.t = 0;
  1611. }
  1612. };
  1613. // BigInteger.prototype.fromString = bnpFromString;
  1614. // (protected) set from string and radix
  1615. BigInteger.prototype.fromString = function(s, b) {
  1616. var k;
  1617. if (b == 16) {
  1618. k = 4;
  1619. } else if (b == 8) {
  1620. k = 3;
  1621. } else if (b == 256) {
  1622. k = 8;
  1623. /* byte array */
  1624. } else if (b == 2) {
  1625. k = 1;
  1626. } else if (b == 32) {
  1627. k = 5;
  1628. } else if (b == 4) {
  1629. k = 2;
  1630. } else {
  1631. this.fromRadix(s, b);
  1632. return;
  1633. }
  1634. this.t = 0;
  1635. this.s = 0;
  1636. var i = s.length;
  1637. var mi = false;
  1638. var sh = 0;
  1639. while (--i >= 0) {
  1640. var x = (k == 8) ? (+s[i]) & 0xff : intAt(s, i);
  1641. if (x < 0) {
  1642. if (s.charAt(i) == "-") {
  1643. mi = true;
  1644. }
  1645. continue;
  1646. }
  1647. mi = false;
  1648. if (sh == 0) {
  1649. this[this.t++] = x;
  1650. } else if (sh + k > this.DB) {
  1651. this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh;
  1652. this[this.t++] = (x >> (this.DB - sh));
  1653. } else {
  1654. this[this.t - 1] |= x << sh;
  1655. }
  1656. sh += k;
  1657. if (sh >= this.DB) {
  1658. sh -= this.DB;
  1659. }
  1660. }
  1661. if (k == 8 && ((+s[0]) & 0x80) != 0) {
  1662. this.s = -1;
  1663. if (sh > 0) {
  1664. this[this.t - 1] |= ((1 << (this.DB - sh)) - 1) << sh;
  1665. }
  1666. }
  1667. this.clamp();
  1668. if (mi) {
  1669. BigInteger.ZERO.subTo(this, this);
  1670. }
  1671. };
  1672. // BigInteger.prototype.clamp = bnpClamp;
  1673. // (protected) clamp off excess high words
  1674. BigInteger.prototype.clamp = function() {
  1675. var c = this.s & this.DM;
  1676. while (this.t > 0 && this[this.t - 1] == c) {
  1677. --this.t;
  1678. }
  1679. };
  1680. // BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
  1681. // (protected) r = this << n*DB
  1682. BigInteger.prototype.dlShiftTo = function(n, r) {
  1683. var i;
  1684. for (i = this.t - 1; i >= 0; --i) {
  1685. r[i + n] = this[i];
  1686. }
  1687. for (i = n - 1; i >= 0; --i) {
  1688. r[i] = 0;
  1689. }
  1690. r.t = this.t + n;
  1691. r.s = this.s;
  1692. };
  1693. // BigInteger.prototype.drShiftTo = bnpDRShiftTo;
  1694. // (protected) r = this >> n*DB
  1695. BigInteger.prototype.drShiftTo = function(n, r) {
  1696. for (var i = n; i < this.t; ++i) {
  1697. r[i - n] = this[i];
  1698. }
  1699. r.t = Math.max(this.t - n, 0);
  1700. r.s = this.s;
  1701. };
  1702. // BigInteger.prototype.lShiftTo = bnpLShiftTo;
  1703. // (protected) r = this << n
  1704. BigInteger.prototype.lShiftTo = function(n, r) {
  1705. var bs = n % this.DB;
  1706. var cbs = this.DB - bs;
  1707. var bm = (1 << cbs) - 1;
  1708. var ds = Math.floor(n / this.DB);
  1709. var c = (this.s << bs) & this.DM;
  1710. for (var i = this.t - 1; i >= 0; --i) {
  1711. r[i + ds + 1] = (this[i] >> cbs) | c;
  1712. c = (this[i] & bm) << bs;
  1713. }
  1714. for (var i = ds - 1; i >= 0; --i) {
  1715. r[i] = 0;
  1716. }
  1717. r[ds] = c;
  1718. r.t = this.t + ds + 1;
  1719. r.s = this.s;
  1720. r.clamp();
  1721. };
  1722. // BigInteger.prototype.rShiftTo = bnpRShiftTo;
  1723. // (protected) r = this >> n
  1724. BigInteger.prototype.rShiftTo = function(n, r) {
  1725. r.s = this.s;
  1726. var ds = Math.floor(n / this.DB);
  1727. if (ds >= this.t) {
  1728. r.t = 0;
  1729. return;
  1730. }
  1731. var bs = n % this.DB;
  1732. var cbs = this.DB - bs;
  1733. var bm = (1 << bs) - 1;
  1734. r[0] = this[ds] >> bs;
  1735. for (var i = ds + 1; i < this.t; ++i) {
  1736. r[i - ds - 1] |= (this[i] & bm) << cbs;
  1737. r[i - ds] = this[i] >> bs;
  1738. }
  1739. if (bs > 0) {
  1740. r[this.t - ds - 1] |= (this.s & bm) << cbs;
  1741. }
  1742. r.t = this.t - ds;
  1743. r.clamp();
  1744. };
  1745. // BigInteger.prototype.subTo = bnpSubTo;
  1746. // (protected) r = this - a
  1747. BigInteger.prototype.subTo = function(a, r) {
  1748. var i = 0;
  1749. var c = 0;
  1750. var m = Math.min(a.t, this.t);
  1751. while (i < m) {
  1752. c += this[i] - a[i];
  1753. r[i++] = c & this.DM;
  1754. c >>= this.DB;
  1755. }
  1756. if (a.t < this.t) {
  1757. c -= a.s;
  1758. while (i < this.t) {
  1759. c += this[i];
  1760. r[i++] = c & this.DM;
  1761. c >>= this.DB;
  1762. }
  1763. c += this.s;
  1764. } else {
  1765. c += this.s;
  1766. while (i < a.t) {
  1767. c -= a[i];
  1768. r[i++] = c & this.DM;
  1769. c >>= this.DB;
  1770. }
  1771. c -= a.s;
  1772. }
  1773. r.s = (c < 0) ? -1 : 0;
  1774. if (c < -1) {
  1775. r[i++] = this.DV + c;
  1776. } else if (c > 0) {
  1777. r[i++] = c;
  1778. }
  1779. r.t = i;
  1780. r.clamp();
  1781. };
  1782. // BigInteger.prototype.multiplyTo = bnpMultiplyTo;
  1783. // (protected) r = this * a, r != this,a (HAC 14.12)
  1784. // "this" should be the larger one if appropriate.
  1785. BigInteger.prototype.multiplyTo = function(a, r) {
  1786. var x = this.abs();
  1787. var y = a.abs();
  1788. var i = x.t;
  1789. r.t = i + y.t;
  1790. while (--i >= 0) {
  1791. r[i] = 0;
  1792. }
  1793. for (i = 0; i < y.t; ++i) {
  1794. r[i + x.t] = x.am(0, y[i], r, i, 0, x.t);
  1795. }
  1796. r.s = 0;
  1797. r.clamp();
  1798. if (this.s != a.s) {
  1799. BigInteger.ZERO.subTo(r, r);
  1800. }
  1801. };
  1802. // BigInteger.prototype.squareTo = bnpSquareTo;
  1803. // (protected) r = this^2, r != this (HAC 14.16)
  1804. BigInteger.prototype.squareTo = function(r) {
  1805. var x = this.abs();
  1806. var i = r.t = 2 * x.t;
  1807. while (--i >= 0) {
  1808. r[i] = 0;
  1809. }
  1810. for (i = 0; i < x.t - 1; ++i) {
  1811. var c = x.am(i, x[i], r, 2 * i, 0, 1);
  1812. if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x
  1813. .DV) {
  1814. r[i + x.t] -= x.DV;
  1815. r[i + x.t + 1] = 1;
  1816. }
  1817. }
  1818. if (r.t > 0) {
  1819. r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1);
  1820. }
  1821. r.s = 0;
  1822. r.clamp();
  1823. };
  1824. // BigInteger.prototype.divRemTo = bnpDivRemTo;
  1825. // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
  1826. // r != q, this != m. q or r may be null.
  1827. BigInteger.prototype.divRemTo = function(m, q, r) {
  1828. var pm = m.abs();
  1829. if (pm.t <= 0) {
  1830. return;
  1831. }
  1832. var pt = this.abs();
  1833. if (pt.t < pm.t) {
  1834. if (q != null) {
  1835. q.fromInt(0);
  1836. }
  1837. if (r != null) {
  1838. this.copyTo(r);
  1839. }
  1840. return;
  1841. }
  1842. if (r == null) {
  1843. r = nbi();
  1844. }
  1845. var y = nbi();
  1846. var ts = this.s;
  1847. var ms = m.s;
  1848. var nsh = this.DB - nbits(pm[pm.t - 1]); // normalize modulus
  1849. if (nsh > 0) {
  1850. pm.lShiftTo(nsh, y);
  1851. pt.lShiftTo(nsh, r);
  1852. } else {
  1853. pm.copyTo(y);
  1854. pt.copyTo(r);
  1855. }
  1856. var ys = y.t;
  1857. var y0 = y[ys - 1];
  1858. if (y0 == 0) {
  1859. return;
  1860. }
  1861. var yt = y0 * (1 << this.F1) + ((ys > 1) ? y[ys - 2] >> this.F2 : 0);
  1862. var d1 = this.FV / yt;
  1863. var d2 = (1 << this.F1) / yt;
  1864. var e = 1 << this.F2;
  1865. var i = r.t;
  1866. var j = i - ys;
  1867. var t = (q == null) ? nbi() : q;
  1868. y.dlShiftTo(j, t);
  1869. if (r.compareTo(t) >= 0) {
  1870. r[r.t++] = 1;
  1871. r.subTo(t, r);
  1872. }
  1873. BigInteger.ONE.dlShiftTo(ys, t);
  1874. t.subTo(y, y); // "negative" y so we can replace sub with am later
  1875. while (y.t < ys) {
  1876. y[y.t++] = 0;
  1877. }
  1878. while (--j >= 0) {
  1879. // Estimate quotient digit
  1880. var qd = (r[--i] == y0) ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2);
  1881. if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out
  1882. y.dlShiftTo(j, t);
  1883. r.subTo(t, r);
  1884. while (r[i] < --qd) {
  1885. r.subTo(t, r);
  1886. }
  1887. }
  1888. }
  1889. if (q != null) {
  1890. r.drShiftTo(ys, q);
  1891. if (ts != ms) {
  1892. BigInteger.ZERO.subTo(q, q);
  1893. }
  1894. }
  1895. r.t = ys;
  1896. r.clamp();
  1897. if (nsh > 0) {
  1898. r.rShiftTo(nsh, r);
  1899. } // Denormalize remainder
  1900. if (ts < 0) {
  1901. BigInteger.ZERO.subTo(r, r);
  1902. }
  1903. };
  1904. // BigInteger.prototype.invDigit = bnpInvDigit;
  1905. // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
  1906. // justification:
  1907. // xy == 1 (mod m)
  1908. // xy = 1+km
  1909. // xy(2-xy) = (1+km)(1-km)
  1910. // x[y(2-xy)] = 1-k^2m^2
  1911. // x[y(2-xy)] == 1 (mod m^2)
  1912. // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
  1913. // should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
  1914. // JS multiply "overflows" differently from C/C++, so care is needed here.
  1915. BigInteger.prototype.invDigit = function() {
  1916. if (this.t < 1) {
  1917. return 0;
  1918. }
  1919. var x = this[0];
  1920. if ((x & 1) == 0) {
  1921. return 0;
  1922. }
  1923. var y = x & 3; // y == 1/x mod 2^2
  1924. y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4
  1925. y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8
  1926. y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16
  1927. // last step - calculate inverse mod DV directly;
  1928. // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
  1929. y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits
  1930. // we really want the negative inverse, and -DV < y < DV
  1931. return (y > 0) ? this.DV - y : -y;
  1932. };
  1933. // BigInteger.prototype.isEven = bnpIsEven;
  1934. // (protected) true iff this is even
  1935. BigInteger.prototype.isEven = function() {
  1936. return ((this.t > 0) ? (this[0] & 1) : this.s) == 0;
  1937. };
  1938. // BigInteger.prototype.exp = bnpExp;
  1939. // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
  1940. BigInteger.prototype.exp = function(e, z) {
  1941. if (e > 0xffffffff || e < 1) {
  1942. return BigInteger.ONE;
  1943. }
  1944. var r = nbi();
  1945. var r2 = nbi();
  1946. var g = z.convert(this);
  1947. var i = nbits(e) - 1;
  1948. g.copyTo(r);
  1949. while (--i >= 0) {
  1950. z.sqrTo(r, r2);
  1951. if ((e & (1 << i)) > 0) {
  1952. z.mulTo(r2, g, r);
  1953. } else {
  1954. var t = r;
  1955. r = r2;
  1956. r2 = t;
  1957. }
  1958. }
  1959. return z.revert(r);
  1960. };
  1961. // BigInteger.prototype.chunkSize = bnpChunkSize;
  1962. // (protected) return x s.t. r^x < DV
  1963. BigInteger.prototype.chunkSize = function(r) {
  1964. return Math.floor(Math.LN2 * this.DB / Math.log(r));
  1965. };
  1966. // BigInteger.prototype.toRadix = bnpToRadix;
  1967. // (protected) convert to radix string
  1968. BigInteger.prototype.toRadix = function(b) {
  1969. if (b == null) {
  1970. b = 10;
  1971. }
  1972. if (this.signum() == 0 || b < 2 || b > 36) {
  1973. return "0";
  1974. }
  1975. var cs = this.chunkSize(b);
  1976. var a = Math.pow(b, cs);
  1977. var d = nbv(a);
  1978. var y = nbi();
  1979. var z = nbi();
  1980. var r = "";
  1981. this.divRemTo(d, y, z);
  1982. while (y.signum() > 0) {
  1983. r = (a + z.intValue()).toString(b).substr(1) + r;
  1984. y.divRemTo(d, y, z);
  1985. }
  1986. return z.intValue().toString(b) + r;
  1987. };
  1988. // BigInteger.prototype.fromRadix = bnpFromRadix;
  1989. // (protected) convert from radix string
  1990. BigInteger.prototype.fromRadix = function(s, b) {
  1991. this.fromInt(0);
  1992. if (b == null) {
  1993. b = 10;
  1994. }
  1995. var cs = this.chunkSize(b);
  1996. var d = Math.pow(b, cs);
  1997. var mi = false;
  1998. var j = 0;
  1999. var w = 0;
  2000. for (var i = 0; i < s.length; ++i) {
  2001. var x = intAt(s, i);
  2002. if (x < 0) {
  2003. if (s.charAt(i) == "-" && this.signum() == 0) {
  2004. mi = true;
  2005. }
  2006. continue;
  2007. }
  2008. w = b * w + x;
  2009. if (++j >= cs) {
  2010. this.dMultiply(d);
  2011. this.dAddOffset(w, 0);
  2012. j = 0;
  2013. w = 0;
  2014. }
  2015. }
  2016. if (j > 0) {
  2017. this.dMultiply(Math.pow(b, j));
  2018. this.dAddOffset(w, 0);
  2019. }
  2020. if (mi) {
  2021. BigInteger.ZERO.subTo(this, this);
  2022. }
  2023. };
  2024. // BigInteger.prototype.fromNumber = bnpFromNumber;
  2025. // (protected) alternate constructor
  2026. BigInteger.prototype.fromNumber = function(a, b, c) {
  2027. if ("number" == typeof b) {
  2028. // new BigInteger(int,int,RNG)
  2029. if (a < 2) {
  2030. this.fromInt(1);
  2031. } else {
  2032. this.fromNumber(a, c);
  2033. if (!this.testBit(a - 1)) {
  2034. // force MSB set
  2035. this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this);
  2036. }
  2037. if (this.isEven()) {
  2038. this.dAddOffset(1, 0);
  2039. } // force odd
  2040. while (!this.isProbablePrime(b)) {
  2041. this.dAddOffset(2, 0);
  2042. if (this.bitLength() > a) {
  2043. this.subTo(BigInteger.ONE.shiftLeft(a - 1), this);
  2044. }
  2045. }
  2046. }
  2047. } else {
  2048. // new BigInteger(int,RNG)
  2049. var x = [];
  2050. var t = a & 7;
  2051. x.length = (a >> 3) + 1;
  2052. b.nextBytes(x);
  2053. if (t > 0) {
  2054. x[0] &= ((1 << t) - 1);
  2055. } else {
  2056. x[0] = 0;
  2057. }
  2058. this.fromString(x, 256);
  2059. }
  2060. };
  2061. // BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
  2062. // (protected) r = this op a (bitwise)
  2063. BigInteger.prototype.bitwiseTo = function(a, op, r) {
  2064. var i;
  2065. var f;
  2066. var m = Math.min(a.t, this.t);
  2067. for (i = 0; i < m; ++i) {
  2068. r[i] = op(this[i], a[i]);
  2069. }
  2070. if (a.t < this.t) {
  2071. f = a.s & this.DM;
  2072. for (i = m; i < this.t; ++i) {
  2073. r[i] = op(this[i], f);
  2074. }
  2075. r.t = this.t;
  2076. } else {
  2077. f = this.s & this.DM;
  2078. for (i = m; i < a.t; ++i) {
  2079. r[i] = op(f, a[i]);
  2080. }
  2081. r.t = a.t;
  2082. }
  2083. r.s = op(this.s, a.s);
  2084. r.clamp();
  2085. };
  2086. // BigInteger.prototype.changeBit = bnpChangeBit;
  2087. // (protected) this op (1<<n)
  2088. BigInteger.prototype.changeBit = function(n, op) {
  2089. var r = BigInteger.ONE.shiftLeft(n);
  2090. this.bitwiseTo(r, op, r);
  2091. return r;
  2092. };
  2093. // BigInteger.prototype.addTo = bnpAddTo;
  2094. // (protected) r = this + a
  2095. BigInteger.prototype.addTo = function(a, r) {
  2096. var i = 0;
  2097. var c = 0;
  2098. var m = Math.min(a.t, this.t);
  2099. while (i < m) {
  2100. c += this[i] + a[i];
  2101. r[i++] = c & this.DM;
  2102. c >>= this.DB;
  2103. }
  2104. if (a.t < this.t) {
  2105. c += a.s;
  2106. while (i < this.t) {
  2107. c += this[i];
  2108. r[i++] = c & this.DM;
  2109. c >>= this.DB;
  2110. }
  2111. c += this.s;
  2112. } else {
  2113. c += this.s;
  2114. while (i < a.t) {
  2115. c += a[i];
  2116. r[i++] = c & this.DM;
  2117. c >>= this.DB;
  2118. }
  2119. c += a.s;
  2120. }
  2121. r.s = (c < 0) ? -1 : 0;
  2122. if (c > 0) {
  2123. r[i++] = c;
  2124. } else if (c < -1) {
  2125. r[i++] = this.DV + c;
  2126. }
  2127. r.t = i;
  2128. r.clamp();
  2129. };
  2130. // BigInteger.prototype.dMultiply = bnpDMultiply;
  2131. // (protected) this *= n, this >= 0, 1 < n < DV
  2132. BigInteger.prototype.dMultiply = function(n) {
  2133. this[this.t] = this.am(0, n - 1, this, 0, 0, this.t);
  2134. ++this.t;
  2135. this.clamp();
  2136. };
  2137. // BigInteger.prototype.dAddOffset = bnpDAddOffset;
  2138. // (protected) this += n << w words, this >= 0
  2139. BigInteger.prototype.dAddOffset = function(n, w) {
  2140. if (n == 0) {
  2141. return;
  2142. }
  2143. while (this.t <= w) {
  2144. this[this.t++] = 0;
  2145. }
  2146. this[w] += n;
  2147. while (this[w] >= this.DV) {
  2148. this[w] -= this.DV;
  2149. if (++w >= this.t) {
  2150. this[this.t++] = 0;
  2151. }
  2152. ++this[w];
  2153. }
  2154. };
  2155. // BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
  2156. // (protected) r = lower n words of "this * a", a.t <= n
  2157. // "this" should be the larger one if appropriate.
  2158. BigInteger.prototype.multiplyLowerTo = function(a, n, r) {
  2159. var i = Math.min(this.t + a.t, n);
  2160. r.s = 0; // assumes a,this >= 0
  2161. r.t = i;
  2162. while (i > 0) {
  2163. r[--i] = 0;
  2164. }
  2165. for (var j = r.t - this.t; i < j; ++i) {
  2166. r[i + this.t] = this.am(0, a[i], r, i, 0, this.t);
  2167. }
  2168. for (var j = Math.min(a.t, n); i < j; ++i) {
  2169. this.am(0, a[i], r, i, 0, n - i);
  2170. }
  2171. r.clamp();
  2172. };
  2173. // BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
  2174. // (protected) r = "this * a" without lower n words, n > 0
  2175. // "this" should be the larger one if appropriate.
  2176. BigInteger.prototype.multiplyUpperTo = function(a, n, r) {
  2177. --n;
  2178. var i = r.t = this.t + a.t - n;
  2179. r.s = 0; // assumes a,this >= 0
  2180. while (--i >= 0) {
  2181. r[i] = 0;
  2182. }
  2183. for (i = Math.max(n - this.t, 0); i < a.t; ++i) {
  2184. r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n);
  2185. }
  2186. r.clamp();
  2187. r.drShiftTo(1, r);
  2188. };
  2189. // BigInteger.prototype.modInt = bnpModInt;
  2190. // (protected) this % n, n < 2^26
  2191. BigInteger.prototype.modInt = function(n) {
  2192. if (n <= 0) {
  2193. return 0;
  2194. }
  2195. var d = this.DV % n;
  2196. var r = (this.s < 0) ? n - 1 : 0;
  2197. if (this.t > 0) {
  2198. if (d == 0) {
  2199. r = this[0] % n;
  2200. } else {
  2201. for (var i = this.t - 1; i >= 0; --i) {
  2202. r = (d * r + this[i]) % n;
  2203. }
  2204. }
  2205. }
  2206. return r;
  2207. };
  2208. // BigInteger.prototype.millerRabin = bnpMillerRabin;
  2209. // (protected) true if probably prime (HAC 4.24, Miller-Rabin)
  2210. BigInteger.prototype.millerRabin = function(t) {
  2211. var n1 = this.subtract(BigInteger.ONE);
  2212. var k = n1.getLowestSetBit();
  2213. if (k <= 0) {
  2214. return false;
  2215. }
  2216. var r = n1.shiftRight(k);
  2217. t = (t + 1) >> 1;
  2218. if (t > lowprimes.length) {
  2219. t = lowprimes.length;
  2220. }
  2221. var a = nbi();
  2222. for (var i = 0; i < t; ++i) {
  2223. // Pick bases at random, instead of starting at 2
  2224. a.fromInt(lowprimes[Math.floor(Math.random() * lowprimes.length)]);
  2225. var y = a.modPow(r, this);
  2226. if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
  2227. var j = 1;
  2228. while (j++ < k && y.compareTo(n1) != 0) {
  2229. y = y.modPowInt(2, this);
  2230. if (y.compareTo(BigInteger.ONE) == 0) {
  2231. return false;
  2232. }
  2233. }
  2234. if (y.compareTo(n1) != 0) {
  2235. return false;
  2236. }
  2237. }
  2238. }
  2239. return true;
  2240. };
  2241. // BigInteger.prototype.square = bnSquare;
  2242. // (public) this^2
  2243. BigInteger.prototype.square = function() {
  2244. var r = nbi();
  2245. this.squareTo(r);
  2246. return r;
  2247. };
  2248. //#region ASYNC
  2249. // Public API method
  2250. BigInteger.prototype.gcda = function(a, callback) {
  2251. var x = (this.s < 0) ? this.negate() : this.clone();
  2252. var y = (a.s < 0) ? a.negate() : a.clone();
  2253. if (x.compareTo(y) < 0) {
  2254. var t = x;
  2255. x = y;
  2256. y = t;
  2257. }
  2258. var i = x.getLowestSetBit();
  2259. var g = y.getLowestSetBit();
  2260. if (g < 0) {
  2261. callback(x);
  2262. return;
  2263. }
  2264. if (i < g) {
  2265. g = i;
  2266. }
  2267. if (g > 0) {
  2268. x.rShiftTo(g, x);
  2269. y.rShiftTo(g, y);
  2270. }
  2271. // Workhorse of the algorithm, gets called 200 - 800 times per 512 bit keygen.
  2272. var gcda1 = function() {
  2273. if ((i = x.getLowestSetBit()) > 0) {
  2274. x.rShiftTo(i, x);
  2275. }
  2276. if ((i = y.getLowestSetBit()) > 0) {
  2277. y.rShiftTo(i, y);
  2278. }
  2279. if (x.compareTo(y) >= 0) {
  2280. x.subTo(y, x);
  2281. x.rShiftTo(1, x);
  2282. } else {
  2283. y.subTo(x, y);
  2284. y.rShiftTo(1, y);
  2285. }
  2286. if (!(x.signum() > 0)) {
  2287. if (g > 0) {
  2288. y.lShiftTo(g, y);
  2289. }
  2290. setTimeout(function() {
  2291. callback(y);
  2292. }, 0); // escape
  2293. } else {
  2294. setTimeout(gcda1, 0);
  2295. }
  2296. };
  2297. setTimeout(gcda1, 10);
  2298. };
  2299. // (protected) alternate constructor
  2300. BigInteger.prototype.fromNumberAsync = function(a, b, c, callback) {
  2301. if ("number" == typeof b) {
  2302. if (a < 2) {
  2303. this.fromInt(1);
  2304. } else {
  2305. this.fromNumber(a, c);
  2306. if (!this.testBit(a - 1)) {
  2307. this.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, this);
  2308. }
  2309. if (this.isEven()) {
  2310. this.dAddOffset(1, 0);
  2311. }
  2312. var bnp_1 = this;
  2313. var bnpfn1_1 = function() {
  2314. bnp_1.dAddOffset(2, 0);
  2315. if (bnp_1.bitLength() > a) {
  2316. bnp_1.subTo(BigInteger.ONE.shiftLeft(a - 1), bnp_1);
  2317. }
  2318. if (bnp_1.isProbablePrime(b)) {
  2319. setTimeout(function() {
  2320. callback();
  2321. }, 0); // escape
  2322. } else {
  2323. setTimeout(bnpfn1_1, 0);
  2324. }
  2325. };
  2326. setTimeout(bnpfn1_1, 0);
  2327. }
  2328. } else {
  2329. var x = [];
  2330. var t = a & 7;
  2331. x.length = (a >> 3) + 1;
  2332. b.nextBytes(x);
  2333. if (t > 0) {
  2334. x[0] &= ((1 << t) - 1);
  2335. } else {
  2336. x[0] = 0;
  2337. }
  2338. this.fromString(x, 256);
  2339. }
  2340. };
  2341. return BigInteger;
  2342. }());
  2343. //#region REDUCERS
  2344. //#region NullExp
  2345. var NullExp = /** @class */ (function() {
  2346. function NullExp() {}
  2347. // NullExp.prototype.convert = nNop;
  2348. NullExp.prototype.convert = function(x) {
  2349. return x;
  2350. };
  2351. // NullExp.prototype.revert = nNop;
  2352. NullExp.prototype.revert = function(x) {
  2353. return x;
  2354. };
  2355. // NullExp.prototype.mulTo = nMulTo;
  2356. NullExp.prototype.mulTo = function(x, y, r) {
  2357. x.multiplyTo(y, r);
  2358. };
  2359. // NullExp.prototype.sqrTo = nSqrTo;
  2360. NullExp.prototype.sqrTo = function(x, r) {
  2361. x.squareTo(r);
  2362. };
  2363. return NullExp;
  2364. }());
  2365. // Modular reduction using "classic" algorithm
  2366. var Classic = /** @class */ (function() {
  2367. function Classic(m) {
  2368. this.m = m;
  2369. }
  2370. // Classic.prototype.convert = cConvert;
  2371. Classic.prototype.convert = function(x) {
  2372. if (x.s < 0 || x.compareTo(this.m) >= 0) {
  2373. return x.mod(this.m);
  2374. } else {
  2375. return x;
  2376. }
  2377. };
  2378. // Classic.prototype.revert = cRevert;
  2379. Classic.prototype.revert = function(x) {
  2380. return x;
  2381. };
  2382. // Classic.prototype.reduce = cReduce;
  2383. Classic.prototype.reduce = function(x) {
  2384. x.divRemTo(this.m, null, x);
  2385. };
  2386. // Classic.prototype.mulTo = cMulTo;
  2387. Classic.prototype.mulTo = function(x, y, r) {
  2388. x.multiplyTo(y, r);
  2389. this.reduce(r);
  2390. };
  2391. // Classic.prototype.sqrTo = cSqrTo;
  2392. Classic.prototype.sqrTo = function(x, r) {
  2393. x.squareTo(r);
  2394. this.reduce(r);
  2395. };
  2396. return Classic;
  2397. }());
  2398. //#endregion
  2399. //#region Montgomery
  2400. // Montgomery reduction
  2401. var Montgomery = /** @class */ (function() {
  2402. function Montgomery(m) {
  2403. this.m = m;
  2404. this.mp = m.invDigit();
  2405. this.mpl = this.mp & 0x7fff;
  2406. this.mph = this.mp >> 15;
  2407. this.um = (1 << (m.DB - 15)) - 1;
  2408. this.mt2 = 2 * m.t;
  2409. }
  2410. // Montgomery.prototype.convert = montConvert;
  2411. // xR mod m
  2412. Montgomery.prototype.convert = function(x) {
  2413. var r = nbi();
  2414. x.abs().dlShiftTo(this.m.t, r);
  2415. r.divRemTo(this.m, null, r);
  2416. if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) {
  2417. this.m.subTo(r, r);
  2418. }
  2419. return r;
  2420. };
  2421. // Montgomery.prototype.revert = montRevert;
  2422. // x/R mod m
  2423. Montgomery.prototype.revert = function(x) {
  2424. var r = nbi();
  2425. x.copyTo(r);
  2426. this.reduce(r);
  2427. return r;
  2428. };
  2429. // Montgomery.prototype.reduce = montReduce;
  2430. // x = x/R mod m (HAC 14.32)
  2431. Montgomery.prototype.reduce = function(x) {
  2432. while (x.t <= this.mt2) {
  2433. // pad x so am has enough room later
  2434. x[x.t++] = 0;
  2435. }
  2436. for (var i = 0; i < this.m.t; ++i) {
  2437. // faster way of calculating u0 = x[i]*mp mod DV
  2438. var j = x[i] & 0x7fff;
  2439. var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this
  2440. .um) << 15)) & x.DM;
  2441. // use am to combine the multiply-shift-add into one call
  2442. j = i + this.m.t;
  2443. x[j] += this.m.am(0, u0, x, i, 0, this.m.t);
  2444. // propagate carry
  2445. while (x[j] >= x.DV) {
  2446. x[j] -= x.DV;
  2447. x[++j]++;
  2448. }
  2449. }
  2450. x.clamp();
  2451. x.drShiftTo(this.m.t, x);
  2452. if (x.compareTo(this.m) >= 0) {
  2453. x.subTo(this.m, x);
  2454. }
  2455. };
  2456. // Montgomery.prototype.mulTo = montMulTo;
  2457. // r = "xy/R mod m"; x,y != r
  2458. Montgomery.prototype.mulTo = function(x, y, r) {
  2459. x.multiplyTo(y, r);
  2460. this.reduce(r);
  2461. };
  2462. // Montgomery.prototype.sqrTo = montSqrTo;
  2463. // r = "x^2/R mod m"; x != r
  2464. Montgomery.prototype.sqrTo = function(x, r) {
  2465. x.squareTo(r);
  2466. this.reduce(r);
  2467. };
  2468. return Montgomery;
  2469. }());
  2470. //#endregion Montgomery
  2471. //#region Barrett
  2472. // Barrett modular reduction
  2473. var Barrett = /** @class */ (function() {
  2474. function Barrett(m) {
  2475. this.m = m;
  2476. // setup Barrett
  2477. this.r2 = nbi();
  2478. this.q3 = nbi();
  2479. BigInteger.ONE.dlShiftTo(2 * m.t, this.r2);
  2480. this.mu = this.r2.divide(m);
  2481. }
  2482. // Barrett.prototype.convert = barrettConvert;
  2483. Barrett.prototype.convert = function(x) {
  2484. if (x.s < 0 || x.t > 2 * this.m.t) {
  2485. return x.mod(this.m);
  2486. } else if (x.compareTo(this.m) < 0) {
  2487. return x;
  2488. } else {
  2489. var r = nbi();
  2490. x.copyTo(r);
  2491. this.reduce(r);
  2492. return r;
  2493. }
  2494. };
  2495. // Barrett.prototype.revert = barrettRevert;
  2496. Barrett.prototype.revert = function(x) {
  2497. return x;
  2498. };
  2499. // Barrett.prototype.reduce = barrettReduce;
  2500. // x = x mod m (HAC 14.42)
  2501. Barrett.prototype.reduce = function(x) {
  2502. x.drShiftTo(this.m.t - 1, this.r2);
  2503. if (x.t > this.m.t + 1) {
  2504. x.t = this.m.t + 1;
  2505. x.clamp();
  2506. }
  2507. this.mu.multiplyUpperTo(this.r2, this.m.t + 1, this.q3);
  2508. this.m.multiplyLowerTo(this.q3, this.m.t + 1, this.r2);
  2509. while (x.compareTo(this.r2) < 0) {
  2510. x.dAddOffset(1, this.m.t + 1);
  2511. }
  2512. x.subTo(this.r2, x);
  2513. while (x.compareTo(this.m) >= 0) {
  2514. x.subTo(this.m, x);
  2515. }
  2516. };
  2517. // Barrett.prototype.mulTo = barrettMulTo;
  2518. // r = x*y mod m; x,y != r
  2519. Barrett.prototype.mulTo = function(x, y, r) {
  2520. x.multiplyTo(y, r);
  2521. this.reduce(r);
  2522. };
  2523. // Barrett.prototype.sqrTo = barrettSqrTo;
  2524. // r = x^2 mod m; x != r
  2525. Barrett.prototype.sqrTo = function(x, r) {
  2526. x.squareTo(r);
  2527. this.reduce(r);
  2528. };
  2529. return Barrett;
  2530. }());
  2531. //#endregion
  2532. //#endregion REDUCERS
  2533. // return new, unset BigInteger
  2534. function nbi() {
  2535. return new BigInteger(null);
  2536. }
  2537. function parseBigInt(str, r) {
  2538. return new BigInteger(str, r);
  2539. }
  2540. // am: Compute w_j += (x*this_i), propagate carries,
  2541. // c is initial carry, returns final carry.
  2542. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue
  2543. // We need to select the fastest one that works in this environment.
  2544. // am1: use a single mult and divide to get the high bits,
  2545. // max digit bits should be 26 because
  2546. // max internal value = 2*dvalue^2-2*dvalue (< 2^53)
  2547. function am1(i, x, w, j, c, n) {
  2548. while (--n >= 0) {
  2549. var v = x * this[i++] + w[j] + c;
  2550. c = Math.floor(v / 0x4000000);
  2551. w[j++] = v & 0x3ffffff;
  2552. }
  2553. return c;
  2554. }
  2555. // am2 avoids a big mult-and-extract completely.
  2556. // Max digit bits should be <= 30 because we do bitwise ops
  2557. // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
  2558. function am2(i, x, w, j, c, n) {
  2559. var xl = x & 0x7fff;
  2560. var xh = x >> 15;
  2561. while (--n >= 0) {
  2562. var l = this[i] & 0x7fff;
  2563. var h = this[i++] >> 15;
  2564. var m = xh * l + h * xl;
  2565. l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff);
  2566. c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30);
  2567. w[j++] = l & 0x3fffffff;
  2568. }
  2569. return c;
  2570. }
  2571. // Alternately, set max digit bits to 28 since some
  2572. // browsers slow down when dealing with 32-bit numbers.
  2573. function am3(i, x, w, j, c, n) {
  2574. var xl = x & 0x3fff;
  2575. var xh = x >> 14;
  2576. while (--n >= 0) {
  2577. var l = this[i] & 0x3fff;
  2578. var h = this[i++] >> 14;
  2579. var m = xh * l + h * xl;
  2580. l = xl * l + ((m & 0x3fff) << 14) + w[j] + c;
  2581. c = (l >> 28) + (m >> 14) + xh * h;
  2582. w[j++] = l & 0xfffffff;
  2583. }
  2584. return c;
  2585. }
  2586. var inBrowser = typeof navigator2 !== "undefined";
  2587. if (inBrowser && j_lm && (navigator2.appName == "Microsoft Internet Explorer")) {
  2588. BigInteger.prototype.am = am2;
  2589. dbits = 30;
  2590. } else if (inBrowser && j_lm && (navigator2.appName != "Netscape")) {
  2591. BigInteger.prototype.am = am1;
  2592. dbits = 26;
  2593. } else { // Mozilla/Netscape seems to prefer am3
  2594. BigInteger.prototype.am = am3;
  2595. dbits = 28;
  2596. }
  2597. BigInteger.prototype.DB = dbits;
  2598. BigInteger.prototype.DM = ((1 << dbits) - 1);
  2599. BigInteger.prototype.DV = (1 << dbits);
  2600. var BI_FP = 52;
  2601. BigInteger.prototype.FV = Math.pow(2, BI_FP);
  2602. BigInteger.prototype.F1 = BI_FP - dbits;
  2603. BigInteger.prototype.F2 = 2 * dbits - BI_FP;
  2604. // Digit conversions
  2605. var BI_RC = [];
  2606. var rr;
  2607. var vv;
  2608. rr = "0".charCodeAt(0);
  2609. for (vv = 0; vv <= 9; ++vv) {
  2610. BI_RC[rr++] = vv;
  2611. }
  2612. rr = "a".charCodeAt(0);
  2613. for (vv = 10; vv < 36; ++vv) {
  2614. BI_RC[rr++] = vv;
  2615. }
  2616. rr = "A".charCodeAt(0);
  2617. for (vv = 10; vv < 36; ++vv) {
  2618. BI_RC[rr++] = vv;
  2619. }
  2620. function intAt(s, i) {
  2621. var c = BI_RC[s.charCodeAt(i)];
  2622. return (c == null) ? -1 : c;
  2623. }
  2624. // return bigint initialized to value
  2625. function nbv(i) {
  2626. var r = nbi();
  2627. r.fromInt(i);
  2628. return r;
  2629. }
  2630. // returns bit length of the integer x
  2631. function nbits(x) {
  2632. var r = 1;
  2633. var t;
  2634. if ((t = x >>> 16) != 0) {
  2635. x = t;
  2636. r += 16;
  2637. }
  2638. if ((t = x >> 8) != 0) {
  2639. x = t;
  2640. r += 8;
  2641. }
  2642. if ((t = x >> 4) != 0) {
  2643. x = t;
  2644. r += 4;
  2645. }
  2646. if ((t = x >> 2) != 0) {
  2647. x = t;
  2648. r += 2;
  2649. }
  2650. if ((t = x >> 1) != 0) {
  2651. x = t;
  2652. r += 1;
  2653. }
  2654. return r;
  2655. }
  2656. // "constants"
  2657. BigInteger.ZERO = nbv(0);
  2658. BigInteger.ONE = nbv(1);
  2659. // prng4.js - uses Arcfour as a PRNG
  2660. var Arcfour = /** @class */ (function() {
  2661. function Arcfour() {
  2662. this.i = 0;
  2663. this.j = 0;
  2664. this.S = [];
  2665. }
  2666. // Arcfour.prototype.init = ARC4init;
  2667. // Initialize arcfour context from key, an array of ints, each from [0..255]
  2668. Arcfour.prototype.init = function(key) {
  2669. var i;
  2670. var j;
  2671. var t;
  2672. for (i = 0; i < 256; ++i) {
  2673. this.S[i] = i;
  2674. }
  2675. j = 0;
  2676. for (i = 0; i < 256; ++i) {
  2677. j = (j + this.S[i] + key[i % key.length]) & 255;
  2678. t = this.S[i];
  2679. this.S[i] = this.S[j];
  2680. this.S[j] = t;
  2681. }
  2682. this.i = 0;
  2683. this.j = 0;
  2684. };
  2685. // Arcfour.prototype.next = ARC4next;
  2686. Arcfour.prototype.next = function() {
  2687. var t;
  2688. this.i = (this.i + 1) & 255;
  2689. this.j = (this.j + this.S[this.i]) & 255;
  2690. t = this.S[this.i];
  2691. this.S[this.i] = this.S[this.j];
  2692. this.S[this.j] = t;
  2693. return this.S[(t + this.S[this.i]) & 255];
  2694. };
  2695. return Arcfour;
  2696. }());
  2697. // Plug in your RNG constructor here
  2698. function prng_newstate() {
  2699. return new Arcfour();
  2700. }
  2701. // Pool size must be a multiple of 4 and greater than 32.
  2702. // An array of bytes the size of the pool will be passed to init()
  2703. var rng_psize = 256;
  2704. // Random number generator - requires a PRNG backend, e.g. prng4.js
  2705. var rng_state;
  2706. var rng_pool = null;
  2707. var rng_pptr;
  2708. // Initialize the pool with junk if needed.
  2709. if (rng_pool == null) {
  2710. rng_pool = [];
  2711. rng_pptr = 0;
  2712. var t = void 0;
  2713. if (window2.crypto && window2.crypto.getRandomValues) {
  2714. // Extract entropy (2048 bits) from RNG if available
  2715. var z = new Uint32Array(256);
  2716. window2.crypto.getRandomValues(z);
  2717. for (t = 0; t < z.length; ++t) {
  2718. rng_pool[rng_pptr++] = z[t] & 255;
  2719. }
  2720. }
  2721. // Use mouse events for entropy, if we do not have enough entropy by the time
  2722. // we need it, entropy will be generated by Math.random.
  2723. var onMouseMoveListener_1 = function(ev) {
  2724. this.count = this.count || 0;
  2725. if (this.count >= 256 || rng_pptr >= rng_psize) {
  2726. if (window2.removeEventListener) {
  2727. window2.removeEventListener("mousemove", onMouseMoveListener_1, false);
  2728. } else if (window2.detachEvent) {
  2729. window2.detachEvent("onmousemove", onMouseMoveListener_1);
  2730. }
  2731. return;
  2732. }
  2733. try {
  2734. var mouseCoordinates = ev.x + ev.y;
  2735. rng_pool[rng_pptr++] = mouseCoordinates & 255;
  2736. this.count += 1;
  2737. } catch (e) {
  2738. // Sometimes Firefox will deny permission to access event properties for some reason. Ignore.
  2739. }
  2740. };
  2741. if (window2.addEventListener) {
  2742. window2.addEventListener("mousemove", onMouseMoveListener_1, false);
  2743. } else if (window2.attachEvent) {
  2744. window2.attachEvent("onmousemove", onMouseMoveListener_1);
  2745. }
  2746. }
  2747. function rng_get_byte() {
  2748. if (rng_state == null) {
  2749. rng_state = prng_newstate();
  2750. // At this point, we may not have collected enough entropy. If not, fall back to Math.random
  2751. while (rng_pptr < rng_psize) {
  2752. var random = Math.floor(65536 * Math.random());
  2753. rng_pool[rng_pptr++] = random & 255;
  2754. }
  2755. rng_state.init(rng_pool);
  2756. for (rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) {
  2757. rng_pool[rng_pptr] = 0;
  2758. }
  2759. rng_pptr = 0;
  2760. }
  2761. // TODO: allow reseeding after first request
  2762. return rng_state.next();
  2763. }
  2764. var SecureRandom = /** @class */ (function() {
  2765. function SecureRandom() {}
  2766. SecureRandom.prototype.nextBytes = function(ba) {
  2767. for (var i = 0; i < ba.length; ++i) {
  2768. ba[i] = rng_get_byte();
  2769. }
  2770. };
  2771. return SecureRandom;
  2772. }());
  2773. // Depends on jsbn.js and rng.js
  2774. // function linebrk(s,n) {
  2775. // var ret = "";
  2776. // var i = 0;
  2777. // while(i + n < s.length) {
  2778. // ret += s.substring(i,i+n) + "\n";
  2779. // i += n;
  2780. // }
  2781. // return ret + s.substring(i,s.length);
  2782. // }
  2783. // function byte2Hex(b) {
  2784. // if(b < 0x10)
  2785. // return "0" + b.toString(16);
  2786. // else
  2787. // return b.toString(16);
  2788. // }
  2789. function pkcs1pad1(s, n) {
  2790. if (n < s.length + 22) {
  2791. console.error("Message too long for RSA");
  2792. return null;
  2793. }
  2794. var len = n - s.length - 6;
  2795. var filler = "";
  2796. for (var f = 0; f < len; f += 2) {
  2797. filler += "ff";
  2798. }
  2799. var m = "0001" + filler + "00" + s;
  2800. return parseBigInt(m, 16);
  2801. }
  2802. // PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint
  2803. function pkcs1pad2(s, n) {
  2804. if (n < s.length + 11) { // TODO: fix for utf-8
  2805. console.error("Message too long for RSA");
  2806. return null;
  2807. }
  2808. var ba = [];
  2809. var i = s.length - 1;
  2810. while (i >= 0 && n > 0) {
  2811. var c = s.charCodeAt(i--);
  2812. if (c < 128) { // encode using utf-8
  2813. ba[--n] = c;
  2814. } else if ((c > 127) && (c < 2048)) {
  2815. ba[--n] = (c & 63) | 128;
  2816. ba[--n] = (c >> 6) | 192;
  2817. } else {
  2818. ba[--n] = (c & 63) | 128;
  2819. ba[--n] = ((c >> 6) & 63) | 128;
  2820. ba[--n] = (c >> 12) | 224;
  2821. }
  2822. }
  2823. ba[--n] = 0;
  2824. var rng = new SecureRandom();
  2825. var x = [];
  2826. while (n > 2) { // random non-zero pad
  2827. x[0] = 0;
  2828. while (x[0] == 0) {
  2829. rng.nextBytes(x);
  2830. }
  2831. ba[--n] = x[0];
  2832. }
  2833. ba[--n] = 2;
  2834. ba[--n] = 0;
  2835. return new BigInteger(ba);
  2836. }
  2837. // "empty" RSA key constructor
  2838. var RSAKey = /** @class */ (function() {
  2839. function RSAKey() {
  2840. this.n = null;
  2841. this.e = 0;
  2842. this.d = null;
  2843. this.p = null;
  2844. this.q = null;
  2845. this.dmp1 = null;
  2846. this.dmq1 = null;
  2847. this.coeff = null;
  2848. }
  2849. //#region PROTECTED
  2850. // protected
  2851. // RSAKey.prototype.doPublic = RSADoPublic;
  2852. // Perform raw public operation on "x": return x^e (mod n)
  2853. RSAKey.prototype.doPublic = function(x) {
  2854. return x.modPowInt(this.e, this.n);
  2855. };
  2856. // RSAKey.prototype.doPrivate = RSADoPrivate;
  2857. // Perform raw private operation on "x": return x^d (mod n)
  2858. RSAKey.prototype.doPrivate = function(x) {
  2859. console.log('p',this.p,'q',this.q)
  2860. console.log('d',this.d,'n',this.n)
  2861. if (this.p == null || this.q == null) {
  2862. return x.modPow(this.d, this.n);
  2863. }
  2864. // TODO: re-calculate any missing CRT params
  2865. var xp = x.mod(this.p).modPow(this.dmp1, this.p);
  2866. var xq = x.mod(this.q).modPow(this.dmq1, this.q);
  2867. while (xp.compareTo(xq) < 0) {
  2868. xp = xp.add(this.p);
  2869. }
  2870. return xp.subtract(xq).multiply(this.coeff).mod(this.p).multiply(this.q).add(xq);
  2871. };
  2872. //#endregion PROTECTED
  2873. //#region PUBLIC
  2874. // RSAKey.prototype.setPublic = RSASetPublic;
  2875. // Set the public key fields N and e from hex strings
  2876. RSAKey.prototype.setPublic = function(N, E) {
  2877. if (N != null && E != null && N.length > 0 && E.length > 0) {
  2878. this.n = parseBigInt(N, 16);
  2879. this.e = parseInt(E, 16);
  2880. } else {
  2881. console.error("Invalid RSA public key");
  2882. }
  2883. };
  2884. // RSAKey.prototype.encrypt = RSAEncrypt;
  2885. // Return the PKCS#1 RSA encryption of "text" as an even-length hex string
  2886. RSAKey.prototype.encrypt = function(text) {
  2887. var m = pkcs1pad2(text, (this.n.bitLength() + 7) >> 3);
  2888. if (m == null) {
  2889. return null;
  2890. }
  2891. var c = this.doPublic(m);
  2892. if (c == null) {
  2893. return null;
  2894. }
  2895. var h = c.toString(16);
  2896. if ((h.length & 1) == 0) {
  2897. return h;
  2898. } else {
  2899. return "0" + h;
  2900. }
  2901. };
  2902. // RSAKey.prototype.setPrivate = RSASetPrivate;
  2903. // Set the private key fields N, e, and d from hex strings
  2904. RSAKey.prototype.setPrivate = function(N, E, D) {
  2905. if (N != null && E != null && N.length > 0 && E.length > 0) {
  2906. this.n = parseBigInt(N, 16);
  2907. this.e = parseInt(E, 16);
  2908. this.d = parseBigInt(D, 16);
  2909. } else {
  2910. console.error("Invalid RSA private key");
  2911. }
  2912. };
  2913. // RSAKey.prototype.setPrivateEx = RSASetPrivateEx;
  2914. // Set the private key fields N, e, d and CRT params from hex strings
  2915. RSAKey.prototype.setPrivateEx = function(N, E, D, P, Q, DP, DQ, C) {
  2916. if (N != null && E != null && N.length > 0 && E.length > 0) {
  2917. this.n = parseBigInt(N, 16);
  2918. this.e = parseInt(E, 16);
  2919. this.d = parseBigInt(D, 16);
  2920. this.p = parseBigInt(P, 16);
  2921. this.q = parseBigInt(Q, 16);
  2922. this.dmp1 = parseBigInt(DP, 16);
  2923. this.dmq1 = parseBigInt(DQ, 16);
  2924. this.coeff = parseBigInt(C, 16);
  2925. } else {
  2926. console.error("Invalid RSA private key");
  2927. }
  2928. };
  2929. // RSAKey.prototype.generate = RSAGenerate;
  2930. // Generate a new random private key B bits long, using public expt E
  2931. RSAKey.prototype.generate = function(B, E) {
  2932. var rng = new SecureRandom();
  2933. var qs = B >> 1;
  2934. this.e = parseInt(E, 16);
  2935. var ee = new BigInteger(E, 16);
  2936. for (;;) {
  2937. for (;;) {
  2938. this.p = new BigInteger(B - qs, 1, rng);
  2939. if (this.p.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) ==
  2940. 0 && this.p.isProbablePrime(10)) {
  2941. break;
  2942. }
  2943. }
  2944. for (;;) {
  2945. this.q = new BigInteger(qs, 1, rng);
  2946. if (this.q.subtract(BigInteger.ONE).gcd(ee).compareTo(BigInteger.ONE) ==
  2947. 0 && this.q.isProbablePrime(10)) {
  2948. break;
  2949. }
  2950. }
  2951. if (this.p.compareTo(this.q) <= 0) {
  2952. var t = this.p;
  2953. this.p = this.q;
  2954. this.q = t;
  2955. }
  2956. var p1 = this.p.subtract(BigInteger.ONE);
  2957. var q1 = this.q.subtract(BigInteger.ONE);
  2958. var phi = p1.multiply(q1);
  2959. if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
  2960. this.n = this.p.multiply(this.q);
  2961. this.d = ee.modInverse(phi);
  2962. this.dmp1 = this.d.mod(p1);
  2963. this.dmq1 = this.d.mod(q1);
  2964. this.coeff = this.q.modInverse(this.p);
  2965. break;
  2966. }
  2967. }
  2968. };
  2969. // RSAKey.prototype.decrypt = RSADecrypt;
  2970. // Return the PKCS#1 RSA decryption of "ctext".
  2971. // "ctext" is an even-length hex string and the output is a plain string.
  2972. RSAKey.prototype.decrypt = function(ctext) {
  2973. var c = parseBigInt(ctext, 16);
  2974. var m = this.doPrivate(c);
  2975. if (m == null) {
  2976. return null;
  2977. }
  2978. return pkcs1unpad2(m, (this.n.bitLength() + 7) >> 3);
  2979. };
  2980. // Generate a new random private key B bits long, using public expt E
  2981. RSAKey.prototype.generateAsync = function(B, E, callback) {
  2982. var rng = new SecureRandom();
  2983. var qs = B >> 1;
  2984. this.e = parseInt(E, 16);
  2985. var ee = new BigInteger(E, 16);
  2986. var rsa = this;
  2987. // These functions have non-descript names because they were originally for(;;) loops.
  2988. // I don't know about cryptography to give them better names than loop1-4.
  2989. var loop1 = function() {
  2990. var loop4 = function() {
  2991. if (rsa.p.compareTo(rsa.q) <= 0) {
  2992. var t = rsa.p;
  2993. rsa.p = rsa.q;
  2994. rsa.q = t;
  2995. }
  2996. var p1 = rsa.p.subtract(BigInteger.ONE);
  2997. var q1 = rsa.q.subtract(BigInteger.ONE);
  2998. var phi = p1.multiply(q1);
  2999. if (phi.gcd(ee).compareTo(BigInteger.ONE) == 0) {
  3000. rsa.n = rsa.p.multiply(rsa.q);
  3001. rsa.d = ee.modInverse(phi);
  3002. rsa.dmp1 = rsa.d.mod(p1);
  3003. rsa.dmq1 = rsa.d.mod(q1);
  3004. rsa.coeff = rsa.q.modInverse(rsa.p);
  3005. setTimeout(function() {
  3006. callback();
  3007. }, 0); // escape
  3008. } else {
  3009. setTimeout(loop1, 0);
  3010. }
  3011. };
  3012. var loop3 = function() {
  3013. rsa.q = nbi();
  3014. rsa.q.fromNumberAsync(qs, 1, rng, function() {
  3015. rsa.q.subtract(BigInteger.ONE).gcda(ee, function(r) {
  3016. if (r.compareTo(BigInteger.ONE) == 0 && rsa
  3017. .q.isProbablePrime(10)) {
  3018. setTimeout(loop4, 0);
  3019. } else {
  3020. setTimeout(loop3, 0);
  3021. }
  3022. });
  3023. });
  3024. };
  3025. var loop2 = function() {
  3026. rsa.p = nbi();
  3027. rsa.p.fromNumberAsync(B - qs, 1, rng, function() {
  3028. rsa.p.subtract(BigInteger.ONE).gcda(ee, function(r) {
  3029. if (r.compareTo(BigInteger.ONE) == 0 && rsa
  3030. .p.isProbablePrime(10)) {
  3031. setTimeout(loop3, 0);
  3032. } else {
  3033. setTimeout(loop2, 0);
  3034. }
  3035. });
  3036. });
  3037. };
  3038. setTimeout(loop2, 0);
  3039. };
  3040. setTimeout(loop1, 0);
  3041. };
  3042. RSAKey.prototype.sign = function(text, digestMethod, digestName) {
  3043. console.log(digestMethod)
  3044. var header = getDigestHeader(digestName);
  3045. var digest = header + digestMethod(text).toString();
  3046. var m = pkcs1pad1(digest, this.n.bitLength() / 4);
  3047. if (m == null) {
  3048. return null;
  3049. }
  3050. console.log("m",m.toString())
  3051. var c = this.doPrivate(m);
  3052. if (c == null) {
  3053. return null;
  3054. }
  3055. var h = c.toString(16);
  3056. if ((h.length & 1) == 0) {
  3057. return h;
  3058. } else {
  3059. return "0" + h;
  3060. }
  3061. };
  3062. RSAKey.prototype.verify = function(text, signature, digestMethod) {
  3063. var c = parseBigInt(signature, 16);
  3064. var m = this.doPublic(c);
  3065. if (m == null) {
  3066. return null;
  3067. }
  3068. var unpadded = m.toString(16).replace(/^1f+00/, "");
  3069. var digest = removeDigestHeader(unpadded);
  3070. return digest == digestMethod(text).toString();
  3071. };
  3072. return RSAKey;
  3073. }());
  3074. // Undo PKCS#1 (type 2, random) padding and, if valid, return the plaintext
  3075. function pkcs1unpad2(d, n) {
  3076. var b = d.toByteArray();
  3077. var i = 0;
  3078. while (i < b.length && b[i] == 0) {
  3079. ++i;
  3080. }
  3081. if (b.length - i != n - 1 || b[i] != 2) {
  3082. return null;
  3083. }
  3084. ++i;
  3085. while (b[i] != 0) {
  3086. if (++i >= b.length) {
  3087. return null;
  3088. }
  3089. }
  3090. var ret = "";
  3091. while (++i < b.length) {
  3092. var c = b[i] & 255;
  3093. if (c < 128) { // utf-8 decode
  3094. ret += String.fromCharCode(c);
  3095. } else if ((c > 191) && (c < 224)) {
  3096. ret += String.fromCharCode(((c & 31) << 6) | (b[i + 1] & 63));
  3097. ++i;
  3098. } else {
  3099. ret += String.fromCharCode(((c & 15) << 12) | ((b[i + 1] & 63) << 6) | (b[i + 2] & 63));
  3100. i += 2;
  3101. }
  3102. }
  3103. return ret;
  3104. }
  3105. // https://tools.ietf.org/html/rfc3447#page-43
  3106. var DIGEST_HEADERS = {
  3107. md2: "3020300c06082a864886f70d020205000410",
  3108. md5: "3020300c06082a864886f70d020505000410",
  3109. sha1: "3021300906052b0e03021a05000414",
  3110. sha224: "302d300d06096086480165030402040500041c",
  3111. sha256: "3031300d060960864801650304020105000420",
  3112. sha384: "3041300d060960864801650304020205000430",
  3113. sha512: "3051300d060960864801650304020305000440",
  3114. ripemd160: "3021300906052b2403020105000414",
  3115. };
  3116. function getDigestHeader(name) {
  3117. return DIGEST_HEADERS[name] || "";
  3118. }
  3119. function removeDigestHeader(str) {
  3120. for (var name_1 in DIGEST_HEADERS) {
  3121. if (DIGEST_HEADERS.hasOwnProperty(name_1)) {
  3122. var header = DIGEST_HEADERS[name_1];
  3123. var len = header.length;
  3124. if (str.substr(0, len) == header) {
  3125. return str.substr(len);
  3126. }
  3127. }
  3128. }
  3129. return str;
  3130. }
  3131. // Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string
  3132. // function RSAEncryptB64(text) {
  3133. // var h = this.encrypt(text);
  3134. // if(h) return hex2b64(h); else return null;
  3135. // }
  3136. // public
  3137. // RSAKey.prototype.encrypt_b64 = RSAEncryptB64;
  3138. /*!
  3139. Copyright (c) 2011, Yahoo! Inc. All rights reserved.
  3140. Code licensed under the BSD License:
  3141. http://developer.yahoo.com/yui/license.html
  3142. version: 2.9.0
  3143. */
  3144. var YAHOO = {};
  3145. YAHOO.lang = {
  3146. /**
  3147. * Utility to set up the prototype, constructor and superclass properties to
  3148. * support an inheritance strategy that can chain constructors and methods.
  3149. * Static members will not be inherited.
  3150. *
  3151. * @method extend
  3152. * @static
  3153. * @param {Function} subc the object to modify
  3154. * @param {Function} superc the object to inherit
  3155. * @param {Object} overrides additional properties/methods to add to the
  3156. * subclass prototype. These will override the
  3157. * matching items obtained from the superclass
  3158. * if present.
  3159. */
  3160. extend: function(subc, superc, overrides) {
  3161. if (!superc || !subc) {
  3162. throw new Error("YAHOO.lang.extend failed, please check that " +
  3163. "all dependencies are included.");
  3164. }
  3165. var F = function() {};
  3166. F.prototype = superc.prototype;
  3167. subc.prototype = new F();
  3168. subc.prototype.constructor = subc;
  3169. subc.superclass = superc.prototype;
  3170. if (superc.prototype.constructor == Object.prototype.constructor) {
  3171. superc.prototype.constructor = superc;
  3172. }
  3173. if (overrides) {
  3174. var i;
  3175. for (i in overrides) {
  3176. subc.prototype[i] = overrides[i];
  3177. }
  3178. /*
  3179. * IE will not enumerate native functions in a derived object even if the
  3180. * function was overridden. This is a workaround for specific functions
  3181. * we care about on the Object prototype.
  3182. * @property _IEEnumFix
  3183. * @param {Function} r the object to receive the augmentation
  3184. * @param {Function} s the object that supplies the properties to augment
  3185. * @static
  3186. * @private
  3187. */
  3188. var _IEEnumFix = function() {},
  3189. ADD = ["toString", "valueOf"];
  3190. try {
  3191. if (/MSIE/.test(navigator2.userAgent)) {
  3192. _IEEnumFix = function(r, s) {
  3193. for (i = 0; i < ADD.length; i = i + 1) {
  3194. var fname = ADD[i],
  3195. f = s[fname];
  3196. if (typeof f === 'function' && f != Object.prototype[fname]) {
  3197. r[fname] = f;
  3198. }
  3199. }
  3200. };
  3201. }
  3202. } catch (ex) {}
  3203. _IEEnumFix(subc.prototype, overrides);
  3204. }
  3205. }
  3206. };
  3207. /* asn1-1.0.13.js (c) 2013-2017 Kenji Urushima | kjur.github.com/jsrsasign/license
  3208. */
  3209. /**
  3210. * @fileOverview
  3211. * @name asn1-1.0.js
  3212. * @author Kenji Urushima kenji.urushima@gmail.com
  3213. * @version asn1 1.0.13 (2017-Jun-02)
  3214. * @since jsrsasign 2.1
  3215. * @license <a href="https://kjur.github.io/jsrsasign/license/">MIT License</a>
  3216. */
  3217. /**
  3218. * kjur's class library name space
  3219. * <p>
  3220. * This name space provides following name spaces:
  3221. * <ul>
  3222. * <li>{@link KJUR.asn1} - ASN.1 primitive hexadecimal encoder</li>
  3223. * <li>{@link KJUR.asn1.x509} - ASN.1 structure for X.509 certificate and CRL</li>
  3224. * <li>{@link KJUR.crypto} - Java Cryptographic Extension(JCE) style MessageDigest/Signature
  3225. * class and utilities</li>
  3226. * </ul>
  3227. * </p>
  3228. * NOTE: Please ignore method summary and document of this namespace. This caused by a bug of jsdoc2.
  3229. * @name KJUR
  3230. * @namespace kjur's class library name space
  3231. */
  3232. var KJUR = {};
  3233. /**
  3234. * kjur's ASN.1 class library name space
  3235. * <p>
  3236. * This is ITU-T X.690 ASN.1 DER encoder class library and
  3237. * class structure and methods is very similar to
  3238. * org.bouncycastle.asn1 package of
  3239. * well known BouncyCaslte Cryptography Library.
  3240. * <h4>PROVIDING ASN.1 PRIMITIVES</h4>
  3241. * Here are ASN.1 DER primitive classes.
  3242. * <ul>
  3243. * <li>0x01 {@link KJUR.asn1.DERBoolean}</li>
  3244. * <li>0x02 {@link KJUR.asn1.DERInteger}</li>
  3245. * <li>0x03 {@link KJUR.asn1.DERBitString}</li>
  3246. * <li>0x04 {@link KJUR.asn1.DEROctetString}</li>
  3247. * <li>0x05 {@link KJUR.asn1.DERNull}</li>
  3248. * <li>0x06 {@link KJUR.asn1.DERObjectIdentifier}</li>
  3249. * <li>0x0a {@link KJUR.asn1.DEREnumerated}</li>
  3250. * <li>0x0c {@link KJUR.asn1.DERUTF8String}</li>
  3251. * <li>0x12 {@link KJUR.asn1.DERNumericString}</li>
  3252. * <li>0x13 {@link KJUR.asn1.DERPrintableString}</li>
  3253. * <li>0x14 {@link KJUR.asn1.DERTeletexString}</li>
  3254. * <li>0x16 {@link KJUR.asn1.DERIA5String}</li>
  3255. * <li>0x17 {@link KJUR.asn1.DERUTCTime}</li>
  3256. * <li>0x18 {@link KJUR.asn1.DERGeneralizedTime}</li>
  3257. * <li>0x30 {@link KJUR.asn1.DERSequence}</li>
  3258. * <li>0x31 {@link KJUR.asn1.DERSet}</li>
  3259. * </ul>
  3260. * <h4>OTHER ASN.1 CLASSES</h4>
  3261. * <ul>
  3262. * <li>{@link KJUR.asn1.ASN1Object}</li>
  3263. * <li>{@link KJUR.asn1.DERAbstractString}</li>
  3264. * <li>{@link KJUR.asn1.DERAbstractTime}</li>
  3265. * <li>{@link KJUR.asn1.DERAbstractStructured}</li>
  3266. * <li>{@link KJUR.asn1.DERTaggedObject}</li>
  3267. * </ul>
  3268. * <h4>SUB NAME SPACES</h4>
  3269. * <ul>
  3270. * <li>{@link KJUR.asn1.cades} - CAdES long term signature format</li>
  3271. * <li>{@link KJUR.asn1.cms} - Cryptographic Message Syntax</li>
  3272. * <li>{@link KJUR.asn1.csr} - Certificate Signing Request (CSR/PKCS#10)</li>
  3273. * <li>{@link KJUR.asn1.tsp} - RFC 3161 Timestamping Protocol Format</li>
  3274. * <li>{@link KJUR.asn1.x509} - RFC 5280 X.509 certificate and CRL</li>
  3275. * </ul>
  3276. * </p>
  3277. * NOTE: Please ignore method summary and document of this namespace.
  3278. * This caused by a bug of jsdoc2.
  3279. * @name KJUR.asn1
  3280. * @namespace
  3281. */
  3282. if (typeof KJUR.asn1 == "undefined" || !KJUR.asn1) KJUR.asn1 = {};
  3283. /**
  3284. * ASN1 utilities class
  3285. * @name KJUR.asn1.ASN1Util
  3286. * @class ASN1 utilities class
  3287. * @since asn1 1.0.2
  3288. */
  3289. KJUR.asn1.ASN1Util = new function() {
  3290. this.integerToByteHex = function(i) {
  3291. var h = i.toString(16);
  3292. if ((h.length % 2) == 1) h = '0' + h;
  3293. return h;
  3294. };
  3295. this.bigIntToMinTwosComplementsHex = function(bigIntegerValue) {
  3296. var h = bigIntegerValue.toString(16);
  3297. if (h.substr(0, 1) != '-') {
  3298. if (h.length % 2 == 1) {
  3299. h = '0' + h;
  3300. } else {
  3301. if (!h.match(/^[0-7]/)) {
  3302. h = '00' + h;
  3303. }
  3304. }
  3305. } else {
  3306. var hPos = h.substr(1);
  3307. var xorLen = hPos.length;
  3308. if (xorLen % 2 == 1) {
  3309. xorLen += 1;
  3310. } else {
  3311. if (!h.match(/^[0-7]/)) {
  3312. xorLen += 2;
  3313. }
  3314. }
  3315. var hMask = '';
  3316. for (var i = 0; i < xorLen; i++) {
  3317. hMask += 'f';
  3318. }
  3319. var biMask = new BigInteger(hMask, 16);
  3320. var biNeg = biMask.xor(bigIntegerValue).add(BigInteger.ONE);
  3321. h = biNeg.toString(16).replace(/^-/, '');
  3322. }
  3323. return h;
  3324. };
  3325. /**
  3326. * get PEM string from hexadecimal data and header string
  3327. * @name getPEMStringFromHex
  3328. * @memberOf KJUR.asn1.ASN1Util
  3329. * @function
  3330. * @param {String} dataHex hexadecimal string of PEM body
  3331. * @param {String} pemHeader PEM header string (ex. 'RSA PRIVATE KEY')
  3332. * @return {String} PEM formatted string of input data
  3333. * @description
  3334. * This method converts a hexadecimal string to a PEM string with
  3335. * a specified header. Its line break will be CRLF("\r\n").
  3336. * @example
  3337. * var pem = KJUR.asn1.ASN1Util.getPEMStringFromHex('616161', 'RSA PRIVATE KEY');
  3338. * // value of pem will be:
  3339. * -----BEGIN PRIVATE KEY-----
  3340. * YWFh
  3341. * -----END PRIVATE KEY-----
  3342. */
  3343. this.getPEMStringFromHex = function(dataHex, pemHeader) {
  3344. return hextopem(dataHex, pemHeader);
  3345. };
  3346. /**
  3347. * generate ASN1Object specifed by JSON parameters
  3348. * @name newObject
  3349. * @memberOf KJUR.asn1.ASN1Util
  3350. * @function
  3351. * @param {Array} param JSON parameter to generate ASN1Object
  3352. * @return {KJUR.asn1.ASN1Object} generated object
  3353. * @since asn1 1.0.3
  3354. * @description
  3355. * generate any ASN1Object specified by JSON param
  3356. * including ASN.1 primitive or structured.
  3357. * Generally 'param' can be described as follows:
  3358. * <blockquote>
  3359. * {TYPE-OF-ASNOBJ: ASN1OBJ-PARAMETER}
  3360. * </blockquote>
  3361. * 'TYPE-OF-ASN1OBJ' can be one of following symbols:
  3362. * <ul>
  3363. * <li>'bool' - DERBoolean</li>
  3364. * <li>'int' - DERInteger</li>
  3365. * <li>'bitstr' - DERBitString</li>
  3366. * <li>'octstr' - DEROctetString</li>
  3367. * <li>'null' - DERNull</li>
  3368. * <li>'oid' - DERObjectIdentifier</li>
  3369. * <li>'enum' - DEREnumerated</li>
  3370. * <li>'utf8str' - DERUTF8String</li>
  3371. * <li>'numstr' - DERNumericString</li>
  3372. * <li>'prnstr' - DERPrintableString</li>
  3373. * <li>'telstr' - DERTeletexString</li>
  3374. * <li>'ia5str' - DERIA5String</li>
  3375. * <li>'utctime' - DERUTCTime</li>
  3376. * <li>'gentime' - DERGeneralizedTime</li>
  3377. * <li>'seq' - DERSequence</li>
  3378. * <li>'set' - DERSet</li>
  3379. * <li>'tag' - DERTaggedObject</li>
  3380. * </ul>
  3381. * @example
  3382. * newObject({'prnstr': 'aaa'});
  3383. * newObject({'seq': [{'int': 3}, {'prnstr': 'aaa'}]})
  3384. * // ASN.1 Tagged Object
  3385. * newObject({'tag': {'tag': 'a1',
  3386. * 'explicit': true,
  3387. * 'obj': {'seq': [{'int': 3}, {'prnstr': 'aaa'}]}}});
  3388. * // more simple representation of ASN.1 Tagged Object
  3389. * newObject({'tag': ['a1',
  3390. * true,
  3391. * {'seq': [
  3392. * {'int': 3},
  3393. * {'prnstr': 'aaa'}]}
  3394. * ]});
  3395. */
  3396. this.newObject = function(param) {
  3397. var _KJUR = KJUR,
  3398. _KJUR_asn1 = _KJUR.asn1,
  3399. _DERBoolean = _KJUR_asn1.DERBoolean,
  3400. _DERInteger = _KJUR_asn1.DERInteger,
  3401. _DERBitString = _KJUR_asn1.DERBitString,
  3402. _DEROctetString = _KJUR_asn1.DEROctetString,
  3403. _DERNull = _KJUR_asn1.DERNull,
  3404. _DERObjectIdentifier = _KJUR_asn1.DERObjectIdentifier,
  3405. _DEREnumerated = _KJUR_asn1.DEREnumerated,
  3406. _DERUTF8String = _KJUR_asn1.DERUTF8String,
  3407. _DERNumericString = _KJUR_asn1.DERNumericString,
  3408. _DERPrintableString = _KJUR_asn1.DERPrintableString,
  3409. _DERTeletexString = _KJUR_asn1.DERTeletexString,
  3410. _DERIA5String = _KJUR_asn1.DERIA5String,
  3411. _DERUTCTime = _KJUR_asn1.DERUTCTime,
  3412. _DERGeneralizedTime = _KJUR_asn1.DERGeneralizedTime,
  3413. _DERSequence = _KJUR_asn1.DERSequence,
  3414. _DERSet = _KJUR_asn1.DERSet,
  3415. _DERTaggedObject = _KJUR_asn1.DERTaggedObject,
  3416. _newObject = _KJUR_asn1.ASN1Util.newObject;
  3417. var keys = Object.keys(param);
  3418. if (keys.length != 1)
  3419. throw "key of param shall be only one.";
  3420. var key = keys[0];
  3421. if (":bool:int:bitstr:octstr:null:oid:enum:utf8str:numstr:prnstr:telstr:ia5str:utctime:gentime:seq:set:tag:"
  3422. .indexOf(":" + key + ":") == -1)
  3423. throw "undefined key: " + key;
  3424. if (key == "bool") return new _DERBoolean(param[key]);
  3425. if (key == "int") return new _DERInteger(param[key]);
  3426. if (key == "bitstr") return new _DERBitString(param[key]);
  3427. if (key == "octstr") return new _DEROctetString(param[key]);
  3428. if (key == "null") return new _DERNull(param[key]);
  3429. if (key == "oid") return new _DERObjectIdentifier(param[key]);
  3430. if (key == "enum") return new _DEREnumerated(param[key]);
  3431. if (key == "utf8str") return new _DERUTF8String(param[key]);
  3432. if (key == "numstr") return new _DERNumericString(param[key]);
  3433. if (key == "prnstr") return new _DERPrintableString(param[key]);
  3434. if (key == "telstr") return new _DERTeletexString(param[key]);
  3435. if (key == "ia5str") return new _DERIA5String(param[key]);
  3436. if (key == "utctime") return new _DERUTCTime(param[key]);
  3437. if (key == "gentime") return new _DERGeneralizedTime(param[key]);
  3438. if (key == "seq") {
  3439. var paramList = param[key];
  3440. var a = [];
  3441. for (var i = 0; i < paramList.length; i++) {
  3442. var asn1Obj = _newObject(paramList[i]);
  3443. a.push(asn1Obj);
  3444. }
  3445. return new _DERSequence({
  3446. 'array': a
  3447. });
  3448. }
  3449. if (key == "set") {
  3450. var paramList = param[key];
  3451. var a = [];
  3452. for (var i = 0; i < paramList.length; i++) {
  3453. var asn1Obj = _newObject(paramList[i]);
  3454. a.push(asn1Obj);
  3455. }
  3456. return new _DERSet({
  3457. 'array': a
  3458. });
  3459. }
  3460. if (key == "tag") {
  3461. var tagParam = param[key];
  3462. if (Object.prototype.toString.call(tagParam) === '[object Array]' &&
  3463. tagParam.length == 3) {
  3464. var obj = _newObject(tagParam[2]);
  3465. return new _DERTaggedObject({
  3466. tag: tagParam[0],
  3467. explicit: tagParam[1],
  3468. obj: obj
  3469. });
  3470. } else {
  3471. var newParam = {};
  3472. if (tagParam.explicit !== undefined)
  3473. newParam.explicit = tagParam.explicit;
  3474. if (tagParam.tag !== undefined)
  3475. newParam.tag = tagParam.tag;
  3476. if (tagParam.obj === undefined)
  3477. throw "obj shall be specified for 'tag'.";
  3478. newParam.obj = _newObject(tagParam.obj);
  3479. return new _DERTaggedObject(newParam);
  3480. }
  3481. }
  3482. };
  3483. /**
  3484. * get encoded hexadecimal string of ASN1Object specifed by JSON parameters
  3485. * @name jsonToASN1HEX
  3486. * @memberOf KJUR.asn1.ASN1Util
  3487. * @function
  3488. * @param {Array} param JSON parameter to generate ASN1Object
  3489. * @return hexadecimal string of ASN1Object
  3490. * @since asn1 1.0.4
  3491. * @description
  3492. * As for ASN.1 object representation of JSON object,
  3493. * please see {@link newObject}.
  3494. * @example
  3495. * jsonToASN1HEX({'prnstr': 'aaa'});
  3496. */
  3497. this.jsonToASN1HEX = function(param) {
  3498. var asn1Obj = this.newObject(param);
  3499. return asn1Obj.getEncodedHex();
  3500. };
  3501. };
  3502. /**
  3503. * get dot noted oid number string from hexadecimal value of OID
  3504. * @name oidHexToInt
  3505. * @memberOf KJUR.asn1.ASN1Util
  3506. * @function
  3507. * @param {String} hex hexadecimal value of object identifier
  3508. * @return {String} dot noted string of object identifier
  3509. * @since jsrsasign 4.8.3 asn1 1.0.7
  3510. * @description
  3511. * This static method converts from hexadecimal string representation of
  3512. * ASN.1 value of object identifier to oid number string.
  3513. * @example
  3514. * KJUR.asn1.ASN1Util.oidHexToInt('550406') &rarr; "2.5.4.6"
  3515. */
  3516. KJUR.asn1.ASN1Util.oidHexToInt = function(hex) {
  3517. var s = "";
  3518. var i01 = parseInt(hex.substr(0, 2), 16);
  3519. var i0 = Math.floor(i01 / 40);
  3520. var i1 = i01 % 40;
  3521. var s = i0 + "." + i1;
  3522. var binbuf = "";
  3523. for (var i = 2; i < hex.length; i += 2) {
  3524. var value = parseInt(hex.substr(i, 2), 16);
  3525. var bin = ("00000000" + value.toString(2)).slice(-8);
  3526. binbuf = binbuf + bin.substr(1, 7);
  3527. if (bin.substr(0, 1) == "0") {
  3528. var bi = new BigInteger(binbuf, 2);
  3529. s = s + "." + bi.toString(10);
  3530. binbuf = "";
  3531. }
  3532. }
  3533. return s;
  3534. };
  3535. /**
  3536. * get hexadecimal value of object identifier from dot noted oid value
  3537. * @name oidIntToHex
  3538. * @memberOf KJUR.asn1.ASN1Util
  3539. * @function
  3540. * @param {String} oidString dot noted string of object identifier
  3541. * @return {String} hexadecimal value of object identifier
  3542. * @since jsrsasign 4.8.3 asn1 1.0.7
  3543. * @description
  3544. * This static method converts from object identifier value string.
  3545. * to hexadecimal string representation of it.
  3546. * @example
  3547. * KJUR.asn1.ASN1Util.oidIntToHex("2.5.4.6") &rarr; "550406"
  3548. */
  3549. KJUR.asn1.ASN1Util.oidIntToHex = function(oidString) {
  3550. var itox = function(i) {
  3551. var h = i.toString(16);
  3552. if (h.length == 1) h = '0' + h;
  3553. return h;
  3554. };
  3555. var roidtox = function(roid) {
  3556. var h = '';
  3557. var bi = new BigInteger(roid, 10);
  3558. var b = bi.toString(2);
  3559. var padLen = 7 - b.length % 7;
  3560. if (padLen == 7) padLen = 0;
  3561. var bPad = '';
  3562. for (var i = 0; i < padLen; i++) bPad += '0';
  3563. b = bPad + b;
  3564. for (var i = 0; i < b.length - 1; i += 7) {
  3565. var b8 = b.substr(i, 7);
  3566. if (i != b.length - 7) b8 = '1' + b8;
  3567. h += itox(parseInt(b8, 2));
  3568. }
  3569. return h;
  3570. };
  3571. if (!oidString.match(/^[0-9.]+$/)) {
  3572. throw "malformed oid string: " + oidString;
  3573. }
  3574. var h = '';
  3575. var a = oidString.split('.');
  3576. var i0 = parseInt(a[0]) * 40 + parseInt(a[1]);
  3577. h += itox(i0);
  3578. a.splice(0, 2);
  3579. for (var i = 0; i < a.length; i++) {
  3580. h += roidtox(a[i]);
  3581. }
  3582. return h;
  3583. };
  3584. // ********************************************************************
  3585. // Abstract ASN.1 Classes
  3586. // ********************************************************************
  3587. // ********************************************************************
  3588. /**
  3589. * base class for ASN.1 DER encoder object
  3590. * @name KJUR.asn1.ASN1Object
  3591. * @class base class for ASN.1 DER encoder object
  3592. * @property {Boolean} isModified flag whether internal data was changed
  3593. * @property {String} hTLV hexadecimal string of ASN.1 TLV
  3594. * @property {String} hT hexadecimal string of ASN.1 TLV tag(T)
  3595. * @property {String} hL hexadecimal string of ASN.1 TLV length(L)
  3596. * @property {String} hV hexadecimal string of ASN.1 TLV value(V)
  3597. * @description
  3598. */
  3599. KJUR.asn1.ASN1Object = function() {
  3600. var hV = '';
  3601. /**
  3602. * get hexadecimal ASN.1 TLV length(L) bytes from TLV value(V)
  3603. * @name getLengthHexFromValue
  3604. * @memberOf KJUR.asn1.ASN1Object#
  3605. * @function
  3606. * @return {String} hexadecimal string of ASN.1 TLV length(L)
  3607. */
  3608. this.getLengthHexFromValue = function() {
  3609. if (typeof this.hV == "undefined" || this.hV == null) {
  3610. throw "this.hV is null or undefined.";
  3611. }
  3612. if (this.hV.length % 2 == 1) {
  3613. throw "value hex must be even length: n=" + hV.length + ",v=" + this.hV;
  3614. }
  3615. var n = this.hV.length / 2;
  3616. var hN = n.toString(16);
  3617. if (hN.length % 2 == 1) {
  3618. hN = "0" + hN;
  3619. }
  3620. if (n < 128) {
  3621. return hN;
  3622. } else {
  3623. var hNlen = hN.length / 2;
  3624. if (hNlen > 15) {
  3625. throw "ASN.1 length too long to represent by 8x: n = " + n.toString(16);
  3626. }
  3627. var head = 128 + hNlen;
  3628. return head.toString(16) + hN;
  3629. }
  3630. };
  3631. /**
  3632. * get hexadecimal string of ASN.1 TLV bytes
  3633. * @name getEncodedHex
  3634. * @memberOf KJUR.asn1.ASN1Object#
  3635. * @function
  3636. * @return {String} hexadecimal string of ASN.1 TLV
  3637. */
  3638. this.getEncodedHex = function() {
  3639. if (this.hTLV == null || this.isModified) {
  3640. this.hV = this.getFreshValueHex();
  3641. this.hL = this.getLengthHexFromValue();
  3642. this.hTLV = this.hT + this.hL + this.hV;
  3643. this.isModified = false;
  3644. //alert("first time: " + this.hTLV);
  3645. }
  3646. return this.hTLV;
  3647. };
  3648. /**
  3649. * get hexadecimal string of ASN.1 TLV value(V) bytes
  3650. * @name getValueHex
  3651. * @memberOf KJUR.asn1.ASN1Object#
  3652. * @function
  3653. * @return {String} hexadecimal string of ASN.1 TLV value(V) bytes
  3654. */
  3655. this.getValueHex = function() {
  3656. this.getEncodedHex();
  3657. return this.hV;
  3658. };
  3659. this.getFreshValueHex = function() {
  3660. return '';
  3661. };
  3662. };
  3663. // == BEGIN DERAbstractString ================================================
  3664. /**
  3665. * base class for ASN.1 DER string classes
  3666. * @name KJUR.asn1.DERAbstractString
  3667. * @class base class for ASN.1 DER string classes
  3668. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  3669. * @property {String} s internal string of value
  3670. * @extends KJUR.asn1.ASN1Object
  3671. * @description
  3672. * <br/>
  3673. * As for argument 'params' for constructor, you can specify one of
  3674. * following properties:
  3675. * <ul>
  3676. * <li>str - specify initial ASN.1 value(V) by a string</li>
  3677. * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  3678. * </ul>
  3679. * NOTE: 'params' can be omitted.
  3680. */
  3681. KJUR.asn1.DERAbstractString = function(params) {
  3682. KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
  3683. /**
  3684. * get string value of this string object
  3685. * @name getString
  3686. * @memberOf KJUR.asn1.DERAbstractString#
  3687. * @function
  3688. * @return {String} string value of this string object
  3689. */
  3690. this.getString = function() {
  3691. return this.s;
  3692. };
  3693. /**
  3694. * set value by a string
  3695. * @name setString
  3696. * @memberOf KJUR.asn1.DERAbstractString#
  3697. * @function
  3698. * @param {String} newS value by a string to set
  3699. */
  3700. this.setString = function(newS) {
  3701. this.hTLV = null;
  3702. this.isModified = true;
  3703. this.s = newS;
  3704. this.hV = stohex(this.s);
  3705. };
  3706. /**
  3707. * set value by a hexadecimal string
  3708. * @name setStringHex
  3709. * @memberOf KJUR.asn1.DERAbstractString#
  3710. * @function
  3711. * @param {String} newHexString value by a hexadecimal string to set
  3712. */
  3713. this.setStringHex = function(newHexString) {
  3714. this.hTLV = null;
  3715. this.isModified = true;
  3716. this.s = null;
  3717. this.hV = newHexString;
  3718. };
  3719. this.getFreshValueHex = function() {
  3720. return this.hV;
  3721. };
  3722. if (typeof params != "undefined") {
  3723. if (typeof params == "string") {
  3724. this.setString(params);
  3725. } else if (typeof params['str'] != "undefined") {
  3726. this.setString(params['str']);
  3727. } else if (typeof params['hex'] != "undefined") {
  3728. this.setStringHex(params['hex']);
  3729. }
  3730. }
  3731. };
  3732. YAHOO.lang.extend(KJUR.asn1.DERAbstractString, KJUR.asn1.ASN1Object);
  3733. // == END DERAbstractString ================================================
  3734. // == BEGIN DERAbstractTime ==================================================
  3735. /**
  3736. * base class for ASN.1 DER Generalized/UTCTime class
  3737. * @name KJUR.asn1.DERAbstractTime
  3738. * @class base class for ASN.1 DER Generalized/UTCTime class
  3739. * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'})
  3740. * @extends KJUR.asn1.ASN1Object
  3741. * @description
  3742. * @see KJUR.asn1.ASN1Object - superclass
  3743. */
  3744. KJUR.asn1.DERAbstractTime = function(params) {
  3745. KJUR.asn1.DERAbstractTime.superclass.constructor.call(this);
  3746. // --- PRIVATE METHODS --------------------
  3747. this.localDateToUTC = function(d) {
  3748. utc = d.getTime() + (d.getTimezoneOffset() * 60000);
  3749. var utcDate = new Date(utc);
  3750. return utcDate;
  3751. };
  3752. /*
  3753. * format date string by Data object
  3754. * @name formatDate
  3755. * @memberOf KJUR.asn1.AbstractTime;
  3756. * @param {Date} dateObject
  3757. * @param {string} type 'utc' or 'gen'
  3758. * @param {boolean} withMillis flag for with millisections or not
  3759. * @description
  3760. * 'withMillis' flag is supported from asn1 1.0.6.
  3761. */
  3762. this.formatDate = function(dateObject, type, withMillis) {
  3763. var pad = this.zeroPadding;
  3764. var d = this.localDateToUTC(dateObject);
  3765. var year = String(d.getFullYear());
  3766. if (type == 'utc') year = year.substr(2, 2);
  3767. var month = pad(String(d.getMonth() + 1), 2);
  3768. var day = pad(String(d.getDate()), 2);
  3769. var hour = pad(String(d.getHours()), 2);
  3770. var min = pad(String(d.getMinutes()), 2);
  3771. var sec = pad(String(d.getSeconds()), 2);
  3772. var s = year + month + day + hour + min + sec;
  3773. if (withMillis === true) {
  3774. var millis = d.getMilliseconds();
  3775. if (millis != 0) {
  3776. var sMillis = pad(String(millis), 3);
  3777. sMillis = sMillis.replace(/[0]+$/, "");
  3778. s = s + "." + sMillis;
  3779. }
  3780. }
  3781. return s + "Z";
  3782. };
  3783. this.zeroPadding = function(s, len) {
  3784. if (s.length >= len) return s;
  3785. return new Array(len - s.length + 1).join('0') + s;
  3786. };
  3787. // --- PUBLIC METHODS --------------------
  3788. /**
  3789. * get string value of this string object
  3790. * @name getString
  3791. * @memberOf KJUR.asn1.DERAbstractTime#
  3792. * @function
  3793. * @return {String} string value of this time object
  3794. */
  3795. this.getString = function() {
  3796. return this.s;
  3797. };
  3798. /**
  3799. * set value by a string
  3800. * @name setString
  3801. * @memberOf KJUR.asn1.DERAbstractTime#
  3802. * @function
  3803. * @param {String} newS value by a string to set such like "130430235959Z"
  3804. */
  3805. this.setString = function(newS) {
  3806. this.hTLV = null;
  3807. this.isModified = true;
  3808. this.s = newS;
  3809. this.hV = stohex(newS);
  3810. };
  3811. /**
  3812. * set value by a Date object
  3813. * @name setByDateValue
  3814. * @memberOf KJUR.asn1.DERAbstractTime#
  3815. * @function
  3816. * @param {Integer} year year of date (ex. 2013)
  3817. * @param {Integer} month month of date between 1 and 12 (ex. 12)
  3818. * @param {Integer} day day of month
  3819. * @param {Integer} hour hours of date
  3820. * @param {Integer} min minutes of date
  3821. * @param {Integer} sec seconds of date
  3822. */
  3823. this.setByDateValue = function(year, month, day, hour, min, sec) {
  3824. var dateObject = new Date(Date.UTC(year, month - 1, day, hour, min, sec, 0));
  3825. this.setByDate(dateObject);
  3826. };
  3827. this.getFreshValueHex = function() {
  3828. return this.hV;
  3829. };
  3830. };
  3831. YAHOO.lang.extend(KJUR.asn1.DERAbstractTime, KJUR.asn1.ASN1Object);
  3832. // == END DERAbstractTime ==================================================
  3833. // == BEGIN DERAbstractStructured ============================================
  3834. /**
  3835. * base class for ASN.1 DER structured class
  3836. * @name KJUR.asn1.DERAbstractStructured
  3837. * @class base class for ASN.1 DER structured class
  3838. * @property {Array} asn1Array internal array of ASN1Object
  3839. * @extends KJUR.asn1.ASN1Object
  3840. * @description
  3841. * @see KJUR.asn1.ASN1Object - superclass
  3842. */
  3843. KJUR.asn1.DERAbstractStructured = function(params) {
  3844. KJUR.asn1.DERAbstractString.superclass.constructor.call(this);
  3845. /**
  3846. * set value by array of ASN1Object
  3847. * @name setByASN1ObjectArray
  3848. * @memberOf KJUR.asn1.DERAbstractStructured#
  3849. * @function
  3850. * @param {array} asn1ObjectArray array of ASN1Object to set
  3851. */
  3852. this.setByASN1ObjectArray = function(asn1ObjectArray) {
  3853. this.hTLV = null;
  3854. this.isModified = true;
  3855. this.asn1Array = asn1ObjectArray;
  3856. };
  3857. /**
  3858. * append an ASN1Object to internal array
  3859. * @name appendASN1Object
  3860. * @memberOf KJUR.asn1.DERAbstractStructured#
  3861. * @function
  3862. * @param {ASN1Object} asn1Object to add
  3863. */
  3864. this.appendASN1Object = function(asn1Object) {
  3865. this.hTLV = null;
  3866. this.isModified = true;
  3867. this.asn1Array.push(asn1Object);
  3868. };
  3869. this.asn1Array = new Array();
  3870. if (typeof params != "undefined") {
  3871. if (typeof params['array'] != "undefined") {
  3872. this.asn1Array = params['array'];
  3873. }
  3874. }
  3875. };
  3876. YAHOO.lang.extend(KJUR.asn1.DERAbstractStructured, KJUR.asn1.ASN1Object);
  3877. // ********************************************************************
  3878. // ASN.1 Object Classes
  3879. // ********************************************************************
  3880. // ********************************************************************
  3881. /**
  3882. * class for ASN.1 DER Boolean
  3883. * @name KJUR.asn1.DERBoolean
  3884. * @class class for ASN.1 DER Boolean
  3885. * @extends KJUR.asn1.ASN1Object
  3886. * @description
  3887. * @see KJUR.asn1.ASN1Object - superclass
  3888. */
  3889. KJUR.asn1.DERBoolean = function() {
  3890. KJUR.asn1.DERBoolean.superclass.constructor.call(this);
  3891. this.hT = "01";
  3892. this.hTLV = "0101ff";
  3893. };
  3894. YAHOO.lang.extend(KJUR.asn1.DERBoolean, KJUR.asn1.ASN1Object);
  3895. // ********************************************************************
  3896. /**
  3897. * class for ASN.1 DER Integer
  3898. * @name KJUR.asn1.DERInteger
  3899. * @class class for ASN.1 DER Integer
  3900. * @extends KJUR.asn1.ASN1Object
  3901. * @description
  3902. * <br/>
  3903. * As for argument 'params' for constructor, you can specify one of
  3904. * following properties:
  3905. * <ul>
  3906. * <li>int - specify initial ASN.1 value(V) by integer value</li>
  3907. * <li>bigint - specify initial ASN.1 value(V) by BigInteger object</li>
  3908. * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  3909. * </ul>
  3910. * NOTE: 'params' can be omitted.
  3911. */
  3912. KJUR.asn1.DERInteger = function(params) {
  3913. KJUR.asn1.DERInteger.superclass.constructor.call(this);
  3914. this.hT = "02";
  3915. /**
  3916. * set value by Tom Wu's BigInteger object
  3917. * @name setByBigInteger
  3918. * @memberOf KJUR.asn1.DERInteger#
  3919. * @function
  3920. * @param {BigInteger} bigIntegerValue to set
  3921. */
  3922. this.setByBigInteger = function(bigIntegerValue) {
  3923. this.hTLV = null;
  3924. this.isModified = true;
  3925. this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
  3926. };
  3927. /**
  3928. * set value by integer value
  3929. * @name setByInteger
  3930. * @memberOf KJUR.asn1.DERInteger
  3931. * @function
  3932. * @param {Integer} integer value to set
  3933. */
  3934. this.setByInteger = function(intValue) {
  3935. var bi = new BigInteger(String(intValue), 10);
  3936. this.setByBigInteger(bi);
  3937. };
  3938. /**
  3939. * set value by integer value
  3940. * @name setValueHex
  3941. * @memberOf KJUR.asn1.DERInteger#
  3942. * @function
  3943. * @param {String} hexadecimal string of integer value
  3944. * @description
  3945. * <br/>
  3946. * NOTE: Value shall be represented by minimum octet length of
  3947. * two's complement representation.
  3948. * @example
  3949. * new KJUR.asn1.DERInteger(123);
  3950. * new KJUR.asn1.DERInteger({'int': 123});
  3951. * new KJUR.asn1.DERInteger({'hex': '1fad'});
  3952. */
  3953. this.setValueHex = function(newHexString) {
  3954. this.hV = newHexString;
  3955. };
  3956. this.getFreshValueHex = function() {
  3957. return this.hV;
  3958. };
  3959. if (typeof params != "undefined") {
  3960. if (typeof params['bigint'] != "undefined") {
  3961. this.setByBigInteger(params['bigint']);
  3962. } else if (typeof params['int'] != "undefined") {
  3963. this.setByInteger(params['int']);
  3964. } else if (typeof params == "number") {
  3965. this.setByInteger(params);
  3966. } else if (typeof params['hex'] != "undefined") {
  3967. this.setValueHex(params['hex']);
  3968. }
  3969. }
  3970. };
  3971. YAHOO.lang.extend(KJUR.asn1.DERInteger, KJUR.asn1.ASN1Object);
  3972. // ********************************************************************
  3973. /**
  3974. * class for ASN.1 DER encoded BitString primitive
  3975. * @name KJUR.asn1.DERBitString
  3976. * @class class for ASN.1 DER encoded BitString primitive
  3977. * @extends KJUR.asn1.ASN1Object
  3978. * @description
  3979. * <br/>
  3980. * As for argument 'params' for constructor, you can specify one of
  3981. * following properties:
  3982. * <ul>
  3983. * <li>bin - specify binary string (ex. '10111')</li>
  3984. * <li>array - specify array of boolean (ex. [true,false,true,true])</li>
  3985. * <li>hex - specify hexadecimal string of ASN.1 value(V) including unused bits</li>
  3986. * <li>obj - specify {@link KJUR.asn1.ASN1Util.newObject}
  3987. * argument for "BitString encapsulates" structure.</li>
  3988. * </ul>
  3989. * NOTE1: 'params' can be omitted.<br/>
  3990. * NOTE2: 'obj' parameter have been supported since
  3991. * asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25).<br/>
  3992. * @example
  3993. * // default constructor
  3994. * o = new KJUR.asn1.DERBitString();
  3995. * // initialize with binary string
  3996. * o = new KJUR.asn1.DERBitString({bin: "1011"});
  3997. * // initialize with boolean array
  3998. * o = new KJUR.asn1.DERBitString({array: [true,false,true,true]});
  3999. * // initialize with hexadecimal string (04 is unused bits)
  4000. * o = new KJUR.asn1.DEROctetString({hex: "04bac0"});
  4001. * // initialize with ASN1Util.newObject argument for encapsulated
  4002. * o = new KJUR.asn1.DERBitString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}});
  4003. * // above generates a ASN.1 data like this:
  4004. * // BIT STRING, encapsulates {
  4005. * // SEQUENCE {
  4006. * // INTEGER 3
  4007. * // PrintableString 'aaa'
  4008. * // }
  4009. * // }
  4010. */
  4011. KJUR.asn1.DERBitString = function(params) {
  4012. if (params !== undefined && typeof params.obj !== "undefined") {
  4013. var o = KJUR.asn1.ASN1Util.newObject(params.obj);
  4014. params.hex = "00" + o.getEncodedHex();
  4015. }
  4016. KJUR.asn1.DERBitString.superclass.constructor.call(this);
  4017. this.hT = "03";
  4018. /**
  4019. * set ASN.1 value(V) by a hexadecimal string including unused bits
  4020. * @name setHexValueIncludingUnusedBits
  4021. * @memberOf KJUR.asn1.DERBitString#
  4022. * @function
  4023. * @param {String} newHexStringIncludingUnusedBits
  4024. */
  4025. this.setHexValueIncludingUnusedBits = function(newHexStringIncludingUnusedBits) {
  4026. this.hTLV = null;
  4027. this.isModified = true;
  4028. this.hV = newHexStringIncludingUnusedBits;
  4029. };
  4030. /**
  4031. * set ASN.1 value(V) by unused bit and hexadecimal string of value
  4032. * @name setUnusedBitsAndHexValue
  4033. * @memberOf KJUR.asn1.DERBitString#
  4034. * @function
  4035. * @param {Integer} unusedBits
  4036. * @param {String} hValue
  4037. */
  4038. this.setUnusedBitsAndHexValue = function(unusedBits, hValue) {
  4039. if (unusedBits < 0 || 7 < unusedBits) {
  4040. throw "unused bits shall be from 0 to 7: u = " + unusedBits;
  4041. }
  4042. var hUnusedBits = "0" + unusedBits;
  4043. this.hTLV = null;
  4044. this.isModified = true;
  4045. this.hV = hUnusedBits + hValue;
  4046. };
  4047. /**
  4048. * set ASN.1 DER BitString by binary string<br/>
  4049. * @name setByBinaryString
  4050. * @memberOf KJUR.asn1.DERBitString#
  4051. * @function
  4052. * @param {String} binaryString binary value string (i.e. '10111')
  4053. * @description
  4054. * Its unused bits will be calculated automatically by length of
  4055. * 'binaryValue'. <br/>
  4056. * NOTE: Trailing zeros '0' will be ignored.
  4057. * @example
  4058. * o = new KJUR.asn1.DERBitString();
  4059. * o.setByBooleanArray("01011");
  4060. */
  4061. this.setByBinaryString = function(binaryString) {
  4062. binaryString = binaryString.replace(/0+$/, '');
  4063. var unusedBits = 8 - binaryString.length % 8;
  4064. if (unusedBits == 8) unusedBits = 0;
  4065. for (var i = 0; i <= unusedBits; i++) {
  4066. binaryString += '0';
  4067. }
  4068. var h = '';
  4069. for (var i = 0; i < binaryString.length - 1; i += 8) {
  4070. var b = binaryString.substr(i, 8);
  4071. var x = parseInt(b, 2).toString(16);
  4072. if (x.length == 1) x = '0' + x;
  4073. h += x;
  4074. }
  4075. this.hTLV = null;
  4076. this.isModified = true;
  4077. this.hV = '0' + unusedBits + h;
  4078. };
  4079. /**
  4080. * set ASN.1 TLV value(V) by an array of boolean<br/>
  4081. * @name setByBooleanArray
  4082. * @memberOf KJUR.asn1.DERBitString#
  4083. * @function
  4084. * @param {array} booleanArray array of boolean (ex. [true, false, true])
  4085. * @description
  4086. * NOTE: Trailing falses will be ignored in the ASN.1 DER Object.
  4087. * @example
  4088. * o = new KJUR.asn1.DERBitString();
  4089. * o.setByBooleanArray([false, true, false, true, true]);
  4090. */
  4091. this.setByBooleanArray = function(booleanArray) {
  4092. var s = '';
  4093. for (var i = 0; i < booleanArray.length; i++) {
  4094. if (booleanArray[i] == true) {
  4095. s += '1';
  4096. } else {
  4097. s += '0';
  4098. }
  4099. }
  4100. this.setByBinaryString(s);
  4101. };
  4102. /**
  4103. * generate an array of falses with specified length<br/>
  4104. * @name newFalseArray
  4105. * @memberOf KJUR.asn1.DERBitString
  4106. * @function
  4107. * @param {Integer} nLength length of array to generate
  4108. * @return {array} array of boolean falses
  4109. * @description
  4110. * This static method may be useful to initialize boolean array.
  4111. * @example
  4112. * o = new KJUR.asn1.DERBitString();
  4113. * o.newFalseArray(3) &rarr; [false, false, false]
  4114. */
  4115. this.newFalseArray = function(nLength) {
  4116. var a = new Array(nLength);
  4117. for (var i = 0; i < nLength; i++) {
  4118. a[i] = false;
  4119. }
  4120. return a;
  4121. };
  4122. this.getFreshValueHex = function() {
  4123. return this.hV;
  4124. };
  4125. if (typeof params != "undefined") {
  4126. if (typeof params == "string" && params.toLowerCase().match(/^[0-9a-f]+$/)) {
  4127. this.setHexValueIncludingUnusedBits(params);
  4128. } else if (typeof params['hex'] != "undefined") {
  4129. this.setHexValueIncludingUnusedBits(params['hex']);
  4130. } else if (typeof params['bin'] != "undefined") {
  4131. this.setByBinaryString(params['bin']);
  4132. } else if (typeof params['array'] != "undefined") {
  4133. this.setByBooleanArray(params['array']);
  4134. }
  4135. }
  4136. };
  4137. YAHOO.lang.extend(KJUR.asn1.DERBitString, KJUR.asn1.ASN1Object);
  4138. // ********************************************************************
  4139. /**
  4140. * class for ASN.1 DER OctetString<br/>
  4141. * @name KJUR.asn1.DEROctetString
  4142. * @class class for ASN.1 DER OctetString
  4143. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  4144. * @extends KJUR.asn1.DERAbstractString
  4145. * @description
  4146. * This class provides ASN.1 OctetString simple type.<br/>
  4147. * Supported "params" attributes are:
  4148. * <ul>
  4149. * <li>str - to set a string as a value</li>
  4150. * <li>hex - to set a hexadecimal string as a value</li>
  4151. * <li>obj - to set a encapsulated ASN.1 value by JSON object
  4152. * which is defined in {@link KJUR.asn1.ASN1Util.newObject}</li>
  4153. * </ul>
  4154. * NOTE: A parameter 'obj' have been supported
  4155. * for "OCTET STRING, encapsulates" structure.
  4156. * since asn1 1.0.11, jsrsasign 6.1.1 (2016-Sep-25).
  4157. * @see KJUR.asn1.DERAbstractString - superclass
  4158. * @example
  4159. * // default constructor
  4160. * o = new KJUR.asn1.DEROctetString();
  4161. * // initialize with string
  4162. * o = new KJUR.asn1.DEROctetString({str: "aaa"});
  4163. * // initialize with hexadecimal string
  4164. * o = new KJUR.asn1.DEROctetString({hex: "616161"});
  4165. * // initialize with ASN1Util.newObject argument
  4166. * o = new KJUR.asn1.DEROctetString({obj: {seq: [{int: 3}, {prnstr: 'aaa'}]}});
  4167. * // above generates a ASN.1 data like this:
  4168. * // OCTET STRING, encapsulates {
  4169. * // SEQUENCE {
  4170. * // INTEGER 3
  4171. * // PrintableString 'aaa'
  4172. * // }
  4173. * // }
  4174. */
  4175. KJUR.asn1.DEROctetString = function(params) {
  4176. if (params !== undefined && typeof params.obj !== "undefined") {
  4177. var o = KJUR.asn1.ASN1Util.newObject(params.obj);
  4178. params.hex = o.getEncodedHex();
  4179. }
  4180. KJUR.asn1.DEROctetString.superclass.constructor.call(this, params);
  4181. this.hT = "04";
  4182. };
  4183. YAHOO.lang.extend(KJUR.asn1.DEROctetString, KJUR.asn1.DERAbstractString);
  4184. // ********************************************************************
  4185. /**
  4186. * class for ASN.1 DER Null
  4187. * @name KJUR.asn1.DERNull
  4188. * @class class for ASN.1 DER Null
  4189. * @extends KJUR.asn1.ASN1Object
  4190. * @description
  4191. * @see KJUR.asn1.ASN1Object - superclass
  4192. */
  4193. KJUR.asn1.DERNull = function() {
  4194. KJUR.asn1.DERNull.superclass.constructor.call(this);
  4195. this.hT = "05";
  4196. this.hTLV = "0500";
  4197. };
  4198. YAHOO.lang.extend(KJUR.asn1.DERNull, KJUR.asn1.ASN1Object);
  4199. // ********************************************************************
  4200. /**
  4201. * class for ASN.1 DER ObjectIdentifier
  4202. * @name KJUR.asn1.DERObjectIdentifier
  4203. * @class class for ASN.1 DER ObjectIdentifier
  4204. * @param {Array} params associative array of parameters (ex. {'oid': '2.5.4.5'})
  4205. * @extends KJUR.asn1.ASN1Object
  4206. * @description
  4207. * <br/>
  4208. * As for argument 'params' for constructor, you can specify one of
  4209. * following properties:
  4210. * <ul>
  4211. * <li>oid - specify initial ASN.1 value(V) by a oid string (ex. 2.5.4.13)</li>
  4212. * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  4213. * </ul>
  4214. * NOTE: 'params' can be omitted.
  4215. */
  4216. KJUR.asn1.DERObjectIdentifier = function(params) {
  4217. var itox = function(i) {
  4218. var h = i.toString(16);
  4219. if (h.length == 1) h = '0' + h;
  4220. return h;
  4221. };
  4222. var roidtox = function(roid) {
  4223. var h = '';
  4224. var bi = new BigInteger(roid, 10);
  4225. var b = bi.toString(2);
  4226. var padLen = 7 - b.length % 7;
  4227. if (padLen == 7) padLen = 0;
  4228. var bPad = '';
  4229. for (var i = 0; i < padLen; i++) bPad += '0';
  4230. b = bPad + b;
  4231. for (var i = 0; i < b.length - 1; i += 7) {
  4232. var b8 = b.substr(i, 7);
  4233. if (i != b.length - 7) b8 = '1' + b8;
  4234. h += itox(parseInt(b8, 2));
  4235. }
  4236. return h;
  4237. };
  4238. KJUR.asn1.DERObjectIdentifier.superclass.constructor.call(this);
  4239. this.hT = "06";
  4240. /**
  4241. * set value by a hexadecimal string
  4242. * @name setValueHex
  4243. * @memberOf KJUR.asn1.DERObjectIdentifier#
  4244. * @function
  4245. * @param {String} newHexString hexadecimal value of OID bytes
  4246. */
  4247. this.setValueHex = function(newHexString) {
  4248. this.hTLV = null;
  4249. this.isModified = true;
  4250. this.s = null;
  4251. this.hV = newHexString;
  4252. };
  4253. /**
  4254. * set value by a OID string<br/>
  4255. * @name setValueOidString
  4256. * @memberOf KJUR.asn1.DERObjectIdentifier#
  4257. * @function
  4258. * @param {String} oidString OID string (ex. 2.5.4.13)
  4259. * @example
  4260. * o = new KJUR.asn1.DERObjectIdentifier();
  4261. * o.setValueOidString("2.5.4.13");
  4262. */
  4263. this.setValueOidString = function(oidString) {
  4264. if (!oidString.match(/^[0-9.]+$/)) {
  4265. throw "malformed oid string: " + oidString;
  4266. }
  4267. var h = '';
  4268. var a = oidString.split('.');
  4269. var i0 = parseInt(a[0]) * 40 + parseInt(a[1]);
  4270. h += itox(i0);
  4271. a.splice(0, 2);
  4272. for (var i = 0; i < a.length; i++) {
  4273. h += roidtox(a[i]);
  4274. }
  4275. this.hTLV = null;
  4276. this.isModified = true;
  4277. this.s = null;
  4278. this.hV = h;
  4279. };
  4280. /**
  4281. * set value by a OID name
  4282. * @name setValueName
  4283. * @memberOf KJUR.asn1.DERObjectIdentifier#
  4284. * @function
  4285. * @param {String} oidName OID name (ex. 'serverAuth')
  4286. * @since 1.0.1
  4287. * @description
  4288. * OID name shall be defined in 'KJUR.asn1.x509.OID.name2oidList'.
  4289. * Otherwise raise error.
  4290. * @example
  4291. * o = new KJUR.asn1.DERObjectIdentifier();
  4292. * o.setValueName("serverAuth");
  4293. */
  4294. this.setValueName = function(oidName) {
  4295. var oid = KJUR.asn1.x509.OID.name2oid(oidName);
  4296. if (oid !== '') {
  4297. this.setValueOidString(oid);
  4298. } else {
  4299. throw "DERObjectIdentifier oidName undefined: " + oidName;
  4300. }
  4301. };
  4302. this.getFreshValueHex = function() {
  4303. return this.hV;
  4304. };
  4305. if (params !== undefined) {
  4306. if (typeof params === "string") {
  4307. if (params.match(/^[0-2].[0-9.]+$/)) {
  4308. this.setValueOidString(params);
  4309. } else {
  4310. this.setValueName(params);
  4311. }
  4312. } else if (params.oid !== undefined) {
  4313. this.setValueOidString(params.oid);
  4314. } else if (params.hex !== undefined) {
  4315. this.setValueHex(params.hex);
  4316. } else if (params.name !== undefined) {
  4317. this.setValueName(params.name);
  4318. }
  4319. }
  4320. };
  4321. YAHOO.lang.extend(KJUR.asn1.DERObjectIdentifier, KJUR.asn1.ASN1Object);
  4322. // ********************************************************************
  4323. /**
  4324. * class for ASN.1 DER Enumerated
  4325. * @name KJUR.asn1.DEREnumerated
  4326. * @class class for ASN.1 DER Enumerated
  4327. * @extends KJUR.asn1.ASN1Object
  4328. * @description
  4329. * <br/>
  4330. * As for argument 'params' for constructor, you can specify one of
  4331. * following properties:
  4332. * <ul>
  4333. * <li>int - specify initial ASN.1 value(V) by integer value</li>
  4334. * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  4335. * </ul>
  4336. * NOTE: 'params' can be omitted.
  4337. * @example
  4338. * new KJUR.asn1.DEREnumerated(123);
  4339. * new KJUR.asn1.DEREnumerated({int: 123});
  4340. * new KJUR.asn1.DEREnumerated({hex: '1fad'});
  4341. */
  4342. KJUR.asn1.DEREnumerated = function(params) {
  4343. KJUR.asn1.DEREnumerated.superclass.constructor.call(this);
  4344. this.hT = "0a";
  4345. /**
  4346. * set value by Tom Wu's BigInteger object
  4347. * @name setByBigInteger
  4348. * @memberOf KJUR.asn1.DEREnumerated#
  4349. * @function
  4350. * @param {BigInteger} bigIntegerValue to set
  4351. */
  4352. this.setByBigInteger = function(bigIntegerValue) {
  4353. this.hTLV = null;
  4354. this.isModified = true;
  4355. this.hV = KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(bigIntegerValue);
  4356. };
  4357. /**
  4358. * set value by integer value
  4359. * @name setByInteger
  4360. * @memberOf KJUR.asn1.DEREnumerated#
  4361. * @function
  4362. * @param {Integer} integer value to set
  4363. */
  4364. this.setByInteger = function(intValue) {
  4365. var bi = new BigInteger(String(intValue), 10);
  4366. this.setByBigInteger(bi);
  4367. };
  4368. /**
  4369. * set value by integer value
  4370. * @name setValueHex
  4371. * @memberOf KJUR.asn1.DEREnumerated#
  4372. * @function
  4373. * @param {String} hexadecimal string of integer value
  4374. * @description
  4375. * <br/>
  4376. * NOTE: Value shall be represented by minimum octet length of
  4377. * two's complement representation.
  4378. */
  4379. this.setValueHex = function(newHexString) {
  4380. this.hV = newHexString;
  4381. };
  4382. this.getFreshValueHex = function() {
  4383. return this.hV;
  4384. };
  4385. if (typeof params != "undefined") {
  4386. if (typeof params['int'] != "undefined") {
  4387. this.setByInteger(params['int']);
  4388. } else if (typeof params == "number") {
  4389. this.setByInteger(params);
  4390. } else if (typeof params['hex'] != "undefined") {
  4391. this.setValueHex(params['hex']);
  4392. }
  4393. }
  4394. };
  4395. YAHOO.lang.extend(KJUR.asn1.DEREnumerated, KJUR.asn1.ASN1Object);
  4396. // ********************************************************************
  4397. /**
  4398. * class for ASN.1 DER UTF8String
  4399. * @name KJUR.asn1.DERUTF8String
  4400. * @class class for ASN.1 DER UTF8String
  4401. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  4402. * @extends KJUR.asn1.DERAbstractString
  4403. * @description
  4404. * @see KJUR.asn1.DERAbstractString - superclass
  4405. */
  4406. KJUR.asn1.DERUTF8String = function(params) {
  4407. KJUR.asn1.DERUTF8String.superclass.constructor.call(this, params);
  4408. this.hT = "0c";
  4409. };
  4410. YAHOO.lang.extend(KJUR.asn1.DERUTF8String, KJUR.asn1.DERAbstractString);
  4411. // ********************************************************************
  4412. /**
  4413. * class for ASN.1 DER NumericString
  4414. * @name KJUR.asn1.DERNumericString
  4415. * @class class for ASN.1 DER NumericString
  4416. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  4417. * @extends KJUR.asn1.DERAbstractString
  4418. * @description
  4419. * @see KJUR.asn1.DERAbstractString - superclass
  4420. */
  4421. KJUR.asn1.DERNumericString = function(params) {
  4422. KJUR.asn1.DERNumericString.superclass.constructor.call(this, params);
  4423. this.hT = "12";
  4424. };
  4425. YAHOO.lang.extend(KJUR.asn1.DERNumericString, KJUR.asn1.DERAbstractString);
  4426. // ********************************************************************
  4427. /**
  4428. * class for ASN.1 DER PrintableString
  4429. * @name KJUR.asn1.DERPrintableString
  4430. * @class class for ASN.1 DER PrintableString
  4431. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  4432. * @extends KJUR.asn1.DERAbstractString
  4433. * @description
  4434. * @see KJUR.asn1.DERAbstractString - superclass
  4435. */
  4436. KJUR.asn1.DERPrintableString = function(params) {
  4437. KJUR.asn1.DERPrintableString.superclass.constructor.call(this, params);
  4438. this.hT = "13";
  4439. };
  4440. YAHOO.lang.extend(KJUR.asn1.DERPrintableString, KJUR.asn1.DERAbstractString);
  4441. // ********************************************************************
  4442. /**
  4443. * class for ASN.1 DER TeletexString
  4444. * @name KJUR.asn1.DERTeletexString
  4445. * @class class for ASN.1 DER TeletexString
  4446. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  4447. * @extends KJUR.asn1.DERAbstractString
  4448. * @description
  4449. * @see KJUR.asn1.DERAbstractString - superclass
  4450. */
  4451. KJUR.asn1.DERTeletexString = function(params) {
  4452. KJUR.asn1.DERTeletexString.superclass.constructor.call(this, params);
  4453. this.hT = "14";
  4454. };
  4455. YAHOO.lang.extend(KJUR.asn1.DERTeletexString, KJUR.asn1.DERAbstractString);
  4456. // ********************************************************************
  4457. /**
  4458. * class for ASN.1 DER IA5String
  4459. * @name KJUR.asn1.DERIA5String
  4460. * @class class for ASN.1 DER IA5String
  4461. * @param {Array} params associative array of parameters (ex. {'str': 'aaa'})
  4462. * @extends KJUR.asn1.DERAbstractString
  4463. * @description
  4464. * @see KJUR.asn1.DERAbstractString - superclass
  4465. */
  4466. KJUR.asn1.DERIA5String = function(params) {
  4467. KJUR.asn1.DERIA5String.superclass.constructor.call(this, params);
  4468. this.hT = "16";
  4469. };
  4470. YAHOO.lang.extend(KJUR.asn1.DERIA5String, KJUR.asn1.DERAbstractString);
  4471. // ********************************************************************
  4472. /**
  4473. * class for ASN.1 DER UTCTime
  4474. * @name KJUR.asn1.DERUTCTime
  4475. * @class class for ASN.1 DER UTCTime
  4476. * @param {Array} params associative array of parameters (ex. {'str': '130430235959Z'})
  4477. * @extends KJUR.asn1.DERAbstractTime
  4478. * @description
  4479. * <br/>
  4480. * As for argument 'params' for constructor, you can specify one of
  4481. * following properties:
  4482. * <ul>
  4483. * <li>str - specify initial ASN.1 value(V) by a string (ex.'130430235959Z')</li>
  4484. * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  4485. * <li>date - specify Date object.</li>
  4486. * </ul>
  4487. * NOTE: 'params' can be omitted.
  4488. * <h4>EXAMPLES</h4>
  4489. * @example
  4490. * d1 = new KJUR.asn1.DERUTCTime();
  4491. * d1.setString('130430125959Z');
  4492. *
  4493. * d2 = new KJUR.asn1.DERUTCTime({'str': '130430125959Z'});
  4494. * d3 = new KJUR.asn1.DERUTCTime({'date': new Date(Date.UTC(2015, 0, 31, 0, 0, 0, 0))});
  4495. * d4 = new KJUR.asn1.DERUTCTime('130430125959Z');
  4496. */
  4497. KJUR.asn1.DERUTCTime = function(params) {
  4498. KJUR.asn1.DERUTCTime.superclass.constructor.call(this, params);
  4499. this.hT = "17";
  4500. /**
  4501. * set value by a Date object<br/>
  4502. * @name setByDate
  4503. * @memberOf KJUR.asn1.DERUTCTime#
  4504. * @function
  4505. * @param {Date} dateObject Date object to set ASN.1 value(V)
  4506. * @example
  4507. * o = new KJUR.asn1.DERUTCTime();
  4508. * o.setByDate(new Date("2016/12/31"));
  4509. */
  4510. this.setByDate = function(dateObject) {
  4511. this.hTLV = null;
  4512. this.isModified = true;
  4513. this.date = dateObject;
  4514. this.s = this.formatDate(this.date, 'utc');
  4515. this.hV = stohex(this.s);
  4516. };
  4517. this.getFreshValueHex = function() {
  4518. if (typeof this.date == "undefined" && typeof this.s == "undefined") {
  4519. this.date = new Date();
  4520. this.s = this.formatDate(this.date, 'utc');
  4521. this.hV = stohex(this.s);
  4522. }
  4523. return this.hV;
  4524. };
  4525. if (params !== undefined) {
  4526. if (params.str !== undefined) {
  4527. this.setString(params.str);
  4528. } else if (typeof params == "string" && params.match(/^[0-9]{12}Z$/)) {
  4529. this.setString(params);
  4530. } else if (params.hex !== undefined) {
  4531. this.setStringHex(params.hex);
  4532. } else if (params.date !== undefined) {
  4533. this.setByDate(params.date);
  4534. }
  4535. }
  4536. };
  4537. YAHOO.lang.extend(KJUR.asn1.DERUTCTime, KJUR.asn1.DERAbstractTime);
  4538. // ********************************************************************
  4539. /**
  4540. * class for ASN.1 DER GeneralizedTime
  4541. * @name KJUR.asn1.DERGeneralizedTime
  4542. * @class class for ASN.1 DER GeneralizedTime
  4543. * @param {Array} params associative array of parameters (ex. {'str': '20130430235959Z'})
  4544. * @property {Boolean} withMillis flag to show milliseconds or not
  4545. * @extends KJUR.asn1.DERAbstractTime
  4546. * @description
  4547. * <br/>
  4548. * As for argument 'params' for constructor, you can specify one of
  4549. * following properties:
  4550. * <ul>
  4551. * <li>str - specify initial ASN.1 value(V) by a string (ex.'20130430235959Z')</li>
  4552. * <li>hex - specify initial ASN.1 value(V) by a hexadecimal string</li>
  4553. * <li>date - specify Date object.</li>
  4554. * <li>millis - specify flag to show milliseconds (from 1.0.6)</li>
  4555. * </ul>
  4556. * NOTE1: 'params' can be omitted.
  4557. * NOTE2: 'withMillis' property is supported from asn1 1.0.6.
  4558. */
  4559. KJUR.asn1.DERGeneralizedTime = function(params) {
  4560. KJUR.asn1.DERGeneralizedTime.superclass.constructor.call(this, params);
  4561. this.hT = "18";
  4562. this.withMillis = false;
  4563. /**
  4564. * set value by a Date object
  4565. * @name setByDate
  4566. * @memberOf KJUR.asn1.DERGeneralizedTime#
  4567. * @function
  4568. * @param {Date} dateObject Date object to set ASN.1 value(V)
  4569. * @example
  4570. * When you specify UTC time, use 'Date.UTC' method like this:<br/>
  4571. * o1 = new DERUTCTime();
  4572. * o1.setByDate(date);
  4573. *
  4574. * date = new Date(Date.UTC(2015, 0, 31, 23, 59, 59, 0)); #2015JAN31 23:59:59
  4575. */
  4576. this.setByDate = function(dateObject) {
  4577. this.hTLV = null;
  4578. this.isModified = true;
  4579. this.date = dateObject;
  4580. this.s = this.formatDate(this.date, 'gen', this.withMillis);
  4581. this.hV = stohex(this.s);
  4582. };
  4583. this.getFreshValueHex = function() {
  4584. if (this.date === undefined && this.s === undefined) {
  4585. this.date = new Date();
  4586. this.s = this.formatDate(this.date, 'gen', this.withMillis);
  4587. this.hV = stohex(this.s);
  4588. }
  4589. return this.hV;
  4590. };
  4591. if (params !== undefined) {
  4592. if (params.str !== undefined) {
  4593. this.setString(params.str);
  4594. } else if (typeof params == "string" && params.match(/^[0-9]{14}Z$/)) {
  4595. this.setString(params);
  4596. } else if (params.hex !== undefined) {
  4597. this.setStringHex(params.hex);
  4598. } else if (params.date !== undefined) {
  4599. this.setByDate(params.date);
  4600. }
  4601. if (params.millis === true) {
  4602. this.withMillis = true;
  4603. }
  4604. }
  4605. };
  4606. YAHOO.lang.extend(KJUR.asn1.DERGeneralizedTime, KJUR.asn1.DERAbstractTime);
  4607. // ********************************************************************
  4608. /**
  4609. * class for ASN.1 DER Sequence
  4610. * @name KJUR.asn1.DERSequence
  4611. * @class class for ASN.1 DER Sequence
  4612. * @extends KJUR.asn1.DERAbstractStructured
  4613. * @description
  4614. * <br/>
  4615. * As for argument 'params' for constructor, you can specify one of
  4616. * following properties:
  4617. * <ul>
  4618. * <li>array - specify array of ASN1Object to set elements of content</li>
  4619. * </ul>
  4620. * NOTE: 'params' can be omitted.
  4621. */
  4622. KJUR.asn1.DERSequence = function(params) {
  4623. KJUR.asn1.DERSequence.superclass.constructor.call(this, params);
  4624. this.hT = "30";
  4625. this.getFreshValueHex = function() {
  4626. var h = '';
  4627. for (var i = 0; i < this.asn1Array.length; i++) {
  4628. var asn1Obj = this.asn1Array[i];
  4629. h += asn1Obj.getEncodedHex();
  4630. }
  4631. this.hV = h;
  4632. return this.hV;
  4633. };
  4634. };
  4635. YAHOO.lang.extend(KJUR.asn1.DERSequence, KJUR.asn1.DERAbstractStructured);
  4636. // ********************************************************************
  4637. /**
  4638. * class for ASN.1 DER Set
  4639. * @name KJUR.asn1.DERSet
  4640. * @class class for ASN.1 DER Set
  4641. * @extends KJUR.asn1.DERAbstractStructured
  4642. * @description
  4643. * <br/>
  4644. * As for argument 'params' for constructor, you can specify one of
  4645. * following properties:
  4646. * <ul>
  4647. * <li>array - specify array of ASN1Object to set elements of content</li>
  4648. * <li>sortflag - flag for sort (default: true). ASN.1 BER is not sorted in 'SET OF'.</li>
  4649. * </ul>
  4650. * NOTE1: 'params' can be omitted.<br/>
  4651. * NOTE2: sortflag is supported since 1.0.5.
  4652. */
  4653. KJUR.asn1.DERSet = function(params) {
  4654. KJUR.asn1.DERSet.superclass.constructor.call(this, params);
  4655. this.hT = "31";
  4656. this.sortFlag = true; // item shall be sorted only in ASN.1 DER
  4657. this.getFreshValueHex = function() {
  4658. var a = new Array();
  4659. for (var i = 0; i < this.asn1Array.length; i++) {
  4660. var asn1Obj = this.asn1Array[i];
  4661. a.push(asn1Obj.getEncodedHex());
  4662. }
  4663. if (this.sortFlag == true) a.sort();
  4664. this.hV = a.join('');
  4665. return this.hV;
  4666. };
  4667. if (typeof params != "undefined") {
  4668. if (typeof params.sortflag != "undefined" &&
  4669. params.sortflag == false)
  4670. this.sortFlag = false;
  4671. }
  4672. };
  4673. YAHOO.lang.extend(KJUR.asn1.DERSet, KJUR.asn1.DERAbstractStructured);
  4674. // ********************************************************************
  4675. /**
  4676. * class for ASN.1 DER TaggedObject
  4677. * @name KJUR.asn1.DERTaggedObject
  4678. * @class class for ASN.1 DER TaggedObject
  4679. * @extends KJUR.asn1.ASN1Object
  4680. * @description
  4681. * <br/>
  4682. * Parameter 'tagNoNex' is ASN.1 tag(T) value for this object.
  4683. * For example, if you find '[1]' tag in a ASN.1 dump,
  4684. * 'tagNoHex' will be 'a1'.
  4685. * <br/>
  4686. * As for optional argument 'params' for constructor, you can specify *ANY* of
  4687. * following properties:
  4688. * <ul>
  4689. * <li>explicit - specify true if this is explicit tag otherwise false
  4690. * (default is 'true').</li>
  4691. * <li>tag - specify tag (default is 'a0' which means [0])</li>
  4692. * <li>obj - specify ASN1Object which is tagged</li>
  4693. * </ul>
  4694. * @example
  4695. * d1 = new KJUR.asn1.DERUTF8String({'str':'a'});
  4696. * d2 = new KJUR.asn1.DERTaggedObject({'obj': d1});
  4697. * hex = d2.getEncodedHex();
  4698. */
  4699. KJUR.asn1.DERTaggedObject = function(params) {
  4700. KJUR.asn1.DERTaggedObject.superclass.constructor.call(this);
  4701. this.hT = "a0";
  4702. this.hV = '';
  4703. this.isExplicit = true;
  4704. this.asn1Object = null;
  4705. /**
  4706. * set value by an ASN1Object
  4707. * @name setString
  4708. * @memberOf KJUR.asn1.DERTaggedObject#
  4709. * @function
  4710. * @param {Boolean} isExplicitFlag flag for explicit/implicit tag
  4711. * @param {Integer} tagNoHex hexadecimal string of ASN.1 tag
  4712. * @param {ASN1Object} asn1Object ASN.1 to encapsulate
  4713. */
  4714. this.setASN1Object = function(isExplicitFlag, tagNoHex, asn1Object) {
  4715. this.hT = tagNoHex;
  4716. this.isExplicit = isExplicitFlag;
  4717. this.asn1Object = asn1Object;
  4718. if (this.isExplicit) {
  4719. this.hV = this.asn1Object.getEncodedHex();
  4720. this.hTLV = null;
  4721. this.isModified = true;
  4722. } else {
  4723. this.hV = null;
  4724. this.hTLV = asn1Object.getEncodedHex();
  4725. this.hTLV = this.hTLV.replace(/^../, tagNoHex);
  4726. this.isModified = false;
  4727. }
  4728. };
  4729. this.getFreshValueHex = function() {
  4730. return this.hV;
  4731. };
  4732. if (typeof params != "undefined") {
  4733. if (typeof params['tag'] != "undefined") {
  4734. this.hT = params['tag'];
  4735. }
  4736. if (typeof params['explicit'] != "undefined") {
  4737. this.isExplicit = params['explicit'];
  4738. }
  4739. if (typeof params['obj'] != "undefined") {
  4740. this.asn1Object = params['obj'];
  4741. this.setASN1Object(this.isExplicit, this.hT, this.asn1Object);
  4742. }
  4743. }
  4744. };
  4745. YAHOO.lang.extend(KJUR.asn1.DERTaggedObject, KJUR.asn1.ASN1Object);
  4746. /**
  4747. * Create a new JSEncryptRSAKey that extends Tom Wu's RSA key object.
  4748. * This object is just a decorator for parsing the key parameter
  4749. * @param {string|Object} key - The key in string format, or an object containing
  4750. * the parameters needed to build a RSAKey object.
  4751. * @constructor
  4752. */
  4753. var JSEncryptRSAKey = /** @class */ (function(_super) {
  4754. __extends(JSEncryptRSAKey, _super);
  4755. function JSEncryptRSAKey(key) {
  4756. var _this = _super.call(this) || this;
  4757. // Call the super constructor.
  4758. // RSAKey.call(this);
  4759. // If a key key was provided.
  4760. if (key) {
  4761. // If this is a string...
  4762. if (typeof key === "string") {
  4763. _this.parseKey(key);
  4764. } else if (JSEncryptRSAKey.hasPrivateKeyProperty(key) ||
  4765. JSEncryptRSAKey.hasPublicKeyProperty(key)) {
  4766. // Set the values for the key.
  4767. _this.parsePropertiesFrom(key);
  4768. }
  4769. }
  4770. return _this;
  4771. }
  4772. /**
  4773. * Method to parse a pem encoded string containing both a public or private key.
  4774. * The method will translate the pem encoded string in a der encoded string and
  4775. * will parse private key and public key parameters. This method accepts public key
  4776. * in the rsaencryption pkcs #1 format (oid: 1.2.840.113549.1.1.1).
  4777. *
  4778. * @todo Check how many rsa formats use the same format of pkcs #1.
  4779. *
  4780. * The format is defined as:
  4781. * PublicKeyInfo ::= SEQUENCE {
  4782. * algorithm AlgorithmIdentifier,
  4783. * PublicKey BIT STRING
  4784. * }
  4785. * Where AlgorithmIdentifier is:
  4786. * AlgorithmIdentifier ::= SEQUENCE {
  4787. * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm
  4788. * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1)
  4789. * }
  4790. * and PublicKey is a SEQUENCE encapsulated in a BIT STRING
  4791. * RSAPublicKey ::= SEQUENCE {
  4792. * modulus INTEGER, -- n
  4793. * publicExponent INTEGER -- e
  4794. * }
  4795. * it's possible to examine the structure of the keys obtained from openssl using
  4796. * an asn.1 dumper as the one used here to parse the components: http://lapo.it/asn1js/
  4797. * @argument {string} pem the pem encoded string, can include the BEGIN/END header/footer
  4798. * @private
  4799. */
  4800. JSEncryptRSAKey.prototype.parseKey = function(pem) {
  4801. try {
  4802. var modulus = 0;
  4803. var public_exponent = 0;
  4804. var reHex = /^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/;
  4805. var der = reHex.test(pem) ? Hex.decode(pem) : Base64.unarmor(pem);
  4806. var asn1 = ASN1.decode(der);
  4807. // Fixes a bug with OpenSSL 1.0+ private keys
  4808. if (asn1.sub.length === 3) {
  4809. asn1 = asn1.sub[2].sub[0];
  4810. }
  4811. if (asn1.sub.length === 9) {
  4812. // Parse the private key.
  4813. modulus = asn1.sub[1].getHexStringValue(); // bigint
  4814. this.n = parseBigInt(modulus, 16);
  4815. public_exponent = asn1.sub[2].getHexStringValue(); // int
  4816. this.e = parseInt(public_exponent, 16);
  4817. var private_exponent = asn1.sub[3].getHexStringValue(); // bigint
  4818. this.d = parseBigInt(private_exponent, 16);
  4819. var prime1 = asn1.sub[4].getHexStringValue(); // bigint
  4820. this.p = parseBigInt(prime1, 16);
  4821. var prime2 = asn1.sub[5].getHexStringValue(); // bigint
  4822. this.q = parseBigInt(prime2, 16);
  4823. var exponent1 = asn1.sub[6].getHexStringValue(); // bigint
  4824. this.dmp1 = parseBigInt(exponent1, 16);
  4825. var exponent2 = asn1.sub[7].getHexStringValue(); // bigint
  4826. this.dmq1 = parseBigInt(exponent2, 16);
  4827. var coefficient = asn1.sub[8].getHexStringValue(); // bigint
  4828. this.coeff = parseBigInt(coefficient, 16);
  4829. } else if (asn1.sub.length === 2) {
  4830. // Parse the public key.
  4831. var bit_string = asn1.sub[1];
  4832. var sequence = bit_string.sub[0];
  4833. modulus = sequence.sub[0].getHexStringValue();
  4834. this.n = parseBigInt(modulus, 16);
  4835. public_exponent = sequence.sub[1].getHexStringValue();
  4836. this.e = parseInt(public_exponent, 16);
  4837. } else {
  4838. return false;
  4839. }
  4840. return true;
  4841. } catch (ex) {
  4842. return false;
  4843. }
  4844. };
  4845. /**
  4846. * Translate rsa parameters in a hex encoded string representing the rsa key.
  4847. *
  4848. * The translation follow the ASN.1 notation :
  4849. * RSAPrivateKey ::= SEQUENCE {
  4850. * version Version,
  4851. * modulus INTEGER, -- n
  4852. * publicExponent INTEGER, -- e
  4853. * privateExponent INTEGER, -- d
  4854. * prime1 INTEGER, -- p
  4855. * prime2 INTEGER, -- q
  4856. * exponent1 INTEGER, -- d mod (p1)
  4857. * exponent2 INTEGER, -- d mod (q-1)
  4858. * coefficient INTEGER, -- (inverse of q) mod p
  4859. * }
  4860. * @returns {string} DER Encoded String representing the rsa private key
  4861. * @private
  4862. */
  4863. JSEncryptRSAKey.prototype.getPrivateBaseKey = function() {
  4864. var options = {
  4865. array: [
  4866. new KJUR.asn1.DERInteger({
  4867. int: 0
  4868. }),
  4869. new KJUR.asn1.DERInteger({
  4870. bigint: this.n
  4871. }),
  4872. new KJUR.asn1.DERInteger({
  4873. int: this.e
  4874. }),
  4875. new KJUR.asn1.DERInteger({
  4876. bigint: this.d
  4877. }),
  4878. new KJUR.asn1.DERInteger({
  4879. bigint: this.p
  4880. }),
  4881. new KJUR.asn1.DERInteger({
  4882. bigint: this.q
  4883. }),
  4884. new KJUR.asn1.DERInteger({
  4885. bigint: this.dmp1
  4886. }),
  4887. new KJUR.asn1.DERInteger({
  4888. bigint: this.dmq1
  4889. }),
  4890. new KJUR.asn1.DERInteger({
  4891. bigint: this.coeff
  4892. })
  4893. ]
  4894. };
  4895. var seq = new KJUR.asn1.DERSequence(options);
  4896. return seq.getEncodedHex();
  4897. };
  4898. /**
  4899. * base64 (pem) encoded version of the DER encoded representation
  4900. * @returns {string} pem encoded representation without header and footer
  4901. * @public
  4902. */
  4903. JSEncryptRSAKey.prototype.getPrivateBaseKeyB64 = function() {
  4904. return hex2b64(this.getPrivateBaseKey());
  4905. };
  4906. /**
  4907. * Translate rsa parameters in a hex encoded string representing the rsa public key.
  4908. * The representation follow the ASN.1 notation :
  4909. * PublicKeyInfo ::= SEQUENCE {
  4910. * algorithm AlgorithmIdentifier,
  4911. * PublicKey BIT STRING
  4912. * }
  4913. * Where AlgorithmIdentifier is:
  4914. * AlgorithmIdentifier ::= SEQUENCE {
  4915. * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm
  4916. * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1)
  4917. * }
  4918. * and PublicKey is a SEQUENCE encapsulated in a BIT STRING
  4919. * RSAPublicKey ::= SEQUENCE {
  4920. * modulus INTEGER, -- n
  4921. * publicExponent INTEGER -- e
  4922. * }
  4923. * @returns {string} DER Encoded String representing the rsa public key
  4924. * @private
  4925. */
  4926. JSEncryptRSAKey.prototype.getPublicBaseKey = function() {
  4927. var first_sequence = new KJUR.asn1.DERSequence({
  4928. array: [
  4929. new KJUR.asn1.DERObjectIdentifier({
  4930. oid: "1.2.840.113549.1.1.1"
  4931. }),
  4932. new KJUR.asn1.DERNull()
  4933. ]
  4934. });
  4935. var second_sequence = new KJUR.asn1.DERSequence({
  4936. array: [
  4937. new KJUR.asn1.DERInteger({
  4938. bigint: this.n
  4939. }),
  4940. new KJUR.asn1.DERInteger({
  4941. int: this.e
  4942. })
  4943. ]
  4944. });
  4945. var bit_string = new KJUR.asn1.DERBitString({
  4946. hex: "00" + second_sequence.getEncodedHex()
  4947. });
  4948. var seq = new KJUR.asn1.DERSequence({
  4949. array: [
  4950. first_sequence,
  4951. bit_string
  4952. ]
  4953. });
  4954. return seq.getEncodedHex();
  4955. };
  4956. /**
  4957. * base64 (pem) encoded version of the DER encoded representation
  4958. * @returns {string} pem encoded representation without header and footer
  4959. * @public
  4960. */
  4961. JSEncryptRSAKey.prototype.getPublicBaseKeyB64 = function() {
  4962. return hex2b64(this.getPublicBaseKey());
  4963. };
  4964. /**
  4965. * wrap the string in block of width chars. The default value for rsa keys is 64
  4966. * characters.
  4967. * @param {string} str the pem encoded string without header and footer
  4968. * @param {Number} [width=64] - the length the string has to be wrapped at
  4969. * @returns {string}
  4970. * @private
  4971. */
  4972. JSEncryptRSAKey.wordwrap = function(str, width) {
  4973. width = width || 64;
  4974. if (!str) {
  4975. return str;
  4976. }
  4977. var regex = "(.{1," + width + "})( +|$\n?)|(.{1," + width + "})";
  4978. return str.match(RegExp(regex, "g")).join("\n");
  4979. };
  4980. /**
  4981. * Retrieve the pem encoded private key
  4982. * @returns {string} the pem encoded private key with header/footer
  4983. * @public
  4984. */
  4985. JSEncryptRSAKey.prototype.getPrivateKey = function() {
  4986. var key = "-----BEGIN RSA PRIVATE KEY-----\n";
  4987. key += JSEncryptRSAKey.wordwrap(this.getPrivateBaseKeyB64()) + "\n";
  4988. key += "-----END RSA PRIVATE KEY-----";
  4989. return key;
  4990. };
  4991. /**
  4992. * Retrieve the pem encoded public key
  4993. * @returns {string} the pem encoded public key with header/footer
  4994. * @public
  4995. */
  4996. JSEncryptRSAKey.prototype.getPublicKey = function() {
  4997. var key = "-----BEGIN PUBLIC KEY-----\n";
  4998. key += JSEncryptRSAKey.wordwrap(this.getPublicBaseKeyB64()) + "\n";
  4999. key += "-----END PUBLIC KEY-----";
  5000. return key;
  5001. };
  5002. /**
  5003. * Check if the object contains the necessary parameters to populate the rsa modulus
  5004. * and public exponent parameters.
  5005. * @param {Object} [obj={}] - An object that may contain the two public key
  5006. * parameters
  5007. * @returns {boolean} true if the object contains both the modulus and the public exponent
  5008. * properties (n and e)
  5009. * @todo check for types of n and e. N should be a parseable bigInt object, E should
  5010. * be a parseable integer number
  5011. * @private
  5012. */
  5013. JSEncryptRSAKey.hasPublicKeyProperty = function(obj) {
  5014. obj = obj || {};
  5015. return (obj.hasOwnProperty("n") &&
  5016. obj.hasOwnProperty("e"));
  5017. };
  5018. /**
  5019. * Check if the object contains ALL the parameters of an RSA key.
  5020. * @param {Object} [obj={}] - An object that may contain nine rsa key
  5021. * parameters
  5022. * @returns {boolean} true if the object contains all the parameters needed
  5023. * @todo check for types of the parameters all the parameters but the public exponent
  5024. * should be parseable bigint objects, the public exponent should be a parseable integer number
  5025. * @private
  5026. */
  5027. JSEncryptRSAKey.hasPrivateKeyProperty = function(obj) {
  5028. obj = obj || {};
  5029. return (obj.hasOwnProperty("n") &&
  5030. obj.hasOwnProperty("e") &&
  5031. obj.hasOwnProperty("d") &&
  5032. obj.hasOwnProperty("p") &&
  5033. obj.hasOwnProperty("q") &&
  5034. obj.hasOwnProperty("dmp1") &&
  5035. obj.hasOwnProperty("dmq1") &&
  5036. obj.hasOwnProperty("coeff"));
  5037. };
  5038. /**
  5039. * Parse the properties of obj in the current rsa object. Obj should AT LEAST
  5040. * include the modulus and public exponent (n, e) parameters.
  5041. * @param {Object} obj - the object containing rsa parameters
  5042. * @private
  5043. */
  5044. JSEncryptRSAKey.prototype.parsePropertiesFrom = function(obj) {
  5045. this.n = obj.n;
  5046. this.e = obj.e;
  5047. if (obj.hasOwnProperty("d")) {
  5048. this.d = obj.d;
  5049. this.p = obj.p;
  5050. this.q = obj.q;
  5051. this.dmp1 = obj.dmp1;
  5052. this.dmq1 = obj.dmq1;
  5053. this.coeff = obj.coeff;
  5054. }
  5055. };
  5056. return JSEncryptRSAKey;
  5057. }(RSAKey));
  5058. /**
  5059. *
  5060. * @param {Object} [options = {}] - An object to customize JSEncrypt behaviour
  5061. * possible parameters are:
  5062. * - default_key_size {number} default: 1024 the key size in bit
  5063. * - default_public_exponent {string} default: '010001' the hexadecimal representation of the public exponent
  5064. * - log {boolean} default: false whether log warn/error or not
  5065. * @constructor
  5066. */
  5067. var JSEncrypt = /** @class */ (function() {
  5068. function JSEncrypt(options) {
  5069. options = options || {};
  5070. this.default_key_size = parseInt(options.default_key_size, 10) || 1024;
  5071. this.default_public_exponent = options.default_public_exponent ||
  5072. "010001"; // 65537 default openssl public exponent for rsa key type
  5073. this.log = options.log || false;
  5074. // The private and public key.
  5075. this.key = null;
  5076. }
  5077. /**
  5078. * Method to set the rsa key parameter (one method is enough to set both the public
  5079. * and the private key, since the private key contains the public key paramenters)
  5080. * Log a warning if logs are enabled
  5081. * @param {Object|string} key the pem encoded string or an object (with or without header/footer)
  5082. * @public
  5083. */
  5084. JSEncrypt.prototype.setKey = function(key) {
  5085. if (this.log && this.key) {
  5086. console.warn("A key was already set, overriding existing.");
  5087. }
  5088. this.key = new JSEncryptRSAKey(key);
  5089. };
  5090. /**
  5091. * Proxy method for setKey, for api compatibility
  5092. * @see setKey
  5093. * @public
  5094. */
  5095. JSEncrypt.prototype.setPrivateKey = function(privkey) {
  5096. // Create the key.
  5097. this.setKey(privkey);
  5098. };
  5099. /**
  5100. * Proxy method for setKey, for api compatibility
  5101. * @see setKey
  5102. * @public
  5103. */
  5104. JSEncrypt.prototype.setPublicKey = function(pubkey) {
  5105. // Sets the public key.
  5106. this.setKey(pubkey);
  5107. };
  5108. /**
  5109. * Proxy method for RSAKey object's decrypt, decrypt the string using the private
  5110. * components of the rsa key object. Note that if the object was not set will be created
  5111. * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor
  5112. * @param {string} str base64 encoded crypted string to decrypt
  5113. * @return {string} the decrypted string
  5114. * @public
  5115. */
  5116. JSEncrypt.prototype.decrypt = function(str) {
  5117. // Return the decrypted string.
  5118. try {
  5119. return this.getKey().decrypt(b64tohex(str));
  5120. } catch (ex) {
  5121. return false;
  5122. }
  5123. };
  5124. /**
  5125. * Proxy method for RSAKey object's encrypt, encrypt the string using the public
  5126. * components of the rsa key object. Note that if the object was not set will be created
  5127. * on the fly (by the getKey method) using the parameters passed in the JSEncrypt constructor
  5128. * @param {string} str the string to encrypt
  5129. * @return {string} the encrypted string encoded in base64
  5130. * @public
  5131. */
  5132. JSEncrypt.prototype.encrypt = function(str) {
  5133. // Return the encrypted string.
  5134. try {
  5135. return hex2b64(this.getKey().encrypt(str));
  5136. } catch (ex) {
  5137. return false;
  5138. }
  5139. };
  5140. /**
  5141. * Proxy method for RSAKey object's sign.
  5142. * @param {string} str the string to sign
  5143. * @param {function} digestMethod hash method
  5144. * @param {string} digestName the name of the hash algorithm
  5145. * @return {string} the signature encoded in base64
  5146. * @public
  5147. */
  5148. JSEncrypt.prototype.sign = function(str, digestMethod, digestName) {
  5149. // return the RSA signature of 'str' in 'hex' format.
  5150. try {
  5151. console.log(arguments)
  5152. return hex2b64(this.getKey().sign(str, digestMethod, digestName));
  5153. } catch (ex) {
  5154. console.log(ex)
  5155. return false;
  5156. }
  5157. };
  5158. /**
  5159. * Proxy method for RSAKey object's verify.
  5160. * @param {string} str the string to verify
  5161. * @param {string} signature the signature encoded in base64 to compare the string to
  5162. * @param {function} digestMethod hash method
  5163. * @return {boolean} whether the data and signature match
  5164. * @public
  5165. */
  5166. JSEncrypt.prototype.verify = function(str, signature, digestMethod) {
  5167. // Return the decrypted 'digest' of the signature.
  5168. try {
  5169. return this.getKey().verify(str, b64tohex(signature), digestMethod);
  5170. } catch (ex) {
  5171. return false;
  5172. }
  5173. };
  5174. /**
  5175. * Getter for the current JSEncryptRSAKey object. If it doesn't exists a new object
  5176. * will be created and returned
  5177. * @param {callback} [cb] the callback to be called if we want the key to be generated
  5178. * in an async fashion
  5179. * @returns {JSEncryptRSAKey} the JSEncryptRSAKey object
  5180. * @public
  5181. */
  5182. JSEncrypt.prototype.getKey = function(cb) {
  5183. // Only create new if it does not exist.
  5184. if (!this.key) {
  5185. // Get a new private key.
  5186. this.key = new JSEncryptRSAKey();
  5187. if (cb && {}.toString.call(cb) === "[object Function]") {
  5188. this.key.generateAsync(this.default_key_size, this.default_public_exponent,
  5189. cb);
  5190. return;
  5191. }
  5192. // Generate the key.
  5193. this.key.generate(this.default_key_size, this.default_public_exponent);
  5194. }
  5195. return this.key;
  5196. };
  5197. /**
  5198. * Returns the pem encoded representation of the private key
  5199. * If the key doesn't exists a new key will be created
  5200. * @returns {string} pem encoded representation of the private key WITH header and footer
  5201. * @public
  5202. */
  5203. JSEncrypt.prototype.getPrivateKey = function() {
  5204. // Return the private representation of this key.
  5205. return this.getKey().getPrivateKey();
  5206. };
  5207. /**
  5208. * Returns the pem encoded representation of the private key
  5209. * If the key doesn't exists a new key will be created
  5210. * @returns {string} pem encoded representation of the private key WITHOUT header and footer
  5211. * @public
  5212. */
  5213. JSEncrypt.prototype.getPrivateKeyB64 = function() {
  5214. // Return the private representation of this key.
  5215. return this.getKey().getPrivateBaseKeyB64();
  5216. };
  5217. /**
  5218. * Returns the pem encoded representation of the public key
  5219. * If the key doesn't exists a new key will be created
  5220. * @returns {string} pem encoded representation of the public key WITH header and footer
  5221. * @public
  5222. */
  5223. JSEncrypt.prototype.getPublicKey = function() {
  5224. // Return the private representation of this key.
  5225. return this.getKey().getPublicKey();
  5226. };
  5227. /**
  5228. * Returns the pem encoded representation of the public key
  5229. * If the key doesn't exists a new key will be created
  5230. * @returns {string} pem encoded representation of the public key WITHOUT header and footer
  5231. * @public
  5232. */
  5233. JSEncrypt.prototype.getPublicKeyB64 = function() {
  5234. // Return the private representation of this key.
  5235. return this.getKey().getPublicBaseKeyB64();
  5236. };
  5237. JSEncrypt.version = "3.0.0-rc.1";
  5238. return JSEncrypt;
  5239. }());
  5240. window2.JSEncrypt = JSEncrypt;
  5241. exports.JSEncrypt = JSEncrypt;
  5242. exports.default = JSEncrypt;
  5243. Object.defineProperty(exports, '__esModule', {
  5244. value: true
  5245. });
  5246. })));