jsencrypt.js 177 KB

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