openpgp.js 1.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.openpgp = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. (function (global){
  3. "use strict";
  4. !function (e, t) {
  5. "object" == typeof exports && "undefined" != typeof module ? t(exports) : "function" == typeof define && define.amd ? define(["exports"], t) : t((e = e || self).WebStreamsPolyfill = {});
  6. }(undefined, function (e) {
  7. "use strict";
  8. const t = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? Symbol : e => `Symbol(${e})`;const r = "undefined" != typeof self ? self : "undefined" != typeof window ? window : "undefined" != typeof global ? global : void 0,
  9. o = Number.isNaN || function (e) {
  10. return e != e;
  11. };function n(e) {
  12. return "object" == typeof e && null !== e || "function" == typeof e;
  13. }function i(e, t, r) {
  14. Object.defineProperty(e, t, { value: r, writable: !0, enumerable: !0, configurable: !0 });
  15. }function a(e) {
  16. return e.slice();
  17. }function s(e, t, r, o, n) {
  18. new Uint8Array(e).set(new Uint8Array(r, o, n), t);
  19. }function l(e) {
  20. return !1 !== function (e) {
  21. if ("number" != typeof e) return !1;if (o(e)) return !1;if (e < 0) return !1;return !0;
  22. }(e) && e !== 1 / 0;
  23. }function c(e, t, r) {
  24. if ("function" != typeof e) throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e, t, r);
  25. }function u(e, t, r, o) {
  26. const n = e[t];if (void 0 !== n) {
  27. if ("function" != typeof n) throw new TypeError(`${n} is not a method`);switch (r) {case 0:
  28. return () => f(n, e, o);case 1:
  29. return t => {
  30. const r = [t].concat(o);return f(n, e, r);
  31. };}
  32. }return () => Promise.resolve();
  33. }function d(e, t, r) {
  34. const o = e[t];if (void 0 !== o) return c(o, e, r);
  35. }function f(e, t, r) {
  36. try {
  37. return Promise.resolve(c(e, t, r));
  38. } catch (e) {
  39. return Promise.reject(e);
  40. }
  41. }function _(e) {
  42. return e;
  43. }function h(e) {
  44. if (e = Number(e), o(e) || e < 0) throw new RangeError("highWaterMark property of a queuing strategy must be non-negative and non-NaN");return e;
  45. }function b(e) {
  46. if (void 0 === e) return () => 1;if ("function" != typeof e) throw new TypeError("size property of a queuing strategy must be a function");return t => e(t);
  47. }function m(e, t, r) {
  48. return Promise.prototype.then.call(e, t, r);
  49. }function y(e, t, r) {
  50. let o, n;const i = new Promise((e, t) => {
  51. o = e, n = t;
  52. });void 0 === r && (r = e => {
  53. throw e;
  54. });return function (e, t, r) {
  55. let o = !1;const n = e => {
  56. !1 === o && (o = !0, r(e));
  57. };let i = 0,
  58. a = 0;const s = e.length,
  59. l = new Array(s);for (const r of e) {
  60. const e = i;m(r, r => {
  61. l[e] = r, ++a === s && t(l);
  62. }, n), ++i;
  63. }
  64. }(e, e => {
  65. try {
  66. const r = t(e);o(r);
  67. } catch (e) {
  68. n(e);
  69. }
  70. }, e => {
  71. try {
  72. const t = r(e);o(t);
  73. } catch (e) {
  74. n(e);
  75. }
  76. }), i;
  77. }function p(e) {}function w(e) {
  78. e && e instanceof p.AssertionError && setTimeout(() => {
  79. throw e;
  80. }, 0);
  81. }function g(e) {
  82. const t = e._queue.shift();return e._queueTotalSize -= t.size, e._queueTotalSize < 0 && (e._queueTotalSize = 0), t.value;
  83. }function S(e, t, r) {
  84. if (!l(r = Number(r))) throw new RangeError("Size must be a finite, non-NaN, non-negative number.");e._queue.push({ value: t, size: r }), e._queueTotalSize += r;
  85. }function v(e) {
  86. e._queue = [], e._queueTotalSize = 0;
  87. }p.AssertionError = function () {};const R = t("[[AbortSteps]]"),
  88. P = t("[[ErrorSteps]]");class WritableStream {
  89. constructor(e = {}, t = {}) {
  90. q(this);const r = t.size;let o = t.highWaterMark;if (void 0 !== e.type) throw new RangeError("Invalid type is specified");const n = b(r);void 0 === o && (o = 1), function (e, t, r, o) {
  91. const n = Object.create(WritableStreamDefaultController.prototype);const i = u(t, "write", 1, [n]),
  92. a = u(t, "close", 0, []),
  93. s = u(t, "abort", 1, []);$(e, n, function () {
  94. return d(t, "start", [n]);
  95. }, i, a, s, r, o);
  96. }(this, e, o = h(o), n);
  97. }get locked() {
  98. if (!1 === E(this)) throw G("locked");return C(this);
  99. }abort(e) {
  100. return !1 === E(this) ? Promise.reject(G("abort")) : !0 === C(this) ? Promise.reject(new TypeError("Cannot abort a stream that already has a writer")) : j(this, e);
  101. }getWriter() {
  102. if (!1 === E(this)) throw G("getWriter");return T(this);
  103. }
  104. }function T(e) {
  105. return new WritableStreamDefaultWriter(e);
  106. }function q(e) {
  107. e._state = "writable", e._storedError = void 0, e._writer = void 0, e._writableStreamController = void 0, e._writeRequests = [], e._inFlightWriteRequest = void 0, e._closeRequest = void 0, e._inFlightCloseRequest = void 0, e._pendingAbortRequest = void 0, e._backpressure = !1;
  108. }function E(e) {
  109. return !!n(e) && !!Object.prototype.hasOwnProperty.call(e, "_writableStreamController");
  110. }function C(e) {
  111. return void 0 !== e._writer;
  112. }function j(e, t) {
  113. const r = e._state;if ("closed" === r || "errored" === r) return Promise.resolve(void 0);if (void 0 !== e._pendingAbortRequest) return e._pendingAbortRequest._promise;let o = !1;"erroring" === r && (o = !0, t = void 0);const n = new Promise((r, n) => {
  114. e._pendingAbortRequest = { _promise: void 0, _resolve: r, _reject: n, _reason: t, _wasAlreadyErroring: o };
  115. });return e._pendingAbortRequest._promise = n, !1 === o && W(e, t), n;
  116. }function A(e, t) {
  117. "writable" !== e._state ? B(e) : W(e, t);
  118. }function W(e, t) {
  119. const r = e._writableStreamController;e._state = "erroring", e._storedError = t;const o = e._writer;void 0 !== o && D(o, t), !1 === function (e) {
  120. if (void 0 === e._inFlightWriteRequest && void 0 === e._inFlightCloseRequest) return !1;return !0;
  121. }(e) && !0 === r._started && B(e);
  122. }function B(e) {
  123. e._state = "errored", e._writableStreamController[P]();const t = e._storedError;for (const r of e._writeRequests) r._reject(t);if (e._writeRequests = [], void 0 === e._pendingAbortRequest) return void z(e);const r = e._pendingAbortRequest;if (e._pendingAbortRequest = void 0, !0 === r._wasAlreadyErroring) return r._reject(t), void z(e);e._writableStreamController[R](r._reason).then(() => {
  124. r._resolve(), z(e);
  125. }, t => {
  126. r._reject(t), z(e);
  127. });
  128. }function O(e) {
  129. return void 0 !== e._closeRequest || void 0 !== e._inFlightCloseRequest;
  130. }function z(e) {
  131. void 0 !== e._closeRequest && (e._closeRequest._reject(e._storedError), e._closeRequest = void 0);const t = e._writer;void 0 !== t && ee(t, e._storedError);
  132. }function k(e, t) {
  133. const r = e._writer;void 0 !== r && t !== e._backpressure && (!0 === t ? function (e) {
  134. re(e);
  135. }(r) : ae(r)), e._backpressure = t;
  136. }class WritableStreamDefaultWriter {
  137. constructor(e) {
  138. if (!1 === E(e)) throw new TypeError("WritableStreamDefaultWriter can only be constructed with a WritableStream instance");if (!0 === C(e)) throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream = e, e._writer = this;const t = e._state;if ("writable" === t) !1 === O(e) && !0 === e._backpressure ? re(this) : ne(this), X(this);else if ("erroring" === t) oe(this, e._storedError), X(this);else if ("closed" === t) ne(this), function (e) {
  139. X(e), te(e);
  140. }(this);else {
  141. const t = e._storedError;oe(this, t), Z(this, t);
  142. }
  143. }get closed() {
  144. return !1 === F(this) ? Promise.reject(J("closed")) : this._closedPromise;
  145. }get desiredSize() {
  146. if (!1 === F(this)) throw J("desiredSize");if (void 0 === this._ownerWritableStream) throw K("desiredSize");return function (e) {
  147. const t = e._ownerWritableStream,
  148. r = t._state;if ("errored" === r || "erroring" === r) return null;if ("closed" === r) return 0;return Q(t._writableStreamController);
  149. }(this);
  150. }get ready() {
  151. return !1 === F(this) ? Promise.reject(J("ready")) : this._readyPromise;
  152. }abort(e) {
  153. return !1 === F(this) ? Promise.reject(J("abort")) : void 0 === this._ownerWritableStream ? Promise.reject(K("abort")) : function (e, t) {
  154. return j(e._ownerWritableStream, t);
  155. }(this, e);
  156. }close() {
  157. if (!1 === F(this)) return Promise.reject(J("close"));const e = this._ownerWritableStream;return void 0 === e ? Promise.reject(K("close")) : !0 === O(e) ? Promise.reject(new TypeError("cannot close an already-closing stream")) : L(this);
  158. }releaseLock() {
  159. if (!1 === F(this)) throw J("releaseLock");void 0 !== this._ownerWritableStream && M(this);
  160. }write(e) {
  161. return !1 === F(this) ? Promise.reject(J("write")) : void 0 === this._ownerWritableStream ? Promise.reject(K("write to")) : Y(this, e);
  162. }
  163. }function F(e) {
  164. return !!n(e) && !!Object.prototype.hasOwnProperty.call(e, "_ownerWritableStream");
  165. }function L(e) {
  166. const t = e._ownerWritableStream,
  167. r = t._state;if ("closed" === r || "errored" === r) return Promise.reject(new TypeError(`The stream (in ${r} state) is not in the writable state and cannot be closed`));const o = new Promise((e, r) => {
  168. const o = { _resolve: e, _reject: r };t._closeRequest = o;
  169. });return !0 === t._backpressure && "writable" === r && ae(e), function (e) {
  170. S(e, "close", 0), x(e);
  171. }(t._writableStreamController), o;
  172. }function I(e, t) {
  173. "pending" === e._closedPromiseState ? ee(e, t) : function (e, t) {
  174. Z(e, t);
  175. }(e, t);
  176. }function D(e, t) {
  177. "pending" === e._readyPromiseState ? ie(e, t) : function (e, t) {
  178. oe(e, t);
  179. }(e, t);
  180. }function M(e) {
  181. const t = e._ownerWritableStream,
  182. r = new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");D(e, r), I(e, r), t._writer = void 0, e._ownerWritableStream = void 0;
  183. }function Y(e, t) {
  184. const r = e._ownerWritableStream,
  185. o = r._writableStreamController,
  186. n = function (e, t) {
  187. try {
  188. return e._strategySizeAlgorithm(t);
  189. } catch (t) {
  190. return H(e, t), 1;
  191. }
  192. }(o, t);if (r !== e._ownerWritableStream) return Promise.reject(K("write to"));const i = r._state;if ("errored" === i) return Promise.reject(r._storedError);if (!0 === O(r) || "closed" === i) return Promise.reject(new TypeError("The stream is closing or closed and cannot be written to"));if ("erroring" === i) return Promise.reject(r._storedError);const a = function (e) {
  193. return new Promise((t, r) => {
  194. const o = { _resolve: t, _reject: r };e._writeRequests.push(o);
  195. });
  196. }(r);return function (e, t, r) {
  197. const o = { chunk: t };try {
  198. S(e, o, r);
  199. } catch (t) {
  200. return void H(e, t);
  201. }const n = e._controlledWritableStream;if (!1 === O(n) && "writable" === n._state) {
  202. const t = U(e);k(n, t);
  203. }x(e);
  204. }(o, t, n), a;
  205. }class WritableStreamDefaultController {
  206. constructor() {
  207. throw new TypeError("WritableStreamDefaultController cannot be constructed explicitly");
  208. }error(e) {
  209. if (!1 === function (e) {
  210. if (!n(e)) return !1;if (!Object.prototype.hasOwnProperty.call(e, "_controlledWritableStream")) return !1;return !0;
  211. }(this)) throw new TypeError("WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController");"writable" === this._controlledWritableStream._state && V(this, e);
  212. }[R](e) {
  213. const t = this._abortAlgorithm(e);return N(this), t;
  214. }[P]() {
  215. v(this);
  216. }
  217. }function $(e, t, r, o, n, i, a, s) {
  218. t._controlledWritableStream = e, e._writableStreamController = t, t._queue = void 0, t._queueTotalSize = void 0, v(t), t._started = !1, t._strategySizeAlgorithm = s, t._strategyHWM = a, t._writeAlgorithm = o, t._closeAlgorithm = n, t._abortAlgorithm = i;const l = U(t);k(e, l);const c = r();Promise.resolve(c).then(() => {
  219. t._started = !0, x(t);
  220. }, r => {
  221. t._started = !0, A(e, r);
  222. }).catch(w);
  223. }function N(e) {
  224. e._writeAlgorithm = void 0, e._closeAlgorithm = void 0, e._abortAlgorithm = void 0, e._strategySizeAlgorithm = void 0;
  225. }function Q(e) {
  226. return e._strategyHWM - e._queueTotalSize;
  227. }function x(e) {
  228. const t = e._controlledWritableStream;if (!1 === e._started) return;if (void 0 !== t._inFlightWriteRequest) return;const r = t._state;if ("closed" === r || "errored" === r) return;if ("erroring" === r) return void B(t);if (0 === e._queue.length) return;const o = function (e) {
  229. return e._queue[0].value;
  230. }(e);"close" === o ? function (e) {
  231. const t = e._controlledWritableStream;(function (e) {
  232. e._inFlightCloseRequest = e._closeRequest, e._closeRequest = void 0;
  233. })(t), g(e);const r = e._closeAlgorithm();N(e), r.then(() => {
  234. !function (e) {
  235. e._inFlightCloseRequest._resolve(void 0), e._inFlightCloseRequest = void 0, "erroring" === e._state && (e._storedError = void 0, void 0 !== e._pendingAbortRequest && (e._pendingAbortRequest._resolve(), e._pendingAbortRequest = void 0)), e._state = "closed";const t = e._writer;void 0 !== t && te(t);
  236. }(t);
  237. }, e => {
  238. !function (e, t) {
  239. e._inFlightCloseRequest._reject(t), e._inFlightCloseRequest = void 0, void 0 !== e._pendingAbortRequest && (e._pendingAbortRequest._reject(t), e._pendingAbortRequest = void 0), A(e, t);
  240. }(t, e);
  241. }).catch(w);
  242. }(e) : function (e, t) {
  243. const r = e._controlledWritableStream;(function (e) {
  244. e._inFlightWriteRequest = e._writeRequests.shift();
  245. })(r), e._writeAlgorithm(t).then(() => {
  246. !function (e) {
  247. e._inFlightWriteRequest._resolve(void 0), e._inFlightWriteRequest = void 0;
  248. }(r);const t = r._state;if (g(e), !1 === O(r) && "writable" === t) {
  249. const t = U(e);k(r, t);
  250. }x(e);
  251. }, t => {
  252. "writable" === r._state && N(e), function (e, t) {
  253. e._inFlightWriteRequest._reject(t), e._inFlightWriteRequest = void 0, A(e, t);
  254. }(r, t);
  255. }).catch(w);
  256. }(e, o.chunk);
  257. }function H(e, t) {
  258. "writable" === e._controlledWritableStream._state && V(e, t);
  259. }function U(e) {
  260. return Q(e) <= 0;
  261. }function V(e, t) {
  262. const r = e._controlledWritableStream;N(e), W(r, t);
  263. }function G(e) {
  264. return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`);
  265. }function J(e) {
  266. return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`);
  267. }function K(e) {
  268. return new TypeError("Cannot " + e + " a stream using a released writer");
  269. }function X(e) {
  270. e._closedPromise = new Promise((t, r) => {
  271. e._closedPromise_resolve = t, e._closedPromise_reject = r, e._closedPromiseState = "pending";
  272. });
  273. }function Z(e, t) {
  274. X(e), ee(e, t);
  275. }function ee(e, t) {
  276. e._closedPromise.catch(() => {}), e._closedPromise_reject(t), e._closedPromise_resolve = void 0, e._closedPromise_reject = void 0, e._closedPromiseState = "rejected";
  277. }function te(e) {
  278. e._closedPromise_resolve(void 0), e._closedPromise_resolve = void 0, e._closedPromise_reject = void 0, e._closedPromiseState = "resolved";
  279. }function re(e) {
  280. e._readyPromise = new Promise((t, r) => {
  281. e._readyPromise_resolve = t, e._readyPromise_reject = r;
  282. }), e._readyPromiseState = "pending";
  283. }function oe(e, t) {
  284. re(e), ie(e, t);
  285. }function ne(e) {
  286. re(e), ae(e);
  287. }function ie(e, t) {
  288. e._readyPromise.catch(() => {}), e._readyPromise_reject(t), e._readyPromise_resolve = void 0, e._readyPromise_reject = void 0, e._readyPromiseState = "rejected";
  289. }function ae(e) {
  290. e._readyPromise_resolve(void 0), e._readyPromise_resolve = void 0, e._readyPromise_reject = void 0, e._readyPromiseState = "fulfilled";
  291. }const se = Number.isInteger || function (e) {
  292. return "number" == typeof e && isFinite(e) && Math.floor(e) === e;
  293. },
  294. le = t("[[CancelSteps]]"),
  295. ce = t("[[PullSteps]]");class ReadableStream {
  296. constructor(e = {}, t = {}) {
  297. fe(this);const r = t.size;let o = t.highWaterMark;const n = e.type;if ("bytes" === String(n)) {
  298. if (void 0 !== r) throw new RangeError("The strategy for a byte stream cannot have a size function");void 0 === o && (o = 0), function (e, t, r) {
  299. const o = Object.create(ReadableByteStreamController.prototype);const n = u(t, "pull", 0, [o]),
  300. i = u(t, "cancel", 1, []);let a = t.autoAllocateChunkSize;if (void 0 !== a && (a = Number(a), !1 === se(a) || a <= 0)) throw new RangeError("autoAllocateChunkSize must be a positive integer");!function (e, t, r, o, n, i, a) {
  301. t._controlledReadableByteStream = e, t._pullAgain = !1, t._pulling = !1, He(t), t._queue = t._queueTotalSize = void 0, v(t), t._closeRequested = !1, t._started = !1, t._strategyHWM = h(i), t._pullAlgorithm = o, t._cancelAlgorithm = n, t._autoAllocateChunkSize = a, t._pendingPullIntos = [], e._readableStreamController = t;const s = r();Promise.resolve(s).then(() => {
  302. t._started = !0, xe(t);
  303. }, e => {
  304. nt(t, e);
  305. }).catch(w);
  306. }(e, o, function () {
  307. return d(t, "start", [o]);
  308. }, n, i, r, a);
  309. }(this, e, o = h(o));
  310. } else {
  311. if (void 0 !== n) throw new RangeError("Invalid type is specified");{
  312. const t = b(r);void 0 === o && (o = 1), function (e, t, r, o) {
  313. const n = Object.create(ReadableStreamDefaultController.prototype);const i = u(t, "pull", 0, [n]),
  314. a = u(t, "cancel", 1, []);$e(e, n, function () {
  315. return d(t, "start", [n]);
  316. }, i, a, r, o);
  317. }(this, e, o = h(o), t);
  318. }
  319. }
  320. }get locked() {
  321. if (!1 === _e(this)) throw st("locked");return he(this);
  322. }cancel(e) {
  323. return !1 === _e(this) ? Promise.reject(st("cancel")) : !0 === he(this) ? Promise.reject(new TypeError("Cannot cancel a stream that already has a reader")) : pe(this, e);
  324. }getReader({ mode: e } = {}) {
  325. if (!1 === _e(this)) throw st("getReader");if (void 0 === e) return ue(this);if ("byob" === (e = String(e))) return function (e) {
  326. return new ReadableStreamBYOBReader(e);
  327. }(this);throw new RangeError("Invalid mode is specified");
  328. }pipeThrough({ writable: e, readable: t }, { preventClose: r, preventAbort: o, preventCancel: n, signal: i } = {}) {
  329. if (!1 === _e(this)) throw st("pipeThrough");if (!1 === E(e)) throw new TypeError("writable argument to pipeThrough must be a WritableStream");if (!1 === _e(t)) throw new TypeError("readable argument to pipeThrough must be a ReadableStream");if (r = Boolean(r), o = Boolean(o), n = Boolean(n), void 0 !== i && !at(i)) throw new TypeError("ReadableStream.prototype.pipeThrough's signal option must be an AbortSignal");if (!0 === he(this)) throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if (!0 === C(e)) throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return be(this, e, r, o, n, i).catch(() => {}), t;
  330. }pipeTo(e, { preventClose: t, preventAbort: r, preventCancel: o, signal: n } = {}) {
  331. return !1 === _e(this) ? Promise.reject(st("pipeTo")) : !1 === E(e) ? Promise.reject(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream")) : (t = Boolean(t), r = Boolean(r), o = Boolean(o), void 0 === n || at(n) ? !0 === he(this) ? Promise.reject(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")) : !0 === C(e) ? Promise.reject(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")) : be(this, e, t, r, o, n) : Promise.reject(new TypeError("ReadableStream.prototype.pipeTo's signal option must be an AbortSignal")));
  332. }tee() {
  333. if (!1 === _e(this)) throw st("tee");const e = function (e, t) {
  334. const r = ue(e);let o,
  335. n,
  336. i,
  337. s,
  338. l,
  339. c = !1,
  340. u = !1,
  341. d = !1;const f = new Promise(e => {
  342. l = e;
  343. });function _() {
  344. return Be(r).then(e => {
  345. const t = e.value,
  346. r = e.done;if (!0 === r && !1 === c && (!1 === u && Le(i._readableStreamController), !1 === d && Le(s._readableStreamController), c = !0), !0 === c) return;const o = t,
  347. n = t;!1 === u && Ie(i._readableStreamController, o), !1 === d && Ie(s._readableStreamController, n);
  348. });
  349. }function h() {}return i = de(h, _, function (t) {
  350. if (u = !0, o = t, !0 === d) {
  351. const t = a([o, n]),
  352. r = pe(e, t);l(r);
  353. }return f;
  354. }), s = de(h, _, function (t) {
  355. if (d = !0, n = t, !0 === u) {
  356. const t = a([o, n]),
  357. r = pe(e, t);l(r);
  358. }return f;
  359. }), r._closedPromise.catch(e => {
  360. !0 !== c && (De(i._readableStreamController, e), De(s._readableStreamController, e), c = !0);
  361. }), [i, s];
  362. }(this);return a(e);
  363. }
  364. }function ue(e) {
  365. return new ReadableStreamDefaultReader(e);
  366. }function de(e, t, r, o = 1, n = () => 1) {
  367. const i = Object.create(ReadableStream.prototype);return fe(i), $e(i, Object.create(ReadableStreamDefaultController.prototype), e, t, r, o, n), i;
  368. }function fe(e) {
  369. e._state = "readable", e._reader = void 0, e._storedError = void 0, e._disturbed = !1;
  370. }function _e(e) {
  371. return !!n(e) && !!Object.prototype.hasOwnProperty.call(e, "_readableStreamController");
  372. }function he(e) {
  373. return void 0 !== e._reader;
  374. }function be(e, t, r, o, n, i) {
  375. const a = ue(e),
  376. s = T(t);let l = !1,
  377. c = Promise.resolve();return new Promise((u, d) => {
  378. let f;if (void 0 !== i) {
  379. if (f = () => {
  380. const r = new DOMException("Aborted", "AbortError"),
  381. i = [];!1 === o && i.push(() => "writable" === t._state ? j(t, r) : Promise.resolve()), !1 === n && i.push(() => "readable" === e._state ? pe(e, r) : Promise.resolve()), b(() => y(i.map(e => e()), e => e), !0, r);
  382. }, !0 === i.aborted) return void f();i.addEventListener("abort", f);
  383. }if (h(e, a._closedPromise, e => {
  384. !1 === o ? b(() => j(t, e), !0, e) : m(!0, e);
  385. }), h(t, s._closedPromise, t => {
  386. !1 === n ? b(() => pe(e, t), !0, t) : m(!0, t);
  387. }), function (e, t, r) {
  388. "closed" === e._state ? r() : t.then(r).catch(w);
  389. }(e, a._closedPromise, () => {
  390. !1 === r ? b(() => function (e) {
  391. const t = e._ownerWritableStream,
  392. r = t._state;return !0 === O(t) || "closed" === r ? Promise.resolve() : "errored" === r ? Promise.reject(t._storedError) : L(e);
  393. }(s)) : m();
  394. }), !0 === O(t) || "closed" === t._state) {
  395. const t = new TypeError("the destination writable stream closed before all data could be piped to it");!1 === n ? b(() => pe(e, t), !0, t) : m(!0, t);
  396. }function _() {
  397. const e = c;return c.then(() => e !== c ? _() : void 0);
  398. }function h(e, t, r) {
  399. "errored" === e._state ? r(e._storedError) : t.catch(r).catch(w);
  400. }function b(e, r, o) {
  401. function n() {
  402. e().then(() => p(r, o), e => p(!0, e)).catch(w);
  403. }!0 !== l && (l = !0, "writable" === t._state && !1 === O(t) ? _().then(n) : n());
  404. }function m(e, r) {
  405. !0 !== l && (l = !0, "writable" === t._state && !1 === O(t) ? _().then(() => p(e, r)).catch(w) : p(e, r));
  406. }function p(e, t) {
  407. M(s), We(a), void 0 !== i && i.removeEventListener("abort", f), e ? d(t) : u(void 0);
  408. }new Promise((e, t) => {
  409. !function r(o) {
  410. o ? e() : (!0 === l ? Promise.resolve(!0) : s._readyPromise.then(() => Be(a).then(({ value: e, done: t }) => !0 === t || (c = Y(s, e).catch(() => {}), !1)))).then(r, t);
  411. }(!1);
  412. }).catch(e => {
  413. c = Promise.resolve(), w(e);
  414. });
  415. });
  416. }function me(e, t) {
  417. return new Promise((r, o) => {
  418. const n = { _resolve: r, _reject: o, _forAuthorCode: t };e._reader._readIntoRequests.push(n);
  419. });
  420. }function ye(e, t) {
  421. return new Promise((r, o) => {
  422. const n = { _resolve: r, _reject: o, _forAuthorCode: t };e._reader._readRequests.push(n);
  423. });
  424. }function pe(e, t) {
  425. if (e._disturbed = !0, "closed" === e._state) return Promise.resolve(void 0);if ("errored" === e._state) return Promise.reject(e._storedError);return we(e), e._readableStreamController[le](t).then(() => void 0);
  426. }function we(e) {
  427. e._state = "closed";const t = e._reader;if (void 0 !== t) {
  428. if (Ce(t)) {
  429. for (const _ref of t._readRequests) {
  430. const e = _ref._resolve;
  431. const r = _ref._forAuthorCode;
  432. e(ge(void 0, !0, r));
  433. }t._readRequests = [];
  434. }_t(t);
  435. }
  436. }function ge(e, t, r) {
  437. let o = null;!0 === r && (o = Object.prototype);const n = Object.create(o);return Object.defineProperty(n, "value", { value: e, enumerable: !0, writable: !0, configurable: !0 }), Object.defineProperty(n, "done", { value: t, enumerable: !0, writable: !0, configurable: !0 }), n;
  438. }function Se(e, t) {
  439. e._state = "errored", e._storedError = t;const r = e._reader;if (void 0 !== r) {
  440. if (Ce(r)) {
  441. for (const e of r._readRequests) e._reject(t);r._readRequests = [];
  442. } else {
  443. for (const e of r._readIntoRequests) e._reject(t);r._readIntoRequests = [];
  444. }ft(r, t);
  445. }
  446. }function ve(e, t, r) {
  447. const o = e._reader._readRequests.shift();o._resolve(ge(t, r, o._forAuthorCode));
  448. }function Re(e) {
  449. return e._reader._readIntoRequests.length;
  450. }function Pe(e) {
  451. return e._reader._readRequests.length;
  452. }function Te(e) {
  453. const t = e._reader;return void 0 !== t && !!Ee(t);
  454. }function qe(e) {
  455. const t = e._reader;return void 0 !== t && !!Ce(t);
  456. }class ReadableStreamDefaultReader {
  457. constructor(e) {
  458. if (!1 === _e(e)) throw new TypeError("ReadableStreamDefaultReader can only be constructed with a ReadableStream instance");if (!0 === he(e)) throw new TypeError("This stream has already been locked for exclusive reading by another reader");je(this, e), this._readRequests = [];
  459. }get closed() {
  460. return Ce(this) ? this._closedPromise : Promise.reject(ct("closed"));
  461. }cancel(e) {
  462. return Ce(this) ? void 0 === this._ownerReadableStream ? Promise.reject(lt("cancel")) : Ae(this, e) : Promise.reject(ct("cancel"));
  463. }read() {
  464. return Ce(this) ? void 0 === this._ownerReadableStream ? Promise.reject(lt("read from")) : Be(this, !0) : Promise.reject(ct("read"));
  465. }releaseLock() {
  466. if (!Ce(this)) throw ct("releaseLock");if (void 0 !== this._ownerReadableStream) {
  467. if (this._readRequests.length > 0) throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");We(this);
  468. }
  469. }
  470. }class ReadableStreamBYOBReader {
  471. constructor(e) {
  472. if (!_e(e)) throw new TypeError("ReadableStreamBYOBReader can only be constructed with a ReadableStream instance given a byte source");if (!1 === Ne(e._readableStreamController)) throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");if (he(e)) throw new TypeError("This stream has already been locked for exclusive reading by another reader");je(this, e), this._readIntoRequests = [];
  473. }get closed() {
  474. return Ee(this) ? this._closedPromise : Promise.reject(ht("closed"));
  475. }cancel(e) {
  476. return Ee(this) ? void 0 === this._ownerReadableStream ? Promise.reject(lt("cancel")) : Ae(this, e) : Promise.reject(ht("cancel"));
  477. }read(e) {
  478. return Ee(this) ? void 0 === this._ownerReadableStream ? Promise.reject(lt("read from")) : ArrayBuffer.isView(e) ? (e.buffer, 0 === e.byteLength ? Promise.reject(new TypeError("view must have non-zero byteLength")) : function (e, t, r = !1) {
  479. const o = e._ownerReadableStream;if (o._disturbed = !0, "errored" === o._state) return Promise.reject(o._storedError);return function (e, t, r) {
  480. const o = e._controlledReadableByteStream;let n = 1;t.constructor !== DataView && (n = t.constructor.BYTES_PER_ELEMENT);const i = t.constructor,
  481. a = { buffer: _(t.buffer), byteOffset: t.byteOffset, byteLength: t.byteLength, bytesFilled: 0, elementSize: n, ctor: i, readerType: "byob" };if (e._pendingPullIntos.length > 0) return e._pendingPullIntos.push(a), me(o, r);if ("closed" === o._state) {
  482. const e = new i(a.buffer, a.byteOffset, 0);return Promise.resolve(ge(e, !0, r));
  483. }if (e._queueTotalSize > 0) {
  484. if (!0 === Je(e, a)) {
  485. const t = Ve(a);return Xe(e), Promise.resolve(ge(t, !1, r));
  486. }if (!0 === e._closeRequested) {
  487. const t = new TypeError("Insufficient bytes to fill elements in the given buffer");return nt(e, t), Promise.reject(t);
  488. }
  489. }e._pendingPullIntos.push(a);const s = me(o, r);return xe(e), s;
  490. }(o._readableStreamController, t, r);
  491. }(this, e, !0)) : Promise.reject(new TypeError("view must be an array buffer view")) : Promise.reject(ht("read"));
  492. }releaseLock() {
  493. if (!Ee(this)) throw ht("releaseLock");if (void 0 !== this._ownerReadableStream) {
  494. if (this._readIntoRequests.length > 0) throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");We(this);
  495. }
  496. }
  497. }function Ee(e) {
  498. return !!n(e) && !!Object.prototype.hasOwnProperty.call(e, "_readIntoRequests");
  499. }function Ce(e) {
  500. return !!n(e) && !!Object.prototype.hasOwnProperty.call(e, "_readRequests");
  501. }function je(e, t) {
  502. e._ownerReadableStream = t, t._reader = e, "readable" === t._state ? ut(e) : "closed" === t._state ? function (e) {
  503. ut(e), _t(e);
  504. }(e) : dt(e, t._storedError);
  505. }function Ae(e, t) {
  506. return pe(e._ownerReadableStream, t);
  507. }function We(e) {
  508. "readable" === e._ownerReadableStream._state ? ft(e, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")) : function (e, t) {
  509. dt(e, t);
  510. }(e, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")), e._ownerReadableStream._reader = void 0, e._ownerReadableStream = void 0;
  511. }function Be(e, t = !1) {
  512. const r = e._ownerReadableStream;return r._disturbed = !0, "closed" === r._state ? Promise.resolve(ge(void 0, !0, t)) : "errored" === r._state ? Promise.reject(r._storedError) : r._readableStreamController[ce](t);
  513. }class ReadableStreamDefaultController {
  514. constructor() {
  515. throw new TypeError();
  516. }get desiredSize() {
  517. if (!1 === Oe(this)) throw bt("desiredSize");return Me(this);
  518. }close() {
  519. if (!1 === Oe(this)) throw bt("close");if (!1 === Ye(this)) throw new TypeError("The stream is not in a state that permits close");Le(this);
  520. }enqueue(e) {
  521. if (!1 === Oe(this)) throw bt("enqueue");if (!1 === Ye(this)) throw new TypeError("The stream is not in a state that permits enqueue");return Ie(this, e);
  522. }error(e) {
  523. if (!1 === Oe(this)) throw bt("error");De(this, e);
  524. }[le](e) {
  525. v(this);const t = this._cancelAlgorithm(e);return Fe(this), t;
  526. }[ce](e) {
  527. const t = this._controlledReadableStream;if (this._queue.length > 0) {
  528. const r = g(this);return !0 === this._closeRequested && 0 === this._queue.length ? (Fe(this), we(t)) : ze(this), Promise.resolve(ge(r, !1, e));
  529. }const r = ye(t, e);return ze(this), r;
  530. }
  531. }function Oe(e) {
  532. return !!n(e) && !!Object.prototype.hasOwnProperty.call(e, "_controlledReadableStream");
  533. }function ze(e) {
  534. !1 !== ke(e) && (!0 !== e._pulling ? (e._pulling = !0, e._pullAlgorithm().then(() => {
  535. if (e._pulling = !1, !0 === e._pullAgain) return e._pullAgain = !1, ze(e);
  536. }, t => {
  537. De(e, t);
  538. }).catch(w)) : e._pullAgain = !0);
  539. }function ke(e) {
  540. const t = e._controlledReadableStream;return !1 !== Ye(e) && !1 !== e._started && (!0 === he(t) && Pe(t) > 0 || Me(e) > 0);
  541. }function Fe(e) {
  542. e._pullAlgorithm = void 0, e._cancelAlgorithm = void 0, e._strategySizeAlgorithm = void 0;
  543. }function Le(e) {
  544. const t = e._controlledReadableStream;e._closeRequested = !0, 0 === e._queue.length && (Fe(e), we(t));
  545. }function Ie(e, t) {
  546. const r = e._controlledReadableStream;if (!0 === he(r) && Pe(r) > 0) ve(r, t, !1);else {
  547. let r;try {
  548. r = e._strategySizeAlgorithm(t);
  549. } catch (t) {
  550. throw De(e, t), t;
  551. }try {
  552. S(e, t, r);
  553. } catch (t) {
  554. throw De(e, t), t;
  555. }
  556. }ze(e);
  557. }function De(e, t) {
  558. const r = e._controlledReadableStream;"readable" === r._state && (v(e), Fe(e), Se(r, t));
  559. }function Me(e) {
  560. const t = e._controlledReadableStream._state;return "errored" === t ? null : "closed" === t ? 0 : e._strategyHWM - e._queueTotalSize;
  561. }function Ye(e) {
  562. const t = e._controlledReadableStream._state;return !1 === e._closeRequested && "readable" === t;
  563. }function $e(e, t, r, o, n, i, a) {
  564. t._controlledReadableStream = e, t._queue = void 0, t._queueTotalSize = void 0, v(t), t._started = !1, t._closeRequested = !1, t._pullAgain = !1, t._pulling = !1, t._strategySizeAlgorithm = a, t._strategyHWM = i, t._pullAlgorithm = o, t._cancelAlgorithm = n, e._readableStreamController = t;const s = r();Promise.resolve(s).then(() => {
  565. t._started = !0, ze(t);
  566. }, e => {
  567. De(t, e);
  568. }).catch(w);
  569. }class ReadableStreamBYOBRequest {
  570. constructor() {
  571. throw new TypeError("ReadableStreamBYOBRequest cannot be used directly");
  572. }get view() {
  573. if (!1 === Qe(this)) throw mt("view");return this._view;
  574. }respond(e) {
  575. if (!1 === Qe(this)) throw mt("respond");if (void 0 === this._associatedReadableByteStreamController) throw new TypeError("This BYOB request has been invalidated");this._view.buffer, function (e, t) {
  576. if (!1 === l(t = Number(t))) throw new RangeError("bytesWritten must be a finite");tt(e, t);
  577. }(this._associatedReadableByteStreamController, e);
  578. }respondWithNewView(e) {
  579. if (!1 === Qe(this)) throw mt("respond");if (void 0 === this._associatedReadableByteStreamController) throw new TypeError("This BYOB request has been invalidated");if (!ArrayBuffer.isView(e)) throw new TypeError("You can only respond with array buffer views");e.buffer, function (e, t) {
  580. const r = e._pendingPullIntos[0];if (r.byteOffset + r.bytesFilled !== t.byteOffset) throw new RangeError("The region specified by view does not match byobRequest");if (r.byteLength !== t.byteLength) throw new RangeError("The buffer of view has different capacity than byobRequest");r.buffer = t.buffer, tt(e, t.byteLength);
  581. }(this._associatedReadableByteStreamController, e);
  582. }
  583. }class ReadableByteStreamController {
  584. constructor() {
  585. throw new TypeError("ReadableByteStreamController constructor cannot be used directly");
  586. }get byobRequest() {
  587. if (!1 === Ne(this)) throw yt("byobRequest");if (void 0 === this._byobRequest && this._pendingPullIntos.length > 0) {
  588. const e = this._pendingPullIntos[0],
  589. t = new Uint8Array(e.buffer, e.byteOffset + e.bytesFilled, e.byteLength - e.bytesFilled),
  590. r = Object.create(ReadableStreamBYOBRequest.prototype);!function (e, t, r) {
  591. e._associatedReadableByteStreamController = t, e._view = r;
  592. }(r, this, t), this._byobRequest = r;
  593. }return this._byobRequest;
  594. }get desiredSize() {
  595. if (!1 === Ne(this)) throw yt("desiredSize");return it(this);
  596. }close() {
  597. if (!1 === Ne(this)) throw yt("close");if (!0 === this._closeRequested) throw new TypeError("The stream has already been closed; do not close it again!");const e = this._controlledReadableByteStream._state;if ("readable" !== e) throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);!function (e) {
  598. const t = e._controlledReadableByteStream;if (e._queueTotalSize > 0) return void (e._closeRequested = !0);if (e._pendingPullIntos.length > 0) {
  599. const t = e._pendingPullIntos[0];if (t.bytesFilled > 0) {
  600. const t = new TypeError("Insufficient bytes to fill elements in the given buffer");throw nt(e, t), t;
  601. }
  602. }ot(e), we(t);
  603. }(this);
  604. }enqueue(e) {
  605. if (!1 === Ne(this)) throw yt("enqueue");if (!0 === this._closeRequested) throw new TypeError("stream is closed or draining");const t = this._controlledReadableByteStream._state;if ("readable" !== t) throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);if (!ArrayBuffer.isView(e)) throw new TypeError("You can only enqueue array buffer views when using a ReadableByteStreamController");e.buffer, function (e, t) {
  606. const r = e._controlledReadableByteStream,
  607. o = t.buffer,
  608. n = t.byteOffset,
  609. i = t.byteLength,
  610. a = _(o);if (!0 === qe(r)) {
  611. if (0 === Pe(r)) Ge(e, a, n, i);else {
  612. const e = new Uint8Array(a, n, i);ve(r, e, !1);
  613. }
  614. } else !0 === Te(r) ? (Ge(e, a, n, i), et(e)) : Ge(e, a, n, i);xe(e);
  615. }(this, e);
  616. }error(e) {
  617. if (!1 === Ne(this)) throw yt("error");nt(this, e);
  618. }[le](e) {
  619. if (this._pendingPullIntos.length > 0) {
  620. this._pendingPullIntos[0].bytesFilled = 0;
  621. }v(this);const t = this._cancelAlgorithm(e);return ot(this), t;
  622. }[ce](e) {
  623. const t = this._controlledReadableByteStream;if (this._queueTotalSize > 0) {
  624. const t = this._queue.shift();let r;this._queueTotalSize -= t.byteLength, Xe(this);try {
  625. r = new Uint8Array(t.buffer, t.byteOffset, t.byteLength);
  626. } catch (e) {
  627. return Promise.reject(e);
  628. }return Promise.resolve(ge(r, !1, e));
  629. }const r = this._autoAllocateChunkSize;if (void 0 !== r) {
  630. let e;try {
  631. e = new ArrayBuffer(r);
  632. } catch (e) {
  633. return Promise.reject(e);
  634. }const t = { buffer: e, byteOffset: 0, byteLength: r, bytesFilled: 0, elementSize: 1, ctor: Uint8Array, readerType: "default" };this._pendingPullIntos.push(t);
  635. }const o = ye(t, e);return xe(this), o;
  636. }
  637. }function Ne(e) {
  638. return !!n(e) && !!Object.prototype.hasOwnProperty.call(e, "_controlledReadableByteStream");
  639. }function Qe(e) {
  640. return !!n(e) && !!Object.prototype.hasOwnProperty.call(e, "_associatedReadableByteStreamController");
  641. }function xe(e) {
  642. !1 !== function (e) {
  643. const t = e._controlledReadableByteStream;if ("readable" !== t._state) return !1;if (!0 === e._closeRequested) return !1;if (!1 === e._started) return !1;if (!0 === qe(t) && Pe(t) > 0) return !0;if (!0 === Te(t) && Re(t) > 0) return !0;if (it(e) > 0) return !0;return !1;
  644. }(e) && (!0 !== e._pulling ? (e._pulling = !0, e._pullAlgorithm().then(() => {
  645. e._pulling = !1, !0 === e._pullAgain && (e._pullAgain = !1, xe(e));
  646. }, t => {
  647. nt(e, t);
  648. }).catch(w)) : e._pullAgain = !0);
  649. }function He(e) {
  650. Ze(e), e._pendingPullIntos = [];
  651. }function Ue(e, t) {
  652. let r = !1;"closed" === e._state && (r = !0);const o = Ve(t);"default" === t.readerType ? ve(e, o, r) : function (e, t, r) {
  653. const o = e._reader._readIntoRequests.shift();o._resolve(ge(t, r, o._forAuthorCode));
  654. }(e, o, r);
  655. }function Ve(e) {
  656. const t = e.bytesFilled,
  657. r = e.elementSize;return new e.ctor(e.buffer, e.byteOffset, t / r);
  658. }function Ge(e, t, r, o) {
  659. e._queue.push({ buffer: t, byteOffset: r, byteLength: o }), e._queueTotalSize += o;
  660. }function Je(e, t) {
  661. const r = t.elementSize,
  662. o = t.bytesFilled - t.bytesFilled % r,
  663. n = Math.min(e._queueTotalSize, t.byteLength - t.bytesFilled),
  664. i = t.bytesFilled + n,
  665. a = i - i % r;let l = n,
  666. c = !1;a > o && (l = a - t.bytesFilled, c = !0);const u = e._queue;for (; l > 0;) {
  667. const r = u[0],
  668. o = Math.min(l, r.byteLength),
  669. n = t.byteOffset + t.bytesFilled;s(t.buffer, n, r.buffer, r.byteOffset, o), r.byteLength === o ? u.shift() : (r.byteOffset += o, r.byteLength -= o), e._queueTotalSize -= o, Ke(e, o, t), l -= o;
  670. }return c;
  671. }function Ke(e, t, r) {
  672. Ze(e), r.bytesFilled += t;
  673. }function Xe(e) {
  674. 0 === e._queueTotalSize && !0 === e._closeRequested ? (ot(e), we(e._controlledReadableByteStream)) : xe(e);
  675. }function Ze(e) {
  676. void 0 !== e._byobRequest && (e._byobRequest._associatedReadableByteStreamController = void 0, e._byobRequest._view = void 0, e._byobRequest = void 0);
  677. }function et(e) {
  678. for (; e._pendingPullIntos.length > 0;) {
  679. if (0 === e._queueTotalSize) return;const t = e._pendingPullIntos[0];!0 === Je(e, t) && (rt(e), Ue(e._controlledReadableByteStream, t));
  680. }
  681. }function tt(e, t) {
  682. const r = e._pendingPullIntos[0];if ("closed" === e._controlledReadableByteStream._state) {
  683. if (0 !== t) throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream");!function (e, t) {
  684. t.buffer = _(t.buffer);const r = e._controlledReadableByteStream;if (!0 === Te(r)) for (; Re(r) > 0;) Ue(r, rt(e));
  685. }(e, r);
  686. } else !function (e, t, r) {
  687. if (r.bytesFilled + t > r.byteLength) throw new RangeError("bytesWritten out of range");if (Ke(e, t, r), r.bytesFilled < r.elementSize) return;rt(e);const o = r.bytesFilled % r.elementSize;if (o > 0) {
  688. const t = r.byteOffset + r.bytesFilled,
  689. n = r.buffer.slice(t - o, t);Ge(e, n, 0, n.byteLength);
  690. }r.buffer = _(r.buffer), r.bytesFilled -= o, Ue(e._controlledReadableByteStream, r), et(e);
  691. }(e, t, r);xe(e);
  692. }function rt(e) {
  693. const t = e._pendingPullIntos.shift();return Ze(e), t;
  694. }function ot(e) {
  695. e._pullAlgorithm = void 0, e._cancelAlgorithm = void 0;
  696. }function nt(e, t) {
  697. const r = e._controlledReadableByteStream;"readable" === r._state && (He(e), v(e), ot(e), Se(r, t));
  698. }function it(e) {
  699. const t = e._controlledReadableByteStream._state;return "errored" === t ? null : "closed" === t ? 0 : e._strategyHWM - e._queueTotalSize;
  700. }function at(e) {
  701. if ("object" != typeof e || null === e) return !1;const t = Object.getOwnPropertyDescriptor(AbortSignal.prototype, "aborted").get;try {
  702. return t.call(e), !0;
  703. } catch (e) {
  704. return !1;
  705. }
  706. }function st(e) {
  707. return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`);
  708. }function lt(e) {
  709. return new TypeError("Cannot " + e + " a stream using a released reader");
  710. }function ct(e) {
  711. return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`);
  712. }function ut(e) {
  713. e._closedPromise = new Promise((t, r) => {
  714. e._closedPromise_resolve = t, e._closedPromise_reject = r;
  715. });
  716. }function dt(e, t) {
  717. ut(e), ft(e, t);
  718. }function ft(e, t) {
  719. e._closedPromise.catch(() => {}), e._closedPromise_reject(t), e._closedPromise_resolve = void 0, e._closedPromise_reject = void 0;
  720. }function _t(e) {
  721. e._closedPromise_resolve(void 0), e._closedPromise_resolve = void 0, e._closedPromise_reject = void 0;
  722. }function ht(e) {
  723. return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`);
  724. }function bt(e) {
  725. return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`);
  726. }function mt(e) {
  727. return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`);
  728. }function yt(e) {
  729. return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`);
  730. }class ByteLengthQueuingStrategy {
  731. constructor({ highWaterMark: e }) {
  732. i(this, "highWaterMark", e);
  733. }size(e) {
  734. return e.byteLength;
  735. }
  736. }class CountQueuingStrategy {
  737. constructor({ highWaterMark: e }) {
  738. i(this, "highWaterMark", e);
  739. }size() {
  740. return 1;
  741. }
  742. }class TransformStream {
  743. constructor(e = {}, t = {}, r = {}) {
  744. const o = t.size;let n = t.highWaterMark;const i = r.size;let a = r.highWaterMark;if (void 0 !== e.writableType) throw new RangeError("Invalid writable type specified");const s = b(o);if (void 0 === n && (n = 1), n = h(n), void 0 !== e.readableType) throw new RangeError("Invalid readable type specified");const l = b(i);let c;void 0 === a && (a = 0), a = h(a), function (e, t, r, o, n, i) {
  745. function a() {
  746. return t;
  747. }e._writable = function (e, t, r, o, n = 1, i = () => 1) {
  748. const a = Object.create(WritableStream.prototype);return q(a), $(a, Object.create(WritableStreamDefaultController.prototype), e, t, r, o, n, i), a;
  749. }(a, function (t) {
  750. return function (e, t) {
  751. const r = e._transformStreamController;if (!0 === e._backpressure) {
  752. const o = e._backpressureChangePromise;return o.then(() => {
  753. const o = e._writable,
  754. n = o._state;if ("erroring" === n) throw o._storedError;return Tt(r, t);
  755. });
  756. }return Tt(r, t);
  757. }(e, t);
  758. }, function () {
  759. return function (e) {
  760. const t = e._readable,
  761. r = e._transformStreamController,
  762. o = r._flushAlgorithm();return Rt(r), o.then(() => {
  763. if ("errored" === t._state) throw t._storedError;const e = t._readableStreamController;!0 === Ye(e) && Le(e);
  764. }).catch(r => {
  765. throw wt(e, r), t._storedError;
  766. });
  767. }(e);
  768. }, function (t) {
  769. return function (e, t) {
  770. return wt(e, t), Promise.resolve();
  771. }(e, t);
  772. }, r, o), e._readable = de(a, function () {
  773. return function (e) {
  774. return St(e, !1), e._backpressureChangePromise;
  775. }(e);
  776. }, function (t) {
  777. return gt(e, t), Promise.resolve();
  778. }, n, i), e._backpressure = void 0, e._backpressureChangePromise = void 0, e._backpressureChangePromise_resolve = void 0, St(e, !0), e._transformStreamController = void 0;
  779. }(this, new Promise(e => {
  780. c = e;
  781. }), n, s, a, l), function (e, t) {
  782. const r = Object.create(TransformStreamDefaultController.prototype);let o = e => {
  783. try {
  784. return Pt(r, e), Promise.resolve();
  785. } catch (e) {
  786. return Promise.reject(e);
  787. }
  788. };const n = t.transform;if (void 0 !== n) {
  789. if ("function" != typeof n) throw new TypeError("transform is not a method");o = e => f(n, t, [e, r]);
  790. }const i = u(t, "flush", 0, [r]);!function (e, t, r, o) {
  791. t._controlledTransformStream = e, e._transformStreamController = t, t._transformAlgorithm = r, t._flushAlgorithm = o;
  792. }(e, r, o, i);
  793. }(this, e);const _ = d(e, "start", [this._transformStreamController]);c(_);
  794. }get readable() {
  795. if (!1 === pt(this)) throw Et("readable");return this._readable;
  796. }get writable() {
  797. if (!1 === pt(this)) throw Et("writable");return this._writable;
  798. }
  799. }function pt(e) {
  800. return !!n(e) && !!Object.prototype.hasOwnProperty.call(e, "_transformStreamController");
  801. }function wt(e, t) {
  802. De(e._readable._readableStreamController, t), gt(e, t);
  803. }function gt(e, t) {
  804. Rt(e._transformStreamController), H(e._writable._writableStreamController, t), !0 === e._backpressure && St(e, !1);
  805. }function St(e, t) {
  806. void 0 !== e._backpressureChangePromise && e._backpressureChangePromise_resolve(), e._backpressureChangePromise = new Promise(t => {
  807. e._backpressureChangePromise_resolve = t;
  808. }), e._backpressure = t;
  809. }class TransformStreamDefaultController {
  810. constructor() {
  811. throw new TypeError("TransformStreamDefaultController instances cannot be created directly");
  812. }get desiredSize() {
  813. if (!1 === vt(this)) throw qt("desiredSize");return Me(this._controlledTransformStream._readable._readableStreamController);
  814. }enqueue(e) {
  815. if (!1 === vt(this)) throw qt("enqueue");Pt(this, e);
  816. }error(e) {
  817. if (!1 === vt(this)) throw qt("error");!function (e, t) {
  818. wt(e._controlledTransformStream, t);
  819. }(this, e);
  820. }terminate() {
  821. if (!1 === vt(this)) throw qt("terminate");!function (e) {
  822. const t = e._controlledTransformStream,
  823. r = t._readable._readableStreamController;!0 === Ye(r) && Le(r);const o = new TypeError("TransformStream terminated");gt(t, o);
  824. }(this);
  825. }
  826. }function vt(e) {
  827. return !!n(e) && !!Object.prototype.hasOwnProperty.call(e, "_controlledTransformStream");
  828. }function Rt(e) {
  829. e._transformAlgorithm = void 0, e._flushAlgorithm = void 0;
  830. }function Pt(e, t) {
  831. const r = e._controlledTransformStream,
  832. o = r._readable._readableStreamController;if (!1 === Ye(o)) throw new TypeError("Readable side is not in a state that permits enqueue");try {
  833. Ie(o, t);
  834. } catch (e) {
  835. throw gt(r, e), r._readable._storedError;
  836. }(function (e) {
  837. return !0 !== ke(e);
  838. })(o) !== r._backpressure && St(r, !0);
  839. }function Tt(e, t) {
  840. return e._transformAlgorithm(t).catch(t => {
  841. throw wt(e._controlledTransformStream, t), t;
  842. });
  843. }function qt(e) {
  844. return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`);
  845. }function Et(e) {
  846. return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`);
  847. }const Ct = { ReadableStream: ReadableStream, WritableStream: WritableStream, ByteLengthQueuingStrategy: ByteLengthQueuingStrategy, CountQueuingStrategy: CountQueuingStrategy, TransformStream: TransformStream };void 0 !== r && Object.assign(r, Ct), e.ReadableStream = ReadableStream, e.WritableStream = WritableStream, e.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy, e.CountQueuingStrategy = CountQueuingStrategy, e.TransformStream = TransformStream, Object.defineProperty(e, "__esModule", { value: !0 });
  848. });
  849. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  850. },{}],2:[function(require,module,exports){
  851. "use strict";
  852. Object.defineProperty(exports, "__esModule", {
  853. value: true
  854. });
  855. /**
  856. * @file {@link http://asmjs.org Asm.js} implementation of the {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard Advanced Encryption Standard}.
  857. * @author Artem S Vybornov <vybornov@gmail.com>
  858. * @license MIT
  859. */
  860. var AES_asm = exports.AES_asm = function () {
  861. "use strict";
  862. /**
  863. * Galois Field stuff init flag
  864. */
  865. var ginit_done = false;
  866. /**
  867. * Galois Field exponentiation and logarithm tables for 3 (the generator)
  868. */
  869. var gexp3, glog3;
  870. /**
  871. * Init Galois Field tables
  872. */
  873. function ginit() {
  874. gexp3 = [], glog3 = [];
  875. var a = 1,
  876. c,
  877. d;
  878. for (c = 0; c < 255; c++) {
  879. gexp3[c] = a;
  880. // Multiply by three
  881. d = a & 0x80, a <<= 1, a &= 255;
  882. if (d === 0x80) a ^= 0x1b;
  883. a ^= gexp3[c];
  884. // Set the log table value
  885. glog3[gexp3[c]] = c;
  886. }
  887. gexp3[255] = gexp3[0];
  888. glog3[0] = 0;
  889. ginit_done = true;
  890. }
  891. /**
  892. * Galois Field multiplication
  893. * @param {number} a
  894. * @param {number} b
  895. * @return {number}
  896. */
  897. function gmul(a, b) {
  898. var c = gexp3[(glog3[a] + glog3[b]) % 255];
  899. if (a === 0 || b === 0) c = 0;
  900. return c;
  901. }
  902. /**
  903. * Galois Field reciprocal
  904. * @param {number} a
  905. * @return {number}
  906. */
  907. function ginv(a) {
  908. var i = gexp3[255 - glog3[a]];
  909. if (a === 0) i = 0;
  910. return i;
  911. }
  912. /**
  913. * AES stuff init flag
  914. */
  915. var aes_init_done = false;
  916. /**
  917. * Encryption, Decryption, S-Box and KeyTransform tables
  918. *
  919. * @type {number[]}
  920. */
  921. var aes_sbox;
  922. /**
  923. * @type {number[]}
  924. */
  925. var aes_sinv;
  926. /**
  927. * @type {number[][]}
  928. */
  929. var aes_enc;
  930. /**
  931. * @type {number[][]}
  932. */
  933. var aes_dec;
  934. /**
  935. * Init AES tables
  936. */
  937. function aes_init() {
  938. if (!ginit_done) ginit();
  939. // Calculates AES S-Box value
  940. function _s(a) {
  941. var c, s, x;
  942. s = x = ginv(a);
  943. for (c = 0; c < 4; c++) {
  944. s = (s << 1 | s >>> 7) & 255;
  945. x ^= s;
  946. }
  947. x ^= 99;
  948. return x;
  949. }
  950. // Tables
  951. aes_sbox = [], aes_sinv = [], aes_enc = [[], [], [], []], aes_dec = [[], [], [], []];
  952. for (var i = 0; i < 256; i++) {
  953. var s = _s(i);
  954. // S-Box and its inverse
  955. aes_sbox[i] = s;
  956. aes_sinv[s] = i;
  957. // Ecryption and Decryption tables
  958. aes_enc[0][i] = gmul(2, s) << 24 | s << 16 | s << 8 | gmul(3, s);
  959. aes_dec[0][s] = gmul(14, i) << 24 | gmul(9, i) << 16 | gmul(13, i) << 8 | gmul(11, i);
  960. // Rotate tables
  961. for (var t = 1; t < 4; t++) {
  962. aes_enc[t][i] = aes_enc[t - 1][i] >>> 8 | aes_enc[t - 1][i] << 24;
  963. aes_dec[t][s] = aes_dec[t - 1][s] >>> 8 | aes_dec[t - 1][s] << 24;
  964. }
  965. }
  966. aes_init_done = true;
  967. }
  968. /**
  969. * Asm.js module constructor.
  970. *
  971. * <p>
  972. * Heap buffer layout by offset:
  973. * <pre>
  974. * 0x0000 encryption key schedule
  975. * 0x0400 decryption key schedule
  976. * 0x0800 sbox
  977. * 0x0c00 inv sbox
  978. * 0x1000 encryption tables
  979. * 0x2000 decryption tables
  980. * 0x3000 reserved (future GCM multiplication lookup table)
  981. * 0x4000 data
  982. * </pre>
  983. * Don't touch anything before <code>0x400</code>.
  984. * </p>
  985. *
  986. * @alias AES_asm
  987. * @class
  988. * @param foreign - <i>ignored</i>
  989. * @param buffer - heap buffer to link with
  990. */
  991. var wrapper = function wrapper(foreign, buffer) {
  992. // Init AES stuff for the first time
  993. if (!aes_init_done) aes_init();
  994. // Fill up AES tables
  995. var heap = new Uint32Array(buffer);
  996. heap.set(aes_sbox, 0x0800 >> 2);
  997. heap.set(aes_sinv, 0x0c00 >> 2);
  998. for (var i = 0; i < 4; i++) {
  999. heap.set(aes_enc[i], 0x1000 + 0x400 * i >> 2);
  1000. heap.set(aes_dec[i], 0x2000 + 0x400 * i >> 2);
  1001. }
  1002. /**
  1003. * Calculate AES key schedules.
  1004. * @instance
  1005. * @memberof AES_asm
  1006. * @param {number} ks - key size, 4/6/8 (for 128/192/256-bit key correspondingly)
  1007. * @param {number} k0 - key vector components
  1008. * @param {number} k1 - key vector components
  1009. * @param {number} k2 - key vector components
  1010. * @param {number} k3 - key vector components
  1011. * @param {number} k4 - key vector components
  1012. * @param {number} k5 - key vector components
  1013. * @param {number} k6 - key vector components
  1014. * @param {number} k7 - key vector components
  1015. */
  1016. function set_key(ks, k0, k1, k2, k3, k4, k5, k6, k7) {
  1017. var ekeys = heap.subarray(0x000, 60),
  1018. dkeys = heap.subarray(0x100, 0x100 + 60);
  1019. // Encryption key schedule
  1020. ekeys.set([k0, k1, k2, k3, k4, k5, k6, k7]);
  1021. for (var i = ks, rcon = 1; i < 4 * ks + 28; i++) {
  1022. var k = ekeys[i - 1];
  1023. if (i % ks === 0 || ks === 8 && i % ks === 4) {
  1024. k = aes_sbox[k >>> 24] << 24 ^ aes_sbox[k >>> 16 & 255] << 16 ^ aes_sbox[k >>> 8 & 255] << 8 ^ aes_sbox[k & 255];
  1025. }
  1026. if (i % ks === 0) {
  1027. k = k << 8 ^ k >>> 24 ^ rcon << 24;
  1028. rcon = rcon << 1 ^ (rcon & 0x80 ? 0x1b : 0);
  1029. }
  1030. ekeys[i] = ekeys[i - ks] ^ k;
  1031. }
  1032. // Decryption key schedule
  1033. for (var j = 0; j < i; j += 4) {
  1034. for (var jj = 0; jj < 4; jj++) {
  1035. var k = ekeys[i - (4 + j) + (4 - jj) % 4];
  1036. if (j < 4 || j >= i - 4) {
  1037. dkeys[j + jj] = k;
  1038. } else {
  1039. dkeys[j + jj] = aes_dec[0][aes_sbox[k >>> 24]] ^ aes_dec[1][aes_sbox[k >>> 16 & 255]] ^ aes_dec[2][aes_sbox[k >>> 8 & 255]] ^ aes_dec[3][aes_sbox[k & 255]];
  1040. }
  1041. }
  1042. }
  1043. // Set rounds number
  1044. asm.set_rounds(ks + 5);
  1045. }
  1046. // create library object with necessary properties
  1047. var stdlib = { Uint8Array: Uint8Array, Uint32Array: Uint32Array };
  1048. var asm = function (stdlib, foreign, buffer) {
  1049. "use asm";
  1050. var S0 = 0,
  1051. S1 = 0,
  1052. S2 = 0,
  1053. S3 = 0,
  1054. I0 = 0,
  1055. I1 = 0,
  1056. I2 = 0,
  1057. I3 = 0,
  1058. N0 = 0,
  1059. N1 = 0,
  1060. N2 = 0,
  1061. N3 = 0,
  1062. M0 = 0,
  1063. M1 = 0,
  1064. M2 = 0,
  1065. M3 = 0,
  1066. H0 = 0,
  1067. H1 = 0,
  1068. H2 = 0,
  1069. H3 = 0,
  1070. R = 0;
  1071. var HEAP = new stdlib.Uint32Array(buffer),
  1072. DATA = new stdlib.Uint8Array(buffer);
  1073. /**
  1074. * AES core
  1075. * @param {number} k - precomputed key schedule offset
  1076. * @param {number} s - precomputed sbox table offset
  1077. * @param {number} t - precomputed round table offset
  1078. * @param {number} r - number of inner rounds to perform
  1079. * @param {number} x0 - 128-bit input block vector
  1080. * @param {number} x1 - 128-bit input block vector
  1081. * @param {number} x2 - 128-bit input block vector
  1082. * @param {number} x3 - 128-bit input block vector
  1083. */
  1084. function _core(k, s, t, r, x0, x1, x2, x3) {
  1085. k = k | 0;
  1086. s = s | 0;
  1087. t = t | 0;
  1088. r = r | 0;
  1089. x0 = x0 | 0;
  1090. x1 = x1 | 0;
  1091. x2 = x2 | 0;
  1092. x3 = x3 | 0;
  1093. var t1 = 0,
  1094. t2 = 0,
  1095. t3 = 0,
  1096. y0 = 0,
  1097. y1 = 0,
  1098. y2 = 0,
  1099. y3 = 0,
  1100. i = 0;
  1101. t1 = t | 0x400, t2 = t | 0x800, t3 = t | 0xc00;
  1102. // round 0
  1103. x0 = x0 ^ HEAP[(k | 0) >> 2], x1 = x1 ^ HEAP[(k | 4) >> 2], x2 = x2 ^ HEAP[(k | 8) >> 2], x3 = x3 ^ HEAP[(k | 12) >> 2];
  1104. // round 1..r
  1105. for (i = 16; (i | 0) <= r << 4; i = i + 16 | 0) {
  1106. y0 = HEAP[(t | x0 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x1 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x2 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x3 << 2 & 1020) >> 2] ^ HEAP[(k | i | 0) >> 2], y1 = HEAP[(t | x1 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x2 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x3 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x0 << 2 & 1020) >> 2] ^ HEAP[(k | i | 4) >> 2], y2 = HEAP[(t | x2 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x3 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x0 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x1 << 2 & 1020) >> 2] ^ HEAP[(k | i | 8) >> 2], y3 = HEAP[(t | x3 >> 22 & 1020) >> 2] ^ HEAP[(t1 | x0 >> 14 & 1020) >> 2] ^ HEAP[(t2 | x1 >> 6 & 1020) >> 2] ^ HEAP[(t3 | x2 << 2 & 1020) >> 2] ^ HEAP[(k | i | 12) >> 2];
  1107. x0 = y0, x1 = y1, x2 = y2, x3 = y3;
  1108. }
  1109. // final round
  1110. S0 = HEAP[(s | x0 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x1 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x2 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x3 << 2 & 1020) >> 2] ^ HEAP[(k | i | 0) >> 2], S1 = HEAP[(s | x1 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x2 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x3 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x0 << 2 & 1020) >> 2] ^ HEAP[(k | i | 4) >> 2], S2 = HEAP[(s | x2 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x3 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x0 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x1 << 2 & 1020) >> 2] ^ HEAP[(k | i | 8) >> 2], S3 = HEAP[(s | x3 >> 22 & 1020) >> 2] << 24 ^ HEAP[(s | x0 >> 14 & 1020) >> 2] << 16 ^ HEAP[(s | x1 >> 6 & 1020) >> 2] << 8 ^ HEAP[(s | x2 << 2 & 1020) >> 2] ^ HEAP[(k | i | 12) >> 2];
  1111. }
  1112. /**
  1113. * ECB mode encryption
  1114. * @param {number} x0 - 128-bit input block vector
  1115. * @param {number} x1 - 128-bit input block vector
  1116. * @param {number} x2 - 128-bit input block vector
  1117. * @param {number} x3 - 128-bit input block vector
  1118. */
  1119. function _ecb_enc(x0, x1, x2, x3) {
  1120. x0 = x0 | 0;
  1121. x1 = x1 | 0;
  1122. x2 = x2 | 0;
  1123. x3 = x3 | 0;
  1124. _core(0x0000, 0x0800, 0x1000, R, x0, x1, x2, x3);
  1125. }
  1126. /**
  1127. * ECB mode decryption
  1128. * @param {number} x0 - 128-bit input block vector
  1129. * @param {number} x1 - 128-bit input block vector
  1130. * @param {number} x2 - 128-bit input block vector
  1131. * @param {number} x3 - 128-bit input block vector
  1132. */
  1133. function _ecb_dec(x0, x1, x2, x3) {
  1134. x0 = x0 | 0;
  1135. x1 = x1 | 0;
  1136. x2 = x2 | 0;
  1137. x3 = x3 | 0;
  1138. var t = 0;
  1139. _core(0x0400, 0x0c00, 0x2000, R, x0, x3, x2, x1);
  1140. t = S1, S1 = S3, S3 = t;
  1141. }
  1142. /**
  1143. * CBC mode encryption
  1144. * @param {number} x0 - 128-bit input block vector
  1145. * @param {number} x1 - 128-bit input block vector
  1146. * @param {number} x2 - 128-bit input block vector
  1147. * @param {number} x3 - 128-bit input block vector
  1148. */
  1149. function _cbc_enc(x0, x1, x2, x3) {
  1150. x0 = x0 | 0;
  1151. x1 = x1 | 0;
  1152. x2 = x2 | 0;
  1153. x3 = x3 | 0;
  1154. _core(0x0000, 0x0800, 0x1000, R, I0 ^ x0, I1 ^ x1, I2 ^ x2, I3 ^ x3);
  1155. I0 = S0, I1 = S1, I2 = S2, I3 = S3;
  1156. }
  1157. /**
  1158. * CBC mode decryption
  1159. * @param {number} x0 - 128-bit input block vector
  1160. * @param {number} x1 - 128-bit input block vector
  1161. * @param {number} x2 - 128-bit input block vector
  1162. * @param {number} x3 - 128-bit input block vector
  1163. */
  1164. function _cbc_dec(x0, x1, x2, x3) {
  1165. x0 = x0 | 0;
  1166. x1 = x1 | 0;
  1167. x2 = x2 | 0;
  1168. x3 = x3 | 0;
  1169. var t = 0;
  1170. _core(0x0400, 0x0c00, 0x2000, R, x0, x3, x2, x1);
  1171. t = S1, S1 = S3, S3 = t;
  1172. S0 = S0 ^ I0, S1 = S1 ^ I1, S2 = S2 ^ I2, S3 = S3 ^ I3;
  1173. I0 = x0, I1 = x1, I2 = x2, I3 = x3;
  1174. }
  1175. /**
  1176. * CFB mode encryption
  1177. * @param {number} x0 - 128-bit input block vector
  1178. * @param {number} x1 - 128-bit input block vector
  1179. * @param {number} x2 - 128-bit input block vector
  1180. * @param {number} x3 - 128-bit input block vector
  1181. */
  1182. function _cfb_enc(x0, x1, x2, x3) {
  1183. x0 = x0 | 0;
  1184. x1 = x1 | 0;
  1185. x2 = x2 | 0;
  1186. x3 = x3 | 0;
  1187. _core(0x0000, 0x0800, 0x1000, R, I0, I1, I2, I3);
  1188. I0 = S0 = S0 ^ x0, I1 = S1 = S1 ^ x1, I2 = S2 = S2 ^ x2, I3 = S3 = S3 ^ x3;
  1189. }
  1190. /**
  1191. * CFB mode decryption
  1192. * @param {number} x0 - 128-bit input block vector
  1193. * @param {number} x1 - 128-bit input block vector
  1194. * @param {number} x2 - 128-bit input block vector
  1195. * @param {number} x3 - 128-bit input block vector
  1196. */
  1197. function _cfb_dec(x0, x1, x2, x3) {
  1198. x0 = x0 | 0;
  1199. x1 = x1 | 0;
  1200. x2 = x2 | 0;
  1201. x3 = x3 | 0;
  1202. _core(0x0000, 0x0800, 0x1000, R, I0, I1, I2, I3);
  1203. S0 = S0 ^ x0, S1 = S1 ^ x1, S2 = S2 ^ x2, S3 = S3 ^ x3;
  1204. I0 = x0, I1 = x1, I2 = x2, I3 = x3;
  1205. }
  1206. /**
  1207. * OFB mode encryption / decryption
  1208. * @param {number} x0 - 128-bit input block vector
  1209. * @param {number} x1 - 128-bit input block vector
  1210. * @param {number} x2 - 128-bit input block vector
  1211. * @param {number} x3 - 128-bit input block vector
  1212. */
  1213. function _ofb(x0, x1, x2, x3) {
  1214. x0 = x0 | 0;
  1215. x1 = x1 | 0;
  1216. x2 = x2 | 0;
  1217. x3 = x3 | 0;
  1218. _core(0x0000, 0x0800, 0x1000, R, I0, I1, I2, I3);
  1219. I0 = S0, I1 = S1, I2 = S2, I3 = S3;
  1220. S0 = S0 ^ x0, S1 = S1 ^ x1, S2 = S2 ^ x2, S3 = S3 ^ x3;
  1221. }
  1222. /**
  1223. * CTR mode encryption / decryption
  1224. * @param {number} x0 - 128-bit input block vector
  1225. * @param {number} x1 - 128-bit input block vector
  1226. * @param {number} x2 - 128-bit input block vector
  1227. * @param {number} x3 - 128-bit input block vector
  1228. */
  1229. function _ctr(x0, x1, x2, x3) {
  1230. x0 = x0 | 0;
  1231. x1 = x1 | 0;
  1232. x2 = x2 | 0;
  1233. x3 = x3 | 0;
  1234. _core(0x0000, 0x0800, 0x1000, R, N0, N1, N2, N3);
  1235. N3 = ~M3 & N3 | M3 & N3 + 1;
  1236. N2 = ~M2 & N2 | M2 & N2 + ((N3 | 0) == 0);
  1237. N1 = ~M1 & N1 | M1 & N1 + ((N2 | 0) == 0);
  1238. N0 = ~M0 & N0 | M0 & N0 + ((N1 | 0) == 0);
  1239. S0 = S0 ^ x0;
  1240. S1 = S1 ^ x1;
  1241. S2 = S2 ^ x2;
  1242. S3 = S3 ^ x3;
  1243. }
  1244. /**
  1245. * GCM mode MAC calculation
  1246. * @param {number} x0 - 128-bit input block vector
  1247. * @param {number} x1 - 128-bit input block vector
  1248. * @param {number} x2 - 128-bit input block vector
  1249. * @param {number} x3 - 128-bit input block vector
  1250. */
  1251. function _gcm_mac(x0, x1, x2, x3) {
  1252. x0 = x0 | 0;
  1253. x1 = x1 | 0;
  1254. x2 = x2 | 0;
  1255. x3 = x3 | 0;
  1256. var y0 = 0,
  1257. y1 = 0,
  1258. y2 = 0,
  1259. y3 = 0,
  1260. z0 = 0,
  1261. z1 = 0,
  1262. z2 = 0,
  1263. z3 = 0,
  1264. i = 0,
  1265. c = 0;
  1266. x0 = x0 ^ I0, x1 = x1 ^ I1, x2 = x2 ^ I2, x3 = x3 ^ I3;
  1267. y0 = H0 | 0, y1 = H1 | 0, y2 = H2 | 0, y3 = H3 | 0;
  1268. for (; (i | 0) < 128; i = i + 1 | 0) {
  1269. if (y0 >>> 31) {
  1270. z0 = z0 ^ x0, z1 = z1 ^ x1, z2 = z2 ^ x2, z3 = z3 ^ x3;
  1271. }
  1272. y0 = y0 << 1 | y1 >>> 31, y1 = y1 << 1 | y2 >>> 31, y2 = y2 << 1 | y3 >>> 31, y3 = y3 << 1;
  1273. c = x3 & 1;
  1274. x3 = x3 >>> 1 | x2 << 31, x2 = x2 >>> 1 | x1 << 31, x1 = x1 >>> 1 | x0 << 31, x0 = x0 >>> 1;
  1275. if (c) x0 = x0 ^ 0xe1000000;
  1276. }
  1277. I0 = z0, I1 = z1, I2 = z2, I3 = z3;
  1278. }
  1279. /**
  1280. * Set the internal rounds number.
  1281. * @instance
  1282. * @memberof AES_asm
  1283. * @param {number} r - number if inner AES rounds
  1284. */
  1285. function set_rounds(r) {
  1286. r = r | 0;
  1287. R = r;
  1288. }
  1289. /**
  1290. * Populate the internal state of the module.
  1291. * @instance
  1292. * @memberof AES_asm
  1293. * @param {number} s0 - state vector
  1294. * @param {number} s1 - state vector
  1295. * @param {number} s2 - state vector
  1296. * @param {number} s3 - state vector
  1297. */
  1298. function set_state(s0, s1, s2, s3) {
  1299. s0 = s0 | 0;
  1300. s1 = s1 | 0;
  1301. s2 = s2 | 0;
  1302. s3 = s3 | 0;
  1303. S0 = s0, S1 = s1, S2 = s2, S3 = s3;
  1304. }
  1305. /**
  1306. * Populate the internal iv of the module.
  1307. * @instance
  1308. * @memberof AES_asm
  1309. * @param {number} i0 - iv vector
  1310. * @param {number} i1 - iv vector
  1311. * @param {number} i2 - iv vector
  1312. * @param {number} i3 - iv vector
  1313. */
  1314. function set_iv(i0, i1, i2, i3) {
  1315. i0 = i0 | 0;
  1316. i1 = i1 | 0;
  1317. i2 = i2 | 0;
  1318. i3 = i3 | 0;
  1319. I0 = i0, I1 = i1, I2 = i2, I3 = i3;
  1320. }
  1321. /**
  1322. * Set nonce for CTR-family modes.
  1323. * @instance
  1324. * @memberof AES_asm
  1325. * @param {number} n0 - nonce vector
  1326. * @param {number} n1 - nonce vector
  1327. * @param {number} n2 - nonce vector
  1328. * @param {number} n3 - nonce vector
  1329. */
  1330. function set_nonce(n0, n1, n2, n3) {
  1331. n0 = n0 | 0;
  1332. n1 = n1 | 0;
  1333. n2 = n2 | 0;
  1334. n3 = n3 | 0;
  1335. N0 = n0, N1 = n1, N2 = n2, N3 = n3;
  1336. }
  1337. /**
  1338. * Set counter mask for CTR-family modes.
  1339. * @instance
  1340. * @memberof AES_asm
  1341. * @param {number} m0 - counter mask vector
  1342. * @param {number} m1 - counter mask vector
  1343. * @param {number} m2 - counter mask vector
  1344. * @param {number} m3 - counter mask vector
  1345. */
  1346. function set_mask(m0, m1, m2, m3) {
  1347. m0 = m0 | 0;
  1348. m1 = m1 | 0;
  1349. m2 = m2 | 0;
  1350. m3 = m3 | 0;
  1351. M0 = m0, M1 = m1, M2 = m2, M3 = m3;
  1352. }
  1353. /**
  1354. * Set counter for CTR-family modes.
  1355. * @instance
  1356. * @memberof AES_asm
  1357. * @param {number} c0 - counter vector
  1358. * @param {number} c1 - counter vector
  1359. * @param {number} c2 - counter vector
  1360. * @param {number} c3 - counter vector
  1361. */
  1362. function set_counter(c0, c1, c2, c3) {
  1363. c0 = c0 | 0;
  1364. c1 = c1 | 0;
  1365. c2 = c2 | 0;
  1366. c3 = c3 | 0;
  1367. N3 = ~M3 & N3 | M3 & c3, N2 = ~M2 & N2 | M2 & c2, N1 = ~M1 & N1 | M1 & c1, N0 = ~M0 & N0 | M0 & c0;
  1368. }
  1369. /**
  1370. * Store the internal state vector into the heap.
  1371. * @instance
  1372. * @memberof AES_asm
  1373. * @param {number} pos - offset where to put the data
  1374. * @return {number} The number of bytes have been written into the heap, always 16.
  1375. */
  1376. function get_state(pos) {
  1377. pos = pos | 0;
  1378. if (pos & 15) return -1;
  1379. DATA[pos | 0] = S0 >>> 24, DATA[pos | 1] = S0 >>> 16 & 255, DATA[pos | 2] = S0 >>> 8 & 255, DATA[pos | 3] = S0 & 255, DATA[pos | 4] = S1 >>> 24, DATA[pos | 5] = S1 >>> 16 & 255, DATA[pos | 6] = S1 >>> 8 & 255, DATA[pos | 7] = S1 & 255, DATA[pos | 8] = S2 >>> 24, DATA[pos | 9] = S2 >>> 16 & 255, DATA[pos | 10] = S2 >>> 8 & 255, DATA[pos | 11] = S2 & 255, DATA[pos | 12] = S3 >>> 24, DATA[pos | 13] = S3 >>> 16 & 255, DATA[pos | 14] = S3 >>> 8 & 255, DATA[pos | 15] = S3 & 255;
  1380. return 16;
  1381. }
  1382. /**
  1383. * Store the internal iv vector into the heap.
  1384. * @instance
  1385. * @memberof AES_asm
  1386. * @param {number} pos - offset where to put the data
  1387. * @return {number} The number of bytes have been written into the heap, always 16.
  1388. */
  1389. function get_iv(pos) {
  1390. pos = pos | 0;
  1391. if (pos & 15) return -1;
  1392. DATA[pos | 0] = I0 >>> 24, DATA[pos | 1] = I0 >>> 16 & 255, DATA[pos | 2] = I0 >>> 8 & 255, DATA[pos | 3] = I0 & 255, DATA[pos | 4] = I1 >>> 24, DATA[pos | 5] = I1 >>> 16 & 255, DATA[pos | 6] = I1 >>> 8 & 255, DATA[pos | 7] = I1 & 255, DATA[pos | 8] = I2 >>> 24, DATA[pos | 9] = I2 >>> 16 & 255, DATA[pos | 10] = I2 >>> 8 & 255, DATA[pos | 11] = I2 & 255, DATA[pos | 12] = I3 >>> 24, DATA[pos | 13] = I3 >>> 16 & 255, DATA[pos | 14] = I3 >>> 8 & 255, DATA[pos | 15] = I3 & 255;
  1393. return 16;
  1394. }
  1395. /**
  1396. * GCM initialization.
  1397. * @instance
  1398. * @memberof AES_asm
  1399. */
  1400. function gcm_init() {
  1401. _ecb_enc(0, 0, 0, 0);
  1402. H0 = S0, H1 = S1, H2 = S2, H3 = S3;
  1403. }
  1404. /**
  1405. * Perform ciphering operation on the supplied data.
  1406. * @instance
  1407. * @memberof AES_asm
  1408. * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants)
  1409. * @param {number} pos - offset of the data being processed
  1410. * @param {number} len - length of the data being processed
  1411. * @return {number} Actual amount of data have been processed.
  1412. */
  1413. function cipher(mode, pos, len) {
  1414. mode = mode | 0;
  1415. pos = pos | 0;
  1416. len = len | 0;
  1417. var ret = 0;
  1418. if (pos & 15) return -1;
  1419. while ((len | 0) >= 16) {
  1420. _cipher_modes[mode & 7](DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3], DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7], DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11], DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15]);
  1421. DATA[pos | 0] = S0 >>> 24, DATA[pos | 1] = S0 >>> 16 & 255, DATA[pos | 2] = S0 >>> 8 & 255, DATA[pos | 3] = S0 & 255, DATA[pos | 4] = S1 >>> 24, DATA[pos | 5] = S1 >>> 16 & 255, DATA[pos | 6] = S1 >>> 8 & 255, DATA[pos | 7] = S1 & 255, DATA[pos | 8] = S2 >>> 24, DATA[pos | 9] = S2 >>> 16 & 255, DATA[pos | 10] = S2 >>> 8 & 255, DATA[pos | 11] = S2 & 255, DATA[pos | 12] = S3 >>> 24, DATA[pos | 13] = S3 >>> 16 & 255, DATA[pos | 14] = S3 >>> 8 & 255, DATA[pos | 15] = S3 & 255;
  1422. ret = ret + 16 | 0, pos = pos + 16 | 0, len = len - 16 | 0;
  1423. }
  1424. return ret | 0;
  1425. }
  1426. /**
  1427. * Calculates MAC of the supplied data.
  1428. * @instance
  1429. * @memberof AES_asm
  1430. * @param {number} mode - block cipher mode (see {@link AES_asm} mode constants)
  1431. * @param {number} pos - offset of the data being processed
  1432. * @param {number} len - length of the data being processed
  1433. * @return {number} Actual amount of data have been processed.
  1434. */
  1435. function mac(mode, pos, len) {
  1436. mode = mode | 0;
  1437. pos = pos | 0;
  1438. len = len | 0;
  1439. var ret = 0;
  1440. if (pos & 15) return -1;
  1441. while ((len | 0) >= 16) {
  1442. _mac_modes[mode & 1](DATA[pos | 0] << 24 | DATA[pos | 1] << 16 | DATA[pos | 2] << 8 | DATA[pos | 3], DATA[pos | 4] << 24 | DATA[pos | 5] << 16 | DATA[pos | 6] << 8 | DATA[pos | 7], DATA[pos | 8] << 24 | DATA[pos | 9] << 16 | DATA[pos | 10] << 8 | DATA[pos | 11], DATA[pos | 12] << 24 | DATA[pos | 13] << 16 | DATA[pos | 14] << 8 | DATA[pos | 15]);
  1443. ret = ret + 16 | 0, pos = pos + 16 | 0, len = len - 16 | 0;
  1444. }
  1445. return ret | 0;
  1446. }
  1447. /**
  1448. * AES cipher modes table (virual methods)
  1449. */
  1450. var _cipher_modes = [_ecb_enc, _ecb_dec, _cbc_enc, _cbc_dec, _cfb_enc, _cfb_dec, _ofb, _ctr];
  1451. /**
  1452. * AES MAC modes table (virual methods)
  1453. */
  1454. var _mac_modes = [_cbc_enc, _gcm_mac];
  1455. /**
  1456. * Asm.js module exports
  1457. */
  1458. return {
  1459. set_rounds: set_rounds,
  1460. set_state: set_state,
  1461. set_iv: set_iv,
  1462. set_nonce: set_nonce,
  1463. set_mask: set_mask,
  1464. set_counter: set_counter,
  1465. get_state: get_state,
  1466. get_iv: get_iv,
  1467. gcm_init: gcm_init,
  1468. cipher: cipher,
  1469. mac: mac
  1470. };
  1471. }(stdlib, foreign, buffer);
  1472. asm.set_key = set_key;
  1473. return asm;
  1474. };
  1475. /**
  1476. * AES enciphering mode constants
  1477. * @enum {number}
  1478. * @const
  1479. */
  1480. wrapper.ENC = {
  1481. ECB: 0,
  1482. CBC: 2,
  1483. CFB: 4,
  1484. OFB: 6,
  1485. CTR: 7
  1486. },
  1487. /**
  1488. * AES deciphering mode constants
  1489. * @enum {number}
  1490. * @const
  1491. */
  1492. wrapper.DEC = {
  1493. ECB: 1,
  1494. CBC: 3,
  1495. CFB: 5,
  1496. OFB: 6,
  1497. CTR: 7
  1498. },
  1499. /**
  1500. * AES MAC mode constants
  1501. * @enum {number}
  1502. * @const
  1503. */
  1504. wrapper.MAC = {
  1505. CBC: 0,
  1506. GCM: 1
  1507. };
  1508. /**
  1509. * Heap data offset
  1510. * @type {number}
  1511. * @const
  1512. */
  1513. wrapper.HEAP_DATA = 0x4000;
  1514. return wrapper;
  1515. }();
  1516. },{}],3:[function(require,module,exports){
  1517. 'use strict';
  1518. Object.defineProperty(exports, "__esModule", {
  1519. value: true
  1520. });
  1521. exports.AES = undefined;
  1522. var _aes = require('./aes.asm');
  1523. var _utils = require('../other/utils');
  1524. var _errors = require('../other/errors');
  1525. var heap_pool = [];
  1526. var asm_pool = [];
  1527. var AES = /** @class */function () {
  1528. function AES(key, iv, padding, mode) {
  1529. if (padding === void 0) {
  1530. padding = true;
  1531. }
  1532. this.pos = 0;
  1533. this.len = 0;
  1534. this.mode = mode;
  1535. // The AES object state
  1536. this.pos = 0;
  1537. this.len = 0;
  1538. this.key = key;
  1539. this.iv = iv;
  1540. this.padding = padding;
  1541. // The AES "worker"
  1542. this.acquire_asm();
  1543. }
  1544. AES.prototype.acquire_asm = function () {
  1545. if (this.heap === undefined && this.asm === undefined) {
  1546. this.heap = heap_pool.pop() || (0, _utils._heap_init)().subarray(_aes.AES_asm.HEAP_DATA);
  1547. this.asm = asm_pool.pop() || (0, _aes.AES_asm)(null, this.heap.buffer);
  1548. this.reset(this.key, this.iv);
  1549. }
  1550. };
  1551. AES.prototype.release_asm = function () {
  1552. heap_pool.push(this.heap);
  1553. ;
  1554. asm_pool.push(this.asm);
  1555. this.heap = undefined;
  1556. this.asm = undefined;
  1557. };
  1558. AES.prototype.reset = function (key, iv) {
  1559. // Key
  1560. var keylen = key.length;
  1561. if (keylen !== 16 && keylen !== 24 && keylen !== 32) throw new _errors.IllegalArgumentError('illegal key size');
  1562. var keyview = new DataView(key.buffer, key.byteOffset, key.byteLength);
  1563. this.asm.set_key(keylen >> 2, keyview.getUint32(0), keyview.getUint32(4), keyview.getUint32(8), keyview.getUint32(12), keylen > 16 ? keyview.getUint32(16) : 0, keylen > 16 ? keyview.getUint32(20) : 0, keylen > 24 ? keyview.getUint32(24) : 0, keylen > 24 ? keyview.getUint32(28) : 0);
  1564. // IV
  1565. if (iv !== undefined) {
  1566. if (iv.length !== 16) throw new _errors.IllegalArgumentError('illegal iv size');
  1567. var ivview = new DataView(iv.buffer, iv.byteOffset, iv.byteLength);
  1568. this.asm.set_iv(ivview.getUint32(0), ivview.getUint32(4), ivview.getUint32(8), ivview.getUint32(12));
  1569. } else {
  1570. this.asm.set_iv(0, 0, 0, 0);
  1571. }
  1572. };
  1573. AES.prototype.AES_Encrypt_process = function (data) {
  1574. if (!(0, _utils.is_bytes)(data)) throw new TypeError("data isn't of expected type");
  1575. this.acquire_asm();
  1576. var asm = this.asm;
  1577. var heap = this.heap;
  1578. var amode = _aes.AES_asm.ENC[this.mode];
  1579. var hpos = _aes.AES_asm.HEAP_DATA;
  1580. var pos = this.pos;
  1581. var len = this.len;
  1582. var dpos = 0;
  1583. var dlen = data.length || 0;
  1584. var rpos = 0;
  1585. var rlen = len + dlen & -16;
  1586. var wlen = 0;
  1587. var result = new Uint8Array(rlen);
  1588. while (dlen > 0) {
  1589. wlen = (0, _utils._heap_write)(heap, pos + len, data, dpos, dlen);
  1590. len += wlen;
  1591. dpos += wlen;
  1592. dlen -= wlen;
  1593. wlen = asm.cipher(amode, hpos + pos, len);
  1594. if (wlen) result.set(heap.subarray(pos, pos + wlen), rpos);
  1595. rpos += wlen;
  1596. if (wlen < len) {
  1597. pos += wlen;
  1598. len -= wlen;
  1599. } else {
  1600. pos = 0;
  1601. len = 0;
  1602. }
  1603. }
  1604. this.pos = pos;
  1605. this.len = len;
  1606. return result;
  1607. };
  1608. AES.prototype.AES_Encrypt_finish = function () {
  1609. this.acquire_asm();
  1610. var asm = this.asm;
  1611. var heap = this.heap;
  1612. var amode = _aes.AES_asm.ENC[this.mode];
  1613. var hpos = _aes.AES_asm.HEAP_DATA;
  1614. var pos = this.pos;
  1615. var len = this.len;
  1616. var plen = 16 - len % 16;
  1617. var rlen = len;
  1618. if (this.hasOwnProperty('padding')) {
  1619. if (this.padding) {
  1620. for (var p = 0; p < plen; ++p) {
  1621. heap[pos + len + p] = plen;
  1622. }
  1623. len += plen;
  1624. rlen = len;
  1625. } else if (len % 16) {
  1626. throw new _errors.IllegalArgumentError('data length must be a multiple of the block size');
  1627. }
  1628. } else {
  1629. len += plen;
  1630. }
  1631. var result = new Uint8Array(rlen);
  1632. if (len) asm.cipher(amode, hpos + pos, len);
  1633. if (rlen) result.set(heap.subarray(pos, pos + rlen));
  1634. this.pos = 0;
  1635. this.len = 0;
  1636. this.release_asm();
  1637. return result;
  1638. };
  1639. AES.prototype.AES_Decrypt_process = function (data) {
  1640. if (!(0, _utils.is_bytes)(data)) throw new TypeError("data isn't of expected type");
  1641. this.acquire_asm();
  1642. var asm = this.asm;
  1643. var heap = this.heap;
  1644. var amode = _aes.AES_asm.DEC[this.mode];
  1645. var hpos = _aes.AES_asm.HEAP_DATA;
  1646. var pos = this.pos;
  1647. var len = this.len;
  1648. var dpos = 0;
  1649. var dlen = data.length || 0;
  1650. var rpos = 0;
  1651. var rlen = len + dlen & -16;
  1652. var plen = 0;
  1653. var wlen = 0;
  1654. if (this.padding) {
  1655. plen = len + dlen - rlen || 16;
  1656. rlen -= plen;
  1657. }
  1658. var result = new Uint8Array(rlen);
  1659. while (dlen > 0) {
  1660. wlen = (0, _utils._heap_write)(heap, pos + len, data, dpos, dlen);
  1661. len += wlen;
  1662. dpos += wlen;
  1663. dlen -= wlen;
  1664. wlen = asm.cipher(amode, hpos + pos, len - (!dlen ? plen : 0));
  1665. if (wlen) result.set(heap.subarray(pos, pos + wlen), rpos);
  1666. rpos += wlen;
  1667. if (wlen < len) {
  1668. pos += wlen;
  1669. len -= wlen;
  1670. } else {
  1671. pos = 0;
  1672. len = 0;
  1673. }
  1674. }
  1675. this.pos = pos;
  1676. this.len = len;
  1677. return result;
  1678. };
  1679. AES.prototype.AES_Decrypt_finish = function () {
  1680. this.acquire_asm();
  1681. var asm = this.asm;
  1682. var heap = this.heap;
  1683. var amode = _aes.AES_asm.DEC[this.mode];
  1684. var hpos = _aes.AES_asm.HEAP_DATA;
  1685. var pos = this.pos;
  1686. var len = this.len;
  1687. var rlen = len;
  1688. if (len > 0) {
  1689. if (len % 16) {
  1690. if (this.hasOwnProperty('padding')) {
  1691. throw new _errors.IllegalArgumentError('data length must be a multiple of the block size');
  1692. } else {
  1693. len += 16 - len % 16;
  1694. }
  1695. }
  1696. asm.cipher(amode, hpos + pos, len);
  1697. if (this.hasOwnProperty('padding') && this.padding) {
  1698. var pad = heap[pos + rlen - 1];
  1699. if (pad < 1 || pad > 16 || pad > rlen) throw new _errors.SecurityError('bad padding');
  1700. var pcheck = 0;
  1701. for (var i = pad; i > 1; i--) pcheck |= pad ^ heap[pos + rlen - i];
  1702. if (pcheck) throw new _errors.SecurityError('bad padding');
  1703. rlen -= pad;
  1704. }
  1705. }
  1706. var result = new Uint8Array(rlen);
  1707. if (rlen > 0) {
  1708. result.set(heap.subarray(pos, pos + rlen));
  1709. }
  1710. this.pos = 0;
  1711. this.len = 0;
  1712. this.release_asm();
  1713. return result;
  1714. };
  1715. return AES;
  1716. }();
  1717. exports.AES = AES;
  1718. },{"../other/errors":14,"../other/utils":15,"./aes.asm":2}],4:[function(require,module,exports){
  1719. 'use strict';
  1720. Object.defineProperty(exports, "__esModule", {
  1721. value: true
  1722. });
  1723. exports.AES_CBC = undefined;
  1724. var _aes = require('./aes');
  1725. var _utils = require('../other/utils');
  1726. var __extends = undefined && undefined.__extends || function () {
  1727. var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) {
  1728. d.__proto__ = b;
  1729. } || function (d, b) {
  1730. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  1731. };
  1732. return function (d, b) {
  1733. extendStatics(d, b);
  1734. function __() {
  1735. this.constructor = d;
  1736. }
  1737. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1738. };
  1739. }();
  1740. var AES_CBC = /** @class */function (_super) {
  1741. __extends(AES_CBC, _super);
  1742. function AES_CBC(key, iv, padding) {
  1743. if (padding === void 0) {
  1744. padding = true;
  1745. }
  1746. return _super.call(this, key, iv, padding, 'CBC') || this;
  1747. }
  1748. AES_CBC.encrypt = function (data, key, padding, iv) {
  1749. if (padding === void 0) {
  1750. padding = true;
  1751. }
  1752. return new AES_CBC(key, iv, padding).encrypt(data);
  1753. };
  1754. AES_CBC.decrypt = function (data, key, padding, iv) {
  1755. if (padding === void 0) {
  1756. padding = true;
  1757. }
  1758. return new AES_CBC(key, iv, padding).decrypt(data);
  1759. };
  1760. AES_CBC.prototype.encrypt = function (data) {
  1761. var r1 = this.AES_Encrypt_process(data);
  1762. var r2 = this.AES_Encrypt_finish();
  1763. return (0, _utils.joinBytes)(r1, r2);
  1764. };
  1765. AES_CBC.prototype.decrypt = function (data) {
  1766. var r1 = this.AES_Decrypt_process(data);
  1767. var r2 = this.AES_Decrypt_finish();
  1768. return (0, _utils.joinBytes)(r1, r2);
  1769. };
  1770. return AES_CBC;
  1771. }(_aes.AES);
  1772. exports.AES_CBC = AES_CBC;
  1773. },{"../other/utils":15,"./aes":3}],5:[function(require,module,exports){
  1774. 'use strict';
  1775. Object.defineProperty(exports, "__esModule", {
  1776. value: true
  1777. });
  1778. exports.AES_CFB = undefined;
  1779. var _aes = require('./aes');
  1780. var _utils = require('../other/utils');
  1781. var __extends = undefined && undefined.__extends || function () {
  1782. var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) {
  1783. d.__proto__ = b;
  1784. } || function (d, b) {
  1785. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  1786. };
  1787. return function (d, b) {
  1788. extendStatics(d, b);
  1789. function __() {
  1790. this.constructor = d;
  1791. }
  1792. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1793. };
  1794. }();
  1795. var AES_CFB = /** @class */function (_super) {
  1796. __extends(AES_CFB, _super);
  1797. function AES_CFB(key, iv) {
  1798. var _this = _super.call(this, key, iv, true, 'CFB') || this;
  1799. delete _this.padding;
  1800. return _this;
  1801. }
  1802. AES_CFB.encrypt = function (data, key, iv) {
  1803. return new AES_CFB(key, iv).encrypt(data);
  1804. };
  1805. AES_CFB.decrypt = function (data, key, iv) {
  1806. return new AES_CFB(key, iv).decrypt(data);
  1807. };
  1808. AES_CFB.prototype.encrypt = function (data) {
  1809. var r1 = this.AES_Encrypt_process(data);
  1810. var r2 = this.AES_Encrypt_finish();
  1811. return (0, _utils.joinBytes)(r1, r2);
  1812. };
  1813. AES_CFB.prototype.decrypt = function (data) {
  1814. var r1 = this.AES_Decrypt_process(data);
  1815. var r2 = this.AES_Decrypt_finish();
  1816. return (0, _utils.joinBytes)(r1, r2);
  1817. };
  1818. return AES_CFB;
  1819. }(_aes.AES);
  1820. exports.AES_CFB = AES_CFB;
  1821. },{"../other/utils":15,"./aes":3}],6:[function(require,module,exports){
  1822. 'use strict';
  1823. Object.defineProperty(exports, "__esModule", {
  1824. value: true
  1825. });
  1826. exports.AES_CTR = undefined;
  1827. var _aes = require('./aes');
  1828. var _errors = require('../other/errors');
  1829. var _utils = require('../other/utils');
  1830. var __extends = undefined && undefined.__extends || function () {
  1831. var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) {
  1832. d.__proto__ = b;
  1833. } || function (d, b) {
  1834. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  1835. };
  1836. return function (d, b) {
  1837. extendStatics(d, b);
  1838. function __() {
  1839. this.constructor = d;
  1840. }
  1841. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1842. };
  1843. }();
  1844. var AES_CTR = /** @class */function (_super) {
  1845. __extends(AES_CTR, _super);
  1846. function AES_CTR(key, nonce) {
  1847. var _this = _super.call(this, key, undefined, false, 'CTR') || this;
  1848. delete _this.padding;
  1849. _this.AES_CTR_set_options(nonce);
  1850. return _this;
  1851. }
  1852. AES_CTR.encrypt = function (data, key, nonce) {
  1853. return new AES_CTR(key, nonce).encrypt(data);
  1854. };
  1855. AES_CTR.decrypt = function (data, key, nonce) {
  1856. return new AES_CTR(key, nonce).encrypt(data);
  1857. };
  1858. AES_CTR.prototype.encrypt = function (data) {
  1859. var r1 = this.AES_Encrypt_process(data);
  1860. var r2 = this.AES_Encrypt_finish();
  1861. return (0, _utils.joinBytes)(r1, r2);
  1862. };
  1863. AES_CTR.prototype.decrypt = function (data) {
  1864. var r1 = this.AES_Encrypt_process(data);
  1865. var r2 = this.AES_Encrypt_finish();
  1866. return (0, _utils.joinBytes)(r1, r2);
  1867. };
  1868. AES_CTR.prototype.AES_CTR_set_options = function (nonce, counter, size) {
  1869. if (size !== undefined) {
  1870. if (size < 8 || size > 48) throw new _errors.IllegalArgumentError('illegal counter size');
  1871. var mask = Math.pow(2, size) - 1;
  1872. this.asm.set_mask(0, 0, mask / 0x100000000 | 0, mask | 0);
  1873. } else {
  1874. size = 48;
  1875. this.asm.set_mask(0, 0, 0xffff, 0xffffffff);
  1876. }
  1877. if (nonce !== undefined) {
  1878. var len = nonce.length;
  1879. if (!len || len > 16) throw new _errors.IllegalArgumentError('illegal nonce size');
  1880. var view = new DataView(new ArrayBuffer(16));
  1881. new Uint8Array(view.buffer).set(nonce);
  1882. this.asm.set_nonce(view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12));
  1883. } else {
  1884. throw new Error('nonce is required');
  1885. }
  1886. if (counter !== undefined) {
  1887. if (counter < 0 || counter >= Math.pow(2, size)) throw new _errors.IllegalArgumentError('illegal counter value');
  1888. this.asm.set_counter(0, 0, counter / 0x100000000 | 0, counter | 0);
  1889. }
  1890. };
  1891. return AES_CTR;
  1892. }(_aes.AES);
  1893. exports.AES_CTR = AES_CTR;
  1894. },{"../other/errors":14,"../other/utils":15,"./aes":3}],7:[function(require,module,exports){
  1895. 'use strict';
  1896. Object.defineProperty(exports, "__esModule", {
  1897. value: true
  1898. });
  1899. exports.AES_ECB = undefined;
  1900. var _aes = require('./aes');
  1901. var _utils = require('../other/utils');
  1902. var __extends = undefined && undefined.__extends || function () {
  1903. var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) {
  1904. d.__proto__ = b;
  1905. } || function (d, b) {
  1906. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  1907. };
  1908. return function (d, b) {
  1909. extendStatics(d, b);
  1910. function __() {
  1911. this.constructor = d;
  1912. }
  1913. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1914. };
  1915. }();
  1916. var AES_ECB = /** @class */function (_super) {
  1917. __extends(AES_ECB, _super);
  1918. function AES_ECB(key, padding) {
  1919. if (padding === void 0) {
  1920. padding = false;
  1921. }
  1922. return _super.call(this, key, undefined, padding, 'ECB') || this;
  1923. }
  1924. AES_ECB.encrypt = function (data, key, padding) {
  1925. if (padding === void 0) {
  1926. padding = false;
  1927. }
  1928. return new AES_ECB(key, padding).encrypt(data);
  1929. };
  1930. AES_ECB.decrypt = function (data, key, padding) {
  1931. if (padding === void 0) {
  1932. padding = false;
  1933. }
  1934. return new AES_ECB(key, padding).decrypt(data);
  1935. };
  1936. AES_ECB.prototype.encrypt = function (data) {
  1937. var r1 = this.AES_Encrypt_process(data);
  1938. var r2 = this.AES_Encrypt_finish();
  1939. return (0, _utils.joinBytes)(r1, r2);
  1940. };
  1941. AES_ECB.prototype.decrypt = function (data) {
  1942. var r1 = this.AES_Decrypt_process(data);
  1943. var r2 = this.AES_Decrypt_finish();
  1944. return (0, _utils.joinBytes)(r1, r2);
  1945. };
  1946. return AES_ECB;
  1947. }(_aes.AES);
  1948. exports.AES_ECB = AES_ECB;
  1949. },{"../other/utils":15,"./aes":3}],8:[function(require,module,exports){
  1950. 'use strict';
  1951. Object.defineProperty(exports, "__esModule", {
  1952. value: true
  1953. });
  1954. exports.AES_GCM = undefined;
  1955. var _errors = require('../other/errors');
  1956. var _utils = require('../other/utils');
  1957. var _aes = require('./aes');
  1958. var _aes2 = require('./aes.asm');
  1959. var __extends = undefined && undefined.__extends || function () {
  1960. var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) {
  1961. d.__proto__ = b;
  1962. } || function (d, b) {
  1963. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  1964. };
  1965. return function (d, b) {
  1966. extendStatics(d, b);
  1967. function __() {
  1968. this.constructor = d;
  1969. }
  1970. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1971. };
  1972. }();
  1973. var _AES_GCM_data_maxLength = 68719476704; // 2^36 - 2^5
  1974. var AES_GCM = /** @class */function (_super) {
  1975. __extends(AES_GCM, _super);
  1976. function AES_GCM(key, nonce, adata, tagSize) {
  1977. if (tagSize === void 0) {
  1978. tagSize = 16;
  1979. }
  1980. var _this = _super.call(this, key, undefined, false, 'CTR') || this;
  1981. _this.tagSize = tagSize;
  1982. _this.gamma0 = 0;
  1983. _this.counter = 1;
  1984. // Init GCM
  1985. _this.asm.gcm_init();
  1986. // Tag size
  1987. if (_this.tagSize < 4 || _this.tagSize > 16) throw new _errors.IllegalArgumentError('illegal tagSize value');
  1988. // Nonce
  1989. var noncelen = nonce.length || 0;
  1990. var noncebuf = new Uint8Array(16);
  1991. if (noncelen !== 12) {
  1992. _this._gcm_mac_process(nonce);
  1993. _this.heap[0] = 0;
  1994. _this.heap[1] = 0;
  1995. _this.heap[2] = 0;
  1996. _this.heap[3] = 0;
  1997. _this.heap[4] = 0;
  1998. _this.heap[5] = 0;
  1999. _this.heap[6] = 0;
  2000. _this.heap[7] = 0;
  2001. _this.heap[8] = 0;
  2002. _this.heap[9] = 0;
  2003. _this.heap[10] = 0;
  2004. _this.heap[11] = noncelen >>> 29;
  2005. _this.heap[12] = noncelen >>> 21 & 255;
  2006. _this.heap[13] = noncelen >>> 13 & 255;
  2007. _this.heap[14] = noncelen >>> 5 & 255;
  2008. _this.heap[15] = noncelen << 3 & 255;
  2009. _this.asm.mac(_aes2.AES_asm.MAC.GCM, _aes2.AES_asm.HEAP_DATA, 16);
  2010. _this.asm.get_iv(_aes2.AES_asm.HEAP_DATA);
  2011. _this.asm.set_iv(0, 0, 0, 0);
  2012. noncebuf.set(_this.heap.subarray(0, 16));
  2013. } else {
  2014. noncebuf.set(nonce);
  2015. noncebuf[15] = 1;
  2016. }
  2017. var nonceview = new DataView(noncebuf.buffer);
  2018. _this.gamma0 = nonceview.getUint32(12);
  2019. _this.asm.set_nonce(nonceview.getUint32(0), nonceview.getUint32(4), nonceview.getUint32(8), 0);
  2020. _this.asm.set_mask(0, 0, 0, 0xffffffff);
  2021. // Associated data
  2022. if (adata !== undefined) {
  2023. if (adata.length > _AES_GCM_data_maxLength) throw new _errors.IllegalArgumentError('illegal adata length');
  2024. if (adata.length) {
  2025. _this.adata = adata;
  2026. _this._gcm_mac_process(adata);
  2027. } else {
  2028. _this.adata = undefined;
  2029. }
  2030. } else {
  2031. _this.adata = undefined;
  2032. }
  2033. // Counter
  2034. if (_this.counter < 1 || _this.counter > 0xffffffff) throw new RangeError('counter must be a positive 32-bit integer');
  2035. _this.asm.set_counter(0, 0, 0, _this.gamma0 + _this.counter | 0);
  2036. return _this;
  2037. }
  2038. AES_GCM.encrypt = function (cleartext, key, nonce, adata, tagsize) {
  2039. return new AES_GCM(key, nonce, adata, tagsize).encrypt(cleartext);
  2040. };
  2041. AES_GCM.decrypt = function (ciphertext, key, nonce, adata, tagsize) {
  2042. return new AES_GCM(key, nonce, adata, tagsize).decrypt(ciphertext);
  2043. };
  2044. AES_GCM.prototype.encrypt = function (data) {
  2045. return this.AES_GCM_encrypt(data);
  2046. };
  2047. AES_GCM.prototype.decrypt = function (data) {
  2048. return this.AES_GCM_decrypt(data);
  2049. };
  2050. AES_GCM.prototype.AES_GCM_Encrypt_process = function (data) {
  2051. var dpos = 0;
  2052. var dlen = data.length || 0;
  2053. var asm = this.asm;
  2054. var heap = this.heap;
  2055. var counter = this.counter;
  2056. var pos = this.pos;
  2057. var len = this.len;
  2058. var rpos = 0;
  2059. var rlen = len + dlen & -16;
  2060. var wlen = 0;
  2061. if ((counter - 1 << 4) + len + dlen > _AES_GCM_data_maxLength) throw new RangeError('counter overflow');
  2062. var result = new Uint8Array(rlen);
  2063. while (dlen > 0) {
  2064. wlen = (0, _utils._heap_write)(heap, pos + len, data, dpos, dlen);
  2065. len += wlen;
  2066. dpos += wlen;
  2067. dlen -= wlen;
  2068. wlen = asm.cipher(_aes2.AES_asm.ENC.CTR, _aes2.AES_asm.HEAP_DATA + pos, len);
  2069. wlen = asm.mac(_aes2.AES_asm.MAC.GCM, _aes2.AES_asm.HEAP_DATA + pos, wlen);
  2070. if (wlen) result.set(heap.subarray(pos, pos + wlen), rpos);
  2071. counter += wlen >>> 4;
  2072. rpos += wlen;
  2073. if (wlen < len) {
  2074. pos += wlen;
  2075. len -= wlen;
  2076. } else {
  2077. pos = 0;
  2078. len = 0;
  2079. }
  2080. }
  2081. this.counter = counter;
  2082. this.pos = pos;
  2083. this.len = len;
  2084. return result;
  2085. };
  2086. AES_GCM.prototype.AES_GCM_Encrypt_finish = function () {
  2087. var asm = this.asm;
  2088. var heap = this.heap;
  2089. var counter = this.counter;
  2090. var tagSize = this.tagSize;
  2091. var adata = this.adata;
  2092. var pos = this.pos;
  2093. var len = this.len;
  2094. var result = new Uint8Array(len + tagSize);
  2095. asm.cipher(_aes2.AES_asm.ENC.CTR, _aes2.AES_asm.HEAP_DATA + pos, len + 15 & -16);
  2096. if (len) result.set(heap.subarray(pos, pos + len));
  2097. var i = len;
  2098. for (; i & 15; i++) heap[pos + i] = 0;
  2099. asm.mac(_aes2.AES_asm.MAC.GCM, _aes2.AES_asm.HEAP_DATA + pos, i);
  2100. var alen = adata !== undefined ? adata.length : 0;
  2101. var clen = (counter - 1 << 4) + len;
  2102. heap[0] = 0;
  2103. heap[1] = 0;
  2104. heap[2] = 0;
  2105. heap[3] = alen >>> 29;
  2106. heap[4] = alen >>> 21;
  2107. heap[5] = alen >>> 13 & 255;
  2108. heap[6] = alen >>> 5 & 255;
  2109. heap[7] = alen << 3 & 255;
  2110. heap[8] = heap[9] = heap[10] = 0;
  2111. heap[11] = clen >>> 29;
  2112. heap[12] = clen >>> 21 & 255;
  2113. heap[13] = clen >>> 13 & 255;
  2114. heap[14] = clen >>> 5 & 255;
  2115. heap[15] = clen << 3 & 255;
  2116. asm.mac(_aes2.AES_asm.MAC.GCM, _aes2.AES_asm.HEAP_DATA, 16);
  2117. asm.get_iv(_aes2.AES_asm.HEAP_DATA);
  2118. asm.set_counter(0, 0, 0, this.gamma0);
  2119. asm.cipher(_aes2.AES_asm.ENC.CTR, _aes2.AES_asm.HEAP_DATA, 16);
  2120. result.set(heap.subarray(0, tagSize), len);
  2121. this.counter = 1;
  2122. this.pos = 0;
  2123. this.len = 0;
  2124. return result;
  2125. };
  2126. AES_GCM.prototype.AES_GCM_Decrypt_process = function (data) {
  2127. var dpos = 0;
  2128. var dlen = data.length || 0;
  2129. var asm = this.asm;
  2130. var heap = this.heap;
  2131. var counter = this.counter;
  2132. var tagSize = this.tagSize;
  2133. var pos = this.pos;
  2134. var len = this.len;
  2135. var rpos = 0;
  2136. var rlen = len + dlen > tagSize ? len + dlen - tagSize & -16 : 0;
  2137. var tlen = len + dlen - rlen;
  2138. var wlen = 0;
  2139. if ((counter - 1 << 4) + len + dlen > _AES_GCM_data_maxLength) throw new RangeError('counter overflow');
  2140. var result = new Uint8Array(rlen);
  2141. while (dlen > tlen) {
  2142. wlen = (0, _utils._heap_write)(heap, pos + len, data, dpos, dlen - tlen);
  2143. len += wlen;
  2144. dpos += wlen;
  2145. dlen -= wlen;
  2146. wlen = asm.mac(_aes2.AES_asm.MAC.GCM, _aes2.AES_asm.HEAP_DATA + pos, wlen);
  2147. wlen = asm.cipher(_aes2.AES_asm.DEC.CTR, _aes2.AES_asm.HEAP_DATA + pos, wlen);
  2148. if (wlen) result.set(heap.subarray(pos, pos + wlen), rpos);
  2149. counter += wlen >>> 4;
  2150. rpos += wlen;
  2151. pos = 0;
  2152. len = 0;
  2153. }
  2154. if (dlen > 0) {
  2155. len += (0, _utils._heap_write)(heap, 0, data, dpos, dlen);
  2156. }
  2157. this.counter = counter;
  2158. this.pos = pos;
  2159. this.len = len;
  2160. return result;
  2161. };
  2162. AES_GCM.prototype.AES_GCM_Decrypt_finish = function () {
  2163. var asm = this.asm;
  2164. var heap = this.heap;
  2165. var tagSize = this.tagSize;
  2166. var adata = this.adata;
  2167. var counter = this.counter;
  2168. var pos = this.pos;
  2169. var len = this.len;
  2170. var rlen = len - tagSize;
  2171. if (len < tagSize) throw new _errors.IllegalStateError('authentication tag not found');
  2172. var result = new Uint8Array(rlen);
  2173. var atag = new Uint8Array(heap.subarray(pos + rlen, pos + len));
  2174. var i = rlen;
  2175. for (; i & 15; i++) heap[pos + i] = 0;
  2176. asm.mac(_aes2.AES_asm.MAC.GCM, _aes2.AES_asm.HEAP_DATA + pos, i);
  2177. asm.cipher(_aes2.AES_asm.DEC.CTR, _aes2.AES_asm.HEAP_DATA + pos, i);
  2178. if (rlen) result.set(heap.subarray(pos, pos + rlen));
  2179. var alen = adata !== undefined ? adata.length : 0;
  2180. var clen = (counter - 1 << 4) + len - tagSize;
  2181. heap[0] = 0;
  2182. heap[1] = 0;
  2183. heap[2] = 0;
  2184. heap[3] = alen >>> 29;
  2185. heap[4] = alen >>> 21;
  2186. heap[5] = alen >>> 13 & 255;
  2187. heap[6] = alen >>> 5 & 255;
  2188. heap[7] = alen << 3 & 255;
  2189. heap[8] = heap[9] = heap[10] = 0;
  2190. heap[11] = clen >>> 29;
  2191. heap[12] = clen >>> 21 & 255;
  2192. heap[13] = clen >>> 13 & 255;
  2193. heap[14] = clen >>> 5 & 255;
  2194. heap[15] = clen << 3 & 255;
  2195. asm.mac(_aes2.AES_asm.MAC.GCM, _aes2.AES_asm.HEAP_DATA, 16);
  2196. asm.get_iv(_aes2.AES_asm.HEAP_DATA);
  2197. asm.set_counter(0, 0, 0, this.gamma0);
  2198. asm.cipher(_aes2.AES_asm.ENC.CTR, _aes2.AES_asm.HEAP_DATA, 16);
  2199. var acheck = 0;
  2200. for (var i_1 = 0; i_1 < tagSize; ++i_1) acheck |= atag[i_1] ^ heap[i_1];
  2201. if (acheck) throw new _errors.SecurityError('data integrity check failed');
  2202. this.counter = 1;
  2203. this.pos = 0;
  2204. this.len = 0;
  2205. return result;
  2206. };
  2207. AES_GCM.prototype.AES_GCM_decrypt = function (data) {
  2208. var result1 = this.AES_GCM_Decrypt_process(data);
  2209. var result2 = this.AES_GCM_Decrypt_finish();
  2210. var result = new Uint8Array(result1.length + result2.length);
  2211. if (result1.length) result.set(result1);
  2212. if (result2.length) result.set(result2, result1.length);
  2213. return result;
  2214. };
  2215. AES_GCM.prototype.AES_GCM_encrypt = function (data) {
  2216. var result1 = this.AES_GCM_Encrypt_process(data);
  2217. var result2 = this.AES_GCM_Encrypt_finish();
  2218. var result = new Uint8Array(result1.length + result2.length);
  2219. if (result1.length) result.set(result1);
  2220. if (result2.length) result.set(result2, result1.length);
  2221. return result;
  2222. };
  2223. AES_GCM.prototype._gcm_mac_process = function (data) {
  2224. var heap = this.heap;
  2225. var asm = this.asm;
  2226. var dpos = 0;
  2227. var dlen = data.length || 0;
  2228. var wlen = 0;
  2229. while (dlen > 0) {
  2230. wlen = (0, _utils._heap_write)(heap, 0, data, dpos, dlen);
  2231. dpos += wlen;
  2232. dlen -= wlen;
  2233. while (wlen & 15) heap[wlen++] = 0;
  2234. asm.mac(_aes2.AES_asm.MAC.GCM, _aes2.AES_asm.HEAP_DATA, wlen);
  2235. }
  2236. };
  2237. return AES_GCM;
  2238. }(_aes.AES);
  2239. exports.AES_GCM = AES_GCM;
  2240. },{"../other/errors":14,"../other/utils":15,"./aes":3,"./aes.asm":2}],9:[function(require,module,exports){
  2241. 'use strict';
  2242. Object.defineProperty(exports, "__esModule", {
  2243. value: true
  2244. });
  2245. exports.Hash = undefined;
  2246. var _utils = require('../other/utils');
  2247. var _errors = require('../other/errors');
  2248. var Hash = /** @class */function () {
  2249. function Hash() {
  2250. this.pos = 0;
  2251. this.len = 0;
  2252. this.acquire_asm();
  2253. }
  2254. Hash.prototype.acquire_asm = function () {
  2255. if (this.heap === undefined && this.asm === undefined) {
  2256. this.heap = this.constructor.heap_pool.pop() || (0, _utils._heap_init)();
  2257. this.asm = this.constructor.asm_pool.pop() || this.constructor.asm_function({ Uint8Array: Uint8Array }, null, this.heap.buffer);
  2258. this.reset();
  2259. }
  2260. };
  2261. Hash.prototype.release_asm = function () {
  2262. this.constructor.heap_pool.push(this.heap);
  2263. ;
  2264. this.constructor.asm_pool.push(this.asm);
  2265. this.heap = undefined;
  2266. this.asm = undefined;
  2267. };
  2268. Hash.prototype.reset = function () {
  2269. this.acquire_asm();
  2270. this.result = null;
  2271. this.pos = 0;
  2272. this.len = 0;
  2273. this.asm.reset();
  2274. return this;
  2275. };
  2276. Hash.prototype.process = function (data) {
  2277. if (this.result !== null) throw new _errors.IllegalStateError('state must be reset before processing new data');
  2278. this.acquire_asm();
  2279. var asm = this.asm;
  2280. var heap = this.heap;
  2281. var hpos = this.pos;
  2282. var hlen = this.len;
  2283. var dpos = 0;
  2284. var dlen = data.length;
  2285. var wlen = 0;
  2286. while (dlen > 0) {
  2287. wlen = (0, _utils._heap_write)(heap, hpos + hlen, data, dpos, dlen);
  2288. hlen += wlen;
  2289. dpos += wlen;
  2290. dlen -= wlen;
  2291. wlen = asm.process(hpos, hlen);
  2292. hpos += wlen;
  2293. hlen -= wlen;
  2294. if (!hlen) hpos = 0;
  2295. }
  2296. this.pos = hpos;
  2297. this.len = hlen;
  2298. return this;
  2299. };
  2300. Hash.prototype.finish = function () {
  2301. if (this.result !== null) throw new _errors.IllegalStateError('state must be reset before processing new data');
  2302. this.acquire_asm();
  2303. this.asm.finish(this.pos, this.len, 0);
  2304. this.result = new Uint8Array(this.HASH_SIZE);
  2305. this.result.set(this.heap.subarray(0, this.HASH_SIZE));
  2306. this.pos = 0;
  2307. this.len = 0;
  2308. this.release_asm();
  2309. return this;
  2310. };
  2311. return Hash;
  2312. }();
  2313. exports.Hash = Hash;
  2314. },{"../other/errors":14,"../other/utils":15}],10:[function(require,module,exports){
  2315. "use strict";
  2316. Object.defineProperty(exports, "__esModule", {
  2317. value: true
  2318. });
  2319. exports.sha1_asm = sha1_asm;
  2320. function sha1_asm(stdlib, foreign, buffer) {
  2321. "use asm";
  2322. // SHA256 state
  2323. var H0 = 0,
  2324. H1 = 0,
  2325. H2 = 0,
  2326. H3 = 0,
  2327. H4 = 0,
  2328. TOTAL0 = 0,
  2329. TOTAL1 = 0;
  2330. // HMAC state
  2331. var I0 = 0,
  2332. I1 = 0,
  2333. I2 = 0,
  2334. I3 = 0,
  2335. I4 = 0,
  2336. O0 = 0,
  2337. O1 = 0,
  2338. O2 = 0,
  2339. O3 = 0,
  2340. O4 = 0;
  2341. // I/O buffer
  2342. var HEAP = new stdlib.Uint8Array(buffer);
  2343. function _core(w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15) {
  2344. w0 = w0 | 0;
  2345. w1 = w1 | 0;
  2346. w2 = w2 | 0;
  2347. w3 = w3 | 0;
  2348. w4 = w4 | 0;
  2349. w5 = w5 | 0;
  2350. w6 = w6 | 0;
  2351. w7 = w7 | 0;
  2352. w8 = w8 | 0;
  2353. w9 = w9 | 0;
  2354. w10 = w10 | 0;
  2355. w11 = w11 | 0;
  2356. w12 = w12 | 0;
  2357. w13 = w13 | 0;
  2358. w14 = w14 | 0;
  2359. w15 = w15 | 0;
  2360. var a = 0,
  2361. b = 0,
  2362. c = 0,
  2363. d = 0,
  2364. e = 0,
  2365. n = 0,
  2366. t = 0,
  2367. w16 = 0,
  2368. w17 = 0,
  2369. w18 = 0,
  2370. w19 = 0,
  2371. w20 = 0,
  2372. w21 = 0,
  2373. w22 = 0,
  2374. w23 = 0,
  2375. w24 = 0,
  2376. w25 = 0,
  2377. w26 = 0,
  2378. w27 = 0,
  2379. w28 = 0,
  2380. w29 = 0,
  2381. w30 = 0,
  2382. w31 = 0,
  2383. w32 = 0,
  2384. w33 = 0,
  2385. w34 = 0,
  2386. w35 = 0,
  2387. w36 = 0,
  2388. w37 = 0,
  2389. w38 = 0,
  2390. w39 = 0,
  2391. w40 = 0,
  2392. w41 = 0,
  2393. w42 = 0,
  2394. w43 = 0,
  2395. w44 = 0,
  2396. w45 = 0,
  2397. w46 = 0,
  2398. w47 = 0,
  2399. w48 = 0,
  2400. w49 = 0,
  2401. w50 = 0,
  2402. w51 = 0,
  2403. w52 = 0,
  2404. w53 = 0,
  2405. w54 = 0,
  2406. w55 = 0,
  2407. w56 = 0,
  2408. w57 = 0,
  2409. w58 = 0,
  2410. w59 = 0,
  2411. w60 = 0,
  2412. w61 = 0,
  2413. w62 = 0,
  2414. w63 = 0,
  2415. w64 = 0,
  2416. w65 = 0,
  2417. w66 = 0,
  2418. w67 = 0,
  2419. w68 = 0,
  2420. w69 = 0,
  2421. w70 = 0,
  2422. w71 = 0,
  2423. w72 = 0,
  2424. w73 = 0,
  2425. w74 = 0,
  2426. w75 = 0,
  2427. w76 = 0,
  2428. w77 = 0,
  2429. w78 = 0,
  2430. w79 = 0;
  2431. a = H0;
  2432. b = H1;
  2433. c = H2;
  2434. d = H3;
  2435. e = H4;
  2436. // 0
  2437. t = w0 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
  2438. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2439. // 1
  2440. t = w1 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
  2441. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2442. // 2
  2443. t = w2 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
  2444. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2445. // 3
  2446. t = w3 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
  2447. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2448. // 4
  2449. t = w4 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
  2450. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2451. // 5
  2452. t = w5 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
  2453. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2454. // 6
  2455. t = w6 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
  2456. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2457. // 7
  2458. t = w7 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
  2459. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2460. // 8
  2461. t = w8 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
  2462. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2463. // 9
  2464. t = w9 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
  2465. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2466. // 10
  2467. t = w10 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
  2468. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2469. // 11
  2470. t = w11 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
  2471. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2472. // 12
  2473. t = w12 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
  2474. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2475. // 13
  2476. t = w13 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
  2477. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2478. // 14
  2479. t = w14 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
  2480. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2481. // 15
  2482. t = w15 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
  2483. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2484. // 16
  2485. n = w13 ^ w8 ^ w2 ^ w0;
  2486. w16 = n << 1 | n >>> 31;
  2487. t = w16 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
  2488. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2489. // 17
  2490. n = w14 ^ w9 ^ w3 ^ w1;
  2491. w17 = n << 1 | n >>> 31;
  2492. t = w17 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
  2493. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2494. // 18
  2495. n = w15 ^ w10 ^ w4 ^ w2;
  2496. w18 = n << 1 | n >>> 31;
  2497. t = w18 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
  2498. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2499. // 19
  2500. n = w16 ^ w11 ^ w5 ^ w3;
  2501. w19 = n << 1 | n >>> 31;
  2502. t = w19 + (a << 5 | a >>> 27) + e + (b & c | ~b & d) + 0x5a827999 | 0;
  2503. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2504. // 20
  2505. n = w17 ^ w12 ^ w6 ^ w4;
  2506. w20 = n << 1 | n >>> 31;
  2507. t = w20 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
  2508. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2509. // 21
  2510. n = w18 ^ w13 ^ w7 ^ w5;
  2511. w21 = n << 1 | n >>> 31;
  2512. t = w21 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
  2513. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2514. // 22
  2515. n = w19 ^ w14 ^ w8 ^ w6;
  2516. w22 = n << 1 | n >>> 31;
  2517. t = w22 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
  2518. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2519. // 23
  2520. n = w20 ^ w15 ^ w9 ^ w7;
  2521. w23 = n << 1 | n >>> 31;
  2522. t = w23 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
  2523. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2524. // 24
  2525. n = w21 ^ w16 ^ w10 ^ w8;
  2526. w24 = n << 1 | n >>> 31;
  2527. t = w24 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
  2528. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2529. // 25
  2530. n = w22 ^ w17 ^ w11 ^ w9;
  2531. w25 = n << 1 | n >>> 31;
  2532. t = w25 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
  2533. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2534. // 26
  2535. n = w23 ^ w18 ^ w12 ^ w10;
  2536. w26 = n << 1 | n >>> 31;
  2537. t = w26 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
  2538. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2539. // 27
  2540. n = w24 ^ w19 ^ w13 ^ w11;
  2541. w27 = n << 1 | n >>> 31;
  2542. t = w27 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
  2543. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2544. // 28
  2545. n = w25 ^ w20 ^ w14 ^ w12;
  2546. w28 = n << 1 | n >>> 31;
  2547. t = w28 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
  2548. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2549. // 29
  2550. n = w26 ^ w21 ^ w15 ^ w13;
  2551. w29 = n << 1 | n >>> 31;
  2552. t = w29 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
  2553. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2554. // 30
  2555. n = w27 ^ w22 ^ w16 ^ w14;
  2556. w30 = n << 1 | n >>> 31;
  2557. t = w30 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
  2558. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2559. // 31
  2560. n = w28 ^ w23 ^ w17 ^ w15;
  2561. w31 = n << 1 | n >>> 31;
  2562. t = w31 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
  2563. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2564. // 32
  2565. n = w29 ^ w24 ^ w18 ^ w16;
  2566. w32 = n << 1 | n >>> 31;
  2567. t = w32 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
  2568. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2569. // 33
  2570. n = w30 ^ w25 ^ w19 ^ w17;
  2571. w33 = n << 1 | n >>> 31;
  2572. t = w33 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
  2573. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2574. // 34
  2575. n = w31 ^ w26 ^ w20 ^ w18;
  2576. w34 = n << 1 | n >>> 31;
  2577. t = w34 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
  2578. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2579. // 35
  2580. n = w32 ^ w27 ^ w21 ^ w19;
  2581. w35 = n << 1 | n >>> 31;
  2582. t = w35 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
  2583. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2584. // 36
  2585. n = w33 ^ w28 ^ w22 ^ w20;
  2586. w36 = n << 1 | n >>> 31;
  2587. t = w36 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
  2588. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2589. // 37
  2590. n = w34 ^ w29 ^ w23 ^ w21;
  2591. w37 = n << 1 | n >>> 31;
  2592. t = w37 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
  2593. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2594. // 38
  2595. n = w35 ^ w30 ^ w24 ^ w22;
  2596. w38 = n << 1 | n >>> 31;
  2597. t = w38 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
  2598. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2599. // 39
  2600. n = w36 ^ w31 ^ w25 ^ w23;
  2601. w39 = n << 1 | n >>> 31;
  2602. t = w39 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) + 0x6ed9eba1 | 0;
  2603. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2604. // 40
  2605. n = w37 ^ w32 ^ w26 ^ w24;
  2606. w40 = n << 1 | n >>> 31;
  2607. t = w40 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
  2608. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2609. // 41
  2610. n = w38 ^ w33 ^ w27 ^ w25;
  2611. w41 = n << 1 | n >>> 31;
  2612. t = w41 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
  2613. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2614. // 42
  2615. n = w39 ^ w34 ^ w28 ^ w26;
  2616. w42 = n << 1 | n >>> 31;
  2617. t = w42 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
  2618. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2619. // 43
  2620. n = w40 ^ w35 ^ w29 ^ w27;
  2621. w43 = n << 1 | n >>> 31;
  2622. t = w43 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
  2623. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2624. // 44
  2625. n = w41 ^ w36 ^ w30 ^ w28;
  2626. w44 = n << 1 | n >>> 31;
  2627. t = w44 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
  2628. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2629. // 45
  2630. n = w42 ^ w37 ^ w31 ^ w29;
  2631. w45 = n << 1 | n >>> 31;
  2632. t = w45 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
  2633. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2634. // 46
  2635. n = w43 ^ w38 ^ w32 ^ w30;
  2636. w46 = n << 1 | n >>> 31;
  2637. t = w46 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
  2638. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2639. // 47
  2640. n = w44 ^ w39 ^ w33 ^ w31;
  2641. w47 = n << 1 | n >>> 31;
  2642. t = w47 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
  2643. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2644. // 48
  2645. n = w45 ^ w40 ^ w34 ^ w32;
  2646. w48 = n << 1 | n >>> 31;
  2647. t = w48 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
  2648. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2649. // 49
  2650. n = w46 ^ w41 ^ w35 ^ w33;
  2651. w49 = n << 1 | n >>> 31;
  2652. t = w49 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
  2653. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2654. // 50
  2655. n = w47 ^ w42 ^ w36 ^ w34;
  2656. w50 = n << 1 | n >>> 31;
  2657. t = w50 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
  2658. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2659. // 51
  2660. n = w48 ^ w43 ^ w37 ^ w35;
  2661. w51 = n << 1 | n >>> 31;
  2662. t = w51 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
  2663. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2664. // 52
  2665. n = w49 ^ w44 ^ w38 ^ w36;
  2666. w52 = n << 1 | n >>> 31;
  2667. t = w52 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
  2668. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2669. // 53
  2670. n = w50 ^ w45 ^ w39 ^ w37;
  2671. w53 = n << 1 | n >>> 31;
  2672. t = w53 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
  2673. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2674. // 54
  2675. n = w51 ^ w46 ^ w40 ^ w38;
  2676. w54 = n << 1 | n >>> 31;
  2677. t = w54 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
  2678. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2679. // 55
  2680. n = w52 ^ w47 ^ w41 ^ w39;
  2681. w55 = n << 1 | n >>> 31;
  2682. t = w55 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
  2683. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2684. // 56
  2685. n = w53 ^ w48 ^ w42 ^ w40;
  2686. w56 = n << 1 | n >>> 31;
  2687. t = w56 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
  2688. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2689. // 57
  2690. n = w54 ^ w49 ^ w43 ^ w41;
  2691. w57 = n << 1 | n >>> 31;
  2692. t = w57 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
  2693. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2694. // 58
  2695. n = w55 ^ w50 ^ w44 ^ w42;
  2696. w58 = n << 1 | n >>> 31;
  2697. t = w58 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
  2698. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2699. // 59
  2700. n = w56 ^ w51 ^ w45 ^ w43;
  2701. w59 = n << 1 | n >>> 31;
  2702. t = w59 + (a << 5 | a >>> 27) + e + (b & c | b & d | c & d) - 0x70e44324 | 0;
  2703. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2704. // 60
  2705. n = w57 ^ w52 ^ w46 ^ w44;
  2706. w60 = n << 1 | n >>> 31;
  2707. t = w60 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
  2708. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2709. // 61
  2710. n = w58 ^ w53 ^ w47 ^ w45;
  2711. w61 = n << 1 | n >>> 31;
  2712. t = w61 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
  2713. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2714. // 62
  2715. n = w59 ^ w54 ^ w48 ^ w46;
  2716. w62 = n << 1 | n >>> 31;
  2717. t = w62 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
  2718. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2719. // 63
  2720. n = w60 ^ w55 ^ w49 ^ w47;
  2721. w63 = n << 1 | n >>> 31;
  2722. t = w63 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
  2723. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2724. // 64
  2725. n = w61 ^ w56 ^ w50 ^ w48;
  2726. w64 = n << 1 | n >>> 31;
  2727. t = w64 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
  2728. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2729. // 65
  2730. n = w62 ^ w57 ^ w51 ^ w49;
  2731. w65 = n << 1 | n >>> 31;
  2732. t = w65 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
  2733. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2734. // 66
  2735. n = w63 ^ w58 ^ w52 ^ w50;
  2736. w66 = n << 1 | n >>> 31;
  2737. t = w66 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
  2738. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2739. // 67
  2740. n = w64 ^ w59 ^ w53 ^ w51;
  2741. w67 = n << 1 | n >>> 31;
  2742. t = w67 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
  2743. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2744. // 68
  2745. n = w65 ^ w60 ^ w54 ^ w52;
  2746. w68 = n << 1 | n >>> 31;
  2747. t = w68 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
  2748. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2749. // 69
  2750. n = w66 ^ w61 ^ w55 ^ w53;
  2751. w69 = n << 1 | n >>> 31;
  2752. t = w69 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
  2753. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2754. // 70
  2755. n = w67 ^ w62 ^ w56 ^ w54;
  2756. w70 = n << 1 | n >>> 31;
  2757. t = w70 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
  2758. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2759. // 71
  2760. n = w68 ^ w63 ^ w57 ^ w55;
  2761. w71 = n << 1 | n >>> 31;
  2762. t = w71 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
  2763. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2764. // 72
  2765. n = w69 ^ w64 ^ w58 ^ w56;
  2766. w72 = n << 1 | n >>> 31;
  2767. t = w72 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
  2768. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2769. // 73
  2770. n = w70 ^ w65 ^ w59 ^ w57;
  2771. w73 = n << 1 | n >>> 31;
  2772. t = w73 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
  2773. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2774. // 74
  2775. n = w71 ^ w66 ^ w60 ^ w58;
  2776. w74 = n << 1 | n >>> 31;
  2777. t = w74 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
  2778. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2779. // 75
  2780. n = w72 ^ w67 ^ w61 ^ w59;
  2781. w75 = n << 1 | n >>> 31;
  2782. t = w75 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
  2783. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2784. // 76
  2785. n = w73 ^ w68 ^ w62 ^ w60;
  2786. w76 = n << 1 | n >>> 31;
  2787. t = w76 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
  2788. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2789. // 77
  2790. n = w74 ^ w69 ^ w63 ^ w61;
  2791. w77 = n << 1 | n >>> 31;
  2792. t = w77 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
  2793. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2794. // 78
  2795. n = w75 ^ w70 ^ w64 ^ w62;
  2796. w78 = n << 1 | n >>> 31;
  2797. t = w78 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
  2798. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2799. // 79
  2800. n = w76 ^ w71 ^ w65 ^ w63;
  2801. w79 = n << 1 | n >>> 31;
  2802. t = w79 + (a << 5 | a >>> 27) + e + (b ^ c ^ d) - 0x359d3e2a | 0;
  2803. e = d;d = c;c = b << 30 | b >>> 2;b = a;a = t;
  2804. H0 = H0 + a | 0;
  2805. H1 = H1 + b | 0;
  2806. H2 = H2 + c | 0;
  2807. H3 = H3 + d | 0;
  2808. H4 = H4 + e | 0;
  2809. }
  2810. function _core_heap(offset) {
  2811. offset = offset | 0;
  2812. _core(HEAP[offset | 0] << 24 | HEAP[offset | 1] << 16 | HEAP[offset | 2] << 8 | HEAP[offset | 3], HEAP[offset | 4] << 24 | HEAP[offset | 5] << 16 | HEAP[offset | 6] << 8 | HEAP[offset | 7], HEAP[offset | 8] << 24 | HEAP[offset | 9] << 16 | HEAP[offset | 10] << 8 | HEAP[offset | 11], HEAP[offset | 12] << 24 | HEAP[offset | 13] << 16 | HEAP[offset | 14] << 8 | HEAP[offset | 15], HEAP[offset | 16] << 24 | HEAP[offset | 17] << 16 | HEAP[offset | 18] << 8 | HEAP[offset | 19], HEAP[offset | 20] << 24 | HEAP[offset | 21] << 16 | HEAP[offset | 22] << 8 | HEAP[offset | 23], HEAP[offset | 24] << 24 | HEAP[offset | 25] << 16 | HEAP[offset | 26] << 8 | HEAP[offset | 27], HEAP[offset | 28] << 24 | HEAP[offset | 29] << 16 | HEAP[offset | 30] << 8 | HEAP[offset | 31], HEAP[offset | 32] << 24 | HEAP[offset | 33] << 16 | HEAP[offset | 34] << 8 | HEAP[offset | 35], HEAP[offset | 36] << 24 | HEAP[offset | 37] << 16 | HEAP[offset | 38] << 8 | HEAP[offset | 39], HEAP[offset | 40] << 24 | HEAP[offset | 41] << 16 | HEAP[offset | 42] << 8 | HEAP[offset | 43], HEAP[offset | 44] << 24 | HEAP[offset | 45] << 16 | HEAP[offset | 46] << 8 | HEAP[offset | 47], HEAP[offset | 48] << 24 | HEAP[offset | 49] << 16 | HEAP[offset | 50] << 8 | HEAP[offset | 51], HEAP[offset | 52] << 24 | HEAP[offset | 53] << 16 | HEAP[offset | 54] << 8 | HEAP[offset | 55], HEAP[offset | 56] << 24 | HEAP[offset | 57] << 16 | HEAP[offset | 58] << 8 | HEAP[offset | 59], HEAP[offset | 60] << 24 | HEAP[offset | 61] << 16 | HEAP[offset | 62] << 8 | HEAP[offset | 63]);
  2813. }
  2814. // offset — multiple of 32
  2815. function _state_to_heap(output) {
  2816. output = output | 0;
  2817. HEAP[output | 0] = H0 >>> 24;
  2818. HEAP[output | 1] = H0 >>> 16 & 255;
  2819. HEAP[output | 2] = H0 >>> 8 & 255;
  2820. HEAP[output | 3] = H0 & 255;
  2821. HEAP[output | 4] = H1 >>> 24;
  2822. HEAP[output | 5] = H1 >>> 16 & 255;
  2823. HEAP[output | 6] = H1 >>> 8 & 255;
  2824. HEAP[output | 7] = H1 & 255;
  2825. HEAP[output | 8] = H2 >>> 24;
  2826. HEAP[output | 9] = H2 >>> 16 & 255;
  2827. HEAP[output | 10] = H2 >>> 8 & 255;
  2828. HEAP[output | 11] = H2 & 255;
  2829. HEAP[output | 12] = H3 >>> 24;
  2830. HEAP[output | 13] = H3 >>> 16 & 255;
  2831. HEAP[output | 14] = H3 >>> 8 & 255;
  2832. HEAP[output | 15] = H3 & 255;
  2833. HEAP[output | 16] = H4 >>> 24;
  2834. HEAP[output | 17] = H4 >>> 16 & 255;
  2835. HEAP[output | 18] = H4 >>> 8 & 255;
  2836. HEAP[output | 19] = H4 & 255;
  2837. }
  2838. function reset() {
  2839. H0 = 0x67452301;
  2840. H1 = 0xefcdab89;
  2841. H2 = 0x98badcfe;
  2842. H3 = 0x10325476;
  2843. H4 = 0xc3d2e1f0;
  2844. TOTAL0 = TOTAL1 = 0;
  2845. }
  2846. function init(h0, h1, h2, h3, h4, total0, total1) {
  2847. h0 = h0 | 0;
  2848. h1 = h1 | 0;
  2849. h2 = h2 | 0;
  2850. h3 = h3 | 0;
  2851. h4 = h4 | 0;
  2852. total0 = total0 | 0;
  2853. total1 = total1 | 0;
  2854. H0 = h0;
  2855. H1 = h1;
  2856. H2 = h2;
  2857. H3 = h3;
  2858. H4 = h4;
  2859. TOTAL0 = total0;
  2860. TOTAL1 = total1;
  2861. }
  2862. // offset — multiple of 64
  2863. function process(offset, length) {
  2864. offset = offset | 0;
  2865. length = length | 0;
  2866. var hashed = 0;
  2867. if (offset & 63) return -1;
  2868. while ((length | 0) >= 64) {
  2869. _core_heap(offset);
  2870. offset = offset + 64 | 0;
  2871. length = length - 64 | 0;
  2872. hashed = hashed + 64 | 0;
  2873. }
  2874. TOTAL0 = TOTAL0 + hashed | 0;
  2875. if (TOTAL0 >>> 0 < hashed >>> 0) TOTAL1 = TOTAL1 + 1 | 0;
  2876. return hashed | 0;
  2877. }
  2878. // offset — multiple of 64
  2879. // output — multiple of 32
  2880. function finish(offset, length, output) {
  2881. offset = offset | 0;
  2882. length = length | 0;
  2883. output = output | 0;
  2884. var hashed = 0,
  2885. i = 0;
  2886. if (offset & 63) return -1;
  2887. if (~output) if (output & 31) return -1;
  2888. if ((length | 0) >= 64) {
  2889. hashed = process(offset, length) | 0;
  2890. if ((hashed | 0) == -1) return -1;
  2891. offset = offset + hashed | 0;
  2892. length = length - hashed | 0;
  2893. }
  2894. hashed = hashed + length | 0;
  2895. TOTAL0 = TOTAL0 + length | 0;
  2896. if (TOTAL0 >>> 0 < length >>> 0) TOTAL1 = TOTAL1 + 1 | 0;
  2897. HEAP[offset | length] = 0x80;
  2898. if ((length | 0) >= 56) {
  2899. for (i = length + 1 | 0; (i | 0) < 64; i = i + 1 | 0) HEAP[offset | i] = 0x00;
  2900. _core_heap(offset);
  2901. length = 0;
  2902. HEAP[offset | 0] = 0;
  2903. }
  2904. for (i = length + 1 | 0; (i | 0) < 59; i = i + 1 | 0) HEAP[offset | i] = 0;
  2905. HEAP[offset | 56] = TOTAL1 >>> 21 & 255;
  2906. HEAP[offset | 57] = TOTAL1 >>> 13 & 255;
  2907. HEAP[offset | 58] = TOTAL1 >>> 5 & 255;
  2908. HEAP[offset | 59] = TOTAL1 << 3 & 255 | TOTAL0 >>> 29;
  2909. HEAP[offset | 60] = TOTAL0 >>> 21 & 255;
  2910. HEAP[offset | 61] = TOTAL0 >>> 13 & 255;
  2911. HEAP[offset | 62] = TOTAL0 >>> 5 & 255;
  2912. HEAP[offset | 63] = TOTAL0 << 3 & 255;
  2913. _core_heap(offset);
  2914. if (~output) _state_to_heap(output);
  2915. return hashed | 0;
  2916. }
  2917. function hmac_reset() {
  2918. H0 = I0;
  2919. H1 = I1;
  2920. H2 = I2;
  2921. H3 = I3;
  2922. H4 = I4;
  2923. TOTAL0 = 64;
  2924. TOTAL1 = 0;
  2925. }
  2926. function _hmac_opad() {
  2927. H0 = O0;
  2928. H1 = O1;
  2929. H2 = O2;
  2930. H3 = O3;
  2931. H4 = O4;
  2932. TOTAL0 = 64;
  2933. TOTAL1 = 0;
  2934. }
  2935. function hmac_init(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15) {
  2936. p0 = p0 | 0;
  2937. p1 = p1 | 0;
  2938. p2 = p2 | 0;
  2939. p3 = p3 | 0;
  2940. p4 = p4 | 0;
  2941. p5 = p5 | 0;
  2942. p6 = p6 | 0;
  2943. p7 = p7 | 0;
  2944. p8 = p8 | 0;
  2945. p9 = p9 | 0;
  2946. p10 = p10 | 0;
  2947. p11 = p11 | 0;
  2948. p12 = p12 | 0;
  2949. p13 = p13 | 0;
  2950. p14 = p14 | 0;
  2951. p15 = p15 | 0;
  2952. // opad
  2953. reset();
  2954. _core(p0 ^ 0x5c5c5c5c, p1 ^ 0x5c5c5c5c, p2 ^ 0x5c5c5c5c, p3 ^ 0x5c5c5c5c, p4 ^ 0x5c5c5c5c, p5 ^ 0x5c5c5c5c, p6 ^ 0x5c5c5c5c, p7 ^ 0x5c5c5c5c, p8 ^ 0x5c5c5c5c, p9 ^ 0x5c5c5c5c, p10 ^ 0x5c5c5c5c, p11 ^ 0x5c5c5c5c, p12 ^ 0x5c5c5c5c, p13 ^ 0x5c5c5c5c, p14 ^ 0x5c5c5c5c, p15 ^ 0x5c5c5c5c);
  2955. O0 = H0;
  2956. O1 = H1;
  2957. O2 = H2;
  2958. O3 = H3;
  2959. O4 = H4;
  2960. // ipad
  2961. reset();
  2962. _core(p0 ^ 0x36363636, p1 ^ 0x36363636, p2 ^ 0x36363636, p3 ^ 0x36363636, p4 ^ 0x36363636, p5 ^ 0x36363636, p6 ^ 0x36363636, p7 ^ 0x36363636, p8 ^ 0x36363636, p9 ^ 0x36363636, p10 ^ 0x36363636, p11 ^ 0x36363636, p12 ^ 0x36363636, p13 ^ 0x36363636, p14 ^ 0x36363636, p15 ^ 0x36363636);
  2963. I0 = H0;
  2964. I1 = H1;
  2965. I2 = H2;
  2966. I3 = H3;
  2967. I4 = H4;
  2968. TOTAL0 = 64;
  2969. TOTAL1 = 0;
  2970. }
  2971. // offset — multiple of 64
  2972. // output — multiple of 32
  2973. function hmac_finish(offset, length, output) {
  2974. offset = offset | 0;
  2975. length = length | 0;
  2976. output = output | 0;
  2977. var t0 = 0,
  2978. t1 = 0,
  2979. t2 = 0,
  2980. t3 = 0,
  2981. t4 = 0,
  2982. hashed = 0;
  2983. if (offset & 63) return -1;
  2984. if (~output) if (output & 31) return -1;
  2985. hashed = finish(offset, length, -1) | 0;
  2986. t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;
  2987. _hmac_opad();
  2988. _core(t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672);
  2989. if (~output) _state_to_heap(output);
  2990. return hashed | 0;
  2991. }
  2992. // salt is assumed to be already processed
  2993. // offset — multiple of 64
  2994. // output — multiple of 32
  2995. function pbkdf2_generate_block(offset, length, block, count, output) {
  2996. offset = offset | 0;
  2997. length = length | 0;
  2998. block = block | 0;
  2999. count = count | 0;
  3000. output = output | 0;
  3001. var h0 = 0,
  3002. h1 = 0,
  3003. h2 = 0,
  3004. h3 = 0,
  3005. h4 = 0,
  3006. t0 = 0,
  3007. t1 = 0,
  3008. t2 = 0,
  3009. t3 = 0,
  3010. t4 = 0;
  3011. if (offset & 63) return -1;
  3012. if (~output) if (output & 31) return -1;
  3013. // pad block number into heap
  3014. // FIXME probable OOB write
  3015. HEAP[offset + length | 0] = block >>> 24;
  3016. HEAP[offset + length + 1 | 0] = block >>> 16 & 255;
  3017. HEAP[offset + length + 2 | 0] = block >>> 8 & 255;
  3018. HEAP[offset + length + 3 | 0] = block & 255;
  3019. // finish first iteration
  3020. hmac_finish(offset, length + 4 | 0, -1) | 0;
  3021. h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4;
  3022. count = count - 1 | 0;
  3023. // perform the rest iterations
  3024. while ((count | 0) > 0) {
  3025. hmac_reset();
  3026. _core(t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672);
  3027. t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;
  3028. _hmac_opad();
  3029. _core(t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672);
  3030. t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;
  3031. h0 = h0 ^ H0;
  3032. h1 = h1 ^ H1;
  3033. h2 = h2 ^ H2;
  3034. h3 = h3 ^ H3;
  3035. h4 = h4 ^ H4;
  3036. count = count - 1 | 0;
  3037. }
  3038. H0 = h0;
  3039. H1 = h1;
  3040. H2 = h2;
  3041. H3 = h3;
  3042. H4 = h4;
  3043. if (~output) _state_to_heap(output);
  3044. return 0;
  3045. }
  3046. return {
  3047. // SHA1
  3048. reset: reset,
  3049. init: init,
  3050. process: process,
  3051. finish: finish,
  3052. // HMAC-SHA1
  3053. hmac_reset: hmac_reset,
  3054. hmac_init: hmac_init,
  3055. hmac_finish: hmac_finish,
  3056. // PBKDF2-HMAC-SHA1
  3057. pbkdf2_generate_block: pbkdf2_generate_block
  3058. };
  3059. }
  3060. },{}],11:[function(require,module,exports){
  3061. 'use strict';
  3062. Object.defineProperty(exports, "__esModule", {
  3063. value: true
  3064. });
  3065. exports.Sha1 = exports._sha1_hash_size = exports._sha1_block_size = undefined;
  3066. var _sha = require('./sha1.asm');
  3067. var _hash = require('../hash');
  3068. var __extends = undefined && undefined.__extends || function () {
  3069. var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) {
  3070. d.__proto__ = b;
  3071. } || function (d, b) {
  3072. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3073. };
  3074. return function (d, b) {
  3075. extendStatics(d, b);
  3076. function __() {
  3077. this.constructor = d;
  3078. }
  3079. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3080. };
  3081. }();
  3082. var _sha1_block_size = exports._sha1_block_size = 64;
  3083. var _sha1_hash_size = exports._sha1_hash_size = 20;
  3084. var Sha1 = /** @class */function (_super) {
  3085. __extends(Sha1, _super);
  3086. function Sha1() {
  3087. var _this = _super !== null && _super.apply(this, arguments) || this;
  3088. _this.NAME = 'sha1';
  3089. _this.BLOCK_SIZE = _sha1_block_size;
  3090. _this.HASH_SIZE = _sha1_hash_size;
  3091. return _this;
  3092. }
  3093. Sha1.bytes = function (data) {
  3094. return new Sha1().process(data).finish().result;
  3095. };
  3096. Sha1.NAME = 'sha1';
  3097. Sha1.heap_pool = [];
  3098. Sha1.asm_pool = [];
  3099. Sha1.asm_function = _sha.sha1_asm;
  3100. return Sha1;
  3101. }(_hash.Hash);
  3102. exports.Sha1 = Sha1;
  3103. },{"../hash":9,"./sha1.asm":10}],12:[function(require,module,exports){
  3104. "use strict";
  3105. Object.defineProperty(exports, "__esModule", {
  3106. value: true
  3107. });
  3108. exports.sha256_asm = sha256_asm;
  3109. function sha256_asm(stdlib, foreign, buffer) {
  3110. "use asm";
  3111. // SHA256 state
  3112. var H0 = 0,
  3113. H1 = 0,
  3114. H2 = 0,
  3115. H3 = 0,
  3116. H4 = 0,
  3117. H5 = 0,
  3118. H6 = 0,
  3119. H7 = 0,
  3120. TOTAL0 = 0,
  3121. TOTAL1 = 0;
  3122. // HMAC state
  3123. var I0 = 0,
  3124. I1 = 0,
  3125. I2 = 0,
  3126. I3 = 0,
  3127. I4 = 0,
  3128. I5 = 0,
  3129. I6 = 0,
  3130. I7 = 0,
  3131. O0 = 0,
  3132. O1 = 0,
  3133. O2 = 0,
  3134. O3 = 0,
  3135. O4 = 0,
  3136. O5 = 0,
  3137. O6 = 0,
  3138. O7 = 0;
  3139. // I/O buffer
  3140. var HEAP = new stdlib.Uint8Array(buffer);
  3141. function _core(w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15) {
  3142. w0 = w0 | 0;
  3143. w1 = w1 | 0;
  3144. w2 = w2 | 0;
  3145. w3 = w3 | 0;
  3146. w4 = w4 | 0;
  3147. w5 = w5 | 0;
  3148. w6 = w6 | 0;
  3149. w7 = w7 | 0;
  3150. w8 = w8 | 0;
  3151. w9 = w9 | 0;
  3152. w10 = w10 | 0;
  3153. w11 = w11 | 0;
  3154. w12 = w12 | 0;
  3155. w13 = w13 | 0;
  3156. w14 = w14 | 0;
  3157. w15 = w15 | 0;
  3158. var a = 0,
  3159. b = 0,
  3160. c = 0,
  3161. d = 0,
  3162. e = 0,
  3163. f = 0,
  3164. g = 0,
  3165. h = 0;
  3166. a = H0;
  3167. b = H1;
  3168. c = H2;
  3169. d = H3;
  3170. e = H4;
  3171. f = H5;
  3172. g = H6;
  3173. h = H7;
  3174. // 0
  3175. h = w0 + h + (e >>> 6 ^ e >>> 11 ^ e >>> 25 ^ e << 26 ^ e << 21 ^ e << 7) + (g ^ e & (f ^ g)) + 0x428a2f98 | 0;
  3176. d = d + h | 0;
  3177. h = h + (a & b ^ c & (a ^ b)) + (a >>> 2 ^ a >>> 13 ^ a >>> 22 ^ a << 30 ^ a << 19 ^ a << 10) | 0;
  3178. // 1
  3179. g = w1 + g + (d >>> 6 ^ d >>> 11 ^ d >>> 25 ^ d << 26 ^ d << 21 ^ d << 7) + (f ^ d & (e ^ f)) + 0x71374491 | 0;
  3180. c = c + g | 0;
  3181. g = g + (h & a ^ b & (h ^ a)) + (h >>> 2 ^ h >>> 13 ^ h >>> 22 ^ h << 30 ^ h << 19 ^ h << 10) | 0;
  3182. // 2
  3183. f = w2 + f + (c >>> 6 ^ c >>> 11 ^ c >>> 25 ^ c << 26 ^ c << 21 ^ c << 7) + (e ^ c & (d ^ e)) + 0xb5c0fbcf | 0;
  3184. b = b + f | 0;
  3185. f = f + (g & h ^ a & (g ^ h)) + (g >>> 2 ^ g >>> 13 ^ g >>> 22 ^ g << 30 ^ g << 19 ^ g << 10) | 0;
  3186. // 3
  3187. e = w3 + e + (b >>> 6 ^ b >>> 11 ^ b >>> 25 ^ b << 26 ^ b << 21 ^ b << 7) + (d ^ b & (c ^ d)) + 0xe9b5dba5 | 0;
  3188. a = a + e | 0;
  3189. e = e + (f & g ^ h & (f ^ g)) + (f >>> 2 ^ f >>> 13 ^ f >>> 22 ^ f << 30 ^ f << 19 ^ f << 10) | 0;
  3190. // 4
  3191. d = w4 + d + (a >>> 6 ^ a >>> 11 ^ a >>> 25 ^ a << 26 ^ a << 21 ^ a << 7) + (c ^ a & (b ^ c)) + 0x3956c25b | 0;
  3192. h = h + d | 0;
  3193. d = d + (e & f ^ g & (e ^ f)) + (e >>> 2 ^ e >>> 13 ^ e >>> 22 ^ e << 30 ^ e << 19 ^ e << 10) | 0;
  3194. // 5
  3195. c = w5 + c + (h >>> 6 ^ h >>> 11 ^ h >>> 25 ^ h << 26 ^ h << 21 ^ h << 7) + (b ^ h & (a ^ b)) + 0x59f111f1 | 0;
  3196. g = g + c | 0;
  3197. c = c + (d & e ^ f & (d ^ e)) + (d >>> 2 ^ d >>> 13 ^ d >>> 22 ^ d << 30 ^ d << 19 ^ d << 10) | 0;
  3198. // 6
  3199. b = w6 + b + (g >>> 6 ^ g >>> 11 ^ g >>> 25 ^ g << 26 ^ g << 21 ^ g << 7) + (a ^ g & (h ^ a)) + 0x923f82a4 | 0;
  3200. f = f + b | 0;
  3201. b = b + (c & d ^ e & (c ^ d)) + (c >>> 2 ^ c >>> 13 ^ c >>> 22 ^ c << 30 ^ c << 19 ^ c << 10) | 0;
  3202. // 7
  3203. a = w7 + a + (f >>> 6 ^ f >>> 11 ^ f >>> 25 ^ f << 26 ^ f << 21 ^ f << 7) + (h ^ f & (g ^ h)) + 0xab1c5ed5 | 0;
  3204. e = e + a | 0;
  3205. a = a + (b & c ^ d & (b ^ c)) + (b >>> 2 ^ b >>> 13 ^ b >>> 22 ^ b << 30 ^ b << 19 ^ b << 10) | 0;
  3206. // 8
  3207. h = w8 + h + (e >>> 6 ^ e >>> 11 ^ e >>> 25 ^ e << 26 ^ e << 21 ^ e << 7) + (g ^ e & (f ^ g)) + 0xd807aa98 | 0;
  3208. d = d + h | 0;
  3209. h = h + (a & b ^ c & (a ^ b)) + (a >>> 2 ^ a >>> 13 ^ a >>> 22 ^ a << 30 ^ a << 19 ^ a << 10) | 0;
  3210. // 9
  3211. g = w9 + g + (d >>> 6 ^ d >>> 11 ^ d >>> 25 ^ d << 26 ^ d << 21 ^ d << 7) + (f ^ d & (e ^ f)) + 0x12835b01 | 0;
  3212. c = c + g | 0;
  3213. g = g + (h & a ^ b & (h ^ a)) + (h >>> 2 ^ h >>> 13 ^ h >>> 22 ^ h << 30 ^ h << 19 ^ h << 10) | 0;
  3214. // 10
  3215. f = w10 + f + (c >>> 6 ^ c >>> 11 ^ c >>> 25 ^ c << 26 ^ c << 21 ^ c << 7) + (e ^ c & (d ^ e)) + 0x243185be | 0;
  3216. b = b + f | 0;
  3217. f = f + (g & h ^ a & (g ^ h)) + (g >>> 2 ^ g >>> 13 ^ g >>> 22 ^ g << 30 ^ g << 19 ^ g << 10) | 0;
  3218. // 11
  3219. e = w11 + e + (b >>> 6 ^ b >>> 11 ^ b >>> 25 ^ b << 26 ^ b << 21 ^ b << 7) + (d ^ b & (c ^ d)) + 0x550c7dc3 | 0;
  3220. a = a + e | 0;
  3221. e = e + (f & g ^ h & (f ^ g)) + (f >>> 2 ^ f >>> 13 ^ f >>> 22 ^ f << 30 ^ f << 19 ^ f << 10) | 0;
  3222. // 12
  3223. d = w12 + d + (a >>> 6 ^ a >>> 11 ^ a >>> 25 ^ a << 26 ^ a << 21 ^ a << 7) + (c ^ a & (b ^ c)) + 0x72be5d74 | 0;
  3224. h = h + d | 0;
  3225. d = d + (e & f ^ g & (e ^ f)) + (e >>> 2 ^ e >>> 13 ^ e >>> 22 ^ e << 30 ^ e << 19 ^ e << 10) | 0;
  3226. // 13
  3227. c = w13 + c + (h >>> 6 ^ h >>> 11 ^ h >>> 25 ^ h << 26 ^ h << 21 ^ h << 7) + (b ^ h & (a ^ b)) + 0x80deb1fe | 0;
  3228. g = g + c | 0;
  3229. c = c + (d & e ^ f & (d ^ e)) + (d >>> 2 ^ d >>> 13 ^ d >>> 22 ^ d << 30 ^ d << 19 ^ d << 10) | 0;
  3230. // 14
  3231. b = w14 + b + (g >>> 6 ^ g >>> 11 ^ g >>> 25 ^ g << 26 ^ g << 21 ^ g << 7) + (a ^ g & (h ^ a)) + 0x9bdc06a7 | 0;
  3232. f = f + b | 0;
  3233. b = b + (c & d ^ e & (c ^ d)) + (c >>> 2 ^ c >>> 13 ^ c >>> 22 ^ c << 30 ^ c << 19 ^ c << 10) | 0;
  3234. // 15
  3235. a = w15 + a + (f >>> 6 ^ f >>> 11 ^ f >>> 25 ^ f << 26 ^ f << 21 ^ f << 7) + (h ^ f & (g ^ h)) + 0xc19bf174 | 0;
  3236. e = e + a | 0;
  3237. a = a + (b & c ^ d & (b ^ c)) + (b >>> 2 ^ b >>> 13 ^ b >>> 22 ^ b << 30 ^ b << 19 ^ b << 10) | 0;
  3238. // 16
  3239. w0 = (w1 >>> 7 ^ w1 >>> 18 ^ w1 >>> 3 ^ w1 << 25 ^ w1 << 14) + (w14 >>> 17 ^ w14 >>> 19 ^ w14 >>> 10 ^ w14 << 15 ^ w14 << 13) + w0 + w9 | 0;
  3240. h = w0 + h + (e >>> 6 ^ e >>> 11 ^ e >>> 25 ^ e << 26 ^ e << 21 ^ e << 7) + (g ^ e & (f ^ g)) + 0xe49b69c1 | 0;
  3241. d = d + h | 0;
  3242. h = h + (a & b ^ c & (a ^ b)) + (a >>> 2 ^ a >>> 13 ^ a >>> 22 ^ a << 30 ^ a << 19 ^ a << 10) | 0;
  3243. // 17
  3244. w1 = (w2 >>> 7 ^ w2 >>> 18 ^ w2 >>> 3 ^ w2 << 25 ^ w2 << 14) + (w15 >>> 17 ^ w15 >>> 19 ^ w15 >>> 10 ^ w15 << 15 ^ w15 << 13) + w1 + w10 | 0;
  3245. g = w1 + g + (d >>> 6 ^ d >>> 11 ^ d >>> 25 ^ d << 26 ^ d << 21 ^ d << 7) + (f ^ d & (e ^ f)) + 0xefbe4786 | 0;
  3246. c = c + g | 0;
  3247. g = g + (h & a ^ b & (h ^ a)) + (h >>> 2 ^ h >>> 13 ^ h >>> 22 ^ h << 30 ^ h << 19 ^ h << 10) | 0;
  3248. // 18
  3249. w2 = (w3 >>> 7 ^ w3 >>> 18 ^ w3 >>> 3 ^ w3 << 25 ^ w3 << 14) + (w0 >>> 17 ^ w0 >>> 19 ^ w0 >>> 10 ^ w0 << 15 ^ w0 << 13) + w2 + w11 | 0;
  3250. f = w2 + f + (c >>> 6 ^ c >>> 11 ^ c >>> 25 ^ c << 26 ^ c << 21 ^ c << 7) + (e ^ c & (d ^ e)) + 0x0fc19dc6 | 0;
  3251. b = b + f | 0;
  3252. f = f + (g & h ^ a & (g ^ h)) + (g >>> 2 ^ g >>> 13 ^ g >>> 22 ^ g << 30 ^ g << 19 ^ g << 10) | 0;
  3253. // 19
  3254. w3 = (w4 >>> 7 ^ w4 >>> 18 ^ w4 >>> 3 ^ w4 << 25 ^ w4 << 14) + (w1 >>> 17 ^ w1 >>> 19 ^ w1 >>> 10 ^ w1 << 15 ^ w1 << 13) + w3 + w12 | 0;
  3255. e = w3 + e + (b >>> 6 ^ b >>> 11 ^ b >>> 25 ^ b << 26 ^ b << 21 ^ b << 7) + (d ^ b & (c ^ d)) + 0x240ca1cc | 0;
  3256. a = a + e | 0;
  3257. e = e + (f & g ^ h & (f ^ g)) + (f >>> 2 ^ f >>> 13 ^ f >>> 22 ^ f << 30 ^ f << 19 ^ f << 10) | 0;
  3258. // 20
  3259. w4 = (w5 >>> 7 ^ w5 >>> 18 ^ w5 >>> 3 ^ w5 << 25 ^ w5 << 14) + (w2 >>> 17 ^ w2 >>> 19 ^ w2 >>> 10 ^ w2 << 15 ^ w2 << 13) + w4 + w13 | 0;
  3260. d = w4 + d + (a >>> 6 ^ a >>> 11 ^ a >>> 25 ^ a << 26 ^ a << 21 ^ a << 7) + (c ^ a & (b ^ c)) + 0x2de92c6f | 0;
  3261. h = h + d | 0;
  3262. d = d + (e & f ^ g & (e ^ f)) + (e >>> 2 ^ e >>> 13 ^ e >>> 22 ^ e << 30 ^ e << 19 ^ e << 10) | 0;
  3263. // 21
  3264. w5 = (w6 >>> 7 ^ w6 >>> 18 ^ w6 >>> 3 ^ w6 << 25 ^ w6 << 14) + (w3 >>> 17 ^ w3 >>> 19 ^ w3 >>> 10 ^ w3 << 15 ^ w3 << 13) + w5 + w14 | 0;
  3265. c = w5 + c + (h >>> 6 ^ h >>> 11 ^ h >>> 25 ^ h << 26 ^ h << 21 ^ h << 7) + (b ^ h & (a ^ b)) + 0x4a7484aa | 0;
  3266. g = g + c | 0;
  3267. c = c + (d & e ^ f & (d ^ e)) + (d >>> 2 ^ d >>> 13 ^ d >>> 22 ^ d << 30 ^ d << 19 ^ d << 10) | 0;
  3268. // 22
  3269. w6 = (w7 >>> 7 ^ w7 >>> 18 ^ w7 >>> 3 ^ w7 << 25 ^ w7 << 14) + (w4 >>> 17 ^ w4 >>> 19 ^ w4 >>> 10 ^ w4 << 15 ^ w4 << 13) + w6 + w15 | 0;
  3270. b = w6 + b + (g >>> 6 ^ g >>> 11 ^ g >>> 25 ^ g << 26 ^ g << 21 ^ g << 7) + (a ^ g & (h ^ a)) + 0x5cb0a9dc | 0;
  3271. f = f + b | 0;
  3272. b = b + (c & d ^ e & (c ^ d)) + (c >>> 2 ^ c >>> 13 ^ c >>> 22 ^ c << 30 ^ c << 19 ^ c << 10) | 0;
  3273. // 23
  3274. w7 = (w8 >>> 7 ^ w8 >>> 18 ^ w8 >>> 3 ^ w8 << 25 ^ w8 << 14) + (w5 >>> 17 ^ w5 >>> 19 ^ w5 >>> 10 ^ w5 << 15 ^ w5 << 13) + w7 + w0 | 0;
  3275. a = w7 + a + (f >>> 6 ^ f >>> 11 ^ f >>> 25 ^ f << 26 ^ f << 21 ^ f << 7) + (h ^ f & (g ^ h)) + 0x76f988da | 0;
  3276. e = e + a | 0;
  3277. a = a + (b & c ^ d & (b ^ c)) + (b >>> 2 ^ b >>> 13 ^ b >>> 22 ^ b << 30 ^ b << 19 ^ b << 10) | 0;
  3278. // 24
  3279. w8 = (w9 >>> 7 ^ w9 >>> 18 ^ w9 >>> 3 ^ w9 << 25 ^ w9 << 14) + (w6 >>> 17 ^ w6 >>> 19 ^ w6 >>> 10 ^ w6 << 15 ^ w6 << 13) + w8 + w1 | 0;
  3280. h = w8 + h + (e >>> 6 ^ e >>> 11 ^ e >>> 25 ^ e << 26 ^ e << 21 ^ e << 7) + (g ^ e & (f ^ g)) + 0x983e5152 | 0;
  3281. d = d + h | 0;
  3282. h = h + (a & b ^ c & (a ^ b)) + (a >>> 2 ^ a >>> 13 ^ a >>> 22 ^ a << 30 ^ a << 19 ^ a << 10) | 0;
  3283. // 25
  3284. w9 = (w10 >>> 7 ^ w10 >>> 18 ^ w10 >>> 3 ^ w10 << 25 ^ w10 << 14) + (w7 >>> 17 ^ w7 >>> 19 ^ w7 >>> 10 ^ w7 << 15 ^ w7 << 13) + w9 + w2 | 0;
  3285. g = w9 + g + (d >>> 6 ^ d >>> 11 ^ d >>> 25 ^ d << 26 ^ d << 21 ^ d << 7) + (f ^ d & (e ^ f)) + 0xa831c66d | 0;
  3286. c = c + g | 0;
  3287. g = g + (h & a ^ b & (h ^ a)) + (h >>> 2 ^ h >>> 13 ^ h >>> 22 ^ h << 30 ^ h << 19 ^ h << 10) | 0;
  3288. // 26
  3289. w10 = (w11 >>> 7 ^ w11 >>> 18 ^ w11 >>> 3 ^ w11 << 25 ^ w11 << 14) + (w8 >>> 17 ^ w8 >>> 19 ^ w8 >>> 10 ^ w8 << 15 ^ w8 << 13) + w10 + w3 | 0;
  3290. f = w10 + f + (c >>> 6 ^ c >>> 11 ^ c >>> 25 ^ c << 26 ^ c << 21 ^ c << 7) + (e ^ c & (d ^ e)) + 0xb00327c8 | 0;
  3291. b = b + f | 0;
  3292. f = f + (g & h ^ a & (g ^ h)) + (g >>> 2 ^ g >>> 13 ^ g >>> 22 ^ g << 30 ^ g << 19 ^ g << 10) | 0;
  3293. // 27
  3294. w11 = (w12 >>> 7 ^ w12 >>> 18 ^ w12 >>> 3 ^ w12 << 25 ^ w12 << 14) + (w9 >>> 17 ^ w9 >>> 19 ^ w9 >>> 10 ^ w9 << 15 ^ w9 << 13) + w11 + w4 | 0;
  3295. e = w11 + e + (b >>> 6 ^ b >>> 11 ^ b >>> 25 ^ b << 26 ^ b << 21 ^ b << 7) + (d ^ b & (c ^ d)) + 0xbf597fc7 | 0;
  3296. a = a + e | 0;
  3297. e = e + (f & g ^ h & (f ^ g)) + (f >>> 2 ^ f >>> 13 ^ f >>> 22 ^ f << 30 ^ f << 19 ^ f << 10) | 0;
  3298. // 28
  3299. w12 = (w13 >>> 7 ^ w13 >>> 18 ^ w13 >>> 3 ^ w13 << 25 ^ w13 << 14) + (w10 >>> 17 ^ w10 >>> 19 ^ w10 >>> 10 ^ w10 << 15 ^ w10 << 13) + w12 + w5 | 0;
  3300. d = w12 + d + (a >>> 6 ^ a >>> 11 ^ a >>> 25 ^ a << 26 ^ a << 21 ^ a << 7) + (c ^ a & (b ^ c)) + 0xc6e00bf3 | 0;
  3301. h = h + d | 0;
  3302. d = d + (e & f ^ g & (e ^ f)) + (e >>> 2 ^ e >>> 13 ^ e >>> 22 ^ e << 30 ^ e << 19 ^ e << 10) | 0;
  3303. // 29
  3304. w13 = (w14 >>> 7 ^ w14 >>> 18 ^ w14 >>> 3 ^ w14 << 25 ^ w14 << 14) + (w11 >>> 17 ^ w11 >>> 19 ^ w11 >>> 10 ^ w11 << 15 ^ w11 << 13) + w13 + w6 | 0;
  3305. c = w13 + c + (h >>> 6 ^ h >>> 11 ^ h >>> 25 ^ h << 26 ^ h << 21 ^ h << 7) + (b ^ h & (a ^ b)) + 0xd5a79147 | 0;
  3306. g = g + c | 0;
  3307. c = c + (d & e ^ f & (d ^ e)) + (d >>> 2 ^ d >>> 13 ^ d >>> 22 ^ d << 30 ^ d << 19 ^ d << 10) | 0;
  3308. // 30
  3309. w14 = (w15 >>> 7 ^ w15 >>> 18 ^ w15 >>> 3 ^ w15 << 25 ^ w15 << 14) + (w12 >>> 17 ^ w12 >>> 19 ^ w12 >>> 10 ^ w12 << 15 ^ w12 << 13) + w14 + w7 | 0;
  3310. b = w14 + b + (g >>> 6 ^ g >>> 11 ^ g >>> 25 ^ g << 26 ^ g << 21 ^ g << 7) + (a ^ g & (h ^ a)) + 0x06ca6351 | 0;
  3311. f = f + b | 0;
  3312. b = b + (c & d ^ e & (c ^ d)) + (c >>> 2 ^ c >>> 13 ^ c >>> 22 ^ c << 30 ^ c << 19 ^ c << 10) | 0;
  3313. // 31
  3314. w15 = (w0 >>> 7 ^ w0 >>> 18 ^ w0 >>> 3 ^ w0 << 25 ^ w0 << 14) + (w13 >>> 17 ^ w13 >>> 19 ^ w13 >>> 10 ^ w13 << 15 ^ w13 << 13) + w15 + w8 | 0;
  3315. a = w15 + a + (f >>> 6 ^ f >>> 11 ^ f >>> 25 ^ f << 26 ^ f << 21 ^ f << 7) + (h ^ f & (g ^ h)) + 0x14292967 | 0;
  3316. e = e + a | 0;
  3317. a = a + (b & c ^ d & (b ^ c)) + (b >>> 2 ^ b >>> 13 ^ b >>> 22 ^ b << 30 ^ b << 19 ^ b << 10) | 0;
  3318. // 32
  3319. w0 = (w1 >>> 7 ^ w1 >>> 18 ^ w1 >>> 3 ^ w1 << 25 ^ w1 << 14) + (w14 >>> 17 ^ w14 >>> 19 ^ w14 >>> 10 ^ w14 << 15 ^ w14 << 13) + w0 + w9 | 0;
  3320. h = w0 + h + (e >>> 6 ^ e >>> 11 ^ e >>> 25 ^ e << 26 ^ e << 21 ^ e << 7) + (g ^ e & (f ^ g)) + 0x27b70a85 | 0;
  3321. d = d + h | 0;
  3322. h = h + (a & b ^ c & (a ^ b)) + (a >>> 2 ^ a >>> 13 ^ a >>> 22 ^ a << 30 ^ a << 19 ^ a << 10) | 0;
  3323. // 33
  3324. w1 = (w2 >>> 7 ^ w2 >>> 18 ^ w2 >>> 3 ^ w2 << 25 ^ w2 << 14) + (w15 >>> 17 ^ w15 >>> 19 ^ w15 >>> 10 ^ w15 << 15 ^ w15 << 13) + w1 + w10 | 0;
  3325. g = w1 + g + (d >>> 6 ^ d >>> 11 ^ d >>> 25 ^ d << 26 ^ d << 21 ^ d << 7) + (f ^ d & (e ^ f)) + 0x2e1b2138 | 0;
  3326. c = c + g | 0;
  3327. g = g + (h & a ^ b & (h ^ a)) + (h >>> 2 ^ h >>> 13 ^ h >>> 22 ^ h << 30 ^ h << 19 ^ h << 10) | 0;
  3328. // 34
  3329. w2 = (w3 >>> 7 ^ w3 >>> 18 ^ w3 >>> 3 ^ w3 << 25 ^ w3 << 14) + (w0 >>> 17 ^ w0 >>> 19 ^ w0 >>> 10 ^ w0 << 15 ^ w0 << 13) + w2 + w11 | 0;
  3330. f = w2 + f + (c >>> 6 ^ c >>> 11 ^ c >>> 25 ^ c << 26 ^ c << 21 ^ c << 7) + (e ^ c & (d ^ e)) + 0x4d2c6dfc | 0;
  3331. b = b + f | 0;
  3332. f = f + (g & h ^ a & (g ^ h)) + (g >>> 2 ^ g >>> 13 ^ g >>> 22 ^ g << 30 ^ g << 19 ^ g << 10) | 0;
  3333. // 35
  3334. w3 = (w4 >>> 7 ^ w4 >>> 18 ^ w4 >>> 3 ^ w4 << 25 ^ w4 << 14) + (w1 >>> 17 ^ w1 >>> 19 ^ w1 >>> 10 ^ w1 << 15 ^ w1 << 13) + w3 + w12 | 0;
  3335. e = w3 + e + (b >>> 6 ^ b >>> 11 ^ b >>> 25 ^ b << 26 ^ b << 21 ^ b << 7) + (d ^ b & (c ^ d)) + 0x53380d13 | 0;
  3336. a = a + e | 0;
  3337. e = e + (f & g ^ h & (f ^ g)) + (f >>> 2 ^ f >>> 13 ^ f >>> 22 ^ f << 30 ^ f << 19 ^ f << 10) | 0;
  3338. // 36
  3339. w4 = (w5 >>> 7 ^ w5 >>> 18 ^ w5 >>> 3 ^ w5 << 25 ^ w5 << 14) + (w2 >>> 17 ^ w2 >>> 19 ^ w2 >>> 10 ^ w2 << 15 ^ w2 << 13) + w4 + w13 | 0;
  3340. d = w4 + d + (a >>> 6 ^ a >>> 11 ^ a >>> 25 ^ a << 26 ^ a << 21 ^ a << 7) + (c ^ a & (b ^ c)) + 0x650a7354 | 0;
  3341. h = h + d | 0;
  3342. d = d + (e & f ^ g & (e ^ f)) + (e >>> 2 ^ e >>> 13 ^ e >>> 22 ^ e << 30 ^ e << 19 ^ e << 10) | 0;
  3343. // 37
  3344. w5 = (w6 >>> 7 ^ w6 >>> 18 ^ w6 >>> 3 ^ w6 << 25 ^ w6 << 14) + (w3 >>> 17 ^ w3 >>> 19 ^ w3 >>> 10 ^ w3 << 15 ^ w3 << 13) + w5 + w14 | 0;
  3345. c = w5 + c + (h >>> 6 ^ h >>> 11 ^ h >>> 25 ^ h << 26 ^ h << 21 ^ h << 7) + (b ^ h & (a ^ b)) + 0x766a0abb | 0;
  3346. g = g + c | 0;
  3347. c = c + (d & e ^ f & (d ^ e)) + (d >>> 2 ^ d >>> 13 ^ d >>> 22 ^ d << 30 ^ d << 19 ^ d << 10) | 0;
  3348. // 38
  3349. w6 = (w7 >>> 7 ^ w7 >>> 18 ^ w7 >>> 3 ^ w7 << 25 ^ w7 << 14) + (w4 >>> 17 ^ w4 >>> 19 ^ w4 >>> 10 ^ w4 << 15 ^ w4 << 13) + w6 + w15 | 0;
  3350. b = w6 + b + (g >>> 6 ^ g >>> 11 ^ g >>> 25 ^ g << 26 ^ g << 21 ^ g << 7) + (a ^ g & (h ^ a)) + 0x81c2c92e | 0;
  3351. f = f + b | 0;
  3352. b = b + (c & d ^ e & (c ^ d)) + (c >>> 2 ^ c >>> 13 ^ c >>> 22 ^ c << 30 ^ c << 19 ^ c << 10) | 0;
  3353. // 39
  3354. w7 = (w8 >>> 7 ^ w8 >>> 18 ^ w8 >>> 3 ^ w8 << 25 ^ w8 << 14) + (w5 >>> 17 ^ w5 >>> 19 ^ w5 >>> 10 ^ w5 << 15 ^ w5 << 13) + w7 + w0 | 0;
  3355. a = w7 + a + (f >>> 6 ^ f >>> 11 ^ f >>> 25 ^ f << 26 ^ f << 21 ^ f << 7) + (h ^ f & (g ^ h)) + 0x92722c85 | 0;
  3356. e = e + a | 0;
  3357. a = a + (b & c ^ d & (b ^ c)) + (b >>> 2 ^ b >>> 13 ^ b >>> 22 ^ b << 30 ^ b << 19 ^ b << 10) | 0;
  3358. // 40
  3359. w8 = (w9 >>> 7 ^ w9 >>> 18 ^ w9 >>> 3 ^ w9 << 25 ^ w9 << 14) + (w6 >>> 17 ^ w6 >>> 19 ^ w6 >>> 10 ^ w6 << 15 ^ w6 << 13) + w8 + w1 | 0;
  3360. h = w8 + h + (e >>> 6 ^ e >>> 11 ^ e >>> 25 ^ e << 26 ^ e << 21 ^ e << 7) + (g ^ e & (f ^ g)) + 0xa2bfe8a1 | 0;
  3361. d = d + h | 0;
  3362. h = h + (a & b ^ c & (a ^ b)) + (a >>> 2 ^ a >>> 13 ^ a >>> 22 ^ a << 30 ^ a << 19 ^ a << 10) | 0;
  3363. // 41
  3364. w9 = (w10 >>> 7 ^ w10 >>> 18 ^ w10 >>> 3 ^ w10 << 25 ^ w10 << 14) + (w7 >>> 17 ^ w7 >>> 19 ^ w7 >>> 10 ^ w7 << 15 ^ w7 << 13) + w9 + w2 | 0;
  3365. g = w9 + g + (d >>> 6 ^ d >>> 11 ^ d >>> 25 ^ d << 26 ^ d << 21 ^ d << 7) + (f ^ d & (e ^ f)) + 0xa81a664b | 0;
  3366. c = c + g | 0;
  3367. g = g + (h & a ^ b & (h ^ a)) + (h >>> 2 ^ h >>> 13 ^ h >>> 22 ^ h << 30 ^ h << 19 ^ h << 10) | 0;
  3368. // 42
  3369. w10 = (w11 >>> 7 ^ w11 >>> 18 ^ w11 >>> 3 ^ w11 << 25 ^ w11 << 14) + (w8 >>> 17 ^ w8 >>> 19 ^ w8 >>> 10 ^ w8 << 15 ^ w8 << 13) + w10 + w3 | 0;
  3370. f = w10 + f + (c >>> 6 ^ c >>> 11 ^ c >>> 25 ^ c << 26 ^ c << 21 ^ c << 7) + (e ^ c & (d ^ e)) + 0xc24b8b70 | 0;
  3371. b = b + f | 0;
  3372. f = f + (g & h ^ a & (g ^ h)) + (g >>> 2 ^ g >>> 13 ^ g >>> 22 ^ g << 30 ^ g << 19 ^ g << 10) | 0;
  3373. // 43
  3374. w11 = (w12 >>> 7 ^ w12 >>> 18 ^ w12 >>> 3 ^ w12 << 25 ^ w12 << 14) + (w9 >>> 17 ^ w9 >>> 19 ^ w9 >>> 10 ^ w9 << 15 ^ w9 << 13) + w11 + w4 | 0;
  3375. e = w11 + e + (b >>> 6 ^ b >>> 11 ^ b >>> 25 ^ b << 26 ^ b << 21 ^ b << 7) + (d ^ b & (c ^ d)) + 0xc76c51a3 | 0;
  3376. a = a + e | 0;
  3377. e = e + (f & g ^ h & (f ^ g)) + (f >>> 2 ^ f >>> 13 ^ f >>> 22 ^ f << 30 ^ f << 19 ^ f << 10) | 0;
  3378. // 44
  3379. w12 = (w13 >>> 7 ^ w13 >>> 18 ^ w13 >>> 3 ^ w13 << 25 ^ w13 << 14) + (w10 >>> 17 ^ w10 >>> 19 ^ w10 >>> 10 ^ w10 << 15 ^ w10 << 13) + w12 + w5 | 0;
  3380. d = w12 + d + (a >>> 6 ^ a >>> 11 ^ a >>> 25 ^ a << 26 ^ a << 21 ^ a << 7) + (c ^ a & (b ^ c)) + 0xd192e819 | 0;
  3381. h = h + d | 0;
  3382. d = d + (e & f ^ g & (e ^ f)) + (e >>> 2 ^ e >>> 13 ^ e >>> 22 ^ e << 30 ^ e << 19 ^ e << 10) | 0;
  3383. // 45
  3384. w13 = (w14 >>> 7 ^ w14 >>> 18 ^ w14 >>> 3 ^ w14 << 25 ^ w14 << 14) + (w11 >>> 17 ^ w11 >>> 19 ^ w11 >>> 10 ^ w11 << 15 ^ w11 << 13) + w13 + w6 | 0;
  3385. c = w13 + c + (h >>> 6 ^ h >>> 11 ^ h >>> 25 ^ h << 26 ^ h << 21 ^ h << 7) + (b ^ h & (a ^ b)) + 0xd6990624 | 0;
  3386. g = g + c | 0;
  3387. c = c + (d & e ^ f & (d ^ e)) + (d >>> 2 ^ d >>> 13 ^ d >>> 22 ^ d << 30 ^ d << 19 ^ d << 10) | 0;
  3388. // 46
  3389. w14 = (w15 >>> 7 ^ w15 >>> 18 ^ w15 >>> 3 ^ w15 << 25 ^ w15 << 14) + (w12 >>> 17 ^ w12 >>> 19 ^ w12 >>> 10 ^ w12 << 15 ^ w12 << 13) + w14 + w7 | 0;
  3390. b = w14 + b + (g >>> 6 ^ g >>> 11 ^ g >>> 25 ^ g << 26 ^ g << 21 ^ g << 7) + (a ^ g & (h ^ a)) + 0xf40e3585 | 0;
  3391. f = f + b | 0;
  3392. b = b + (c & d ^ e & (c ^ d)) + (c >>> 2 ^ c >>> 13 ^ c >>> 22 ^ c << 30 ^ c << 19 ^ c << 10) | 0;
  3393. // 47
  3394. w15 = (w0 >>> 7 ^ w0 >>> 18 ^ w0 >>> 3 ^ w0 << 25 ^ w0 << 14) + (w13 >>> 17 ^ w13 >>> 19 ^ w13 >>> 10 ^ w13 << 15 ^ w13 << 13) + w15 + w8 | 0;
  3395. a = w15 + a + (f >>> 6 ^ f >>> 11 ^ f >>> 25 ^ f << 26 ^ f << 21 ^ f << 7) + (h ^ f & (g ^ h)) + 0x106aa070 | 0;
  3396. e = e + a | 0;
  3397. a = a + (b & c ^ d & (b ^ c)) + (b >>> 2 ^ b >>> 13 ^ b >>> 22 ^ b << 30 ^ b << 19 ^ b << 10) | 0;
  3398. // 48
  3399. w0 = (w1 >>> 7 ^ w1 >>> 18 ^ w1 >>> 3 ^ w1 << 25 ^ w1 << 14) + (w14 >>> 17 ^ w14 >>> 19 ^ w14 >>> 10 ^ w14 << 15 ^ w14 << 13) + w0 + w9 | 0;
  3400. h = w0 + h + (e >>> 6 ^ e >>> 11 ^ e >>> 25 ^ e << 26 ^ e << 21 ^ e << 7) + (g ^ e & (f ^ g)) + 0x19a4c116 | 0;
  3401. d = d + h | 0;
  3402. h = h + (a & b ^ c & (a ^ b)) + (a >>> 2 ^ a >>> 13 ^ a >>> 22 ^ a << 30 ^ a << 19 ^ a << 10) | 0;
  3403. // 49
  3404. w1 = (w2 >>> 7 ^ w2 >>> 18 ^ w2 >>> 3 ^ w2 << 25 ^ w2 << 14) + (w15 >>> 17 ^ w15 >>> 19 ^ w15 >>> 10 ^ w15 << 15 ^ w15 << 13) + w1 + w10 | 0;
  3405. g = w1 + g + (d >>> 6 ^ d >>> 11 ^ d >>> 25 ^ d << 26 ^ d << 21 ^ d << 7) + (f ^ d & (e ^ f)) + 0x1e376c08 | 0;
  3406. c = c + g | 0;
  3407. g = g + (h & a ^ b & (h ^ a)) + (h >>> 2 ^ h >>> 13 ^ h >>> 22 ^ h << 30 ^ h << 19 ^ h << 10) | 0;
  3408. // 50
  3409. w2 = (w3 >>> 7 ^ w3 >>> 18 ^ w3 >>> 3 ^ w3 << 25 ^ w3 << 14) + (w0 >>> 17 ^ w0 >>> 19 ^ w0 >>> 10 ^ w0 << 15 ^ w0 << 13) + w2 + w11 | 0;
  3410. f = w2 + f + (c >>> 6 ^ c >>> 11 ^ c >>> 25 ^ c << 26 ^ c << 21 ^ c << 7) + (e ^ c & (d ^ e)) + 0x2748774c | 0;
  3411. b = b + f | 0;
  3412. f = f + (g & h ^ a & (g ^ h)) + (g >>> 2 ^ g >>> 13 ^ g >>> 22 ^ g << 30 ^ g << 19 ^ g << 10) | 0;
  3413. // 51
  3414. w3 = (w4 >>> 7 ^ w4 >>> 18 ^ w4 >>> 3 ^ w4 << 25 ^ w4 << 14) + (w1 >>> 17 ^ w1 >>> 19 ^ w1 >>> 10 ^ w1 << 15 ^ w1 << 13) + w3 + w12 | 0;
  3415. e = w3 + e + (b >>> 6 ^ b >>> 11 ^ b >>> 25 ^ b << 26 ^ b << 21 ^ b << 7) + (d ^ b & (c ^ d)) + 0x34b0bcb5 | 0;
  3416. a = a + e | 0;
  3417. e = e + (f & g ^ h & (f ^ g)) + (f >>> 2 ^ f >>> 13 ^ f >>> 22 ^ f << 30 ^ f << 19 ^ f << 10) | 0;
  3418. // 52
  3419. w4 = (w5 >>> 7 ^ w5 >>> 18 ^ w5 >>> 3 ^ w5 << 25 ^ w5 << 14) + (w2 >>> 17 ^ w2 >>> 19 ^ w2 >>> 10 ^ w2 << 15 ^ w2 << 13) + w4 + w13 | 0;
  3420. d = w4 + d + (a >>> 6 ^ a >>> 11 ^ a >>> 25 ^ a << 26 ^ a << 21 ^ a << 7) + (c ^ a & (b ^ c)) + 0x391c0cb3 | 0;
  3421. h = h + d | 0;
  3422. d = d + (e & f ^ g & (e ^ f)) + (e >>> 2 ^ e >>> 13 ^ e >>> 22 ^ e << 30 ^ e << 19 ^ e << 10) | 0;
  3423. // 53
  3424. w5 = (w6 >>> 7 ^ w6 >>> 18 ^ w6 >>> 3 ^ w6 << 25 ^ w6 << 14) + (w3 >>> 17 ^ w3 >>> 19 ^ w3 >>> 10 ^ w3 << 15 ^ w3 << 13) + w5 + w14 | 0;
  3425. c = w5 + c + (h >>> 6 ^ h >>> 11 ^ h >>> 25 ^ h << 26 ^ h << 21 ^ h << 7) + (b ^ h & (a ^ b)) + 0x4ed8aa4a | 0;
  3426. g = g + c | 0;
  3427. c = c + (d & e ^ f & (d ^ e)) + (d >>> 2 ^ d >>> 13 ^ d >>> 22 ^ d << 30 ^ d << 19 ^ d << 10) | 0;
  3428. // 54
  3429. w6 = (w7 >>> 7 ^ w7 >>> 18 ^ w7 >>> 3 ^ w7 << 25 ^ w7 << 14) + (w4 >>> 17 ^ w4 >>> 19 ^ w4 >>> 10 ^ w4 << 15 ^ w4 << 13) + w6 + w15 | 0;
  3430. b = w6 + b + (g >>> 6 ^ g >>> 11 ^ g >>> 25 ^ g << 26 ^ g << 21 ^ g << 7) + (a ^ g & (h ^ a)) + 0x5b9cca4f | 0;
  3431. f = f + b | 0;
  3432. b = b + (c & d ^ e & (c ^ d)) + (c >>> 2 ^ c >>> 13 ^ c >>> 22 ^ c << 30 ^ c << 19 ^ c << 10) | 0;
  3433. // 55
  3434. w7 = (w8 >>> 7 ^ w8 >>> 18 ^ w8 >>> 3 ^ w8 << 25 ^ w8 << 14) + (w5 >>> 17 ^ w5 >>> 19 ^ w5 >>> 10 ^ w5 << 15 ^ w5 << 13) + w7 + w0 | 0;
  3435. a = w7 + a + (f >>> 6 ^ f >>> 11 ^ f >>> 25 ^ f << 26 ^ f << 21 ^ f << 7) + (h ^ f & (g ^ h)) + 0x682e6ff3 | 0;
  3436. e = e + a | 0;
  3437. a = a + (b & c ^ d & (b ^ c)) + (b >>> 2 ^ b >>> 13 ^ b >>> 22 ^ b << 30 ^ b << 19 ^ b << 10) | 0;
  3438. // 56
  3439. w8 = (w9 >>> 7 ^ w9 >>> 18 ^ w9 >>> 3 ^ w9 << 25 ^ w9 << 14) + (w6 >>> 17 ^ w6 >>> 19 ^ w6 >>> 10 ^ w6 << 15 ^ w6 << 13) + w8 + w1 | 0;
  3440. h = w8 + h + (e >>> 6 ^ e >>> 11 ^ e >>> 25 ^ e << 26 ^ e << 21 ^ e << 7) + (g ^ e & (f ^ g)) + 0x748f82ee | 0;
  3441. d = d + h | 0;
  3442. h = h + (a & b ^ c & (a ^ b)) + (a >>> 2 ^ a >>> 13 ^ a >>> 22 ^ a << 30 ^ a << 19 ^ a << 10) | 0;
  3443. // 57
  3444. w9 = (w10 >>> 7 ^ w10 >>> 18 ^ w10 >>> 3 ^ w10 << 25 ^ w10 << 14) + (w7 >>> 17 ^ w7 >>> 19 ^ w7 >>> 10 ^ w7 << 15 ^ w7 << 13) + w9 + w2 | 0;
  3445. g = w9 + g + (d >>> 6 ^ d >>> 11 ^ d >>> 25 ^ d << 26 ^ d << 21 ^ d << 7) + (f ^ d & (e ^ f)) + 0x78a5636f | 0;
  3446. c = c + g | 0;
  3447. g = g + (h & a ^ b & (h ^ a)) + (h >>> 2 ^ h >>> 13 ^ h >>> 22 ^ h << 30 ^ h << 19 ^ h << 10) | 0;
  3448. // 58
  3449. w10 = (w11 >>> 7 ^ w11 >>> 18 ^ w11 >>> 3 ^ w11 << 25 ^ w11 << 14) + (w8 >>> 17 ^ w8 >>> 19 ^ w8 >>> 10 ^ w8 << 15 ^ w8 << 13) + w10 + w3 | 0;
  3450. f = w10 + f + (c >>> 6 ^ c >>> 11 ^ c >>> 25 ^ c << 26 ^ c << 21 ^ c << 7) + (e ^ c & (d ^ e)) + 0x84c87814 | 0;
  3451. b = b + f | 0;
  3452. f = f + (g & h ^ a & (g ^ h)) + (g >>> 2 ^ g >>> 13 ^ g >>> 22 ^ g << 30 ^ g << 19 ^ g << 10) | 0;
  3453. // 59
  3454. w11 = (w12 >>> 7 ^ w12 >>> 18 ^ w12 >>> 3 ^ w12 << 25 ^ w12 << 14) + (w9 >>> 17 ^ w9 >>> 19 ^ w9 >>> 10 ^ w9 << 15 ^ w9 << 13) + w11 + w4 | 0;
  3455. e = w11 + e + (b >>> 6 ^ b >>> 11 ^ b >>> 25 ^ b << 26 ^ b << 21 ^ b << 7) + (d ^ b & (c ^ d)) + 0x8cc70208 | 0;
  3456. a = a + e | 0;
  3457. e = e + (f & g ^ h & (f ^ g)) + (f >>> 2 ^ f >>> 13 ^ f >>> 22 ^ f << 30 ^ f << 19 ^ f << 10) | 0;
  3458. // 60
  3459. w12 = (w13 >>> 7 ^ w13 >>> 18 ^ w13 >>> 3 ^ w13 << 25 ^ w13 << 14) + (w10 >>> 17 ^ w10 >>> 19 ^ w10 >>> 10 ^ w10 << 15 ^ w10 << 13) + w12 + w5 | 0;
  3460. d = w12 + d + (a >>> 6 ^ a >>> 11 ^ a >>> 25 ^ a << 26 ^ a << 21 ^ a << 7) + (c ^ a & (b ^ c)) + 0x90befffa | 0;
  3461. h = h + d | 0;
  3462. d = d + (e & f ^ g & (e ^ f)) + (e >>> 2 ^ e >>> 13 ^ e >>> 22 ^ e << 30 ^ e << 19 ^ e << 10) | 0;
  3463. // 61
  3464. w13 = (w14 >>> 7 ^ w14 >>> 18 ^ w14 >>> 3 ^ w14 << 25 ^ w14 << 14) + (w11 >>> 17 ^ w11 >>> 19 ^ w11 >>> 10 ^ w11 << 15 ^ w11 << 13) + w13 + w6 | 0;
  3465. c = w13 + c + (h >>> 6 ^ h >>> 11 ^ h >>> 25 ^ h << 26 ^ h << 21 ^ h << 7) + (b ^ h & (a ^ b)) + 0xa4506ceb | 0;
  3466. g = g + c | 0;
  3467. c = c + (d & e ^ f & (d ^ e)) + (d >>> 2 ^ d >>> 13 ^ d >>> 22 ^ d << 30 ^ d << 19 ^ d << 10) | 0;
  3468. // 62
  3469. w14 = (w15 >>> 7 ^ w15 >>> 18 ^ w15 >>> 3 ^ w15 << 25 ^ w15 << 14) + (w12 >>> 17 ^ w12 >>> 19 ^ w12 >>> 10 ^ w12 << 15 ^ w12 << 13) + w14 + w7 | 0;
  3470. b = w14 + b + (g >>> 6 ^ g >>> 11 ^ g >>> 25 ^ g << 26 ^ g << 21 ^ g << 7) + (a ^ g & (h ^ a)) + 0xbef9a3f7 | 0;
  3471. f = f + b | 0;
  3472. b = b + (c & d ^ e & (c ^ d)) + (c >>> 2 ^ c >>> 13 ^ c >>> 22 ^ c << 30 ^ c << 19 ^ c << 10) | 0;
  3473. // 63
  3474. w15 = (w0 >>> 7 ^ w0 >>> 18 ^ w0 >>> 3 ^ w0 << 25 ^ w0 << 14) + (w13 >>> 17 ^ w13 >>> 19 ^ w13 >>> 10 ^ w13 << 15 ^ w13 << 13) + w15 + w8 | 0;
  3475. a = w15 + a + (f >>> 6 ^ f >>> 11 ^ f >>> 25 ^ f << 26 ^ f << 21 ^ f << 7) + (h ^ f & (g ^ h)) + 0xc67178f2 | 0;
  3476. e = e + a | 0;
  3477. a = a + (b & c ^ d & (b ^ c)) + (b >>> 2 ^ b >>> 13 ^ b >>> 22 ^ b << 30 ^ b << 19 ^ b << 10) | 0;
  3478. H0 = H0 + a | 0;
  3479. H1 = H1 + b | 0;
  3480. H2 = H2 + c | 0;
  3481. H3 = H3 + d | 0;
  3482. H4 = H4 + e | 0;
  3483. H5 = H5 + f | 0;
  3484. H6 = H6 + g | 0;
  3485. H7 = H7 + h | 0;
  3486. }
  3487. function _core_heap(offset) {
  3488. offset = offset | 0;
  3489. _core(HEAP[offset | 0] << 24 | HEAP[offset | 1] << 16 | HEAP[offset | 2] << 8 | HEAP[offset | 3], HEAP[offset | 4] << 24 | HEAP[offset | 5] << 16 | HEAP[offset | 6] << 8 | HEAP[offset | 7], HEAP[offset | 8] << 24 | HEAP[offset | 9] << 16 | HEAP[offset | 10] << 8 | HEAP[offset | 11], HEAP[offset | 12] << 24 | HEAP[offset | 13] << 16 | HEAP[offset | 14] << 8 | HEAP[offset | 15], HEAP[offset | 16] << 24 | HEAP[offset | 17] << 16 | HEAP[offset | 18] << 8 | HEAP[offset | 19], HEAP[offset | 20] << 24 | HEAP[offset | 21] << 16 | HEAP[offset | 22] << 8 | HEAP[offset | 23], HEAP[offset | 24] << 24 | HEAP[offset | 25] << 16 | HEAP[offset | 26] << 8 | HEAP[offset | 27], HEAP[offset | 28] << 24 | HEAP[offset | 29] << 16 | HEAP[offset | 30] << 8 | HEAP[offset | 31], HEAP[offset | 32] << 24 | HEAP[offset | 33] << 16 | HEAP[offset | 34] << 8 | HEAP[offset | 35], HEAP[offset | 36] << 24 | HEAP[offset | 37] << 16 | HEAP[offset | 38] << 8 | HEAP[offset | 39], HEAP[offset | 40] << 24 | HEAP[offset | 41] << 16 | HEAP[offset | 42] << 8 | HEAP[offset | 43], HEAP[offset | 44] << 24 | HEAP[offset | 45] << 16 | HEAP[offset | 46] << 8 | HEAP[offset | 47], HEAP[offset | 48] << 24 | HEAP[offset | 49] << 16 | HEAP[offset | 50] << 8 | HEAP[offset | 51], HEAP[offset | 52] << 24 | HEAP[offset | 53] << 16 | HEAP[offset | 54] << 8 | HEAP[offset | 55], HEAP[offset | 56] << 24 | HEAP[offset | 57] << 16 | HEAP[offset | 58] << 8 | HEAP[offset | 59], HEAP[offset | 60] << 24 | HEAP[offset | 61] << 16 | HEAP[offset | 62] << 8 | HEAP[offset | 63]);
  3490. }
  3491. // offset — multiple of 32
  3492. function _state_to_heap(output) {
  3493. output = output | 0;
  3494. HEAP[output | 0] = H0 >>> 24;
  3495. HEAP[output | 1] = H0 >>> 16 & 255;
  3496. HEAP[output | 2] = H0 >>> 8 & 255;
  3497. HEAP[output | 3] = H0 & 255;
  3498. HEAP[output | 4] = H1 >>> 24;
  3499. HEAP[output | 5] = H1 >>> 16 & 255;
  3500. HEAP[output | 6] = H1 >>> 8 & 255;
  3501. HEAP[output | 7] = H1 & 255;
  3502. HEAP[output | 8] = H2 >>> 24;
  3503. HEAP[output | 9] = H2 >>> 16 & 255;
  3504. HEAP[output | 10] = H2 >>> 8 & 255;
  3505. HEAP[output | 11] = H2 & 255;
  3506. HEAP[output | 12] = H3 >>> 24;
  3507. HEAP[output | 13] = H3 >>> 16 & 255;
  3508. HEAP[output | 14] = H3 >>> 8 & 255;
  3509. HEAP[output | 15] = H3 & 255;
  3510. HEAP[output | 16] = H4 >>> 24;
  3511. HEAP[output | 17] = H4 >>> 16 & 255;
  3512. HEAP[output | 18] = H4 >>> 8 & 255;
  3513. HEAP[output | 19] = H4 & 255;
  3514. HEAP[output | 20] = H5 >>> 24;
  3515. HEAP[output | 21] = H5 >>> 16 & 255;
  3516. HEAP[output | 22] = H5 >>> 8 & 255;
  3517. HEAP[output | 23] = H5 & 255;
  3518. HEAP[output | 24] = H6 >>> 24;
  3519. HEAP[output | 25] = H6 >>> 16 & 255;
  3520. HEAP[output | 26] = H6 >>> 8 & 255;
  3521. HEAP[output | 27] = H6 & 255;
  3522. HEAP[output | 28] = H7 >>> 24;
  3523. HEAP[output | 29] = H7 >>> 16 & 255;
  3524. HEAP[output | 30] = H7 >>> 8 & 255;
  3525. HEAP[output | 31] = H7 & 255;
  3526. }
  3527. function reset() {
  3528. H0 = 0x6a09e667;
  3529. H1 = 0xbb67ae85;
  3530. H2 = 0x3c6ef372;
  3531. H3 = 0xa54ff53a;
  3532. H4 = 0x510e527f;
  3533. H5 = 0x9b05688c;
  3534. H6 = 0x1f83d9ab;
  3535. H7 = 0x5be0cd19;
  3536. TOTAL0 = TOTAL1 = 0;
  3537. }
  3538. function init(h0, h1, h2, h3, h4, h5, h6, h7, total0, total1) {
  3539. h0 = h0 | 0;
  3540. h1 = h1 | 0;
  3541. h2 = h2 | 0;
  3542. h3 = h3 | 0;
  3543. h4 = h4 | 0;
  3544. h5 = h5 | 0;
  3545. h6 = h6 | 0;
  3546. h7 = h7 | 0;
  3547. total0 = total0 | 0;
  3548. total1 = total1 | 0;
  3549. H0 = h0;
  3550. H1 = h1;
  3551. H2 = h2;
  3552. H3 = h3;
  3553. H4 = h4;
  3554. H5 = h5;
  3555. H6 = h6;
  3556. H7 = h7;
  3557. TOTAL0 = total0;
  3558. TOTAL1 = total1;
  3559. }
  3560. // offset — multiple of 64
  3561. function process(offset, length) {
  3562. offset = offset | 0;
  3563. length = length | 0;
  3564. var hashed = 0;
  3565. if (offset & 63) return -1;
  3566. while ((length | 0) >= 64) {
  3567. _core_heap(offset);
  3568. offset = offset + 64 | 0;
  3569. length = length - 64 | 0;
  3570. hashed = hashed + 64 | 0;
  3571. }
  3572. TOTAL0 = TOTAL0 + hashed | 0;
  3573. if (TOTAL0 >>> 0 < hashed >>> 0) TOTAL1 = TOTAL1 + 1 | 0;
  3574. return hashed | 0;
  3575. }
  3576. // offset — multiple of 64
  3577. // output — multiple of 32
  3578. function finish(offset, length, output) {
  3579. offset = offset | 0;
  3580. length = length | 0;
  3581. output = output | 0;
  3582. var hashed = 0,
  3583. i = 0;
  3584. if (offset & 63) return -1;
  3585. if (~output) if (output & 31) return -1;
  3586. if ((length | 0) >= 64) {
  3587. hashed = process(offset, length) | 0;
  3588. if ((hashed | 0) == -1) return -1;
  3589. offset = offset + hashed | 0;
  3590. length = length - hashed | 0;
  3591. }
  3592. hashed = hashed + length | 0;
  3593. TOTAL0 = TOTAL0 + length | 0;
  3594. if (TOTAL0 >>> 0 < length >>> 0) TOTAL1 = TOTAL1 + 1 | 0;
  3595. HEAP[offset | length] = 0x80;
  3596. if ((length | 0) >= 56) {
  3597. for (i = length + 1 | 0; (i | 0) < 64; i = i + 1 | 0) HEAP[offset | i] = 0x00;
  3598. _core_heap(offset);
  3599. length = 0;
  3600. HEAP[offset | 0] = 0;
  3601. }
  3602. for (i = length + 1 | 0; (i | 0) < 59; i = i + 1 | 0) HEAP[offset | i] = 0;
  3603. HEAP[offset | 56] = TOTAL1 >>> 21 & 255;
  3604. HEAP[offset | 57] = TOTAL1 >>> 13 & 255;
  3605. HEAP[offset | 58] = TOTAL1 >>> 5 & 255;
  3606. HEAP[offset | 59] = TOTAL1 << 3 & 255 | TOTAL0 >>> 29;
  3607. HEAP[offset | 60] = TOTAL0 >>> 21 & 255;
  3608. HEAP[offset | 61] = TOTAL0 >>> 13 & 255;
  3609. HEAP[offset | 62] = TOTAL0 >>> 5 & 255;
  3610. HEAP[offset | 63] = TOTAL0 << 3 & 255;
  3611. _core_heap(offset);
  3612. if (~output) _state_to_heap(output);
  3613. return hashed | 0;
  3614. }
  3615. function hmac_reset() {
  3616. H0 = I0;
  3617. H1 = I1;
  3618. H2 = I2;
  3619. H3 = I3;
  3620. H4 = I4;
  3621. H5 = I5;
  3622. H6 = I6;
  3623. H7 = I7;
  3624. TOTAL0 = 64;
  3625. TOTAL1 = 0;
  3626. }
  3627. function _hmac_opad() {
  3628. H0 = O0;
  3629. H1 = O1;
  3630. H2 = O2;
  3631. H3 = O3;
  3632. H4 = O4;
  3633. H5 = O5;
  3634. H6 = O6;
  3635. H7 = O7;
  3636. TOTAL0 = 64;
  3637. TOTAL1 = 0;
  3638. }
  3639. function hmac_init(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15) {
  3640. p0 = p0 | 0;
  3641. p1 = p1 | 0;
  3642. p2 = p2 | 0;
  3643. p3 = p3 | 0;
  3644. p4 = p4 | 0;
  3645. p5 = p5 | 0;
  3646. p6 = p6 | 0;
  3647. p7 = p7 | 0;
  3648. p8 = p8 | 0;
  3649. p9 = p9 | 0;
  3650. p10 = p10 | 0;
  3651. p11 = p11 | 0;
  3652. p12 = p12 | 0;
  3653. p13 = p13 | 0;
  3654. p14 = p14 | 0;
  3655. p15 = p15 | 0;
  3656. // opad
  3657. reset();
  3658. _core(p0 ^ 0x5c5c5c5c, p1 ^ 0x5c5c5c5c, p2 ^ 0x5c5c5c5c, p3 ^ 0x5c5c5c5c, p4 ^ 0x5c5c5c5c, p5 ^ 0x5c5c5c5c, p6 ^ 0x5c5c5c5c, p7 ^ 0x5c5c5c5c, p8 ^ 0x5c5c5c5c, p9 ^ 0x5c5c5c5c, p10 ^ 0x5c5c5c5c, p11 ^ 0x5c5c5c5c, p12 ^ 0x5c5c5c5c, p13 ^ 0x5c5c5c5c, p14 ^ 0x5c5c5c5c, p15 ^ 0x5c5c5c5c);
  3659. O0 = H0;
  3660. O1 = H1;
  3661. O2 = H2;
  3662. O3 = H3;
  3663. O4 = H4;
  3664. O5 = H5;
  3665. O6 = H6;
  3666. O7 = H7;
  3667. // ipad
  3668. reset();
  3669. _core(p0 ^ 0x36363636, p1 ^ 0x36363636, p2 ^ 0x36363636, p3 ^ 0x36363636, p4 ^ 0x36363636, p5 ^ 0x36363636, p6 ^ 0x36363636, p7 ^ 0x36363636, p8 ^ 0x36363636, p9 ^ 0x36363636, p10 ^ 0x36363636, p11 ^ 0x36363636, p12 ^ 0x36363636, p13 ^ 0x36363636, p14 ^ 0x36363636, p15 ^ 0x36363636);
  3670. I0 = H0;
  3671. I1 = H1;
  3672. I2 = H2;
  3673. I3 = H3;
  3674. I4 = H4;
  3675. I5 = H5;
  3676. I6 = H6;
  3677. I7 = H7;
  3678. TOTAL0 = 64;
  3679. TOTAL1 = 0;
  3680. }
  3681. // offset — multiple of 64
  3682. // output — multiple of 32
  3683. function hmac_finish(offset, length, output) {
  3684. offset = offset | 0;
  3685. length = length | 0;
  3686. output = output | 0;
  3687. var t0 = 0,
  3688. t1 = 0,
  3689. t2 = 0,
  3690. t3 = 0,
  3691. t4 = 0,
  3692. t5 = 0,
  3693. t6 = 0,
  3694. t7 = 0,
  3695. hashed = 0;
  3696. if (offset & 63) return -1;
  3697. if (~output) if (output & 31) return -1;
  3698. hashed = finish(offset, length, -1) | 0;
  3699. t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;
  3700. _hmac_opad();
  3701. _core(t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768);
  3702. if (~output) _state_to_heap(output);
  3703. return hashed | 0;
  3704. }
  3705. // salt is assumed to be already processed
  3706. // offset — multiple of 64
  3707. // output — multiple of 32
  3708. function pbkdf2_generate_block(offset, length, block, count, output) {
  3709. offset = offset | 0;
  3710. length = length | 0;
  3711. block = block | 0;
  3712. count = count | 0;
  3713. output = output | 0;
  3714. var h0 = 0,
  3715. h1 = 0,
  3716. h2 = 0,
  3717. h3 = 0,
  3718. h4 = 0,
  3719. h5 = 0,
  3720. h6 = 0,
  3721. h7 = 0,
  3722. t0 = 0,
  3723. t1 = 0,
  3724. t2 = 0,
  3725. t3 = 0,
  3726. t4 = 0,
  3727. t5 = 0,
  3728. t6 = 0,
  3729. t7 = 0;
  3730. if (offset & 63) return -1;
  3731. if (~output) if (output & 31) return -1;
  3732. // pad block number into heap
  3733. // FIXME probable OOB write
  3734. HEAP[offset + length | 0] = block >>> 24;
  3735. HEAP[offset + length + 1 | 0] = block >>> 16 & 255;
  3736. HEAP[offset + length + 2 | 0] = block >>> 8 & 255;
  3737. HEAP[offset + length + 3 | 0] = block & 255;
  3738. // finish first iteration
  3739. hmac_finish(offset, length + 4 | 0, -1) | 0;
  3740. h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4, h5 = t5 = H5, h6 = t6 = H6, h7 = t7 = H7;
  3741. count = count - 1 | 0;
  3742. // perform the rest iterations
  3743. while ((count | 0) > 0) {
  3744. hmac_reset();
  3745. _core(t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768);
  3746. t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;
  3747. _hmac_opad();
  3748. _core(t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768);
  3749. t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;
  3750. h0 = h0 ^ H0;
  3751. h1 = h1 ^ H1;
  3752. h2 = h2 ^ H2;
  3753. h3 = h3 ^ H3;
  3754. h4 = h4 ^ H4;
  3755. h5 = h5 ^ H5;
  3756. h6 = h6 ^ H6;
  3757. h7 = h7 ^ H7;
  3758. count = count - 1 | 0;
  3759. }
  3760. H0 = h0;
  3761. H1 = h1;
  3762. H2 = h2;
  3763. H3 = h3;
  3764. H4 = h4;
  3765. H5 = h5;
  3766. H6 = h6;
  3767. H7 = h7;
  3768. if (~output) _state_to_heap(output);
  3769. return 0;
  3770. }
  3771. return {
  3772. // SHA256
  3773. reset: reset,
  3774. init: init,
  3775. process: process,
  3776. finish: finish,
  3777. // HMAC-SHA256
  3778. hmac_reset: hmac_reset,
  3779. hmac_init: hmac_init,
  3780. hmac_finish: hmac_finish,
  3781. // PBKDF2-HMAC-SHA256
  3782. pbkdf2_generate_block: pbkdf2_generate_block
  3783. };
  3784. }
  3785. },{}],13:[function(require,module,exports){
  3786. 'use strict';
  3787. Object.defineProperty(exports, "__esModule", {
  3788. value: true
  3789. });
  3790. exports.Sha256 = exports._sha256_hash_size = exports._sha256_block_size = undefined;
  3791. var _sha = require('./sha256.asm');
  3792. var _hash = require('../hash');
  3793. var __extends = undefined && undefined.__extends || function () {
  3794. var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) {
  3795. d.__proto__ = b;
  3796. } || function (d, b) {
  3797. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3798. };
  3799. return function (d, b) {
  3800. extendStatics(d, b);
  3801. function __() {
  3802. this.constructor = d;
  3803. }
  3804. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3805. };
  3806. }();
  3807. var _sha256_block_size = exports._sha256_block_size = 64;
  3808. var _sha256_hash_size = exports._sha256_hash_size = 32;
  3809. var Sha256 = /** @class */function (_super) {
  3810. __extends(Sha256, _super);
  3811. function Sha256() {
  3812. var _this = _super !== null && _super.apply(this, arguments) || this;
  3813. _this.NAME = 'sha256';
  3814. _this.BLOCK_SIZE = _sha256_block_size;
  3815. _this.HASH_SIZE = _sha256_hash_size;
  3816. return _this;
  3817. }
  3818. Sha256.bytes = function (data) {
  3819. return new Sha256().process(data).finish().result;
  3820. };
  3821. Sha256.NAME = 'sha256';
  3822. Sha256.heap_pool = [];
  3823. Sha256.asm_pool = [];
  3824. Sha256.asm_function = _sha.sha256_asm;
  3825. return Sha256;
  3826. }(_hash.Hash);
  3827. exports.Sha256 = Sha256;
  3828. },{"../hash":9,"./sha256.asm":12}],14:[function(require,module,exports){
  3829. 'use strict';
  3830. Object.defineProperty(exports, "__esModule", {
  3831. value: true
  3832. });
  3833. var __extends = undefined && undefined.__extends || function () {
  3834. var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) {
  3835. d.__proto__ = b;
  3836. } || function (d, b) {
  3837. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3838. };
  3839. return function (d, b) {
  3840. extendStatics(d, b);
  3841. function __() {
  3842. this.constructor = d;
  3843. }
  3844. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3845. };
  3846. }();
  3847. var IllegalStateError = /** @class */function (_super) {
  3848. __extends(IllegalStateError, _super);
  3849. function IllegalStateError() {
  3850. var args = [];
  3851. for (var _i = 0; _i < arguments.length; _i++) {
  3852. args[_i] = arguments[_i];
  3853. }
  3854. var _this = _super.apply(this, args) || this;
  3855. Object.create(Error.prototype, { name: { value: 'IllegalStateError' } });
  3856. return _this;
  3857. }
  3858. return IllegalStateError;
  3859. }(Error);
  3860. exports.IllegalStateError = IllegalStateError;
  3861. var IllegalArgumentError = /** @class */function (_super) {
  3862. __extends(IllegalArgumentError, _super);
  3863. function IllegalArgumentError() {
  3864. var args = [];
  3865. for (var _i = 0; _i < arguments.length; _i++) {
  3866. args[_i] = arguments[_i];
  3867. }
  3868. var _this = _super.apply(this, args) || this;
  3869. Object.create(Error.prototype, { name: { value: 'IllegalArgumentError' } });
  3870. return _this;
  3871. }
  3872. return IllegalArgumentError;
  3873. }(Error);
  3874. exports.IllegalArgumentError = IllegalArgumentError;
  3875. var SecurityError = /** @class */function (_super) {
  3876. __extends(SecurityError, _super);
  3877. function SecurityError() {
  3878. var args = [];
  3879. for (var _i = 0; _i < arguments.length; _i++) {
  3880. args[_i] = arguments[_i];
  3881. }
  3882. var _this = _super.apply(this, args) || this;
  3883. Object.create(Error.prototype, { name: { value: 'SecurityError' } });
  3884. return _this;
  3885. }
  3886. return SecurityError;
  3887. }(Error);
  3888. exports.SecurityError = SecurityError;
  3889. },{}],15:[function(require,module,exports){
  3890. 'use strict';
  3891. Object.defineProperty(exports, "__esModule", {
  3892. value: true
  3893. });
  3894. exports.string_to_bytes = string_to_bytes;
  3895. exports.hex_to_bytes = hex_to_bytes;
  3896. exports.base64_to_bytes = base64_to_bytes;
  3897. exports.bytes_to_string = bytes_to_string;
  3898. exports.bytes_to_hex = bytes_to_hex;
  3899. exports.bytes_to_base64 = bytes_to_base64;
  3900. exports.pow2_ceil = pow2_ceil;
  3901. exports.is_number = is_number;
  3902. exports.is_string = is_string;
  3903. exports.is_buffer = is_buffer;
  3904. exports.is_bytes = is_bytes;
  3905. exports.is_typed_array = is_typed_array;
  3906. exports._heap_init = _heap_init;
  3907. exports._heap_write = _heap_write;
  3908. exports.joinBytes = joinBytes;
  3909. var local_atob = typeof atob === 'undefined' ? function (str) {
  3910. return require('buffer').Buffer.from(str, 'base64').toString('binary');
  3911. } : atob;
  3912. var local_btoa = typeof btoa === 'undefined' ? function (str) {
  3913. return require('buffer').Buffer.from(str, 'binary').toString('base64');
  3914. } : btoa;
  3915. function string_to_bytes(str, utf8) {
  3916. if (utf8 === void 0) {
  3917. utf8 = false;
  3918. }
  3919. var len = str.length,
  3920. bytes = new Uint8Array(utf8 ? 4 * len : len);
  3921. for (var i = 0, j = 0; i < len; i++) {
  3922. var c = str.charCodeAt(i);
  3923. if (utf8 && 0xd800 <= c && c <= 0xdbff) {
  3924. if (++i >= len) throw new Error('Malformed string, low surrogate expected at position ' + i);
  3925. c = (c ^ 0xd800) << 10 | 0x10000 | str.charCodeAt(i) ^ 0xdc00;
  3926. } else if (!utf8 && c >>> 8) {
  3927. throw new Error('Wide characters are not allowed.');
  3928. }
  3929. if (!utf8 || c <= 0x7f) {
  3930. bytes[j++] = c;
  3931. } else if (c <= 0x7ff) {
  3932. bytes[j++] = 0xc0 | c >> 6;
  3933. bytes[j++] = 0x80 | c & 0x3f;
  3934. } else if (c <= 0xffff) {
  3935. bytes[j++] = 0xe0 | c >> 12;
  3936. bytes[j++] = 0x80 | c >> 6 & 0x3f;
  3937. bytes[j++] = 0x80 | c & 0x3f;
  3938. } else {
  3939. bytes[j++] = 0xf0 | c >> 18;
  3940. bytes[j++] = 0x80 | c >> 12 & 0x3f;
  3941. bytes[j++] = 0x80 | c >> 6 & 0x3f;
  3942. bytes[j++] = 0x80 | c & 0x3f;
  3943. }
  3944. }
  3945. return bytes.subarray(0, j);
  3946. }
  3947. function hex_to_bytes(str) {
  3948. var len = str.length;
  3949. if (len & 1) {
  3950. str = '0' + str;
  3951. len++;
  3952. }
  3953. var bytes = new Uint8Array(len >> 1);
  3954. for (var i = 0; i < len; i += 2) {
  3955. bytes[i >> 1] = parseInt(str.substr(i, 2), 16);
  3956. }
  3957. return bytes;
  3958. }
  3959. function base64_to_bytes(str) {
  3960. return string_to_bytes(local_atob(str));
  3961. }
  3962. function bytes_to_string(bytes, utf8) {
  3963. if (utf8 === void 0) {
  3964. utf8 = false;
  3965. }
  3966. var len = bytes.length,
  3967. chars = new Array(len);
  3968. for (var i = 0, j = 0; i < len; i++) {
  3969. var b = bytes[i];
  3970. if (!utf8 || b < 128) {
  3971. chars[j++] = b;
  3972. } else if (b >= 192 && b < 224 && i + 1 < len) {
  3973. chars[j++] = (b & 0x1f) << 6 | bytes[++i] & 0x3f;
  3974. } else if (b >= 224 && b < 240 && i + 2 < len) {
  3975. chars[j++] = (b & 0xf) << 12 | (bytes[++i] & 0x3f) << 6 | bytes[++i] & 0x3f;
  3976. } else if (b >= 240 && b < 248 && i + 3 < len) {
  3977. var c = (b & 7) << 18 | (bytes[++i] & 0x3f) << 12 | (bytes[++i] & 0x3f) << 6 | bytes[++i] & 0x3f;
  3978. if (c <= 0xffff) {
  3979. chars[j++] = c;
  3980. } else {
  3981. c ^= 0x10000;
  3982. chars[j++] = 0xd800 | c >> 10;
  3983. chars[j++] = 0xdc00 | c & 0x3ff;
  3984. }
  3985. } else {
  3986. throw new Error('Malformed UTF8 character at byte offset ' + i);
  3987. }
  3988. }
  3989. var str = '',
  3990. bs = 16384;
  3991. for (var i = 0; i < j; i += bs) {
  3992. str += String.fromCharCode.apply(String, chars.slice(i, i + bs <= j ? i + bs : j));
  3993. }
  3994. return str;
  3995. }
  3996. function bytes_to_hex(arr) {
  3997. var str = '';
  3998. for (var i = 0; i < arr.length; i++) {
  3999. var h = (arr[i] & 0xff).toString(16);
  4000. if (h.length < 2) str += '0';
  4001. str += h;
  4002. }
  4003. return str;
  4004. }
  4005. function bytes_to_base64(arr) {
  4006. return local_btoa(bytes_to_string(arr));
  4007. }
  4008. function pow2_ceil(a) {
  4009. a -= 1;
  4010. a |= a >>> 1;
  4011. a |= a >>> 2;
  4012. a |= a >>> 4;
  4013. a |= a >>> 8;
  4014. a |= a >>> 16;
  4015. a += 1;
  4016. return a;
  4017. }
  4018. function is_number(a) {
  4019. return typeof a === 'number';
  4020. }
  4021. function is_string(a) {
  4022. return typeof a === 'string';
  4023. }
  4024. function is_buffer(a) {
  4025. return a instanceof ArrayBuffer;
  4026. }
  4027. function is_bytes(a) {
  4028. return a instanceof Uint8Array;
  4029. }
  4030. function is_typed_array(a) {
  4031. return a instanceof Int8Array || a instanceof Uint8Array || a instanceof Int16Array || a instanceof Uint16Array || a instanceof Int32Array || a instanceof Uint32Array || a instanceof Float32Array || a instanceof Float64Array;
  4032. }
  4033. function _heap_init(heap, heapSize) {
  4034. var size = heap ? heap.byteLength : heapSize || 65536;
  4035. if (size & 0xfff || size <= 0) throw new Error('heap size must be a positive integer and a multiple of 4096');
  4036. heap = heap || new Uint8Array(new ArrayBuffer(size));
  4037. return heap;
  4038. }
  4039. function _heap_write(heap, hpos, data, dpos, dlen) {
  4040. var hlen = heap.length - hpos;
  4041. var wlen = hlen < dlen ? hlen : dlen;
  4042. heap.set(data.subarray(dpos, dpos + wlen), hpos);
  4043. return wlen;
  4044. }
  4045. function joinBytes() {
  4046. var arg = [];
  4047. for (var _i = 0; _i < arguments.length; _i++) {
  4048. arg[_i] = arguments[_i];
  4049. }
  4050. var totalLenght = arg.reduce(function (sum, curr) {
  4051. return sum + curr.length;
  4052. }, 0);
  4053. var ret = new Uint8Array(totalLenght);
  4054. var cursor = 0;
  4055. for (var i = 0; i < arg.length; i++) {
  4056. ret.set(arg[i], cursor);
  4057. cursor += arg[i].length;
  4058. }
  4059. return ret;
  4060. }
  4061. },{"buffer":"buffer"}],16:[function(require,module,exports){
  4062. (function (module, exports) {
  4063. 'use strict';
  4064. // Utils
  4065. function assert (val, msg) {
  4066. if (!val) throw new Error(msg || 'Assertion failed');
  4067. }
  4068. // Could use `inherits` module, but don't want to move from single file
  4069. // architecture yet.
  4070. function inherits (ctor, superCtor) {
  4071. ctor.super_ = superCtor;
  4072. var TempCtor = function () {};
  4073. TempCtor.prototype = superCtor.prototype;
  4074. ctor.prototype = new TempCtor();
  4075. ctor.prototype.constructor = ctor;
  4076. }
  4077. // BN
  4078. function BN (number, base, endian) {
  4079. if (BN.isBN(number)) {
  4080. return number;
  4081. }
  4082. this.negative = 0;
  4083. this.words = null;
  4084. this.length = 0;
  4085. // Reduction context
  4086. this.red = null;
  4087. if (number !== null) {
  4088. if (base === 'le' || base === 'be') {
  4089. endian = base;
  4090. base = 10;
  4091. }
  4092. this._init(number || 0, base || 10, endian || 'be');
  4093. }
  4094. }
  4095. if (typeof module === 'object') {
  4096. module.exports = BN;
  4097. } else {
  4098. exports.BN = BN;
  4099. }
  4100. BN.BN = BN;
  4101. BN.wordSize = 26;
  4102. var Buffer;
  4103. try {
  4104. Buffer = require('buffer').Buffer;
  4105. } catch (e) {
  4106. }
  4107. BN.isBN = function isBN (num) {
  4108. if (num instanceof BN) {
  4109. return true;
  4110. }
  4111. return num !== null && typeof num === 'object' &&
  4112. num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
  4113. };
  4114. BN.max = function max (left, right) {
  4115. if (left.cmp(right) > 0) return left;
  4116. return right;
  4117. };
  4118. BN.min = function min (left, right) {
  4119. if (left.cmp(right) < 0) return left;
  4120. return right;
  4121. };
  4122. BN.prototype._init = function init (number, base, endian) {
  4123. if (typeof number === 'number') {
  4124. return this._initNumber(number, base, endian);
  4125. }
  4126. if (typeof number === 'object') {
  4127. return this._initArray(number, base, endian);
  4128. }
  4129. if (base === 'hex') {
  4130. base = 16;
  4131. }
  4132. assert(base === (base | 0) && base >= 2 && base <= 36);
  4133. number = number.toString().replace(/\s+/g, '');
  4134. var start = 0;
  4135. if (number[0] === '-') {
  4136. start++;
  4137. }
  4138. if (base === 16) {
  4139. this._parseHex(number, start);
  4140. } else {
  4141. this._parseBase(number, base, start);
  4142. }
  4143. if (number[0] === '-') {
  4144. this.negative = 1;
  4145. }
  4146. this.strip();
  4147. if (endian !== 'le') return;
  4148. this._initArray(this.toArray(), base, endian);
  4149. };
  4150. BN.prototype._initNumber = function _initNumber (number, base, endian) {
  4151. if (number < 0) {
  4152. this.negative = 1;
  4153. number = -number;
  4154. }
  4155. if (number < 0x4000000) {
  4156. this.words = [ number & 0x3ffffff ];
  4157. this.length = 1;
  4158. } else if (number < 0x10000000000000) {
  4159. this.words = [
  4160. number & 0x3ffffff,
  4161. (number / 0x4000000) & 0x3ffffff
  4162. ];
  4163. this.length = 2;
  4164. } else {
  4165. assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
  4166. this.words = [
  4167. number & 0x3ffffff,
  4168. (number / 0x4000000) & 0x3ffffff,
  4169. 1
  4170. ];
  4171. this.length = 3;
  4172. }
  4173. if (endian !== 'le') return;
  4174. // Reverse the bytes
  4175. this._initArray(this.toArray(), base, endian);
  4176. };
  4177. BN.prototype._initArray = function _initArray (number, base, endian) {
  4178. // Perhaps a Uint8Array
  4179. assert(typeof number.length === 'number');
  4180. if (number.length <= 0) {
  4181. this.words = [ 0 ];
  4182. this.length = 1;
  4183. return this;
  4184. }
  4185. this.length = Math.ceil(number.length / 3);
  4186. this.words = new Array(this.length);
  4187. for (var i = 0; i < this.length; i++) {
  4188. this.words[i] = 0;
  4189. }
  4190. var j, w;
  4191. var off = 0;
  4192. if (endian === 'be') {
  4193. for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
  4194. w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
  4195. this.words[j] |= (w << off) & 0x3ffffff;
  4196. this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
  4197. off += 24;
  4198. if (off >= 26) {
  4199. off -= 26;
  4200. j++;
  4201. }
  4202. }
  4203. } else if (endian === 'le') {
  4204. for (i = 0, j = 0; i < number.length; i += 3) {
  4205. w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
  4206. this.words[j] |= (w << off) & 0x3ffffff;
  4207. this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
  4208. off += 24;
  4209. if (off >= 26) {
  4210. off -= 26;
  4211. j++;
  4212. }
  4213. }
  4214. }
  4215. return this.strip();
  4216. };
  4217. function parseHex (str, start, end) {
  4218. var r = 0;
  4219. var len = Math.min(str.length, end);
  4220. for (var i = start; i < len; i++) {
  4221. var c = str.charCodeAt(i) - 48;
  4222. r <<= 4;
  4223. // 'a' - 'f'
  4224. if (c >= 49 && c <= 54) {
  4225. r |= c - 49 + 0xa;
  4226. // 'A' - 'F'
  4227. } else if (c >= 17 && c <= 22) {
  4228. r |= c - 17 + 0xa;
  4229. // '0' - '9'
  4230. } else {
  4231. r |= c & 0xf;
  4232. }
  4233. }
  4234. return r;
  4235. }
  4236. BN.prototype._parseHex = function _parseHex (number, start) {
  4237. // Create possibly bigger array to ensure that it fits the number
  4238. this.length = Math.ceil((number.length - start) / 6);
  4239. this.words = new Array(this.length);
  4240. for (var i = 0; i < this.length; i++) {
  4241. this.words[i] = 0;
  4242. }
  4243. var j, w;
  4244. // Scan 24-bit chunks and add them to the number
  4245. var off = 0;
  4246. for (i = number.length - 6, j = 0; i >= start; i -= 6) {
  4247. w = parseHex(number, i, i + 6);
  4248. this.words[j] |= (w << off) & 0x3ffffff;
  4249. // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
  4250. this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
  4251. off += 24;
  4252. if (off >= 26) {
  4253. off -= 26;
  4254. j++;
  4255. }
  4256. }
  4257. if (i + 6 !== start) {
  4258. w = parseHex(number, start, i + 6);
  4259. this.words[j] |= (w << off) & 0x3ffffff;
  4260. this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
  4261. }
  4262. this.strip();
  4263. };
  4264. function parseBase (str, start, end, mul) {
  4265. var r = 0;
  4266. var len = Math.min(str.length, end);
  4267. for (var i = start; i < len; i++) {
  4268. var c = str.charCodeAt(i) - 48;
  4269. r *= mul;
  4270. // 'a'
  4271. if (c >= 49) {
  4272. r += c - 49 + 0xa;
  4273. // 'A'
  4274. } else if (c >= 17) {
  4275. r += c - 17 + 0xa;
  4276. // '0' - '9'
  4277. } else {
  4278. r += c;
  4279. }
  4280. }
  4281. return r;
  4282. }
  4283. BN.prototype._parseBase = function _parseBase (number, base, start) {
  4284. // Initialize as zero
  4285. this.words = [ 0 ];
  4286. this.length = 1;
  4287. // Find length of limb in base
  4288. for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
  4289. limbLen++;
  4290. }
  4291. limbLen--;
  4292. limbPow = (limbPow / base) | 0;
  4293. var total = number.length - start;
  4294. var mod = total % limbLen;
  4295. var end = Math.min(total, total - mod) + start;
  4296. var word = 0;
  4297. for (var i = start; i < end; i += limbLen) {
  4298. word = parseBase(number, i, i + limbLen, base);
  4299. this.imuln(limbPow);
  4300. if (this.words[0] + word < 0x4000000) {
  4301. this.words[0] += word;
  4302. } else {
  4303. this._iaddn(word);
  4304. }
  4305. }
  4306. if (mod !== 0) {
  4307. var pow = 1;
  4308. word = parseBase(number, i, number.length, base);
  4309. for (i = 0; i < mod; i++) {
  4310. pow *= base;
  4311. }
  4312. this.imuln(pow);
  4313. if (this.words[0] + word < 0x4000000) {
  4314. this.words[0] += word;
  4315. } else {
  4316. this._iaddn(word);
  4317. }
  4318. }
  4319. };
  4320. BN.prototype.copy = function copy (dest) {
  4321. dest.words = new Array(this.length);
  4322. for (var i = 0; i < this.length; i++) {
  4323. dest.words[i] = this.words[i];
  4324. }
  4325. dest.length = this.length;
  4326. dest.negative = this.negative;
  4327. dest.red = this.red;
  4328. };
  4329. BN.prototype.clone = function clone () {
  4330. var r = new BN(null);
  4331. this.copy(r);
  4332. return r;
  4333. };
  4334. BN.prototype._expand = function _expand (size) {
  4335. while (this.length < size) {
  4336. this.words[this.length++] = 0;
  4337. }
  4338. return this;
  4339. };
  4340. // Remove leading `0` from `this`
  4341. BN.prototype.strip = function strip () {
  4342. while (this.length > 1 && this.words[this.length - 1] === 0) {
  4343. this.length--;
  4344. }
  4345. return this._normSign();
  4346. };
  4347. BN.prototype._normSign = function _normSign () {
  4348. // -0 = 0
  4349. if (this.length === 1 && this.words[0] === 0) {
  4350. this.negative = 0;
  4351. }
  4352. return this;
  4353. };
  4354. BN.prototype.inspect = function inspect () {
  4355. return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
  4356. };
  4357. /*
  4358. var zeros = [];
  4359. var groupSizes = [];
  4360. var groupBases = [];
  4361. var s = '';
  4362. var i = -1;
  4363. while (++i < BN.wordSize) {
  4364. zeros[i] = s;
  4365. s += '0';
  4366. }
  4367. groupSizes[0] = 0;
  4368. groupSizes[1] = 0;
  4369. groupBases[0] = 0;
  4370. groupBases[1] = 0;
  4371. var base = 2 - 1;
  4372. while (++base < 36 + 1) {
  4373. var groupSize = 0;
  4374. var groupBase = 1;
  4375. while (groupBase < (1 << BN.wordSize) / base) {
  4376. groupBase *= base;
  4377. groupSize += 1;
  4378. }
  4379. groupSizes[base] = groupSize;
  4380. groupBases[base] = groupBase;
  4381. }
  4382. */
  4383. var zeros = [
  4384. '',
  4385. '0',
  4386. '00',
  4387. '000',
  4388. '0000',
  4389. '00000',
  4390. '000000',
  4391. '0000000',
  4392. '00000000',
  4393. '000000000',
  4394. '0000000000',
  4395. '00000000000',
  4396. '000000000000',
  4397. '0000000000000',
  4398. '00000000000000',
  4399. '000000000000000',
  4400. '0000000000000000',
  4401. '00000000000000000',
  4402. '000000000000000000',
  4403. '0000000000000000000',
  4404. '00000000000000000000',
  4405. '000000000000000000000',
  4406. '0000000000000000000000',
  4407. '00000000000000000000000',
  4408. '000000000000000000000000',
  4409. '0000000000000000000000000'
  4410. ];
  4411. var groupSizes = [
  4412. 0, 0,
  4413. 25, 16, 12, 11, 10, 9, 8,
  4414. 8, 7, 7, 7, 7, 6, 6,
  4415. 6, 6, 6, 6, 6, 5, 5,
  4416. 5, 5, 5, 5, 5, 5, 5,
  4417. 5, 5, 5, 5, 5, 5, 5
  4418. ];
  4419. var groupBases = [
  4420. 0, 0,
  4421. 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
  4422. 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
  4423. 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
  4424. 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
  4425. 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
  4426. ];
  4427. BN.prototype.toString = function toString (base, padding) {
  4428. base = base || 10;
  4429. padding = padding | 0 || 1;
  4430. var out;
  4431. if (base === 16 || base === 'hex') {
  4432. out = '';
  4433. var off = 0;
  4434. var carry = 0;
  4435. for (var i = 0; i < this.length; i++) {
  4436. var w = this.words[i];
  4437. var word = (((w << off) | carry) & 0xffffff).toString(16);
  4438. carry = (w >>> (24 - off)) & 0xffffff;
  4439. if (carry !== 0 || i !== this.length - 1) {
  4440. out = zeros[6 - word.length] + word + out;
  4441. } else {
  4442. out = word + out;
  4443. }
  4444. off += 2;
  4445. if (off >= 26) {
  4446. off -= 26;
  4447. i--;
  4448. }
  4449. }
  4450. if (carry !== 0) {
  4451. out = carry.toString(16) + out;
  4452. }
  4453. while (out.length % padding !== 0) {
  4454. out = '0' + out;
  4455. }
  4456. if (this.negative !== 0) {
  4457. out = '-' + out;
  4458. }
  4459. return out;
  4460. }
  4461. if (base === (base | 0) && base >= 2 && base <= 36) {
  4462. // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
  4463. var groupSize = groupSizes[base];
  4464. // var groupBase = Math.pow(base, groupSize);
  4465. var groupBase = groupBases[base];
  4466. out = '';
  4467. var c = this.clone();
  4468. c.negative = 0;
  4469. while (!c.isZero()) {
  4470. var r = c.modn(groupBase).toString(base);
  4471. c = c.idivn(groupBase);
  4472. if (!c.isZero()) {
  4473. out = zeros[groupSize - r.length] + r + out;
  4474. } else {
  4475. out = r + out;
  4476. }
  4477. }
  4478. if (this.isZero()) {
  4479. out = '0' + out;
  4480. }
  4481. while (out.length % padding !== 0) {
  4482. out = '0' + out;
  4483. }
  4484. if (this.negative !== 0) {
  4485. out = '-' + out;
  4486. }
  4487. return out;
  4488. }
  4489. assert(false, 'Base should be between 2 and 36');
  4490. };
  4491. BN.prototype.toNumber = function toNumber () {
  4492. var ret = this.words[0];
  4493. if (this.length === 2) {
  4494. ret += this.words[1] * 0x4000000;
  4495. } else if (this.length === 3 && this.words[2] === 0x01) {
  4496. // NOTE: at this stage it is known that the top bit is set
  4497. ret += 0x10000000000000 + (this.words[1] * 0x4000000);
  4498. } else if (this.length > 2) {
  4499. assert(false, 'Number can only safely store up to 53 bits');
  4500. }
  4501. return (this.negative !== 0) ? -ret : ret;
  4502. };
  4503. BN.prototype.toJSON = function toJSON () {
  4504. return this.toString(16);
  4505. };
  4506. BN.prototype.toBuffer = function toBuffer (endian, length) {
  4507. assert(typeof Buffer !== 'undefined');
  4508. return this.toArrayLike(Buffer, endian, length);
  4509. };
  4510. BN.prototype.toArray = function toArray (endian, length) {
  4511. return this.toArrayLike(Array, endian, length);
  4512. };
  4513. BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
  4514. var byteLength = this.byteLength();
  4515. var reqLength = length || Math.max(1, byteLength);
  4516. assert(byteLength <= reqLength, 'byte array longer than desired length');
  4517. assert(reqLength > 0, 'Requested array length <= 0');
  4518. this.strip();
  4519. var littleEndian = endian === 'le';
  4520. var res = new ArrayType(reqLength);
  4521. var b, i;
  4522. var q = this.clone();
  4523. if (!littleEndian) {
  4524. // Assume big-endian
  4525. for (i = 0; i < reqLength - byteLength; i++) {
  4526. res[i] = 0;
  4527. }
  4528. for (i = 0; !q.isZero(); i++) {
  4529. b = q.andln(0xff);
  4530. q.iushrn(8);
  4531. res[reqLength - i - 1] = b;
  4532. }
  4533. } else {
  4534. for (i = 0; !q.isZero(); i++) {
  4535. b = q.andln(0xff);
  4536. q.iushrn(8);
  4537. res[i] = b;
  4538. }
  4539. for (; i < reqLength; i++) {
  4540. res[i] = 0;
  4541. }
  4542. }
  4543. return res;
  4544. };
  4545. if (Math.clz32) {
  4546. BN.prototype._countBits = function _countBits (w) {
  4547. return 32 - Math.clz32(w);
  4548. };
  4549. } else {
  4550. BN.prototype._countBits = function _countBits (w) {
  4551. var t = w;
  4552. var r = 0;
  4553. if (t >= 0x1000) {
  4554. r += 13;
  4555. t >>>= 13;
  4556. }
  4557. if (t >= 0x40) {
  4558. r += 7;
  4559. t >>>= 7;
  4560. }
  4561. if (t >= 0x8) {
  4562. r += 4;
  4563. t >>>= 4;
  4564. }
  4565. if (t >= 0x02) {
  4566. r += 2;
  4567. t >>>= 2;
  4568. }
  4569. return r + t;
  4570. };
  4571. }
  4572. BN.prototype._zeroBits = function _zeroBits (w) {
  4573. // Short-cut
  4574. if (w === 0) return 26;
  4575. var t = w;
  4576. var r = 0;
  4577. if ((t & 0x1fff) === 0) {
  4578. r += 13;
  4579. t >>>= 13;
  4580. }
  4581. if ((t & 0x7f) === 0) {
  4582. r += 7;
  4583. t >>>= 7;
  4584. }
  4585. if ((t & 0xf) === 0) {
  4586. r += 4;
  4587. t >>>= 4;
  4588. }
  4589. if ((t & 0x3) === 0) {
  4590. r += 2;
  4591. t >>>= 2;
  4592. }
  4593. if ((t & 0x1) === 0) {
  4594. r++;
  4595. }
  4596. return r;
  4597. };
  4598. // Return number of used bits in a BN
  4599. BN.prototype.bitLength = function bitLength () {
  4600. var w = this.words[this.length - 1];
  4601. var hi = this._countBits(w);
  4602. return (this.length - 1) * 26 + hi;
  4603. };
  4604. function toBitArray (num) {
  4605. var w = new Array(num.bitLength());
  4606. for (var bit = 0; bit < w.length; bit++) {
  4607. var off = (bit / 26) | 0;
  4608. var wbit = bit % 26;
  4609. w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
  4610. }
  4611. return w;
  4612. }
  4613. // Number of trailing zero bits
  4614. BN.prototype.zeroBits = function zeroBits () {
  4615. if (this.isZero()) return 0;
  4616. var r = 0;
  4617. for (var i = 0; i < this.length; i++) {
  4618. var b = this._zeroBits(this.words[i]);
  4619. r += b;
  4620. if (b !== 26) break;
  4621. }
  4622. return r;
  4623. };
  4624. BN.prototype.byteLength = function byteLength () {
  4625. return Math.ceil(this.bitLength() / 8);
  4626. };
  4627. BN.prototype.toTwos = function toTwos (width) {
  4628. if (this.negative !== 0) {
  4629. return this.abs().inotn(width).iaddn(1);
  4630. }
  4631. return this.clone();
  4632. };
  4633. BN.prototype.fromTwos = function fromTwos (width) {
  4634. if (this.testn(width - 1)) {
  4635. return this.notn(width).iaddn(1).ineg();
  4636. }
  4637. return this.clone();
  4638. };
  4639. BN.prototype.isNeg = function isNeg () {
  4640. return this.negative !== 0;
  4641. };
  4642. // Return negative clone of `this`
  4643. BN.prototype.neg = function neg () {
  4644. return this.clone().ineg();
  4645. };
  4646. BN.prototype.ineg = function ineg () {
  4647. if (!this.isZero()) {
  4648. this.negative ^= 1;
  4649. }
  4650. return this;
  4651. };
  4652. // Or `num` with `this` in-place
  4653. BN.prototype.iuor = function iuor (num) {
  4654. while (this.length < num.length) {
  4655. this.words[this.length++] = 0;
  4656. }
  4657. for (var i = 0; i < num.length; i++) {
  4658. this.words[i] = this.words[i] | num.words[i];
  4659. }
  4660. return this.strip();
  4661. };
  4662. BN.prototype.ior = function ior (num) {
  4663. assert((this.negative | num.negative) === 0);
  4664. return this.iuor(num);
  4665. };
  4666. // Or `num` with `this`
  4667. BN.prototype.or = function or (num) {
  4668. if (this.length > num.length) return this.clone().ior(num);
  4669. return num.clone().ior(this);
  4670. };
  4671. BN.prototype.uor = function uor (num) {
  4672. if (this.length > num.length) return this.clone().iuor(num);
  4673. return num.clone().iuor(this);
  4674. };
  4675. // And `num` with `this` in-place
  4676. BN.prototype.iuand = function iuand (num) {
  4677. // b = min-length(num, this)
  4678. var b;
  4679. if (this.length > num.length) {
  4680. b = num;
  4681. } else {
  4682. b = this;
  4683. }
  4684. for (var i = 0; i < b.length; i++) {
  4685. this.words[i] = this.words[i] & num.words[i];
  4686. }
  4687. this.length = b.length;
  4688. return this.strip();
  4689. };
  4690. BN.prototype.iand = function iand (num) {
  4691. assert((this.negative | num.negative) === 0);
  4692. return this.iuand(num);
  4693. };
  4694. // And `num` with `this`
  4695. BN.prototype.and = function and (num) {
  4696. if (this.length > num.length) return this.clone().iand(num);
  4697. return num.clone().iand(this);
  4698. };
  4699. BN.prototype.uand = function uand (num) {
  4700. if (this.length > num.length) return this.clone().iuand(num);
  4701. return num.clone().iuand(this);
  4702. };
  4703. // Xor `num` with `this` in-place
  4704. BN.prototype.iuxor = function iuxor (num) {
  4705. // a.length > b.length
  4706. var a;
  4707. var b;
  4708. if (this.length > num.length) {
  4709. a = this;
  4710. b = num;
  4711. } else {
  4712. a = num;
  4713. b = this;
  4714. }
  4715. for (var i = 0; i < b.length; i++) {
  4716. this.words[i] = a.words[i] ^ b.words[i];
  4717. }
  4718. if (this !== a) {
  4719. for (; i < a.length; i++) {
  4720. this.words[i] = a.words[i];
  4721. }
  4722. }
  4723. this.length = a.length;
  4724. return this.strip();
  4725. };
  4726. BN.prototype.ixor = function ixor (num) {
  4727. assert((this.negative | num.negative) === 0);
  4728. return this.iuxor(num);
  4729. };
  4730. // Xor `num` with `this`
  4731. BN.prototype.xor = function xor (num) {
  4732. if (this.length > num.length) return this.clone().ixor(num);
  4733. return num.clone().ixor(this);
  4734. };
  4735. BN.prototype.uxor = function uxor (num) {
  4736. if (this.length > num.length) return this.clone().iuxor(num);
  4737. return num.clone().iuxor(this);
  4738. };
  4739. // Not ``this`` with ``width`` bitwidth
  4740. BN.prototype.inotn = function inotn (width) {
  4741. assert(typeof width === 'number' && width >= 0);
  4742. var bytesNeeded = Math.ceil(width / 26) | 0;
  4743. var bitsLeft = width % 26;
  4744. // Extend the buffer with leading zeroes
  4745. this._expand(bytesNeeded);
  4746. if (bitsLeft > 0) {
  4747. bytesNeeded--;
  4748. }
  4749. // Handle complete words
  4750. for (var i = 0; i < bytesNeeded; i++) {
  4751. this.words[i] = ~this.words[i] & 0x3ffffff;
  4752. }
  4753. // Handle the residue
  4754. if (bitsLeft > 0) {
  4755. this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
  4756. }
  4757. // And remove leading zeroes
  4758. return this.strip();
  4759. };
  4760. BN.prototype.notn = function notn (width) {
  4761. return this.clone().inotn(width);
  4762. };
  4763. // Set `bit` of `this`
  4764. BN.prototype.setn = function setn (bit, val) {
  4765. assert(typeof bit === 'number' && bit >= 0);
  4766. var off = (bit / 26) | 0;
  4767. var wbit = bit % 26;
  4768. this._expand(off + 1);
  4769. if (val) {
  4770. this.words[off] = this.words[off] | (1 << wbit);
  4771. } else {
  4772. this.words[off] = this.words[off] & ~(1 << wbit);
  4773. }
  4774. return this.strip();
  4775. };
  4776. // Add `num` to `this` in-place
  4777. BN.prototype.iadd = function iadd (num) {
  4778. var r;
  4779. // negative + positive
  4780. if (this.negative !== 0 && num.negative === 0) {
  4781. this.negative = 0;
  4782. r = this.isub(num);
  4783. this.negative ^= 1;
  4784. return this._normSign();
  4785. // positive + negative
  4786. } else if (this.negative === 0 && num.negative !== 0) {
  4787. num.negative = 0;
  4788. r = this.isub(num);
  4789. num.negative = 1;
  4790. return r._normSign();
  4791. }
  4792. // a.length > b.length
  4793. var a, b;
  4794. if (this.length > num.length) {
  4795. a = this;
  4796. b = num;
  4797. } else {
  4798. a = num;
  4799. b = this;
  4800. }
  4801. var carry = 0;
  4802. for (var i = 0; i < b.length; i++) {
  4803. r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
  4804. this.words[i] = r & 0x3ffffff;
  4805. carry = r >>> 26;
  4806. }
  4807. for (; carry !== 0 && i < a.length; i++) {
  4808. r = (a.words[i] | 0) + carry;
  4809. this.words[i] = r & 0x3ffffff;
  4810. carry = r >>> 26;
  4811. }
  4812. this.length = a.length;
  4813. if (carry !== 0) {
  4814. this.words[this.length] = carry;
  4815. this.length++;
  4816. // Copy the rest of the words
  4817. } else if (a !== this) {
  4818. for (; i < a.length; i++) {
  4819. this.words[i] = a.words[i];
  4820. }
  4821. }
  4822. return this;
  4823. };
  4824. // Add `num` to `this`
  4825. BN.prototype.add = function add (num) {
  4826. var res;
  4827. if (num.negative !== 0 && this.negative === 0) {
  4828. num.negative = 0;
  4829. res = this.sub(num);
  4830. num.negative ^= 1;
  4831. return res;
  4832. } else if (num.negative === 0 && this.negative !== 0) {
  4833. this.negative = 0;
  4834. res = num.sub(this);
  4835. this.negative = 1;
  4836. return res;
  4837. }
  4838. if (this.length > num.length) return this.clone().iadd(num);
  4839. return num.clone().iadd(this);
  4840. };
  4841. // Subtract `num` from `this` in-place
  4842. BN.prototype.isub = function isub (num) {
  4843. // this - (-num) = this + num
  4844. if (num.negative !== 0) {
  4845. num.negative = 0;
  4846. var r = this.iadd(num);
  4847. num.negative = 1;
  4848. return r._normSign();
  4849. // -this - num = -(this + num)
  4850. } else if (this.negative !== 0) {
  4851. this.negative = 0;
  4852. this.iadd(num);
  4853. this.negative = 1;
  4854. return this._normSign();
  4855. }
  4856. // At this point both numbers are positive
  4857. var cmp = this.cmp(num);
  4858. // Optimization - zeroify
  4859. if (cmp === 0) {
  4860. this.negative = 0;
  4861. this.length = 1;
  4862. this.words[0] = 0;
  4863. return this;
  4864. }
  4865. // a > b
  4866. var a, b;
  4867. if (cmp > 0) {
  4868. a = this;
  4869. b = num;
  4870. } else {
  4871. a = num;
  4872. b = this;
  4873. }
  4874. var carry = 0;
  4875. for (var i = 0; i < b.length; i++) {
  4876. r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
  4877. carry = r >> 26;
  4878. this.words[i] = r & 0x3ffffff;
  4879. }
  4880. for (; carry !== 0 && i < a.length; i++) {
  4881. r = (a.words[i] | 0) + carry;
  4882. carry = r >> 26;
  4883. this.words[i] = r & 0x3ffffff;
  4884. }
  4885. // Copy rest of the words
  4886. if (carry === 0 && i < a.length && a !== this) {
  4887. for (; i < a.length; i++) {
  4888. this.words[i] = a.words[i];
  4889. }
  4890. }
  4891. this.length = Math.max(this.length, i);
  4892. if (a !== this) {
  4893. this.negative = 1;
  4894. }
  4895. return this.strip();
  4896. };
  4897. // Subtract `num` from `this`
  4898. BN.prototype.sub = function sub (num) {
  4899. return this.clone().isub(num);
  4900. };
  4901. function smallMulTo (self, num, out) {
  4902. out.negative = num.negative ^ self.negative;
  4903. var len = (self.length + num.length) | 0;
  4904. out.length = len;
  4905. len = (len - 1) | 0;
  4906. // Peel one iteration (compiler can't do it, because of code complexity)
  4907. var a = self.words[0] | 0;
  4908. var b = num.words[0] | 0;
  4909. var r = a * b;
  4910. var lo = r & 0x3ffffff;
  4911. var carry = (r / 0x4000000) | 0;
  4912. out.words[0] = lo;
  4913. for (var k = 1; k < len; k++) {
  4914. // Sum all words with the same `i + j = k` and accumulate `ncarry`,
  4915. // note that ncarry could be >= 0x3ffffff
  4916. var ncarry = carry >>> 26;
  4917. var rword = carry & 0x3ffffff;
  4918. var maxJ = Math.min(k, num.length - 1);
  4919. for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
  4920. var i = (k - j) | 0;
  4921. a = self.words[i] | 0;
  4922. b = num.words[j] | 0;
  4923. r = a * b + rword;
  4924. ncarry += (r / 0x4000000) | 0;
  4925. rword = r & 0x3ffffff;
  4926. }
  4927. out.words[k] = rword | 0;
  4928. carry = ncarry | 0;
  4929. }
  4930. if (carry !== 0) {
  4931. out.words[k] = carry | 0;
  4932. } else {
  4933. out.length--;
  4934. }
  4935. return out.strip();
  4936. }
  4937. // TODO(indutny): it may be reasonable to omit it for users who don't need
  4938. // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
  4939. // multiplication (like elliptic secp256k1).
  4940. var comb10MulTo = function comb10MulTo (self, num, out) {
  4941. var a = self.words;
  4942. var b = num.words;
  4943. var o = out.words;
  4944. var c = 0;
  4945. var lo;
  4946. var mid;
  4947. var hi;
  4948. var a0 = a[0] | 0;
  4949. var al0 = a0 & 0x1fff;
  4950. var ah0 = a0 >>> 13;
  4951. var a1 = a[1] | 0;
  4952. var al1 = a1 & 0x1fff;
  4953. var ah1 = a1 >>> 13;
  4954. var a2 = a[2] | 0;
  4955. var al2 = a2 & 0x1fff;
  4956. var ah2 = a2 >>> 13;
  4957. var a3 = a[3] | 0;
  4958. var al3 = a3 & 0x1fff;
  4959. var ah3 = a3 >>> 13;
  4960. var a4 = a[4] | 0;
  4961. var al4 = a4 & 0x1fff;
  4962. var ah4 = a4 >>> 13;
  4963. var a5 = a[5] | 0;
  4964. var al5 = a5 & 0x1fff;
  4965. var ah5 = a5 >>> 13;
  4966. var a6 = a[6] | 0;
  4967. var al6 = a6 & 0x1fff;
  4968. var ah6 = a6 >>> 13;
  4969. var a7 = a[7] | 0;
  4970. var al7 = a7 & 0x1fff;
  4971. var ah7 = a7 >>> 13;
  4972. var a8 = a[8] | 0;
  4973. var al8 = a8 & 0x1fff;
  4974. var ah8 = a8 >>> 13;
  4975. var a9 = a[9] | 0;
  4976. var al9 = a9 & 0x1fff;
  4977. var ah9 = a9 >>> 13;
  4978. var b0 = b[0] | 0;
  4979. var bl0 = b0 & 0x1fff;
  4980. var bh0 = b0 >>> 13;
  4981. var b1 = b[1] | 0;
  4982. var bl1 = b1 & 0x1fff;
  4983. var bh1 = b1 >>> 13;
  4984. var b2 = b[2] | 0;
  4985. var bl2 = b2 & 0x1fff;
  4986. var bh2 = b2 >>> 13;
  4987. var b3 = b[3] | 0;
  4988. var bl3 = b3 & 0x1fff;
  4989. var bh3 = b3 >>> 13;
  4990. var b4 = b[4] | 0;
  4991. var bl4 = b4 & 0x1fff;
  4992. var bh4 = b4 >>> 13;
  4993. var b5 = b[5] | 0;
  4994. var bl5 = b5 & 0x1fff;
  4995. var bh5 = b5 >>> 13;
  4996. var b6 = b[6] | 0;
  4997. var bl6 = b6 & 0x1fff;
  4998. var bh6 = b6 >>> 13;
  4999. var b7 = b[7] | 0;
  5000. var bl7 = b7 & 0x1fff;
  5001. var bh7 = b7 >>> 13;
  5002. var b8 = b[8] | 0;
  5003. var bl8 = b8 & 0x1fff;
  5004. var bh8 = b8 >>> 13;
  5005. var b9 = b[9] | 0;
  5006. var bl9 = b9 & 0x1fff;
  5007. var bh9 = b9 >>> 13;
  5008. out.negative = self.negative ^ num.negative;
  5009. out.length = 19;
  5010. /* k = 0 */
  5011. lo = Math.imul(al0, bl0);
  5012. mid = Math.imul(al0, bh0);
  5013. mid = (mid + Math.imul(ah0, bl0)) | 0;
  5014. hi = Math.imul(ah0, bh0);
  5015. var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  5016. c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
  5017. w0 &= 0x3ffffff;
  5018. /* k = 1 */
  5019. lo = Math.imul(al1, bl0);
  5020. mid = Math.imul(al1, bh0);
  5021. mid = (mid + Math.imul(ah1, bl0)) | 0;
  5022. hi = Math.imul(ah1, bh0);
  5023. lo = (lo + Math.imul(al0, bl1)) | 0;
  5024. mid = (mid + Math.imul(al0, bh1)) | 0;
  5025. mid = (mid + Math.imul(ah0, bl1)) | 0;
  5026. hi = (hi + Math.imul(ah0, bh1)) | 0;
  5027. var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  5028. c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
  5029. w1 &= 0x3ffffff;
  5030. /* k = 2 */
  5031. lo = Math.imul(al2, bl0);
  5032. mid = Math.imul(al2, bh0);
  5033. mid = (mid + Math.imul(ah2, bl0)) | 0;
  5034. hi = Math.imul(ah2, bh0);
  5035. lo = (lo + Math.imul(al1, bl1)) | 0;
  5036. mid = (mid + Math.imul(al1, bh1)) | 0;
  5037. mid = (mid + Math.imul(ah1, bl1)) | 0;
  5038. hi = (hi + Math.imul(ah1, bh1)) | 0;
  5039. lo = (lo + Math.imul(al0, bl2)) | 0;
  5040. mid = (mid + Math.imul(al0, bh2)) | 0;
  5041. mid = (mid + Math.imul(ah0, bl2)) | 0;
  5042. hi = (hi + Math.imul(ah0, bh2)) | 0;
  5043. var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  5044. c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
  5045. w2 &= 0x3ffffff;
  5046. /* k = 3 */
  5047. lo = Math.imul(al3, bl0);
  5048. mid = Math.imul(al3, bh0);
  5049. mid = (mid + Math.imul(ah3, bl0)) | 0;
  5050. hi = Math.imul(ah3, bh0);
  5051. lo = (lo + Math.imul(al2, bl1)) | 0;
  5052. mid = (mid + Math.imul(al2, bh1)) | 0;
  5053. mid = (mid + Math.imul(ah2, bl1)) | 0;
  5054. hi = (hi + Math.imul(ah2, bh1)) | 0;
  5055. lo = (lo + Math.imul(al1, bl2)) | 0;
  5056. mid = (mid + Math.imul(al1, bh2)) | 0;
  5057. mid = (mid + Math.imul(ah1, bl2)) | 0;
  5058. hi = (hi + Math.imul(ah1, bh2)) | 0;
  5059. lo = (lo + Math.imul(al0, bl3)) | 0;
  5060. mid = (mid + Math.imul(al0, bh3)) | 0;
  5061. mid = (mid + Math.imul(ah0, bl3)) | 0;
  5062. hi = (hi + Math.imul(ah0, bh3)) | 0;
  5063. var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  5064. c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
  5065. w3 &= 0x3ffffff;
  5066. /* k = 4 */
  5067. lo = Math.imul(al4, bl0);
  5068. mid = Math.imul(al4, bh0);
  5069. mid = (mid + Math.imul(ah4, bl0)) | 0;
  5070. hi = Math.imul(ah4, bh0);
  5071. lo = (lo + Math.imul(al3, bl1)) | 0;
  5072. mid = (mid + Math.imul(al3, bh1)) | 0;
  5073. mid = (mid + Math.imul(ah3, bl1)) | 0;
  5074. hi = (hi + Math.imul(ah3, bh1)) | 0;
  5075. lo = (lo + Math.imul(al2, bl2)) | 0;
  5076. mid = (mid + Math.imul(al2, bh2)) | 0;
  5077. mid = (mid + Math.imul(ah2, bl2)) | 0;
  5078. hi = (hi + Math.imul(ah2, bh2)) | 0;
  5079. lo = (lo + Math.imul(al1, bl3)) | 0;
  5080. mid = (mid + Math.imul(al1, bh3)) | 0;
  5081. mid = (mid + Math.imul(ah1, bl3)) | 0;
  5082. hi = (hi + Math.imul(ah1, bh3)) | 0;
  5083. lo = (lo + Math.imul(al0, bl4)) | 0;
  5084. mid = (mid + Math.imul(al0, bh4)) | 0;
  5085. mid = (mid + Math.imul(ah0, bl4)) | 0;
  5086. hi = (hi + Math.imul(ah0, bh4)) | 0;
  5087. var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  5088. c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
  5089. w4 &= 0x3ffffff;
  5090. /* k = 5 */
  5091. lo = Math.imul(al5, bl0);
  5092. mid = Math.imul(al5, bh0);
  5093. mid = (mid + Math.imul(ah5, bl0)) | 0;
  5094. hi = Math.imul(ah5, bh0);
  5095. lo = (lo + Math.imul(al4, bl1)) | 0;
  5096. mid = (mid + Math.imul(al4, bh1)) | 0;
  5097. mid = (mid + Math.imul(ah4, bl1)) | 0;
  5098. hi = (hi + Math.imul(ah4, bh1)) | 0;
  5099. lo = (lo + Math.imul(al3, bl2)) | 0;
  5100. mid = (mid + Math.imul(al3, bh2)) | 0;
  5101. mid = (mid + Math.imul(ah3, bl2)) | 0;
  5102. hi = (hi + Math.imul(ah3, bh2)) | 0;
  5103. lo = (lo + Math.imul(al2, bl3)) | 0;
  5104. mid = (mid + Math.imul(al2, bh3)) | 0;
  5105. mid = (mid + Math.imul(ah2, bl3)) | 0;
  5106. hi = (hi + Math.imul(ah2, bh3)) | 0;
  5107. lo = (lo + Math.imul(al1, bl4)) | 0;
  5108. mid = (mid + Math.imul(al1, bh4)) | 0;
  5109. mid = (mid + Math.imul(ah1, bl4)) | 0;
  5110. hi = (hi + Math.imul(ah1, bh4)) | 0;
  5111. lo = (lo + Math.imul(al0, bl5)) | 0;
  5112. mid = (mid + Math.imul(al0, bh5)) | 0;
  5113. mid = (mid + Math.imul(ah0, bl5)) | 0;
  5114. hi = (hi + Math.imul(ah0, bh5)) | 0;
  5115. var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  5116. c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
  5117. w5 &= 0x3ffffff;
  5118. /* k = 6 */
  5119. lo = Math.imul(al6, bl0);
  5120. mid = Math.imul(al6, bh0);
  5121. mid = (mid + Math.imul(ah6, bl0)) | 0;
  5122. hi = Math.imul(ah6, bh0);
  5123. lo = (lo + Math.imul(al5, bl1)) | 0;
  5124. mid = (mid + Math.imul(al5, bh1)) | 0;
  5125. mid = (mid + Math.imul(ah5, bl1)) | 0;
  5126. hi = (hi + Math.imul(ah5, bh1)) | 0;
  5127. lo = (lo + Math.imul(al4, bl2)) | 0;
  5128. mid = (mid + Math.imul(al4, bh2)) | 0;
  5129. mid = (mid + Math.imul(ah4, bl2)) | 0;
  5130. hi = (hi + Math.imul(ah4, bh2)) | 0;
  5131. lo = (lo + Math.imul(al3, bl3)) | 0;
  5132. mid = (mid + Math.imul(al3, bh3)) | 0;
  5133. mid = (mid + Math.imul(ah3, bl3)) | 0;
  5134. hi = (hi + Math.imul(ah3, bh3)) | 0;
  5135. lo = (lo + Math.imul(al2, bl4)) | 0;
  5136. mid = (mid + Math.imul(al2, bh4)) | 0;
  5137. mid = (mid + Math.imul(ah2, bl4)) | 0;
  5138. hi = (hi + Math.imul(ah2, bh4)) | 0;
  5139. lo = (lo + Math.imul(al1, bl5)) | 0;
  5140. mid = (mid + Math.imul(al1, bh5)) | 0;
  5141. mid = (mid + Math.imul(ah1, bl5)) | 0;
  5142. hi = (hi + Math.imul(ah1, bh5)) | 0;
  5143. lo = (lo + Math.imul(al0, bl6)) | 0;
  5144. mid = (mid + Math.imul(al0, bh6)) | 0;
  5145. mid = (mid + Math.imul(ah0, bl6)) | 0;
  5146. hi = (hi + Math.imul(ah0, bh6)) | 0;
  5147. var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  5148. c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
  5149. w6 &= 0x3ffffff;
  5150. /* k = 7 */
  5151. lo = Math.imul(al7, bl0);
  5152. mid = Math.imul(al7, bh0);
  5153. mid = (mid + Math.imul(ah7, bl0)) | 0;
  5154. hi = Math.imul(ah7, bh0);
  5155. lo = (lo + Math.imul(al6, bl1)) | 0;
  5156. mid = (mid + Math.imul(al6, bh1)) | 0;
  5157. mid = (mid + Math.imul(ah6, bl1)) | 0;
  5158. hi = (hi + Math.imul(ah6, bh1)) | 0;
  5159. lo = (lo + Math.imul(al5, bl2)) | 0;
  5160. mid = (mid + Math.imul(al5, bh2)) | 0;
  5161. mid = (mid + Math.imul(ah5, bl2)) | 0;
  5162. hi = (hi + Math.imul(ah5, bh2)) | 0;
  5163. lo = (lo + Math.imul(al4, bl3)) | 0;
  5164. mid = (mid + Math.imul(al4, bh3)) | 0;
  5165. mid = (mid + Math.imul(ah4, bl3)) | 0;
  5166. hi = (hi + Math.imul(ah4, bh3)) | 0;
  5167. lo = (lo + Math.imul(al3, bl4)) | 0;
  5168. mid = (mid + Math.imul(al3, bh4)) | 0;
  5169. mid = (mid + Math.imul(ah3, bl4)) | 0;
  5170. hi = (hi + Math.imul(ah3, bh4)) | 0;
  5171. lo = (lo + Math.imul(al2, bl5)) | 0;
  5172. mid = (mid + Math.imul(al2, bh5)) | 0;
  5173. mid = (mid + Math.imul(ah2, bl5)) | 0;
  5174. hi = (hi + Math.imul(ah2, bh5)) | 0;
  5175. lo = (lo + Math.imul(al1, bl6)) | 0;
  5176. mid = (mid + Math.imul(al1, bh6)) | 0;
  5177. mid = (mid + Math.imul(ah1, bl6)) | 0;
  5178. hi = (hi + Math.imul(ah1, bh6)) | 0;
  5179. lo = (lo + Math.imul(al0, bl7)) | 0;
  5180. mid = (mid + Math.imul(al0, bh7)) | 0;
  5181. mid = (mid + Math.imul(ah0, bl7)) | 0;
  5182. hi = (hi + Math.imul(ah0, bh7)) | 0;
  5183. var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  5184. c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
  5185. w7 &= 0x3ffffff;
  5186. /* k = 8 */
  5187. lo = Math.imul(al8, bl0);
  5188. mid = Math.imul(al8, bh0);
  5189. mid = (mid + Math.imul(ah8, bl0)) | 0;
  5190. hi = Math.imul(ah8, bh0);
  5191. lo = (lo + Math.imul(al7, bl1)) | 0;
  5192. mid = (mid + Math.imul(al7, bh1)) | 0;
  5193. mid = (mid + Math.imul(ah7, bl1)) | 0;
  5194. hi = (hi + Math.imul(ah7, bh1)) | 0;
  5195. lo = (lo + Math.imul(al6, bl2)) | 0;
  5196. mid = (mid + Math.imul(al6, bh2)) | 0;
  5197. mid = (mid + Math.imul(ah6, bl2)) | 0;
  5198. hi = (hi + Math.imul(ah6, bh2)) | 0;
  5199. lo = (lo + Math.imul(al5, bl3)) | 0;
  5200. mid = (mid + Math.imul(al5, bh3)) | 0;
  5201. mid = (mid + Math.imul(ah5, bl3)) | 0;
  5202. hi = (hi + Math.imul(ah5, bh3)) | 0;
  5203. lo = (lo + Math.imul(al4, bl4)) | 0;
  5204. mid = (mid + Math.imul(al4, bh4)) | 0;
  5205. mid = (mid + Math.imul(ah4, bl4)) | 0;
  5206. hi = (hi + Math.imul(ah4, bh4)) | 0;
  5207. lo = (lo + Math.imul(al3, bl5)) | 0;
  5208. mid = (mid + Math.imul(al3, bh5)) | 0;
  5209. mid = (mid + Math.imul(ah3, bl5)) | 0;
  5210. hi = (hi + Math.imul(ah3, bh5)) | 0;
  5211. lo = (lo + Math.imul(al2, bl6)) | 0;
  5212. mid = (mid + Math.imul(al2, bh6)) | 0;
  5213. mid = (mid + Math.imul(ah2, bl6)) | 0;
  5214. hi = (hi + Math.imul(ah2, bh6)) | 0;
  5215. lo = (lo + Math.imul(al1, bl7)) | 0;
  5216. mid = (mid + Math.imul(al1, bh7)) | 0;
  5217. mid = (mid + Math.imul(ah1, bl7)) | 0;
  5218. hi = (hi + Math.imul(ah1, bh7)) | 0;
  5219. lo = (lo + Math.imul(al0, bl8)) | 0;
  5220. mid = (mid + Math.imul(al0, bh8)) | 0;
  5221. mid = (mid + Math.imul(ah0, bl8)) | 0;
  5222. hi = (hi + Math.imul(ah0, bh8)) | 0;
  5223. var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  5224. c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
  5225. w8 &= 0x3ffffff;
  5226. /* k = 9 */
  5227. lo = Math.imul(al9, bl0);
  5228. mid = Math.imul(al9, bh0);
  5229. mid = (mid + Math.imul(ah9, bl0)) | 0;
  5230. hi = Math.imul(ah9, bh0);
  5231. lo = (lo + Math.imul(al8, bl1)) | 0;
  5232. mid = (mid + Math.imul(al8, bh1)) | 0;
  5233. mid = (mid + Math.imul(ah8, bl1)) | 0;
  5234. hi = (hi + Math.imul(ah8, bh1)) | 0;
  5235. lo = (lo + Math.imul(al7, bl2)) | 0;
  5236. mid = (mid + Math.imul(al7, bh2)) | 0;
  5237. mid = (mid + Math.imul(ah7, bl2)) | 0;
  5238. hi = (hi + Math.imul(ah7, bh2)) | 0;
  5239. lo = (lo + Math.imul(al6, bl3)) | 0;
  5240. mid = (mid + Math.imul(al6, bh3)) | 0;
  5241. mid = (mid + Math.imul(ah6, bl3)) | 0;
  5242. hi = (hi + Math.imul(ah6, bh3)) | 0;
  5243. lo = (lo + Math.imul(al5, bl4)) | 0;
  5244. mid = (mid + Math.imul(al5, bh4)) | 0;
  5245. mid = (mid + Math.imul(ah5, bl4)) | 0;
  5246. hi = (hi + Math.imul(ah5, bh4)) | 0;
  5247. lo = (lo + Math.imul(al4, bl5)) | 0;
  5248. mid = (mid + Math.imul(al4, bh5)) | 0;
  5249. mid = (mid + Math.imul(ah4, bl5)) | 0;
  5250. hi = (hi + Math.imul(ah4, bh5)) | 0;
  5251. lo = (lo + Math.imul(al3, bl6)) | 0;
  5252. mid = (mid + Math.imul(al3, bh6)) | 0;
  5253. mid = (mid + Math.imul(ah3, bl6)) | 0;
  5254. hi = (hi + Math.imul(ah3, bh6)) | 0;
  5255. lo = (lo + Math.imul(al2, bl7)) | 0;
  5256. mid = (mid + Math.imul(al2, bh7)) | 0;
  5257. mid = (mid + Math.imul(ah2, bl7)) | 0;
  5258. hi = (hi + Math.imul(ah2, bh7)) | 0;
  5259. lo = (lo + Math.imul(al1, bl8)) | 0;
  5260. mid = (mid + Math.imul(al1, bh8)) | 0;
  5261. mid = (mid + Math.imul(ah1, bl8)) | 0;
  5262. hi = (hi + Math.imul(ah1, bh8)) | 0;
  5263. lo = (lo + Math.imul(al0, bl9)) | 0;
  5264. mid = (mid + Math.imul(al0, bh9)) | 0;
  5265. mid = (mid + Math.imul(ah0, bl9)) | 0;
  5266. hi = (hi + Math.imul(ah0, bh9)) | 0;
  5267. var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  5268. c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
  5269. w9 &= 0x3ffffff;
  5270. /* k = 10 */
  5271. lo = Math.imul(al9, bl1);
  5272. mid = Math.imul(al9, bh1);
  5273. mid = (mid + Math.imul(ah9, bl1)) | 0;
  5274. hi = Math.imul(ah9, bh1);
  5275. lo = (lo + Math.imul(al8, bl2)) | 0;
  5276. mid = (mid + Math.imul(al8, bh2)) | 0;
  5277. mid = (mid + Math.imul(ah8, bl2)) | 0;
  5278. hi = (hi + Math.imul(ah8, bh2)) | 0;
  5279. lo = (lo + Math.imul(al7, bl3)) | 0;
  5280. mid = (mid + Math.imul(al7, bh3)) | 0;
  5281. mid = (mid + Math.imul(ah7, bl3)) | 0;
  5282. hi = (hi + Math.imul(ah7, bh3)) | 0;
  5283. lo = (lo + Math.imul(al6, bl4)) | 0;
  5284. mid = (mid + Math.imul(al6, bh4)) | 0;
  5285. mid = (mid + Math.imul(ah6, bl4)) | 0;
  5286. hi = (hi + Math.imul(ah6, bh4)) | 0;
  5287. lo = (lo + Math.imul(al5, bl5)) | 0;
  5288. mid = (mid + Math.imul(al5, bh5)) | 0;
  5289. mid = (mid + Math.imul(ah5, bl5)) | 0;
  5290. hi = (hi + Math.imul(ah5, bh5)) | 0;
  5291. lo = (lo + Math.imul(al4, bl6)) | 0;
  5292. mid = (mid + Math.imul(al4, bh6)) | 0;
  5293. mid = (mid + Math.imul(ah4, bl6)) | 0;
  5294. hi = (hi + Math.imul(ah4, bh6)) | 0;
  5295. lo = (lo + Math.imul(al3, bl7)) | 0;
  5296. mid = (mid + Math.imul(al3, bh7)) | 0;
  5297. mid = (mid + Math.imul(ah3, bl7)) | 0;
  5298. hi = (hi + Math.imul(ah3, bh7)) | 0;
  5299. lo = (lo + Math.imul(al2, bl8)) | 0;
  5300. mid = (mid + Math.imul(al2, bh8)) | 0;
  5301. mid = (mid + Math.imul(ah2, bl8)) | 0;
  5302. hi = (hi + Math.imul(ah2, bh8)) | 0;
  5303. lo = (lo + Math.imul(al1, bl9)) | 0;
  5304. mid = (mid + Math.imul(al1, bh9)) | 0;
  5305. mid = (mid + Math.imul(ah1, bl9)) | 0;
  5306. hi = (hi + Math.imul(ah1, bh9)) | 0;
  5307. var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  5308. c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
  5309. w10 &= 0x3ffffff;
  5310. /* k = 11 */
  5311. lo = Math.imul(al9, bl2);
  5312. mid = Math.imul(al9, bh2);
  5313. mid = (mid + Math.imul(ah9, bl2)) | 0;
  5314. hi = Math.imul(ah9, bh2);
  5315. lo = (lo + Math.imul(al8, bl3)) | 0;
  5316. mid = (mid + Math.imul(al8, bh3)) | 0;
  5317. mid = (mid + Math.imul(ah8, bl3)) | 0;
  5318. hi = (hi + Math.imul(ah8, bh3)) | 0;
  5319. lo = (lo + Math.imul(al7, bl4)) | 0;
  5320. mid = (mid + Math.imul(al7, bh4)) | 0;
  5321. mid = (mid + Math.imul(ah7, bl4)) | 0;
  5322. hi = (hi + Math.imul(ah7, bh4)) | 0;
  5323. lo = (lo + Math.imul(al6, bl5)) | 0;
  5324. mid = (mid + Math.imul(al6, bh5)) | 0;
  5325. mid = (mid + Math.imul(ah6, bl5)) | 0;
  5326. hi = (hi + Math.imul(ah6, bh5)) | 0;
  5327. lo = (lo + Math.imul(al5, bl6)) | 0;
  5328. mid = (mid + Math.imul(al5, bh6)) | 0;
  5329. mid = (mid + Math.imul(ah5, bl6)) | 0;
  5330. hi = (hi + Math.imul(ah5, bh6)) | 0;
  5331. lo = (lo + Math.imul(al4, bl7)) | 0;
  5332. mid = (mid + Math.imul(al4, bh7)) | 0;
  5333. mid = (mid + Math.imul(ah4, bl7)) | 0;
  5334. hi = (hi + Math.imul(ah4, bh7)) | 0;
  5335. lo = (lo + Math.imul(al3, bl8)) | 0;
  5336. mid = (mid + Math.imul(al3, bh8)) | 0;
  5337. mid = (mid + Math.imul(ah3, bl8)) | 0;
  5338. hi = (hi + Math.imul(ah3, bh8)) | 0;
  5339. lo = (lo + Math.imul(al2, bl9)) | 0;
  5340. mid = (mid + Math.imul(al2, bh9)) | 0;
  5341. mid = (mid + Math.imul(ah2, bl9)) | 0;
  5342. hi = (hi + Math.imul(ah2, bh9)) | 0;
  5343. var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  5344. c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
  5345. w11 &= 0x3ffffff;
  5346. /* k = 12 */
  5347. lo = Math.imul(al9, bl3);
  5348. mid = Math.imul(al9, bh3);
  5349. mid = (mid + Math.imul(ah9, bl3)) | 0;
  5350. hi = Math.imul(ah9, bh3);
  5351. lo = (lo + Math.imul(al8, bl4)) | 0;
  5352. mid = (mid + Math.imul(al8, bh4)) | 0;
  5353. mid = (mid + Math.imul(ah8, bl4)) | 0;
  5354. hi = (hi + Math.imul(ah8, bh4)) | 0;
  5355. lo = (lo + Math.imul(al7, bl5)) | 0;
  5356. mid = (mid + Math.imul(al7, bh5)) | 0;
  5357. mid = (mid + Math.imul(ah7, bl5)) | 0;
  5358. hi = (hi + Math.imul(ah7, bh5)) | 0;
  5359. lo = (lo + Math.imul(al6, bl6)) | 0;
  5360. mid = (mid + Math.imul(al6, bh6)) | 0;
  5361. mid = (mid + Math.imul(ah6, bl6)) | 0;
  5362. hi = (hi + Math.imul(ah6, bh6)) | 0;
  5363. lo = (lo + Math.imul(al5, bl7)) | 0;
  5364. mid = (mid + Math.imul(al5, bh7)) | 0;
  5365. mid = (mid + Math.imul(ah5, bl7)) | 0;
  5366. hi = (hi + Math.imul(ah5, bh7)) | 0;
  5367. lo = (lo + Math.imul(al4, bl8)) | 0;
  5368. mid = (mid + Math.imul(al4, bh8)) | 0;
  5369. mid = (mid + Math.imul(ah4, bl8)) | 0;
  5370. hi = (hi + Math.imul(ah4, bh8)) | 0;
  5371. lo = (lo + Math.imul(al3, bl9)) | 0;
  5372. mid = (mid + Math.imul(al3, bh9)) | 0;
  5373. mid = (mid + Math.imul(ah3, bl9)) | 0;
  5374. hi = (hi + Math.imul(ah3, bh9)) | 0;
  5375. var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  5376. c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
  5377. w12 &= 0x3ffffff;
  5378. /* k = 13 */
  5379. lo = Math.imul(al9, bl4);
  5380. mid = Math.imul(al9, bh4);
  5381. mid = (mid + Math.imul(ah9, bl4)) | 0;
  5382. hi = Math.imul(ah9, bh4);
  5383. lo = (lo + Math.imul(al8, bl5)) | 0;
  5384. mid = (mid + Math.imul(al8, bh5)) | 0;
  5385. mid = (mid + Math.imul(ah8, bl5)) | 0;
  5386. hi = (hi + Math.imul(ah8, bh5)) | 0;
  5387. lo = (lo + Math.imul(al7, bl6)) | 0;
  5388. mid = (mid + Math.imul(al7, bh6)) | 0;
  5389. mid = (mid + Math.imul(ah7, bl6)) | 0;
  5390. hi = (hi + Math.imul(ah7, bh6)) | 0;
  5391. lo = (lo + Math.imul(al6, bl7)) | 0;
  5392. mid = (mid + Math.imul(al6, bh7)) | 0;
  5393. mid = (mid + Math.imul(ah6, bl7)) | 0;
  5394. hi = (hi + Math.imul(ah6, bh7)) | 0;
  5395. lo = (lo + Math.imul(al5, bl8)) | 0;
  5396. mid = (mid + Math.imul(al5, bh8)) | 0;
  5397. mid = (mid + Math.imul(ah5, bl8)) | 0;
  5398. hi = (hi + Math.imul(ah5, bh8)) | 0;
  5399. lo = (lo + Math.imul(al4, bl9)) | 0;
  5400. mid = (mid + Math.imul(al4, bh9)) | 0;
  5401. mid = (mid + Math.imul(ah4, bl9)) | 0;
  5402. hi = (hi + Math.imul(ah4, bh9)) | 0;
  5403. var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  5404. c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
  5405. w13 &= 0x3ffffff;
  5406. /* k = 14 */
  5407. lo = Math.imul(al9, bl5);
  5408. mid = Math.imul(al9, bh5);
  5409. mid = (mid + Math.imul(ah9, bl5)) | 0;
  5410. hi = Math.imul(ah9, bh5);
  5411. lo = (lo + Math.imul(al8, bl6)) | 0;
  5412. mid = (mid + Math.imul(al8, bh6)) | 0;
  5413. mid = (mid + Math.imul(ah8, bl6)) | 0;
  5414. hi = (hi + Math.imul(ah8, bh6)) | 0;
  5415. lo = (lo + Math.imul(al7, bl7)) | 0;
  5416. mid = (mid + Math.imul(al7, bh7)) | 0;
  5417. mid = (mid + Math.imul(ah7, bl7)) | 0;
  5418. hi = (hi + Math.imul(ah7, bh7)) | 0;
  5419. lo = (lo + Math.imul(al6, bl8)) | 0;
  5420. mid = (mid + Math.imul(al6, bh8)) | 0;
  5421. mid = (mid + Math.imul(ah6, bl8)) | 0;
  5422. hi = (hi + Math.imul(ah6, bh8)) | 0;
  5423. lo = (lo + Math.imul(al5, bl9)) | 0;
  5424. mid = (mid + Math.imul(al5, bh9)) | 0;
  5425. mid = (mid + Math.imul(ah5, bl9)) | 0;
  5426. hi = (hi + Math.imul(ah5, bh9)) | 0;
  5427. var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  5428. c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
  5429. w14 &= 0x3ffffff;
  5430. /* k = 15 */
  5431. lo = Math.imul(al9, bl6);
  5432. mid = Math.imul(al9, bh6);
  5433. mid = (mid + Math.imul(ah9, bl6)) | 0;
  5434. hi = Math.imul(ah9, bh6);
  5435. lo = (lo + Math.imul(al8, bl7)) | 0;
  5436. mid = (mid + Math.imul(al8, bh7)) | 0;
  5437. mid = (mid + Math.imul(ah8, bl7)) | 0;
  5438. hi = (hi + Math.imul(ah8, bh7)) | 0;
  5439. lo = (lo + Math.imul(al7, bl8)) | 0;
  5440. mid = (mid + Math.imul(al7, bh8)) | 0;
  5441. mid = (mid + Math.imul(ah7, bl8)) | 0;
  5442. hi = (hi + Math.imul(ah7, bh8)) | 0;
  5443. lo = (lo + Math.imul(al6, bl9)) | 0;
  5444. mid = (mid + Math.imul(al6, bh9)) | 0;
  5445. mid = (mid + Math.imul(ah6, bl9)) | 0;
  5446. hi = (hi + Math.imul(ah6, bh9)) | 0;
  5447. var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  5448. c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
  5449. w15 &= 0x3ffffff;
  5450. /* k = 16 */
  5451. lo = Math.imul(al9, bl7);
  5452. mid = Math.imul(al9, bh7);
  5453. mid = (mid + Math.imul(ah9, bl7)) | 0;
  5454. hi = Math.imul(ah9, bh7);
  5455. lo = (lo + Math.imul(al8, bl8)) | 0;
  5456. mid = (mid + Math.imul(al8, bh8)) | 0;
  5457. mid = (mid + Math.imul(ah8, bl8)) | 0;
  5458. hi = (hi + Math.imul(ah8, bh8)) | 0;
  5459. lo = (lo + Math.imul(al7, bl9)) | 0;
  5460. mid = (mid + Math.imul(al7, bh9)) | 0;
  5461. mid = (mid + Math.imul(ah7, bl9)) | 0;
  5462. hi = (hi + Math.imul(ah7, bh9)) | 0;
  5463. var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  5464. c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
  5465. w16 &= 0x3ffffff;
  5466. /* k = 17 */
  5467. lo = Math.imul(al9, bl8);
  5468. mid = Math.imul(al9, bh8);
  5469. mid = (mid + Math.imul(ah9, bl8)) | 0;
  5470. hi = Math.imul(ah9, bh8);
  5471. lo = (lo + Math.imul(al8, bl9)) | 0;
  5472. mid = (mid + Math.imul(al8, bh9)) | 0;
  5473. mid = (mid + Math.imul(ah8, bl9)) | 0;
  5474. hi = (hi + Math.imul(ah8, bh9)) | 0;
  5475. var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  5476. c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
  5477. w17 &= 0x3ffffff;
  5478. /* k = 18 */
  5479. lo = Math.imul(al9, bl9);
  5480. mid = Math.imul(al9, bh9);
  5481. mid = (mid + Math.imul(ah9, bl9)) | 0;
  5482. hi = Math.imul(ah9, bh9);
  5483. var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
  5484. c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
  5485. w18 &= 0x3ffffff;
  5486. o[0] = w0;
  5487. o[1] = w1;
  5488. o[2] = w2;
  5489. o[3] = w3;
  5490. o[4] = w4;
  5491. o[5] = w5;
  5492. o[6] = w6;
  5493. o[7] = w7;
  5494. o[8] = w8;
  5495. o[9] = w9;
  5496. o[10] = w10;
  5497. o[11] = w11;
  5498. o[12] = w12;
  5499. o[13] = w13;
  5500. o[14] = w14;
  5501. o[15] = w15;
  5502. o[16] = w16;
  5503. o[17] = w17;
  5504. o[18] = w18;
  5505. if (c !== 0) {
  5506. o[19] = c;
  5507. out.length++;
  5508. }
  5509. return out;
  5510. };
  5511. // Polyfill comb
  5512. if (!Math.imul) {
  5513. comb10MulTo = smallMulTo;
  5514. }
  5515. function bigMulTo (self, num, out) {
  5516. out.negative = num.negative ^ self.negative;
  5517. out.length = self.length + num.length;
  5518. var carry = 0;
  5519. var hncarry = 0;
  5520. for (var k = 0; k < out.length - 1; k++) {
  5521. // Sum all words with the same `i + j = k` and accumulate `ncarry`,
  5522. // note that ncarry could be >= 0x3ffffff
  5523. var ncarry = hncarry;
  5524. hncarry = 0;
  5525. var rword = carry & 0x3ffffff;
  5526. var maxJ = Math.min(k, num.length - 1);
  5527. for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
  5528. var i = k - j;
  5529. var a = self.words[i] | 0;
  5530. var b = num.words[j] | 0;
  5531. var r = a * b;
  5532. var lo = r & 0x3ffffff;
  5533. ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
  5534. lo = (lo + rword) | 0;
  5535. rword = lo & 0x3ffffff;
  5536. ncarry = (ncarry + (lo >>> 26)) | 0;
  5537. hncarry += ncarry >>> 26;
  5538. ncarry &= 0x3ffffff;
  5539. }
  5540. out.words[k] = rword;
  5541. carry = ncarry;
  5542. ncarry = hncarry;
  5543. }
  5544. if (carry !== 0) {
  5545. out.words[k] = carry;
  5546. } else {
  5547. out.length--;
  5548. }
  5549. return out.strip();
  5550. }
  5551. function jumboMulTo (self, num, out) {
  5552. var fftm = new FFTM();
  5553. return fftm.mulp(self, num, out);
  5554. }
  5555. BN.prototype.mulTo = function mulTo (num, out) {
  5556. var res;
  5557. var len = this.length + num.length;
  5558. if (this.length === 10 && num.length === 10) {
  5559. res = comb10MulTo(this, num, out);
  5560. } else if (len < 63) {
  5561. res = smallMulTo(this, num, out);
  5562. } else if (len < 1024) {
  5563. res = bigMulTo(this, num, out);
  5564. } else {
  5565. res = jumboMulTo(this, num, out);
  5566. }
  5567. return res;
  5568. };
  5569. // Cooley-Tukey algorithm for FFT
  5570. // slightly revisited to rely on looping instead of recursion
  5571. function FFTM (x, y) {
  5572. this.x = x;
  5573. this.y = y;
  5574. }
  5575. FFTM.prototype.makeRBT = function makeRBT (N) {
  5576. var t = new Array(N);
  5577. var l = BN.prototype._countBits(N) - 1;
  5578. for (var i = 0; i < N; i++) {
  5579. t[i] = this.revBin(i, l, N);
  5580. }
  5581. return t;
  5582. };
  5583. // Returns binary-reversed representation of `x`
  5584. FFTM.prototype.revBin = function revBin (x, l, N) {
  5585. if (x === 0 || x === N - 1) return x;
  5586. var rb = 0;
  5587. for (var i = 0; i < l; i++) {
  5588. rb |= (x & 1) << (l - i - 1);
  5589. x >>= 1;
  5590. }
  5591. return rb;
  5592. };
  5593. // Performs "tweedling" phase, therefore 'emulating'
  5594. // behaviour of the recursive algorithm
  5595. FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
  5596. for (var i = 0; i < N; i++) {
  5597. rtws[i] = rws[rbt[i]];
  5598. itws[i] = iws[rbt[i]];
  5599. }
  5600. };
  5601. FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
  5602. this.permute(rbt, rws, iws, rtws, itws, N);
  5603. for (var s = 1; s < N; s <<= 1) {
  5604. var l = s << 1;
  5605. var rtwdf = Math.cos(2 * Math.PI / l);
  5606. var itwdf = Math.sin(2 * Math.PI / l);
  5607. for (var p = 0; p < N; p += l) {
  5608. var rtwdf_ = rtwdf;
  5609. var itwdf_ = itwdf;
  5610. for (var j = 0; j < s; j++) {
  5611. var re = rtws[p + j];
  5612. var ie = itws[p + j];
  5613. var ro = rtws[p + j + s];
  5614. var io = itws[p + j + s];
  5615. var rx = rtwdf_ * ro - itwdf_ * io;
  5616. io = rtwdf_ * io + itwdf_ * ro;
  5617. ro = rx;
  5618. rtws[p + j] = re + ro;
  5619. itws[p + j] = ie + io;
  5620. rtws[p + j + s] = re - ro;
  5621. itws[p + j + s] = ie - io;
  5622. /* jshint maxdepth : false */
  5623. if (j !== l) {
  5624. rx = rtwdf * rtwdf_ - itwdf * itwdf_;
  5625. itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
  5626. rtwdf_ = rx;
  5627. }
  5628. }
  5629. }
  5630. }
  5631. };
  5632. FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
  5633. var N = Math.max(m, n) | 1;
  5634. var odd = N & 1;
  5635. var i = 0;
  5636. for (N = N / 2 | 0; N; N = N >>> 1) {
  5637. i++;
  5638. }
  5639. return 1 << i + 1 + odd;
  5640. };
  5641. FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
  5642. if (N <= 1) return;
  5643. for (var i = 0; i < N / 2; i++) {
  5644. var t = rws[i];
  5645. rws[i] = rws[N - i - 1];
  5646. rws[N - i - 1] = t;
  5647. t = iws[i];
  5648. iws[i] = -iws[N - i - 1];
  5649. iws[N - i - 1] = -t;
  5650. }
  5651. };
  5652. FFTM.prototype.normalize13b = function normalize13b (ws, N) {
  5653. var carry = 0;
  5654. for (var i = 0; i < N / 2; i++) {
  5655. var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
  5656. Math.round(ws[2 * i] / N) +
  5657. carry;
  5658. ws[i] = w & 0x3ffffff;
  5659. if (w < 0x4000000) {
  5660. carry = 0;
  5661. } else {
  5662. carry = w / 0x4000000 | 0;
  5663. }
  5664. }
  5665. return ws;
  5666. };
  5667. FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
  5668. var carry = 0;
  5669. for (var i = 0; i < len; i++) {
  5670. carry = carry + (ws[i] | 0);
  5671. rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
  5672. rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
  5673. }
  5674. // Pad with zeroes
  5675. for (i = 2 * len; i < N; ++i) {
  5676. rws[i] = 0;
  5677. }
  5678. assert(carry === 0);
  5679. assert((carry & ~0x1fff) === 0);
  5680. };
  5681. FFTM.prototype.stub = function stub (N) {
  5682. var ph = new Array(N);
  5683. for (var i = 0; i < N; i++) {
  5684. ph[i] = 0;
  5685. }
  5686. return ph;
  5687. };
  5688. FFTM.prototype.mulp = function mulp (x, y, out) {
  5689. var N = 2 * this.guessLen13b(x.length, y.length);
  5690. var rbt = this.makeRBT(N);
  5691. var _ = this.stub(N);
  5692. var rws = new Array(N);
  5693. var rwst = new Array(N);
  5694. var iwst = new Array(N);
  5695. var nrws = new Array(N);
  5696. var nrwst = new Array(N);
  5697. var niwst = new Array(N);
  5698. var rmws = out.words;
  5699. rmws.length = N;
  5700. this.convert13b(x.words, x.length, rws, N);
  5701. this.convert13b(y.words, y.length, nrws, N);
  5702. this.transform(rws, _, rwst, iwst, N, rbt);
  5703. this.transform(nrws, _, nrwst, niwst, N, rbt);
  5704. for (var i = 0; i < N; i++) {
  5705. var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
  5706. iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
  5707. rwst[i] = rx;
  5708. }
  5709. this.conjugate(rwst, iwst, N);
  5710. this.transform(rwst, iwst, rmws, _, N, rbt);
  5711. this.conjugate(rmws, _, N);
  5712. this.normalize13b(rmws, N);
  5713. out.negative = x.negative ^ y.negative;
  5714. out.length = x.length + y.length;
  5715. return out.strip();
  5716. };
  5717. // Multiply `this` by `num`
  5718. BN.prototype.mul = function mul (num) {
  5719. var out = new BN(null);
  5720. out.words = new Array(this.length + num.length);
  5721. return this.mulTo(num, out);
  5722. };
  5723. // Multiply employing FFT
  5724. BN.prototype.mulf = function mulf (num) {
  5725. var out = new BN(null);
  5726. out.words = new Array(this.length + num.length);
  5727. return jumboMulTo(this, num, out);
  5728. };
  5729. // In-place Multiplication
  5730. BN.prototype.imul = function imul (num) {
  5731. return this.clone().mulTo(num, this);
  5732. };
  5733. BN.prototype.imuln = function imuln (num) {
  5734. assert(typeof num === 'number');
  5735. assert(num < 0x4000000);
  5736. // Carry
  5737. var carry = 0;
  5738. for (var i = 0; i < this.length; i++) {
  5739. var w = (this.words[i] | 0) * num;
  5740. var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
  5741. carry >>= 26;
  5742. carry += (w / 0x4000000) | 0;
  5743. // NOTE: lo is 27bit maximum
  5744. carry += lo >>> 26;
  5745. this.words[i] = lo & 0x3ffffff;
  5746. }
  5747. if (carry !== 0) {
  5748. this.words[i] = carry;
  5749. this.length++;
  5750. }
  5751. return this;
  5752. };
  5753. BN.prototype.muln = function muln (num) {
  5754. return this.clone().imuln(num);
  5755. };
  5756. // `this` * `this`
  5757. BN.prototype.sqr = function sqr () {
  5758. return this.mul(this);
  5759. };
  5760. // `this` * `this` in-place
  5761. BN.prototype.isqr = function isqr () {
  5762. return this.imul(this.clone());
  5763. };
  5764. // Math.pow(`this`, `num`)
  5765. BN.prototype.pow = function pow (num) {
  5766. var w = toBitArray(num);
  5767. if (w.length === 0) return new BN(1);
  5768. // Skip leading zeroes
  5769. var res = this;
  5770. for (var i = 0; i < w.length; i++, res = res.sqr()) {
  5771. if (w[i] !== 0) break;
  5772. }
  5773. if (++i < w.length) {
  5774. for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
  5775. if (w[i] === 0) continue;
  5776. res = res.mul(q);
  5777. }
  5778. }
  5779. return res;
  5780. };
  5781. // Shift-left in-place
  5782. BN.prototype.iushln = function iushln (bits) {
  5783. assert(typeof bits === 'number' && bits >= 0);
  5784. var r = bits % 26;
  5785. var s = (bits - r) / 26;
  5786. var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
  5787. var i;
  5788. if (r !== 0) {
  5789. var carry = 0;
  5790. for (i = 0; i < this.length; i++) {
  5791. var newCarry = this.words[i] & carryMask;
  5792. var c = ((this.words[i] | 0) - newCarry) << r;
  5793. this.words[i] = c | carry;
  5794. carry = newCarry >>> (26 - r);
  5795. }
  5796. if (carry) {
  5797. this.words[i] = carry;
  5798. this.length++;
  5799. }
  5800. }
  5801. if (s !== 0) {
  5802. for (i = this.length - 1; i >= 0; i--) {
  5803. this.words[i + s] = this.words[i];
  5804. }
  5805. for (i = 0; i < s; i++) {
  5806. this.words[i] = 0;
  5807. }
  5808. this.length += s;
  5809. }
  5810. return this.strip();
  5811. };
  5812. BN.prototype.ishln = function ishln (bits) {
  5813. // TODO(indutny): implement me
  5814. assert(this.negative === 0);
  5815. return this.iushln(bits);
  5816. };
  5817. // Shift-right in-place
  5818. // NOTE: `hint` is a lowest bit before trailing zeroes
  5819. // NOTE: if `extended` is present - it will be filled with destroyed bits
  5820. BN.prototype.iushrn = function iushrn (bits, hint, extended) {
  5821. assert(typeof bits === 'number' && bits >= 0);
  5822. var h;
  5823. if (hint) {
  5824. h = (hint - (hint % 26)) / 26;
  5825. } else {
  5826. h = 0;
  5827. }
  5828. var r = bits % 26;
  5829. var s = Math.min((bits - r) / 26, this.length);
  5830. var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
  5831. var maskedWords = extended;
  5832. h -= s;
  5833. h = Math.max(0, h);
  5834. // Extended mode, copy masked part
  5835. if (maskedWords) {
  5836. for (var i = 0; i < s; i++) {
  5837. maskedWords.words[i] = this.words[i];
  5838. }
  5839. maskedWords.length = s;
  5840. }
  5841. if (s === 0) {
  5842. // No-op, we should not move anything at all
  5843. } else if (this.length > s) {
  5844. this.length -= s;
  5845. for (i = 0; i < this.length; i++) {
  5846. this.words[i] = this.words[i + s];
  5847. }
  5848. } else {
  5849. this.words[0] = 0;
  5850. this.length = 1;
  5851. }
  5852. var carry = 0;
  5853. for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
  5854. var word = this.words[i] | 0;
  5855. this.words[i] = (carry << (26 - r)) | (word >>> r);
  5856. carry = word & mask;
  5857. }
  5858. // Push carried bits as a mask
  5859. if (maskedWords && carry !== 0) {
  5860. maskedWords.words[maskedWords.length++] = carry;
  5861. }
  5862. if (this.length === 0) {
  5863. this.words[0] = 0;
  5864. this.length = 1;
  5865. }
  5866. return this.strip();
  5867. };
  5868. BN.prototype.ishrn = function ishrn (bits, hint, extended) {
  5869. // TODO(indutny): implement me
  5870. assert(this.negative === 0);
  5871. return this.iushrn(bits, hint, extended);
  5872. };
  5873. // Shift-left
  5874. BN.prototype.shln = function shln (bits) {
  5875. return this.clone().ishln(bits);
  5876. };
  5877. BN.prototype.ushln = function ushln (bits) {
  5878. return this.clone().iushln(bits);
  5879. };
  5880. // Shift-right
  5881. BN.prototype.shrn = function shrn (bits) {
  5882. return this.clone().ishrn(bits);
  5883. };
  5884. BN.prototype.ushrn = function ushrn (bits) {
  5885. return this.clone().iushrn(bits);
  5886. };
  5887. // Test if n bit is set
  5888. BN.prototype.testn = function testn (bit) {
  5889. assert(typeof bit === 'number' && bit >= 0);
  5890. var r = bit % 26;
  5891. var s = (bit - r) / 26;
  5892. var q = 1 << r;
  5893. // Fast case: bit is much higher than all existing words
  5894. if (this.length <= s) return false;
  5895. // Check bit and return
  5896. var w = this.words[s];
  5897. return !!(w & q);
  5898. };
  5899. // Return only lowers bits of number (in-place)
  5900. BN.prototype.imaskn = function imaskn (bits) {
  5901. assert(typeof bits === 'number' && bits >= 0);
  5902. var r = bits % 26;
  5903. var s = (bits - r) / 26;
  5904. assert(this.negative === 0, 'imaskn works only with positive numbers');
  5905. if (this.length <= s) {
  5906. return this;
  5907. }
  5908. if (r !== 0) {
  5909. s++;
  5910. }
  5911. this.length = Math.min(s, this.length);
  5912. if (r !== 0) {
  5913. var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
  5914. this.words[this.length - 1] &= mask;
  5915. }
  5916. return this.strip();
  5917. };
  5918. // Return only lowers bits of number
  5919. BN.prototype.maskn = function maskn (bits) {
  5920. return this.clone().imaskn(bits);
  5921. };
  5922. // Add plain number `num` to `this`
  5923. BN.prototype.iaddn = function iaddn (num) {
  5924. assert(typeof num === 'number');
  5925. assert(num < 0x4000000);
  5926. if (num < 0) return this.isubn(-num);
  5927. // Possible sign change
  5928. if (this.negative !== 0) {
  5929. if (this.length === 1 && (this.words[0] | 0) < num) {
  5930. this.words[0] = num - (this.words[0] | 0);
  5931. this.negative = 0;
  5932. return this;
  5933. }
  5934. this.negative = 0;
  5935. this.isubn(num);
  5936. this.negative = 1;
  5937. return this;
  5938. }
  5939. // Add without checks
  5940. return this._iaddn(num);
  5941. };
  5942. BN.prototype._iaddn = function _iaddn (num) {
  5943. this.words[0] += num;
  5944. // Carry
  5945. for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
  5946. this.words[i] -= 0x4000000;
  5947. if (i === this.length - 1) {
  5948. this.words[i + 1] = 1;
  5949. } else {
  5950. this.words[i + 1]++;
  5951. }
  5952. }
  5953. this.length = Math.max(this.length, i + 1);
  5954. return this;
  5955. };
  5956. // Subtract plain number `num` from `this`
  5957. BN.prototype.isubn = function isubn (num) {
  5958. assert(typeof num === 'number');
  5959. assert(num < 0x4000000);
  5960. if (num < 0) return this.iaddn(-num);
  5961. if (this.negative !== 0) {
  5962. this.negative = 0;
  5963. this.iaddn(num);
  5964. this.negative = 1;
  5965. return this;
  5966. }
  5967. this.words[0] -= num;
  5968. if (this.length === 1 && this.words[0] < 0) {
  5969. this.words[0] = -this.words[0];
  5970. this.negative = 1;
  5971. } else {
  5972. // Carry
  5973. for (var i = 0; i < this.length && this.words[i] < 0; i++) {
  5974. this.words[i] += 0x4000000;
  5975. this.words[i + 1] -= 1;
  5976. }
  5977. }
  5978. return this.strip();
  5979. };
  5980. BN.prototype.addn = function addn (num) {
  5981. return this.clone().iaddn(num);
  5982. };
  5983. BN.prototype.subn = function subn (num) {
  5984. return this.clone().isubn(num);
  5985. };
  5986. BN.prototype.iabs = function iabs () {
  5987. this.negative = 0;
  5988. return this;
  5989. };
  5990. BN.prototype.abs = function abs () {
  5991. return this.clone().iabs();
  5992. };
  5993. BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
  5994. var len = num.length + shift;
  5995. var i;
  5996. this._expand(len);
  5997. var w;
  5998. var carry = 0;
  5999. for (i = 0; i < num.length; i++) {
  6000. w = (this.words[i + shift] | 0) + carry;
  6001. var right = (num.words[i] | 0) * mul;
  6002. w -= right & 0x3ffffff;
  6003. carry = (w >> 26) - ((right / 0x4000000) | 0);
  6004. this.words[i + shift] = w & 0x3ffffff;
  6005. }
  6006. for (; i < this.length - shift; i++) {
  6007. w = (this.words[i + shift] | 0) + carry;
  6008. carry = w >> 26;
  6009. this.words[i + shift] = w & 0x3ffffff;
  6010. }
  6011. if (carry === 0) return this.strip();
  6012. // Subtraction overflow
  6013. assert(carry === -1);
  6014. carry = 0;
  6015. for (i = 0; i < this.length; i++) {
  6016. w = -(this.words[i] | 0) + carry;
  6017. carry = w >> 26;
  6018. this.words[i] = w & 0x3ffffff;
  6019. }
  6020. this.negative = 1;
  6021. return this.strip();
  6022. };
  6023. BN.prototype._wordDiv = function _wordDiv (num, mode) {
  6024. var shift = this.length - num.length;
  6025. var a = this.clone();
  6026. var b = num;
  6027. // Normalize
  6028. var bhi = b.words[b.length - 1] | 0;
  6029. var bhiBits = this._countBits(bhi);
  6030. shift = 26 - bhiBits;
  6031. if (shift !== 0) {
  6032. b = b.ushln(shift);
  6033. a.iushln(shift);
  6034. bhi = b.words[b.length - 1] | 0;
  6035. }
  6036. // Initialize quotient
  6037. var m = a.length - b.length;
  6038. var q;
  6039. if (mode !== 'mod') {
  6040. q = new BN(null);
  6041. q.length = m + 1;
  6042. q.words = new Array(q.length);
  6043. for (var i = 0; i < q.length; i++) {
  6044. q.words[i] = 0;
  6045. }
  6046. }
  6047. var diff = a.clone()._ishlnsubmul(b, 1, m);
  6048. if (diff.negative === 0) {
  6049. a = diff;
  6050. if (q) {
  6051. q.words[m] = 1;
  6052. }
  6053. }
  6054. for (var j = m - 1; j >= 0; j--) {
  6055. var qj = (a.words[b.length + j] | 0) * 0x4000000 +
  6056. (a.words[b.length + j - 1] | 0);
  6057. // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
  6058. // (0x7ffffff)
  6059. qj = Math.min((qj / bhi) | 0, 0x3ffffff);
  6060. a._ishlnsubmul(b, qj, j);
  6061. while (a.negative !== 0) {
  6062. qj--;
  6063. a.negative = 0;
  6064. a._ishlnsubmul(b, 1, j);
  6065. if (!a.isZero()) {
  6066. a.negative ^= 1;
  6067. }
  6068. }
  6069. if (q) {
  6070. q.words[j] = qj;
  6071. }
  6072. }
  6073. if (q) {
  6074. q.strip();
  6075. }
  6076. a.strip();
  6077. // Denormalize
  6078. if (mode !== 'div' && shift !== 0) {
  6079. a.iushrn(shift);
  6080. }
  6081. return {
  6082. div: q || null,
  6083. mod: a
  6084. };
  6085. };
  6086. // NOTE: 1) `mode` can be set to `mod` to request mod only,
  6087. // to `div` to request div only, or be absent to
  6088. // request both div & mod
  6089. // 2) `positive` is true if unsigned mod is requested
  6090. BN.prototype.divmod = function divmod (num, mode, positive) {
  6091. assert(!num.isZero());
  6092. if (this.isZero()) {
  6093. return {
  6094. div: new BN(0),
  6095. mod: new BN(0)
  6096. };
  6097. }
  6098. var div, mod, res;
  6099. if (this.negative !== 0 && num.negative === 0) {
  6100. res = this.neg().divmod(num, mode);
  6101. if (mode !== 'mod') {
  6102. div = res.div.neg();
  6103. }
  6104. if (mode !== 'div') {
  6105. mod = res.mod.neg();
  6106. if (positive && mod.negative !== 0) {
  6107. mod.iadd(num);
  6108. }
  6109. }
  6110. return {
  6111. div: div,
  6112. mod: mod
  6113. };
  6114. }
  6115. if (this.negative === 0 && num.negative !== 0) {
  6116. res = this.divmod(num.neg(), mode);
  6117. if (mode !== 'mod') {
  6118. div = res.div.neg();
  6119. }
  6120. return {
  6121. div: div,
  6122. mod: res.mod
  6123. };
  6124. }
  6125. if ((this.negative & num.negative) !== 0) {
  6126. res = this.neg().divmod(num.neg(), mode);
  6127. if (mode !== 'div') {
  6128. mod = res.mod.neg();
  6129. if (positive && mod.negative !== 0) {
  6130. mod.isub(num);
  6131. }
  6132. }
  6133. return {
  6134. div: res.div,
  6135. mod: mod
  6136. };
  6137. }
  6138. // Both numbers are positive at this point
  6139. // Strip both numbers to approximate shift value
  6140. if (num.length > this.length || this.cmp(num) < 0) {
  6141. return {
  6142. div: new BN(0),
  6143. mod: this
  6144. };
  6145. }
  6146. // Very short reduction
  6147. if (num.length === 1) {
  6148. if (mode === 'div') {
  6149. return {
  6150. div: this.divn(num.words[0]),
  6151. mod: null
  6152. };
  6153. }
  6154. if (mode === 'mod') {
  6155. return {
  6156. div: null,
  6157. mod: new BN(this.modn(num.words[0]))
  6158. };
  6159. }
  6160. return {
  6161. div: this.divn(num.words[0]),
  6162. mod: new BN(this.modn(num.words[0]))
  6163. };
  6164. }
  6165. return this._wordDiv(num, mode);
  6166. };
  6167. // Find `this` / `num`
  6168. BN.prototype.div = function div (num) {
  6169. return this.divmod(num, 'div', false).div;
  6170. };
  6171. // Find `this` % `num`
  6172. BN.prototype.mod = function mod (num) {
  6173. return this.divmod(num, 'mod', false).mod;
  6174. };
  6175. BN.prototype.umod = function umod (num) {
  6176. return this.divmod(num, 'mod', true).mod;
  6177. };
  6178. // Find Round(`this` / `num`)
  6179. BN.prototype.divRound = function divRound (num) {
  6180. var dm = this.divmod(num);
  6181. // Fast case - exact division
  6182. if (dm.mod.isZero()) return dm.div;
  6183. var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
  6184. var half = num.ushrn(1);
  6185. var r2 = num.andln(1);
  6186. var cmp = mod.cmp(half);
  6187. // Round down
  6188. if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
  6189. // Round up
  6190. return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
  6191. };
  6192. BN.prototype.modn = function modn (num) {
  6193. assert(num <= 0x3ffffff);
  6194. var p = (1 << 26) % num;
  6195. var acc = 0;
  6196. for (var i = this.length - 1; i >= 0; i--) {
  6197. acc = (p * acc + (this.words[i] | 0)) % num;
  6198. }
  6199. return acc;
  6200. };
  6201. // In-place division by number
  6202. BN.prototype.idivn = function idivn (num) {
  6203. assert(num <= 0x3ffffff);
  6204. var carry = 0;
  6205. for (var i = this.length - 1; i >= 0; i--) {
  6206. var w = (this.words[i] | 0) + carry * 0x4000000;
  6207. this.words[i] = (w / num) | 0;
  6208. carry = w % num;
  6209. }
  6210. return this.strip();
  6211. };
  6212. BN.prototype.divn = function divn (num) {
  6213. return this.clone().idivn(num);
  6214. };
  6215. BN.prototype.egcd = function egcd (p) {
  6216. assert(p.negative === 0);
  6217. assert(!p.isZero());
  6218. var x = this;
  6219. var y = p.clone();
  6220. if (x.negative !== 0) {
  6221. x = x.umod(p);
  6222. } else {
  6223. x = x.clone();
  6224. }
  6225. // A * x + B * y = x
  6226. var A = new BN(1);
  6227. var B = new BN(0);
  6228. // C * x + D * y = y
  6229. var C = new BN(0);
  6230. var D = new BN(1);
  6231. var g = 0;
  6232. while (x.isEven() && y.isEven()) {
  6233. x.iushrn(1);
  6234. y.iushrn(1);
  6235. ++g;
  6236. }
  6237. var yp = y.clone();
  6238. var xp = x.clone();
  6239. while (!x.isZero()) {
  6240. for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
  6241. if (i > 0) {
  6242. x.iushrn(i);
  6243. while (i-- > 0) {
  6244. if (A.isOdd() || B.isOdd()) {
  6245. A.iadd(yp);
  6246. B.isub(xp);
  6247. }
  6248. A.iushrn(1);
  6249. B.iushrn(1);
  6250. }
  6251. }
  6252. for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
  6253. if (j > 0) {
  6254. y.iushrn(j);
  6255. while (j-- > 0) {
  6256. if (C.isOdd() || D.isOdd()) {
  6257. C.iadd(yp);
  6258. D.isub(xp);
  6259. }
  6260. C.iushrn(1);
  6261. D.iushrn(1);
  6262. }
  6263. }
  6264. if (x.cmp(y) >= 0) {
  6265. x.isub(y);
  6266. A.isub(C);
  6267. B.isub(D);
  6268. } else {
  6269. y.isub(x);
  6270. C.isub(A);
  6271. D.isub(B);
  6272. }
  6273. }
  6274. return {
  6275. a: C,
  6276. b: D,
  6277. gcd: y.iushln(g)
  6278. };
  6279. };
  6280. // This is reduced incarnation of the binary EEA
  6281. // above, designated to invert members of the
  6282. // _prime_ fields F(p) at a maximal speed
  6283. BN.prototype._invmp = function _invmp (p) {
  6284. assert(p.negative === 0);
  6285. assert(!p.isZero());
  6286. var a = this;
  6287. var b = p.clone();
  6288. if (a.negative !== 0) {
  6289. a = a.umod(p);
  6290. } else {
  6291. a = a.clone();
  6292. }
  6293. var x1 = new BN(1);
  6294. var x2 = new BN(0);
  6295. var delta = b.clone();
  6296. while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
  6297. for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
  6298. if (i > 0) {
  6299. a.iushrn(i);
  6300. while (i-- > 0) {
  6301. if (x1.isOdd()) {
  6302. x1.iadd(delta);
  6303. }
  6304. x1.iushrn(1);
  6305. }
  6306. }
  6307. for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
  6308. if (j > 0) {
  6309. b.iushrn(j);
  6310. while (j-- > 0) {
  6311. if (x2.isOdd()) {
  6312. x2.iadd(delta);
  6313. }
  6314. x2.iushrn(1);
  6315. }
  6316. }
  6317. if (a.cmp(b) >= 0) {
  6318. a.isub(b);
  6319. x1.isub(x2);
  6320. } else {
  6321. b.isub(a);
  6322. x2.isub(x1);
  6323. }
  6324. }
  6325. var res;
  6326. if (a.cmpn(1) === 0) {
  6327. res = x1;
  6328. } else {
  6329. res = x2;
  6330. }
  6331. if (res.cmpn(0) < 0) {
  6332. res.iadd(p);
  6333. }
  6334. return res;
  6335. };
  6336. BN.prototype.gcd = function gcd (num) {
  6337. if (this.isZero()) return num.abs();
  6338. if (num.isZero()) return this.abs();
  6339. var a = this.clone();
  6340. var b = num.clone();
  6341. a.negative = 0;
  6342. b.negative = 0;
  6343. // Remove common factor of two
  6344. for (var shift = 0; a.isEven() && b.isEven(); shift++) {
  6345. a.iushrn(1);
  6346. b.iushrn(1);
  6347. }
  6348. do {
  6349. while (a.isEven()) {
  6350. a.iushrn(1);
  6351. }
  6352. while (b.isEven()) {
  6353. b.iushrn(1);
  6354. }
  6355. var r = a.cmp(b);
  6356. if (r < 0) {
  6357. // Swap `a` and `b` to make `a` always bigger than `b`
  6358. var t = a;
  6359. a = b;
  6360. b = t;
  6361. } else if (r === 0 || b.cmpn(1) === 0) {
  6362. break;
  6363. }
  6364. a.isub(b);
  6365. } while (true);
  6366. return b.iushln(shift);
  6367. };
  6368. // Invert number in the field F(num)
  6369. BN.prototype.invm = function invm (num) {
  6370. return this.egcd(num).a.umod(num);
  6371. };
  6372. BN.prototype.isEven = function isEven () {
  6373. return (this.words[0] & 1) === 0;
  6374. };
  6375. BN.prototype.isOdd = function isOdd () {
  6376. return (this.words[0] & 1) === 1;
  6377. };
  6378. // And first word and num
  6379. BN.prototype.andln = function andln (num) {
  6380. return this.words[0] & num;
  6381. };
  6382. // Increment at the bit position in-line
  6383. BN.prototype.bincn = function bincn (bit) {
  6384. assert(typeof bit === 'number');
  6385. var r = bit % 26;
  6386. var s = (bit - r) / 26;
  6387. var q = 1 << r;
  6388. // Fast case: bit is much higher than all existing words
  6389. if (this.length <= s) {
  6390. this._expand(s + 1);
  6391. this.words[s] |= q;
  6392. return this;
  6393. }
  6394. // Add bit and propagate, if needed
  6395. var carry = q;
  6396. for (var i = s; carry !== 0 && i < this.length; i++) {
  6397. var w = this.words[i] | 0;
  6398. w += carry;
  6399. carry = w >>> 26;
  6400. w &= 0x3ffffff;
  6401. this.words[i] = w;
  6402. }
  6403. if (carry !== 0) {
  6404. this.words[i] = carry;
  6405. this.length++;
  6406. }
  6407. return this;
  6408. };
  6409. BN.prototype.isZero = function isZero () {
  6410. return this.length === 1 && this.words[0] === 0;
  6411. };
  6412. BN.prototype.cmpn = function cmpn (num) {
  6413. var negative = num < 0;
  6414. if (this.negative !== 0 && !negative) return -1;
  6415. if (this.negative === 0 && negative) return 1;
  6416. this.strip();
  6417. var res;
  6418. if (this.length > 1) {
  6419. res = 1;
  6420. } else {
  6421. if (negative) {
  6422. num = -num;
  6423. }
  6424. assert(num <= 0x3ffffff, 'Number is too big');
  6425. var w = this.words[0] | 0;
  6426. res = w === num ? 0 : w < num ? -1 : 1;
  6427. }
  6428. if (this.negative !== 0) return -res | 0;
  6429. return res;
  6430. };
  6431. // Compare two numbers and return:
  6432. // 1 - if `this` > `num`
  6433. // 0 - if `this` == `num`
  6434. // -1 - if `this` < `num`
  6435. BN.prototype.cmp = function cmp (num) {
  6436. if (this.negative !== 0 && num.negative === 0) return -1;
  6437. if (this.negative === 0 && num.negative !== 0) return 1;
  6438. var res = this.ucmp(num);
  6439. if (this.negative !== 0) return -res | 0;
  6440. return res;
  6441. };
  6442. // Unsigned comparison
  6443. BN.prototype.ucmp = function ucmp (num) {
  6444. // At this point both numbers have the same sign
  6445. if (this.length > num.length) return 1;
  6446. if (this.length < num.length) return -1;
  6447. var res = 0;
  6448. for (var i = this.length - 1; i >= 0; i--) {
  6449. var a = this.words[i] | 0;
  6450. var b = num.words[i] | 0;
  6451. if (a === b) continue;
  6452. if (a < b) {
  6453. res = -1;
  6454. } else if (a > b) {
  6455. res = 1;
  6456. }
  6457. break;
  6458. }
  6459. return res;
  6460. };
  6461. BN.prototype.gtn = function gtn (num) {
  6462. return this.cmpn(num) === 1;
  6463. };
  6464. BN.prototype.gt = function gt (num) {
  6465. return this.cmp(num) === 1;
  6466. };
  6467. BN.prototype.gten = function gten (num) {
  6468. return this.cmpn(num) >= 0;
  6469. };
  6470. BN.prototype.gte = function gte (num) {
  6471. return this.cmp(num) >= 0;
  6472. };
  6473. BN.prototype.ltn = function ltn (num) {
  6474. return this.cmpn(num) === -1;
  6475. };
  6476. BN.prototype.lt = function lt (num) {
  6477. return this.cmp(num) === -1;
  6478. };
  6479. BN.prototype.lten = function lten (num) {
  6480. return this.cmpn(num) <= 0;
  6481. };
  6482. BN.prototype.lte = function lte (num) {
  6483. return this.cmp(num) <= 0;
  6484. };
  6485. BN.prototype.eqn = function eqn (num) {
  6486. return this.cmpn(num) === 0;
  6487. };
  6488. BN.prototype.eq = function eq (num) {
  6489. return this.cmp(num) === 0;
  6490. };
  6491. //
  6492. // A reduce context, could be using montgomery or something better, depending
  6493. // on the `m` itself.
  6494. //
  6495. BN.red = function red (num) {
  6496. return new Red(num);
  6497. };
  6498. BN.prototype.toRed = function toRed (ctx) {
  6499. assert(!this.red, 'Already a number in reduction context');
  6500. assert(this.negative === 0, 'red works only with positives');
  6501. return ctx.convertTo(this)._forceRed(ctx);
  6502. };
  6503. BN.prototype.fromRed = function fromRed () {
  6504. assert(this.red, 'fromRed works only with numbers in reduction context');
  6505. return this.red.convertFrom(this);
  6506. };
  6507. BN.prototype._forceRed = function _forceRed (ctx) {
  6508. this.red = ctx;
  6509. return this;
  6510. };
  6511. BN.prototype.forceRed = function forceRed (ctx) {
  6512. assert(!this.red, 'Already a number in reduction context');
  6513. return this._forceRed(ctx);
  6514. };
  6515. BN.prototype.redAdd = function redAdd (num) {
  6516. assert(this.red, 'redAdd works only with red numbers');
  6517. return this.red.add(this, num);
  6518. };
  6519. BN.prototype.redIAdd = function redIAdd (num) {
  6520. assert(this.red, 'redIAdd works only with red numbers');
  6521. return this.red.iadd(this, num);
  6522. };
  6523. BN.prototype.redSub = function redSub (num) {
  6524. assert(this.red, 'redSub works only with red numbers');
  6525. return this.red.sub(this, num);
  6526. };
  6527. BN.prototype.redISub = function redISub (num) {
  6528. assert(this.red, 'redISub works only with red numbers');
  6529. return this.red.isub(this, num);
  6530. };
  6531. BN.prototype.redShl = function redShl (num) {
  6532. assert(this.red, 'redShl works only with red numbers');
  6533. return this.red.shl(this, num);
  6534. };
  6535. BN.prototype.redMul = function redMul (num) {
  6536. assert(this.red, 'redMul works only with red numbers');
  6537. this.red._verify2(this, num);
  6538. return this.red.mul(this, num);
  6539. };
  6540. BN.prototype.redIMul = function redIMul (num) {
  6541. assert(this.red, 'redMul works only with red numbers');
  6542. this.red._verify2(this, num);
  6543. return this.red.imul(this, num);
  6544. };
  6545. BN.prototype.redSqr = function redSqr () {
  6546. assert(this.red, 'redSqr works only with red numbers');
  6547. this.red._verify1(this);
  6548. return this.red.sqr(this);
  6549. };
  6550. BN.prototype.redISqr = function redISqr () {
  6551. assert(this.red, 'redISqr works only with red numbers');
  6552. this.red._verify1(this);
  6553. return this.red.isqr(this);
  6554. };
  6555. // Square root over p
  6556. BN.prototype.redSqrt = function redSqrt () {
  6557. assert(this.red, 'redSqrt works only with red numbers');
  6558. this.red._verify1(this);
  6559. return this.red.sqrt(this);
  6560. };
  6561. BN.prototype.redInvm = function redInvm () {
  6562. assert(this.red, 'redInvm works only with red numbers');
  6563. this.red._verify1(this);
  6564. return this.red.invm(this);
  6565. };
  6566. // Return negative clone of `this` % `red modulo`
  6567. BN.prototype.redNeg = function redNeg () {
  6568. assert(this.red, 'redNeg works only with red numbers');
  6569. this.red._verify1(this);
  6570. return this.red.neg(this);
  6571. };
  6572. BN.prototype.redPow = function redPow (num) {
  6573. assert(this.red && !num.red, 'redPow(normalNum)');
  6574. this.red._verify1(this);
  6575. return this.red.pow(this, num);
  6576. };
  6577. // Prime numbers with efficient reduction
  6578. var primes = {
  6579. k256: null,
  6580. p224: null,
  6581. p192: null,
  6582. p25519: null
  6583. };
  6584. // Pseudo-Mersenne prime
  6585. function MPrime (name, p) {
  6586. // P = 2 ^ N - K
  6587. this.name = name;
  6588. this.p = new BN(p, 16);
  6589. this.n = this.p.bitLength();
  6590. this.k = new BN(1).iushln(this.n).isub(this.p);
  6591. this.tmp = this._tmp();
  6592. }
  6593. MPrime.prototype._tmp = function _tmp () {
  6594. var tmp = new BN(null);
  6595. tmp.words = new Array(Math.ceil(this.n / 13));
  6596. return tmp;
  6597. };
  6598. MPrime.prototype.ireduce = function ireduce (num) {
  6599. // Assumes that `num` is less than `P^2`
  6600. // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
  6601. var r = num;
  6602. var rlen;
  6603. do {
  6604. this.split(r, this.tmp);
  6605. r = this.imulK(r);
  6606. r = r.iadd(this.tmp);
  6607. rlen = r.bitLength();
  6608. } while (rlen > this.n);
  6609. var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
  6610. if (cmp === 0) {
  6611. r.words[0] = 0;
  6612. r.length = 1;
  6613. } else if (cmp > 0) {
  6614. r.isub(this.p);
  6615. } else {
  6616. r.strip();
  6617. }
  6618. return r;
  6619. };
  6620. MPrime.prototype.split = function split (input, out) {
  6621. input.iushrn(this.n, 0, out);
  6622. };
  6623. MPrime.prototype.imulK = function imulK (num) {
  6624. return num.imul(this.k);
  6625. };
  6626. function K256 () {
  6627. MPrime.call(
  6628. this,
  6629. 'k256',
  6630. 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
  6631. }
  6632. inherits(K256, MPrime);
  6633. K256.prototype.split = function split (input, output) {
  6634. // 256 = 9 * 26 + 22
  6635. var mask = 0x3fffff;
  6636. var outLen = Math.min(input.length, 9);
  6637. for (var i = 0; i < outLen; i++) {
  6638. output.words[i] = input.words[i];
  6639. }
  6640. output.length = outLen;
  6641. if (input.length <= 9) {
  6642. input.words[0] = 0;
  6643. input.length = 1;
  6644. return;
  6645. }
  6646. // Shift by 9 limbs
  6647. var prev = input.words[9];
  6648. output.words[output.length++] = prev & mask;
  6649. for (i = 10; i < input.length; i++) {
  6650. var next = input.words[i] | 0;
  6651. input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
  6652. prev = next;
  6653. }
  6654. prev >>>= 22;
  6655. input.words[i - 10] = prev;
  6656. if (prev === 0 && input.length > 10) {
  6657. input.length -= 10;
  6658. } else {
  6659. input.length -= 9;
  6660. }
  6661. };
  6662. K256.prototype.imulK = function imulK (num) {
  6663. // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
  6664. num.words[num.length] = 0;
  6665. num.words[num.length + 1] = 0;
  6666. num.length += 2;
  6667. // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
  6668. var lo = 0;
  6669. for (var i = 0; i < num.length; i++) {
  6670. var w = num.words[i] | 0;
  6671. lo += w * 0x3d1;
  6672. num.words[i] = lo & 0x3ffffff;
  6673. lo = w * 0x40 + ((lo / 0x4000000) | 0);
  6674. }
  6675. // Fast length reduction
  6676. if (num.words[num.length - 1] === 0) {
  6677. num.length--;
  6678. if (num.words[num.length - 1] === 0) {
  6679. num.length--;
  6680. }
  6681. }
  6682. return num;
  6683. };
  6684. function P224 () {
  6685. MPrime.call(
  6686. this,
  6687. 'p224',
  6688. 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
  6689. }
  6690. inherits(P224, MPrime);
  6691. function P192 () {
  6692. MPrime.call(
  6693. this,
  6694. 'p192',
  6695. 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
  6696. }
  6697. inherits(P192, MPrime);
  6698. function P25519 () {
  6699. // 2 ^ 255 - 19
  6700. MPrime.call(
  6701. this,
  6702. '25519',
  6703. '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
  6704. }
  6705. inherits(P25519, MPrime);
  6706. P25519.prototype.imulK = function imulK (num) {
  6707. // K = 0x13
  6708. var carry = 0;
  6709. for (var i = 0; i < num.length; i++) {
  6710. var hi = (num.words[i] | 0) * 0x13 + carry;
  6711. var lo = hi & 0x3ffffff;
  6712. hi >>>= 26;
  6713. num.words[i] = lo;
  6714. carry = hi;
  6715. }
  6716. if (carry !== 0) {
  6717. num.words[num.length++] = carry;
  6718. }
  6719. return num;
  6720. };
  6721. // Exported mostly for testing purposes, use plain name instead
  6722. BN._prime = function prime (name) {
  6723. // Cached version of prime
  6724. if (primes[name]) return primes[name];
  6725. var prime;
  6726. if (name === 'k256') {
  6727. prime = new K256();
  6728. } else if (name === 'p224') {
  6729. prime = new P224();
  6730. } else if (name === 'p192') {
  6731. prime = new P192();
  6732. } else if (name === 'p25519') {
  6733. prime = new P25519();
  6734. } else {
  6735. throw new Error('Unknown prime ' + name);
  6736. }
  6737. primes[name] = prime;
  6738. return prime;
  6739. };
  6740. //
  6741. // Base reduction engine
  6742. //
  6743. function Red (m) {
  6744. if (typeof m === 'string') {
  6745. var prime = BN._prime(m);
  6746. this.m = prime.p;
  6747. this.prime = prime;
  6748. } else {
  6749. assert(m.gtn(1), 'modulus must be greater than 1');
  6750. this.m = m;
  6751. this.prime = null;
  6752. }
  6753. }
  6754. Red.prototype._verify1 = function _verify1 (a) {
  6755. assert(a.negative === 0, 'red works only with positives');
  6756. assert(a.red, 'red works only with red numbers');
  6757. };
  6758. Red.prototype._verify2 = function _verify2 (a, b) {
  6759. assert((a.negative | b.negative) === 0, 'red works only with positives');
  6760. assert(a.red && a.red === b.red,
  6761. 'red works only with red numbers');
  6762. };
  6763. Red.prototype.imod = function imod (a) {
  6764. if (this.prime) return this.prime.ireduce(a)._forceRed(this);
  6765. return a.umod(this.m)._forceRed(this);
  6766. };
  6767. Red.prototype.neg = function neg (a) {
  6768. if (a.isZero()) {
  6769. return a.clone();
  6770. }
  6771. return this.m.sub(a)._forceRed(this);
  6772. };
  6773. Red.prototype.add = function add (a, b) {
  6774. this._verify2(a, b);
  6775. var res = a.add(b);
  6776. if (res.cmp(this.m) >= 0) {
  6777. res.isub(this.m);
  6778. }
  6779. return res._forceRed(this);
  6780. };
  6781. Red.prototype.iadd = function iadd (a, b) {
  6782. this._verify2(a, b);
  6783. var res = a.iadd(b);
  6784. if (res.cmp(this.m) >= 0) {
  6785. res.isub(this.m);
  6786. }
  6787. return res;
  6788. };
  6789. Red.prototype.sub = function sub (a, b) {
  6790. this._verify2(a, b);
  6791. var res = a.sub(b);
  6792. if (res.cmpn(0) < 0) {
  6793. res.iadd(this.m);
  6794. }
  6795. return res._forceRed(this);
  6796. };
  6797. Red.prototype.isub = function isub (a, b) {
  6798. this._verify2(a, b);
  6799. var res = a.isub(b);
  6800. if (res.cmpn(0) < 0) {
  6801. res.iadd(this.m);
  6802. }
  6803. return res;
  6804. };
  6805. Red.prototype.shl = function shl (a, num) {
  6806. this._verify1(a);
  6807. return this.imod(a.ushln(num));
  6808. };
  6809. Red.prototype.imul = function imul (a, b) {
  6810. this._verify2(a, b);
  6811. return this.imod(a.imul(b));
  6812. };
  6813. Red.prototype.mul = function mul (a, b) {
  6814. this._verify2(a, b);
  6815. return this.imod(a.mul(b));
  6816. };
  6817. Red.prototype.isqr = function isqr (a) {
  6818. return this.imul(a, a.clone());
  6819. };
  6820. Red.prototype.sqr = function sqr (a) {
  6821. return this.mul(a, a);
  6822. };
  6823. Red.prototype.sqrt = function sqrt (a) {
  6824. if (a.isZero()) return a.clone();
  6825. var mod3 = this.m.andln(3);
  6826. assert(mod3 % 2 === 1);
  6827. // Fast case
  6828. if (mod3 === 3) {
  6829. var pow = this.m.add(new BN(1)).iushrn(2);
  6830. return this.pow(a, pow);
  6831. }
  6832. // Tonelli-Shanks algorithm (Totally unoptimized and slow)
  6833. //
  6834. // Find Q and S, that Q * 2 ^ S = (P - 1)
  6835. var q = this.m.subn(1);
  6836. var s = 0;
  6837. while (!q.isZero() && q.andln(1) === 0) {
  6838. s++;
  6839. q.iushrn(1);
  6840. }
  6841. assert(!q.isZero());
  6842. var one = new BN(1).toRed(this);
  6843. var nOne = one.redNeg();
  6844. // Find quadratic non-residue
  6845. // NOTE: Max is such because of generalized Riemann hypothesis.
  6846. var lpow = this.m.subn(1).iushrn(1);
  6847. var z = this.m.bitLength();
  6848. z = new BN(2 * z * z).toRed(this);
  6849. while (this.pow(z, lpow).cmp(nOne) !== 0) {
  6850. z.redIAdd(nOne);
  6851. }
  6852. var c = this.pow(z, q);
  6853. var r = this.pow(a, q.addn(1).iushrn(1));
  6854. var t = this.pow(a, q);
  6855. var m = s;
  6856. while (t.cmp(one) !== 0) {
  6857. var tmp = t;
  6858. for (var i = 0; tmp.cmp(one) !== 0; i++) {
  6859. tmp = tmp.redSqr();
  6860. }
  6861. assert(i < m);
  6862. var b = this.pow(c, new BN(1).iushln(m - i - 1));
  6863. r = r.redMul(b);
  6864. c = b.redSqr();
  6865. t = t.redMul(c);
  6866. m = i;
  6867. }
  6868. return r;
  6869. };
  6870. Red.prototype.invm = function invm (a) {
  6871. var inv = a._invmp(this.m);
  6872. if (inv.negative !== 0) {
  6873. inv.negative = 0;
  6874. return this.imod(inv).redNeg();
  6875. } else {
  6876. return this.imod(inv);
  6877. }
  6878. };
  6879. Red.prototype.pow = function pow (a, num) {
  6880. if (num.isZero()) return new BN(1).toRed(this);
  6881. if (num.cmpn(1) === 0) return a.clone();
  6882. var windowSize = 4;
  6883. var wnd = new Array(1 << windowSize);
  6884. wnd[0] = new BN(1).toRed(this);
  6885. wnd[1] = a;
  6886. for (var i = 2; i < wnd.length; i++) {
  6887. wnd[i] = this.mul(wnd[i - 1], a);
  6888. }
  6889. var res = wnd[0];
  6890. var current = 0;
  6891. var currentLen = 0;
  6892. var start = num.bitLength() % 26;
  6893. if (start === 0) {
  6894. start = 26;
  6895. }
  6896. for (i = num.length - 1; i >= 0; i--) {
  6897. var word = num.words[i];
  6898. for (var j = start - 1; j >= 0; j--) {
  6899. var bit = (word >> j) & 1;
  6900. if (res !== wnd[0]) {
  6901. res = this.sqr(res);
  6902. }
  6903. if (bit === 0 && current === 0) {
  6904. currentLen = 0;
  6905. continue;
  6906. }
  6907. current <<= 1;
  6908. current |= bit;
  6909. currentLen++;
  6910. if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
  6911. res = this.mul(res, wnd[current]);
  6912. currentLen = 0;
  6913. current = 0;
  6914. }
  6915. start = 26;
  6916. }
  6917. return res;
  6918. };
  6919. Red.prototype.convertTo = function convertTo (num) {
  6920. var r = num.umod(this.m);
  6921. return r === num ? r.clone() : r;
  6922. };
  6923. Red.prototype.convertFrom = function convertFrom (num) {
  6924. var res = num.clone();
  6925. res.red = null;
  6926. return res;
  6927. };
  6928. //
  6929. // Montgomery method engine
  6930. //
  6931. BN.mont = function mont (num) {
  6932. return new Mont(num);
  6933. };
  6934. function Mont (m) {
  6935. Red.call(this, m);
  6936. this.shift = this.m.bitLength();
  6937. if (this.shift % 26 !== 0) {
  6938. this.shift += 26 - (this.shift % 26);
  6939. }
  6940. this.r = new BN(1).iushln(this.shift);
  6941. this.r2 = this.imod(this.r.sqr());
  6942. this.rinv = this.r._invmp(this.m);
  6943. this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
  6944. this.minv = this.minv.umod(this.r);
  6945. this.minv = this.r.sub(this.minv);
  6946. }
  6947. inherits(Mont, Red);
  6948. Mont.prototype.convertTo = function convertTo (num) {
  6949. return this.imod(num.ushln(this.shift));
  6950. };
  6951. Mont.prototype.convertFrom = function convertFrom (num) {
  6952. var r = this.imod(num.mul(this.rinv));
  6953. r.red = null;
  6954. return r;
  6955. };
  6956. Mont.prototype.imul = function imul (a, b) {
  6957. if (a.isZero() || b.isZero()) {
  6958. a.words[0] = 0;
  6959. a.length = 1;
  6960. return a;
  6961. }
  6962. var t = a.imul(b);
  6963. var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
  6964. var u = t.isub(c).iushrn(this.shift);
  6965. var res = u;
  6966. if (u.cmp(this.m) >= 0) {
  6967. res = u.isub(this.m);
  6968. } else if (u.cmpn(0) < 0) {
  6969. res = u.iadd(this.m);
  6970. }
  6971. return res._forceRed(this);
  6972. };
  6973. Mont.prototype.mul = function mul (a, b) {
  6974. if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
  6975. var t = a.mul(b);
  6976. var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
  6977. var u = t.isub(c).iushrn(this.shift);
  6978. var res = u;
  6979. if (u.cmp(this.m) >= 0) {
  6980. res = u.isub(this.m);
  6981. } else if (u.cmpn(0) < 0) {
  6982. res = u.iadd(this.m);
  6983. }
  6984. return res._forceRed(this);
  6985. };
  6986. Mont.prototype.invm = function invm (a) {
  6987. // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
  6988. var res = this.imod(a._invmp(this.m).mul(this.r2));
  6989. return res._forceRed(this);
  6990. };
  6991. })(typeof module === 'undefined' || module, this);
  6992. },{"buffer":"buffer"}],17:[function(require,module,exports){
  6993. var r;
  6994. module.exports = function rand(len) {
  6995. if (!r)
  6996. r = new Rand(null);
  6997. return r.generate(len);
  6998. };
  6999. function Rand(rand) {
  7000. this.rand = rand;
  7001. }
  7002. module.exports.Rand = Rand;
  7003. Rand.prototype.generate = function generate(len) {
  7004. return this._rand(len);
  7005. };
  7006. // Emulate crypto API using randy
  7007. Rand.prototype._rand = function _rand(n) {
  7008. if (this.rand.getBytes)
  7009. return this.rand.getBytes(n);
  7010. var res = new Uint8Array(n);
  7011. for (var i = 0; i < res.length; i++)
  7012. res[i] = this.rand.getByte();
  7013. return res;
  7014. };
  7015. if (typeof self === 'object') {
  7016. if (self.crypto && self.crypto.getRandomValues) {
  7017. // Modern browsers
  7018. Rand.prototype._rand = function _rand(n) {
  7019. var arr = new Uint8Array(n);
  7020. self.crypto.getRandomValues(arr);
  7021. return arr;
  7022. };
  7023. } else if (self.msCrypto && self.msCrypto.getRandomValues) {
  7024. // IE
  7025. Rand.prototype._rand = function _rand(n) {
  7026. var arr = new Uint8Array(n);
  7027. self.msCrypto.getRandomValues(arr);
  7028. return arr;
  7029. };
  7030. // Safari's WebWorkers do not have `crypto`
  7031. } else if (typeof window === 'object') {
  7032. // Old junk
  7033. Rand.prototype._rand = function() {
  7034. throw new Error('Not implemented yet');
  7035. };
  7036. }
  7037. } else {
  7038. // Node.js or Web worker with no crypto support
  7039. try {
  7040. var crypto = require('crypto');
  7041. if (typeof crypto.randomBytes !== 'function')
  7042. throw new Error('Not supported');
  7043. Rand.prototype._rand = function _rand(n) {
  7044. return crypto.randomBytes(n);
  7045. };
  7046. } catch (e) {
  7047. }
  7048. }
  7049. },{"crypto":"crypto"}],18:[function(require,module,exports){
  7050. 'use strict';
  7051. var elliptic = exports;
  7052. elliptic.utils = require('./elliptic/utils');
  7053. elliptic.rand = require('brorand');
  7054. elliptic.curve = require('./elliptic/curve');
  7055. elliptic.curves = require('./elliptic/curves');
  7056. // Protocols
  7057. elliptic.ec = require('./elliptic/ec');
  7058. elliptic.eddsa = require('./elliptic/eddsa');
  7059. },{"./elliptic/curve":21,"./elliptic/curves":24,"./elliptic/ec":25,"./elliptic/eddsa":28,"./elliptic/utils":32,"brorand":17}],19:[function(require,module,exports){
  7060. 'use strict';
  7061. var BN = require('bn.js');
  7062. var utils = require('../utils');
  7063. var getNAF = utils.getNAF;
  7064. var getJSF = utils.getJSF;
  7065. var assert = utils.assert;
  7066. function BaseCurve(type, conf) {
  7067. this.type = type;
  7068. this.p = new BN(conf.p, 16);
  7069. // Use Montgomery, when there is no fast reduction for the prime
  7070. this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);
  7071. // Useful for many curves
  7072. this.zero = new BN(0).toRed(this.red);
  7073. this.one = new BN(1).toRed(this.red);
  7074. this.two = new BN(2).toRed(this.red);
  7075. // Curve configuration, optional
  7076. this.n = conf.n && new BN(conf.n, 16);
  7077. this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
  7078. // Temporary arrays
  7079. this._wnafT1 = new Array(4);
  7080. this._wnafT2 = new Array(4);
  7081. this._wnafT3 = new Array(4);
  7082. this._wnafT4 = new Array(4);
  7083. // Generalized Greg Maxwell's trick
  7084. var adjustCount = this.n && this.p.div(this.n);
  7085. if (!adjustCount || adjustCount.cmpn(100) > 0) {
  7086. this.redN = null;
  7087. } else {
  7088. this._maxwellTrick = true;
  7089. this.redN = this.n.toRed(this.red);
  7090. }
  7091. }
  7092. module.exports = BaseCurve;
  7093. BaseCurve.prototype.point = function point() {
  7094. throw new Error('Not implemented');
  7095. };
  7096. BaseCurve.prototype.validate = function validate() {
  7097. throw new Error('Not implemented');
  7098. };
  7099. BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
  7100. assert(p.precomputed);
  7101. var doubles = p._getDoubles();
  7102. var naf = getNAF(k, 1);
  7103. var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
  7104. I /= 3;
  7105. // Translate into more windowed form
  7106. var repr = [];
  7107. for (var j = 0; j < naf.length; j += doubles.step) {
  7108. var nafW = 0;
  7109. for (var k = j + doubles.step - 1; k >= j; k--)
  7110. nafW = (nafW << 1) + naf[k];
  7111. repr.push(nafW);
  7112. }
  7113. var a = this.jpoint(null, null, null);
  7114. var b = this.jpoint(null, null, null);
  7115. for (var i = I; i > 0; i--) {
  7116. for (var j = 0; j < repr.length; j++) {
  7117. var nafW = repr[j];
  7118. if (nafW === i)
  7119. b = b.mixedAdd(doubles.points[j]);
  7120. else if (nafW === -i)
  7121. b = b.mixedAdd(doubles.points[j].neg());
  7122. }
  7123. a = a.add(b);
  7124. }
  7125. return a.toP();
  7126. };
  7127. BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
  7128. var w = 4;
  7129. // Precompute window
  7130. var nafPoints = p._getNAFPoints(w);
  7131. w = nafPoints.wnd;
  7132. var wnd = nafPoints.points;
  7133. // Get NAF form
  7134. var naf = getNAF(k, w);
  7135. // Add `this`*(N+1) for every w-NAF index
  7136. var acc = this.jpoint(null, null, null);
  7137. for (var i = naf.length - 1; i >= 0; i--) {
  7138. // Count zeroes
  7139. for (var k = 0; i >= 0 && naf[i] === 0; i--)
  7140. k++;
  7141. if (i >= 0)
  7142. k++;
  7143. acc = acc.dblp(k);
  7144. if (i < 0)
  7145. break;
  7146. var z = naf[i];
  7147. assert(z !== 0);
  7148. if (p.type === 'affine') {
  7149. // J +- P
  7150. if (z > 0)
  7151. acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
  7152. else
  7153. acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
  7154. } else {
  7155. // J +- J
  7156. if (z > 0)
  7157. acc = acc.add(wnd[(z - 1) >> 1]);
  7158. else
  7159. acc = acc.add(wnd[(-z - 1) >> 1].neg());
  7160. }
  7161. }
  7162. return p.type === 'affine' ? acc.toP() : acc;
  7163. };
  7164. BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
  7165. points,
  7166. coeffs,
  7167. len,
  7168. jacobianResult) {
  7169. var wndWidth = this._wnafT1;
  7170. var wnd = this._wnafT2;
  7171. var naf = this._wnafT3;
  7172. // Fill all arrays
  7173. var max = 0;
  7174. for (var i = 0; i < len; i++) {
  7175. var p = points[i];
  7176. var nafPoints = p._getNAFPoints(defW);
  7177. wndWidth[i] = nafPoints.wnd;
  7178. wnd[i] = nafPoints.points;
  7179. }
  7180. // Comb small window NAFs
  7181. for (var i = len - 1; i >= 1; i -= 2) {
  7182. var a = i - 1;
  7183. var b = i;
  7184. if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
  7185. naf[a] = getNAF(coeffs[a], wndWidth[a]);
  7186. naf[b] = getNAF(coeffs[b], wndWidth[b]);
  7187. max = Math.max(naf[a].length, max);
  7188. max = Math.max(naf[b].length, max);
  7189. continue;
  7190. }
  7191. var comb = [
  7192. points[a], /* 1 */
  7193. null, /* 3 */
  7194. null, /* 5 */
  7195. points[b] /* 7 */
  7196. ];
  7197. // Try to avoid Projective points, if possible
  7198. if (points[a].y.cmp(points[b].y) === 0) {
  7199. comb[1] = points[a].add(points[b]);
  7200. comb[2] = points[a].toJ().mixedAdd(points[b].neg());
  7201. } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
  7202. comb[1] = points[a].toJ().mixedAdd(points[b]);
  7203. comb[2] = points[a].add(points[b].neg());
  7204. } else {
  7205. comb[1] = points[a].toJ().mixedAdd(points[b]);
  7206. comb[2] = points[a].toJ().mixedAdd(points[b].neg());
  7207. }
  7208. var index = [
  7209. -3, /* -1 -1 */
  7210. -1, /* -1 0 */
  7211. -5, /* -1 1 */
  7212. -7, /* 0 -1 */
  7213. 0, /* 0 0 */
  7214. 7, /* 0 1 */
  7215. 5, /* 1 -1 */
  7216. 1, /* 1 0 */
  7217. 3 /* 1 1 */
  7218. ];
  7219. var jsf = getJSF(coeffs[a], coeffs[b]);
  7220. max = Math.max(jsf[0].length, max);
  7221. naf[a] = new Array(max);
  7222. naf[b] = new Array(max);
  7223. for (var j = 0; j < max; j++) {
  7224. var ja = jsf[0][j] | 0;
  7225. var jb = jsf[1][j] | 0;
  7226. naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
  7227. naf[b][j] = 0;
  7228. wnd[a] = comb;
  7229. }
  7230. }
  7231. var acc = this.jpoint(null, null, null);
  7232. var tmp = this._wnafT4;
  7233. for (var i = max; i >= 0; i--) {
  7234. var k = 0;
  7235. while (i >= 0) {
  7236. var zero = true;
  7237. for (var j = 0; j < len; j++) {
  7238. tmp[j] = naf[j][i] | 0;
  7239. if (tmp[j] !== 0)
  7240. zero = false;
  7241. }
  7242. if (!zero)
  7243. break;
  7244. k++;
  7245. i--;
  7246. }
  7247. if (i >= 0)
  7248. k++;
  7249. acc = acc.dblp(k);
  7250. if (i < 0)
  7251. break;
  7252. for (var j = 0; j < len; j++) {
  7253. var z = tmp[j];
  7254. var p;
  7255. if (z === 0)
  7256. continue;
  7257. else if (z > 0)
  7258. p = wnd[j][(z - 1) >> 1];
  7259. else if (z < 0)
  7260. p = wnd[j][(-z - 1) >> 1].neg();
  7261. if (p.type === 'affine')
  7262. acc = acc.mixedAdd(p);
  7263. else
  7264. acc = acc.add(p);
  7265. }
  7266. }
  7267. // Zeroify references
  7268. for (var i = 0; i < len; i++)
  7269. wnd[i] = null;
  7270. if (jacobianResult)
  7271. return acc;
  7272. else
  7273. return acc.toP();
  7274. };
  7275. function BasePoint(curve, type) {
  7276. this.curve = curve;
  7277. this.type = type;
  7278. this.precomputed = null;
  7279. }
  7280. BaseCurve.BasePoint = BasePoint;
  7281. BasePoint.prototype.eq = function eq(/*other*/) {
  7282. throw new Error('Not implemented');
  7283. };
  7284. BasePoint.prototype.validate = function validate() {
  7285. return this.curve.validate(this);
  7286. };
  7287. BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
  7288. bytes = utils.toArray(bytes, enc);
  7289. var len = this.p.byteLength();
  7290. // uncompressed, hybrid-odd, hybrid-even
  7291. if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&
  7292. bytes.length - 1 === 2 * len) {
  7293. if (bytes[0] === 0x06)
  7294. assert(bytes[bytes.length - 1] % 2 === 0);
  7295. else if (bytes[0] === 0x07)
  7296. assert(bytes[bytes.length - 1] % 2 === 1);
  7297. var res = this.point(bytes.slice(1, 1 + len),
  7298. bytes.slice(1 + len, 1 + 2 * len));
  7299. return res;
  7300. } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&
  7301. bytes.length - 1 === len) {
  7302. return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);
  7303. }
  7304. throw new Error('Unknown point format');
  7305. };
  7306. BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
  7307. return this.encode(enc, true);
  7308. };
  7309. BasePoint.prototype._encode = function _encode(compact) {
  7310. var len = this.curve.p.byteLength();
  7311. var x = this.getX().toArray('be', len);
  7312. if (compact)
  7313. return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);
  7314. return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ;
  7315. };
  7316. BasePoint.prototype.encode = function encode(enc, compact) {
  7317. return utils.encode(this._encode(compact), enc);
  7318. };
  7319. BasePoint.prototype.precompute = function precompute(power) {
  7320. if (this.precomputed)
  7321. return this;
  7322. var precomputed = {
  7323. doubles: null,
  7324. naf: null,
  7325. beta: null
  7326. };
  7327. precomputed.naf = this._getNAFPoints(8);
  7328. precomputed.doubles = this._getDoubles(4, power);
  7329. precomputed.beta = this._getBeta();
  7330. this.precomputed = precomputed;
  7331. return this;
  7332. };
  7333. BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
  7334. if (!this.precomputed)
  7335. return false;
  7336. var doubles = this.precomputed.doubles;
  7337. if (!doubles)
  7338. return false;
  7339. return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
  7340. };
  7341. BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
  7342. if (this.precomputed && this.precomputed.doubles)
  7343. return this.precomputed.doubles;
  7344. var doubles = [ this ];
  7345. var acc = this;
  7346. for (var i = 0; i < power; i += step) {
  7347. for (var j = 0; j < step; j++)
  7348. acc = acc.dbl();
  7349. doubles.push(acc);
  7350. }
  7351. return {
  7352. step: step,
  7353. points: doubles
  7354. };
  7355. };
  7356. BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
  7357. if (this.precomputed && this.precomputed.naf)
  7358. return this.precomputed.naf;
  7359. var res = [ this ];
  7360. var max = (1 << wnd) - 1;
  7361. var dbl = max === 1 ? null : this.dbl();
  7362. for (var i = 1; i < max; i++)
  7363. res[i] = res[i - 1].add(dbl);
  7364. return {
  7365. wnd: wnd,
  7366. points: res
  7367. };
  7368. };
  7369. BasePoint.prototype._getBeta = function _getBeta() {
  7370. return null;
  7371. };
  7372. BasePoint.prototype.dblp = function dblp(k) {
  7373. var r = this;
  7374. for (var i = 0; i < k; i++)
  7375. r = r.dbl();
  7376. return r;
  7377. };
  7378. },{"../utils":32,"bn.js":16}],20:[function(require,module,exports){
  7379. 'use strict';
  7380. var utils = require('../utils');
  7381. var BN = require('bn.js');
  7382. var inherits = require('inherits');
  7383. var Base = require('./base');
  7384. var assert = utils.assert;
  7385. function EdwardsCurve(conf) {
  7386. // NOTE: Important as we are creating point in Base.call()
  7387. this.twisted = (conf.a | 0) !== 1;
  7388. this.mOneA = this.twisted && (conf.a | 0) === -1;
  7389. this.extended = this.mOneA;
  7390. Base.call(this, 'edwards', conf);
  7391. this.a = new BN(conf.a, 16).umod(this.red.m);
  7392. this.a = this.a.toRed(this.red);
  7393. this.c = new BN(conf.c, 16).toRed(this.red);
  7394. this.c2 = this.c.redSqr();
  7395. this.d = new BN(conf.d, 16).toRed(this.red);
  7396. this.dd = this.d.redAdd(this.d);
  7397. assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);
  7398. this.oneC = (conf.c | 0) === 1;
  7399. }
  7400. inherits(EdwardsCurve, Base);
  7401. module.exports = EdwardsCurve;
  7402. EdwardsCurve.prototype._mulA = function _mulA(num) {
  7403. if (this.mOneA)
  7404. return num.redNeg();
  7405. else
  7406. return this.a.redMul(num);
  7407. };
  7408. EdwardsCurve.prototype._mulC = function _mulC(num) {
  7409. if (this.oneC)
  7410. return num;
  7411. else
  7412. return this.c.redMul(num);
  7413. };
  7414. // Just for compatibility with Short curve
  7415. EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {
  7416. return this.point(x, y, z, t);
  7417. };
  7418. EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {
  7419. x = new BN(x, 16);
  7420. if (!x.red)
  7421. x = x.toRed(this.red);
  7422. var x2 = x.redSqr();
  7423. var rhs = this.c2.redSub(this.a.redMul(x2));
  7424. var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));
  7425. var y2 = rhs.redMul(lhs.redInvm());
  7426. var y = y2.redSqrt();
  7427. if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
  7428. throw new Error('invalid point');
  7429. var isOdd = y.fromRed().isOdd();
  7430. if (odd && !isOdd || !odd && isOdd)
  7431. y = y.redNeg();
  7432. return this.point(x, y);
  7433. };
  7434. EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {
  7435. y = new BN(y, 16);
  7436. if (!y.red)
  7437. y = y.toRed(this.red);
  7438. // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)
  7439. var y2 = y.redSqr();
  7440. var lhs = y2.redSub(this.c2);
  7441. var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);
  7442. var x2 = lhs.redMul(rhs.redInvm());
  7443. if (x2.cmp(this.zero) === 0) {
  7444. if (odd)
  7445. throw new Error('invalid point');
  7446. else
  7447. return this.point(this.zero, y);
  7448. }
  7449. var x = x2.redSqrt();
  7450. if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)
  7451. throw new Error('invalid point');
  7452. if (x.fromRed().isOdd() !== odd)
  7453. x = x.redNeg();
  7454. return this.point(x, y);
  7455. };
  7456. EdwardsCurve.prototype.validate = function validate(point) {
  7457. if (point.isInfinity())
  7458. return true;
  7459. // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)
  7460. point.normalize();
  7461. var x2 = point.x.redSqr();
  7462. var y2 = point.y.redSqr();
  7463. var lhs = x2.redMul(this.a).redAdd(y2);
  7464. var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));
  7465. return lhs.cmp(rhs) === 0;
  7466. };
  7467. function Point(curve, x, y, z, t) {
  7468. Base.BasePoint.call(this, curve, 'projective');
  7469. if (x === null && y === null && z === null) {
  7470. this.x = this.curve.zero;
  7471. this.y = this.curve.one;
  7472. this.z = this.curve.one;
  7473. this.t = this.curve.zero;
  7474. this.zOne = true;
  7475. } else {
  7476. this.x = new BN(x, 16);
  7477. this.y = new BN(y, 16);
  7478. this.z = z ? new BN(z, 16) : this.curve.one;
  7479. this.t = t && new BN(t, 16);
  7480. if (!this.x.red)
  7481. this.x = this.x.toRed(this.curve.red);
  7482. if (!this.y.red)
  7483. this.y = this.y.toRed(this.curve.red);
  7484. if (!this.z.red)
  7485. this.z = this.z.toRed(this.curve.red);
  7486. if (this.t && !this.t.red)
  7487. this.t = this.t.toRed(this.curve.red);
  7488. this.zOne = this.z === this.curve.one;
  7489. // Use extended coordinates
  7490. if (this.curve.extended && !this.t) {
  7491. this.t = this.x.redMul(this.y);
  7492. if (!this.zOne)
  7493. this.t = this.t.redMul(this.z.redInvm());
  7494. }
  7495. }
  7496. }
  7497. inherits(Point, Base.BasePoint);
  7498. EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
  7499. return Point.fromJSON(this, obj);
  7500. };
  7501. EdwardsCurve.prototype.point = function point(x, y, z, t) {
  7502. return new Point(this, x, y, z, t);
  7503. };
  7504. Point.fromJSON = function fromJSON(curve, obj) {
  7505. return new Point(curve, obj[0], obj[1], obj[2]);
  7506. };
  7507. Point.prototype.inspect = function inspect() {
  7508. if (this.isInfinity())
  7509. return '<EC Point Infinity>';
  7510. return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
  7511. ' y: ' + this.y.fromRed().toString(16, 2) +
  7512. ' z: ' + this.z.fromRed().toString(16, 2) + '>';
  7513. };
  7514. Point.prototype.isInfinity = function isInfinity() {
  7515. // XXX This code assumes that zero is always zero in red
  7516. return this.x.cmpn(0) === 0 &&
  7517. (this.y.cmp(this.z) === 0 ||
  7518. (this.zOne && this.y.cmp(this.curve.c) === 0));
  7519. };
  7520. Point.prototype._extDbl = function _extDbl() {
  7521. // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
  7522. // #doubling-dbl-2008-hwcd
  7523. // 4M + 4S
  7524. // A = X1^2
  7525. var a = this.x.redSqr();
  7526. // B = Y1^2
  7527. var b = this.y.redSqr();
  7528. // C = 2 * Z1^2
  7529. var c = this.z.redSqr();
  7530. c = c.redIAdd(c);
  7531. // D = a * A
  7532. var d = this.curve._mulA(a);
  7533. // E = (X1 + Y1)^2 - A - B
  7534. var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);
  7535. // G = D + B
  7536. var g = d.redAdd(b);
  7537. // F = G - C
  7538. var f = g.redSub(c);
  7539. // H = D - B
  7540. var h = d.redSub(b);
  7541. // X3 = E * F
  7542. var nx = e.redMul(f);
  7543. // Y3 = G * H
  7544. var ny = g.redMul(h);
  7545. // T3 = E * H
  7546. var nt = e.redMul(h);
  7547. // Z3 = F * G
  7548. var nz = f.redMul(g);
  7549. return this.curve.point(nx, ny, nz, nt);
  7550. };
  7551. Point.prototype._projDbl = function _projDbl() {
  7552. // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
  7553. // #doubling-dbl-2008-bbjlp
  7554. // #doubling-dbl-2007-bl
  7555. // and others
  7556. // Generally 3M + 4S or 2M + 4S
  7557. // B = (X1 + Y1)^2
  7558. var b = this.x.redAdd(this.y).redSqr();
  7559. // C = X1^2
  7560. var c = this.x.redSqr();
  7561. // D = Y1^2
  7562. var d = this.y.redSqr();
  7563. var nx;
  7564. var ny;
  7565. var nz;
  7566. if (this.curve.twisted) {
  7567. // E = a * C
  7568. var e = this.curve._mulA(c);
  7569. // F = E + D
  7570. var f = e.redAdd(d);
  7571. if (this.zOne) {
  7572. // X3 = (B - C - D) * (F - 2)
  7573. nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));
  7574. // Y3 = F * (E - D)
  7575. ny = f.redMul(e.redSub(d));
  7576. // Z3 = F^2 - 2 * F
  7577. nz = f.redSqr().redSub(f).redSub(f);
  7578. } else {
  7579. // H = Z1^2
  7580. var h = this.z.redSqr();
  7581. // J = F - 2 * H
  7582. var j = f.redSub(h).redISub(h);
  7583. // X3 = (B-C-D)*J
  7584. nx = b.redSub(c).redISub(d).redMul(j);
  7585. // Y3 = F * (E - D)
  7586. ny = f.redMul(e.redSub(d));
  7587. // Z3 = F * J
  7588. nz = f.redMul(j);
  7589. }
  7590. } else {
  7591. // E = C + D
  7592. var e = c.redAdd(d);
  7593. // H = (c * Z1)^2
  7594. var h = this.curve._mulC(this.z).redSqr();
  7595. // J = E - 2 * H
  7596. var j = e.redSub(h).redSub(h);
  7597. // X3 = c * (B - E) * J
  7598. nx = this.curve._mulC(b.redISub(e)).redMul(j);
  7599. // Y3 = c * E * (C - D)
  7600. ny = this.curve._mulC(e).redMul(c.redISub(d));
  7601. // Z3 = E * J
  7602. nz = e.redMul(j);
  7603. }
  7604. return this.curve.point(nx, ny, nz);
  7605. };
  7606. Point.prototype.dbl = function dbl() {
  7607. if (this.isInfinity())
  7608. return this;
  7609. // Double in extended coordinates
  7610. if (this.curve.extended)
  7611. return this._extDbl();
  7612. else
  7613. return this._projDbl();
  7614. };
  7615. Point.prototype._extAdd = function _extAdd(p) {
  7616. // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
  7617. // #addition-add-2008-hwcd-3
  7618. // 8M
  7619. // A = (Y1 - X1) * (Y2 - X2)
  7620. var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));
  7621. // B = (Y1 + X1) * (Y2 + X2)
  7622. var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));
  7623. // C = T1 * k * T2
  7624. var c = this.t.redMul(this.curve.dd).redMul(p.t);
  7625. // D = Z1 * 2 * Z2
  7626. var d = this.z.redMul(p.z.redAdd(p.z));
  7627. // E = B - A
  7628. var e = b.redSub(a);
  7629. // F = D - C
  7630. var f = d.redSub(c);
  7631. // G = D + C
  7632. var g = d.redAdd(c);
  7633. // H = B + A
  7634. var h = b.redAdd(a);
  7635. // X3 = E * F
  7636. var nx = e.redMul(f);
  7637. // Y3 = G * H
  7638. var ny = g.redMul(h);
  7639. // T3 = E * H
  7640. var nt = e.redMul(h);
  7641. // Z3 = F * G
  7642. var nz = f.redMul(g);
  7643. return this.curve.point(nx, ny, nz, nt);
  7644. };
  7645. Point.prototype._projAdd = function _projAdd(p) {
  7646. // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
  7647. // #addition-add-2008-bbjlp
  7648. // #addition-add-2007-bl
  7649. // 10M + 1S
  7650. // A = Z1 * Z2
  7651. var a = this.z.redMul(p.z);
  7652. // B = A^2
  7653. var b = a.redSqr();
  7654. // C = X1 * X2
  7655. var c = this.x.redMul(p.x);
  7656. // D = Y1 * Y2
  7657. var d = this.y.redMul(p.y);
  7658. // E = d * C * D
  7659. var e = this.curve.d.redMul(c).redMul(d);
  7660. // F = B - E
  7661. var f = b.redSub(e);
  7662. // G = B + E
  7663. var g = b.redAdd(e);
  7664. // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)
  7665. var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);
  7666. var nx = a.redMul(f).redMul(tmp);
  7667. var ny;
  7668. var nz;
  7669. if (this.curve.twisted) {
  7670. // Y3 = A * G * (D - a * C)
  7671. ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));
  7672. // Z3 = F * G
  7673. nz = f.redMul(g);
  7674. } else {
  7675. // Y3 = A * G * (D - C)
  7676. ny = a.redMul(g).redMul(d.redSub(c));
  7677. // Z3 = c * F * G
  7678. nz = this.curve._mulC(f).redMul(g);
  7679. }
  7680. return this.curve.point(nx, ny, nz);
  7681. };
  7682. Point.prototype.add = function add(p) {
  7683. if (this.isInfinity())
  7684. return p;
  7685. if (p.isInfinity())
  7686. return this;
  7687. if (this.curve.extended)
  7688. return this._extAdd(p);
  7689. else
  7690. return this._projAdd(p);
  7691. };
  7692. Point.prototype.mul = function mul(k) {
  7693. if (this._hasDoubles(k))
  7694. return this.curve._fixedNafMul(this, k);
  7695. else
  7696. return this.curve._wnafMul(this, k);
  7697. };
  7698. Point.prototype.mulAdd = function mulAdd(k1, p, k2) {
  7699. return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);
  7700. };
  7701. Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) {
  7702. return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);
  7703. };
  7704. Point.prototype.normalize = function normalize() {
  7705. if (this.zOne)
  7706. return this;
  7707. // Normalize coordinates
  7708. var zi = this.z.redInvm();
  7709. this.x = this.x.redMul(zi);
  7710. this.y = this.y.redMul(zi);
  7711. if (this.t)
  7712. this.t = this.t.redMul(zi);
  7713. this.z = this.curve.one;
  7714. this.zOne = true;
  7715. return this;
  7716. };
  7717. Point.prototype.neg = function neg() {
  7718. return this.curve.point(this.x.redNeg(),
  7719. this.y,
  7720. this.z,
  7721. this.t && this.t.redNeg());
  7722. };
  7723. Point.prototype.getX = function getX() {
  7724. this.normalize();
  7725. return this.x.fromRed();
  7726. };
  7727. Point.prototype.getY = function getY() {
  7728. this.normalize();
  7729. return this.y.fromRed();
  7730. };
  7731. Point.prototype.eq = function eq(other) {
  7732. return this === other ||
  7733. this.getX().cmp(other.getX()) === 0 &&
  7734. this.getY().cmp(other.getY()) === 0;
  7735. };
  7736. Point.prototype.eqXToP = function eqXToP(x) {
  7737. var rx = x.toRed(this.curve.red).redMul(this.z);
  7738. if (this.x.cmp(rx) === 0)
  7739. return true;
  7740. var xc = x.clone();
  7741. var t = this.curve.redN.redMul(this.z);
  7742. for (;;) {
  7743. xc.iadd(this.curve.n);
  7744. if (xc.cmp(this.curve.p) >= 0)
  7745. return false;
  7746. rx.redIAdd(t);
  7747. if (this.x.cmp(rx) === 0)
  7748. return true;
  7749. }
  7750. };
  7751. // Compatibility with BaseCurve
  7752. Point.prototype.toP = Point.prototype.normalize;
  7753. Point.prototype.mixedAdd = Point.prototype.add;
  7754. },{"../utils":32,"./base":19,"bn.js":16,"inherits":47}],21:[function(require,module,exports){
  7755. 'use strict';
  7756. var curve = exports;
  7757. curve.base = require('./base');
  7758. curve.short = require('./short');
  7759. curve.mont = require('./mont');
  7760. curve.edwards = require('./edwards');
  7761. },{"./base":19,"./edwards":20,"./mont":22,"./short":23}],22:[function(require,module,exports){
  7762. 'use strict';
  7763. var BN = require('bn.js');
  7764. var inherits = require('inherits');
  7765. var Base = require('./base');
  7766. var utils = require('../utils');
  7767. function MontCurve(conf) {
  7768. Base.call(this, 'mont', conf);
  7769. this.a = new BN(conf.a, 16).toRed(this.red);
  7770. this.b = new BN(conf.b, 16).toRed(this.red);
  7771. this.i4 = new BN(4).toRed(this.red).redInvm();
  7772. this.two = new BN(2).toRed(this.red);
  7773. // Note: this implementation is according to the original paper
  7774. // by P. Montgomery, NOT the one by D. J. Bernstein.
  7775. this.a24 = this.i4.redMul(this.a.redAdd(this.two));
  7776. }
  7777. inherits(MontCurve, Base);
  7778. module.exports = MontCurve;
  7779. MontCurve.prototype.validate = function validate(point) {
  7780. var x = point.normalize().x;
  7781. var x2 = x.redSqr();
  7782. var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);
  7783. var y = rhs.redSqrt();
  7784. return y.redSqr().cmp(rhs) === 0;
  7785. };
  7786. function Point(curve, x, z) {
  7787. Base.BasePoint.call(this, curve, 'projective');
  7788. if (x === null && z === null) {
  7789. this.x = this.curve.one;
  7790. this.z = this.curve.zero;
  7791. } else {
  7792. this.x = new BN(x, 16);
  7793. this.z = new BN(z, 16);
  7794. if (!this.x.red)
  7795. this.x = this.x.toRed(this.curve.red);
  7796. if (!this.z.red)
  7797. this.z = this.z.toRed(this.curve.red);
  7798. }
  7799. }
  7800. inherits(Point, Base.BasePoint);
  7801. MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
  7802. var bytes = utils.toArray(bytes, enc);
  7803. // TODO Curve448
  7804. // Montgomery curve points must be represented in the compressed format
  7805. // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B
  7806. if (bytes.length === 33 && bytes[0] === 0x40)
  7807. bytes = bytes.slice(1, 33).reverse(); // point must be little-endian
  7808. if (bytes.length !== 32)
  7809. throw new Error('Unknown point compression format');
  7810. return this.point(bytes, 1);
  7811. };
  7812. MontCurve.prototype.point = function point(x, z) {
  7813. return new Point(this, x, z);
  7814. };
  7815. MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
  7816. return Point.fromJSON(this, obj);
  7817. };
  7818. Point.prototype.precompute = function precompute() {
  7819. // No-op
  7820. };
  7821. Point.prototype._encode = function _encode(compact) {
  7822. var len = this.curve.p.byteLength();
  7823. // Note: the output should always be little-endian
  7824. // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B
  7825. if (compact) {
  7826. return [ 0x40 ].concat(this.getX().toArray('le', len));
  7827. } else {
  7828. return this.getX().toArray('be', len);
  7829. }
  7830. };
  7831. Point.fromJSON = function fromJSON(curve, obj) {
  7832. return new Point(curve, obj[0], obj[1] || curve.one);
  7833. };
  7834. Point.prototype.inspect = function inspect() {
  7835. if (this.isInfinity())
  7836. return '<EC Point Infinity>';
  7837. return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
  7838. ' z: ' + this.z.fromRed().toString(16, 2) + '>';
  7839. };
  7840. Point.prototype.isInfinity = function isInfinity() {
  7841. // XXX This code assumes that zero is always zero in red
  7842. return this.z.cmpn(0) === 0;
  7843. };
  7844. Point.prototype.dbl = function dbl() {
  7845. // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3
  7846. // 2M + 2S + 4A
  7847. // A = X1 + Z1
  7848. var a = this.x.redAdd(this.z);
  7849. // AA = A^2
  7850. var aa = a.redSqr();
  7851. // B = X1 - Z1
  7852. var b = this.x.redSub(this.z);
  7853. // BB = B^2
  7854. var bb = b.redSqr();
  7855. // C = AA - BB
  7856. var c = aa.redSub(bb);
  7857. // X3 = AA * BB
  7858. var nx = aa.redMul(bb);
  7859. // Z3 = C * (BB + A24 * C)
  7860. var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));
  7861. return this.curve.point(nx, nz);
  7862. };
  7863. Point.prototype.add = function add() {
  7864. throw new Error('Not supported on Montgomery curve');
  7865. };
  7866. Point.prototype.diffAdd = function diffAdd(p, diff) {
  7867. // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3
  7868. // 4M + 2S + 6A
  7869. // A = X2 + Z2
  7870. var a = this.x.redAdd(this.z);
  7871. // B = X2 - Z2
  7872. var b = this.x.redSub(this.z);
  7873. // C = X3 + Z3
  7874. var c = p.x.redAdd(p.z);
  7875. // D = X3 - Z3
  7876. var d = p.x.redSub(p.z);
  7877. // DA = D * A
  7878. var da = d.redMul(a);
  7879. // CB = C * B
  7880. var cb = c.redMul(b);
  7881. // X5 = Z1 * (DA + CB)^2
  7882. var nx = diff.z.redMul(da.redAdd(cb).redSqr());
  7883. // Z5 = X1 * (DA - CB)^2
  7884. var nz = diff.x.redMul(da.redISub(cb).redSqr());
  7885. return this.curve.point(nx, nz);
  7886. };
  7887. Point.prototype.mul = function mul(k) {
  7888. k = new BN(k, 16);
  7889. var t = k.clone();
  7890. var a = this; // (N / 2) * Q + Q
  7891. var b = this.curve.point(null, null); // (N / 2) * Q
  7892. var c = this; // Q
  7893. for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))
  7894. bits.push(t.andln(1));
  7895. for (var i = bits.length - 1; i >= 0; i--) {
  7896. if (bits[i] === 0) {
  7897. // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q
  7898. a = a.diffAdd(b, c);
  7899. // N * Q = 2 * ((N / 2) * Q + Q))
  7900. b = b.dbl();
  7901. } else {
  7902. // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)
  7903. b = a.diffAdd(b, c);
  7904. // N * Q + Q = 2 * ((N / 2) * Q + Q)
  7905. a = a.dbl();
  7906. }
  7907. }
  7908. return b;
  7909. };
  7910. Point.prototype.mulAdd = function mulAdd() {
  7911. throw new Error('Not supported on Montgomery curve');
  7912. };
  7913. Point.prototype.jumlAdd = function jumlAdd() {
  7914. throw new Error('Not supported on Montgomery curve');
  7915. };
  7916. Point.prototype.eq = function eq(other) {
  7917. return this.getX().cmp(other.getX()) === 0;
  7918. };
  7919. Point.prototype.normalize = function normalize() {
  7920. this.x = this.x.redMul(this.z.redInvm());
  7921. this.z = this.curve.one;
  7922. return this;
  7923. };
  7924. Point.prototype.getX = function getX() {
  7925. // Normalize coordinates
  7926. this.normalize();
  7927. return this.x.fromRed();
  7928. };
  7929. },{"../utils":32,"./base":19,"bn.js":16,"inherits":47}],23:[function(require,module,exports){
  7930. 'use strict';
  7931. var utils = require('../utils');
  7932. var BN = require('bn.js');
  7933. var inherits = require('inherits');
  7934. var Base = require('./base');
  7935. var assert = utils.assert;
  7936. function ShortCurve(conf) {
  7937. Base.call(this, 'short', conf);
  7938. this.a = new BN(conf.a, 16).toRed(this.red);
  7939. this.b = new BN(conf.b, 16).toRed(this.red);
  7940. this.tinv = this.two.redInvm();
  7941. this.zeroA = this.a.fromRed().cmpn(0) === 0;
  7942. this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;
  7943. // If the curve is endomorphic, precalculate beta and lambda
  7944. this.endo = this._getEndomorphism(conf);
  7945. this._endoWnafT1 = new Array(4);
  7946. this._endoWnafT2 = new Array(4);
  7947. }
  7948. inherits(ShortCurve, Base);
  7949. module.exports = ShortCurve;
  7950. ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
  7951. // No efficient endomorphism
  7952. if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
  7953. return;
  7954. // Compute beta and lambda, that lambda * P = (beta * Px; Py)
  7955. var beta;
  7956. var lambda;
  7957. if (conf.beta) {
  7958. beta = new BN(conf.beta, 16).toRed(this.red);
  7959. } else {
  7960. var betas = this._getEndoRoots(this.p);
  7961. // Choose the smallest beta
  7962. beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
  7963. beta = beta.toRed(this.red);
  7964. }
  7965. if (conf.lambda) {
  7966. lambda = new BN(conf.lambda, 16);
  7967. } else {
  7968. // Choose the lambda that is matching selected beta
  7969. var lambdas = this._getEndoRoots(this.n);
  7970. if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
  7971. lambda = lambdas[0];
  7972. } else {
  7973. lambda = lambdas[1];
  7974. assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
  7975. }
  7976. }
  7977. // Get basis vectors, used for balanced length-two representation
  7978. var basis;
  7979. if (conf.basis) {
  7980. basis = conf.basis.map(function(vec) {
  7981. return {
  7982. a: new BN(vec.a, 16),
  7983. b: new BN(vec.b, 16)
  7984. };
  7985. });
  7986. } else {
  7987. basis = this._getEndoBasis(lambda);
  7988. }
  7989. return {
  7990. beta: beta,
  7991. lambda: lambda,
  7992. basis: basis
  7993. };
  7994. };
  7995. ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
  7996. // Find roots of for x^2 + x + 1 in F
  7997. // Root = (-1 +- Sqrt(-3)) / 2
  7998. //
  7999. var red = num === this.p ? this.red : BN.mont(num);
  8000. var tinv = new BN(2).toRed(red).redInvm();
  8001. var ntinv = tinv.redNeg();
  8002. var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);
  8003. var l1 = ntinv.redAdd(s).fromRed();
  8004. var l2 = ntinv.redSub(s).fromRed();
  8005. return [ l1, l2 ];
  8006. };
  8007. ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
  8008. // aprxSqrt >= sqrt(this.n)
  8009. var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));
  8010. // 3.74
  8011. // Run EGCD, until r(L + 1) < aprxSqrt
  8012. var u = lambda;
  8013. var v = this.n.clone();
  8014. var x1 = new BN(1);
  8015. var y1 = new BN(0);
  8016. var x2 = new BN(0);
  8017. var y2 = new BN(1);
  8018. // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
  8019. var a0;
  8020. var b0;
  8021. // First vector
  8022. var a1;
  8023. var b1;
  8024. // Second vector
  8025. var a2;
  8026. var b2;
  8027. var prevR;
  8028. var i = 0;
  8029. var r;
  8030. var x;
  8031. while (u.cmpn(0) !== 0) {
  8032. var q = v.div(u);
  8033. r = v.sub(q.mul(u));
  8034. x = x2.sub(q.mul(x1));
  8035. var y = y2.sub(q.mul(y1));
  8036. if (!a1 && r.cmp(aprxSqrt) < 0) {
  8037. a0 = prevR.neg();
  8038. b0 = x1;
  8039. a1 = r.neg();
  8040. b1 = x;
  8041. } else if (a1 && ++i === 2) {
  8042. break;
  8043. }
  8044. prevR = r;
  8045. v = u;
  8046. u = r;
  8047. x2 = x1;
  8048. x1 = x;
  8049. y2 = y1;
  8050. y1 = y;
  8051. }
  8052. a2 = r.neg();
  8053. b2 = x;
  8054. var len1 = a1.sqr().add(b1.sqr());
  8055. var len2 = a2.sqr().add(b2.sqr());
  8056. if (len2.cmp(len1) >= 0) {
  8057. a2 = a0;
  8058. b2 = b0;
  8059. }
  8060. // Normalize signs
  8061. if (a1.negative) {
  8062. a1 = a1.neg();
  8063. b1 = b1.neg();
  8064. }
  8065. if (a2.negative) {
  8066. a2 = a2.neg();
  8067. b2 = b2.neg();
  8068. }
  8069. return [
  8070. { a: a1, b: b1 },
  8071. { a: a2, b: b2 }
  8072. ];
  8073. };
  8074. ShortCurve.prototype._endoSplit = function _endoSplit(k) {
  8075. var basis = this.endo.basis;
  8076. var v1 = basis[0];
  8077. var v2 = basis[1];
  8078. var c1 = v2.b.mul(k).divRound(this.n);
  8079. var c2 = v1.b.neg().mul(k).divRound(this.n);
  8080. var p1 = c1.mul(v1.a);
  8081. var p2 = c2.mul(v2.a);
  8082. var q1 = c1.mul(v1.b);
  8083. var q2 = c2.mul(v2.b);
  8084. // Calculate answer
  8085. var k1 = k.sub(p1).sub(p2);
  8086. var k2 = q1.add(q2).neg();
  8087. return { k1: k1, k2: k2 };
  8088. };
  8089. ShortCurve.prototype.pointFromX = function pointFromX(x, odd) {
  8090. x = new BN(x, 16);
  8091. if (!x.red)
  8092. x = x.toRed(this.red);
  8093. var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
  8094. var y = y2.redSqrt();
  8095. if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
  8096. throw new Error('invalid point');
  8097. // XXX Is there any way to tell if the number is odd without converting it
  8098. // to non-red form?
  8099. var isOdd = y.fromRed().isOdd();
  8100. if (odd && !isOdd || !odd && isOdd)
  8101. y = y.redNeg();
  8102. return this.point(x, y);
  8103. };
  8104. ShortCurve.prototype.validate = function validate(point) {
  8105. if (point.inf)
  8106. return true;
  8107. var x = point.x;
  8108. var y = point.y;
  8109. var ax = this.a.redMul(x);
  8110. var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
  8111. return y.redSqr().redISub(rhs).cmpn(0) === 0;
  8112. };
  8113. ShortCurve.prototype._endoWnafMulAdd =
  8114. function _endoWnafMulAdd(points, coeffs, jacobianResult) {
  8115. var npoints = this._endoWnafT1;
  8116. var ncoeffs = this._endoWnafT2;
  8117. for (var i = 0; i < points.length; i++) {
  8118. var split = this._endoSplit(coeffs[i]);
  8119. var p = points[i];
  8120. var beta = p._getBeta();
  8121. if (split.k1.negative) {
  8122. split.k1.ineg();
  8123. p = p.neg(true);
  8124. }
  8125. if (split.k2.negative) {
  8126. split.k2.ineg();
  8127. beta = beta.neg(true);
  8128. }
  8129. npoints[i * 2] = p;
  8130. npoints[i * 2 + 1] = beta;
  8131. ncoeffs[i * 2] = split.k1;
  8132. ncoeffs[i * 2 + 1] = split.k2;
  8133. }
  8134. var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);
  8135. // Clean-up references to points and coefficients
  8136. for (var j = 0; j < i * 2; j++) {
  8137. npoints[j] = null;
  8138. ncoeffs[j] = null;
  8139. }
  8140. return res;
  8141. };
  8142. function Point(curve, x, y, isRed) {
  8143. Base.BasePoint.call(this, curve, 'affine');
  8144. if (x === null && y === null) {
  8145. this.x = null;
  8146. this.y = null;
  8147. this.inf = true;
  8148. } else {
  8149. this.x = new BN(x, 16);
  8150. this.y = new BN(y, 16);
  8151. // Force redgomery representation when loading from JSON
  8152. if (isRed) {
  8153. this.x.forceRed(this.curve.red);
  8154. this.y.forceRed(this.curve.red);
  8155. }
  8156. if (!this.x.red)
  8157. this.x = this.x.toRed(this.curve.red);
  8158. if (!this.y.red)
  8159. this.y = this.y.toRed(this.curve.red);
  8160. this.inf = false;
  8161. }
  8162. }
  8163. inherits(Point, Base.BasePoint);
  8164. ShortCurve.prototype.point = function point(x, y, isRed) {
  8165. return new Point(this, x, y, isRed);
  8166. };
  8167. ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
  8168. return Point.fromJSON(this, obj, red);
  8169. };
  8170. Point.prototype._getBeta = function _getBeta() {
  8171. if (!this.curve.endo)
  8172. return;
  8173. var pre = this.precomputed;
  8174. if (pre && pre.beta)
  8175. return pre.beta;
  8176. var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
  8177. if (pre) {
  8178. var curve = this.curve;
  8179. var endoMul = function(p) {
  8180. return curve.point(p.x.redMul(curve.endo.beta), p.y);
  8181. };
  8182. pre.beta = beta;
  8183. beta.precomputed = {
  8184. beta: null,
  8185. naf: pre.naf && {
  8186. wnd: pre.naf.wnd,
  8187. points: pre.naf.points.map(endoMul)
  8188. },
  8189. doubles: pre.doubles && {
  8190. step: pre.doubles.step,
  8191. points: pre.doubles.points.map(endoMul)
  8192. }
  8193. };
  8194. }
  8195. return beta;
  8196. };
  8197. Point.prototype.toJSON = function toJSON() {
  8198. if (!this.precomputed)
  8199. return [ this.x, this.y ];
  8200. return [ this.x, this.y, this.precomputed && {
  8201. doubles: this.precomputed.doubles && {
  8202. step: this.precomputed.doubles.step,
  8203. points: this.precomputed.doubles.points.slice(1)
  8204. },
  8205. naf: this.precomputed.naf && {
  8206. wnd: this.precomputed.naf.wnd,
  8207. points: this.precomputed.naf.points.slice(1)
  8208. }
  8209. } ];
  8210. };
  8211. Point.fromJSON = function fromJSON(curve, obj, red) {
  8212. if (typeof obj === 'string')
  8213. obj = JSON.parse(obj);
  8214. var res = curve.point(obj[0], obj[1], red);
  8215. if (!obj[2])
  8216. return res;
  8217. function obj2point(obj) {
  8218. return curve.point(obj[0], obj[1], red);
  8219. }
  8220. var pre = obj[2];
  8221. res.precomputed = {
  8222. beta: null,
  8223. doubles: pre.doubles && {
  8224. step: pre.doubles.step,
  8225. points: [ res ].concat(pre.doubles.points.map(obj2point))
  8226. },
  8227. naf: pre.naf && {
  8228. wnd: pre.naf.wnd,
  8229. points: [ res ].concat(pre.naf.points.map(obj2point))
  8230. }
  8231. };
  8232. return res;
  8233. };
  8234. Point.prototype.inspect = function inspect() {
  8235. if (this.isInfinity())
  8236. return '<EC Point Infinity>';
  8237. return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
  8238. ' y: ' + this.y.fromRed().toString(16, 2) + '>';
  8239. };
  8240. Point.prototype.isInfinity = function isInfinity() {
  8241. return this.inf;
  8242. };
  8243. Point.prototype.add = function add(p) {
  8244. // O + P = P
  8245. if (this.inf)
  8246. return p;
  8247. // P + O = P
  8248. if (p.inf)
  8249. return this;
  8250. // P + P = 2P
  8251. if (this.eq(p))
  8252. return this.dbl();
  8253. // P + (-P) = O
  8254. if (this.neg().eq(p))
  8255. return this.curve.point(null, null);
  8256. // P + Q = O
  8257. if (this.x.cmp(p.x) === 0)
  8258. return this.curve.point(null, null);
  8259. var c = this.y.redSub(p.y);
  8260. if (c.cmpn(0) !== 0)
  8261. c = c.redMul(this.x.redSub(p.x).redInvm());
  8262. var nx = c.redSqr().redISub(this.x).redISub(p.x);
  8263. var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
  8264. return this.curve.point(nx, ny);
  8265. };
  8266. Point.prototype.dbl = function dbl() {
  8267. if (this.inf)
  8268. return this;
  8269. // 2P = O
  8270. var ys1 = this.y.redAdd(this.y);
  8271. if (ys1.cmpn(0) === 0)
  8272. return this.curve.point(null, null);
  8273. var a = this.curve.a;
  8274. var x2 = this.x.redSqr();
  8275. var dyinv = ys1.redInvm();
  8276. var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);
  8277. var nx = c.redSqr().redISub(this.x.redAdd(this.x));
  8278. var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
  8279. return this.curve.point(nx, ny);
  8280. };
  8281. Point.prototype.getX = function getX() {
  8282. return this.x.fromRed();
  8283. };
  8284. Point.prototype.getY = function getY() {
  8285. return this.y.fromRed();
  8286. };
  8287. Point.prototype.mul = function mul(k) {
  8288. k = new BN(k, 16);
  8289. if (this.isInfinity())
  8290. return this;
  8291. else if (this._hasDoubles(k))
  8292. return this.curve._fixedNafMul(this, k);
  8293. else if (this.curve.endo)
  8294. return this.curve._endoWnafMulAdd([ this ], [ k ]);
  8295. else
  8296. return this.curve._wnafMul(this, k);
  8297. };
  8298. Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
  8299. var points = [ this, p2 ];
  8300. var coeffs = [ k1, k2 ];
  8301. if (this.curve.endo)
  8302. return this.curve._endoWnafMulAdd(points, coeffs);
  8303. else
  8304. return this.curve._wnafMulAdd(1, points, coeffs, 2);
  8305. };
  8306. Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {
  8307. var points = [ this, p2 ];
  8308. var coeffs = [ k1, k2 ];
  8309. if (this.curve.endo)
  8310. return this.curve._endoWnafMulAdd(points, coeffs, true);
  8311. else
  8312. return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
  8313. };
  8314. Point.prototype.eq = function eq(p) {
  8315. return this === p ||
  8316. this.inf === p.inf &&
  8317. (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
  8318. };
  8319. Point.prototype.neg = function neg(_precompute) {
  8320. if (this.inf)
  8321. return this;
  8322. var res = this.curve.point(this.x, this.y.redNeg());
  8323. if (_precompute && this.precomputed) {
  8324. var pre = this.precomputed;
  8325. var negate = function(p) {
  8326. return p.neg();
  8327. };
  8328. res.precomputed = {
  8329. naf: pre.naf && {
  8330. wnd: pre.naf.wnd,
  8331. points: pre.naf.points.map(negate)
  8332. },
  8333. doubles: pre.doubles && {
  8334. step: pre.doubles.step,
  8335. points: pre.doubles.points.map(negate)
  8336. }
  8337. };
  8338. }
  8339. return res;
  8340. };
  8341. Point.prototype.toJ = function toJ() {
  8342. if (this.inf)
  8343. return this.curve.jpoint(null, null, null);
  8344. var res = this.curve.jpoint(this.x, this.y, this.curve.one);
  8345. return res;
  8346. };
  8347. function JPoint(curve, x, y, z) {
  8348. Base.BasePoint.call(this, curve, 'jacobian');
  8349. if (x === null && y === null && z === null) {
  8350. this.x = this.curve.one;
  8351. this.y = this.curve.one;
  8352. this.z = new BN(0);
  8353. } else {
  8354. this.x = new BN(x, 16);
  8355. this.y = new BN(y, 16);
  8356. this.z = new BN(z, 16);
  8357. }
  8358. if (!this.x.red)
  8359. this.x = this.x.toRed(this.curve.red);
  8360. if (!this.y.red)
  8361. this.y = this.y.toRed(this.curve.red);
  8362. if (!this.z.red)
  8363. this.z = this.z.toRed(this.curve.red);
  8364. this.zOne = this.z === this.curve.one;
  8365. }
  8366. inherits(JPoint, Base.BasePoint);
  8367. ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
  8368. return new JPoint(this, x, y, z);
  8369. };
  8370. JPoint.prototype.toP = function toP() {
  8371. if (this.isInfinity())
  8372. return this.curve.point(null, null);
  8373. var zinv = this.z.redInvm();
  8374. var zinv2 = zinv.redSqr();
  8375. var ax = this.x.redMul(zinv2);
  8376. var ay = this.y.redMul(zinv2).redMul(zinv);
  8377. return this.curve.point(ax, ay);
  8378. };
  8379. JPoint.prototype.neg = function neg() {
  8380. return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
  8381. };
  8382. JPoint.prototype.add = function add(p) {
  8383. // O + P = P
  8384. if (this.isInfinity())
  8385. return p;
  8386. // P + O = P
  8387. if (p.isInfinity())
  8388. return this;
  8389. // 12M + 4S + 7A
  8390. var pz2 = p.z.redSqr();
  8391. var z2 = this.z.redSqr();
  8392. var u1 = this.x.redMul(pz2);
  8393. var u2 = p.x.redMul(z2);
  8394. var s1 = this.y.redMul(pz2.redMul(p.z));
  8395. var s2 = p.y.redMul(z2.redMul(this.z));
  8396. var h = u1.redSub(u2);
  8397. var r = s1.redSub(s2);
  8398. if (h.cmpn(0) === 0) {
  8399. if (r.cmpn(0) !== 0)
  8400. return this.curve.jpoint(null, null, null);
  8401. else
  8402. return this.dbl();
  8403. }
  8404. var h2 = h.redSqr();
  8405. var h3 = h2.redMul(h);
  8406. var v = u1.redMul(h2);
  8407. var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
  8408. var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
  8409. var nz = this.z.redMul(p.z).redMul(h);
  8410. return this.curve.jpoint(nx, ny, nz);
  8411. };
  8412. JPoint.prototype.mixedAdd = function mixedAdd(p) {
  8413. // O + P = P
  8414. if (this.isInfinity())
  8415. return p.toJ();
  8416. // P + O = P
  8417. if (p.isInfinity())
  8418. return this;
  8419. // 8M + 3S + 7A
  8420. var z2 = this.z.redSqr();
  8421. var u1 = this.x;
  8422. var u2 = p.x.redMul(z2);
  8423. var s1 = this.y;
  8424. var s2 = p.y.redMul(z2).redMul(this.z);
  8425. var h = u1.redSub(u2);
  8426. var r = s1.redSub(s2);
  8427. if (h.cmpn(0) === 0) {
  8428. if (r.cmpn(0) !== 0)
  8429. return this.curve.jpoint(null, null, null);
  8430. else
  8431. return this.dbl();
  8432. }
  8433. var h2 = h.redSqr();
  8434. var h3 = h2.redMul(h);
  8435. var v = u1.redMul(h2);
  8436. var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
  8437. var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
  8438. var nz = this.z.redMul(h);
  8439. return this.curve.jpoint(nx, ny, nz);
  8440. };
  8441. JPoint.prototype.dblp = function dblp(pow) {
  8442. if (pow === 0)
  8443. return this;
  8444. if (this.isInfinity())
  8445. return this;
  8446. if (!pow)
  8447. return this.dbl();
  8448. if (this.curve.zeroA || this.curve.threeA) {
  8449. var r = this;
  8450. for (var i = 0; i < pow; i++)
  8451. r = r.dbl();
  8452. return r;
  8453. }
  8454. // 1M + 2S + 1A + N * (4S + 5M + 8A)
  8455. // N = 1 => 6M + 6S + 9A
  8456. var a = this.curve.a;
  8457. var tinv = this.curve.tinv;
  8458. var jx = this.x;
  8459. var jy = this.y;
  8460. var jz = this.z;
  8461. var jz4 = jz.redSqr().redSqr();
  8462. // Reuse results
  8463. var jyd = jy.redAdd(jy);
  8464. for (var i = 0; i < pow; i++) {
  8465. var jx2 = jx.redSqr();
  8466. var jyd2 = jyd.redSqr();
  8467. var jyd4 = jyd2.redSqr();
  8468. var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
  8469. var t1 = jx.redMul(jyd2);
  8470. var nx = c.redSqr().redISub(t1.redAdd(t1));
  8471. var t2 = t1.redISub(nx);
  8472. var dny = c.redMul(t2);
  8473. dny = dny.redIAdd(dny).redISub(jyd4);
  8474. var nz = jyd.redMul(jz);
  8475. if (i + 1 < pow)
  8476. jz4 = jz4.redMul(jyd4);
  8477. jx = nx;
  8478. jz = nz;
  8479. jyd = dny;
  8480. }
  8481. return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
  8482. };
  8483. JPoint.prototype.dbl = function dbl() {
  8484. if (this.isInfinity())
  8485. return this;
  8486. if (this.curve.zeroA)
  8487. return this._zeroDbl();
  8488. else if (this.curve.threeA)
  8489. return this._threeDbl();
  8490. else
  8491. return this._dbl();
  8492. };
  8493. JPoint.prototype._zeroDbl = function _zeroDbl() {
  8494. var nx;
  8495. var ny;
  8496. var nz;
  8497. // Z = 1
  8498. if (this.zOne) {
  8499. // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
  8500. // #doubling-mdbl-2007-bl
  8501. // 1M + 5S + 14A
  8502. // XX = X1^2
  8503. var xx = this.x.redSqr();
  8504. // YY = Y1^2
  8505. var yy = this.y.redSqr();
  8506. // YYYY = YY^2
  8507. var yyyy = yy.redSqr();
  8508. // S = 2 * ((X1 + YY)^2 - XX - YYYY)
  8509. var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
  8510. s = s.redIAdd(s);
  8511. // M = 3 * XX + a; a = 0
  8512. var m = xx.redAdd(xx).redIAdd(xx);
  8513. // T = M ^ 2 - 2*S
  8514. var t = m.redSqr().redISub(s).redISub(s);
  8515. // 8 * YYYY
  8516. var yyyy8 = yyyy.redIAdd(yyyy);
  8517. yyyy8 = yyyy8.redIAdd(yyyy8);
  8518. yyyy8 = yyyy8.redIAdd(yyyy8);
  8519. // X3 = T
  8520. nx = t;
  8521. // Y3 = M * (S - T) - 8 * YYYY
  8522. ny = m.redMul(s.redISub(t)).redISub(yyyy8);
  8523. // Z3 = 2*Y1
  8524. nz = this.y.redAdd(this.y);
  8525. } else {
  8526. // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
  8527. // #doubling-dbl-2009-l
  8528. // 2M + 5S + 13A
  8529. // A = X1^2
  8530. var a = this.x.redSqr();
  8531. // B = Y1^2
  8532. var b = this.y.redSqr();
  8533. // C = B^2
  8534. var c = b.redSqr();
  8535. // D = 2 * ((X1 + B)^2 - A - C)
  8536. var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
  8537. d = d.redIAdd(d);
  8538. // E = 3 * A
  8539. var e = a.redAdd(a).redIAdd(a);
  8540. // F = E^2
  8541. var f = e.redSqr();
  8542. // 8 * C
  8543. var c8 = c.redIAdd(c);
  8544. c8 = c8.redIAdd(c8);
  8545. c8 = c8.redIAdd(c8);
  8546. // X3 = F - 2 * D
  8547. nx = f.redISub(d).redISub(d);
  8548. // Y3 = E * (D - X3) - 8 * C
  8549. ny = e.redMul(d.redISub(nx)).redISub(c8);
  8550. // Z3 = 2 * Y1 * Z1
  8551. nz = this.y.redMul(this.z);
  8552. nz = nz.redIAdd(nz);
  8553. }
  8554. return this.curve.jpoint(nx, ny, nz);
  8555. };
  8556. JPoint.prototype._threeDbl = function _threeDbl() {
  8557. var nx;
  8558. var ny;
  8559. var nz;
  8560. // Z = 1
  8561. if (this.zOne) {
  8562. // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
  8563. // #doubling-mdbl-2007-bl
  8564. // 1M + 5S + 15A
  8565. // XX = X1^2
  8566. var xx = this.x.redSqr();
  8567. // YY = Y1^2
  8568. var yy = this.y.redSqr();
  8569. // YYYY = YY^2
  8570. var yyyy = yy.redSqr();
  8571. // S = 2 * ((X1 + YY)^2 - XX - YYYY)
  8572. var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
  8573. s = s.redIAdd(s);
  8574. // M = 3 * XX + a
  8575. var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
  8576. // T = M^2 - 2 * S
  8577. var t = m.redSqr().redISub(s).redISub(s);
  8578. // X3 = T
  8579. nx = t;
  8580. // Y3 = M * (S - T) - 8 * YYYY
  8581. var yyyy8 = yyyy.redIAdd(yyyy);
  8582. yyyy8 = yyyy8.redIAdd(yyyy8);
  8583. yyyy8 = yyyy8.redIAdd(yyyy8);
  8584. ny = m.redMul(s.redISub(t)).redISub(yyyy8);
  8585. // Z3 = 2 * Y1
  8586. nz = this.y.redAdd(this.y);
  8587. } else {
  8588. // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
  8589. // 3M + 5S
  8590. // delta = Z1^2
  8591. var delta = this.z.redSqr();
  8592. // gamma = Y1^2
  8593. var gamma = this.y.redSqr();
  8594. // beta = X1 * gamma
  8595. var beta = this.x.redMul(gamma);
  8596. // alpha = 3 * (X1 - delta) * (X1 + delta)
  8597. var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
  8598. alpha = alpha.redAdd(alpha).redIAdd(alpha);
  8599. // X3 = alpha^2 - 8 * beta
  8600. var beta4 = beta.redIAdd(beta);
  8601. beta4 = beta4.redIAdd(beta4);
  8602. var beta8 = beta4.redAdd(beta4);
  8603. nx = alpha.redSqr().redISub(beta8);
  8604. // Z3 = (Y1 + Z1)^2 - gamma - delta
  8605. nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
  8606. // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
  8607. var ggamma8 = gamma.redSqr();
  8608. ggamma8 = ggamma8.redIAdd(ggamma8);
  8609. ggamma8 = ggamma8.redIAdd(ggamma8);
  8610. ggamma8 = ggamma8.redIAdd(ggamma8);
  8611. ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
  8612. }
  8613. return this.curve.jpoint(nx, ny, nz);
  8614. };
  8615. JPoint.prototype._dbl = function _dbl() {
  8616. var a = this.curve.a;
  8617. // 4M + 6S + 10A
  8618. var jx = this.x;
  8619. var jy = this.y;
  8620. var jz = this.z;
  8621. var jz4 = jz.redSqr().redSqr();
  8622. var jx2 = jx.redSqr();
  8623. var jy2 = jy.redSqr();
  8624. var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
  8625. var jxd4 = jx.redAdd(jx);
  8626. jxd4 = jxd4.redIAdd(jxd4);
  8627. var t1 = jxd4.redMul(jy2);
  8628. var nx = c.redSqr().redISub(t1.redAdd(t1));
  8629. var t2 = t1.redISub(nx);
  8630. var jyd8 = jy2.redSqr();
  8631. jyd8 = jyd8.redIAdd(jyd8);
  8632. jyd8 = jyd8.redIAdd(jyd8);
  8633. jyd8 = jyd8.redIAdd(jyd8);
  8634. var ny = c.redMul(t2).redISub(jyd8);
  8635. var nz = jy.redAdd(jy).redMul(jz);
  8636. return this.curve.jpoint(nx, ny, nz);
  8637. };
  8638. JPoint.prototype.trpl = function trpl() {
  8639. if (!this.curve.zeroA)
  8640. return this.dbl().add(this);
  8641. // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
  8642. // 5M + 10S + ...
  8643. // XX = X1^2
  8644. var xx = this.x.redSqr();
  8645. // YY = Y1^2
  8646. var yy = this.y.redSqr();
  8647. // ZZ = Z1^2
  8648. var zz = this.z.redSqr();
  8649. // YYYY = YY^2
  8650. var yyyy = yy.redSqr();
  8651. // M = 3 * XX + a * ZZ2; a = 0
  8652. var m = xx.redAdd(xx).redIAdd(xx);
  8653. // MM = M^2
  8654. var mm = m.redSqr();
  8655. // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
  8656. var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
  8657. e = e.redIAdd(e);
  8658. e = e.redAdd(e).redIAdd(e);
  8659. e = e.redISub(mm);
  8660. // EE = E^2
  8661. var ee = e.redSqr();
  8662. // T = 16*YYYY
  8663. var t = yyyy.redIAdd(yyyy);
  8664. t = t.redIAdd(t);
  8665. t = t.redIAdd(t);
  8666. t = t.redIAdd(t);
  8667. // U = (M + E)^2 - MM - EE - T
  8668. var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
  8669. // X3 = 4 * (X1 * EE - 4 * YY * U)
  8670. var yyu4 = yy.redMul(u);
  8671. yyu4 = yyu4.redIAdd(yyu4);
  8672. yyu4 = yyu4.redIAdd(yyu4);
  8673. var nx = this.x.redMul(ee).redISub(yyu4);
  8674. nx = nx.redIAdd(nx);
  8675. nx = nx.redIAdd(nx);
  8676. // Y3 = 8 * Y1 * (U * (T - U) - E * EE)
  8677. var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
  8678. ny = ny.redIAdd(ny);
  8679. ny = ny.redIAdd(ny);
  8680. ny = ny.redIAdd(ny);
  8681. // Z3 = (Z1 + E)^2 - ZZ - EE
  8682. var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);
  8683. return this.curve.jpoint(nx, ny, nz);
  8684. };
  8685. JPoint.prototype.mul = function mul(k, kbase) {
  8686. k = new BN(k, kbase);
  8687. return this.curve._wnafMul(this, k);
  8688. };
  8689. JPoint.prototype.eq = function eq(p) {
  8690. if (p.type === 'affine')
  8691. return this.eq(p.toJ());
  8692. if (this === p)
  8693. return true;
  8694. // x1 * z2^2 == x2 * z1^2
  8695. var z2 = this.z.redSqr();
  8696. var pz2 = p.z.redSqr();
  8697. if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)
  8698. return false;
  8699. // y1 * z2^3 == y2 * z1^3
  8700. var z3 = z2.redMul(this.z);
  8701. var pz3 = pz2.redMul(p.z);
  8702. return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
  8703. };
  8704. JPoint.prototype.eqXToP = function eqXToP(x) {
  8705. var zs = this.z.redSqr();
  8706. var rx = x.toRed(this.curve.red).redMul(zs);
  8707. if (this.x.cmp(rx) === 0)
  8708. return true;
  8709. var xc = x.clone();
  8710. var t = this.curve.redN.redMul(zs);
  8711. for (;;) {
  8712. xc.iadd(this.curve.n);
  8713. if (xc.cmp(this.curve.p) >= 0)
  8714. return false;
  8715. rx.redIAdd(t);
  8716. if (this.x.cmp(rx) === 0)
  8717. return true;
  8718. }
  8719. };
  8720. JPoint.prototype.inspect = function inspect() {
  8721. if (this.isInfinity())
  8722. return '<EC JPoint Infinity>';
  8723. return '<EC JPoint x: ' + this.x.toString(16, 2) +
  8724. ' y: ' + this.y.toString(16, 2) +
  8725. ' z: ' + this.z.toString(16, 2) + '>';
  8726. };
  8727. JPoint.prototype.isInfinity = function isInfinity() {
  8728. // XXX This code assumes that zero is always zero in red
  8729. return this.z.cmpn(0) === 0;
  8730. };
  8731. },{"../utils":32,"./base":19,"bn.js":16,"inherits":47}],24:[function(require,module,exports){
  8732. 'use strict';
  8733. var curves = exports;
  8734. var hash = require('hash.js');
  8735. var curve = require('./curve');
  8736. var utils = require('./utils');
  8737. var assert = utils.assert;
  8738. function PresetCurve(options) {
  8739. if (options.type === 'short')
  8740. this.curve = new curve.short(options);
  8741. else if (options.type === 'edwards')
  8742. this.curve = new curve.edwards(options);
  8743. else if (options.type === 'mont')
  8744. this.curve = new curve.mont(options);
  8745. else throw new Error('Unknown curve type.');
  8746. this.g = this.curve.g;
  8747. this.n = this.curve.n;
  8748. this.hash = options.hash;
  8749. assert(this.g.validate(), 'Invalid curve');
  8750. assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, n*G != O');
  8751. }
  8752. curves.PresetCurve = PresetCurve;
  8753. function defineCurve(name, options) {
  8754. Object.defineProperty(curves, name, {
  8755. configurable: true,
  8756. enumerable: true,
  8757. get: function() {
  8758. var curve = new PresetCurve(options);
  8759. Object.defineProperty(curves, name, {
  8760. configurable: true,
  8761. enumerable: true,
  8762. value: curve
  8763. });
  8764. return curve;
  8765. }
  8766. });
  8767. }
  8768. defineCurve('p192', {
  8769. type: 'short',
  8770. prime: 'p192',
  8771. p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
  8772. a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
  8773. b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
  8774. n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
  8775. hash: hash.sha256,
  8776. gRed: false,
  8777. g: [
  8778. '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
  8779. '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'
  8780. ]
  8781. });
  8782. defineCurve('p224', {
  8783. type: 'short',
  8784. prime: 'p224',
  8785. p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
  8786. a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
  8787. b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
  8788. n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
  8789. hash: hash.sha256,
  8790. gRed: false,
  8791. g: [
  8792. 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
  8793. 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'
  8794. ]
  8795. });
  8796. defineCurve('p256', {
  8797. type: 'short',
  8798. prime: null,
  8799. p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
  8800. a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
  8801. b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
  8802. n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
  8803. hash: hash.sha256,
  8804. gRed: false,
  8805. g: [
  8806. '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
  8807. '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'
  8808. ]
  8809. });
  8810. defineCurve('p384', {
  8811. type: 'short',
  8812. prime: null,
  8813. p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
  8814. 'fffffffe ffffffff 00000000 00000000 ffffffff',
  8815. a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
  8816. 'fffffffe ffffffff 00000000 00000000 fffffffc',
  8817. b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +
  8818. '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',
  8819. n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +
  8820. 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',
  8821. hash: hash.sha384,
  8822. gRed: false,
  8823. g: [
  8824. 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +
  8825. '5502f25d bf55296c 3a545e38 72760ab7',
  8826. '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +
  8827. '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'
  8828. ]
  8829. });
  8830. defineCurve('p521', {
  8831. type: 'short',
  8832. prime: null,
  8833. p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
  8834. 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
  8835. 'ffffffff ffffffff ffffffff ffffffff ffffffff',
  8836. a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
  8837. 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
  8838. 'ffffffff ffffffff ffffffff ffffffff fffffffc',
  8839. b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +
  8840. '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +
  8841. '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',
  8842. n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
  8843. 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +
  8844. 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',
  8845. hash: hash.sha512,
  8846. gRed: false,
  8847. g: [
  8848. '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +
  8849. '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +
  8850. 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',
  8851. '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +
  8852. '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +
  8853. '3fad0761 353c7086 a272c240 88be9476 9fd16650'
  8854. ]
  8855. });
  8856. // https://tools.ietf.org/html/rfc7748#section-4.1
  8857. defineCurve('curve25519', {
  8858. type: 'mont',
  8859. prime: 'p25519',
  8860. p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
  8861. a: '76d06',
  8862. b: '1',
  8863. n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
  8864. cofactor: '8',
  8865. hash: hash.sha256,
  8866. gRed: false,
  8867. g: [
  8868. '9'
  8869. ]
  8870. });
  8871. defineCurve('ed25519', {
  8872. type: 'edwards',
  8873. prime: 'p25519',
  8874. p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
  8875. a: '-1',
  8876. c: '1',
  8877. // -121665 * (121666^(-1)) (mod P)
  8878. d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
  8879. n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
  8880. cofactor: '8',
  8881. hash: hash.sha256,
  8882. gRed: false,
  8883. g: [
  8884. '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',
  8885. // 4/5
  8886. '6666666666666666666666666666666666666666666666666666666666666658'
  8887. ]
  8888. });
  8889. // https://tools.ietf.org/html/rfc5639#section-3.4
  8890. defineCurve('brainpoolP256r1', {
  8891. type: 'short',
  8892. prime: null,
  8893. p: 'A9FB57DB A1EEA9BC 3E660A90 9D838D72 6E3BF623 D5262028 2013481D 1F6E5377',
  8894. a: '7D5A0975 FC2C3057 EEF67530 417AFFE7 FB8055C1 26DC5C6C E94A4B44 F330B5D9',
  8895. b: '26DC5C6C E94A4B44 F330B5D9 BBD77CBF 95841629 5CF7E1CE 6BCCDC18 FF8C07B6',
  8896. n: 'A9FB57DB A1EEA9BC 3E660A90 9D838D71 8C397AA3 B561A6F7 901E0E82 974856A7',
  8897. hash: hash.sha256, // or 384, or 512
  8898. gRed: false,
  8899. g: [
  8900. '8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262',
  8901. '547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997'
  8902. ]
  8903. });
  8904. // https://tools.ietf.org/html/rfc5639#section-3.6
  8905. defineCurve('brainpoolP384r1', {
  8906. type: 'short',
  8907. prime: null,
  8908. p: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B4 12B1DA19 7FB71123' +
  8909. 'ACD3A729 901D1A71 87470013 3107EC53',
  8910. a: '7BC382C6 3D8C150C 3C72080A CE05AFA0 C2BEA28E 4FB22787 139165EF BA91F90F' +
  8911. '8AA5814A 503AD4EB 04A8C7DD 22CE2826',
  8912. b: '04A8C7DD 22CE2826 8B39B554 16F0447C 2FB77DE1 07DCD2A6 2E880EA5 3EEB62D5' +
  8913. '7CB43902 95DBC994 3AB78696 FA504C11',
  8914. n: '8CB91E82 A3386D28 0F5D6F7E 50E641DF 152F7109 ED5456B3 1F166E6C AC0425A7' +
  8915. 'CF3AB6AF 6B7FC310 3B883202 E9046565',
  8916. hash: hash.sha384, // or 512
  8917. gRed: false,
  8918. g: [
  8919. '1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10' +
  8920. 'E8E826E03436D646AAEF87B2E247D4AF1E',
  8921. '8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129' +
  8922. '280E4646217791811142820341263C5315'
  8923. ]
  8924. });
  8925. // https://tools.ietf.org/html/rfc5639#section-3.7
  8926. defineCurve('brainpoolP512r1', {
  8927. type: 'short',
  8928. prime: null,
  8929. p: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330871' +
  8930. '7D4D9B00 9BC66842 AECDA12A E6A380E6 2881FF2F 2D82C685 28AA6056 583A48F3',
  8931. a: '7830A331 8B603B89 E2327145 AC234CC5 94CBDD8D 3DF91610 A83441CA EA9863BC' +
  8932. '2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7 2BF2C7B9 E7C1AC4D 77FC94CA',
  8933. b: '3DF91610 A83441CA EA9863BC 2DED5D5A A8253AA1 0A2EF1C9 8B9AC8B5 7F1117A7' +
  8934. '2BF2C7B9 E7C1AC4D 77FC94CA DC083E67 984050B7 5EBAE5DD 2809BD63 8016F723',
  8935. n: 'AADD9DB8 DBE9C48B 3FD4E6AE 33C9FC07 CB308DB3 B3C9D20E D6639CCA 70330870' +
  8936. '553E5C41 4CA92619 41866119 7FAC1047 1DB1D381 085DDADD B5879682 9CA90069',
  8937. hash: hash.sha512,
  8938. gRed: false,
  8939. g: [
  8940. '81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D009' +
  8941. '8EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822',
  8942. '7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F81' +
  8943. '11B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892'
  8944. ]
  8945. });
  8946. // https://en.bitcoin.it/wiki/Secp256k1
  8947. var pre;
  8948. try {
  8949. pre = require('./precomputed/secp256k1');
  8950. } catch (e) {
  8951. pre = undefined;
  8952. }
  8953. defineCurve('secp256k1', {
  8954. type: 'short',
  8955. prime: 'k256',
  8956. p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
  8957. a: '0',
  8958. b: '7',
  8959. n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
  8960. h: '1',
  8961. hash: hash.sha256,
  8962. // Precomputed endomorphism
  8963. beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
  8964. lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
  8965. basis: [
  8966. {
  8967. a: '3086d221a7d46bcde86c90e49284eb15',
  8968. b: '-e4437ed6010e88286f547fa90abfe4c3'
  8969. },
  8970. {
  8971. a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
  8972. b: '3086d221a7d46bcde86c90e49284eb15'
  8973. }
  8974. ],
  8975. gRed: false,
  8976. g: [
  8977. '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
  8978. '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
  8979. pre
  8980. ]
  8981. });
  8982. },{"./curve":21,"./precomputed/secp256k1":31,"./utils":32,"hash.js":34}],25:[function(require,module,exports){
  8983. 'use strict';
  8984. var BN = require('bn.js');
  8985. var HmacDRBG = require('hmac-drbg');
  8986. var utils = require('../utils');
  8987. var curves = require('../curves');
  8988. var rand = require('brorand');
  8989. var assert = utils.assert;
  8990. var KeyPair = require('./key');
  8991. var Signature = require('./signature');
  8992. function EC(options) {
  8993. if (!(this instanceof EC))
  8994. return new EC(options);
  8995. // Shortcut `elliptic.ec(curve-name)`
  8996. if (typeof options === 'string') {
  8997. assert(curves.hasOwnProperty(options), 'Unknown curve ' + options);
  8998. options = curves[options];
  8999. }
  9000. // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
  9001. if (options instanceof curves.PresetCurve)
  9002. options = { curve: options };
  9003. this.curve = options.curve.curve;
  9004. this.n = this.curve.n;
  9005. this.nh = this.n.ushrn(1);
  9006. this.g = this.curve.g;
  9007. // Point on curve
  9008. this.g = options.curve.g;
  9009. this.g.precompute(options.curve.n.bitLength() + 1);
  9010. // Hash function for DRBG
  9011. this.hash = options.hash || options.curve.hash;
  9012. }
  9013. module.exports = EC;
  9014. EC.prototype.keyPair = function keyPair(options) {
  9015. return new KeyPair(this, options);
  9016. };
  9017. EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
  9018. return KeyPair.fromPrivate(this, priv, enc);
  9019. };
  9020. EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
  9021. return KeyPair.fromPublic(this, pub, enc);
  9022. };
  9023. EC.prototype.genKeyPair = function genKeyPair(options) {
  9024. if (!options)
  9025. options = {};
  9026. // Instantiate Hmac_DRBG
  9027. var drbg = new HmacDRBG({
  9028. hash: this.hash,
  9029. pers: options.pers,
  9030. persEnc: options.persEnc || 'utf8',
  9031. entropy: options.entropy || rand(this.hash.hmacStrength),
  9032. entropyEnc: options.entropy && options.entropyEnc || 'utf8',
  9033. nonce: this.n.toArray()
  9034. });
  9035. // Key generation for curve25519 is simpler
  9036. if (this.curve.type === 'mont') {
  9037. var priv = new BN(drbg.generate(32));
  9038. return this.keyFromPrivate(priv);
  9039. }
  9040. var bytes = this.n.byteLength();
  9041. var ns2 = this.n.sub(new BN(2));
  9042. do {
  9043. var priv = new BN(drbg.generate(bytes));
  9044. if (priv.cmp(ns2) > 0)
  9045. continue;
  9046. priv.iaddn(1);
  9047. return this.keyFromPrivate(priv);
  9048. } while (true);
  9049. };
  9050. EC.prototype._truncateToN = function truncateToN(msg, truncOnly, bitSize) {
  9051. bitSize = bitSize || msg.byteLength() * 8;
  9052. var delta = bitSize - this.n.bitLength();
  9053. if (delta > 0)
  9054. msg = msg.ushrn(delta);
  9055. if (!truncOnly && msg.cmp(this.n) >= 0)
  9056. return msg.sub(this.n);
  9057. else
  9058. return msg;
  9059. };
  9060. EC.prototype.truncateMsg = function truncateMSG(msg) {
  9061. // Bit size is only determined correctly for Uint8Arrays and hex strings
  9062. var bitSize;
  9063. if (msg instanceof Uint8Array) {
  9064. bitSize = msg.byteLength * 8;
  9065. msg = this._truncateToN(new BN(msg, 16), false, bitSize);
  9066. } else if (typeof msg === 'string') {
  9067. bitSize = msg.length * 4;
  9068. msg = this._truncateToN(new BN(msg, 16), false, bitSize);
  9069. } else {
  9070. msg = this._truncateToN(new BN(msg, 16));
  9071. }
  9072. return msg;
  9073. }
  9074. EC.prototype.sign = function sign(msg, key, enc, options) {
  9075. if (typeof enc === 'object') {
  9076. options = enc;
  9077. enc = null;
  9078. }
  9079. if (!options)
  9080. options = {};
  9081. key = this.keyFromPrivate(key, enc);
  9082. msg = this.truncateMsg(msg);
  9083. // Zero-extend key to provide enough entropy
  9084. var bytes = this.n.byteLength();
  9085. var bkey = key.getPrivate().toArray('be', bytes);
  9086. // Zero-extend nonce to have the same byte size as N
  9087. var nonce = msg.toArray('be', bytes);
  9088. // Instantiate Hmac_DRBG
  9089. var drbg = new HmacDRBG({
  9090. hash: this.hash,
  9091. entropy: bkey,
  9092. nonce: nonce,
  9093. pers: options.pers,
  9094. persEnc: options.persEnc || 'utf8'
  9095. });
  9096. // Number of bytes to generate
  9097. var ns1 = this.n.sub(new BN(1));
  9098. for (var iter = 0; true; iter++) {
  9099. var k = options.k ?
  9100. options.k(iter) :
  9101. new BN(drbg.generate(this.n.byteLength()));
  9102. k = this._truncateToN(k, true);
  9103. if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
  9104. continue;
  9105. var kp = this.g.mul(k);
  9106. if (kp.isInfinity())
  9107. continue;
  9108. var kpX = kp.getX();
  9109. var r = kpX.umod(this.n);
  9110. if (r.cmpn(0) === 0)
  9111. continue;
  9112. var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));
  9113. s = s.umod(this.n);
  9114. if (s.cmpn(0) === 0)
  9115. continue;
  9116. var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |
  9117. (kpX.cmp(r) !== 0 ? 2 : 0);
  9118. // Use complement of `s`, if it is > `n / 2`
  9119. if (options.canonical && s.cmp(this.nh) > 0) {
  9120. s = this.n.sub(s);
  9121. recoveryParam ^= 1;
  9122. }
  9123. return new Signature({ r: r, s: s, recoveryParam: recoveryParam });
  9124. }
  9125. };
  9126. EC.prototype.verify = function verify(msg, signature, key, enc) {
  9127. key = this.keyFromPublic(key, enc);
  9128. signature = new Signature(signature, 'hex');
  9129. // Fallback to the old code
  9130. var ret = this._verify(this.truncateMsg(msg), signature, key) ||
  9131. this._verify(this._truncateToN(new BN(msg, 16)), signature, key);
  9132. return ret;
  9133. };
  9134. EC.prototype._verify = function _verify(msg, signature, key) {
  9135. // Perform primitive values validation
  9136. var r = signature.r;
  9137. var s = signature.s;
  9138. if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)
  9139. return false;
  9140. if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
  9141. return false;
  9142. // Validate signature
  9143. var sinv = s.invm(this.n);
  9144. var u1 = sinv.mul(msg).umod(this.n);
  9145. var u2 = sinv.mul(r).umod(this.n);
  9146. if (!this.curve._maxwellTrick) {
  9147. var p = this.g.mulAdd(u1, key.getPublic(), u2);
  9148. if (p.isInfinity())
  9149. return false;
  9150. return p.getX().umod(this.n).cmp(r) === 0;
  9151. }
  9152. // NOTE: Greg Maxwell's trick, inspired by:
  9153. // https://git.io/vad3K
  9154. var p = this.g.jmulAdd(u1, key.getPublic(), u2);
  9155. if (p.isInfinity())
  9156. return false;
  9157. // Compare `p.x` of Jacobian point with `r`,
  9158. // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the
  9159. // inverse of `p.z^2`
  9160. return p.eqXToP(r);
  9161. };
  9162. EC.prototype.recoverPubKey = function(msg, signature, j, enc) {
  9163. assert((3 & j) === j, 'The recovery param is more than two bits');
  9164. signature = new Signature(signature, enc);
  9165. var n = this.n;
  9166. var e = new BN(msg);
  9167. var r = signature.r;
  9168. var s = signature.s;
  9169. // A set LSB signifies that the y-coordinate is odd
  9170. var isYOdd = j & 1;
  9171. var isSecondKey = j >> 1;
  9172. if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)
  9173. throw new Error('Unable to find sencond key candinate');
  9174. // 1.1. Let x = r + jn.
  9175. if (isSecondKey)
  9176. r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);
  9177. else
  9178. r = this.curve.pointFromX(r, isYOdd);
  9179. var rInv = signature.r.invm(n);
  9180. var s1 = n.sub(e).mul(rInv).umod(n);
  9181. var s2 = s.mul(rInv).umod(n);
  9182. // 1.6.1 Compute Q = r^-1 (sR - eG)
  9183. // Q = r^-1 (sR + -eG)
  9184. return this.g.mulAdd(s1, r, s2);
  9185. };
  9186. EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {
  9187. signature = new Signature(signature, enc);
  9188. if (signature.recoveryParam !== null)
  9189. return signature.recoveryParam;
  9190. for (var i = 0; i < 4; i++) {
  9191. var Qprime;
  9192. try {
  9193. Qprime = this.recoverPubKey(e, signature, i);
  9194. } catch (e) {
  9195. continue;
  9196. }
  9197. if (Qprime.eq(Q))
  9198. return i;
  9199. }
  9200. throw new Error('Unable to find valid recovery factor');
  9201. };
  9202. },{"../curves":24,"../utils":32,"./key":26,"./signature":27,"bn.js":16,"brorand":17,"hmac-drbg":46}],26:[function(require,module,exports){
  9203. 'use strict';
  9204. var BN = require('bn.js');
  9205. var utils = require('../utils');
  9206. var assert = utils.assert;
  9207. function KeyPair(ec, options) {
  9208. this.ec = ec;
  9209. this.priv = null;
  9210. this.pub = null;
  9211. // KeyPair(ec, { priv: ..., pub: ... })
  9212. if (options.priv)
  9213. this._importPrivate(options.priv, options.privEnc);
  9214. if (options.pub)
  9215. this._importPublic(options.pub, options.pubEnc);
  9216. }
  9217. module.exports = KeyPair;
  9218. KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
  9219. if (pub instanceof KeyPair)
  9220. return pub;
  9221. return new KeyPair(ec, {
  9222. pub: pub,
  9223. pubEnc: enc
  9224. });
  9225. };
  9226. KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
  9227. if (priv instanceof KeyPair)
  9228. return priv;
  9229. return new KeyPair(ec, {
  9230. priv: priv,
  9231. privEnc: enc
  9232. });
  9233. };
  9234. // TODO: should not validate for X25519
  9235. KeyPair.prototype.validate = function validate() {
  9236. var pub = this.getPublic();
  9237. if (pub.isInfinity())
  9238. return { result: false, reason: 'Invalid public key' };
  9239. if (!pub.validate())
  9240. return { result: false, reason: 'Public key is not a point' };
  9241. if (!pub.mul(this.ec.curve.n).isInfinity())
  9242. return { result: false, reason: 'Public key * N != O' };
  9243. return { result: true, reason: null };
  9244. };
  9245. KeyPair.prototype.getPublic = function getPublic(enc, compact) {
  9246. if (!this.pub)
  9247. this.pub = this.ec.g.mul(this.priv);
  9248. if (!enc)
  9249. return this.pub;
  9250. return this.pub.encode(enc, compact);
  9251. };
  9252. KeyPair.prototype.getPrivate = function getPrivate(enc) {
  9253. if (enc === 'hex')
  9254. return this.priv.toString(16, 2);
  9255. else
  9256. return this.priv;
  9257. };
  9258. KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
  9259. this.priv = new BN(key, enc || 16);
  9260. // For Curve25519/Curve448 we have a specific procedure.
  9261. // TODO Curve448
  9262. if (this.ec.curve.type === 'mont') {
  9263. var one = this.ec.curve.one;
  9264. var mask = one.ushln(255 - 3).sub(one).ushln(3);
  9265. this.priv = this.priv.or(one.ushln(255 - 1));
  9266. this.priv = this.priv.and(mask);
  9267. } else
  9268. // Ensure that the priv won't be bigger than n, otherwise we may fail
  9269. // in fixed multiplication method
  9270. this.priv = this.priv.umod(this.ec.curve.n);
  9271. };
  9272. KeyPair.prototype._importPublic = function _importPublic(key, enc) {
  9273. if (key.x || key.y) {
  9274. // Montgomery points only have an `x` coordinate.
  9275. // Weierstrass/Edwards points on the other hand have both `x` and
  9276. // `y` coordinates.
  9277. if (this.ec.curve.type === 'mont') {
  9278. assert(key.x, 'Need x coordinate');
  9279. } else if (this.ec.curve.type === 'short' ||
  9280. this.ec.curve.type === 'edwards') {
  9281. assert(key.x && key.y, 'Need both x and y coordinate');
  9282. }
  9283. this.pub = this.ec.curve.point(key.x, key.y);
  9284. return;
  9285. }
  9286. this.pub = this.ec.curve.decodePoint(key, enc);
  9287. };
  9288. // ECDH
  9289. KeyPair.prototype.derive = function derive(pub) {
  9290. return pub.mul(this.priv).getX();
  9291. };
  9292. // ECDSA
  9293. KeyPair.prototype.sign = function sign(msg, enc, options) {
  9294. return this.ec.sign(msg, this, enc, options);
  9295. };
  9296. KeyPair.prototype.verify = function verify(msg, signature) {
  9297. return this.ec.verify(msg, signature, this);
  9298. };
  9299. KeyPair.prototype.inspect = function inspect() {
  9300. return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) +
  9301. ' pub: ' + (this.pub && this.pub.inspect()) + ' >';
  9302. };
  9303. },{"../utils":32,"bn.js":16}],27:[function(require,module,exports){
  9304. 'use strict';
  9305. var BN = require('bn.js');
  9306. var utils = require('../utils');
  9307. var assert = utils.assert;
  9308. function Signature(options, enc) {
  9309. if (options instanceof Signature)
  9310. return options;
  9311. if (this._importDER(options, enc))
  9312. return;
  9313. assert(options.r && options.s, 'Signature without r or s');
  9314. this.r = new BN(options.r, 16);
  9315. this.s = new BN(options.s, 16);
  9316. if (options.recoveryParam === undefined)
  9317. this.recoveryParam = null;
  9318. else
  9319. this.recoveryParam = options.recoveryParam;
  9320. }
  9321. module.exports = Signature;
  9322. function Position() {
  9323. this.place = 0;
  9324. }
  9325. function getLength(buf, p) {
  9326. var initial = buf[p.place++];
  9327. if (!(initial & 0x80)) {
  9328. return initial;
  9329. }
  9330. var octetLen = initial & 0xf;
  9331. var val = 0;
  9332. for (var i = 0, off = p.place; i < octetLen; i++, off++) {
  9333. val <<= 8;
  9334. val |= buf[off];
  9335. }
  9336. p.place = off;
  9337. return val;
  9338. }
  9339. function rmPadding(buf) {
  9340. var i = 0;
  9341. var len = buf.length - 1;
  9342. while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {
  9343. i++;
  9344. }
  9345. if (i === 0) {
  9346. return buf;
  9347. }
  9348. return buf.slice(i);
  9349. }
  9350. Signature.prototype._importDER = function _importDER(data, enc) {
  9351. data = utils.toArray(data, enc);
  9352. var p = new Position();
  9353. if (data[p.place++] !== 0x30) {
  9354. return false;
  9355. }
  9356. var len = getLength(data, p);
  9357. if ((len + p.place) !== data.length) {
  9358. return false;
  9359. }
  9360. if (data[p.place++] !== 0x02) {
  9361. return false;
  9362. }
  9363. var rlen = getLength(data, p);
  9364. var r = data.slice(p.place, rlen + p.place);
  9365. p.place += rlen;
  9366. if (data[p.place++] !== 0x02) {
  9367. return false;
  9368. }
  9369. var slen = getLength(data, p);
  9370. if (data.length !== slen + p.place) {
  9371. return false;
  9372. }
  9373. var s = data.slice(p.place, slen + p.place);
  9374. if (r[0] === 0 && (r[1] & 0x80)) {
  9375. r = r.slice(1);
  9376. }
  9377. if (s[0] === 0 && (s[1] & 0x80)) {
  9378. s = s.slice(1);
  9379. }
  9380. this.r = new BN(r);
  9381. this.s = new BN(s);
  9382. this.recoveryParam = null;
  9383. return true;
  9384. };
  9385. function constructLength(arr, len) {
  9386. if (len < 0x80) {
  9387. arr.push(len);
  9388. return;
  9389. }
  9390. var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);
  9391. arr.push(octets | 0x80);
  9392. while (--octets) {
  9393. arr.push((len >>> (octets << 3)) & 0xff);
  9394. }
  9395. arr.push(len);
  9396. }
  9397. Signature.prototype.toDER = function toDER(enc) {
  9398. var r = this.r.toArray();
  9399. var s = this.s.toArray();
  9400. // Pad values
  9401. if (r[0] & 0x80)
  9402. r = [ 0 ].concat(r);
  9403. // Pad values
  9404. if (s[0] & 0x80)
  9405. s = [ 0 ].concat(s);
  9406. r = rmPadding(r);
  9407. s = rmPadding(s);
  9408. while (!s[0] && !(s[1] & 0x80)) {
  9409. s = s.slice(1);
  9410. }
  9411. var arr = [ 0x02 ];
  9412. constructLength(arr, r.length);
  9413. arr = arr.concat(r);
  9414. arr.push(0x02);
  9415. constructLength(arr, s.length);
  9416. var backHalf = arr.concat(s);
  9417. var res = [ 0x30 ];
  9418. constructLength(res, backHalf.length);
  9419. res = res.concat(backHalf);
  9420. return utils.encode(res, enc);
  9421. };
  9422. },{"../utils":32,"bn.js":16}],28:[function(require,module,exports){
  9423. 'use strict';
  9424. var hash = require('hash.js');
  9425. var HmacDRBG = require('hmac-drbg');
  9426. var rand = require('brorand');
  9427. var curves = require('../curves');
  9428. var utils = require('../utils');
  9429. var assert = utils.assert;
  9430. var parseBytes = utils.parseBytes;
  9431. var KeyPair = require('./key');
  9432. var Signature = require('./signature');
  9433. function EDDSA(curve) {
  9434. assert(curve === 'ed25519', 'only tested with ed25519 so far');
  9435. if (!(this instanceof EDDSA))
  9436. return new EDDSA(curve);
  9437. var curve = curves[curve].curve;
  9438. this.curve = curve;
  9439. this.g = curve.g;
  9440. this.g.precompute(curve.n.bitLength() + 1);
  9441. this.pointClass = curve.point().constructor;
  9442. this.encodingLength = Math.ceil(curve.n.bitLength() / 8);
  9443. this.hash = hash.sha512;
  9444. }
  9445. module.exports = EDDSA;
  9446. /**
  9447. * @param {Array|String} message - message bytes
  9448. * @param {Array|String|KeyPair} secret - secret bytes or a keypair
  9449. * @returns {Signature} - signature
  9450. */
  9451. EDDSA.prototype.sign = function sign(message, secret) {
  9452. message = parseBytes(message);
  9453. var key = this.keyFromSecret(secret);
  9454. var r = this.hashInt(key.messagePrefix(), message);
  9455. var R = this.g.mul(r);
  9456. var Rencoded = this.encodePoint(R);
  9457. var s_ = this.hashInt(Rencoded, key.pubBytes(), message)
  9458. .mul(key.priv());
  9459. var S = r.add(s_).umod(this.curve.n);
  9460. return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });
  9461. };
  9462. /**
  9463. * @param {Array} message - message bytes
  9464. * @param {Array|String|Signature} sig - sig bytes
  9465. * @param {Array|String|Point|KeyPair} pub - public key
  9466. * @returns {Boolean} - true if public key matches sig of message
  9467. */
  9468. EDDSA.prototype.verify = function verify(message, sig, pub) {
  9469. message = parseBytes(message);
  9470. sig = this.makeSignature(sig);
  9471. var key = this.keyFromPublic(pub);
  9472. var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);
  9473. var SG = this.g.mul(sig.S());
  9474. var RplusAh = sig.R().add(key.pub().mul(h));
  9475. return RplusAh.eq(SG);
  9476. };
  9477. EDDSA.prototype.hashInt = function hashInt() {
  9478. var hash = this.hash();
  9479. for (var i = 0; i < arguments.length; i++)
  9480. hash.update(arguments[i]);
  9481. return utils.intFromLE(hash.digest()).umod(this.curve.n);
  9482. };
  9483. EDDSA.prototype.keyPair = function keyPair(options) {
  9484. return new KeyPair(this, options);
  9485. };
  9486. EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {
  9487. return KeyPair.fromPublic(this, pub);
  9488. };
  9489. EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {
  9490. return KeyPair.fromSecret(this, secret);
  9491. };
  9492. EDDSA.prototype.genKeyPair = function genKeyPair(options) {
  9493. if (!options)
  9494. options = {};
  9495. // Instantiate Hmac_DRBG
  9496. var drbg = new HmacDRBG({
  9497. hash: this.hash,
  9498. pers: options.pers,
  9499. persEnc: options.persEnc || 'utf8',
  9500. entropy: options.entropy || rand(this.hash.hmacStrength),
  9501. entropyEnc: options.entropy && options.entropyEnc || 'utf8',
  9502. nonce: this.curve.n.toArray()
  9503. });
  9504. return this.keyFromSecret(drbg.generate(32));
  9505. };
  9506. EDDSA.prototype.makeSignature = function makeSignature(sig) {
  9507. if (sig instanceof Signature)
  9508. return sig;
  9509. return new Signature(this, sig);
  9510. };
  9511. /**
  9512. * * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2
  9513. *
  9514. * EDDSA defines methods for encoding and decoding points and integers. These are
  9515. * helper convenience methods, that pass along to utility functions implied
  9516. * parameters.
  9517. *
  9518. */
  9519. EDDSA.prototype.encodePoint = function encodePoint(point) {
  9520. var enc = point.getY().toArray('le', this.encodingLength);
  9521. enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;
  9522. return enc;
  9523. };
  9524. EDDSA.prototype.decodePoint = function decodePoint(bytes) {
  9525. bytes = utils.parseBytes(bytes);
  9526. var lastIx = bytes.length - 1;
  9527. var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);
  9528. var xIsOdd = (bytes[lastIx] & 0x80) !== 0;
  9529. var y = utils.intFromLE(normed);
  9530. return this.curve.pointFromY(y, xIsOdd);
  9531. };
  9532. EDDSA.prototype.encodeInt = function encodeInt(num) {
  9533. return num.toArray('le', this.encodingLength);
  9534. };
  9535. EDDSA.prototype.decodeInt = function decodeInt(bytes) {
  9536. return utils.intFromLE(bytes);
  9537. };
  9538. EDDSA.prototype.isPoint = function isPoint(val) {
  9539. return val instanceof this.pointClass;
  9540. };
  9541. },{"../curves":24,"../utils":32,"./key":29,"./signature":30,"brorand":17,"hash.js":34,"hmac-drbg":46}],29:[function(require,module,exports){
  9542. 'use strict';
  9543. var utils = require('../utils');
  9544. var assert = utils.assert;
  9545. var parseBytes = utils.parseBytes;
  9546. var cachedProperty = utils.cachedProperty;
  9547. /**
  9548. * @param {EDDSA} eddsa - instance
  9549. * @param {Object} params - public/private key parameters
  9550. *
  9551. * @param {Array<Byte>} [params.secret] - secret seed bytes
  9552. * @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)
  9553. * @param {Array<Byte>} [params.pub] - public key point encoded as bytes
  9554. *
  9555. */
  9556. function KeyPair(eddsa, params) {
  9557. this.eddsa = eddsa;
  9558. if (params.hasOwnProperty('secret'))
  9559. this._secret = parseBytes(params.secret);
  9560. if (eddsa.isPoint(params.pub))
  9561. this._pub = params.pub;
  9562. else {
  9563. this._pubBytes = parseBytes(params.pub);
  9564. if (this._pubBytes && this._pubBytes.length === 33 &&
  9565. this._pubBytes[0] === 0x40)
  9566. this._pubBytes = this._pubBytes.slice(1, 33);
  9567. if (this._pubBytes && this._pubBytes.length !== 32)
  9568. throw new Error('Unknown point compression format');
  9569. }
  9570. }
  9571. KeyPair.fromPublic = function fromPublic(eddsa, pub) {
  9572. if (pub instanceof KeyPair)
  9573. return pub;
  9574. return new KeyPair(eddsa, { pub: pub });
  9575. };
  9576. KeyPair.fromSecret = function fromSecret(eddsa, secret) {
  9577. if (secret instanceof KeyPair)
  9578. return secret;
  9579. return new KeyPair(eddsa, { secret: secret });
  9580. };
  9581. KeyPair.prototype.secret = function secret() {
  9582. return this._secret;
  9583. };
  9584. cachedProperty(KeyPair, 'pubBytes', function pubBytes() {
  9585. return this.eddsa.encodePoint(this.pub());
  9586. });
  9587. cachedProperty(KeyPair, 'pub', function pub() {
  9588. if (this._pubBytes)
  9589. return this.eddsa.decodePoint(this._pubBytes);
  9590. return this.eddsa.g.mul(this.priv());
  9591. });
  9592. cachedProperty(KeyPair, 'privBytes', function privBytes() {
  9593. var eddsa = this.eddsa;
  9594. var hash = this.hash();
  9595. var lastIx = eddsa.encodingLength - 1;
  9596. // https://tools.ietf.org/html/rfc8032#section-5.1.5
  9597. var a = hash.slice(0, eddsa.encodingLength);
  9598. a[0] &= 248;
  9599. a[lastIx] &= 127;
  9600. a[lastIx] |= 64;
  9601. return a;
  9602. });
  9603. cachedProperty(KeyPair, 'priv', function priv() {
  9604. return this.eddsa.decodeInt(this.privBytes());
  9605. });
  9606. cachedProperty(KeyPair, 'hash', function hash() {
  9607. return this.eddsa.hash().update(this.secret()).digest();
  9608. });
  9609. cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() {
  9610. return this.hash().slice(this.eddsa.encodingLength);
  9611. });
  9612. KeyPair.prototype.sign = function sign(message) {
  9613. assert(this._secret, 'KeyPair can only verify');
  9614. return this.eddsa.sign(message, this);
  9615. };
  9616. KeyPair.prototype.verify = function verify(message, sig) {
  9617. return this.eddsa.verify(message, sig, this);
  9618. };
  9619. KeyPair.prototype.getSecret = function getSecret(enc) {
  9620. assert(this._secret, 'KeyPair is public only');
  9621. return utils.encode(this.secret(), enc);
  9622. };
  9623. KeyPair.prototype.getPublic = function getPublic(enc, compact) {
  9624. return utils.encode((compact ? [ 0x40 ] : []).concat(this.pubBytes()), enc);
  9625. };
  9626. module.exports = KeyPair;
  9627. },{"../utils":32}],30:[function(require,module,exports){
  9628. 'use strict';
  9629. var BN = require('bn.js');
  9630. var utils = require('../utils');
  9631. var assert = utils.assert;
  9632. var cachedProperty = utils.cachedProperty;
  9633. var parseBytes = utils.parseBytes;
  9634. /**
  9635. * @param {EDDSA} eddsa - eddsa instance
  9636. * @param {Array<Bytes>|Object} sig -
  9637. * @param {Array<Bytes>|Point} [sig.R] - R point as Point or bytes
  9638. * @param {Array<Bytes>|bn} [sig.S] - S scalar as bn or bytes
  9639. * @param {Array<Bytes>} [sig.Rencoded] - R point encoded
  9640. * @param {Array<Bytes>} [sig.Sencoded] - S scalar encoded
  9641. */
  9642. function Signature(eddsa, sig) {
  9643. this.eddsa = eddsa;
  9644. if (typeof sig !== 'object')
  9645. sig = parseBytes(sig);
  9646. if (Array.isArray(sig)) {
  9647. sig = {
  9648. R: sig.slice(0, eddsa.encodingLength),
  9649. S: sig.slice(eddsa.encodingLength)
  9650. };
  9651. }
  9652. assert(sig.R && sig.S, 'Signature without R or S');
  9653. if (eddsa.isPoint(sig.R))
  9654. this._R = sig.R;
  9655. if (sig.S instanceof BN)
  9656. this._S = sig.S;
  9657. this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;
  9658. this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;
  9659. }
  9660. cachedProperty(Signature, 'S', function S() {
  9661. return this.eddsa.decodeInt(this.Sencoded());
  9662. });
  9663. cachedProperty(Signature, 'R', function R() {
  9664. return this.eddsa.decodePoint(this.Rencoded());
  9665. });
  9666. cachedProperty(Signature, 'Rencoded', function Rencoded() {
  9667. return this.eddsa.encodePoint(this.R());
  9668. });
  9669. cachedProperty(Signature, 'Sencoded', function Sencoded() {
  9670. return this.eddsa.encodeInt(this.S());
  9671. });
  9672. Signature.prototype.toBytes = function toBytes() {
  9673. return this.Rencoded().concat(this.Sencoded());
  9674. };
  9675. Signature.prototype.toHex = function toHex() {
  9676. return utils.encode(this.toBytes(), 'hex').toUpperCase();
  9677. };
  9678. module.exports = Signature;
  9679. },{"../utils":32,"bn.js":16}],31:[function(require,module,exports){
  9680. module.exports = {
  9681. doubles: {
  9682. step: 4,
  9683. points: [
  9684. [
  9685. 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',
  9686. 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'
  9687. ],
  9688. [
  9689. '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',
  9690. '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'
  9691. ],
  9692. [
  9693. '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',
  9694. 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'
  9695. ],
  9696. [
  9697. '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',
  9698. '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'
  9699. ],
  9700. [
  9701. '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',
  9702. '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'
  9703. ],
  9704. [
  9705. '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',
  9706. '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'
  9707. ],
  9708. [
  9709. 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',
  9710. '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'
  9711. ],
  9712. [
  9713. '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',
  9714. 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'
  9715. ],
  9716. [
  9717. 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',
  9718. '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'
  9719. ],
  9720. [
  9721. 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',
  9722. 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'
  9723. ],
  9724. [
  9725. 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',
  9726. '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'
  9727. ],
  9728. [
  9729. '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',
  9730. '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'
  9731. ],
  9732. [
  9733. '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',
  9734. '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'
  9735. ],
  9736. [
  9737. '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',
  9738. '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'
  9739. ],
  9740. [
  9741. '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',
  9742. '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'
  9743. ],
  9744. [
  9745. '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',
  9746. '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'
  9747. ],
  9748. [
  9749. '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',
  9750. '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'
  9751. ],
  9752. [
  9753. '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',
  9754. '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'
  9755. ],
  9756. [
  9757. '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',
  9758. 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'
  9759. ],
  9760. [
  9761. 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',
  9762. '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'
  9763. ],
  9764. [
  9765. 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',
  9766. '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'
  9767. ],
  9768. [
  9769. '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',
  9770. '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'
  9771. ],
  9772. [
  9773. '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',
  9774. '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'
  9775. ],
  9776. [
  9777. 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',
  9778. '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'
  9779. ],
  9780. [
  9781. '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',
  9782. 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'
  9783. ],
  9784. [
  9785. 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',
  9786. '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'
  9787. ],
  9788. [
  9789. 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',
  9790. 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'
  9791. ],
  9792. [
  9793. 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',
  9794. '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'
  9795. ],
  9796. [
  9797. 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',
  9798. 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'
  9799. ],
  9800. [
  9801. 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',
  9802. '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'
  9803. ],
  9804. [
  9805. '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',
  9806. 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'
  9807. ],
  9808. [
  9809. '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',
  9810. '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'
  9811. ],
  9812. [
  9813. 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',
  9814. '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'
  9815. ],
  9816. [
  9817. '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',
  9818. 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'
  9819. ],
  9820. [
  9821. 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',
  9822. '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'
  9823. ],
  9824. [
  9825. 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',
  9826. '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'
  9827. ],
  9828. [
  9829. 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',
  9830. 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'
  9831. ],
  9832. [
  9833. '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',
  9834. '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'
  9835. ],
  9836. [
  9837. '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',
  9838. '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'
  9839. ],
  9840. [
  9841. '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',
  9842. 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'
  9843. ],
  9844. [
  9845. '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',
  9846. '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'
  9847. ],
  9848. [
  9849. 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',
  9850. '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'
  9851. ],
  9852. [
  9853. '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',
  9854. '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'
  9855. ],
  9856. [
  9857. '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',
  9858. 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'
  9859. ],
  9860. [
  9861. '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',
  9862. '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'
  9863. ],
  9864. [
  9865. 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',
  9866. '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'
  9867. ],
  9868. [
  9869. '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',
  9870. 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'
  9871. ],
  9872. [
  9873. 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',
  9874. 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'
  9875. ],
  9876. [
  9877. 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',
  9878. '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'
  9879. ],
  9880. [
  9881. '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',
  9882. 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'
  9883. ],
  9884. [
  9885. '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',
  9886. 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'
  9887. ],
  9888. [
  9889. 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',
  9890. '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'
  9891. ],
  9892. [
  9893. 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',
  9894. '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'
  9895. ],
  9896. [
  9897. 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',
  9898. '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'
  9899. ],
  9900. [
  9901. '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',
  9902. 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'
  9903. ],
  9904. [
  9905. '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',
  9906. '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'
  9907. ],
  9908. [
  9909. 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',
  9910. 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'
  9911. ],
  9912. [
  9913. '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',
  9914. 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'
  9915. ],
  9916. [
  9917. '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',
  9918. '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'
  9919. ],
  9920. [
  9921. '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',
  9922. '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'
  9923. ],
  9924. [
  9925. 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',
  9926. 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'
  9927. ],
  9928. [
  9929. '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',
  9930. '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'
  9931. ],
  9932. [
  9933. '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',
  9934. '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'
  9935. ],
  9936. [
  9937. 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',
  9938. '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'
  9939. ],
  9940. [
  9941. 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',
  9942. 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'
  9943. ]
  9944. ]
  9945. },
  9946. naf: {
  9947. wnd: 7,
  9948. points: [
  9949. [
  9950. 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',
  9951. '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'
  9952. ],
  9953. [
  9954. '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',
  9955. 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'
  9956. ],
  9957. [
  9958. '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',
  9959. '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'
  9960. ],
  9961. [
  9962. 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',
  9963. 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'
  9964. ],
  9965. [
  9966. '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',
  9967. 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'
  9968. ],
  9969. [
  9970. 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',
  9971. 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'
  9972. ],
  9973. [
  9974. 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',
  9975. '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'
  9976. ],
  9977. [
  9978. 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',
  9979. '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'
  9980. ],
  9981. [
  9982. '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',
  9983. '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'
  9984. ],
  9985. [
  9986. '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',
  9987. '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'
  9988. ],
  9989. [
  9990. '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',
  9991. '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'
  9992. ],
  9993. [
  9994. '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',
  9995. '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'
  9996. ],
  9997. [
  9998. 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',
  9999. 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'
  10000. ],
  10001. [
  10002. 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',
  10003. '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'
  10004. ],
  10005. [
  10006. '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',
  10007. 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'
  10008. ],
  10009. [
  10010. '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',
  10011. 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'
  10012. ],
  10013. [
  10014. '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',
  10015. '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'
  10016. ],
  10017. [
  10018. '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',
  10019. '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'
  10020. ],
  10021. [
  10022. '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',
  10023. '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'
  10024. ],
  10025. [
  10026. '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',
  10027. 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'
  10028. ],
  10029. [
  10030. 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',
  10031. 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'
  10032. ],
  10033. [
  10034. '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',
  10035. '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'
  10036. ],
  10037. [
  10038. '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',
  10039. '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'
  10040. ],
  10041. [
  10042. 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',
  10043. 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'
  10044. ],
  10045. [
  10046. '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',
  10047. '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'
  10048. ],
  10049. [
  10050. 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',
  10051. 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'
  10052. ],
  10053. [
  10054. 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',
  10055. 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'
  10056. ],
  10057. [
  10058. '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',
  10059. '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'
  10060. ],
  10061. [
  10062. '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',
  10063. '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'
  10064. ],
  10065. [
  10066. '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',
  10067. '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'
  10068. ],
  10069. [
  10070. 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',
  10071. '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'
  10072. ],
  10073. [
  10074. '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',
  10075. '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'
  10076. ],
  10077. [
  10078. 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',
  10079. '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'
  10080. ],
  10081. [
  10082. '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',
  10083. 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'
  10084. ],
  10085. [
  10086. '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',
  10087. 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'
  10088. ],
  10089. [
  10090. 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',
  10091. 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'
  10092. ],
  10093. [
  10094. '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',
  10095. '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'
  10096. ],
  10097. [
  10098. '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',
  10099. 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'
  10100. ],
  10101. [
  10102. 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',
  10103. 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'
  10104. ],
  10105. [
  10106. '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',
  10107. '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'
  10108. ],
  10109. [
  10110. '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',
  10111. 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'
  10112. ],
  10113. [
  10114. '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',
  10115. '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'
  10116. ],
  10117. [
  10118. '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',
  10119. 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'
  10120. ],
  10121. [
  10122. 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',
  10123. '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'
  10124. ],
  10125. [
  10126. '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',
  10127. '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'
  10128. ],
  10129. [
  10130. '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',
  10131. 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'
  10132. ],
  10133. [
  10134. '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',
  10135. 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'
  10136. ],
  10137. [
  10138. 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',
  10139. 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'
  10140. ],
  10141. [
  10142. 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',
  10143. 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'
  10144. ],
  10145. [
  10146. '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',
  10147. '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'
  10148. ],
  10149. [
  10150. '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',
  10151. '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'
  10152. ],
  10153. [
  10154. 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',
  10155. '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'
  10156. ],
  10157. [
  10158. 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',
  10159. 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'
  10160. ],
  10161. [
  10162. '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',
  10163. '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'
  10164. ],
  10165. [
  10166. '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',
  10167. '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'
  10168. ],
  10169. [
  10170. 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',
  10171. '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'
  10172. ],
  10173. [
  10174. '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',
  10175. '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'
  10176. ],
  10177. [
  10178. 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',
  10179. 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'
  10180. ],
  10181. [
  10182. '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',
  10183. 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'
  10184. ],
  10185. [
  10186. '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',
  10187. '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'
  10188. ],
  10189. [
  10190. 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',
  10191. '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'
  10192. ],
  10193. [
  10194. 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',
  10195. '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'
  10196. ],
  10197. [
  10198. '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',
  10199. '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'
  10200. ],
  10201. [
  10202. '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',
  10203. '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'
  10204. ],
  10205. [
  10206. '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',
  10207. 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'
  10208. ],
  10209. [
  10210. '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',
  10211. 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'
  10212. ],
  10213. [
  10214. '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',
  10215. '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'
  10216. ],
  10217. [
  10218. '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',
  10219. '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'
  10220. ],
  10221. [
  10222. '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',
  10223. '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'
  10224. ],
  10225. [
  10226. '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',
  10227. 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'
  10228. ],
  10229. [
  10230. 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',
  10231. 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'
  10232. ],
  10233. [
  10234. '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',
  10235. 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'
  10236. ],
  10237. [
  10238. 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',
  10239. '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'
  10240. ],
  10241. [
  10242. 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',
  10243. '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'
  10244. ],
  10245. [
  10246. 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',
  10247. '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'
  10248. ],
  10249. [
  10250. 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',
  10251. '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'
  10252. ],
  10253. [
  10254. '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',
  10255. 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'
  10256. ],
  10257. [
  10258. '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',
  10259. '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'
  10260. ],
  10261. [
  10262. '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',
  10263. 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'
  10264. ],
  10265. [
  10266. 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',
  10267. 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'
  10268. ],
  10269. [
  10270. 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',
  10271. '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'
  10272. ],
  10273. [
  10274. 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',
  10275. 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'
  10276. ],
  10277. [
  10278. 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',
  10279. '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'
  10280. ],
  10281. [
  10282. '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',
  10283. '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'
  10284. ],
  10285. [
  10286. 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',
  10287. '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'
  10288. ],
  10289. [
  10290. 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',
  10291. '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'
  10292. ],
  10293. [
  10294. '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',
  10295. '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'
  10296. ],
  10297. [
  10298. '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',
  10299. 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'
  10300. ],
  10301. [
  10302. 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',
  10303. '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'
  10304. ],
  10305. [
  10306. 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',
  10307. '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'
  10308. ],
  10309. [
  10310. 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',
  10311. '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'
  10312. ],
  10313. [
  10314. '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',
  10315. '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'
  10316. ],
  10317. [
  10318. 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',
  10319. 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'
  10320. ],
  10321. [
  10322. '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',
  10323. 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'
  10324. ],
  10325. [
  10326. 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',
  10327. 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'
  10328. ],
  10329. [
  10330. 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',
  10331. '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'
  10332. ],
  10333. [
  10334. '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',
  10335. 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'
  10336. ],
  10337. [
  10338. 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',
  10339. '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'
  10340. ],
  10341. [
  10342. 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',
  10343. '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'
  10344. ],
  10345. [
  10346. 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',
  10347. '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'
  10348. ],
  10349. [
  10350. '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',
  10351. 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'
  10352. ],
  10353. [
  10354. '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',
  10355. 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'
  10356. ],
  10357. [
  10358. 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',
  10359. '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'
  10360. ],
  10361. [
  10362. '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',
  10363. 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'
  10364. ],
  10365. [
  10366. '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',
  10367. '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'
  10368. ],
  10369. [
  10370. '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',
  10371. 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'
  10372. ],
  10373. [
  10374. 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',
  10375. 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'
  10376. ],
  10377. [
  10378. '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',
  10379. 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'
  10380. ],
  10381. [
  10382. '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',
  10383. '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'
  10384. ],
  10385. [
  10386. '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',
  10387. 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'
  10388. ],
  10389. [
  10390. '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',
  10391. '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'
  10392. ],
  10393. [
  10394. 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',
  10395. 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'
  10396. ],
  10397. [
  10398. '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',
  10399. '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'
  10400. ],
  10401. [
  10402. 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',
  10403. '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'
  10404. ],
  10405. [
  10406. '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',
  10407. '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'
  10408. ],
  10409. [
  10410. 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',
  10411. 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'
  10412. ],
  10413. [
  10414. 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',
  10415. '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'
  10416. ],
  10417. [
  10418. 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',
  10419. 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'
  10420. ],
  10421. [
  10422. '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',
  10423. 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'
  10424. ],
  10425. [
  10426. '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',
  10427. '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'
  10428. ],
  10429. [
  10430. '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',
  10431. 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'
  10432. ],
  10433. [
  10434. '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',
  10435. '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'
  10436. ],
  10437. [
  10438. '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',
  10439. '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'
  10440. ],
  10441. [
  10442. '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',
  10443. 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'
  10444. ],
  10445. [
  10446. '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',
  10447. '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'
  10448. ],
  10449. [
  10450. '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',
  10451. '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'
  10452. ],
  10453. [
  10454. '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',
  10455. '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'
  10456. ]
  10457. ]
  10458. }
  10459. };
  10460. },{}],32:[function(require,module,exports){
  10461. 'use strict';
  10462. var utils = exports;
  10463. var BN = require('bn.js');
  10464. var minAssert = require('minimalistic-assert');
  10465. var minUtils = require('minimalistic-crypto-utils');
  10466. utils.assert = minAssert;
  10467. utils.toArray = minUtils.toArray;
  10468. utils.zero2 = minUtils.zero2;
  10469. utils.toHex = minUtils.toHex;
  10470. utils.encode = minUtils.encode;
  10471. // Represent num in a w-NAF form
  10472. function getNAF(num, w) {
  10473. var naf = [];
  10474. var ws = 1 << (w + 1);
  10475. var k = num.clone();
  10476. while (k.cmpn(1) >= 0) {
  10477. var z;
  10478. if (k.isOdd()) {
  10479. var mod = k.andln(ws - 1);
  10480. if (mod > (ws >> 1) - 1)
  10481. z = (ws >> 1) - mod;
  10482. else
  10483. z = mod;
  10484. k.isubn(z);
  10485. } else {
  10486. z = 0;
  10487. }
  10488. naf.push(z);
  10489. // Optimization, shift by word if possible
  10490. var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1;
  10491. for (var i = 1; i < shift; i++)
  10492. naf.push(0);
  10493. k.iushrn(shift);
  10494. }
  10495. return naf;
  10496. }
  10497. utils.getNAF = getNAF;
  10498. // Represent k1, k2 in a Joint Sparse Form
  10499. function getJSF(k1, k2) {
  10500. var jsf = [
  10501. [],
  10502. []
  10503. ];
  10504. k1 = k1.clone();
  10505. k2 = k2.clone();
  10506. var d1 = 0;
  10507. var d2 = 0;
  10508. while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
  10509. // First phase
  10510. var m14 = (k1.andln(3) + d1) & 3;
  10511. var m24 = (k2.andln(3) + d2) & 3;
  10512. if (m14 === 3)
  10513. m14 = -1;
  10514. if (m24 === 3)
  10515. m24 = -1;
  10516. var u1;
  10517. if ((m14 & 1) === 0) {
  10518. u1 = 0;
  10519. } else {
  10520. var m8 = (k1.andln(7) + d1) & 7;
  10521. if ((m8 === 3 || m8 === 5) && m24 === 2)
  10522. u1 = -m14;
  10523. else
  10524. u1 = m14;
  10525. }
  10526. jsf[0].push(u1);
  10527. var u2;
  10528. if ((m24 & 1) === 0) {
  10529. u2 = 0;
  10530. } else {
  10531. var m8 = (k2.andln(7) + d2) & 7;
  10532. if ((m8 === 3 || m8 === 5) && m14 === 2)
  10533. u2 = -m24;
  10534. else
  10535. u2 = m24;
  10536. }
  10537. jsf[1].push(u2);
  10538. // Second phase
  10539. if (2 * d1 === u1 + 1)
  10540. d1 = 1 - d1;
  10541. if (2 * d2 === u2 + 1)
  10542. d2 = 1 - d2;
  10543. k1.iushrn(1);
  10544. k2.iushrn(1);
  10545. }
  10546. return jsf;
  10547. }
  10548. utils.getJSF = getJSF;
  10549. function cachedProperty(obj, name, computer) {
  10550. var key = '_' + name;
  10551. obj.prototype[name] = function cachedProperty() {
  10552. return this[key] !== undefined ? this[key] :
  10553. this[key] = computer.call(this);
  10554. };
  10555. }
  10556. utils.cachedProperty = cachedProperty;
  10557. function parseBytes(bytes) {
  10558. return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :
  10559. bytes;
  10560. }
  10561. utils.parseBytes = parseBytes;
  10562. function intFromLE(bytes) {
  10563. return new BN(bytes, 'hex', 'le');
  10564. }
  10565. utils.intFromLE = intFromLE;
  10566. },{"bn.js":16,"minimalistic-assert":48,"minimalistic-crypto-utils":49}],33:[function(require,module,exports){
  10567. "use strict";
  10568. // email-addresses.js - RFC 5322 email address parser
  10569. // v 3.1.0
  10570. //
  10571. // http://tools.ietf.org/html/rfc5322
  10572. //
  10573. // This library does not validate email addresses.
  10574. // emailAddresses attempts to parse addresses using the (fairly liberal)
  10575. // grammar specified in RFC 5322.
  10576. //
  10577. // email-addresses returns {
  10578. // ast: <an abstract syntax tree based on rfc5322>,
  10579. // addresses: [{
  10580. // node: <node in ast for this address>,
  10581. // name: <display-name>,
  10582. // address: <addr-spec>,
  10583. // local: <local-part>,
  10584. // domain: <domain>
  10585. // }, ...]
  10586. // }
  10587. //
  10588. // emailAddresses.parseOneAddress and emailAddresses.parseAddressList
  10589. // work as you might expect. Try it out.
  10590. //
  10591. // Many thanks to Dominic Sayers and his documentation on the is_email function,
  10592. // http://code.google.com/p/isemail/ , which helped greatly in writing this parser.
  10593. (function (global) {
  10594. "use strict";
  10595. function parse5322(opts) {
  10596. // tokenizing functions
  10597. function inStr() {
  10598. return pos < len;
  10599. }
  10600. function curTok() {
  10601. return parseString[pos];
  10602. }
  10603. function getPos() {
  10604. return pos;
  10605. }
  10606. function setPos(i) {
  10607. pos = i;
  10608. }
  10609. function nextTok() {
  10610. pos += 1;
  10611. }
  10612. function initialize() {
  10613. pos = 0;
  10614. len = parseString.length;
  10615. }
  10616. // parser helper functions
  10617. function o(name, value) {
  10618. return {
  10619. name: name,
  10620. tokens: value || "",
  10621. semantic: value || "",
  10622. children: []
  10623. };
  10624. }
  10625. function wrap(name, ast) {
  10626. var n;
  10627. if (ast === null) {
  10628. return null;
  10629. }
  10630. n = o(name);
  10631. n.tokens = ast.tokens;
  10632. n.semantic = ast.semantic;
  10633. n.children.push(ast);
  10634. return n;
  10635. }
  10636. function add(parent, child) {
  10637. if (child !== null) {
  10638. parent.tokens += child.tokens;
  10639. parent.semantic += child.semantic;
  10640. }
  10641. parent.children.push(child);
  10642. return parent;
  10643. }
  10644. function compareToken(fxnCompare) {
  10645. var tok;
  10646. if (!inStr()) {
  10647. return null;
  10648. }
  10649. tok = curTok();
  10650. if (fxnCompare(tok)) {
  10651. nextTok();
  10652. return o('token', tok);
  10653. }
  10654. return null;
  10655. }
  10656. function literal(lit) {
  10657. return function literalFunc() {
  10658. return wrap('literal', compareToken(function (tok) {
  10659. return tok === lit;
  10660. }));
  10661. };
  10662. }
  10663. function and() {
  10664. var args = arguments;
  10665. return function andFunc() {
  10666. var i, s, result, start;
  10667. start = getPos();
  10668. s = o('and');
  10669. for (i = 0; i < args.length; i += 1) {
  10670. result = args[i]();
  10671. if (result === null) {
  10672. setPos(start);
  10673. return null;
  10674. }
  10675. add(s, result);
  10676. }
  10677. return s;
  10678. };
  10679. }
  10680. function or() {
  10681. var args = arguments;
  10682. return function orFunc() {
  10683. var i, result, start;
  10684. start = getPos();
  10685. for (i = 0; i < args.length; i += 1) {
  10686. result = args[i]();
  10687. if (result !== null) {
  10688. return result;
  10689. }
  10690. setPos(start);
  10691. }
  10692. return null;
  10693. };
  10694. }
  10695. function opt(prod) {
  10696. return function optFunc() {
  10697. var result, start;
  10698. start = getPos();
  10699. result = prod();
  10700. if (result !== null) {
  10701. return result;
  10702. } else {
  10703. setPos(start);
  10704. return o('opt');
  10705. }
  10706. };
  10707. }
  10708. function invis(prod) {
  10709. return function invisFunc() {
  10710. var result = prod();
  10711. if (result !== null) {
  10712. result.semantic = "";
  10713. }
  10714. return result;
  10715. };
  10716. }
  10717. function colwsp(prod) {
  10718. return function collapseSemanticWhitespace() {
  10719. var result = prod();
  10720. if (result !== null && result.semantic.length > 0) {
  10721. result.semantic = " ";
  10722. }
  10723. return result;
  10724. };
  10725. }
  10726. function star(prod, minimum) {
  10727. return function starFunc() {
  10728. var s, result, count, start, min;
  10729. start = getPos();
  10730. s = o('star');
  10731. count = 0;
  10732. min = minimum === undefined ? 0 : minimum;
  10733. while ((result = prod()) !== null) {
  10734. count = count + 1;
  10735. add(s, result);
  10736. }
  10737. if (count >= min) {
  10738. return s;
  10739. } else {
  10740. setPos(start);
  10741. return null;
  10742. }
  10743. };
  10744. }
  10745. // One expects names to get normalized like this:
  10746. // " First Last " -> "First Last"
  10747. // "First Last" -> "First Last"
  10748. // "First Last" -> "First Last"
  10749. function collapseWhitespace(s) {
  10750. return s.replace(/([ \t]|\r\n)+/g, ' ').replace(/^\s*/, '').replace(/\s*$/, '');
  10751. }
  10752. // UTF-8 pseudo-production (RFC 6532)
  10753. // RFC 6532 extends RFC 5322 productions to include UTF-8
  10754. // using the following productions:
  10755. // UTF8-non-ascii = UTF8-2 / UTF8-3 / UTF8-4
  10756. // UTF8-2 = <Defined in Section 4 of RFC3629>
  10757. // UTF8-3 = <Defined in Section 4 of RFC3629>
  10758. // UTF8-4 = <Defined in Section 4 of RFC3629>
  10759. //
  10760. // For reference, the extended RFC 5322 productions are:
  10761. // VCHAR =/ UTF8-non-ascii
  10762. // ctext =/ UTF8-non-ascii
  10763. // atext =/ UTF8-non-ascii
  10764. // qtext =/ UTF8-non-ascii
  10765. // dtext =/ UTF8-non-ascii
  10766. function isUTF8NonAscii(tok) {
  10767. // In JavaScript, we just deal directly with Unicode code points,
  10768. // so we aren't checking individual bytes for UTF-8 encoding.
  10769. // Just check that the character is non-ascii.
  10770. return tok.charCodeAt(0) >= 128;
  10771. }
  10772. // common productions (RFC 5234)
  10773. // http://tools.ietf.org/html/rfc5234
  10774. // B.1. Core Rules
  10775. // CR = %x0D
  10776. // ; carriage return
  10777. function cr() {
  10778. return wrap('cr', literal('\r')());
  10779. }
  10780. // CRLF = CR LF
  10781. // ; Internet standard newline
  10782. function crlf() {
  10783. return wrap('crlf', and(cr, lf)());
  10784. }
  10785. // DQUOTE = %x22
  10786. // ; " (Double Quote)
  10787. function dquote() {
  10788. return wrap('dquote', literal('"')());
  10789. }
  10790. // HTAB = %x09
  10791. // ; horizontal tab
  10792. function htab() {
  10793. return wrap('htab', literal('\t')());
  10794. }
  10795. // LF = %x0A
  10796. // ; linefeed
  10797. function lf() {
  10798. return wrap('lf', literal('\n')());
  10799. }
  10800. // SP = %x20
  10801. function sp() {
  10802. return wrap('sp', literal(' ')());
  10803. }
  10804. // VCHAR = %x21-7E
  10805. // ; visible (printing) characters
  10806. function vchar() {
  10807. return wrap('vchar', compareToken(function vcharFunc(tok) {
  10808. var code = tok.charCodeAt(0);
  10809. var accept = 0x21 <= code && code <= 0x7E;
  10810. if (opts.rfc6532) {
  10811. accept = accept || isUTF8NonAscii(tok);
  10812. }
  10813. return accept;
  10814. }));
  10815. }
  10816. // WSP = SP / HTAB
  10817. // ; white space
  10818. function wsp() {
  10819. return wrap('wsp', or(sp, htab)());
  10820. }
  10821. // email productions (RFC 5322)
  10822. // http://tools.ietf.org/html/rfc5322
  10823. // 3.2.1. Quoted characters
  10824. // quoted-pair = ("\" (VCHAR / WSP)) / obs-qp
  10825. function quotedPair() {
  10826. var qp = wrap('quoted-pair', or(and(literal('\\'), or(vchar, wsp)), obsQP)());
  10827. if (qp === null) {
  10828. return null;
  10829. }
  10830. // a quoted pair will be two characters, and the "\" character
  10831. // should be semantically "invisible" (RFC 5322 3.2.1)
  10832. qp.semantic = qp.semantic[1];
  10833. return qp;
  10834. }
  10835. // 3.2.2. Folding White Space and Comments
  10836. // FWS = ([*WSP CRLF] 1*WSP) / obs-FWS
  10837. function fws() {
  10838. return wrap('fws', or(obsFws, and(opt(and(star(wsp), invis(crlf))), star(wsp, 1)))());
  10839. }
  10840. // ctext = %d33-39 / ; Printable US-ASCII
  10841. // %d42-91 / ; characters not including
  10842. // %d93-126 / ; "(", ")", or "\"
  10843. // obs-ctext
  10844. function ctext() {
  10845. return wrap('ctext', or(function ctextFunc1() {
  10846. return compareToken(function ctextFunc2(tok) {
  10847. var code = tok.charCodeAt(0);
  10848. var accept = 33 <= code && code <= 39 || 42 <= code && code <= 91 || 93 <= code && code <= 126;
  10849. if (opts.rfc6532) {
  10850. accept = accept || isUTF8NonAscii(tok);
  10851. }
  10852. return accept;
  10853. });
  10854. }, obsCtext)());
  10855. }
  10856. // ccontent = ctext / quoted-pair / comment
  10857. function ccontent() {
  10858. return wrap('ccontent', or(ctext, quotedPair, comment)());
  10859. }
  10860. // comment = "(" *([FWS] ccontent) [FWS] ")"
  10861. function comment() {
  10862. return wrap('comment', and(literal('('), star(and(opt(fws), ccontent)), opt(fws), literal(')'))());
  10863. }
  10864. // CFWS = (1*([FWS] comment) [FWS]) / FWS
  10865. function cfws() {
  10866. return wrap('cfws', or(and(star(and(opt(fws), comment), 1), opt(fws)), fws)());
  10867. }
  10868. // 3.2.3. Atom
  10869. //atext = ALPHA / DIGIT / ; Printable US-ASCII
  10870. // "!" / "#" / ; characters not including
  10871. // "$" / "%" / ; specials. Used for atoms.
  10872. // "&" / "'" /
  10873. // "*" / "+" /
  10874. // "-" / "/" /
  10875. // "=" / "?" /
  10876. // "^" / "_" /
  10877. // "`" / "{" /
  10878. // "|" / "}" /
  10879. // "~"
  10880. function atext() {
  10881. return wrap('atext', compareToken(function atextFunc(tok) {
  10882. var accept = 'a' <= tok && tok <= 'z' || 'A' <= tok && tok <= 'Z' || '0' <= tok && tok <= '9' || ['!', '#', '$', '%', '&', '\'', '*', '+', '-', '/', '=', '?', '^', '_', '`', '{', '|', '}', '~'].indexOf(tok) >= 0;
  10883. if (opts.rfc6532) {
  10884. accept = accept || isUTF8NonAscii(tok);
  10885. }
  10886. return accept;
  10887. }));
  10888. }
  10889. // atom = [CFWS] 1*atext [CFWS]
  10890. function atom() {
  10891. return wrap('atom', and(colwsp(opt(cfws)), star(atext, 1), colwsp(opt(cfws)))());
  10892. }
  10893. // dot-atom-text = 1*atext *("." 1*atext)
  10894. function dotAtomText() {
  10895. var s, maybeText;
  10896. s = wrap('dot-atom-text', star(atext, 1)());
  10897. if (s === null) {
  10898. return s;
  10899. }
  10900. maybeText = star(and(literal('.'), star(atext, 1)))();
  10901. if (maybeText !== null) {
  10902. add(s, maybeText);
  10903. }
  10904. return s;
  10905. }
  10906. // dot-atom = [CFWS] dot-atom-text [CFWS]
  10907. function dotAtom() {
  10908. return wrap('dot-atom', and(invis(opt(cfws)), dotAtomText, invis(opt(cfws)))());
  10909. }
  10910. // 3.2.4. Quoted Strings
  10911. // qtext = %d33 / ; Printable US-ASCII
  10912. // %d35-91 / ; characters not including
  10913. // %d93-126 / ; "\" or the quote character
  10914. // obs-qtext
  10915. function qtext() {
  10916. return wrap('qtext', or(function qtextFunc1() {
  10917. return compareToken(function qtextFunc2(tok) {
  10918. var code = tok.charCodeAt(0);
  10919. var accept = 33 === code || 35 <= code && code <= 91 || 93 <= code && code <= 126;
  10920. if (opts.rfc6532) {
  10921. accept = accept || isUTF8NonAscii(tok);
  10922. }
  10923. return accept;
  10924. });
  10925. }, obsQtext)());
  10926. }
  10927. // qcontent = qtext / quoted-pair
  10928. function qcontent() {
  10929. return wrap('qcontent', or(qtext, quotedPair)());
  10930. }
  10931. // quoted-string = [CFWS]
  10932. // DQUOTE *([FWS] qcontent) [FWS] DQUOTE
  10933. // [CFWS]
  10934. function quotedString() {
  10935. return wrap('quoted-string', and(invis(opt(cfws)), invis(dquote), star(and(opt(colwsp(fws)), qcontent)), opt(invis(fws)), invis(dquote), invis(opt(cfws)))());
  10936. }
  10937. // 3.2.5 Miscellaneous Tokens
  10938. // word = atom / quoted-string
  10939. function word() {
  10940. return wrap('word', or(atom, quotedString)());
  10941. }
  10942. // phrase = 1*word / obs-phrase
  10943. function phrase() {
  10944. return wrap('phrase', or(obsPhrase, star(word, 1))());
  10945. }
  10946. // 3.4. Address Specification
  10947. // address = mailbox / group
  10948. function address() {
  10949. return wrap('address', or(mailbox, group)());
  10950. }
  10951. // mailbox = name-addr / addr-spec
  10952. function mailbox() {
  10953. return wrap('mailbox', or(nameAddr, addrSpec)());
  10954. }
  10955. // name-addr = [display-name] angle-addr
  10956. function nameAddr() {
  10957. return wrap('name-addr', and(opt(displayName), angleAddr)());
  10958. }
  10959. // angle-addr = [CFWS] "<" addr-spec ">" [CFWS] /
  10960. // obs-angle-addr
  10961. function angleAddr() {
  10962. return wrap('angle-addr', or(and(invis(opt(cfws)), literal('<'), addrSpec, literal('>'), invis(opt(cfws))), obsAngleAddr)());
  10963. }
  10964. // group = display-name ":" [group-list] ";" [CFWS]
  10965. function group() {
  10966. return wrap('group', and(displayName, literal(':'), opt(groupList), literal(';'), invis(opt(cfws)))());
  10967. }
  10968. // display-name = phrase
  10969. function displayName() {
  10970. return wrap('display-name', function phraseFixedSemantic() {
  10971. var result = phrase();
  10972. if (result !== null) {
  10973. result.semantic = collapseWhitespace(result.semantic);
  10974. }
  10975. return result;
  10976. }());
  10977. }
  10978. // mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list
  10979. function mailboxList() {
  10980. return wrap('mailbox-list', or(and(mailbox, star(and(literal(','), mailbox))), obsMboxList)());
  10981. }
  10982. // address-list = (address *("," address)) / obs-addr-list
  10983. function addressList() {
  10984. return wrap('address-list', or(and(address, star(and(literal(','), address))), obsAddrList)());
  10985. }
  10986. // group-list = mailbox-list / CFWS / obs-group-list
  10987. function groupList() {
  10988. return wrap('group-list', or(mailboxList, invis(cfws), obsGroupList)());
  10989. }
  10990. // 3.4.1 Addr-Spec Specification
  10991. // local-part = dot-atom / quoted-string / obs-local-part
  10992. function localPart() {
  10993. // note: quoted-string, dotAtom are proper subsets of obs-local-part
  10994. // so we really just have to look for obsLocalPart, if we don't care about the exact parse tree
  10995. return wrap('local-part', or(obsLocalPart, dotAtom, quotedString)());
  10996. }
  10997. // dtext = %d33-90 / ; Printable US-ASCII
  10998. // %d94-126 / ; characters not including
  10999. // obs-dtext ; "[", "]", or "\"
  11000. function dtext() {
  11001. return wrap('dtext', or(function dtextFunc1() {
  11002. return compareToken(function dtextFunc2(tok) {
  11003. var code = tok.charCodeAt(0);
  11004. var accept = 33 <= code && code <= 90 || 94 <= code && code <= 126;
  11005. if (opts.rfc6532) {
  11006. accept = accept || isUTF8NonAscii(tok);
  11007. }
  11008. return accept;
  11009. });
  11010. }, obsDtext)());
  11011. }
  11012. // domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]
  11013. function domainLiteral() {
  11014. return wrap('domain-literal', and(invis(opt(cfws)), literal('['), star(and(opt(fws), dtext)), opt(fws), literal(']'), invis(opt(cfws)))());
  11015. }
  11016. // domain = dot-atom / domain-literal / obs-domain
  11017. function domain() {
  11018. return wrap('domain', function domainCheckTLD() {
  11019. var result = or(obsDomain, dotAtom, domainLiteral)();
  11020. if (opts.rejectTLD) {
  11021. if (result && result.semantic && result.semantic.indexOf('.') < 0) {
  11022. return null;
  11023. }
  11024. }
  11025. // strip all whitespace from domains
  11026. if (result) {
  11027. result.semantic = result.semantic.replace(/\s+/g, '');
  11028. }
  11029. return result;
  11030. }());
  11031. }
  11032. // addr-spec = local-part "@" domain
  11033. function addrSpec() {
  11034. return wrap('addr-spec', and(localPart, literal('@'), domain)());
  11035. }
  11036. // 3.6.2 Originator Fields
  11037. // Below we only parse the field body, not the name of the field
  11038. // like "From:", "Sender:", or "Reply-To:". Other libraries that
  11039. // parse email headers can parse those and defer to these productions
  11040. // for the "RFC 5322" part.
  11041. // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields
  11042. // from = "From:" (mailbox-list / address-list) CRLF
  11043. function fromSpec() {
  11044. return wrap('from', or(mailboxList, addressList)());
  11045. }
  11046. // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields
  11047. // sender = "Sender:" (mailbox / address) CRLF
  11048. function senderSpec() {
  11049. return wrap('sender', or(mailbox, address)());
  11050. }
  11051. // RFC 6854 2.1. Replacement of RFC 5322, Section 3.6.2. Originator Fields
  11052. // reply-to = "Reply-To:" address-list CRLF
  11053. function replyToSpec() {
  11054. return wrap('reply-to', addressList());
  11055. }
  11056. // 4.1. Miscellaneous Obsolete Tokens
  11057. // obs-NO-WS-CTL = %d1-8 / ; US-ASCII control
  11058. // %d11 / ; characters that do not
  11059. // %d12 / ; include the carriage
  11060. // %d14-31 / ; return, line feed, and
  11061. // %d127 ; white space characters
  11062. function obsNoWsCtl() {
  11063. return opts.strict ? null : wrap('obs-NO-WS-CTL', compareToken(function (tok) {
  11064. var code = tok.charCodeAt(0);
  11065. return 1 <= code && code <= 8 || 11 === code || 12 === code || 14 <= code && code <= 31 || 127 === code;
  11066. }));
  11067. }
  11068. // obs-ctext = obs-NO-WS-CTL
  11069. function obsCtext() {
  11070. return opts.strict ? null : wrap('obs-ctext', obsNoWsCtl());
  11071. }
  11072. // obs-qtext = obs-NO-WS-CTL
  11073. function obsQtext() {
  11074. return opts.strict ? null : wrap('obs-qtext', obsNoWsCtl());
  11075. }
  11076. // obs-qp = "\" (%d0 / obs-NO-WS-CTL / LF / CR)
  11077. function obsQP() {
  11078. return opts.strict ? null : wrap('obs-qp', and(literal('\\'), or(literal('\0'), obsNoWsCtl, lf, cr))());
  11079. }
  11080. // obs-phrase = word *(word / "." / CFWS)
  11081. function obsPhrase() {
  11082. if (opts.strict) return null;
  11083. return opts.atInDisplayName ? wrap('obs-phrase', and(word, star(or(word, literal('.'), literal('@'), colwsp(cfws))))()) : wrap('obs-phrase', and(word, star(or(word, literal('.'), colwsp(cfws))))());
  11084. }
  11085. // 4.2. Obsolete Folding White Space
  11086. // NOTE: read the errata http://www.rfc-editor.org/errata_search.php?rfc=5322&eid=1908
  11087. // obs-FWS = 1*([CRLF] WSP)
  11088. function obsFws() {
  11089. return opts.strict ? null : wrap('obs-FWS', star(and(invis(opt(crlf)), wsp), 1)());
  11090. }
  11091. // 4.4. Obsolete Addressing
  11092. // obs-angle-addr = [CFWS] "<" obs-route addr-spec ">" [CFWS]
  11093. function obsAngleAddr() {
  11094. return opts.strict ? null : wrap('obs-angle-addr', and(invis(opt(cfws)), literal('<'), obsRoute, addrSpec, literal('>'), invis(opt(cfws)))());
  11095. }
  11096. // obs-route = obs-domain-list ":"
  11097. function obsRoute() {
  11098. return opts.strict ? null : wrap('obs-route', and(obsDomainList, literal(':'))());
  11099. }
  11100. // obs-domain-list = *(CFWS / ",") "@" domain
  11101. // *("," [CFWS] ["@" domain])
  11102. function obsDomainList() {
  11103. return opts.strict ? null : wrap('obs-domain-list', and(star(or(invis(cfws), literal(','))), literal('@'), domain, star(and(literal(','), invis(opt(cfws)), opt(and(literal('@'), domain)))))());
  11104. }
  11105. // obs-mbox-list = *([CFWS] ",") mailbox *("," [mailbox / CFWS])
  11106. function obsMboxList() {
  11107. return opts.strict ? null : wrap('obs-mbox-list', and(star(and(invis(opt(cfws)), literal(','))), mailbox, star(and(literal(','), opt(and(mailbox, invis(cfws))))))());
  11108. }
  11109. // obs-addr-list = *([CFWS] ",") address *("," [address / CFWS])
  11110. function obsAddrList() {
  11111. return opts.strict ? null : wrap('obs-addr-list', and(star(and(invis(opt(cfws)), literal(','))), address, star(and(literal(','), opt(and(address, invis(cfws))))))());
  11112. }
  11113. // obs-group-list = 1*([CFWS] ",") [CFWS]
  11114. function obsGroupList() {
  11115. return opts.strict ? null : wrap('obs-group-list', and(star(and(invis(opt(cfws)), literal(',')), 1), invis(opt(cfws)))());
  11116. }
  11117. // obs-local-part = word *("." word)
  11118. function obsLocalPart() {
  11119. return opts.strict ? null : wrap('obs-local-part', and(word, star(and(literal('.'), word)))());
  11120. }
  11121. // obs-domain = atom *("." atom)
  11122. function obsDomain() {
  11123. return opts.strict ? null : wrap('obs-domain', and(atom, star(and(literal('.'), atom)))());
  11124. }
  11125. // obs-dtext = obs-NO-WS-CTL / quoted-pair
  11126. function obsDtext() {
  11127. return opts.strict ? null : wrap('obs-dtext', or(obsNoWsCtl, quotedPair)());
  11128. }
  11129. /////////////////////////////////////////////////////
  11130. // ast analysis
  11131. function findNode(name, root) {
  11132. var i, stack, node;
  11133. if (root === null || root === undefined) {
  11134. return null;
  11135. }
  11136. stack = [root];
  11137. while (stack.length > 0) {
  11138. node = stack.pop();
  11139. if (node.name === name) {
  11140. return node;
  11141. }
  11142. for (i = node.children.length - 1; i >= 0; i -= 1) {
  11143. stack.push(node.children[i]);
  11144. }
  11145. }
  11146. return null;
  11147. }
  11148. function findAllNodes(name, root) {
  11149. var i, stack, node, result;
  11150. if (root === null || root === undefined) {
  11151. return null;
  11152. }
  11153. stack = [root];
  11154. result = [];
  11155. while (stack.length > 0) {
  11156. node = stack.pop();
  11157. if (node.name === name) {
  11158. result.push(node);
  11159. }
  11160. for (i = node.children.length - 1; i >= 0; i -= 1) {
  11161. stack.push(node.children[i]);
  11162. }
  11163. }
  11164. return result;
  11165. }
  11166. function findAllNodesNoChildren(names, root) {
  11167. var i, stack, node, result, namesLookup;
  11168. if (root === null || root === undefined) {
  11169. return null;
  11170. }
  11171. stack = [root];
  11172. result = [];
  11173. namesLookup = {};
  11174. for (i = 0; i < names.length; i += 1) {
  11175. namesLookup[names[i]] = true;
  11176. }
  11177. while (stack.length > 0) {
  11178. node = stack.pop();
  11179. if (node.name in namesLookup) {
  11180. result.push(node);
  11181. // don't look at children (hence findAllNodesNoChildren)
  11182. } else {
  11183. for (i = node.children.length - 1; i >= 0; i -= 1) {
  11184. stack.push(node.children[i]);
  11185. }
  11186. }
  11187. }
  11188. return result;
  11189. }
  11190. function giveResult(ast) {
  11191. var addresses, groupsAndMailboxes, i, groupOrMailbox, result;
  11192. if (ast === null) {
  11193. return null;
  11194. }
  11195. addresses = [];
  11196. // An address is a 'group' (i.e. a list of mailboxes) or a 'mailbox'.
  11197. groupsAndMailboxes = findAllNodesNoChildren(['group', 'mailbox'], ast);
  11198. for (i = 0; i < groupsAndMailboxes.length; i += 1) {
  11199. groupOrMailbox = groupsAndMailboxes[i];
  11200. if (groupOrMailbox.name === 'group') {
  11201. addresses.push(giveResultGroup(groupOrMailbox));
  11202. } else if (groupOrMailbox.name === 'mailbox') {
  11203. addresses.push(giveResultMailbox(groupOrMailbox));
  11204. }
  11205. }
  11206. result = {
  11207. ast: ast,
  11208. addresses: addresses
  11209. };
  11210. if (opts.simple) {
  11211. result = simplifyResult(result);
  11212. }
  11213. if (opts.oneResult) {
  11214. return oneResult(result);
  11215. }
  11216. if (opts.simple) {
  11217. return result && result.addresses;
  11218. } else {
  11219. return result;
  11220. }
  11221. }
  11222. function giveResultGroup(group) {
  11223. var i;
  11224. var groupName = findNode('display-name', group);
  11225. var groupResultMailboxes = [];
  11226. var mailboxes = findAllNodesNoChildren(['mailbox'], group);
  11227. for (i = 0; i < mailboxes.length; i += 1) {
  11228. groupResultMailboxes.push(giveResultMailbox(mailboxes[i]));
  11229. }
  11230. return {
  11231. node: group,
  11232. parts: {
  11233. name: groupName
  11234. },
  11235. type: group.name, // 'group'
  11236. name: grabSemantic(groupName),
  11237. addresses: groupResultMailboxes
  11238. };
  11239. }
  11240. function giveResultMailbox(mailbox) {
  11241. var name = findNode('display-name', mailbox);
  11242. var aspec = findNode('addr-spec', mailbox);
  11243. var cfws = findAllNodes('cfws', mailbox);
  11244. var comments = findAllNodesNoChildren(['comment'], mailbox);
  11245. var local = findNode('local-part', aspec);
  11246. var domain = findNode('domain', aspec);
  11247. return {
  11248. node: mailbox,
  11249. parts: {
  11250. name: name,
  11251. address: aspec,
  11252. local: local,
  11253. domain: domain,
  11254. comments: cfws
  11255. },
  11256. type: mailbox.name, // 'mailbox'
  11257. name: grabSemantic(name),
  11258. address: grabSemantic(aspec),
  11259. local: grabSemantic(local),
  11260. domain: grabSemantic(domain),
  11261. comments: concatComments(comments),
  11262. groupName: grabSemantic(mailbox.groupName)
  11263. };
  11264. }
  11265. function grabSemantic(n) {
  11266. return n !== null && n !== undefined ? n.semantic : null;
  11267. }
  11268. function simplifyResult(result) {
  11269. var i;
  11270. if (result && result.addresses) {
  11271. for (i = 0; i < result.addresses.length; i += 1) {
  11272. delete result.addresses[i].node;
  11273. }
  11274. }
  11275. return result;
  11276. }
  11277. function concatComments(comments) {
  11278. var result = '';
  11279. if (comments) {
  11280. for (var i = 0; i < comments.length; i += 1) {
  11281. result += grabSemantic(comments[i]);
  11282. }
  11283. }
  11284. return result;
  11285. }
  11286. function oneResult(result) {
  11287. if (!result) {
  11288. return null;
  11289. }
  11290. if (!opts.partial && result.addresses.length > 1) {
  11291. return null;
  11292. }
  11293. return result.addresses && result.addresses[0];
  11294. }
  11295. /////////////////////////////////////////////////////
  11296. var parseString, pos, len, parsed, startProduction;
  11297. opts = handleOpts(opts, {});
  11298. if (opts === null) {
  11299. return null;
  11300. }
  11301. parseString = opts.input;
  11302. startProduction = {
  11303. 'address': address,
  11304. 'address-list': addressList,
  11305. 'angle-addr': angleAddr,
  11306. 'from': fromSpec,
  11307. 'group': group,
  11308. 'mailbox': mailbox,
  11309. 'mailbox-list': mailboxList,
  11310. 'reply-to': replyToSpec,
  11311. 'sender': senderSpec
  11312. }[opts.startAt] || addressList;
  11313. if (!opts.strict) {
  11314. initialize();
  11315. opts.strict = true;
  11316. parsed = startProduction(parseString);
  11317. if (opts.partial || !inStr()) {
  11318. return giveResult(parsed);
  11319. }
  11320. opts.strict = false;
  11321. }
  11322. initialize();
  11323. parsed = startProduction(parseString);
  11324. if (!opts.partial && inStr()) {
  11325. return null;
  11326. }
  11327. return giveResult(parsed);
  11328. }
  11329. function parseOneAddressSimple(opts) {
  11330. return parse5322(handleOpts(opts, {
  11331. oneResult: true,
  11332. rfc6532: true,
  11333. simple: true,
  11334. startAt: 'address-list'
  11335. }));
  11336. }
  11337. function parseAddressListSimple(opts) {
  11338. return parse5322(handleOpts(opts, {
  11339. rfc6532: true,
  11340. simple: true,
  11341. startAt: 'address-list'
  11342. }));
  11343. }
  11344. function parseFromSimple(opts) {
  11345. return parse5322(handleOpts(opts, {
  11346. rfc6532: true,
  11347. simple: true,
  11348. startAt: 'from'
  11349. }));
  11350. }
  11351. function parseSenderSimple(opts) {
  11352. return parse5322(handleOpts(opts, {
  11353. oneResult: true,
  11354. rfc6532: true,
  11355. simple: true,
  11356. startAt: 'sender'
  11357. }));
  11358. }
  11359. function parseReplyToSimple(opts) {
  11360. return parse5322(handleOpts(opts, {
  11361. rfc6532: true,
  11362. simple: true,
  11363. startAt: 'reply-to'
  11364. }));
  11365. }
  11366. function handleOpts(opts, defs) {
  11367. function isString(str) {
  11368. return Object.prototype.toString.call(str) === '[object String]';
  11369. }
  11370. function isObject(o) {
  11371. return o === Object(o);
  11372. }
  11373. function isNullUndef(o) {
  11374. return o === null || o === undefined;
  11375. }
  11376. var defaults, o;
  11377. if (isString(opts)) {
  11378. opts = { input: opts };
  11379. } else if (!isObject(opts)) {
  11380. return null;
  11381. }
  11382. if (!isString(opts.input)) {
  11383. return null;
  11384. }
  11385. if (!defs) {
  11386. return null;
  11387. }
  11388. defaults = {
  11389. oneResult: false,
  11390. partial: false,
  11391. rejectTLD: false,
  11392. rfc6532: false,
  11393. simple: false,
  11394. startAt: 'address-list',
  11395. strict: false,
  11396. atInDisplayName: false
  11397. };
  11398. for (o in defaults) {
  11399. if (isNullUndef(opts[o])) {
  11400. opts[o] = !isNullUndef(defs[o]) ? defs[o] : defaults[o];
  11401. }
  11402. }
  11403. return opts;
  11404. }
  11405. parse5322.parseOneAddress = parseOneAddressSimple;
  11406. parse5322.parseAddressList = parseAddressListSimple;
  11407. parse5322.parseFrom = parseFromSimple;
  11408. parse5322.parseSender = parseSenderSimple;
  11409. parse5322.parseReplyTo = parseReplyToSimple;
  11410. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  11411. module.exports = parse5322;
  11412. } else {
  11413. global.emailAddresses = parse5322;
  11414. }
  11415. })(undefined);
  11416. },{}],34:[function(require,module,exports){
  11417. var hash = exports;
  11418. hash.utils = require('./hash/utils');
  11419. hash.common = require('./hash/common');
  11420. hash.sha = require('./hash/sha');
  11421. hash.ripemd = require('./hash/ripemd');
  11422. hash.hmac = require('./hash/hmac');
  11423. // Proxy hash functions to the main object
  11424. hash.sha1 = hash.sha.sha1;
  11425. hash.sha256 = hash.sha.sha256;
  11426. hash.sha224 = hash.sha.sha224;
  11427. hash.sha384 = hash.sha.sha384;
  11428. hash.sha512 = hash.sha.sha512;
  11429. hash.ripemd160 = hash.ripemd.ripemd160;
  11430. },{"./hash/common":35,"./hash/hmac":36,"./hash/ripemd":37,"./hash/sha":38,"./hash/utils":45}],35:[function(require,module,exports){
  11431. 'use strict';
  11432. var utils = require('./utils');
  11433. var assert = require('minimalistic-assert');
  11434. function BlockHash() {
  11435. this.pending = null;
  11436. this.pendingTotal = 0;
  11437. this.blockSize = this.constructor.blockSize;
  11438. this.outSize = this.constructor.outSize;
  11439. this.hmacStrength = this.constructor.hmacStrength;
  11440. this.padLength = this.constructor.padLength / 8;
  11441. this.endian = 'big';
  11442. this._delta8 = this.blockSize / 8;
  11443. this._delta32 = this.blockSize / 32;
  11444. }
  11445. exports.BlockHash = BlockHash;
  11446. BlockHash.prototype.update = function update(msg, enc) {
  11447. // Convert message to array, pad it, and join into 32bit blocks
  11448. msg = utils.toArray(msg, enc);
  11449. if (!this.pending)
  11450. this.pending = msg;
  11451. else
  11452. this.pending = this.pending.concat(msg);
  11453. this.pendingTotal += msg.length;
  11454. // Enough data, try updating
  11455. if (this.pending.length >= this._delta8) {
  11456. msg = this.pending;
  11457. // Process pending data in blocks
  11458. var r = msg.length % this._delta8;
  11459. this.pending = msg.slice(msg.length - r, msg.length);
  11460. if (this.pending.length === 0)
  11461. this.pending = null;
  11462. msg = utils.join32(msg, 0, msg.length - r, this.endian);
  11463. for (var i = 0; i < msg.length; i += this._delta32)
  11464. this._update(msg, i, i + this._delta32);
  11465. }
  11466. return this;
  11467. };
  11468. BlockHash.prototype.digest = function digest(enc) {
  11469. this.update(this._pad());
  11470. assert(this.pending === null);
  11471. return this._digest(enc);
  11472. };
  11473. BlockHash.prototype._pad = function pad() {
  11474. var len = this.pendingTotal;
  11475. var bytes = this._delta8;
  11476. var k = bytes - ((len + this.padLength) % bytes);
  11477. var res = new Array(k + this.padLength);
  11478. res[0] = 0x80;
  11479. for (var i = 1; i < k; i++)
  11480. res[i] = 0;
  11481. // Append length
  11482. len <<= 3;
  11483. if (this.endian === 'big') {
  11484. for (var t = 8; t < this.padLength; t++)
  11485. res[i++] = 0;
  11486. res[i++] = 0;
  11487. res[i++] = 0;
  11488. res[i++] = 0;
  11489. res[i++] = 0;
  11490. res[i++] = (len >>> 24) & 0xff;
  11491. res[i++] = (len >>> 16) & 0xff;
  11492. res[i++] = (len >>> 8) & 0xff;
  11493. res[i++] = len & 0xff;
  11494. } else {
  11495. res[i++] = len & 0xff;
  11496. res[i++] = (len >>> 8) & 0xff;
  11497. res[i++] = (len >>> 16) & 0xff;
  11498. res[i++] = (len >>> 24) & 0xff;
  11499. res[i++] = 0;
  11500. res[i++] = 0;
  11501. res[i++] = 0;
  11502. res[i++] = 0;
  11503. for (t = 8; t < this.padLength; t++)
  11504. res[i++] = 0;
  11505. }
  11506. return res;
  11507. };
  11508. },{"./utils":45,"minimalistic-assert":48}],36:[function(require,module,exports){
  11509. 'use strict';
  11510. var utils = require('./utils');
  11511. var assert = require('minimalistic-assert');
  11512. function Hmac(hash, key, enc) {
  11513. if (!(this instanceof Hmac))
  11514. return new Hmac(hash, key, enc);
  11515. this.Hash = hash;
  11516. this.blockSize = hash.blockSize / 8;
  11517. this.outSize = hash.outSize / 8;
  11518. this.inner = null;
  11519. this.outer = null;
  11520. this._init(utils.toArray(key, enc));
  11521. }
  11522. module.exports = Hmac;
  11523. Hmac.prototype._init = function init(key) {
  11524. // Shorten key, if needed
  11525. if (key.length > this.blockSize)
  11526. key = new this.Hash().update(key).digest();
  11527. assert(key.length <= this.blockSize);
  11528. // Add padding to key
  11529. for (var i = key.length; i < this.blockSize; i++)
  11530. key.push(0);
  11531. for (i = 0; i < key.length; i++)
  11532. key[i] ^= 0x36;
  11533. this.inner = new this.Hash().update(key);
  11534. // 0x36 ^ 0x5c = 0x6a
  11535. for (i = 0; i < key.length; i++)
  11536. key[i] ^= 0x6a;
  11537. this.outer = new this.Hash().update(key);
  11538. };
  11539. Hmac.prototype.update = function update(msg, enc) {
  11540. this.inner.update(msg, enc);
  11541. return this;
  11542. };
  11543. Hmac.prototype.digest = function digest(enc) {
  11544. this.outer.update(this.inner.digest());
  11545. return this.outer.digest(enc);
  11546. };
  11547. },{"./utils":45,"minimalistic-assert":48}],37:[function(require,module,exports){
  11548. 'use strict';
  11549. var utils = require('./utils');
  11550. var common = require('./common');
  11551. var rotl32 = utils.rotl32;
  11552. var sum32 = utils.sum32;
  11553. var sum32_3 = utils.sum32_3;
  11554. var sum32_4 = utils.sum32_4;
  11555. var BlockHash = common.BlockHash;
  11556. function RIPEMD160() {
  11557. if (!(this instanceof RIPEMD160))
  11558. return new RIPEMD160();
  11559. BlockHash.call(this);
  11560. this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
  11561. this.endian = 'little';
  11562. }
  11563. utils.inherits(RIPEMD160, BlockHash);
  11564. exports.ripemd160 = RIPEMD160;
  11565. RIPEMD160.blockSize = 512;
  11566. RIPEMD160.outSize = 160;
  11567. RIPEMD160.hmacStrength = 192;
  11568. RIPEMD160.padLength = 64;
  11569. RIPEMD160.prototype._update = function update(msg, start) {
  11570. var A = this.h[0];
  11571. var B = this.h[1];
  11572. var C = this.h[2];
  11573. var D = this.h[3];
  11574. var E = this.h[4];
  11575. var Ah = A;
  11576. var Bh = B;
  11577. var Ch = C;
  11578. var Dh = D;
  11579. var Eh = E;
  11580. for (var j = 0; j < 80; j++) {
  11581. var T = sum32(
  11582. rotl32(
  11583. sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)),
  11584. s[j]),
  11585. E);
  11586. A = E;
  11587. E = D;
  11588. D = rotl32(C, 10);
  11589. C = B;
  11590. B = T;
  11591. T = sum32(
  11592. rotl32(
  11593. sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),
  11594. sh[j]),
  11595. Eh);
  11596. Ah = Eh;
  11597. Eh = Dh;
  11598. Dh = rotl32(Ch, 10);
  11599. Ch = Bh;
  11600. Bh = T;
  11601. }
  11602. T = sum32_3(this.h[1], C, Dh);
  11603. this.h[1] = sum32_3(this.h[2], D, Eh);
  11604. this.h[2] = sum32_3(this.h[3], E, Ah);
  11605. this.h[3] = sum32_3(this.h[4], A, Bh);
  11606. this.h[4] = sum32_3(this.h[0], B, Ch);
  11607. this.h[0] = T;
  11608. };
  11609. RIPEMD160.prototype._digest = function digest(enc) {
  11610. if (enc === 'hex')
  11611. return utils.toHex32(this.h, 'little');
  11612. else
  11613. return utils.split32(this.h, 'little');
  11614. };
  11615. function f(j, x, y, z) {
  11616. if (j <= 15)
  11617. return x ^ y ^ z;
  11618. else if (j <= 31)
  11619. return (x & y) | ((~x) & z);
  11620. else if (j <= 47)
  11621. return (x | (~y)) ^ z;
  11622. else if (j <= 63)
  11623. return (x & z) | (y & (~z));
  11624. else
  11625. return x ^ (y | (~z));
  11626. }
  11627. function K(j) {
  11628. if (j <= 15)
  11629. return 0x00000000;
  11630. else if (j <= 31)
  11631. return 0x5a827999;
  11632. else if (j <= 47)
  11633. return 0x6ed9eba1;
  11634. else if (j <= 63)
  11635. return 0x8f1bbcdc;
  11636. else
  11637. return 0xa953fd4e;
  11638. }
  11639. function Kh(j) {
  11640. if (j <= 15)
  11641. return 0x50a28be6;
  11642. else if (j <= 31)
  11643. return 0x5c4dd124;
  11644. else if (j <= 47)
  11645. return 0x6d703ef3;
  11646. else if (j <= 63)
  11647. return 0x7a6d76e9;
  11648. else
  11649. return 0x00000000;
  11650. }
  11651. var r = [
  11652. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
  11653. 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
  11654. 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
  11655. 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
  11656. 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
  11657. ];
  11658. var rh = [
  11659. 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
  11660. 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
  11661. 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
  11662. 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
  11663. 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
  11664. ];
  11665. var s = [
  11666. 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
  11667. 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
  11668. 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
  11669. 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
  11670. 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
  11671. ];
  11672. var sh = [
  11673. 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
  11674. 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
  11675. 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
  11676. 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
  11677. 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
  11678. ];
  11679. },{"./common":35,"./utils":45}],38:[function(require,module,exports){
  11680. 'use strict';
  11681. exports.sha1 = require('./sha/1');
  11682. exports.sha224 = require('./sha/224');
  11683. exports.sha256 = require('./sha/256');
  11684. exports.sha384 = require('./sha/384');
  11685. exports.sha512 = require('./sha/512');
  11686. },{"./sha/1":39,"./sha/224":40,"./sha/256":41,"./sha/384":42,"./sha/512":43}],39:[function(require,module,exports){
  11687. 'use strict';
  11688. var utils = require('../utils');
  11689. var common = require('../common');
  11690. var shaCommon = require('./common');
  11691. var rotl32 = utils.rotl32;
  11692. var sum32 = utils.sum32;
  11693. var sum32_5 = utils.sum32_5;
  11694. var ft_1 = shaCommon.ft_1;
  11695. var BlockHash = common.BlockHash;
  11696. var sha1_K = [
  11697. 0x5A827999, 0x6ED9EBA1,
  11698. 0x8F1BBCDC, 0xCA62C1D6
  11699. ];
  11700. function SHA1() {
  11701. if (!(this instanceof SHA1))
  11702. return new SHA1();
  11703. BlockHash.call(this);
  11704. this.h = [
  11705. 0x67452301, 0xefcdab89, 0x98badcfe,
  11706. 0x10325476, 0xc3d2e1f0 ];
  11707. this.W = new Array(80);
  11708. }
  11709. utils.inherits(SHA1, BlockHash);
  11710. module.exports = SHA1;
  11711. SHA1.blockSize = 512;
  11712. SHA1.outSize = 160;
  11713. SHA1.hmacStrength = 80;
  11714. SHA1.padLength = 64;
  11715. SHA1.prototype._update = function _update(msg, start) {
  11716. var W = this.W;
  11717. for (var i = 0; i < 16; i++)
  11718. W[i] = msg[start + i];
  11719. for(; i < W.length; i++)
  11720. W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
  11721. var a = this.h[0];
  11722. var b = this.h[1];
  11723. var c = this.h[2];
  11724. var d = this.h[3];
  11725. var e = this.h[4];
  11726. for (i = 0; i < W.length; i++) {
  11727. var s = ~~(i / 20);
  11728. var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]);
  11729. e = d;
  11730. d = c;
  11731. c = rotl32(b, 30);
  11732. b = a;
  11733. a = t;
  11734. }
  11735. this.h[0] = sum32(this.h[0], a);
  11736. this.h[1] = sum32(this.h[1], b);
  11737. this.h[2] = sum32(this.h[2], c);
  11738. this.h[3] = sum32(this.h[3], d);
  11739. this.h[4] = sum32(this.h[4], e);
  11740. };
  11741. SHA1.prototype._digest = function digest(enc) {
  11742. if (enc === 'hex')
  11743. return utils.toHex32(this.h, 'big');
  11744. else
  11745. return utils.split32(this.h, 'big');
  11746. };
  11747. },{"../common":35,"../utils":45,"./common":44}],40:[function(require,module,exports){
  11748. 'use strict';
  11749. var utils = require('../utils');
  11750. var SHA256 = require('./256');
  11751. function SHA224() {
  11752. if (!(this instanceof SHA224))
  11753. return new SHA224();
  11754. SHA256.call(this);
  11755. this.h = [
  11756. 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
  11757. 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];
  11758. }
  11759. utils.inherits(SHA224, SHA256);
  11760. module.exports = SHA224;
  11761. SHA224.blockSize = 512;
  11762. SHA224.outSize = 224;
  11763. SHA224.hmacStrength = 192;
  11764. SHA224.padLength = 64;
  11765. SHA224.prototype._digest = function digest(enc) {
  11766. // Just truncate output
  11767. if (enc === 'hex')
  11768. return utils.toHex32(this.h.slice(0, 7), 'big');
  11769. else
  11770. return utils.split32(this.h.slice(0, 7), 'big');
  11771. };
  11772. },{"../utils":45,"./256":41}],41:[function(require,module,exports){
  11773. 'use strict';
  11774. var utils = require('../utils');
  11775. var common = require('../common');
  11776. var shaCommon = require('./common');
  11777. var assert = require('minimalistic-assert');
  11778. var sum32 = utils.sum32;
  11779. var sum32_4 = utils.sum32_4;
  11780. var sum32_5 = utils.sum32_5;
  11781. var ch32 = shaCommon.ch32;
  11782. var maj32 = shaCommon.maj32;
  11783. var s0_256 = shaCommon.s0_256;
  11784. var s1_256 = shaCommon.s1_256;
  11785. var g0_256 = shaCommon.g0_256;
  11786. var g1_256 = shaCommon.g1_256;
  11787. var BlockHash = common.BlockHash;
  11788. var sha256_K = [
  11789. 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
  11790. 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
  11791. 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
  11792. 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
  11793. 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
  11794. 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
  11795. 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
  11796. 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
  11797. 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
  11798. 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
  11799. 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
  11800. 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
  11801. 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
  11802. 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
  11803. 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
  11804. 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
  11805. ];
  11806. function SHA256() {
  11807. if (!(this instanceof SHA256))
  11808. return new SHA256();
  11809. BlockHash.call(this);
  11810. this.h = [
  11811. 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
  11812. 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
  11813. ];
  11814. this.k = sha256_K;
  11815. this.W = new Array(64);
  11816. }
  11817. utils.inherits(SHA256, BlockHash);
  11818. module.exports = SHA256;
  11819. SHA256.blockSize = 512;
  11820. SHA256.outSize = 256;
  11821. SHA256.hmacStrength = 192;
  11822. SHA256.padLength = 64;
  11823. SHA256.prototype._update = function _update(msg, start) {
  11824. var W = this.W;
  11825. for (var i = 0; i < 16; i++)
  11826. W[i] = msg[start + i];
  11827. for (; i < W.length; i++)
  11828. W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);
  11829. var a = this.h[0];
  11830. var b = this.h[1];
  11831. var c = this.h[2];
  11832. var d = this.h[3];
  11833. var e = this.h[4];
  11834. var f = this.h[5];
  11835. var g = this.h[6];
  11836. var h = this.h[7];
  11837. assert(this.k.length === W.length);
  11838. for (i = 0; i < W.length; i++) {
  11839. var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);
  11840. var T2 = sum32(s0_256(a), maj32(a, b, c));
  11841. h = g;
  11842. g = f;
  11843. f = e;
  11844. e = sum32(d, T1);
  11845. d = c;
  11846. c = b;
  11847. b = a;
  11848. a = sum32(T1, T2);
  11849. }
  11850. this.h[0] = sum32(this.h[0], a);
  11851. this.h[1] = sum32(this.h[1], b);
  11852. this.h[2] = sum32(this.h[2], c);
  11853. this.h[3] = sum32(this.h[3], d);
  11854. this.h[4] = sum32(this.h[4], e);
  11855. this.h[5] = sum32(this.h[5], f);
  11856. this.h[6] = sum32(this.h[6], g);
  11857. this.h[7] = sum32(this.h[7], h);
  11858. };
  11859. SHA256.prototype._digest = function digest(enc) {
  11860. if (enc === 'hex')
  11861. return utils.toHex32(this.h, 'big');
  11862. else
  11863. return utils.split32(this.h, 'big');
  11864. };
  11865. },{"../common":35,"../utils":45,"./common":44,"minimalistic-assert":48}],42:[function(require,module,exports){
  11866. 'use strict';
  11867. var utils = require('../utils');
  11868. var SHA512 = require('./512');
  11869. function SHA384() {
  11870. if (!(this instanceof SHA384))
  11871. return new SHA384();
  11872. SHA512.call(this);
  11873. this.h = [
  11874. 0xcbbb9d5d, 0xc1059ed8,
  11875. 0x629a292a, 0x367cd507,
  11876. 0x9159015a, 0x3070dd17,
  11877. 0x152fecd8, 0xf70e5939,
  11878. 0x67332667, 0xffc00b31,
  11879. 0x8eb44a87, 0x68581511,
  11880. 0xdb0c2e0d, 0x64f98fa7,
  11881. 0x47b5481d, 0xbefa4fa4 ];
  11882. }
  11883. utils.inherits(SHA384, SHA512);
  11884. module.exports = SHA384;
  11885. SHA384.blockSize = 1024;
  11886. SHA384.outSize = 384;
  11887. SHA384.hmacStrength = 192;
  11888. SHA384.padLength = 128;
  11889. SHA384.prototype._digest = function digest(enc) {
  11890. if (enc === 'hex')
  11891. return utils.toHex32(this.h.slice(0, 12), 'big');
  11892. else
  11893. return utils.split32(this.h.slice(0, 12), 'big');
  11894. };
  11895. },{"../utils":45,"./512":43}],43:[function(require,module,exports){
  11896. 'use strict';
  11897. var utils = require('../utils');
  11898. var common = require('../common');
  11899. var assert = require('minimalistic-assert');
  11900. var rotr64_hi = utils.rotr64_hi;
  11901. var rotr64_lo = utils.rotr64_lo;
  11902. var shr64_hi = utils.shr64_hi;
  11903. var shr64_lo = utils.shr64_lo;
  11904. var sum64 = utils.sum64;
  11905. var sum64_hi = utils.sum64_hi;
  11906. var sum64_lo = utils.sum64_lo;
  11907. var sum64_4_hi = utils.sum64_4_hi;
  11908. var sum64_4_lo = utils.sum64_4_lo;
  11909. var sum64_5_hi = utils.sum64_5_hi;
  11910. var sum64_5_lo = utils.sum64_5_lo;
  11911. var BlockHash = common.BlockHash;
  11912. var sha512_K = [
  11913. 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
  11914. 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
  11915. 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
  11916. 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
  11917. 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
  11918. 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
  11919. 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
  11920. 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
  11921. 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
  11922. 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
  11923. 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
  11924. 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
  11925. 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
  11926. 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
  11927. 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
  11928. 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
  11929. 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
  11930. 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
  11931. 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
  11932. 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
  11933. 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
  11934. 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
  11935. 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
  11936. 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
  11937. 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
  11938. 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
  11939. 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
  11940. 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
  11941. 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
  11942. 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
  11943. 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
  11944. 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
  11945. 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
  11946. 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
  11947. 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
  11948. 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
  11949. 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
  11950. 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
  11951. 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
  11952. 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
  11953. ];
  11954. function SHA512() {
  11955. if (!(this instanceof SHA512))
  11956. return new SHA512();
  11957. BlockHash.call(this);
  11958. this.h = [
  11959. 0x6a09e667, 0xf3bcc908,
  11960. 0xbb67ae85, 0x84caa73b,
  11961. 0x3c6ef372, 0xfe94f82b,
  11962. 0xa54ff53a, 0x5f1d36f1,
  11963. 0x510e527f, 0xade682d1,
  11964. 0x9b05688c, 0x2b3e6c1f,
  11965. 0x1f83d9ab, 0xfb41bd6b,
  11966. 0x5be0cd19, 0x137e2179 ];
  11967. this.k = sha512_K;
  11968. this.W = new Array(160);
  11969. }
  11970. utils.inherits(SHA512, BlockHash);
  11971. module.exports = SHA512;
  11972. SHA512.blockSize = 1024;
  11973. SHA512.outSize = 512;
  11974. SHA512.hmacStrength = 192;
  11975. SHA512.padLength = 128;
  11976. SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
  11977. var W = this.W;
  11978. // 32 x 32bit words
  11979. for (var i = 0; i < 32; i++)
  11980. W[i] = msg[start + i];
  11981. for (; i < W.length; i += 2) {
  11982. var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2
  11983. var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
  11984. var c1_hi = W[i - 14]; // i - 7
  11985. var c1_lo = W[i - 13];
  11986. var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15
  11987. var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
  11988. var c3_hi = W[i - 32]; // i - 16
  11989. var c3_lo = W[i - 31];
  11990. W[i] = sum64_4_hi(
  11991. c0_hi, c0_lo,
  11992. c1_hi, c1_lo,
  11993. c2_hi, c2_lo,
  11994. c3_hi, c3_lo);
  11995. W[i + 1] = sum64_4_lo(
  11996. c0_hi, c0_lo,
  11997. c1_hi, c1_lo,
  11998. c2_hi, c2_lo,
  11999. c3_hi, c3_lo);
  12000. }
  12001. };
  12002. SHA512.prototype._update = function _update(msg, start) {
  12003. this._prepareBlock(msg, start);
  12004. var W = this.W;
  12005. var ah = this.h[0];
  12006. var al = this.h[1];
  12007. var bh = this.h[2];
  12008. var bl = this.h[3];
  12009. var ch = this.h[4];
  12010. var cl = this.h[5];
  12011. var dh = this.h[6];
  12012. var dl = this.h[7];
  12013. var eh = this.h[8];
  12014. var el = this.h[9];
  12015. var fh = this.h[10];
  12016. var fl = this.h[11];
  12017. var gh = this.h[12];
  12018. var gl = this.h[13];
  12019. var hh = this.h[14];
  12020. var hl = this.h[15];
  12021. assert(this.k.length === W.length);
  12022. for (var i = 0; i < W.length; i += 2) {
  12023. var c0_hi = hh;
  12024. var c0_lo = hl;
  12025. var c1_hi = s1_512_hi(eh, el);
  12026. var c1_lo = s1_512_lo(eh, el);
  12027. var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);
  12028. var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
  12029. var c3_hi = this.k[i];
  12030. var c3_lo = this.k[i + 1];
  12031. var c4_hi = W[i];
  12032. var c4_lo = W[i + 1];
  12033. var T1_hi = sum64_5_hi(
  12034. c0_hi, c0_lo,
  12035. c1_hi, c1_lo,
  12036. c2_hi, c2_lo,
  12037. c3_hi, c3_lo,
  12038. c4_hi, c4_lo);
  12039. var T1_lo = sum64_5_lo(
  12040. c0_hi, c0_lo,
  12041. c1_hi, c1_lo,
  12042. c2_hi, c2_lo,
  12043. c3_hi, c3_lo,
  12044. c4_hi, c4_lo);
  12045. c0_hi = s0_512_hi(ah, al);
  12046. c0_lo = s0_512_lo(ah, al);
  12047. c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);
  12048. c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
  12049. var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);
  12050. var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);
  12051. hh = gh;
  12052. hl = gl;
  12053. gh = fh;
  12054. gl = fl;
  12055. fh = eh;
  12056. fl = el;
  12057. eh = sum64_hi(dh, dl, T1_hi, T1_lo);
  12058. el = sum64_lo(dl, dl, T1_hi, T1_lo);
  12059. dh = ch;
  12060. dl = cl;
  12061. ch = bh;
  12062. cl = bl;
  12063. bh = ah;
  12064. bl = al;
  12065. ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);
  12066. al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);
  12067. }
  12068. sum64(this.h, 0, ah, al);
  12069. sum64(this.h, 2, bh, bl);
  12070. sum64(this.h, 4, ch, cl);
  12071. sum64(this.h, 6, dh, dl);
  12072. sum64(this.h, 8, eh, el);
  12073. sum64(this.h, 10, fh, fl);
  12074. sum64(this.h, 12, gh, gl);
  12075. sum64(this.h, 14, hh, hl);
  12076. };
  12077. SHA512.prototype._digest = function digest(enc) {
  12078. if (enc === 'hex')
  12079. return utils.toHex32(this.h, 'big');
  12080. else
  12081. return utils.split32(this.h, 'big');
  12082. };
  12083. function ch64_hi(xh, xl, yh, yl, zh) {
  12084. var r = (xh & yh) ^ ((~xh) & zh);
  12085. if (r < 0)
  12086. r += 0x100000000;
  12087. return r;
  12088. }
  12089. function ch64_lo(xh, xl, yh, yl, zh, zl) {
  12090. var r = (xl & yl) ^ ((~xl) & zl);
  12091. if (r < 0)
  12092. r += 0x100000000;
  12093. return r;
  12094. }
  12095. function maj64_hi(xh, xl, yh, yl, zh) {
  12096. var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
  12097. if (r < 0)
  12098. r += 0x100000000;
  12099. return r;
  12100. }
  12101. function maj64_lo(xh, xl, yh, yl, zh, zl) {
  12102. var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
  12103. if (r < 0)
  12104. r += 0x100000000;
  12105. return r;
  12106. }
  12107. function s0_512_hi(xh, xl) {
  12108. var c0_hi = rotr64_hi(xh, xl, 28);
  12109. var c1_hi = rotr64_hi(xl, xh, 2); // 34
  12110. var c2_hi = rotr64_hi(xl, xh, 7); // 39
  12111. var r = c0_hi ^ c1_hi ^ c2_hi;
  12112. if (r < 0)
  12113. r += 0x100000000;
  12114. return r;
  12115. }
  12116. function s0_512_lo(xh, xl) {
  12117. var c0_lo = rotr64_lo(xh, xl, 28);
  12118. var c1_lo = rotr64_lo(xl, xh, 2); // 34
  12119. var c2_lo = rotr64_lo(xl, xh, 7); // 39
  12120. var r = c0_lo ^ c1_lo ^ c2_lo;
  12121. if (r < 0)
  12122. r += 0x100000000;
  12123. return r;
  12124. }
  12125. function s1_512_hi(xh, xl) {
  12126. var c0_hi = rotr64_hi(xh, xl, 14);
  12127. var c1_hi = rotr64_hi(xh, xl, 18);
  12128. var c2_hi = rotr64_hi(xl, xh, 9); // 41
  12129. var r = c0_hi ^ c1_hi ^ c2_hi;
  12130. if (r < 0)
  12131. r += 0x100000000;
  12132. return r;
  12133. }
  12134. function s1_512_lo(xh, xl) {
  12135. var c0_lo = rotr64_lo(xh, xl, 14);
  12136. var c1_lo = rotr64_lo(xh, xl, 18);
  12137. var c2_lo = rotr64_lo(xl, xh, 9); // 41
  12138. var r = c0_lo ^ c1_lo ^ c2_lo;
  12139. if (r < 0)
  12140. r += 0x100000000;
  12141. return r;
  12142. }
  12143. function g0_512_hi(xh, xl) {
  12144. var c0_hi = rotr64_hi(xh, xl, 1);
  12145. var c1_hi = rotr64_hi(xh, xl, 8);
  12146. var c2_hi = shr64_hi(xh, xl, 7);
  12147. var r = c0_hi ^ c1_hi ^ c2_hi;
  12148. if (r < 0)
  12149. r += 0x100000000;
  12150. return r;
  12151. }
  12152. function g0_512_lo(xh, xl) {
  12153. var c0_lo = rotr64_lo(xh, xl, 1);
  12154. var c1_lo = rotr64_lo(xh, xl, 8);
  12155. var c2_lo = shr64_lo(xh, xl, 7);
  12156. var r = c0_lo ^ c1_lo ^ c2_lo;
  12157. if (r < 0)
  12158. r += 0x100000000;
  12159. return r;
  12160. }
  12161. function g1_512_hi(xh, xl) {
  12162. var c0_hi = rotr64_hi(xh, xl, 19);
  12163. var c1_hi = rotr64_hi(xl, xh, 29); // 61
  12164. var c2_hi = shr64_hi(xh, xl, 6);
  12165. var r = c0_hi ^ c1_hi ^ c2_hi;
  12166. if (r < 0)
  12167. r += 0x100000000;
  12168. return r;
  12169. }
  12170. function g1_512_lo(xh, xl) {
  12171. var c0_lo = rotr64_lo(xh, xl, 19);
  12172. var c1_lo = rotr64_lo(xl, xh, 29); // 61
  12173. var c2_lo = shr64_lo(xh, xl, 6);
  12174. var r = c0_lo ^ c1_lo ^ c2_lo;
  12175. if (r < 0)
  12176. r += 0x100000000;
  12177. return r;
  12178. }
  12179. },{"../common":35,"../utils":45,"minimalistic-assert":48}],44:[function(require,module,exports){
  12180. 'use strict';
  12181. var utils = require('../utils');
  12182. var rotr32 = utils.rotr32;
  12183. function ft_1(s, x, y, z) {
  12184. if (s === 0)
  12185. return ch32(x, y, z);
  12186. if (s === 1 || s === 3)
  12187. return p32(x, y, z);
  12188. if (s === 2)
  12189. return maj32(x, y, z);
  12190. }
  12191. exports.ft_1 = ft_1;
  12192. function ch32(x, y, z) {
  12193. return (x & y) ^ ((~x) & z);
  12194. }
  12195. exports.ch32 = ch32;
  12196. function maj32(x, y, z) {
  12197. return (x & y) ^ (x & z) ^ (y & z);
  12198. }
  12199. exports.maj32 = maj32;
  12200. function p32(x, y, z) {
  12201. return x ^ y ^ z;
  12202. }
  12203. exports.p32 = p32;
  12204. function s0_256(x) {
  12205. return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);
  12206. }
  12207. exports.s0_256 = s0_256;
  12208. function s1_256(x) {
  12209. return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);
  12210. }
  12211. exports.s1_256 = s1_256;
  12212. function g0_256(x) {
  12213. return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);
  12214. }
  12215. exports.g0_256 = g0_256;
  12216. function g1_256(x) {
  12217. return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);
  12218. }
  12219. exports.g1_256 = g1_256;
  12220. },{"../utils":45}],45:[function(require,module,exports){
  12221. 'use strict';
  12222. var assert = require('minimalistic-assert');
  12223. var inherits = require('inherits');
  12224. exports.inherits = inherits;
  12225. function toArray(msg, enc) {
  12226. if (Array.isArray(msg))
  12227. return msg.slice();
  12228. if (!msg)
  12229. return [];
  12230. var res = [];
  12231. if (typeof msg === 'string') {
  12232. if (!enc) {
  12233. for (var i = 0; i < msg.length; i++) {
  12234. var c = msg.charCodeAt(i);
  12235. var hi = c >> 8;
  12236. var lo = c & 0xff;
  12237. if (hi)
  12238. res.push(hi, lo);
  12239. else
  12240. res.push(lo);
  12241. }
  12242. } else if (enc === 'hex') {
  12243. msg = msg.replace(/[^a-z0-9]+/ig, '');
  12244. if (msg.length % 2 !== 0)
  12245. msg = '0' + msg;
  12246. for (i = 0; i < msg.length; i += 2)
  12247. res.push(parseInt(msg[i] + msg[i + 1], 16));
  12248. }
  12249. } else {
  12250. for (i = 0; i < msg.length; i++)
  12251. res[i] = msg[i] | 0;
  12252. }
  12253. return res;
  12254. }
  12255. exports.toArray = toArray;
  12256. function toHex(msg) {
  12257. var res = '';
  12258. for (var i = 0; i < msg.length; i++)
  12259. res += zero2(msg[i].toString(16));
  12260. return res;
  12261. }
  12262. exports.toHex = toHex;
  12263. function htonl(w) {
  12264. var res = (w >>> 24) |
  12265. ((w >>> 8) & 0xff00) |
  12266. ((w << 8) & 0xff0000) |
  12267. ((w & 0xff) << 24);
  12268. return res >>> 0;
  12269. }
  12270. exports.htonl = htonl;
  12271. function toHex32(msg, endian) {
  12272. var res = '';
  12273. for (var i = 0; i < msg.length; i++) {
  12274. var w = msg[i];
  12275. if (endian === 'little')
  12276. w = htonl(w);
  12277. res += zero8(w.toString(16));
  12278. }
  12279. return res;
  12280. }
  12281. exports.toHex32 = toHex32;
  12282. function zero2(word) {
  12283. if (word.length === 1)
  12284. return '0' + word;
  12285. else
  12286. return word;
  12287. }
  12288. exports.zero2 = zero2;
  12289. function zero8(word) {
  12290. if (word.length === 7)
  12291. return '0' + word;
  12292. else if (word.length === 6)
  12293. return '00' + word;
  12294. else if (word.length === 5)
  12295. return '000' + word;
  12296. else if (word.length === 4)
  12297. return '0000' + word;
  12298. else if (word.length === 3)
  12299. return '00000' + word;
  12300. else if (word.length === 2)
  12301. return '000000' + word;
  12302. else if (word.length === 1)
  12303. return '0000000' + word;
  12304. else
  12305. return word;
  12306. }
  12307. exports.zero8 = zero8;
  12308. function join32(msg, start, end, endian) {
  12309. var len = end - start;
  12310. assert(len % 4 === 0);
  12311. var res = new Array(len / 4);
  12312. for (var i = 0, k = start; i < res.length; i++, k += 4) {
  12313. var w;
  12314. if (endian === 'big')
  12315. w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
  12316. else
  12317. w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
  12318. res[i] = w >>> 0;
  12319. }
  12320. return res;
  12321. }
  12322. exports.join32 = join32;
  12323. function split32(msg, endian) {
  12324. var res = new Array(msg.length * 4);
  12325. for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
  12326. var m = msg[i];
  12327. if (endian === 'big') {
  12328. res[k] = m >>> 24;
  12329. res[k + 1] = (m >>> 16) & 0xff;
  12330. res[k + 2] = (m >>> 8) & 0xff;
  12331. res[k + 3] = m & 0xff;
  12332. } else {
  12333. res[k + 3] = m >>> 24;
  12334. res[k + 2] = (m >>> 16) & 0xff;
  12335. res[k + 1] = (m >>> 8) & 0xff;
  12336. res[k] = m & 0xff;
  12337. }
  12338. }
  12339. return res;
  12340. }
  12341. exports.split32 = split32;
  12342. function rotr32(w, b) {
  12343. return (w >>> b) | (w << (32 - b));
  12344. }
  12345. exports.rotr32 = rotr32;
  12346. function rotl32(w, b) {
  12347. return (w << b) | (w >>> (32 - b));
  12348. }
  12349. exports.rotl32 = rotl32;
  12350. function sum32(a, b) {
  12351. return (a + b) >>> 0;
  12352. }
  12353. exports.sum32 = sum32;
  12354. function sum32_3(a, b, c) {
  12355. return (a + b + c) >>> 0;
  12356. }
  12357. exports.sum32_3 = sum32_3;
  12358. function sum32_4(a, b, c, d) {
  12359. return (a + b + c + d) >>> 0;
  12360. }
  12361. exports.sum32_4 = sum32_4;
  12362. function sum32_5(a, b, c, d, e) {
  12363. return (a + b + c + d + e) >>> 0;
  12364. }
  12365. exports.sum32_5 = sum32_5;
  12366. function sum64(buf, pos, ah, al) {
  12367. var bh = buf[pos];
  12368. var bl = buf[pos + 1];
  12369. var lo = (al + bl) >>> 0;
  12370. var hi = (lo < al ? 1 : 0) + ah + bh;
  12371. buf[pos] = hi >>> 0;
  12372. buf[pos + 1] = lo;
  12373. }
  12374. exports.sum64 = sum64;
  12375. function sum64_hi(ah, al, bh, bl) {
  12376. var lo = (al + bl) >>> 0;
  12377. var hi = (lo < al ? 1 : 0) + ah + bh;
  12378. return hi >>> 0;
  12379. }
  12380. exports.sum64_hi = sum64_hi;
  12381. function sum64_lo(ah, al, bh, bl) {
  12382. var lo = al + bl;
  12383. return lo >>> 0;
  12384. }
  12385. exports.sum64_lo = sum64_lo;
  12386. function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
  12387. var carry = 0;
  12388. var lo = al;
  12389. lo = (lo + bl) >>> 0;
  12390. carry += lo < al ? 1 : 0;
  12391. lo = (lo + cl) >>> 0;
  12392. carry += lo < cl ? 1 : 0;
  12393. lo = (lo + dl) >>> 0;
  12394. carry += lo < dl ? 1 : 0;
  12395. var hi = ah + bh + ch + dh + carry;
  12396. return hi >>> 0;
  12397. }
  12398. exports.sum64_4_hi = sum64_4_hi;
  12399. function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
  12400. var lo = al + bl + cl + dl;
  12401. return lo >>> 0;
  12402. }
  12403. exports.sum64_4_lo = sum64_4_lo;
  12404. function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
  12405. var carry = 0;
  12406. var lo = al;
  12407. lo = (lo + bl) >>> 0;
  12408. carry += lo < al ? 1 : 0;
  12409. lo = (lo + cl) >>> 0;
  12410. carry += lo < cl ? 1 : 0;
  12411. lo = (lo + dl) >>> 0;
  12412. carry += lo < dl ? 1 : 0;
  12413. lo = (lo + el) >>> 0;
  12414. carry += lo < el ? 1 : 0;
  12415. var hi = ah + bh + ch + dh + eh + carry;
  12416. return hi >>> 0;
  12417. }
  12418. exports.sum64_5_hi = sum64_5_hi;
  12419. function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
  12420. var lo = al + bl + cl + dl + el;
  12421. return lo >>> 0;
  12422. }
  12423. exports.sum64_5_lo = sum64_5_lo;
  12424. function rotr64_hi(ah, al, num) {
  12425. var r = (al << (32 - num)) | (ah >>> num);
  12426. return r >>> 0;
  12427. }
  12428. exports.rotr64_hi = rotr64_hi;
  12429. function rotr64_lo(ah, al, num) {
  12430. var r = (ah << (32 - num)) | (al >>> num);
  12431. return r >>> 0;
  12432. }
  12433. exports.rotr64_lo = rotr64_lo;
  12434. function shr64_hi(ah, al, num) {
  12435. return ah >>> num;
  12436. }
  12437. exports.shr64_hi = shr64_hi;
  12438. function shr64_lo(ah, al, num) {
  12439. var r = (ah << (32 - num)) | (al >>> num);
  12440. return r >>> 0;
  12441. }
  12442. exports.shr64_lo = shr64_lo;
  12443. },{"inherits":47,"minimalistic-assert":48}],46:[function(require,module,exports){
  12444. 'use strict';
  12445. var hash = require('hash.js');
  12446. var utils = require('minimalistic-crypto-utils');
  12447. var assert = require('minimalistic-assert');
  12448. function HmacDRBG(options) {
  12449. if (!(this instanceof HmacDRBG))
  12450. return new HmacDRBG(options);
  12451. this.hash = options.hash;
  12452. this.predResist = !!options.predResist;
  12453. this.outLen = this.hash.outSize;
  12454. this.minEntropy = options.minEntropy || this.hash.hmacStrength;
  12455. this._reseed = null;
  12456. this.reseedInterval = null;
  12457. this.K = null;
  12458. this.V = null;
  12459. var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex');
  12460. var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex');
  12461. var pers = utils.toArray(options.pers, options.persEnc || 'hex');
  12462. assert(entropy.length >= (this.minEntropy / 8),
  12463. 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
  12464. this._init(entropy, nonce, pers);
  12465. }
  12466. module.exports = HmacDRBG;
  12467. HmacDRBG.prototype._init = function init(entropy, nonce, pers) {
  12468. var seed = entropy.concat(nonce).concat(pers);
  12469. this.K = new Array(this.outLen / 8);
  12470. this.V = new Array(this.outLen / 8);
  12471. for (var i = 0; i < this.V.length; i++) {
  12472. this.K[i] = 0x00;
  12473. this.V[i] = 0x01;
  12474. }
  12475. this._update(seed);
  12476. this._reseed = 1;
  12477. this.reseedInterval = 0x1000000000000; // 2^48
  12478. };
  12479. HmacDRBG.prototype._hmac = function hmac() {
  12480. return new hash.hmac(this.hash, this.K);
  12481. };
  12482. HmacDRBG.prototype._update = function update(seed) {
  12483. var kmac = this._hmac()
  12484. .update(this.V)
  12485. .update([ 0x00 ]);
  12486. if (seed)
  12487. kmac = kmac.update(seed);
  12488. this.K = kmac.digest();
  12489. this.V = this._hmac().update(this.V).digest();
  12490. if (!seed)
  12491. return;
  12492. this.K = this._hmac()
  12493. .update(this.V)
  12494. .update([ 0x01 ])
  12495. .update(seed)
  12496. .digest();
  12497. this.V = this._hmac().update(this.V).digest();
  12498. };
  12499. HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {
  12500. // Optional entropy enc
  12501. if (typeof entropyEnc !== 'string') {
  12502. addEnc = add;
  12503. add = entropyEnc;
  12504. entropyEnc = null;
  12505. }
  12506. entropy = utils.toArray(entropy, entropyEnc);
  12507. add = utils.toArray(add, addEnc);
  12508. assert(entropy.length >= (this.minEntropy / 8),
  12509. 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
  12510. this._update(entropy.concat(add || []));
  12511. this._reseed = 1;
  12512. };
  12513. HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
  12514. if (this._reseed > this.reseedInterval)
  12515. throw new Error('Reseed is required');
  12516. // Optional encoding
  12517. if (typeof enc !== 'string') {
  12518. addEnc = add;
  12519. add = enc;
  12520. enc = null;
  12521. }
  12522. // Optional additional data
  12523. if (add) {
  12524. add = utils.toArray(add, addEnc || 'hex');
  12525. this._update(add);
  12526. }
  12527. var temp = [];
  12528. while (temp.length < len) {
  12529. this.V = this._hmac().update(this.V).digest();
  12530. temp = temp.concat(this.V);
  12531. }
  12532. var res = temp.slice(0, len);
  12533. this._update(add);
  12534. this._reseed++;
  12535. return utils.encode(res, enc);
  12536. };
  12537. },{"hash.js":34,"minimalistic-assert":48,"minimalistic-crypto-utils":49}],47:[function(require,module,exports){
  12538. if (typeof Object.create === 'function') {
  12539. // implementation from standard node.js 'util' module
  12540. module.exports = function inherits(ctor, superCtor) {
  12541. ctor.super_ = superCtor
  12542. ctor.prototype = Object.create(superCtor.prototype, {
  12543. constructor: {
  12544. value: ctor,
  12545. enumerable: false,
  12546. writable: true,
  12547. configurable: true
  12548. }
  12549. });
  12550. };
  12551. } else {
  12552. // old school shim for old browsers
  12553. module.exports = function inherits(ctor, superCtor) {
  12554. ctor.super_ = superCtor
  12555. var TempCtor = function () {}
  12556. TempCtor.prototype = superCtor.prototype
  12557. ctor.prototype = new TempCtor()
  12558. ctor.prototype.constructor = ctor
  12559. }
  12560. }
  12561. },{}],48:[function(require,module,exports){
  12562. module.exports = assert;
  12563. function assert(val, msg) {
  12564. if (!val)
  12565. throw new Error(msg || 'Assertion failed');
  12566. }
  12567. assert.equal = function assertEqual(l, r, msg) {
  12568. if (l != r)
  12569. throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
  12570. };
  12571. },{}],49:[function(require,module,exports){
  12572. 'use strict';
  12573. var utils = exports;
  12574. function toArray(msg, enc) {
  12575. if (Array.isArray(msg))
  12576. return msg.slice();
  12577. if (!msg)
  12578. return [];
  12579. var res = [];
  12580. if (typeof msg !== 'string') {
  12581. for (var i = 0; i < msg.length; i++)
  12582. res[i] = msg[i] | 0;
  12583. return res;
  12584. }
  12585. if (enc === 'hex') {
  12586. msg = msg.replace(/[^a-z0-9]+/ig, '');
  12587. if (msg.length % 2 !== 0)
  12588. msg = '0' + msg;
  12589. for (var i = 0; i < msg.length; i += 2)
  12590. res.push(parseInt(msg[i] + msg[i + 1], 16));
  12591. } else {
  12592. for (var i = 0; i < msg.length; i++) {
  12593. var c = msg.charCodeAt(i);
  12594. var hi = c >> 8;
  12595. var lo = c & 0xff;
  12596. if (hi)
  12597. res.push(hi, lo);
  12598. else
  12599. res.push(lo);
  12600. }
  12601. }
  12602. return res;
  12603. }
  12604. utils.toArray = toArray;
  12605. function zero2(word) {
  12606. if (word.length === 1)
  12607. return '0' + word;
  12608. else
  12609. return word;
  12610. }
  12611. utils.zero2 = zero2;
  12612. function toHex(msg) {
  12613. var res = '';
  12614. for (var i = 0; i < msg.length; i++)
  12615. res += zero2(msg[i].toString(16));
  12616. return res;
  12617. }
  12618. utils.toHex = toHex;
  12619. utils.encode = function encode(arr, enc) {
  12620. if (enc === 'hex')
  12621. return toHex(arr);
  12622. else
  12623. return arr;
  12624. };
  12625. },{}],50:[function(require,module,exports){
  12626. // Top level file is just a mixin of submodules & constants
  12627. 'use strict';
  12628. var assign = require('./lib/utils/common').assign;
  12629. var deflate = require('./lib/deflate');
  12630. var inflate = require('./lib/inflate');
  12631. var constants = require('./lib/zlib/constants');
  12632. var pako = {};
  12633. assign(pako, deflate, inflate, constants);
  12634. module.exports = pako;
  12635. },{"./lib/deflate":51,"./lib/inflate":52,"./lib/utils/common":53,"./lib/zlib/constants":56}],51:[function(require,module,exports){
  12636. 'use strict';
  12637. var zlib_deflate = require('./zlib/deflate');
  12638. var utils = require('./utils/common');
  12639. var strings = require('./utils/strings');
  12640. var msg = require('./zlib/messages');
  12641. var ZStream = require('./zlib/zstream');
  12642. var toString = Object.prototype.toString;
  12643. /* Public constants ==========================================================*/
  12644. /* ===========================================================================*/
  12645. var Z_NO_FLUSH = 0;
  12646. var Z_FINISH = 4;
  12647. var Z_OK = 0;
  12648. var Z_STREAM_END = 1;
  12649. var Z_SYNC_FLUSH = 2;
  12650. var Z_DEFAULT_COMPRESSION = -1;
  12651. var Z_DEFAULT_STRATEGY = 0;
  12652. var Z_DEFLATED = 8;
  12653. /* ===========================================================================*/
  12654. /**
  12655. * class Deflate
  12656. *
  12657. * Generic JS-style wrapper for zlib calls. If you don't need
  12658. * streaming behaviour - use more simple functions: [[deflate]],
  12659. * [[deflateRaw]] and [[gzip]].
  12660. **/
  12661. /* internal
  12662. * Deflate.chunks -> Array
  12663. *
  12664. * Chunks of output data, if [[Deflate#onData]] not overridden.
  12665. **/
  12666. /**
  12667. * Deflate.result -> Uint8Array|Array
  12668. *
  12669. * Compressed result, generated by default [[Deflate#onData]]
  12670. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  12671. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  12672. * push a chunk with explicit flush (call [[Deflate#push]] with
  12673. * `Z_SYNC_FLUSH` param).
  12674. **/
  12675. /**
  12676. * Deflate.err -> Number
  12677. *
  12678. * Error code after deflate finished. 0 (Z_OK) on success.
  12679. * You will not need it in real life, because deflate errors
  12680. * are possible only on wrong options or bad `onData` / `onEnd`
  12681. * custom handlers.
  12682. **/
  12683. /**
  12684. * Deflate.msg -> String
  12685. *
  12686. * Error message, if [[Deflate.err]] != 0
  12687. **/
  12688. /**
  12689. * new Deflate(options)
  12690. * - options (Object): zlib deflate options.
  12691. *
  12692. * Creates new deflator instance with specified params. Throws exception
  12693. * on bad params. Supported options:
  12694. *
  12695. * - `level`
  12696. * - `windowBits`
  12697. * - `memLevel`
  12698. * - `strategy`
  12699. * - `dictionary`
  12700. *
  12701. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  12702. * for more information on these.
  12703. *
  12704. * Additional options, for internal needs:
  12705. *
  12706. * - `chunkSize` - size of generated data chunks (16K by default)
  12707. * - `raw` (Boolean) - do raw deflate
  12708. * - `gzip` (Boolean) - create gzip wrapper
  12709. * - `to` (String) - if equal to 'string', then result will be "binary string"
  12710. * (each char code [0..255])
  12711. * - `header` (Object) - custom header for gzip
  12712. * - `text` (Boolean) - true if compressed data believed to be text
  12713. * - `time` (Number) - modification time, unix timestamp
  12714. * - `os` (Number) - operation system code
  12715. * - `extra` (Array) - array of bytes with extra data (max 65536)
  12716. * - `name` (String) - file name (binary string)
  12717. * - `comment` (String) - comment (binary string)
  12718. * - `hcrc` (Boolean) - true if header crc should be added
  12719. *
  12720. * ##### Example:
  12721. *
  12722. * ```javascript
  12723. * var pako = require('pako')
  12724. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  12725. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  12726. *
  12727. * var deflate = new pako.Deflate({ level: 3});
  12728. *
  12729. * deflate.push(chunk1, false);
  12730. * deflate.push(chunk2, true); // true -> last chunk
  12731. *
  12732. * if (deflate.err) { throw new Error(deflate.err); }
  12733. *
  12734. * console.log(deflate.result);
  12735. * ```
  12736. **/
  12737. function Deflate(options) {
  12738. if (!(this instanceof Deflate)) return new Deflate(options);
  12739. this.options = utils.assign({
  12740. level: Z_DEFAULT_COMPRESSION,
  12741. method: Z_DEFLATED,
  12742. chunkSize: 16384,
  12743. windowBits: 15,
  12744. memLevel: 8,
  12745. strategy: Z_DEFAULT_STRATEGY,
  12746. to: ''
  12747. }, options || {});
  12748. var opt = this.options;
  12749. if (opt.raw && (opt.windowBits > 0)) {
  12750. opt.windowBits = -opt.windowBits;
  12751. }
  12752. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  12753. opt.windowBits += 16;
  12754. }
  12755. this.err = 0; // error code, if happens (0 = Z_OK)
  12756. this.msg = ''; // error message
  12757. this.ended = false; // used to avoid multiple onEnd() calls
  12758. this.chunks = []; // chunks of compressed data
  12759. this.strm = new ZStream();
  12760. this.strm.avail_out = 0;
  12761. var status = zlib_deflate.deflateInit2(
  12762. this.strm,
  12763. opt.level,
  12764. opt.method,
  12765. opt.windowBits,
  12766. opt.memLevel,
  12767. opt.strategy
  12768. );
  12769. if (status !== Z_OK) {
  12770. throw new Error(msg[status]);
  12771. }
  12772. if (opt.header) {
  12773. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  12774. }
  12775. if (opt.dictionary) {
  12776. var dict;
  12777. // Convert data if needed
  12778. if (typeof opt.dictionary === 'string') {
  12779. // If we need to compress text, change encoding to utf8.
  12780. dict = strings.string2buf(opt.dictionary);
  12781. } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {
  12782. dict = new Uint8Array(opt.dictionary);
  12783. } else {
  12784. dict = opt.dictionary;
  12785. }
  12786. status = zlib_deflate.deflateSetDictionary(this.strm, dict);
  12787. if (status !== Z_OK) {
  12788. throw new Error(msg[status]);
  12789. }
  12790. this._dict_set = true;
  12791. }
  12792. }
  12793. /**
  12794. * Deflate#push(data[, mode]) -> Boolean
  12795. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  12796. * converted to utf8 byte sequence.
  12797. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  12798. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
  12799. *
  12800. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  12801. * new compressed chunks. Returns `true` on success. The last data block must have
  12802. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  12803. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  12804. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  12805. *
  12806. * On fail call [[Deflate#onEnd]] with error code and return false.
  12807. *
  12808. * We strongly recommend to use `Uint8Array` on input for best speed (output
  12809. * array format is detected automatically). Also, don't skip last param and always
  12810. * use the same type in your code (boolean or number). That will improve JS speed.
  12811. *
  12812. * For regular `Array`-s make sure all elements are [0..255].
  12813. *
  12814. * ##### Example
  12815. *
  12816. * ```javascript
  12817. * push(chunk, false); // push one of data chunks
  12818. * ...
  12819. * push(chunk, true); // push last chunk
  12820. * ```
  12821. **/
  12822. Deflate.prototype.push = function (data, mode) {
  12823. var strm = this.strm;
  12824. var chunkSize = this.options.chunkSize;
  12825. var status, _mode;
  12826. if (this.ended) { return false; }
  12827. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  12828. // Convert data if needed
  12829. if (typeof data === 'string') {
  12830. // If we need to compress text, change encoding to utf8.
  12831. strm.input = strings.string2buf(data);
  12832. } else if (toString.call(data) === '[object ArrayBuffer]') {
  12833. strm.input = new Uint8Array(data);
  12834. } else {
  12835. strm.input = data;
  12836. }
  12837. strm.next_in = 0;
  12838. strm.avail_in = strm.input.length;
  12839. do {
  12840. if (strm.avail_out === 0) {
  12841. strm.output = new utils.Buf8(chunkSize);
  12842. strm.next_out = 0;
  12843. strm.avail_out = chunkSize;
  12844. }
  12845. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  12846. if (status !== Z_STREAM_END && status !== Z_OK) {
  12847. this.onEnd(status);
  12848. this.ended = true;
  12849. return false;
  12850. }
  12851. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  12852. if (this.options.to === 'string') {
  12853. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  12854. } else {
  12855. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  12856. }
  12857. }
  12858. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  12859. // Finalize on the last chunk.
  12860. if (_mode === Z_FINISH) {
  12861. status = zlib_deflate.deflateEnd(this.strm);
  12862. this.onEnd(status);
  12863. this.ended = true;
  12864. return status === Z_OK;
  12865. }
  12866. // callback interim results if Z_SYNC_FLUSH.
  12867. if (_mode === Z_SYNC_FLUSH) {
  12868. this.onEnd(Z_OK);
  12869. strm.avail_out = 0;
  12870. return true;
  12871. }
  12872. return true;
  12873. };
  12874. /**
  12875. * Deflate#onData(chunk) -> Void
  12876. * - chunk (Uint8Array|Array|String): output data. Type of array depends
  12877. * on js engine support. When string output requested, each chunk
  12878. * will be string.
  12879. *
  12880. * By default, stores data blocks in `chunks[]` property and glue
  12881. * those in `onEnd`. Override this handler, if you need another behaviour.
  12882. **/
  12883. Deflate.prototype.onData = function (chunk) {
  12884. this.chunks.push(chunk);
  12885. };
  12886. /**
  12887. * Deflate#onEnd(status) -> Void
  12888. * - status (Number): deflate status. 0 (Z_OK) on success,
  12889. * other if not.
  12890. *
  12891. * Called once after you tell deflate that the input stream is
  12892. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  12893. * or if an error happened. By default - join collected chunks,
  12894. * free memory and fill `results` / `err` properties.
  12895. **/
  12896. Deflate.prototype.onEnd = function (status) {
  12897. // On success - join
  12898. if (status === Z_OK) {
  12899. if (this.options.to === 'string') {
  12900. this.result = this.chunks.join('');
  12901. } else {
  12902. this.result = utils.flattenChunks(this.chunks);
  12903. }
  12904. }
  12905. this.chunks = [];
  12906. this.err = status;
  12907. this.msg = this.strm.msg;
  12908. };
  12909. /**
  12910. * deflate(data[, options]) -> Uint8Array|Array|String
  12911. * - data (Uint8Array|Array|String): input data to compress.
  12912. * - options (Object): zlib deflate options.
  12913. *
  12914. * Compress `data` with deflate algorithm and `options`.
  12915. *
  12916. * Supported options are:
  12917. *
  12918. * - level
  12919. * - windowBits
  12920. * - memLevel
  12921. * - strategy
  12922. * - dictionary
  12923. *
  12924. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  12925. * for more information on these.
  12926. *
  12927. * Sugar (options):
  12928. *
  12929. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  12930. * negative windowBits implicitly.
  12931. * - `to` (String) - if equal to 'string', then result will be "binary string"
  12932. * (each char code [0..255])
  12933. *
  12934. * ##### Example:
  12935. *
  12936. * ```javascript
  12937. * var pako = require('pako')
  12938. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  12939. *
  12940. * console.log(pako.deflate(data));
  12941. * ```
  12942. **/
  12943. function deflate(input, options) {
  12944. var deflator = new Deflate(options);
  12945. deflator.push(input, true);
  12946. // That will never happens, if you don't cheat with options :)
  12947. if (deflator.err) { throw deflator.msg || msg[deflator.err]; }
  12948. return deflator.result;
  12949. }
  12950. /**
  12951. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  12952. * - data (Uint8Array|Array|String): input data to compress.
  12953. * - options (Object): zlib deflate options.
  12954. *
  12955. * The same as [[deflate]], but creates raw data, without wrapper
  12956. * (header and adler32 crc).
  12957. **/
  12958. function deflateRaw(input, options) {
  12959. options = options || {};
  12960. options.raw = true;
  12961. return deflate(input, options);
  12962. }
  12963. /**
  12964. * gzip(data[, options]) -> Uint8Array|Array|String
  12965. * - data (Uint8Array|Array|String): input data to compress.
  12966. * - options (Object): zlib deflate options.
  12967. *
  12968. * The same as [[deflate]], but create gzip wrapper instead of
  12969. * deflate one.
  12970. **/
  12971. function gzip(input, options) {
  12972. options = options || {};
  12973. options.gzip = true;
  12974. return deflate(input, options);
  12975. }
  12976. exports.Deflate = Deflate;
  12977. exports.deflate = deflate;
  12978. exports.deflateRaw = deflateRaw;
  12979. exports.gzip = gzip;
  12980. },{"./utils/common":53,"./utils/strings":54,"./zlib/deflate":58,"./zlib/messages":63,"./zlib/zstream":65}],52:[function(require,module,exports){
  12981. 'use strict';
  12982. var zlib_inflate = require('./zlib/inflate');
  12983. var utils = require('./utils/common');
  12984. var strings = require('./utils/strings');
  12985. var c = require('./zlib/constants');
  12986. var msg = require('./zlib/messages');
  12987. var ZStream = require('./zlib/zstream');
  12988. var GZheader = require('./zlib/gzheader');
  12989. var toString = Object.prototype.toString;
  12990. /**
  12991. * class Inflate
  12992. *
  12993. * Generic JS-style wrapper for zlib calls. If you don't need
  12994. * streaming behaviour - use more simple functions: [[inflate]]
  12995. * and [[inflateRaw]].
  12996. **/
  12997. /* internal
  12998. * inflate.chunks -> Array
  12999. *
  13000. * Chunks of output data, if [[Inflate#onData]] not overridden.
  13001. **/
  13002. /**
  13003. * Inflate.result -> Uint8Array|Array|String
  13004. *
  13005. * Uncompressed result, generated by default [[Inflate#onData]]
  13006. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  13007. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  13008. * push a chunk with explicit flush (call [[Inflate#push]] with
  13009. * `Z_SYNC_FLUSH` param).
  13010. **/
  13011. /**
  13012. * Inflate.err -> Number
  13013. *
  13014. * Error code after inflate finished. 0 (Z_OK) on success.
  13015. * Should be checked if broken data possible.
  13016. **/
  13017. /**
  13018. * Inflate.msg -> String
  13019. *
  13020. * Error message, if [[Inflate.err]] != 0
  13021. **/
  13022. /**
  13023. * new Inflate(options)
  13024. * - options (Object): zlib inflate options.
  13025. *
  13026. * Creates new inflator instance with specified params. Throws exception
  13027. * on bad params. Supported options:
  13028. *
  13029. * - `windowBits`
  13030. * - `dictionary`
  13031. *
  13032. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13033. * for more information on these.
  13034. *
  13035. * Additional options, for internal needs:
  13036. *
  13037. * - `chunkSize` - size of generated data chunks (16K by default)
  13038. * - `raw` (Boolean) - do raw inflate
  13039. * - `to` (String) - if equal to 'string', then result will be converted
  13040. * from utf8 to utf16 (javascript) string. When string output requested,
  13041. * chunk length can differ from `chunkSize`, depending on content.
  13042. *
  13043. * By default, when no options set, autodetect deflate/gzip data format via
  13044. * wrapper header.
  13045. *
  13046. * ##### Example:
  13047. *
  13048. * ```javascript
  13049. * var pako = require('pako')
  13050. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  13051. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  13052. *
  13053. * var inflate = new pako.Inflate({ level: 3});
  13054. *
  13055. * inflate.push(chunk1, false);
  13056. * inflate.push(chunk2, true); // true -> last chunk
  13057. *
  13058. * if (inflate.err) { throw new Error(inflate.err); }
  13059. *
  13060. * console.log(inflate.result);
  13061. * ```
  13062. **/
  13063. function Inflate(options) {
  13064. if (!(this instanceof Inflate)) return new Inflate(options);
  13065. this.options = utils.assign({
  13066. chunkSize: 16384,
  13067. windowBits: 0,
  13068. to: ''
  13069. }, options || {});
  13070. var opt = this.options;
  13071. // Force window size for `raw` data, if not set directly,
  13072. // because we have no header for autodetect.
  13073. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  13074. opt.windowBits = -opt.windowBits;
  13075. if (opt.windowBits === 0) { opt.windowBits = -15; }
  13076. }
  13077. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  13078. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  13079. !(options && options.windowBits)) {
  13080. opt.windowBits += 32;
  13081. }
  13082. // Gzip header has no info about windows size, we can do autodetect only
  13083. // for deflate. So, if window size not set, force it to max when gzip possible
  13084. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  13085. // bit 3 (16) -> gzipped data
  13086. // bit 4 (32) -> autodetect gzip/deflate
  13087. if ((opt.windowBits & 15) === 0) {
  13088. opt.windowBits |= 15;
  13089. }
  13090. }
  13091. this.err = 0; // error code, if happens (0 = Z_OK)
  13092. this.msg = ''; // error message
  13093. this.ended = false; // used to avoid multiple onEnd() calls
  13094. this.chunks = []; // chunks of compressed data
  13095. this.strm = new ZStream();
  13096. this.strm.avail_out = 0;
  13097. var status = zlib_inflate.inflateInit2(
  13098. this.strm,
  13099. opt.windowBits
  13100. );
  13101. if (status !== c.Z_OK) {
  13102. throw new Error(msg[status]);
  13103. }
  13104. this.header = new GZheader();
  13105. zlib_inflate.inflateGetHeader(this.strm, this.header);
  13106. }
  13107. /**
  13108. * Inflate#push(data[, mode]) -> Boolean
  13109. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  13110. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  13111. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.
  13112. *
  13113. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  13114. * new output chunks. Returns `true` on success. The last data block must have
  13115. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  13116. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  13117. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  13118. *
  13119. * On fail call [[Inflate#onEnd]] with error code and return false.
  13120. *
  13121. * We strongly recommend to use `Uint8Array` on input for best speed (output
  13122. * format is detected automatically). Also, don't skip last param and always
  13123. * use the same type in your code (boolean or number). That will improve JS speed.
  13124. *
  13125. * For regular `Array`-s make sure all elements are [0..255].
  13126. *
  13127. * ##### Example
  13128. *
  13129. * ```javascript
  13130. * push(chunk, false); // push one of data chunks
  13131. * ...
  13132. * push(chunk, true); // push last chunk
  13133. * ```
  13134. **/
  13135. Inflate.prototype.push = function (data, mode) {
  13136. var strm = this.strm;
  13137. var chunkSize = this.options.chunkSize;
  13138. var dictionary = this.options.dictionary;
  13139. var status, _mode;
  13140. var next_out_utf8, tail, utf8str;
  13141. var dict;
  13142. // Flag to properly process Z_BUF_ERROR on testing inflate call
  13143. // when we check that all output data was flushed.
  13144. var allowBufError = false;
  13145. if (this.ended) { return false; }
  13146. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  13147. // Convert data if needed
  13148. if (typeof data === 'string') {
  13149. // Only binary strings can be decompressed on practice
  13150. strm.input = strings.binstring2buf(data);
  13151. } else if (toString.call(data) === '[object ArrayBuffer]') {
  13152. strm.input = new Uint8Array(data);
  13153. } else {
  13154. strm.input = data;
  13155. }
  13156. strm.next_in = 0;
  13157. strm.avail_in = strm.input.length;
  13158. do {
  13159. if (strm.avail_out === 0) {
  13160. strm.output = new utils.Buf8(chunkSize);
  13161. strm.next_out = 0;
  13162. strm.avail_out = chunkSize;
  13163. }
  13164. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  13165. if (status === c.Z_NEED_DICT && dictionary) {
  13166. // Convert data if needed
  13167. if (typeof dictionary === 'string') {
  13168. dict = strings.string2buf(dictionary);
  13169. } else if (toString.call(dictionary) === '[object ArrayBuffer]') {
  13170. dict = new Uint8Array(dictionary);
  13171. } else {
  13172. dict = dictionary;
  13173. }
  13174. status = zlib_inflate.inflateSetDictionary(this.strm, dict);
  13175. }
  13176. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  13177. status = c.Z_OK;
  13178. allowBufError = false;
  13179. }
  13180. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  13181. this.onEnd(status);
  13182. this.ended = true;
  13183. return false;
  13184. }
  13185. if (strm.next_out) {
  13186. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  13187. if (this.options.to === 'string') {
  13188. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  13189. tail = strm.next_out - next_out_utf8;
  13190. utf8str = strings.buf2string(strm.output, next_out_utf8);
  13191. // move tail
  13192. strm.next_out = tail;
  13193. strm.avail_out = chunkSize - tail;
  13194. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  13195. this.onData(utf8str);
  13196. } else {
  13197. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  13198. }
  13199. }
  13200. }
  13201. // When no more input data, we should check that internal inflate buffers
  13202. // are flushed. The only way to do it when avail_out = 0 - run one more
  13203. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  13204. // Here we set flag to process this error properly.
  13205. //
  13206. // NOTE. Deflate does not return error in this case and does not needs such
  13207. // logic.
  13208. if (strm.avail_in === 0 && strm.avail_out === 0) {
  13209. allowBufError = true;
  13210. }
  13211. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  13212. if (status === c.Z_STREAM_END) {
  13213. _mode = c.Z_FINISH;
  13214. }
  13215. // Finalize on the last chunk.
  13216. if (_mode === c.Z_FINISH) {
  13217. status = zlib_inflate.inflateEnd(this.strm);
  13218. this.onEnd(status);
  13219. this.ended = true;
  13220. return status === c.Z_OK;
  13221. }
  13222. // callback interim results if Z_SYNC_FLUSH.
  13223. if (_mode === c.Z_SYNC_FLUSH) {
  13224. this.onEnd(c.Z_OK);
  13225. strm.avail_out = 0;
  13226. return true;
  13227. }
  13228. return true;
  13229. };
  13230. /**
  13231. * Inflate#onData(chunk) -> Void
  13232. * - chunk (Uint8Array|Array|String): output data. Type of array depends
  13233. * on js engine support. When string output requested, each chunk
  13234. * will be string.
  13235. *
  13236. * By default, stores data blocks in `chunks[]` property and glue
  13237. * those in `onEnd`. Override this handler, if you need another behaviour.
  13238. **/
  13239. Inflate.prototype.onData = function (chunk) {
  13240. this.chunks.push(chunk);
  13241. };
  13242. /**
  13243. * Inflate#onEnd(status) -> Void
  13244. * - status (Number): inflate status. 0 (Z_OK) on success,
  13245. * other if not.
  13246. *
  13247. * Called either after you tell inflate that the input stream is
  13248. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  13249. * or if an error happened. By default - join collected chunks,
  13250. * free memory and fill `results` / `err` properties.
  13251. **/
  13252. Inflate.prototype.onEnd = function (status) {
  13253. // On success - join
  13254. if (status === c.Z_OK) {
  13255. if (this.options.to === 'string') {
  13256. // Glue & convert here, until we teach pako to send
  13257. // utf8 aligned strings to onData
  13258. this.result = this.chunks.join('');
  13259. } else {
  13260. this.result = utils.flattenChunks(this.chunks);
  13261. }
  13262. }
  13263. this.chunks = [];
  13264. this.err = status;
  13265. this.msg = this.strm.msg;
  13266. };
  13267. /**
  13268. * inflate(data[, options]) -> Uint8Array|Array|String
  13269. * - data (Uint8Array|Array|String): input data to decompress.
  13270. * - options (Object): zlib inflate options.
  13271. *
  13272. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  13273. * format via wrapper header by default. That's why we don't provide
  13274. * separate `ungzip` method.
  13275. *
  13276. * Supported options are:
  13277. *
  13278. * - windowBits
  13279. *
  13280. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  13281. * for more information.
  13282. *
  13283. * Sugar (options):
  13284. *
  13285. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  13286. * negative windowBits implicitly.
  13287. * - `to` (String) - if equal to 'string', then result will be converted
  13288. * from utf8 to utf16 (javascript) string. When string output requested,
  13289. * chunk length can differ from `chunkSize`, depending on content.
  13290. *
  13291. *
  13292. * ##### Example:
  13293. *
  13294. * ```javascript
  13295. * var pako = require('pako')
  13296. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  13297. * , output;
  13298. *
  13299. * try {
  13300. * output = pako.inflate(input);
  13301. * } catch (err)
  13302. * console.log(err);
  13303. * }
  13304. * ```
  13305. **/
  13306. function inflate(input, options) {
  13307. var inflator = new Inflate(options);
  13308. inflator.push(input, true);
  13309. // That will never happens, if you don't cheat with options :)
  13310. if (inflator.err) { throw inflator.msg || msg[inflator.err]; }
  13311. return inflator.result;
  13312. }
  13313. /**
  13314. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  13315. * - data (Uint8Array|Array|String): input data to decompress.
  13316. * - options (Object): zlib inflate options.
  13317. *
  13318. * The same as [[inflate]], but creates raw data, without wrapper
  13319. * (header and adler32 crc).
  13320. **/
  13321. function inflateRaw(input, options) {
  13322. options = options || {};
  13323. options.raw = true;
  13324. return inflate(input, options);
  13325. }
  13326. /**
  13327. * ungzip(data[, options]) -> Uint8Array|Array|String
  13328. * - data (Uint8Array|Array|String): input data to decompress.
  13329. * - options (Object): zlib inflate options.
  13330. *
  13331. * Just shortcut to [[inflate]], because it autodetects format
  13332. * by header.content. Done for convenience.
  13333. **/
  13334. exports.Inflate = Inflate;
  13335. exports.inflate = inflate;
  13336. exports.inflateRaw = inflateRaw;
  13337. exports.ungzip = inflate;
  13338. },{"./utils/common":53,"./utils/strings":54,"./zlib/constants":56,"./zlib/gzheader":59,"./zlib/inflate":61,"./zlib/messages":63,"./zlib/zstream":65}],53:[function(require,module,exports){
  13339. 'use strict';
  13340. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  13341. (typeof Uint16Array !== 'undefined') &&
  13342. (typeof Int32Array !== 'undefined');
  13343. function _has(obj, key) {
  13344. return Object.prototype.hasOwnProperty.call(obj, key);
  13345. }
  13346. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  13347. var sources = Array.prototype.slice.call(arguments, 1);
  13348. while (sources.length) {
  13349. var source = sources.shift();
  13350. if (!source) { continue; }
  13351. if (typeof source !== 'object') {
  13352. throw new TypeError(source + 'must be non-object');
  13353. }
  13354. for (var p in source) {
  13355. if (_has(source, p)) {
  13356. obj[p] = source[p];
  13357. }
  13358. }
  13359. }
  13360. return obj;
  13361. };
  13362. // reduce buffer size, avoiding mem copy
  13363. exports.shrinkBuf = function (buf, size) {
  13364. if (buf.length === size) { return buf; }
  13365. if (buf.subarray) { return buf.subarray(0, size); }
  13366. buf.length = size;
  13367. return buf;
  13368. };
  13369. var fnTyped = {
  13370. arraySet: function (dest, src, src_offs, len, dest_offs) {
  13371. if (src.subarray && dest.subarray) {
  13372. dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
  13373. return;
  13374. }
  13375. // Fallback to ordinary array
  13376. for (var i = 0; i < len; i++) {
  13377. dest[dest_offs + i] = src[src_offs + i];
  13378. }
  13379. },
  13380. // Join array of chunks to single array.
  13381. flattenChunks: function (chunks) {
  13382. var i, l, len, pos, chunk, result;
  13383. // calculate data length
  13384. len = 0;
  13385. for (i = 0, l = chunks.length; i < l; i++) {
  13386. len += chunks[i].length;
  13387. }
  13388. // join chunks
  13389. result = new Uint8Array(len);
  13390. pos = 0;
  13391. for (i = 0, l = chunks.length; i < l; i++) {
  13392. chunk = chunks[i];
  13393. result.set(chunk, pos);
  13394. pos += chunk.length;
  13395. }
  13396. return result;
  13397. }
  13398. };
  13399. var fnUntyped = {
  13400. arraySet: function (dest, src, src_offs, len, dest_offs) {
  13401. for (var i = 0; i < len; i++) {
  13402. dest[dest_offs + i] = src[src_offs + i];
  13403. }
  13404. },
  13405. // Join array of chunks to single array.
  13406. flattenChunks: function (chunks) {
  13407. return [].concat.apply([], chunks);
  13408. }
  13409. };
  13410. // Enable/Disable typed arrays use, for testing
  13411. //
  13412. exports.setTyped = function (on) {
  13413. if (on) {
  13414. exports.Buf8 = Uint8Array;
  13415. exports.Buf16 = Uint16Array;
  13416. exports.Buf32 = Int32Array;
  13417. exports.assign(exports, fnTyped);
  13418. } else {
  13419. exports.Buf8 = Array;
  13420. exports.Buf16 = Array;
  13421. exports.Buf32 = Array;
  13422. exports.assign(exports, fnUntyped);
  13423. }
  13424. };
  13425. exports.setTyped(TYPED_OK);
  13426. },{}],54:[function(require,module,exports){
  13427. // String encode/decode helpers
  13428. 'use strict';
  13429. var utils = require('./common');
  13430. // Quick check if we can use fast array to bin string conversion
  13431. //
  13432. // - apply(Array) can fail on Android 2.2
  13433. // - apply(Uint8Array) can fail on iOS 5.1 Safari
  13434. //
  13435. var STR_APPLY_OK = true;
  13436. var STR_APPLY_UIA_OK = true;
  13437. try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; }
  13438. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }
  13439. // Table with utf8 lengths (calculated by first byte of sequence)
  13440. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  13441. // because max possible codepoint is 0x10ffff
  13442. var _utf8len = new utils.Buf8(256);
  13443. for (var q = 0; q < 256; q++) {
  13444. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  13445. }
  13446. _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start
  13447. // convert string to array (typed, when possible)
  13448. exports.string2buf = function (str) {
  13449. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  13450. // count binary size
  13451. for (m_pos = 0; m_pos < str_len; m_pos++) {
  13452. c = str.charCodeAt(m_pos);
  13453. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  13454. c2 = str.charCodeAt(m_pos + 1);
  13455. if ((c2 & 0xfc00) === 0xdc00) {
  13456. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  13457. m_pos++;
  13458. }
  13459. }
  13460. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  13461. }
  13462. // allocate buffer
  13463. buf = new utils.Buf8(buf_len);
  13464. // convert
  13465. for (i = 0, m_pos = 0; i < buf_len; m_pos++) {
  13466. c = str.charCodeAt(m_pos);
  13467. if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {
  13468. c2 = str.charCodeAt(m_pos + 1);
  13469. if ((c2 & 0xfc00) === 0xdc00) {
  13470. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  13471. m_pos++;
  13472. }
  13473. }
  13474. if (c < 0x80) {
  13475. /* one byte */
  13476. buf[i++] = c;
  13477. } else if (c < 0x800) {
  13478. /* two bytes */
  13479. buf[i++] = 0xC0 | (c >>> 6);
  13480. buf[i++] = 0x80 | (c & 0x3f);
  13481. } else if (c < 0x10000) {
  13482. /* three bytes */
  13483. buf[i++] = 0xE0 | (c >>> 12);
  13484. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  13485. buf[i++] = 0x80 | (c & 0x3f);
  13486. } else {
  13487. /* four bytes */
  13488. buf[i++] = 0xf0 | (c >>> 18);
  13489. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  13490. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  13491. buf[i++] = 0x80 | (c & 0x3f);
  13492. }
  13493. }
  13494. return buf;
  13495. };
  13496. // Helper (used in 2 places)
  13497. function buf2binstring(buf, len) {
  13498. // use fallback for big arrays to avoid stack overflow
  13499. if (len < 65537) {
  13500. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  13501. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  13502. }
  13503. }
  13504. var result = '';
  13505. for (var i = 0; i < len; i++) {
  13506. result += String.fromCharCode(buf[i]);
  13507. }
  13508. return result;
  13509. }
  13510. // Convert byte array to binary string
  13511. exports.buf2binstring = function (buf) {
  13512. return buf2binstring(buf, buf.length);
  13513. };
  13514. // Convert binary string (typed, when possible)
  13515. exports.binstring2buf = function (str) {
  13516. var buf = new utils.Buf8(str.length);
  13517. for (var i = 0, len = buf.length; i < len; i++) {
  13518. buf[i] = str.charCodeAt(i);
  13519. }
  13520. return buf;
  13521. };
  13522. // convert array to string
  13523. exports.buf2string = function (buf, max) {
  13524. var i, out, c, c_len;
  13525. var len = max || buf.length;
  13526. // Reserve max possible length (2 words per char)
  13527. // NB: by unknown reasons, Array is significantly faster for
  13528. // String.fromCharCode.apply than Uint16Array.
  13529. var utf16buf = new Array(len * 2);
  13530. for (out = 0, i = 0; i < len;) {
  13531. c = buf[i++];
  13532. // quick process ascii
  13533. if (c < 0x80) { utf16buf[out++] = c; continue; }
  13534. c_len = _utf8len[c];
  13535. // skip 5 & 6 byte codes
  13536. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }
  13537. // apply mask on first byte
  13538. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  13539. // join the rest
  13540. while (c_len > 1 && i < len) {
  13541. c = (c << 6) | (buf[i++] & 0x3f);
  13542. c_len--;
  13543. }
  13544. // terminated by end of string?
  13545. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  13546. if (c < 0x10000) {
  13547. utf16buf[out++] = c;
  13548. } else {
  13549. c -= 0x10000;
  13550. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  13551. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  13552. }
  13553. }
  13554. return buf2binstring(utf16buf, out);
  13555. };
  13556. // Calculate max possible position in utf8 buffer,
  13557. // that will not break sequence. If that's not possible
  13558. // - (very small limits) return max size as is.
  13559. //
  13560. // buf[] - utf8 bytes array
  13561. // max - length limit (mandatory);
  13562. exports.utf8border = function (buf, max) {
  13563. var pos;
  13564. max = max || buf.length;
  13565. if (max > buf.length) { max = buf.length; }
  13566. // go back from last position, until start of sequence found
  13567. pos = max - 1;
  13568. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  13569. // Very small and broken sequence,
  13570. // return max, because we should return something anyway.
  13571. if (pos < 0) { return max; }
  13572. // If we came to start of buffer - that means buffer is too small,
  13573. // return max too.
  13574. if (pos === 0) { return max; }
  13575. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  13576. };
  13577. },{"./common":53}],55:[function(require,module,exports){
  13578. 'use strict';
  13579. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  13580. // It isn't worth it to make additional optimizations as in original.
  13581. // Small size is preferable.
  13582. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  13583. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  13584. //
  13585. // This software is provided 'as-is', without any express or implied
  13586. // warranty. In no event will the authors be held liable for any damages
  13587. // arising from the use of this software.
  13588. //
  13589. // Permission is granted to anyone to use this software for any purpose,
  13590. // including commercial applications, and to alter it and redistribute it
  13591. // freely, subject to the following restrictions:
  13592. //
  13593. // 1. The origin of this software must not be misrepresented; you must not
  13594. // claim that you wrote the original software. If you use this software
  13595. // in a product, an acknowledgment in the product documentation would be
  13596. // appreciated but is not required.
  13597. // 2. Altered source versions must be plainly marked as such, and must not be
  13598. // misrepresented as being the original software.
  13599. // 3. This notice may not be removed or altered from any source distribution.
  13600. function adler32(adler, buf, len, pos) {
  13601. var s1 = (adler & 0xffff) |0,
  13602. s2 = ((adler >>> 16) & 0xffff) |0,
  13603. n = 0;
  13604. while (len !== 0) {
  13605. // Set limit ~ twice less than 5552, to keep
  13606. // s2 in 31-bits, because we force signed ints.
  13607. // in other case %= will fail.
  13608. n = len > 2000 ? 2000 : len;
  13609. len -= n;
  13610. do {
  13611. s1 = (s1 + buf[pos++]) |0;
  13612. s2 = (s2 + s1) |0;
  13613. } while (--n);
  13614. s1 %= 65521;
  13615. s2 %= 65521;
  13616. }
  13617. return (s1 | (s2 << 16)) |0;
  13618. }
  13619. module.exports = adler32;
  13620. },{}],56:[function(require,module,exports){
  13621. 'use strict';
  13622. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  13623. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  13624. //
  13625. // This software is provided 'as-is', without any express or implied
  13626. // warranty. In no event will the authors be held liable for any damages
  13627. // arising from the use of this software.
  13628. //
  13629. // Permission is granted to anyone to use this software for any purpose,
  13630. // including commercial applications, and to alter it and redistribute it
  13631. // freely, subject to the following restrictions:
  13632. //
  13633. // 1. The origin of this software must not be misrepresented; you must not
  13634. // claim that you wrote the original software. If you use this software
  13635. // in a product, an acknowledgment in the product documentation would be
  13636. // appreciated but is not required.
  13637. // 2. Altered source versions must be plainly marked as such, and must not be
  13638. // misrepresented as being the original software.
  13639. // 3. This notice may not be removed or altered from any source distribution.
  13640. module.exports = {
  13641. /* Allowed flush values; see deflate() and inflate() below for details */
  13642. Z_NO_FLUSH: 0,
  13643. Z_PARTIAL_FLUSH: 1,
  13644. Z_SYNC_FLUSH: 2,
  13645. Z_FULL_FLUSH: 3,
  13646. Z_FINISH: 4,
  13647. Z_BLOCK: 5,
  13648. Z_TREES: 6,
  13649. /* Return codes for the compression/decompression functions. Negative values
  13650. * are errors, positive values are used for special but normal events.
  13651. */
  13652. Z_OK: 0,
  13653. Z_STREAM_END: 1,
  13654. Z_NEED_DICT: 2,
  13655. Z_ERRNO: -1,
  13656. Z_STREAM_ERROR: -2,
  13657. Z_DATA_ERROR: -3,
  13658. //Z_MEM_ERROR: -4,
  13659. Z_BUF_ERROR: -5,
  13660. //Z_VERSION_ERROR: -6,
  13661. /* compression levels */
  13662. Z_NO_COMPRESSION: 0,
  13663. Z_BEST_SPEED: 1,
  13664. Z_BEST_COMPRESSION: 9,
  13665. Z_DEFAULT_COMPRESSION: -1,
  13666. Z_FILTERED: 1,
  13667. Z_HUFFMAN_ONLY: 2,
  13668. Z_RLE: 3,
  13669. Z_FIXED: 4,
  13670. Z_DEFAULT_STRATEGY: 0,
  13671. /* Possible values of the data_type field (though see inflate()) */
  13672. Z_BINARY: 0,
  13673. Z_TEXT: 1,
  13674. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  13675. Z_UNKNOWN: 2,
  13676. /* The deflate compression method */
  13677. Z_DEFLATED: 8
  13678. //Z_NULL: null // Use -1 or null inline, depending on var type
  13679. };
  13680. },{}],57:[function(require,module,exports){
  13681. 'use strict';
  13682. // Note: we can't get significant speed boost here.
  13683. // So write code to minimize size - no pregenerated tables
  13684. // and array tools dependencies.
  13685. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  13686. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  13687. //
  13688. // This software is provided 'as-is', without any express or implied
  13689. // warranty. In no event will the authors be held liable for any damages
  13690. // arising from the use of this software.
  13691. //
  13692. // Permission is granted to anyone to use this software for any purpose,
  13693. // including commercial applications, and to alter it and redistribute it
  13694. // freely, subject to the following restrictions:
  13695. //
  13696. // 1. The origin of this software must not be misrepresented; you must not
  13697. // claim that you wrote the original software. If you use this software
  13698. // in a product, an acknowledgment in the product documentation would be
  13699. // appreciated but is not required.
  13700. // 2. Altered source versions must be plainly marked as such, and must not be
  13701. // misrepresented as being the original software.
  13702. // 3. This notice may not be removed or altered from any source distribution.
  13703. // Use ordinary array, since untyped makes no boost here
  13704. function makeTable() {
  13705. var c, table = [];
  13706. for (var n = 0; n < 256; n++) {
  13707. c = n;
  13708. for (var k = 0; k < 8; k++) {
  13709. c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  13710. }
  13711. table[n] = c;
  13712. }
  13713. return table;
  13714. }
  13715. // Create table on load. Just 255 signed longs. Not a problem.
  13716. var crcTable = makeTable();
  13717. function crc32(crc, buf, len, pos) {
  13718. var t = crcTable,
  13719. end = pos + len;
  13720. crc ^= -1;
  13721. for (var i = pos; i < end; i++) {
  13722. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  13723. }
  13724. return (crc ^ (-1)); // >>> 0;
  13725. }
  13726. module.exports = crc32;
  13727. },{}],58:[function(require,module,exports){
  13728. 'use strict';
  13729. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  13730. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  13731. //
  13732. // This software is provided 'as-is', without any express or implied
  13733. // warranty. In no event will the authors be held liable for any damages
  13734. // arising from the use of this software.
  13735. //
  13736. // Permission is granted to anyone to use this software for any purpose,
  13737. // including commercial applications, and to alter it and redistribute it
  13738. // freely, subject to the following restrictions:
  13739. //
  13740. // 1. The origin of this software must not be misrepresented; you must not
  13741. // claim that you wrote the original software. If you use this software
  13742. // in a product, an acknowledgment in the product documentation would be
  13743. // appreciated but is not required.
  13744. // 2. Altered source versions must be plainly marked as such, and must not be
  13745. // misrepresented as being the original software.
  13746. // 3. This notice may not be removed or altered from any source distribution.
  13747. var utils = require('../utils/common');
  13748. var trees = require('./trees');
  13749. var adler32 = require('./adler32');
  13750. var crc32 = require('./crc32');
  13751. var msg = require('./messages');
  13752. /* Public constants ==========================================================*/
  13753. /* ===========================================================================*/
  13754. /* Allowed flush values; see deflate() and inflate() below for details */
  13755. var Z_NO_FLUSH = 0;
  13756. var Z_PARTIAL_FLUSH = 1;
  13757. //var Z_SYNC_FLUSH = 2;
  13758. var Z_FULL_FLUSH = 3;
  13759. var Z_FINISH = 4;
  13760. var Z_BLOCK = 5;
  13761. //var Z_TREES = 6;
  13762. /* Return codes for the compression/decompression functions. Negative values
  13763. * are errors, positive values are used for special but normal events.
  13764. */
  13765. var Z_OK = 0;
  13766. var Z_STREAM_END = 1;
  13767. //var Z_NEED_DICT = 2;
  13768. //var Z_ERRNO = -1;
  13769. var Z_STREAM_ERROR = -2;
  13770. var Z_DATA_ERROR = -3;
  13771. //var Z_MEM_ERROR = -4;
  13772. var Z_BUF_ERROR = -5;
  13773. //var Z_VERSION_ERROR = -6;
  13774. /* compression levels */
  13775. //var Z_NO_COMPRESSION = 0;
  13776. //var Z_BEST_SPEED = 1;
  13777. //var Z_BEST_COMPRESSION = 9;
  13778. var Z_DEFAULT_COMPRESSION = -1;
  13779. var Z_FILTERED = 1;
  13780. var Z_HUFFMAN_ONLY = 2;
  13781. var Z_RLE = 3;
  13782. var Z_FIXED = 4;
  13783. var Z_DEFAULT_STRATEGY = 0;
  13784. /* Possible values of the data_type field (though see inflate()) */
  13785. //var Z_BINARY = 0;
  13786. //var Z_TEXT = 1;
  13787. //var Z_ASCII = 1; // = Z_TEXT
  13788. var Z_UNKNOWN = 2;
  13789. /* The deflate compression method */
  13790. var Z_DEFLATED = 8;
  13791. /*============================================================================*/
  13792. var MAX_MEM_LEVEL = 9;
  13793. /* Maximum value for memLevel in deflateInit2 */
  13794. var MAX_WBITS = 15;
  13795. /* 32K LZ77 window */
  13796. var DEF_MEM_LEVEL = 8;
  13797. var LENGTH_CODES = 29;
  13798. /* number of length codes, not counting the special END_BLOCK code */
  13799. var LITERALS = 256;
  13800. /* number of literal bytes 0..255 */
  13801. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  13802. /* number of Literal or Length codes, including the END_BLOCK code */
  13803. var D_CODES = 30;
  13804. /* number of distance codes */
  13805. var BL_CODES = 19;
  13806. /* number of codes used to transfer the bit lengths */
  13807. var HEAP_SIZE = 2 * L_CODES + 1;
  13808. /* maximum heap size */
  13809. var MAX_BITS = 15;
  13810. /* All codes must not exceed MAX_BITS bits */
  13811. var MIN_MATCH = 3;
  13812. var MAX_MATCH = 258;
  13813. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  13814. var PRESET_DICT = 0x20;
  13815. var INIT_STATE = 42;
  13816. var EXTRA_STATE = 69;
  13817. var NAME_STATE = 73;
  13818. var COMMENT_STATE = 91;
  13819. var HCRC_STATE = 103;
  13820. var BUSY_STATE = 113;
  13821. var FINISH_STATE = 666;
  13822. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  13823. var BS_BLOCK_DONE = 2; /* block flush performed */
  13824. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  13825. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  13826. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  13827. function err(strm, errorCode) {
  13828. strm.msg = msg[errorCode];
  13829. return errorCode;
  13830. }
  13831. function rank(f) {
  13832. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  13833. }
  13834. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  13835. /* =========================================================================
  13836. * Flush as much pending output as possible. All deflate() output goes
  13837. * through this function so some applications may wish to modify it
  13838. * to avoid allocating a large strm->output buffer and copying into it.
  13839. * (See also read_buf()).
  13840. */
  13841. function flush_pending(strm) {
  13842. var s = strm.state;
  13843. //_tr_flush_bits(s);
  13844. var len = s.pending;
  13845. if (len > strm.avail_out) {
  13846. len = strm.avail_out;
  13847. }
  13848. if (len === 0) { return; }
  13849. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  13850. strm.next_out += len;
  13851. s.pending_out += len;
  13852. strm.total_out += len;
  13853. strm.avail_out -= len;
  13854. s.pending -= len;
  13855. if (s.pending === 0) {
  13856. s.pending_out = 0;
  13857. }
  13858. }
  13859. function flush_block_only(s, last) {
  13860. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  13861. s.block_start = s.strstart;
  13862. flush_pending(s.strm);
  13863. }
  13864. function put_byte(s, b) {
  13865. s.pending_buf[s.pending++] = b;
  13866. }
  13867. /* =========================================================================
  13868. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  13869. * IN assertion: the stream state is correct and there is enough room in
  13870. * pending_buf.
  13871. */
  13872. function putShortMSB(s, b) {
  13873. // put_byte(s, (Byte)(b >> 8));
  13874. // put_byte(s, (Byte)(b & 0xff));
  13875. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  13876. s.pending_buf[s.pending++] = b & 0xff;
  13877. }
  13878. /* ===========================================================================
  13879. * Read a new buffer from the current input stream, update the adler32
  13880. * and total number of bytes read. All deflate() input goes through
  13881. * this function so some applications may wish to modify it to avoid
  13882. * allocating a large strm->input buffer and copying from it.
  13883. * (See also flush_pending()).
  13884. */
  13885. function read_buf(strm, buf, start, size) {
  13886. var len = strm.avail_in;
  13887. if (len > size) { len = size; }
  13888. if (len === 0) { return 0; }
  13889. strm.avail_in -= len;
  13890. // zmemcpy(buf, strm->next_in, len);
  13891. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  13892. if (strm.state.wrap === 1) {
  13893. strm.adler = adler32(strm.adler, buf, len, start);
  13894. }
  13895. else if (strm.state.wrap === 2) {
  13896. strm.adler = crc32(strm.adler, buf, len, start);
  13897. }
  13898. strm.next_in += len;
  13899. strm.total_in += len;
  13900. return len;
  13901. }
  13902. /* ===========================================================================
  13903. * Set match_start to the longest match starting at the given string and
  13904. * return its length. Matches shorter or equal to prev_length are discarded,
  13905. * in which case the result is equal to prev_length and match_start is
  13906. * garbage.
  13907. * IN assertions: cur_match is the head of the hash chain for the current
  13908. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  13909. * OUT assertion: the match length is not greater than s->lookahead.
  13910. */
  13911. function longest_match(s, cur_match) {
  13912. var chain_length = s.max_chain_length; /* max hash chain length */
  13913. var scan = s.strstart; /* current string */
  13914. var match; /* matched string */
  13915. var len; /* length of current match */
  13916. var best_len = s.prev_length; /* best match length so far */
  13917. var nice_match = s.nice_match; /* stop if match long enough */
  13918. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  13919. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  13920. var _win = s.window; // shortcut
  13921. var wmask = s.w_mask;
  13922. var prev = s.prev;
  13923. /* Stop when cur_match becomes <= limit. To simplify the code,
  13924. * we prevent matches with the string of window index 0.
  13925. */
  13926. var strend = s.strstart + MAX_MATCH;
  13927. var scan_end1 = _win[scan + best_len - 1];
  13928. var scan_end = _win[scan + best_len];
  13929. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  13930. * It is easy to get rid of this optimization if necessary.
  13931. */
  13932. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  13933. /* Do not waste too much time if we already have a good match: */
  13934. if (s.prev_length >= s.good_match) {
  13935. chain_length >>= 2;
  13936. }
  13937. /* Do not look for matches beyond the end of the input. This is necessary
  13938. * to make deflate deterministic.
  13939. */
  13940. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  13941. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  13942. do {
  13943. // Assert(cur_match < s->strstart, "no future");
  13944. match = cur_match;
  13945. /* Skip to next match if the match length cannot increase
  13946. * or if the match length is less than 2. Note that the checks below
  13947. * for insufficient lookahead only occur occasionally for performance
  13948. * reasons. Therefore uninitialized memory will be accessed, and
  13949. * conditional jumps will be made that depend on those values.
  13950. * However the length of the match is limited to the lookahead, so
  13951. * the output of deflate is not affected by the uninitialized values.
  13952. */
  13953. if (_win[match + best_len] !== scan_end ||
  13954. _win[match + best_len - 1] !== scan_end1 ||
  13955. _win[match] !== _win[scan] ||
  13956. _win[++match] !== _win[scan + 1]) {
  13957. continue;
  13958. }
  13959. /* The check at best_len-1 can be removed because it will be made
  13960. * again later. (This heuristic is not always a win.)
  13961. * It is not necessary to compare scan[2] and match[2] since they
  13962. * are always equal when the other bytes match, given that
  13963. * the hash keys are equal and that HASH_BITS >= 8.
  13964. */
  13965. scan += 2;
  13966. match++;
  13967. // Assert(*scan == *match, "match[2]?");
  13968. /* We check for insufficient lookahead only every 8th comparison;
  13969. * the 256th check will be made at strstart+258.
  13970. */
  13971. do {
  13972. /*jshint noempty:false*/
  13973. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13974. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13975. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13976. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  13977. scan < strend);
  13978. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  13979. len = MAX_MATCH - (strend - scan);
  13980. scan = strend - MAX_MATCH;
  13981. if (len > best_len) {
  13982. s.match_start = cur_match;
  13983. best_len = len;
  13984. if (len >= nice_match) {
  13985. break;
  13986. }
  13987. scan_end1 = _win[scan + best_len - 1];
  13988. scan_end = _win[scan + best_len];
  13989. }
  13990. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  13991. if (best_len <= s.lookahead) {
  13992. return best_len;
  13993. }
  13994. return s.lookahead;
  13995. }
  13996. /* ===========================================================================
  13997. * Fill the window when the lookahead becomes insufficient.
  13998. * Updates strstart and lookahead.
  13999. *
  14000. * IN assertion: lookahead < MIN_LOOKAHEAD
  14001. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  14002. * At least one byte has been read, or avail_in == 0; reads are
  14003. * performed for at least two bytes (required for the zip translate_eol
  14004. * option -- not supported here).
  14005. */
  14006. function fill_window(s) {
  14007. var _w_size = s.w_size;
  14008. var p, n, m, more, str;
  14009. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  14010. do {
  14011. more = s.window_size - s.lookahead - s.strstart;
  14012. // JS ints have 32 bit, block below not needed
  14013. /* Deal with !@#$% 64K limit: */
  14014. //if (sizeof(int) <= 2) {
  14015. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  14016. // more = wsize;
  14017. //
  14018. // } else if (more == (unsigned)(-1)) {
  14019. // /* Very unlikely, but possible on 16 bit machine if
  14020. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  14021. // */
  14022. // more--;
  14023. // }
  14024. //}
  14025. /* If the window is almost full and there is insufficient lookahead,
  14026. * move the upper half to the lower one to make room in the upper half.
  14027. */
  14028. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  14029. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  14030. s.match_start -= _w_size;
  14031. s.strstart -= _w_size;
  14032. /* we now have strstart >= MAX_DIST */
  14033. s.block_start -= _w_size;
  14034. /* Slide the hash table (could be avoided with 32 bit values
  14035. at the expense of memory usage). We slide even when level == 0
  14036. to keep the hash table consistent if we switch back to level > 0
  14037. later. (Using level 0 permanently is not an optimal usage of
  14038. zlib, so we don't care about this pathological case.)
  14039. */
  14040. n = s.hash_size;
  14041. p = n;
  14042. do {
  14043. m = s.head[--p];
  14044. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  14045. } while (--n);
  14046. n = _w_size;
  14047. p = n;
  14048. do {
  14049. m = s.prev[--p];
  14050. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  14051. /* If n is not on any hash chain, prev[n] is garbage but
  14052. * its value will never be used.
  14053. */
  14054. } while (--n);
  14055. more += _w_size;
  14056. }
  14057. if (s.strm.avail_in === 0) {
  14058. break;
  14059. }
  14060. /* If there was no sliding:
  14061. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  14062. * more == window_size - lookahead - strstart
  14063. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  14064. * => more >= window_size - 2*WSIZE + 2
  14065. * In the BIG_MEM or MMAP case (not yet supported),
  14066. * window_size == input_size + MIN_LOOKAHEAD &&
  14067. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  14068. * Otherwise, window_size == 2*WSIZE so more >= 2.
  14069. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  14070. */
  14071. //Assert(more >= 2, "more < 2");
  14072. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  14073. s.lookahead += n;
  14074. /* Initialize the hash value now that we have some input: */
  14075. if (s.lookahead + s.insert >= MIN_MATCH) {
  14076. str = s.strstart - s.insert;
  14077. s.ins_h = s.window[str];
  14078. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  14079. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  14080. //#if MIN_MATCH != 3
  14081. // Call update_hash() MIN_MATCH-3 more times
  14082. //#endif
  14083. while (s.insert) {
  14084. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  14085. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  14086. s.prev[str & s.w_mask] = s.head[s.ins_h];
  14087. s.head[s.ins_h] = str;
  14088. str++;
  14089. s.insert--;
  14090. if (s.lookahead + s.insert < MIN_MATCH) {
  14091. break;
  14092. }
  14093. }
  14094. }
  14095. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  14096. * but this is not important since only literal bytes will be emitted.
  14097. */
  14098. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  14099. /* If the WIN_INIT bytes after the end of the current data have never been
  14100. * written, then zero those bytes in order to avoid memory check reports of
  14101. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  14102. * the longest match routines. Update the high water mark for the next
  14103. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  14104. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  14105. */
  14106. // if (s.high_water < s.window_size) {
  14107. // var curr = s.strstart + s.lookahead;
  14108. // var init = 0;
  14109. //
  14110. // if (s.high_water < curr) {
  14111. // /* Previous high water mark below current data -- zero WIN_INIT
  14112. // * bytes or up to end of window, whichever is less.
  14113. // */
  14114. // init = s.window_size - curr;
  14115. // if (init > WIN_INIT)
  14116. // init = WIN_INIT;
  14117. // zmemzero(s->window + curr, (unsigned)init);
  14118. // s->high_water = curr + init;
  14119. // }
  14120. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  14121. // /* High water mark at or above current data, but below current data
  14122. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  14123. // * to end of window, whichever is less.
  14124. // */
  14125. // init = (ulg)curr + WIN_INIT - s->high_water;
  14126. // if (init > s->window_size - s->high_water)
  14127. // init = s->window_size - s->high_water;
  14128. // zmemzero(s->window + s->high_water, (unsigned)init);
  14129. // s->high_water += init;
  14130. // }
  14131. // }
  14132. //
  14133. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  14134. // "not enough room for search");
  14135. }
  14136. /* ===========================================================================
  14137. * Copy without compression as much as possible from the input stream, return
  14138. * the current block state.
  14139. * This function does not insert new strings in the dictionary since
  14140. * uncompressible data is probably not useful. This function is used
  14141. * only for the level=0 compression option.
  14142. * NOTE: this function should be optimized to avoid extra copying from
  14143. * window to pending_buf.
  14144. */
  14145. function deflate_stored(s, flush) {
  14146. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  14147. * to pending_buf_size, and each stored block has a 5 byte header:
  14148. */
  14149. var max_block_size = 0xffff;
  14150. if (max_block_size > s.pending_buf_size - 5) {
  14151. max_block_size = s.pending_buf_size - 5;
  14152. }
  14153. /* Copy as much as possible from input to output: */
  14154. for (;;) {
  14155. /* Fill the window as much as possible: */
  14156. if (s.lookahead <= 1) {
  14157. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  14158. // s->block_start >= (long)s->w_size, "slide too late");
  14159. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  14160. // s.block_start >= s.w_size)) {
  14161. // throw new Error("slide too late");
  14162. // }
  14163. fill_window(s);
  14164. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  14165. return BS_NEED_MORE;
  14166. }
  14167. if (s.lookahead === 0) {
  14168. break;
  14169. }
  14170. /* flush the current block */
  14171. }
  14172. //Assert(s->block_start >= 0L, "block gone");
  14173. // if (s.block_start < 0) throw new Error("block gone");
  14174. s.strstart += s.lookahead;
  14175. s.lookahead = 0;
  14176. /* Emit a stored block if pending_buf will be full: */
  14177. var max_start = s.block_start + max_block_size;
  14178. if (s.strstart === 0 || s.strstart >= max_start) {
  14179. /* strstart == 0 is possible when wraparound on 16-bit machine */
  14180. s.lookahead = s.strstart - max_start;
  14181. s.strstart = max_start;
  14182. /*** FLUSH_BLOCK(s, 0); ***/
  14183. flush_block_only(s, false);
  14184. if (s.strm.avail_out === 0) {
  14185. return BS_NEED_MORE;
  14186. }
  14187. /***/
  14188. }
  14189. /* Flush if we may have to slide, otherwise block_start may become
  14190. * negative and the data will be gone:
  14191. */
  14192. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  14193. /*** FLUSH_BLOCK(s, 0); ***/
  14194. flush_block_only(s, false);
  14195. if (s.strm.avail_out === 0) {
  14196. return BS_NEED_MORE;
  14197. }
  14198. /***/
  14199. }
  14200. }
  14201. s.insert = 0;
  14202. if (flush === Z_FINISH) {
  14203. /*** FLUSH_BLOCK(s, 1); ***/
  14204. flush_block_only(s, true);
  14205. if (s.strm.avail_out === 0) {
  14206. return BS_FINISH_STARTED;
  14207. }
  14208. /***/
  14209. return BS_FINISH_DONE;
  14210. }
  14211. if (s.strstart > s.block_start) {
  14212. /*** FLUSH_BLOCK(s, 0); ***/
  14213. flush_block_only(s, false);
  14214. if (s.strm.avail_out === 0) {
  14215. return BS_NEED_MORE;
  14216. }
  14217. /***/
  14218. }
  14219. return BS_NEED_MORE;
  14220. }
  14221. /* ===========================================================================
  14222. * Compress as much as possible from the input stream, return the current
  14223. * block state.
  14224. * This function does not perform lazy evaluation of matches and inserts
  14225. * new strings in the dictionary only for unmatched strings or for short
  14226. * matches. It is used only for the fast compression options.
  14227. */
  14228. function deflate_fast(s, flush) {
  14229. var hash_head; /* head of the hash chain */
  14230. var bflush; /* set if current block must be flushed */
  14231. for (;;) {
  14232. /* Make sure that we always have enough lookahead, except
  14233. * at the end of the input file. We need MAX_MATCH bytes
  14234. * for the next match, plus MIN_MATCH bytes to insert the
  14235. * string following the next match.
  14236. */
  14237. if (s.lookahead < MIN_LOOKAHEAD) {
  14238. fill_window(s);
  14239. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  14240. return BS_NEED_MORE;
  14241. }
  14242. if (s.lookahead === 0) {
  14243. break; /* flush the current block */
  14244. }
  14245. }
  14246. /* Insert the string window[strstart .. strstart+2] in the
  14247. * dictionary, and set hash_head to the head of the hash chain:
  14248. */
  14249. hash_head = 0/*NIL*/;
  14250. if (s.lookahead >= MIN_MATCH) {
  14251. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14252. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14253. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14254. s.head[s.ins_h] = s.strstart;
  14255. /***/
  14256. }
  14257. /* Find the longest match, discarding those <= prev_length.
  14258. * At this point we have always match_length < MIN_MATCH
  14259. */
  14260. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  14261. /* To simplify the code, we prevent matches with the string
  14262. * of window index 0 (in particular we have to avoid a match
  14263. * of the string with itself at the start of the input file).
  14264. */
  14265. s.match_length = longest_match(s, hash_head);
  14266. /* longest_match() sets match_start */
  14267. }
  14268. if (s.match_length >= MIN_MATCH) {
  14269. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  14270. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  14271. s.match_length - MIN_MATCH, bflush); ***/
  14272. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  14273. s.lookahead -= s.match_length;
  14274. /* Insert new strings in the hash table only if the match length
  14275. * is not too large. This saves time but degrades compression.
  14276. */
  14277. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  14278. s.match_length--; /* string at strstart already in table */
  14279. do {
  14280. s.strstart++;
  14281. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14282. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14283. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14284. s.head[s.ins_h] = s.strstart;
  14285. /***/
  14286. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  14287. * always MIN_MATCH bytes ahead.
  14288. */
  14289. } while (--s.match_length !== 0);
  14290. s.strstart++;
  14291. } else
  14292. {
  14293. s.strstart += s.match_length;
  14294. s.match_length = 0;
  14295. s.ins_h = s.window[s.strstart];
  14296. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  14297. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  14298. //#if MIN_MATCH != 3
  14299. // Call UPDATE_HASH() MIN_MATCH-3 more times
  14300. //#endif
  14301. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  14302. * matter since it will be recomputed at next deflate call.
  14303. */
  14304. }
  14305. } else {
  14306. /* No match, output a literal byte */
  14307. //Tracevv((stderr,"%c", s.window[s.strstart]));
  14308. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14309. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14310. s.lookahead--;
  14311. s.strstart++;
  14312. }
  14313. if (bflush) {
  14314. /*** FLUSH_BLOCK(s, 0); ***/
  14315. flush_block_only(s, false);
  14316. if (s.strm.avail_out === 0) {
  14317. return BS_NEED_MORE;
  14318. }
  14319. /***/
  14320. }
  14321. }
  14322. s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
  14323. if (flush === Z_FINISH) {
  14324. /*** FLUSH_BLOCK(s, 1); ***/
  14325. flush_block_only(s, true);
  14326. if (s.strm.avail_out === 0) {
  14327. return BS_FINISH_STARTED;
  14328. }
  14329. /***/
  14330. return BS_FINISH_DONE;
  14331. }
  14332. if (s.last_lit) {
  14333. /*** FLUSH_BLOCK(s, 0); ***/
  14334. flush_block_only(s, false);
  14335. if (s.strm.avail_out === 0) {
  14336. return BS_NEED_MORE;
  14337. }
  14338. /***/
  14339. }
  14340. return BS_BLOCK_DONE;
  14341. }
  14342. /* ===========================================================================
  14343. * Same as above, but achieves better compression. We use a lazy
  14344. * evaluation for matches: a match is finally adopted only if there is
  14345. * no better match at the next window position.
  14346. */
  14347. function deflate_slow(s, flush) {
  14348. var hash_head; /* head of hash chain */
  14349. var bflush; /* set if current block must be flushed */
  14350. var max_insert;
  14351. /* Process the input block. */
  14352. for (;;) {
  14353. /* Make sure that we always have enough lookahead, except
  14354. * at the end of the input file. We need MAX_MATCH bytes
  14355. * for the next match, plus MIN_MATCH bytes to insert the
  14356. * string following the next match.
  14357. */
  14358. if (s.lookahead < MIN_LOOKAHEAD) {
  14359. fill_window(s);
  14360. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  14361. return BS_NEED_MORE;
  14362. }
  14363. if (s.lookahead === 0) { break; } /* flush the current block */
  14364. }
  14365. /* Insert the string window[strstart .. strstart+2] in the
  14366. * dictionary, and set hash_head to the head of the hash chain:
  14367. */
  14368. hash_head = 0/*NIL*/;
  14369. if (s.lookahead >= MIN_MATCH) {
  14370. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14371. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14372. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14373. s.head[s.ins_h] = s.strstart;
  14374. /***/
  14375. }
  14376. /* Find the longest match, discarding those <= prev_length.
  14377. */
  14378. s.prev_length = s.match_length;
  14379. s.prev_match = s.match_start;
  14380. s.match_length = MIN_MATCH - 1;
  14381. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  14382. s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  14383. /* To simplify the code, we prevent matches with the string
  14384. * of window index 0 (in particular we have to avoid a match
  14385. * of the string with itself at the start of the input file).
  14386. */
  14387. s.match_length = longest_match(s, hash_head);
  14388. /* longest_match() sets match_start */
  14389. if (s.match_length <= 5 &&
  14390. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  14391. /* If prev_match is also MIN_MATCH, match_start is garbage
  14392. * but we will ignore the current match anyway.
  14393. */
  14394. s.match_length = MIN_MATCH - 1;
  14395. }
  14396. }
  14397. /* If there was a match at the previous step and the current
  14398. * match is not better, output the previous match:
  14399. */
  14400. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  14401. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  14402. /* Do not insert strings in hash table beyond this. */
  14403. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  14404. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  14405. s.prev_length - MIN_MATCH, bflush);***/
  14406. bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
  14407. /* Insert in hash table all strings up to the end of the match.
  14408. * strstart-1 and strstart are already inserted. If there is not
  14409. * enough lookahead, the last two strings are not inserted in
  14410. * the hash table.
  14411. */
  14412. s.lookahead -= s.prev_length - 1;
  14413. s.prev_length -= 2;
  14414. do {
  14415. if (++s.strstart <= max_insert) {
  14416. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  14417. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  14418. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  14419. s.head[s.ins_h] = s.strstart;
  14420. /***/
  14421. }
  14422. } while (--s.prev_length !== 0);
  14423. s.match_available = 0;
  14424. s.match_length = MIN_MATCH - 1;
  14425. s.strstart++;
  14426. if (bflush) {
  14427. /*** FLUSH_BLOCK(s, 0); ***/
  14428. flush_block_only(s, false);
  14429. if (s.strm.avail_out === 0) {
  14430. return BS_NEED_MORE;
  14431. }
  14432. /***/
  14433. }
  14434. } else if (s.match_available) {
  14435. /* If there was no match at the previous position, output a
  14436. * single literal. If there was a match but the current match
  14437. * is longer, truncate the previous match to a single literal.
  14438. */
  14439. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  14440. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  14441. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  14442. if (bflush) {
  14443. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  14444. flush_block_only(s, false);
  14445. /***/
  14446. }
  14447. s.strstart++;
  14448. s.lookahead--;
  14449. if (s.strm.avail_out === 0) {
  14450. return BS_NEED_MORE;
  14451. }
  14452. } else {
  14453. /* There is no previous match to compare with, wait for
  14454. * the next step to decide.
  14455. */
  14456. s.match_available = 1;
  14457. s.strstart++;
  14458. s.lookahead--;
  14459. }
  14460. }
  14461. //Assert (flush != Z_NO_FLUSH, "no flush?");
  14462. if (s.match_available) {
  14463. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  14464. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  14465. bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
  14466. s.match_available = 0;
  14467. }
  14468. s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
  14469. if (flush === Z_FINISH) {
  14470. /*** FLUSH_BLOCK(s, 1); ***/
  14471. flush_block_only(s, true);
  14472. if (s.strm.avail_out === 0) {
  14473. return BS_FINISH_STARTED;
  14474. }
  14475. /***/
  14476. return BS_FINISH_DONE;
  14477. }
  14478. if (s.last_lit) {
  14479. /*** FLUSH_BLOCK(s, 0); ***/
  14480. flush_block_only(s, false);
  14481. if (s.strm.avail_out === 0) {
  14482. return BS_NEED_MORE;
  14483. }
  14484. /***/
  14485. }
  14486. return BS_BLOCK_DONE;
  14487. }
  14488. /* ===========================================================================
  14489. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  14490. * one. Do not maintain a hash table. (It will be regenerated if this run of
  14491. * deflate switches away from Z_RLE.)
  14492. */
  14493. function deflate_rle(s, flush) {
  14494. var bflush; /* set if current block must be flushed */
  14495. var prev; /* byte at distance one to match */
  14496. var scan, strend; /* scan goes up to strend for length of run */
  14497. var _win = s.window;
  14498. for (;;) {
  14499. /* Make sure that we always have enough lookahead, except
  14500. * at the end of the input file. We need MAX_MATCH bytes
  14501. * for the longest run, plus one for the unrolled loop.
  14502. */
  14503. if (s.lookahead <= MAX_MATCH) {
  14504. fill_window(s);
  14505. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  14506. return BS_NEED_MORE;
  14507. }
  14508. if (s.lookahead === 0) { break; } /* flush the current block */
  14509. }
  14510. /* See how many times the previous byte repeats */
  14511. s.match_length = 0;
  14512. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  14513. scan = s.strstart - 1;
  14514. prev = _win[scan];
  14515. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  14516. strend = s.strstart + MAX_MATCH;
  14517. do {
  14518. /*jshint noempty:false*/
  14519. } while (prev === _win[++scan] && prev === _win[++scan] &&
  14520. prev === _win[++scan] && prev === _win[++scan] &&
  14521. prev === _win[++scan] && prev === _win[++scan] &&
  14522. prev === _win[++scan] && prev === _win[++scan] &&
  14523. scan < strend);
  14524. s.match_length = MAX_MATCH - (strend - scan);
  14525. if (s.match_length > s.lookahead) {
  14526. s.match_length = s.lookahead;
  14527. }
  14528. }
  14529. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  14530. }
  14531. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  14532. if (s.match_length >= MIN_MATCH) {
  14533. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  14534. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  14535. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  14536. s.lookahead -= s.match_length;
  14537. s.strstart += s.match_length;
  14538. s.match_length = 0;
  14539. } else {
  14540. /* No match, output a literal byte */
  14541. //Tracevv((stderr,"%c", s->window[s->strstart]));
  14542. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14543. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14544. s.lookahead--;
  14545. s.strstart++;
  14546. }
  14547. if (bflush) {
  14548. /*** FLUSH_BLOCK(s, 0); ***/
  14549. flush_block_only(s, false);
  14550. if (s.strm.avail_out === 0) {
  14551. return BS_NEED_MORE;
  14552. }
  14553. /***/
  14554. }
  14555. }
  14556. s.insert = 0;
  14557. if (flush === Z_FINISH) {
  14558. /*** FLUSH_BLOCK(s, 1); ***/
  14559. flush_block_only(s, true);
  14560. if (s.strm.avail_out === 0) {
  14561. return BS_FINISH_STARTED;
  14562. }
  14563. /***/
  14564. return BS_FINISH_DONE;
  14565. }
  14566. if (s.last_lit) {
  14567. /*** FLUSH_BLOCK(s, 0); ***/
  14568. flush_block_only(s, false);
  14569. if (s.strm.avail_out === 0) {
  14570. return BS_NEED_MORE;
  14571. }
  14572. /***/
  14573. }
  14574. return BS_BLOCK_DONE;
  14575. }
  14576. /* ===========================================================================
  14577. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  14578. * (It will be regenerated if this run of deflate switches away from Huffman.)
  14579. */
  14580. function deflate_huff(s, flush) {
  14581. var bflush; /* set if current block must be flushed */
  14582. for (;;) {
  14583. /* Make sure that we have a literal to write. */
  14584. if (s.lookahead === 0) {
  14585. fill_window(s);
  14586. if (s.lookahead === 0) {
  14587. if (flush === Z_NO_FLUSH) {
  14588. return BS_NEED_MORE;
  14589. }
  14590. break; /* flush the current block */
  14591. }
  14592. }
  14593. /* Output a literal byte */
  14594. s.match_length = 0;
  14595. //Tracevv((stderr,"%c", s->window[s->strstart]));
  14596. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  14597. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  14598. s.lookahead--;
  14599. s.strstart++;
  14600. if (bflush) {
  14601. /*** FLUSH_BLOCK(s, 0); ***/
  14602. flush_block_only(s, false);
  14603. if (s.strm.avail_out === 0) {
  14604. return BS_NEED_MORE;
  14605. }
  14606. /***/
  14607. }
  14608. }
  14609. s.insert = 0;
  14610. if (flush === Z_FINISH) {
  14611. /*** FLUSH_BLOCK(s, 1); ***/
  14612. flush_block_only(s, true);
  14613. if (s.strm.avail_out === 0) {
  14614. return BS_FINISH_STARTED;
  14615. }
  14616. /***/
  14617. return BS_FINISH_DONE;
  14618. }
  14619. if (s.last_lit) {
  14620. /*** FLUSH_BLOCK(s, 0); ***/
  14621. flush_block_only(s, false);
  14622. if (s.strm.avail_out === 0) {
  14623. return BS_NEED_MORE;
  14624. }
  14625. /***/
  14626. }
  14627. return BS_BLOCK_DONE;
  14628. }
  14629. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  14630. * the desired pack level (0..9). The values given below have been tuned to
  14631. * exclude worst case performance for pathological files. Better values may be
  14632. * found for specific files.
  14633. */
  14634. function Config(good_length, max_lazy, nice_length, max_chain, func) {
  14635. this.good_length = good_length;
  14636. this.max_lazy = max_lazy;
  14637. this.nice_length = nice_length;
  14638. this.max_chain = max_chain;
  14639. this.func = func;
  14640. }
  14641. var configuration_table;
  14642. configuration_table = [
  14643. /* good lazy nice chain */
  14644. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  14645. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  14646. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  14647. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  14648. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  14649. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  14650. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  14651. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  14652. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  14653. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  14654. ];
  14655. /* ===========================================================================
  14656. * Initialize the "longest match" routines for a new zlib stream
  14657. */
  14658. function lm_init(s) {
  14659. s.window_size = 2 * s.w_size;
  14660. /*** CLEAR_HASH(s); ***/
  14661. zero(s.head); // Fill with NIL (= 0);
  14662. /* Set the default configuration parameters:
  14663. */
  14664. s.max_lazy_match = configuration_table[s.level].max_lazy;
  14665. s.good_match = configuration_table[s.level].good_length;
  14666. s.nice_match = configuration_table[s.level].nice_length;
  14667. s.max_chain_length = configuration_table[s.level].max_chain;
  14668. s.strstart = 0;
  14669. s.block_start = 0;
  14670. s.lookahead = 0;
  14671. s.insert = 0;
  14672. s.match_length = s.prev_length = MIN_MATCH - 1;
  14673. s.match_available = 0;
  14674. s.ins_h = 0;
  14675. }
  14676. function DeflateState() {
  14677. this.strm = null; /* pointer back to this zlib stream */
  14678. this.status = 0; /* as the name implies */
  14679. this.pending_buf = null; /* output still pending */
  14680. this.pending_buf_size = 0; /* size of pending_buf */
  14681. this.pending_out = 0; /* next pending byte to output to the stream */
  14682. this.pending = 0; /* nb of bytes in the pending buffer */
  14683. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  14684. this.gzhead = null; /* gzip header information to write */
  14685. this.gzindex = 0; /* where in extra, name, or comment */
  14686. this.method = Z_DEFLATED; /* can only be DEFLATED */
  14687. this.last_flush = -1; /* value of flush param for previous deflate call */
  14688. this.w_size = 0; /* LZ77 window size (32K by default) */
  14689. this.w_bits = 0; /* log2(w_size) (8..16) */
  14690. this.w_mask = 0; /* w_size - 1 */
  14691. this.window = null;
  14692. /* Sliding window. Input bytes are read into the second half of the window,
  14693. * and move to the first half later to keep a dictionary of at least wSize
  14694. * bytes. With this organization, matches are limited to a distance of
  14695. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  14696. * performed with a length multiple of the block size.
  14697. */
  14698. this.window_size = 0;
  14699. /* Actual size of window: 2*wSize, except when the user input buffer
  14700. * is directly used as sliding window.
  14701. */
  14702. this.prev = null;
  14703. /* Link to older string with same hash index. To limit the size of this
  14704. * array to 64K, this link is maintained only for the last 32K strings.
  14705. * An index in this array is thus a window index modulo 32K.
  14706. */
  14707. this.head = null; /* Heads of the hash chains or NIL. */
  14708. this.ins_h = 0; /* hash index of string to be inserted */
  14709. this.hash_size = 0; /* number of elements in hash table */
  14710. this.hash_bits = 0; /* log2(hash_size) */
  14711. this.hash_mask = 0; /* hash_size-1 */
  14712. this.hash_shift = 0;
  14713. /* Number of bits by which ins_h must be shifted at each input
  14714. * step. It must be such that after MIN_MATCH steps, the oldest
  14715. * byte no longer takes part in the hash key, that is:
  14716. * hash_shift * MIN_MATCH >= hash_bits
  14717. */
  14718. this.block_start = 0;
  14719. /* Window position at the beginning of the current output block. Gets
  14720. * negative when the window is moved backwards.
  14721. */
  14722. this.match_length = 0; /* length of best match */
  14723. this.prev_match = 0; /* previous match */
  14724. this.match_available = 0; /* set if previous match exists */
  14725. this.strstart = 0; /* start of string to insert */
  14726. this.match_start = 0; /* start of matching string */
  14727. this.lookahead = 0; /* number of valid bytes ahead in window */
  14728. this.prev_length = 0;
  14729. /* Length of the best match at previous step. Matches not greater than this
  14730. * are discarded. This is used in the lazy match evaluation.
  14731. */
  14732. this.max_chain_length = 0;
  14733. /* To speed up deflation, hash chains are never searched beyond this
  14734. * length. A higher limit improves compression ratio but degrades the
  14735. * speed.
  14736. */
  14737. this.max_lazy_match = 0;
  14738. /* Attempt to find a better match only when the current match is strictly
  14739. * smaller than this value. This mechanism is used only for compression
  14740. * levels >= 4.
  14741. */
  14742. // That's alias to max_lazy_match, don't use directly
  14743. //this.max_insert_length = 0;
  14744. /* Insert new strings in the hash table only if the match length is not
  14745. * greater than this length. This saves time but degrades compression.
  14746. * max_insert_length is used only for compression levels <= 3.
  14747. */
  14748. this.level = 0; /* compression level (1..9) */
  14749. this.strategy = 0; /* favor or force Huffman coding*/
  14750. this.good_match = 0;
  14751. /* Use a faster search when the previous match is longer than this */
  14752. this.nice_match = 0; /* Stop searching when current match exceeds this */
  14753. /* used by trees.c: */
  14754. /* Didn't use ct_data typedef below to suppress compiler warning */
  14755. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  14756. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  14757. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  14758. // Use flat array of DOUBLE size, with interleaved fata,
  14759. // because JS does not support effective
  14760. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  14761. this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
  14762. this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
  14763. zero(this.dyn_ltree);
  14764. zero(this.dyn_dtree);
  14765. zero(this.bl_tree);
  14766. this.l_desc = null; /* desc. for literal tree */
  14767. this.d_desc = null; /* desc. for distance tree */
  14768. this.bl_desc = null; /* desc. for bit length tree */
  14769. //ush bl_count[MAX_BITS+1];
  14770. this.bl_count = new utils.Buf16(MAX_BITS + 1);
  14771. /* number of codes at each bit length for an optimal tree */
  14772. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  14773. this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
  14774. zero(this.heap);
  14775. this.heap_len = 0; /* number of elements in the heap */
  14776. this.heap_max = 0; /* element of largest frequency */
  14777. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  14778. * The same heap array is used to build all trees.
  14779. */
  14780. this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
  14781. zero(this.depth);
  14782. /* Depth of each subtree used as tie breaker for trees of equal frequency
  14783. */
  14784. this.l_buf = 0; /* buffer index for literals or lengths */
  14785. this.lit_bufsize = 0;
  14786. /* Size of match buffer for literals/lengths. There are 4 reasons for
  14787. * limiting lit_bufsize to 64K:
  14788. * - frequencies can be kept in 16 bit counters
  14789. * - if compression is not successful for the first block, all input
  14790. * data is still in the window so we can still emit a stored block even
  14791. * when input comes from standard input. (This can also be done for
  14792. * all blocks if lit_bufsize is not greater than 32K.)
  14793. * - if compression is not successful for a file smaller than 64K, we can
  14794. * even emit a stored file instead of a stored block (saving 5 bytes).
  14795. * This is applicable only for zip (not gzip or zlib).
  14796. * - creating new Huffman trees less frequently may not provide fast
  14797. * adaptation to changes in the input data statistics. (Take for
  14798. * example a binary file with poorly compressible code followed by
  14799. * a highly compressible string table.) Smaller buffer sizes give
  14800. * fast adaptation but have of course the overhead of transmitting
  14801. * trees more frequently.
  14802. * - I can't count above 4
  14803. */
  14804. this.last_lit = 0; /* running index in l_buf */
  14805. this.d_buf = 0;
  14806. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  14807. * the same number of elements. To use different lengths, an extra flag
  14808. * array would be necessary.
  14809. */
  14810. this.opt_len = 0; /* bit length of current block with optimal trees */
  14811. this.static_len = 0; /* bit length of current block with static trees */
  14812. this.matches = 0; /* number of string matches in current block */
  14813. this.insert = 0; /* bytes at end of window left to insert */
  14814. this.bi_buf = 0;
  14815. /* Output buffer. bits are inserted starting at the bottom (least
  14816. * significant bits).
  14817. */
  14818. this.bi_valid = 0;
  14819. /* Number of valid bits in bi_buf. All bits above the last valid bit
  14820. * are always zero.
  14821. */
  14822. // Used for window memory init. We safely ignore it for JS. That makes
  14823. // sense only for pointers and memory check tools.
  14824. //this.high_water = 0;
  14825. /* High water mark offset in window for initialized bytes -- bytes above
  14826. * this are set to zero in order to avoid memory check warnings when
  14827. * longest match routines access bytes past the input. This is then
  14828. * updated to the new high water mark.
  14829. */
  14830. }
  14831. function deflateResetKeep(strm) {
  14832. var s;
  14833. if (!strm || !strm.state) {
  14834. return err(strm, Z_STREAM_ERROR);
  14835. }
  14836. strm.total_in = strm.total_out = 0;
  14837. strm.data_type = Z_UNKNOWN;
  14838. s = strm.state;
  14839. s.pending = 0;
  14840. s.pending_out = 0;
  14841. if (s.wrap < 0) {
  14842. s.wrap = -s.wrap;
  14843. /* was made negative by deflate(..., Z_FINISH); */
  14844. }
  14845. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  14846. strm.adler = (s.wrap === 2) ?
  14847. 0 // crc32(0, Z_NULL, 0)
  14848. :
  14849. 1; // adler32(0, Z_NULL, 0)
  14850. s.last_flush = Z_NO_FLUSH;
  14851. trees._tr_init(s);
  14852. return Z_OK;
  14853. }
  14854. function deflateReset(strm) {
  14855. var ret = deflateResetKeep(strm);
  14856. if (ret === Z_OK) {
  14857. lm_init(strm.state);
  14858. }
  14859. return ret;
  14860. }
  14861. function deflateSetHeader(strm, head) {
  14862. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  14863. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  14864. strm.state.gzhead = head;
  14865. return Z_OK;
  14866. }
  14867. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  14868. if (!strm) { // === Z_NULL
  14869. return Z_STREAM_ERROR;
  14870. }
  14871. var wrap = 1;
  14872. if (level === Z_DEFAULT_COMPRESSION) {
  14873. level = 6;
  14874. }
  14875. if (windowBits < 0) { /* suppress zlib wrapper */
  14876. wrap = 0;
  14877. windowBits = -windowBits;
  14878. }
  14879. else if (windowBits > 15) {
  14880. wrap = 2; /* write gzip wrapper instead */
  14881. windowBits -= 16;
  14882. }
  14883. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  14884. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  14885. strategy < 0 || strategy > Z_FIXED) {
  14886. return err(strm, Z_STREAM_ERROR);
  14887. }
  14888. if (windowBits === 8) {
  14889. windowBits = 9;
  14890. }
  14891. /* until 256-byte window bug fixed */
  14892. var s = new DeflateState();
  14893. strm.state = s;
  14894. s.strm = strm;
  14895. s.wrap = wrap;
  14896. s.gzhead = null;
  14897. s.w_bits = windowBits;
  14898. s.w_size = 1 << s.w_bits;
  14899. s.w_mask = s.w_size - 1;
  14900. s.hash_bits = memLevel + 7;
  14901. s.hash_size = 1 << s.hash_bits;
  14902. s.hash_mask = s.hash_size - 1;
  14903. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  14904. s.window = new utils.Buf8(s.w_size * 2);
  14905. s.head = new utils.Buf16(s.hash_size);
  14906. s.prev = new utils.Buf16(s.w_size);
  14907. // Don't need mem init magic for JS.
  14908. //s.high_water = 0; /* nothing written to s->window yet */
  14909. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  14910. s.pending_buf_size = s.lit_bufsize * 4;
  14911. //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  14912. //s->pending_buf = (uchf *) overlay;
  14913. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  14914. // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
  14915. //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  14916. s.d_buf = 1 * s.lit_bufsize;
  14917. //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  14918. s.l_buf = (1 + 2) * s.lit_bufsize;
  14919. s.level = level;
  14920. s.strategy = strategy;
  14921. s.method = method;
  14922. return deflateReset(strm);
  14923. }
  14924. function deflateInit(strm, level) {
  14925. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  14926. }
  14927. function deflate(strm, flush) {
  14928. var old_flush, s;
  14929. var beg, val; // for gzip header write only
  14930. if (!strm || !strm.state ||
  14931. flush > Z_BLOCK || flush < 0) {
  14932. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  14933. }
  14934. s = strm.state;
  14935. if (!strm.output ||
  14936. (!strm.input && strm.avail_in !== 0) ||
  14937. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  14938. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  14939. }
  14940. s.strm = strm; /* just in case */
  14941. old_flush = s.last_flush;
  14942. s.last_flush = flush;
  14943. /* Write the header */
  14944. if (s.status === INIT_STATE) {
  14945. if (s.wrap === 2) { // GZIP header
  14946. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  14947. put_byte(s, 31);
  14948. put_byte(s, 139);
  14949. put_byte(s, 8);
  14950. if (!s.gzhead) { // s->gzhead == Z_NULL
  14951. put_byte(s, 0);
  14952. put_byte(s, 0);
  14953. put_byte(s, 0);
  14954. put_byte(s, 0);
  14955. put_byte(s, 0);
  14956. put_byte(s, s.level === 9 ? 2 :
  14957. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  14958. 4 : 0));
  14959. put_byte(s, OS_CODE);
  14960. s.status = BUSY_STATE;
  14961. }
  14962. else {
  14963. put_byte(s, (s.gzhead.text ? 1 : 0) +
  14964. (s.gzhead.hcrc ? 2 : 0) +
  14965. (!s.gzhead.extra ? 0 : 4) +
  14966. (!s.gzhead.name ? 0 : 8) +
  14967. (!s.gzhead.comment ? 0 : 16)
  14968. );
  14969. put_byte(s, s.gzhead.time & 0xff);
  14970. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  14971. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  14972. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  14973. put_byte(s, s.level === 9 ? 2 :
  14974. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  14975. 4 : 0));
  14976. put_byte(s, s.gzhead.os & 0xff);
  14977. if (s.gzhead.extra && s.gzhead.extra.length) {
  14978. put_byte(s, s.gzhead.extra.length & 0xff);
  14979. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  14980. }
  14981. if (s.gzhead.hcrc) {
  14982. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  14983. }
  14984. s.gzindex = 0;
  14985. s.status = EXTRA_STATE;
  14986. }
  14987. }
  14988. else // DEFLATE header
  14989. {
  14990. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  14991. var level_flags = -1;
  14992. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  14993. level_flags = 0;
  14994. } else if (s.level < 6) {
  14995. level_flags = 1;
  14996. } else if (s.level === 6) {
  14997. level_flags = 2;
  14998. } else {
  14999. level_flags = 3;
  15000. }
  15001. header |= (level_flags << 6);
  15002. if (s.strstart !== 0) { header |= PRESET_DICT; }
  15003. header += 31 - (header % 31);
  15004. s.status = BUSY_STATE;
  15005. putShortMSB(s, header);
  15006. /* Save the adler32 of the preset dictionary: */
  15007. if (s.strstart !== 0) {
  15008. putShortMSB(s, strm.adler >>> 16);
  15009. putShortMSB(s, strm.adler & 0xffff);
  15010. }
  15011. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  15012. }
  15013. }
  15014. //#ifdef GZIP
  15015. if (s.status === EXTRA_STATE) {
  15016. if (s.gzhead.extra/* != Z_NULL*/) {
  15017. beg = s.pending; /* start of bytes to update crc */
  15018. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  15019. if (s.pending === s.pending_buf_size) {
  15020. if (s.gzhead.hcrc && s.pending > beg) {
  15021. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15022. }
  15023. flush_pending(strm);
  15024. beg = s.pending;
  15025. if (s.pending === s.pending_buf_size) {
  15026. break;
  15027. }
  15028. }
  15029. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  15030. s.gzindex++;
  15031. }
  15032. if (s.gzhead.hcrc && s.pending > beg) {
  15033. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15034. }
  15035. if (s.gzindex === s.gzhead.extra.length) {
  15036. s.gzindex = 0;
  15037. s.status = NAME_STATE;
  15038. }
  15039. }
  15040. else {
  15041. s.status = NAME_STATE;
  15042. }
  15043. }
  15044. if (s.status === NAME_STATE) {
  15045. if (s.gzhead.name/* != Z_NULL*/) {
  15046. beg = s.pending; /* start of bytes to update crc */
  15047. //int val;
  15048. do {
  15049. if (s.pending === s.pending_buf_size) {
  15050. if (s.gzhead.hcrc && s.pending > beg) {
  15051. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15052. }
  15053. flush_pending(strm);
  15054. beg = s.pending;
  15055. if (s.pending === s.pending_buf_size) {
  15056. val = 1;
  15057. break;
  15058. }
  15059. }
  15060. // JS specific: little magic to add zero terminator to end of string
  15061. if (s.gzindex < s.gzhead.name.length) {
  15062. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  15063. } else {
  15064. val = 0;
  15065. }
  15066. put_byte(s, val);
  15067. } while (val !== 0);
  15068. if (s.gzhead.hcrc && s.pending > beg) {
  15069. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15070. }
  15071. if (val === 0) {
  15072. s.gzindex = 0;
  15073. s.status = COMMENT_STATE;
  15074. }
  15075. }
  15076. else {
  15077. s.status = COMMENT_STATE;
  15078. }
  15079. }
  15080. if (s.status === COMMENT_STATE) {
  15081. if (s.gzhead.comment/* != Z_NULL*/) {
  15082. beg = s.pending; /* start of bytes to update crc */
  15083. //int val;
  15084. do {
  15085. if (s.pending === s.pending_buf_size) {
  15086. if (s.gzhead.hcrc && s.pending > beg) {
  15087. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15088. }
  15089. flush_pending(strm);
  15090. beg = s.pending;
  15091. if (s.pending === s.pending_buf_size) {
  15092. val = 1;
  15093. break;
  15094. }
  15095. }
  15096. // JS specific: little magic to add zero terminator to end of string
  15097. if (s.gzindex < s.gzhead.comment.length) {
  15098. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  15099. } else {
  15100. val = 0;
  15101. }
  15102. put_byte(s, val);
  15103. } while (val !== 0);
  15104. if (s.gzhead.hcrc && s.pending > beg) {
  15105. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  15106. }
  15107. if (val === 0) {
  15108. s.status = HCRC_STATE;
  15109. }
  15110. }
  15111. else {
  15112. s.status = HCRC_STATE;
  15113. }
  15114. }
  15115. if (s.status === HCRC_STATE) {
  15116. if (s.gzhead.hcrc) {
  15117. if (s.pending + 2 > s.pending_buf_size) {
  15118. flush_pending(strm);
  15119. }
  15120. if (s.pending + 2 <= s.pending_buf_size) {
  15121. put_byte(s, strm.adler & 0xff);
  15122. put_byte(s, (strm.adler >> 8) & 0xff);
  15123. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  15124. s.status = BUSY_STATE;
  15125. }
  15126. }
  15127. else {
  15128. s.status = BUSY_STATE;
  15129. }
  15130. }
  15131. //#endif
  15132. /* Flush as much pending output as possible */
  15133. if (s.pending !== 0) {
  15134. flush_pending(strm);
  15135. if (strm.avail_out === 0) {
  15136. /* Since avail_out is 0, deflate will be called again with
  15137. * more output space, but possibly with both pending and
  15138. * avail_in equal to zero. There won't be anything to do,
  15139. * but this is not an error situation so make sure we
  15140. * return OK instead of BUF_ERROR at next call of deflate:
  15141. */
  15142. s.last_flush = -1;
  15143. return Z_OK;
  15144. }
  15145. /* Make sure there is something to do and avoid duplicate consecutive
  15146. * flushes. For repeated and useless calls with Z_FINISH, we keep
  15147. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  15148. */
  15149. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  15150. flush !== Z_FINISH) {
  15151. return err(strm, Z_BUF_ERROR);
  15152. }
  15153. /* User must not provide more input after the first FINISH: */
  15154. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  15155. return err(strm, Z_BUF_ERROR);
  15156. }
  15157. /* Start a new block or continue the current one.
  15158. */
  15159. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  15160. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  15161. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  15162. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  15163. configuration_table[s.level].func(s, flush));
  15164. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  15165. s.status = FINISH_STATE;
  15166. }
  15167. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  15168. if (strm.avail_out === 0) {
  15169. s.last_flush = -1;
  15170. /* avoid BUF_ERROR next call, see above */
  15171. }
  15172. return Z_OK;
  15173. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  15174. * of deflate should use the same flush parameter to make sure
  15175. * that the flush is complete. So we don't have to output an
  15176. * empty block here, this will be done at next call. This also
  15177. * ensures that for a very small output buffer, we emit at most
  15178. * one empty block.
  15179. */
  15180. }
  15181. if (bstate === BS_BLOCK_DONE) {
  15182. if (flush === Z_PARTIAL_FLUSH) {
  15183. trees._tr_align(s);
  15184. }
  15185. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  15186. trees._tr_stored_block(s, 0, 0, false);
  15187. /* For a full flush, this empty block will be recognized
  15188. * as a special marker by inflate_sync().
  15189. */
  15190. if (flush === Z_FULL_FLUSH) {
  15191. /*** CLEAR_HASH(s); ***/ /* forget history */
  15192. zero(s.head); // Fill with NIL (= 0);
  15193. if (s.lookahead === 0) {
  15194. s.strstart = 0;
  15195. s.block_start = 0;
  15196. s.insert = 0;
  15197. }
  15198. }
  15199. }
  15200. flush_pending(strm);
  15201. if (strm.avail_out === 0) {
  15202. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  15203. return Z_OK;
  15204. }
  15205. }
  15206. }
  15207. //Assert(strm->avail_out > 0, "bug2");
  15208. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  15209. if (flush !== Z_FINISH) { return Z_OK; }
  15210. if (s.wrap <= 0) { return Z_STREAM_END; }
  15211. /* Write the trailer */
  15212. if (s.wrap === 2) {
  15213. put_byte(s, strm.adler & 0xff);
  15214. put_byte(s, (strm.adler >> 8) & 0xff);
  15215. put_byte(s, (strm.adler >> 16) & 0xff);
  15216. put_byte(s, (strm.adler >> 24) & 0xff);
  15217. put_byte(s, strm.total_in & 0xff);
  15218. put_byte(s, (strm.total_in >> 8) & 0xff);
  15219. put_byte(s, (strm.total_in >> 16) & 0xff);
  15220. put_byte(s, (strm.total_in >> 24) & 0xff);
  15221. }
  15222. else
  15223. {
  15224. putShortMSB(s, strm.adler >>> 16);
  15225. putShortMSB(s, strm.adler & 0xffff);
  15226. }
  15227. flush_pending(strm);
  15228. /* If avail_out is zero, the application will call deflate again
  15229. * to flush the rest.
  15230. */
  15231. if (s.wrap > 0) { s.wrap = -s.wrap; }
  15232. /* write the trailer only once! */
  15233. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  15234. }
  15235. function deflateEnd(strm) {
  15236. var status;
  15237. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  15238. return Z_STREAM_ERROR;
  15239. }
  15240. status = strm.state.status;
  15241. if (status !== INIT_STATE &&
  15242. status !== EXTRA_STATE &&
  15243. status !== NAME_STATE &&
  15244. status !== COMMENT_STATE &&
  15245. status !== HCRC_STATE &&
  15246. status !== BUSY_STATE &&
  15247. status !== FINISH_STATE
  15248. ) {
  15249. return err(strm, Z_STREAM_ERROR);
  15250. }
  15251. strm.state = null;
  15252. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  15253. }
  15254. /* =========================================================================
  15255. * Initializes the compression dictionary from the given byte
  15256. * sequence without producing any compressed output.
  15257. */
  15258. function deflateSetDictionary(strm, dictionary) {
  15259. var dictLength = dictionary.length;
  15260. var s;
  15261. var str, n;
  15262. var wrap;
  15263. var avail;
  15264. var next;
  15265. var input;
  15266. var tmpDict;
  15267. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  15268. return Z_STREAM_ERROR;
  15269. }
  15270. s = strm.state;
  15271. wrap = s.wrap;
  15272. if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
  15273. return Z_STREAM_ERROR;
  15274. }
  15275. /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  15276. if (wrap === 1) {
  15277. /* adler32(strm->adler, dictionary, dictLength); */
  15278. strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
  15279. }
  15280. s.wrap = 0; /* avoid computing Adler-32 in read_buf */
  15281. /* if dictionary would fill window, just replace the history */
  15282. if (dictLength >= s.w_size) {
  15283. if (wrap === 0) { /* already empty otherwise */
  15284. /*** CLEAR_HASH(s); ***/
  15285. zero(s.head); // Fill with NIL (= 0);
  15286. s.strstart = 0;
  15287. s.block_start = 0;
  15288. s.insert = 0;
  15289. }
  15290. /* use the tail */
  15291. // dictionary = dictionary.slice(dictLength - s.w_size);
  15292. tmpDict = new utils.Buf8(s.w_size);
  15293. utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
  15294. dictionary = tmpDict;
  15295. dictLength = s.w_size;
  15296. }
  15297. /* insert dictionary into window and hash */
  15298. avail = strm.avail_in;
  15299. next = strm.next_in;
  15300. input = strm.input;
  15301. strm.avail_in = dictLength;
  15302. strm.next_in = 0;
  15303. strm.input = dictionary;
  15304. fill_window(s);
  15305. while (s.lookahead >= MIN_MATCH) {
  15306. str = s.strstart;
  15307. n = s.lookahead - (MIN_MATCH - 1);
  15308. do {
  15309. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  15310. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
  15311. s.prev[str & s.w_mask] = s.head[s.ins_h];
  15312. s.head[s.ins_h] = str;
  15313. str++;
  15314. } while (--n);
  15315. s.strstart = str;
  15316. s.lookahead = MIN_MATCH - 1;
  15317. fill_window(s);
  15318. }
  15319. s.strstart += s.lookahead;
  15320. s.block_start = s.strstart;
  15321. s.insert = s.lookahead;
  15322. s.lookahead = 0;
  15323. s.match_length = s.prev_length = MIN_MATCH - 1;
  15324. s.match_available = 0;
  15325. strm.next_in = next;
  15326. strm.input = input;
  15327. strm.avail_in = avail;
  15328. s.wrap = wrap;
  15329. return Z_OK;
  15330. }
  15331. exports.deflateInit = deflateInit;
  15332. exports.deflateInit2 = deflateInit2;
  15333. exports.deflateReset = deflateReset;
  15334. exports.deflateResetKeep = deflateResetKeep;
  15335. exports.deflateSetHeader = deflateSetHeader;
  15336. exports.deflate = deflate;
  15337. exports.deflateEnd = deflateEnd;
  15338. exports.deflateSetDictionary = deflateSetDictionary;
  15339. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  15340. /* Not implemented
  15341. exports.deflateBound = deflateBound;
  15342. exports.deflateCopy = deflateCopy;
  15343. exports.deflateParams = deflateParams;
  15344. exports.deflatePending = deflatePending;
  15345. exports.deflatePrime = deflatePrime;
  15346. exports.deflateTune = deflateTune;
  15347. */
  15348. },{"../utils/common":53,"./adler32":55,"./crc32":57,"./messages":63,"./trees":64}],59:[function(require,module,exports){
  15349. 'use strict';
  15350. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  15351. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  15352. //
  15353. // This software is provided 'as-is', without any express or implied
  15354. // warranty. In no event will the authors be held liable for any damages
  15355. // arising from the use of this software.
  15356. //
  15357. // Permission is granted to anyone to use this software for any purpose,
  15358. // including commercial applications, and to alter it and redistribute it
  15359. // freely, subject to the following restrictions:
  15360. //
  15361. // 1. The origin of this software must not be misrepresented; you must not
  15362. // claim that you wrote the original software. If you use this software
  15363. // in a product, an acknowledgment in the product documentation would be
  15364. // appreciated but is not required.
  15365. // 2. Altered source versions must be plainly marked as such, and must not be
  15366. // misrepresented as being the original software.
  15367. // 3. This notice may not be removed or altered from any source distribution.
  15368. function GZheader() {
  15369. /* true if compressed data believed to be text */
  15370. this.text = 0;
  15371. /* modification time */
  15372. this.time = 0;
  15373. /* extra flags (not used when writing a gzip file) */
  15374. this.xflags = 0;
  15375. /* operating system */
  15376. this.os = 0;
  15377. /* pointer to extra field or Z_NULL if none */
  15378. this.extra = null;
  15379. /* extra field length (valid if extra != Z_NULL) */
  15380. this.extra_len = 0; // Actually, we don't need it in JS,
  15381. // but leave for few code modifications
  15382. //
  15383. // Setup limits is not necessary because in js we should not preallocate memory
  15384. // for inflate use constant limit in 65536 bytes
  15385. //
  15386. /* space at extra (only when reading header) */
  15387. // this.extra_max = 0;
  15388. /* pointer to zero-terminated file name or Z_NULL */
  15389. this.name = '';
  15390. /* space at name (only when reading header) */
  15391. // this.name_max = 0;
  15392. /* pointer to zero-terminated comment or Z_NULL */
  15393. this.comment = '';
  15394. /* space at comment (only when reading header) */
  15395. // this.comm_max = 0;
  15396. /* true if there was or will be a header crc */
  15397. this.hcrc = 0;
  15398. /* true when done reading gzip header (not used when writing a gzip file) */
  15399. this.done = false;
  15400. }
  15401. module.exports = GZheader;
  15402. },{}],60:[function(require,module,exports){
  15403. 'use strict';
  15404. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  15405. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  15406. //
  15407. // This software is provided 'as-is', without any express or implied
  15408. // warranty. In no event will the authors be held liable for any damages
  15409. // arising from the use of this software.
  15410. //
  15411. // Permission is granted to anyone to use this software for any purpose,
  15412. // including commercial applications, and to alter it and redistribute it
  15413. // freely, subject to the following restrictions:
  15414. //
  15415. // 1. The origin of this software must not be misrepresented; you must not
  15416. // claim that you wrote the original software. If you use this software
  15417. // in a product, an acknowledgment in the product documentation would be
  15418. // appreciated but is not required.
  15419. // 2. Altered source versions must be plainly marked as such, and must not be
  15420. // misrepresented as being the original software.
  15421. // 3. This notice may not be removed or altered from any source distribution.
  15422. // See state defs from inflate.js
  15423. var BAD = 30; /* got a data error -- remain here until reset */
  15424. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  15425. /*
  15426. Decode literal, length, and distance codes and write out the resulting
  15427. literal and match bytes until either not enough input or output is
  15428. available, an end-of-block is encountered, or a data error is encountered.
  15429. When large enough input and output buffers are supplied to inflate(), for
  15430. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  15431. inflate execution time is spent in this routine.
  15432. Entry assumptions:
  15433. state.mode === LEN
  15434. strm.avail_in >= 6
  15435. strm.avail_out >= 258
  15436. start >= strm.avail_out
  15437. state.bits < 8
  15438. On return, state.mode is one of:
  15439. LEN -- ran out of enough output space or enough available input
  15440. TYPE -- reached end of block code, inflate() to interpret next block
  15441. BAD -- error in block data
  15442. Notes:
  15443. - The maximum input bits used by a length/distance pair is 15 bits for the
  15444. length code, 5 bits for the length extra, 15 bits for the distance code,
  15445. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  15446. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  15447. checking for available input while decoding.
  15448. - The maximum bytes that a single length/distance pair can output is 258
  15449. bytes, which is the maximum length that can be coded. inflate_fast()
  15450. requires strm.avail_out >= 258 for each loop to avoid checking for
  15451. output space.
  15452. */
  15453. module.exports = function inflate_fast(strm, start) {
  15454. var state;
  15455. var _in; /* local strm.input */
  15456. var last; /* have enough input while in < last */
  15457. var _out; /* local strm.output */
  15458. var beg; /* inflate()'s initial strm.output */
  15459. var end; /* while out < end, enough space available */
  15460. //#ifdef INFLATE_STRICT
  15461. var dmax; /* maximum distance from zlib header */
  15462. //#endif
  15463. var wsize; /* window size or zero if not using window */
  15464. var whave; /* valid bytes in the window */
  15465. var wnext; /* window write index */
  15466. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  15467. var s_window; /* allocated sliding window, if wsize != 0 */
  15468. var hold; /* local strm.hold */
  15469. var bits; /* local strm.bits */
  15470. var lcode; /* local strm.lencode */
  15471. var dcode; /* local strm.distcode */
  15472. var lmask; /* mask for first level of length codes */
  15473. var dmask; /* mask for first level of distance codes */
  15474. var here; /* retrieved table entry */
  15475. var op; /* code bits, operation, extra bits, or */
  15476. /* window position, window bytes to copy */
  15477. var len; /* match length, unused bytes */
  15478. var dist; /* match distance */
  15479. var from; /* where to copy match from */
  15480. var from_source;
  15481. var input, output; // JS specific, because we have no pointers
  15482. /* copy state to local variables */
  15483. state = strm.state;
  15484. //here = state.here;
  15485. _in = strm.next_in;
  15486. input = strm.input;
  15487. last = _in + (strm.avail_in - 5);
  15488. _out = strm.next_out;
  15489. output = strm.output;
  15490. beg = _out - (start - strm.avail_out);
  15491. end = _out + (strm.avail_out - 257);
  15492. //#ifdef INFLATE_STRICT
  15493. dmax = state.dmax;
  15494. //#endif
  15495. wsize = state.wsize;
  15496. whave = state.whave;
  15497. wnext = state.wnext;
  15498. s_window = state.window;
  15499. hold = state.hold;
  15500. bits = state.bits;
  15501. lcode = state.lencode;
  15502. dcode = state.distcode;
  15503. lmask = (1 << state.lenbits) - 1;
  15504. dmask = (1 << state.distbits) - 1;
  15505. /* decode literals and length/distances until end-of-block or not enough
  15506. input data or output space */
  15507. top:
  15508. do {
  15509. if (bits < 15) {
  15510. hold += input[_in++] << bits;
  15511. bits += 8;
  15512. hold += input[_in++] << bits;
  15513. bits += 8;
  15514. }
  15515. here = lcode[hold & lmask];
  15516. dolen:
  15517. for (;;) { // Goto emulation
  15518. op = here >>> 24/*here.bits*/;
  15519. hold >>>= op;
  15520. bits -= op;
  15521. op = (here >>> 16) & 0xff/*here.op*/;
  15522. if (op === 0) { /* literal */
  15523. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  15524. // "inflate: literal '%c'\n" :
  15525. // "inflate: literal 0x%02x\n", here.val));
  15526. output[_out++] = here & 0xffff/*here.val*/;
  15527. }
  15528. else if (op & 16) { /* length base */
  15529. len = here & 0xffff/*here.val*/;
  15530. op &= 15; /* number of extra bits */
  15531. if (op) {
  15532. if (bits < op) {
  15533. hold += input[_in++] << bits;
  15534. bits += 8;
  15535. }
  15536. len += hold & ((1 << op) - 1);
  15537. hold >>>= op;
  15538. bits -= op;
  15539. }
  15540. //Tracevv((stderr, "inflate: length %u\n", len));
  15541. if (bits < 15) {
  15542. hold += input[_in++] << bits;
  15543. bits += 8;
  15544. hold += input[_in++] << bits;
  15545. bits += 8;
  15546. }
  15547. here = dcode[hold & dmask];
  15548. dodist:
  15549. for (;;) { // goto emulation
  15550. op = here >>> 24/*here.bits*/;
  15551. hold >>>= op;
  15552. bits -= op;
  15553. op = (here >>> 16) & 0xff/*here.op*/;
  15554. if (op & 16) { /* distance base */
  15555. dist = here & 0xffff/*here.val*/;
  15556. op &= 15; /* number of extra bits */
  15557. if (bits < op) {
  15558. hold += input[_in++] << bits;
  15559. bits += 8;
  15560. if (bits < op) {
  15561. hold += input[_in++] << bits;
  15562. bits += 8;
  15563. }
  15564. }
  15565. dist += hold & ((1 << op) - 1);
  15566. //#ifdef INFLATE_STRICT
  15567. if (dist > dmax) {
  15568. strm.msg = 'invalid distance too far back';
  15569. state.mode = BAD;
  15570. break top;
  15571. }
  15572. //#endif
  15573. hold >>>= op;
  15574. bits -= op;
  15575. //Tracevv((stderr, "inflate: distance %u\n", dist));
  15576. op = _out - beg; /* max distance in output */
  15577. if (dist > op) { /* see if copy from window */
  15578. op = dist - op; /* distance back in window */
  15579. if (op > whave) {
  15580. if (state.sane) {
  15581. strm.msg = 'invalid distance too far back';
  15582. state.mode = BAD;
  15583. break top;
  15584. }
  15585. // (!) This block is disabled in zlib defaults,
  15586. // don't enable it for binary compatibility
  15587. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  15588. // if (len <= op - whave) {
  15589. // do {
  15590. // output[_out++] = 0;
  15591. // } while (--len);
  15592. // continue top;
  15593. // }
  15594. // len -= op - whave;
  15595. // do {
  15596. // output[_out++] = 0;
  15597. // } while (--op > whave);
  15598. // if (op === 0) {
  15599. // from = _out - dist;
  15600. // do {
  15601. // output[_out++] = output[from++];
  15602. // } while (--len);
  15603. // continue top;
  15604. // }
  15605. //#endif
  15606. }
  15607. from = 0; // window index
  15608. from_source = s_window;
  15609. if (wnext === 0) { /* very common case */
  15610. from += wsize - op;
  15611. if (op < len) { /* some from window */
  15612. len -= op;
  15613. do {
  15614. output[_out++] = s_window[from++];
  15615. } while (--op);
  15616. from = _out - dist; /* rest from output */
  15617. from_source = output;
  15618. }
  15619. }
  15620. else if (wnext < op) { /* wrap around window */
  15621. from += wsize + wnext - op;
  15622. op -= wnext;
  15623. if (op < len) { /* some from end of window */
  15624. len -= op;
  15625. do {
  15626. output[_out++] = s_window[from++];
  15627. } while (--op);
  15628. from = 0;
  15629. if (wnext < len) { /* some from start of window */
  15630. op = wnext;
  15631. len -= op;
  15632. do {
  15633. output[_out++] = s_window[from++];
  15634. } while (--op);
  15635. from = _out - dist; /* rest from output */
  15636. from_source = output;
  15637. }
  15638. }
  15639. }
  15640. else { /* contiguous in window */
  15641. from += wnext - op;
  15642. if (op < len) { /* some from window */
  15643. len -= op;
  15644. do {
  15645. output[_out++] = s_window[from++];
  15646. } while (--op);
  15647. from = _out - dist; /* rest from output */
  15648. from_source = output;
  15649. }
  15650. }
  15651. while (len > 2) {
  15652. output[_out++] = from_source[from++];
  15653. output[_out++] = from_source[from++];
  15654. output[_out++] = from_source[from++];
  15655. len -= 3;
  15656. }
  15657. if (len) {
  15658. output[_out++] = from_source[from++];
  15659. if (len > 1) {
  15660. output[_out++] = from_source[from++];
  15661. }
  15662. }
  15663. }
  15664. else {
  15665. from = _out - dist; /* copy direct from output */
  15666. do { /* minimum length is three */
  15667. output[_out++] = output[from++];
  15668. output[_out++] = output[from++];
  15669. output[_out++] = output[from++];
  15670. len -= 3;
  15671. } while (len > 2);
  15672. if (len) {
  15673. output[_out++] = output[from++];
  15674. if (len > 1) {
  15675. output[_out++] = output[from++];
  15676. }
  15677. }
  15678. }
  15679. }
  15680. else if ((op & 64) === 0) { /* 2nd level distance code */
  15681. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  15682. continue dodist;
  15683. }
  15684. else {
  15685. strm.msg = 'invalid distance code';
  15686. state.mode = BAD;
  15687. break top;
  15688. }
  15689. break; // need to emulate goto via "continue"
  15690. }
  15691. }
  15692. else if ((op & 64) === 0) { /* 2nd level length code */
  15693. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  15694. continue dolen;
  15695. }
  15696. else if (op & 32) { /* end-of-block */
  15697. //Tracevv((stderr, "inflate: end of block\n"));
  15698. state.mode = TYPE;
  15699. break top;
  15700. }
  15701. else {
  15702. strm.msg = 'invalid literal/length code';
  15703. state.mode = BAD;
  15704. break top;
  15705. }
  15706. break; // need to emulate goto via "continue"
  15707. }
  15708. } while (_in < last && _out < end);
  15709. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  15710. len = bits >> 3;
  15711. _in -= len;
  15712. bits -= len << 3;
  15713. hold &= (1 << bits) - 1;
  15714. /* update state and return */
  15715. strm.next_in = _in;
  15716. strm.next_out = _out;
  15717. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  15718. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  15719. state.hold = hold;
  15720. state.bits = bits;
  15721. return;
  15722. };
  15723. },{}],61:[function(require,module,exports){
  15724. 'use strict';
  15725. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  15726. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  15727. //
  15728. // This software is provided 'as-is', without any express or implied
  15729. // warranty. In no event will the authors be held liable for any damages
  15730. // arising from the use of this software.
  15731. //
  15732. // Permission is granted to anyone to use this software for any purpose,
  15733. // including commercial applications, and to alter it and redistribute it
  15734. // freely, subject to the following restrictions:
  15735. //
  15736. // 1. The origin of this software must not be misrepresented; you must not
  15737. // claim that you wrote the original software. If you use this software
  15738. // in a product, an acknowledgment in the product documentation would be
  15739. // appreciated but is not required.
  15740. // 2. Altered source versions must be plainly marked as such, and must not be
  15741. // misrepresented as being the original software.
  15742. // 3. This notice may not be removed or altered from any source distribution.
  15743. var utils = require('../utils/common');
  15744. var adler32 = require('./adler32');
  15745. var crc32 = require('./crc32');
  15746. var inflate_fast = require('./inffast');
  15747. var inflate_table = require('./inftrees');
  15748. var CODES = 0;
  15749. var LENS = 1;
  15750. var DISTS = 2;
  15751. /* Public constants ==========================================================*/
  15752. /* ===========================================================================*/
  15753. /* Allowed flush values; see deflate() and inflate() below for details */
  15754. //var Z_NO_FLUSH = 0;
  15755. //var Z_PARTIAL_FLUSH = 1;
  15756. //var Z_SYNC_FLUSH = 2;
  15757. //var Z_FULL_FLUSH = 3;
  15758. var Z_FINISH = 4;
  15759. var Z_BLOCK = 5;
  15760. var Z_TREES = 6;
  15761. /* Return codes for the compression/decompression functions. Negative values
  15762. * are errors, positive values are used for special but normal events.
  15763. */
  15764. var Z_OK = 0;
  15765. var Z_STREAM_END = 1;
  15766. var Z_NEED_DICT = 2;
  15767. //var Z_ERRNO = -1;
  15768. var Z_STREAM_ERROR = -2;
  15769. var Z_DATA_ERROR = -3;
  15770. var Z_MEM_ERROR = -4;
  15771. var Z_BUF_ERROR = -5;
  15772. //var Z_VERSION_ERROR = -6;
  15773. /* The deflate compression method */
  15774. var Z_DEFLATED = 8;
  15775. /* STATES ====================================================================*/
  15776. /* ===========================================================================*/
  15777. var HEAD = 1; /* i: waiting for magic header */
  15778. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  15779. var TIME = 3; /* i: waiting for modification time (gzip) */
  15780. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  15781. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  15782. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  15783. var NAME = 7; /* i: waiting for end of file name (gzip) */
  15784. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  15785. var HCRC = 9; /* i: waiting for header crc (gzip) */
  15786. var DICTID = 10; /* i: waiting for dictionary check value */
  15787. var DICT = 11; /* waiting for inflateSetDictionary() call */
  15788. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  15789. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  15790. var STORED = 14; /* i: waiting for stored size (length and complement) */
  15791. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  15792. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  15793. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  15794. var LENLENS = 18; /* i: waiting for code length code lengths */
  15795. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  15796. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  15797. var LEN = 21; /* i: waiting for length/lit/eob code */
  15798. var LENEXT = 22; /* i: waiting for length extra bits */
  15799. var DIST = 23; /* i: waiting for distance code */
  15800. var DISTEXT = 24; /* i: waiting for distance extra bits */
  15801. var MATCH = 25; /* o: waiting for output space to copy string */
  15802. var LIT = 26; /* o: waiting for output space to write literal */
  15803. var CHECK = 27; /* i: waiting for 32-bit check value */
  15804. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  15805. var DONE = 29; /* finished check, done -- remain here until reset */
  15806. var BAD = 30; /* got a data error -- remain here until reset */
  15807. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  15808. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  15809. /* ===========================================================================*/
  15810. var ENOUGH_LENS = 852;
  15811. var ENOUGH_DISTS = 592;
  15812. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  15813. var MAX_WBITS = 15;
  15814. /* 32K LZ77 window */
  15815. var DEF_WBITS = MAX_WBITS;
  15816. function zswap32(q) {
  15817. return (((q >>> 24) & 0xff) +
  15818. ((q >>> 8) & 0xff00) +
  15819. ((q & 0xff00) << 8) +
  15820. ((q & 0xff) << 24));
  15821. }
  15822. function InflateState() {
  15823. this.mode = 0; /* current inflate mode */
  15824. this.last = false; /* true if processing last block */
  15825. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  15826. this.havedict = false; /* true if dictionary provided */
  15827. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  15828. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  15829. this.check = 0; /* protected copy of check value */
  15830. this.total = 0; /* protected copy of output count */
  15831. // TODO: may be {}
  15832. this.head = null; /* where to save gzip header information */
  15833. /* sliding window */
  15834. this.wbits = 0; /* log base 2 of requested window size */
  15835. this.wsize = 0; /* window size or zero if not using window */
  15836. this.whave = 0; /* valid bytes in the window */
  15837. this.wnext = 0; /* window write index */
  15838. this.window = null; /* allocated sliding window, if needed */
  15839. /* bit accumulator */
  15840. this.hold = 0; /* input bit accumulator */
  15841. this.bits = 0; /* number of bits in "in" */
  15842. /* for string and stored block copying */
  15843. this.length = 0; /* literal or length of data to copy */
  15844. this.offset = 0; /* distance back to copy string from */
  15845. /* for table and code decoding */
  15846. this.extra = 0; /* extra bits needed */
  15847. /* fixed and dynamic code tables */
  15848. this.lencode = null; /* starting table for length/literal codes */
  15849. this.distcode = null; /* starting table for distance codes */
  15850. this.lenbits = 0; /* index bits for lencode */
  15851. this.distbits = 0; /* index bits for distcode */
  15852. /* dynamic table building */
  15853. this.ncode = 0; /* number of code length code lengths */
  15854. this.nlen = 0; /* number of length code lengths */
  15855. this.ndist = 0; /* number of distance code lengths */
  15856. this.have = 0; /* number of code lengths in lens[] */
  15857. this.next = null; /* next available space in codes[] */
  15858. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  15859. this.work = new utils.Buf16(288); /* work area for code table building */
  15860. /*
  15861. because we don't have pointers in js, we use lencode and distcode directly
  15862. as buffers so we don't need codes
  15863. */
  15864. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  15865. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  15866. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  15867. this.sane = 0; /* if false, allow invalid distance too far */
  15868. this.back = 0; /* bits back of last unprocessed length/lit */
  15869. this.was = 0; /* initial length of match */
  15870. }
  15871. function inflateResetKeep(strm) {
  15872. var state;
  15873. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15874. state = strm.state;
  15875. strm.total_in = strm.total_out = state.total = 0;
  15876. strm.msg = ''; /*Z_NULL*/
  15877. if (state.wrap) { /* to support ill-conceived Java test suite */
  15878. strm.adler = state.wrap & 1;
  15879. }
  15880. state.mode = HEAD;
  15881. state.last = 0;
  15882. state.havedict = 0;
  15883. state.dmax = 32768;
  15884. state.head = null/*Z_NULL*/;
  15885. state.hold = 0;
  15886. state.bits = 0;
  15887. //state.lencode = state.distcode = state.next = state.codes;
  15888. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  15889. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  15890. state.sane = 1;
  15891. state.back = -1;
  15892. //Tracev((stderr, "inflate: reset\n"));
  15893. return Z_OK;
  15894. }
  15895. function inflateReset(strm) {
  15896. var state;
  15897. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15898. state = strm.state;
  15899. state.wsize = 0;
  15900. state.whave = 0;
  15901. state.wnext = 0;
  15902. return inflateResetKeep(strm);
  15903. }
  15904. function inflateReset2(strm, windowBits) {
  15905. var wrap;
  15906. var state;
  15907. /* get the state */
  15908. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  15909. state = strm.state;
  15910. /* extract wrap request from windowBits parameter */
  15911. if (windowBits < 0) {
  15912. wrap = 0;
  15913. windowBits = -windowBits;
  15914. }
  15915. else {
  15916. wrap = (windowBits >> 4) + 1;
  15917. if (windowBits < 48) {
  15918. windowBits &= 15;
  15919. }
  15920. }
  15921. /* set number of window bits, free window if different */
  15922. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  15923. return Z_STREAM_ERROR;
  15924. }
  15925. if (state.window !== null && state.wbits !== windowBits) {
  15926. state.window = null;
  15927. }
  15928. /* update state and reset the rest of it */
  15929. state.wrap = wrap;
  15930. state.wbits = windowBits;
  15931. return inflateReset(strm);
  15932. }
  15933. function inflateInit2(strm, windowBits) {
  15934. var ret;
  15935. var state;
  15936. if (!strm) { return Z_STREAM_ERROR; }
  15937. //strm.msg = Z_NULL; /* in case we return an error */
  15938. state = new InflateState();
  15939. //if (state === Z_NULL) return Z_MEM_ERROR;
  15940. //Tracev((stderr, "inflate: allocated\n"));
  15941. strm.state = state;
  15942. state.window = null/*Z_NULL*/;
  15943. ret = inflateReset2(strm, windowBits);
  15944. if (ret !== Z_OK) {
  15945. strm.state = null/*Z_NULL*/;
  15946. }
  15947. return ret;
  15948. }
  15949. function inflateInit(strm) {
  15950. return inflateInit2(strm, DEF_WBITS);
  15951. }
  15952. /*
  15953. Return state with length and distance decoding tables and index sizes set to
  15954. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  15955. If BUILDFIXED is defined, then instead this routine builds the tables the
  15956. first time it's called, and returns those tables the first time and
  15957. thereafter. This reduces the size of the code by about 2K bytes, in
  15958. exchange for a little execution time. However, BUILDFIXED should not be
  15959. used for threaded applications, since the rewriting of the tables and virgin
  15960. may not be thread-safe.
  15961. */
  15962. var virgin = true;
  15963. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  15964. function fixedtables(state) {
  15965. /* build fixed huffman tables if first call (may not be thread safe) */
  15966. if (virgin) {
  15967. var sym;
  15968. lenfix = new utils.Buf32(512);
  15969. distfix = new utils.Buf32(32);
  15970. /* literal/length table */
  15971. sym = 0;
  15972. while (sym < 144) { state.lens[sym++] = 8; }
  15973. while (sym < 256) { state.lens[sym++] = 9; }
  15974. while (sym < 280) { state.lens[sym++] = 7; }
  15975. while (sym < 288) { state.lens[sym++] = 8; }
  15976. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
  15977. /* distance table */
  15978. sym = 0;
  15979. while (sym < 32) { state.lens[sym++] = 5; }
  15980. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
  15981. /* do this just once */
  15982. virgin = false;
  15983. }
  15984. state.lencode = lenfix;
  15985. state.lenbits = 9;
  15986. state.distcode = distfix;
  15987. state.distbits = 5;
  15988. }
  15989. /*
  15990. Update the window with the last wsize (normally 32K) bytes written before
  15991. returning. If window does not exist yet, create it. This is only called
  15992. when a window is already in use, or when output has been written during this
  15993. inflate call, but the end of the deflate stream has not been reached yet.
  15994. It is also called to create a window for dictionary data when a dictionary
  15995. is loaded.
  15996. Providing output buffers larger than 32K to inflate() should provide a speed
  15997. advantage, since only the last 32K of output is copied to the sliding window
  15998. upon return from inflate(), and since all distances after the first 32K of
  15999. output will fall in the output data, making match copies simpler and faster.
  16000. The advantage may be dependent on the size of the processor's data caches.
  16001. */
  16002. function updatewindow(strm, src, end, copy) {
  16003. var dist;
  16004. var state = strm.state;
  16005. /* if it hasn't been done already, allocate space for the window */
  16006. if (state.window === null) {
  16007. state.wsize = 1 << state.wbits;
  16008. state.wnext = 0;
  16009. state.whave = 0;
  16010. state.window = new utils.Buf8(state.wsize);
  16011. }
  16012. /* copy state->wsize or less output bytes into the circular window */
  16013. if (copy >= state.wsize) {
  16014. utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
  16015. state.wnext = 0;
  16016. state.whave = state.wsize;
  16017. }
  16018. else {
  16019. dist = state.wsize - state.wnext;
  16020. if (dist > copy) {
  16021. dist = copy;
  16022. }
  16023. //zmemcpy(state->window + state->wnext, end - copy, dist);
  16024. utils.arraySet(state.window, src, end - copy, dist, state.wnext);
  16025. copy -= dist;
  16026. if (copy) {
  16027. //zmemcpy(state->window, end - copy, copy);
  16028. utils.arraySet(state.window, src, end - copy, copy, 0);
  16029. state.wnext = copy;
  16030. state.whave = state.wsize;
  16031. }
  16032. else {
  16033. state.wnext += dist;
  16034. if (state.wnext === state.wsize) { state.wnext = 0; }
  16035. if (state.whave < state.wsize) { state.whave += dist; }
  16036. }
  16037. }
  16038. return 0;
  16039. }
  16040. function inflate(strm, flush) {
  16041. var state;
  16042. var input, output; // input/output buffers
  16043. var next; /* next input INDEX */
  16044. var put; /* next output INDEX */
  16045. var have, left; /* available input and output */
  16046. var hold; /* bit buffer */
  16047. var bits; /* bits in bit buffer */
  16048. var _in, _out; /* save starting available input and output */
  16049. var copy; /* number of stored or match bytes to copy */
  16050. var from; /* where to copy match bytes from */
  16051. var from_source;
  16052. var here = 0; /* current decoding table entry */
  16053. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  16054. //var last; /* parent table entry */
  16055. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  16056. var len; /* length to copy for repeats, bits to drop */
  16057. var ret; /* return code */
  16058. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  16059. var opts;
  16060. var n; // temporary var for NEED_BITS
  16061. var order = /* permutation of code lengths */
  16062. [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
  16063. if (!strm || !strm.state || !strm.output ||
  16064. (!strm.input && strm.avail_in !== 0)) {
  16065. return Z_STREAM_ERROR;
  16066. }
  16067. state = strm.state;
  16068. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  16069. //--- LOAD() ---
  16070. put = strm.next_out;
  16071. output = strm.output;
  16072. left = strm.avail_out;
  16073. next = strm.next_in;
  16074. input = strm.input;
  16075. have = strm.avail_in;
  16076. hold = state.hold;
  16077. bits = state.bits;
  16078. //---
  16079. _in = have;
  16080. _out = left;
  16081. ret = Z_OK;
  16082. inf_leave: // goto emulation
  16083. for (;;) {
  16084. switch (state.mode) {
  16085. case HEAD:
  16086. if (state.wrap === 0) {
  16087. state.mode = TYPEDO;
  16088. break;
  16089. }
  16090. //=== NEEDBITS(16);
  16091. while (bits < 16) {
  16092. if (have === 0) { break inf_leave; }
  16093. have--;
  16094. hold += input[next++] << bits;
  16095. bits += 8;
  16096. }
  16097. //===//
  16098. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  16099. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  16100. //=== CRC2(state.check, hold);
  16101. hbuf[0] = hold & 0xff;
  16102. hbuf[1] = (hold >>> 8) & 0xff;
  16103. state.check = crc32(state.check, hbuf, 2, 0);
  16104. //===//
  16105. //=== INITBITS();
  16106. hold = 0;
  16107. bits = 0;
  16108. //===//
  16109. state.mode = FLAGS;
  16110. break;
  16111. }
  16112. state.flags = 0; /* expect zlib header */
  16113. if (state.head) {
  16114. state.head.done = false;
  16115. }
  16116. if (!(state.wrap & 1) || /* check if zlib header allowed */
  16117. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  16118. strm.msg = 'incorrect header check';
  16119. state.mode = BAD;
  16120. break;
  16121. }
  16122. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  16123. strm.msg = 'unknown compression method';
  16124. state.mode = BAD;
  16125. break;
  16126. }
  16127. //--- DROPBITS(4) ---//
  16128. hold >>>= 4;
  16129. bits -= 4;
  16130. //---//
  16131. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  16132. if (state.wbits === 0) {
  16133. state.wbits = len;
  16134. }
  16135. else if (len > state.wbits) {
  16136. strm.msg = 'invalid window size';
  16137. state.mode = BAD;
  16138. break;
  16139. }
  16140. state.dmax = 1 << len;
  16141. //Tracev((stderr, "inflate: zlib header ok\n"));
  16142. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  16143. state.mode = hold & 0x200 ? DICTID : TYPE;
  16144. //=== INITBITS();
  16145. hold = 0;
  16146. bits = 0;
  16147. //===//
  16148. break;
  16149. case FLAGS:
  16150. //=== NEEDBITS(16); */
  16151. while (bits < 16) {
  16152. if (have === 0) { break inf_leave; }
  16153. have--;
  16154. hold += input[next++] << bits;
  16155. bits += 8;
  16156. }
  16157. //===//
  16158. state.flags = hold;
  16159. if ((state.flags & 0xff) !== Z_DEFLATED) {
  16160. strm.msg = 'unknown compression method';
  16161. state.mode = BAD;
  16162. break;
  16163. }
  16164. if (state.flags & 0xe000) {
  16165. strm.msg = 'unknown header flags set';
  16166. state.mode = BAD;
  16167. break;
  16168. }
  16169. if (state.head) {
  16170. state.head.text = ((hold >> 8) & 1);
  16171. }
  16172. if (state.flags & 0x0200) {
  16173. //=== CRC2(state.check, hold);
  16174. hbuf[0] = hold & 0xff;
  16175. hbuf[1] = (hold >>> 8) & 0xff;
  16176. state.check = crc32(state.check, hbuf, 2, 0);
  16177. //===//
  16178. }
  16179. //=== INITBITS();
  16180. hold = 0;
  16181. bits = 0;
  16182. //===//
  16183. state.mode = TIME;
  16184. /* falls through */
  16185. case TIME:
  16186. //=== NEEDBITS(32); */
  16187. while (bits < 32) {
  16188. if (have === 0) { break inf_leave; }
  16189. have--;
  16190. hold += input[next++] << bits;
  16191. bits += 8;
  16192. }
  16193. //===//
  16194. if (state.head) {
  16195. state.head.time = hold;
  16196. }
  16197. if (state.flags & 0x0200) {
  16198. //=== CRC4(state.check, hold)
  16199. hbuf[0] = hold & 0xff;
  16200. hbuf[1] = (hold >>> 8) & 0xff;
  16201. hbuf[2] = (hold >>> 16) & 0xff;
  16202. hbuf[3] = (hold >>> 24) & 0xff;
  16203. state.check = crc32(state.check, hbuf, 4, 0);
  16204. //===
  16205. }
  16206. //=== INITBITS();
  16207. hold = 0;
  16208. bits = 0;
  16209. //===//
  16210. state.mode = OS;
  16211. /* falls through */
  16212. case OS:
  16213. //=== NEEDBITS(16); */
  16214. while (bits < 16) {
  16215. if (have === 0) { break inf_leave; }
  16216. have--;
  16217. hold += input[next++] << bits;
  16218. bits += 8;
  16219. }
  16220. //===//
  16221. if (state.head) {
  16222. state.head.xflags = (hold & 0xff);
  16223. state.head.os = (hold >> 8);
  16224. }
  16225. if (state.flags & 0x0200) {
  16226. //=== CRC2(state.check, hold);
  16227. hbuf[0] = hold & 0xff;
  16228. hbuf[1] = (hold >>> 8) & 0xff;
  16229. state.check = crc32(state.check, hbuf, 2, 0);
  16230. //===//
  16231. }
  16232. //=== INITBITS();
  16233. hold = 0;
  16234. bits = 0;
  16235. //===//
  16236. state.mode = EXLEN;
  16237. /* falls through */
  16238. case EXLEN:
  16239. if (state.flags & 0x0400) {
  16240. //=== NEEDBITS(16); */
  16241. while (bits < 16) {
  16242. if (have === 0) { break inf_leave; }
  16243. have--;
  16244. hold += input[next++] << bits;
  16245. bits += 8;
  16246. }
  16247. //===//
  16248. state.length = hold;
  16249. if (state.head) {
  16250. state.head.extra_len = hold;
  16251. }
  16252. if (state.flags & 0x0200) {
  16253. //=== CRC2(state.check, hold);
  16254. hbuf[0] = hold & 0xff;
  16255. hbuf[1] = (hold >>> 8) & 0xff;
  16256. state.check = crc32(state.check, hbuf, 2, 0);
  16257. //===//
  16258. }
  16259. //=== INITBITS();
  16260. hold = 0;
  16261. bits = 0;
  16262. //===//
  16263. }
  16264. else if (state.head) {
  16265. state.head.extra = null/*Z_NULL*/;
  16266. }
  16267. state.mode = EXTRA;
  16268. /* falls through */
  16269. case EXTRA:
  16270. if (state.flags & 0x0400) {
  16271. copy = state.length;
  16272. if (copy > have) { copy = have; }
  16273. if (copy) {
  16274. if (state.head) {
  16275. len = state.head.extra_len - state.length;
  16276. if (!state.head.extra) {
  16277. // Use untyped array for more convenient processing later
  16278. state.head.extra = new Array(state.head.extra_len);
  16279. }
  16280. utils.arraySet(
  16281. state.head.extra,
  16282. input,
  16283. next,
  16284. // extra field is limited to 65536 bytes
  16285. // - no need for additional size check
  16286. copy,
  16287. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  16288. len
  16289. );
  16290. //zmemcpy(state.head.extra + len, next,
  16291. // len + copy > state.head.extra_max ?
  16292. // state.head.extra_max - len : copy);
  16293. }
  16294. if (state.flags & 0x0200) {
  16295. state.check = crc32(state.check, input, copy, next);
  16296. }
  16297. have -= copy;
  16298. next += copy;
  16299. state.length -= copy;
  16300. }
  16301. if (state.length) { break inf_leave; }
  16302. }
  16303. state.length = 0;
  16304. state.mode = NAME;
  16305. /* falls through */
  16306. case NAME:
  16307. if (state.flags & 0x0800) {
  16308. if (have === 0) { break inf_leave; }
  16309. copy = 0;
  16310. do {
  16311. // TODO: 2 or 1 bytes?
  16312. len = input[next + copy++];
  16313. /* use constant limit because in js we should not preallocate memory */
  16314. if (state.head && len &&
  16315. (state.length < 65536 /*state.head.name_max*/)) {
  16316. state.head.name += String.fromCharCode(len);
  16317. }
  16318. } while (len && copy < have);
  16319. if (state.flags & 0x0200) {
  16320. state.check = crc32(state.check, input, copy, next);
  16321. }
  16322. have -= copy;
  16323. next += copy;
  16324. if (len) { break inf_leave; }
  16325. }
  16326. else if (state.head) {
  16327. state.head.name = null;
  16328. }
  16329. state.length = 0;
  16330. state.mode = COMMENT;
  16331. /* falls through */
  16332. case COMMENT:
  16333. if (state.flags & 0x1000) {
  16334. if (have === 0) { break inf_leave; }
  16335. copy = 0;
  16336. do {
  16337. len = input[next + copy++];
  16338. /* use constant limit because in js we should not preallocate memory */
  16339. if (state.head && len &&
  16340. (state.length < 65536 /*state.head.comm_max*/)) {
  16341. state.head.comment += String.fromCharCode(len);
  16342. }
  16343. } while (len && copy < have);
  16344. if (state.flags & 0x0200) {
  16345. state.check = crc32(state.check, input, copy, next);
  16346. }
  16347. have -= copy;
  16348. next += copy;
  16349. if (len) { break inf_leave; }
  16350. }
  16351. else if (state.head) {
  16352. state.head.comment = null;
  16353. }
  16354. state.mode = HCRC;
  16355. /* falls through */
  16356. case HCRC:
  16357. if (state.flags & 0x0200) {
  16358. //=== NEEDBITS(16); */
  16359. while (bits < 16) {
  16360. if (have === 0) { break inf_leave; }
  16361. have--;
  16362. hold += input[next++] << bits;
  16363. bits += 8;
  16364. }
  16365. //===//
  16366. if (hold !== (state.check & 0xffff)) {
  16367. strm.msg = 'header crc mismatch';
  16368. state.mode = BAD;
  16369. break;
  16370. }
  16371. //=== INITBITS();
  16372. hold = 0;
  16373. bits = 0;
  16374. //===//
  16375. }
  16376. if (state.head) {
  16377. state.head.hcrc = ((state.flags >> 9) & 1);
  16378. state.head.done = true;
  16379. }
  16380. strm.adler = state.check = 0;
  16381. state.mode = TYPE;
  16382. break;
  16383. case DICTID:
  16384. //=== NEEDBITS(32); */
  16385. while (bits < 32) {
  16386. if (have === 0) { break inf_leave; }
  16387. have--;
  16388. hold += input[next++] << bits;
  16389. bits += 8;
  16390. }
  16391. //===//
  16392. strm.adler = state.check = zswap32(hold);
  16393. //=== INITBITS();
  16394. hold = 0;
  16395. bits = 0;
  16396. //===//
  16397. state.mode = DICT;
  16398. /* falls through */
  16399. case DICT:
  16400. if (state.havedict === 0) {
  16401. //--- RESTORE() ---
  16402. strm.next_out = put;
  16403. strm.avail_out = left;
  16404. strm.next_in = next;
  16405. strm.avail_in = have;
  16406. state.hold = hold;
  16407. state.bits = bits;
  16408. //---
  16409. return Z_NEED_DICT;
  16410. }
  16411. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  16412. state.mode = TYPE;
  16413. /* falls through */
  16414. case TYPE:
  16415. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  16416. /* falls through */
  16417. case TYPEDO:
  16418. if (state.last) {
  16419. //--- BYTEBITS() ---//
  16420. hold >>>= bits & 7;
  16421. bits -= bits & 7;
  16422. //---//
  16423. state.mode = CHECK;
  16424. break;
  16425. }
  16426. //=== NEEDBITS(3); */
  16427. while (bits < 3) {
  16428. if (have === 0) { break inf_leave; }
  16429. have--;
  16430. hold += input[next++] << bits;
  16431. bits += 8;
  16432. }
  16433. //===//
  16434. state.last = (hold & 0x01)/*BITS(1)*/;
  16435. //--- DROPBITS(1) ---//
  16436. hold >>>= 1;
  16437. bits -= 1;
  16438. //---//
  16439. switch ((hold & 0x03)/*BITS(2)*/) {
  16440. case 0: /* stored block */
  16441. //Tracev((stderr, "inflate: stored block%s\n",
  16442. // state.last ? " (last)" : ""));
  16443. state.mode = STORED;
  16444. break;
  16445. case 1: /* fixed block */
  16446. fixedtables(state);
  16447. //Tracev((stderr, "inflate: fixed codes block%s\n",
  16448. // state.last ? " (last)" : ""));
  16449. state.mode = LEN_; /* decode codes */
  16450. if (flush === Z_TREES) {
  16451. //--- DROPBITS(2) ---//
  16452. hold >>>= 2;
  16453. bits -= 2;
  16454. //---//
  16455. break inf_leave;
  16456. }
  16457. break;
  16458. case 2: /* dynamic block */
  16459. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  16460. // state.last ? " (last)" : ""));
  16461. state.mode = TABLE;
  16462. break;
  16463. case 3:
  16464. strm.msg = 'invalid block type';
  16465. state.mode = BAD;
  16466. }
  16467. //--- DROPBITS(2) ---//
  16468. hold >>>= 2;
  16469. bits -= 2;
  16470. //---//
  16471. break;
  16472. case STORED:
  16473. //--- BYTEBITS() ---// /* go to byte boundary */
  16474. hold >>>= bits & 7;
  16475. bits -= bits & 7;
  16476. //---//
  16477. //=== NEEDBITS(32); */
  16478. while (bits < 32) {
  16479. if (have === 0) { break inf_leave; }
  16480. have--;
  16481. hold += input[next++] << bits;
  16482. bits += 8;
  16483. }
  16484. //===//
  16485. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  16486. strm.msg = 'invalid stored block lengths';
  16487. state.mode = BAD;
  16488. break;
  16489. }
  16490. state.length = hold & 0xffff;
  16491. //Tracev((stderr, "inflate: stored length %u\n",
  16492. // state.length));
  16493. //=== INITBITS();
  16494. hold = 0;
  16495. bits = 0;
  16496. //===//
  16497. state.mode = COPY_;
  16498. if (flush === Z_TREES) { break inf_leave; }
  16499. /* falls through */
  16500. case COPY_:
  16501. state.mode = COPY;
  16502. /* falls through */
  16503. case COPY:
  16504. copy = state.length;
  16505. if (copy) {
  16506. if (copy > have) { copy = have; }
  16507. if (copy > left) { copy = left; }
  16508. if (copy === 0) { break inf_leave; }
  16509. //--- zmemcpy(put, next, copy); ---
  16510. utils.arraySet(output, input, next, copy, put);
  16511. //---//
  16512. have -= copy;
  16513. next += copy;
  16514. left -= copy;
  16515. put += copy;
  16516. state.length -= copy;
  16517. break;
  16518. }
  16519. //Tracev((stderr, "inflate: stored end\n"));
  16520. state.mode = TYPE;
  16521. break;
  16522. case TABLE:
  16523. //=== NEEDBITS(14); */
  16524. while (bits < 14) {
  16525. if (have === 0) { break inf_leave; }
  16526. have--;
  16527. hold += input[next++] << bits;
  16528. bits += 8;
  16529. }
  16530. //===//
  16531. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  16532. //--- DROPBITS(5) ---//
  16533. hold >>>= 5;
  16534. bits -= 5;
  16535. //---//
  16536. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  16537. //--- DROPBITS(5) ---//
  16538. hold >>>= 5;
  16539. bits -= 5;
  16540. //---//
  16541. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  16542. //--- DROPBITS(4) ---//
  16543. hold >>>= 4;
  16544. bits -= 4;
  16545. //---//
  16546. //#ifndef PKZIP_BUG_WORKAROUND
  16547. if (state.nlen > 286 || state.ndist > 30) {
  16548. strm.msg = 'too many length or distance symbols';
  16549. state.mode = BAD;
  16550. break;
  16551. }
  16552. //#endif
  16553. //Tracev((stderr, "inflate: table sizes ok\n"));
  16554. state.have = 0;
  16555. state.mode = LENLENS;
  16556. /* falls through */
  16557. case LENLENS:
  16558. while (state.have < state.ncode) {
  16559. //=== NEEDBITS(3);
  16560. while (bits < 3) {
  16561. if (have === 0) { break inf_leave; }
  16562. have--;
  16563. hold += input[next++] << bits;
  16564. bits += 8;
  16565. }
  16566. //===//
  16567. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  16568. //--- DROPBITS(3) ---//
  16569. hold >>>= 3;
  16570. bits -= 3;
  16571. //---//
  16572. }
  16573. while (state.have < 19) {
  16574. state.lens[order[state.have++]] = 0;
  16575. }
  16576. // We have separate tables & no pointers. 2 commented lines below not needed.
  16577. //state.next = state.codes;
  16578. //state.lencode = state.next;
  16579. // Switch to use dynamic table
  16580. state.lencode = state.lendyn;
  16581. state.lenbits = 7;
  16582. opts = { bits: state.lenbits };
  16583. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  16584. state.lenbits = opts.bits;
  16585. if (ret) {
  16586. strm.msg = 'invalid code lengths set';
  16587. state.mode = BAD;
  16588. break;
  16589. }
  16590. //Tracev((stderr, "inflate: code lengths ok\n"));
  16591. state.have = 0;
  16592. state.mode = CODELENS;
  16593. /* falls through */
  16594. case CODELENS:
  16595. while (state.have < state.nlen + state.ndist) {
  16596. for (;;) {
  16597. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  16598. here_bits = here >>> 24;
  16599. here_op = (here >>> 16) & 0xff;
  16600. here_val = here & 0xffff;
  16601. if ((here_bits) <= bits) { break; }
  16602. //--- PULLBYTE() ---//
  16603. if (have === 0) { break inf_leave; }
  16604. have--;
  16605. hold += input[next++] << bits;
  16606. bits += 8;
  16607. //---//
  16608. }
  16609. if (here_val < 16) {
  16610. //--- DROPBITS(here.bits) ---//
  16611. hold >>>= here_bits;
  16612. bits -= here_bits;
  16613. //---//
  16614. state.lens[state.have++] = here_val;
  16615. }
  16616. else {
  16617. if (here_val === 16) {
  16618. //=== NEEDBITS(here.bits + 2);
  16619. n = here_bits + 2;
  16620. while (bits < n) {
  16621. if (have === 0) { break inf_leave; }
  16622. have--;
  16623. hold += input[next++] << bits;
  16624. bits += 8;
  16625. }
  16626. //===//
  16627. //--- DROPBITS(here.bits) ---//
  16628. hold >>>= here_bits;
  16629. bits -= here_bits;
  16630. //---//
  16631. if (state.have === 0) {
  16632. strm.msg = 'invalid bit length repeat';
  16633. state.mode = BAD;
  16634. break;
  16635. }
  16636. len = state.lens[state.have - 1];
  16637. copy = 3 + (hold & 0x03);//BITS(2);
  16638. //--- DROPBITS(2) ---//
  16639. hold >>>= 2;
  16640. bits -= 2;
  16641. //---//
  16642. }
  16643. else if (here_val === 17) {
  16644. //=== NEEDBITS(here.bits + 3);
  16645. n = here_bits + 3;
  16646. while (bits < n) {
  16647. if (have === 0) { break inf_leave; }
  16648. have--;
  16649. hold += input[next++] << bits;
  16650. bits += 8;
  16651. }
  16652. //===//
  16653. //--- DROPBITS(here.bits) ---//
  16654. hold >>>= here_bits;
  16655. bits -= here_bits;
  16656. //---//
  16657. len = 0;
  16658. copy = 3 + (hold & 0x07);//BITS(3);
  16659. //--- DROPBITS(3) ---//
  16660. hold >>>= 3;
  16661. bits -= 3;
  16662. //---//
  16663. }
  16664. else {
  16665. //=== NEEDBITS(here.bits + 7);
  16666. n = here_bits + 7;
  16667. while (bits < n) {
  16668. if (have === 0) { break inf_leave; }
  16669. have--;
  16670. hold += input[next++] << bits;
  16671. bits += 8;
  16672. }
  16673. //===//
  16674. //--- DROPBITS(here.bits) ---//
  16675. hold >>>= here_bits;
  16676. bits -= here_bits;
  16677. //---//
  16678. len = 0;
  16679. copy = 11 + (hold & 0x7f);//BITS(7);
  16680. //--- DROPBITS(7) ---//
  16681. hold >>>= 7;
  16682. bits -= 7;
  16683. //---//
  16684. }
  16685. if (state.have + copy > state.nlen + state.ndist) {
  16686. strm.msg = 'invalid bit length repeat';
  16687. state.mode = BAD;
  16688. break;
  16689. }
  16690. while (copy--) {
  16691. state.lens[state.have++] = len;
  16692. }
  16693. }
  16694. }
  16695. /* handle error breaks in while */
  16696. if (state.mode === BAD) { break; }
  16697. /* check for end-of-block code (better have one) */
  16698. if (state.lens[256] === 0) {
  16699. strm.msg = 'invalid code -- missing end-of-block';
  16700. state.mode = BAD;
  16701. break;
  16702. }
  16703. /* build code tables -- note: do not change the lenbits or distbits
  16704. values here (9 and 6) without reading the comments in inftrees.h
  16705. concerning the ENOUGH constants, which depend on those values */
  16706. state.lenbits = 9;
  16707. opts = { bits: state.lenbits };
  16708. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  16709. // We have separate tables & no pointers. 2 commented lines below not needed.
  16710. // state.next_index = opts.table_index;
  16711. state.lenbits = opts.bits;
  16712. // state.lencode = state.next;
  16713. if (ret) {
  16714. strm.msg = 'invalid literal/lengths set';
  16715. state.mode = BAD;
  16716. break;
  16717. }
  16718. state.distbits = 6;
  16719. //state.distcode.copy(state.codes);
  16720. // Switch to use dynamic table
  16721. state.distcode = state.distdyn;
  16722. opts = { bits: state.distbits };
  16723. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  16724. // We have separate tables & no pointers. 2 commented lines below not needed.
  16725. // state.next_index = opts.table_index;
  16726. state.distbits = opts.bits;
  16727. // state.distcode = state.next;
  16728. if (ret) {
  16729. strm.msg = 'invalid distances set';
  16730. state.mode = BAD;
  16731. break;
  16732. }
  16733. //Tracev((stderr, 'inflate: codes ok\n'));
  16734. state.mode = LEN_;
  16735. if (flush === Z_TREES) { break inf_leave; }
  16736. /* falls through */
  16737. case LEN_:
  16738. state.mode = LEN;
  16739. /* falls through */
  16740. case LEN:
  16741. if (have >= 6 && left >= 258) {
  16742. //--- RESTORE() ---
  16743. strm.next_out = put;
  16744. strm.avail_out = left;
  16745. strm.next_in = next;
  16746. strm.avail_in = have;
  16747. state.hold = hold;
  16748. state.bits = bits;
  16749. //---
  16750. inflate_fast(strm, _out);
  16751. //--- LOAD() ---
  16752. put = strm.next_out;
  16753. output = strm.output;
  16754. left = strm.avail_out;
  16755. next = strm.next_in;
  16756. input = strm.input;
  16757. have = strm.avail_in;
  16758. hold = state.hold;
  16759. bits = state.bits;
  16760. //---
  16761. if (state.mode === TYPE) {
  16762. state.back = -1;
  16763. }
  16764. break;
  16765. }
  16766. state.back = 0;
  16767. for (;;) {
  16768. here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
  16769. here_bits = here >>> 24;
  16770. here_op = (here >>> 16) & 0xff;
  16771. here_val = here & 0xffff;
  16772. if (here_bits <= bits) { break; }
  16773. //--- PULLBYTE() ---//
  16774. if (have === 0) { break inf_leave; }
  16775. have--;
  16776. hold += input[next++] << bits;
  16777. bits += 8;
  16778. //---//
  16779. }
  16780. if (here_op && (here_op & 0xf0) === 0) {
  16781. last_bits = here_bits;
  16782. last_op = here_op;
  16783. last_val = here_val;
  16784. for (;;) {
  16785. here = state.lencode[last_val +
  16786. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  16787. here_bits = here >>> 24;
  16788. here_op = (here >>> 16) & 0xff;
  16789. here_val = here & 0xffff;
  16790. if ((last_bits + here_bits) <= bits) { break; }
  16791. //--- PULLBYTE() ---//
  16792. if (have === 0) { break inf_leave; }
  16793. have--;
  16794. hold += input[next++] << bits;
  16795. bits += 8;
  16796. //---//
  16797. }
  16798. //--- DROPBITS(last.bits) ---//
  16799. hold >>>= last_bits;
  16800. bits -= last_bits;
  16801. //---//
  16802. state.back += last_bits;
  16803. }
  16804. //--- DROPBITS(here.bits) ---//
  16805. hold >>>= here_bits;
  16806. bits -= here_bits;
  16807. //---//
  16808. state.back += here_bits;
  16809. state.length = here_val;
  16810. if (here_op === 0) {
  16811. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  16812. // "inflate: literal '%c'\n" :
  16813. // "inflate: literal 0x%02x\n", here.val));
  16814. state.mode = LIT;
  16815. break;
  16816. }
  16817. if (here_op & 32) {
  16818. //Tracevv((stderr, "inflate: end of block\n"));
  16819. state.back = -1;
  16820. state.mode = TYPE;
  16821. break;
  16822. }
  16823. if (here_op & 64) {
  16824. strm.msg = 'invalid literal/length code';
  16825. state.mode = BAD;
  16826. break;
  16827. }
  16828. state.extra = here_op & 15;
  16829. state.mode = LENEXT;
  16830. /* falls through */
  16831. case LENEXT:
  16832. if (state.extra) {
  16833. //=== NEEDBITS(state.extra);
  16834. n = state.extra;
  16835. while (bits < n) {
  16836. if (have === 0) { break inf_leave; }
  16837. have--;
  16838. hold += input[next++] << bits;
  16839. bits += 8;
  16840. }
  16841. //===//
  16842. state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  16843. //--- DROPBITS(state.extra) ---//
  16844. hold >>>= state.extra;
  16845. bits -= state.extra;
  16846. //---//
  16847. state.back += state.extra;
  16848. }
  16849. //Tracevv((stderr, "inflate: length %u\n", state.length));
  16850. state.was = state.length;
  16851. state.mode = DIST;
  16852. /* falls through */
  16853. case DIST:
  16854. for (;;) {
  16855. here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
  16856. here_bits = here >>> 24;
  16857. here_op = (here >>> 16) & 0xff;
  16858. here_val = here & 0xffff;
  16859. if ((here_bits) <= bits) { break; }
  16860. //--- PULLBYTE() ---//
  16861. if (have === 0) { break inf_leave; }
  16862. have--;
  16863. hold += input[next++] << bits;
  16864. bits += 8;
  16865. //---//
  16866. }
  16867. if ((here_op & 0xf0) === 0) {
  16868. last_bits = here_bits;
  16869. last_op = here_op;
  16870. last_val = here_val;
  16871. for (;;) {
  16872. here = state.distcode[last_val +
  16873. ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  16874. here_bits = here >>> 24;
  16875. here_op = (here >>> 16) & 0xff;
  16876. here_val = here & 0xffff;
  16877. if ((last_bits + here_bits) <= bits) { break; }
  16878. //--- PULLBYTE() ---//
  16879. if (have === 0) { break inf_leave; }
  16880. have--;
  16881. hold += input[next++] << bits;
  16882. bits += 8;
  16883. //---//
  16884. }
  16885. //--- DROPBITS(last.bits) ---//
  16886. hold >>>= last_bits;
  16887. bits -= last_bits;
  16888. //---//
  16889. state.back += last_bits;
  16890. }
  16891. //--- DROPBITS(here.bits) ---//
  16892. hold >>>= here_bits;
  16893. bits -= here_bits;
  16894. //---//
  16895. state.back += here_bits;
  16896. if (here_op & 64) {
  16897. strm.msg = 'invalid distance code';
  16898. state.mode = BAD;
  16899. break;
  16900. }
  16901. state.offset = here_val;
  16902. state.extra = (here_op) & 15;
  16903. state.mode = DISTEXT;
  16904. /* falls through */
  16905. case DISTEXT:
  16906. if (state.extra) {
  16907. //=== NEEDBITS(state.extra);
  16908. n = state.extra;
  16909. while (bits < n) {
  16910. if (have === 0) { break inf_leave; }
  16911. have--;
  16912. hold += input[next++] << bits;
  16913. bits += 8;
  16914. }
  16915. //===//
  16916. state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
  16917. //--- DROPBITS(state.extra) ---//
  16918. hold >>>= state.extra;
  16919. bits -= state.extra;
  16920. //---//
  16921. state.back += state.extra;
  16922. }
  16923. //#ifdef INFLATE_STRICT
  16924. if (state.offset > state.dmax) {
  16925. strm.msg = 'invalid distance too far back';
  16926. state.mode = BAD;
  16927. break;
  16928. }
  16929. //#endif
  16930. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  16931. state.mode = MATCH;
  16932. /* falls through */
  16933. case MATCH:
  16934. if (left === 0) { break inf_leave; }
  16935. copy = _out - left;
  16936. if (state.offset > copy) { /* copy from window */
  16937. copy = state.offset - copy;
  16938. if (copy > state.whave) {
  16939. if (state.sane) {
  16940. strm.msg = 'invalid distance too far back';
  16941. state.mode = BAD;
  16942. break;
  16943. }
  16944. // (!) This block is disabled in zlib defaults,
  16945. // don't enable it for binary compatibility
  16946. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  16947. // Trace((stderr, "inflate.c too far\n"));
  16948. // copy -= state.whave;
  16949. // if (copy > state.length) { copy = state.length; }
  16950. // if (copy > left) { copy = left; }
  16951. // left -= copy;
  16952. // state.length -= copy;
  16953. // do {
  16954. // output[put++] = 0;
  16955. // } while (--copy);
  16956. // if (state.length === 0) { state.mode = LEN; }
  16957. // break;
  16958. //#endif
  16959. }
  16960. if (copy > state.wnext) {
  16961. copy -= state.wnext;
  16962. from = state.wsize - copy;
  16963. }
  16964. else {
  16965. from = state.wnext - copy;
  16966. }
  16967. if (copy > state.length) { copy = state.length; }
  16968. from_source = state.window;
  16969. }
  16970. else { /* copy from output */
  16971. from_source = output;
  16972. from = put - state.offset;
  16973. copy = state.length;
  16974. }
  16975. if (copy > left) { copy = left; }
  16976. left -= copy;
  16977. state.length -= copy;
  16978. do {
  16979. output[put++] = from_source[from++];
  16980. } while (--copy);
  16981. if (state.length === 0) { state.mode = LEN; }
  16982. break;
  16983. case LIT:
  16984. if (left === 0) { break inf_leave; }
  16985. output[put++] = state.length;
  16986. left--;
  16987. state.mode = LEN;
  16988. break;
  16989. case CHECK:
  16990. if (state.wrap) {
  16991. //=== NEEDBITS(32);
  16992. while (bits < 32) {
  16993. if (have === 0) { break inf_leave; }
  16994. have--;
  16995. // Use '|' instead of '+' to make sure that result is signed
  16996. hold |= input[next++] << bits;
  16997. bits += 8;
  16998. }
  16999. //===//
  17000. _out -= left;
  17001. strm.total_out += _out;
  17002. state.total += _out;
  17003. if (_out) {
  17004. strm.adler = state.check =
  17005. /*UPDATE(state.check, put - _out, _out);*/
  17006. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  17007. }
  17008. _out = left;
  17009. // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
  17010. if ((state.flags ? hold : zswap32(hold)) !== state.check) {
  17011. strm.msg = 'incorrect data check';
  17012. state.mode = BAD;
  17013. break;
  17014. }
  17015. //=== INITBITS();
  17016. hold = 0;
  17017. bits = 0;
  17018. //===//
  17019. //Tracev((stderr, "inflate: check matches trailer\n"));
  17020. }
  17021. state.mode = LENGTH;
  17022. /* falls through */
  17023. case LENGTH:
  17024. if (state.wrap && state.flags) {
  17025. //=== NEEDBITS(32);
  17026. while (bits < 32) {
  17027. if (have === 0) { break inf_leave; }
  17028. have--;
  17029. hold += input[next++] << bits;
  17030. bits += 8;
  17031. }
  17032. //===//
  17033. if (hold !== (state.total & 0xffffffff)) {
  17034. strm.msg = 'incorrect length check';
  17035. state.mode = BAD;
  17036. break;
  17037. }
  17038. //=== INITBITS();
  17039. hold = 0;
  17040. bits = 0;
  17041. //===//
  17042. //Tracev((stderr, "inflate: length matches trailer\n"));
  17043. }
  17044. state.mode = DONE;
  17045. /* falls through */
  17046. case DONE:
  17047. ret = Z_STREAM_END;
  17048. break inf_leave;
  17049. case BAD:
  17050. ret = Z_DATA_ERROR;
  17051. break inf_leave;
  17052. case MEM:
  17053. return Z_MEM_ERROR;
  17054. case SYNC:
  17055. /* falls through */
  17056. default:
  17057. return Z_STREAM_ERROR;
  17058. }
  17059. }
  17060. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  17061. /*
  17062. Return from inflate(), updating the total counts and the check value.
  17063. If there was no progress during the inflate() call, return a buffer
  17064. error. Call updatewindow() to create and/or update the window state.
  17065. Note: a memory error from inflate() is non-recoverable.
  17066. */
  17067. //--- RESTORE() ---
  17068. strm.next_out = put;
  17069. strm.avail_out = left;
  17070. strm.next_in = next;
  17071. strm.avail_in = have;
  17072. state.hold = hold;
  17073. state.bits = bits;
  17074. //---
  17075. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  17076. (state.mode < CHECK || flush !== Z_FINISH))) {
  17077. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  17078. state.mode = MEM;
  17079. return Z_MEM_ERROR;
  17080. }
  17081. }
  17082. _in -= strm.avail_in;
  17083. _out -= strm.avail_out;
  17084. strm.total_in += _in;
  17085. strm.total_out += _out;
  17086. state.total += _out;
  17087. if (state.wrap && _out) {
  17088. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  17089. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  17090. }
  17091. strm.data_type = state.bits + (state.last ? 64 : 0) +
  17092. (state.mode === TYPE ? 128 : 0) +
  17093. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  17094. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  17095. ret = Z_BUF_ERROR;
  17096. }
  17097. return ret;
  17098. }
  17099. function inflateEnd(strm) {
  17100. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  17101. return Z_STREAM_ERROR;
  17102. }
  17103. var state = strm.state;
  17104. if (state.window) {
  17105. state.window = null;
  17106. }
  17107. strm.state = null;
  17108. return Z_OK;
  17109. }
  17110. function inflateGetHeader(strm, head) {
  17111. var state;
  17112. /* check state */
  17113. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17114. state = strm.state;
  17115. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  17116. /* save header structure */
  17117. state.head = head;
  17118. head.done = false;
  17119. return Z_OK;
  17120. }
  17121. function inflateSetDictionary(strm, dictionary) {
  17122. var dictLength = dictionary.length;
  17123. var state;
  17124. var dictid;
  17125. var ret;
  17126. /* check state */
  17127. if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
  17128. state = strm.state;
  17129. if (state.wrap !== 0 && state.mode !== DICT) {
  17130. return Z_STREAM_ERROR;
  17131. }
  17132. /* check for correct dictionary identifier */
  17133. if (state.mode === DICT) {
  17134. dictid = 1; /* adler32(0, null, 0)*/
  17135. /* dictid = adler32(dictid, dictionary, dictLength); */
  17136. dictid = adler32(dictid, dictionary, dictLength, 0);
  17137. if (dictid !== state.check) {
  17138. return Z_DATA_ERROR;
  17139. }
  17140. }
  17141. /* copy dictionary to window using updatewindow(), which will amend the
  17142. existing dictionary if appropriate */
  17143. ret = updatewindow(strm, dictionary, dictLength, dictLength);
  17144. if (ret) {
  17145. state.mode = MEM;
  17146. return Z_MEM_ERROR;
  17147. }
  17148. state.havedict = 1;
  17149. // Tracev((stderr, "inflate: dictionary set\n"));
  17150. return Z_OK;
  17151. }
  17152. exports.inflateReset = inflateReset;
  17153. exports.inflateReset2 = inflateReset2;
  17154. exports.inflateResetKeep = inflateResetKeep;
  17155. exports.inflateInit = inflateInit;
  17156. exports.inflateInit2 = inflateInit2;
  17157. exports.inflate = inflate;
  17158. exports.inflateEnd = inflateEnd;
  17159. exports.inflateGetHeader = inflateGetHeader;
  17160. exports.inflateSetDictionary = inflateSetDictionary;
  17161. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  17162. /* Not implemented
  17163. exports.inflateCopy = inflateCopy;
  17164. exports.inflateGetDictionary = inflateGetDictionary;
  17165. exports.inflateMark = inflateMark;
  17166. exports.inflatePrime = inflatePrime;
  17167. exports.inflateSync = inflateSync;
  17168. exports.inflateSyncPoint = inflateSyncPoint;
  17169. exports.inflateUndermine = inflateUndermine;
  17170. */
  17171. },{"../utils/common":53,"./adler32":55,"./crc32":57,"./inffast":60,"./inftrees":62}],62:[function(require,module,exports){
  17172. 'use strict';
  17173. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  17174. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  17175. //
  17176. // This software is provided 'as-is', without any express or implied
  17177. // warranty. In no event will the authors be held liable for any damages
  17178. // arising from the use of this software.
  17179. //
  17180. // Permission is granted to anyone to use this software for any purpose,
  17181. // including commercial applications, and to alter it and redistribute it
  17182. // freely, subject to the following restrictions:
  17183. //
  17184. // 1. The origin of this software must not be misrepresented; you must not
  17185. // claim that you wrote the original software. If you use this software
  17186. // in a product, an acknowledgment in the product documentation would be
  17187. // appreciated but is not required.
  17188. // 2. Altered source versions must be plainly marked as such, and must not be
  17189. // misrepresented as being the original software.
  17190. // 3. This notice may not be removed or altered from any source distribution.
  17191. var utils = require('../utils/common');
  17192. var MAXBITS = 15;
  17193. var ENOUGH_LENS = 852;
  17194. var ENOUGH_DISTS = 592;
  17195. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  17196. var CODES = 0;
  17197. var LENS = 1;
  17198. var DISTS = 2;
  17199. var lbase = [ /* Length codes 257..285 base */
  17200. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  17201. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  17202. ];
  17203. var lext = [ /* Length codes 257..285 extra */
  17204. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  17205. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  17206. ];
  17207. var dbase = [ /* Distance codes 0..29 base */
  17208. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  17209. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  17210. 8193, 12289, 16385, 24577, 0, 0
  17211. ];
  17212. var dext = [ /* Distance codes 0..29 extra */
  17213. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  17214. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  17215. 28, 28, 29, 29, 64, 64
  17216. ];
  17217. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  17218. {
  17219. var bits = opts.bits;
  17220. //here = opts.here; /* table entry for duplication */
  17221. var len = 0; /* a code's length in bits */
  17222. var sym = 0; /* index of code symbols */
  17223. var min = 0, max = 0; /* minimum and maximum code lengths */
  17224. var root = 0; /* number of index bits for root table */
  17225. var curr = 0; /* number of index bits for current table */
  17226. var drop = 0; /* code bits to drop for sub-table */
  17227. var left = 0; /* number of prefix codes available */
  17228. var used = 0; /* code entries in table used */
  17229. var huff = 0; /* Huffman code */
  17230. var incr; /* for incrementing code, index */
  17231. var fill; /* index for replicating entries */
  17232. var low; /* low bits for current root entry */
  17233. var mask; /* mask for low root bits */
  17234. var next; /* next available space in table */
  17235. var base = null; /* base value table to use */
  17236. var base_index = 0;
  17237. // var shoextra; /* extra bits table to use */
  17238. var end; /* use base and extra for symbol > end */
  17239. var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
  17240. var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
  17241. var extra = null;
  17242. var extra_index = 0;
  17243. var here_bits, here_op, here_val;
  17244. /*
  17245. Process a set of code lengths to create a canonical Huffman code. The
  17246. code lengths are lens[0..codes-1]. Each length corresponds to the
  17247. symbols 0..codes-1. The Huffman code is generated by first sorting the
  17248. symbols by length from short to long, and retaining the symbol order
  17249. for codes with equal lengths. Then the code starts with all zero bits
  17250. for the first code of the shortest length, and the codes are integer
  17251. increments for the same length, and zeros are appended as the length
  17252. increases. For the deflate format, these bits are stored backwards
  17253. from their more natural integer increment ordering, and so when the
  17254. decoding tables are built in the large loop below, the integer codes
  17255. are incremented backwards.
  17256. This routine assumes, but does not check, that all of the entries in
  17257. lens[] are in the range 0..MAXBITS. The caller must assure this.
  17258. 1..MAXBITS is interpreted as that code length. zero means that that
  17259. symbol does not occur in this code.
  17260. The codes are sorted by computing a count of codes for each length,
  17261. creating from that a table of starting indices for each length in the
  17262. sorted table, and then entering the symbols in order in the sorted
  17263. table. The sorted table is work[], with that space being provided by
  17264. the caller.
  17265. The length counts are used for other purposes as well, i.e. finding
  17266. the minimum and maximum length codes, determining if there are any
  17267. codes at all, checking for a valid set of lengths, and looking ahead
  17268. at length counts to determine sub-table sizes when building the
  17269. decoding tables.
  17270. */
  17271. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  17272. for (len = 0; len <= MAXBITS; len++) {
  17273. count[len] = 0;
  17274. }
  17275. for (sym = 0; sym < codes; sym++) {
  17276. count[lens[lens_index + sym]]++;
  17277. }
  17278. /* bound code lengths, force root to be within code lengths */
  17279. root = bits;
  17280. for (max = MAXBITS; max >= 1; max--) {
  17281. if (count[max] !== 0) { break; }
  17282. }
  17283. if (root > max) {
  17284. root = max;
  17285. }
  17286. if (max === 0) { /* no symbols to code at all */
  17287. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  17288. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  17289. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  17290. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  17291. //table.op[opts.table_index] = 64;
  17292. //table.bits[opts.table_index] = 1;
  17293. //table.val[opts.table_index++] = 0;
  17294. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  17295. opts.bits = 1;
  17296. return 0; /* no symbols, but wait for decoding to report error */
  17297. }
  17298. for (min = 1; min < max; min++) {
  17299. if (count[min] !== 0) { break; }
  17300. }
  17301. if (root < min) {
  17302. root = min;
  17303. }
  17304. /* check for an over-subscribed or incomplete set of lengths */
  17305. left = 1;
  17306. for (len = 1; len <= MAXBITS; len++) {
  17307. left <<= 1;
  17308. left -= count[len];
  17309. if (left < 0) {
  17310. return -1;
  17311. } /* over-subscribed */
  17312. }
  17313. if (left > 0 && (type === CODES || max !== 1)) {
  17314. return -1; /* incomplete set */
  17315. }
  17316. /* generate offsets into symbol table for each length for sorting */
  17317. offs[1] = 0;
  17318. for (len = 1; len < MAXBITS; len++) {
  17319. offs[len + 1] = offs[len] + count[len];
  17320. }
  17321. /* sort symbols by length, by symbol order within each length */
  17322. for (sym = 0; sym < codes; sym++) {
  17323. if (lens[lens_index + sym] !== 0) {
  17324. work[offs[lens[lens_index + sym]]++] = sym;
  17325. }
  17326. }
  17327. /*
  17328. Create and fill in decoding tables. In this loop, the table being
  17329. filled is at next and has curr index bits. The code being used is huff
  17330. with length len. That code is converted to an index by dropping drop
  17331. bits off of the bottom. For codes where len is less than drop + curr,
  17332. those top drop + curr - len bits are incremented through all values to
  17333. fill the table with replicated entries.
  17334. root is the number of index bits for the root table. When len exceeds
  17335. root, sub-tables are created pointed to by the root entry with an index
  17336. of the low root bits of huff. This is saved in low to check for when a
  17337. new sub-table should be started. drop is zero when the root table is
  17338. being filled, and drop is root when sub-tables are being filled.
  17339. When a new sub-table is needed, it is necessary to look ahead in the
  17340. code lengths to determine what size sub-table is needed. The length
  17341. counts are used for this, and so count[] is decremented as codes are
  17342. entered in the tables.
  17343. used keeps track of how many table entries have been allocated from the
  17344. provided *table space. It is checked for LENS and DIST tables against
  17345. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  17346. the initial root table size constants. See the comments in inftrees.h
  17347. for more information.
  17348. sym increments through all symbols, and the loop terminates when
  17349. all codes of length max, i.e. all codes, have been processed. This
  17350. routine permits incomplete codes, so another loop after this one fills
  17351. in the rest of the decoding tables with invalid code markers.
  17352. */
  17353. /* set up for code type */
  17354. // poor man optimization - use if-else instead of switch,
  17355. // to avoid deopts in old v8
  17356. if (type === CODES) {
  17357. base = extra = work; /* dummy value--not used */
  17358. end = 19;
  17359. } else if (type === LENS) {
  17360. base = lbase;
  17361. base_index -= 257;
  17362. extra = lext;
  17363. extra_index -= 257;
  17364. end = 256;
  17365. } else { /* DISTS */
  17366. base = dbase;
  17367. extra = dext;
  17368. end = -1;
  17369. }
  17370. /* initialize opts for loop */
  17371. huff = 0; /* starting code */
  17372. sym = 0; /* starting code symbol */
  17373. len = min; /* starting code length */
  17374. next = table_index; /* current table to fill in */
  17375. curr = root; /* current table index bits */
  17376. drop = 0; /* current bits to drop from code for index */
  17377. low = -1; /* trigger new sub-table when len > root */
  17378. used = 1 << root; /* use root table entries */
  17379. mask = used - 1; /* mask for comparing low */
  17380. /* check available table space */
  17381. if ((type === LENS && used > ENOUGH_LENS) ||
  17382. (type === DISTS && used > ENOUGH_DISTS)) {
  17383. return 1;
  17384. }
  17385. /* process all codes and make table entries */
  17386. for (;;) {
  17387. /* create table entry */
  17388. here_bits = len - drop;
  17389. if (work[sym] < end) {
  17390. here_op = 0;
  17391. here_val = work[sym];
  17392. }
  17393. else if (work[sym] > end) {
  17394. here_op = extra[extra_index + work[sym]];
  17395. here_val = base[base_index + work[sym]];
  17396. }
  17397. else {
  17398. here_op = 32 + 64; /* end of block */
  17399. here_val = 0;
  17400. }
  17401. /* replicate for those indices with low len bits equal to huff */
  17402. incr = 1 << (len - drop);
  17403. fill = 1 << curr;
  17404. min = fill; /* save offset to next table */
  17405. do {
  17406. fill -= incr;
  17407. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  17408. } while (fill !== 0);
  17409. /* backwards increment the len-bit code huff */
  17410. incr = 1 << (len - 1);
  17411. while (huff & incr) {
  17412. incr >>= 1;
  17413. }
  17414. if (incr !== 0) {
  17415. huff &= incr - 1;
  17416. huff += incr;
  17417. } else {
  17418. huff = 0;
  17419. }
  17420. /* go to next symbol, update count, len */
  17421. sym++;
  17422. if (--count[len] === 0) {
  17423. if (len === max) { break; }
  17424. len = lens[lens_index + work[sym]];
  17425. }
  17426. /* create new sub-table if needed */
  17427. if (len > root && (huff & mask) !== low) {
  17428. /* if first time, transition to sub-tables */
  17429. if (drop === 0) {
  17430. drop = root;
  17431. }
  17432. /* increment past last table */
  17433. next += min; /* here min is 1 << curr */
  17434. /* determine length of next table */
  17435. curr = len - drop;
  17436. left = 1 << curr;
  17437. while (curr + drop < max) {
  17438. left -= count[curr + drop];
  17439. if (left <= 0) { break; }
  17440. curr++;
  17441. left <<= 1;
  17442. }
  17443. /* check for enough space */
  17444. used += 1 << curr;
  17445. if ((type === LENS && used > ENOUGH_LENS) ||
  17446. (type === DISTS && used > ENOUGH_DISTS)) {
  17447. return 1;
  17448. }
  17449. /* point entry in root table to sub-table */
  17450. low = huff & mask;
  17451. /*table.op[low] = curr;
  17452. table.bits[low] = root;
  17453. table.val[low] = next - opts.table_index;*/
  17454. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  17455. }
  17456. }
  17457. /* fill in remaining table entry if code is incomplete (guaranteed to have
  17458. at most one remaining entry, since if the code is incomplete, the
  17459. maximum code length that was allowed to get this far is one bit) */
  17460. if (huff !== 0) {
  17461. //table.op[next + huff] = 64; /* invalid code marker */
  17462. //table.bits[next + huff] = len - drop;
  17463. //table.val[next + huff] = 0;
  17464. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  17465. }
  17466. /* set return parameters */
  17467. //opts.table_index += used;
  17468. opts.bits = root;
  17469. return 0;
  17470. };
  17471. },{"../utils/common":53}],63:[function(require,module,exports){
  17472. 'use strict';
  17473. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  17474. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  17475. //
  17476. // This software is provided 'as-is', without any express or implied
  17477. // warranty. In no event will the authors be held liable for any damages
  17478. // arising from the use of this software.
  17479. //
  17480. // Permission is granted to anyone to use this software for any purpose,
  17481. // including commercial applications, and to alter it and redistribute it
  17482. // freely, subject to the following restrictions:
  17483. //
  17484. // 1. The origin of this software must not be misrepresented; you must not
  17485. // claim that you wrote the original software. If you use this software
  17486. // in a product, an acknowledgment in the product documentation would be
  17487. // appreciated but is not required.
  17488. // 2. Altered source versions must be plainly marked as such, and must not be
  17489. // misrepresented as being the original software.
  17490. // 3. This notice may not be removed or altered from any source distribution.
  17491. module.exports = {
  17492. 2: 'need dictionary', /* Z_NEED_DICT 2 */
  17493. 1: 'stream end', /* Z_STREAM_END 1 */
  17494. 0: '', /* Z_OK 0 */
  17495. '-1': 'file error', /* Z_ERRNO (-1) */
  17496. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  17497. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  17498. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  17499. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  17500. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  17501. };
  17502. },{}],64:[function(require,module,exports){
  17503. 'use strict';
  17504. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  17505. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  17506. //
  17507. // This software is provided 'as-is', without any express or implied
  17508. // warranty. In no event will the authors be held liable for any damages
  17509. // arising from the use of this software.
  17510. //
  17511. // Permission is granted to anyone to use this software for any purpose,
  17512. // including commercial applications, and to alter it and redistribute it
  17513. // freely, subject to the following restrictions:
  17514. //
  17515. // 1. The origin of this software must not be misrepresented; you must not
  17516. // claim that you wrote the original software. If you use this software
  17517. // in a product, an acknowledgment in the product documentation would be
  17518. // appreciated but is not required.
  17519. // 2. Altered source versions must be plainly marked as such, and must not be
  17520. // misrepresented as being the original software.
  17521. // 3. This notice may not be removed or altered from any source distribution.
  17522. var utils = require('../utils/common');
  17523. /* Public constants ==========================================================*/
  17524. /* ===========================================================================*/
  17525. //var Z_FILTERED = 1;
  17526. //var Z_HUFFMAN_ONLY = 2;
  17527. //var Z_RLE = 3;
  17528. var Z_FIXED = 4;
  17529. //var Z_DEFAULT_STRATEGY = 0;
  17530. /* Possible values of the data_type field (though see inflate()) */
  17531. var Z_BINARY = 0;
  17532. var Z_TEXT = 1;
  17533. //var Z_ASCII = 1; // = Z_TEXT
  17534. var Z_UNKNOWN = 2;
  17535. /*============================================================================*/
  17536. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  17537. // From zutil.h
  17538. var STORED_BLOCK = 0;
  17539. var STATIC_TREES = 1;
  17540. var DYN_TREES = 2;
  17541. /* The three kinds of block type */
  17542. var MIN_MATCH = 3;
  17543. var MAX_MATCH = 258;
  17544. /* The minimum and maximum match lengths */
  17545. // From deflate.h
  17546. /* ===========================================================================
  17547. * Internal compression state.
  17548. */
  17549. var LENGTH_CODES = 29;
  17550. /* number of length codes, not counting the special END_BLOCK code */
  17551. var LITERALS = 256;
  17552. /* number of literal bytes 0..255 */
  17553. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  17554. /* number of Literal or Length codes, including the END_BLOCK code */
  17555. var D_CODES = 30;
  17556. /* number of distance codes */
  17557. var BL_CODES = 19;
  17558. /* number of codes used to transfer the bit lengths */
  17559. var HEAP_SIZE = 2 * L_CODES + 1;
  17560. /* maximum heap size */
  17561. var MAX_BITS = 15;
  17562. /* All codes must not exceed MAX_BITS bits */
  17563. var Buf_size = 16;
  17564. /* size of bit buffer in bi_buf */
  17565. /* ===========================================================================
  17566. * Constants
  17567. */
  17568. var MAX_BL_BITS = 7;
  17569. /* Bit length codes must not exceed MAX_BL_BITS bits */
  17570. var END_BLOCK = 256;
  17571. /* end of block literal code */
  17572. var REP_3_6 = 16;
  17573. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  17574. var REPZ_3_10 = 17;
  17575. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  17576. var REPZ_11_138 = 18;
  17577. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  17578. /* eslint-disable comma-spacing,array-bracket-spacing */
  17579. var extra_lbits = /* extra bits for each length code */
  17580. [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
  17581. var extra_dbits = /* extra bits for each distance code */
  17582. [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
  17583. var extra_blbits = /* extra bits for each bit length code */
  17584. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  17585. var bl_order =
  17586. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  17587. /* eslint-enable comma-spacing,array-bracket-spacing */
  17588. /* The lengths of the bit length codes are sent in order of decreasing
  17589. * probability, to avoid transmitting the lengths for unused bit length codes.
  17590. */
  17591. /* ===========================================================================
  17592. * Local data. These are initialized only once.
  17593. */
  17594. // We pre-fill arrays with 0 to avoid uninitialized gaps
  17595. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  17596. // !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
  17597. var static_ltree = new Array((L_CODES + 2) * 2);
  17598. zero(static_ltree);
  17599. /* The static literal tree. Since the bit lengths are imposed, there is no
  17600. * need for the L_CODES extra codes used during heap construction. However
  17601. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  17602. * below).
  17603. */
  17604. var static_dtree = new Array(D_CODES * 2);
  17605. zero(static_dtree);
  17606. /* The static distance tree. (Actually a trivial tree since all codes use
  17607. * 5 bits.)
  17608. */
  17609. var _dist_code = new Array(DIST_CODE_LEN);
  17610. zero(_dist_code);
  17611. /* Distance codes. The first 256 values correspond to the distances
  17612. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  17613. * the 15 bit distances.
  17614. */
  17615. var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
  17616. zero(_length_code);
  17617. /* length code for each normalized match length (0 == MIN_MATCH) */
  17618. var base_length = new Array(LENGTH_CODES);
  17619. zero(base_length);
  17620. /* First normalized length for each code (0 = MIN_MATCH) */
  17621. var base_dist = new Array(D_CODES);
  17622. zero(base_dist);
  17623. /* First normalized distance for each code (0 = distance of 1) */
  17624. function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
  17625. this.static_tree = static_tree; /* static tree or NULL */
  17626. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  17627. this.extra_base = extra_base; /* base index for extra_bits */
  17628. this.elems = elems; /* max number of elements in the tree */
  17629. this.max_length = max_length; /* max bit length for the codes */
  17630. // show if `static_tree` has data or dummy - needed for monomorphic objects
  17631. this.has_stree = static_tree && static_tree.length;
  17632. }
  17633. var static_l_desc;
  17634. var static_d_desc;
  17635. var static_bl_desc;
  17636. function TreeDesc(dyn_tree, stat_desc) {
  17637. this.dyn_tree = dyn_tree; /* the dynamic tree */
  17638. this.max_code = 0; /* largest code with non zero frequency */
  17639. this.stat_desc = stat_desc; /* the corresponding static tree */
  17640. }
  17641. function d_code(dist) {
  17642. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  17643. }
  17644. /* ===========================================================================
  17645. * Output a short LSB first on the stream.
  17646. * IN assertion: there is enough room in pendingBuf.
  17647. */
  17648. function put_short(s, w) {
  17649. // put_byte(s, (uch)((w) & 0xff));
  17650. // put_byte(s, (uch)((ush)(w) >> 8));
  17651. s.pending_buf[s.pending++] = (w) & 0xff;
  17652. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  17653. }
  17654. /* ===========================================================================
  17655. * Send a value on a given number of bits.
  17656. * IN assertion: length <= 16 and value fits in length bits.
  17657. */
  17658. function send_bits(s, value, length) {
  17659. if (s.bi_valid > (Buf_size - length)) {
  17660. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  17661. put_short(s, s.bi_buf);
  17662. s.bi_buf = value >> (Buf_size - s.bi_valid);
  17663. s.bi_valid += length - Buf_size;
  17664. } else {
  17665. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  17666. s.bi_valid += length;
  17667. }
  17668. }
  17669. function send_code(s, c, tree) {
  17670. send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
  17671. }
  17672. /* ===========================================================================
  17673. * Reverse the first len bits of a code, using straightforward code (a faster
  17674. * method would use a table)
  17675. * IN assertion: 1 <= len <= 15
  17676. */
  17677. function bi_reverse(code, len) {
  17678. var res = 0;
  17679. do {
  17680. res |= code & 1;
  17681. code >>>= 1;
  17682. res <<= 1;
  17683. } while (--len > 0);
  17684. return res >>> 1;
  17685. }
  17686. /* ===========================================================================
  17687. * Flush the bit buffer, keeping at most 7 bits in it.
  17688. */
  17689. function bi_flush(s) {
  17690. if (s.bi_valid === 16) {
  17691. put_short(s, s.bi_buf);
  17692. s.bi_buf = 0;
  17693. s.bi_valid = 0;
  17694. } else if (s.bi_valid >= 8) {
  17695. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  17696. s.bi_buf >>= 8;
  17697. s.bi_valid -= 8;
  17698. }
  17699. }
  17700. /* ===========================================================================
  17701. * Compute the optimal bit lengths for a tree and update the total bit length
  17702. * for the current block.
  17703. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  17704. * above are the tree nodes sorted by increasing frequency.
  17705. * OUT assertions: the field len is set to the optimal bit length, the
  17706. * array bl_count contains the frequencies for each bit length.
  17707. * The length opt_len is updated; static_len is also updated if stree is
  17708. * not null.
  17709. */
  17710. function gen_bitlen(s, desc)
  17711. // deflate_state *s;
  17712. // tree_desc *desc; /* the tree descriptor */
  17713. {
  17714. var tree = desc.dyn_tree;
  17715. var max_code = desc.max_code;
  17716. var stree = desc.stat_desc.static_tree;
  17717. var has_stree = desc.stat_desc.has_stree;
  17718. var extra = desc.stat_desc.extra_bits;
  17719. var base = desc.stat_desc.extra_base;
  17720. var max_length = desc.stat_desc.max_length;
  17721. var h; /* heap index */
  17722. var n, m; /* iterate over the tree elements */
  17723. var bits; /* bit length */
  17724. var xbits; /* extra bits */
  17725. var f; /* frequency */
  17726. var overflow = 0; /* number of elements with bit length too large */
  17727. for (bits = 0; bits <= MAX_BITS; bits++) {
  17728. s.bl_count[bits] = 0;
  17729. }
  17730. /* In a first pass, compute the optimal bit lengths (which may
  17731. * overflow in the case of the bit length tree).
  17732. */
  17733. tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
  17734. for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
  17735. n = s.heap[h];
  17736. bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  17737. if (bits > max_length) {
  17738. bits = max_length;
  17739. overflow++;
  17740. }
  17741. tree[n * 2 + 1]/*.Len*/ = bits;
  17742. /* We overwrite tree[n].Dad which is no longer needed */
  17743. if (n > max_code) { continue; } /* not a leaf node */
  17744. s.bl_count[bits]++;
  17745. xbits = 0;
  17746. if (n >= base) {
  17747. xbits = extra[n - base];
  17748. }
  17749. f = tree[n * 2]/*.Freq*/;
  17750. s.opt_len += f * (bits + xbits);
  17751. if (has_stree) {
  17752. s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
  17753. }
  17754. }
  17755. if (overflow === 0) { return; }
  17756. // Trace((stderr,"\nbit length overflow\n"));
  17757. /* This happens for example on obj2 and pic of the Calgary corpus */
  17758. /* Find the first bit length which could increase: */
  17759. do {
  17760. bits = max_length - 1;
  17761. while (s.bl_count[bits] === 0) { bits--; }
  17762. s.bl_count[bits]--; /* move one leaf down the tree */
  17763. s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
  17764. s.bl_count[max_length]--;
  17765. /* The brother of the overflow item also moves one step up,
  17766. * but this does not affect bl_count[max_length]
  17767. */
  17768. overflow -= 2;
  17769. } while (overflow > 0);
  17770. /* Now recompute all bit lengths, scanning in increasing frequency.
  17771. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  17772. * lengths instead of fixing only the wrong ones. This idea is taken
  17773. * from 'ar' written by Haruhiko Okumura.)
  17774. */
  17775. for (bits = max_length; bits !== 0; bits--) {
  17776. n = s.bl_count[bits];
  17777. while (n !== 0) {
  17778. m = s.heap[--h];
  17779. if (m > max_code) { continue; }
  17780. if (tree[m * 2 + 1]/*.Len*/ !== bits) {
  17781. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  17782. s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
  17783. tree[m * 2 + 1]/*.Len*/ = bits;
  17784. }
  17785. n--;
  17786. }
  17787. }
  17788. }
  17789. /* ===========================================================================
  17790. * Generate the codes for a given tree and bit counts (which need not be
  17791. * optimal).
  17792. * IN assertion: the array bl_count contains the bit length statistics for
  17793. * the given tree and the field len is set for all tree elements.
  17794. * OUT assertion: the field code is set for all tree elements of non
  17795. * zero code length.
  17796. */
  17797. function gen_codes(tree, max_code, bl_count)
  17798. // ct_data *tree; /* the tree to decorate */
  17799. // int max_code; /* largest code with non zero frequency */
  17800. // ushf *bl_count; /* number of codes at each bit length */
  17801. {
  17802. var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
  17803. var code = 0; /* running code value */
  17804. var bits; /* bit index */
  17805. var n; /* code index */
  17806. /* The distribution counts are first used to generate the code values
  17807. * without bit reversal.
  17808. */
  17809. for (bits = 1; bits <= MAX_BITS; bits++) {
  17810. next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
  17811. }
  17812. /* Check that the bit counts in bl_count are consistent. The last code
  17813. * must be all ones.
  17814. */
  17815. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  17816. // "inconsistent bit counts");
  17817. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  17818. for (n = 0; n <= max_code; n++) {
  17819. var len = tree[n * 2 + 1]/*.Len*/;
  17820. if (len === 0) { continue; }
  17821. /* Now reverse the bits */
  17822. tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  17823. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  17824. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  17825. }
  17826. }
  17827. /* ===========================================================================
  17828. * Initialize the various 'constant' tables.
  17829. */
  17830. function tr_static_init() {
  17831. var n; /* iterates over tree elements */
  17832. var bits; /* bit counter */
  17833. var length; /* length value */
  17834. var code; /* code value */
  17835. var dist; /* distance index */
  17836. var bl_count = new Array(MAX_BITS + 1);
  17837. /* number of codes at each bit length for an optimal tree */
  17838. // do check in _tr_init()
  17839. //if (static_init_done) return;
  17840. /* For some embedded targets, global variables are not initialized: */
  17841. /*#ifdef NO_INIT_GLOBAL_POINTERS
  17842. static_l_desc.static_tree = static_ltree;
  17843. static_l_desc.extra_bits = extra_lbits;
  17844. static_d_desc.static_tree = static_dtree;
  17845. static_d_desc.extra_bits = extra_dbits;
  17846. static_bl_desc.extra_bits = extra_blbits;
  17847. #endif*/
  17848. /* Initialize the mapping length (0..255) -> length code (0..28) */
  17849. length = 0;
  17850. for (code = 0; code < LENGTH_CODES - 1; code++) {
  17851. base_length[code] = length;
  17852. for (n = 0; n < (1 << extra_lbits[code]); n++) {
  17853. _length_code[length++] = code;
  17854. }
  17855. }
  17856. //Assert (length == 256, "tr_static_init: length != 256");
  17857. /* Note that the length 255 (match length 258) can be represented
  17858. * in two different ways: code 284 + 5 bits or code 285, so we
  17859. * overwrite length_code[255] to use the best encoding:
  17860. */
  17861. _length_code[length - 1] = code;
  17862. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  17863. dist = 0;
  17864. for (code = 0; code < 16; code++) {
  17865. base_dist[code] = dist;
  17866. for (n = 0; n < (1 << extra_dbits[code]); n++) {
  17867. _dist_code[dist++] = code;
  17868. }
  17869. }
  17870. //Assert (dist == 256, "tr_static_init: dist != 256");
  17871. dist >>= 7; /* from now on, all distances are divided by 128 */
  17872. for (; code < D_CODES; code++) {
  17873. base_dist[code] = dist << 7;
  17874. for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
  17875. _dist_code[256 + dist++] = code;
  17876. }
  17877. }
  17878. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  17879. /* Construct the codes of the static literal tree */
  17880. for (bits = 0; bits <= MAX_BITS; bits++) {
  17881. bl_count[bits] = 0;
  17882. }
  17883. n = 0;
  17884. while (n <= 143) {
  17885. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  17886. n++;
  17887. bl_count[8]++;
  17888. }
  17889. while (n <= 255) {
  17890. static_ltree[n * 2 + 1]/*.Len*/ = 9;
  17891. n++;
  17892. bl_count[9]++;
  17893. }
  17894. while (n <= 279) {
  17895. static_ltree[n * 2 + 1]/*.Len*/ = 7;
  17896. n++;
  17897. bl_count[7]++;
  17898. }
  17899. while (n <= 287) {
  17900. static_ltree[n * 2 + 1]/*.Len*/ = 8;
  17901. n++;
  17902. bl_count[8]++;
  17903. }
  17904. /* Codes 286 and 287 do not exist, but we must include them in the
  17905. * tree construction to get a canonical Huffman tree (longest code
  17906. * all ones)
  17907. */
  17908. gen_codes(static_ltree, L_CODES + 1, bl_count);
  17909. /* The static distance tree is trivial: */
  17910. for (n = 0; n < D_CODES; n++) {
  17911. static_dtree[n * 2 + 1]/*.Len*/ = 5;
  17912. static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
  17913. }
  17914. // Now data ready and we can init static trees
  17915. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
  17916. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  17917. static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  17918. //static_init_done = true;
  17919. }
  17920. /* ===========================================================================
  17921. * Initialize a new block.
  17922. */
  17923. function init_block(s) {
  17924. var n; /* iterates over tree elements */
  17925. /* Initialize the trees. */
  17926. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
  17927. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
  17928. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
  17929. s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
  17930. s.opt_len = s.static_len = 0;
  17931. s.last_lit = s.matches = 0;
  17932. }
  17933. /* ===========================================================================
  17934. * Flush the bit buffer and align the output on a byte boundary
  17935. */
  17936. function bi_windup(s)
  17937. {
  17938. if (s.bi_valid > 8) {
  17939. put_short(s, s.bi_buf);
  17940. } else if (s.bi_valid > 0) {
  17941. //put_byte(s, (Byte)s->bi_buf);
  17942. s.pending_buf[s.pending++] = s.bi_buf;
  17943. }
  17944. s.bi_buf = 0;
  17945. s.bi_valid = 0;
  17946. }
  17947. /* ===========================================================================
  17948. * Copy a stored block, storing first the length and its
  17949. * one's complement if requested.
  17950. */
  17951. function copy_block(s, buf, len, header)
  17952. //DeflateState *s;
  17953. //charf *buf; /* the input data */
  17954. //unsigned len; /* its length */
  17955. //int header; /* true if block header must be written */
  17956. {
  17957. bi_windup(s); /* align on byte boundary */
  17958. if (header) {
  17959. put_short(s, len);
  17960. put_short(s, ~len);
  17961. }
  17962. // while (len--) {
  17963. // put_byte(s, *buf++);
  17964. // }
  17965. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  17966. s.pending += len;
  17967. }
  17968. /* ===========================================================================
  17969. * Compares to subtrees, using the tree depth as tie breaker when
  17970. * the subtrees have equal frequency. This minimizes the worst case length.
  17971. */
  17972. function smaller(tree, n, m, depth) {
  17973. var _n2 = n * 2;
  17974. var _m2 = m * 2;
  17975. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  17976. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  17977. }
  17978. /* ===========================================================================
  17979. * Restore the heap property by moving down the tree starting at node k,
  17980. * exchanging a node with the smallest of its two sons if necessary, stopping
  17981. * when the heap property is re-established (each father smaller than its
  17982. * two sons).
  17983. */
  17984. function pqdownheap(s, tree, k)
  17985. // deflate_state *s;
  17986. // ct_data *tree; /* the tree to restore */
  17987. // int k; /* node to move down */
  17988. {
  17989. var v = s.heap[k];
  17990. var j = k << 1; /* left son of k */
  17991. while (j <= s.heap_len) {
  17992. /* Set j to the smallest of the two sons: */
  17993. if (j < s.heap_len &&
  17994. smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
  17995. j++;
  17996. }
  17997. /* Exit if v is smaller than both sons */
  17998. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  17999. /* Exchange v with the smallest son */
  18000. s.heap[k] = s.heap[j];
  18001. k = j;
  18002. /* And continue down the tree, setting j to the left son of k */
  18003. j <<= 1;
  18004. }
  18005. s.heap[k] = v;
  18006. }
  18007. // inlined manually
  18008. // var SMALLEST = 1;
  18009. /* ===========================================================================
  18010. * Send the block data compressed using the given Huffman trees
  18011. */
  18012. function compress_block(s, ltree, dtree)
  18013. // deflate_state *s;
  18014. // const ct_data *ltree; /* literal tree */
  18015. // const ct_data *dtree; /* distance tree */
  18016. {
  18017. var dist; /* distance of matched string */
  18018. var lc; /* match length or unmatched char (if dist == 0) */
  18019. var lx = 0; /* running index in l_buf */
  18020. var code; /* the code to send */
  18021. var extra; /* number of extra bits to send */
  18022. if (s.last_lit !== 0) {
  18023. do {
  18024. dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
  18025. lc = s.pending_buf[s.l_buf + lx];
  18026. lx++;
  18027. if (dist === 0) {
  18028. send_code(s, lc, ltree); /* send a literal byte */
  18029. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  18030. } else {
  18031. /* Here, lc is the match length - MIN_MATCH */
  18032. code = _length_code[lc];
  18033. send_code(s, code + LITERALS + 1, ltree); /* send the length code */
  18034. extra = extra_lbits[code];
  18035. if (extra !== 0) {
  18036. lc -= base_length[code];
  18037. send_bits(s, lc, extra); /* send the extra length bits */
  18038. }
  18039. dist--; /* dist is now the match distance - 1 */
  18040. code = d_code(dist);
  18041. //Assert (code < D_CODES, "bad d_code");
  18042. send_code(s, code, dtree); /* send the distance code */
  18043. extra = extra_dbits[code];
  18044. if (extra !== 0) {
  18045. dist -= base_dist[code];
  18046. send_bits(s, dist, extra); /* send the extra distance bits */
  18047. }
  18048. } /* literal or match pair ? */
  18049. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  18050. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  18051. // "pendingBuf overflow");
  18052. } while (lx < s.last_lit);
  18053. }
  18054. send_code(s, END_BLOCK, ltree);
  18055. }
  18056. /* ===========================================================================
  18057. * Construct one Huffman tree and assigns the code bit strings and lengths.
  18058. * Update the total bit length for the current block.
  18059. * IN assertion: the field freq is set for all tree elements.
  18060. * OUT assertions: the fields len and code are set to the optimal bit length
  18061. * and corresponding code. The length opt_len is updated; static_len is
  18062. * also updated if stree is not null. The field max_code is set.
  18063. */
  18064. function build_tree(s, desc)
  18065. // deflate_state *s;
  18066. // tree_desc *desc; /* the tree descriptor */
  18067. {
  18068. var tree = desc.dyn_tree;
  18069. var stree = desc.stat_desc.static_tree;
  18070. var has_stree = desc.stat_desc.has_stree;
  18071. var elems = desc.stat_desc.elems;
  18072. var n, m; /* iterate over heap elements */
  18073. var max_code = -1; /* largest code with non zero frequency */
  18074. var node; /* new node being created */
  18075. /* Construct the initial heap, with least frequent element in
  18076. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  18077. * heap[0] is not used.
  18078. */
  18079. s.heap_len = 0;
  18080. s.heap_max = HEAP_SIZE;
  18081. for (n = 0; n < elems; n++) {
  18082. if (tree[n * 2]/*.Freq*/ !== 0) {
  18083. s.heap[++s.heap_len] = max_code = n;
  18084. s.depth[n] = 0;
  18085. } else {
  18086. tree[n * 2 + 1]/*.Len*/ = 0;
  18087. }
  18088. }
  18089. /* The pkzip format requires that at least one distance code exists,
  18090. * and that at least one bit should be sent even if there is only one
  18091. * possible code. So to avoid special checks later on we force at least
  18092. * two codes of non zero frequency.
  18093. */
  18094. while (s.heap_len < 2) {
  18095. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  18096. tree[node * 2]/*.Freq*/ = 1;
  18097. s.depth[node] = 0;
  18098. s.opt_len--;
  18099. if (has_stree) {
  18100. s.static_len -= stree[node * 2 + 1]/*.Len*/;
  18101. }
  18102. /* node is 0 or 1 so it does not have extra bits */
  18103. }
  18104. desc.max_code = max_code;
  18105. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  18106. * establish sub-heaps of increasing lengths:
  18107. */
  18108. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  18109. /* Construct the Huffman tree by repeatedly combining the least two
  18110. * frequent nodes.
  18111. */
  18112. node = elems; /* next internal node of the tree */
  18113. do {
  18114. //pqremove(s, tree, n); /* n = node of least frequency */
  18115. /*** pqremove ***/
  18116. n = s.heap[1/*SMALLEST*/];
  18117. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  18118. pqdownheap(s, tree, 1/*SMALLEST*/);
  18119. /***/
  18120. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  18121. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  18122. s.heap[--s.heap_max] = m;
  18123. /* Create a new node father of n and m */
  18124. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  18125. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  18126. tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
  18127. /* and insert the new node in the heap */
  18128. s.heap[1/*SMALLEST*/] = node++;
  18129. pqdownheap(s, tree, 1/*SMALLEST*/);
  18130. } while (s.heap_len >= 2);
  18131. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  18132. /* At this point, the fields freq and dad are set. We can now
  18133. * generate the bit lengths.
  18134. */
  18135. gen_bitlen(s, desc);
  18136. /* The field len is now set, we can generate the bit codes */
  18137. gen_codes(tree, max_code, s.bl_count);
  18138. }
  18139. /* ===========================================================================
  18140. * Scan a literal or distance tree to determine the frequencies of the codes
  18141. * in the bit length tree.
  18142. */
  18143. function scan_tree(s, tree, max_code)
  18144. // deflate_state *s;
  18145. // ct_data *tree; /* the tree to be scanned */
  18146. // int max_code; /* and its largest code of non zero frequency */
  18147. {
  18148. var n; /* iterates over all tree elements */
  18149. var prevlen = -1; /* last emitted length */
  18150. var curlen; /* length of current code */
  18151. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  18152. var count = 0; /* repeat count of the current code */
  18153. var max_count = 7; /* max repeat count */
  18154. var min_count = 4; /* min repeat count */
  18155. if (nextlen === 0) {
  18156. max_count = 138;
  18157. min_count = 3;
  18158. }
  18159. tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
  18160. for (n = 0; n <= max_code; n++) {
  18161. curlen = nextlen;
  18162. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  18163. if (++count < max_count && curlen === nextlen) {
  18164. continue;
  18165. } else if (count < min_count) {
  18166. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  18167. } else if (curlen !== 0) {
  18168. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  18169. s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
  18170. } else if (count <= 10) {
  18171. s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
  18172. } else {
  18173. s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
  18174. }
  18175. count = 0;
  18176. prevlen = curlen;
  18177. if (nextlen === 0) {
  18178. max_count = 138;
  18179. min_count = 3;
  18180. } else if (curlen === nextlen) {
  18181. max_count = 6;
  18182. min_count = 3;
  18183. } else {
  18184. max_count = 7;
  18185. min_count = 4;
  18186. }
  18187. }
  18188. }
  18189. /* ===========================================================================
  18190. * Send a literal or distance tree in compressed form, using the codes in
  18191. * bl_tree.
  18192. */
  18193. function send_tree(s, tree, max_code)
  18194. // deflate_state *s;
  18195. // ct_data *tree; /* the tree to be scanned */
  18196. // int max_code; /* and its largest code of non zero frequency */
  18197. {
  18198. var n; /* iterates over all tree elements */
  18199. var prevlen = -1; /* last emitted length */
  18200. var curlen; /* length of current code */
  18201. var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
  18202. var count = 0; /* repeat count of the current code */
  18203. var max_count = 7; /* max repeat count */
  18204. var min_count = 4; /* min repeat count */
  18205. /* tree[max_code+1].Len = -1; */ /* guard already set */
  18206. if (nextlen === 0) {
  18207. max_count = 138;
  18208. min_count = 3;
  18209. }
  18210. for (n = 0; n <= max_code; n++) {
  18211. curlen = nextlen;
  18212. nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
  18213. if (++count < max_count && curlen === nextlen) {
  18214. continue;
  18215. } else if (count < min_count) {
  18216. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  18217. } else if (curlen !== 0) {
  18218. if (curlen !== prevlen) {
  18219. send_code(s, curlen, s.bl_tree);
  18220. count--;
  18221. }
  18222. //Assert(count >= 3 && count <= 6, " 3_6?");
  18223. send_code(s, REP_3_6, s.bl_tree);
  18224. send_bits(s, count - 3, 2);
  18225. } else if (count <= 10) {
  18226. send_code(s, REPZ_3_10, s.bl_tree);
  18227. send_bits(s, count - 3, 3);
  18228. } else {
  18229. send_code(s, REPZ_11_138, s.bl_tree);
  18230. send_bits(s, count - 11, 7);
  18231. }
  18232. count = 0;
  18233. prevlen = curlen;
  18234. if (nextlen === 0) {
  18235. max_count = 138;
  18236. min_count = 3;
  18237. } else if (curlen === nextlen) {
  18238. max_count = 6;
  18239. min_count = 3;
  18240. } else {
  18241. max_count = 7;
  18242. min_count = 4;
  18243. }
  18244. }
  18245. }
  18246. /* ===========================================================================
  18247. * Construct the Huffman tree for the bit lengths and return the index in
  18248. * bl_order of the last bit length code to send.
  18249. */
  18250. function build_bl_tree(s) {
  18251. var max_blindex; /* index of last bit length code of non zero freq */
  18252. /* Determine the bit length frequencies for literal and distance trees */
  18253. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  18254. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  18255. /* Build the bit length tree: */
  18256. build_tree(s, s.bl_desc);
  18257. /* opt_len now includes the length of the tree representations, except
  18258. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  18259. */
  18260. /* Determine the number of bit length codes to send. The pkzip format
  18261. * requires that at least 4 bit length codes be sent. (appnote.txt says
  18262. * 3 but the actual value used is 4.)
  18263. */
  18264. for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
  18265. if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
  18266. break;
  18267. }
  18268. }
  18269. /* Update opt_len to include the bit length tree and counts */
  18270. s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
  18271. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  18272. // s->opt_len, s->static_len));
  18273. return max_blindex;
  18274. }
  18275. /* ===========================================================================
  18276. * Send the header for a block using dynamic Huffman trees: the counts, the
  18277. * lengths of the bit length codes, the literal tree and the distance tree.
  18278. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  18279. */
  18280. function send_all_trees(s, lcodes, dcodes, blcodes)
  18281. // deflate_state *s;
  18282. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  18283. {
  18284. var rank; /* index in bl_order */
  18285. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  18286. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  18287. // "too many codes");
  18288. //Tracev((stderr, "\nbl counts: "));
  18289. send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
  18290. send_bits(s, dcodes - 1, 5);
  18291. send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
  18292. for (rank = 0; rank < blcodes; rank++) {
  18293. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  18294. send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
  18295. }
  18296. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  18297. send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
  18298. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  18299. send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
  18300. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  18301. }
  18302. /* ===========================================================================
  18303. * Check if the data type is TEXT or BINARY, using the following algorithm:
  18304. * - TEXT if the two conditions below are satisfied:
  18305. * a) There are no non-portable control characters belonging to the
  18306. * "black list" (0..6, 14..25, 28..31).
  18307. * b) There is at least one printable character belonging to the
  18308. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  18309. * - BINARY otherwise.
  18310. * - The following partially-portable control characters form a
  18311. * "gray list" that is ignored in this detection algorithm:
  18312. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  18313. * IN assertion: the fields Freq of dyn_ltree are set.
  18314. */
  18315. function detect_data_type(s) {
  18316. /* black_mask is the bit mask of black-listed bytes
  18317. * set bits 0..6, 14..25, and 28..31
  18318. * 0xf3ffc07f = binary 11110011111111111100000001111111
  18319. */
  18320. var black_mask = 0xf3ffc07f;
  18321. var n;
  18322. /* Check for non-textual ("black-listed") bytes. */
  18323. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  18324. if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
  18325. return Z_BINARY;
  18326. }
  18327. }
  18328. /* Check for textual ("white-listed") bytes. */
  18329. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  18330. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  18331. return Z_TEXT;
  18332. }
  18333. for (n = 32; n < LITERALS; n++) {
  18334. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  18335. return Z_TEXT;
  18336. }
  18337. }
  18338. /* There are no "black-listed" or "white-listed" bytes:
  18339. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  18340. */
  18341. return Z_BINARY;
  18342. }
  18343. var static_init_done = false;
  18344. /* ===========================================================================
  18345. * Initialize the tree data structures for a new zlib stream.
  18346. */
  18347. function _tr_init(s)
  18348. {
  18349. if (!static_init_done) {
  18350. tr_static_init();
  18351. static_init_done = true;
  18352. }
  18353. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  18354. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  18355. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  18356. s.bi_buf = 0;
  18357. s.bi_valid = 0;
  18358. /* Initialize the first block of the first file: */
  18359. init_block(s);
  18360. }
  18361. /* ===========================================================================
  18362. * Send a stored block
  18363. */
  18364. function _tr_stored_block(s, buf, stored_len, last)
  18365. //DeflateState *s;
  18366. //charf *buf; /* input block */
  18367. //ulg stored_len; /* length of input block */
  18368. //int last; /* one if this is the last block for a file */
  18369. {
  18370. send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
  18371. copy_block(s, buf, stored_len, true); /* with header */
  18372. }
  18373. /* ===========================================================================
  18374. * Send one empty static block to give enough lookahead for inflate.
  18375. * This takes 10 bits, of which 7 may remain in the bit buffer.
  18376. */
  18377. function _tr_align(s) {
  18378. send_bits(s, STATIC_TREES << 1, 3);
  18379. send_code(s, END_BLOCK, static_ltree);
  18380. bi_flush(s);
  18381. }
  18382. /* ===========================================================================
  18383. * Determine the best encoding for the current block: dynamic trees, static
  18384. * trees or store, and output the encoded block to the zip file.
  18385. */
  18386. function _tr_flush_block(s, buf, stored_len, last)
  18387. //DeflateState *s;
  18388. //charf *buf; /* input block, or NULL if too old */
  18389. //ulg stored_len; /* length of input block */
  18390. //int last; /* one if this is the last block for a file */
  18391. {
  18392. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  18393. var max_blindex = 0; /* index of last bit length code of non zero freq */
  18394. /* Build the Huffman trees unless a stored block is forced */
  18395. if (s.level > 0) {
  18396. /* Check if the file is binary or text */
  18397. if (s.strm.data_type === Z_UNKNOWN) {
  18398. s.strm.data_type = detect_data_type(s);
  18399. }
  18400. /* Construct the literal and distance trees */
  18401. build_tree(s, s.l_desc);
  18402. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  18403. // s->static_len));
  18404. build_tree(s, s.d_desc);
  18405. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  18406. // s->static_len));
  18407. /* At this point, opt_len and static_len are the total bit lengths of
  18408. * the compressed block data, excluding the tree representations.
  18409. */
  18410. /* Build the bit length tree for the above two trees, and get the index
  18411. * in bl_order of the last bit length code to send.
  18412. */
  18413. max_blindex = build_bl_tree(s);
  18414. /* Determine the best encoding. Compute the block lengths in bytes. */
  18415. opt_lenb = (s.opt_len + 3 + 7) >>> 3;
  18416. static_lenb = (s.static_len + 3 + 7) >>> 3;
  18417. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  18418. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  18419. // s->last_lit));
  18420. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  18421. } else {
  18422. // Assert(buf != (char*)0, "lost buf");
  18423. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  18424. }
  18425. if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
  18426. /* 4: two words for the lengths */
  18427. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  18428. * Otherwise we can't have processed more than WSIZE input bytes since
  18429. * the last block flush, because compression would have been
  18430. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  18431. * transform a block into a stored block.
  18432. */
  18433. _tr_stored_block(s, buf, stored_len, last);
  18434. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  18435. send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
  18436. compress_block(s, static_ltree, static_dtree);
  18437. } else {
  18438. send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
  18439. send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
  18440. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  18441. }
  18442. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  18443. /* The above check is made mod 2^32, for files larger than 512 MB
  18444. * and uLong implemented on 32 bits.
  18445. */
  18446. init_block(s);
  18447. if (last) {
  18448. bi_windup(s);
  18449. }
  18450. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  18451. // s->compressed_len-7*last));
  18452. }
  18453. /* ===========================================================================
  18454. * Save the match info and tally the frequency counts. Return true if
  18455. * the current block must be flushed.
  18456. */
  18457. function _tr_tally(s, dist, lc)
  18458. // deflate_state *s;
  18459. // unsigned dist; /* distance of matched string */
  18460. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  18461. {
  18462. //var out_length, in_length, dcode;
  18463. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  18464. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  18465. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  18466. s.last_lit++;
  18467. if (dist === 0) {
  18468. /* lc is the unmatched char */
  18469. s.dyn_ltree[lc * 2]/*.Freq*/++;
  18470. } else {
  18471. s.matches++;
  18472. /* Here, lc is the match length - MIN_MATCH */
  18473. dist--; /* dist = match distance - 1 */
  18474. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  18475. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  18476. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  18477. s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
  18478. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  18479. }
  18480. // (!) This block is disabled in zlib defaults,
  18481. // don't enable it for binary compatibility
  18482. //#ifdef TRUNCATE_BLOCK
  18483. // /* Try to guess if it is profitable to stop the current block here */
  18484. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  18485. // /* Compute an upper bound for the compressed length */
  18486. // out_length = s.last_lit*8;
  18487. // in_length = s.strstart - s.block_start;
  18488. //
  18489. // for (dcode = 0; dcode < D_CODES; dcode++) {
  18490. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  18491. // }
  18492. // out_length >>>= 3;
  18493. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  18494. // // s->last_lit, in_length, out_length,
  18495. // // 100L - out_length*100L/in_length));
  18496. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  18497. // return true;
  18498. // }
  18499. // }
  18500. //#endif
  18501. return (s.last_lit === s.lit_bufsize - 1);
  18502. /* We avoid equality with lit_bufsize because of wraparound at 64K
  18503. * on 16 bit machines and because stored blocks are restricted to
  18504. * 64K-1 bytes.
  18505. */
  18506. }
  18507. exports._tr_init = _tr_init;
  18508. exports._tr_stored_block = _tr_stored_block;
  18509. exports._tr_flush_block = _tr_flush_block;
  18510. exports._tr_tally = _tr_tally;
  18511. exports._tr_align = _tr_align;
  18512. },{"../utils/common":53}],65:[function(require,module,exports){
  18513. 'use strict';
  18514. // (C) 1995-2013 Jean-loup Gailly and Mark Adler
  18515. // (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
  18516. //
  18517. // This software is provided 'as-is', without any express or implied
  18518. // warranty. In no event will the authors be held liable for any damages
  18519. // arising from the use of this software.
  18520. //
  18521. // Permission is granted to anyone to use this software for any purpose,
  18522. // including commercial applications, and to alter it and redistribute it
  18523. // freely, subject to the following restrictions:
  18524. //
  18525. // 1. The origin of this software must not be misrepresented; you must not
  18526. // claim that you wrote the original software. If you use this software
  18527. // in a product, an acknowledgment in the product documentation would be
  18528. // appreciated but is not required.
  18529. // 2. Altered source versions must be plainly marked as such, and must not be
  18530. // misrepresented as being the original software.
  18531. // 3. This notice may not be removed or altered from any source distribution.
  18532. function ZStream() {
  18533. /* next input byte */
  18534. this.input = null; // JS specific, because we have no pointers
  18535. this.next_in = 0;
  18536. /* number of bytes available at input */
  18537. this.avail_in = 0;
  18538. /* total number of input bytes read so far */
  18539. this.total_in = 0;
  18540. /* next output byte should be put there */
  18541. this.output = null; // JS specific, because we have no pointers
  18542. this.next_out = 0;
  18543. /* remaining free space at output */
  18544. this.avail_out = 0;
  18545. /* total number of bytes output so far */
  18546. this.total_out = 0;
  18547. /* last error message, NULL if no error */
  18548. this.msg = ''/*Z_NULL*/;
  18549. /* not visible by applications */
  18550. this.state = null;
  18551. /* best guess about the data type: binary or text */
  18552. this.data_type = 2/*Z_UNKNOWN*/;
  18553. /* adler32 value of the uncompressed data */
  18554. this.adler = 0;
  18555. }
  18556. module.exports = ZStream;
  18557. },{}],66:[function(require,module,exports){
  18558. // shim for using process in browser
  18559. var process = module.exports = {};
  18560. // cached from whatever global is present so that test runners that stub it
  18561. // don't break things. But we need to wrap it in a try catch in case it is
  18562. // wrapped in strict mode code which doesn't define any globals. It's inside a
  18563. // function because try/catches deoptimize in certain engines.
  18564. var cachedSetTimeout;
  18565. var cachedClearTimeout;
  18566. function defaultSetTimout() {
  18567. throw new Error('setTimeout has not been defined');
  18568. }
  18569. function defaultClearTimeout () {
  18570. throw new Error('clearTimeout has not been defined');
  18571. }
  18572. (function () {
  18573. try {
  18574. if (typeof setTimeout === 'function') {
  18575. cachedSetTimeout = setTimeout;
  18576. } else {
  18577. cachedSetTimeout = defaultSetTimout;
  18578. }
  18579. } catch (e) {
  18580. cachedSetTimeout = defaultSetTimout;
  18581. }
  18582. try {
  18583. if (typeof clearTimeout === 'function') {
  18584. cachedClearTimeout = clearTimeout;
  18585. } else {
  18586. cachedClearTimeout = defaultClearTimeout;
  18587. }
  18588. } catch (e) {
  18589. cachedClearTimeout = defaultClearTimeout;
  18590. }
  18591. } ())
  18592. function runTimeout(fun) {
  18593. if (cachedSetTimeout === setTimeout) {
  18594. //normal enviroments in sane situations
  18595. return setTimeout(fun, 0);
  18596. }
  18597. // if setTimeout wasn't available but was latter defined
  18598. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  18599. cachedSetTimeout = setTimeout;
  18600. return setTimeout(fun, 0);
  18601. }
  18602. try {
  18603. // when when somebody has screwed with setTimeout but no I.E. maddness
  18604. return cachedSetTimeout(fun, 0);
  18605. } catch(e){
  18606. try {
  18607. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  18608. return cachedSetTimeout.call(null, fun, 0);
  18609. } catch(e){
  18610. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  18611. return cachedSetTimeout.call(this, fun, 0);
  18612. }
  18613. }
  18614. }
  18615. function runClearTimeout(marker) {
  18616. if (cachedClearTimeout === clearTimeout) {
  18617. //normal enviroments in sane situations
  18618. return clearTimeout(marker);
  18619. }
  18620. // if clearTimeout wasn't available but was latter defined
  18621. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  18622. cachedClearTimeout = clearTimeout;
  18623. return clearTimeout(marker);
  18624. }
  18625. try {
  18626. // when when somebody has screwed with setTimeout but no I.E. maddness
  18627. return cachedClearTimeout(marker);
  18628. } catch (e){
  18629. try {
  18630. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  18631. return cachedClearTimeout.call(null, marker);
  18632. } catch (e){
  18633. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  18634. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  18635. return cachedClearTimeout.call(this, marker);
  18636. }
  18637. }
  18638. }
  18639. var queue = [];
  18640. var draining = false;
  18641. var currentQueue;
  18642. var queueIndex = -1;
  18643. function cleanUpNextTick() {
  18644. if (!draining || !currentQueue) {
  18645. return;
  18646. }
  18647. draining = false;
  18648. if (currentQueue.length) {
  18649. queue = currentQueue.concat(queue);
  18650. } else {
  18651. queueIndex = -1;
  18652. }
  18653. if (queue.length) {
  18654. drainQueue();
  18655. }
  18656. }
  18657. function drainQueue() {
  18658. if (draining) {
  18659. return;
  18660. }
  18661. var timeout = runTimeout(cleanUpNextTick);
  18662. draining = true;
  18663. var len = queue.length;
  18664. while(len) {
  18665. currentQueue = queue;
  18666. queue = [];
  18667. while (++queueIndex < len) {
  18668. if (currentQueue) {
  18669. currentQueue[queueIndex].run();
  18670. }
  18671. }
  18672. queueIndex = -1;
  18673. len = queue.length;
  18674. }
  18675. currentQueue = null;
  18676. draining = false;
  18677. runClearTimeout(timeout);
  18678. }
  18679. process.nextTick = function (fun) {
  18680. var args = new Array(arguments.length - 1);
  18681. if (arguments.length > 1) {
  18682. for (var i = 1; i < arguments.length; i++) {
  18683. args[i - 1] = arguments[i];
  18684. }
  18685. }
  18686. queue.push(new Item(fun, args));
  18687. if (queue.length === 1 && !draining) {
  18688. runTimeout(drainQueue);
  18689. }
  18690. };
  18691. // v8 likes predictible objects
  18692. function Item(fun, array) {
  18693. this.fun = fun;
  18694. this.array = array;
  18695. }
  18696. Item.prototype.run = function () {
  18697. this.fun.apply(null, this.array);
  18698. };
  18699. process.title = 'browser';
  18700. process.browser = true;
  18701. process.env = {};
  18702. process.argv = [];
  18703. process.version = ''; // empty string to avoid regexp issues
  18704. process.versions = {};
  18705. function noop() {}
  18706. process.on = noop;
  18707. process.addListener = noop;
  18708. process.once = noop;
  18709. process.off = noop;
  18710. process.removeListener = noop;
  18711. process.removeAllListeners = noop;
  18712. process.emit = noop;
  18713. process.prependListener = noop;
  18714. process.prependOnceListener = noop;
  18715. process.listeners = function (name) { return [] }
  18716. process.binding = function (name) {
  18717. throw new Error('process.binding is not supported');
  18718. };
  18719. process.cwd = function () { return '/' };
  18720. process.chdir = function (dir) {
  18721. throw new Error('process.chdir is not supported');
  18722. };
  18723. process.umask = function() { return 0; };
  18724. },{}],67:[function(require,module,exports){
  18725. 'use strict';
  18726. /*
  18727. node-bzip - a pure-javascript Node.JS module for decoding bzip2 data
  18728. Copyright (C) 2012 Eli Skeggs
  18729. This library is free software; you can redistribute it and/or
  18730. modify it under the terms of the GNU Lesser General Public
  18731. License as published by the Free Software Foundation; either
  18732. version 2.1 of the License, or (at your option) any later version.
  18733. This library is distributed in the hope that it will be useful,
  18734. but WITHOUT ANY WARRANTY; without even the implied warranty of
  18735. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  18736. Lesser General Public License for more details.
  18737. You should have received a copy of the GNU Lesser General Public
  18738. License along with this library; if not, see
  18739. http://www.gnu.org/licenses/lgpl-2.1.html
  18740. Adapted from bzip2.js, copyright 2011 antimatter15 (antimatter15@gmail.com).
  18741. Based on micro-bunzip by Rob Landley (rob@landley.net).
  18742. Based on bzip2 decompression code by Julian R Seward (jseward@acm.org),
  18743. which also acknowledges contributions by Mike Burrows, David Wheeler,
  18744. Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,
  18745. Robert Sedgewick, and Jon L. Bentley.
  18746. */
  18747. var BITMASK = [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF];
  18748. // offset in bytes
  18749. var BitReader = function BitReader(stream) {
  18750. this.stream = stream;
  18751. this.bitOffset = 0;
  18752. this.curByte = 0;
  18753. this.hasByte = false;
  18754. };
  18755. BitReader.prototype._ensureByte = function () {
  18756. if (!this.hasByte) {
  18757. this.curByte = this.stream.readByte();
  18758. this.hasByte = true;
  18759. }
  18760. };
  18761. // reads bits from the buffer
  18762. BitReader.prototype.read = function (bits) {
  18763. var result = 0;
  18764. while (bits > 0) {
  18765. this._ensureByte();
  18766. var remaining = 8 - this.bitOffset;
  18767. // if we're in a byte
  18768. if (bits >= remaining) {
  18769. result <<= remaining;
  18770. result |= BITMASK[remaining] & this.curByte;
  18771. this.hasByte = false;
  18772. this.bitOffset = 0;
  18773. bits -= remaining;
  18774. } else {
  18775. result <<= bits;
  18776. var shift = remaining - bits;
  18777. result |= (this.curByte & BITMASK[bits] << shift) >> shift;
  18778. this.bitOffset += bits;
  18779. bits = 0;
  18780. }
  18781. }
  18782. return result;
  18783. };
  18784. // seek to an arbitrary point in the buffer (expressed in bits)
  18785. BitReader.prototype.seek = function (pos) {
  18786. var n_bit = pos % 8;
  18787. var n_byte = (pos - n_bit) / 8;
  18788. this.bitOffset = n_bit;
  18789. this.stream.seek(n_byte);
  18790. this.hasByte = false;
  18791. };
  18792. // reads 6 bytes worth of data using the read method
  18793. BitReader.prototype.pi = function () {
  18794. var buf = new Uint8Array(6),
  18795. i;
  18796. for (i = 0; i < buf.length; i++) {
  18797. buf[i] = this.read(8);
  18798. }
  18799. return bufToHex(buf);
  18800. };
  18801. function bufToHex(buf) {
  18802. return Array.prototype.map.call(buf, x => ('00' + x.toString(16)).slice(-2)).join('');
  18803. }
  18804. module.exports = BitReader;
  18805. },{}],68:[function(require,module,exports){
  18806. "use strict";
  18807. /* CRC32, used in Bzip2 implementation.
  18808. * This is a port of CRC32.java from the jbzip2 implementation at
  18809. * https://code.google.com/p/jbzip2
  18810. * which is:
  18811. * Copyright (c) 2011 Matthew Francis
  18812. *
  18813. * Permission is hereby granted, free of charge, to any person
  18814. * obtaining a copy of this software and associated documentation
  18815. * files (the "Software"), to deal in the Software without
  18816. * restriction, including without limitation the rights to use,
  18817. * copy, modify, merge, publish, distribute, sublicense, and/or sell
  18818. * copies of the Software, and to permit persons to whom the
  18819. * Software is furnished to do so, subject to the following
  18820. * conditions:
  18821. *
  18822. * The above copyright notice and this permission notice shall be
  18823. * included in all copies or substantial portions of the Software.
  18824. *
  18825. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  18826. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  18827. * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  18828. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  18829. * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  18830. * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  18831. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  18832. * OTHER DEALINGS IN THE SOFTWARE.
  18833. * This JavaScript implementation is:
  18834. * Copyright (c) 2013 C. Scott Ananian
  18835. * with the same licensing terms as Matthew Francis' original implementation.
  18836. */
  18837. module.exports = function () {
  18838. /**
  18839. * A static CRC lookup table
  18840. */
  18841. var crc32Lookup = new Uint32Array([0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75, 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd, 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d, 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95, 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072, 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba, 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692, 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a, 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a, 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53, 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b, 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3, 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3, 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec, 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654, 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c, 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c, 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4]);
  18842. var CRC32 = function CRC32() {
  18843. /**
  18844. * The current CRC
  18845. */
  18846. var crc = 0xffffffff;
  18847. /**
  18848. * @return The current CRC
  18849. */
  18850. this.getCRC = function () {
  18851. return ~crc >>> 0; // return an unsigned value
  18852. };
  18853. /**
  18854. * Update the CRC with a single byte
  18855. * @param value The value to update the CRC with
  18856. */
  18857. this.updateCRC = function (value) {
  18858. crc = crc << 8 ^ crc32Lookup[(crc >>> 24 ^ value) & 0xff];
  18859. };
  18860. /**
  18861. * Update the CRC with a sequence of identical bytes
  18862. * @param value The value to update the CRC with
  18863. * @param count The number of bytes
  18864. */
  18865. this.updateCRCRun = function (value, count) {
  18866. while (count-- > 0) {
  18867. crc = crc << 8 ^ crc32Lookup[(crc >>> 24 ^ value) & 0xff];
  18868. }
  18869. };
  18870. };
  18871. return CRC32;
  18872. }();
  18873. },{}],69:[function(require,module,exports){
  18874. 'use strict';
  18875. /*
  18876. seek-bzip - a pure-javascript module for seeking within bzip2 data
  18877. Copyright (C) 2013 C. Scott Ananian
  18878. Copyright (C) 2012 Eli Skeggs
  18879. Copyright (C) 2011 Kevin Kwok
  18880. This library is free software; you can redistribute it and/or
  18881. modify it under the terms of the GNU Lesser General Public
  18882. License as published by the Free Software Foundation; either
  18883. version 2.1 of the License, or (at your option) any later version.
  18884. This library is distributed in the hope that it will be useful,
  18885. but WITHOUT ANY WARRANTY; without even the implied warranty of
  18886. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  18887. Lesser General Public License for more details.
  18888. You should have received a copy of the GNU Lesser General Public
  18889. License along with this library; if not, see
  18890. http://www.gnu.org/licenses/lgpl-2.1.html
  18891. Adapted from node-bzip, copyright 2012 Eli Skeggs.
  18892. Adapted from bzip2.js, copyright 2011 Kevin Kwok (antimatter15@gmail.com).
  18893. Based on micro-bunzip by Rob Landley (rob@landley.net).
  18894. Based on bzip2 decompression code by Julian R Seward (jseward@acm.org),
  18895. which also acknowledges contributions by Mike Burrows, David Wheeler,
  18896. Peter Fenwick, Alistair Moffat, Radford Neal, Ian H. Witten,
  18897. Robert Sedgewick, and Jon L. Bentley.
  18898. */
  18899. var BitReader = require('./bitreader');
  18900. var Stream = require('./stream');
  18901. var CRC32 = require('./crc32');
  18902. var MAX_HUFCODE_BITS = 20;
  18903. var MAX_SYMBOLS = 258;
  18904. var SYMBOL_RUNA = 0;
  18905. var SYMBOL_RUNB = 1;
  18906. var MIN_GROUPS = 2;
  18907. var MAX_GROUPS = 6;
  18908. var GROUP_SIZE = 50;
  18909. var WHOLEPI = "314159265359";
  18910. var SQRTPI = "177245385090";
  18911. var mtf = function mtf(array, index) {
  18912. var src = array[index],
  18913. i;
  18914. for (i = index; i > 0; i--) {
  18915. array[i] = array[i - 1];
  18916. }
  18917. array[0] = src;
  18918. return src;
  18919. };
  18920. var Err = {
  18921. OK: 0,
  18922. LAST_BLOCK: -1,
  18923. NOT_BZIP_DATA: -2,
  18924. UNEXPECTED_INPUT_EOF: -3,
  18925. UNEXPECTED_OUTPUT_EOF: -4,
  18926. DATA_ERROR: -5,
  18927. OUT_OF_MEMORY: -6,
  18928. OBSOLETE_INPUT: -7,
  18929. END_OF_BLOCK: -8
  18930. };
  18931. var ErrorMessages = {};
  18932. ErrorMessages[Err.LAST_BLOCK] = "Bad file checksum";
  18933. ErrorMessages[Err.NOT_BZIP_DATA] = "Not bzip data";
  18934. ErrorMessages[Err.UNEXPECTED_INPUT_EOF] = "Unexpected input EOF";
  18935. ErrorMessages[Err.UNEXPECTED_OUTPUT_EOF] = "Unexpected output EOF";
  18936. ErrorMessages[Err.DATA_ERROR] = "Data error";
  18937. ErrorMessages[Err.OUT_OF_MEMORY] = "Out of memory";
  18938. ErrorMessages[Err.OBSOLETE_INPUT] = "Obsolete (pre 0.9.5) bzip format not supported.";
  18939. var _throw = function _throw(status, optDetail) {
  18940. var msg = ErrorMessages[status] || 'unknown error';
  18941. if (optDetail) {
  18942. msg += ': ' + optDetail;
  18943. }
  18944. var e = new TypeError(msg);
  18945. e.errorCode = status;
  18946. throw e;
  18947. };
  18948. var Bunzip = function Bunzip(inputStream, outputStream) {
  18949. this.writePos = this.writeCurrent = this.writeCount = 0;
  18950. this._start_bunzip(inputStream, outputStream);
  18951. };
  18952. Bunzip.prototype._init_block = function () {
  18953. var moreBlocks = this._get_next_block();
  18954. if (!moreBlocks) {
  18955. this.writeCount = -1;
  18956. return false; /* no more blocks */
  18957. }
  18958. this.blockCRC = new CRC32();
  18959. return true;
  18960. };
  18961. /* XXX micro-bunzip uses (inputStream, inputBuffer, len) as arguments */
  18962. Bunzip.prototype._start_bunzip = function (inputStream, outputStream) {
  18963. /* Ensure that file starts with "BZh['1'-'9']." */
  18964. var buf = new Uint8Array(4);
  18965. if (inputStream.read(buf, 0, 4) !== 4 || String.fromCharCode(buf[0], buf[1], buf[2]) !== 'BZh') _throw(Err.NOT_BZIP_DATA, 'bad magic');
  18966. var level = buf[3] - 0x30;
  18967. if (level < 1 || level > 9) _throw(Err.NOT_BZIP_DATA, 'level out of range');
  18968. this.reader = new BitReader(inputStream);
  18969. /* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of
  18970. uncompressed data. Allocate intermediate buffer for block. */
  18971. this.dbufSize = 100000 * level;
  18972. this.nextoutput = 0;
  18973. this.outputStream = outputStream;
  18974. this.streamCRC = 0;
  18975. };
  18976. Bunzip.prototype._get_next_block = function () {
  18977. var i, j, k;
  18978. var reader = this.reader;
  18979. // this is get_next_block() function from micro-bunzip:
  18980. /* Read in header signature and CRC, then validate signature.
  18981. (last block signature means CRC is for whole file, return now) */
  18982. var h = reader.pi();
  18983. if (h === SQRTPI) {
  18984. // last block
  18985. return false; /* no more blocks */
  18986. }
  18987. if (h !== WHOLEPI) _throw(Err.NOT_BZIP_DATA);
  18988. this.targetBlockCRC = reader.read(32) >>> 0; // (convert to unsigned)
  18989. this.streamCRC = (this.targetBlockCRC ^ (this.streamCRC << 1 | this.streamCRC >>> 31)) >>> 0;
  18990. /* We can add support for blockRandomised if anybody complains. There was
  18991. some code for this in busybox 1.0.0-pre3, but nobody ever noticed that
  18992. it didn't actually work. */
  18993. if (reader.read(1)) _throw(Err.OBSOLETE_INPUT);
  18994. var origPointer = reader.read(24);
  18995. if (origPointer > this.dbufSize) _throw(Err.DATA_ERROR, 'initial position out of bounds');
  18996. /* mapping table: if some byte values are never used (encoding things
  18997. like ascii text), the compression code removes the gaps to have fewer
  18998. symbols to deal with, and writes a sparse bitfield indicating which
  18999. values were present. We make a translation table to convert the symbols
  19000. back to the corresponding bytes. */
  19001. var t = reader.read(16);
  19002. var symToByte = new Uint8Array(256),
  19003. symTotal = 0;
  19004. for (i = 0; i < 16; i++) {
  19005. if (t & 1 << 0xF - i) {
  19006. var o = i * 16;
  19007. k = reader.read(16);
  19008. for (j = 0; j < 16; j++) if (k & 1 << 0xF - j) symToByte[symTotal++] = o + j;
  19009. }
  19010. }
  19011. /* How many different huffman coding groups does this block use? */
  19012. var groupCount = reader.read(3);
  19013. if (groupCount < MIN_GROUPS || groupCount > MAX_GROUPS) _throw(Err.DATA_ERROR);
  19014. /* nSelectors: Every GROUP_SIZE many symbols we select a new huffman coding
  19015. group. Read in the group selector list, which is stored as MTF encoded
  19016. bit runs. (MTF=Move To Front, as each value is used it's moved to the
  19017. start of the list.) */
  19018. var nSelectors = reader.read(15);
  19019. if (nSelectors === 0) _throw(Err.DATA_ERROR);
  19020. var mtfSymbol = new Uint8Array(256);
  19021. for (i = 0; i < groupCount; i++) mtfSymbol[i] = i;
  19022. var selectors = new Uint8Array(nSelectors); // was 32768...
  19023. for (i = 0; i < nSelectors; i++) {
  19024. /* Get next value */
  19025. for (j = 0; reader.read(1); j++) if (j >= groupCount) _throw(Err.DATA_ERROR);
  19026. /* Decode MTF to get the next selector */
  19027. selectors[i] = mtf(mtfSymbol, j);
  19028. }
  19029. /* Read the huffman coding tables for each group, which code for symTotal
  19030. literal symbols, plus two run symbols (RUNA, RUNB) */
  19031. var symCount = symTotal + 2;
  19032. var groups = [],
  19033. hufGroup;
  19034. for (j = 0; j < groupCount; j++) {
  19035. var length = new Uint8Array(symCount),
  19036. temp = new Uint16Array(MAX_HUFCODE_BITS + 1);
  19037. /* Read huffman code lengths for each symbol. They're stored in
  19038. a way similar to mtf; record a starting value for the first symbol,
  19039. and an offset from the previous value for everys symbol after that. */
  19040. t = reader.read(5); // lengths
  19041. for (i = 0; i < symCount; i++) {
  19042. for (;;) {
  19043. if (t < 1 || t > MAX_HUFCODE_BITS) _throw(Err.DATA_ERROR);
  19044. /* If first bit is 0, stop. Else second bit indicates whether
  19045. to increment or decrement the value. */
  19046. if (!reader.read(1)) break;
  19047. if (!reader.read(1)) t++;else t--;
  19048. }
  19049. length[i] = t;
  19050. }
  19051. /* Find largest and smallest lengths in this group */
  19052. var minLen, maxLen;
  19053. minLen = maxLen = length[0];
  19054. for (i = 1; i < symCount; i++) {
  19055. if (length[i] > maxLen) maxLen = length[i];else if (length[i] < minLen) minLen = length[i];
  19056. }
  19057. /* Calculate permute[], base[], and limit[] tables from length[].
  19058. *
  19059. * permute[] is the lookup table for converting huffman coded symbols
  19060. * into decoded symbols. base[] is the amount to subtract from the
  19061. * value of a huffman symbol of a given length when using permute[].
  19062. *
  19063. * limit[] indicates the largest numerical value a symbol with a given
  19064. * number of bits can have. This is how the huffman codes can vary in
  19065. * length: each code with a value>limit[length] needs another bit.
  19066. */
  19067. hufGroup = {};
  19068. groups.push(hufGroup);
  19069. hufGroup.permute = new Uint16Array(MAX_SYMBOLS);
  19070. hufGroup.limit = new Uint32Array(MAX_HUFCODE_BITS + 2);
  19071. hufGroup.base = new Uint32Array(MAX_HUFCODE_BITS + 1);
  19072. hufGroup.minLen = minLen;
  19073. hufGroup.maxLen = maxLen;
  19074. /* Calculate permute[]. Concurently, initialize temp[] and limit[]. */
  19075. var pp = 0;
  19076. for (i = minLen; i <= maxLen; i++) {
  19077. temp[i] = hufGroup.limit[i] = 0;
  19078. for (t = 0; t < symCount; t++) if (length[t] === i) hufGroup.permute[pp++] = t;
  19079. }
  19080. /* Count symbols coded for at each bit length */
  19081. for (i = 0; i < symCount; i++) temp[length[i]]++;
  19082. /* Calculate limit[] (the largest symbol-coding value at each bit
  19083. * length, which is (previous limit<<1)+symbols at this level), and
  19084. * base[] (number of symbols to ignore at each bit length, which is
  19085. * limit minus the cumulative count of symbols coded for already). */
  19086. pp = t = 0;
  19087. for (i = minLen; i < maxLen; i++) {
  19088. pp += temp[i];
  19089. /* We read the largest possible symbol size and then unget bits
  19090. after determining how many we need, and those extra bits could
  19091. be set to anything. (They're noise from future symbols.) At
  19092. each level we're really only interested in the first few bits,
  19093. so here we set all the trailing to-be-ignored bits to 1 so they
  19094. don't affect the value>limit[length] comparison. */
  19095. hufGroup.limit[i] = pp - 1;
  19096. pp <<= 1;
  19097. t += temp[i];
  19098. hufGroup.base[i + 1] = pp - t;
  19099. }
  19100. hufGroup.limit[maxLen + 1] = Number.MAX_VALUE; /* Sentinal value for reading next sym. */
  19101. hufGroup.limit[maxLen] = pp + temp[maxLen] - 1;
  19102. hufGroup.base[minLen] = 0;
  19103. }
  19104. /* We've finished reading and digesting the block header. Now read this
  19105. block's huffman coded symbols from the file and undo the huffman coding
  19106. and run length encoding, saving the result into dbuf[dbufCount++]=uc */
  19107. /* Initialize symbol occurrence counters and symbol Move To Front table */
  19108. var byteCount = new Uint32Array(256);
  19109. for (i = 0; i < 256; i++) mtfSymbol[i] = i;
  19110. /* Loop through compressed symbols. */
  19111. var runPos = 0,
  19112. dbufCount = 0,
  19113. selector = 0,
  19114. uc;
  19115. var dbuf = this.dbuf = new Uint32Array(this.dbufSize);
  19116. symCount = 0;
  19117. for (;;) {
  19118. /* Determine which huffman coding group to use. */
  19119. if (!symCount--) {
  19120. symCount = GROUP_SIZE - 1;
  19121. if (selector >= nSelectors) {
  19122. _throw(Err.DATA_ERROR);
  19123. }
  19124. hufGroup = groups[selectors[selector++]];
  19125. }
  19126. /* Read next huffman-coded symbol. */
  19127. i = hufGroup.minLen;
  19128. j = reader.read(i);
  19129. for (;; i++) {
  19130. if (i > hufGroup.maxLen) {
  19131. _throw(Err.DATA_ERROR);
  19132. }
  19133. if (j <= hufGroup.limit[i]) break;
  19134. j = j << 1 | reader.read(1);
  19135. }
  19136. /* Huffman decode value to get nextSym (with bounds checking) */
  19137. j -= hufGroup.base[i];
  19138. if (j < 0 || j >= MAX_SYMBOLS) {
  19139. _throw(Err.DATA_ERROR);
  19140. }
  19141. var nextSym = hufGroup.permute[j];
  19142. /* We have now decoded the symbol, which indicates either a new literal
  19143. byte, or a repeated run of the most recent literal byte. First,
  19144. check if nextSym indicates a repeated run, and if so loop collecting
  19145. how many times to repeat the last literal. */
  19146. if (nextSym === SYMBOL_RUNA || nextSym === SYMBOL_RUNB) {
  19147. /* If this is the start of a new run, zero out counter */
  19148. if (!runPos) {
  19149. runPos = 1;
  19150. t = 0;
  19151. }
  19152. /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at
  19153. each bit position, add 1 or 2 instead. For example,
  19154. 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2.
  19155. You can make any bit pattern that way using 1 less symbol than
  19156. the basic or 0/1 method (except all bits 0, which would use no
  19157. symbols, but a run of length 0 doesn't mean anything in this
  19158. context). Thus space is saved. */
  19159. if (nextSym === SYMBOL_RUNA) t += runPos;else t += 2 * runPos;
  19160. runPos <<= 1;
  19161. continue;
  19162. }
  19163. /* When we hit the first non-run symbol after a run, we now know
  19164. how many times to repeat the last literal, so append that many
  19165. copies to our buffer of decoded symbols (dbuf) now. (The last
  19166. literal used is the one at the head of the mtfSymbol array.) */
  19167. if (runPos) {
  19168. runPos = 0;
  19169. if (dbufCount + t > this.dbufSize) {
  19170. _throw(Err.DATA_ERROR);
  19171. }
  19172. uc = symToByte[mtfSymbol[0]];
  19173. byteCount[uc] += t;
  19174. while (t--) dbuf[dbufCount++] = uc;
  19175. }
  19176. /* Is this the terminating symbol? */
  19177. if (nextSym > symTotal) break;
  19178. /* At this point, nextSym indicates a new literal character. Subtract
  19179. one to get the position in the MTF array at which this literal is
  19180. currently to be found. (Note that the result can't be -1 or 0,
  19181. because 0 and 1 are RUNA and RUNB. But another instance of the
  19182. first symbol in the mtf array, position 0, would have been handled
  19183. as part of a run above. Therefore 1 unused mtf position minus
  19184. 2 non-literal nextSym values equals -1.) */
  19185. if (dbufCount >= this.dbufSize) {
  19186. _throw(Err.DATA_ERROR);
  19187. }
  19188. i = nextSym - 1;
  19189. uc = mtf(mtfSymbol, i);
  19190. uc = symToByte[uc];
  19191. /* We have our literal byte. Save it into dbuf. */
  19192. byteCount[uc]++;
  19193. dbuf[dbufCount++] = uc;
  19194. }
  19195. /* At this point, we've read all the huffman-coded symbols (and repeated
  19196. runs) for this block from the input stream, and decoded them into the
  19197. intermediate buffer. There are dbufCount many decoded bytes in dbuf[].
  19198. Now undo the Burrows-Wheeler transform on dbuf.
  19199. See http://dogma.net/markn/articles/bwt/bwt.htm
  19200. */
  19201. if (origPointer < 0 || origPointer >= dbufCount) {
  19202. _throw(Err.DATA_ERROR);
  19203. }
  19204. /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */
  19205. j = 0;
  19206. for (i = 0; i < 256; i++) {
  19207. k = j + byteCount[i];
  19208. byteCount[i] = j;
  19209. j = k;
  19210. }
  19211. /* Figure out what order dbuf would be in if we sorted it. */
  19212. for (i = 0; i < dbufCount; i++) {
  19213. uc = dbuf[i] & 0xff;
  19214. dbuf[byteCount[uc]] |= i << 8;
  19215. byteCount[uc]++;
  19216. }
  19217. /* Decode first byte by hand to initialize "previous" byte. Note that it
  19218. doesn't get output, and if the first three characters are identical
  19219. it doesn't qualify as a run (hence writeRunCountdown=5). */
  19220. var pos = 0,
  19221. current = 0,
  19222. run = 0;
  19223. if (dbufCount) {
  19224. pos = dbuf[origPointer];
  19225. current = pos & 0xff;
  19226. pos >>= 8;
  19227. run = -1;
  19228. }
  19229. this.writePos = pos;
  19230. this.writeCurrent = current;
  19231. this.writeCount = dbufCount;
  19232. this.writeRun = run;
  19233. return true; /* more blocks to come */
  19234. };
  19235. /* Undo burrows-wheeler transform on intermediate buffer to produce output.
  19236. If start_bunzip was initialized with out_fd=-1, then up to len bytes of
  19237. data are written to outbuf. Return value is number of bytes written or
  19238. error (all errors are negative numbers). If out_fd!=-1, outbuf and len
  19239. are ignored, data is written to out_fd and return is RETVAL_OK or error.
  19240. */
  19241. Bunzip.prototype._read_bunzip = function (outputBuffer, len) {
  19242. var copies, previous, outbyte;
  19243. /* james@jamestaylor.org: writeCount goes to -1 when the buffer is fully
  19244. decoded, which results in this returning RETVAL_LAST_BLOCK, also
  19245. equal to -1... Confusing, I'm returning 0 here to indicate no
  19246. bytes written into the buffer */
  19247. if (this.writeCount < 0) {
  19248. return 0;
  19249. }
  19250. var gotcount = 0;
  19251. var dbuf = this.dbuf,
  19252. pos = this.writePos,
  19253. current = this.writeCurrent;
  19254. var dbufCount = this.writeCount,
  19255. outputsize = this.outputsize;
  19256. var run = this.writeRun;
  19257. while (dbufCount) {
  19258. dbufCount--;
  19259. previous = current;
  19260. pos = dbuf[pos];
  19261. current = pos & 0xff;
  19262. pos >>= 8;
  19263. if (run++ === 3) {
  19264. copies = current;
  19265. outbyte = previous;
  19266. current = -1;
  19267. } else {
  19268. copies = 1;
  19269. outbyte = current;
  19270. }
  19271. this.blockCRC.updateCRCRun(outbyte, copies);
  19272. while (copies--) {
  19273. this.outputStream.writeByte(outbyte);
  19274. this.nextoutput++;
  19275. }
  19276. if (current != previous) run = 0;
  19277. }
  19278. this.writeCount = dbufCount;
  19279. // check CRC
  19280. if (this.blockCRC.getCRC() !== this.targetBlockCRC) {
  19281. _throw(Err.DATA_ERROR, "Bad block CRC " + "(got " + this.blockCRC.getCRC().toString(16) + " expected " + this.targetBlockCRC.toString(16) + ")");
  19282. }
  19283. return this.nextoutput;
  19284. };
  19285. var coerceInputStream = function coerceInputStream(input) {
  19286. if ('readByte' in input) {
  19287. return input;
  19288. }
  19289. var inputStream = new Stream();
  19290. inputStream.pos = 0;
  19291. inputStream.readByte = function () {
  19292. return input[this.pos++];
  19293. };
  19294. inputStream.seek = function (pos) {
  19295. this.pos = pos;
  19296. };
  19297. inputStream.eof = function () {
  19298. return this.pos >= input.length;
  19299. };
  19300. return inputStream;
  19301. };
  19302. var coerceOutputStream = function coerceOutputStream(output) {
  19303. var outputStream = new Stream();
  19304. var resizeOk = true;
  19305. if (output) {
  19306. if (typeof output === 'number') {
  19307. outputStream.buffer = new Uint8Array(output);
  19308. resizeOk = false;
  19309. } else if ('writeByte' in output) {
  19310. return output;
  19311. } else {
  19312. outputStream.buffer = output;
  19313. resizeOk = false;
  19314. }
  19315. } else {
  19316. outputStream.buffer = new Uint8Array(16384);
  19317. }
  19318. outputStream.pos = 0;
  19319. outputStream.writeByte = function (_byte) {
  19320. if (resizeOk && this.pos >= this.buffer.length) {
  19321. var newBuffer = new Uint8Array(this.buffer.length * 2);
  19322. newBuffer.set(this.buffer);
  19323. this.buffer = newBuffer;
  19324. }
  19325. this.buffer[this.pos++] = _byte;
  19326. };
  19327. outputStream.getBuffer = function () {
  19328. // trim buffer
  19329. if (this.pos !== this.buffer.length) {
  19330. if (!resizeOk) throw new TypeError('outputsize does not match decoded input');
  19331. var newBuffer = new Uint8Array(this.pos);
  19332. newBuffer.set(this.buffer.subarray(0, this.pos));
  19333. this.buffer = newBuffer;
  19334. }
  19335. return this.buffer;
  19336. };
  19337. outputStream._coerced = true;
  19338. return outputStream;
  19339. };
  19340. /* Static helper functions */
  19341. Bunzip.Err = Err;
  19342. // 'input' can be a stream or a buffer
  19343. // 'output' can be a stream or a buffer or a number (buffer size)
  19344. Bunzip.decode = function (input, output, multistream) {
  19345. // make a stream from a buffer, if necessary
  19346. var inputStream = coerceInputStream(input);
  19347. var outputStream = coerceOutputStream(output);
  19348. var bz = new Bunzip(inputStream, outputStream);
  19349. while (true) {
  19350. if ('eof' in inputStream && inputStream.eof()) break;
  19351. if (bz._init_block()) {
  19352. bz._read_bunzip();
  19353. } else {
  19354. var targetStreamCRC = bz.reader.read(32) >>> 0; // (convert to unsigned)
  19355. if (targetStreamCRC !== bz.streamCRC) {
  19356. _throw(Err.DATA_ERROR, "Bad stream CRC " + "(got " + bz.streamCRC.toString(16) + " expected " + targetStreamCRC.toString(16) + ")");
  19357. }
  19358. if (multistream && 'eof' in inputStream && !inputStream.eof()) {
  19359. // note that start_bunzip will also resync the bit reader to next byte
  19360. bz._start_bunzip(inputStream, outputStream);
  19361. } else break;
  19362. }
  19363. }
  19364. if ('getBuffer' in outputStream) return outputStream.getBuffer();
  19365. };
  19366. Bunzip.decodeBlock = function (input, pos, output) {
  19367. // make a stream from a buffer, if necessary
  19368. var inputStream = coerceInputStream(input);
  19369. var outputStream = coerceOutputStream(output);
  19370. var bz = new Bunzip(inputStream, outputStream);
  19371. bz.reader.seek(pos);
  19372. /* Fill the decode buffer for the block */
  19373. var moreBlocks = bz._get_next_block();
  19374. if (moreBlocks) {
  19375. /* Init the CRC for writing */
  19376. bz.blockCRC = new CRC32();
  19377. /* Zero this so the current byte from before the seek is not written */
  19378. bz.writeCopies = 0;
  19379. /* Decompress the block and write to stdout */
  19380. bz._read_bunzip();
  19381. // XXX keep writing?
  19382. }
  19383. if ('getBuffer' in outputStream) return outputStream.getBuffer();
  19384. };
  19385. /* Reads bzip2 file from stream or buffer `input`, and invoke
  19386. * `callback(position, size)` once for each bzip2 block,
  19387. * where position gives the starting position (in *bits*)
  19388. * and size gives uncompressed size of the block (in *bytes*). */
  19389. Bunzip.table = function (input, callback, multistream) {
  19390. // make a stream from a buffer, if necessary
  19391. var inputStream = new Stream();
  19392. inputStream.delegate = coerceInputStream(input);
  19393. inputStream.pos = 0;
  19394. inputStream.readByte = function () {
  19395. this.pos++;
  19396. return this.delegate.readByte();
  19397. };
  19398. if (inputStream.delegate.eof) {
  19399. inputStream.eof = inputStream.delegate.eof.bind(inputStream.delegate);
  19400. }
  19401. var outputStream = new Stream();
  19402. outputStream.pos = 0;
  19403. outputStream.writeByte = function () {
  19404. this.pos++;
  19405. };
  19406. var bz = new Bunzip(inputStream, outputStream);
  19407. var blockSize = bz.dbufSize;
  19408. while (true) {
  19409. if ('eof' in inputStream && inputStream.eof()) break;
  19410. var position = inputStream.pos * 8 + bz.reader.bitOffset;
  19411. if (bz.reader.hasByte) {
  19412. position -= 8;
  19413. }
  19414. if (bz._init_block()) {
  19415. var start = outputStream.pos;
  19416. bz._read_bunzip();
  19417. callback(position, outputStream.pos - start);
  19418. } else {
  19419. var crc = bz.reader.read(32); // (but we ignore the crc)
  19420. if (multistream && 'eof' in inputStream && !inputStream.eof()) {
  19421. // note that start_bunzip will also resync the bit reader to next byte
  19422. bz._start_bunzip(inputStream, outputStream);
  19423. console.assert(bz.dbufSize === blockSize, "shouldn't change block size within multistream file");
  19424. } else break;
  19425. }
  19426. }
  19427. };
  19428. Bunzip.Stream = Stream;
  19429. module.exports = Bunzip;
  19430. },{"./bitreader":67,"./crc32":68,"./stream":70}],70:[function(require,module,exports){
  19431. "use strict";
  19432. /* very simple input/output stream interface */
  19433. var Stream = function Stream() {};
  19434. // input streams //////////////
  19435. /** Returns the next byte, or -1 for EOF. */
  19436. Stream.prototype.readByte = function () {
  19437. throw new Error("abstract method readByte() not implemented");
  19438. };
  19439. /** Attempts to fill the buffer; returns number of bytes read, or
  19440. * -1 for EOF. */
  19441. Stream.prototype.read = function (buffer, bufOffset, length) {
  19442. var bytesRead = 0;
  19443. while (bytesRead < length) {
  19444. var c = this.readByte();
  19445. if (c < 0) {
  19446. // EOF
  19447. return bytesRead === 0 ? -1 : bytesRead;
  19448. }
  19449. buffer[bufOffset++] = c;
  19450. bytesRead++;
  19451. }
  19452. return bytesRead;
  19453. };
  19454. Stream.prototype.seek = function (new_pos) {
  19455. throw new Error("abstract method seek() not implemented");
  19456. };
  19457. // output streams ///////////
  19458. Stream.prototype.writeByte = function (_byte) {
  19459. throw new Error("abstract method readByte() not implemented");
  19460. };
  19461. Stream.prototype.write = function (buffer, bufOffset, length) {
  19462. var i;
  19463. for (i = 0; i < length; i++) {
  19464. this.writeByte(buffer[bufOffset++]);
  19465. }
  19466. return length;
  19467. };
  19468. Stream.prototype.flush = function () {};
  19469. module.exports = Stream;
  19470. },{}],71:[function(require,module,exports){
  19471. 'use strict';
  19472. // This is free and unencumbered software released into the public domain.
  19473. // See LICENSE.md for more information.
  19474. //
  19475. // Utilities
  19476. //
  19477. /**
  19478. * @param {number} a The number to test.
  19479. * @param {number} min The minimum value in the range, inclusive.
  19480. * @param {number} max The maximum value in the range, inclusive.
  19481. * @return {boolean} True if a >= min and a <= max.
  19482. */
  19483. function inRange(a, min, max) {
  19484. return min <= a && a <= max;
  19485. }
  19486. /**
  19487. * @param {*} o
  19488. * @return {Object}
  19489. */
  19490. function ToDictionary(o) {
  19491. if (o === undefined) return {};
  19492. if (o === Object(o)) return o;
  19493. throw TypeError('Could not convert argument to dictionary');
  19494. }
  19495. /**
  19496. * @param {string} string Input string of UTF-16 code units.
  19497. * @return {!Array.<number>} Code points.
  19498. */
  19499. function stringToCodePoints(string) {
  19500. // https://heycam.github.io/webidl/#dfn-obtain-unicode
  19501. // 1. Let S be the DOMString value.
  19502. var s = String(string);
  19503. // 2. Let n be the length of S.
  19504. var n = s.length;
  19505. // 3. Initialize i to 0.
  19506. var i = 0;
  19507. // 4. Initialize U to be an empty sequence of Unicode characters.
  19508. var u = [];
  19509. // 5. While i < n:
  19510. while (i < n) {
  19511. // 1. Let c be the code unit in S at index i.
  19512. var c = s.charCodeAt(i);
  19513. // 2. Depending on the value of c:
  19514. // c < 0xD800 or c > 0xDFFF
  19515. if (c < 0xD800 || c > 0xDFFF) {
  19516. // Append to U the Unicode character with code point c.
  19517. u.push(c);
  19518. }
  19519. // 0xDC00 ≤ c ≤ 0xDFFF
  19520. else if (0xDC00 <= c && c <= 0xDFFF) {
  19521. // Append to U a U+FFFD REPLACEMENT CHARACTER.
  19522. u.push(0xFFFD);
  19523. }
  19524. // 0xD800 ≤ c ≤ 0xDBFF
  19525. else if (0xD800 <= c && c <= 0xDBFF) {
  19526. // 1. If i = n−1, then append to U a U+FFFD REPLACEMENT
  19527. // CHARACTER.
  19528. if (i === n - 1) {
  19529. u.push(0xFFFD);
  19530. }
  19531. // 2. Otherwise, i < n−1:
  19532. else {
  19533. // 1. Let d be the code unit in S at index i+1.
  19534. var d = string.charCodeAt(i + 1);
  19535. // 2. If 0xDC00 ≤ d ≤ 0xDFFF, then:
  19536. if (0xDC00 <= d && d <= 0xDFFF) {
  19537. // 1. Let a be c & 0x3FF.
  19538. var a = c & 0x3FF;
  19539. // 2. Let b be d & 0x3FF.
  19540. var b = d & 0x3FF;
  19541. // 3. Append to U the Unicode character with code point
  19542. // 2^16+2^10*a+b.
  19543. u.push(0x10000 + (a << 10) + b);
  19544. // 4. Set i to i+1.
  19545. i += 1;
  19546. }
  19547. // 3. Otherwise, d < 0xDC00 or d > 0xDFFF. Append to U a
  19548. // U+FFFD REPLACEMENT CHARACTER.
  19549. else {
  19550. u.push(0xFFFD);
  19551. }
  19552. }
  19553. }
  19554. // 3. Set i to i+1.
  19555. i += 1;
  19556. }
  19557. // 6. Return U.
  19558. return u;
  19559. }
  19560. /**
  19561. * @param {!Array.<number>} code_points Array of code points.
  19562. * @return {string} string String of UTF-16 code units.
  19563. */
  19564. function codePointsToString(code_points) {
  19565. var s = '';
  19566. for (var i = 0; i < code_points.length; ++i) {
  19567. var cp = code_points[i];
  19568. if (cp <= 0xFFFF) {
  19569. s += String.fromCharCode(cp);
  19570. } else {
  19571. cp -= 0x10000;
  19572. s += String.fromCharCode((cp >> 10) + 0xD800,
  19573. (cp & 0x3FF) + 0xDC00);
  19574. }
  19575. }
  19576. return s;
  19577. }
  19578. //
  19579. // Implementation of Encoding specification
  19580. // https://encoding.spec.whatwg.org/
  19581. //
  19582. //
  19583. // 3. Terminology
  19584. //
  19585. /**
  19586. * End-of-stream is a special token that signifies no more tokens
  19587. * are in the stream.
  19588. * @const
  19589. */ var end_of_stream = -1;
  19590. /**
  19591. * A stream represents an ordered sequence of tokens.
  19592. *
  19593. * @constructor
  19594. * @param {!(Array.<number>|Uint8Array)} tokens Array of tokens that provide the
  19595. * stream.
  19596. */
  19597. function Stream(tokens) {
  19598. /** @type {!Array.<number>} */
  19599. this.tokens = [].slice.call(tokens);
  19600. }
  19601. Stream.prototype = {
  19602. /**
  19603. * @return {boolean} True if end-of-stream has been hit.
  19604. */
  19605. endOfStream: function() {
  19606. return !this.tokens.length;
  19607. },
  19608. /**
  19609. * When a token is read from a stream, the first token in the
  19610. * stream must be returned and subsequently removed, and
  19611. * end-of-stream must be returned otherwise.
  19612. *
  19613. * @return {number} Get the next token from the stream, or
  19614. * end_of_stream.
  19615. */
  19616. read: function() {
  19617. if (!this.tokens.length)
  19618. return end_of_stream;
  19619. return this.tokens.shift();
  19620. },
  19621. /**
  19622. * When one or more tokens are prepended to a stream, those tokens
  19623. * must be inserted, in given order, before the first token in the
  19624. * stream.
  19625. *
  19626. * @param {(number|!Array.<number>)} token The token(s) to prepend to the stream.
  19627. */
  19628. prepend: function(token) {
  19629. if (Array.isArray(token)) {
  19630. var tokens = /**@type {!Array.<number>}*/(token);
  19631. while (tokens.length)
  19632. this.tokens.unshift(tokens.pop());
  19633. } else {
  19634. this.tokens.unshift(token);
  19635. }
  19636. },
  19637. /**
  19638. * When one or more tokens are pushed to a stream, those tokens
  19639. * must be inserted, in given order, after the last token in the
  19640. * stream.
  19641. *
  19642. * @param {(number|!Array.<number>)} token The tokens(s) to prepend to the stream.
  19643. */
  19644. push: function(token) {
  19645. if (Array.isArray(token)) {
  19646. var tokens = /**@type {!Array.<number>}*/(token);
  19647. while (tokens.length)
  19648. this.tokens.push(tokens.shift());
  19649. } else {
  19650. this.tokens.push(token);
  19651. }
  19652. }
  19653. };
  19654. //
  19655. // 4. Encodings
  19656. //
  19657. // 4.1 Encoders and decoders
  19658. /** @const */
  19659. var finished = -1;
  19660. /**
  19661. * @param {boolean} fatal If true, decoding errors raise an exception.
  19662. * @param {number=} opt_code_point Override the standard fallback code point.
  19663. * @return {number} The code point to insert on a decoding error.
  19664. */
  19665. function decoderError(fatal, opt_code_point) {
  19666. if (fatal)
  19667. throw TypeError('Decoder error');
  19668. return opt_code_point || 0xFFFD;
  19669. }
  19670. //
  19671. // 7. API
  19672. //
  19673. /** @const */ var DEFAULT_ENCODING = 'utf-8';
  19674. // 7.1 Interface TextDecoder
  19675. /**
  19676. * @constructor
  19677. * @param {string=} encoding The label of the encoding;
  19678. * defaults to 'utf-8'.
  19679. * @param {Object=} options
  19680. */
  19681. function TextDecoder(encoding, options) {
  19682. if (!(this instanceof TextDecoder)) {
  19683. return new TextDecoder(encoding, options);
  19684. }
  19685. encoding = encoding !== undefined ? String(encoding).toLowerCase() : DEFAULT_ENCODING;
  19686. if (encoding !== DEFAULT_ENCODING) {
  19687. throw new Error('Encoding not supported. Only utf-8 is supported');
  19688. }
  19689. options = ToDictionary(options);
  19690. /** @private @type {boolean} */
  19691. this._streaming = false;
  19692. /** @private @type {boolean} */
  19693. this._BOMseen = false;
  19694. /** @private @type {?Decoder} */
  19695. this._decoder = null;
  19696. /** @private @type {boolean} */
  19697. this._fatal = Boolean(options['fatal']);
  19698. /** @private @type {boolean} */
  19699. this._ignoreBOM = Boolean(options['ignoreBOM']);
  19700. Object.defineProperty(this, 'encoding', {value: 'utf-8'});
  19701. Object.defineProperty(this, 'fatal', {value: this._fatal});
  19702. Object.defineProperty(this, 'ignoreBOM', {value: this._ignoreBOM});
  19703. }
  19704. TextDecoder.prototype = {
  19705. /**
  19706. * @param {ArrayBufferView=} input The buffer of bytes to decode.
  19707. * @param {Object=} options
  19708. * @return {string} The decoded string.
  19709. */
  19710. decode: function decode(input, options) {
  19711. var bytes;
  19712. if (typeof input === 'object' && input instanceof ArrayBuffer) {
  19713. bytes = new Uint8Array(input);
  19714. } else if (typeof input === 'object' && 'buffer' in input &&
  19715. input.buffer instanceof ArrayBuffer) {
  19716. bytes = new Uint8Array(input.buffer,
  19717. input.byteOffset,
  19718. input.byteLength);
  19719. } else {
  19720. bytes = new Uint8Array(0);
  19721. }
  19722. options = ToDictionary(options);
  19723. if (!this._streaming) {
  19724. this._decoder = new UTF8Decoder({fatal: this._fatal});
  19725. this._BOMseen = false;
  19726. }
  19727. this._streaming = Boolean(options['stream']);
  19728. var input_stream = new Stream(bytes);
  19729. var code_points = [];
  19730. /** @type {?(number|!Array.<number>)} */
  19731. var result;
  19732. while (!input_stream.endOfStream()) {
  19733. result = this._decoder.handler(input_stream, input_stream.read());
  19734. if (result === finished)
  19735. break;
  19736. if (result === null)
  19737. continue;
  19738. if (Array.isArray(result))
  19739. code_points.push.apply(code_points, /**@type {!Array.<number>}*/(result));
  19740. else
  19741. code_points.push(result);
  19742. }
  19743. if (!this._streaming) {
  19744. do {
  19745. result = this._decoder.handler(input_stream, input_stream.read());
  19746. if (result === finished)
  19747. break;
  19748. if (result === null)
  19749. continue;
  19750. if (Array.isArray(result))
  19751. code_points.push.apply(code_points, /**@type {!Array.<number>}*/(result));
  19752. else
  19753. code_points.push(result);
  19754. } while (!input_stream.endOfStream());
  19755. this._decoder = null;
  19756. }
  19757. if (code_points.length) {
  19758. // If encoding is one of utf-8, utf-16be, and utf-16le, and
  19759. // ignore BOM flag and BOM seen flag are unset, run these
  19760. // subsubsteps:
  19761. if (['utf-8'].indexOf(this.encoding) !== -1 &&
  19762. !this._ignoreBOM && !this._BOMseen) {
  19763. // If token is U+FEFF, set BOM seen flag.
  19764. if (code_points[0] === 0xFEFF) {
  19765. this._BOMseen = true;
  19766. code_points.shift();
  19767. } else {
  19768. // Otherwise, if token is not end-of-stream, set BOM seen
  19769. // flag and append token to output.
  19770. this._BOMseen = true;
  19771. }
  19772. }
  19773. }
  19774. return codePointsToString(code_points);
  19775. }
  19776. };
  19777. // 7.2 Interface TextEncoder
  19778. /**
  19779. * @constructor
  19780. * @param {string=} encoding The label of the encoding;
  19781. * defaults to 'utf-8'.
  19782. * @param {Object=} options
  19783. */
  19784. function TextEncoder(encoding, options) {
  19785. if (!(this instanceof TextEncoder))
  19786. return new TextEncoder(encoding, options);
  19787. encoding = encoding !== undefined ? String(encoding).toLowerCase() : DEFAULT_ENCODING;
  19788. if (encoding !== DEFAULT_ENCODING) {
  19789. throw new Error('Encoding not supported. Only utf-8 is supported');
  19790. }
  19791. options = ToDictionary(options);
  19792. /** @private @type {boolean} */
  19793. this._streaming = false;
  19794. /** @private @type {?Encoder} */
  19795. this._encoder = null;
  19796. /** @private @type {{fatal: boolean}} */
  19797. this._options = {fatal: Boolean(options['fatal'])};
  19798. Object.defineProperty(this, 'encoding', {value: 'utf-8'});
  19799. }
  19800. TextEncoder.prototype = {
  19801. /**
  19802. * @param {string=} opt_string The string to encode.
  19803. * @param {Object=} options
  19804. * @return {Uint8Array} Encoded bytes, as a Uint8Array.
  19805. */
  19806. encode: function encode(opt_string, options) {
  19807. opt_string = opt_string ? String(opt_string) : '';
  19808. options = ToDictionary(options);
  19809. // NOTE: This option is nonstandard. None of the encodings
  19810. // permitted for encoding (i.e. UTF-8, UTF-16) are stateful,
  19811. // so streaming is not necessary.
  19812. if (!this._streaming)
  19813. this._encoder = new UTF8Encoder(this._options);
  19814. this._streaming = Boolean(options['stream']);
  19815. var bytes = [];
  19816. var input_stream = new Stream(stringToCodePoints(opt_string));
  19817. /** @type {?(number|!Array.<number>)} */
  19818. var result;
  19819. while (!input_stream.endOfStream()) {
  19820. result = this._encoder.handler(input_stream, input_stream.read());
  19821. if (result === finished)
  19822. break;
  19823. if (Array.isArray(result))
  19824. bytes.push.apply(bytes, /**@type {!Array.<number>}*/(result));
  19825. else
  19826. bytes.push(result);
  19827. }
  19828. if (!this._streaming) {
  19829. while (true) {
  19830. result = this._encoder.handler(input_stream, input_stream.read());
  19831. if (result === finished)
  19832. break;
  19833. if (Array.isArray(result))
  19834. bytes.push.apply(bytes, /**@type {!Array.<number>}*/(result));
  19835. else
  19836. bytes.push(result);
  19837. }
  19838. this._encoder = null;
  19839. }
  19840. return new Uint8Array(bytes);
  19841. }
  19842. };
  19843. //
  19844. // 8. The encoding
  19845. //
  19846. // 8.1 utf-8
  19847. /**
  19848. * @constructor
  19849. * @implements {Decoder}
  19850. * @param {{fatal: boolean}} options
  19851. */
  19852. function UTF8Decoder(options) {
  19853. var fatal = options.fatal;
  19854. // utf-8's decoder's has an associated utf-8 code point, utf-8
  19855. // bytes seen, and utf-8 bytes needed (all initially 0), a utf-8
  19856. // lower boundary (initially 0x80), and a utf-8 upper boundary
  19857. // (initially 0xBF).
  19858. var /** @type {number} */ utf8_code_point = 0,
  19859. /** @type {number} */ utf8_bytes_seen = 0,
  19860. /** @type {number} */ utf8_bytes_needed = 0,
  19861. /** @type {number} */ utf8_lower_boundary = 0x80,
  19862. /** @type {number} */ utf8_upper_boundary = 0xBF;
  19863. /**
  19864. * @param {Stream} stream The stream of bytes being decoded.
  19865. * @param {number} bite The next byte read from the stream.
  19866. * @return {?(number|!Array.<number>)} The next code point(s)
  19867. * decoded, or null if not enough data exists in the input
  19868. * stream to decode a complete code point.
  19869. */
  19870. this.handler = function(stream, bite) {
  19871. // 1. If byte is end-of-stream and utf-8 bytes needed is not 0,
  19872. // set utf-8 bytes needed to 0 and return error.
  19873. if (bite === end_of_stream && utf8_bytes_needed !== 0) {
  19874. utf8_bytes_needed = 0;
  19875. return decoderError(fatal);
  19876. }
  19877. // 2. If byte is end-of-stream, return finished.
  19878. if (bite === end_of_stream)
  19879. return finished;
  19880. // 3. If utf-8 bytes needed is 0, based on byte:
  19881. if (utf8_bytes_needed === 0) {
  19882. // 0x00 to 0x7F
  19883. if (inRange(bite, 0x00, 0x7F)) {
  19884. // Return a code point whose value is byte.
  19885. return bite;
  19886. }
  19887. // 0xC2 to 0xDF
  19888. if (inRange(bite, 0xC2, 0xDF)) {
  19889. // Set utf-8 bytes needed to 1 and utf-8 code point to byte
  19890. // − 0xC0.
  19891. utf8_bytes_needed = 1;
  19892. utf8_code_point = bite - 0xC0;
  19893. }
  19894. // 0xE0 to 0xEF
  19895. else if (inRange(bite, 0xE0, 0xEF)) {
  19896. // 1. If byte is 0xE0, set utf-8 lower boundary to 0xA0.
  19897. if (bite === 0xE0)
  19898. utf8_lower_boundary = 0xA0;
  19899. // 2. If byte is 0xED, set utf-8 upper boundary to 0x9F.
  19900. if (bite === 0xED)
  19901. utf8_upper_boundary = 0x9F;
  19902. // 3. Set utf-8 bytes needed to 2 and utf-8 code point to
  19903. // byte − 0xE0.
  19904. utf8_bytes_needed = 2;
  19905. utf8_code_point = bite - 0xE0;
  19906. }
  19907. // 0xF0 to 0xF4
  19908. else if (inRange(bite, 0xF0, 0xF4)) {
  19909. // 1. If byte is 0xF0, set utf-8 lower boundary to 0x90.
  19910. if (bite === 0xF0)
  19911. utf8_lower_boundary = 0x90;
  19912. // 2. If byte is 0xF4, set utf-8 upper boundary to 0x8F.
  19913. if (bite === 0xF4)
  19914. utf8_upper_boundary = 0x8F;
  19915. // 3. Set utf-8 bytes needed to 3 and utf-8 code point to
  19916. // byte − 0xF0.
  19917. utf8_bytes_needed = 3;
  19918. utf8_code_point = bite - 0xF0;
  19919. }
  19920. // Otherwise
  19921. else {
  19922. // Return error.
  19923. return decoderError(fatal);
  19924. }
  19925. // Then (byte is in the range 0xC2 to 0xF4) set utf-8 code
  19926. // point to utf-8 code point << (6 × utf-8 bytes needed) and
  19927. // return continue.
  19928. utf8_code_point = utf8_code_point << (6 * utf8_bytes_needed);
  19929. return null;
  19930. }
  19931. // 4. If byte is not in the range utf-8 lower boundary to utf-8
  19932. // upper boundary, run these substeps:
  19933. if (!inRange(bite, utf8_lower_boundary, utf8_upper_boundary)) {
  19934. // 1. Set utf-8 code point, utf-8 bytes needed, and utf-8
  19935. // bytes seen to 0, set utf-8 lower boundary to 0x80, and set
  19936. // utf-8 upper boundary to 0xBF.
  19937. utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0;
  19938. utf8_lower_boundary = 0x80;
  19939. utf8_upper_boundary = 0xBF;
  19940. // 2. Prepend byte to stream.
  19941. stream.prepend(bite);
  19942. // 3. Return error.
  19943. return decoderError(fatal);
  19944. }
  19945. // 5. Set utf-8 lower boundary to 0x80 and utf-8 upper boundary
  19946. // to 0xBF.
  19947. utf8_lower_boundary = 0x80;
  19948. utf8_upper_boundary = 0xBF;
  19949. // 6. Increase utf-8 bytes seen by one and set utf-8 code point
  19950. // to utf-8 code point + (byte − 0x80) << (6 × (utf-8 bytes
  19951. // needed − utf-8 bytes seen)).
  19952. utf8_bytes_seen += 1;
  19953. utf8_code_point += (bite - 0x80) << (6 * (utf8_bytes_needed - utf8_bytes_seen));
  19954. // 7. If utf-8 bytes seen is not equal to utf-8 bytes needed,
  19955. // continue.
  19956. if (utf8_bytes_seen !== utf8_bytes_needed)
  19957. return null;
  19958. // 8. Let code point be utf-8 code point.
  19959. var code_point = utf8_code_point;
  19960. // 9. Set utf-8 code point, utf-8 bytes needed, and utf-8 bytes
  19961. // seen to 0.
  19962. utf8_code_point = utf8_bytes_needed = utf8_bytes_seen = 0;
  19963. // 10. Return a code point whose value is code point.
  19964. return code_point;
  19965. };
  19966. }
  19967. /**
  19968. * @constructor
  19969. * @implements {Encoder}
  19970. * @param {{fatal: boolean}} options
  19971. */
  19972. function UTF8Encoder(options) {
  19973. var fatal = options.fatal;
  19974. /**
  19975. * @param {Stream} stream Input stream.
  19976. * @param {number} code_point Next code point read from the stream.
  19977. * @return {(number|!Array.<number>)} Byte(s) to emit.
  19978. */
  19979. this.handler = function(stream, code_point) {
  19980. // 1. If code point is end-of-stream, return finished.
  19981. if (code_point === end_of_stream)
  19982. return finished;
  19983. // 2. If code point is in the range U+0000 to U+007F, return a
  19984. // byte whose value is code point.
  19985. if (inRange(code_point, 0x0000, 0x007f))
  19986. return code_point;
  19987. // 3. Set count and offset based on the range code point is in:
  19988. var count, offset;
  19989. // U+0080 to U+07FF: 1 and 0xC0
  19990. if (inRange(code_point, 0x0080, 0x07FF)) {
  19991. count = 1;
  19992. offset = 0xC0;
  19993. }
  19994. // U+0800 to U+FFFF: 2 and 0xE0
  19995. else if (inRange(code_point, 0x0800, 0xFFFF)) {
  19996. count = 2;
  19997. offset = 0xE0;
  19998. }
  19999. // U+10000 to U+10FFFF: 3 and 0xF0
  20000. else if (inRange(code_point, 0x10000, 0x10FFFF)) {
  20001. count = 3;
  20002. offset = 0xF0;
  20003. }
  20004. // 4.Let bytes be a byte sequence whose first byte is (code
  20005. // point >> (6 × count)) + offset.
  20006. var bytes = [(code_point >> (6 * count)) + offset];
  20007. // 5. Run these substeps while count is greater than 0:
  20008. while (count > 0) {
  20009. // 1. Set temp to code point >> (6 × (count − 1)).
  20010. var temp = code_point >> (6 * (count - 1));
  20011. // 2. Append to bytes 0x80 | (temp & 0x3F).
  20012. bytes.push(0x80 | (temp & 0x3F));
  20013. // 3. Decrease count by one.
  20014. count -= 1;
  20015. }
  20016. // 6. Return bytes bytes, in order.
  20017. return bytes;
  20018. };
  20019. }
  20020. exports.TextEncoder = TextEncoder;
  20021. exports.TextDecoder = TextDecoder;
  20022. },{}],72:[function(require,module,exports){
  20023. /*jshint bitwise: false*/
  20024. (function(nacl) {
  20025. 'use strict';
  20026. // Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.
  20027. // Public domain.
  20028. //
  20029. // Implementation derived from TweetNaCl version 20140427.
  20030. // See for details: http://tweetnacl.cr.yp.to/
  20031. var gf = function(init) {
  20032. var i, r = new Float64Array(16);
  20033. if (init) for (i = 0; i < init.length; i++) r[i] = init[i];
  20034. return r;
  20035. };
  20036. // Pluggable, initialized in high-level API below.
  20037. var randombytes = function(/* x, n */) { throw new Error('no PRNG'); };
  20038. var _9 = new Uint8Array(32); _9[0] = 9;
  20039. var gf0 = gf(),
  20040. gf1 = gf([1]),
  20041. _121665 = gf([0xdb41, 1]),
  20042. D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),
  20043. D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),
  20044. X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),
  20045. Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),
  20046. I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);
  20047. function vn(x, xi, y, yi, n) {
  20048. var i,d = 0;
  20049. for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];
  20050. return (1 & ((d - 1) >>> 8)) - 1;
  20051. }
  20052. function crypto_verify_32(x, xi, y, yi) {
  20053. return vn(x,xi,y,yi,32);
  20054. }
  20055. function set25519(r, a) {
  20056. var i;
  20057. for (i = 0; i < 16; i++) r[i] = a[i]|0;
  20058. }
  20059. function car25519(o) {
  20060. var i, v, c = 1;
  20061. for (i = 0; i < 16; i++) {
  20062. v = o[i] + c + 65535;
  20063. c = Math.floor(v / 65536);
  20064. o[i] = v - c * 65536;
  20065. }
  20066. o[0] += c-1 + 37 * (c-1);
  20067. }
  20068. function sel25519(p, q, b) {
  20069. var t, c = ~(b-1);
  20070. for (var i = 0; i < 16; i++) {
  20071. t = c & (p[i] ^ q[i]);
  20072. p[i] ^= t;
  20073. q[i] ^= t;
  20074. }
  20075. }
  20076. function pack25519(o, n) {
  20077. var i, j, b;
  20078. var m = gf(), t = gf();
  20079. for (i = 0; i < 16; i++) t[i] = n[i];
  20080. car25519(t);
  20081. car25519(t);
  20082. car25519(t);
  20083. for (j = 0; j < 2; j++) {
  20084. m[0] = t[0] - 0xffed;
  20085. for (i = 1; i < 15; i++) {
  20086. m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);
  20087. m[i-1] &= 0xffff;
  20088. }
  20089. m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);
  20090. b = (m[15]>>16) & 1;
  20091. m[14] &= 0xffff;
  20092. sel25519(t, m, 1-b);
  20093. }
  20094. for (i = 0; i < 16; i++) {
  20095. o[2*i] = t[i] & 0xff;
  20096. o[2*i+1] = t[i]>>8;
  20097. }
  20098. }
  20099. function neq25519(a, b) {
  20100. var c = new Uint8Array(32), d = new Uint8Array(32);
  20101. pack25519(c, a);
  20102. pack25519(d, b);
  20103. return crypto_verify_32(c, 0, d, 0);
  20104. }
  20105. function par25519(a) {
  20106. var d = new Uint8Array(32);
  20107. pack25519(d, a);
  20108. return d[0] & 1;
  20109. }
  20110. function unpack25519(o, n) {
  20111. var i;
  20112. for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);
  20113. o[15] &= 0x7fff;
  20114. }
  20115. function A(o, a, b) {
  20116. for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];
  20117. }
  20118. function Z(o, a, b) {
  20119. for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];
  20120. }
  20121. function M(o, a, b) {
  20122. var v, c,
  20123. t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,
  20124. t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,
  20125. t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,
  20126. t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,
  20127. b0 = b[0],
  20128. b1 = b[1],
  20129. b2 = b[2],
  20130. b3 = b[3],
  20131. b4 = b[4],
  20132. b5 = b[5],
  20133. b6 = b[6],
  20134. b7 = b[7],
  20135. b8 = b[8],
  20136. b9 = b[9],
  20137. b10 = b[10],
  20138. b11 = b[11],
  20139. b12 = b[12],
  20140. b13 = b[13],
  20141. b14 = b[14],
  20142. b15 = b[15];
  20143. v = a[0];
  20144. t0 += v * b0;
  20145. t1 += v * b1;
  20146. t2 += v * b2;
  20147. t3 += v * b3;
  20148. t4 += v * b4;
  20149. t5 += v * b5;
  20150. t6 += v * b6;
  20151. t7 += v * b7;
  20152. t8 += v * b8;
  20153. t9 += v * b9;
  20154. t10 += v * b10;
  20155. t11 += v * b11;
  20156. t12 += v * b12;
  20157. t13 += v * b13;
  20158. t14 += v * b14;
  20159. t15 += v * b15;
  20160. v = a[1];
  20161. t1 += v * b0;
  20162. t2 += v * b1;
  20163. t3 += v * b2;
  20164. t4 += v * b3;
  20165. t5 += v * b4;
  20166. t6 += v * b5;
  20167. t7 += v * b6;
  20168. t8 += v * b7;
  20169. t9 += v * b8;
  20170. t10 += v * b9;
  20171. t11 += v * b10;
  20172. t12 += v * b11;
  20173. t13 += v * b12;
  20174. t14 += v * b13;
  20175. t15 += v * b14;
  20176. t16 += v * b15;
  20177. v = a[2];
  20178. t2 += v * b0;
  20179. t3 += v * b1;
  20180. t4 += v * b2;
  20181. t5 += v * b3;
  20182. t6 += v * b4;
  20183. t7 += v * b5;
  20184. t8 += v * b6;
  20185. t9 += v * b7;
  20186. t10 += v * b8;
  20187. t11 += v * b9;
  20188. t12 += v * b10;
  20189. t13 += v * b11;
  20190. t14 += v * b12;
  20191. t15 += v * b13;
  20192. t16 += v * b14;
  20193. t17 += v * b15;
  20194. v = a[3];
  20195. t3 += v * b0;
  20196. t4 += v * b1;
  20197. t5 += v * b2;
  20198. t6 += v * b3;
  20199. t7 += v * b4;
  20200. t8 += v * b5;
  20201. t9 += v * b6;
  20202. t10 += v * b7;
  20203. t11 += v * b8;
  20204. t12 += v * b9;
  20205. t13 += v * b10;
  20206. t14 += v * b11;
  20207. t15 += v * b12;
  20208. t16 += v * b13;
  20209. t17 += v * b14;
  20210. t18 += v * b15;
  20211. v = a[4];
  20212. t4 += v * b0;
  20213. t5 += v * b1;
  20214. t6 += v * b2;
  20215. t7 += v * b3;
  20216. t8 += v * b4;
  20217. t9 += v * b5;
  20218. t10 += v * b6;
  20219. t11 += v * b7;
  20220. t12 += v * b8;
  20221. t13 += v * b9;
  20222. t14 += v * b10;
  20223. t15 += v * b11;
  20224. t16 += v * b12;
  20225. t17 += v * b13;
  20226. t18 += v * b14;
  20227. t19 += v * b15;
  20228. v = a[5];
  20229. t5 += v * b0;
  20230. t6 += v * b1;
  20231. t7 += v * b2;
  20232. t8 += v * b3;
  20233. t9 += v * b4;
  20234. t10 += v * b5;
  20235. t11 += v * b6;
  20236. t12 += v * b7;
  20237. t13 += v * b8;
  20238. t14 += v * b9;
  20239. t15 += v * b10;
  20240. t16 += v * b11;
  20241. t17 += v * b12;
  20242. t18 += v * b13;
  20243. t19 += v * b14;
  20244. t20 += v * b15;
  20245. v = a[6];
  20246. t6 += v * b0;
  20247. t7 += v * b1;
  20248. t8 += v * b2;
  20249. t9 += v * b3;
  20250. t10 += v * b4;
  20251. t11 += v * b5;
  20252. t12 += v * b6;
  20253. t13 += v * b7;
  20254. t14 += v * b8;
  20255. t15 += v * b9;
  20256. t16 += v * b10;
  20257. t17 += v * b11;
  20258. t18 += v * b12;
  20259. t19 += v * b13;
  20260. t20 += v * b14;
  20261. t21 += v * b15;
  20262. v = a[7];
  20263. t7 += v * b0;
  20264. t8 += v * b1;
  20265. t9 += v * b2;
  20266. t10 += v * b3;
  20267. t11 += v * b4;
  20268. t12 += v * b5;
  20269. t13 += v * b6;
  20270. t14 += v * b7;
  20271. t15 += v * b8;
  20272. t16 += v * b9;
  20273. t17 += v * b10;
  20274. t18 += v * b11;
  20275. t19 += v * b12;
  20276. t20 += v * b13;
  20277. t21 += v * b14;
  20278. t22 += v * b15;
  20279. v = a[8];
  20280. t8 += v * b0;
  20281. t9 += v * b1;
  20282. t10 += v * b2;
  20283. t11 += v * b3;
  20284. t12 += v * b4;
  20285. t13 += v * b5;
  20286. t14 += v * b6;
  20287. t15 += v * b7;
  20288. t16 += v * b8;
  20289. t17 += v * b9;
  20290. t18 += v * b10;
  20291. t19 += v * b11;
  20292. t20 += v * b12;
  20293. t21 += v * b13;
  20294. t22 += v * b14;
  20295. t23 += v * b15;
  20296. v = a[9];
  20297. t9 += v * b0;
  20298. t10 += v * b1;
  20299. t11 += v * b2;
  20300. t12 += v * b3;
  20301. t13 += v * b4;
  20302. t14 += v * b5;
  20303. t15 += v * b6;
  20304. t16 += v * b7;
  20305. t17 += v * b8;
  20306. t18 += v * b9;
  20307. t19 += v * b10;
  20308. t20 += v * b11;
  20309. t21 += v * b12;
  20310. t22 += v * b13;
  20311. t23 += v * b14;
  20312. t24 += v * b15;
  20313. v = a[10];
  20314. t10 += v * b0;
  20315. t11 += v * b1;
  20316. t12 += v * b2;
  20317. t13 += v * b3;
  20318. t14 += v * b4;
  20319. t15 += v * b5;
  20320. t16 += v * b6;
  20321. t17 += v * b7;
  20322. t18 += v * b8;
  20323. t19 += v * b9;
  20324. t20 += v * b10;
  20325. t21 += v * b11;
  20326. t22 += v * b12;
  20327. t23 += v * b13;
  20328. t24 += v * b14;
  20329. t25 += v * b15;
  20330. v = a[11];
  20331. t11 += v * b0;
  20332. t12 += v * b1;
  20333. t13 += v * b2;
  20334. t14 += v * b3;
  20335. t15 += v * b4;
  20336. t16 += v * b5;
  20337. t17 += v * b6;
  20338. t18 += v * b7;
  20339. t19 += v * b8;
  20340. t20 += v * b9;
  20341. t21 += v * b10;
  20342. t22 += v * b11;
  20343. t23 += v * b12;
  20344. t24 += v * b13;
  20345. t25 += v * b14;
  20346. t26 += v * b15;
  20347. v = a[12];
  20348. t12 += v * b0;
  20349. t13 += v * b1;
  20350. t14 += v * b2;
  20351. t15 += v * b3;
  20352. t16 += v * b4;
  20353. t17 += v * b5;
  20354. t18 += v * b6;
  20355. t19 += v * b7;
  20356. t20 += v * b8;
  20357. t21 += v * b9;
  20358. t22 += v * b10;
  20359. t23 += v * b11;
  20360. t24 += v * b12;
  20361. t25 += v * b13;
  20362. t26 += v * b14;
  20363. t27 += v * b15;
  20364. v = a[13];
  20365. t13 += v * b0;
  20366. t14 += v * b1;
  20367. t15 += v * b2;
  20368. t16 += v * b3;
  20369. t17 += v * b4;
  20370. t18 += v * b5;
  20371. t19 += v * b6;
  20372. t20 += v * b7;
  20373. t21 += v * b8;
  20374. t22 += v * b9;
  20375. t23 += v * b10;
  20376. t24 += v * b11;
  20377. t25 += v * b12;
  20378. t26 += v * b13;
  20379. t27 += v * b14;
  20380. t28 += v * b15;
  20381. v = a[14];
  20382. t14 += v * b0;
  20383. t15 += v * b1;
  20384. t16 += v * b2;
  20385. t17 += v * b3;
  20386. t18 += v * b4;
  20387. t19 += v * b5;
  20388. t20 += v * b6;
  20389. t21 += v * b7;
  20390. t22 += v * b8;
  20391. t23 += v * b9;
  20392. t24 += v * b10;
  20393. t25 += v * b11;
  20394. t26 += v * b12;
  20395. t27 += v * b13;
  20396. t28 += v * b14;
  20397. t29 += v * b15;
  20398. v = a[15];
  20399. t15 += v * b0;
  20400. t16 += v * b1;
  20401. t17 += v * b2;
  20402. t18 += v * b3;
  20403. t19 += v * b4;
  20404. t20 += v * b5;
  20405. t21 += v * b6;
  20406. t22 += v * b7;
  20407. t23 += v * b8;
  20408. t24 += v * b9;
  20409. t25 += v * b10;
  20410. t26 += v * b11;
  20411. t27 += v * b12;
  20412. t28 += v * b13;
  20413. t29 += v * b14;
  20414. t30 += v * b15;
  20415. t0 += 38 * t16;
  20416. t1 += 38 * t17;
  20417. t2 += 38 * t18;
  20418. t3 += 38 * t19;
  20419. t4 += 38 * t20;
  20420. t5 += 38 * t21;
  20421. t6 += 38 * t22;
  20422. t7 += 38 * t23;
  20423. t8 += 38 * t24;
  20424. t9 += 38 * t25;
  20425. t10 += 38 * t26;
  20426. t11 += 38 * t27;
  20427. t12 += 38 * t28;
  20428. t13 += 38 * t29;
  20429. t14 += 38 * t30;
  20430. // t15 left as is
  20431. // first car
  20432. c = 1;
  20433. v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
  20434. v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
  20435. v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
  20436. v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
  20437. v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
  20438. v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
  20439. v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
  20440. v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
  20441. v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
  20442. v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
  20443. v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
  20444. v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
  20445. v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
  20446. v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
  20447. v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
  20448. v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
  20449. t0 += c-1 + 37 * (c-1);
  20450. // second car
  20451. c = 1;
  20452. v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
  20453. v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
  20454. v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
  20455. v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
  20456. v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
  20457. v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
  20458. v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
  20459. v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
  20460. v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
  20461. v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
  20462. v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
  20463. v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
  20464. v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
  20465. v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
  20466. v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
  20467. v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
  20468. t0 += c-1 + 37 * (c-1);
  20469. o[ 0] = t0;
  20470. o[ 1] = t1;
  20471. o[ 2] = t2;
  20472. o[ 3] = t3;
  20473. o[ 4] = t4;
  20474. o[ 5] = t5;
  20475. o[ 6] = t6;
  20476. o[ 7] = t7;
  20477. o[ 8] = t8;
  20478. o[ 9] = t9;
  20479. o[10] = t10;
  20480. o[11] = t11;
  20481. o[12] = t12;
  20482. o[13] = t13;
  20483. o[14] = t14;
  20484. o[15] = t15;
  20485. }
  20486. function S(o, a) {
  20487. M(o, a, a);
  20488. }
  20489. function inv25519(o, i) {
  20490. var c = gf();
  20491. var a;
  20492. for (a = 0; a < 16; a++) c[a] = i[a];
  20493. for (a = 253; a >= 0; a--) {
  20494. S(c, c);
  20495. if(a !== 2 && a !== 4) M(c, c, i);
  20496. }
  20497. for (a = 0; a < 16; a++) o[a] = c[a];
  20498. }
  20499. function pow2523(o, i) {
  20500. var c = gf();
  20501. var a;
  20502. for (a = 0; a < 16; a++) c[a] = i[a];
  20503. for (a = 250; a >= 0; a--) {
  20504. S(c, c);
  20505. if(a !== 1) M(c, c, i);
  20506. }
  20507. for (a = 0; a < 16; a++) o[a] = c[a];
  20508. }
  20509. function crypto_scalarmult(q, n, p) {
  20510. var z = new Uint8Array(32);
  20511. var x = new Float64Array(80), r, i;
  20512. var a = gf(), b = gf(), c = gf(),
  20513. d = gf(), e = gf(), f = gf();
  20514. for (i = 0; i < 31; i++) z[i] = n[i];
  20515. z[31]=(n[31]&127)|64;
  20516. z[0]&=248;
  20517. unpack25519(x,p);
  20518. for (i = 0; i < 16; i++) {
  20519. b[i]=x[i];
  20520. d[i]=a[i]=c[i]=0;
  20521. }
  20522. a[0]=d[0]=1;
  20523. for (i=254; i>=0; --i) {
  20524. r=(z[i>>>3]>>>(i&7))&1;
  20525. sel25519(a,b,r);
  20526. sel25519(c,d,r);
  20527. A(e,a,c);
  20528. Z(a,a,c);
  20529. A(c,b,d);
  20530. Z(b,b,d);
  20531. S(d,e);
  20532. S(f,a);
  20533. M(a,c,a);
  20534. M(c,b,e);
  20535. A(e,a,c);
  20536. Z(a,a,c);
  20537. S(b,a);
  20538. Z(c,d,f);
  20539. M(a,c,_121665);
  20540. A(a,a,d);
  20541. M(c,c,a);
  20542. M(a,d,f);
  20543. M(d,b,x);
  20544. S(b,e);
  20545. sel25519(a,b,r);
  20546. sel25519(c,d,r);
  20547. }
  20548. for (i = 0; i < 16; i++) {
  20549. x[i+16]=a[i];
  20550. x[i+32]=c[i];
  20551. x[i+48]=b[i];
  20552. x[i+64]=d[i];
  20553. }
  20554. var x32 = x.subarray(32);
  20555. var x16 = x.subarray(16);
  20556. inv25519(x32,x32);
  20557. M(x16,x16,x32);
  20558. pack25519(q,x16);
  20559. return 0;
  20560. }
  20561. function crypto_scalarmult_base(q, n) {
  20562. return crypto_scalarmult(q, n, _9);
  20563. }
  20564. function crypto_box_keypair(y, x) {
  20565. randombytes(x, 32);
  20566. return crypto_scalarmult_base(y, x);
  20567. }
  20568. function add(p, q) {
  20569. var a = gf(), b = gf(), c = gf(),
  20570. d = gf(), e = gf(), f = gf(),
  20571. g = gf(), h = gf(), t = gf();
  20572. Z(a, p[1], p[0]);
  20573. Z(t, q[1], q[0]);
  20574. M(a, a, t);
  20575. A(b, p[0], p[1]);
  20576. A(t, q[0], q[1]);
  20577. M(b, b, t);
  20578. M(c, p[3], q[3]);
  20579. M(c, c, D2);
  20580. M(d, p[2], q[2]);
  20581. A(d, d, d);
  20582. Z(e, b, a);
  20583. Z(f, d, c);
  20584. A(g, d, c);
  20585. A(h, b, a);
  20586. M(p[0], e, f);
  20587. M(p[1], h, g);
  20588. M(p[2], g, f);
  20589. M(p[3], e, h);
  20590. }
  20591. function cswap(p, q, b) {
  20592. var i;
  20593. for (i = 0; i < 4; i++) {
  20594. sel25519(p[i], q[i], b);
  20595. }
  20596. }
  20597. function pack(r, p) {
  20598. var tx = gf(), ty = gf(), zi = gf();
  20599. inv25519(zi, p[2]);
  20600. M(tx, p[0], zi);
  20601. M(ty, p[1], zi);
  20602. pack25519(r, ty);
  20603. r[31] ^= par25519(tx) << 7;
  20604. }
  20605. function scalarmult(p, q, s) {
  20606. var b, i;
  20607. set25519(p[0], gf0);
  20608. set25519(p[1], gf1);
  20609. set25519(p[2], gf1);
  20610. set25519(p[3], gf0);
  20611. for (i = 255; i >= 0; --i) {
  20612. b = (s[(i/8)|0] >> (i&7)) & 1;
  20613. cswap(p, q, b);
  20614. add(q, p);
  20615. add(p, p);
  20616. cswap(p, q, b);
  20617. }
  20618. }
  20619. function scalarbase(p, s) {
  20620. var q = [gf(), gf(), gf(), gf()];
  20621. set25519(q[0], X);
  20622. set25519(q[1], Y);
  20623. set25519(q[2], gf1);
  20624. M(q[3], X, Y);
  20625. scalarmult(p, q, s);
  20626. }
  20627. function crypto_sign_keypair(pk, sk, seeded) {
  20628. var d;
  20629. var p = [gf(), gf(), gf(), gf()];
  20630. var i;
  20631. if (!seeded) randombytes(sk, 32);
  20632. d = nacl.hash(sk.subarray(0, 32));
  20633. d[0] &= 248;
  20634. d[31] &= 127;
  20635. d[31] |= 64;
  20636. scalarbase(p, d);
  20637. pack(pk, p);
  20638. for (i = 0; i < 32; i++) sk[i+32] = pk[i];
  20639. return 0;
  20640. }
  20641. var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);
  20642. function modL(r, x) {
  20643. var carry, i, j, k;
  20644. for (i = 63; i >= 32; --i) {
  20645. carry = 0;
  20646. for (j = i - 32, k = i - 12; j < k; ++j) {
  20647. x[j] += carry - 16 * x[i] * L[j - (i - 32)];
  20648. carry = (x[j] + 128) >> 8;
  20649. x[j] -= carry * 256;
  20650. }
  20651. x[j] += carry;
  20652. x[i] = 0;
  20653. }
  20654. carry = 0;
  20655. for (j = 0; j < 32; j++) {
  20656. x[j] += carry - (x[31] >> 4) * L[j];
  20657. carry = x[j] >> 8;
  20658. x[j] &= 255;
  20659. }
  20660. for (j = 0; j < 32; j++) x[j] -= carry * L[j];
  20661. for (i = 0; i < 32; i++) {
  20662. x[i+1] += x[i] >> 8;
  20663. r[i] = x[i] & 255;
  20664. }
  20665. }
  20666. function reduce(r) {
  20667. var x = new Float64Array(64), i;
  20668. for (i = 0; i < 64; i++) x[i] = r[i];
  20669. for (i = 0; i < 64; i++) r[i] = 0;
  20670. modL(r, x);
  20671. }
  20672. // Note: difference from C - smlen returned, not passed as argument.
  20673. function crypto_sign(sm, m, n, sk) {
  20674. var d, h, r;
  20675. var i, j, x = new Float64Array(64);
  20676. var p = [gf(), gf(), gf(), gf()];
  20677. d = nacl.hash(sk.subarray(0, 32));
  20678. d[0] &= 248;
  20679. d[31] &= 127;
  20680. d[31] |= 64;
  20681. var smlen = n + 64;
  20682. for (i = 0; i < n; i++) sm[64 + i] = m[i];
  20683. for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];
  20684. r = nacl.hash(sm.subarray(32, smlen));
  20685. reduce(r);
  20686. scalarbase(p, r);
  20687. pack(sm, p);
  20688. for (i = 32; i < 64; i++) sm[i] = sk[i];
  20689. h = nacl.hash(sm.subarray(0, smlen));
  20690. reduce(h);
  20691. for (i = 0; i < 64; i++) x[i] = 0;
  20692. for (i = 0; i < 32; i++) x[i] = r[i];
  20693. for (i = 0; i < 32; i++) {
  20694. for (j = 0; j < 32; j++) {
  20695. x[i+j] += h[i] * d[j];
  20696. }
  20697. }
  20698. modL(sm.subarray(32), x);
  20699. return smlen;
  20700. }
  20701. function unpackneg(r, p) {
  20702. var t = gf(), chk = gf(), num = gf(),
  20703. den = gf(), den2 = gf(), den4 = gf(),
  20704. den6 = gf();
  20705. set25519(r[2], gf1);
  20706. unpack25519(r[1], p);
  20707. S(num, r[1]);
  20708. M(den, num, D);
  20709. Z(num, num, r[2]);
  20710. A(den, r[2], den);
  20711. S(den2, den);
  20712. S(den4, den2);
  20713. M(den6, den4, den2);
  20714. M(t, den6, num);
  20715. M(t, t, den);
  20716. pow2523(t, t);
  20717. M(t, t, num);
  20718. M(t, t, den);
  20719. M(t, t, den);
  20720. M(r[0], t, den);
  20721. S(chk, r[0]);
  20722. M(chk, chk, den);
  20723. if (neq25519(chk, num)) M(r[0], r[0], I);
  20724. S(chk, r[0]);
  20725. M(chk, chk, den);
  20726. if (neq25519(chk, num)) return -1;
  20727. if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);
  20728. M(r[3], r[0], r[1]);
  20729. return 0;
  20730. }
  20731. function crypto_sign_open(m, sm, n, pk) {
  20732. var i, mlen;
  20733. var t = new Uint8Array(32), h;
  20734. var p = [gf(), gf(), gf(), gf()],
  20735. q = [gf(), gf(), gf(), gf()];
  20736. mlen = -1;
  20737. if (n < 64) return -1;
  20738. if (unpackneg(q, pk)) return -1;
  20739. for (i = 0; i < n; i++) m[i] = sm[i];
  20740. for (i = 0; i < 32; i++) m[i+32] = pk[i];
  20741. h = nacl.hash(m.subarray(0, n));
  20742. reduce(h);
  20743. scalarmult(p, q, h);
  20744. scalarbase(q, sm.subarray(32));
  20745. add(p, q);
  20746. pack(t, p);
  20747. n -= 64;
  20748. if (crypto_verify_32(sm, 0, t, 0)) {
  20749. for (i = 0; i < n; i++) m[i] = 0;
  20750. return -1;
  20751. }
  20752. for (i = 0; i < n; i++) m[i] = sm[i + 64];
  20753. mlen = n;
  20754. return mlen;
  20755. }
  20756. var crypto_scalarmult_BYTES = 32,
  20757. crypto_scalarmult_SCALARBYTES = 32,
  20758. crypto_box_PUBLICKEYBYTES = 32,
  20759. crypto_box_SECRETKEYBYTES = 32,
  20760. crypto_sign_BYTES = 64,
  20761. crypto_sign_PUBLICKEYBYTES = 32,
  20762. crypto_sign_SECRETKEYBYTES = 64,
  20763. crypto_sign_SEEDBYTES = 32;
  20764. function checkArrayTypes() {
  20765. for (var i = 0; i < arguments.length; i++) {
  20766. if (!(arguments[i] instanceof Uint8Array))
  20767. throw new TypeError('unexpected type, use Uint8Array');
  20768. }
  20769. }
  20770. function cleanup(arr) {
  20771. for (var i = 0; i < arr.length; i++) arr[i] = 0;
  20772. }
  20773. nacl.scalarMult = function(n, p) {
  20774. checkArrayTypes(n, p);
  20775. if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');
  20776. if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');
  20777. var q = new Uint8Array(crypto_scalarmult_BYTES);
  20778. crypto_scalarmult(q, n, p);
  20779. return q;
  20780. };
  20781. nacl.box = {};
  20782. nacl.box.keyPair = function() {
  20783. var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
  20784. var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);
  20785. crypto_box_keypair(pk, sk);
  20786. return {publicKey: pk, secretKey: sk};
  20787. };
  20788. nacl.box.keyPair.fromSecretKey = function(secretKey) {
  20789. checkArrayTypes(secretKey);
  20790. if (secretKey.length !== crypto_box_SECRETKEYBYTES)
  20791. throw new Error('bad secret key size');
  20792. var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
  20793. crypto_scalarmult_base(pk, secretKey);
  20794. return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
  20795. };
  20796. nacl.sign = function(msg, secretKey) {
  20797. checkArrayTypes(msg, secretKey);
  20798. if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
  20799. throw new Error('bad secret key size');
  20800. var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);
  20801. crypto_sign(signedMsg, msg, msg.length, secretKey);
  20802. return signedMsg;
  20803. };
  20804. nacl.sign.detached = function(msg, secretKey) {
  20805. var signedMsg = nacl.sign(msg, secretKey);
  20806. var sig = new Uint8Array(crypto_sign_BYTES);
  20807. for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];
  20808. return sig;
  20809. };
  20810. nacl.sign.detached.verify = function(msg, sig, publicKey) {
  20811. checkArrayTypes(msg, sig, publicKey);
  20812. if (sig.length !== crypto_sign_BYTES)
  20813. throw new Error('bad signature size');
  20814. if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
  20815. throw new Error('bad public key size');
  20816. var sm = new Uint8Array(crypto_sign_BYTES + msg.length);
  20817. var m = new Uint8Array(crypto_sign_BYTES + msg.length);
  20818. var i;
  20819. for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];
  20820. for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];
  20821. return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);
  20822. };
  20823. nacl.sign.keyPair = function() {
  20824. var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
  20825. var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
  20826. crypto_sign_keypair(pk, sk);
  20827. return {publicKey: pk, secretKey: sk};
  20828. };
  20829. nacl.sign.keyPair.fromSecretKey = function(secretKey) {
  20830. checkArrayTypes(secretKey);
  20831. if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
  20832. throw new Error('bad secret key size');
  20833. var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
  20834. for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];
  20835. return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
  20836. };
  20837. nacl.sign.keyPair.fromSeed = function(seed) {
  20838. checkArrayTypes(seed);
  20839. if (seed.length !== crypto_sign_SEEDBYTES)
  20840. throw new Error('bad seed size');
  20841. var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
  20842. var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
  20843. for (var i = 0; i < 32; i++) sk[i] = seed[i];
  20844. crypto_sign_keypair(pk, sk, true);
  20845. return {publicKey: pk, secretKey: sk};
  20846. };
  20847. nacl.setPRNG = function(fn) {
  20848. randombytes = fn;
  20849. };
  20850. (function() {
  20851. // Initialize PRNG if environment provides CSPRNG.
  20852. // If not, methods calling randombytes will throw.
  20853. var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;
  20854. if (crypto && crypto.getRandomValues) {
  20855. // Browsers.
  20856. var QUOTA = 65536;
  20857. nacl.setPRNG(function(x, n) {
  20858. var i, v = new Uint8Array(n);
  20859. for (i = 0; i < n; i += QUOTA) {
  20860. crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
  20861. }
  20862. for (i = 0; i < n; i++) x[i] = v[i];
  20863. cleanup(v);
  20864. });
  20865. } else if (typeof require !== 'undefined') {
  20866. // Node.js.
  20867. crypto = require('crypto');
  20868. if (crypto && crypto.randomBytes) {
  20869. nacl.setPRNG(function(x, n) {
  20870. var i, v = crypto.randomBytes(n);
  20871. for (i = 0; i < n; i++) x[i] = v[i];
  20872. cleanup(v);
  20873. });
  20874. }
  20875. }
  20876. })();
  20877. })(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {}));
  20878. },{"crypto":"crypto"}],73:[function(require,module,exports){
  20879. 'use strict';
  20880. Object.defineProperty(exports, "__esModule", {
  20881. value: true
  20882. });
  20883. exports.webToNode = exports.nodeToWeb = undefined;
  20884. var _util = require('./util');
  20885. var _streams = require('./streams');
  20886. var _streams2 = _interopRequireDefault(_streams);
  20887. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  20888. const NodeReadableStream = _util.isNode && require('stream').Readable;
  20889. /**
  20890. * Web / node stream conversion functions
  20891. * From https://github.com/gwicke/node-web-streams
  20892. */
  20893. let nodeToWeb;
  20894. let webToNode;
  20895. if (NodeReadableStream) {
  20896. /**
  20897. * Convert a Node Readable Stream to a Web ReadableStream
  20898. * @param {Readable} nodeStream
  20899. * @returns {ReadableStream}
  20900. */
  20901. exports.nodeToWeb = nodeToWeb = function nodeToWeb(nodeStream) {
  20902. return new ReadableStream({
  20903. start(controller) {
  20904. nodeStream.pause();
  20905. nodeStream.on('data', chunk => {
  20906. controller.enqueue(chunk);
  20907. nodeStream.pause();
  20908. });
  20909. nodeStream.on('end', () => controller.close());
  20910. nodeStream.on('error', e => controller.error(e));
  20911. },
  20912. pull() {
  20913. nodeStream.resume();
  20914. },
  20915. cancel(reason) {
  20916. nodeStream.pause();
  20917. if (nodeStream.cancel) {
  20918. return nodeStream.cancel(reason);
  20919. }
  20920. }
  20921. });
  20922. };
  20923. class NodeReadable extends NodeReadableStream {
  20924. constructor(webStream, options) {
  20925. super(options);
  20926. this._webStream = webStream;
  20927. this._reader = _streams2.default.getReader(webStream);
  20928. this._reading = false;
  20929. this._doneReadingPromise = Promise.resolve();
  20930. this._cancelling = false;
  20931. }
  20932. _read(size) {
  20933. if (this._reading || this._cancelling) {
  20934. return;
  20935. }
  20936. this._reading = true;
  20937. const doRead = async () => {
  20938. try {
  20939. while (true) {
  20940. var _ref = await this._reader.read();
  20941. const done = _ref.done,
  20942. value = _ref.value;
  20943. if (done) {
  20944. this.push(null);
  20945. break;
  20946. }
  20947. if (!this.push(value) || this._cancelling) {
  20948. this._reading = false;
  20949. break;
  20950. }
  20951. }
  20952. } catch (e) {
  20953. this.emit('error', e);
  20954. }
  20955. };
  20956. this._doneReadingPromise = doRead();
  20957. }
  20958. async cancel(reason) {
  20959. this._cancelling = true;
  20960. await this._doneReadingPromise;
  20961. this._reader.releaseLock();
  20962. return this._webStream.cancel(reason);
  20963. }
  20964. }
  20965. /**
  20966. * Convert a Web ReadableStream to a Node Readable Stream
  20967. * @param {ReadableStream} webStream
  20968. * @returns {Readable}
  20969. */
  20970. exports.webToNode = webToNode = function webToNode(webStream) {
  20971. return new NodeReadable(webStream);
  20972. };
  20973. }
  20974. exports.nodeToWeb = nodeToWeb;
  20975. exports.webToNode = webToNode;
  20976. },{"./streams":75,"./util":76,"stream":"stream"}],74:[function(require,module,exports){
  20977. 'use strict';
  20978. Object.defineProperty(exports, "__esModule", {
  20979. value: true
  20980. });
  20981. exports.externalBuffer = exports.Reader = undefined;
  20982. var _streams = require('./streams');
  20983. var _streams2 = _interopRequireDefault(_streams);
  20984. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  20985. const doneReadingSet = new WeakSet();
  20986. const externalBuffer = Symbol('externalBuffer');
  20987. /**
  20988. * A wrapper class over the native ReadableStreamDefaultReader.
  20989. * This additionally implements pushing back data on the stream, which
  20990. * lets us implement peeking and a host of convenience functions.
  20991. * It also lets you read data other than streams, such as a Uint8Array.
  20992. * @class
  20993. */
  20994. function Reader(input) {
  20995. this.stream = input;
  20996. if (input[externalBuffer]) {
  20997. this[externalBuffer] = input[externalBuffer].slice();
  20998. }
  20999. let streamType = _streams2.default.isStream(input);
  21000. if (streamType === 'node') {
  21001. input = _streams2.default.nodeToWeb(input);
  21002. }
  21003. if (streamType) {
  21004. const reader = input.getReader();
  21005. this._read = reader.read.bind(reader);
  21006. this._releaseLock = () => {
  21007. reader.closed.catch(function () {});
  21008. reader.releaseLock();
  21009. };
  21010. return;
  21011. }
  21012. let doneReading = false;
  21013. this._read = async () => {
  21014. if (doneReading || doneReadingSet.has(input)) {
  21015. return { value: undefined, done: true };
  21016. }
  21017. doneReading = true;
  21018. return { value: input, done: false };
  21019. };
  21020. this._releaseLock = () => {
  21021. if (doneReading) {
  21022. try {
  21023. doneReadingSet.add(input);
  21024. } catch (e) {}
  21025. }
  21026. };
  21027. }
  21028. /**
  21029. * Read a chunk of data.
  21030. * @returns {Promise<Object>} Either { done: false, value: Uint8Array | String } or { done: true, value: undefined }
  21031. * @async
  21032. */
  21033. Reader.prototype.read = async function () {
  21034. if (this[externalBuffer] && this[externalBuffer].length) {
  21035. const value = this[externalBuffer].shift();
  21036. return { done: false, value };
  21037. }
  21038. return this._read();
  21039. };
  21040. /**
  21041. * Allow others to read the stream.
  21042. */
  21043. Reader.prototype.releaseLock = function () {
  21044. if (this[externalBuffer]) {
  21045. this.stream[externalBuffer] = this[externalBuffer];
  21046. }
  21047. this._releaseLock();
  21048. };
  21049. /**
  21050. * Read up to and including the first \n character.
  21051. * @returns {Promise<String|Undefined>}
  21052. * @async
  21053. */
  21054. Reader.prototype.readLine = async function () {
  21055. let buffer = [];
  21056. let returnVal;
  21057. while (!returnVal) {
  21058. var _ref = await this.read();
  21059. let done = _ref.done,
  21060. value = _ref.value;
  21061. value += '';
  21062. if (done) {
  21063. if (buffer.length) return _streams2.default.concat(buffer);
  21064. return;
  21065. }
  21066. const lineEndIndex = value.indexOf('\n') + 1;
  21067. if (lineEndIndex) {
  21068. returnVal = _streams2.default.concat(buffer.concat(value.substr(0, lineEndIndex)));
  21069. buffer = [];
  21070. }
  21071. if (lineEndIndex !== value.length) {
  21072. buffer.push(value.substr(lineEndIndex));
  21073. }
  21074. }
  21075. this.unshift(...buffer);
  21076. return returnVal;
  21077. };
  21078. /**
  21079. * Read a single byte/character.
  21080. * @returns {Promise<Number|String|Undefined>}
  21081. * @async
  21082. */
  21083. Reader.prototype.readByte = async function () {
  21084. var _ref2 = await this.read();
  21085. const done = _ref2.done,
  21086. value = _ref2.value;
  21087. if (done) return;
  21088. const byte = value[0];
  21089. this.unshift(_streams2.default.slice(value, 1));
  21090. return byte;
  21091. };
  21092. /**
  21093. * Read a specific amount of bytes/characters, unless the stream ends before that amount.
  21094. * @returns {Promise<Uint8Array|String|Undefined>}
  21095. * @async
  21096. */
  21097. Reader.prototype.readBytes = async function (length) {
  21098. const buffer = [];
  21099. let bufferLength = 0;
  21100. while (true) {
  21101. var _ref3 = await this.read();
  21102. const done = _ref3.done,
  21103. value = _ref3.value;
  21104. if (done) {
  21105. if (buffer.length) return _streams2.default.concat(buffer);
  21106. return;
  21107. }
  21108. buffer.push(value);
  21109. bufferLength += value.length;
  21110. if (bufferLength >= length) {
  21111. const bufferConcat = _streams2.default.concat(buffer);
  21112. this.unshift(_streams2.default.slice(bufferConcat, length));
  21113. return _streams2.default.slice(bufferConcat, 0, length);
  21114. }
  21115. }
  21116. };
  21117. /**
  21118. * Peek (look ahead) a specific amount of bytes/characters, unless the stream ends before that amount.
  21119. * @returns {Promise<Uint8Array|String|Undefined>}
  21120. * @async
  21121. */
  21122. Reader.prototype.peekBytes = async function (length) {
  21123. const bytes = await this.readBytes(length);
  21124. this.unshift(bytes);
  21125. return bytes;
  21126. };
  21127. /**
  21128. * Push data to the front of the stream.
  21129. * @param {...(Uint8Array|String|Undefined)} values
  21130. */
  21131. Reader.prototype.unshift = function (...values) {
  21132. if (!this[externalBuffer]) {
  21133. this[externalBuffer] = [];
  21134. }
  21135. this[externalBuffer].unshift(...values.filter(value => value && value.length));
  21136. };
  21137. /**
  21138. * Read the stream to the end and return its contents, concatenated by the join function (defaults to streams.concat).
  21139. * @param {Function} join
  21140. * @returns {Promise<Uint8array|String|Any>} the return value of join()
  21141. * @async
  21142. */
  21143. Reader.prototype.readToEnd = async function (join = _streams2.default.concat) {
  21144. const result = [];
  21145. while (true) {
  21146. var _ref4 = await this.read();
  21147. const done = _ref4.done,
  21148. value = _ref4.value;
  21149. if (done) break;
  21150. result.push(value);
  21151. }
  21152. return join(result);
  21153. };
  21154. exports.Reader = Reader;
  21155. exports.externalBuffer = externalBuffer;
  21156. },{"./streams":75}],75:[function(require,module,exports){
  21157. (function (process){
  21158. 'use strict';
  21159. Object.defineProperty(exports, "__esModule", {
  21160. value: true
  21161. });
  21162. var _util = require('./util');
  21163. var _nodeConversions = require('./node-conversions');
  21164. var _reader = require('./reader');
  21165. const NodeBuffer = _util.isNode && require('buffer').Buffer;
  21166. /**
  21167. * Convert data to Stream
  21168. * @param {ReadableStream|Uint8array|String} input data to convert
  21169. * @returns {ReadableStream} Converted data
  21170. */
  21171. function toStream(input) {
  21172. let streamType = (0, _util.isStream)(input);
  21173. if (streamType === 'node') {
  21174. return (0, _nodeConversions.nodeToWeb)(input);
  21175. } else if (streamType) {
  21176. return input;
  21177. }
  21178. return new ReadableStream({
  21179. start(controller) {
  21180. controller.enqueue(input);
  21181. controller.close();
  21182. }
  21183. });
  21184. }
  21185. /**
  21186. * Concat a list of Uint8Arrays, Strings or Streams
  21187. * The caller should not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.
  21188. * @param {Array<Uint8array|String|ReadableStream>} Array of Uint8Arrays/Strings/Streams to concatenate
  21189. * @returns {Uint8array|String|ReadableStream} Concatenated array
  21190. */
  21191. function concat(list) {
  21192. if (list.some(_util.isStream)) {
  21193. return concatStream(list);
  21194. }
  21195. if (typeof list[0] === 'string') {
  21196. return list.join('');
  21197. }
  21198. if (NodeBuffer && NodeBuffer.isBuffer(list[0])) {
  21199. return NodeBuffer.concat(list);
  21200. }
  21201. return (0, _util.concatUint8Array)(list);
  21202. }
  21203. /**
  21204. * Concat a list of Streams
  21205. * @param {Array<ReadableStream|Uint8array|String>} list Array of Uint8Arrays/Strings/Streams to concatenate
  21206. * @returns {ReadableStream} Concatenated list
  21207. */
  21208. function concatStream(list) {
  21209. list = list.map(toStream);
  21210. const transform = transformWithCancel(async function (reason) {
  21211. await Promise.all(transforms.map(stream => cancel(stream, reason)));
  21212. });
  21213. let prev = Promise.resolve();
  21214. const transforms = list.map((stream, i) => transformPair(stream, (readable, writable) => {
  21215. prev = prev.then(() => pipe(readable, transform.writable, {
  21216. preventClose: i !== list.length - 1
  21217. }));
  21218. return prev;
  21219. }));
  21220. return transform.readable;
  21221. }
  21222. /**
  21223. * Get a Reader
  21224. * @param {ReadableStream|Uint8array|String} input
  21225. * @returns {Reader}
  21226. */
  21227. function getReader(input) {
  21228. return new _reader.Reader(input);
  21229. }
  21230. /**
  21231. * Get a Writer
  21232. * @param {WritableStream} input
  21233. * @returns {WritableStreamDefaultWriter}
  21234. */
  21235. function getWriter(input) {
  21236. const writer = input.getWriter();
  21237. const releaseLock = writer.releaseLock;
  21238. writer.releaseLock = () => {
  21239. writer.closed.catch(function () {});
  21240. releaseLock.call(writer);
  21241. };
  21242. return writer;
  21243. }
  21244. /**
  21245. * Pipe a readable stream to a writable stream. Don't throw on input stream errors, but forward them to the output stream.
  21246. * @param {ReadableStream|Uint8array|String} input
  21247. * @param {WritableStream} target
  21248. * @param {Object} (optional) options
  21249. * @returns {Promise<undefined>} Promise indicating when piping has finished (input stream closed or errored)
  21250. * @async
  21251. */
  21252. async function pipe(input, target, options) {
  21253. input = toStream(input);
  21254. try {
  21255. if (input[_reader.externalBuffer]) {
  21256. const writer = getWriter(target);
  21257. for (let i = 0; i < input[_reader.externalBuffer].length; i++) {
  21258. await writer.ready;
  21259. await writer.write(input[_reader.externalBuffer][i]);
  21260. }
  21261. writer.releaseLock();
  21262. }
  21263. return await input.pipeTo(target, options);
  21264. } catch (e) {}
  21265. }
  21266. /**
  21267. * Pipe a readable stream through a transform stream.
  21268. * @param {ReadableStream|Uint8array|String} input
  21269. * @param {Object} (optional) options
  21270. * @returns {ReadableStream} transformed stream
  21271. */
  21272. function transformRaw(input, options) {
  21273. const transformStream = new TransformStream(options);
  21274. pipe(input, transformStream.writable);
  21275. return transformStream.readable;
  21276. }
  21277. /**
  21278. * Create a cancelable TransformStream.
  21279. * @param {Function} cancel
  21280. * @returns {TransformStream}
  21281. */
  21282. function transformWithCancel(cancel) {
  21283. let pulled = false;
  21284. let backpressureChangePromiseResolve;
  21285. let outputController;
  21286. return {
  21287. readable: new ReadableStream({
  21288. start(controller) {
  21289. outputController = controller;
  21290. },
  21291. pull() {
  21292. if (backpressureChangePromiseResolve) {
  21293. backpressureChangePromiseResolve();
  21294. } else {
  21295. pulled = true;
  21296. }
  21297. },
  21298. cancel
  21299. }, { highWaterMark: 0 }),
  21300. writable: new WritableStream({
  21301. write: async function write(chunk) {
  21302. outputController.enqueue(chunk);
  21303. if (!pulled) {
  21304. await new Promise(resolve => {
  21305. backpressureChangePromiseResolve = resolve;
  21306. });
  21307. backpressureChangePromiseResolve = null;
  21308. } else {
  21309. pulled = false;
  21310. }
  21311. },
  21312. close: outputController.close.bind(outputController),
  21313. abort: outputController.error.bind(outputController)
  21314. })
  21315. };
  21316. }
  21317. /**
  21318. * Transform a stream using helper functions which are called on each chunk, and on stream close, respectively.
  21319. * @param {ReadableStream|Uint8array|String} input
  21320. * @param {Function} process
  21321. * @param {Function} finish
  21322. * @returns {ReadableStream|Uint8array|String}
  21323. */
  21324. function transform(input, process = () => undefined, finish = () => undefined) {
  21325. if ((0, _util.isStream)(input)) {
  21326. return transformRaw(input, {
  21327. async transform(value, controller) {
  21328. try {
  21329. const result = await process(value);
  21330. if (result !== undefined) controller.enqueue(result);
  21331. } catch (e) {
  21332. controller.error(e);
  21333. }
  21334. },
  21335. async flush(controller) {
  21336. try {
  21337. const result = await finish();
  21338. if (result !== undefined) controller.enqueue(result);
  21339. } catch (e) {
  21340. controller.error(e);
  21341. }
  21342. }
  21343. });
  21344. }
  21345. const result1 = process(input);
  21346. const result2 = finish();
  21347. if (result1 !== undefined && result2 !== undefined) return concat([result1, result2]);
  21348. return result1 !== undefined ? result1 : result2;
  21349. }
  21350. /**
  21351. * Transform a stream using a helper function which is passed a readable and a writable stream.
  21352. * This function also maintains the possibility to cancel the input stream,
  21353. * and does so on cancelation of the output stream, despite cancelation
  21354. * normally being impossible when the input stream is being read from.
  21355. * @param {ReadableStream|Uint8array|String} input
  21356. * @param {Function} fn
  21357. * @returns {ReadableStream}
  21358. */
  21359. function transformPair(input, fn) {
  21360. let incomingTransformController;
  21361. const incoming = new TransformStream({
  21362. start(controller) {
  21363. incomingTransformController = controller;
  21364. }
  21365. });
  21366. const pipeDonePromise = pipe(input, incoming.writable);
  21367. const outgoing = transformWithCancel(async function () {
  21368. incomingTransformController.error(new Error('Readable side was canceled.'));
  21369. await pipeDonePromise;
  21370. await new Promise(setTimeout);
  21371. });
  21372. fn(incoming.readable, outgoing.writable);
  21373. return outgoing.readable;
  21374. }
  21375. /**
  21376. * Parse a stream using a helper function which is passed a Reader.
  21377. * The reader additionally has a remainder() method which returns a
  21378. * stream pointing to the remainder of input, and is linked to input
  21379. * for cancelation.
  21380. * @param {ReadableStream|Uint8array|String} input
  21381. * @param {Function} fn
  21382. * @returns {Any} the return value of fn()
  21383. */
  21384. function parse(input, fn) {
  21385. let returnValue;
  21386. const transformed = transformPair(input, (readable, writable) => {
  21387. const reader = getReader(readable);
  21388. reader.remainder = () => {
  21389. reader.releaseLock();
  21390. pipe(readable, writable);
  21391. return transformed;
  21392. };
  21393. returnValue = fn(reader);
  21394. });
  21395. return returnValue;
  21396. }
  21397. /**
  21398. * Tee a Stream for reading it twice. The input stream can no longer be read after tee()ing.
  21399. * Reading either of the two returned streams will pull from the input stream.
  21400. * The input stream will only be canceled if both of the returned streams are canceled.
  21401. * @param {ReadableStream|Uint8array|String} input
  21402. * @returns {Array<ReadableStream|Uint8array|String>} array containing two copies of input
  21403. */
  21404. function tee(input) {
  21405. if ((0, _util.isStream)(input)) {
  21406. const teed = toStream(input).tee();
  21407. teed[0][_reader.externalBuffer] = teed[1][_reader.externalBuffer] = input[_reader.externalBuffer];
  21408. return teed;
  21409. }
  21410. return [slice(input), slice(input)];
  21411. }
  21412. /**
  21413. * Clone a Stream for reading it twice. The input stream can still be read after clone()ing.
  21414. * Reading from the clone will pull from the input stream.
  21415. * The input stream will only be canceled if both the clone and the input stream are canceled.
  21416. * @param {ReadableStream|Uint8array|String} input
  21417. * @returns {ReadableStream|Uint8array|String} cloned input
  21418. */
  21419. function clone(input) {
  21420. if ((0, _util.isStream)(input)) {
  21421. const teed = tee(input);
  21422. overwrite(input, teed[0]);
  21423. return teed[1];
  21424. }
  21425. return slice(input);
  21426. }
  21427. /**
  21428. * Clone a Stream for reading it twice. Data will arrive at the same rate as the input stream is being read.
  21429. * Reading from the clone will NOT pull from the input stream. Data only arrives when reading the input stream.
  21430. * The input stream will NOT be canceled if the clone is canceled, only if the input stream are canceled.
  21431. * If the input stream is canceled, the clone will be errored.
  21432. * @param {ReadableStream|Uint8array|String} input
  21433. * @returns {ReadableStream|Uint8array|String} cloned input
  21434. */
  21435. function passiveClone(input) {
  21436. if ((0, _util.isStream)(input)) {
  21437. return new ReadableStream({
  21438. start(controller) {
  21439. const transformed = transformPair(input, async (readable, writable) => {
  21440. const reader = getReader(readable);
  21441. const writer = getWriter(writable);
  21442. try {
  21443. while (true) {
  21444. await writer.ready;
  21445. var _ref = await reader.read();
  21446. const done = _ref.done,
  21447. value = _ref.value;
  21448. if (done) {
  21449. try {
  21450. controller.close();
  21451. } catch (e) {}
  21452. await writer.close();
  21453. return;
  21454. }
  21455. try {
  21456. controller.enqueue(value);
  21457. } catch (e) {}
  21458. await writer.write(value);
  21459. }
  21460. } catch (e) {
  21461. controller.error(e);
  21462. await writer.abort(e);
  21463. }
  21464. });
  21465. overwrite(input, transformed);
  21466. }
  21467. });
  21468. }
  21469. return slice(input);
  21470. }
  21471. /**
  21472. * Modify a stream object to point to a different stream object.
  21473. * This is used internally by clone() and passiveClone() to provide an abstraction over tee().
  21474. * @param {ReadableStream} input
  21475. * @param {ReadableStream} clone
  21476. */
  21477. function overwrite(input, clone) {
  21478. // Overwrite input.getReader, input.locked, etc to point to clone
  21479. Object.entries(Object.getOwnPropertyDescriptors(ReadableStream.prototype)).forEach(([name, descriptor]) => {
  21480. if (name === 'constructor') {
  21481. return;
  21482. }
  21483. if (descriptor.value) {
  21484. descriptor.value = descriptor.value.bind(clone);
  21485. } else {
  21486. descriptor.get = descriptor.get.bind(clone);
  21487. }
  21488. Object.defineProperty(input, name, descriptor);
  21489. });
  21490. }
  21491. /**
  21492. * Return a stream pointing to a part of the input stream.
  21493. * @param {ReadableStream|Uint8array|String} input
  21494. * @returns {ReadableStream|Uint8array|String} clone
  21495. */
  21496. function slice(input, begin = 0, end = Infinity) {
  21497. if ((0, _util.isStream)(input)) {
  21498. if (begin >= 0 && end >= 0) {
  21499. let bytesRead = 0;
  21500. return transformRaw(input, {
  21501. transform(value, controller) {
  21502. if (bytesRead < end) {
  21503. if (bytesRead + value.length >= begin) {
  21504. controller.enqueue(slice(value, Math.max(begin - bytesRead, 0), end - bytesRead));
  21505. }
  21506. bytesRead += value.length;
  21507. } else {
  21508. controller.terminate();
  21509. }
  21510. }
  21511. });
  21512. }
  21513. if (begin < 0 && (end < 0 || end === Infinity)) {
  21514. let lastBytes = [];
  21515. return transform(input, value => {
  21516. if (value.length >= -begin) lastBytes = [value];else lastBytes.push(value);
  21517. }, () => slice(concat(lastBytes), begin, end));
  21518. }
  21519. if (begin === 0 && end < 0) {
  21520. let lastBytes;
  21521. return transform(input, value => {
  21522. const returnValue = lastBytes ? concat([lastBytes, value]) : value;
  21523. if (returnValue.length >= -end) {
  21524. lastBytes = slice(returnValue, end);
  21525. return slice(returnValue, begin, end);
  21526. } else {
  21527. lastBytes = returnValue;
  21528. }
  21529. });
  21530. }
  21531. console.warn(`stream.slice(input, ${begin}, ${end}) not implemented efficiently.`);
  21532. return fromAsync(async () => slice((await readToEnd(input)), begin, end));
  21533. }
  21534. if (input[_reader.externalBuffer]) {
  21535. input = concat(input[_reader.externalBuffer].concat([input]));
  21536. }
  21537. if ((0, _util.isUint8Array)(input) && !(NodeBuffer && NodeBuffer.isBuffer(input))) {
  21538. if (end === Infinity) end = input.length;
  21539. return input.subarray(begin, end);
  21540. }
  21541. return input.slice(begin, end);
  21542. }
  21543. /**
  21544. * Read a stream to the end and return its contents, concatenated by the concat function (defaults to concat).
  21545. * @param {ReadableStream|Uint8array|String} input
  21546. * @param {Function} concat
  21547. * @returns {Promise<Uint8array|String|Any>} the return value of concat()
  21548. * @async
  21549. */
  21550. async function readToEnd(input, concat) {
  21551. if ((0, _util.isStream)(input)) {
  21552. return getReader(input).readToEnd(concat);
  21553. }
  21554. return input;
  21555. }
  21556. /**
  21557. * Cancel a stream.
  21558. * @param {ReadableStream|Uint8array|String} input
  21559. * @param {Any} reason
  21560. * @returns {Promise<Any>} indicates when the stream has been canceled
  21561. * @async
  21562. */
  21563. async function cancel(input, reason) {
  21564. if ((0, _util.isStream)(input) && input.cancel) {
  21565. return input.cancel(reason);
  21566. }
  21567. }
  21568. /**
  21569. * Convert an async function to a Stream. When the function returns, its return value is enqueued to the stream.
  21570. * @param {Function} fn
  21571. * @returns {ReadableStream}
  21572. */
  21573. function fromAsync(fn) {
  21574. return new ReadableStream({
  21575. pull: async controller => {
  21576. try {
  21577. controller.enqueue((await fn()));
  21578. controller.close();
  21579. } catch (e) {
  21580. controller.error(e);
  21581. }
  21582. }
  21583. });
  21584. }
  21585. exports.default = { isStream: _util.isStream, isUint8Array: _util.isUint8Array, toStream, concatUint8Array: _util.concatUint8Array, concatStream, concat, getReader, getWriter, pipe, transformRaw, transform, transformPair, parse, clone, passiveClone, slice, readToEnd, cancel, fromAsync, nodeToWeb: _nodeConversions.nodeToWeb, webToNode: _nodeConversions.webToNode };
  21586. }).call(this,require('_process'))
  21587. },{"./node-conversions":73,"./reader":74,"./util":76,"_process":66,"buffer":"buffer"}],76:[function(require,module,exports){
  21588. (function (global){
  21589. 'use strict';
  21590. Object.defineProperty(exports, "__esModule", {
  21591. value: true
  21592. });
  21593. const isNode = typeof global.process === 'object' && typeof global.process.versions === 'object';
  21594. const NodeReadableStream = isNode && require('stream').Readable;
  21595. /**
  21596. * Check whether data is a Stream, and if so of which type
  21597. * @param {Any} input data to check
  21598. * @returns {'web'|'node'|false}
  21599. */
  21600. function isStream(input) {
  21601. if (ReadableStream.prototype.isPrototypeOf(input)) {
  21602. return 'web';
  21603. }
  21604. if (NodeReadableStream && NodeReadableStream.prototype.isPrototypeOf(input)) {
  21605. return 'node';
  21606. }
  21607. return false;
  21608. }
  21609. /**
  21610. * Check whether data is a Uint8Array
  21611. * @param {Any} input data to check
  21612. * @returns {Boolean}
  21613. */
  21614. function isUint8Array(input) {
  21615. return Uint8Array.prototype.isPrototypeOf(input);
  21616. }
  21617. /**
  21618. * Concat Uint8Arrays
  21619. * @param {Array<Uint8array>} Array of Uint8Arrays to concatenate
  21620. * @returns {Uint8array} Concatenated array
  21621. */
  21622. function concatUint8Array(arrays) {
  21623. if (arrays.length === 1) return arrays[0];
  21624. let totalLength = 0;
  21625. for (let i = 0; i < arrays.length; i++) {
  21626. if (!isUint8Array(arrays[i])) {
  21627. throw new Error('concatUint8Array: Data must be in the form of a Uint8Array');
  21628. }
  21629. totalLength += arrays[i].length;
  21630. }
  21631. const result = new Uint8Array(totalLength);
  21632. let pos = 0;
  21633. arrays.forEach(function (element) {
  21634. result.set(element, pos);
  21635. pos += element.length;
  21636. });
  21637. return result;
  21638. }
  21639. exports.isNode = isNode;
  21640. exports.isStream = isStream;
  21641. exports.isUint8Array = isUint8Array;
  21642. exports.concatUint8Array = concatUint8Array;
  21643. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  21644. },{"stream":"stream"}],77:[function(require,module,exports){
  21645. 'use strict';
  21646. Object.defineProperty(exports, "__esModule", {
  21647. value: true
  21648. });
  21649. exports.CleartextMessage = CleartextMessage;
  21650. exports.readArmored = readArmored;
  21651. exports.fromText = fromText;
  21652. var _armor = require('./encoding/armor');
  21653. var _armor2 = _interopRequireDefault(_armor);
  21654. var _enums = require('./enums');
  21655. var _enums2 = _interopRequireDefault(_enums);
  21656. var _util = require('./util');
  21657. var _util2 = _interopRequireDefault(_util);
  21658. var _packet = require('./packet');
  21659. var _packet2 = _interopRequireDefault(_packet);
  21660. var _signature = require('./signature');
  21661. var _message = require('./message');
  21662. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  21663. /**
  21664. * @class
  21665. * @classdesc Class that represents an OpenPGP cleartext signed message.
  21666. * See {@link https://tools.ietf.org/html/rfc4880#section-7}
  21667. * @param {String} text The cleartext of the signed message
  21668. * @param {module:signature.Signature} signature The detached signature or an empty signature for unsigned messages
  21669. */
  21670. // GPG4Browsers - An OpenPGP implementation in javascript
  21671. // Copyright (C) 2011 Recurity Labs GmbH
  21672. //
  21673. // This library is free software; you can redistribute it and/or
  21674. // modify it under the terms of the GNU Lesser General Public
  21675. // License as published by the Free Software Foundation; either
  21676. // version 3.0 of the License, or (at your option) any later version.
  21677. //
  21678. // This library is distributed in the hope that it will be useful,
  21679. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  21680. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  21681. // Lesser General Public License for more details.
  21682. //
  21683. // You should have received a copy of the GNU Lesser General Public
  21684. // License along with this library; if not, write to the Free Software
  21685. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21686. /**
  21687. * @requires encoding/armor
  21688. * @requires enums
  21689. * @requires util
  21690. * @requires packet
  21691. * @requires signature
  21692. * @module cleartext
  21693. */
  21694. function CleartextMessage(text, signature) {
  21695. if (!(this instanceof CleartextMessage)) {
  21696. return new CleartextMessage(text, signature);
  21697. }
  21698. // normalize EOL to canonical form <CR><LF>
  21699. this.text = _util2.default.canonicalizeEOL(_util2.default.removeTrailingSpaces(text));
  21700. if (signature && !(signature instanceof _signature.Signature)) {
  21701. throw new Error('Invalid signature input');
  21702. }
  21703. this.signature = signature || new _signature.Signature(new _packet2.default.List());
  21704. }
  21705. /**
  21706. * Returns the key IDs of the keys that signed the cleartext message
  21707. * @returns {Array<module:type/keyid>} array of keyid objects
  21708. */
  21709. CleartextMessage.prototype.getSigningKeyIds = function () {
  21710. const keyIds = [];
  21711. const signatureList = this.signature.packets;
  21712. signatureList.forEach(function (packet) {
  21713. keyIds.push(packet.issuerKeyId);
  21714. });
  21715. return keyIds;
  21716. };
  21717. /**
  21718. * Sign the cleartext message
  21719. * @param {Array<module:key.Key>} privateKeys private keys with decrypted secret key data for signing
  21720. * @param {Signature} signature (optional) any existing detached signature
  21721. * @param {Date} date (optional) The creation time of the signature that should be created
  21722. * @param {Array} userIds (optional) user IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
  21723. * @returns {Promise<module:cleartext.CleartextMessage>} new cleartext message with signed content
  21724. * @async
  21725. */
  21726. CleartextMessage.prototype.sign = async function (privateKeys, signature = null, date = new Date(), userIds = []) {
  21727. return new CleartextMessage(this.text, (await this.signDetached(privateKeys, signature, date, userIds)));
  21728. };
  21729. /**
  21730. * Sign the cleartext message
  21731. * @param {Array<module:key.Key>} privateKeys private keys with decrypted secret key data for signing
  21732. * @param {Signature} signature (optional) any existing detached signature
  21733. * @param {Date} date (optional) The creation time of the signature that should be created
  21734. * @param {Array} userIds (optional) user IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
  21735. * @returns {Promise<module:signature.Signature>} new detached signature of message content
  21736. * @async
  21737. */
  21738. CleartextMessage.prototype.signDetached = async function (privateKeys, signature = null, date = new Date(), userIds = []) {
  21739. const literalDataPacket = new _packet2.default.Literal();
  21740. literalDataPacket.setText(this.text);
  21741. return new _signature.Signature((await (0, _message.createSignaturePackets)(literalDataPacket, privateKeys, signature, date, userIds, true)));
  21742. };
  21743. /**
  21744. * Verify signatures of cleartext signed message
  21745. * @param {Array<module:key.Key>} keys array of keys to verify signatures
  21746. * @param {Date} date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time
  21747. * @returns {Promise<Array<{keyid: module:type/keyid, valid: Boolean}>>} list of signer's keyid and validity of signature
  21748. * @async
  21749. */
  21750. CleartextMessage.prototype.verify = function (keys, date = new Date()) {
  21751. return this.verifyDetached(this.signature, keys, date);
  21752. };
  21753. /**
  21754. * Verify signatures of cleartext signed message
  21755. * @param {Array<module:key.Key>} keys array of keys to verify signatures
  21756. * @param {Date} date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time
  21757. * @returns {Promise<Array<{keyid: module:type/keyid, valid: Boolean}>>} list of signer's keyid and validity of signature
  21758. * @async
  21759. */
  21760. CleartextMessage.prototype.verifyDetached = function (signature, keys, date = new Date()) {
  21761. const signatureList = signature.packets;
  21762. const literalDataPacket = new _packet2.default.Literal();
  21763. // we assume that cleartext signature is generated based on UTF8 cleartext
  21764. literalDataPacket.setText(this.text);
  21765. return (0, _message.createVerificationObjects)(signatureList, [literalDataPacket], keys, date, true);
  21766. };
  21767. /**
  21768. * Get cleartext
  21769. * @returns {String} cleartext of message
  21770. */
  21771. CleartextMessage.prototype.getText = function () {
  21772. // normalize end of line to \n
  21773. return _util2.default.nativeEOL(this.text);
  21774. };
  21775. /**
  21776. * Returns ASCII armored text of cleartext signed message
  21777. * @returns {String | ReadableStream<String>} ASCII armor
  21778. */
  21779. CleartextMessage.prototype.armor = function () {
  21780. let hashes = this.signature.packets.map(function (packet) {
  21781. return _enums2.default.read(_enums2.default.hash, packet.hashAlgorithm).toUpperCase();
  21782. });
  21783. hashes = hashes.filter(function (item, i, ar) {
  21784. return ar.indexOf(item) === i;
  21785. });
  21786. const body = {
  21787. hash: hashes.join(),
  21788. text: this.text,
  21789. data: this.signature.packets.write()
  21790. };
  21791. return _armor2.default.encode(_enums2.default.armor.signed, body);
  21792. };
  21793. /**
  21794. * reads an OpenPGP cleartext signed message and returns a CleartextMessage object
  21795. * @param {String | ReadableStream<String>} armoredText text to be parsed
  21796. * @returns {module:cleartext.CleartextMessage} new cleartext message object
  21797. * @async
  21798. * @static
  21799. */
  21800. async function readArmored(armoredText) {
  21801. const input = await _armor2.default.decode(armoredText);
  21802. if (input.type !== _enums2.default.armor.signed) {
  21803. throw new Error('No cleartext signed message.');
  21804. }
  21805. const packetlist = new _packet2.default.List();
  21806. await packetlist.read(input.data);
  21807. verifyHeaders(input.headers, packetlist);
  21808. const signature = new _signature.Signature(packetlist);
  21809. return new CleartextMessage(input.text, signature);
  21810. }
  21811. /**
  21812. * Compare hash algorithm specified in the armor header with signatures
  21813. * @param {Array<String>} headers Armor headers
  21814. * @param {module:packet.List} packetlist The packetlist with signature packets
  21815. * @private
  21816. */
  21817. function verifyHeaders(headers, packetlist) {
  21818. const checkHashAlgos = function checkHashAlgos(hashAlgos) {
  21819. const check = packet => algo => packet.hashAlgorithm === algo;
  21820. for (let i = 0; i < packetlist.length; i++) {
  21821. if (packetlist[i].tag === _enums2.default.packet.signature && !hashAlgos.some(check(packetlist[i]))) {
  21822. return false;
  21823. }
  21824. }
  21825. return true;
  21826. };
  21827. let oneHeader = null;
  21828. let hashAlgos = [];
  21829. headers.forEach(function (header) {
  21830. oneHeader = header.match(/Hash: (.+)/); // get header value
  21831. if (oneHeader) {
  21832. oneHeader = oneHeader[1].replace(/\s/g, ''); // remove whitespace
  21833. oneHeader = oneHeader.split(',');
  21834. oneHeader = oneHeader.map(function (hash) {
  21835. hash = hash.toLowerCase();
  21836. try {
  21837. return _enums2.default.write(_enums2.default.hash, hash);
  21838. } catch (e) {
  21839. throw new Error('Unknown hash algorithm in armor header: ' + hash);
  21840. }
  21841. });
  21842. hashAlgos = hashAlgos.concat(oneHeader);
  21843. } else {
  21844. throw new Error('Only "Hash" header allowed in cleartext signed message');
  21845. }
  21846. });
  21847. if (!hashAlgos.length && !checkHashAlgos([_enums2.default.hash.md5])) {
  21848. throw new Error('If no "Hash" header in cleartext signed message, then only MD5 signatures allowed');
  21849. } else if (hashAlgos.length && !checkHashAlgos(hashAlgos)) {
  21850. throw new Error('Hash algorithm mismatch in armor header and signature');
  21851. }
  21852. }
  21853. /**
  21854. * Creates a new CleartextMessage object from text
  21855. * @param {String} text
  21856. * @static
  21857. */
  21858. function fromText(text) {
  21859. return new CleartextMessage(text);
  21860. }
  21861. },{"./encoding/armor":111,"./enums":113,"./message":126,"./packet":131,"./signature":151,"./util":158}],78:[function(require,module,exports){
  21862. "use strict";
  21863. Object.defineProperty(exports, "__esModule", {
  21864. value: true
  21865. });
  21866. var _enums = require("../enums");
  21867. var _enums2 = _interopRequireDefault(_enums);
  21868. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  21869. exports.default = {
  21870. /**
  21871. * @memberof module:config
  21872. * @property {Integer} prefer_hash_algorithm Default hash algorithm {@link module:enums.hash}
  21873. */
  21874. prefer_hash_algorithm: _enums2.default.hash.sha256,
  21875. /**
  21876. * @memberof module:config
  21877. * @property {Integer} encryption_cipher Default encryption cipher {@link module:enums.symmetric}
  21878. */
  21879. encryption_cipher: _enums2.default.symmetric.aes256,
  21880. /**
  21881. * @memberof module:config
  21882. * @property {Integer} compression Default compression algorithm {@link module:enums.compression}
  21883. */
  21884. compression: _enums2.default.compression.uncompressed,
  21885. /**
  21886. * @memberof module:config
  21887. * @property {Integer} deflate_level Default zip/zlib compression level, between 1 and 9
  21888. */
  21889. deflate_level: 6,
  21890. /**
  21891. * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption.
  21892. * **NOT INTEROPERABLE WITH OTHER OPENPGP IMPLEMENTATIONS**
  21893. * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**
  21894. * @see {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-07|RFC4880bis-07}
  21895. * @memberof module:config
  21896. * @property {Boolean} aead_protect
  21897. */
  21898. aead_protect: false,
  21899. /**
  21900. * Default Authenticated Encryption with Additional Data (AEAD) encryption mode
  21901. * Only has an effect when aead_protect is set to true.
  21902. * @memberof module:config
  21903. * @property {Integer} aead_mode Default AEAD mode {@link module:enums.aead}
  21904. */
  21905. aead_mode: _enums2.default.aead.eax,
  21906. /**
  21907. * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode
  21908. * Only has an effect when aead_protect is set to true.
  21909. * Must be an integer value from 0 to 56.
  21910. * @memberof module:config
  21911. * @property {Integer} aead_chunk_size_byte
  21912. */
  21913. aead_chunk_size_byte: 12,
  21914. /**
  21915. * Use V5 keys.
  21916. * **NOT INTEROPERABLE WITH OTHER OPENPGP IMPLEMENTATIONS**
  21917. * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION**
  21918. * @memberof module:config
  21919. * @property {Boolean} v5_keys
  21920. */
  21921. v5_keys: false,
  21922. /**
  21923. * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}:
  21924. * Iteration Count Byte for S2K (String to Key)
  21925. * @memberof module:config
  21926. * @property {Integer} s2k_iteration_count_byte
  21927. */
  21928. s2k_iteration_count_byte: 224,
  21929. /** Use integrity protection for symmetric encryption
  21930. * @memberof module:config
  21931. * @property {Boolean} integrity_protect
  21932. */
  21933. integrity_protect: true,
  21934. /**
  21935. * @memberof module:config
  21936. * @property {Boolean} ignore_mdc_error Fail on decrypt if message is not integrity protected
  21937. */
  21938. ignore_mdc_error: false,
  21939. /**
  21940. * @memberof module:config
  21941. * @property {Boolean} allow_unauthenticated_stream Stream unauthenticated data before integrity has been checked
  21942. */
  21943. allow_unauthenticated_stream: false,
  21944. /**
  21945. * @memberof module:config
  21946. * @property {Boolean} checksum_required Do not throw error when armor is missing a checksum
  21947. */
  21948. checksum_required: false,
  21949. /**
  21950. * @memberof module:config
  21951. * @property {Boolean} rsa_blinding
  21952. */
  21953. rsa_blinding: true,
  21954. /**
  21955. * Work-around for rare GPG decryption bug when encrypting with multiple passwords.
  21956. * **Slower and slightly less secure**
  21957. * @memberof module:config
  21958. * @property {Boolean} password_collision_check
  21959. */
  21960. password_collision_check: false,
  21961. /**
  21962. * @memberof module:config
  21963. * @property {Boolean} revocations_expire If true, expired revocation signatures are ignored
  21964. */
  21965. revocations_expire: false,
  21966. /**
  21967. * @memberof module:config
  21968. * @property {Boolean} use_native Use native Node.js crypto/zlib and WebCrypto APIs when available
  21969. */
  21970. use_native: true,
  21971. /**
  21972. * @memberof module:config
  21973. * @property {Integer} min_bytes_for_web_crypto The minimum amount of bytes for which to use native WebCrypto APIs when available
  21974. */
  21975. min_bytes_for_web_crypto: 1000,
  21976. /**
  21977. * @memberof module:config
  21978. * @property {Boolean} Use transferable objects between the Web Worker and main thread
  21979. */
  21980. zero_copy: false,
  21981. /**
  21982. * @memberof module:config
  21983. * @property {Boolean} debug If enabled, debug messages will be printed
  21984. */
  21985. debug: false,
  21986. /**
  21987. * @memberof module:config
  21988. * @property {Boolean} tolerant Ignore unsupported/unrecognizable packets instead of throwing an error
  21989. */
  21990. tolerant: true,
  21991. /**
  21992. * @memberof module:config
  21993. * @property {Boolean} show_version Whether to include {@link module:config/config.versionstring} in armored messages
  21994. */
  21995. show_version: true,
  21996. /**
  21997. * @memberof module:config
  21998. * @property {Boolean} show_comment Whether to include {@link module:config/config.commentstring} in armored messages
  21999. */
  22000. show_comment: true,
  22001. /**
  22002. * @memberof module:config
  22003. * @property {String} versionstring A version string to be included in armored messages
  22004. */
  22005. versionstring: "OpenPGP.js v4.7.1",
  22006. /**
  22007. * @memberof module:config
  22008. * @property {String} commentstring A comment string to be included in armored messages
  22009. */
  22010. commentstring: "https://openpgpjs.org",
  22011. /**
  22012. * @memberof module:config
  22013. * @property {String} keyserver
  22014. */
  22015. keyserver: "https://keyserver.ubuntu.com",
  22016. /**
  22017. * @memberof module:config
  22018. * @property {String} node_store
  22019. */
  22020. node_store: "./openpgp.store",
  22021. /**
  22022. * Max userid string length (used for parsing)
  22023. * @memberof module:config
  22024. * @property {Integer} max_userid_length
  22025. */
  22026. max_userid_length: 1024 * 5,
  22027. /**
  22028. * Contains notatations that are considered "known". Known notations do not trigger
  22029. * validation error when the notation is marked as critical.
  22030. * @memberof module:config
  22031. * @property {Array} known_notations
  22032. */
  22033. known_notations: ["preferred-email-encoding@pgp.com", "pka-address@gnupg.org"],
  22034. /**
  22035. * @memberof module:config
  22036. * @property {Boolean} use_indutny_elliptic Whether to use the indutny/elliptic library. When false, certain curves will not be supported.
  22037. */
  22038. use_indutny_elliptic: true,
  22039. /**
  22040. * @memberof module:config
  22041. * @property {Boolean} external_indutny_elliptic Whether to lazily load the indutny/elliptic library from an external path on demand.
  22042. */
  22043. external_indutny_elliptic: false,
  22044. /**
  22045. * @memberof module:config
  22046. * @property {String} indutny_elliptic_path The path to load the indutny/elliptic library from. Only has an effect if `config.external_indutny_elliptic` is true.
  22047. */
  22048. indutny_elliptic_path: './elliptic.min.js',
  22049. /**
  22050. * @memberof module:config
  22051. * @property {Object} indutny_elliptic_fetch_options Options object to pass to `fetch` when loading the indutny/elliptic library. Only has an effect if `config.external_indutny_elliptic` is true.
  22052. */
  22053. indutny_elliptic_fetch_options: {}
  22054. }; // GPG4Browsers - An OpenPGP implementation in javascript
  22055. // Copyright (C) 2011 Recurity Labs GmbH
  22056. //
  22057. // This library is free software; you can redistribute it and/or
  22058. // modify it under the terms of the GNU Lesser General Public
  22059. // License as published by the Free Software Foundation; either
  22060. // version 3.0 of the License, or (at your option) any later version.
  22061. //
  22062. // This library is distributed in the hope that it will be useful,
  22063. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  22064. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  22065. // Lesser General Public License for more details.
  22066. //
  22067. // You should have received a copy of the GNU Lesser General Public
  22068. // License along with this library; if not, write to the Free Software
  22069. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  22070. /**
  22071. * Global configuration values.
  22072. * @requires enums
  22073. */
  22074. },{"../enums":113}],79:[function(require,module,exports){
  22075. 'use strict';
  22076. Object.defineProperty(exports, "__esModule", {
  22077. value: true
  22078. });
  22079. var _config = require('./config.js');
  22080. Object.defineProperty(exports, 'default', {
  22081. enumerable: true,
  22082. get: function get() {
  22083. return _interopRequireDefault(_config).default;
  22084. }
  22085. });
  22086. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  22087. },{"./config.js":78}],80:[function(require,module,exports){
  22088. 'use strict';
  22089. Object.defineProperty(exports, "__esModule", {
  22090. value: true
  22091. });
  22092. var _cipher = require('./cipher');
  22093. var _cipher2 = _interopRequireDefault(_cipher);
  22094. var _util = require('../util');
  22095. var _util2 = _interopRequireDefault(_util);
  22096. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  22097. // OpenPGP.js - An OpenPGP implementation in javascript
  22098. // Copyright (C) 2015-2016 Decentral
  22099. //
  22100. // This library is free software; you can redistribute it and/or
  22101. // modify it under the terms of the GNU Lesser General Public
  22102. // License as published by the Free Software Foundation; either
  22103. // version 3.0 of the License, or (at your option) any later version.
  22104. //
  22105. // This library is distributed in the hope that it will be useful,
  22106. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  22107. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  22108. // Lesser General Public License for more details.
  22109. //
  22110. // You should have received a copy of the GNU Lesser General Public
  22111. // License along with this library; if not, write to the Free Software
  22112. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  22113. /**
  22114. * @fileoverview Implementation of RFC 3394 AES Key Wrap & Key Unwrap funcions
  22115. * @see module:crypto/public_key/elliptic/ecdh
  22116. * @requires crypto/cipher
  22117. * @requires util
  22118. * @module crypto/aes_kw
  22119. */
  22120. function wrap(key, data) {
  22121. const aes = new _cipher2.default["aes" + key.length * 8](key);
  22122. const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);
  22123. const P = unpack(data);
  22124. let A = IV;
  22125. const R = P;
  22126. const n = P.length / 2;
  22127. const t = new Uint32Array([0, 0]);
  22128. let B = new Uint32Array(4);
  22129. for (let j = 0; j <= 5; ++j) {
  22130. for (let i = 0; i < n; ++i) {
  22131. t[1] = n * j + (1 + i);
  22132. // B = A
  22133. B[0] = A[0];
  22134. B[1] = A[1];
  22135. // B = A || R[i]
  22136. B[2] = R[2 * i];
  22137. B[3] = R[2 * i + 1];
  22138. // B = AES(K, B)
  22139. B = unpack(aes.encrypt(pack(B)));
  22140. // A = MSB(64, B) ^ t
  22141. A = B.subarray(0, 2);
  22142. A[0] ^= t[0];
  22143. A[1] ^= t[1];
  22144. // R[i] = LSB(64, B)
  22145. R[2 * i] = B[2];
  22146. R[2 * i + 1] = B[3];
  22147. }
  22148. }
  22149. return pack(A, R);
  22150. }
  22151. function unwrap(key, data) {
  22152. const aes = new _cipher2.default["aes" + key.length * 8](key);
  22153. const IV = new Uint32Array([0xA6A6A6A6, 0xA6A6A6A6]);
  22154. const C = unpack(data);
  22155. let A = C.subarray(0, 2);
  22156. const R = C.subarray(2);
  22157. const n = C.length / 2 - 1;
  22158. const t = new Uint32Array([0, 0]);
  22159. let B = new Uint32Array(4);
  22160. for (let j = 5; j >= 0; --j) {
  22161. for (let i = n - 1; i >= 0; --i) {
  22162. t[1] = n * j + (i + 1);
  22163. // B = A ^ t
  22164. B[0] = A[0] ^ t[0];
  22165. B[1] = A[1] ^ t[1];
  22166. // B = (A ^ t) || R[i]
  22167. B[2] = R[2 * i];
  22168. B[3] = R[2 * i + 1];
  22169. // B = AES-1(B)
  22170. B = unpack(aes.decrypt(pack(B)));
  22171. // A = MSB(64, B)
  22172. A = B.subarray(0, 2);
  22173. // R[i] = LSB(64, B)
  22174. R[2 * i] = B[2];
  22175. R[2 * i + 1] = B[3];
  22176. }
  22177. }
  22178. if (A[0] === IV[0] && A[1] === IV[1]) {
  22179. return pack(R);
  22180. }
  22181. throw new Error("Key Data Integrity failed");
  22182. }
  22183. function createArrayBuffer(data) {
  22184. if (_util2.default.isString(data)) {
  22185. const length = data.length;
  22186. const buffer = new ArrayBuffer(length);
  22187. const view = new Uint8Array(buffer);
  22188. for (let j = 0; j < length; ++j) {
  22189. view[j] = data.charCodeAt(j);
  22190. }
  22191. return buffer;
  22192. }
  22193. return new Uint8Array(data).buffer;
  22194. }
  22195. function unpack(data) {
  22196. const length = data.length;
  22197. const buffer = createArrayBuffer(data);
  22198. const view = new DataView(buffer);
  22199. const arr = new Uint32Array(length / 4);
  22200. for (let i = 0; i < length / 4; ++i) {
  22201. arr[i] = view.getUint32(4 * i);
  22202. }
  22203. return arr;
  22204. }
  22205. function pack() {
  22206. let length = 0;
  22207. for (let k = 0; k < arguments.length; ++k) {
  22208. length += 4 * arguments[k].length;
  22209. }
  22210. const buffer = new ArrayBuffer(length);
  22211. const view = new DataView(buffer);
  22212. let offset = 0;
  22213. for (let i = 0; i < arguments.length; ++i) {
  22214. for (let j = 0; j < arguments[i].length; ++j) {
  22215. view.setUint32(offset + 4 * j, arguments[i][j]);
  22216. }
  22217. offset += 4 * arguments[i].length;
  22218. }
  22219. return new Uint8Array(buffer);
  22220. }
  22221. exports.default = {
  22222. /**
  22223. * AES key wrap
  22224. * @function
  22225. * @param {String} key
  22226. * @param {String} data
  22227. * @returns {Uint8Array}
  22228. */
  22229. wrap,
  22230. /**
  22231. * AES key unwrap
  22232. * @function
  22233. * @param {String} key
  22234. * @param {String} data
  22235. * @returns {Uint8Array}
  22236. * @throws {Error}
  22237. */
  22238. unwrap
  22239. };
  22240. },{"../util":158,"./cipher":86}],81:[function(require,module,exports){
  22241. 'use strict';
  22242. Object.defineProperty(exports, "__esModule", {
  22243. value: true
  22244. });
  22245. var _cfb = require('asmcrypto.js/dist_es5/aes/cfb');
  22246. var _webStreamTools = require('web-stream-tools');
  22247. var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
  22248. var _cipher = require('./cipher');
  22249. var _cipher2 = _interopRequireDefault(_cipher);
  22250. var _config = require('../config');
  22251. var _config2 = _interopRequireDefault(_config);
  22252. var _util = require('../util');
  22253. var _util2 = _interopRequireDefault(_util);
  22254. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  22255. const webCrypto = _util2.default.getWebCrypto(); // Modified by ProtonTech AG
  22256. // Modified by Recurity Labs GmbH
  22257. // modified version of https://www.hanewin.net/encrypt/PGdecode.js:
  22258. /* OpenPGP encryption using RSA/AES
  22259. * Copyright 2005-2006 Herbert Hanewinkel, www.haneWIN.de
  22260. * version 2.0, check www.haneWIN.de for the latest version
  22261. * This software is provided as-is, without express or implied warranty.
  22262. * Permission to use, copy, modify, distribute or sell this software, with or
  22263. * without fee, for any purpose and by any individual or organization, is hereby
  22264. * granted, provided that the above copyright notice and this paragraph appear
  22265. * in all copies. Distribution as a part of an application or binary must
  22266. * include the above copyright notice in the documentation and/or other
  22267. * materials provided with the application or distribution.
  22268. */
  22269. /**
  22270. * @requires web-stream-tools
  22271. * @requires crypto/cipher
  22272. * @requires util
  22273. * @module crypto/cfb
  22274. */
  22275. const nodeCrypto = _util2.default.getNodeCrypto();
  22276. const Buffer = _util2.default.getNodeBuffer();
  22277. exports.default = {
  22278. encrypt: function encrypt(algo, key, plaintext, iv) {
  22279. if (algo.substr(0, 3) === 'aes') {
  22280. return aesEncrypt(algo, key, plaintext, iv);
  22281. }
  22282. const cipherfn = new _cipher2.default[algo](key);
  22283. const block_size = cipherfn.blockSize;
  22284. let blocki = new Uint8Array(block_size);
  22285. const blockc = iv.slice();
  22286. let pos = 0;
  22287. const ciphertext = new Uint8Array(plaintext.length);
  22288. let i;
  22289. let j = 0;
  22290. while (plaintext.length > block_size * pos) {
  22291. const encblock = cipherfn.encrypt(blockc);
  22292. blocki = plaintext.subarray(pos * block_size, pos * block_size + block_size);
  22293. for (i = 0; i < blocki.length; i++) {
  22294. blockc[i] = blocki[i] ^ encblock[i];
  22295. ciphertext[j++] = blockc[i];
  22296. }
  22297. pos++;
  22298. }
  22299. return ciphertext;
  22300. },
  22301. decrypt: async function decrypt(algo, key, ciphertext, iv) {
  22302. if (algo.substr(0, 3) === 'aes') {
  22303. return aesDecrypt(algo, key, ciphertext, iv);
  22304. }
  22305. ciphertext = await _webStreamTools2.default.readToEnd(ciphertext);
  22306. const cipherfn = new _cipher2.default[algo](key);
  22307. const block_size = cipherfn.blockSize;
  22308. let blockp = iv;
  22309. let pos = 0;
  22310. const plaintext = new Uint8Array(ciphertext.length);
  22311. const offset = 0;
  22312. let i;
  22313. let j = 0;
  22314. while (ciphertext.length > block_size * pos) {
  22315. const decblock = cipherfn.encrypt(blockp);
  22316. blockp = ciphertext.subarray(pos * block_size + offset, pos * block_size + block_size + offset);
  22317. for (i = 0; i < blockp.length; i++) {
  22318. plaintext[j++] = blockp[i] ^ decblock[i];
  22319. }
  22320. pos++;
  22321. }
  22322. return plaintext;
  22323. }
  22324. };
  22325. function aesEncrypt(algo, key, pt, iv) {
  22326. if (_util2.default.getWebCrypto() && key.length !== 24 && // Chrome doesn't support 192 bit keys, see https://www.chromium.org/blink/webcrypto#TOC-AES-support
  22327. !_util2.default.isStream(pt) && pt.length >= 3000 * _config2.default.min_bytes_for_web_crypto // Default to a 3MB minimum. Chrome is pretty slow for small messages, see: https://bugs.chromium.org/p/chromium/issues/detail?id=701188#c2
  22328. ) {
  22329. // Web Crypto
  22330. return webEncrypt(algo, key, pt, iv);
  22331. }
  22332. if (nodeCrypto) {
  22333. // Node crypto library.
  22334. return nodeEncrypt(algo, key, pt, iv);
  22335. } // asm.js fallback
  22336. const cfb = new _cfb.AES_CFB(key, iv);
  22337. return _webStreamTools2.default.transform(pt, value => cfb.AES_Encrypt_process(value), () => cfb.AES_Encrypt_finish());
  22338. }
  22339. function aesDecrypt(algo, key, ct, iv) {
  22340. if (nodeCrypto) {
  22341. // Node crypto library.
  22342. return nodeDecrypt(algo, key, ct, iv);
  22343. }
  22344. if (_util2.default.isStream(ct)) {
  22345. const cfb = new _cfb.AES_CFB(key, iv);
  22346. return _webStreamTools2.default.transform(ct, value => cfb.AES_Decrypt_process(value), () => cfb.AES_Decrypt_finish());
  22347. }
  22348. return _cfb.AES_CFB.decrypt(ct, key, iv);
  22349. }
  22350. function xorMut(a, b) {
  22351. for (let i = 0; i < a.length; i++) {
  22352. a[i] = a[i] ^ b[i];
  22353. }
  22354. }
  22355. async function webEncrypt(algo, key, pt, iv) {
  22356. const ALGO = 'AES-CBC';
  22357. const _key = await webCrypto.importKey('raw', key, { name: ALGO }, false, ['encrypt']);
  22358. const blockSize = _cipher2.default[algo].blockSize;
  22359. const cbc_pt = _util2.default.concatUint8Array([new Uint8Array(blockSize), pt]);
  22360. const ct = new Uint8Array((await webCrypto.encrypt({ name: ALGO, iv }, _key, cbc_pt))).subarray(0, pt.length);
  22361. xorMut(ct, pt);
  22362. return ct;
  22363. }
  22364. function nodeEncrypt(algo, key, pt, iv) {
  22365. key = Buffer.from(key);
  22366. iv = Buffer.from(iv);
  22367. const cipherObj = new nodeCrypto.createCipheriv('aes-' + algo.substr(3, 3) + '-cfb', key, iv);
  22368. return _webStreamTools2.default.transform(pt, value => new Uint8Array(cipherObj.update(Buffer.from(value))));
  22369. }
  22370. function nodeDecrypt(algo, key, ct, iv) {
  22371. key = Buffer.from(key);
  22372. iv = Buffer.from(iv);
  22373. const decipherObj = new nodeCrypto.createDecipheriv('aes-' + algo.substr(3, 3) + '-cfb', key, iv);
  22374. return _webStreamTools2.default.transform(ct, value => new Uint8Array(decipherObj.update(Buffer.from(value))));
  22375. }
  22376. },{"../config":79,"../util":158,"./cipher":86,"asmcrypto.js/dist_es5/aes/cfb":5,"web-stream-tools":75}],82:[function(require,module,exports){
  22377. 'use strict';
  22378. Object.defineProperty(exports, "__esModule", {
  22379. value: true
  22380. });
  22381. var _ecb = require('asmcrypto.js/dist_es5/aes/ecb');
  22382. // TODO use webCrypto or nodeCrypto when possible.
  22383. function aes(length) {
  22384. const C = function C(key) {
  22385. const aes_ecb = new _ecb.AES_ECB(key);
  22386. this.encrypt = function (block) {
  22387. return aes_ecb.encrypt(block);
  22388. };
  22389. this.decrypt = function (block) {
  22390. return aes_ecb.decrypt(block);
  22391. };
  22392. };
  22393. C.blockSize = C.prototype.blockSize = 16;
  22394. C.keySize = C.prototype.keySize = length / 8;
  22395. return C;
  22396. } /**
  22397. * @requires asmcrypto.js
  22398. */
  22399. exports.default = aes;
  22400. },{"asmcrypto.js/dist_es5/aes/ecb":7}],83:[function(require,module,exports){
  22401. "use strict";
  22402. Object.defineProperty(exports, "__esModule", {
  22403. value: true
  22404. });
  22405. /* Modified by Recurity Labs GmbH
  22406. *
  22407. * Originally written by nklein software (nklein.com)
  22408. */
  22409. /*
  22410. * Javascript implementation based on Bruce Schneier's reference implementation.
  22411. *
  22412. *
  22413. * The constructor doesn't do much of anything. It's just here
  22414. * so we can start defining properties and methods and such.
  22415. */
  22416. function Blowfish() {}
  22417. /*
  22418. * Declare the block size so that protocols know what size
  22419. * Initialization Vector (IV) they will need.
  22420. */
  22421. Blowfish.prototype.BLOCKSIZE = 8;
  22422. /*
  22423. * These are the default SBOXES.
  22424. */
  22425. Blowfish.prototype.SBOXES = [[0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a], [0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7], [0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0], [0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6]];
  22426. //*
  22427. //* This is the default PARRAY
  22428. //*
  22429. Blowfish.prototype.PARRAY = [0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b];
  22430. //*
  22431. //* This is the number of rounds the cipher will go
  22432. //*
  22433. Blowfish.prototype.NN = 16;
  22434. //*
  22435. //* This function is needed to get rid of problems
  22436. //* with the high-bit getting set. If we don't do
  22437. //* this, then sometimes ( aa & 0x00FFFFFFFF ) is not
  22438. //* equal to ( bb & 0x00FFFFFFFF ) even when they
  22439. //* agree bit-for-bit for the first 32 bits.
  22440. //*
  22441. Blowfish.prototype._clean = function (xx) {
  22442. if (xx < 0) {
  22443. const yy = xx & 0x7FFFFFFF;
  22444. xx = yy + 0x80000000;
  22445. }
  22446. return xx;
  22447. };
  22448. //*
  22449. //* This is the mixing function that uses the sboxes
  22450. //*
  22451. Blowfish.prototype._F = function (xx) {
  22452. let yy;
  22453. const dd = xx & 0x00FF;
  22454. xx >>>= 8;
  22455. const cc = xx & 0x00FF;
  22456. xx >>>= 8;
  22457. const bb = xx & 0x00FF;
  22458. xx >>>= 8;
  22459. const aa = xx & 0x00FF;
  22460. yy = this.sboxes[0][aa] + this.sboxes[1][bb];
  22461. yy ^= this.sboxes[2][cc];
  22462. yy += this.sboxes[3][dd];
  22463. return yy;
  22464. };
  22465. //*
  22466. //* This method takes an array with two values, left and right
  22467. //* and does NN rounds of Blowfish on them.
  22468. //*
  22469. Blowfish.prototype._encrypt_block = function (vals) {
  22470. let dataL = vals[0];
  22471. let dataR = vals[1];
  22472. let ii;
  22473. for (ii = 0; ii < this.NN; ++ii) {
  22474. dataL ^= this.parray[ii];
  22475. dataR = this._F(dataL) ^ dataR;
  22476. const tmp = dataL;
  22477. dataL = dataR;
  22478. dataR = tmp;
  22479. }
  22480. dataL ^= this.parray[this.NN + 0];
  22481. dataR ^= this.parray[this.NN + 1];
  22482. vals[0] = this._clean(dataR);
  22483. vals[1] = this._clean(dataL);
  22484. };
  22485. //*
  22486. //* This method takes a vector of numbers and turns them
  22487. //* into long words so that they can be processed by the
  22488. //* real algorithm.
  22489. //*
  22490. //* Maybe I should make the real algorithm above take a vector
  22491. //* instead. That will involve more looping, but it won't require
  22492. //* the F() method to deconstruct the vector.
  22493. //*
  22494. Blowfish.prototype.encrypt_block = function (vector) {
  22495. let ii;
  22496. const vals = [0, 0];
  22497. const off = this.BLOCKSIZE / 2;
  22498. for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {
  22499. vals[0] = vals[0] << 8 | vector[ii + 0] & 0x00FF;
  22500. vals[1] = vals[1] << 8 | vector[ii + off] & 0x00FF;
  22501. }
  22502. this._encrypt_block(vals);
  22503. const ret = [];
  22504. for (ii = 0; ii < this.BLOCKSIZE / 2; ++ii) {
  22505. ret[ii + 0] = vals[0] >>> 24 - 8 * ii & 0x00FF;
  22506. ret[ii + off] = vals[1] >>> 24 - 8 * ii & 0x00FF;
  22507. // vals[ 0 ] = ( vals[ 0 ] >>> 8 );
  22508. // vals[ 1 ] = ( vals[ 1 ] >>> 8 );
  22509. }
  22510. return ret;
  22511. };
  22512. //*
  22513. //* This method takes an array with two values, left and right
  22514. //* and undoes NN rounds of Blowfish on them.
  22515. //*
  22516. Blowfish.prototype._decrypt_block = function (vals) {
  22517. let dataL = vals[0];
  22518. let dataR = vals[1];
  22519. let ii;
  22520. for (ii = this.NN + 1; ii > 1; --ii) {
  22521. dataL ^= this.parray[ii];
  22522. dataR = this._F(dataL) ^ dataR;
  22523. const tmp = dataL;
  22524. dataL = dataR;
  22525. dataR = tmp;
  22526. }
  22527. dataL ^= this.parray[1];
  22528. dataR ^= this.parray[0];
  22529. vals[0] = this._clean(dataR);
  22530. vals[1] = this._clean(dataL);
  22531. };
  22532. //*
  22533. //* This method takes a key array and initializes the
  22534. //* sboxes and parray for this encryption.
  22535. //*
  22536. Blowfish.prototype.init = function (key) {
  22537. let ii;
  22538. let jj = 0;
  22539. this.parray = [];
  22540. for (ii = 0; ii < this.NN + 2; ++ii) {
  22541. let data = 0x00000000;
  22542. for (let kk = 0; kk < 4; ++kk) {
  22543. data = data << 8 | key[jj] & 0x00FF;
  22544. if (++jj >= key.length) {
  22545. jj = 0;
  22546. }
  22547. }
  22548. this.parray[ii] = this.PARRAY[ii] ^ data;
  22549. }
  22550. this.sboxes = [];
  22551. for (ii = 0; ii < 4; ++ii) {
  22552. this.sboxes[ii] = [];
  22553. for (jj = 0; jj < 256; ++jj) {
  22554. this.sboxes[ii][jj] = this.SBOXES[ii][jj];
  22555. }
  22556. }
  22557. const vals = [0x00000000, 0x00000000];
  22558. for (ii = 0; ii < this.NN + 2; ii += 2) {
  22559. this._encrypt_block(vals);
  22560. this.parray[ii + 0] = vals[0];
  22561. this.parray[ii + 1] = vals[1];
  22562. }
  22563. for (ii = 0; ii < 4; ++ii) {
  22564. for (jj = 0; jj < 256; jj += 2) {
  22565. this._encrypt_block(vals);
  22566. this.sboxes[ii][jj + 0] = vals[0];
  22567. this.sboxes[ii][jj + 1] = vals[1];
  22568. }
  22569. }
  22570. };
  22571. // added by Recurity Labs
  22572. function BF(key) {
  22573. this.bf = new Blowfish();
  22574. this.bf.init(key);
  22575. this.encrypt = function (block) {
  22576. return this.bf.encrypt_block(block);
  22577. };
  22578. }
  22579. BF.keySize = BF.prototype.keySize = 16;
  22580. BF.blockSize = BF.prototype.blockSize = 16;
  22581. exports.default = BF;
  22582. },{}],84:[function(require,module,exports){
  22583. 'use strict';
  22584. Object.defineProperty(exports, "__esModule", {
  22585. value: true
  22586. });
  22587. // Use of this source code is governed by a BSD-style
  22588. // license that can be found in the LICENSE file.
  22589. // Copyright 2010 pjacobs@xeekr.com . All rights reserved.
  22590. // Modified by Recurity Labs GmbH
  22591. // fixed/modified by Herbert Hanewinkel, www.haneWIN.de
  22592. // check www.haneWIN.de for the latest version
  22593. // cast5.js is a Javascript implementation of CAST-128, as defined in RFC 2144.
  22594. // CAST-128 is a common OpenPGP cipher.
  22595. // CAST5 constructor
  22596. function OpenpgpSymencCast5() {
  22597. this.BlockSize = 8;
  22598. this.KeySize = 16;
  22599. this.setKey = function (key) {
  22600. this.masking = new Array(16);
  22601. this.rotate = new Array(16);
  22602. this.reset();
  22603. if (key.length === this.KeySize) {
  22604. this.keySchedule(key);
  22605. } else {
  22606. throw new Error('CAST-128: keys must be 16 bytes');
  22607. }
  22608. return true;
  22609. };
  22610. this.reset = function () {
  22611. for (let i = 0; i < 16; i++) {
  22612. this.masking[i] = 0;
  22613. this.rotate[i] = 0;
  22614. }
  22615. };
  22616. this.getBlockSize = function () {
  22617. return this.BlockSize;
  22618. };
  22619. this.encrypt = function (src) {
  22620. const dst = new Array(src.length);
  22621. for (let i = 0; i < src.length; i += 8) {
  22622. let l = src[i] << 24 | src[i + 1] << 16 | src[i + 2] << 8 | src[i + 3];
  22623. let r = src[i + 4] << 24 | src[i + 5] << 16 | src[i + 6] << 8 | src[i + 7];
  22624. let t;
  22625. t = r;
  22626. r = l ^ f1(r, this.masking[0], this.rotate[0]);
  22627. l = t;
  22628. t = r;
  22629. r = l ^ f2(r, this.masking[1], this.rotate[1]);
  22630. l = t;
  22631. t = r;
  22632. r = l ^ f3(r, this.masking[2], this.rotate[2]);
  22633. l = t;
  22634. t = r;
  22635. r = l ^ f1(r, this.masking[3], this.rotate[3]);
  22636. l = t;
  22637. t = r;
  22638. r = l ^ f2(r, this.masking[4], this.rotate[4]);
  22639. l = t;
  22640. t = r;
  22641. r = l ^ f3(r, this.masking[5], this.rotate[5]);
  22642. l = t;
  22643. t = r;
  22644. r = l ^ f1(r, this.masking[6], this.rotate[6]);
  22645. l = t;
  22646. t = r;
  22647. r = l ^ f2(r, this.masking[7], this.rotate[7]);
  22648. l = t;
  22649. t = r;
  22650. r = l ^ f3(r, this.masking[8], this.rotate[8]);
  22651. l = t;
  22652. t = r;
  22653. r = l ^ f1(r, this.masking[9], this.rotate[9]);
  22654. l = t;
  22655. t = r;
  22656. r = l ^ f2(r, this.masking[10], this.rotate[10]);
  22657. l = t;
  22658. t = r;
  22659. r = l ^ f3(r, this.masking[11], this.rotate[11]);
  22660. l = t;
  22661. t = r;
  22662. r = l ^ f1(r, this.masking[12], this.rotate[12]);
  22663. l = t;
  22664. t = r;
  22665. r = l ^ f2(r, this.masking[13], this.rotate[13]);
  22666. l = t;
  22667. t = r;
  22668. r = l ^ f3(r, this.masking[14], this.rotate[14]);
  22669. l = t;
  22670. t = r;
  22671. r = l ^ f1(r, this.masking[15], this.rotate[15]);
  22672. l = t;
  22673. dst[i] = r >>> 24 & 255;
  22674. dst[i + 1] = r >>> 16 & 255;
  22675. dst[i + 2] = r >>> 8 & 255;
  22676. dst[i + 3] = r & 255;
  22677. dst[i + 4] = l >>> 24 & 255;
  22678. dst[i + 5] = l >>> 16 & 255;
  22679. dst[i + 6] = l >>> 8 & 255;
  22680. dst[i + 7] = l & 255;
  22681. }
  22682. return dst;
  22683. };
  22684. this.decrypt = function (src) {
  22685. const dst = new Array(src.length);
  22686. for (let i = 0; i < src.length; i += 8) {
  22687. let l = src[i] << 24 | src[i + 1] << 16 | src[i + 2] << 8 | src[i + 3];
  22688. let r = src[i + 4] << 24 | src[i + 5] << 16 | src[i + 6] << 8 | src[i + 7];
  22689. let t;
  22690. t = r;
  22691. r = l ^ f1(r, this.masking[15], this.rotate[15]);
  22692. l = t;
  22693. t = r;
  22694. r = l ^ f3(r, this.masking[14], this.rotate[14]);
  22695. l = t;
  22696. t = r;
  22697. r = l ^ f2(r, this.masking[13], this.rotate[13]);
  22698. l = t;
  22699. t = r;
  22700. r = l ^ f1(r, this.masking[12], this.rotate[12]);
  22701. l = t;
  22702. t = r;
  22703. r = l ^ f3(r, this.masking[11], this.rotate[11]);
  22704. l = t;
  22705. t = r;
  22706. r = l ^ f2(r, this.masking[10], this.rotate[10]);
  22707. l = t;
  22708. t = r;
  22709. r = l ^ f1(r, this.masking[9], this.rotate[9]);
  22710. l = t;
  22711. t = r;
  22712. r = l ^ f3(r, this.masking[8], this.rotate[8]);
  22713. l = t;
  22714. t = r;
  22715. r = l ^ f2(r, this.masking[7], this.rotate[7]);
  22716. l = t;
  22717. t = r;
  22718. r = l ^ f1(r, this.masking[6], this.rotate[6]);
  22719. l = t;
  22720. t = r;
  22721. r = l ^ f3(r, this.masking[5], this.rotate[5]);
  22722. l = t;
  22723. t = r;
  22724. r = l ^ f2(r, this.masking[4], this.rotate[4]);
  22725. l = t;
  22726. t = r;
  22727. r = l ^ f1(r, this.masking[3], this.rotate[3]);
  22728. l = t;
  22729. t = r;
  22730. r = l ^ f3(r, this.masking[2], this.rotate[2]);
  22731. l = t;
  22732. t = r;
  22733. r = l ^ f2(r, this.masking[1], this.rotate[1]);
  22734. l = t;
  22735. t = r;
  22736. r = l ^ f1(r, this.masking[0], this.rotate[0]);
  22737. l = t;
  22738. dst[i] = r >>> 24 & 255;
  22739. dst[i + 1] = r >>> 16 & 255;
  22740. dst[i + 2] = r >>> 8 & 255;
  22741. dst[i + 3] = r & 255;
  22742. dst[i + 4] = l >>> 24 & 255;
  22743. dst[i + 5] = l >> 16 & 255;
  22744. dst[i + 6] = l >> 8 & 255;
  22745. dst[i + 7] = l & 255;
  22746. }
  22747. return dst;
  22748. };
  22749. const scheduleA = new Array(4);
  22750. scheduleA[0] = new Array(4);
  22751. scheduleA[0][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 0x8];
  22752. scheduleA[0][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];
  22753. scheduleA[0][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];
  22754. scheduleA[0][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];
  22755. scheduleA[1] = new Array(4);
  22756. scheduleA[1][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];
  22757. scheduleA[1][1] = [1, 4, 0, 2, 1, 3, 16 + 2];
  22758. scheduleA[1][2] = [2, 5, 7, 6, 5, 4, 16 + 1];
  22759. scheduleA[1][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];
  22760. scheduleA[2] = new Array(4);
  22761. scheduleA[2][0] = [4, 0, 0xd, 0xf, 0xc, 0xe, 8];
  22762. scheduleA[2][1] = [5, 2, 16 + 0, 16 + 2, 16 + 1, 16 + 3, 0xa];
  22763. scheduleA[2][2] = [6, 3, 16 + 7, 16 + 6, 16 + 5, 16 + 4, 9];
  22764. scheduleA[2][3] = [7, 1, 16 + 0xa, 16 + 9, 16 + 0xb, 16 + 8, 0xb];
  22765. scheduleA[3] = new Array(4);
  22766. scheduleA[3][0] = [0, 6, 16 + 5, 16 + 7, 16 + 4, 16 + 6, 16 + 0];
  22767. scheduleA[3][1] = [1, 4, 0, 2, 1, 3, 16 + 2];
  22768. scheduleA[3][2] = [2, 5, 7, 6, 5, 4, 16 + 1];
  22769. scheduleA[3][3] = [3, 7, 0xa, 9, 0xb, 8, 16 + 3];
  22770. const scheduleB = new Array(4);
  22771. scheduleB[0] = new Array(4);
  22772. scheduleB[0][0] = [16 + 8, 16 + 9, 16 + 7, 16 + 6, 16 + 2];
  22773. scheduleB[0][1] = [16 + 0xa, 16 + 0xb, 16 + 5, 16 + 4, 16 + 6];
  22774. scheduleB[0][2] = [16 + 0xc, 16 + 0xd, 16 + 3, 16 + 2, 16 + 9];
  22775. scheduleB[0][3] = [16 + 0xe, 16 + 0xf, 16 + 1, 16 + 0, 16 + 0xc];
  22776. scheduleB[1] = new Array(4);
  22777. scheduleB[1][0] = [3, 2, 0xc, 0xd, 8];
  22778. scheduleB[1][1] = [1, 0, 0xe, 0xf, 0xd];
  22779. scheduleB[1][2] = [7, 6, 8, 9, 3];
  22780. scheduleB[1][3] = [5, 4, 0xa, 0xb, 7];
  22781. scheduleB[2] = new Array(4);
  22782. scheduleB[2][0] = [16 + 3, 16 + 2, 16 + 0xc, 16 + 0xd, 16 + 9];
  22783. scheduleB[2][1] = [16 + 1, 16 + 0, 16 + 0xe, 16 + 0xf, 16 + 0xc];
  22784. scheduleB[2][2] = [16 + 7, 16 + 6, 16 + 8, 16 + 9, 16 + 2];
  22785. scheduleB[2][3] = [16 + 5, 16 + 4, 16 + 0xa, 16 + 0xb, 16 + 6];
  22786. scheduleB[3] = new Array(4);
  22787. scheduleB[3][0] = [8, 9, 7, 6, 3];
  22788. scheduleB[3][1] = [0xa, 0xb, 5, 4, 7];
  22789. scheduleB[3][2] = [0xc, 0xd, 3, 2, 8];
  22790. scheduleB[3][3] = [0xe, 0xf, 1, 0, 0xd];
  22791. // changed 'in' to 'inn' (in javascript 'in' is a reserved word)
  22792. this.keySchedule = function (inn) {
  22793. const t = new Array(8);
  22794. const k = new Array(32);
  22795. let j;
  22796. for (let i = 0; i < 4; i++) {
  22797. j = i * 4;
  22798. t[i] = inn[j] << 24 | inn[j + 1] << 16 | inn[j + 2] << 8 | inn[j + 3];
  22799. }
  22800. const x = [6, 7, 4, 5];
  22801. let ki = 0;
  22802. let w;
  22803. for (let half = 0; half < 2; half++) {
  22804. for (let round = 0; round < 4; round++) {
  22805. for (j = 0; j < 4; j++) {
  22806. const a = scheduleA[round][j];
  22807. w = t[a[1]];
  22808. w ^= sBox[4][t[a[2] >>> 2] >>> 24 - 8 * (a[2] & 3) & 0xff];
  22809. w ^= sBox[5][t[a[3] >>> 2] >>> 24 - 8 * (a[3] & 3) & 0xff];
  22810. w ^= sBox[6][t[a[4] >>> 2] >>> 24 - 8 * (a[4] & 3) & 0xff];
  22811. w ^= sBox[7][t[a[5] >>> 2] >>> 24 - 8 * (a[5] & 3) & 0xff];
  22812. w ^= sBox[x[j]][t[a[6] >>> 2] >>> 24 - 8 * (a[6] & 3) & 0xff];
  22813. t[a[0]] = w;
  22814. }
  22815. for (j = 0; j < 4; j++) {
  22816. const b = scheduleB[round][j];
  22817. w = sBox[4][t[b[0] >>> 2] >>> 24 - 8 * (b[0] & 3) & 0xff];
  22818. w ^= sBox[5][t[b[1] >>> 2] >>> 24 - 8 * (b[1] & 3) & 0xff];
  22819. w ^= sBox[6][t[b[2] >>> 2] >>> 24 - 8 * (b[2] & 3) & 0xff];
  22820. w ^= sBox[7][t[b[3] >>> 2] >>> 24 - 8 * (b[3] & 3) & 0xff];
  22821. w ^= sBox[4 + j][t[b[4] >>> 2] >>> 24 - 8 * (b[4] & 3) & 0xff];
  22822. k[ki] = w;
  22823. ki++;
  22824. }
  22825. }
  22826. }
  22827. for (let i = 0; i < 16; i++) {
  22828. this.masking[i] = k[i];
  22829. this.rotate[i] = k[16 + i] & 0x1f;
  22830. }
  22831. };
  22832. // These are the three 'f' functions. See RFC 2144, section 2.2.
  22833. function f1(d, m, r) {
  22834. const t = m + d;
  22835. const I = t << r | t >>> 32 - r;
  22836. return (sBox[0][I >>> 24] ^ sBox[1][I >>> 16 & 255]) - sBox[2][I >>> 8 & 255] + sBox[3][I & 255];
  22837. }
  22838. function f2(d, m, r) {
  22839. const t = m ^ d;
  22840. const I = t << r | t >>> 32 - r;
  22841. return sBox[0][I >>> 24] - sBox[1][I >>> 16 & 255] + sBox[2][I >>> 8 & 255] ^ sBox[3][I & 255];
  22842. }
  22843. function f3(d, m, r) {
  22844. const t = m - d;
  22845. const I = t << r | t >>> 32 - r;
  22846. return (sBox[0][I >>> 24] + sBox[1][I >>> 16 & 255] ^ sBox[2][I >>> 8 & 255]) - sBox[3][I & 255];
  22847. }
  22848. const sBox = new Array(8);
  22849. sBox[0] = [0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949, 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e, 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d, 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0, 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7, 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935, 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d, 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50, 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe, 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3, 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167, 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291, 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779, 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2, 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511, 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d, 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5, 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324, 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c, 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc, 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d, 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96, 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a, 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d, 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd, 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6, 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9, 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872, 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c, 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e, 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9, 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf];
  22850. sBox[1] = [0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651, 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3, 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb, 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806, 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b, 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359, 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b, 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c, 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34, 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb, 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd, 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860, 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b, 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304, 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b, 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf, 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c, 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13, 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f, 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6, 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6, 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58, 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906, 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d, 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6, 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4, 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6, 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f, 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249, 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa, 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9, 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1];
  22851. sBox[2] = [0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90, 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5, 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e, 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240, 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5, 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b, 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71, 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04, 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82, 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15, 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2, 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176, 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148, 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc, 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341, 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e, 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51, 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f, 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a, 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b, 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b, 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5, 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45, 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536, 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc, 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0, 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69, 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2, 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49, 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d, 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a, 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783];
  22852. sBox[3] = [0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1, 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf, 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15, 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121, 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25, 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5, 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb, 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5, 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d, 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6, 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23, 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003, 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6, 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119, 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24, 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a, 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79, 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df, 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26, 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab, 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7, 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417, 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2, 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2, 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a, 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919, 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef, 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876, 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab, 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04, 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282, 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2];
  22853. sBox[4] = [0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f, 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a, 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff, 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02, 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a, 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7, 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9, 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981, 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774, 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655, 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2, 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910, 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1, 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da, 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049, 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f, 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba, 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be, 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3, 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840, 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4, 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2, 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7, 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5, 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e, 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e, 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801, 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad, 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0, 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20, 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8, 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4];
  22854. sBox[5] = [0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac, 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138, 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367, 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98, 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072, 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3, 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd, 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8, 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9, 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54, 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387, 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc, 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf, 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf, 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f, 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289, 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950, 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f, 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b, 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be, 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13, 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976, 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0, 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891, 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da, 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc, 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084, 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25, 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121, 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5, 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd, 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f];
  22855. sBox[6] = [0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f, 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de, 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43, 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19, 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2, 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516, 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88, 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816, 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756, 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a, 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264, 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688, 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28, 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3, 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7, 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06, 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033, 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a, 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566, 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509, 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962, 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e, 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c, 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c, 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285, 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301, 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be, 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767, 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647, 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914, 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c, 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3];
  22856. sBox[7] = [0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5, 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc, 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd, 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d, 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2, 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862, 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc, 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c, 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e, 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039, 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8, 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42, 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5, 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472, 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225, 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c, 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb, 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054, 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70, 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc, 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c, 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3, 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4, 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101, 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f, 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e, 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a, 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c, 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384, 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c, 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82, 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e];
  22857. }
  22858. function Cast5(key) {
  22859. this.cast5 = new OpenpgpSymencCast5();
  22860. this.cast5.setKey(key);
  22861. this.encrypt = function (block) {
  22862. return this.cast5.encrypt(block);
  22863. };
  22864. }
  22865. Cast5.blockSize = Cast5.prototype.blockSize = 8;
  22866. Cast5.keySize = Cast5.prototype.keySize = 16;
  22867. exports.default = Cast5;
  22868. },{}],85:[function(require,module,exports){
  22869. "use strict";
  22870. Object.defineProperty(exports, "__esModule", {
  22871. value: true
  22872. });
  22873. //Paul Tero, July 2001
  22874. //http://www.tero.co.uk/des/
  22875. //
  22876. //Optimised for performance with large blocks by Michael Hayworth, November 2001
  22877. //http://www.netdealing.com
  22878. //
  22879. // Modified by Recurity Labs GmbH
  22880. //THIS SOFTWARE IS PROVIDED "AS IS" AND
  22881. //ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  22882. //IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  22883. //ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  22884. //FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  22885. //DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  22886. //OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  22887. //HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  22888. //LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  22889. //OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  22890. //SUCH DAMAGE.
  22891. //des
  22892. //this takes the key, the message, and whether to encrypt or decrypt
  22893. function des(keys, message, encrypt, mode, iv, padding) {
  22894. //declaring this locally speeds things up a bit
  22895. const spfunction1 = [0x1010400, 0, 0x10000, 0x1010404, 0x1010004, 0x10404, 0x4, 0x10000, 0x400, 0x1010400, 0x1010404, 0x400, 0x1000404, 0x1010004, 0x1000000, 0x4, 0x404, 0x1000400, 0x1000400, 0x10400, 0x10400, 0x1010000, 0x1010000, 0x1000404, 0x10004, 0x1000004, 0x1000004, 0x10004, 0, 0x404, 0x10404, 0x1000000, 0x10000, 0x1010404, 0x4, 0x1010000, 0x1010400, 0x1000000, 0x1000000, 0x400, 0x1010004, 0x10000, 0x10400, 0x1000004, 0x400, 0x4, 0x1000404, 0x10404, 0x1010404, 0x10004, 0x1010000, 0x1000404, 0x1000004, 0x404, 0x10404, 0x1010400, 0x404, 0x1000400, 0x1000400, 0, 0x10004, 0x10400, 0, 0x1010004];
  22896. const spfunction2 = [-0x7fef7fe0, -0x7fff8000, 0x8000, 0x108020, 0x100000, 0x20, -0x7fefffe0, -0x7fff7fe0, -0x7fffffe0, -0x7fef7fe0, -0x7fef8000, -0x80000000, -0x7fff8000, 0x100000, 0x20, -0x7fefffe0, 0x108000, 0x100020, -0x7fff7fe0, 0, -0x80000000, 0x8000, 0x108020, -0x7ff00000, 0x100020, -0x7fffffe0, 0, 0x108000, 0x8020, -0x7fef8000, -0x7ff00000, 0x8020, 0, 0x108020, -0x7fefffe0, 0x100000, -0x7fff7fe0, -0x7ff00000, -0x7fef8000, 0x8000, -0x7ff00000, -0x7fff8000, 0x20, -0x7fef7fe0, 0x108020, 0x20, 0x8000, -0x80000000, 0x8020, -0x7fef8000, 0x100000, -0x7fffffe0, 0x100020, -0x7fff7fe0, -0x7fffffe0, 0x100020, 0x108000, 0, -0x7fff8000, 0x8020, -0x80000000, -0x7fefffe0, -0x7fef7fe0, 0x108000];
  22897. const spfunction3 = [0x208, 0x8020200, 0, 0x8020008, 0x8000200, 0, 0x20208, 0x8000200, 0x20008, 0x8000008, 0x8000008, 0x20000, 0x8020208, 0x20008, 0x8020000, 0x208, 0x8000000, 0x8, 0x8020200, 0x200, 0x20200, 0x8020000, 0x8020008, 0x20208, 0x8000208, 0x20200, 0x20000, 0x8000208, 0x8, 0x8020208, 0x200, 0x8000000, 0x8020200, 0x8000000, 0x20008, 0x208, 0x20000, 0x8020200, 0x8000200, 0, 0x200, 0x20008, 0x8020208, 0x8000200, 0x8000008, 0x200, 0, 0x8020008, 0x8000208, 0x20000, 0x8000000, 0x8020208, 0x8, 0x20208, 0x20200, 0x8000008, 0x8020000, 0x8000208, 0x208, 0x8020000, 0x20208, 0x8, 0x8020008, 0x20200];
  22898. const spfunction4 = [0x802001, 0x2081, 0x2081, 0x80, 0x802080, 0x800081, 0x800001, 0x2001, 0, 0x802000, 0x802000, 0x802081, 0x81, 0, 0x800080, 0x800001, 0x1, 0x2000, 0x800000, 0x802001, 0x80, 0x800000, 0x2001, 0x2080, 0x800081, 0x1, 0x2080, 0x800080, 0x2000, 0x802080, 0x802081, 0x81, 0x800080, 0x800001, 0x802000, 0x802081, 0x81, 0, 0, 0x802000, 0x2080, 0x800080, 0x800081, 0x1, 0x802001, 0x2081, 0x2081, 0x80, 0x802081, 0x81, 0x1, 0x2000, 0x800001, 0x2001, 0x802080, 0x800081, 0x2001, 0x2080, 0x800000, 0x802001, 0x80, 0x800000, 0x2000, 0x802080];
  22899. const spfunction5 = [0x100, 0x2080100, 0x2080000, 0x42000100, 0x80000, 0x100, 0x40000000, 0x2080000, 0x40080100, 0x80000, 0x2000100, 0x40080100, 0x42000100, 0x42080000, 0x80100, 0x40000000, 0x2000000, 0x40080000, 0x40080000, 0, 0x40000100, 0x42080100, 0x42080100, 0x2000100, 0x42080000, 0x40000100, 0, 0x42000000, 0x2080100, 0x2000000, 0x42000000, 0x80100, 0x80000, 0x42000100, 0x100, 0x2000000, 0x40000000, 0x2080000, 0x42000100, 0x40080100, 0x2000100, 0x40000000, 0x42080000, 0x2080100, 0x40080100, 0x100, 0x2000000, 0x42080000, 0x42080100, 0x80100, 0x42000000, 0x42080100, 0x2080000, 0, 0x40080000, 0x42000000, 0x80100, 0x2000100, 0x40000100, 0x80000, 0, 0x40080000, 0x2080100, 0x40000100];
  22900. const spfunction6 = [0x20000010, 0x20400000, 0x4000, 0x20404010, 0x20400000, 0x10, 0x20404010, 0x400000, 0x20004000, 0x404010, 0x400000, 0x20000010, 0x400010, 0x20004000, 0x20000000, 0x4010, 0, 0x400010, 0x20004010, 0x4000, 0x404000, 0x20004010, 0x10, 0x20400010, 0x20400010, 0, 0x404010, 0x20404000, 0x4010, 0x404000, 0x20404000, 0x20000000, 0x20004000, 0x10, 0x20400010, 0x404000, 0x20404010, 0x400000, 0x4010, 0x20000010, 0x400000, 0x20004000, 0x20000000, 0x4010, 0x20000010, 0x20404010, 0x404000, 0x20400000, 0x404010, 0x20404000, 0, 0x20400010, 0x10, 0x4000, 0x20400000, 0x404010, 0x4000, 0x400010, 0x20004010, 0, 0x20404000, 0x20000000, 0x400010, 0x20004010];
  22901. const spfunction7 = [0x200000, 0x4200002, 0x4000802, 0, 0x800, 0x4000802, 0x200802, 0x4200800, 0x4200802, 0x200000, 0, 0x4000002, 0x2, 0x4000000, 0x4200002, 0x802, 0x4000800, 0x200802, 0x200002, 0x4000800, 0x4000002, 0x4200000, 0x4200800, 0x200002, 0x4200000, 0x800, 0x802, 0x4200802, 0x200800, 0x2, 0x4000000, 0x200800, 0x4000000, 0x200800, 0x200000, 0x4000802, 0x4000802, 0x4200002, 0x4200002, 0x2, 0x200002, 0x4000000, 0x4000800, 0x200000, 0x4200800, 0x802, 0x200802, 0x4200800, 0x802, 0x4000002, 0x4200802, 0x4200000, 0x200800, 0, 0x2, 0x4200802, 0, 0x200802, 0x4200000, 0x800, 0x4000002, 0x4000800, 0x800, 0x200002];
  22902. const spfunction8 = [0x10001040, 0x1000, 0x40000, 0x10041040, 0x10000000, 0x10001040, 0x40, 0x10000000, 0x40040, 0x10040000, 0x10041040, 0x41000, 0x10041000, 0x41040, 0x1000, 0x40, 0x10040000, 0x10000040, 0x10001000, 0x1040, 0x41000, 0x40040, 0x10040040, 0x10041000, 0x1040, 0, 0, 0x10040040, 0x10000040, 0x10001000, 0x41040, 0x40000, 0x41040, 0x40000, 0x10041000, 0x1000, 0x40, 0x10040040, 0x1000, 0x41040, 0x10001000, 0x40, 0x10000040, 0x10040000, 0x10040040, 0x10000000, 0x40000, 0x10001040, 0, 0x10041040, 0x40040, 0x10000040, 0x10040000, 0x10001000, 0x10001040, 0, 0x10041040, 0x41000, 0x41000, 0x1040, 0x1040, 0x40040, 0x10000000, 0x10041000];
  22903. //create the 16 or 48 subkeys we will need
  22904. let m = 0;
  22905. let i;
  22906. let j;
  22907. let temp;
  22908. let right1;
  22909. let right2;
  22910. let left;
  22911. let right;
  22912. let looping;
  22913. let cbcleft;
  22914. let cbcleft2;
  22915. let cbcright;
  22916. let cbcright2;
  22917. let endloop;
  22918. let loopinc;
  22919. let len = message.length;
  22920. //set up the loops for single and triple des
  22921. const iterations = keys.length === 32 ? 3 : 9; //single or triple des
  22922. if (iterations === 3) {
  22923. looping = encrypt ? [0, 32, 2] : [30, -2, -2];
  22924. } else {
  22925. looping = encrypt ? [0, 32, 2, 62, 30, -2, 64, 96, 2] : [94, 62, -2, 32, 64, 2, 30, -2, -2];
  22926. }
  22927. //pad the message depending on the padding parameter
  22928. //only add padding if encrypting - note that you need to use the same padding option for both encrypt and decrypt
  22929. if (encrypt) {
  22930. message = des_addPadding(message, padding);
  22931. len = message.length;
  22932. }
  22933. //store the result here
  22934. let result = new Uint8Array(len);
  22935. let k = 0;
  22936. if (mode === 1) {
  22937. //CBC mode
  22938. cbcleft = iv[m++] << 24 | iv[m++] << 16 | iv[m++] << 8 | iv[m++];
  22939. cbcright = iv[m++] << 24 | iv[m++] << 16 | iv[m++] << 8 | iv[m++];
  22940. m = 0;
  22941. }
  22942. //loop through each 64 bit chunk of the message
  22943. while (m < len) {
  22944. left = message[m++] << 24 | message[m++] << 16 | message[m++] << 8 | message[m++];
  22945. right = message[m++] << 24 | message[m++] << 16 | message[m++] << 8 | message[m++];
  22946. //for Cipher Block Chaining mode, xor the message with the previous result
  22947. if (mode === 1) {
  22948. if (encrypt) {
  22949. left ^= cbcleft;
  22950. right ^= cbcright;
  22951. } else {
  22952. cbcleft2 = cbcleft;
  22953. cbcright2 = cbcright;
  22954. cbcleft = left;
  22955. cbcright = right;
  22956. }
  22957. }
  22958. //first each 64 but chunk of the message must be permuted according to IP
  22959. temp = (left >>> 4 ^ right) & 0x0f0f0f0f;
  22960. right ^= temp;
  22961. left ^= temp << 4;
  22962. temp = (left >>> 16 ^ right) & 0x0000ffff;
  22963. right ^= temp;
  22964. left ^= temp << 16;
  22965. temp = (right >>> 2 ^ left) & 0x33333333;
  22966. left ^= temp;
  22967. right ^= temp << 2;
  22968. temp = (right >>> 8 ^ left) & 0x00ff00ff;
  22969. left ^= temp;
  22970. right ^= temp << 8;
  22971. temp = (left >>> 1 ^ right) & 0x55555555;
  22972. right ^= temp;
  22973. left ^= temp << 1;
  22974. left = left << 1 | left >>> 31;
  22975. right = right << 1 | right >>> 31;
  22976. //do this either 1 or 3 times for each chunk of the message
  22977. for (j = 0; j < iterations; j += 3) {
  22978. endloop = looping[j + 1];
  22979. loopinc = looping[j + 2];
  22980. //now go through and perform the encryption or decryption
  22981. for (i = looping[j]; i !== endloop; i += loopinc) {
  22982. //for efficiency
  22983. right1 = right ^ keys[i];
  22984. right2 = (right >>> 4 | right << 28) ^ keys[i + 1];
  22985. //the result is attained by passing these bytes through the S selection functions
  22986. temp = left;
  22987. left = right;
  22988. right = temp ^ (spfunction2[right1 >>> 24 & 0x3f] | spfunction4[right1 >>> 16 & 0x3f] | spfunction6[right1 >>> 8 & 0x3f] | spfunction8[right1 & 0x3f] | spfunction1[right2 >>> 24 & 0x3f] | spfunction3[right2 >>> 16 & 0x3f] | spfunction5[right2 >>> 8 & 0x3f] | spfunction7[right2 & 0x3f]);
  22989. }
  22990. temp = left;
  22991. left = right;
  22992. right = temp; //unreverse left and right
  22993. } //for either 1 or 3 iterations
  22994. //move then each one bit to the right
  22995. left = left >>> 1 | left << 31;
  22996. right = right >>> 1 | right << 31;
  22997. //now perform IP-1, which is IP in the opposite direction
  22998. temp = (left >>> 1 ^ right) & 0x55555555;
  22999. right ^= temp;
  23000. left ^= temp << 1;
  23001. temp = (right >>> 8 ^ left) & 0x00ff00ff;
  23002. left ^= temp;
  23003. right ^= temp << 8;
  23004. temp = (right >>> 2 ^ left) & 0x33333333;
  23005. left ^= temp;
  23006. right ^= temp << 2;
  23007. temp = (left >>> 16 ^ right) & 0x0000ffff;
  23008. right ^= temp;
  23009. left ^= temp << 16;
  23010. temp = (left >>> 4 ^ right) & 0x0f0f0f0f;
  23011. right ^= temp;
  23012. left ^= temp << 4;
  23013. //for Cipher Block Chaining mode, xor the message with the previous result
  23014. if (mode === 1) {
  23015. if (encrypt) {
  23016. cbcleft = left;
  23017. cbcright = right;
  23018. } else {
  23019. left ^= cbcleft2;
  23020. right ^= cbcright2;
  23021. }
  23022. }
  23023. result[k++] = left >>> 24;
  23024. result[k++] = left >>> 16 & 0xff;
  23025. result[k++] = left >>> 8 & 0xff;
  23026. result[k++] = left & 0xff;
  23027. result[k++] = right >>> 24;
  23028. result[k++] = right >>> 16 & 0xff;
  23029. result[k++] = right >>> 8 & 0xff;
  23030. result[k++] = right & 0xff;
  23031. } //for every 8 characters, or 64 bits in the message
  23032. //only remove padding if decrypting - note that you need to use the same padding option for both encrypt and decrypt
  23033. if (!encrypt) {
  23034. result = des_removePadding(result, padding);
  23035. }
  23036. return result;
  23037. } //end of des
  23038. //des_createKeys
  23039. //this takes as input a 64 bit key (even though only 56 bits are used)
  23040. //as an array of 2 integers, and returns 16 48 bit keys
  23041. function des_createKeys(key) {
  23042. //declaring this locally speeds things up a bit
  23043. const pc2bytes0 = [0, 0x4, 0x20000000, 0x20000004, 0x10000, 0x10004, 0x20010000, 0x20010004, 0x200, 0x204, 0x20000200, 0x20000204, 0x10200, 0x10204, 0x20010200, 0x20010204];
  23044. const pc2bytes1 = [0, 0x1, 0x100000, 0x100001, 0x4000000, 0x4000001, 0x4100000, 0x4100001, 0x100, 0x101, 0x100100, 0x100101, 0x4000100, 0x4000101, 0x4100100, 0x4100101];
  23045. const pc2bytes2 = [0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808, 0, 0x8, 0x800, 0x808, 0x1000000, 0x1000008, 0x1000800, 0x1000808];
  23046. const pc2bytes3 = [0, 0x200000, 0x8000000, 0x8200000, 0x2000, 0x202000, 0x8002000, 0x8202000, 0x20000, 0x220000, 0x8020000, 0x8220000, 0x22000, 0x222000, 0x8022000, 0x8222000];
  23047. const pc2bytes4 = [0, 0x40000, 0x10, 0x40010, 0, 0x40000, 0x10, 0x40010, 0x1000, 0x41000, 0x1010, 0x41010, 0x1000, 0x41000, 0x1010, 0x41010];
  23048. const pc2bytes5 = [0, 0x400, 0x20, 0x420, 0, 0x400, 0x20, 0x420, 0x2000000, 0x2000400, 0x2000020, 0x2000420, 0x2000000, 0x2000400, 0x2000020, 0x2000420];
  23049. const pc2bytes6 = [0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002, 0, 0x10000000, 0x80000, 0x10080000, 0x2, 0x10000002, 0x80002, 0x10080002];
  23050. const pc2bytes7 = [0, 0x10000, 0x800, 0x10800, 0x20000000, 0x20010000, 0x20000800, 0x20010800, 0x20000, 0x30000, 0x20800, 0x30800, 0x20020000, 0x20030000, 0x20020800, 0x20030800];
  23051. const pc2bytes8 = [0, 0x40000, 0, 0x40000, 0x2, 0x40002, 0x2, 0x40002, 0x2000000, 0x2040000, 0x2000000, 0x2040000, 0x2000002, 0x2040002, 0x2000002, 0x2040002];
  23052. const pc2bytes9 = [0, 0x10000000, 0x8, 0x10000008, 0, 0x10000000, 0x8, 0x10000008, 0x400, 0x10000400, 0x408, 0x10000408, 0x400, 0x10000400, 0x408, 0x10000408];
  23053. const pc2bytes10 = [0, 0x20, 0, 0x20, 0x100000, 0x100020, 0x100000, 0x100020, 0x2000, 0x2020, 0x2000, 0x2020, 0x102000, 0x102020, 0x102000, 0x102020];
  23054. const pc2bytes11 = [0, 0x1000000, 0x200, 0x1000200, 0x200000, 0x1200000, 0x200200, 0x1200200, 0x4000000, 0x5000000, 0x4000200, 0x5000200, 0x4200000, 0x5200000, 0x4200200, 0x5200200];
  23055. const pc2bytes12 = [0, 0x1000, 0x8000000, 0x8001000, 0x80000, 0x81000, 0x8080000, 0x8081000, 0x10, 0x1010, 0x8000010, 0x8001010, 0x80010, 0x81010, 0x8080010, 0x8081010];
  23056. const pc2bytes13 = [0, 0x4, 0x100, 0x104, 0, 0x4, 0x100, 0x104, 0x1, 0x5, 0x101, 0x105, 0x1, 0x5, 0x101, 0x105];
  23057. //how many iterations (1 for des, 3 for triple des)
  23058. const iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys
  23059. //stores the return keys
  23060. const keys = new Array(32 * iterations);
  23061. //now define the left shifts which need to be done
  23062. const shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];
  23063. //other variables
  23064. let lefttemp;
  23065. let righttemp;
  23066. let m = 0;
  23067. let n = 0;
  23068. let temp;
  23069. for (let j = 0; j < iterations; j++) {
  23070. //either 1 or 3 iterations
  23071. let left = key[m++] << 24 | key[m++] << 16 | key[m++] << 8 | key[m++];
  23072. let right = key[m++] << 24 | key[m++] << 16 | key[m++] << 8 | key[m++];
  23073. temp = (left >>> 4 ^ right) & 0x0f0f0f0f;
  23074. right ^= temp;
  23075. left ^= temp << 4;
  23076. temp = (right >>> -16 ^ left) & 0x0000ffff;
  23077. left ^= temp;
  23078. right ^= temp << -16;
  23079. temp = (left >>> 2 ^ right) & 0x33333333;
  23080. right ^= temp;
  23081. left ^= temp << 2;
  23082. temp = (right >>> -16 ^ left) & 0x0000ffff;
  23083. left ^= temp;
  23084. right ^= temp << -16;
  23085. temp = (left >>> 1 ^ right) & 0x55555555;
  23086. right ^= temp;
  23087. left ^= temp << 1;
  23088. temp = (right >>> 8 ^ left) & 0x00ff00ff;
  23089. left ^= temp;
  23090. right ^= temp << 8;
  23091. temp = (left >>> 1 ^ right) & 0x55555555;
  23092. right ^= temp;
  23093. left ^= temp << 1;
  23094. //the right side needs to be shifted and to get the last four bits of the left side
  23095. temp = left << 8 | right >>> 20 & 0x000000f0;
  23096. //left needs to be put upside down
  23097. left = right << 24 | right << 8 & 0xff0000 | right >>> 8 & 0xff00 | right >>> 24 & 0xf0;
  23098. right = temp;
  23099. //now go through and perform these shifts on the left and right keys
  23100. for (let i = 0; i < shifts.length; i++) {
  23101. //shift the keys either one or two bits to the left
  23102. if (shifts[i]) {
  23103. left = left << 2 | left >>> 26;
  23104. right = right << 2 | right >>> 26;
  23105. } else {
  23106. left = left << 1 | left >>> 27;
  23107. right = right << 1 | right >>> 27;
  23108. }
  23109. left &= -0xf;
  23110. right &= -0xf;
  23111. //now apply PC-2, in such a way that E is easier when encrypting or decrypting
  23112. //this conversion will look like PC-2 except only the last 6 bits of each byte are used
  23113. //rather than 48 consecutive bits and the order of lines will be according to
  23114. //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7
  23115. lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[left >>> 24 & 0xf] | pc2bytes2[left >>> 20 & 0xf] | pc2bytes3[left >>> 16 & 0xf] | pc2bytes4[left >>> 12 & 0xf] | pc2bytes5[left >>> 8 & 0xf] | pc2bytes6[left >>> 4 & 0xf];
  23116. righttemp = pc2bytes7[right >>> 28] | pc2bytes8[right >>> 24 & 0xf] | pc2bytes9[right >>> 20 & 0xf] | pc2bytes10[right >>> 16 & 0xf] | pc2bytes11[right >>> 12 & 0xf] | pc2bytes12[right >>> 8 & 0xf] | pc2bytes13[right >>> 4 & 0xf];
  23117. temp = (righttemp >>> 16 ^ lefttemp) & 0x0000ffff;
  23118. keys[n++] = lefttemp ^ temp;
  23119. keys[n++] = righttemp ^ temp << 16;
  23120. }
  23121. } //for each iterations
  23122. //return the keys we've created
  23123. return keys;
  23124. } //end of des_createKeys
  23125. function des_addPadding(message, padding) {
  23126. const padLength = 8 - message.length % 8;
  23127. let pad;
  23128. if (padding === 2 && padLength < 8) {
  23129. //pad the message with spaces
  23130. pad = " ".charCodeAt(0);
  23131. } else if (padding === 1) {
  23132. //PKCS7 padding
  23133. pad = padLength;
  23134. } else if (!padding && padLength < 8) {
  23135. //pad the message out with null bytes
  23136. pad = 0;
  23137. } else if (padLength === 8) {
  23138. return message;
  23139. } else {
  23140. throw new Error('des: invalid padding');
  23141. }
  23142. const paddedMessage = new Uint8Array(message.length + padLength);
  23143. for (let i = 0; i < message.length; i++) {
  23144. paddedMessage[i] = message[i];
  23145. }
  23146. for (let j = 0; j < padLength; j++) {
  23147. paddedMessage[message.length + j] = pad;
  23148. }
  23149. return paddedMessage;
  23150. }
  23151. function des_removePadding(message, padding) {
  23152. let padLength = null;
  23153. let pad;
  23154. if (padding === 2) {
  23155. // space padded
  23156. pad = " ".charCodeAt(0);
  23157. } else if (padding === 1) {
  23158. // PKCS7
  23159. padLength = message[message.length - 1];
  23160. } else if (!padding) {
  23161. // null padding
  23162. pad = 0;
  23163. } else {
  23164. throw new Error('des: invalid padding');
  23165. }
  23166. if (!padLength) {
  23167. padLength = 1;
  23168. while (message[message.length - padLength] === pad) {
  23169. padLength++;
  23170. }
  23171. padLength--;
  23172. }
  23173. return message.subarray(0, message.length - padLength);
  23174. }
  23175. // added by Recurity Labs
  23176. function TripleDES(key) {
  23177. this.key = [];
  23178. for (let i = 0; i < 3; i++) {
  23179. this.key.push(new Uint8Array(key.subarray(i * 8, i * 8 + 8)));
  23180. }
  23181. this.encrypt = function (block) {
  23182. return des(des_createKeys(this.key[2]), des(des_createKeys(this.key[1]), des(des_createKeys(this.key[0]), block, true, 0, null, null), false, 0, null, null), true, 0, null, null);
  23183. };
  23184. }
  23185. TripleDES.keySize = TripleDES.prototype.keySize = 24;
  23186. TripleDES.blockSize = TripleDES.prototype.blockSize = 8;
  23187. // This is "original" DES
  23188. function DES(key) {
  23189. this.key = key;
  23190. this.encrypt = function (block, padding) {
  23191. const keys = des_createKeys(this.key);
  23192. return des(keys, block, true, 0, null, padding);
  23193. };
  23194. this.decrypt = function (block, padding) {
  23195. const keys = des_createKeys(this.key);
  23196. return des(keys, block, false, 0, null, padding);
  23197. };
  23198. }
  23199. exports.default = { DES, TripleDES };
  23200. },{}],86:[function(require,module,exports){
  23201. 'use strict';
  23202. Object.defineProperty(exports, "__esModule", {
  23203. value: true
  23204. });
  23205. var _aes = require('./aes');
  23206. var _aes2 = _interopRequireDefault(_aes);
  23207. var _des = require('./des.js');
  23208. var _des2 = _interopRequireDefault(_des);
  23209. var _cast = require('./cast5');
  23210. var _cast2 = _interopRequireDefault(_cast);
  23211. var _twofish = require('./twofish');
  23212. var _twofish2 = _interopRequireDefault(_twofish);
  23213. var _blowfish = require('./blowfish');
  23214. var _blowfish2 = _interopRequireDefault(_blowfish);
  23215. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  23216. exports.default = {
  23217. /**
  23218. * AES-128 encryption and decryption (ID 7)
  23219. * @function
  23220. * @param {String} key 128-bit key
  23221. * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
  23222. * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
  23223. * @returns {Object}
  23224. * @requires asmcrypto.js
  23225. */
  23226. aes128: (0, _aes2.default)(128),
  23227. /**
  23228. * AES-128 Block Cipher (ID 8)
  23229. * @function
  23230. * @param {String} key 192-bit key
  23231. * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
  23232. * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
  23233. * @returns {Object}
  23234. * @requires asmcrypto.js
  23235. */
  23236. aes192: (0, _aes2.default)(192),
  23237. /**
  23238. * AES-128 Block Cipher (ID 9)
  23239. * @function
  23240. * @param {String} key 256-bit key
  23241. * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
  23242. * @see {@link https://csrc.nist.gov/publications/fips/fips197/fips-197.pdf|NIST FIPS-197}
  23243. * @returns {Object}
  23244. * @requires asmcrypto.js
  23245. */
  23246. aes256: (0, _aes2.default)(256),
  23247. // Not in OpenPGP specifications
  23248. des: _des2.default.DES,
  23249. /**
  23250. * Triple DES Block Cipher (ID 2)
  23251. * @function
  23252. * @param {String} key 192-bit key
  23253. * @see {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-67r2.pdf|NIST SP 800-67}
  23254. * @returns {Object}
  23255. */
  23256. tripledes: _des2.default.TripleDES,
  23257. '3des': _des2.default.TripleDES,
  23258. /**
  23259. * CAST-128 Block Cipher (ID 3)
  23260. * @function
  23261. * @param {String} key 128-bit key
  23262. * @see {@link https://tools.ietf.org/html/rfc2144|The CAST-128 Encryption Algorithm}
  23263. * @returns {Object}
  23264. */
  23265. cast5: _cast2.default,
  23266. /**
  23267. * Twofish Block Cipher (ID 10)
  23268. * @function
  23269. * @param {String} key 256-bit key
  23270. * @see {@link https://tools.ietf.org/html/rfc4880#ref-TWOFISH|TWOFISH}
  23271. * @returns {Object}
  23272. */
  23273. twofish: _twofish2.default,
  23274. /**
  23275. * Blowfish Block Cipher (ID 4)
  23276. * @function
  23277. * @param {String} key 128-bit key
  23278. * @see {@link https://tools.ietf.org/html/rfc4880#ref-BLOWFISH|BLOWFISH}
  23279. * @returns {Object}
  23280. */
  23281. blowfish: _blowfish2.default,
  23282. /**
  23283. * Not implemented
  23284. * @function
  23285. * @throws {Error}
  23286. */
  23287. idea: function idea() {
  23288. throw new Error('IDEA symmetric-key algorithm not implemented');
  23289. }
  23290. }; /**
  23291. * @fileoverview Symmetric cryptography functions
  23292. * @requires crypto/cipher/aes
  23293. * @requires crypto/cipher/des
  23294. * @requires crypto/cipher/cast5
  23295. * @requires crypto/cipher/twofish
  23296. * @requires crypto/cipher/blowfish
  23297. * @module crypto/cipher
  23298. */
  23299. },{"./aes":82,"./blowfish":83,"./cast5":84,"./des.js":85,"./twofish":87}],87:[function(require,module,exports){
  23300. "use strict";
  23301. Object.defineProperty(exports, "__esModule", {
  23302. value: true
  23303. });
  23304. /* eslint-disable no-mixed-operators, no-fallthrough */
  23305. /* Modified by Recurity Labs GmbH
  23306. *
  23307. * Cipher.js
  23308. * A block-cipher algorithm implementation on JavaScript
  23309. * See Cipher.readme.txt for further information.
  23310. *
  23311. * Copyright(c) 2009 Atsushi Oka [ http://oka.nu/ ]
  23312. * This script file is distributed under the LGPL
  23313. *
  23314. * ACKNOWLEDGMENT
  23315. *
  23316. * The main subroutines are written by Michiel van Everdingen.
  23317. *
  23318. * Michiel van Everdingen
  23319. * http://home.versatel.nl/MAvanEverdingen/index.html
  23320. *
  23321. * All rights for these routines are reserved to Michiel van Everdingen.
  23322. *
  23323. */
  23324. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  23325. //Math
  23326. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  23327. const MAXINT = 0xFFFFFFFF;
  23328. function rotw(w, n) {
  23329. return (w << n | w >>> 32 - n) & MAXINT;
  23330. }
  23331. function getW(a, i) {
  23332. return a[i] | a[i + 1] << 8 | a[i + 2] << 16 | a[i + 3] << 24;
  23333. }
  23334. function setW(a, i, w) {
  23335. a.splice(i, 4, w & 0xFF, w >>> 8 & 0xFF, w >>> 16 & 0xFF, w >>> 24 & 0xFF);
  23336. }
  23337. function getB(x, n) {
  23338. return x >>> n * 8 & 0xFF;
  23339. }
  23340. // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  23341. // Twofish
  23342. // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  23343. function createTwofish() {
  23344. //
  23345. let keyBytes = null;
  23346. let dataBytes = null;
  23347. let dataOffset = -1;
  23348. // var dataLength = -1;
  23349. // var idx2 = -1;
  23350. //
  23351. let tfsKey = [];
  23352. let tfsM = [[], [], [], []];
  23353. function tfsInit(key) {
  23354. keyBytes = key;
  23355. let i;
  23356. let a;
  23357. let b;
  23358. let c;
  23359. let d;
  23360. const meKey = [];
  23361. const moKey = [];
  23362. const inKey = [];
  23363. let kLen;
  23364. const sKey = [];
  23365. let f01;
  23366. let f5b;
  23367. let fef;
  23368. const q0 = [[8, 1, 7, 13, 6, 15, 3, 2, 0, 11, 5, 9, 14, 12, 10, 4], [2, 8, 11, 13, 15, 7, 6, 14, 3, 1, 9, 4, 0, 10, 12, 5]];
  23369. const q1 = [[14, 12, 11, 8, 1, 2, 3, 5, 15, 4, 10, 6, 7, 0, 9, 13], [1, 14, 2, 11, 4, 12, 3, 7, 6, 13, 10, 5, 15, 9, 0, 8]];
  23370. const q2 = [[11, 10, 5, 14, 6, 13, 9, 0, 12, 8, 15, 3, 2, 4, 7, 1], [4, 12, 7, 5, 1, 6, 9, 10, 0, 14, 13, 8, 2, 11, 3, 15]];
  23371. const q3 = [[13, 7, 15, 4, 1, 2, 6, 14, 9, 11, 3, 0, 8, 5, 12, 10], [11, 9, 5, 1, 12, 3, 13, 14, 6, 4, 7, 15, 2, 0, 8, 10]];
  23372. const ror4 = [0, 8, 1, 9, 2, 10, 3, 11, 4, 12, 5, 13, 6, 14, 7, 15];
  23373. const ashx = [0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 5, 14, 7];
  23374. const q = [[], []];
  23375. const m = [[], [], [], []];
  23376. function ffm5b(x) {
  23377. return x ^ x >> 2 ^ [0, 90, 180, 238][x & 3];
  23378. }
  23379. function ffmEf(x) {
  23380. return x ^ x >> 1 ^ x >> 2 ^ [0, 238, 180, 90][x & 3];
  23381. }
  23382. function mdsRem(p, q) {
  23383. let i;
  23384. let t;
  23385. let u;
  23386. for (i = 0; i < 8; i++) {
  23387. t = q >>> 24;
  23388. q = q << 8 & MAXINT | p >>> 24;
  23389. p = p << 8 & MAXINT;
  23390. u = t << 1;
  23391. if (t & 128) {
  23392. u ^= 333;
  23393. }
  23394. q ^= t ^ u << 16;
  23395. u ^= t >>> 1;
  23396. if (t & 1) {
  23397. u ^= 166;
  23398. }
  23399. q ^= u << 24 | u << 8;
  23400. }
  23401. return q;
  23402. }
  23403. function qp(n, x) {
  23404. const a = x >> 4;
  23405. const b = x & 15;
  23406. const c = q0[n][a ^ b];
  23407. const d = q1[n][ror4[b] ^ ashx[a]];
  23408. return q3[n][ror4[d] ^ ashx[c]] << 4 | q2[n][c ^ d];
  23409. }
  23410. function hFun(x, key) {
  23411. let a = getB(x, 0);
  23412. let b = getB(x, 1);
  23413. let c = getB(x, 2);
  23414. let d = getB(x, 3);
  23415. switch (kLen) {
  23416. case 4:
  23417. a = q[1][a] ^ getB(key[3], 0);
  23418. b = q[0][b] ^ getB(key[3], 1);
  23419. c = q[0][c] ^ getB(key[3], 2);
  23420. d = q[1][d] ^ getB(key[3], 3);
  23421. case 3:
  23422. a = q[1][a] ^ getB(key[2], 0);
  23423. b = q[1][b] ^ getB(key[2], 1);
  23424. c = q[0][c] ^ getB(key[2], 2);
  23425. d = q[0][d] ^ getB(key[2], 3);
  23426. case 2:
  23427. a = q[0][q[0][a] ^ getB(key[1], 0)] ^ getB(key[0], 0);
  23428. b = q[0][q[1][b] ^ getB(key[1], 1)] ^ getB(key[0], 1);
  23429. c = q[1][q[0][c] ^ getB(key[1], 2)] ^ getB(key[0], 2);
  23430. d = q[1][q[1][d] ^ getB(key[1], 3)] ^ getB(key[0], 3);
  23431. }
  23432. return m[0][a] ^ m[1][b] ^ m[2][c] ^ m[3][d];
  23433. }
  23434. keyBytes = keyBytes.slice(0, 32);
  23435. i = keyBytes.length;
  23436. while (i !== 16 && i !== 24 && i !== 32) {
  23437. keyBytes[i++] = 0;
  23438. }
  23439. for (i = 0; i < keyBytes.length; i += 4) {
  23440. inKey[i >> 2] = getW(keyBytes, i);
  23441. }
  23442. for (i = 0; i < 256; i++) {
  23443. q[0][i] = qp(0, i);
  23444. q[1][i] = qp(1, i);
  23445. }
  23446. for (i = 0; i < 256; i++) {
  23447. f01 = q[1][i];
  23448. f5b = ffm5b(f01);
  23449. fef = ffmEf(f01);
  23450. m[0][i] = f01 + (f5b << 8) + (fef << 16) + (fef << 24);
  23451. m[2][i] = f5b + (fef << 8) + (f01 << 16) + (fef << 24);
  23452. f01 = q[0][i];
  23453. f5b = ffm5b(f01);
  23454. fef = ffmEf(f01);
  23455. m[1][i] = fef + (fef << 8) + (f5b << 16) + (f01 << 24);
  23456. m[3][i] = f5b + (f01 << 8) + (fef << 16) + (f5b << 24);
  23457. }
  23458. kLen = inKey.length / 2;
  23459. for (i = 0; i < kLen; i++) {
  23460. a = inKey[i + i];
  23461. meKey[i] = a;
  23462. b = inKey[i + i + 1];
  23463. moKey[i] = b;
  23464. sKey[kLen - i - 1] = mdsRem(a, b);
  23465. }
  23466. for (i = 0; i < 40; i += 2) {
  23467. a = 0x1010101 * i;
  23468. b = a + 0x1010101;
  23469. a = hFun(a, meKey);
  23470. b = rotw(hFun(b, moKey), 8);
  23471. tfsKey[i] = a + b & MAXINT;
  23472. tfsKey[i + 1] = rotw(a + 2 * b, 9);
  23473. }
  23474. for (i = 0; i < 256; i++) {
  23475. a = b = c = d = i;
  23476. switch (kLen) {
  23477. case 4:
  23478. a = q[1][a] ^ getB(sKey[3], 0);
  23479. b = q[0][b] ^ getB(sKey[3], 1);
  23480. c = q[0][c] ^ getB(sKey[3], 2);
  23481. d = q[1][d] ^ getB(sKey[3], 3);
  23482. case 3:
  23483. a = q[1][a] ^ getB(sKey[2], 0);
  23484. b = q[1][b] ^ getB(sKey[2], 1);
  23485. c = q[0][c] ^ getB(sKey[2], 2);
  23486. d = q[0][d] ^ getB(sKey[2], 3);
  23487. case 2:
  23488. tfsM[0][i] = m[0][q[0][q[0][a] ^ getB(sKey[1], 0)] ^ getB(sKey[0], 0)];
  23489. tfsM[1][i] = m[1][q[0][q[1][b] ^ getB(sKey[1], 1)] ^ getB(sKey[0], 1)];
  23490. tfsM[2][i] = m[2][q[1][q[0][c] ^ getB(sKey[1], 2)] ^ getB(sKey[0], 2)];
  23491. tfsM[3][i] = m[3][q[1][q[1][d] ^ getB(sKey[1], 3)] ^ getB(sKey[0], 3)];
  23492. }
  23493. }
  23494. }
  23495. function tfsG0(x) {
  23496. return tfsM[0][getB(x, 0)] ^ tfsM[1][getB(x, 1)] ^ tfsM[2][getB(x, 2)] ^ tfsM[3][getB(x, 3)];
  23497. }
  23498. function tfsG1(x) {
  23499. return tfsM[0][getB(x, 3)] ^ tfsM[1][getB(x, 0)] ^ tfsM[2][getB(x, 1)] ^ tfsM[3][getB(x, 2)];
  23500. }
  23501. function tfsFrnd(r, blk) {
  23502. let a = tfsG0(blk[0]);
  23503. let b = tfsG1(blk[1]);
  23504. blk[2] = rotw(blk[2] ^ a + b + tfsKey[4 * r + 8] & MAXINT, 31);
  23505. blk[3] = rotw(blk[3], 1) ^ a + 2 * b + tfsKey[4 * r + 9] & MAXINT;
  23506. a = tfsG0(blk[2]);
  23507. b = tfsG1(blk[3]);
  23508. blk[0] = rotw(blk[0] ^ a + b + tfsKey[4 * r + 10] & MAXINT, 31);
  23509. blk[1] = rotw(blk[1], 1) ^ a + 2 * b + tfsKey[4 * r + 11] & MAXINT;
  23510. }
  23511. function tfsIrnd(i, blk) {
  23512. let a = tfsG0(blk[0]);
  23513. let b = tfsG1(blk[1]);
  23514. blk[2] = rotw(blk[2], 1) ^ a + b + tfsKey[4 * i + 10] & MAXINT;
  23515. blk[3] = rotw(blk[3] ^ a + 2 * b + tfsKey[4 * i + 11] & MAXINT, 31);
  23516. a = tfsG0(blk[2]);
  23517. b = tfsG1(blk[3]);
  23518. blk[0] = rotw(blk[0], 1) ^ a + b + tfsKey[4 * i + 8] & MAXINT;
  23519. blk[1] = rotw(blk[1] ^ a + 2 * b + tfsKey[4 * i + 9] & MAXINT, 31);
  23520. }
  23521. function tfsClose() {
  23522. tfsKey = [];
  23523. tfsM = [[], [], [], []];
  23524. }
  23525. function tfsEncrypt(data, offset) {
  23526. dataBytes = data;
  23527. dataOffset = offset;
  23528. const blk = [getW(dataBytes, dataOffset) ^ tfsKey[0], getW(dataBytes, dataOffset + 4) ^ tfsKey[1], getW(dataBytes, dataOffset + 8) ^ tfsKey[2], getW(dataBytes, dataOffset + 12) ^ tfsKey[3]];
  23529. for (let j = 0; j < 8; j++) {
  23530. tfsFrnd(j, blk);
  23531. }
  23532. setW(dataBytes, dataOffset, blk[2] ^ tfsKey[4]);
  23533. setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[5]);
  23534. setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[6]);
  23535. setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[7]);
  23536. dataOffset += 16;
  23537. return dataBytes;
  23538. }
  23539. function tfsDecrypt(data, offset) {
  23540. dataBytes = data;
  23541. dataOffset = offset;
  23542. const blk = [getW(dataBytes, dataOffset) ^ tfsKey[4], getW(dataBytes, dataOffset + 4) ^ tfsKey[5], getW(dataBytes, dataOffset + 8) ^ tfsKey[6], getW(dataBytes, dataOffset + 12) ^ tfsKey[7]];
  23543. for (let j = 7; j >= 0; j--) {
  23544. tfsIrnd(j, blk);
  23545. }
  23546. setW(dataBytes, dataOffset, blk[2] ^ tfsKey[0]);
  23547. setW(dataBytes, dataOffset + 4, blk[3] ^ tfsKey[1]);
  23548. setW(dataBytes, dataOffset + 8, blk[0] ^ tfsKey[2]);
  23549. setW(dataBytes, dataOffset + 12, blk[1] ^ tfsKey[3]);
  23550. dataOffset += 16;
  23551. }
  23552. // added by Recurity Labs
  23553. function tfsFinal() {
  23554. return dataBytes;
  23555. }
  23556. return {
  23557. name: "twofish",
  23558. blocksize: 128 / 8,
  23559. open: tfsInit,
  23560. close: tfsClose,
  23561. encrypt: tfsEncrypt,
  23562. decrypt: tfsDecrypt,
  23563. // added by Recurity Labs
  23564. finalize: tfsFinal
  23565. };
  23566. }
  23567. // added by Recurity Labs
  23568. function TF(key) {
  23569. this.tf = createTwofish();
  23570. this.tf.open(Array.from(key), 0);
  23571. this.encrypt = function (block) {
  23572. return this.tf.encrypt(Array.from(block), 0);
  23573. };
  23574. }
  23575. TF.keySize = TF.prototype.keySize = 32;
  23576. TF.blockSize = TF.prototype.blockSize = 16;
  23577. exports.default = TF;
  23578. },{}],88:[function(require,module,exports){
  23579. 'use strict';
  23580. Object.defineProperty(exports, "__esModule", {
  23581. value: true
  23582. });
  23583. var _cbc = require('asmcrypto.js/dist_es5/aes/cbc');
  23584. var _util = require('../util');
  23585. var _util2 = _interopRequireDefault(_util);
  23586. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  23587. /**
  23588. * @fileoverview This module implements AES-CMAC on top of
  23589. * native AES-CBC using either the WebCrypto API or Node.js' crypto API.
  23590. * @requires asmcrypto.js
  23591. * @requires util
  23592. * @module crypto/cmac
  23593. */
  23594. const webCrypto = _util2.default.getWebCrypto();
  23595. const nodeCrypto = _util2.default.getNodeCrypto();
  23596. const Buffer = _util2.default.getNodeBuffer();
  23597. /**
  23598. * This implementation of CMAC is based on the description of OMAC in
  23599. * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that
  23600. * document:
  23601. *
  23602. * We have made a small modification to the OMAC algorithm as it was
  23603. * originally presented, changing one of its two constants.
  23604. * Specifically, the constant 4 at line 85 was the constant 1/2 (the
  23605. * multiplicative inverse of 2) in the original definition of OMAC [14].
  23606. * The OMAC authors indicate that they will promulgate this modification
  23607. * [15], which slightly simplifies implementations.
  23608. */
  23609. const blockLength = 16;
  23610. /**
  23611. * xor `padding` into the end of `data`. This function implements "the
  23612. * operation xor→ [which] xors the shorter string into the end of longer
  23613. * one". Since data is always as least as long as padding, we can
  23614. * simplify the implementation.
  23615. * @param {Uint8Array} data
  23616. * @param {Uint8Array} padding
  23617. */
  23618. function rightXorMut(data, padding) {
  23619. const offset = data.length - blockLength;
  23620. for (let i = 0; i < blockLength; i++) {
  23621. data[i + offset] ^= padding[i];
  23622. }
  23623. return data;
  23624. }
  23625. function pad(data, padding, padding2) {
  23626. // if |M| in {n, 2n, 3n, ...}
  23627. if (data.length && data.length % blockLength === 0) {
  23628. // then return M xor→ B,
  23629. return rightXorMut(data, padding);
  23630. }
  23631. // else return (M || 10^(n−1−(|M| mod n))) xor→ P
  23632. const padded = new Uint8Array(data.length + (blockLength - data.length % blockLength));
  23633. padded.set(data);
  23634. padded[data.length] = 0b10000000;
  23635. return rightXorMut(padded, padding2);
  23636. }
  23637. const zeroBlock = new Uint8Array(blockLength);
  23638. exports.default = async function CMAC(key) {
  23639. const cbc = await CBC(key);
  23640. // L ← E_K(0^n); B ← 2L; P ← 4L
  23641. const padding = _util2.default.double((await cbc(zeroBlock)));
  23642. const padding2 = _util2.default.double(padding);
  23643. return async function (data) {
  23644. // return CBC_K(pad(M; B, P))
  23645. return (await cbc(pad(data, padding, padding2))).subarray(-blockLength);
  23646. };
  23647. };
  23648. async function CBC(key) {
  23649. if (_util2.default.getWebCrypto() && key.length !== 24) {
  23650. // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
  23651. key = await webCrypto.importKey('raw', key, { name: 'AES-CBC', length: key.length * 8 }, false, ['encrypt']);
  23652. return async function (pt) {
  23653. const ct = await webCrypto.encrypt({ name: 'AES-CBC', iv: zeroBlock, length: blockLength * 8 }, key, pt);
  23654. return new Uint8Array(ct).subarray(0, ct.byteLength - blockLength);
  23655. };
  23656. }
  23657. if (_util2.default.getNodeCrypto()) {
  23658. // Node crypto library
  23659. key = Buffer.from(key);
  23660. return async function (pt) {
  23661. pt = Buffer.from(pt);
  23662. const en = new nodeCrypto.createCipheriv('aes-' + key.length * 8 + '-cbc', key, zeroBlock);
  23663. const ct = en.update(pt);
  23664. return new Uint8Array(ct);
  23665. };
  23666. }
  23667. // asm.js fallback
  23668. return async function (pt) {
  23669. return _cbc.AES_CBC.encrypt(pt, key, false, zeroBlock);
  23670. };
  23671. }
  23672. },{"../util":158,"asmcrypto.js/dist_es5/aes/cbc":4}],89:[function(require,module,exports){
  23673. 'use strict';
  23674. Object.defineProperty(exports, "__esModule", {
  23675. value: true
  23676. });
  23677. var _public_key = require('./public_key');
  23678. var _public_key2 = _interopRequireDefault(_public_key);
  23679. var _cipher = require('./cipher');
  23680. var _cipher2 = _interopRequireDefault(_cipher);
  23681. var _random = require('./random');
  23682. var _random2 = _interopRequireDefault(_random);
  23683. var _ecdh_symkey = require('../type/ecdh_symkey');
  23684. var _ecdh_symkey2 = _interopRequireDefault(_ecdh_symkey);
  23685. var _kdf_params = require('../type/kdf_params');
  23686. var _kdf_params2 = _interopRequireDefault(_kdf_params);
  23687. var _mpi = require('../type/mpi');
  23688. var _mpi2 = _interopRequireDefault(_mpi);
  23689. var _oid = require('../type/oid');
  23690. var _oid2 = _interopRequireDefault(_oid);
  23691. var _enums = require('../enums');
  23692. var _enums2 = _interopRequireDefault(_enums);
  23693. var _util = require('../util');
  23694. var _util2 = _interopRequireDefault(_util);
  23695. var _pkcs = require('./pkcs1');
  23696. var _pkcs2 = _interopRequireDefault(_pkcs);
  23697. var _pkcs3 = require('./pkcs5');
  23698. var _pkcs4 = _interopRequireDefault(_pkcs3);
  23699. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  23700. function constructParams(types, data) {
  23701. return types.map(function (type, i) {
  23702. if (data && data[i]) {
  23703. return new type(data[i]);
  23704. }
  23705. return new type();
  23706. });
  23707. } // GPG4Browsers - An OpenPGP implementation in javascript
  23708. // Copyright (C) 2011 Recurity Labs GmbH
  23709. //
  23710. // This library is free software; you can redistribute it and/or
  23711. // modify it under the terms of the GNU Lesser General Public
  23712. // License as published by the Free Software Foundation; either
  23713. // version 3.0 of the License, or (at your option) any later version.
  23714. //
  23715. // This library is distributed in the hope that it will be useful,
  23716. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  23717. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  23718. // Lesser General Public License for more details.
  23719. //
  23720. // You should have received a copy of the GNU Lesser General Public
  23721. // License along with this library; if not, write to the Free Software
  23722. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  23723. // The GPG4Browsers crypto interface
  23724. /**
  23725. * @fileoverview Provides functions for asymmetric encryption and decryption as
  23726. * well as key generation and parameter handling for all public-key cryptosystems.
  23727. * @requires crypto/public_key
  23728. * @requires crypto/cipher
  23729. * @requires crypto/random
  23730. * @requires type/ecdh_symkey
  23731. * @requires type/kdf_params
  23732. * @requires type/mpi
  23733. * @requires type/oid
  23734. * @requires enums
  23735. * @requires util
  23736. * @module crypto/crypto
  23737. */
  23738. exports.default = {
  23739. /**
  23740. * Encrypts data using specified algorithm and public key parameters.
  23741. * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms.
  23742. * @param {module:enums.publicKey} algo Public key algorithm
  23743. * @param {Array<module:type/mpi|
  23744. module:type/oid|
  23745. module:type/kdf_params>} pub_params Algorithm-specific public key parameters
  23746. * @param {String} data Data to be encrypted
  23747. * @param {String} fingerprint Recipient fingerprint
  23748. * @returns {Array<module:type/mpi|
  23749. * module:type/ecdh_symkey>} encrypted session key parameters
  23750. * @async
  23751. */
  23752. publicKeyEncrypt: async function publicKeyEncrypt(algo, pub_params, data, fingerprint) {
  23753. const types = this.getEncSessionKeyParamTypes(algo);
  23754. switch (algo) {
  23755. case _enums2.default.publicKey.rsa_encrypt:
  23756. case _enums2.default.publicKey.rsa_encrypt_sign:
  23757. {
  23758. data = _util2.default.str_to_Uint8Array(data);
  23759. const n = pub_params[0].toUint8Array();
  23760. const e = pub_params[1].toUint8Array();
  23761. const res = await _public_key2.default.rsa.encrypt(data, n, e);
  23762. return constructParams(types, [res]);
  23763. }
  23764. case _enums2.default.publicKey.elgamal:
  23765. {
  23766. data = new _mpi2.default((await _pkcs2.default.eme.encode(data, pub_params[0].byteLength())));
  23767. const m = data.toBN();
  23768. const p = pub_params[0].toBN();
  23769. const g = pub_params[1].toBN();
  23770. const y = pub_params[2].toBN();
  23771. const res = await _public_key2.default.elgamal.encrypt(m, p, g, y);
  23772. return constructParams(types, [res.c1, res.c2]);
  23773. }
  23774. case _enums2.default.publicKey.ecdh:
  23775. {
  23776. data = new _mpi2.default(_pkcs4.default.encode(data));
  23777. const oid = pub_params[0];
  23778. const Q = pub_params[1].toUint8Array();
  23779. const kdf_params = pub_params[2];
  23780. var _ref = await _public_key2.default.elliptic.ecdh.encrypt(oid, kdf_params.cipher, kdf_params.hash, data, Q, fingerprint);
  23781. const V = _ref.publicKey,
  23782. C = _ref.wrappedKey;
  23783. return constructParams(types, [V, C]);
  23784. }
  23785. default:
  23786. return [];
  23787. }
  23788. },
  23789. /**
  23790. * Decrypts data using specified algorithm and private key parameters.
  23791. * See {@link https://tools.ietf.org/html/rfc4880#section-5.5.3|RFC 4880 5.5.3}
  23792. * @param {module:enums.publicKey} algo Public key algorithm
  23793. * @param {Array<module:type/mpi|
  23794. module:type/oid|
  23795. module:type/kdf_params>} key_params Algorithm-specific public, private key parameters
  23796. * @param {Array<module:type/mpi|
  23797. module:type/ecdh_symkey>}
  23798. data_params encrypted session key parameters
  23799. * @param {String} fingerprint Recipient fingerprint
  23800. * @returns {String} String containing the decrypted data
  23801. * @async
  23802. */
  23803. publicKeyDecrypt: async function publicKeyDecrypt(algo, key_params, data_params, fingerprint) {
  23804. switch (algo) {
  23805. case _enums2.default.publicKey.rsa_encrypt_sign:
  23806. case _enums2.default.publicKey.rsa_encrypt:
  23807. {
  23808. const c = data_params[0].toUint8Array();
  23809. const n = key_params[0].toUint8Array(); // n = pq
  23810. const e = key_params[1].toUint8Array();
  23811. const d = key_params[2].toUint8Array(); // de = 1 mod (p-1)(q-1)
  23812. const p = key_params[3].toUint8Array();
  23813. const q = key_params[4].toUint8Array();
  23814. const u = key_params[5].toUint8Array(); // p^-1 mod q
  23815. return _public_key2.default.rsa.decrypt(c, n, e, d, p, q, u);
  23816. }
  23817. case _enums2.default.publicKey.elgamal:
  23818. {
  23819. const c1 = data_params[0].toBN();
  23820. const c2 = data_params[1].toBN();
  23821. const p = key_params[0].toBN();
  23822. const x = key_params[3].toBN();
  23823. const result = new _mpi2.default((await _public_key2.default.elgamal.decrypt(c1, c2, p, x)));
  23824. return _pkcs2.default.eme.decode(result.toString());
  23825. }
  23826. case _enums2.default.publicKey.ecdh:
  23827. {
  23828. const oid = key_params[0];
  23829. const kdf_params = key_params[2];
  23830. const V = data_params[0].toUint8Array();
  23831. const C = data_params[1].data;
  23832. const Q = key_params[1].toUint8Array();
  23833. const d = key_params[3].toUint8Array();
  23834. const result = new _mpi2.default((await _public_key2.default.elliptic.ecdh.decrypt(oid, kdf_params.cipher, kdf_params.hash, V, C, Q, d, fingerprint)));
  23835. return _pkcs4.default.decode(result.toString());
  23836. }
  23837. default:
  23838. throw new Error('Invalid public key encryption algorithm.');
  23839. }
  23840. },
  23841. /** Returns the types comprising the private key of an algorithm
  23842. * @param {String} algo The public key algorithm
  23843. * @returns {Array<String>} The array of types
  23844. */
  23845. getPrivKeyParamTypes: function getPrivKeyParamTypes(algo) {
  23846. switch (algo) {
  23847. // Algorithm-Specific Fields for RSA secret keys:
  23848. // - multiprecision integer (MPI) of RSA secret exponent d.
  23849. // - MPI of RSA secret prime value p.
  23850. // - MPI of RSA secret prime value q (p < q).
  23851. // - MPI of u, the multiplicative inverse of p, mod q.
  23852. case _enums2.default.publicKey.rsa_encrypt:
  23853. case _enums2.default.publicKey.rsa_encrypt_sign:
  23854. case _enums2.default.publicKey.rsa_sign:
  23855. return [_mpi2.default, _mpi2.default, _mpi2.default, _mpi2.default];
  23856. // Algorithm-Specific Fields for Elgamal secret keys:
  23857. // - MPI of Elgamal secret exponent x.
  23858. case _enums2.default.publicKey.elgamal:
  23859. return [_mpi2.default];
  23860. // Algorithm-Specific Fields for DSA secret keys:
  23861. // - MPI of DSA secret exponent x.
  23862. case _enums2.default.publicKey.dsa:
  23863. return [_mpi2.default];
  23864. // Algorithm-Specific Fields for ECDSA or ECDH secret keys:
  23865. // - MPI of an integer representing the secret key.
  23866. case _enums2.default.publicKey.ecdh:
  23867. case _enums2.default.publicKey.ecdsa:
  23868. case _enums2.default.publicKey.eddsa:
  23869. return [_mpi2.default];
  23870. default:
  23871. throw new Error('Invalid public key encryption algorithm.');
  23872. }
  23873. },
  23874. /** Returns the types comprising the public key of an algorithm
  23875. * @param {String} algo The public key algorithm
  23876. * @returns {Array<String>} The array of types
  23877. */
  23878. getPubKeyParamTypes: function getPubKeyParamTypes(algo) {
  23879. switch (algo) {
  23880. // Algorithm-Specific Fields for RSA public keys:
  23881. // - a multiprecision integer (MPI) of RSA public modulus n;
  23882. // - an MPI of RSA public encryption exponent e.
  23883. case _enums2.default.publicKey.rsa_encrypt:
  23884. case _enums2.default.publicKey.rsa_encrypt_sign:
  23885. case _enums2.default.publicKey.rsa_sign:
  23886. return [_mpi2.default, _mpi2.default];
  23887. // Algorithm-Specific Fields for Elgamal public keys:
  23888. // - MPI of Elgamal prime p;
  23889. // - MPI of Elgamal group generator g;
  23890. // - MPI of Elgamal public key value y (= g**x mod p where x is secret).
  23891. case _enums2.default.publicKey.elgamal:
  23892. return [_mpi2.default, _mpi2.default, _mpi2.default];
  23893. // Algorithm-Specific Fields for DSA public keys:
  23894. // - MPI of DSA prime p;
  23895. // - MPI of DSA group order q (q is a prime divisor of p-1);
  23896. // - MPI of DSA group generator g;
  23897. // - MPI of DSA public-key value y (= g**x mod p where x is secret).
  23898. case _enums2.default.publicKey.dsa:
  23899. return [_mpi2.default, _mpi2.default, _mpi2.default, _mpi2.default];
  23900. // Algorithm-Specific Fields for ECDSA/EdDSA public keys:
  23901. // - OID of curve;
  23902. // - MPI of EC point representing public key.
  23903. case _enums2.default.publicKey.ecdsa:
  23904. case _enums2.default.publicKey.eddsa:
  23905. return [_oid2.default, _mpi2.default];
  23906. // Algorithm-Specific Fields for ECDH public keys:
  23907. // - OID of curve;
  23908. // - MPI of EC point representing public key.
  23909. // - KDF: variable-length field containing KDF parameters.
  23910. case _enums2.default.publicKey.ecdh:
  23911. return [_oid2.default, _mpi2.default, _kdf_params2.default];
  23912. default:
  23913. throw new Error('Invalid public key encryption algorithm.');
  23914. }
  23915. },
  23916. /** Returns the types comprising the encrypted session key of an algorithm
  23917. * @param {String} algo The public key algorithm
  23918. * @returns {Array<String>} The array of types
  23919. */
  23920. getEncSessionKeyParamTypes: function getEncSessionKeyParamTypes(algo) {
  23921. switch (algo) {
  23922. // Algorithm-Specific Fields for RSA encrypted session keys:
  23923. // - MPI of RSA encrypted value m**e mod n.
  23924. case _enums2.default.publicKey.rsa_encrypt:
  23925. case _enums2.default.publicKey.rsa_encrypt_sign:
  23926. return [_mpi2.default];
  23927. // Algorithm-Specific Fields for Elgamal encrypted session keys:
  23928. // - MPI of Elgamal value g**k mod p
  23929. // - MPI of Elgamal value m * y**k mod p
  23930. case _enums2.default.publicKey.elgamal:
  23931. return [_mpi2.default, _mpi2.default];
  23932. // Algorithm-Specific Fields for ECDH encrypted session keys:
  23933. // - MPI containing the ephemeral key used to establish the shared secret
  23934. // - ECDH Symmetric Key
  23935. case _enums2.default.publicKey.ecdh:
  23936. return [_mpi2.default, _ecdh_symkey2.default];
  23937. default:
  23938. throw new Error('Invalid public key encryption algorithm.');
  23939. }
  23940. },
  23941. /** Generate algorithm-specific key parameters
  23942. * @param {String} algo The public key algorithm
  23943. * @param {Integer} bits Bit length for RSA keys
  23944. * @param {module:type/oid} oid Object identifier for ECC keys
  23945. * @returns {Array} The array of parameters
  23946. * @async
  23947. */
  23948. generateParams: function generateParams(algo, bits, oid) {
  23949. const types = [].concat(this.getPubKeyParamTypes(algo), this.getPrivKeyParamTypes(algo));
  23950. switch (algo) {
  23951. case _enums2.default.publicKey.rsa_encrypt:
  23952. case _enums2.default.publicKey.rsa_encrypt_sign:
  23953. case _enums2.default.publicKey.rsa_sign:
  23954. {
  23955. return _public_key2.default.rsa.generate(bits, "10001").then(function (keyObject) {
  23956. return constructParams(types, [keyObject.n, keyObject.e, keyObject.d, keyObject.p, keyObject.q, keyObject.u]);
  23957. });
  23958. }
  23959. case _enums2.default.publicKey.dsa:
  23960. case _enums2.default.publicKey.elgamal:
  23961. throw new Error('Unsupported algorithm for key generation.');
  23962. case _enums2.default.publicKey.ecdsa:
  23963. case _enums2.default.publicKey.eddsa:
  23964. return _public_key2.default.elliptic.generate(oid).then(function (keyObject) {
  23965. return constructParams(types, [keyObject.oid, keyObject.Q, keyObject.d]);
  23966. });
  23967. case _enums2.default.publicKey.ecdh:
  23968. return _public_key2.default.elliptic.generate(oid).then(function (keyObject) {
  23969. return constructParams(types, [keyObject.oid, keyObject.Q, [keyObject.hash, keyObject.cipher], keyObject.d]);
  23970. });
  23971. default:
  23972. throw new Error('Invalid public key algorithm.');
  23973. }
  23974. },
  23975. /**
  23976. * Generates a random byte prefix for the specified algorithm
  23977. * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
  23978. * @param {module:enums.symmetric} algo Symmetric encryption algorithm
  23979. * @returns {Uint8Array} Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated.
  23980. * @async
  23981. */
  23982. getPrefixRandom: async function getPrefixRandom(algo) {
  23983. const prefixrandom = await _random2.default.getRandomBytes(_cipher2.default[algo].blockSize);
  23984. const repeat = new Uint8Array([prefixrandom[prefixrandom.length - 2], prefixrandom[prefixrandom.length - 1]]);
  23985. return _util2.default.concat([prefixrandom, repeat]);
  23986. },
  23987. /**
  23988. * Generating a session key for the specified symmetric algorithm
  23989. * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
  23990. * @param {module:enums.symmetric} algo Symmetric encryption algorithm
  23991. * @returns {Uint8Array} Random bytes as a string to be used as a key
  23992. * @async
  23993. */
  23994. generateSessionKey: function generateSessionKey(algo) {
  23995. return _random2.default.getRandomBytes(_cipher2.default[algo].keySize);
  23996. },
  23997. constructParams: constructParams
  23998. };
  23999. },{"../enums":113,"../type/ecdh_symkey":152,"../type/kdf_params":153,"../type/mpi":155,"../type/oid":156,"../util":158,"./cipher":86,"./pkcs1":96,"./pkcs5":97,"./public_key":106,"./random":109}],90:[function(require,module,exports){
  24000. 'use strict';
  24001. Object.defineProperty(exports, "__esModule", {
  24002. value: true
  24003. });
  24004. var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); // OpenPGP.js - An OpenPGP implementation in javascript
  24005. // Copyright (C) 2018 ProtonTech AG
  24006. //
  24007. // This library is free software; you can redistribute it and/or
  24008. // modify it under the terms of the GNU Lesser General Public
  24009. // License as published by the Free Software Foundation; either
  24010. // version 3.0 of the License, or (at your option) any later version.
  24011. //
  24012. // This library is distributed in the hope that it will be useful,
  24013. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  24014. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  24015. // Lesser General Public License for more details.
  24016. //
  24017. // You should have received a copy of the GNU Lesser General Public
  24018. // License along with this library; if not, write to the Free Software
  24019. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  24020. /**
  24021. * @fileoverview This module implements AES-EAX en/decryption on top of
  24022. * native AES-CTR using either the WebCrypto API or Node.js' crypto API.
  24023. * @requires asmcrypto.js
  24024. * @requires crypto/cmac
  24025. * @requires util
  24026. * @module crypto/eax
  24027. */
  24028. var _ctr = require('asmcrypto.js/dist_es5/aes/ctr');
  24029. var _cmac = require('./cmac');
  24030. var _cmac2 = _interopRequireDefault(_cmac);
  24031. var _util = require('../util');
  24032. var _util2 = _interopRequireDefault(_util);
  24033. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24034. const webCrypto = _util2.default.getWebCrypto();
  24035. const nodeCrypto = _util2.default.getNodeCrypto();
  24036. const Buffer = _util2.default.getNodeBuffer();
  24037. const blockLength = 16;
  24038. const ivLength = blockLength;
  24039. const tagLength = blockLength;
  24040. const zero = new Uint8Array(blockLength);
  24041. const one = new Uint8Array(blockLength);one[blockLength - 1] = 1;
  24042. const two = new Uint8Array(blockLength);two[blockLength - 1] = 2;
  24043. async function OMAC(key) {
  24044. const cmac = await (0, _cmac2.default)(key);
  24045. return function (t, message) {
  24046. return cmac(_util2.default.concatUint8Array([t, message]));
  24047. };
  24048. }
  24049. async function CTR(key) {
  24050. if (_util2.default.getWebCrypto() && key.length !== 24 && // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
  24051. navigator.userAgent.indexOf('Edge') === -1) {
  24052. key = await webCrypto.importKey('raw', key, { name: 'AES-CTR', length: key.length * 8 }, false, ['encrypt']);
  24053. return async function (pt, iv) {
  24054. const ct = await webCrypto.encrypt({ name: 'AES-CTR', counter: iv, length: blockLength * 8 }, key, pt);
  24055. return new Uint8Array(ct);
  24056. };
  24057. }
  24058. if (_util2.default.getNodeCrypto()) {
  24059. // Node crypto library
  24060. key = Buffer.from(key);
  24061. return async function (pt, iv) {
  24062. pt = Buffer.from(pt);
  24063. iv = Buffer.from(iv);
  24064. const en = new nodeCrypto.createCipheriv('aes-' + key.length * 8 + '-ctr', key, iv);
  24065. const ct = Buffer.concat([en.update(pt), en.final()]);
  24066. return new Uint8Array(ct);
  24067. };
  24068. }
  24069. // asm.js fallback
  24070. return async function (pt, iv) {
  24071. return _ctr.AES_CTR.encrypt(pt, key, iv);
  24072. };
  24073. }
  24074. /**
  24075. * Class to en/decrypt using EAX mode.
  24076. * @param {String} cipher The symmetric cipher algorithm to use e.g. 'aes128'
  24077. * @param {Uint8Array} key The encryption key
  24078. */
  24079. async function EAX(cipher, key) {
  24080. if (cipher.substr(0, 3) !== 'aes') {
  24081. throw new Error('EAX mode supports only AES cipher');
  24082. }
  24083. var _ref = await Promise.all([OMAC(key), CTR(key)]),
  24084. _ref2 = _slicedToArray(_ref, 2);
  24085. const omac = _ref2[0],
  24086. ctr = _ref2[1];
  24087. return {
  24088. /**
  24089. * Encrypt plaintext input.
  24090. * @param {Uint8Array} plaintext The cleartext input to be encrypted
  24091. * @param {Uint8Array} nonce The nonce (16 bytes)
  24092. * @param {Uint8Array} adata Associated data to sign
  24093. * @returns {Promise<Uint8Array>} The ciphertext output
  24094. */
  24095. encrypt: async function encrypt(plaintext, nonce, adata) {
  24096. var _ref3 = await Promise.all([omac(zero, nonce), omac(one, adata)]),
  24097. _ref4 = _slicedToArray(_ref3, 2);
  24098. const omacNonce = _ref4[0],
  24099. omacAdata = _ref4[1];
  24100. const ciphered = await ctr(plaintext, omacNonce);
  24101. const omacCiphered = await omac(two, ciphered);
  24102. const tag = omacCiphered; // Assumes that omac(*).length === tagLength.
  24103. for (let i = 0; i < tagLength; i++) {
  24104. tag[i] ^= omacAdata[i] ^ omacNonce[i];
  24105. }
  24106. return _util2.default.concatUint8Array([ciphered, tag]);
  24107. },
  24108. /**
  24109. * Decrypt ciphertext input.
  24110. * @param {Uint8Array} ciphertext The ciphertext input to be decrypted
  24111. * @param {Uint8Array} nonce The nonce (16 bytes)
  24112. * @param {Uint8Array} adata Associated data to verify
  24113. * @returns {Promise<Uint8Array>} The plaintext output
  24114. */
  24115. decrypt: async function decrypt(ciphertext, nonce, adata) {
  24116. if (ciphertext.length < tagLength) throw new Error('Invalid EAX ciphertext');
  24117. const ciphered = ciphertext.subarray(0, -tagLength);
  24118. const ctTag = ciphertext.subarray(-tagLength);
  24119. var _ref5 = await Promise.all([omac(zero, nonce), omac(one, adata), omac(two, ciphered)]),
  24120. _ref6 = _slicedToArray(_ref5, 3);
  24121. const omacNonce = _ref6[0],
  24122. omacAdata = _ref6[1],
  24123. omacCiphered = _ref6[2];
  24124. const tag = omacCiphered; // Assumes that omac(*).length === tagLength.
  24125. for (let i = 0; i < tagLength; i++) {
  24126. tag[i] ^= omacAdata[i] ^ omacNonce[i];
  24127. }
  24128. if (!_util2.default.equalsUint8Array(ctTag, tag)) throw new Error('Authentication tag mismatch');
  24129. const plaintext = await ctr(ciphered, omacNonce);
  24130. return plaintext;
  24131. }
  24132. };
  24133. }
  24134. /**
  24135. * Get EAX nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.1|RFC4880bis-04, section 5.16.1}.
  24136. * @param {Uint8Array} iv The initialization vector (16 bytes)
  24137. * @param {Uint8Array} chunkIndex The chunk index (8 bytes)
  24138. */
  24139. EAX.getNonce = function (iv, chunkIndex) {
  24140. const nonce = iv.slice();
  24141. for (let i = 0; i < chunkIndex.length; i++) {
  24142. nonce[8 + i] ^= chunkIndex[i];
  24143. }
  24144. return nonce;
  24145. };
  24146. EAX.blockLength = blockLength;
  24147. EAX.ivLength = ivLength;
  24148. EAX.tagLength = tagLength;
  24149. exports.default = EAX;
  24150. },{"../util":158,"./cmac":88,"asmcrypto.js/dist_es5/aes/ctr":6}],91:[function(require,module,exports){
  24151. 'use strict';
  24152. Object.defineProperty(exports, "__esModule", {
  24153. value: true
  24154. });
  24155. var _gcm = require('asmcrypto.js/dist_es5/aes/gcm');
  24156. var _util = require('../util');
  24157. var _util2 = _interopRequireDefault(_util);
  24158. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24159. // OpenPGP.js - An OpenPGP implementation in javascript
  24160. // Copyright (C) 2016 Tankred Hase
  24161. //
  24162. // This library is free software; you can redistribute it and/or
  24163. // modify it under the terms of the GNU Lesser General Public
  24164. // License as published by the Free Software Foundation; either
  24165. // version 3.0 of the License, or (at your option) any later version.
  24166. //
  24167. // This library is distributed in the hope that it will be useful,
  24168. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  24169. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  24170. // Lesser General Public License for more details.
  24171. //
  24172. // You should have received a copy of the GNU Lesser General Public
  24173. // License along with this library; if not, write to the Free Software
  24174. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  24175. /**
  24176. * @fileoverview This module wraps native AES-GCM en/decryption for both
  24177. * the WebCrypto api as well as node.js' crypto api.
  24178. * @requires asmcrypto.js
  24179. * @requires util
  24180. * @module crypto/gcm
  24181. */
  24182. const webCrypto = _util2.default.getWebCrypto(); // no GCM support in IE11, Safari 9
  24183. const nodeCrypto = _util2.default.getNodeCrypto();
  24184. const Buffer = _util2.default.getNodeBuffer();
  24185. const blockLength = 16;
  24186. const ivLength = 12; // size of the IV in bytes
  24187. const tagLength = 16; // size of the tag in bytes
  24188. const ALGO = 'AES-GCM';
  24189. /**
  24190. * Class to en/decrypt using GCM mode.
  24191. * @param {String} cipher The symmetric cipher algorithm to use e.g. 'aes128'
  24192. * @param {Uint8Array} key The encryption key
  24193. */
  24194. async function GCM(cipher, key) {
  24195. if (cipher.substr(0, 3) !== 'aes') {
  24196. throw new Error('GCM mode supports only AES cipher');
  24197. }
  24198. if (_util2.default.getWebCrypto() && key.length !== 24) {
  24199. // WebCrypto (no 192 bit support) see: https://www.chromium.org/blink/webcrypto#TOC-AES-support
  24200. const _key = await webCrypto.importKey('raw', key, { name: ALGO }, false, ['encrypt', 'decrypt']);
  24201. return {
  24202. encrypt: async function encrypt(pt, iv, adata = new Uint8Array()) {
  24203. if (!pt.length ||
  24204. // iOS does not support GCM-en/decrypting empty messages
  24205. // Also, synchronous en/decryption might be faster in this case.
  24206. !adata.length && navigator.userAgent.indexOf('Edge') !== -1
  24207. // Edge does not support GCM-en/decrypting without ADATA
  24208. ) {
  24209. return _gcm.AES_GCM.encrypt(pt, key, iv, adata);
  24210. }
  24211. const ct = await webCrypto.encrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, pt);
  24212. return new Uint8Array(ct);
  24213. },
  24214. decrypt: async function decrypt(ct, iv, adata = new Uint8Array()) {
  24215. if (ct.length === tagLength ||
  24216. // iOS does not support GCM-en/decrypting empty messages
  24217. // Also, synchronous en/decryption might be faster in this case.
  24218. !adata.length && navigator.userAgent.indexOf('Edge') !== -1
  24219. // Edge does not support GCM-en/decrypting without ADATA
  24220. ) {
  24221. return _gcm.AES_GCM.decrypt(ct, key, iv, adata);
  24222. }
  24223. const pt = await webCrypto.decrypt({ name: ALGO, iv, additionalData: adata, tagLength: tagLength * 8 }, _key, ct);
  24224. return new Uint8Array(pt);
  24225. }
  24226. };
  24227. }
  24228. if (_util2.default.getNodeCrypto()) {
  24229. // Node crypto library
  24230. key = Buffer.from(key);
  24231. return {
  24232. encrypt: async function encrypt(pt, iv, adata = new Uint8Array()) {
  24233. pt = Buffer.from(pt);
  24234. iv = Buffer.from(iv);
  24235. adata = Buffer.from(adata);
  24236. const en = new nodeCrypto.createCipheriv('aes-' + key.length * 8 + '-gcm', key, iv);
  24237. en.setAAD(adata);
  24238. const ct = Buffer.concat([en.update(pt), en.final(), en.getAuthTag()]); // append auth tag to ciphertext
  24239. return new Uint8Array(ct);
  24240. },
  24241. decrypt: async function decrypt(ct, iv, adata = new Uint8Array()) {
  24242. ct = Buffer.from(ct);
  24243. iv = Buffer.from(iv);
  24244. adata = Buffer.from(adata);
  24245. const de = new nodeCrypto.createDecipheriv('aes-' + key.length * 8 + '-gcm', key, iv);
  24246. de.setAAD(adata);
  24247. de.setAuthTag(ct.slice(ct.length - tagLength, ct.length)); // read auth tag at end of ciphertext
  24248. const pt = Buffer.concat([de.update(ct.slice(0, ct.length - tagLength)), de.final()]);
  24249. return new Uint8Array(pt);
  24250. }
  24251. };
  24252. }
  24253. return {
  24254. encrypt: async function encrypt(pt, iv, adata) {
  24255. return _gcm.AES_GCM.encrypt(pt, key, iv, adata);
  24256. },
  24257. decrypt: async function decrypt(ct, iv, adata) {
  24258. return _gcm.AES_GCM.decrypt(ct, key, iv, adata);
  24259. }
  24260. };
  24261. }
  24262. /**
  24263. * Get GCM nonce. Note: this operation is not defined by the standard.
  24264. * A future version of the standard may define GCM mode differently,
  24265. * hopefully under a different ID (we use Private/Experimental algorithm
  24266. * ID 100) so that we can maintain backwards compatibility.
  24267. * @param {Uint8Array} iv The initialization vector (12 bytes)
  24268. * @param {Uint8Array} chunkIndex The chunk index (8 bytes)
  24269. */
  24270. GCM.getNonce = function (iv, chunkIndex) {
  24271. const nonce = iv.slice();
  24272. for (let i = 0; i < chunkIndex.length; i++) {
  24273. nonce[4 + i] ^= chunkIndex[i];
  24274. }
  24275. return nonce;
  24276. };
  24277. GCM.blockLength = blockLength;
  24278. GCM.ivLength = ivLength;
  24279. GCM.tagLength = tagLength;
  24280. exports.default = GCM;
  24281. },{"../util":158,"asmcrypto.js/dist_es5/aes/gcm":8}],92:[function(require,module,exports){
  24282. 'use strict';
  24283. Object.defineProperty(exports, "__esModule", {
  24284. value: true
  24285. });
  24286. var _sha = require('asmcrypto.js/dist_es5/hash/sha1/sha1');
  24287. var _sha2 = require('asmcrypto.js/dist_es5/hash/sha256/sha256');
  24288. var _ = require('hash.js/lib/hash/sha/224');
  24289. var _2 = _interopRequireDefault(_);
  24290. var _3 = require('hash.js/lib/hash/sha/384');
  24291. var _4 = _interopRequireDefault(_3);
  24292. var _5 = require('hash.js/lib/hash/sha/512');
  24293. var _6 = _interopRequireDefault(_5);
  24294. var _ripemd = require('hash.js/lib/hash/ripemd');
  24295. var _webStreamTools = require('web-stream-tools');
  24296. var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
  24297. var _md = require('./md5');
  24298. var _md2 = _interopRequireDefault(_md);
  24299. var _config = require('../../config');
  24300. var _config2 = _interopRequireDefault(_config);
  24301. var _util = require('../../util');
  24302. var _util2 = _interopRequireDefault(_util);
  24303. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24304. /**
  24305. * @fileoverview Provides an interface to hashing functions available in Node.js or external libraries.
  24306. * @see {@link https://github.com/asmcrypto/asmcrypto.js|asmCrypto}
  24307. * @see {@link https://github.com/indutny/hash.js|hash.js}
  24308. * @requires asmcrypto.js
  24309. * @requires hash.js
  24310. * @requires web-stream-tools
  24311. * @requires crypto/hash/md5
  24312. * @requires config
  24313. * @requires util
  24314. * @module crypto/hash
  24315. */
  24316. const webCrypto = _util2.default.getWebCrypto();
  24317. const nodeCrypto = _util2.default.getNodeCrypto();
  24318. const Buffer = _util2.default.getNodeBuffer();
  24319. function node_hash(type) {
  24320. return async function (data) {
  24321. const shasum = nodeCrypto.createHash(type);
  24322. return _webStreamTools2.default.transform(data, value => {
  24323. shasum.update(Buffer.from(value));
  24324. }, () => new Uint8Array(shasum.digest()));
  24325. };
  24326. }
  24327. function hashjs_hash(hash, webCryptoHash) {
  24328. return async function (data) {
  24329. if (!_util2.default.isStream(data) && webCrypto && webCryptoHash && data.length >= _config2.default.min_bytes_for_web_crypto) {
  24330. return new Uint8Array((await webCrypto.digest(webCryptoHash, data)));
  24331. }
  24332. const hashInstance = hash();
  24333. return _webStreamTools2.default.transform(data, value => {
  24334. hashInstance.update(value);
  24335. }, () => new Uint8Array(hashInstance.digest()));
  24336. };
  24337. }
  24338. function asmcrypto_hash(hash, webCryptoHash) {
  24339. return async function (data) {
  24340. if (_util2.default.isStream(data)) {
  24341. const hashInstance = new hash();
  24342. return _webStreamTools2.default.transform(data, value => {
  24343. hashInstance.process(value);
  24344. }, () => hashInstance.finish().result);
  24345. } else if (webCrypto && webCryptoHash && data.length >= _config2.default.min_bytes_for_web_crypto) {
  24346. return new Uint8Array((await webCrypto.digest(webCryptoHash, data)));
  24347. } else {
  24348. return hash.bytes(data);
  24349. }
  24350. };
  24351. }
  24352. let hash_fns;
  24353. if (nodeCrypto) {
  24354. // Use Node native crypto for all hash functions
  24355. hash_fns = {
  24356. md5: node_hash('md5'),
  24357. sha1: node_hash('sha1'),
  24358. sha224: node_hash('sha224'),
  24359. sha256: node_hash('sha256'),
  24360. sha384: node_hash('sha384'),
  24361. sha512: node_hash('sha512'),
  24362. ripemd: node_hash('ripemd160')
  24363. };
  24364. } else {
  24365. // Use JS fallbacks
  24366. hash_fns = {
  24367. md5: _md2.default,
  24368. sha1: asmcrypto_hash(_sha.Sha1, navigator.userAgent.indexOf('Edge') === -1 && 'SHA-1'),
  24369. sha224: hashjs_hash(_2.default),
  24370. sha256: asmcrypto_hash(_sha2.Sha256, 'SHA-256'),
  24371. sha384: hashjs_hash(_4.default, 'SHA-384'),
  24372. sha512: hashjs_hash(_6.default, 'SHA-512'), // asmcrypto sha512 is huge.
  24373. ripemd: hashjs_hash(_ripemd.ripemd160)
  24374. };
  24375. }
  24376. exports.default = {
  24377. /** @see module:md5 */
  24378. md5: hash_fns.md5,
  24379. /** @see asmCrypto */
  24380. sha1: hash_fns.sha1,
  24381. /** @see hash.js */
  24382. sha224: hash_fns.sha224,
  24383. /** @see asmCrypto */
  24384. sha256: hash_fns.sha256,
  24385. /** @see hash.js */
  24386. sha384: hash_fns.sha384,
  24387. /** @see asmCrypto */
  24388. sha512: hash_fns.sha512,
  24389. /** @see hash.js */
  24390. ripemd: hash_fns.ripemd,
  24391. /**
  24392. * Create a hash on the specified data using the specified algorithm
  24393. * @param {module:enums.hash} algo Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})
  24394. * @param {Uint8Array} data Data to be hashed
  24395. * @returns {Promise<Uint8Array>} hash value
  24396. */
  24397. digest: function digest(algo, data) {
  24398. switch (algo) {
  24399. case 1:
  24400. // - MD5 [HAC]
  24401. return this.md5(data);
  24402. case 2:
  24403. // - SHA-1 [FIPS180]
  24404. return this.sha1(data);
  24405. case 3:
  24406. // - RIPE-MD/160 [HAC]
  24407. return this.ripemd(data);
  24408. case 8:
  24409. // - SHA256 [FIPS180]
  24410. return this.sha256(data);
  24411. case 9:
  24412. // - SHA384 [FIPS180]
  24413. return this.sha384(data);
  24414. case 10:
  24415. // - SHA512 [FIPS180]
  24416. return this.sha512(data);
  24417. case 11:
  24418. // - SHA224 [FIPS180]
  24419. return this.sha224(data);
  24420. default:
  24421. throw new Error('Invalid hash function.');
  24422. }
  24423. },
  24424. /**
  24425. * Returns the hash size in bytes of the specified hash algorithm type
  24426. * @param {module:enums.hash} algo Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4})
  24427. * @returns {Integer} Size in bytes of the resulting hash
  24428. */
  24429. getHashByteLength: function getHashByteLength(algo) {
  24430. switch (algo) {
  24431. case 1:
  24432. // - MD5 [HAC]
  24433. return 16;
  24434. case 2: // - SHA-1 [FIPS180]
  24435. case 3:
  24436. // - RIPE-MD/160 [HAC]
  24437. return 20;
  24438. case 8:
  24439. // - SHA256 [FIPS180]
  24440. return 32;
  24441. case 9:
  24442. // - SHA384 [FIPS180]
  24443. return 48;
  24444. case 10:
  24445. // - SHA512 [FIPS180]
  24446. return 64;
  24447. case 11:
  24448. // - SHA224 [FIPS180]
  24449. return 28;
  24450. default:
  24451. throw new Error('Invalid hash algorithm.');
  24452. }
  24453. }
  24454. };
  24455. },{"../../config":79,"../../util":158,"./md5":93,"asmcrypto.js/dist_es5/hash/sha1/sha1":11,"asmcrypto.js/dist_es5/hash/sha256/sha256":13,"hash.js/lib/hash/ripemd":37,"hash.js/lib/hash/sha/224":40,"hash.js/lib/hash/sha/384":42,"hash.js/lib/hash/sha/512":43,"web-stream-tools":75}],93:[function(require,module,exports){
  24456. 'use strict';
  24457. Object.defineProperty(exports, "__esModule", {
  24458. value: true
  24459. });
  24460. var _util = require('../../util');
  24461. var _util2 = _interopRequireDefault(_util);
  24462. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24463. // MD5 Digest
  24464. async function md5(entree) {
  24465. const digest = md51(_util2.default.Uint8Array_to_str(entree));
  24466. return _util2.default.hex_to_Uint8Array(hex(digest));
  24467. } /**
  24468. * A fast MD5 JavaScript implementation
  24469. * Copyright (c) 2012 Joseph Myers
  24470. * http://www.myersdaily.org/joseph/javascript/md5-text.html
  24471. *
  24472. * Permission to use, copy, modify, and distribute this software
  24473. * and its documentation for any purposes and without
  24474. * fee is hereby granted provided that this copyright notice
  24475. * appears in all copies.
  24476. *
  24477. * Of course, this soft is provided "as is" without express or implied
  24478. * warranty of any kind.
  24479. */
  24480. /**
  24481. * @requires util
  24482. */
  24483. function md5cycle(x, k) {
  24484. let a = x[0];
  24485. let b = x[1];
  24486. let c = x[2];
  24487. let d = x[3];
  24488. a = ff(a, b, c, d, k[0], 7, -680876936);
  24489. d = ff(d, a, b, c, k[1], 12, -389564586);
  24490. c = ff(c, d, a, b, k[2], 17, 606105819);
  24491. b = ff(b, c, d, a, k[3], 22, -1044525330);
  24492. a = ff(a, b, c, d, k[4], 7, -176418897);
  24493. d = ff(d, a, b, c, k[5], 12, 1200080426);
  24494. c = ff(c, d, a, b, k[6], 17, -1473231341);
  24495. b = ff(b, c, d, a, k[7], 22, -45705983);
  24496. a = ff(a, b, c, d, k[8], 7, 1770035416);
  24497. d = ff(d, a, b, c, k[9], 12, -1958414417);
  24498. c = ff(c, d, a, b, k[10], 17, -42063);
  24499. b = ff(b, c, d, a, k[11], 22, -1990404162);
  24500. a = ff(a, b, c, d, k[12], 7, 1804603682);
  24501. d = ff(d, a, b, c, k[13], 12, -40341101);
  24502. c = ff(c, d, a, b, k[14], 17, -1502002290);
  24503. b = ff(b, c, d, a, k[15], 22, 1236535329);
  24504. a = gg(a, b, c, d, k[1], 5, -165796510);
  24505. d = gg(d, a, b, c, k[6], 9, -1069501632);
  24506. c = gg(c, d, a, b, k[11], 14, 643717713);
  24507. b = gg(b, c, d, a, k[0], 20, -373897302);
  24508. a = gg(a, b, c, d, k[5], 5, -701558691);
  24509. d = gg(d, a, b, c, k[10], 9, 38016083);
  24510. c = gg(c, d, a, b, k[15], 14, -660478335);
  24511. b = gg(b, c, d, a, k[4], 20, -405537848);
  24512. a = gg(a, b, c, d, k[9], 5, 568446438);
  24513. d = gg(d, a, b, c, k[14], 9, -1019803690);
  24514. c = gg(c, d, a, b, k[3], 14, -187363961);
  24515. b = gg(b, c, d, a, k[8], 20, 1163531501);
  24516. a = gg(a, b, c, d, k[13], 5, -1444681467);
  24517. d = gg(d, a, b, c, k[2], 9, -51403784);
  24518. c = gg(c, d, a, b, k[7], 14, 1735328473);
  24519. b = gg(b, c, d, a, k[12], 20, -1926607734);
  24520. a = hh(a, b, c, d, k[5], 4, -378558);
  24521. d = hh(d, a, b, c, k[8], 11, -2022574463);
  24522. c = hh(c, d, a, b, k[11], 16, 1839030562);
  24523. b = hh(b, c, d, a, k[14], 23, -35309556);
  24524. a = hh(a, b, c, d, k[1], 4, -1530992060);
  24525. d = hh(d, a, b, c, k[4], 11, 1272893353);
  24526. c = hh(c, d, a, b, k[7], 16, -155497632);
  24527. b = hh(b, c, d, a, k[10], 23, -1094730640);
  24528. a = hh(a, b, c, d, k[13], 4, 681279174);
  24529. d = hh(d, a, b, c, k[0], 11, -358537222);
  24530. c = hh(c, d, a, b, k[3], 16, -722521979);
  24531. b = hh(b, c, d, a, k[6], 23, 76029189);
  24532. a = hh(a, b, c, d, k[9], 4, -640364487);
  24533. d = hh(d, a, b, c, k[12], 11, -421815835);
  24534. c = hh(c, d, a, b, k[15], 16, 530742520);
  24535. b = hh(b, c, d, a, k[2], 23, -995338651);
  24536. a = ii(a, b, c, d, k[0], 6, -198630844);
  24537. d = ii(d, a, b, c, k[7], 10, 1126891415);
  24538. c = ii(c, d, a, b, k[14], 15, -1416354905);
  24539. b = ii(b, c, d, a, k[5], 21, -57434055);
  24540. a = ii(a, b, c, d, k[12], 6, 1700485571);
  24541. d = ii(d, a, b, c, k[3], 10, -1894986606);
  24542. c = ii(c, d, a, b, k[10], 15, -1051523);
  24543. b = ii(b, c, d, a, k[1], 21, -2054922799);
  24544. a = ii(a, b, c, d, k[8], 6, 1873313359);
  24545. d = ii(d, a, b, c, k[15], 10, -30611744);
  24546. c = ii(c, d, a, b, k[6], 15, -1560198380);
  24547. b = ii(b, c, d, a, k[13], 21, 1309151649);
  24548. a = ii(a, b, c, d, k[4], 6, -145523070);
  24549. d = ii(d, a, b, c, k[11], 10, -1120210379);
  24550. c = ii(c, d, a, b, k[2], 15, 718787259);
  24551. b = ii(b, c, d, a, k[9], 21, -343485551);
  24552. x[0] = add32(a, x[0]);
  24553. x[1] = add32(b, x[1]);
  24554. x[2] = add32(c, x[2]);
  24555. x[3] = add32(d, x[3]);
  24556. }
  24557. function cmn(q, a, b, x, s, t) {
  24558. a = add32(add32(a, q), add32(x, t));
  24559. return add32(a << s | a >>> 32 - s, b);
  24560. }
  24561. function ff(a, b, c, d, x, s, t) {
  24562. return cmn(b & c | ~b & d, a, b, x, s, t);
  24563. }
  24564. function gg(a, b, c, d, x, s, t) {
  24565. return cmn(b & d | c & ~d, a, b, x, s, t);
  24566. }
  24567. function hh(a, b, c, d, x, s, t) {
  24568. return cmn(b ^ c ^ d, a, b, x, s, t);
  24569. }
  24570. function ii(a, b, c, d, x, s, t) {
  24571. return cmn(c ^ (b | ~d), a, b, x, s, t);
  24572. }
  24573. function md51(s) {
  24574. const n = s.length;
  24575. const state = [1732584193, -271733879, -1732584194, 271733878];
  24576. let i;
  24577. for (i = 64; i <= s.length; i += 64) {
  24578. md5cycle(state, md5blk(s.substring(i - 64, i)));
  24579. }
  24580. s = s.substring(i - 64);
  24581. const tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
  24582. for (i = 0; i < s.length; i++) {
  24583. tail[i >> 2] |= s.charCodeAt(i) << (i % 4 << 3);
  24584. }
  24585. tail[i >> 2] |= 0x80 << (i % 4 << 3);
  24586. if (i > 55) {
  24587. md5cycle(state, tail);
  24588. for (i = 0; i < 16; i++) {
  24589. tail[i] = 0;
  24590. }
  24591. }
  24592. tail[14] = n * 8;
  24593. md5cycle(state, tail);
  24594. return state;
  24595. }
  24596. /* there needs to be support for Unicode here,
  24597. * unless we pretend that we can redefine the MD-5
  24598. * algorithm for multi-byte characters (perhaps
  24599. * by adding every four 16-bit characters and
  24600. * shortening the sum to 32 bits). Otherwise
  24601. * I suggest performing MD-5 as if every character
  24602. * was two bytes--e.g., 0040 0025 = @%--but then
  24603. * how will an ordinary MD-5 sum be matched?
  24604. * There is no way to standardize text to something
  24605. * like UTF-8 before transformation; speed cost is
  24606. * utterly prohibitive. The JavaScript standard
  24607. * itself needs to look at this: it should start
  24608. * providing access to strings as preformed UTF-8
  24609. * 8-bit unsigned value arrays.
  24610. */
  24611. function md5blk(s) {
  24612. /* I figured global was faster. */
  24613. const md5blks = [];
  24614. let i; /* Andy King said do it this way. */
  24615. for (i = 0; i < 64; i += 4) {
  24616. md5blks[i >> 2] = s.charCodeAt(i) + (s.charCodeAt(i + 1) << 8) + (s.charCodeAt(i + 2) << 16) + (s.charCodeAt(i + 3) << 24);
  24617. }
  24618. return md5blks;
  24619. }
  24620. const hex_chr = '0123456789abcdef'.split('');
  24621. function rhex(n) {
  24622. let s = '';
  24623. let j = 0;
  24624. for (; j < 4; j++) {
  24625. s += hex_chr[n >> j * 8 + 4 & 0x0F] + hex_chr[n >> j * 8 & 0x0F];
  24626. }
  24627. return s;
  24628. }
  24629. function hex(x) {
  24630. for (let i = 0; i < x.length; i++) {
  24631. x[i] = rhex(x[i]);
  24632. }
  24633. return x.join('');
  24634. }
  24635. /* this function is much faster,
  24636. so if possible we use it. Some IEs
  24637. are the only ones I know of that
  24638. need the idiotic second function,
  24639. generated by an if clause. */
  24640. function add32(a, b) {
  24641. return a + b & 0xFFFFFFFF;
  24642. }
  24643. exports.default = md5;
  24644. },{"../../util":158}],94:[function(require,module,exports){
  24645. 'use strict';
  24646. Object.defineProperty(exports, "__esModule", {
  24647. value: true
  24648. });
  24649. var _cipher = require('./cipher');
  24650. var _cipher2 = _interopRequireDefault(_cipher);
  24651. var _hash = require('./hash');
  24652. var _hash2 = _interopRequireDefault(_hash);
  24653. var _cfb = require('./cfb');
  24654. var _cfb2 = _interopRequireDefault(_cfb);
  24655. var _gcm = require('./gcm');
  24656. var _gcm2 = _interopRequireDefault(_gcm);
  24657. var _eax = require('./eax');
  24658. var _eax2 = _interopRequireDefault(_eax);
  24659. var _ocb = require('./ocb');
  24660. var _ocb2 = _interopRequireDefault(_ocb);
  24661. var _public_key = require('./public_key');
  24662. var _public_key2 = _interopRequireDefault(_public_key);
  24663. var _signature = require('./signature');
  24664. var _signature2 = _interopRequireDefault(_signature);
  24665. var _random = require('./random');
  24666. var _random2 = _interopRequireDefault(_random);
  24667. var _pkcs = require('./pkcs1');
  24668. var _pkcs2 = _interopRequireDefault(_pkcs);
  24669. var _pkcs3 = require('./pkcs5');
  24670. var _pkcs4 = _interopRequireDefault(_pkcs3);
  24671. var _crypto = require('./crypto');
  24672. var _crypto2 = _interopRequireDefault(_crypto);
  24673. var _aes_kw = require('./aes_kw');
  24674. var _aes_kw2 = _interopRequireDefault(_aes_kw);
  24675. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24676. // TODO move cfb and gcm to cipher
  24677. const mod = {
  24678. /** @see module:crypto/cipher */
  24679. cipher: _cipher2.default,
  24680. /** @see module:crypto/hash */
  24681. hash: _hash2.default,
  24682. /** @see module:crypto/cfb */
  24683. cfb: _cfb2.default,
  24684. /** @see module:crypto/gcm */
  24685. gcm: _gcm2.default,
  24686. experimental_gcm: _gcm2.default,
  24687. /** @see module:crypto/eax */
  24688. eax: _eax2.default,
  24689. /** @see module:crypto/ocb */
  24690. ocb: _ocb2.default,
  24691. /** @see module:crypto/public_key */
  24692. publicKey: _public_key2.default,
  24693. /** @see module:crypto/signature */
  24694. signature: _signature2.default,
  24695. /** @see module:crypto/random */
  24696. random: _random2.default,
  24697. /** @see module:crypto/pkcs1 */
  24698. pkcs1: _pkcs2.default,
  24699. /** @see module:crypto/pkcs5 */
  24700. pkcs5: _pkcs4.default,
  24701. /** @see module:crypto/aes_kw */
  24702. aes_kw: _aes_kw2.default
  24703. }; /**
  24704. * @fileoverview Provides access to all cryptographic primitives used in OpenPGP.js
  24705. * @see module:crypto/crypto
  24706. * @see module:crypto/signature
  24707. * @see module:crypto/public_key
  24708. * @see module:crypto/cipher
  24709. * @see module:crypto/random
  24710. * @see module:crypto/hash
  24711. * @module crypto
  24712. */
  24713. Object.assign(mod, _crypto2.default);
  24714. exports.default = mod;
  24715. },{"./aes_kw":80,"./cfb":81,"./cipher":86,"./crypto":89,"./eax":90,"./gcm":91,"./hash":92,"./ocb":95,"./pkcs1":96,"./pkcs5":97,"./public_key":106,"./random":109,"./signature":110}],95:[function(require,module,exports){
  24716. 'use strict';
  24717. Object.defineProperty(exports, "__esModule", {
  24718. value: true
  24719. });
  24720. var _cipher = require('./cipher');
  24721. var _cipher2 = _interopRequireDefault(_cipher);
  24722. var _util = require('../util');
  24723. var _util2 = _interopRequireDefault(_util);
  24724. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24725. // OpenPGP.js - An OpenPGP implementation in javascript
  24726. // Copyright (C) 2018 ProtonTech AG
  24727. //
  24728. // This library is free software; you can redistribute it and/or
  24729. // modify it under the terms of the GNU Lesser General Public
  24730. // License as published by the Free Software Foundation; either
  24731. // version 3.0 of the License, or (at your option) any later version.
  24732. //
  24733. // This library is distributed in the hope that it will be useful,
  24734. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  24735. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  24736. // Lesser General Public License for more details.
  24737. //
  24738. // You should have received a copy of the GNU Lesser General Public
  24739. // License along with this library; if not, write to the Free Software
  24740. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  24741. /**
  24742. * @fileoverview This module implements AES-OCB en/decryption.
  24743. * @requires crypto/cipher
  24744. * @requires util
  24745. * @module crypto/ocb
  24746. */
  24747. const blockLength = 16;
  24748. const ivLength = 15;
  24749. // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2:
  24750. // While OCB [RFC7253] allows the authentication tag length to be of any
  24751. // number up to 128 bits long, this document requires a fixed
  24752. // authentication tag length of 128 bits (16 octets) for simplicity.
  24753. const tagLength = 16;
  24754. function ntz(n) {
  24755. let ntz = 0;
  24756. for (let i = 1; (n & i) === 0; i <<= 1) {
  24757. ntz++;
  24758. }
  24759. return ntz;
  24760. }
  24761. function xorMut(S, T) {
  24762. for (let i = 0; i < S.length; i++) {
  24763. S[i] ^= T[i];
  24764. }
  24765. return S;
  24766. }
  24767. function xor(S, T) {
  24768. return xorMut(S.slice(), T);
  24769. }
  24770. const zeroBlock = new Uint8Array(blockLength);
  24771. const one = new Uint8Array([1]);
  24772. /**
  24773. * Class to en/decrypt using OCB mode.
  24774. * @param {String} cipher The symmetric cipher algorithm to use e.g. 'aes128'
  24775. * @param {Uint8Array} key The encryption key
  24776. */
  24777. async function OCB(cipher, key) {
  24778. let maxNtz = 0;
  24779. let encipher;
  24780. let decipher;
  24781. let mask;
  24782. constructKeyVariables(cipher, key);
  24783. function constructKeyVariables(cipher, key) {
  24784. const aes = new _cipher2.default[cipher](key);
  24785. encipher = aes.encrypt.bind(aes);
  24786. decipher = aes.decrypt.bind(aes);
  24787. const mask_x = encipher(zeroBlock);
  24788. const mask_$ = _util2.default.double(mask_x);
  24789. mask = [];
  24790. mask[0] = _util2.default.double(mask_$);
  24791. mask.x = mask_x;
  24792. mask.$ = mask_$;
  24793. }
  24794. function extendKeyVariables(text, adata) {
  24795. const newMaxNtz = _util2.default.nbits(Math.max(text.length, adata.length) / blockLength | 0) - 1;
  24796. for (let i = maxNtz + 1; i <= newMaxNtz; i++) {
  24797. mask[i] = _util2.default.double(mask[i - 1]);
  24798. }
  24799. maxNtz = newMaxNtz;
  24800. }
  24801. function hash(adata) {
  24802. if (!adata.length) {
  24803. // Fast path
  24804. return zeroBlock;
  24805. }
  24806. //
  24807. // Consider A as a sequence of 128-bit blocks
  24808. //
  24809. const m = adata.length / blockLength | 0;
  24810. const offset = new Uint8Array(blockLength);
  24811. const sum = new Uint8Array(blockLength);
  24812. for (let i = 0; i < m; i++) {
  24813. xorMut(offset, mask[ntz(i + 1)]);
  24814. xorMut(sum, encipher(xor(offset, adata)));
  24815. adata = adata.subarray(blockLength);
  24816. }
  24817. //
  24818. // Process any final partial block; compute final hash value
  24819. //
  24820. if (adata.length) {
  24821. xorMut(offset, mask.x);
  24822. const cipherInput = new Uint8Array(blockLength);
  24823. cipherInput.set(adata, 0);
  24824. cipherInput[adata.length] = 0b10000000;
  24825. xorMut(cipherInput, offset);
  24826. xorMut(sum, encipher(cipherInput));
  24827. }
  24828. return sum;
  24829. }
  24830. /**
  24831. * Encrypt/decrypt data.
  24832. * @param {encipher|decipher} fn Encryption/decryption block cipher function
  24833. * @param {Uint8Array} text The cleartext or ciphertext (without tag) input
  24834. * @param {Uint8Array} nonce The nonce (15 bytes)
  24835. * @param {Uint8Array} adata Associated data to sign
  24836. * @returns {Promise<Uint8Array>} The ciphertext or plaintext output, with tag appended in both cases
  24837. */
  24838. function crypt(fn, text, nonce, adata) {
  24839. //
  24840. // Consider P as a sequence of 128-bit blocks
  24841. //
  24842. const m = text.length / blockLength | 0;
  24843. //
  24844. // Key-dependent variables
  24845. //
  24846. extendKeyVariables(text, adata);
  24847. //
  24848. // Nonce-dependent and per-encryption variables
  24849. //
  24850. // Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N
  24851. // Note: We assume here that tagLength mod 16 == 0.
  24852. const paddedNonce = _util2.default.concatUint8Array([zeroBlock.subarray(0, ivLength - nonce.length), one, nonce]);
  24853. // bottom = str2num(Nonce[123..128])
  24854. const bottom = paddedNonce[blockLength - 1] & 0b111111;
  24855. // Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6))
  24856. paddedNonce[blockLength - 1] &= 0b11000000;
  24857. const kTop = encipher(paddedNonce);
  24858. // Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72])
  24859. const stretched = _util2.default.concatUint8Array([kTop, xor(kTop.subarray(0, 8), kTop.subarray(1, 9))]);
  24860. // Offset_0 = Stretch[1+bottom..128+bottom]
  24861. const offset = _util2.default.shiftRight(stretched.subarray(0 + (bottom >> 3), 17 + (bottom >> 3)), 8 - (bottom & 7)).subarray(1);
  24862. // Checksum_0 = zeros(128)
  24863. const checksum = new Uint8Array(blockLength);
  24864. const ct = new Uint8Array(text.length + tagLength);
  24865. //
  24866. // Process any whole blocks
  24867. //
  24868. let i;
  24869. let pos = 0;
  24870. for (i = 0; i < m; i++) {
  24871. // Offset_i = Offset_{i-1} xor L_{ntz(i)}
  24872. xorMut(offset, mask[ntz(i + 1)]);
  24873. // C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i)
  24874. // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i)
  24875. ct.set(xorMut(fn(xor(offset, text)), offset), pos);
  24876. // Checksum_i = Checksum_{i-1} xor P_i
  24877. xorMut(checksum, fn === encipher ? text : ct.subarray(pos));
  24878. text = text.subarray(blockLength);
  24879. pos += blockLength;
  24880. }
  24881. //
  24882. // Process any final partial block and compute raw tag
  24883. //
  24884. if (text.length) {
  24885. // Offset_* = Offset_m xor L_*
  24886. xorMut(offset, mask.x);
  24887. // Pad = ENCIPHER(K, Offset_*)
  24888. const padding = encipher(offset);
  24889. // C_* = P_* xor Pad[1..bitlen(P_*)]
  24890. ct.set(xor(text, padding), pos);
  24891. // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*)))
  24892. const xorInput = new Uint8Array(blockLength);
  24893. xorInput.set(fn === encipher ? text : ct.subarray(pos, -tagLength), 0);
  24894. xorInput[text.length] = 0b10000000;
  24895. xorMut(checksum, xorInput);
  24896. pos += text.length;
  24897. }
  24898. // Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A)
  24899. const tag = xorMut(encipher(xorMut(xorMut(checksum, offset), mask.$)), hash(adata));
  24900. //
  24901. // Assemble ciphertext
  24902. //
  24903. // C = C_1 || C_2 || ... || C_m || C_* || Tag[1..TAGLEN]
  24904. ct.set(tag, pos);
  24905. return ct;
  24906. }
  24907. return {
  24908. /**
  24909. * Encrypt plaintext input.
  24910. * @param {Uint8Array} plaintext The cleartext input to be encrypted
  24911. * @param {Uint8Array} nonce The nonce (15 bytes)
  24912. * @param {Uint8Array} adata Associated data to sign
  24913. * @returns {Promise<Uint8Array>} The ciphertext output
  24914. */
  24915. encrypt: async function encrypt(plaintext, nonce, adata) {
  24916. return crypt(encipher, plaintext, nonce, adata);
  24917. },
  24918. /**
  24919. * Decrypt ciphertext input.
  24920. * @param {Uint8Array} ciphertext The ciphertext input to be decrypted
  24921. * @param {Uint8Array} nonce The nonce (15 bytes)
  24922. * @param {Uint8Array} adata Associated data to sign
  24923. * @returns {Promise<Uint8Array>} The ciphertext output
  24924. */
  24925. decrypt: async function decrypt(ciphertext, nonce, adata) {
  24926. if (ciphertext.length < tagLength) throw new Error('Invalid OCB ciphertext');
  24927. const tag = ciphertext.subarray(-tagLength);
  24928. ciphertext = ciphertext.subarray(0, -tagLength);
  24929. const crypted = crypt(decipher, ciphertext, nonce, adata);
  24930. // if (Tag[1..TAGLEN] == T)
  24931. if (_util2.default.equalsUint8Array(tag, crypted.subarray(-tagLength))) {
  24932. return crypted.subarray(0, -tagLength);
  24933. }
  24934. throw new Error('Authentication tag mismatch');
  24935. }
  24936. };
  24937. }
  24938. /**
  24939. * Get OCB nonce as defined by {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.16.2|RFC4880bis-04, section 5.16.2}.
  24940. * @param {Uint8Array} iv The initialization vector (15 bytes)
  24941. * @param {Uint8Array} chunkIndex The chunk index (8 bytes)
  24942. */
  24943. OCB.getNonce = function (iv, chunkIndex) {
  24944. const nonce = iv.slice();
  24945. for (let i = 0; i < chunkIndex.length; i++) {
  24946. nonce[7 + i] ^= chunkIndex[i];
  24947. }
  24948. return nonce;
  24949. };
  24950. OCB.blockLength = blockLength;
  24951. OCB.ivLength = ivLength;
  24952. OCB.tagLength = tagLength;
  24953. exports.default = OCB;
  24954. },{"../util":158,"./cipher":86}],96:[function(require,module,exports){
  24955. 'use strict';
  24956. Object.defineProperty(exports, "__esModule", {
  24957. value: true
  24958. });
  24959. var _random = require('./random');
  24960. var _random2 = _interopRequireDefault(_random);
  24961. var _hash = require('./hash');
  24962. var _hash2 = _interopRequireDefault(_hash);
  24963. var _util = require('../util');
  24964. var _util2 = _interopRequireDefault(_util);
  24965. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  24966. /** @namespace */
  24967. const eme = {};
  24968. /** @namespace */
  24969. // GPG4Browsers - An OpenPGP implementation in javascript
  24970. // Copyright (C) 2011 Recurity Labs GmbH
  24971. //
  24972. // This library is free software; you can redistribute it and/or
  24973. // modify it under the terms of the GNU Lesser General Public
  24974. // License as published by the Free Software Foundation; either
  24975. // version 3.0 of the License, or (at your option) any later version.
  24976. //
  24977. // This library is distributed in the hope that it will be useful,
  24978. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  24979. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  24980. // Lesser General Public License for more details.
  24981. //
  24982. // You should have received a copy of the GNU Lesser General Public
  24983. // License along with this library; if not, write to the Free Software
  24984. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  24985. /**
  24986. * @fileoverview Provides EME-PKCS1-v1_5 encoding and decoding and EMSA-PKCS1-v1_5 encoding function
  24987. * @see module:crypto/public_key/rsa
  24988. * @see module:crypto/public_key/elliptic/ecdh
  24989. * @see module:packet.PublicKeyEncryptedSessionKey
  24990. * @requires crypto/random
  24991. * @requires crypto/hash
  24992. * @requires util
  24993. * @module crypto/pkcs1
  24994. */
  24995. const emsa = {};
  24996. /**
  24997. * ASN1 object identifiers for hashes
  24998. * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.2}
  24999. */
  25000. const hash_headers = [];
  25001. hash_headers[1] = [0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10];
  25002. hash_headers[2] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14];
  25003. hash_headers[3] = [0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14];
  25004. hash_headers[8] = [0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20];
  25005. hash_headers[9] = [0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30];
  25006. hash_headers[10] = [0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40];
  25007. hash_headers[11] = [0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1C];
  25008. /**
  25009. * Create padding with secure random data
  25010. * @private
  25011. * @param {Integer} length Length of the padding in bytes
  25012. * @returns {String} Padding as string
  25013. * @async
  25014. */
  25015. async function getPkcs1Padding(length) {
  25016. let result = '';
  25017. while (result.length < length) {
  25018. const randomBytes = await _random2.default.getRandomBytes(length - result.length);
  25019. for (let i = 0; i < randomBytes.length; i++) {
  25020. if (randomBytes[i] !== 0) {
  25021. result += String.fromCharCode(randomBytes[i]);
  25022. }
  25023. }
  25024. }
  25025. return result;
  25026. }
  25027. /**
  25028. * Create a EME-PKCS1-v1_5 padded message
  25029. * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.1|RFC 4880 13.1.1}
  25030. * @param {String} M message to be encoded
  25031. * @param {Integer} k the length in octets of the key modulus
  25032. * @returns {Promise<String>} EME-PKCS1 padded message
  25033. * @async
  25034. */
  25035. eme.encode = async function (M, k) {
  25036. const mLen = M.length;
  25037. // length checking
  25038. if (mLen > k - 11) {
  25039. throw new Error('Message too long');
  25040. }
  25041. // Generate an octet string PS of length k - mLen - 3 consisting of
  25042. // pseudo-randomly generated nonzero octets
  25043. const PS = await getPkcs1Padding(k - mLen - 3);
  25044. // Concatenate PS, the message M, and other padding to form an
  25045. // encoded message EM of length k octets as EM = 0x00 || 0x02 || PS || 0x00 || M.
  25046. return String.fromCharCode(0) + String.fromCharCode(2) + PS + String.fromCharCode(0) + M;
  25047. };
  25048. /**
  25049. * Decode a EME-PKCS1-v1_5 padded message
  25050. * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.2|RFC 4880 13.1.2}
  25051. * @param {String} EM encoded message, an octet string
  25052. * @returns {String} message, an octet string
  25053. */
  25054. eme.decode = function (EM) {
  25055. // leading zeros truncated by bn.js
  25056. if (EM.charCodeAt(0) !== 0) {
  25057. EM = String.fromCharCode(0) + EM;
  25058. }
  25059. const firstOct = EM.charCodeAt(0);
  25060. const secondOct = EM.charCodeAt(1);
  25061. let i = 2;
  25062. while (EM.charCodeAt(i) !== 0 && i < EM.length) {
  25063. i++;
  25064. }
  25065. const psLen = i - 2;
  25066. const separator = EM.charCodeAt(i++);
  25067. if (firstOct === 0 && secondOct === 2 && psLen >= 8 && separator === 0) {
  25068. return EM.substr(i);
  25069. }
  25070. throw new Error('Decryption error');
  25071. };
  25072. /**
  25073. * Create a EMSA-PKCS1-v1_5 padded message
  25074. * @see {@link https://tools.ietf.org/html/rfc4880#section-13.1.3|RFC 4880 13.1.3}
  25075. * @param {Integer} algo Hash algorithm type used
  25076. * @param {Uint8Array} hashed message to be encoded
  25077. * @param {Integer} emLen intended length in octets of the encoded message
  25078. * @returns {String} encoded message
  25079. */
  25080. emsa.encode = async function (algo, hashed, emLen) {
  25081. let i;
  25082. const H = _util2.default.Uint8Array_to_str(hashed);
  25083. if (H.length !== _hash2.default.getHashByteLength(algo)) {
  25084. throw new Error('Invalid hash length');
  25085. }
  25086. // produce an ASN.1 DER value for the hash function used.
  25087. // Let T be the full hash prefix
  25088. let T = '';
  25089. for (i = 0; i < hash_headers[algo].length; i++) {
  25090. T += String.fromCharCode(hash_headers[algo][i]);
  25091. }
  25092. // add hash value to prefix
  25093. T += H;
  25094. // and let tLen be the length in octets of T
  25095. const tLen = T.length;
  25096. if (emLen < tLen + 11) {
  25097. throw new Error('Intended encoded message length too short');
  25098. }
  25099. // an octet string PS consisting of emLen - tLen - 3 octets with hexadecimal value 0xFF
  25100. // The length of PS will be at least 8 octets
  25101. let PS = '';
  25102. for (i = 0; i < emLen - tLen - 3; i++) {
  25103. PS += String.fromCharCode(0xff);
  25104. }
  25105. // Concatenate PS, the hash prefix T, and other padding to form the
  25106. // encoded message EM as EM = 0x00 || 0x01 || PS || 0x00 || T.
  25107. const EM = String.fromCharCode(0x00) + String.fromCharCode(0x01) + PS + String.fromCharCode(0x00) + T;
  25108. return _util2.default.str_to_hex(EM);
  25109. };
  25110. exports.default = { eme, emsa };
  25111. },{"../util":158,"./hash":92,"./random":109}],97:[function(require,module,exports){
  25112. 'use strict';
  25113. Object.defineProperty(exports, "__esModule", {
  25114. value: true
  25115. });
  25116. // OpenPGP.js - An OpenPGP implementation in javascript
  25117. // Copyright (C) 2015-2016 Decentral
  25118. //
  25119. // This library is free software; you can redistribute it and/or
  25120. // modify it under the terms of the GNU Lesser General Public
  25121. // License as published by the Free Software Foundation; either
  25122. // version 3.0 of the License, or (at your option) any later version.
  25123. //
  25124. // This library is distributed in the hope that it will be useful,
  25125. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  25126. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  25127. // Lesser General Public License for more details.
  25128. //
  25129. // You should have received a copy of the GNU Lesser General Public
  25130. // License along with this library; if not, write to the Free Software
  25131. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  25132. /**
  25133. * @fileoverview Functions to add and remove PKCS5 padding
  25134. * @see module:packet.PublicKeyEncryptedSessionKey
  25135. * @module crypto/pkcs5
  25136. */
  25137. /**
  25138. * Add pkcs5 padding to a text.
  25139. * @param {String} msg Text to add padding
  25140. * @returns {String} Text with padding added
  25141. */
  25142. function encode(msg) {
  25143. const c = 8 - msg.length % 8;
  25144. const padding = String.fromCharCode(c).repeat(c);
  25145. return msg + padding;
  25146. }
  25147. /**
  25148. * Remove pkcs5 padding from a string.
  25149. * @param {String} msg Text to remove padding from
  25150. * @returns {String} Text with padding removed
  25151. */
  25152. function decode(msg) {
  25153. const len = msg.length;
  25154. if (len > 0) {
  25155. const c = msg.charCodeAt(len - 1);
  25156. if (c >= 1 && c <= 8) {
  25157. const provided = msg.substr(len - c);
  25158. const computed = String.fromCharCode(c).repeat(c);
  25159. if (provided === computed) {
  25160. return msg.substr(0, len - c);
  25161. }
  25162. }
  25163. }
  25164. throw new Error('Invalid padding');
  25165. }
  25166. exports.default = { encode, decode };
  25167. },{}],98:[function(require,module,exports){
  25168. 'use strict';
  25169. Object.defineProperty(exports, "__esModule", {
  25170. value: true
  25171. });
  25172. var _bn = require('bn.js');
  25173. var _bn2 = _interopRequireDefault(_bn);
  25174. var _random = require('../random');
  25175. var _random2 = _interopRequireDefault(_random);
  25176. var _util = require('../../util');
  25177. var _util2 = _interopRequireDefault(_util);
  25178. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  25179. const one = new _bn2.default(1); // GPG4Browsers - An OpenPGP implementation in javascript
  25180. // Copyright (C) 2011 Recurity Labs GmbH
  25181. //
  25182. // This library is free software; you can redistribute it and/or
  25183. // modify it under the terms of the GNU Lesser General Public
  25184. // License as published by the Free Software Foundation; either
  25185. // version 3.0 of the License, or (at your option) any later version.
  25186. //
  25187. // This library is distributed in the hope that it will be useful,
  25188. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  25189. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  25190. // Lesser General Public License for more details.
  25191. //
  25192. // You should have received a copy of the GNU Lesser General Public
  25193. // License along with this library; if not, write to the Free Software
  25194. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  25195. /**
  25196. * @fileoverview A Digital signature algorithm implementation
  25197. * @requires bn.js
  25198. * @requires crypto/random
  25199. * @requires util
  25200. * @module crypto/public_key/dsa
  25201. */
  25202. const zero = new _bn2.default(0);
  25203. /*
  25204. TODO regarding the hash function, read:
  25205. https://tools.ietf.org/html/rfc4880#section-13.6
  25206. https://tools.ietf.org/html/rfc4880#section-14
  25207. */
  25208. exports.default = {
  25209. /**
  25210. * DSA Sign function
  25211. * @param {Integer} hash_algo
  25212. * @param {Uint8Array} hashed
  25213. * @param {BN} g
  25214. * @param {BN} p
  25215. * @param {BN} q
  25216. * @param {BN} x
  25217. * @returns {{ r: BN, s: BN }}
  25218. * @async
  25219. */
  25220. sign: async function sign(hash_algo, hashed, g, p, q, x) {
  25221. let k;
  25222. let r;
  25223. let s;
  25224. let t;
  25225. const redp = new _bn2.default.red(p);
  25226. const redq = new _bn2.default.red(q);
  25227. const gred = g.toRed(redp);
  25228. const xred = x.toRed(redq);
  25229. // If the output size of the chosen hash is larger than the number of
  25230. // bits of q, the hash result is truncated to fit by taking the number
  25231. // of leftmost bits equal to the number of bits of q. This (possibly
  25232. // truncated) hash function result is treated as a number and used
  25233. // directly in the DSA signature algorithm.
  25234. const h = new _bn2.default(hashed.subarray(0, q.byteLength())).toRed(redq);
  25235. // FIPS-186-4, section 4.6:
  25236. // The values of r and s shall be checked to determine if r = 0 or s = 0.
  25237. // If either r = 0 or s = 0, a new value of k shall be generated, and the
  25238. // signature shall be recalculated. It is extremely unlikely that r = 0
  25239. // or s = 0 if signatures are generated properly.
  25240. while (true) {
  25241. // See Appendix B here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
  25242. k = await _random2.default.getRandomBN(one, q); // returns in [1, q-1]
  25243. r = gred.redPow(k).fromRed().toRed(redq); // (g**k mod p) mod q
  25244. if (zero.cmp(r) === 0) {
  25245. continue;
  25246. }
  25247. t = h.redAdd(xred.redMul(r)); // H(m) + x*r mod q
  25248. s = k.toRed(redq).redInvm().redMul(t); // k**-1 * (H(m) + x*r) mod q
  25249. if (zero.cmp(s) === 0) {
  25250. continue;
  25251. }
  25252. break;
  25253. }
  25254. return {
  25255. r: r.toArrayLike(Uint8Array, 'be', q.byteLength()),
  25256. s: s.toArrayLike(Uint8Array, 'be', q.byteLength())
  25257. };
  25258. },
  25259. /**
  25260. * DSA Verify function
  25261. * @param {Integer} hash_algo
  25262. * @param {BN} r
  25263. * @param {BN} s
  25264. * @param {Uint8Array} hashed
  25265. * @param {BN} g
  25266. * @param {BN} p
  25267. * @param {BN} q
  25268. * @param {BN} y
  25269. * @returns {boolean}
  25270. * @async
  25271. */
  25272. verify: async function verify(hash_algo, r, s, hashed, g, p, q, y) {
  25273. if (zero.ucmp(r) >= 0 || r.ucmp(q) >= 0 || zero.ucmp(s) >= 0 || s.ucmp(q) >= 0) {
  25274. _util2.default.print_debug("invalid DSA Signature");
  25275. return null;
  25276. }
  25277. const redp = new _bn2.default.red(p);
  25278. const redq = new _bn2.default.red(q);
  25279. const h = new _bn2.default(hashed.subarray(0, q.byteLength()));
  25280. const w = s.toRed(redq).redInvm(); // s**-1 mod q
  25281. if (zero.cmp(w) === 0) {
  25282. _util2.default.print_debug("invalid DSA Signature");
  25283. return null;
  25284. }
  25285. const u1 = h.toRed(redq).redMul(w); // H(m) * w mod q
  25286. const u2 = r.toRed(redq).redMul(w); // r * w mod q
  25287. const t1 = g.toRed(redp).redPow(u1.fromRed()); // g**u1 mod p
  25288. const t2 = y.toRed(redp).redPow(u2.fromRed()); // y**u2 mod p
  25289. const v = t1.redMul(t2).fromRed().mod(q); // (g**u1 * y**u2 mod p) mod q
  25290. return v.cmp(r) === 0;
  25291. }
  25292. };
  25293. },{"../../util":158,"../random":109,"bn.js":16}],99:[function(require,module,exports){
  25294. 'use strict';
  25295. Object.defineProperty(exports, "__esModule", {
  25296. value: true
  25297. });
  25298. var _bn = require('bn.js');
  25299. var _bn2 = _interopRequireDefault(_bn);
  25300. var _random = require('../random');
  25301. var _random2 = _interopRequireDefault(_random);
  25302. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  25303. // GPG4Browsers - An OpenPGP implementation in javascript
  25304. // Copyright (C) 2011 Recurity Labs GmbH
  25305. //
  25306. // This library is free software; you can redistribute it and/or
  25307. // modify it under the terms of the GNU Lesser General Public
  25308. // License as published by the Free Software Foundation; either
  25309. // version 3.0 of the License, or (at your option) any later version.
  25310. //
  25311. // This library is distributed in the hope that it will be useful,
  25312. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  25313. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  25314. // Lesser General Public License for more details.
  25315. //
  25316. // You should have received a copy of the GNU Lesser General Public
  25317. // License along with this library; if not, write to the Free Software
  25318. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  25319. /**
  25320. * @fileoverview ElGamal implementation
  25321. * @requires bn.js
  25322. * @requires crypto/random
  25323. * @module crypto/public_key/elgamal
  25324. */
  25325. const zero = new _bn2.default(0);
  25326. exports.default = {
  25327. /**
  25328. * ElGamal Encryption function
  25329. * @param {BN} m
  25330. * @param {BN} p
  25331. * @param {BN} g
  25332. * @param {BN} y
  25333. * @returns {{ c1: BN, c2: BN }}
  25334. * @async
  25335. */
  25336. encrypt: async function encrypt(m, p, g, y) {
  25337. const redp = new _bn2.default.red(p);
  25338. const mred = m.toRed(redp);
  25339. const gred = g.toRed(redp);
  25340. const yred = y.toRed(redp);
  25341. // See Section 11.5 here: https://crypto.stanford.edu/~dabo/cryptobook/BonehShoup_0_4.pdf
  25342. const k = await _random2.default.getRandomBN(zero, p); // returns in [0, p-1]
  25343. return {
  25344. c1: gred.redPow(k).fromRed(),
  25345. c2: yred.redPow(k).redMul(mred).fromRed()
  25346. };
  25347. },
  25348. /**
  25349. * ElGamal Encryption function
  25350. * @param {BN} c1
  25351. * @param {BN} c2
  25352. * @param {BN} p
  25353. * @param {BN} x
  25354. * @returns BN
  25355. * @async
  25356. */
  25357. decrypt: async function decrypt(c1, c2, p, x) {
  25358. const redp = new _bn2.default.red(p);
  25359. const c1red = c1.toRed(redp);
  25360. const c2red = c2.toRed(redp);
  25361. return c1red.redPow(x).redInvm().redMul(c2red).fromRed();
  25362. }
  25363. };
  25364. },{"../random":109,"bn.js":16}],100:[function(require,module,exports){
  25365. 'use strict';
  25366. Object.defineProperty(exports, "__esModule", {
  25367. value: true
  25368. });
  25369. exports.privateToJwk = exports.rawPublicToJwk = exports.jwkToRawPublic = exports.getPreferredHashAlgo = exports.generate = exports.nodeCurves = exports.webCurves = exports.curves = undefined;
  25370. var _bn = require('bn.js');
  25371. var _bn2 = _interopRequireDefault(_bn);
  25372. var _naclFastLight = require('tweetnacl/nacl-fast-light.js');
  25373. var _naclFastLight2 = _interopRequireDefault(_naclFastLight);
  25374. var _random = require('../../random');
  25375. var _random2 = _interopRequireDefault(_random);
  25376. var _enums = require('../../../enums');
  25377. var _enums2 = _interopRequireDefault(_enums);
  25378. var _util = require('../../../util');
  25379. var _util2 = _interopRequireDefault(_util);
  25380. var _oid = require('../../../type/oid');
  25381. var _oid2 = _interopRequireDefault(_oid);
  25382. var _indutnyKey = require('./indutnyKey');
  25383. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  25384. const webCrypto = _util2.default.getWebCrypto(); // OpenPGP.js - An OpenPGP implementation in javascript
  25385. // Copyright (C) 2015-2016 Decentral
  25386. //
  25387. // This library is free software; you can redistribute it and/or
  25388. // modify it under the terms of the GNU Lesser General Public
  25389. // License as published by the Free Software Foundation; either
  25390. // version 3.0 of the License, or (at your option) any later version.
  25391. //
  25392. // This library is distributed in the hope that it will be useful,
  25393. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  25394. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  25395. // Lesser General Public License for more details.
  25396. //
  25397. // You should have received a copy of the GNU Lesser General Public
  25398. // License along with this library; if not, write to the Free Software
  25399. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  25400. /**
  25401. * @fileoverview Wrapper of an instance of an Elliptic Curve
  25402. * @requires bn.js
  25403. * @requires tweetnacl
  25404. * @requires crypto/public_key/elliptic/key
  25405. * @requires crypto/random
  25406. * @requires enums
  25407. * @requires util
  25408. * @requires type/oid
  25409. * @requires config
  25410. * @module crypto/public_key/elliptic/curve
  25411. */
  25412. const nodeCrypto = _util2.default.getNodeCrypto();
  25413. const webCurves = {
  25414. 'p256': 'P-256',
  25415. 'p384': 'P-384',
  25416. 'p521': 'P-521'
  25417. };
  25418. const knownCurves = nodeCrypto ? nodeCrypto.getCurves() : [];
  25419. const nodeCurves = nodeCrypto ? {
  25420. secp256k1: knownCurves.includes('secp256k1') ? 'secp256k1' : undefined,
  25421. p256: knownCurves.includes('prime256v1') ? 'prime256v1' : undefined,
  25422. p384: knownCurves.includes('secp384r1') ? 'secp384r1' : undefined,
  25423. p521: knownCurves.includes('secp521r1') ? 'secp521r1' : undefined,
  25424. ed25519: knownCurves.includes('ED25519') ? 'ED25519' : undefined,
  25425. curve25519: knownCurves.includes('X25519') ? 'X25519' : undefined,
  25426. brainpoolP256r1: knownCurves.includes('brainpoolP256r1') ? 'brainpoolP256r1' : undefined,
  25427. brainpoolP384r1: knownCurves.includes('brainpoolP384r1') ? 'brainpoolP384r1' : undefined,
  25428. brainpoolP512r1: knownCurves.includes('brainpoolP512r1') ? 'brainpoolP512r1' : undefined
  25429. } : {};
  25430. const curves = {
  25431. p256: {
  25432. oid: [0x06, 0x08, 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07],
  25433. keyType: _enums2.default.publicKey.ecdsa,
  25434. hash: _enums2.default.hash.sha256,
  25435. cipher: _enums2.default.symmetric.aes128,
  25436. node: nodeCurves.p256,
  25437. web: webCurves.p256,
  25438. payloadSize: 32,
  25439. sharedSize: 256
  25440. },
  25441. p384: {
  25442. oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x22],
  25443. keyType: _enums2.default.publicKey.ecdsa,
  25444. hash: _enums2.default.hash.sha384,
  25445. cipher: _enums2.default.symmetric.aes192,
  25446. node: nodeCurves.p384,
  25447. web: webCurves.p384,
  25448. payloadSize: 48,
  25449. sharedSize: 384
  25450. },
  25451. p521: {
  25452. oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x23],
  25453. keyType: _enums2.default.publicKey.ecdsa,
  25454. hash: _enums2.default.hash.sha512,
  25455. cipher: _enums2.default.symmetric.aes256,
  25456. node: nodeCurves.p521,
  25457. web: webCurves.p521,
  25458. payloadSize: 66,
  25459. sharedSize: 528
  25460. },
  25461. secp256k1: {
  25462. oid: [0x06, 0x05, 0x2B, 0x81, 0x04, 0x00, 0x0A],
  25463. keyType: _enums2.default.publicKey.ecdsa,
  25464. hash: _enums2.default.hash.sha256,
  25465. cipher: _enums2.default.symmetric.aes128,
  25466. node: nodeCurves.secp256k1,
  25467. payloadSize: 32
  25468. },
  25469. ed25519: {
  25470. oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01],
  25471. keyType: _enums2.default.publicKey.eddsa,
  25472. hash: _enums2.default.hash.sha512,
  25473. node: false, // nodeCurves.ed25519 TODO
  25474. payloadSize: 32
  25475. },
  25476. curve25519: {
  25477. oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01],
  25478. keyType: _enums2.default.publicKey.ecdsa,
  25479. hash: _enums2.default.hash.sha256,
  25480. cipher: _enums2.default.symmetric.aes128,
  25481. node: false, // nodeCurves.curve25519 TODO
  25482. payloadSize: 32
  25483. },
  25484. brainpoolP256r1: {
  25485. oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07],
  25486. keyType: _enums2.default.publicKey.ecdsa,
  25487. hash: _enums2.default.hash.sha256,
  25488. cipher: _enums2.default.symmetric.aes128,
  25489. node: nodeCurves.brainpoolP256r1,
  25490. payloadSize: 32
  25491. },
  25492. brainpoolP384r1: {
  25493. oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B],
  25494. keyType: _enums2.default.publicKey.ecdsa,
  25495. hash: _enums2.default.hash.sha384,
  25496. cipher: _enums2.default.symmetric.aes192,
  25497. node: nodeCurves.brainpoolP384r1,
  25498. payloadSize: 48
  25499. },
  25500. brainpoolP512r1: {
  25501. oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D],
  25502. keyType: _enums2.default.publicKey.ecdsa,
  25503. hash: _enums2.default.hash.sha512,
  25504. cipher: _enums2.default.symmetric.aes256,
  25505. node: nodeCurves.brainpoolP512r1,
  25506. payloadSize: 64
  25507. }
  25508. };
  25509. /**
  25510. * @constructor
  25511. */
  25512. function Curve(oid_or_name, params) {
  25513. try {
  25514. if (_util2.default.isArray(oid_or_name) || _util2.default.isUint8Array(oid_or_name)) {
  25515. // by oid byte array
  25516. oid_or_name = new _oid2.default(oid_or_name);
  25517. }
  25518. if (oid_or_name instanceof _oid2.default) {
  25519. // by curve OID
  25520. oid_or_name = oid_or_name.getName();
  25521. }
  25522. // by curve name or oid string
  25523. this.name = _enums2.default.write(_enums2.default.curve, oid_or_name);
  25524. } catch (err) {
  25525. throw new Error('Not valid curve');
  25526. }
  25527. params = params || curves[this.name];
  25528. this.keyType = params.keyType;
  25529. this.oid = params.oid;
  25530. this.hash = params.hash;
  25531. this.cipher = params.cipher;
  25532. this.node = params.node && curves[this.name];
  25533. this.web = params.web && curves[this.name];
  25534. this.payloadSize = params.payloadSize;
  25535. if (this.web && _util2.default.getWebCrypto()) {
  25536. this.type = 'web';
  25537. } else if (this.node && _util2.default.getNodeCrypto()) {
  25538. this.type = 'node';
  25539. } else if (this.name === 'curve25519') {
  25540. this.type = 'curve25519';
  25541. } else if (this.name === 'ed25519') {
  25542. this.type = 'ed25519';
  25543. }
  25544. }
  25545. Curve.prototype.genKeyPair = async function () {
  25546. let keyPair;
  25547. switch (this.type) {
  25548. case 'web':
  25549. try {
  25550. return await webGenKeyPair(this.name);
  25551. } catch (err) {
  25552. _util2.default.print_debug_error("Browser did not support generating ec key " + err.message);
  25553. break;
  25554. }
  25555. case 'node':
  25556. return nodeGenKeyPair(this.name);
  25557. case 'curve25519':
  25558. {
  25559. const privateKey = await _random2.default.getRandomBytes(32);
  25560. privateKey[0] = privateKey[0] & 127 | 64;
  25561. privateKey[31] &= 248;
  25562. const secretKey = privateKey.slice().reverse();
  25563. keyPair = _naclFastLight2.default.box.keyPair.fromSecretKey(secretKey);
  25564. const publicKey = _util2.default.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]);
  25565. return { publicKey, privateKey };
  25566. }
  25567. case 'ed25519':
  25568. {
  25569. const privateKey = await _random2.default.getRandomBytes(32);
  25570. const keyPair = _naclFastLight2.default.sign.keyPair.fromSeed(privateKey);
  25571. const publicKey = _util2.default.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]);
  25572. return { publicKey, privateKey };
  25573. }
  25574. }
  25575. const indutnyCurve = await (0, _indutnyKey.getIndutnyCurve)(this.name);
  25576. keyPair = await indutnyCurve.genKeyPair({
  25577. entropy: _util2.default.Uint8Array_to_str((await _random2.default.getRandomBytes(32)))
  25578. });
  25579. return { publicKey: new Uint8Array(keyPair.getPublic('array', false)), privateKey: keyPair.getPrivate().toArrayLike(Uint8Array) };
  25580. };
  25581. async function generate(curve) {
  25582. curve = new Curve(curve);
  25583. const keyPair = await curve.genKeyPair();
  25584. return {
  25585. oid: curve.oid,
  25586. Q: new _bn2.default(keyPair.publicKey),
  25587. d: new _bn2.default(keyPair.privateKey),
  25588. hash: curve.hash,
  25589. cipher: curve.cipher
  25590. };
  25591. }
  25592. function getPreferredHashAlgo(oid) {
  25593. return curves[_enums2.default.write(_enums2.default.curve, oid.toHex())].hash;
  25594. }
  25595. exports.default = Curve;
  25596. exports.curves = curves;
  25597. exports.webCurves = webCurves;
  25598. exports.nodeCurves = nodeCurves;
  25599. exports.generate = generate;
  25600. exports.getPreferredHashAlgo = getPreferredHashAlgo;
  25601. exports.jwkToRawPublic = jwkToRawPublic;
  25602. exports.rawPublicToJwk = rawPublicToJwk;
  25603. exports.privateToJwk = privateToJwk;
  25604. //////////////////////////
  25605. // //
  25606. // Helper functions //
  25607. // //
  25608. //////////////////////////
  25609. async function webGenKeyPair(name) {
  25610. // Note: keys generated with ECDSA and ECDH are structurally equivalent
  25611. const webCryptoKey = await webCrypto.generateKey({ name: "ECDSA", namedCurve: webCurves[name] }, true, ["sign", "verify"]);
  25612. const privateKey = await webCrypto.exportKey("jwk", webCryptoKey.privateKey);
  25613. const publicKey = await webCrypto.exportKey("jwk", webCryptoKey.publicKey);
  25614. return {
  25615. publicKey: jwkToRawPublic(publicKey),
  25616. privateKey: _util2.default.b64_to_Uint8Array(privateKey.d, true)
  25617. };
  25618. }
  25619. async function nodeGenKeyPair(name) {
  25620. // Note: ECDSA and ECDH key generation is structurally equivalent
  25621. const ecdh = nodeCrypto.createECDH(nodeCurves[name]);
  25622. await ecdh.generateKeys();
  25623. return {
  25624. publicKey: new Uint8Array(ecdh.getPublicKey()),
  25625. privateKey: new Uint8Array(ecdh.getPrivateKey())
  25626. };
  25627. }
  25628. //////////////////////////
  25629. // //
  25630. // Helper functions //
  25631. // //
  25632. //////////////////////////
  25633. /**
  25634. * @param {JsonWebKey} jwk key for conversion
  25635. *
  25636. * @returns {Uint8Array} raw public key
  25637. */
  25638. function jwkToRawPublic(jwk) {
  25639. const bufX = _util2.default.b64_to_Uint8Array(jwk.x);
  25640. const bufY = _util2.default.b64_to_Uint8Array(jwk.y);
  25641. const publicKey = new Uint8Array(bufX.length + bufY.length + 1);
  25642. publicKey[0] = 0x04;
  25643. publicKey.set(bufX, 1);
  25644. publicKey.set(bufY, bufX.length + 1);
  25645. return publicKey;
  25646. }
  25647. /**
  25648. * @param {Integer} payloadSize ec payload size
  25649. * @param {String} name curve name
  25650. * @param {Uint8Array} publicKey public key
  25651. *
  25652. * @returns {JsonWebKey} public key in jwk format
  25653. */
  25654. function rawPublicToJwk(payloadSize, name, publicKey) {
  25655. const len = payloadSize;
  25656. const bufX = publicKey.slice(1, len + 1);
  25657. const bufY = publicKey.slice(len + 1, len * 2 + 1);
  25658. // https://www.rfc-editor.org/rfc/rfc7518.txt
  25659. const jwk = {
  25660. kty: "EC",
  25661. crv: name,
  25662. x: _util2.default.Uint8Array_to_b64(bufX, true),
  25663. y: _util2.default.Uint8Array_to_b64(bufY, true),
  25664. ext: true
  25665. };
  25666. return jwk;
  25667. }
  25668. /**
  25669. * @param {Integer} payloadSize ec payload size
  25670. * @param {String} name curve name
  25671. * @param {Uint8Array} publicKey public key
  25672. * @param {Uint8Array} privateKey private key
  25673. *
  25674. * @returns {JsonWebKey} private key in jwk format
  25675. */
  25676. function privateToJwk(payloadSize, name, publicKey, privateKey) {
  25677. const jwk = rawPublicToJwk(payloadSize, name, publicKey);
  25678. jwk.d = _util2.default.Uint8Array_to_b64(privateKey, true);
  25679. return jwk;
  25680. }
  25681. },{"../../../enums":113,"../../../type/oid":156,"../../../util":158,"../../random":109,"./indutnyKey":105,"bn.js":16,"tweetnacl/nacl-fast-light.js":72}],101:[function(require,module,exports){
  25682. 'use strict';
  25683. Object.defineProperty(exports, "__esModule", {
  25684. value: true
  25685. });
  25686. var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); // OpenPGP.js - An OpenPGP implementation in javascript
  25687. // Copyright (C) 2015-2016 Decentral
  25688. //
  25689. // This library is free software; you can redistribute it and/or
  25690. // modify it under the terms of the GNU Lesser General Public
  25691. // License as published by the Free Software Foundation; either
  25692. // version 3.0 of the License, or (at your option) any later version.
  25693. //
  25694. // This library is distributed in the hope that it will be useful,
  25695. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  25696. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  25697. // Lesser General Public License for more details.
  25698. //
  25699. // You should have received a copy of the GNU Lesser General Public
  25700. // License along with this library; if not, write to the Free Software
  25701. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  25702. /**
  25703. * @fileoverview Key encryption and decryption for RFC 6637 ECDH
  25704. * @requires bn.js
  25705. * @requires tweetnacl
  25706. * @requires crypto/public_key/elliptic/curve
  25707. * @requires crypto/aes_kw
  25708. * @requires crypto/cipher
  25709. * @requires crypto/random
  25710. * @requires crypto/hash
  25711. * @requires type/kdf_params
  25712. * @requires enums
  25713. * @requires util
  25714. * @module crypto/public_key/elliptic/ecdh
  25715. */
  25716. var _bn = require('bn.js');
  25717. var _bn2 = _interopRequireDefault(_bn);
  25718. var _naclFastLight = require('tweetnacl/nacl-fast-light.js');
  25719. var _naclFastLight2 = _interopRequireDefault(_naclFastLight);
  25720. var _curves = require('./curves');
  25721. var _curves2 = _interopRequireDefault(_curves);
  25722. var _aes_kw = require('../../aes_kw');
  25723. var _aes_kw2 = _interopRequireDefault(_aes_kw);
  25724. var _cipher = require('../../cipher');
  25725. var _cipher2 = _interopRequireDefault(_cipher);
  25726. var _random = require('../../random');
  25727. var _random2 = _interopRequireDefault(_random);
  25728. var _hash = require('../../hash');
  25729. var _hash2 = _interopRequireDefault(_hash);
  25730. var _kdf_params = require('../../../type/kdf_params');
  25731. var _kdf_params2 = _interopRequireDefault(_kdf_params);
  25732. var _enums = require('../../../enums');
  25733. var _enums2 = _interopRequireDefault(_enums);
  25734. var _util = require('../../../util');
  25735. var _util2 = _interopRequireDefault(_util);
  25736. var _indutnyKey = require('./indutnyKey');
  25737. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  25738. const webCrypto = _util2.default.getWebCrypto();
  25739. const nodeCrypto = _util2.default.getNodeCrypto();
  25740. // Build Param for ECDH algorithm (RFC 6637)
  25741. function buildEcdhParam(public_algo, oid, cipher_algo, hash_algo, fingerprint) {
  25742. const kdf_params = new _kdf_params2.default([hash_algo, cipher_algo]);
  25743. return _util2.default.concatUint8Array([oid.write(), new Uint8Array([public_algo]), kdf_params.write(), _util2.default.str_to_Uint8Array("Anonymous Sender "), fingerprint.subarray(0, 20)]);
  25744. }
  25745. // Key Derivation Function (RFC 6637)
  25746. async function kdf(hash_algo, X, length, param, stripLeading = false, stripTrailing = false) {
  25747. // Note: X is little endian for Curve25519, big-endian for all others.
  25748. // This is not ideal, but the RFC's are unclear
  25749. // https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-02#appendix-B
  25750. let i;
  25751. if (stripLeading) {
  25752. // Work around old go crypto bug
  25753. for (i = 0; i < X.length && X[i] === 0; i++);
  25754. X = X.subarray(i);
  25755. }
  25756. if (stripTrailing) {
  25757. // Work around old OpenPGP.js bug
  25758. for (i = X.length - 1; i >= 0 && X[i] === 0; i--);
  25759. X = X.subarray(0, i + 1);
  25760. }
  25761. const digest = await _hash2.default.digest(hash_algo, _util2.default.concatUint8Array([new Uint8Array([0, 0, 0, 1]), X, param]));
  25762. return digest.subarray(0, length);
  25763. }
  25764. /**
  25765. * Generate ECDHE ephemeral key and secret from public key
  25766. *
  25767. * @param {Curve} curve Elliptic curve object
  25768. * @param {Uint8Array} Q Recipient public key
  25769. * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}
  25770. * @async
  25771. */
  25772. async function genPublicEphemeralKey(curve, Q) {
  25773. switch (curve.type) {
  25774. case 'curve25519':
  25775. {
  25776. const d = await _random2.default.getRandomBytes(32);
  25777. var _ref = await genPrivateEphemeralKey(curve, Q, null, d);
  25778. const secretKey = _ref.secretKey,
  25779. sharedKey = _ref.sharedKey;
  25780. var _nacl$box$keyPair$fro = _naclFastLight2.default.box.keyPair.fromSecretKey(secretKey);
  25781. let publicKey = _nacl$box$keyPair$fro.publicKey;
  25782. publicKey = _util2.default.concatUint8Array([new Uint8Array([0x40]), publicKey]);
  25783. return { publicKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below
  25784. }
  25785. case 'web':
  25786. if (curve.web && _util2.default.getWebCrypto()) {
  25787. try {
  25788. return await webPublicEphemeralKey(curve, Q);
  25789. } catch (err) {
  25790. _util2.default.print_debug_error(err);
  25791. }
  25792. }
  25793. break;
  25794. case 'node':
  25795. return nodePublicEphemeralKey(curve, Q);
  25796. }
  25797. return ellipticPublicEphemeralKey(curve, Q);
  25798. }
  25799. /**
  25800. * Encrypt and wrap a session key
  25801. *
  25802. * @param {module:type/oid} oid Elliptic curve object identifier
  25803. * @param {module:enums.symmetric} cipher_algo Symmetric cipher to use
  25804. * @param {module:enums.hash} hash_algo Hash algorithm to use
  25805. * @param {module:type/mpi} m Value derived from session key (RFC 6637)
  25806. * @param {Uint8Array} Q Recipient public key
  25807. * @param {String} fingerprint Recipient fingerprint
  25808. * @returns {Promise<{publicKey: Uint8Array, wrappedKey: Uint8Array}>}
  25809. * @async
  25810. */
  25811. async function encrypt(oid, cipher_algo, hash_algo, m, Q, fingerprint) {
  25812. const curve = new _curves2.default(oid);
  25813. var _ref2 = await genPublicEphemeralKey(curve, Q);
  25814. const publicKey = _ref2.publicKey,
  25815. sharedKey = _ref2.sharedKey;
  25816. const param = buildEcdhParam(_enums2.default.publicKey.ecdh, oid, cipher_algo, hash_algo, fingerprint);
  25817. cipher_algo = _enums2.default.read(_enums2.default.symmetric, cipher_algo);
  25818. const Z = await kdf(hash_algo, sharedKey, _cipher2.default[cipher_algo].keySize, param);
  25819. const wrappedKey = _aes_kw2.default.wrap(Z, m.toString());
  25820. return { publicKey, wrappedKey };
  25821. }
  25822. /**
  25823. * Generate ECDHE secret from private key and public part of ephemeral key
  25824. *
  25825. * @param {Curve} curve Elliptic curve object
  25826. * @param {Uint8Array} V Public part of ephemeral key
  25827. * @param {Uint8Array} Q Recipient public key
  25828. * @param {Uint8Array} d Recipient private key
  25829. * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}
  25830. * @async
  25831. */
  25832. async function genPrivateEphemeralKey(curve, V, Q, d) {
  25833. if (d.length !== curve.payloadSize) {
  25834. const privateKey = new Uint8Array(curve.payloadSize);
  25835. privateKey.set(d, curve.payloadSize - d.length);
  25836. d = privateKey;
  25837. }
  25838. switch (curve.type) {
  25839. case 'curve25519':
  25840. {
  25841. const secretKey = d.slice().reverse();
  25842. const sharedKey = _naclFastLight2.default.scalarMult(secretKey, V.subarray(1));
  25843. return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below
  25844. }
  25845. case 'web':
  25846. if (curve.web && _util2.default.getWebCrypto()) {
  25847. try {
  25848. return await webPrivateEphemeralKey(curve, V, Q, d);
  25849. } catch (err) {
  25850. _util2.default.print_debug_error(err);
  25851. }
  25852. }
  25853. break;
  25854. case 'node':
  25855. return nodePrivateEphemeralKey(curve, V, d);
  25856. }
  25857. return ellipticPrivateEphemeralKey(curve, V, d);
  25858. }
  25859. /**
  25860. * Decrypt and unwrap the value derived from session key
  25861. *
  25862. * @param {module:type/oid} oid Elliptic curve object identifier
  25863. * @param {module:enums.symmetric} cipher_algo Symmetric cipher to use
  25864. * @param {module:enums.hash} hash_algo Hash algorithm to use
  25865. * @param {Uint8Array} V Public part of ephemeral key
  25866. * @param {Uint8Array} C Encrypted and wrapped value derived from session key
  25867. * @param {Uint8Array} Q Recipient public key
  25868. * @param {Uint8Array} d Recipient private key
  25869. * @param {String} fingerprint Recipient fingerprint
  25870. * @returns {Promise<BN>} Value derived from session key
  25871. * @async
  25872. */
  25873. async function decrypt(oid, cipher_algo, hash_algo, V, C, Q, d, fingerprint) {
  25874. const curve = new _curves2.default(oid);
  25875. var _ref3 = await genPrivateEphemeralKey(curve, V, Q, d);
  25876. const sharedKey = _ref3.sharedKey;
  25877. const param = buildEcdhParam(_enums2.default.publicKey.ecdh, oid, cipher_algo, hash_algo, fingerprint);
  25878. cipher_algo = _enums2.default.read(_enums2.default.symmetric, cipher_algo);
  25879. let err;
  25880. for (let i = 0; i < 3; i++) {
  25881. try {
  25882. // Work around old go crypto bug and old OpenPGP.js bug, respectively.
  25883. const Z = await kdf(hash_algo, sharedKey, _cipher2.default[cipher_algo].keySize, param, i === 1, i === 2);
  25884. return new _bn2.default(_aes_kw2.default.unwrap(Z, C));
  25885. } catch (e) {
  25886. err = e;
  25887. }
  25888. }
  25889. throw err;
  25890. }
  25891. /**
  25892. * Generate ECDHE secret from private key and public part of ephemeral key using webCrypto
  25893. *
  25894. * @param {Curve} curve Elliptic curve object
  25895. * @param {Uint8Array} V Public part of ephemeral key
  25896. * @param {Uint8Array} Q Recipient public key
  25897. * @param {Uint8Array} d Recipient private key
  25898. * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}
  25899. * @async
  25900. */
  25901. async function webPrivateEphemeralKey(curve, V, Q, d) {
  25902. const recipient = (0, _curves.privateToJwk)(curve.payloadSize, curve.web.web, Q, d);
  25903. let privateKey = webCrypto.importKey("jwk", recipient, {
  25904. name: "ECDH",
  25905. namedCurve: curve.web.web
  25906. }, true, ["deriveKey", "deriveBits"]);
  25907. const jwk = (0, _curves.rawPublicToJwk)(curve.payloadSize, curve.web.web, V);
  25908. let sender = webCrypto.importKey("jwk", jwk, {
  25909. name: "ECDH",
  25910. namedCurve: curve.web.web
  25911. }, true, []);
  25912. var _ref4 = await Promise.all([privateKey, sender]);
  25913. var _ref5 = _slicedToArray(_ref4, 2);
  25914. privateKey = _ref5[0];
  25915. sender = _ref5[1];
  25916. let S = webCrypto.deriveBits({
  25917. name: "ECDH",
  25918. namedCurve: curve.web.web,
  25919. public: sender
  25920. }, privateKey, curve.web.sharedSize);
  25921. let secret = webCrypto.exportKey("jwk", privateKey);
  25922. var _ref6 = await Promise.all([S, secret]);
  25923. var _ref7 = _slicedToArray(_ref6, 2);
  25924. S = _ref7[0];
  25925. secret = _ref7[1];
  25926. const sharedKey = new Uint8Array(S);
  25927. const secretKey = _util2.default.b64_to_Uint8Array(secret.d, true);
  25928. return { secretKey, sharedKey };
  25929. }
  25930. /**
  25931. * Generate ECDHE ephemeral key and secret from public key using webCrypto
  25932. *
  25933. * @param {Curve} curve Elliptic curve object
  25934. * @param {Uint8Array} Q Recipient public key
  25935. * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}
  25936. * @async
  25937. */
  25938. async function webPublicEphemeralKey(curve, Q) {
  25939. const jwk = (0, _curves.rawPublicToJwk)(curve.payloadSize, curve.web.web, Q);
  25940. let keyPair = webCrypto.generateKey({
  25941. name: "ECDH",
  25942. namedCurve: curve.web.web
  25943. }, true, ["deriveKey", "deriveBits"]);
  25944. let recipient = webCrypto.importKey("jwk", jwk, {
  25945. name: "ECDH",
  25946. namedCurve: curve.web.web
  25947. }, false, []);
  25948. var _ref8 = await Promise.all([keyPair, recipient]);
  25949. var _ref9 = _slicedToArray(_ref8, 2);
  25950. keyPair = _ref9[0];
  25951. recipient = _ref9[1];
  25952. let s = webCrypto.deriveBits({
  25953. name: "ECDH",
  25954. namedCurve: curve.web.web,
  25955. public: recipient
  25956. }, keyPair.privateKey, curve.web.sharedSize);
  25957. let p = webCrypto.exportKey("jwk", keyPair.publicKey);
  25958. var _ref10 = await Promise.all([s, p]);
  25959. var _ref11 = _slicedToArray(_ref10, 2);
  25960. s = _ref11[0];
  25961. p = _ref11[1];
  25962. const sharedKey = new Uint8Array(s);
  25963. const publicKey = new Uint8Array((0, _curves.jwkToRawPublic)(p));
  25964. return { publicKey, sharedKey };
  25965. }
  25966. /**
  25967. * Generate ECDHE secret from private key and public part of ephemeral key using indutny/elliptic
  25968. *
  25969. * @param {Curve} curve Elliptic curve object
  25970. * @param {Uint8Array} V Public part of ephemeral key
  25971. * @param {Uint8Array} d Recipient private key
  25972. * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}
  25973. * @async
  25974. */
  25975. async function ellipticPrivateEphemeralKey(curve, V, d) {
  25976. const indutnyCurve = await (0, _indutnyKey.getIndutnyCurve)(curve.name);
  25977. V = (0, _indutnyKey.keyFromPublic)(indutnyCurve, V);
  25978. d = (0, _indutnyKey.keyFromPrivate)(indutnyCurve, d);
  25979. const secretKey = new Uint8Array(d.getPrivate());
  25980. const S = d.derive(V.getPublic());
  25981. const len = indutnyCurve.curve.p.byteLength();
  25982. const sharedKey = S.toArrayLike(Uint8Array, 'be', len);
  25983. return { secretKey, sharedKey };
  25984. }
  25985. /**
  25986. * Generate ECDHE ephemeral key and secret from public key using indutny/elliptic
  25987. *
  25988. * @param {Curve} curve Elliptic curve object
  25989. * @param {Uint8Array} Q Recipient public key
  25990. * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}
  25991. * @async
  25992. */
  25993. async function ellipticPublicEphemeralKey(curve, Q) {
  25994. const indutnyCurve = await (0, _indutnyKey.getIndutnyCurve)(curve.name);
  25995. const v = await curve.genKeyPair();
  25996. Q = (0, _indutnyKey.keyFromPublic)(indutnyCurve, Q);
  25997. const V = (0, _indutnyKey.keyFromPrivate)(indutnyCurve, v.privateKey);
  25998. const publicKey = v.publicKey;
  25999. const S = V.derive(Q.getPublic());
  26000. const len = indutnyCurve.curve.p.byteLength();
  26001. const sharedKey = S.toArrayLike(Uint8Array, 'be', len);
  26002. return { publicKey, sharedKey };
  26003. }
  26004. /**
  26005. * Generate ECDHE secret from private key and public part of ephemeral key using nodeCrypto
  26006. *
  26007. * @param {Curve} curve Elliptic curve object
  26008. * @param {Uint8Array} V Public part of ephemeral key
  26009. * @param {Uint8Array} d Recipient private key
  26010. * @returns {Promise<{secretKey: Uint8Array, sharedKey: Uint8Array}>}
  26011. * @async
  26012. */
  26013. async function nodePrivateEphemeralKey(curve, V, d) {
  26014. const recipient = nodeCrypto.createECDH(curve.node.node);
  26015. recipient.setPrivateKey(d);
  26016. const sharedKey = new Uint8Array(recipient.computeSecret(V));
  26017. const secretKey = new Uint8Array(recipient.getPrivateKey());
  26018. return { secretKey, sharedKey };
  26019. }
  26020. /**
  26021. * Generate ECDHE ephemeral key and secret from public key using nodeCrypto
  26022. *
  26023. * @param {Curve} curve Elliptic curve object
  26024. * @param {Uint8Array} Q Recipient public key
  26025. * @returns {Promise<{publicKey: Uint8Array, sharedKey: Uint8Array}>}
  26026. * @async
  26027. */
  26028. async function nodePublicEphemeralKey(curve, Q) {
  26029. const sender = nodeCrypto.createECDH(curve.node.node);
  26030. sender.generateKeys();
  26031. const sharedKey = new Uint8Array(sender.computeSecret(Q));
  26032. const publicKey = new Uint8Array(sender.getPublicKey());
  26033. return { publicKey, sharedKey };
  26034. }
  26035. exports.default = { encrypt, decrypt, genPublicEphemeralKey, genPrivateEphemeralKey, buildEcdhParam, kdf, webPublicEphemeralKey, webPrivateEphemeralKey, ellipticPublicEphemeralKey, ellipticPrivateEphemeralKey, nodePublicEphemeralKey, nodePrivateEphemeralKey };
  26036. },{"../../../enums":113,"../../../type/kdf_params":153,"../../../util":158,"../../aes_kw":80,"../../cipher":86,"../../hash":92,"../../random":109,"./curves":100,"./indutnyKey":105,"bn.js":16,"tweetnacl/nacl-fast-light.js":72}],102:[function(require,module,exports){
  26037. 'use strict';
  26038. Object.defineProperty(exports, "__esModule", {
  26039. value: true
  26040. });
  26041. var _bn = require('bn.js');
  26042. var _bn2 = _interopRequireDefault(_bn);
  26043. var _enums = require('../../../enums');
  26044. var _enums2 = _interopRequireDefault(_enums);
  26045. var _util = require('../../../util');
  26046. var _util2 = _interopRequireDefault(_util);
  26047. var _curves = require('./curves');
  26048. var _curves2 = _interopRequireDefault(_curves);
  26049. var _indutnyKey = require('./indutnyKey');
  26050. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  26051. const webCrypto = _util2.default.getWebCrypto(); // OpenPGP.js - An OpenPGP implementation in javascript
  26052. // Copyright (C) 2015-2016 Decentral
  26053. //
  26054. // This library is free software; you can redistribute it and/or
  26055. // modify it under the terms of the GNU Lesser General Public
  26056. // License as published by the Free Software Foundation; either
  26057. // version 3.0 of the License, or (at your option) any later version.
  26058. //
  26059. // This library is distributed in the hope that it will be useful,
  26060. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  26061. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  26062. // Lesser General Public License for more details.
  26063. //
  26064. // You should have received a copy of the GNU Lesser General Public
  26065. // License along with this library; if not, write to the Free Software
  26066. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  26067. /**
  26068. * @fileoverview Implementation of ECDSA following RFC6637 for Openpgpjs
  26069. * @requires bn.js
  26070. * @requires web-stream-tools
  26071. * @requires enums
  26072. * @requires util
  26073. * @requires crypto/public_key/elliptic/curves
  26074. * @module crypto/public_key/elliptic/ecdsa
  26075. */
  26076. const nodeCrypto = _util2.default.getNodeCrypto();
  26077. /**
  26078. * Sign a message using the provided key
  26079. * @param {module:type/oid} oid Elliptic curve object identifier
  26080. * @param {module:enums.hash} hash_algo Hash algorithm used to sign
  26081. * @param {Uint8Array} message Message to sign
  26082. * @param {Uint8Array} publicKey Public key
  26083. * @param {Uint8Array} privateKey Private key used to sign the message
  26084. * @param {Uint8Array} hashed The hashed message
  26085. * @returns {{r: Uint8Array,
  26086. * s: Uint8Array}} Signature of the message
  26087. * @async
  26088. */
  26089. async function sign(oid, hash_algo, message, publicKey, privateKey, hashed) {
  26090. const curve = new _curves2.default(oid);
  26091. if (message && !_util2.default.isStream(message)) {
  26092. const keyPair = { publicKey, privateKey };
  26093. switch (curve.type) {
  26094. case 'web':
  26095. {
  26096. // If browser doesn't support a curve, we'll catch it
  26097. try {
  26098. // Need to await to make sure browser succeeds
  26099. return await webSign(curve, hash_algo, message, keyPair);
  26100. } catch (err) {
  26101. _util2.default.print_debug_error("Browser did not support signing: " + err.message);
  26102. }
  26103. break;
  26104. }
  26105. case 'node':
  26106. {
  26107. const signature = await nodeSign(curve, hash_algo, message, keyPair);
  26108. return {
  26109. r: signature.r.toArrayLike(Uint8Array),
  26110. s: signature.s.toArrayLike(Uint8Array)
  26111. };
  26112. }
  26113. }
  26114. }
  26115. return ellipticSign(curve, hashed, privateKey);
  26116. }
  26117. /**
  26118. * Verifies if a signature is valid for a message
  26119. * @param {module:type/oid} oid Elliptic curve object identifier
  26120. * @param {module:enums.hash} hash_algo Hash algorithm used in the signature
  26121. * @param {{r: Uint8Array,
  26122. s: Uint8Array}} signature Signature to verify
  26123. * @param {Uint8Array} message Message to verify
  26124. * @param {Uint8Array} publicKey Public key used to verify the message
  26125. * @param {Uint8Array} hashed The hashed message
  26126. * @returns {Boolean}
  26127. * @async
  26128. */
  26129. async function verify(oid, hash_algo, signature, message, publicKey, hashed) {
  26130. const curve = new _curves2.default(oid);
  26131. if (message && !_util2.default.isStream(message)) {
  26132. switch (curve.type) {
  26133. case 'web':
  26134. try {
  26135. // Need to await to make sure browser succeeds
  26136. return await webVerify(curve, hash_algo, signature, message, publicKey);
  26137. } catch (err) {
  26138. _util2.default.print_debug_error("Browser did not support verifying: " + err.message);
  26139. }
  26140. break;
  26141. case 'node':
  26142. return nodeVerify(curve, hash_algo, signature, message, publicKey);
  26143. }
  26144. }
  26145. const digest = typeof hash_algo === 'undefined' ? message : hashed;
  26146. return ellipticVerify(curve, signature, digest, publicKey);
  26147. }
  26148. exports.default = { sign, verify, ellipticVerify, ellipticSign };
  26149. //////////////////////////
  26150. // //
  26151. // Helper functions //
  26152. // //
  26153. //////////////////////////
  26154. async function ellipticSign(curve, hashed, privateKey) {
  26155. const indutnyCurve = await (0, _indutnyKey.getIndutnyCurve)(curve.name);
  26156. const key = (0, _indutnyKey.keyFromPrivate)(indutnyCurve, privateKey);
  26157. const signature = key.sign(hashed);
  26158. return {
  26159. r: signature.r.toArrayLike(Uint8Array),
  26160. s: signature.s.toArrayLike(Uint8Array)
  26161. };
  26162. }
  26163. async function ellipticVerify(curve, signature, digest, publicKey) {
  26164. const indutnyCurve = await (0, _indutnyKey.getIndutnyCurve)(curve.name);
  26165. const key = (0, _indutnyKey.keyFromPublic)(indutnyCurve, publicKey);
  26166. return key.verify(digest, signature);
  26167. }
  26168. async function webSign(curve, hash_algo, message, keyPair) {
  26169. const len = curve.payloadSize;
  26170. const jwk = (0, _curves.privateToJwk)(curve.payloadSize, _curves.webCurves[curve.name], keyPair.publicKey, keyPair.privateKey);
  26171. const key = await webCrypto.importKey("jwk", jwk, {
  26172. "name": "ECDSA",
  26173. "namedCurve": _curves.webCurves[curve.name],
  26174. "hash": { name: _enums2.default.read(_enums2.default.webHash, curve.hash) }
  26175. }, false, ["sign"]);
  26176. const signature = new Uint8Array((await webCrypto.sign({
  26177. "name": 'ECDSA',
  26178. "namedCurve": _curves.webCurves[curve.name],
  26179. "hash": { name: _enums2.default.read(_enums2.default.webHash, hash_algo) }
  26180. }, key, message)));
  26181. return {
  26182. r: signature.slice(0, len),
  26183. s: signature.slice(len, len << 1)
  26184. };
  26185. }
  26186. async function webVerify(curve, hash_algo, { r, s }, message, publicKey) {
  26187. const len = curve.payloadSize;
  26188. const jwk = (0, _curves.rawPublicToJwk)(curve.payloadSize, _curves.webCurves[curve.name], publicKey);
  26189. const key = await webCrypto.importKey("jwk", jwk, {
  26190. "name": "ECDSA",
  26191. "namedCurve": _curves.webCurves[curve.name],
  26192. "hash": { name: _enums2.default.read(_enums2.default.webHash, curve.hash) }
  26193. }, false, ["verify"]);
  26194. const signature = _util2.default.concatUint8Array([new Uint8Array(len - r.length), r, new Uint8Array(len - s.length), s]).buffer;
  26195. return webCrypto.verify({
  26196. "name": 'ECDSA',
  26197. "namedCurve": _curves.webCurves[curve.name],
  26198. "hash": { name: _enums2.default.read(_enums2.default.webHash, hash_algo) }
  26199. }, key, signature, message);
  26200. }
  26201. async function nodeSign(curve, hash_algo, message, keyPair) {
  26202. const sign = nodeCrypto.createSign(_enums2.default.read(_enums2.default.hash, hash_algo));
  26203. sign.write(message);
  26204. sign.end();
  26205. const key = ECPrivateKey.encode({
  26206. version: 1,
  26207. parameters: curve.oid,
  26208. privateKey: Array.from(keyPair.privateKey),
  26209. publicKey: { unused: 0, data: Array.from(keyPair.publicKey) }
  26210. }, 'pem', {
  26211. label: 'EC PRIVATE KEY'
  26212. });
  26213. return ECDSASignature.decode(sign.sign(key), 'der');
  26214. }
  26215. async function nodeVerify(curve, hash_algo, { r, s }, message, publicKey) {
  26216. const verify = nodeCrypto.createVerify(_enums2.default.read(_enums2.default.hash, hash_algo));
  26217. verify.write(message);
  26218. verify.end();
  26219. const key = SubjectPublicKeyInfo.encode({
  26220. algorithm: {
  26221. algorithm: [1, 2, 840, 10045, 2, 1],
  26222. parameters: curve.oid
  26223. },
  26224. subjectPublicKey: { unused: 0, data: Array.from(publicKey) }
  26225. }, 'pem', {
  26226. label: 'PUBLIC KEY'
  26227. });
  26228. const signature = ECDSASignature.encode({
  26229. r: new _bn2.default(r), s: new _bn2.default(s)
  26230. }, 'der');
  26231. try {
  26232. return verify.verify(key, signature);
  26233. } catch (err) {
  26234. return false;
  26235. }
  26236. }
  26237. // Originally written by Owen Smith https://github.com/omsmith
  26238. // Adapted on Feb 2018 from https://github.com/Brightspace/node-jwk-to-pem/
  26239. /* eslint-disable no-invalid-this */
  26240. const asn1 = nodeCrypto ? require('asn1.js') : undefined;
  26241. const ECDSASignature = nodeCrypto ? asn1.define('ECDSASignature', function () {
  26242. this.seq().obj(this.key('r').int(), this.key('s').int());
  26243. }) : undefined;
  26244. const ECPrivateKey = nodeCrypto ? asn1.define('ECPrivateKey', function () {
  26245. this.seq().obj(this.key('version').int(), this.key('privateKey').octstr(), this.key('parameters').explicit(0).optional().any(), this.key('publicKey').explicit(1).optional().bitstr());
  26246. }) : undefined;
  26247. const AlgorithmIdentifier = nodeCrypto ? asn1.define('AlgorithmIdentifier', function () {
  26248. this.seq().obj(this.key('algorithm').objid(), this.key('parameters').optional().any());
  26249. }) : undefined;
  26250. const SubjectPublicKeyInfo = nodeCrypto ? asn1.define('SubjectPublicKeyInfo', function () {
  26251. this.seq().obj(this.key('algorithm').use(AlgorithmIdentifier), this.key('subjectPublicKey').bitstr());
  26252. }) : undefined;
  26253. },{"../../../enums":113,"../../../util":158,"./curves":100,"./indutnyKey":105,"asn1.js":"asn1.js","bn.js":16}],103:[function(require,module,exports){
  26254. 'use strict';
  26255. Object.defineProperty(exports, "__esModule", {
  26256. value: true
  26257. });
  26258. var _ = require('hash.js/lib/hash/sha/512');
  26259. var _2 = _interopRequireDefault(_);
  26260. var _naclFastLight = require('tweetnacl/nacl-fast-light.js');
  26261. var _naclFastLight2 = _interopRequireDefault(_naclFastLight);
  26262. var _util = require('../../../util');
  26263. var _util2 = _interopRequireDefault(_util);
  26264. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  26265. _naclFastLight2.default.hash = bytes => new Uint8Array((0, _2.default)().update(bytes).digest());
  26266. /**
  26267. * Sign a message using the provided key
  26268. * @param {module:type/oid} oid Elliptic curve object identifier
  26269. * @param {module:enums.hash} hash_algo Hash algorithm used to sign
  26270. * @param {Uint8Array} message Message to sign
  26271. * @param {Uint8Array} publicKey Public key
  26272. * @param {Uint8Array} privateKey Private key used to sign the message
  26273. * @param {Uint8Array} hashed The hashed message
  26274. * @returns {{R: Uint8Array,
  26275. * S: Uint8Array}} Signature of the message
  26276. * @async
  26277. */
  26278. // OpenPGP.js - An OpenPGP implementation in javascript
  26279. // Copyright (C) 2018 Proton Technologies AG
  26280. //
  26281. // This library is free software; you can redistribute it and/or
  26282. // modify it under the terms of the GNU Lesser General Public
  26283. // License as published by the Free Software Foundation; either
  26284. // version 3.0 of the License, or (at your option) any later version.
  26285. //
  26286. // This library is distributed in the hope that it will be useful,
  26287. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  26288. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  26289. // Lesser General Public License for more details.
  26290. //
  26291. // You should have received a copy of the GNU Lesser General Public
  26292. // License along with this library; if not, write to the Free Software
  26293. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  26294. /**
  26295. * @fileoverview Implementation of EdDSA following RFC4880bis-03 for OpenPGP
  26296. * @requires hash.js
  26297. * @requires tweetnacl
  26298. * @requires crypto/public_key/elliptic/curve
  26299. * @requires util
  26300. * @module crypto/public_key/elliptic/eddsa
  26301. */
  26302. async function sign(oid, hash_algo, message, publicKey, privateKey, hashed) {
  26303. const secretKey = _util2.default.concatUint8Array([privateKey, publicKey.subarray(1)]);
  26304. const signature = _naclFastLight2.default.sign.detached(hashed, secretKey);
  26305. // EdDSA signature params are returned in little-endian format
  26306. return {
  26307. R: signature.subarray(0, 32),
  26308. S: signature.subarray(32)
  26309. };
  26310. }
  26311. /**
  26312. * Verifies if a signature is valid for a message
  26313. * @param {module:type/oid} oid Elliptic curve object identifier
  26314. * @param {module:enums.hash} hash_algo Hash algorithm used in the signature
  26315. * @param {{R: Uint8Array,
  26316. S: Uint8Array}} signature Signature to verify the message
  26317. * @param {Uint8Array} m Message to verify
  26318. * @param {Uint8Array} publicKey Public key used to verify the message
  26319. * @param {Uint8Array} hashed The hashed message
  26320. * @returns {Boolean}
  26321. * @async
  26322. */
  26323. async function verify(oid, hash_algo, { R, S }, m, publicKey, hashed) {
  26324. const signature = _util2.default.concatUint8Array([R, S]);
  26325. return _naclFastLight2.default.sign.detached.verify(hashed, signature, publicKey.subarray(1));
  26326. }
  26327. exports.default = { sign, verify };
  26328. },{"../../../util":158,"hash.js/lib/hash/sha/512":43,"tweetnacl/nacl-fast-light.js":72}],104:[function(require,module,exports){
  26329. 'use strict';
  26330. Object.defineProperty(exports, "__esModule", {
  26331. value: true
  26332. });
  26333. var _curves = require('./curves');
  26334. var _curves2 = _interopRequireDefault(_curves);
  26335. var _ecdsa = require('./ecdsa');
  26336. var _ecdsa2 = _interopRequireDefault(_ecdsa);
  26337. var _eddsa = require('./eddsa');
  26338. var _eddsa2 = _interopRequireDefault(_eddsa);
  26339. var _ecdh = require('./ecdh');
  26340. var _ecdh2 = _interopRequireDefault(_ecdh);
  26341. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  26342. // OpenPGP.js - An OpenPGP implementation in javascript
  26343. // Copyright (C) 2015-2016 Decentral
  26344. //
  26345. // This library is free software; you can redistribute it and/or
  26346. // modify it under the terms of the GNU Lesser General Public
  26347. // License as published by the Free Software Foundation; either
  26348. // version 3.0 of the License, or (at your option) any later version.
  26349. //
  26350. // This library is distributed in the hope that it will be useful,
  26351. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  26352. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  26353. // Lesser General Public License for more details.
  26354. //
  26355. // You should have received a copy of the GNU Lesser General Public
  26356. // License along with this library; if not, write to the Free Software
  26357. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  26358. /**
  26359. * @fileoverview Functions to access Elliptic Curve Cryptography
  26360. * @see module:crypto/public_key/elliptic/curve
  26361. * @see module:crypto/public_key/elliptic/ecdh
  26362. * @see module:crypto/public_key/elliptic/ecdsa
  26363. * @see module:crypto/public_key/elliptic/eddsa
  26364. * @module crypto/public_key/elliptic
  26365. */
  26366. exports.default = {
  26367. Curve: _curves2.default, ecdh: _ecdh2.default, ecdsa: _ecdsa2.default, eddsa: _eddsa2.default, generate: _curves.generate, getPreferredHashAlgo: _curves.getPreferredHashAlgo
  26368. };
  26369. },{"./curves":100,"./ecdh":101,"./ecdsa":102,"./eddsa":103}],105:[function(require,module,exports){
  26370. 'use strict';
  26371. Object.defineProperty(exports, "__esModule", {
  26372. value: true
  26373. });
  26374. exports.keyFromPrivate = keyFromPrivate;
  26375. exports.keyFromPublic = keyFromPublic;
  26376. exports.getIndutnyCurve = getIndutnyCurve;
  26377. var _lightweight_helper = require('../../../lightweight_helper');
  26378. var _config = require('../../../config');
  26379. var _config2 = _interopRequireDefault(_config);
  26380. var _util = require('../../../util');
  26381. var _util2 = _interopRequireDefault(_util);
  26382. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  26383. function keyFromPrivate(indutnyCurve, priv) {
  26384. const keyPair = indutnyCurve.keyPair({ priv: priv });
  26385. return keyPair;
  26386. } // OpenPGP.js - An OpenPGP implementation in javascript
  26387. // Copyright (C) 2015-2016 Decentral
  26388. //
  26389. // This library is free software; you can redistribute it and/or
  26390. // modify it under the terms of the GNU Lesser General Public
  26391. // License as published by the Free Software Foundation; either
  26392. // version 3.0 of the License, or (at your option) any later version.
  26393. //
  26394. // This library is distributed in the hope that it will be useful,
  26395. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  26396. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  26397. // Lesser General Public License for more details.
  26398. //
  26399. // You should have received a copy of the GNU Lesser General Public
  26400. // License along with this library; if not, write to the Free Software
  26401. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  26402. /**
  26403. * @fileoverview Wrapper for a KeyPair of an curve from indutny/elliptic library
  26404. * @requires enums
  26405. * @requires asn1.js
  26406. * @module crypto/public_key/elliptic/indutnyKey
  26407. */
  26408. function keyFromPublic(indutnyCurve, pub) {
  26409. const keyPair = indutnyCurve.keyPair({ pub: pub });
  26410. if (keyPair.validate().result !== true) {
  26411. throw new Error('Invalid elliptic public key');
  26412. }
  26413. return keyPair;
  26414. }
  26415. /**
  26416. * Load elliptic on demand to the window.openpgp.elliptic
  26417. * @returns {Promise<elliptic>}
  26418. */
  26419. async function loadEllipticPromise() {
  26420. const path = _config2.default.indutny_elliptic_path;
  26421. const options = _config2.default.indutny_elliptic_fetch_options;
  26422. const ellipticDlPromise = (0, _lightweight_helper.dl)(path, options).catch(() => (0, _lightweight_helper.dl)(path, options));
  26423. const ellipticContents = await ellipticDlPromise;
  26424. const mainUrl = URL.createObjectURL(new Blob([ellipticContents], { type: 'text/javascript' }));
  26425. await (0, _lightweight_helper.loadScript)(mainUrl);
  26426. URL.revokeObjectURL(mainUrl);
  26427. if (!window.openpgp.elliptic) {
  26428. throw new Error('Elliptic library failed to load correctly');
  26429. }
  26430. return window.openpgp.elliptic;
  26431. }
  26432. let ellipticPromise;
  26433. function loadElliptic() {
  26434. if (!_config2.default.external_indutny_elliptic) {
  26435. return require('elliptic');
  26436. }
  26437. if (_util2.default.detectNode()) {
  26438. // eslint-disable-next-line
  26439. return require(_config2.default.indutny_elliptic_path);
  26440. }
  26441. if (!ellipticPromise) {
  26442. ellipticPromise = loadEllipticPromise().catch(e => {
  26443. ellipticPromise = undefined;
  26444. throw e;
  26445. });
  26446. }
  26447. return ellipticPromise;
  26448. }
  26449. async function getIndutnyCurve(name) {
  26450. if (!_config2.default.use_indutny_elliptic) {
  26451. throw new Error('This curve is only supported in the full build of OpenPGP.js');
  26452. }
  26453. const elliptic = await loadElliptic();
  26454. return new elliptic.ec(name);
  26455. }
  26456. },{"../../../config":79,"../../../lightweight_helper":125,"../../../util":158,"elliptic":18}],106:[function(require,module,exports){
  26457. 'use strict';
  26458. Object.defineProperty(exports, "__esModule", {
  26459. value: true
  26460. });
  26461. var _naclFastLight = require('tweetnacl/nacl-fast-light.js');
  26462. var _naclFastLight2 = _interopRequireDefault(_naclFastLight);
  26463. var _rsa = require('./rsa');
  26464. var _rsa2 = _interopRequireDefault(_rsa);
  26465. var _elgamal = require('./elgamal');
  26466. var _elgamal2 = _interopRequireDefault(_elgamal);
  26467. var _elliptic = require('./elliptic');
  26468. var _elliptic2 = _interopRequireDefault(_elliptic);
  26469. var _dsa = require('./dsa');
  26470. var _dsa2 = _interopRequireDefault(_dsa);
  26471. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  26472. exports.default = {
  26473. /** @see module:crypto/public_key/rsa */
  26474. rsa: _rsa2.default,
  26475. /** @see module:crypto/public_key/elgamal */
  26476. elgamal: _elgamal2.default,
  26477. /** @see module:crypto/public_key/elliptic */
  26478. elliptic: _elliptic2.default,
  26479. /** @see module:crypto/public_key/dsa */
  26480. dsa: _dsa2.default,
  26481. /** @see tweetnacl */
  26482. nacl: _naclFastLight2.default
  26483. }; /**
  26484. * @fileoverview Asymmetric cryptography functions
  26485. * @requires tweetnacl
  26486. * @requires crypto/public_key/dsa
  26487. * @requires crypto/public_key/elgamal
  26488. * @requires crypto/public_key/elliptic
  26489. * @requires crypto/public_key/rsa
  26490. * @module crypto/public_key
  26491. */
  26492. },{"./dsa":98,"./elgamal":99,"./elliptic":104,"./rsa":108,"tweetnacl/nacl-fast-light.js":72}],107:[function(require,module,exports){
  26493. 'use strict';
  26494. Object.defineProperty(exports, "__esModule", {
  26495. value: true
  26496. });
  26497. var _bn = require('bn.js');
  26498. var _bn2 = _interopRequireDefault(_bn);
  26499. var _random = require('../random');
  26500. var _random2 = _interopRequireDefault(_random);
  26501. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  26502. // OpenPGP.js - An OpenPGP implementation in javascript
  26503. // Copyright (C) 2018 Proton Technologies AG
  26504. //
  26505. // This library is free software; you can redistribute it and/or
  26506. // modify it under the terms of the GNU Lesser General Public
  26507. // License as published by the Free Software Foundation; either
  26508. // version 3.0 of the License, or (at your option) any later version.
  26509. //
  26510. // This library is distributed in the hope that it will be useful,
  26511. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  26512. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  26513. // Lesser General Public License for more details.
  26514. //
  26515. // You should have received a copy of the GNU Lesser General Public
  26516. // License along with this library; if not, write to the Free Software
  26517. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  26518. /**
  26519. * @fileoverview Algorithms for probabilistic random prime generation
  26520. * @requires bn.js
  26521. * @requires crypto/random
  26522. * @module crypto/public_key/prime
  26523. */
  26524. exports.default = {
  26525. randomProbablePrime, isProbablePrime, fermat, millerRabin, divisionTest
  26526. };
  26527. /**
  26528. * Probabilistic random number generator
  26529. * @param {Integer} bits Bit length of the prime
  26530. * @param {BN} e Optional RSA exponent to check against the prime
  26531. * @param {Integer} k Optional number of iterations of Miller-Rabin test
  26532. * @returns BN
  26533. * @async
  26534. */
  26535. async function randomProbablePrime(bits, e, k) {
  26536. const min = new _bn2.default(1).shln(bits - 1);
  26537. const thirty = new _bn2.default(30);
  26538. /*
  26539. * We can avoid any multiples of 3 and 5 by looking at n mod 30
  26540. * n mod 30 = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
  26541. * the next possible prime is mod 30:
  26542. * 1 7 7 7 7 7 7 11 11 11 11 13 13 17 17 17 17 19 19 23 23 23 23 29 29 29 29 29 29 1
  26543. */
  26544. const adds = [1, 6, 5, 4, 3, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 2, 1, 4, 3, 2, 1, 6, 5, 4, 3, 2, 1, 2];
  26545. let n = await _random2.default.getRandomBN(min, min.shln(1));
  26546. let i = n.mod(thirty).toNumber();
  26547. do {
  26548. n.iaddn(adds[i]);
  26549. i = (i + adds[i]) % adds.length;
  26550. // If reached the maximum, go back to the minimum.
  26551. if (n.bitLength() > bits) {
  26552. n = n.mod(min.shln(1)).iadd(min);
  26553. i = n.mod(thirty).toNumber();
  26554. }
  26555. } while (!(await isProbablePrime(n, e, k)));
  26556. return n;
  26557. }
  26558. /**
  26559. * Probabilistic primality testing
  26560. * @param {BN} n Number to test
  26561. * @param {BN} e Optional RSA exponent to check against the prime
  26562. * @param {Integer} k Optional number of iterations of Miller-Rabin test
  26563. * @returns {boolean}
  26564. * @async
  26565. */
  26566. async function isProbablePrime(n, e, k) {
  26567. if (e && !n.subn(1).gcd(e).eqn(1)) {
  26568. return false;
  26569. }
  26570. if (!divisionTest(n)) {
  26571. return false;
  26572. }
  26573. if (!fermat(n)) {
  26574. return false;
  26575. }
  26576. if (!(await millerRabin(n, k))) {
  26577. return false;
  26578. }
  26579. // TODO implement the Lucas test
  26580. // See Section C.3.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
  26581. return true;
  26582. }
  26583. /**
  26584. * Tests whether n is probably prime or not using Fermat's test with b = 2.
  26585. * Fails if b^(n-1) mod n === 1.
  26586. * @param {BN} n Number to test
  26587. * @param {Integer} b Optional Fermat test base
  26588. * @returns {boolean}
  26589. */
  26590. function fermat(n, b) {
  26591. b = b || new _bn2.default(2);
  26592. return b.toRed(_bn2.default.mont(n)).redPow(n.subn(1)).fromRed().cmpn(1) === 0;
  26593. }
  26594. function divisionTest(n) {
  26595. return small_primes.every(m => {
  26596. return n.modn(m) !== 0;
  26597. });
  26598. }
  26599. // https://github.com/gpg/libgcrypt/blob/master/cipher/primegen.c
  26600. const small_primes = [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, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733, 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053, 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129, 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213, 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357, 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531, 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617, 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687, 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741, 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819, 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903, 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999, 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079, 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181, 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257, 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331, 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413, 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511, 3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571, 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643, 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727, 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821, 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907, 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989, 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057, 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139, 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231, 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297, 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409, 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493, 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583, 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657, 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751, 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831, 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937, 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999];
  26601. // Miller-Rabin - Miller Rabin algorithm for primality test
  26602. // Copyright Fedor Indutny, 2014.
  26603. //
  26604. // This software is licensed under the MIT License.
  26605. //
  26606. // Permission is hereby granted, free of charge, to any person obtaining a
  26607. // copy of this software and associated documentation files (the
  26608. // "Software"), to deal in the Software without restriction, including
  26609. // without limitation the rights to use, copy, modify, merge, publish,
  26610. // distribute, sublicense, and/or sell copies of the Software, and to permit
  26611. // persons to whom the Software is furnished to do so, subject to the
  26612. // following conditions:
  26613. //
  26614. // The above copyright notice and this permission notice shall be included
  26615. // in all copies or substantial portions of the Software.
  26616. //
  26617. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  26618. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26619. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  26620. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  26621. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  26622. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  26623. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  26624. // Adapted on Jan 2018 from version 4.0.1 at https://github.com/indutny/miller-rabin
  26625. // Sample syntax for Fixed-Base Miller-Rabin:
  26626. // millerRabin(n, k, () => new BN(small_primes[Math.random() * small_primes.length | 0]))
  26627. /**
  26628. * Tests whether n is probably prime or not using the Miller-Rabin test.
  26629. * See HAC Remark 4.28.
  26630. * @param {BN} n Number to test
  26631. * @param {Integer} k Optional number of iterations of Miller-Rabin test
  26632. * @param {Function} rand Optional function to generate potential witnesses
  26633. * @returns {boolean}
  26634. * @async
  26635. */
  26636. async function millerRabin(n, k, rand) {
  26637. const len = n.bitLength();
  26638. const red = _bn2.default.mont(n);
  26639. const rone = new _bn2.default(1).toRed(red);
  26640. if (!k) {
  26641. k = Math.max(1, len / 48 | 0);
  26642. }
  26643. const n1 = n.subn(1);
  26644. const rn1 = n1.toRed(red);
  26645. // Find d and s, (n - 1) = (2 ^ s) * d;
  26646. let s = 0;
  26647. while (!n1.testn(s)) {
  26648. s++;
  26649. }
  26650. const d = n.shrn(s);
  26651. for (; k > 0; k--) {
  26652. const a = rand ? rand() : await _random2.default.getRandomBN(new _bn2.default(2), n1);
  26653. let x = a.toRed(red).redPow(d);
  26654. if (x.eq(rone) || x.eq(rn1)) {
  26655. continue;
  26656. }
  26657. let i;
  26658. for (i = 1; i < s; i++) {
  26659. x = x.redSqr();
  26660. if (x.eq(rone)) {
  26661. return false;
  26662. }
  26663. if (x.eq(rn1)) {
  26664. break;
  26665. }
  26666. }
  26667. if (i === s) {
  26668. return false;
  26669. }
  26670. }
  26671. return true;
  26672. }
  26673. },{"../random":109,"bn.js":16}],108:[function(require,module,exports){
  26674. 'use strict';
  26675. Object.defineProperty(exports, "__esModule", {
  26676. value: true
  26677. });
  26678. var _bn = require('bn.js');
  26679. var _bn2 = _interopRequireDefault(_bn);
  26680. var _prime = require('./prime');
  26681. var _prime2 = _interopRequireDefault(_prime);
  26682. var _random = require('../random');
  26683. var _random2 = _interopRequireDefault(_random);
  26684. var _config = require('../../config');
  26685. var _config2 = _interopRequireDefault(_config);
  26686. var _util = require('../../util');
  26687. var _util2 = _interopRequireDefault(_util);
  26688. var _pkcs = require('../pkcs1');
  26689. var _pkcs2 = _interopRequireDefault(_pkcs);
  26690. var _enums = require('../../enums');
  26691. var _enums2 = _interopRequireDefault(_enums);
  26692. var _mpi = require('../../type/mpi');
  26693. var _mpi2 = _interopRequireDefault(_mpi);
  26694. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  26695. // GPG4Browsers - An OpenPGP implementation in javascript
  26696. // Copyright (C) 2011 Recurity Labs GmbH
  26697. //
  26698. // This library is free software; you can redistribute it and/or
  26699. // modify it under the terms of the GNU Lesser General Public
  26700. // License as published by the Free Software Foundation; either
  26701. // version 3.0 of the License, or (at your option) any later version.
  26702. //
  26703. // This library is distributed in the hope that it will be useful,
  26704. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  26705. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  26706. // Lesser General Public License for more details.
  26707. //
  26708. // You should have received a copy of the GNU Lesser General Public
  26709. // License along with this library; if not, write to the Free Software
  26710. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  26711. /**
  26712. * @fileoverview RSA implementation
  26713. * @requires bn.js
  26714. * @requires crypto/public_key/prime
  26715. * @requires crypto/random
  26716. * @requires config
  26717. * @requires util
  26718. * @module crypto/public_key/rsa
  26719. */
  26720. const webCrypto = _util2.default.getWebCrypto();
  26721. const nodeCrypto = _util2.default.getNodeCrypto();
  26722. const asn1 = nodeCrypto ? require('asn1.js') : undefined;
  26723. // Helper for IE11 KeyOperation objects
  26724. function promisifyIE11Op(keyObj, err) {
  26725. if (typeof keyObj.then !== 'function') {
  26726. // IE11 KeyOperation
  26727. return new Promise(function (resolve, reject) {
  26728. keyObj.onerror = function () {
  26729. reject(new Error(err));
  26730. };
  26731. keyObj.oncomplete = function (e) {
  26732. resolve(e.target.result);
  26733. };
  26734. });
  26735. }
  26736. return keyObj;
  26737. }
  26738. /* eslint-disable no-invalid-this */
  26739. const RSAPrivateKey = _util2.default.detectNode() ? asn1.define('RSAPrivateKey', function () {
  26740. this.seq().obj( // used for native NodeJS crypto
  26741. this.key('version').int(), // 0
  26742. this.key('modulus').int(), // n
  26743. this.key('publicExponent').int(), // e
  26744. this.key('privateExponent').int(), // d
  26745. this.key('prime1').int(), // p
  26746. this.key('prime2').int(), // q
  26747. this.key('exponent1').int(), // dp
  26748. this.key('exponent2').int(), // dq
  26749. this.key('coefficient').int() // u
  26750. );
  26751. }) : undefined;
  26752. const RSAPublicKey = _util2.default.detectNode() ? asn1.define('RSAPubliceKey', function () {
  26753. this.seq().obj( // used for native NodeJS crypto
  26754. this.key('modulus').int(), // n
  26755. this.key('publicExponent').int() // e
  26756. );
  26757. }) : undefined;
  26758. /* eslint-enable no-invalid-this */
  26759. exports.default = {
  26760. /** Create signature
  26761. * @param {module:enums.hash} hash_algo Hash algorithm
  26762. * @param {Uint8Array} data message
  26763. * @param {Uint8Array} n RSA public modulus
  26764. * @param {Uint8Array} e RSA public exponent
  26765. * @param {Uint8Array} d RSA private exponent
  26766. * @param {Uint8Array} p RSA private prime p
  26767. * @param {Uint8Array} q RSA private prime q
  26768. * @param {Uint8Array} u RSA private coefficient
  26769. * @param {Uint8Array} hashed hashed message
  26770. * @returns {Uint8Array} RSA Signature
  26771. * @async
  26772. */
  26773. sign: async function sign(hash_algo, data, n, e, d, p, q, u, hashed) {
  26774. if (data && !_util2.default.isStream(data)) {
  26775. if (_util2.default.getWebCrypto()) {
  26776. try {
  26777. return await this.webSign(_enums2.default.read(_enums2.default.webHash, hash_algo), data, n, e, d, p, q, u);
  26778. } catch (err) {
  26779. _util2.default.print_debug_error(err);
  26780. }
  26781. } else if (_util2.default.getNodeCrypto()) {
  26782. return this.nodeSign(hash_algo, data, n, e, d, p, q, u);
  26783. }
  26784. }
  26785. return this.bnSign(hash_algo, n, d, hashed);
  26786. },
  26787. /**
  26788. * Verify signature
  26789. * @param {module:enums.hash} hash_algo Hash algorithm
  26790. * @param {Uint8Array} data message
  26791. * @param {Uint8Array} s signature
  26792. * @param {Uint8Array} n RSA public modulus
  26793. * @param {Uint8Array} e RSA public exponent
  26794. * @param {Uint8Array} hashed hashed message
  26795. * @returns {Boolean}
  26796. * @async
  26797. */
  26798. verify: async function verify(hash_algo, data, s, n, e, hashed) {
  26799. if (data && !_util2.default.isStream(data)) {
  26800. if (_util2.default.getWebCrypto()) {
  26801. try {
  26802. return await this.webVerify(_enums2.default.read(_enums2.default.webHash, hash_algo), data, s, n, e);
  26803. } catch (err) {
  26804. _util2.default.print_debug_error(err);
  26805. }
  26806. } else if (_util2.default.getNodeCrypto()) {
  26807. return this.nodeVerify(hash_algo, data, s, n, e);
  26808. }
  26809. }
  26810. return this.bnVerify(hash_algo, s, n, e, hashed);
  26811. },
  26812. /**
  26813. * Encrypt message
  26814. * @param {Uint8Array} data message
  26815. * @param {Uint8Array} n RSA public modulus
  26816. * @param {Uint8Array} e RSA public exponent
  26817. * @returns {Uint8Array} RSA Ciphertext
  26818. * @async
  26819. */
  26820. encrypt: async function encrypt(data, n, e) {
  26821. if (_util2.default.getNodeCrypto()) {
  26822. return this.nodeEncrypt(data, n, e);
  26823. }
  26824. return this.bnEncrypt(data, n, e);
  26825. },
  26826. /**
  26827. * Decrypt RSA message
  26828. * @param {Uint8Array} m message
  26829. * @param {Uint8Array} n RSA public modulus
  26830. * @param {Uint8Array} e RSA public exponent
  26831. * @param {Uint8Array} d RSA private exponent
  26832. * @param {Uint8Array} p RSA private prime p
  26833. * @param {Uint8Array} q RSA private prime q
  26834. * @param {Uint8Array} u RSA private coefficient
  26835. * @returns {String} RSA Plaintext
  26836. * @async
  26837. */
  26838. decrypt: async function decrypt(data, n, e, d, p, q, u) {
  26839. if (_util2.default.getNodeCrypto()) {
  26840. return this.nodeDecrypt(data, n, e, d, p, q, u);
  26841. }
  26842. return this.bnDecrypt(data, n, e, d, p, q, u);
  26843. },
  26844. /**
  26845. * Generate a new random private key B bits long with public exponent E.
  26846. *
  26847. * When possible, webCrypto or nodeCrypto is used. Otherwise, primes are generated using
  26848. * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm.
  26849. * @see module:crypto/public_key/prime
  26850. * @param {Integer} B RSA bit length
  26851. * @param {String} E RSA public exponent in hex string
  26852. * @returns {{n: BN, e: BN, d: BN,
  26853. * p: BN, q: BN, u: BN}} RSA public modulus, RSA public exponent, RSA private exponent,
  26854. * RSA private prime p, RSA private prime q, u = q ** -1 mod p
  26855. * @async
  26856. */
  26857. generate: async function generate(B, E) {
  26858. let key;
  26859. E = new _bn2.default(E, 16);
  26860. // Native RSA keygen using Web Crypto
  26861. if (_util2.default.getWebCrypto()) {
  26862. let keyPair;
  26863. let keyGenOpt;
  26864. if (window.crypto && window.crypto.subtle || window.msCrypto) {
  26865. // current standard spec
  26866. keyGenOpt = {
  26867. name: 'RSASSA-PKCS1-v1_5',
  26868. modulusLength: B, // the specified keysize in bits
  26869. publicExponent: E.toArrayLike(Uint8Array), // take three bytes (max 65537) for exponent
  26870. hash: {
  26871. name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify'
  26872. }
  26873. };
  26874. keyPair = webCrypto.generateKey(keyGenOpt, true, ['sign', 'verify']);
  26875. keyPair = await promisifyIE11Op(keyPair, 'Error generating RSA key pair.');
  26876. } else if (window.crypto && window.crypto.webkitSubtle) {
  26877. // outdated spec implemented by old Webkit
  26878. keyGenOpt = {
  26879. name: 'RSA-OAEP',
  26880. modulusLength: B, // the specified keysize in bits
  26881. publicExponent: E.toArrayLike(Uint8Array), // take three bytes (max 65537) for exponent
  26882. hash: {
  26883. name: 'SHA-1' // not required for actual RSA keys, but for crypto api 'sign' and 'verify'
  26884. }
  26885. };
  26886. keyPair = await webCrypto.generateKey(keyGenOpt, true, ['encrypt', 'decrypt']);
  26887. } else {
  26888. throw new Error('Unknown WebCrypto implementation');
  26889. }
  26890. // export the generated keys as JsonWebKey (JWK)
  26891. // https://tools.ietf.org/html/draft-ietf-jose-json-web-key-33
  26892. let jwk = webCrypto.exportKey('jwk', keyPair.privateKey);
  26893. jwk = await promisifyIE11Op(jwk, 'Error exporting RSA key pair.');
  26894. // parse raw ArrayBuffer bytes to jwk/json (WebKit/Safari/IE11 quirk)
  26895. if (jwk instanceof ArrayBuffer) {
  26896. jwk = JSON.parse(String.fromCharCode.apply(null, new Uint8Array(jwk)));
  26897. }
  26898. // map JWK parameters to BN
  26899. key = {};
  26900. key.n = new _bn2.default(_util2.default.b64_to_Uint8Array(jwk.n));
  26901. key.e = E;
  26902. key.d = new _bn2.default(_util2.default.b64_to_Uint8Array(jwk.d));
  26903. // switch p and q
  26904. key.p = new _bn2.default(_util2.default.b64_to_Uint8Array(jwk.q));
  26905. key.q = new _bn2.default(_util2.default.b64_to_Uint8Array(jwk.p));
  26906. // Since p and q are switched in places, we could keep u
  26907. key.u = new _bn2.default(_util2.default.b64_to_Uint8Array(jwk.qi));
  26908. return key;
  26909. } else if (_util2.default.getNodeCrypto() && nodeCrypto.generateKeyPair && RSAPrivateKey) {
  26910. const opts = {
  26911. modulusLength: Number(B.toString(10)),
  26912. publicExponent: Number(E.toString(10)),
  26913. publicKeyEncoding: { type: 'pkcs1', format: 'der' },
  26914. privateKeyEncoding: { type: 'pkcs1', format: 'der' }
  26915. };
  26916. const prv = await new Promise((resolve, reject) => nodeCrypto.generateKeyPair('rsa', opts, (err, _, der) => {
  26917. if (err) {
  26918. reject(err);
  26919. } else {
  26920. resolve(RSAPrivateKey.decode(der, 'der'));
  26921. }
  26922. }));
  26923. /** PGP spec differs from DER spec, DER: `(inverse of q) mod p`, PGP: `(inverse of p) mod q`.
  26924. * @link https://tools.ietf.org/html/rfc3447#section-3.2
  26925. * @link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-08#section-5.6.1
  26926. */
  26927. return {
  26928. n: prv.modulus,
  26929. e: prv.publicExponent,
  26930. d: prv.privateExponent,
  26931. // switch p and q
  26932. p: prv.prime2,
  26933. q: prv.prime1,
  26934. // Since p and q are switched in places, we could keep u
  26935. u: prv.coefficient // PGP type of u
  26936. };
  26937. }
  26938. // RSA keygen fallback using 40 iterations of the Miller-Rabin test
  26939. // See https://stackoverflow.com/a/6330138 for justification
  26940. // Also see section C.3 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST
  26941. let q = await _prime2.default.randomProbablePrime(B - (B >> 1), E, 40);
  26942. let p = await _prime2.default.randomProbablePrime(B >> 1, E, 40);
  26943. if (q.cmp(p) < 0) {
  26944. var _ref = [q, p];
  26945. p = _ref[0];
  26946. q = _ref[1];
  26947. }
  26948. const phi = p.subn(1).mul(q.subn(1));
  26949. return {
  26950. n: p.mul(q),
  26951. e: E,
  26952. d: E.invm(phi),
  26953. p: p,
  26954. q: q,
  26955. // dp: d.mod(p.subn(1)),
  26956. // dq: d.mod(q.subn(1)),
  26957. u: p.invm(q)
  26958. };
  26959. },
  26960. bnSign: async function bnSign(hash_algo, n, d, hashed) {
  26961. n = new _bn2.default(n);
  26962. const m = new _bn2.default((await _pkcs2.default.emsa.encode(hash_algo, hashed, n.byteLength())), 16);
  26963. d = new _bn2.default(d);
  26964. if (n.cmp(m) <= 0) {
  26965. throw new Error('Message size cannot exceed modulus size');
  26966. }
  26967. const nred = new _bn2.default.red(n);
  26968. return m.toRed(nred).redPow(d).toArrayLike(Uint8Array, 'be', n.byteLength());
  26969. },
  26970. webSign: async function webSign(hash_name, data, n, e, d, p, q, u) {
  26971. /** OpenPGP keys require that p < q, and Safari Web Crypto requires that p > q.
  26972. * We swap them in privateToJwk, so it usually works out, but nevertheless,
  26973. * not all OpenPGP keys are compatible with this requirement.
  26974. * OpenPGP.js used to generate RSA keys the wrong way around (p > q), and still
  26975. * does if the underlying Web Crypto does so (e.g. old MS Edge 50% of the time).
  26976. */
  26977. const jwk = privateToJwk(n, e, d, p, q, u);
  26978. const algo = {
  26979. name: "RSASSA-PKCS1-v1_5",
  26980. hash: { name: hash_name }
  26981. };
  26982. const key = await webCrypto.importKey("jwk", jwk, algo, false, ["sign"]);
  26983. // add hash field for ms edge support
  26984. return new Uint8Array((await webCrypto.sign({ "name": "RSASSA-PKCS1-v1_5", "hash": hash_name }, key, data)));
  26985. },
  26986. nodeSign: async function nodeSign(hash_algo, data, n, e, d, p, q, u) {
  26987. const pBNum = new _bn2.default(p);
  26988. const qBNum = new _bn2.default(q);
  26989. const dBNum = new _bn2.default(d);
  26990. const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1)
  26991. const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1)
  26992. const sign = nodeCrypto.createSign(_enums2.default.read(_enums2.default.hash, hash_algo));
  26993. sign.write(data);
  26994. sign.end();
  26995. const keyObject = {
  26996. version: 0,
  26997. modulus: new _bn2.default(n),
  26998. publicExponent: new _bn2.default(e),
  26999. privateExponent: new _bn2.default(d),
  27000. // switch p and q
  27001. prime1: new _bn2.default(q),
  27002. prime2: new _bn2.default(p),
  27003. // switch dp and dq
  27004. exponent1: dq,
  27005. exponent2: dp,
  27006. coefficient: new _bn2.default(u)
  27007. };
  27008. if (typeof nodeCrypto.createPrivateKey !== 'undefined') {
  27009. //from version 11.6.0 Node supports der encoded key objects
  27010. const der = RSAPrivateKey.encode(keyObject, 'der');
  27011. return new Uint8Array(sign.sign({ key: der, format: 'der', type: 'pkcs1' }));
  27012. }
  27013. const pem = RSAPrivateKey.encode(keyObject, 'pem', {
  27014. label: 'RSA PRIVATE KEY'
  27015. });
  27016. return new Uint8Array(sign.sign(pem));
  27017. },
  27018. bnVerify: async function bnVerify(hash_algo, s, n, e, hashed) {
  27019. n = new _bn2.default(n);
  27020. s = new _bn2.default(s);
  27021. e = new _bn2.default(e);
  27022. if (n.cmp(s) <= 0) {
  27023. throw new Error('Signature size cannot exceed modulus size');
  27024. }
  27025. const nred = new _bn2.default.red(n);
  27026. const EM1 = s.toRed(nred).redPow(e).toArrayLike(Uint8Array, 'be', n.byteLength());
  27027. const EM2 = await _pkcs2.default.emsa.encode(hash_algo, hashed, n.byteLength());
  27028. return _util2.default.Uint8Array_to_hex(EM1) === EM2;
  27029. },
  27030. webVerify: async function webVerify(hash_name, data, s, n, e) {
  27031. const jwk = publicToJwk(n, e);
  27032. const key = await webCrypto.importKey("jwk", jwk, {
  27033. name: "RSASSA-PKCS1-v1_5",
  27034. hash: { name: hash_name }
  27035. }, false, ["verify"]);
  27036. // add hash field for ms edge support
  27037. return webCrypto.verify({ "name": "RSASSA-PKCS1-v1_5", "hash": hash_name }, key, s, data);
  27038. },
  27039. nodeVerify: async function nodeVerify(hash_algo, data, s, n, e) {
  27040. const verify = nodeCrypto.createVerify(_enums2.default.read(_enums2.default.hash, hash_algo));
  27041. verify.write(data);
  27042. verify.end();
  27043. const keyObject = {
  27044. modulus: new _bn2.default(n),
  27045. publicExponent: new _bn2.default(e)
  27046. };
  27047. let key;
  27048. if (typeof nodeCrypto.createPrivateKey !== 'undefined') {
  27049. //from version 11.6.0 Node supports der encoded key objects
  27050. const der = RSAPublicKey.encode(keyObject, 'der');
  27051. key = { key: der, format: 'der', type: 'pkcs1' };
  27052. } else {
  27053. key = RSAPublicKey.encode(keyObject, 'pem', {
  27054. label: 'RSA PUBLIC KEY'
  27055. });
  27056. }
  27057. try {
  27058. return await verify.verify(key, s);
  27059. } catch (err) {
  27060. return false;
  27061. }
  27062. },
  27063. nodeEncrypt: async function nodeEncrypt(data, n, e) {
  27064. const keyObject = {
  27065. modulus: new _bn2.default(n),
  27066. publicExponent: new _bn2.default(e)
  27067. };
  27068. let key;
  27069. if (typeof nodeCrypto.createPrivateKey !== 'undefined') {
  27070. const der = RSAPublicKey.encode(keyObject, 'der');
  27071. key = { key: der, format: 'der', type: 'pkcs1', padding: nodeCrypto.constants.RSA_PKCS1_PADDING };
  27072. } else {
  27073. const pem = RSAPublicKey.encode(keyObject, 'pem', {
  27074. label: 'RSA PUBLIC KEY'
  27075. });
  27076. key = { key: pem, padding: nodeCrypto.constants.RSA_PKCS1_PADDING };
  27077. }
  27078. return new Uint8Array(nodeCrypto.publicEncrypt(key, data));
  27079. },
  27080. bnEncrypt: async function bnEncrypt(data, n, e) {
  27081. n = new _bn2.default(n);
  27082. data = new _mpi2.default((await _pkcs2.default.eme.encode(_util2.default.Uint8Array_to_str(data), n.byteLength())));
  27083. data = data.toBN();
  27084. e = new _bn2.default(e);
  27085. if (n.cmp(data) <= 0) {
  27086. throw new Error('Message size cannot exceed modulus size');
  27087. }
  27088. const nred = new _bn2.default.red(n);
  27089. return data.toRed(nred).redPow(e).toArrayLike(Uint8Array, 'be', n.byteLength());
  27090. },
  27091. nodeDecrypt: function nodeDecrypt(data, n, e, d, p, q, u) {
  27092. const pBNum = new _bn2.default(p);
  27093. const qBNum = new _bn2.default(q);
  27094. const dBNum = new _bn2.default(d);
  27095. const dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1)
  27096. const dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1)
  27097. const keyObject = {
  27098. version: 0,
  27099. modulus: new _bn2.default(n),
  27100. publicExponent: new _bn2.default(e),
  27101. privateExponent: new _bn2.default(d),
  27102. // switch p and q
  27103. prime1: new _bn2.default(q),
  27104. prime2: new _bn2.default(p),
  27105. // switch dp and dq
  27106. exponent1: dq,
  27107. exponent2: dp,
  27108. coefficient: new _bn2.default(u)
  27109. };
  27110. let key;
  27111. if (typeof nodeCrypto.createPrivateKey !== 'undefined') {
  27112. const der = RSAPrivateKey.encode(keyObject, 'der');
  27113. key = { key: der, format: 'der', type: 'pkcs1', padding: nodeCrypto.constants.RSA_PKCS1_PADDING };
  27114. } else {
  27115. const pem = RSAPrivateKey.encode(keyObject, 'pem', {
  27116. label: 'RSA PRIVATE KEY'
  27117. });
  27118. key = { key: pem, padding: nodeCrypto.constants.RSA_PKCS1_PADDING };
  27119. }
  27120. return _util2.default.Uint8Array_to_str(nodeCrypto.privateDecrypt(key, data));
  27121. },
  27122. bnDecrypt: async function bnDecrypt(data, n, e, d, p, q, u) {
  27123. data = new _bn2.default(data);
  27124. n = new _bn2.default(n);
  27125. e = new _bn2.default(e);
  27126. d = new _bn2.default(d);
  27127. p = new _bn2.default(p);
  27128. q = new _bn2.default(q);
  27129. u = new _bn2.default(u);
  27130. if (n.cmp(data) <= 0) {
  27131. throw new Error('Data too large.');
  27132. }
  27133. const dq = d.mod(q.subn(1)); // d mod (q-1)
  27134. const dp = d.mod(p.subn(1)); // d mod (p-1)
  27135. const pred = new _bn2.default.red(p);
  27136. const qred = new _bn2.default.red(q);
  27137. const nred = new _bn2.default.red(n);
  27138. let blinder;
  27139. let unblinder;
  27140. if (_config2.default.rsa_blinding) {
  27141. unblinder = (await _random2.default.getRandomBN(new _bn2.default(2), n)).toRed(nred);
  27142. blinder = unblinder.redInvm().redPow(e);
  27143. data = data.toRed(nred).redMul(blinder).fromRed();
  27144. }
  27145. const mp = data.toRed(pred).redPow(dp);
  27146. const mq = data.toRed(qred).redPow(dq);
  27147. const t = mq.redSub(mp.fromRed().toRed(qred));
  27148. const h = u.toRed(qred).redMul(t).fromRed();
  27149. let result = h.mul(p).add(mp).toRed(nred);
  27150. if (_config2.default.rsa_blinding) {
  27151. result = result.redMul(unblinder);
  27152. }
  27153. return _pkcs2.default.eme.decode(new _mpi2.default(result).toString());
  27154. },
  27155. prime: _prime2.default
  27156. };
  27157. /** Convert Openpgp private key params to jwk key according to
  27158. * @link https://tools.ietf.org/html/rfc7517
  27159. * @param {String} hash_algo
  27160. * @param {Uint8Array} n
  27161. * @param {Uint8Array} e
  27162. * @param {Uint8Array} d
  27163. * @param {Uint8Array} p
  27164. * @param {Uint8Array} q
  27165. * @param {Uint8Array} u
  27166. */
  27167. function privateToJwk(n, e, d, p, q, u) {
  27168. const pBNum = new _bn2.default(p);
  27169. const qBNum = new _bn2.default(q);
  27170. const dBNum = new _bn2.default(d);
  27171. let dq = dBNum.mod(qBNum.subn(1)); // d mod (q-1)
  27172. let dp = dBNum.mod(pBNum.subn(1)); // d mod (p-1)
  27173. dp = dp.toArrayLike(Uint8Array);
  27174. dq = dq.toArrayLike(Uint8Array);
  27175. return {
  27176. kty: 'RSA',
  27177. n: _util2.default.Uint8Array_to_b64(n, true),
  27178. e: _util2.default.Uint8Array_to_b64(e, true),
  27179. d: _util2.default.Uint8Array_to_b64(d, true),
  27180. // switch p and q
  27181. p: _util2.default.Uint8Array_to_b64(q, true),
  27182. q: _util2.default.Uint8Array_to_b64(p, true),
  27183. // switch dp and dq
  27184. dp: _util2.default.Uint8Array_to_b64(dq, true),
  27185. dq: _util2.default.Uint8Array_to_b64(dp, true),
  27186. qi: _util2.default.Uint8Array_to_b64(u, true),
  27187. ext: true
  27188. };
  27189. }
  27190. /** Convert Openpgp key public params to jwk key according to
  27191. * @link https://tools.ietf.org/html/rfc7517
  27192. * @param {String} hash_algo
  27193. * @param {Uint8Array} n
  27194. * @param {Uint8Array} e
  27195. */
  27196. function publicToJwk(n, e) {
  27197. return {
  27198. kty: 'RSA',
  27199. n: _util2.default.Uint8Array_to_b64(n, true),
  27200. e: _util2.default.Uint8Array_to_b64(e, true),
  27201. ext: true
  27202. };
  27203. }
  27204. },{"../../config":79,"../../enums":113,"../../type/mpi":155,"../../util":158,"../pkcs1":96,"../random":109,"./prime":107,"asn1.js":"asn1.js","bn.js":16}],109:[function(require,module,exports){
  27205. 'use strict';
  27206. Object.defineProperty(exports, "__esModule", {
  27207. value: true
  27208. });
  27209. var _bn = require('bn.js');
  27210. var _bn2 = _interopRequireDefault(_bn);
  27211. var _util = require('../util');
  27212. var _util2 = _interopRequireDefault(_util);
  27213. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  27214. // Do not use util.getNodeCrypto because we need this regardless of use_native setting
  27215. // GPG4Browsers - An OpenPGP implementation in javascript
  27216. // Copyright (C) 2011 Recurity Labs GmbH
  27217. //
  27218. // This library is free software; you can redistribute it and/or
  27219. // modify it under the terms of the GNU Lesser General Public
  27220. // License as published by the Free Software Foundation; either
  27221. // version 3.0 of the License, or (at your option) any later version.
  27222. //
  27223. // This library is distributed in the hope that it will be useful,
  27224. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  27225. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  27226. // Lesser General Public License for more details.
  27227. //
  27228. // You should have received a copy of the GNU Lesser General Public
  27229. // License along with this library; if not, write to the Free Software
  27230. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  27231. // The GPG4Browsers crypto interface
  27232. /**
  27233. * @fileoverview Provides tools for retrieving secure randomness from browsers or Node.js
  27234. * @requires bn.js
  27235. * @requires util
  27236. * @module crypto/random
  27237. */
  27238. const nodeCrypto = _util2.default.detectNode() && require('crypto');
  27239. exports.default = {
  27240. /**
  27241. * Retrieve secure random byte array of the specified length
  27242. * @param {Integer} length Length in bytes to generate
  27243. * @returns {Uint8Array} Random byte array
  27244. * @async
  27245. */
  27246. getRandomBytes: async function getRandomBytes(length) {
  27247. const buf = new Uint8Array(length);
  27248. if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
  27249. crypto.getRandomValues(buf);
  27250. } else if (typeof window !== 'undefined' && typeof window.msCrypto === 'object' && typeof window.msCrypto.getRandomValues === 'function') {
  27251. window.msCrypto.getRandomValues(buf);
  27252. } else if (nodeCrypto) {
  27253. const bytes = nodeCrypto.randomBytes(buf.length);
  27254. buf.set(bytes);
  27255. } else if (this.randomBuffer.buffer) {
  27256. await this.randomBuffer.get(buf);
  27257. } else {
  27258. throw new Error('No secure random number generator available.');
  27259. }
  27260. return buf;
  27261. },
  27262. /**
  27263. * Create a secure random MPI that is greater than or equal to min and less than max.
  27264. * @param {module:type/mpi} min Lower bound, included
  27265. * @param {module:type/mpi} max Upper bound, excluded
  27266. * @returns {module:BN} Random MPI
  27267. * @async
  27268. */
  27269. getRandomBN: async function getRandomBN(min, max) {
  27270. if (max.cmp(min) <= 0) {
  27271. throw new Error('Illegal parameter value: max <= min');
  27272. }
  27273. const modulus = max.sub(min);
  27274. const bytes = modulus.byteLength();
  27275. // Using a while loop is necessary to avoid bias introduced by the mod operation.
  27276. // However, we request 64 extra random bits so that the bias is negligible.
  27277. // Section B.1.1 here: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
  27278. const r = new _bn2.default((await this.getRandomBytes(bytes + 8)));
  27279. return r.mod(modulus).add(min);
  27280. },
  27281. randomBuffer: new RandomBuffer()
  27282. };
  27283. /**
  27284. * Buffer for secure random numbers
  27285. */
  27286. function RandomBuffer() {
  27287. this.buffer = null;
  27288. this.size = null;
  27289. this.callback = null;
  27290. }
  27291. /**
  27292. * Initialize buffer
  27293. * @param {Integer} size size of buffer
  27294. */
  27295. RandomBuffer.prototype.init = function (size, callback) {
  27296. this.buffer = new Uint8Array(size);
  27297. this.size = 0;
  27298. this.callback = callback;
  27299. };
  27300. /**
  27301. * Concat array of secure random numbers to buffer
  27302. * @param {Uint8Array} buf
  27303. */
  27304. RandomBuffer.prototype.set = function (buf) {
  27305. if (!this.buffer) {
  27306. throw new Error('RandomBuffer is not initialized');
  27307. }
  27308. if (!(buf instanceof Uint8Array)) {
  27309. throw new Error('Invalid type: buf not an Uint8Array');
  27310. }
  27311. const freeSpace = this.buffer.length - this.size;
  27312. if (buf.length > freeSpace) {
  27313. buf = buf.subarray(0, freeSpace);
  27314. }
  27315. // set buf with offset old size of buffer
  27316. this.buffer.set(buf, this.size);
  27317. this.size += buf.length;
  27318. };
  27319. /**
  27320. * Take numbers out of buffer and copy to array
  27321. * @param {Uint8Array} buf the destination array
  27322. */
  27323. RandomBuffer.prototype.get = async function (buf) {
  27324. if (!this.buffer) {
  27325. throw new Error('RandomBuffer is not initialized');
  27326. }
  27327. if (!(buf instanceof Uint8Array)) {
  27328. throw new Error('Invalid type: buf not an Uint8Array');
  27329. }
  27330. if (this.size < buf.length) {
  27331. if (!this.callback) {
  27332. throw new Error('Random number buffer depleted');
  27333. }
  27334. // Wait for random bytes from main context, then try again
  27335. await this.callback();
  27336. return this.get(buf);
  27337. }
  27338. for (let i = 0; i < buf.length; i++) {
  27339. buf[i] = this.buffer[--this.size];
  27340. // clear buffer value
  27341. this.buffer[this.size] = 0;
  27342. }
  27343. };
  27344. },{"../util":158,"bn.js":16,"crypto":"crypto"}],110:[function(require,module,exports){
  27345. 'use strict';
  27346. Object.defineProperty(exports, "__esModule", {
  27347. value: true
  27348. });
  27349. var _crypto = require('./crypto');
  27350. var _crypto2 = _interopRequireDefault(_crypto);
  27351. var _public_key = require('./public_key');
  27352. var _public_key2 = _interopRequireDefault(_public_key);
  27353. var _enums = require('../enums');
  27354. var _enums2 = _interopRequireDefault(_enums);
  27355. var _util = require('../util');
  27356. var _util2 = _interopRequireDefault(_util);
  27357. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  27358. /**
  27359. * @fileoverview Provides functions for asymmetric signing and signature verification
  27360. * @requires crypto/crypto
  27361. * @requires crypto/public_key
  27362. * @requires enums
  27363. * @requires util
  27364. * @module crypto/signature
  27365. */
  27366. exports.default = {
  27367. /**
  27368. * Verifies the signature provided for data using specified algorithms and public key parameters.
  27369. * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}
  27370. * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}
  27371. * for public key and hash algorithms.
  27372. * @param {module:enums.publicKey} algo Public key algorithm
  27373. * @param {module:enums.hash} hash_algo Hash algorithm
  27374. * @param {Array<module:type/mpi>} msg_MPIs Algorithm-specific signature parameters
  27375. * @param {Array<module:type/mpi>} pub_MPIs Algorithm-specific public key parameters
  27376. * @param {Uint8Array} data Data for which the signature was created
  27377. * @param {Uint8Array} hashed The hashed data
  27378. * @returns {Boolean} True if signature is valid
  27379. * @async
  27380. */
  27381. verify: async function verify(algo, hash_algo, msg_MPIs, pub_MPIs, data, hashed) {
  27382. const types = _crypto2.default.getPubKeyParamTypes(algo);
  27383. if (pub_MPIs.length < types.length) {
  27384. throw new Error('Missing public key parameters');
  27385. }
  27386. switch (algo) {
  27387. case _enums2.default.publicKey.rsa_encrypt_sign:
  27388. case _enums2.default.publicKey.rsa_encrypt:
  27389. case _enums2.default.publicKey.rsa_sign:
  27390. {
  27391. const n = pub_MPIs[0].toUint8Array();
  27392. const e = pub_MPIs[1].toUint8Array();
  27393. const m = msg_MPIs[0].toUint8Array('be', n.length);
  27394. return _public_key2.default.rsa.verify(hash_algo, data, m, n, e, hashed);
  27395. }
  27396. case _enums2.default.publicKey.dsa:
  27397. {
  27398. const r = msg_MPIs[0].toBN();
  27399. const s = msg_MPIs[1].toBN();
  27400. const p = pub_MPIs[0].toBN();
  27401. const q = pub_MPIs[1].toBN();
  27402. const g = pub_MPIs[2].toBN();
  27403. const y = pub_MPIs[3].toBN();
  27404. return _public_key2.default.dsa.verify(hash_algo, r, s, hashed, g, p, q, y);
  27405. }
  27406. case _enums2.default.publicKey.ecdsa:
  27407. {
  27408. const oid = pub_MPIs[0];
  27409. const signature = { r: msg_MPIs[0].toUint8Array(), s: msg_MPIs[1].toUint8Array() };
  27410. const Q = pub_MPIs[1].toUint8Array();
  27411. return _public_key2.default.elliptic.ecdsa.verify(oid, hash_algo, signature, data, Q, hashed);
  27412. }
  27413. case _enums2.default.publicKey.eddsa:
  27414. {
  27415. const oid = pub_MPIs[0];
  27416. // EdDSA signature params are expected in little-endian format
  27417. const signature = {
  27418. R: msg_MPIs[0].toUint8Array('le', 32),
  27419. S: msg_MPIs[1].toUint8Array('le', 32)
  27420. };
  27421. const Q = pub_MPIs[1].toUint8Array('be', 33);
  27422. return _public_key2.default.elliptic.eddsa.verify(oid, hash_algo, signature, data, Q, hashed);
  27423. }
  27424. default:
  27425. throw new Error('Invalid signature algorithm.');
  27426. }
  27427. },
  27428. /**
  27429. * Creates a signature on data using specified algorithms and private key parameters.
  27430. * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1}
  27431. * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}
  27432. * for public key and hash algorithms.
  27433. * @param {module:enums.publicKey} algo Public key algorithm
  27434. * @param {module:enums.hash} hash_algo Hash algorithm
  27435. * @param {Array<module:type/mpi>} key_params Algorithm-specific public and private key parameters
  27436. * @param {Uint8Array} data Data to be signed
  27437. * @param {Uint8Array} hashed The hashed data
  27438. * @returns {Uint8Array} Signature
  27439. * @async
  27440. */
  27441. sign: async function sign(algo, hash_algo, key_params, data, hashed) {
  27442. const types = [].concat(_crypto2.default.getPubKeyParamTypes(algo), _crypto2.default.getPrivKeyParamTypes(algo));
  27443. if (key_params.length < types.length) {
  27444. throw new Error('Missing private key parameters');
  27445. }
  27446. switch (algo) {
  27447. case _enums2.default.publicKey.rsa_encrypt_sign:
  27448. case _enums2.default.publicKey.rsa_encrypt:
  27449. case _enums2.default.publicKey.rsa_sign:
  27450. {
  27451. const n = key_params[0].toUint8Array();
  27452. const e = key_params[1].toUint8Array();
  27453. const d = key_params[2].toUint8Array();
  27454. const p = key_params[3].toUint8Array();
  27455. const q = key_params[4].toUint8Array();
  27456. const u = key_params[5].toUint8Array();
  27457. const signature = await _public_key2.default.rsa.sign(hash_algo, data, n, e, d, p, q, u, hashed);
  27458. return _util2.default.Uint8Array_to_MPI(signature);
  27459. }
  27460. case _enums2.default.publicKey.dsa:
  27461. {
  27462. const p = key_params[0].toBN();
  27463. const q = key_params[1].toBN();
  27464. const g = key_params[2].toBN();
  27465. const x = key_params[4].toBN();
  27466. const signature = await _public_key2.default.dsa.sign(hash_algo, hashed, g, p, q, x);
  27467. return _util2.default.concatUint8Array([_util2.default.Uint8Array_to_MPI(signature.r), _util2.default.Uint8Array_to_MPI(signature.s)]);
  27468. }
  27469. case _enums2.default.publicKey.elgamal:
  27470. {
  27471. throw new Error('Signing with Elgamal is not defined in the OpenPGP standard.');
  27472. }
  27473. case _enums2.default.publicKey.ecdsa:
  27474. {
  27475. const oid = key_params[0];
  27476. const Q = key_params[1].toUint8Array();
  27477. const d = key_params[2].toUint8Array();
  27478. const signature = await _public_key2.default.elliptic.ecdsa.sign(oid, hash_algo, data, Q, d, hashed);
  27479. return _util2.default.concatUint8Array([_util2.default.Uint8Array_to_MPI(signature.r), _util2.default.Uint8Array_to_MPI(signature.s)]);
  27480. }
  27481. case _enums2.default.publicKey.eddsa:
  27482. {
  27483. const oid = key_params[0];
  27484. const Q = key_params[1].toUint8Array('be', 33);
  27485. const d = key_params[2].toUint8Array('be', 32);
  27486. const signature = await _public_key2.default.elliptic.eddsa.sign(oid, hash_algo, data, Q, d, hashed);
  27487. return _util2.default.concatUint8Array([_util2.default.Uint8Array_to_MPI(signature.R), _util2.default.Uint8Array_to_MPI(signature.S)]);
  27488. }
  27489. default:
  27490. throw new Error('Invalid signature algorithm.');
  27491. }
  27492. }
  27493. };
  27494. },{"../enums":113,"../util":158,"./crypto":89,"./public_key":106}],111:[function(require,module,exports){
  27495. 'use strict';
  27496. Object.defineProperty(exports, "__esModule", {
  27497. value: true
  27498. });
  27499. var _webStreamTools = require('web-stream-tools');
  27500. var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
  27501. var _base = require('./base64.js');
  27502. var _base2 = _interopRequireDefault(_base);
  27503. var _enums = require('../enums.js');
  27504. var _enums2 = _interopRequireDefault(_enums);
  27505. var _config = require('../config');
  27506. var _config2 = _interopRequireDefault(_config);
  27507. var _util = require('../util');
  27508. var _util2 = _interopRequireDefault(_util);
  27509. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  27510. /**
  27511. * Finds out which Ascii Armoring type is used. Throws error if unknown type.
  27512. * @private
  27513. * @param {String} text [String] ascii armored text
  27514. * @returns {Integer} 0 = MESSAGE PART n of m
  27515. * 1 = MESSAGE PART n
  27516. * 2 = SIGNED MESSAGE
  27517. * 3 = PGP MESSAGE
  27518. * 4 = PUBLIC KEY BLOCK
  27519. * 5 = PRIVATE KEY BLOCK
  27520. * 6 = SIGNATURE
  27521. */
  27522. function getType(text) {
  27523. const reHeader = /^-----BEGIN PGP (MESSAGE, PART \d+\/\d+|MESSAGE, PART \d+|SIGNED MESSAGE|MESSAGE|PUBLIC KEY BLOCK|PRIVATE KEY BLOCK|SIGNATURE)-----$/m;
  27524. const header = text.match(reHeader);
  27525. if (!header) {
  27526. throw new Error('Unknown ASCII armor type');
  27527. }
  27528. // BEGIN PGP MESSAGE, PART X/Y
  27529. // Used for multi-part messages, where the armor is split amongst Y
  27530. // parts, and this is the Xth part out of Y.
  27531. if (/MESSAGE, PART \d+\/\d+/.test(header[1])) {
  27532. return _enums2.default.armor.multipart_section;
  27533. } else
  27534. // BEGIN PGP MESSAGE, PART X
  27535. // Used for multi-part messages, where this is the Xth part of an
  27536. // unspecified number of parts. Requires the MESSAGE-ID Armor
  27537. // Header to be used.
  27538. if (/MESSAGE, PART \d+/.test(header[1])) {
  27539. return _enums2.default.armor.multipart_last;
  27540. } else
  27541. // BEGIN PGP SIGNED MESSAGE
  27542. if (/SIGNED MESSAGE/.test(header[1])) {
  27543. return _enums2.default.armor.signed;
  27544. } else
  27545. // BEGIN PGP MESSAGE
  27546. // Used for signed, encrypted, or compressed files.
  27547. if (/MESSAGE/.test(header[1])) {
  27548. return _enums2.default.armor.message;
  27549. } else
  27550. // BEGIN PGP PUBLIC KEY BLOCK
  27551. // Used for armoring public keys.
  27552. if (/PUBLIC KEY BLOCK/.test(header[1])) {
  27553. return _enums2.default.armor.public_key;
  27554. } else
  27555. // BEGIN PGP PRIVATE KEY BLOCK
  27556. // Used for armoring private keys.
  27557. if (/PRIVATE KEY BLOCK/.test(header[1])) {
  27558. return _enums2.default.armor.private_key;
  27559. } else
  27560. // BEGIN PGP SIGNATURE
  27561. // Used for detached signatures, OpenPGP/MIME signatures, and
  27562. // cleartext signatures. Note that PGP 2.x uses BEGIN PGP MESSAGE
  27563. // for detached signatures.
  27564. if (/SIGNATURE/.test(header[1])) {
  27565. return _enums2.default.armor.signature;
  27566. }
  27567. }
  27568. /**
  27569. * Add additional information to the armor version of an OpenPGP binary
  27570. * packet block.
  27571. * @author Alex
  27572. * @version 2011-12-16
  27573. * @param {String} customComment (optional) additional comment to add to the armored string
  27574. * @returns {String} The header information
  27575. */
  27576. // GPG4Browsers - An OpenPGP implementation in javascript
  27577. // Copyright (C) 2011 Recurity Labs GmbH
  27578. //
  27579. // This library is free software; you can redistribute it and/or
  27580. // modify it under the terms of the GNU Lesser General Public
  27581. // License as published by the Free Software Foundation; either
  27582. // version 3.0 of the License, or (at your option) any later version.
  27583. //
  27584. // This library is distributed in the hope that it will be useful,
  27585. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  27586. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  27587. // Lesser General Public License for more details.
  27588. //
  27589. // You should have received a copy of the GNU Lesser General Public
  27590. // License along with this library; if not, write to the Free Software
  27591. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  27592. /**
  27593. * @requires web-stream-tools
  27594. * @requires encoding/base64
  27595. * @requires enums
  27596. * @requires config
  27597. * @requires util
  27598. * @module encoding/armor
  27599. */
  27600. function addheader(customComment) {
  27601. let result = "";
  27602. if (_config2.default.show_version) {
  27603. result += "Version: " + _config2.default.versionstring + '\r\n';
  27604. }
  27605. if (_config2.default.show_comment) {
  27606. result += "Comment: " + _config2.default.commentstring + '\r\n';
  27607. }
  27608. if (customComment) {
  27609. result += "Comment: " + customComment + '\r\n';
  27610. }
  27611. result += '\r\n';
  27612. return result;
  27613. }
  27614. /**
  27615. * Calculates a checksum over the given data and returns it base64 encoded
  27616. * @param {String | ReadableStream<String>} data Data to create a CRC-24 checksum for
  27617. * @returns {String | ReadableStream<String>} Base64 encoded checksum
  27618. */
  27619. function getCheckSum(data) {
  27620. const crc = createcrc24(data);
  27621. return _base2.default.encode(crc);
  27622. }
  27623. const crc_table = [0x00000000, 0x00864cfb, 0x018ad50d, 0x010c99f6, 0x0393e6e1, 0x0315aa1a, 0x021933ec, 0x029f7f17, 0x07a18139, 0x0727cdc2, 0x062b5434, 0x06ad18cf, 0x043267d8, 0x04b42b23, 0x05b8b2d5, 0x053efe2e, 0x0fc54e89, 0x0f430272, 0x0e4f9b84, 0x0ec9d77f, 0x0c56a868, 0x0cd0e493, 0x0ddc7d65, 0x0d5a319e, 0x0864cfb0, 0x08e2834b, 0x09ee1abd, 0x09685646, 0x0bf72951, 0x0b7165aa, 0x0a7dfc5c, 0x0afbb0a7, 0x1f0cd1e9, 0x1f8a9d12, 0x1e8604e4, 0x1e00481f, 0x1c9f3708, 0x1c197bf3, 0x1d15e205, 0x1d93aefe, 0x18ad50d0, 0x182b1c2b, 0x192785dd, 0x19a1c926, 0x1b3eb631, 0x1bb8faca, 0x1ab4633c, 0x1a322fc7, 0x10c99f60, 0x104fd39b, 0x11434a6d, 0x11c50696, 0x135a7981, 0x13dc357a, 0x12d0ac8c, 0x1256e077, 0x17681e59, 0x17ee52a2, 0x16e2cb54, 0x166487af, 0x14fbf8b8, 0x147db443, 0x15712db5, 0x15f7614e, 0x3e19a3d2, 0x3e9fef29, 0x3f9376df, 0x3f153a24, 0x3d8a4533, 0x3d0c09c8, 0x3c00903e, 0x3c86dcc5, 0x39b822eb, 0x393e6e10, 0x3832f7e6, 0x38b4bb1d, 0x3a2bc40a, 0x3aad88f1, 0x3ba11107, 0x3b275dfc, 0x31dced5b, 0x315aa1a0, 0x30563856, 0x30d074ad, 0x324f0bba, 0x32c94741, 0x33c5deb7, 0x3343924c, 0x367d6c62, 0x36fb2099, 0x37f7b96f, 0x3771f594, 0x35ee8a83, 0x3568c678, 0x34645f8e, 0x34e21375, 0x2115723b, 0x21933ec0, 0x209fa736, 0x2019ebcd, 0x228694da, 0x2200d821, 0x230c41d7, 0x238a0d2c, 0x26b4f302, 0x2632bff9, 0x273e260f, 0x27b86af4, 0x252715e3, 0x25a15918, 0x24adc0ee, 0x242b8c15, 0x2ed03cb2, 0x2e567049, 0x2f5ae9bf, 0x2fdca544, 0x2d43da53, 0x2dc596a8, 0x2cc90f5e, 0x2c4f43a5, 0x2971bd8b, 0x29f7f170, 0x28fb6886, 0x287d247d, 0x2ae25b6a, 0x2a641791, 0x2b688e67, 0x2beec29c, 0x7c3347a4, 0x7cb50b5f, 0x7db992a9, 0x7d3fde52, 0x7fa0a145, 0x7f26edbe, 0x7e2a7448, 0x7eac38b3, 0x7b92c69d, 0x7b148a66, 0x7a181390, 0x7a9e5f6b, 0x7801207c, 0x78876c87, 0x798bf571, 0x790db98a, 0x73f6092d, 0x737045d6, 0x727cdc20, 0x72fa90db, 0x7065efcc, 0x70e3a337, 0x71ef3ac1, 0x7169763a, 0x74578814, 0x74d1c4ef, 0x75dd5d19, 0x755b11e2, 0x77c46ef5, 0x7742220e, 0x764ebbf8, 0x76c8f703, 0x633f964d, 0x63b9dab6, 0x62b54340, 0x62330fbb, 0x60ac70ac, 0x602a3c57, 0x6126a5a1, 0x61a0e95a, 0x649e1774, 0x64185b8f, 0x6514c279, 0x65928e82, 0x670df195, 0x678bbd6e, 0x66872498, 0x66016863, 0x6cfad8c4, 0x6c7c943f, 0x6d700dc9, 0x6df64132, 0x6f693e25, 0x6fef72de, 0x6ee3eb28, 0x6e65a7d3, 0x6b5b59fd, 0x6bdd1506, 0x6ad18cf0, 0x6a57c00b, 0x68c8bf1c, 0x684ef3e7, 0x69426a11, 0x69c426ea, 0x422ae476, 0x42aca88d, 0x43a0317b, 0x43267d80, 0x41b90297, 0x413f4e6c, 0x4033d79a, 0x40b59b61, 0x458b654f, 0x450d29b4, 0x4401b042, 0x4487fcb9, 0x461883ae, 0x469ecf55, 0x479256a3, 0x47141a58, 0x4defaaff, 0x4d69e604, 0x4c657ff2, 0x4ce33309, 0x4e7c4c1e, 0x4efa00e5, 0x4ff69913, 0x4f70d5e8, 0x4a4e2bc6, 0x4ac8673d, 0x4bc4fecb, 0x4b42b230, 0x49ddcd27, 0x495b81dc, 0x4857182a, 0x48d154d1, 0x5d26359f, 0x5da07964, 0x5cace092, 0x5c2aac69, 0x5eb5d37e, 0x5e339f85, 0x5f3f0673, 0x5fb94a88, 0x5a87b4a6, 0x5a01f85d, 0x5b0d61ab, 0x5b8b2d50, 0x59145247, 0x59921ebc, 0x589e874a, 0x5818cbb1, 0x52e37b16, 0x526537ed, 0x5369ae1b, 0x53efe2e0, 0x51709df7, 0x51f6d10c, 0x50fa48fa, 0x507c0401, 0x5542fa2f, 0x55c4b6d4, 0x54c82f22, 0x544e63d9, 0x56d11cce, 0x56575035, 0x575bc9c3, 0x57dd8538];
  27624. /**
  27625. * Internal function to calculate a CRC-24 checksum over a given string (data)
  27626. * @param {String | ReadableStream<String>} data Data to create a CRC-24 checksum for
  27627. * @returns {Uint8Array | ReadableStream<Uint8Array>} The CRC-24 checksum
  27628. */
  27629. function createcrc24(input) {
  27630. let crc = 0xB704CE;
  27631. return _webStreamTools2.default.transform(input, value => {
  27632. for (let index = 0; index < value.length; index++) {
  27633. crc = crc << 8 ^ crc_table[(crc >> 16 ^ value[index]) & 0xff];
  27634. }
  27635. }, () => new Uint8Array([crc >> 16, crc >> 8, crc]));
  27636. }
  27637. /**
  27638. * Verify armored headers. RFC4880, section 6.3: "OpenPGP should consider improperly formatted
  27639. * Armor Headers to be corruption of the ASCII Armor."
  27640. * @private
  27641. * @param {Array<String>} headers Armor headers
  27642. */
  27643. function verifyHeaders(headers) {
  27644. for (let i = 0; i < headers.length; i++) {
  27645. if (!/^([^\s:]|[^\s:][^:]*[^\s:]): .+$/.test(headers[i])) {
  27646. throw new Error('Improperly formatted armor header: ' + headers[i]);
  27647. }
  27648. if (!/^(Version|Comment|MessageID|Hash|Charset): .+$/.test(headers[i])) {
  27649. _util2.default.print_debug_error(new Error('Unknown header: ' + headers[i]));
  27650. }
  27651. }
  27652. }
  27653. /**
  27654. * Splits a message into two parts, the body and the checksum. This is an internal function
  27655. * @param {String} text OpenPGP armored message part
  27656. * @returns {Object} An object with attribute "body" containing the body
  27657. * and an attribute "checksum" containing the checksum.
  27658. */
  27659. function splitChecksum(text) {
  27660. let body = text;
  27661. let checksum = "";
  27662. const lastEquals = text.lastIndexOf("=");
  27663. if (lastEquals >= 0 && lastEquals !== text.length - 1) {
  27664. // '=' as the last char means no checksum
  27665. body = text.slice(0, lastEquals);
  27666. checksum = text.slice(lastEquals + 1).substr(0, 4);
  27667. }
  27668. return { body: body, checksum: checksum };
  27669. }
  27670. /**
  27671. * DeArmor an OpenPGP armored message; verify the checksum and return
  27672. * the encoded bytes
  27673. * @param {String} text OpenPGP armored message
  27674. * @returns {Promise<Object>} An object with attribute "text" containing the message text,
  27675. * an attribute "data" containing a stream of bytes and "type" for the ASCII armor type
  27676. * @async
  27677. * @static
  27678. */
  27679. function dearmor(input) {
  27680. return new Promise(async (resolve, reject) => {
  27681. try {
  27682. const reSplit = /^-----[^-]+-----$/m;
  27683. const reEmptyLine = /^[ \f\r\t\u00a0\u2000-\u200a\u202f\u205f\u3000]*$/;
  27684. let type;
  27685. const headers = [];
  27686. let lastHeaders = headers;
  27687. let headersDone;
  27688. let text = [];
  27689. let textDone;
  27690. let checksum;
  27691. let data = _base2.default.decode(_webStreamTools2.default.transformPair(input, async (readable, writable) => {
  27692. const reader = _webStreamTools2.default.getReader(readable);
  27693. try {
  27694. while (true) {
  27695. let line = await reader.readLine();
  27696. if (line === undefined) {
  27697. throw new Error('Misformed armored text');
  27698. }
  27699. // remove trailing whitespace at end of lines
  27700. line = _util2.default.removeTrailingSpaces(line.replace(/[\r\n]/g, ''));
  27701. if (!type) {
  27702. if (reSplit.test(line)) {
  27703. type = getType(line);
  27704. }
  27705. } else if (!headersDone) {
  27706. if (reSplit.test(line)) {
  27707. reject(new Error('Mandatory blank line missing between armor headers and armor data'));
  27708. }
  27709. if (!reEmptyLine.test(line)) {
  27710. lastHeaders.push(line);
  27711. } else {
  27712. verifyHeaders(lastHeaders);
  27713. headersDone = true;
  27714. if (textDone || type !== 2) {
  27715. resolve({ text, data, headers, type });
  27716. break;
  27717. }
  27718. }
  27719. } else if (!textDone && type === 2) {
  27720. if (!reSplit.test(line)) {
  27721. // Reverse dash-escaping for msg
  27722. text.push(line.replace(/^- /, ''));
  27723. } else {
  27724. text = text.join('\r\n');
  27725. textDone = true;
  27726. verifyHeaders(lastHeaders);
  27727. lastHeaders = [];
  27728. headersDone = false;
  27729. }
  27730. }
  27731. }
  27732. } catch (e) {
  27733. reject(e);
  27734. return;
  27735. }
  27736. const writer = _webStreamTools2.default.getWriter(writable);
  27737. try {
  27738. while (true) {
  27739. await writer.ready;
  27740. var _ref = await reader.read();
  27741. const done = _ref.done,
  27742. value = _ref.value;
  27743. if (done) {
  27744. throw new Error('Misformed armored text');
  27745. }
  27746. const line = value + '';
  27747. if (line.indexOf('=') === -1 && line.indexOf('-') === -1) {
  27748. await writer.write(line);
  27749. } else {
  27750. let remainder = await reader.readToEnd();
  27751. if (!remainder.length) remainder = '';
  27752. remainder = line + remainder;
  27753. remainder = _util2.default.removeTrailingSpaces(remainder.replace(/\r/g, ''));
  27754. const parts = remainder.split(reSplit);
  27755. if (parts.length === 1) {
  27756. throw new Error('Misformed armored text');
  27757. }
  27758. const split = splitChecksum(parts[0].slice(0, -1));
  27759. checksum = split.checksum;
  27760. await writer.write(split.body);
  27761. break;
  27762. }
  27763. }
  27764. await writer.ready;
  27765. await writer.close();
  27766. } catch (e) {
  27767. await writer.abort(e);
  27768. }
  27769. }));
  27770. data = _webStreamTools2.default.transformPair(data, async (readable, writable) => {
  27771. const checksumVerified = getCheckSum(_webStreamTools2.default.passiveClone(readable));
  27772. await _webStreamTools2.default.pipe(readable, writable, {
  27773. preventClose: true
  27774. });
  27775. const writer = _webStreamTools2.default.getWriter(writable);
  27776. try {
  27777. const checksumVerifiedString = await _webStreamTools2.default.readToEnd(checksumVerified);
  27778. if (checksum !== checksumVerifiedString && (checksum || _config2.default.checksum_required)) {
  27779. throw new Error("Ascii armor integrity check on message failed: '" + checksum + "' should be '" + checksumVerifiedString + "'");
  27780. }
  27781. await writer.ready;
  27782. await writer.close();
  27783. } catch (e) {
  27784. await writer.abort(e);
  27785. }
  27786. });
  27787. } catch (e) {
  27788. reject(e);
  27789. }
  27790. });
  27791. }
  27792. /**
  27793. * Armor an OpenPGP binary packet block
  27794. * @param {Integer} messagetype type of the message
  27795. * @param body
  27796. * @param {Integer} partindex
  27797. * @param {Integer} parttotal
  27798. * @param {String} customComment (optional) additional comment to add to the armored string
  27799. * @returns {String | ReadableStream<String>} Armored text
  27800. * @static
  27801. */
  27802. function armor(messagetype, body, partindex, parttotal, customComment) {
  27803. let text;
  27804. let hash;
  27805. if (messagetype === _enums2.default.armor.signed) {
  27806. text = body.text;
  27807. hash = body.hash;
  27808. body = body.data;
  27809. }
  27810. const bodyClone = _webStreamTools2.default.passiveClone(body);
  27811. const result = [];
  27812. switch (messagetype) {
  27813. case _enums2.default.armor.multipart_section:
  27814. result.push("-----BEGIN PGP MESSAGE, PART " + partindex + "/" + parttotal + "-----\r\n");
  27815. result.push(addheader(customComment));
  27816. result.push(_base2.default.encode(body));
  27817. result.push("\r\n=", getCheckSum(bodyClone), "\r\n");
  27818. result.push("-----END PGP MESSAGE, PART " + partindex + "/" + parttotal + "-----\r\n");
  27819. break;
  27820. case _enums2.default.armor.multipart_last:
  27821. result.push("-----BEGIN PGP MESSAGE, PART " + partindex + "-----\r\n");
  27822. result.push(addheader(customComment));
  27823. result.push(_base2.default.encode(body));
  27824. result.push("\r\n=", getCheckSum(bodyClone), "\r\n");
  27825. result.push("-----END PGP MESSAGE, PART " + partindex + "-----\r\n");
  27826. break;
  27827. case _enums2.default.armor.signed:
  27828. result.push("\r\n-----BEGIN PGP SIGNED MESSAGE-----\r\n");
  27829. result.push("Hash: " + hash + "\r\n\r\n");
  27830. result.push(text.replace(/^-/mg, "- -"));
  27831. result.push("\r\n-----BEGIN PGP SIGNATURE-----\r\n");
  27832. result.push(addheader(customComment));
  27833. result.push(_base2.default.encode(body));
  27834. result.push("\r\n=", getCheckSum(bodyClone), "\r\n");
  27835. result.push("-----END PGP SIGNATURE-----\r\n");
  27836. break;
  27837. case _enums2.default.armor.message:
  27838. result.push("-----BEGIN PGP MESSAGE-----\r\n");
  27839. result.push(addheader(customComment));
  27840. result.push(_base2.default.encode(body));
  27841. result.push("\r\n=", getCheckSum(bodyClone), "\r\n");
  27842. result.push("-----END PGP MESSAGE-----\r\n");
  27843. break;
  27844. case _enums2.default.armor.public_key:
  27845. result.push("-----BEGIN PGP PUBLIC KEY BLOCK-----\r\n");
  27846. result.push(addheader(customComment));
  27847. result.push(_base2.default.encode(body));
  27848. result.push("\r\n=", getCheckSum(bodyClone), "\r\n");
  27849. result.push("-----END PGP PUBLIC KEY BLOCK-----\r\n");
  27850. break;
  27851. case _enums2.default.armor.private_key:
  27852. result.push("-----BEGIN PGP PRIVATE KEY BLOCK-----\r\n");
  27853. result.push(addheader(customComment));
  27854. result.push(_base2.default.encode(body));
  27855. result.push("\r\n=", getCheckSum(bodyClone), "\r\n");
  27856. result.push("-----END PGP PRIVATE KEY BLOCK-----\r\n");
  27857. break;
  27858. case _enums2.default.armor.signature:
  27859. result.push("-----BEGIN PGP SIGNATURE-----\r\n");
  27860. result.push(addheader(customComment));
  27861. result.push(_base2.default.encode(body));
  27862. result.push("\r\n=", getCheckSum(bodyClone), "\r\n");
  27863. result.push("-----END PGP SIGNATURE-----\r\n");
  27864. break;
  27865. }
  27866. return _util2.default.concat(result);
  27867. }
  27868. exports.default = {
  27869. encode: armor,
  27870. decode: dearmor
  27871. };
  27872. },{"../config":79,"../enums.js":113,"../util":158,"./base64.js":112,"web-stream-tools":75}],112:[function(require,module,exports){
  27873. 'use strict';
  27874. Object.defineProperty(exports, "__esModule", {
  27875. value: true
  27876. });
  27877. var _webStreamTools = require('web-stream-tools');
  27878. var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
  27879. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  27880. const b64s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; // Standard radix-64
  27881. /* OpenPGP radix-64/base64 string encoding/decoding
  27882. * Copyright 2005 Herbert Hanewinkel, www.haneWIN.de
  27883. * version 1.0, check www.haneWIN.de for the latest version
  27884. *
  27885. * This software is provided as-is, without express or implied warranty.
  27886. * Permission to use, copy, modify, distribute or sell this software, with or
  27887. * without fee, for any purpose and by any individual or organization, is hereby
  27888. * granted, provided that the above copyright notice and this paragraph appear
  27889. * in all copies. Distribution as a part of an application or binary must
  27890. * include the above copyright notice in the documentation and/or other materials
  27891. * provided with the application or distribution.
  27892. */
  27893. /**
  27894. * @requires web-stream-tools
  27895. * @module encoding/base64
  27896. */
  27897. const b64u = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'; // URL-safe radix-64
  27898. const b64toByte = [];
  27899. for (let i = 0; i < b64s.length; i++) {
  27900. b64toByte[b64s.charCodeAt(i)] = i;
  27901. }
  27902. b64toByte[b64u.charCodeAt(62)] = 62;
  27903. b64toByte[b64u.charCodeAt(63)] = 63;
  27904. /**
  27905. * Convert binary array to radix-64
  27906. * @param {Uint8Array | ReadableStream<Uint8Array>} t Uint8Array to convert
  27907. * @param {bool} u if true, output is URL-safe
  27908. * @returns {String | ReadableStream<String>} radix-64 version of input string
  27909. * @static
  27910. */
  27911. function s2r(t, u = false) {
  27912. // TODO check btoa alternative
  27913. const b64 = u ? b64u : b64s;
  27914. let a;
  27915. let c;
  27916. let l = 0;
  27917. let s = 0;
  27918. return _webStreamTools2.default.transform(t, value => {
  27919. const r = [];
  27920. const tl = value.length;
  27921. for (let n = 0; n < tl; n++) {
  27922. if (l && l % 60 === 0 && !u) {
  27923. r.push("\r\n");
  27924. }
  27925. c = value[n];
  27926. if (s === 0) {
  27927. r.push(b64.charAt(c >> 2 & 63));
  27928. a = (c & 3) << 4;
  27929. } else if (s === 1) {
  27930. r.push(b64.charAt(a | c >> 4 & 15));
  27931. a = (c & 15) << 2;
  27932. } else if (s === 2) {
  27933. r.push(b64.charAt(a | c >> 6 & 3));
  27934. l += 1;
  27935. if (l % 60 === 0 && !u) {
  27936. r.push("\r\n");
  27937. }
  27938. r.push(b64.charAt(c & 63));
  27939. }
  27940. l += 1;
  27941. s += 1;
  27942. if (s === 3) {
  27943. s = 0;
  27944. }
  27945. }
  27946. return r.join('');
  27947. }, () => {
  27948. const r = [];
  27949. if (s > 0) {
  27950. r.push(b64.charAt(a));
  27951. l += 1;
  27952. if (l % 60 === 0 && !u) {
  27953. r.push("\r\n");
  27954. }
  27955. if (!u) {
  27956. r.push('=');
  27957. l += 1;
  27958. }
  27959. }
  27960. if (s === 1 && !u) {
  27961. if (l % 60 === 0 && !u) {
  27962. r.push("\r\n");
  27963. }
  27964. r.push('=');
  27965. }
  27966. return r.join('');
  27967. });
  27968. }
  27969. /**
  27970. * Convert radix-64 to binary array
  27971. * @param {String | ReadableStream<String>} t radix-64 string to convert
  27972. * @returns {Uint8Array | ReadableStream<Uint8Array>} binary array version of input string
  27973. * @static
  27974. */
  27975. function r2s(t) {
  27976. // TODO check atob alternative
  27977. let c;
  27978. let s = 0;
  27979. let a = 0;
  27980. return _webStreamTools2.default.transform(t, value => {
  27981. const tl = value.length;
  27982. const r = new Uint8Array(Math.ceil(0.75 * tl));
  27983. let index = 0;
  27984. for (let n = 0; n < tl; n++) {
  27985. c = b64toByte[value.charCodeAt(n)];
  27986. if (c >= 0) {
  27987. if (s) {
  27988. r[index++] = a | c >> 6 - s & 255;
  27989. }
  27990. s = s + 2 & 7;
  27991. a = c << s & 255;
  27992. }
  27993. }
  27994. return r.subarray(0, index);
  27995. });
  27996. }
  27997. exports.default = {
  27998. encode: s2r,
  27999. decode: r2s
  28000. };
  28001. },{"web-stream-tools":75}],113:[function(require,module,exports){
  28002. "use strict";
  28003. Object.defineProperty(exports, "__esModule", {
  28004. value: true
  28005. });
  28006. /**
  28007. * @module enums
  28008. */
  28009. const byValue = Symbol('byValue');
  28010. exports.default = {
  28011. /** Maps curve names under various standards to one
  28012. * @see {@link https://wiki.gnupg.org/ECC|ECC - GnuPG wiki}
  28013. * @enum {String}
  28014. * @readonly
  28015. */
  28016. curve: {
  28017. /** NIST P-256 Curve */
  28018. "p256": "p256",
  28019. "P-256": "p256",
  28020. "secp256r1": "p256",
  28021. "prime256v1": "p256",
  28022. "1.2.840.10045.3.1.7": "p256",
  28023. "2a8648ce3d030107": "p256",
  28024. "2A8648CE3D030107": "p256",
  28025. /** NIST P-384 Curve */
  28026. "p384": "p384",
  28027. "P-384": "p384",
  28028. "secp384r1": "p384",
  28029. "1.3.132.0.34": "p384",
  28030. "2b81040022": "p384",
  28031. "2B81040022": "p384",
  28032. /** NIST P-521 Curve */
  28033. "p521": "p521",
  28034. "P-521": "p521",
  28035. "secp521r1": "p521",
  28036. "1.3.132.0.35": "p521",
  28037. "2b81040023": "p521",
  28038. "2B81040023": "p521",
  28039. /** SECG SECP256k1 Curve */
  28040. "secp256k1": "secp256k1",
  28041. "1.3.132.0.10": "secp256k1",
  28042. "2b8104000a": "secp256k1",
  28043. "2B8104000A": "secp256k1",
  28044. /** Ed25519 */
  28045. "ED25519": "ed25519",
  28046. "ed25519": "ed25519",
  28047. "Ed25519": "ed25519",
  28048. "1.3.6.1.4.1.11591.15.1": "ed25519",
  28049. "2b06010401da470f01": "ed25519",
  28050. "2B06010401DA470F01": "ed25519",
  28051. /** Curve25519 */
  28052. "X25519": "curve25519",
  28053. "cv25519": "curve25519",
  28054. "curve25519": "curve25519",
  28055. "Curve25519": "curve25519",
  28056. "1.3.6.1.4.1.3029.1.5.1": "curve25519",
  28057. "2b060104019755010501": "curve25519",
  28058. "2B060104019755010501": "curve25519",
  28059. /** BrainpoolP256r1 Curve */
  28060. "brainpoolP256r1": "brainpoolP256r1",
  28061. "1.3.36.3.3.2.8.1.1.7": "brainpoolP256r1",
  28062. "2b2403030208010107": "brainpoolP256r1",
  28063. "2B2403030208010107": "brainpoolP256r1",
  28064. /** BrainpoolP384r1 Curve */
  28065. "brainpoolP384r1": "brainpoolP384r1",
  28066. "1.3.36.3.3.2.8.1.1.11": "brainpoolP384r1",
  28067. "2b240303020801010b": "brainpoolP384r1",
  28068. "2B240303020801010B": "brainpoolP384r1",
  28069. /** BrainpoolP512r1 Curve */
  28070. "brainpoolP512r1": "brainpoolP512r1",
  28071. "1.3.36.3.3.2.8.1.1.13": "brainpoolP512r1",
  28072. "2b240303020801010d": "brainpoolP512r1",
  28073. "2B240303020801010D": "brainpoolP512r1"
  28074. },
  28075. /** A string to key specifier type
  28076. * @enum {Integer}
  28077. * @readonly
  28078. */
  28079. s2k: {
  28080. simple: 0,
  28081. salted: 1,
  28082. iterated: 3,
  28083. gnu: 101
  28084. },
  28085. /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.1|RFC4880bis-04, section 9.1}
  28086. * @enum {Integer}
  28087. * @readonly
  28088. */
  28089. publicKey: {
  28090. /** RSA (Encrypt or Sign) [HAC] */
  28091. rsa_encrypt_sign: 1,
  28092. /** RSA (Encrypt only) [HAC] */
  28093. rsa_encrypt: 2,
  28094. /** RSA (Sign only) [HAC] */
  28095. rsa_sign: 3,
  28096. /** Elgamal (Encrypt only) [ELGAMAL] [HAC] */
  28097. elgamal: 16,
  28098. /** DSA (Sign only) [FIPS186] [HAC] */
  28099. dsa: 17,
  28100. /** ECDH (Encrypt only) [RFC6637] */
  28101. ecdh: 18,
  28102. /** ECDSA (Sign only) [RFC6637] */
  28103. ecdsa: 19,
  28104. /** EdDSA (Sign only)
  28105. * [{@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] */
  28106. eddsa: 22,
  28107. /** Reserved for AEDH */
  28108. aedh: 23,
  28109. /** Reserved for AEDSA */
  28110. aedsa: 24
  28111. },
  28112. /** {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2}
  28113. * @enum {Integer}
  28114. * @readonly
  28115. */
  28116. symmetric: {
  28117. plaintext: 0,
  28118. /** Not implemented! */
  28119. idea: 1,
  28120. '3des': 2,
  28121. tripledes: 2,
  28122. cast5: 3,
  28123. blowfish: 4,
  28124. aes128: 7,
  28125. aes192: 8,
  28126. aes256: 9,
  28127. twofish: 10
  28128. },
  28129. /** {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3}
  28130. * @enum {Integer}
  28131. * @readonly
  28132. */
  28133. compression: {
  28134. uncompressed: 0,
  28135. /** RFC1951 */
  28136. zip: 1,
  28137. /** RFC1950 */
  28138. zlib: 2,
  28139. bzip2: 3
  28140. },
  28141. /** {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4}
  28142. * @enum {Integer}
  28143. * @readonly
  28144. */
  28145. hash: {
  28146. md5: 1,
  28147. sha1: 2,
  28148. ripemd: 3,
  28149. sha256: 8,
  28150. sha384: 9,
  28151. sha512: 10,
  28152. sha224: 11
  28153. },
  28154. /** A list of hash names as accepted by webCrypto functions.
  28155. * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo}
  28156. * @enum {String}
  28157. */
  28158. webHash: {
  28159. 'SHA-1': 2,
  28160. 'SHA-256': 8,
  28161. 'SHA-384': 9,
  28162. 'SHA-512': 10
  28163. },
  28164. /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.6|RFC4880bis-04, section 9.6}
  28165. * @enum {Integer}
  28166. * @readonly
  28167. */
  28168. aead: {
  28169. eax: 1,
  28170. ocb: 2,
  28171. experimental_gcm: 100 // Private algorithm
  28172. },
  28173. /** A list of packet types and numeric tags associated with them.
  28174. * @enum {Integer}
  28175. * @readonly
  28176. */
  28177. packet: {
  28178. publicKeyEncryptedSessionKey: 1,
  28179. signature: 2,
  28180. symEncryptedSessionKey: 3,
  28181. onePassSignature: 4,
  28182. secretKey: 5,
  28183. publicKey: 6,
  28184. secretSubkey: 7,
  28185. compressed: 8,
  28186. symmetricallyEncrypted: 9,
  28187. marker: 10,
  28188. literal: 11,
  28189. trust: 12,
  28190. userid: 13,
  28191. publicSubkey: 14,
  28192. userAttribute: 17,
  28193. symEncryptedIntegrityProtected: 18,
  28194. modificationDetectionCode: 19,
  28195. symEncryptedAEADProtected: 20 // see IETF draft: https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1
  28196. },
  28197. /** Data types in the literal packet
  28198. * @enum {Integer}
  28199. * @readonly
  28200. */
  28201. literal: {
  28202. /** Binary data 'b' */
  28203. binary: 'b'.charCodeAt(),
  28204. /** Text data 't' */
  28205. text: 't'.charCodeAt(),
  28206. /** Utf8 data 'u' */
  28207. utf8: 'u'.charCodeAt(),
  28208. /** MIME message body part 'm' */
  28209. mime: 'm'.charCodeAt()
  28210. },
  28211. /** One pass signature packet type
  28212. * @enum {Integer}
  28213. * @readonly
  28214. */
  28215. signature: {
  28216. /** 0x00: Signature of a binary document. */
  28217. binary: 0,
  28218. /** 0x01: Signature of a canonical text document.
  28219. *
  28220. * Canonicalyzing the document by converting line endings. */
  28221. text: 1,
  28222. /** 0x02: Standalone signature.
  28223. *
  28224. * This signature is a signature of only its own subpacket contents.
  28225. * It is calculated identically to a signature over a zero-lengh
  28226. * binary document. Note that it doesn't make sense to have a V3
  28227. * standalone signature. */
  28228. standalone: 2,
  28229. /** 0x10: Generic certification of a User ID and Public-Key packet.
  28230. *
  28231. * The issuer of this certification does not make any particular
  28232. * assertion as to how well the certifier has checked that the owner
  28233. * of the key is in fact the person described by the User ID. */
  28234. cert_generic: 16,
  28235. /** 0x11: Persona certification of a User ID and Public-Key packet.
  28236. *
  28237. * The issuer of this certification has not done any verification of
  28238. * the claim that the owner of this key is the User ID specified. */
  28239. cert_persona: 17,
  28240. /** 0x12: Casual certification of a User ID and Public-Key packet.
  28241. *
  28242. * The issuer of this certification has done some casual
  28243. * verification of the claim of identity. */
  28244. cert_casual: 18,
  28245. /** 0x13: Positive certification of a User ID and Public-Key packet.
  28246. *
  28247. * The issuer of this certification has done substantial
  28248. * verification of the claim of identity.
  28249. *
  28250. * Most OpenPGP implementations make their "key signatures" as 0x10
  28251. * certifications. Some implementations can issue 0x11-0x13
  28252. * certifications, but few differentiate between the types. */
  28253. cert_positive: 19,
  28254. /** 0x30: Certification revocation signature
  28255. *
  28256. * This signature revokes an earlier User ID certification signature
  28257. * (signature class 0x10 through 0x13) or direct-key signature
  28258. * (0x1F). It should be issued by the same key that issued the
  28259. * revoked signature or an authorized revocation key. The signature
  28260. * is computed over the same data as the certificate that it
  28261. * revokes, and should have a later creation date than that
  28262. * certificate. */
  28263. cert_revocation: 48,
  28264. /** 0x18: Subkey Binding Signature
  28265. *
  28266. * This signature is a statement by the top-level signing key that
  28267. * indicates that it owns the subkey. This signature is calculated
  28268. * directly on the primary key and subkey, and not on any User ID or
  28269. * other packets. A signature that binds a signing subkey MUST have
  28270. * an Embedded Signature subpacket in this binding signature that
  28271. * contains a 0x19 signature made by the signing subkey on the
  28272. * primary key and subkey. */
  28273. subkey_binding: 24,
  28274. /** 0x19: Primary Key Binding Signature
  28275. *
  28276. * This signature is a statement by a signing subkey, indicating
  28277. * that it is owned by the primary key and subkey. This signature
  28278. * is calculated the same way as a 0x18 signature: directly on the
  28279. * primary key and subkey, and not on any User ID or other packets.
  28280. *
  28281. * When a signature is made over a key, the hash data starts with the
  28282. * octet 0x99, followed by a two-octet length of the key, and then body
  28283. * of the key packet. (Note that this is an old-style packet header for
  28284. * a key packet with two-octet length.) A subkey binding signature
  28285. * (type 0x18) or primary key binding signature (type 0x19) then hashes
  28286. * the subkey using the same format as the main key (also using 0x99 as
  28287. * the first octet). */
  28288. key_binding: 25,
  28289. /** 0x1F: Signature directly on a key
  28290. *
  28291. * This signature is calculated directly on a key. It binds the
  28292. * information in the Signature subpackets to the key, and is
  28293. * appropriate to be used for subpackets that provide information
  28294. * about the key, such as the Revocation Key subpacket. It is also
  28295. * appropriate for statements that non-self certifiers want to make
  28296. * about the key itself, rather than the binding between a key and a
  28297. * name. */
  28298. key: 31,
  28299. /** 0x20: Key revocation signature
  28300. *
  28301. * The signature is calculated directly on the key being revoked. A
  28302. * revoked key is not to be used. Only revocation signatures by the
  28303. * key being revoked, or by an authorized revocation key, should be
  28304. * considered valid revocation signatures.a */
  28305. key_revocation: 32,
  28306. /** 0x28: Subkey revocation signature
  28307. *
  28308. * The signature is calculated directly on the subkey being revoked.
  28309. * A revoked subkey is not to be used. Only revocation signatures
  28310. * by the top-level signature key that is bound to this subkey, or
  28311. * by an authorized revocation key, should be considered valid
  28312. * revocation signatures.
  28313. *
  28314. * Key revocation signatures (types 0x20 and 0x28)
  28315. * hash only the key being revoked. */
  28316. subkey_revocation: 40,
  28317. /** 0x40: Timestamp signature.
  28318. * This signature is only meaningful for the timestamp contained in
  28319. * it. */
  28320. timestamp: 64,
  28321. /** 0x50: Third-Party Confirmation signature.
  28322. *
  28323. * This signature is a signature over some other OpenPGP Signature
  28324. * packet(s). It is analogous to a notary seal on the signed data.
  28325. * A third-party signature SHOULD include Signature Target
  28326. * subpacket(s) to give easy identification. Note that we really do
  28327. * mean SHOULD. There are plausible uses for this (such as a blind
  28328. * party that only sees the signature, not the key or source
  28329. * document) that cannot include a target subpacket. */
  28330. third_party: 80
  28331. },
  28332. /** Signature subpacket type
  28333. * @enum {Integer}
  28334. * @readonly
  28335. */
  28336. signatureSubpacket: {
  28337. signature_creation_time: 2,
  28338. signature_expiration_time: 3,
  28339. exportable_certification: 4,
  28340. trust_signature: 5,
  28341. regular_expression: 6,
  28342. revocable: 7,
  28343. key_expiration_time: 9,
  28344. placeholder_backwards_compatibility: 10,
  28345. preferred_symmetric_algorithms: 11,
  28346. revocation_key: 12,
  28347. issuer: 16,
  28348. notation_data: 20,
  28349. preferred_hash_algorithms: 21,
  28350. preferred_compression_algorithms: 22,
  28351. key_server_preferences: 23,
  28352. preferred_key_server: 24,
  28353. primary_user_id: 25,
  28354. policy_uri: 26,
  28355. key_flags: 27,
  28356. signers_user_id: 28,
  28357. reason_for_revocation: 29,
  28358. features: 30,
  28359. signature_target: 31,
  28360. embedded_signature: 32,
  28361. issuer_fingerprint: 33,
  28362. preferred_aead_algorithms: 34
  28363. },
  28364. /** Key flags
  28365. * @enum {Integer}
  28366. * @readonly
  28367. */
  28368. keyFlags: {
  28369. /** 0x01 - This key may be used to certify other keys. */
  28370. certify_keys: 1,
  28371. /** 0x02 - This key may be used to sign data. */
  28372. sign_data: 2,
  28373. /** 0x04 - This key may be used to encrypt communications. */
  28374. encrypt_communication: 4,
  28375. /** 0x08 - This key may be used to encrypt storage. */
  28376. encrypt_storage: 8,
  28377. /** 0x10 - The private component of this key may have been split
  28378. * by a secret-sharing mechanism. */
  28379. split_private_key: 16,
  28380. /** 0x20 - This key may be used for authentication. */
  28381. authentication: 32,
  28382. /** 0x80 - The private component of this key may be in the
  28383. * possession of more than one person. */
  28384. shared_private_key: 128
  28385. },
  28386. /** Key status
  28387. * @enum {Integer}
  28388. * @readonly
  28389. */
  28390. keyStatus: {
  28391. invalid: 0,
  28392. expired: 1,
  28393. revoked: 2,
  28394. valid: 3,
  28395. no_self_cert: 4
  28396. },
  28397. /** Armor type
  28398. * @enum {Integer}
  28399. * @readonly
  28400. */
  28401. armor: {
  28402. multipart_section: 0,
  28403. multipart_last: 1,
  28404. signed: 2,
  28405. message: 3,
  28406. public_key: 4,
  28407. private_key: 5,
  28408. signature: 6
  28409. },
  28410. /** {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23}
  28411. * @enum {Integer}
  28412. * @readonly
  28413. */
  28414. reasonForRevocation: {
  28415. /** No reason specified (key revocations or cert revocations) */
  28416. no_reason: 0,
  28417. /** Key is superseded (key revocations) */
  28418. key_superseded: 1,
  28419. /** Key material has been compromised (key revocations) */
  28420. key_compromised: 2,
  28421. /** Key is retired and no longer used (key revocations) */
  28422. key_retired: 3,
  28423. /** User ID information is no longer valid (cert revocations) */
  28424. userid_invalid: 32
  28425. },
  28426. /** {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25}
  28427. * @enum {Integer}
  28428. * @readonly
  28429. */
  28430. features: {
  28431. /** 0x01 - Modification Detection (packets 18 and 19) */
  28432. modification_detection: 1,
  28433. /** 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5
  28434. * Symmetric-Key Encrypted Session Key Packets (packet 3) */
  28435. aead: 2,
  28436. /** 0x04 - Version 5 Public-Key Packet format and corresponding new
  28437. * fingerprint format */
  28438. v5_keys: 4
  28439. },
  28440. /** Asserts validity and converts from string/integer to integer. */
  28441. write: function write(type, e) {
  28442. if (typeof e === 'number') {
  28443. e = this.read(type, e);
  28444. }
  28445. if (type[e] !== undefined) {
  28446. return type[e];
  28447. }
  28448. throw new Error('Invalid enum value.');
  28449. },
  28450. /** Converts from an integer to string. */
  28451. read: function read(type, e) {
  28452. if (!type[byValue]) {
  28453. type[byValue] = [];
  28454. Object.entries(type).forEach(([key, value]) => {
  28455. type[byValue][value] = key;
  28456. });
  28457. }
  28458. if (type[byValue][e] !== undefined) {
  28459. return type[byValue][e];
  28460. }
  28461. throw new Error('Invalid enum value.');
  28462. }
  28463. };
  28464. },{}],114:[function(require,module,exports){
  28465. 'use strict';
  28466. Object.defineProperty(exports, "__esModule", {
  28467. value: true
  28468. });
  28469. var _config = require('./config');
  28470. var _config2 = _interopRequireDefault(_config);
  28471. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  28472. /**
  28473. * Initialize the HKP client and configure it with the key server url and fetch function.
  28474. * @constructor
  28475. * @param {String} keyServerBaseUrl (optional) The HKP key server base url including
  28476. * the protocol to use, e.g. 'https://pgp.mit.edu'; defaults to
  28477. * openpgp.config.keyserver (https://keyserver.ubuntu.com)
  28478. */
  28479. function HKP(keyServerBaseUrl) {
  28480. this._baseUrl = keyServerBaseUrl || _config2.default.keyserver;
  28481. this._fetch = typeof window !== 'undefined' ? window.fetch : require('node-fetch');
  28482. }
  28483. /**
  28484. * Search for a public key on the key server either by key ID or part of the user ID.
  28485. * @param {String} options.keyID The long public key ID.
  28486. * @param {String} options.query This can be any part of the key user ID such as name
  28487. * or email address.
  28488. * @returns {Promise<String>} The ascii armored public key.
  28489. * @async
  28490. */
  28491. // OpenPGP.js - An OpenPGP implementation in javascript
  28492. // Copyright (C) 2015 Tankred Hase
  28493. //
  28494. // This library is free software; you can redistribute it and/or
  28495. // modify it under the terms of the GNU Lesser General Public
  28496. // License as published by the Free Software Foundation; either
  28497. // version 3.0 of the License, or (at your option) any later version.
  28498. //
  28499. // This library is distributed in the hope that it will be useful,
  28500. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  28501. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  28502. // Lesser General Public License for more details.
  28503. //
  28504. // You should have received a copy of the GNU Lesser General Public
  28505. // License along with this library; if not, write to the Free Software
  28506. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  28507. /**
  28508. * @fileoverview This class implements a client for the OpenPGP HTTP Keyserver Protocol (HKP)
  28509. * in order to lookup and upload keys on standard public key servers.
  28510. * @module hkp
  28511. */
  28512. HKP.prototype.lookup = function (options) {
  28513. let uri = this._baseUrl + '/pks/lookup?op=get&options=mr&search=';
  28514. const fetch = this._fetch;
  28515. if (options.keyId) {
  28516. uri += '0x' + encodeURIComponent(options.keyId);
  28517. } else if (options.query) {
  28518. uri += encodeURIComponent(options.query);
  28519. } else {
  28520. throw new Error('You must provide a query parameter!');
  28521. }
  28522. return fetch(uri).then(function (response) {
  28523. if (response.status === 200) {
  28524. return response.text();
  28525. }
  28526. }).then(function (publicKeyArmored) {
  28527. if (!publicKeyArmored || publicKeyArmored.indexOf('-----END PGP PUBLIC KEY BLOCK-----') < 0) {
  28528. return;
  28529. }
  28530. return publicKeyArmored.trim();
  28531. });
  28532. };
  28533. /**
  28534. * Upload a public key to the server.
  28535. * @param {String} publicKeyArmored An ascii armored public key to be uploaded.
  28536. * @returns {Promise}
  28537. * @async
  28538. */
  28539. HKP.prototype.upload = function (publicKeyArmored) {
  28540. const uri = this._baseUrl + '/pks/add';
  28541. const fetch = this._fetch;
  28542. return fetch(uri, {
  28543. method: 'post',
  28544. headers: {
  28545. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
  28546. },
  28547. body: 'keytext=' + encodeURIComponent(publicKeyArmored)
  28548. });
  28549. };
  28550. exports.default = HKP;
  28551. },{"./config":79,"node-fetch":"node-fetch"}],115:[function(require,module,exports){
  28552. 'use strict';
  28553. Object.defineProperty(exports, "__esModule", {
  28554. value: true
  28555. });
  28556. exports.lightweight = exports.WKD = exports.HKP = exports.AsyncProxy = exports.Keyring = exports.crypto = exports.config = exports.enums = exports.armor = exports.stream = exports.OID = exports.KDFParams = exports.ECDHSymmetricKey = exports.Keyid = exports.S2K = exports.MPI = exports.packet = exports.util = exports.cleartext = exports.message = exports.signature = exports.key = exports.destroyWorker = exports.getWorker = exports.initWorker = exports.decryptSessionKeys = exports.encryptSessionKey = exports.decryptKey = exports.revokeKey = exports.reformatKey = exports.generateKey = exports.verify = exports.sign = exports.decrypt = exports.encrypt = undefined;
  28557. var _openpgp = require('./openpgp');
  28558. Object.defineProperty(exports, 'encrypt', {
  28559. enumerable: true,
  28560. get: function get() {
  28561. return _openpgp.encrypt;
  28562. }
  28563. });
  28564. Object.defineProperty(exports, 'decrypt', {
  28565. enumerable: true,
  28566. get: function get() {
  28567. return _openpgp.decrypt;
  28568. }
  28569. });
  28570. Object.defineProperty(exports, 'sign', {
  28571. enumerable: true,
  28572. get: function get() {
  28573. return _openpgp.sign;
  28574. }
  28575. });
  28576. Object.defineProperty(exports, 'verify', {
  28577. enumerable: true,
  28578. get: function get() {
  28579. return _openpgp.verify;
  28580. }
  28581. });
  28582. Object.defineProperty(exports, 'generateKey', {
  28583. enumerable: true,
  28584. get: function get() {
  28585. return _openpgp.generateKey;
  28586. }
  28587. });
  28588. Object.defineProperty(exports, 'reformatKey', {
  28589. enumerable: true,
  28590. get: function get() {
  28591. return _openpgp.reformatKey;
  28592. }
  28593. });
  28594. Object.defineProperty(exports, 'revokeKey', {
  28595. enumerable: true,
  28596. get: function get() {
  28597. return _openpgp.revokeKey;
  28598. }
  28599. });
  28600. Object.defineProperty(exports, 'decryptKey', {
  28601. enumerable: true,
  28602. get: function get() {
  28603. return _openpgp.decryptKey;
  28604. }
  28605. });
  28606. Object.defineProperty(exports, 'encryptSessionKey', {
  28607. enumerable: true,
  28608. get: function get() {
  28609. return _openpgp.encryptSessionKey;
  28610. }
  28611. });
  28612. Object.defineProperty(exports, 'decryptSessionKeys', {
  28613. enumerable: true,
  28614. get: function get() {
  28615. return _openpgp.decryptSessionKeys;
  28616. }
  28617. });
  28618. Object.defineProperty(exports, 'initWorker', {
  28619. enumerable: true,
  28620. get: function get() {
  28621. return _openpgp.initWorker;
  28622. }
  28623. });
  28624. Object.defineProperty(exports, 'getWorker', {
  28625. enumerable: true,
  28626. get: function get() {
  28627. return _openpgp.getWorker;
  28628. }
  28629. });
  28630. Object.defineProperty(exports, 'destroyWorker', {
  28631. enumerable: true,
  28632. get: function get() {
  28633. return _openpgp.destroyWorker;
  28634. }
  28635. });
  28636. var _util = require('./util');
  28637. Object.defineProperty(exports, 'util', {
  28638. enumerable: true,
  28639. get: function get() {
  28640. return _interopRequireDefault(_util).default;
  28641. }
  28642. });
  28643. var _packet = require('./packet');
  28644. Object.defineProperty(exports, 'packet', {
  28645. enumerable: true,
  28646. get: function get() {
  28647. return _interopRequireDefault(_packet).default;
  28648. }
  28649. });
  28650. var _mpi = require('./type/mpi');
  28651. Object.defineProperty(exports, 'MPI', {
  28652. enumerable: true,
  28653. get: function get() {
  28654. return _interopRequireDefault(_mpi).default;
  28655. }
  28656. });
  28657. var _s2k = require('./type/s2k');
  28658. Object.defineProperty(exports, 'S2K', {
  28659. enumerable: true,
  28660. get: function get() {
  28661. return _interopRequireDefault(_s2k).default;
  28662. }
  28663. });
  28664. var _keyid = require('./type/keyid');
  28665. Object.defineProperty(exports, 'Keyid', {
  28666. enumerable: true,
  28667. get: function get() {
  28668. return _interopRequireDefault(_keyid).default;
  28669. }
  28670. });
  28671. var _ecdh_symkey = require('./type/ecdh_symkey');
  28672. Object.defineProperty(exports, 'ECDHSymmetricKey', {
  28673. enumerable: true,
  28674. get: function get() {
  28675. return _interopRequireDefault(_ecdh_symkey).default;
  28676. }
  28677. });
  28678. var _kdf_params = require('./type/kdf_params');
  28679. Object.defineProperty(exports, 'KDFParams', {
  28680. enumerable: true,
  28681. get: function get() {
  28682. return _interopRequireDefault(_kdf_params).default;
  28683. }
  28684. });
  28685. var _oid = require('./type/oid');
  28686. Object.defineProperty(exports, 'OID', {
  28687. enumerable: true,
  28688. get: function get() {
  28689. return _interopRequireDefault(_oid).default;
  28690. }
  28691. });
  28692. var _webStreamTools = require('web-stream-tools');
  28693. Object.defineProperty(exports, 'stream', {
  28694. enumerable: true,
  28695. get: function get() {
  28696. return _interopRequireDefault(_webStreamTools).default;
  28697. }
  28698. });
  28699. var _armor = require('./encoding/armor');
  28700. Object.defineProperty(exports, 'armor', {
  28701. enumerable: true,
  28702. get: function get() {
  28703. return _interopRequireDefault(_armor).default;
  28704. }
  28705. });
  28706. var _enums = require('./enums');
  28707. Object.defineProperty(exports, 'enums', {
  28708. enumerable: true,
  28709. get: function get() {
  28710. return _interopRequireDefault(_enums).default;
  28711. }
  28712. });
  28713. var _config = require('./config/config');
  28714. Object.defineProperty(exports, 'config', {
  28715. enumerable: true,
  28716. get: function get() {
  28717. return _interopRequireDefault(_config).default;
  28718. }
  28719. });
  28720. var _crypto = require('./crypto');
  28721. Object.defineProperty(exports, 'crypto', {
  28722. enumerable: true,
  28723. get: function get() {
  28724. return _interopRequireDefault(_crypto).default;
  28725. }
  28726. });
  28727. var _keyring = require('./keyring');
  28728. Object.defineProperty(exports, 'Keyring', {
  28729. enumerable: true,
  28730. get: function get() {
  28731. return _interopRequireDefault(_keyring).default;
  28732. }
  28733. });
  28734. var _async_proxy = require('./worker/async_proxy');
  28735. Object.defineProperty(exports, 'AsyncProxy', {
  28736. enumerable: true,
  28737. get: function get() {
  28738. return _interopRequireDefault(_async_proxy).default;
  28739. }
  28740. });
  28741. var _hkp = require('./hkp');
  28742. Object.defineProperty(exports, 'HKP', {
  28743. enumerable: true,
  28744. get: function get() {
  28745. return _interopRequireDefault(_hkp).default;
  28746. }
  28747. });
  28748. var _wkd = require('./wkd');
  28749. Object.defineProperty(exports, 'WKD', {
  28750. enumerable: true,
  28751. get: function get() {
  28752. return _interopRequireDefault(_wkd).default;
  28753. }
  28754. });
  28755. var openpgp = _interopRequireWildcard(_openpgp);
  28756. var _key = require('./key');
  28757. var keyMod = _interopRequireWildcard(_key);
  28758. var _signature = require('./signature');
  28759. var signatureMod = _interopRequireWildcard(_signature);
  28760. var _message = require('./message');
  28761. var messageMod = _interopRequireWildcard(_message);
  28762. var _cleartext = require('./cleartext');
  28763. var cleartextMod = _interopRequireWildcard(_cleartext);
  28764. var _lightweight_helper = require('./lightweight_helper');
  28765. var lightweightMod = _interopRequireWildcard(_lightweight_helper);
  28766. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  28767. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  28768. exports.default = openpgp;
  28769. /**
  28770. * Export each high level api function separately.
  28771. * Usage:
  28772. *
  28773. * import { encryptMessage } from 'openpgp.js'
  28774. * encryptMessage(keys, text)
  28775. */
  28776. /* eslint-disable import/newline-after-import, import/first */
  28777. /**
  28778. * Export high level api as default.
  28779. * Usage:
  28780. *
  28781. * import openpgp from 'openpgp.js'
  28782. * openpgp.encryptMessage(keys, text)
  28783. */
  28784. /**
  28785. * @see module:key
  28786. * @name module:openpgp.key
  28787. */
  28788. const key = exports.key = keyMod;
  28789. /**
  28790. * @see module:signature
  28791. * @name module:openpgp.signature
  28792. */
  28793. const signature = exports.signature = signatureMod;
  28794. /**
  28795. * @see module:message
  28796. * @name module:openpgp.message
  28797. */
  28798. const message = exports.message = messageMod;
  28799. /**
  28800. * @see module:cleartext
  28801. * @name module:openpgp.cleartext
  28802. */
  28803. const cleartext = exports.cleartext = cleartextMod;
  28804. /**
  28805. * @see module:util
  28806. * @name module:openpgp.util
  28807. */
  28808. /**
  28809. * @see module:lightweight
  28810. */
  28811. const lightweight = exports.lightweight = lightweightMod;
  28812. },{"./cleartext":77,"./config/config":78,"./crypto":94,"./encoding/armor":111,"./enums":113,"./hkp":114,"./key":118,"./keyring":122,"./lightweight_helper":125,"./message":126,"./openpgp":127,"./packet":131,"./signature":151,"./type/ecdh_symkey":152,"./type/kdf_params":153,"./type/keyid":154,"./type/mpi":155,"./type/oid":156,"./type/s2k":157,"./util":158,"./wkd":159,"./worker/async_proxy":160,"web-stream-tools":75}],116:[function(require,module,exports){
  28813. 'use strict';
  28814. Object.defineProperty(exports, "__esModule", {
  28815. value: true
  28816. });
  28817. exports.generate = generate;
  28818. exports.reformat = reformat;
  28819. exports.read = read;
  28820. exports.readArmored = readArmored;
  28821. var _packet = require('../packet');
  28822. var _packet2 = _interopRequireDefault(_packet);
  28823. var _key = require('./key');
  28824. var _key2 = _interopRequireDefault(_key);
  28825. var _helper = require('./helper');
  28826. var helper = _interopRequireWildcard(_helper);
  28827. var _enums = require('../enums');
  28828. var _enums2 = _interopRequireDefault(_enums);
  28829. var _util = require('../util');
  28830. var _util2 = _interopRequireDefault(_util);
  28831. var _config = require('../config');
  28832. var _config2 = _interopRequireDefault(_config);
  28833. var _armor = require('../encoding/armor');
  28834. var _armor2 = _interopRequireDefault(_armor);
  28835. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  28836. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  28837. /**
  28838. * Generates a new OpenPGP key. Supports RSA and ECC keys.
  28839. * Primary and subkey will be of same type.
  28840. * @param {module:enums.publicKey} [options.keyType=module:enums.publicKey.rsa_encrypt_sign]
  28841. * To indicate what type of key to make.
  28842. * RSA is 1. See {@link https://tools.ietf.org/html/rfc4880#section-9.1}
  28843. * @param {Integer} options.numBits number of bits for the key creation.
  28844. * @param {String|Array<String>} options.userIds
  28845. * Assumes already in form of "User Name <username@email.com>"
  28846. * If array is used, the first userId is set as primary user Id
  28847. * @param {String} options.passphrase The passphrase used to encrypt the resulting private key
  28848. * @param {Number} [options.keyExpirationTime=0]
  28849. * The number of seconds after the key creation time that the key expires
  28850. * @param {String} curve (optional) elliptic curve for ECC keys
  28851. * @param {Date} date Override the creation date of the key and the key signatures
  28852. * @param {Array<Object>} subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]
  28853. * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt
  28854. * @returns {Promise<module:key.Key>}
  28855. * @async
  28856. * @static
  28857. */
  28858. async function generate(options) {
  28859. options.sign = true; // primary key is always a signing key
  28860. options = helper.sanitizeKeyOptions(options);
  28861. options.subkeys = options.subkeys.map(function (subkey, index) {
  28862. return helper.sanitizeKeyOptions(options.subkeys[index], options);
  28863. });
  28864. let promises = [helper.generateSecretKey(options)];
  28865. promises = promises.concat(options.subkeys.map(helper.generateSecretSubkey));
  28866. return Promise.all(promises).then(packets => wrapKeyObject(packets[0], packets.slice(1), options));
  28867. }
  28868. /**
  28869. * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys.
  28870. * @param {module:key.Key} options.privateKey The private key to reformat
  28871. * @param {module:enums.publicKey} [options.keyType=module:enums.publicKey.rsa_encrypt_sign]
  28872. * @param {String|Array<String>} options.userIds
  28873. * Assumes already in form of "User Name <username@email.com>"
  28874. * If array is used, the first userId is set as primary user Id
  28875. * @param {String} options.passphrase The passphrase used to encrypt the resulting private key
  28876. * @param {Number} [options.keyExpirationTime=0]
  28877. * The number of seconds after the key creation time that the key expires
  28878. * @param {Date} date Override the creation date of the key and the key signatures
  28879. * @param {Array<Object>} subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]
  28880. *
  28881. * @returns {Promise<module:key.Key>}
  28882. * @async
  28883. * @static
  28884. */
  28885. // OpenPGP.js - An OpenPGP implementation in javascript
  28886. // Copyright (C) 2015-2016 Decentral
  28887. //
  28888. // This library is free software; you can redistribute it and/or
  28889. // modify it under the terms of the GNU Lesser General Public
  28890. // License as published by the Free Software Foundation; either
  28891. // version 3.0 of the License, or (at your option) any later version.
  28892. //
  28893. // This library is distributed in the hope that it will be useful,
  28894. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  28895. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  28896. // Lesser General Public License for more details.
  28897. //
  28898. // You should have received a copy of the GNU Lesser General Public
  28899. // License along with this library; if not, write to the Free Software
  28900. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  28901. /**
  28902. * @fileoverview Provides factory methods for key creation
  28903. * @requires packet
  28904. * @requires key/Key
  28905. * @requires key/helper
  28906. * @requires enums
  28907. * @requires util
  28908. * @requires config
  28909. * @requires armor
  28910. * @module key/factory
  28911. */
  28912. async function reformat(options) {
  28913. options = sanitize(options);
  28914. try {
  28915. const isDecrypted = options.privateKey.getKeys().every(key => key.isDecrypted());
  28916. if (!isDecrypted) {
  28917. await options.privateKey.decrypt();
  28918. }
  28919. } catch (err) {
  28920. throw new Error('Key not decrypted');
  28921. }
  28922. const packetlist = options.privateKey.toPacketlist();
  28923. let secretKeyPacket;
  28924. const secretSubkeyPackets = [];
  28925. for (let i = 0; i < packetlist.length; i++) {
  28926. if (packetlist[i].tag === _enums2.default.packet.secretKey) {
  28927. secretKeyPacket = packetlist[i];
  28928. } else if (packetlist[i].tag === _enums2.default.packet.secretSubkey) {
  28929. secretSubkeyPackets.push(packetlist[i]);
  28930. }
  28931. }
  28932. if (!secretKeyPacket) {
  28933. throw new Error('Key does not contain a secret key packet');
  28934. }
  28935. if (!options.subkeys) {
  28936. options.subkeys = await Promise.all(secretSubkeyPackets.map(async secretSubkeyPacket => ({
  28937. sign: (await options.privateKey.getSigningKey(secretSubkeyPacket.getKeyId(), null)) && !(await options.privateKey.getEncryptionKey(secretSubkeyPacket.getKeyId(), null))
  28938. })));
  28939. }
  28940. if (options.subkeys.length !== secretSubkeyPackets.length) {
  28941. throw new Error('Number of subkey options does not match number of subkeys');
  28942. }
  28943. options.subkeys = options.subkeys.map(function (subkey, index) {
  28944. return sanitize(options.subkeys[index], options);
  28945. });
  28946. return wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options);
  28947. function sanitize(options, subkeyDefaults = {}) {
  28948. options.keyExpirationTime = options.keyExpirationTime || subkeyDefaults.keyExpirationTime;
  28949. options.passphrase = _util2.default.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;
  28950. options.date = options.date || subkeyDefaults.date;
  28951. return options;
  28952. }
  28953. }
  28954. async function wrapKeyObject(secretKeyPacket, secretSubkeyPackets, options) {
  28955. // set passphrase protection
  28956. if (options.passphrase) {
  28957. await secretKeyPacket.encrypt(options.passphrase);
  28958. }
  28959. await Promise.all(secretSubkeyPackets.map(async function (secretSubkeyPacket, index) {
  28960. const subkeyPassphrase = options.subkeys[index].passphrase;
  28961. if (subkeyPassphrase) {
  28962. await secretSubkeyPacket.encrypt(subkeyPassphrase);
  28963. }
  28964. }));
  28965. const packetlist = new _packet2.default.List();
  28966. packetlist.push(secretKeyPacket);
  28967. await Promise.all(options.userIds.map(async function (userId, index) {
  28968. function createdPreferredAlgos(algos, configAlgo) {
  28969. if (configAlgo) {
  28970. // Not `uncompressed` / `plaintext`
  28971. const configIndex = algos.indexOf(configAlgo);
  28972. if (configIndex >= 1) {
  28973. // If it is included and not in first place,
  28974. algos.splice(configIndex, 1); // remove it.
  28975. }
  28976. if (configIndex !== 0) {
  28977. // If it was included and not in first place, or wasn't included,
  28978. algos.unshift(configAlgo); // add it to the front.
  28979. }
  28980. }
  28981. return algos;
  28982. }
  28983. const userIdPacket = new _packet2.default.Userid();
  28984. userIdPacket.format(userId);
  28985. const dataToSign = {};
  28986. dataToSign.userId = userIdPacket;
  28987. dataToSign.key = secretKeyPacket;
  28988. const signaturePacket = new _packet2.default.Signature(options.date);
  28989. signaturePacket.signatureType = _enums2.default.signature.cert_generic;
  28990. signaturePacket.publicKeyAlgorithm = secretKeyPacket.algorithm;
  28991. signaturePacket.hashAlgorithm = await helper.getPreferredHashAlgo(null, secretKeyPacket);
  28992. signaturePacket.keyFlags = [_enums2.default.keyFlags.certify_keys | _enums2.default.keyFlags.sign_data];
  28993. signaturePacket.preferredSymmetricAlgorithms = createdPreferredAlgos([
  28994. // prefer aes256, aes128, then aes192 (no WebCrypto support: https://www.chromium.org/blink/webcrypto#TOC-AES-support)
  28995. _enums2.default.symmetric.aes256, _enums2.default.symmetric.aes128, _enums2.default.symmetric.aes192, _enums2.default.symmetric.cast5, _enums2.default.symmetric.tripledes], _config2.default.encryption_cipher);
  28996. if (_config2.default.aead_protect) {
  28997. signaturePacket.preferredAeadAlgorithms = createdPreferredAlgos([_enums2.default.aead.eax, _enums2.default.aead.ocb], _config2.default.aead_mode);
  28998. }
  28999. signaturePacket.preferredHashAlgorithms = createdPreferredAlgos([
  29000. // prefer fast asm.js implementations (SHA-256). SHA-1 will not be secure much longer...move to bottom of list
  29001. _enums2.default.hash.sha256, _enums2.default.hash.sha512, _enums2.default.hash.sha1], _config2.default.prefer_hash_algorithm);
  29002. signaturePacket.preferredCompressionAlgorithms = createdPreferredAlgos([_enums2.default.compression.zlib, _enums2.default.compression.zip], _config2.default.compression);
  29003. if (index === 0) {
  29004. signaturePacket.isPrimaryUserID = true;
  29005. }
  29006. if (_config2.default.integrity_protect) {
  29007. signaturePacket.features = [0];
  29008. signaturePacket.features[0] |= _enums2.default.features.modification_detection;
  29009. }
  29010. if (_config2.default.aead_protect) {
  29011. signaturePacket.features || (signaturePacket.features = [0]);
  29012. signaturePacket.features[0] |= _enums2.default.features.aead;
  29013. }
  29014. if (_config2.default.v5_keys) {
  29015. signaturePacket.features || (signaturePacket.features = [0]);
  29016. signaturePacket.features[0] |= _enums2.default.features.v5_keys;
  29017. }
  29018. if (options.keyExpirationTime > 0) {
  29019. signaturePacket.keyExpirationTime = options.keyExpirationTime;
  29020. signaturePacket.keyNeverExpires = false;
  29021. }
  29022. await signaturePacket.sign(secretKeyPacket, dataToSign);
  29023. return { userIdPacket, signaturePacket };
  29024. })).then(list => {
  29025. list.forEach(({ userIdPacket, signaturePacket }) => {
  29026. packetlist.push(userIdPacket);
  29027. packetlist.push(signaturePacket);
  29028. });
  29029. });
  29030. await Promise.all(secretSubkeyPackets.map(async function (secretSubkeyPacket, index) {
  29031. const subkeyOptions = options.subkeys[index];
  29032. const subkeySignaturePacket = await helper.createBindingSignature(secretSubkeyPacket, secretKeyPacket, subkeyOptions);
  29033. return { secretSubkeyPacket, subkeySignaturePacket };
  29034. })).then(packets => {
  29035. packets.forEach(({ secretSubkeyPacket, subkeySignaturePacket }) => {
  29036. packetlist.push(secretSubkeyPacket);
  29037. packetlist.push(subkeySignaturePacket);
  29038. });
  29039. });
  29040. // Add revocation signature packet for creating a revocation certificate.
  29041. // This packet should be removed before returning the key.
  29042. const dataToSign = { key: secretKeyPacket };
  29043. packetlist.push((await helper.createSignaturePacket(dataToSign, null, secretKeyPacket, {
  29044. signatureType: _enums2.default.signature.key_revocation,
  29045. reasonForRevocationFlag: _enums2.default.reasonForRevocation.no_reason,
  29046. reasonForRevocationString: ''
  29047. }, options.date)));
  29048. // set passphrase protection
  29049. if (options.passphrase) {
  29050. secretKeyPacket.clearPrivateParams();
  29051. }
  29052. await Promise.all(secretSubkeyPackets.map(async function (secretSubkeyPacket, index) {
  29053. const subkeyPassphrase = options.subkeys[index].passphrase;
  29054. if (subkeyPassphrase) {
  29055. secretSubkeyPacket.clearPrivateParams();
  29056. }
  29057. }));
  29058. return new _key2.default(packetlist);
  29059. }
  29060. /**
  29061. * Reads an unarmored OpenPGP key list and returns one or multiple key objects
  29062. * @param {Uint8Array} data to be parsed
  29063. * @returns {Promise<{keys: Array<module:key.Key>,
  29064. * err: (Array<Error>|null)}>} result object with key and error arrays
  29065. * @async
  29066. * @static
  29067. */
  29068. async function read(data) {
  29069. const result = {};
  29070. result.keys = [];
  29071. const err = [];
  29072. try {
  29073. const packetlist = new _packet2.default.List();
  29074. await packetlist.read(data);
  29075. const keyIndex = packetlist.indexOfTag(_enums2.default.packet.publicKey, _enums2.default.packet.secretKey);
  29076. if (keyIndex.length === 0) {
  29077. throw new Error('No key packet found');
  29078. }
  29079. for (let i = 0; i < keyIndex.length; i++) {
  29080. const oneKeyList = packetlist.slice(keyIndex[i], keyIndex[i + 1]);
  29081. try {
  29082. const newKey = new _key2.default(oneKeyList);
  29083. result.keys.push(newKey);
  29084. } catch (e) {
  29085. err.push(e);
  29086. }
  29087. }
  29088. } catch (e) {
  29089. err.push(e);
  29090. }
  29091. if (err.length) {
  29092. result.err = err;
  29093. }
  29094. return result;
  29095. }
  29096. /**
  29097. * Reads an OpenPGP armored text and returns one or multiple key objects
  29098. * @param {String | ReadableStream<String>} armoredText text to be parsed
  29099. * @returns {Promise<{keys: Array<module:key.Key>,
  29100. * err: (Array<Error>|null)}>} result object with key and error arrays
  29101. * @async
  29102. * @static
  29103. */
  29104. async function readArmored(armoredText) {
  29105. try {
  29106. const input = await _armor2.default.decode(armoredText);
  29107. if (!(input.type === _enums2.default.armor.public_key || input.type === _enums2.default.armor.private_key)) {
  29108. throw new Error('Armored text not of type key');
  29109. }
  29110. return read(input.data);
  29111. } catch (e) {
  29112. const result = { keys: [], err: [] };
  29113. result.err.push(e);
  29114. return result;
  29115. }
  29116. }
  29117. },{"../config":79,"../encoding/armor":111,"../enums":113,"../packet":131,"../util":158,"./helper":117,"./key":119}],117:[function(require,module,exports){
  29118. 'use strict';
  29119. Object.defineProperty(exports, "__esModule", {
  29120. value: true
  29121. });
  29122. var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); /**
  29123. * @fileoverview Provides helpers methods for key module
  29124. * @requires packet
  29125. * @requires enums
  29126. * @requires config
  29127. * @requires crypto
  29128. * @module key/helper
  29129. */
  29130. exports.generateSecretSubkey = generateSecretSubkey;
  29131. exports.generateSecretKey = generateSecretKey;
  29132. exports.getLatestValidSignature = getLatestValidSignature;
  29133. exports.isDataExpired = isDataExpired;
  29134. exports.createBindingSignature = createBindingSignature;
  29135. exports.getPreferredHashAlgo = getPreferredHashAlgo;
  29136. exports.getPreferredAlgo = getPreferredAlgo;
  29137. exports.createSignaturePacket = createSignaturePacket;
  29138. exports.mergeSignatures = mergeSignatures;
  29139. exports.isDataRevoked = isDataRevoked;
  29140. exports.getExpirationTime = getExpirationTime;
  29141. exports.checkRevocationKey = checkRevocationKey;
  29142. exports.isAeadSupported = isAeadSupported;
  29143. exports.sanitizeKeyOptions = sanitizeKeyOptions;
  29144. exports.isValidSigningKeyPacket = isValidSigningKeyPacket;
  29145. exports.isValidEncryptionKeyPacket = isValidEncryptionKeyPacket;
  29146. var _packet = require('../packet');
  29147. var _packet2 = _interopRequireDefault(_packet);
  29148. var _enums = require('../enums');
  29149. var _enums2 = _interopRequireDefault(_enums);
  29150. var _config = require('../config');
  29151. var _config2 = _interopRequireDefault(_config);
  29152. var _crypto = require('../crypto');
  29153. var _crypto2 = _interopRequireDefault(_crypto);
  29154. var _util = require('../util');
  29155. var _util2 = _interopRequireDefault(_util);
  29156. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  29157. async function generateSecretSubkey(options) {
  29158. const secretSubkeyPacket = new _packet2.default.SecretSubkey(options.date);
  29159. secretSubkeyPacket.packets = null;
  29160. secretSubkeyPacket.algorithm = _enums2.default.read(_enums2.default.publicKey, options.algorithm);
  29161. await secretSubkeyPacket.generate(options.rsaBits, options.curve);
  29162. return secretSubkeyPacket;
  29163. }
  29164. async function generateSecretKey(options) {
  29165. const secretKeyPacket = new _packet2.default.SecretKey(options.date);
  29166. secretKeyPacket.packets = null;
  29167. secretKeyPacket.algorithm = _enums2.default.read(_enums2.default.publicKey, options.algorithm);
  29168. await secretKeyPacket.generate(options.rsaBits, options.curve);
  29169. return secretKeyPacket;
  29170. }
  29171. /**
  29172. * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future.
  29173. * @param {Array<module:packet.Signature>} signatures List of signatures
  29174. * @param {Date} date Use the given date instead of the current time
  29175. * @returns {Promise<module:packet.Signature>} The latest valid signature
  29176. * @async
  29177. */
  29178. async function getLatestValidSignature(signatures, primaryKey, signatureType, dataToVerify, date = new Date()) {
  29179. let signature;
  29180. for (let i = signatures.length - 1; i >= 0; i--) {
  29181. if ((!signature || signatures[i].created >= signature.created) &&
  29182. // check binding signature is not expired (ie, check for V4 expiration time)
  29183. !signatures[i].isExpired(date) && (
  29184. // check binding signature is verified
  29185. signatures[i].verified || (await signatures[i].verify(primaryKey, signatureType, dataToVerify)))) {
  29186. signature = signatures[i];
  29187. }
  29188. }
  29189. return signature;
  29190. }
  29191. function isDataExpired(keyPacket, signature, date = new Date()) {
  29192. const normDate = _util2.default.normalizeDate(date);
  29193. if (normDate !== null) {
  29194. const expirationTime = getExpirationTime(keyPacket, signature);
  29195. return !(keyPacket.created <= normDate && normDate <= expirationTime) || signature && signature.isExpired(date);
  29196. }
  29197. return false;
  29198. }
  29199. /**
  29200. * Create Binding signature to the key according to the {@link https://tools.ietf.org/html/rfc4880#section-5.2.1}
  29201. * @param {module:packet.SecretSubkey|} subkey Subkey key packet
  29202. * @param {module:packet.SecretKey} primaryKey Primary key packet
  29203. * @param {Object} options
  29204. */
  29205. async function createBindingSignature(subkey, primaryKey, options) {
  29206. const dataToSign = {};
  29207. dataToSign.key = primaryKey;
  29208. dataToSign.bind = subkey;
  29209. const subkeySignaturePacket = new _packet2.default.Signature(options.date);
  29210. subkeySignaturePacket.signatureType = _enums2.default.signature.subkey_binding;
  29211. subkeySignaturePacket.publicKeyAlgorithm = primaryKey.algorithm;
  29212. subkeySignaturePacket.hashAlgorithm = await getPreferredHashAlgo(null, subkey);
  29213. if (options.sign) {
  29214. subkeySignaturePacket.keyFlags = [_enums2.default.keyFlags.sign_data];
  29215. subkeySignaturePacket.embeddedSignature = await createSignaturePacket(dataToSign, null, subkey, {
  29216. signatureType: _enums2.default.signature.key_binding
  29217. }, options.date);
  29218. } else {
  29219. subkeySignaturePacket.keyFlags = [_enums2.default.keyFlags.encrypt_communication | _enums2.default.keyFlags.encrypt_storage];
  29220. }
  29221. if (options.keyExpirationTime > 0) {
  29222. subkeySignaturePacket.keyExpirationTime = options.keyExpirationTime;
  29223. subkeySignaturePacket.keyNeverExpires = false;
  29224. }
  29225. await subkeySignaturePacket.sign(primaryKey, dataToSign);
  29226. return subkeySignaturePacket;
  29227. }
  29228. /**
  29229. * Returns the preferred signature hash algorithm of a key
  29230. * @param {module:key.Key} key (optional) the key to get preferences from
  29231. * @param {module:packet.SecretKey|module:packet.SecretSubkey} keyPacket key packet used for signing
  29232. * @param {Date} date (optional) use the given date for verification instead of the current time
  29233. * @param {Object} userId (optional) user ID
  29234. * @returns {Promise<String>}
  29235. * @async
  29236. */
  29237. async function getPreferredHashAlgo(key, keyPacket, date = new Date(), userId = {}) {
  29238. let hash_algo = _config2.default.prefer_hash_algorithm;
  29239. let pref_algo = hash_algo;
  29240. if (key) {
  29241. const primaryUser = await key.getPrimaryUser(date, userId);
  29242. if (primaryUser && primaryUser.selfCertification.preferredHashAlgorithms) {
  29243. var _primaryUser$selfCert = _slicedToArray(primaryUser.selfCertification.preferredHashAlgorithms, 1);
  29244. pref_algo = _primaryUser$selfCert[0];
  29245. hash_algo = _crypto2.default.hash.getHashByteLength(hash_algo) <= _crypto2.default.hash.getHashByteLength(pref_algo) ? pref_algo : hash_algo;
  29246. }
  29247. }
  29248. switch (Object.getPrototypeOf(keyPacket)) {
  29249. case _packet2.default.SecretKey.prototype:
  29250. case _packet2.default.PublicKey.prototype:
  29251. case _packet2.default.SecretSubkey.prototype:
  29252. case _packet2.default.PublicSubkey.prototype:
  29253. switch (keyPacket.algorithm) {
  29254. case 'ecdh':
  29255. case 'ecdsa':
  29256. case 'eddsa':
  29257. pref_algo = _crypto2.default.publicKey.elliptic.getPreferredHashAlgo(keyPacket.params[0]);
  29258. }
  29259. }
  29260. return _crypto2.default.hash.getHashByteLength(hash_algo) <= _crypto2.default.hash.getHashByteLength(pref_algo) ? pref_algo : hash_algo;
  29261. }
  29262. /**
  29263. * Returns the preferred symmetric/aead algorithm for a set of keys
  29264. * @param {symmetric|aead} type Type of preference to return
  29265. * @param {Array<module:key.Key>} keys Set of keys
  29266. * @param {Date} date (optional) use the given date for verification instead of the current time
  29267. * @param {Array} userIds (optional) user IDs
  29268. * @returns {Promise<module:enums.symmetric>} Preferred symmetric algorithm
  29269. * @async
  29270. */
  29271. async function getPreferredAlgo(type, keys, date = new Date(), userIds = []) {
  29272. const prefProperty = type === 'symmetric' ? 'preferredSymmetricAlgorithms' : 'preferredAeadAlgorithms';
  29273. const defaultAlgo = type === 'symmetric' ? _enums2.default.symmetric.aes128 : _enums2.default.aead.eax;
  29274. const prioMap = {};
  29275. await Promise.all(keys.map(async function (key, i) {
  29276. const primaryUser = await key.getPrimaryUser(date, userIds[i]);
  29277. if (!primaryUser || !primaryUser.selfCertification[prefProperty]) {
  29278. return defaultAlgo;
  29279. }
  29280. primaryUser.selfCertification[prefProperty].forEach(function (algo, index) {
  29281. const entry = prioMap[algo] || (prioMap[algo] = { prio: 0, count: 0, algo: algo });
  29282. entry.prio += 64 >> index;
  29283. entry.count++;
  29284. });
  29285. }));
  29286. let prefAlgo = { prio: 0, algo: defaultAlgo };
  29287. Object.values(prioMap).forEach(({ prio, count, algo }) => {
  29288. try {
  29289. if (algo !== _enums2.default[type].plaintext && algo !== _enums2.default[type].idea && // not implemented
  29290. _enums2.default.read(_enums2.default[type], algo) && // known algorithm
  29291. count === keys.length && // available for all keys
  29292. prio > prefAlgo.prio) {
  29293. prefAlgo = prioMap[algo];
  29294. }
  29295. } catch (e) {}
  29296. });
  29297. return prefAlgo.algo;
  29298. }
  29299. /**
  29300. * Create signature packet
  29301. * @param {Object} dataToSign Contains packets to be signed
  29302. * @param {module:packet.SecretKey|
  29303. * module:packet.SecretSubkey} signingKeyPacket secret key packet for signing
  29304. * @param {Object} signatureProperties (optional) properties to write on the signature packet before signing
  29305. * @param {Date} date (optional) override the creationtime of the signature
  29306. * @param {Object} userId (optional) user ID
  29307. * @param {Object} detached (optional) whether to create a detached signature packet
  29308. * @param {Boolean} streaming (optional) whether to process data as a stream
  29309. * @returns {module:packet/signature} signature packet
  29310. */
  29311. async function createSignaturePacket(dataToSign, privateKey, signingKeyPacket, signatureProperties, date, userId, detached = false, streaming = false) {
  29312. if (!signingKeyPacket.isDecrypted()) {
  29313. throw new Error('Private key is not decrypted.');
  29314. }
  29315. const signaturePacket = new _packet2.default.Signature(date);
  29316. Object.assign(signaturePacket, signatureProperties);
  29317. signaturePacket.publicKeyAlgorithm = signingKeyPacket.algorithm;
  29318. signaturePacket.hashAlgorithm = await getPreferredHashAlgo(privateKey, signingKeyPacket, date, userId);
  29319. await signaturePacket.sign(signingKeyPacket, dataToSign, detached, streaming);
  29320. return signaturePacket;
  29321. }
  29322. /**
  29323. * Merges signatures from source[attr] to dest[attr]
  29324. * @private
  29325. * @param {Object} source
  29326. * @param {Object} dest
  29327. * @param {String} attr
  29328. * @param {Function} checkFn optional, signature only merged if true
  29329. */
  29330. async function mergeSignatures(source, dest, attr, checkFn) {
  29331. source = source[attr];
  29332. if (source) {
  29333. if (!dest[attr].length) {
  29334. dest[attr] = source;
  29335. } else {
  29336. await Promise.all(source.map(async function (sourceSig) {
  29337. if (!sourceSig.isExpired() && (!checkFn || (await checkFn(sourceSig))) && !dest[attr].some(function (destSig) {
  29338. return _util2.default.equalsUint8Array(destSig.signature, sourceSig.signature);
  29339. })) {
  29340. dest[attr].push(sourceSig);
  29341. }
  29342. }));
  29343. }
  29344. }
  29345. }
  29346. /**
  29347. * Checks if a given certificate or binding signature is revoked
  29348. * @param {module:packet.SecretKey|
  29349. * module:packet.PublicKey} primaryKey The primary key packet
  29350. * @param {Object} dataToVerify The data to check
  29351. * @param {Array<module:packet.Signature>} revocations The revocation signatures to check
  29352. * @param {module:packet.Signature} signature The certificate or signature to check
  29353. * @param {module:packet.PublicSubkey|
  29354. * module:packet.SecretSubkey|
  29355. * module:packet.PublicKey|
  29356. * module:packet.SecretKey} key, optional The key packet to check the signature
  29357. * @param {Date} date Use the given date instead of the current time
  29358. * @returns {Promise<Boolean>} True if the signature revokes the data
  29359. * @async
  29360. */
  29361. async function isDataRevoked(primaryKey, signatureType, dataToVerify, revocations, signature, key, date = new Date()) {
  29362. key = key || primaryKey;
  29363. const normDate = _util2.default.normalizeDate(date);
  29364. const revocationKeyIds = [];
  29365. await Promise.all(revocations.map(async function (revocationSignature) {
  29366. if (
  29367. // Note: a third-party revocation signature could legitimately revoke a
  29368. // self-signature if the signature has an authorized revocation key.
  29369. // However, we don't support passing authorized revocation keys, nor
  29370. // verifying such revocation signatures. Instead, we indicate an error
  29371. // when parsing a key with an authorized revocation key, and ignore
  29372. // third-party revocation signatures here. (It could also be revoking a
  29373. // third-party key certification, which should only affect
  29374. // `verifyAllCertifications`.)
  29375. (!signature || revocationSignature.issuerKeyId.equals(signature.issuerKeyId)) && !(_config2.default.revocations_expire && revocationSignature.isExpired(normDate)) && (revocationSignature.verified || (await revocationSignature.verify(key, signatureType, dataToVerify)))) {
  29376. // TODO get an identifier of the revoked object instead
  29377. revocationKeyIds.push(revocationSignature.issuerKeyId);
  29378. return true;
  29379. }
  29380. return false;
  29381. }));
  29382. // TODO further verify that this is the signature that should be revoked
  29383. if (signature) {
  29384. signature.revoked = revocationKeyIds.some(keyId => keyId.equals(signature.issuerKeyId)) ? true : signature.revoked || false;
  29385. return signature.revoked;
  29386. }
  29387. return revocationKeyIds.length > 0;
  29388. }
  29389. function getExpirationTime(keyPacket, signature) {
  29390. let expirationTime;
  29391. // check V4 expiration time
  29392. if (signature.keyNeverExpires === false) {
  29393. expirationTime = keyPacket.created.getTime() + signature.keyExpirationTime * 1000;
  29394. }
  29395. return expirationTime ? new Date(expirationTime) : Infinity;
  29396. }
  29397. /**
  29398. * Check if signature has revocation key sub packet (not supported by OpenPGP.js)
  29399. * and throw error if found
  29400. * @param {module:packet.Signature} signature The certificate or signature to check
  29401. * @param {type/keyid} keyId Check only certificates or signatures from a certain issuer key ID
  29402. */
  29403. function checkRevocationKey(signature, keyId) {
  29404. if (signature.revocationKeyClass !== null && signature.issuerKeyId.equals(keyId)) {
  29405. throw new Error('This key is intended to be revoked with an authorized key, which OpenPGP.js does not support.');
  29406. }
  29407. }
  29408. /**
  29409. * Returns whether aead is supported by all keys in the set
  29410. * @param {Array<module:key.Key>} keys Set of keys
  29411. * @param {Date} date (optional) use the given date for verification instead of the current time
  29412. * @param {Array} userIds (optional) user IDs
  29413. * @returns {Promise<Boolean>}
  29414. * @async
  29415. */
  29416. async function isAeadSupported(keys, date = new Date(), userIds = []) {
  29417. let supported = true;
  29418. // TODO replace when Promise.some or Promise.any are implemented
  29419. await Promise.all(keys.map(async function (key, i) {
  29420. const primaryUser = await key.getPrimaryUser(date, userIds[i]);
  29421. if (!primaryUser || !primaryUser.selfCertification.features || !(primaryUser.selfCertification.features[0] & _enums2.default.features.aead)) {
  29422. supported = false;
  29423. }
  29424. }));
  29425. return supported;
  29426. }
  29427. function sanitizeKeyOptions(options, subkeyDefaults = {}) {
  29428. options.curve = options.curve || subkeyDefaults.curve;
  29429. options.rsaBits = options.rsaBits || subkeyDefaults.rsaBits;
  29430. options.keyExpirationTime = options.keyExpirationTime !== undefined ? options.keyExpirationTime : subkeyDefaults.keyExpirationTime;
  29431. options.passphrase = _util2.default.isString(options.passphrase) ? options.passphrase : subkeyDefaults.passphrase;
  29432. options.date = options.date || subkeyDefaults.date;
  29433. options.sign = options.sign || false;
  29434. if (options.curve) {
  29435. try {
  29436. options.curve = _enums2.default.write(_enums2.default.curve, options.curve);
  29437. } catch (e) {
  29438. throw new Error('Not valid curve.');
  29439. }
  29440. if (options.curve === _enums2.default.curve.ed25519 || options.curve === _enums2.default.curve.curve25519) {
  29441. options.curve = options.sign ? _enums2.default.curve.ed25519 : _enums2.default.curve.curve25519;
  29442. }
  29443. if (options.sign) {
  29444. options.algorithm = options.curve === _enums2.default.curve.ed25519 ? _enums2.default.publicKey.eddsa : _enums2.default.publicKey.ecdsa;
  29445. } else {
  29446. options.algorithm = _enums2.default.publicKey.ecdh;
  29447. }
  29448. } else if (options.rsaBits) {
  29449. options.algorithm = _enums2.default.publicKey.rsa_encrypt_sign;
  29450. } else {
  29451. throw new Error('Unrecognized key type');
  29452. }
  29453. return options;
  29454. }
  29455. function isValidSigningKeyPacket(keyPacket, signature) {
  29456. if (!signature.verified || signature.revoked !== false) {
  29457. // Sanity check
  29458. throw new Error('Signature not verified');
  29459. }
  29460. return keyPacket.algorithm !== _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.rsa_encrypt) && keyPacket.algorithm !== _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.elgamal) && keyPacket.algorithm !== _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.ecdh) && (!signature.keyFlags || (signature.keyFlags[0] & _enums2.default.keyFlags.sign_data) !== 0);
  29461. }
  29462. function isValidEncryptionKeyPacket(keyPacket, signature) {
  29463. if (!signature.verified || signature.revoked !== false) {
  29464. // Sanity check
  29465. throw new Error('Signature not verified');
  29466. }
  29467. return keyPacket.algorithm !== _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.dsa) && keyPacket.algorithm !== _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.rsa_sign) && keyPacket.algorithm !== _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.ecdsa) && keyPacket.algorithm !== _enums2.default.read(_enums2.default.publicKey, _enums2.default.publicKey.eddsa) && (!signature.keyFlags || (signature.keyFlags[0] & _enums2.default.keyFlags.encrypt_communication) !== 0 || (signature.keyFlags[0] & _enums2.default.keyFlags.encrypt_storage) !== 0);
  29468. }
  29469. },{"../config":79,"../crypto":94,"../enums":113,"../packet":131,"../util":158}],118:[function(require,module,exports){
  29470. 'use strict';
  29471. Object.defineProperty(exports, "__esModule", {
  29472. value: true
  29473. });
  29474. exports.Key = exports.createSignaturePacket = exports.getPreferredHashAlgo = exports.isAeadSupported = exports.getPreferredAlgo = exports.reformat = exports.read = exports.generate = exports.readArmored = undefined;
  29475. var _factory = require('./factory');
  29476. var _helper = require('./helper');
  29477. var _key = require('./key.js');
  29478. var _key2 = _interopRequireDefault(_key);
  29479. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  29480. exports.readArmored = _factory.readArmored;
  29481. exports.generate = _factory.generate;
  29482. exports.read = _factory.read;
  29483. exports.reformat = _factory.reformat;
  29484. exports.getPreferredAlgo = _helper.getPreferredAlgo;
  29485. exports.isAeadSupported = _helper.isAeadSupported;
  29486. exports.getPreferredHashAlgo = _helper.getPreferredHashAlgo;
  29487. exports.createSignaturePacket = _helper.createSignaturePacket;
  29488. exports.Key = _key2.default; /**
  29489. * @fileoverview helper, factory methods, constructors dealing with openPGP key object
  29490. * @module key
  29491. */
  29492. },{"./factory":116,"./helper":117,"./key.js":119}],119:[function(require,module,exports){
  29493. 'use strict';
  29494. Object.defineProperty(exports, "__esModule", {
  29495. value: true
  29496. });
  29497. exports.default = Key;
  29498. var _armor = require('../encoding/armor');
  29499. var _armor2 = _interopRequireDefault(_armor);
  29500. var _packet = require('../packet');
  29501. var _packet2 = _interopRequireDefault(_packet);
  29502. var _enums = require('../enums');
  29503. var _enums2 = _interopRequireDefault(_enums);
  29504. var _util = require('../util');
  29505. var _util2 = _interopRequireDefault(_util);
  29506. var _user = require('./user');
  29507. var _user2 = _interopRequireDefault(_user);
  29508. var _subkey = require('./subkey');
  29509. var _subkey2 = _interopRequireDefault(_subkey);
  29510. var _helper = require('./helper');
  29511. var helper = _interopRequireWildcard(_helper);
  29512. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  29513. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  29514. /**
  29515. * @class
  29516. * @classdesc Class that represents an OpenPGP key. Must contain a primary key.
  29517. * Can contain additional subkeys, signatures, user ids, user attributes.
  29518. * @param {module:packet.List} packetlist The packets that form this key
  29519. * @borrows module:packet.PublicKey#getKeyId as Key#getKeyId
  29520. * @borrows module:packet.PublicKey#getFingerprint as Key#getFingerprint
  29521. * @borrows module:packet.PublicKey#hasSameFingerprintAs as Key#hasSameFingerprintAs
  29522. * @borrows module:packet.PublicKey#getAlgorithmInfo as Key#getAlgorithmInfo
  29523. * @borrows module:packet.PublicKey#getCreationTime as Key#getCreationTime
  29524. * @borrows module:packet.PublicKey#isDecrypted as Key#isDecrypted
  29525. */
  29526. function Key(packetlist) {
  29527. if (!(this instanceof Key)) {
  29528. return new Key(packetlist);
  29529. }
  29530. // same data as in packetlist but in structured form
  29531. this.keyPacket = null;
  29532. this.revocationSignatures = [];
  29533. this.directSignatures = [];
  29534. this.users = [];
  29535. this.subKeys = [];
  29536. this.packetlist2structure(packetlist);
  29537. if (!this.keyPacket || !this.users.length) {
  29538. throw new Error('Invalid key: need at least key and user ID packet');
  29539. }
  29540. } // GPG4Browsers - An OpenPGP implementation in javascript
  29541. // Copyright (C) 2011 Recurity Labs GmbH
  29542. //
  29543. // This library is free software; you can redistribute it and/or
  29544. // modify it under the terms of the GNU Lesser General Public
  29545. // License as published by the Free Software Foundation; either
  29546. // version 3.0 of the License, or (at your option) any later version.
  29547. //
  29548. // This library is distributed in the hope that it will be useful,
  29549. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  29550. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  29551. // Lesser General Public License for more details.
  29552. //
  29553. // You should have received a copy of the GNU Lesser General Public
  29554. // License along with this library; if not, write to the Free Software
  29555. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  29556. /**
  29557. * @requires encoding/armor
  29558. * @requires packet
  29559. * @requires enums
  29560. * @requires util
  29561. * @requires key/User
  29562. * @requires key/Subkey
  29563. * @module key/Key
  29564. */
  29565. Object.defineProperty(Key.prototype, 'primaryKey', {
  29566. get() {
  29567. return this.keyPacket;
  29568. },
  29569. configurable: true,
  29570. enumerable: true
  29571. });
  29572. /**
  29573. * Transforms packetlist to structured key data
  29574. * @param {module:packet.List} packetlist The packets that form a key
  29575. */
  29576. Key.prototype.packetlist2structure = function (packetlist) {
  29577. let user;
  29578. let primaryKeyId;
  29579. let subKey;
  29580. for (let i = 0; i < packetlist.length; i++) {
  29581. switch (packetlist[i].tag) {
  29582. case _enums2.default.packet.publicKey:
  29583. case _enums2.default.packet.secretKey:
  29584. this.keyPacket = packetlist[i];
  29585. primaryKeyId = this.getKeyId();
  29586. break;
  29587. case _enums2.default.packet.userid:
  29588. case _enums2.default.packet.userAttribute:
  29589. user = new _user2.default(packetlist[i]);
  29590. this.users.push(user);
  29591. break;
  29592. case _enums2.default.packet.publicSubkey:
  29593. case _enums2.default.packet.secretSubkey:
  29594. user = null;
  29595. subKey = new _subkey2.default(packetlist[i]);
  29596. this.subKeys.push(subKey);
  29597. break;
  29598. case _enums2.default.packet.signature:
  29599. switch (packetlist[i].signatureType) {
  29600. case _enums2.default.signature.cert_generic:
  29601. case _enums2.default.signature.cert_persona:
  29602. case _enums2.default.signature.cert_casual:
  29603. case _enums2.default.signature.cert_positive:
  29604. if (!user) {
  29605. _util2.default.print_debug('Dropping certification signatures without preceding user packet');
  29606. continue;
  29607. }
  29608. if (packetlist[i].issuerKeyId.equals(primaryKeyId)) {
  29609. helper.checkRevocationKey(packetlist[i], primaryKeyId);
  29610. user.selfCertifications.push(packetlist[i]);
  29611. } else {
  29612. user.otherCertifications.push(packetlist[i]);
  29613. }
  29614. break;
  29615. case _enums2.default.signature.cert_revocation:
  29616. if (user) {
  29617. user.revocationSignatures.push(packetlist[i]);
  29618. } else {
  29619. this.directSignatures.push(packetlist[i]);
  29620. }
  29621. break;
  29622. case _enums2.default.signature.key:
  29623. helper.checkRevocationKey(packetlist[i], primaryKeyId);
  29624. this.directSignatures.push(packetlist[i]);
  29625. break;
  29626. case _enums2.default.signature.subkey_binding:
  29627. if (!subKey) {
  29628. _util2.default.print_debug('Dropping subkey binding signature without preceding subkey packet');
  29629. continue;
  29630. }
  29631. helper.checkRevocationKey(packetlist[i], primaryKeyId);
  29632. subKey.bindingSignatures.push(packetlist[i]);
  29633. break;
  29634. case _enums2.default.signature.key_revocation:
  29635. this.revocationSignatures.push(packetlist[i]);
  29636. break;
  29637. case _enums2.default.signature.subkey_revocation:
  29638. if (!subKey) {
  29639. _util2.default.print_debug('Dropping subkey revocation signature without preceding subkey packet');
  29640. continue;
  29641. }
  29642. subKey.revocationSignatures.push(packetlist[i]);
  29643. break;
  29644. }
  29645. break;
  29646. }
  29647. }
  29648. };
  29649. /**
  29650. * Transforms structured key data to packetlist
  29651. * @returns {module:packet.List} The packets that form a key
  29652. */
  29653. Key.prototype.toPacketlist = function () {
  29654. const packetlist = new _packet2.default.List();
  29655. packetlist.push(this.keyPacket);
  29656. packetlist.concat(this.revocationSignatures);
  29657. packetlist.concat(this.directSignatures);
  29658. this.users.map(user => packetlist.concat(user.toPacketlist()));
  29659. this.subKeys.map(subKey => packetlist.concat(subKey.toPacketlist()));
  29660. return packetlist;
  29661. };
  29662. /**
  29663. * Returns an array containing all public or private subkeys matching keyId;
  29664. * If keyId is not present, returns all subkeys.
  29665. * @param {type/keyid} keyId
  29666. * @returns {Array<module:key~SubKey>}
  29667. */
  29668. Key.prototype.getSubkeys = function (keyId = null) {
  29669. const subKeys = [];
  29670. this.subKeys.forEach(subKey => {
  29671. if (!keyId || subKey.getKeyId().equals(keyId, true)) {
  29672. subKeys.push(subKey);
  29673. }
  29674. });
  29675. return subKeys;
  29676. };
  29677. /**
  29678. * Returns an array containing all public or private keys matching keyId.
  29679. * If keyId is not present, returns all keys starting with the primary key.
  29680. * @param {type/keyid} keyId
  29681. * @returns {Array<module:key.Key|module:key~SubKey>}
  29682. */
  29683. Key.prototype.getKeys = function (keyId = null) {
  29684. const keys = [];
  29685. if (!keyId || this.getKeyId().equals(keyId, true)) {
  29686. keys.push(this);
  29687. }
  29688. return keys.concat(this.getSubkeys(keyId));
  29689. };
  29690. /**
  29691. * Returns key IDs of all keys
  29692. * @returns {Array<module:type/keyid>}
  29693. */
  29694. Key.prototype.getKeyIds = function () {
  29695. return this.getKeys().map(key => key.getKeyId());
  29696. };
  29697. /**
  29698. * Returns userids
  29699. * @returns {Array<string>} array of userids
  29700. */
  29701. Key.prototype.getUserIds = function () {
  29702. return this.users.map(user => {
  29703. return user.userId ? user.userId.userid : null;
  29704. }).filter(userid => userid !== null);
  29705. };
  29706. /**
  29707. * Returns true if this is a public key
  29708. * @returns {Boolean}
  29709. */
  29710. Key.prototype.isPublic = function () {
  29711. return this.keyPacket.tag === _enums2.default.packet.publicKey;
  29712. };
  29713. /**
  29714. * Returns true if this is a private key
  29715. * @returns {Boolean}
  29716. */
  29717. Key.prototype.isPrivate = function () {
  29718. return this.keyPacket.tag === _enums2.default.packet.secretKey;
  29719. };
  29720. /**
  29721. * Returns key as public key (shallow copy)
  29722. * @returns {module:key.Key} new public Key
  29723. */
  29724. Key.prototype.toPublic = function () {
  29725. const packetlist = new _packet2.default.List();
  29726. const keyPackets = this.toPacketlist();
  29727. let bytes;
  29728. let pubKeyPacket;
  29729. let pubSubkeyPacket;
  29730. for (let i = 0; i < keyPackets.length; i++) {
  29731. switch (keyPackets[i].tag) {
  29732. case _enums2.default.packet.secretKey:
  29733. bytes = keyPackets[i].writePublicKey();
  29734. pubKeyPacket = new _packet2.default.PublicKey();
  29735. pubKeyPacket.read(bytes);
  29736. packetlist.push(pubKeyPacket);
  29737. break;
  29738. case _enums2.default.packet.secretSubkey:
  29739. bytes = keyPackets[i].writePublicKey();
  29740. pubSubkeyPacket = new _packet2.default.PublicSubkey();
  29741. pubSubkeyPacket.read(bytes);
  29742. packetlist.push(pubSubkeyPacket);
  29743. break;
  29744. default:
  29745. packetlist.push(keyPackets[i]);
  29746. }
  29747. }
  29748. return new Key(packetlist);
  29749. };
  29750. /**
  29751. * Returns ASCII armored text of key
  29752. * @returns {ReadableStream<String>} ASCII armor
  29753. */
  29754. Key.prototype.armor = function () {
  29755. const type = this.isPublic() ? _enums2.default.armor.public_key : _enums2.default.armor.private_key;
  29756. return _armor2.default.encode(type, this.toPacketlist().write());
  29757. };
  29758. /**
  29759. * Returns last created key or key by given keyId that is available for signing and verification
  29760. * @param {module:type/keyid} keyId, optional
  29761. * @param {Date} date (optional) use the given date for verification instead of the current time
  29762. * @param {Object} userId, optional user ID
  29763. * @returns {Promise<module:key.Key|module:key~SubKey|null>} key or null if no signing key has been found
  29764. * @async
  29765. */
  29766. Key.prototype.getSigningKey = async function (keyId = null, date = new Date(), userId = {}) {
  29767. const primaryKey = this.keyPacket;
  29768. if ((await this.verifyPrimaryKey(date, userId)) === _enums2.default.keyStatus.valid) {
  29769. const subKeys = this.subKeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);
  29770. for (let i = 0; i < subKeys.length; i++) {
  29771. if (!keyId || subKeys[i].getKeyId().equals(keyId)) {
  29772. if ((await subKeys[i].verify(primaryKey, date)) === _enums2.default.keyStatus.valid) {
  29773. const dataToVerify = { key: primaryKey, bind: subKeys[i].keyPacket };
  29774. const bindingSignature = await helper.getLatestValidSignature(subKeys[i].bindingSignatures, primaryKey, _enums2.default.signature.subkey_binding, dataToVerify, date);
  29775. if (bindingSignature && bindingSignature.embeddedSignature && helper.isValidSigningKeyPacket(subKeys[i].keyPacket, bindingSignature) && (await helper.getLatestValidSignature([bindingSignature.embeddedSignature], subKeys[i].keyPacket, _enums2.default.signature.key_binding, dataToVerify, date))) {
  29776. return subKeys[i];
  29777. }
  29778. }
  29779. }
  29780. }
  29781. const primaryUser = await this.getPrimaryUser(date, userId);
  29782. if (primaryUser && (!keyId || primaryKey.getKeyId().equals(keyId)) && helper.isValidSigningKeyPacket(primaryKey, primaryUser.selfCertification)) {
  29783. return this;
  29784. }
  29785. }
  29786. return null;
  29787. };
  29788. /**
  29789. * Returns last created key or key by given keyId that is available for encryption or decryption
  29790. * @param {module:type/keyid} keyId, optional
  29791. * @param {Date} date, optional
  29792. * @param {String} userId, optional
  29793. * @returns {Promise<module:key.Key|module:key~SubKey|null>} key or null if no encryption key has been found
  29794. * @async
  29795. */
  29796. Key.prototype.getEncryptionKey = async function (keyId, date = new Date(), userId = {}) {
  29797. const primaryKey = this.keyPacket;
  29798. if ((await this.verifyPrimaryKey(date, userId)) === _enums2.default.keyStatus.valid) {
  29799. // V4: by convention subkeys are preffered for encryption service
  29800. const subKeys = this.subKeys.slice().sort((a, b) => b.keyPacket.created - a.keyPacket.created);
  29801. for (let i = 0; i < subKeys.length; i++) {
  29802. if (!keyId || subKeys[i].getKeyId().equals(keyId)) {
  29803. if ((await subKeys[i].verify(primaryKey, date)) === _enums2.default.keyStatus.valid) {
  29804. const dataToVerify = { key: primaryKey, bind: subKeys[i].keyPacket };
  29805. const bindingSignature = await helper.getLatestValidSignature(subKeys[i].bindingSignatures, primaryKey, _enums2.default.signature.subkey_binding, dataToVerify, date);
  29806. if (bindingSignature && helper.isValidEncryptionKeyPacket(subKeys[i].keyPacket, bindingSignature)) {
  29807. return subKeys[i];
  29808. }
  29809. }
  29810. }
  29811. }
  29812. // if no valid subkey for encryption, evaluate primary key
  29813. const primaryUser = await this.getPrimaryUser(date, userId);
  29814. if (primaryUser && (!keyId || primaryKey.getKeyId().equals(keyId)) && helper.isValidEncryptionKeyPacket(primaryKey, primaryUser.selfCertification)) {
  29815. return this;
  29816. }
  29817. }
  29818. return null;
  29819. };
  29820. /**
  29821. * Encrypts all secret key and subkey packets matching keyId
  29822. * @param {String|Array<String>} passphrases - if multiple passphrases, then should be in same order as packets each should encrypt
  29823. * @param {module:type/keyid} keyId
  29824. * @returns {Promise<Array<module:packet.SecretKey|module:packet.SecretSubkey>>}
  29825. * @async
  29826. */
  29827. Key.prototype.encrypt = async function (passphrases, keyId = null) {
  29828. if (!this.isPrivate()) {
  29829. throw new Error("Nothing to encrypt in a public key");
  29830. }
  29831. const keys = this.getKeys(keyId);
  29832. passphrases = _util2.default.isArray(passphrases) ? passphrases : new Array(keys.length).fill(passphrases);
  29833. if (passphrases.length !== keys.length) {
  29834. throw new Error("Invalid number of passphrases for key");
  29835. }
  29836. return Promise.all(keys.map(async function (key, i) {
  29837. const keyPacket = key.keyPacket;
  29838. await keyPacket.encrypt(passphrases[i]);
  29839. keyPacket.clearPrivateParams();
  29840. return keyPacket;
  29841. }));
  29842. };
  29843. /**
  29844. * Decrypts all secret key and subkey packets matching keyId
  29845. * @param {String|Array<String>} passphrases
  29846. * @param {module:type/keyid} keyId
  29847. * @returns {Promise<Boolean>} true if all matching key and subkey packets decrypted successfully
  29848. * @async
  29849. */
  29850. Key.prototype.decrypt = async function (passphrases, keyId = null) {
  29851. if (!this.isPrivate()) {
  29852. throw new Error("Nothing to decrypt in a public key");
  29853. }
  29854. passphrases = _util2.default.isArray(passphrases) ? passphrases : [passphrases];
  29855. const results = await Promise.all(this.getKeys(keyId).map(async function (key) {
  29856. let decrypted = false;
  29857. let error = null;
  29858. await Promise.all(passphrases.map(async function (passphrase) {
  29859. try {
  29860. await key.keyPacket.decrypt(passphrase);
  29861. decrypted = true;
  29862. } catch (e) {
  29863. error = e;
  29864. }
  29865. }));
  29866. if (!decrypted) {
  29867. throw error;
  29868. }
  29869. return decrypted;
  29870. }));
  29871. return results.every(result => result === true);
  29872. };
  29873. /**
  29874. * Checks if a signature on a key is revoked
  29875. * @param {module:packet.SecretKey|
  29876. * @param {module:packet.Signature} signature The signature to verify
  29877. * @param {module:packet.PublicSubkey|
  29878. * module:packet.SecretSubkey|
  29879. * module:packet.PublicKey|
  29880. * module:packet.SecretKey} key, optional The key to verify the signature
  29881. * @param {Date} date Use the given date instead of the current time
  29882. * @returns {Promise<Boolean>} True if the certificate is revoked
  29883. * @async
  29884. */
  29885. Key.prototype.isRevoked = async function (signature, key, date = new Date()) {
  29886. return helper.isDataRevoked(this.keyPacket, _enums2.default.signature.key_revocation, { key: this.keyPacket }, this.revocationSignatures, signature, key, date);
  29887. };
  29888. /**
  29889. * Verify primary key. Checks for revocation signatures, expiration time
  29890. * and valid self signature
  29891. * @param {Date} date (optional) use the given date for verification instead of the current time
  29892. * @param {Object} userId (optional) user ID
  29893. * @returns {Promise<module:enums.keyStatus>} The status of the primary key
  29894. * @async
  29895. */
  29896. Key.prototype.verifyPrimaryKey = async function (date = new Date(), userId = {}) {
  29897. const primaryKey = this.keyPacket;
  29898. // check for key revocation signatures
  29899. if (await this.isRevoked(null, null, date)) {
  29900. return _enums2.default.keyStatus.revoked;
  29901. }
  29902. // check for at least one self signature. Self signature of user ID not mandatory
  29903. // See {@link https://tools.ietf.org/html/rfc4880#section-11.1}
  29904. if (!this.users.some(user => user.userId && user.selfCertifications.length)) {
  29905. return _enums2.default.keyStatus.no_self_cert;
  29906. }
  29907. // check for valid, unrevoked, unexpired self signature
  29908. var _ref = (await this.getPrimaryUser(date, userId)) || {};
  29909. const user = _ref.user,
  29910. selfCertification = _ref.selfCertification;
  29911. if (!user) {
  29912. return _enums2.default.keyStatus.invalid;
  29913. }
  29914. // check for expiration time
  29915. if (helper.isDataExpired(primaryKey, selfCertification, date)) {
  29916. return _enums2.default.keyStatus.expired;
  29917. }
  29918. return _enums2.default.keyStatus.valid;
  29919. };
  29920. /**
  29921. * Returns the latest date when the key can be used for encrypting, signing, or both, depending on the `capabilities` paramater.
  29922. * When `capabilities` is null, defaults to returning the expiry date of the primary key.
  29923. * Returns null if `capabilities` is passed and the key does not have the specified capabilities or is revoked or invalid.
  29924. * Returns Infinity if the key doesn't expire.
  29925. * @param {encrypt|sign|encrypt_sign} capabilities, optional
  29926. * @param {module:type/keyid} keyId, optional
  29927. * @param {Object} userId, optional user ID
  29928. * @returns {Promise<Date | Infinity | null>}
  29929. * @async
  29930. */
  29931. Key.prototype.getExpirationTime = async function (capabilities, keyId, userId) {
  29932. const primaryUser = await this.getPrimaryUser(null, userId);
  29933. if (!primaryUser) {
  29934. throw new Error('Could not find primary user');
  29935. }
  29936. const selfCert = primaryUser.selfCertification;
  29937. const keyExpiry = helper.getExpirationTime(this.keyPacket, selfCert);
  29938. const sigExpiry = selfCert.getExpirationTime();
  29939. let expiry = keyExpiry < sigExpiry ? keyExpiry : sigExpiry;
  29940. if (capabilities === 'encrypt' || capabilities === 'encrypt_sign') {
  29941. const encryptKey = (await this.getEncryptionKey(keyId, expiry, userId)) || (await this.getEncryptionKey(keyId, null, userId));
  29942. if (!encryptKey) return null;
  29943. const encryptExpiry = await encryptKey.getExpirationTime(this.keyPacket);
  29944. if (encryptExpiry < expiry) expiry = encryptExpiry;
  29945. }
  29946. if (capabilities === 'sign' || capabilities === 'encrypt_sign') {
  29947. const signKey = (await this.getSigningKey(keyId, expiry, userId)) || (await this.getSigningKey(keyId, null, userId));
  29948. if (!signKey) return null;
  29949. const signExpiry = await signKey.getExpirationTime(this.keyPacket);
  29950. if (signExpiry < expiry) expiry = signExpiry;
  29951. }
  29952. return expiry;
  29953. };
  29954. /**
  29955. * Returns primary user and most significant (latest valid) self signature
  29956. * - if multiple primary users exist, returns the one with the latest self signature
  29957. * - otherwise, returns the user with the latest self signature
  29958. * @param {Date} date (optional) use the given date for verification instead of the current time
  29959. * @param {Object} userId (optional) user ID to get instead of the primary user, if it exists
  29960. * @returns {Promise<{user: module:key.User,
  29961. * selfCertification: module:packet.Signature}>} The primary user and the self signature
  29962. * @async
  29963. */
  29964. Key.prototype.getPrimaryUser = async function (date = new Date(), userId = {}) {
  29965. const primaryKey = this.keyPacket;
  29966. const users = [];
  29967. for (let i = 0; i < this.users.length; i++) {
  29968. const user = this.users[i];
  29969. if (!user.userId || !((userId.name === undefined || user.userId.name === userId.name) && (userId.email === undefined || user.userId.email === userId.email) && (userId.comment === undefined || user.userId.comment === userId.comment))) continue;
  29970. const dataToVerify = { userId: user.userId, key: primaryKey };
  29971. const selfCertification = await helper.getLatestValidSignature(user.selfCertifications, primaryKey, _enums2.default.signature.cert_generic, dataToVerify, date);
  29972. if (!selfCertification) continue;
  29973. users.push({ index: i, user, selfCertification });
  29974. }
  29975. if (!users.length) {
  29976. if (userId.name !== undefined || userId.email !== undefined || userId.comment !== undefined) {
  29977. throw new Error('Could not find user that matches that user ID');
  29978. }
  29979. return null;
  29980. }
  29981. await Promise.all(users.map(async function (a) {
  29982. return a.user.revoked || a.user.isRevoked(primaryKey, a.selfCertification, null, date);
  29983. }));
  29984. // sort by primary user flag and signature creation time
  29985. const primaryUser = users.sort(function (a, b) {
  29986. const A = a.selfCertification;
  29987. const B = b.selfCertification;
  29988. return B.revoked - A.revoked || A.isPrimaryUserID - B.isPrimaryUserID || A.created - B.created;
  29989. }).pop();
  29990. const user = primaryUser.user,
  29991. cert = primaryUser.selfCertification;
  29992. if (cert.revoked || (await user.isRevoked(primaryKey, cert, null, date))) {
  29993. return null;
  29994. }
  29995. return primaryUser;
  29996. };
  29997. /**
  29998. * Update key with new components from specified key with same key ID:
  29999. * users, subkeys, certificates are merged into the destination key,
  30000. * duplicates and expired signatures are ignored.
  30001. *
  30002. * If the specified key is a private key and the destination key is public,
  30003. * the destination key is transformed to a private key.
  30004. * @param {module:key.Key} key Source key to merge
  30005. * @returns {Promise<undefined>}
  30006. * @async
  30007. */
  30008. Key.prototype.update = async function (key) {
  30009. if ((await key.verifyPrimaryKey()) === _enums2.default.keyStatus.invalid) {
  30010. return;
  30011. }
  30012. if (!this.hasSameFingerprintAs(key)) {
  30013. throw new Error('Key update method: fingerprints of keys not equal');
  30014. }
  30015. if (this.isPublic() && key.isPrivate()) {
  30016. // check for equal subkey packets
  30017. const equal = this.subKeys.length === key.subKeys.length && this.subKeys.every(destSubKey => {
  30018. return key.subKeys.some(srcSubKey => {
  30019. return destSubKey.hasSameFingerprintAs(srcSubKey);
  30020. });
  30021. });
  30022. if (!equal) {
  30023. throw new Error('Cannot update public key with private key if subkey mismatch');
  30024. }
  30025. this.keyPacket = key.keyPacket;
  30026. }
  30027. // revocation signatures
  30028. await helper.mergeSignatures(key, this, 'revocationSignatures', srcRevSig => {
  30029. return helper.isDataRevoked(this.keyPacket, _enums2.default.signature.key_revocation, this, [srcRevSig], null, key.keyPacket);
  30030. });
  30031. // direct signatures
  30032. await helper.mergeSignatures(key, this, 'directSignatures');
  30033. // TODO replace when Promise.some or Promise.any are implemented
  30034. // users
  30035. await Promise.all(key.users.map(async srcUser => {
  30036. let found = false;
  30037. await Promise.all(this.users.map(async dstUser => {
  30038. if (srcUser.userId && dstUser.userId && srcUser.userId.userid === dstUser.userId.userid || srcUser.userAttribute && srcUser.userAttribute.equals(dstUser.userAttribute)) {
  30039. await dstUser.update(srcUser, this.keyPacket);
  30040. found = true;
  30041. }
  30042. }));
  30043. if (!found) {
  30044. this.users.push(srcUser);
  30045. }
  30046. }));
  30047. // TODO replace when Promise.some or Promise.any are implemented
  30048. // subkeys
  30049. await Promise.all(key.subKeys.map(async srcSubKey => {
  30050. let found = false;
  30051. await Promise.all(this.subKeys.map(async dstSubKey => {
  30052. if (dstSubKey.hasSameFingerprintAs(srcSubKey)) {
  30053. await dstSubKey.update(srcSubKey, this.keyPacket);
  30054. found = true;
  30055. }
  30056. }));
  30057. if (!found) {
  30058. this.subKeys.push(srcSubKey);
  30059. }
  30060. }));
  30061. };
  30062. /**
  30063. * Revokes the key
  30064. * @param {Object} reasonForRevocation optional, object indicating the reason for revocation
  30065. * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation
  30066. * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation
  30067. * @param {Date} date optional, override the creationtime of the revocation signature
  30068. * @returns {Promise<module:key.Key>} new key with revocation signature
  30069. * @async
  30070. */
  30071. Key.prototype.revoke = async function ({
  30072. flag: reasonForRevocationFlag = _enums2.default.reasonForRevocation.no_reason,
  30073. string: reasonForRevocationString = ''
  30074. } = {}, date = new Date()) {
  30075. if (this.isPublic()) {
  30076. throw new Error('Need private key for revoking');
  30077. }
  30078. const dataToSign = { key: this.keyPacket };
  30079. const key = new Key(this.toPacketlist());
  30080. key.revocationSignatures.push((await helper.createSignaturePacket(dataToSign, null, this.keyPacket, {
  30081. signatureType: _enums2.default.signature.key_revocation,
  30082. reasonForRevocationFlag: _enums2.default.write(_enums2.default.reasonForRevocation, reasonForRevocationFlag),
  30083. reasonForRevocationString
  30084. }, date)));
  30085. return key;
  30086. };
  30087. /**
  30088. * Get revocation certificate from a revoked key.
  30089. * (To get a revocation certificate for an unrevoked key, call revoke() first.)
  30090. * @returns {Promise<String>} armored revocation certificate
  30091. * @async
  30092. */
  30093. Key.prototype.getRevocationCertificate = async function () {
  30094. const dataToVerify = { key: this.keyPacket };
  30095. const revocationSignature = await helper.getLatestValidSignature(this.revocationSignatures, this.keyPacket, _enums2.default.signature.key_revocation, dataToVerify);
  30096. if (revocationSignature) {
  30097. const packetlist = new _packet2.default.List();
  30098. packetlist.push(revocationSignature);
  30099. return _armor2.default.encode(_enums2.default.armor.public_key, packetlist.write(), null, null, 'This is a revocation certificate');
  30100. }
  30101. };
  30102. /**
  30103. * Applies a revocation certificate to a key
  30104. * This adds the first signature packet in the armored text to the key,
  30105. * if it is a valid revocation signature.
  30106. * @param {String} revocationCertificate armored revocation certificate
  30107. * @returns {Promise<module:key.Key>} new revoked key
  30108. * @async
  30109. */
  30110. Key.prototype.applyRevocationCertificate = async function (revocationCertificate) {
  30111. const input = await _armor2.default.decode(revocationCertificate);
  30112. const packetlist = new _packet2.default.List();
  30113. await packetlist.read(input.data);
  30114. const revocationSignature = packetlist.findPacket(_enums2.default.packet.signature);
  30115. if (!revocationSignature || revocationSignature.signatureType !== _enums2.default.signature.key_revocation) {
  30116. throw new Error('Could not find revocation signature packet');
  30117. }
  30118. if (!revocationSignature.issuerKeyId.equals(this.getKeyId())) {
  30119. throw new Error('Revocation signature does not match key');
  30120. }
  30121. if (revocationSignature.isExpired()) {
  30122. throw new Error('Revocation signature is expired');
  30123. }
  30124. if (!(await revocationSignature.verify(this.keyPacket, _enums2.default.signature.key_revocation, { key: this.keyPacket }))) {
  30125. throw new Error('Could not verify revocation signature');
  30126. }
  30127. const key = new Key(this.toPacketlist());
  30128. key.revocationSignatures.push(revocationSignature);
  30129. return key;
  30130. };
  30131. /**
  30132. * Signs primary user of key
  30133. * @param {Array<module:key.Key>} privateKey decrypted private keys for signing
  30134. * @param {Date} date (optional) use the given date for verification instead of the current time
  30135. * @param {Object} userId (optional) user ID to get instead of the primary user, if it exists
  30136. * @returns {Promise<module:key.Key>} new public key with new certificate signature
  30137. * @async
  30138. */
  30139. Key.prototype.signPrimaryUser = async function (privateKeys, date, userId) {
  30140. var _ref2 = (await this.getPrimaryUser(date, userId)) || {};
  30141. const index = _ref2.index,
  30142. user = _ref2.user;
  30143. if (!user) {
  30144. throw new Error('Could not find primary user');
  30145. }
  30146. const userSign = await user.sign(this.keyPacket, privateKeys);
  30147. const key = new Key(this.toPacketlist());
  30148. key.users[index] = userSign;
  30149. return key;
  30150. };
  30151. /**
  30152. * Signs all users of key
  30153. * @param {Array<module:key.Key>} privateKeys decrypted private keys for signing
  30154. * @returns {Promise<module:key.Key>} new public key with new certificate signature
  30155. * @async
  30156. */
  30157. Key.prototype.signAllUsers = async function (privateKeys) {
  30158. const that = this;
  30159. const key = new Key(this.toPacketlist());
  30160. key.users = await Promise.all(this.users.map(function (user) {
  30161. return user.sign(that.keyPacket, privateKeys);
  30162. }));
  30163. return key;
  30164. };
  30165. /**
  30166. * Verifies primary user of key
  30167. * - if no arguments are given, verifies the self certificates;
  30168. * - otherwise, verifies all certificates signed with given keys.
  30169. * @param {Array<module:key.Key>} keys array of keys to verify certificate signatures
  30170. * @param {Date} date (optional) use the given date for verification instead of the current time
  30171. * @param {Object} userId (optional) user ID to get instead of the primary user, if it exists
  30172. * @returns {Promise<Array<{keyid: module:type/keyid,
  30173. * valid: Boolean}>>} List of signer's keyid and validity of signature
  30174. * @async
  30175. */
  30176. Key.prototype.verifyPrimaryUser = async function (keys, date, userId) {
  30177. const primaryKey = this.keyPacket;
  30178. var _ref3 = (await this.getPrimaryUser(date, userId)) || {};
  30179. const user = _ref3.user;
  30180. if (!user) {
  30181. throw new Error('Could not find primary user');
  30182. }
  30183. const results = keys ? await user.verifyAllCertifications(primaryKey, keys) : [{ keyid: primaryKey.keyid, valid: (await user.verify(primaryKey)) === _enums2.default.keyStatus.valid }];
  30184. return results;
  30185. };
  30186. /**
  30187. * Verifies all users of key
  30188. * - if no arguments are given, verifies the self certificates;
  30189. * - otherwise, verifies all certificates signed with given keys.
  30190. * @param {Array<module:key.Key>} keys array of keys to verify certificate signatures
  30191. * @returns {Promise<Array<{userid: String,
  30192. * keyid: module:type/keyid,
  30193. * valid: Boolean}>>} list of userid, signer's keyid and validity of signature
  30194. * @async
  30195. */
  30196. Key.prototype.verifyAllUsers = async function (keys) {
  30197. const results = [];
  30198. const primaryKey = this.keyPacket;
  30199. await Promise.all(this.users.map(async function (user) {
  30200. const signatures = keys ? await user.verifyAllCertifications(primaryKey, keys) : [{ keyid: primaryKey.keyid, valid: (await user.verify(primaryKey)) === _enums2.default.keyStatus.valid }];
  30201. signatures.forEach(signature => {
  30202. results.push({
  30203. userid: user.userId.userid,
  30204. keyid: signature.keyid,
  30205. valid: signature.valid
  30206. });
  30207. });
  30208. }));
  30209. return results;
  30210. };
  30211. /**
  30212. * Generates a new OpenPGP subkey, and returns a clone of the Key object with the new subkey added.
  30213. * Supports RSA and ECC keys. Defaults to the algorithm and bit size/curve of the primary key.
  30214. * @param {Integer} options.rsaBits number of bits for the key creation.
  30215. * @param {Number} [options.keyExpirationTime=0]
  30216. * The number of seconds after the key creation time that the key expires
  30217. * @param {String} curve (optional) Elliptic curve for ECC keys
  30218. * @param {Date} date (optional) Override the creation date of the key and the key signatures
  30219. * @param {Boolean} subkeys (optional) Indicates whether the subkey should sign rather than encrypt. Defaults to false
  30220. * @returns {Promise<module:key.Key>}
  30221. * @async
  30222. */
  30223. Key.prototype.addSubkey = async function (options = {}) {
  30224. if (!this.isPrivate()) {
  30225. throw new Error("Cannot add a subkey to a public key");
  30226. }
  30227. if (options.passphrase) {
  30228. throw new Error("Subkey could not be encrypted here, please encrypt whole key");
  30229. }
  30230. if (_util2.default.getWebCryptoAll() && options.rsaBits < 2048) {
  30231. throw new Error('When using webCrypto rsaBits should be 2048 or 4096, found: ' + options.rsaBits);
  30232. }
  30233. const secretKeyPacket = this.primaryKey;
  30234. if (!secretKeyPacket.isDecrypted()) {
  30235. throw new Error("Key is not decrypted");
  30236. }
  30237. const defaultOptions = secretKeyPacket.getAlgorithmInfo();
  30238. options = helper.sanitizeKeyOptions(options, defaultOptions);
  30239. const keyPacket = await helper.generateSecretSubkey(options);
  30240. const bindingSignature = await helper.createBindingSignature(keyPacket, secretKeyPacket, options);
  30241. const packetList = this.toPacketlist();
  30242. packetList.push(keyPacket);
  30243. packetList.push(bindingSignature);
  30244. return new Key(packetList);
  30245. };
  30246. ['getKeyId', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted', 'hasSameFingerprintAs'].forEach(name => {
  30247. Key.prototype[name] = _subkey2.default.prototype[name];
  30248. });
  30249. },{"../encoding/armor":111,"../enums":113,"../packet":131,"../util":158,"./helper":117,"./subkey":120,"./user":121}],120:[function(require,module,exports){
  30250. 'use strict';
  30251. Object.defineProperty(exports, "__esModule", {
  30252. value: true
  30253. });
  30254. exports.default = SubKey;
  30255. var _enums = require('../enums');
  30256. var _enums2 = _interopRequireDefault(_enums);
  30257. var _helper = require('./helper');
  30258. var helper = _interopRequireWildcard(_helper);
  30259. var _packet = require('../packet');
  30260. var _packet2 = _interopRequireDefault(_packet);
  30261. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  30262. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  30263. /**
  30264. * @class
  30265. * @classdesc Class that represents a subkey packet and the relevant signatures.
  30266. * @borrows module:packet.PublicSubkey#getKeyId as SubKey#getKeyId
  30267. * @borrows module:packet.PublicSubkey#getFingerprint as SubKey#getFingerprint
  30268. * @borrows module:packet.PublicSubkey#hasSameFingerprintAs as SubKey#hasSameFingerprintAs
  30269. * @borrows module:packet.PublicSubkey#getAlgorithmInfo as SubKey#getAlgorithmInfo
  30270. * @borrows module:packet.PublicSubkey#getCreationTime as SubKey#getCreationTime
  30271. * @borrows module:packet.PublicSubkey#isDecrypted as SubKey#isDecrypted
  30272. */
  30273. function SubKey(subKeyPacket) {
  30274. if (!(this instanceof SubKey)) {
  30275. return new SubKey(subKeyPacket);
  30276. }
  30277. this.keyPacket = subKeyPacket;
  30278. this.bindingSignatures = [];
  30279. this.revocationSignatures = [];
  30280. }
  30281. /**
  30282. * Transforms structured subkey data to packetlist
  30283. * @returns {module:packet.List}
  30284. */
  30285. /**
  30286. * @requires enums
  30287. * @requires key/helper
  30288. * @requires packet
  30289. * @module key/SubKey
  30290. */
  30291. SubKey.prototype.toPacketlist = function () {
  30292. const packetlist = new _packet2.default.List();
  30293. packetlist.push(this.keyPacket);
  30294. packetlist.concat(this.revocationSignatures);
  30295. packetlist.concat(this.bindingSignatures);
  30296. return packetlist;
  30297. };
  30298. /**
  30299. * Checks if a binding signature of a subkey is revoked
  30300. * @param {module:packet.SecretKey|
  30301. * module:packet.PublicKey} primaryKey The primary key packet
  30302. * @param {module:packet.Signature} signature The binding signature to verify
  30303. * @param {module:packet.PublicSubkey|
  30304. * module:packet.SecretSubkey|
  30305. * module:packet.PublicKey|
  30306. * module:packet.SecretKey} key, optional The key to verify the signature
  30307. * @param {Date} date Use the given date instead of the current time
  30308. * @returns {Promise<Boolean>} True if the binding signature is revoked
  30309. * @async
  30310. */
  30311. SubKey.prototype.isRevoked = async function (primaryKey, signature, key, date = new Date()) {
  30312. return helper.isDataRevoked(primaryKey, _enums2.default.signature.subkey_revocation, {
  30313. key: primaryKey,
  30314. bind: this.keyPacket
  30315. }, this.revocationSignatures, signature, key, date);
  30316. };
  30317. /**
  30318. * Verify subkey. Checks for revocation signatures, expiration time
  30319. * and valid binding signature
  30320. * @param {module:packet.SecretKey|
  30321. * module:packet.PublicKey} primaryKey The primary key packet
  30322. * @param {Date} date Use the given date instead of the current time
  30323. * @returns {Promise<module:enums.keyStatus>} The status of the subkey
  30324. * @async
  30325. */
  30326. SubKey.prototype.verify = async function (primaryKey, date = new Date()) {
  30327. const that = this;
  30328. const dataToVerify = { key: primaryKey, bind: this.keyPacket };
  30329. // check subkey binding signatures
  30330. const bindingSignature = await helper.getLatestValidSignature(this.bindingSignatures, primaryKey, _enums2.default.signature.subkey_binding, dataToVerify, date);
  30331. // check binding signature is verified
  30332. if (!bindingSignature) {
  30333. return _enums2.default.keyStatus.invalid;
  30334. }
  30335. // check binding signature is not revoked
  30336. if (bindingSignature.revoked || (await that.isRevoked(primaryKey, bindingSignature, null, date))) {
  30337. return _enums2.default.keyStatus.revoked;
  30338. }
  30339. // check for expiration time
  30340. if (helper.isDataExpired(this.keyPacket, bindingSignature, date)) {
  30341. return _enums2.default.keyStatus.expired;
  30342. }
  30343. return _enums2.default.keyStatus.valid; // binding signature passed all checks
  30344. };
  30345. /**
  30346. * Returns the expiration time of the subkey or Infinity if key does not expire
  30347. * Returns null if the subkey is invalid.
  30348. * @param {module:packet.SecretKey|
  30349. * module:packet.PublicKey} primaryKey The primary key packet
  30350. * @param {Date} date Use the given date instead of the current time
  30351. * @returns {Promise<Date | Infinity | null>}
  30352. * @async
  30353. */
  30354. SubKey.prototype.getExpirationTime = async function (primaryKey, date = new Date()) {
  30355. const dataToVerify = { key: primaryKey, bind: this.keyPacket };
  30356. const bindingSignature = await helper.getLatestValidSignature(this.bindingSignatures, primaryKey, _enums2.default.signature.subkey_binding, dataToVerify, date);
  30357. if (!bindingSignature) return null;
  30358. const keyExpiry = helper.getExpirationTime(this.keyPacket, bindingSignature);
  30359. const sigExpiry = bindingSignature.getExpirationTime();
  30360. return keyExpiry < sigExpiry ? keyExpiry : sigExpiry;
  30361. };
  30362. /**
  30363. * Update subkey with new components from specified subkey
  30364. * @param {module:key~SubKey} subKey Source subkey to merge
  30365. * @param {module:packet.SecretKey|
  30366. module:packet.SecretSubkey} primaryKey primary key used for validation
  30367. * @returns {Promise<undefined>}
  30368. * @async
  30369. */
  30370. SubKey.prototype.update = async function (subKey, primaryKey) {
  30371. if ((await subKey.verify(primaryKey)) === _enums2.default.keyStatus.invalid) {
  30372. return;
  30373. }
  30374. if (!this.hasSameFingerprintAs(subKey)) {
  30375. throw new Error('SubKey update method: fingerprints of subkeys not equal');
  30376. }
  30377. // key packet
  30378. if (this.keyPacket.tag === _enums2.default.packet.publicSubkey && subKey.keyPacket.tag === _enums2.default.packet.secretSubkey) {
  30379. this.keyPacket = subKey.keyPacket;
  30380. }
  30381. // update missing binding signatures
  30382. const that = this;
  30383. const dataToVerify = { key: primaryKey, bind: that.keyPacket };
  30384. await helper.mergeSignatures(subKey, this, 'bindingSignatures', async function (srcBindSig) {
  30385. if (!(srcBindSig.verified || (await srcBindSig.verify(primaryKey, _enums2.default.signature.subkey_binding, dataToVerify)))) {
  30386. return false;
  30387. }
  30388. for (let i = 0; i < that.bindingSignatures.length; i++) {
  30389. if (that.bindingSignatures[i].issuerKeyId.equals(srcBindSig.issuerKeyId)) {
  30390. if (srcBindSig.created > that.bindingSignatures[i].created) {
  30391. that.bindingSignatures[i] = srcBindSig;
  30392. }
  30393. return false;
  30394. }
  30395. }
  30396. return true;
  30397. });
  30398. // revocation signatures
  30399. await helper.mergeSignatures(subKey, this, 'revocationSignatures', function (srcRevSig) {
  30400. return helper.isDataRevoked(primaryKey, _enums2.default.signature.subkey_revocation, dataToVerify, [srcRevSig]);
  30401. });
  30402. };
  30403. /**
  30404. * Revokes the subkey
  30405. * @param {module:packet.SecretKey} primaryKey decrypted private primary key for revocation
  30406. * @param {Object} reasonForRevocation optional, object indicating the reason for revocation
  30407. * @param {module:enums.reasonForRevocation} reasonForRevocation.flag optional, flag indicating the reason for revocation
  30408. * @param {String} reasonForRevocation.string optional, string explaining the reason for revocation
  30409. * @param {Date} date optional, override the creationtime of the revocation signature
  30410. * @returns {Promise<module:key~SubKey>} new subkey with revocation signature
  30411. * @async
  30412. */
  30413. SubKey.prototype.revoke = async function (primaryKey, {
  30414. flag: reasonForRevocationFlag = _enums2.default.reasonForRevocation.no_reason,
  30415. string: reasonForRevocationString = ''
  30416. } = {}, date = new Date()) {
  30417. const dataToSign = { key: primaryKey, bind: this.keyPacket };
  30418. const subKey = new SubKey(this.keyPacket);
  30419. subKey.revocationSignatures.push((await helper.createSignaturePacket(dataToSign, null, primaryKey, {
  30420. signatureType: _enums2.default.signature.subkey_revocation,
  30421. reasonForRevocationFlag: _enums2.default.write(_enums2.default.reasonForRevocation, reasonForRevocationFlag),
  30422. reasonForRevocationString
  30423. }, date)));
  30424. await subKey.update(this, primaryKey);
  30425. return subKey;
  30426. };
  30427. ['getKeyId', 'getFingerprint', 'getAlgorithmInfo', 'getCreationTime', 'isDecrypted'].forEach(name => {
  30428. SubKey.prototype[name] = function () {
  30429. return this.keyPacket[name]();
  30430. };
  30431. });
  30432. SubKey.prototype.hasSameFingerprintAs = function (other) {
  30433. return this.keyPacket.hasSameFingerprintAs(other.keyPacket || other);
  30434. };
  30435. },{"../enums":113,"../packet":131,"./helper":117}],121:[function(require,module,exports){
  30436. 'use strict';
  30437. Object.defineProperty(exports, "__esModule", {
  30438. value: true
  30439. });
  30440. exports.default = User;
  30441. var _packet = require('../packet');
  30442. var _packet2 = _interopRequireDefault(_packet);
  30443. var _enums = require('../enums');
  30444. var _enums2 = _interopRequireDefault(_enums);
  30445. var _helper = require('./helper');
  30446. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  30447. /**
  30448. * @class
  30449. * @classdesc Class that represents an user ID or attribute packet and the relevant signatures.
  30450. */
  30451. function User(userPacket) {
  30452. if (!(this instanceof User)) {
  30453. return new User(userPacket);
  30454. }
  30455. this.userId = userPacket.tag === _enums2.default.packet.userid ? userPacket : null;
  30456. this.userAttribute = userPacket.tag === _enums2.default.packet.userAttribute ? userPacket : null;
  30457. this.selfCertifications = [];
  30458. this.otherCertifications = [];
  30459. this.revocationSignatures = [];
  30460. }
  30461. /**
  30462. * Transforms structured user data to packetlist
  30463. * @returns {module:packet.List}
  30464. */
  30465. /**
  30466. * @requires enums
  30467. * @requires packet
  30468. * @requires key/helper
  30469. * @module key/User
  30470. */
  30471. User.prototype.toPacketlist = function () {
  30472. const packetlist = new _packet2.default.List();
  30473. packetlist.push(this.userId || this.userAttribute);
  30474. packetlist.concat(this.revocationSignatures);
  30475. packetlist.concat(this.selfCertifications);
  30476. packetlist.concat(this.otherCertifications);
  30477. return packetlist;
  30478. };
  30479. /**
  30480. * Signs user
  30481. * @param {module:packet.SecretKey|
  30482. * module:packet.PublicKey} primaryKey The primary key packet
  30483. * @param {Array<module:key.Key>} privateKeys Decrypted private keys for signing
  30484. * @returns {Promise<module:key.Key>} New user with new certificate signatures
  30485. * @async
  30486. */
  30487. User.prototype.sign = async function (primaryKey, privateKeys) {
  30488. const dataToSign = {
  30489. userId: this.userId,
  30490. userAttribute: this.userAttribute,
  30491. key: primaryKey
  30492. };
  30493. const user = new User(dataToSign.userId || dataToSign.userAttribute);
  30494. user.otherCertifications = await Promise.all(privateKeys.map(async function (privateKey) {
  30495. if (privateKey.isPublic()) {
  30496. throw new Error('Need private key for signing');
  30497. }
  30498. if (privateKey.hasSameFingerprintAs(primaryKey)) {
  30499. throw new Error('Not implemented for self signing');
  30500. }
  30501. const signingKey = await privateKey.getSigningKey();
  30502. if (!signingKey) {
  30503. throw new Error('Could not find valid signing key packet in key ' + privateKey.getKeyId().toHex());
  30504. }
  30505. return (0, _helper.createSignaturePacket)(dataToSign, privateKey, signingKey.keyPacket, {
  30506. // Most OpenPGP implementations use generic certification (0x10)
  30507. signatureType: _enums2.default.signature.cert_generic,
  30508. keyFlags: [_enums2.default.keyFlags.certify_keys | _enums2.default.keyFlags.sign_data]
  30509. });
  30510. }));
  30511. await user.update(this, primaryKey);
  30512. return user;
  30513. };
  30514. /**
  30515. * Checks if a given certificate of the user is revoked
  30516. * @param {module:packet.SecretKey|
  30517. * module:packet.PublicKey} primaryKey The primary key packet
  30518. * @param {module:packet.Signature} certificate The certificate to verify
  30519. * @param {module:packet.PublicSubkey|
  30520. * module:packet.SecretSubkey|
  30521. * module:packet.PublicKey|
  30522. * module:packet.SecretKey} key, optional The key to verify the signature
  30523. * @param {Date} date Use the given date instead of the current time
  30524. * @returns {Promise<Boolean>} True if the certificate is revoked
  30525. * @async
  30526. */
  30527. User.prototype.isRevoked = async function (primaryKey, certificate, key, date = new Date()) {
  30528. return (0, _helper.isDataRevoked)(primaryKey, _enums2.default.signature.cert_revocation, {
  30529. key: primaryKey,
  30530. userId: this.userId,
  30531. userAttribute: this.userAttribute
  30532. }, this.revocationSignatures, certificate, key, date);
  30533. };
  30534. /**
  30535. * Verifies the user certificate
  30536. * @param {module:packet.SecretKey|
  30537. * module:packet.PublicKey} primaryKey The primary key packet
  30538. * @param {module:packet.Signature} certificate A certificate of this user
  30539. * @param {Array<module:key.Key>} keys Array of keys to verify certificate signatures
  30540. * @param {Date} date Use the given date instead of the current time
  30541. * @returns {Promise<module:enums.keyStatus>} status of the certificate
  30542. * @async
  30543. */
  30544. User.prototype.verifyCertificate = async function (primaryKey, certificate, keys, date = new Date()) {
  30545. const that = this;
  30546. const keyid = certificate.issuerKeyId;
  30547. const dataToVerify = {
  30548. userId: this.userId,
  30549. userAttribute: this.userAttribute,
  30550. key: primaryKey
  30551. };
  30552. const results = await Promise.all(keys.map(async function (key) {
  30553. if (!key.getKeyIds().some(id => id.equals(keyid))) {
  30554. return;
  30555. }
  30556. const signingKey = await key.getSigningKey(keyid, date);
  30557. if (certificate.revoked || (await that.isRevoked(primaryKey, certificate, signingKey.keyPacket, date))) {
  30558. return _enums2.default.keyStatus.revoked;
  30559. }
  30560. if (!(certificate.verified || (await certificate.verify(signingKey.keyPacket, _enums2.default.signature.cert_generic, dataToVerify)))) {
  30561. return _enums2.default.keyStatus.invalid;
  30562. }
  30563. if (certificate.isExpired(date)) {
  30564. return _enums2.default.keyStatus.expired;
  30565. }
  30566. return _enums2.default.keyStatus.valid;
  30567. }));
  30568. return results.find(result => result !== undefined);
  30569. };
  30570. /**
  30571. * Verifies all user certificates
  30572. * @param {module:packet.SecretKey|
  30573. * module:packet.PublicKey} primaryKey The primary key packet
  30574. * @param {Array<module:key.Key>} keys Array of keys to verify certificate signatures
  30575. * @param {Date} date Use the given date instead of the current time
  30576. * @returns {Promise<Array<{keyid: module:type/keyid,
  30577. * valid: Boolean}>>} List of signer's keyid and validity of signature
  30578. * @async
  30579. */
  30580. User.prototype.verifyAllCertifications = async function (primaryKey, keys, date = new Date()) {
  30581. const that = this;
  30582. const certifications = this.selfCertifications.concat(this.otherCertifications);
  30583. return Promise.all(certifications.map(async function (certification) {
  30584. const status = await that.verifyCertificate(primaryKey, certification, keys, date);
  30585. return {
  30586. keyid: certification.issuerKeyId,
  30587. valid: status === undefined ? null : status === _enums2.default.keyStatus.valid
  30588. };
  30589. }));
  30590. };
  30591. /**
  30592. * Verify User. Checks for existence of self signatures, revocation signatures
  30593. * and validity of self signature
  30594. * @param {module:packet.SecretKey|
  30595. * module:packet.PublicKey} primaryKey The primary key packet
  30596. * @param {Date} date Use the given date instead of the current time
  30597. * @returns {Promise<module:enums.keyStatus>} Status of user
  30598. * @async
  30599. */
  30600. User.prototype.verify = async function (primaryKey, date = new Date()) {
  30601. if (!this.selfCertifications.length) {
  30602. return _enums2.default.keyStatus.no_self_cert;
  30603. }
  30604. const that = this;
  30605. const dataToVerify = {
  30606. userId: this.userId,
  30607. userAttribute: this.userAttribute,
  30608. key: primaryKey
  30609. };
  30610. // TODO replace when Promise.some or Promise.any are implemented
  30611. const results = [_enums2.default.keyStatus.invalid].concat((await Promise.all(this.selfCertifications.map(async function (selfCertification) {
  30612. if (selfCertification.revoked || (await that.isRevoked(primaryKey, selfCertification, undefined, date))) {
  30613. return _enums2.default.keyStatus.revoked;
  30614. }
  30615. if (!(selfCertification.verified || (await selfCertification.verify(primaryKey, _enums2.default.signature.cert_generic, dataToVerify)))) {
  30616. return _enums2.default.keyStatus.invalid;
  30617. }
  30618. if (selfCertification.isExpired(date)) {
  30619. return _enums2.default.keyStatus.expired;
  30620. }
  30621. return _enums2.default.keyStatus.valid;
  30622. }))));
  30623. return results.some(status => status === _enums2.default.keyStatus.valid) ? _enums2.default.keyStatus.valid : results.pop();
  30624. };
  30625. /**
  30626. * Update user with new components from specified user
  30627. * @param {module:key.User} user Source user to merge
  30628. * @param {module:packet.SecretKey|
  30629. * module:packet.SecretSubkey} primaryKey primary key used for validation
  30630. * @returns {Promise<undefined>}
  30631. * @async
  30632. */
  30633. User.prototype.update = async function (user, primaryKey) {
  30634. const dataToVerify = {
  30635. userId: this.userId,
  30636. userAttribute: this.userAttribute,
  30637. key: primaryKey
  30638. };
  30639. // self signatures
  30640. await (0, _helper.mergeSignatures)(user, this, 'selfCertifications', async function (srcSelfSig) {
  30641. return srcSelfSig.verified || srcSelfSig.verify(primaryKey, _enums2.default.signature.cert_generic, dataToVerify);
  30642. });
  30643. // other signatures
  30644. await (0, _helper.mergeSignatures)(user, this, 'otherCertifications');
  30645. // revocation signatures
  30646. await (0, _helper.mergeSignatures)(user, this, 'revocationSignatures', function (srcRevSig) {
  30647. return (0, _helper.isDataRevoked)(primaryKey, _enums2.default.signature.cert_revocation, dataToVerify, [srcRevSig]);
  30648. });
  30649. };
  30650. },{"../enums":113,"../packet":131,"./helper":117}],122:[function(require,module,exports){
  30651. 'use strict';
  30652. Object.defineProperty(exports, "__esModule", {
  30653. value: true
  30654. });
  30655. var _keyring = require('./keyring.js');
  30656. var _keyring2 = _interopRequireDefault(_keyring);
  30657. var _localstore = require('./localstore.js');
  30658. var _localstore2 = _interopRequireDefault(_localstore);
  30659. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  30660. /**
  30661. * @fileoverview Functions dealing with storage of the keyring.
  30662. * @see module:keyring/keyring
  30663. * @see module:keyring/localstore
  30664. * @module keyring
  30665. */
  30666. _keyring2.default.localstore = _localstore2.default;
  30667. exports.default = _keyring2.default;
  30668. },{"./keyring.js":123,"./localstore.js":124}],123:[function(require,module,exports){
  30669. 'use strict';
  30670. Object.defineProperty(exports, "__esModule", {
  30671. value: true
  30672. });
  30673. var _key = require('../key');
  30674. var _localstore = require('./localstore');
  30675. var _localstore2 = _interopRequireDefault(_localstore);
  30676. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  30677. /**
  30678. * Initialization routine for the keyring.
  30679. * @constructor
  30680. * @param {keyring/localstore} [storeHandler] class implementing loadPublic(), loadPrivate(), storePublic(), and storePrivate() methods
  30681. */
  30682. // GPG4Browsers - An OpenPGP implementation in javascript
  30683. // Copyright (C) 2011 Recurity Labs GmbH
  30684. //
  30685. // This library is free software; you can redistribute it and/or
  30686. // modify it under the terms of the GNU Lesser General Public
  30687. // License as published by the Free Software Foundation; either
  30688. // version 3.0 of the License, or (at your option) any later version.
  30689. //
  30690. // This library is distributed in the hope that it will be useful,
  30691. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  30692. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  30693. // Lesser General Public License for more details.
  30694. //
  30695. // You should have received a copy of the GNU Lesser General Public
  30696. // License along with this library; if not, write to the Free Software
  30697. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  30698. /**
  30699. * @fileoverview Provides the Keyring class
  30700. * @requires key
  30701. * @requires keyring/localstore
  30702. * @module keyring/keyring
  30703. */
  30704. function Keyring(storeHandler) {
  30705. this.storeHandler = storeHandler || new _localstore2.default();
  30706. }
  30707. /**
  30708. * Calls the storeHandler to load the keys
  30709. * @async
  30710. */
  30711. Keyring.prototype.load = async function () {
  30712. this.publicKeys = new KeyArray((await this.storeHandler.loadPublic()));
  30713. this.privateKeys = new KeyArray((await this.storeHandler.loadPrivate()));
  30714. };
  30715. /**
  30716. * Calls the storeHandler to save the keys
  30717. * @async
  30718. */
  30719. Keyring.prototype.store = async function () {
  30720. await Promise.all([this.storeHandler.storePublic(this.publicKeys.keys), this.storeHandler.storePrivate(this.privateKeys.keys)]);
  30721. };
  30722. /**
  30723. * Clear the keyring - erase all the keys
  30724. */
  30725. Keyring.prototype.clear = function () {
  30726. this.publicKeys.keys = [];
  30727. this.privateKeys.keys = [];
  30728. };
  30729. /**
  30730. * Searches the keyring for keys having the specified key id
  30731. * @param {String} keyId provided as string of lowercase hex number
  30732. * withouth 0x prefix (can be 16-character key ID or fingerprint)
  30733. * @param {Boolean} deep if true search also in subkeys
  30734. * @returns {Array<module:key.Key>|null} keys found or null
  30735. */
  30736. Keyring.prototype.getKeysForId = function (keyId, deep) {
  30737. let result = [];
  30738. result = result.concat(this.publicKeys.getForId(keyId, deep) || []);
  30739. result = result.concat(this.privateKeys.getForId(keyId, deep) || []);
  30740. return result.length ? result : null;
  30741. };
  30742. /**
  30743. * Removes keys having the specified key id from the keyring
  30744. * @param {String} keyId provided as string of lowercase hex number
  30745. * withouth 0x prefix (can be 16-character key ID or fingerprint)
  30746. * @returns {Array<module:key.Key>|null} keys found or null
  30747. */
  30748. Keyring.prototype.removeKeysForId = function (keyId) {
  30749. let result = [];
  30750. result = result.concat(this.publicKeys.removeForId(keyId) || []);
  30751. result = result.concat(this.privateKeys.removeForId(keyId) || []);
  30752. return result.length ? result : null;
  30753. };
  30754. /**
  30755. * Get all public and private keys
  30756. * @returns {Array<module:key.Key>} all keys
  30757. */
  30758. Keyring.prototype.getAllKeys = function () {
  30759. return this.publicKeys.keys.concat(this.privateKeys.keys);
  30760. };
  30761. /**
  30762. * Array of keys
  30763. * @param {Array<module:key.Key>} keys The keys to store in this array
  30764. */
  30765. function KeyArray(keys) {
  30766. this.keys = keys;
  30767. }
  30768. /**
  30769. * Searches all keys in the KeyArray matching the address or address part of the user ids
  30770. * @param {String} email email address to search for
  30771. * @returns {Array<module:key.Key>} The public keys associated with provided email address.
  30772. */
  30773. KeyArray.prototype.getForAddress = function (email) {
  30774. const results = [];
  30775. for (let i = 0; i < this.keys.length; i++) {
  30776. if (emailCheck(email, this.keys[i])) {
  30777. results.push(this.keys[i]);
  30778. }
  30779. }
  30780. return results;
  30781. };
  30782. /**
  30783. * Checks a key to see if it matches the specified email address
  30784. * @private
  30785. * @param {String} email email address to search for
  30786. * @param {module:key.Key} key The key to be checked.
  30787. * @returns {Boolean} True if the email address is defined in the specified key
  30788. */
  30789. function emailCheck(email, key) {
  30790. email = email.toLowerCase();
  30791. // escape email before using in regular expression
  30792. const emailEsc = email.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  30793. const emailRegex = new RegExp('<' + emailEsc + '>');
  30794. const userIds = key.getUserIds();
  30795. for (let i = 0; i < userIds.length; i++) {
  30796. const userId = userIds[i].toLowerCase();
  30797. if (email === userId || emailRegex.test(userId)) {
  30798. return true;
  30799. }
  30800. }
  30801. return false;
  30802. }
  30803. /**
  30804. * Checks a key to see if it matches the specified keyid
  30805. * @private
  30806. * @param {String} keyId provided as string of lowercase hex number
  30807. * withouth 0x prefix (can be 16-character key ID or fingerprint)
  30808. * @param {module:key.Key|module:key.SubKey} key The key to be checked
  30809. * @returns {Boolean} True if key has the specified keyid
  30810. */
  30811. function keyIdCheck(keyId, key) {
  30812. if (keyId.length === 16) {
  30813. return keyId === key.getKeyId().toHex();
  30814. }
  30815. return keyId === key.getFingerprint();
  30816. }
  30817. /**
  30818. * Searches the KeyArray for a key having the specified key id
  30819. * @param {String} keyId provided as string of lowercase hex number
  30820. * withouth 0x prefix (can be 16-character key ID or fingerprint)
  30821. * @param {Boolean} deep if true search also in subkeys
  30822. * @returns {module:key.Key|null} key found or null
  30823. */
  30824. KeyArray.prototype.getForId = function (keyId, deep) {
  30825. for (let i = 0; i < this.keys.length; i++) {
  30826. if (keyIdCheck(keyId, this.keys[i])) {
  30827. return this.keys[i];
  30828. }
  30829. if (deep && this.keys[i].subKeys.length) {
  30830. for (let j = 0; j < this.keys[i].subKeys.length; j++) {
  30831. if (keyIdCheck(keyId, this.keys[i].subKeys[j])) {
  30832. return this.keys[i];
  30833. }
  30834. }
  30835. }
  30836. }
  30837. return null;
  30838. };
  30839. /**
  30840. * Imports a key from an ascii armored message
  30841. * @param {String} armored message to read the keys/key from
  30842. * @returns {Promise<Array<Error>|null>} array of error objects or null
  30843. * @async
  30844. */
  30845. KeyArray.prototype.importKey = async function (armored) {
  30846. const imported = await (0, _key.readArmored)(armored);
  30847. for (let i = 0; i < imported.keys.length; i++) {
  30848. const key = imported.keys[i];
  30849. // check if key already in key array
  30850. const keyidHex = key.getKeyId().toHex();
  30851. const keyFound = this.getForId(keyidHex);
  30852. if (keyFound) {
  30853. await keyFound.update(key);
  30854. } else {
  30855. this.push(key);
  30856. }
  30857. }
  30858. return imported.err ? imported.err : null;
  30859. };
  30860. /**
  30861. * Add key to KeyArray
  30862. * @param {module:key.Key} key The key that will be added to the keyring
  30863. * @returns {Number} The new length of the KeyArray
  30864. */
  30865. KeyArray.prototype.push = function (key) {
  30866. return this.keys.push(key);
  30867. };
  30868. /**
  30869. * Removes a key with the specified keyid from the keyring
  30870. * @param {String} keyId provided as string of lowercase hex number
  30871. * withouth 0x prefix (can be 16-character key ID or fingerprint)
  30872. * @returns {module:key.Key|null} The key object which has been removed or null
  30873. */
  30874. KeyArray.prototype.removeForId = function (keyId) {
  30875. for (let i = 0; i < this.keys.length; i++) {
  30876. if (keyIdCheck(keyId, this.keys[i])) {
  30877. return this.keys.splice(i, 1)[0];
  30878. }
  30879. }
  30880. return null;
  30881. };
  30882. exports.default = Keyring;
  30883. },{"../key":118,"./localstore":124}],124:[function(require,module,exports){
  30884. 'use strict';
  30885. Object.defineProperty(exports, "__esModule", {
  30886. value: true
  30887. });
  30888. var _webStreamTools = require('web-stream-tools');
  30889. var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
  30890. var _config = require('../config');
  30891. var _config2 = _interopRequireDefault(_config);
  30892. var _key = require('../key');
  30893. var _util = require('../util');
  30894. var _util2 = _interopRequireDefault(_util);
  30895. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  30896. /**
  30897. * The class that deals with storage of the keyring.
  30898. * Currently the only option is to use HTML5 local storage.
  30899. * @constructor
  30900. * @param {String} prefix prefix for itemnames in localstore
  30901. */
  30902. // GPG4Browsers - An OpenPGP implementation in javascript
  30903. // Copyright (C) 2011 Recurity Labs GmbH
  30904. //
  30905. // This library is free software; you can redistribute it and/or
  30906. // modify it under the terms of the GNU Lesser General Public
  30907. // License as published by the Free Software Foundation; either
  30908. // version 3.0 of the License, or (at your option) any later version.
  30909. //
  30910. // This library is distributed in the hope that it will be useful,
  30911. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  30912. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  30913. // Lesser General Public License for more details.
  30914. //
  30915. // You should have received a copy of the GNU Lesser General Public
  30916. // License along with this library; if not, write to the Free Software
  30917. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  30918. /**
  30919. * @fileoverview Provides the LocalStore class
  30920. * @requires web-stream-tools
  30921. * @requires config
  30922. * @requires key
  30923. * @requires util
  30924. * @module keyring/localstore
  30925. */
  30926. function LocalStore(prefix) {
  30927. prefix = prefix || 'openpgp-';
  30928. this.publicKeysItem = prefix + this.publicKeysItem;
  30929. this.privateKeysItem = prefix + this.privateKeysItem;
  30930. if (typeof window !== 'undefined' && window.localStorage) {
  30931. this.storage = window.localStorage;
  30932. } else {
  30933. this.storage = new (require('node-localstorage').LocalStorage)(_config2.default.node_store);
  30934. }
  30935. }
  30936. /*
  30937. * Declare the localstore itemnames
  30938. */
  30939. LocalStore.prototype.publicKeysItem = 'public-keys';
  30940. LocalStore.prototype.privateKeysItem = 'private-keys';
  30941. /**
  30942. * Load the public keys from HTML5 local storage.
  30943. * @returns {Array<module:key.Key>} array of keys retrieved from localstore
  30944. * @async
  30945. */
  30946. LocalStore.prototype.loadPublic = async function () {
  30947. return loadKeys(this.storage, this.publicKeysItem);
  30948. };
  30949. /**
  30950. * Load the private keys from HTML5 local storage.
  30951. * @returns {Array<module:key.Key>} array of keys retrieved from localstore
  30952. * @async
  30953. */
  30954. LocalStore.prototype.loadPrivate = async function () {
  30955. return loadKeys(this.storage, this.privateKeysItem);
  30956. };
  30957. async function loadKeys(storage, itemname) {
  30958. const armoredKeys = JSON.parse(storage.getItem(itemname));
  30959. const keys = [];
  30960. if (armoredKeys !== null && armoredKeys.length !== 0) {
  30961. let key;
  30962. for (let i = 0; i < armoredKeys.length; i++) {
  30963. key = await (0, _key.readArmored)(armoredKeys[i]);
  30964. if (!key.err) {
  30965. keys.push(key.keys[0]);
  30966. } else {
  30967. _util2.default.print_debug("Error reading armored key from keyring index: " + i);
  30968. }
  30969. }
  30970. }
  30971. return keys;
  30972. }
  30973. /**
  30974. * Saves the current state of the public keys to HTML5 local storage.
  30975. * The key array gets stringified using JSON
  30976. * @param {Array<module:key.Key>} keys array of keys to save in localstore
  30977. * @async
  30978. */
  30979. LocalStore.prototype.storePublic = async function (keys) {
  30980. await storeKeys(this.storage, this.publicKeysItem, keys);
  30981. };
  30982. /**
  30983. * Saves the current state of the private keys to HTML5 local storage.
  30984. * The key array gets stringified using JSON
  30985. * @param {Array<module:key.Key>} keys array of keys to save in localstore
  30986. * @async
  30987. */
  30988. LocalStore.prototype.storePrivate = async function (keys) {
  30989. await storeKeys(this.storage, this.privateKeysItem, keys);
  30990. };
  30991. async function storeKeys(storage, itemname, keys) {
  30992. if (keys.length) {
  30993. const armoredKeys = await Promise.all(keys.map(key => _webStreamTools2.default.readToEnd(key.armor())));
  30994. storage.setItem(itemname, JSON.stringify(armoredKeys));
  30995. } else {
  30996. storage.removeItem(itemname);
  30997. }
  30998. }
  30999. exports.default = LocalStore;
  31000. },{"../config":79,"../key":118,"../util":158,"node-localstorage":"node-localstorage","web-stream-tools":75}],125:[function(require,module,exports){
  31001. 'use strict';
  31002. Object.defineProperty(exports, "__esModule", {
  31003. value: true
  31004. });
  31005. /**
  31006. * Load script from path
  31007. * @param {String} path
  31008. */
  31009. const loadScript = exports.loadScript = path => {
  31010. if (typeof importScripts !== 'undefined') {
  31011. return importScripts(path);
  31012. }
  31013. return new Promise((resolve, reject) => {
  31014. const script = document.createElement('script');
  31015. script.src = path;
  31016. script.onload = () => resolve();
  31017. script.onerror = e => reject(new Error(e.message));
  31018. document.head.appendChild(script);
  31019. });
  31020. };
  31021. /**
  31022. * Download script from path
  31023. * @param {String} path fetch path
  31024. * @param {Object} options fetch options
  31025. */
  31026. const dl = exports.dl = async function dl(path, options) {
  31027. const response = await fetch(path, options);
  31028. return response.arrayBuffer();
  31029. };
  31030. },{}],126:[function(require,module,exports){
  31031. 'use strict';
  31032. Object.defineProperty(exports, "__esModule", {
  31033. value: true
  31034. });
  31035. exports.Message = Message;
  31036. exports.encryptSessionKey = encryptSessionKey;
  31037. exports.createSignaturePackets = createSignaturePackets;
  31038. exports.createVerificationObjects = createVerificationObjects;
  31039. exports.readArmored = readArmored;
  31040. exports.read = read;
  31041. exports.fromText = fromText;
  31042. exports.fromBinary = fromBinary;
  31043. var _webStreamTools = require('web-stream-tools');
  31044. var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
  31045. var _armor = require('./encoding/armor');
  31046. var _armor2 = _interopRequireDefault(_armor);
  31047. var _keyid = require('./type/keyid');
  31048. var _keyid2 = _interopRequireDefault(_keyid);
  31049. var _config = require('./config');
  31050. var _config2 = _interopRequireDefault(_config);
  31051. var _crypto = require('./crypto');
  31052. var _crypto2 = _interopRequireDefault(_crypto);
  31053. var _enums = require('./enums');
  31054. var _enums2 = _interopRequireDefault(_enums);
  31055. var _util = require('./util');
  31056. var _util2 = _interopRequireDefault(_util);
  31057. var _packet = require('./packet');
  31058. var _packet2 = _interopRequireDefault(_packet);
  31059. var _signature = require('./signature');
  31060. var _key = require('./key');
  31061. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  31062. /**
  31063. * @class
  31064. * @classdesc Class that represents an OpenPGP message.
  31065. * Can be an encrypted message, signed message, compressed message or literal message
  31066. * @param {module:packet.List} packetlist The packets that form this message
  31067. * See {@link https://tools.ietf.org/html/rfc4880#section-11.3}
  31068. */
  31069. // GPG4Browsers - An OpenPGP implementation in javascript
  31070. // Copyright (C) 2011 Recurity Labs GmbH
  31071. //
  31072. // This library is free software; you can redistribute it and/or
  31073. // modify it under the terms of the GNU Lesser General Public
  31074. // License as published by the Free Software Foundation; either
  31075. // version 3.0 of the License, or (at your option) any later version.
  31076. //
  31077. // This library is distributed in the hope that it will be useful,
  31078. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  31079. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  31080. // Lesser General Public License for more details.
  31081. //
  31082. // You should have received a copy of the GNU Lesser General Public
  31083. // License along with this library; if not, write to the Free Software
  31084. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  31085. /**
  31086. * @requires web-stream-tools
  31087. * @requires encoding/armor
  31088. * @requires type/keyid
  31089. * @requires config
  31090. * @requires crypto
  31091. * @requires enums
  31092. * @requires util
  31093. * @requires packet
  31094. * @requires signature
  31095. * @requires key
  31096. * @module message
  31097. */
  31098. function Message(packetlist) {
  31099. if (!(this instanceof Message)) {
  31100. return new Message(packetlist);
  31101. }
  31102. this.packets = packetlist || new _packet2.default.List();
  31103. }
  31104. /**
  31105. * Returns the key IDs of the keys to which the session key is encrypted
  31106. * @returns {Array<module:type/keyid>} array of keyid objects
  31107. */
  31108. Message.prototype.getEncryptionKeyIds = function () {
  31109. const keyIds = [];
  31110. const pkESKeyPacketlist = this.packets.filterByTag(_enums2.default.packet.publicKeyEncryptedSessionKey);
  31111. pkESKeyPacketlist.forEach(function (packet) {
  31112. keyIds.push(packet.publicKeyId);
  31113. });
  31114. return keyIds;
  31115. };
  31116. /**
  31117. * Returns the key IDs of the keys that signed the message
  31118. * @returns {Array<module:type/keyid>} array of keyid objects
  31119. */
  31120. Message.prototype.getSigningKeyIds = function () {
  31121. const keyIds = [];
  31122. const msg = this.unwrapCompressed();
  31123. // search for one pass signatures
  31124. const onePassSigList = msg.packets.filterByTag(_enums2.default.packet.onePassSignature);
  31125. onePassSigList.forEach(function (packet) {
  31126. keyIds.push(packet.issuerKeyId);
  31127. });
  31128. // if nothing found look for signature packets
  31129. if (!keyIds.length) {
  31130. const signatureList = msg.packets.filterByTag(_enums2.default.packet.signature);
  31131. signatureList.forEach(function (packet) {
  31132. keyIds.push(packet.issuerKeyId);
  31133. });
  31134. }
  31135. return keyIds;
  31136. };
  31137. /**
  31138. * Decrypt the message. Either a private key, a session key, or a password must be specified.
  31139. * @param {Array<Key>} privateKeys (optional) private keys with decrypted secret data
  31140. * @param {Array<String>} passwords (optional) passwords used to decrypt
  31141. * @param {Array<Object>} sessionKeys (optional) session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }
  31142. * @param {Boolean} streaming (optional) whether to process data as a stream
  31143. * @returns {Promise<Message>} new message with decrypted content
  31144. * @async
  31145. */
  31146. Message.prototype.decrypt = async function (privateKeys, passwords, sessionKeys, streaming) {
  31147. const keyObjs = sessionKeys || (await this.decryptSessionKeys(privateKeys, passwords));
  31148. const symEncryptedPacketlist = this.packets.filterByTag(_enums2.default.packet.symmetricallyEncrypted, _enums2.default.packet.symEncryptedIntegrityProtected, _enums2.default.packet.symEncryptedAEADProtected);
  31149. if (symEncryptedPacketlist.length === 0) {
  31150. return this;
  31151. }
  31152. const symEncryptedPacket = symEncryptedPacketlist[0];
  31153. let exception = null;
  31154. const decryptedPromise = Promise.all(keyObjs.map(async keyObj => {
  31155. if (!keyObj || !_util2.default.isUint8Array(keyObj.data) || !_util2.default.isString(keyObj.algorithm)) {
  31156. throw new Error('Invalid session key for decryption.');
  31157. }
  31158. try {
  31159. await symEncryptedPacket.decrypt(keyObj.algorithm, keyObj.data, streaming);
  31160. } catch (e) {
  31161. _util2.default.print_debug_error(e);
  31162. exception = e;
  31163. }
  31164. }));
  31165. // We don't await stream.cancel here because it only returns when the other copy is canceled too.
  31166. _webStreamTools2.default.cancel(symEncryptedPacket.encrypted); // Don't keep copy of encrypted data in memory.
  31167. symEncryptedPacket.encrypted = null;
  31168. await decryptedPromise;
  31169. if (!symEncryptedPacket.packets || !symEncryptedPacket.packets.length) {
  31170. throw exception || new Error('Decryption failed.');
  31171. }
  31172. const resultMsg = new Message(symEncryptedPacket.packets);
  31173. symEncryptedPacket.packets = new _packet2.default.List(); // remove packets after decryption
  31174. return resultMsg;
  31175. };
  31176. /**
  31177. * Decrypt encrypted session keys either with private keys or passwords.
  31178. * @param {Array<Key>} privateKeys (optional) private keys with decrypted secret data
  31179. * @param {Array<String>} passwords (optional) passwords used to decrypt
  31180. * @returns {Promise<Array<{ data: Uint8Array,
  31181. algorithm: String }>>} array of object with potential sessionKey, algorithm pairs
  31182. * @async
  31183. */
  31184. Message.prototype.decryptSessionKeys = async function (privateKeys, passwords) {
  31185. let keyPackets = [];
  31186. let exception;
  31187. if (passwords) {
  31188. const symESKeyPacketlist = this.packets.filterByTag(_enums2.default.packet.symEncryptedSessionKey);
  31189. if (!symESKeyPacketlist) {
  31190. throw new Error('No symmetrically encrypted session key packet found.');
  31191. }
  31192. await Promise.all(passwords.map(async function (password, i) {
  31193. let packets;
  31194. if (i) {
  31195. packets = new _packet2.default.List();
  31196. await packets.read(symESKeyPacketlist.write());
  31197. } else {
  31198. packets = symESKeyPacketlist;
  31199. }
  31200. await Promise.all(packets.map(async function (keyPacket) {
  31201. try {
  31202. await keyPacket.decrypt(password);
  31203. keyPackets.push(keyPacket);
  31204. } catch (err) {
  31205. _util2.default.print_debug_error(err);
  31206. }
  31207. }));
  31208. }));
  31209. } else if (privateKeys) {
  31210. const pkESKeyPacketlist = this.packets.filterByTag(_enums2.default.packet.publicKeyEncryptedSessionKey);
  31211. if (!pkESKeyPacketlist) {
  31212. throw new Error('No public key encrypted session key packet found.');
  31213. }
  31214. await Promise.all(pkESKeyPacketlist.map(async function (keyPacket) {
  31215. await Promise.all(privateKeys.map(async function (privateKey) {
  31216. const primaryUser = await privateKey.getPrimaryUser(); // TODO: Pass userId from somewhere.
  31217. let algos = [_enums2.default.symmetric.aes256, // Old OpenPGP.js default fallback
  31218. _enums2.default.symmetric.aes128, // RFC4880bis fallback
  31219. _enums2.default.symmetric.tripledes, // RFC4880 fallback
  31220. _enums2.default.symmetric.cast5 // Golang OpenPGP fallback
  31221. ];
  31222. if (primaryUser && primaryUser.selfCertification.preferredSymmetricAlgorithms) {
  31223. algos = algos.concat(primaryUser.selfCertification.preferredSymmetricAlgorithms);
  31224. }
  31225. const privateKeyPackets = privateKey.getKeys(keyPacket.publicKeyId).map(key => key.keyPacket);
  31226. await Promise.all(privateKeyPackets.map(async function (privateKeyPacket) {
  31227. if (!privateKeyPacket) {
  31228. return;
  31229. }
  31230. if (!privateKeyPacket.isDecrypted()) {
  31231. throw new Error('Private key is not decrypted.');
  31232. }
  31233. try {
  31234. await keyPacket.decrypt(privateKeyPacket);
  31235. if (!algos.includes(_enums2.default.write(_enums2.default.symmetric, keyPacket.sessionKeyAlgorithm))) {
  31236. throw new Error('A non-preferred symmetric algorithm was used.');
  31237. }
  31238. keyPackets.push(keyPacket);
  31239. } catch (err) {
  31240. _util2.default.print_debug_error(err);
  31241. exception = err;
  31242. }
  31243. }));
  31244. }));
  31245. _webStreamTools2.default.cancel(keyPacket.encrypted); // Don't keep copy of encrypted data in memory.
  31246. keyPacket.encrypted = null;
  31247. }));
  31248. } else {
  31249. throw new Error('No key or password specified.');
  31250. }
  31251. if (keyPackets.length) {
  31252. // Return only unique session keys
  31253. if (keyPackets.length > 1) {
  31254. const seen = {};
  31255. keyPackets = keyPackets.filter(function (item) {
  31256. const k = item.sessionKeyAlgorithm + _util2.default.Uint8Array_to_str(item.sessionKey);
  31257. if (seen.hasOwnProperty(k)) {
  31258. return false;
  31259. }
  31260. seen[k] = true;
  31261. return true;
  31262. });
  31263. }
  31264. return keyPackets.map(packet => ({ data: packet.sessionKey, algorithm: packet.sessionKeyAlgorithm }));
  31265. }
  31266. throw exception || new Error('Session key decryption failed.');
  31267. };
  31268. /**
  31269. * Get literal data that is the body of the message
  31270. * @returns {(Uint8Array|null)} literal body of the message as Uint8Array
  31271. */
  31272. Message.prototype.getLiteralData = function () {
  31273. const msg = this.unwrapCompressed();
  31274. const literal = msg.packets.findPacket(_enums2.default.packet.literal);
  31275. return literal && literal.getBytes() || null;
  31276. };
  31277. /**
  31278. * Get filename from literal data packet
  31279. * @returns {(String|null)} filename of literal data packet as string
  31280. */
  31281. Message.prototype.getFilename = function () {
  31282. const msg = this.unwrapCompressed();
  31283. const literal = msg.packets.findPacket(_enums2.default.packet.literal);
  31284. return literal && literal.getFilename() || null;
  31285. };
  31286. /**
  31287. * Get literal data as text
  31288. * @returns {(String|null)} literal body of the message interpreted as text
  31289. */
  31290. Message.prototype.getText = function () {
  31291. const msg = this.unwrapCompressed();
  31292. const literal = msg.packets.findPacket(_enums2.default.packet.literal);
  31293. if (literal) {
  31294. return literal.getText();
  31295. }
  31296. return null;
  31297. };
  31298. /**
  31299. * Encrypt the message either with public keys, passwords, or both at once.
  31300. * @param {Array<Key>} keys (optional) public key(s) for message encryption
  31301. * @param {Array<String>} passwords (optional) password(s) for message encryption
  31302. * @param {Object} sessionKey (optional) session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] }
  31303. * @param {Boolean} wildcard (optional) use a key ID of 0 instead of the public key IDs
  31304. * @param {Date} date (optional) override the creation date of the literal package
  31305. * @param {Array} userIds (optional) user IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]
  31306. * @param {Boolean} streaming (optional) whether to process data as a stream
  31307. * @returns {Promise<Message>} new message with encrypted content
  31308. * @async
  31309. */
  31310. Message.prototype.encrypt = async function (keys, passwords, sessionKey, wildcard = false, date = new Date(), userIds = [], streaming) {
  31311. let symAlgo;
  31312. let aeadAlgo;
  31313. let symEncryptedPacket;
  31314. if (sessionKey) {
  31315. if (!_util2.default.isUint8Array(sessionKey.data) || !_util2.default.isString(sessionKey.algorithm)) {
  31316. throw new Error('Invalid session key for encryption.');
  31317. }
  31318. symAlgo = sessionKey.algorithm;
  31319. aeadAlgo = sessionKey.aeadAlgorithm;
  31320. sessionKey = sessionKey.data;
  31321. } else if (keys && keys.length) {
  31322. symAlgo = _enums2.default.read(_enums2.default.symmetric, (await (0, _key.getPreferredAlgo)('symmetric', keys, date, userIds)));
  31323. if (_config2.default.aead_protect && (await (0, _key.isAeadSupported)(keys, date, userIds))) {
  31324. aeadAlgo = _enums2.default.read(_enums2.default.aead, (await (0, _key.getPreferredAlgo)('aead', keys, date, userIds)));
  31325. }
  31326. } else if (passwords && passwords.length) {
  31327. symAlgo = _enums2.default.read(_enums2.default.symmetric, _config2.default.encryption_cipher);
  31328. aeadAlgo = _enums2.default.read(_enums2.default.aead, _config2.default.aead_mode);
  31329. } else {
  31330. throw new Error('No keys, passwords, or session key provided.');
  31331. }
  31332. if (!sessionKey) {
  31333. sessionKey = await _crypto2.default.generateSessionKey(symAlgo);
  31334. }
  31335. const msg = await encryptSessionKey(sessionKey, symAlgo, aeadAlgo, keys, passwords, wildcard, date, userIds);
  31336. if (_config2.default.aead_protect && aeadAlgo) {
  31337. symEncryptedPacket = new _packet2.default.SymEncryptedAEADProtected();
  31338. symEncryptedPacket.aeadAlgorithm = aeadAlgo;
  31339. } else if (_config2.default.integrity_protect) {
  31340. symEncryptedPacket = new _packet2.default.SymEncryptedIntegrityProtected();
  31341. } else {
  31342. symEncryptedPacket = new _packet2.default.SymmetricallyEncrypted();
  31343. }
  31344. symEncryptedPacket.packets = this.packets;
  31345. await symEncryptedPacket.encrypt(symAlgo, sessionKey, streaming);
  31346. msg.packets.push(symEncryptedPacket);
  31347. symEncryptedPacket.packets = new _packet2.default.List(); // remove packets after encryption
  31348. return {
  31349. message: msg,
  31350. sessionKey: {
  31351. data: sessionKey,
  31352. algorithm: symAlgo,
  31353. aeadAlgorithm: aeadAlgo
  31354. }
  31355. };
  31356. };
  31357. /**
  31358. * Encrypt a session key either with public keys, passwords, or both at once.
  31359. * @param {Uint8Array} sessionKey session key for encryption
  31360. * @param {String} symAlgo session key algorithm
  31361. * @param {String} aeadAlgo (optional) aead algorithm, e.g. 'eax' or 'ocb'
  31362. * @param {Array<Key>} publicKeys (optional) public key(s) for message encryption
  31363. * @param {Array<String>} passwords (optional) for message encryption
  31364. * @param {Boolean} wildcard (optional) use a key ID of 0 instead of the public key IDs
  31365. * @param {Date} date (optional) override the date
  31366. * @param {Array} userIds (optional) user IDs to encrypt for, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]
  31367. * @returns {Promise<Message>} new message with encrypted content
  31368. * @async
  31369. */
  31370. async function encryptSessionKey(sessionKey, symAlgo, aeadAlgo, publicKeys, passwords, wildcard = false, date = new Date(), userIds = []) {
  31371. const packetlist = new _packet2.default.List();
  31372. if (publicKeys) {
  31373. const results = await Promise.all(publicKeys.map(async function (publicKey) {
  31374. const encryptionKey = await publicKey.getEncryptionKey(undefined, date, userIds);
  31375. if (!encryptionKey) {
  31376. throw new Error('Could not find valid key packet for encryption in key ' + publicKey.getKeyId().toHex());
  31377. }
  31378. const pkESKeyPacket = new _packet2.default.PublicKeyEncryptedSessionKey();
  31379. pkESKeyPacket.publicKeyId = wildcard ? _keyid2.default.wildcard() : encryptionKey.getKeyId();
  31380. pkESKeyPacket.publicKeyAlgorithm = encryptionKey.keyPacket.algorithm;
  31381. pkESKeyPacket.sessionKey = sessionKey;
  31382. pkESKeyPacket.sessionKeyAlgorithm = symAlgo;
  31383. await pkESKeyPacket.encrypt(encryptionKey.keyPacket);
  31384. delete pkESKeyPacket.sessionKey; // delete plaintext session key after encryption
  31385. return pkESKeyPacket;
  31386. }));
  31387. packetlist.concat(results);
  31388. }
  31389. if (passwords) {
  31390. const testDecrypt = async function testDecrypt(keyPacket, password) {
  31391. try {
  31392. await keyPacket.decrypt(password);
  31393. return 1;
  31394. } catch (e) {
  31395. return 0;
  31396. }
  31397. };
  31398. const sum = (accumulator, currentValue) => accumulator + currentValue;
  31399. const encryptPassword = async function encryptPassword(sessionKey, symAlgo, aeadAlgo, password) {
  31400. const symEncryptedSessionKeyPacket = new _packet2.default.SymEncryptedSessionKey();
  31401. symEncryptedSessionKeyPacket.sessionKey = sessionKey;
  31402. symEncryptedSessionKeyPacket.sessionKeyAlgorithm = symAlgo;
  31403. if (aeadAlgo) {
  31404. symEncryptedSessionKeyPacket.aeadAlgorithm = aeadAlgo;
  31405. }
  31406. await symEncryptedSessionKeyPacket.encrypt(password);
  31407. if (_config2.default.password_collision_check) {
  31408. const results = await Promise.all(passwords.map(pwd => testDecrypt(symEncryptedSessionKeyPacket, pwd)));
  31409. if (results.reduce(sum) !== 1) {
  31410. return encryptPassword(sessionKey, symAlgo, password);
  31411. }
  31412. }
  31413. delete symEncryptedSessionKeyPacket.sessionKey; // delete plaintext session key after encryption
  31414. return symEncryptedSessionKeyPacket;
  31415. };
  31416. const results = await Promise.all(passwords.map(pwd => encryptPassword(sessionKey, symAlgo, aeadAlgo, pwd)));
  31417. packetlist.concat(results);
  31418. }
  31419. return new Message(packetlist);
  31420. }
  31421. /**
  31422. * Sign the message (the literal data packet of the message)
  31423. * @param {Array<module:key.Key>} privateKeys private keys with decrypted secret key data for signing
  31424. * @param {Signature} signature (optional) any existing detached signature to add to the message
  31425. * @param {Date} date (optional) override the creation time of the signature
  31426. * @param {Array} userIds (optional) user IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
  31427. * @param {Boolean} streaming (optional) whether to process data as a stream
  31428. * @returns {Promise<Message>} new message with signed content
  31429. * @async
  31430. */
  31431. Message.prototype.sign = async function (privateKeys = [], signature = null, date = new Date(), userIds = [], streaming = false) {
  31432. const packetlist = new _packet2.default.List();
  31433. const literalDataPacket = this.packets.findPacket(_enums2.default.packet.literal);
  31434. if (!literalDataPacket) {
  31435. throw new Error('No literal data packet to sign.');
  31436. }
  31437. let i;
  31438. let existingSigPacketlist;
  31439. // If data packet was created from Uint8Array, use binary, otherwise use text
  31440. const signatureType = literalDataPacket.text === null ? _enums2.default.signature.binary : _enums2.default.signature.text;
  31441. if (signature) {
  31442. existingSigPacketlist = signature.packets.filterByTag(_enums2.default.packet.signature);
  31443. for (i = existingSigPacketlist.length - 1; i >= 0; i--) {
  31444. const signaturePacket = existingSigPacketlist[i];
  31445. const onePassSig = new _packet2.default.OnePassSignature();
  31446. onePassSig.signatureType = signaturePacket.signatureType;
  31447. onePassSig.hashAlgorithm = signaturePacket.hashAlgorithm;
  31448. onePassSig.publicKeyAlgorithm = signaturePacket.publicKeyAlgorithm;
  31449. onePassSig.issuerKeyId = signaturePacket.issuerKeyId;
  31450. if (!privateKeys.length && i === 0) {
  31451. onePassSig.flags = 1;
  31452. }
  31453. packetlist.push(onePassSig);
  31454. }
  31455. }
  31456. await Promise.all(Array.from(privateKeys).reverse().map(async function (privateKey, i) {
  31457. if (privateKey.isPublic()) {
  31458. throw new Error('Need private key for signing');
  31459. }
  31460. const signingKey = await privateKey.getSigningKey(undefined, date, userIds);
  31461. if (!signingKey) {
  31462. throw new Error('Could not find valid key packet for signing in key ' + privateKey.getKeyId().toHex());
  31463. }
  31464. const onePassSig = new _packet2.default.OnePassSignature();
  31465. onePassSig.signatureType = signatureType;
  31466. onePassSig.hashAlgorithm = await (0, _key.getPreferredHashAlgo)(privateKey, signingKey.keyPacket, date, userIds);
  31467. onePassSig.publicKeyAlgorithm = signingKey.keyPacket.algorithm;
  31468. onePassSig.issuerKeyId = signingKey.getKeyId();
  31469. if (i === privateKeys.length - 1) {
  31470. onePassSig.flags = 1;
  31471. }
  31472. return onePassSig;
  31473. })).then(onePassSignatureList => {
  31474. onePassSignatureList.forEach(onePassSig => packetlist.push(onePassSig));
  31475. });
  31476. packetlist.push(literalDataPacket);
  31477. packetlist.concat((await createSignaturePackets(literalDataPacket, privateKeys, signature, date, userIds, false, streaming)));
  31478. return new Message(packetlist);
  31479. };
  31480. /**
  31481. * Compresses the message (the literal and -if signed- signature data packets of the message)
  31482. * @param {module:enums.compression} compression compression algorithm to be used
  31483. * @returns {module:message.Message} new message with compressed content
  31484. */
  31485. Message.prototype.compress = function (compression) {
  31486. if (compression === _enums2.default.compression.uncompressed) {
  31487. return this;
  31488. }
  31489. const compressed = new _packet2.default.Compressed();
  31490. compressed.packets = this.packets;
  31491. compressed.algorithm = _enums2.default.read(_enums2.default.compression, compression);
  31492. const packetList = new _packet2.default.List();
  31493. packetList.push(compressed);
  31494. return new Message(packetList);
  31495. };
  31496. /**
  31497. * Create a detached signature for the message (the literal data packet of the message)
  31498. * @param {Array<module:key.Key>} privateKeys private keys with decrypted secret key data for signing
  31499. * @param {Signature} signature (optional) any existing detached signature
  31500. * @param {Date} date (optional) override the creation time of the signature
  31501. * @param {Array} userIds (optional) user IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
  31502. * @param {Boolean} streaming (optional) whether to process data as a stream
  31503. * @returns {Promise<module:signature.Signature>} new detached signature of message content
  31504. * @async
  31505. */
  31506. Message.prototype.signDetached = async function (privateKeys = [], signature = null, date = new Date(), userIds = [], streaming = false) {
  31507. const literalDataPacket = this.packets.findPacket(_enums2.default.packet.literal);
  31508. if (!literalDataPacket) {
  31509. throw new Error('No literal data packet to sign.');
  31510. }
  31511. return new _signature.Signature((await createSignaturePackets(literalDataPacket, privateKeys, signature, date, userIds, true, streaming)));
  31512. };
  31513. /**
  31514. * Create signature packets for the message
  31515. * @param {module:packet.Literal} literalDataPacket the literal data packet to sign
  31516. * @param {Array<module:key.Key>} privateKeys private keys with decrypted secret key data for signing
  31517. * @param {Signature} signature (optional) any existing detached signature to append
  31518. * @param {Date} date (optional) override the creationtime of the signature
  31519. * @param {Array} userIds (optional) user IDs to sign with, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
  31520. * @param {Boolean} detached (optional) whether to create detached signature packets
  31521. * @param {Boolean} streaming (optional) whether to process data as a stream
  31522. * @returns {Promise<module:packet.List>} list of signature packets
  31523. * @async
  31524. */
  31525. async function createSignaturePackets(literalDataPacket, privateKeys, signature = null, date = new Date(), userIds = [], detached = false, streaming = false) {
  31526. const packetlist = new _packet2.default.List();
  31527. // If data packet was created from Uint8Array, use binary, otherwise use text
  31528. const signatureType = literalDataPacket.text === null ? _enums2.default.signature.binary : _enums2.default.signature.text;
  31529. await Promise.all(privateKeys.map(async (privateKey, i) => {
  31530. const userId = userIds[i];
  31531. if (privateKey.isPublic()) {
  31532. throw new Error('Need private key for signing');
  31533. }
  31534. const signingKey = await privateKey.getSigningKey(undefined, date, userId);
  31535. if (!signingKey) {
  31536. throw new Error(`Could not find valid signing key packet in key ${privateKey.getKeyId().toHex()}`);
  31537. }
  31538. return (0, _key.createSignaturePacket)(literalDataPacket, privateKey, signingKey.keyPacket, { signatureType }, date, userId, detached, streaming);
  31539. })).then(signatureList => {
  31540. signatureList.forEach(signaturePacket => packetlist.push(signaturePacket));
  31541. });
  31542. if (signature) {
  31543. const existingSigPacketlist = signature.packets.filterByTag(_enums2.default.packet.signature);
  31544. packetlist.concat(existingSigPacketlist);
  31545. }
  31546. return packetlist;
  31547. }
  31548. /**
  31549. * Verify message signatures
  31550. * @param {Array<module:key.Key>} keys array of keys to verify signatures
  31551. * @param {Date} date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time
  31552. * @param {Boolean} streaming (optional) whether to process data as a stream
  31553. * @returns {Promise<Array<({keyid: module:type/keyid, valid: Boolean})>>} list of signer's keyid and validity of signature
  31554. * @async
  31555. */
  31556. Message.prototype.verify = async function (keys, date = new Date(), streaming) {
  31557. const msg = this.unwrapCompressed();
  31558. const literalDataList = msg.packets.filterByTag(_enums2.default.packet.literal);
  31559. if (literalDataList.length !== 1) {
  31560. throw new Error('Can only verify message with one literal data packet.');
  31561. }
  31562. if (!streaming) {
  31563. msg.packets.concat((await _webStreamTools2.default.readToEnd(msg.packets.stream, _ => _)));
  31564. }
  31565. const onePassSigList = msg.packets.filterByTag(_enums2.default.packet.onePassSignature).reverse();
  31566. const signatureList = msg.packets.filterByTag(_enums2.default.packet.signature);
  31567. if (streaming && onePassSigList.length && !signatureList.length && msg.packets.stream) {
  31568. await Promise.all(onePassSigList.map(async onePassSig => {
  31569. onePassSig.correspondingSig = new Promise((resolve, reject) => {
  31570. onePassSig.correspondingSigResolve = resolve;
  31571. onePassSig.correspondingSigReject = reject;
  31572. });
  31573. onePassSig.signatureData = _webStreamTools2.default.fromAsync(async () => (await onePassSig.correspondingSig).signatureData);
  31574. onePassSig.hashed = await onePassSig.hash(onePassSig.signatureType, literalDataList[0], undefined, false, streaming);
  31575. }));
  31576. msg.packets.stream = _webStreamTools2.default.transformPair(msg.packets.stream, async (readable, writable) => {
  31577. const reader = _webStreamTools2.default.getReader(readable);
  31578. const writer = _webStreamTools2.default.getWriter(writable);
  31579. try {
  31580. for (let i = 0; i < onePassSigList.length; i++) {
  31581. var _ref = await reader.read();
  31582. const signature = _ref.value;
  31583. onePassSigList[i].correspondingSigResolve(signature);
  31584. }
  31585. await reader.readToEnd();
  31586. await writer.ready;
  31587. await writer.close();
  31588. } catch (e) {
  31589. onePassSigList.forEach(onePassSig => {
  31590. onePassSig.correspondingSigReject(e);
  31591. });
  31592. await writer.abort(e);
  31593. }
  31594. });
  31595. return createVerificationObjects(onePassSigList, literalDataList, keys, date, false, streaming);
  31596. }
  31597. return createVerificationObjects(signatureList, literalDataList, keys, date, false, streaming);
  31598. };
  31599. /**
  31600. * Verify detached message signature
  31601. * @param {Array<module:key.Key>} keys array of keys to verify signatures
  31602. * @param {Signature} signature
  31603. * @param {Date} date Verify the signature against the given date, i.e. check signature creation time < date < expiration time
  31604. * @returns {Promise<Array<({keyid: module:type/keyid, valid: Boolean})>>} list of signer's keyid and validity of signature
  31605. * @async
  31606. */
  31607. Message.prototype.verifyDetached = function (signature, keys, date = new Date()) {
  31608. const msg = this.unwrapCompressed();
  31609. const literalDataList = msg.packets.filterByTag(_enums2.default.packet.literal);
  31610. if (literalDataList.length !== 1) {
  31611. throw new Error('Can only verify message with one literal data packet.');
  31612. }
  31613. const signatureList = signature.packets;
  31614. return createVerificationObjects(signatureList, literalDataList, keys, date, true);
  31615. };
  31616. /**
  31617. * Create object containing signer's keyid and validity of signature
  31618. * @param {module:packet.Signature} signature signature packets
  31619. * @param {Array<module:packet.Literal>} literalDataList array of literal data packets
  31620. * @param {Array<module:key.Key>} keys array of keys to verify signatures
  31621. * @param {Date} date Verify the signature against the given date,
  31622. * i.e. check signature creation time < date < expiration time
  31623. * @param {Boolean} detached (optional) whether to verify detached signature packets
  31624. * @returns {Promise<Array<{keyid: module:type/keyid,
  31625. * valid: Boolean}>>} list of signer's keyid and validity of signature
  31626. * @async
  31627. */
  31628. async function createVerificationObject(signature, literalDataList, keys, date = new Date(), detached = false, streaming = false) {
  31629. let primaryKey = null;
  31630. let signingKey = null;
  31631. await Promise.all(keys.map(async function (key) {
  31632. // Look for the unique key that matches issuerKeyId of signature
  31633. const result = await key.getSigningKey(signature.issuerKeyId, null);
  31634. if (result) {
  31635. primaryKey = key;
  31636. signingKey = result;
  31637. }
  31638. }));
  31639. const signaturePacket = signature.correspondingSig || signature;
  31640. const verifiedSig = {
  31641. keyid: signature.issuerKeyId,
  31642. verified: (async () => {
  31643. if (!signingKey) {
  31644. return null;
  31645. }
  31646. const verified = await signature.verify(signingKey.keyPacket, signature.signatureType, literalDataList[0], detached, streaming);
  31647. const sig = await signaturePacket;
  31648. if (sig.isExpired(date) || !(sig.created >= signingKey.getCreationTime() && sig.created < (await (signingKey === primaryKey ? signingKey.getExpirationTime() : signingKey.getExpirationTime(primaryKey, date))))) {
  31649. return null;
  31650. }
  31651. return verified;
  31652. })(),
  31653. signature: (async () => {
  31654. const sig = await signaturePacket;
  31655. const packetlist = new _packet2.default.List();
  31656. packetlist.push(sig);
  31657. return new _signature.Signature(packetlist);
  31658. })()
  31659. };
  31660. // Mark potential promise rejections as "handled". This is needed because in
  31661. // some cases, we reject them before the user has a reasonable chance to
  31662. // handle them (e.g. `await readToEnd(result.data); await result.verified` and
  31663. // the data stream errors).
  31664. verifiedSig.signature.catch(() => {});
  31665. verifiedSig.verified.catch(() => {});
  31666. return verifiedSig;
  31667. }
  31668. /**
  31669. * Create list of objects containing signer's keyid and validity of signature
  31670. * @param {Array<module:packet.Signature>} signatureList array of signature packets
  31671. * @param {Array<module:packet.Literal>} literalDataList array of literal data packets
  31672. * @param {Array<module:key.Key>} keys array of keys to verify signatures
  31673. * @param {Date} date Verify the signature against the given date,
  31674. * i.e. check signature creation time < date < expiration time
  31675. * @param {Boolean} detached (optional) whether to verify detached signature packets
  31676. * @returns {Promise<Array<{keyid: module:type/keyid,
  31677. * valid: Boolean}>>} list of signer's keyid and validity of signature
  31678. * @async
  31679. */
  31680. async function createVerificationObjects(signatureList, literalDataList, keys, date = new Date(), detached = false, streaming = false) {
  31681. return Promise.all(signatureList.filter(function (signature) {
  31682. return ['text', 'binary'].includes(_enums2.default.read(_enums2.default.signature, signature.signatureType));
  31683. }).map(async function (signature) {
  31684. return createVerificationObject(signature, literalDataList, keys, date, detached, streaming);
  31685. }));
  31686. }
  31687. /**
  31688. * Unwrap compressed message
  31689. * @returns {module:message.Message} message Content of compressed message
  31690. */
  31691. Message.prototype.unwrapCompressed = function () {
  31692. const compressed = this.packets.filterByTag(_enums2.default.packet.compressed);
  31693. if (compressed.length) {
  31694. return new Message(compressed[0].packets);
  31695. }
  31696. return this;
  31697. };
  31698. /**
  31699. * Append signature to unencrypted message object
  31700. * @param {String|Uint8Array} detachedSignature The detached ASCII-armored or Uint8Array PGP signature
  31701. */
  31702. Message.prototype.appendSignature = async function (detachedSignature) {
  31703. await this.packets.read(_util2.default.isUint8Array(detachedSignature) ? detachedSignature : (await _armor2.default.decode(detachedSignature)).data);
  31704. };
  31705. /**
  31706. * Returns ASCII armored text of message
  31707. * @returns {ReadableStream<String>} ASCII armor
  31708. */
  31709. Message.prototype.armor = function () {
  31710. return _armor2.default.encode(_enums2.default.armor.message, this.packets.write());
  31711. };
  31712. /**
  31713. * reads an OpenPGP armored message and returns a message object
  31714. * @param {String | ReadableStream<String>} armoredText text to be parsed
  31715. * @returns {Promise<module:message.Message>} new message object
  31716. * @async
  31717. * @static
  31718. */
  31719. async function readArmored(armoredText) {
  31720. //TODO how do we want to handle bad text? Exception throwing
  31721. //TODO don't accept non-message armored texts
  31722. const streamType = _util2.default.isStream(armoredText);
  31723. if (streamType === 'node') {
  31724. armoredText = _webStreamTools2.default.nodeToWeb(armoredText);
  31725. }
  31726. const input = await _armor2.default.decode(armoredText);
  31727. return read(input.data, streamType);
  31728. }
  31729. /**
  31730. * reads an OpenPGP message as byte array and returns a message object
  31731. * @param {Uint8Array | ReadableStream<Uint8Array>} input binary message
  31732. * @param {Boolean} fromStream whether the message was created from a Stream
  31733. * @returns {Promise<module:message.Message>} new message object
  31734. * @async
  31735. * @static
  31736. */
  31737. async function read(input, fromStream = _util2.default.isStream(input)) {
  31738. const streamType = _util2.default.isStream(input);
  31739. if (streamType === 'node') {
  31740. input = _webStreamTools2.default.nodeToWeb(input);
  31741. }
  31742. const packetlist = new _packet2.default.List();
  31743. await packetlist.read(input, fromStream);
  31744. const message = new Message(packetlist);
  31745. message.fromStream = fromStream;
  31746. return message;
  31747. }
  31748. /**
  31749. * creates new message object from text
  31750. * @param {String | ReadableStream<String>} text
  31751. * @param {String} filename (optional)
  31752. * @param {Date} date (optional)
  31753. * @param {utf8|binary|text|mime} type (optional) data packet type
  31754. * @returns {module:message.Message} new message object
  31755. * @static
  31756. */
  31757. function fromText(text, filename, date = new Date(), type = 'utf8') {
  31758. const streamType = _util2.default.isStream(text);
  31759. if (streamType === 'node') {
  31760. text = _webStreamTools2.default.nodeToWeb(text);
  31761. }
  31762. const literalDataPacket = new _packet2.default.Literal(date);
  31763. // text will be converted to UTF8
  31764. literalDataPacket.setText(text, type);
  31765. if (filename !== undefined) {
  31766. literalDataPacket.setFilename(filename);
  31767. }
  31768. const literalDataPacketlist = new _packet2.default.List();
  31769. literalDataPacketlist.push(literalDataPacket);
  31770. const message = new Message(literalDataPacketlist);
  31771. message.fromStream = streamType;
  31772. return message;
  31773. }
  31774. /**
  31775. * creates new message object from binary data
  31776. * @param {Uint8Array | ReadableStream<Uint8Array>} bytes
  31777. * @param {String} filename (optional)
  31778. * @param {Date} date (optional)
  31779. * @param {utf8|binary|text|mime} type (optional) data packet type
  31780. * @returns {module:message.Message} new message object
  31781. * @static
  31782. */
  31783. function fromBinary(bytes, filename, date = new Date(), type = 'binary') {
  31784. const streamType = _util2.default.isStream(bytes);
  31785. if (!_util2.default.isUint8Array(bytes) && !streamType) {
  31786. throw new Error('Data must be in the form of a Uint8Array or Stream');
  31787. }
  31788. if (streamType === 'node') {
  31789. bytes = _webStreamTools2.default.nodeToWeb(bytes);
  31790. }
  31791. const literalDataPacket = new _packet2.default.Literal(date);
  31792. literalDataPacket.setBytes(bytes, type);
  31793. if (filename !== undefined) {
  31794. literalDataPacket.setFilename(filename);
  31795. }
  31796. const literalDataPacketlist = new _packet2.default.List();
  31797. literalDataPacketlist.push(literalDataPacket);
  31798. const message = new Message(literalDataPacketlist);
  31799. message.fromStream = streamType;
  31800. return message;
  31801. }
  31802. },{"./config":79,"./crypto":94,"./encoding/armor":111,"./enums":113,"./key":118,"./packet":131,"./signature":151,"./type/keyid":154,"./util":158,"web-stream-tools":75}],127:[function(require,module,exports){
  31803. 'use strict';
  31804. Object.defineProperty(exports, "__esModule", {
  31805. value: true
  31806. });
  31807. exports.initWorker = initWorker;
  31808. exports.getWorker = getWorker;
  31809. exports.destroyWorker = destroyWorker;
  31810. exports.generateKey = generateKey;
  31811. exports.reformatKey = reformatKey;
  31812. exports.revokeKey = revokeKey;
  31813. exports.decryptKey = decryptKey;
  31814. exports.encryptKey = encryptKey;
  31815. exports.encrypt = encrypt;
  31816. exports.decrypt = decrypt;
  31817. exports.sign = sign;
  31818. exports.verify = verify;
  31819. exports.encryptSessionKey = encryptSessionKey;
  31820. exports.decryptSessionKeys = decryptSessionKeys;
  31821. var _webStreamTools = require('web-stream-tools');
  31822. var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
  31823. var _message = require('./message');
  31824. var messageLib = _interopRequireWildcard(_message);
  31825. var _cleartext = require('./cleartext');
  31826. var _key = require('./key');
  31827. var _config = require('./config/config');
  31828. var _config2 = _interopRequireDefault(_config);
  31829. var _enums = require('./enums');
  31830. var _enums2 = _interopRequireDefault(_enums);
  31831. require('./polyfills');
  31832. var _util = require('./util');
  31833. var _util2 = _interopRequireDefault(_util);
  31834. var _async_proxy = require('./worker/async_proxy');
  31835. var _async_proxy2 = _interopRequireDefault(_async_proxy);
  31836. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  31837. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  31838. //////////////////////////
  31839. // //
  31840. // Web Worker setup //
  31841. // //
  31842. //////////////////////////
  31843. let asyncProxy; // instance of the asyncproxy
  31844. /**
  31845. * Set the path for the web worker script and create an instance of the async proxy
  31846. * @param {String} path relative path to the worker scripts, default: 'openpgp.worker.js'
  31847. * @param {Number} n number of workers to initialize
  31848. * @param {Array<Object>} workers alternative to path parameter: web workers initialized with 'openpgp.worker.js'
  31849. * @returns {Promise<Boolean>} returns a promise that resolves to true if all workers have succesfully finished loading
  31850. * @async
  31851. */
  31852. // OpenPGP.js - An OpenPGP implementation in javascript
  31853. // Copyright (C) 2016 Tankred Hase
  31854. //
  31855. // This library is free software; you can redistribute it and/or
  31856. // modify it under the terms of the GNU Lesser General Public
  31857. // License as published by the Free Software Foundation; either
  31858. // version 3.0 of the License, or (at your option) any later version.
  31859. //
  31860. // This library is distributed in the hope that it will be useful,
  31861. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  31862. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  31863. // Lesser General Public License for more details.
  31864. //
  31865. // You should have received a copy of the GNU Lesser General Public
  31866. // License along with this library; if not, write to the Free Software
  31867. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  31868. /**
  31869. * @fileoverview The openpgp base module should provide all of the functionality
  31870. * to consume the openpgp.js library. All additional classes are documented
  31871. * for extending and developing on top of the base library.
  31872. * @requires web-stream-tools
  31873. * @requires message
  31874. * @requires cleartext
  31875. * @requires key
  31876. * @requires config
  31877. * @requires enums
  31878. * @requires util
  31879. * @requires polyfills
  31880. * @requires worker/async_proxy
  31881. * @module openpgp
  31882. */
  31883. // This file intentionally has two separate file overviews so that
  31884. // a reference to this module appears at the end of doc/index.html.
  31885. /**
  31886. * @fileoverview To view the full API documentation, start from
  31887. * {@link module:openpgp}
  31888. */
  31889. async function initWorker({ path = 'openpgp.worker.js', n = 1, workers = [] } = {}) {
  31890. if (workers.length || typeof window !== 'undefined' && window.Worker && window.MessageChannel) {
  31891. const proxy = new _async_proxy2.default({ path, n, workers, config: _config2.default });
  31892. const loaded = await proxy.loaded();
  31893. if (loaded) {
  31894. asyncProxy = proxy;
  31895. return true;
  31896. }
  31897. }
  31898. return false;
  31899. }
  31900. /**
  31901. * Returns a reference to the async proxy if the worker was initialized with openpgp.initWorker()
  31902. * @returns {module:worker/async_proxy.AsyncProxy|null} the async proxy or null if not initialized
  31903. */
  31904. function getWorker() {
  31905. return asyncProxy;
  31906. }
  31907. /**
  31908. * Cleanup the current instance of the web worker.
  31909. */
  31910. function destroyWorker() {
  31911. asyncProxy = undefined;
  31912. }
  31913. //////////////////////
  31914. // //
  31915. // Key handling //
  31916. // //
  31917. //////////////////////
  31918. /**
  31919. * Generates a new OpenPGP key pair. Supports RSA and ECC keys. Primary and subkey will be of same type.
  31920. * @param {Array<Object>} userIds array of user IDs e.g. [{ name:'Phil Zimmermann', email:'phil@openpgp.org' }]
  31921. * @param {String} passphrase (optional) The passphrase used to encrypt the resulting private key
  31922. * @param {Number} rsaBits (optional) number of bits for RSA keys: 2048 or 4096.
  31923. * @param {Number} keyExpirationTime (optional) The number of seconds after the key creation time that the key expires
  31924. * @param {String} curve (optional) elliptic curve for ECC keys:
  31925. * curve25519, p256, p384, p521, secp256k1,
  31926. * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1.
  31927. * @param {Date} date (optional) override the creation date of the key and the key signatures
  31928. * @param {Array<Object>} subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}]
  31929. * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt
  31930. * @returns {Promise<Object>} The generated key object in the form:
  31931. * { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String }
  31932. * @async
  31933. * @static
  31934. */
  31935. function generateKey({ userIds = [], passphrase = "", numBits = 2048, rsaBits = numBits, keyExpirationTime = 0, curve = "", date = new Date(), subkeys = [{}] }) {
  31936. userIds = toArray(userIds);
  31937. const options = { userIds, passphrase, rsaBits, keyExpirationTime, curve, date, subkeys };
  31938. if (_util2.default.getWebCryptoAll() && rsaBits < 2048) {
  31939. throw new Error('rsaBits should be 2048 or 4096, found: ' + rsaBits);
  31940. }
  31941. if (!_util2.default.getWebCryptoAll() && asyncProxy) {
  31942. // use web worker if web crypto apis are not supported
  31943. return asyncProxy.delegate('generateKey', options);
  31944. }
  31945. return (0, _key.generate)(options).then(async key => {
  31946. const revocationCertificate = await key.getRevocationCertificate();
  31947. key.revocationSignatures = [];
  31948. return convertStreams({
  31949. key: key,
  31950. privateKeyArmored: key.armor(),
  31951. publicKeyArmored: key.toPublic().armor(),
  31952. revocationCertificate: revocationCertificate
  31953. });
  31954. }).catch(onError.bind(null, 'Error generating keypair'));
  31955. }
  31956. /**
  31957. * Reformats signature packets for a key and rewraps key object.
  31958. * @param {Key} privateKey private key to reformat
  31959. * @param {Array<Object>} userIds array of user IDs e.g. [{ name:'Phil Zimmermann', email:'phil@openpgp.org' }]
  31960. * @param {String} passphrase (optional) The passphrase used to encrypt the resulting private key
  31961. * @param {Number} keyExpirationTime (optional) The number of seconds after the key creation time that the key expires
  31962. * @param {Boolean} revocationCertificate (optional) Whether the returned object should include a revocation certificate to revoke the public key
  31963. * @returns {Promise<Object>} The generated key object in the form:
  31964. * { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String }
  31965. * @async
  31966. * @static
  31967. */
  31968. function reformatKey({ privateKey, userIds = [], passphrase = "", keyExpirationTime = 0, date, revocationCertificate = true }) {
  31969. userIds = toArray(userIds);
  31970. const options = { privateKey, userIds, passphrase, keyExpirationTime, date, revocationCertificate };
  31971. if (asyncProxy) {
  31972. return asyncProxy.delegate('reformatKey', options);
  31973. }
  31974. options.revoked = options.revocationCertificate;
  31975. return (0, _key.reformat)(options).then(async key => {
  31976. const revocationCertificate = await key.getRevocationCertificate();
  31977. key.revocationSignatures = [];
  31978. return convertStreams({
  31979. key: key,
  31980. privateKeyArmored: key.armor(),
  31981. publicKeyArmored: key.toPublic().armor(),
  31982. revocationCertificate: revocationCertificate
  31983. });
  31984. }).catch(onError.bind(null, 'Error reformatting keypair'));
  31985. }
  31986. /**
  31987. * Revokes a key. Requires either a private key or a revocation certificate.
  31988. * If a revocation certificate is passed, the reasonForRevocation parameters will be ignored.
  31989. * @param {Key} key (optional) public or private key to revoke
  31990. * @param {String} revocationCertificate (optional) revocation certificate to revoke the key with
  31991. * @param {Object} reasonForRevocation (optional) object indicating the reason for revocation
  31992. * @param {module:enums.reasonForRevocation} reasonForRevocation.flag (optional) flag indicating the reason for revocation
  31993. * @param {String} reasonForRevocation.string (optional) string explaining the reason for revocation
  31994. * @returns {Promise<Object>} The revoked key object in the form:
  31995. * { privateKey:Key, privateKeyArmored:String, publicKey:Key, publicKeyArmored:String }
  31996. * (if private key is passed) or { publicKey:Key, publicKeyArmored:String } (otherwise)
  31997. * @static
  31998. */
  31999. function revokeKey({
  32000. key, revocationCertificate, reasonForRevocation
  32001. } = {}) {
  32002. const options = {
  32003. key, revocationCertificate, reasonForRevocation
  32004. };
  32005. if (!_util2.default.getWebCryptoAll() && asyncProxy) {
  32006. // use web worker if web crypto apis are not supported
  32007. return asyncProxy.delegate('revokeKey', options);
  32008. }
  32009. return Promise.resolve().then(() => {
  32010. if (revocationCertificate) {
  32011. return key.applyRevocationCertificate(revocationCertificate);
  32012. } else {
  32013. return key.revoke(reasonForRevocation);
  32014. }
  32015. }).then(async key => {
  32016. await convertStreams(key);
  32017. if (key.isPrivate()) {
  32018. const publicKey = key.toPublic();
  32019. return {
  32020. privateKey: key,
  32021. privateKeyArmored: key.armor(),
  32022. publicKey: publicKey,
  32023. publicKeyArmored: publicKey.armor()
  32024. };
  32025. }
  32026. return {
  32027. publicKey: key,
  32028. publicKeyArmored: key.armor()
  32029. };
  32030. }).catch(onError.bind(null, 'Error revoking key'));
  32031. }
  32032. /**
  32033. * Unlock a private key with your passphrase.
  32034. * @param {Key} privateKey the private key that is to be decrypted
  32035. * @param {String|Array<String>} passphrase the user's passphrase(s) chosen during key generation
  32036. * @returns {Promise<Object>} the unlocked key object in the form: { key:Key }
  32037. * @async
  32038. */
  32039. function decryptKey({ privateKey, passphrase }) {
  32040. if (asyncProxy) {
  32041. // use web worker if available
  32042. return asyncProxy.delegate('decryptKey', { privateKey, passphrase });
  32043. }
  32044. return Promise.resolve().then(async function () {
  32045. await privateKey.decrypt(passphrase);
  32046. return {
  32047. key: privateKey
  32048. };
  32049. }).catch(onError.bind(null, 'Error decrypting private key'));
  32050. }
  32051. /**
  32052. * Lock a private key with your passphrase.
  32053. * @param {Key} privateKey the private key that is to be decrypted
  32054. * @param {String|Array<String>} passphrase the user's passphrase(s) chosen during key generation
  32055. * @returns {Promise<Object>} the locked key object in the form: { key:Key }
  32056. * @async
  32057. */
  32058. function encryptKey({ privateKey, passphrase }) {
  32059. if (asyncProxy) {
  32060. // use web worker if available
  32061. return asyncProxy.delegate('encryptKey', { privateKey, passphrase });
  32062. }
  32063. return Promise.resolve().then(async function () {
  32064. await privateKey.encrypt(passphrase);
  32065. return {
  32066. key: privateKey
  32067. };
  32068. }).catch(onError.bind(null, 'Error decrypting private key'));
  32069. }
  32070. ///////////////////////////////////////////
  32071. // //
  32072. // Message encryption and decryption //
  32073. // //
  32074. ///////////////////////////////////////////
  32075. /**
  32076. * Encrypts message text/data with public keys, passwords or both at once. At least either public keys or passwords
  32077. * must be specified. If private keys are specified, those will be used to sign the message.
  32078. * @param {Message} message message to be encrypted as created by openpgp.message.fromText or openpgp.message.fromBinary
  32079. * @param {Key|Array<Key>} publicKeys (optional) array of keys or single key, used to encrypt the message
  32080. * @param {Key|Array<Key>} privateKeys (optional) private keys for signing. If omitted message will not be signed
  32081. * @param {String|Array<String>} passwords (optional) array of passwords or a single password to encrypt the message
  32082. * @param {Object} sessionKey (optional) session key in the form: { data:Uint8Array, algorithm:String }
  32083. * @param {module:enums.compression} compression (optional) which compression algorithm to compress the message with, defaults to what is specified in config
  32084. * @param {Boolean} armor (optional) if the return values should be ascii armored or the message/signature objects
  32085. * @param {'web'|'node'|false} streaming (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any.
  32086. * @param {Boolean} detached (optional) if the signature should be detached (if true, signature will be added to returned object)
  32087. * @param {Signature} signature (optional) a detached signature to add to the encrypted message
  32088. * @param {Boolean} returnSessionKey (optional) if the unencrypted session key should be added to returned object
  32089. * @param {Boolean} wildcard (optional) use a key ID of 0 instead of the public key IDs
  32090. * @param {Date} date (optional) override the creation date of the message signature
  32091. * @param {Array} fromUserIds (optional) array of user IDs to sign with, one per key in `privateKeys`, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
  32092. * @param {Array} toUserIds (optional) array of user IDs to encrypt for, one per key in `publicKeys`, e.g. [{ name:'Robert Receiver', email:'robert@openpgp.org' }]
  32093. * @returns {Promise<Object>} Object containing encrypted (and optionally signed) message in the form:
  32094. *
  32095. * {
  32096. * data: String|ReadableStream<String>|NodeStream, (if `armor` was true, the default)
  32097. * message: Message, (if `armor` was false)
  32098. * signature: String|ReadableStream<String>|NodeStream, (if `detached` was true and `armor` was true)
  32099. * signature: Signature (if `detached` was true and `armor` was false)
  32100. * sessionKey: { data, algorithm, aeadAlgorithm } (if `returnSessionKey` was true)
  32101. * }
  32102. * @async
  32103. * @static
  32104. */
  32105. function encrypt({ message, publicKeys, privateKeys, passwords, sessionKey, compression = _config2.default.compression, armor = true, streaming = message && message.fromStream, detached = false, signature = null, returnSessionKey = false, wildcard = false, date = new Date(), fromUserIds = [], toUserIds = [] }) {
  32106. checkMessage(message);publicKeys = toArray(publicKeys);privateKeys = toArray(privateKeys);passwords = toArray(passwords);fromUserIds = toArray(fromUserIds);toUserIds = toArray(toUserIds);
  32107. if (!nativeAEAD() && asyncProxy) {
  32108. // use web worker if web crypto apis are not supported
  32109. return asyncProxy.delegate('encrypt', { message, publicKeys, privateKeys, passwords, sessionKey, compression, armor, streaming, detached, signature, returnSessionKey, wildcard, date, fromUserIds, toUserIds });
  32110. }
  32111. const result = {};
  32112. return Promise.resolve().then(async function () {
  32113. if (!privateKeys) {
  32114. privateKeys = [];
  32115. }
  32116. if (privateKeys.length || signature) {
  32117. // sign the message only if private keys or signature is specified
  32118. if (detached) {
  32119. const detachedSignature = await message.signDetached(privateKeys, signature, date, fromUserIds, message.fromStream);
  32120. result.signature = armor ? detachedSignature.armor() : detachedSignature;
  32121. } else {
  32122. message = await message.sign(privateKeys, signature, date, fromUserIds, message.fromStream);
  32123. }
  32124. }
  32125. message = message.compress(compression);
  32126. return message.encrypt(publicKeys, passwords, sessionKey, wildcard, date, toUserIds, streaming);
  32127. }).then(async encrypted => {
  32128. if (armor) {
  32129. result.data = encrypted.message.armor();
  32130. } else {
  32131. result.message = encrypted.message;
  32132. }
  32133. if (returnSessionKey) {
  32134. result.sessionKey = encrypted.sessionKey;
  32135. }
  32136. return convertStreams(result, streaming, armor ? ['signature', 'data'] : []);
  32137. }).catch(onError.bind(null, 'Error encrypting message'));
  32138. }
  32139. /**
  32140. * Decrypts a message with the user's private key, a session key or a password. Either a private key,
  32141. * a session key or a password must be specified.
  32142. * @param {Message} message the message object with the encrypted data
  32143. * @param {Key|Array<Key>} privateKeys (optional) private keys with decrypted secret key data or session key
  32144. * @param {String|Array<String>} passwords (optional) passwords to decrypt the message
  32145. * @param {Object|Array<Object>} sessionKeys (optional) session keys in the form: { data:Uint8Array, algorithm:String }
  32146. * @param {Key|Array<Key>} publicKeys (optional) array of public keys or single key, to verify signatures
  32147. * @param {'utf8'|'binary'} format (optional) whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines.
  32148. * @param {'web'|'node'|false} streaming (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any.
  32149. * @param {Signature} signature (optional) detached signature for verification
  32150. * @param {Date} date (optional) use the given date for verification instead of the current time
  32151. * @returns {Promise<Object>} Object containing decrypted and verified message in the form:
  32152. *
  32153. * {
  32154. * data: String|ReadableStream<String>|NodeStream, (if format was 'utf8', the default)
  32155. * data: Uint8Array|ReadableStream<Uint8Array>|NodeStream, (if format was 'binary')
  32156. * filename: String,
  32157. * signatures: [
  32158. * {
  32159. * keyid: module:type/keyid,
  32160. * verified: Promise<Boolean>,
  32161. * valid: Boolean (if streaming was false)
  32162. * }, ...
  32163. * ]
  32164. * }
  32165. * @async
  32166. * @static
  32167. */
  32168. function decrypt({ message, privateKeys, passwords, sessionKeys, publicKeys, format = 'utf8', streaming = message && message.fromStream, signature = null, date = new Date() }) {
  32169. checkMessage(message);publicKeys = toArray(publicKeys);privateKeys = toArray(privateKeys);passwords = toArray(passwords);sessionKeys = toArray(sessionKeys);
  32170. if (!nativeAEAD() && asyncProxy) {
  32171. // use web worker if web crypto apis are not supported
  32172. return asyncProxy.delegate('decrypt', { message, privateKeys, passwords, sessionKeys, publicKeys, format, streaming, signature, date });
  32173. }
  32174. return message.decrypt(privateKeys, passwords, sessionKeys, streaming).then(async function (decrypted) {
  32175. if (!publicKeys) {
  32176. publicKeys = [];
  32177. }
  32178. const result = {};
  32179. result.signatures = signature ? await decrypted.verifyDetached(signature, publicKeys, date, streaming) : await decrypted.verify(publicKeys, date, streaming);
  32180. result.data = format === 'binary' ? decrypted.getLiteralData() : decrypted.getText();
  32181. result.filename = decrypted.getFilename();
  32182. if (streaming) linkStreams(result, message);
  32183. result.data = await convertStream(result.data, streaming);
  32184. if (!streaming) await prepareSignatures(result.signatures);
  32185. return result;
  32186. }).catch(onError.bind(null, 'Error decrypting message'));
  32187. }
  32188. //////////////////////////////////////////
  32189. // //
  32190. // Message signing and verification //
  32191. // //
  32192. //////////////////////////////////////////
  32193. /**
  32194. * Signs a cleartext message.
  32195. * @param {CleartextMessage|Message} message (cleartext) message to be signed
  32196. * @param {Key|Array<Key>} privateKeys array of keys or single key with decrypted secret key data to sign cleartext
  32197. * @param {Boolean} armor (optional) if the return value should be ascii armored or the message object
  32198. * @param {'web'|'node'|false} streaming (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any.
  32199. * @param {Boolean} detached (optional) if the return value should contain a detached signature
  32200. * @param {Date} date (optional) override the creation date of the signature
  32201. * @param {Array} fromUserIds (optional) array of user IDs to sign with, one per key in `privateKeys`, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }]
  32202. * @returns {Promise<Object>} Object containing signed message in the form:
  32203. *
  32204. * {
  32205. * data: String|ReadableStream<String>|NodeStream, (if `armor` was true, the default)
  32206. * message: Message (if `armor` was false)
  32207. * }
  32208. *
  32209. * Or, if `detached` was true:
  32210. *
  32211. * {
  32212. * signature: String|ReadableStream<String>|NodeStream, (if `armor` was true, the default)
  32213. * signature: Signature (if `armor` was false)
  32214. * }
  32215. * @async
  32216. * @static
  32217. */
  32218. function sign({ message, privateKeys, armor = true, streaming = message && message.fromStream, detached = false, date = new Date(), fromUserIds = [] }) {
  32219. checkCleartextOrMessage(message);
  32220. privateKeys = toArray(privateKeys);fromUserIds = toArray(fromUserIds);
  32221. if (asyncProxy) {
  32222. // use web worker if available
  32223. return asyncProxy.delegate('sign', {
  32224. message, privateKeys, armor, streaming, detached, date, fromUserIds
  32225. });
  32226. }
  32227. const result = {};
  32228. return Promise.resolve().then(async function () {
  32229. if (detached) {
  32230. const signature = await message.signDetached(privateKeys, undefined, date, fromUserIds, message.fromStream);
  32231. result.signature = armor ? signature.armor() : signature;
  32232. if (message.packets) {
  32233. result.signature = _webStreamTools2.default.transformPair(message.packets.write(), async (readable, writable) => {
  32234. await Promise.all([_webStreamTools2.default.pipe(result.signature, writable), _webStreamTools2.default.readToEnd(readable).catch(() => {})]);
  32235. });
  32236. }
  32237. } else {
  32238. message = await message.sign(privateKeys, undefined, date, fromUserIds, message.fromStream);
  32239. if (armor) {
  32240. result.data = message.armor();
  32241. } else {
  32242. result.message = message;
  32243. }
  32244. }
  32245. return convertStreams(result, streaming, armor ? ['signature', 'data'] : []);
  32246. }).catch(onError.bind(null, 'Error signing cleartext message'));
  32247. }
  32248. /**
  32249. * Verifies signatures of cleartext signed message
  32250. * @param {Key|Array<Key>} publicKeys array of publicKeys or single key, to verify signatures
  32251. * @param {CleartextMessage|Message} message (cleartext) message object with signatures
  32252. * @param {'web'|'node'|false} streaming (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any.
  32253. * @param {Signature} signature (optional) detached signature for verification
  32254. * @param {Date} date (optional) use the given date for verification instead of the current time
  32255. * @returns {Promise<Object>} Object containing verified message in the form:
  32256. *
  32257. * {
  32258. * data: String|ReadableStream<String>|NodeStream, (if `message` was a CleartextMessage)
  32259. * data: Uint8Array|ReadableStream<Uint8Array>|NodeStream, (if `message` was a Message)
  32260. * signatures: [
  32261. * {
  32262. * keyid: module:type/keyid,
  32263. * verified: Promise<Boolean>,
  32264. * valid: Boolean (if `streaming` was false)
  32265. * }, ...
  32266. * ]
  32267. * }
  32268. * @async
  32269. * @static
  32270. */
  32271. function verify({ message, publicKeys, streaming = message && message.fromStream, signature = null, date = new Date() }) {
  32272. checkCleartextOrMessage(message);
  32273. publicKeys = toArray(publicKeys);
  32274. if (asyncProxy) {
  32275. // use web worker if available
  32276. return asyncProxy.delegate('verify', { message, publicKeys, streaming, signature, date });
  32277. }
  32278. return Promise.resolve().then(async function () {
  32279. const result = {};
  32280. result.signatures = signature ? await message.verifyDetached(signature, publicKeys, date, streaming) : await message.verify(publicKeys, date, streaming);
  32281. result.data = message instanceof _cleartext.CleartextMessage ? message.getText() : message.getLiteralData();
  32282. if (streaming) linkStreams(result, message);
  32283. result.data = await convertStream(result.data, streaming);
  32284. if (!streaming) await prepareSignatures(result.signatures);
  32285. return result;
  32286. }).catch(onError.bind(null, 'Error verifying cleartext signed message'));
  32287. }
  32288. ///////////////////////////////////////////////
  32289. // //
  32290. // Session key encryption and decryption //
  32291. // //
  32292. ///////////////////////////////////////////////
  32293. /**
  32294. * Encrypt a symmetric session key with public keys, passwords, or both at once. At least either public keys
  32295. * or passwords must be specified.
  32296. * @param {Uint8Array} data the session key to be encrypted e.g. 16 random bytes (for aes128)
  32297. * @param {String} algorithm algorithm of the symmetric session key e.g. 'aes128' or 'aes256'
  32298. * @param {String} aeadAlgorithm (optional) aead algorithm, e.g. 'eax' or 'ocb'
  32299. * @param {Key|Array<Key>} publicKeys (optional) array of public keys or single key, used to encrypt the key
  32300. * @param {String|Array<String>} passwords (optional) passwords for the message
  32301. * @param {Boolean} wildcard (optional) use a key ID of 0 instead of the public key IDs
  32302. * @param {Date} date (optional) override the date
  32303. * @param {Array} toUserIds (optional) array of user IDs to encrypt for, one per key in `publicKeys`, e.g. [{ name:'Phil Zimmermann', email:'phil@openpgp.org' }]
  32304. * @returns {Promise<Message>} the encrypted session key packets contained in a message object
  32305. * @async
  32306. * @static
  32307. */
  32308. function encryptSessionKey({ data, algorithm, aeadAlgorithm, publicKeys, passwords, wildcard = false, date = new Date(), toUserIds = [] }) {
  32309. checkBinary(data);checkString(algorithm, 'algorithm');publicKeys = toArray(publicKeys);passwords = toArray(passwords);toUserIds = toArray(toUserIds);
  32310. if (asyncProxy) {
  32311. // use web worker if available
  32312. return asyncProxy.delegate('encryptSessionKey', { data, algorithm, aeadAlgorithm, publicKeys, passwords, wildcard, date, toUserIds });
  32313. }
  32314. return Promise.resolve().then(async function () {
  32315. return { message: await messageLib.encryptSessionKey(data, algorithm, aeadAlgorithm, publicKeys, passwords, wildcard, date, toUserIds) };
  32316. }).catch(onError.bind(null, 'Error encrypting session key'));
  32317. }
  32318. /**
  32319. * Decrypt symmetric session keys with a private key or password. Either a private key or
  32320. * a password must be specified.
  32321. * @param {Message} message a message object containing the encrypted session key packets
  32322. * @param {Key|Array<Key>} privateKeys (optional) private keys with decrypted secret key data
  32323. * @param {String|Array<String>} passwords (optional) passwords to decrypt the session key
  32324. * @returns {Promise<Object|undefined>} Array of decrypted session key, algorithm pairs in form:
  32325. * { data:Uint8Array, algorithm:String }
  32326. * or 'undefined' if no key packets found
  32327. * @async
  32328. * @static
  32329. */
  32330. function decryptSessionKeys({ message, privateKeys, passwords }) {
  32331. checkMessage(message);privateKeys = toArray(privateKeys);passwords = toArray(passwords);
  32332. if (asyncProxy) {
  32333. // use web worker if available
  32334. return asyncProxy.delegate('decryptSessionKeys', { message, privateKeys, passwords });
  32335. }
  32336. return Promise.resolve().then(async function () {
  32337. return message.decryptSessionKeys(privateKeys, passwords);
  32338. }).catch(onError.bind(null, 'Error decrypting session keys'));
  32339. }
  32340. //////////////////////////
  32341. // //
  32342. // Helper functions //
  32343. // //
  32344. //////////////////////////
  32345. /**
  32346. * Input validation
  32347. */
  32348. function checkString(data, name) {
  32349. if (!_util2.default.isString(data)) {
  32350. throw new Error('Parameter [' + (name || 'data') + '] must be of type String');
  32351. }
  32352. }
  32353. function checkBinary(data, name) {
  32354. if (!_util2.default.isUint8Array(data)) {
  32355. throw new Error('Parameter [' + (name || 'data') + '] must be of type Uint8Array');
  32356. }
  32357. }
  32358. function checkMessage(message) {
  32359. if (!(message instanceof messageLib.Message)) {
  32360. throw new Error('Parameter [message] needs to be of type Message');
  32361. }
  32362. }
  32363. function checkCleartextOrMessage(message) {
  32364. if (!(message instanceof _cleartext.CleartextMessage) && !(message instanceof messageLib.Message)) {
  32365. throw new Error('Parameter [message] needs to be of type Message or CleartextMessage');
  32366. }
  32367. }
  32368. /**
  32369. * Normalize parameter to an array if it is not undefined.
  32370. * @param {Object} param the parameter to be normalized
  32371. * @returns {Array<Object>|undefined} the resulting array or undefined
  32372. */
  32373. function toArray(param) {
  32374. if (param && !_util2.default.isArray(param)) {
  32375. param = [param];
  32376. }
  32377. return param;
  32378. }
  32379. /**
  32380. * Convert data to or from Stream
  32381. * @param {Object} data the data to convert
  32382. * @param {'web'|'node'|false} streaming (optional) whether to return a ReadableStream
  32383. * @returns {Object} the data in the respective format
  32384. */
  32385. async function convertStream(data, streaming) {
  32386. if (!streaming && _util2.default.isStream(data)) {
  32387. return _webStreamTools2.default.readToEnd(data);
  32388. }
  32389. if (streaming && !_util2.default.isStream(data)) {
  32390. data = new ReadableStream({
  32391. start(controller) {
  32392. controller.enqueue(data);
  32393. controller.close();
  32394. }
  32395. });
  32396. }
  32397. if (streaming === 'node') {
  32398. data = _webStreamTools2.default.webToNode(data);
  32399. }
  32400. return data;
  32401. }
  32402. /**
  32403. * Convert object properties from Stream
  32404. * @param {Object} obj the data to convert
  32405. * @param {'web'|'node'|false} streaming (optional) whether to return ReadableStreams
  32406. * @param {Array<String>} keys (optional) which keys to return as streams, if possible
  32407. * @returns {Object} the data in the respective format
  32408. */
  32409. async function convertStreams(obj, streaming, keys = []) {
  32410. if (Object.prototype.isPrototypeOf(obj) && !Uint8Array.prototype.isPrototypeOf(obj)) {
  32411. await Promise.all(Object.entries(obj).map(async ([key, value]) => {
  32412. // recursively search all children
  32413. if (_util2.default.isStream(value) || keys.includes(key)) {
  32414. obj[key] = await convertStream(value, streaming);
  32415. } else {
  32416. await convertStreams(obj[key], streaming);
  32417. }
  32418. }));
  32419. }
  32420. return obj;
  32421. }
  32422. /**
  32423. * Link result.data to the message stream for cancellation.
  32424. * @param {Object} result the data to convert
  32425. * @param {Message} message message object
  32426. * @returns {Object}
  32427. */
  32428. function linkStreams(result, message) {
  32429. result.data = _webStreamTools2.default.transformPair(message.packets.stream, async (readable, writable) => {
  32430. await _webStreamTools2.default.pipe(result.data, writable);
  32431. });
  32432. }
  32433. /**
  32434. * Wait until signature objects have been verified
  32435. * @param {Object} signatures list of signatures
  32436. */
  32437. async function prepareSignatures(signatures) {
  32438. await Promise.all(signatures.map(async signature => {
  32439. signature.signature = await signature.signature;
  32440. try {
  32441. signature.valid = await signature.verified;
  32442. } catch (e) {
  32443. signature.valid = null;
  32444. signature.error = e;
  32445. _util2.default.print_debug_error(e);
  32446. }
  32447. }));
  32448. }
  32449. /**
  32450. * Global error handler that logs the stack trace and rethrows a high lvl error message.
  32451. * @param {String} message A human readable high level error Message
  32452. * @param {Error} error The internal error that caused the failure
  32453. */
  32454. function onError(message, error) {
  32455. // log the stack trace
  32456. _util2.default.print_debug_error(error);
  32457. // update error message
  32458. try {
  32459. error.message = message + ': ' + error.message;
  32460. } catch (e) {}
  32461. throw error;
  32462. }
  32463. /**
  32464. * Check for native AEAD support and configuration by the user. Only
  32465. * browsers that implement the current WebCrypto specification support
  32466. * native GCM. Native EAX is built on CTR and CBC, which current
  32467. * browsers support. OCB and CFB are not natively supported.
  32468. * @returns {Boolean} If authenticated encryption should be used
  32469. */
  32470. function nativeAEAD() {
  32471. return _config2.default.aead_protect && (_config2.default.aead_mode === _enums2.default.aead.eax || _config2.default.aead_mode === _enums2.default.aead.experimental_gcm) && _util2.default.getWebCrypto();
  32472. }
  32473. },{"./cleartext":77,"./config/config":78,"./enums":113,"./key":118,"./message":126,"./polyfills":150,"./util":158,"./worker/async_proxy":160,"web-stream-tools":75}],128:[function(require,module,exports){
  32474. 'use strict';
  32475. Object.defineProperty(exports, "__esModule", {
  32476. value: true
  32477. });
  32478. exports.Trust = exports.Signature = exports.SecretSubkey = exports.Userid = exports.SecretKey = exports.OnePassSignature = exports.UserAttribute = exports.PublicSubkey = exports.Marker = exports.SymmetricallyEncrypted = exports.PublicKey = exports.Literal = exports.SymEncryptedSessionKey = exports.PublicKeyEncryptedSessionKey = exports.SymEncryptedAEADProtected = exports.SymEncryptedIntegrityProtected = exports.Compressed = undefined;
  32479. var _compressed = require('./compressed.js');
  32480. Object.defineProperty(exports, 'Compressed', {
  32481. enumerable: true,
  32482. get: function get() {
  32483. return _interopRequireDefault(_compressed).default;
  32484. }
  32485. });
  32486. var _sym_encrypted_integrity_protected = require('./sym_encrypted_integrity_protected.js');
  32487. Object.defineProperty(exports, 'SymEncryptedIntegrityProtected', {
  32488. enumerable: true,
  32489. get: function get() {
  32490. return _interopRequireDefault(_sym_encrypted_integrity_protected).default;
  32491. }
  32492. });
  32493. var _sym_encrypted_aead_protected = require('./sym_encrypted_aead_protected.js');
  32494. Object.defineProperty(exports, 'SymEncryptedAEADProtected', {
  32495. enumerable: true,
  32496. get: function get() {
  32497. return _interopRequireDefault(_sym_encrypted_aead_protected).default;
  32498. }
  32499. });
  32500. var _public_key_encrypted_session_key = require('./public_key_encrypted_session_key.js');
  32501. Object.defineProperty(exports, 'PublicKeyEncryptedSessionKey', {
  32502. enumerable: true,
  32503. get: function get() {
  32504. return _interopRequireDefault(_public_key_encrypted_session_key).default;
  32505. }
  32506. });
  32507. var _sym_encrypted_session_key = require('./sym_encrypted_session_key.js');
  32508. Object.defineProperty(exports, 'SymEncryptedSessionKey', {
  32509. enumerable: true,
  32510. get: function get() {
  32511. return _interopRequireDefault(_sym_encrypted_session_key).default;
  32512. }
  32513. });
  32514. var _literal = require('./literal.js');
  32515. Object.defineProperty(exports, 'Literal', {
  32516. enumerable: true,
  32517. get: function get() {
  32518. return _interopRequireDefault(_literal).default;
  32519. }
  32520. });
  32521. var _public_key = require('./public_key.js');
  32522. Object.defineProperty(exports, 'PublicKey', {
  32523. enumerable: true,
  32524. get: function get() {
  32525. return _interopRequireDefault(_public_key).default;
  32526. }
  32527. });
  32528. var _symmetrically_encrypted = require('./symmetrically_encrypted.js');
  32529. Object.defineProperty(exports, 'SymmetricallyEncrypted', {
  32530. enumerable: true,
  32531. get: function get() {
  32532. return _interopRequireDefault(_symmetrically_encrypted).default;
  32533. }
  32534. });
  32535. var _marker = require('./marker.js');
  32536. Object.defineProperty(exports, 'Marker', {
  32537. enumerable: true,
  32538. get: function get() {
  32539. return _interopRequireDefault(_marker).default;
  32540. }
  32541. });
  32542. var _public_subkey = require('./public_subkey.js');
  32543. Object.defineProperty(exports, 'PublicSubkey', {
  32544. enumerable: true,
  32545. get: function get() {
  32546. return _interopRequireDefault(_public_subkey).default;
  32547. }
  32548. });
  32549. var _user_attribute = require('./user_attribute.js');
  32550. Object.defineProperty(exports, 'UserAttribute', {
  32551. enumerable: true,
  32552. get: function get() {
  32553. return _interopRequireDefault(_user_attribute).default;
  32554. }
  32555. });
  32556. var _one_pass_signature = require('./one_pass_signature.js');
  32557. Object.defineProperty(exports, 'OnePassSignature', {
  32558. enumerable: true,
  32559. get: function get() {
  32560. return _interopRequireDefault(_one_pass_signature).default;
  32561. }
  32562. });
  32563. var _secret_key = require('./secret_key.js');
  32564. Object.defineProperty(exports, 'SecretKey', {
  32565. enumerable: true,
  32566. get: function get() {
  32567. return _interopRequireDefault(_secret_key).default;
  32568. }
  32569. });
  32570. var _userid = require('./userid.js');
  32571. Object.defineProperty(exports, 'Userid', {
  32572. enumerable: true,
  32573. get: function get() {
  32574. return _interopRequireDefault(_userid).default;
  32575. }
  32576. });
  32577. var _secret_subkey = require('./secret_subkey.js');
  32578. Object.defineProperty(exports, 'SecretSubkey', {
  32579. enumerable: true,
  32580. get: function get() {
  32581. return _interopRequireDefault(_secret_subkey).default;
  32582. }
  32583. });
  32584. var _signature = require('./signature.js');
  32585. Object.defineProperty(exports, 'Signature', {
  32586. enumerable: true,
  32587. get: function get() {
  32588. return _interopRequireDefault(_signature).default;
  32589. }
  32590. });
  32591. var _trust = require('./trust.js');
  32592. Object.defineProperty(exports, 'Trust', {
  32593. enumerable: true,
  32594. get: function get() {
  32595. return _interopRequireDefault(_trust).default;
  32596. }
  32597. });
  32598. exports.newPacketFromTag = newPacketFromTag;
  32599. exports.fromStructuredClone = fromStructuredClone;
  32600. var _enums = require('../enums.js');
  32601. var _enums2 = _interopRequireDefault(_enums);
  32602. var _all_packets = require('./all_packets.js');
  32603. var packets = _interopRequireWildcard(_all_packets);
  32604. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  32605. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  32606. /**
  32607. * Allocate a new packet
  32608. * @function newPacketFromTag
  32609. * @memberof module:packet
  32610. * @param {String} tag property name from {@link module:enums.packet}
  32611. * @returns {Object} new packet object with type based on tag
  32612. */
  32613. function newPacketFromTag(tag) {
  32614. return new packets[packetClassFromTagName(tag)]();
  32615. }
  32616. /**
  32617. * Allocate a new packet from structured packet clone
  32618. * @see {@link https://w3c.github.io/html/infrastructure.html#safe-passing-of-structured-data}
  32619. * @function fromStructuredClone
  32620. * @memberof module:packet
  32621. * @param {Object} packetClone packet clone
  32622. * @returns {Object} new packet object with data from packet clone
  32623. */
  32624. function fromStructuredClone(packetClone) {
  32625. const tagName = _enums2.default.read(_enums2.default.packet, packetClone.tag);
  32626. const packet = newPacketFromTag(tagName);
  32627. Object.assign(packet, packetClone);
  32628. if (packet.postCloneTypeFix) {
  32629. packet.postCloneTypeFix();
  32630. }
  32631. return packet;
  32632. }
  32633. /**
  32634. * Convert tag name to class name
  32635. * @param {String} tag property name from {@link module:enums.packet}
  32636. * @returns {String}
  32637. * @private
  32638. */
  32639. function packetClassFromTagName(tag) {
  32640. return tag.substr(0, 1).toUpperCase() + tag.substr(1);
  32641. }
  32642. },{"../enums.js":113,"./all_packets.js":128,"./compressed.js":130,"./literal.js":132,"./marker.js":133,"./one_pass_signature.js":134,"./public_key.js":137,"./public_key_encrypted_session_key.js":138,"./public_subkey.js":139,"./secret_key.js":140,"./secret_subkey.js":141,"./signature.js":142,"./sym_encrypted_aead_protected.js":143,"./sym_encrypted_integrity_protected.js":144,"./sym_encrypted_session_key.js":145,"./symmetrically_encrypted.js":146,"./trust.js":147,"./user_attribute.js":148,"./userid.js":149}],129:[function(require,module,exports){
  32643. 'use strict';
  32644. Object.defineProperty(exports, "__esModule", {
  32645. value: true
  32646. });
  32647. exports.clonePackets = clonePackets;
  32648. exports.parseClonedPackets = parseClonedPackets;
  32649. var _webStreamTools = require('web-stream-tools');
  32650. var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
  32651. var _key = require('../key');
  32652. var _message = require('../message');
  32653. var _cleartext = require('../cleartext');
  32654. var _signature = require('../signature');
  32655. var _packetlist = require('./packetlist');
  32656. var _packetlist2 = _interopRequireDefault(_packetlist);
  32657. var _keyid = require('../type/keyid');
  32658. var _keyid2 = _interopRequireDefault(_keyid);
  32659. var _util = require('../util');
  32660. var _util2 = _interopRequireDefault(_util);
  32661. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  32662. //////////////////////////////
  32663. // //
  32664. // List --> Clone //
  32665. // //
  32666. //////////////////////////////
  32667. /**
  32668. * Create a packetlist from the correspoding object types.
  32669. * @param {Object} options the object passed to and from the web worker
  32670. * @returns {Object} a mutated version of the options optject
  32671. */
  32672. // OpenPGP.js - An OpenPGP implementation in javascript
  32673. // Copyright (C) 2015 Tankred Hase
  32674. //
  32675. // This library is free software; you can redistribute it and/or
  32676. // modify it under the terms of the GNU Lesser General Public
  32677. // License as published by the Free Software Foundation; either
  32678. // version 3.0 of the License, or (at your option) any later version.
  32679. //
  32680. // This library is distributed in the hope that it will be useful,
  32681. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  32682. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  32683. // Lesser General Public License for more details.
  32684. //
  32685. // You should have received a copy of the GNU Lesser General Public
  32686. // License along with this library; if not, write to the Free Software
  32687. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  32688. /**
  32689. * @fileoverview This module implements packet list cloning required to
  32690. * pass certain object types between the web worker and main thread using
  32691. * the structured cloning algorithm.
  32692. * @module packet/clone
  32693. */
  32694. function clonePackets(options) {
  32695. if (options.publicKeys) {
  32696. options.publicKeys = options.publicKeys.map(key => key.toPacketlist());
  32697. }
  32698. if (options.privateKeys) {
  32699. options.privateKeys = options.privateKeys.map(key => key.toPacketlist());
  32700. }
  32701. if (options.publicKey) {
  32702. options.publicKey = options.publicKey.toPacketlist();
  32703. }
  32704. if (options.privateKey) {
  32705. options.privateKey = options.privateKey.toPacketlist();
  32706. }
  32707. if (options.key) {
  32708. options.key = options.key.toPacketlist();
  32709. }
  32710. if (options.message) {
  32711. //could be either a Message or CleartextMessage object
  32712. if (options.message instanceof _message.Message) {
  32713. options.message = options.message.packets;
  32714. } else if (options.message instanceof _cleartext.CleartextMessage) {
  32715. options.message = { text: options.message.text, signature: options.message.signature.packets };
  32716. }
  32717. }
  32718. if (options.signature && options.signature instanceof _signature.Signature) {
  32719. options.signature = options.signature.packets;
  32720. }
  32721. if (options.signatures) {
  32722. options.signatures.forEach(verificationObjectToClone);
  32723. }
  32724. return options;
  32725. }
  32726. function verificationObjectToClone(verObject) {
  32727. const verified = verObject.verified;
  32728. verObject.verified = _webStreamTools2.default.fromAsync(() => verified);
  32729. if (verObject.signature instanceof Promise) {
  32730. const signature = verObject.signature;
  32731. verObject.signature = _webStreamTools2.default.fromAsync(async () => {
  32732. const packets = (await signature).packets;
  32733. try {
  32734. await verified;
  32735. delete packets[0].signature;
  32736. } catch (e) {}
  32737. return packets;
  32738. });
  32739. } else {
  32740. verObject.signature = verObject.signature.packets;
  32741. }
  32742. if (verObject.error) {
  32743. verObject.error = verObject.error.message;
  32744. }
  32745. return verObject;
  32746. }
  32747. //////////////////////////////
  32748. // //
  32749. // Clone --> List //
  32750. // //
  32751. //////////////////////////////
  32752. /**
  32753. * Creates an object with the correct prototype from a corresponding packetlist.
  32754. * @param {Object} options the object passed to and from the web worker
  32755. * @param {String} method the public api function name to be delegated to the worker
  32756. * @returns {Object} a mutated version of the options optject
  32757. */
  32758. function parseClonedPackets(options) {
  32759. if (options.publicKeys) {
  32760. options.publicKeys = options.publicKeys.map(packetlistCloneToKey);
  32761. }
  32762. if (options.privateKeys) {
  32763. options.privateKeys = options.privateKeys.map(packetlistCloneToKey);
  32764. }
  32765. if (options.publicKey) {
  32766. options.publicKey = packetlistCloneToKey(options.publicKey);
  32767. }
  32768. if (options.privateKey) {
  32769. options.privateKey = packetlistCloneToKey(options.privateKey);
  32770. }
  32771. if (options.key) {
  32772. options.key = packetlistCloneToKey(options.key);
  32773. }
  32774. if (options.message && options.message.signature) {
  32775. options.message = packetlistCloneToCleartextMessage(options.message);
  32776. } else if (options.message) {
  32777. options.message = packetlistCloneToMessage(options.message);
  32778. }
  32779. if (options.signatures) {
  32780. options.signatures = options.signatures.map(packetlistCloneToSignatures);
  32781. }
  32782. if (options.signature) {
  32783. options.signature = packetlistCloneToSignature(options.signature);
  32784. }
  32785. return options;
  32786. }
  32787. function packetlistCloneToKey(clone) {
  32788. const packetlist = _packetlist2.default.fromStructuredClone(clone);
  32789. return new _key.Key(packetlist);
  32790. }
  32791. function packetlistCloneToMessage(clone) {
  32792. const packetlist = _packetlist2.default.fromStructuredClone(clone);
  32793. return new _message.Message(packetlist);
  32794. }
  32795. function packetlistCloneToCleartextMessage(clone) {
  32796. const packetlist = _packetlist2.default.fromStructuredClone(clone.signature);
  32797. return new _cleartext.CleartextMessage(clone.text, new _signature.Signature(packetlist));
  32798. }
  32799. //verification objects
  32800. function packetlistCloneToSignatures(clone) {
  32801. clone.keyid = _keyid2.default.fromClone(clone.keyid);
  32802. if (_util2.default.isStream(clone.signature)) {
  32803. clone.signature = _webStreamTools2.default.readToEnd(clone.signature, ([signature]) => new _signature.Signature(_packetlist2.default.fromStructuredClone(signature)));
  32804. clone.signature.catch(() => {});
  32805. } else {
  32806. clone.signature = new _signature.Signature(_packetlist2.default.fromStructuredClone(clone.signature));
  32807. }
  32808. clone.verified = _webStreamTools2.default.readToEnd(clone.verified, ([verified]) => verified);
  32809. clone.verified.catch(() => {});
  32810. if (clone.error) {
  32811. clone.error = new Error(clone.error);
  32812. }
  32813. return clone;
  32814. }
  32815. function packetlistCloneToSignature(clone) {
  32816. if (_util2.default.isString(clone) || _util2.default.isStream(clone)) {
  32817. //signature is armored
  32818. return clone;
  32819. }
  32820. const packetlist = _packetlist2.default.fromStructuredClone(clone);
  32821. return new _signature.Signature(packetlist);
  32822. }
  32823. },{"../cleartext":77,"../key":118,"../message":126,"../signature":151,"../type/keyid":154,"../util":158,"./packetlist":136,"web-stream-tools":75}],130:[function(require,module,exports){
  32824. 'use strict';
  32825. Object.defineProperty(exports, "__esModule", {
  32826. value: true
  32827. });
  32828. var _pako = require('pako');
  32829. var _pako2 = _interopRequireDefault(_pako);
  32830. var _seekBzip = require('seek-bzip');
  32831. var _seekBzip2 = _interopRequireDefault(_seekBzip);
  32832. var _webStreamTools = require('web-stream-tools');
  32833. var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
  32834. var _config = require('../config');
  32835. var _config2 = _interopRequireDefault(_config);
  32836. var _enums = require('../enums');
  32837. var _enums2 = _interopRequireDefault(_enums);
  32838. var _util = require('../util');
  32839. var _util2 = _interopRequireDefault(_util);
  32840. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  32841. /**
  32842. * Implementation of the Compressed Data Packet (Tag 8)
  32843. *
  32844. * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}:
  32845. * The Compressed Data packet contains compressed data. Typically,
  32846. * this packet is found as the contents of an encrypted packet, or following
  32847. * a Signature or One-Pass Signature packet, and contains a literal data packet.
  32848. * @memberof module:packet
  32849. * @constructor
  32850. */
  32851. // GPG4Browsers - An OpenPGP implementation in javascript
  32852. // Copyright (C) 2011 Recurity Labs GmbH
  32853. //
  32854. // This library is free software; you can redistribute it and/or
  32855. // modify it under the terms of the GNU Lesser General Public
  32856. // License as published by the Free Software Foundation; either
  32857. // version 3.0 of the License, or (at your option) any later version.
  32858. //
  32859. // This library is distributed in the hope that it will be useful,
  32860. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  32861. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  32862. // Lesser General Public License for more details.
  32863. //
  32864. // You should have received a copy of the GNU Lesser General Public
  32865. // License along with this library; if not, write to the Free Software
  32866. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  32867. /**
  32868. * @requires web-stream-tools
  32869. * @requires pako
  32870. * @requires config
  32871. * @requires enums
  32872. * @requires util
  32873. * @requires compression/bzip2
  32874. */
  32875. function Compressed() {
  32876. /**
  32877. * Packet type
  32878. * @type {module:enums.packet}
  32879. */
  32880. this.tag = _enums2.default.packet.compressed;
  32881. /**
  32882. * List of packets
  32883. * @type {module:packet.List}
  32884. */
  32885. this.packets = null;
  32886. /**
  32887. * Compression algorithm
  32888. * @type {compression}
  32889. */
  32890. this.algorithm = 'zip';
  32891. /**
  32892. * Compressed packet data
  32893. * @type {Uint8Array | ReadableStream<Uint8Array>}
  32894. */
  32895. this.compressed = null;
  32896. }
  32897. /**
  32898. * Parsing function for the packet.
  32899. * @param {Uint8Array | ReadableStream<Uint8Array>} bytes Payload of a tag 8 packet
  32900. */
  32901. Compressed.prototype.read = async function (bytes, streaming) {
  32902. await _webStreamTools2.default.parse(bytes, async reader => {
  32903. // One octet that gives the algorithm used to compress the packet.
  32904. this.algorithm = _enums2.default.read(_enums2.default.compression, (await reader.readByte()));
  32905. // Compressed data, which makes up the remainder of the packet.
  32906. this.compressed = reader.remainder();
  32907. await this.decompress(streaming);
  32908. });
  32909. };
  32910. /**
  32911. * Return the compressed packet.
  32912. * @returns {Uint8Array | ReadableStream<Uint8Array>} binary compressed packet
  32913. */
  32914. Compressed.prototype.write = function () {
  32915. if (this.compressed === null) {
  32916. this.compress();
  32917. }
  32918. return _util2.default.concat([new Uint8Array([_enums2.default.write(_enums2.default.compression, this.algorithm)]), this.compressed]);
  32919. };
  32920. /**
  32921. * Decompression method for decompressing the compressed data
  32922. * read by read_packet
  32923. */
  32924. Compressed.prototype.decompress = async function (streaming) {
  32925. if (!decompress_fns[this.algorithm]) {
  32926. throw new Error(this.algorithm + ' decompression not supported');
  32927. }
  32928. await this.packets.read(decompress_fns[this.algorithm](this.compressed), streaming);
  32929. };
  32930. /**
  32931. * Compress the packet data (member decompressedData)
  32932. */
  32933. Compressed.prototype.compress = function () {
  32934. if (!compress_fns[this.algorithm]) {
  32935. throw new Error(this.algorithm + ' compression not supported');
  32936. }
  32937. this.compressed = compress_fns[this.algorithm](this.packets.write());
  32938. };
  32939. exports.default = Compressed;
  32940. //////////////////////////
  32941. // //
  32942. // Helper functions //
  32943. // //
  32944. //////////////////////////
  32945. const nodeZlib = _util2.default.getNodeZlib();
  32946. function node_zlib(func, options = {}) {
  32947. return function (data) {
  32948. return _webStreamTools2.default.nodeToWeb(_webStreamTools2.default.webToNode(data).pipe(func(options)));
  32949. };
  32950. }
  32951. function pako_zlib(constructor, options = {}) {
  32952. return function (data) {
  32953. const obj = new constructor(options);
  32954. return _webStreamTools2.default.transform(data, value => {
  32955. if (value.length) {
  32956. obj.push(value, _pako2.default.Z_SYNC_FLUSH);
  32957. return obj.result;
  32958. }
  32959. }, () => {
  32960. if (constructor === _pako2.default.Deflate) {
  32961. obj.push([], _pako2.default.Z_FINISH);
  32962. return obj.result;
  32963. }
  32964. });
  32965. };
  32966. }
  32967. function bzip2(func) {
  32968. return function (data) {
  32969. return _webStreamTools2.default.fromAsync(async () => func((await _webStreamTools2.default.readToEnd(data))));
  32970. };
  32971. }
  32972. let compress_fns;
  32973. let decompress_fns;
  32974. if (nodeZlib) {
  32975. // Use Node native zlib for DEFLATE compression/decompression
  32976. compress_fns = {
  32977. zip: node_zlib(nodeZlib.createDeflateRaw, { level: _config2.default.deflate_level }),
  32978. zlib: node_zlib(nodeZlib.createDeflate, { level: _config2.default.deflate_level })
  32979. };
  32980. decompress_fns = {
  32981. zip: node_zlib(nodeZlib.createInflateRaw),
  32982. zlib: node_zlib(nodeZlib.createInflate),
  32983. bzip2: bzip2(_seekBzip2.default.decode)
  32984. };
  32985. } else {
  32986. // Use JS fallbacks
  32987. compress_fns = {
  32988. zip: pako_zlib(_pako2.default.Deflate, { raw: true, level: _config2.default.deflate_level }),
  32989. zlib: pako_zlib(_pako2.default.Deflate, { level: _config2.default.deflate_level })
  32990. };
  32991. decompress_fns = {
  32992. zip: pako_zlib(_pako2.default.Inflate, { raw: true }),
  32993. zlib: pako_zlib(_pako2.default.Inflate),
  32994. bzip2: bzip2(_seekBzip2.default.decode)
  32995. };
  32996. }
  32997. },{"../config":79,"../enums":113,"../util":158,"pako":50,"seek-bzip":69,"web-stream-tools":75}],131:[function(require,module,exports){
  32998. 'use strict';
  32999. Object.defineProperty(exports, "__esModule", {
  33000. value: true
  33001. });
  33002. var _all_packets = require('./all_packets');
  33003. var packets = _interopRequireWildcard(_all_packets);
  33004. var _clone = require('./clone');
  33005. var clone = _interopRequireWildcard(_clone);
  33006. var _packetlist = require('./packetlist');
  33007. var _packetlist2 = _interopRequireDefault(_packetlist);
  33008. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  33009. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  33010. const mod = {
  33011. List: _packetlist2.default,
  33012. clone
  33013. }; /**
  33014. * @fileoverview OpenPGP packet types
  33015. * @see module:packet/all_packets
  33016. * @see module:packet/clone
  33017. * @see module:packet.List
  33018. * @module packet
  33019. */
  33020. Object.assign(mod, packets);
  33021. exports.default = mod;
  33022. },{"./all_packets":128,"./clone":129,"./packetlist":136}],132:[function(require,module,exports){
  33023. 'use strict';
  33024. Object.defineProperty(exports, "__esModule", {
  33025. value: true
  33026. });
  33027. var _webStreamTools = require('web-stream-tools');
  33028. var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
  33029. var _enums = require('../enums');
  33030. var _enums2 = _interopRequireDefault(_enums);
  33031. var _util = require('../util');
  33032. var _util2 = _interopRequireDefault(_util);
  33033. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  33034. /**
  33035. * Implementation of the Literal Data Packet (Tag 11)
  33036. *
  33037. * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}:
  33038. * A Literal Data packet contains the body of a message; data that is not to be
  33039. * further interpreted.
  33040. * @param {Date} date the creation date of the literal package
  33041. * @memberof module:packet
  33042. * @constructor
  33043. */
  33044. function Literal(date = new Date()) {
  33045. this.tag = _enums2.default.packet.literal;
  33046. this.format = 'utf8'; // default format for literal data packets
  33047. this.date = _util2.default.normalizeDate(date);
  33048. this.text = null; // textual data representation
  33049. this.data = null; // literal data representation
  33050. this.filename = 'msg.txt';
  33051. }
  33052. /**
  33053. * Set the packet data to a javascript native string, end of line
  33054. * will be normalized to \r\n and by default text is converted to UTF8
  33055. * @param {String | ReadableStream<String>} text Any native javascript string
  33056. * @param {utf8|binary|text|mime} format (optional) The format of the string of bytes
  33057. */
  33058. // GPG4Browsers - An OpenPGP implementation in javascript
  33059. // Copyright (C) 2011 Recurity Labs GmbH
  33060. //
  33061. // This library is free software; you can redistribute it and/or
  33062. // modify it under the terms of the GNU Lesser General Public
  33063. // License as published by the Free Software Foundation; either
  33064. // version 3.0 of the License, or (at your option) any later version.
  33065. //
  33066. // This library is distributed in the hope that it will be useful,
  33067. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  33068. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  33069. // Lesser General Public License for more details.
  33070. //
  33071. // You should have received a copy of the GNU Lesser General Public
  33072. // License along with this library; if not, write to the Free Software
  33073. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  33074. /**
  33075. * @requires web-stream-tools
  33076. * @requires enums
  33077. * @requires util
  33078. */
  33079. Literal.prototype.setText = function (text, format = 'utf8') {
  33080. this.format = format;
  33081. this.text = text;
  33082. this.data = null;
  33083. };
  33084. /**
  33085. * Returns literal data packets as native JavaScript string
  33086. * with normalized end of line to \n
  33087. * @param {Boolean} clone (optional) Whether to return a clone so that getBytes/getText can be called again
  33088. * @returns {String | ReadableStream<String>} literal data as text
  33089. */
  33090. Literal.prototype.getText = function (clone = false) {
  33091. if (this.text === null || _util2.default.isStream(this.text)) {
  33092. // Assume that this.text has been read
  33093. this.text = _util2.default.nativeEOL(_util2.default.decode_utf8(this.getBytes(clone)));
  33094. }
  33095. return this.text;
  33096. };
  33097. /**
  33098. * Set the packet data to value represented by the provided string of bytes.
  33099. * @param {Uint8Array | ReadableStream<Uint8Array>} bytes The string of bytes
  33100. * @param {utf8|binary|text|mime} format The format of the string of bytes
  33101. */
  33102. Literal.prototype.setBytes = function (bytes, format) {
  33103. this.format = format;
  33104. this.data = bytes;
  33105. this.text = null;
  33106. };
  33107. /**
  33108. * Get the byte sequence representing the literal packet data
  33109. * @param {Boolean} clone (optional) Whether to return a clone so that getBytes/getText can be called again
  33110. * @returns {Uint8Array | ReadableStream<Uint8Array>} A sequence of bytes
  33111. */
  33112. Literal.prototype.getBytes = function (clone = false) {
  33113. if (this.data === null) {
  33114. // normalize EOL to \r\n and encode UTF8
  33115. this.data = _util2.default.encode_utf8(_util2.default.canonicalizeEOL(this.text));
  33116. }
  33117. if (clone) {
  33118. return _webStreamTools2.default.passiveClone(this.data);
  33119. }
  33120. return this.data;
  33121. };
  33122. /**
  33123. * Sets the filename of the literal packet data
  33124. * @param {String} filename Any native javascript string
  33125. */
  33126. Literal.prototype.setFilename = function (filename) {
  33127. this.filename = filename;
  33128. };
  33129. /**
  33130. * Get the filename of the literal packet data
  33131. * @returns {String} filename
  33132. */
  33133. Literal.prototype.getFilename = function () {
  33134. return this.filename;
  33135. };
  33136. /**
  33137. * Parsing function for a literal data packet (tag 11).
  33138. *
  33139. * @param {Uint8Array | ReadableStream<Uint8Array>} input Payload of a tag 11 packet
  33140. * @returns {module:packet.Literal} object representation
  33141. */
  33142. Literal.prototype.read = async function (bytes) {
  33143. await _webStreamTools2.default.parse(bytes, async reader => {
  33144. // - A one-octet field that describes how the data is formatted.
  33145. const format = _enums2.default.read(_enums2.default.literal, (await reader.readByte()));
  33146. const filename_len = await reader.readByte();
  33147. this.filename = _util2.default.decode_utf8((await reader.readBytes(filename_len)));
  33148. this.date = _util2.default.readDate((await reader.readBytes(4)));
  33149. const data = reader.remainder();
  33150. this.setBytes(data, format);
  33151. });
  33152. };
  33153. /**
  33154. * Creates a Uint8Array representation of the packet, excluding the data
  33155. *
  33156. * @returns {Uint8Array} Uint8Array representation of the packet
  33157. */
  33158. Literal.prototype.writeHeader = function () {
  33159. const filename = _util2.default.encode_utf8(this.filename);
  33160. const filename_length = new Uint8Array([filename.length]);
  33161. const format = new Uint8Array([_enums2.default.write(_enums2.default.literal, this.format)]);
  33162. const date = _util2.default.writeDate(this.date);
  33163. return _util2.default.concatUint8Array([format, filename_length, filename, date]);
  33164. };
  33165. /**
  33166. * Creates a Uint8Array representation of the packet
  33167. *
  33168. * @returns {Uint8Array | ReadableStream<Uint8Array>} Uint8Array representation of the packet
  33169. */
  33170. Literal.prototype.write = function () {
  33171. const header = this.writeHeader();
  33172. const data = this.getBytes();
  33173. return _util2.default.concat([header, data]);
  33174. };
  33175. exports.default = Literal;
  33176. },{"../enums":113,"../util":158,"web-stream-tools":75}],133:[function(require,module,exports){
  33177. 'use strict';
  33178. Object.defineProperty(exports, "__esModule", {
  33179. value: true
  33180. });
  33181. var _enums = require('../enums');
  33182. var _enums2 = _interopRequireDefault(_enums);
  33183. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  33184. /**
  33185. * Implementation of the strange "Marker packet" (Tag 10)
  33186. *
  33187. * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}:
  33188. * An experimental version of PGP used this packet as the Literal
  33189. * packet, but no released version of PGP generated Literal packets with this
  33190. * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as
  33191. * the Marker packet.
  33192. *
  33193. * Such a packet MUST be ignored when received.
  33194. * @memberof module:packet
  33195. * @constructor
  33196. */
  33197. function Marker() {
  33198. this.tag = _enums2.default.packet.marker;
  33199. }
  33200. /**
  33201. * Parsing function for a literal data packet (tag 10).
  33202. *
  33203. * @param {String} input Payload of a tag 10 packet
  33204. * @param {Integer} position
  33205. * Position to start reading from the input string
  33206. * @param {Integer} len
  33207. * Length of the packet or the remaining length of
  33208. * input at position
  33209. * @returns {module:packet.Marker} Object representation
  33210. */
  33211. // GPG4Browsers - An OpenPGP implementation in javascript
  33212. // Copyright (C) 2011 Recurity Labs GmbH
  33213. //
  33214. // This library is free software; you can redistribute it and/or
  33215. // modify it under the terms of the GNU Lesser General Public
  33216. // License as published by the Free Software Foundation; either
  33217. // version 3.0 of the License, or (at your option) any later version.
  33218. //
  33219. // This library is distributed in the hope that it will be useful,
  33220. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  33221. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  33222. // Lesser General Public License for more details.
  33223. //
  33224. // You should have received a copy of the GNU Lesser General Public
  33225. // License along with this library; if not, write to the Free Software
  33226. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  33227. /**
  33228. * @requires enums
  33229. */
  33230. Marker.prototype.read = function (bytes) {
  33231. if (bytes[0] === 0x50 && // P
  33232. bytes[1] === 0x47 && // G
  33233. bytes[2] === 0x50) {
  33234. // P
  33235. return true;
  33236. }
  33237. // marker packet does not contain "PGP"
  33238. return false;
  33239. };
  33240. exports.default = Marker;
  33241. },{"../enums":113}],134:[function(require,module,exports){
  33242. 'use strict';
  33243. Object.defineProperty(exports, "__esModule", {
  33244. value: true
  33245. });
  33246. var _webStreamTools = require('web-stream-tools');
  33247. var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
  33248. var _signature = require('./signature');
  33249. var _signature2 = _interopRequireDefault(_signature);
  33250. var _keyid = require('../type/keyid');
  33251. var _keyid2 = _interopRequireDefault(_keyid);
  33252. var _enums = require('../enums');
  33253. var _enums2 = _interopRequireDefault(_enums);
  33254. var _util = require('../util');
  33255. var _util2 = _interopRequireDefault(_util);
  33256. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  33257. /**
  33258. * Implementation of the One-Pass Signature Packets (Tag 4)
  33259. *
  33260. * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}:
  33261. * The One-Pass Signature packet precedes the signed data and contains
  33262. * enough information to allow the receiver to begin calculating any
  33263. * hashes needed to verify the signature. It allows the Signature
  33264. * packet to be placed at the end of the message, so that the signer
  33265. * can compute the entire signed message in one pass.
  33266. * @memberof module:packet
  33267. * @constructor
  33268. */
  33269. function OnePassSignature() {
  33270. /**
  33271. * Packet type
  33272. * @type {module:enums.packet}
  33273. */
  33274. this.tag = _enums2.default.packet.onePassSignature;
  33275. /** A one-octet version number. The current version is 3. */
  33276. this.version = null;
  33277. /**
  33278. * A one-octet signature type.
  33279. * Signature types are described in
  33280. * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}.
  33281. */
  33282. this.signatureType = null;
  33283. /**
  33284. * A one-octet number describing the hash algorithm used.
  33285. * @see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880 9.4}
  33286. */
  33287. this.hashAlgorithm = null;
  33288. /**
  33289. * A one-octet number describing the public-key algorithm used.
  33290. * @see {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC4880 9.1}
  33291. */
  33292. this.publicKeyAlgorithm = null;
  33293. /** An eight-octet number holding the Key ID of the signing key. */
  33294. this.issuerKeyId = null;
  33295. /**
  33296. * A one-octet number holding a flag showing whether the signature is nested.
  33297. * A zero value indicates that the next packet is another One-Pass Signature packet
  33298. * that describes another signature to be applied to the same message data.
  33299. */
  33300. this.flags = null;
  33301. }
  33302. /**
  33303. * parsing function for a one-pass signature packet (tag 4).
  33304. * @param {Uint8Array} bytes payload of a tag 4 packet
  33305. * @returns {module:packet.OnePassSignature} object representation
  33306. */
  33307. // GPG4Browsers - An OpenPGP implementation in javascript
  33308. // Copyright (C) 2011 Recurity Labs GmbH
  33309. //
  33310. // This library is free software; you can redistribute it and/or
  33311. // modify it under the terms of the GNU Lesser General Public
  33312. // License as published by the Free Software Foundation; either
  33313. // version 3.0 of the License, or (at your option) any later version.
  33314. //
  33315. // This library is distributed in the hope that it will be useful,
  33316. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  33317. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  33318. // Lesser General Public License for more details.
  33319. //
  33320. // You should have received a copy of the GNU Lesser General Public
  33321. // License along with this library; if not, write to the Free Software
  33322. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  33323. /**
  33324. * @requires web-stream-tools
  33325. * @requires packet/signature
  33326. * @requires type/keyid
  33327. * @requires enums
  33328. * @requires util
  33329. */
  33330. OnePassSignature.prototype.read = function (bytes) {
  33331. let mypos = 0;
  33332. // A one-octet version number. The current version is 3.
  33333. this.version = bytes[mypos++];
  33334. // A one-octet signature type. Signature types are described in
  33335. // Section 5.2.1.
  33336. this.signatureType = bytes[mypos++];
  33337. // A one-octet number describing the hash algorithm used.
  33338. this.hashAlgorithm = bytes[mypos++];
  33339. // A one-octet number describing the public-key algorithm used.
  33340. this.publicKeyAlgorithm = bytes[mypos++];
  33341. // An eight-octet number holding the Key ID of the signing key.
  33342. this.issuerKeyId = new _keyid2.default();
  33343. this.issuerKeyId.read(bytes.subarray(mypos, mypos + 8));
  33344. mypos += 8;
  33345. // A one-octet number holding a flag showing whether the signature
  33346. // is nested. A zero value indicates that the next packet is
  33347. // another One-Pass Signature packet that describes another
  33348. // signature to be applied to the same message data.
  33349. this.flags = bytes[mypos++];
  33350. return this;
  33351. };
  33352. /**
  33353. * creates a string representation of a one-pass signature packet
  33354. * @returns {Uint8Array} a Uint8Array representation of a one-pass signature packet
  33355. */
  33356. OnePassSignature.prototype.write = function () {
  33357. const start = new Uint8Array([3, _enums2.default.write(_enums2.default.signature, this.signatureType), _enums2.default.write(_enums2.default.hash, this.hashAlgorithm), _enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm)]);
  33358. const end = new Uint8Array([this.flags]);
  33359. return _util2.default.concatUint8Array([start, this.issuerKeyId.write(), end]);
  33360. };
  33361. /**
  33362. * Fix custom types after cloning
  33363. */
  33364. OnePassSignature.prototype.postCloneTypeFix = function () {
  33365. this.issuerKeyId = _keyid2.default.fromClone(this.issuerKeyId);
  33366. };
  33367. OnePassSignature.prototype.hash = _signature2.default.prototype.hash;
  33368. OnePassSignature.prototype.toHash = _signature2.default.prototype.toHash;
  33369. OnePassSignature.prototype.toSign = _signature2.default.prototype.toSign;
  33370. OnePassSignature.prototype.calculateTrailer = function (...args) {
  33371. return _webStreamTools2.default.fromAsync(async () => _signature2.default.prototype.calculateTrailer.apply((await this.correspondingSig), args));
  33372. };
  33373. OnePassSignature.prototype.verify = async function () {
  33374. const correspondingSig = await this.correspondingSig;
  33375. if (!correspondingSig || correspondingSig.tag !== _enums2.default.packet.signature) {
  33376. throw new Error('Corresponding signature packet missing');
  33377. }
  33378. if (correspondingSig.signatureType !== this.signatureType || correspondingSig.hashAlgorithm !== this.hashAlgorithm || correspondingSig.publicKeyAlgorithm !== this.publicKeyAlgorithm || !correspondingSig.issuerKeyId.equals(this.issuerKeyId)) {
  33379. throw new Error('Corresponding signature packet does not match one-pass signature packet');
  33380. }
  33381. correspondingSig.hashed = this.hashed;
  33382. return correspondingSig.verify.apply(correspondingSig, arguments);
  33383. };
  33384. exports.default = OnePassSignature;
  33385. },{"../enums":113,"../type/keyid":154,"../util":158,"./signature":142,"web-stream-tools":75}],135:[function(require,module,exports){
  33386. 'use strict';
  33387. Object.defineProperty(exports, "__esModule", {
  33388. value: true
  33389. });
  33390. var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); // GPG4Browsers - An OpenPGP implementation in javascript
  33391. // Copyright (C) 2011 Recurity Labs GmbH
  33392. //
  33393. // This library is free software; you can redistribute it and/or
  33394. // modify it under the terms of the GNU Lesser General Public
  33395. // License as published by the Free Software Foundation; either
  33396. // version 3.0 of the License, or (at your option) any later version.
  33397. //
  33398. // This library is distributed in the hope that it will be useful,
  33399. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  33400. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  33401. // Lesser General Public License for more details.
  33402. //
  33403. // You should have received a copy of the GNU Lesser General Public
  33404. // License along with this library; if not, write to the Free Software
  33405. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  33406. /* eslint-disable callback-return */
  33407. /**
  33408. * @fileoverview Functions for reading and writing packets
  33409. * @requires web-stream-tools
  33410. * @requires enums
  33411. * @requires util
  33412. * @module packet/packet
  33413. */
  33414. var _webStreamTools = require('web-stream-tools');
  33415. var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
  33416. var _enums = require('../enums');
  33417. var _enums2 = _interopRequireDefault(_enums);
  33418. var _util = require('../util');
  33419. var _util2 = _interopRequireDefault(_util);
  33420. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  33421. exports.default = {
  33422. readSimpleLength: function readSimpleLength(bytes) {
  33423. let len = 0;
  33424. let offset;
  33425. const type = bytes[0];
  33426. if (type < 192) {
  33427. var _bytes = _slicedToArray(bytes, 1);
  33428. len = _bytes[0];
  33429. offset = 1;
  33430. } else if (type < 255) {
  33431. len = (bytes[0] - 192 << 8) + bytes[1] + 192;
  33432. offset = 2;
  33433. } else if (type === 255) {
  33434. len = _util2.default.readNumber(bytes.subarray(1, 1 + 4));
  33435. offset = 5;
  33436. }
  33437. return {
  33438. len: len,
  33439. offset: offset
  33440. };
  33441. },
  33442. /**
  33443. * Encodes a given integer of length to the openpgp length specifier to a
  33444. * string
  33445. *
  33446. * @param {Integer} length The length to encode
  33447. * @returns {Uint8Array} String with openpgp length representation
  33448. */
  33449. writeSimpleLength: function writeSimpleLength(length) {
  33450. if (length < 192) {
  33451. return new Uint8Array([length]);
  33452. } else if (length > 191 && length < 8384) {
  33453. /*
  33454. * let a = (total data packet length) - 192 let bc = two octet
  33455. * representation of a let d = b + 192
  33456. */
  33457. return new Uint8Array([(length - 192 >> 8) + 192, length - 192 & 0xFF]);
  33458. }
  33459. return _util2.default.concatUint8Array([new Uint8Array([255]), _util2.default.writeNumber(length, 4)]);
  33460. },
  33461. writePartialLength: function writePartialLength(power) {
  33462. if (power < 0 || power > 30) {
  33463. throw new Error('Partial Length power must be between 1 and 30');
  33464. }
  33465. return new Uint8Array([224 + power]);
  33466. },
  33467. writeTag: function writeTag(tag_type) {
  33468. /* we're only generating v4 packet headers here */
  33469. return new Uint8Array([0xC0 | tag_type]);
  33470. },
  33471. /**
  33472. * Writes a packet header version 4 with the given tag_type and length to a
  33473. * string
  33474. *
  33475. * @param {Integer} tag_type Tag type
  33476. * @param {Integer} length Length of the payload
  33477. * @returns {String} String of the header
  33478. */
  33479. writeHeader: function writeHeader(tag_type, length) {
  33480. /* we're only generating v4 packet headers here */
  33481. return _util2.default.concatUint8Array([this.writeTag(tag_type), this.writeSimpleLength(length)]);
  33482. },
  33483. /**
  33484. * Whether the packet type supports partial lengths per RFC4880
  33485. * @param {Integer} tag_type Tag type
  33486. * @returns {Boolean} String of the header
  33487. */
  33488. supportsStreaming: function supportsStreaming(tag_type) {
  33489. return [_enums2.default.packet.literal, _enums2.default.packet.compressed, _enums2.default.packet.symmetricallyEncrypted, _enums2.default.packet.symEncryptedIntegrityProtected, _enums2.default.packet.symEncryptedAEADProtected].includes(tag_type);
  33490. },
  33491. /**
  33492. * Generic static Packet Parser function
  33493. *
  33494. * @param {Uint8Array | ReadableStream<Uint8Array>} input Input stream as string
  33495. * @param {Function} callback Function to call with the parsed packet
  33496. * @returns {Boolean} Returns false if the stream was empty and parsing is done, and true otherwise.
  33497. */
  33498. read: async function read(input, streaming, callback) {
  33499. const reader = _webStreamTools2.default.getReader(input);
  33500. let writer;
  33501. let callbackReturned;
  33502. try {
  33503. const peekedBytes = await reader.peekBytes(2);
  33504. // some sanity checks
  33505. if (!peekedBytes || peekedBytes.length < 2 || (peekedBytes[0] & 0x80) === 0) {
  33506. throw new Error("Error during parsing. This message / key probably does not conform to a valid OpenPGP format.");
  33507. }
  33508. const headerByte = await reader.readByte();
  33509. let tag = -1;
  33510. let format = -1;
  33511. let packet_length;
  33512. format = 0; // 0 = old format; 1 = new format
  33513. if ((headerByte & 0x40) !== 0) {
  33514. format = 1;
  33515. }
  33516. let packet_length_type;
  33517. if (format) {
  33518. // new format header
  33519. tag = headerByte & 0x3F; // bit 5-0
  33520. } else {
  33521. // old format header
  33522. tag = (headerByte & 0x3F) >> 2; // bit 5-2
  33523. packet_length_type = headerByte & 0x03; // bit 1-0
  33524. }
  33525. const supportsStreaming = this.supportsStreaming(tag);
  33526. let packet = null;
  33527. if (streaming && supportsStreaming) {
  33528. const transform = new TransformStream();
  33529. writer = _webStreamTools2.default.getWriter(transform.writable);
  33530. packet = transform.readable;
  33531. callbackReturned = callback({ tag, packet });
  33532. } else {
  33533. packet = [];
  33534. }
  33535. let wasPartialLength;
  33536. do {
  33537. if (!format) {
  33538. // 4.2.1. Old Format Packet Lengths
  33539. switch (packet_length_type) {
  33540. case 0:
  33541. // The packet has a one-octet length. The header is 2 octets
  33542. // long.
  33543. packet_length = await reader.readByte();
  33544. break;
  33545. case 1:
  33546. // The packet has a two-octet length. The header is 3 octets
  33547. // long.
  33548. packet_length = (await reader.readByte()) << 8 | (await reader.readByte());
  33549. break;
  33550. case 2:
  33551. // The packet has a four-octet length. The header is 5
  33552. // octets long.
  33553. packet_length = (await reader.readByte()) << 24 | (await reader.readByte()) << 16 | (await reader.readByte()) << 8 | (await reader.readByte());
  33554. break;
  33555. default:
  33556. // 3 - The packet is of indeterminate length. The header is 1
  33557. // octet long, and the implementation must determine how long
  33558. // the packet is. If the packet is in a file, this means that
  33559. // the packet extends until the end of the file. In general,
  33560. // an implementation SHOULD NOT use indeterminate-length
  33561. // packets except where the end of the data will be clear
  33562. // from the context, and even then it is better to use a
  33563. // definite length, or a new format header. The new format
  33564. // headers described below have a mechanism for precisely
  33565. // encoding data of indeterminate length.
  33566. packet_length = Infinity;
  33567. break;
  33568. }
  33569. } else {
  33570. // 4.2.2. New Format Packet Lengths
  33571. // 4.2.2.1. One-Octet Lengths
  33572. const lengthByte = await reader.readByte();
  33573. wasPartialLength = false;
  33574. if (lengthByte < 192) {
  33575. packet_length = lengthByte;
  33576. // 4.2.2.2. Two-Octet Lengths
  33577. } else if (lengthByte >= 192 && lengthByte < 224) {
  33578. packet_length = (lengthByte - 192 << 8) + (await reader.readByte()) + 192;
  33579. // 4.2.2.4. Partial Body Lengths
  33580. } else if (lengthByte > 223 && lengthByte < 255) {
  33581. packet_length = 1 << (lengthByte & 0x1F);
  33582. wasPartialLength = true;
  33583. if (!supportsStreaming) {
  33584. throw new TypeError('This packet type does not support partial lengths.');
  33585. }
  33586. // 4.2.2.3. Five-Octet Lengths
  33587. } else {
  33588. packet_length = (await reader.readByte()) << 24 | (await reader.readByte()) << 16 | (await reader.readByte()) << 8 | (await reader.readByte());
  33589. }
  33590. }
  33591. if (packet_length > 0) {
  33592. let bytesRead = 0;
  33593. while (true) {
  33594. if (writer) await writer.ready;
  33595. var _ref = await reader.read();
  33596. const done = _ref.done,
  33597. value = _ref.value;
  33598. if (done) {
  33599. if (packet_length === Infinity) break;
  33600. throw new Error('Unexpected end of packet');
  33601. }
  33602. const chunk = packet_length === Infinity ? value : value.subarray(0, packet_length - bytesRead);
  33603. if (writer) await writer.write(chunk);else packet.push(chunk);
  33604. bytesRead += value.length;
  33605. if (bytesRead >= packet_length) {
  33606. reader.unshift(value.subarray(packet_length - bytesRead + value.length));
  33607. break;
  33608. }
  33609. }
  33610. }
  33611. } while (wasPartialLength);
  33612. // If this was not a packet that "supports streaming", we peek to check
  33613. // whether it is the last packet in the message. We peek 2 bytes instead
  33614. // of 1 because the beginning of this function also peeks 2 bytes, and we
  33615. // want to cut a `subarray` of the correct length into `web-stream-tools`'
  33616. // `externalBuffer` as a tiny optimization here.
  33617. //
  33618. // If it *was* a streaming packet (i.e. the data packets), we peek at the
  33619. // entire remainder of the stream, in order to forward errors in the
  33620. // remainder of the stream to the packet data. (Note that this means we
  33621. // read/peek at all signature packets before closing the literal data
  33622. // packet, for example.) This forwards armor checksum errors to the
  33623. // encrypted data stream, for example, so that they don't get lost /
  33624. // forgotten on encryptedMessage.packets.stream, which we never look at.
  33625. //
  33626. // Note that subsequent packet parsing errors could still end up there if
  33627. // `config.tolerant` is set to false, or on malformed messages with
  33628. // multiple data packets, but usually it shouldn't happen.
  33629. //
  33630. // An example of what we do when stream-parsing a message containing
  33631. // [ one-pass signature packet, literal data packet, signature packet ]:
  33632. // 1. Read the one-pass signature packet
  33633. // 2. Peek 2 bytes of the literal data packet
  33634. // 3. Parse the one-pass signature packet
  33635. //
  33636. // 4. Read the literal data packet, simultaneously stream-parsing it
  33637. // 5. Peek until the end of the message
  33638. // 6. Finish parsing the literal data packet
  33639. //
  33640. // 7. Read the signature packet again (we already peeked at it in step 5)
  33641. // 8. Peek at the end of the stream again (`peekBytes` returns undefined)
  33642. // 9. Parse the signature packet
  33643. //
  33644. // Note that this means that if there's an error in the very end of the
  33645. // stream, such as an MDC error, we throw in step 5 instead of in step 8
  33646. // (or never), which is the point of this exercise.
  33647. const nextPacket = await reader.peekBytes(supportsStreaming ? Infinity : 2);
  33648. if (writer) {
  33649. await writer.ready;
  33650. await writer.close();
  33651. } else {
  33652. packet = _util2.default.concatUint8Array(packet);
  33653. await callback({ tag, packet });
  33654. }
  33655. return !nextPacket || !nextPacket.length;
  33656. } catch (e) {
  33657. if (writer) {
  33658. await writer.abort(e);
  33659. return true;
  33660. } else {
  33661. throw e;
  33662. }
  33663. } finally {
  33664. if (writer) {
  33665. await callbackReturned;
  33666. }
  33667. reader.releaseLock();
  33668. }
  33669. }
  33670. };
  33671. },{"../enums":113,"../util":158,"web-stream-tools":75}],136:[function(require,module,exports){
  33672. 'use strict';
  33673. Object.defineProperty(exports, "__esModule", {
  33674. value: true
  33675. });
  33676. var _webStreamTools = require('web-stream-tools');
  33677. var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
  33678. var _all_packets = require('./all_packets');
  33679. var packets = _interopRequireWildcard(_all_packets);
  33680. var _packet = require('./packet');
  33681. var _packet2 = _interopRequireDefault(_packet);
  33682. var _config = require('../config');
  33683. var _config2 = _interopRequireDefault(_config);
  33684. var _enums = require('../enums');
  33685. var _enums2 = _interopRequireDefault(_enums);
  33686. var _util = require('../util');
  33687. var _util2 = _interopRequireDefault(_util);
  33688. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  33689. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  33690. /**
  33691. * This class represents a list of openpgp packets.
  33692. * Take care when iterating over it - the packets themselves
  33693. * are stored as numerical indices.
  33694. * @memberof module:packet
  33695. * @constructor
  33696. * @extends Array
  33697. */
  33698. /* eslint-disable callback-return */
  33699. /**
  33700. * @requires web-stream-tools
  33701. * @requires packet/all_packets
  33702. * @requires packet/packet
  33703. * @requires config
  33704. * @requires enums
  33705. * @requires util
  33706. */
  33707. function List() {
  33708. /**
  33709. * The number of packets contained within the list.
  33710. * @readonly
  33711. * @type {Integer}
  33712. */
  33713. this.length = 0;
  33714. }
  33715. List.prototype = [];
  33716. /**
  33717. * Reads a stream of binary data and interprents it as a list of packets.
  33718. * @param {Uint8Array | ReadableStream<Uint8Array>} A Uint8Array of bytes.
  33719. */
  33720. List.prototype.read = async function (bytes, streaming) {
  33721. this.stream = _webStreamTools2.default.transformPair(bytes, async (readable, writable) => {
  33722. const writer = _webStreamTools2.default.getWriter(writable);
  33723. try {
  33724. while (true) {
  33725. await writer.ready;
  33726. const done = await _packet2.default.read(readable, streaming, async parsed => {
  33727. try {
  33728. const tag = _enums2.default.read(_enums2.default.packet, parsed.tag);
  33729. const packet = packets.newPacketFromTag(tag);
  33730. packet.packets = new List();
  33731. packet.fromStream = _util2.default.isStream(parsed.packet);
  33732. await packet.read(parsed.packet, streaming);
  33733. await writer.write(packet);
  33734. } catch (e) {
  33735. if (!_config2.default.tolerant || _packet2.default.supportsStreaming(parsed.tag)) {
  33736. // The packets that support streaming are the ones that contain
  33737. // message data. Those are also the ones we want to be more strict
  33738. // about and throw on parse errors for.
  33739. await writer.abort(e);
  33740. }
  33741. _util2.default.print_debug_error(e);
  33742. }
  33743. });
  33744. if (done) {
  33745. await writer.ready;
  33746. await writer.close();
  33747. return;
  33748. }
  33749. }
  33750. } catch (e) {
  33751. await writer.abort(e);
  33752. }
  33753. });
  33754. // Wait until first few packets have been read
  33755. const reader = _webStreamTools2.default.getReader(this.stream);
  33756. while (true) {
  33757. var _ref = await reader.read();
  33758. const done = _ref.done,
  33759. value = _ref.value;
  33760. if (!done) {
  33761. this.push(value);
  33762. } else {
  33763. this.stream = null;
  33764. }
  33765. if (done || _packet2.default.supportsStreaming(value.tag)) {
  33766. break;
  33767. }
  33768. }
  33769. reader.releaseLock();
  33770. };
  33771. /**
  33772. * Creates a binary representation of openpgp objects contained within the
  33773. * class instance.
  33774. * @returns {Uint8Array} A Uint8Array containing valid openpgp packets.
  33775. */
  33776. List.prototype.write = function () {
  33777. const arr = [];
  33778. for (let i = 0; i < this.length; i++) {
  33779. const packetbytes = this[i].write();
  33780. if (_util2.default.isStream(packetbytes) && _packet2.default.supportsStreaming(this[i].tag)) {
  33781. let buffer = [];
  33782. let bufferLength = 0;
  33783. const minLength = 512;
  33784. arr.push(_packet2.default.writeTag(this[i].tag));
  33785. arr.push(_webStreamTools2.default.transform(packetbytes, value => {
  33786. buffer.push(value);
  33787. bufferLength += value.length;
  33788. if (bufferLength >= minLength) {
  33789. const powerOf2 = Math.min(Math.log(bufferLength) / Math.LN2 | 0, 30);
  33790. const chunkSize = 2 ** powerOf2;
  33791. const bufferConcat = _util2.default.concat([_packet2.default.writePartialLength(powerOf2)].concat(buffer));
  33792. buffer = [bufferConcat.subarray(1 + chunkSize)];
  33793. bufferLength = buffer[0].length;
  33794. return bufferConcat.subarray(0, 1 + chunkSize);
  33795. }
  33796. }, () => _util2.default.concat([_packet2.default.writeSimpleLength(bufferLength)].concat(buffer))));
  33797. } else {
  33798. if (_util2.default.isStream(packetbytes)) {
  33799. let length = 0;
  33800. arr.push(_webStreamTools2.default.transform(_webStreamTools2.default.clone(packetbytes), value => {
  33801. length += value.length;
  33802. }, () => _packet2.default.writeHeader(this[i].tag, length)));
  33803. } else {
  33804. arr.push(_packet2.default.writeHeader(this[i].tag, packetbytes.length));
  33805. }
  33806. arr.push(packetbytes);
  33807. }
  33808. }
  33809. return _util2.default.concat(arr);
  33810. };
  33811. /**
  33812. * Adds a packet to the list. This is the only supported method of doing so;
  33813. * writing to packetlist[i] directly will result in an error.
  33814. * @param {Object} packet Packet to push
  33815. */
  33816. List.prototype.push = function (packet) {
  33817. if (!packet) {
  33818. return;
  33819. }
  33820. packet.packets = packet.packets || new List();
  33821. this[this.length] = packet;
  33822. this.length++;
  33823. };
  33824. /**
  33825. * Creates a new PacketList with all packets from the given types
  33826. */
  33827. List.prototype.filterByTag = function (...args) {
  33828. const filtered = new List();
  33829. const handle = tag => packetType => tag === packetType;
  33830. for (let i = 0; i < this.length; i++) {
  33831. if (args.some(handle(this[i].tag))) {
  33832. filtered.push(this[i]);
  33833. }
  33834. }
  33835. return filtered;
  33836. };
  33837. /**
  33838. * Traverses packet tree and returns first matching packet
  33839. * @param {module:enums.packet} type The packet type
  33840. * @returns {module:packet/packet|undefined}
  33841. */
  33842. List.prototype.findPacket = function (type) {
  33843. return this.find(packet => packet.tag === type);
  33844. };
  33845. /**
  33846. * Returns array of found indices by tag
  33847. */
  33848. List.prototype.indexOfTag = function (...args) {
  33849. const tagIndex = [];
  33850. const that = this;
  33851. const handle = tag => packetType => tag === packetType;
  33852. for (let i = 0; i < this.length; i++) {
  33853. if (args.some(handle(that[i].tag))) {
  33854. tagIndex.push(i);
  33855. }
  33856. }
  33857. return tagIndex;
  33858. };
  33859. /**
  33860. * Concatenates packetlist or array of packets
  33861. */
  33862. List.prototype.concat = function (packetlist) {
  33863. if (packetlist) {
  33864. for (let i = 0; i < packetlist.length; i++) {
  33865. this.push(packetlist[i]);
  33866. }
  33867. }
  33868. return this;
  33869. };
  33870. /**
  33871. * Allocate a new packetlist from structured packetlist clone
  33872. * See {@link https://w3c.github.io/html/infrastructure.html#safe-passing-of-structured-data}
  33873. * @param {Object} packetClone packetlist clone
  33874. * @returns {Object} new packetlist object with data from packetlist clone
  33875. */
  33876. List.fromStructuredClone = function (packetlistClone) {
  33877. const packetlist = new List();
  33878. for (let i = 0; i < packetlistClone.length; i++) {
  33879. const packet = packets.fromStructuredClone(packetlistClone[i]);
  33880. packetlist.push(packet);
  33881. if (packet.embeddedSignature) {
  33882. packet.embeddedSignature = packets.fromStructuredClone(packet.embeddedSignature);
  33883. }
  33884. if (packet.packets.length !== 0) {
  33885. packet.packets = this.fromStructuredClone(packet.packets);
  33886. } else {
  33887. packet.packets = new List();
  33888. }
  33889. }
  33890. if (packetlistClone.stream) {
  33891. packetlist.stream = _webStreamTools2.default.transform(packetlistClone.stream, packet => packets.fromStructuredClone(packet));
  33892. }
  33893. return packetlist;
  33894. };
  33895. exports.default = List;
  33896. },{"../config":79,"../enums":113,"../util":158,"./all_packets":128,"./packet":135,"web-stream-tools":75}],137:[function(require,module,exports){
  33897. 'use strict';
  33898. Object.defineProperty(exports, "__esModule", {
  33899. value: true
  33900. });
  33901. var _sha = require('asmcrypto.js/dist_es5/hash/sha1/sha1');
  33902. var _sha2 = require('asmcrypto.js/dist_es5/hash/sha256/sha256');
  33903. var _keyid = require('../type/keyid');
  33904. var _keyid2 = _interopRequireDefault(_keyid);
  33905. var _mpi = require('../type/mpi');
  33906. var _mpi2 = _interopRequireDefault(_mpi);
  33907. var _config = require('../config');
  33908. var _config2 = _interopRequireDefault(_config);
  33909. var _crypto = require('../crypto');
  33910. var _crypto2 = _interopRequireDefault(_crypto);
  33911. var _enums = require('../enums');
  33912. var _enums2 = _interopRequireDefault(_enums);
  33913. var _util = require('../util');
  33914. var _util2 = _interopRequireDefault(_util);
  33915. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  33916. /**
  33917. * Implementation of the Key Material Packet (Tag 5,6,7,14)
  33918. *
  33919. * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}:
  33920. * A key material packet contains all the information about a public or
  33921. * private key. There are four variants of this packet type, and two
  33922. * major versions.
  33923. *
  33924. * A Public-Key packet starts a series of packets that forms an OpenPGP
  33925. * key (sometimes called an OpenPGP certificate).
  33926. * @memberof module:packet
  33927. * @constructor
  33928. */
  33929. // GPG4Browsers - An OpenPGP implementation in javascript
  33930. // Copyright (C) 2011 Recurity Labs GmbH
  33931. //
  33932. // This library is free software; you can redistribute it and/or
  33933. // modify it under the terms of the GNU Lesser General Public
  33934. // License as published by the Free Software Foundation; either
  33935. // version 3.0 of the License, or (at your option) any later version.
  33936. //
  33937. // This library is distributed in the hope that it will be useful,
  33938. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  33939. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  33940. // Lesser General Public License for more details.
  33941. //
  33942. // You should have received a copy of the GNU Lesser General Public
  33943. // License along with this library; if not, write to the Free Software
  33944. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  33945. /**
  33946. * @requires type/keyid
  33947. * @requires type/mpi
  33948. * @requires config
  33949. * @requires crypto
  33950. * @requires enums
  33951. * @requires util
  33952. */
  33953. function PublicKey(date = new Date()) {
  33954. /**
  33955. * Packet type
  33956. * @type {module:enums.packet}
  33957. */
  33958. this.tag = _enums2.default.packet.publicKey;
  33959. /**
  33960. * Packet version
  33961. * @type {Integer}
  33962. */
  33963. this.version = _config2.default.v5_keys ? 5 : 4;
  33964. /**
  33965. * Key creation date.
  33966. * @type {Date}
  33967. */
  33968. this.created = _util2.default.normalizeDate(date);
  33969. /**
  33970. * Public key algorithm.
  33971. * @type {String}
  33972. */
  33973. this.algorithm = null;
  33974. /**
  33975. * Algorithm specific params
  33976. * @type {Array<Object>}
  33977. */
  33978. this.params = [];
  33979. /**
  33980. * Time until expiration in days (V3 only)
  33981. * @type {Integer}
  33982. */
  33983. this.expirationTimeV3 = 0;
  33984. /**
  33985. * Fingerprint in lowercase hex
  33986. * @type {String}
  33987. */
  33988. this.fingerprint = null;
  33989. /**
  33990. * Keyid
  33991. * @type {module:type/keyid}
  33992. */
  33993. this.keyid = null;
  33994. }
  33995. /**
  33996. * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats}
  33997. * called by read_tag&lt;num&gt;
  33998. * @param {Uint8Array} bytes Input array to read the packet from
  33999. * @returns {Object} This object with attributes set by the parser
  34000. */
  34001. PublicKey.prototype.read = function (bytes) {
  34002. let pos = 0;
  34003. // A one-octet version number (3, 4 or 5).
  34004. this.version = bytes[pos++];
  34005. if (this.version === 4 || this.version === 5) {
  34006. // - A four-octet number denoting the time that the key was created.
  34007. this.created = _util2.default.readDate(bytes.subarray(pos, pos + 4));
  34008. pos += 4;
  34009. // - A one-octet number denoting the public-key algorithm of this key.
  34010. this.algorithm = _enums2.default.read(_enums2.default.publicKey, bytes[pos++]);
  34011. const algo = _enums2.default.write(_enums2.default.publicKey, this.algorithm);
  34012. if (this.version === 5) {
  34013. // - A four-octet scalar octet count for the following key material.
  34014. pos += 4;
  34015. }
  34016. // - A series of values comprising the key material. This is
  34017. // algorithm-specific and described in section XXXX.
  34018. const types = _crypto2.default.getPubKeyParamTypes(algo);
  34019. this.params = _crypto2.default.constructParams(types);
  34020. for (let i = 0; i < types.length && pos < bytes.length; i++) {
  34021. pos += this.params[i].read(bytes.subarray(pos, bytes.length));
  34022. if (pos > bytes.length) {
  34023. throw new Error('Error reading MPI @:' + pos);
  34024. }
  34025. }
  34026. return pos;
  34027. }
  34028. throw new Error('Version ' + this.version + ' of the key packet is unsupported.');
  34029. };
  34030. /**
  34031. * Alias of read()
  34032. * @see module:packet.PublicKey#read
  34033. */
  34034. PublicKey.prototype.readPublicKey = PublicKey.prototype.read;
  34035. /**
  34036. * Same as write_private_key, but has less information because of
  34037. * public key.
  34038. * @returns {Uint8Array} OpenPGP packet body contents,
  34039. */
  34040. PublicKey.prototype.write = function () {
  34041. const arr = [];
  34042. // Version
  34043. arr.push(new Uint8Array([this.version]));
  34044. arr.push(_util2.default.writeDate(this.created));
  34045. // A one-octet number denoting the public-key algorithm of this key
  34046. const algo = _enums2.default.write(_enums2.default.publicKey, this.algorithm);
  34047. arr.push(new Uint8Array([algo]));
  34048. const paramCount = _crypto2.default.getPubKeyParamTypes(algo).length;
  34049. const params = _util2.default.concatUint8Array(this.params.slice(0, paramCount).map(param => param.write()));
  34050. if (this.version === 5) {
  34051. // A four-octet scalar octet count for the following key material
  34052. arr.push(_util2.default.writeNumber(params.length, 4));
  34053. }
  34054. // Algorithm-specific params
  34055. arr.push(params);
  34056. return _util2.default.concatUint8Array(arr);
  34057. };
  34058. /**
  34059. * Alias of write()
  34060. * @see module:packet.PublicKey#write
  34061. */
  34062. PublicKey.prototype.writePublicKey = PublicKey.prototype.write;
  34063. /**
  34064. * Write packet in order to be hashed; either for a signature or a fingerprint.
  34065. */
  34066. PublicKey.prototype.writeForHash = function (version) {
  34067. const bytes = this.writePublicKey();
  34068. if (version === 5) {
  34069. return _util2.default.concatUint8Array([new Uint8Array([0x9A]), _util2.default.writeNumber(bytes.length, 4), bytes]);
  34070. }
  34071. return _util2.default.concatUint8Array([new Uint8Array([0x99]), _util2.default.writeNumber(bytes.length, 2), bytes]);
  34072. };
  34073. /**
  34074. * Check whether secret-key data is available in decrypted form. Returns null for public keys.
  34075. * @returns {Boolean|null}
  34076. */
  34077. PublicKey.prototype.isDecrypted = function () {
  34078. return null;
  34079. };
  34080. /**
  34081. * Returns the creation time of the key
  34082. * @returns {Date}
  34083. */
  34084. PublicKey.prototype.getCreationTime = function () {
  34085. return this.created;
  34086. };
  34087. /**
  34088. * Calculates the key id of the key
  34089. * @returns {String} A 8 byte key id
  34090. */
  34091. PublicKey.prototype.getKeyId = function () {
  34092. if (this.keyid) {
  34093. return this.keyid;
  34094. }
  34095. this.keyid = new _keyid2.default();
  34096. if (this.version === 5) {
  34097. this.keyid.read(_util2.default.hex_to_Uint8Array(this.getFingerprint()).subarray(0, 8));
  34098. } else if (this.version === 4) {
  34099. this.keyid.read(_util2.default.hex_to_Uint8Array(this.getFingerprint()).subarray(12, 20));
  34100. }
  34101. return this.keyid;
  34102. };
  34103. /**
  34104. * Calculates the fingerprint of the key
  34105. * @returns {Uint8Array} A Uint8Array containing the fingerprint
  34106. */
  34107. PublicKey.prototype.getFingerprintBytes = function () {
  34108. if (this.fingerprint) {
  34109. return this.fingerprint;
  34110. }
  34111. const toHash = this.writeForHash(this.version);
  34112. if (this.version === 5) {
  34113. this.fingerprint = _sha2.Sha256.bytes(toHash);
  34114. } else if (this.version === 4) {
  34115. this.fingerprint = _sha.Sha1.bytes(toHash);
  34116. }
  34117. return this.fingerprint;
  34118. };
  34119. /**
  34120. * Calculates the fingerprint of the key
  34121. * @returns {String} A string containing the fingerprint in lowercase hex
  34122. */
  34123. PublicKey.prototype.getFingerprint = function () {
  34124. return _util2.default.Uint8Array_to_hex(this.getFingerprintBytes());
  34125. };
  34126. /**
  34127. * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint
  34128. * @returns {Boolean} Whether the two keys have the same version and public key data
  34129. */
  34130. PublicKey.prototype.hasSameFingerprintAs = function (other) {
  34131. return this.version === other.version && _util2.default.equalsUint8Array(this.writePublicKey(), other.writePublicKey());
  34132. };
  34133. /**
  34134. * Returns algorithm information
  34135. * @returns {Object} An object of the form {algorithm: String, rsaBits:int, curve:String}
  34136. */
  34137. PublicKey.prototype.getAlgorithmInfo = function () {
  34138. const result = {};
  34139. result.algorithm = this.algorithm;
  34140. if (this.params[0] instanceof _mpi2.default) {
  34141. result.rsaBits = this.params[0].byteLength() * 8;
  34142. result.bits = result.rsaBits; // Deprecated.
  34143. } else {
  34144. result.curve = this.params[0].getName();
  34145. }
  34146. return result;
  34147. };
  34148. /**
  34149. * Fix custom types after cloning
  34150. */
  34151. PublicKey.prototype.postCloneTypeFix = function () {
  34152. const algo = _enums2.default.write(_enums2.default.publicKey, this.algorithm);
  34153. const types = _crypto2.default.getPubKeyParamTypes(algo);
  34154. for (let i = 0; i < types.length; i++) {
  34155. const param = this.params[i];
  34156. this.params[i] = types[i].fromClone(param);
  34157. }
  34158. if (this.keyid) {
  34159. this.keyid = _keyid2.default.fromClone(this.keyid);
  34160. }
  34161. };
  34162. exports.default = PublicKey;
  34163. },{"../config":79,"../crypto":94,"../enums":113,"../type/keyid":154,"../type/mpi":155,"../util":158,"asmcrypto.js/dist_es5/hash/sha1/sha1":11,"asmcrypto.js/dist_es5/hash/sha256/sha256":13}],138:[function(require,module,exports){
  34164. 'use strict';
  34165. Object.defineProperty(exports, "__esModule", {
  34166. value: true
  34167. });
  34168. var _keyid = require('../type/keyid');
  34169. var _keyid2 = _interopRequireDefault(_keyid);
  34170. var _crypto = require('../crypto');
  34171. var _crypto2 = _interopRequireDefault(_crypto);
  34172. var _enums = require('../enums');
  34173. var _enums2 = _interopRequireDefault(_enums);
  34174. var _util = require('../util');
  34175. var _util2 = _interopRequireDefault(_util);
  34176. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  34177. /**
  34178. * Public-Key Encrypted Session Key Packets (Tag 1)
  34179. *
  34180. * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}:
  34181. * A Public-Key Encrypted Session Key packet holds the session key
  34182. * used to encrypt a message. Zero or more Public-Key Encrypted Session Key
  34183. * packets and/or Symmetric-Key Encrypted Session Key packets may precede a
  34184. * Symmetrically Encrypted Data Packet, which holds an encrypted message. The
  34185. * message is encrypted with the session key, and the session key is itself
  34186. * encrypted and stored in the Encrypted Session Key packet(s). The
  34187. * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted
  34188. * Session Key packet for each OpenPGP key to which the message is encrypted.
  34189. * The recipient of the message finds a session key that is encrypted to their
  34190. * public key, decrypts the session key, and then uses the session key to
  34191. * decrypt the message.
  34192. * @memberof module:packet
  34193. * @constructor
  34194. */
  34195. // GPG4Browsers - An OpenPGP implementation in javascript
  34196. // Copyright (C) 2011 Recurity Labs GmbH
  34197. //
  34198. // This library is free software; you can redistribute it and/or
  34199. // modify it under the terms of the GNU Lesser General Public
  34200. // License as published by the Free Software Foundation; either
  34201. // version 3.0 of the License, or (at your option) any later version.
  34202. //
  34203. // This library is distributed in the hope that it will be useful,
  34204. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  34205. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  34206. // Lesser General Public License for more details.
  34207. //
  34208. // You should have received a copy of the GNU Lesser General Public
  34209. // License along with this library; if not, write to the Free Software
  34210. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  34211. /**
  34212. * @requires type/keyid
  34213. * @requires type/mpi
  34214. * @requires crypto
  34215. * @requires enums
  34216. * @requires util
  34217. */
  34218. function PublicKeyEncryptedSessionKey() {
  34219. this.tag = _enums2.default.packet.publicKeyEncryptedSessionKey;
  34220. this.version = 3;
  34221. this.publicKeyId = new _keyid2.default();
  34222. this.publicKeyAlgorithm = null;
  34223. this.sessionKey = null;
  34224. this.sessionKeyAlgorithm = null;
  34225. /** @type {Array<module:type/mpi>} */
  34226. this.encrypted = [];
  34227. }
  34228. /**
  34229. * Parsing function for a publickey encrypted session key packet (tag 1).
  34230. *
  34231. * @param {Uint8Array} input Payload of a tag 1 packet
  34232. * @param {Integer} position Position to start reading from the input string
  34233. * @param {Integer} len Length of the packet or the remaining length of
  34234. * input at position
  34235. * @returns {module:packet.PublicKeyEncryptedSessionKey} Object representation
  34236. */
  34237. PublicKeyEncryptedSessionKey.prototype.read = function (bytes) {
  34238. this.version = bytes[0];
  34239. this.publicKeyId.read(bytes.subarray(1, bytes.length));
  34240. this.publicKeyAlgorithm = _enums2.default.read(_enums2.default.publicKey, bytes[9]);
  34241. let i = 10;
  34242. const algo = _enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm);
  34243. const types = _crypto2.default.getEncSessionKeyParamTypes(algo);
  34244. this.encrypted = _crypto2.default.constructParams(types);
  34245. for (let j = 0; j < types.length; j++) {
  34246. i += this.encrypted[j].read(bytes.subarray(i, bytes.length));
  34247. }
  34248. };
  34249. /**
  34250. * Create a string representation of a tag 1 packet
  34251. *
  34252. * @returns {Uint8Array} The Uint8Array representation
  34253. */
  34254. PublicKeyEncryptedSessionKey.prototype.write = function () {
  34255. const arr = [new Uint8Array([this.version]), this.publicKeyId.write(), new Uint8Array([_enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm)])];
  34256. for (let i = 0; i < this.encrypted.length; i++) {
  34257. arr.push(this.encrypted[i].write());
  34258. }
  34259. return _util2.default.concatUint8Array(arr);
  34260. };
  34261. /**
  34262. * Encrypt session key packet
  34263. * @param {module:packet.PublicKey} key Public key
  34264. * @returns {Promise<Boolean>}
  34265. * @async
  34266. */
  34267. PublicKeyEncryptedSessionKey.prototype.encrypt = async function (key) {
  34268. let data = String.fromCharCode(_enums2.default.write(_enums2.default.symmetric, this.sessionKeyAlgorithm));
  34269. data += _util2.default.Uint8Array_to_str(this.sessionKey);
  34270. data += _util2.default.Uint8Array_to_str(_util2.default.write_checksum(this.sessionKey));
  34271. const algo = _enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm);
  34272. this.encrypted = await _crypto2.default.publicKeyEncrypt(algo, key.params, data, key.getFingerprintBytes());
  34273. return true;
  34274. };
  34275. /**
  34276. * Decrypts the session key (only for public key encrypted session key
  34277. * packets (tag 1)
  34278. *
  34279. * @param {module:packet.SecretKey} key
  34280. * Private key with secret params unlocked
  34281. * @returns {Promise<Boolean>}
  34282. * @async
  34283. */
  34284. PublicKeyEncryptedSessionKey.prototype.decrypt = async function (key) {
  34285. const algo = _enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm);
  34286. const decoded = await _crypto2.default.publicKeyDecrypt(algo, key.params, this.encrypted, key.getFingerprintBytes());
  34287. const checksum = _util2.default.str_to_Uint8Array(decoded.substr(decoded.length - 2));
  34288. key = _util2.default.str_to_Uint8Array(decoded.substring(1, decoded.length - 2));
  34289. if (!_util2.default.equalsUint8Array(checksum, _util2.default.write_checksum(key))) {
  34290. throw new Error('Decryption error');
  34291. } else {
  34292. this.sessionKey = key;
  34293. this.sessionKeyAlgorithm = _enums2.default.read(_enums2.default.symmetric, decoded.charCodeAt(0));
  34294. }
  34295. return true;
  34296. };
  34297. /**
  34298. * Fix custom types after cloning
  34299. */
  34300. PublicKeyEncryptedSessionKey.prototype.postCloneTypeFix = function () {
  34301. this.publicKeyId = _keyid2.default.fromClone(this.publicKeyId);
  34302. const algo = _enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm);
  34303. const types = _crypto2.default.getEncSessionKeyParamTypes(algo);
  34304. for (let i = 0; i < this.encrypted.length; i++) {
  34305. this.encrypted[i] = types[i].fromClone(this.encrypted[i]);
  34306. }
  34307. };
  34308. exports.default = PublicKeyEncryptedSessionKey;
  34309. },{"../crypto":94,"../enums":113,"../type/keyid":154,"../util":158}],139:[function(require,module,exports){
  34310. 'use strict';
  34311. Object.defineProperty(exports, "__esModule", {
  34312. value: true
  34313. });
  34314. var _public_key = require('./public_key');
  34315. var _public_key2 = _interopRequireDefault(_public_key);
  34316. var _enums = require('../enums');
  34317. var _enums2 = _interopRequireDefault(_enums);
  34318. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  34319. /**
  34320. * A Public-Subkey packet (tag 14) has exactly the same format as a
  34321. * Public-Key packet, but denotes a subkey. One or more subkeys may be
  34322. * associated with a top-level key. By convention, the top-level key
  34323. * provides signature services, and the subkeys provide encryption
  34324. * services.
  34325. * @memberof module:packet
  34326. * @constructor
  34327. * @extends module:packet.PublicKey
  34328. */
  34329. // GPG4Browsers - An OpenPGP implementation in javascript
  34330. // Copyright (C) 2011 Recurity Labs GmbH
  34331. //
  34332. // This library is free software; you can redistribute it and/or
  34333. // modify it under the terms of the GNU Lesser General Public
  34334. // License as published by the Free Software Foundation; either
  34335. // version 3.0 of the License, or (at your option) any later version.
  34336. //
  34337. // This library is distributed in the hope that it will be useful,
  34338. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  34339. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  34340. // Lesser General Public License for more details.
  34341. //
  34342. // You should have received a copy of the GNU Lesser General Public
  34343. // License along with this library; if not, write to the Free Software
  34344. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  34345. /**
  34346. * @requires packet/public_key
  34347. * @requires enums
  34348. */
  34349. function PublicSubkey() {
  34350. _public_key2.default.call(this);
  34351. this.tag = _enums2.default.packet.publicSubkey;
  34352. }
  34353. PublicSubkey.prototype = new _public_key2.default();
  34354. PublicSubkey.prototype.constructor = PublicSubkey;
  34355. exports.default = PublicSubkey;
  34356. },{"../enums":113,"./public_key":137}],140:[function(require,module,exports){
  34357. 'use strict';
  34358. Object.defineProperty(exports, "__esModule", {
  34359. value: true
  34360. });
  34361. var _public_key = require('./public_key');
  34362. var _public_key2 = _interopRequireDefault(_public_key);
  34363. var _keyid = require('../type/keyid.js');
  34364. var _keyid2 = _interopRequireDefault(_keyid);
  34365. var _s2k = require('../type/s2k');
  34366. var _s2k2 = _interopRequireDefault(_s2k);
  34367. var _crypto = require('../crypto');
  34368. var _crypto2 = _interopRequireDefault(_crypto);
  34369. var _enums = require('../enums');
  34370. var _enums2 = _interopRequireDefault(_enums);
  34371. var _util = require('../util');
  34372. var _util2 = _interopRequireDefault(_util);
  34373. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  34374. /**
  34375. * A Secret-Key packet contains all the information that is found in a
  34376. * Public-Key packet, including the public-key material, but also
  34377. * includes the secret-key material after all the public-key fields.
  34378. * @memberof module:packet
  34379. * @constructor
  34380. * @extends module:packet.PublicKey
  34381. */
  34382. // GPG4Browsers - An OpenPGP implementation in javascript
  34383. // Copyright (C) 2011 Recurity Labs GmbH
  34384. //
  34385. // This library is free software; you can redistribute it and/or
  34386. // modify it under the terms of the GNU Lesser General Public
  34387. // License as published by the Free Software Foundation; either
  34388. // version 3.0 of the License, or (at your option) any later version.
  34389. //
  34390. // This library is distributed in the hope that it will be useful,
  34391. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  34392. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  34393. // Lesser General Public License for more details.
  34394. //
  34395. // You should have received a copy of the GNU Lesser General Public
  34396. // License along with this library; if not, write to the Free Software
  34397. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  34398. /**
  34399. * @requires packet/public_key
  34400. * @requires type/keyid
  34401. * @requires type/s2k
  34402. * @requires crypto
  34403. * @requires enums
  34404. * @requires util
  34405. */
  34406. function SecretKey(date = new Date()) {
  34407. _public_key2.default.call(this, date);
  34408. /**
  34409. * Packet type
  34410. * @type {module:enums.packet}
  34411. */
  34412. this.tag = _enums2.default.packet.secretKey;
  34413. /**
  34414. * Secret-key data
  34415. */
  34416. this.keyMaterial = null;
  34417. /**
  34418. * Indicates whether secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form.
  34419. */
  34420. this.isEncrypted = null;
  34421. /**
  34422. * S2K usage
  34423. * @type {Integer}
  34424. */
  34425. this.s2k_usage = 0;
  34426. /**
  34427. * S2K object
  34428. * @type {type/s2k}
  34429. */
  34430. this.s2k = null;
  34431. /**
  34432. * Symmetric algorithm
  34433. * @type {String}
  34434. */
  34435. this.symmetric = null;
  34436. /**
  34437. * AEAD algorithm
  34438. * @type {String}
  34439. */
  34440. this.aead = null;
  34441. }
  34442. SecretKey.prototype = new _public_key2.default();
  34443. SecretKey.prototype.constructor = SecretKey;
  34444. // Helper function
  34445. function parse_cleartext_params(cleartext, algorithm) {
  34446. const algo = _enums2.default.write(_enums2.default.publicKey, algorithm);
  34447. const types = _crypto2.default.getPrivKeyParamTypes(algo);
  34448. const params = _crypto2.default.constructParams(types);
  34449. let p = 0;
  34450. for (let i = 0; i < types.length && p < cleartext.length; i++) {
  34451. p += params[i].read(cleartext.subarray(p, cleartext.length));
  34452. if (p > cleartext.length) {
  34453. throw new Error('Error reading param @:' + p);
  34454. }
  34455. }
  34456. return params;
  34457. }
  34458. function write_cleartext_params(params, algorithm) {
  34459. const arr = [];
  34460. const algo = _enums2.default.write(_enums2.default.publicKey, algorithm);
  34461. const numPublicParams = _crypto2.default.getPubKeyParamTypes(algo).length;
  34462. for (let i = numPublicParams; i < params.length; i++) {
  34463. arr.push(params[i].write());
  34464. }
  34465. return _util2.default.concatUint8Array(arr);
  34466. }
  34467. // 5.5.3. Secret-Key Packet Formats
  34468. /**
  34469. * Internal parser for private keys as specified in
  34470. * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3}
  34471. * @param {String} bytes Input string to read the packet from
  34472. */
  34473. SecretKey.prototype.read = function (bytes) {
  34474. // - A Public-Key or Public-Subkey packet, as described above.
  34475. let i = this.readPublicKey(bytes);
  34476. // - One octet indicating string-to-key usage conventions. Zero
  34477. // indicates that the secret-key data is not encrypted. 255 or 254
  34478. // indicates that a string-to-key specifier is being given. Any
  34479. // other value is a symmetric-key encryption algorithm identifier.
  34480. this.s2k_usage = bytes[i++];
  34481. // - Only for a version 5 packet, a one-octet scalar octet count of
  34482. // the next 4 optional fields.
  34483. if (this.version === 5) {
  34484. i++;
  34485. }
  34486. // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
  34487. // one-octet symmetric encryption algorithm.
  34488. if (this.s2k_usage === 255 || this.s2k_usage === 254 || this.s2k_usage === 253) {
  34489. this.symmetric = bytes[i++];
  34490. this.symmetric = _enums2.default.read(_enums2.default.symmetric, this.symmetric);
  34491. // - [Optional] If string-to-key usage octet was 253, a one-octet
  34492. // AEAD algorithm.
  34493. if (this.s2k_usage === 253) {
  34494. this.aead = bytes[i++];
  34495. this.aead = _enums2.default.read(_enums2.default.aead, this.aead);
  34496. }
  34497. // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
  34498. // string-to-key specifier. The length of the string-to-key
  34499. // specifier is implied by its type, as described above.
  34500. this.s2k = new _s2k2.default();
  34501. i += this.s2k.read(bytes.subarray(i, bytes.length));
  34502. if (this.s2k.type === 'gnu-dummy') {
  34503. return;
  34504. }
  34505. } else if (this.s2k_usage) {
  34506. this.symmetric = this.s2k_usage;
  34507. this.symmetric = _enums2.default.read(_enums2.default.symmetric, this.symmetric);
  34508. }
  34509. // - [Optional] If secret data is encrypted (string-to-key usage octet
  34510. // not zero), an Initial Vector (IV) of the same length as the
  34511. // cipher's block size.
  34512. if (this.s2k_usage) {
  34513. this.iv = bytes.subarray(i, i + _crypto2.default.cipher[this.symmetric].blockSize);
  34514. i += this.iv.length;
  34515. }
  34516. // - Only for a version 5 packet, a four-octet scalar octet count for
  34517. // the following key material.
  34518. if (this.version === 5) {
  34519. i += 4;
  34520. }
  34521. // - Plain or encrypted multiprecision integers comprising the secret
  34522. // key data. These algorithm-specific fields are as described
  34523. // below.
  34524. this.keyMaterial = bytes.subarray(i);
  34525. this.isEncrypted = !!this.s2k_usage;
  34526. if (!this.isEncrypted) {
  34527. const cleartext = this.keyMaterial.subarray(0, -2);
  34528. if (!_util2.default.equalsUint8Array(_util2.default.write_checksum(cleartext), this.keyMaterial.subarray(-2))) {
  34529. throw new Error('Key checksum mismatch');
  34530. }
  34531. const privParams = parse_cleartext_params(cleartext, this.algorithm);
  34532. this.params = this.params.concat(privParams);
  34533. }
  34534. };
  34535. /**
  34536. * Creates an OpenPGP key packet for the given key.
  34537. * @returns {String} A string of bytes containing the secret key OpenPGP packet
  34538. */
  34539. SecretKey.prototype.write = function () {
  34540. const arr = [this.writePublicKey()];
  34541. arr.push(new Uint8Array([this.s2k_usage]));
  34542. const optionalFieldsArr = [];
  34543. // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
  34544. // one- octet symmetric encryption algorithm.
  34545. if (this.s2k_usage === 255 || this.s2k_usage === 254 || this.s2k_usage === 253) {
  34546. optionalFieldsArr.push(_enums2.default.write(_enums2.default.symmetric, this.symmetric));
  34547. // - [Optional] If string-to-key usage octet was 253, a one-octet
  34548. // AEAD algorithm.
  34549. if (this.s2k_usage === 253) {
  34550. optionalFieldsArr.push(_enums2.default.write(_enums2.default.aead, this.aead));
  34551. }
  34552. // - [Optional] If string-to-key usage octet was 255, 254, or 253, a
  34553. // string-to-key specifier. The length of the string-to-key
  34554. // specifier is implied by its type, as described above.
  34555. optionalFieldsArr.push(...this.s2k.write());
  34556. }
  34557. // - [Optional] If secret data is encrypted (string-to-key usage octet
  34558. // not zero), an Initial Vector (IV) of the same length as the
  34559. // cipher's block size.
  34560. if (this.s2k_usage && this.s2k.type !== 'gnu-dummy') {
  34561. optionalFieldsArr.push(...this.iv);
  34562. }
  34563. if (this.version === 5) {
  34564. arr.push(new Uint8Array([optionalFieldsArr.length]));
  34565. }
  34566. arr.push(new Uint8Array(optionalFieldsArr));
  34567. if (!this.s2k || this.s2k.type !== 'gnu-dummy') {
  34568. if (!this.s2k_usage) {
  34569. const cleartextParams = write_cleartext_params(this.params, this.algorithm);
  34570. this.keyMaterial = _util2.default.concatUint8Array([cleartextParams, _util2.default.write_checksum(cleartextParams)]);
  34571. }
  34572. if (this.version === 5) {
  34573. arr.push(_util2.default.writeNumber(this.keyMaterial.length, 4));
  34574. }
  34575. arr.push(this.keyMaterial);
  34576. }
  34577. return _util2.default.concatUint8Array(arr);
  34578. };
  34579. /**
  34580. * Check whether secret-key data is available in decrypted form. Returns null for public keys.
  34581. * @returns {Boolean|null}
  34582. */
  34583. SecretKey.prototype.isDecrypted = function () {
  34584. return this.isEncrypted === false;
  34585. };
  34586. /**
  34587. * Encrypt the payload. By default, we use aes256 and iterated, salted string
  34588. * to key specifier. If the key is in a decrypted state (isEncrypted === false)
  34589. * and the passphrase is empty or undefined, the key will be set as not encrypted.
  34590. * This can be used to remove passphrase protection after calling decrypt().
  34591. * @param {String} passphrase
  34592. * @returns {Promise<Boolean>}
  34593. * @async
  34594. */
  34595. SecretKey.prototype.encrypt = async function (passphrase) {
  34596. if (this.s2k && this.s2k.type === 'gnu-dummy') {
  34597. return false;
  34598. }
  34599. if (!this.isDecrypted()) {
  34600. throw new Error('Key packet is already encrypted');
  34601. }
  34602. if (this.isDecrypted() && !passphrase) {
  34603. this.s2k_usage = 0;
  34604. return false;
  34605. } else if (!passphrase) {
  34606. throw new Error('The key must be decrypted before removing passphrase protection.');
  34607. }
  34608. this.s2k = new _s2k2.default();
  34609. this.s2k.salt = await _crypto2.default.random.getRandomBytes(8);
  34610. const cleartext = write_cleartext_params(this.params, this.algorithm);
  34611. this.symmetric = 'aes256';
  34612. const key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric);
  34613. const blockLen = _crypto2.default.cipher[this.symmetric].blockSize;
  34614. this.iv = await _crypto2.default.random.getRandomBytes(blockLen);
  34615. if (this.version === 5) {
  34616. this.s2k_usage = 253;
  34617. this.aead = 'eax';
  34618. const mode = _crypto2.default[this.aead];
  34619. const modeInstance = await mode(this.symmetric, key);
  34620. this.keyMaterial = await modeInstance.encrypt(cleartext, this.iv.subarray(0, mode.ivLength), new Uint8Array());
  34621. } else {
  34622. this.s2k_usage = 254;
  34623. this.keyMaterial = _crypto2.default.cfb.encrypt(this.symmetric, key, _util2.default.concatUint8Array([cleartext, await _crypto2.default.hash.sha1(cleartext)]), this.iv);
  34624. }
  34625. return true;
  34626. };
  34627. async function produceEncryptionKey(s2k, passphrase, algorithm) {
  34628. return s2k.produce_key(passphrase, _crypto2.default.cipher[algorithm].keySize);
  34629. }
  34630. /**
  34631. * Decrypts the private key params which are needed to use the key.
  34632. * {@link module:packet.SecretKey.isDecrypted} should be false, as
  34633. * otherwise calls to this function will throw an error.
  34634. * @param {String} passphrase The passphrase for this private key as string
  34635. * @returns {Promise<Boolean>}
  34636. * @async
  34637. */
  34638. SecretKey.prototype.decrypt = async function (passphrase) {
  34639. if (this.s2k.type === 'gnu-dummy') {
  34640. this.isEncrypted = false;
  34641. return false;
  34642. }
  34643. if (this.isDecrypted()) {
  34644. throw new Error('Key packet is already decrypted.');
  34645. }
  34646. let key;
  34647. if (this.s2k_usage === 255 || this.s2k_usage === 254 || this.s2k_usage === 253) {
  34648. key = await produceEncryptionKey(this.s2k, passphrase, this.symmetric);
  34649. } else {
  34650. key = await _crypto2.default.hash.md5(passphrase);
  34651. }
  34652. let cleartext;
  34653. if (this.s2k_usage === 253) {
  34654. const mode = _crypto2.default[this.aead];
  34655. try {
  34656. const modeInstance = await mode(this.symmetric, key);
  34657. cleartext = await modeInstance.decrypt(this.keyMaterial, this.iv.subarray(0, mode.ivLength), new Uint8Array());
  34658. } catch (err) {
  34659. if (err.message === 'Authentication tag mismatch') {
  34660. throw new Error('Incorrect key passphrase: ' + err.message);
  34661. }
  34662. throw err;
  34663. }
  34664. } else {
  34665. const cleartextWithHash = await _crypto2.default.cfb.decrypt(this.symmetric, key, this.keyMaterial, this.iv);
  34666. let hash;
  34667. let hashlen;
  34668. if (this.s2k_usage === 255) {
  34669. hashlen = 2;
  34670. cleartext = cleartextWithHash.subarray(0, -hashlen);
  34671. hash = _util2.default.write_checksum(cleartext);
  34672. } else {
  34673. hashlen = 20;
  34674. cleartext = cleartextWithHash.subarray(0, -hashlen);
  34675. hash = await _crypto2.default.hash.sha1(cleartext);
  34676. }
  34677. if (!_util2.default.equalsUint8Array(hash, cleartextWithHash.subarray(-hashlen))) {
  34678. throw new Error('Incorrect key passphrase');
  34679. }
  34680. }
  34681. const privParams = parse_cleartext_params(cleartext, this.algorithm);
  34682. this.params = this.params.concat(privParams);
  34683. this.isEncrypted = false;
  34684. this.keyMaterial = null;
  34685. this.s2k_usage = 0;
  34686. return true;
  34687. };
  34688. SecretKey.prototype.generate = async function (bits, curve) {
  34689. const algo = _enums2.default.write(_enums2.default.publicKey, this.algorithm);
  34690. this.params = await _crypto2.default.generateParams(algo, bits, curve);
  34691. this.isEncrypted = false;
  34692. };
  34693. /**
  34694. * Clear private params, return to initial state
  34695. */
  34696. SecretKey.prototype.clearPrivateParams = function () {
  34697. if (this.s2k && this.s2k.type === 'gnu-dummy') {
  34698. this.isEncrypted = true;
  34699. return;
  34700. }
  34701. if (!this.keyMaterial) {
  34702. throw new Error('If secret key is not encrypted, clearing private params is irreversible.');
  34703. }
  34704. const algo = _enums2.default.write(_enums2.default.publicKey, this.algorithm);
  34705. this.params = this.params.slice(0, _crypto2.default.getPubKeyParamTypes(algo).length);
  34706. this.isEncrypted = true;
  34707. };
  34708. /**
  34709. * Fix custom types after cloning
  34710. */
  34711. SecretKey.prototype.postCloneTypeFix = function () {
  34712. const algo = _enums2.default.write(_enums2.default.publicKey, this.algorithm);
  34713. const types = [].concat(_crypto2.default.getPubKeyParamTypes(algo), _crypto2.default.getPrivKeyParamTypes(algo));
  34714. for (let i = 0; i < this.params.length; i++) {
  34715. const param = this.params[i];
  34716. this.params[i] = types[i].fromClone(param);
  34717. }
  34718. if (this.keyid) {
  34719. this.keyid = _keyid2.default.fromClone(this.keyid);
  34720. }
  34721. if (this.s2k) {
  34722. this.s2k = _s2k2.default.fromClone(this.s2k);
  34723. }
  34724. };
  34725. exports.default = SecretKey;
  34726. },{"../crypto":94,"../enums":113,"../type/keyid.js":154,"../type/s2k":157,"../util":158,"./public_key":137}],141:[function(require,module,exports){
  34727. 'use strict';
  34728. Object.defineProperty(exports, "__esModule", {
  34729. value: true
  34730. });
  34731. var _secret_key = require('./secret_key');
  34732. var _secret_key2 = _interopRequireDefault(_secret_key);
  34733. var _enums = require('../enums');
  34734. var _enums2 = _interopRequireDefault(_enums);
  34735. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  34736. /**
  34737. * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret
  34738. * Key packet and has exactly the same format.
  34739. * @memberof module:packet
  34740. * @constructor
  34741. * @extends module:packet.SecretKey
  34742. */
  34743. // GPG4Browsers - An OpenPGP implementation in javascript
  34744. // Copyright (C) 2011 Recurity Labs GmbH
  34745. //
  34746. // This library is free software; you can redistribute it and/or
  34747. // modify it under the terms of the GNU Lesser General Public
  34748. // License as published by the Free Software Foundation; either
  34749. // version 3.0 of the License, or (at your option) any later version.
  34750. //
  34751. // This library is distributed in the hope that it will be useful,
  34752. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  34753. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  34754. // Lesser General Public License for more details.
  34755. //
  34756. // You should have received a copy of the GNU Lesser General Public
  34757. // License along with this library; if not, write to the Free Software
  34758. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  34759. /**
  34760. * @requires packet/secret_key
  34761. * @requires enums
  34762. */
  34763. function SecretSubkey(date = new Date()) {
  34764. _secret_key2.default.call(this, date);
  34765. this.tag = _enums2.default.packet.secretSubkey;
  34766. }
  34767. SecretSubkey.prototype = new _secret_key2.default();
  34768. SecretSubkey.prototype.constructor = SecretSubkey;
  34769. exports.default = SecretSubkey;
  34770. },{"../enums":113,"./secret_key":140}],142:[function(require,module,exports){
  34771. 'use strict';
  34772. Object.defineProperty(exports, "__esModule", {
  34773. value: true
  34774. });
  34775. var _webStreamTools = require('web-stream-tools');
  34776. var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
  34777. var _packet = require('./packet');
  34778. var _packet2 = _interopRequireDefault(_packet);
  34779. var _keyid = require('../type/keyid.js');
  34780. var _keyid2 = _interopRequireDefault(_keyid);
  34781. var _mpi = require('../type/mpi.js');
  34782. var _mpi2 = _interopRequireDefault(_mpi);
  34783. var _crypto = require('../crypto');
  34784. var _crypto2 = _interopRequireDefault(_crypto);
  34785. var _enums = require('../enums');
  34786. var _enums2 = _interopRequireDefault(_enums);
  34787. var _util = require('../util');
  34788. var _util2 = _interopRequireDefault(_util);
  34789. var _config = require('../config');
  34790. var _config2 = _interopRequireDefault(_config);
  34791. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  34792. /**
  34793. * Implementation of the Signature Packet (Tag 2)
  34794. *
  34795. * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}:
  34796. * A Signature packet describes a binding between some public key and
  34797. * some data. The most common signatures are a signature of a file or a
  34798. * block of text, and a signature that is a certification of a User ID.
  34799. * @memberof module:packet
  34800. * @constructor
  34801. * @param {Date} date the creation date of the signature
  34802. */
  34803. // GPG4Browsers - An OpenPGP implementation in javascript
  34804. // Copyright (C) 2011 Recurity Labs GmbH
  34805. //
  34806. // This library is free software; you can redistribute it and/or
  34807. // modify it under the terms of the GNU Lesser General Public
  34808. // License as published by the Free Software Foundation; either
  34809. // version 3.0 of the License, or (at your option) any later version.
  34810. //
  34811. // This library is distributed in the hope that it will be useful,
  34812. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  34813. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  34814. // Lesser General Public License for more details.
  34815. //
  34816. // You should have received a copy of the GNU Lesser General Public
  34817. // License along with this library; if not, write to the Free Software
  34818. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  34819. /**
  34820. * @requires web-stream-tools
  34821. * @requires packet/packet
  34822. * @requires type/keyid
  34823. * @requires type/mpi
  34824. * @requires crypto
  34825. * @requires enums
  34826. * @requires util
  34827. */
  34828. function Signature(date = new Date()) {
  34829. this.tag = _enums2.default.packet.signature;
  34830. this.version = 4; // This is set to 5 below if we sign with a V5 key.
  34831. this.signatureType = null;
  34832. this.hashAlgorithm = null;
  34833. this.publicKeyAlgorithm = null;
  34834. this.signatureData = null;
  34835. this.unhashedSubpackets = [];
  34836. this.signedHashValue = null;
  34837. this.created = _util2.default.normalizeDate(date);
  34838. this.signatureExpirationTime = null;
  34839. this.signatureNeverExpires = true;
  34840. this.exportable = null;
  34841. this.trustLevel = null;
  34842. this.trustAmount = null;
  34843. this.regularExpression = null;
  34844. this.revocable = null;
  34845. this.keyExpirationTime = null;
  34846. this.keyNeverExpires = null;
  34847. this.preferredSymmetricAlgorithms = null;
  34848. this.revocationKeyClass = null;
  34849. this.revocationKeyAlgorithm = null;
  34850. this.revocationKeyFingerprint = null;
  34851. this.issuerKeyId = new _keyid2.default();
  34852. this.notations = [];
  34853. this.preferredHashAlgorithms = null;
  34854. this.preferredCompressionAlgorithms = null;
  34855. this.keyServerPreferences = null;
  34856. this.preferredKeyServer = null;
  34857. this.isPrimaryUserID = null;
  34858. this.policyURI = null;
  34859. this.keyFlags = null;
  34860. this.signersUserId = null;
  34861. this.reasonForRevocationFlag = null;
  34862. this.reasonForRevocationString = null;
  34863. this.features = null;
  34864. this.signatureTargetPublicKeyAlgorithm = null;
  34865. this.signatureTargetHashAlgorithm = null;
  34866. this.signatureTargetHash = null;
  34867. this.embeddedSignature = null;
  34868. this.issuerKeyVersion = null;
  34869. this.issuerFingerprint = null;
  34870. this.preferredAeadAlgorithms = null;
  34871. this.verified = null;
  34872. this.revoked = null;
  34873. }
  34874. /**
  34875. * parsing function for a signature packet (tag 2).
  34876. * @param {String} bytes payload of a tag 2 packet
  34877. * @param {Integer} position position to start reading from the bytes string
  34878. * @param {Integer} len length of the packet or the remaining length of bytes at position
  34879. * @returns {module:packet.Signature} object representation
  34880. */
  34881. Signature.prototype.read = function (bytes) {
  34882. let i = 0;
  34883. this.version = bytes[i++];
  34884. if (this.version !== 4 && this.version !== 5) {
  34885. throw new Error('Version ' + this.version + ' of the signature is unsupported.');
  34886. }
  34887. this.signatureType = bytes[i++];
  34888. this.publicKeyAlgorithm = bytes[i++];
  34889. this.hashAlgorithm = bytes[i++];
  34890. // hashed subpackets
  34891. i += this.read_sub_packets(bytes.subarray(i, bytes.length), true);
  34892. // A V4 signature hashes the packet body
  34893. // starting from its first field, the version number, through the end
  34894. // of the hashed subpacket data. Thus, the fields hashed are the
  34895. // signature version, the signature type, the public-key algorithm, the
  34896. // hash algorithm, the hashed subpacket length, and the hashed
  34897. // subpacket body.
  34898. this.signatureData = bytes.subarray(0, i);
  34899. // unhashed subpackets
  34900. i += this.read_sub_packets(bytes.subarray(i, bytes.length), false);
  34901. // Two-octet field holding left 16 bits of signed hash value.
  34902. this.signedHashValue = bytes.subarray(i, i + 2);
  34903. i += 2;
  34904. this.signature = bytes.subarray(i, bytes.length);
  34905. };
  34906. Signature.prototype.write = function () {
  34907. const arr = [];
  34908. arr.push(this.signatureData);
  34909. arr.push(this.write_unhashed_sub_packets());
  34910. arr.push(this.signedHashValue);
  34911. arr.push(_webStreamTools2.default.clone(this.signature));
  34912. return _util2.default.concat(arr);
  34913. };
  34914. /**
  34915. * Signs provided data. This needs to be done prior to serialization.
  34916. * @param {module:packet.SecretKey} key private key used to sign the message.
  34917. * @param {Object} data Contains packets to be signed.
  34918. * @param {Boolean} detached (optional) whether to create a detached signature
  34919. * @param {Boolean} streaming (optional) whether to process data as a stream
  34920. * @returns {Promise<Boolean>}
  34921. * @async
  34922. */
  34923. Signature.prototype.sign = async function (key, data, detached = false, streaming = false) {
  34924. const signatureType = _enums2.default.write(_enums2.default.signature, this.signatureType);
  34925. const publicKeyAlgorithm = _enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm);
  34926. const hashAlgorithm = _enums2.default.write(_enums2.default.hash, this.hashAlgorithm);
  34927. if (key.version === 5) {
  34928. this.version = 5;
  34929. }
  34930. const arr = [new Uint8Array([this.version, signatureType, publicKeyAlgorithm, hashAlgorithm])];
  34931. if (key.version === 5) {
  34932. // We could also generate this subpacket for version 4 keys, but for
  34933. // now we don't.
  34934. this.issuerKeyVersion = key.version;
  34935. this.issuerFingerprint = key.getFingerprintBytes();
  34936. }
  34937. this.issuerKeyId = key.getKeyId();
  34938. // Add hashed subpackets
  34939. arr.push(this.write_hashed_sub_packets());
  34940. this.signatureData = _util2.default.concat(arr);
  34941. const toHash = this.toHash(signatureType, data, detached);
  34942. const hash = await this.hash(signatureType, data, toHash, detached);
  34943. this.signedHashValue = _webStreamTools2.default.slice(_webStreamTools2.default.clone(hash), 0, 2);
  34944. const params = key.params;
  34945. const signed = async () => _crypto2.default.signature.sign(publicKeyAlgorithm, hashAlgorithm, params, toHash, (await _webStreamTools2.default.readToEnd(hash)));
  34946. if (streaming) {
  34947. this.signature = _webStreamTools2.default.fromAsync(signed);
  34948. } else {
  34949. this.signature = await signed();
  34950. // Store the fact that this signature is valid, e.g. for when we call `await
  34951. // getLatestValidSignature(this.revocationSignatures, key, data)` later.
  34952. // Note that this only holds up if the key and data passed to verify are the
  34953. // same as the ones passed to sign.
  34954. this.verified = true;
  34955. }
  34956. return true;
  34957. };
  34958. /**
  34959. * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets
  34960. * @returns {Uint8Array} subpacket data
  34961. */
  34962. Signature.prototype.write_hashed_sub_packets = function () {
  34963. const sub = _enums2.default.signatureSubpacket;
  34964. const arr = [];
  34965. let bytes;
  34966. if (this.created !== null) {
  34967. arr.push(write_sub_packet(sub.signature_creation_time, _util2.default.writeDate(this.created)));
  34968. }
  34969. if (this.signatureExpirationTime !== null) {
  34970. arr.push(write_sub_packet(sub.signature_expiration_time, _util2.default.writeNumber(this.signatureExpirationTime, 4)));
  34971. }
  34972. if (this.exportable !== null) {
  34973. arr.push(write_sub_packet(sub.exportable_certification, new Uint8Array([this.exportable ? 1 : 0])));
  34974. }
  34975. if (this.trustLevel !== null) {
  34976. bytes = new Uint8Array([this.trustLevel, this.trustAmount]);
  34977. arr.push(write_sub_packet(sub.trust_signature, bytes));
  34978. }
  34979. if (this.regularExpression !== null) {
  34980. arr.push(write_sub_packet(sub.regular_expression, this.regularExpression));
  34981. }
  34982. if (this.revocable !== null) {
  34983. arr.push(write_sub_packet(sub.revocable, new Uint8Array([this.revocable ? 1 : 0])));
  34984. }
  34985. if (this.keyExpirationTime !== null) {
  34986. arr.push(write_sub_packet(sub.key_expiration_time, _util2.default.writeNumber(this.keyExpirationTime, 4)));
  34987. }
  34988. if (this.preferredSymmetricAlgorithms !== null) {
  34989. bytes = _util2.default.str_to_Uint8Array(_util2.default.Uint8Array_to_str(this.preferredSymmetricAlgorithms));
  34990. arr.push(write_sub_packet(sub.preferred_symmetric_algorithms, bytes));
  34991. }
  34992. if (this.revocationKeyClass !== null) {
  34993. bytes = new Uint8Array([this.revocationKeyClass, this.revocationKeyAlgorithm]);
  34994. bytes = _util2.default.concat([bytes, this.revocationKeyFingerprint]);
  34995. arr.push(write_sub_packet(sub.revocation_key, bytes));
  34996. }
  34997. this.notations.forEach(([name, value]) => {
  34998. bytes = [new Uint8Array([0x80, 0, 0, 0])];
  34999. // 2 octets of name length
  35000. bytes.push(_util2.default.writeNumber(name.length, 2));
  35001. // 2 octets of value length
  35002. bytes.push(_util2.default.writeNumber(value.length, 2));
  35003. bytes.push(_util2.default.str_to_Uint8Array(name + value));
  35004. bytes = _util2.default.concat(bytes);
  35005. arr.push(write_sub_packet(sub.notation_data, bytes));
  35006. });
  35007. if (this.preferredHashAlgorithms !== null) {
  35008. bytes = _util2.default.str_to_Uint8Array(_util2.default.Uint8Array_to_str(this.preferredHashAlgorithms));
  35009. arr.push(write_sub_packet(sub.preferred_hash_algorithms, bytes));
  35010. }
  35011. if (this.preferredCompressionAlgorithms !== null) {
  35012. bytes = _util2.default.str_to_Uint8Array(_util2.default.Uint8Array_to_str(this.preferredCompressionAlgorithms));
  35013. arr.push(write_sub_packet(sub.preferred_compression_algorithms, bytes));
  35014. }
  35015. if (this.keyServerPreferences !== null) {
  35016. bytes = _util2.default.str_to_Uint8Array(_util2.default.Uint8Array_to_str(this.keyServerPreferences));
  35017. arr.push(write_sub_packet(sub.key_server_preferences, bytes));
  35018. }
  35019. if (this.preferredKeyServer !== null) {
  35020. arr.push(write_sub_packet(sub.preferred_key_server, _util2.default.str_to_Uint8Array(this.preferredKeyServer)));
  35021. }
  35022. if (this.isPrimaryUserID !== null) {
  35023. arr.push(write_sub_packet(sub.primary_user_id, new Uint8Array([this.isPrimaryUserID ? 1 : 0])));
  35024. }
  35025. if (this.policyURI !== null) {
  35026. arr.push(write_sub_packet(sub.policy_uri, _util2.default.str_to_Uint8Array(this.policyURI)));
  35027. }
  35028. if (this.keyFlags !== null) {
  35029. bytes = _util2.default.str_to_Uint8Array(_util2.default.Uint8Array_to_str(this.keyFlags));
  35030. arr.push(write_sub_packet(sub.key_flags, bytes));
  35031. }
  35032. if (this.signersUserId !== null) {
  35033. arr.push(write_sub_packet(sub.signers_user_id, _util2.default.str_to_Uint8Array(this.signersUserId)));
  35034. }
  35035. if (this.reasonForRevocationFlag !== null) {
  35036. bytes = _util2.default.str_to_Uint8Array(String.fromCharCode(this.reasonForRevocationFlag) + this.reasonForRevocationString);
  35037. arr.push(write_sub_packet(sub.reason_for_revocation, bytes));
  35038. }
  35039. if (this.features !== null) {
  35040. bytes = _util2.default.str_to_Uint8Array(_util2.default.Uint8Array_to_str(this.features));
  35041. arr.push(write_sub_packet(sub.features, bytes));
  35042. }
  35043. if (this.signatureTargetPublicKeyAlgorithm !== null) {
  35044. bytes = [new Uint8Array([this.signatureTargetPublicKeyAlgorithm, this.signatureTargetHashAlgorithm])];
  35045. bytes.push(_util2.default.str_to_Uint8Array(this.signatureTargetHash));
  35046. bytes = _util2.default.concat(bytes);
  35047. arr.push(write_sub_packet(sub.signature_target, bytes));
  35048. }
  35049. if (this.preferredAeadAlgorithms !== null) {
  35050. bytes = _util2.default.str_to_Uint8Array(_util2.default.Uint8Array_to_str(this.preferredAeadAlgorithms));
  35051. arr.push(write_sub_packet(sub.preferred_aead_algorithms, bytes));
  35052. }
  35053. const result = _util2.default.concat(arr);
  35054. const length = _util2.default.writeNumber(result.length, 2);
  35055. return _util2.default.concat([length, result]);
  35056. };
  35057. /**
  35058. * Creates Uint8Array of bytes of Issuer and Embedded Signature subpackets
  35059. * @returns {Uint8Array} subpacket data
  35060. */
  35061. Signature.prototype.write_unhashed_sub_packets = function () {
  35062. const sub = _enums2.default.signatureSubpacket;
  35063. const arr = [];
  35064. let bytes;
  35065. if (!this.issuerKeyId.isNull() && this.issuerKeyVersion !== 5) {
  35066. // If the version of [the] key is greater than 4, this subpacket
  35067. // MUST NOT be included in the signature.
  35068. arr.push(write_sub_packet(sub.issuer, this.issuerKeyId.write()));
  35069. }
  35070. if (this.embeddedSignature !== null) {
  35071. arr.push(write_sub_packet(sub.embedded_signature, this.embeddedSignature.write()));
  35072. }
  35073. if (this.issuerFingerprint !== null) {
  35074. bytes = [new Uint8Array([this.issuerKeyVersion]), this.issuerFingerprint];
  35075. bytes = _util2.default.concat(bytes);
  35076. arr.push(write_sub_packet(sub.issuer_fingerprint, bytes));
  35077. }
  35078. this.unhashedSubpackets.forEach(data => {
  35079. arr.push(_packet2.default.writeSimpleLength(data.length));
  35080. arr.push(data);
  35081. });
  35082. const result = _util2.default.concat(arr);
  35083. const length = _util2.default.writeNumber(result.length, 2);
  35084. return _util2.default.concat([length, result]);
  35085. };
  35086. /**
  35087. * Creates a string representation of a sub signature packet
  35088. * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.1|RFC4880 5.2.3.1}
  35089. * @see {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.2|RFC4880 5.2.3.2}
  35090. * @param {Integer} type subpacket signature type.
  35091. * @param {String} data data to be included
  35092. * @returns {String} a string-representation of a sub signature packet
  35093. * @private
  35094. */
  35095. function write_sub_packet(type, data) {
  35096. const arr = [];
  35097. arr.push(_packet2.default.writeSimpleLength(data.length + 1));
  35098. arr.push(new Uint8Array([type]));
  35099. arr.push(data);
  35100. return _util2.default.concat(arr);
  35101. }
  35102. // V4 signature sub packets
  35103. Signature.prototype.read_sub_packet = function (bytes, trusted = true) {
  35104. let mypos = 0;
  35105. const read_array = (prop, bytes) => {
  35106. this[prop] = [];
  35107. for (let i = 0; i < bytes.length; i++) {
  35108. this[prop].push(bytes[i]);
  35109. }
  35110. };
  35111. // The leftmost bit denotes a "critical" packet
  35112. const critical = bytes[mypos] & 0x80;
  35113. const type = bytes[mypos] & 0x7F;
  35114. // GPG puts the Issuer and Signature subpackets in the unhashed area.
  35115. // Tampering with those invalidates the signature, so we can trust them.
  35116. // Ignore all other unhashed subpackets.
  35117. if (!trusted && ![_enums2.default.signatureSubpacket.issuer, _enums2.default.signatureSubpacket.issuer_fingerprint, _enums2.default.signatureSubpacket.embedded_signature].includes(type)) {
  35118. this.unhashedSubpackets.push(bytes.subarray(mypos, bytes.length));
  35119. return;
  35120. }
  35121. mypos++;
  35122. // subpacket type
  35123. switch (type) {
  35124. case 2:
  35125. // Signature Creation Time
  35126. this.created = _util2.default.readDate(bytes.subarray(mypos, bytes.length));
  35127. break;
  35128. case 3:
  35129. {
  35130. // Signature Expiration Time in seconds
  35131. const seconds = _util2.default.readNumber(bytes.subarray(mypos, bytes.length));
  35132. this.signatureNeverExpires = seconds === 0;
  35133. this.signatureExpirationTime = seconds;
  35134. break;
  35135. }
  35136. case 4:
  35137. // Exportable Certification
  35138. this.exportable = bytes[mypos++] === 1;
  35139. break;
  35140. case 5:
  35141. // Trust Signature
  35142. this.trustLevel = bytes[mypos++];
  35143. this.trustAmount = bytes[mypos++];
  35144. break;
  35145. case 6:
  35146. // Regular Expression
  35147. this.regularExpression = bytes[mypos];
  35148. break;
  35149. case 7:
  35150. // Revocable
  35151. this.revocable = bytes[mypos++] === 1;
  35152. break;
  35153. case 9:
  35154. {
  35155. // Key Expiration Time in seconds
  35156. const seconds = _util2.default.readNumber(bytes.subarray(mypos, bytes.length));
  35157. this.keyExpirationTime = seconds;
  35158. this.keyNeverExpires = seconds === 0;
  35159. break;
  35160. }
  35161. case 11:
  35162. // Preferred Symmetric Algorithms
  35163. read_array('preferredSymmetricAlgorithms', bytes.subarray(mypos, bytes.length));
  35164. break;
  35165. case 12:
  35166. // Revocation Key
  35167. // (1 octet of class, 1 octet of public-key algorithm ID, 20
  35168. // octets of
  35169. // fingerprint)
  35170. this.revocationKeyClass = bytes[mypos++];
  35171. this.revocationKeyAlgorithm = bytes[mypos++];
  35172. this.revocationKeyFingerprint = bytes.subarray(mypos, mypos + 20);
  35173. break;
  35174. case 16:
  35175. // Issuer
  35176. this.issuerKeyId.read(bytes.subarray(mypos, bytes.length));
  35177. break;
  35178. case 20:
  35179. // Notation Data
  35180. // We don't know how to handle anything but a text flagged data.
  35181. if (bytes[mypos] === 0x80) {
  35182. // We extract key/value tuple from the byte stream.
  35183. mypos += 4;
  35184. const m = _util2.default.readNumber(bytes.subarray(mypos, mypos + 2));
  35185. mypos += 2;
  35186. const n = _util2.default.readNumber(bytes.subarray(mypos, mypos + 2));
  35187. mypos += 2;
  35188. const name = _util2.default.Uint8Array_to_str(bytes.subarray(mypos, mypos + m));
  35189. const value = _util2.default.Uint8Array_to_str(bytes.subarray(mypos + m, mypos + m + n));
  35190. this.notations.push([name, value]);
  35191. if (critical && _config2.default.known_notations.indexOf(name) === -1) {
  35192. throw new Error("Unknown critical notation: " + name);
  35193. }
  35194. } else {
  35195. _util2.default.print_debug("Unsupported notation flag " + bytes[mypos]);
  35196. }
  35197. break;
  35198. case 21:
  35199. // Preferred Hash Algorithms
  35200. read_array('preferredHashAlgorithms', bytes.subarray(mypos, bytes.length));
  35201. break;
  35202. case 22:
  35203. // Preferred Compression Algorithms
  35204. read_array('preferredCompressionAlgorithms', bytes.subarray(mypos, bytes.length));
  35205. break;
  35206. case 23:
  35207. // Key Server Preferences
  35208. read_array('keyServerPreferences', bytes.subarray(mypos, bytes.length));
  35209. break;
  35210. case 24:
  35211. // Preferred Key Server
  35212. this.preferredKeyServer = _util2.default.Uint8Array_to_str(bytes.subarray(mypos, bytes.length));
  35213. break;
  35214. case 25:
  35215. // Primary User ID
  35216. this.isPrimaryUserID = bytes[mypos++] !== 0;
  35217. break;
  35218. case 26:
  35219. // Policy URI
  35220. this.policyURI = _util2.default.Uint8Array_to_str(bytes.subarray(mypos, bytes.length));
  35221. break;
  35222. case 27:
  35223. // Key Flags
  35224. read_array('keyFlags', bytes.subarray(mypos, bytes.length));
  35225. break;
  35226. case 28:
  35227. // Signer's User ID
  35228. this.signersUserId = _util2.default.Uint8Array_to_str(bytes.subarray(mypos, bytes.length));
  35229. break;
  35230. case 29:
  35231. // Reason for Revocation
  35232. this.reasonForRevocationFlag = bytes[mypos++];
  35233. this.reasonForRevocationString = _util2.default.Uint8Array_to_str(bytes.subarray(mypos, bytes.length));
  35234. break;
  35235. case 30:
  35236. // Features
  35237. read_array('features', bytes.subarray(mypos, bytes.length));
  35238. break;
  35239. case 31:
  35240. {
  35241. // Signature Target
  35242. // (1 octet public-key algorithm, 1 octet hash algorithm, N octets hash)
  35243. this.signatureTargetPublicKeyAlgorithm = bytes[mypos++];
  35244. this.signatureTargetHashAlgorithm = bytes[mypos++];
  35245. const len = _crypto2.default.getHashByteLength(this.signatureTargetHashAlgorithm);
  35246. this.signatureTargetHash = _util2.default.Uint8Array_to_str(bytes.subarray(mypos, mypos + len));
  35247. break;
  35248. }
  35249. case 32:
  35250. // Embedded Signature
  35251. this.embeddedSignature = new Signature();
  35252. this.embeddedSignature.read(bytes.subarray(mypos, bytes.length));
  35253. break;
  35254. case 33:
  35255. // Issuer Fingerprint
  35256. this.issuerKeyVersion = bytes[mypos++];
  35257. this.issuerFingerprint = bytes.subarray(mypos, bytes.length);
  35258. if (this.issuerKeyVersion === 5) {
  35259. this.issuerKeyId.read(this.issuerFingerprint);
  35260. } else {
  35261. this.issuerKeyId.read(this.issuerFingerprint.subarray(-8));
  35262. }
  35263. break;
  35264. case 34:
  35265. // Preferred AEAD Algorithms
  35266. read_array.call(this, 'preferredAeadAlgorithms', bytes.subarray(mypos, bytes.length));
  35267. break;
  35268. default:
  35269. {
  35270. const err = new Error("Unknown signature subpacket type " + type + " @:" + mypos);
  35271. if (critical) {
  35272. throw err;
  35273. } else {
  35274. _util2.default.print_debug(err);
  35275. }
  35276. }
  35277. }
  35278. };
  35279. Signature.prototype.read_sub_packets = function (bytes, trusted = true) {
  35280. // Two-octet scalar octet count for following subpacket data.
  35281. const subpacket_length = _util2.default.readNumber(bytes.subarray(0, 2));
  35282. let i = 2;
  35283. // subpacket data set (zero or more subpackets)
  35284. while (i < 2 + subpacket_length) {
  35285. const len = _packet2.default.readSimpleLength(bytes.subarray(i, bytes.length));
  35286. i += len.offset;
  35287. this.read_sub_packet(bytes.subarray(i, i + len.len), trusted);
  35288. i += len.len;
  35289. }
  35290. return i;
  35291. };
  35292. // Produces data to produce signature on
  35293. Signature.prototype.toSign = function (type, data) {
  35294. const t = _enums2.default.signature;
  35295. switch (type) {
  35296. case t.binary:
  35297. if (data.text !== null) {
  35298. return _util2.default.str_to_Uint8Array(data.getText(true));
  35299. }
  35300. return data.getBytes(true);
  35301. case t.text:
  35302. {
  35303. let text = data.getText(true);
  35304. // normalize EOL to \r\n
  35305. text = _util2.default.canonicalizeEOL(text);
  35306. // encode UTF8
  35307. return _util2.default.encode_utf8(text);
  35308. }
  35309. case t.standalone:
  35310. return new Uint8Array(0);
  35311. case t.cert_generic:
  35312. case t.cert_persona:
  35313. case t.cert_casual:
  35314. case t.cert_positive:
  35315. case t.cert_revocation:
  35316. {
  35317. let packet;
  35318. let tag;
  35319. if (data.userId) {
  35320. tag = 0xB4;
  35321. packet = data.userId;
  35322. } else if (data.userAttribute) {
  35323. tag = 0xD1;
  35324. packet = data.userAttribute;
  35325. } else {
  35326. throw new Error('Either a userId or userAttribute packet needs to be ' + 'supplied for certification.');
  35327. }
  35328. const bytes = packet.write();
  35329. return _util2.default.concat([this.toSign(t.key, data), new Uint8Array([tag]), _util2.default.writeNumber(bytes.length, 4), bytes]);
  35330. }
  35331. case t.subkey_binding:
  35332. case t.subkey_revocation:
  35333. case t.key_binding:
  35334. return _util2.default.concat([this.toSign(t.key, data), this.toSign(t.key, {
  35335. key: data.bind
  35336. })]);
  35337. case t.key:
  35338. if (data.key === undefined) {
  35339. throw new Error('Key packet is required for this signature.');
  35340. }
  35341. return data.key.writeForHash(this.version);
  35342. case t.key_revocation:
  35343. return this.toSign(t.key, data);
  35344. case t.timestamp:
  35345. return new Uint8Array(0);
  35346. case t.third_party:
  35347. throw new Error('Not implemented');
  35348. default:
  35349. throw new Error('Unknown signature type.');
  35350. }
  35351. };
  35352. Signature.prototype.calculateTrailer = function (data, detached) {
  35353. let length = 0;
  35354. return _webStreamTools2.default.transform(_webStreamTools2.default.clone(this.signatureData), value => {
  35355. length += value.length;
  35356. }, () => {
  35357. const arr = [];
  35358. if (this.version === 5 && (this.signatureType === _enums2.default.signature.binary || this.signatureType === _enums2.default.signature.text)) {
  35359. if (detached) {
  35360. arr.push(new Uint8Array(6));
  35361. } else {
  35362. arr.push(data.writeHeader());
  35363. }
  35364. }
  35365. arr.push(new Uint8Array([this.version, 0xFF]));
  35366. if (this.version === 5) {
  35367. arr.push(new Uint8Array(4));
  35368. }
  35369. arr.push(_util2.default.writeNumber(length, 4));
  35370. // For v5, this should really be writeNumber(length, 8) rather than the
  35371. // hardcoded 4 zero bytes above
  35372. return _util2.default.concat(arr);
  35373. });
  35374. };
  35375. Signature.prototype.toHash = function (signatureType, data, detached = false) {
  35376. const bytes = this.toSign(signatureType, data);
  35377. return _util2.default.concat([bytes, this.signatureData, this.calculateTrailer(data, detached)]);
  35378. };
  35379. Signature.prototype.hash = async function (signatureType, data, toHash, detached = false, streaming = true) {
  35380. const hashAlgorithm = _enums2.default.write(_enums2.default.hash, this.hashAlgorithm);
  35381. if (!toHash) toHash = this.toHash(signatureType, data, detached);
  35382. if (!streaming && _util2.default.isStream(toHash)) {
  35383. return _webStreamTools2.default.fromAsync(async () => this.hash(signatureType, data, (await _webStreamTools2.default.readToEnd(toHash)), detached));
  35384. }
  35385. return _crypto2.default.hash.digest(hashAlgorithm, toHash);
  35386. };
  35387. /**
  35388. * verifies the signature packet. Note: not all signature types are implemented
  35389. * @param {module:packet.PublicSubkey|module:packet.PublicKey|
  35390. * module:packet.SecretSubkey|module:packet.SecretKey} key the public key to verify the signature
  35391. * @param {module:enums.signature} signatureType expected signature type
  35392. * @param {String|Object} data data which on the signature applies
  35393. * @param {Boolean} detached (optional) whether to verify a detached signature
  35394. * @returns {Promise<Boolean>} True if message is verified, else false.
  35395. * @async
  35396. */
  35397. Signature.prototype.verify = async function (key, signatureType, data, detached = false, streaming = false) {
  35398. const publicKeyAlgorithm = _enums2.default.write(_enums2.default.publicKey, this.publicKeyAlgorithm);
  35399. const hashAlgorithm = _enums2.default.write(_enums2.default.hash, this.hashAlgorithm);
  35400. if (publicKeyAlgorithm !== _enums2.default.write(_enums2.default.publicKey, key.algorithm)) {
  35401. throw new Error('Public key algorithm used to sign signature does not match issuer key algorithm.');
  35402. }
  35403. let toHash;
  35404. let hash;
  35405. if (this.hashed) {
  35406. hash = this.hashed;
  35407. } else {
  35408. toHash = this.toHash(signatureType, data, detached);
  35409. if (!streaming) toHash = await _webStreamTools2.default.readToEnd(toHash);
  35410. hash = await this.hash(signatureType, data, toHash);
  35411. }
  35412. hash = await _webStreamTools2.default.readToEnd(hash);
  35413. if (this.signedHashValue[0] !== hash[0] || this.signedHashValue[1] !== hash[1]) {
  35414. this.verified = false;
  35415. } else {
  35416. let mpicount = 0;
  35417. // Algorithm-Specific Fields for RSA signatures:
  35418. // - multiprecision number (MPI) of RSA signature value m**d mod n.
  35419. if (publicKeyAlgorithm > 0 && publicKeyAlgorithm < 4) {
  35420. mpicount = 1;
  35421. // Algorithm-Specific Fields for DSA, ECDSA, and EdDSA signatures:
  35422. // - MPI of DSA value r.
  35423. // - MPI of DSA value s.
  35424. } else if (publicKeyAlgorithm === _enums2.default.publicKey.dsa || publicKeyAlgorithm === _enums2.default.publicKey.ecdsa || publicKeyAlgorithm === _enums2.default.publicKey.eddsa) {
  35425. mpicount = 2;
  35426. }
  35427. // EdDSA signature parameters are encoded in little-endian format
  35428. // https://tools.ietf.org/html/rfc8032#section-5.1.2
  35429. const endian = publicKeyAlgorithm === _enums2.default.publicKey.eddsa ? 'le' : 'be';
  35430. const mpi = [];
  35431. let i = 0;
  35432. this.signature = await _webStreamTools2.default.readToEnd(this.signature);
  35433. for (let j = 0; j < mpicount; j++) {
  35434. mpi[j] = new _mpi2.default();
  35435. i += mpi[j].read(this.signature.subarray(i, this.signature.length), endian);
  35436. }
  35437. this.verified = await _crypto2.default.signature.verify(publicKeyAlgorithm, hashAlgorithm, mpi, key.params, toHash, hash);
  35438. }
  35439. return this.verified;
  35440. };
  35441. /**
  35442. * Verifies signature expiration date
  35443. * @param {Date} date (optional) use the given date for verification instead of the current time
  35444. * @returns {Boolean} true if expired
  35445. */
  35446. Signature.prototype.isExpired = function (date = new Date()) {
  35447. const normDate = _util2.default.normalizeDate(date);
  35448. if (normDate !== null) {
  35449. const expirationTime = this.getExpirationTime();
  35450. return !(this.created <= normDate && normDate <= expirationTime);
  35451. }
  35452. return false;
  35453. };
  35454. /**
  35455. * Returns the expiration time of the signature or Infinity if signature does not expire
  35456. * @returns {Date} expiration time
  35457. */
  35458. Signature.prototype.getExpirationTime = function () {
  35459. return !this.signatureNeverExpires ? new Date(this.created.getTime() + this.signatureExpirationTime * 1000) : Infinity;
  35460. };
  35461. /**
  35462. * Fix custom types after cloning
  35463. */
  35464. Signature.prototype.postCloneTypeFix = function () {
  35465. this.issuerKeyId = _keyid2.default.fromClone(this.issuerKeyId);
  35466. };
  35467. exports.default = Signature;
  35468. },{"../config":79,"../crypto":94,"../enums":113,"../type/keyid.js":154,"../type/mpi.js":155,"../util":158,"./packet":135,"web-stream-tools":75}],143:[function(require,module,exports){
  35469. 'use strict';
  35470. Object.defineProperty(exports, "__esModule", {
  35471. value: true
  35472. });
  35473. var _webStreamTools = require('web-stream-tools');
  35474. var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
  35475. var _config = require('../config');
  35476. var _config2 = _interopRequireDefault(_config);
  35477. var _crypto = require('../crypto');
  35478. var _crypto2 = _interopRequireDefault(_crypto);
  35479. var _enums = require('../enums');
  35480. var _enums2 = _interopRequireDefault(_enums);
  35481. var _util = require('../util');
  35482. var _util2 = _interopRequireDefault(_util);
  35483. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  35484. const VERSION = 1; // A one-octet version number of the data packet.
  35485. /**
  35486. * Implementation of the Symmetrically Encrypted Authenticated Encryption with
  35487. * Additional Data (AEAD) Protected Data Packet
  35488. *
  35489. * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}:
  35490. * AEAD Protected Data Packet
  35491. * @memberof module:packet
  35492. * @constructor
  35493. */
  35494. // OpenPGP.js - An OpenPGP implementation in javascript
  35495. // Copyright (C) 2016 Tankred Hase
  35496. //
  35497. // This library is free software; you can redistribute it and/or
  35498. // modify it under the terms of the GNU Lesser General Public
  35499. // License as published by the Free Software Foundation; either
  35500. // version 3.0 of the License, or (at your option) any later version.
  35501. //
  35502. // This library is distributed in the hope that it will be useful,
  35503. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  35504. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  35505. // Lesser General Public License for more details.
  35506. //
  35507. // You should have received a copy of the GNU Lesser General Public
  35508. // License along with this library; if not, write to the Free Software
  35509. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  35510. /**
  35511. * @requires web-stream-tools
  35512. * @requires config
  35513. * @requires crypto
  35514. * @requires enums
  35515. * @requires util
  35516. */
  35517. function SymEncryptedAEADProtected() {
  35518. this.tag = _enums2.default.packet.symEncryptedAEADProtected;
  35519. this.version = VERSION;
  35520. this.cipherAlgo = null;
  35521. this.aeadAlgorithm = 'eax';
  35522. this.aeadAlgo = null;
  35523. this.chunkSizeByte = null;
  35524. this.iv = null;
  35525. this.encrypted = null;
  35526. this.packets = null;
  35527. }
  35528. exports.default = SymEncryptedAEADProtected;
  35529. /**
  35530. * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification)
  35531. * @param {Uint8Array | ReadableStream<Uint8Array>} bytes
  35532. */
  35533. SymEncryptedAEADProtected.prototype.read = async function (bytes) {
  35534. await _webStreamTools2.default.parse(bytes, async reader => {
  35535. if ((await reader.readByte()) !== VERSION) {
  35536. // The only currently defined value is 1.
  35537. throw new Error('Invalid packet version.');
  35538. }
  35539. this.cipherAlgo = await reader.readByte();
  35540. this.aeadAlgo = await reader.readByte();
  35541. this.chunkSizeByte = await reader.readByte();
  35542. const mode = _crypto2.default[_enums2.default.read(_enums2.default.aead, this.aeadAlgo)];
  35543. this.iv = await reader.readBytes(mode.ivLength);
  35544. this.encrypted = reader.remainder();
  35545. });
  35546. };
  35547. /**
  35548. * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification)
  35549. * @returns {Uint8Array | ReadableStream<Uint8Array>} The encrypted payload
  35550. */
  35551. SymEncryptedAEADProtected.prototype.write = function () {
  35552. return _util2.default.concat([new Uint8Array([this.version, this.cipherAlgo, this.aeadAlgo, this.chunkSizeByte]), this.iv, this.encrypted]);
  35553. };
  35554. /**
  35555. * Decrypt the encrypted payload.
  35556. * @param {String} sessionKeyAlgorithm The session key's cipher algorithm e.g. 'aes128'
  35557. * @param {Uint8Array} key The session key used to encrypt the payload
  35558. * @param {Boolean} streaming Whether the top-level function will return a stream
  35559. * @returns {Boolean}
  35560. * @async
  35561. */
  35562. SymEncryptedAEADProtected.prototype.decrypt = async function (sessionKeyAlgorithm, key, streaming) {
  35563. await this.packets.read((await this.crypt('decrypt', key, _webStreamTools2.default.clone(this.encrypted), streaming)), streaming);
  35564. return true;
  35565. };
  35566. /**
  35567. * Encrypt the packet list payload.
  35568. * @param {String} sessionKeyAlgorithm The session key's cipher algorithm e.g. 'aes128'
  35569. * @param {Uint8Array} key The session key used to encrypt the payload
  35570. * @param {Boolean} streaming Whether the top-level function will return a stream
  35571. * @async
  35572. */
  35573. SymEncryptedAEADProtected.prototype.encrypt = async function (sessionKeyAlgorithm, key, streaming) {
  35574. this.cipherAlgo = _enums2.default.write(_enums2.default.symmetric, sessionKeyAlgorithm);
  35575. this.aeadAlgo = _enums2.default.write(_enums2.default.aead, this.aeadAlgorithm);
  35576. const mode = _crypto2.default[_enums2.default.read(_enums2.default.aead, this.aeadAlgo)];
  35577. this.iv = await _crypto2.default.random.getRandomBytes(mode.ivLength); // generate new random IV
  35578. this.chunkSizeByte = _config2.default.aead_chunk_size_byte;
  35579. const data = this.packets.write();
  35580. this.encrypted = await this.crypt('encrypt', key, data, streaming);
  35581. };
  35582. /**
  35583. * En/decrypt the payload.
  35584. * @param {encrypt|decrypt} fn Whether to encrypt or decrypt
  35585. * @param {Uint8Array} key The session key used to en/decrypt the payload
  35586. * @param {Uint8Array | ReadableStream<Uint8Array>} data The data to en/decrypt
  35587. * @param {Boolean} streaming Whether the top-level function will return a stream
  35588. * @returns {Uint8Array | ReadableStream<Uint8Array>}
  35589. * @async
  35590. */
  35591. SymEncryptedAEADProtected.prototype.crypt = async function (fn, key, data, streaming) {
  35592. const cipher = _enums2.default.read(_enums2.default.symmetric, this.cipherAlgo);
  35593. const mode = _crypto2.default[_enums2.default.read(_enums2.default.aead, this.aeadAlgo)];
  35594. const modeInstance = await mode(cipher, key);
  35595. const tagLengthIfDecrypting = fn === 'decrypt' ? mode.tagLength : 0;
  35596. const tagLengthIfEncrypting = fn === 'encrypt' ? mode.tagLength : 0;
  35597. const chunkSize = 2 ** (this.chunkSizeByte + 6) + tagLengthIfDecrypting; // ((uint64_t)1 << (c + 6))
  35598. const adataBuffer = new ArrayBuffer(21);
  35599. const adataArray = new Uint8Array(adataBuffer, 0, 13);
  35600. const adataTagArray = new Uint8Array(adataBuffer);
  35601. const adataView = new DataView(adataBuffer);
  35602. const chunkIndexArray = new Uint8Array(adataBuffer, 5, 8);
  35603. adataArray.set([0xC0 | this.tag, this.version, this.cipherAlgo, this.aeadAlgo, this.chunkSizeByte], 0);
  35604. let chunkIndex = 0;
  35605. let latestPromise = Promise.resolve();
  35606. let cryptedBytes = 0;
  35607. let queuedBytes = 0;
  35608. const iv = this.iv;
  35609. return _webStreamTools2.default.transformPair(data, async (readable, writable) => {
  35610. const reader = _webStreamTools2.default.getReader(readable);
  35611. const buffer = new TransformStream({}, {
  35612. highWaterMark: streaming ? _util2.default.getHardwareConcurrency() * 2 ** (this.chunkSizeByte + 6) : Infinity,
  35613. size: array => array.length
  35614. });
  35615. _webStreamTools2.default.pipe(buffer.readable, writable);
  35616. const writer = _webStreamTools2.default.getWriter(buffer.writable);
  35617. try {
  35618. while (true) {
  35619. let chunk = (await reader.readBytes(chunkSize + tagLengthIfDecrypting)) || new Uint8Array();
  35620. const finalChunk = chunk.subarray(chunk.length - tagLengthIfDecrypting);
  35621. chunk = chunk.subarray(0, chunk.length - tagLengthIfDecrypting);
  35622. let cryptedPromise;
  35623. let done;
  35624. if (!chunkIndex || chunk.length) {
  35625. reader.unshift(finalChunk);
  35626. cryptedPromise = modeInstance[fn](chunk, mode.getNonce(iv, chunkIndexArray), adataArray);
  35627. queuedBytes += chunk.length - tagLengthIfDecrypting + tagLengthIfEncrypting;
  35628. } else {
  35629. // After the last chunk, we either encrypt a final, empty
  35630. // data chunk to get the final authentication tag or
  35631. // validate that final authentication tag.
  35632. adataView.setInt32(13 + 4, cryptedBytes); // Should be setInt64(13, ...)
  35633. cryptedPromise = modeInstance[fn](finalChunk, mode.getNonce(iv, chunkIndexArray), adataTagArray);
  35634. queuedBytes += tagLengthIfEncrypting;
  35635. done = true;
  35636. }
  35637. cryptedBytes += chunk.length - tagLengthIfDecrypting;
  35638. // eslint-disable-next-line no-loop-func
  35639. latestPromise = latestPromise.then(() => cryptedPromise).then(async crypted => {
  35640. await writer.ready;
  35641. await writer.write(crypted);
  35642. queuedBytes -= crypted.length;
  35643. }).catch(err => writer.abort(err));
  35644. if (done || queuedBytes > writer.desiredSize) {
  35645. await latestPromise; // Respect backpressure
  35646. }
  35647. if (!done) {
  35648. adataView.setInt32(5 + 4, ++chunkIndex); // Should be setInt64(5, ...)
  35649. } else {
  35650. await writer.close();
  35651. break;
  35652. }
  35653. }
  35654. } catch (e) {
  35655. await writer.abort(e);
  35656. }
  35657. });
  35658. };
  35659. },{"../config":79,"../crypto":94,"../enums":113,"../util":158,"web-stream-tools":75}],144:[function(require,module,exports){
  35660. 'use strict';
  35661. Object.defineProperty(exports, "__esModule", {
  35662. value: true
  35663. });
  35664. var _webStreamTools = require('web-stream-tools');
  35665. var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
  35666. var _config = require('../config');
  35667. var _config2 = _interopRequireDefault(_config);
  35668. var _crypto = require('../crypto');
  35669. var _crypto2 = _interopRequireDefault(_crypto);
  35670. var _enums = require('../enums');
  35671. var _enums2 = _interopRequireDefault(_enums);
  35672. var _util = require('../util');
  35673. var _util2 = _interopRequireDefault(_util);
  35674. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  35675. const VERSION = 1; // A one-octet version number of the data packet.
  35676. /**
  35677. * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18)
  35678. *
  35679. * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}:
  35680. * The Symmetrically Encrypted Integrity Protected Data packet is
  35681. * a variant of the Symmetrically Encrypted Data packet. It is a new feature
  35682. * created for OpenPGP that addresses the problem of detecting a modification to
  35683. * encrypted data. It is used in combination with a Modification Detection Code
  35684. * packet.
  35685. * @memberof module:packet
  35686. * @constructor
  35687. */
  35688. // GPG4Browsers - An OpenPGP implementation in javascript
  35689. // Copyright (C) 2011 Recurity Labs GmbH
  35690. //
  35691. // This library is free software; you can redistribute it and/or
  35692. // modify it under the terms of the GNU Lesser General Public
  35693. // License as published by the Free Software Foundation; either
  35694. // version 3.0 of the License, or (at your option) any later version.
  35695. //
  35696. // This library is distributed in the hope that it will be useful,
  35697. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  35698. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  35699. // Lesser General Public License for more details.
  35700. //
  35701. // You should have received a copy of the GNU Lesser General Public
  35702. // License along with this library; if not, write to the Free Software
  35703. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  35704. /**
  35705. * @requires asmcrypto.js
  35706. * @requires web-stream-tools
  35707. * @requires config
  35708. * @requires crypto
  35709. * @requires enums
  35710. * @requires util
  35711. */
  35712. function SymEncryptedIntegrityProtected() {
  35713. this.tag = _enums2.default.packet.symEncryptedIntegrityProtected;
  35714. this.version = VERSION;
  35715. /** The encrypted payload. */
  35716. this.encrypted = null; // string
  35717. /**
  35718. * If after decrypting the packet this is set to true,
  35719. * a modification has been detected and thus the contents
  35720. * should be discarded.
  35721. * @type {Boolean}
  35722. */
  35723. this.modification = false;
  35724. this.packets = null;
  35725. }
  35726. SymEncryptedIntegrityProtected.prototype.read = async function (bytes) {
  35727. await _webStreamTools2.default.parse(bytes, async reader => {
  35728. // - A one-octet version number. The only currently defined value is 1.
  35729. if ((await reader.readByte()) !== VERSION) {
  35730. throw new Error('Invalid packet version.');
  35731. }
  35732. // - Encrypted data, the output of the selected symmetric-key cipher
  35733. // operating in Cipher Feedback mode with shift amount equal to the
  35734. // block size of the cipher (CFB-n where n is the block size).
  35735. this.encrypted = reader.remainder();
  35736. });
  35737. };
  35738. SymEncryptedIntegrityProtected.prototype.write = function () {
  35739. return _util2.default.concat([new Uint8Array([VERSION]), this.encrypted]);
  35740. };
  35741. /**
  35742. * Encrypt the payload in the packet.
  35743. * @param {String} sessionKeyAlgorithm The selected symmetric encryption algorithm to be used e.g. 'aes128'
  35744. * @param {Uint8Array} key The key of cipher blocksize length to be used
  35745. * @param {Boolean} streaming Whether to set this.encrypted to a stream
  35746. * @returns {Promise<Boolean>}
  35747. * @async
  35748. */
  35749. SymEncryptedIntegrityProtected.prototype.encrypt = async function (sessionKeyAlgorithm, key, streaming) {
  35750. let bytes = this.packets.write();
  35751. if (!streaming) bytes = await _webStreamTools2.default.readToEnd(bytes);
  35752. const prefix = await _crypto2.default.getPrefixRandom(sessionKeyAlgorithm);
  35753. const mdc = new Uint8Array([0xD3, 0x14]); // modification detection code packet
  35754. const tohash = _util2.default.concat([prefix, bytes, mdc]);
  35755. const hash = await _crypto2.default.hash.sha1(_webStreamTools2.default.passiveClone(tohash));
  35756. const plaintext = _util2.default.concat([tohash, hash]);
  35757. this.encrypted = await _crypto2.default.cfb.encrypt(sessionKeyAlgorithm, key, plaintext, new Uint8Array(_crypto2.default.cipher[sessionKeyAlgorithm].blockSize));
  35758. return true;
  35759. };
  35760. /**
  35761. * Decrypts the encrypted data contained in the packet.
  35762. * @param {String} sessionKeyAlgorithm The selected symmetric encryption algorithm to be used e.g. 'aes128'
  35763. * @param {Uint8Array} key The key of cipher blocksize length to be used
  35764. * @param {Boolean} streaming Whether to read this.encrypted as a stream
  35765. * @returns {Promise<Boolean>}
  35766. * @async
  35767. */
  35768. SymEncryptedIntegrityProtected.prototype.decrypt = async function (sessionKeyAlgorithm, key, streaming) {
  35769. let encrypted = _webStreamTools2.default.clone(this.encrypted);
  35770. if (!streaming) encrypted = await _webStreamTools2.default.readToEnd(encrypted);
  35771. const decrypted = await _crypto2.default.cfb.decrypt(sessionKeyAlgorithm, key, encrypted, new Uint8Array(_crypto2.default.cipher[sessionKeyAlgorithm].blockSize));
  35772. // there must be a modification detection code packet as the
  35773. // last packet and everything gets hashed except the hash itself
  35774. const realHash = _webStreamTools2.default.slice(_webStreamTools2.default.passiveClone(decrypted), -20);
  35775. const tohash = _webStreamTools2.default.slice(decrypted, 0, -20);
  35776. const verifyHash = Promise.all([_webStreamTools2.default.readToEnd((await _crypto2.default.hash.sha1(_webStreamTools2.default.passiveClone(tohash)))), _webStreamTools2.default.readToEnd(realHash)]).then(([hash, mdc]) => {
  35777. if (!_util2.default.equalsUint8Array(hash, mdc)) {
  35778. throw new Error('Modification detected.');
  35779. }
  35780. return new Uint8Array();
  35781. });
  35782. const bytes = _webStreamTools2.default.slice(tohash, _crypto2.default.cipher[sessionKeyAlgorithm].blockSize + 2); // Remove random prefix
  35783. let packetbytes = _webStreamTools2.default.slice(bytes, 0, -2); // Remove MDC packet
  35784. packetbytes = _webStreamTools2.default.concat([packetbytes, _webStreamTools2.default.fromAsync(() => verifyHash)]);
  35785. if (!_util2.default.isStream(encrypted) || !_config2.default.allow_unauthenticated_stream) {
  35786. packetbytes = await _webStreamTools2.default.readToEnd(packetbytes);
  35787. }
  35788. await this.packets.read(packetbytes, streaming);
  35789. return true;
  35790. };
  35791. exports.default = SymEncryptedIntegrityProtected;
  35792. },{"../config":79,"../crypto":94,"../enums":113,"../util":158,"web-stream-tools":75}],145:[function(require,module,exports){
  35793. 'use strict';
  35794. Object.defineProperty(exports, "__esModule", {
  35795. value: true
  35796. });
  35797. var _s2k = require('../type/s2k');
  35798. var _s2k2 = _interopRequireDefault(_s2k);
  35799. var _config = require('../config');
  35800. var _config2 = _interopRequireDefault(_config);
  35801. var _crypto = require('../crypto');
  35802. var _crypto2 = _interopRequireDefault(_crypto);
  35803. var _enums = require('../enums');
  35804. var _enums2 = _interopRequireDefault(_enums);
  35805. var _util = require('../util');
  35806. var _util2 = _interopRequireDefault(_util);
  35807. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  35808. /**
  35809. * Public-Key Encrypted Session Key Packets (Tag 1)
  35810. *
  35811. * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}:
  35812. * A Public-Key Encrypted Session Key packet holds the session key
  35813. * used to encrypt a message. Zero or more Public-Key Encrypted Session Key
  35814. * packets and/or Symmetric-Key Encrypted Session Key packets may precede a
  35815. * Symmetrically Encrypted Data Packet, which holds an encrypted message. The
  35816. * message is encrypted with the session key, and the session key is itself
  35817. * encrypted and stored in the Encrypted Session Key packet(s). The
  35818. * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted
  35819. * Session Key packet for each OpenPGP key to which the message is encrypted.
  35820. * The recipient of the message finds a session key that is encrypted to their
  35821. * public key, decrypts the session key, and then uses the session key to
  35822. * decrypt the message.
  35823. * @memberof module:packet
  35824. * @constructor
  35825. */
  35826. function SymEncryptedSessionKey() {
  35827. this.tag = _enums2.default.packet.symEncryptedSessionKey;
  35828. this.version = _config2.default.aead_protect ? 5 : 4;
  35829. this.sessionKey = null;
  35830. this.sessionKeyEncryptionAlgorithm = null;
  35831. this.sessionKeyAlgorithm = 'aes256';
  35832. this.aeadAlgorithm = _enums2.default.read(_enums2.default.aead, _config2.default.aead_mode);
  35833. this.encrypted = null;
  35834. this.s2k = null;
  35835. this.iv = null;
  35836. }
  35837. /**
  35838. * Parsing function for a symmetric encrypted session key packet (tag 3).
  35839. *
  35840. * @param {Uint8Array} input Payload of a tag 1 packet
  35841. * @param {Integer} position Position to start reading from the input string
  35842. * @param {Integer} len
  35843. * Length of the packet or the remaining length of
  35844. * input at position
  35845. * @returns {module:packet.SymEncryptedSessionKey} Object representation
  35846. */
  35847. // GPG4Browsers - An OpenPGP implementation in javascript
  35848. // Copyright (C) 2011 Recurity Labs GmbH
  35849. //
  35850. // This library is free software; you can redistribute it and/or
  35851. // modify it under the terms of the GNU Lesser General Public
  35852. // License as published by the Free Software Foundation; either
  35853. // version 3.0 of the License, or (at your option) any later version.
  35854. //
  35855. // This library is distributed in the hope that it will be useful,
  35856. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  35857. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  35858. // Lesser General Public License for more details.
  35859. //
  35860. // You should have received a copy of the GNU Lesser General Public
  35861. // License along with this library; if not, write to the Free Software
  35862. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  35863. /**
  35864. * @requires type/s2k
  35865. * @requires config
  35866. * @requires crypto
  35867. * @requires enums
  35868. * @requires util
  35869. */
  35870. SymEncryptedSessionKey.prototype.read = function (bytes) {
  35871. let offset = 0;
  35872. // A one-octet version number. The only currently defined version is 4.
  35873. this.version = bytes[offset++];
  35874. // A one-octet number describing the symmetric algorithm used.
  35875. const algo = _enums2.default.read(_enums2.default.symmetric, bytes[offset++]);
  35876. if (this.version === 5) {
  35877. // A one-octet AEAD algorithm.
  35878. this.aeadAlgorithm = _enums2.default.read(_enums2.default.aead, bytes[offset++]);
  35879. }
  35880. // A string-to-key (S2K) specifier, length as defined above.
  35881. this.s2k = new _s2k2.default();
  35882. offset += this.s2k.read(bytes.subarray(offset, bytes.length));
  35883. if (this.version === 5) {
  35884. const mode = _crypto2.default[this.aeadAlgorithm];
  35885. // A starting initialization vector of size specified by the AEAD
  35886. // algorithm.
  35887. this.iv = bytes.subarray(offset, offset += mode.ivLength);
  35888. }
  35889. // The encrypted session key itself, which is decrypted with the
  35890. // string-to-key object. This is optional in version 4.
  35891. if (this.version === 5 || offset < bytes.length) {
  35892. this.encrypted = bytes.subarray(offset, bytes.length);
  35893. this.sessionKeyEncryptionAlgorithm = algo;
  35894. } else {
  35895. this.sessionKeyAlgorithm = algo;
  35896. }
  35897. };
  35898. SymEncryptedSessionKey.prototype.write = function () {
  35899. const algo = this.encrypted === null ? this.sessionKeyAlgorithm : this.sessionKeyEncryptionAlgorithm;
  35900. let bytes;
  35901. if (this.version === 5) {
  35902. bytes = _util2.default.concatUint8Array([new Uint8Array([this.version, _enums2.default.write(_enums2.default.symmetric, algo), _enums2.default.write(_enums2.default.aead, this.aeadAlgorithm)]), this.s2k.write(), this.iv, this.encrypted]);
  35903. } else {
  35904. bytes = _util2.default.concatUint8Array([new Uint8Array([this.version, _enums2.default.write(_enums2.default.symmetric, algo)]), this.s2k.write()]);
  35905. if (this.encrypted !== null) {
  35906. bytes = _util2.default.concatUint8Array([bytes, this.encrypted]);
  35907. }
  35908. }
  35909. return bytes;
  35910. };
  35911. /**
  35912. * Decrypts the session key
  35913. * @param {String} passphrase The passphrase in string form
  35914. * @returns {Promise<Boolean>}
  35915. * @async
  35916. */
  35917. SymEncryptedSessionKey.prototype.decrypt = async function (passphrase) {
  35918. const algo = this.sessionKeyEncryptionAlgorithm !== null ? this.sessionKeyEncryptionAlgorithm : this.sessionKeyAlgorithm;
  35919. const length = _crypto2.default.cipher[algo].keySize;
  35920. const key = await this.s2k.produce_key(passphrase, length);
  35921. if (this.version === 5) {
  35922. const mode = _crypto2.default[this.aeadAlgorithm];
  35923. const adata = new Uint8Array([0xC0 | this.tag, this.version, _enums2.default.write(_enums2.default.symmetric, this.sessionKeyEncryptionAlgorithm), _enums2.default.write(_enums2.default.aead, this.aeadAlgorithm)]);
  35924. const modeInstance = await mode(algo, key);
  35925. this.sessionKey = await modeInstance.decrypt(this.encrypted, this.iv, adata);
  35926. } else if (this.encrypted !== null) {
  35927. const decrypted = await _crypto2.default.cfb.decrypt(algo, key, this.encrypted, new Uint8Array(_crypto2.default.cipher[algo].blockSize));
  35928. this.sessionKeyAlgorithm = _enums2.default.read(_enums2.default.symmetric, decrypted[0]);
  35929. this.sessionKey = decrypted.subarray(1, decrypted.length);
  35930. } else {
  35931. this.sessionKey = key;
  35932. }
  35933. return true;
  35934. };
  35935. /**
  35936. * Encrypts the session key
  35937. * @param {String} passphrase The passphrase in string form
  35938. * @returns {Promise<Boolean>}
  35939. * @async
  35940. */
  35941. SymEncryptedSessionKey.prototype.encrypt = async function (passphrase) {
  35942. const algo = this.sessionKeyEncryptionAlgorithm !== null ? this.sessionKeyEncryptionAlgorithm : this.sessionKeyAlgorithm;
  35943. this.sessionKeyEncryptionAlgorithm = algo;
  35944. this.s2k = new _s2k2.default();
  35945. this.s2k.salt = await _crypto2.default.random.getRandomBytes(8);
  35946. const length = _crypto2.default.cipher[algo].keySize;
  35947. const key = await this.s2k.produce_key(passphrase, length);
  35948. if (this.sessionKey === null) {
  35949. this.sessionKey = await _crypto2.default.generateSessionKey(this.sessionKeyAlgorithm);
  35950. }
  35951. if (this.version === 5) {
  35952. const mode = _crypto2.default[this.aeadAlgorithm];
  35953. this.iv = await _crypto2.default.random.getRandomBytes(mode.ivLength); // generate new random IV
  35954. const adata = new Uint8Array([0xC0 | this.tag, this.version, _enums2.default.write(_enums2.default.symmetric, this.sessionKeyEncryptionAlgorithm), _enums2.default.write(_enums2.default.aead, this.aeadAlgorithm)]);
  35955. const modeInstance = await mode(algo, key);
  35956. this.encrypted = await modeInstance.encrypt(this.sessionKey, this.iv, adata);
  35957. } else {
  35958. const algo_enum = new Uint8Array([_enums2.default.write(_enums2.default.symmetric, this.sessionKeyAlgorithm)]);
  35959. const private_key = _util2.default.concatUint8Array([algo_enum, this.sessionKey]);
  35960. this.encrypted = await _crypto2.default.cfb.encrypt(algo, key, private_key, new Uint8Array(_crypto2.default.cipher[algo].blockSize));
  35961. }
  35962. return true;
  35963. };
  35964. /**
  35965. * Fix custom types after cloning
  35966. */
  35967. SymEncryptedSessionKey.prototype.postCloneTypeFix = function () {
  35968. this.s2k = _s2k2.default.fromClone(this.s2k);
  35969. };
  35970. exports.default = SymEncryptedSessionKey;
  35971. },{"../config":79,"../crypto":94,"../enums":113,"../type/s2k":157,"../util":158}],146:[function(require,module,exports){
  35972. 'use strict';
  35973. Object.defineProperty(exports, "__esModule", {
  35974. value: true
  35975. });
  35976. var _webStreamTools = require('web-stream-tools');
  35977. var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
  35978. var _config = require('../config');
  35979. var _config2 = _interopRequireDefault(_config);
  35980. var _crypto = require('../crypto');
  35981. var _crypto2 = _interopRequireDefault(_crypto);
  35982. var _enums = require('../enums');
  35983. var _enums2 = _interopRequireDefault(_enums);
  35984. var _util = require('../util');
  35985. var _util2 = _interopRequireDefault(_util);
  35986. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  35987. /**
  35988. * Implementation of the Symmetrically Encrypted Data Packet (Tag 9)
  35989. *
  35990. * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}:
  35991. * The Symmetrically Encrypted Data packet contains data encrypted with a
  35992. * symmetric-key algorithm. When it has been decrypted, it contains other
  35993. * packets (usually a literal data packet or compressed data packet, but in
  35994. * theory other Symmetrically Encrypted Data packets or sequences of packets
  35995. * that form whole OpenPGP messages).
  35996. * @memberof module:packet
  35997. * @constructor
  35998. */
  35999. function SymmetricallyEncrypted() {
  36000. /**
  36001. * Packet type
  36002. * @type {module:enums.packet}
  36003. */
  36004. this.tag = _enums2.default.packet.symmetricallyEncrypted;
  36005. /**
  36006. * Encrypted secret-key data
  36007. */
  36008. this.encrypted = null;
  36009. /**
  36010. * Decrypted packets contained within.
  36011. * @type {module:packet.List}
  36012. */
  36013. this.packets = null;
  36014. /**
  36015. * When true, decrypt fails if message is not integrity protected
  36016. * @see module:config.ignore_mdc_error
  36017. */
  36018. this.ignore_mdc_error = _config2.default.ignore_mdc_error;
  36019. } // GPG4Browsers - An OpenPGP implementation in javascript
  36020. // Copyright (C) 2011 Recurity Labs GmbH
  36021. //
  36022. // This library is free software; you can redistribute it and/or
  36023. // modify it under the terms of the GNU Lesser General Public
  36024. // License as published by the Free Software Foundation; either
  36025. // version 3.0 of the License, or (at your option) any later version.
  36026. //
  36027. // This library is distributed in the hope that it will be useful,
  36028. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  36029. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  36030. // Lesser General Public License for more details.
  36031. //
  36032. // You should have received a copy of the GNU Lesser General Public
  36033. // License along with this library; if not, write to the Free Software
  36034. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  36035. /**
  36036. * @requires web-stream-tools
  36037. * @requires config
  36038. * @requires crypto
  36039. * @requires enums
  36040. * @requires util
  36041. */
  36042. SymmetricallyEncrypted.prototype.read = function (bytes) {
  36043. this.encrypted = bytes;
  36044. };
  36045. SymmetricallyEncrypted.prototype.write = function () {
  36046. return this.encrypted;
  36047. };
  36048. /**
  36049. * Decrypt the symmetrically-encrypted packet data
  36050. * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
  36051. * @param {module:enums.symmetric} sessionKeyAlgorithm Symmetric key algorithm to use
  36052. * @param {Uint8Array} key The key of cipher blocksize length to be used
  36053. * @returns {Promise<Boolean>}
  36054. * @async
  36055. */
  36056. SymmetricallyEncrypted.prototype.decrypt = async function (sessionKeyAlgorithm, key) {
  36057. // If MDC errors are not being ignored, all missing MDC packets in symmetrically encrypted data should throw an error
  36058. if (!this.ignore_mdc_error) {
  36059. throw new Error('Decryption failed due to missing MDC.');
  36060. }
  36061. this.encrypted = await _webStreamTools2.default.readToEnd(this.encrypted);
  36062. const decrypted = await _crypto2.default.cfb.decrypt(sessionKeyAlgorithm, key, this.encrypted.subarray(_crypto2.default.cipher[sessionKeyAlgorithm].blockSize + 2), this.encrypted.subarray(2, _crypto2.default.cipher[sessionKeyAlgorithm].blockSize + 2));
  36063. await this.packets.read(decrypted);
  36064. return true;
  36065. };
  36066. /**
  36067. * Encrypt the symmetrically-encrypted packet data
  36068. * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms.
  36069. * @param {module:enums.symmetric} sessionKeyAlgorithm Symmetric key algorithm to use
  36070. * @param {Uint8Array} key The key of cipher blocksize length to be used
  36071. * @returns {Promise<Boolean>}
  36072. * @async
  36073. */
  36074. SymmetricallyEncrypted.prototype.encrypt = async function (algo, key) {
  36075. const data = this.packets.write();
  36076. const prefix = await _crypto2.default.getPrefixRandom(algo);
  36077. const FRE = await _crypto2.default.cfb.encrypt(algo, key, prefix, new Uint8Array(_crypto2.default.cipher[algo].blockSize));
  36078. const ciphertext = await _crypto2.default.cfb.encrypt(algo, key, data, FRE.subarray(2));
  36079. this.encrypted = _util2.default.concat([FRE, ciphertext]);
  36080. return true;
  36081. };
  36082. exports.default = SymmetricallyEncrypted;
  36083. },{"../config":79,"../crypto":94,"../enums":113,"../util":158,"web-stream-tools":75}],147:[function(require,module,exports){
  36084. 'use strict';
  36085. Object.defineProperty(exports, "__esModule", {
  36086. value: true
  36087. });
  36088. var _enums = require('../enums');
  36089. var _enums2 = _interopRequireDefault(_enums);
  36090. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  36091. /**
  36092. * Implementation of the Trust Packet (Tag 12)
  36093. *
  36094. * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}:
  36095. * The Trust packet is used only within keyrings and is not normally
  36096. * exported. Trust packets contain data that record the user's
  36097. * specifications of which key holders are trustworthy introducers,
  36098. * along with other information that implementing software uses for
  36099. * trust information. The format of Trust packets is defined by a given
  36100. * implementation.
  36101. *
  36102. * Trust packets SHOULD NOT be emitted to output streams that are
  36103. * transferred to other users, and they SHOULD be ignored on any input
  36104. * other than local keyring files.
  36105. * @memberof module:packet
  36106. * @constructor
  36107. */
  36108. function Trust() {
  36109. this.tag = _enums2.default.packet.trust;
  36110. }
  36111. /**
  36112. * Parsing function for a trust packet (tag 12).
  36113. * Currently not implemented as we ignore trust packets
  36114. * @param {String} byptes payload of a tag 12 packet
  36115. */
  36116. /**
  36117. * @requires enums
  36118. */
  36119. Trust.prototype.read = function () {}; // TODO
  36120. exports.default = Trust;
  36121. },{"../enums":113}],148:[function(require,module,exports){
  36122. 'use strict';
  36123. Object.defineProperty(exports, "__esModule", {
  36124. value: true
  36125. });
  36126. var _packet = require('./packet');
  36127. var _packet2 = _interopRequireDefault(_packet);
  36128. var _enums = require('../enums');
  36129. var _enums2 = _interopRequireDefault(_enums);
  36130. var _util = require('../util');
  36131. var _util2 = _interopRequireDefault(_util);
  36132. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  36133. /**
  36134. * Implementation of the User Attribute Packet (Tag 17)
  36135. *
  36136. * The User Attribute packet is a variation of the User ID packet. It
  36137. * is capable of storing more types of data than the User ID packet,
  36138. * which is limited to text. Like the User ID packet, a User Attribute
  36139. * packet may be certified by the key owner ("self-signed") or any other
  36140. * key owner who cares to certify it. Except as noted, a User Attribute
  36141. * packet may be used anywhere that a User ID packet may be used.
  36142. *
  36143. * While User Attribute packets are not a required part of the OpenPGP
  36144. * standard, implementations SHOULD provide at least enough
  36145. * compatibility to properly handle a certification signature on the
  36146. * User Attribute packet. A simple way to do this is by treating the
  36147. * User Attribute packet as a User ID packet with opaque contents, but
  36148. * an implementation may use any method desired.
  36149. * @memberof module:packet
  36150. * @constructor
  36151. */
  36152. function UserAttribute() {
  36153. this.tag = _enums2.default.packet.userAttribute;
  36154. this.attributes = [];
  36155. }
  36156. /**
  36157. * parsing function for a user attribute packet (tag 17).
  36158. * @param {Uint8Array} input payload of a tag 17 packet
  36159. */
  36160. // GPG4Browsers - An OpenPGP implementation in javascript
  36161. // Copyright (C) 2011 Recurity Labs GmbH
  36162. //
  36163. // This library is free software; you can redistribute it and/or
  36164. // modify it under the terms of the GNU Lesser General Public
  36165. // License as published by the Free Software Foundation; either
  36166. // version 3.0 of the License, or (at your option) any later version.
  36167. //
  36168. // This library is distributed in the hope that it will be useful,
  36169. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  36170. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  36171. // Lesser General Public License for more details.
  36172. //
  36173. // You should have received a copy of the GNU Lesser General Public
  36174. // License along with this library; if not, write to the Free Software
  36175. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  36176. /**
  36177. * @requires packet
  36178. * @requires enums
  36179. * @requires util
  36180. */
  36181. UserAttribute.prototype.read = function (bytes) {
  36182. let i = 0;
  36183. while (i < bytes.length) {
  36184. const len = _packet2.default.readSimpleLength(bytes.subarray(i, bytes.length));
  36185. i += len.offset;
  36186. this.attributes.push(_util2.default.Uint8Array_to_str(bytes.subarray(i, i + len.len)));
  36187. i += len.len;
  36188. }
  36189. };
  36190. /**
  36191. * Creates a binary representation of the user attribute packet
  36192. * @returns {Uint8Array} string representation
  36193. */
  36194. UserAttribute.prototype.write = function () {
  36195. const arr = [];
  36196. for (let i = 0; i < this.attributes.length; i++) {
  36197. arr.push(_packet2.default.writeSimpleLength(this.attributes[i].length));
  36198. arr.push(_util2.default.str_to_Uint8Array(this.attributes[i]));
  36199. }
  36200. return _util2.default.concatUint8Array(arr);
  36201. };
  36202. /**
  36203. * Compare for equality
  36204. * @param {module:packet.UserAttribute} usrAttr
  36205. * @returns {Boolean} true if equal
  36206. */
  36207. UserAttribute.prototype.equals = function (usrAttr) {
  36208. if (!usrAttr || !(usrAttr instanceof UserAttribute)) {
  36209. return false;
  36210. }
  36211. return this.attributes.every(function (attr, index) {
  36212. return attr === usrAttr.attributes[index];
  36213. });
  36214. };
  36215. exports.default = UserAttribute;
  36216. },{"../enums":113,"../util":158,"./packet":135}],149:[function(require,module,exports){
  36217. 'use strict';
  36218. Object.defineProperty(exports, "__esModule", {
  36219. value: true
  36220. });
  36221. var _enums = require('../enums');
  36222. var _enums2 = _interopRequireDefault(_enums);
  36223. var _util = require('../util');
  36224. var _util2 = _interopRequireDefault(_util);
  36225. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  36226. /**
  36227. * Implementation of the User ID Packet (Tag 13)
  36228. *
  36229. * A User ID packet consists of UTF-8 text that is intended to represent
  36230. * the name and email address of the key holder. By convention, it
  36231. * includes an RFC 2822 [RFC2822] mail name-addr, but there are no
  36232. * restrictions on its content. The packet length in the header
  36233. * specifies the length of the User ID.
  36234. * @memberof module:packet
  36235. * @constructor
  36236. */
  36237. // GPG4Browsers - An OpenPGP implementation in javascript
  36238. // Copyright (C) 2011 Recurity Labs GmbH
  36239. //
  36240. // This library is free software; you can redistribute it and/or
  36241. // modify it under the terms of the GNU Lesser General Public
  36242. // License as published by the Free Software Foundation; either
  36243. // version 3.0 of the License, or (at your option) any later version.
  36244. //
  36245. // This library is distributed in the hope that it will be useful,
  36246. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  36247. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  36248. // Lesser General Public License for more details.
  36249. //
  36250. // You should have received a copy of the GNU Lesser General Public
  36251. // License along with this library; if not, write to the Free Software
  36252. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  36253. /**
  36254. * @requires enums
  36255. * @requires util
  36256. */
  36257. function Userid() {
  36258. this.tag = _enums2.default.packet.userid;
  36259. /** A string containing the user id. Usually in the form
  36260. * John Doe <john@example.com>
  36261. * @type {String}
  36262. */
  36263. this.userid = '';
  36264. this.name = '';
  36265. this.email = '';
  36266. this.comment = '';
  36267. }
  36268. /**
  36269. * Parsing function for a user id packet (tag 13).
  36270. * @param {Uint8Array} input payload of a tag 13 packet
  36271. */
  36272. Userid.prototype.read = function (bytes) {
  36273. this.parse(_util2.default.decode_utf8(bytes));
  36274. };
  36275. /**
  36276. * Parse userid string, e.g. 'John Doe <john@example.com>'
  36277. */
  36278. Userid.prototype.parse = function (userid) {
  36279. try {
  36280. Object.assign(this, _util2.default.parseUserId(userid));
  36281. } catch (e) {}
  36282. this.userid = userid;
  36283. };
  36284. /**
  36285. * Creates a binary representation of the user id packet
  36286. * @returns {Uint8Array} binary representation
  36287. */
  36288. Userid.prototype.write = function () {
  36289. return _util2.default.encode_utf8(this.userid);
  36290. };
  36291. /**
  36292. * Set userid string from object, e.g. { name:'Phil Zimmermann', email:'phil@openpgp.org' }
  36293. */
  36294. Userid.prototype.format = function (userid) {
  36295. if (_util2.default.isString(userid)) {
  36296. userid = _util2.default.parseUserId(userid);
  36297. }
  36298. Object.assign(this, userid);
  36299. this.userid = _util2.default.formatUserId(userid);
  36300. };
  36301. exports.default = Userid;
  36302. },{"../enums":113,"../util":158}],150:[function(require,module,exports){
  36303. (function (global){
  36304. 'use strict';
  36305. var _util = require('./util');
  36306. var _util2 = _interopRequireDefault(_util);
  36307. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  36308. if (typeof window !== 'undefined') {
  36309. /********************************************************************
  36310. * NOTE: This list is duplicated in Gruntfile.js, *
  36311. * so that these polyfills are only included in the compat bundle. *
  36312. ********************************************************************/
  36313. try {
  36314. if (typeof window.fetch === 'undefined') {
  36315. require('whatwg-fetch');
  36316. }
  36317. if (typeof Array.prototype.fill === 'undefined') {
  36318. require('core-js/fn/array/fill');
  36319. }
  36320. if (typeof Array.prototype.find === 'undefined') {
  36321. require('core-js/fn/array/find');
  36322. }
  36323. if (typeof Array.prototype.includes === 'undefined') {
  36324. require('core-js/fn/array/includes');
  36325. }
  36326. if (typeof Array.from === 'undefined') {
  36327. require('core-js/fn/array/from');
  36328. }
  36329. // No if-statement on Promise because of IE11. Otherwise Promise is undefined in the service worker.
  36330. require('core-js/fn/promise');
  36331. if (typeof Uint8Array.from === 'undefined') {
  36332. require('core-js/fn/typed/uint8-array');
  36333. }
  36334. if (typeof String.prototype.repeat === 'undefined') {
  36335. require('core-js/fn/string/repeat');
  36336. }
  36337. if (typeof Symbol === 'undefined') {
  36338. require('core-js/fn/symbol');
  36339. }
  36340. if (typeof Object.assign === 'undefined') {
  36341. require('core-js/fn/object/assign');
  36342. }
  36343. } catch (e) {}
  36344. } /**
  36345. * @fileoverview Old browser polyfills
  36346. * All are listed as dev dependencies because Node does not need them
  36347. * and for browser babel will take care of it
  36348. * @requires util
  36349. * @module polyfills
  36350. */
  36351. if (typeof TransformStream === 'undefined') {
  36352. require('@mattiasbuelens/web-streams-polyfill/es6');
  36353. }
  36354. if (typeof TextEncoder === 'undefined') {
  36355. const nodeUtil = _util2.default.nodeRequire('util') || {};
  36356. global.TextEncoder = nodeUtil.TextEncoder;
  36357. global.TextDecoder = nodeUtil.TextDecoder;
  36358. }
  36359. if (typeof TextEncoder === 'undefined') {
  36360. const textEncoding = require('text-encoding-utf-8');
  36361. global.TextEncoder = textEncoding.TextEncoder;
  36362. global.TextDecoder = textEncoding.TextDecoder;
  36363. }
  36364. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  36365. },{"./util":158,"@mattiasbuelens/web-streams-polyfill/es6":1,"core-js/fn/array/fill":"core-js/fn/array/fill","core-js/fn/array/find":"core-js/fn/array/find","core-js/fn/array/from":"core-js/fn/array/from","core-js/fn/array/includes":"core-js/fn/array/includes","core-js/fn/object/assign":"core-js/fn/object/assign","core-js/fn/promise":"core-js/fn/promise","core-js/fn/string/repeat":"core-js/fn/string/repeat","core-js/fn/symbol":"core-js/fn/symbol","core-js/fn/typed/uint8-array":"core-js/fn/typed/uint8-array","text-encoding-utf-8":71,"whatwg-fetch":"whatwg-fetch"}],151:[function(require,module,exports){
  36366. 'use strict';
  36367. Object.defineProperty(exports, "__esModule", {
  36368. value: true
  36369. });
  36370. exports.Signature = Signature;
  36371. exports.readArmored = readArmored;
  36372. exports.read = read;
  36373. var _armor = require('./encoding/armor');
  36374. var _armor2 = _interopRequireDefault(_armor);
  36375. var _packet = require('./packet');
  36376. var _packet2 = _interopRequireDefault(_packet);
  36377. var _enums = require('./enums');
  36378. var _enums2 = _interopRequireDefault(_enums);
  36379. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  36380. /**
  36381. * @class
  36382. * @classdesc Class that represents an OpenPGP signature.
  36383. * @param {module:packet.List} packetlist The signature packets
  36384. */
  36385. function Signature(packetlist) {
  36386. if (!(this instanceof Signature)) {
  36387. return new Signature(packetlist);
  36388. }
  36389. this.packets = packetlist || new _packet2.default.List();
  36390. }
  36391. /**
  36392. * Returns ASCII armored text of signature
  36393. * @returns {ReadableStream<String>} ASCII armor
  36394. */
  36395. // GPG4Browsers - An OpenPGP implementation in javascript
  36396. // Copyright (C) 2011 Recurity Labs GmbH
  36397. //
  36398. // This library is free software; you can redistribute it and/or
  36399. // modify it under the terms of the GNU Lesser General Public
  36400. // License as published by the Free Software Foundation; either
  36401. // version 3.0 of the License, or (at your option) any later version.
  36402. //
  36403. // This library is distributed in the hope that it will be useful,
  36404. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  36405. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  36406. // Lesser General Public License for more details.
  36407. //
  36408. // You should have received a copy of the GNU Lesser General Public
  36409. // License along with this library; if not, write to the Free Software
  36410. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  36411. /**
  36412. * @requires encoding/armor
  36413. * @requires packet
  36414. * @requires enums
  36415. * @module signature
  36416. */
  36417. Signature.prototype.armor = function () {
  36418. return _armor2.default.encode(_enums2.default.armor.signature, this.packets.write());
  36419. };
  36420. /**
  36421. * reads an OpenPGP armored signature and returns a signature object
  36422. * @param {String | ReadableStream<String>} armoredText text to be parsed
  36423. * @returns {Signature} new signature object
  36424. * @async
  36425. * @static
  36426. */
  36427. async function readArmored(armoredText) {
  36428. const input = await _armor2.default.decode(armoredText);
  36429. return read(input.data);
  36430. }
  36431. /**
  36432. * reads an OpenPGP signature as byte array and returns a signature object
  36433. * @param {Uint8Array | ReadableStream<Uint8Array>} input binary signature
  36434. * @returns {Signature} new signature object
  36435. * @async
  36436. * @static
  36437. */
  36438. async function read(input) {
  36439. const packetlist = new _packet2.default.List();
  36440. await packetlist.read(input);
  36441. return new Signature(packetlist);
  36442. }
  36443. },{"./encoding/armor":111,"./enums":113,"./packet":131}],152:[function(require,module,exports){
  36444. 'use strict';
  36445. Object.defineProperty(exports, "__esModule", {
  36446. value: true
  36447. });
  36448. var _util = require('../util');
  36449. var _util2 = _interopRequireDefault(_util);
  36450. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  36451. /**
  36452. * @constructor
  36453. */
  36454. function ECDHSymmetricKey(data) {
  36455. if (typeof data === 'undefined') {
  36456. data = new Uint8Array([]);
  36457. } else if (_util2.default.isString(data)) {
  36458. data = _util2.default.str_to_Uint8Array(data);
  36459. } else {
  36460. data = new Uint8Array(data);
  36461. }
  36462. this.data = data;
  36463. }
  36464. /**
  36465. * Read an ECDHSymmetricKey from an Uint8Array
  36466. * @param {Uint8Array} input Where to read the encoded symmetric key from
  36467. * @returns {Number} Number of read bytes
  36468. */
  36469. // OpenPGP.js - An OpenPGP implementation in javascript
  36470. // Copyright (C) 2015-2016 Decentral
  36471. //
  36472. // This library is free software; you can redistribute it and/or
  36473. // modify it under the terms of the GNU Lesser General Public
  36474. // License as published by the Free Software Foundation; either
  36475. // version 3.0 of the License, or (at your option) any later version.
  36476. //
  36477. // This library is distributed in the hope that it will be useful,
  36478. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  36479. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  36480. // Lesser General Public License for more details.
  36481. //
  36482. // You should have received a copy of the GNU Lesser General Public
  36483. // License along with this library; if not, write to the Free Software
  36484. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  36485. /**
  36486. * Encoded symmetric key for ECDH
  36487. *
  36488. * @requires util
  36489. * @module type/ecdh_symkey
  36490. */
  36491. ECDHSymmetricKey.prototype.read = function (input) {
  36492. if (input.length >= 1) {
  36493. const length = input[0];
  36494. if (input.length >= 1 + length) {
  36495. this.data = input.subarray(1, 1 + length);
  36496. return 1 + this.data.length;
  36497. }
  36498. }
  36499. throw new Error('Invalid symmetric key');
  36500. };
  36501. /**
  36502. * Write an ECDHSymmetricKey as an Uint8Array
  36503. * @returns {Uint8Array} An array containing the value
  36504. */
  36505. ECDHSymmetricKey.prototype.write = function () {
  36506. return _util2.default.concatUint8Array([new Uint8Array([this.data.length]), this.data]);
  36507. };
  36508. ECDHSymmetricKey.fromClone = function (clone) {
  36509. return new ECDHSymmetricKey(clone.data);
  36510. };
  36511. exports.default = ECDHSymmetricKey;
  36512. },{"../util":158}],153:[function(require,module,exports){
  36513. 'use strict';
  36514. Object.defineProperty(exports, "__esModule", {
  36515. value: true
  36516. });
  36517. var _enums = require('../enums.js');
  36518. var _enums2 = _interopRequireDefault(_enums);
  36519. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  36520. /**
  36521. * @constructor
  36522. * @param {enums.hash} hash Hash algorithm
  36523. * @param {enums.symmetric} cipher Symmetric algorithm
  36524. */
  36525. function KDFParams(data) {
  36526. if (data && data.length === 2) {
  36527. this.hash = data[0];
  36528. this.cipher = data[1];
  36529. } else {
  36530. this.hash = _enums2.default.hash.sha1;
  36531. this.cipher = _enums2.default.symmetric.aes128;
  36532. }
  36533. }
  36534. /**
  36535. * Read KDFParams from an Uint8Array
  36536. * @param {Uint8Array} input Where to read the KDFParams from
  36537. * @returns {Number} Number of read bytes
  36538. */
  36539. // OpenPGP.js - An OpenPGP implementation in javascript
  36540. // Copyright (C) 2015-2016 Decentral
  36541. //
  36542. // This library is free software; you can redistribute it and/or
  36543. // modify it under the terms of the GNU Lesser General Public
  36544. // License as published by the Free Software Foundation; either
  36545. // version 3.0 of the License, or (at your option) any later version.
  36546. //
  36547. // This library is distributed in the hope that it will be useful,
  36548. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  36549. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  36550. // Lesser General Public License for more details.
  36551. //
  36552. // You should have received a copy of the GNU Lesser General Public
  36553. // License along with this library; if not, write to the Free Software
  36554. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  36555. /**
  36556. * Implementation of type KDF parameters
  36557. *
  36558. * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}:
  36559. * A key derivation function (KDF) is necessary to implement the EC
  36560. * encryption. The Concatenation Key Derivation Function (Approved
  36561. * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is
  36562. * SHA2-256 [FIPS-180-3] or stronger is REQUIRED.
  36563. * @requires enums
  36564. * @module type/kdf_params
  36565. */
  36566. KDFParams.prototype.read = function (input) {
  36567. if (input.length < 4 || input[0] !== 3 || input[1] !== 1) {
  36568. throw new Error('Cannot read KDFParams');
  36569. }
  36570. this.hash = input[2];
  36571. this.cipher = input[3];
  36572. return 4;
  36573. };
  36574. /**
  36575. * Write KDFParams to an Uint8Array
  36576. * @returns {Uint8Array} Array with the KDFParams value
  36577. */
  36578. KDFParams.prototype.write = function () {
  36579. return new Uint8Array([3, 1, this.hash, this.cipher]);
  36580. };
  36581. KDFParams.fromClone = function (clone) {
  36582. return new KDFParams([clone.hash, clone.cipher]);
  36583. };
  36584. exports.default = KDFParams;
  36585. },{"../enums.js":113}],154:[function(require,module,exports){
  36586. 'use strict';
  36587. Object.defineProperty(exports, "__esModule", {
  36588. value: true
  36589. });
  36590. var _util = require('../util.js');
  36591. var _util2 = _interopRequireDefault(_util);
  36592. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  36593. /**
  36594. * @constructor
  36595. */
  36596. function Keyid() {
  36597. this.bytes = '';
  36598. }
  36599. /**
  36600. * Parsing method for a key id
  36601. * @param {Uint8Array} input Input to read the key id from
  36602. */
  36603. // GPG4Browsers - An OpenPGP implementation in javascript
  36604. // Copyright (C) 2011 Recurity Labs GmbH
  36605. //
  36606. // This library is free software; you can redistribute it and/or
  36607. // modify it under the terms of the GNU Lesser General Public
  36608. // License as published by the Free Software Foundation; either
  36609. // version 3.0 of the License, or (at your option) any later version.
  36610. //
  36611. // This library is distributed in the hope that it will be useful,
  36612. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  36613. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  36614. // Lesser General Public License for more details.
  36615. //
  36616. // You should have received a copy of the GNU Lesser General Public
  36617. // License along with this library; if not, write to the Free Software
  36618. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  36619. /**
  36620. * Implementation of type key id
  36621. *
  36622. * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}:
  36623. * A Key ID is an eight-octet scalar that identifies a key.
  36624. * Implementations SHOULD NOT assume that Key IDs are unique. The
  36625. * section "Enhanced Key Formats" below describes how Key IDs are
  36626. * formed.
  36627. * @requires util
  36628. * @module type/keyid
  36629. */
  36630. Keyid.prototype.read = function (bytes) {
  36631. this.bytes = _util2.default.Uint8Array_to_str(bytes.subarray(0, 8));
  36632. };
  36633. Keyid.prototype.write = function () {
  36634. return _util2.default.str_to_Uint8Array(this.bytes);
  36635. };
  36636. Keyid.prototype.toHex = function () {
  36637. return _util2.default.str_to_hex(this.bytes);
  36638. };
  36639. /**
  36640. * Checks equality of Key ID's
  36641. * @param {Keyid} keyid
  36642. * @param {Boolean} matchWildcard Indicates whether to check if either keyid is a wildcard
  36643. */
  36644. Keyid.prototype.equals = function (keyid, matchWildcard = false) {
  36645. return matchWildcard && (keyid.isWildcard() || this.isWildcard()) || this.bytes === keyid.bytes;
  36646. };
  36647. Keyid.prototype.isNull = function () {
  36648. return this.bytes === '';
  36649. };
  36650. Keyid.prototype.isWildcard = function () {
  36651. return (/^0+$/.test(this.toHex())
  36652. );
  36653. };
  36654. Keyid.mapToHex = function (keyId) {
  36655. return keyId.toHex();
  36656. };
  36657. Keyid.fromClone = function (clone) {
  36658. const keyid = new Keyid();
  36659. keyid.bytes = clone.bytes;
  36660. return keyid;
  36661. };
  36662. Keyid.fromId = function (hex) {
  36663. const keyid = new Keyid();
  36664. keyid.read(_util2.default.hex_to_Uint8Array(hex));
  36665. return keyid;
  36666. };
  36667. Keyid.wildcard = function () {
  36668. const keyid = new Keyid();
  36669. keyid.read(new Uint8Array(8));
  36670. return keyid;
  36671. };
  36672. exports.default = Keyid;
  36673. },{"../util.js":158}],155:[function(require,module,exports){
  36674. 'use strict';
  36675. Object.defineProperty(exports, "__esModule", {
  36676. value: true
  36677. });
  36678. var _bn = require('bn.js');
  36679. var _bn2 = _interopRequireDefault(_bn);
  36680. var _util = require('../util');
  36681. var _util2 = _interopRequireDefault(_util);
  36682. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  36683. /**
  36684. * @constructor
  36685. */
  36686. // GPG4Browsers - An OpenPGP implementation in javascript
  36687. // Copyright (C) 2011 Recurity Labs GmbH
  36688. //
  36689. // This library is free software; you can redistribute it and/or
  36690. // modify it under the terms of the GNU Lesser General Public
  36691. // License as published by the Free Software Foundation; either
  36692. // version 3.0 of the License, or (at your option) any later version.
  36693. //
  36694. // This library is distributed in the hope that it will be useful,
  36695. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  36696. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  36697. // Lesser General Public License for more details.
  36698. //
  36699. // You should have received a copy of the GNU Lesser General Public
  36700. // License along with this library; if not, write to the Free Software
  36701. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  36702. // Hint: We hold our MPIs as an array of octets in big endian format preceding a two
  36703. // octet scalar: MPI: [a,b,c,d,e,f]
  36704. // - MPI size: (a << 8) | b
  36705. // - MPI = c | d << 8 | e << ((MPI.length -2)*8) | f ((MPI.length -2)*8)
  36706. /**
  36707. * Implementation of type MPI ({@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC4880 3.2})
  36708. * Multiprecision integers (also called MPIs) are unsigned integers used
  36709. * to hold large integers such as the ones used in cryptographic
  36710. * calculations.
  36711. * An MPI consists of two pieces: a two-octet scalar that is the length
  36712. * of the MPI in bits followed by a string of octets that contain the
  36713. * actual integer.
  36714. * @requires bn.js
  36715. * @requires util
  36716. * @module type/mpi
  36717. */
  36718. function MPI(data) {
  36719. /** An implementation dependent integer */
  36720. if (data instanceof MPI) {
  36721. this.data = data.data;
  36722. } else if (_bn2.default.isBN(data)) {
  36723. this.fromBN(data);
  36724. } else if (_util2.default.isUint8Array(data)) {
  36725. this.fromUint8Array(data);
  36726. } else if (_util2.default.isString(data)) {
  36727. this.fromString(data);
  36728. } else {
  36729. this.data = null;
  36730. }
  36731. }
  36732. /**
  36733. * Parsing function for a MPI ({@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC 4880 3.2}).
  36734. * @param {Uint8Array} input Payload of MPI data
  36735. * @param {String} endian Endianness of the data; 'be' for big-endian or 'le' for little-endian
  36736. * @returns {Integer} Length of data read
  36737. */
  36738. MPI.prototype.read = function (bytes, endian = 'be') {
  36739. if (_util2.default.isString(bytes)) {
  36740. bytes = _util2.default.str_to_Uint8Array(bytes);
  36741. }
  36742. const bits = bytes[0] << 8 | bytes[1];
  36743. const bytelen = bits + 7 >>> 3;
  36744. const payload = bytes.subarray(2, 2 + bytelen);
  36745. this.fromUint8Array(payload, endian);
  36746. return 2 + bytelen;
  36747. };
  36748. /**
  36749. * Converts the mpi object to a bytes as specified in
  36750. * {@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC4880 3.2}
  36751. * @param {String} endian Endianness of the payload; 'be' for big-endian or 'le' for little-endian
  36752. * @param {Integer} length Length of the data part of the MPI
  36753. * @returns {Uint8Aray} mpi Byte representation
  36754. */
  36755. MPI.prototype.write = function (endian, length) {
  36756. return _util2.default.Uint8Array_to_MPI(this.toUint8Array(endian, length));
  36757. };
  36758. MPI.prototype.bitLength = function () {
  36759. return (this.data.length - 1) * 8 + _util2.default.nbits(this.data[0]);
  36760. };
  36761. MPI.prototype.byteLength = function () {
  36762. return this.data.length;
  36763. };
  36764. MPI.prototype.toUint8Array = function (endian, length) {
  36765. endian = endian || 'be';
  36766. length = length || this.data.length;
  36767. const payload = new Uint8Array(length);
  36768. const start = length - this.data.length;
  36769. if (start < 0) {
  36770. throw new Error('Payload is too large.');
  36771. }
  36772. payload.set(this.data, start);
  36773. if (endian === 'le') {
  36774. payload.reverse();
  36775. }
  36776. return payload;
  36777. };
  36778. MPI.prototype.fromUint8Array = function (bytes, endian = 'be') {
  36779. this.data = new Uint8Array(bytes.length);
  36780. this.data.set(bytes);
  36781. if (endian === 'le') {
  36782. this.data.reverse();
  36783. }
  36784. };
  36785. MPI.prototype.toString = function () {
  36786. return _util2.default.Uint8Array_to_str(this.toUint8Array());
  36787. };
  36788. MPI.prototype.fromString = function (str, endian = 'be') {
  36789. this.fromUint8Array(_util2.default.str_to_Uint8Array(str), endian);
  36790. };
  36791. MPI.prototype.toBN = function () {
  36792. return new _bn2.default(this.toUint8Array());
  36793. };
  36794. MPI.prototype.fromBN = function (bn) {
  36795. this.data = bn.toArrayLike(Uint8Array);
  36796. };
  36797. MPI.fromClone = function (clone) {
  36798. return new MPI(clone.data);
  36799. };
  36800. exports.default = MPI;
  36801. },{"../util":158,"bn.js":16}],156:[function(require,module,exports){
  36802. 'use strict';
  36803. Object.defineProperty(exports, "__esModule", {
  36804. value: true
  36805. });
  36806. var _util = require('../util');
  36807. var _util2 = _interopRequireDefault(_util);
  36808. var _enums = require('../enums');
  36809. var _enums2 = _interopRequireDefault(_enums);
  36810. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  36811. /**
  36812. * @constructor
  36813. */
  36814. // OpenPGP.js - An OpenPGP implementation in javascript
  36815. // Copyright (C) 2015-2016 Decentral
  36816. //
  36817. // This library is free software; you can redistribute it and/or
  36818. // modify it under the terms of the GNU Lesser General Public
  36819. // License as published by the Free Software Foundation; either
  36820. // version 3.0 of the License, or (at your option) any later version.
  36821. //
  36822. // This library is distributed in the hope that it will be useful,
  36823. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  36824. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  36825. // Lesser General Public License for more details.
  36826. //
  36827. // You should have received a copy of the GNU Lesser General Public
  36828. // License along with this library; if not, write to the Free Software
  36829. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  36830. /**
  36831. * Wrapper to an OID value
  36832. *
  36833. * {@link https://tools.ietf.org/html/rfc6637#section-11|RFC6637, section 11}:
  36834. * The sequence of octets in the third column is the result of applying
  36835. * the Distinguished Encoding Rules (DER) to the ASN.1 Object Identifier
  36836. * with subsequent truncation. The truncation removes the two fields of
  36837. * encoded Object Identifier. The first omitted field is one octet
  36838. * representing the Object Identifier tag, and the second omitted field
  36839. * is the length of the Object Identifier body. For example, the
  36840. * complete ASN.1 DER encoding for the NIST P-256 curve OID is "06 08 2A
  36841. * 86 48 CE 3D 03 01 07", from which the first entry in the table above
  36842. * is constructed by omitting the first two octets. Only the truncated
  36843. * sequence of octets is the valid representation of a curve OID.
  36844. * @requires util
  36845. * @requires enums
  36846. * @module type/oid
  36847. */
  36848. function OID(oid) {
  36849. if (oid instanceof OID) {
  36850. this.oid = oid.oid;
  36851. } else if (_util2.default.isArray(oid) || _util2.default.isUint8Array(oid)) {
  36852. oid = new Uint8Array(oid);
  36853. if (oid[0] === 0x06) {
  36854. // DER encoded oid byte array
  36855. if (oid[1] !== oid.length - 2) {
  36856. throw new Error('Length mismatch in DER encoded oid');
  36857. }
  36858. oid = oid.subarray(2);
  36859. }
  36860. this.oid = oid;
  36861. } else {
  36862. this.oid = '';
  36863. }
  36864. }
  36865. /**
  36866. * Method to read an OID object
  36867. * @param {Uint8Array} input Where to read the OID from
  36868. * @returns {Number} Number of read bytes
  36869. */
  36870. OID.prototype.read = function (input) {
  36871. if (input.length >= 1) {
  36872. const length = input[0];
  36873. if (input.length >= 1 + length) {
  36874. this.oid = input.subarray(1, 1 + length);
  36875. return 1 + this.oid.length;
  36876. }
  36877. }
  36878. throw new Error('Invalid oid');
  36879. };
  36880. /**
  36881. * Serialize an OID object
  36882. * @returns {Uint8Array} Array with the serialized value the OID
  36883. */
  36884. OID.prototype.write = function () {
  36885. return _util2.default.concatUint8Array([new Uint8Array([this.oid.length]), this.oid]);
  36886. };
  36887. /**
  36888. * Serialize an OID object as a hex string
  36889. * @returns {string} String with the hex value of the OID
  36890. */
  36891. OID.prototype.toHex = function () {
  36892. return _util2.default.Uint8Array_to_hex(this.oid);
  36893. };
  36894. /**
  36895. * If a known curve object identifier, return the canonical name of the curve
  36896. * @returns {string} String with the canonical name of the curve
  36897. */
  36898. OID.prototype.getName = function () {
  36899. const hex = this.toHex();
  36900. if (_enums2.default.curve[hex]) {
  36901. return _enums2.default.write(_enums2.default.curve, hex);
  36902. } else {
  36903. throw new Error('Unknown curve object identifier.');
  36904. }
  36905. };
  36906. OID.fromClone = function (clone) {
  36907. return new OID(clone.oid);
  36908. };
  36909. exports.default = OID;
  36910. },{"../enums":113,"../util":158}],157:[function(require,module,exports){
  36911. 'use strict';
  36912. Object.defineProperty(exports, "__esModule", {
  36913. value: true
  36914. });
  36915. var _config = require('../config');
  36916. var _config2 = _interopRequireDefault(_config);
  36917. var _crypto = require('../crypto');
  36918. var _crypto2 = _interopRequireDefault(_crypto);
  36919. var _enums = require('../enums.js');
  36920. var _enums2 = _interopRequireDefault(_enums);
  36921. var _util = require('../util.js');
  36922. var _util2 = _interopRequireDefault(_util);
  36923. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  36924. /**
  36925. * @constructor
  36926. */
  36927. // GPG4Browsers - An OpenPGP implementation in javascript
  36928. // Copyright (C) 2011 Recurity Labs GmbH
  36929. //
  36930. // This library is free software; you can redistribute it and/or
  36931. // modify it under the terms of the GNU Lesser General Public
  36932. // License as published by the Free Software Foundation; either
  36933. // version 3.0 of the License, or (at your option) any later version.
  36934. //
  36935. // This library is distributed in the hope that it will be useful,
  36936. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  36937. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  36938. // Lesser General Public License for more details.
  36939. //
  36940. // You should have received a copy of the GNU Lesser General Public
  36941. // License along with this library; if not, write to the Free Software
  36942. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  36943. /**
  36944. * Implementation of the String-to-key specifier
  36945. *
  36946. * {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC4880 3.7}:
  36947. * String-to-key (S2K) specifiers are used to convert passphrase strings
  36948. * into symmetric-key encryption/decryption keys. They are used in two
  36949. * places, currently: to encrypt the secret part of private keys in the
  36950. * private keyring, and to convert passphrases to encryption keys for
  36951. * symmetrically encrypted messages.
  36952. * @requires config
  36953. * @requires crypto
  36954. * @requires enums
  36955. * @requires util
  36956. * @module type/s2k
  36957. */
  36958. function S2K() {
  36959. /** @type {module:enums.hash} */
  36960. this.algorithm = 'sha256';
  36961. /** @type {module:enums.s2k} */
  36962. this.type = 'iterated';
  36963. /** @type {Integer} */
  36964. this.c = _config2.default.s2k_iteration_count_byte;
  36965. /** Eight bytes of salt in a binary string.
  36966. * @type {String}
  36967. */
  36968. this.salt = null;
  36969. }
  36970. S2K.prototype.get_count = function () {
  36971. // Exponent bias, defined in RFC4880
  36972. const expbias = 6;
  36973. return 16 + (this.c & 15) << (this.c >> 4) + expbias;
  36974. };
  36975. /**
  36976. * Parsing function for a string-to-key specifier ({@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}).
  36977. * @param {String} input Payload of string-to-key specifier
  36978. * @returns {Integer} Actual length of the object
  36979. */
  36980. S2K.prototype.read = function (bytes) {
  36981. let i = 0;
  36982. this.type = _enums2.default.read(_enums2.default.s2k, bytes[i++]);
  36983. this.algorithm = bytes[i++];
  36984. if (this.type !== 'gnu') {
  36985. this.algorithm = _enums2.default.read(_enums2.default.hash, this.algorithm);
  36986. }
  36987. switch (this.type) {
  36988. case 'simple':
  36989. break;
  36990. case 'salted':
  36991. this.salt = bytes.subarray(i, i + 8);
  36992. i += 8;
  36993. break;
  36994. case 'iterated':
  36995. this.salt = bytes.subarray(i, i + 8);
  36996. i += 8;
  36997. // Octet 10: count, a one-octet, coded value
  36998. this.c = bytes[i++];
  36999. break;
  37000. case 'gnu':
  37001. if (_util2.default.Uint8Array_to_str(bytes.subarray(i, i + 3)) === "GNU") {
  37002. i += 3; // GNU
  37003. const gnuExtType = 1000 + bytes[i++];
  37004. if (gnuExtType === 1001) {
  37005. this.type = 'gnu-dummy';
  37006. // GnuPG extension mode 1001 -- don't write secret key at all
  37007. } else {
  37008. throw new Error("Unknown s2k gnu protection mode.");
  37009. }
  37010. } else {
  37011. throw new Error("Unknown s2k type.");
  37012. }
  37013. break;
  37014. default:
  37015. throw new Error("Unknown s2k type.");
  37016. }
  37017. return i;
  37018. };
  37019. /**
  37020. * Serializes s2k information
  37021. * @returns {Uint8Array} binary representation of s2k
  37022. */
  37023. S2K.prototype.write = function () {
  37024. if (this.type === 'gnu-dummy') {
  37025. return new Uint8Array([101, 0, ..._util2.default.str_to_Uint8Array('GNU'), 1]);
  37026. }
  37027. const arr = [new Uint8Array([_enums2.default.write(_enums2.default.s2k, this.type), _enums2.default.write(_enums2.default.hash, this.algorithm)])];
  37028. switch (this.type) {
  37029. case 'simple':
  37030. break;
  37031. case 'salted':
  37032. arr.push(this.salt);
  37033. break;
  37034. case 'iterated':
  37035. arr.push(this.salt);
  37036. arr.push(new Uint8Array([this.c]));
  37037. break;
  37038. case 'gnu':
  37039. throw new Error("GNU s2k type not supported.");
  37040. default:
  37041. throw new Error("Unknown s2k type.");
  37042. }
  37043. return _util2.default.concatUint8Array(arr);
  37044. };
  37045. /**
  37046. * Produces a key using the specified passphrase and the defined
  37047. * hashAlgorithm
  37048. * @param {String} passphrase Passphrase containing user input
  37049. * @returns {Uint8Array} Produced key with a length corresponding to
  37050. * hashAlgorithm hash length
  37051. */
  37052. S2K.prototype.produce_key = async function (passphrase, numBytes) {
  37053. passphrase = _util2.default.encode_utf8(passphrase);
  37054. const algorithm = _enums2.default.write(_enums2.default.hash, this.algorithm);
  37055. const arr = [];
  37056. let rlength = 0;
  37057. let prefixlen = 0;
  37058. while (rlength < numBytes) {
  37059. let toHash;
  37060. switch (this.type) {
  37061. case 'simple':
  37062. toHash = _util2.default.concatUint8Array([new Uint8Array(prefixlen), passphrase]);
  37063. break;
  37064. case 'salted':
  37065. toHash = _util2.default.concatUint8Array([new Uint8Array(prefixlen), this.salt, passphrase]);
  37066. break;
  37067. case 'iterated':
  37068. {
  37069. const data = _util2.default.concatUint8Array([this.salt, passphrase]);
  37070. let datalen = data.length;
  37071. const count = Math.max(this.get_count(), datalen);
  37072. toHash = new Uint8Array(prefixlen + count);
  37073. toHash.set(data, prefixlen);
  37074. for (let pos = prefixlen + datalen; pos < count; pos += datalen, datalen *= 2) {
  37075. toHash.copyWithin(pos, prefixlen, pos);
  37076. }
  37077. break;
  37078. }
  37079. case 'gnu':
  37080. throw new Error("GNU s2k type not supported.");
  37081. default:
  37082. throw new Error("Unknown s2k type.");
  37083. }
  37084. const result = await _crypto2.default.hash.digest(algorithm, toHash);
  37085. arr.push(result);
  37086. rlength += result.length;
  37087. prefixlen++;
  37088. }
  37089. return _util2.default.concatUint8Array(arr).subarray(0, numBytes);
  37090. };
  37091. S2K.fromClone = function (clone) {
  37092. const s2k = new S2K();
  37093. s2k.algorithm = clone.algorithm;
  37094. s2k.type = clone.type;
  37095. s2k.c = clone.c;
  37096. s2k.salt = clone.salt;
  37097. return s2k;
  37098. };
  37099. exports.default = S2K;
  37100. },{"../config":79,"../crypto":94,"../enums.js":113,"../util.js":158}],158:[function(require,module,exports){
  37101. (function (global){
  37102. 'use strict';
  37103. Object.defineProperty(exports, "__esModule", {
  37104. value: true
  37105. });
  37106. var _emailAddresses = require('email-addresses');
  37107. var _emailAddresses2 = _interopRequireDefault(_emailAddresses);
  37108. var _webStreamTools = require('web-stream-tools');
  37109. var _webStreamTools2 = _interopRequireDefault(_webStreamTools);
  37110. var _config = require('./config');
  37111. var _config2 = _interopRequireDefault(_config);
  37112. var _util = require('./util');
  37113. var _util2 = _interopRequireDefault(_util);
  37114. var _base = require('./encoding/base64');
  37115. var _base2 = _interopRequireDefault(_base);
  37116. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  37117. exports.default = {
  37118. isString: function isString(data) {
  37119. return typeof data === 'string' || String.prototype.isPrototypeOf(data);
  37120. },
  37121. isArray: function isArray(data) {
  37122. return Array.prototype.isPrototypeOf(data);
  37123. },
  37124. isUint8Array: _webStreamTools2.default.isUint8Array,
  37125. isStream: _webStreamTools2.default.isStream,
  37126. /**
  37127. * Get transferable objects to pass buffers with zero copy (similar to "pass by reference" in C++)
  37128. * See: https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage
  37129. * Also, convert ReadableStreams to MessagePorts
  37130. * @param {Object} obj the options object to be passed to the web worker
  37131. * @returns {Array<ArrayBuffer>} an array of binary data to be passed
  37132. */
  37133. getTransferables: function getTransferables(obj, zero_copy) {
  37134. const transferables = [];
  37135. _util2.default.collectTransferables(obj, transferables, zero_copy);
  37136. return transferables.length ? transferables : undefined;
  37137. },
  37138. collectTransferables: function collectTransferables(obj, collection, zero_copy) {
  37139. if (!obj) {
  37140. return;
  37141. }
  37142. if (_util2.default.isUint8Array(obj)) {
  37143. if (zero_copy && collection.indexOf(obj.buffer) === -1 && !(navigator.userAgent.indexOf('Version/11.1') !== -1 || // Safari 11.1
  37144. (navigator.userAgent.match(/Chrome\/(\d+)/) || [])[1] < 56 && navigator.userAgent.indexOf('Edge') === -1 // Chrome < 56
  37145. )) {
  37146. collection.push(obj.buffer);
  37147. }
  37148. return;
  37149. }
  37150. if (Object.prototype.isPrototypeOf(obj)) {
  37151. Object.entries(obj).forEach(([key, value]) => {
  37152. // recursively search all children
  37153. if (_util2.default.isStream(value)) {
  37154. if (value.locked) {
  37155. obj[key] = null;
  37156. } else {
  37157. const transformed = _webStreamTools2.default.transformPair(value, async readable => {
  37158. const reader = _webStreamTools2.default.getReader(readable);
  37159. var _ref = new MessageChannel();
  37160. const port1 = _ref.port1,
  37161. port2 = _ref.port2;
  37162. port1.onmessage = async function ({ data: { action } }) {
  37163. if (action === 'read') {
  37164. try {
  37165. const result = await reader.read();
  37166. port1.postMessage(result, _util2.default.getTransferables(result));
  37167. } catch (e) {
  37168. port1.postMessage({ error: e.message });
  37169. }
  37170. } else if (action === 'cancel') {
  37171. await transformed.cancel();
  37172. port1.postMessage();
  37173. }
  37174. };
  37175. obj[key] = port2;
  37176. collection.push(port2);
  37177. });
  37178. }
  37179. return;
  37180. }
  37181. if (Object.prototype.toString.call(value) === '[object MessagePort]') {
  37182. throw new Error("Can't transfer the same stream twice.");
  37183. }
  37184. _util2.default.collectTransferables(value, collection, zero_copy);
  37185. });
  37186. }
  37187. },
  37188. /**
  37189. * Convert MessagePorts back to ReadableStreams
  37190. * @param {Object} obj
  37191. * @returns {Object}
  37192. */
  37193. restoreStreams: function restoreStreams(obj) {
  37194. if (Object.prototype.isPrototypeOf(obj) && !Uint8Array.prototype.isPrototypeOf(obj)) {
  37195. Object.entries(obj).forEach(([key, value]) => {
  37196. // recursively search all children
  37197. if (Object.prototype.toString.call(value) === '[object MessagePort]') {
  37198. obj[key] = new ReadableStream({
  37199. pull(controller) {
  37200. return new Promise(resolve => {
  37201. value.onmessage = evt => {
  37202. var _evt$data = evt.data;
  37203. const done = _evt$data.done,
  37204. value = _evt$data.value,
  37205. error = _evt$data.error;
  37206. if (error) {
  37207. controller.error(new Error(error));
  37208. } else if (!done) {
  37209. controller.enqueue(value);
  37210. } else {
  37211. controller.close();
  37212. }
  37213. resolve();
  37214. };
  37215. value.postMessage({ action: 'read' });
  37216. });
  37217. },
  37218. cancel() {
  37219. return new Promise(resolve => {
  37220. value.onmessage = resolve;
  37221. value.postMessage({ action: 'cancel' });
  37222. });
  37223. }
  37224. }, { highWaterMark: 0 });
  37225. return;
  37226. }
  37227. _util2.default.restoreStreams(value);
  37228. });
  37229. }
  37230. return obj;
  37231. },
  37232. readNumber: function readNumber(bytes) {
  37233. let n = 0;
  37234. for (let i = 0; i < bytes.length; i++) {
  37235. n += 256 ** i * bytes[bytes.length - 1 - i];
  37236. }
  37237. return n;
  37238. },
  37239. writeNumber: function writeNumber(n, bytes) {
  37240. const b = new Uint8Array(bytes);
  37241. for (let i = 0; i < bytes; i++) {
  37242. b[i] = n >> 8 * (bytes - i - 1) & 0xFF;
  37243. }
  37244. return b;
  37245. },
  37246. readDate: function readDate(bytes) {
  37247. const n = _util2.default.readNumber(bytes);
  37248. const d = new Date(n * 1000);
  37249. return d;
  37250. },
  37251. writeDate: function writeDate(time) {
  37252. const numeric = Math.floor(time.getTime() / 1000);
  37253. return _util2.default.writeNumber(numeric, 4);
  37254. },
  37255. normalizeDate: function normalizeDate(time = Date.now()) {
  37256. return time === null || time === Infinity ? time : new Date(Math.floor(+time / 1000) * 1000);
  37257. },
  37258. /**
  37259. * Create hex string from a binary
  37260. * @param {String} str String to convert
  37261. * @returns {String} String containing the hexadecimal values
  37262. */
  37263. str_to_hex: function str_to_hex(str) {
  37264. if (str === null) {
  37265. return "";
  37266. }
  37267. const r = [];
  37268. const e = str.length;
  37269. let c = 0;
  37270. let h;
  37271. while (c < e) {
  37272. h = str.charCodeAt(c++).toString(16);
  37273. while (h.length < 2) {
  37274. h = "0" + h;
  37275. }
  37276. r.push("" + h);
  37277. }
  37278. return r.join('');
  37279. },
  37280. /**
  37281. * Create binary string from a hex encoded string
  37282. * @param {String} str Hex string to convert
  37283. * @returns {String}
  37284. */
  37285. hex_to_str: function hex_to_str(hex) {
  37286. let str = '';
  37287. for (let i = 0; i < hex.length; i += 2) {
  37288. str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
  37289. }
  37290. return str;
  37291. },
  37292. /**
  37293. * Convert a Uint8Array to an MPI-formatted Uint8Array.
  37294. * Note: the output is **not** an MPI object.
  37295. * @see {@link module:type/mpi/MPI.fromUint8Array}
  37296. * @see {@link module:type/mpi/MPI.toUint8Array}
  37297. * @param {Uint8Array} bin An array of 8-bit integers to convert
  37298. * @returns {Uint8Array} MPI-formatted Uint8Array
  37299. */
  37300. Uint8Array_to_MPI: function Uint8Array_to_MPI(bin) {
  37301. const size = (bin.length - 1) * 8 + _util2.default.nbits(bin[0]);
  37302. const prefix = Uint8Array.from([(size & 0xFF00) >> 8, size & 0xFF]);
  37303. return _util2.default.concatUint8Array([prefix, bin]);
  37304. },
  37305. /**
  37306. * Convert a Base-64 encoded string an array of 8-bit integer
  37307. *
  37308. * Note: accepts both Radix-64 and URL-safe strings
  37309. * @param {String} base64 Base-64 encoded string to convert
  37310. * @returns {Uint8Array} An array of 8-bit integers
  37311. */
  37312. b64_to_Uint8Array: function b64_to_Uint8Array(base64) {
  37313. return _base2.default.decode(base64.replace(/-/g, '+').replace(/_/g, '/'));
  37314. },
  37315. /**
  37316. * Convert an array of 8-bit integer to a Base-64 encoded string
  37317. * @param {Uint8Array} bytes An array of 8-bit integers to convert
  37318. * @param {bool} url If true, output is URL-safe
  37319. * @returns {String} Base-64 encoded string
  37320. */
  37321. Uint8Array_to_b64: function Uint8Array_to_b64(bytes, url) {
  37322. return _base2.default.encode(bytes, url).replace(/[\r\n]/g, '');
  37323. },
  37324. /**
  37325. * Convert a hex string to an array of 8-bit integers
  37326. * @param {String} hex A hex string to convert
  37327. * @returns {Uint8Array} An array of 8-bit integers
  37328. */
  37329. hex_to_Uint8Array: function hex_to_Uint8Array(hex) {
  37330. const result = new Uint8Array(hex.length >> 1);
  37331. for (let k = 0; k < hex.length >> 1; k++) {
  37332. result[k] = parseInt(hex.substr(k << 1, 2), 16);
  37333. }
  37334. return result;
  37335. },
  37336. /**
  37337. * Convert an array of 8-bit integers to a hex string
  37338. * @param {Uint8Array} bytes Array of 8-bit integers to convert
  37339. * @returns {String} Hexadecimal representation of the array
  37340. */
  37341. Uint8Array_to_hex: function Uint8Array_to_hex(bytes) {
  37342. const r = [];
  37343. const e = bytes.length;
  37344. let c = 0;
  37345. let h;
  37346. while (c < e) {
  37347. h = bytes[c++].toString(16);
  37348. while (h.length < 2) {
  37349. h = "0" + h;
  37350. }
  37351. r.push("" + h);
  37352. }
  37353. return r.join('');
  37354. },
  37355. /**
  37356. * Convert a string to an array of 8-bit integers
  37357. * @param {String} str String to convert
  37358. * @returns {Uint8Array} An array of 8-bit integers
  37359. */
  37360. str_to_Uint8Array: function str_to_Uint8Array(str) {
  37361. return _webStreamTools2.default.transform(str, str => {
  37362. if (!_util2.default.isString(str)) {
  37363. throw new Error('str_to_Uint8Array: Data must be in the form of a string');
  37364. }
  37365. const result = new Uint8Array(str.length);
  37366. for (let i = 0; i < str.length; i++) {
  37367. result[i] = str.charCodeAt(i);
  37368. }
  37369. return result;
  37370. });
  37371. },
  37372. /**
  37373. * Convert an array of 8-bit integers to a string
  37374. * @param {Uint8Array} bytes An array of 8-bit integers to convert
  37375. * @returns {String} String representation of the array
  37376. */
  37377. Uint8Array_to_str: function Uint8Array_to_str(bytes) {
  37378. bytes = new Uint8Array(bytes);
  37379. const result = [];
  37380. const bs = 1 << 14;
  37381. const j = bytes.length;
  37382. for (let i = 0; i < j; i += bs) {
  37383. result.push(String.fromCharCode.apply(String, bytes.subarray(i, i + bs < j ? i + bs : j)));
  37384. }
  37385. return result.join('');
  37386. },
  37387. /**
  37388. * Convert a native javascript string to a Uint8Array of utf8 bytes
  37389. * @param {String|ReadableStream} str The string to convert
  37390. * @returns {Uint8Array|ReadableStream} A valid squence of utf8 bytes
  37391. */
  37392. encode_utf8: function encode_utf8(str) {
  37393. const encoder = new TextEncoder('utf-8');
  37394. // eslint-disable-next-line no-inner-declarations
  37395. function process(value, lastChunk = false) {
  37396. return encoder.encode(value, { stream: !lastChunk });
  37397. }
  37398. return _webStreamTools2.default.transform(str, process, () => process('', true));
  37399. },
  37400. /**
  37401. * Convert a Uint8Array of utf8 bytes to a native javascript string
  37402. * @param {Uint8Array|ReadableStream} utf8 A valid squence of utf8 bytes
  37403. * @returns {String|ReadableStream} A native javascript string
  37404. */
  37405. decode_utf8: function decode_utf8(utf8) {
  37406. const decoder = new TextDecoder('utf-8');
  37407. // eslint-disable-next-line no-inner-declarations
  37408. function process(value, lastChunk = false) {
  37409. return decoder.decode(value, { stream: !lastChunk });
  37410. }
  37411. return _webStreamTools2.default.transform(utf8, process, () => process(new Uint8Array(), true));
  37412. },
  37413. /**
  37414. * Concat a list of Uint8Arrays, Strings or Streams
  37415. * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams.
  37416. * @param {Array<Uint8Array|String|ReadableStream>} Array of Uint8Arrays/Strings/Streams to concatenate
  37417. * @returns {Uint8Array|String|ReadableStream} Concatenated array
  37418. */
  37419. concat: _webStreamTools2.default.concat,
  37420. /**
  37421. * Concat Uint8Arrays
  37422. * @param {Array<Uint8Array>} Array of Uint8Arrays to concatenate
  37423. * @returns {Uint8Array} Concatenated array
  37424. */
  37425. concatUint8Array: _webStreamTools2.default.concatUint8Array,
  37426. /**
  37427. * Check Uint8Array equality
  37428. * @param {Uint8Array} first array
  37429. * @param {Uint8Array} second array
  37430. * @returns {Boolean} equality
  37431. */
  37432. equalsUint8Array: function equalsUint8Array(array1, array2) {
  37433. if (!_util2.default.isUint8Array(array1) || !_util2.default.isUint8Array(array2)) {
  37434. throw new Error('Data must be in the form of a Uint8Array');
  37435. }
  37436. if (array1.length !== array2.length) {
  37437. return false;
  37438. }
  37439. for (let i = 0; i < array1.length; i++) {
  37440. if (array1[i] !== array2[i]) {
  37441. return false;
  37442. }
  37443. }
  37444. return true;
  37445. },
  37446. /**
  37447. * Calculates a 16bit sum of a Uint8Array by adding each character
  37448. * codes modulus 65535
  37449. * @param {Uint8Array} Uint8Array to create a sum of
  37450. * @returns {Uint8Array} 2 bytes containing the sum of all charcodes % 65535
  37451. */
  37452. write_checksum: function write_checksum(text) {
  37453. let s = 0;
  37454. for (let i = 0; i < text.length; i++) {
  37455. s = s + text[i] & 0xFFFF;
  37456. }
  37457. return _util2.default.writeNumber(s, 2);
  37458. },
  37459. /**
  37460. * Helper function to print a debug message. Debug
  37461. * messages are only printed if
  37462. * @link module:config/config.debug is set to true.
  37463. * @param {String} str String of the debug message
  37464. */
  37465. print_debug: function print_debug(str) {
  37466. if (_config2.default.debug) {
  37467. console.log(str);
  37468. }
  37469. },
  37470. /**
  37471. * Helper function to print a debug message. Debug
  37472. * messages are only printed if
  37473. * @link module:config/config.debug is set to true.
  37474. * Different than print_debug because will call Uint8Array_to_hex iff necessary.
  37475. * @param {String} str String of the debug message
  37476. */
  37477. print_debug_hexarray_dump: function print_debug_hexarray_dump(str, arrToHex) {
  37478. if (_config2.default.debug) {
  37479. str += ': ' + _util2.default.Uint8Array_to_hex(arrToHex);
  37480. console.log(str);
  37481. }
  37482. },
  37483. /**
  37484. * Helper function to print a debug message. Debug
  37485. * messages are only printed if
  37486. * @link module:config/config.debug is set to true.
  37487. * Different than print_debug because will call str_to_hex iff necessary.
  37488. * @param {String} str String of the debug message
  37489. */
  37490. print_debug_hexstr_dump: function print_debug_hexstr_dump(str, strToHex) {
  37491. if (_config2.default.debug) {
  37492. str += _util2.default.str_to_hex(strToHex);
  37493. console.log(str);
  37494. }
  37495. },
  37496. /**
  37497. * Helper function to print a debug error. Debug
  37498. * messages are only printed if
  37499. * @link module:config/config.debug is set to true.
  37500. * @param {String} str String of the debug message
  37501. */
  37502. print_debug_error: function print_debug_error(error) {
  37503. if (_config2.default.debug) {
  37504. console.error(error);
  37505. }
  37506. },
  37507. /**
  37508. * Read a stream to the end and print it to the console when it's closed.
  37509. * @param {String} str String of the debug message
  37510. * @param {ReadableStream|Uint8array|String} input Stream to print
  37511. * @param {Function} concat Function to concatenate chunks of the stream (defaults to util.concat).
  37512. */
  37513. print_entire_stream: function print_entire_stream(str, input, concat) {
  37514. _webStreamTools2.default.readToEnd(_webStreamTools2.default.clone(input), concat).then(result => {
  37515. console.log(str + ': ', result);
  37516. });
  37517. },
  37518. // returns bit length of the integer x
  37519. nbits: function nbits(x) {
  37520. let r = 1;
  37521. let t = x >>> 16;
  37522. if (t !== 0) {
  37523. x = t;
  37524. r += 16;
  37525. }
  37526. t = x >> 8;
  37527. if (t !== 0) {
  37528. x = t;
  37529. r += 8;
  37530. }
  37531. t = x >> 4;
  37532. if (t !== 0) {
  37533. x = t;
  37534. r += 4;
  37535. }
  37536. t = x >> 2;
  37537. if (t !== 0) {
  37538. x = t;
  37539. r += 2;
  37540. }
  37541. t = x >> 1;
  37542. if (t !== 0) {
  37543. x = t;
  37544. r += 1;
  37545. }
  37546. return r;
  37547. },
  37548. /**
  37549. * If S[1] == 0, then double(S) == (S[2..128] || 0);
  37550. * otherwise, double(S) == (S[2..128] || 0) xor
  37551. * (zeros(120) || 10000111).
  37552. *
  37553. * Both OCB and EAX (through CMAC) require this function to be constant-time.
  37554. *
  37555. * @param {Uint8Array} data
  37556. */
  37557. double: function double(data) {
  37558. const double_var = new Uint8Array(data.length);
  37559. const last = data.length - 1;
  37560. for (let i = 0; i < last; i++) {
  37561. double_var[i] = data[i] << 1 ^ data[i + 1] >> 7;
  37562. }
  37563. double_var[last] = data[last] << 1 ^ (data[0] >> 7) * 0x87;
  37564. return double_var;
  37565. },
  37566. /**
  37567. * Shift a Uint8Array to the right by n bits
  37568. * @param {Uint8Array} array The array to shift
  37569. * @param {Integer} bits Amount of bits to shift (MUST be smaller
  37570. * than 8)
  37571. * @returns {String} Resulting array.
  37572. */
  37573. shiftRight: function shiftRight(array, bits) {
  37574. if (bits) {
  37575. for (let i = array.length - 1; i >= 0; i--) {
  37576. array[i] >>= bits;
  37577. if (i > 0) {
  37578. array[i] |= array[i - 1] << 8 - bits;
  37579. }
  37580. }
  37581. }
  37582. return array;
  37583. },
  37584. /**
  37585. * Get native Web Cryptography api, only the current version of the spec.
  37586. * The default configuration is to use the api when available. But it can
  37587. * be deactivated with config.use_native
  37588. * @returns {Object} The SubtleCrypto api or 'undefined'
  37589. */
  37590. getWebCrypto: function getWebCrypto() {
  37591. if (!_config2.default.use_native) {
  37592. return;
  37593. }
  37594. return typeof window !== 'undefined' && window.crypto && window.crypto.subtle;
  37595. },
  37596. /**
  37597. * Get native Web Cryptography api for all browsers, including legacy
  37598. * implementations of the spec e.g IE11 and Safari 8/9. The default
  37599. * configuration is to use the api when available. But it can be deactivated
  37600. * with config.use_native
  37601. * @returns {Object} The SubtleCrypto api or 'undefined'
  37602. */
  37603. getWebCryptoAll: function getWebCryptoAll() {
  37604. if (!_config2.default.use_native) {
  37605. return;
  37606. }
  37607. if (typeof window !== 'undefined') {
  37608. if (window.crypto) {
  37609. return window.crypto.subtle || window.crypto.webkitSubtle;
  37610. }
  37611. if (window.msCrypto) {
  37612. return window.msCrypto.subtle;
  37613. }
  37614. }
  37615. },
  37616. /**
  37617. * Detect Node.js runtime.
  37618. */
  37619. detectNode: function detectNode() {
  37620. return typeof global.process === 'object' && typeof global.process.versions === 'object';
  37621. },
  37622. /**
  37623. * Get native Node.js module
  37624. * @param {String} The module to require
  37625. * @returns {Object} The required module or 'undefined'
  37626. */
  37627. nodeRequire: function nodeRequire(module) {
  37628. if (!_util2.default.detectNode()) {
  37629. return;
  37630. }
  37631. // Requiring the module dynamically allows us to access the native node module.
  37632. // otherwise, it gets replaced with the browserified version
  37633. // eslint-disable-next-line import/no-dynamic-require
  37634. return require(module);
  37635. },
  37636. /**
  37637. * Get native Node.js crypto api. The default configuration is to use
  37638. * the api when available. But it can also be deactivated with config.use_native
  37639. * @returns {Object} The crypto module or 'undefined'
  37640. */
  37641. getNodeCrypto: function getNodeCrypto() {
  37642. if (!_config2.default.use_native) {
  37643. return;
  37644. }
  37645. return _util2.default.nodeRequire('crypto');
  37646. },
  37647. getNodeZlib: function getNodeZlib() {
  37648. if (!_config2.default.use_native) {
  37649. return;
  37650. }
  37651. return _util2.default.nodeRequire('zlib');
  37652. },
  37653. /**
  37654. * Get native Node.js Buffer constructor. This should be used since
  37655. * Buffer is not available under browserify.
  37656. * @returns {Function} The Buffer constructor or 'undefined'
  37657. */
  37658. getNodeBuffer: function getNodeBuffer() {
  37659. return (_util2.default.nodeRequire('buffer') || {}).Buffer;
  37660. },
  37661. getNodeStream: function getNodeStream() {
  37662. return (_util2.default.nodeRequire('stream') || {}).Readable;
  37663. },
  37664. getHardwareConcurrency: function getHardwareConcurrency() {
  37665. if (_util2.default.detectNode()) {
  37666. const os = _util2.default.nodeRequire('os');
  37667. return os.cpus().length;
  37668. }
  37669. return navigator.hardwareConcurrency || 1;
  37670. },
  37671. isEmailAddress: function isEmailAddress(data) {
  37672. if (!_util2.default.isString(data)) {
  37673. return false;
  37674. }
  37675. const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+([a-zA-Z]{2,}|xn--[a-zA-Z\-0-9]+)))$/;
  37676. return re.test(data);
  37677. },
  37678. /**
  37679. * Format user id for internal use.
  37680. */
  37681. formatUserId: function formatUserId(id) {
  37682. // name, email address and comment can be empty but must be of the correct type
  37683. if (id.name && !_util2.default.isString(id.name) || id.email && !_util2.default.isEmailAddress(id.email) || id.comment && !_util2.default.isString(id.comment)) {
  37684. throw new Error('Invalid user id format');
  37685. }
  37686. const components = [];
  37687. if (id.name) {
  37688. components.push(id.name);
  37689. }
  37690. if (id.comment) {
  37691. components.push(`(${id.comment})`);
  37692. }
  37693. if (id.email) {
  37694. components.push(`<${id.email}>`);
  37695. }
  37696. return components.join(' ');
  37697. },
  37698. /**
  37699. * Parse user id.
  37700. */
  37701. parseUserId: function parseUserId(userid) {
  37702. if (userid.length > _config2.default.max_userid_length) {
  37703. throw new Error('User id string is too long');
  37704. }
  37705. try {
  37706. var _emailAddresses$parse = _emailAddresses2.default.parseOneAddress({ input: userid, atInDisplayName: true });
  37707. const name = _emailAddresses$parse.name,
  37708. email = _emailAddresses$parse.address,
  37709. comments = _emailAddresses$parse.comments;
  37710. return { name, email, comment: comments.replace(/^\(|\)$/g, '') };
  37711. } catch (e) {
  37712. throw new Error('Invalid user id format');
  37713. }
  37714. },
  37715. /**
  37716. * Normalize line endings to \r\n
  37717. */
  37718. canonicalizeEOL: function canonicalizeEOL(text) {
  37719. return _webStreamTools2.default.transform(_util2.default.nativeEOL(text), value => value.replace(/\r/g, "\n").replace(/\n/g, "\r\n"));
  37720. },
  37721. /**
  37722. * Convert line endings from canonicalized \r\n to native \n
  37723. */
  37724. nativeEOL: function nativeEOL(text) {
  37725. let lastChar = '';
  37726. return _webStreamTools2.default.transform(text, value => {
  37727. value = lastChar + value;
  37728. if (value[value.length - 1] === '\r') {
  37729. lastChar = '\r';
  37730. value = value.slice(0, -1);
  37731. } else {
  37732. lastChar = '';
  37733. }
  37734. return value.replace(/\r\n/g, '\n');
  37735. }, () => lastChar);
  37736. },
  37737. /**
  37738. * Remove trailing spaces and tabs from each line
  37739. */
  37740. removeTrailingSpaces: function removeTrailingSpaces(text) {
  37741. return text.split('\n').map(line => {
  37742. let i = line.length - 1;
  37743. for (; i >= 0 && (line[i] === ' ' || line[i] === '\t'); i--);
  37744. return line.substr(0, i + 1);
  37745. }).join('\n');
  37746. },
  37747. /**
  37748. * Encode input buffer using Z-Base32 encoding.
  37749. * See: https://tools.ietf.org/html/rfc6189#section-5.1.6
  37750. *
  37751. * @param {Uint8Array} data The binary data to encode
  37752. * @returns {String} Binary data encoded using Z-Base32
  37753. */
  37754. encodeZBase32: function encodeZBase32(data) {
  37755. if (data.length === 0) {
  37756. return "";
  37757. }
  37758. const ALPHABET = "ybndrfg8ejkmcpqxot1uwisza345h769";
  37759. const SHIFT = 5;
  37760. const MASK = 31;
  37761. let buffer = data[0];
  37762. let index = 1;
  37763. let bitsLeft = 8;
  37764. let result = '';
  37765. while (bitsLeft > 0 || index < data.length) {
  37766. if (bitsLeft < SHIFT) {
  37767. if (index < data.length) {
  37768. buffer <<= 8;
  37769. buffer |= data[index++] & 0xff;
  37770. bitsLeft += 8;
  37771. } else {
  37772. const pad = SHIFT - bitsLeft;
  37773. buffer <<= pad;
  37774. bitsLeft += pad;
  37775. }
  37776. }
  37777. bitsLeft -= SHIFT;
  37778. result += ALPHABET[MASK & buffer >> bitsLeft];
  37779. }
  37780. return result;
  37781. }
  37782. }; // re-import module to access util functions
  37783. // GPG4Browsers - An OpenPGP implementation in javascript
  37784. // Copyright (C) 2011 Recurity Labs GmbH
  37785. //
  37786. // This library is free software; you can redistribute it and/or
  37787. // modify it under the terms of the GNU Lesser General Public
  37788. // License as published by the Free Software Foundation; either
  37789. // version 3.0 of the License, or (at your option) any later version.
  37790. //
  37791. // This library is distributed in the hope that it will be useful,
  37792. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  37793. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  37794. // Lesser General Public License for more details.
  37795. //
  37796. // You should have received a copy of the GNU Lesser General Public
  37797. // License along with this library; if not, write to the Free Software
  37798. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  37799. /* eslint-disable no-console */
  37800. /**
  37801. * This object contains utility functions
  37802. * @requires email-addresses
  37803. * @requires web-stream-tools
  37804. * @requires config
  37805. * @requires encoding/base64
  37806. * @module util
  37807. */
  37808. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  37809. },{"./config":79,"./encoding/base64":112,"./util":158,"email-addresses":33,"web-stream-tools":75}],159:[function(require,module,exports){
  37810. 'use strict';
  37811. Object.defineProperty(exports, "__esModule", {
  37812. value: true
  37813. });
  37814. var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); // OpenPGP.js - An OpenPGP implementation in javascript
  37815. // Copyright (C) 2018 Wiktor Kwapisiewicz
  37816. //
  37817. // This library is free software; you can redistribute it and/or
  37818. // modify it under the terms of the GNU Lesser General Public
  37819. // License as published by the Free Software Foundation; either
  37820. // version 3.0 of the License, or (at your option) any later version.
  37821. //
  37822. // This library is distributed in the hope that it will be useful,
  37823. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  37824. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  37825. // Lesser General Public License for more details.
  37826. //
  37827. // You should have received a copy of the GNU Lesser General Public
  37828. // License along with this library; if not, write to the Free Software
  37829. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  37830. /**
  37831. * @fileoverview This class implements a client for the Web Key Directory (wkd) protocol
  37832. * in order to lookup keys on designated servers.
  37833. * See: https://datatracker.ietf.org/doc/draft-koch-openpgp-webkey-service/
  37834. * @module wkd
  37835. */
  37836. var _util = require('./util');
  37837. var _util2 = _interopRequireDefault(_util);
  37838. var _crypto = require('./crypto');
  37839. var _crypto2 = _interopRequireDefault(_crypto);
  37840. var _key = require('./key');
  37841. var keyMod = _interopRequireWildcard(_key);
  37842. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  37843. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  37844. /**
  37845. * Initialize the WKD client
  37846. * @constructor
  37847. */
  37848. function WKD() {
  37849. this._fetch = typeof window !== 'undefined' ? window.fetch : require('node-fetch');
  37850. }
  37851. /**
  37852. * Search for a public key using Web Key Directory protocol.
  37853. * @param {String} options.email User's email.
  37854. * @param {Boolean} options.rawBytes Returns Uint8Array instead of parsed key.
  37855. * @returns {Promise<Uint8Array|
  37856. * {keys: Array<module:key.Key>,
  37857. * err: (Array<Error>|null)}>} The public key.
  37858. * @async
  37859. */
  37860. WKD.prototype.lookup = async function (options) {
  37861. const fetch = this._fetch;
  37862. if (!options.email) {
  37863. throw new Error('You must provide an email parameter!');
  37864. }
  37865. if (!_util2.default.isEmailAddress(options.email)) {
  37866. throw new Error('Invalid e-mail address.');
  37867. }
  37868. var _$exec = /(.*)@(.*)/.exec(options.email),
  37869. _$exec2 = _slicedToArray(_$exec, 3);
  37870. const localPart = _$exec2[1],
  37871. domain = _$exec2[2];
  37872. const localEncoded = _util2.default.encodeZBase32((await _crypto2.default.hash.sha1(_util2.default.str_to_Uint8Array(localPart.toLowerCase()))));
  37873. const url = `https://${domain}/.well-known/openpgpkey/hu/${localEncoded}`;
  37874. return fetch(url).then(function (response) {
  37875. if (response.status === 200) {
  37876. return response.arrayBuffer();
  37877. }
  37878. }).then(function (publicKey) {
  37879. if (publicKey) {
  37880. const rawBytes = new Uint8Array(publicKey);
  37881. if (options.rawBytes) {
  37882. return rawBytes;
  37883. }
  37884. return keyMod.read(rawBytes);
  37885. }
  37886. });
  37887. };
  37888. exports.default = WKD;
  37889. },{"./crypto":94,"./key":118,"./util":158,"node-fetch":"node-fetch"}],160:[function(require,module,exports){
  37890. 'use strict';
  37891. Object.defineProperty(exports, "__esModule", {
  37892. value: true
  37893. });
  37894. var _util = require('../util.js');
  37895. var _util2 = _interopRequireDefault(_util);
  37896. var _config = require('../config');
  37897. var _config2 = _interopRequireDefault(_config);
  37898. var _crypto = require('../crypto');
  37899. var _crypto2 = _interopRequireDefault(_crypto);
  37900. var _packet = require('../packet');
  37901. var _packet2 = _interopRequireDefault(_packet);
  37902. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  37903. /**
  37904. * Initializes a new proxy and loads the web worker
  37905. * @param {String} path The path to the worker or 'openpgp.worker.js' by default
  37906. * @param {Number} n number of workers to initialize if path given
  37907. * @param {Object} config config The worker configuration
  37908. * @param {Array<Object>} worker alternative to path parameter: web worker initialized with 'openpgp.worker.js'
  37909. * @constructor
  37910. */
  37911. // GPG4Browsers - An OpenPGP implementation in javascript
  37912. // Copyright (C) 2011 Recurity Labs GmbH
  37913. //
  37914. // This library is free software; you can redistribute it and/or
  37915. // modify it under the terms of the GNU Lesser General Public
  37916. // License as published by the Free Software Foundation; either
  37917. // version 3.0 of the License, or (at your option) any later version.
  37918. //
  37919. // This library is distributed in the hope that it will be useful,
  37920. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  37921. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  37922. // Lesser General Public License for more details.
  37923. //
  37924. // You should have received a copy of the GNU Lesser General Public
  37925. // License along with this library; if not, write to the Free Software
  37926. // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  37927. /**
  37928. * @fileoverview Provides functions for maintaining browser workers
  37929. * @see module:openpgp.initWorker
  37930. * @see module:openpgp.getWorker
  37931. * @see module:openpgp.destroyWorker
  37932. * @see module:worker/worker
  37933. * @requires util
  37934. * @requires config
  37935. * @requires crypto
  37936. * @requires packet
  37937. * @module worker/async_proxy
  37938. */
  37939. function AsyncProxy({ path = 'openpgp.worker.js', n = 1, workers = [], config } = {}) {
  37940. /**
  37941. * Message handling
  37942. */
  37943. const handleMessage = workerId => event => {
  37944. const msg = event.data;
  37945. switch (msg.event) {
  37946. case 'loaded':
  37947. this.workers[workerId].loadedResolve(true);
  37948. break;
  37949. case 'method-return':
  37950. if (msg.err) {
  37951. // fail
  37952. const err = new Error(msg.err);
  37953. // add worker stack
  37954. err.workerStack = msg.stack;
  37955. this.tasks[msg.id].reject(err);
  37956. } else {
  37957. // success
  37958. this.tasks[msg.id].resolve(msg.data);
  37959. }
  37960. delete this.tasks[msg.id];
  37961. this.workers[workerId].requests--;
  37962. break;
  37963. case 'request-seed':
  37964. this.seedRandom(workerId, msg.amount);
  37965. break;
  37966. default:
  37967. throw new Error('Unknown Worker Event.');
  37968. }
  37969. };
  37970. if (workers.length) {
  37971. this.workers = workers;
  37972. } else {
  37973. this.workers = [];
  37974. while (this.workers.length < n) {
  37975. this.workers.push(new Worker(path));
  37976. }
  37977. }
  37978. let workerId = 0;
  37979. this.workers.forEach(worker => {
  37980. worker.loadedPromise = new Promise(resolve => {
  37981. worker.loadedResolve = resolve;
  37982. });
  37983. worker.requests = 0;
  37984. worker.onmessage = handleMessage(workerId++);
  37985. worker.onerror = e => {
  37986. worker.loadedResolve(false);
  37987. console.error('Unhandled error in openpgp worker: ' + e.message + ' (' + e.filename + ':' + e.lineno + ')');
  37988. return false;
  37989. };
  37990. if (config) {
  37991. worker.postMessage({ event: 'configure', config });
  37992. }
  37993. });
  37994. // Cannot rely on task order being maintained, use object keyed by request ID to track tasks
  37995. this.tasks = {};
  37996. this.currentID = 0;
  37997. }
  37998. /**
  37999. * Returns a promise that resolves when all workers have finished loading
  38000. * @returns {Promise<Boolean>} Resolves to true if all workers have loaded succesfully; false otherwise
  38001. */
  38002. AsyncProxy.prototype.loaded = async function () {
  38003. const loaded = await Promise.all(this.workers.map(worker => worker.loadedPromise));
  38004. return loaded.every(Boolean);
  38005. };
  38006. /**
  38007. * Get new request ID
  38008. * @returns {integer} New unique request ID
  38009. */
  38010. AsyncProxy.prototype.getID = function () {
  38011. return this.currentID++;
  38012. };
  38013. /**
  38014. * Send message to worker with random data
  38015. * @param {Integer} size Number of bytes to send
  38016. * @async
  38017. */
  38018. AsyncProxy.prototype.seedRandom = async function (workerId, size) {
  38019. const buf = await _crypto2.default.random.getRandomBytes(size);
  38020. this.workers[workerId].postMessage({ event: 'seed-random', buf }, _util2.default.getTransferables(buf, true));
  38021. };
  38022. /**
  38023. * Terminates the workers
  38024. */
  38025. AsyncProxy.prototype.terminate = function () {
  38026. this.workers.forEach(worker => {
  38027. worker.terminate();
  38028. });
  38029. };
  38030. /**
  38031. * Generic proxy function that handles all commands from the public api.
  38032. * @param {String} method the public api function to be delegated to the worker thread
  38033. * @param {Object} options the api function's options
  38034. * @returns {Promise} see the corresponding public api functions for their return types
  38035. * @async
  38036. */
  38037. AsyncProxy.prototype.delegate = function (method, options) {
  38038. const id = this.getID();
  38039. const requests = this.workers.map(worker => worker.requests);
  38040. const minRequests = Math.min(...requests);
  38041. let workerId = 0;
  38042. for (; workerId < this.workers.length; workerId++) {
  38043. if (this.workers[workerId].requests === minRequests) {
  38044. break;
  38045. }
  38046. }
  38047. return new Promise((_resolve, reject) => {
  38048. // clone packets (for web worker structured cloning algorithm)
  38049. this.workers[workerId].postMessage({ id: id, event: method, options: _packet2.default.clone.clonePackets(options) }, _util2.default.getTransferables(options, _config2.default.zero_copy));
  38050. this.workers[workerId].requests++;
  38051. // remember to handle parsing cloned packets from worker
  38052. this.tasks[id] = { resolve: data => _resolve(_packet2.default.clone.parseClonedPackets(_util2.default.restoreStreams(data), method)), reject };
  38053. });
  38054. };
  38055. exports.default = AsyncProxy;
  38056. },{"../config":79,"../crypto":94,"../packet":131,"../util.js":158}]},{},[115])(115)
  38057. });