jsencryp.js 174 KB

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