jsencrypt.js 174 KB

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