dep-0e948eb3.js 854 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169
  1. 'use strict';
  2. var build = require('./dep-1be34a63.js');
  3. var require$$1 = require('crypto');
  4. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e['default'] : e; }
  5. var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1);
  6. var selfsigned = {};
  7. /**
  8. * Node.js module for Forge.
  9. *
  10. * @author Dave Longley
  11. *
  12. * Copyright 2011-2016 Digital Bazaar, Inc.
  13. */
  14. var forge$F = {
  15. // default options
  16. options: {
  17. usePureJavaScript: false
  18. }
  19. };
  20. /**
  21. * Base-N/Base-X encoding/decoding functions.
  22. *
  23. * Original implementation from base-x:
  24. * https://github.com/cryptocoinjs/base-x
  25. *
  26. * Which is MIT licensed:
  27. *
  28. * The MIT License (MIT)
  29. *
  30. * Copyright base-x contributors (c) 2016
  31. *
  32. * Permission is hereby granted, free of charge, to any person obtaining a copy
  33. * of this software and associated documentation files (the "Software"), to deal
  34. * in the Software without restriction, including without limitation the rights
  35. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  36. * copies of the Software, and to permit persons to whom the Software is
  37. * furnished to do so, subject to the following conditions:
  38. *
  39. * The above copyright notice and this permission notice shall be included in
  40. * all copies or substantial portions of the Software.
  41. *
  42. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  43. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  44. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  45. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  46. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  47. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  48. * DEALINGS IN THE SOFTWARE.
  49. */
  50. var api = {};
  51. var baseN$1 = api;
  52. // baseN alphabet indexes
  53. var _reverseAlphabets = {};
  54. /**
  55. * BaseN-encodes a Uint8Array using the given alphabet.
  56. *
  57. * @param input the Uint8Array to encode.
  58. * @param maxline the maximum number of encoded characters per line to use,
  59. * defaults to none.
  60. *
  61. * @return the baseN-encoded output string.
  62. */
  63. api.encode = function(input, alphabet, maxline) {
  64. if(typeof alphabet !== 'string') {
  65. throw new TypeError('"alphabet" must be a string.');
  66. }
  67. if(maxline !== undefined && typeof maxline !== 'number') {
  68. throw new TypeError('"maxline" must be a number.');
  69. }
  70. var output = '';
  71. if(!(input instanceof Uint8Array)) {
  72. // assume forge byte buffer
  73. output = _encodeWithByteBuffer(input, alphabet);
  74. } else {
  75. var i = 0;
  76. var base = alphabet.length;
  77. var first = alphabet.charAt(0);
  78. var digits = [0];
  79. for(i = 0; i < input.length; ++i) {
  80. for(var j = 0, carry = input[i]; j < digits.length; ++j) {
  81. carry += digits[j] << 8;
  82. digits[j] = carry % base;
  83. carry = (carry / base) | 0;
  84. }
  85. while(carry > 0) {
  86. digits.push(carry % base);
  87. carry = (carry / base) | 0;
  88. }
  89. }
  90. // deal with leading zeros
  91. for(i = 0; input[i] === 0 && i < input.length - 1; ++i) {
  92. output += first;
  93. }
  94. // convert digits to a string
  95. for(i = digits.length - 1; i >= 0; --i) {
  96. output += alphabet[digits[i]];
  97. }
  98. }
  99. if(maxline) {
  100. var regex = new RegExp('.{1,' + maxline + '}', 'g');
  101. output = output.match(regex).join('\r\n');
  102. }
  103. return output;
  104. };
  105. /**
  106. * Decodes a baseN-encoded (using the given alphabet) string to a
  107. * Uint8Array.
  108. *
  109. * @param input the baseN-encoded input string.
  110. *
  111. * @return the Uint8Array.
  112. */
  113. api.decode = function(input, alphabet) {
  114. if(typeof input !== 'string') {
  115. throw new TypeError('"input" must be a string.');
  116. }
  117. if(typeof alphabet !== 'string') {
  118. throw new TypeError('"alphabet" must be a string.');
  119. }
  120. var table = _reverseAlphabets[alphabet];
  121. if(!table) {
  122. // compute reverse alphabet
  123. table = _reverseAlphabets[alphabet] = [];
  124. for(var i = 0; i < alphabet.length; ++i) {
  125. table[alphabet.charCodeAt(i)] = i;
  126. }
  127. }
  128. // remove whitespace characters
  129. input = input.replace(/\s/g, '');
  130. var base = alphabet.length;
  131. var first = alphabet.charAt(0);
  132. var bytes = [0];
  133. for(var i = 0; i < input.length; i++) {
  134. var value = table[input.charCodeAt(i)];
  135. if(value === undefined) {
  136. return;
  137. }
  138. for(var j = 0, carry = value; j < bytes.length; ++j) {
  139. carry += bytes[j] * base;
  140. bytes[j] = carry & 0xff;
  141. carry >>= 8;
  142. }
  143. while(carry > 0) {
  144. bytes.push(carry & 0xff);
  145. carry >>= 8;
  146. }
  147. }
  148. // deal with leading zeros
  149. for(var k = 0; input[k] === first && k < input.length - 1; ++k) {
  150. bytes.push(0);
  151. }
  152. if(typeof Buffer !== 'undefined') {
  153. return Buffer.from(bytes.reverse());
  154. }
  155. return new Uint8Array(bytes.reverse());
  156. };
  157. function _encodeWithByteBuffer(input, alphabet) {
  158. var i = 0;
  159. var base = alphabet.length;
  160. var first = alphabet.charAt(0);
  161. var digits = [0];
  162. for(i = 0; i < input.length(); ++i) {
  163. for(var j = 0, carry = input.at(i); j < digits.length; ++j) {
  164. carry += digits[j] << 8;
  165. digits[j] = carry % base;
  166. carry = (carry / base) | 0;
  167. }
  168. while(carry > 0) {
  169. digits.push(carry % base);
  170. carry = (carry / base) | 0;
  171. }
  172. }
  173. var output = '';
  174. // deal with leading zeros
  175. for(i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) {
  176. output += first;
  177. }
  178. // convert digits to a string
  179. for(i = digits.length - 1; i >= 0; --i) {
  180. output += alphabet[digits[i]];
  181. }
  182. return output;
  183. }
  184. /**
  185. * Utility functions for web applications.
  186. *
  187. * @author Dave Longley
  188. *
  189. * Copyright (c) 2010-2018 Digital Bazaar, Inc.
  190. */
  191. var forge$E = forge$F;
  192. var baseN = baseN$1;
  193. /* Utilities API */
  194. var util$1 = forge$E.util = forge$E.util || {};
  195. // define setImmediate and nextTick
  196. (function() {
  197. // use native nextTick (unless we're in webpack)
  198. // webpack (or better node-libs-browser polyfill) sets process.browser.
  199. // this way we can detect webpack properly
  200. if(typeof process !== 'undefined' && process.nextTick && !process.browser) {
  201. util$1.nextTick = process.nextTick;
  202. if(typeof setImmediate === 'function') {
  203. util$1.setImmediate = setImmediate;
  204. } else {
  205. // polyfill setImmediate with nextTick, older versions of node
  206. // (those w/o setImmediate) won't totally starve IO
  207. util$1.setImmediate = util$1.nextTick;
  208. }
  209. return;
  210. }
  211. // polyfill nextTick with native setImmediate
  212. if(typeof setImmediate === 'function') {
  213. util$1.setImmediate = function() { return setImmediate.apply(undefined, arguments); };
  214. util$1.nextTick = function(callback) {
  215. return setImmediate(callback);
  216. };
  217. return;
  218. }
  219. /* Note: A polyfill upgrade pattern is used here to allow combining
  220. polyfills. For example, MutationObserver is fast, but blocks UI updates,
  221. so it needs to allow UI updates periodically, so it falls back on
  222. postMessage or setTimeout. */
  223. // polyfill with setTimeout
  224. util$1.setImmediate = function(callback) {
  225. setTimeout(callback, 0);
  226. };
  227. // upgrade polyfill to use postMessage
  228. if(typeof window !== 'undefined' &&
  229. typeof window.postMessage === 'function') {
  230. var msg = 'forge.setImmediate';
  231. var callbacks = [];
  232. util$1.setImmediate = function(callback) {
  233. callbacks.push(callback);
  234. // only send message when one hasn't been sent in
  235. // the current turn of the event loop
  236. if(callbacks.length === 1) {
  237. window.postMessage(msg, '*');
  238. }
  239. };
  240. function handler(event) {
  241. if(event.source === window && event.data === msg) {
  242. event.stopPropagation();
  243. var copy = callbacks.slice();
  244. callbacks.length = 0;
  245. copy.forEach(function(callback) {
  246. callback();
  247. });
  248. }
  249. }
  250. window.addEventListener('message', handler, true);
  251. }
  252. // upgrade polyfill to use MutationObserver
  253. if(typeof MutationObserver !== 'undefined') {
  254. // polyfill with MutationObserver
  255. var now = Date.now();
  256. var attr = true;
  257. var div = document.createElement('div');
  258. var callbacks = [];
  259. new MutationObserver(function() {
  260. var copy = callbacks.slice();
  261. callbacks.length = 0;
  262. copy.forEach(function(callback) {
  263. callback();
  264. });
  265. }).observe(div, {attributes: true});
  266. var oldSetImmediate = util$1.setImmediate;
  267. util$1.setImmediate = function(callback) {
  268. if(Date.now() - now > 15) {
  269. now = Date.now();
  270. oldSetImmediate(callback);
  271. } else {
  272. callbacks.push(callback);
  273. // only trigger observer when it hasn't been triggered in
  274. // the current turn of the event loop
  275. if(callbacks.length === 1) {
  276. div.setAttribute('a', attr = !attr);
  277. }
  278. }
  279. };
  280. }
  281. util$1.nextTick = util$1.setImmediate;
  282. })();
  283. // check if running under Node.js
  284. util$1.isNodejs =
  285. typeof process !== 'undefined' && process.versions && process.versions.node;
  286. // 'self' will also work in Web Workers (instance of WorkerGlobalScope) while
  287. // it will point to `window` in the main thread.
  288. // To remain compatible with older browsers, we fall back to 'window' if 'self'
  289. // is not available.
  290. util$1.globalScope = (function() {
  291. if(util$1.isNodejs) {
  292. return build.commonjsGlobal;
  293. }
  294. return typeof self === 'undefined' ? window : self;
  295. })();
  296. // define isArray
  297. util$1.isArray = Array.isArray || function(x) {
  298. return Object.prototype.toString.call(x) === '[object Array]';
  299. };
  300. // define isArrayBuffer
  301. util$1.isArrayBuffer = function(x) {
  302. return typeof ArrayBuffer !== 'undefined' && x instanceof ArrayBuffer;
  303. };
  304. // define isArrayBufferView
  305. util$1.isArrayBufferView = function(x) {
  306. return x && util$1.isArrayBuffer(x.buffer) && x.byteLength !== undefined;
  307. };
  308. /**
  309. * Ensure a bits param is 8, 16, 24, or 32. Used to validate input for
  310. * algorithms where bit manipulation, JavaScript limitations, and/or algorithm
  311. * design only allow for byte operations of a limited size.
  312. *
  313. * @param n number of bits.
  314. *
  315. * Throw Error if n invalid.
  316. */
  317. function _checkBitsParam(n) {
  318. if(!(n === 8 || n === 16 || n === 24 || n === 32)) {
  319. throw new Error('Only 8, 16, 24, or 32 bits supported: ' + n);
  320. }
  321. }
  322. // TODO: set ByteBuffer to best available backing
  323. util$1.ByteBuffer = ByteStringBuffer;
  324. /** Buffer w/BinaryString backing */
  325. /**
  326. * Constructor for a binary string backed byte buffer.
  327. *
  328. * @param [b] the bytes to wrap (either encoded as string, one byte per
  329. * character, or as an ArrayBuffer or Typed Array).
  330. */
  331. function ByteStringBuffer(b) {
  332. // TODO: update to match DataBuffer API
  333. // the data in this buffer
  334. this.data = '';
  335. // the pointer for reading from this buffer
  336. this.read = 0;
  337. if(typeof b === 'string') {
  338. this.data = b;
  339. } else if(util$1.isArrayBuffer(b) || util$1.isArrayBufferView(b)) {
  340. if(typeof Buffer !== 'undefined' && b instanceof Buffer) {
  341. this.data = b.toString('binary');
  342. } else {
  343. // convert native buffer to forge buffer
  344. // FIXME: support native buffers internally instead
  345. var arr = new Uint8Array(b);
  346. try {
  347. this.data = String.fromCharCode.apply(null, arr);
  348. } catch(e) {
  349. for(var i = 0; i < arr.length; ++i) {
  350. this.putByte(arr[i]);
  351. }
  352. }
  353. }
  354. } else if(b instanceof ByteStringBuffer ||
  355. (typeof b === 'object' && typeof b.data === 'string' &&
  356. typeof b.read === 'number')) {
  357. // copy existing buffer
  358. this.data = b.data;
  359. this.read = b.read;
  360. }
  361. // used for v8 optimization
  362. this._constructedStringLength = 0;
  363. }
  364. util$1.ByteStringBuffer = ByteStringBuffer;
  365. /* Note: This is an optimization for V8-based browsers. When V8 concatenates
  366. a string, the strings are only joined logically using a "cons string" or
  367. "constructed/concatenated string". These containers keep references to one
  368. another and can result in very large memory usage. For example, if a 2MB
  369. string is constructed by concatenating 4 bytes together at a time, the
  370. memory usage will be ~44MB; so ~22x increase. The strings are only joined
  371. together when an operation requiring their joining takes place, such as
  372. substr(). This function is called when adding data to this buffer to ensure
  373. these types of strings are periodically joined to reduce the memory
  374. footprint. */
  375. var _MAX_CONSTRUCTED_STRING_LENGTH = 4096;
  376. util$1.ByteStringBuffer.prototype._optimizeConstructedString = function(x) {
  377. this._constructedStringLength += x;
  378. if(this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) {
  379. // this substr() should cause the constructed string to join
  380. this.data.substr(0, 1);
  381. this._constructedStringLength = 0;
  382. }
  383. };
  384. /**
  385. * Gets the number of bytes in this buffer.
  386. *
  387. * @return the number of bytes in this buffer.
  388. */
  389. util$1.ByteStringBuffer.prototype.length = function() {
  390. return this.data.length - this.read;
  391. };
  392. /**
  393. * Gets whether or not this buffer is empty.
  394. *
  395. * @return true if this buffer is empty, false if not.
  396. */
  397. util$1.ByteStringBuffer.prototype.isEmpty = function() {
  398. return this.length() <= 0;
  399. };
  400. /**
  401. * Puts a byte in this buffer.
  402. *
  403. * @param b the byte to put.
  404. *
  405. * @return this buffer.
  406. */
  407. util$1.ByteStringBuffer.prototype.putByte = function(b) {
  408. return this.putBytes(String.fromCharCode(b));
  409. };
  410. /**
  411. * Puts a byte in this buffer N times.
  412. *
  413. * @param b the byte to put.
  414. * @param n the number of bytes of value b to put.
  415. *
  416. * @return this buffer.
  417. */
  418. util$1.ByteStringBuffer.prototype.fillWithByte = function(b, n) {
  419. b = String.fromCharCode(b);
  420. var d = this.data;
  421. while(n > 0) {
  422. if(n & 1) {
  423. d += b;
  424. }
  425. n >>>= 1;
  426. if(n > 0) {
  427. b += b;
  428. }
  429. }
  430. this.data = d;
  431. this._optimizeConstructedString(n);
  432. return this;
  433. };
  434. /**
  435. * Puts bytes in this buffer.
  436. *
  437. * @param bytes the bytes (as a binary encoded string) to put.
  438. *
  439. * @return this buffer.
  440. */
  441. util$1.ByteStringBuffer.prototype.putBytes = function(bytes) {
  442. this.data += bytes;
  443. this._optimizeConstructedString(bytes.length);
  444. return this;
  445. };
  446. /**
  447. * Puts a UTF-16 encoded string into this buffer.
  448. *
  449. * @param str the string to put.
  450. *
  451. * @return this buffer.
  452. */
  453. util$1.ByteStringBuffer.prototype.putString = function(str) {
  454. return this.putBytes(util$1.encodeUtf8(str));
  455. };
  456. /**
  457. * Puts a 16-bit integer in this buffer in big-endian order.
  458. *
  459. * @param i the 16-bit integer.
  460. *
  461. * @return this buffer.
  462. */
  463. util$1.ByteStringBuffer.prototype.putInt16 = function(i) {
  464. return this.putBytes(
  465. String.fromCharCode(i >> 8 & 0xFF) +
  466. String.fromCharCode(i & 0xFF));
  467. };
  468. /**
  469. * Puts a 24-bit integer in this buffer in big-endian order.
  470. *
  471. * @param i the 24-bit integer.
  472. *
  473. * @return this buffer.
  474. */
  475. util$1.ByteStringBuffer.prototype.putInt24 = function(i) {
  476. return this.putBytes(
  477. String.fromCharCode(i >> 16 & 0xFF) +
  478. String.fromCharCode(i >> 8 & 0xFF) +
  479. String.fromCharCode(i & 0xFF));
  480. };
  481. /**
  482. * Puts a 32-bit integer in this buffer in big-endian order.
  483. *
  484. * @param i the 32-bit integer.
  485. *
  486. * @return this buffer.
  487. */
  488. util$1.ByteStringBuffer.prototype.putInt32 = function(i) {
  489. return this.putBytes(
  490. String.fromCharCode(i >> 24 & 0xFF) +
  491. String.fromCharCode(i >> 16 & 0xFF) +
  492. String.fromCharCode(i >> 8 & 0xFF) +
  493. String.fromCharCode(i & 0xFF));
  494. };
  495. /**
  496. * Puts a 16-bit integer in this buffer in little-endian order.
  497. *
  498. * @param i the 16-bit integer.
  499. *
  500. * @return this buffer.
  501. */
  502. util$1.ByteStringBuffer.prototype.putInt16Le = function(i) {
  503. return this.putBytes(
  504. String.fromCharCode(i & 0xFF) +
  505. String.fromCharCode(i >> 8 & 0xFF));
  506. };
  507. /**
  508. * Puts a 24-bit integer in this buffer in little-endian order.
  509. *
  510. * @param i the 24-bit integer.
  511. *
  512. * @return this buffer.
  513. */
  514. util$1.ByteStringBuffer.prototype.putInt24Le = function(i) {
  515. return this.putBytes(
  516. String.fromCharCode(i & 0xFF) +
  517. String.fromCharCode(i >> 8 & 0xFF) +
  518. String.fromCharCode(i >> 16 & 0xFF));
  519. };
  520. /**
  521. * Puts a 32-bit integer in this buffer in little-endian order.
  522. *
  523. * @param i the 32-bit integer.
  524. *
  525. * @return this buffer.
  526. */
  527. util$1.ByteStringBuffer.prototype.putInt32Le = function(i) {
  528. return this.putBytes(
  529. String.fromCharCode(i & 0xFF) +
  530. String.fromCharCode(i >> 8 & 0xFF) +
  531. String.fromCharCode(i >> 16 & 0xFF) +
  532. String.fromCharCode(i >> 24 & 0xFF));
  533. };
  534. /**
  535. * Puts an n-bit integer in this buffer in big-endian order.
  536. *
  537. * @param i the n-bit integer.
  538. * @param n the number of bits in the integer (8, 16, 24, or 32).
  539. *
  540. * @return this buffer.
  541. */
  542. util$1.ByteStringBuffer.prototype.putInt = function(i, n) {
  543. _checkBitsParam(n);
  544. var bytes = '';
  545. do {
  546. n -= 8;
  547. bytes += String.fromCharCode((i >> n) & 0xFF);
  548. } while(n > 0);
  549. return this.putBytes(bytes);
  550. };
  551. /**
  552. * Puts a signed n-bit integer in this buffer in big-endian order. Two's
  553. * complement representation is used.
  554. *
  555. * @param i the n-bit integer.
  556. * @param n the number of bits in the integer (8, 16, 24, or 32).
  557. *
  558. * @return this buffer.
  559. */
  560. util$1.ByteStringBuffer.prototype.putSignedInt = function(i, n) {
  561. // putInt checks n
  562. if(i < 0) {
  563. i += 2 << (n - 1);
  564. }
  565. return this.putInt(i, n);
  566. };
  567. /**
  568. * Puts the given buffer into this buffer.
  569. *
  570. * @param buffer the buffer to put into this one.
  571. *
  572. * @return this buffer.
  573. */
  574. util$1.ByteStringBuffer.prototype.putBuffer = function(buffer) {
  575. return this.putBytes(buffer.getBytes());
  576. };
  577. /**
  578. * Gets a byte from this buffer and advances the read pointer by 1.
  579. *
  580. * @return the byte.
  581. */
  582. util$1.ByteStringBuffer.prototype.getByte = function() {
  583. return this.data.charCodeAt(this.read++);
  584. };
  585. /**
  586. * Gets a uint16 from this buffer in big-endian order and advances the read
  587. * pointer by 2.
  588. *
  589. * @return the uint16.
  590. */
  591. util$1.ByteStringBuffer.prototype.getInt16 = function() {
  592. var rval = (
  593. this.data.charCodeAt(this.read) << 8 ^
  594. this.data.charCodeAt(this.read + 1));
  595. this.read += 2;
  596. return rval;
  597. };
  598. /**
  599. * Gets a uint24 from this buffer in big-endian order and advances the read
  600. * pointer by 3.
  601. *
  602. * @return the uint24.
  603. */
  604. util$1.ByteStringBuffer.prototype.getInt24 = function() {
  605. var rval = (
  606. this.data.charCodeAt(this.read) << 16 ^
  607. this.data.charCodeAt(this.read + 1) << 8 ^
  608. this.data.charCodeAt(this.read + 2));
  609. this.read += 3;
  610. return rval;
  611. };
  612. /**
  613. * Gets a uint32 from this buffer in big-endian order and advances the read
  614. * pointer by 4.
  615. *
  616. * @return the word.
  617. */
  618. util$1.ByteStringBuffer.prototype.getInt32 = function() {
  619. var rval = (
  620. this.data.charCodeAt(this.read) << 24 ^
  621. this.data.charCodeAt(this.read + 1) << 16 ^
  622. this.data.charCodeAt(this.read + 2) << 8 ^
  623. this.data.charCodeAt(this.read + 3));
  624. this.read += 4;
  625. return rval;
  626. };
  627. /**
  628. * Gets a uint16 from this buffer in little-endian order and advances the read
  629. * pointer by 2.
  630. *
  631. * @return the uint16.
  632. */
  633. util$1.ByteStringBuffer.prototype.getInt16Le = function() {
  634. var rval = (
  635. this.data.charCodeAt(this.read) ^
  636. this.data.charCodeAt(this.read + 1) << 8);
  637. this.read += 2;
  638. return rval;
  639. };
  640. /**
  641. * Gets a uint24 from this buffer in little-endian order and advances the read
  642. * pointer by 3.
  643. *
  644. * @return the uint24.
  645. */
  646. util$1.ByteStringBuffer.prototype.getInt24Le = function() {
  647. var rval = (
  648. this.data.charCodeAt(this.read) ^
  649. this.data.charCodeAt(this.read + 1) << 8 ^
  650. this.data.charCodeAt(this.read + 2) << 16);
  651. this.read += 3;
  652. return rval;
  653. };
  654. /**
  655. * Gets a uint32 from this buffer in little-endian order and advances the read
  656. * pointer by 4.
  657. *
  658. * @return the word.
  659. */
  660. util$1.ByteStringBuffer.prototype.getInt32Le = function() {
  661. var rval = (
  662. this.data.charCodeAt(this.read) ^
  663. this.data.charCodeAt(this.read + 1) << 8 ^
  664. this.data.charCodeAt(this.read + 2) << 16 ^
  665. this.data.charCodeAt(this.read + 3) << 24);
  666. this.read += 4;
  667. return rval;
  668. };
  669. /**
  670. * Gets an n-bit integer from this buffer in big-endian order and advances the
  671. * read pointer by ceil(n/8).
  672. *
  673. * @param n the number of bits in the integer (8, 16, 24, or 32).
  674. *
  675. * @return the integer.
  676. */
  677. util$1.ByteStringBuffer.prototype.getInt = function(n) {
  678. _checkBitsParam(n);
  679. var rval = 0;
  680. do {
  681. // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits.
  682. rval = (rval << 8) + this.data.charCodeAt(this.read++);
  683. n -= 8;
  684. } while(n > 0);
  685. return rval;
  686. };
  687. /**
  688. * Gets a signed n-bit integer from this buffer in big-endian order, using
  689. * two's complement, and advances the read pointer by n/8.
  690. *
  691. * @param n the number of bits in the integer (8, 16, 24, or 32).
  692. *
  693. * @return the integer.
  694. */
  695. util$1.ByteStringBuffer.prototype.getSignedInt = function(n) {
  696. // getInt checks n
  697. var x = this.getInt(n);
  698. var max = 2 << (n - 2);
  699. if(x >= max) {
  700. x -= max << 1;
  701. }
  702. return x;
  703. };
  704. /**
  705. * Reads bytes out as a binary encoded string and clears them from the
  706. * buffer. Note that the resulting string is binary encoded (in node.js this
  707. * encoding is referred to as `binary`, it is *not* `utf8`).
  708. *
  709. * @param count the number of bytes to read, undefined or null for all.
  710. *
  711. * @return a binary encoded string of bytes.
  712. */
  713. util$1.ByteStringBuffer.prototype.getBytes = function(count) {
  714. var rval;
  715. if(count) {
  716. // read count bytes
  717. count = Math.min(this.length(), count);
  718. rval = this.data.slice(this.read, this.read + count);
  719. this.read += count;
  720. } else if(count === 0) {
  721. rval = '';
  722. } else {
  723. // read all bytes, optimize to only copy when needed
  724. rval = (this.read === 0) ? this.data : this.data.slice(this.read);
  725. this.clear();
  726. }
  727. return rval;
  728. };
  729. /**
  730. * Gets a binary encoded string of the bytes from this buffer without
  731. * modifying the read pointer.
  732. *
  733. * @param count the number of bytes to get, omit to get all.
  734. *
  735. * @return a string full of binary encoded characters.
  736. */
  737. util$1.ByteStringBuffer.prototype.bytes = function(count) {
  738. return (typeof(count) === 'undefined' ?
  739. this.data.slice(this.read) :
  740. this.data.slice(this.read, this.read + count));
  741. };
  742. /**
  743. * Gets a byte at the given index without modifying the read pointer.
  744. *
  745. * @param i the byte index.
  746. *
  747. * @return the byte.
  748. */
  749. util$1.ByteStringBuffer.prototype.at = function(i) {
  750. return this.data.charCodeAt(this.read + i);
  751. };
  752. /**
  753. * Puts a byte at the given index without modifying the read pointer.
  754. *
  755. * @param i the byte index.
  756. * @param b the byte to put.
  757. *
  758. * @return this buffer.
  759. */
  760. util$1.ByteStringBuffer.prototype.setAt = function(i, b) {
  761. this.data = this.data.substr(0, this.read + i) +
  762. String.fromCharCode(b) +
  763. this.data.substr(this.read + i + 1);
  764. return this;
  765. };
  766. /**
  767. * Gets the last byte without modifying the read pointer.
  768. *
  769. * @return the last byte.
  770. */
  771. util$1.ByteStringBuffer.prototype.last = function() {
  772. return this.data.charCodeAt(this.data.length - 1);
  773. };
  774. /**
  775. * Creates a copy of this buffer.
  776. *
  777. * @return the copy.
  778. */
  779. util$1.ByteStringBuffer.prototype.copy = function() {
  780. var c = util$1.createBuffer(this.data);
  781. c.read = this.read;
  782. return c;
  783. };
  784. /**
  785. * Compacts this buffer.
  786. *
  787. * @return this buffer.
  788. */
  789. util$1.ByteStringBuffer.prototype.compact = function() {
  790. if(this.read > 0) {
  791. this.data = this.data.slice(this.read);
  792. this.read = 0;
  793. }
  794. return this;
  795. };
  796. /**
  797. * Clears this buffer.
  798. *
  799. * @return this buffer.
  800. */
  801. util$1.ByteStringBuffer.prototype.clear = function() {
  802. this.data = '';
  803. this.read = 0;
  804. return this;
  805. };
  806. /**
  807. * Shortens this buffer by triming bytes off of the end of this buffer.
  808. *
  809. * @param count the number of bytes to trim off.
  810. *
  811. * @return this buffer.
  812. */
  813. util$1.ByteStringBuffer.prototype.truncate = function(count) {
  814. var len = Math.max(0, this.length() - count);
  815. this.data = this.data.substr(this.read, len);
  816. this.read = 0;
  817. return this;
  818. };
  819. /**
  820. * Converts this buffer to a hexadecimal string.
  821. *
  822. * @return a hexadecimal string.
  823. */
  824. util$1.ByteStringBuffer.prototype.toHex = function() {
  825. var rval = '';
  826. for(var i = this.read; i < this.data.length; ++i) {
  827. var b = this.data.charCodeAt(i);
  828. if(b < 16) {
  829. rval += '0';
  830. }
  831. rval += b.toString(16);
  832. }
  833. return rval;
  834. };
  835. /**
  836. * Converts this buffer to a UTF-16 string (standard JavaScript string).
  837. *
  838. * @return a UTF-16 string.
  839. */
  840. util$1.ByteStringBuffer.prototype.toString = function() {
  841. return util$1.decodeUtf8(this.bytes());
  842. };
  843. /** End Buffer w/BinaryString backing */
  844. /** Buffer w/UInt8Array backing */
  845. /**
  846. * FIXME: Experimental. Do not use yet.
  847. *
  848. * Constructor for an ArrayBuffer-backed byte buffer.
  849. *
  850. * The buffer may be constructed from a string, an ArrayBuffer, DataView, or a
  851. * TypedArray.
  852. *
  853. * If a string is given, its encoding should be provided as an option,
  854. * otherwise it will default to 'binary'. A 'binary' string is encoded such
  855. * that each character is one byte in length and size.
  856. *
  857. * If an ArrayBuffer, DataView, or TypedArray is given, it will be used
  858. * *directly* without any copying. Note that, if a write to the buffer requires
  859. * more space, the buffer will allocate a new backing ArrayBuffer to
  860. * accommodate. The starting read and write offsets for the buffer may be
  861. * given as options.
  862. *
  863. * @param [b] the initial bytes for this buffer.
  864. * @param options the options to use:
  865. * [readOffset] the starting read offset to use (default: 0).
  866. * [writeOffset] the starting write offset to use (default: the
  867. * length of the first parameter).
  868. * [growSize] the minimum amount, in bytes, to grow the buffer by to
  869. * accommodate writes (default: 1024).
  870. * [encoding] the encoding ('binary', 'utf8', 'utf16', 'hex') for the
  871. * first parameter, if it is a string (default: 'binary').
  872. */
  873. function DataBuffer(b, options) {
  874. // default options
  875. options = options || {};
  876. // pointers for read from/write to buffer
  877. this.read = options.readOffset || 0;
  878. this.growSize = options.growSize || 1024;
  879. var isArrayBuffer = util$1.isArrayBuffer(b);
  880. var isArrayBufferView = util$1.isArrayBufferView(b);
  881. if(isArrayBuffer || isArrayBufferView) {
  882. // use ArrayBuffer directly
  883. if(isArrayBuffer) {
  884. this.data = new DataView(b);
  885. } else {
  886. // TODO: adjust read/write offset based on the type of view
  887. // or specify that this must be done in the options ... that the
  888. // offsets are byte-based
  889. this.data = new DataView(b.buffer, b.byteOffset, b.byteLength);
  890. }
  891. this.write = ('writeOffset' in options ?
  892. options.writeOffset : this.data.byteLength);
  893. return;
  894. }
  895. // initialize to empty array buffer and add any given bytes using putBytes
  896. this.data = new DataView(new ArrayBuffer(0));
  897. this.write = 0;
  898. if(b !== null && b !== undefined) {
  899. this.putBytes(b);
  900. }
  901. if('writeOffset' in options) {
  902. this.write = options.writeOffset;
  903. }
  904. }
  905. util$1.DataBuffer = DataBuffer;
  906. /**
  907. * Gets the number of bytes in this buffer.
  908. *
  909. * @return the number of bytes in this buffer.
  910. */
  911. util$1.DataBuffer.prototype.length = function() {
  912. return this.write - this.read;
  913. };
  914. /**
  915. * Gets whether or not this buffer is empty.
  916. *
  917. * @return true if this buffer is empty, false if not.
  918. */
  919. util$1.DataBuffer.prototype.isEmpty = function() {
  920. return this.length() <= 0;
  921. };
  922. /**
  923. * Ensures this buffer has enough empty space to accommodate the given number
  924. * of bytes. An optional parameter may be given that indicates a minimum
  925. * amount to grow the buffer if necessary. If the parameter is not given,
  926. * the buffer will be grown by some previously-specified default amount
  927. * or heuristic.
  928. *
  929. * @param amount the number of bytes to accommodate.
  930. * @param [growSize] the minimum amount, in bytes, to grow the buffer by if
  931. * necessary.
  932. */
  933. util$1.DataBuffer.prototype.accommodate = function(amount, growSize) {
  934. if(this.length() >= amount) {
  935. return this;
  936. }
  937. growSize = Math.max(growSize || this.growSize, amount);
  938. // grow buffer
  939. var src = new Uint8Array(
  940. this.data.buffer, this.data.byteOffset, this.data.byteLength);
  941. var dst = new Uint8Array(this.length() + growSize);
  942. dst.set(src);
  943. this.data = new DataView(dst.buffer);
  944. return this;
  945. };
  946. /**
  947. * Puts a byte in this buffer.
  948. *
  949. * @param b the byte to put.
  950. *
  951. * @return this buffer.
  952. */
  953. util$1.DataBuffer.prototype.putByte = function(b) {
  954. this.accommodate(1);
  955. this.data.setUint8(this.write++, b);
  956. return this;
  957. };
  958. /**
  959. * Puts a byte in this buffer N times.
  960. *
  961. * @param b the byte to put.
  962. * @param n the number of bytes of value b to put.
  963. *
  964. * @return this buffer.
  965. */
  966. util$1.DataBuffer.prototype.fillWithByte = function(b, n) {
  967. this.accommodate(n);
  968. for(var i = 0; i < n; ++i) {
  969. this.data.setUint8(b);
  970. }
  971. return this;
  972. };
  973. /**
  974. * Puts bytes in this buffer. The bytes may be given as a string, an
  975. * ArrayBuffer, a DataView, or a TypedArray.
  976. *
  977. * @param bytes the bytes to put.
  978. * @param [encoding] the encoding for the first parameter ('binary', 'utf8',
  979. * 'utf16', 'hex'), if it is a string (default: 'binary').
  980. *
  981. * @return this buffer.
  982. */
  983. util$1.DataBuffer.prototype.putBytes = function(bytes, encoding) {
  984. if(util$1.isArrayBufferView(bytes)) {
  985. var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
  986. var len = src.byteLength - src.byteOffset;
  987. this.accommodate(len);
  988. var dst = new Uint8Array(this.data.buffer, this.write);
  989. dst.set(src);
  990. this.write += len;
  991. return this;
  992. }
  993. if(util$1.isArrayBuffer(bytes)) {
  994. var src = new Uint8Array(bytes);
  995. this.accommodate(src.byteLength);
  996. var dst = new Uint8Array(this.data.buffer);
  997. dst.set(src, this.write);
  998. this.write += src.byteLength;
  999. return this;
  1000. }
  1001. // bytes is a util.DataBuffer or equivalent
  1002. if(bytes instanceof util$1.DataBuffer ||
  1003. (typeof bytes === 'object' &&
  1004. typeof bytes.read === 'number' && typeof bytes.write === 'number' &&
  1005. util$1.isArrayBufferView(bytes.data))) {
  1006. var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length());
  1007. this.accommodate(src.byteLength);
  1008. var dst = new Uint8Array(bytes.data.byteLength, this.write);
  1009. dst.set(src);
  1010. this.write += src.byteLength;
  1011. return this;
  1012. }
  1013. if(bytes instanceof util$1.ByteStringBuffer) {
  1014. // copy binary string and process as the same as a string parameter below
  1015. bytes = bytes.data;
  1016. encoding = 'binary';
  1017. }
  1018. // string conversion
  1019. encoding = encoding || 'binary';
  1020. if(typeof bytes === 'string') {
  1021. var view;
  1022. // decode from string
  1023. if(encoding === 'hex') {
  1024. this.accommodate(Math.ceil(bytes.length / 2));
  1025. view = new Uint8Array(this.data.buffer, this.write);
  1026. this.write += util$1.binary.hex.decode(bytes, view, this.write);
  1027. return this;
  1028. }
  1029. if(encoding === 'base64') {
  1030. this.accommodate(Math.ceil(bytes.length / 4) * 3);
  1031. view = new Uint8Array(this.data.buffer, this.write);
  1032. this.write += util$1.binary.base64.decode(bytes, view, this.write);
  1033. return this;
  1034. }
  1035. // encode text as UTF-8 bytes
  1036. if(encoding === 'utf8') {
  1037. // encode as UTF-8 then decode string as raw binary
  1038. bytes = util$1.encodeUtf8(bytes);
  1039. encoding = 'binary';
  1040. }
  1041. // decode string as raw binary
  1042. if(encoding === 'binary' || encoding === 'raw') {
  1043. // one byte per character
  1044. this.accommodate(bytes.length);
  1045. view = new Uint8Array(this.data.buffer, this.write);
  1046. this.write += util$1.binary.raw.decode(view);
  1047. return this;
  1048. }
  1049. // encode text as UTF-16 bytes
  1050. if(encoding === 'utf16') {
  1051. // two bytes per character
  1052. this.accommodate(bytes.length * 2);
  1053. view = new Uint16Array(this.data.buffer, this.write);
  1054. this.write += util$1.text.utf16.encode(view);
  1055. return this;
  1056. }
  1057. throw new Error('Invalid encoding: ' + encoding);
  1058. }
  1059. throw Error('Invalid parameter: ' + bytes);
  1060. };
  1061. /**
  1062. * Puts the given buffer into this buffer.
  1063. *
  1064. * @param buffer the buffer to put into this one.
  1065. *
  1066. * @return this buffer.
  1067. */
  1068. util$1.DataBuffer.prototype.putBuffer = function(buffer) {
  1069. this.putBytes(buffer);
  1070. buffer.clear();
  1071. return this;
  1072. };
  1073. /**
  1074. * Puts a string into this buffer.
  1075. *
  1076. * @param str the string to put.
  1077. * @param [encoding] the encoding for the string (default: 'utf16').
  1078. *
  1079. * @return this buffer.
  1080. */
  1081. util$1.DataBuffer.prototype.putString = function(str) {
  1082. return this.putBytes(str, 'utf16');
  1083. };
  1084. /**
  1085. * Puts a 16-bit integer in this buffer in big-endian order.
  1086. *
  1087. * @param i the 16-bit integer.
  1088. *
  1089. * @return this buffer.
  1090. */
  1091. util$1.DataBuffer.prototype.putInt16 = function(i) {
  1092. this.accommodate(2);
  1093. this.data.setInt16(this.write, i);
  1094. this.write += 2;
  1095. return this;
  1096. };
  1097. /**
  1098. * Puts a 24-bit integer in this buffer in big-endian order.
  1099. *
  1100. * @param i the 24-bit integer.
  1101. *
  1102. * @return this buffer.
  1103. */
  1104. util$1.DataBuffer.prototype.putInt24 = function(i) {
  1105. this.accommodate(3);
  1106. this.data.setInt16(this.write, i >> 8 & 0xFFFF);
  1107. this.data.setInt8(this.write, i >> 16 & 0xFF);
  1108. this.write += 3;
  1109. return this;
  1110. };
  1111. /**
  1112. * Puts a 32-bit integer in this buffer in big-endian order.
  1113. *
  1114. * @param i the 32-bit integer.
  1115. *
  1116. * @return this buffer.
  1117. */
  1118. util$1.DataBuffer.prototype.putInt32 = function(i) {
  1119. this.accommodate(4);
  1120. this.data.setInt32(this.write, i);
  1121. this.write += 4;
  1122. return this;
  1123. };
  1124. /**
  1125. * Puts a 16-bit integer in this buffer in little-endian order.
  1126. *
  1127. * @param i the 16-bit integer.
  1128. *
  1129. * @return this buffer.
  1130. */
  1131. util$1.DataBuffer.prototype.putInt16Le = function(i) {
  1132. this.accommodate(2);
  1133. this.data.setInt16(this.write, i, true);
  1134. this.write += 2;
  1135. return this;
  1136. };
  1137. /**
  1138. * Puts a 24-bit integer in this buffer in little-endian order.
  1139. *
  1140. * @param i the 24-bit integer.
  1141. *
  1142. * @return this buffer.
  1143. */
  1144. util$1.DataBuffer.prototype.putInt24Le = function(i) {
  1145. this.accommodate(3);
  1146. this.data.setInt8(this.write, i >> 16 & 0xFF);
  1147. this.data.setInt16(this.write, i >> 8 & 0xFFFF, true);
  1148. this.write += 3;
  1149. return this;
  1150. };
  1151. /**
  1152. * Puts a 32-bit integer in this buffer in little-endian order.
  1153. *
  1154. * @param i the 32-bit integer.
  1155. *
  1156. * @return this buffer.
  1157. */
  1158. util$1.DataBuffer.prototype.putInt32Le = function(i) {
  1159. this.accommodate(4);
  1160. this.data.setInt32(this.write, i, true);
  1161. this.write += 4;
  1162. return this;
  1163. };
  1164. /**
  1165. * Puts an n-bit integer in this buffer in big-endian order.
  1166. *
  1167. * @param i the n-bit integer.
  1168. * @param n the number of bits in the integer (8, 16, 24, or 32).
  1169. *
  1170. * @return this buffer.
  1171. */
  1172. util$1.DataBuffer.prototype.putInt = function(i, n) {
  1173. _checkBitsParam(n);
  1174. this.accommodate(n / 8);
  1175. do {
  1176. n -= 8;
  1177. this.data.setInt8(this.write++, (i >> n) & 0xFF);
  1178. } while(n > 0);
  1179. return this;
  1180. };
  1181. /**
  1182. * Puts a signed n-bit integer in this buffer in big-endian order. Two's
  1183. * complement representation is used.
  1184. *
  1185. * @param i the n-bit integer.
  1186. * @param n the number of bits in the integer.
  1187. *
  1188. * @return this buffer.
  1189. */
  1190. util$1.DataBuffer.prototype.putSignedInt = function(i, n) {
  1191. _checkBitsParam(n);
  1192. this.accommodate(n / 8);
  1193. if(i < 0) {
  1194. i += 2 << (n - 1);
  1195. }
  1196. return this.putInt(i, n);
  1197. };
  1198. /**
  1199. * Gets a byte from this buffer and advances the read pointer by 1.
  1200. *
  1201. * @return the byte.
  1202. */
  1203. util$1.DataBuffer.prototype.getByte = function() {
  1204. return this.data.getInt8(this.read++);
  1205. };
  1206. /**
  1207. * Gets a uint16 from this buffer in big-endian order and advances the read
  1208. * pointer by 2.
  1209. *
  1210. * @return the uint16.
  1211. */
  1212. util$1.DataBuffer.prototype.getInt16 = function() {
  1213. var rval = this.data.getInt16(this.read);
  1214. this.read += 2;
  1215. return rval;
  1216. };
  1217. /**
  1218. * Gets a uint24 from this buffer in big-endian order and advances the read
  1219. * pointer by 3.
  1220. *
  1221. * @return the uint24.
  1222. */
  1223. util$1.DataBuffer.prototype.getInt24 = function() {
  1224. var rval = (
  1225. this.data.getInt16(this.read) << 8 ^
  1226. this.data.getInt8(this.read + 2));
  1227. this.read += 3;
  1228. return rval;
  1229. };
  1230. /**
  1231. * Gets a uint32 from this buffer in big-endian order and advances the read
  1232. * pointer by 4.
  1233. *
  1234. * @return the word.
  1235. */
  1236. util$1.DataBuffer.prototype.getInt32 = function() {
  1237. var rval = this.data.getInt32(this.read);
  1238. this.read += 4;
  1239. return rval;
  1240. };
  1241. /**
  1242. * Gets a uint16 from this buffer in little-endian order and advances the read
  1243. * pointer by 2.
  1244. *
  1245. * @return the uint16.
  1246. */
  1247. util$1.DataBuffer.prototype.getInt16Le = function() {
  1248. var rval = this.data.getInt16(this.read, true);
  1249. this.read += 2;
  1250. return rval;
  1251. };
  1252. /**
  1253. * Gets a uint24 from this buffer in little-endian order and advances the read
  1254. * pointer by 3.
  1255. *
  1256. * @return the uint24.
  1257. */
  1258. util$1.DataBuffer.prototype.getInt24Le = function() {
  1259. var rval = (
  1260. this.data.getInt8(this.read) ^
  1261. this.data.getInt16(this.read + 1, true) << 8);
  1262. this.read += 3;
  1263. return rval;
  1264. };
  1265. /**
  1266. * Gets a uint32 from this buffer in little-endian order and advances the read
  1267. * pointer by 4.
  1268. *
  1269. * @return the word.
  1270. */
  1271. util$1.DataBuffer.prototype.getInt32Le = function() {
  1272. var rval = this.data.getInt32(this.read, true);
  1273. this.read += 4;
  1274. return rval;
  1275. };
  1276. /**
  1277. * Gets an n-bit integer from this buffer in big-endian order and advances the
  1278. * read pointer by n/8.
  1279. *
  1280. * @param n the number of bits in the integer (8, 16, 24, or 32).
  1281. *
  1282. * @return the integer.
  1283. */
  1284. util$1.DataBuffer.prototype.getInt = function(n) {
  1285. _checkBitsParam(n);
  1286. var rval = 0;
  1287. do {
  1288. // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits.
  1289. rval = (rval << 8) + this.data.getInt8(this.read++);
  1290. n -= 8;
  1291. } while(n > 0);
  1292. return rval;
  1293. };
  1294. /**
  1295. * Gets a signed n-bit integer from this buffer in big-endian order, using
  1296. * two's complement, and advances the read pointer by n/8.
  1297. *
  1298. * @param n the number of bits in the integer (8, 16, 24, or 32).
  1299. *
  1300. * @return the integer.
  1301. */
  1302. util$1.DataBuffer.prototype.getSignedInt = function(n) {
  1303. // getInt checks n
  1304. var x = this.getInt(n);
  1305. var max = 2 << (n - 2);
  1306. if(x >= max) {
  1307. x -= max << 1;
  1308. }
  1309. return x;
  1310. };
  1311. /**
  1312. * Reads bytes out as a binary encoded string and clears them from the
  1313. * buffer.
  1314. *
  1315. * @param count the number of bytes to read, undefined or null for all.
  1316. *
  1317. * @return a binary encoded string of bytes.
  1318. */
  1319. util$1.DataBuffer.prototype.getBytes = function(count) {
  1320. // TODO: deprecate this method, it is poorly named and
  1321. // this.toString('binary') replaces it
  1322. // add a toTypedArray()/toArrayBuffer() function
  1323. var rval;
  1324. if(count) {
  1325. // read count bytes
  1326. count = Math.min(this.length(), count);
  1327. rval = this.data.slice(this.read, this.read + count);
  1328. this.read += count;
  1329. } else if(count === 0) {
  1330. rval = '';
  1331. } else {
  1332. // read all bytes, optimize to only copy when needed
  1333. rval = (this.read === 0) ? this.data : this.data.slice(this.read);
  1334. this.clear();
  1335. }
  1336. return rval;
  1337. };
  1338. /**
  1339. * Gets a binary encoded string of the bytes from this buffer without
  1340. * modifying the read pointer.
  1341. *
  1342. * @param count the number of bytes to get, omit to get all.
  1343. *
  1344. * @return a string full of binary encoded characters.
  1345. */
  1346. util$1.DataBuffer.prototype.bytes = function(count) {
  1347. // TODO: deprecate this method, it is poorly named, add "getString()"
  1348. return (typeof(count) === 'undefined' ?
  1349. this.data.slice(this.read) :
  1350. this.data.slice(this.read, this.read + count));
  1351. };
  1352. /**
  1353. * Gets a byte at the given index without modifying the read pointer.
  1354. *
  1355. * @param i the byte index.
  1356. *
  1357. * @return the byte.
  1358. */
  1359. util$1.DataBuffer.prototype.at = function(i) {
  1360. return this.data.getUint8(this.read + i);
  1361. };
  1362. /**
  1363. * Puts a byte at the given index without modifying the read pointer.
  1364. *
  1365. * @param i the byte index.
  1366. * @param b the byte to put.
  1367. *
  1368. * @return this buffer.
  1369. */
  1370. util$1.DataBuffer.prototype.setAt = function(i, b) {
  1371. this.data.setUint8(i, b);
  1372. return this;
  1373. };
  1374. /**
  1375. * Gets the last byte without modifying the read pointer.
  1376. *
  1377. * @return the last byte.
  1378. */
  1379. util$1.DataBuffer.prototype.last = function() {
  1380. return this.data.getUint8(this.write - 1);
  1381. };
  1382. /**
  1383. * Creates a copy of this buffer.
  1384. *
  1385. * @return the copy.
  1386. */
  1387. util$1.DataBuffer.prototype.copy = function() {
  1388. return new util$1.DataBuffer(this);
  1389. };
  1390. /**
  1391. * Compacts this buffer.
  1392. *
  1393. * @return this buffer.
  1394. */
  1395. util$1.DataBuffer.prototype.compact = function() {
  1396. if(this.read > 0) {
  1397. var src = new Uint8Array(this.data.buffer, this.read);
  1398. var dst = new Uint8Array(src.byteLength);
  1399. dst.set(src);
  1400. this.data = new DataView(dst);
  1401. this.write -= this.read;
  1402. this.read = 0;
  1403. }
  1404. return this;
  1405. };
  1406. /**
  1407. * Clears this buffer.
  1408. *
  1409. * @return this buffer.
  1410. */
  1411. util$1.DataBuffer.prototype.clear = function() {
  1412. this.data = new DataView(new ArrayBuffer(0));
  1413. this.read = this.write = 0;
  1414. return this;
  1415. };
  1416. /**
  1417. * Shortens this buffer by triming bytes off of the end of this buffer.
  1418. *
  1419. * @param count the number of bytes to trim off.
  1420. *
  1421. * @return this buffer.
  1422. */
  1423. util$1.DataBuffer.prototype.truncate = function(count) {
  1424. this.write = Math.max(0, this.length() - count);
  1425. this.read = Math.min(this.read, this.write);
  1426. return this;
  1427. };
  1428. /**
  1429. * Converts this buffer to a hexadecimal string.
  1430. *
  1431. * @return a hexadecimal string.
  1432. */
  1433. util$1.DataBuffer.prototype.toHex = function() {
  1434. var rval = '';
  1435. for(var i = this.read; i < this.data.byteLength; ++i) {
  1436. var b = this.data.getUint8(i);
  1437. if(b < 16) {
  1438. rval += '0';
  1439. }
  1440. rval += b.toString(16);
  1441. }
  1442. return rval;
  1443. };
  1444. /**
  1445. * Converts this buffer to a string, using the given encoding. If no
  1446. * encoding is given, 'utf8' (UTF-8) is used.
  1447. *
  1448. * @param [encoding] the encoding to use: 'binary', 'utf8', 'utf16', 'hex',
  1449. * 'base64' (default: 'utf8').
  1450. *
  1451. * @return a string representation of the bytes in this buffer.
  1452. */
  1453. util$1.DataBuffer.prototype.toString = function(encoding) {
  1454. var view = new Uint8Array(this.data, this.read, this.length());
  1455. encoding = encoding || 'utf8';
  1456. // encode to string
  1457. if(encoding === 'binary' || encoding === 'raw') {
  1458. return util$1.binary.raw.encode(view);
  1459. }
  1460. if(encoding === 'hex') {
  1461. return util$1.binary.hex.encode(view);
  1462. }
  1463. if(encoding === 'base64') {
  1464. return util$1.binary.base64.encode(view);
  1465. }
  1466. // decode to text
  1467. if(encoding === 'utf8') {
  1468. return util$1.text.utf8.decode(view);
  1469. }
  1470. if(encoding === 'utf16') {
  1471. return util$1.text.utf16.decode(view);
  1472. }
  1473. throw new Error('Invalid encoding: ' + encoding);
  1474. };
  1475. /** End Buffer w/UInt8Array backing */
  1476. /**
  1477. * Creates a buffer that stores bytes. A value may be given to populate the
  1478. * buffer with data. This value can either be string of encoded bytes or a
  1479. * regular string of characters. When passing a string of binary encoded
  1480. * bytes, the encoding `raw` should be given. This is also the default. When
  1481. * passing a string of characters, the encoding `utf8` should be given.
  1482. *
  1483. * @param [input] a string with encoded bytes to store in the buffer.
  1484. * @param [encoding] (default: 'raw', other: 'utf8').
  1485. */
  1486. util$1.createBuffer = function(input, encoding) {
  1487. // TODO: deprecate, use new ByteBuffer() instead
  1488. encoding = encoding || 'raw';
  1489. if(input !== undefined && encoding === 'utf8') {
  1490. input = util$1.encodeUtf8(input);
  1491. }
  1492. return new util$1.ByteBuffer(input);
  1493. };
  1494. /**
  1495. * Fills a string with a particular value. If you want the string to be a byte
  1496. * string, pass in String.fromCharCode(theByte).
  1497. *
  1498. * @param c the character to fill the string with, use String.fromCharCode
  1499. * to fill the string with a byte value.
  1500. * @param n the number of characters of value c to fill with.
  1501. *
  1502. * @return the filled string.
  1503. */
  1504. util$1.fillString = function(c, n) {
  1505. var s = '';
  1506. while(n > 0) {
  1507. if(n & 1) {
  1508. s += c;
  1509. }
  1510. n >>>= 1;
  1511. if(n > 0) {
  1512. c += c;
  1513. }
  1514. }
  1515. return s;
  1516. };
  1517. /**
  1518. * Performs a per byte XOR between two byte strings and returns the result as a
  1519. * string of bytes.
  1520. *
  1521. * @param s1 first string of bytes.
  1522. * @param s2 second string of bytes.
  1523. * @param n the number of bytes to XOR.
  1524. *
  1525. * @return the XOR'd result.
  1526. */
  1527. util$1.xorBytes = function(s1, s2, n) {
  1528. var s3 = '';
  1529. var b = '';
  1530. var t = '';
  1531. var i = 0;
  1532. var c = 0;
  1533. for(; n > 0; --n, ++i) {
  1534. b = s1.charCodeAt(i) ^ s2.charCodeAt(i);
  1535. if(c >= 10) {
  1536. s3 += t;
  1537. t = '';
  1538. c = 0;
  1539. }
  1540. t += String.fromCharCode(b);
  1541. ++c;
  1542. }
  1543. s3 += t;
  1544. return s3;
  1545. };
  1546. /**
  1547. * Converts a hex string into a 'binary' encoded string of bytes.
  1548. *
  1549. * @param hex the hexadecimal string to convert.
  1550. *
  1551. * @return the binary-encoded string of bytes.
  1552. */
  1553. util$1.hexToBytes = function(hex) {
  1554. // TODO: deprecate: "Deprecated. Use util.binary.hex.decode instead."
  1555. var rval = '';
  1556. var i = 0;
  1557. if(hex.length & 1 == 1) {
  1558. // odd number of characters, convert first character alone
  1559. i = 1;
  1560. rval += String.fromCharCode(parseInt(hex[0], 16));
  1561. }
  1562. // convert 2 characters (1 byte) at a time
  1563. for(; i < hex.length; i += 2) {
  1564. rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
  1565. }
  1566. return rval;
  1567. };
  1568. /**
  1569. * Converts a 'binary' encoded string of bytes to hex.
  1570. *
  1571. * @param bytes the byte string to convert.
  1572. *
  1573. * @return the string of hexadecimal characters.
  1574. */
  1575. util$1.bytesToHex = function(bytes) {
  1576. // TODO: deprecate: "Deprecated. Use util.binary.hex.encode instead."
  1577. return util$1.createBuffer(bytes).toHex();
  1578. };
  1579. /**
  1580. * Converts an 32-bit integer to 4-big-endian byte string.
  1581. *
  1582. * @param i the integer.
  1583. *
  1584. * @return the byte string.
  1585. */
  1586. util$1.int32ToBytes = function(i) {
  1587. return (
  1588. String.fromCharCode(i >> 24 & 0xFF) +
  1589. String.fromCharCode(i >> 16 & 0xFF) +
  1590. String.fromCharCode(i >> 8 & 0xFF) +
  1591. String.fromCharCode(i & 0xFF));
  1592. };
  1593. // base64 characters, reverse mapping
  1594. var _base64 =
  1595. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1596. var _base64Idx = [
  1597. /*43 -43 = 0*/
  1598. /*'+', 1, 2, 3,'/' */
  1599. 62, -1, -1, -1, 63,
  1600. /*'0','1','2','3','4','5','6','7','8','9' */
  1601. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
  1602. /*15, 16, 17,'=', 19, 20, 21 */
  1603. -1, -1, -1, 64, -1, -1, -1,
  1604. /*65 - 43 = 22*/
  1605. /*'A','B','C','D','E','F','G','H','I','J','K','L','M', */
  1606. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
  1607. /*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */
  1608. 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
  1609. /*91 - 43 = 48 */
  1610. /*48, 49, 50, 51, 52, 53 */
  1611. -1, -1, -1, -1, -1, -1,
  1612. /*97 - 43 = 54*/
  1613. /*'a','b','c','d','e','f','g','h','i','j','k','l','m' */
  1614. 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
  1615. /*'n','o','p','q','r','s','t','u','v','w','x','y','z' */
  1616. 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
  1617. ];
  1618. // base58 characters (Bitcoin alphabet)
  1619. var _base58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
  1620. /**
  1621. * Base64 encodes a 'binary' encoded string of bytes.
  1622. *
  1623. * @param input the binary encoded string of bytes to base64-encode.
  1624. * @param maxline the maximum number of encoded characters per line to use,
  1625. * defaults to none.
  1626. *
  1627. * @return the base64-encoded output.
  1628. */
  1629. util$1.encode64 = function(input, maxline) {
  1630. // TODO: deprecate: "Deprecated. Use util.binary.base64.encode instead."
  1631. var line = '';
  1632. var output = '';
  1633. var chr1, chr2, chr3;
  1634. var i = 0;
  1635. while(i < input.length) {
  1636. chr1 = input.charCodeAt(i++);
  1637. chr2 = input.charCodeAt(i++);
  1638. chr3 = input.charCodeAt(i++);
  1639. // encode 4 character group
  1640. line += _base64.charAt(chr1 >> 2);
  1641. line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4));
  1642. if(isNaN(chr2)) {
  1643. line += '==';
  1644. } else {
  1645. line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6));
  1646. line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63);
  1647. }
  1648. if(maxline && line.length > maxline) {
  1649. output += line.substr(0, maxline) + '\r\n';
  1650. line = line.substr(maxline);
  1651. }
  1652. }
  1653. output += line;
  1654. return output;
  1655. };
  1656. /**
  1657. * Base64 decodes a string into a 'binary' encoded string of bytes.
  1658. *
  1659. * @param input the base64-encoded input.
  1660. *
  1661. * @return the binary encoded string.
  1662. */
  1663. util$1.decode64 = function(input) {
  1664. // TODO: deprecate: "Deprecated. Use util.binary.base64.decode instead."
  1665. // remove all non-base64 characters
  1666. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
  1667. var output = '';
  1668. var enc1, enc2, enc3, enc4;
  1669. var i = 0;
  1670. while(i < input.length) {
  1671. enc1 = _base64Idx[input.charCodeAt(i++) - 43];
  1672. enc2 = _base64Idx[input.charCodeAt(i++) - 43];
  1673. enc3 = _base64Idx[input.charCodeAt(i++) - 43];
  1674. enc4 = _base64Idx[input.charCodeAt(i++) - 43];
  1675. output += String.fromCharCode((enc1 << 2) | (enc2 >> 4));
  1676. if(enc3 !== 64) {
  1677. // decoded at least 2 bytes
  1678. output += String.fromCharCode(((enc2 & 15) << 4) | (enc3 >> 2));
  1679. if(enc4 !== 64) {
  1680. // decoded 3 bytes
  1681. output += String.fromCharCode(((enc3 & 3) << 6) | enc4);
  1682. }
  1683. }
  1684. }
  1685. return output;
  1686. };
  1687. /**
  1688. * Encodes the given string of characters (a standard JavaScript
  1689. * string) as a binary encoded string where the bytes represent
  1690. * a UTF-8 encoded string of characters. Non-ASCII characters will be
  1691. * encoded as multiple bytes according to UTF-8.
  1692. *
  1693. * @param str a standard string of characters to encode.
  1694. *
  1695. * @return the binary encoded string.
  1696. */
  1697. util$1.encodeUtf8 = function(str) {
  1698. return unescape(encodeURIComponent(str));
  1699. };
  1700. /**
  1701. * Decodes a binary encoded string that contains bytes that
  1702. * represent a UTF-8 encoded string of characters -- into a
  1703. * string of characters (a standard JavaScript string).
  1704. *
  1705. * @param str the binary encoded string to decode.
  1706. *
  1707. * @return the resulting standard string of characters.
  1708. */
  1709. util$1.decodeUtf8 = function(str) {
  1710. return decodeURIComponent(escape(str));
  1711. };
  1712. // binary encoding/decoding tools
  1713. // FIXME: Experimental. Do not use yet.
  1714. util$1.binary = {
  1715. raw: {},
  1716. hex: {},
  1717. base64: {},
  1718. base58: {},
  1719. baseN : {
  1720. encode: baseN.encode,
  1721. decode: baseN.decode
  1722. }
  1723. };
  1724. /**
  1725. * Encodes a Uint8Array as a binary-encoded string. This encoding uses
  1726. * a value between 0 and 255 for each character.
  1727. *
  1728. * @param bytes the Uint8Array to encode.
  1729. *
  1730. * @return the binary-encoded string.
  1731. */
  1732. util$1.binary.raw.encode = function(bytes) {
  1733. return String.fromCharCode.apply(null, bytes);
  1734. };
  1735. /**
  1736. * Decodes a binary-encoded string to a Uint8Array. This encoding uses
  1737. * a value between 0 and 255 for each character.
  1738. *
  1739. * @param str the binary-encoded string to decode.
  1740. * @param [output] an optional Uint8Array to write the output to; if it
  1741. * is too small, an exception will be thrown.
  1742. * @param [offset] the start offset for writing to the output (default: 0).
  1743. *
  1744. * @return the Uint8Array or the number of bytes written if output was given.
  1745. */
  1746. util$1.binary.raw.decode = function(str, output, offset) {
  1747. var out = output;
  1748. if(!out) {
  1749. out = new Uint8Array(str.length);
  1750. }
  1751. offset = offset || 0;
  1752. var j = offset;
  1753. for(var i = 0; i < str.length; ++i) {
  1754. out[j++] = str.charCodeAt(i);
  1755. }
  1756. return output ? (j - offset) : out;
  1757. };
  1758. /**
  1759. * Encodes a 'binary' string, ArrayBuffer, DataView, TypedArray, or
  1760. * ByteBuffer as a string of hexadecimal characters.
  1761. *
  1762. * @param bytes the bytes to convert.
  1763. *
  1764. * @return the string of hexadecimal characters.
  1765. */
  1766. util$1.binary.hex.encode = util$1.bytesToHex;
  1767. /**
  1768. * Decodes a hex-encoded string to a Uint8Array.
  1769. *
  1770. * @param hex the hexadecimal string to convert.
  1771. * @param [output] an optional Uint8Array to write the output to; if it
  1772. * is too small, an exception will be thrown.
  1773. * @param [offset] the start offset for writing to the output (default: 0).
  1774. *
  1775. * @return the Uint8Array or the number of bytes written if output was given.
  1776. */
  1777. util$1.binary.hex.decode = function(hex, output, offset) {
  1778. var out = output;
  1779. if(!out) {
  1780. out = new Uint8Array(Math.ceil(hex.length / 2));
  1781. }
  1782. offset = offset || 0;
  1783. var i = 0, j = offset;
  1784. if(hex.length & 1) {
  1785. // odd number of characters, convert first character alone
  1786. i = 1;
  1787. out[j++] = parseInt(hex[0], 16);
  1788. }
  1789. // convert 2 characters (1 byte) at a time
  1790. for(; i < hex.length; i += 2) {
  1791. out[j++] = parseInt(hex.substr(i, 2), 16);
  1792. }
  1793. return output ? (j - offset) : out;
  1794. };
  1795. /**
  1796. * Base64-encodes a Uint8Array.
  1797. *
  1798. * @param input the Uint8Array to encode.
  1799. * @param maxline the maximum number of encoded characters per line to use,
  1800. * defaults to none.
  1801. *
  1802. * @return the base64-encoded output string.
  1803. */
  1804. util$1.binary.base64.encode = function(input, maxline) {
  1805. var line = '';
  1806. var output = '';
  1807. var chr1, chr2, chr3;
  1808. var i = 0;
  1809. while(i < input.byteLength) {
  1810. chr1 = input[i++];
  1811. chr2 = input[i++];
  1812. chr3 = input[i++];
  1813. // encode 4 character group
  1814. line += _base64.charAt(chr1 >> 2);
  1815. line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4));
  1816. if(isNaN(chr2)) {
  1817. line += '==';
  1818. } else {
  1819. line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6));
  1820. line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63);
  1821. }
  1822. if(maxline && line.length > maxline) {
  1823. output += line.substr(0, maxline) + '\r\n';
  1824. line = line.substr(maxline);
  1825. }
  1826. }
  1827. output += line;
  1828. return output;
  1829. };
  1830. /**
  1831. * Decodes a base64-encoded string to a Uint8Array.
  1832. *
  1833. * @param input the base64-encoded input string.
  1834. * @param [output] an optional Uint8Array to write the output to; if it
  1835. * is too small, an exception will be thrown.
  1836. * @param [offset] the start offset for writing to the output (default: 0).
  1837. *
  1838. * @return the Uint8Array or the number of bytes written if output was given.
  1839. */
  1840. util$1.binary.base64.decode = function(input, output, offset) {
  1841. var out = output;
  1842. if(!out) {
  1843. out = new Uint8Array(Math.ceil(input.length / 4) * 3);
  1844. }
  1845. // remove all non-base64 characters
  1846. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
  1847. offset = offset || 0;
  1848. var enc1, enc2, enc3, enc4;
  1849. var i = 0, j = offset;
  1850. while(i < input.length) {
  1851. enc1 = _base64Idx[input.charCodeAt(i++) - 43];
  1852. enc2 = _base64Idx[input.charCodeAt(i++) - 43];
  1853. enc3 = _base64Idx[input.charCodeAt(i++) - 43];
  1854. enc4 = _base64Idx[input.charCodeAt(i++) - 43];
  1855. out[j++] = (enc1 << 2) | (enc2 >> 4);
  1856. if(enc3 !== 64) {
  1857. // decoded at least 2 bytes
  1858. out[j++] = ((enc2 & 15) << 4) | (enc3 >> 2);
  1859. if(enc4 !== 64) {
  1860. // decoded 3 bytes
  1861. out[j++] = ((enc3 & 3) << 6) | enc4;
  1862. }
  1863. }
  1864. }
  1865. // make sure result is the exact decoded length
  1866. return output ? (j - offset) : out.subarray(0, j);
  1867. };
  1868. // add support for base58 encoding/decoding with Bitcoin alphabet
  1869. util$1.binary.base58.encode = function(input, maxline) {
  1870. return util$1.binary.baseN.encode(input, _base58, maxline);
  1871. };
  1872. util$1.binary.base58.decode = function(input, maxline) {
  1873. return util$1.binary.baseN.decode(input, _base58, maxline);
  1874. };
  1875. // text encoding/decoding tools
  1876. // FIXME: Experimental. Do not use yet.
  1877. util$1.text = {
  1878. utf8: {},
  1879. utf16: {}
  1880. };
  1881. /**
  1882. * Encodes the given string as UTF-8 in a Uint8Array.
  1883. *
  1884. * @param str the string to encode.
  1885. * @param [output] an optional Uint8Array to write the output to; if it
  1886. * is too small, an exception will be thrown.
  1887. * @param [offset] the start offset for writing to the output (default: 0).
  1888. *
  1889. * @return the Uint8Array or the number of bytes written if output was given.
  1890. */
  1891. util$1.text.utf8.encode = function(str, output, offset) {
  1892. str = util$1.encodeUtf8(str);
  1893. var out = output;
  1894. if(!out) {
  1895. out = new Uint8Array(str.length);
  1896. }
  1897. offset = offset || 0;
  1898. var j = offset;
  1899. for(var i = 0; i < str.length; ++i) {
  1900. out[j++] = str.charCodeAt(i);
  1901. }
  1902. return output ? (j - offset) : out;
  1903. };
  1904. /**
  1905. * Decodes the UTF-8 contents from a Uint8Array.
  1906. *
  1907. * @param bytes the Uint8Array to decode.
  1908. *
  1909. * @return the resulting string.
  1910. */
  1911. util$1.text.utf8.decode = function(bytes) {
  1912. return util$1.decodeUtf8(String.fromCharCode.apply(null, bytes));
  1913. };
  1914. /**
  1915. * Encodes the given string as UTF-16 in a Uint8Array.
  1916. *
  1917. * @param str the string to encode.
  1918. * @param [output] an optional Uint8Array to write the output to; if it
  1919. * is too small, an exception will be thrown.
  1920. * @param [offset] the start offset for writing to the output (default: 0).
  1921. *
  1922. * @return the Uint8Array or the number of bytes written if output was given.
  1923. */
  1924. util$1.text.utf16.encode = function(str, output, offset) {
  1925. var out = output;
  1926. if(!out) {
  1927. out = new Uint8Array(str.length * 2);
  1928. }
  1929. var view = new Uint16Array(out.buffer);
  1930. offset = offset || 0;
  1931. var j = offset;
  1932. var k = offset;
  1933. for(var i = 0; i < str.length; ++i) {
  1934. view[k++] = str.charCodeAt(i);
  1935. j += 2;
  1936. }
  1937. return output ? (j - offset) : out;
  1938. };
  1939. /**
  1940. * Decodes the UTF-16 contents from a Uint8Array.
  1941. *
  1942. * @param bytes the Uint8Array to decode.
  1943. *
  1944. * @return the resulting string.
  1945. */
  1946. util$1.text.utf16.decode = function(bytes) {
  1947. return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer));
  1948. };
  1949. /**
  1950. * Deflates the given data using a flash interface.
  1951. *
  1952. * @param api the flash interface.
  1953. * @param bytes the data.
  1954. * @param raw true to return only raw deflate data, false to include zlib
  1955. * header and trailer.
  1956. *
  1957. * @return the deflated data as a string.
  1958. */
  1959. util$1.deflate = function(api, bytes, raw) {
  1960. bytes = util$1.decode64(api.deflate(util$1.encode64(bytes)).rval);
  1961. // strip zlib header and trailer if necessary
  1962. if(raw) {
  1963. // zlib header is 2 bytes (CMF,FLG) where FLG indicates that
  1964. // there is a 4-byte DICT (alder-32) block before the data if
  1965. // its 5th bit is set
  1966. var start = 2;
  1967. var flg = bytes.charCodeAt(1);
  1968. if(flg & 0x20) {
  1969. start = 6;
  1970. }
  1971. // zlib trailer is 4 bytes of adler-32
  1972. bytes = bytes.substring(start, bytes.length - 4);
  1973. }
  1974. return bytes;
  1975. };
  1976. /**
  1977. * Inflates the given data using a flash interface.
  1978. *
  1979. * @param api the flash interface.
  1980. * @param bytes the data.
  1981. * @param raw true if the incoming data has no zlib header or trailer and is
  1982. * raw DEFLATE data.
  1983. *
  1984. * @return the inflated data as a string, null on error.
  1985. */
  1986. util$1.inflate = function(api, bytes, raw) {
  1987. // TODO: add zlib header and trailer if necessary/possible
  1988. var rval = api.inflate(util$1.encode64(bytes)).rval;
  1989. return (rval === null) ? null : util$1.decode64(rval);
  1990. };
  1991. /**
  1992. * Sets a storage object.
  1993. *
  1994. * @param api the storage interface.
  1995. * @param id the storage ID to use.
  1996. * @param obj the storage object, null to remove.
  1997. */
  1998. var _setStorageObject = function(api, id, obj) {
  1999. if(!api) {
  2000. throw new Error('WebStorage not available.');
  2001. }
  2002. var rval;
  2003. if(obj === null) {
  2004. rval = api.removeItem(id);
  2005. } else {
  2006. // json-encode and base64-encode object
  2007. obj = util$1.encode64(JSON.stringify(obj));
  2008. rval = api.setItem(id, obj);
  2009. }
  2010. // handle potential flash error
  2011. if(typeof(rval) !== 'undefined' && rval.rval !== true) {
  2012. var error = new Error(rval.error.message);
  2013. error.id = rval.error.id;
  2014. error.name = rval.error.name;
  2015. throw error;
  2016. }
  2017. };
  2018. /**
  2019. * Gets a storage object.
  2020. *
  2021. * @param api the storage interface.
  2022. * @param id the storage ID to use.
  2023. *
  2024. * @return the storage object entry or null if none exists.
  2025. */
  2026. var _getStorageObject = function(api, id) {
  2027. if(!api) {
  2028. throw new Error('WebStorage not available.');
  2029. }
  2030. // get the existing entry
  2031. var rval = api.getItem(id);
  2032. /* Note: We check api.init because we can't do (api == localStorage)
  2033. on IE because of "Class doesn't support Automation" exception. Only
  2034. the flash api has an init method so this works too, but we need a
  2035. better solution in the future. */
  2036. // flash returns item wrapped in an object, handle special case
  2037. if(api.init) {
  2038. if(rval.rval === null) {
  2039. if(rval.error) {
  2040. var error = new Error(rval.error.message);
  2041. error.id = rval.error.id;
  2042. error.name = rval.error.name;
  2043. throw error;
  2044. }
  2045. // no error, but also no item
  2046. rval = null;
  2047. } else {
  2048. rval = rval.rval;
  2049. }
  2050. }
  2051. // handle decoding
  2052. if(rval !== null) {
  2053. // base64-decode and json-decode data
  2054. rval = JSON.parse(util$1.decode64(rval));
  2055. }
  2056. return rval;
  2057. };
  2058. /**
  2059. * Stores an item in local storage.
  2060. *
  2061. * @param api the storage interface.
  2062. * @param id the storage ID to use.
  2063. * @param key the key for the item.
  2064. * @param data the data for the item (any javascript object/primitive).
  2065. */
  2066. var _setItem = function(api, id, key, data) {
  2067. // get storage object
  2068. var obj = _getStorageObject(api, id);
  2069. if(obj === null) {
  2070. // create a new storage object
  2071. obj = {};
  2072. }
  2073. // update key
  2074. obj[key] = data;
  2075. // set storage object
  2076. _setStorageObject(api, id, obj);
  2077. };
  2078. /**
  2079. * Gets an item from local storage.
  2080. *
  2081. * @param api the storage interface.
  2082. * @param id the storage ID to use.
  2083. * @param key the key for the item.
  2084. *
  2085. * @return the item.
  2086. */
  2087. var _getItem = function(api, id, key) {
  2088. // get storage object
  2089. var rval = _getStorageObject(api, id);
  2090. if(rval !== null) {
  2091. // return data at key
  2092. rval = (key in rval) ? rval[key] : null;
  2093. }
  2094. return rval;
  2095. };
  2096. /**
  2097. * Removes an item from local storage.
  2098. *
  2099. * @param api the storage interface.
  2100. * @param id the storage ID to use.
  2101. * @param key the key for the item.
  2102. */
  2103. var _removeItem = function(api, id, key) {
  2104. // get storage object
  2105. var obj = _getStorageObject(api, id);
  2106. if(obj !== null && key in obj) {
  2107. // remove key
  2108. delete obj[key];
  2109. // see if entry has no keys remaining
  2110. var empty = true;
  2111. for(var prop in obj) {
  2112. empty = false;
  2113. break;
  2114. }
  2115. if(empty) {
  2116. // remove entry entirely if no keys are left
  2117. obj = null;
  2118. }
  2119. // set storage object
  2120. _setStorageObject(api, id, obj);
  2121. }
  2122. };
  2123. /**
  2124. * Clears the local disk storage identified by the given ID.
  2125. *
  2126. * @param api the storage interface.
  2127. * @param id the storage ID to use.
  2128. */
  2129. var _clearItems = function(api, id) {
  2130. _setStorageObject(api, id, null);
  2131. };
  2132. /**
  2133. * Calls a storage function.
  2134. *
  2135. * @param func the function to call.
  2136. * @param args the arguments for the function.
  2137. * @param location the location argument.
  2138. *
  2139. * @return the return value from the function.
  2140. */
  2141. var _callStorageFunction = function(func, args, location) {
  2142. var rval = null;
  2143. // default storage types
  2144. if(typeof(location) === 'undefined') {
  2145. location = ['web', 'flash'];
  2146. }
  2147. // apply storage types in order of preference
  2148. var type;
  2149. var done = false;
  2150. var exception = null;
  2151. for(var idx in location) {
  2152. type = location[idx];
  2153. try {
  2154. if(type === 'flash' || type === 'both') {
  2155. if(args[0] === null) {
  2156. throw new Error('Flash local storage not available.');
  2157. }
  2158. rval = func.apply(this, args);
  2159. done = (type === 'flash');
  2160. }
  2161. if(type === 'web' || type === 'both') {
  2162. args[0] = localStorage;
  2163. rval = func.apply(this, args);
  2164. done = true;
  2165. }
  2166. } catch(ex) {
  2167. exception = ex;
  2168. }
  2169. if(done) {
  2170. break;
  2171. }
  2172. }
  2173. if(!done) {
  2174. throw exception;
  2175. }
  2176. return rval;
  2177. };
  2178. /**
  2179. * Stores an item on local disk.
  2180. *
  2181. * The available types of local storage include 'flash', 'web', and 'both'.
  2182. *
  2183. * The type 'flash' refers to flash local storage (SharedObject). In order
  2184. * to use flash local storage, the 'api' parameter must be valid. The type
  2185. * 'web' refers to WebStorage, if supported by the browser. The type 'both'
  2186. * refers to storing using both 'flash' and 'web', not just one or the
  2187. * other.
  2188. *
  2189. * The location array should list the storage types to use in order of
  2190. * preference:
  2191. *
  2192. * ['flash']: flash only storage
  2193. * ['web']: web only storage
  2194. * ['both']: try to store in both
  2195. * ['flash','web']: store in flash first, but if not available, 'web'
  2196. * ['web','flash']: store in web first, but if not available, 'flash'
  2197. *
  2198. * The location array defaults to: ['web', 'flash']
  2199. *
  2200. * @param api the flash interface, null to use only WebStorage.
  2201. * @param id the storage ID to use.
  2202. * @param key the key for the item.
  2203. * @param data the data for the item (any javascript object/primitive).
  2204. * @param location an array with the preferred types of storage to use.
  2205. */
  2206. util$1.setItem = function(api, id, key, data, location) {
  2207. _callStorageFunction(_setItem, arguments, location);
  2208. };
  2209. /**
  2210. * Gets an item on local disk.
  2211. *
  2212. * Set setItem() for details on storage types.
  2213. *
  2214. * @param api the flash interface, null to use only WebStorage.
  2215. * @param id the storage ID to use.
  2216. * @param key the key for the item.
  2217. * @param location an array with the preferred types of storage to use.
  2218. *
  2219. * @return the item.
  2220. */
  2221. util$1.getItem = function(api, id, key, location) {
  2222. return _callStorageFunction(_getItem, arguments, location);
  2223. };
  2224. /**
  2225. * Removes an item on local disk.
  2226. *
  2227. * Set setItem() for details on storage types.
  2228. *
  2229. * @param api the flash interface.
  2230. * @param id the storage ID to use.
  2231. * @param key the key for the item.
  2232. * @param location an array with the preferred types of storage to use.
  2233. */
  2234. util$1.removeItem = function(api, id, key, location) {
  2235. _callStorageFunction(_removeItem, arguments, location);
  2236. };
  2237. /**
  2238. * Clears the local disk storage identified by the given ID.
  2239. *
  2240. * Set setItem() for details on storage types.
  2241. *
  2242. * @param api the flash interface if flash is available.
  2243. * @param id the storage ID to use.
  2244. * @param location an array with the preferred types of storage to use.
  2245. */
  2246. util$1.clearItems = function(api, id, location) {
  2247. _callStorageFunction(_clearItems, arguments, location);
  2248. };
  2249. /**
  2250. * Parses the scheme, host, and port from an http(s) url.
  2251. *
  2252. * @param str the url string.
  2253. *
  2254. * @return the parsed url object or null if the url is invalid.
  2255. */
  2256. util$1.parseUrl = function(str) {
  2257. // FIXME: this regex looks a bit broken
  2258. var regex = /^(https?):\/\/([^:&^\/]*):?(\d*)(.*)$/g;
  2259. regex.lastIndex = 0;
  2260. var m = regex.exec(str);
  2261. var url = (m === null) ? null : {
  2262. full: str,
  2263. scheme: m[1],
  2264. host: m[2],
  2265. port: m[3],
  2266. path: m[4]
  2267. };
  2268. if(url) {
  2269. url.fullHost = url.host;
  2270. if(url.port) {
  2271. if(url.port !== 80 && url.scheme === 'http') {
  2272. url.fullHost += ':' + url.port;
  2273. } else if(url.port !== 443 && url.scheme === 'https') {
  2274. url.fullHost += ':' + url.port;
  2275. }
  2276. } else if(url.scheme === 'http') {
  2277. url.port = 80;
  2278. } else if(url.scheme === 'https') {
  2279. url.port = 443;
  2280. }
  2281. url.full = url.scheme + '://' + url.fullHost;
  2282. }
  2283. return url;
  2284. };
  2285. /* Storage for query variables */
  2286. var _queryVariables = null;
  2287. /**
  2288. * Returns the window location query variables. Query is parsed on the first
  2289. * call and the same object is returned on subsequent calls. The mapping
  2290. * is from keys to an array of values. Parameters without values will have
  2291. * an object key set but no value added to the value array. Values are
  2292. * unescaped.
  2293. *
  2294. * ...?k1=v1&k2=v2:
  2295. * {
  2296. * "k1": ["v1"],
  2297. * "k2": ["v2"]
  2298. * }
  2299. *
  2300. * ...?k1=v1&k1=v2:
  2301. * {
  2302. * "k1": ["v1", "v2"]
  2303. * }
  2304. *
  2305. * ...?k1=v1&k2:
  2306. * {
  2307. * "k1": ["v1"],
  2308. * "k2": []
  2309. * }
  2310. *
  2311. * ...?k1=v1&k1:
  2312. * {
  2313. * "k1": ["v1"]
  2314. * }
  2315. *
  2316. * ...?k1&k1:
  2317. * {
  2318. * "k1": []
  2319. * }
  2320. *
  2321. * @param query the query string to parse (optional, default to cached
  2322. * results from parsing window location search query).
  2323. *
  2324. * @return object mapping keys to variables.
  2325. */
  2326. util$1.getQueryVariables = function(query) {
  2327. var parse = function(q) {
  2328. var rval = {};
  2329. var kvpairs = q.split('&');
  2330. for(var i = 0; i < kvpairs.length; i++) {
  2331. var pos = kvpairs[i].indexOf('=');
  2332. var key;
  2333. var val;
  2334. if(pos > 0) {
  2335. key = kvpairs[i].substring(0, pos);
  2336. val = kvpairs[i].substring(pos + 1);
  2337. } else {
  2338. key = kvpairs[i];
  2339. val = null;
  2340. }
  2341. if(!(key in rval)) {
  2342. rval[key] = [];
  2343. }
  2344. // disallow overriding object prototype keys
  2345. if(!(key in Object.prototype) && val !== null) {
  2346. rval[key].push(unescape(val));
  2347. }
  2348. }
  2349. return rval;
  2350. };
  2351. var rval;
  2352. if(typeof(query) === 'undefined') {
  2353. // set cached variables if needed
  2354. if(_queryVariables === null) {
  2355. if(typeof(window) !== 'undefined' && window.location && window.location.search) {
  2356. // parse window search query
  2357. _queryVariables = parse(window.location.search.substring(1));
  2358. } else {
  2359. // no query variables available
  2360. _queryVariables = {};
  2361. }
  2362. }
  2363. rval = _queryVariables;
  2364. } else {
  2365. // parse given query
  2366. rval = parse(query);
  2367. }
  2368. return rval;
  2369. };
  2370. /**
  2371. * Parses a fragment into a path and query. This method will take a URI
  2372. * fragment and break it up as if it were the main URI. For example:
  2373. * /bar/baz?a=1&b=2
  2374. * results in:
  2375. * {
  2376. * path: ["bar", "baz"],
  2377. * query: {"k1": ["v1"], "k2": ["v2"]}
  2378. * }
  2379. *
  2380. * @return object with a path array and query object.
  2381. */
  2382. util$1.parseFragment = function(fragment) {
  2383. // default to whole fragment
  2384. var fp = fragment;
  2385. var fq = '';
  2386. // split into path and query if possible at the first '?'
  2387. var pos = fragment.indexOf('?');
  2388. if(pos > 0) {
  2389. fp = fragment.substring(0, pos);
  2390. fq = fragment.substring(pos + 1);
  2391. }
  2392. // split path based on '/' and ignore first element if empty
  2393. var path = fp.split('/');
  2394. if(path.length > 0 && path[0] === '') {
  2395. path.shift();
  2396. }
  2397. // convert query into object
  2398. var query = (fq === '') ? {} : util$1.getQueryVariables(fq);
  2399. return {
  2400. pathString: fp,
  2401. queryString: fq,
  2402. path: path,
  2403. query: query
  2404. };
  2405. };
  2406. /**
  2407. * Makes a request out of a URI-like request string. This is intended to
  2408. * be used where a fragment id (after a URI '#') is parsed as a URI with
  2409. * path and query parts. The string should have a path beginning and
  2410. * delimited by '/' and optional query parameters following a '?'. The
  2411. * query should be a standard URL set of key value pairs delimited by
  2412. * '&'. For backwards compatibility the initial '/' on the path is not
  2413. * required. The request object has the following API, (fully described
  2414. * in the method code):
  2415. * {
  2416. * path: <the path string part>.
  2417. * query: <the query string part>,
  2418. * getPath(i): get part or all of the split path array,
  2419. * getQuery(k, i): get part or all of a query key array,
  2420. * getQueryLast(k, _default): get last element of a query key array.
  2421. * }
  2422. *
  2423. * @return object with request parameters.
  2424. */
  2425. util$1.makeRequest = function(reqString) {
  2426. var frag = util$1.parseFragment(reqString);
  2427. var req = {
  2428. // full path string
  2429. path: frag.pathString,
  2430. // full query string
  2431. query: frag.queryString,
  2432. /**
  2433. * Get path or element in path.
  2434. *
  2435. * @param i optional path index.
  2436. *
  2437. * @return path or part of path if i provided.
  2438. */
  2439. getPath: function(i) {
  2440. return (typeof(i) === 'undefined') ? frag.path : frag.path[i];
  2441. },
  2442. /**
  2443. * Get query, values for a key, or value for a key index.
  2444. *
  2445. * @param k optional query key.
  2446. * @param i optional query key index.
  2447. *
  2448. * @return query, values for a key, or value for a key index.
  2449. */
  2450. getQuery: function(k, i) {
  2451. var rval;
  2452. if(typeof(k) === 'undefined') {
  2453. rval = frag.query;
  2454. } else {
  2455. rval = frag.query[k];
  2456. if(rval && typeof(i) !== 'undefined') {
  2457. rval = rval[i];
  2458. }
  2459. }
  2460. return rval;
  2461. },
  2462. getQueryLast: function(k, _default) {
  2463. var rval;
  2464. var vals = req.getQuery(k);
  2465. if(vals) {
  2466. rval = vals[vals.length - 1];
  2467. } else {
  2468. rval = _default;
  2469. }
  2470. return rval;
  2471. }
  2472. };
  2473. return req;
  2474. };
  2475. /**
  2476. * Makes a URI out of a path, an object with query parameters, and a
  2477. * fragment. Uses jQuery.param() internally for query string creation.
  2478. * If the path is an array, it will be joined with '/'.
  2479. *
  2480. * @param path string path or array of strings.
  2481. * @param query object with query parameters. (optional)
  2482. * @param fragment fragment string. (optional)
  2483. *
  2484. * @return string object with request parameters.
  2485. */
  2486. util$1.makeLink = function(path, query, fragment) {
  2487. // join path parts if needed
  2488. path = jQuery.isArray(path) ? path.join('/') : path;
  2489. var qstr = jQuery.param(query || {});
  2490. fragment = fragment || '';
  2491. return path +
  2492. ((qstr.length > 0) ? ('?' + qstr) : '') +
  2493. ((fragment.length > 0) ? ('#' + fragment) : '');
  2494. };
  2495. /**
  2496. * Check if an object is empty.
  2497. *
  2498. * Taken from:
  2499. * http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json/679937#679937
  2500. *
  2501. * @param object the object to check.
  2502. */
  2503. util$1.isEmpty = function(obj) {
  2504. for(var prop in obj) {
  2505. if(obj.hasOwnProperty(prop)) {
  2506. return false;
  2507. }
  2508. }
  2509. return true;
  2510. };
  2511. /**
  2512. * Format with simple printf-style interpolation.
  2513. *
  2514. * %%: literal '%'
  2515. * %s,%o: convert next argument into a string.
  2516. *
  2517. * @param format the string to format.
  2518. * @param ... arguments to interpolate into the format string.
  2519. */
  2520. util$1.format = function(format) {
  2521. var re = /%./g;
  2522. // current match
  2523. var match;
  2524. // current part
  2525. var part;
  2526. // current arg index
  2527. var argi = 0;
  2528. // collected parts to recombine later
  2529. var parts = [];
  2530. // last index found
  2531. var last = 0;
  2532. // loop while matches remain
  2533. while((match = re.exec(format))) {
  2534. part = format.substring(last, re.lastIndex - 2);
  2535. // don't add empty strings (ie, parts between %s%s)
  2536. if(part.length > 0) {
  2537. parts.push(part);
  2538. }
  2539. last = re.lastIndex;
  2540. // switch on % code
  2541. var code = match[0][1];
  2542. switch(code) {
  2543. case 's':
  2544. case 'o':
  2545. // check if enough arguments were given
  2546. if(argi < arguments.length) {
  2547. parts.push(arguments[argi++ + 1]);
  2548. } else {
  2549. parts.push('<?>');
  2550. }
  2551. break;
  2552. // FIXME: do proper formating for numbers, etc
  2553. //case 'f':
  2554. //case 'd':
  2555. case '%':
  2556. parts.push('%');
  2557. break;
  2558. default:
  2559. parts.push('<%' + code + '?>');
  2560. }
  2561. }
  2562. // add trailing part of format string
  2563. parts.push(format.substring(last));
  2564. return parts.join('');
  2565. };
  2566. /**
  2567. * Formats a number.
  2568. *
  2569. * http://snipplr.com/view/5945/javascript-numberformat--ported-from-php/
  2570. */
  2571. util$1.formatNumber = function(number, decimals, dec_point, thousands_sep) {
  2572. // http://kevin.vanzonneveld.net
  2573. // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  2574. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  2575. // + bugfix by: Michael White (http://crestidg.com)
  2576. // + bugfix by: Benjamin Lupton
  2577. // + bugfix by: Allan Jensen (http://www.winternet.no)
  2578. // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  2579. // * example 1: number_format(1234.5678, 2, '.', '');
  2580. // * returns 1: 1234.57
  2581. var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
  2582. var d = dec_point === undefined ? ',' : dec_point;
  2583. var t = thousands_sep === undefined ?
  2584. '.' : thousands_sep, s = n < 0 ? '-' : '';
  2585. var i = parseInt((n = Math.abs(+n || 0).toFixed(c)), 10) + '';
  2586. var j = (i.length > 3) ? i.length % 3 : 0;
  2587. return s + (j ? i.substr(0, j) + t : '') +
  2588. i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + t) +
  2589. (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');
  2590. };
  2591. /**
  2592. * Formats a byte size.
  2593. *
  2594. * http://snipplr.com/view/5949/format-humanize-file-byte-size-presentation-in-javascript/
  2595. */
  2596. util$1.formatSize = function(size) {
  2597. if(size >= 1073741824) {
  2598. size = util$1.formatNumber(size / 1073741824, 2, '.', '') + ' GiB';
  2599. } else if(size >= 1048576) {
  2600. size = util$1.formatNumber(size / 1048576, 2, '.', '') + ' MiB';
  2601. } else if(size >= 1024) {
  2602. size = util$1.formatNumber(size / 1024, 0) + ' KiB';
  2603. } else {
  2604. size = util$1.formatNumber(size, 0) + ' bytes';
  2605. }
  2606. return size;
  2607. };
  2608. /**
  2609. * Converts an IPv4 or IPv6 string representation into bytes (in network order).
  2610. *
  2611. * @param ip the IPv4 or IPv6 address to convert.
  2612. *
  2613. * @return the 4-byte IPv6 or 16-byte IPv6 address or null if the address can't
  2614. * be parsed.
  2615. */
  2616. util$1.bytesFromIP = function(ip) {
  2617. if(ip.indexOf('.') !== -1) {
  2618. return util$1.bytesFromIPv4(ip);
  2619. }
  2620. if(ip.indexOf(':') !== -1) {
  2621. return util$1.bytesFromIPv6(ip);
  2622. }
  2623. return null;
  2624. };
  2625. /**
  2626. * Converts an IPv4 string representation into bytes (in network order).
  2627. *
  2628. * @param ip the IPv4 address to convert.
  2629. *
  2630. * @return the 4-byte address or null if the address can't be parsed.
  2631. */
  2632. util$1.bytesFromIPv4 = function(ip) {
  2633. ip = ip.split('.');
  2634. if(ip.length !== 4) {
  2635. return null;
  2636. }
  2637. var b = util$1.createBuffer();
  2638. for(var i = 0; i < ip.length; ++i) {
  2639. var num = parseInt(ip[i], 10);
  2640. if(isNaN(num)) {
  2641. return null;
  2642. }
  2643. b.putByte(num);
  2644. }
  2645. return b.getBytes();
  2646. };
  2647. /**
  2648. * Converts an IPv6 string representation into bytes (in network order).
  2649. *
  2650. * @param ip the IPv6 address to convert.
  2651. *
  2652. * @return the 16-byte address or null if the address can't be parsed.
  2653. */
  2654. util$1.bytesFromIPv6 = function(ip) {
  2655. var blanks = 0;
  2656. ip = ip.split(':').filter(function(e) {
  2657. if(e.length === 0) ++blanks;
  2658. return true;
  2659. });
  2660. var zeros = (8 - ip.length + blanks) * 2;
  2661. var b = util$1.createBuffer();
  2662. for(var i = 0; i < 8; ++i) {
  2663. if(!ip[i] || ip[i].length === 0) {
  2664. b.fillWithByte(0, zeros);
  2665. zeros = 0;
  2666. continue;
  2667. }
  2668. var bytes = util$1.hexToBytes(ip[i]);
  2669. if(bytes.length < 2) {
  2670. b.putByte(0);
  2671. }
  2672. b.putBytes(bytes);
  2673. }
  2674. return b.getBytes();
  2675. };
  2676. /**
  2677. * Converts 4-bytes into an IPv4 string representation or 16-bytes into
  2678. * an IPv6 string representation. The bytes must be in network order.
  2679. *
  2680. * @param bytes the bytes to convert.
  2681. *
  2682. * @return the IPv4 or IPv6 string representation if 4 or 16 bytes,
  2683. * respectively, are given, otherwise null.
  2684. */
  2685. util$1.bytesToIP = function(bytes) {
  2686. if(bytes.length === 4) {
  2687. return util$1.bytesToIPv4(bytes);
  2688. }
  2689. if(bytes.length === 16) {
  2690. return util$1.bytesToIPv6(bytes);
  2691. }
  2692. return null;
  2693. };
  2694. /**
  2695. * Converts 4-bytes into an IPv4 string representation. The bytes must be
  2696. * in network order.
  2697. *
  2698. * @param bytes the bytes to convert.
  2699. *
  2700. * @return the IPv4 string representation or null for an invalid # of bytes.
  2701. */
  2702. util$1.bytesToIPv4 = function(bytes) {
  2703. if(bytes.length !== 4) {
  2704. return null;
  2705. }
  2706. var ip = [];
  2707. for(var i = 0; i < bytes.length; ++i) {
  2708. ip.push(bytes.charCodeAt(i));
  2709. }
  2710. return ip.join('.');
  2711. };
  2712. /**
  2713. * Converts 16-bytes into an IPv16 string representation. The bytes must be
  2714. * in network order.
  2715. *
  2716. * @param bytes the bytes to convert.
  2717. *
  2718. * @return the IPv16 string representation or null for an invalid # of bytes.
  2719. */
  2720. util$1.bytesToIPv6 = function(bytes) {
  2721. if(bytes.length !== 16) {
  2722. return null;
  2723. }
  2724. var ip = [];
  2725. var zeroGroups = [];
  2726. var zeroMaxGroup = 0;
  2727. for(var i = 0; i < bytes.length; i += 2) {
  2728. var hex = util$1.bytesToHex(bytes[i] + bytes[i + 1]);
  2729. // canonicalize zero representation
  2730. while(hex[0] === '0' && hex !== '0') {
  2731. hex = hex.substr(1);
  2732. }
  2733. if(hex === '0') {
  2734. var last = zeroGroups[zeroGroups.length - 1];
  2735. var idx = ip.length;
  2736. if(!last || idx !== last.end + 1) {
  2737. zeroGroups.push({start: idx, end: idx});
  2738. } else {
  2739. last.end = idx;
  2740. if((last.end - last.start) >
  2741. (zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start)) {
  2742. zeroMaxGroup = zeroGroups.length - 1;
  2743. }
  2744. }
  2745. }
  2746. ip.push(hex);
  2747. }
  2748. if(zeroGroups.length > 0) {
  2749. var group = zeroGroups[zeroMaxGroup];
  2750. // only shorten group of length > 0
  2751. if(group.end - group.start > 0) {
  2752. ip.splice(group.start, group.end - group.start + 1, '');
  2753. if(group.start === 0) {
  2754. ip.unshift('');
  2755. }
  2756. if(group.end === 7) {
  2757. ip.push('');
  2758. }
  2759. }
  2760. }
  2761. return ip.join(':');
  2762. };
  2763. /**
  2764. * Estimates the number of processes that can be run concurrently. If
  2765. * creating Web Workers, keep in mind that the main JavaScript process needs
  2766. * its own core.
  2767. *
  2768. * @param options the options to use:
  2769. * update true to force an update (not use the cached value).
  2770. * @param callback(err, max) called once the operation completes.
  2771. */
  2772. util$1.estimateCores = function(options, callback) {
  2773. if(typeof options === 'function') {
  2774. callback = options;
  2775. options = {};
  2776. }
  2777. options = options || {};
  2778. if('cores' in util$1 && !options.update) {
  2779. return callback(null, util$1.cores);
  2780. }
  2781. if(typeof navigator !== 'undefined' &&
  2782. 'hardwareConcurrency' in navigator &&
  2783. navigator.hardwareConcurrency > 0) {
  2784. util$1.cores = navigator.hardwareConcurrency;
  2785. return callback(null, util$1.cores);
  2786. }
  2787. if(typeof Worker === 'undefined') {
  2788. // workers not available
  2789. util$1.cores = 1;
  2790. return callback(null, util$1.cores);
  2791. }
  2792. if(typeof Blob === 'undefined') {
  2793. // can't estimate, default to 2
  2794. util$1.cores = 2;
  2795. return callback(null, util$1.cores);
  2796. }
  2797. // create worker concurrency estimation code as blob
  2798. var blobUrl = URL.createObjectURL(new Blob(['(',
  2799. function() {
  2800. self.addEventListener('message', function(e) {
  2801. // run worker for 4 ms
  2802. var st = Date.now();
  2803. var et = st + 4;
  2804. self.postMessage({st: st, et: et});
  2805. });
  2806. }.toString(),
  2807. ')()'], {type: 'application/javascript'}));
  2808. // take 5 samples using 16 workers
  2809. sample([], 5, 16);
  2810. function sample(max, samples, numWorkers) {
  2811. if(samples === 0) {
  2812. // get overlap average
  2813. var avg = Math.floor(max.reduce(function(avg, x) {
  2814. return avg + x;
  2815. }, 0) / max.length);
  2816. util$1.cores = Math.max(1, avg);
  2817. URL.revokeObjectURL(blobUrl);
  2818. return callback(null, util$1.cores);
  2819. }
  2820. map(numWorkers, function(err, results) {
  2821. max.push(reduce(numWorkers, results));
  2822. sample(max, samples - 1, numWorkers);
  2823. });
  2824. }
  2825. function map(numWorkers, callback) {
  2826. var workers = [];
  2827. var results = [];
  2828. for(var i = 0; i < numWorkers; ++i) {
  2829. var worker = new Worker(blobUrl);
  2830. worker.addEventListener('message', function(e) {
  2831. results.push(e.data);
  2832. if(results.length === numWorkers) {
  2833. for(var i = 0; i < numWorkers; ++i) {
  2834. workers[i].terminate();
  2835. }
  2836. callback(null, results);
  2837. }
  2838. });
  2839. workers.push(worker);
  2840. }
  2841. for(var i = 0; i < numWorkers; ++i) {
  2842. workers[i].postMessage(i);
  2843. }
  2844. }
  2845. function reduce(numWorkers, results) {
  2846. // find overlapping time windows
  2847. var overlaps = [];
  2848. for(var n = 0; n < numWorkers; ++n) {
  2849. var r1 = results[n];
  2850. var overlap = overlaps[n] = [];
  2851. for(var i = 0; i < numWorkers; ++i) {
  2852. if(n === i) {
  2853. continue;
  2854. }
  2855. var r2 = results[i];
  2856. if((r1.st > r2.st && r1.st < r2.et) ||
  2857. (r2.st > r1.st && r2.st < r1.et)) {
  2858. overlap.push(i);
  2859. }
  2860. }
  2861. }
  2862. // get maximum overlaps ... don't include overlapping worker itself
  2863. // as the main JS process was also being scheduled during the work and
  2864. // would have to be subtracted from the estimate anyway
  2865. return overlaps.reduce(function(max, overlap) {
  2866. return Math.max(max, overlap.length);
  2867. }, 0);
  2868. }
  2869. };
  2870. /**
  2871. * Cipher base API.
  2872. *
  2873. * @author Dave Longley
  2874. *
  2875. * Copyright (c) 2010-2014 Digital Bazaar, Inc.
  2876. */
  2877. var forge$D = forge$F;
  2878. forge$D.cipher = forge$D.cipher || {};
  2879. // registered algorithms
  2880. forge$D.cipher.algorithms = forge$D.cipher.algorithms || {};
  2881. /**
  2882. * Creates a cipher object that can be used to encrypt data using the given
  2883. * algorithm and key. The algorithm may be provided as a string value for a
  2884. * previously registered algorithm or it may be given as a cipher algorithm
  2885. * API object.
  2886. *
  2887. * @param algorithm the algorithm to use, either a string or an algorithm API
  2888. * object.
  2889. * @param key the key to use, as a binary-encoded string of bytes or a
  2890. * byte buffer.
  2891. *
  2892. * @return the cipher.
  2893. */
  2894. forge$D.cipher.createCipher = function(algorithm, key) {
  2895. var api = algorithm;
  2896. if(typeof api === 'string') {
  2897. api = forge$D.cipher.getAlgorithm(api);
  2898. if(api) {
  2899. api = api();
  2900. }
  2901. }
  2902. if(!api) {
  2903. throw new Error('Unsupported algorithm: ' + algorithm);
  2904. }
  2905. // assume block cipher
  2906. return new forge$D.cipher.BlockCipher({
  2907. algorithm: api,
  2908. key: key,
  2909. decrypt: false
  2910. });
  2911. };
  2912. /**
  2913. * Creates a decipher object that can be used to decrypt data using the given
  2914. * algorithm and key. The algorithm may be provided as a string value for a
  2915. * previously registered algorithm or it may be given as a cipher algorithm
  2916. * API object.
  2917. *
  2918. * @param algorithm the algorithm to use, either a string or an algorithm API
  2919. * object.
  2920. * @param key the key to use, as a binary-encoded string of bytes or a
  2921. * byte buffer.
  2922. *
  2923. * @return the cipher.
  2924. */
  2925. forge$D.cipher.createDecipher = function(algorithm, key) {
  2926. var api = algorithm;
  2927. if(typeof api === 'string') {
  2928. api = forge$D.cipher.getAlgorithm(api);
  2929. if(api) {
  2930. api = api();
  2931. }
  2932. }
  2933. if(!api) {
  2934. throw new Error('Unsupported algorithm: ' + algorithm);
  2935. }
  2936. // assume block cipher
  2937. return new forge$D.cipher.BlockCipher({
  2938. algorithm: api,
  2939. key: key,
  2940. decrypt: true
  2941. });
  2942. };
  2943. /**
  2944. * Registers an algorithm by name. If the name was already registered, the
  2945. * algorithm API object will be overwritten.
  2946. *
  2947. * @param name the name of the algorithm.
  2948. * @param algorithm the algorithm API object.
  2949. */
  2950. forge$D.cipher.registerAlgorithm = function(name, algorithm) {
  2951. name = name.toUpperCase();
  2952. forge$D.cipher.algorithms[name] = algorithm;
  2953. };
  2954. /**
  2955. * Gets a registered algorithm by name.
  2956. *
  2957. * @param name the name of the algorithm.
  2958. *
  2959. * @return the algorithm, if found, null if not.
  2960. */
  2961. forge$D.cipher.getAlgorithm = function(name) {
  2962. name = name.toUpperCase();
  2963. if(name in forge$D.cipher.algorithms) {
  2964. return forge$D.cipher.algorithms[name];
  2965. }
  2966. return null;
  2967. };
  2968. var BlockCipher = forge$D.cipher.BlockCipher = function(options) {
  2969. this.algorithm = options.algorithm;
  2970. this.mode = this.algorithm.mode;
  2971. this.blockSize = this.mode.blockSize;
  2972. this._finish = false;
  2973. this._input = null;
  2974. this.output = null;
  2975. this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt;
  2976. this._decrypt = options.decrypt;
  2977. this.algorithm.initialize(options);
  2978. };
  2979. /**
  2980. * Starts or restarts the encryption or decryption process, whichever
  2981. * was previously configured.
  2982. *
  2983. * For non-GCM mode, the IV may be a binary-encoded string of bytes, an array
  2984. * of bytes, a byte buffer, or an array of 32-bit integers. If the IV is in
  2985. * bytes, then it must be Nb (16) bytes in length. If the IV is given in as
  2986. * 32-bit integers, then it must be 4 integers long.
  2987. *
  2988. * Note: an IV is not required or used in ECB mode.
  2989. *
  2990. * For GCM-mode, the IV must be given as a binary-encoded string of bytes or
  2991. * a byte buffer. The number of bytes should be 12 (96 bits) as recommended
  2992. * by NIST SP-800-38D but another length may be given.
  2993. *
  2994. * @param options the options to use:
  2995. * iv the initialization vector to use as a binary-encoded string of
  2996. * bytes, null to reuse the last ciphered block from a previous
  2997. * update() (this "residue" method is for legacy support only).
  2998. * additionalData additional authentication data as a binary-encoded
  2999. * string of bytes, for 'GCM' mode, (default: none).
  3000. * tagLength desired length of authentication tag, in bits, for
  3001. * 'GCM' mode (0-128, default: 128).
  3002. * tag the authentication tag to check if decrypting, as a
  3003. * binary-encoded string of bytes.
  3004. * output the output the buffer to write to, null to create one.
  3005. */
  3006. BlockCipher.prototype.start = function(options) {
  3007. options = options || {};
  3008. var opts = {};
  3009. for(var key in options) {
  3010. opts[key] = options[key];
  3011. }
  3012. opts.decrypt = this._decrypt;
  3013. this._finish = false;
  3014. this._input = forge$D.util.createBuffer();
  3015. this.output = options.output || forge$D.util.createBuffer();
  3016. this.mode.start(opts);
  3017. };
  3018. /**
  3019. * Updates the next block according to the cipher mode.
  3020. *
  3021. * @param input the buffer to read from.
  3022. */
  3023. BlockCipher.prototype.update = function(input) {
  3024. if(input) {
  3025. // input given, so empty it into the input buffer
  3026. this._input.putBuffer(input);
  3027. }
  3028. // do cipher operation until it needs more input and not finished
  3029. while(!this._op.call(this.mode, this._input, this.output, this._finish) &&
  3030. !this._finish) {}
  3031. // free consumed memory from input buffer
  3032. this._input.compact();
  3033. };
  3034. /**
  3035. * Finishes encrypting or decrypting.
  3036. *
  3037. * @param pad a padding function to use in CBC mode, null for default,
  3038. * signature(blockSize, buffer, decrypt).
  3039. *
  3040. * @return true if successful, false on error.
  3041. */
  3042. BlockCipher.prototype.finish = function(pad) {
  3043. // backwards-compatibility w/deprecated padding API
  3044. // Note: will overwrite padding functions even after another start() call
  3045. if(pad && (this.mode.name === 'ECB' || this.mode.name === 'CBC')) {
  3046. this.mode.pad = function(input) {
  3047. return pad(this.blockSize, input, false);
  3048. };
  3049. this.mode.unpad = function(output) {
  3050. return pad(this.blockSize, output, true);
  3051. };
  3052. }
  3053. // build options for padding and afterFinish functions
  3054. var options = {};
  3055. options.decrypt = this._decrypt;
  3056. // get # of bytes that won't fill a block
  3057. options.overflow = this._input.length() % this.blockSize;
  3058. if(!this._decrypt && this.mode.pad) {
  3059. if(!this.mode.pad(this._input, options)) {
  3060. return false;
  3061. }
  3062. }
  3063. // do final update
  3064. this._finish = true;
  3065. this.update();
  3066. if(this._decrypt && this.mode.unpad) {
  3067. if(!this.mode.unpad(this.output, options)) {
  3068. return false;
  3069. }
  3070. }
  3071. if(this.mode.afterFinish) {
  3072. if(!this.mode.afterFinish(this.output, options)) {
  3073. return false;
  3074. }
  3075. }
  3076. return true;
  3077. };
  3078. /**
  3079. * Supported cipher modes.
  3080. *
  3081. * @author Dave Longley
  3082. *
  3083. * Copyright (c) 2010-2014 Digital Bazaar, Inc.
  3084. */
  3085. var forge$C = forge$F;
  3086. forge$C.cipher = forge$C.cipher || {};
  3087. // supported cipher modes
  3088. var modes = forge$C.cipher.modes = forge$C.cipher.modes || {};
  3089. /** Electronic codebook (ECB) (Don't use this; it's not secure) **/
  3090. modes.ecb = function(options) {
  3091. options = options || {};
  3092. this.name = 'ECB';
  3093. this.cipher = options.cipher;
  3094. this.blockSize = options.blockSize || 16;
  3095. this._ints = this.blockSize / 4;
  3096. this._inBlock = new Array(this._ints);
  3097. this._outBlock = new Array(this._ints);
  3098. };
  3099. modes.ecb.prototype.start = function(options) {};
  3100. modes.ecb.prototype.encrypt = function(input, output, finish) {
  3101. // not enough input to encrypt
  3102. if(input.length() < this.blockSize && !(finish && input.length() > 0)) {
  3103. return true;
  3104. }
  3105. // get next block
  3106. for(var i = 0; i < this._ints; ++i) {
  3107. this._inBlock[i] = input.getInt32();
  3108. }
  3109. // encrypt block
  3110. this.cipher.encrypt(this._inBlock, this._outBlock);
  3111. // write output
  3112. for(var i = 0; i < this._ints; ++i) {
  3113. output.putInt32(this._outBlock[i]);
  3114. }
  3115. };
  3116. modes.ecb.prototype.decrypt = function(input, output, finish) {
  3117. // not enough input to decrypt
  3118. if(input.length() < this.blockSize && !(finish && input.length() > 0)) {
  3119. return true;
  3120. }
  3121. // get next block
  3122. for(var i = 0; i < this._ints; ++i) {
  3123. this._inBlock[i] = input.getInt32();
  3124. }
  3125. // decrypt block
  3126. this.cipher.decrypt(this._inBlock, this._outBlock);
  3127. // write output
  3128. for(var i = 0; i < this._ints; ++i) {
  3129. output.putInt32(this._outBlock[i]);
  3130. }
  3131. };
  3132. modes.ecb.prototype.pad = function(input, options) {
  3133. // add PKCS#7 padding to block (each pad byte is the
  3134. // value of the number of pad bytes)
  3135. var padding = (input.length() === this.blockSize ?
  3136. this.blockSize : (this.blockSize - input.length()));
  3137. input.fillWithByte(padding, padding);
  3138. return true;
  3139. };
  3140. modes.ecb.prototype.unpad = function(output, options) {
  3141. // check for error: input data not a multiple of blockSize
  3142. if(options.overflow > 0) {
  3143. return false;
  3144. }
  3145. // ensure padding byte count is valid
  3146. var len = output.length();
  3147. var count = output.at(len - 1);
  3148. if(count > (this.blockSize << 2)) {
  3149. return false;
  3150. }
  3151. // trim off padding bytes
  3152. output.truncate(count);
  3153. return true;
  3154. };
  3155. /** Cipher-block Chaining (CBC) **/
  3156. modes.cbc = function(options) {
  3157. options = options || {};
  3158. this.name = 'CBC';
  3159. this.cipher = options.cipher;
  3160. this.blockSize = options.blockSize || 16;
  3161. this._ints = this.blockSize / 4;
  3162. this._inBlock = new Array(this._ints);
  3163. this._outBlock = new Array(this._ints);
  3164. };
  3165. modes.cbc.prototype.start = function(options) {
  3166. // Note: legacy support for using IV residue (has security flaws)
  3167. // if IV is null, reuse block from previous processing
  3168. if(options.iv === null) {
  3169. // must have a previous block
  3170. if(!this._prev) {
  3171. throw new Error('Invalid IV parameter.');
  3172. }
  3173. this._iv = this._prev.slice(0);
  3174. } else if(!('iv' in options)) {
  3175. throw new Error('Invalid IV parameter.');
  3176. } else {
  3177. // save IV as "previous" block
  3178. this._iv = transformIV(options.iv, this.blockSize);
  3179. this._prev = this._iv.slice(0);
  3180. }
  3181. };
  3182. modes.cbc.prototype.encrypt = function(input, output, finish) {
  3183. // not enough input to encrypt
  3184. if(input.length() < this.blockSize && !(finish && input.length() > 0)) {
  3185. return true;
  3186. }
  3187. // get next block
  3188. // CBC XOR's IV (or previous block) with plaintext
  3189. for(var i = 0; i < this._ints; ++i) {
  3190. this._inBlock[i] = this._prev[i] ^ input.getInt32();
  3191. }
  3192. // encrypt block
  3193. this.cipher.encrypt(this._inBlock, this._outBlock);
  3194. // write output, save previous block
  3195. for(var i = 0; i < this._ints; ++i) {
  3196. output.putInt32(this._outBlock[i]);
  3197. }
  3198. this._prev = this._outBlock;
  3199. };
  3200. modes.cbc.prototype.decrypt = function(input, output, finish) {
  3201. // not enough input to decrypt
  3202. if(input.length() < this.blockSize && !(finish && input.length() > 0)) {
  3203. return true;
  3204. }
  3205. // get next block
  3206. for(var i = 0; i < this._ints; ++i) {
  3207. this._inBlock[i] = input.getInt32();
  3208. }
  3209. // decrypt block
  3210. this.cipher.decrypt(this._inBlock, this._outBlock);
  3211. // write output, save previous ciphered block
  3212. // CBC XOR's IV (or previous block) with ciphertext
  3213. for(var i = 0; i < this._ints; ++i) {
  3214. output.putInt32(this._prev[i] ^ this._outBlock[i]);
  3215. }
  3216. this._prev = this._inBlock.slice(0);
  3217. };
  3218. modes.cbc.prototype.pad = function(input, options) {
  3219. // add PKCS#7 padding to block (each pad byte is the
  3220. // value of the number of pad bytes)
  3221. var padding = (input.length() === this.blockSize ?
  3222. this.blockSize : (this.blockSize - input.length()));
  3223. input.fillWithByte(padding, padding);
  3224. return true;
  3225. };
  3226. modes.cbc.prototype.unpad = function(output, options) {
  3227. // check for error: input data not a multiple of blockSize
  3228. if(options.overflow > 0) {
  3229. return false;
  3230. }
  3231. // ensure padding byte count is valid
  3232. var len = output.length();
  3233. var count = output.at(len - 1);
  3234. if(count > (this.blockSize << 2)) {
  3235. return false;
  3236. }
  3237. // trim off padding bytes
  3238. output.truncate(count);
  3239. return true;
  3240. };
  3241. /** Cipher feedback (CFB) **/
  3242. modes.cfb = function(options) {
  3243. options = options || {};
  3244. this.name = 'CFB';
  3245. this.cipher = options.cipher;
  3246. this.blockSize = options.blockSize || 16;
  3247. this._ints = this.blockSize / 4;
  3248. this._inBlock = null;
  3249. this._outBlock = new Array(this._ints);
  3250. this._partialBlock = new Array(this._ints);
  3251. this._partialOutput = forge$C.util.createBuffer();
  3252. this._partialBytes = 0;
  3253. };
  3254. modes.cfb.prototype.start = function(options) {
  3255. if(!('iv' in options)) {
  3256. throw new Error('Invalid IV parameter.');
  3257. }
  3258. // use IV as first input
  3259. this._iv = transformIV(options.iv, this.blockSize);
  3260. this._inBlock = this._iv.slice(0);
  3261. this._partialBytes = 0;
  3262. };
  3263. modes.cfb.prototype.encrypt = function(input, output, finish) {
  3264. // not enough input to encrypt
  3265. var inputLength = input.length();
  3266. if(inputLength === 0) {
  3267. return true;
  3268. }
  3269. // encrypt block
  3270. this.cipher.encrypt(this._inBlock, this._outBlock);
  3271. // handle full block
  3272. if(this._partialBytes === 0 && inputLength >= this.blockSize) {
  3273. // XOR input with output, write input as output
  3274. for(var i = 0; i < this._ints; ++i) {
  3275. this._inBlock[i] = input.getInt32() ^ this._outBlock[i];
  3276. output.putInt32(this._inBlock[i]);
  3277. }
  3278. return;
  3279. }
  3280. // handle partial block
  3281. var partialBytes = (this.blockSize - inputLength) % this.blockSize;
  3282. if(partialBytes > 0) {
  3283. partialBytes = this.blockSize - partialBytes;
  3284. }
  3285. // XOR input with output, write input as partial output
  3286. this._partialOutput.clear();
  3287. for(var i = 0; i < this._ints; ++i) {
  3288. this._partialBlock[i] = input.getInt32() ^ this._outBlock[i];
  3289. this._partialOutput.putInt32(this._partialBlock[i]);
  3290. }
  3291. if(partialBytes > 0) {
  3292. // block still incomplete, restore input buffer
  3293. input.read -= this.blockSize;
  3294. } else {
  3295. // block complete, update input block
  3296. for(var i = 0; i < this._ints; ++i) {
  3297. this._inBlock[i] = this._partialBlock[i];
  3298. }
  3299. }
  3300. // skip any previous partial bytes
  3301. if(this._partialBytes > 0) {
  3302. this._partialOutput.getBytes(this._partialBytes);
  3303. }
  3304. if(partialBytes > 0 && !finish) {
  3305. output.putBytes(this._partialOutput.getBytes(
  3306. partialBytes - this._partialBytes));
  3307. this._partialBytes = partialBytes;
  3308. return true;
  3309. }
  3310. output.putBytes(this._partialOutput.getBytes(
  3311. inputLength - this._partialBytes));
  3312. this._partialBytes = 0;
  3313. };
  3314. modes.cfb.prototype.decrypt = function(input, output, finish) {
  3315. // not enough input to decrypt
  3316. var inputLength = input.length();
  3317. if(inputLength === 0) {
  3318. return true;
  3319. }
  3320. // encrypt block (CFB always uses encryption mode)
  3321. this.cipher.encrypt(this._inBlock, this._outBlock);
  3322. // handle full block
  3323. if(this._partialBytes === 0 && inputLength >= this.blockSize) {
  3324. // XOR input with output, write input as output
  3325. for(var i = 0; i < this._ints; ++i) {
  3326. this._inBlock[i] = input.getInt32();
  3327. output.putInt32(this._inBlock[i] ^ this._outBlock[i]);
  3328. }
  3329. return;
  3330. }
  3331. // handle partial block
  3332. var partialBytes = (this.blockSize - inputLength) % this.blockSize;
  3333. if(partialBytes > 0) {
  3334. partialBytes = this.blockSize - partialBytes;
  3335. }
  3336. // XOR input with output, write input as partial output
  3337. this._partialOutput.clear();
  3338. for(var i = 0; i < this._ints; ++i) {
  3339. this._partialBlock[i] = input.getInt32();
  3340. this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]);
  3341. }
  3342. if(partialBytes > 0) {
  3343. // block still incomplete, restore input buffer
  3344. input.read -= this.blockSize;
  3345. } else {
  3346. // block complete, update input block
  3347. for(var i = 0; i < this._ints; ++i) {
  3348. this._inBlock[i] = this._partialBlock[i];
  3349. }
  3350. }
  3351. // skip any previous partial bytes
  3352. if(this._partialBytes > 0) {
  3353. this._partialOutput.getBytes(this._partialBytes);
  3354. }
  3355. if(partialBytes > 0 && !finish) {
  3356. output.putBytes(this._partialOutput.getBytes(
  3357. partialBytes - this._partialBytes));
  3358. this._partialBytes = partialBytes;
  3359. return true;
  3360. }
  3361. output.putBytes(this._partialOutput.getBytes(
  3362. inputLength - this._partialBytes));
  3363. this._partialBytes = 0;
  3364. };
  3365. /** Output feedback (OFB) **/
  3366. modes.ofb = function(options) {
  3367. options = options || {};
  3368. this.name = 'OFB';
  3369. this.cipher = options.cipher;
  3370. this.blockSize = options.blockSize || 16;
  3371. this._ints = this.blockSize / 4;
  3372. this._inBlock = null;
  3373. this._outBlock = new Array(this._ints);
  3374. this._partialOutput = forge$C.util.createBuffer();
  3375. this._partialBytes = 0;
  3376. };
  3377. modes.ofb.prototype.start = function(options) {
  3378. if(!('iv' in options)) {
  3379. throw new Error('Invalid IV parameter.');
  3380. }
  3381. // use IV as first input
  3382. this._iv = transformIV(options.iv, this.blockSize);
  3383. this._inBlock = this._iv.slice(0);
  3384. this._partialBytes = 0;
  3385. };
  3386. modes.ofb.prototype.encrypt = function(input, output, finish) {
  3387. // not enough input to encrypt
  3388. var inputLength = input.length();
  3389. if(input.length() === 0) {
  3390. return true;
  3391. }
  3392. // encrypt block (OFB always uses encryption mode)
  3393. this.cipher.encrypt(this._inBlock, this._outBlock);
  3394. // handle full block
  3395. if(this._partialBytes === 0 && inputLength >= this.blockSize) {
  3396. // XOR input with output and update next input
  3397. for(var i = 0; i < this._ints; ++i) {
  3398. output.putInt32(input.getInt32() ^ this._outBlock[i]);
  3399. this._inBlock[i] = this._outBlock[i];
  3400. }
  3401. return;
  3402. }
  3403. // handle partial block
  3404. var partialBytes = (this.blockSize - inputLength) % this.blockSize;
  3405. if(partialBytes > 0) {
  3406. partialBytes = this.blockSize - partialBytes;
  3407. }
  3408. // XOR input with output
  3409. this._partialOutput.clear();
  3410. for(var i = 0; i < this._ints; ++i) {
  3411. this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);
  3412. }
  3413. if(partialBytes > 0) {
  3414. // block still incomplete, restore input buffer
  3415. input.read -= this.blockSize;
  3416. } else {
  3417. // block complete, update input block
  3418. for(var i = 0; i < this._ints; ++i) {
  3419. this._inBlock[i] = this._outBlock[i];
  3420. }
  3421. }
  3422. // skip any previous partial bytes
  3423. if(this._partialBytes > 0) {
  3424. this._partialOutput.getBytes(this._partialBytes);
  3425. }
  3426. if(partialBytes > 0 && !finish) {
  3427. output.putBytes(this._partialOutput.getBytes(
  3428. partialBytes - this._partialBytes));
  3429. this._partialBytes = partialBytes;
  3430. return true;
  3431. }
  3432. output.putBytes(this._partialOutput.getBytes(
  3433. inputLength - this._partialBytes));
  3434. this._partialBytes = 0;
  3435. };
  3436. modes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt;
  3437. /** Counter (CTR) **/
  3438. modes.ctr = function(options) {
  3439. options = options || {};
  3440. this.name = 'CTR';
  3441. this.cipher = options.cipher;
  3442. this.blockSize = options.blockSize || 16;
  3443. this._ints = this.blockSize / 4;
  3444. this._inBlock = null;
  3445. this._outBlock = new Array(this._ints);
  3446. this._partialOutput = forge$C.util.createBuffer();
  3447. this._partialBytes = 0;
  3448. };
  3449. modes.ctr.prototype.start = function(options) {
  3450. if(!('iv' in options)) {
  3451. throw new Error('Invalid IV parameter.');
  3452. }
  3453. // use IV as first input
  3454. this._iv = transformIV(options.iv, this.blockSize);
  3455. this._inBlock = this._iv.slice(0);
  3456. this._partialBytes = 0;
  3457. };
  3458. modes.ctr.prototype.encrypt = function(input, output, finish) {
  3459. // not enough input to encrypt
  3460. var inputLength = input.length();
  3461. if(inputLength === 0) {
  3462. return true;
  3463. }
  3464. // encrypt block (CTR always uses encryption mode)
  3465. this.cipher.encrypt(this._inBlock, this._outBlock);
  3466. // handle full block
  3467. if(this._partialBytes === 0 && inputLength >= this.blockSize) {
  3468. // XOR input with output
  3469. for(var i = 0; i < this._ints; ++i) {
  3470. output.putInt32(input.getInt32() ^ this._outBlock[i]);
  3471. }
  3472. } else {
  3473. // handle partial block
  3474. var partialBytes = (this.blockSize - inputLength) % this.blockSize;
  3475. if(partialBytes > 0) {
  3476. partialBytes = this.blockSize - partialBytes;
  3477. }
  3478. // XOR input with output
  3479. this._partialOutput.clear();
  3480. for(var i = 0; i < this._ints; ++i) {
  3481. this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);
  3482. }
  3483. if(partialBytes > 0) {
  3484. // block still incomplete, restore input buffer
  3485. input.read -= this.blockSize;
  3486. }
  3487. // skip any previous partial bytes
  3488. if(this._partialBytes > 0) {
  3489. this._partialOutput.getBytes(this._partialBytes);
  3490. }
  3491. if(partialBytes > 0 && !finish) {
  3492. output.putBytes(this._partialOutput.getBytes(
  3493. partialBytes - this._partialBytes));
  3494. this._partialBytes = partialBytes;
  3495. return true;
  3496. }
  3497. output.putBytes(this._partialOutput.getBytes(
  3498. inputLength - this._partialBytes));
  3499. this._partialBytes = 0;
  3500. }
  3501. // block complete, increment counter (input block)
  3502. inc32(this._inBlock);
  3503. };
  3504. modes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt;
  3505. /** Galois/Counter Mode (GCM) **/
  3506. modes.gcm = function(options) {
  3507. options = options || {};
  3508. this.name = 'GCM';
  3509. this.cipher = options.cipher;
  3510. this.blockSize = options.blockSize || 16;
  3511. this._ints = this.blockSize / 4;
  3512. this._inBlock = new Array(this._ints);
  3513. this._outBlock = new Array(this._ints);
  3514. this._partialOutput = forge$C.util.createBuffer();
  3515. this._partialBytes = 0;
  3516. // R is actually this value concatenated with 120 more zero bits, but
  3517. // we only XOR against R so the other zeros have no effect -- we just
  3518. // apply this value to the first integer in a block
  3519. this._R = 0xE1000000;
  3520. };
  3521. modes.gcm.prototype.start = function(options) {
  3522. if(!('iv' in options)) {
  3523. throw new Error('Invalid IV parameter.');
  3524. }
  3525. // ensure IV is a byte buffer
  3526. var iv = forge$C.util.createBuffer(options.iv);
  3527. // no ciphered data processed yet
  3528. this._cipherLength = 0;
  3529. // default additional data is none
  3530. var additionalData;
  3531. if('additionalData' in options) {
  3532. additionalData = forge$C.util.createBuffer(options.additionalData);
  3533. } else {
  3534. additionalData = forge$C.util.createBuffer();
  3535. }
  3536. // default tag length is 128 bits
  3537. if('tagLength' in options) {
  3538. this._tagLength = options.tagLength;
  3539. } else {
  3540. this._tagLength = 128;
  3541. }
  3542. // if tag is given, ensure tag matches tag length
  3543. this._tag = null;
  3544. if(options.decrypt) {
  3545. // save tag to check later
  3546. this._tag = forge$C.util.createBuffer(options.tag).getBytes();
  3547. if(this._tag.length !== (this._tagLength / 8)) {
  3548. throw new Error('Authentication tag does not match tag length.');
  3549. }
  3550. }
  3551. // create tmp storage for hash calculation
  3552. this._hashBlock = new Array(this._ints);
  3553. // no tag generated yet
  3554. this.tag = null;
  3555. // generate hash subkey
  3556. // (apply block cipher to "zero" block)
  3557. this._hashSubkey = new Array(this._ints);
  3558. this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey);
  3559. // generate table M
  3560. // use 4-bit tables (32 component decomposition of a 16 byte value)
  3561. // 8-bit tables take more space and are known to have security
  3562. // vulnerabilities (in native implementations)
  3563. this.componentBits = 4;
  3564. this._m = this.generateHashTable(this._hashSubkey, this.componentBits);
  3565. // Note: support IV length different from 96 bits? (only supporting
  3566. // 96 bits is recommended by NIST SP-800-38D)
  3567. // generate J_0
  3568. var ivLength = iv.length();
  3569. if(ivLength === 12) {
  3570. // 96-bit IV
  3571. this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1];
  3572. } else {
  3573. // IV is NOT 96-bits
  3574. this._j0 = [0, 0, 0, 0];
  3575. while(iv.length() > 0) {
  3576. this._j0 = this.ghash(
  3577. this._hashSubkey, this._j0,
  3578. [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]);
  3579. }
  3580. this._j0 = this.ghash(
  3581. this._hashSubkey, this._j0, [0, 0].concat(from64To32(ivLength * 8)));
  3582. }
  3583. // generate ICB (initial counter block)
  3584. this._inBlock = this._j0.slice(0);
  3585. inc32(this._inBlock);
  3586. this._partialBytes = 0;
  3587. // consume authentication data
  3588. additionalData = forge$C.util.createBuffer(additionalData);
  3589. // save additional data length as a BE 64-bit number
  3590. this._aDataLength = from64To32(additionalData.length() * 8);
  3591. // pad additional data to 128 bit (16 byte) block size
  3592. var overflow = additionalData.length() % this.blockSize;
  3593. if(overflow) {
  3594. additionalData.fillWithByte(0, this.blockSize - overflow);
  3595. }
  3596. this._s = [0, 0, 0, 0];
  3597. while(additionalData.length() > 0) {
  3598. this._s = this.ghash(this._hashSubkey, this._s, [
  3599. additionalData.getInt32(),
  3600. additionalData.getInt32(),
  3601. additionalData.getInt32(),
  3602. additionalData.getInt32()
  3603. ]);
  3604. }
  3605. };
  3606. modes.gcm.prototype.encrypt = function(input, output, finish) {
  3607. // not enough input to encrypt
  3608. var inputLength = input.length();
  3609. if(inputLength === 0) {
  3610. return true;
  3611. }
  3612. // encrypt block
  3613. this.cipher.encrypt(this._inBlock, this._outBlock);
  3614. // handle full block
  3615. if(this._partialBytes === 0 && inputLength >= this.blockSize) {
  3616. // XOR input with output
  3617. for(var i = 0; i < this._ints; ++i) {
  3618. output.putInt32(this._outBlock[i] ^= input.getInt32());
  3619. }
  3620. this._cipherLength += this.blockSize;
  3621. } else {
  3622. // handle partial block
  3623. var partialBytes = (this.blockSize - inputLength) % this.blockSize;
  3624. if(partialBytes > 0) {
  3625. partialBytes = this.blockSize - partialBytes;
  3626. }
  3627. // XOR input with output
  3628. this._partialOutput.clear();
  3629. for(var i = 0; i < this._ints; ++i) {
  3630. this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);
  3631. }
  3632. if(partialBytes <= 0 || finish) {
  3633. // handle overflow prior to hashing
  3634. if(finish) {
  3635. // get block overflow
  3636. var overflow = inputLength % this.blockSize;
  3637. this._cipherLength += overflow;
  3638. // truncate for hash function
  3639. this._partialOutput.truncate(this.blockSize - overflow);
  3640. } else {
  3641. this._cipherLength += this.blockSize;
  3642. }
  3643. // get output block for hashing
  3644. for(var i = 0; i < this._ints; ++i) {
  3645. this._outBlock[i] = this._partialOutput.getInt32();
  3646. }
  3647. this._partialOutput.read -= this.blockSize;
  3648. }
  3649. // skip any previous partial bytes
  3650. if(this._partialBytes > 0) {
  3651. this._partialOutput.getBytes(this._partialBytes);
  3652. }
  3653. if(partialBytes > 0 && !finish) {
  3654. // block still incomplete, restore input buffer, get partial output,
  3655. // and return early
  3656. input.read -= this.blockSize;
  3657. output.putBytes(this._partialOutput.getBytes(
  3658. partialBytes - this._partialBytes));
  3659. this._partialBytes = partialBytes;
  3660. return true;
  3661. }
  3662. output.putBytes(this._partialOutput.getBytes(
  3663. inputLength - this._partialBytes));
  3664. this._partialBytes = 0;
  3665. }
  3666. // update hash block S
  3667. this._s = this.ghash(this._hashSubkey, this._s, this._outBlock);
  3668. // increment counter (input block)
  3669. inc32(this._inBlock);
  3670. };
  3671. modes.gcm.prototype.decrypt = function(input, output, finish) {
  3672. // not enough input to decrypt
  3673. var inputLength = input.length();
  3674. if(inputLength < this.blockSize && !(finish && inputLength > 0)) {
  3675. return true;
  3676. }
  3677. // encrypt block (GCM always uses encryption mode)
  3678. this.cipher.encrypt(this._inBlock, this._outBlock);
  3679. // increment counter (input block)
  3680. inc32(this._inBlock);
  3681. // update hash block S
  3682. this._hashBlock[0] = input.getInt32();
  3683. this._hashBlock[1] = input.getInt32();
  3684. this._hashBlock[2] = input.getInt32();
  3685. this._hashBlock[3] = input.getInt32();
  3686. this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock);
  3687. // XOR hash input with output
  3688. for(var i = 0; i < this._ints; ++i) {
  3689. output.putInt32(this._outBlock[i] ^ this._hashBlock[i]);
  3690. }
  3691. // increment cipher data length
  3692. if(inputLength < this.blockSize) {
  3693. this._cipherLength += inputLength % this.blockSize;
  3694. } else {
  3695. this._cipherLength += this.blockSize;
  3696. }
  3697. };
  3698. modes.gcm.prototype.afterFinish = function(output, options) {
  3699. var rval = true;
  3700. // handle overflow
  3701. if(options.decrypt && options.overflow) {
  3702. output.truncate(this.blockSize - options.overflow);
  3703. }
  3704. // handle authentication tag
  3705. this.tag = forge$C.util.createBuffer();
  3706. // concatenate additional data length with cipher length
  3707. var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8));
  3708. // include lengths in hash
  3709. this._s = this.ghash(this._hashSubkey, this._s, lengths);
  3710. // do GCTR(J_0, S)
  3711. var tag = [];
  3712. this.cipher.encrypt(this._j0, tag);
  3713. for(var i = 0; i < this._ints; ++i) {
  3714. this.tag.putInt32(this._s[i] ^ tag[i]);
  3715. }
  3716. // trim tag to length
  3717. this.tag.truncate(this.tag.length() % (this._tagLength / 8));
  3718. // check authentication tag
  3719. if(options.decrypt && this.tag.bytes() !== this._tag) {
  3720. rval = false;
  3721. }
  3722. return rval;
  3723. };
  3724. /**
  3725. * See NIST SP-800-38D 6.3 (Algorithm 1). This function performs Galois
  3726. * field multiplication. The field, GF(2^128), is defined by the polynomial:
  3727. *
  3728. * x^128 + x^7 + x^2 + x + 1
  3729. *
  3730. * Which is represented in little-endian binary form as: 11100001 (0xe1). When
  3731. * the value of a coefficient is 1, a bit is set. The value R, is the
  3732. * concatenation of this value and 120 zero bits, yielding a 128-bit value
  3733. * which matches the block size.
  3734. *
  3735. * This function will multiply two elements (vectors of bytes), X and Y, in
  3736. * the field GF(2^128). The result is initialized to zero. For each bit of
  3737. * X (out of 128), x_i, if x_i is set, then the result is multiplied (XOR'd)
  3738. * by the current value of Y. For each bit, the value of Y will be raised by
  3739. * a power of x (multiplied by the polynomial x). This can be achieved by
  3740. * shifting Y once to the right. If the current value of Y, prior to being
  3741. * multiplied by x, has 0 as its LSB, then it is a 127th degree polynomial.
  3742. * Otherwise, we must divide by R after shifting to find the remainder.
  3743. *
  3744. * @param x the first block to multiply by the second.
  3745. * @param y the second block to multiply by the first.
  3746. *
  3747. * @return the block result of the multiplication.
  3748. */
  3749. modes.gcm.prototype.multiply = function(x, y) {
  3750. var z_i = [0, 0, 0, 0];
  3751. var v_i = y.slice(0);
  3752. // calculate Z_128 (block has 128 bits)
  3753. for(var i = 0; i < 128; ++i) {
  3754. // if x_i is 0, Z_{i+1} = Z_i (unchanged)
  3755. // else Z_{i+1} = Z_i ^ V_i
  3756. // get x_i by finding 32-bit int position, then left shift 1 by remainder
  3757. var x_i = x[(i / 32) | 0] & (1 << (31 - i % 32));
  3758. if(x_i) {
  3759. z_i[0] ^= v_i[0];
  3760. z_i[1] ^= v_i[1];
  3761. z_i[2] ^= v_i[2];
  3762. z_i[3] ^= v_i[3];
  3763. }
  3764. // if LSB(V_i) is 1, V_i = V_i >> 1
  3765. // else V_i = (V_i >> 1) ^ R
  3766. this.pow(v_i, v_i);
  3767. }
  3768. return z_i;
  3769. };
  3770. modes.gcm.prototype.pow = function(x, out) {
  3771. // if LSB(x) is 1, x = x >>> 1
  3772. // else x = (x >>> 1) ^ R
  3773. var lsb = x[3] & 1;
  3774. // always do x >>> 1:
  3775. // starting with the rightmost integer, shift each integer to the right
  3776. // one bit, pulling in the bit from the integer to the left as its top
  3777. // most bit (do this for the last 3 integers)
  3778. for(var i = 3; i > 0; --i) {
  3779. out[i] = (x[i] >>> 1) | ((x[i - 1] & 1) << 31);
  3780. }
  3781. // shift the first integer normally
  3782. out[0] = x[0] >>> 1;
  3783. // if lsb was not set, then polynomial had a degree of 127 and doesn't
  3784. // need to divided; otherwise, XOR with R to find the remainder; we only
  3785. // need to XOR the first integer since R technically ends w/120 zero bits
  3786. if(lsb) {
  3787. out[0] ^= this._R;
  3788. }
  3789. };
  3790. modes.gcm.prototype.tableMultiply = function(x) {
  3791. // assumes 4-bit tables are used
  3792. var z = [0, 0, 0, 0];
  3793. for(var i = 0; i < 32; ++i) {
  3794. var idx = (i / 8) | 0;
  3795. var x_i = (x[idx] >>> ((7 - (i % 8)) * 4)) & 0xF;
  3796. var ah = this._m[i][x_i];
  3797. z[0] ^= ah[0];
  3798. z[1] ^= ah[1];
  3799. z[2] ^= ah[2];
  3800. z[3] ^= ah[3];
  3801. }
  3802. return z;
  3803. };
  3804. /**
  3805. * A continuing version of the GHASH algorithm that operates on a single
  3806. * block. The hash block, last hash value (Ym) and the new block to hash
  3807. * are given.
  3808. *
  3809. * @param h the hash block.
  3810. * @param y the previous value for Ym, use [0, 0, 0, 0] for a new hash.
  3811. * @param x the block to hash.
  3812. *
  3813. * @return the hashed value (Ym).
  3814. */
  3815. modes.gcm.prototype.ghash = function(h, y, x) {
  3816. y[0] ^= x[0];
  3817. y[1] ^= x[1];
  3818. y[2] ^= x[2];
  3819. y[3] ^= x[3];
  3820. return this.tableMultiply(y);
  3821. //return this.multiply(y, h);
  3822. };
  3823. /**
  3824. * Precomputes a table for multiplying against the hash subkey. This
  3825. * mechanism provides a substantial speed increase over multiplication
  3826. * performed without a table. The table-based multiplication this table is
  3827. * for solves X * H by multiplying each component of X by H and then
  3828. * composing the results together using XOR.
  3829. *
  3830. * This function can be used to generate tables with different bit sizes
  3831. * for the components, however, this implementation assumes there are
  3832. * 32 components of X (which is a 16 byte vector), therefore each component
  3833. * takes 4-bits (so the table is constructed with bits=4).
  3834. *
  3835. * @param h the hash subkey.
  3836. * @param bits the bit size for a component.
  3837. */
  3838. modes.gcm.prototype.generateHashTable = function(h, bits) {
  3839. // TODO: There are further optimizations that would use only the
  3840. // first table M_0 (or some variant) along with a remainder table;
  3841. // this can be explored in the future
  3842. var multiplier = 8 / bits;
  3843. var perInt = 4 * multiplier;
  3844. var size = 16 * multiplier;
  3845. var m = new Array(size);
  3846. for(var i = 0; i < size; ++i) {
  3847. var tmp = [0, 0, 0, 0];
  3848. var idx = (i / perInt) | 0;
  3849. var shft = ((perInt - 1 - (i % perInt)) * bits);
  3850. tmp[idx] = (1 << (bits - 1)) << shft;
  3851. m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits);
  3852. }
  3853. return m;
  3854. };
  3855. /**
  3856. * Generates a table for multiplying against the hash subkey for one
  3857. * particular component (out of all possible component values).
  3858. *
  3859. * @param mid the pre-multiplied value for the middle key of the table.
  3860. * @param bits the bit size for a component.
  3861. */
  3862. modes.gcm.prototype.generateSubHashTable = function(mid, bits) {
  3863. // compute the table quickly by minimizing the number of
  3864. // POW operations -- they only need to be performed for powers of 2,
  3865. // all other entries can be composed from those powers using XOR
  3866. var size = 1 << bits;
  3867. var half = size >>> 1;
  3868. var m = new Array(size);
  3869. m[half] = mid.slice(0);
  3870. var i = half >>> 1;
  3871. while(i > 0) {
  3872. // raise m0[2 * i] and store in m0[i]
  3873. this.pow(m[2 * i], m[i] = []);
  3874. i >>= 1;
  3875. }
  3876. i = 2;
  3877. while(i < half) {
  3878. for(var j = 1; j < i; ++j) {
  3879. var m_i = m[i];
  3880. var m_j = m[j];
  3881. m[i + j] = [
  3882. m_i[0] ^ m_j[0],
  3883. m_i[1] ^ m_j[1],
  3884. m_i[2] ^ m_j[2],
  3885. m_i[3] ^ m_j[3]
  3886. ];
  3887. }
  3888. i *= 2;
  3889. }
  3890. m[0] = [0, 0, 0, 0];
  3891. /* Note: We could avoid storing these by doing composition during multiply
  3892. calculate top half using composition by speed is preferred. */
  3893. for(i = half + 1; i < size; ++i) {
  3894. var c = m[i ^ half];
  3895. m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]];
  3896. }
  3897. return m;
  3898. };
  3899. /** Utility functions */
  3900. function transformIV(iv, blockSize) {
  3901. if(typeof iv === 'string') {
  3902. // convert iv string into byte buffer
  3903. iv = forge$C.util.createBuffer(iv);
  3904. }
  3905. if(forge$C.util.isArray(iv) && iv.length > 4) {
  3906. // convert iv byte array into byte buffer
  3907. var tmp = iv;
  3908. iv = forge$C.util.createBuffer();
  3909. for(var i = 0; i < tmp.length; ++i) {
  3910. iv.putByte(tmp[i]);
  3911. }
  3912. }
  3913. if(iv.length() < blockSize) {
  3914. throw new Error(
  3915. 'Invalid IV length; got ' + iv.length() +
  3916. ' bytes and expected ' + blockSize + ' bytes.');
  3917. }
  3918. if(!forge$C.util.isArray(iv)) {
  3919. // convert iv byte buffer into 32-bit integer array
  3920. var ints = [];
  3921. var blocks = blockSize / 4;
  3922. for(var i = 0; i < blocks; ++i) {
  3923. ints.push(iv.getInt32());
  3924. }
  3925. iv = ints;
  3926. }
  3927. return iv;
  3928. }
  3929. function inc32(block) {
  3930. // increment last 32 bits of block only
  3931. block[block.length - 1] = (block[block.length - 1] + 1) & 0xFFFFFFFF;
  3932. }
  3933. function from64To32(num) {
  3934. // convert 64-bit number to two BE Int32s
  3935. return [(num / 0x100000000) | 0, num & 0xFFFFFFFF];
  3936. }
  3937. /**
  3938. * Advanced Encryption Standard (AES) implementation.
  3939. *
  3940. * This implementation is based on the public domain library 'jscrypto' which
  3941. * was written by:
  3942. *
  3943. * Emily Stark (estark@stanford.edu)
  3944. * Mike Hamburg (mhamburg@stanford.edu)
  3945. * Dan Boneh (dabo@cs.stanford.edu)
  3946. *
  3947. * Parts of this code are based on the OpenSSL implementation of AES:
  3948. * http://www.openssl.org
  3949. *
  3950. * @author Dave Longley
  3951. *
  3952. * Copyright (c) 2010-2014 Digital Bazaar, Inc.
  3953. */
  3954. var forge$B = forge$F;
  3955. /* AES API */
  3956. forge$B.aes = forge$B.aes || {};
  3957. /**
  3958. * Deprecated. Instead, use:
  3959. *
  3960. * var cipher = forge.cipher.createCipher('AES-<mode>', key);
  3961. * cipher.start({iv: iv});
  3962. *
  3963. * Creates an AES cipher object to encrypt data using the given symmetric key.
  3964. * The output will be stored in the 'output' member of the returned cipher.
  3965. *
  3966. * The key and iv may be given as a string of bytes, an array of bytes,
  3967. * a byte buffer, or an array of 32-bit words.
  3968. *
  3969. * @param key the symmetric key to use.
  3970. * @param iv the initialization vector to use.
  3971. * @param output the buffer to write to, null to create one.
  3972. * @param mode the cipher mode to use (default: 'CBC').
  3973. *
  3974. * @return the cipher.
  3975. */
  3976. forge$B.aes.startEncrypting = function(key, iv, output, mode) {
  3977. var cipher = _createCipher$1({
  3978. key: key,
  3979. output: output,
  3980. decrypt: false,
  3981. mode: mode
  3982. });
  3983. cipher.start(iv);
  3984. return cipher;
  3985. };
  3986. /**
  3987. * Deprecated. Instead, use:
  3988. *
  3989. * var cipher = forge.cipher.createCipher('AES-<mode>', key);
  3990. *
  3991. * Creates an AES cipher object to encrypt data using the given symmetric key.
  3992. *
  3993. * The key may be given as a string of bytes, an array of bytes, a
  3994. * byte buffer, or an array of 32-bit words.
  3995. *
  3996. * @param key the symmetric key to use.
  3997. * @param mode the cipher mode to use (default: 'CBC').
  3998. *
  3999. * @return the cipher.
  4000. */
  4001. forge$B.aes.createEncryptionCipher = function(key, mode) {
  4002. return _createCipher$1({
  4003. key: key,
  4004. output: null,
  4005. decrypt: false,
  4006. mode: mode
  4007. });
  4008. };
  4009. /**
  4010. * Deprecated. Instead, use:
  4011. *
  4012. * var decipher = forge.cipher.createDecipher('AES-<mode>', key);
  4013. * decipher.start({iv: iv});
  4014. *
  4015. * Creates an AES cipher object to decrypt data using the given symmetric key.
  4016. * The output will be stored in the 'output' member of the returned cipher.
  4017. *
  4018. * The key and iv may be given as a string of bytes, an array of bytes,
  4019. * a byte buffer, or an array of 32-bit words.
  4020. *
  4021. * @param key the symmetric key to use.
  4022. * @param iv the initialization vector to use.
  4023. * @param output the buffer to write to, null to create one.
  4024. * @param mode the cipher mode to use (default: 'CBC').
  4025. *
  4026. * @return the cipher.
  4027. */
  4028. forge$B.aes.startDecrypting = function(key, iv, output, mode) {
  4029. var cipher = _createCipher$1({
  4030. key: key,
  4031. output: output,
  4032. decrypt: true,
  4033. mode: mode
  4034. });
  4035. cipher.start(iv);
  4036. return cipher;
  4037. };
  4038. /**
  4039. * Deprecated. Instead, use:
  4040. *
  4041. * var decipher = forge.cipher.createDecipher('AES-<mode>', key);
  4042. *
  4043. * Creates an AES cipher object to decrypt data using the given symmetric key.
  4044. *
  4045. * The key may be given as a string of bytes, an array of bytes, a
  4046. * byte buffer, or an array of 32-bit words.
  4047. *
  4048. * @param key the symmetric key to use.
  4049. * @param mode the cipher mode to use (default: 'CBC').
  4050. *
  4051. * @return the cipher.
  4052. */
  4053. forge$B.aes.createDecryptionCipher = function(key, mode) {
  4054. return _createCipher$1({
  4055. key: key,
  4056. output: null,
  4057. decrypt: true,
  4058. mode: mode
  4059. });
  4060. };
  4061. /**
  4062. * Creates a new AES cipher algorithm object.
  4063. *
  4064. * @param name the name of the algorithm.
  4065. * @param mode the mode factory function.
  4066. *
  4067. * @return the AES algorithm object.
  4068. */
  4069. forge$B.aes.Algorithm = function(name, mode) {
  4070. if(!init) {
  4071. initialize();
  4072. }
  4073. var self = this;
  4074. self.name = name;
  4075. self.mode = new mode({
  4076. blockSize: 16,
  4077. cipher: {
  4078. encrypt: function(inBlock, outBlock) {
  4079. return _updateBlock$1(self._w, inBlock, outBlock, false);
  4080. },
  4081. decrypt: function(inBlock, outBlock) {
  4082. return _updateBlock$1(self._w, inBlock, outBlock, true);
  4083. }
  4084. }
  4085. });
  4086. self._init = false;
  4087. };
  4088. /**
  4089. * Initializes this AES algorithm by expanding its key.
  4090. *
  4091. * @param options the options to use.
  4092. * key the key to use with this algorithm.
  4093. * decrypt true if the algorithm should be initialized for decryption,
  4094. * false for encryption.
  4095. */
  4096. forge$B.aes.Algorithm.prototype.initialize = function(options) {
  4097. if(this._init) {
  4098. return;
  4099. }
  4100. var key = options.key;
  4101. var tmp;
  4102. /* Note: The key may be a string of bytes, an array of bytes, a byte
  4103. buffer, or an array of 32-bit integers. If the key is in bytes, then
  4104. it must be 16, 24, or 32 bytes in length. If it is in 32-bit
  4105. integers, it must be 4, 6, or 8 integers long. */
  4106. if(typeof key === 'string' &&
  4107. (key.length === 16 || key.length === 24 || key.length === 32)) {
  4108. // convert key string into byte buffer
  4109. key = forge$B.util.createBuffer(key);
  4110. } else if(forge$B.util.isArray(key) &&
  4111. (key.length === 16 || key.length === 24 || key.length === 32)) {
  4112. // convert key integer array into byte buffer
  4113. tmp = key;
  4114. key = forge$B.util.createBuffer();
  4115. for(var i = 0; i < tmp.length; ++i) {
  4116. key.putByte(tmp[i]);
  4117. }
  4118. }
  4119. // convert key byte buffer into 32-bit integer array
  4120. if(!forge$B.util.isArray(key)) {
  4121. tmp = key;
  4122. key = [];
  4123. // key lengths of 16, 24, 32 bytes allowed
  4124. var len = tmp.length();
  4125. if(len === 16 || len === 24 || len === 32) {
  4126. len = len >>> 2;
  4127. for(var i = 0; i < len; ++i) {
  4128. key.push(tmp.getInt32());
  4129. }
  4130. }
  4131. }
  4132. // key must be an array of 32-bit integers by now
  4133. if(!forge$B.util.isArray(key) ||
  4134. !(key.length === 4 || key.length === 6 || key.length === 8)) {
  4135. throw new Error('Invalid key parameter.');
  4136. }
  4137. // encryption operation is always used for these modes
  4138. var mode = this.mode.name;
  4139. var encryptOp = (['CFB', 'OFB', 'CTR', 'GCM'].indexOf(mode) !== -1);
  4140. // do key expansion
  4141. this._w = _expandKey(key, options.decrypt && !encryptOp);
  4142. this._init = true;
  4143. };
  4144. /**
  4145. * Expands a key. Typically only used for testing.
  4146. *
  4147. * @param key the symmetric key to expand, as an array of 32-bit words.
  4148. * @param decrypt true to expand for decryption, false for encryption.
  4149. *
  4150. * @return the expanded key.
  4151. */
  4152. forge$B.aes._expandKey = function(key, decrypt) {
  4153. if(!init) {
  4154. initialize();
  4155. }
  4156. return _expandKey(key, decrypt);
  4157. };
  4158. /**
  4159. * Updates a single block. Typically only used for testing.
  4160. *
  4161. * @param w the expanded key to use.
  4162. * @param input an array of block-size 32-bit words.
  4163. * @param output an array of block-size 32-bit words.
  4164. * @param decrypt true to decrypt, false to encrypt.
  4165. */
  4166. forge$B.aes._updateBlock = _updateBlock$1;
  4167. /** Register AES algorithms **/
  4168. registerAlgorithm$1('AES-ECB', forge$B.cipher.modes.ecb);
  4169. registerAlgorithm$1('AES-CBC', forge$B.cipher.modes.cbc);
  4170. registerAlgorithm$1('AES-CFB', forge$B.cipher.modes.cfb);
  4171. registerAlgorithm$1('AES-OFB', forge$B.cipher.modes.ofb);
  4172. registerAlgorithm$1('AES-CTR', forge$B.cipher.modes.ctr);
  4173. registerAlgorithm$1('AES-GCM', forge$B.cipher.modes.gcm);
  4174. function registerAlgorithm$1(name, mode) {
  4175. var factory = function() {
  4176. return new forge$B.aes.Algorithm(name, mode);
  4177. };
  4178. forge$B.cipher.registerAlgorithm(name, factory);
  4179. }
  4180. /** AES implementation **/
  4181. var init = false; // not yet initialized
  4182. var Nb = 4; // number of words comprising the state (AES = 4)
  4183. var sbox; // non-linear substitution table used in key expansion
  4184. var isbox; // inversion of sbox
  4185. var rcon; // round constant word array
  4186. var mix; // mix-columns table
  4187. var imix; // inverse mix-columns table
  4188. /**
  4189. * Performs initialization, ie: precomputes tables to optimize for speed.
  4190. *
  4191. * One way to understand how AES works is to imagine that 'addition' and
  4192. * 'multiplication' are interfaces that require certain mathematical
  4193. * properties to hold true (ie: they are associative) but they might have
  4194. * different implementations and produce different kinds of results ...
  4195. * provided that their mathematical properties remain true. AES defines
  4196. * its own methods of addition and multiplication but keeps some important
  4197. * properties the same, ie: associativity and distributivity. The
  4198. * explanation below tries to shed some light on how AES defines addition
  4199. * and multiplication of bytes and 32-bit words in order to perform its
  4200. * encryption and decryption algorithms.
  4201. *
  4202. * The basics:
  4203. *
  4204. * The AES algorithm views bytes as binary representations of polynomials
  4205. * that have either 1 or 0 as the coefficients. It defines the addition
  4206. * or subtraction of two bytes as the XOR operation. It also defines the
  4207. * multiplication of two bytes as a finite field referred to as GF(2^8)
  4208. * (Note: 'GF' means "Galois Field" which is a field that contains a finite
  4209. * number of elements so GF(2^8) has 256 elements).
  4210. *
  4211. * This means that any two bytes can be represented as binary polynomials;
  4212. * when they multiplied together and modularly reduced by an irreducible
  4213. * polynomial of the 8th degree, the results are the field GF(2^8). The
  4214. * specific irreducible polynomial that AES uses in hexadecimal is 0x11b.
  4215. * This multiplication is associative with 0x01 as the identity:
  4216. *
  4217. * (b * 0x01 = GF(b, 0x01) = b).
  4218. *
  4219. * The operation GF(b, 0x02) can be performed at the byte level by left
  4220. * shifting b once and then XOR'ing it (to perform the modular reduction)
  4221. * with 0x11b if b is >= 128. Repeated application of the multiplication
  4222. * of 0x02 can be used to implement the multiplication of any two bytes.
  4223. *
  4224. * For instance, multiplying 0x57 and 0x13, denoted as GF(0x57, 0x13), can
  4225. * be performed by factoring 0x13 into 0x01, 0x02, and 0x10. Then these
  4226. * factors can each be multiplied by 0x57 and then added together. To do
  4227. * the multiplication, values for 0x57 multiplied by each of these 3 factors
  4228. * can be precomputed and stored in a table. To add them, the values from
  4229. * the table are XOR'd together.
  4230. *
  4231. * AES also defines addition and multiplication of words, that is 4-byte
  4232. * numbers represented as polynomials of 3 degrees where the coefficients
  4233. * are the values of the bytes.
  4234. *
  4235. * The word [a0, a1, a2, a3] is a polynomial a3x^3 + a2x^2 + a1x + a0.
  4236. *
  4237. * Addition is performed by XOR'ing like powers of x. Multiplication
  4238. * is performed in two steps, the first is an algebriac expansion as
  4239. * you would do normally (where addition is XOR). But the result is
  4240. * a polynomial larger than 3 degrees and thus it cannot fit in a word. So
  4241. * next the result is modularly reduced by an AES-specific polynomial of
  4242. * degree 4 which will always produce a polynomial of less than 4 degrees
  4243. * such that it will fit in a word. In AES, this polynomial is x^4 + 1.
  4244. *
  4245. * The modular product of two polynomials 'a' and 'b' is thus:
  4246. *
  4247. * d(x) = d3x^3 + d2x^2 + d1x + d0
  4248. * with
  4249. * d0 = GF(a0, b0) ^ GF(a3, b1) ^ GF(a2, b2) ^ GF(a1, b3)
  4250. * d1 = GF(a1, b0) ^ GF(a0, b1) ^ GF(a3, b2) ^ GF(a2, b3)
  4251. * d2 = GF(a2, b0) ^ GF(a1, b1) ^ GF(a0, b2) ^ GF(a3, b3)
  4252. * d3 = GF(a3, b0) ^ GF(a2, b1) ^ GF(a1, b2) ^ GF(a0, b3)
  4253. *
  4254. * As a matrix:
  4255. *
  4256. * [d0] = [a0 a3 a2 a1][b0]
  4257. * [d1] [a1 a0 a3 a2][b1]
  4258. * [d2] [a2 a1 a0 a3][b2]
  4259. * [d3] [a3 a2 a1 a0][b3]
  4260. *
  4261. * Special polynomials defined by AES (0x02 == {02}):
  4262. * a(x) = {03}x^3 + {01}x^2 + {01}x + {02}
  4263. * a^-1(x) = {0b}x^3 + {0d}x^2 + {09}x + {0e}.
  4264. *
  4265. * These polynomials are used in the MixColumns() and InverseMixColumns()
  4266. * operations, respectively, to cause each element in the state to affect
  4267. * the output (referred to as diffusing).
  4268. *
  4269. * RotWord() uses: a0 = a1 = a2 = {00} and a3 = {01}, which is the
  4270. * polynomial x3.
  4271. *
  4272. * The ShiftRows() method modifies the last 3 rows in the state (where
  4273. * the state is 4 words with 4 bytes per word) by shifting bytes cyclically.
  4274. * The 1st byte in the second row is moved to the end of the row. The 1st
  4275. * and 2nd bytes in the third row are moved to the end of the row. The 1st,
  4276. * 2nd, and 3rd bytes are moved in the fourth row.
  4277. *
  4278. * More details on how AES arithmetic works:
  4279. *
  4280. * In the polynomial representation of binary numbers, XOR performs addition
  4281. * and subtraction and multiplication in GF(2^8) denoted as GF(a, b)
  4282. * corresponds with the multiplication of polynomials modulo an irreducible
  4283. * polynomial of degree 8. In other words, for AES, GF(a, b) will multiply
  4284. * polynomial 'a' with polynomial 'b' and then do a modular reduction by
  4285. * an AES-specific irreducible polynomial of degree 8.
  4286. *
  4287. * A polynomial is irreducible if its only divisors are one and itself. For
  4288. * the AES algorithm, this irreducible polynomial is:
  4289. *
  4290. * m(x) = x^8 + x^4 + x^3 + x + 1,
  4291. *
  4292. * or {01}{1b} in hexadecimal notation, where each coefficient is a bit:
  4293. * 100011011 = 283 = 0x11b.
  4294. *
  4295. * For example, GF(0x57, 0x83) = 0xc1 because
  4296. *
  4297. * 0x57 = 87 = 01010111 = x^6 + x^4 + x^2 + x + 1
  4298. * 0x85 = 131 = 10000101 = x^7 + x + 1
  4299. *
  4300. * (x^6 + x^4 + x^2 + x + 1) * (x^7 + x + 1)
  4301. * = x^13 + x^11 + x^9 + x^8 + x^7 +
  4302. * x^7 + x^5 + x^3 + x^2 + x +
  4303. * x^6 + x^4 + x^2 + x + 1
  4304. * = x^13 + x^11 + x^9 + x^8 + x^6 + x^5 + x^4 + x^3 + 1 = y
  4305. * y modulo (x^8 + x^4 + x^3 + x + 1)
  4306. * = x^7 + x^6 + 1.
  4307. *
  4308. * The modular reduction by m(x) guarantees the result will be a binary
  4309. * polynomial of less than degree 8, so that it can fit in a byte.
  4310. *
  4311. * The operation to multiply a binary polynomial b with x (the polynomial
  4312. * x in binary representation is 00000010) is:
  4313. *
  4314. * b_7x^8 + b_6x^7 + b_5x^6 + b_4x^5 + b_3x^4 + b_2x^3 + b_1x^2 + b_0x^1
  4315. *
  4316. * To get GF(b, x) we must reduce that by m(x). If b_7 is 0 (that is the
  4317. * most significant bit is 0 in b) then the result is already reduced. If
  4318. * it is 1, then we can reduce it by subtracting m(x) via an XOR.
  4319. *
  4320. * It follows that multiplication by x (00000010 or 0x02) can be implemented
  4321. * by performing a left shift followed by a conditional bitwise XOR with
  4322. * 0x1b. This operation on bytes is denoted by xtime(). Multiplication by
  4323. * higher powers of x can be implemented by repeated application of xtime().
  4324. *
  4325. * By adding intermediate results, multiplication by any constant can be
  4326. * implemented. For instance:
  4327. *
  4328. * GF(0x57, 0x13) = 0xfe because:
  4329. *
  4330. * xtime(b) = (b & 128) ? (b << 1 ^ 0x11b) : (b << 1)
  4331. *
  4332. * Note: We XOR with 0x11b instead of 0x1b because in javascript our
  4333. * datatype for b can be larger than 1 byte, so a left shift will not
  4334. * automatically eliminate bits that overflow a byte ... by XOR'ing the
  4335. * overflow bit with 1 (the extra one from 0x11b) we zero it out.
  4336. *
  4337. * GF(0x57, 0x02) = xtime(0x57) = 0xae
  4338. * GF(0x57, 0x04) = xtime(0xae) = 0x47
  4339. * GF(0x57, 0x08) = xtime(0x47) = 0x8e
  4340. * GF(0x57, 0x10) = xtime(0x8e) = 0x07
  4341. *
  4342. * GF(0x57, 0x13) = GF(0x57, (0x01 ^ 0x02 ^ 0x10))
  4343. *
  4344. * And by the distributive property (since XOR is addition and GF() is
  4345. * multiplication):
  4346. *
  4347. * = GF(0x57, 0x01) ^ GF(0x57, 0x02) ^ GF(0x57, 0x10)
  4348. * = 0x57 ^ 0xae ^ 0x07
  4349. * = 0xfe.
  4350. */
  4351. function initialize() {
  4352. init = true;
  4353. /* Populate the Rcon table. These are the values given by
  4354. [x^(i-1),{00},{00},{00}] where x^(i-1) are powers of x (and x = 0x02)
  4355. in the field of GF(2^8), where i starts at 1.
  4356. rcon[0] = [0x00, 0x00, 0x00, 0x00]
  4357. rcon[1] = [0x01, 0x00, 0x00, 0x00] 2^(1-1) = 2^0 = 1
  4358. rcon[2] = [0x02, 0x00, 0x00, 0x00] 2^(2-1) = 2^1 = 2
  4359. ...
  4360. rcon[9] = [0x1B, 0x00, 0x00, 0x00] 2^(9-1) = 2^8 = 0x1B
  4361. rcon[10] = [0x36, 0x00, 0x00, 0x00] 2^(10-1) = 2^9 = 0x36
  4362. We only store the first byte because it is the only one used.
  4363. */
  4364. rcon = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36];
  4365. // compute xtime table which maps i onto GF(i, 0x02)
  4366. var xtime = new Array(256);
  4367. for(var i = 0; i < 128; ++i) {
  4368. xtime[i] = i << 1;
  4369. xtime[i + 128] = (i + 128) << 1 ^ 0x11B;
  4370. }
  4371. // compute all other tables
  4372. sbox = new Array(256);
  4373. isbox = new Array(256);
  4374. mix = new Array(4);
  4375. imix = new Array(4);
  4376. for(var i = 0; i < 4; ++i) {
  4377. mix[i] = new Array(256);
  4378. imix[i] = new Array(256);
  4379. }
  4380. var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime;
  4381. for(var i = 0; i < 256; ++i) {
  4382. /* We need to generate the SubBytes() sbox and isbox tables so that
  4383. we can perform byte substitutions. This requires us to traverse
  4384. all of the elements in GF, find their multiplicative inverses,
  4385. and apply to each the following affine transformation:
  4386. bi' = bi ^ b(i + 4) mod 8 ^ b(i + 5) mod 8 ^ b(i + 6) mod 8 ^
  4387. b(i + 7) mod 8 ^ ci
  4388. for 0 <= i < 8, where bi is the ith bit of the byte, and ci is the
  4389. ith bit of a byte c with the value {63} or {01100011}.
  4390. It is possible to traverse every possible value in a Galois field
  4391. using what is referred to as a 'generator'. There are many
  4392. generators (128 out of 256): 3,5,6,9,11,82 to name a few. To fully
  4393. traverse GF we iterate 255 times, multiplying by our generator
  4394. each time.
  4395. On each iteration we can determine the multiplicative inverse for
  4396. the current element.
  4397. Suppose there is an element in GF 'e'. For a given generator 'g',
  4398. e = g^x. The multiplicative inverse of e is g^(255 - x). It turns
  4399. out that if use the inverse of a generator as another generator
  4400. it will produce all of the corresponding multiplicative inverses
  4401. at the same time. For this reason, we choose 5 as our inverse
  4402. generator because it only requires 2 multiplies and 1 add and its
  4403. inverse, 82, requires relatively few operations as well.
  4404. In order to apply the affine transformation, the multiplicative
  4405. inverse 'ei' of 'e' can be repeatedly XOR'd (4 times) with a
  4406. bit-cycling of 'ei'. To do this 'ei' is first stored in 's' and
  4407. 'x'. Then 's' is left shifted and the high bit of 's' is made the
  4408. low bit. The resulting value is stored in 's'. Then 'x' is XOR'd
  4409. with 's' and stored in 'x'. On each subsequent iteration the same
  4410. operation is performed. When 4 iterations are complete, 'x' is
  4411. XOR'd with 'c' (0x63) and the transformed value is stored in 'x'.
  4412. For example:
  4413. s = 01000001
  4414. x = 01000001
  4415. iteration 1: s = 10000010, x ^= s
  4416. iteration 2: s = 00000101, x ^= s
  4417. iteration 3: s = 00001010, x ^= s
  4418. iteration 4: s = 00010100, x ^= s
  4419. x ^= 0x63
  4420. This can be done with a loop where s = (s << 1) | (s >> 7). However,
  4421. it can also be done by using a single 16-bit (in this case 32-bit)
  4422. number 'sx'. Since XOR is an associative operation, we can set 'sx'
  4423. to 'ei' and then XOR it with 'sx' left-shifted 1,2,3, and 4 times.
  4424. The most significant bits will flow into the high 8 bit positions
  4425. and be correctly XOR'd with one another. All that remains will be
  4426. to cycle the high 8 bits by XOR'ing them all with the lower 8 bits
  4427. afterwards.
  4428. At the same time we're populating sbox and isbox we can precompute
  4429. the multiplication we'll need to do to do MixColumns() later.
  4430. */
  4431. // apply affine transformation
  4432. sx = ei ^ (ei << 1) ^ (ei << 2) ^ (ei << 3) ^ (ei << 4);
  4433. sx = (sx >> 8) ^ (sx & 255) ^ 0x63;
  4434. // update tables
  4435. sbox[e] = sx;
  4436. isbox[sx] = e;
  4437. /* Mixing columns is done using matrix multiplication. The columns
  4438. that are to be mixed are each a single word in the current state.
  4439. The state has Nb columns (4 columns). Therefore each column is a
  4440. 4 byte word. So to mix the columns in a single column 'c' where
  4441. its rows are r0, r1, r2, and r3, we use the following matrix
  4442. multiplication:
  4443. [2 3 1 1]*[r0,c]=[r'0,c]
  4444. [1 2 3 1] [r1,c] [r'1,c]
  4445. [1 1 2 3] [r2,c] [r'2,c]
  4446. [3 1 1 2] [r3,c] [r'3,c]
  4447. r0, r1, r2, and r3 are each 1 byte of one of the words in the
  4448. state (a column). To do matrix multiplication for each mixed
  4449. column c' we multiply the corresponding row from the left matrix
  4450. with the corresponding column from the right matrix. In total, we
  4451. get 4 equations:
  4452. r0,c' = 2*r0,c + 3*r1,c + 1*r2,c + 1*r3,c
  4453. r1,c' = 1*r0,c + 2*r1,c + 3*r2,c + 1*r3,c
  4454. r2,c' = 1*r0,c + 1*r1,c + 2*r2,c + 3*r3,c
  4455. r3,c' = 3*r0,c + 1*r1,c + 1*r2,c + 2*r3,c
  4456. As usual, the multiplication is as previously defined and the
  4457. addition is XOR. In order to optimize mixing columns we can store
  4458. the multiplication results in tables. If you think of the whole
  4459. column as a word (it might help to visualize by mentally rotating
  4460. the equations above by counterclockwise 90 degrees) then you can
  4461. see that it would be useful to map the multiplications performed on
  4462. each byte (r0, r1, r2, r3) onto a word as well. For instance, we
  4463. could map 2*r0,1*r0,1*r0,3*r0 onto a word by storing 2*r0 in the
  4464. highest 8 bits and 3*r0 in the lowest 8 bits (with the other two
  4465. respectively in the middle). This means that a table can be
  4466. constructed that uses r0 as an index to the word. We can do the
  4467. same with r1, r2, and r3, creating a total of 4 tables.
  4468. To construct a full c', we can just look up each byte of c in
  4469. their respective tables and XOR the results together.
  4470. Also, to build each table we only have to calculate the word
  4471. for 2,1,1,3 for every byte ... which we can do on each iteration
  4472. of this loop since we will iterate over every byte. After we have
  4473. calculated 2,1,1,3 we can get the results for the other tables
  4474. by cycling the byte at the end to the beginning. For instance
  4475. we can take the result of table 2,1,1,3 and produce table 3,2,1,1
  4476. by moving the right most byte to the left most position just like
  4477. how you can imagine the 3 moved out of 2,1,1,3 and to the front
  4478. to produce 3,2,1,1.
  4479. There is another optimization in that the same multiples of
  4480. the current element we need in order to advance our generator
  4481. to the next iteration can be reused in performing the 2,1,1,3
  4482. calculation. We also calculate the inverse mix column tables,
  4483. with e,9,d,b being the inverse of 2,1,1,3.
  4484. When we're done, and we need to actually mix columns, the first
  4485. byte of each state word should be put through mix[0] (2,1,1,3),
  4486. the second through mix[1] (3,2,1,1) and so forth. Then they should
  4487. be XOR'd together to produce the fully mixed column.
  4488. */
  4489. // calculate mix and imix table values
  4490. sx2 = xtime[sx];
  4491. e2 = xtime[e];
  4492. e4 = xtime[e2];
  4493. e8 = xtime[e4];
  4494. me =
  4495. (sx2 << 24) ^ // 2
  4496. (sx << 16) ^ // 1
  4497. (sx << 8) ^ // 1
  4498. (sx ^ sx2); // 3
  4499. ime =
  4500. (e2 ^ e4 ^ e8) << 24 ^ // E (14)
  4501. (e ^ e8) << 16 ^ // 9
  4502. (e ^ e4 ^ e8) << 8 ^ // D (13)
  4503. (e ^ e2 ^ e8); // B (11)
  4504. // produce each of the mix tables by rotating the 2,1,1,3 value
  4505. for(var n = 0; n < 4; ++n) {
  4506. mix[n][e] = me;
  4507. imix[n][sx] = ime;
  4508. // cycle the right most byte to the left most position
  4509. // ie: 2,1,1,3 becomes 3,2,1,1
  4510. me = me << 24 | me >>> 8;
  4511. ime = ime << 24 | ime >>> 8;
  4512. }
  4513. // get next element and inverse
  4514. if(e === 0) {
  4515. // 1 is the inverse of 1
  4516. e = ei = 1;
  4517. } else {
  4518. // e = 2e + 2*2*2*(10e)) = multiply e by 82 (chosen generator)
  4519. // ei = ei + 2*2*ei = multiply ei by 5 (inverse generator)
  4520. e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]];
  4521. ei ^= xtime[xtime[ei]];
  4522. }
  4523. }
  4524. }
  4525. /**
  4526. * Generates a key schedule using the AES key expansion algorithm.
  4527. *
  4528. * The AES algorithm takes the Cipher Key, K, and performs a Key Expansion
  4529. * routine to generate a key schedule. The Key Expansion generates a total
  4530. * of Nb*(Nr + 1) words: the algorithm requires an initial set of Nb words,
  4531. * and each of the Nr rounds requires Nb words of key data. The resulting
  4532. * key schedule consists of a linear array of 4-byte words, denoted [wi ],
  4533. * with i in the range 0 <= i < Nb(Nr + 1).
  4534. *
  4535. * KeyExpansion(byte key[4*Nk], word w[Nb*(Nr+1)], Nk)
  4536. * AES-128 (Nb=4, Nk=4, Nr=10)
  4537. * AES-192 (Nb=4, Nk=6, Nr=12)
  4538. * AES-256 (Nb=4, Nk=8, Nr=14)
  4539. * Note: Nr=Nk+6.
  4540. *
  4541. * Nb is the number of columns (32-bit words) comprising the State (or
  4542. * number of bytes in a block). For AES, Nb=4.
  4543. *
  4544. * @param key the key to schedule (as an array of 32-bit words).
  4545. * @param decrypt true to modify the key schedule to decrypt, false not to.
  4546. *
  4547. * @return the generated key schedule.
  4548. */
  4549. function _expandKey(key, decrypt) {
  4550. // copy the key's words to initialize the key schedule
  4551. var w = key.slice(0);
  4552. /* RotWord() will rotate a word, moving the first byte to the last
  4553. byte's position (shifting the other bytes left).
  4554. We will be getting the value of Rcon at i / Nk. 'i' will iterate
  4555. from Nk to (Nb * Nr+1). Nk = 4 (4 byte key), Nb = 4 (4 words in
  4556. a block), Nr = Nk + 6 (10). Therefore 'i' will iterate from
  4557. 4 to 44 (exclusive). Each time we iterate 4 times, i / Nk will
  4558. increase by 1. We use a counter iNk to keep track of this.
  4559. */
  4560. // go through the rounds expanding the key
  4561. var temp, iNk = 1;
  4562. var Nk = w.length;
  4563. var Nr1 = Nk + 6 + 1;
  4564. var end = Nb * Nr1;
  4565. for(var i = Nk; i < end; ++i) {
  4566. temp = w[i - 1];
  4567. if(i % Nk === 0) {
  4568. // temp = SubWord(RotWord(temp)) ^ Rcon[i / Nk]
  4569. temp =
  4570. sbox[temp >>> 16 & 255] << 24 ^
  4571. sbox[temp >>> 8 & 255] << 16 ^
  4572. sbox[temp & 255] << 8 ^
  4573. sbox[temp >>> 24] ^ (rcon[iNk] << 24);
  4574. iNk++;
  4575. } else if(Nk > 6 && (i % Nk === 4)) {
  4576. // temp = SubWord(temp)
  4577. temp =
  4578. sbox[temp >>> 24] << 24 ^
  4579. sbox[temp >>> 16 & 255] << 16 ^
  4580. sbox[temp >>> 8 & 255] << 8 ^
  4581. sbox[temp & 255];
  4582. }
  4583. w[i] = w[i - Nk] ^ temp;
  4584. }
  4585. /* When we are updating a cipher block we always use the code path for
  4586. encryption whether we are decrypting or not (to shorten code and
  4587. simplify the generation of look up tables). However, because there
  4588. are differences in the decryption algorithm, other than just swapping
  4589. in different look up tables, we must transform our key schedule to
  4590. account for these changes:
  4591. 1. The decryption algorithm gets its key rounds in reverse order.
  4592. 2. The decryption algorithm adds the round key before mixing columns
  4593. instead of afterwards.
  4594. We don't need to modify our key schedule to handle the first case,
  4595. we can just traverse the key schedule in reverse order when decrypting.
  4596. The second case requires a little work.
  4597. The tables we built for performing rounds will take an input and then
  4598. perform SubBytes() and MixColumns() or, for the decrypt version,
  4599. InvSubBytes() and InvMixColumns(). But the decrypt algorithm requires
  4600. us to AddRoundKey() before InvMixColumns(). This means we'll need to
  4601. apply some transformations to the round key to inverse-mix its columns
  4602. so they'll be correct for moving AddRoundKey() to after the state has
  4603. had its columns inverse-mixed.
  4604. To inverse-mix the columns of the state when we're decrypting we use a
  4605. lookup table that will apply InvSubBytes() and InvMixColumns() at the
  4606. same time. However, the round key's bytes are not inverse-substituted
  4607. in the decryption algorithm. To get around this problem, we can first
  4608. substitute the bytes in the round key so that when we apply the
  4609. transformation via the InvSubBytes()+InvMixColumns() table, it will
  4610. undo our substitution leaving us with the original value that we
  4611. want -- and then inverse-mix that value.
  4612. This change will correctly alter our key schedule so that we can XOR
  4613. each round key with our already transformed decryption state. This
  4614. allows us to use the same code path as the encryption algorithm.
  4615. We make one more change to the decryption key. Since the decryption
  4616. algorithm runs in reverse from the encryption algorithm, we reverse
  4617. the order of the round keys to avoid having to iterate over the key
  4618. schedule backwards when running the encryption algorithm later in
  4619. decryption mode. In addition to reversing the order of the round keys,
  4620. we also swap each round key's 2nd and 4th rows. See the comments
  4621. section where rounds are performed for more details about why this is
  4622. done. These changes are done inline with the other substitution
  4623. described above.
  4624. */
  4625. if(decrypt) {
  4626. var tmp;
  4627. var m0 = imix[0];
  4628. var m1 = imix[1];
  4629. var m2 = imix[2];
  4630. var m3 = imix[3];
  4631. var wnew = w.slice(0);
  4632. end = w.length;
  4633. for(var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) {
  4634. // do not sub the first or last round key (round keys are Nb
  4635. // words) as no column mixing is performed before they are added,
  4636. // but do change the key order
  4637. if(i === 0 || i === (end - Nb)) {
  4638. wnew[i] = w[wi];
  4639. wnew[i + 1] = w[wi + 3];
  4640. wnew[i + 2] = w[wi + 2];
  4641. wnew[i + 3] = w[wi + 1];
  4642. } else {
  4643. // substitute each round key byte because the inverse-mix
  4644. // table will inverse-substitute it (effectively cancel the
  4645. // substitution because round key bytes aren't sub'd in
  4646. // decryption mode) and swap indexes 3 and 1
  4647. for(var n = 0; n < Nb; ++n) {
  4648. tmp = w[wi + n];
  4649. wnew[i + (3&-n)] =
  4650. m0[sbox[tmp >>> 24]] ^
  4651. m1[sbox[tmp >>> 16 & 255]] ^
  4652. m2[sbox[tmp >>> 8 & 255]] ^
  4653. m3[sbox[tmp & 255]];
  4654. }
  4655. }
  4656. }
  4657. w = wnew;
  4658. }
  4659. return w;
  4660. }
  4661. /**
  4662. * Updates a single block (16 bytes) using AES. The update will either
  4663. * encrypt or decrypt the block.
  4664. *
  4665. * @param w the key schedule.
  4666. * @param input the input block (an array of 32-bit words).
  4667. * @param output the updated output block.
  4668. * @param decrypt true to decrypt the block, false to encrypt it.
  4669. */
  4670. function _updateBlock$1(w, input, output, decrypt) {
  4671. /*
  4672. Cipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])
  4673. begin
  4674. byte state[4,Nb]
  4675. state = in
  4676. AddRoundKey(state, w[0, Nb-1])
  4677. for round = 1 step 1 to Nr-1
  4678. SubBytes(state)
  4679. ShiftRows(state)
  4680. MixColumns(state)
  4681. AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])
  4682. end for
  4683. SubBytes(state)
  4684. ShiftRows(state)
  4685. AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])
  4686. out = state
  4687. end
  4688. InvCipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])
  4689. begin
  4690. byte state[4,Nb]
  4691. state = in
  4692. AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])
  4693. for round = Nr-1 step -1 downto 1
  4694. InvShiftRows(state)
  4695. InvSubBytes(state)
  4696. AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])
  4697. InvMixColumns(state)
  4698. end for
  4699. InvShiftRows(state)
  4700. InvSubBytes(state)
  4701. AddRoundKey(state, w[0, Nb-1])
  4702. out = state
  4703. end
  4704. */
  4705. // Encrypt: AddRoundKey(state, w[0, Nb-1])
  4706. // Decrypt: AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])
  4707. var Nr = w.length / 4 - 1;
  4708. var m0, m1, m2, m3, sub;
  4709. if(decrypt) {
  4710. m0 = imix[0];
  4711. m1 = imix[1];
  4712. m2 = imix[2];
  4713. m3 = imix[3];
  4714. sub = isbox;
  4715. } else {
  4716. m0 = mix[0];
  4717. m1 = mix[1];
  4718. m2 = mix[2];
  4719. m3 = mix[3];
  4720. sub = sbox;
  4721. }
  4722. var a, b, c, d, a2, b2, c2;
  4723. a = input[0] ^ w[0];
  4724. b = input[decrypt ? 3 : 1] ^ w[1];
  4725. c = input[2] ^ w[2];
  4726. d = input[decrypt ? 1 : 3] ^ w[3];
  4727. var i = 3;
  4728. /* In order to share code we follow the encryption algorithm when both
  4729. encrypting and decrypting. To account for the changes required in the
  4730. decryption algorithm, we use different lookup tables when decrypting
  4731. and use a modified key schedule to account for the difference in the
  4732. order of transformations applied when performing rounds. We also get
  4733. key rounds in reverse order (relative to encryption). */
  4734. for(var round = 1; round < Nr; ++round) {
  4735. /* As described above, we'll be using table lookups to perform the
  4736. column mixing. Each column is stored as a word in the state (the
  4737. array 'input' has one column as a word at each index). In order to
  4738. mix a column, we perform these transformations on each row in c,
  4739. which is 1 byte in each word. The new column for c0 is c'0:
  4740. m0 m1 m2 m3
  4741. r0,c'0 = 2*r0,c0 + 3*r1,c0 + 1*r2,c0 + 1*r3,c0
  4742. r1,c'0 = 1*r0,c0 + 2*r1,c0 + 3*r2,c0 + 1*r3,c0
  4743. r2,c'0 = 1*r0,c0 + 1*r1,c0 + 2*r2,c0 + 3*r3,c0
  4744. r3,c'0 = 3*r0,c0 + 1*r1,c0 + 1*r2,c0 + 2*r3,c0
  4745. So using mix tables where c0 is a word with r0 being its upper
  4746. 8 bits and r3 being its lower 8 bits:
  4747. m0[c0 >> 24] will yield this word: [2*r0,1*r0,1*r0,3*r0]
  4748. ...
  4749. m3[c0 & 255] will yield this word: [1*r3,1*r3,3*r3,2*r3]
  4750. Therefore to mix the columns in each word in the state we
  4751. do the following (& 255 omitted for brevity):
  4752. c'0,r0 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]
  4753. c'0,r1 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]
  4754. c'0,r2 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]
  4755. c'0,r3 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]
  4756. However, before mixing, the algorithm requires us to perform
  4757. ShiftRows(). The ShiftRows() transformation cyclically shifts the
  4758. last 3 rows of the state over different offsets. The first row
  4759. (r = 0) is not shifted.
  4760. s'_r,c = s_r,(c + shift(r, Nb) mod Nb
  4761. for 0 < r < 4 and 0 <= c < Nb and
  4762. shift(1, 4) = 1
  4763. shift(2, 4) = 2
  4764. shift(3, 4) = 3.
  4765. This causes the first byte in r = 1 to be moved to the end of
  4766. the row, the first 2 bytes in r = 2 to be moved to the end of
  4767. the row, the first 3 bytes in r = 3 to be moved to the end of
  4768. the row:
  4769. r1: [c0 c1 c2 c3] => [c1 c2 c3 c0]
  4770. r2: [c0 c1 c2 c3] [c2 c3 c0 c1]
  4771. r3: [c0 c1 c2 c3] [c3 c0 c1 c2]
  4772. We can make these substitutions inline with our column mixing to
  4773. generate an updated set of equations to produce each word in the
  4774. state (note the columns have changed positions):
  4775. c0 c1 c2 c3 => c0 c1 c2 c3
  4776. c0 c1 c2 c3 c1 c2 c3 c0 (cycled 1 byte)
  4777. c0 c1 c2 c3 c2 c3 c0 c1 (cycled 2 bytes)
  4778. c0 c1 c2 c3 c3 c0 c1 c2 (cycled 3 bytes)
  4779. Therefore:
  4780. c'0 = 2*r0,c0 + 3*r1,c1 + 1*r2,c2 + 1*r3,c3
  4781. c'0 = 1*r0,c0 + 2*r1,c1 + 3*r2,c2 + 1*r3,c3
  4782. c'0 = 1*r0,c0 + 1*r1,c1 + 2*r2,c2 + 3*r3,c3
  4783. c'0 = 3*r0,c0 + 1*r1,c1 + 1*r2,c2 + 2*r3,c3
  4784. c'1 = 2*r0,c1 + 3*r1,c2 + 1*r2,c3 + 1*r3,c0
  4785. c'1 = 1*r0,c1 + 2*r1,c2 + 3*r2,c3 + 1*r3,c0
  4786. c'1 = 1*r0,c1 + 1*r1,c2 + 2*r2,c3 + 3*r3,c0
  4787. c'1 = 3*r0,c1 + 1*r1,c2 + 1*r2,c3 + 2*r3,c0
  4788. ... and so forth for c'2 and c'3. The important distinction is
  4789. that the columns are cycling, with c0 being used with the m0
  4790. map when calculating c0, but c1 being used with the m0 map when
  4791. calculating c1 ... and so forth.
  4792. When performing the inverse we transform the mirror image and
  4793. skip the bottom row, instead of the top one, and move upwards:
  4794. c3 c2 c1 c0 => c0 c3 c2 c1 (cycled 3 bytes) *same as encryption
  4795. c3 c2 c1 c0 c1 c0 c3 c2 (cycled 2 bytes)
  4796. c3 c2 c1 c0 c2 c1 c0 c3 (cycled 1 byte) *same as encryption
  4797. c3 c2 c1 c0 c3 c2 c1 c0
  4798. If you compare the resulting matrices for ShiftRows()+MixColumns()
  4799. and for InvShiftRows()+InvMixColumns() the 2nd and 4th columns are
  4800. different (in encrypt mode vs. decrypt mode). So in order to use
  4801. the same code to handle both encryption and decryption, we will
  4802. need to do some mapping.
  4803. If in encryption mode we let a=c0, b=c1, c=c2, d=c3, and r<N> be
  4804. a row number in the state, then the resulting matrix in encryption
  4805. mode for applying the above transformations would be:
  4806. r1: a b c d
  4807. r2: b c d a
  4808. r3: c d a b
  4809. r4: d a b c
  4810. If we did the same in decryption mode we would get:
  4811. r1: a d c b
  4812. r2: b a d c
  4813. r3: c b a d
  4814. r4: d c b a
  4815. If instead we swap d and b (set b=c3 and d=c1), then we get:
  4816. r1: a b c d
  4817. r2: d a b c
  4818. r3: c d a b
  4819. r4: b c d a
  4820. Now the 1st and 3rd rows are the same as the encryption matrix. All
  4821. we need to do then to make the mapping exactly the same is to swap
  4822. the 2nd and 4th rows when in decryption mode. To do this without
  4823. having to do it on each iteration, we swapped the 2nd and 4th rows
  4824. in the decryption key schedule. We also have to do the swap above
  4825. when we first pull in the input and when we set the final output. */
  4826. a2 =
  4827. m0[a >>> 24] ^
  4828. m1[b >>> 16 & 255] ^
  4829. m2[c >>> 8 & 255] ^
  4830. m3[d & 255] ^ w[++i];
  4831. b2 =
  4832. m0[b >>> 24] ^
  4833. m1[c >>> 16 & 255] ^
  4834. m2[d >>> 8 & 255] ^
  4835. m3[a & 255] ^ w[++i];
  4836. c2 =
  4837. m0[c >>> 24] ^
  4838. m1[d >>> 16 & 255] ^
  4839. m2[a >>> 8 & 255] ^
  4840. m3[b & 255] ^ w[++i];
  4841. d =
  4842. m0[d >>> 24] ^
  4843. m1[a >>> 16 & 255] ^
  4844. m2[b >>> 8 & 255] ^
  4845. m3[c & 255] ^ w[++i];
  4846. a = a2;
  4847. b = b2;
  4848. c = c2;
  4849. }
  4850. /*
  4851. Encrypt:
  4852. SubBytes(state)
  4853. ShiftRows(state)
  4854. AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])
  4855. Decrypt:
  4856. InvShiftRows(state)
  4857. InvSubBytes(state)
  4858. AddRoundKey(state, w[0, Nb-1])
  4859. */
  4860. // Note: rows are shifted inline
  4861. output[0] =
  4862. (sub[a >>> 24] << 24) ^
  4863. (sub[b >>> 16 & 255] << 16) ^
  4864. (sub[c >>> 8 & 255] << 8) ^
  4865. (sub[d & 255]) ^ w[++i];
  4866. output[decrypt ? 3 : 1] =
  4867. (sub[b >>> 24] << 24) ^
  4868. (sub[c >>> 16 & 255] << 16) ^
  4869. (sub[d >>> 8 & 255] << 8) ^
  4870. (sub[a & 255]) ^ w[++i];
  4871. output[2] =
  4872. (sub[c >>> 24] << 24) ^
  4873. (sub[d >>> 16 & 255] << 16) ^
  4874. (sub[a >>> 8 & 255] << 8) ^
  4875. (sub[b & 255]) ^ w[++i];
  4876. output[decrypt ? 1 : 3] =
  4877. (sub[d >>> 24] << 24) ^
  4878. (sub[a >>> 16 & 255] << 16) ^
  4879. (sub[b >>> 8 & 255] << 8) ^
  4880. (sub[c & 255]) ^ w[++i];
  4881. }
  4882. /**
  4883. * Deprecated. Instead, use:
  4884. *
  4885. * forge.cipher.createCipher('AES-<mode>', key);
  4886. * forge.cipher.createDecipher('AES-<mode>', key);
  4887. *
  4888. * Creates a deprecated AES cipher object. This object's mode will default to
  4889. * CBC (cipher-block-chaining).
  4890. *
  4891. * The key and iv may be given as a string of bytes, an array of bytes, a
  4892. * byte buffer, or an array of 32-bit words.
  4893. *
  4894. * @param options the options to use.
  4895. * key the symmetric key to use.
  4896. * output the buffer to write to.
  4897. * decrypt true for decryption, false for encryption.
  4898. * mode the cipher mode to use (default: 'CBC').
  4899. *
  4900. * @return the cipher.
  4901. */
  4902. function _createCipher$1(options) {
  4903. options = options || {};
  4904. var mode = (options.mode || 'CBC').toUpperCase();
  4905. var algorithm = 'AES-' + mode;
  4906. var cipher;
  4907. if(options.decrypt) {
  4908. cipher = forge$B.cipher.createDecipher(algorithm, options.key);
  4909. } else {
  4910. cipher = forge$B.cipher.createCipher(algorithm, options.key);
  4911. }
  4912. // backwards compatible start API
  4913. var start = cipher.start;
  4914. cipher.start = function(iv, options) {
  4915. // backwards compatibility: support second arg as output buffer
  4916. var output = null;
  4917. if(options instanceof forge$B.util.ByteBuffer) {
  4918. output = options;
  4919. options = {};
  4920. }
  4921. options = options || {};
  4922. options.output = output;
  4923. options.iv = iv;
  4924. start.call(cipher, options);
  4925. };
  4926. return cipher;
  4927. }
  4928. /**
  4929. * Object IDs for ASN.1.
  4930. *
  4931. * @author Dave Longley
  4932. *
  4933. * Copyright (c) 2010-2013 Digital Bazaar, Inc.
  4934. */
  4935. var forge$A = forge$F;
  4936. forge$A.pki = forge$A.pki || {};
  4937. var oids$2 = forge$A.pki.oids = forge$A.oids = forge$A.oids || {};
  4938. // set id to name mapping and name to id mapping
  4939. function _IN(id, name) {
  4940. oids$2[id] = name;
  4941. oids$2[name] = id;
  4942. }
  4943. // set id to name mapping only
  4944. function _I_(id, name) {
  4945. oids$2[id] = name;
  4946. }
  4947. // algorithm OIDs
  4948. _IN('1.2.840.113549.1.1.1', 'rsaEncryption');
  4949. // Note: md2 & md4 not implemented
  4950. //_IN('1.2.840.113549.1.1.2', 'md2WithRSAEncryption');
  4951. //_IN('1.2.840.113549.1.1.3', 'md4WithRSAEncryption');
  4952. _IN('1.2.840.113549.1.1.4', 'md5WithRSAEncryption');
  4953. _IN('1.2.840.113549.1.1.5', 'sha1WithRSAEncryption');
  4954. _IN('1.2.840.113549.1.1.7', 'RSAES-OAEP');
  4955. _IN('1.2.840.113549.1.1.8', 'mgf1');
  4956. _IN('1.2.840.113549.1.1.9', 'pSpecified');
  4957. _IN('1.2.840.113549.1.1.10', 'RSASSA-PSS');
  4958. _IN('1.2.840.113549.1.1.11', 'sha256WithRSAEncryption');
  4959. _IN('1.2.840.113549.1.1.12', 'sha384WithRSAEncryption');
  4960. _IN('1.2.840.113549.1.1.13', 'sha512WithRSAEncryption');
  4961. // Edwards-curve Digital Signature Algorithm (EdDSA) Ed25519
  4962. _IN('1.3.101.112', 'EdDSA25519');
  4963. _IN('1.2.840.10040.4.3', 'dsa-with-sha1');
  4964. _IN('1.3.14.3.2.7', 'desCBC');
  4965. _IN('1.3.14.3.2.26', 'sha1');
  4966. _IN('2.16.840.1.101.3.4.2.1', 'sha256');
  4967. _IN('2.16.840.1.101.3.4.2.2', 'sha384');
  4968. _IN('2.16.840.1.101.3.4.2.3', 'sha512');
  4969. _IN('1.2.840.113549.2.5', 'md5');
  4970. // pkcs#7 content types
  4971. _IN('1.2.840.113549.1.7.1', 'data');
  4972. _IN('1.2.840.113549.1.7.2', 'signedData');
  4973. _IN('1.2.840.113549.1.7.3', 'envelopedData');
  4974. _IN('1.2.840.113549.1.7.4', 'signedAndEnvelopedData');
  4975. _IN('1.2.840.113549.1.7.5', 'digestedData');
  4976. _IN('1.2.840.113549.1.7.6', 'encryptedData');
  4977. // pkcs#9 oids
  4978. _IN('1.2.840.113549.1.9.1', 'emailAddress');
  4979. _IN('1.2.840.113549.1.9.2', 'unstructuredName');
  4980. _IN('1.2.840.113549.1.9.3', 'contentType');
  4981. _IN('1.2.840.113549.1.9.4', 'messageDigest');
  4982. _IN('1.2.840.113549.1.9.5', 'signingTime');
  4983. _IN('1.2.840.113549.1.9.6', 'counterSignature');
  4984. _IN('1.2.840.113549.1.9.7', 'challengePassword');
  4985. _IN('1.2.840.113549.1.9.8', 'unstructuredAddress');
  4986. _IN('1.2.840.113549.1.9.14', 'extensionRequest');
  4987. _IN('1.2.840.113549.1.9.20', 'friendlyName');
  4988. _IN('1.2.840.113549.1.9.21', 'localKeyId');
  4989. _IN('1.2.840.113549.1.9.22.1', 'x509Certificate');
  4990. // pkcs#12 safe bags
  4991. _IN('1.2.840.113549.1.12.10.1.1', 'keyBag');
  4992. _IN('1.2.840.113549.1.12.10.1.2', 'pkcs8ShroudedKeyBag');
  4993. _IN('1.2.840.113549.1.12.10.1.3', 'certBag');
  4994. _IN('1.2.840.113549.1.12.10.1.4', 'crlBag');
  4995. _IN('1.2.840.113549.1.12.10.1.5', 'secretBag');
  4996. _IN('1.2.840.113549.1.12.10.1.6', 'safeContentsBag');
  4997. // password-based-encryption for pkcs#12
  4998. _IN('1.2.840.113549.1.5.13', 'pkcs5PBES2');
  4999. _IN('1.2.840.113549.1.5.12', 'pkcs5PBKDF2');
  5000. _IN('1.2.840.113549.1.12.1.1', 'pbeWithSHAAnd128BitRC4');
  5001. _IN('1.2.840.113549.1.12.1.2', 'pbeWithSHAAnd40BitRC4');
  5002. _IN('1.2.840.113549.1.12.1.3', 'pbeWithSHAAnd3-KeyTripleDES-CBC');
  5003. _IN('1.2.840.113549.1.12.1.4', 'pbeWithSHAAnd2-KeyTripleDES-CBC');
  5004. _IN('1.2.840.113549.1.12.1.5', 'pbeWithSHAAnd128BitRC2-CBC');
  5005. _IN('1.2.840.113549.1.12.1.6', 'pbewithSHAAnd40BitRC2-CBC');
  5006. // hmac OIDs
  5007. _IN('1.2.840.113549.2.7', 'hmacWithSHA1');
  5008. _IN('1.2.840.113549.2.8', 'hmacWithSHA224');
  5009. _IN('1.2.840.113549.2.9', 'hmacWithSHA256');
  5010. _IN('1.2.840.113549.2.10', 'hmacWithSHA384');
  5011. _IN('1.2.840.113549.2.11', 'hmacWithSHA512');
  5012. // symmetric key algorithm oids
  5013. _IN('1.2.840.113549.3.7', 'des-EDE3-CBC');
  5014. _IN('2.16.840.1.101.3.4.1.2', 'aes128-CBC');
  5015. _IN('2.16.840.1.101.3.4.1.22', 'aes192-CBC');
  5016. _IN('2.16.840.1.101.3.4.1.42', 'aes256-CBC');
  5017. // certificate issuer/subject OIDs
  5018. _IN('2.5.4.3', 'commonName');
  5019. _IN('2.5.4.5', 'serialName');
  5020. _IN('2.5.4.6', 'countryName');
  5021. _IN('2.5.4.7', 'localityName');
  5022. _IN('2.5.4.8', 'stateOrProvinceName');
  5023. _IN('2.5.4.9', 'streetAddress');
  5024. _IN('2.5.4.10', 'organizationName');
  5025. _IN('2.5.4.11', 'organizationalUnitName');
  5026. _IN('2.5.4.13', 'description');
  5027. _IN('2.5.4.15', 'businessCategory');
  5028. _IN('2.5.4.17', 'postalCode');
  5029. _IN('1.3.6.1.4.1.311.60.2.1.2', 'jurisdictionOfIncorporationStateOrProvinceName');
  5030. _IN('1.3.6.1.4.1.311.60.2.1.3', 'jurisdictionOfIncorporationCountryName');
  5031. // X.509 extension OIDs
  5032. _IN('2.16.840.1.113730.1.1', 'nsCertType');
  5033. _IN('2.16.840.1.113730.1.13', 'nsComment'); // deprecated in theory; still widely used
  5034. _I_('2.5.29.1', 'authorityKeyIdentifier'); // deprecated, use .35
  5035. _I_('2.5.29.2', 'keyAttributes'); // obsolete use .37 or .15
  5036. _I_('2.5.29.3', 'certificatePolicies'); // deprecated, use .32
  5037. _I_('2.5.29.4', 'keyUsageRestriction'); // obsolete use .37 or .15
  5038. _I_('2.5.29.5', 'policyMapping'); // deprecated use .33
  5039. _I_('2.5.29.6', 'subtreesConstraint'); // obsolete use .30
  5040. _I_('2.5.29.7', 'subjectAltName'); // deprecated use .17
  5041. _I_('2.5.29.8', 'issuerAltName'); // deprecated use .18
  5042. _I_('2.5.29.9', 'subjectDirectoryAttributes');
  5043. _I_('2.5.29.10', 'basicConstraints'); // deprecated use .19
  5044. _I_('2.5.29.11', 'nameConstraints'); // deprecated use .30
  5045. _I_('2.5.29.12', 'policyConstraints'); // deprecated use .36
  5046. _I_('2.5.29.13', 'basicConstraints'); // deprecated use .19
  5047. _IN('2.5.29.14', 'subjectKeyIdentifier');
  5048. _IN('2.5.29.15', 'keyUsage');
  5049. _I_('2.5.29.16', 'privateKeyUsagePeriod');
  5050. _IN('2.5.29.17', 'subjectAltName');
  5051. _IN('2.5.29.18', 'issuerAltName');
  5052. _IN('2.5.29.19', 'basicConstraints');
  5053. _I_('2.5.29.20', 'cRLNumber');
  5054. _I_('2.5.29.21', 'cRLReason');
  5055. _I_('2.5.29.22', 'expirationDate');
  5056. _I_('2.5.29.23', 'instructionCode');
  5057. _I_('2.5.29.24', 'invalidityDate');
  5058. _I_('2.5.29.25', 'cRLDistributionPoints'); // deprecated use .31
  5059. _I_('2.5.29.26', 'issuingDistributionPoint'); // deprecated use .28
  5060. _I_('2.5.29.27', 'deltaCRLIndicator');
  5061. _I_('2.5.29.28', 'issuingDistributionPoint');
  5062. _I_('2.5.29.29', 'certificateIssuer');
  5063. _I_('2.5.29.30', 'nameConstraints');
  5064. _IN('2.5.29.31', 'cRLDistributionPoints');
  5065. _IN('2.5.29.32', 'certificatePolicies');
  5066. _I_('2.5.29.33', 'policyMappings');
  5067. _I_('2.5.29.34', 'policyConstraints'); // deprecated use .36
  5068. _IN('2.5.29.35', 'authorityKeyIdentifier');
  5069. _I_('2.5.29.36', 'policyConstraints');
  5070. _IN('2.5.29.37', 'extKeyUsage');
  5071. _I_('2.5.29.46', 'freshestCRL');
  5072. _I_('2.5.29.54', 'inhibitAnyPolicy');
  5073. // extKeyUsage purposes
  5074. _IN('1.3.6.1.4.1.11129.2.4.2', 'timestampList');
  5075. _IN('1.3.6.1.5.5.7.1.1', 'authorityInfoAccess');
  5076. _IN('1.3.6.1.5.5.7.3.1', 'serverAuth');
  5077. _IN('1.3.6.1.5.5.7.3.2', 'clientAuth');
  5078. _IN('1.3.6.1.5.5.7.3.3', 'codeSigning');
  5079. _IN('1.3.6.1.5.5.7.3.4', 'emailProtection');
  5080. _IN('1.3.6.1.5.5.7.3.8', 'timeStamping');
  5081. /**
  5082. * Javascript implementation of Abstract Syntax Notation Number One.
  5083. *
  5084. * @author Dave Longley
  5085. *
  5086. * Copyright (c) 2010-2015 Digital Bazaar, Inc.
  5087. *
  5088. * An API for storing data using the Abstract Syntax Notation Number One
  5089. * format using DER (Distinguished Encoding Rules) encoding. This encoding is
  5090. * commonly used to store data for PKI, i.e. X.509 Certificates, and this
  5091. * implementation exists for that purpose.
  5092. *
  5093. * Abstract Syntax Notation Number One (ASN.1) is used to define the abstract
  5094. * syntax of information without restricting the way the information is encoded
  5095. * for transmission. It provides a standard that allows for open systems
  5096. * communication. ASN.1 defines the syntax of information data and a number of
  5097. * simple data types as well as a notation for describing them and specifying
  5098. * values for them.
  5099. *
  5100. * The RSA algorithm creates public and private keys that are often stored in
  5101. * X.509 or PKCS#X formats -- which use ASN.1 (encoded in DER format). This
  5102. * class provides the most basic functionality required to store and load DSA
  5103. * keys that are encoded according to ASN.1.
  5104. *
  5105. * The most common binary encodings for ASN.1 are BER (Basic Encoding Rules)
  5106. * and DER (Distinguished Encoding Rules). DER is just a subset of BER that
  5107. * has stricter requirements for how data must be encoded.
  5108. *
  5109. * Each ASN.1 structure has a tag (a byte identifying the ASN.1 structure type)
  5110. * and a byte array for the value of this ASN1 structure which may be data or a
  5111. * list of ASN.1 structures.
  5112. *
  5113. * Each ASN.1 structure using BER is (Tag-Length-Value):
  5114. *
  5115. * | byte 0 | bytes X | bytes Y |
  5116. * |--------|---------|----------
  5117. * | tag | length | value |
  5118. *
  5119. * ASN.1 allows for tags to be of "High-tag-number form" which allows a tag to
  5120. * be two or more octets, but that is not supported by this class. A tag is
  5121. * only 1 byte. Bits 1-5 give the tag number (ie the data type within a
  5122. * particular 'class'), 6 indicates whether or not the ASN.1 value is
  5123. * constructed from other ASN.1 values, and bits 7 and 8 give the 'class'. If
  5124. * bits 7 and 8 are both zero, the class is UNIVERSAL. If only bit 7 is set,
  5125. * then the class is APPLICATION. If only bit 8 is set, then the class is
  5126. * CONTEXT_SPECIFIC. If both bits 7 and 8 are set, then the class is PRIVATE.
  5127. * The tag numbers for the data types for the class UNIVERSAL are listed below:
  5128. *
  5129. * UNIVERSAL 0 Reserved for use by the encoding rules
  5130. * UNIVERSAL 1 Boolean type
  5131. * UNIVERSAL 2 Integer type
  5132. * UNIVERSAL 3 Bitstring type
  5133. * UNIVERSAL 4 Octetstring type
  5134. * UNIVERSAL 5 Null type
  5135. * UNIVERSAL 6 Object identifier type
  5136. * UNIVERSAL 7 Object descriptor type
  5137. * UNIVERSAL 8 External type and Instance-of type
  5138. * UNIVERSAL 9 Real type
  5139. * UNIVERSAL 10 Enumerated type
  5140. * UNIVERSAL 11 Embedded-pdv type
  5141. * UNIVERSAL 12 UTF8String type
  5142. * UNIVERSAL 13 Relative object identifier type
  5143. * UNIVERSAL 14-15 Reserved for future editions
  5144. * UNIVERSAL 16 Sequence and Sequence-of types
  5145. * UNIVERSAL 17 Set and Set-of types
  5146. * UNIVERSAL 18-22, 25-30 Character string types
  5147. * UNIVERSAL 23-24 Time types
  5148. *
  5149. * The length of an ASN.1 structure is specified after the tag identifier.
  5150. * There is a definite form and an indefinite form. The indefinite form may
  5151. * be used if the encoding is constructed and not all immediately available.
  5152. * The indefinite form is encoded using a length byte with only the 8th bit
  5153. * set. The end of the constructed object is marked using end-of-contents
  5154. * octets (two zero bytes).
  5155. *
  5156. * The definite form looks like this:
  5157. *
  5158. * The length may take up 1 or more bytes, it depends on the length of the
  5159. * value of the ASN.1 structure. DER encoding requires that if the ASN.1
  5160. * structure has a value that has a length greater than 127, more than 1 byte
  5161. * will be used to store its length, otherwise just one byte will be used.
  5162. * This is strict.
  5163. *
  5164. * In the case that the length of the ASN.1 value is less than 127, 1 octet
  5165. * (byte) is used to store the "short form" length. The 8th bit has a value of
  5166. * 0 indicating the length is "short form" and not "long form" and bits 7-1
  5167. * give the length of the data. (The 8th bit is the left-most, most significant
  5168. * bit: also known as big endian or network format).
  5169. *
  5170. * In the case that the length of the ASN.1 value is greater than 127, 2 to
  5171. * 127 octets (bytes) are used to store the "long form" length. The first
  5172. * byte's 8th bit is set to 1 to indicate the length is "long form." Bits 7-1
  5173. * give the number of additional octets. All following octets are in base 256
  5174. * with the most significant digit first (typical big-endian binary unsigned
  5175. * integer storage). So, for instance, if the length of a value was 257, the
  5176. * first byte would be set to:
  5177. *
  5178. * 10000010 = 130 = 0x82.
  5179. *
  5180. * This indicates there are 2 octets (base 256) for the length. The second and
  5181. * third bytes (the octets just mentioned) would store the length in base 256:
  5182. *
  5183. * octet 2: 00000001 = 1 * 256^1 = 256
  5184. * octet 3: 00000001 = 1 * 256^0 = 1
  5185. * total = 257
  5186. *
  5187. * The algorithm for converting a js integer value of 257 to base-256 is:
  5188. *
  5189. * var value = 257;
  5190. * var bytes = [];
  5191. * bytes[0] = (value >>> 8) & 0xFF; // most significant byte first
  5192. * bytes[1] = value & 0xFF; // least significant byte last
  5193. *
  5194. * On the ASN.1 UNIVERSAL Object Identifier (OID) type:
  5195. *
  5196. * An OID can be written like: "value1.value2.value3...valueN"
  5197. *
  5198. * The DER encoding rules:
  5199. *
  5200. * The first byte has the value 40 * value1 + value2.
  5201. * The following bytes, if any, encode the remaining values. Each value is
  5202. * encoded in base 128, most significant digit first (big endian), with as
  5203. * few digits as possible, and the most significant bit of each byte set
  5204. * to 1 except the last in each value's encoding. For example: Given the
  5205. * OID "1.2.840.113549", its DER encoding is (remember each byte except the
  5206. * last one in each encoding is OR'd with 0x80):
  5207. *
  5208. * byte 1: 40 * 1 + 2 = 42 = 0x2A.
  5209. * bytes 2-3: 128 * 6 + 72 = 840 = 6 72 = 6 72 = 0x0648 = 0x8648
  5210. * bytes 4-6: 16384 * 6 + 128 * 119 + 13 = 6 119 13 = 0x06770D = 0x86F70D
  5211. *
  5212. * The final value is: 0x2A864886F70D.
  5213. * The full OID (including ASN.1 tag and length of 6 bytes) is:
  5214. * 0x06062A864886F70D
  5215. */
  5216. var forge$z = forge$F;
  5217. /* ASN.1 API */
  5218. var asn1$8 = forge$z.asn1 = forge$z.asn1 || {};
  5219. /**
  5220. * ASN.1 classes.
  5221. */
  5222. asn1$8.Class = {
  5223. UNIVERSAL: 0x00,
  5224. APPLICATION: 0x40,
  5225. CONTEXT_SPECIFIC: 0x80,
  5226. PRIVATE: 0xC0
  5227. };
  5228. /**
  5229. * ASN.1 types. Not all types are supported by this implementation, only
  5230. * those necessary to implement a simple PKI are implemented.
  5231. */
  5232. asn1$8.Type = {
  5233. NONE: 0,
  5234. BOOLEAN: 1,
  5235. INTEGER: 2,
  5236. BITSTRING: 3,
  5237. OCTETSTRING: 4,
  5238. NULL: 5,
  5239. OID: 6,
  5240. ODESC: 7,
  5241. EXTERNAL: 8,
  5242. REAL: 9,
  5243. ENUMERATED: 10,
  5244. EMBEDDED: 11,
  5245. UTF8: 12,
  5246. ROID: 13,
  5247. SEQUENCE: 16,
  5248. SET: 17,
  5249. PRINTABLESTRING: 19,
  5250. IA5STRING: 22,
  5251. UTCTIME: 23,
  5252. GENERALIZEDTIME: 24,
  5253. BMPSTRING: 30
  5254. };
  5255. /**
  5256. * Creates a new asn1 object.
  5257. *
  5258. * @param tagClass the tag class for the object.
  5259. * @param type the data type (tag number) for the object.
  5260. * @param constructed true if the asn1 object is in constructed form.
  5261. * @param value the value for the object, if it is not constructed.
  5262. * @param [options] the options to use:
  5263. * [bitStringContents] the plain BIT STRING content including padding
  5264. * byte.
  5265. *
  5266. * @return the asn1 object.
  5267. */
  5268. asn1$8.create = function(tagClass, type, constructed, value, options) {
  5269. /* An asn1 object has a tagClass, a type, a constructed flag, and a
  5270. value. The value's type depends on the constructed flag. If
  5271. constructed, it will contain a list of other asn1 objects. If not,
  5272. it will contain the ASN.1 value as an array of bytes formatted
  5273. according to the ASN.1 data type. */
  5274. // remove undefined values
  5275. if(forge$z.util.isArray(value)) {
  5276. var tmp = [];
  5277. for(var i = 0; i < value.length; ++i) {
  5278. if(value[i] !== undefined) {
  5279. tmp.push(value[i]);
  5280. }
  5281. }
  5282. value = tmp;
  5283. }
  5284. var obj = {
  5285. tagClass: tagClass,
  5286. type: type,
  5287. constructed: constructed,
  5288. composed: constructed || forge$z.util.isArray(value),
  5289. value: value
  5290. };
  5291. if(options && 'bitStringContents' in options) {
  5292. // TODO: copy byte buffer if it's a buffer not a string
  5293. obj.bitStringContents = options.bitStringContents;
  5294. // TODO: add readonly flag to avoid this overhead
  5295. // save copy to detect changes
  5296. obj.original = asn1$8.copy(obj);
  5297. }
  5298. return obj;
  5299. };
  5300. /**
  5301. * Copies an asn1 object.
  5302. *
  5303. * @param obj the asn1 object.
  5304. * @param [options] copy options:
  5305. * [excludeBitStringContents] true to not copy bitStringContents
  5306. *
  5307. * @return the a copy of the asn1 object.
  5308. */
  5309. asn1$8.copy = function(obj, options) {
  5310. var copy;
  5311. if(forge$z.util.isArray(obj)) {
  5312. copy = [];
  5313. for(var i = 0; i < obj.length; ++i) {
  5314. copy.push(asn1$8.copy(obj[i], options));
  5315. }
  5316. return copy;
  5317. }
  5318. if(typeof obj === 'string') {
  5319. // TODO: copy byte buffer if it's a buffer not a string
  5320. return obj;
  5321. }
  5322. copy = {
  5323. tagClass: obj.tagClass,
  5324. type: obj.type,
  5325. constructed: obj.constructed,
  5326. composed: obj.composed,
  5327. value: asn1$8.copy(obj.value, options)
  5328. };
  5329. if(options && !options.excludeBitStringContents) {
  5330. // TODO: copy byte buffer if it's a buffer not a string
  5331. copy.bitStringContents = obj.bitStringContents;
  5332. }
  5333. return copy;
  5334. };
  5335. /**
  5336. * Compares asn1 objects for equality.
  5337. *
  5338. * Note this function does not run in constant time.
  5339. *
  5340. * @param obj1 the first asn1 object.
  5341. * @param obj2 the second asn1 object.
  5342. * @param [options] compare options:
  5343. * [includeBitStringContents] true to compare bitStringContents
  5344. *
  5345. * @return true if the asn1 objects are equal.
  5346. */
  5347. asn1$8.equals = function(obj1, obj2, options) {
  5348. if(forge$z.util.isArray(obj1)) {
  5349. if(!forge$z.util.isArray(obj2)) {
  5350. return false;
  5351. }
  5352. if(obj1.length !== obj2.length) {
  5353. return false;
  5354. }
  5355. for(var i = 0; i < obj1.length; ++i) {
  5356. if(!asn1$8.equals(obj1[i], obj2[i])) {
  5357. return false;
  5358. }
  5359. }
  5360. return true;
  5361. }
  5362. if(typeof obj1 !== typeof obj2) {
  5363. return false;
  5364. }
  5365. if(typeof obj1 === 'string') {
  5366. return obj1 === obj2;
  5367. }
  5368. var equal = obj1.tagClass === obj2.tagClass &&
  5369. obj1.type === obj2.type &&
  5370. obj1.constructed === obj2.constructed &&
  5371. obj1.composed === obj2.composed &&
  5372. asn1$8.equals(obj1.value, obj2.value);
  5373. if(options && options.includeBitStringContents) {
  5374. equal = equal && (obj1.bitStringContents === obj2.bitStringContents);
  5375. }
  5376. return equal;
  5377. };
  5378. /**
  5379. * Gets the length of a BER-encoded ASN.1 value.
  5380. *
  5381. * In case the length is not specified, undefined is returned.
  5382. *
  5383. * @param b the BER-encoded ASN.1 byte buffer, starting with the first
  5384. * length byte.
  5385. *
  5386. * @return the length of the BER-encoded ASN.1 value or undefined.
  5387. */
  5388. asn1$8.getBerValueLength = function(b) {
  5389. // TODO: move this function and related DER/BER functions to a der.js
  5390. // file; better abstract ASN.1 away from der/ber.
  5391. var b2 = b.getByte();
  5392. if(b2 === 0x80) {
  5393. return undefined;
  5394. }
  5395. // see if the length is "short form" or "long form" (bit 8 set)
  5396. var length;
  5397. var longForm = b2 & 0x80;
  5398. if(!longForm) {
  5399. // length is just the first byte
  5400. length = b2;
  5401. } else {
  5402. // the number of bytes the length is specified in bits 7 through 1
  5403. // and each length byte is in big-endian base-256
  5404. length = b.getInt((b2 & 0x7F) << 3);
  5405. }
  5406. return length;
  5407. };
  5408. /**
  5409. * Check if the byte buffer has enough bytes. Throws an Error if not.
  5410. *
  5411. * @param bytes the byte buffer to parse from.
  5412. * @param remaining the bytes remaining in the current parsing state.
  5413. * @param n the number of bytes the buffer must have.
  5414. */
  5415. function _checkBufferLength(bytes, remaining, n) {
  5416. if(n > remaining) {
  5417. var error = new Error('Too few bytes to parse DER.');
  5418. error.available = bytes.length();
  5419. error.remaining = remaining;
  5420. error.requested = n;
  5421. throw error;
  5422. }
  5423. }
  5424. /**
  5425. * Gets the length of a BER-encoded ASN.1 value.
  5426. *
  5427. * In case the length is not specified, undefined is returned.
  5428. *
  5429. * @param bytes the byte buffer to parse from.
  5430. * @param remaining the bytes remaining in the current parsing state.
  5431. *
  5432. * @return the length of the BER-encoded ASN.1 value or undefined.
  5433. */
  5434. var _getValueLength = function(bytes, remaining) {
  5435. // TODO: move this function and related DER/BER functions to a der.js
  5436. // file; better abstract ASN.1 away from der/ber.
  5437. // fromDer already checked that this byte exists
  5438. var b2 = bytes.getByte();
  5439. remaining--;
  5440. if(b2 === 0x80) {
  5441. return undefined;
  5442. }
  5443. // see if the length is "short form" or "long form" (bit 8 set)
  5444. var length;
  5445. var longForm = b2 & 0x80;
  5446. if(!longForm) {
  5447. // length is just the first byte
  5448. length = b2;
  5449. } else {
  5450. // the number of bytes the length is specified in bits 7 through 1
  5451. // and each length byte is in big-endian base-256
  5452. var longFormBytes = b2 & 0x7F;
  5453. _checkBufferLength(bytes, remaining, longFormBytes);
  5454. length = bytes.getInt(longFormBytes << 3);
  5455. }
  5456. // FIXME: this will only happen for 32 bit getInt with high bit set
  5457. if(length < 0) {
  5458. throw new Error('Negative length: ' + length);
  5459. }
  5460. return length;
  5461. };
  5462. /**
  5463. * Parses an asn1 object from a byte buffer in DER format.
  5464. *
  5465. * @param bytes the byte buffer to parse from.
  5466. * @param [strict] true to be strict when checking value lengths, false to
  5467. * allow truncated values (default: true).
  5468. * @param [options] object with options or boolean strict flag
  5469. * [strict] true to be strict when checking value lengths, false to
  5470. * allow truncated values (default: true).
  5471. * [decodeBitStrings] true to attempt to decode the content of
  5472. * BIT STRINGs (not OCTET STRINGs) using strict mode. Note that
  5473. * without schema support to understand the data context this can
  5474. * erroneously decode values that happen to be valid ASN.1. This
  5475. * flag will be deprecated or removed as soon as schema support is
  5476. * available. (default: true)
  5477. *
  5478. * @return the parsed asn1 object.
  5479. */
  5480. asn1$8.fromDer = function(bytes, options) {
  5481. if(options === undefined) {
  5482. options = {
  5483. strict: true,
  5484. decodeBitStrings: true
  5485. };
  5486. }
  5487. if(typeof options === 'boolean') {
  5488. options = {
  5489. strict: options,
  5490. decodeBitStrings: true
  5491. };
  5492. }
  5493. if(!('strict' in options)) {
  5494. options.strict = true;
  5495. }
  5496. if(!('decodeBitStrings' in options)) {
  5497. options.decodeBitStrings = true;
  5498. }
  5499. // wrap in buffer if needed
  5500. if(typeof bytes === 'string') {
  5501. bytes = forge$z.util.createBuffer(bytes);
  5502. }
  5503. return _fromDer(bytes, bytes.length(), 0, options);
  5504. };
  5505. /**
  5506. * Internal function to parse an asn1 object from a byte buffer in DER format.
  5507. *
  5508. * @param bytes the byte buffer to parse from.
  5509. * @param remaining the number of bytes remaining for this chunk.
  5510. * @param depth the current parsing depth.
  5511. * @param options object with same options as fromDer().
  5512. *
  5513. * @return the parsed asn1 object.
  5514. */
  5515. function _fromDer(bytes, remaining, depth, options) {
  5516. // temporary storage for consumption calculations
  5517. var start;
  5518. // minimum length for ASN.1 DER structure is 2
  5519. _checkBufferLength(bytes, remaining, 2);
  5520. // get the first byte
  5521. var b1 = bytes.getByte();
  5522. // consumed one byte
  5523. remaining--;
  5524. // get the tag class
  5525. var tagClass = (b1 & 0xC0);
  5526. // get the type (bits 1-5)
  5527. var type = b1 & 0x1F;
  5528. // get the variable value length and adjust remaining bytes
  5529. start = bytes.length();
  5530. var length = _getValueLength(bytes, remaining);
  5531. remaining -= start - bytes.length();
  5532. // ensure there are enough bytes to get the value
  5533. if(length !== undefined && length > remaining) {
  5534. if(options.strict) {
  5535. var error = new Error('Too few bytes to read ASN.1 value.');
  5536. error.available = bytes.length();
  5537. error.remaining = remaining;
  5538. error.requested = length;
  5539. throw error;
  5540. }
  5541. // Note: be lenient with truncated values and use remaining state bytes
  5542. length = remaining;
  5543. }
  5544. // value storage
  5545. var value;
  5546. // possible BIT STRING contents storage
  5547. var bitStringContents;
  5548. // constructed flag is bit 6 (32 = 0x20) of the first byte
  5549. var constructed = ((b1 & 0x20) === 0x20);
  5550. if(constructed) {
  5551. // parse child asn1 objects from the value
  5552. value = [];
  5553. if(length === undefined) {
  5554. // asn1 object of indefinite length, read until end tag
  5555. for(;;) {
  5556. _checkBufferLength(bytes, remaining, 2);
  5557. if(bytes.bytes(2) === String.fromCharCode(0, 0)) {
  5558. bytes.getBytes(2);
  5559. remaining -= 2;
  5560. break;
  5561. }
  5562. start = bytes.length();
  5563. value.push(_fromDer(bytes, remaining, depth + 1, options));
  5564. remaining -= start - bytes.length();
  5565. }
  5566. } else {
  5567. // parsing asn1 object of definite length
  5568. while(length > 0) {
  5569. start = bytes.length();
  5570. value.push(_fromDer(bytes, length, depth + 1, options));
  5571. remaining -= start - bytes.length();
  5572. length -= start - bytes.length();
  5573. }
  5574. }
  5575. }
  5576. // if a BIT STRING, save the contents including padding
  5577. if(value === undefined && tagClass === asn1$8.Class.UNIVERSAL &&
  5578. type === asn1$8.Type.BITSTRING) {
  5579. bitStringContents = bytes.bytes(length);
  5580. }
  5581. // determine if a non-constructed value should be decoded as a composed
  5582. // value that contains other ASN.1 objects. BIT STRINGs (and OCTET STRINGs)
  5583. // can be used this way.
  5584. if(value === undefined && options.decodeBitStrings &&
  5585. tagClass === asn1$8.Class.UNIVERSAL &&
  5586. // FIXME: OCTET STRINGs not yet supported here
  5587. // .. other parts of forge expect to decode OCTET STRINGs manually
  5588. (type === asn1$8.Type.BITSTRING /*|| type === asn1.Type.OCTETSTRING*/) &&
  5589. length > 1) {
  5590. // save read position
  5591. var savedRead = bytes.read;
  5592. var savedRemaining = remaining;
  5593. var unused = 0;
  5594. if(type === asn1$8.Type.BITSTRING) {
  5595. /* The first octet gives the number of bits by which the length of the
  5596. bit string is less than the next multiple of eight (this is called
  5597. the "number of unused bits").
  5598. The second and following octets give the value of the bit string
  5599. converted to an octet string. */
  5600. _checkBufferLength(bytes, remaining, 1);
  5601. unused = bytes.getByte();
  5602. remaining--;
  5603. }
  5604. // if all bits are used, maybe the BIT/OCTET STRING holds ASN.1 objs
  5605. if(unused === 0) {
  5606. try {
  5607. // attempt to parse child asn1 object from the value
  5608. // (stored in array to signal composed value)
  5609. start = bytes.length();
  5610. var subOptions = {
  5611. // enforce strict mode to avoid parsing ASN.1 from plain data
  5612. verbose: options.verbose,
  5613. strict: true,
  5614. decodeBitStrings: true
  5615. };
  5616. var composed = _fromDer(bytes, remaining, depth + 1, subOptions);
  5617. var used = start - bytes.length();
  5618. remaining -= used;
  5619. if(type == asn1$8.Type.BITSTRING) {
  5620. used++;
  5621. }
  5622. // if the data all decoded and the class indicates UNIVERSAL or
  5623. // CONTEXT_SPECIFIC then assume we've got an encapsulated ASN.1 object
  5624. var tc = composed.tagClass;
  5625. if(used === length &&
  5626. (tc === asn1$8.Class.UNIVERSAL || tc === asn1$8.Class.CONTEXT_SPECIFIC)) {
  5627. value = [composed];
  5628. }
  5629. } catch(ex) {
  5630. }
  5631. }
  5632. if(value === undefined) {
  5633. // restore read position
  5634. bytes.read = savedRead;
  5635. remaining = savedRemaining;
  5636. }
  5637. }
  5638. if(value === undefined) {
  5639. // asn1 not constructed or composed, get raw value
  5640. // TODO: do DER to OID conversion and vice-versa in .toDer?
  5641. if(length === undefined) {
  5642. if(options.strict) {
  5643. throw new Error('Non-constructed ASN.1 object of indefinite length.');
  5644. }
  5645. // be lenient and use remaining state bytes
  5646. length = remaining;
  5647. }
  5648. if(type === asn1$8.Type.BMPSTRING) {
  5649. value = '';
  5650. for(; length > 0; length -= 2) {
  5651. _checkBufferLength(bytes, remaining, 2);
  5652. value += String.fromCharCode(bytes.getInt16());
  5653. remaining -= 2;
  5654. }
  5655. } else {
  5656. value = bytes.getBytes(length);
  5657. }
  5658. }
  5659. // add BIT STRING contents if available
  5660. var asn1Options = bitStringContents === undefined ? null : {
  5661. bitStringContents: bitStringContents
  5662. };
  5663. // create and return asn1 object
  5664. return asn1$8.create(tagClass, type, constructed, value, asn1Options);
  5665. }
  5666. /**
  5667. * Converts the given asn1 object to a buffer of bytes in DER format.
  5668. *
  5669. * @param asn1 the asn1 object to convert to bytes.
  5670. *
  5671. * @return the buffer of bytes.
  5672. */
  5673. asn1$8.toDer = function(obj) {
  5674. var bytes = forge$z.util.createBuffer();
  5675. // build the first byte
  5676. var b1 = obj.tagClass | obj.type;
  5677. // for storing the ASN.1 value
  5678. var value = forge$z.util.createBuffer();
  5679. // use BIT STRING contents if available and data not changed
  5680. var useBitStringContents = false;
  5681. if('bitStringContents' in obj) {
  5682. useBitStringContents = true;
  5683. if(obj.original) {
  5684. useBitStringContents = asn1$8.equals(obj, obj.original);
  5685. }
  5686. }
  5687. if(useBitStringContents) {
  5688. value.putBytes(obj.bitStringContents);
  5689. } else if(obj.composed) {
  5690. // if composed, use each child asn1 object's DER bytes as value
  5691. // turn on 6th bit (0x20 = 32) to indicate asn1 is constructed
  5692. // from other asn1 objects
  5693. if(obj.constructed) {
  5694. b1 |= 0x20;
  5695. } else {
  5696. // type is a bit string, add unused bits of 0x00
  5697. value.putByte(0x00);
  5698. }
  5699. // add all of the child DER bytes together
  5700. for(var i = 0; i < obj.value.length; ++i) {
  5701. if(obj.value[i] !== undefined) {
  5702. value.putBuffer(asn1$8.toDer(obj.value[i]));
  5703. }
  5704. }
  5705. } else {
  5706. // use asn1.value directly
  5707. if(obj.type === asn1$8.Type.BMPSTRING) {
  5708. for(var i = 0; i < obj.value.length; ++i) {
  5709. value.putInt16(obj.value.charCodeAt(i));
  5710. }
  5711. } else {
  5712. // ensure integer is minimally-encoded
  5713. // TODO: should all leading bytes be stripped vs just one?
  5714. // .. ex '00 00 01' => '01'?
  5715. if(obj.type === asn1$8.Type.INTEGER &&
  5716. obj.value.length > 1 &&
  5717. // leading 0x00 for positive integer
  5718. ((obj.value.charCodeAt(0) === 0 &&
  5719. (obj.value.charCodeAt(1) & 0x80) === 0) ||
  5720. // leading 0xFF for negative integer
  5721. (obj.value.charCodeAt(0) === 0xFF &&
  5722. (obj.value.charCodeAt(1) & 0x80) === 0x80))) {
  5723. value.putBytes(obj.value.substr(1));
  5724. } else {
  5725. value.putBytes(obj.value);
  5726. }
  5727. }
  5728. }
  5729. // add tag byte
  5730. bytes.putByte(b1);
  5731. // use "short form" encoding
  5732. if(value.length() <= 127) {
  5733. // one byte describes the length
  5734. // bit 8 = 0 and bits 7-1 = length
  5735. bytes.putByte(value.length() & 0x7F);
  5736. } else {
  5737. // use "long form" encoding
  5738. // 2 to 127 bytes describe the length
  5739. // first byte: bit 8 = 1 and bits 7-1 = # of additional bytes
  5740. // other bytes: length in base 256, big-endian
  5741. var len = value.length();
  5742. var lenBytes = '';
  5743. do {
  5744. lenBytes += String.fromCharCode(len & 0xFF);
  5745. len = len >>> 8;
  5746. } while(len > 0);
  5747. // set first byte to # bytes used to store the length and turn on
  5748. // bit 8 to indicate long-form length is used
  5749. bytes.putByte(lenBytes.length | 0x80);
  5750. // concatenate length bytes in reverse since they were generated
  5751. // little endian and we need big endian
  5752. for(var i = lenBytes.length - 1; i >= 0; --i) {
  5753. bytes.putByte(lenBytes.charCodeAt(i));
  5754. }
  5755. }
  5756. // concatenate value bytes
  5757. bytes.putBuffer(value);
  5758. return bytes;
  5759. };
  5760. /**
  5761. * Converts an OID dot-separated string to a byte buffer. The byte buffer
  5762. * contains only the DER-encoded value, not any tag or length bytes.
  5763. *
  5764. * @param oid the OID dot-separated string.
  5765. *
  5766. * @return the byte buffer.
  5767. */
  5768. asn1$8.oidToDer = function(oid) {
  5769. // split OID into individual values
  5770. var values = oid.split('.');
  5771. var bytes = forge$z.util.createBuffer();
  5772. // first byte is 40 * value1 + value2
  5773. bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10));
  5774. // other bytes are each value in base 128 with 8th bit set except for
  5775. // the last byte for each value
  5776. var last, valueBytes, value, b;
  5777. for(var i = 2; i < values.length; ++i) {
  5778. // produce value bytes in reverse because we don't know how many
  5779. // bytes it will take to store the value
  5780. last = true;
  5781. valueBytes = [];
  5782. value = parseInt(values[i], 10);
  5783. do {
  5784. b = value & 0x7F;
  5785. value = value >>> 7;
  5786. // if value is not last, then turn on 8th bit
  5787. if(!last) {
  5788. b |= 0x80;
  5789. }
  5790. valueBytes.push(b);
  5791. last = false;
  5792. } while(value > 0);
  5793. // add value bytes in reverse (needs to be in big endian)
  5794. for(var n = valueBytes.length - 1; n >= 0; --n) {
  5795. bytes.putByte(valueBytes[n]);
  5796. }
  5797. }
  5798. return bytes;
  5799. };
  5800. /**
  5801. * Converts a DER-encoded byte buffer to an OID dot-separated string. The
  5802. * byte buffer should contain only the DER-encoded value, not any tag or
  5803. * length bytes.
  5804. *
  5805. * @param bytes the byte buffer.
  5806. *
  5807. * @return the OID dot-separated string.
  5808. */
  5809. asn1$8.derToOid = function(bytes) {
  5810. var oid;
  5811. // wrap in buffer if needed
  5812. if(typeof bytes === 'string') {
  5813. bytes = forge$z.util.createBuffer(bytes);
  5814. }
  5815. // first byte is 40 * value1 + value2
  5816. var b = bytes.getByte();
  5817. oid = Math.floor(b / 40) + '.' + (b % 40);
  5818. // other bytes are each value in base 128 with 8th bit set except for
  5819. // the last byte for each value
  5820. var value = 0;
  5821. while(bytes.length() > 0) {
  5822. b = bytes.getByte();
  5823. value = value << 7;
  5824. // not the last byte for the value
  5825. if(b & 0x80) {
  5826. value += b & 0x7F;
  5827. } else {
  5828. // last byte
  5829. oid += '.' + (value + b);
  5830. value = 0;
  5831. }
  5832. }
  5833. return oid;
  5834. };
  5835. /**
  5836. * Converts a UTCTime value to a date.
  5837. *
  5838. * Note: GeneralizedTime has 4 digits for the year and is used for X.509
  5839. * dates past 2049. Parsing that structure hasn't been implemented yet.
  5840. *
  5841. * @param utc the UTCTime value to convert.
  5842. *
  5843. * @return the date.
  5844. */
  5845. asn1$8.utcTimeToDate = function(utc) {
  5846. /* The following formats can be used:
  5847. YYMMDDhhmmZ
  5848. YYMMDDhhmm+hh'mm'
  5849. YYMMDDhhmm-hh'mm'
  5850. YYMMDDhhmmssZ
  5851. YYMMDDhhmmss+hh'mm'
  5852. YYMMDDhhmmss-hh'mm'
  5853. Where:
  5854. YY is the least significant two digits of the year
  5855. MM is the month (01 to 12)
  5856. DD is the day (01 to 31)
  5857. hh is the hour (00 to 23)
  5858. mm are the minutes (00 to 59)
  5859. ss are the seconds (00 to 59)
  5860. Z indicates that local time is GMT, + indicates that local time is
  5861. later than GMT, and - indicates that local time is earlier than GMT
  5862. hh' is the absolute value of the offset from GMT in hours
  5863. mm' is the absolute value of the offset from GMT in minutes */
  5864. var date = new Date();
  5865. // if YY >= 50 use 19xx, if YY < 50 use 20xx
  5866. var year = parseInt(utc.substr(0, 2), 10);
  5867. year = (year >= 50) ? 1900 + year : 2000 + year;
  5868. var MM = parseInt(utc.substr(2, 2), 10) - 1; // use 0-11 for month
  5869. var DD = parseInt(utc.substr(4, 2), 10);
  5870. var hh = parseInt(utc.substr(6, 2), 10);
  5871. var mm = parseInt(utc.substr(8, 2), 10);
  5872. var ss = 0;
  5873. // not just YYMMDDhhmmZ
  5874. if(utc.length > 11) {
  5875. // get character after minutes
  5876. var c = utc.charAt(10);
  5877. var end = 10;
  5878. // see if seconds are present
  5879. if(c !== '+' && c !== '-') {
  5880. // get seconds
  5881. ss = parseInt(utc.substr(10, 2), 10);
  5882. end += 2;
  5883. }
  5884. }
  5885. // update date
  5886. date.setUTCFullYear(year, MM, DD);
  5887. date.setUTCHours(hh, mm, ss, 0);
  5888. if(end) {
  5889. // get +/- after end of time
  5890. c = utc.charAt(end);
  5891. if(c === '+' || c === '-') {
  5892. // get hours+minutes offset
  5893. var hhoffset = parseInt(utc.substr(end + 1, 2), 10);
  5894. var mmoffset = parseInt(utc.substr(end + 4, 2), 10);
  5895. // calculate offset in milliseconds
  5896. var offset = hhoffset * 60 + mmoffset;
  5897. offset *= 60000;
  5898. // apply offset
  5899. if(c === '+') {
  5900. date.setTime(+date - offset);
  5901. } else {
  5902. date.setTime(+date + offset);
  5903. }
  5904. }
  5905. }
  5906. return date;
  5907. };
  5908. /**
  5909. * Converts a GeneralizedTime value to a date.
  5910. *
  5911. * @param gentime the GeneralizedTime value to convert.
  5912. *
  5913. * @return the date.
  5914. */
  5915. asn1$8.generalizedTimeToDate = function(gentime) {
  5916. /* The following formats can be used:
  5917. YYYYMMDDHHMMSS
  5918. YYYYMMDDHHMMSS.fff
  5919. YYYYMMDDHHMMSSZ
  5920. YYYYMMDDHHMMSS.fffZ
  5921. YYYYMMDDHHMMSS+hh'mm'
  5922. YYYYMMDDHHMMSS.fff+hh'mm'
  5923. YYYYMMDDHHMMSS-hh'mm'
  5924. YYYYMMDDHHMMSS.fff-hh'mm'
  5925. Where:
  5926. YYYY is the year
  5927. MM is the month (01 to 12)
  5928. DD is the day (01 to 31)
  5929. hh is the hour (00 to 23)
  5930. mm are the minutes (00 to 59)
  5931. ss are the seconds (00 to 59)
  5932. .fff is the second fraction, accurate to three decimal places
  5933. Z indicates that local time is GMT, + indicates that local time is
  5934. later than GMT, and - indicates that local time is earlier than GMT
  5935. hh' is the absolute value of the offset from GMT in hours
  5936. mm' is the absolute value of the offset from GMT in minutes */
  5937. var date = new Date();
  5938. var YYYY = parseInt(gentime.substr(0, 4), 10);
  5939. var MM = parseInt(gentime.substr(4, 2), 10) - 1; // use 0-11 for month
  5940. var DD = parseInt(gentime.substr(6, 2), 10);
  5941. var hh = parseInt(gentime.substr(8, 2), 10);
  5942. var mm = parseInt(gentime.substr(10, 2), 10);
  5943. var ss = parseInt(gentime.substr(12, 2), 10);
  5944. var fff = 0;
  5945. var offset = 0;
  5946. var isUTC = false;
  5947. if(gentime.charAt(gentime.length - 1) === 'Z') {
  5948. isUTC = true;
  5949. }
  5950. var end = gentime.length - 5, c = gentime.charAt(end);
  5951. if(c === '+' || c === '-') {
  5952. // get hours+minutes offset
  5953. var hhoffset = parseInt(gentime.substr(end + 1, 2), 10);
  5954. var mmoffset = parseInt(gentime.substr(end + 4, 2), 10);
  5955. // calculate offset in milliseconds
  5956. offset = hhoffset * 60 + mmoffset;
  5957. offset *= 60000;
  5958. // apply offset
  5959. if(c === '+') {
  5960. offset *= -1;
  5961. }
  5962. isUTC = true;
  5963. }
  5964. // check for second fraction
  5965. if(gentime.charAt(14) === '.') {
  5966. fff = parseFloat(gentime.substr(14), 10) * 1000;
  5967. }
  5968. if(isUTC) {
  5969. date.setUTCFullYear(YYYY, MM, DD);
  5970. date.setUTCHours(hh, mm, ss, fff);
  5971. // apply offset
  5972. date.setTime(+date + offset);
  5973. } else {
  5974. date.setFullYear(YYYY, MM, DD);
  5975. date.setHours(hh, mm, ss, fff);
  5976. }
  5977. return date;
  5978. };
  5979. /**
  5980. * Converts a date to a UTCTime value.
  5981. *
  5982. * Note: GeneralizedTime has 4 digits for the year and is used for X.509
  5983. * dates past 2049. Converting to a GeneralizedTime hasn't been
  5984. * implemented yet.
  5985. *
  5986. * @param date the date to convert.
  5987. *
  5988. * @return the UTCTime value.
  5989. */
  5990. asn1$8.dateToUtcTime = function(date) {
  5991. // TODO: validate; currently assumes proper format
  5992. if(typeof date === 'string') {
  5993. return date;
  5994. }
  5995. var rval = '';
  5996. // create format YYMMDDhhmmssZ
  5997. var format = [];
  5998. format.push(('' + date.getUTCFullYear()).substr(2));
  5999. format.push('' + (date.getUTCMonth() + 1));
  6000. format.push('' + date.getUTCDate());
  6001. format.push('' + date.getUTCHours());
  6002. format.push('' + date.getUTCMinutes());
  6003. format.push('' + date.getUTCSeconds());
  6004. // ensure 2 digits are used for each format entry
  6005. for(var i = 0; i < format.length; ++i) {
  6006. if(format[i].length < 2) {
  6007. rval += '0';
  6008. }
  6009. rval += format[i];
  6010. }
  6011. rval += 'Z';
  6012. return rval;
  6013. };
  6014. /**
  6015. * Converts a date to a GeneralizedTime value.
  6016. *
  6017. * @param date the date to convert.
  6018. *
  6019. * @return the GeneralizedTime value as a string.
  6020. */
  6021. asn1$8.dateToGeneralizedTime = function(date) {
  6022. // TODO: validate; currently assumes proper format
  6023. if(typeof date === 'string') {
  6024. return date;
  6025. }
  6026. var rval = '';
  6027. // create format YYYYMMDDHHMMSSZ
  6028. var format = [];
  6029. format.push('' + date.getUTCFullYear());
  6030. format.push('' + (date.getUTCMonth() + 1));
  6031. format.push('' + date.getUTCDate());
  6032. format.push('' + date.getUTCHours());
  6033. format.push('' + date.getUTCMinutes());
  6034. format.push('' + date.getUTCSeconds());
  6035. // ensure 2 digits are used for each format entry
  6036. for(var i = 0; i < format.length; ++i) {
  6037. if(format[i].length < 2) {
  6038. rval += '0';
  6039. }
  6040. rval += format[i];
  6041. }
  6042. rval += 'Z';
  6043. return rval;
  6044. };
  6045. /**
  6046. * Converts a javascript integer to a DER-encoded byte buffer to be used
  6047. * as the value for an INTEGER type.
  6048. *
  6049. * @param x the integer.
  6050. *
  6051. * @return the byte buffer.
  6052. */
  6053. asn1$8.integerToDer = function(x) {
  6054. var rval = forge$z.util.createBuffer();
  6055. if(x >= -0x80 && x < 0x80) {
  6056. return rval.putSignedInt(x, 8);
  6057. }
  6058. if(x >= -0x8000 && x < 0x8000) {
  6059. return rval.putSignedInt(x, 16);
  6060. }
  6061. if(x >= -0x800000 && x < 0x800000) {
  6062. return rval.putSignedInt(x, 24);
  6063. }
  6064. if(x >= -0x80000000 && x < 0x80000000) {
  6065. return rval.putSignedInt(x, 32);
  6066. }
  6067. var error = new Error('Integer too large; max is 32-bits.');
  6068. error.integer = x;
  6069. throw error;
  6070. };
  6071. /**
  6072. * Converts a DER-encoded byte buffer to a javascript integer. This is
  6073. * typically used to decode the value of an INTEGER type.
  6074. *
  6075. * @param bytes the byte buffer.
  6076. *
  6077. * @return the integer.
  6078. */
  6079. asn1$8.derToInteger = function(bytes) {
  6080. // wrap in buffer if needed
  6081. if(typeof bytes === 'string') {
  6082. bytes = forge$z.util.createBuffer(bytes);
  6083. }
  6084. var n = bytes.length() * 8;
  6085. if(n > 32) {
  6086. throw new Error('Integer too large; max is 32-bits.');
  6087. }
  6088. return bytes.getSignedInt(n);
  6089. };
  6090. /**
  6091. * Validates that the given ASN.1 object is at least a super set of the
  6092. * given ASN.1 structure. Only tag classes and types are checked. An
  6093. * optional map may also be provided to capture ASN.1 values while the
  6094. * structure is checked.
  6095. *
  6096. * To capture an ASN.1 value, set an object in the validator's 'capture'
  6097. * parameter to the key to use in the capture map. To capture the full
  6098. * ASN.1 object, specify 'captureAsn1'. To capture BIT STRING bytes, including
  6099. * the leading unused bits counter byte, specify 'captureBitStringContents'.
  6100. * To capture BIT STRING bytes, without the leading unused bits counter byte,
  6101. * specify 'captureBitStringValue'.
  6102. *
  6103. * Objects in the validator may set a field 'optional' to true to indicate
  6104. * that it isn't necessary to pass validation.
  6105. *
  6106. * @param obj the ASN.1 object to validate.
  6107. * @param v the ASN.1 structure validator.
  6108. * @param capture an optional map to capture values in.
  6109. * @param errors an optional array for storing validation errors.
  6110. *
  6111. * @return true on success, false on failure.
  6112. */
  6113. asn1$8.validate = function(obj, v, capture, errors) {
  6114. var rval = false;
  6115. // ensure tag class and type are the same if specified
  6116. if((obj.tagClass === v.tagClass || typeof(v.tagClass) === 'undefined') &&
  6117. (obj.type === v.type || typeof(v.type) === 'undefined')) {
  6118. // ensure constructed flag is the same if specified
  6119. if(obj.constructed === v.constructed ||
  6120. typeof(v.constructed) === 'undefined') {
  6121. rval = true;
  6122. // handle sub values
  6123. if(v.value && forge$z.util.isArray(v.value)) {
  6124. var j = 0;
  6125. for(var i = 0; rval && i < v.value.length; ++i) {
  6126. rval = v.value[i].optional || false;
  6127. if(obj.value[j]) {
  6128. rval = asn1$8.validate(obj.value[j], v.value[i], capture, errors);
  6129. if(rval) {
  6130. ++j;
  6131. } else if(v.value[i].optional) {
  6132. rval = true;
  6133. }
  6134. }
  6135. if(!rval && errors) {
  6136. errors.push(
  6137. '[' + v.name + '] ' +
  6138. 'Tag class "' + v.tagClass + '", type "' +
  6139. v.type + '" expected value length "' +
  6140. v.value.length + '", got "' +
  6141. obj.value.length + '"');
  6142. }
  6143. }
  6144. }
  6145. if(rval && capture) {
  6146. if(v.capture) {
  6147. capture[v.capture] = obj.value;
  6148. }
  6149. if(v.captureAsn1) {
  6150. capture[v.captureAsn1] = obj;
  6151. }
  6152. if(v.captureBitStringContents && 'bitStringContents' in obj) {
  6153. capture[v.captureBitStringContents] = obj.bitStringContents;
  6154. }
  6155. if(v.captureBitStringValue && 'bitStringContents' in obj) {
  6156. if(obj.bitStringContents.length < 2) {
  6157. capture[v.captureBitStringValue] = '';
  6158. } else {
  6159. // FIXME: support unused bits with data shifting
  6160. var unused = obj.bitStringContents.charCodeAt(0);
  6161. if(unused !== 0) {
  6162. throw new Error(
  6163. 'captureBitStringValue only supported for zero unused bits');
  6164. }
  6165. capture[v.captureBitStringValue] = obj.bitStringContents.slice(1);
  6166. }
  6167. }
  6168. }
  6169. } else if(errors) {
  6170. errors.push(
  6171. '[' + v.name + '] ' +
  6172. 'Expected constructed "' + v.constructed + '", got "' +
  6173. obj.constructed + '"');
  6174. }
  6175. } else if(errors) {
  6176. if(obj.tagClass !== v.tagClass) {
  6177. errors.push(
  6178. '[' + v.name + '] ' +
  6179. 'Expected tag class "' + v.tagClass + '", got "' +
  6180. obj.tagClass + '"');
  6181. }
  6182. if(obj.type !== v.type) {
  6183. errors.push(
  6184. '[' + v.name + '] ' +
  6185. 'Expected type "' + v.type + '", got "' + obj.type + '"');
  6186. }
  6187. }
  6188. return rval;
  6189. };
  6190. // regex for testing for non-latin characters
  6191. var _nonLatinRegex = /[^\\u0000-\\u00ff]/;
  6192. /**
  6193. * Pretty prints an ASN.1 object to a string.
  6194. *
  6195. * @param obj the object to write out.
  6196. * @param level the level in the tree.
  6197. * @param indentation the indentation to use.
  6198. *
  6199. * @return the string.
  6200. */
  6201. asn1$8.prettyPrint = function(obj, level, indentation) {
  6202. var rval = '';
  6203. // set default level and indentation
  6204. level = level || 0;
  6205. indentation = indentation || 2;
  6206. // start new line for deep levels
  6207. if(level > 0) {
  6208. rval += '\n';
  6209. }
  6210. // create indent
  6211. var indent = '';
  6212. for(var i = 0; i < level * indentation; ++i) {
  6213. indent += ' ';
  6214. }
  6215. // print class:type
  6216. rval += indent + 'Tag: ';
  6217. switch(obj.tagClass) {
  6218. case asn1$8.Class.UNIVERSAL:
  6219. rval += 'Universal:';
  6220. break;
  6221. case asn1$8.Class.APPLICATION:
  6222. rval += 'Application:';
  6223. break;
  6224. case asn1$8.Class.CONTEXT_SPECIFIC:
  6225. rval += 'Context-Specific:';
  6226. break;
  6227. case asn1$8.Class.PRIVATE:
  6228. rval += 'Private:';
  6229. break;
  6230. }
  6231. if(obj.tagClass === asn1$8.Class.UNIVERSAL) {
  6232. rval += obj.type;
  6233. // known types
  6234. switch(obj.type) {
  6235. case asn1$8.Type.NONE:
  6236. rval += ' (None)';
  6237. break;
  6238. case asn1$8.Type.BOOLEAN:
  6239. rval += ' (Boolean)';
  6240. break;
  6241. case asn1$8.Type.INTEGER:
  6242. rval += ' (Integer)';
  6243. break;
  6244. case asn1$8.Type.BITSTRING:
  6245. rval += ' (Bit string)';
  6246. break;
  6247. case asn1$8.Type.OCTETSTRING:
  6248. rval += ' (Octet string)';
  6249. break;
  6250. case asn1$8.Type.NULL:
  6251. rval += ' (Null)';
  6252. break;
  6253. case asn1$8.Type.OID:
  6254. rval += ' (Object Identifier)';
  6255. break;
  6256. case asn1$8.Type.ODESC:
  6257. rval += ' (Object Descriptor)';
  6258. break;
  6259. case asn1$8.Type.EXTERNAL:
  6260. rval += ' (External or Instance of)';
  6261. break;
  6262. case asn1$8.Type.REAL:
  6263. rval += ' (Real)';
  6264. break;
  6265. case asn1$8.Type.ENUMERATED:
  6266. rval += ' (Enumerated)';
  6267. break;
  6268. case asn1$8.Type.EMBEDDED:
  6269. rval += ' (Embedded PDV)';
  6270. break;
  6271. case asn1$8.Type.UTF8:
  6272. rval += ' (UTF8)';
  6273. break;
  6274. case asn1$8.Type.ROID:
  6275. rval += ' (Relative Object Identifier)';
  6276. break;
  6277. case asn1$8.Type.SEQUENCE:
  6278. rval += ' (Sequence)';
  6279. break;
  6280. case asn1$8.Type.SET:
  6281. rval += ' (Set)';
  6282. break;
  6283. case asn1$8.Type.PRINTABLESTRING:
  6284. rval += ' (Printable String)';
  6285. break;
  6286. case asn1$8.Type.IA5String:
  6287. rval += ' (IA5String (ASCII))';
  6288. break;
  6289. case asn1$8.Type.UTCTIME:
  6290. rval += ' (UTC time)';
  6291. break;
  6292. case asn1$8.Type.GENERALIZEDTIME:
  6293. rval += ' (Generalized time)';
  6294. break;
  6295. case asn1$8.Type.BMPSTRING:
  6296. rval += ' (BMP String)';
  6297. break;
  6298. }
  6299. } else {
  6300. rval += obj.type;
  6301. }
  6302. rval += '\n';
  6303. rval += indent + 'Constructed: ' + obj.constructed + '\n';
  6304. if(obj.composed) {
  6305. var subvalues = 0;
  6306. var sub = '';
  6307. for(var i = 0; i < obj.value.length; ++i) {
  6308. if(obj.value[i] !== undefined) {
  6309. subvalues += 1;
  6310. sub += asn1$8.prettyPrint(obj.value[i], level + 1, indentation);
  6311. if((i + 1) < obj.value.length) {
  6312. sub += ',';
  6313. }
  6314. }
  6315. }
  6316. rval += indent + 'Sub values: ' + subvalues + sub;
  6317. } else {
  6318. rval += indent + 'Value: ';
  6319. if(obj.type === asn1$8.Type.OID) {
  6320. var oid = asn1$8.derToOid(obj.value);
  6321. rval += oid;
  6322. if(forge$z.pki && forge$z.pki.oids) {
  6323. if(oid in forge$z.pki.oids) {
  6324. rval += ' (' + forge$z.pki.oids[oid] + ') ';
  6325. }
  6326. }
  6327. }
  6328. if(obj.type === asn1$8.Type.INTEGER) {
  6329. try {
  6330. rval += asn1$8.derToInteger(obj.value);
  6331. } catch(ex) {
  6332. rval += '0x' + forge$z.util.bytesToHex(obj.value);
  6333. }
  6334. } else if(obj.type === asn1$8.Type.BITSTRING) {
  6335. // TODO: shift bits as needed to display without padding
  6336. if(obj.value.length > 1) {
  6337. // remove unused bits field
  6338. rval += '0x' + forge$z.util.bytesToHex(obj.value.slice(1));
  6339. } else {
  6340. rval += '(none)';
  6341. }
  6342. // show unused bit count
  6343. if(obj.value.length > 0) {
  6344. var unused = obj.value.charCodeAt(0);
  6345. if(unused == 1) {
  6346. rval += ' (1 unused bit shown)';
  6347. } else if(unused > 1) {
  6348. rval += ' (' + unused + ' unused bits shown)';
  6349. }
  6350. }
  6351. } else if(obj.type === asn1$8.Type.OCTETSTRING) {
  6352. if(!_nonLatinRegex.test(obj.value)) {
  6353. rval += '(' + obj.value + ') ';
  6354. }
  6355. rval += '0x' + forge$z.util.bytesToHex(obj.value);
  6356. } else if(obj.type === asn1$8.Type.UTF8) {
  6357. rval += forge$z.util.decodeUtf8(obj.value);
  6358. } else if(obj.type === asn1$8.Type.PRINTABLESTRING ||
  6359. obj.type === asn1$8.Type.IA5String) {
  6360. rval += obj.value;
  6361. } else if(_nonLatinRegex.test(obj.value)) {
  6362. rval += '0x' + forge$z.util.bytesToHex(obj.value);
  6363. } else if(obj.value.length === 0) {
  6364. rval += '[null]';
  6365. } else {
  6366. rval += obj.value;
  6367. }
  6368. }
  6369. return rval;
  6370. };
  6371. /**
  6372. * Node.js module for Forge message digests.
  6373. *
  6374. * @author Dave Longley
  6375. *
  6376. * Copyright 2011-2017 Digital Bazaar, Inc.
  6377. */
  6378. var forge$y = forge$F;
  6379. forge$y.md = forge$y.md || {};
  6380. forge$y.md.algorithms = forge$y.md.algorithms || {};
  6381. /**
  6382. * Hash-based Message Authentication Code implementation. Requires a message
  6383. * digest object that can be obtained, for example, from forge.md.sha1 or
  6384. * forge.md.md5.
  6385. *
  6386. * @author Dave Longley
  6387. *
  6388. * Copyright (c) 2010-2012 Digital Bazaar, Inc. All rights reserved.
  6389. */
  6390. var forge$x = forge$F;
  6391. /* HMAC API */
  6392. var hmac = forge$x.hmac = forge$x.hmac || {};
  6393. /**
  6394. * Creates an HMAC object that uses the given message digest object.
  6395. *
  6396. * @return an HMAC object.
  6397. */
  6398. hmac.create = function() {
  6399. // the hmac key to use
  6400. var _key = null;
  6401. // the message digest to use
  6402. var _md = null;
  6403. // the inner padding
  6404. var _ipadding = null;
  6405. // the outer padding
  6406. var _opadding = null;
  6407. // hmac context
  6408. var ctx = {};
  6409. /**
  6410. * Starts or restarts the HMAC with the given key and message digest.
  6411. *
  6412. * @param md the message digest to use, null to reuse the previous one,
  6413. * a string to use builtin 'sha1', 'md5', 'sha256'.
  6414. * @param key the key to use as a string, array of bytes, byte buffer,
  6415. * or null to reuse the previous key.
  6416. */
  6417. ctx.start = function(md, key) {
  6418. if(md !== null) {
  6419. if(typeof md === 'string') {
  6420. // create builtin message digest
  6421. md = md.toLowerCase();
  6422. if(md in forge$x.md.algorithms) {
  6423. _md = forge$x.md.algorithms[md].create();
  6424. } else {
  6425. throw new Error('Unknown hash algorithm "' + md + '"');
  6426. }
  6427. } else {
  6428. // store message digest
  6429. _md = md;
  6430. }
  6431. }
  6432. if(key === null) {
  6433. // reuse previous key
  6434. key = _key;
  6435. } else {
  6436. if(typeof key === 'string') {
  6437. // convert string into byte buffer
  6438. key = forge$x.util.createBuffer(key);
  6439. } else if(forge$x.util.isArray(key)) {
  6440. // convert byte array into byte buffer
  6441. var tmp = key;
  6442. key = forge$x.util.createBuffer();
  6443. for(var i = 0; i < tmp.length; ++i) {
  6444. key.putByte(tmp[i]);
  6445. }
  6446. }
  6447. // if key is longer than blocksize, hash it
  6448. var keylen = key.length();
  6449. if(keylen > _md.blockLength) {
  6450. _md.start();
  6451. _md.update(key.bytes());
  6452. key = _md.digest();
  6453. }
  6454. // mix key into inner and outer padding
  6455. // ipadding = [0x36 * blocksize] ^ key
  6456. // opadding = [0x5C * blocksize] ^ key
  6457. _ipadding = forge$x.util.createBuffer();
  6458. _opadding = forge$x.util.createBuffer();
  6459. keylen = key.length();
  6460. for(var i = 0; i < keylen; ++i) {
  6461. var tmp = key.at(i);
  6462. _ipadding.putByte(0x36 ^ tmp);
  6463. _opadding.putByte(0x5C ^ tmp);
  6464. }
  6465. // if key is shorter than blocksize, add additional padding
  6466. if(keylen < _md.blockLength) {
  6467. var tmp = _md.blockLength - keylen;
  6468. for(var i = 0; i < tmp; ++i) {
  6469. _ipadding.putByte(0x36);
  6470. _opadding.putByte(0x5C);
  6471. }
  6472. }
  6473. _key = key;
  6474. _ipadding = _ipadding.bytes();
  6475. _opadding = _opadding.bytes();
  6476. }
  6477. // digest is done like so: hash(opadding | hash(ipadding | message))
  6478. // prepare to do inner hash
  6479. // hash(ipadding | message)
  6480. _md.start();
  6481. _md.update(_ipadding);
  6482. };
  6483. /**
  6484. * Updates the HMAC with the given message bytes.
  6485. *
  6486. * @param bytes the bytes to update with.
  6487. */
  6488. ctx.update = function(bytes) {
  6489. _md.update(bytes);
  6490. };
  6491. /**
  6492. * Produces the Message Authentication Code (MAC).
  6493. *
  6494. * @return a byte buffer containing the digest value.
  6495. */
  6496. ctx.getMac = function() {
  6497. // digest is done like so: hash(opadding | hash(ipadding | message))
  6498. // here we do the outer hashing
  6499. var inner = _md.digest().bytes();
  6500. _md.start();
  6501. _md.update(_opadding);
  6502. _md.update(inner);
  6503. return _md.digest();
  6504. };
  6505. // alias for getMac
  6506. ctx.digest = ctx.getMac;
  6507. return ctx;
  6508. };
  6509. /**
  6510. * Message Digest Algorithm 5 with 128-bit digest (MD5) implementation.
  6511. *
  6512. * @author Dave Longley
  6513. *
  6514. * Copyright (c) 2010-2014 Digital Bazaar, Inc.
  6515. */
  6516. var forge$w = forge$F;
  6517. var md5 = forge$w.md5 = forge$w.md5 || {};
  6518. forge$w.md.md5 = forge$w.md.algorithms.md5 = md5;
  6519. /**
  6520. * Creates an MD5 message digest object.
  6521. *
  6522. * @return a message digest object.
  6523. */
  6524. md5.create = function() {
  6525. // do initialization as necessary
  6526. if(!_initialized$3) {
  6527. _init$3();
  6528. }
  6529. // MD5 state contains four 32-bit integers
  6530. var _state = null;
  6531. // input buffer
  6532. var _input = forge$w.util.createBuffer();
  6533. // used for word storage
  6534. var _w = new Array(16);
  6535. // message digest object
  6536. var md = {
  6537. algorithm: 'md5',
  6538. blockLength: 64,
  6539. digestLength: 16,
  6540. // 56-bit length of message so far (does not including padding)
  6541. messageLength: 0,
  6542. // true message length
  6543. fullMessageLength: null,
  6544. // size of message length in bytes
  6545. messageLengthSize: 8
  6546. };
  6547. /**
  6548. * Starts the digest.
  6549. *
  6550. * @return this digest object.
  6551. */
  6552. md.start = function() {
  6553. // up to 56-bit message length for convenience
  6554. md.messageLength = 0;
  6555. // full message length (set md.messageLength64 for backwards-compatibility)
  6556. md.fullMessageLength = md.messageLength64 = [];
  6557. var int32s = md.messageLengthSize / 4;
  6558. for(var i = 0; i < int32s; ++i) {
  6559. md.fullMessageLength.push(0);
  6560. }
  6561. _input = forge$w.util.createBuffer();
  6562. _state = {
  6563. h0: 0x67452301,
  6564. h1: 0xEFCDAB89,
  6565. h2: 0x98BADCFE,
  6566. h3: 0x10325476
  6567. };
  6568. return md;
  6569. };
  6570. // start digest automatically for first time
  6571. md.start();
  6572. /**
  6573. * Updates the digest with the given message input. The given input can
  6574. * treated as raw input (no encoding will be applied) or an encoding of
  6575. * 'utf8' maybe given to encode the input using UTF-8.
  6576. *
  6577. * @param msg the message input to update with.
  6578. * @param encoding the encoding to use (default: 'raw', other: 'utf8').
  6579. *
  6580. * @return this digest object.
  6581. */
  6582. md.update = function(msg, encoding) {
  6583. if(encoding === 'utf8') {
  6584. msg = forge$w.util.encodeUtf8(msg);
  6585. }
  6586. // update message length
  6587. var len = msg.length;
  6588. md.messageLength += len;
  6589. len = [(len / 0x100000000) >>> 0, len >>> 0];
  6590. for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {
  6591. md.fullMessageLength[i] += len[1];
  6592. len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);
  6593. md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;
  6594. len[0] = (len[1] / 0x100000000) >>> 0;
  6595. }
  6596. // add bytes to input buffer
  6597. _input.putBytes(msg);
  6598. // process bytes
  6599. _update$3(_state, _w, _input);
  6600. // compact input buffer every 2K or if empty
  6601. if(_input.read > 2048 || _input.length() === 0) {
  6602. _input.compact();
  6603. }
  6604. return md;
  6605. };
  6606. /**
  6607. * Produces the digest.
  6608. *
  6609. * @return a byte buffer containing the digest value.
  6610. */
  6611. md.digest = function() {
  6612. /* Note: Here we copy the remaining bytes in the input buffer and
  6613. add the appropriate MD5 padding. Then we do the final update
  6614. on a copy of the state so that if the user wants to get
  6615. intermediate digests they can do so. */
  6616. /* Determine the number of bytes that must be added to the message
  6617. to ensure its length is congruent to 448 mod 512. In other words,
  6618. the data to be digested must be a multiple of 512 bits (or 128 bytes).
  6619. This data includes the message, some padding, and the length of the
  6620. message. Since the length of the message will be encoded as 8 bytes (64
  6621. bits), that means that the last segment of the data must have 56 bytes
  6622. (448 bits) of message and padding. Therefore, the length of the message
  6623. plus the padding must be congruent to 448 mod 512 because
  6624. 512 - 128 = 448.
  6625. In order to fill up the message length it must be filled with
  6626. padding that begins with 1 bit followed by all 0 bits. Padding
  6627. must *always* be present, so if the message length is already
  6628. congruent to 448 mod 512, then 512 padding bits must be added. */
  6629. var finalBlock = forge$w.util.createBuffer();
  6630. finalBlock.putBytes(_input.bytes());
  6631. // compute remaining size to be digested (include message length size)
  6632. var remaining = (
  6633. md.fullMessageLength[md.fullMessageLength.length - 1] +
  6634. md.messageLengthSize);
  6635. // add padding for overflow blockSize - overflow
  6636. // _padding starts with 1 byte with first bit is set (byte value 128), then
  6637. // there may be up to (blockSize - 1) other pad bytes
  6638. var overflow = remaining & (md.blockLength - 1);
  6639. finalBlock.putBytes(_padding$3.substr(0, md.blockLength - overflow));
  6640. // serialize message length in bits in little-endian order; since length
  6641. // is stored in bytes we multiply by 8 and add carry
  6642. var bits, carry = 0;
  6643. for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {
  6644. bits = md.fullMessageLength[i] * 8 + carry;
  6645. carry = (bits / 0x100000000) >>> 0;
  6646. finalBlock.putInt32Le(bits >>> 0);
  6647. }
  6648. var s2 = {
  6649. h0: _state.h0,
  6650. h1: _state.h1,
  6651. h2: _state.h2,
  6652. h3: _state.h3
  6653. };
  6654. _update$3(s2, _w, finalBlock);
  6655. var rval = forge$w.util.createBuffer();
  6656. rval.putInt32Le(s2.h0);
  6657. rval.putInt32Le(s2.h1);
  6658. rval.putInt32Le(s2.h2);
  6659. rval.putInt32Le(s2.h3);
  6660. return rval;
  6661. };
  6662. return md;
  6663. };
  6664. // padding, constant tables for calculating md5
  6665. var _padding$3 = null;
  6666. var _g = null;
  6667. var _r = null;
  6668. var _k$2 = null;
  6669. var _initialized$3 = false;
  6670. /**
  6671. * Initializes the constant tables.
  6672. */
  6673. function _init$3() {
  6674. // create padding
  6675. _padding$3 = String.fromCharCode(128);
  6676. _padding$3 += forge$w.util.fillString(String.fromCharCode(0x00), 64);
  6677. // g values
  6678. _g = [
  6679. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
  6680. 1, 6, 11, 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12,
  6681. 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2,
  6682. 0, 7, 14, 5, 12, 3, 10, 1, 8, 15, 6, 13, 4, 11, 2, 9];
  6683. // rounds table
  6684. _r = [
  6685. 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
  6686. 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
  6687. 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
  6688. 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21];
  6689. // get the result of abs(sin(i + 1)) as a 32-bit integer
  6690. _k$2 = new Array(64);
  6691. for(var i = 0; i < 64; ++i) {
  6692. _k$2[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 0x100000000);
  6693. }
  6694. // now initialized
  6695. _initialized$3 = true;
  6696. }
  6697. /**
  6698. * Updates an MD5 state with the given byte buffer.
  6699. *
  6700. * @param s the MD5 state to update.
  6701. * @param w the array to use to store words.
  6702. * @param bytes the byte buffer to update with.
  6703. */
  6704. function _update$3(s, w, bytes) {
  6705. // consume 512 bit (64 byte) chunks
  6706. var t, a, b, c, d, f, r, i;
  6707. var len = bytes.length();
  6708. while(len >= 64) {
  6709. // initialize hash value for this chunk
  6710. a = s.h0;
  6711. b = s.h1;
  6712. c = s.h2;
  6713. d = s.h3;
  6714. // round 1
  6715. for(i = 0; i < 16; ++i) {
  6716. w[i] = bytes.getInt32Le();
  6717. f = d ^ (b & (c ^ d));
  6718. t = (a + f + _k$2[i] + w[i]);
  6719. r = _r[i];
  6720. a = d;
  6721. d = c;
  6722. c = b;
  6723. b += (t << r) | (t >>> (32 - r));
  6724. }
  6725. // round 2
  6726. for(; i < 32; ++i) {
  6727. f = c ^ (d & (b ^ c));
  6728. t = (a + f + _k$2[i] + w[_g[i]]);
  6729. r = _r[i];
  6730. a = d;
  6731. d = c;
  6732. c = b;
  6733. b += (t << r) | (t >>> (32 - r));
  6734. }
  6735. // round 3
  6736. for(; i < 48; ++i) {
  6737. f = b ^ c ^ d;
  6738. t = (a + f + _k$2[i] + w[_g[i]]);
  6739. r = _r[i];
  6740. a = d;
  6741. d = c;
  6742. c = b;
  6743. b += (t << r) | (t >>> (32 - r));
  6744. }
  6745. // round 4
  6746. for(; i < 64; ++i) {
  6747. f = c ^ (b | ~d);
  6748. t = (a + f + _k$2[i] + w[_g[i]]);
  6749. r = _r[i];
  6750. a = d;
  6751. d = c;
  6752. c = b;
  6753. b += (t << r) | (t >>> (32 - r));
  6754. }
  6755. // update hash state
  6756. s.h0 = (s.h0 + a) | 0;
  6757. s.h1 = (s.h1 + b) | 0;
  6758. s.h2 = (s.h2 + c) | 0;
  6759. s.h3 = (s.h3 + d) | 0;
  6760. len -= 64;
  6761. }
  6762. }
  6763. /**
  6764. * Javascript implementation of basic PEM (Privacy Enhanced Mail) algorithms.
  6765. *
  6766. * See: RFC 1421.
  6767. *
  6768. * @author Dave Longley
  6769. *
  6770. * Copyright (c) 2013-2014 Digital Bazaar, Inc.
  6771. *
  6772. * A Forge PEM object has the following fields:
  6773. *
  6774. * type: identifies the type of message (eg: "RSA PRIVATE KEY").
  6775. *
  6776. * procType: identifies the type of processing performed on the message,
  6777. * it has two subfields: version and type, eg: 4,ENCRYPTED.
  6778. *
  6779. * contentDomain: identifies the type of content in the message, typically
  6780. * only uses the value: "RFC822".
  6781. *
  6782. * dekInfo: identifies the message encryption algorithm and mode and includes
  6783. * any parameters for the algorithm, it has two subfields: algorithm and
  6784. * parameters, eg: DES-CBC,F8143EDE5960C597.
  6785. *
  6786. * headers: contains all other PEM encapsulated headers -- where order is
  6787. * significant (for pairing data like recipient ID + key info).
  6788. *
  6789. * body: the binary-encoded body.
  6790. */
  6791. var forge$v = forge$F;
  6792. // shortcut for pem API
  6793. var pem = forge$v.pem = forge$v.pem || {};
  6794. /**
  6795. * Encodes (serializes) the given PEM object.
  6796. *
  6797. * @param msg the PEM message object to encode.
  6798. * @param options the options to use:
  6799. * maxline the maximum characters per line for the body, (default: 64).
  6800. *
  6801. * @return the PEM-formatted string.
  6802. */
  6803. pem.encode = function(msg, options) {
  6804. options = options || {};
  6805. var rval = '-----BEGIN ' + msg.type + '-----\r\n';
  6806. // encode special headers
  6807. var header;
  6808. if(msg.procType) {
  6809. header = {
  6810. name: 'Proc-Type',
  6811. values: [String(msg.procType.version), msg.procType.type]
  6812. };
  6813. rval += foldHeader(header);
  6814. }
  6815. if(msg.contentDomain) {
  6816. header = {name: 'Content-Domain', values: [msg.contentDomain]};
  6817. rval += foldHeader(header);
  6818. }
  6819. if(msg.dekInfo) {
  6820. header = {name: 'DEK-Info', values: [msg.dekInfo.algorithm]};
  6821. if(msg.dekInfo.parameters) {
  6822. header.values.push(msg.dekInfo.parameters);
  6823. }
  6824. rval += foldHeader(header);
  6825. }
  6826. if(msg.headers) {
  6827. // encode all other headers
  6828. for(var i = 0; i < msg.headers.length; ++i) {
  6829. rval += foldHeader(msg.headers[i]);
  6830. }
  6831. }
  6832. // terminate header
  6833. if(msg.procType) {
  6834. rval += '\r\n';
  6835. }
  6836. // add body
  6837. rval += forge$v.util.encode64(msg.body, options.maxline || 64) + '\r\n';
  6838. rval += '-----END ' + msg.type + '-----\r\n';
  6839. return rval;
  6840. };
  6841. /**
  6842. * Decodes (deserializes) all PEM messages found in the given string.
  6843. *
  6844. * @param str the PEM-formatted string to decode.
  6845. *
  6846. * @return the PEM message objects in an array.
  6847. */
  6848. pem.decode = function(str) {
  6849. var rval = [];
  6850. // split string into PEM messages (be lenient w/EOF on BEGIN line)
  6851. var rMessage = /\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g;
  6852. var rHeader = /([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/;
  6853. var rCRLF = /\r?\n/;
  6854. var match;
  6855. while(true) {
  6856. match = rMessage.exec(str);
  6857. if(!match) {
  6858. break;
  6859. }
  6860. var msg = {
  6861. type: match[1],
  6862. procType: null,
  6863. contentDomain: null,
  6864. dekInfo: null,
  6865. headers: [],
  6866. body: forge$v.util.decode64(match[3])
  6867. };
  6868. rval.push(msg);
  6869. // no headers
  6870. if(!match[2]) {
  6871. continue;
  6872. }
  6873. // parse headers
  6874. var lines = match[2].split(rCRLF);
  6875. var li = 0;
  6876. while(match && li < lines.length) {
  6877. // get line, trim any rhs whitespace
  6878. var line = lines[li].replace(/\s+$/, '');
  6879. // RFC2822 unfold any following folded lines
  6880. for(var nl = li + 1; nl < lines.length; ++nl) {
  6881. var next = lines[nl];
  6882. if(!/\s/.test(next[0])) {
  6883. break;
  6884. }
  6885. line += next;
  6886. li = nl;
  6887. }
  6888. // parse header
  6889. match = line.match(rHeader);
  6890. if(match) {
  6891. var header = {name: match[1], values: []};
  6892. var values = match[2].split(',');
  6893. for(var vi = 0; vi < values.length; ++vi) {
  6894. header.values.push(ltrim(values[vi]));
  6895. }
  6896. // Proc-Type must be the first header
  6897. if(!msg.procType) {
  6898. if(header.name !== 'Proc-Type') {
  6899. throw new Error('Invalid PEM formatted message. The first ' +
  6900. 'encapsulated header must be "Proc-Type".');
  6901. } else if(header.values.length !== 2) {
  6902. throw new Error('Invalid PEM formatted message. The "Proc-Type" ' +
  6903. 'header must have two subfields.');
  6904. }
  6905. msg.procType = {version: values[0], type: values[1]};
  6906. } else if(!msg.contentDomain && header.name === 'Content-Domain') {
  6907. // special-case Content-Domain
  6908. msg.contentDomain = values[0] || '';
  6909. } else if(!msg.dekInfo && header.name === 'DEK-Info') {
  6910. // special-case DEK-Info
  6911. if(header.values.length === 0) {
  6912. throw new Error('Invalid PEM formatted message. The "DEK-Info" ' +
  6913. 'header must have at least one subfield.');
  6914. }
  6915. msg.dekInfo = {algorithm: values[0], parameters: values[1] || null};
  6916. } else {
  6917. msg.headers.push(header);
  6918. }
  6919. }
  6920. ++li;
  6921. }
  6922. if(msg.procType === 'ENCRYPTED' && !msg.dekInfo) {
  6923. throw new Error('Invalid PEM formatted message. The "DEK-Info" ' +
  6924. 'header must be present if "Proc-Type" is "ENCRYPTED".');
  6925. }
  6926. }
  6927. if(rval.length === 0) {
  6928. throw new Error('Invalid PEM formatted message.');
  6929. }
  6930. return rval;
  6931. };
  6932. function foldHeader(header) {
  6933. var rval = header.name + ': ';
  6934. // ensure values with CRLF are folded
  6935. var values = [];
  6936. var insertSpace = function(match, $1) {
  6937. return ' ' + $1;
  6938. };
  6939. for(var i = 0; i < header.values.length; ++i) {
  6940. values.push(header.values[i].replace(/^(\S+\r\n)/, insertSpace));
  6941. }
  6942. rval += values.join(',') + '\r\n';
  6943. // do folding
  6944. var length = 0;
  6945. var candidate = -1;
  6946. for(var i = 0; i < rval.length; ++i, ++length) {
  6947. if(length > 65 && candidate !== -1) {
  6948. var insert = rval[candidate];
  6949. if(insert === ',') {
  6950. ++candidate;
  6951. rval = rval.substr(0, candidate) + '\r\n ' + rval.substr(candidate);
  6952. } else {
  6953. rval = rval.substr(0, candidate) +
  6954. '\r\n' + insert + rval.substr(candidate + 1);
  6955. }
  6956. length = (i - candidate - 1);
  6957. candidate = -1;
  6958. ++i;
  6959. } else if(rval[i] === ' ' || rval[i] === '\t' || rval[i] === ',') {
  6960. candidate = i;
  6961. }
  6962. }
  6963. return rval;
  6964. }
  6965. function ltrim(str) {
  6966. return str.replace(/^\s+/, '');
  6967. }
  6968. /**
  6969. * DES (Data Encryption Standard) implementation.
  6970. *
  6971. * This implementation supports DES as well as 3DES-EDE in ECB and CBC mode.
  6972. * It is based on the BSD-licensed implementation by Paul Tero:
  6973. *
  6974. * Paul Tero, July 2001
  6975. * http://www.tero.co.uk/des/
  6976. *
  6977. * Optimised for performance with large blocks by
  6978. * Michael Hayworth, November 2001
  6979. * http://www.netdealing.com
  6980. *
  6981. * THIS SOFTWARE IS PROVIDED "AS IS" AND
  6982. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  6983. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  6984. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  6985. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  6986. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  6987. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  6988. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  6989. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  6990. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  6991. * SUCH DAMAGE.
  6992. *
  6993. * @author Stefan Siegl
  6994. * @author Dave Longley
  6995. *
  6996. * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>
  6997. * Copyright (c) 2012-2014 Digital Bazaar, Inc.
  6998. */
  6999. var forge$u = forge$F;
  7000. /* DES API */
  7001. forge$u.des = forge$u.des || {};
  7002. /**
  7003. * Deprecated. Instead, use:
  7004. *
  7005. * var cipher = forge.cipher.createCipher('DES-<mode>', key);
  7006. * cipher.start({iv: iv});
  7007. *
  7008. * Creates an DES cipher object to encrypt data using the given symmetric key.
  7009. * The output will be stored in the 'output' member of the returned cipher.
  7010. *
  7011. * The key and iv may be given as binary-encoded strings of bytes or
  7012. * byte buffers.
  7013. *
  7014. * @param key the symmetric key to use (64 or 192 bits).
  7015. * @param iv the initialization vector to use.
  7016. * @param output the buffer to write to, null to create one.
  7017. * @param mode the cipher mode to use (default: 'CBC' if IV is
  7018. * given, 'ECB' if null).
  7019. *
  7020. * @return the cipher.
  7021. */
  7022. forge$u.des.startEncrypting = function(key, iv, output, mode) {
  7023. var cipher = _createCipher({
  7024. key: key,
  7025. output: output,
  7026. decrypt: false,
  7027. mode: mode || (iv === null ? 'ECB' : 'CBC')
  7028. });
  7029. cipher.start(iv);
  7030. return cipher;
  7031. };
  7032. /**
  7033. * Deprecated. Instead, use:
  7034. *
  7035. * var cipher = forge.cipher.createCipher('DES-<mode>', key);
  7036. *
  7037. * Creates an DES cipher object to encrypt data using the given symmetric key.
  7038. *
  7039. * The key may be given as a binary-encoded string of bytes or a byte buffer.
  7040. *
  7041. * @param key the symmetric key to use (64 or 192 bits).
  7042. * @param mode the cipher mode to use (default: 'CBC').
  7043. *
  7044. * @return the cipher.
  7045. */
  7046. forge$u.des.createEncryptionCipher = function(key, mode) {
  7047. return _createCipher({
  7048. key: key,
  7049. output: null,
  7050. decrypt: false,
  7051. mode: mode
  7052. });
  7053. };
  7054. /**
  7055. * Deprecated. Instead, use:
  7056. *
  7057. * var decipher = forge.cipher.createDecipher('DES-<mode>', key);
  7058. * decipher.start({iv: iv});
  7059. *
  7060. * Creates an DES cipher object to decrypt data using the given symmetric key.
  7061. * The output will be stored in the 'output' member of the returned cipher.
  7062. *
  7063. * The key and iv may be given as binary-encoded strings of bytes or
  7064. * byte buffers.
  7065. *
  7066. * @param key the symmetric key to use (64 or 192 bits).
  7067. * @param iv the initialization vector to use.
  7068. * @param output the buffer to write to, null to create one.
  7069. * @param mode the cipher mode to use (default: 'CBC' if IV is
  7070. * given, 'ECB' if null).
  7071. *
  7072. * @return the cipher.
  7073. */
  7074. forge$u.des.startDecrypting = function(key, iv, output, mode) {
  7075. var cipher = _createCipher({
  7076. key: key,
  7077. output: output,
  7078. decrypt: true,
  7079. mode: mode || (iv === null ? 'ECB' : 'CBC')
  7080. });
  7081. cipher.start(iv);
  7082. return cipher;
  7083. };
  7084. /**
  7085. * Deprecated. Instead, use:
  7086. *
  7087. * var decipher = forge.cipher.createDecipher('DES-<mode>', key);
  7088. *
  7089. * Creates an DES cipher object to decrypt data using the given symmetric key.
  7090. *
  7091. * The key may be given as a binary-encoded string of bytes or a byte buffer.
  7092. *
  7093. * @param key the symmetric key to use (64 or 192 bits).
  7094. * @param mode the cipher mode to use (default: 'CBC').
  7095. *
  7096. * @return the cipher.
  7097. */
  7098. forge$u.des.createDecryptionCipher = function(key, mode) {
  7099. return _createCipher({
  7100. key: key,
  7101. output: null,
  7102. decrypt: true,
  7103. mode: mode
  7104. });
  7105. };
  7106. /**
  7107. * Creates a new DES cipher algorithm object.
  7108. *
  7109. * @param name the name of the algorithm.
  7110. * @param mode the mode factory function.
  7111. *
  7112. * @return the DES algorithm object.
  7113. */
  7114. forge$u.des.Algorithm = function(name, mode) {
  7115. var self = this;
  7116. self.name = name;
  7117. self.mode = new mode({
  7118. blockSize: 8,
  7119. cipher: {
  7120. encrypt: function(inBlock, outBlock) {
  7121. return _updateBlock(self._keys, inBlock, outBlock, false);
  7122. },
  7123. decrypt: function(inBlock, outBlock) {
  7124. return _updateBlock(self._keys, inBlock, outBlock, true);
  7125. }
  7126. }
  7127. });
  7128. self._init = false;
  7129. };
  7130. /**
  7131. * Initializes this DES algorithm by expanding its key.
  7132. *
  7133. * @param options the options to use.
  7134. * key the key to use with this algorithm.
  7135. * decrypt true if the algorithm should be initialized for decryption,
  7136. * false for encryption.
  7137. */
  7138. forge$u.des.Algorithm.prototype.initialize = function(options) {
  7139. if(this._init) {
  7140. return;
  7141. }
  7142. var key = forge$u.util.createBuffer(options.key);
  7143. if(this.name.indexOf('3DES') === 0) {
  7144. if(key.length() !== 24) {
  7145. throw new Error('Invalid Triple-DES key size: ' + key.length() * 8);
  7146. }
  7147. }
  7148. // do key expansion to 16 or 48 subkeys (single or triple DES)
  7149. this._keys = _createKeys(key);
  7150. this._init = true;
  7151. };
  7152. /** Register DES algorithms **/
  7153. registerAlgorithm('DES-ECB', forge$u.cipher.modes.ecb);
  7154. registerAlgorithm('DES-CBC', forge$u.cipher.modes.cbc);
  7155. registerAlgorithm('DES-CFB', forge$u.cipher.modes.cfb);
  7156. registerAlgorithm('DES-OFB', forge$u.cipher.modes.ofb);
  7157. registerAlgorithm('DES-CTR', forge$u.cipher.modes.ctr);
  7158. registerAlgorithm('3DES-ECB', forge$u.cipher.modes.ecb);
  7159. registerAlgorithm('3DES-CBC', forge$u.cipher.modes.cbc);
  7160. registerAlgorithm('3DES-CFB', forge$u.cipher.modes.cfb);
  7161. registerAlgorithm('3DES-OFB', forge$u.cipher.modes.ofb);
  7162. registerAlgorithm('3DES-CTR', forge$u.cipher.modes.ctr);
  7163. function registerAlgorithm(name, mode) {
  7164. var factory = function() {
  7165. return new forge$u.des.Algorithm(name, mode);
  7166. };
  7167. forge$u.cipher.registerAlgorithm(name, factory);
  7168. }
  7169. /** DES implementation **/
  7170. var 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];
  7171. var 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];
  7172. var 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];
  7173. var 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];
  7174. var 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];
  7175. var 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];
  7176. var 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];
  7177. var 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];
  7178. /**
  7179. * Create necessary sub keys.
  7180. *
  7181. * @param key the 64-bit or 192-bit key.
  7182. *
  7183. * @return the expanded keys.
  7184. */
  7185. function _createKeys(key) {
  7186. var pc2bytes0 = [0,0x4,0x20000000,0x20000004,0x10000,0x10004,0x20010000,0x20010004,0x200,0x204,0x20000200,0x20000204,0x10200,0x10204,0x20010200,0x20010204],
  7187. pc2bytes1 = [0,0x1,0x100000,0x100001,0x4000000,0x4000001,0x4100000,0x4100001,0x100,0x101,0x100100,0x100101,0x4000100,0x4000101,0x4100100,0x4100101],
  7188. pc2bytes2 = [0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808,0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808],
  7189. pc2bytes3 = [0,0x200000,0x8000000,0x8200000,0x2000,0x202000,0x8002000,0x8202000,0x20000,0x220000,0x8020000,0x8220000,0x22000,0x222000,0x8022000,0x8222000],
  7190. pc2bytes4 = [0,0x40000,0x10,0x40010,0,0x40000,0x10,0x40010,0x1000,0x41000,0x1010,0x41010,0x1000,0x41000,0x1010,0x41010],
  7191. pc2bytes5 = [0,0x400,0x20,0x420,0,0x400,0x20,0x420,0x2000000,0x2000400,0x2000020,0x2000420,0x2000000,0x2000400,0x2000020,0x2000420],
  7192. pc2bytes6 = [0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002,0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002],
  7193. pc2bytes7 = [0,0x10000,0x800,0x10800,0x20000000,0x20010000,0x20000800,0x20010800,0x20000,0x30000,0x20800,0x30800,0x20020000,0x20030000,0x20020800,0x20030800],
  7194. pc2bytes8 = [0,0x40000,0,0x40000,0x2,0x40002,0x2,0x40002,0x2000000,0x2040000,0x2000000,0x2040000,0x2000002,0x2040002,0x2000002,0x2040002],
  7195. pc2bytes9 = [0,0x10000000,0x8,0x10000008,0,0x10000000,0x8,0x10000008,0x400,0x10000400,0x408,0x10000408,0x400,0x10000400,0x408,0x10000408],
  7196. pc2bytes10 = [0,0x20,0,0x20,0x100000,0x100020,0x100000,0x100020,0x2000,0x2020,0x2000,0x2020,0x102000,0x102020,0x102000,0x102020],
  7197. pc2bytes11 = [0,0x1000000,0x200,0x1000200,0x200000,0x1200000,0x200200,0x1200200,0x4000000,0x5000000,0x4000200,0x5000200,0x4200000,0x5200000,0x4200200,0x5200200],
  7198. pc2bytes12 = [0,0x1000,0x8000000,0x8001000,0x80000,0x81000,0x8080000,0x8081000,0x10,0x1010,0x8000010,0x8001010,0x80010,0x81010,0x8080010,0x8081010],
  7199. pc2bytes13 = [0,0x4,0x100,0x104,0,0x4,0x100,0x104,0x1,0x5,0x101,0x105,0x1,0x5,0x101,0x105];
  7200. // how many iterations (1 for des, 3 for triple des)
  7201. // changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys
  7202. var iterations = key.length() > 8 ? 3 : 1;
  7203. // stores the return keys
  7204. var keys = [];
  7205. // now define the left shifts which need to be done
  7206. var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];
  7207. var n = 0, tmp;
  7208. for(var j = 0; j < iterations; j++) {
  7209. var left = key.getInt32();
  7210. var right = key.getInt32();
  7211. tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;
  7212. right ^= tmp;
  7213. left ^= (tmp << 4);
  7214. tmp = ((right >>> -16) ^ left) & 0x0000ffff;
  7215. left ^= tmp;
  7216. right ^= (tmp << -16);
  7217. tmp = ((left >>> 2) ^ right) & 0x33333333;
  7218. right ^= tmp;
  7219. left ^= (tmp << 2);
  7220. tmp = ((right >>> -16) ^ left) & 0x0000ffff;
  7221. left ^= tmp;
  7222. right ^= (tmp << -16);
  7223. tmp = ((left >>> 1) ^ right) & 0x55555555;
  7224. right ^= tmp;
  7225. left ^= (tmp << 1);
  7226. tmp = ((right >>> 8) ^ left) & 0x00ff00ff;
  7227. left ^= tmp;
  7228. right ^= (tmp << 8);
  7229. tmp = ((left >>> 1) ^ right) & 0x55555555;
  7230. right ^= tmp;
  7231. left ^= (tmp << 1);
  7232. // right needs to be shifted and OR'd with last four bits of left
  7233. tmp = (left << 8) | ((right >>> 20) & 0x000000f0);
  7234. // left needs to be put upside down
  7235. left = ((right << 24) | ((right << 8) & 0xff0000) |
  7236. ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0));
  7237. right = tmp;
  7238. // now go through and perform these shifts on the left and right keys
  7239. for(var i = 0; i < shifts.length; ++i) {
  7240. //shift the keys either one or two bits to the left
  7241. if(shifts[i]) {
  7242. left = (left << 2) | (left >>> 26);
  7243. right = (right << 2) | (right >>> 26);
  7244. } else {
  7245. left = (left << 1) | (left >>> 27);
  7246. right = (right << 1) | (right >>> 27);
  7247. }
  7248. left &= -0xf;
  7249. right &= -0xf;
  7250. // now apply PC-2, in such a way that E is easier when encrypting or
  7251. // decrypting this conversion will look like PC-2 except only the last 6
  7252. // bits of each byte are used rather than 48 consecutive bits and the
  7253. // order of lines will be according to how the S selection functions will
  7254. // be applied: S2, S4, S6, S8, S1, S3, S5, S7
  7255. var lefttmp = (
  7256. pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] |
  7257. pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(left >>> 16) & 0xf] |
  7258. pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] |
  7259. pc2bytes6[(left >>> 4) & 0xf]);
  7260. var righttmp = (
  7261. pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] |
  7262. pc2bytes9[(right >>> 20) & 0xf] | pc2bytes10[(right >>> 16) & 0xf] |
  7263. pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |
  7264. pc2bytes13[(right >>> 4) & 0xf]);
  7265. tmp = ((righttmp >>> 16) ^ lefttmp) & 0x0000ffff;
  7266. keys[n++] = lefttmp ^ tmp;
  7267. keys[n++] = righttmp ^ (tmp << 16);
  7268. }
  7269. }
  7270. return keys;
  7271. }
  7272. /**
  7273. * Updates a single block (1 byte) using DES. The update will either
  7274. * encrypt or decrypt the block.
  7275. *
  7276. * @param keys the expanded keys.
  7277. * @param input the input block (an array of 32-bit words).
  7278. * @param output the updated output block.
  7279. * @param decrypt true to decrypt the block, false to encrypt it.
  7280. */
  7281. function _updateBlock(keys, input, output, decrypt) {
  7282. // set up loops for single or triple DES
  7283. var iterations = keys.length === 32 ? 3 : 9;
  7284. var looping;
  7285. if(iterations === 3) {
  7286. looping = decrypt ? [30, -2, -2] : [0, 32, 2];
  7287. } else {
  7288. looping = (decrypt ?
  7289. [94, 62, -2, 32, 64, 2, 30, -2, -2] :
  7290. [0, 32, 2, 62, 30, -2, 64, 96, 2]);
  7291. }
  7292. var tmp;
  7293. var left = input[0];
  7294. var right = input[1];
  7295. // first each 64 bit chunk of the message must be permuted according to IP
  7296. tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;
  7297. right ^= tmp;
  7298. left ^= (tmp << 4);
  7299. tmp = ((left >>> 16) ^ right) & 0x0000ffff;
  7300. right ^= tmp;
  7301. left ^= (tmp << 16);
  7302. tmp = ((right >>> 2) ^ left) & 0x33333333;
  7303. left ^= tmp;
  7304. right ^= (tmp << 2);
  7305. tmp = ((right >>> 8) ^ left) & 0x00ff00ff;
  7306. left ^= tmp;
  7307. right ^= (tmp << 8);
  7308. tmp = ((left >>> 1) ^ right) & 0x55555555;
  7309. right ^= tmp;
  7310. left ^= (tmp << 1);
  7311. // rotate left 1 bit
  7312. left = ((left << 1) | (left >>> 31));
  7313. right = ((right << 1) | (right >>> 31));
  7314. for(var j = 0; j < iterations; j += 3) {
  7315. var endloop = looping[j + 1];
  7316. var loopinc = looping[j + 2];
  7317. // now go through and perform the encryption or decryption
  7318. for(var i = looping[j]; i != endloop; i += loopinc) {
  7319. var right1 = right ^ keys[i];
  7320. var right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];
  7321. // passing these bytes through the S selection functions
  7322. tmp = left;
  7323. left = right;
  7324. right = tmp ^ (
  7325. spfunction2[(right1 >>> 24) & 0x3f] |
  7326. spfunction4[(right1 >>> 16) & 0x3f] |
  7327. spfunction6[(right1 >>> 8) & 0x3f] |
  7328. spfunction8[right1 & 0x3f] |
  7329. spfunction1[(right2 >>> 24) & 0x3f] |
  7330. spfunction3[(right2 >>> 16) & 0x3f] |
  7331. spfunction5[(right2 >>> 8) & 0x3f] |
  7332. spfunction7[right2 & 0x3f]);
  7333. }
  7334. // unreverse left and right
  7335. tmp = left;
  7336. left = right;
  7337. right = tmp;
  7338. }
  7339. // rotate right 1 bit
  7340. left = ((left >>> 1) | (left << 31));
  7341. right = ((right >>> 1) | (right << 31));
  7342. // now perform IP-1, which is IP in the opposite direction
  7343. tmp = ((left >>> 1) ^ right) & 0x55555555;
  7344. right ^= tmp;
  7345. left ^= (tmp << 1);
  7346. tmp = ((right >>> 8) ^ left) & 0x00ff00ff;
  7347. left ^= tmp;
  7348. right ^= (tmp << 8);
  7349. tmp = ((right >>> 2) ^ left) & 0x33333333;
  7350. left ^= tmp;
  7351. right ^= (tmp << 2);
  7352. tmp = ((left >>> 16) ^ right) & 0x0000ffff;
  7353. right ^= tmp;
  7354. left ^= (tmp << 16);
  7355. tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;
  7356. right ^= tmp;
  7357. left ^= (tmp << 4);
  7358. output[0] = left;
  7359. output[1] = right;
  7360. }
  7361. /**
  7362. * Deprecated. Instead, use:
  7363. *
  7364. * forge.cipher.createCipher('DES-<mode>', key);
  7365. * forge.cipher.createDecipher('DES-<mode>', key);
  7366. *
  7367. * Creates a deprecated DES cipher object. This object's mode will default to
  7368. * CBC (cipher-block-chaining).
  7369. *
  7370. * The key may be given as a binary-encoded string of bytes or a byte buffer.
  7371. *
  7372. * @param options the options to use.
  7373. * key the symmetric key to use (64 or 192 bits).
  7374. * output the buffer to write to.
  7375. * decrypt true for decryption, false for encryption.
  7376. * mode the cipher mode to use (default: 'CBC').
  7377. *
  7378. * @return the cipher.
  7379. */
  7380. function _createCipher(options) {
  7381. options = options || {};
  7382. var mode = (options.mode || 'CBC').toUpperCase();
  7383. var algorithm = 'DES-' + mode;
  7384. var cipher;
  7385. if(options.decrypt) {
  7386. cipher = forge$u.cipher.createDecipher(algorithm, options.key);
  7387. } else {
  7388. cipher = forge$u.cipher.createCipher(algorithm, options.key);
  7389. }
  7390. // backwards compatible start API
  7391. var start = cipher.start;
  7392. cipher.start = function(iv, options) {
  7393. // backwards compatibility: support second arg as output buffer
  7394. var output = null;
  7395. if(options instanceof forge$u.util.ByteBuffer) {
  7396. output = options;
  7397. options = {};
  7398. }
  7399. options = options || {};
  7400. options.output = output;
  7401. options.iv = iv;
  7402. start.call(cipher, options);
  7403. };
  7404. return cipher;
  7405. }
  7406. /**
  7407. * Password-Based Key-Derivation Function #2 implementation.
  7408. *
  7409. * See RFC 2898 for details.
  7410. *
  7411. * @author Dave Longley
  7412. *
  7413. * Copyright (c) 2010-2013 Digital Bazaar, Inc.
  7414. */
  7415. var forge$t = forge$F;
  7416. var pkcs5 = forge$t.pkcs5 = forge$t.pkcs5 || {};
  7417. var crypto;
  7418. if(forge$t.util.isNodejs && !forge$t.options.usePureJavaScript) {
  7419. crypto = require$$1__default;
  7420. }
  7421. /**
  7422. * Derives a key from a password.
  7423. *
  7424. * @param p the password as a binary-encoded string of bytes.
  7425. * @param s the salt as a binary-encoded string of bytes.
  7426. * @param c the iteration count, a positive integer.
  7427. * @param dkLen the intended length, in bytes, of the derived key,
  7428. * (max: 2^32 - 1) * hash length of the PRF.
  7429. * @param [md] the message digest (or algorithm identifier as a string) to use
  7430. * in the PRF, defaults to SHA-1.
  7431. * @param [callback(err, key)] presence triggers asynchronous version, called
  7432. * once the operation completes.
  7433. *
  7434. * @return the derived key, as a binary-encoded string of bytes, for the
  7435. * synchronous version (if no callback is specified).
  7436. */
  7437. forge$t.pbkdf2 = pkcs5.pbkdf2 = function(
  7438. p, s, c, dkLen, md, callback) {
  7439. if(typeof md === 'function') {
  7440. callback = md;
  7441. md = null;
  7442. }
  7443. // use native implementation if possible and not disabled, note that
  7444. // some node versions only support SHA-1, others allow digest to be changed
  7445. if(forge$t.util.isNodejs && !forge$t.options.usePureJavaScript &&
  7446. crypto.pbkdf2 && (md === null || typeof md !== 'object') &&
  7447. (crypto.pbkdf2Sync.length > 4 || (!md || md === 'sha1'))) {
  7448. if(typeof md !== 'string') {
  7449. // default prf to SHA-1
  7450. md = 'sha1';
  7451. }
  7452. p = Buffer.from(p, 'binary');
  7453. s = Buffer.from(s, 'binary');
  7454. if(!callback) {
  7455. if(crypto.pbkdf2Sync.length === 4) {
  7456. return crypto.pbkdf2Sync(p, s, c, dkLen).toString('binary');
  7457. }
  7458. return crypto.pbkdf2Sync(p, s, c, dkLen, md).toString('binary');
  7459. }
  7460. if(crypto.pbkdf2Sync.length === 4) {
  7461. return crypto.pbkdf2(p, s, c, dkLen, function(err, key) {
  7462. if(err) {
  7463. return callback(err);
  7464. }
  7465. callback(null, key.toString('binary'));
  7466. });
  7467. }
  7468. return crypto.pbkdf2(p, s, c, dkLen, md, function(err, key) {
  7469. if(err) {
  7470. return callback(err);
  7471. }
  7472. callback(null, key.toString('binary'));
  7473. });
  7474. }
  7475. if(typeof md === 'undefined' || md === null) {
  7476. // default prf to SHA-1
  7477. md = 'sha1';
  7478. }
  7479. if(typeof md === 'string') {
  7480. if(!(md in forge$t.md.algorithms)) {
  7481. throw new Error('Unknown hash algorithm: ' + md);
  7482. }
  7483. md = forge$t.md[md].create();
  7484. }
  7485. var hLen = md.digestLength;
  7486. /* 1. If dkLen > (2^32 - 1) * hLen, output "derived key too long" and
  7487. stop. */
  7488. if(dkLen > (0xFFFFFFFF * hLen)) {
  7489. var err = new Error('Derived key is too long.');
  7490. if(callback) {
  7491. return callback(err);
  7492. }
  7493. throw err;
  7494. }
  7495. /* 2. Let len be the number of hLen-octet blocks in the derived key,
  7496. rounding up, and let r be the number of octets in the last
  7497. block:
  7498. len = CEIL(dkLen / hLen),
  7499. r = dkLen - (len - 1) * hLen. */
  7500. var len = Math.ceil(dkLen / hLen);
  7501. var r = dkLen - (len - 1) * hLen;
  7502. /* 3. For each block of the derived key apply the function F defined
  7503. below to the password P, the salt S, the iteration count c, and
  7504. the block index to compute the block:
  7505. T_1 = F(P, S, c, 1),
  7506. T_2 = F(P, S, c, 2),
  7507. ...
  7508. T_len = F(P, S, c, len),
  7509. where the function F is defined as the exclusive-or sum of the
  7510. first c iterates of the underlying pseudorandom function PRF
  7511. applied to the password P and the concatenation of the salt S
  7512. and the block index i:
  7513. F(P, S, c, i) = u_1 XOR u_2 XOR ... XOR u_c
  7514. where
  7515. u_1 = PRF(P, S || INT(i)),
  7516. u_2 = PRF(P, u_1),
  7517. ...
  7518. u_c = PRF(P, u_{c-1}).
  7519. Here, INT(i) is a four-octet encoding of the integer i, most
  7520. significant octet first. */
  7521. var prf = forge$t.hmac.create();
  7522. prf.start(md, p);
  7523. var dk = '';
  7524. var xor, u_c, u_c1;
  7525. // sync version
  7526. if(!callback) {
  7527. for(var i = 1; i <= len; ++i) {
  7528. // PRF(P, S || INT(i)) (first iteration)
  7529. prf.start(null, null);
  7530. prf.update(s);
  7531. prf.update(forge$t.util.int32ToBytes(i));
  7532. xor = u_c1 = prf.digest().getBytes();
  7533. // PRF(P, u_{c-1}) (other iterations)
  7534. for(var j = 2; j <= c; ++j) {
  7535. prf.start(null, null);
  7536. prf.update(u_c1);
  7537. u_c = prf.digest().getBytes();
  7538. // F(p, s, c, i)
  7539. xor = forge$t.util.xorBytes(xor, u_c, hLen);
  7540. u_c1 = u_c;
  7541. }
  7542. /* 4. Concatenate the blocks and extract the first dkLen octets to
  7543. produce a derived key DK:
  7544. DK = T_1 || T_2 || ... || T_len<0..r-1> */
  7545. dk += (i < len) ? xor : xor.substr(0, r);
  7546. }
  7547. /* 5. Output the derived key DK. */
  7548. return dk;
  7549. }
  7550. // async version
  7551. var i = 1, j;
  7552. function outer() {
  7553. if(i > len) {
  7554. // done
  7555. return callback(null, dk);
  7556. }
  7557. // PRF(P, S || INT(i)) (first iteration)
  7558. prf.start(null, null);
  7559. prf.update(s);
  7560. prf.update(forge$t.util.int32ToBytes(i));
  7561. xor = u_c1 = prf.digest().getBytes();
  7562. // PRF(P, u_{c-1}) (other iterations)
  7563. j = 2;
  7564. inner();
  7565. }
  7566. function inner() {
  7567. if(j <= c) {
  7568. prf.start(null, null);
  7569. prf.update(u_c1);
  7570. u_c = prf.digest().getBytes();
  7571. // F(p, s, c, i)
  7572. xor = forge$t.util.xorBytes(xor, u_c, hLen);
  7573. u_c1 = u_c;
  7574. ++j;
  7575. return forge$t.util.setImmediate(inner);
  7576. }
  7577. /* 4. Concatenate the blocks and extract the first dkLen octets to
  7578. produce a derived key DK:
  7579. DK = T_1 || T_2 || ... || T_len<0..r-1> */
  7580. dk += (i < len) ? xor : xor.substr(0, r);
  7581. ++i;
  7582. outer();
  7583. }
  7584. outer();
  7585. };
  7586. /**
  7587. * Secure Hash Algorithm with 256-bit digest (SHA-256) implementation.
  7588. *
  7589. * See FIPS 180-2 for details.
  7590. *
  7591. * @author Dave Longley
  7592. *
  7593. * Copyright (c) 2010-2015 Digital Bazaar, Inc.
  7594. */
  7595. var forge$s = forge$F;
  7596. var sha256 = forge$s.sha256 = forge$s.sha256 || {};
  7597. forge$s.md.sha256 = forge$s.md.algorithms.sha256 = sha256;
  7598. /**
  7599. * Creates a SHA-256 message digest object.
  7600. *
  7601. * @return a message digest object.
  7602. */
  7603. sha256.create = function() {
  7604. // do initialization as necessary
  7605. if(!_initialized$2) {
  7606. _init$2();
  7607. }
  7608. // SHA-256 state contains eight 32-bit integers
  7609. var _state = null;
  7610. // input buffer
  7611. var _input = forge$s.util.createBuffer();
  7612. // used for word storage
  7613. var _w = new Array(64);
  7614. // message digest object
  7615. var md = {
  7616. algorithm: 'sha256',
  7617. blockLength: 64,
  7618. digestLength: 32,
  7619. // 56-bit length of message so far (does not including padding)
  7620. messageLength: 0,
  7621. // true message length
  7622. fullMessageLength: null,
  7623. // size of message length in bytes
  7624. messageLengthSize: 8
  7625. };
  7626. /**
  7627. * Starts the digest.
  7628. *
  7629. * @return this digest object.
  7630. */
  7631. md.start = function() {
  7632. // up to 56-bit message length for convenience
  7633. md.messageLength = 0;
  7634. // full message length (set md.messageLength64 for backwards-compatibility)
  7635. md.fullMessageLength = md.messageLength64 = [];
  7636. var int32s = md.messageLengthSize / 4;
  7637. for(var i = 0; i < int32s; ++i) {
  7638. md.fullMessageLength.push(0);
  7639. }
  7640. _input = forge$s.util.createBuffer();
  7641. _state = {
  7642. h0: 0x6A09E667,
  7643. h1: 0xBB67AE85,
  7644. h2: 0x3C6EF372,
  7645. h3: 0xA54FF53A,
  7646. h4: 0x510E527F,
  7647. h5: 0x9B05688C,
  7648. h6: 0x1F83D9AB,
  7649. h7: 0x5BE0CD19
  7650. };
  7651. return md;
  7652. };
  7653. // start digest automatically for first time
  7654. md.start();
  7655. /**
  7656. * Updates the digest with the given message input. The given input can
  7657. * treated as raw input (no encoding will be applied) or an encoding of
  7658. * 'utf8' maybe given to encode the input using UTF-8.
  7659. *
  7660. * @param msg the message input to update with.
  7661. * @param encoding the encoding to use (default: 'raw', other: 'utf8').
  7662. *
  7663. * @return this digest object.
  7664. */
  7665. md.update = function(msg, encoding) {
  7666. if(encoding === 'utf8') {
  7667. msg = forge$s.util.encodeUtf8(msg);
  7668. }
  7669. // update message length
  7670. var len = msg.length;
  7671. md.messageLength += len;
  7672. len = [(len / 0x100000000) >>> 0, len >>> 0];
  7673. for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {
  7674. md.fullMessageLength[i] += len[1];
  7675. len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);
  7676. md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;
  7677. len[0] = ((len[1] / 0x100000000) >>> 0);
  7678. }
  7679. // add bytes to input buffer
  7680. _input.putBytes(msg);
  7681. // process bytes
  7682. _update$2(_state, _w, _input);
  7683. // compact input buffer every 2K or if empty
  7684. if(_input.read > 2048 || _input.length() === 0) {
  7685. _input.compact();
  7686. }
  7687. return md;
  7688. };
  7689. /**
  7690. * Produces the digest.
  7691. *
  7692. * @return a byte buffer containing the digest value.
  7693. */
  7694. md.digest = function() {
  7695. /* Note: Here we copy the remaining bytes in the input buffer and
  7696. add the appropriate SHA-256 padding. Then we do the final update
  7697. on a copy of the state so that if the user wants to get
  7698. intermediate digests they can do so. */
  7699. /* Determine the number of bytes that must be added to the message
  7700. to ensure its length is congruent to 448 mod 512. In other words,
  7701. the data to be digested must be a multiple of 512 bits (or 128 bytes).
  7702. This data includes the message, some padding, and the length of the
  7703. message. Since the length of the message will be encoded as 8 bytes (64
  7704. bits), that means that the last segment of the data must have 56 bytes
  7705. (448 bits) of message and padding. Therefore, the length of the message
  7706. plus the padding must be congruent to 448 mod 512 because
  7707. 512 - 128 = 448.
  7708. In order to fill up the message length it must be filled with
  7709. padding that begins with 1 bit followed by all 0 bits. Padding
  7710. must *always* be present, so if the message length is already
  7711. congruent to 448 mod 512, then 512 padding bits must be added. */
  7712. var finalBlock = forge$s.util.createBuffer();
  7713. finalBlock.putBytes(_input.bytes());
  7714. // compute remaining size to be digested (include message length size)
  7715. var remaining = (
  7716. md.fullMessageLength[md.fullMessageLength.length - 1] +
  7717. md.messageLengthSize);
  7718. // add padding for overflow blockSize - overflow
  7719. // _padding starts with 1 byte with first bit is set (byte value 128), then
  7720. // there may be up to (blockSize - 1) other pad bytes
  7721. var overflow = remaining & (md.blockLength - 1);
  7722. finalBlock.putBytes(_padding$2.substr(0, md.blockLength - overflow));
  7723. // serialize message length in bits in big-endian order; since length
  7724. // is stored in bytes we multiply by 8 and add carry from next int
  7725. var next, carry;
  7726. var bits = md.fullMessageLength[0] * 8;
  7727. for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {
  7728. next = md.fullMessageLength[i + 1] * 8;
  7729. carry = (next / 0x100000000) >>> 0;
  7730. bits += carry;
  7731. finalBlock.putInt32(bits >>> 0);
  7732. bits = next >>> 0;
  7733. }
  7734. finalBlock.putInt32(bits);
  7735. var s2 = {
  7736. h0: _state.h0,
  7737. h1: _state.h1,
  7738. h2: _state.h2,
  7739. h3: _state.h3,
  7740. h4: _state.h4,
  7741. h5: _state.h5,
  7742. h6: _state.h6,
  7743. h7: _state.h7
  7744. };
  7745. _update$2(s2, _w, finalBlock);
  7746. var rval = forge$s.util.createBuffer();
  7747. rval.putInt32(s2.h0);
  7748. rval.putInt32(s2.h1);
  7749. rval.putInt32(s2.h2);
  7750. rval.putInt32(s2.h3);
  7751. rval.putInt32(s2.h4);
  7752. rval.putInt32(s2.h5);
  7753. rval.putInt32(s2.h6);
  7754. rval.putInt32(s2.h7);
  7755. return rval;
  7756. };
  7757. return md;
  7758. };
  7759. // sha-256 padding bytes not initialized yet
  7760. var _padding$2 = null;
  7761. var _initialized$2 = false;
  7762. // table of constants
  7763. var _k$1 = null;
  7764. /**
  7765. * Initializes the constant tables.
  7766. */
  7767. function _init$2() {
  7768. // create padding
  7769. _padding$2 = String.fromCharCode(128);
  7770. _padding$2 += forge$s.util.fillString(String.fromCharCode(0x00), 64);
  7771. // create K table for SHA-256
  7772. _k$1 = [
  7773. 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
  7774. 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
  7775. 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
  7776. 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
  7777. 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
  7778. 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
  7779. 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
  7780. 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
  7781. 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
  7782. 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
  7783. 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
  7784. 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
  7785. 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
  7786. 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
  7787. 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
  7788. 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];
  7789. // now initialized
  7790. _initialized$2 = true;
  7791. }
  7792. /**
  7793. * Updates a SHA-256 state with the given byte buffer.
  7794. *
  7795. * @param s the SHA-256 state to update.
  7796. * @param w the array to use to store words.
  7797. * @param bytes the byte buffer to update with.
  7798. */
  7799. function _update$2(s, w, bytes) {
  7800. // consume 512 bit (64 byte) chunks
  7801. var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h;
  7802. var len = bytes.length();
  7803. while(len >= 64) {
  7804. // the w array will be populated with sixteen 32-bit big-endian words
  7805. // and then extended into 64 32-bit words according to SHA-256
  7806. for(i = 0; i < 16; ++i) {
  7807. w[i] = bytes.getInt32();
  7808. }
  7809. for(; i < 64; ++i) {
  7810. // XOR word 2 words ago rot right 17, rot right 19, shft right 10
  7811. t1 = w[i - 2];
  7812. t1 =
  7813. ((t1 >>> 17) | (t1 << 15)) ^
  7814. ((t1 >>> 19) | (t1 << 13)) ^
  7815. (t1 >>> 10);
  7816. // XOR word 15 words ago rot right 7, rot right 18, shft right 3
  7817. t2 = w[i - 15];
  7818. t2 =
  7819. ((t2 >>> 7) | (t2 << 25)) ^
  7820. ((t2 >>> 18) | (t2 << 14)) ^
  7821. (t2 >>> 3);
  7822. // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^32
  7823. w[i] = (t1 + w[i - 7] + t2 + w[i - 16]) | 0;
  7824. }
  7825. // initialize hash value for this chunk
  7826. a = s.h0;
  7827. b = s.h1;
  7828. c = s.h2;
  7829. d = s.h3;
  7830. e = s.h4;
  7831. f = s.h5;
  7832. g = s.h6;
  7833. h = s.h7;
  7834. // round function
  7835. for(i = 0; i < 64; ++i) {
  7836. // Sum1(e)
  7837. s1 =
  7838. ((e >>> 6) | (e << 26)) ^
  7839. ((e >>> 11) | (e << 21)) ^
  7840. ((e >>> 25) | (e << 7));
  7841. // Ch(e, f, g) (optimized the same way as SHA-1)
  7842. ch = g ^ (e & (f ^ g));
  7843. // Sum0(a)
  7844. s0 =
  7845. ((a >>> 2) | (a << 30)) ^
  7846. ((a >>> 13) | (a << 19)) ^
  7847. ((a >>> 22) | (a << 10));
  7848. // Maj(a, b, c) (optimized the same way as SHA-1)
  7849. maj = (a & b) | (c & (a ^ b));
  7850. // main algorithm
  7851. t1 = h + s1 + ch + _k$1[i] + w[i];
  7852. t2 = s0 + maj;
  7853. h = g;
  7854. g = f;
  7855. f = e;
  7856. // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug
  7857. // can't truncate with `| 0`
  7858. e = (d + t1) >>> 0;
  7859. d = c;
  7860. c = b;
  7861. b = a;
  7862. // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug
  7863. // can't truncate with `| 0`
  7864. a = (t1 + t2) >>> 0;
  7865. }
  7866. // update hash state
  7867. s.h0 = (s.h0 + a) | 0;
  7868. s.h1 = (s.h1 + b) | 0;
  7869. s.h2 = (s.h2 + c) | 0;
  7870. s.h3 = (s.h3 + d) | 0;
  7871. s.h4 = (s.h4 + e) | 0;
  7872. s.h5 = (s.h5 + f) | 0;
  7873. s.h6 = (s.h6 + g) | 0;
  7874. s.h7 = (s.h7 + h) | 0;
  7875. len -= 64;
  7876. }
  7877. }
  7878. /**
  7879. * A javascript implementation of a cryptographically-secure
  7880. * Pseudo Random Number Generator (PRNG). The Fortuna algorithm is followed
  7881. * here though the use of SHA-256 is not enforced; when generating an
  7882. * a PRNG context, the hashing algorithm and block cipher used for
  7883. * the generator are specified via a plugin.
  7884. *
  7885. * @author Dave Longley
  7886. *
  7887. * Copyright (c) 2010-2014 Digital Bazaar, Inc.
  7888. */
  7889. var forge$r = forge$F;
  7890. var _crypto$1 = null;
  7891. if(forge$r.util.isNodejs && !forge$r.options.usePureJavaScript &&
  7892. !process.versions['node-webkit']) {
  7893. _crypto$1 = require$$1__default;
  7894. }
  7895. /* PRNG API */
  7896. var prng = forge$r.prng = forge$r.prng || {};
  7897. /**
  7898. * Creates a new PRNG context.
  7899. *
  7900. * A PRNG plugin must be passed in that will provide:
  7901. *
  7902. * 1. A function that initializes the key and seed of a PRNG context. It
  7903. * will be given a 16 byte key and a 16 byte seed. Any key expansion
  7904. * or transformation of the seed from a byte string into an array of
  7905. * integers (or similar) should be performed.
  7906. * 2. The cryptographic function used by the generator. It takes a key and
  7907. * a seed.
  7908. * 3. A seed increment function. It takes the seed and returns seed + 1.
  7909. * 4. An api to create a message digest.
  7910. *
  7911. * For an example, see random.js.
  7912. *
  7913. * @param plugin the PRNG plugin to use.
  7914. */
  7915. prng.create = function(plugin) {
  7916. var ctx = {
  7917. plugin: plugin,
  7918. key: null,
  7919. seed: null,
  7920. time: null,
  7921. // number of reseeds so far
  7922. reseeds: 0,
  7923. // amount of data generated so far
  7924. generated: 0,
  7925. // no initial key bytes
  7926. keyBytes: ''
  7927. };
  7928. // create 32 entropy pools (each is a message digest)
  7929. var md = plugin.md;
  7930. var pools = new Array(32);
  7931. for(var i = 0; i < 32; ++i) {
  7932. pools[i] = md.create();
  7933. }
  7934. ctx.pools = pools;
  7935. // entropy pools are written to cyclically, starting at index 0
  7936. ctx.pool = 0;
  7937. /**
  7938. * Generates random bytes. The bytes may be generated synchronously or
  7939. * asynchronously. Web workers must use the asynchronous interface or
  7940. * else the behavior is undefined.
  7941. *
  7942. * @param count the number of random bytes to generate.
  7943. * @param [callback(err, bytes)] called once the operation completes.
  7944. *
  7945. * @return count random bytes as a string.
  7946. */
  7947. ctx.generate = function(count, callback) {
  7948. // do synchronously
  7949. if(!callback) {
  7950. return ctx.generateSync(count);
  7951. }
  7952. // simple generator using counter-based CBC
  7953. var cipher = ctx.plugin.cipher;
  7954. var increment = ctx.plugin.increment;
  7955. var formatKey = ctx.plugin.formatKey;
  7956. var formatSeed = ctx.plugin.formatSeed;
  7957. var b = forge$r.util.createBuffer();
  7958. // paranoid deviation from Fortuna:
  7959. // reset key for every request to protect previously
  7960. // generated random bytes should the key be discovered;
  7961. // there is no 100ms based reseeding because of this
  7962. // forced reseed for every `generate` call
  7963. ctx.key = null;
  7964. generate();
  7965. function generate(err) {
  7966. if(err) {
  7967. return callback(err);
  7968. }
  7969. // sufficient bytes generated
  7970. if(b.length() >= count) {
  7971. return callback(null, b.getBytes(count));
  7972. }
  7973. // if amount of data generated is greater than 1 MiB, trigger reseed
  7974. if(ctx.generated > 0xfffff) {
  7975. ctx.key = null;
  7976. }
  7977. if(ctx.key === null) {
  7978. // prevent stack overflow
  7979. return forge$r.util.nextTick(function() {
  7980. _reseed(generate);
  7981. });
  7982. }
  7983. // generate the random bytes
  7984. var bytes = cipher(ctx.key, ctx.seed);
  7985. ctx.generated += bytes.length;
  7986. b.putBytes(bytes);
  7987. // generate bytes for a new key and seed
  7988. ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed)));
  7989. ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));
  7990. forge$r.util.setImmediate(generate);
  7991. }
  7992. };
  7993. /**
  7994. * Generates random bytes synchronously.
  7995. *
  7996. * @param count the number of random bytes to generate.
  7997. *
  7998. * @return count random bytes as a string.
  7999. */
  8000. ctx.generateSync = function(count) {
  8001. // simple generator using counter-based CBC
  8002. var cipher = ctx.plugin.cipher;
  8003. var increment = ctx.plugin.increment;
  8004. var formatKey = ctx.plugin.formatKey;
  8005. var formatSeed = ctx.plugin.formatSeed;
  8006. // paranoid deviation from Fortuna:
  8007. // reset key for every request to protect previously
  8008. // generated random bytes should the key be discovered;
  8009. // there is no 100ms based reseeding because of this
  8010. // forced reseed for every `generateSync` call
  8011. ctx.key = null;
  8012. var b = forge$r.util.createBuffer();
  8013. while(b.length() < count) {
  8014. // if amount of data generated is greater than 1 MiB, trigger reseed
  8015. if(ctx.generated > 0xfffff) {
  8016. ctx.key = null;
  8017. }
  8018. if(ctx.key === null) {
  8019. _reseedSync();
  8020. }
  8021. // generate the random bytes
  8022. var bytes = cipher(ctx.key, ctx.seed);
  8023. ctx.generated += bytes.length;
  8024. b.putBytes(bytes);
  8025. // generate bytes for a new key and seed
  8026. ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed)));
  8027. ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));
  8028. }
  8029. return b.getBytes(count);
  8030. };
  8031. /**
  8032. * Private function that asynchronously reseeds a generator.
  8033. *
  8034. * @param callback(err) called once the operation completes.
  8035. */
  8036. function _reseed(callback) {
  8037. if(ctx.pools[0].messageLength >= 32) {
  8038. _seed();
  8039. return callback();
  8040. }
  8041. // not enough seed data...
  8042. var needed = (32 - ctx.pools[0].messageLength) << 5;
  8043. ctx.seedFile(needed, function(err, bytes) {
  8044. if(err) {
  8045. return callback(err);
  8046. }
  8047. ctx.collect(bytes);
  8048. _seed();
  8049. callback();
  8050. });
  8051. }
  8052. /**
  8053. * Private function that synchronously reseeds a generator.
  8054. */
  8055. function _reseedSync() {
  8056. if(ctx.pools[0].messageLength >= 32) {
  8057. return _seed();
  8058. }
  8059. // not enough seed data...
  8060. var needed = (32 - ctx.pools[0].messageLength) << 5;
  8061. ctx.collect(ctx.seedFileSync(needed));
  8062. _seed();
  8063. }
  8064. /**
  8065. * Private function that seeds a generator once enough bytes are available.
  8066. */
  8067. function _seed() {
  8068. // update reseed count
  8069. ctx.reseeds = (ctx.reseeds === 0xffffffff) ? 0 : ctx.reseeds + 1;
  8070. // goal is to update `key` via:
  8071. // key = hash(key + s)
  8072. // where 's' is all collected entropy from selected pools, then...
  8073. // create a plugin-based message digest
  8074. var md = ctx.plugin.md.create();
  8075. // consume current key bytes
  8076. md.update(ctx.keyBytes);
  8077. // digest the entropy of pools whose index k meet the
  8078. // condition 'n mod 2^k == 0' where n is the number of reseeds
  8079. var _2powK = 1;
  8080. for(var k = 0; k < 32; ++k) {
  8081. if(ctx.reseeds % _2powK === 0) {
  8082. md.update(ctx.pools[k].digest().getBytes());
  8083. ctx.pools[k].start();
  8084. }
  8085. _2powK = _2powK << 1;
  8086. }
  8087. // get digest for key bytes
  8088. ctx.keyBytes = md.digest().getBytes();
  8089. // paranoid deviation from Fortuna:
  8090. // update `seed` via `seed = hash(key)`
  8091. // instead of initializing to zero once and only
  8092. // ever incrementing it
  8093. md.start();
  8094. md.update(ctx.keyBytes);
  8095. var seedBytes = md.digest().getBytes();
  8096. // update state
  8097. ctx.key = ctx.plugin.formatKey(ctx.keyBytes);
  8098. ctx.seed = ctx.plugin.formatSeed(seedBytes);
  8099. ctx.generated = 0;
  8100. }
  8101. /**
  8102. * The built-in default seedFile. This seedFile is used when entropy
  8103. * is needed immediately.
  8104. *
  8105. * @param needed the number of bytes that are needed.
  8106. *
  8107. * @return the random bytes.
  8108. */
  8109. function defaultSeedFile(needed) {
  8110. // use window.crypto.getRandomValues strong source of entropy if available
  8111. var getRandomValues = null;
  8112. var globalScope = forge$r.util.globalScope;
  8113. var _crypto = globalScope.crypto || globalScope.msCrypto;
  8114. if(_crypto && _crypto.getRandomValues) {
  8115. getRandomValues = function(arr) {
  8116. return _crypto.getRandomValues(arr);
  8117. };
  8118. }
  8119. var b = forge$r.util.createBuffer();
  8120. if(getRandomValues) {
  8121. while(b.length() < needed) {
  8122. // max byte length is 65536 before QuotaExceededError is thrown
  8123. // http://www.w3.org/TR/WebCryptoAPI/#RandomSource-method-getRandomValues
  8124. var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4);
  8125. var entropy = new Uint32Array(Math.floor(count));
  8126. try {
  8127. getRandomValues(entropy);
  8128. for(var i = 0; i < entropy.length; ++i) {
  8129. b.putInt32(entropy[i]);
  8130. }
  8131. } catch(e) {
  8132. /* only ignore QuotaExceededError */
  8133. if(!(typeof QuotaExceededError !== 'undefined' &&
  8134. e instanceof QuotaExceededError)) {
  8135. throw e;
  8136. }
  8137. }
  8138. }
  8139. }
  8140. // be sad and add some weak random data
  8141. if(b.length() < needed) {
  8142. /* Draws from Park-Miller "minimal standard" 31 bit PRNG,
  8143. implemented with David G. Carta's optimization: with 32 bit math
  8144. and without division (Public Domain). */
  8145. var hi, lo, next;
  8146. var seed = Math.floor(Math.random() * 0x010000);
  8147. while(b.length() < needed) {
  8148. lo = 16807 * (seed & 0xFFFF);
  8149. hi = 16807 * (seed >> 16);
  8150. lo += (hi & 0x7FFF) << 16;
  8151. lo += hi >> 15;
  8152. lo = (lo & 0x7FFFFFFF) + (lo >> 31);
  8153. seed = lo & 0xFFFFFFFF;
  8154. // consume lower 3 bytes of seed
  8155. for(var i = 0; i < 3; ++i) {
  8156. // throw in more pseudo random
  8157. next = seed >>> (i << 3);
  8158. next ^= Math.floor(Math.random() * 0x0100);
  8159. b.putByte(String.fromCharCode(next & 0xFF));
  8160. }
  8161. }
  8162. }
  8163. return b.getBytes(needed);
  8164. }
  8165. // initialize seed file APIs
  8166. if(_crypto$1) {
  8167. // use nodejs async API
  8168. ctx.seedFile = function(needed, callback) {
  8169. _crypto$1.randomBytes(needed, function(err, bytes) {
  8170. if(err) {
  8171. return callback(err);
  8172. }
  8173. callback(null, bytes.toString());
  8174. });
  8175. };
  8176. // use nodejs sync API
  8177. ctx.seedFileSync = function(needed) {
  8178. return _crypto$1.randomBytes(needed).toString();
  8179. };
  8180. } else {
  8181. ctx.seedFile = function(needed, callback) {
  8182. try {
  8183. callback(null, defaultSeedFile(needed));
  8184. } catch(e) {
  8185. callback(e);
  8186. }
  8187. };
  8188. ctx.seedFileSync = defaultSeedFile;
  8189. }
  8190. /**
  8191. * Adds entropy to a prng ctx's accumulator.
  8192. *
  8193. * @param bytes the bytes of entropy as a string.
  8194. */
  8195. ctx.collect = function(bytes) {
  8196. // iterate over pools distributing entropy cyclically
  8197. var count = bytes.length;
  8198. for(var i = 0; i < count; ++i) {
  8199. ctx.pools[ctx.pool].update(bytes.substr(i, 1));
  8200. ctx.pool = (ctx.pool === 31) ? 0 : ctx.pool + 1;
  8201. }
  8202. };
  8203. /**
  8204. * Collects an integer of n bits.
  8205. *
  8206. * @param i the integer entropy.
  8207. * @param n the number of bits in the integer.
  8208. */
  8209. ctx.collectInt = function(i, n) {
  8210. var bytes = '';
  8211. for(var x = 0; x < n; x += 8) {
  8212. bytes += String.fromCharCode((i >> x) & 0xFF);
  8213. }
  8214. ctx.collect(bytes);
  8215. };
  8216. /**
  8217. * Registers a Web Worker to receive immediate entropy from the main thread.
  8218. * This method is required until Web Workers can access the native crypto
  8219. * API. This method should be called twice for each created worker, once in
  8220. * the main thread, and once in the worker itself.
  8221. *
  8222. * @param worker the worker to register.
  8223. */
  8224. ctx.registerWorker = function(worker) {
  8225. // worker receives random bytes
  8226. if(worker === self) {
  8227. ctx.seedFile = function(needed, callback) {
  8228. function listener(e) {
  8229. var data = e.data;
  8230. if(data.forge && data.forge.prng) {
  8231. self.removeEventListener('message', listener);
  8232. callback(data.forge.prng.err, data.forge.prng.bytes);
  8233. }
  8234. }
  8235. self.addEventListener('message', listener);
  8236. self.postMessage({forge: {prng: {needed: needed}}});
  8237. };
  8238. } else {
  8239. // main thread sends random bytes upon request
  8240. var listener = function(e) {
  8241. var data = e.data;
  8242. if(data.forge && data.forge.prng) {
  8243. ctx.seedFile(data.forge.prng.needed, function(err, bytes) {
  8244. worker.postMessage({forge: {prng: {err: err, bytes: bytes}}});
  8245. });
  8246. }
  8247. };
  8248. // TODO: do we need to remove the event listener when the worker dies?
  8249. worker.addEventListener('message', listener);
  8250. }
  8251. };
  8252. return ctx;
  8253. };
  8254. /**
  8255. * An API for getting cryptographically-secure random bytes. The bytes are
  8256. * generated using the Fortuna algorithm devised by Bruce Schneier and
  8257. * Niels Ferguson.
  8258. *
  8259. * Getting strong random bytes is not yet easy to do in javascript. The only
  8260. * truish random entropy that can be collected is from the mouse, keyboard, or
  8261. * from timing with respect to page loads, etc. This generator makes a poor
  8262. * attempt at providing random bytes when those sources haven't yet provided
  8263. * enough entropy to initially seed or to reseed the PRNG.
  8264. *
  8265. * @author Dave Longley
  8266. *
  8267. * Copyright (c) 2009-2014 Digital Bazaar, Inc.
  8268. */
  8269. var forge$q = forge$F;
  8270. (function() {
  8271. // forge.random already defined
  8272. if(forge$q.random && forge$q.random.getBytes) {
  8273. return;
  8274. }
  8275. (function(jQuery) {
  8276. // the default prng plugin, uses AES-128
  8277. var prng_aes = {};
  8278. var _prng_aes_output = new Array(4);
  8279. var _prng_aes_buffer = forge$q.util.createBuffer();
  8280. prng_aes.formatKey = function(key) {
  8281. // convert the key into 32-bit integers
  8282. var tmp = forge$q.util.createBuffer(key);
  8283. key = new Array(4);
  8284. key[0] = tmp.getInt32();
  8285. key[1] = tmp.getInt32();
  8286. key[2] = tmp.getInt32();
  8287. key[3] = tmp.getInt32();
  8288. // return the expanded key
  8289. return forge$q.aes._expandKey(key, false);
  8290. };
  8291. prng_aes.formatSeed = function(seed) {
  8292. // convert seed into 32-bit integers
  8293. var tmp = forge$q.util.createBuffer(seed);
  8294. seed = new Array(4);
  8295. seed[0] = tmp.getInt32();
  8296. seed[1] = tmp.getInt32();
  8297. seed[2] = tmp.getInt32();
  8298. seed[3] = tmp.getInt32();
  8299. return seed;
  8300. };
  8301. prng_aes.cipher = function(key, seed) {
  8302. forge$q.aes._updateBlock(key, seed, _prng_aes_output, false);
  8303. _prng_aes_buffer.putInt32(_prng_aes_output[0]);
  8304. _prng_aes_buffer.putInt32(_prng_aes_output[1]);
  8305. _prng_aes_buffer.putInt32(_prng_aes_output[2]);
  8306. _prng_aes_buffer.putInt32(_prng_aes_output[3]);
  8307. return _prng_aes_buffer.getBytes();
  8308. };
  8309. prng_aes.increment = function(seed) {
  8310. // FIXME: do we care about carry or signed issues?
  8311. ++seed[3];
  8312. return seed;
  8313. };
  8314. prng_aes.md = forge$q.md.sha256;
  8315. /**
  8316. * Creates a new PRNG.
  8317. */
  8318. function spawnPrng() {
  8319. var ctx = forge$q.prng.create(prng_aes);
  8320. /**
  8321. * Gets random bytes. If a native secure crypto API is unavailable, this
  8322. * method tries to make the bytes more unpredictable by drawing from data that
  8323. * can be collected from the user of the browser, eg: mouse movement.
  8324. *
  8325. * If a callback is given, this method will be called asynchronously.
  8326. *
  8327. * @param count the number of random bytes to get.
  8328. * @param [callback(err, bytes)] called once the operation completes.
  8329. *
  8330. * @return the random bytes in a string.
  8331. */
  8332. ctx.getBytes = function(count, callback) {
  8333. return ctx.generate(count, callback);
  8334. };
  8335. /**
  8336. * Gets random bytes asynchronously. If a native secure crypto API is
  8337. * unavailable, this method tries to make the bytes more unpredictable by
  8338. * drawing from data that can be collected from the user of the browser,
  8339. * eg: mouse movement.
  8340. *
  8341. * @param count the number of random bytes to get.
  8342. *
  8343. * @return the random bytes in a string.
  8344. */
  8345. ctx.getBytesSync = function(count) {
  8346. return ctx.generate(count);
  8347. };
  8348. return ctx;
  8349. }
  8350. // create default prng context
  8351. var _ctx = spawnPrng();
  8352. // add other sources of entropy only if window.crypto.getRandomValues is not
  8353. // available -- otherwise this source will be automatically used by the prng
  8354. var getRandomValues = null;
  8355. var globalScope = forge$q.util.globalScope;
  8356. var _crypto = globalScope.crypto || globalScope.msCrypto;
  8357. if(_crypto && _crypto.getRandomValues) {
  8358. getRandomValues = function(arr) {
  8359. return _crypto.getRandomValues(arr);
  8360. };
  8361. }
  8362. if((!forge$q.util.isNodejs && !getRandomValues)) {
  8363. // get load time entropy
  8364. _ctx.collectInt(+new Date(), 32);
  8365. // add some entropy from navigator object
  8366. if(typeof(navigator) !== 'undefined') {
  8367. var _navBytes = '';
  8368. for(var key in navigator) {
  8369. try {
  8370. if(typeof(navigator[key]) == 'string') {
  8371. _navBytes += navigator[key];
  8372. }
  8373. } catch(e) {
  8374. /* Some navigator keys might not be accessible, e.g. the geolocation
  8375. attribute throws an exception if touched in Mozilla chrome://
  8376. context.
  8377. Silently ignore this and just don't use this as a source of
  8378. entropy. */
  8379. }
  8380. }
  8381. _ctx.collect(_navBytes);
  8382. _navBytes = null;
  8383. }
  8384. // add mouse and keyboard collectors if jquery is available
  8385. if(jQuery) {
  8386. // set up mouse entropy capture
  8387. jQuery().mousemove(function(e) {
  8388. // add mouse coords
  8389. _ctx.collectInt(e.clientX, 16);
  8390. _ctx.collectInt(e.clientY, 16);
  8391. });
  8392. // set up keyboard entropy capture
  8393. jQuery().keypress(function(e) {
  8394. _ctx.collectInt(e.charCode, 8);
  8395. });
  8396. }
  8397. }
  8398. /* Random API */
  8399. if(!forge$q.random) {
  8400. forge$q.random = _ctx;
  8401. } else {
  8402. // extend forge.random with _ctx
  8403. for(var key in _ctx) {
  8404. forge$q.random[key] = _ctx[key];
  8405. }
  8406. }
  8407. // expose spawn PRNG
  8408. forge$q.random.createInstance = spawnPrng;
  8409. })(typeof(jQuery) !== 'undefined' ? jQuery : null);
  8410. })();
  8411. /**
  8412. * RC2 implementation.
  8413. *
  8414. * @author Stefan Siegl
  8415. *
  8416. * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>
  8417. *
  8418. * Information on the RC2 cipher is available from RFC #2268,
  8419. * http://www.ietf.org/rfc/rfc2268.txt
  8420. */
  8421. var forge$p = forge$F;
  8422. var piTable = [
  8423. 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d,
  8424. 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2,
  8425. 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32,
  8426. 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82,
  8427. 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc,
  8428. 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26,
  8429. 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03,
  8430. 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7,
  8431. 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a,
  8432. 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec,
  8433. 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39,
  8434. 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31,
  8435. 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9,
  8436. 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9,
  8437. 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e,
  8438. 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad
  8439. ];
  8440. var s = [1, 2, 3, 5];
  8441. /**
  8442. * Rotate a word left by given number of bits.
  8443. *
  8444. * Bits that are shifted out on the left are put back in on the right
  8445. * hand side.
  8446. *
  8447. * @param word The word to shift left.
  8448. * @param bits The number of bits to shift by.
  8449. * @return The rotated word.
  8450. */
  8451. var rol = function(word, bits) {
  8452. return ((word << bits) & 0xffff) | ((word & 0xffff) >> (16 - bits));
  8453. };
  8454. /**
  8455. * Rotate a word right by given number of bits.
  8456. *
  8457. * Bits that are shifted out on the right are put back in on the left
  8458. * hand side.
  8459. *
  8460. * @param word The word to shift right.
  8461. * @param bits The number of bits to shift by.
  8462. * @return The rotated word.
  8463. */
  8464. var ror = function(word, bits) {
  8465. return ((word & 0xffff) >> bits) | ((word << (16 - bits)) & 0xffff);
  8466. };
  8467. /* RC2 API */
  8468. forge$p.rc2 = forge$p.rc2 || {};
  8469. /**
  8470. * Perform RC2 key expansion as per RFC #2268, section 2.
  8471. *
  8472. * @param key variable-length user key (between 1 and 128 bytes)
  8473. * @param effKeyBits number of effective key bits (default: 128)
  8474. * @return the expanded RC2 key (ByteBuffer of 128 bytes)
  8475. */
  8476. forge$p.rc2.expandKey = function(key, effKeyBits) {
  8477. if(typeof key === 'string') {
  8478. key = forge$p.util.createBuffer(key);
  8479. }
  8480. effKeyBits = effKeyBits || 128;
  8481. /* introduce variables that match the names used in RFC #2268 */
  8482. var L = key;
  8483. var T = key.length();
  8484. var T1 = effKeyBits;
  8485. var T8 = Math.ceil(T1 / 8);
  8486. var TM = 0xff >> (T1 & 0x07);
  8487. var i;
  8488. for(i = T; i < 128; i++) {
  8489. L.putByte(piTable[(L.at(i - 1) + L.at(i - T)) & 0xff]);
  8490. }
  8491. L.setAt(128 - T8, piTable[L.at(128 - T8) & TM]);
  8492. for(i = 127 - T8; i >= 0; i--) {
  8493. L.setAt(i, piTable[L.at(i + 1) ^ L.at(i + T8)]);
  8494. }
  8495. return L;
  8496. };
  8497. /**
  8498. * Creates a RC2 cipher object.
  8499. *
  8500. * @param key the symmetric key to use (as base for key generation).
  8501. * @param bits the number of effective key bits.
  8502. * @param encrypt false for decryption, true for encryption.
  8503. *
  8504. * @return the cipher.
  8505. */
  8506. var createCipher = function(key, bits, encrypt) {
  8507. var _finish = false, _input = null, _output = null, _iv = null;
  8508. var mixRound, mashRound;
  8509. var i, j, K = [];
  8510. /* Expand key and fill into K[] Array */
  8511. key = forge$p.rc2.expandKey(key, bits);
  8512. for(i = 0; i < 64; i++) {
  8513. K.push(key.getInt16Le());
  8514. }
  8515. if(encrypt) {
  8516. /**
  8517. * Perform one mixing round "in place".
  8518. *
  8519. * @param R Array of four words to perform mixing on.
  8520. */
  8521. mixRound = function(R) {
  8522. for(i = 0; i < 4; i++) {
  8523. R[i] += K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) +
  8524. ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);
  8525. R[i] = rol(R[i], s[i]);
  8526. j++;
  8527. }
  8528. };
  8529. /**
  8530. * Perform one mashing round "in place".
  8531. *
  8532. * @param R Array of four words to perform mashing on.
  8533. */
  8534. mashRound = function(R) {
  8535. for(i = 0; i < 4; i++) {
  8536. R[i] += K[R[(i + 3) % 4] & 63];
  8537. }
  8538. };
  8539. } else {
  8540. /**
  8541. * Perform one r-mixing round "in place".
  8542. *
  8543. * @param R Array of four words to perform mixing on.
  8544. */
  8545. mixRound = function(R) {
  8546. for(i = 3; i >= 0; i--) {
  8547. R[i] = ror(R[i], s[i]);
  8548. R[i] -= K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) +
  8549. ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);
  8550. j--;
  8551. }
  8552. };
  8553. /**
  8554. * Perform one r-mashing round "in place".
  8555. *
  8556. * @param R Array of four words to perform mashing on.
  8557. */
  8558. mashRound = function(R) {
  8559. for(i = 3; i >= 0; i--) {
  8560. R[i] -= K[R[(i + 3) % 4] & 63];
  8561. }
  8562. };
  8563. }
  8564. /**
  8565. * Run the specified cipher execution plan.
  8566. *
  8567. * This function takes four words from the input buffer, applies the IV on
  8568. * it (if requested) and runs the provided execution plan.
  8569. *
  8570. * The plan must be put together in form of a array of arrays. Where the
  8571. * outer one is simply a list of steps to perform and the inner one needs
  8572. * to have two elements: the first one telling how many rounds to perform,
  8573. * the second one telling what to do (i.e. the function to call).
  8574. *
  8575. * @param {Array} plan The plan to execute.
  8576. */
  8577. var runPlan = function(plan) {
  8578. var R = [];
  8579. /* Get data from input buffer and fill the four words into R */
  8580. for(i = 0; i < 4; i++) {
  8581. var val = _input.getInt16Le();
  8582. if(_iv !== null) {
  8583. if(encrypt) {
  8584. /* We're encrypting, apply the IV first. */
  8585. val ^= _iv.getInt16Le();
  8586. } else {
  8587. /* We're decryption, keep cipher text for next block. */
  8588. _iv.putInt16Le(val);
  8589. }
  8590. }
  8591. R.push(val & 0xffff);
  8592. }
  8593. /* Reset global "j" variable as per spec. */
  8594. j = encrypt ? 0 : 63;
  8595. /* Run execution plan. */
  8596. for(var ptr = 0; ptr < plan.length; ptr++) {
  8597. for(var ctr = 0; ctr < plan[ptr][0]; ctr++) {
  8598. plan[ptr][1](R);
  8599. }
  8600. }
  8601. /* Write back result to output buffer. */
  8602. for(i = 0; i < 4; i++) {
  8603. if(_iv !== null) {
  8604. if(encrypt) {
  8605. /* We're encrypting in CBC-mode, feed back encrypted bytes into
  8606. IV buffer to carry it forward to next block. */
  8607. _iv.putInt16Le(R[i]);
  8608. } else {
  8609. R[i] ^= _iv.getInt16Le();
  8610. }
  8611. }
  8612. _output.putInt16Le(R[i]);
  8613. }
  8614. };
  8615. /* Create cipher object */
  8616. var cipher = null;
  8617. cipher = {
  8618. /**
  8619. * Starts or restarts the encryption or decryption process, whichever
  8620. * was previously configured.
  8621. *
  8622. * To use the cipher in CBC mode, iv may be given either as a string
  8623. * of bytes, or as a byte buffer. For ECB mode, give null as iv.
  8624. *
  8625. * @param iv the initialization vector to use, null for ECB mode.
  8626. * @param output the output the buffer to write to, null to create one.
  8627. */
  8628. start: function(iv, output) {
  8629. if(iv) {
  8630. /* CBC mode */
  8631. if(typeof iv === 'string') {
  8632. iv = forge$p.util.createBuffer(iv);
  8633. }
  8634. }
  8635. _finish = false;
  8636. _input = forge$p.util.createBuffer();
  8637. _output = output || new forge$p.util.createBuffer();
  8638. _iv = iv;
  8639. cipher.output = _output;
  8640. },
  8641. /**
  8642. * Updates the next block.
  8643. *
  8644. * @param input the buffer to read from.
  8645. */
  8646. update: function(input) {
  8647. if(!_finish) {
  8648. // not finishing, so fill the input buffer with more input
  8649. _input.putBuffer(input);
  8650. }
  8651. while(_input.length() >= 8) {
  8652. runPlan([
  8653. [ 5, mixRound ],
  8654. [ 1, mashRound ],
  8655. [ 6, mixRound ],
  8656. [ 1, mashRound ],
  8657. [ 5, mixRound ]
  8658. ]);
  8659. }
  8660. },
  8661. /**
  8662. * Finishes encrypting or decrypting.
  8663. *
  8664. * @param pad a padding function to use, null for PKCS#7 padding,
  8665. * signature(blockSize, buffer, decrypt).
  8666. *
  8667. * @return true if successful, false on error.
  8668. */
  8669. finish: function(pad) {
  8670. var rval = true;
  8671. if(encrypt) {
  8672. if(pad) {
  8673. rval = pad(8, _input, !encrypt);
  8674. } else {
  8675. // add PKCS#7 padding to block (each pad byte is the
  8676. // value of the number of pad bytes)
  8677. var padding = (_input.length() === 8) ? 8 : (8 - _input.length());
  8678. _input.fillWithByte(padding, padding);
  8679. }
  8680. }
  8681. if(rval) {
  8682. // do final update
  8683. _finish = true;
  8684. cipher.update();
  8685. }
  8686. if(!encrypt) {
  8687. // check for error: input data not a multiple of block size
  8688. rval = (_input.length() === 0);
  8689. if(rval) {
  8690. if(pad) {
  8691. rval = pad(8, _output, !encrypt);
  8692. } else {
  8693. // ensure padding byte count is valid
  8694. var len = _output.length();
  8695. var count = _output.at(len - 1);
  8696. if(count > len) {
  8697. rval = false;
  8698. } else {
  8699. // trim off padding bytes
  8700. _output.truncate(count);
  8701. }
  8702. }
  8703. }
  8704. }
  8705. return rval;
  8706. }
  8707. };
  8708. return cipher;
  8709. };
  8710. /**
  8711. * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the
  8712. * given symmetric key. The output will be stored in the 'output' member
  8713. * of the returned cipher.
  8714. *
  8715. * The key and iv may be given as a string of bytes or a byte buffer.
  8716. * The cipher is initialized to use 128 effective key bits.
  8717. *
  8718. * @param key the symmetric key to use.
  8719. * @param iv the initialization vector to use.
  8720. * @param output the buffer to write to, null to create one.
  8721. *
  8722. * @return the cipher.
  8723. */
  8724. forge$p.rc2.startEncrypting = function(key, iv, output) {
  8725. var cipher = forge$p.rc2.createEncryptionCipher(key, 128);
  8726. cipher.start(iv, output);
  8727. return cipher;
  8728. };
  8729. /**
  8730. * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the
  8731. * given symmetric key.
  8732. *
  8733. * The key may be given as a string of bytes or a byte buffer.
  8734. *
  8735. * To start encrypting call start() on the cipher with an iv and optional
  8736. * output buffer.
  8737. *
  8738. * @param key the symmetric key to use.
  8739. *
  8740. * @return the cipher.
  8741. */
  8742. forge$p.rc2.createEncryptionCipher = function(key, bits) {
  8743. return createCipher(key, bits, true);
  8744. };
  8745. /**
  8746. * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the
  8747. * given symmetric key. The output will be stored in the 'output' member
  8748. * of the returned cipher.
  8749. *
  8750. * The key and iv may be given as a string of bytes or a byte buffer.
  8751. * The cipher is initialized to use 128 effective key bits.
  8752. *
  8753. * @param key the symmetric key to use.
  8754. * @param iv the initialization vector to use.
  8755. * @param output the buffer to write to, null to create one.
  8756. *
  8757. * @return the cipher.
  8758. */
  8759. forge$p.rc2.startDecrypting = function(key, iv, output) {
  8760. var cipher = forge$p.rc2.createDecryptionCipher(key, 128);
  8761. cipher.start(iv, output);
  8762. return cipher;
  8763. };
  8764. /**
  8765. * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the
  8766. * given symmetric key.
  8767. *
  8768. * The key may be given as a string of bytes or a byte buffer.
  8769. *
  8770. * To start decrypting call start() on the cipher with an iv and optional
  8771. * output buffer.
  8772. *
  8773. * @param key the symmetric key to use.
  8774. *
  8775. * @return the cipher.
  8776. */
  8777. forge$p.rc2.createDecryptionCipher = function(key, bits) {
  8778. return createCipher(key, bits, false);
  8779. };
  8780. // Copyright (c) 2005 Tom Wu
  8781. // All Rights Reserved.
  8782. // See "LICENSE" for details.
  8783. // Basic JavaScript BN library - subset useful for RSA encryption.
  8784. /*
  8785. Licensing (LICENSE)
  8786. -------------------
  8787. This software is covered under the following copyright:
  8788. */
  8789. /*
  8790. * Copyright (c) 2003-2005 Tom Wu
  8791. * All Rights Reserved.
  8792. *
  8793. * Permission is hereby granted, free of charge, to any person obtaining
  8794. * a copy of this software and associated documentation files (the
  8795. * "Software"), to deal in the Software without restriction, including
  8796. * without limitation the rights to use, copy, modify, merge, publish,
  8797. * distribute, sublicense, and/or sell copies of the Software, and to
  8798. * permit persons to whom the Software is furnished to do so, subject to
  8799. * the following conditions:
  8800. *
  8801. * The above copyright notice and this permission notice shall be
  8802. * included in all copies or substantial portions of the Software.
  8803. *
  8804. * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
  8805. * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
  8806. * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
  8807. *
  8808. * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
  8809. * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER
  8810. * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF
  8811. * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT
  8812. * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  8813. *
  8814. * In addition, the following condition applies:
  8815. *
  8816. * All redistributions must retain an intact copy of this copyright notice
  8817. * and disclaimer.
  8818. */
  8819. /*
  8820. Address all questions regarding this license to:
  8821. Tom Wu
  8822. tjw@cs.Stanford.EDU
  8823. */
  8824. var forge$o = forge$F;
  8825. forge$o.jsbn = forge$o.jsbn || {};
  8826. // Bits per digit
  8827. var dbits;
  8828. // (public) Constructor
  8829. function BigInteger$2(a,b,c) {
  8830. this.data = [];
  8831. if(a != null)
  8832. if("number" == typeof a) this.fromNumber(a,b,c);
  8833. else if(b == null && "string" != typeof a) this.fromString(a,256);
  8834. else this.fromString(a,b);
  8835. }
  8836. forge$o.jsbn.BigInteger = BigInteger$2;
  8837. // return new, unset BigInteger
  8838. function nbi() { return new BigInteger$2(null); }
  8839. // am: Compute w_j += (x*this_i), propagate carries,
  8840. // c is initial carry, returns final carry.
  8841. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue
  8842. // We need to select the fastest one that works in this environment.
  8843. // am1: use a single mult and divide to get the high bits,
  8844. // max digit bits should be 26 because
  8845. // max internal value = 2*dvalue^2-2*dvalue (< 2^53)
  8846. function am1(i,x,w,j,c,n) {
  8847. while(--n >= 0) {
  8848. var v = x*this.data[i++]+w.data[j]+c;
  8849. c = Math.floor(v/0x4000000);
  8850. w.data[j++] = v&0x3ffffff;
  8851. }
  8852. return c;
  8853. }
  8854. // am2 avoids a big mult-and-extract completely.
  8855. // Max digit bits should be <= 30 because we do bitwise ops
  8856. // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
  8857. function am2(i,x,w,j,c,n) {
  8858. var xl = x&0x7fff, xh = x>>15;
  8859. while(--n >= 0) {
  8860. var l = this.data[i]&0x7fff;
  8861. var h = this.data[i++]>>15;
  8862. var m = xh*l+h*xl;
  8863. l = xl*l+((m&0x7fff)<<15)+w.data[j]+(c&0x3fffffff);
  8864. c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);
  8865. w.data[j++] = l&0x3fffffff;
  8866. }
  8867. return c;
  8868. }
  8869. // Alternately, set max digit bits to 28 since some
  8870. // browsers slow down when dealing with 32-bit numbers.
  8871. function am3(i,x,w,j,c,n) {
  8872. var xl = x&0x3fff, xh = x>>14;
  8873. while(--n >= 0) {
  8874. var l = this.data[i]&0x3fff;
  8875. var h = this.data[i++]>>14;
  8876. var m = xh*l+h*xl;
  8877. l = xl*l+((m&0x3fff)<<14)+w.data[j]+c;
  8878. c = (l>>28)+(m>>14)+xh*h;
  8879. w.data[j++] = l&0xfffffff;
  8880. }
  8881. return c;
  8882. }
  8883. // node.js (no browser)
  8884. if(typeof(navigator) === 'undefined')
  8885. {
  8886. BigInteger$2.prototype.am = am3;
  8887. dbits = 28;
  8888. } else if((navigator.appName == "Microsoft Internet Explorer")) {
  8889. BigInteger$2.prototype.am = am2;
  8890. dbits = 30;
  8891. } else if((navigator.appName != "Netscape")) {
  8892. BigInteger$2.prototype.am = am1;
  8893. dbits = 26;
  8894. } else { // Mozilla/Netscape seems to prefer am3
  8895. BigInteger$2.prototype.am = am3;
  8896. dbits = 28;
  8897. }
  8898. BigInteger$2.prototype.DB = dbits;
  8899. BigInteger$2.prototype.DM = ((1<<dbits)-1);
  8900. BigInteger$2.prototype.DV = (1<<dbits);
  8901. var BI_FP = 52;
  8902. BigInteger$2.prototype.FV = Math.pow(2,BI_FP);
  8903. BigInteger$2.prototype.F1 = BI_FP-dbits;
  8904. BigInteger$2.prototype.F2 = 2*dbits-BI_FP;
  8905. // Digit conversions
  8906. var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
  8907. var BI_RC = new Array();
  8908. var rr,vv;
  8909. rr = "0".charCodeAt(0);
  8910. for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv;
  8911. rr = "a".charCodeAt(0);
  8912. for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
  8913. rr = "A".charCodeAt(0);
  8914. for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
  8915. function int2char(n) { return BI_RM.charAt(n); }
  8916. function intAt(s,i) {
  8917. var c = BI_RC[s.charCodeAt(i)];
  8918. return (c==null)?-1:c;
  8919. }
  8920. // (protected) copy this to r
  8921. function bnpCopyTo(r) {
  8922. for(var i = this.t-1; i >= 0; --i) r.data[i] = this.data[i];
  8923. r.t = this.t;
  8924. r.s = this.s;
  8925. }
  8926. // (protected) set from integer value x, -DV <= x < DV
  8927. function bnpFromInt(x) {
  8928. this.t = 1;
  8929. this.s = (x<0)?-1:0;
  8930. if(x > 0) this.data[0] = x;
  8931. else if(x < -1) this.data[0] = x+this.DV;
  8932. else this.t = 0;
  8933. }
  8934. // return bigint initialized to value
  8935. function nbv(i) { var r = nbi(); r.fromInt(i); return r; }
  8936. // (protected) set from string and radix
  8937. function bnpFromString(s,b) {
  8938. var k;
  8939. if(b == 16) k = 4;
  8940. else if(b == 8) k = 3;
  8941. else if(b == 256) k = 8; // byte array
  8942. else if(b == 2) k = 1;
  8943. else if(b == 32) k = 5;
  8944. else if(b == 4) k = 2;
  8945. else { this.fromRadix(s,b); return; }
  8946. this.t = 0;
  8947. this.s = 0;
  8948. var i = s.length, mi = false, sh = 0;
  8949. while(--i >= 0) {
  8950. var x = (k==8)?s[i]&0xff:intAt(s,i);
  8951. if(x < 0) {
  8952. if(s.charAt(i) == "-") mi = true;
  8953. continue;
  8954. }
  8955. mi = false;
  8956. if(sh == 0)
  8957. this.data[this.t++] = x;
  8958. else if(sh+k > this.DB) {
  8959. this.data[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh;
  8960. this.data[this.t++] = (x>>(this.DB-sh));
  8961. } else
  8962. this.data[this.t-1] |= x<<sh;
  8963. sh += k;
  8964. if(sh >= this.DB) sh -= this.DB;
  8965. }
  8966. if(k == 8 && (s[0]&0x80) != 0) {
  8967. this.s = -1;
  8968. if(sh > 0) this.data[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh;
  8969. }
  8970. this.clamp();
  8971. if(mi) BigInteger$2.ZERO.subTo(this,this);
  8972. }
  8973. // (protected) clamp off excess high words
  8974. function bnpClamp() {
  8975. var c = this.s&this.DM;
  8976. while(this.t > 0 && this.data[this.t-1] == c) --this.t;
  8977. }
  8978. // (public) return string representation in given radix
  8979. function bnToString(b) {
  8980. if(this.s < 0) return "-"+this.negate().toString(b);
  8981. var k;
  8982. if(b == 16) k = 4;
  8983. else if(b == 8) k = 3;
  8984. else if(b == 2) k = 1;
  8985. else if(b == 32) k = 5;
  8986. else if(b == 4) k = 2;
  8987. else return this.toRadix(b);
  8988. var km = (1<<k)-1, d, m = false, r = "", i = this.t;
  8989. var p = this.DB-(i*this.DB)%k;
  8990. if(i-- > 0) {
  8991. if(p < this.DB && (d = this.data[i]>>p) > 0) { m = true; r = int2char(d); }
  8992. while(i >= 0) {
  8993. if(p < k) {
  8994. d = (this.data[i]&((1<<p)-1))<<(k-p);
  8995. d |= this.data[--i]>>(p+=this.DB-k);
  8996. } else {
  8997. d = (this.data[i]>>(p-=k))&km;
  8998. if(p <= 0) { p += this.DB; --i; }
  8999. }
  9000. if(d > 0) m = true;
  9001. if(m) r += int2char(d);
  9002. }
  9003. }
  9004. return m?r:"0";
  9005. }
  9006. // (public) -this
  9007. function bnNegate() { var r = nbi(); BigInteger$2.ZERO.subTo(this,r); return r; }
  9008. // (public) |this|
  9009. function bnAbs() { return (this.s<0)?this.negate():this; }
  9010. // (public) return + if this > a, - if this < a, 0 if equal
  9011. function bnCompareTo(a) {
  9012. var r = this.s-a.s;
  9013. if(r != 0) return r;
  9014. var i = this.t;
  9015. r = i-a.t;
  9016. if(r != 0) return (this.s<0)?-r:r;
  9017. while(--i >= 0) if((r=this.data[i]-a.data[i]) != 0) return r;
  9018. return 0;
  9019. }
  9020. // returns bit length of the integer x
  9021. function nbits(x) {
  9022. var r = 1, t;
  9023. if((t=x>>>16) != 0) { x = t; r += 16; }
  9024. if((t=x>>8) != 0) { x = t; r += 8; }
  9025. if((t=x>>4) != 0) { x = t; r += 4; }
  9026. if((t=x>>2) != 0) { x = t; r += 2; }
  9027. if((t=x>>1) != 0) { x = t; r += 1; }
  9028. return r;
  9029. }
  9030. // (public) return the number of bits in "this"
  9031. function bnBitLength() {
  9032. if(this.t <= 0) return 0;
  9033. return this.DB*(this.t-1)+nbits(this.data[this.t-1]^(this.s&this.DM));
  9034. }
  9035. // (protected) r = this << n*DB
  9036. function bnpDLShiftTo(n,r) {
  9037. var i;
  9038. for(i = this.t-1; i >= 0; --i) r.data[i+n] = this.data[i];
  9039. for(i = n-1; i >= 0; --i) r.data[i] = 0;
  9040. r.t = this.t+n;
  9041. r.s = this.s;
  9042. }
  9043. // (protected) r = this >> n*DB
  9044. function bnpDRShiftTo(n,r) {
  9045. for(var i = n; i < this.t; ++i) r.data[i-n] = this.data[i];
  9046. r.t = Math.max(this.t-n,0);
  9047. r.s = this.s;
  9048. }
  9049. // (protected) r = this << n
  9050. function bnpLShiftTo(n,r) {
  9051. var bs = n%this.DB;
  9052. var cbs = this.DB-bs;
  9053. var bm = (1<<cbs)-1;
  9054. var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i;
  9055. for(i = this.t-1; i >= 0; --i) {
  9056. r.data[i+ds+1] = (this.data[i]>>cbs)|c;
  9057. c = (this.data[i]&bm)<<bs;
  9058. }
  9059. for(i = ds-1; i >= 0; --i) r.data[i] = 0;
  9060. r.data[ds] = c;
  9061. r.t = this.t+ds+1;
  9062. r.s = this.s;
  9063. r.clamp();
  9064. }
  9065. // (protected) r = this >> n
  9066. function bnpRShiftTo(n,r) {
  9067. r.s = this.s;
  9068. var ds = Math.floor(n/this.DB);
  9069. if(ds >= this.t) { r.t = 0; return; }
  9070. var bs = n%this.DB;
  9071. var cbs = this.DB-bs;
  9072. var bm = (1<<bs)-1;
  9073. r.data[0] = this.data[ds]>>bs;
  9074. for(var i = ds+1; i < this.t; ++i) {
  9075. r.data[i-ds-1] |= (this.data[i]&bm)<<cbs;
  9076. r.data[i-ds] = this.data[i]>>bs;
  9077. }
  9078. if(bs > 0) r.data[this.t-ds-1] |= (this.s&bm)<<cbs;
  9079. r.t = this.t-ds;
  9080. r.clamp();
  9081. }
  9082. // (protected) r = this - a
  9083. function bnpSubTo(a,r) {
  9084. var i = 0, c = 0, m = Math.min(a.t,this.t);
  9085. while(i < m) {
  9086. c += this.data[i]-a.data[i];
  9087. r.data[i++] = c&this.DM;
  9088. c >>= this.DB;
  9089. }
  9090. if(a.t < this.t) {
  9091. c -= a.s;
  9092. while(i < this.t) {
  9093. c += this.data[i];
  9094. r.data[i++] = c&this.DM;
  9095. c >>= this.DB;
  9096. }
  9097. c += this.s;
  9098. } else {
  9099. c += this.s;
  9100. while(i < a.t) {
  9101. c -= a.data[i];
  9102. r.data[i++] = c&this.DM;
  9103. c >>= this.DB;
  9104. }
  9105. c -= a.s;
  9106. }
  9107. r.s = (c<0)?-1:0;
  9108. if(c < -1) r.data[i++] = this.DV+c;
  9109. else if(c > 0) r.data[i++] = c;
  9110. r.t = i;
  9111. r.clamp();
  9112. }
  9113. // (protected) r = this * a, r != this,a (HAC 14.12)
  9114. // "this" should be the larger one if appropriate.
  9115. function bnpMultiplyTo(a,r) {
  9116. var x = this.abs(), y = a.abs();
  9117. var i = x.t;
  9118. r.t = i+y.t;
  9119. while(--i >= 0) r.data[i] = 0;
  9120. for(i = 0; i < y.t; ++i) r.data[i+x.t] = x.am(0,y.data[i],r,i,0,x.t);
  9121. r.s = 0;
  9122. r.clamp();
  9123. if(this.s != a.s) BigInteger$2.ZERO.subTo(r,r);
  9124. }
  9125. // (protected) r = this^2, r != this (HAC 14.16)
  9126. function bnpSquareTo(r) {
  9127. var x = this.abs();
  9128. var i = r.t = 2*x.t;
  9129. while(--i >= 0) r.data[i] = 0;
  9130. for(i = 0; i < x.t-1; ++i) {
  9131. var c = x.am(i,x.data[i],r,2*i,0,1);
  9132. if((r.data[i+x.t]+=x.am(i+1,2*x.data[i],r,2*i+1,c,x.t-i-1)) >= x.DV) {
  9133. r.data[i+x.t] -= x.DV;
  9134. r.data[i+x.t+1] = 1;
  9135. }
  9136. }
  9137. if(r.t > 0) r.data[r.t-1] += x.am(i,x.data[i],r,2*i,0,1);
  9138. r.s = 0;
  9139. r.clamp();
  9140. }
  9141. // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
  9142. // r != q, this != m. q or r may be null.
  9143. function bnpDivRemTo(m,q,r) {
  9144. var pm = m.abs();
  9145. if(pm.t <= 0) return;
  9146. var pt = this.abs();
  9147. if(pt.t < pm.t) {
  9148. if(q != null) q.fromInt(0);
  9149. if(r != null) this.copyTo(r);
  9150. return;
  9151. }
  9152. if(r == null) r = nbi();
  9153. var y = nbi(), ts = this.s, ms = m.s;
  9154. var nsh = this.DB-nbits(pm.data[pm.t-1]); // normalize modulus
  9155. if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); }
  9156. var ys = y.t;
  9157. var y0 = y.data[ys-1];
  9158. if(y0 == 0) return;
  9159. var yt = y0*(1<<this.F1)+((ys>1)?y.data[ys-2]>>this.F2:0);
  9160. var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2;
  9161. var i = r.t, j = i-ys, t = (q==null)?nbi():q;
  9162. y.dlShiftTo(j,t);
  9163. if(r.compareTo(t) >= 0) {
  9164. r.data[r.t++] = 1;
  9165. r.subTo(t,r);
  9166. }
  9167. BigInteger$2.ONE.dlShiftTo(ys,t);
  9168. t.subTo(y,y); // "negative" y so we can replace sub with am later
  9169. while(y.t < ys) y.data[y.t++] = 0;
  9170. while(--j >= 0) {
  9171. // Estimate quotient digit
  9172. var qd = (r.data[--i]==y0)?this.DM:Math.floor(r.data[i]*d1+(r.data[i-1]+e)*d2);
  9173. if((r.data[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out
  9174. y.dlShiftTo(j,t);
  9175. r.subTo(t,r);
  9176. while(r.data[i] < --qd) r.subTo(t,r);
  9177. }
  9178. }
  9179. if(q != null) {
  9180. r.drShiftTo(ys,q);
  9181. if(ts != ms) BigInteger$2.ZERO.subTo(q,q);
  9182. }
  9183. r.t = ys;
  9184. r.clamp();
  9185. if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder
  9186. if(ts < 0) BigInteger$2.ZERO.subTo(r,r);
  9187. }
  9188. // (public) this mod a
  9189. function bnMod(a) {
  9190. var r = nbi();
  9191. this.abs().divRemTo(a,null,r);
  9192. if(this.s < 0 && r.compareTo(BigInteger$2.ZERO) > 0) a.subTo(r,r);
  9193. return r;
  9194. }
  9195. // Modular reduction using "classic" algorithm
  9196. function Classic(m) { this.m = m; }
  9197. function cConvert(x) {
  9198. if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);
  9199. else return x;
  9200. }
  9201. function cRevert(x) { return x; }
  9202. function cReduce(x) { x.divRemTo(this.m,null,x); }
  9203. function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
  9204. function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
  9205. Classic.prototype.convert = cConvert;
  9206. Classic.prototype.revert = cRevert;
  9207. Classic.prototype.reduce = cReduce;
  9208. Classic.prototype.mulTo = cMulTo;
  9209. Classic.prototype.sqrTo = cSqrTo;
  9210. // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
  9211. // justification:
  9212. // xy == 1 (mod m)
  9213. // xy = 1+km
  9214. // xy(2-xy) = (1+km)(1-km)
  9215. // x[y(2-xy)] = 1-k^2m^2
  9216. // x[y(2-xy)] == 1 (mod m^2)
  9217. // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
  9218. // should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
  9219. // JS multiply "overflows" differently from C/C++, so care is needed here.
  9220. function bnpInvDigit() {
  9221. if(this.t < 1) return 0;
  9222. var x = this.data[0];
  9223. if((x&1) == 0) return 0;
  9224. var y = x&3; // y == 1/x mod 2^2
  9225. y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4
  9226. y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8
  9227. y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16
  9228. // last step - calculate inverse mod DV directly;
  9229. // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
  9230. y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits
  9231. // we really want the negative inverse, and -DV < y < DV
  9232. return (y>0)?this.DV-y:-y;
  9233. }
  9234. // Montgomery reduction
  9235. function Montgomery(m) {
  9236. this.m = m;
  9237. this.mp = m.invDigit();
  9238. this.mpl = this.mp&0x7fff;
  9239. this.mph = this.mp>>15;
  9240. this.um = (1<<(m.DB-15))-1;
  9241. this.mt2 = 2*m.t;
  9242. }
  9243. // xR mod m
  9244. function montConvert(x) {
  9245. var r = nbi();
  9246. x.abs().dlShiftTo(this.m.t,r);
  9247. r.divRemTo(this.m,null,r);
  9248. if(x.s < 0 && r.compareTo(BigInteger$2.ZERO) > 0) this.m.subTo(r,r);
  9249. return r;
  9250. }
  9251. // x/R mod m
  9252. function montRevert(x) {
  9253. var r = nbi();
  9254. x.copyTo(r);
  9255. this.reduce(r);
  9256. return r;
  9257. }
  9258. // x = x/R mod m (HAC 14.32)
  9259. function montReduce(x) {
  9260. while(x.t <= this.mt2) // pad x so am has enough room later
  9261. x.data[x.t++] = 0;
  9262. for(var i = 0; i < this.m.t; ++i) {
  9263. // faster way of calculating u0 = x.data[i]*mp mod DV
  9264. var j = x.data[i]&0x7fff;
  9265. var u0 = (j*this.mpl+(((j*this.mph+(x.data[i]>>15)*this.mpl)&this.um)<<15))&x.DM;
  9266. // use am to combine the multiply-shift-add into one call
  9267. j = i+this.m.t;
  9268. x.data[j] += this.m.am(0,u0,x,i,0,this.m.t);
  9269. // propagate carry
  9270. while(x.data[j] >= x.DV) { x.data[j] -= x.DV; x.data[++j]++; }
  9271. }
  9272. x.clamp();
  9273. x.drShiftTo(this.m.t,x);
  9274. if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
  9275. }
  9276. // r = "x^2/R mod m"; x != r
  9277. function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
  9278. // r = "xy/R mod m"; x,y != r
  9279. function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
  9280. Montgomery.prototype.convert = montConvert;
  9281. Montgomery.prototype.revert = montRevert;
  9282. Montgomery.prototype.reduce = montReduce;
  9283. Montgomery.prototype.mulTo = montMulTo;
  9284. Montgomery.prototype.sqrTo = montSqrTo;
  9285. // (protected) true iff this is even
  9286. function bnpIsEven() { return ((this.t>0)?(this.data[0]&1):this.s) == 0; }
  9287. // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
  9288. function bnpExp(e,z) {
  9289. if(e > 0xffffffff || e < 1) return BigInteger$2.ONE;
  9290. var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;
  9291. g.copyTo(r);
  9292. while(--i >= 0) {
  9293. z.sqrTo(r,r2);
  9294. if((e&(1<<i)) > 0) z.mulTo(r2,g,r);
  9295. else { var t = r; r = r2; r2 = t; }
  9296. }
  9297. return z.revert(r);
  9298. }
  9299. // (public) this^e % m, 0 <= e < 2^32
  9300. function bnModPowInt(e,m) {
  9301. var z;
  9302. if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);
  9303. return this.exp(e,z);
  9304. }
  9305. // protected
  9306. BigInteger$2.prototype.copyTo = bnpCopyTo;
  9307. BigInteger$2.prototype.fromInt = bnpFromInt;
  9308. BigInteger$2.prototype.fromString = bnpFromString;
  9309. BigInteger$2.prototype.clamp = bnpClamp;
  9310. BigInteger$2.prototype.dlShiftTo = bnpDLShiftTo;
  9311. BigInteger$2.prototype.drShiftTo = bnpDRShiftTo;
  9312. BigInteger$2.prototype.lShiftTo = bnpLShiftTo;
  9313. BigInteger$2.prototype.rShiftTo = bnpRShiftTo;
  9314. BigInteger$2.prototype.subTo = bnpSubTo;
  9315. BigInteger$2.prototype.multiplyTo = bnpMultiplyTo;
  9316. BigInteger$2.prototype.squareTo = bnpSquareTo;
  9317. BigInteger$2.prototype.divRemTo = bnpDivRemTo;
  9318. BigInteger$2.prototype.invDigit = bnpInvDigit;
  9319. BigInteger$2.prototype.isEven = bnpIsEven;
  9320. BigInteger$2.prototype.exp = bnpExp;
  9321. // public
  9322. BigInteger$2.prototype.toString = bnToString;
  9323. BigInteger$2.prototype.negate = bnNegate;
  9324. BigInteger$2.prototype.abs = bnAbs;
  9325. BigInteger$2.prototype.compareTo = bnCompareTo;
  9326. BigInteger$2.prototype.bitLength = bnBitLength;
  9327. BigInteger$2.prototype.mod = bnMod;
  9328. BigInteger$2.prototype.modPowInt = bnModPowInt;
  9329. // "constants"
  9330. BigInteger$2.ZERO = nbv(0);
  9331. BigInteger$2.ONE = nbv(1);
  9332. // jsbn2 lib
  9333. //Copyright (c) 2005-2009 Tom Wu
  9334. //All Rights Reserved.
  9335. //See "LICENSE" for details (See jsbn.js for LICENSE).
  9336. //Extended JavaScript BN functions, required for RSA private ops.
  9337. //Version 1.1: new BigInteger("0", 10) returns "proper" zero
  9338. //(public)
  9339. function bnClone() { var r = nbi(); this.copyTo(r); return r; }
  9340. //(public) return value as integer
  9341. function bnIntValue() {
  9342. if(this.s < 0) {
  9343. if(this.t == 1) return this.data[0]-this.DV;
  9344. else if(this.t == 0) return -1;
  9345. } else if(this.t == 1) return this.data[0];
  9346. else if(this.t == 0) return 0;
  9347. // assumes 16 < DB < 32
  9348. return ((this.data[1]&((1<<(32-this.DB))-1))<<this.DB)|this.data[0];
  9349. }
  9350. //(public) return value as byte
  9351. function bnByteValue() { return (this.t==0)?this.s:(this.data[0]<<24)>>24; }
  9352. //(public) return value as short (assumes DB>=16)
  9353. function bnShortValue() { return (this.t==0)?this.s:(this.data[0]<<16)>>16; }
  9354. //(protected) return x s.t. r^x < DV
  9355. function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); }
  9356. //(public) 0 if this == 0, 1 if this > 0
  9357. function bnSigNum() {
  9358. if(this.s < 0) return -1;
  9359. else if(this.t <= 0 || (this.t == 1 && this.data[0] <= 0)) return 0;
  9360. else return 1;
  9361. }
  9362. //(protected) convert to radix string
  9363. function bnpToRadix(b) {
  9364. if(b == null) b = 10;
  9365. if(this.signum() == 0 || b < 2 || b > 36) return "0";
  9366. var cs = this.chunkSize(b);
  9367. var a = Math.pow(b,cs);
  9368. var d = nbv(a), y = nbi(), z = nbi(), r = "";
  9369. this.divRemTo(d,y,z);
  9370. while(y.signum() > 0) {
  9371. r = (a+z.intValue()).toString(b).substr(1) + r;
  9372. y.divRemTo(d,y,z);
  9373. }
  9374. return z.intValue().toString(b) + r;
  9375. }
  9376. //(protected) convert from radix string
  9377. function bnpFromRadix(s,b) {
  9378. this.fromInt(0);
  9379. if(b == null) b = 10;
  9380. var cs = this.chunkSize(b);
  9381. var d = Math.pow(b,cs), mi = false, j = 0, w = 0;
  9382. for(var i = 0; i < s.length; ++i) {
  9383. var x = intAt(s,i);
  9384. if(x < 0) {
  9385. if(s.charAt(i) == "-" && this.signum() == 0) mi = true;
  9386. continue;
  9387. }
  9388. w = b*w+x;
  9389. if(++j >= cs) {
  9390. this.dMultiply(d);
  9391. this.dAddOffset(w,0);
  9392. j = 0;
  9393. w = 0;
  9394. }
  9395. }
  9396. if(j > 0) {
  9397. this.dMultiply(Math.pow(b,j));
  9398. this.dAddOffset(w,0);
  9399. }
  9400. if(mi) BigInteger$2.ZERO.subTo(this,this);
  9401. }
  9402. //(protected) alternate constructor
  9403. function bnpFromNumber(a,b,c) {
  9404. if("number" == typeof b) {
  9405. // new BigInteger(int,int,RNG)
  9406. if(a < 2) this.fromInt(1);
  9407. else {
  9408. this.fromNumber(a,c);
  9409. if(!this.testBit(a-1)) // force MSB set
  9410. this.bitwiseTo(BigInteger$2.ONE.shiftLeft(a-1),op_or,this);
  9411. if(this.isEven()) this.dAddOffset(1,0); // force odd
  9412. while(!this.isProbablePrime(b)) {
  9413. this.dAddOffset(2,0);
  9414. if(this.bitLength() > a) this.subTo(BigInteger$2.ONE.shiftLeft(a-1),this);
  9415. }
  9416. }
  9417. } else {
  9418. // new BigInteger(int,RNG)
  9419. var x = new Array(), t = a&7;
  9420. x.length = (a>>3)+1;
  9421. b.nextBytes(x);
  9422. if(t > 0) x[0] &= ((1<<t)-1); else x[0] = 0;
  9423. this.fromString(x,256);
  9424. }
  9425. }
  9426. //(public) convert to bigendian byte array
  9427. function bnToByteArray() {
  9428. var i = this.t, r = new Array();
  9429. r[0] = this.s;
  9430. var p = this.DB-(i*this.DB)%8, d, k = 0;
  9431. if(i-- > 0) {
  9432. if(p < this.DB && (d = this.data[i]>>p) != (this.s&this.DM)>>p)
  9433. r[k++] = d|(this.s<<(this.DB-p));
  9434. while(i >= 0) {
  9435. if(p < 8) {
  9436. d = (this.data[i]&((1<<p)-1))<<(8-p);
  9437. d |= this.data[--i]>>(p+=this.DB-8);
  9438. } else {
  9439. d = (this.data[i]>>(p-=8))&0xff;
  9440. if(p <= 0) { p += this.DB; --i; }
  9441. }
  9442. if((d&0x80) != 0) d |= -256;
  9443. if(k == 0 && (this.s&0x80) != (d&0x80)) ++k;
  9444. if(k > 0 || d != this.s) r[k++] = d;
  9445. }
  9446. }
  9447. return r;
  9448. }
  9449. function bnEquals(a) { return(this.compareTo(a)==0); }
  9450. function bnMin(a) { return (this.compareTo(a)<0)?this:a; }
  9451. function bnMax(a) { return (this.compareTo(a)>0)?this:a; }
  9452. //(protected) r = this op a (bitwise)
  9453. function bnpBitwiseTo(a,op,r) {
  9454. var i, f, m = Math.min(a.t,this.t);
  9455. for(i = 0; i < m; ++i) r.data[i] = op(this.data[i],a.data[i]);
  9456. if(a.t < this.t) {
  9457. f = a.s&this.DM;
  9458. for(i = m; i < this.t; ++i) r.data[i] = op(this.data[i],f);
  9459. r.t = this.t;
  9460. } else {
  9461. f = this.s&this.DM;
  9462. for(i = m; i < a.t; ++i) r.data[i] = op(f,a.data[i]);
  9463. r.t = a.t;
  9464. }
  9465. r.s = op(this.s,a.s);
  9466. r.clamp();
  9467. }
  9468. //(public) this & a
  9469. function op_and(x,y) { return x&y; }
  9470. function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }
  9471. //(public) this | a
  9472. function op_or(x,y) { return x|y; }
  9473. function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }
  9474. //(public) this ^ a
  9475. function op_xor(x,y) { return x^y; }
  9476. function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }
  9477. //(public) this & ~a
  9478. function op_andnot(x,y) { return x&~y; }
  9479. function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; }
  9480. //(public) ~this
  9481. function bnNot() {
  9482. var r = nbi();
  9483. for(var i = 0; i < this.t; ++i) r.data[i] = this.DM&~this.data[i];
  9484. r.t = this.t;
  9485. r.s = ~this.s;
  9486. return r;
  9487. }
  9488. //(public) this << n
  9489. function bnShiftLeft(n) {
  9490. var r = nbi();
  9491. if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r);
  9492. return r;
  9493. }
  9494. //(public) this >> n
  9495. function bnShiftRight(n) {
  9496. var r = nbi();
  9497. if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r);
  9498. return r;
  9499. }
  9500. //return index of lowest 1-bit in x, x < 2^31
  9501. function lbit(x) {
  9502. if(x == 0) return -1;
  9503. var r = 0;
  9504. if((x&0xffff) == 0) { x >>= 16; r += 16; }
  9505. if((x&0xff) == 0) { x >>= 8; r += 8; }
  9506. if((x&0xf) == 0) { x >>= 4; r += 4; }
  9507. if((x&3) == 0) { x >>= 2; r += 2; }
  9508. if((x&1) == 0) ++r;
  9509. return r;
  9510. }
  9511. //(public) returns index of lowest 1-bit (or -1 if none)
  9512. function bnGetLowestSetBit() {
  9513. for(var i = 0; i < this.t; ++i)
  9514. if(this.data[i] != 0) return i*this.DB+lbit(this.data[i]);
  9515. if(this.s < 0) return this.t*this.DB;
  9516. return -1;
  9517. }
  9518. //return number of 1 bits in x
  9519. function cbit(x) {
  9520. var r = 0;
  9521. while(x != 0) { x &= x-1; ++r; }
  9522. return r;
  9523. }
  9524. //(public) return number of set bits
  9525. function bnBitCount() {
  9526. var r = 0, x = this.s&this.DM;
  9527. for(var i = 0; i < this.t; ++i) r += cbit(this.data[i]^x);
  9528. return r;
  9529. }
  9530. //(public) true iff nth bit is set
  9531. function bnTestBit(n) {
  9532. var j = Math.floor(n/this.DB);
  9533. if(j >= this.t) return(this.s!=0);
  9534. return((this.data[j]&(1<<(n%this.DB)))!=0);
  9535. }
  9536. //(protected) this op (1<<n)
  9537. function bnpChangeBit(n,op) {
  9538. var r = BigInteger$2.ONE.shiftLeft(n);
  9539. this.bitwiseTo(r,op,r);
  9540. return r;
  9541. }
  9542. //(public) this | (1<<n)
  9543. function bnSetBit(n) { return this.changeBit(n,op_or); }
  9544. //(public) this & ~(1<<n)
  9545. function bnClearBit(n) { return this.changeBit(n,op_andnot); }
  9546. //(public) this ^ (1<<n)
  9547. function bnFlipBit(n) { return this.changeBit(n,op_xor); }
  9548. //(protected) r = this + a
  9549. function bnpAddTo(a,r) {
  9550. var i = 0, c = 0, m = Math.min(a.t,this.t);
  9551. while(i < m) {
  9552. c += this.data[i]+a.data[i];
  9553. r.data[i++] = c&this.DM;
  9554. c >>= this.DB;
  9555. }
  9556. if(a.t < this.t) {
  9557. c += a.s;
  9558. while(i < this.t) {
  9559. c += this.data[i];
  9560. r.data[i++] = c&this.DM;
  9561. c >>= this.DB;
  9562. }
  9563. c += this.s;
  9564. } else {
  9565. c += this.s;
  9566. while(i < a.t) {
  9567. c += a.data[i];
  9568. r.data[i++] = c&this.DM;
  9569. c >>= this.DB;
  9570. }
  9571. c += a.s;
  9572. }
  9573. r.s = (c<0)?-1:0;
  9574. if(c > 0) r.data[i++] = c;
  9575. else if(c < -1) r.data[i++] = this.DV+c;
  9576. r.t = i;
  9577. r.clamp();
  9578. }
  9579. //(public) this + a
  9580. function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }
  9581. //(public) this - a
  9582. function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }
  9583. //(public) this * a
  9584. function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }
  9585. //(public) this / a
  9586. function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }
  9587. //(public) this % a
  9588. function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; }
  9589. //(public) [this/a,this%a]
  9590. function bnDivideAndRemainder(a) {
  9591. var q = nbi(), r = nbi();
  9592. this.divRemTo(a,q,r);
  9593. return new Array(q,r);
  9594. }
  9595. //(protected) this *= n, this >= 0, 1 < n < DV
  9596. function bnpDMultiply(n) {
  9597. this.data[this.t] = this.am(0,n-1,this,0,0,this.t);
  9598. ++this.t;
  9599. this.clamp();
  9600. }
  9601. //(protected) this += n << w words, this >= 0
  9602. function bnpDAddOffset(n,w) {
  9603. if(n == 0) return;
  9604. while(this.t <= w) this.data[this.t++] = 0;
  9605. this.data[w] += n;
  9606. while(this.data[w] >= this.DV) {
  9607. this.data[w] -= this.DV;
  9608. if(++w >= this.t) this.data[this.t++] = 0;
  9609. ++this.data[w];
  9610. }
  9611. }
  9612. //A "null" reducer
  9613. function NullExp() {}
  9614. function nNop(x) { return x; }
  9615. function nMulTo(x,y,r) { x.multiplyTo(y,r); }
  9616. function nSqrTo(x,r) { x.squareTo(r); }
  9617. NullExp.prototype.convert = nNop;
  9618. NullExp.prototype.revert = nNop;
  9619. NullExp.prototype.mulTo = nMulTo;
  9620. NullExp.prototype.sqrTo = nSqrTo;
  9621. //(public) this^e
  9622. function bnPow(e) { return this.exp(e,new NullExp()); }
  9623. //(protected) r = lower n words of "this * a", a.t <= n
  9624. //"this" should be the larger one if appropriate.
  9625. function bnpMultiplyLowerTo(a,n,r) {
  9626. var i = Math.min(this.t+a.t,n);
  9627. r.s = 0; // assumes a,this >= 0
  9628. r.t = i;
  9629. while(i > 0) r.data[--i] = 0;
  9630. var j;
  9631. for(j = r.t-this.t; i < j; ++i) r.data[i+this.t] = this.am(0,a.data[i],r,i,0,this.t);
  9632. for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a.data[i],r,i,0,n-i);
  9633. r.clamp();
  9634. }
  9635. //(protected) r = "this * a" without lower n words, n > 0
  9636. //"this" should be the larger one if appropriate.
  9637. function bnpMultiplyUpperTo(a,n,r) {
  9638. --n;
  9639. var i = r.t = this.t+a.t-n;
  9640. r.s = 0; // assumes a,this >= 0
  9641. while(--i >= 0) r.data[i] = 0;
  9642. for(i = Math.max(n-this.t,0); i < a.t; ++i)
  9643. r.data[this.t+i-n] = this.am(n-i,a.data[i],r,0,0,this.t+i-n);
  9644. r.clamp();
  9645. r.drShiftTo(1,r);
  9646. }
  9647. //Barrett modular reduction
  9648. function Barrett(m) {
  9649. // setup Barrett
  9650. this.r2 = nbi();
  9651. this.q3 = nbi();
  9652. BigInteger$2.ONE.dlShiftTo(2*m.t,this.r2);
  9653. this.mu = this.r2.divide(m);
  9654. this.m = m;
  9655. }
  9656. function barrettConvert(x) {
  9657. if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m);
  9658. else if(x.compareTo(this.m) < 0) return x;
  9659. else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }
  9660. }
  9661. function barrettRevert(x) { return x; }
  9662. //x = x mod m (HAC 14.42)
  9663. function barrettReduce(x) {
  9664. x.drShiftTo(this.m.t-1,this.r2);
  9665. if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }
  9666. this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);
  9667. this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);
  9668. while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1);
  9669. x.subTo(this.r2,x);
  9670. while(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
  9671. }
  9672. //r = x^2 mod m; x != r
  9673. function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
  9674. //r = x*y mod m; x,y != r
  9675. function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
  9676. Barrett.prototype.convert = barrettConvert;
  9677. Barrett.prototype.revert = barrettRevert;
  9678. Barrett.prototype.reduce = barrettReduce;
  9679. Barrett.prototype.mulTo = barrettMulTo;
  9680. Barrett.prototype.sqrTo = barrettSqrTo;
  9681. //(public) this^e % m (HAC 14.85)
  9682. function bnModPow(e,m) {
  9683. var i = e.bitLength(), k, r = nbv(1), z;
  9684. if(i <= 0) return r;
  9685. else if(i < 18) k = 1;
  9686. else if(i < 48) k = 3;
  9687. else if(i < 144) k = 4;
  9688. else if(i < 768) k = 5;
  9689. else k = 6;
  9690. if(i < 8)
  9691. z = new Classic(m);
  9692. else if(m.isEven())
  9693. z = new Barrett(m);
  9694. else
  9695. z = new Montgomery(m);
  9696. // precomputation
  9697. var g = new Array(), n = 3, k1 = k-1, km = (1<<k)-1;
  9698. g[1] = z.convert(this);
  9699. if(k > 1) {
  9700. var g2 = nbi();
  9701. z.sqrTo(g[1],g2);
  9702. while(n <= km) {
  9703. g[n] = nbi();
  9704. z.mulTo(g2,g[n-2],g[n]);
  9705. n += 2;
  9706. }
  9707. }
  9708. var j = e.t-1, w, is1 = true, r2 = nbi(), t;
  9709. i = nbits(e.data[j])-1;
  9710. while(j >= 0) {
  9711. if(i >= k1) w = (e.data[j]>>(i-k1))&km;
  9712. else {
  9713. w = (e.data[j]&((1<<(i+1))-1))<<(k1-i);
  9714. if(j > 0) w |= e.data[j-1]>>(this.DB+i-k1);
  9715. }
  9716. n = k;
  9717. while((w&1) == 0) { w >>= 1; --n; }
  9718. if((i -= n) < 0) { i += this.DB; --j; }
  9719. if(is1) { // ret == 1, don't bother squaring or multiplying it
  9720. g[w].copyTo(r);
  9721. is1 = false;
  9722. } else {
  9723. while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; }
  9724. if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; }
  9725. z.mulTo(r2,g[w],r);
  9726. }
  9727. while(j >= 0 && (e.data[j]&(1<<i)) == 0) {
  9728. z.sqrTo(r,r2); t = r; r = r2; r2 = t;
  9729. if(--i < 0) { i = this.DB-1; --j; }
  9730. }
  9731. }
  9732. return z.revert(r);
  9733. }
  9734. //(public) gcd(this,a) (HAC 14.54)
  9735. function bnGCD(a) {
  9736. var x = (this.s<0)?this.negate():this.clone();
  9737. var y = (a.s<0)?a.negate():a.clone();
  9738. if(x.compareTo(y) < 0) { var t = x; x = y; y = t; }
  9739. var i = x.getLowestSetBit(), g = y.getLowestSetBit();
  9740. if(g < 0) return x;
  9741. if(i < g) g = i;
  9742. if(g > 0) {
  9743. x.rShiftTo(g,x);
  9744. y.rShiftTo(g,y);
  9745. }
  9746. while(x.signum() > 0) {
  9747. if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x);
  9748. if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y);
  9749. if(x.compareTo(y) >= 0) {
  9750. x.subTo(y,x);
  9751. x.rShiftTo(1,x);
  9752. } else {
  9753. y.subTo(x,y);
  9754. y.rShiftTo(1,y);
  9755. }
  9756. }
  9757. if(g > 0) y.lShiftTo(g,y);
  9758. return y;
  9759. }
  9760. //(protected) this % n, n < 2^26
  9761. function bnpModInt(n) {
  9762. if(n <= 0) return 0;
  9763. var d = this.DV%n, r = (this.s<0)?n-1:0;
  9764. if(this.t > 0)
  9765. if(d == 0) r = this.data[0]%n;
  9766. else for(var i = this.t-1; i >= 0; --i) r = (d*r+this.data[i])%n;
  9767. return r;
  9768. }
  9769. //(public) 1/this % m (HAC 14.61)
  9770. function bnModInverse(m) {
  9771. var ac = m.isEven();
  9772. if((this.isEven() && ac) || m.signum() == 0) return BigInteger$2.ZERO;
  9773. var u = m.clone(), v = this.clone();
  9774. var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);
  9775. while(u.signum() != 0) {
  9776. while(u.isEven()) {
  9777. u.rShiftTo(1,u);
  9778. if(ac) {
  9779. if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); }
  9780. a.rShiftTo(1,a);
  9781. } else if(!b.isEven()) b.subTo(m,b);
  9782. b.rShiftTo(1,b);
  9783. }
  9784. while(v.isEven()) {
  9785. v.rShiftTo(1,v);
  9786. if(ac) {
  9787. if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); }
  9788. c.rShiftTo(1,c);
  9789. } else if(!d.isEven()) d.subTo(m,d);
  9790. d.rShiftTo(1,d);
  9791. }
  9792. if(u.compareTo(v) >= 0) {
  9793. u.subTo(v,u);
  9794. if(ac) a.subTo(c,a);
  9795. b.subTo(d,b);
  9796. } else {
  9797. v.subTo(u,v);
  9798. if(ac) c.subTo(a,c);
  9799. d.subTo(b,d);
  9800. }
  9801. }
  9802. if(v.compareTo(BigInteger$2.ONE) != 0) return BigInteger$2.ZERO;
  9803. if(d.compareTo(m) >= 0) return d.subtract(m);
  9804. if(d.signum() < 0) d.addTo(m,d); else return d;
  9805. if(d.signum() < 0) return d.add(m); else return d;
  9806. }
  9807. var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509];
  9808. var lplim = (1<<26)/lowprimes[lowprimes.length-1];
  9809. //(public) test primality with certainty >= 1-.5^t
  9810. function bnIsProbablePrime(t) {
  9811. var i, x = this.abs();
  9812. if(x.t == 1 && x.data[0] <= lowprimes[lowprimes.length-1]) {
  9813. for(i = 0; i < lowprimes.length; ++i)
  9814. if(x.data[0] == lowprimes[i]) return true;
  9815. return false;
  9816. }
  9817. if(x.isEven()) return false;
  9818. i = 1;
  9819. while(i < lowprimes.length) {
  9820. var m = lowprimes[i], j = i+1;
  9821. while(j < lowprimes.length && m < lplim) m *= lowprimes[j++];
  9822. m = x.modInt(m);
  9823. while(i < j) if(m%lowprimes[i++] == 0) return false;
  9824. }
  9825. return x.millerRabin(t);
  9826. }
  9827. //(protected) true if probably prime (HAC 4.24, Miller-Rabin)
  9828. function bnpMillerRabin(t) {
  9829. var n1 = this.subtract(BigInteger$2.ONE);
  9830. var k = n1.getLowestSetBit();
  9831. if(k <= 0) return false;
  9832. var r = n1.shiftRight(k);
  9833. var prng = bnGetPrng();
  9834. var a;
  9835. for(var i = 0; i < t; ++i) {
  9836. // select witness 'a' at random from between 1 and n1
  9837. do {
  9838. a = new BigInteger$2(this.bitLength(), prng);
  9839. }
  9840. while(a.compareTo(BigInteger$2.ONE) <= 0 || a.compareTo(n1) >= 0);
  9841. var y = a.modPow(r,this);
  9842. if(y.compareTo(BigInteger$2.ONE) != 0 && y.compareTo(n1) != 0) {
  9843. var j = 1;
  9844. while(j++ < k && y.compareTo(n1) != 0) {
  9845. y = y.modPowInt(2,this);
  9846. if(y.compareTo(BigInteger$2.ONE) == 0) return false;
  9847. }
  9848. if(y.compareTo(n1) != 0) return false;
  9849. }
  9850. }
  9851. return true;
  9852. }
  9853. // get pseudo random number generator
  9854. function bnGetPrng() {
  9855. // create prng with api that matches BigInteger secure random
  9856. return {
  9857. // x is an array to fill with bytes
  9858. nextBytes: function(x) {
  9859. for(var i = 0; i < x.length; ++i) {
  9860. x[i] = Math.floor(Math.random() * 0x0100);
  9861. }
  9862. }
  9863. };
  9864. }
  9865. //protected
  9866. BigInteger$2.prototype.chunkSize = bnpChunkSize;
  9867. BigInteger$2.prototype.toRadix = bnpToRadix;
  9868. BigInteger$2.prototype.fromRadix = bnpFromRadix;
  9869. BigInteger$2.prototype.fromNumber = bnpFromNumber;
  9870. BigInteger$2.prototype.bitwiseTo = bnpBitwiseTo;
  9871. BigInteger$2.prototype.changeBit = bnpChangeBit;
  9872. BigInteger$2.prototype.addTo = bnpAddTo;
  9873. BigInteger$2.prototype.dMultiply = bnpDMultiply;
  9874. BigInteger$2.prototype.dAddOffset = bnpDAddOffset;
  9875. BigInteger$2.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
  9876. BigInteger$2.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
  9877. BigInteger$2.prototype.modInt = bnpModInt;
  9878. BigInteger$2.prototype.millerRabin = bnpMillerRabin;
  9879. //public
  9880. BigInteger$2.prototype.clone = bnClone;
  9881. BigInteger$2.prototype.intValue = bnIntValue;
  9882. BigInteger$2.prototype.byteValue = bnByteValue;
  9883. BigInteger$2.prototype.shortValue = bnShortValue;
  9884. BigInteger$2.prototype.signum = bnSigNum;
  9885. BigInteger$2.prototype.toByteArray = bnToByteArray;
  9886. BigInteger$2.prototype.equals = bnEquals;
  9887. BigInteger$2.prototype.min = bnMin;
  9888. BigInteger$2.prototype.max = bnMax;
  9889. BigInteger$2.prototype.and = bnAnd;
  9890. BigInteger$2.prototype.or = bnOr;
  9891. BigInteger$2.prototype.xor = bnXor;
  9892. BigInteger$2.prototype.andNot = bnAndNot;
  9893. BigInteger$2.prototype.not = bnNot;
  9894. BigInteger$2.prototype.shiftLeft = bnShiftLeft;
  9895. BigInteger$2.prototype.shiftRight = bnShiftRight;
  9896. BigInteger$2.prototype.getLowestSetBit = bnGetLowestSetBit;
  9897. BigInteger$2.prototype.bitCount = bnBitCount;
  9898. BigInteger$2.prototype.testBit = bnTestBit;
  9899. BigInteger$2.prototype.setBit = bnSetBit;
  9900. BigInteger$2.prototype.clearBit = bnClearBit;
  9901. BigInteger$2.prototype.flipBit = bnFlipBit;
  9902. BigInteger$2.prototype.add = bnAdd;
  9903. BigInteger$2.prototype.subtract = bnSubtract;
  9904. BigInteger$2.prototype.multiply = bnMultiply;
  9905. BigInteger$2.prototype.divide = bnDivide;
  9906. BigInteger$2.prototype.remainder = bnRemainder;
  9907. BigInteger$2.prototype.divideAndRemainder = bnDivideAndRemainder;
  9908. BigInteger$2.prototype.modPow = bnModPow;
  9909. BigInteger$2.prototype.modInverse = bnModInverse;
  9910. BigInteger$2.prototype.pow = bnPow;
  9911. BigInteger$2.prototype.gcd = bnGCD;
  9912. BigInteger$2.prototype.isProbablePrime = bnIsProbablePrime;
  9913. /**
  9914. * Secure Hash Algorithm with 160-bit digest (SHA-1) implementation.
  9915. *
  9916. * @author Dave Longley
  9917. *
  9918. * Copyright (c) 2010-2015 Digital Bazaar, Inc.
  9919. */
  9920. var forge$n = forge$F;
  9921. var sha1 = forge$n.sha1 = forge$n.sha1 || {};
  9922. forge$n.md.sha1 = forge$n.md.algorithms.sha1 = sha1;
  9923. /**
  9924. * Creates a SHA-1 message digest object.
  9925. *
  9926. * @return a message digest object.
  9927. */
  9928. sha1.create = function() {
  9929. // do initialization as necessary
  9930. if(!_initialized$1) {
  9931. _init$1();
  9932. }
  9933. // SHA-1 state contains five 32-bit integers
  9934. var _state = null;
  9935. // input buffer
  9936. var _input = forge$n.util.createBuffer();
  9937. // used for word storage
  9938. var _w = new Array(80);
  9939. // message digest object
  9940. var md = {
  9941. algorithm: 'sha1',
  9942. blockLength: 64,
  9943. digestLength: 20,
  9944. // 56-bit length of message so far (does not including padding)
  9945. messageLength: 0,
  9946. // true message length
  9947. fullMessageLength: null,
  9948. // size of message length in bytes
  9949. messageLengthSize: 8
  9950. };
  9951. /**
  9952. * Starts the digest.
  9953. *
  9954. * @return this digest object.
  9955. */
  9956. md.start = function() {
  9957. // up to 56-bit message length for convenience
  9958. md.messageLength = 0;
  9959. // full message length (set md.messageLength64 for backwards-compatibility)
  9960. md.fullMessageLength = md.messageLength64 = [];
  9961. var int32s = md.messageLengthSize / 4;
  9962. for(var i = 0; i < int32s; ++i) {
  9963. md.fullMessageLength.push(0);
  9964. }
  9965. _input = forge$n.util.createBuffer();
  9966. _state = {
  9967. h0: 0x67452301,
  9968. h1: 0xEFCDAB89,
  9969. h2: 0x98BADCFE,
  9970. h3: 0x10325476,
  9971. h4: 0xC3D2E1F0
  9972. };
  9973. return md;
  9974. };
  9975. // start digest automatically for first time
  9976. md.start();
  9977. /**
  9978. * Updates the digest with the given message input. The given input can
  9979. * treated as raw input (no encoding will be applied) or an encoding of
  9980. * 'utf8' maybe given to encode the input using UTF-8.
  9981. *
  9982. * @param msg the message input to update with.
  9983. * @param encoding the encoding to use (default: 'raw', other: 'utf8').
  9984. *
  9985. * @return this digest object.
  9986. */
  9987. md.update = function(msg, encoding) {
  9988. if(encoding === 'utf8') {
  9989. msg = forge$n.util.encodeUtf8(msg);
  9990. }
  9991. // update message length
  9992. var len = msg.length;
  9993. md.messageLength += len;
  9994. len = [(len / 0x100000000) >>> 0, len >>> 0];
  9995. for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {
  9996. md.fullMessageLength[i] += len[1];
  9997. len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);
  9998. md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;
  9999. len[0] = ((len[1] / 0x100000000) >>> 0);
  10000. }
  10001. // add bytes to input buffer
  10002. _input.putBytes(msg);
  10003. // process bytes
  10004. _update$1(_state, _w, _input);
  10005. // compact input buffer every 2K or if empty
  10006. if(_input.read > 2048 || _input.length() === 0) {
  10007. _input.compact();
  10008. }
  10009. return md;
  10010. };
  10011. /**
  10012. * Produces the digest.
  10013. *
  10014. * @return a byte buffer containing the digest value.
  10015. */
  10016. md.digest = function() {
  10017. /* Note: Here we copy the remaining bytes in the input buffer and
  10018. add the appropriate SHA-1 padding. Then we do the final update
  10019. on a copy of the state so that if the user wants to get
  10020. intermediate digests they can do so. */
  10021. /* Determine the number of bytes that must be added to the message
  10022. to ensure its length is congruent to 448 mod 512. In other words,
  10023. the data to be digested must be a multiple of 512 bits (or 128 bytes).
  10024. This data includes the message, some padding, and the length of the
  10025. message. Since the length of the message will be encoded as 8 bytes (64
  10026. bits), that means that the last segment of the data must have 56 bytes
  10027. (448 bits) of message and padding. Therefore, the length of the message
  10028. plus the padding must be congruent to 448 mod 512 because
  10029. 512 - 128 = 448.
  10030. In order to fill up the message length it must be filled with
  10031. padding that begins with 1 bit followed by all 0 bits. Padding
  10032. must *always* be present, so if the message length is already
  10033. congruent to 448 mod 512, then 512 padding bits must be added. */
  10034. var finalBlock = forge$n.util.createBuffer();
  10035. finalBlock.putBytes(_input.bytes());
  10036. // compute remaining size to be digested (include message length size)
  10037. var remaining = (
  10038. md.fullMessageLength[md.fullMessageLength.length - 1] +
  10039. md.messageLengthSize);
  10040. // add padding for overflow blockSize - overflow
  10041. // _padding starts with 1 byte with first bit is set (byte value 128), then
  10042. // there may be up to (blockSize - 1) other pad bytes
  10043. var overflow = remaining & (md.blockLength - 1);
  10044. finalBlock.putBytes(_padding$1.substr(0, md.blockLength - overflow));
  10045. // serialize message length in bits in big-endian order; since length
  10046. // is stored in bytes we multiply by 8 and add carry from next int
  10047. var next, carry;
  10048. var bits = md.fullMessageLength[0] * 8;
  10049. for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {
  10050. next = md.fullMessageLength[i + 1] * 8;
  10051. carry = (next / 0x100000000) >>> 0;
  10052. bits += carry;
  10053. finalBlock.putInt32(bits >>> 0);
  10054. bits = next >>> 0;
  10055. }
  10056. finalBlock.putInt32(bits);
  10057. var s2 = {
  10058. h0: _state.h0,
  10059. h1: _state.h1,
  10060. h2: _state.h2,
  10061. h3: _state.h3,
  10062. h4: _state.h4
  10063. };
  10064. _update$1(s2, _w, finalBlock);
  10065. var rval = forge$n.util.createBuffer();
  10066. rval.putInt32(s2.h0);
  10067. rval.putInt32(s2.h1);
  10068. rval.putInt32(s2.h2);
  10069. rval.putInt32(s2.h3);
  10070. rval.putInt32(s2.h4);
  10071. return rval;
  10072. };
  10073. return md;
  10074. };
  10075. // sha-1 padding bytes not initialized yet
  10076. var _padding$1 = null;
  10077. var _initialized$1 = false;
  10078. /**
  10079. * Initializes the constant tables.
  10080. */
  10081. function _init$1() {
  10082. // create padding
  10083. _padding$1 = String.fromCharCode(128);
  10084. _padding$1 += forge$n.util.fillString(String.fromCharCode(0x00), 64);
  10085. // now initialized
  10086. _initialized$1 = true;
  10087. }
  10088. /**
  10089. * Updates a SHA-1 state with the given byte buffer.
  10090. *
  10091. * @param s the SHA-1 state to update.
  10092. * @param w the array to use to store words.
  10093. * @param bytes the byte buffer to update with.
  10094. */
  10095. function _update$1(s, w, bytes) {
  10096. // consume 512 bit (64 byte) chunks
  10097. var t, a, b, c, d, e, f, i;
  10098. var len = bytes.length();
  10099. while(len >= 64) {
  10100. // the w array will be populated with sixteen 32-bit big-endian words
  10101. // and then extended into 80 32-bit words according to SHA-1 algorithm
  10102. // and for 32-79 using Max Locktyukhin's optimization
  10103. // initialize hash value for this chunk
  10104. a = s.h0;
  10105. b = s.h1;
  10106. c = s.h2;
  10107. d = s.h3;
  10108. e = s.h4;
  10109. // round 1
  10110. for(i = 0; i < 16; ++i) {
  10111. t = bytes.getInt32();
  10112. w[i] = t;
  10113. f = d ^ (b & (c ^ d));
  10114. t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;
  10115. e = d;
  10116. d = c;
  10117. // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug
  10118. c = ((b << 30) | (b >>> 2)) >>> 0;
  10119. b = a;
  10120. a = t;
  10121. }
  10122. for(; i < 20; ++i) {
  10123. t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);
  10124. t = (t << 1) | (t >>> 31);
  10125. w[i] = t;
  10126. f = d ^ (b & (c ^ d));
  10127. t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;
  10128. e = d;
  10129. d = c;
  10130. // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug
  10131. c = ((b << 30) | (b >>> 2)) >>> 0;
  10132. b = a;
  10133. a = t;
  10134. }
  10135. // round 2
  10136. for(; i < 32; ++i) {
  10137. t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);
  10138. t = (t << 1) | (t >>> 31);
  10139. w[i] = t;
  10140. f = b ^ c ^ d;
  10141. t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;
  10142. e = d;
  10143. d = c;
  10144. // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug
  10145. c = ((b << 30) | (b >>> 2)) >>> 0;
  10146. b = a;
  10147. a = t;
  10148. }
  10149. for(; i < 40; ++i) {
  10150. t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);
  10151. t = (t << 2) | (t >>> 30);
  10152. w[i] = t;
  10153. f = b ^ c ^ d;
  10154. t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;
  10155. e = d;
  10156. d = c;
  10157. // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug
  10158. c = ((b << 30) | (b >>> 2)) >>> 0;
  10159. b = a;
  10160. a = t;
  10161. }
  10162. // round 3
  10163. for(; i < 60; ++i) {
  10164. t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);
  10165. t = (t << 2) | (t >>> 30);
  10166. w[i] = t;
  10167. f = (b & c) | (d & (b ^ c));
  10168. t = ((a << 5) | (a >>> 27)) + f + e + 0x8F1BBCDC + t;
  10169. e = d;
  10170. d = c;
  10171. // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug
  10172. c = ((b << 30) | (b >>> 2)) >>> 0;
  10173. b = a;
  10174. a = t;
  10175. }
  10176. // round 4
  10177. for(; i < 80; ++i) {
  10178. t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);
  10179. t = (t << 2) | (t >>> 30);
  10180. w[i] = t;
  10181. f = b ^ c ^ d;
  10182. t = ((a << 5) | (a >>> 27)) + f + e + 0xCA62C1D6 + t;
  10183. e = d;
  10184. d = c;
  10185. // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug
  10186. c = ((b << 30) | (b >>> 2)) >>> 0;
  10187. b = a;
  10188. a = t;
  10189. }
  10190. // update hash state
  10191. s.h0 = (s.h0 + a) | 0;
  10192. s.h1 = (s.h1 + b) | 0;
  10193. s.h2 = (s.h2 + c) | 0;
  10194. s.h3 = (s.h3 + d) | 0;
  10195. s.h4 = (s.h4 + e) | 0;
  10196. len -= 64;
  10197. }
  10198. }
  10199. /**
  10200. * Partial implementation of PKCS#1 v2.2: RSA-OEAP
  10201. *
  10202. * Modified but based on the following MIT and BSD licensed code:
  10203. *
  10204. * https://github.com/kjur/jsjws/blob/master/rsa.js:
  10205. *
  10206. * The 'jsjws'(JSON Web Signature JavaScript Library) License
  10207. *
  10208. * Copyright (c) 2012 Kenji Urushima
  10209. *
  10210. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10211. * of this software and associated documentation files (the "Software"), to deal
  10212. * in the Software without restriction, including without limitation the rights
  10213. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10214. * copies of the Software, and to permit persons to whom the Software is
  10215. * furnished to do so, subject to the following conditions:
  10216. *
  10217. * The above copyright notice and this permission notice shall be included in
  10218. * all copies or substantial portions of the Software.
  10219. *
  10220. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  10221. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  10222. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  10223. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  10224. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  10225. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  10226. * THE SOFTWARE.
  10227. *
  10228. * http://webrsa.cvs.sourceforge.net/viewvc/webrsa/Client/RSAES-OAEP.js?content-type=text%2Fplain:
  10229. *
  10230. * RSAES-OAEP.js
  10231. * $Id: RSAES-OAEP.js,v 1.1.1.1 2003/03/19 15:37:20 ellispritchard Exp $
  10232. * JavaScript Implementation of PKCS #1 v2.1 RSA CRYPTOGRAPHY STANDARD (RSA Laboratories, June 14, 2002)
  10233. * Copyright (C) Ellis Pritchard, Guardian Unlimited 2003.
  10234. * Contact: ellis@nukinetics.com
  10235. * Distributed under the BSD License.
  10236. *
  10237. * Official documentation: http://www.rsa.com/rsalabs/node.asp?id=2125
  10238. *
  10239. * @author Evan Jones (http://evanjones.ca/)
  10240. * @author Dave Longley
  10241. *
  10242. * Copyright (c) 2013-2014 Digital Bazaar, Inc.
  10243. */
  10244. var forge$m = forge$F;
  10245. // shortcut for PKCS#1 API
  10246. var pkcs1 = forge$m.pkcs1 = forge$m.pkcs1 || {};
  10247. /**
  10248. * Encode the given RSAES-OAEP message (M) using key, with optional label (L)
  10249. * and seed.
  10250. *
  10251. * This method does not perform RSA encryption, it only encodes the message
  10252. * using RSAES-OAEP.
  10253. *
  10254. * @param key the RSA key to use.
  10255. * @param message the message to encode.
  10256. * @param options the options to use:
  10257. * label an optional label to use.
  10258. * seed the seed to use.
  10259. * md the message digest object to use, undefined for SHA-1.
  10260. * mgf1 optional mgf1 parameters:
  10261. * md the message digest object to use for MGF1.
  10262. *
  10263. * @return the encoded message bytes.
  10264. */
  10265. pkcs1.encode_rsa_oaep = function(key, message, options) {
  10266. // parse arguments
  10267. var label;
  10268. var seed;
  10269. var md;
  10270. var mgf1Md;
  10271. // legacy args (label, seed, md)
  10272. if(typeof options === 'string') {
  10273. label = options;
  10274. seed = arguments[3] || undefined;
  10275. md = arguments[4] || undefined;
  10276. } else if(options) {
  10277. label = options.label || undefined;
  10278. seed = options.seed || undefined;
  10279. md = options.md || undefined;
  10280. if(options.mgf1 && options.mgf1.md) {
  10281. mgf1Md = options.mgf1.md;
  10282. }
  10283. }
  10284. // default OAEP to SHA-1 message digest
  10285. if(!md) {
  10286. md = forge$m.md.sha1.create();
  10287. } else {
  10288. md.start();
  10289. }
  10290. // default MGF-1 to same as OAEP
  10291. if(!mgf1Md) {
  10292. mgf1Md = md;
  10293. }
  10294. // compute length in bytes and check output
  10295. var keyLength = Math.ceil(key.n.bitLength() / 8);
  10296. var maxLength = keyLength - 2 * md.digestLength - 2;
  10297. if(message.length > maxLength) {
  10298. var error = new Error('RSAES-OAEP input message length is too long.');
  10299. error.length = message.length;
  10300. error.maxLength = maxLength;
  10301. throw error;
  10302. }
  10303. if(!label) {
  10304. label = '';
  10305. }
  10306. md.update(label, 'raw');
  10307. var lHash = md.digest();
  10308. var PS = '';
  10309. var PS_length = maxLength - message.length;
  10310. for(var i = 0; i < PS_length; i++) {
  10311. PS += '\x00';
  10312. }
  10313. var DB = lHash.getBytes() + PS + '\x01' + message;
  10314. if(!seed) {
  10315. seed = forge$m.random.getBytes(md.digestLength);
  10316. } else if(seed.length !== md.digestLength) {
  10317. var error = new Error('Invalid RSAES-OAEP seed. The seed length must ' +
  10318. 'match the digest length.');
  10319. error.seedLength = seed.length;
  10320. error.digestLength = md.digestLength;
  10321. throw error;
  10322. }
  10323. var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);
  10324. var maskedDB = forge$m.util.xorBytes(DB, dbMask, DB.length);
  10325. var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);
  10326. var maskedSeed = forge$m.util.xorBytes(seed, seedMask, seed.length);
  10327. // return encoded message
  10328. return '\x00' + maskedSeed + maskedDB;
  10329. };
  10330. /**
  10331. * Decode the given RSAES-OAEP encoded message (EM) using key, with optional
  10332. * label (L).
  10333. *
  10334. * This method does not perform RSA decryption, it only decodes the message
  10335. * using RSAES-OAEP.
  10336. *
  10337. * @param key the RSA key to use.
  10338. * @param em the encoded message to decode.
  10339. * @param options the options to use:
  10340. * label an optional label to use.
  10341. * md the message digest object to use for OAEP, undefined for SHA-1.
  10342. * mgf1 optional mgf1 parameters:
  10343. * md the message digest object to use for MGF1.
  10344. *
  10345. * @return the decoded message bytes.
  10346. */
  10347. pkcs1.decode_rsa_oaep = function(key, em, options) {
  10348. // parse args
  10349. var label;
  10350. var md;
  10351. var mgf1Md;
  10352. // legacy args
  10353. if(typeof options === 'string') {
  10354. label = options;
  10355. md = arguments[3] || undefined;
  10356. } else if(options) {
  10357. label = options.label || undefined;
  10358. md = options.md || undefined;
  10359. if(options.mgf1 && options.mgf1.md) {
  10360. mgf1Md = options.mgf1.md;
  10361. }
  10362. }
  10363. // compute length in bytes
  10364. var keyLength = Math.ceil(key.n.bitLength() / 8);
  10365. if(em.length !== keyLength) {
  10366. var error = new Error('RSAES-OAEP encoded message length is invalid.');
  10367. error.length = em.length;
  10368. error.expectedLength = keyLength;
  10369. throw error;
  10370. }
  10371. // default OAEP to SHA-1 message digest
  10372. if(md === undefined) {
  10373. md = forge$m.md.sha1.create();
  10374. } else {
  10375. md.start();
  10376. }
  10377. // default MGF-1 to same as OAEP
  10378. if(!mgf1Md) {
  10379. mgf1Md = md;
  10380. }
  10381. if(keyLength < 2 * md.digestLength + 2) {
  10382. throw new Error('RSAES-OAEP key is too short for the hash function.');
  10383. }
  10384. if(!label) {
  10385. label = '';
  10386. }
  10387. md.update(label, 'raw');
  10388. var lHash = md.digest().getBytes();
  10389. // split the message into its parts
  10390. var y = em.charAt(0);
  10391. var maskedSeed = em.substring(1, md.digestLength + 1);
  10392. var maskedDB = em.substring(1 + md.digestLength);
  10393. var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);
  10394. var seed = forge$m.util.xorBytes(maskedSeed, seedMask, maskedSeed.length);
  10395. var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);
  10396. var db = forge$m.util.xorBytes(maskedDB, dbMask, maskedDB.length);
  10397. var lHashPrime = db.substring(0, md.digestLength);
  10398. // constant time check that all values match what is expected
  10399. var error = (y !== '\x00');
  10400. // constant time check lHash vs lHashPrime
  10401. for(var i = 0; i < md.digestLength; ++i) {
  10402. error |= (lHash.charAt(i) !== lHashPrime.charAt(i));
  10403. }
  10404. // "constant time" find the 0x1 byte separating the padding (zeros) from the
  10405. // message
  10406. // TODO: It must be possible to do this in a better/smarter way?
  10407. var in_ps = 1;
  10408. var index = md.digestLength;
  10409. for(var j = md.digestLength; j < db.length; j++) {
  10410. var code = db.charCodeAt(j);
  10411. var is_0 = (code & 0x1) ^ 0x1;
  10412. // non-zero if not 0 or 1 in the ps section
  10413. var error_mask = in_ps ? 0xfffe : 0x0000;
  10414. error |= (code & error_mask);
  10415. // latch in_ps to zero after we find 0x1
  10416. in_ps = in_ps & is_0;
  10417. index += in_ps;
  10418. }
  10419. if(error || db.charCodeAt(index) !== 0x1) {
  10420. throw new Error('Invalid RSAES-OAEP padding.');
  10421. }
  10422. return db.substring(index + 1);
  10423. };
  10424. function rsa_mgf1(seed, maskLength, hash) {
  10425. // default to SHA-1 message digest
  10426. if(!hash) {
  10427. hash = forge$m.md.sha1.create();
  10428. }
  10429. var t = '';
  10430. var count = Math.ceil(maskLength / hash.digestLength);
  10431. for(var i = 0; i < count; ++i) {
  10432. var c = String.fromCharCode(
  10433. (i >> 24) & 0xFF, (i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF);
  10434. hash.start();
  10435. hash.update(seed + c);
  10436. t += hash.digest().getBytes();
  10437. }
  10438. return t.substring(0, maskLength);
  10439. }
  10440. /**
  10441. * Prime number generation API.
  10442. *
  10443. * @author Dave Longley
  10444. *
  10445. * Copyright (c) 2014 Digital Bazaar, Inc.
  10446. */
  10447. var forge$l = forge$F;
  10448. (function() {
  10449. // forge.prime already defined
  10450. if(forge$l.prime) {
  10451. return;
  10452. }
  10453. /* PRIME API */
  10454. var prime = forge$l.prime = forge$l.prime || {};
  10455. var BigInteger = forge$l.jsbn.BigInteger;
  10456. // primes are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29
  10457. var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];
  10458. var THIRTY = new BigInteger(null);
  10459. THIRTY.fromInt(30);
  10460. var op_or = function(x, y) {return x|y;};
  10461. /**
  10462. * Generates a random probable prime with the given number of bits.
  10463. *
  10464. * Alternative algorithms can be specified by name as a string or as an
  10465. * object with custom options like so:
  10466. *
  10467. * {
  10468. * name: 'PRIMEINC',
  10469. * options: {
  10470. * maxBlockTime: <the maximum amount of time to block the main
  10471. * thread before allowing I/O other JS to run>,
  10472. * millerRabinTests: <the number of miller-rabin tests to run>,
  10473. * workerScript: <the worker script URL>,
  10474. * workers: <the number of web workers (if supported) to use,
  10475. * -1 to use estimated cores minus one>.
  10476. * workLoad: the size of the work load, ie: number of possible prime
  10477. * numbers for each web worker to check per work assignment,
  10478. * (default: 100).
  10479. * }
  10480. * }
  10481. *
  10482. * @param bits the number of bits for the prime number.
  10483. * @param options the options to use.
  10484. * [algorithm] the algorithm to use (default: 'PRIMEINC').
  10485. * [prng] a custom crypto-secure pseudo-random number generator to use,
  10486. * that must define "getBytesSync".
  10487. *
  10488. * @return callback(err, num) called once the operation completes.
  10489. */
  10490. prime.generateProbablePrime = function(bits, options, callback) {
  10491. if(typeof options === 'function') {
  10492. callback = options;
  10493. options = {};
  10494. }
  10495. options = options || {};
  10496. // default to PRIMEINC algorithm
  10497. var algorithm = options.algorithm || 'PRIMEINC';
  10498. if(typeof algorithm === 'string') {
  10499. algorithm = {name: algorithm};
  10500. }
  10501. algorithm.options = algorithm.options || {};
  10502. // create prng with api that matches BigInteger secure random
  10503. var prng = options.prng || forge$l.random;
  10504. var rng = {
  10505. // x is an array to fill with bytes
  10506. nextBytes: function(x) {
  10507. var b = prng.getBytesSync(x.length);
  10508. for(var i = 0; i < x.length; ++i) {
  10509. x[i] = b.charCodeAt(i);
  10510. }
  10511. }
  10512. };
  10513. if(algorithm.name === 'PRIMEINC') {
  10514. return primeincFindPrime(bits, rng, algorithm.options, callback);
  10515. }
  10516. throw new Error('Invalid prime generation algorithm: ' + algorithm.name);
  10517. };
  10518. function primeincFindPrime(bits, rng, options, callback) {
  10519. if('workers' in options) {
  10520. return primeincFindPrimeWithWorkers(bits, rng, options, callback);
  10521. }
  10522. return primeincFindPrimeWithoutWorkers(bits, rng, options, callback);
  10523. }
  10524. function primeincFindPrimeWithoutWorkers(bits, rng, options, callback) {
  10525. // initialize random number
  10526. var num = generateRandom(bits, rng);
  10527. /* Note: All primes are of the form 30k+i for i < 30 and gcd(30, i)=1. The
  10528. number we are given is always aligned at 30k + 1. Each time the number is
  10529. determined not to be prime we add to get to the next 'i', eg: if the number
  10530. was at 30k + 1 we add 6. */
  10531. var deltaIdx = 0;
  10532. // get required number of MR tests
  10533. var mrTests = getMillerRabinTests(num.bitLength());
  10534. if('millerRabinTests' in options) {
  10535. mrTests = options.millerRabinTests;
  10536. }
  10537. // find prime nearest to 'num' for maxBlockTime ms
  10538. // 10 ms gives 5ms of leeway for other calculations before dropping
  10539. // below 60fps (1000/60 == 16.67), but in reality, the number will
  10540. // likely be higher due to an 'atomic' big int modPow
  10541. var maxBlockTime = 10;
  10542. if('maxBlockTime' in options) {
  10543. maxBlockTime = options.maxBlockTime;
  10544. }
  10545. _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);
  10546. }
  10547. function _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) {
  10548. var start = +new Date();
  10549. do {
  10550. // overflow, regenerate random number
  10551. if(num.bitLength() > bits) {
  10552. num = generateRandom(bits, rng);
  10553. }
  10554. // do primality test
  10555. if(num.isProbablePrime(mrTests)) {
  10556. return callback(null, num);
  10557. }
  10558. // get next potential prime
  10559. num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);
  10560. } while(maxBlockTime < 0 || (+new Date() - start < maxBlockTime));
  10561. // keep trying later
  10562. forge$l.util.setImmediate(function() {
  10563. _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);
  10564. });
  10565. }
  10566. // NOTE: This algorithm is indeterminate in nature because workers
  10567. // run in parallel looking at different segments of numbers. Even if this
  10568. // algorithm is run twice with the same input from a predictable RNG, it
  10569. // may produce different outputs.
  10570. function primeincFindPrimeWithWorkers(bits, rng, options, callback) {
  10571. // web workers unavailable
  10572. if(typeof Worker === 'undefined') {
  10573. return primeincFindPrimeWithoutWorkers(bits, rng, options, callback);
  10574. }
  10575. // initialize random number
  10576. var num = generateRandom(bits, rng);
  10577. // use web workers to generate keys
  10578. var numWorkers = options.workers;
  10579. var workLoad = options.workLoad || 100;
  10580. var range = workLoad * 30 / 8;
  10581. var workerScript = options.workerScript || 'forge/prime.worker.js';
  10582. if(numWorkers === -1) {
  10583. return forge$l.util.estimateCores(function(err, cores) {
  10584. if(err) {
  10585. // default to 2
  10586. cores = 2;
  10587. }
  10588. numWorkers = cores - 1;
  10589. generate();
  10590. });
  10591. }
  10592. generate();
  10593. function generate() {
  10594. // require at least 1 worker
  10595. numWorkers = Math.max(1, numWorkers);
  10596. // TODO: consider optimizing by starting workers outside getPrime() ...
  10597. // note that in order to clean up they will have to be made internally
  10598. // asynchronous which may actually be slower
  10599. // start workers immediately
  10600. var workers = [];
  10601. for(var i = 0; i < numWorkers; ++i) {
  10602. // FIXME: fix path or use blob URLs
  10603. workers[i] = new Worker(workerScript);
  10604. }
  10605. // listen for requests from workers and assign ranges to find prime
  10606. for(var i = 0; i < numWorkers; ++i) {
  10607. workers[i].addEventListener('message', workerMessage);
  10608. }
  10609. /* Note: The distribution of random numbers is unknown. Therefore, each
  10610. web worker is continuously allocated a range of numbers to check for a
  10611. random number until one is found.
  10612. Every 30 numbers will be checked just 8 times, because prime numbers
  10613. have the form:
  10614. 30k+i, for i < 30 and gcd(30, i)=1 (there are 8 values of i for this)
  10615. Therefore, if we want a web worker to run N checks before asking for
  10616. a new range of numbers, each range must contain N*30/8 numbers.
  10617. For 100 checks (workLoad), this is a range of 375. */
  10618. var found = false;
  10619. function workerMessage(e) {
  10620. // ignore message, prime already found
  10621. if(found) {
  10622. return;
  10623. }
  10624. var data = e.data;
  10625. if(data.found) {
  10626. // terminate all workers
  10627. for(var i = 0; i < workers.length; ++i) {
  10628. workers[i].terminate();
  10629. }
  10630. found = true;
  10631. return callback(null, new BigInteger(data.prime, 16));
  10632. }
  10633. // overflow, regenerate random number
  10634. if(num.bitLength() > bits) {
  10635. num = generateRandom(bits, rng);
  10636. }
  10637. // assign new range to check
  10638. var hex = num.toString(16);
  10639. // start prime search
  10640. e.target.postMessage({
  10641. hex: hex,
  10642. workLoad: workLoad
  10643. });
  10644. num.dAddOffset(range, 0);
  10645. }
  10646. }
  10647. }
  10648. /**
  10649. * Generates a random number using the given number of bits and RNG.
  10650. *
  10651. * @param bits the number of bits for the number.
  10652. * @param rng the random number generator to use.
  10653. *
  10654. * @return the random number.
  10655. */
  10656. function generateRandom(bits, rng) {
  10657. var num = new BigInteger(bits, rng);
  10658. // force MSB set
  10659. var bits1 = bits - 1;
  10660. if(!num.testBit(bits1)) {
  10661. num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num);
  10662. }
  10663. // align number on 30k+1 boundary
  10664. num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0);
  10665. return num;
  10666. }
  10667. /**
  10668. * Returns the required number of Miller-Rabin tests to generate a
  10669. * prime with an error probability of (1/2)^80.
  10670. *
  10671. * See Handbook of Applied Cryptography Chapter 4, Table 4.4.
  10672. *
  10673. * @param bits the bit size.
  10674. *
  10675. * @return the required number of iterations.
  10676. */
  10677. function getMillerRabinTests(bits) {
  10678. if(bits <= 100) return 27;
  10679. if(bits <= 150) return 18;
  10680. if(bits <= 200) return 15;
  10681. if(bits <= 250) return 12;
  10682. if(bits <= 300) return 9;
  10683. if(bits <= 350) return 8;
  10684. if(bits <= 400) return 7;
  10685. if(bits <= 500) return 6;
  10686. if(bits <= 600) return 5;
  10687. if(bits <= 800) return 4;
  10688. if(bits <= 1250) return 3;
  10689. return 2;
  10690. }
  10691. })();
  10692. /**
  10693. * Javascript implementation of basic RSA algorithms.
  10694. *
  10695. * @author Dave Longley
  10696. *
  10697. * Copyright (c) 2010-2014 Digital Bazaar, Inc.
  10698. *
  10699. * The only algorithm currently supported for PKI is RSA.
  10700. *
  10701. * An RSA key is often stored in ASN.1 DER format. The SubjectPublicKeyInfo
  10702. * ASN.1 structure is composed of an algorithm of type AlgorithmIdentifier
  10703. * and a subjectPublicKey of type bit string.
  10704. *
  10705. * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters
  10706. * for the algorithm, if any. In the case of RSA, there aren't any.
  10707. *
  10708. * SubjectPublicKeyInfo ::= SEQUENCE {
  10709. * algorithm AlgorithmIdentifier,
  10710. * subjectPublicKey BIT STRING
  10711. * }
  10712. *
  10713. * AlgorithmIdentifer ::= SEQUENCE {
  10714. * algorithm OBJECT IDENTIFIER,
  10715. * parameters ANY DEFINED BY algorithm OPTIONAL
  10716. * }
  10717. *
  10718. * For an RSA public key, the subjectPublicKey is:
  10719. *
  10720. * RSAPublicKey ::= SEQUENCE {
  10721. * modulus INTEGER, -- n
  10722. * publicExponent INTEGER -- e
  10723. * }
  10724. *
  10725. * PrivateKeyInfo ::= SEQUENCE {
  10726. * version Version,
  10727. * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
  10728. * privateKey PrivateKey,
  10729. * attributes [0] IMPLICIT Attributes OPTIONAL
  10730. * }
  10731. *
  10732. * Version ::= INTEGER
  10733. * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
  10734. * PrivateKey ::= OCTET STRING
  10735. * Attributes ::= SET OF Attribute
  10736. *
  10737. * An RSA private key as the following structure:
  10738. *
  10739. * RSAPrivateKey ::= SEQUENCE {
  10740. * version Version,
  10741. * modulus INTEGER, -- n
  10742. * publicExponent INTEGER, -- e
  10743. * privateExponent INTEGER, -- d
  10744. * prime1 INTEGER, -- p
  10745. * prime2 INTEGER, -- q
  10746. * exponent1 INTEGER, -- d mod (p-1)
  10747. * exponent2 INTEGER, -- d mod (q-1)
  10748. * coefficient INTEGER -- (inverse of q) mod p
  10749. * }
  10750. *
  10751. * Version ::= INTEGER
  10752. *
  10753. * The OID for the RSA key algorithm is: 1.2.840.113549.1.1.1
  10754. */
  10755. var forge$k = forge$F;
  10756. if(typeof BigInteger$1 === 'undefined') {
  10757. var BigInteger$1 = forge$k.jsbn.BigInteger;
  10758. }
  10759. var _crypto = forge$k.util.isNodejs ? require$$1__default : null;
  10760. // shortcut for asn.1 API
  10761. var asn1$7 = forge$k.asn1;
  10762. // shortcut for util API
  10763. var util = forge$k.util;
  10764. /*
  10765. * RSA encryption and decryption, see RFC 2313.
  10766. */
  10767. forge$k.pki = forge$k.pki || {};
  10768. forge$k.pki.rsa = forge$k.rsa = forge$k.rsa || {};
  10769. var pki$4 = forge$k.pki;
  10770. // for finding primes, which are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29
  10771. var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];
  10772. // validator for a PrivateKeyInfo structure
  10773. var privateKeyValidator$1 = {
  10774. // PrivateKeyInfo
  10775. name: 'PrivateKeyInfo',
  10776. tagClass: asn1$7.Class.UNIVERSAL,
  10777. type: asn1$7.Type.SEQUENCE,
  10778. constructed: true,
  10779. value: [{
  10780. // Version (INTEGER)
  10781. name: 'PrivateKeyInfo.version',
  10782. tagClass: asn1$7.Class.UNIVERSAL,
  10783. type: asn1$7.Type.INTEGER,
  10784. constructed: false,
  10785. capture: 'privateKeyVersion'
  10786. }, {
  10787. // privateKeyAlgorithm
  10788. name: 'PrivateKeyInfo.privateKeyAlgorithm',
  10789. tagClass: asn1$7.Class.UNIVERSAL,
  10790. type: asn1$7.Type.SEQUENCE,
  10791. constructed: true,
  10792. value: [{
  10793. name: 'AlgorithmIdentifier.algorithm',
  10794. tagClass: asn1$7.Class.UNIVERSAL,
  10795. type: asn1$7.Type.OID,
  10796. constructed: false,
  10797. capture: 'privateKeyOid'
  10798. }]
  10799. }, {
  10800. // PrivateKey
  10801. name: 'PrivateKeyInfo',
  10802. tagClass: asn1$7.Class.UNIVERSAL,
  10803. type: asn1$7.Type.OCTETSTRING,
  10804. constructed: false,
  10805. capture: 'privateKey'
  10806. }]
  10807. };
  10808. // validator for an RSA private key
  10809. var rsaPrivateKeyValidator = {
  10810. // RSAPrivateKey
  10811. name: 'RSAPrivateKey',
  10812. tagClass: asn1$7.Class.UNIVERSAL,
  10813. type: asn1$7.Type.SEQUENCE,
  10814. constructed: true,
  10815. value: [{
  10816. // Version (INTEGER)
  10817. name: 'RSAPrivateKey.version',
  10818. tagClass: asn1$7.Class.UNIVERSAL,
  10819. type: asn1$7.Type.INTEGER,
  10820. constructed: false,
  10821. capture: 'privateKeyVersion'
  10822. }, {
  10823. // modulus (n)
  10824. name: 'RSAPrivateKey.modulus',
  10825. tagClass: asn1$7.Class.UNIVERSAL,
  10826. type: asn1$7.Type.INTEGER,
  10827. constructed: false,
  10828. capture: 'privateKeyModulus'
  10829. }, {
  10830. // publicExponent (e)
  10831. name: 'RSAPrivateKey.publicExponent',
  10832. tagClass: asn1$7.Class.UNIVERSAL,
  10833. type: asn1$7.Type.INTEGER,
  10834. constructed: false,
  10835. capture: 'privateKeyPublicExponent'
  10836. }, {
  10837. // privateExponent (d)
  10838. name: 'RSAPrivateKey.privateExponent',
  10839. tagClass: asn1$7.Class.UNIVERSAL,
  10840. type: asn1$7.Type.INTEGER,
  10841. constructed: false,
  10842. capture: 'privateKeyPrivateExponent'
  10843. }, {
  10844. // prime1 (p)
  10845. name: 'RSAPrivateKey.prime1',
  10846. tagClass: asn1$7.Class.UNIVERSAL,
  10847. type: asn1$7.Type.INTEGER,
  10848. constructed: false,
  10849. capture: 'privateKeyPrime1'
  10850. }, {
  10851. // prime2 (q)
  10852. name: 'RSAPrivateKey.prime2',
  10853. tagClass: asn1$7.Class.UNIVERSAL,
  10854. type: asn1$7.Type.INTEGER,
  10855. constructed: false,
  10856. capture: 'privateKeyPrime2'
  10857. }, {
  10858. // exponent1 (d mod (p-1))
  10859. name: 'RSAPrivateKey.exponent1',
  10860. tagClass: asn1$7.Class.UNIVERSAL,
  10861. type: asn1$7.Type.INTEGER,
  10862. constructed: false,
  10863. capture: 'privateKeyExponent1'
  10864. }, {
  10865. // exponent2 (d mod (q-1))
  10866. name: 'RSAPrivateKey.exponent2',
  10867. tagClass: asn1$7.Class.UNIVERSAL,
  10868. type: asn1$7.Type.INTEGER,
  10869. constructed: false,
  10870. capture: 'privateKeyExponent2'
  10871. }, {
  10872. // coefficient ((inverse of q) mod p)
  10873. name: 'RSAPrivateKey.coefficient',
  10874. tagClass: asn1$7.Class.UNIVERSAL,
  10875. type: asn1$7.Type.INTEGER,
  10876. constructed: false,
  10877. capture: 'privateKeyCoefficient'
  10878. }]
  10879. };
  10880. // validator for an RSA public key
  10881. var rsaPublicKeyValidator = {
  10882. // RSAPublicKey
  10883. name: 'RSAPublicKey',
  10884. tagClass: asn1$7.Class.UNIVERSAL,
  10885. type: asn1$7.Type.SEQUENCE,
  10886. constructed: true,
  10887. value: [{
  10888. // modulus (n)
  10889. name: 'RSAPublicKey.modulus',
  10890. tagClass: asn1$7.Class.UNIVERSAL,
  10891. type: asn1$7.Type.INTEGER,
  10892. constructed: false,
  10893. capture: 'publicKeyModulus'
  10894. }, {
  10895. // publicExponent (e)
  10896. name: 'RSAPublicKey.exponent',
  10897. tagClass: asn1$7.Class.UNIVERSAL,
  10898. type: asn1$7.Type.INTEGER,
  10899. constructed: false,
  10900. capture: 'publicKeyExponent'
  10901. }]
  10902. };
  10903. // validator for an SubjectPublicKeyInfo structure
  10904. // Note: Currently only works with an RSA public key
  10905. var publicKeyValidator$2 = forge$k.pki.rsa.publicKeyValidator = {
  10906. name: 'SubjectPublicKeyInfo',
  10907. tagClass: asn1$7.Class.UNIVERSAL,
  10908. type: asn1$7.Type.SEQUENCE,
  10909. constructed: true,
  10910. captureAsn1: 'subjectPublicKeyInfo',
  10911. value: [{
  10912. name: 'SubjectPublicKeyInfo.AlgorithmIdentifier',
  10913. tagClass: asn1$7.Class.UNIVERSAL,
  10914. type: asn1$7.Type.SEQUENCE,
  10915. constructed: true,
  10916. value: [{
  10917. name: 'AlgorithmIdentifier.algorithm',
  10918. tagClass: asn1$7.Class.UNIVERSAL,
  10919. type: asn1$7.Type.OID,
  10920. constructed: false,
  10921. capture: 'publicKeyOid'
  10922. }]
  10923. }, {
  10924. // subjectPublicKey
  10925. name: 'SubjectPublicKeyInfo.subjectPublicKey',
  10926. tagClass: asn1$7.Class.UNIVERSAL,
  10927. type: asn1$7.Type.BITSTRING,
  10928. constructed: false,
  10929. value: [{
  10930. // RSAPublicKey
  10931. name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey',
  10932. tagClass: asn1$7.Class.UNIVERSAL,
  10933. type: asn1$7.Type.SEQUENCE,
  10934. constructed: true,
  10935. optional: true,
  10936. captureAsn1: 'rsaPublicKey'
  10937. }]
  10938. }]
  10939. };
  10940. /**
  10941. * Wrap digest in DigestInfo object.
  10942. *
  10943. * This function implements EMSA-PKCS1-v1_5-ENCODE as per RFC 3447.
  10944. *
  10945. * DigestInfo ::= SEQUENCE {
  10946. * digestAlgorithm DigestAlgorithmIdentifier,
  10947. * digest Digest
  10948. * }
  10949. *
  10950. * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
  10951. * Digest ::= OCTET STRING
  10952. *
  10953. * @param md the message digest object with the hash to sign.
  10954. *
  10955. * @return the encoded message (ready for RSA encrytion)
  10956. */
  10957. var emsaPkcs1v15encode = function(md) {
  10958. // get the oid for the algorithm
  10959. var oid;
  10960. if(md.algorithm in pki$4.oids) {
  10961. oid = pki$4.oids[md.algorithm];
  10962. } else {
  10963. var error = new Error('Unknown message digest algorithm.');
  10964. error.algorithm = md.algorithm;
  10965. throw error;
  10966. }
  10967. var oidBytes = asn1$7.oidToDer(oid).getBytes();
  10968. // create the digest info
  10969. var digestInfo = asn1$7.create(
  10970. asn1$7.Class.UNIVERSAL, asn1$7.Type.SEQUENCE, true, []);
  10971. var digestAlgorithm = asn1$7.create(
  10972. asn1$7.Class.UNIVERSAL, asn1$7.Type.SEQUENCE, true, []);
  10973. digestAlgorithm.value.push(asn1$7.create(
  10974. asn1$7.Class.UNIVERSAL, asn1$7.Type.OID, false, oidBytes));
  10975. digestAlgorithm.value.push(asn1$7.create(
  10976. asn1$7.Class.UNIVERSAL, asn1$7.Type.NULL, false, ''));
  10977. var digest = asn1$7.create(
  10978. asn1$7.Class.UNIVERSAL, asn1$7.Type.OCTETSTRING,
  10979. false, md.digest().getBytes());
  10980. digestInfo.value.push(digestAlgorithm);
  10981. digestInfo.value.push(digest);
  10982. // encode digest info
  10983. return asn1$7.toDer(digestInfo).getBytes();
  10984. };
  10985. /**
  10986. * Performs x^c mod n (RSA encryption or decryption operation).
  10987. *
  10988. * @param x the number to raise and mod.
  10989. * @param key the key to use.
  10990. * @param pub true if the key is public, false if private.
  10991. *
  10992. * @return the result of x^c mod n.
  10993. */
  10994. var _modPow = function(x, key, pub) {
  10995. if(pub) {
  10996. return x.modPow(key.e, key.n);
  10997. }
  10998. if(!key.p || !key.q) {
  10999. // allow calculation without CRT params (slow)
  11000. return x.modPow(key.d, key.n);
  11001. }
  11002. // pre-compute dP, dQ, and qInv if necessary
  11003. if(!key.dP) {
  11004. key.dP = key.d.mod(key.p.subtract(BigInteger$1.ONE));
  11005. }
  11006. if(!key.dQ) {
  11007. key.dQ = key.d.mod(key.q.subtract(BigInteger$1.ONE));
  11008. }
  11009. if(!key.qInv) {
  11010. key.qInv = key.q.modInverse(key.p);
  11011. }
  11012. /* Chinese remainder theorem (CRT) states:
  11013. Suppose n1, n2, ..., nk are positive integers which are pairwise
  11014. coprime (n1 and n2 have no common factors other than 1). For any
  11015. integers x1, x2, ..., xk there exists an integer x solving the
  11016. system of simultaneous congruences (where ~= means modularly
  11017. congruent so a ~= b mod n means a mod n = b mod n):
  11018. x ~= x1 mod n1
  11019. x ~= x2 mod n2
  11020. ...
  11021. x ~= xk mod nk
  11022. This system of congruences has a single simultaneous solution x
  11023. between 0 and n - 1. Furthermore, each xk solution and x itself
  11024. is congruent modulo the product n = n1*n2*...*nk.
  11025. So x1 mod n = x2 mod n = xk mod n = x mod n.
  11026. The single simultaneous solution x can be solved with the following
  11027. equation:
  11028. x = sum(xi*ri*si) mod n where ri = n/ni and si = ri^-1 mod ni.
  11029. Where x is less than n, xi = x mod ni.
  11030. For RSA we are only concerned with k = 2. The modulus n = pq, where
  11031. p and q are coprime. The RSA decryption algorithm is:
  11032. y = x^d mod n
  11033. Given the above:
  11034. x1 = x^d mod p
  11035. r1 = n/p = q
  11036. s1 = q^-1 mod p
  11037. x2 = x^d mod q
  11038. r2 = n/q = p
  11039. s2 = p^-1 mod q
  11040. So y = (x1r1s1 + x2r2s2) mod n
  11041. = ((x^d mod p)q(q^-1 mod p) + (x^d mod q)p(p^-1 mod q)) mod n
  11042. According to Fermat's Little Theorem, if the modulus P is prime,
  11043. for any integer A not evenly divisible by P, A^(P-1) ~= 1 mod P.
  11044. Since A is not divisible by P it follows that if:
  11045. N ~= M mod (P - 1), then A^N mod P = A^M mod P. Therefore:
  11046. A^N mod P = A^(M mod (P - 1)) mod P. (The latter takes less effort
  11047. to calculate). In order to calculate x^d mod p more quickly the
  11048. exponent d mod (p - 1) is stored in the RSA private key (the same
  11049. is done for x^d mod q). These values are referred to as dP and dQ
  11050. respectively. Therefore we now have:
  11051. y = ((x^dP mod p)q(q^-1 mod p) + (x^dQ mod q)p(p^-1 mod q)) mod n
  11052. Since we'll be reducing x^dP by modulo p (same for q) we can also
  11053. reduce x by p (and q respectively) before hand. Therefore, let
  11054. xp = ((x mod p)^dP mod p), and
  11055. xq = ((x mod q)^dQ mod q), yielding:
  11056. y = (xp*q*(q^-1 mod p) + xq*p*(p^-1 mod q)) mod n
  11057. This can be further reduced to a simple algorithm that only
  11058. requires 1 inverse (the q inverse is used) to be used and stored.
  11059. The algorithm is called Garner's algorithm. If qInv is the
  11060. inverse of q, we simply calculate:
  11061. y = (qInv*(xp - xq) mod p) * q + xq
  11062. However, there are two further complications. First, we need to
  11063. ensure that xp > xq to prevent signed BigIntegers from being used
  11064. so we add p until this is true (since we will be mod'ing with
  11065. p anyway). Then, there is a known timing attack on algorithms
  11066. using the CRT. To mitigate this risk, "cryptographic blinding"
  11067. should be used. This requires simply generating a random number r
  11068. between 0 and n-1 and its inverse and multiplying x by r^e before
  11069. calculating y and then multiplying y by r^-1 afterwards. Note that
  11070. r must be coprime with n (gcd(r, n) === 1) in order to have an
  11071. inverse.
  11072. */
  11073. // cryptographic blinding
  11074. var r;
  11075. do {
  11076. r = new BigInteger$1(
  11077. forge$k.util.bytesToHex(forge$k.random.getBytes(key.n.bitLength() / 8)),
  11078. 16);
  11079. } while(r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger$1.ONE));
  11080. x = x.multiply(r.modPow(key.e, key.n)).mod(key.n);
  11081. // calculate xp and xq
  11082. var xp = x.mod(key.p).modPow(key.dP, key.p);
  11083. var xq = x.mod(key.q).modPow(key.dQ, key.q);
  11084. // xp must be larger than xq to avoid signed bit usage
  11085. while(xp.compareTo(xq) < 0) {
  11086. xp = xp.add(key.p);
  11087. }
  11088. // do last step
  11089. var y = xp.subtract(xq)
  11090. .multiply(key.qInv).mod(key.p)
  11091. .multiply(key.q).add(xq);
  11092. // remove effect of random for cryptographic blinding
  11093. y = y.multiply(r.modInverse(key.n)).mod(key.n);
  11094. return y;
  11095. };
  11096. /**
  11097. * NOTE: THIS METHOD IS DEPRECATED, use 'sign' on a private key object or
  11098. * 'encrypt' on a public key object instead.
  11099. *
  11100. * Performs RSA encryption.
  11101. *
  11102. * The parameter bt controls whether to put padding bytes before the
  11103. * message passed in. Set bt to either true or false to disable padding
  11104. * completely (in order to handle e.g. EMSA-PSS encoding seperately before),
  11105. * signaling whether the encryption operation is a public key operation
  11106. * (i.e. encrypting data) or not, i.e. private key operation (data signing).
  11107. *
  11108. * For PKCS#1 v1.5 padding pass in the block type to use, i.e. either 0x01
  11109. * (for signing) or 0x02 (for encryption). The key operation mode (private
  11110. * or public) is derived from this flag in that case).
  11111. *
  11112. * @param m the message to encrypt as a byte string.
  11113. * @param key the RSA key to use.
  11114. * @param bt for PKCS#1 v1.5 padding, the block type to use
  11115. * (0x01 for private key, 0x02 for public),
  11116. * to disable padding: true = public key, false = private key.
  11117. *
  11118. * @return the encrypted bytes as a string.
  11119. */
  11120. pki$4.rsa.encrypt = function(m, key, bt) {
  11121. var pub = bt;
  11122. var eb;
  11123. // get the length of the modulus in bytes
  11124. var k = Math.ceil(key.n.bitLength() / 8);
  11125. if(bt !== false && bt !== true) {
  11126. // legacy, default to PKCS#1 v1.5 padding
  11127. pub = (bt === 0x02);
  11128. eb = _encodePkcs1_v1_5(m, key, bt);
  11129. } else {
  11130. eb = forge$k.util.createBuffer();
  11131. eb.putBytes(m);
  11132. }
  11133. // load encryption block as big integer 'x'
  11134. // FIXME: hex conversion inefficient, get BigInteger w/byte strings
  11135. var x = new BigInteger$1(eb.toHex(), 16);
  11136. // do RSA encryption
  11137. var y = _modPow(x, key, pub);
  11138. // convert y into the encrypted data byte string, if y is shorter in
  11139. // bytes than k, then prepend zero bytes to fill up ed
  11140. // FIXME: hex conversion inefficient, get BigInteger w/byte strings
  11141. var yhex = y.toString(16);
  11142. var ed = forge$k.util.createBuffer();
  11143. var zeros = k - Math.ceil(yhex.length / 2);
  11144. while(zeros > 0) {
  11145. ed.putByte(0x00);
  11146. --zeros;
  11147. }
  11148. ed.putBytes(forge$k.util.hexToBytes(yhex));
  11149. return ed.getBytes();
  11150. };
  11151. /**
  11152. * NOTE: THIS METHOD IS DEPRECATED, use 'decrypt' on a private key object or
  11153. * 'verify' on a public key object instead.
  11154. *
  11155. * Performs RSA decryption.
  11156. *
  11157. * The parameter ml controls whether to apply PKCS#1 v1.5 padding
  11158. * or not. Set ml = false to disable padding removal completely
  11159. * (in order to handle e.g. EMSA-PSS later on) and simply pass back
  11160. * the RSA encryption block.
  11161. *
  11162. * @param ed the encrypted data to decrypt in as a byte string.
  11163. * @param key the RSA key to use.
  11164. * @param pub true for a public key operation, false for private.
  11165. * @param ml the message length, if known, false to disable padding.
  11166. *
  11167. * @return the decrypted message as a byte string.
  11168. */
  11169. pki$4.rsa.decrypt = function(ed, key, pub, ml) {
  11170. // get the length of the modulus in bytes
  11171. var k = Math.ceil(key.n.bitLength() / 8);
  11172. // error if the length of the encrypted data ED is not k
  11173. if(ed.length !== k) {
  11174. var error = new Error('Encrypted message length is invalid.');
  11175. error.length = ed.length;
  11176. error.expected = k;
  11177. throw error;
  11178. }
  11179. // convert encrypted data into a big integer
  11180. // FIXME: hex conversion inefficient, get BigInteger w/byte strings
  11181. var y = new BigInteger$1(forge$k.util.createBuffer(ed).toHex(), 16);
  11182. // y must be less than the modulus or it wasn't the result of
  11183. // a previous mod operation (encryption) using that modulus
  11184. if(y.compareTo(key.n) >= 0) {
  11185. throw new Error('Encrypted message is invalid.');
  11186. }
  11187. // do RSA decryption
  11188. var x = _modPow(y, key, pub);
  11189. // create the encryption block, if x is shorter in bytes than k, then
  11190. // prepend zero bytes to fill up eb
  11191. // FIXME: hex conversion inefficient, get BigInteger w/byte strings
  11192. var xhex = x.toString(16);
  11193. var eb = forge$k.util.createBuffer();
  11194. var zeros = k - Math.ceil(xhex.length / 2);
  11195. while(zeros > 0) {
  11196. eb.putByte(0x00);
  11197. --zeros;
  11198. }
  11199. eb.putBytes(forge$k.util.hexToBytes(xhex));
  11200. if(ml !== false) {
  11201. // legacy, default to PKCS#1 v1.5 padding
  11202. return _decodePkcs1_v1_5(eb.getBytes(), key, pub);
  11203. }
  11204. // return message
  11205. return eb.getBytes();
  11206. };
  11207. /**
  11208. * Creates an RSA key-pair generation state object. It is used to allow
  11209. * key-generation to be performed in steps. It also allows for a UI to
  11210. * display progress updates.
  11211. *
  11212. * @param bits the size for the private key in bits, defaults to 2048.
  11213. * @param e the public exponent to use, defaults to 65537 (0x10001).
  11214. * @param [options] the options to use.
  11215. * prng a custom crypto-secure pseudo-random number generator to use,
  11216. * that must define "getBytesSync".
  11217. * algorithm the algorithm to use (default: 'PRIMEINC').
  11218. *
  11219. * @return the state object to use to generate the key-pair.
  11220. */
  11221. pki$4.rsa.createKeyPairGenerationState = function(bits, e, options) {
  11222. // TODO: migrate step-based prime generation code to forge.prime
  11223. // set default bits
  11224. if(typeof(bits) === 'string') {
  11225. bits = parseInt(bits, 10);
  11226. }
  11227. bits = bits || 2048;
  11228. // create prng with api that matches BigInteger secure random
  11229. options = options || {};
  11230. var prng = options.prng || forge$k.random;
  11231. var rng = {
  11232. // x is an array to fill with bytes
  11233. nextBytes: function(x) {
  11234. var b = prng.getBytesSync(x.length);
  11235. for(var i = 0; i < x.length; ++i) {
  11236. x[i] = b.charCodeAt(i);
  11237. }
  11238. }
  11239. };
  11240. var algorithm = options.algorithm || 'PRIMEINC';
  11241. // create PRIMEINC algorithm state
  11242. var rval;
  11243. if(algorithm === 'PRIMEINC') {
  11244. rval = {
  11245. algorithm: algorithm,
  11246. state: 0,
  11247. bits: bits,
  11248. rng: rng,
  11249. eInt: e || 65537,
  11250. e: new BigInteger$1(null),
  11251. p: null,
  11252. q: null,
  11253. qBits: bits >> 1,
  11254. pBits: bits - (bits >> 1),
  11255. pqState: 0,
  11256. num: null,
  11257. keys: null
  11258. };
  11259. rval.e.fromInt(rval.eInt);
  11260. } else {
  11261. throw new Error('Invalid key generation algorithm: ' + algorithm);
  11262. }
  11263. return rval;
  11264. };
  11265. /**
  11266. * Attempts to runs the key-generation algorithm for at most n seconds
  11267. * (approximately) using the given state. When key-generation has completed,
  11268. * the keys will be stored in state.keys.
  11269. *
  11270. * To use this function to update a UI while generating a key or to prevent
  11271. * causing browser lockups/warnings, set "n" to a value other than 0. A
  11272. * simple pattern for generating a key and showing a progress indicator is:
  11273. *
  11274. * var state = pki.rsa.createKeyPairGenerationState(2048);
  11275. * var step = function() {
  11276. * // step key-generation, run algorithm for 100 ms, repeat
  11277. * if(!forge.pki.rsa.stepKeyPairGenerationState(state, 100)) {
  11278. * setTimeout(step, 1);
  11279. * } else {
  11280. * // key-generation complete
  11281. * // TODO: turn off progress indicator here
  11282. * // TODO: use the generated key-pair in "state.keys"
  11283. * }
  11284. * };
  11285. * // TODO: turn on progress indicator here
  11286. * setTimeout(step, 0);
  11287. *
  11288. * @param state the state to use.
  11289. * @param n the maximum number of milliseconds to run the algorithm for, 0
  11290. * to run the algorithm to completion.
  11291. *
  11292. * @return true if the key-generation completed, false if not.
  11293. */
  11294. pki$4.rsa.stepKeyPairGenerationState = function(state, n) {
  11295. // set default algorithm if not set
  11296. if(!('algorithm' in state)) {
  11297. state.algorithm = 'PRIMEINC';
  11298. }
  11299. // TODO: migrate step-based prime generation code to forge.prime
  11300. // TODO: abstract as PRIMEINC algorithm
  11301. // do key generation (based on Tom Wu's rsa.js, see jsbn.js license)
  11302. // with some minor optimizations and designed to run in steps
  11303. // local state vars
  11304. var THIRTY = new BigInteger$1(null);
  11305. THIRTY.fromInt(30);
  11306. var deltaIdx = 0;
  11307. var op_or = function(x, y) {return x | y;};
  11308. // keep stepping until time limit is reached or done
  11309. var t1 = +new Date();
  11310. var t2;
  11311. var total = 0;
  11312. while(state.keys === null && (n <= 0 || total < n)) {
  11313. // generate p or q
  11314. if(state.state === 0) {
  11315. /* Note: All primes are of the form:
  11316. 30k+i, for i < 30 and gcd(30, i)=1, where there are 8 values for i
  11317. When we generate a random number, we always align it at 30k + 1. Each
  11318. time the number is determined not to be prime we add to get to the
  11319. next 'i', eg: if the number was at 30k + 1 we add 6. */
  11320. var bits = (state.p === null) ? state.pBits : state.qBits;
  11321. var bits1 = bits - 1;
  11322. // get a random number
  11323. if(state.pqState === 0) {
  11324. state.num = new BigInteger$1(bits, state.rng);
  11325. // force MSB set
  11326. if(!state.num.testBit(bits1)) {
  11327. state.num.bitwiseTo(
  11328. BigInteger$1.ONE.shiftLeft(bits1), op_or, state.num);
  11329. }
  11330. // align number on 30k+1 boundary
  11331. state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0);
  11332. deltaIdx = 0;
  11333. ++state.pqState;
  11334. } else if(state.pqState === 1) {
  11335. // try to make the number a prime
  11336. if(state.num.bitLength() > bits) {
  11337. // overflow, try again
  11338. state.pqState = 0;
  11339. // do primality test
  11340. } else if(state.num.isProbablePrime(
  11341. _getMillerRabinTests(state.num.bitLength()))) {
  11342. ++state.pqState;
  11343. } else {
  11344. // get next potential prime
  11345. state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);
  11346. }
  11347. } else if(state.pqState === 2) {
  11348. // ensure number is coprime with e
  11349. state.pqState =
  11350. (state.num.subtract(BigInteger$1.ONE).gcd(state.e)
  11351. .compareTo(BigInteger$1.ONE) === 0) ? 3 : 0;
  11352. } else if(state.pqState === 3) {
  11353. // store p or q
  11354. state.pqState = 0;
  11355. if(state.p === null) {
  11356. state.p = state.num;
  11357. } else {
  11358. state.q = state.num;
  11359. }
  11360. // advance state if both p and q are ready
  11361. if(state.p !== null && state.q !== null) {
  11362. ++state.state;
  11363. }
  11364. state.num = null;
  11365. }
  11366. } else if(state.state === 1) {
  11367. // ensure p is larger than q (swap them if not)
  11368. if(state.p.compareTo(state.q) < 0) {
  11369. state.num = state.p;
  11370. state.p = state.q;
  11371. state.q = state.num;
  11372. }
  11373. ++state.state;
  11374. } else if(state.state === 2) {
  11375. // compute phi: (p - 1)(q - 1) (Euler's totient function)
  11376. state.p1 = state.p.subtract(BigInteger$1.ONE);
  11377. state.q1 = state.q.subtract(BigInteger$1.ONE);
  11378. state.phi = state.p1.multiply(state.q1);
  11379. ++state.state;
  11380. } else if(state.state === 3) {
  11381. // ensure e and phi are coprime
  11382. if(state.phi.gcd(state.e).compareTo(BigInteger$1.ONE) === 0) {
  11383. // phi and e are coprime, advance
  11384. ++state.state;
  11385. } else {
  11386. // phi and e aren't coprime, so generate a new p and q
  11387. state.p = null;
  11388. state.q = null;
  11389. state.state = 0;
  11390. }
  11391. } else if(state.state === 4) {
  11392. // create n, ensure n is has the right number of bits
  11393. state.n = state.p.multiply(state.q);
  11394. // ensure n is right number of bits
  11395. if(state.n.bitLength() === state.bits) {
  11396. // success, advance
  11397. ++state.state;
  11398. } else {
  11399. // failed, get new q
  11400. state.q = null;
  11401. state.state = 0;
  11402. }
  11403. } else if(state.state === 5) {
  11404. // set keys
  11405. var d = state.e.modInverse(state.phi);
  11406. state.keys = {
  11407. privateKey: pki$4.rsa.setPrivateKey(
  11408. state.n, state.e, d, state.p, state.q,
  11409. d.mod(state.p1), d.mod(state.q1),
  11410. state.q.modInverse(state.p)),
  11411. publicKey: pki$4.rsa.setPublicKey(state.n, state.e)
  11412. };
  11413. }
  11414. // update timing
  11415. t2 = +new Date();
  11416. total += t2 - t1;
  11417. t1 = t2;
  11418. }
  11419. return state.keys !== null;
  11420. };
  11421. /**
  11422. * Generates an RSA public-private key pair in a single call.
  11423. *
  11424. * To generate a key-pair in steps (to allow for progress updates and to
  11425. * prevent blocking or warnings in slow browsers) then use the key-pair
  11426. * generation state functions.
  11427. *
  11428. * To generate a key-pair asynchronously (either through web-workers, if
  11429. * available, or by breaking up the work on the main thread), pass a
  11430. * callback function.
  11431. *
  11432. * @param [bits] the size for the private key in bits, defaults to 2048.
  11433. * @param [e] the public exponent to use, defaults to 65537.
  11434. * @param [options] options for key-pair generation, if given then 'bits'
  11435. * and 'e' must *not* be given:
  11436. * bits the size for the private key in bits, (default: 2048).
  11437. * e the public exponent to use, (default: 65537 (0x10001)).
  11438. * workerScript the worker script URL.
  11439. * workers the number of web workers (if supported) to use,
  11440. * (default: 2).
  11441. * workLoad the size of the work load, ie: number of possible prime
  11442. * numbers for each web worker to check per work assignment,
  11443. * (default: 100).
  11444. * prng a custom crypto-secure pseudo-random number generator to use,
  11445. * that must define "getBytesSync". Disables use of native APIs.
  11446. * algorithm the algorithm to use (default: 'PRIMEINC').
  11447. * @param [callback(err, keypair)] called once the operation completes.
  11448. *
  11449. * @return an object with privateKey and publicKey properties.
  11450. */
  11451. pki$4.rsa.generateKeyPair = function(bits, e, options, callback) {
  11452. // (bits), (options), (callback)
  11453. if(arguments.length === 1) {
  11454. if(typeof bits === 'object') {
  11455. options = bits;
  11456. bits = undefined;
  11457. } else if(typeof bits === 'function') {
  11458. callback = bits;
  11459. bits = undefined;
  11460. }
  11461. } else if(arguments.length === 2) {
  11462. // (bits, e), (bits, options), (bits, callback), (options, callback)
  11463. if(typeof bits === 'number') {
  11464. if(typeof e === 'function') {
  11465. callback = e;
  11466. e = undefined;
  11467. } else if(typeof e !== 'number') {
  11468. options = e;
  11469. e = undefined;
  11470. }
  11471. } else {
  11472. options = bits;
  11473. callback = e;
  11474. bits = undefined;
  11475. e = undefined;
  11476. }
  11477. } else if(arguments.length === 3) {
  11478. // (bits, e, options), (bits, e, callback), (bits, options, callback)
  11479. if(typeof e === 'number') {
  11480. if(typeof options === 'function') {
  11481. callback = options;
  11482. options = undefined;
  11483. }
  11484. } else {
  11485. callback = options;
  11486. options = e;
  11487. e = undefined;
  11488. }
  11489. }
  11490. options = options || {};
  11491. if(bits === undefined) {
  11492. bits = options.bits || 2048;
  11493. }
  11494. if(e === undefined) {
  11495. e = options.e || 0x10001;
  11496. }
  11497. // use native code if permitted, available, and parameters are acceptable
  11498. if(!options.prng &&
  11499. bits >= 256 && bits <= 16384 && (e === 0x10001 || e === 3)) {
  11500. if(callback) {
  11501. // try native async
  11502. if(_detectNodeCrypto('generateKeyPair')) {
  11503. return _crypto.generateKeyPair('rsa', {
  11504. modulusLength: bits,
  11505. publicExponent: e,
  11506. publicKeyEncoding: {
  11507. type: 'spki',
  11508. format: 'pem'
  11509. },
  11510. privateKeyEncoding: {
  11511. type: 'pkcs8',
  11512. format: 'pem'
  11513. }
  11514. }, function(err, pub, priv) {
  11515. if(err) {
  11516. return callback(err);
  11517. }
  11518. callback(null, {
  11519. privateKey: pki$4.privateKeyFromPem(priv),
  11520. publicKey: pki$4.publicKeyFromPem(pub)
  11521. });
  11522. });
  11523. }
  11524. if(_detectSubtleCrypto('generateKey') &&
  11525. _detectSubtleCrypto('exportKey')) {
  11526. // use standard native generateKey
  11527. return util.globalScope.crypto.subtle.generateKey({
  11528. name: 'RSASSA-PKCS1-v1_5',
  11529. modulusLength: bits,
  11530. publicExponent: _intToUint8Array(e),
  11531. hash: {name: 'SHA-256'}
  11532. }, true /* key can be exported*/, ['sign', 'verify'])
  11533. .then(function(pair) {
  11534. return util.globalScope.crypto.subtle.exportKey(
  11535. 'pkcs8', pair.privateKey);
  11536. // avoiding catch(function(err) {...}) to support IE <= 8
  11537. }).then(undefined, function(err) {
  11538. callback(err);
  11539. }).then(function(pkcs8) {
  11540. if(pkcs8) {
  11541. var privateKey = pki$4.privateKeyFromAsn1(
  11542. asn1$7.fromDer(forge$k.util.createBuffer(pkcs8)));
  11543. callback(null, {
  11544. privateKey: privateKey,
  11545. publicKey: pki$4.setRsaPublicKey(privateKey.n, privateKey.e)
  11546. });
  11547. }
  11548. });
  11549. }
  11550. if(_detectSubtleMsCrypto('generateKey') &&
  11551. _detectSubtleMsCrypto('exportKey')) {
  11552. var genOp = util.globalScope.msCrypto.subtle.generateKey({
  11553. name: 'RSASSA-PKCS1-v1_5',
  11554. modulusLength: bits,
  11555. publicExponent: _intToUint8Array(e),
  11556. hash: {name: 'SHA-256'}
  11557. }, true /* key can be exported*/, ['sign', 'verify']);
  11558. genOp.oncomplete = function(e) {
  11559. var pair = e.target.result;
  11560. var exportOp = util.globalScope.msCrypto.subtle.exportKey(
  11561. 'pkcs8', pair.privateKey);
  11562. exportOp.oncomplete = function(e) {
  11563. var pkcs8 = e.target.result;
  11564. var privateKey = pki$4.privateKeyFromAsn1(
  11565. asn1$7.fromDer(forge$k.util.createBuffer(pkcs8)));
  11566. callback(null, {
  11567. privateKey: privateKey,
  11568. publicKey: pki$4.setRsaPublicKey(privateKey.n, privateKey.e)
  11569. });
  11570. };
  11571. exportOp.onerror = function(err) {
  11572. callback(err);
  11573. };
  11574. };
  11575. genOp.onerror = function(err) {
  11576. callback(err);
  11577. };
  11578. return;
  11579. }
  11580. } else {
  11581. // try native sync
  11582. if(_detectNodeCrypto('generateKeyPairSync')) {
  11583. var keypair = _crypto.generateKeyPairSync('rsa', {
  11584. modulusLength: bits,
  11585. publicExponent: e,
  11586. publicKeyEncoding: {
  11587. type: 'spki',
  11588. format: 'pem'
  11589. },
  11590. privateKeyEncoding: {
  11591. type: 'pkcs8',
  11592. format: 'pem'
  11593. }
  11594. });
  11595. return {
  11596. privateKey: pki$4.privateKeyFromPem(keypair.privateKey),
  11597. publicKey: pki$4.publicKeyFromPem(keypair.publicKey)
  11598. };
  11599. }
  11600. }
  11601. }
  11602. // use JavaScript implementation
  11603. var state = pki$4.rsa.createKeyPairGenerationState(bits, e, options);
  11604. if(!callback) {
  11605. pki$4.rsa.stepKeyPairGenerationState(state, 0);
  11606. return state.keys;
  11607. }
  11608. _generateKeyPair(state, options, callback);
  11609. };
  11610. /**
  11611. * Sets an RSA public key from BigIntegers modulus and exponent.
  11612. *
  11613. * @param n the modulus.
  11614. * @param e the exponent.
  11615. *
  11616. * @return the public key.
  11617. */
  11618. pki$4.setRsaPublicKey = pki$4.rsa.setPublicKey = function(n, e) {
  11619. var key = {
  11620. n: n,
  11621. e: e
  11622. };
  11623. /**
  11624. * Encrypts the given data with this public key. Newer applications
  11625. * should use the 'RSA-OAEP' decryption scheme, 'RSAES-PKCS1-V1_5' is for
  11626. * legacy applications.
  11627. *
  11628. * @param data the byte string to encrypt.
  11629. * @param scheme the encryption scheme to use:
  11630. * 'RSAES-PKCS1-V1_5' (default),
  11631. * 'RSA-OAEP',
  11632. * 'RAW', 'NONE', or null to perform raw RSA encryption,
  11633. * an object with an 'encode' property set to a function
  11634. * with the signature 'function(data, key)' that returns
  11635. * a binary-encoded string representing the encoded data.
  11636. * @param schemeOptions any scheme-specific options.
  11637. *
  11638. * @return the encrypted byte string.
  11639. */
  11640. key.encrypt = function(data, scheme, schemeOptions) {
  11641. if(typeof scheme === 'string') {
  11642. scheme = scheme.toUpperCase();
  11643. } else if(scheme === undefined) {
  11644. scheme = 'RSAES-PKCS1-V1_5';
  11645. }
  11646. if(scheme === 'RSAES-PKCS1-V1_5') {
  11647. scheme = {
  11648. encode: function(m, key, pub) {
  11649. return _encodePkcs1_v1_5(m, key, 0x02).getBytes();
  11650. }
  11651. };
  11652. } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {
  11653. scheme = {
  11654. encode: function(m, key) {
  11655. return forge$k.pkcs1.encode_rsa_oaep(key, m, schemeOptions);
  11656. }
  11657. };
  11658. } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {
  11659. scheme = {encode: function(e) {return e;}};
  11660. } else if(typeof scheme === 'string') {
  11661. throw new Error('Unsupported encryption scheme: "' + scheme + '".');
  11662. }
  11663. // do scheme-based encoding then rsa encryption
  11664. var e = scheme.encode(data, key, true);
  11665. return pki$4.rsa.encrypt(e, key, true);
  11666. };
  11667. /**
  11668. * Verifies the given signature against the given digest.
  11669. *
  11670. * PKCS#1 supports multiple (currently two) signature schemes:
  11671. * RSASSA-PKCS1-V1_5 and RSASSA-PSS.
  11672. *
  11673. * By default this implementation uses the "old scheme", i.e.
  11674. * RSASSA-PKCS1-V1_5, in which case once RSA-decrypted, the
  11675. * signature is an OCTET STRING that holds a DigestInfo.
  11676. *
  11677. * DigestInfo ::= SEQUENCE {
  11678. * digestAlgorithm DigestAlgorithmIdentifier,
  11679. * digest Digest
  11680. * }
  11681. * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
  11682. * Digest ::= OCTET STRING
  11683. *
  11684. * To perform PSS signature verification, provide an instance
  11685. * of Forge PSS object as the scheme parameter.
  11686. *
  11687. * @param digest the message digest hash to compare against the signature,
  11688. * as a binary-encoded string.
  11689. * @param signature the signature to verify, as a binary-encoded string.
  11690. * @param scheme signature verification scheme to use:
  11691. * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5,
  11692. * a Forge PSS object for RSASSA-PSS,
  11693. * 'NONE' or null for none, DigestInfo will not be expected, but
  11694. * PKCS#1 v1.5 padding will still be used.
  11695. *
  11696. * @return true if the signature was verified, false if not.
  11697. */
  11698. key.verify = function(digest, signature, scheme) {
  11699. if(typeof scheme === 'string') {
  11700. scheme = scheme.toUpperCase();
  11701. } else if(scheme === undefined) {
  11702. scheme = 'RSASSA-PKCS1-V1_5';
  11703. }
  11704. if(scheme === 'RSASSA-PKCS1-V1_5') {
  11705. scheme = {
  11706. verify: function(digest, d) {
  11707. // remove padding
  11708. d = _decodePkcs1_v1_5(d, key, true);
  11709. // d is ASN.1 BER-encoded DigestInfo
  11710. var obj = asn1$7.fromDer(d);
  11711. // compare the given digest to the decrypted one
  11712. return digest === obj.value[1].value;
  11713. }
  11714. };
  11715. } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {
  11716. scheme = {
  11717. verify: function(digest, d) {
  11718. // remove padding
  11719. d = _decodePkcs1_v1_5(d, key, true);
  11720. return digest === d;
  11721. }
  11722. };
  11723. }
  11724. // do rsa decryption w/o any decoding, then verify -- which does decoding
  11725. var d = pki$4.rsa.decrypt(signature, key, true, false);
  11726. return scheme.verify(digest, d, key.n.bitLength());
  11727. };
  11728. return key;
  11729. };
  11730. /**
  11731. * Sets an RSA private key from BigIntegers modulus, exponent, primes,
  11732. * prime exponents, and modular multiplicative inverse.
  11733. *
  11734. * @param n the modulus.
  11735. * @param e the public exponent.
  11736. * @param d the private exponent ((inverse of e) mod n).
  11737. * @param p the first prime.
  11738. * @param q the second prime.
  11739. * @param dP exponent1 (d mod (p-1)).
  11740. * @param dQ exponent2 (d mod (q-1)).
  11741. * @param qInv ((inverse of q) mod p)
  11742. *
  11743. * @return the private key.
  11744. */
  11745. pki$4.setRsaPrivateKey = pki$4.rsa.setPrivateKey = function(
  11746. n, e, d, p, q, dP, dQ, qInv) {
  11747. var key = {
  11748. n: n,
  11749. e: e,
  11750. d: d,
  11751. p: p,
  11752. q: q,
  11753. dP: dP,
  11754. dQ: dQ,
  11755. qInv: qInv
  11756. };
  11757. /**
  11758. * Decrypts the given data with this private key. The decryption scheme
  11759. * must match the one used to encrypt the data.
  11760. *
  11761. * @param data the byte string to decrypt.
  11762. * @param scheme the decryption scheme to use:
  11763. * 'RSAES-PKCS1-V1_5' (default),
  11764. * 'RSA-OAEP',
  11765. * 'RAW', 'NONE', or null to perform raw RSA decryption.
  11766. * @param schemeOptions any scheme-specific options.
  11767. *
  11768. * @return the decrypted byte string.
  11769. */
  11770. key.decrypt = function(data, scheme, schemeOptions) {
  11771. if(typeof scheme === 'string') {
  11772. scheme = scheme.toUpperCase();
  11773. } else if(scheme === undefined) {
  11774. scheme = 'RSAES-PKCS1-V1_5';
  11775. }
  11776. // do rsa decryption w/o any decoding
  11777. var d = pki$4.rsa.decrypt(data, key, false, false);
  11778. if(scheme === 'RSAES-PKCS1-V1_5') {
  11779. scheme = {decode: _decodePkcs1_v1_5};
  11780. } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {
  11781. scheme = {
  11782. decode: function(d, key) {
  11783. return forge$k.pkcs1.decode_rsa_oaep(key, d, schemeOptions);
  11784. }
  11785. };
  11786. } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {
  11787. scheme = {decode: function(d) {return d;}};
  11788. } else {
  11789. throw new Error('Unsupported encryption scheme: "' + scheme + '".');
  11790. }
  11791. // decode according to scheme
  11792. return scheme.decode(d, key, false);
  11793. };
  11794. /**
  11795. * Signs the given digest, producing a signature.
  11796. *
  11797. * PKCS#1 supports multiple (currently two) signature schemes:
  11798. * RSASSA-PKCS1-V1_5 and RSASSA-PSS.
  11799. *
  11800. * By default this implementation uses the "old scheme", i.e.
  11801. * RSASSA-PKCS1-V1_5. In order to generate a PSS signature, provide
  11802. * an instance of Forge PSS object as the scheme parameter.
  11803. *
  11804. * @param md the message digest object with the hash to sign.
  11805. * @param scheme the signature scheme to use:
  11806. * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5,
  11807. * a Forge PSS object for RSASSA-PSS,
  11808. * 'NONE' or null for none, DigestInfo will not be used but
  11809. * PKCS#1 v1.5 padding will still be used.
  11810. *
  11811. * @return the signature as a byte string.
  11812. */
  11813. key.sign = function(md, scheme) {
  11814. /* Note: The internal implementation of RSA operations is being
  11815. transitioned away from a PKCS#1 v1.5 hard-coded scheme. Some legacy
  11816. code like the use of an encoding block identifier 'bt' will eventually
  11817. be removed. */
  11818. // private key operation
  11819. var bt = false;
  11820. if(typeof scheme === 'string') {
  11821. scheme = scheme.toUpperCase();
  11822. }
  11823. if(scheme === undefined || scheme === 'RSASSA-PKCS1-V1_5') {
  11824. scheme = {encode: emsaPkcs1v15encode};
  11825. bt = 0x01;
  11826. } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {
  11827. scheme = {encode: function() {return md;}};
  11828. bt = 0x01;
  11829. }
  11830. // encode and then encrypt
  11831. var d = scheme.encode(md, key.n.bitLength());
  11832. return pki$4.rsa.encrypt(d, key, bt);
  11833. };
  11834. return key;
  11835. };
  11836. /**
  11837. * Wraps an RSAPrivateKey ASN.1 object in an ASN.1 PrivateKeyInfo object.
  11838. *
  11839. * @param rsaKey the ASN.1 RSAPrivateKey.
  11840. *
  11841. * @return the ASN.1 PrivateKeyInfo.
  11842. */
  11843. pki$4.wrapRsaPrivateKey = function(rsaKey) {
  11844. // PrivateKeyInfo
  11845. return asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.SEQUENCE, true, [
  11846. // version (0)
  11847. asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false,
  11848. asn1$7.integerToDer(0).getBytes()),
  11849. // privateKeyAlgorithm
  11850. asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.SEQUENCE, true, [
  11851. asn1$7.create(
  11852. asn1$7.Class.UNIVERSAL, asn1$7.Type.OID, false,
  11853. asn1$7.oidToDer(pki$4.oids.rsaEncryption).getBytes()),
  11854. asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.NULL, false, '')
  11855. ]),
  11856. // PrivateKey
  11857. asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.OCTETSTRING, false,
  11858. asn1$7.toDer(rsaKey).getBytes())
  11859. ]);
  11860. };
  11861. /**
  11862. * Converts a private key from an ASN.1 object.
  11863. *
  11864. * @param obj the ASN.1 representation of a PrivateKeyInfo containing an
  11865. * RSAPrivateKey or an RSAPrivateKey.
  11866. *
  11867. * @return the private key.
  11868. */
  11869. pki$4.privateKeyFromAsn1 = function(obj) {
  11870. // get PrivateKeyInfo
  11871. var capture = {};
  11872. var errors = [];
  11873. if(asn1$7.validate(obj, privateKeyValidator$1, capture, errors)) {
  11874. obj = asn1$7.fromDer(forge$k.util.createBuffer(capture.privateKey));
  11875. }
  11876. // get RSAPrivateKey
  11877. capture = {};
  11878. errors = [];
  11879. if(!asn1$7.validate(obj, rsaPrivateKeyValidator, capture, errors)) {
  11880. var error = new Error('Cannot read private key. ' +
  11881. 'ASN.1 object does not contain an RSAPrivateKey.');
  11882. error.errors = errors;
  11883. throw error;
  11884. }
  11885. // Note: Version is currently ignored.
  11886. // capture.privateKeyVersion
  11887. // FIXME: inefficient, get a BigInteger that uses byte strings
  11888. var n, e, d, p, q, dP, dQ, qInv;
  11889. n = forge$k.util.createBuffer(capture.privateKeyModulus).toHex();
  11890. e = forge$k.util.createBuffer(capture.privateKeyPublicExponent).toHex();
  11891. d = forge$k.util.createBuffer(capture.privateKeyPrivateExponent).toHex();
  11892. p = forge$k.util.createBuffer(capture.privateKeyPrime1).toHex();
  11893. q = forge$k.util.createBuffer(capture.privateKeyPrime2).toHex();
  11894. dP = forge$k.util.createBuffer(capture.privateKeyExponent1).toHex();
  11895. dQ = forge$k.util.createBuffer(capture.privateKeyExponent2).toHex();
  11896. qInv = forge$k.util.createBuffer(capture.privateKeyCoefficient).toHex();
  11897. // set private key
  11898. return pki$4.setRsaPrivateKey(
  11899. new BigInteger$1(n, 16),
  11900. new BigInteger$1(e, 16),
  11901. new BigInteger$1(d, 16),
  11902. new BigInteger$1(p, 16),
  11903. new BigInteger$1(q, 16),
  11904. new BigInteger$1(dP, 16),
  11905. new BigInteger$1(dQ, 16),
  11906. new BigInteger$1(qInv, 16));
  11907. };
  11908. /**
  11909. * Converts a private key to an ASN.1 RSAPrivateKey.
  11910. *
  11911. * @param key the private key.
  11912. *
  11913. * @return the ASN.1 representation of an RSAPrivateKey.
  11914. */
  11915. pki$4.privateKeyToAsn1 = pki$4.privateKeyToRSAPrivateKey = function(key) {
  11916. // RSAPrivateKey
  11917. return asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.SEQUENCE, true, [
  11918. // version (0 = only 2 primes, 1 multiple primes)
  11919. asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false,
  11920. asn1$7.integerToDer(0).getBytes()),
  11921. // modulus (n)
  11922. asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false,
  11923. _bnToBytes(key.n)),
  11924. // publicExponent (e)
  11925. asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false,
  11926. _bnToBytes(key.e)),
  11927. // privateExponent (d)
  11928. asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false,
  11929. _bnToBytes(key.d)),
  11930. // privateKeyPrime1 (p)
  11931. asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false,
  11932. _bnToBytes(key.p)),
  11933. // privateKeyPrime2 (q)
  11934. asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false,
  11935. _bnToBytes(key.q)),
  11936. // privateKeyExponent1 (dP)
  11937. asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false,
  11938. _bnToBytes(key.dP)),
  11939. // privateKeyExponent2 (dQ)
  11940. asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false,
  11941. _bnToBytes(key.dQ)),
  11942. // coefficient (qInv)
  11943. asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false,
  11944. _bnToBytes(key.qInv))
  11945. ]);
  11946. };
  11947. /**
  11948. * Converts a public key from an ASN.1 SubjectPublicKeyInfo or RSAPublicKey.
  11949. *
  11950. * @param obj the asn1 representation of a SubjectPublicKeyInfo or RSAPublicKey.
  11951. *
  11952. * @return the public key.
  11953. */
  11954. pki$4.publicKeyFromAsn1 = function(obj) {
  11955. // get SubjectPublicKeyInfo
  11956. var capture = {};
  11957. var errors = [];
  11958. if(asn1$7.validate(obj, publicKeyValidator$2, capture, errors)) {
  11959. // get oid
  11960. var oid = asn1$7.derToOid(capture.publicKeyOid);
  11961. if(oid !== pki$4.oids.rsaEncryption) {
  11962. var error = new Error('Cannot read public key. Unknown OID.');
  11963. error.oid = oid;
  11964. throw error;
  11965. }
  11966. obj = capture.rsaPublicKey;
  11967. }
  11968. // get RSA params
  11969. errors = [];
  11970. if(!asn1$7.validate(obj, rsaPublicKeyValidator, capture, errors)) {
  11971. var error = new Error('Cannot read public key. ' +
  11972. 'ASN.1 object does not contain an RSAPublicKey.');
  11973. error.errors = errors;
  11974. throw error;
  11975. }
  11976. // FIXME: inefficient, get a BigInteger that uses byte strings
  11977. var n = forge$k.util.createBuffer(capture.publicKeyModulus).toHex();
  11978. var e = forge$k.util.createBuffer(capture.publicKeyExponent).toHex();
  11979. // set public key
  11980. return pki$4.setRsaPublicKey(
  11981. new BigInteger$1(n, 16),
  11982. new BigInteger$1(e, 16));
  11983. };
  11984. /**
  11985. * Converts a public key to an ASN.1 SubjectPublicKeyInfo.
  11986. *
  11987. * @param key the public key.
  11988. *
  11989. * @return the asn1 representation of a SubjectPublicKeyInfo.
  11990. */
  11991. pki$4.publicKeyToAsn1 = pki$4.publicKeyToSubjectPublicKeyInfo = function(key) {
  11992. // SubjectPublicKeyInfo
  11993. return asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.SEQUENCE, true, [
  11994. // AlgorithmIdentifier
  11995. asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.SEQUENCE, true, [
  11996. // algorithm
  11997. asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.OID, false,
  11998. asn1$7.oidToDer(pki$4.oids.rsaEncryption).getBytes()),
  11999. // parameters (null)
  12000. asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.NULL, false, '')
  12001. ]),
  12002. // subjectPublicKey
  12003. asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.BITSTRING, false, [
  12004. pki$4.publicKeyToRSAPublicKey(key)
  12005. ])
  12006. ]);
  12007. };
  12008. /**
  12009. * Converts a public key to an ASN.1 RSAPublicKey.
  12010. *
  12011. * @param key the public key.
  12012. *
  12013. * @return the asn1 representation of a RSAPublicKey.
  12014. */
  12015. pki$4.publicKeyToRSAPublicKey = function(key) {
  12016. // RSAPublicKey
  12017. return asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.SEQUENCE, true, [
  12018. // modulus (n)
  12019. asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false,
  12020. _bnToBytes(key.n)),
  12021. // publicExponent (e)
  12022. asn1$7.create(asn1$7.Class.UNIVERSAL, asn1$7.Type.INTEGER, false,
  12023. _bnToBytes(key.e))
  12024. ]);
  12025. };
  12026. /**
  12027. * Encodes a message using PKCS#1 v1.5 padding.
  12028. *
  12029. * @param m the message to encode.
  12030. * @param key the RSA key to use.
  12031. * @param bt the block type to use, i.e. either 0x01 (for signing) or 0x02
  12032. * (for encryption).
  12033. *
  12034. * @return the padded byte buffer.
  12035. */
  12036. function _encodePkcs1_v1_5(m, key, bt) {
  12037. var eb = forge$k.util.createBuffer();
  12038. // get the length of the modulus in bytes
  12039. var k = Math.ceil(key.n.bitLength() / 8);
  12040. /* use PKCS#1 v1.5 padding */
  12041. if(m.length > (k - 11)) {
  12042. var error = new Error('Message is too long for PKCS#1 v1.5 padding.');
  12043. error.length = m.length;
  12044. error.max = k - 11;
  12045. throw error;
  12046. }
  12047. /* A block type BT, a padding string PS, and the data D shall be
  12048. formatted into an octet string EB, the encryption block:
  12049. EB = 00 || BT || PS || 00 || D
  12050. The block type BT shall be a single octet indicating the structure of
  12051. the encryption block. For this version of the document it shall have
  12052. value 00, 01, or 02. For a private-key operation, the block type
  12053. shall be 00 or 01. For a public-key operation, it shall be 02.
  12054. The padding string PS shall consist of k-3-||D|| octets. For block
  12055. type 00, the octets shall have value 00; for block type 01, they
  12056. shall have value FF; and for block type 02, they shall be
  12057. pseudorandomly generated and nonzero. This makes the length of the
  12058. encryption block EB equal to k. */
  12059. // build the encryption block
  12060. eb.putByte(0x00);
  12061. eb.putByte(bt);
  12062. // create the padding
  12063. var padNum = k - 3 - m.length;
  12064. var padByte;
  12065. // private key op
  12066. if(bt === 0x00 || bt === 0x01) {
  12067. padByte = (bt === 0x00) ? 0x00 : 0xFF;
  12068. for(var i = 0; i < padNum; ++i) {
  12069. eb.putByte(padByte);
  12070. }
  12071. } else {
  12072. // public key op
  12073. // pad with random non-zero values
  12074. while(padNum > 0) {
  12075. var numZeros = 0;
  12076. var padBytes = forge$k.random.getBytes(padNum);
  12077. for(var i = 0; i < padNum; ++i) {
  12078. padByte = padBytes.charCodeAt(i);
  12079. if(padByte === 0) {
  12080. ++numZeros;
  12081. } else {
  12082. eb.putByte(padByte);
  12083. }
  12084. }
  12085. padNum = numZeros;
  12086. }
  12087. }
  12088. // zero followed by message
  12089. eb.putByte(0x00);
  12090. eb.putBytes(m);
  12091. return eb;
  12092. }
  12093. /**
  12094. * Decodes a message using PKCS#1 v1.5 padding.
  12095. *
  12096. * @param em the message to decode.
  12097. * @param key the RSA key to use.
  12098. * @param pub true if the key is a public key, false if it is private.
  12099. * @param ml the message length, if specified.
  12100. *
  12101. * @return the decoded bytes.
  12102. */
  12103. function _decodePkcs1_v1_5(em, key, pub, ml) {
  12104. // get the length of the modulus in bytes
  12105. var k = Math.ceil(key.n.bitLength() / 8);
  12106. /* It is an error if any of the following conditions occurs:
  12107. 1. The encryption block EB cannot be parsed unambiguously.
  12108. 2. The padding string PS consists of fewer than eight octets
  12109. or is inconsisent with the block type BT.
  12110. 3. The decryption process is a public-key operation and the block
  12111. type BT is not 00 or 01, or the decryption process is a
  12112. private-key operation and the block type is not 02.
  12113. */
  12114. // parse the encryption block
  12115. var eb = forge$k.util.createBuffer(em);
  12116. var first = eb.getByte();
  12117. var bt = eb.getByte();
  12118. if(first !== 0x00 ||
  12119. (pub && bt !== 0x00 && bt !== 0x01) ||
  12120. (!pub && bt != 0x02) ||
  12121. (pub && bt === 0x00 && typeof(ml) === 'undefined')) {
  12122. throw new Error('Encryption block is invalid.');
  12123. }
  12124. var padNum = 0;
  12125. if(bt === 0x00) {
  12126. // check all padding bytes for 0x00
  12127. padNum = k - 3 - ml;
  12128. for(var i = 0; i < padNum; ++i) {
  12129. if(eb.getByte() !== 0x00) {
  12130. throw new Error('Encryption block is invalid.');
  12131. }
  12132. }
  12133. } else if(bt === 0x01) {
  12134. // find the first byte that isn't 0xFF, should be after all padding
  12135. padNum = 0;
  12136. while(eb.length() > 1) {
  12137. if(eb.getByte() !== 0xFF) {
  12138. --eb.read;
  12139. break;
  12140. }
  12141. ++padNum;
  12142. }
  12143. } else if(bt === 0x02) {
  12144. // look for 0x00 byte
  12145. padNum = 0;
  12146. while(eb.length() > 1) {
  12147. if(eb.getByte() === 0x00) {
  12148. --eb.read;
  12149. break;
  12150. }
  12151. ++padNum;
  12152. }
  12153. }
  12154. // zero must be 0x00 and padNum must be (k - 3 - message length)
  12155. var zero = eb.getByte();
  12156. if(zero !== 0x00 || padNum !== (k - 3 - eb.length())) {
  12157. throw new Error('Encryption block is invalid.');
  12158. }
  12159. return eb.getBytes();
  12160. }
  12161. /**
  12162. * Runs the key-generation algorithm asynchronously, either in the background
  12163. * via Web Workers, or using the main thread and setImmediate.
  12164. *
  12165. * @param state the key-pair generation state.
  12166. * @param [options] options for key-pair generation:
  12167. * workerScript the worker script URL.
  12168. * workers the number of web workers (if supported) to use,
  12169. * (default: 2, -1 to use estimated cores minus one).
  12170. * workLoad the size of the work load, ie: number of possible prime
  12171. * numbers for each web worker to check per work assignment,
  12172. * (default: 100).
  12173. * @param callback(err, keypair) called once the operation completes.
  12174. */
  12175. function _generateKeyPair(state, options, callback) {
  12176. if(typeof options === 'function') {
  12177. callback = options;
  12178. options = {};
  12179. }
  12180. options = options || {};
  12181. var opts = {
  12182. algorithm: {
  12183. name: options.algorithm || 'PRIMEINC',
  12184. options: {
  12185. workers: options.workers || 2,
  12186. workLoad: options.workLoad || 100,
  12187. workerScript: options.workerScript
  12188. }
  12189. }
  12190. };
  12191. if('prng' in options) {
  12192. opts.prng = options.prng;
  12193. }
  12194. generate();
  12195. function generate() {
  12196. // find p and then q (done in series to simplify)
  12197. getPrime(state.pBits, function(err, num) {
  12198. if(err) {
  12199. return callback(err);
  12200. }
  12201. state.p = num;
  12202. if(state.q !== null) {
  12203. return finish(err, state.q);
  12204. }
  12205. getPrime(state.qBits, finish);
  12206. });
  12207. }
  12208. function getPrime(bits, callback) {
  12209. forge$k.prime.generateProbablePrime(bits, opts, callback);
  12210. }
  12211. function finish(err, num) {
  12212. if(err) {
  12213. return callback(err);
  12214. }
  12215. // set q
  12216. state.q = num;
  12217. // ensure p is larger than q (swap them if not)
  12218. if(state.p.compareTo(state.q) < 0) {
  12219. var tmp = state.p;
  12220. state.p = state.q;
  12221. state.q = tmp;
  12222. }
  12223. // ensure p is coprime with e
  12224. if(state.p.subtract(BigInteger$1.ONE).gcd(state.e)
  12225. .compareTo(BigInteger$1.ONE) !== 0) {
  12226. state.p = null;
  12227. generate();
  12228. return;
  12229. }
  12230. // ensure q is coprime with e
  12231. if(state.q.subtract(BigInteger$1.ONE).gcd(state.e)
  12232. .compareTo(BigInteger$1.ONE) !== 0) {
  12233. state.q = null;
  12234. getPrime(state.qBits, finish);
  12235. return;
  12236. }
  12237. // compute phi: (p - 1)(q - 1) (Euler's totient function)
  12238. state.p1 = state.p.subtract(BigInteger$1.ONE);
  12239. state.q1 = state.q.subtract(BigInteger$1.ONE);
  12240. state.phi = state.p1.multiply(state.q1);
  12241. // ensure e and phi are coprime
  12242. if(state.phi.gcd(state.e).compareTo(BigInteger$1.ONE) !== 0) {
  12243. // phi and e aren't coprime, so generate a new p and q
  12244. state.p = state.q = null;
  12245. generate();
  12246. return;
  12247. }
  12248. // create n, ensure n is has the right number of bits
  12249. state.n = state.p.multiply(state.q);
  12250. if(state.n.bitLength() !== state.bits) {
  12251. // failed, get new q
  12252. state.q = null;
  12253. getPrime(state.qBits, finish);
  12254. return;
  12255. }
  12256. // set keys
  12257. var d = state.e.modInverse(state.phi);
  12258. state.keys = {
  12259. privateKey: pki$4.rsa.setPrivateKey(
  12260. state.n, state.e, d, state.p, state.q,
  12261. d.mod(state.p1), d.mod(state.q1),
  12262. state.q.modInverse(state.p)),
  12263. publicKey: pki$4.rsa.setPublicKey(state.n, state.e)
  12264. };
  12265. callback(null, state.keys);
  12266. }
  12267. }
  12268. /**
  12269. * Converts a positive BigInteger into 2's-complement big-endian bytes.
  12270. *
  12271. * @param b the big integer to convert.
  12272. *
  12273. * @return the bytes.
  12274. */
  12275. function _bnToBytes(b) {
  12276. // prepend 0x00 if first byte >= 0x80
  12277. var hex = b.toString(16);
  12278. if(hex[0] >= '8') {
  12279. hex = '00' + hex;
  12280. }
  12281. var bytes = forge$k.util.hexToBytes(hex);
  12282. // ensure integer is minimally-encoded
  12283. if(bytes.length > 1 &&
  12284. // leading 0x00 for positive integer
  12285. ((bytes.charCodeAt(0) === 0 &&
  12286. (bytes.charCodeAt(1) & 0x80) === 0) ||
  12287. // leading 0xFF for negative integer
  12288. (bytes.charCodeAt(0) === 0xFF &&
  12289. (bytes.charCodeAt(1) & 0x80) === 0x80))) {
  12290. return bytes.substr(1);
  12291. }
  12292. return bytes;
  12293. }
  12294. /**
  12295. * Returns the required number of Miller-Rabin tests to generate a
  12296. * prime with an error probability of (1/2)^80.
  12297. *
  12298. * See Handbook of Applied Cryptography Chapter 4, Table 4.4.
  12299. *
  12300. * @param bits the bit size.
  12301. *
  12302. * @return the required number of iterations.
  12303. */
  12304. function _getMillerRabinTests(bits) {
  12305. if(bits <= 100) return 27;
  12306. if(bits <= 150) return 18;
  12307. if(bits <= 200) return 15;
  12308. if(bits <= 250) return 12;
  12309. if(bits <= 300) return 9;
  12310. if(bits <= 350) return 8;
  12311. if(bits <= 400) return 7;
  12312. if(bits <= 500) return 6;
  12313. if(bits <= 600) return 5;
  12314. if(bits <= 800) return 4;
  12315. if(bits <= 1250) return 3;
  12316. return 2;
  12317. }
  12318. /**
  12319. * Performs feature detection on the Node crypto interface.
  12320. *
  12321. * @param fn the feature (function) to detect.
  12322. *
  12323. * @return true if detected, false if not.
  12324. */
  12325. function _detectNodeCrypto(fn) {
  12326. return forge$k.util.isNodejs && typeof _crypto[fn] === 'function';
  12327. }
  12328. /**
  12329. * Performs feature detection on the SubtleCrypto interface.
  12330. *
  12331. * @param fn the feature (function) to detect.
  12332. *
  12333. * @return true if detected, false if not.
  12334. */
  12335. function _detectSubtleCrypto(fn) {
  12336. return (typeof util.globalScope !== 'undefined' &&
  12337. typeof util.globalScope.crypto === 'object' &&
  12338. typeof util.globalScope.crypto.subtle === 'object' &&
  12339. typeof util.globalScope.crypto.subtle[fn] === 'function');
  12340. }
  12341. /**
  12342. * Performs feature detection on the deprecated Microsoft Internet Explorer
  12343. * outdated SubtleCrypto interface. This function should only be used after
  12344. * checking for the modern, standard SubtleCrypto interface.
  12345. *
  12346. * @param fn the feature (function) to detect.
  12347. *
  12348. * @return true if detected, false if not.
  12349. */
  12350. function _detectSubtleMsCrypto(fn) {
  12351. return (typeof util.globalScope !== 'undefined' &&
  12352. typeof util.globalScope.msCrypto === 'object' &&
  12353. typeof util.globalScope.msCrypto.subtle === 'object' &&
  12354. typeof util.globalScope.msCrypto.subtle[fn] === 'function');
  12355. }
  12356. function _intToUint8Array(x) {
  12357. var bytes = forge$k.util.hexToBytes(x.toString(16));
  12358. var buffer = new Uint8Array(bytes.length);
  12359. for(var i = 0; i < bytes.length; ++i) {
  12360. buffer[i] = bytes.charCodeAt(i);
  12361. }
  12362. return buffer;
  12363. }
  12364. /**
  12365. * Password-based encryption functions.
  12366. *
  12367. * @author Dave Longley
  12368. * @author Stefan Siegl <stesie@brokenpipe.de>
  12369. *
  12370. * Copyright (c) 2010-2013 Digital Bazaar, Inc.
  12371. * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>
  12372. *
  12373. * An EncryptedPrivateKeyInfo:
  12374. *
  12375. * EncryptedPrivateKeyInfo ::= SEQUENCE {
  12376. * encryptionAlgorithm EncryptionAlgorithmIdentifier,
  12377. * encryptedData EncryptedData }
  12378. *
  12379. * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
  12380. *
  12381. * EncryptedData ::= OCTET STRING
  12382. */
  12383. var forge$j = forge$F;
  12384. // shortcut for asn.1 API
  12385. var asn1$6 = forge$j.asn1;
  12386. /* Password-based encryption implementation. */
  12387. var pki$3 = forge$j.pki = forge$j.pki || {};
  12388. pki$3.pbe = forge$j.pbe = forge$j.pbe || {};
  12389. var oids$1 = pki$3.oids;
  12390. // validator for an EncryptedPrivateKeyInfo structure
  12391. // Note: Currently only works w/algorithm params
  12392. var encryptedPrivateKeyValidator = {
  12393. name: 'EncryptedPrivateKeyInfo',
  12394. tagClass: asn1$6.Class.UNIVERSAL,
  12395. type: asn1$6.Type.SEQUENCE,
  12396. constructed: true,
  12397. value: [{
  12398. name: 'EncryptedPrivateKeyInfo.encryptionAlgorithm',
  12399. tagClass: asn1$6.Class.UNIVERSAL,
  12400. type: asn1$6.Type.SEQUENCE,
  12401. constructed: true,
  12402. value: [{
  12403. name: 'AlgorithmIdentifier.algorithm',
  12404. tagClass: asn1$6.Class.UNIVERSAL,
  12405. type: asn1$6.Type.OID,
  12406. constructed: false,
  12407. capture: 'encryptionOid'
  12408. }, {
  12409. name: 'AlgorithmIdentifier.parameters',
  12410. tagClass: asn1$6.Class.UNIVERSAL,
  12411. type: asn1$6.Type.SEQUENCE,
  12412. constructed: true,
  12413. captureAsn1: 'encryptionParams'
  12414. }]
  12415. }, {
  12416. // encryptedData
  12417. name: 'EncryptedPrivateKeyInfo.encryptedData',
  12418. tagClass: asn1$6.Class.UNIVERSAL,
  12419. type: asn1$6.Type.OCTETSTRING,
  12420. constructed: false,
  12421. capture: 'encryptedData'
  12422. }]
  12423. };
  12424. // validator for a PBES2Algorithms structure
  12425. // Note: Currently only works w/PBKDF2 + AES encryption schemes
  12426. var PBES2AlgorithmsValidator = {
  12427. name: 'PBES2Algorithms',
  12428. tagClass: asn1$6.Class.UNIVERSAL,
  12429. type: asn1$6.Type.SEQUENCE,
  12430. constructed: true,
  12431. value: [{
  12432. name: 'PBES2Algorithms.keyDerivationFunc',
  12433. tagClass: asn1$6.Class.UNIVERSAL,
  12434. type: asn1$6.Type.SEQUENCE,
  12435. constructed: true,
  12436. value: [{
  12437. name: 'PBES2Algorithms.keyDerivationFunc.oid',
  12438. tagClass: asn1$6.Class.UNIVERSAL,
  12439. type: asn1$6.Type.OID,
  12440. constructed: false,
  12441. capture: 'kdfOid'
  12442. }, {
  12443. name: 'PBES2Algorithms.params',
  12444. tagClass: asn1$6.Class.UNIVERSAL,
  12445. type: asn1$6.Type.SEQUENCE,
  12446. constructed: true,
  12447. value: [{
  12448. name: 'PBES2Algorithms.params.salt',
  12449. tagClass: asn1$6.Class.UNIVERSAL,
  12450. type: asn1$6.Type.OCTETSTRING,
  12451. constructed: false,
  12452. capture: 'kdfSalt'
  12453. }, {
  12454. name: 'PBES2Algorithms.params.iterationCount',
  12455. tagClass: asn1$6.Class.UNIVERSAL,
  12456. type: asn1$6.Type.INTEGER,
  12457. constructed: false,
  12458. capture: 'kdfIterationCount'
  12459. }, {
  12460. name: 'PBES2Algorithms.params.keyLength',
  12461. tagClass: asn1$6.Class.UNIVERSAL,
  12462. type: asn1$6.Type.INTEGER,
  12463. constructed: false,
  12464. optional: true,
  12465. capture: 'keyLength'
  12466. }, {
  12467. // prf
  12468. name: 'PBES2Algorithms.params.prf',
  12469. tagClass: asn1$6.Class.UNIVERSAL,
  12470. type: asn1$6.Type.SEQUENCE,
  12471. constructed: true,
  12472. optional: true,
  12473. value: [{
  12474. name: 'PBES2Algorithms.params.prf.algorithm',
  12475. tagClass: asn1$6.Class.UNIVERSAL,
  12476. type: asn1$6.Type.OID,
  12477. constructed: false,
  12478. capture: 'prfOid'
  12479. }]
  12480. }]
  12481. }]
  12482. }, {
  12483. name: 'PBES2Algorithms.encryptionScheme',
  12484. tagClass: asn1$6.Class.UNIVERSAL,
  12485. type: asn1$6.Type.SEQUENCE,
  12486. constructed: true,
  12487. value: [{
  12488. name: 'PBES2Algorithms.encryptionScheme.oid',
  12489. tagClass: asn1$6.Class.UNIVERSAL,
  12490. type: asn1$6.Type.OID,
  12491. constructed: false,
  12492. capture: 'encOid'
  12493. }, {
  12494. name: 'PBES2Algorithms.encryptionScheme.iv',
  12495. tagClass: asn1$6.Class.UNIVERSAL,
  12496. type: asn1$6.Type.OCTETSTRING,
  12497. constructed: false,
  12498. capture: 'encIv'
  12499. }]
  12500. }]
  12501. };
  12502. var pkcs12PbeParamsValidator = {
  12503. name: 'pkcs-12PbeParams',
  12504. tagClass: asn1$6.Class.UNIVERSAL,
  12505. type: asn1$6.Type.SEQUENCE,
  12506. constructed: true,
  12507. value: [{
  12508. name: 'pkcs-12PbeParams.salt',
  12509. tagClass: asn1$6.Class.UNIVERSAL,
  12510. type: asn1$6.Type.OCTETSTRING,
  12511. constructed: false,
  12512. capture: 'salt'
  12513. }, {
  12514. name: 'pkcs-12PbeParams.iterations',
  12515. tagClass: asn1$6.Class.UNIVERSAL,
  12516. type: asn1$6.Type.INTEGER,
  12517. constructed: false,
  12518. capture: 'iterations'
  12519. }]
  12520. };
  12521. /**
  12522. * Encrypts a ASN.1 PrivateKeyInfo object, producing an EncryptedPrivateKeyInfo.
  12523. *
  12524. * PBES2Algorithms ALGORITHM-IDENTIFIER ::=
  12525. * { {PBES2-params IDENTIFIED BY id-PBES2}, ...}
  12526. *
  12527. * id-PBES2 OBJECT IDENTIFIER ::= {pkcs-5 13}
  12528. *
  12529. * PBES2-params ::= SEQUENCE {
  12530. * keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},
  12531. * encryptionScheme AlgorithmIdentifier {{PBES2-Encs}}
  12532. * }
  12533. *
  12534. * PBES2-KDFs ALGORITHM-IDENTIFIER ::=
  12535. * { {PBKDF2-params IDENTIFIED BY id-PBKDF2}, ... }
  12536. *
  12537. * PBES2-Encs ALGORITHM-IDENTIFIER ::= { ... }
  12538. *
  12539. * PBKDF2-params ::= SEQUENCE {
  12540. * salt CHOICE {
  12541. * specified OCTET STRING,
  12542. * otherSource AlgorithmIdentifier {{PBKDF2-SaltSources}}
  12543. * },
  12544. * iterationCount INTEGER (1..MAX),
  12545. * keyLength INTEGER (1..MAX) OPTIONAL,
  12546. * prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1
  12547. * }
  12548. *
  12549. * @param obj the ASN.1 PrivateKeyInfo object.
  12550. * @param password the password to encrypt with.
  12551. * @param options:
  12552. * algorithm the encryption algorithm to use
  12553. * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'.
  12554. * count the iteration count to use.
  12555. * saltSize the salt size to use.
  12556. * prfAlgorithm the PRF message digest algorithm to use
  12557. * ('sha1', 'sha224', 'sha256', 'sha384', 'sha512')
  12558. *
  12559. * @return the ASN.1 EncryptedPrivateKeyInfo.
  12560. */
  12561. pki$3.encryptPrivateKeyInfo = function(obj, password, options) {
  12562. // set default options
  12563. options = options || {};
  12564. options.saltSize = options.saltSize || 8;
  12565. options.count = options.count || 2048;
  12566. options.algorithm = options.algorithm || 'aes128';
  12567. options.prfAlgorithm = options.prfAlgorithm || 'sha1';
  12568. // generate PBE params
  12569. var salt = forge$j.random.getBytesSync(options.saltSize);
  12570. var count = options.count;
  12571. var countBytes = asn1$6.integerToDer(count);
  12572. var dkLen;
  12573. var encryptionAlgorithm;
  12574. var encryptedData;
  12575. if(options.algorithm.indexOf('aes') === 0 || options.algorithm === 'des') {
  12576. // do PBES2
  12577. var ivLen, encOid, cipherFn;
  12578. switch(options.algorithm) {
  12579. case 'aes128':
  12580. dkLen = 16;
  12581. ivLen = 16;
  12582. encOid = oids$1['aes128-CBC'];
  12583. cipherFn = forge$j.aes.createEncryptionCipher;
  12584. break;
  12585. case 'aes192':
  12586. dkLen = 24;
  12587. ivLen = 16;
  12588. encOid = oids$1['aes192-CBC'];
  12589. cipherFn = forge$j.aes.createEncryptionCipher;
  12590. break;
  12591. case 'aes256':
  12592. dkLen = 32;
  12593. ivLen = 16;
  12594. encOid = oids$1['aes256-CBC'];
  12595. cipherFn = forge$j.aes.createEncryptionCipher;
  12596. break;
  12597. case 'des':
  12598. dkLen = 8;
  12599. ivLen = 8;
  12600. encOid = oids$1['desCBC'];
  12601. cipherFn = forge$j.des.createEncryptionCipher;
  12602. break;
  12603. default:
  12604. var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.');
  12605. error.algorithm = options.algorithm;
  12606. throw error;
  12607. }
  12608. // get PRF message digest
  12609. var prfAlgorithm = 'hmacWith' + options.prfAlgorithm.toUpperCase();
  12610. var md = prfAlgorithmToMessageDigest(prfAlgorithm);
  12611. // encrypt private key using pbe SHA-1 and AES/DES
  12612. var dk = forge$j.pkcs5.pbkdf2(password, salt, count, dkLen, md);
  12613. var iv = forge$j.random.getBytesSync(ivLen);
  12614. var cipher = cipherFn(dk);
  12615. cipher.start(iv);
  12616. cipher.update(asn1$6.toDer(obj));
  12617. cipher.finish();
  12618. encryptedData = cipher.output.getBytes();
  12619. // get PBKDF2-params
  12620. var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm);
  12621. encryptionAlgorithm = asn1$6.create(
  12622. asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [
  12623. asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.OID, false,
  12624. asn1$6.oidToDer(oids$1['pkcs5PBES2']).getBytes()),
  12625. asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [
  12626. // keyDerivationFunc
  12627. asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [
  12628. asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.OID, false,
  12629. asn1$6.oidToDer(oids$1['pkcs5PBKDF2']).getBytes()),
  12630. // PBKDF2-params
  12631. params
  12632. ]),
  12633. // encryptionScheme
  12634. asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [
  12635. asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.OID, false,
  12636. asn1$6.oidToDer(encOid).getBytes()),
  12637. // iv
  12638. asn1$6.create(
  12639. asn1$6.Class.UNIVERSAL, asn1$6.Type.OCTETSTRING, false, iv)
  12640. ])
  12641. ])
  12642. ]);
  12643. } else if(options.algorithm === '3des') {
  12644. // Do PKCS12 PBE
  12645. dkLen = 24;
  12646. var saltBytes = new forge$j.util.ByteBuffer(salt);
  12647. var dk = pki$3.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen);
  12648. var iv = pki$3.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen);
  12649. var cipher = forge$j.des.createEncryptionCipher(dk);
  12650. cipher.start(iv);
  12651. cipher.update(asn1$6.toDer(obj));
  12652. cipher.finish();
  12653. encryptedData = cipher.output.getBytes();
  12654. encryptionAlgorithm = asn1$6.create(
  12655. asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [
  12656. asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.OID, false,
  12657. asn1$6.oidToDer(oids$1['pbeWithSHAAnd3-KeyTripleDES-CBC']).getBytes()),
  12658. // pkcs-12PbeParams
  12659. asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [
  12660. // salt
  12661. asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.OCTETSTRING, false, salt),
  12662. // iteration count
  12663. asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.INTEGER, false,
  12664. countBytes.getBytes())
  12665. ])
  12666. ]);
  12667. } else {
  12668. var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.');
  12669. error.algorithm = options.algorithm;
  12670. throw error;
  12671. }
  12672. // EncryptedPrivateKeyInfo
  12673. var rval = asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [
  12674. // encryptionAlgorithm
  12675. encryptionAlgorithm,
  12676. // encryptedData
  12677. asn1$6.create(
  12678. asn1$6.Class.UNIVERSAL, asn1$6.Type.OCTETSTRING, false, encryptedData)
  12679. ]);
  12680. return rval;
  12681. };
  12682. /**
  12683. * Decrypts a ASN.1 PrivateKeyInfo object.
  12684. *
  12685. * @param obj the ASN.1 EncryptedPrivateKeyInfo object.
  12686. * @param password the password to decrypt with.
  12687. *
  12688. * @return the ASN.1 PrivateKeyInfo on success, null on failure.
  12689. */
  12690. pki$3.decryptPrivateKeyInfo = function(obj, password) {
  12691. var rval = null;
  12692. // get PBE params
  12693. var capture = {};
  12694. var errors = [];
  12695. if(!asn1$6.validate(obj, encryptedPrivateKeyValidator, capture, errors)) {
  12696. var error = new Error('Cannot read encrypted private key. ' +
  12697. 'ASN.1 object is not a supported EncryptedPrivateKeyInfo.');
  12698. error.errors = errors;
  12699. throw error;
  12700. }
  12701. // get cipher
  12702. var oid = asn1$6.derToOid(capture.encryptionOid);
  12703. var cipher = pki$3.pbe.getCipher(oid, capture.encryptionParams, password);
  12704. // get encrypted data
  12705. var encrypted = forge$j.util.createBuffer(capture.encryptedData);
  12706. cipher.update(encrypted);
  12707. if(cipher.finish()) {
  12708. rval = asn1$6.fromDer(cipher.output);
  12709. }
  12710. return rval;
  12711. };
  12712. /**
  12713. * Converts a EncryptedPrivateKeyInfo to PEM format.
  12714. *
  12715. * @param epki the EncryptedPrivateKeyInfo.
  12716. * @param maxline the maximum characters per line, defaults to 64.
  12717. *
  12718. * @return the PEM-formatted encrypted private key.
  12719. */
  12720. pki$3.encryptedPrivateKeyToPem = function(epki, maxline) {
  12721. // convert to DER, then PEM-encode
  12722. var msg = {
  12723. type: 'ENCRYPTED PRIVATE KEY',
  12724. body: asn1$6.toDer(epki).getBytes()
  12725. };
  12726. return forge$j.pem.encode(msg, {maxline: maxline});
  12727. };
  12728. /**
  12729. * Converts a PEM-encoded EncryptedPrivateKeyInfo to ASN.1 format. Decryption
  12730. * is not performed.
  12731. *
  12732. * @param pem the EncryptedPrivateKeyInfo in PEM-format.
  12733. *
  12734. * @return the ASN.1 EncryptedPrivateKeyInfo.
  12735. */
  12736. pki$3.encryptedPrivateKeyFromPem = function(pem) {
  12737. var msg = forge$j.pem.decode(pem)[0];
  12738. if(msg.type !== 'ENCRYPTED PRIVATE KEY') {
  12739. var error = new Error('Could not convert encrypted private key from PEM; ' +
  12740. 'PEM header type is "ENCRYPTED PRIVATE KEY".');
  12741. error.headerType = msg.type;
  12742. throw error;
  12743. }
  12744. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  12745. throw new Error('Could not convert encrypted private key from PEM; ' +
  12746. 'PEM is encrypted.');
  12747. }
  12748. // convert DER to ASN.1 object
  12749. return asn1$6.fromDer(msg.body);
  12750. };
  12751. /**
  12752. * Encrypts an RSA private key. By default, the key will be wrapped in
  12753. * a PrivateKeyInfo and encrypted to produce a PKCS#8 EncryptedPrivateKeyInfo.
  12754. * This is the standard, preferred way to encrypt a private key.
  12755. *
  12756. * To produce a non-standard PEM-encrypted private key that uses encapsulated
  12757. * headers to indicate the encryption algorithm (old-style non-PKCS#8 OpenSSL
  12758. * private key encryption), set the 'legacy' option to true. Note: Using this
  12759. * option will cause the iteration count to be forced to 1.
  12760. *
  12761. * Note: The 'des' algorithm is supported, but it is not considered to be
  12762. * secure because it only uses a single 56-bit key. If possible, it is highly
  12763. * recommended that a different algorithm be used.
  12764. *
  12765. * @param rsaKey the RSA key to encrypt.
  12766. * @param password the password to use.
  12767. * @param options:
  12768. * algorithm: the encryption algorithm to use
  12769. * ('aes128', 'aes192', 'aes256', '3des', 'des').
  12770. * count: the iteration count to use.
  12771. * saltSize: the salt size to use.
  12772. * legacy: output an old non-PKCS#8 PEM-encrypted+encapsulated
  12773. * headers (DEK-Info) private key.
  12774. *
  12775. * @return the PEM-encoded ASN.1 EncryptedPrivateKeyInfo.
  12776. */
  12777. pki$3.encryptRsaPrivateKey = function(rsaKey, password, options) {
  12778. // standard PKCS#8
  12779. options = options || {};
  12780. if(!options.legacy) {
  12781. // encrypt PrivateKeyInfo
  12782. var rval = pki$3.wrapRsaPrivateKey(pki$3.privateKeyToAsn1(rsaKey));
  12783. rval = pki$3.encryptPrivateKeyInfo(rval, password, options);
  12784. return pki$3.encryptedPrivateKeyToPem(rval);
  12785. }
  12786. // legacy non-PKCS#8
  12787. var algorithm;
  12788. var iv;
  12789. var dkLen;
  12790. var cipherFn;
  12791. switch(options.algorithm) {
  12792. case 'aes128':
  12793. algorithm = 'AES-128-CBC';
  12794. dkLen = 16;
  12795. iv = forge$j.random.getBytesSync(16);
  12796. cipherFn = forge$j.aes.createEncryptionCipher;
  12797. break;
  12798. case 'aes192':
  12799. algorithm = 'AES-192-CBC';
  12800. dkLen = 24;
  12801. iv = forge$j.random.getBytesSync(16);
  12802. cipherFn = forge$j.aes.createEncryptionCipher;
  12803. break;
  12804. case 'aes256':
  12805. algorithm = 'AES-256-CBC';
  12806. dkLen = 32;
  12807. iv = forge$j.random.getBytesSync(16);
  12808. cipherFn = forge$j.aes.createEncryptionCipher;
  12809. break;
  12810. case '3des':
  12811. algorithm = 'DES-EDE3-CBC';
  12812. dkLen = 24;
  12813. iv = forge$j.random.getBytesSync(8);
  12814. cipherFn = forge$j.des.createEncryptionCipher;
  12815. break;
  12816. case 'des':
  12817. algorithm = 'DES-CBC';
  12818. dkLen = 8;
  12819. iv = forge$j.random.getBytesSync(8);
  12820. cipherFn = forge$j.des.createEncryptionCipher;
  12821. break;
  12822. default:
  12823. var error = new Error('Could not encrypt RSA private key; unsupported ' +
  12824. 'encryption algorithm "' + options.algorithm + '".');
  12825. error.algorithm = options.algorithm;
  12826. throw error;
  12827. }
  12828. // encrypt private key using OpenSSL legacy key derivation
  12829. var dk = forge$j.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);
  12830. var cipher = cipherFn(dk);
  12831. cipher.start(iv);
  12832. cipher.update(asn1$6.toDer(pki$3.privateKeyToAsn1(rsaKey)));
  12833. cipher.finish();
  12834. var msg = {
  12835. type: 'RSA PRIVATE KEY',
  12836. procType: {
  12837. version: '4',
  12838. type: 'ENCRYPTED'
  12839. },
  12840. dekInfo: {
  12841. algorithm: algorithm,
  12842. parameters: forge$j.util.bytesToHex(iv).toUpperCase()
  12843. },
  12844. body: cipher.output.getBytes()
  12845. };
  12846. return forge$j.pem.encode(msg);
  12847. };
  12848. /**
  12849. * Decrypts an RSA private key.
  12850. *
  12851. * @param pem the PEM-formatted EncryptedPrivateKeyInfo to decrypt.
  12852. * @param password the password to use.
  12853. *
  12854. * @return the RSA key on success, null on failure.
  12855. */
  12856. pki$3.decryptRsaPrivateKey = function(pem, password) {
  12857. var rval = null;
  12858. var msg = forge$j.pem.decode(pem)[0];
  12859. if(msg.type !== 'ENCRYPTED PRIVATE KEY' &&
  12860. msg.type !== 'PRIVATE KEY' &&
  12861. msg.type !== 'RSA PRIVATE KEY') {
  12862. var error = new Error('Could not convert private key from PEM; PEM header type ' +
  12863. 'is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');
  12864. error.headerType = error;
  12865. throw error;
  12866. }
  12867. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  12868. var dkLen;
  12869. var cipherFn;
  12870. switch(msg.dekInfo.algorithm) {
  12871. case 'DES-CBC':
  12872. dkLen = 8;
  12873. cipherFn = forge$j.des.createDecryptionCipher;
  12874. break;
  12875. case 'DES-EDE3-CBC':
  12876. dkLen = 24;
  12877. cipherFn = forge$j.des.createDecryptionCipher;
  12878. break;
  12879. case 'AES-128-CBC':
  12880. dkLen = 16;
  12881. cipherFn = forge$j.aes.createDecryptionCipher;
  12882. break;
  12883. case 'AES-192-CBC':
  12884. dkLen = 24;
  12885. cipherFn = forge$j.aes.createDecryptionCipher;
  12886. break;
  12887. case 'AES-256-CBC':
  12888. dkLen = 32;
  12889. cipherFn = forge$j.aes.createDecryptionCipher;
  12890. break;
  12891. case 'RC2-40-CBC':
  12892. dkLen = 5;
  12893. cipherFn = function(key) {
  12894. return forge$j.rc2.createDecryptionCipher(key, 40);
  12895. };
  12896. break;
  12897. case 'RC2-64-CBC':
  12898. dkLen = 8;
  12899. cipherFn = function(key) {
  12900. return forge$j.rc2.createDecryptionCipher(key, 64);
  12901. };
  12902. break;
  12903. case 'RC2-128-CBC':
  12904. dkLen = 16;
  12905. cipherFn = function(key) {
  12906. return forge$j.rc2.createDecryptionCipher(key, 128);
  12907. };
  12908. break;
  12909. default:
  12910. var error = new Error('Could not decrypt private key; unsupported ' +
  12911. 'encryption algorithm "' + msg.dekInfo.algorithm + '".');
  12912. error.algorithm = msg.dekInfo.algorithm;
  12913. throw error;
  12914. }
  12915. // use OpenSSL legacy key derivation
  12916. var iv = forge$j.util.hexToBytes(msg.dekInfo.parameters);
  12917. var dk = forge$j.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);
  12918. var cipher = cipherFn(dk);
  12919. cipher.start(iv);
  12920. cipher.update(forge$j.util.createBuffer(msg.body));
  12921. if(cipher.finish()) {
  12922. rval = cipher.output.getBytes();
  12923. } else {
  12924. return rval;
  12925. }
  12926. } else {
  12927. rval = msg.body;
  12928. }
  12929. if(msg.type === 'ENCRYPTED PRIVATE KEY') {
  12930. rval = pki$3.decryptPrivateKeyInfo(asn1$6.fromDer(rval), password);
  12931. } else {
  12932. // decryption already performed above
  12933. rval = asn1$6.fromDer(rval);
  12934. }
  12935. if(rval !== null) {
  12936. rval = pki$3.privateKeyFromAsn1(rval);
  12937. }
  12938. return rval;
  12939. };
  12940. /**
  12941. * Derives a PKCS#12 key.
  12942. *
  12943. * @param password the password to derive the key material from, null or
  12944. * undefined for none.
  12945. * @param salt the salt, as a ByteBuffer, to use.
  12946. * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC).
  12947. * @param iter the iteration count.
  12948. * @param n the number of bytes to derive from the password.
  12949. * @param md the message digest to use, defaults to SHA-1.
  12950. *
  12951. * @return a ByteBuffer with the bytes derived from the password.
  12952. */
  12953. pki$3.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md) {
  12954. var j, l;
  12955. if(typeof md === 'undefined' || md === null) {
  12956. if(!('sha1' in forge$j.md)) {
  12957. throw new Error('"sha1" hash algorithm unavailable.');
  12958. }
  12959. md = forge$j.md.sha1.create();
  12960. }
  12961. var u = md.digestLength;
  12962. var v = md.blockLength;
  12963. var result = new forge$j.util.ByteBuffer();
  12964. /* Convert password to Unicode byte buffer + trailing 0-byte. */
  12965. var passBuf = new forge$j.util.ByteBuffer();
  12966. if(password !== null && password !== undefined) {
  12967. for(l = 0; l < password.length; l++) {
  12968. passBuf.putInt16(password.charCodeAt(l));
  12969. }
  12970. passBuf.putInt16(0);
  12971. }
  12972. /* Length of salt and password in BYTES. */
  12973. var p = passBuf.length();
  12974. var s = salt.length();
  12975. /* 1. Construct a string, D (the "diversifier"), by concatenating
  12976. v copies of ID. */
  12977. var D = new forge$j.util.ByteBuffer();
  12978. D.fillWithByte(id, v);
  12979. /* 2. Concatenate copies of the salt together to create a string S of length
  12980. v * ceil(s / v) bytes (the final copy of the salt may be trunacted
  12981. to create S).
  12982. Note that if the salt is the empty string, then so is S. */
  12983. var Slen = v * Math.ceil(s / v);
  12984. var S = new forge$j.util.ByteBuffer();
  12985. for(l = 0; l < Slen; l++) {
  12986. S.putByte(salt.at(l % s));
  12987. }
  12988. /* 3. Concatenate copies of the password together to create a string P of
  12989. length v * ceil(p / v) bytes (the final copy of the password may be
  12990. truncated to create P).
  12991. Note that if the password is the empty string, then so is P. */
  12992. var Plen = v * Math.ceil(p / v);
  12993. var P = new forge$j.util.ByteBuffer();
  12994. for(l = 0; l < Plen; l++) {
  12995. P.putByte(passBuf.at(l % p));
  12996. }
  12997. /* 4. Set I=S||P to be the concatenation of S and P. */
  12998. var I = S;
  12999. I.putBuffer(P);
  13000. /* 5. Set c=ceil(n / u). */
  13001. var c = Math.ceil(n / u);
  13002. /* 6. For i=1, 2, ..., c, do the following: */
  13003. for(var i = 1; i <= c; i++) {
  13004. /* a) Set Ai=H^r(D||I). (l.e. the rth hash of D||I, H(H(H(...H(D||I)))) */
  13005. var buf = new forge$j.util.ByteBuffer();
  13006. buf.putBytes(D.bytes());
  13007. buf.putBytes(I.bytes());
  13008. for(var round = 0; round < iter; round++) {
  13009. md.start();
  13010. md.update(buf.getBytes());
  13011. buf = md.digest();
  13012. }
  13013. /* b) Concatenate copies of Ai to create a string B of length v bytes (the
  13014. final copy of Ai may be truncated to create B). */
  13015. var B = new forge$j.util.ByteBuffer();
  13016. for(l = 0; l < v; l++) {
  13017. B.putByte(buf.at(l % u));
  13018. }
  13019. /* c) Treating I as a concatenation I0, I1, ..., Ik-1 of v-byte blocks,
  13020. where k=ceil(s / v) + ceil(p / v), modify I by setting
  13021. Ij=(Ij+B+1) mod 2v for each j. */
  13022. var k = Math.ceil(s / v) + Math.ceil(p / v);
  13023. var Inew = new forge$j.util.ByteBuffer();
  13024. for(j = 0; j < k; j++) {
  13025. var chunk = new forge$j.util.ByteBuffer(I.getBytes(v));
  13026. var x = 0x1ff;
  13027. for(l = B.length() - 1; l >= 0; l--) {
  13028. x = x >> 8;
  13029. x += B.at(l) + chunk.at(l);
  13030. chunk.setAt(l, x & 0xff);
  13031. }
  13032. Inew.putBuffer(chunk);
  13033. }
  13034. I = Inew;
  13035. /* Add Ai to A. */
  13036. result.putBuffer(buf);
  13037. }
  13038. result.truncate(result.length() - n);
  13039. return result;
  13040. };
  13041. /**
  13042. * Get new Forge cipher object instance.
  13043. *
  13044. * @param oid the OID (in string notation).
  13045. * @param params the ASN.1 params object.
  13046. * @param password the password to decrypt with.
  13047. *
  13048. * @return new cipher object instance.
  13049. */
  13050. pki$3.pbe.getCipher = function(oid, params, password) {
  13051. switch(oid) {
  13052. case pki$3.oids['pkcs5PBES2']:
  13053. return pki$3.pbe.getCipherForPBES2(oid, params, password);
  13054. case pki$3.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']:
  13055. case pki$3.oids['pbewithSHAAnd40BitRC2-CBC']:
  13056. return pki$3.pbe.getCipherForPKCS12PBE(oid, params, password);
  13057. default:
  13058. var error = new Error('Cannot read encrypted PBE data block. Unsupported OID.');
  13059. error.oid = oid;
  13060. error.supportedOids = [
  13061. 'pkcs5PBES2',
  13062. 'pbeWithSHAAnd3-KeyTripleDES-CBC',
  13063. 'pbewithSHAAnd40BitRC2-CBC'
  13064. ];
  13065. throw error;
  13066. }
  13067. };
  13068. /**
  13069. * Get new Forge cipher object instance according to PBES2 params block.
  13070. *
  13071. * The returned cipher instance is already started using the IV
  13072. * from PBES2 parameter block.
  13073. *
  13074. * @param oid the PKCS#5 PBKDF2 OID (in string notation).
  13075. * @param params the ASN.1 PBES2-params object.
  13076. * @param password the password to decrypt with.
  13077. *
  13078. * @return new cipher object instance.
  13079. */
  13080. pki$3.pbe.getCipherForPBES2 = function(oid, params, password) {
  13081. // get PBE params
  13082. var capture = {};
  13083. var errors = [];
  13084. if(!asn1$6.validate(params, PBES2AlgorithmsValidator, capture, errors)) {
  13085. var error = new Error('Cannot read password-based-encryption algorithm ' +
  13086. 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.');
  13087. error.errors = errors;
  13088. throw error;
  13089. }
  13090. // check oids
  13091. oid = asn1$6.derToOid(capture.kdfOid);
  13092. if(oid !== pki$3.oids['pkcs5PBKDF2']) {
  13093. var error = new Error('Cannot read encrypted private key. ' +
  13094. 'Unsupported key derivation function OID.');
  13095. error.oid = oid;
  13096. error.supportedOids = ['pkcs5PBKDF2'];
  13097. throw error;
  13098. }
  13099. oid = asn1$6.derToOid(capture.encOid);
  13100. if(oid !== pki$3.oids['aes128-CBC'] &&
  13101. oid !== pki$3.oids['aes192-CBC'] &&
  13102. oid !== pki$3.oids['aes256-CBC'] &&
  13103. oid !== pki$3.oids['des-EDE3-CBC'] &&
  13104. oid !== pki$3.oids['desCBC']) {
  13105. var error = new Error('Cannot read encrypted private key. ' +
  13106. 'Unsupported encryption scheme OID.');
  13107. error.oid = oid;
  13108. error.supportedOids = [
  13109. 'aes128-CBC', 'aes192-CBC', 'aes256-CBC', 'des-EDE3-CBC', 'desCBC'];
  13110. throw error;
  13111. }
  13112. // set PBE params
  13113. var salt = capture.kdfSalt;
  13114. var count = forge$j.util.createBuffer(capture.kdfIterationCount);
  13115. count = count.getInt(count.length() << 3);
  13116. var dkLen;
  13117. var cipherFn;
  13118. switch(pki$3.oids[oid]) {
  13119. case 'aes128-CBC':
  13120. dkLen = 16;
  13121. cipherFn = forge$j.aes.createDecryptionCipher;
  13122. break;
  13123. case 'aes192-CBC':
  13124. dkLen = 24;
  13125. cipherFn = forge$j.aes.createDecryptionCipher;
  13126. break;
  13127. case 'aes256-CBC':
  13128. dkLen = 32;
  13129. cipherFn = forge$j.aes.createDecryptionCipher;
  13130. break;
  13131. case 'des-EDE3-CBC':
  13132. dkLen = 24;
  13133. cipherFn = forge$j.des.createDecryptionCipher;
  13134. break;
  13135. case 'desCBC':
  13136. dkLen = 8;
  13137. cipherFn = forge$j.des.createDecryptionCipher;
  13138. break;
  13139. }
  13140. // get PRF message digest
  13141. var md = prfOidToMessageDigest(capture.prfOid);
  13142. // decrypt private key using pbe with chosen PRF and AES/DES
  13143. var dk = forge$j.pkcs5.pbkdf2(password, salt, count, dkLen, md);
  13144. var iv = capture.encIv;
  13145. var cipher = cipherFn(dk);
  13146. cipher.start(iv);
  13147. return cipher;
  13148. };
  13149. /**
  13150. * Get new Forge cipher object instance for PKCS#12 PBE.
  13151. *
  13152. * The returned cipher instance is already started using the key & IV
  13153. * derived from the provided password and PKCS#12 PBE salt.
  13154. *
  13155. * @param oid The PKCS#12 PBE OID (in string notation).
  13156. * @param params The ASN.1 PKCS#12 PBE-params object.
  13157. * @param password The password to decrypt with.
  13158. *
  13159. * @return the new cipher object instance.
  13160. */
  13161. pki$3.pbe.getCipherForPKCS12PBE = function(oid, params, password) {
  13162. // get PBE params
  13163. var capture = {};
  13164. var errors = [];
  13165. if(!asn1$6.validate(params, pkcs12PbeParamsValidator, capture, errors)) {
  13166. var error = new Error('Cannot read password-based-encryption algorithm ' +
  13167. 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.');
  13168. error.errors = errors;
  13169. throw error;
  13170. }
  13171. var salt = forge$j.util.createBuffer(capture.salt);
  13172. var count = forge$j.util.createBuffer(capture.iterations);
  13173. count = count.getInt(count.length() << 3);
  13174. var dkLen, dIvLen, cipherFn;
  13175. switch(oid) {
  13176. case pki$3.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']:
  13177. dkLen = 24;
  13178. dIvLen = 8;
  13179. cipherFn = forge$j.des.startDecrypting;
  13180. break;
  13181. case pki$3.oids['pbewithSHAAnd40BitRC2-CBC']:
  13182. dkLen = 5;
  13183. dIvLen = 8;
  13184. cipherFn = function(key, iv) {
  13185. var cipher = forge$j.rc2.createDecryptionCipher(key, 40);
  13186. cipher.start(iv, null);
  13187. return cipher;
  13188. };
  13189. break;
  13190. default:
  13191. var error = new Error('Cannot read PKCS #12 PBE data block. Unsupported OID.');
  13192. error.oid = oid;
  13193. throw error;
  13194. }
  13195. // get PRF message digest
  13196. var md = prfOidToMessageDigest(capture.prfOid);
  13197. var key = pki$3.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md);
  13198. md.start();
  13199. var iv = pki$3.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md);
  13200. return cipherFn(key, iv);
  13201. };
  13202. /**
  13203. * OpenSSL's legacy key derivation function.
  13204. *
  13205. * See: http://www.openssl.org/docs/crypto/EVP_BytesToKey.html
  13206. *
  13207. * @param password the password to derive the key from.
  13208. * @param salt the salt to use, null for none.
  13209. * @param dkLen the number of bytes needed for the derived key.
  13210. * @param [options] the options to use:
  13211. * [md] an optional message digest object to use.
  13212. */
  13213. pki$3.pbe.opensslDeriveBytes = function(password, salt, dkLen, md) {
  13214. if(typeof md === 'undefined' || md === null) {
  13215. if(!('md5' in forge$j.md)) {
  13216. throw new Error('"md5" hash algorithm unavailable.');
  13217. }
  13218. md = forge$j.md.md5.create();
  13219. }
  13220. if(salt === null) {
  13221. salt = '';
  13222. }
  13223. var digests = [hash(md, password + salt)];
  13224. for(var length = 16, i = 1; length < dkLen; ++i, length += 16) {
  13225. digests.push(hash(md, digests[i - 1] + password + salt));
  13226. }
  13227. return digests.join('').substr(0, dkLen);
  13228. };
  13229. function hash(md, bytes) {
  13230. return md.start().update(bytes).digest().getBytes();
  13231. }
  13232. function prfOidToMessageDigest(prfOid) {
  13233. // get PRF algorithm, default to SHA-1
  13234. var prfAlgorithm;
  13235. if(!prfOid) {
  13236. prfAlgorithm = 'hmacWithSHA1';
  13237. } else {
  13238. prfAlgorithm = pki$3.oids[asn1$6.derToOid(prfOid)];
  13239. if(!prfAlgorithm) {
  13240. var error = new Error('Unsupported PRF OID.');
  13241. error.oid = prfOid;
  13242. error.supported = [
  13243. 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384',
  13244. 'hmacWithSHA512'];
  13245. throw error;
  13246. }
  13247. }
  13248. return prfAlgorithmToMessageDigest(prfAlgorithm);
  13249. }
  13250. function prfAlgorithmToMessageDigest(prfAlgorithm) {
  13251. var factory = forge$j.md;
  13252. switch(prfAlgorithm) {
  13253. case 'hmacWithSHA224':
  13254. factory = forge$j.md.sha512;
  13255. case 'hmacWithSHA1':
  13256. case 'hmacWithSHA256':
  13257. case 'hmacWithSHA384':
  13258. case 'hmacWithSHA512':
  13259. prfAlgorithm = prfAlgorithm.substr(8).toLowerCase();
  13260. break;
  13261. default:
  13262. var error = new Error('Unsupported PRF algorithm.');
  13263. error.algorithm = prfAlgorithm;
  13264. error.supported = [
  13265. 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384',
  13266. 'hmacWithSHA512'];
  13267. throw error;
  13268. }
  13269. if(!factory || !(prfAlgorithm in factory)) {
  13270. throw new Error('Unknown hash algorithm: ' + prfAlgorithm);
  13271. }
  13272. return factory[prfAlgorithm].create();
  13273. }
  13274. function createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) {
  13275. var params = asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [
  13276. // salt
  13277. asn1$6.create(
  13278. asn1$6.Class.UNIVERSAL, asn1$6.Type.OCTETSTRING, false, salt),
  13279. // iteration count
  13280. asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.INTEGER, false,
  13281. countBytes.getBytes())
  13282. ]);
  13283. // when PRF algorithm is not SHA-1 default, add key length and PRF algorithm
  13284. if(prfAlgorithm !== 'hmacWithSHA1') {
  13285. params.value.push(
  13286. // key length
  13287. asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.INTEGER, false,
  13288. forge$j.util.hexToBytes(dkLen.toString(16))),
  13289. // AlgorithmIdentifier
  13290. asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.SEQUENCE, true, [
  13291. // algorithm
  13292. asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.OID, false,
  13293. asn1$6.oidToDer(pki$3.oids[prfAlgorithm]).getBytes()),
  13294. // parameters (null)
  13295. asn1$6.create(asn1$6.Class.UNIVERSAL, asn1$6.Type.NULL, false, '')
  13296. ]));
  13297. }
  13298. return params;
  13299. }
  13300. /**
  13301. * Javascript implementation of ASN.1 validators for PKCS#7 v1.5.
  13302. *
  13303. * @author Dave Longley
  13304. * @author Stefan Siegl
  13305. *
  13306. * Copyright (c) 2012-2015 Digital Bazaar, Inc.
  13307. * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>
  13308. *
  13309. * The ASN.1 representation of PKCS#7 is as follows
  13310. * (see RFC #2315 for details, http://www.ietf.org/rfc/rfc2315.txt):
  13311. *
  13312. * A PKCS#7 message consists of a ContentInfo on root level, which may
  13313. * contain any number of further ContentInfo nested into it.
  13314. *
  13315. * ContentInfo ::= SEQUENCE {
  13316. * contentType ContentType,
  13317. * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL
  13318. * }
  13319. *
  13320. * ContentType ::= OBJECT IDENTIFIER
  13321. *
  13322. * EnvelopedData ::= SEQUENCE {
  13323. * version Version,
  13324. * recipientInfos RecipientInfos,
  13325. * encryptedContentInfo EncryptedContentInfo
  13326. * }
  13327. *
  13328. * EncryptedData ::= SEQUENCE {
  13329. * version Version,
  13330. * encryptedContentInfo EncryptedContentInfo
  13331. * }
  13332. *
  13333. * id-signedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)
  13334. * us(840) rsadsi(113549) pkcs(1) pkcs7(7) 2 }
  13335. *
  13336. * SignedData ::= SEQUENCE {
  13337. * version INTEGER,
  13338. * digestAlgorithms DigestAlgorithmIdentifiers,
  13339. * contentInfo ContentInfo,
  13340. * certificates [0] IMPLICIT Certificates OPTIONAL,
  13341. * crls [1] IMPLICIT CertificateRevocationLists OPTIONAL,
  13342. * signerInfos SignerInfos
  13343. * }
  13344. *
  13345. * SignerInfos ::= SET OF SignerInfo
  13346. *
  13347. * SignerInfo ::= SEQUENCE {
  13348. * version Version,
  13349. * issuerAndSerialNumber IssuerAndSerialNumber,
  13350. * digestAlgorithm DigestAlgorithmIdentifier,
  13351. * authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL,
  13352. * digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier,
  13353. * encryptedDigest EncryptedDigest,
  13354. * unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL
  13355. * }
  13356. *
  13357. * EncryptedDigest ::= OCTET STRING
  13358. *
  13359. * Attributes ::= SET OF Attribute
  13360. *
  13361. * Attribute ::= SEQUENCE {
  13362. * attrType OBJECT IDENTIFIER,
  13363. * attrValues SET OF AttributeValue
  13364. * }
  13365. *
  13366. * AttributeValue ::= ANY
  13367. *
  13368. * Version ::= INTEGER
  13369. *
  13370. * RecipientInfos ::= SET OF RecipientInfo
  13371. *
  13372. * EncryptedContentInfo ::= SEQUENCE {
  13373. * contentType ContentType,
  13374. * contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,
  13375. * encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL
  13376. * }
  13377. *
  13378. * ContentEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
  13379. *
  13380. * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters
  13381. * for the algorithm, if any. In the case of AES and DES3, there is only one,
  13382. * the IV.
  13383. *
  13384. * AlgorithmIdentifer ::= SEQUENCE {
  13385. * algorithm OBJECT IDENTIFIER,
  13386. * parameters ANY DEFINED BY algorithm OPTIONAL
  13387. * }
  13388. *
  13389. * EncryptedContent ::= OCTET STRING
  13390. *
  13391. * RecipientInfo ::= SEQUENCE {
  13392. * version Version,
  13393. * issuerAndSerialNumber IssuerAndSerialNumber,
  13394. * keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
  13395. * encryptedKey EncryptedKey
  13396. * }
  13397. *
  13398. * IssuerAndSerialNumber ::= SEQUENCE {
  13399. * issuer Name,
  13400. * serialNumber CertificateSerialNumber
  13401. * }
  13402. *
  13403. * CertificateSerialNumber ::= INTEGER
  13404. *
  13405. * KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
  13406. *
  13407. * EncryptedKey ::= OCTET STRING
  13408. */
  13409. var forge$i = forge$F;
  13410. // shortcut for ASN.1 API
  13411. var asn1$5 = forge$i.asn1;
  13412. // shortcut for PKCS#7 API
  13413. var p7v = forge$i.pkcs7asn1 = forge$i.pkcs7asn1 || {};
  13414. forge$i.pkcs7 = forge$i.pkcs7 || {};
  13415. forge$i.pkcs7.asn1 = p7v;
  13416. var contentInfoValidator$1 = {
  13417. name: 'ContentInfo',
  13418. tagClass: asn1$5.Class.UNIVERSAL,
  13419. type: asn1$5.Type.SEQUENCE,
  13420. constructed: true,
  13421. value: [{
  13422. name: 'ContentInfo.ContentType',
  13423. tagClass: asn1$5.Class.UNIVERSAL,
  13424. type: asn1$5.Type.OID,
  13425. constructed: false,
  13426. capture: 'contentType'
  13427. }, {
  13428. name: 'ContentInfo.content',
  13429. tagClass: asn1$5.Class.CONTEXT_SPECIFIC,
  13430. type: 0,
  13431. constructed: true,
  13432. optional: true,
  13433. captureAsn1: 'content'
  13434. }]
  13435. };
  13436. p7v.contentInfoValidator = contentInfoValidator$1;
  13437. var encryptedContentInfoValidator = {
  13438. name: 'EncryptedContentInfo',
  13439. tagClass: asn1$5.Class.UNIVERSAL,
  13440. type: asn1$5.Type.SEQUENCE,
  13441. constructed: true,
  13442. value: [{
  13443. name: 'EncryptedContentInfo.contentType',
  13444. tagClass: asn1$5.Class.UNIVERSAL,
  13445. type: asn1$5.Type.OID,
  13446. constructed: false,
  13447. capture: 'contentType'
  13448. }, {
  13449. name: 'EncryptedContentInfo.contentEncryptionAlgorithm',
  13450. tagClass: asn1$5.Class.UNIVERSAL,
  13451. type: asn1$5.Type.SEQUENCE,
  13452. constructed: true,
  13453. value: [{
  13454. name: 'EncryptedContentInfo.contentEncryptionAlgorithm.algorithm',
  13455. tagClass: asn1$5.Class.UNIVERSAL,
  13456. type: asn1$5.Type.OID,
  13457. constructed: false,
  13458. capture: 'encAlgorithm'
  13459. }, {
  13460. name: 'EncryptedContentInfo.contentEncryptionAlgorithm.parameter',
  13461. tagClass: asn1$5.Class.UNIVERSAL,
  13462. captureAsn1: 'encParameter'
  13463. }]
  13464. }, {
  13465. name: 'EncryptedContentInfo.encryptedContent',
  13466. tagClass: asn1$5.Class.CONTEXT_SPECIFIC,
  13467. type: 0,
  13468. /* The PKCS#7 structure output by OpenSSL somewhat differs from what
  13469. * other implementations do generate.
  13470. *
  13471. * OpenSSL generates a structure like this:
  13472. * SEQUENCE {
  13473. * ...
  13474. * [0]
  13475. * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38
  13476. * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45
  13477. * ...
  13478. * }
  13479. *
  13480. * Whereas other implementations (and this PKCS#7 module) generate:
  13481. * SEQUENCE {
  13482. * ...
  13483. * [0] {
  13484. * OCTET STRING
  13485. * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38
  13486. * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45
  13487. * ...
  13488. * }
  13489. * }
  13490. *
  13491. * In order to support both, we just capture the context specific
  13492. * field here. The OCTET STRING bit is removed below.
  13493. */
  13494. capture: 'encryptedContent',
  13495. captureAsn1: 'encryptedContentAsn1'
  13496. }]
  13497. };
  13498. p7v.envelopedDataValidator = {
  13499. name: 'EnvelopedData',
  13500. tagClass: asn1$5.Class.UNIVERSAL,
  13501. type: asn1$5.Type.SEQUENCE,
  13502. constructed: true,
  13503. value: [{
  13504. name: 'EnvelopedData.Version',
  13505. tagClass: asn1$5.Class.UNIVERSAL,
  13506. type: asn1$5.Type.INTEGER,
  13507. constructed: false,
  13508. capture: 'version'
  13509. }, {
  13510. name: 'EnvelopedData.RecipientInfos',
  13511. tagClass: asn1$5.Class.UNIVERSAL,
  13512. type: asn1$5.Type.SET,
  13513. constructed: true,
  13514. captureAsn1: 'recipientInfos'
  13515. }].concat(encryptedContentInfoValidator)
  13516. };
  13517. p7v.encryptedDataValidator = {
  13518. name: 'EncryptedData',
  13519. tagClass: asn1$5.Class.UNIVERSAL,
  13520. type: asn1$5.Type.SEQUENCE,
  13521. constructed: true,
  13522. value: [{
  13523. name: 'EncryptedData.Version',
  13524. tagClass: asn1$5.Class.UNIVERSAL,
  13525. type: asn1$5.Type.INTEGER,
  13526. constructed: false,
  13527. capture: 'version'
  13528. }].concat(encryptedContentInfoValidator)
  13529. };
  13530. var signerValidator = {
  13531. name: 'SignerInfo',
  13532. tagClass: asn1$5.Class.UNIVERSAL,
  13533. type: asn1$5.Type.SEQUENCE,
  13534. constructed: true,
  13535. value: [{
  13536. name: 'SignerInfo.version',
  13537. tagClass: asn1$5.Class.UNIVERSAL,
  13538. type: asn1$5.Type.INTEGER,
  13539. constructed: false
  13540. }, {
  13541. name: 'SignerInfo.issuerAndSerialNumber',
  13542. tagClass: asn1$5.Class.UNIVERSAL,
  13543. type: asn1$5.Type.SEQUENCE,
  13544. constructed: true,
  13545. value: [{
  13546. name: 'SignerInfo.issuerAndSerialNumber.issuer',
  13547. tagClass: asn1$5.Class.UNIVERSAL,
  13548. type: asn1$5.Type.SEQUENCE,
  13549. constructed: true,
  13550. captureAsn1: 'issuer'
  13551. }, {
  13552. name: 'SignerInfo.issuerAndSerialNumber.serialNumber',
  13553. tagClass: asn1$5.Class.UNIVERSAL,
  13554. type: asn1$5.Type.INTEGER,
  13555. constructed: false,
  13556. capture: 'serial'
  13557. }]
  13558. }, {
  13559. name: 'SignerInfo.digestAlgorithm',
  13560. tagClass: asn1$5.Class.UNIVERSAL,
  13561. type: asn1$5.Type.SEQUENCE,
  13562. constructed: true,
  13563. value: [{
  13564. name: 'SignerInfo.digestAlgorithm.algorithm',
  13565. tagClass: asn1$5.Class.UNIVERSAL,
  13566. type: asn1$5.Type.OID,
  13567. constructed: false,
  13568. capture: 'digestAlgorithm'
  13569. }, {
  13570. name: 'SignerInfo.digestAlgorithm.parameter',
  13571. tagClass: asn1$5.Class.UNIVERSAL,
  13572. constructed: false,
  13573. captureAsn1: 'digestParameter',
  13574. optional: true
  13575. }]
  13576. }, {
  13577. name: 'SignerInfo.authenticatedAttributes',
  13578. tagClass: asn1$5.Class.CONTEXT_SPECIFIC,
  13579. type: 0,
  13580. constructed: true,
  13581. optional: true,
  13582. capture: 'authenticatedAttributes'
  13583. }, {
  13584. name: 'SignerInfo.digestEncryptionAlgorithm',
  13585. tagClass: asn1$5.Class.UNIVERSAL,
  13586. type: asn1$5.Type.SEQUENCE,
  13587. constructed: true,
  13588. capture: 'signatureAlgorithm'
  13589. }, {
  13590. name: 'SignerInfo.encryptedDigest',
  13591. tagClass: asn1$5.Class.UNIVERSAL,
  13592. type: asn1$5.Type.OCTETSTRING,
  13593. constructed: false,
  13594. capture: 'signature'
  13595. }, {
  13596. name: 'SignerInfo.unauthenticatedAttributes',
  13597. tagClass: asn1$5.Class.CONTEXT_SPECIFIC,
  13598. type: 1,
  13599. constructed: true,
  13600. optional: true,
  13601. capture: 'unauthenticatedAttributes'
  13602. }]
  13603. };
  13604. p7v.signedDataValidator = {
  13605. name: 'SignedData',
  13606. tagClass: asn1$5.Class.UNIVERSAL,
  13607. type: asn1$5.Type.SEQUENCE,
  13608. constructed: true,
  13609. value: [{
  13610. name: 'SignedData.Version',
  13611. tagClass: asn1$5.Class.UNIVERSAL,
  13612. type: asn1$5.Type.INTEGER,
  13613. constructed: false,
  13614. capture: 'version'
  13615. }, {
  13616. name: 'SignedData.DigestAlgorithms',
  13617. tagClass: asn1$5.Class.UNIVERSAL,
  13618. type: asn1$5.Type.SET,
  13619. constructed: true,
  13620. captureAsn1: 'digestAlgorithms'
  13621. },
  13622. contentInfoValidator$1,
  13623. {
  13624. name: 'SignedData.Certificates',
  13625. tagClass: asn1$5.Class.CONTEXT_SPECIFIC,
  13626. type: 0,
  13627. optional: true,
  13628. captureAsn1: 'certificates'
  13629. }, {
  13630. name: 'SignedData.CertificateRevocationLists',
  13631. tagClass: asn1$5.Class.CONTEXT_SPECIFIC,
  13632. type: 1,
  13633. optional: true,
  13634. captureAsn1: 'crls'
  13635. }, {
  13636. name: 'SignedData.SignerInfos',
  13637. tagClass: asn1$5.Class.UNIVERSAL,
  13638. type: asn1$5.Type.SET,
  13639. capture: 'signerInfos',
  13640. optional: true,
  13641. value: [signerValidator]
  13642. }]
  13643. };
  13644. p7v.recipientInfoValidator = {
  13645. name: 'RecipientInfo',
  13646. tagClass: asn1$5.Class.UNIVERSAL,
  13647. type: asn1$5.Type.SEQUENCE,
  13648. constructed: true,
  13649. value: [{
  13650. name: 'RecipientInfo.version',
  13651. tagClass: asn1$5.Class.UNIVERSAL,
  13652. type: asn1$5.Type.INTEGER,
  13653. constructed: false,
  13654. capture: 'version'
  13655. }, {
  13656. name: 'RecipientInfo.issuerAndSerial',
  13657. tagClass: asn1$5.Class.UNIVERSAL,
  13658. type: asn1$5.Type.SEQUENCE,
  13659. constructed: true,
  13660. value: [{
  13661. name: 'RecipientInfo.issuerAndSerial.issuer',
  13662. tagClass: asn1$5.Class.UNIVERSAL,
  13663. type: asn1$5.Type.SEQUENCE,
  13664. constructed: true,
  13665. captureAsn1: 'issuer'
  13666. }, {
  13667. name: 'RecipientInfo.issuerAndSerial.serialNumber',
  13668. tagClass: asn1$5.Class.UNIVERSAL,
  13669. type: asn1$5.Type.INTEGER,
  13670. constructed: false,
  13671. capture: 'serial'
  13672. }]
  13673. }, {
  13674. name: 'RecipientInfo.keyEncryptionAlgorithm',
  13675. tagClass: asn1$5.Class.UNIVERSAL,
  13676. type: asn1$5.Type.SEQUENCE,
  13677. constructed: true,
  13678. value: [{
  13679. name: 'RecipientInfo.keyEncryptionAlgorithm.algorithm',
  13680. tagClass: asn1$5.Class.UNIVERSAL,
  13681. type: asn1$5.Type.OID,
  13682. constructed: false,
  13683. capture: 'encAlgorithm'
  13684. }, {
  13685. name: 'RecipientInfo.keyEncryptionAlgorithm.parameter',
  13686. tagClass: asn1$5.Class.UNIVERSAL,
  13687. constructed: false,
  13688. captureAsn1: 'encParameter'
  13689. }]
  13690. }, {
  13691. name: 'RecipientInfo.encryptedKey',
  13692. tagClass: asn1$5.Class.UNIVERSAL,
  13693. type: asn1$5.Type.OCTETSTRING,
  13694. constructed: false,
  13695. capture: 'encKey'
  13696. }]
  13697. };
  13698. /**
  13699. * Javascript implementation of mask generation function MGF1.
  13700. *
  13701. * @author Stefan Siegl
  13702. * @author Dave Longley
  13703. *
  13704. * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>
  13705. * Copyright (c) 2014 Digital Bazaar, Inc.
  13706. */
  13707. var forge$h = forge$F;
  13708. forge$h.mgf = forge$h.mgf || {};
  13709. var mgf1 = forge$h.mgf.mgf1 = forge$h.mgf1 = forge$h.mgf1 || {};
  13710. /**
  13711. * Creates a MGF1 mask generation function object.
  13712. *
  13713. * @param md the message digest API to use (eg: forge.md.sha1.create()).
  13714. *
  13715. * @return a mask generation function object.
  13716. */
  13717. mgf1.create = function(md) {
  13718. var mgf = {
  13719. /**
  13720. * Generate mask of specified length.
  13721. *
  13722. * @param {String} seed The seed for mask generation.
  13723. * @param maskLen Number of bytes to generate.
  13724. * @return {String} The generated mask.
  13725. */
  13726. generate: function(seed, maskLen) {
  13727. /* 2. Let T be the empty octet string. */
  13728. var t = new forge$h.util.ByteBuffer();
  13729. /* 3. For counter from 0 to ceil(maskLen / hLen), do the following: */
  13730. var len = Math.ceil(maskLen / md.digestLength);
  13731. for(var i = 0; i < len; i++) {
  13732. /* a. Convert counter to an octet string C of length 4 octets */
  13733. var c = new forge$h.util.ByteBuffer();
  13734. c.putInt32(i);
  13735. /* b. Concatenate the hash of the seed mgfSeed and C to the octet
  13736. * string T: */
  13737. md.start();
  13738. md.update(seed + c.getBytes());
  13739. t.putBuffer(md.digest());
  13740. }
  13741. /* Output the leading maskLen octets of T as the octet string mask. */
  13742. t.truncate(t.length() - maskLen);
  13743. return t.getBytes();
  13744. }
  13745. };
  13746. return mgf;
  13747. };
  13748. /**
  13749. * Node.js module for Forge mask generation functions.
  13750. *
  13751. * @author Stefan Siegl
  13752. *
  13753. * Copyright 2012 Stefan Siegl <stesie@brokenpipe.de>
  13754. */
  13755. var forge$g = forge$F;
  13756. forge$g.mgf = forge$g.mgf || {};
  13757. forge$g.mgf.mgf1 = forge$g.mgf1;
  13758. /**
  13759. * Javascript implementation of PKCS#1 PSS signature padding.
  13760. *
  13761. * @author Stefan Siegl
  13762. *
  13763. * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>
  13764. */
  13765. var forge$f = forge$F;
  13766. // shortcut for PSS API
  13767. var pss = forge$f.pss = forge$f.pss || {};
  13768. /**
  13769. * Creates a PSS signature scheme object.
  13770. *
  13771. * There are several ways to provide a salt for encoding:
  13772. *
  13773. * 1. Specify the saltLength only and the built-in PRNG will generate it.
  13774. * 2. Specify the saltLength and a custom PRNG with 'getBytesSync' defined that
  13775. * will be used.
  13776. * 3. Specify the salt itself as a forge.util.ByteBuffer.
  13777. *
  13778. * @param options the options to use:
  13779. * md the message digest object to use, a forge md instance.
  13780. * mgf the mask generation function to use, a forge mgf instance.
  13781. * [saltLength] the length of the salt in octets.
  13782. * [prng] the pseudo-random number generator to use to produce a salt.
  13783. * [salt] the salt to use when encoding.
  13784. *
  13785. * @return a signature scheme object.
  13786. */
  13787. pss.create = function(options) {
  13788. // backwards compatibility w/legacy args: hash, mgf, sLen
  13789. if(arguments.length === 3) {
  13790. options = {
  13791. md: arguments[0],
  13792. mgf: arguments[1],
  13793. saltLength: arguments[2]
  13794. };
  13795. }
  13796. var hash = options.md;
  13797. var mgf = options.mgf;
  13798. var hLen = hash.digestLength;
  13799. var salt_ = options.salt || null;
  13800. if(typeof salt_ === 'string') {
  13801. // assume binary-encoded string
  13802. salt_ = forge$f.util.createBuffer(salt_);
  13803. }
  13804. var sLen;
  13805. if('saltLength' in options) {
  13806. sLen = options.saltLength;
  13807. } else if(salt_ !== null) {
  13808. sLen = salt_.length();
  13809. } else {
  13810. throw new Error('Salt length not specified or specific salt not given.');
  13811. }
  13812. if(salt_ !== null && salt_.length() !== sLen) {
  13813. throw new Error('Given salt length does not match length of given salt.');
  13814. }
  13815. var prng = options.prng || forge$f.random;
  13816. var pssobj = {};
  13817. /**
  13818. * Encodes a PSS signature.
  13819. *
  13820. * This function implements EMSA-PSS-ENCODE as per RFC 3447, section 9.1.1.
  13821. *
  13822. * @param md the message digest object with the hash to sign.
  13823. * @param modsBits the length of the RSA modulus in bits.
  13824. *
  13825. * @return the encoded message as a binary-encoded string of length
  13826. * ceil((modBits - 1) / 8).
  13827. */
  13828. pssobj.encode = function(md, modBits) {
  13829. var i;
  13830. var emBits = modBits - 1;
  13831. var emLen = Math.ceil(emBits / 8);
  13832. /* 2. Let mHash = Hash(M), an octet string of length hLen. */
  13833. var mHash = md.digest().getBytes();
  13834. /* 3. If emLen < hLen + sLen + 2, output "encoding error" and stop. */
  13835. if(emLen < hLen + sLen + 2) {
  13836. throw new Error('Message is too long to encrypt.');
  13837. }
  13838. /* 4. Generate a random octet string salt of length sLen; if sLen = 0,
  13839. * then salt is the empty string. */
  13840. var salt;
  13841. if(salt_ === null) {
  13842. salt = prng.getBytesSync(sLen);
  13843. } else {
  13844. salt = salt_.bytes();
  13845. }
  13846. /* 5. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt; */
  13847. var m_ = new forge$f.util.ByteBuffer();
  13848. m_.fillWithByte(0, 8);
  13849. m_.putBytes(mHash);
  13850. m_.putBytes(salt);
  13851. /* 6. Let H = Hash(M'), an octet string of length hLen. */
  13852. hash.start();
  13853. hash.update(m_.getBytes());
  13854. var h = hash.digest().getBytes();
  13855. /* 7. Generate an octet string PS consisting of emLen - sLen - hLen - 2
  13856. * zero octets. The length of PS may be 0. */
  13857. var ps = new forge$f.util.ByteBuffer();
  13858. ps.fillWithByte(0, emLen - sLen - hLen - 2);
  13859. /* 8. Let DB = PS || 0x01 || salt; DB is an octet string of length
  13860. * emLen - hLen - 1. */
  13861. ps.putByte(0x01);
  13862. ps.putBytes(salt);
  13863. var db = ps.getBytes();
  13864. /* 9. Let dbMask = MGF(H, emLen - hLen - 1). */
  13865. var maskLen = emLen - hLen - 1;
  13866. var dbMask = mgf.generate(h, maskLen);
  13867. /* 10. Let maskedDB = DB \xor dbMask. */
  13868. var maskedDB = '';
  13869. for(i = 0; i < maskLen; i++) {
  13870. maskedDB += String.fromCharCode(db.charCodeAt(i) ^ dbMask.charCodeAt(i));
  13871. }
  13872. /* 11. Set the leftmost 8emLen - emBits bits of the leftmost octet in
  13873. * maskedDB to zero. */
  13874. var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF;
  13875. maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) +
  13876. maskedDB.substr(1);
  13877. /* 12. Let EM = maskedDB || H || 0xbc.
  13878. * 13. Output EM. */
  13879. return maskedDB + h + String.fromCharCode(0xbc);
  13880. };
  13881. /**
  13882. * Verifies a PSS signature.
  13883. *
  13884. * This function implements EMSA-PSS-VERIFY as per RFC 3447, section 9.1.2.
  13885. *
  13886. * @param mHash the message digest hash, as a binary-encoded string, to
  13887. * compare against the signature.
  13888. * @param em the encoded message, as a binary-encoded string
  13889. * (RSA decryption result).
  13890. * @param modsBits the length of the RSA modulus in bits.
  13891. *
  13892. * @return true if the signature was verified, false if not.
  13893. */
  13894. pssobj.verify = function(mHash, em, modBits) {
  13895. var i;
  13896. var emBits = modBits - 1;
  13897. var emLen = Math.ceil(emBits / 8);
  13898. /* c. Convert the message representative m to an encoded message EM
  13899. * of length emLen = ceil((modBits - 1) / 8) octets, where modBits
  13900. * is the length in bits of the RSA modulus n */
  13901. em = em.substr(-emLen);
  13902. /* 3. If emLen < hLen + sLen + 2, output "inconsistent" and stop. */
  13903. if(emLen < hLen + sLen + 2) {
  13904. throw new Error('Inconsistent parameters to PSS signature verification.');
  13905. }
  13906. /* 4. If the rightmost octet of EM does not have hexadecimal value
  13907. * 0xbc, output "inconsistent" and stop. */
  13908. if(em.charCodeAt(emLen - 1) !== 0xbc) {
  13909. throw new Error('Encoded message does not end in 0xBC.');
  13910. }
  13911. /* 5. Let maskedDB be the leftmost emLen - hLen - 1 octets of EM, and
  13912. * let H be the next hLen octets. */
  13913. var maskLen = emLen - hLen - 1;
  13914. var maskedDB = em.substr(0, maskLen);
  13915. var h = em.substr(maskLen, hLen);
  13916. /* 6. If the leftmost 8emLen - emBits bits of the leftmost octet in
  13917. * maskedDB are not all equal to zero, output "inconsistent" and stop. */
  13918. var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF;
  13919. if((maskedDB.charCodeAt(0) & mask) !== 0) {
  13920. throw new Error('Bits beyond keysize not zero as expected.');
  13921. }
  13922. /* 7. Let dbMask = MGF(H, emLen - hLen - 1). */
  13923. var dbMask = mgf.generate(h, maskLen);
  13924. /* 8. Let DB = maskedDB \xor dbMask. */
  13925. var db = '';
  13926. for(i = 0; i < maskLen; i++) {
  13927. db += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i));
  13928. }
  13929. /* 9. Set the leftmost 8emLen - emBits bits of the leftmost octet
  13930. * in DB to zero. */
  13931. db = String.fromCharCode(db.charCodeAt(0) & ~mask) + db.substr(1);
  13932. /* 10. If the emLen - hLen - sLen - 2 leftmost octets of DB are not zero
  13933. * or if the octet at position emLen - hLen - sLen - 1 (the leftmost
  13934. * position is "position 1") does not have hexadecimal value 0x01,
  13935. * output "inconsistent" and stop. */
  13936. var checkLen = emLen - hLen - sLen - 2;
  13937. for(i = 0; i < checkLen; i++) {
  13938. if(db.charCodeAt(i) !== 0x00) {
  13939. throw new Error('Leftmost octets not zero as expected');
  13940. }
  13941. }
  13942. if(db.charCodeAt(checkLen) !== 0x01) {
  13943. throw new Error('Inconsistent PSS signature, 0x01 marker not found');
  13944. }
  13945. /* 11. Let salt be the last sLen octets of DB. */
  13946. var salt = db.substr(-sLen);
  13947. /* 12. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt */
  13948. var m_ = new forge$f.util.ByteBuffer();
  13949. m_.fillWithByte(0, 8);
  13950. m_.putBytes(mHash);
  13951. m_.putBytes(salt);
  13952. /* 13. Let H' = Hash(M'), an octet string of length hLen. */
  13953. hash.start();
  13954. hash.update(m_.getBytes());
  13955. var h_ = hash.digest().getBytes();
  13956. /* 14. If H = H', output "consistent." Otherwise, output "inconsistent." */
  13957. return h === h_;
  13958. };
  13959. return pssobj;
  13960. };
  13961. /**
  13962. * Javascript implementation of X.509 and related components (such as
  13963. * Certification Signing Requests) of a Public Key Infrastructure.
  13964. *
  13965. * @author Dave Longley
  13966. *
  13967. * Copyright (c) 2010-2014 Digital Bazaar, Inc.
  13968. *
  13969. * The ASN.1 representation of an X.509v3 certificate is as follows
  13970. * (see RFC 2459):
  13971. *
  13972. * Certificate ::= SEQUENCE {
  13973. * tbsCertificate TBSCertificate,
  13974. * signatureAlgorithm AlgorithmIdentifier,
  13975. * signatureValue BIT STRING
  13976. * }
  13977. *
  13978. * TBSCertificate ::= SEQUENCE {
  13979. * version [0] EXPLICIT Version DEFAULT v1,
  13980. * serialNumber CertificateSerialNumber,
  13981. * signature AlgorithmIdentifier,
  13982. * issuer Name,
  13983. * validity Validity,
  13984. * subject Name,
  13985. * subjectPublicKeyInfo SubjectPublicKeyInfo,
  13986. * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
  13987. * -- If present, version shall be v2 or v3
  13988. * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
  13989. * -- If present, version shall be v2 or v3
  13990. * extensions [3] EXPLICIT Extensions OPTIONAL
  13991. * -- If present, version shall be v3
  13992. * }
  13993. *
  13994. * Version ::= INTEGER { v1(0), v2(1), v3(2) }
  13995. *
  13996. * CertificateSerialNumber ::= INTEGER
  13997. *
  13998. * Name ::= CHOICE {
  13999. * // only one possible choice for now
  14000. * RDNSequence
  14001. * }
  14002. *
  14003. * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
  14004. *
  14005. * RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
  14006. *
  14007. * AttributeTypeAndValue ::= SEQUENCE {
  14008. * type AttributeType,
  14009. * value AttributeValue
  14010. * }
  14011. * AttributeType ::= OBJECT IDENTIFIER
  14012. * AttributeValue ::= ANY DEFINED BY AttributeType
  14013. *
  14014. * Validity ::= SEQUENCE {
  14015. * notBefore Time,
  14016. * notAfter Time
  14017. * }
  14018. *
  14019. * Time ::= CHOICE {
  14020. * utcTime UTCTime,
  14021. * generalTime GeneralizedTime
  14022. * }
  14023. *
  14024. * UniqueIdentifier ::= BIT STRING
  14025. *
  14026. * SubjectPublicKeyInfo ::= SEQUENCE {
  14027. * algorithm AlgorithmIdentifier,
  14028. * subjectPublicKey BIT STRING
  14029. * }
  14030. *
  14031. * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
  14032. *
  14033. * Extension ::= SEQUENCE {
  14034. * extnID OBJECT IDENTIFIER,
  14035. * critical BOOLEAN DEFAULT FALSE,
  14036. * extnValue OCTET STRING
  14037. * }
  14038. *
  14039. * The only key algorithm currently supported for PKI is RSA.
  14040. *
  14041. * RSASSA-PSS signatures are described in RFC 3447 and RFC 4055.
  14042. *
  14043. * PKCS#10 v1.7 describes certificate signing requests:
  14044. *
  14045. * CertificationRequestInfo:
  14046. *
  14047. * CertificationRequestInfo ::= SEQUENCE {
  14048. * version INTEGER { v1(0) } (v1,...),
  14049. * subject Name,
  14050. * subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }},
  14051. * attributes [0] Attributes{{ CRIAttributes }}
  14052. * }
  14053. *
  14054. * Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }}
  14055. *
  14056. * CRIAttributes ATTRIBUTE ::= {
  14057. * ... -- add any locally defined attributes here -- }
  14058. *
  14059. * Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE {
  14060. * type ATTRIBUTE.&id({IOSet}),
  14061. * values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type})
  14062. * }
  14063. *
  14064. * CertificationRequest ::= SEQUENCE {
  14065. * certificationRequestInfo CertificationRequestInfo,
  14066. * signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }},
  14067. * signature BIT STRING
  14068. * }
  14069. */
  14070. var forge$e = forge$F;
  14071. // shortcut for asn.1 API
  14072. var asn1$4 = forge$e.asn1;
  14073. /* Public Key Infrastructure (PKI) implementation. */
  14074. var pki$2 = forge$e.pki = forge$e.pki || {};
  14075. var oids = pki$2.oids;
  14076. // short name OID mappings
  14077. var _shortNames = {};
  14078. _shortNames['CN'] = oids['commonName'];
  14079. _shortNames['commonName'] = 'CN';
  14080. _shortNames['C'] = oids['countryName'];
  14081. _shortNames['countryName'] = 'C';
  14082. _shortNames['L'] = oids['localityName'];
  14083. _shortNames['localityName'] = 'L';
  14084. _shortNames['ST'] = oids['stateOrProvinceName'];
  14085. _shortNames['stateOrProvinceName'] = 'ST';
  14086. _shortNames['O'] = oids['organizationName'];
  14087. _shortNames['organizationName'] = 'O';
  14088. _shortNames['OU'] = oids['organizationalUnitName'];
  14089. _shortNames['organizationalUnitName'] = 'OU';
  14090. _shortNames['E'] = oids['emailAddress'];
  14091. _shortNames['emailAddress'] = 'E';
  14092. // validator for an SubjectPublicKeyInfo structure
  14093. // Note: Currently only works with an RSA public key
  14094. var publicKeyValidator$1 = forge$e.pki.rsa.publicKeyValidator;
  14095. // validator for an X.509v3 certificate
  14096. var x509CertificateValidator = {
  14097. name: 'Certificate',
  14098. tagClass: asn1$4.Class.UNIVERSAL,
  14099. type: asn1$4.Type.SEQUENCE,
  14100. constructed: true,
  14101. value: [{
  14102. name: 'Certificate.TBSCertificate',
  14103. tagClass: asn1$4.Class.UNIVERSAL,
  14104. type: asn1$4.Type.SEQUENCE,
  14105. constructed: true,
  14106. captureAsn1: 'tbsCertificate',
  14107. value: [{
  14108. name: 'Certificate.TBSCertificate.version',
  14109. tagClass: asn1$4.Class.CONTEXT_SPECIFIC,
  14110. type: 0,
  14111. constructed: true,
  14112. optional: true,
  14113. value: [{
  14114. name: 'Certificate.TBSCertificate.version.integer',
  14115. tagClass: asn1$4.Class.UNIVERSAL,
  14116. type: asn1$4.Type.INTEGER,
  14117. constructed: false,
  14118. capture: 'certVersion'
  14119. }]
  14120. }, {
  14121. name: 'Certificate.TBSCertificate.serialNumber',
  14122. tagClass: asn1$4.Class.UNIVERSAL,
  14123. type: asn1$4.Type.INTEGER,
  14124. constructed: false,
  14125. capture: 'certSerialNumber'
  14126. }, {
  14127. name: 'Certificate.TBSCertificate.signature',
  14128. tagClass: asn1$4.Class.UNIVERSAL,
  14129. type: asn1$4.Type.SEQUENCE,
  14130. constructed: true,
  14131. value: [{
  14132. name: 'Certificate.TBSCertificate.signature.algorithm',
  14133. tagClass: asn1$4.Class.UNIVERSAL,
  14134. type: asn1$4.Type.OID,
  14135. constructed: false,
  14136. capture: 'certinfoSignatureOid'
  14137. }, {
  14138. name: 'Certificate.TBSCertificate.signature.parameters',
  14139. tagClass: asn1$4.Class.UNIVERSAL,
  14140. optional: true,
  14141. captureAsn1: 'certinfoSignatureParams'
  14142. }]
  14143. }, {
  14144. name: 'Certificate.TBSCertificate.issuer',
  14145. tagClass: asn1$4.Class.UNIVERSAL,
  14146. type: asn1$4.Type.SEQUENCE,
  14147. constructed: true,
  14148. captureAsn1: 'certIssuer'
  14149. }, {
  14150. name: 'Certificate.TBSCertificate.validity',
  14151. tagClass: asn1$4.Class.UNIVERSAL,
  14152. type: asn1$4.Type.SEQUENCE,
  14153. constructed: true,
  14154. // Note: UTC and generalized times may both appear so the capture
  14155. // names are based on their detected order, the names used below
  14156. // are only for the common case, which validity time really means
  14157. // "notBefore" and which means "notAfter" will be determined by order
  14158. value: [{
  14159. // notBefore (Time) (UTC time case)
  14160. name: 'Certificate.TBSCertificate.validity.notBefore (utc)',
  14161. tagClass: asn1$4.Class.UNIVERSAL,
  14162. type: asn1$4.Type.UTCTIME,
  14163. constructed: false,
  14164. optional: true,
  14165. capture: 'certValidity1UTCTime'
  14166. }, {
  14167. // notBefore (Time) (generalized time case)
  14168. name: 'Certificate.TBSCertificate.validity.notBefore (generalized)',
  14169. tagClass: asn1$4.Class.UNIVERSAL,
  14170. type: asn1$4.Type.GENERALIZEDTIME,
  14171. constructed: false,
  14172. optional: true,
  14173. capture: 'certValidity2GeneralizedTime'
  14174. }, {
  14175. // notAfter (Time) (only UTC time is supported)
  14176. name: 'Certificate.TBSCertificate.validity.notAfter (utc)',
  14177. tagClass: asn1$4.Class.UNIVERSAL,
  14178. type: asn1$4.Type.UTCTIME,
  14179. constructed: false,
  14180. optional: true,
  14181. capture: 'certValidity3UTCTime'
  14182. }, {
  14183. // notAfter (Time) (only UTC time is supported)
  14184. name: 'Certificate.TBSCertificate.validity.notAfter (generalized)',
  14185. tagClass: asn1$4.Class.UNIVERSAL,
  14186. type: asn1$4.Type.GENERALIZEDTIME,
  14187. constructed: false,
  14188. optional: true,
  14189. capture: 'certValidity4GeneralizedTime'
  14190. }]
  14191. }, {
  14192. // Name (subject) (RDNSequence)
  14193. name: 'Certificate.TBSCertificate.subject',
  14194. tagClass: asn1$4.Class.UNIVERSAL,
  14195. type: asn1$4.Type.SEQUENCE,
  14196. constructed: true,
  14197. captureAsn1: 'certSubject'
  14198. },
  14199. // SubjectPublicKeyInfo
  14200. publicKeyValidator$1,
  14201. {
  14202. // issuerUniqueID (optional)
  14203. name: 'Certificate.TBSCertificate.issuerUniqueID',
  14204. tagClass: asn1$4.Class.CONTEXT_SPECIFIC,
  14205. type: 1,
  14206. constructed: true,
  14207. optional: true,
  14208. value: [{
  14209. name: 'Certificate.TBSCertificate.issuerUniqueID.id',
  14210. tagClass: asn1$4.Class.UNIVERSAL,
  14211. type: asn1$4.Type.BITSTRING,
  14212. constructed: false,
  14213. // TODO: support arbitrary bit length ids
  14214. captureBitStringValue: 'certIssuerUniqueId'
  14215. }]
  14216. }, {
  14217. // subjectUniqueID (optional)
  14218. name: 'Certificate.TBSCertificate.subjectUniqueID',
  14219. tagClass: asn1$4.Class.CONTEXT_SPECIFIC,
  14220. type: 2,
  14221. constructed: true,
  14222. optional: true,
  14223. value: [{
  14224. name: 'Certificate.TBSCertificate.subjectUniqueID.id',
  14225. tagClass: asn1$4.Class.UNIVERSAL,
  14226. type: asn1$4.Type.BITSTRING,
  14227. constructed: false,
  14228. // TODO: support arbitrary bit length ids
  14229. captureBitStringValue: 'certSubjectUniqueId'
  14230. }]
  14231. }, {
  14232. // Extensions (optional)
  14233. name: 'Certificate.TBSCertificate.extensions',
  14234. tagClass: asn1$4.Class.CONTEXT_SPECIFIC,
  14235. type: 3,
  14236. constructed: true,
  14237. captureAsn1: 'certExtensions',
  14238. optional: true
  14239. }]
  14240. }, {
  14241. // AlgorithmIdentifier (signature algorithm)
  14242. name: 'Certificate.signatureAlgorithm',
  14243. tagClass: asn1$4.Class.UNIVERSAL,
  14244. type: asn1$4.Type.SEQUENCE,
  14245. constructed: true,
  14246. value: [{
  14247. // algorithm
  14248. name: 'Certificate.signatureAlgorithm.algorithm',
  14249. tagClass: asn1$4.Class.UNIVERSAL,
  14250. type: asn1$4.Type.OID,
  14251. constructed: false,
  14252. capture: 'certSignatureOid'
  14253. }, {
  14254. name: 'Certificate.TBSCertificate.signature.parameters',
  14255. tagClass: asn1$4.Class.UNIVERSAL,
  14256. optional: true,
  14257. captureAsn1: 'certSignatureParams'
  14258. }]
  14259. }, {
  14260. // SignatureValue
  14261. name: 'Certificate.signatureValue',
  14262. tagClass: asn1$4.Class.UNIVERSAL,
  14263. type: asn1$4.Type.BITSTRING,
  14264. constructed: false,
  14265. captureBitStringValue: 'certSignature'
  14266. }]
  14267. };
  14268. var rsassaPssParameterValidator = {
  14269. name: 'rsapss',
  14270. tagClass: asn1$4.Class.UNIVERSAL,
  14271. type: asn1$4.Type.SEQUENCE,
  14272. constructed: true,
  14273. value: [{
  14274. name: 'rsapss.hashAlgorithm',
  14275. tagClass: asn1$4.Class.CONTEXT_SPECIFIC,
  14276. type: 0,
  14277. constructed: true,
  14278. value: [{
  14279. name: 'rsapss.hashAlgorithm.AlgorithmIdentifier',
  14280. tagClass: asn1$4.Class.UNIVERSAL,
  14281. type: asn1$4.Class.SEQUENCE,
  14282. constructed: true,
  14283. optional: true,
  14284. value: [{
  14285. name: 'rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm',
  14286. tagClass: asn1$4.Class.UNIVERSAL,
  14287. type: asn1$4.Type.OID,
  14288. constructed: false,
  14289. capture: 'hashOid'
  14290. /* parameter block omitted, for SHA1 NULL anyhow. */
  14291. }]
  14292. }]
  14293. }, {
  14294. name: 'rsapss.maskGenAlgorithm',
  14295. tagClass: asn1$4.Class.CONTEXT_SPECIFIC,
  14296. type: 1,
  14297. constructed: true,
  14298. value: [{
  14299. name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier',
  14300. tagClass: asn1$4.Class.UNIVERSAL,
  14301. type: asn1$4.Class.SEQUENCE,
  14302. constructed: true,
  14303. optional: true,
  14304. value: [{
  14305. name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm',
  14306. tagClass: asn1$4.Class.UNIVERSAL,
  14307. type: asn1$4.Type.OID,
  14308. constructed: false,
  14309. capture: 'maskGenOid'
  14310. }, {
  14311. name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params',
  14312. tagClass: asn1$4.Class.UNIVERSAL,
  14313. type: asn1$4.Type.SEQUENCE,
  14314. constructed: true,
  14315. value: [{
  14316. name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm',
  14317. tagClass: asn1$4.Class.UNIVERSAL,
  14318. type: asn1$4.Type.OID,
  14319. constructed: false,
  14320. capture: 'maskGenHashOid'
  14321. /* parameter block omitted, for SHA1 NULL anyhow. */
  14322. }]
  14323. }]
  14324. }]
  14325. }, {
  14326. name: 'rsapss.saltLength',
  14327. tagClass: asn1$4.Class.CONTEXT_SPECIFIC,
  14328. type: 2,
  14329. optional: true,
  14330. value: [{
  14331. name: 'rsapss.saltLength.saltLength',
  14332. tagClass: asn1$4.Class.UNIVERSAL,
  14333. type: asn1$4.Class.INTEGER,
  14334. constructed: false,
  14335. capture: 'saltLength'
  14336. }]
  14337. }, {
  14338. name: 'rsapss.trailerField',
  14339. tagClass: asn1$4.Class.CONTEXT_SPECIFIC,
  14340. type: 3,
  14341. optional: true,
  14342. value: [{
  14343. name: 'rsapss.trailer.trailer',
  14344. tagClass: asn1$4.Class.UNIVERSAL,
  14345. type: asn1$4.Class.INTEGER,
  14346. constructed: false,
  14347. capture: 'trailer'
  14348. }]
  14349. }]
  14350. };
  14351. // validator for a CertificationRequestInfo structure
  14352. var certificationRequestInfoValidator = {
  14353. name: 'CertificationRequestInfo',
  14354. tagClass: asn1$4.Class.UNIVERSAL,
  14355. type: asn1$4.Type.SEQUENCE,
  14356. constructed: true,
  14357. captureAsn1: 'certificationRequestInfo',
  14358. value: [{
  14359. name: 'CertificationRequestInfo.integer',
  14360. tagClass: asn1$4.Class.UNIVERSAL,
  14361. type: asn1$4.Type.INTEGER,
  14362. constructed: false,
  14363. capture: 'certificationRequestInfoVersion'
  14364. }, {
  14365. // Name (subject) (RDNSequence)
  14366. name: 'CertificationRequestInfo.subject',
  14367. tagClass: asn1$4.Class.UNIVERSAL,
  14368. type: asn1$4.Type.SEQUENCE,
  14369. constructed: true,
  14370. captureAsn1: 'certificationRequestInfoSubject'
  14371. },
  14372. // SubjectPublicKeyInfo
  14373. publicKeyValidator$1,
  14374. {
  14375. name: 'CertificationRequestInfo.attributes',
  14376. tagClass: asn1$4.Class.CONTEXT_SPECIFIC,
  14377. type: 0,
  14378. constructed: true,
  14379. optional: true,
  14380. capture: 'certificationRequestInfoAttributes',
  14381. value: [{
  14382. name: 'CertificationRequestInfo.attributes',
  14383. tagClass: asn1$4.Class.UNIVERSAL,
  14384. type: asn1$4.Type.SEQUENCE,
  14385. constructed: true,
  14386. value: [{
  14387. name: 'CertificationRequestInfo.attributes.type',
  14388. tagClass: asn1$4.Class.UNIVERSAL,
  14389. type: asn1$4.Type.OID,
  14390. constructed: false
  14391. }, {
  14392. name: 'CertificationRequestInfo.attributes.value',
  14393. tagClass: asn1$4.Class.UNIVERSAL,
  14394. type: asn1$4.Type.SET,
  14395. constructed: true
  14396. }]
  14397. }]
  14398. }]
  14399. };
  14400. // validator for a CertificationRequest structure
  14401. var certificationRequestValidator = {
  14402. name: 'CertificationRequest',
  14403. tagClass: asn1$4.Class.UNIVERSAL,
  14404. type: asn1$4.Type.SEQUENCE,
  14405. constructed: true,
  14406. captureAsn1: 'csr',
  14407. value: [
  14408. certificationRequestInfoValidator, {
  14409. // AlgorithmIdentifier (signature algorithm)
  14410. name: 'CertificationRequest.signatureAlgorithm',
  14411. tagClass: asn1$4.Class.UNIVERSAL,
  14412. type: asn1$4.Type.SEQUENCE,
  14413. constructed: true,
  14414. value: [{
  14415. // algorithm
  14416. name: 'CertificationRequest.signatureAlgorithm.algorithm',
  14417. tagClass: asn1$4.Class.UNIVERSAL,
  14418. type: asn1$4.Type.OID,
  14419. constructed: false,
  14420. capture: 'csrSignatureOid'
  14421. }, {
  14422. name: 'CertificationRequest.signatureAlgorithm.parameters',
  14423. tagClass: asn1$4.Class.UNIVERSAL,
  14424. optional: true,
  14425. captureAsn1: 'csrSignatureParams'
  14426. }]
  14427. }, {
  14428. // signature
  14429. name: 'CertificationRequest.signature',
  14430. tagClass: asn1$4.Class.UNIVERSAL,
  14431. type: asn1$4.Type.BITSTRING,
  14432. constructed: false,
  14433. captureBitStringValue: 'csrSignature'
  14434. }
  14435. ]
  14436. };
  14437. /**
  14438. * Converts an RDNSequence of ASN.1 DER-encoded RelativeDistinguishedName
  14439. * sets into an array with objects that have type and value properties.
  14440. *
  14441. * @param rdn the RDNSequence to convert.
  14442. * @param md a message digest to append type and value to if provided.
  14443. */
  14444. pki$2.RDNAttributesAsArray = function(rdn, md) {
  14445. var rval = [];
  14446. // each value in 'rdn' in is a SET of RelativeDistinguishedName
  14447. var set, attr, obj;
  14448. for(var si = 0; si < rdn.value.length; ++si) {
  14449. // get the RelativeDistinguishedName set
  14450. set = rdn.value[si];
  14451. // each value in the SET is an AttributeTypeAndValue sequence
  14452. // containing first a type (an OID) and second a value (defined by
  14453. // the OID)
  14454. for(var i = 0; i < set.value.length; ++i) {
  14455. obj = {};
  14456. attr = set.value[i];
  14457. obj.type = asn1$4.derToOid(attr.value[0].value);
  14458. obj.value = attr.value[1].value;
  14459. obj.valueTagClass = attr.value[1].type;
  14460. // if the OID is known, get its name and short name
  14461. if(obj.type in oids) {
  14462. obj.name = oids[obj.type];
  14463. if(obj.name in _shortNames) {
  14464. obj.shortName = _shortNames[obj.name];
  14465. }
  14466. }
  14467. if(md) {
  14468. md.update(obj.type);
  14469. md.update(obj.value);
  14470. }
  14471. rval.push(obj);
  14472. }
  14473. }
  14474. return rval;
  14475. };
  14476. /**
  14477. * Converts ASN.1 CRIAttributes into an array with objects that have type and
  14478. * value properties.
  14479. *
  14480. * @param attributes the CRIAttributes to convert.
  14481. */
  14482. pki$2.CRIAttributesAsArray = function(attributes) {
  14483. var rval = [];
  14484. // each value in 'attributes' in is a SEQUENCE with an OID and a SET
  14485. for(var si = 0; si < attributes.length; ++si) {
  14486. // get the attribute sequence
  14487. var seq = attributes[si];
  14488. // each value in the SEQUENCE containing first a type (an OID) and
  14489. // second a set of values (defined by the OID)
  14490. var type = asn1$4.derToOid(seq.value[0].value);
  14491. var values = seq.value[1].value;
  14492. for(var vi = 0; vi < values.length; ++vi) {
  14493. var obj = {};
  14494. obj.type = type;
  14495. obj.value = values[vi].value;
  14496. obj.valueTagClass = values[vi].type;
  14497. // if the OID is known, get its name and short name
  14498. if(obj.type in oids) {
  14499. obj.name = oids[obj.type];
  14500. if(obj.name in _shortNames) {
  14501. obj.shortName = _shortNames[obj.name];
  14502. }
  14503. }
  14504. // parse extensions
  14505. if(obj.type === oids.extensionRequest) {
  14506. obj.extensions = [];
  14507. for(var ei = 0; ei < obj.value.length; ++ei) {
  14508. obj.extensions.push(pki$2.certificateExtensionFromAsn1(obj.value[ei]));
  14509. }
  14510. }
  14511. rval.push(obj);
  14512. }
  14513. }
  14514. return rval;
  14515. };
  14516. /**
  14517. * Gets an issuer or subject attribute from its name, type, or short name.
  14518. *
  14519. * @param obj the issuer or subject object.
  14520. * @param options a short name string or an object with:
  14521. * shortName the short name for the attribute.
  14522. * name the name for the attribute.
  14523. * type the type for the attribute.
  14524. *
  14525. * @return the attribute.
  14526. */
  14527. function _getAttribute(obj, options) {
  14528. if(typeof options === 'string') {
  14529. options = {shortName: options};
  14530. }
  14531. var rval = null;
  14532. var attr;
  14533. for(var i = 0; rval === null && i < obj.attributes.length; ++i) {
  14534. attr = obj.attributes[i];
  14535. if(options.type && options.type === attr.type) {
  14536. rval = attr;
  14537. } else if(options.name && options.name === attr.name) {
  14538. rval = attr;
  14539. } else if(options.shortName && options.shortName === attr.shortName) {
  14540. rval = attr;
  14541. }
  14542. }
  14543. return rval;
  14544. }
  14545. /**
  14546. * Converts signature parameters from ASN.1 structure.
  14547. *
  14548. * Currently only RSASSA-PSS supported. The PKCS#1 v1.5 signature scheme had
  14549. * no parameters.
  14550. *
  14551. * RSASSA-PSS-params ::= SEQUENCE {
  14552. * hashAlgorithm [0] HashAlgorithm DEFAULT
  14553. * sha1Identifier,
  14554. * maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT
  14555. * mgf1SHA1Identifier,
  14556. * saltLength [2] INTEGER DEFAULT 20,
  14557. * trailerField [3] INTEGER DEFAULT 1
  14558. * }
  14559. *
  14560. * HashAlgorithm ::= AlgorithmIdentifier
  14561. *
  14562. * MaskGenAlgorithm ::= AlgorithmIdentifier
  14563. *
  14564. * AlgorithmIdentifer ::= SEQUENCE {
  14565. * algorithm OBJECT IDENTIFIER,
  14566. * parameters ANY DEFINED BY algorithm OPTIONAL
  14567. * }
  14568. *
  14569. * @param oid The OID specifying the signature algorithm
  14570. * @param obj The ASN.1 structure holding the parameters
  14571. * @param fillDefaults Whether to use return default values where omitted
  14572. * @return signature parameter object
  14573. */
  14574. var _readSignatureParameters = function(oid, obj, fillDefaults) {
  14575. var params = {};
  14576. if(oid !== oids['RSASSA-PSS']) {
  14577. return params;
  14578. }
  14579. if(fillDefaults) {
  14580. params = {
  14581. hash: {
  14582. algorithmOid: oids['sha1']
  14583. },
  14584. mgf: {
  14585. algorithmOid: oids['mgf1'],
  14586. hash: {
  14587. algorithmOid: oids['sha1']
  14588. }
  14589. },
  14590. saltLength: 20
  14591. };
  14592. }
  14593. var capture = {};
  14594. var errors = [];
  14595. if(!asn1$4.validate(obj, rsassaPssParameterValidator, capture, errors)) {
  14596. var error = new Error('Cannot read RSASSA-PSS parameter block.');
  14597. error.errors = errors;
  14598. throw error;
  14599. }
  14600. if(capture.hashOid !== undefined) {
  14601. params.hash = params.hash || {};
  14602. params.hash.algorithmOid = asn1$4.derToOid(capture.hashOid);
  14603. }
  14604. if(capture.maskGenOid !== undefined) {
  14605. params.mgf = params.mgf || {};
  14606. params.mgf.algorithmOid = asn1$4.derToOid(capture.maskGenOid);
  14607. params.mgf.hash = params.mgf.hash || {};
  14608. params.mgf.hash.algorithmOid = asn1$4.derToOid(capture.maskGenHashOid);
  14609. }
  14610. if(capture.saltLength !== undefined) {
  14611. params.saltLength = capture.saltLength.charCodeAt(0);
  14612. }
  14613. return params;
  14614. };
  14615. /**
  14616. * Converts an X.509 certificate from PEM format.
  14617. *
  14618. * Note: If the certificate is to be verified then compute hash should
  14619. * be set to true. This will scan the TBSCertificate part of the ASN.1
  14620. * object while it is converted so it doesn't need to be converted back
  14621. * to ASN.1-DER-encoding later.
  14622. *
  14623. * @param pem the PEM-formatted certificate.
  14624. * @param computeHash true to compute the hash for verification.
  14625. * @param strict true to be strict when checking ASN.1 value lengths, false to
  14626. * allow truncated values (default: true).
  14627. *
  14628. * @return the certificate.
  14629. */
  14630. pki$2.certificateFromPem = function(pem, computeHash, strict) {
  14631. var msg = forge$e.pem.decode(pem)[0];
  14632. if(msg.type !== 'CERTIFICATE' &&
  14633. msg.type !== 'X509 CERTIFICATE' &&
  14634. msg.type !== 'TRUSTED CERTIFICATE') {
  14635. var error = new Error(
  14636. 'Could not convert certificate from PEM; PEM header type ' +
  14637. 'is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');
  14638. error.headerType = msg.type;
  14639. throw error;
  14640. }
  14641. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  14642. throw new Error(
  14643. 'Could not convert certificate from PEM; PEM is encrypted.');
  14644. }
  14645. // convert DER to ASN.1 object
  14646. var obj = asn1$4.fromDer(msg.body, strict);
  14647. return pki$2.certificateFromAsn1(obj, computeHash);
  14648. };
  14649. /**
  14650. * Converts an X.509 certificate to PEM format.
  14651. *
  14652. * @param cert the certificate.
  14653. * @param maxline the maximum characters per line, defaults to 64.
  14654. *
  14655. * @return the PEM-formatted certificate.
  14656. */
  14657. pki$2.certificateToPem = function(cert, maxline) {
  14658. // convert to ASN.1, then DER, then PEM-encode
  14659. var msg = {
  14660. type: 'CERTIFICATE',
  14661. body: asn1$4.toDer(pki$2.certificateToAsn1(cert)).getBytes()
  14662. };
  14663. return forge$e.pem.encode(msg, {maxline: maxline});
  14664. };
  14665. /**
  14666. * Converts an RSA public key from PEM format.
  14667. *
  14668. * @param pem the PEM-formatted public key.
  14669. *
  14670. * @return the public key.
  14671. */
  14672. pki$2.publicKeyFromPem = function(pem) {
  14673. var msg = forge$e.pem.decode(pem)[0];
  14674. if(msg.type !== 'PUBLIC KEY' && msg.type !== 'RSA PUBLIC KEY') {
  14675. var error = new Error('Could not convert public key from PEM; PEM header ' +
  14676. 'type is not "PUBLIC KEY" or "RSA PUBLIC KEY".');
  14677. error.headerType = msg.type;
  14678. throw error;
  14679. }
  14680. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  14681. throw new Error('Could not convert public key from PEM; PEM is encrypted.');
  14682. }
  14683. // convert DER to ASN.1 object
  14684. var obj = asn1$4.fromDer(msg.body);
  14685. return pki$2.publicKeyFromAsn1(obj);
  14686. };
  14687. /**
  14688. * Converts an RSA public key to PEM format (using a SubjectPublicKeyInfo).
  14689. *
  14690. * @param key the public key.
  14691. * @param maxline the maximum characters per line, defaults to 64.
  14692. *
  14693. * @return the PEM-formatted public key.
  14694. */
  14695. pki$2.publicKeyToPem = function(key, maxline) {
  14696. // convert to ASN.1, then DER, then PEM-encode
  14697. var msg = {
  14698. type: 'PUBLIC KEY',
  14699. body: asn1$4.toDer(pki$2.publicKeyToAsn1(key)).getBytes()
  14700. };
  14701. return forge$e.pem.encode(msg, {maxline: maxline});
  14702. };
  14703. /**
  14704. * Converts an RSA public key to PEM format (using an RSAPublicKey).
  14705. *
  14706. * @param key the public key.
  14707. * @param maxline the maximum characters per line, defaults to 64.
  14708. *
  14709. * @return the PEM-formatted public key.
  14710. */
  14711. pki$2.publicKeyToRSAPublicKeyPem = function(key, maxline) {
  14712. // convert to ASN.1, then DER, then PEM-encode
  14713. var msg = {
  14714. type: 'RSA PUBLIC KEY',
  14715. body: asn1$4.toDer(pki$2.publicKeyToRSAPublicKey(key)).getBytes()
  14716. };
  14717. return forge$e.pem.encode(msg, {maxline: maxline});
  14718. };
  14719. /**
  14720. * Gets a fingerprint for the given public key.
  14721. *
  14722. * @param options the options to use.
  14723. * [md] the message digest object to use (defaults to forge.md.sha1).
  14724. * [type] the type of fingerprint, such as 'RSAPublicKey',
  14725. * 'SubjectPublicKeyInfo' (defaults to 'RSAPublicKey').
  14726. * [encoding] an alternative output encoding, such as 'hex'
  14727. * (defaults to none, outputs a byte buffer).
  14728. * [delimiter] the delimiter to use between bytes for 'hex' encoded
  14729. * output, eg: ':' (defaults to none).
  14730. *
  14731. * @return the fingerprint as a byte buffer or other encoding based on options.
  14732. */
  14733. pki$2.getPublicKeyFingerprint = function(key, options) {
  14734. options = options || {};
  14735. var md = options.md || forge$e.md.sha1.create();
  14736. var type = options.type || 'RSAPublicKey';
  14737. var bytes;
  14738. switch(type) {
  14739. case 'RSAPublicKey':
  14740. bytes = asn1$4.toDer(pki$2.publicKeyToRSAPublicKey(key)).getBytes();
  14741. break;
  14742. case 'SubjectPublicKeyInfo':
  14743. bytes = asn1$4.toDer(pki$2.publicKeyToAsn1(key)).getBytes();
  14744. break;
  14745. default:
  14746. throw new Error('Unknown fingerprint type "' + options.type + '".');
  14747. }
  14748. // hash public key bytes
  14749. md.start();
  14750. md.update(bytes);
  14751. var digest = md.digest();
  14752. if(options.encoding === 'hex') {
  14753. var hex = digest.toHex();
  14754. if(options.delimiter) {
  14755. return hex.match(/.{2}/g).join(options.delimiter);
  14756. }
  14757. return hex;
  14758. } else if(options.encoding === 'binary') {
  14759. return digest.getBytes();
  14760. } else if(options.encoding) {
  14761. throw new Error('Unknown encoding "' + options.encoding + '".');
  14762. }
  14763. return digest;
  14764. };
  14765. /**
  14766. * Converts a PKCS#10 certification request (CSR) from PEM format.
  14767. *
  14768. * Note: If the certification request is to be verified then compute hash
  14769. * should be set to true. This will scan the CertificationRequestInfo part of
  14770. * the ASN.1 object while it is converted so it doesn't need to be converted
  14771. * back to ASN.1-DER-encoding later.
  14772. *
  14773. * @param pem the PEM-formatted certificate.
  14774. * @param computeHash true to compute the hash for verification.
  14775. * @param strict true to be strict when checking ASN.1 value lengths, false to
  14776. * allow truncated values (default: true).
  14777. *
  14778. * @return the certification request (CSR).
  14779. */
  14780. pki$2.certificationRequestFromPem = function(pem, computeHash, strict) {
  14781. var msg = forge$e.pem.decode(pem)[0];
  14782. if(msg.type !== 'CERTIFICATE REQUEST') {
  14783. var error = new Error('Could not convert certification request from PEM; ' +
  14784. 'PEM header type is not "CERTIFICATE REQUEST".');
  14785. error.headerType = msg.type;
  14786. throw error;
  14787. }
  14788. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  14789. throw new Error('Could not convert certification request from PEM; ' +
  14790. 'PEM is encrypted.');
  14791. }
  14792. // convert DER to ASN.1 object
  14793. var obj = asn1$4.fromDer(msg.body, strict);
  14794. return pki$2.certificationRequestFromAsn1(obj, computeHash);
  14795. };
  14796. /**
  14797. * Converts a PKCS#10 certification request (CSR) to PEM format.
  14798. *
  14799. * @param csr the certification request.
  14800. * @param maxline the maximum characters per line, defaults to 64.
  14801. *
  14802. * @return the PEM-formatted certification request.
  14803. */
  14804. pki$2.certificationRequestToPem = function(csr, maxline) {
  14805. // convert to ASN.1, then DER, then PEM-encode
  14806. var msg = {
  14807. type: 'CERTIFICATE REQUEST',
  14808. body: asn1$4.toDer(pki$2.certificationRequestToAsn1(csr)).getBytes()
  14809. };
  14810. return forge$e.pem.encode(msg, {maxline: maxline});
  14811. };
  14812. /**
  14813. * Creates an empty X.509v3 RSA certificate.
  14814. *
  14815. * @return the certificate.
  14816. */
  14817. pki$2.createCertificate = function() {
  14818. var cert = {};
  14819. cert.version = 0x02;
  14820. cert.serialNumber = '00';
  14821. cert.signatureOid = null;
  14822. cert.signature = null;
  14823. cert.siginfo = {};
  14824. cert.siginfo.algorithmOid = null;
  14825. cert.validity = {};
  14826. cert.validity.notBefore = new Date();
  14827. cert.validity.notAfter = new Date();
  14828. cert.issuer = {};
  14829. cert.issuer.getField = function(sn) {
  14830. return _getAttribute(cert.issuer, sn);
  14831. };
  14832. cert.issuer.addField = function(attr) {
  14833. _fillMissingFields([attr]);
  14834. cert.issuer.attributes.push(attr);
  14835. };
  14836. cert.issuer.attributes = [];
  14837. cert.issuer.hash = null;
  14838. cert.subject = {};
  14839. cert.subject.getField = function(sn) {
  14840. return _getAttribute(cert.subject, sn);
  14841. };
  14842. cert.subject.addField = function(attr) {
  14843. _fillMissingFields([attr]);
  14844. cert.subject.attributes.push(attr);
  14845. };
  14846. cert.subject.attributes = [];
  14847. cert.subject.hash = null;
  14848. cert.extensions = [];
  14849. cert.publicKey = null;
  14850. cert.md = null;
  14851. /**
  14852. * Sets the subject of this certificate.
  14853. *
  14854. * @param attrs the array of subject attributes to use.
  14855. * @param uniqueId an optional a unique ID to use.
  14856. */
  14857. cert.setSubject = function(attrs, uniqueId) {
  14858. // set new attributes, clear hash
  14859. _fillMissingFields(attrs);
  14860. cert.subject.attributes = attrs;
  14861. delete cert.subject.uniqueId;
  14862. if(uniqueId) {
  14863. // TODO: support arbitrary bit length ids
  14864. cert.subject.uniqueId = uniqueId;
  14865. }
  14866. cert.subject.hash = null;
  14867. };
  14868. /**
  14869. * Sets the issuer of this certificate.
  14870. *
  14871. * @param attrs the array of issuer attributes to use.
  14872. * @param uniqueId an optional a unique ID to use.
  14873. */
  14874. cert.setIssuer = function(attrs, uniqueId) {
  14875. // set new attributes, clear hash
  14876. _fillMissingFields(attrs);
  14877. cert.issuer.attributes = attrs;
  14878. delete cert.issuer.uniqueId;
  14879. if(uniqueId) {
  14880. // TODO: support arbitrary bit length ids
  14881. cert.issuer.uniqueId = uniqueId;
  14882. }
  14883. cert.issuer.hash = null;
  14884. };
  14885. /**
  14886. * Sets the extensions of this certificate.
  14887. *
  14888. * @param exts the array of extensions to use.
  14889. */
  14890. cert.setExtensions = function(exts) {
  14891. for(var i = 0; i < exts.length; ++i) {
  14892. _fillMissingExtensionFields(exts[i], {cert: cert});
  14893. }
  14894. // set new extensions
  14895. cert.extensions = exts;
  14896. };
  14897. /**
  14898. * Gets an extension by its name or id.
  14899. *
  14900. * @param options the name to use or an object with:
  14901. * name the name to use.
  14902. * id the id to use.
  14903. *
  14904. * @return the extension or null if not found.
  14905. */
  14906. cert.getExtension = function(options) {
  14907. if(typeof options === 'string') {
  14908. options = {name: options};
  14909. }
  14910. var rval = null;
  14911. var ext;
  14912. for(var i = 0; rval === null && i < cert.extensions.length; ++i) {
  14913. ext = cert.extensions[i];
  14914. if(options.id && ext.id === options.id) {
  14915. rval = ext;
  14916. } else if(options.name && ext.name === options.name) {
  14917. rval = ext;
  14918. }
  14919. }
  14920. return rval;
  14921. };
  14922. /**
  14923. * Signs this certificate using the given private key.
  14924. *
  14925. * @param key the private key to sign with.
  14926. * @param md the message digest object to use (defaults to forge.md.sha1).
  14927. */
  14928. cert.sign = function(key, md) {
  14929. // TODO: get signature OID from private key
  14930. cert.md = md || forge$e.md.sha1.create();
  14931. var algorithmOid = oids[cert.md.algorithm + 'WithRSAEncryption'];
  14932. if(!algorithmOid) {
  14933. var error = new Error('Could not compute certificate digest. ' +
  14934. 'Unknown message digest algorithm OID.');
  14935. error.algorithm = cert.md.algorithm;
  14936. throw error;
  14937. }
  14938. cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid;
  14939. // get TBSCertificate, convert to DER
  14940. cert.tbsCertificate = pki$2.getTBSCertificate(cert);
  14941. var bytes = asn1$4.toDer(cert.tbsCertificate);
  14942. // digest and sign
  14943. cert.md.update(bytes.getBytes());
  14944. cert.signature = key.sign(cert.md);
  14945. };
  14946. /**
  14947. * Attempts verify the signature on the passed certificate using this
  14948. * certificate's public key.
  14949. *
  14950. * @param child the certificate to verify.
  14951. *
  14952. * @return true if verified, false if not.
  14953. */
  14954. cert.verify = function(child) {
  14955. var rval = false;
  14956. if(!cert.issued(child)) {
  14957. var issuer = child.issuer;
  14958. var subject = cert.subject;
  14959. var error = new Error(
  14960. 'The parent certificate did not issue the given child ' +
  14961. 'certificate; the child certificate\'s issuer does not match the ' +
  14962. 'parent\'s subject.');
  14963. error.expectedIssuer = issuer.attributes;
  14964. error.actualIssuer = subject.attributes;
  14965. throw error;
  14966. }
  14967. var md = child.md;
  14968. if(md === null) {
  14969. // check signature OID for supported signature types
  14970. if(child.signatureOid in oids) {
  14971. var oid = oids[child.signatureOid];
  14972. switch(oid) {
  14973. case 'sha1WithRSAEncryption':
  14974. md = forge$e.md.sha1.create();
  14975. break;
  14976. case 'md5WithRSAEncryption':
  14977. md = forge$e.md.md5.create();
  14978. break;
  14979. case 'sha256WithRSAEncryption':
  14980. md = forge$e.md.sha256.create();
  14981. break;
  14982. case 'sha384WithRSAEncryption':
  14983. md = forge$e.md.sha384.create();
  14984. break;
  14985. case 'sha512WithRSAEncryption':
  14986. md = forge$e.md.sha512.create();
  14987. break;
  14988. case 'RSASSA-PSS':
  14989. md = forge$e.md.sha256.create();
  14990. break;
  14991. }
  14992. }
  14993. if(md === null) {
  14994. var error = new Error('Could not compute certificate digest. ' +
  14995. 'Unknown signature OID.');
  14996. error.signatureOid = child.signatureOid;
  14997. throw error;
  14998. }
  14999. // produce DER formatted TBSCertificate and digest it
  15000. var tbsCertificate = child.tbsCertificate || pki$2.getTBSCertificate(child);
  15001. var bytes = asn1$4.toDer(tbsCertificate);
  15002. md.update(bytes.getBytes());
  15003. }
  15004. if(md !== null) {
  15005. var scheme;
  15006. switch(child.signatureOid) {
  15007. case oids.sha1WithRSAEncryption:
  15008. scheme = undefined; /* use PKCS#1 v1.5 padding scheme */
  15009. break;
  15010. case oids['RSASSA-PSS']:
  15011. var hash, mgf;
  15012. /* initialize mgf */
  15013. hash = oids[child.signatureParameters.mgf.hash.algorithmOid];
  15014. if(hash === undefined || forge$e.md[hash] === undefined) {
  15015. var error = new Error('Unsupported MGF hash function.');
  15016. error.oid = child.signatureParameters.mgf.hash.algorithmOid;
  15017. error.name = hash;
  15018. throw error;
  15019. }
  15020. mgf = oids[child.signatureParameters.mgf.algorithmOid];
  15021. if(mgf === undefined || forge$e.mgf[mgf] === undefined) {
  15022. var error = new Error('Unsupported MGF function.');
  15023. error.oid = child.signatureParameters.mgf.algorithmOid;
  15024. error.name = mgf;
  15025. throw error;
  15026. }
  15027. mgf = forge$e.mgf[mgf].create(forge$e.md[hash].create());
  15028. /* initialize hash function */
  15029. hash = oids[child.signatureParameters.hash.algorithmOid];
  15030. if(hash === undefined || forge$e.md[hash] === undefined) {
  15031. throw {
  15032. message: 'Unsupported RSASSA-PSS hash function.',
  15033. oid: child.signatureParameters.hash.algorithmOid,
  15034. name: hash
  15035. };
  15036. }
  15037. scheme = forge$e.pss.create(forge$e.md[hash].create(), mgf,
  15038. child.signatureParameters.saltLength);
  15039. break;
  15040. }
  15041. // verify signature on cert using public key
  15042. rval = cert.publicKey.verify(
  15043. md.digest().getBytes(), child.signature, scheme);
  15044. }
  15045. return rval;
  15046. };
  15047. /**
  15048. * Returns true if this certificate's issuer matches the passed
  15049. * certificate's subject. Note that no signature check is performed.
  15050. *
  15051. * @param parent the certificate to check.
  15052. *
  15053. * @return true if this certificate's issuer matches the passed certificate's
  15054. * subject.
  15055. */
  15056. cert.isIssuer = function(parent) {
  15057. var rval = false;
  15058. var i = cert.issuer;
  15059. var s = parent.subject;
  15060. // compare hashes if present
  15061. if(i.hash && s.hash) {
  15062. rval = (i.hash === s.hash);
  15063. } else if(i.attributes.length === s.attributes.length) {
  15064. // all attributes are the same so issuer matches subject
  15065. rval = true;
  15066. var iattr, sattr;
  15067. for(var n = 0; rval && n < i.attributes.length; ++n) {
  15068. iattr = i.attributes[n];
  15069. sattr = s.attributes[n];
  15070. if(iattr.type !== sattr.type || iattr.value !== sattr.value) {
  15071. // attribute mismatch
  15072. rval = false;
  15073. }
  15074. }
  15075. }
  15076. return rval;
  15077. };
  15078. /**
  15079. * Returns true if this certificate's subject matches the issuer of the
  15080. * given certificate). Note that not signature check is performed.
  15081. *
  15082. * @param child the certificate to check.
  15083. *
  15084. * @return true if this certificate's subject matches the passed
  15085. * certificate's issuer.
  15086. */
  15087. cert.issued = function(child) {
  15088. return child.isIssuer(cert);
  15089. };
  15090. /**
  15091. * Generates the subjectKeyIdentifier for this certificate as byte buffer.
  15092. *
  15093. * @return the subjectKeyIdentifier for this certificate as byte buffer.
  15094. */
  15095. cert.generateSubjectKeyIdentifier = function() {
  15096. /* See: 4.2.1.2 section of the the RFC3280, keyIdentifier is either:
  15097. (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
  15098. value of the BIT STRING subjectPublicKey (excluding the tag,
  15099. length, and number of unused bits).
  15100. (2) The keyIdentifier is composed of a four bit type field with
  15101. the value 0100 followed by the least significant 60 bits of the
  15102. SHA-1 hash of the value of the BIT STRING subjectPublicKey
  15103. (excluding the tag, length, and number of unused bit string bits).
  15104. */
  15105. // skipping the tag, length, and number of unused bits is the same
  15106. // as just using the RSAPublicKey (for RSA keys, which are the
  15107. // only ones supported)
  15108. return pki$2.getPublicKeyFingerprint(cert.publicKey, {type: 'RSAPublicKey'});
  15109. };
  15110. /**
  15111. * Verifies the subjectKeyIdentifier extension value for this certificate
  15112. * against its public key. If no extension is found, false will be
  15113. * returned.
  15114. *
  15115. * @return true if verified, false if not.
  15116. */
  15117. cert.verifySubjectKeyIdentifier = function() {
  15118. var oid = oids['subjectKeyIdentifier'];
  15119. for(var i = 0; i < cert.extensions.length; ++i) {
  15120. var ext = cert.extensions[i];
  15121. if(ext.id === oid) {
  15122. var ski = cert.generateSubjectKeyIdentifier().getBytes();
  15123. return (forge$e.util.hexToBytes(ext.subjectKeyIdentifier) === ski);
  15124. }
  15125. }
  15126. return false;
  15127. };
  15128. return cert;
  15129. };
  15130. /**
  15131. * Converts an X.509v3 RSA certificate from an ASN.1 object.
  15132. *
  15133. * Note: If the certificate is to be verified then compute hash should
  15134. * be set to true. There is currently no implementation for converting
  15135. * a certificate back to ASN.1 so the TBSCertificate part of the ASN.1
  15136. * object needs to be scanned before the cert object is created.
  15137. *
  15138. * @param obj the asn1 representation of an X.509v3 RSA certificate.
  15139. * @param computeHash true to compute the hash for verification.
  15140. *
  15141. * @return the certificate.
  15142. */
  15143. pki$2.certificateFromAsn1 = function(obj, computeHash) {
  15144. // validate certificate and capture data
  15145. var capture = {};
  15146. var errors = [];
  15147. if(!asn1$4.validate(obj, x509CertificateValidator, capture, errors)) {
  15148. var error = new Error('Cannot read X.509 certificate. ' +
  15149. 'ASN.1 object is not an X509v3 Certificate.');
  15150. error.errors = errors;
  15151. throw error;
  15152. }
  15153. // get oid
  15154. var oid = asn1$4.derToOid(capture.publicKeyOid);
  15155. if(oid !== pki$2.oids.rsaEncryption) {
  15156. throw new Error('Cannot read public key. OID is not RSA.');
  15157. }
  15158. // create certificate
  15159. var cert = pki$2.createCertificate();
  15160. cert.version = capture.certVersion ?
  15161. capture.certVersion.charCodeAt(0) : 0;
  15162. var serial = forge$e.util.createBuffer(capture.certSerialNumber);
  15163. cert.serialNumber = serial.toHex();
  15164. cert.signatureOid = forge$e.asn1.derToOid(capture.certSignatureOid);
  15165. cert.signatureParameters = _readSignatureParameters(
  15166. cert.signatureOid, capture.certSignatureParams, true);
  15167. cert.siginfo.algorithmOid = forge$e.asn1.derToOid(capture.certinfoSignatureOid);
  15168. cert.siginfo.parameters = _readSignatureParameters(cert.siginfo.algorithmOid,
  15169. capture.certinfoSignatureParams, false);
  15170. cert.signature = capture.certSignature;
  15171. var validity = [];
  15172. if(capture.certValidity1UTCTime !== undefined) {
  15173. validity.push(asn1$4.utcTimeToDate(capture.certValidity1UTCTime));
  15174. }
  15175. if(capture.certValidity2GeneralizedTime !== undefined) {
  15176. validity.push(asn1$4.generalizedTimeToDate(
  15177. capture.certValidity2GeneralizedTime));
  15178. }
  15179. if(capture.certValidity3UTCTime !== undefined) {
  15180. validity.push(asn1$4.utcTimeToDate(capture.certValidity3UTCTime));
  15181. }
  15182. if(capture.certValidity4GeneralizedTime !== undefined) {
  15183. validity.push(asn1$4.generalizedTimeToDate(
  15184. capture.certValidity4GeneralizedTime));
  15185. }
  15186. if(validity.length > 2) {
  15187. throw new Error('Cannot read notBefore/notAfter validity times; more ' +
  15188. 'than two times were provided in the certificate.');
  15189. }
  15190. if(validity.length < 2) {
  15191. throw new Error('Cannot read notBefore/notAfter validity times; they ' +
  15192. 'were not provided as either UTCTime or GeneralizedTime.');
  15193. }
  15194. cert.validity.notBefore = validity[0];
  15195. cert.validity.notAfter = validity[1];
  15196. // keep TBSCertificate to preserve signature when exporting
  15197. cert.tbsCertificate = capture.tbsCertificate;
  15198. if(computeHash) {
  15199. // check signature OID for supported signature types
  15200. cert.md = null;
  15201. if(cert.signatureOid in oids) {
  15202. var oid = oids[cert.signatureOid];
  15203. switch(oid) {
  15204. case 'sha1WithRSAEncryption':
  15205. cert.md = forge$e.md.sha1.create();
  15206. break;
  15207. case 'md5WithRSAEncryption':
  15208. cert.md = forge$e.md.md5.create();
  15209. break;
  15210. case 'sha256WithRSAEncryption':
  15211. cert.md = forge$e.md.sha256.create();
  15212. break;
  15213. case 'sha384WithRSAEncryption':
  15214. cert.md = forge$e.md.sha384.create();
  15215. break;
  15216. case 'sha512WithRSAEncryption':
  15217. cert.md = forge$e.md.sha512.create();
  15218. break;
  15219. case 'RSASSA-PSS':
  15220. cert.md = forge$e.md.sha256.create();
  15221. break;
  15222. }
  15223. }
  15224. if(cert.md === null) {
  15225. var error = new Error('Could not compute certificate digest. ' +
  15226. 'Unknown signature OID.');
  15227. error.signatureOid = cert.signatureOid;
  15228. throw error;
  15229. }
  15230. // produce DER formatted TBSCertificate and digest it
  15231. var bytes = asn1$4.toDer(cert.tbsCertificate);
  15232. cert.md.update(bytes.getBytes());
  15233. }
  15234. // handle issuer, build issuer message digest
  15235. var imd = forge$e.md.sha1.create();
  15236. cert.issuer.getField = function(sn) {
  15237. return _getAttribute(cert.issuer, sn);
  15238. };
  15239. cert.issuer.addField = function(attr) {
  15240. _fillMissingFields([attr]);
  15241. cert.issuer.attributes.push(attr);
  15242. };
  15243. cert.issuer.attributes = pki$2.RDNAttributesAsArray(capture.certIssuer, imd);
  15244. if(capture.certIssuerUniqueId) {
  15245. cert.issuer.uniqueId = capture.certIssuerUniqueId;
  15246. }
  15247. cert.issuer.hash = imd.digest().toHex();
  15248. // handle subject, build subject message digest
  15249. var smd = forge$e.md.sha1.create();
  15250. cert.subject.getField = function(sn) {
  15251. return _getAttribute(cert.subject, sn);
  15252. };
  15253. cert.subject.addField = function(attr) {
  15254. _fillMissingFields([attr]);
  15255. cert.subject.attributes.push(attr);
  15256. };
  15257. cert.subject.attributes = pki$2.RDNAttributesAsArray(capture.certSubject, smd);
  15258. if(capture.certSubjectUniqueId) {
  15259. cert.subject.uniqueId = capture.certSubjectUniqueId;
  15260. }
  15261. cert.subject.hash = smd.digest().toHex();
  15262. // handle extensions
  15263. if(capture.certExtensions) {
  15264. cert.extensions = pki$2.certificateExtensionsFromAsn1(capture.certExtensions);
  15265. } else {
  15266. cert.extensions = [];
  15267. }
  15268. // convert RSA public key from ASN.1
  15269. cert.publicKey = pki$2.publicKeyFromAsn1(capture.subjectPublicKeyInfo);
  15270. return cert;
  15271. };
  15272. /**
  15273. * Converts an ASN.1 extensions object (with extension sequences as its
  15274. * values) into an array of extension objects with types and values.
  15275. *
  15276. * Supported extensions:
  15277. *
  15278. * id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 }
  15279. * KeyUsage ::= BIT STRING {
  15280. * digitalSignature (0),
  15281. * nonRepudiation (1),
  15282. * keyEncipherment (2),
  15283. * dataEncipherment (3),
  15284. * keyAgreement (4),
  15285. * keyCertSign (5),
  15286. * cRLSign (6),
  15287. * encipherOnly (7),
  15288. * decipherOnly (8)
  15289. * }
  15290. *
  15291. * id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 }
  15292. * BasicConstraints ::= SEQUENCE {
  15293. * cA BOOLEAN DEFAULT FALSE,
  15294. * pathLenConstraint INTEGER (0..MAX) OPTIONAL
  15295. * }
  15296. *
  15297. * subjectAltName EXTENSION ::= {
  15298. * SYNTAX GeneralNames
  15299. * IDENTIFIED BY id-ce-subjectAltName
  15300. * }
  15301. *
  15302. * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
  15303. *
  15304. * GeneralName ::= CHOICE {
  15305. * otherName [0] INSTANCE OF OTHER-NAME,
  15306. * rfc822Name [1] IA5String,
  15307. * dNSName [2] IA5String,
  15308. * x400Address [3] ORAddress,
  15309. * directoryName [4] Name,
  15310. * ediPartyName [5] EDIPartyName,
  15311. * uniformResourceIdentifier [6] IA5String,
  15312. * IPAddress [7] OCTET STRING,
  15313. * registeredID [8] OBJECT IDENTIFIER
  15314. * }
  15315. *
  15316. * OTHER-NAME ::= TYPE-IDENTIFIER
  15317. *
  15318. * EDIPartyName ::= SEQUENCE {
  15319. * nameAssigner [0] DirectoryString {ub-name} OPTIONAL,
  15320. * partyName [1] DirectoryString {ub-name}
  15321. * }
  15322. *
  15323. * @param exts the extensions ASN.1 with extension sequences to parse.
  15324. *
  15325. * @return the array.
  15326. */
  15327. pki$2.certificateExtensionsFromAsn1 = function(exts) {
  15328. var rval = [];
  15329. for(var i = 0; i < exts.value.length; ++i) {
  15330. // get extension sequence
  15331. var extseq = exts.value[i];
  15332. for(var ei = 0; ei < extseq.value.length; ++ei) {
  15333. rval.push(pki$2.certificateExtensionFromAsn1(extseq.value[ei]));
  15334. }
  15335. }
  15336. return rval;
  15337. };
  15338. /**
  15339. * Parses a single certificate extension from ASN.1.
  15340. *
  15341. * @param ext the extension in ASN.1 format.
  15342. *
  15343. * @return the parsed extension as an object.
  15344. */
  15345. pki$2.certificateExtensionFromAsn1 = function(ext) {
  15346. // an extension has:
  15347. // [0] extnID OBJECT IDENTIFIER
  15348. // [1] critical BOOLEAN DEFAULT FALSE
  15349. // [2] extnValue OCTET STRING
  15350. var e = {};
  15351. e.id = asn1$4.derToOid(ext.value[0].value);
  15352. e.critical = false;
  15353. if(ext.value[1].type === asn1$4.Type.BOOLEAN) {
  15354. e.critical = (ext.value[1].value.charCodeAt(0) !== 0x00);
  15355. e.value = ext.value[2].value;
  15356. } else {
  15357. e.value = ext.value[1].value;
  15358. }
  15359. // if the oid is known, get its name
  15360. if(e.id in oids) {
  15361. e.name = oids[e.id];
  15362. // handle key usage
  15363. if(e.name === 'keyUsage') {
  15364. // get value as BIT STRING
  15365. var ev = asn1$4.fromDer(e.value);
  15366. var b2 = 0x00;
  15367. var b3 = 0x00;
  15368. if(ev.value.length > 1) {
  15369. // skip first byte, just indicates unused bits which
  15370. // will be padded with 0s anyway
  15371. // get bytes with flag bits
  15372. b2 = ev.value.charCodeAt(1);
  15373. b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0;
  15374. }
  15375. // set flags
  15376. e.digitalSignature = (b2 & 0x80) === 0x80;
  15377. e.nonRepudiation = (b2 & 0x40) === 0x40;
  15378. e.keyEncipherment = (b2 & 0x20) === 0x20;
  15379. e.dataEncipherment = (b2 & 0x10) === 0x10;
  15380. e.keyAgreement = (b2 & 0x08) === 0x08;
  15381. e.keyCertSign = (b2 & 0x04) === 0x04;
  15382. e.cRLSign = (b2 & 0x02) === 0x02;
  15383. e.encipherOnly = (b2 & 0x01) === 0x01;
  15384. e.decipherOnly = (b3 & 0x80) === 0x80;
  15385. } else if(e.name === 'basicConstraints') {
  15386. // handle basic constraints
  15387. // get value as SEQUENCE
  15388. var ev = asn1$4.fromDer(e.value);
  15389. // get cA BOOLEAN flag (defaults to false)
  15390. if(ev.value.length > 0 && ev.value[0].type === asn1$4.Type.BOOLEAN) {
  15391. e.cA = (ev.value[0].value.charCodeAt(0) !== 0x00);
  15392. } else {
  15393. e.cA = false;
  15394. }
  15395. // get path length constraint
  15396. var value = null;
  15397. if(ev.value.length > 0 && ev.value[0].type === asn1$4.Type.INTEGER) {
  15398. value = ev.value[0].value;
  15399. } else if(ev.value.length > 1) {
  15400. value = ev.value[1].value;
  15401. }
  15402. if(value !== null) {
  15403. e.pathLenConstraint = asn1$4.derToInteger(value);
  15404. }
  15405. } else if(e.name === 'extKeyUsage') {
  15406. // handle extKeyUsage
  15407. // value is a SEQUENCE of OIDs
  15408. var ev = asn1$4.fromDer(e.value);
  15409. for(var vi = 0; vi < ev.value.length; ++vi) {
  15410. var oid = asn1$4.derToOid(ev.value[vi].value);
  15411. if(oid in oids) {
  15412. e[oids[oid]] = true;
  15413. } else {
  15414. e[oid] = true;
  15415. }
  15416. }
  15417. } else if(e.name === 'nsCertType') {
  15418. // handle nsCertType
  15419. // get value as BIT STRING
  15420. var ev = asn1$4.fromDer(e.value);
  15421. var b2 = 0x00;
  15422. if(ev.value.length > 1) {
  15423. // skip first byte, just indicates unused bits which
  15424. // will be padded with 0s anyway
  15425. // get bytes with flag bits
  15426. b2 = ev.value.charCodeAt(1);
  15427. }
  15428. // set flags
  15429. e.client = (b2 & 0x80) === 0x80;
  15430. e.server = (b2 & 0x40) === 0x40;
  15431. e.email = (b2 & 0x20) === 0x20;
  15432. e.objsign = (b2 & 0x10) === 0x10;
  15433. e.reserved = (b2 & 0x08) === 0x08;
  15434. e.sslCA = (b2 & 0x04) === 0x04;
  15435. e.emailCA = (b2 & 0x02) === 0x02;
  15436. e.objCA = (b2 & 0x01) === 0x01;
  15437. } else if(
  15438. e.name === 'subjectAltName' ||
  15439. e.name === 'issuerAltName') {
  15440. // handle subjectAltName/issuerAltName
  15441. e.altNames = [];
  15442. // ev is a SYNTAX SEQUENCE
  15443. var gn;
  15444. var ev = asn1$4.fromDer(e.value);
  15445. for(var n = 0; n < ev.value.length; ++n) {
  15446. // get GeneralName
  15447. gn = ev.value[n];
  15448. var altName = {
  15449. type: gn.type,
  15450. value: gn.value
  15451. };
  15452. e.altNames.push(altName);
  15453. // Note: Support for types 1,2,6,7,8
  15454. switch(gn.type) {
  15455. // rfc822Name
  15456. case 1:
  15457. // dNSName
  15458. case 2:
  15459. // uniformResourceIdentifier (URI)
  15460. case 6:
  15461. break;
  15462. // IPAddress
  15463. case 7:
  15464. // convert to IPv4/IPv6 string representation
  15465. altName.ip = forge$e.util.bytesToIP(gn.value);
  15466. break;
  15467. // registeredID
  15468. case 8:
  15469. altName.oid = asn1$4.derToOid(gn.value);
  15470. break;
  15471. // unsupported
  15472. }
  15473. }
  15474. } else if(e.name === 'subjectKeyIdentifier') {
  15475. // value is an OCTETSTRING w/the hash of the key-type specific
  15476. // public key structure (eg: RSAPublicKey)
  15477. var ev = asn1$4.fromDer(e.value);
  15478. e.subjectKeyIdentifier = forge$e.util.bytesToHex(ev.value);
  15479. }
  15480. }
  15481. return e;
  15482. };
  15483. /**
  15484. * Converts a PKCS#10 certification request (CSR) from an ASN.1 object.
  15485. *
  15486. * Note: If the certification request is to be verified then compute hash
  15487. * should be set to true. There is currently no implementation for converting
  15488. * a certificate back to ASN.1 so the CertificationRequestInfo part of the
  15489. * ASN.1 object needs to be scanned before the csr object is created.
  15490. *
  15491. * @param obj the asn1 representation of a PKCS#10 certification request (CSR).
  15492. * @param computeHash true to compute the hash for verification.
  15493. *
  15494. * @return the certification request (CSR).
  15495. */
  15496. pki$2.certificationRequestFromAsn1 = function(obj, computeHash) {
  15497. // validate certification request and capture data
  15498. var capture = {};
  15499. var errors = [];
  15500. if(!asn1$4.validate(obj, certificationRequestValidator, capture, errors)) {
  15501. var error = new Error('Cannot read PKCS#10 certificate request. ' +
  15502. 'ASN.1 object is not a PKCS#10 CertificationRequest.');
  15503. error.errors = errors;
  15504. throw error;
  15505. }
  15506. // get oid
  15507. var oid = asn1$4.derToOid(capture.publicKeyOid);
  15508. if(oid !== pki$2.oids.rsaEncryption) {
  15509. throw new Error('Cannot read public key. OID is not RSA.');
  15510. }
  15511. // create certification request
  15512. var csr = pki$2.createCertificationRequest();
  15513. csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0;
  15514. csr.signatureOid = forge$e.asn1.derToOid(capture.csrSignatureOid);
  15515. csr.signatureParameters = _readSignatureParameters(
  15516. csr.signatureOid, capture.csrSignatureParams, true);
  15517. csr.siginfo.algorithmOid = forge$e.asn1.derToOid(capture.csrSignatureOid);
  15518. csr.siginfo.parameters = _readSignatureParameters(
  15519. csr.siginfo.algorithmOid, capture.csrSignatureParams, false);
  15520. csr.signature = capture.csrSignature;
  15521. // keep CertificationRequestInfo to preserve signature when exporting
  15522. csr.certificationRequestInfo = capture.certificationRequestInfo;
  15523. if(computeHash) {
  15524. // check signature OID for supported signature types
  15525. csr.md = null;
  15526. if(csr.signatureOid in oids) {
  15527. var oid = oids[csr.signatureOid];
  15528. switch(oid) {
  15529. case 'sha1WithRSAEncryption':
  15530. csr.md = forge$e.md.sha1.create();
  15531. break;
  15532. case 'md5WithRSAEncryption':
  15533. csr.md = forge$e.md.md5.create();
  15534. break;
  15535. case 'sha256WithRSAEncryption':
  15536. csr.md = forge$e.md.sha256.create();
  15537. break;
  15538. case 'sha384WithRSAEncryption':
  15539. csr.md = forge$e.md.sha384.create();
  15540. break;
  15541. case 'sha512WithRSAEncryption':
  15542. csr.md = forge$e.md.sha512.create();
  15543. break;
  15544. case 'RSASSA-PSS':
  15545. csr.md = forge$e.md.sha256.create();
  15546. break;
  15547. }
  15548. }
  15549. if(csr.md === null) {
  15550. var error = new Error('Could not compute certification request digest. ' +
  15551. 'Unknown signature OID.');
  15552. error.signatureOid = csr.signatureOid;
  15553. throw error;
  15554. }
  15555. // produce DER formatted CertificationRequestInfo and digest it
  15556. var bytes = asn1$4.toDer(csr.certificationRequestInfo);
  15557. csr.md.update(bytes.getBytes());
  15558. }
  15559. // handle subject, build subject message digest
  15560. var smd = forge$e.md.sha1.create();
  15561. csr.subject.getField = function(sn) {
  15562. return _getAttribute(csr.subject, sn);
  15563. };
  15564. csr.subject.addField = function(attr) {
  15565. _fillMissingFields([attr]);
  15566. csr.subject.attributes.push(attr);
  15567. };
  15568. csr.subject.attributes = pki$2.RDNAttributesAsArray(
  15569. capture.certificationRequestInfoSubject, smd);
  15570. csr.subject.hash = smd.digest().toHex();
  15571. // convert RSA public key from ASN.1
  15572. csr.publicKey = pki$2.publicKeyFromAsn1(capture.subjectPublicKeyInfo);
  15573. // convert attributes from ASN.1
  15574. csr.getAttribute = function(sn) {
  15575. return _getAttribute(csr, sn);
  15576. };
  15577. csr.addAttribute = function(attr) {
  15578. _fillMissingFields([attr]);
  15579. csr.attributes.push(attr);
  15580. };
  15581. csr.attributes = pki$2.CRIAttributesAsArray(
  15582. capture.certificationRequestInfoAttributes || []);
  15583. return csr;
  15584. };
  15585. /**
  15586. * Creates an empty certification request (a CSR or certificate signing
  15587. * request). Once created, its public key and attributes can be set and then
  15588. * it can be signed.
  15589. *
  15590. * @return the empty certification request.
  15591. */
  15592. pki$2.createCertificationRequest = function() {
  15593. var csr = {};
  15594. csr.version = 0x00;
  15595. csr.signatureOid = null;
  15596. csr.signature = null;
  15597. csr.siginfo = {};
  15598. csr.siginfo.algorithmOid = null;
  15599. csr.subject = {};
  15600. csr.subject.getField = function(sn) {
  15601. return _getAttribute(csr.subject, sn);
  15602. };
  15603. csr.subject.addField = function(attr) {
  15604. _fillMissingFields([attr]);
  15605. csr.subject.attributes.push(attr);
  15606. };
  15607. csr.subject.attributes = [];
  15608. csr.subject.hash = null;
  15609. csr.publicKey = null;
  15610. csr.attributes = [];
  15611. csr.getAttribute = function(sn) {
  15612. return _getAttribute(csr, sn);
  15613. };
  15614. csr.addAttribute = function(attr) {
  15615. _fillMissingFields([attr]);
  15616. csr.attributes.push(attr);
  15617. };
  15618. csr.md = null;
  15619. /**
  15620. * Sets the subject of this certification request.
  15621. *
  15622. * @param attrs the array of subject attributes to use.
  15623. */
  15624. csr.setSubject = function(attrs) {
  15625. // set new attributes
  15626. _fillMissingFields(attrs);
  15627. csr.subject.attributes = attrs;
  15628. csr.subject.hash = null;
  15629. };
  15630. /**
  15631. * Sets the attributes of this certification request.
  15632. *
  15633. * @param attrs the array of attributes to use.
  15634. */
  15635. csr.setAttributes = function(attrs) {
  15636. // set new attributes
  15637. _fillMissingFields(attrs);
  15638. csr.attributes = attrs;
  15639. };
  15640. /**
  15641. * Signs this certification request using the given private key.
  15642. *
  15643. * @param key the private key to sign with.
  15644. * @param md the message digest object to use (defaults to forge.md.sha1).
  15645. */
  15646. csr.sign = function(key, md) {
  15647. // TODO: get signature OID from private key
  15648. csr.md = md || forge$e.md.sha1.create();
  15649. var algorithmOid = oids[csr.md.algorithm + 'WithRSAEncryption'];
  15650. if(!algorithmOid) {
  15651. var error = new Error('Could not compute certification request digest. ' +
  15652. 'Unknown message digest algorithm OID.');
  15653. error.algorithm = csr.md.algorithm;
  15654. throw error;
  15655. }
  15656. csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid;
  15657. // get CertificationRequestInfo, convert to DER
  15658. csr.certificationRequestInfo = pki$2.getCertificationRequestInfo(csr);
  15659. var bytes = asn1$4.toDer(csr.certificationRequestInfo);
  15660. // digest and sign
  15661. csr.md.update(bytes.getBytes());
  15662. csr.signature = key.sign(csr.md);
  15663. };
  15664. /**
  15665. * Attempts verify the signature on the passed certification request using
  15666. * its public key.
  15667. *
  15668. * A CSR that has been exported to a file in PEM format can be verified using
  15669. * OpenSSL using this command:
  15670. *
  15671. * openssl req -in <the-csr-pem-file> -verify -noout -text
  15672. *
  15673. * @return true if verified, false if not.
  15674. */
  15675. csr.verify = function() {
  15676. var rval = false;
  15677. var md = csr.md;
  15678. if(md === null) {
  15679. // check signature OID for supported signature types
  15680. if(csr.signatureOid in oids) {
  15681. // TODO: create DRY `OID to md` function
  15682. var oid = oids[csr.signatureOid];
  15683. switch(oid) {
  15684. case 'sha1WithRSAEncryption':
  15685. md = forge$e.md.sha1.create();
  15686. break;
  15687. case 'md5WithRSAEncryption':
  15688. md = forge$e.md.md5.create();
  15689. break;
  15690. case 'sha256WithRSAEncryption':
  15691. md = forge$e.md.sha256.create();
  15692. break;
  15693. case 'sha384WithRSAEncryption':
  15694. md = forge$e.md.sha384.create();
  15695. break;
  15696. case 'sha512WithRSAEncryption':
  15697. md = forge$e.md.sha512.create();
  15698. break;
  15699. case 'RSASSA-PSS':
  15700. md = forge$e.md.sha256.create();
  15701. break;
  15702. }
  15703. }
  15704. if(md === null) {
  15705. var error = new Error(
  15706. 'Could not compute certification request digest. ' +
  15707. 'Unknown signature OID.');
  15708. error.signatureOid = csr.signatureOid;
  15709. throw error;
  15710. }
  15711. // produce DER formatted CertificationRequestInfo and digest it
  15712. var cri = csr.certificationRequestInfo ||
  15713. pki$2.getCertificationRequestInfo(csr);
  15714. var bytes = asn1$4.toDer(cri);
  15715. md.update(bytes.getBytes());
  15716. }
  15717. if(md !== null) {
  15718. var scheme;
  15719. switch(csr.signatureOid) {
  15720. case oids.sha1WithRSAEncryption:
  15721. /* use PKCS#1 v1.5 padding scheme */
  15722. break;
  15723. case oids['RSASSA-PSS']:
  15724. var hash, mgf;
  15725. /* initialize mgf */
  15726. hash = oids[csr.signatureParameters.mgf.hash.algorithmOid];
  15727. if(hash === undefined || forge$e.md[hash] === undefined) {
  15728. var error = new Error('Unsupported MGF hash function.');
  15729. error.oid = csr.signatureParameters.mgf.hash.algorithmOid;
  15730. error.name = hash;
  15731. throw error;
  15732. }
  15733. mgf = oids[csr.signatureParameters.mgf.algorithmOid];
  15734. if(mgf === undefined || forge$e.mgf[mgf] === undefined) {
  15735. var error = new Error('Unsupported MGF function.');
  15736. error.oid = csr.signatureParameters.mgf.algorithmOid;
  15737. error.name = mgf;
  15738. throw error;
  15739. }
  15740. mgf = forge$e.mgf[mgf].create(forge$e.md[hash].create());
  15741. /* initialize hash function */
  15742. hash = oids[csr.signatureParameters.hash.algorithmOid];
  15743. if(hash === undefined || forge$e.md[hash] === undefined) {
  15744. var error = new Error('Unsupported RSASSA-PSS hash function.');
  15745. error.oid = csr.signatureParameters.hash.algorithmOid;
  15746. error.name = hash;
  15747. throw error;
  15748. }
  15749. scheme = forge$e.pss.create(forge$e.md[hash].create(), mgf,
  15750. csr.signatureParameters.saltLength);
  15751. break;
  15752. }
  15753. // verify signature on csr using its public key
  15754. rval = csr.publicKey.verify(
  15755. md.digest().getBytes(), csr.signature, scheme);
  15756. }
  15757. return rval;
  15758. };
  15759. return csr;
  15760. };
  15761. /**
  15762. * Converts an X.509 subject or issuer to an ASN.1 RDNSequence.
  15763. *
  15764. * @param obj the subject or issuer (distinguished name).
  15765. *
  15766. * @return the ASN.1 RDNSequence.
  15767. */
  15768. function _dnToAsn1(obj) {
  15769. // create an empty RDNSequence
  15770. var rval = asn1$4.create(
  15771. asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []);
  15772. // iterate over attributes
  15773. var attr, set;
  15774. var attrs = obj.attributes;
  15775. for(var i = 0; i < attrs.length; ++i) {
  15776. attr = attrs[i];
  15777. var value = attr.value;
  15778. // reuse tag class for attribute value if available
  15779. var valueTagClass = asn1$4.Type.PRINTABLESTRING;
  15780. if('valueTagClass' in attr) {
  15781. valueTagClass = attr.valueTagClass;
  15782. if(valueTagClass === asn1$4.Type.UTF8) {
  15783. value = forge$e.util.encodeUtf8(value);
  15784. }
  15785. // FIXME: handle more encodings
  15786. }
  15787. // create a RelativeDistinguishedName set
  15788. // each value in the set is an AttributeTypeAndValue first
  15789. // containing the type (an OID) and second the value
  15790. set = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SET, true, [
  15791. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [
  15792. // AttributeType
  15793. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false,
  15794. asn1$4.oidToDer(attr.type).getBytes()),
  15795. // AttributeValue
  15796. asn1$4.create(asn1$4.Class.UNIVERSAL, valueTagClass, false, value)
  15797. ])
  15798. ]);
  15799. rval.value.push(set);
  15800. }
  15801. return rval;
  15802. }
  15803. /**
  15804. * Fills in missing fields in attributes.
  15805. *
  15806. * @param attrs the attributes to fill missing fields in.
  15807. */
  15808. function _fillMissingFields(attrs) {
  15809. var attr;
  15810. for(var i = 0; i < attrs.length; ++i) {
  15811. attr = attrs[i];
  15812. // populate missing name
  15813. if(typeof attr.name === 'undefined') {
  15814. if(attr.type && attr.type in pki$2.oids) {
  15815. attr.name = pki$2.oids[attr.type];
  15816. } else if(attr.shortName && attr.shortName in _shortNames) {
  15817. attr.name = pki$2.oids[_shortNames[attr.shortName]];
  15818. }
  15819. }
  15820. // populate missing type (OID)
  15821. if(typeof attr.type === 'undefined') {
  15822. if(attr.name && attr.name in pki$2.oids) {
  15823. attr.type = pki$2.oids[attr.name];
  15824. } else {
  15825. var error = new Error('Attribute type not specified.');
  15826. error.attribute = attr;
  15827. throw error;
  15828. }
  15829. }
  15830. // populate missing shortname
  15831. if(typeof attr.shortName === 'undefined') {
  15832. if(attr.name && attr.name in _shortNames) {
  15833. attr.shortName = _shortNames[attr.name];
  15834. }
  15835. }
  15836. // convert extensions to value
  15837. if(attr.type === oids.extensionRequest) {
  15838. attr.valueConstructed = true;
  15839. attr.valueTagClass = asn1$4.Type.SEQUENCE;
  15840. if(!attr.value && attr.extensions) {
  15841. attr.value = [];
  15842. for(var ei = 0; ei < attr.extensions.length; ++ei) {
  15843. attr.value.push(pki$2.certificateExtensionToAsn1(
  15844. _fillMissingExtensionFields(attr.extensions[ei])));
  15845. }
  15846. }
  15847. }
  15848. if(typeof attr.value === 'undefined') {
  15849. var error = new Error('Attribute value not specified.');
  15850. error.attribute = attr;
  15851. throw error;
  15852. }
  15853. }
  15854. }
  15855. /**
  15856. * Fills in missing fields in certificate extensions.
  15857. *
  15858. * @param e the extension.
  15859. * @param [options] the options to use.
  15860. * [cert] the certificate the extensions are for.
  15861. *
  15862. * @return the extension.
  15863. */
  15864. function _fillMissingExtensionFields(e, options) {
  15865. options = options || {};
  15866. // populate missing name
  15867. if(typeof e.name === 'undefined') {
  15868. if(e.id && e.id in pki$2.oids) {
  15869. e.name = pki$2.oids[e.id];
  15870. }
  15871. }
  15872. // populate missing id
  15873. if(typeof e.id === 'undefined') {
  15874. if(e.name && e.name in pki$2.oids) {
  15875. e.id = pki$2.oids[e.name];
  15876. } else {
  15877. var error = new Error('Extension ID not specified.');
  15878. error.extension = e;
  15879. throw error;
  15880. }
  15881. }
  15882. if(typeof e.value !== 'undefined') {
  15883. return e;
  15884. }
  15885. // handle missing value:
  15886. // value is a BIT STRING
  15887. if(e.name === 'keyUsage') {
  15888. // build flags
  15889. var unused = 0;
  15890. var b2 = 0x00;
  15891. var b3 = 0x00;
  15892. if(e.digitalSignature) {
  15893. b2 |= 0x80;
  15894. unused = 7;
  15895. }
  15896. if(e.nonRepudiation) {
  15897. b2 |= 0x40;
  15898. unused = 6;
  15899. }
  15900. if(e.keyEncipherment) {
  15901. b2 |= 0x20;
  15902. unused = 5;
  15903. }
  15904. if(e.dataEncipherment) {
  15905. b2 |= 0x10;
  15906. unused = 4;
  15907. }
  15908. if(e.keyAgreement) {
  15909. b2 |= 0x08;
  15910. unused = 3;
  15911. }
  15912. if(e.keyCertSign) {
  15913. b2 |= 0x04;
  15914. unused = 2;
  15915. }
  15916. if(e.cRLSign) {
  15917. b2 |= 0x02;
  15918. unused = 1;
  15919. }
  15920. if(e.encipherOnly) {
  15921. b2 |= 0x01;
  15922. unused = 0;
  15923. }
  15924. if(e.decipherOnly) {
  15925. b3 |= 0x80;
  15926. unused = 7;
  15927. }
  15928. // create bit string
  15929. var value = String.fromCharCode(unused);
  15930. if(b3 !== 0) {
  15931. value += String.fromCharCode(b2) + String.fromCharCode(b3);
  15932. } else if(b2 !== 0) {
  15933. value += String.fromCharCode(b2);
  15934. }
  15935. e.value = asn1$4.create(
  15936. asn1$4.Class.UNIVERSAL, asn1$4.Type.BITSTRING, false, value);
  15937. } else if(e.name === 'basicConstraints') {
  15938. // basicConstraints is a SEQUENCE
  15939. e.value = asn1$4.create(
  15940. asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []);
  15941. // cA BOOLEAN flag defaults to false
  15942. if(e.cA) {
  15943. e.value.value.push(asn1$4.create(
  15944. asn1$4.Class.UNIVERSAL, asn1$4.Type.BOOLEAN, false,
  15945. String.fromCharCode(0xFF)));
  15946. }
  15947. if('pathLenConstraint' in e) {
  15948. e.value.value.push(asn1$4.create(
  15949. asn1$4.Class.UNIVERSAL, asn1$4.Type.INTEGER, false,
  15950. asn1$4.integerToDer(e.pathLenConstraint).getBytes()));
  15951. }
  15952. } else if(e.name === 'extKeyUsage') {
  15953. // extKeyUsage is a SEQUENCE of OIDs
  15954. e.value = asn1$4.create(
  15955. asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []);
  15956. var seq = e.value.value;
  15957. for(var key in e) {
  15958. if(e[key] !== true) {
  15959. continue;
  15960. }
  15961. // key is name in OID map
  15962. if(key in oids) {
  15963. seq.push(asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID,
  15964. false, asn1$4.oidToDer(oids[key]).getBytes()));
  15965. } else if(key.indexOf('.') !== -1) {
  15966. // assume key is an OID
  15967. seq.push(asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID,
  15968. false, asn1$4.oidToDer(key).getBytes()));
  15969. }
  15970. }
  15971. } else if(e.name === 'nsCertType') {
  15972. // nsCertType is a BIT STRING
  15973. // build flags
  15974. var unused = 0;
  15975. var b2 = 0x00;
  15976. if(e.client) {
  15977. b2 |= 0x80;
  15978. unused = 7;
  15979. }
  15980. if(e.server) {
  15981. b2 |= 0x40;
  15982. unused = 6;
  15983. }
  15984. if(e.email) {
  15985. b2 |= 0x20;
  15986. unused = 5;
  15987. }
  15988. if(e.objsign) {
  15989. b2 |= 0x10;
  15990. unused = 4;
  15991. }
  15992. if(e.reserved) {
  15993. b2 |= 0x08;
  15994. unused = 3;
  15995. }
  15996. if(e.sslCA) {
  15997. b2 |= 0x04;
  15998. unused = 2;
  15999. }
  16000. if(e.emailCA) {
  16001. b2 |= 0x02;
  16002. unused = 1;
  16003. }
  16004. if(e.objCA) {
  16005. b2 |= 0x01;
  16006. unused = 0;
  16007. }
  16008. // create bit string
  16009. var value = String.fromCharCode(unused);
  16010. if(b2 !== 0) {
  16011. value += String.fromCharCode(b2);
  16012. }
  16013. e.value = asn1$4.create(
  16014. asn1$4.Class.UNIVERSAL, asn1$4.Type.BITSTRING, false, value);
  16015. } else if(e.name === 'subjectAltName' || e.name === 'issuerAltName') {
  16016. // SYNTAX SEQUENCE
  16017. e.value = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []);
  16018. var altName;
  16019. for(var n = 0; n < e.altNames.length; ++n) {
  16020. altName = e.altNames[n];
  16021. var value = altName.value;
  16022. // handle IP
  16023. if(altName.type === 7 && altName.ip) {
  16024. value = forge$e.util.bytesFromIP(altName.ip);
  16025. if(value === null) {
  16026. var error = new Error(
  16027. 'Extension "ip" value is not a valid IPv4 or IPv6 address.');
  16028. error.extension = e;
  16029. throw error;
  16030. }
  16031. } else if(altName.type === 8) {
  16032. // handle OID
  16033. if(altName.oid) {
  16034. value = asn1$4.oidToDer(asn1$4.oidToDer(altName.oid));
  16035. } else {
  16036. // deprecated ... convert value to OID
  16037. value = asn1$4.oidToDer(value);
  16038. }
  16039. }
  16040. e.value.value.push(asn1$4.create(
  16041. asn1$4.Class.CONTEXT_SPECIFIC, altName.type, false,
  16042. value));
  16043. }
  16044. } else if(e.name === 'nsComment' && options.cert) {
  16045. // sanity check value is ASCII (req'd) and not too big
  16046. if(!(/^[\x00-\x7F]*$/.test(e.comment)) ||
  16047. (e.comment.length < 1) || (e.comment.length > 128)) {
  16048. throw new Error('Invalid "nsComment" content.');
  16049. }
  16050. // IA5STRING opaque comment
  16051. e.value = asn1$4.create(
  16052. asn1$4.Class.UNIVERSAL, asn1$4.Type.IA5STRING, false, e.comment);
  16053. } else if(e.name === 'subjectKeyIdentifier' && options.cert) {
  16054. var ski = options.cert.generateSubjectKeyIdentifier();
  16055. e.subjectKeyIdentifier = ski.toHex();
  16056. // OCTETSTRING w/digest
  16057. e.value = asn1$4.create(
  16058. asn1$4.Class.UNIVERSAL, asn1$4.Type.OCTETSTRING, false, ski.getBytes());
  16059. } else if(e.name === 'authorityKeyIdentifier' && options.cert) {
  16060. // SYNTAX SEQUENCE
  16061. e.value = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []);
  16062. var seq = e.value.value;
  16063. if(e.keyIdentifier) {
  16064. var keyIdentifier = (e.keyIdentifier === true ?
  16065. options.cert.generateSubjectKeyIdentifier().getBytes() :
  16066. e.keyIdentifier);
  16067. seq.push(
  16068. asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier));
  16069. }
  16070. if(e.authorityCertIssuer) {
  16071. var authorityCertIssuer = [
  16072. asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 4, true, [
  16073. _dnToAsn1(e.authorityCertIssuer === true ?
  16074. options.cert.issuer : e.authorityCertIssuer)
  16075. ])
  16076. ];
  16077. seq.push(
  16078. asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer));
  16079. }
  16080. if(e.serialNumber) {
  16081. var serialNumber = forge$e.util.hexToBytes(e.serialNumber === true ?
  16082. options.cert.serialNumber : e.serialNumber);
  16083. seq.push(
  16084. asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 2, false, serialNumber));
  16085. }
  16086. } else if(e.name === 'cRLDistributionPoints') {
  16087. e.value = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []);
  16088. var seq = e.value.value;
  16089. // Create sub SEQUENCE of DistributionPointName
  16090. var subSeq = asn1$4.create(
  16091. asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []);
  16092. // Create fullName CHOICE
  16093. var fullNameGeneralNames = asn1$4.create(
  16094. asn1$4.Class.CONTEXT_SPECIFIC, 0, true, []);
  16095. var altName;
  16096. for(var n = 0; n < e.altNames.length; ++n) {
  16097. altName = e.altNames[n];
  16098. var value = altName.value;
  16099. // handle IP
  16100. if(altName.type === 7 && altName.ip) {
  16101. value = forge$e.util.bytesFromIP(altName.ip);
  16102. if(value === null) {
  16103. var error = new Error(
  16104. 'Extension "ip" value is not a valid IPv4 or IPv6 address.');
  16105. error.extension = e;
  16106. throw error;
  16107. }
  16108. } else if(altName.type === 8) {
  16109. // handle OID
  16110. if(altName.oid) {
  16111. value = asn1$4.oidToDer(asn1$4.oidToDer(altName.oid));
  16112. } else {
  16113. // deprecated ... convert value to OID
  16114. value = asn1$4.oidToDer(value);
  16115. }
  16116. }
  16117. fullNameGeneralNames.value.push(asn1$4.create(
  16118. asn1$4.Class.CONTEXT_SPECIFIC, altName.type, false,
  16119. value));
  16120. }
  16121. // Add to the parent SEQUENCE
  16122. subSeq.value.push(asn1$4.create(
  16123. asn1$4.Class.CONTEXT_SPECIFIC, 0, true, [fullNameGeneralNames]));
  16124. seq.push(subSeq);
  16125. }
  16126. // ensure value has been defined by now
  16127. if(typeof e.value === 'undefined') {
  16128. var error = new Error('Extension value not specified.');
  16129. error.extension = e;
  16130. throw error;
  16131. }
  16132. return e;
  16133. }
  16134. /**
  16135. * Convert signature parameters object to ASN.1
  16136. *
  16137. * @param {String} oid Signature algorithm OID
  16138. * @param params The signature parametrs object
  16139. * @return ASN.1 object representing signature parameters
  16140. */
  16141. function _signatureParametersToAsn1(oid, params) {
  16142. switch(oid) {
  16143. case oids['RSASSA-PSS']:
  16144. var parts = [];
  16145. if(params.hash.algorithmOid !== undefined) {
  16146. parts.push(asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 0, true, [
  16147. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [
  16148. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false,
  16149. asn1$4.oidToDer(params.hash.algorithmOid).getBytes()),
  16150. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.NULL, false, '')
  16151. ])
  16152. ]));
  16153. }
  16154. if(params.mgf.algorithmOid !== undefined) {
  16155. parts.push(asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 1, true, [
  16156. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [
  16157. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false,
  16158. asn1$4.oidToDer(params.mgf.algorithmOid).getBytes()),
  16159. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [
  16160. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false,
  16161. asn1$4.oidToDer(params.mgf.hash.algorithmOid).getBytes()),
  16162. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.NULL, false, '')
  16163. ])
  16164. ])
  16165. ]));
  16166. }
  16167. if(params.saltLength !== undefined) {
  16168. parts.push(asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 2, true, [
  16169. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.INTEGER, false,
  16170. asn1$4.integerToDer(params.saltLength).getBytes())
  16171. ]));
  16172. }
  16173. return asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, parts);
  16174. default:
  16175. return asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.NULL, false, '');
  16176. }
  16177. }
  16178. /**
  16179. * Converts a certification request's attributes to an ASN.1 set of
  16180. * CRIAttributes.
  16181. *
  16182. * @param csr certification request.
  16183. *
  16184. * @return the ASN.1 set of CRIAttributes.
  16185. */
  16186. function _CRIAttributesToAsn1(csr) {
  16187. // create an empty context-specific container
  16188. var rval = asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 0, true, []);
  16189. // no attributes, return empty container
  16190. if(csr.attributes.length === 0) {
  16191. return rval;
  16192. }
  16193. // each attribute has a sequence with a type and a set of values
  16194. var attrs = csr.attributes;
  16195. for(var i = 0; i < attrs.length; ++i) {
  16196. var attr = attrs[i];
  16197. var value = attr.value;
  16198. // reuse tag class for attribute value if available
  16199. var valueTagClass = asn1$4.Type.UTF8;
  16200. if('valueTagClass' in attr) {
  16201. valueTagClass = attr.valueTagClass;
  16202. }
  16203. if(valueTagClass === asn1$4.Type.UTF8) {
  16204. value = forge$e.util.encodeUtf8(value);
  16205. }
  16206. var valueConstructed = false;
  16207. if('valueConstructed' in attr) {
  16208. valueConstructed = attr.valueConstructed;
  16209. }
  16210. // FIXME: handle more encodings
  16211. // create a RelativeDistinguishedName set
  16212. // each value in the set is an AttributeTypeAndValue first
  16213. // containing the type (an OID) and second the value
  16214. var seq = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [
  16215. // AttributeType
  16216. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false,
  16217. asn1$4.oidToDer(attr.type).getBytes()),
  16218. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SET, true, [
  16219. // AttributeValue
  16220. asn1$4.create(
  16221. asn1$4.Class.UNIVERSAL, valueTagClass, valueConstructed, value)
  16222. ])
  16223. ]);
  16224. rval.value.push(seq);
  16225. }
  16226. return rval;
  16227. }
  16228. var jan_1_1950 = new Date('1950-01-01T00:00:00Z');
  16229. var jan_1_2050 = new Date('2050-01-01T00:00:00Z');
  16230. /**
  16231. * Converts a Date object to ASN.1
  16232. * Handles the different format before and after 1st January 2050
  16233. *
  16234. * @param date date object.
  16235. *
  16236. * @return the ASN.1 object representing the date.
  16237. */
  16238. function _dateToAsn1(date) {
  16239. if(date >= jan_1_1950 && date < jan_1_2050) {
  16240. return asn1$4.create(
  16241. asn1$4.Class.UNIVERSAL, asn1$4.Type.UTCTIME, false,
  16242. asn1$4.dateToUtcTime(date));
  16243. } else {
  16244. return asn1$4.create(
  16245. asn1$4.Class.UNIVERSAL, asn1$4.Type.GENERALIZEDTIME, false,
  16246. asn1$4.dateToGeneralizedTime(date));
  16247. }
  16248. }
  16249. /**
  16250. * Gets the ASN.1 TBSCertificate part of an X.509v3 certificate.
  16251. *
  16252. * @param cert the certificate.
  16253. *
  16254. * @return the asn1 TBSCertificate.
  16255. */
  16256. pki$2.getTBSCertificate = function(cert) {
  16257. // TBSCertificate
  16258. var notBefore = _dateToAsn1(cert.validity.notBefore);
  16259. var notAfter = _dateToAsn1(cert.validity.notAfter);
  16260. var tbs = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [
  16261. // version
  16262. asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 0, true, [
  16263. // integer
  16264. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.INTEGER, false,
  16265. asn1$4.integerToDer(cert.version).getBytes())
  16266. ]),
  16267. // serialNumber
  16268. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.INTEGER, false,
  16269. forge$e.util.hexToBytes(cert.serialNumber)),
  16270. // signature
  16271. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [
  16272. // algorithm
  16273. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false,
  16274. asn1$4.oidToDer(cert.siginfo.algorithmOid).getBytes()),
  16275. // parameters
  16276. _signatureParametersToAsn1(
  16277. cert.siginfo.algorithmOid, cert.siginfo.parameters)
  16278. ]),
  16279. // issuer
  16280. _dnToAsn1(cert.issuer),
  16281. // validity
  16282. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [
  16283. notBefore,
  16284. notAfter
  16285. ]),
  16286. // subject
  16287. _dnToAsn1(cert.subject),
  16288. // SubjectPublicKeyInfo
  16289. pki$2.publicKeyToAsn1(cert.publicKey)
  16290. ]);
  16291. if(cert.issuer.uniqueId) {
  16292. // issuerUniqueID (optional)
  16293. tbs.value.push(
  16294. asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 1, true, [
  16295. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.BITSTRING, false,
  16296. // TODO: support arbitrary bit length ids
  16297. String.fromCharCode(0x00) +
  16298. cert.issuer.uniqueId
  16299. )
  16300. ])
  16301. );
  16302. }
  16303. if(cert.subject.uniqueId) {
  16304. // subjectUniqueID (optional)
  16305. tbs.value.push(
  16306. asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 2, true, [
  16307. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.BITSTRING, false,
  16308. // TODO: support arbitrary bit length ids
  16309. String.fromCharCode(0x00) +
  16310. cert.subject.uniqueId
  16311. )
  16312. ])
  16313. );
  16314. }
  16315. if(cert.extensions.length > 0) {
  16316. // extensions (optional)
  16317. tbs.value.push(pki$2.certificateExtensionsToAsn1(cert.extensions));
  16318. }
  16319. return tbs;
  16320. };
  16321. /**
  16322. * Gets the ASN.1 CertificationRequestInfo part of a
  16323. * PKCS#10 CertificationRequest.
  16324. *
  16325. * @param csr the certification request.
  16326. *
  16327. * @return the asn1 CertificationRequestInfo.
  16328. */
  16329. pki$2.getCertificationRequestInfo = function(csr) {
  16330. // CertificationRequestInfo
  16331. var cri = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [
  16332. // version
  16333. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.INTEGER, false,
  16334. asn1$4.integerToDer(csr.version).getBytes()),
  16335. // subject
  16336. _dnToAsn1(csr.subject),
  16337. // SubjectPublicKeyInfo
  16338. pki$2.publicKeyToAsn1(csr.publicKey),
  16339. // attributes
  16340. _CRIAttributesToAsn1(csr)
  16341. ]);
  16342. return cri;
  16343. };
  16344. /**
  16345. * Converts a DistinguishedName (subject or issuer) to an ASN.1 object.
  16346. *
  16347. * @param dn the DistinguishedName.
  16348. *
  16349. * @return the asn1 representation of a DistinguishedName.
  16350. */
  16351. pki$2.distinguishedNameToAsn1 = function(dn) {
  16352. return _dnToAsn1(dn);
  16353. };
  16354. /**
  16355. * Converts an X.509v3 RSA certificate to an ASN.1 object.
  16356. *
  16357. * @param cert the certificate.
  16358. *
  16359. * @return the asn1 representation of an X.509v3 RSA certificate.
  16360. */
  16361. pki$2.certificateToAsn1 = function(cert) {
  16362. // prefer cached TBSCertificate over generating one
  16363. var tbsCertificate = cert.tbsCertificate || pki$2.getTBSCertificate(cert);
  16364. // Certificate
  16365. return asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [
  16366. // TBSCertificate
  16367. tbsCertificate,
  16368. // AlgorithmIdentifier (signature algorithm)
  16369. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [
  16370. // algorithm
  16371. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false,
  16372. asn1$4.oidToDer(cert.signatureOid).getBytes()),
  16373. // parameters
  16374. _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters)
  16375. ]),
  16376. // SignatureValue
  16377. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.BITSTRING, false,
  16378. String.fromCharCode(0x00) + cert.signature)
  16379. ]);
  16380. };
  16381. /**
  16382. * Converts X.509v3 certificate extensions to ASN.1.
  16383. *
  16384. * @param exts the extensions to convert.
  16385. *
  16386. * @return the extensions in ASN.1 format.
  16387. */
  16388. pki$2.certificateExtensionsToAsn1 = function(exts) {
  16389. // create top-level extension container
  16390. var rval = asn1$4.create(asn1$4.Class.CONTEXT_SPECIFIC, 3, true, []);
  16391. // create extension sequence (stores a sequence for each extension)
  16392. var seq = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []);
  16393. rval.value.push(seq);
  16394. for(var i = 0; i < exts.length; ++i) {
  16395. seq.value.push(pki$2.certificateExtensionToAsn1(exts[i]));
  16396. }
  16397. return rval;
  16398. };
  16399. /**
  16400. * Converts a single certificate extension to ASN.1.
  16401. *
  16402. * @param ext the extension to convert.
  16403. *
  16404. * @return the extension in ASN.1 format.
  16405. */
  16406. pki$2.certificateExtensionToAsn1 = function(ext) {
  16407. // create a sequence for each extension
  16408. var extseq = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, []);
  16409. // extnID (OID)
  16410. extseq.value.push(asn1$4.create(
  16411. asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false,
  16412. asn1$4.oidToDer(ext.id).getBytes()));
  16413. // critical defaults to false
  16414. if(ext.critical) {
  16415. // critical BOOLEAN DEFAULT FALSE
  16416. extseq.value.push(asn1$4.create(
  16417. asn1$4.Class.UNIVERSAL, asn1$4.Type.BOOLEAN, false,
  16418. String.fromCharCode(0xFF)));
  16419. }
  16420. var value = ext.value;
  16421. if(typeof ext.value !== 'string') {
  16422. // value is asn.1
  16423. value = asn1$4.toDer(value).getBytes();
  16424. }
  16425. // extnValue (OCTET STRING)
  16426. extseq.value.push(asn1$4.create(
  16427. asn1$4.Class.UNIVERSAL, asn1$4.Type.OCTETSTRING, false, value));
  16428. return extseq;
  16429. };
  16430. /**
  16431. * Converts a PKCS#10 certification request to an ASN.1 object.
  16432. *
  16433. * @param csr the certification request.
  16434. *
  16435. * @return the asn1 representation of a certification request.
  16436. */
  16437. pki$2.certificationRequestToAsn1 = function(csr) {
  16438. // prefer cached CertificationRequestInfo over generating one
  16439. var cri = csr.certificationRequestInfo ||
  16440. pki$2.getCertificationRequestInfo(csr);
  16441. // Certificate
  16442. return asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [
  16443. // CertificationRequestInfo
  16444. cri,
  16445. // AlgorithmIdentifier (signature algorithm)
  16446. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [
  16447. // algorithm
  16448. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false,
  16449. asn1$4.oidToDer(csr.signatureOid).getBytes()),
  16450. // parameters
  16451. _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters)
  16452. ]),
  16453. // signature
  16454. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.BITSTRING, false,
  16455. String.fromCharCode(0x00) + csr.signature)
  16456. ]);
  16457. };
  16458. /**
  16459. * Creates a CA store.
  16460. *
  16461. * @param certs an optional array of certificate objects or PEM-formatted
  16462. * certificate strings to add to the CA store.
  16463. *
  16464. * @return the CA store.
  16465. */
  16466. pki$2.createCaStore = function(certs) {
  16467. // create CA store
  16468. var caStore = {
  16469. // stored certificates
  16470. certs: {}
  16471. };
  16472. /**
  16473. * Gets the certificate that issued the passed certificate or its
  16474. * 'parent'.
  16475. *
  16476. * @param cert the certificate to get the parent for.
  16477. *
  16478. * @return the parent certificate or null if none was found.
  16479. */
  16480. caStore.getIssuer = function(cert) {
  16481. var rval = getBySubject(cert.issuer);
  16482. // see if there are multiple matches
  16483. /*if(forge.util.isArray(rval)) {
  16484. // TODO: resolve multiple matches by checking
  16485. // authorityKey/subjectKey/issuerUniqueID/other identifiers, etc.
  16486. // FIXME: or alternatively do authority key mapping
  16487. // if possible (X.509v1 certs can't work?)
  16488. throw new Error('Resolving multiple issuer matches not implemented yet.');
  16489. }*/
  16490. return rval;
  16491. };
  16492. /**
  16493. * Adds a trusted certificate to the store.
  16494. *
  16495. * @param cert the certificate to add as a trusted certificate (either a
  16496. * pki.certificate object or a PEM-formatted certificate).
  16497. */
  16498. caStore.addCertificate = function(cert) {
  16499. // convert from pem if necessary
  16500. if(typeof cert === 'string') {
  16501. cert = forge$e.pki.certificateFromPem(cert);
  16502. }
  16503. ensureSubjectHasHash(cert.subject);
  16504. if(!caStore.hasCertificate(cert)) { // avoid duplicate certificates in store
  16505. if(cert.subject.hash in caStore.certs) {
  16506. // subject hash already exists, append to array
  16507. var tmp = caStore.certs[cert.subject.hash];
  16508. if(!forge$e.util.isArray(tmp)) {
  16509. tmp = [tmp];
  16510. }
  16511. tmp.push(cert);
  16512. caStore.certs[cert.subject.hash] = tmp;
  16513. } else {
  16514. caStore.certs[cert.subject.hash] = cert;
  16515. }
  16516. }
  16517. };
  16518. /**
  16519. * Checks to see if the given certificate is in the store.
  16520. *
  16521. * @param cert the certificate to check (either a pki.certificate or a
  16522. * PEM-formatted certificate).
  16523. *
  16524. * @return true if the certificate is in the store, false if not.
  16525. */
  16526. caStore.hasCertificate = function(cert) {
  16527. // convert from pem if necessary
  16528. if(typeof cert === 'string') {
  16529. cert = forge$e.pki.certificateFromPem(cert);
  16530. }
  16531. var match = getBySubject(cert.subject);
  16532. if(!match) {
  16533. return false;
  16534. }
  16535. if(!forge$e.util.isArray(match)) {
  16536. match = [match];
  16537. }
  16538. // compare DER-encoding of certificates
  16539. var der1 = asn1$4.toDer(pki$2.certificateToAsn1(cert)).getBytes();
  16540. for(var i = 0; i < match.length; ++i) {
  16541. var der2 = asn1$4.toDer(pki$2.certificateToAsn1(match[i])).getBytes();
  16542. if(der1 === der2) {
  16543. return true;
  16544. }
  16545. }
  16546. return false;
  16547. };
  16548. /**
  16549. * Lists all of the certificates kept in the store.
  16550. *
  16551. * @return an array of all of the pki.certificate objects in the store.
  16552. */
  16553. caStore.listAllCertificates = function() {
  16554. var certList = [];
  16555. for(var hash in caStore.certs) {
  16556. if(caStore.certs.hasOwnProperty(hash)) {
  16557. var value = caStore.certs[hash];
  16558. if(!forge$e.util.isArray(value)) {
  16559. certList.push(value);
  16560. } else {
  16561. for(var i = 0; i < value.length; ++i) {
  16562. certList.push(value[i]);
  16563. }
  16564. }
  16565. }
  16566. }
  16567. return certList;
  16568. };
  16569. /**
  16570. * Removes a certificate from the store.
  16571. *
  16572. * @param cert the certificate to remove (either a pki.certificate or a
  16573. * PEM-formatted certificate).
  16574. *
  16575. * @return the certificate that was removed or null if the certificate
  16576. * wasn't in store.
  16577. */
  16578. caStore.removeCertificate = function(cert) {
  16579. var result;
  16580. // convert from pem if necessary
  16581. if(typeof cert === 'string') {
  16582. cert = forge$e.pki.certificateFromPem(cert);
  16583. }
  16584. ensureSubjectHasHash(cert.subject);
  16585. if(!caStore.hasCertificate(cert)) {
  16586. return null;
  16587. }
  16588. var match = getBySubject(cert.subject);
  16589. if(!forge$e.util.isArray(match)) {
  16590. result = caStore.certs[cert.subject.hash];
  16591. delete caStore.certs[cert.subject.hash];
  16592. return result;
  16593. }
  16594. // compare DER-encoding of certificates
  16595. var der1 = asn1$4.toDer(pki$2.certificateToAsn1(cert)).getBytes();
  16596. for(var i = 0; i < match.length; ++i) {
  16597. var der2 = asn1$4.toDer(pki$2.certificateToAsn1(match[i])).getBytes();
  16598. if(der1 === der2) {
  16599. result = match[i];
  16600. match.splice(i, 1);
  16601. }
  16602. }
  16603. if(match.length === 0) {
  16604. delete caStore.certs[cert.subject.hash];
  16605. }
  16606. return result;
  16607. };
  16608. function getBySubject(subject) {
  16609. ensureSubjectHasHash(subject);
  16610. return caStore.certs[subject.hash] || null;
  16611. }
  16612. function ensureSubjectHasHash(subject) {
  16613. // produce subject hash if it doesn't exist
  16614. if(!subject.hash) {
  16615. var md = forge$e.md.sha1.create();
  16616. subject.attributes = pki$2.RDNAttributesAsArray(_dnToAsn1(subject), md);
  16617. subject.hash = md.digest().toHex();
  16618. }
  16619. }
  16620. // auto-add passed in certs
  16621. if(certs) {
  16622. // parse PEM-formatted certificates as necessary
  16623. for(var i = 0; i < certs.length; ++i) {
  16624. var cert = certs[i];
  16625. caStore.addCertificate(cert);
  16626. }
  16627. }
  16628. return caStore;
  16629. };
  16630. /**
  16631. * Certificate verification errors, based on TLS.
  16632. */
  16633. pki$2.certificateError = {
  16634. bad_certificate: 'forge.pki.BadCertificate',
  16635. unsupported_certificate: 'forge.pki.UnsupportedCertificate',
  16636. certificate_revoked: 'forge.pki.CertificateRevoked',
  16637. certificate_expired: 'forge.pki.CertificateExpired',
  16638. certificate_unknown: 'forge.pki.CertificateUnknown',
  16639. unknown_ca: 'forge.pki.UnknownCertificateAuthority'
  16640. };
  16641. /**
  16642. * Verifies a certificate chain against the given Certificate Authority store
  16643. * with an optional custom verify callback.
  16644. *
  16645. * @param caStore a certificate store to verify against.
  16646. * @param chain the certificate chain to verify, with the root or highest
  16647. * authority at the end (an array of certificates).
  16648. * @param options a callback to be called for every certificate in the chain or
  16649. * an object with:
  16650. * verify a callback to be called for every certificate in the
  16651. * chain
  16652. * validityCheckDate the date against which the certificate
  16653. * validity period should be checked. Pass null to not check
  16654. * the validity period. By default, the current date is used.
  16655. *
  16656. * The verify callback has the following signature:
  16657. *
  16658. * verified - Set to true if certificate was verified, otherwise the
  16659. * pki.certificateError for why the certificate failed.
  16660. * depth - The current index in the chain, where 0 is the end point's cert.
  16661. * certs - The certificate chain, *NOTE* an empty chain indicates an anonymous
  16662. * end point.
  16663. *
  16664. * The function returns true on success and on failure either the appropriate
  16665. * pki.certificateError or an object with 'error' set to the appropriate
  16666. * pki.certificateError and 'message' set to a custom error message.
  16667. *
  16668. * @return true if successful, error thrown if not.
  16669. */
  16670. pki$2.verifyCertificateChain = function(caStore, chain, options) {
  16671. /* From: RFC3280 - Internet X.509 Public Key Infrastructure Certificate
  16672. Section 6: Certification Path Validation
  16673. See inline parentheticals related to this particular implementation.
  16674. The primary goal of path validation is to verify the binding between
  16675. a subject distinguished name or a subject alternative name and subject
  16676. public key, as represented in the end entity certificate, based on the
  16677. public key of the trust anchor. This requires obtaining a sequence of
  16678. certificates that support that binding. That sequence should be provided
  16679. in the passed 'chain'. The trust anchor should be in the given CA
  16680. store. The 'end entity' certificate is the certificate provided by the
  16681. end point (typically a server) and is the first in the chain.
  16682. To meet this goal, the path validation process verifies, among other
  16683. things, that a prospective certification path (a sequence of n
  16684. certificates or a 'chain') satisfies the following conditions:
  16685. (a) for all x in {1, ..., n-1}, the subject of certificate x is
  16686. the issuer of certificate x+1;
  16687. (b) certificate 1 is issued by the trust anchor;
  16688. (c) certificate n is the certificate to be validated; and
  16689. (d) for all x in {1, ..., n}, the certificate was valid at the
  16690. time in question.
  16691. Note that here 'n' is index 0 in the chain and 1 is the last certificate
  16692. in the chain and it must be signed by a certificate in the connection's
  16693. CA store.
  16694. The path validation process also determines the set of certificate
  16695. policies that are valid for this path, based on the certificate policies
  16696. extension, policy mapping extension, policy constraints extension, and
  16697. inhibit any-policy extension.
  16698. Note: Policy mapping extension not supported (Not Required).
  16699. Note: If the certificate has an unsupported critical extension, then it
  16700. must be rejected.
  16701. Note: A certificate is self-issued if the DNs that appear in the subject
  16702. and issuer fields are identical and are not empty.
  16703. The path validation algorithm assumes the following seven inputs are
  16704. provided to the path processing logic. What this specific implementation
  16705. will use is provided parenthetically:
  16706. (a) a prospective certification path of length n (the 'chain')
  16707. (b) the current date/time: ('now').
  16708. (c) user-initial-policy-set: A set of certificate policy identifiers
  16709. naming the policies that are acceptable to the certificate user.
  16710. The user-initial-policy-set contains the special value any-policy
  16711. if the user is not concerned about certificate policy
  16712. (Not implemented. Any policy is accepted).
  16713. (d) trust anchor information, describing a CA that serves as a trust
  16714. anchor for the certification path. The trust anchor information
  16715. includes:
  16716. (1) the trusted issuer name,
  16717. (2) the trusted public key algorithm,
  16718. (3) the trusted public key, and
  16719. (4) optionally, the trusted public key parameters associated
  16720. with the public key.
  16721. (Trust anchors are provided via certificates in the CA store).
  16722. The trust anchor information may be provided to the path processing
  16723. procedure in the form of a self-signed certificate. The trusted anchor
  16724. information is trusted because it was delivered to the path processing
  16725. procedure by some trustworthy out-of-band procedure. If the trusted
  16726. public key algorithm requires parameters, then the parameters are
  16727. provided along with the trusted public key (No parameters used in this
  16728. implementation).
  16729. (e) initial-policy-mapping-inhibit, which indicates if policy mapping is
  16730. allowed in the certification path.
  16731. (Not implemented, no policy checking)
  16732. (f) initial-explicit-policy, which indicates if the path must be valid
  16733. for at least one of the certificate policies in the user-initial-
  16734. policy-set.
  16735. (Not implemented, no policy checking)
  16736. (g) initial-any-policy-inhibit, which indicates whether the
  16737. anyPolicy OID should be processed if it is included in a
  16738. certificate.
  16739. (Not implemented, so any policy is valid provided that it is
  16740. not marked as critical) */
  16741. /* Basic Path Processing:
  16742. For each certificate in the 'chain', the following is checked:
  16743. 1. The certificate validity period includes the current time.
  16744. 2. The certificate was signed by its parent (where the parent is either
  16745. the next in the chain or from the CA store). Allow processing to
  16746. continue to the next step if no parent is found but the certificate is
  16747. in the CA store.
  16748. 3. TODO: The certificate has not been revoked.
  16749. 4. The certificate issuer name matches the parent's subject name.
  16750. 5. TODO: If the certificate is self-issued and not the final certificate
  16751. in the chain, skip this step, otherwise verify that the subject name
  16752. is within one of the permitted subtrees of X.500 distinguished names
  16753. and that each of the alternative names in the subjectAltName extension
  16754. (critical or non-critical) is within one of the permitted subtrees for
  16755. that name type.
  16756. 6. TODO: If the certificate is self-issued and not the final certificate
  16757. in the chain, skip this step, otherwise verify that the subject name
  16758. is not within one of the excluded subtrees for X.500 distinguished
  16759. names and none of the subjectAltName extension names are excluded for
  16760. that name type.
  16761. 7. The other steps in the algorithm for basic path processing involve
  16762. handling the policy extension which is not presently supported in this
  16763. implementation. Instead, if a critical policy extension is found, the
  16764. certificate is rejected as not supported.
  16765. 8. If the certificate is not the first or if its the only certificate in
  16766. the chain (having no parent from the CA store or is self-signed) and it
  16767. has a critical key usage extension, verify that the keyCertSign bit is
  16768. set. If the key usage extension exists, verify that the basic
  16769. constraints extension exists. If the basic constraints extension exists,
  16770. verify that the cA flag is set. If pathLenConstraint is set, ensure that
  16771. the number of certificates that precede in the chain (come earlier
  16772. in the chain as implemented below), excluding the very first in the
  16773. chain (typically the end-entity one), isn't greater than the
  16774. pathLenConstraint. This constraint limits the number of intermediate
  16775. CAs that may appear below a CA before only end-entity certificates
  16776. may be issued. */
  16777. // if a verify callback is passed as the third parameter, package it within
  16778. // the options object. This is to support a legacy function signature that
  16779. // expected the verify callback as the third parameter.
  16780. if(typeof options === 'function') {
  16781. options = {verify: options};
  16782. }
  16783. options = options || {};
  16784. // copy cert chain references to another array to protect against changes
  16785. // in verify callback
  16786. chain = chain.slice(0);
  16787. var certs = chain.slice(0);
  16788. var validityCheckDate = options.validityCheckDate;
  16789. // if no validityCheckDate is specified, default to the current date. Make
  16790. // sure to maintain the value null because it indicates that the validity
  16791. // period should not be checked.
  16792. if(typeof validityCheckDate === 'undefined') {
  16793. validityCheckDate = new Date();
  16794. }
  16795. // verify each cert in the chain using its parent, where the parent
  16796. // is either the next in the chain or from the CA store
  16797. var first = true;
  16798. var error = null;
  16799. var depth = 0;
  16800. do {
  16801. var cert = chain.shift();
  16802. var parent = null;
  16803. var selfSigned = false;
  16804. if(validityCheckDate) {
  16805. // 1. check valid time
  16806. if(validityCheckDate < cert.validity.notBefore ||
  16807. validityCheckDate > cert.validity.notAfter) {
  16808. error = {
  16809. message: 'Certificate is not valid yet or has expired.',
  16810. error: pki$2.certificateError.certificate_expired,
  16811. notBefore: cert.validity.notBefore,
  16812. notAfter: cert.validity.notAfter,
  16813. // TODO: we might want to reconsider renaming 'now' to
  16814. // 'validityCheckDate' should this API be changed in the future.
  16815. now: validityCheckDate
  16816. };
  16817. }
  16818. }
  16819. // 2. verify with parent from chain or CA store
  16820. if(error === null) {
  16821. parent = chain[0] || caStore.getIssuer(cert);
  16822. if(parent === null) {
  16823. // check for self-signed cert
  16824. if(cert.isIssuer(cert)) {
  16825. selfSigned = true;
  16826. parent = cert;
  16827. }
  16828. }
  16829. if(parent) {
  16830. // FIXME: current CA store implementation might have multiple
  16831. // certificates where the issuer can't be determined from the
  16832. // certificate (happens rarely with, eg: old certificates) so normalize
  16833. // by always putting parents into an array
  16834. // TODO: there's may be an extreme degenerate case currently uncovered
  16835. // where an old intermediate certificate seems to have a matching parent
  16836. // but none of the parents actually verify ... but the intermediate
  16837. // is in the CA and it should pass this check; needs investigation
  16838. var parents = parent;
  16839. if(!forge$e.util.isArray(parents)) {
  16840. parents = [parents];
  16841. }
  16842. // try to verify with each possible parent (typically only one)
  16843. var verified = false;
  16844. while(!verified && parents.length > 0) {
  16845. parent = parents.shift();
  16846. try {
  16847. verified = parent.verify(cert);
  16848. } catch(ex) {
  16849. // failure to verify, don't care why, try next one
  16850. }
  16851. }
  16852. if(!verified) {
  16853. error = {
  16854. message: 'Certificate signature is invalid.',
  16855. error: pki$2.certificateError.bad_certificate
  16856. };
  16857. }
  16858. }
  16859. if(error === null && (!parent || selfSigned) &&
  16860. !caStore.hasCertificate(cert)) {
  16861. // no parent issuer and certificate itself is not trusted
  16862. error = {
  16863. message: 'Certificate is not trusted.',
  16864. error: pki$2.certificateError.unknown_ca
  16865. };
  16866. }
  16867. }
  16868. // TODO: 3. check revoked
  16869. // 4. check for matching issuer/subject
  16870. if(error === null && parent && !cert.isIssuer(parent)) {
  16871. // parent is not issuer
  16872. error = {
  16873. message: 'Certificate issuer is invalid.',
  16874. error: pki$2.certificateError.bad_certificate
  16875. };
  16876. }
  16877. // 5. TODO: check names with permitted names tree
  16878. // 6. TODO: check names against excluded names tree
  16879. // 7. check for unsupported critical extensions
  16880. if(error === null) {
  16881. // supported extensions
  16882. var se = {
  16883. keyUsage: true,
  16884. basicConstraints: true
  16885. };
  16886. for(var i = 0; error === null && i < cert.extensions.length; ++i) {
  16887. var ext = cert.extensions[i];
  16888. if(ext.critical && !(ext.name in se)) {
  16889. error = {
  16890. message:
  16891. 'Certificate has an unsupported critical extension.',
  16892. error: pki$2.certificateError.unsupported_certificate
  16893. };
  16894. }
  16895. }
  16896. }
  16897. // 8. check for CA if cert is not first or is the only certificate
  16898. // remaining in chain with no parent or is self-signed
  16899. if(error === null &&
  16900. (!first || (chain.length === 0 && (!parent || selfSigned)))) {
  16901. // first check keyUsage extension and then basic constraints
  16902. var bcExt = cert.getExtension('basicConstraints');
  16903. var keyUsageExt = cert.getExtension('keyUsage');
  16904. if(keyUsageExt !== null) {
  16905. // keyCertSign must be true and there must be a basic
  16906. // constraints extension
  16907. if(!keyUsageExt.keyCertSign || bcExt === null) {
  16908. // bad certificate
  16909. error = {
  16910. message:
  16911. 'Certificate keyUsage or basicConstraints conflict ' +
  16912. 'or indicate that the certificate is not a CA. ' +
  16913. 'If the certificate is the only one in the chain or ' +
  16914. 'isn\'t the first then the certificate must be a ' +
  16915. 'valid CA.',
  16916. error: pki$2.certificateError.bad_certificate
  16917. };
  16918. }
  16919. }
  16920. // basic constraints cA flag must be set
  16921. if(error === null && bcExt !== null && !bcExt.cA) {
  16922. // bad certificate
  16923. error = {
  16924. message:
  16925. 'Certificate basicConstraints indicates the certificate ' +
  16926. 'is not a CA.',
  16927. error: pki$2.certificateError.bad_certificate
  16928. };
  16929. }
  16930. // if error is not null and keyUsage is available, then we know it
  16931. // has keyCertSign and there is a basic constraints extension too,
  16932. // which means we can check pathLenConstraint (if it exists)
  16933. if(error === null && keyUsageExt !== null &&
  16934. 'pathLenConstraint' in bcExt) {
  16935. // pathLen is the maximum # of intermediate CA certs that can be
  16936. // found between the current certificate and the end-entity (depth 0)
  16937. // certificate; this number does not include the end-entity (depth 0,
  16938. // last in the chain) even if it happens to be a CA certificate itself
  16939. var pathLen = depth - 1;
  16940. if(pathLen > bcExt.pathLenConstraint) {
  16941. // pathLenConstraint violated, bad certificate
  16942. error = {
  16943. message:
  16944. 'Certificate basicConstraints pathLenConstraint violated.',
  16945. error: pki$2.certificateError.bad_certificate
  16946. };
  16947. }
  16948. }
  16949. }
  16950. // call application callback
  16951. var vfd = (error === null) ? true : error.error;
  16952. var ret = options.verify ? options.verify(vfd, depth, certs) : vfd;
  16953. if(ret === true) {
  16954. // clear any set error
  16955. error = null;
  16956. } else {
  16957. // if passed basic tests, set default message and alert
  16958. if(vfd === true) {
  16959. error = {
  16960. message: 'The application rejected the certificate.',
  16961. error: pki$2.certificateError.bad_certificate
  16962. };
  16963. }
  16964. // check for custom error info
  16965. if(ret || ret === 0) {
  16966. // set custom message and error
  16967. if(typeof ret === 'object' && !forge$e.util.isArray(ret)) {
  16968. if(ret.message) {
  16969. error.message = ret.message;
  16970. }
  16971. if(ret.error) {
  16972. error.error = ret.error;
  16973. }
  16974. } else if(typeof ret === 'string') {
  16975. // set custom error
  16976. error.error = ret;
  16977. }
  16978. }
  16979. // throw error
  16980. throw error;
  16981. }
  16982. // no longer first cert in chain
  16983. first = false;
  16984. ++depth;
  16985. } while(chain.length > 0);
  16986. return true;
  16987. };
  16988. /**
  16989. * Javascript implementation of PKCS#12.
  16990. *
  16991. * @author Dave Longley
  16992. * @author Stefan Siegl <stesie@brokenpipe.de>
  16993. *
  16994. * Copyright (c) 2010-2014 Digital Bazaar, Inc.
  16995. * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>
  16996. *
  16997. * The ASN.1 representation of PKCS#12 is as follows
  16998. * (see ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12-tc1.pdf for details)
  16999. *
  17000. * PFX ::= SEQUENCE {
  17001. * version INTEGER {v3(3)}(v3,...),
  17002. * authSafe ContentInfo,
  17003. * macData MacData OPTIONAL
  17004. * }
  17005. *
  17006. * MacData ::= SEQUENCE {
  17007. * mac DigestInfo,
  17008. * macSalt OCTET STRING,
  17009. * iterations INTEGER DEFAULT 1
  17010. * }
  17011. * Note: The iterations default is for historical reasons and its use is
  17012. * deprecated. A higher value, like 1024, is recommended.
  17013. *
  17014. * DigestInfo is defined in PKCS#7 as follows:
  17015. *
  17016. * DigestInfo ::= SEQUENCE {
  17017. * digestAlgorithm DigestAlgorithmIdentifier,
  17018. * digest Digest
  17019. * }
  17020. *
  17021. * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
  17022. *
  17023. * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters
  17024. * for the algorithm, if any. In the case of SHA1 there is none.
  17025. *
  17026. * AlgorithmIdentifer ::= SEQUENCE {
  17027. * algorithm OBJECT IDENTIFIER,
  17028. * parameters ANY DEFINED BY algorithm OPTIONAL
  17029. * }
  17030. *
  17031. * Digest ::= OCTET STRING
  17032. *
  17033. *
  17034. * ContentInfo ::= SEQUENCE {
  17035. * contentType ContentType,
  17036. * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL
  17037. * }
  17038. *
  17039. * ContentType ::= OBJECT IDENTIFIER
  17040. *
  17041. * AuthenticatedSafe ::= SEQUENCE OF ContentInfo
  17042. * -- Data if unencrypted
  17043. * -- EncryptedData if password-encrypted
  17044. * -- EnvelopedData if public key-encrypted
  17045. *
  17046. *
  17047. * SafeContents ::= SEQUENCE OF SafeBag
  17048. *
  17049. * SafeBag ::= SEQUENCE {
  17050. * bagId BAG-TYPE.&id ({PKCS12BagSet})
  17051. * bagValue [0] EXPLICIT BAG-TYPE.&Type({PKCS12BagSet}{@bagId}),
  17052. * bagAttributes SET OF PKCS12Attribute OPTIONAL
  17053. * }
  17054. *
  17055. * PKCS12Attribute ::= SEQUENCE {
  17056. * attrId ATTRIBUTE.&id ({PKCS12AttrSet}),
  17057. * attrValues SET OF ATTRIBUTE.&Type ({PKCS12AttrSet}{@attrId})
  17058. * } -- This type is compatible with the X.500 type 'Attribute'
  17059. *
  17060. * PKCS12AttrSet ATTRIBUTE ::= {
  17061. * friendlyName | -- from PKCS #9
  17062. * localKeyId, -- from PKCS #9
  17063. * ... -- Other attributes are allowed
  17064. * }
  17065. *
  17066. * CertBag ::= SEQUENCE {
  17067. * certId BAG-TYPE.&id ({CertTypes}),
  17068. * certValue [0] EXPLICIT BAG-TYPE.&Type ({CertTypes}{@certId})
  17069. * }
  17070. *
  17071. * x509Certificate BAG-TYPE ::= {OCTET STRING IDENTIFIED BY {certTypes 1}}
  17072. * -- DER-encoded X.509 certificate stored in OCTET STRING
  17073. *
  17074. * sdsiCertificate BAG-TYPE ::= {IA5String IDENTIFIED BY {certTypes 2}}
  17075. * -- Base64-encoded SDSI certificate stored in IA5String
  17076. *
  17077. * CertTypes BAG-TYPE ::= {
  17078. * x509Certificate |
  17079. * sdsiCertificate,
  17080. * ... -- For future extensions
  17081. * }
  17082. */
  17083. var forge$d = forge$F;
  17084. // shortcut for asn.1 & PKI API
  17085. var asn1$3 = forge$d.asn1;
  17086. var pki$1 = forge$d.pki;
  17087. // shortcut for PKCS#12 API
  17088. var p12 = forge$d.pkcs12 = forge$d.pkcs12 || {};
  17089. var contentInfoValidator = {
  17090. name: 'ContentInfo',
  17091. tagClass: asn1$3.Class.UNIVERSAL,
  17092. type: asn1$3.Type.SEQUENCE, // a ContentInfo
  17093. constructed: true,
  17094. value: [{
  17095. name: 'ContentInfo.contentType',
  17096. tagClass: asn1$3.Class.UNIVERSAL,
  17097. type: asn1$3.Type.OID,
  17098. constructed: false,
  17099. capture: 'contentType'
  17100. }, {
  17101. name: 'ContentInfo.content',
  17102. tagClass: asn1$3.Class.CONTEXT_SPECIFIC,
  17103. constructed: true,
  17104. captureAsn1: 'content'
  17105. }]
  17106. };
  17107. var pfxValidator = {
  17108. name: 'PFX',
  17109. tagClass: asn1$3.Class.UNIVERSAL,
  17110. type: asn1$3.Type.SEQUENCE,
  17111. constructed: true,
  17112. value: [{
  17113. name: 'PFX.version',
  17114. tagClass: asn1$3.Class.UNIVERSAL,
  17115. type: asn1$3.Type.INTEGER,
  17116. constructed: false,
  17117. capture: 'version'
  17118. },
  17119. contentInfoValidator, {
  17120. name: 'PFX.macData',
  17121. tagClass: asn1$3.Class.UNIVERSAL,
  17122. type: asn1$3.Type.SEQUENCE,
  17123. constructed: true,
  17124. optional: true,
  17125. captureAsn1: 'mac',
  17126. value: [{
  17127. name: 'PFX.macData.mac',
  17128. tagClass: asn1$3.Class.UNIVERSAL,
  17129. type: asn1$3.Type.SEQUENCE, // DigestInfo
  17130. constructed: true,
  17131. value: [{
  17132. name: 'PFX.macData.mac.digestAlgorithm',
  17133. tagClass: asn1$3.Class.UNIVERSAL,
  17134. type: asn1$3.Type.SEQUENCE, // DigestAlgorithmIdentifier
  17135. constructed: true,
  17136. value: [{
  17137. name: 'PFX.macData.mac.digestAlgorithm.algorithm',
  17138. tagClass: asn1$3.Class.UNIVERSAL,
  17139. type: asn1$3.Type.OID,
  17140. constructed: false,
  17141. capture: 'macAlgorithm'
  17142. }, {
  17143. name: 'PFX.macData.mac.digestAlgorithm.parameters',
  17144. tagClass: asn1$3.Class.UNIVERSAL,
  17145. captureAsn1: 'macAlgorithmParameters'
  17146. }]
  17147. }, {
  17148. name: 'PFX.macData.mac.digest',
  17149. tagClass: asn1$3.Class.UNIVERSAL,
  17150. type: asn1$3.Type.OCTETSTRING,
  17151. constructed: false,
  17152. capture: 'macDigest'
  17153. }]
  17154. }, {
  17155. name: 'PFX.macData.macSalt',
  17156. tagClass: asn1$3.Class.UNIVERSAL,
  17157. type: asn1$3.Type.OCTETSTRING,
  17158. constructed: false,
  17159. capture: 'macSalt'
  17160. }, {
  17161. name: 'PFX.macData.iterations',
  17162. tagClass: asn1$3.Class.UNIVERSAL,
  17163. type: asn1$3.Type.INTEGER,
  17164. constructed: false,
  17165. optional: true,
  17166. capture: 'macIterations'
  17167. }]
  17168. }]
  17169. };
  17170. var safeBagValidator = {
  17171. name: 'SafeBag',
  17172. tagClass: asn1$3.Class.UNIVERSAL,
  17173. type: asn1$3.Type.SEQUENCE,
  17174. constructed: true,
  17175. value: [{
  17176. name: 'SafeBag.bagId',
  17177. tagClass: asn1$3.Class.UNIVERSAL,
  17178. type: asn1$3.Type.OID,
  17179. constructed: false,
  17180. capture: 'bagId'
  17181. }, {
  17182. name: 'SafeBag.bagValue',
  17183. tagClass: asn1$3.Class.CONTEXT_SPECIFIC,
  17184. constructed: true,
  17185. captureAsn1: 'bagValue'
  17186. }, {
  17187. name: 'SafeBag.bagAttributes',
  17188. tagClass: asn1$3.Class.UNIVERSAL,
  17189. type: asn1$3.Type.SET,
  17190. constructed: true,
  17191. optional: true,
  17192. capture: 'bagAttributes'
  17193. }]
  17194. };
  17195. var attributeValidator = {
  17196. name: 'Attribute',
  17197. tagClass: asn1$3.Class.UNIVERSAL,
  17198. type: asn1$3.Type.SEQUENCE,
  17199. constructed: true,
  17200. value: [{
  17201. name: 'Attribute.attrId',
  17202. tagClass: asn1$3.Class.UNIVERSAL,
  17203. type: asn1$3.Type.OID,
  17204. constructed: false,
  17205. capture: 'oid'
  17206. }, {
  17207. name: 'Attribute.attrValues',
  17208. tagClass: asn1$3.Class.UNIVERSAL,
  17209. type: asn1$3.Type.SET,
  17210. constructed: true,
  17211. capture: 'values'
  17212. }]
  17213. };
  17214. var certBagValidator = {
  17215. name: 'CertBag',
  17216. tagClass: asn1$3.Class.UNIVERSAL,
  17217. type: asn1$3.Type.SEQUENCE,
  17218. constructed: true,
  17219. value: [{
  17220. name: 'CertBag.certId',
  17221. tagClass: asn1$3.Class.UNIVERSAL,
  17222. type: asn1$3.Type.OID,
  17223. constructed: false,
  17224. capture: 'certId'
  17225. }, {
  17226. name: 'CertBag.certValue',
  17227. tagClass: asn1$3.Class.CONTEXT_SPECIFIC,
  17228. constructed: true,
  17229. /* So far we only support X.509 certificates (which are wrapped in
  17230. an OCTET STRING, hence hard code that here). */
  17231. value: [{
  17232. name: 'CertBag.certValue[0]',
  17233. tagClass: asn1$3.Class.UNIVERSAL,
  17234. type: asn1$3.Class.OCTETSTRING,
  17235. constructed: false,
  17236. capture: 'cert'
  17237. }]
  17238. }]
  17239. };
  17240. /**
  17241. * Search SafeContents structure for bags with matching attributes.
  17242. *
  17243. * The search can optionally be narrowed by a certain bag type.
  17244. *
  17245. * @param safeContents the SafeContents structure to search in.
  17246. * @param attrName the name of the attribute to compare against.
  17247. * @param attrValue the attribute value to search for.
  17248. * @param [bagType] bag type to narrow search by.
  17249. *
  17250. * @return an array of matching bags.
  17251. */
  17252. function _getBagsByAttribute(safeContents, attrName, attrValue, bagType) {
  17253. var result = [];
  17254. for(var i = 0; i < safeContents.length; i++) {
  17255. for(var j = 0; j < safeContents[i].safeBags.length; j++) {
  17256. var bag = safeContents[i].safeBags[j];
  17257. if(bagType !== undefined && bag.type !== bagType) {
  17258. continue;
  17259. }
  17260. // only filter by bag type, no attribute specified
  17261. if(attrName === null) {
  17262. result.push(bag);
  17263. continue;
  17264. }
  17265. if(bag.attributes[attrName] !== undefined &&
  17266. bag.attributes[attrName].indexOf(attrValue) >= 0) {
  17267. result.push(bag);
  17268. }
  17269. }
  17270. }
  17271. return result;
  17272. }
  17273. /**
  17274. * Converts a PKCS#12 PFX in ASN.1 notation into a PFX object.
  17275. *
  17276. * @param obj The PKCS#12 PFX in ASN.1 notation.
  17277. * @param strict true to use strict DER decoding, false not to (default: true).
  17278. * @param {String} password Password to decrypt with (optional).
  17279. *
  17280. * @return PKCS#12 PFX object.
  17281. */
  17282. p12.pkcs12FromAsn1 = function(obj, strict, password) {
  17283. // handle args
  17284. if(typeof strict === 'string') {
  17285. password = strict;
  17286. strict = true;
  17287. } else if(strict === undefined) {
  17288. strict = true;
  17289. }
  17290. // validate PFX and capture data
  17291. var capture = {};
  17292. var errors = [];
  17293. if(!asn1$3.validate(obj, pfxValidator, capture, errors)) {
  17294. var error = new Error('Cannot read PKCS#12 PFX. ' +
  17295. 'ASN.1 object is not an PKCS#12 PFX.');
  17296. error.errors = error;
  17297. throw error;
  17298. }
  17299. var pfx = {
  17300. version: capture.version.charCodeAt(0),
  17301. safeContents: [],
  17302. /**
  17303. * Gets bags with matching attributes.
  17304. *
  17305. * @param filter the attributes to filter by:
  17306. * [localKeyId] the localKeyId to search for.
  17307. * [localKeyIdHex] the localKeyId in hex to search for.
  17308. * [friendlyName] the friendly name to search for.
  17309. * [bagType] bag type to narrow each attribute search by.
  17310. *
  17311. * @return a map of attribute type to an array of matching bags or, if no
  17312. * attribute was given but a bag type, the map key will be the
  17313. * bag type.
  17314. */
  17315. getBags: function(filter) {
  17316. var rval = {};
  17317. var localKeyId;
  17318. if('localKeyId' in filter) {
  17319. localKeyId = filter.localKeyId;
  17320. } else if('localKeyIdHex' in filter) {
  17321. localKeyId = forge$d.util.hexToBytes(filter.localKeyIdHex);
  17322. }
  17323. // filter on bagType only
  17324. if(localKeyId === undefined && !('friendlyName' in filter) &&
  17325. 'bagType' in filter) {
  17326. rval[filter.bagType] = _getBagsByAttribute(
  17327. pfx.safeContents, null, null, filter.bagType);
  17328. }
  17329. if(localKeyId !== undefined) {
  17330. rval.localKeyId = _getBagsByAttribute(
  17331. pfx.safeContents, 'localKeyId',
  17332. localKeyId, filter.bagType);
  17333. }
  17334. if('friendlyName' in filter) {
  17335. rval.friendlyName = _getBagsByAttribute(
  17336. pfx.safeContents, 'friendlyName',
  17337. filter.friendlyName, filter.bagType);
  17338. }
  17339. return rval;
  17340. },
  17341. /**
  17342. * DEPRECATED: use getBags() instead.
  17343. *
  17344. * Get bags with matching friendlyName attribute.
  17345. *
  17346. * @param friendlyName the friendly name to search for.
  17347. * @param [bagType] bag type to narrow search by.
  17348. *
  17349. * @return an array of bags with matching friendlyName attribute.
  17350. */
  17351. getBagsByFriendlyName: function(friendlyName, bagType) {
  17352. return _getBagsByAttribute(
  17353. pfx.safeContents, 'friendlyName', friendlyName, bagType);
  17354. },
  17355. /**
  17356. * DEPRECATED: use getBags() instead.
  17357. *
  17358. * Get bags with matching localKeyId attribute.
  17359. *
  17360. * @param localKeyId the localKeyId to search for.
  17361. * @param [bagType] bag type to narrow search by.
  17362. *
  17363. * @return an array of bags with matching localKeyId attribute.
  17364. */
  17365. getBagsByLocalKeyId: function(localKeyId, bagType) {
  17366. return _getBagsByAttribute(
  17367. pfx.safeContents, 'localKeyId', localKeyId, bagType);
  17368. }
  17369. };
  17370. if(capture.version.charCodeAt(0) !== 3) {
  17371. var error = new Error('PKCS#12 PFX of version other than 3 not supported.');
  17372. error.version = capture.version.charCodeAt(0);
  17373. throw error;
  17374. }
  17375. if(asn1$3.derToOid(capture.contentType) !== pki$1.oids.data) {
  17376. var error = new Error('Only PKCS#12 PFX in password integrity mode supported.');
  17377. error.oid = asn1$3.derToOid(capture.contentType);
  17378. throw error;
  17379. }
  17380. var data = capture.content.value[0];
  17381. if(data.tagClass !== asn1$3.Class.UNIVERSAL ||
  17382. data.type !== asn1$3.Type.OCTETSTRING) {
  17383. throw new Error('PKCS#12 authSafe content data is not an OCTET STRING.');
  17384. }
  17385. data = _decodePkcs7Data(data);
  17386. // check for MAC
  17387. if(capture.mac) {
  17388. var md = null;
  17389. var macKeyBytes = 0;
  17390. var macAlgorithm = asn1$3.derToOid(capture.macAlgorithm);
  17391. switch(macAlgorithm) {
  17392. case pki$1.oids.sha1:
  17393. md = forge$d.md.sha1.create();
  17394. macKeyBytes = 20;
  17395. break;
  17396. case pki$1.oids.sha256:
  17397. md = forge$d.md.sha256.create();
  17398. macKeyBytes = 32;
  17399. break;
  17400. case pki$1.oids.sha384:
  17401. md = forge$d.md.sha384.create();
  17402. macKeyBytes = 48;
  17403. break;
  17404. case pki$1.oids.sha512:
  17405. md = forge$d.md.sha512.create();
  17406. macKeyBytes = 64;
  17407. break;
  17408. case pki$1.oids.md5:
  17409. md = forge$d.md.md5.create();
  17410. macKeyBytes = 16;
  17411. break;
  17412. }
  17413. if(md === null) {
  17414. throw new Error('PKCS#12 uses unsupported MAC algorithm: ' + macAlgorithm);
  17415. }
  17416. // verify MAC (iterations default to 1)
  17417. var macSalt = new forge$d.util.ByteBuffer(capture.macSalt);
  17418. var macIterations = (('macIterations' in capture) ?
  17419. parseInt(forge$d.util.bytesToHex(capture.macIterations), 16) : 1);
  17420. var macKey = p12.generateKey(
  17421. password, macSalt, 3, macIterations, macKeyBytes, md);
  17422. var mac = forge$d.hmac.create();
  17423. mac.start(md, macKey);
  17424. mac.update(data.value);
  17425. var macValue = mac.getMac();
  17426. if(macValue.getBytes() !== capture.macDigest) {
  17427. throw new Error('PKCS#12 MAC could not be verified. Invalid password?');
  17428. }
  17429. }
  17430. _decodeAuthenticatedSafe(pfx, data.value, strict, password);
  17431. return pfx;
  17432. };
  17433. /**
  17434. * Decodes PKCS#7 Data. PKCS#7 (RFC 2315) defines "Data" as an OCTET STRING,
  17435. * but it is sometimes an OCTET STRING that is composed/constructed of chunks,
  17436. * each its own OCTET STRING. This is BER-encoding vs. DER-encoding. This
  17437. * function transforms this corner-case into the usual simple,
  17438. * non-composed/constructed OCTET STRING.
  17439. *
  17440. * This function may be moved to ASN.1 at some point to better deal with
  17441. * more BER-encoding issues, should they arise.
  17442. *
  17443. * @param data the ASN.1 Data object to transform.
  17444. */
  17445. function _decodePkcs7Data(data) {
  17446. // handle special case of "chunked" data content: an octet string composed
  17447. // of other octet strings
  17448. if(data.composed || data.constructed) {
  17449. var value = forge$d.util.createBuffer();
  17450. for(var i = 0; i < data.value.length; ++i) {
  17451. value.putBytes(data.value[i].value);
  17452. }
  17453. data.composed = data.constructed = false;
  17454. data.value = value.getBytes();
  17455. }
  17456. return data;
  17457. }
  17458. /**
  17459. * Decode PKCS#12 AuthenticatedSafe (BER encoded) into PFX object.
  17460. *
  17461. * The AuthenticatedSafe is a BER-encoded SEQUENCE OF ContentInfo.
  17462. *
  17463. * @param pfx The PKCS#12 PFX object to fill.
  17464. * @param {String} authSafe BER-encoded AuthenticatedSafe.
  17465. * @param strict true to use strict DER decoding, false not to.
  17466. * @param {String} password Password to decrypt with (optional).
  17467. */
  17468. function _decodeAuthenticatedSafe(pfx, authSafe, strict, password) {
  17469. authSafe = asn1$3.fromDer(authSafe, strict); /* actually it's BER encoded */
  17470. if(authSafe.tagClass !== asn1$3.Class.UNIVERSAL ||
  17471. authSafe.type !== asn1$3.Type.SEQUENCE ||
  17472. authSafe.constructed !== true) {
  17473. throw new Error('PKCS#12 AuthenticatedSafe expected to be a ' +
  17474. 'SEQUENCE OF ContentInfo');
  17475. }
  17476. for(var i = 0; i < authSafe.value.length; i++) {
  17477. var contentInfo = authSafe.value[i];
  17478. // validate contentInfo and capture data
  17479. var capture = {};
  17480. var errors = [];
  17481. if(!asn1$3.validate(contentInfo, contentInfoValidator, capture, errors)) {
  17482. var error = new Error('Cannot read ContentInfo.');
  17483. error.errors = errors;
  17484. throw error;
  17485. }
  17486. var obj = {
  17487. encrypted: false
  17488. };
  17489. var safeContents = null;
  17490. var data = capture.content.value[0];
  17491. switch(asn1$3.derToOid(capture.contentType)) {
  17492. case pki$1.oids.data:
  17493. if(data.tagClass !== asn1$3.Class.UNIVERSAL ||
  17494. data.type !== asn1$3.Type.OCTETSTRING) {
  17495. throw new Error('PKCS#12 SafeContents Data is not an OCTET STRING.');
  17496. }
  17497. safeContents = _decodePkcs7Data(data).value;
  17498. break;
  17499. case pki$1.oids.encryptedData:
  17500. safeContents = _decryptSafeContents(data, password);
  17501. obj.encrypted = true;
  17502. break;
  17503. default:
  17504. var error = new Error('Unsupported PKCS#12 contentType.');
  17505. error.contentType = asn1$3.derToOid(capture.contentType);
  17506. throw error;
  17507. }
  17508. obj.safeBags = _decodeSafeContents(safeContents, strict, password);
  17509. pfx.safeContents.push(obj);
  17510. }
  17511. }
  17512. /**
  17513. * Decrypt PKCS#7 EncryptedData structure.
  17514. *
  17515. * @param data ASN.1 encoded EncryptedContentInfo object.
  17516. * @param password The user-provided password.
  17517. *
  17518. * @return The decrypted SafeContents (ASN.1 object).
  17519. */
  17520. function _decryptSafeContents(data, password) {
  17521. var capture = {};
  17522. var errors = [];
  17523. if(!asn1$3.validate(
  17524. data, forge$d.pkcs7.asn1.encryptedDataValidator, capture, errors)) {
  17525. var error = new Error('Cannot read EncryptedContentInfo.');
  17526. error.errors = errors;
  17527. throw error;
  17528. }
  17529. var oid = asn1$3.derToOid(capture.contentType);
  17530. if(oid !== pki$1.oids.data) {
  17531. var error = new Error(
  17532. 'PKCS#12 EncryptedContentInfo ContentType is not Data.');
  17533. error.oid = oid;
  17534. throw error;
  17535. }
  17536. // get cipher
  17537. oid = asn1$3.derToOid(capture.encAlgorithm);
  17538. var cipher = pki$1.pbe.getCipher(oid, capture.encParameter, password);
  17539. // get encrypted data
  17540. var encryptedContentAsn1 = _decodePkcs7Data(capture.encryptedContentAsn1);
  17541. var encrypted = forge$d.util.createBuffer(encryptedContentAsn1.value);
  17542. cipher.update(encrypted);
  17543. if(!cipher.finish()) {
  17544. throw new Error('Failed to decrypt PKCS#12 SafeContents.');
  17545. }
  17546. return cipher.output.getBytes();
  17547. }
  17548. /**
  17549. * Decode PKCS#12 SafeContents (BER-encoded) into array of Bag objects.
  17550. *
  17551. * The safeContents is a BER-encoded SEQUENCE OF SafeBag.
  17552. *
  17553. * @param {String} safeContents BER-encoded safeContents.
  17554. * @param strict true to use strict DER decoding, false not to.
  17555. * @param {String} password Password to decrypt with (optional).
  17556. *
  17557. * @return {Array} Array of Bag objects.
  17558. */
  17559. function _decodeSafeContents(safeContents, strict, password) {
  17560. // if strict and no safe contents, return empty safes
  17561. if(!strict && safeContents.length === 0) {
  17562. return [];
  17563. }
  17564. // actually it's BER-encoded
  17565. safeContents = asn1$3.fromDer(safeContents, strict);
  17566. if(safeContents.tagClass !== asn1$3.Class.UNIVERSAL ||
  17567. safeContents.type !== asn1$3.Type.SEQUENCE ||
  17568. safeContents.constructed !== true) {
  17569. throw new Error(
  17570. 'PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.');
  17571. }
  17572. var res = [];
  17573. for(var i = 0; i < safeContents.value.length; i++) {
  17574. var safeBag = safeContents.value[i];
  17575. // validate SafeBag and capture data
  17576. var capture = {};
  17577. var errors = [];
  17578. if(!asn1$3.validate(safeBag, safeBagValidator, capture, errors)) {
  17579. var error = new Error('Cannot read SafeBag.');
  17580. error.errors = errors;
  17581. throw error;
  17582. }
  17583. /* Create bag object and push to result array. */
  17584. var bag = {
  17585. type: asn1$3.derToOid(capture.bagId),
  17586. attributes: _decodeBagAttributes(capture.bagAttributes)
  17587. };
  17588. res.push(bag);
  17589. var validator, decoder;
  17590. var bagAsn1 = capture.bagValue.value[0];
  17591. switch(bag.type) {
  17592. case pki$1.oids.pkcs8ShroudedKeyBag:
  17593. /* bagAsn1 has a EncryptedPrivateKeyInfo, which we need to decrypt.
  17594. Afterwards we can handle it like a keyBag,
  17595. which is a PrivateKeyInfo. */
  17596. bagAsn1 = pki$1.decryptPrivateKeyInfo(bagAsn1, password);
  17597. if(bagAsn1 === null) {
  17598. throw new Error(
  17599. 'Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?');
  17600. }
  17601. /* fall through */
  17602. case pki$1.oids.keyBag:
  17603. /* A PKCS#12 keyBag is a simple PrivateKeyInfo as understood by our
  17604. PKI module, hence we don't have to do validation/capturing here,
  17605. just pass what we already got. */
  17606. try {
  17607. bag.key = pki$1.privateKeyFromAsn1(bagAsn1);
  17608. } catch(e) {
  17609. // ignore unknown key type, pass asn1 value
  17610. bag.key = null;
  17611. bag.asn1 = bagAsn1;
  17612. }
  17613. continue; /* Nothing more to do. */
  17614. case pki$1.oids.certBag:
  17615. /* A PKCS#12 certBag can wrap both X.509 and sdsi certificates.
  17616. Therefore put the SafeBag content through another validator to
  17617. capture the fields. Afterwards check & store the results. */
  17618. validator = certBagValidator;
  17619. decoder = function() {
  17620. if(asn1$3.derToOid(capture.certId) !== pki$1.oids.x509Certificate) {
  17621. var error = new Error(
  17622. 'Unsupported certificate type, only X.509 supported.');
  17623. error.oid = asn1$3.derToOid(capture.certId);
  17624. throw error;
  17625. }
  17626. // true=produce cert hash
  17627. var certAsn1 = asn1$3.fromDer(capture.cert, strict);
  17628. try {
  17629. bag.cert = pki$1.certificateFromAsn1(certAsn1, true);
  17630. } catch(e) {
  17631. // ignore unknown cert type, pass asn1 value
  17632. bag.cert = null;
  17633. bag.asn1 = certAsn1;
  17634. }
  17635. };
  17636. break;
  17637. default:
  17638. var error = new Error('Unsupported PKCS#12 SafeBag type.');
  17639. error.oid = bag.type;
  17640. throw error;
  17641. }
  17642. /* Validate SafeBag value (i.e. CertBag, etc.) and capture data if needed. */
  17643. if(validator !== undefined &&
  17644. !asn1$3.validate(bagAsn1, validator, capture, errors)) {
  17645. var error = new Error('Cannot read PKCS#12 ' + validator.name);
  17646. error.errors = errors;
  17647. throw error;
  17648. }
  17649. /* Call decoder function from above to store the results. */
  17650. decoder();
  17651. }
  17652. return res;
  17653. }
  17654. /**
  17655. * Decode PKCS#12 SET OF PKCS12Attribute into JavaScript object.
  17656. *
  17657. * @param attributes SET OF PKCS12Attribute (ASN.1 object).
  17658. *
  17659. * @return the decoded attributes.
  17660. */
  17661. function _decodeBagAttributes(attributes) {
  17662. var decodedAttrs = {};
  17663. if(attributes !== undefined) {
  17664. for(var i = 0; i < attributes.length; ++i) {
  17665. var capture = {};
  17666. var errors = [];
  17667. if(!asn1$3.validate(attributes[i], attributeValidator, capture, errors)) {
  17668. var error = new Error('Cannot read PKCS#12 BagAttribute.');
  17669. error.errors = errors;
  17670. throw error;
  17671. }
  17672. var oid = asn1$3.derToOid(capture.oid);
  17673. if(pki$1.oids[oid] === undefined) {
  17674. // unsupported attribute type, ignore.
  17675. continue;
  17676. }
  17677. decodedAttrs[pki$1.oids[oid]] = [];
  17678. for(var j = 0; j < capture.values.length; ++j) {
  17679. decodedAttrs[pki$1.oids[oid]].push(capture.values[j].value);
  17680. }
  17681. }
  17682. }
  17683. return decodedAttrs;
  17684. }
  17685. /**
  17686. * Wraps a private key and certificate in a PKCS#12 PFX wrapper. If a
  17687. * password is provided then the private key will be encrypted.
  17688. *
  17689. * An entire certificate chain may also be included. To do this, pass
  17690. * an array for the "cert" parameter where the first certificate is
  17691. * the one that is paired with the private key and each subsequent one
  17692. * verifies the previous one. The certificates may be in PEM format or
  17693. * have been already parsed by Forge.
  17694. *
  17695. * @todo implement password-based-encryption for the whole package
  17696. *
  17697. * @param key the private key.
  17698. * @param cert the certificate (may be an array of certificates in order
  17699. * to specify a certificate chain).
  17700. * @param password the password to use, null for none.
  17701. * @param options:
  17702. * algorithm the encryption algorithm to use
  17703. * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'.
  17704. * count the iteration count to use.
  17705. * saltSize the salt size to use.
  17706. * useMac true to include a MAC, false not to, defaults to true.
  17707. * localKeyId the local key ID to use, in hex.
  17708. * friendlyName the friendly name to use.
  17709. * generateLocalKeyId true to generate a random local key ID,
  17710. * false not to, defaults to true.
  17711. *
  17712. * @return the PKCS#12 PFX ASN.1 object.
  17713. */
  17714. p12.toPkcs12Asn1 = function(key, cert, password, options) {
  17715. // set default options
  17716. options = options || {};
  17717. options.saltSize = options.saltSize || 8;
  17718. options.count = options.count || 2048;
  17719. options.algorithm = options.algorithm || options.encAlgorithm || 'aes128';
  17720. if(!('useMac' in options)) {
  17721. options.useMac = true;
  17722. }
  17723. if(!('localKeyId' in options)) {
  17724. options.localKeyId = null;
  17725. }
  17726. if(!('generateLocalKeyId' in options)) {
  17727. options.generateLocalKeyId = true;
  17728. }
  17729. var localKeyId = options.localKeyId;
  17730. var bagAttrs;
  17731. if(localKeyId !== null) {
  17732. localKeyId = forge$d.util.hexToBytes(localKeyId);
  17733. } else if(options.generateLocalKeyId) {
  17734. // use SHA-1 of paired cert, if available
  17735. if(cert) {
  17736. var pairedCert = forge$d.util.isArray(cert) ? cert[0] : cert;
  17737. if(typeof pairedCert === 'string') {
  17738. pairedCert = pki$1.certificateFromPem(pairedCert);
  17739. }
  17740. var sha1 = forge$d.md.sha1.create();
  17741. sha1.update(asn1$3.toDer(pki$1.certificateToAsn1(pairedCert)).getBytes());
  17742. localKeyId = sha1.digest().getBytes();
  17743. } else {
  17744. // FIXME: consider using SHA-1 of public key (which can be generated
  17745. // from private key components), see: cert.generateSubjectKeyIdentifier
  17746. // generate random bytes
  17747. localKeyId = forge$d.random.getBytes(20);
  17748. }
  17749. }
  17750. var attrs = [];
  17751. if(localKeyId !== null) {
  17752. attrs.push(
  17753. // localKeyID
  17754. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [
  17755. // attrId
  17756. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false,
  17757. asn1$3.oidToDer(pki$1.oids.localKeyId).getBytes()),
  17758. // attrValues
  17759. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SET, true, [
  17760. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OCTETSTRING, false,
  17761. localKeyId)
  17762. ])
  17763. ]));
  17764. }
  17765. if('friendlyName' in options) {
  17766. attrs.push(
  17767. // friendlyName
  17768. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [
  17769. // attrId
  17770. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false,
  17771. asn1$3.oidToDer(pki$1.oids.friendlyName).getBytes()),
  17772. // attrValues
  17773. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SET, true, [
  17774. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.BMPSTRING, false,
  17775. options.friendlyName)
  17776. ])
  17777. ]));
  17778. }
  17779. if(attrs.length > 0) {
  17780. bagAttrs = asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SET, true, attrs);
  17781. }
  17782. // collect contents for AuthenticatedSafe
  17783. var contents = [];
  17784. // create safe bag(s) for certificate chain
  17785. var chain = [];
  17786. if(cert !== null) {
  17787. if(forge$d.util.isArray(cert)) {
  17788. chain = cert;
  17789. } else {
  17790. chain = [cert];
  17791. }
  17792. }
  17793. var certSafeBags = [];
  17794. for(var i = 0; i < chain.length; ++i) {
  17795. // convert cert from PEM as necessary
  17796. cert = chain[i];
  17797. if(typeof cert === 'string') {
  17798. cert = pki$1.certificateFromPem(cert);
  17799. }
  17800. // SafeBag
  17801. var certBagAttrs = (i === 0) ? bagAttrs : undefined;
  17802. var certAsn1 = pki$1.certificateToAsn1(cert);
  17803. var certSafeBag =
  17804. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [
  17805. // bagId
  17806. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false,
  17807. asn1$3.oidToDer(pki$1.oids.certBag).getBytes()),
  17808. // bagValue
  17809. asn1$3.create(asn1$3.Class.CONTEXT_SPECIFIC, 0, true, [
  17810. // CertBag
  17811. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [
  17812. // certId
  17813. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false,
  17814. asn1$3.oidToDer(pki$1.oids.x509Certificate).getBytes()),
  17815. // certValue (x509Certificate)
  17816. asn1$3.create(asn1$3.Class.CONTEXT_SPECIFIC, 0, true, [
  17817. asn1$3.create(
  17818. asn1$3.Class.UNIVERSAL, asn1$3.Type.OCTETSTRING, false,
  17819. asn1$3.toDer(certAsn1).getBytes())
  17820. ])])]),
  17821. // bagAttributes (OPTIONAL)
  17822. certBagAttrs
  17823. ]);
  17824. certSafeBags.push(certSafeBag);
  17825. }
  17826. if(certSafeBags.length > 0) {
  17827. // SafeContents
  17828. var certSafeContents = asn1$3.create(
  17829. asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, certSafeBags);
  17830. // ContentInfo
  17831. var certCI =
  17832. // PKCS#7 ContentInfo
  17833. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [
  17834. // contentType
  17835. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false,
  17836. // OID for the content type is 'data'
  17837. asn1$3.oidToDer(pki$1.oids.data).getBytes()),
  17838. // content
  17839. asn1$3.create(asn1$3.Class.CONTEXT_SPECIFIC, 0, true, [
  17840. asn1$3.create(
  17841. asn1$3.Class.UNIVERSAL, asn1$3.Type.OCTETSTRING, false,
  17842. asn1$3.toDer(certSafeContents).getBytes())
  17843. ])
  17844. ]);
  17845. contents.push(certCI);
  17846. }
  17847. // create safe contents for private key
  17848. var keyBag = null;
  17849. if(key !== null) {
  17850. // SafeBag
  17851. var pkAsn1 = pki$1.wrapRsaPrivateKey(pki$1.privateKeyToAsn1(key));
  17852. if(password === null) {
  17853. // no encryption
  17854. keyBag = asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [
  17855. // bagId
  17856. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false,
  17857. asn1$3.oidToDer(pki$1.oids.keyBag).getBytes()),
  17858. // bagValue
  17859. asn1$3.create(asn1$3.Class.CONTEXT_SPECIFIC, 0, true, [
  17860. // PrivateKeyInfo
  17861. pkAsn1
  17862. ]),
  17863. // bagAttributes (OPTIONAL)
  17864. bagAttrs
  17865. ]);
  17866. } else {
  17867. // encrypted PrivateKeyInfo
  17868. keyBag = asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [
  17869. // bagId
  17870. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false,
  17871. asn1$3.oidToDer(pki$1.oids.pkcs8ShroudedKeyBag).getBytes()),
  17872. // bagValue
  17873. asn1$3.create(asn1$3.Class.CONTEXT_SPECIFIC, 0, true, [
  17874. // EncryptedPrivateKeyInfo
  17875. pki$1.encryptPrivateKeyInfo(pkAsn1, password, options)
  17876. ]),
  17877. // bagAttributes (OPTIONAL)
  17878. bagAttrs
  17879. ]);
  17880. }
  17881. // SafeContents
  17882. var keySafeContents =
  17883. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [keyBag]);
  17884. // ContentInfo
  17885. var keyCI =
  17886. // PKCS#7 ContentInfo
  17887. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [
  17888. // contentType
  17889. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false,
  17890. // OID for the content type is 'data'
  17891. asn1$3.oidToDer(pki$1.oids.data).getBytes()),
  17892. // content
  17893. asn1$3.create(asn1$3.Class.CONTEXT_SPECIFIC, 0, true, [
  17894. asn1$3.create(
  17895. asn1$3.Class.UNIVERSAL, asn1$3.Type.OCTETSTRING, false,
  17896. asn1$3.toDer(keySafeContents).getBytes())
  17897. ])
  17898. ]);
  17899. contents.push(keyCI);
  17900. }
  17901. // create AuthenticatedSafe by stringing together the contents
  17902. var safe = asn1$3.create(
  17903. asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, contents);
  17904. var macData;
  17905. if(options.useMac) {
  17906. // MacData
  17907. var sha1 = forge$d.md.sha1.create();
  17908. var macSalt = new forge$d.util.ByteBuffer(
  17909. forge$d.random.getBytes(options.saltSize));
  17910. var count = options.count;
  17911. // 160-bit key
  17912. var key = p12.generateKey(password, macSalt, 3, count, 20);
  17913. var mac = forge$d.hmac.create();
  17914. mac.start(sha1, key);
  17915. mac.update(asn1$3.toDer(safe).getBytes());
  17916. var macValue = mac.getMac();
  17917. macData = asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [
  17918. // mac DigestInfo
  17919. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [
  17920. // digestAlgorithm
  17921. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [
  17922. // algorithm = SHA-1
  17923. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false,
  17924. asn1$3.oidToDer(pki$1.oids.sha1).getBytes()),
  17925. // parameters = Null
  17926. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.NULL, false, '')
  17927. ]),
  17928. // digest
  17929. asn1$3.create(
  17930. asn1$3.Class.UNIVERSAL, asn1$3.Type.OCTETSTRING,
  17931. false, macValue.getBytes())
  17932. ]),
  17933. // macSalt OCTET STRING
  17934. asn1$3.create(
  17935. asn1$3.Class.UNIVERSAL, asn1$3.Type.OCTETSTRING, false, macSalt.getBytes()),
  17936. // iterations INTEGER (XXX: Only support count < 65536)
  17937. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.INTEGER, false,
  17938. asn1$3.integerToDer(count).getBytes()
  17939. )
  17940. ]);
  17941. }
  17942. // PFX
  17943. return asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [
  17944. // version (3)
  17945. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.INTEGER, false,
  17946. asn1$3.integerToDer(3).getBytes()),
  17947. // PKCS#7 ContentInfo
  17948. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.SEQUENCE, true, [
  17949. // contentType
  17950. asn1$3.create(asn1$3.Class.UNIVERSAL, asn1$3.Type.OID, false,
  17951. // OID for the content type is 'data'
  17952. asn1$3.oidToDer(pki$1.oids.data).getBytes()),
  17953. // content
  17954. asn1$3.create(asn1$3.Class.CONTEXT_SPECIFIC, 0, true, [
  17955. asn1$3.create(
  17956. asn1$3.Class.UNIVERSAL, asn1$3.Type.OCTETSTRING, false,
  17957. asn1$3.toDer(safe).getBytes())
  17958. ])
  17959. ]),
  17960. macData
  17961. ]);
  17962. };
  17963. /**
  17964. * Derives a PKCS#12 key.
  17965. *
  17966. * @param password the password to derive the key material from, null or
  17967. * undefined for none.
  17968. * @param salt the salt, as a ByteBuffer, to use.
  17969. * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC).
  17970. * @param iter the iteration count.
  17971. * @param n the number of bytes to derive from the password.
  17972. * @param md the message digest to use, defaults to SHA-1.
  17973. *
  17974. * @return a ByteBuffer with the bytes derived from the password.
  17975. */
  17976. p12.generateKey = forge$d.pbe.generatePkcs12Key;
  17977. /**
  17978. * Javascript implementation of a basic Public Key Infrastructure, including
  17979. * support for RSA public and private keys.
  17980. *
  17981. * @author Dave Longley
  17982. *
  17983. * Copyright (c) 2010-2013 Digital Bazaar, Inc.
  17984. */
  17985. var forge$c = forge$F;
  17986. // shortcut for asn.1 API
  17987. var asn1$2 = forge$c.asn1;
  17988. /* Public Key Infrastructure (PKI) implementation. */
  17989. var pki = forge$c.pki = forge$c.pki || {};
  17990. /**
  17991. * NOTE: THIS METHOD IS DEPRECATED. Use pem.decode() instead.
  17992. *
  17993. * Converts PEM-formatted data to DER.
  17994. *
  17995. * @param pem the PEM-formatted data.
  17996. *
  17997. * @return the DER-formatted data.
  17998. */
  17999. pki.pemToDer = function(pem) {
  18000. var msg = forge$c.pem.decode(pem)[0];
  18001. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  18002. throw new Error('Could not convert PEM to DER; PEM is encrypted.');
  18003. }
  18004. return forge$c.util.createBuffer(msg.body);
  18005. };
  18006. /**
  18007. * Converts an RSA private key from PEM format.
  18008. *
  18009. * @param pem the PEM-formatted private key.
  18010. *
  18011. * @return the private key.
  18012. */
  18013. pki.privateKeyFromPem = function(pem) {
  18014. var msg = forge$c.pem.decode(pem)[0];
  18015. if(msg.type !== 'PRIVATE KEY' && msg.type !== 'RSA PRIVATE KEY') {
  18016. var error = new Error('Could not convert private key from PEM; PEM ' +
  18017. 'header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".');
  18018. error.headerType = msg.type;
  18019. throw error;
  18020. }
  18021. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  18022. throw new Error('Could not convert private key from PEM; PEM is encrypted.');
  18023. }
  18024. // convert DER to ASN.1 object
  18025. var obj = asn1$2.fromDer(msg.body);
  18026. return pki.privateKeyFromAsn1(obj);
  18027. };
  18028. /**
  18029. * Converts an RSA private key to PEM format.
  18030. *
  18031. * @param key the private key.
  18032. * @param maxline the maximum characters per line, defaults to 64.
  18033. *
  18034. * @return the PEM-formatted private key.
  18035. */
  18036. pki.privateKeyToPem = function(key, maxline) {
  18037. // convert to ASN.1, then DER, then PEM-encode
  18038. var msg = {
  18039. type: 'RSA PRIVATE KEY',
  18040. body: asn1$2.toDer(pki.privateKeyToAsn1(key)).getBytes()
  18041. };
  18042. return forge$c.pem.encode(msg, {maxline: maxline});
  18043. };
  18044. /**
  18045. * Converts a PrivateKeyInfo to PEM format.
  18046. *
  18047. * @param pki the PrivateKeyInfo.
  18048. * @param maxline the maximum characters per line, defaults to 64.
  18049. *
  18050. * @return the PEM-formatted private key.
  18051. */
  18052. pki.privateKeyInfoToPem = function(pki, maxline) {
  18053. // convert to DER, then PEM-encode
  18054. var msg = {
  18055. type: 'PRIVATE KEY',
  18056. body: asn1$2.toDer(pki).getBytes()
  18057. };
  18058. return forge$c.pem.encode(msg, {maxline: maxline});
  18059. };
  18060. /**
  18061. * A Javascript implementation of Transport Layer Security (TLS).
  18062. *
  18063. * @author Dave Longley
  18064. *
  18065. * Copyright (c) 2009-2014 Digital Bazaar, Inc.
  18066. *
  18067. * The TLS Handshake Protocol involves the following steps:
  18068. *
  18069. * - Exchange hello messages to agree on algorithms, exchange random values,
  18070. * and check for session resumption.
  18071. *
  18072. * - Exchange the necessary cryptographic parameters to allow the client and
  18073. * server to agree on a premaster secret.
  18074. *
  18075. * - Exchange certificates and cryptographic information to allow the client
  18076. * and server to authenticate themselves.
  18077. *
  18078. * - Generate a master secret from the premaster secret and exchanged random
  18079. * values.
  18080. *
  18081. * - Provide security parameters to the record layer.
  18082. *
  18083. * - Allow the client and server to verify that their peer has calculated the
  18084. * same security parameters and that the handshake occurred without tampering
  18085. * by an attacker.
  18086. *
  18087. * Up to 4 different messages may be sent during a key exchange. The server
  18088. * certificate, the server key exchange, the client certificate, and the
  18089. * client key exchange.
  18090. *
  18091. * A typical handshake (from the client's perspective).
  18092. *
  18093. * 1. Client sends ClientHello.
  18094. * 2. Client receives ServerHello.
  18095. * 3. Client receives optional Certificate.
  18096. * 4. Client receives optional ServerKeyExchange.
  18097. * 5. Client receives ServerHelloDone.
  18098. * 6. Client sends optional Certificate.
  18099. * 7. Client sends ClientKeyExchange.
  18100. * 8. Client sends optional CertificateVerify.
  18101. * 9. Client sends ChangeCipherSpec.
  18102. * 10. Client sends Finished.
  18103. * 11. Client receives ChangeCipherSpec.
  18104. * 12. Client receives Finished.
  18105. * 13. Client sends/receives application data.
  18106. *
  18107. * To reuse an existing session:
  18108. *
  18109. * 1. Client sends ClientHello with session ID for reuse.
  18110. * 2. Client receives ServerHello with same session ID if reusing.
  18111. * 3. Client receives ChangeCipherSpec message if reusing.
  18112. * 4. Client receives Finished.
  18113. * 5. Client sends ChangeCipherSpec.
  18114. * 6. Client sends Finished.
  18115. *
  18116. * Note: Client ignores HelloRequest if in the middle of a handshake.
  18117. *
  18118. * Record Layer:
  18119. *
  18120. * The record layer fragments information blocks into TLSPlaintext records
  18121. * carrying data in chunks of 2^14 bytes or less. Client message boundaries are
  18122. * not preserved in the record layer (i.e., multiple client messages of the
  18123. * same ContentType MAY be coalesced into a single TLSPlaintext record, or a
  18124. * single message MAY be fragmented across several records).
  18125. *
  18126. * struct {
  18127. * uint8 major;
  18128. * uint8 minor;
  18129. * } ProtocolVersion;
  18130. *
  18131. * struct {
  18132. * ContentType type;
  18133. * ProtocolVersion version;
  18134. * uint16 length;
  18135. * opaque fragment[TLSPlaintext.length];
  18136. * } TLSPlaintext;
  18137. *
  18138. * type:
  18139. * The higher-level protocol used to process the enclosed fragment.
  18140. *
  18141. * version:
  18142. * The version of the protocol being employed. TLS Version 1.2 uses version
  18143. * {3, 3}. TLS Version 1.0 uses version {3, 1}. Note that a client that
  18144. * supports multiple versions of TLS may not know what version will be
  18145. * employed before it receives the ServerHello.
  18146. *
  18147. * length:
  18148. * The length (in bytes) of the following TLSPlaintext.fragment. The length
  18149. * MUST NOT exceed 2^14 = 16384 bytes.
  18150. *
  18151. * fragment:
  18152. * The application data. This data is transparent and treated as an
  18153. * independent block to be dealt with by the higher-level protocol specified
  18154. * by the type field.
  18155. *
  18156. * Implementations MUST NOT send zero-length fragments of Handshake, Alert, or
  18157. * ChangeCipherSpec content types. Zero-length fragments of Application data
  18158. * MAY be sent as they are potentially useful as a traffic analysis
  18159. * countermeasure.
  18160. *
  18161. * Note: Data of different TLS record layer content types MAY be interleaved.
  18162. * Application data is generally of lower precedence for transmission than
  18163. * other content types. However, records MUST be delivered to the network in
  18164. * the same order as they are protected by the record layer. Recipients MUST
  18165. * receive and process interleaved application layer traffic during handshakes
  18166. * subsequent to the first one on a connection.
  18167. *
  18168. * struct {
  18169. * ContentType type; // same as TLSPlaintext.type
  18170. * ProtocolVersion version;// same as TLSPlaintext.version
  18171. * uint16 length;
  18172. * opaque fragment[TLSCompressed.length];
  18173. * } TLSCompressed;
  18174. *
  18175. * length:
  18176. * The length (in bytes) of the following TLSCompressed.fragment.
  18177. * The length MUST NOT exceed 2^14 + 1024.
  18178. *
  18179. * fragment:
  18180. * The compressed form of TLSPlaintext.fragment.
  18181. *
  18182. * Note: A CompressionMethod.null operation is an identity operation; no fields
  18183. * are altered. In this implementation, since no compression is supported,
  18184. * uncompressed records are always the same as compressed records.
  18185. *
  18186. * Encryption Information:
  18187. *
  18188. * The encryption and MAC functions translate a TLSCompressed structure into a
  18189. * TLSCiphertext. The decryption functions reverse the process. The MAC of the
  18190. * record also includes a sequence number so that missing, extra, or repeated
  18191. * messages are detectable.
  18192. *
  18193. * struct {
  18194. * ContentType type;
  18195. * ProtocolVersion version;
  18196. * uint16 length;
  18197. * select (SecurityParameters.cipher_type) {
  18198. * case stream: GenericStreamCipher;
  18199. * case block: GenericBlockCipher;
  18200. * case aead: GenericAEADCipher;
  18201. * } fragment;
  18202. * } TLSCiphertext;
  18203. *
  18204. * type:
  18205. * The type field is identical to TLSCompressed.type.
  18206. *
  18207. * version:
  18208. * The version field is identical to TLSCompressed.version.
  18209. *
  18210. * length:
  18211. * The length (in bytes) of the following TLSCiphertext.fragment.
  18212. * The length MUST NOT exceed 2^14 + 2048.
  18213. *
  18214. * fragment:
  18215. * The encrypted form of TLSCompressed.fragment, with the MAC.
  18216. *
  18217. * Note: Only CBC Block Ciphers are supported by this implementation.
  18218. *
  18219. * The TLSCompressed.fragment structures are converted to/from block
  18220. * TLSCiphertext.fragment structures.
  18221. *
  18222. * struct {
  18223. * opaque IV[SecurityParameters.record_iv_length];
  18224. * block-ciphered struct {
  18225. * opaque content[TLSCompressed.length];
  18226. * opaque MAC[SecurityParameters.mac_length];
  18227. * uint8 padding[GenericBlockCipher.padding_length];
  18228. * uint8 padding_length;
  18229. * };
  18230. * } GenericBlockCipher;
  18231. *
  18232. * The MAC is generated as described in Section 6.2.3.1.
  18233. *
  18234. * IV:
  18235. * The Initialization Vector (IV) SHOULD be chosen at random, and MUST be
  18236. * unpredictable. Note that in versions of TLS prior to 1.1, there was no
  18237. * IV field, and the last ciphertext block of the previous record (the "CBC
  18238. * residue") was used as the IV. This was changed to prevent the attacks
  18239. * described in [CBCATT]. For block ciphers, the IV length is of length
  18240. * SecurityParameters.record_iv_length, which is equal to the
  18241. * SecurityParameters.block_size.
  18242. *
  18243. * padding:
  18244. * Padding that is added to force the length of the plaintext to be an
  18245. * integral multiple of the block cipher's block length. The padding MAY be
  18246. * any length up to 255 bytes, as long as it results in the
  18247. * TLSCiphertext.length being an integral multiple of the block length.
  18248. * Lengths longer than necessary might be desirable to frustrate attacks on
  18249. * a protocol that are based on analysis of the lengths of exchanged
  18250. * messages. Each uint8 in the padding data vector MUST be filled with the
  18251. * padding length value. The receiver MUST check this padding and MUST use
  18252. * the bad_record_mac alert to indicate padding errors.
  18253. *
  18254. * padding_length:
  18255. * The padding length MUST be such that the total size of the
  18256. * GenericBlockCipher structure is a multiple of the cipher's block length.
  18257. * Legal values range from zero to 255, inclusive. This length specifies the
  18258. * length of the padding field exclusive of the padding_length field itself.
  18259. *
  18260. * The encrypted data length (TLSCiphertext.length) is one more than the sum of
  18261. * SecurityParameters.block_length, TLSCompressed.length,
  18262. * SecurityParameters.mac_length, and padding_length.
  18263. *
  18264. * Example: If the block length is 8 bytes, the content length
  18265. * (TLSCompressed.length) is 61 bytes, and the MAC length is 20 bytes, then the
  18266. * length before padding is 82 bytes (this does not include the IV. Thus, the
  18267. * padding length modulo 8 must be equal to 6 in order to make the total length
  18268. * an even multiple of 8 bytes (the block length). The padding length can be
  18269. * 6, 14, 22, and so on, through 254. If the padding length were the minimum
  18270. * necessary, 6, the padding would be 6 bytes, each containing the value 6.
  18271. * Thus, the last 8 octets of the GenericBlockCipher before block encryption
  18272. * would be xx 06 06 06 06 06 06 06, where xx is the last octet of the MAC.
  18273. *
  18274. * Note: With block ciphers in CBC mode (Cipher Block Chaining), it is critical
  18275. * that the entire plaintext of the record be known before any ciphertext is
  18276. * transmitted. Otherwise, it is possible for the attacker to mount the attack
  18277. * described in [CBCATT].
  18278. *
  18279. * Implementation note: Canvel et al. [CBCTIME] have demonstrated a timing
  18280. * attack on CBC padding based on the time required to compute the MAC. In
  18281. * order to defend against this attack, implementations MUST ensure that
  18282. * record processing time is essentially the same whether or not the padding
  18283. * is correct. In general, the best way to do this is to compute the MAC even
  18284. * if the padding is incorrect, and only then reject the packet. For instance,
  18285. * if the pad appears to be incorrect, the implementation might assume a
  18286. * zero-length pad and then compute the MAC. This leaves a small timing
  18287. * channel, since MAC performance depends, to some extent, on the size of the
  18288. * data fragment, but it is not believed to be large enough to be exploitable,
  18289. * due to the large block size of existing MACs and the small size of the
  18290. * timing signal.
  18291. */
  18292. var forge$b = forge$F;
  18293. /**
  18294. * Generates pseudo random bytes by mixing the result of two hash functions,
  18295. * MD5 and SHA-1.
  18296. *
  18297. * prf_TLS1(secret, label, seed) =
  18298. * P_MD5(S1, label + seed) XOR P_SHA-1(S2, label + seed);
  18299. *
  18300. * Each P_hash function functions as follows:
  18301. *
  18302. * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
  18303. * HMAC_hash(secret, A(2) + seed) +
  18304. * HMAC_hash(secret, A(3) + seed) + ...
  18305. * A() is defined as:
  18306. * A(0) = seed
  18307. * A(i) = HMAC_hash(secret, A(i-1))
  18308. *
  18309. * The '+' operator denotes concatenation.
  18310. *
  18311. * As many iterations A(N) as are needed are performed to generate enough
  18312. * pseudo random byte output. If an iteration creates more data than is
  18313. * necessary, then it is truncated.
  18314. *
  18315. * Therefore:
  18316. * A(1) = HMAC_hash(secret, A(0))
  18317. * = HMAC_hash(secret, seed)
  18318. * A(2) = HMAC_hash(secret, A(1))
  18319. * = HMAC_hash(secret, HMAC_hash(secret, seed))
  18320. *
  18321. * Therefore:
  18322. * P_hash(secret, seed) =
  18323. * HMAC_hash(secret, HMAC_hash(secret, A(0)) + seed) +
  18324. * HMAC_hash(secret, HMAC_hash(secret, A(1)) + seed) +
  18325. * ...
  18326. *
  18327. * Therefore:
  18328. * P_hash(secret, seed) =
  18329. * HMAC_hash(secret, HMAC_hash(secret, seed) + seed) +
  18330. * HMAC_hash(secret, HMAC_hash(secret, HMAC_hash(secret, seed)) + seed) +
  18331. * ...
  18332. *
  18333. * @param secret the secret to use.
  18334. * @param label the label to use.
  18335. * @param seed the seed value to use.
  18336. * @param length the number of bytes to generate.
  18337. *
  18338. * @return the pseudo random bytes in a byte buffer.
  18339. */
  18340. var prf_TLS1 = function(secret, label, seed, length) {
  18341. var rval = forge$b.util.createBuffer();
  18342. /* For TLS 1.0, the secret is split in half, into two secrets of equal
  18343. length. If the secret has an odd length then the last byte of the first
  18344. half will be the same as the first byte of the second. The length of the
  18345. two secrets is half of the secret rounded up. */
  18346. var idx = (secret.length >> 1);
  18347. var slen = idx + (secret.length & 1);
  18348. var s1 = secret.substr(0, slen);
  18349. var s2 = secret.substr(idx, slen);
  18350. var ai = forge$b.util.createBuffer();
  18351. var hmac = forge$b.hmac.create();
  18352. seed = label + seed;
  18353. // determine the number of iterations that must be performed to generate
  18354. // enough output bytes, md5 creates 16 byte hashes, sha1 creates 20
  18355. var md5itr = Math.ceil(length / 16);
  18356. var sha1itr = Math.ceil(length / 20);
  18357. // do md5 iterations
  18358. hmac.start('MD5', s1);
  18359. var md5bytes = forge$b.util.createBuffer();
  18360. ai.putBytes(seed);
  18361. for(var i = 0; i < md5itr; ++i) {
  18362. // HMAC_hash(secret, A(i-1))
  18363. hmac.start(null, null);
  18364. hmac.update(ai.getBytes());
  18365. ai.putBuffer(hmac.digest());
  18366. // HMAC_hash(secret, A(i) + seed)
  18367. hmac.start(null, null);
  18368. hmac.update(ai.bytes() + seed);
  18369. md5bytes.putBuffer(hmac.digest());
  18370. }
  18371. // do sha1 iterations
  18372. hmac.start('SHA1', s2);
  18373. var sha1bytes = forge$b.util.createBuffer();
  18374. ai.clear();
  18375. ai.putBytes(seed);
  18376. for(var i = 0; i < sha1itr; ++i) {
  18377. // HMAC_hash(secret, A(i-1))
  18378. hmac.start(null, null);
  18379. hmac.update(ai.getBytes());
  18380. ai.putBuffer(hmac.digest());
  18381. // HMAC_hash(secret, A(i) + seed)
  18382. hmac.start(null, null);
  18383. hmac.update(ai.bytes() + seed);
  18384. sha1bytes.putBuffer(hmac.digest());
  18385. }
  18386. // XOR the md5 bytes with the sha1 bytes
  18387. rval.putBytes(forge$b.util.xorBytes(
  18388. md5bytes.getBytes(), sha1bytes.getBytes(), length));
  18389. return rval;
  18390. };
  18391. /**
  18392. * Gets a MAC for a record using the SHA-1 hash algorithm.
  18393. *
  18394. * @param key the mac key.
  18395. * @param state the sequence number (array of two 32-bit integers).
  18396. * @param record the record.
  18397. *
  18398. * @return the sha-1 hash (20 bytes) for the given record.
  18399. */
  18400. var hmac_sha1 = function(key, seqNum, record) {
  18401. /* MAC is computed like so:
  18402. HMAC_hash(
  18403. key, seqNum +
  18404. TLSCompressed.type +
  18405. TLSCompressed.version +
  18406. TLSCompressed.length +
  18407. TLSCompressed.fragment)
  18408. */
  18409. var hmac = forge$b.hmac.create();
  18410. hmac.start('SHA1', key);
  18411. var b = forge$b.util.createBuffer();
  18412. b.putInt32(seqNum[0]);
  18413. b.putInt32(seqNum[1]);
  18414. b.putByte(record.type);
  18415. b.putByte(record.version.major);
  18416. b.putByte(record.version.minor);
  18417. b.putInt16(record.length);
  18418. b.putBytes(record.fragment.bytes());
  18419. hmac.update(b.getBytes());
  18420. return hmac.digest().getBytes();
  18421. };
  18422. /**
  18423. * Compresses the TLSPlaintext record into a TLSCompressed record using the
  18424. * deflate algorithm.
  18425. *
  18426. * @param c the TLS connection.
  18427. * @param record the TLSPlaintext record to compress.
  18428. * @param s the ConnectionState to use.
  18429. *
  18430. * @return true on success, false on failure.
  18431. */
  18432. var deflate = function(c, record, s) {
  18433. var rval = false;
  18434. try {
  18435. var bytes = c.deflate(record.fragment.getBytes());
  18436. record.fragment = forge$b.util.createBuffer(bytes);
  18437. record.length = bytes.length;
  18438. rval = true;
  18439. } catch(ex) {
  18440. // deflate error, fail out
  18441. }
  18442. return rval;
  18443. };
  18444. /**
  18445. * Decompresses the TLSCompressed record into a TLSPlaintext record using the
  18446. * deflate algorithm.
  18447. *
  18448. * @param c the TLS connection.
  18449. * @param record the TLSCompressed record to decompress.
  18450. * @param s the ConnectionState to use.
  18451. *
  18452. * @return true on success, false on failure.
  18453. */
  18454. var inflate = function(c, record, s) {
  18455. var rval = false;
  18456. try {
  18457. var bytes = c.inflate(record.fragment.getBytes());
  18458. record.fragment = forge$b.util.createBuffer(bytes);
  18459. record.length = bytes.length;
  18460. rval = true;
  18461. } catch(ex) {
  18462. // inflate error, fail out
  18463. }
  18464. return rval;
  18465. };
  18466. /**
  18467. * Reads a TLS variable-length vector from a byte buffer.
  18468. *
  18469. * Variable-length vectors are defined by specifying a subrange of legal
  18470. * lengths, inclusively, using the notation <floor..ceiling>. When these are
  18471. * encoded, the actual length precedes the vector's contents in the byte
  18472. * stream. The length will be in the form of a number consuming as many bytes
  18473. * as required to hold the vector's specified maximum (ceiling) length. A
  18474. * variable-length vector with an actual length field of zero is referred to
  18475. * as an empty vector.
  18476. *
  18477. * @param b the byte buffer.
  18478. * @param lenBytes the number of bytes required to store the length.
  18479. *
  18480. * @return the resulting byte buffer.
  18481. */
  18482. var readVector = function(b, lenBytes) {
  18483. var len = 0;
  18484. switch(lenBytes) {
  18485. case 1:
  18486. len = b.getByte();
  18487. break;
  18488. case 2:
  18489. len = b.getInt16();
  18490. break;
  18491. case 3:
  18492. len = b.getInt24();
  18493. break;
  18494. case 4:
  18495. len = b.getInt32();
  18496. break;
  18497. }
  18498. // read vector bytes into a new buffer
  18499. return forge$b.util.createBuffer(b.getBytes(len));
  18500. };
  18501. /**
  18502. * Writes a TLS variable-length vector to a byte buffer.
  18503. *
  18504. * @param b the byte buffer.
  18505. * @param lenBytes the number of bytes required to store the length.
  18506. * @param v the byte buffer vector.
  18507. */
  18508. var writeVector = function(b, lenBytes, v) {
  18509. // encode length at the start of the vector, where the number of bytes for
  18510. // the length is the maximum number of bytes it would take to encode the
  18511. // vector's ceiling
  18512. b.putInt(v.length(), lenBytes << 3);
  18513. b.putBuffer(v);
  18514. };
  18515. /**
  18516. * The tls implementation.
  18517. */
  18518. var tls$1 = {};
  18519. /**
  18520. * Version: TLS 1.2 = 3.3, TLS 1.1 = 3.2, TLS 1.0 = 3.1. Both TLS 1.1 and
  18521. * TLS 1.2 were still too new (ie: openSSL didn't implement them) at the time
  18522. * of this implementation so TLS 1.0 was implemented instead.
  18523. */
  18524. tls$1.Versions = {
  18525. TLS_1_0: {major: 3, minor: 1},
  18526. TLS_1_1: {major: 3, minor: 2},
  18527. TLS_1_2: {major: 3, minor: 3}
  18528. };
  18529. tls$1.SupportedVersions = [
  18530. tls$1.Versions.TLS_1_1,
  18531. tls$1.Versions.TLS_1_0
  18532. ];
  18533. tls$1.Version = tls$1.SupportedVersions[0];
  18534. /**
  18535. * Maximum fragment size. True maximum is 16384, but we fragment before that
  18536. * to allow for unusual small increases during compression.
  18537. */
  18538. tls$1.MaxFragment = 16384 - 1024;
  18539. /**
  18540. * Whether this entity is considered the "client" or "server".
  18541. * enum { server, client } ConnectionEnd;
  18542. */
  18543. tls$1.ConnectionEnd = {
  18544. server: 0,
  18545. client: 1
  18546. };
  18547. /**
  18548. * Pseudo-random function algorithm used to generate keys from the master
  18549. * secret.
  18550. * enum { tls_prf_sha256 } PRFAlgorithm;
  18551. */
  18552. tls$1.PRFAlgorithm = {
  18553. tls_prf_sha256: 0
  18554. };
  18555. /**
  18556. * Bulk encryption algorithms.
  18557. * enum { null, rc4, des3, aes } BulkCipherAlgorithm;
  18558. */
  18559. tls$1.BulkCipherAlgorithm = {
  18560. none: null,
  18561. rc4: 0,
  18562. des3: 1,
  18563. aes: 2
  18564. };
  18565. /**
  18566. * Cipher types.
  18567. * enum { stream, block, aead } CipherType;
  18568. */
  18569. tls$1.CipherType = {
  18570. stream: 0,
  18571. block: 1,
  18572. aead: 2
  18573. };
  18574. /**
  18575. * MAC (Message Authentication Code) algorithms.
  18576. * enum { null, hmac_md5, hmac_sha1, hmac_sha256,
  18577. * hmac_sha384, hmac_sha512} MACAlgorithm;
  18578. */
  18579. tls$1.MACAlgorithm = {
  18580. none: null,
  18581. hmac_md5: 0,
  18582. hmac_sha1: 1,
  18583. hmac_sha256: 2,
  18584. hmac_sha384: 3,
  18585. hmac_sha512: 4
  18586. };
  18587. /**
  18588. * Compression algorithms.
  18589. * enum { null(0), deflate(1), (255) } CompressionMethod;
  18590. */
  18591. tls$1.CompressionMethod = {
  18592. none: 0,
  18593. deflate: 1
  18594. };
  18595. /**
  18596. * TLS record content types.
  18597. * enum {
  18598. * change_cipher_spec(20), alert(21), handshake(22),
  18599. * application_data(23), (255)
  18600. * } ContentType;
  18601. */
  18602. tls$1.ContentType = {
  18603. change_cipher_spec: 20,
  18604. alert: 21,
  18605. handshake: 22,
  18606. application_data: 23,
  18607. heartbeat: 24
  18608. };
  18609. /**
  18610. * TLS handshake types.
  18611. * enum {
  18612. * hello_request(0), client_hello(1), server_hello(2),
  18613. * certificate(11), server_key_exchange (12),
  18614. * certificate_request(13), server_hello_done(14),
  18615. * certificate_verify(15), client_key_exchange(16),
  18616. * finished(20), (255)
  18617. * } HandshakeType;
  18618. */
  18619. tls$1.HandshakeType = {
  18620. hello_request: 0,
  18621. client_hello: 1,
  18622. server_hello: 2,
  18623. certificate: 11,
  18624. server_key_exchange: 12,
  18625. certificate_request: 13,
  18626. server_hello_done: 14,
  18627. certificate_verify: 15,
  18628. client_key_exchange: 16,
  18629. finished: 20
  18630. };
  18631. /**
  18632. * TLS Alert Protocol.
  18633. *
  18634. * enum { warning(1), fatal(2), (255) } AlertLevel;
  18635. *
  18636. * enum {
  18637. * close_notify(0),
  18638. * unexpected_message(10),
  18639. * bad_record_mac(20),
  18640. * decryption_failed(21),
  18641. * record_overflow(22),
  18642. * decompression_failure(30),
  18643. * handshake_failure(40),
  18644. * bad_certificate(42),
  18645. * unsupported_certificate(43),
  18646. * certificate_revoked(44),
  18647. * certificate_expired(45),
  18648. * certificate_unknown(46),
  18649. * illegal_parameter(47),
  18650. * unknown_ca(48),
  18651. * access_denied(49),
  18652. * decode_error(50),
  18653. * decrypt_error(51),
  18654. * export_restriction(60),
  18655. * protocol_version(70),
  18656. * insufficient_security(71),
  18657. * internal_error(80),
  18658. * user_canceled(90),
  18659. * no_renegotiation(100),
  18660. * (255)
  18661. * } AlertDescription;
  18662. *
  18663. * struct {
  18664. * AlertLevel level;
  18665. * AlertDescription description;
  18666. * } Alert;
  18667. */
  18668. tls$1.Alert = {};
  18669. tls$1.Alert.Level = {
  18670. warning: 1,
  18671. fatal: 2
  18672. };
  18673. tls$1.Alert.Description = {
  18674. close_notify: 0,
  18675. unexpected_message: 10,
  18676. bad_record_mac: 20,
  18677. decryption_failed: 21,
  18678. record_overflow: 22,
  18679. decompression_failure: 30,
  18680. handshake_failure: 40,
  18681. bad_certificate: 42,
  18682. unsupported_certificate: 43,
  18683. certificate_revoked: 44,
  18684. certificate_expired: 45,
  18685. certificate_unknown: 46,
  18686. illegal_parameter: 47,
  18687. unknown_ca: 48,
  18688. access_denied: 49,
  18689. decode_error: 50,
  18690. decrypt_error: 51,
  18691. export_restriction: 60,
  18692. protocol_version: 70,
  18693. insufficient_security: 71,
  18694. internal_error: 80,
  18695. user_canceled: 90,
  18696. no_renegotiation: 100
  18697. };
  18698. /**
  18699. * TLS Heartbeat Message types.
  18700. * enum {
  18701. * heartbeat_request(1),
  18702. * heartbeat_response(2),
  18703. * (255)
  18704. * } HeartbeatMessageType;
  18705. */
  18706. tls$1.HeartbeatMessageType = {
  18707. heartbeat_request: 1,
  18708. heartbeat_response: 2
  18709. };
  18710. /**
  18711. * Supported cipher suites.
  18712. */
  18713. tls$1.CipherSuites = {};
  18714. /**
  18715. * Gets a supported cipher suite from its 2 byte ID.
  18716. *
  18717. * @param twoBytes two bytes in a string.
  18718. *
  18719. * @return the matching supported cipher suite or null.
  18720. */
  18721. tls$1.getCipherSuite = function(twoBytes) {
  18722. var rval = null;
  18723. for(var key in tls$1.CipherSuites) {
  18724. var cs = tls$1.CipherSuites[key];
  18725. if(cs.id[0] === twoBytes.charCodeAt(0) &&
  18726. cs.id[1] === twoBytes.charCodeAt(1)) {
  18727. rval = cs;
  18728. break;
  18729. }
  18730. }
  18731. return rval;
  18732. };
  18733. /**
  18734. * Called when an unexpected record is encountered.
  18735. *
  18736. * @param c the connection.
  18737. * @param record the record.
  18738. */
  18739. tls$1.handleUnexpected = function(c, record) {
  18740. // if connection is client and closed, ignore unexpected messages
  18741. var ignore = (!c.open && c.entity === tls$1.ConnectionEnd.client);
  18742. if(!ignore) {
  18743. c.error(c, {
  18744. message: 'Unexpected message. Received TLS record out of order.',
  18745. send: true,
  18746. alert: {
  18747. level: tls$1.Alert.Level.fatal,
  18748. description: tls$1.Alert.Description.unexpected_message
  18749. }
  18750. });
  18751. }
  18752. };
  18753. /**
  18754. * Called when a client receives a HelloRequest record.
  18755. *
  18756. * @param c the connection.
  18757. * @param record the record.
  18758. * @param length the length of the handshake message.
  18759. */
  18760. tls$1.handleHelloRequest = function(c, record, length) {
  18761. // ignore renegotiation requests from the server during a handshake, but
  18762. // if handshaking, send a warning alert that renegotation is denied
  18763. if(!c.handshaking && c.handshakes > 0) {
  18764. // send alert warning
  18765. tls$1.queue(c, tls$1.createAlert(c, {
  18766. level: tls$1.Alert.Level.warning,
  18767. description: tls$1.Alert.Description.no_renegotiation
  18768. }));
  18769. tls$1.flush(c);
  18770. }
  18771. // continue
  18772. c.process();
  18773. };
  18774. /**
  18775. * Parses a hello message from a ClientHello or ServerHello record.
  18776. *
  18777. * @param record the record to parse.
  18778. *
  18779. * @return the parsed message.
  18780. */
  18781. tls$1.parseHelloMessage = function(c, record, length) {
  18782. var msg = null;
  18783. var client = (c.entity === tls$1.ConnectionEnd.client);
  18784. // minimum of 38 bytes in message
  18785. if(length < 38) {
  18786. c.error(c, {
  18787. message: client ?
  18788. 'Invalid ServerHello message. Message too short.' :
  18789. 'Invalid ClientHello message. Message too short.',
  18790. send: true,
  18791. alert: {
  18792. level: tls$1.Alert.Level.fatal,
  18793. description: tls$1.Alert.Description.illegal_parameter
  18794. }
  18795. });
  18796. } else {
  18797. // use 'remaining' to calculate # of remaining bytes in the message
  18798. var b = record.fragment;
  18799. var remaining = b.length();
  18800. msg = {
  18801. version: {
  18802. major: b.getByte(),
  18803. minor: b.getByte()
  18804. },
  18805. random: forge$b.util.createBuffer(b.getBytes(32)),
  18806. session_id: readVector(b, 1),
  18807. extensions: []
  18808. };
  18809. if(client) {
  18810. msg.cipher_suite = b.getBytes(2);
  18811. msg.compression_method = b.getByte();
  18812. } else {
  18813. msg.cipher_suites = readVector(b, 2);
  18814. msg.compression_methods = readVector(b, 1);
  18815. }
  18816. // read extensions if there are any bytes left in the message
  18817. remaining = length - (remaining - b.length());
  18818. if(remaining > 0) {
  18819. // parse extensions
  18820. var exts = readVector(b, 2);
  18821. while(exts.length() > 0) {
  18822. msg.extensions.push({
  18823. type: [exts.getByte(), exts.getByte()],
  18824. data: readVector(exts, 2)
  18825. });
  18826. }
  18827. // TODO: make extension support modular
  18828. if(!client) {
  18829. for(var i = 0; i < msg.extensions.length; ++i) {
  18830. var ext = msg.extensions[i];
  18831. // support SNI extension
  18832. if(ext.type[0] === 0x00 && ext.type[1] === 0x00) {
  18833. // get server name list
  18834. var snl = readVector(ext.data, 2);
  18835. while(snl.length() > 0) {
  18836. // read server name type
  18837. var snType = snl.getByte();
  18838. // only HostName type (0x00) is known, break out if
  18839. // another type is detected
  18840. if(snType !== 0x00) {
  18841. break;
  18842. }
  18843. // add host name to server name list
  18844. c.session.extensions.server_name.serverNameList.push(
  18845. readVector(snl, 2).getBytes());
  18846. }
  18847. }
  18848. }
  18849. }
  18850. }
  18851. // version already set, do not allow version change
  18852. if(c.session.version) {
  18853. if(msg.version.major !== c.session.version.major ||
  18854. msg.version.minor !== c.session.version.minor) {
  18855. return c.error(c, {
  18856. message: 'TLS version change is disallowed during renegotiation.',
  18857. send: true,
  18858. alert: {
  18859. level: tls$1.Alert.Level.fatal,
  18860. description: tls$1.Alert.Description.protocol_version
  18861. }
  18862. });
  18863. }
  18864. }
  18865. // get the chosen (ServerHello) cipher suite
  18866. if(client) {
  18867. // FIXME: should be checking configured acceptable cipher suites
  18868. c.session.cipherSuite = tls$1.getCipherSuite(msg.cipher_suite);
  18869. } else {
  18870. // get a supported preferred (ClientHello) cipher suite
  18871. // choose the first supported cipher suite
  18872. var tmp = forge$b.util.createBuffer(msg.cipher_suites.bytes());
  18873. while(tmp.length() > 0) {
  18874. // FIXME: should be checking configured acceptable suites
  18875. // cipher suites take up 2 bytes
  18876. c.session.cipherSuite = tls$1.getCipherSuite(tmp.getBytes(2));
  18877. if(c.session.cipherSuite !== null) {
  18878. break;
  18879. }
  18880. }
  18881. }
  18882. // cipher suite not supported
  18883. if(c.session.cipherSuite === null) {
  18884. return c.error(c, {
  18885. message: 'No cipher suites in common.',
  18886. send: true,
  18887. alert: {
  18888. level: tls$1.Alert.Level.fatal,
  18889. description: tls$1.Alert.Description.handshake_failure
  18890. },
  18891. cipherSuite: forge$b.util.bytesToHex(msg.cipher_suite)
  18892. });
  18893. }
  18894. // TODO: handle compression methods
  18895. if(client) {
  18896. c.session.compressionMethod = msg.compression_method;
  18897. } else {
  18898. // no compression
  18899. c.session.compressionMethod = tls$1.CompressionMethod.none;
  18900. }
  18901. }
  18902. return msg;
  18903. };
  18904. /**
  18905. * Creates security parameters for the given connection based on the given
  18906. * hello message.
  18907. *
  18908. * @param c the TLS connection.
  18909. * @param msg the hello message.
  18910. */
  18911. tls$1.createSecurityParameters = function(c, msg) {
  18912. /* Note: security params are from TLS 1.2, some values like prf_algorithm
  18913. are ignored for TLS 1.0/1.1 and the builtin as specified in the spec is
  18914. used. */
  18915. // TODO: handle other options from server when more supported
  18916. // get client and server randoms
  18917. var client = (c.entity === tls$1.ConnectionEnd.client);
  18918. var msgRandom = msg.random.bytes();
  18919. var cRandom = client ? c.session.sp.client_random : msgRandom;
  18920. var sRandom = client ? msgRandom : tls$1.createRandom().getBytes();
  18921. // create new security parameters
  18922. c.session.sp = {
  18923. entity: c.entity,
  18924. prf_algorithm: tls$1.PRFAlgorithm.tls_prf_sha256,
  18925. bulk_cipher_algorithm: null,
  18926. cipher_type: null,
  18927. enc_key_length: null,
  18928. block_length: null,
  18929. fixed_iv_length: null,
  18930. record_iv_length: null,
  18931. mac_algorithm: null,
  18932. mac_length: null,
  18933. mac_key_length: null,
  18934. compression_algorithm: c.session.compressionMethod,
  18935. pre_master_secret: null,
  18936. master_secret: null,
  18937. client_random: cRandom,
  18938. server_random: sRandom
  18939. };
  18940. };
  18941. /**
  18942. * Called when a client receives a ServerHello record.
  18943. *
  18944. * When a ServerHello message will be sent:
  18945. * The server will send this message in response to a client hello message
  18946. * when it was able to find an acceptable set of algorithms. If it cannot
  18947. * find such a match, it will respond with a handshake failure alert.
  18948. *
  18949. * uint24 length;
  18950. * struct {
  18951. * ProtocolVersion server_version;
  18952. * Random random;
  18953. * SessionID session_id;
  18954. * CipherSuite cipher_suite;
  18955. * CompressionMethod compression_method;
  18956. * select(extensions_present) {
  18957. * case false:
  18958. * struct {};
  18959. * case true:
  18960. * Extension extensions<0..2^16-1>;
  18961. * };
  18962. * } ServerHello;
  18963. *
  18964. * @param c the connection.
  18965. * @param record the record.
  18966. * @param length the length of the handshake message.
  18967. */
  18968. tls$1.handleServerHello = function(c, record, length) {
  18969. var msg = tls$1.parseHelloMessage(c, record, length);
  18970. if(c.fail) {
  18971. return;
  18972. }
  18973. // ensure server version is compatible
  18974. if(msg.version.minor <= c.version.minor) {
  18975. c.version.minor = msg.version.minor;
  18976. } else {
  18977. return c.error(c, {
  18978. message: 'Incompatible TLS version.',
  18979. send: true,
  18980. alert: {
  18981. level: tls$1.Alert.Level.fatal,
  18982. description: tls$1.Alert.Description.protocol_version
  18983. }
  18984. });
  18985. }
  18986. // indicate session version has been set
  18987. c.session.version = c.version;
  18988. // get the session ID from the message
  18989. var sessionId = msg.session_id.bytes();
  18990. // if the session ID is not blank and matches the cached one, resume
  18991. // the session
  18992. if(sessionId.length > 0 && sessionId === c.session.id) {
  18993. // resuming session, expect a ChangeCipherSpec next
  18994. c.expect = SCC;
  18995. c.session.resuming = true;
  18996. // get new server random
  18997. c.session.sp.server_random = msg.random.bytes();
  18998. } else {
  18999. // not resuming, expect a server Certificate message next
  19000. c.expect = SCE;
  19001. c.session.resuming = false;
  19002. // create new security parameters
  19003. tls$1.createSecurityParameters(c, msg);
  19004. }
  19005. // set new session ID
  19006. c.session.id = sessionId;
  19007. // continue
  19008. c.process();
  19009. };
  19010. /**
  19011. * Called when a server receives a ClientHello record.
  19012. *
  19013. * When a ClientHello message will be sent:
  19014. * When a client first connects to a server it is required to send the
  19015. * client hello as its first message. The client can also send a client
  19016. * hello in response to a hello request or on its own initiative in order
  19017. * to renegotiate the security parameters in an existing connection.
  19018. *
  19019. * @param c the connection.
  19020. * @param record the record.
  19021. * @param length the length of the handshake message.
  19022. */
  19023. tls$1.handleClientHello = function(c, record, length) {
  19024. var msg = tls$1.parseHelloMessage(c, record, length);
  19025. if(c.fail) {
  19026. return;
  19027. }
  19028. // get the session ID from the message
  19029. var sessionId = msg.session_id.bytes();
  19030. // see if the given session ID is in the cache
  19031. var session = null;
  19032. if(c.sessionCache) {
  19033. session = c.sessionCache.getSession(sessionId);
  19034. if(session === null) {
  19035. // session ID not found
  19036. sessionId = '';
  19037. } else if(session.version.major !== msg.version.major ||
  19038. session.version.minor > msg.version.minor) {
  19039. // if session version is incompatible with client version, do not resume
  19040. session = null;
  19041. sessionId = '';
  19042. }
  19043. }
  19044. // no session found to resume, generate a new session ID
  19045. if(sessionId.length === 0) {
  19046. sessionId = forge$b.random.getBytes(32);
  19047. }
  19048. // update session
  19049. c.session.id = sessionId;
  19050. c.session.clientHelloVersion = msg.version;
  19051. c.session.sp = {};
  19052. if(session) {
  19053. // use version and security parameters from resumed session
  19054. c.version = c.session.version = session.version;
  19055. c.session.sp = session.sp;
  19056. } else {
  19057. // use highest compatible minor version
  19058. var version;
  19059. for(var i = 1; i < tls$1.SupportedVersions.length; ++i) {
  19060. version = tls$1.SupportedVersions[i];
  19061. if(version.minor <= msg.version.minor) {
  19062. break;
  19063. }
  19064. }
  19065. c.version = {major: version.major, minor: version.minor};
  19066. c.session.version = c.version;
  19067. }
  19068. // if a session is set, resume it
  19069. if(session !== null) {
  19070. // resuming session, expect a ChangeCipherSpec next
  19071. c.expect = CCC;
  19072. c.session.resuming = true;
  19073. // get new client random
  19074. c.session.sp.client_random = msg.random.bytes();
  19075. } else {
  19076. // not resuming, expect a Certificate or ClientKeyExchange
  19077. c.expect = (c.verifyClient !== false) ? CCE : CKE;
  19078. c.session.resuming = false;
  19079. // create new security parameters
  19080. tls$1.createSecurityParameters(c, msg);
  19081. }
  19082. // connection now open
  19083. c.open = true;
  19084. // queue server hello
  19085. tls$1.queue(c, tls$1.createRecord(c, {
  19086. type: tls$1.ContentType.handshake,
  19087. data: tls$1.createServerHello(c)
  19088. }));
  19089. if(c.session.resuming) {
  19090. // queue change cipher spec message
  19091. tls$1.queue(c, tls$1.createRecord(c, {
  19092. type: tls$1.ContentType.change_cipher_spec,
  19093. data: tls$1.createChangeCipherSpec()
  19094. }));
  19095. // create pending state
  19096. c.state.pending = tls$1.createConnectionState(c);
  19097. // change current write state to pending write state
  19098. c.state.current.write = c.state.pending.write;
  19099. // queue finished
  19100. tls$1.queue(c, tls$1.createRecord(c, {
  19101. type: tls$1.ContentType.handshake,
  19102. data: tls$1.createFinished(c)
  19103. }));
  19104. } else {
  19105. // queue server certificate
  19106. tls$1.queue(c, tls$1.createRecord(c, {
  19107. type: tls$1.ContentType.handshake,
  19108. data: tls$1.createCertificate(c)
  19109. }));
  19110. if(!c.fail) {
  19111. // queue server key exchange
  19112. tls$1.queue(c, tls$1.createRecord(c, {
  19113. type: tls$1.ContentType.handshake,
  19114. data: tls$1.createServerKeyExchange(c)
  19115. }));
  19116. // request client certificate if set
  19117. if(c.verifyClient !== false) {
  19118. // queue certificate request
  19119. tls$1.queue(c, tls$1.createRecord(c, {
  19120. type: tls$1.ContentType.handshake,
  19121. data: tls$1.createCertificateRequest(c)
  19122. }));
  19123. }
  19124. // queue server hello done
  19125. tls$1.queue(c, tls$1.createRecord(c, {
  19126. type: tls$1.ContentType.handshake,
  19127. data: tls$1.createServerHelloDone(c)
  19128. }));
  19129. }
  19130. }
  19131. // send records
  19132. tls$1.flush(c);
  19133. // continue
  19134. c.process();
  19135. };
  19136. /**
  19137. * Called when a client receives a Certificate record.
  19138. *
  19139. * When this message will be sent:
  19140. * The server must send a certificate whenever the agreed-upon key exchange
  19141. * method is not an anonymous one. This message will always immediately
  19142. * follow the server hello message.
  19143. *
  19144. * Meaning of this message:
  19145. * The certificate type must be appropriate for the selected cipher suite's
  19146. * key exchange algorithm, and is generally an X.509v3 certificate. It must
  19147. * contain a key which matches the key exchange method, as follows. Unless
  19148. * otherwise specified, the signing algorithm for the certificate must be
  19149. * the same as the algorithm for the certificate key. Unless otherwise
  19150. * specified, the public key may be of any length.
  19151. *
  19152. * opaque ASN.1Cert<1..2^24-1>;
  19153. * struct {
  19154. * ASN.1Cert certificate_list<1..2^24-1>;
  19155. * } Certificate;
  19156. *
  19157. * @param c the connection.
  19158. * @param record the record.
  19159. * @param length the length of the handshake message.
  19160. */
  19161. tls$1.handleCertificate = function(c, record, length) {
  19162. // minimum of 3 bytes in message
  19163. if(length < 3) {
  19164. return c.error(c, {
  19165. message: 'Invalid Certificate message. Message too short.',
  19166. send: true,
  19167. alert: {
  19168. level: tls$1.Alert.Level.fatal,
  19169. description: tls$1.Alert.Description.illegal_parameter
  19170. }
  19171. });
  19172. }
  19173. var b = record.fragment;
  19174. var msg = {
  19175. certificate_list: readVector(b, 3)
  19176. };
  19177. /* The sender's certificate will be first in the list (chain), each
  19178. subsequent one that follows will certify the previous one, but root
  19179. certificates (self-signed) that specify the certificate authority may
  19180. be omitted under the assumption that clients must already possess it. */
  19181. var cert, asn1;
  19182. var certs = [];
  19183. try {
  19184. while(msg.certificate_list.length() > 0) {
  19185. // each entry in msg.certificate_list is a vector with 3 len bytes
  19186. cert = readVector(msg.certificate_list, 3);
  19187. asn1 = forge$b.asn1.fromDer(cert);
  19188. cert = forge$b.pki.certificateFromAsn1(asn1, true);
  19189. certs.push(cert);
  19190. }
  19191. } catch(ex) {
  19192. return c.error(c, {
  19193. message: 'Could not parse certificate list.',
  19194. cause: ex,
  19195. send: true,
  19196. alert: {
  19197. level: tls$1.Alert.Level.fatal,
  19198. description: tls$1.Alert.Description.bad_certificate
  19199. }
  19200. });
  19201. }
  19202. // ensure at least 1 certificate was provided if in client-mode
  19203. // or if verifyClient was set to true to require a certificate
  19204. // (as opposed to 'optional')
  19205. var client = (c.entity === tls$1.ConnectionEnd.client);
  19206. if((client || c.verifyClient === true) && certs.length === 0) {
  19207. // error, no certificate
  19208. c.error(c, {
  19209. message: client ?
  19210. 'No server certificate provided.' :
  19211. 'No client certificate provided.',
  19212. send: true,
  19213. alert: {
  19214. level: tls$1.Alert.Level.fatal,
  19215. description: tls$1.Alert.Description.illegal_parameter
  19216. }
  19217. });
  19218. } else if(certs.length === 0) {
  19219. // no certs to verify
  19220. // expect a ServerKeyExchange or ClientKeyExchange message next
  19221. c.expect = client ? SKE : CKE;
  19222. } else {
  19223. // save certificate in session
  19224. if(client) {
  19225. c.session.serverCertificate = certs[0];
  19226. } else {
  19227. c.session.clientCertificate = certs[0];
  19228. }
  19229. if(tls$1.verifyCertificateChain(c, certs)) {
  19230. // expect a ServerKeyExchange or ClientKeyExchange message next
  19231. c.expect = client ? SKE : CKE;
  19232. }
  19233. }
  19234. // continue
  19235. c.process();
  19236. };
  19237. /**
  19238. * Called when a client receives a ServerKeyExchange record.
  19239. *
  19240. * When this message will be sent:
  19241. * This message will be sent immediately after the server certificate
  19242. * message (or the server hello message, if this is an anonymous
  19243. * negotiation).
  19244. *
  19245. * The server key exchange message is sent by the server only when the
  19246. * server certificate message (if sent) does not contain enough data to
  19247. * allow the client to exchange a premaster secret.
  19248. *
  19249. * Meaning of this message:
  19250. * This message conveys cryptographic information to allow the client to
  19251. * communicate the premaster secret: either an RSA public key to encrypt
  19252. * the premaster secret with, or a Diffie-Hellman public key with which the
  19253. * client can complete a key exchange (with the result being the premaster
  19254. * secret.)
  19255. *
  19256. * enum {
  19257. * dhe_dss, dhe_rsa, dh_anon, rsa, dh_dss, dh_rsa
  19258. * } KeyExchangeAlgorithm;
  19259. *
  19260. * struct {
  19261. * opaque dh_p<1..2^16-1>;
  19262. * opaque dh_g<1..2^16-1>;
  19263. * opaque dh_Ys<1..2^16-1>;
  19264. * } ServerDHParams;
  19265. *
  19266. * struct {
  19267. * select(KeyExchangeAlgorithm) {
  19268. * case dh_anon:
  19269. * ServerDHParams params;
  19270. * case dhe_dss:
  19271. * case dhe_rsa:
  19272. * ServerDHParams params;
  19273. * digitally-signed struct {
  19274. * opaque client_random[32];
  19275. * opaque server_random[32];
  19276. * ServerDHParams params;
  19277. * } signed_params;
  19278. * case rsa:
  19279. * case dh_dss:
  19280. * case dh_rsa:
  19281. * struct {};
  19282. * };
  19283. * } ServerKeyExchange;
  19284. *
  19285. * @param c the connection.
  19286. * @param record the record.
  19287. * @param length the length of the handshake message.
  19288. */
  19289. tls$1.handleServerKeyExchange = function(c, record, length) {
  19290. // this implementation only supports RSA, no Diffie-Hellman support
  19291. // so any length > 0 is invalid
  19292. if(length > 0) {
  19293. return c.error(c, {
  19294. message: 'Invalid key parameters. Only RSA is supported.',
  19295. send: true,
  19296. alert: {
  19297. level: tls$1.Alert.Level.fatal,
  19298. description: tls$1.Alert.Description.unsupported_certificate
  19299. }
  19300. });
  19301. }
  19302. // expect an optional CertificateRequest message next
  19303. c.expect = SCR;
  19304. // continue
  19305. c.process();
  19306. };
  19307. /**
  19308. * Called when a client receives a ClientKeyExchange record.
  19309. *
  19310. * @param c the connection.
  19311. * @param record the record.
  19312. * @param length the length of the handshake message.
  19313. */
  19314. tls$1.handleClientKeyExchange = function(c, record, length) {
  19315. // this implementation only supports RSA, no Diffie-Hellman support
  19316. // so any length < 48 is invalid
  19317. if(length < 48) {
  19318. return c.error(c, {
  19319. message: 'Invalid key parameters. Only RSA is supported.',
  19320. send: true,
  19321. alert: {
  19322. level: tls$1.Alert.Level.fatal,
  19323. description: tls$1.Alert.Description.unsupported_certificate
  19324. }
  19325. });
  19326. }
  19327. var b = record.fragment;
  19328. var msg = {
  19329. enc_pre_master_secret: readVector(b, 2).getBytes()
  19330. };
  19331. // do rsa decryption
  19332. var privateKey = null;
  19333. if(c.getPrivateKey) {
  19334. try {
  19335. privateKey = c.getPrivateKey(c, c.session.serverCertificate);
  19336. privateKey = forge$b.pki.privateKeyFromPem(privateKey);
  19337. } catch(ex) {
  19338. c.error(c, {
  19339. message: 'Could not get private key.',
  19340. cause: ex,
  19341. send: true,
  19342. alert: {
  19343. level: tls$1.Alert.Level.fatal,
  19344. description: tls$1.Alert.Description.internal_error
  19345. }
  19346. });
  19347. }
  19348. }
  19349. if(privateKey === null) {
  19350. return c.error(c, {
  19351. message: 'No private key set.',
  19352. send: true,
  19353. alert: {
  19354. level: tls$1.Alert.Level.fatal,
  19355. description: tls$1.Alert.Description.internal_error
  19356. }
  19357. });
  19358. }
  19359. try {
  19360. // decrypt 48-byte pre-master secret
  19361. var sp = c.session.sp;
  19362. sp.pre_master_secret = privateKey.decrypt(msg.enc_pre_master_secret);
  19363. // ensure client hello version matches first 2 bytes
  19364. var version = c.session.clientHelloVersion;
  19365. if(version.major !== sp.pre_master_secret.charCodeAt(0) ||
  19366. version.minor !== sp.pre_master_secret.charCodeAt(1)) {
  19367. // error, do not send alert (see BLEI attack below)
  19368. throw new Error('TLS version rollback attack detected.');
  19369. }
  19370. } catch(ex) {
  19371. /* Note: Daniel Bleichenbacher [BLEI] can be used to attack a
  19372. TLS server which is using PKCS#1 encoded RSA, so instead of
  19373. failing here, we generate 48 random bytes and use that as
  19374. the pre-master secret. */
  19375. sp.pre_master_secret = forge$b.random.getBytes(48);
  19376. }
  19377. // expect a CertificateVerify message if a Certificate was received that
  19378. // does not have fixed Diffie-Hellman params, otherwise expect
  19379. // ChangeCipherSpec
  19380. c.expect = CCC;
  19381. if(c.session.clientCertificate !== null) {
  19382. // only RSA support, so expect CertificateVerify
  19383. // TODO: support Diffie-Hellman
  19384. c.expect = CCV;
  19385. }
  19386. // continue
  19387. c.process();
  19388. };
  19389. /**
  19390. * Called when a client receives a CertificateRequest record.
  19391. *
  19392. * When this message will be sent:
  19393. * A non-anonymous server can optionally request a certificate from the
  19394. * client, if appropriate for the selected cipher suite. This message, if
  19395. * sent, will immediately follow the Server Key Exchange message (if it is
  19396. * sent; otherwise, the Server Certificate message).
  19397. *
  19398. * enum {
  19399. * rsa_sign(1), dss_sign(2), rsa_fixed_dh(3), dss_fixed_dh(4),
  19400. * rsa_ephemeral_dh_RESERVED(5), dss_ephemeral_dh_RESERVED(6),
  19401. * fortezza_dms_RESERVED(20), (255)
  19402. * } ClientCertificateType;
  19403. *
  19404. * opaque DistinguishedName<1..2^16-1>;
  19405. *
  19406. * struct {
  19407. * ClientCertificateType certificate_types<1..2^8-1>;
  19408. * SignatureAndHashAlgorithm supported_signature_algorithms<2^16-1>;
  19409. * DistinguishedName certificate_authorities<0..2^16-1>;
  19410. * } CertificateRequest;
  19411. *
  19412. * @param c the connection.
  19413. * @param record the record.
  19414. * @param length the length of the handshake message.
  19415. */
  19416. tls$1.handleCertificateRequest = function(c, record, length) {
  19417. // minimum of 3 bytes in message
  19418. if(length < 3) {
  19419. return c.error(c, {
  19420. message: 'Invalid CertificateRequest. Message too short.',
  19421. send: true,
  19422. alert: {
  19423. level: tls$1.Alert.Level.fatal,
  19424. description: tls$1.Alert.Description.illegal_parameter
  19425. }
  19426. });
  19427. }
  19428. // TODO: TLS 1.2+ has different format including
  19429. // SignatureAndHashAlgorithm after cert types
  19430. var b = record.fragment;
  19431. var msg = {
  19432. certificate_types: readVector(b, 1),
  19433. certificate_authorities: readVector(b, 2)
  19434. };
  19435. // save certificate request in session
  19436. c.session.certificateRequest = msg;
  19437. // expect a ServerHelloDone message next
  19438. c.expect = SHD;
  19439. // continue
  19440. c.process();
  19441. };
  19442. /**
  19443. * Called when a server receives a CertificateVerify record.
  19444. *
  19445. * @param c the connection.
  19446. * @param record the record.
  19447. * @param length the length of the handshake message.
  19448. */
  19449. tls$1.handleCertificateVerify = function(c, record, length) {
  19450. if(length < 2) {
  19451. return c.error(c, {
  19452. message: 'Invalid CertificateVerify. Message too short.',
  19453. send: true,
  19454. alert: {
  19455. level: tls$1.Alert.Level.fatal,
  19456. description: tls$1.Alert.Description.illegal_parameter
  19457. }
  19458. });
  19459. }
  19460. // rewind to get full bytes for message so it can be manually
  19461. // digested below (special case for CertificateVerify messages because
  19462. // they must be digested *after* handling as opposed to all others)
  19463. var b = record.fragment;
  19464. b.read -= 4;
  19465. var msgBytes = b.bytes();
  19466. b.read += 4;
  19467. var msg = {
  19468. signature: readVector(b, 2).getBytes()
  19469. };
  19470. // TODO: add support for DSA
  19471. // generate data to verify
  19472. var verify = forge$b.util.createBuffer();
  19473. verify.putBuffer(c.session.md5.digest());
  19474. verify.putBuffer(c.session.sha1.digest());
  19475. verify = verify.getBytes();
  19476. try {
  19477. var cert = c.session.clientCertificate;
  19478. /*b = forge.pki.rsa.decrypt(
  19479. msg.signature, cert.publicKey, true, verify.length);
  19480. if(b !== verify) {*/
  19481. if(!cert.publicKey.verify(verify, msg.signature, 'NONE')) {
  19482. throw new Error('CertificateVerify signature does not match.');
  19483. }
  19484. // digest message now that it has been handled
  19485. c.session.md5.update(msgBytes);
  19486. c.session.sha1.update(msgBytes);
  19487. } catch(ex) {
  19488. return c.error(c, {
  19489. message: 'Bad signature in CertificateVerify.',
  19490. send: true,
  19491. alert: {
  19492. level: tls$1.Alert.Level.fatal,
  19493. description: tls$1.Alert.Description.handshake_failure
  19494. }
  19495. });
  19496. }
  19497. // expect ChangeCipherSpec
  19498. c.expect = CCC;
  19499. // continue
  19500. c.process();
  19501. };
  19502. /**
  19503. * Called when a client receives a ServerHelloDone record.
  19504. *
  19505. * When this message will be sent:
  19506. * The server hello done message is sent by the server to indicate the end
  19507. * of the server hello and associated messages. After sending this message
  19508. * the server will wait for a client response.
  19509. *
  19510. * Meaning of this message:
  19511. * This message means that the server is done sending messages to support
  19512. * the key exchange, and the client can proceed with its phase of the key
  19513. * exchange.
  19514. *
  19515. * Upon receipt of the server hello done message the client should verify
  19516. * that the server provided a valid certificate if required and check that
  19517. * the server hello parameters are acceptable.
  19518. *
  19519. * struct {} ServerHelloDone;
  19520. *
  19521. * @param c the connection.
  19522. * @param record the record.
  19523. * @param length the length of the handshake message.
  19524. */
  19525. tls$1.handleServerHelloDone = function(c, record, length) {
  19526. // len must be 0 bytes
  19527. if(length > 0) {
  19528. return c.error(c, {
  19529. message: 'Invalid ServerHelloDone message. Invalid length.',
  19530. send: true,
  19531. alert: {
  19532. level: tls$1.Alert.Level.fatal,
  19533. description: tls$1.Alert.Description.record_overflow
  19534. }
  19535. });
  19536. }
  19537. if(c.serverCertificate === null) {
  19538. // no server certificate was provided
  19539. var error = {
  19540. message: 'No server certificate provided. Not enough security.',
  19541. send: true,
  19542. alert: {
  19543. level: tls$1.Alert.Level.fatal,
  19544. description: tls$1.Alert.Description.insufficient_security
  19545. }
  19546. };
  19547. // call application callback
  19548. var depth = 0;
  19549. var ret = c.verify(c, error.alert.description, depth, []);
  19550. if(ret !== true) {
  19551. // check for custom alert info
  19552. if(ret || ret === 0) {
  19553. // set custom message and alert description
  19554. if(typeof ret === 'object' && !forge$b.util.isArray(ret)) {
  19555. if(ret.message) {
  19556. error.message = ret.message;
  19557. }
  19558. if(ret.alert) {
  19559. error.alert.description = ret.alert;
  19560. }
  19561. } else if(typeof ret === 'number') {
  19562. // set custom alert description
  19563. error.alert.description = ret;
  19564. }
  19565. }
  19566. // send error
  19567. return c.error(c, error);
  19568. }
  19569. }
  19570. // create client certificate message if requested
  19571. if(c.session.certificateRequest !== null) {
  19572. record = tls$1.createRecord(c, {
  19573. type: tls$1.ContentType.handshake,
  19574. data: tls$1.createCertificate(c)
  19575. });
  19576. tls$1.queue(c, record);
  19577. }
  19578. // create client key exchange message
  19579. record = tls$1.createRecord(c, {
  19580. type: tls$1.ContentType.handshake,
  19581. data: tls$1.createClientKeyExchange(c)
  19582. });
  19583. tls$1.queue(c, record);
  19584. // expect no messages until the following callback has been called
  19585. c.expect = SER;
  19586. // create callback to handle client signature (for client-certs)
  19587. var callback = function(c, signature) {
  19588. if(c.session.certificateRequest !== null &&
  19589. c.session.clientCertificate !== null) {
  19590. // create certificate verify message
  19591. tls$1.queue(c, tls$1.createRecord(c, {
  19592. type: tls$1.ContentType.handshake,
  19593. data: tls$1.createCertificateVerify(c, signature)
  19594. }));
  19595. }
  19596. // create change cipher spec message
  19597. tls$1.queue(c, tls$1.createRecord(c, {
  19598. type: tls$1.ContentType.change_cipher_spec,
  19599. data: tls$1.createChangeCipherSpec()
  19600. }));
  19601. // create pending state
  19602. c.state.pending = tls$1.createConnectionState(c);
  19603. // change current write state to pending write state
  19604. c.state.current.write = c.state.pending.write;
  19605. // create finished message
  19606. tls$1.queue(c, tls$1.createRecord(c, {
  19607. type: tls$1.ContentType.handshake,
  19608. data: tls$1.createFinished(c)
  19609. }));
  19610. // expect a server ChangeCipherSpec message next
  19611. c.expect = SCC;
  19612. // send records
  19613. tls$1.flush(c);
  19614. // continue
  19615. c.process();
  19616. };
  19617. // if there is no certificate request or no client certificate, do
  19618. // callback immediately
  19619. if(c.session.certificateRequest === null ||
  19620. c.session.clientCertificate === null) {
  19621. return callback(c, null);
  19622. }
  19623. // otherwise get the client signature
  19624. tls$1.getClientSignature(c, callback);
  19625. };
  19626. /**
  19627. * Called when a ChangeCipherSpec record is received.
  19628. *
  19629. * @param c the connection.
  19630. * @param record the record.
  19631. */
  19632. tls$1.handleChangeCipherSpec = function(c, record) {
  19633. if(record.fragment.getByte() !== 0x01) {
  19634. return c.error(c, {
  19635. message: 'Invalid ChangeCipherSpec message received.',
  19636. send: true,
  19637. alert: {
  19638. level: tls$1.Alert.Level.fatal,
  19639. description: tls$1.Alert.Description.illegal_parameter
  19640. }
  19641. });
  19642. }
  19643. // create pending state if:
  19644. // 1. Resuming session in client mode OR
  19645. // 2. NOT resuming session in server mode
  19646. var client = (c.entity === tls$1.ConnectionEnd.client);
  19647. if((c.session.resuming && client) || (!c.session.resuming && !client)) {
  19648. c.state.pending = tls$1.createConnectionState(c);
  19649. }
  19650. // change current read state to pending read state
  19651. c.state.current.read = c.state.pending.read;
  19652. // clear pending state if:
  19653. // 1. NOT resuming session in client mode OR
  19654. // 2. resuming a session in server mode
  19655. if((!c.session.resuming && client) || (c.session.resuming && !client)) {
  19656. c.state.pending = null;
  19657. }
  19658. // expect a Finished record next
  19659. c.expect = client ? SFI : CFI;
  19660. // continue
  19661. c.process();
  19662. };
  19663. /**
  19664. * Called when a Finished record is received.
  19665. *
  19666. * When this message will be sent:
  19667. * A finished message is always sent immediately after a change
  19668. * cipher spec message to verify that the key exchange and
  19669. * authentication processes were successful. It is essential that a
  19670. * change cipher spec message be received between the other
  19671. * handshake messages and the Finished message.
  19672. *
  19673. * Meaning of this message:
  19674. * The finished message is the first protected with the just-
  19675. * negotiated algorithms, keys, and secrets. Recipients of finished
  19676. * messages must verify that the contents are correct. Once a side
  19677. * has sent its Finished message and received and validated the
  19678. * Finished message from its peer, it may begin to send and receive
  19679. * application data over the connection.
  19680. *
  19681. * struct {
  19682. * opaque verify_data[verify_data_length];
  19683. * } Finished;
  19684. *
  19685. * verify_data
  19686. * PRF(master_secret, finished_label, Hash(handshake_messages))
  19687. * [0..verify_data_length-1];
  19688. *
  19689. * finished_label
  19690. * For Finished messages sent by the client, the string
  19691. * "client finished". For Finished messages sent by the server, the
  19692. * string "server finished".
  19693. *
  19694. * verify_data_length depends on the cipher suite. If it is not specified
  19695. * by the cipher suite, then it is 12. Versions of TLS < 1.2 always used
  19696. * 12 bytes.
  19697. *
  19698. * @param c the connection.
  19699. * @param record the record.
  19700. * @param length the length of the handshake message.
  19701. */
  19702. tls$1.handleFinished = function(c, record, length) {
  19703. // rewind to get full bytes for message so it can be manually
  19704. // digested below (special case for Finished messages because they
  19705. // must be digested *after* handling as opposed to all others)
  19706. var b = record.fragment;
  19707. b.read -= 4;
  19708. var msgBytes = b.bytes();
  19709. b.read += 4;
  19710. // message contains only verify_data
  19711. var vd = record.fragment.getBytes();
  19712. // ensure verify data is correct
  19713. b = forge$b.util.createBuffer();
  19714. b.putBuffer(c.session.md5.digest());
  19715. b.putBuffer(c.session.sha1.digest());
  19716. // set label based on entity type
  19717. var client = (c.entity === tls$1.ConnectionEnd.client);
  19718. var label = client ? 'server finished' : 'client finished';
  19719. // TODO: determine prf function and verify length for TLS 1.2
  19720. var sp = c.session.sp;
  19721. var vdl = 12;
  19722. var prf = prf_TLS1;
  19723. b = prf(sp.master_secret, label, b.getBytes(), vdl);
  19724. if(b.getBytes() !== vd) {
  19725. return c.error(c, {
  19726. message: 'Invalid verify_data in Finished message.',
  19727. send: true,
  19728. alert: {
  19729. level: tls$1.Alert.Level.fatal,
  19730. description: tls$1.Alert.Description.decrypt_error
  19731. }
  19732. });
  19733. }
  19734. // digest finished message now that it has been handled
  19735. c.session.md5.update(msgBytes);
  19736. c.session.sha1.update(msgBytes);
  19737. // resuming session as client or NOT resuming session as server
  19738. if((c.session.resuming && client) || (!c.session.resuming && !client)) {
  19739. // create change cipher spec message
  19740. tls$1.queue(c, tls$1.createRecord(c, {
  19741. type: tls$1.ContentType.change_cipher_spec,
  19742. data: tls$1.createChangeCipherSpec()
  19743. }));
  19744. // change current write state to pending write state, clear pending
  19745. c.state.current.write = c.state.pending.write;
  19746. c.state.pending = null;
  19747. // create finished message
  19748. tls$1.queue(c, tls$1.createRecord(c, {
  19749. type: tls$1.ContentType.handshake,
  19750. data: tls$1.createFinished(c)
  19751. }));
  19752. }
  19753. // expect application data next
  19754. c.expect = client ? SAD : CAD;
  19755. // handshake complete
  19756. c.handshaking = false;
  19757. ++c.handshakes;
  19758. // save access to peer certificate
  19759. c.peerCertificate = client ?
  19760. c.session.serverCertificate : c.session.clientCertificate;
  19761. // send records
  19762. tls$1.flush(c);
  19763. // now connected
  19764. c.isConnected = true;
  19765. c.connected(c);
  19766. // continue
  19767. c.process();
  19768. };
  19769. /**
  19770. * Called when an Alert record is received.
  19771. *
  19772. * @param c the connection.
  19773. * @param record the record.
  19774. */
  19775. tls$1.handleAlert = function(c, record) {
  19776. // read alert
  19777. var b = record.fragment;
  19778. var alert = {
  19779. level: b.getByte(),
  19780. description: b.getByte()
  19781. };
  19782. // TODO: consider using a table?
  19783. // get appropriate message
  19784. var msg;
  19785. switch(alert.description) {
  19786. case tls$1.Alert.Description.close_notify:
  19787. msg = 'Connection closed.';
  19788. break;
  19789. case tls$1.Alert.Description.unexpected_message:
  19790. msg = 'Unexpected message.';
  19791. break;
  19792. case tls$1.Alert.Description.bad_record_mac:
  19793. msg = 'Bad record MAC.';
  19794. break;
  19795. case tls$1.Alert.Description.decryption_failed:
  19796. msg = 'Decryption failed.';
  19797. break;
  19798. case tls$1.Alert.Description.record_overflow:
  19799. msg = 'Record overflow.';
  19800. break;
  19801. case tls$1.Alert.Description.decompression_failure:
  19802. msg = 'Decompression failed.';
  19803. break;
  19804. case tls$1.Alert.Description.handshake_failure:
  19805. msg = 'Handshake failure.';
  19806. break;
  19807. case tls$1.Alert.Description.bad_certificate:
  19808. msg = 'Bad certificate.';
  19809. break;
  19810. case tls$1.Alert.Description.unsupported_certificate:
  19811. msg = 'Unsupported certificate.';
  19812. break;
  19813. case tls$1.Alert.Description.certificate_revoked:
  19814. msg = 'Certificate revoked.';
  19815. break;
  19816. case tls$1.Alert.Description.certificate_expired:
  19817. msg = 'Certificate expired.';
  19818. break;
  19819. case tls$1.Alert.Description.certificate_unknown:
  19820. msg = 'Certificate unknown.';
  19821. break;
  19822. case tls$1.Alert.Description.illegal_parameter:
  19823. msg = 'Illegal parameter.';
  19824. break;
  19825. case tls$1.Alert.Description.unknown_ca:
  19826. msg = 'Unknown certificate authority.';
  19827. break;
  19828. case tls$1.Alert.Description.access_denied:
  19829. msg = 'Access denied.';
  19830. break;
  19831. case tls$1.Alert.Description.decode_error:
  19832. msg = 'Decode error.';
  19833. break;
  19834. case tls$1.Alert.Description.decrypt_error:
  19835. msg = 'Decrypt error.';
  19836. break;
  19837. case tls$1.Alert.Description.export_restriction:
  19838. msg = 'Export restriction.';
  19839. break;
  19840. case tls$1.Alert.Description.protocol_version:
  19841. msg = 'Unsupported protocol version.';
  19842. break;
  19843. case tls$1.Alert.Description.insufficient_security:
  19844. msg = 'Insufficient security.';
  19845. break;
  19846. case tls$1.Alert.Description.internal_error:
  19847. msg = 'Internal error.';
  19848. break;
  19849. case tls$1.Alert.Description.user_canceled:
  19850. msg = 'User canceled.';
  19851. break;
  19852. case tls$1.Alert.Description.no_renegotiation:
  19853. msg = 'Renegotiation not supported.';
  19854. break;
  19855. default:
  19856. msg = 'Unknown error.';
  19857. break;
  19858. }
  19859. // close connection on close_notify, not an error
  19860. if(alert.description === tls$1.Alert.Description.close_notify) {
  19861. return c.close();
  19862. }
  19863. // call error handler
  19864. c.error(c, {
  19865. message: msg,
  19866. send: false,
  19867. // origin is the opposite end
  19868. origin: (c.entity === tls$1.ConnectionEnd.client) ? 'server' : 'client',
  19869. alert: alert
  19870. });
  19871. // continue
  19872. c.process();
  19873. };
  19874. /**
  19875. * Called when a Handshake record is received.
  19876. *
  19877. * @param c the connection.
  19878. * @param record the record.
  19879. */
  19880. tls$1.handleHandshake = function(c, record) {
  19881. // get the handshake type and message length
  19882. var b = record.fragment;
  19883. var type = b.getByte();
  19884. var length = b.getInt24();
  19885. // see if the record fragment doesn't yet contain the full message
  19886. if(length > b.length()) {
  19887. // cache the record, clear its fragment, and reset the buffer read
  19888. // pointer before the type and length were read
  19889. c.fragmented = record;
  19890. record.fragment = forge$b.util.createBuffer();
  19891. b.read -= 4;
  19892. // continue
  19893. return c.process();
  19894. }
  19895. // full message now available, clear cache, reset read pointer to
  19896. // before type and length
  19897. c.fragmented = null;
  19898. b.read -= 4;
  19899. // save the handshake bytes for digestion after handler is found
  19900. // (include type and length of handshake msg)
  19901. var bytes = b.bytes(length + 4);
  19902. // restore read pointer
  19903. b.read += 4;
  19904. // handle expected message
  19905. if(type in hsTable[c.entity][c.expect]) {
  19906. // initialize server session
  19907. if(c.entity === tls$1.ConnectionEnd.server && !c.open && !c.fail) {
  19908. c.handshaking = true;
  19909. c.session = {
  19910. version: null,
  19911. extensions: {
  19912. server_name: {
  19913. serverNameList: []
  19914. }
  19915. },
  19916. cipherSuite: null,
  19917. compressionMethod: null,
  19918. serverCertificate: null,
  19919. clientCertificate: null,
  19920. md5: forge$b.md.md5.create(),
  19921. sha1: forge$b.md.sha1.create()
  19922. };
  19923. }
  19924. /* Update handshake messages digest. Finished and CertificateVerify
  19925. messages are not digested here. They can't be digested as part of
  19926. the verify_data that they contain. These messages are manually
  19927. digested in their handlers. HelloRequest messages are simply never
  19928. included in the handshake message digest according to spec. */
  19929. if(type !== tls$1.HandshakeType.hello_request &&
  19930. type !== tls$1.HandshakeType.certificate_verify &&
  19931. type !== tls$1.HandshakeType.finished) {
  19932. c.session.md5.update(bytes);
  19933. c.session.sha1.update(bytes);
  19934. }
  19935. // handle specific handshake type record
  19936. hsTable[c.entity][c.expect][type](c, record, length);
  19937. } else {
  19938. // unexpected record
  19939. tls$1.handleUnexpected(c, record);
  19940. }
  19941. };
  19942. /**
  19943. * Called when an ApplicationData record is received.
  19944. *
  19945. * @param c the connection.
  19946. * @param record the record.
  19947. */
  19948. tls$1.handleApplicationData = function(c, record) {
  19949. // buffer data, notify that its ready
  19950. c.data.putBuffer(record.fragment);
  19951. c.dataReady(c);
  19952. // continue
  19953. c.process();
  19954. };
  19955. /**
  19956. * Called when a Heartbeat record is received.
  19957. *
  19958. * @param c the connection.
  19959. * @param record the record.
  19960. */
  19961. tls$1.handleHeartbeat = function(c, record) {
  19962. // get the heartbeat type and payload
  19963. var b = record.fragment;
  19964. var type = b.getByte();
  19965. var length = b.getInt16();
  19966. var payload = b.getBytes(length);
  19967. if(type === tls$1.HeartbeatMessageType.heartbeat_request) {
  19968. // discard request during handshake or if length is too large
  19969. if(c.handshaking || length > payload.length) {
  19970. // continue
  19971. return c.process();
  19972. }
  19973. // retransmit payload
  19974. tls$1.queue(c, tls$1.createRecord(c, {
  19975. type: tls$1.ContentType.heartbeat,
  19976. data: tls$1.createHeartbeat(
  19977. tls$1.HeartbeatMessageType.heartbeat_response, payload)
  19978. }));
  19979. tls$1.flush(c);
  19980. } else if(type === tls$1.HeartbeatMessageType.heartbeat_response) {
  19981. // check payload against expected payload, discard heartbeat if no match
  19982. if(payload !== c.expectedHeartbeatPayload) {
  19983. // continue
  19984. return c.process();
  19985. }
  19986. // notify that a valid heartbeat was received
  19987. if(c.heartbeatReceived) {
  19988. c.heartbeatReceived(c, forge$b.util.createBuffer(payload));
  19989. }
  19990. }
  19991. // continue
  19992. c.process();
  19993. };
  19994. /**
  19995. * The transistional state tables for receiving TLS records. It maps the
  19996. * current TLS engine state and a received record to a function to handle the
  19997. * record and update the state.
  19998. *
  19999. * For instance, if the current state is SHE, then the TLS engine is expecting
  20000. * a ServerHello record. Once a record is received, the handler function is
  20001. * looked up using the state SHE and the record's content type.
  20002. *
  20003. * The resulting function will either be an error handler or a record handler.
  20004. * The function will take whatever action is appropriate and update the state
  20005. * for the next record.
  20006. *
  20007. * The states are all based on possible server record types. Note that the
  20008. * client will never specifically expect to receive a HelloRequest or an alert
  20009. * from the server so there is no state that reflects this. These messages may
  20010. * occur at any time.
  20011. *
  20012. * There are two tables for mapping states because there is a second tier of
  20013. * types for handshake messages. Once a record with a content type of handshake
  20014. * is received, the handshake record handler will look up the handshake type in
  20015. * the secondary map to get its appropriate handler.
  20016. *
  20017. * Valid message orders are as follows:
  20018. *
  20019. * =======================FULL HANDSHAKE======================
  20020. * Client Server
  20021. *
  20022. * ClientHello -------->
  20023. * ServerHello
  20024. * Certificate*
  20025. * ServerKeyExchange*
  20026. * CertificateRequest*
  20027. * <-------- ServerHelloDone
  20028. * Certificate*
  20029. * ClientKeyExchange
  20030. * CertificateVerify*
  20031. * [ChangeCipherSpec]
  20032. * Finished -------->
  20033. * [ChangeCipherSpec]
  20034. * <-------- Finished
  20035. * Application Data <-------> Application Data
  20036. *
  20037. * =====================SESSION RESUMPTION=====================
  20038. * Client Server
  20039. *
  20040. * ClientHello -------->
  20041. * ServerHello
  20042. * [ChangeCipherSpec]
  20043. * <-------- Finished
  20044. * [ChangeCipherSpec]
  20045. * Finished -------->
  20046. * Application Data <-------> Application Data
  20047. */
  20048. // client expect states (indicate which records are expected to be received)
  20049. var SHE = 0; // rcv server hello
  20050. var SCE = 1; // rcv server certificate
  20051. var SKE = 2; // rcv server key exchange
  20052. var SCR = 3; // rcv certificate request
  20053. var SHD = 4; // rcv server hello done
  20054. var SCC = 5; // rcv change cipher spec
  20055. var SFI = 6; // rcv finished
  20056. var SAD = 7; // rcv application data
  20057. var SER = 8; // not expecting any messages at this point
  20058. // server expect states
  20059. var CHE = 0; // rcv client hello
  20060. var CCE = 1; // rcv client certificate
  20061. var CKE = 2; // rcv client key exchange
  20062. var CCV = 3; // rcv certificate verify
  20063. var CCC = 4; // rcv change cipher spec
  20064. var CFI = 5; // rcv finished
  20065. var CAD = 6; // rcv application data
  20066. // map client current expect state and content type to function
  20067. var __ = tls$1.handleUnexpected;
  20068. var R0 = tls$1.handleChangeCipherSpec;
  20069. var R1 = tls$1.handleAlert;
  20070. var R2 = tls$1.handleHandshake;
  20071. var R3 = tls$1.handleApplicationData;
  20072. var R4 = tls$1.handleHeartbeat;
  20073. var ctTable = [];
  20074. ctTable[tls$1.ConnectionEnd.client] = [
  20075. // CC,AL,HS,AD,HB
  20076. /*SHE*/[__,R1,R2,__,R4],
  20077. /*SCE*/[__,R1,R2,__,R4],
  20078. /*SKE*/[__,R1,R2,__,R4],
  20079. /*SCR*/[__,R1,R2,__,R4],
  20080. /*SHD*/[__,R1,R2,__,R4],
  20081. /*SCC*/[R0,R1,__,__,R4],
  20082. /*SFI*/[__,R1,R2,__,R4],
  20083. /*SAD*/[__,R1,R2,R3,R4],
  20084. /*SER*/[__,R1,R2,__,R4]
  20085. ];
  20086. // map server current expect state and content type to function
  20087. ctTable[tls$1.ConnectionEnd.server] = [
  20088. // CC,AL,HS,AD
  20089. /*CHE*/[__,R1,R2,__,R4],
  20090. /*CCE*/[__,R1,R2,__,R4],
  20091. /*CKE*/[__,R1,R2,__,R4],
  20092. /*CCV*/[__,R1,R2,__,R4],
  20093. /*CCC*/[R0,R1,__,__,R4],
  20094. /*CFI*/[__,R1,R2,__,R4],
  20095. /*CAD*/[__,R1,R2,R3,R4],
  20096. /*CER*/[__,R1,R2,__,R4]
  20097. ];
  20098. // map client current expect state and handshake type to function
  20099. var H0 = tls$1.handleHelloRequest;
  20100. var H1 = tls$1.handleServerHello;
  20101. var H2 = tls$1.handleCertificate;
  20102. var H3 = tls$1.handleServerKeyExchange;
  20103. var H4 = tls$1.handleCertificateRequest;
  20104. var H5 = tls$1.handleServerHelloDone;
  20105. var H6 = tls$1.handleFinished;
  20106. var hsTable = [];
  20107. hsTable[tls$1.ConnectionEnd.client] = [
  20108. // HR,01,SH,03,04,05,06,07,08,09,10,SC,SK,CR,HD,15,CK,17,18,19,FI
  20109. /*SHE*/[__,__,H1,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],
  20110. /*SCE*/[H0,__,__,__,__,__,__,__,__,__,__,H2,H3,H4,H5,__,__,__,__,__,__],
  20111. /*SKE*/[H0,__,__,__,__,__,__,__,__,__,__,__,H3,H4,H5,__,__,__,__,__,__],
  20112. /*SCR*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,H4,H5,__,__,__,__,__,__],
  20113. /*SHD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,H5,__,__,__,__,__,__],
  20114. /*SCC*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],
  20115. /*SFI*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],
  20116. /*SAD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],
  20117. /*SER*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]
  20118. ];
  20119. // map server current expect state and handshake type to function
  20120. // Note: CAD[CH] does not map to FB because renegotation is prohibited
  20121. var H7 = tls$1.handleClientHello;
  20122. var H8 = tls$1.handleClientKeyExchange;
  20123. var H9 = tls$1.handleCertificateVerify;
  20124. hsTable[tls$1.ConnectionEnd.server] = [
  20125. // 01,CH,02,03,04,05,06,07,08,09,10,CC,12,13,14,CV,CK,17,18,19,FI
  20126. /*CHE*/[__,H7,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],
  20127. /*CCE*/[__,__,__,__,__,__,__,__,__,__,__,H2,__,__,__,__,__,__,__,__,__],
  20128. /*CKE*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H8,__,__,__,__],
  20129. /*CCV*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H9,__,__,__,__,__],
  20130. /*CCC*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],
  20131. /*CFI*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],
  20132. /*CAD*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],
  20133. /*CER*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]
  20134. ];
  20135. /**
  20136. * Generates the master_secret and keys using the given security parameters.
  20137. *
  20138. * The security parameters for a TLS connection state are defined as such:
  20139. *
  20140. * struct {
  20141. * ConnectionEnd entity;
  20142. * PRFAlgorithm prf_algorithm;
  20143. * BulkCipherAlgorithm bulk_cipher_algorithm;
  20144. * CipherType cipher_type;
  20145. * uint8 enc_key_length;
  20146. * uint8 block_length;
  20147. * uint8 fixed_iv_length;
  20148. * uint8 record_iv_length;
  20149. * MACAlgorithm mac_algorithm;
  20150. * uint8 mac_length;
  20151. * uint8 mac_key_length;
  20152. * CompressionMethod compression_algorithm;
  20153. * opaque master_secret[48];
  20154. * opaque client_random[32];
  20155. * opaque server_random[32];
  20156. * } SecurityParameters;
  20157. *
  20158. * Note that this definition is from TLS 1.2. In TLS 1.0 some of these
  20159. * parameters are ignored because, for instance, the PRFAlgorithm is a
  20160. * builtin-fixed algorithm combining iterations of MD5 and SHA-1 in TLS 1.0.
  20161. *
  20162. * The Record Protocol requires an algorithm to generate keys required by the
  20163. * current connection state.
  20164. *
  20165. * The master secret is expanded into a sequence of secure bytes, which is then
  20166. * split to a client write MAC key, a server write MAC key, a client write
  20167. * encryption key, and a server write encryption key. In TLS 1.0 a client write
  20168. * IV and server write IV are also generated. Each of these is generated from
  20169. * the byte sequence in that order. Unused values are empty. In TLS 1.2, some
  20170. * AEAD ciphers may additionally require a client write IV and a server write
  20171. * IV (see Section 6.2.3.3).
  20172. *
  20173. * When keys, MAC keys, and IVs are generated, the master secret is used as an
  20174. * entropy source.
  20175. *
  20176. * To generate the key material, compute:
  20177. *
  20178. * master_secret = PRF(pre_master_secret, "master secret",
  20179. * ClientHello.random + ServerHello.random)
  20180. *
  20181. * key_block = PRF(SecurityParameters.master_secret,
  20182. * "key expansion",
  20183. * SecurityParameters.server_random +
  20184. * SecurityParameters.client_random);
  20185. *
  20186. * until enough output has been generated. Then, the key_block is
  20187. * partitioned as follows:
  20188. *
  20189. * client_write_MAC_key[SecurityParameters.mac_key_length]
  20190. * server_write_MAC_key[SecurityParameters.mac_key_length]
  20191. * client_write_key[SecurityParameters.enc_key_length]
  20192. * server_write_key[SecurityParameters.enc_key_length]
  20193. * client_write_IV[SecurityParameters.fixed_iv_length]
  20194. * server_write_IV[SecurityParameters.fixed_iv_length]
  20195. *
  20196. * In TLS 1.2, the client_write_IV and server_write_IV are only generated for
  20197. * implicit nonce techniques as described in Section 3.2.1 of [AEAD]. This
  20198. * implementation uses TLS 1.0 so IVs are generated.
  20199. *
  20200. * Implementation note: The currently defined cipher suite which requires the
  20201. * most material is AES_256_CBC_SHA256. It requires 2 x 32 byte keys and 2 x 32
  20202. * byte MAC keys, for a total 128 bytes of key material. In TLS 1.0 it also
  20203. * requires 2 x 16 byte IVs, so it actually takes 160 bytes of key material.
  20204. *
  20205. * @param c the connection.
  20206. * @param sp the security parameters to use.
  20207. *
  20208. * @return the security keys.
  20209. */
  20210. tls$1.generateKeys = function(c, sp) {
  20211. // TLS_RSA_WITH_AES_128_CBC_SHA (required to be compliant with TLS 1.2) &
  20212. // TLS_RSA_WITH_AES_256_CBC_SHA are the only cipher suites implemented
  20213. // at present
  20214. // TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA is required to be compliant with
  20215. // TLS 1.0 but we don't care right now because AES is better and we have
  20216. // an implementation for it
  20217. // TODO: TLS 1.2 implementation
  20218. /*
  20219. // determine the PRF
  20220. var prf;
  20221. switch(sp.prf_algorithm) {
  20222. case tls.PRFAlgorithm.tls_prf_sha256:
  20223. prf = prf_sha256;
  20224. break;
  20225. default:
  20226. // should never happen
  20227. throw new Error('Invalid PRF');
  20228. }
  20229. */
  20230. // TLS 1.0/1.1 implementation
  20231. var prf = prf_TLS1;
  20232. // concatenate server and client random
  20233. var random = sp.client_random + sp.server_random;
  20234. // only create master secret if session is new
  20235. if(!c.session.resuming) {
  20236. // create master secret, clean up pre-master secret
  20237. sp.master_secret = prf(
  20238. sp.pre_master_secret, 'master secret', random, 48).bytes();
  20239. sp.pre_master_secret = null;
  20240. }
  20241. // generate the amount of key material needed
  20242. random = sp.server_random + sp.client_random;
  20243. var length = 2 * sp.mac_key_length + 2 * sp.enc_key_length;
  20244. // include IV for TLS/1.0
  20245. var tls10 = (c.version.major === tls$1.Versions.TLS_1_0.major &&
  20246. c.version.minor === tls$1.Versions.TLS_1_0.minor);
  20247. if(tls10) {
  20248. length += 2 * sp.fixed_iv_length;
  20249. }
  20250. var km = prf(sp.master_secret, 'key expansion', random, length);
  20251. // split the key material into the MAC and encryption keys
  20252. var rval = {
  20253. client_write_MAC_key: km.getBytes(sp.mac_key_length),
  20254. server_write_MAC_key: km.getBytes(sp.mac_key_length),
  20255. client_write_key: km.getBytes(sp.enc_key_length),
  20256. server_write_key: km.getBytes(sp.enc_key_length)
  20257. };
  20258. // include TLS 1.0 IVs
  20259. if(tls10) {
  20260. rval.client_write_IV = km.getBytes(sp.fixed_iv_length);
  20261. rval.server_write_IV = km.getBytes(sp.fixed_iv_length);
  20262. }
  20263. return rval;
  20264. };
  20265. /**
  20266. * Creates a new initialized TLS connection state. A connection state has
  20267. * a read mode and a write mode.
  20268. *
  20269. * compression state:
  20270. * The current state of the compression algorithm.
  20271. *
  20272. * cipher state:
  20273. * The current state of the encryption algorithm. This will consist of the
  20274. * scheduled key for that connection. For stream ciphers, this will also
  20275. * contain whatever state information is necessary to allow the stream to
  20276. * continue to encrypt or decrypt data.
  20277. *
  20278. * MAC key:
  20279. * The MAC key for the connection.
  20280. *
  20281. * sequence number:
  20282. * Each connection state contains a sequence number, which is maintained
  20283. * separately for read and write states. The sequence number MUST be set to
  20284. * zero whenever a connection state is made the active state. Sequence
  20285. * numbers are of type uint64 and may not exceed 2^64-1. Sequence numbers do
  20286. * not wrap. If a TLS implementation would need to wrap a sequence number,
  20287. * it must renegotiate instead. A sequence number is incremented after each
  20288. * record: specifically, the first record transmitted under a particular
  20289. * connection state MUST use sequence number 0.
  20290. *
  20291. * @param c the connection.
  20292. *
  20293. * @return the new initialized TLS connection state.
  20294. */
  20295. tls$1.createConnectionState = function(c) {
  20296. var client = (c.entity === tls$1.ConnectionEnd.client);
  20297. var createMode = function() {
  20298. var mode = {
  20299. // two 32-bit numbers, first is most significant
  20300. sequenceNumber: [0, 0],
  20301. macKey: null,
  20302. macLength: 0,
  20303. macFunction: null,
  20304. cipherState: null,
  20305. cipherFunction: function(record) {return true;},
  20306. compressionState: null,
  20307. compressFunction: function(record) {return true;},
  20308. updateSequenceNumber: function() {
  20309. if(mode.sequenceNumber[1] === 0xFFFFFFFF) {
  20310. mode.sequenceNumber[1] = 0;
  20311. ++mode.sequenceNumber[0];
  20312. } else {
  20313. ++mode.sequenceNumber[1];
  20314. }
  20315. }
  20316. };
  20317. return mode;
  20318. };
  20319. var state = {
  20320. read: createMode(),
  20321. write: createMode()
  20322. };
  20323. // update function in read mode will decrypt then decompress a record
  20324. state.read.update = function(c, record) {
  20325. if(!state.read.cipherFunction(record, state.read)) {
  20326. c.error(c, {
  20327. message: 'Could not decrypt record or bad MAC.',
  20328. send: true,
  20329. alert: {
  20330. level: tls$1.Alert.Level.fatal,
  20331. // doesn't matter if decryption failed or MAC was
  20332. // invalid, return the same error so as not to reveal
  20333. // which one occurred
  20334. description: tls$1.Alert.Description.bad_record_mac
  20335. }
  20336. });
  20337. } else if(!state.read.compressFunction(c, record, state.read)) {
  20338. c.error(c, {
  20339. message: 'Could not decompress record.',
  20340. send: true,
  20341. alert: {
  20342. level: tls$1.Alert.Level.fatal,
  20343. description: tls$1.Alert.Description.decompression_failure
  20344. }
  20345. });
  20346. }
  20347. return !c.fail;
  20348. };
  20349. // update function in write mode will compress then encrypt a record
  20350. state.write.update = function(c, record) {
  20351. if(!state.write.compressFunction(c, record, state.write)) {
  20352. // error, but do not send alert since it would require
  20353. // compression as well
  20354. c.error(c, {
  20355. message: 'Could not compress record.',
  20356. send: false,
  20357. alert: {
  20358. level: tls$1.Alert.Level.fatal,
  20359. description: tls$1.Alert.Description.internal_error
  20360. }
  20361. });
  20362. } else if(!state.write.cipherFunction(record, state.write)) {
  20363. // error, but do not send alert since it would require
  20364. // encryption as well
  20365. c.error(c, {
  20366. message: 'Could not encrypt record.',
  20367. send: false,
  20368. alert: {
  20369. level: tls$1.Alert.Level.fatal,
  20370. description: tls$1.Alert.Description.internal_error
  20371. }
  20372. });
  20373. }
  20374. return !c.fail;
  20375. };
  20376. // handle security parameters
  20377. if(c.session) {
  20378. var sp = c.session.sp;
  20379. c.session.cipherSuite.initSecurityParameters(sp);
  20380. // generate keys
  20381. sp.keys = tls$1.generateKeys(c, sp);
  20382. state.read.macKey = client ?
  20383. sp.keys.server_write_MAC_key : sp.keys.client_write_MAC_key;
  20384. state.write.macKey = client ?
  20385. sp.keys.client_write_MAC_key : sp.keys.server_write_MAC_key;
  20386. // cipher suite setup
  20387. c.session.cipherSuite.initConnectionState(state, c, sp);
  20388. // compression setup
  20389. switch(sp.compression_algorithm) {
  20390. case tls$1.CompressionMethod.none:
  20391. break;
  20392. case tls$1.CompressionMethod.deflate:
  20393. state.read.compressFunction = inflate;
  20394. state.write.compressFunction = deflate;
  20395. break;
  20396. default:
  20397. throw new Error('Unsupported compression algorithm.');
  20398. }
  20399. }
  20400. return state;
  20401. };
  20402. /**
  20403. * Creates a Random structure.
  20404. *
  20405. * struct {
  20406. * uint32 gmt_unix_time;
  20407. * opaque random_bytes[28];
  20408. * } Random;
  20409. *
  20410. * gmt_unix_time:
  20411. * The current time and date in standard UNIX 32-bit format (seconds since
  20412. * the midnight starting Jan 1, 1970, UTC, ignoring leap seconds) according
  20413. * to the sender's internal clock. Clocks are not required to be set
  20414. * correctly by the basic TLS protocol; higher-level or application
  20415. * protocols may define additional requirements. Note that, for historical
  20416. * reasons, the data element is named using GMT, the predecessor of the
  20417. * current worldwide time base, UTC.
  20418. * random_bytes:
  20419. * 28 bytes generated by a secure random number generator.
  20420. *
  20421. * @return the Random structure as a byte array.
  20422. */
  20423. tls$1.createRandom = function() {
  20424. // get UTC milliseconds
  20425. var d = new Date();
  20426. var utc = +d + d.getTimezoneOffset() * 60000;
  20427. var rval = forge$b.util.createBuffer();
  20428. rval.putInt32(utc);
  20429. rval.putBytes(forge$b.random.getBytes(28));
  20430. return rval;
  20431. };
  20432. /**
  20433. * Creates a TLS record with the given type and data.
  20434. *
  20435. * @param c the connection.
  20436. * @param options:
  20437. * type: the record type.
  20438. * data: the plain text data in a byte buffer.
  20439. *
  20440. * @return the created record.
  20441. */
  20442. tls$1.createRecord = function(c, options) {
  20443. if(!options.data) {
  20444. return null;
  20445. }
  20446. var record = {
  20447. type: options.type,
  20448. version: {
  20449. major: c.version.major,
  20450. minor: c.version.minor
  20451. },
  20452. length: options.data.length(),
  20453. fragment: options.data
  20454. };
  20455. return record;
  20456. };
  20457. /**
  20458. * Creates a TLS alert record.
  20459. *
  20460. * @param c the connection.
  20461. * @param alert:
  20462. * level: the TLS alert level.
  20463. * description: the TLS alert description.
  20464. *
  20465. * @return the created alert record.
  20466. */
  20467. tls$1.createAlert = function(c, alert) {
  20468. var b = forge$b.util.createBuffer();
  20469. b.putByte(alert.level);
  20470. b.putByte(alert.description);
  20471. return tls$1.createRecord(c, {
  20472. type: tls$1.ContentType.alert,
  20473. data: b
  20474. });
  20475. };
  20476. /* The structure of a TLS handshake message.
  20477. *
  20478. * struct {
  20479. * HandshakeType msg_type; // handshake type
  20480. * uint24 length; // bytes in message
  20481. * select(HandshakeType) {
  20482. * case hello_request: HelloRequest;
  20483. * case client_hello: ClientHello;
  20484. * case server_hello: ServerHello;
  20485. * case certificate: Certificate;
  20486. * case server_key_exchange: ServerKeyExchange;
  20487. * case certificate_request: CertificateRequest;
  20488. * case server_hello_done: ServerHelloDone;
  20489. * case certificate_verify: CertificateVerify;
  20490. * case client_key_exchange: ClientKeyExchange;
  20491. * case finished: Finished;
  20492. * } body;
  20493. * } Handshake;
  20494. */
  20495. /**
  20496. * Creates a ClientHello message.
  20497. *
  20498. * opaque SessionID<0..32>;
  20499. * enum { null(0), deflate(1), (255) } CompressionMethod;
  20500. * uint8 CipherSuite[2];
  20501. *
  20502. * struct {
  20503. * ProtocolVersion client_version;
  20504. * Random random;
  20505. * SessionID session_id;
  20506. * CipherSuite cipher_suites<2..2^16-2>;
  20507. * CompressionMethod compression_methods<1..2^8-1>;
  20508. * select(extensions_present) {
  20509. * case false:
  20510. * struct {};
  20511. * case true:
  20512. * Extension extensions<0..2^16-1>;
  20513. * };
  20514. * } ClientHello;
  20515. *
  20516. * The extension format for extended client hellos and server hellos is:
  20517. *
  20518. * struct {
  20519. * ExtensionType extension_type;
  20520. * opaque extension_data<0..2^16-1>;
  20521. * } Extension;
  20522. *
  20523. * Here:
  20524. *
  20525. * - "extension_type" identifies the particular extension type.
  20526. * - "extension_data" contains information specific to the particular
  20527. * extension type.
  20528. *
  20529. * The extension types defined in this document are:
  20530. *
  20531. * enum {
  20532. * server_name(0), max_fragment_length(1),
  20533. * client_certificate_url(2), trusted_ca_keys(3),
  20534. * truncated_hmac(4), status_request(5), (65535)
  20535. * } ExtensionType;
  20536. *
  20537. * @param c the connection.
  20538. *
  20539. * @return the ClientHello byte buffer.
  20540. */
  20541. tls$1.createClientHello = function(c) {
  20542. // save hello version
  20543. c.session.clientHelloVersion = {
  20544. major: c.version.major,
  20545. minor: c.version.minor
  20546. };
  20547. // create supported cipher suites
  20548. var cipherSuites = forge$b.util.createBuffer();
  20549. for(var i = 0; i < c.cipherSuites.length; ++i) {
  20550. var cs = c.cipherSuites[i];
  20551. cipherSuites.putByte(cs.id[0]);
  20552. cipherSuites.putByte(cs.id[1]);
  20553. }
  20554. var cSuites = cipherSuites.length();
  20555. // create supported compression methods, null always supported, but
  20556. // also support deflate if connection has inflate and deflate methods
  20557. var compressionMethods = forge$b.util.createBuffer();
  20558. compressionMethods.putByte(tls$1.CompressionMethod.none);
  20559. // FIXME: deflate support disabled until issues with raw deflate data
  20560. // without zlib headers are resolved
  20561. /*
  20562. if(c.inflate !== null && c.deflate !== null) {
  20563. compressionMethods.putByte(tls.CompressionMethod.deflate);
  20564. }
  20565. */
  20566. var cMethods = compressionMethods.length();
  20567. // create TLS SNI (server name indication) extension if virtual host
  20568. // has been specified, see RFC 3546
  20569. var extensions = forge$b.util.createBuffer();
  20570. if(c.virtualHost) {
  20571. // create extension struct
  20572. var ext = forge$b.util.createBuffer();
  20573. ext.putByte(0x00); // type server_name (ExtensionType is 2 bytes)
  20574. ext.putByte(0x00);
  20575. /* In order to provide the server name, clients MAY include an
  20576. * extension of type "server_name" in the (extended) client hello.
  20577. * The "extension_data" field of this extension SHALL contain
  20578. * "ServerNameList" where:
  20579. *
  20580. * struct {
  20581. * NameType name_type;
  20582. * select(name_type) {
  20583. * case host_name: HostName;
  20584. * } name;
  20585. * } ServerName;
  20586. *
  20587. * enum {
  20588. * host_name(0), (255)
  20589. * } NameType;
  20590. *
  20591. * opaque HostName<1..2^16-1>;
  20592. *
  20593. * struct {
  20594. * ServerName server_name_list<1..2^16-1>
  20595. * } ServerNameList;
  20596. */
  20597. var serverName = forge$b.util.createBuffer();
  20598. serverName.putByte(0x00); // type host_name
  20599. writeVector(serverName, 2, forge$b.util.createBuffer(c.virtualHost));
  20600. // ServerNameList is in extension_data
  20601. var snList = forge$b.util.createBuffer();
  20602. writeVector(snList, 2, serverName);
  20603. writeVector(ext, 2, snList);
  20604. extensions.putBuffer(ext);
  20605. }
  20606. var extLength = extensions.length();
  20607. if(extLength > 0) {
  20608. // add extension vector length
  20609. extLength += 2;
  20610. }
  20611. // determine length of the handshake message
  20612. // cipher suites and compression methods size will need to be
  20613. // updated if more get added to the list
  20614. var sessionId = c.session.id;
  20615. var length =
  20616. sessionId.length + 1 + // session ID vector
  20617. 2 + // version (major + minor)
  20618. 4 + 28 + // random time and random bytes
  20619. 2 + cSuites + // cipher suites vector
  20620. 1 + cMethods + // compression methods vector
  20621. extLength; // extensions vector
  20622. // build record fragment
  20623. var rval = forge$b.util.createBuffer();
  20624. rval.putByte(tls$1.HandshakeType.client_hello);
  20625. rval.putInt24(length); // handshake length
  20626. rval.putByte(c.version.major); // major version
  20627. rval.putByte(c.version.minor); // minor version
  20628. rval.putBytes(c.session.sp.client_random); // random time + bytes
  20629. writeVector(rval, 1, forge$b.util.createBuffer(sessionId));
  20630. writeVector(rval, 2, cipherSuites);
  20631. writeVector(rval, 1, compressionMethods);
  20632. if(extLength > 0) {
  20633. writeVector(rval, 2, extensions);
  20634. }
  20635. return rval;
  20636. };
  20637. /**
  20638. * Creates a ServerHello message.
  20639. *
  20640. * @param c the connection.
  20641. *
  20642. * @return the ServerHello byte buffer.
  20643. */
  20644. tls$1.createServerHello = function(c) {
  20645. // determine length of the handshake message
  20646. var sessionId = c.session.id;
  20647. var length =
  20648. sessionId.length + 1 + // session ID vector
  20649. 2 + // version (major + minor)
  20650. 4 + 28 + // random time and random bytes
  20651. 2 + // chosen cipher suite
  20652. 1; // chosen compression method
  20653. // build record fragment
  20654. var rval = forge$b.util.createBuffer();
  20655. rval.putByte(tls$1.HandshakeType.server_hello);
  20656. rval.putInt24(length); // handshake length
  20657. rval.putByte(c.version.major); // major version
  20658. rval.putByte(c.version.minor); // minor version
  20659. rval.putBytes(c.session.sp.server_random); // random time + bytes
  20660. writeVector(rval, 1, forge$b.util.createBuffer(sessionId));
  20661. rval.putByte(c.session.cipherSuite.id[0]);
  20662. rval.putByte(c.session.cipherSuite.id[1]);
  20663. rval.putByte(c.session.compressionMethod);
  20664. return rval;
  20665. };
  20666. /**
  20667. * Creates a Certificate message.
  20668. *
  20669. * When this message will be sent:
  20670. * This is the first message the client can send after receiving a server
  20671. * hello done message and the first message the server can send after
  20672. * sending a ServerHello. This client message is only sent if the server
  20673. * requests a certificate. If no suitable certificate is available, the
  20674. * client should send a certificate message containing no certificates. If
  20675. * client authentication is required by the server for the handshake to
  20676. * continue, it may respond with a fatal handshake failure alert.
  20677. *
  20678. * opaque ASN.1Cert<1..2^24-1>;
  20679. *
  20680. * struct {
  20681. * ASN.1Cert certificate_list<0..2^24-1>;
  20682. * } Certificate;
  20683. *
  20684. * @param c the connection.
  20685. *
  20686. * @return the Certificate byte buffer.
  20687. */
  20688. tls$1.createCertificate = function(c) {
  20689. // TODO: check certificate request to ensure types are supported
  20690. // get a certificate (a certificate as a PEM string)
  20691. var client = (c.entity === tls$1.ConnectionEnd.client);
  20692. var cert = null;
  20693. if(c.getCertificate) {
  20694. var hint;
  20695. if(client) {
  20696. hint = c.session.certificateRequest;
  20697. } else {
  20698. hint = c.session.extensions.server_name.serverNameList;
  20699. }
  20700. cert = c.getCertificate(c, hint);
  20701. }
  20702. // buffer to hold certificate list
  20703. var certList = forge$b.util.createBuffer();
  20704. if(cert !== null) {
  20705. try {
  20706. // normalize cert to a chain of certificates
  20707. if(!forge$b.util.isArray(cert)) {
  20708. cert = [cert];
  20709. }
  20710. var asn1 = null;
  20711. for(var i = 0; i < cert.length; ++i) {
  20712. var msg = forge$b.pem.decode(cert[i])[0];
  20713. if(msg.type !== 'CERTIFICATE' &&
  20714. msg.type !== 'X509 CERTIFICATE' &&
  20715. msg.type !== 'TRUSTED CERTIFICATE') {
  20716. var error = new Error('Could not convert certificate from PEM; PEM ' +
  20717. 'header type is not "CERTIFICATE", "X509 CERTIFICATE", or ' +
  20718. '"TRUSTED CERTIFICATE".');
  20719. error.headerType = msg.type;
  20720. throw error;
  20721. }
  20722. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  20723. throw new Error('Could not convert certificate from PEM; PEM is encrypted.');
  20724. }
  20725. var der = forge$b.util.createBuffer(msg.body);
  20726. if(asn1 === null) {
  20727. asn1 = forge$b.asn1.fromDer(der.bytes(), false);
  20728. }
  20729. // certificate entry is itself a vector with 3 length bytes
  20730. var certBuffer = forge$b.util.createBuffer();
  20731. writeVector(certBuffer, 3, der);
  20732. // add cert vector to cert list vector
  20733. certList.putBuffer(certBuffer);
  20734. }
  20735. // save certificate
  20736. cert = forge$b.pki.certificateFromAsn1(asn1);
  20737. if(client) {
  20738. c.session.clientCertificate = cert;
  20739. } else {
  20740. c.session.serverCertificate = cert;
  20741. }
  20742. } catch(ex) {
  20743. return c.error(c, {
  20744. message: 'Could not send certificate list.',
  20745. cause: ex,
  20746. send: true,
  20747. alert: {
  20748. level: tls$1.Alert.Level.fatal,
  20749. description: tls$1.Alert.Description.bad_certificate
  20750. }
  20751. });
  20752. }
  20753. }
  20754. // determine length of the handshake message
  20755. var length = 3 + certList.length(); // cert list vector
  20756. // build record fragment
  20757. var rval = forge$b.util.createBuffer();
  20758. rval.putByte(tls$1.HandshakeType.certificate);
  20759. rval.putInt24(length);
  20760. writeVector(rval, 3, certList);
  20761. return rval;
  20762. };
  20763. /**
  20764. * Creates a ClientKeyExchange message.
  20765. *
  20766. * When this message will be sent:
  20767. * This message is always sent by the client. It will immediately follow the
  20768. * client certificate message, if it is sent. Otherwise it will be the first
  20769. * message sent by the client after it receives the server hello done
  20770. * message.
  20771. *
  20772. * Meaning of this message:
  20773. * With this message, the premaster secret is set, either though direct
  20774. * transmission of the RSA-encrypted secret, or by the transmission of
  20775. * Diffie-Hellman parameters which will allow each side to agree upon the
  20776. * same premaster secret. When the key exchange method is DH_RSA or DH_DSS,
  20777. * client certification has been requested, and the client was able to
  20778. * respond with a certificate which contained a Diffie-Hellman public key
  20779. * whose parameters (group and generator) matched those specified by the
  20780. * server in its certificate, this message will not contain any data.
  20781. *
  20782. * Meaning of this message:
  20783. * If RSA is being used for key agreement and authentication, the client
  20784. * generates a 48-byte premaster secret, encrypts it using the public key
  20785. * from the server's certificate or the temporary RSA key provided in a
  20786. * server key exchange message, and sends the result in an encrypted
  20787. * premaster secret message. This structure is a variant of the client
  20788. * key exchange message, not a message in itself.
  20789. *
  20790. * struct {
  20791. * select(KeyExchangeAlgorithm) {
  20792. * case rsa: EncryptedPreMasterSecret;
  20793. * case diffie_hellman: ClientDiffieHellmanPublic;
  20794. * } exchange_keys;
  20795. * } ClientKeyExchange;
  20796. *
  20797. * struct {
  20798. * ProtocolVersion client_version;
  20799. * opaque random[46];
  20800. * } PreMasterSecret;
  20801. *
  20802. * struct {
  20803. * public-key-encrypted PreMasterSecret pre_master_secret;
  20804. * } EncryptedPreMasterSecret;
  20805. *
  20806. * A public-key-encrypted element is encoded as a vector <0..2^16-1>.
  20807. *
  20808. * @param c the connection.
  20809. *
  20810. * @return the ClientKeyExchange byte buffer.
  20811. */
  20812. tls$1.createClientKeyExchange = function(c) {
  20813. // create buffer to encrypt
  20814. var b = forge$b.util.createBuffer();
  20815. // add highest client-supported protocol to help server avoid version
  20816. // rollback attacks
  20817. b.putByte(c.session.clientHelloVersion.major);
  20818. b.putByte(c.session.clientHelloVersion.minor);
  20819. // generate and add 46 random bytes
  20820. b.putBytes(forge$b.random.getBytes(46));
  20821. // save pre-master secret
  20822. var sp = c.session.sp;
  20823. sp.pre_master_secret = b.getBytes();
  20824. // RSA-encrypt the pre-master secret
  20825. var key = c.session.serverCertificate.publicKey;
  20826. b = key.encrypt(sp.pre_master_secret);
  20827. /* Note: The encrypted pre-master secret will be stored in a
  20828. public-key-encrypted opaque vector that has the length prefixed using
  20829. 2 bytes, so include those 2 bytes in the handshake message length. This
  20830. is done as a minor optimization instead of calling writeVector(). */
  20831. // determine length of the handshake message
  20832. var length = b.length + 2;
  20833. // build record fragment
  20834. var rval = forge$b.util.createBuffer();
  20835. rval.putByte(tls$1.HandshakeType.client_key_exchange);
  20836. rval.putInt24(length);
  20837. // add vector length bytes
  20838. rval.putInt16(b.length);
  20839. rval.putBytes(b);
  20840. return rval;
  20841. };
  20842. /**
  20843. * Creates a ServerKeyExchange message.
  20844. *
  20845. * @param c the connection.
  20846. *
  20847. * @return the ServerKeyExchange byte buffer.
  20848. */
  20849. tls$1.createServerKeyExchange = function(c) {
  20850. // build record fragment
  20851. var rval = forge$b.util.createBuffer();
  20852. return rval;
  20853. };
  20854. /**
  20855. * Gets the signed data used to verify a client-side certificate. See
  20856. * tls.createCertificateVerify() for details.
  20857. *
  20858. * @param c the connection.
  20859. * @param callback the callback to call once the signed data is ready.
  20860. */
  20861. tls$1.getClientSignature = function(c, callback) {
  20862. // generate data to RSA encrypt
  20863. var b = forge$b.util.createBuffer();
  20864. b.putBuffer(c.session.md5.digest());
  20865. b.putBuffer(c.session.sha1.digest());
  20866. b = b.getBytes();
  20867. // create default signing function as necessary
  20868. c.getSignature = c.getSignature || function(c, b, callback) {
  20869. // do rsa encryption, call callback
  20870. var privateKey = null;
  20871. if(c.getPrivateKey) {
  20872. try {
  20873. privateKey = c.getPrivateKey(c, c.session.clientCertificate);
  20874. privateKey = forge$b.pki.privateKeyFromPem(privateKey);
  20875. } catch(ex) {
  20876. c.error(c, {
  20877. message: 'Could not get private key.',
  20878. cause: ex,
  20879. send: true,
  20880. alert: {
  20881. level: tls$1.Alert.Level.fatal,
  20882. description: tls$1.Alert.Description.internal_error
  20883. }
  20884. });
  20885. }
  20886. }
  20887. if(privateKey === null) {
  20888. c.error(c, {
  20889. message: 'No private key set.',
  20890. send: true,
  20891. alert: {
  20892. level: tls$1.Alert.Level.fatal,
  20893. description: tls$1.Alert.Description.internal_error
  20894. }
  20895. });
  20896. } else {
  20897. b = privateKey.sign(b, null);
  20898. }
  20899. callback(c, b);
  20900. };
  20901. // get client signature
  20902. c.getSignature(c, b, callback);
  20903. };
  20904. /**
  20905. * Creates a CertificateVerify message.
  20906. *
  20907. * Meaning of this message:
  20908. * This structure conveys the client's Diffie-Hellman public value
  20909. * (Yc) if it was not already included in the client's certificate.
  20910. * The encoding used for Yc is determined by the enumerated
  20911. * PublicValueEncoding. This structure is a variant of the client
  20912. * key exchange message, not a message in itself.
  20913. *
  20914. * When this message will be sent:
  20915. * This message is used to provide explicit verification of a client
  20916. * certificate. This message is only sent following a client
  20917. * certificate that has signing capability (i.e. all certificates
  20918. * except those containing fixed Diffie-Hellman parameters). When
  20919. * sent, it will immediately follow the client key exchange message.
  20920. *
  20921. * struct {
  20922. * Signature signature;
  20923. * } CertificateVerify;
  20924. *
  20925. * CertificateVerify.signature.md5_hash
  20926. * MD5(handshake_messages);
  20927. *
  20928. * Certificate.signature.sha_hash
  20929. * SHA(handshake_messages);
  20930. *
  20931. * Here handshake_messages refers to all handshake messages sent or
  20932. * received starting at client hello up to but not including this
  20933. * message, including the type and length fields of the handshake
  20934. * messages.
  20935. *
  20936. * select(SignatureAlgorithm) {
  20937. * case anonymous: struct { };
  20938. * case rsa:
  20939. * digitally-signed struct {
  20940. * opaque md5_hash[16];
  20941. * opaque sha_hash[20];
  20942. * };
  20943. * case dsa:
  20944. * digitally-signed struct {
  20945. * opaque sha_hash[20];
  20946. * };
  20947. * } Signature;
  20948. *
  20949. * In digital signing, one-way hash functions are used as input for a
  20950. * signing algorithm. A digitally-signed element is encoded as an opaque
  20951. * vector <0..2^16-1>, where the length is specified by the signing
  20952. * algorithm and key.
  20953. *
  20954. * In RSA signing, a 36-byte structure of two hashes (one SHA and one
  20955. * MD5) is signed (encrypted with the private key). It is encoded with
  20956. * PKCS #1 block type 0 or type 1 as described in [PKCS1].
  20957. *
  20958. * In DSS, the 20 bytes of the SHA hash are run directly through the
  20959. * Digital Signing Algorithm with no additional hashing.
  20960. *
  20961. * @param c the connection.
  20962. * @param signature the signature to include in the message.
  20963. *
  20964. * @return the CertificateVerify byte buffer.
  20965. */
  20966. tls$1.createCertificateVerify = function(c, signature) {
  20967. /* Note: The signature will be stored in a "digitally-signed" opaque
  20968. vector that has the length prefixed using 2 bytes, so include those
  20969. 2 bytes in the handshake message length. This is done as a minor
  20970. optimization instead of calling writeVector(). */
  20971. // determine length of the handshake message
  20972. var length = signature.length + 2;
  20973. // build record fragment
  20974. var rval = forge$b.util.createBuffer();
  20975. rval.putByte(tls$1.HandshakeType.certificate_verify);
  20976. rval.putInt24(length);
  20977. // add vector length bytes
  20978. rval.putInt16(signature.length);
  20979. rval.putBytes(signature);
  20980. return rval;
  20981. };
  20982. /**
  20983. * Creates a CertificateRequest message.
  20984. *
  20985. * @param c the connection.
  20986. *
  20987. * @return the CertificateRequest byte buffer.
  20988. */
  20989. tls$1.createCertificateRequest = function(c) {
  20990. // TODO: support other certificate types
  20991. var certTypes = forge$b.util.createBuffer();
  20992. // common RSA certificate type
  20993. certTypes.putByte(0x01);
  20994. // add distinguished names from CA store
  20995. var cAs = forge$b.util.createBuffer();
  20996. for(var key in c.caStore.certs) {
  20997. var cert = c.caStore.certs[key];
  20998. var dn = forge$b.pki.distinguishedNameToAsn1(cert.subject);
  20999. var byteBuffer = forge$b.asn1.toDer(dn);
  21000. cAs.putInt16(byteBuffer.length());
  21001. cAs.putBuffer(byteBuffer);
  21002. }
  21003. // TODO: TLS 1.2+ has a different format
  21004. // determine length of the handshake message
  21005. var length =
  21006. 1 + certTypes.length() +
  21007. 2 + cAs.length();
  21008. // build record fragment
  21009. var rval = forge$b.util.createBuffer();
  21010. rval.putByte(tls$1.HandshakeType.certificate_request);
  21011. rval.putInt24(length);
  21012. writeVector(rval, 1, certTypes);
  21013. writeVector(rval, 2, cAs);
  21014. return rval;
  21015. };
  21016. /**
  21017. * Creates a ServerHelloDone message.
  21018. *
  21019. * @param c the connection.
  21020. *
  21021. * @return the ServerHelloDone byte buffer.
  21022. */
  21023. tls$1.createServerHelloDone = function(c) {
  21024. // build record fragment
  21025. var rval = forge$b.util.createBuffer();
  21026. rval.putByte(tls$1.HandshakeType.server_hello_done);
  21027. rval.putInt24(0);
  21028. return rval;
  21029. };
  21030. /**
  21031. * Creates a ChangeCipherSpec message.
  21032. *
  21033. * The change cipher spec protocol exists to signal transitions in
  21034. * ciphering strategies. The protocol consists of a single message,
  21035. * which is encrypted and compressed under the current (not the pending)
  21036. * connection state. The message consists of a single byte of value 1.
  21037. *
  21038. * struct {
  21039. * enum { change_cipher_spec(1), (255) } type;
  21040. * } ChangeCipherSpec;
  21041. *
  21042. * @return the ChangeCipherSpec byte buffer.
  21043. */
  21044. tls$1.createChangeCipherSpec = function() {
  21045. var rval = forge$b.util.createBuffer();
  21046. rval.putByte(0x01);
  21047. return rval;
  21048. };
  21049. /**
  21050. * Creates a Finished message.
  21051. *
  21052. * struct {
  21053. * opaque verify_data[12];
  21054. * } Finished;
  21055. *
  21056. * verify_data
  21057. * PRF(master_secret, finished_label, MD5(handshake_messages) +
  21058. * SHA-1(handshake_messages)) [0..11];
  21059. *
  21060. * finished_label
  21061. * For Finished messages sent by the client, the string "client
  21062. * finished". For Finished messages sent by the server, the
  21063. * string "server finished".
  21064. *
  21065. * handshake_messages
  21066. * All of the data from all handshake messages up to but not
  21067. * including this message. This is only data visible at the
  21068. * handshake layer and does not include record layer headers.
  21069. * This is the concatenation of all the Handshake structures as
  21070. * defined in 7.4 exchanged thus far.
  21071. *
  21072. * @param c the connection.
  21073. *
  21074. * @return the Finished byte buffer.
  21075. */
  21076. tls$1.createFinished = function(c) {
  21077. // generate verify_data
  21078. var b = forge$b.util.createBuffer();
  21079. b.putBuffer(c.session.md5.digest());
  21080. b.putBuffer(c.session.sha1.digest());
  21081. // TODO: determine prf function and verify length for TLS 1.2
  21082. var client = (c.entity === tls$1.ConnectionEnd.client);
  21083. var sp = c.session.sp;
  21084. var vdl = 12;
  21085. var prf = prf_TLS1;
  21086. var label = client ? 'client finished' : 'server finished';
  21087. b = prf(sp.master_secret, label, b.getBytes(), vdl);
  21088. // build record fragment
  21089. var rval = forge$b.util.createBuffer();
  21090. rval.putByte(tls$1.HandshakeType.finished);
  21091. rval.putInt24(b.length());
  21092. rval.putBuffer(b);
  21093. return rval;
  21094. };
  21095. /**
  21096. * Creates a HeartbeatMessage (See RFC 6520).
  21097. *
  21098. * struct {
  21099. * HeartbeatMessageType type;
  21100. * uint16 payload_length;
  21101. * opaque payload[HeartbeatMessage.payload_length];
  21102. * opaque padding[padding_length];
  21103. * } HeartbeatMessage;
  21104. *
  21105. * The total length of a HeartbeatMessage MUST NOT exceed 2^14 or
  21106. * max_fragment_length when negotiated as defined in [RFC6066].
  21107. *
  21108. * type: The message type, either heartbeat_request or heartbeat_response.
  21109. *
  21110. * payload_length: The length of the payload.
  21111. *
  21112. * payload: The payload consists of arbitrary content.
  21113. *
  21114. * padding: The padding is random content that MUST be ignored by the
  21115. * receiver. The length of a HeartbeatMessage is TLSPlaintext.length
  21116. * for TLS and DTLSPlaintext.length for DTLS. Furthermore, the
  21117. * length of the type field is 1 byte, and the length of the
  21118. * payload_length is 2. Therefore, the padding_length is
  21119. * TLSPlaintext.length - payload_length - 3 for TLS and
  21120. * DTLSPlaintext.length - payload_length - 3 for DTLS. The
  21121. * padding_length MUST be at least 16.
  21122. *
  21123. * The sender of a HeartbeatMessage MUST use a random padding of at
  21124. * least 16 bytes. The padding of a received HeartbeatMessage message
  21125. * MUST be ignored.
  21126. *
  21127. * If the payload_length of a received HeartbeatMessage is too large,
  21128. * the received HeartbeatMessage MUST be discarded silently.
  21129. *
  21130. * @param c the connection.
  21131. * @param type the tls.HeartbeatMessageType.
  21132. * @param payload the heartbeat data to send as the payload.
  21133. * @param [payloadLength] the payload length to use, defaults to the
  21134. * actual payload length.
  21135. *
  21136. * @return the HeartbeatRequest byte buffer.
  21137. */
  21138. tls$1.createHeartbeat = function(type, payload, payloadLength) {
  21139. if(typeof payloadLength === 'undefined') {
  21140. payloadLength = payload.length;
  21141. }
  21142. // build record fragment
  21143. var rval = forge$b.util.createBuffer();
  21144. rval.putByte(type); // heartbeat message type
  21145. rval.putInt16(payloadLength); // payload length
  21146. rval.putBytes(payload); // payload
  21147. // padding
  21148. var plaintextLength = rval.length();
  21149. var paddingLength = Math.max(16, plaintextLength - payloadLength - 3);
  21150. rval.putBytes(forge$b.random.getBytes(paddingLength));
  21151. return rval;
  21152. };
  21153. /**
  21154. * Fragments, compresses, encrypts, and queues a record for delivery.
  21155. *
  21156. * @param c the connection.
  21157. * @param record the record to queue.
  21158. */
  21159. tls$1.queue = function(c, record) {
  21160. // error during record creation
  21161. if(!record) {
  21162. return;
  21163. }
  21164. if(record.fragment.length() === 0) {
  21165. if(record.type === tls$1.ContentType.handshake ||
  21166. record.type === tls$1.ContentType.alert ||
  21167. record.type === tls$1.ContentType.change_cipher_spec) {
  21168. // Empty handshake, alert of change cipher spec messages are not allowed per the TLS specification and should not be sent.
  21169. return;
  21170. }
  21171. }
  21172. // if the record is a handshake record, update handshake hashes
  21173. if(record.type === tls$1.ContentType.handshake) {
  21174. var bytes = record.fragment.bytes();
  21175. c.session.md5.update(bytes);
  21176. c.session.sha1.update(bytes);
  21177. bytes = null;
  21178. }
  21179. // handle record fragmentation
  21180. var records;
  21181. if(record.fragment.length() <= tls$1.MaxFragment) {
  21182. records = [record];
  21183. } else {
  21184. // fragment data as long as it is too long
  21185. records = [];
  21186. var data = record.fragment.bytes();
  21187. while(data.length > tls$1.MaxFragment) {
  21188. records.push(tls$1.createRecord(c, {
  21189. type: record.type,
  21190. data: forge$b.util.createBuffer(data.slice(0, tls$1.MaxFragment))
  21191. }));
  21192. data = data.slice(tls$1.MaxFragment);
  21193. }
  21194. // add last record
  21195. if(data.length > 0) {
  21196. records.push(tls$1.createRecord(c, {
  21197. type: record.type,
  21198. data: forge$b.util.createBuffer(data)
  21199. }));
  21200. }
  21201. }
  21202. // compress and encrypt all fragmented records
  21203. for(var i = 0; i < records.length && !c.fail; ++i) {
  21204. // update the record using current write state
  21205. var rec = records[i];
  21206. var s = c.state.current.write;
  21207. if(s.update(c, rec)) {
  21208. // store record
  21209. c.records.push(rec);
  21210. }
  21211. }
  21212. };
  21213. /**
  21214. * Flushes all queued records to the output buffer and calls the
  21215. * tlsDataReady() handler on the given connection.
  21216. *
  21217. * @param c the connection.
  21218. *
  21219. * @return true on success, false on failure.
  21220. */
  21221. tls$1.flush = function(c) {
  21222. for(var i = 0; i < c.records.length; ++i) {
  21223. var record = c.records[i];
  21224. // add record header and fragment
  21225. c.tlsData.putByte(record.type);
  21226. c.tlsData.putByte(record.version.major);
  21227. c.tlsData.putByte(record.version.minor);
  21228. c.tlsData.putInt16(record.fragment.length());
  21229. c.tlsData.putBuffer(c.records[i].fragment);
  21230. }
  21231. c.records = [];
  21232. return c.tlsDataReady(c);
  21233. };
  21234. /**
  21235. * Maps a pki.certificateError to a tls.Alert.Description.
  21236. *
  21237. * @param error the error to map.
  21238. *
  21239. * @return the alert description.
  21240. */
  21241. var _certErrorToAlertDesc = function(error) {
  21242. switch(error) {
  21243. case true:
  21244. return true;
  21245. case forge$b.pki.certificateError.bad_certificate:
  21246. return tls$1.Alert.Description.bad_certificate;
  21247. case forge$b.pki.certificateError.unsupported_certificate:
  21248. return tls$1.Alert.Description.unsupported_certificate;
  21249. case forge$b.pki.certificateError.certificate_revoked:
  21250. return tls$1.Alert.Description.certificate_revoked;
  21251. case forge$b.pki.certificateError.certificate_expired:
  21252. return tls$1.Alert.Description.certificate_expired;
  21253. case forge$b.pki.certificateError.certificate_unknown:
  21254. return tls$1.Alert.Description.certificate_unknown;
  21255. case forge$b.pki.certificateError.unknown_ca:
  21256. return tls$1.Alert.Description.unknown_ca;
  21257. default:
  21258. return tls$1.Alert.Description.bad_certificate;
  21259. }
  21260. };
  21261. /**
  21262. * Maps a tls.Alert.Description to a pki.certificateError.
  21263. *
  21264. * @param desc the alert description.
  21265. *
  21266. * @return the certificate error.
  21267. */
  21268. var _alertDescToCertError = function(desc) {
  21269. switch(desc) {
  21270. case true:
  21271. return true;
  21272. case tls$1.Alert.Description.bad_certificate:
  21273. return forge$b.pki.certificateError.bad_certificate;
  21274. case tls$1.Alert.Description.unsupported_certificate:
  21275. return forge$b.pki.certificateError.unsupported_certificate;
  21276. case tls$1.Alert.Description.certificate_revoked:
  21277. return forge$b.pki.certificateError.certificate_revoked;
  21278. case tls$1.Alert.Description.certificate_expired:
  21279. return forge$b.pki.certificateError.certificate_expired;
  21280. case tls$1.Alert.Description.certificate_unknown:
  21281. return forge$b.pki.certificateError.certificate_unknown;
  21282. case tls$1.Alert.Description.unknown_ca:
  21283. return forge$b.pki.certificateError.unknown_ca;
  21284. default:
  21285. return forge$b.pki.certificateError.bad_certificate;
  21286. }
  21287. };
  21288. /**
  21289. * Verifies a certificate chain against the given connection's
  21290. * Certificate Authority store.
  21291. *
  21292. * @param c the TLS connection.
  21293. * @param chain the certificate chain to verify, with the root or highest
  21294. * authority at the end.
  21295. *
  21296. * @return true if successful, false if not.
  21297. */
  21298. tls$1.verifyCertificateChain = function(c, chain) {
  21299. try {
  21300. // Make a copy of c.verifyOptions so that we can modify options.verify
  21301. // without modifying c.verifyOptions.
  21302. var options = {};
  21303. for (var key in c.verifyOptions) {
  21304. options[key] = c.verifyOptions[key];
  21305. }
  21306. options.verify = function(vfd, depth, chain) {
  21307. // call application callback
  21308. var ret = c.verify(c, vfd, depth, chain);
  21309. if(ret !== true) {
  21310. if(typeof ret === 'object' && !forge$b.util.isArray(ret)) {
  21311. // throw custom error
  21312. var error = new Error('The application rejected the certificate.');
  21313. error.send = true;
  21314. error.alert = {
  21315. level: tls$1.Alert.Level.fatal,
  21316. description: tls$1.Alert.Description.bad_certificate
  21317. };
  21318. if(ret.message) {
  21319. error.message = ret.message;
  21320. }
  21321. if(ret.alert) {
  21322. error.alert.description = ret.alert;
  21323. }
  21324. throw error;
  21325. }
  21326. // convert tls alert description to pki.certificateError
  21327. if(ret !== vfd) {
  21328. ret = _alertDescToCertError(ret);
  21329. }
  21330. }
  21331. return ret;
  21332. };
  21333. // verify chain
  21334. forge$b.pki.verifyCertificateChain(c.caStore, chain, options);
  21335. } catch(ex) {
  21336. // build tls error if not already customized
  21337. var err = ex;
  21338. if(typeof err !== 'object' || forge$b.util.isArray(err)) {
  21339. err = {
  21340. send: true,
  21341. alert: {
  21342. level: tls$1.Alert.Level.fatal,
  21343. description: _certErrorToAlertDesc(ex)
  21344. }
  21345. };
  21346. }
  21347. if(!('send' in err)) {
  21348. err.send = true;
  21349. }
  21350. if(!('alert' in err)) {
  21351. err.alert = {
  21352. level: tls$1.Alert.Level.fatal,
  21353. description: _certErrorToAlertDesc(err.error)
  21354. };
  21355. }
  21356. // send error
  21357. c.error(c, err);
  21358. }
  21359. return !c.fail;
  21360. };
  21361. /**
  21362. * Creates a new TLS session cache.
  21363. *
  21364. * @param cache optional map of session ID to cached session.
  21365. * @param capacity the maximum size for the cache (default: 100).
  21366. *
  21367. * @return the new TLS session cache.
  21368. */
  21369. tls$1.createSessionCache = function(cache, capacity) {
  21370. var rval = null;
  21371. // assume input is already a session cache object
  21372. if(cache && cache.getSession && cache.setSession && cache.order) {
  21373. rval = cache;
  21374. } else {
  21375. // create cache
  21376. rval = {};
  21377. rval.cache = cache || {};
  21378. rval.capacity = Math.max(capacity || 100, 1);
  21379. rval.order = [];
  21380. // store order for sessions, delete session overflow
  21381. for(var key in cache) {
  21382. if(rval.order.length <= capacity) {
  21383. rval.order.push(key);
  21384. } else {
  21385. delete cache[key];
  21386. }
  21387. }
  21388. // get a session from a session ID (or get any session)
  21389. rval.getSession = function(sessionId) {
  21390. var session = null;
  21391. var key = null;
  21392. // if session ID provided, use it
  21393. if(sessionId) {
  21394. key = forge$b.util.bytesToHex(sessionId);
  21395. } else if(rval.order.length > 0) {
  21396. // get first session from cache
  21397. key = rval.order[0];
  21398. }
  21399. if(key !== null && key in rval.cache) {
  21400. // get cached session and remove from cache
  21401. session = rval.cache[key];
  21402. delete rval.cache[key];
  21403. for(var i in rval.order) {
  21404. if(rval.order[i] === key) {
  21405. rval.order.splice(i, 1);
  21406. break;
  21407. }
  21408. }
  21409. }
  21410. return session;
  21411. };
  21412. // set a session in the cache
  21413. rval.setSession = function(sessionId, session) {
  21414. // remove session from cache if at capacity
  21415. if(rval.order.length === rval.capacity) {
  21416. var key = rval.order.shift();
  21417. delete rval.cache[key];
  21418. }
  21419. // add session to cache
  21420. var key = forge$b.util.bytesToHex(sessionId);
  21421. rval.order.push(key);
  21422. rval.cache[key] = session;
  21423. };
  21424. }
  21425. return rval;
  21426. };
  21427. /**
  21428. * Creates a new TLS connection.
  21429. *
  21430. * See public createConnection() docs for more details.
  21431. *
  21432. * @param options the options for this connection.
  21433. *
  21434. * @return the new TLS connection.
  21435. */
  21436. tls$1.createConnection = function(options) {
  21437. var caStore = null;
  21438. if(options.caStore) {
  21439. // if CA store is an array, convert it to a CA store object
  21440. if(forge$b.util.isArray(options.caStore)) {
  21441. caStore = forge$b.pki.createCaStore(options.caStore);
  21442. } else {
  21443. caStore = options.caStore;
  21444. }
  21445. } else {
  21446. // create empty CA store
  21447. caStore = forge$b.pki.createCaStore();
  21448. }
  21449. // setup default cipher suites
  21450. var cipherSuites = options.cipherSuites || null;
  21451. if(cipherSuites === null) {
  21452. cipherSuites = [];
  21453. for(var key in tls$1.CipherSuites) {
  21454. cipherSuites.push(tls$1.CipherSuites[key]);
  21455. }
  21456. }
  21457. // set default entity
  21458. var entity = (options.server || false) ?
  21459. tls$1.ConnectionEnd.server : tls$1.ConnectionEnd.client;
  21460. // create session cache if requested
  21461. var sessionCache = options.sessionCache ?
  21462. tls$1.createSessionCache(options.sessionCache) : null;
  21463. // create TLS connection
  21464. var c = {
  21465. version: {major: tls$1.Version.major, minor: tls$1.Version.minor},
  21466. entity: entity,
  21467. sessionId: options.sessionId,
  21468. caStore: caStore,
  21469. sessionCache: sessionCache,
  21470. cipherSuites: cipherSuites,
  21471. connected: options.connected,
  21472. virtualHost: options.virtualHost || null,
  21473. verifyClient: options.verifyClient || false,
  21474. verify: options.verify || function(cn, vfd, dpth, cts) {return vfd;},
  21475. verifyOptions: options.verifyOptions || {},
  21476. getCertificate: options.getCertificate || null,
  21477. getPrivateKey: options.getPrivateKey || null,
  21478. getSignature: options.getSignature || null,
  21479. input: forge$b.util.createBuffer(),
  21480. tlsData: forge$b.util.createBuffer(),
  21481. data: forge$b.util.createBuffer(),
  21482. tlsDataReady: options.tlsDataReady,
  21483. dataReady: options.dataReady,
  21484. heartbeatReceived: options.heartbeatReceived,
  21485. closed: options.closed,
  21486. error: function(c, ex) {
  21487. // set origin if not set
  21488. ex.origin = ex.origin ||
  21489. ((c.entity === tls$1.ConnectionEnd.client) ? 'client' : 'server');
  21490. // send TLS alert
  21491. if(ex.send) {
  21492. tls$1.queue(c, tls$1.createAlert(c, ex.alert));
  21493. tls$1.flush(c);
  21494. }
  21495. // error is fatal by default
  21496. var fatal = (ex.fatal !== false);
  21497. if(fatal) {
  21498. // set fail flag
  21499. c.fail = true;
  21500. }
  21501. // call error handler first
  21502. options.error(c, ex);
  21503. if(fatal) {
  21504. // fatal error, close connection, do not clear fail
  21505. c.close(false);
  21506. }
  21507. },
  21508. deflate: options.deflate || null,
  21509. inflate: options.inflate || null
  21510. };
  21511. /**
  21512. * Resets a closed TLS connection for reuse. Called in c.close().
  21513. *
  21514. * @param clearFail true to clear the fail flag (default: true).
  21515. */
  21516. c.reset = function(clearFail) {
  21517. c.version = {major: tls$1.Version.major, minor: tls$1.Version.minor};
  21518. c.record = null;
  21519. c.session = null;
  21520. c.peerCertificate = null;
  21521. c.state = {
  21522. pending: null,
  21523. current: null
  21524. };
  21525. c.expect = (c.entity === tls$1.ConnectionEnd.client) ? SHE : CHE;
  21526. c.fragmented = null;
  21527. c.records = [];
  21528. c.open = false;
  21529. c.handshakes = 0;
  21530. c.handshaking = false;
  21531. c.isConnected = false;
  21532. c.fail = !(clearFail || typeof(clearFail) === 'undefined');
  21533. c.input.clear();
  21534. c.tlsData.clear();
  21535. c.data.clear();
  21536. c.state.current = tls$1.createConnectionState(c);
  21537. };
  21538. // do initial reset of connection
  21539. c.reset();
  21540. /**
  21541. * Updates the current TLS engine state based on the given record.
  21542. *
  21543. * @param c the TLS connection.
  21544. * @param record the TLS record to act on.
  21545. */
  21546. var _update = function(c, record) {
  21547. // get record handler (align type in table by subtracting lowest)
  21548. var aligned = record.type - tls$1.ContentType.change_cipher_spec;
  21549. var handlers = ctTable[c.entity][c.expect];
  21550. if(aligned in handlers) {
  21551. handlers[aligned](c, record);
  21552. } else {
  21553. // unexpected record
  21554. tls$1.handleUnexpected(c, record);
  21555. }
  21556. };
  21557. /**
  21558. * Reads the record header and initializes the next record on the given
  21559. * connection.
  21560. *
  21561. * @param c the TLS connection with the next record.
  21562. *
  21563. * @return 0 if the input data could be processed, otherwise the
  21564. * number of bytes required for data to be processed.
  21565. */
  21566. var _readRecordHeader = function(c) {
  21567. var rval = 0;
  21568. // get input buffer and its length
  21569. var b = c.input;
  21570. var len = b.length();
  21571. // need at least 5 bytes to initialize a record
  21572. if(len < 5) {
  21573. rval = 5 - len;
  21574. } else {
  21575. // enough bytes for header
  21576. // initialize record
  21577. c.record = {
  21578. type: b.getByte(),
  21579. version: {
  21580. major: b.getByte(),
  21581. minor: b.getByte()
  21582. },
  21583. length: b.getInt16(),
  21584. fragment: forge$b.util.createBuffer(),
  21585. ready: false
  21586. };
  21587. // check record version
  21588. var compatibleVersion = (c.record.version.major === c.version.major);
  21589. if(compatibleVersion && c.session && c.session.version) {
  21590. // session version already set, require same minor version
  21591. compatibleVersion = (c.record.version.minor === c.version.minor);
  21592. }
  21593. if(!compatibleVersion) {
  21594. c.error(c, {
  21595. message: 'Incompatible TLS version.',
  21596. send: true,
  21597. alert: {
  21598. level: tls$1.Alert.Level.fatal,
  21599. description: tls$1.Alert.Description.protocol_version
  21600. }
  21601. });
  21602. }
  21603. }
  21604. return rval;
  21605. };
  21606. /**
  21607. * Reads the next record's contents and appends its message to any
  21608. * previously fragmented message.
  21609. *
  21610. * @param c the TLS connection with the next record.
  21611. *
  21612. * @return 0 if the input data could be processed, otherwise the
  21613. * number of bytes required for data to be processed.
  21614. */
  21615. var _readRecord = function(c) {
  21616. var rval = 0;
  21617. // ensure there is enough input data to get the entire record
  21618. var b = c.input;
  21619. var len = b.length();
  21620. if(len < c.record.length) {
  21621. // not enough data yet, return how much is required
  21622. rval = c.record.length - len;
  21623. } else {
  21624. // there is enough data to parse the pending record
  21625. // fill record fragment and compact input buffer
  21626. c.record.fragment.putBytes(b.getBytes(c.record.length));
  21627. b.compact();
  21628. // update record using current read state
  21629. var s = c.state.current.read;
  21630. if(s.update(c, c.record)) {
  21631. // see if there is a previously fragmented message that the
  21632. // new record's message fragment should be appended to
  21633. if(c.fragmented !== null) {
  21634. // if the record type matches a previously fragmented
  21635. // record, append the record fragment to it
  21636. if(c.fragmented.type === c.record.type) {
  21637. // concatenate record fragments
  21638. c.fragmented.fragment.putBuffer(c.record.fragment);
  21639. c.record = c.fragmented;
  21640. } else {
  21641. // error, invalid fragmented record
  21642. c.error(c, {
  21643. message: 'Invalid fragmented record.',
  21644. send: true,
  21645. alert: {
  21646. level: tls$1.Alert.Level.fatal,
  21647. description:
  21648. tls$1.Alert.Description.unexpected_message
  21649. }
  21650. });
  21651. }
  21652. }
  21653. // record is now ready
  21654. c.record.ready = true;
  21655. }
  21656. }
  21657. return rval;
  21658. };
  21659. /**
  21660. * Performs a handshake using the TLS Handshake Protocol, as a client.
  21661. *
  21662. * This method should only be called if the connection is in client mode.
  21663. *
  21664. * @param sessionId the session ID to use, null to start a new one.
  21665. */
  21666. c.handshake = function(sessionId) {
  21667. // error to call this in non-client mode
  21668. if(c.entity !== tls$1.ConnectionEnd.client) {
  21669. // not fatal error
  21670. c.error(c, {
  21671. message: 'Cannot initiate handshake as a server.',
  21672. fatal: false
  21673. });
  21674. } else if(c.handshaking) {
  21675. // handshake is already in progress, fail but not fatal error
  21676. c.error(c, {
  21677. message: 'Handshake already in progress.',
  21678. fatal: false
  21679. });
  21680. } else {
  21681. // clear fail flag on reuse
  21682. if(c.fail && !c.open && c.handshakes === 0) {
  21683. c.fail = false;
  21684. }
  21685. // now handshaking
  21686. c.handshaking = true;
  21687. // default to blank (new session)
  21688. sessionId = sessionId || '';
  21689. // if a session ID was specified, try to find it in the cache
  21690. var session = null;
  21691. if(sessionId.length > 0) {
  21692. if(c.sessionCache) {
  21693. session = c.sessionCache.getSession(sessionId);
  21694. }
  21695. // matching session not found in cache, clear session ID
  21696. if(session === null) {
  21697. sessionId = '';
  21698. }
  21699. }
  21700. // no session given, grab a session from the cache, if available
  21701. if(sessionId.length === 0 && c.sessionCache) {
  21702. session = c.sessionCache.getSession();
  21703. if(session !== null) {
  21704. sessionId = session.id;
  21705. }
  21706. }
  21707. // set up session
  21708. c.session = {
  21709. id: sessionId,
  21710. version: null,
  21711. cipherSuite: null,
  21712. compressionMethod: null,
  21713. serverCertificate: null,
  21714. certificateRequest: null,
  21715. clientCertificate: null,
  21716. sp: {},
  21717. md5: forge$b.md.md5.create(),
  21718. sha1: forge$b.md.sha1.create()
  21719. };
  21720. // use existing session information
  21721. if(session) {
  21722. // only update version on connection, session version not yet set
  21723. c.version = session.version;
  21724. c.session.sp = session.sp;
  21725. }
  21726. // generate new client random
  21727. c.session.sp.client_random = tls$1.createRandom().getBytes();
  21728. // connection now open
  21729. c.open = true;
  21730. // send hello
  21731. tls$1.queue(c, tls$1.createRecord(c, {
  21732. type: tls$1.ContentType.handshake,
  21733. data: tls$1.createClientHello(c)
  21734. }));
  21735. tls$1.flush(c);
  21736. }
  21737. };
  21738. /**
  21739. * Called when TLS protocol data has been received from somewhere and should
  21740. * be processed by the TLS engine.
  21741. *
  21742. * @param data the TLS protocol data, as a string, to process.
  21743. *
  21744. * @return 0 if the data could be processed, otherwise the number of bytes
  21745. * required for data to be processed.
  21746. */
  21747. c.process = function(data) {
  21748. var rval = 0;
  21749. // buffer input data
  21750. if(data) {
  21751. c.input.putBytes(data);
  21752. }
  21753. // process next record if no failure, process will be called after
  21754. // each record is handled (since handling can be asynchronous)
  21755. if(!c.fail) {
  21756. // reset record if ready and now empty
  21757. if(c.record !== null &&
  21758. c.record.ready && c.record.fragment.isEmpty()) {
  21759. c.record = null;
  21760. }
  21761. // if there is no pending record, try to read record header
  21762. if(c.record === null) {
  21763. rval = _readRecordHeader(c);
  21764. }
  21765. // read the next record (if record not yet ready)
  21766. if(!c.fail && c.record !== null && !c.record.ready) {
  21767. rval = _readRecord(c);
  21768. }
  21769. // record ready to be handled, update engine state
  21770. if(!c.fail && c.record !== null && c.record.ready) {
  21771. _update(c, c.record);
  21772. }
  21773. }
  21774. return rval;
  21775. };
  21776. /**
  21777. * Requests that application data be packaged into a TLS record. The
  21778. * tlsDataReady handler will be called when the TLS record(s) have been
  21779. * prepared.
  21780. *
  21781. * @param data the application data, as a raw 'binary' encoded string, to
  21782. * be sent; to send utf-16/utf-8 string data, use the return value
  21783. * of util.encodeUtf8(str).
  21784. *
  21785. * @return true on success, false on failure.
  21786. */
  21787. c.prepare = function(data) {
  21788. tls$1.queue(c, tls$1.createRecord(c, {
  21789. type: tls$1.ContentType.application_data,
  21790. data: forge$b.util.createBuffer(data)
  21791. }));
  21792. return tls$1.flush(c);
  21793. };
  21794. /**
  21795. * Requests that a heartbeat request be packaged into a TLS record for
  21796. * transmission. The tlsDataReady handler will be called when TLS record(s)
  21797. * have been prepared.
  21798. *
  21799. * When a heartbeat response has been received, the heartbeatReceived
  21800. * handler will be called with the matching payload. This handler can
  21801. * be used to clear a retransmission timer, etc.
  21802. *
  21803. * @param payload the heartbeat data to send as the payload in the message.
  21804. * @param [payloadLength] the payload length to use, defaults to the
  21805. * actual payload length.
  21806. *
  21807. * @return true on success, false on failure.
  21808. */
  21809. c.prepareHeartbeatRequest = function(payload, payloadLength) {
  21810. if(payload instanceof forge$b.util.ByteBuffer) {
  21811. payload = payload.bytes();
  21812. }
  21813. if(typeof payloadLength === 'undefined') {
  21814. payloadLength = payload.length;
  21815. }
  21816. c.expectedHeartbeatPayload = payload;
  21817. tls$1.queue(c, tls$1.createRecord(c, {
  21818. type: tls$1.ContentType.heartbeat,
  21819. data: tls$1.createHeartbeat(
  21820. tls$1.HeartbeatMessageType.heartbeat_request, payload, payloadLength)
  21821. }));
  21822. return tls$1.flush(c);
  21823. };
  21824. /**
  21825. * Closes the connection (sends a close_notify alert).
  21826. *
  21827. * @param clearFail true to clear the fail flag (default: true).
  21828. */
  21829. c.close = function(clearFail) {
  21830. // save session if connection didn't fail
  21831. if(!c.fail && c.sessionCache && c.session) {
  21832. // only need to preserve session ID, version, and security params
  21833. var session = {
  21834. id: c.session.id,
  21835. version: c.session.version,
  21836. sp: c.session.sp
  21837. };
  21838. session.sp.keys = null;
  21839. c.sessionCache.setSession(session.id, session);
  21840. }
  21841. if(c.open) {
  21842. // connection no longer open, clear input
  21843. c.open = false;
  21844. c.input.clear();
  21845. // if connected or handshaking, send an alert
  21846. if(c.isConnected || c.handshaking) {
  21847. c.isConnected = c.handshaking = false;
  21848. // send close_notify alert
  21849. tls$1.queue(c, tls$1.createAlert(c, {
  21850. level: tls$1.Alert.Level.warning,
  21851. description: tls$1.Alert.Description.close_notify
  21852. }));
  21853. tls$1.flush(c);
  21854. }
  21855. // call handler
  21856. c.closed(c);
  21857. }
  21858. // reset TLS connection, do not clear fail flag
  21859. c.reset(clearFail);
  21860. };
  21861. return c;
  21862. };
  21863. /* TLS API */
  21864. forge$b.tls = forge$b.tls || {};
  21865. // expose non-functions
  21866. for(var key in tls$1) {
  21867. if(typeof tls$1[key] !== 'function') {
  21868. forge$b.tls[key] = tls$1[key];
  21869. }
  21870. }
  21871. // expose prf_tls1 for testing
  21872. forge$b.tls.prf_tls1 = prf_TLS1;
  21873. // expose sha1 hmac method
  21874. forge$b.tls.hmac_sha1 = hmac_sha1;
  21875. // expose session cache creation
  21876. forge$b.tls.createSessionCache = tls$1.createSessionCache;
  21877. /**
  21878. * Creates a new TLS connection. This does not make any assumptions about the
  21879. * transport layer that TLS is working on top of, ie: it does not assume there
  21880. * is a TCP/IP connection or establish one. A TLS connection is totally
  21881. * abstracted away from the layer is runs on top of, it merely establishes a
  21882. * secure channel between a client" and a "server".
  21883. *
  21884. * A TLS connection contains 4 connection states: pending read and write, and
  21885. * current read and write.
  21886. *
  21887. * At initialization, the current read and write states will be null. Only once
  21888. * the security parameters have been set and the keys have been generated can
  21889. * the pending states be converted into current states. Current states will be
  21890. * updated for each record processed.
  21891. *
  21892. * A custom certificate verify callback may be provided to check information
  21893. * like the common name on the server's certificate. It will be called for
  21894. * every certificate in the chain. It has the following signature:
  21895. *
  21896. * variable func(c, certs, index, preVerify)
  21897. * Where:
  21898. * c The TLS connection
  21899. * verified Set to true if certificate was verified, otherwise the alert
  21900. * tls.Alert.Description for why the certificate failed.
  21901. * depth The current index in the chain, where 0 is the server's cert.
  21902. * certs The certificate chain, *NOTE* if the server was anonymous then
  21903. * the chain will be empty.
  21904. *
  21905. * The function returns true on success and on failure either the appropriate
  21906. * tls.Alert.Description or an object with 'alert' set to the appropriate
  21907. * tls.Alert.Description and 'message' set to a custom error message. If true
  21908. * is not returned then the connection will abort using, in order of
  21909. * availability, first the returned alert description, second the preVerify
  21910. * alert description, and lastly the default 'bad_certificate'.
  21911. *
  21912. * There are three callbacks that can be used to make use of client-side
  21913. * certificates where each takes the TLS connection as the first parameter:
  21914. *
  21915. * getCertificate(conn, hint)
  21916. * The second parameter is a hint as to which certificate should be
  21917. * returned. If the connection entity is a client, then the hint will be
  21918. * the CertificateRequest message from the server that is part of the
  21919. * TLS protocol. If the connection entity is a server, then it will be
  21920. * the servername list provided via an SNI extension the ClientHello, if
  21921. * one was provided (empty array if not). The hint can be examined to
  21922. * determine which certificate to use (advanced). Most implementations
  21923. * will just return a certificate. The return value must be a
  21924. * PEM-formatted certificate or an array of PEM-formatted certificates
  21925. * that constitute a certificate chain, with the first in the array/chain
  21926. * being the client's certificate.
  21927. * getPrivateKey(conn, certificate)
  21928. * The second parameter is an forge.pki X.509 certificate object that
  21929. * is associated with the requested private key. The return value must
  21930. * be a PEM-formatted private key.
  21931. * getSignature(conn, bytes, callback)
  21932. * This callback can be used instead of getPrivateKey if the private key
  21933. * is not directly accessible in javascript or should not be. For
  21934. * instance, a secure external web service could provide the signature
  21935. * in exchange for appropriate credentials. The second parameter is a
  21936. * string of bytes to be signed that are part of the TLS protocol. These
  21937. * bytes are used to verify that the private key for the previously
  21938. * provided client-side certificate is accessible to the client. The
  21939. * callback is a function that takes 2 parameters, the TLS connection
  21940. * and the RSA encrypted (signed) bytes as a string. This callback must
  21941. * be called once the signature is ready.
  21942. *
  21943. * @param options the options for this connection:
  21944. * server: true if the connection is server-side, false for client.
  21945. * sessionId: a session ID to reuse, null for a new connection.
  21946. * caStore: an array of certificates to trust.
  21947. * sessionCache: a session cache to use.
  21948. * cipherSuites: an optional array of cipher suites to use,
  21949. * see tls.CipherSuites.
  21950. * connected: function(conn) called when the first handshake completes.
  21951. * virtualHost: the virtual server name to use in a TLS SNI extension.
  21952. * verifyClient: true to require a client certificate in server mode,
  21953. * 'optional' to request one, false not to (default: false).
  21954. * verify: a handler used to custom verify certificates in the chain.
  21955. * verifyOptions: an object with options for the certificate chain validation.
  21956. * See documentation of pki.verifyCertificateChain for possible options.
  21957. * verifyOptions.verify is ignored. If you wish to specify a verify handler
  21958. * use the verify key.
  21959. * getCertificate: an optional callback used to get a certificate or
  21960. * a chain of certificates (as an array).
  21961. * getPrivateKey: an optional callback used to get a private key.
  21962. * getSignature: an optional callback used to get a signature.
  21963. * tlsDataReady: function(conn) called when TLS protocol data has been
  21964. * prepared and is ready to be used (typically sent over a socket
  21965. * connection to its destination), read from conn.tlsData buffer.
  21966. * dataReady: function(conn) called when application data has
  21967. * been parsed from a TLS record and should be consumed by the
  21968. * application, read from conn.data buffer.
  21969. * closed: function(conn) called when the connection has been closed.
  21970. * error: function(conn, error) called when there was an error.
  21971. * deflate: function(inBytes) if provided, will deflate TLS records using
  21972. * the deflate algorithm if the server supports it.
  21973. * inflate: function(inBytes) if provided, will inflate TLS records using
  21974. * the deflate algorithm if the server supports it.
  21975. *
  21976. * @return the new TLS connection.
  21977. */
  21978. forge$b.tls.createConnection = tls$1.createConnection;
  21979. /**
  21980. * A Javascript implementation of AES Cipher Suites for TLS.
  21981. *
  21982. * @author Dave Longley
  21983. *
  21984. * Copyright (c) 2009-2015 Digital Bazaar, Inc.
  21985. *
  21986. */
  21987. var forge$a = forge$F;
  21988. var tls = forge$a.tls;
  21989. /**
  21990. * Supported cipher suites.
  21991. */
  21992. tls.CipherSuites['TLS_RSA_WITH_AES_128_CBC_SHA'] = {
  21993. id: [0x00, 0x2f],
  21994. name: 'TLS_RSA_WITH_AES_128_CBC_SHA',
  21995. initSecurityParameters: function(sp) {
  21996. sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes;
  21997. sp.cipher_type = tls.CipherType.block;
  21998. sp.enc_key_length = 16;
  21999. sp.block_length = 16;
  22000. sp.fixed_iv_length = 16;
  22001. sp.record_iv_length = 16;
  22002. sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1;
  22003. sp.mac_length = 20;
  22004. sp.mac_key_length = 20;
  22005. },
  22006. initConnectionState: initConnectionState
  22007. };
  22008. tls.CipherSuites['TLS_RSA_WITH_AES_256_CBC_SHA'] = {
  22009. id: [0x00, 0x35],
  22010. name: 'TLS_RSA_WITH_AES_256_CBC_SHA',
  22011. initSecurityParameters: function(sp) {
  22012. sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes;
  22013. sp.cipher_type = tls.CipherType.block;
  22014. sp.enc_key_length = 32;
  22015. sp.block_length = 16;
  22016. sp.fixed_iv_length = 16;
  22017. sp.record_iv_length = 16;
  22018. sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1;
  22019. sp.mac_length = 20;
  22020. sp.mac_key_length = 20;
  22021. },
  22022. initConnectionState: initConnectionState
  22023. };
  22024. function initConnectionState(state, c, sp) {
  22025. var client = (c.entity === forge$a.tls.ConnectionEnd.client);
  22026. // cipher setup
  22027. state.read.cipherState = {
  22028. init: false,
  22029. cipher: forge$a.cipher.createDecipher('AES-CBC', client ?
  22030. sp.keys.server_write_key : sp.keys.client_write_key),
  22031. iv: client ? sp.keys.server_write_IV : sp.keys.client_write_IV
  22032. };
  22033. state.write.cipherState = {
  22034. init: false,
  22035. cipher: forge$a.cipher.createCipher('AES-CBC', client ?
  22036. sp.keys.client_write_key : sp.keys.server_write_key),
  22037. iv: client ? sp.keys.client_write_IV : sp.keys.server_write_IV
  22038. };
  22039. state.read.cipherFunction = decrypt_aes_cbc_sha1;
  22040. state.write.cipherFunction = encrypt_aes_cbc_sha1;
  22041. // MAC setup
  22042. state.read.macLength = state.write.macLength = sp.mac_length;
  22043. state.read.macFunction = state.write.macFunction = tls.hmac_sha1;
  22044. }
  22045. /**
  22046. * Encrypts the TLSCompressed record into a TLSCipherText record using AES
  22047. * in CBC mode.
  22048. *
  22049. * @param record the TLSCompressed record to encrypt.
  22050. * @param s the ConnectionState to use.
  22051. *
  22052. * @return true on success, false on failure.
  22053. */
  22054. function encrypt_aes_cbc_sha1(record, s) {
  22055. var rval = false;
  22056. // append MAC to fragment, update sequence number
  22057. var mac = s.macFunction(s.macKey, s.sequenceNumber, record);
  22058. record.fragment.putBytes(mac);
  22059. s.updateSequenceNumber();
  22060. // TLS 1.1+ use an explicit IV every time to protect against CBC attacks
  22061. var iv;
  22062. if(record.version.minor === tls.Versions.TLS_1_0.minor) {
  22063. // use the pre-generated IV when initializing for TLS 1.0, otherwise use
  22064. // the residue from the previous encryption
  22065. iv = s.cipherState.init ? null : s.cipherState.iv;
  22066. } else {
  22067. iv = forge$a.random.getBytesSync(16);
  22068. }
  22069. s.cipherState.init = true;
  22070. // start cipher
  22071. var cipher = s.cipherState.cipher;
  22072. cipher.start({iv: iv});
  22073. // TLS 1.1+ write IV into output
  22074. if(record.version.minor >= tls.Versions.TLS_1_1.minor) {
  22075. cipher.output.putBytes(iv);
  22076. }
  22077. // do encryption (default padding is appropriate)
  22078. cipher.update(record.fragment);
  22079. if(cipher.finish(encrypt_aes_cbc_sha1_padding)) {
  22080. // set record fragment to encrypted output
  22081. record.fragment = cipher.output;
  22082. record.length = record.fragment.length();
  22083. rval = true;
  22084. }
  22085. return rval;
  22086. }
  22087. /**
  22088. * Handles padding for aes_cbc_sha1 in encrypt mode.
  22089. *
  22090. * @param blockSize the block size.
  22091. * @param input the input buffer.
  22092. * @param decrypt true in decrypt mode, false in encrypt mode.
  22093. *
  22094. * @return true on success, false on failure.
  22095. */
  22096. function encrypt_aes_cbc_sha1_padding(blockSize, input, decrypt) {
  22097. /* The encrypted data length (TLSCiphertext.length) is one more than the sum
  22098. of SecurityParameters.block_length, TLSCompressed.length,
  22099. SecurityParameters.mac_length, and padding_length.
  22100. The padding may be any length up to 255 bytes long, as long as it results in
  22101. the TLSCiphertext.length being an integral multiple of the block length.
  22102. Lengths longer than necessary might be desirable to frustrate attacks on a
  22103. protocol based on analysis of the lengths of exchanged messages. Each uint8
  22104. in the padding data vector must be filled with the padding length value.
  22105. The padding length should be such that the total size of the
  22106. GenericBlockCipher structure is a multiple of the cipher's block length.
  22107. Legal values range from zero to 255, inclusive. This length specifies the
  22108. length of the padding field exclusive of the padding_length field itself.
  22109. This is slightly different from PKCS#7 because the padding value is 1
  22110. less than the actual number of padding bytes if you include the
  22111. padding_length uint8 itself as a padding byte. */
  22112. if(!decrypt) {
  22113. // get the number of padding bytes required to reach the blockSize and
  22114. // subtract 1 for the padding value (to make room for the padding_length
  22115. // uint8)
  22116. var padding = blockSize - (input.length() % blockSize);
  22117. input.fillWithByte(padding - 1, padding);
  22118. }
  22119. return true;
  22120. }
  22121. /**
  22122. * Handles padding for aes_cbc_sha1 in decrypt mode.
  22123. *
  22124. * @param blockSize the block size.
  22125. * @param output the output buffer.
  22126. * @param decrypt true in decrypt mode, false in encrypt mode.
  22127. *
  22128. * @return true on success, false on failure.
  22129. */
  22130. function decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt) {
  22131. var rval = true;
  22132. if(decrypt) {
  22133. /* The last byte in the output specifies the number of padding bytes not
  22134. including itself. Each of the padding bytes has the same value as that
  22135. last byte (known as the padding_length). Here we check all padding
  22136. bytes to ensure they have the value of padding_length even if one of
  22137. them is bad in order to ward-off timing attacks. */
  22138. var len = output.length();
  22139. var paddingLength = output.last();
  22140. for(var i = len - 1 - paddingLength; i < len - 1; ++i) {
  22141. rval = rval && (output.at(i) == paddingLength);
  22142. }
  22143. if(rval) {
  22144. // trim off padding bytes and last padding length byte
  22145. output.truncate(paddingLength + 1);
  22146. }
  22147. }
  22148. return rval;
  22149. }
  22150. /**
  22151. * Decrypts a TLSCipherText record into a TLSCompressed record using
  22152. * AES in CBC mode.
  22153. *
  22154. * @param record the TLSCipherText record to decrypt.
  22155. * @param s the ConnectionState to use.
  22156. *
  22157. * @return true on success, false on failure.
  22158. */
  22159. function decrypt_aes_cbc_sha1(record, s) {
  22160. var rval = false;
  22161. var iv;
  22162. if(record.version.minor === tls.Versions.TLS_1_0.minor) {
  22163. // use pre-generated IV when initializing for TLS 1.0, otherwise use the
  22164. // residue from the previous decryption
  22165. iv = s.cipherState.init ? null : s.cipherState.iv;
  22166. } else {
  22167. // TLS 1.1+ use an explicit IV every time to protect against CBC attacks
  22168. // that is appended to the record fragment
  22169. iv = record.fragment.getBytes(16);
  22170. }
  22171. s.cipherState.init = true;
  22172. // start cipher
  22173. var cipher = s.cipherState.cipher;
  22174. cipher.start({iv: iv});
  22175. // do decryption
  22176. cipher.update(record.fragment);
  22177. rval = cipher.finish(decrypt_aes_cbc_sha1_padding);
  22178. // even if decryption fails, keep going to minimize timing attacks
  22179. // decrypted data:
  22180. // first (len - 20) bytes = application data
  22181. // last 20 bytes = MAC
  22182. var macLen = s.macLength;
  22183. // create a random MAC to check against should the mac length check fail
  22184. // Note: do this regardless of the failure to keep timing consistent
  22185. var mac = forge$a.random.getBytesSync(macLen);
  22186. // get fragment and mac
  22187. var len = cipher.output.length();
  22188. if(len >= macLen) {
  22189. record.fragment = cipher.output.getBytes(len - macLen);
  22190. mac = cipher.output.getBytes(macLen);
  22191. } else {
  22192. // bad data, but get bytes anyway to try to keep timing consistent
  22193. record.fragment = cipher.output.getBytes();
  22194. }
  22195. record.fragment = forge$a.util.createBuffer(record.fragment);
  22196. record.length = record.fragment.length();
  22197. // see if data integrity checks out, update sequence number
  22198. var mac2 = s.macFunction(s.macKey, s.sequenceNumber, record);
  22199. s.updateSequenceNumber();
  22200. rval = compareMacs(s.macKey, mac, mac2) && rval;
  22201. return rval;
  22202. }
  22203. /**
  22204. * Safely compare two MACs. This function will compare two MACs in a way
  22205. * that protects against timing attacks.
  22206. *
  22207. * TODO: Expose elsewhere as a utility API.
  22208. *
  22209. * See: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/february/double-hmac-verification/
  22210. *
  22211. * @param key the MAC key to use.
  22212. * @param mac1 as a binary-encoded string of bytes.
  22213. * @param mac2 as a binary-encoded string of bytes.
  22214. *
  22215. * @return true if the MACs are the same, false if not.
  22216. */
  22217. function compareMacs(key, mac1, mac2) {
  22218. var hmac = forge$a.hmac.create();
  22219. hmac.start('SHA1', key);
  22220. hmac.update(mac1);
  22221. mac1 = hmac.digest().getBytes();
  22222. hmac.start(null, null);
  22223. hmac.update(mac2);
  22224. mac2 = hmac.digest().getBytes();
  22225. return mac1 === mac2;
  22226. }
  22227. /**
  22228. * Debugging support for web applications.
  22229. *
  22230. * @author David I. Lehn <dlehn@digitalbazaar.com>
  22231. *
  22232. * Copyright 2008-2013 Digital Bazaar, Inc.
  22233. */
  22234. var forge$9 = forge$F;
  22235. /* DEBUG API */
  22236. forge$9.debug = forge$9.debug || {};
  22237. // Private storage for debugging.
  22238. // Useful to expose data that is otherwise unviewable behind closures.
  22239. // NOTE: remember that this can hold references to data and cause leaks!
  22240. // format is "forge._debug.<modulename>.<dataname> = data"
  22241. // Example:
  22242. // (function() {
  22243. // var cat = 'forge.test.Test'; // debugging category
  22244. // var sState = {...}; // local state
  22245. // forge.debug.set(cat, 'sState', sState);
  22246. // })();
  22247. forge$9.debug.storage = {};
  22248. /**
  22249. * Gets debug data. Omit name for all cat data Omit name and cat for
  22250. * all data.
  22251. *
  22252. * @param cat name of debugging category.
  22253. * @param name name of data to get (optional).
  22254. * @return object with requested debug data or undefined.
  22255. */
  22256. forge$9.debug.get = function(cat, name) {
  22257. var rval;
  22258. if(typeof(cat) === 'undefined') {
  22259. rval = forge$9.debug.storage;
  22260. } else if(cat in forge$9.debug.storage) {
  22261. if(typeof(name) === 'undefined') {
  22262. rval = forge$9.debug.storage[cat];
  22263. } else {
  22264. rval = forge$9.debug.storage[cat][name];
  22265. }
  22266. }
  22267. return rval;
  22268. };
  22269. /**
  22270. * Sets debug data.
  22271. *
  22272. * @param cat name of debugging category.
  22273. * @param name name of data to set.
  22274. * @param data data to set.
  22275. */
  22276. forge$9.debug.set = function(cat, name, data) {
  22277. if(!(cat in forge$9.debug.storage)) {
  22278. forge$9.debug.storage[cat] = {};
  22279. }
  22280. forge$9.debug.storage[cat][name] = data;
  22281. };
  22282. /**
  22283. * Clears debug data. Omit name for all cat data. Omit name and cat for
  22284. * all data.
  22285. *
  22286. * @param cat name of debugging category.
  22287. * @param name name of data to clear or omit to clear entire category.
  22288. */
  22289. forge$9.debug.clear = function(cat, name) {
  22290. if(typeof(cat) === 'undefined') {
  22291. forge$9.debug.storage = {};
  22292. } else if(cat in forge$9.debug.storage) {
  22293. if(typeof(name) === 'undefined') {
  22294. delete forge$9.debug.storage[cat];
  22295. } else {
  22296. delete forge$9.debug.storage[cat][name];
  22297. }
  22298. }
  22299. };
  22300. /**
  22301. * Secure Hash Algorithm with a 1024-bit block size implementation.
  22302. *
  22303. * This includes: SHA-512, SHA-384, SHA-512/224, and SHA-512/256. For
  22304. * SHA-256 (block size 512 bits), see sha256.js.
  22305. *
  22306. * See FIPS 180-4 for details.
  22307. *
  22308. * @author Dave Longley
  22309. *
  22310. * Copyright (c) 2014-2015 Digital Bazaar, Inc.
  22311. */
  22312. var forge$8 = forge$F;
  22313. var sha512$1 = forge$8.sha512 = forge$8.sha512 || {};
  22314. // SHA-512
  22315. forge$8.md.sha512 = forge$8.md.algorithms.sha512 = sha512$1;
  22316. // SHA-384
  22317. var sha384 = forge$8.sha384 = forge$8.sha512.sha384 = forge$8.sha512.sha384 || {};
  22318. sha384.create = function() {
  22319. return sha512$1.create('SHA-384');
  22320. };
  22321. forge$8.md.sha384 = forge$8.md.algorithms.sha384 = sha384;
  22322. // SHA-512/256
  22323. forge$8.sha512.sha256 = forge$8.sha512.sha256 || {
  22324. create: function() {
  22325. return sha512$1.create('SHA-512/256');
  22326. }
  22327. };
  22328. forge$8.md['sha512/256'] = forge$8.md.algorithms['sha512/256'] =
  22329. forge$8.sha512.sha256;
  22330. // SHA-512/224
  22331. forge$8.sha512.sha224 = forge$8.sha512.sha224 || {
  22332. create: function() {
  22333. return sha512$1.create('SHA-512/224');
  22334. }
  22335. };
  22336. forge$8.md['sha512/224'] = forge$8.md.algorithms['sha512/224'] =
  22337. forge$8.sha512.sha224;
  22338. /**
  22339. * Creates a SHA-2 message digest object.
  22340. *
  22341. * @param algorithm the algorithm to use (SHA-512, SHA-384, SHA-512/224,
  22342. * SHA-512/256).
  22343. *
  22344. * @return a message digest object.
  22345. */
  22346. sha512$1.create = function(algorithm) {
  22347. // do initialization as necessary
  22348. if(!_initialized) {
  22349. _init();
  22350. }
  22351. if(typeof algorithm === 'undefined') {
  22352. algorithm = 'SHA-512';
  22353. }
  22354. if(!(algorithm in _states)) {
  22355. throw new Error('Invalid SHA-512 algorithm: ' + algorithm);
  22356. }
  22357. // SHA-512 state contains eight 64-bit integers (each as two 32-bit ints)
  22358. var _state = _states[algorithm];
  22359. var _h = null;
  22360. // input buffer
  22361. var _input = forge$8.util.createBuffer();
  22362. // used for 64-bit word storage
  22363. var _w = new Array(80);
  22364. for(var wi = 0; wi < 80; ++wi) {
  22365. _w[wi] = new Array(2);
  22366. }
  22367. // determine digest length by algorithm name (default)
  22368. var digestLength = 64;
  22369. switch(algorithm) {
  22370. case 'SHA-384':
  22371. digestLength = 48;
  22372. break;
  22373. case 'SHA-512/256':
  22374. digestLength = 32;
  22375. break;
  22376. case 'SHA-512/224':
  22377. digestLength = 28;
  22378. break;
  22379. }
  22380. // message digest object
  22381. var md = {
  22382. // SHA-512 => sha512
  22383. algorithm: algorithm.replace('-', '').toLowerCase(),
  22384. blockLength: 128,
  22385. digestLength: digestLength,
  22386. // 56-bit length of message so far (does not including padding)
  22387. messageLength: 0,
  22388. // true message length
  22389. fullMessageLength: null,
  22390. // size of message length in bytes
  22391. messageLengthSize: 16
  22392. };
  22393. /**
  22394. * Starts the digest.
  22395. *
  22396. * @return this digest object.
  22397. */
  22398. md.start = function() {
  22399. // up to 56-bit message length for convenience
  22400. md.messageLength = 0;
  22401. // full message length (set md.messageLength128 for backwards-compatibility)
  22402. md.fullMessageLength = md.messageLength128 = [];
  22403. var int32s = md.messageLengthSize / 4;
  22404. for(var i = 0; i < int32s; ++i) {
  22405. md.fullMessageLength.push(0);
  22406. }
  22407. _input = forge$8.util.createBuffer();
  22408. _h = new Array(_state.length);
  22409. for(var i = 0; i < _state.length; ++i) {
  22410. _h[i] = _state[i].slice(0);
  22411. }
  22412. return md;
  22413. };
  22414. // start digest automatically for first time
  22415. md.start();
  22416. /**
  22417. * Updates the digest with the given message input. The given input can
  22418. * treated as raw input (no encoding will be applied) or an encoding of
  22419. * 'utf8' maybe given to encode the input using UTF-8.
  22420. *
  22421. * @param msg the message input to update with.
  22422. * @param encoding the encoding to use (default: 'raw', other: 'utf8').
  22423. *
  22424. * @return this digest object.
  22425. */
  22426. md.update = function(msg, encoding) {
  22427. if(encoding === 'utf8') {
  22428. msg = forge$8.util.encodeUtf8(msg);
  22429. }
  22430. // update message length
  22431. var len = msg.length;
  22432. md.messageLength += len;
  22433. len = [(len / 0x100000000) >>> 0, len >>> 0];
  22434. for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {
  22435. md.fullMessageLength[i] += len[1];
  22436. len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);
  22437. md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;
  22438. len[0] = ((len[1] / 0x100000000) >>> 0);
  22439. }
  22440. // add bytes to input buffer
  22441. _input.putBytes(msg);
  22442. // process bytes
  22443. _update(_h, _w, _input);
  22444. // compact input buffer every 2K or if empty
  22445. if(_input.read > 2048 || _input.length() === 0) {
  22446. _input.compact();
  22447. }
  22448. return md;
  22449. };
  22450. /**
  22451. * Produces the digest.
  22452. *
  22453. * @return a byte buffer containing the digest value.
  22454. */
  22455. md.digest = function() {
  22456. /* Note: Here we copy the remaining bytes in the input buffer and
  22457. add the appropriate SHA-512 padding. Then we do the final update
  22458. on a copy of the state so that if the user wants to get
  22459. intermediate digests they can do so. */
  22460. /* Determine the number of bytes that must be added to the message
  22461. to ensure its length is congruent to 896 mod 1024. In other words,
  22462. the data to be digested must be a multiple of 1024 bits (or 128 bytes).
  22463. This data includes the message, some padding, and the length of the
  22464. message. Since the length of the message will be encoded as 16 bytes (128
  22465. bits), that means that the last segment of the data must have 112 bytes
  22466. (896 bits) of message and padding. Therefore, the length of the message
  22467. plus the padding must be congruent to 896 mod 1024 because
  22468. 1024 - 128 = 896.
  22469. In order to fill up the message length it must be filled with
  22470. padding that begins with 1 bit followed by all 0 bits. Padding
  22471. must *always* be present, so if the message length is already
  22472. congruent to 896 mod 1024, then 1024 padding bits must be added. */
  22473. var finalBlock = forge$8.util.createBuffer();
  22474. finalBlock.putBytes(_input.bytes());
  22475. // compute remaining size to be digested (include message length size)
  22476. var remaining = (
  22477. md.fullMessageLength[md.fullMessageLength.length - 1] +
  22478. md.messageLengthSize);
  22479. // add padding for overflow blockSize - overflow
  22480. // _padding starts with 1 byte with first bit is set (byte value 128), then
  22481. // there may be up to (blockSize - 1) other pad bytes
  22482. var overflow = remaining & (md.blockLength - 1);
  22483. finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));
  22484. // serialize message length in bits in big-endian order; since length
  22485. // is stored in bytes we multiply by 8 and add carry from next int
  22486. var next, carry;
  22487. var bits = md.fullMessageLength[0] * 8;
  22488. for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {
  22489. next = md.fullMessageLength[i + 1] * 8;
  22490. carry = (next / 0x100000000) >>> 0;
  22491. bits += carry;
  22492. finalBlock.putInt32(bits >>> 0);
  22493. bits = next >>> 0;
  22494. }
  22495. finalBlock.putInt32(bits);
  22496. var h = new Array(_h.length);
  22497. for(var i = 0; i < _h.length; ++i) {
  22498. h[i] = _h[i].slice(0);
  22499. }
  22500. _update(h, _w, finalBlock);
  22501. var rval = forge$8.util.createBuffer();
  22502. var hlen;
  22503. if(algorithm === 'SHA-512') {
  22504. hlen = h.length;
  22505. } else if(algorithm === 'SHA-384') {
  22506. hlen = h.length - 2;
  22507. } else {
  22508. hlen = h.length - 4;
  22509. }
  22510. for(var i = 0; i < hlen; ++i) {
  22511. rval.putInt32(h[i][0]);
  22512. if(i !== hlen - 1 || algorithm !== 'SHA-512/224') {
  22513. rval.putInt32(h[i][1]);
  22514. }
  22515. }
  22516. return rval;
  22517. };
  22518. return md;
  22519. };
  22520. // sha-512 padding bytes not initialized yet
  22521. var _padding = null;
  22522. var _initialized = false;
  22523. // table of constants
  22524. var _k = null;
  22525. // initial hash states
  22526. var _states = null;
  22527. /**
  22528. * Initializes the constant tables.
  22529. */
  22530. function _init() {
  22531. // create padding
  22532. _padding = String.fromCharCode(128);
  22533. _padding += forge$8.util.fillString(String.fromCharCode(0x00), 128);
  22534. // create K table for SHA-512
  22535. _k = [
  22536. [0x428a2f98, 0xd728ae22], [0x71374491, 0x23ef65cd],
  22537. [0xb5c0fbcf, 0xec4d3b2f], [0xe9b5dba5, 0x8189dbbc],
  22538. [0x3956c25b, 0xf348b538], [0x59f111f1, 0xb605d019],
  22539. [0x923f82a4, 0xaf194f9b], [0xab1c5ed5, 0xda6d8118],
  22540. [0xd807aa98, 0xa3030242], [0x12835b01, 0x45706fbe],
  22541. [0x243185be, 0x4ee4b28c], [0x550c7dc3, 0xd5ffb4e2],
  22542. [0x72be5d74, 0xf27b896f], [0x80deb1fe, 0x3b1696b1],
  22543. [0x9bdc06a7, 0x25c71235], [0xc19bf174, 0xcf692694],
  22544. [0xe49b69c1, 0x9ef14ad2], [0xefbe4786, 0x384f25e3],
  22545. [0x0fc19dc6, 0x8b8cd5b5], [0x240ca1cc, 0x77ac9c65],
  22546. [0x2de92c6f, 0x592b0275], [0x4a7484aa, 0x6ea6e483],
  22547. [0x5cb0a9dc, 0xbd41fbd4], [0x76f988da, 0x831153b5],
  22548. [0x983e5152, 0xee66dfab], [0xa831c66d, 0x2db43210],
  22549. [0xb00327c8, 0x98fb213f], [0xbf597fc7, 0xbeef0ee4],
  22550. [0xc6e00bf3, 0x3da88fc2], [0xd5a79147, 0x930aa725],
  22551. [0x06ca6351, 0xe003826f], [0x14292967, 0x0a0e6e70],
  22552. [0x27b70a85, 0x46d22ffc], [0x2e1b2138, 0x5c26c926],
  22553. [0x4d2c6dfc, 0x5ac42aed], [0x53380d13, 0x9d95b3df],
  22554. [0x650a7354, 0x8baf63de], [0x766a0abb, 0x3c77b2a8],
  22555. [0x81c2c92e, 0x47edaee6], [0x92722c85, 0x1482353b],
  22556. [0xa2bfe8a1, 0x4cf10364], [0xa81a664b, 0xbc423001],
  22557. [0xc24b8b70, 0xd0f89791], [0xc76c51a3, 0x0654be30],
  22558. [0xd192e819, 0xd6ef5218], [0xd6990624, 0x5565a910],
  22559. [0xf40e3585, 0x5771202a], [0x106aa070, 0x32bbd1b8],
  22560. [0x19a4c116, 0xb8d2d0c8], [0x1e376c08, 0x5141ab53],
  22561. [0x2748774c, 0xdf8eeb99], [0x34b0bcb5, 0xe19b48a8],
  22562. [0x391c0cb3, 0xc5c95a63], [0x4ed8aa4a, 0xe3418acb],
  22563. [0x5b9cca4f, 0x7763e373], [0x682e6ff3, 0xd6b2b8a3],
  22564. [0x748f82ee, 0x5defb2fc], [0x78a5636f, 0x43172f60],
  22565. [0x84c87814, 0xa1f0ab72], [0x8cc70208, 0x1a6439ec],
  22566. [0x90befffa, 0x23631e28], [0xa4506ceb, 0xde82bde9],
  22567. [0xbef9a3f7, 0xb2c67915], [0xc67178f2, 0xe372532b],
  22568. [0xca273ece, 0xea26619c], [0xd186b8c7, 0x21c0c207],
  22569. [0xeada7dd6, 0xcde0eb1e], [0xf57d4f7f, 0xee6ed178],
  22570. [0x06f067aa, 0x72176fba], [0x0a637dc5, 0xa2c898a6],
  22571. [0x113f9804, 0xbef90dae], [0x1b710b35, 0x131c471b],
  22572. [0x28db77f5, 0x23047d84], [0x32caab7b, 0x40c72493],
  22573. [0x3c9ebe0a, 0x15c9bebc], [0x431d67c4, 0x9c100d4c],
  22574. [0x4cc5d4be, 0xcb3e42b6], [0x597f299c, 0xfc657e2a],
  22575. [0x5fcb6fab, 0x3ad6faec], [0x6c44198c, 0x4a475817]
  22576. ];
  22577. // initial hash states
  22578. _states = {};
  22579. _states['SHA-512'] = [
  22580. [0x6a09e667, 0xf3bcc908],
  22581. [0xbb67ae85, 0x84caa73b],
  22582. [0x3c6ef372, 0xfe94f82b],
  22583. [0xa54ff53a, 0x5f1d36f1],
  22584. [0x510e527f, 0xade682d1],
  22585. [0x9b05688c, 0x2b3e6c1f],
  22586. [0x1f83d9ab, 0xfb41bd6b],
  22587. [0x5be0cd19, 0x137e2179]
  22588. ];
  22589. _states['SHA-384'] = [
  22590. [0xcbbb9d5d, 0xc1059ed8],
  22591. [0x629a292a, 0x367cd507],
  22592. [0x9159015a, 0x3070dd17],
  22593. [0x152fecd8, 0xf70e5939],
  22594. [0x67332667, 0xffc00b31],
  22595. [0x8eb44a87, 0x68581511],
  22596. [0xdb0c2e0d, 0x64f98fa7],
  22597. [0x47b5481d, 0xbefa4fa4]
  22598. ];
  22599. _states['SHA-512/256'] = [
  22600. [0x22312194, 0xFC2BF72C],
  22601. [0x9F555FA3, 0xC84C64C2],
  22602. [0x2393B86B, 0x6F53B151],
  22603. [0x96387719, 0x5940EABD],
  22604. [0x96283EE2, 0xA88EFFE3],
  22605. [0xBE5E1E25, 0x53863992],
  22606. [0x2B0199FC, 0x2C85B8AA],
  22607. [0x0EB72DDC, 0x81C52CA2]
  22608. ];
  22609. _states['SHA-512/224'] = [
  22610. [0x8C3D37C8, 0x19544DA2],
  22611. [0x73E19966, 0x89DCD4D6],
  22612. [0x1DFAB7AE, 0x32FF9C82],
  22613. [0x679DD514, 0x582F9FCF],
  22614. [0x0F6D2B69, 0x7BD44DA8],
  22615. [0x77E36F73, 0x04C48942],
  22616. [0x3F9D85A8, 0x6A1D36C8],
  22617. [0x1112E6AD, 0x91D692A1]
  22618. ];
  22619. // now initialized
  22620. _initialized = true;
  22621. }
  22622. /**
  22623. * Updates a SHA-512 state with the given byte buffer.
  22624. *
  22625. * @param s the SHA-512 state to update.
  22626. * @param w the array to use to store words.
  22627. * @param bytes the byte buffer to update with.
  22628. */
  22629. function _update(s, w, bytes) {
  22630. // consume 512 bit (128 byte) chunks
  22631. var t1_hi, t1_lo;
  22632. var t2_hi, t2_lo;
  22633. var s0_hi, s0_lo;
  22634. var s1_hi, s1_lo;
  22635. var ch_hi, ch_lo;
  22636. var maj_hi, maj_lo;
  22637. var a_hi, a_lo;
  22638. var b_hi, b_lo;
  22639. var c_hi, c_lo;
  22640. var d_hi, d_lo;
  22641. var e_hi, e_lo;
  22642. var f_hi, f_lo;
  22643. var g_hi, g_lo;
  22644. var h_hi, h_lo;
  22645. var i, hi, lo, w2, w7, w15, w16;
  22646. var len = bytes.length();
  22647. while(len >= 128) {
  22648. // the w array will be populated with sixteen 64-bit big-endian words
  22649. // and then extended into 64 64-bit words according to SHA-512
  22650. for(i = 0; i < 16; ++i) {
  22651. w[i][0] = bytes.getInt32() >>> 0;
  22652. w[i][1] = bytes.getInt32() >>> 0;
  22653. }
  22654. for(; i < 80; ++i) {
  22655. // for word 2 words ago: ROTR 19(x) ^ ROTR 61(x) ^ SHR 6(x)
  22656. w2 = w[i - 2];
  22657. hi = w2[0];
  22658. lo = w2[1];
  22659. // high bits
  22660. t1_hi = (
  22661. ((hi >>> 19) | (lo << 13)) ^ // ROTR 19
  22662. ((lo >>> 29) | (hi << 3)) ^ // ROTR 61/(swap + ROTR 29)
  22663. (hi >>> 6)) >>> 0; // SHR 6
  22664. // low bits
  22665. t1_lo = (
  22666. ((hi << 13) | (lo >>> 19)) ^ // ROTR 19
  22667. ((lo << 3) | (hi >>> 29)) ^ // ROTR 61/(swap + ROTR 29)
  22668. ((hi << 26) | (lo >>> 6))) >>> 0; // SHR 6
  22669. // for word 15 words ago: ROTR 1(x) ^ ROTR 8(x) ^ SHR 7(x)
  22670. w15 = w[i - 15];
  22671. hi = w15[0];
  22672. lo = w15[1];
  22673. // high bits
  22674. t2_hi = (
  22675. ((hi >>> 1) | (lo << 31)) ^ // ROTR 1
  22676. ((hi >>> 8) | (lo << 24)) ^ // ROTR 8
  22677. (hi >>> 7)) >>> 0; // SHR 7
  22678. // low bits
  22679. t2_lo = (
  22680. ((hi << 31) | (lo >>> 1)) ^ // ROTR 1
  22681. ((hi << 24) | (lo >>> 8)) ^ // ROTR 8
  22682. ((hi << 25) | (lo >>> 7))) >>> 0; // SHR 7
  22683. // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^64 (carry lo overflow)
  22684. w7 = w[i - 7];
  22685. w16 = w[i - 16];
  22686. lo = (t1_lo + w7[1] + t2_lo + w16[1]);
  22687. w[i][0] = (t1_hi + w7[0] + t2_hi + w16[0] +
  22688. ((lo / 0x100000000) >>> 0)) >>> 0;
  22689. w[i][1] = lo >>> 0;
  22690. }
  22691. // initialize hash value for this chunk
  22692. a_hi = s[0][0];
  22693. a_lo = s[0][1];
  22694. b_hi = s[1][0];
  22695. b_lo = s[1][1];
  22696. c_hi = s[2][0];
  22697. c_lo = s[2][1];
  22698. d_hi = s[3][0];
  22699. d_lo = s[3][1];
  22700. e_hi = s[4][0];
  22701. e_lo = s[4][1];
  22702. f_hi = s[5][0];
  22703. f_lo = s[5][1];
  22704. g_hi = s[6][0];
  22705. g_lo = s[6][1];
  22706. h_hi = s[7][0];
  22707. h_lo = s[7][1];
  22708. // round function
  22709. for(i = 0; i < 80; ++i) {
  22710. // Sum1(e) = ROTR 14(e) ^ ROTR 18(e) ^ ROTR 41(e)
  22711. s1_hi = (
  22712. ((e_hi >>> 14) | (e_lo << 18)) ^ // ROTR 14
  22713. ((e_hi >>> 18) | (e_lo << 14)) ^ // ROTR 18
  22714. ((e_lo >>> 9) | (e_hi << 23))) >>> 0; // ROTR 41/(swap + ROTR 9)
  22715. s1_lo = (
  22716. ((e_hi << 18) | (e_lo >>> 14)) ^ // ROTR 14
  22717. ((e_hi << 14) | (e_lo >>> 18)) ^ // ROTR 18
  22718. ((e_lo << 23) | (e_hi >>> 9))) >>> 0; // ROTR 41/(swap + ROTR 9)
  22719. // Ch(e, f, g) (optimized the same way as SHA-1)
  22720. ch_hi = (g_hi ^ (e_hi & (f_hi ^ g_hi))) >>> 0;
  22721. ch_lo = (g_lo ^ (e_lo & (f_lo ^ g_lo))) >>> 0;
  22722. // Sum0(a) = ROTR 28(a) ^ ROTR 34(a) ^ ROTR 39(a)
  22723. s0_hi = (
  22724. ((a_hi >>> 28) | (a_lo << 4)) ^ // ROTR 28
  22725. ((a_lo >>> 2) | (a_hi << 30)) ^ // ROTR 34/(swap + ROTR 2)
  22726. ((a_lo >>> 7) | (a_hi << 25))) >>> 0; // ROTR 39/(swap + ROTR 7)
  22727. s0_lo = (
  22728. ((a_hi << 4) | (a_lo >>> 28)) ^ // ROTR 28
  22729. ((a_lo << 30) | (a_hi >>> 2)) ^ // ROTR 34/(swap + ROTR 2)
  22730. ((a_lo << 25) | (a_hi >>> 7))) >>> 0; // ROTR 39/(swap + ROTR 7)
  22731. // Maj(a, b, c) (optimized the same way as SHA-1)
  22732. maj_hi = ((a_hi & b_hi) | (c_hi & (a_hi ^ b_hi))) >>> 0;
  22733. maj_lo = ((a_lo & b_lo) | (c_lo & (a_lo ^ b_lo))) >>> 0;
  22734. // main algorithm
  22735. // t1 = (h + s1 + ch + _k[i] + _w[i]) modulo 2^64 (carry lo overflow)
  22736. lo = (h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]);
  22737. t1_hi = (h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] +
  22738. ((lo / 0x100000000) >>> 0)) >>> 0;
  22739. t1_lo = lo >>> 0;
  22740. // t2 = s0 + maj modulo 2^64 (carry lo overflow)
  22741. lo = s0_lo + maj_lo;
  22742. t2_hi = (s0_hi + maj_hi + ((lo / 0x100000000) >>> 0)) >>> 0;
  22743. t2_lo = lo >>> 0;
  22744. h_hi = g_hi;
  22745. h_lo = g_lo;
  22746. g_hi = f_hi;
  22747. g_lo = f_lo;
  22748. f_hi = e_hi;
  22749. f_lo = e_lo;
  22750. // e = (d + t1) modulo 2^64 (carry lo overflow)
  22751. lo = d_lo + t1_lo;
  22752. e_hi = (d_hi + t1_hi + ((lo / 0x100000000) >>> 0)) >>> 0;
  22753. e_lo = lo >>> 0;
  22754. d_hi = c_hi;
  22755. d_lo = c_lo;
  22756. c_hi = b_hi;
  22757. c_lo = b_lo;
  22758. b_hi = a_hi;
  22759. b_lo = a_lo;
  22760. // a = (t1 + t2) modulo 2^64 (carry lo overflow)
  22761. lo = t1_lo + t2_lo;
  22762. a_hi = (t1_hi + t2_hi + ((lo / 0x100000000) >>> 0)) >>> 0;
  22763. a_lo = lo >>> 0;
  22764. }
  22765. // update hash state (additional modulo 2^64)
  22766. lo = s[0][1] + a_lo;
  22767. s[0][0] = (s[0][0] + a_hi + ((lo / 0x100000000) >>> 0)) >>> 0;
  22768. s[0][1] = lo >>> 0;
  22769. lo = s[1][1] + b_lo;
  22770. s[1][0] = (s[1][0] + b_hi + ((lo / 0x100000000) >>> 0)) >>> 0;
  22771. s[1][1] = lo >>> 0;
  22772. lo = s[2][1] + c_lo;
  22773. s[2][0] = (s[2][0] + c_hi + ((lo / 0x100000000) >>> 0)) >>> 0;
  22774. s[2][1] = lo >>> 0;
  22775. lo = s[3][1] + d_lo;
  22776. s[3][0] = (s[3][0] + d_hi + ((lo / 0x100000000) >>> 0)) >>> 0;
  22777. s[3][1] = lo >>> 0;
  22778. lo = s[4][1] + e_lo;
  22779. s[4][0] = (s[4][0] + e_hi + ((lo / 0x100000000) >>> 0)) >>> 0;
  22780. s[4][1] = lo >>> 0;
  22781. lo = s[5][1] + f_lo;
  22782. s[5][0] = (s[5][0] + f_hi + ((lo / 0x100000000) >>> 0)) >>> 0;
  22783. s[5][1] = lo >>> 0;
  22784. lo = s[6][1] + g_lo;
  22785. s[6][0] = (s[6][0] + g_hi + ((lo / 0x100000000) >>> 0)) >>> 0;
  22786. s[6][1] = lo >>> 0;
  22787. lo = s[7][1] + h_lo;
  22788. s[7][0] = (s[7][0] + h_hi + ((lo / 0x100000000) >>> 0)) >>> 0;
  22789. s[7][1] = lo >>> 0;
  22790. len -= 128;
  22791. }
  22792. }
  22793. var asn1Validator$1 = {};
  22794. /**
  22795. * Copyright (c) 2019 Digital Bazaar, Inc.
  22796. */
  22797. var forge$7 = forge$F;
  22798. var asn1$1 = forge$7.asn1;
  22799. asn1Validator$1.privateKeyValidator = {
  22800. // PrivateKeyInfo
  22801. name: 'PrivateKeyInfo',
  22802. tagClass: asn1$1.Class.UNIVERSAL,
  22803. type: asn1$1.Type.SEQUENCE,
  22804. constructed: true,
  22805. value: [{
  22806. // Version (INTEGER)
  22807. name: 'PrivateKeyInfo.version',
  22808. tagClass: asn1$1.Class.UNIVERSAL,
  22809. type: asn1$1.Type.INTEGER,
  22810. constructed: false,
  22811. capture: 'privateKeyVersion'
  22812. }, {
  22813. // privateKeyAlgorithm
  22814. name: 'PrivateKeyInfo.privateKeyAlgorithm',
  22815. tagClass: asn1$1.Class.UNIVERSAL,
  22816. type: asn1$1.Type.SEQUENCE,
  22817. constructed: true,
  22818. value: [{
  22819. name: 'AlgorithmIdentifier.algorithm',
  22820. tagClass: asn1$1.Class.UNIVERSAL,
  22821. type: asn1$1.Type.OID,
  22822. constructed: false,
  22823. capture: 'privateKeyOid'
  22824. }]
  22825. }, {
  22826. // PrivateKey
  22827. name: 'PrivateKeyInfo',
  22828. tagClass: asn1$1.Class.UNIVERSAL,
  22829. type: asn1$1.Type.OCTETSTRING,
  22830. constructed: false,
  22831. capture: 'privateKey'
  22832. }]
  22833. };
  22834. asn1Validator$1.publicKeyValidator = {
  22835. name: 'SubjectPublicKeyInfo',
  22836. tagClass: asn1$1.Class.UNIVERSAL,
  22837. type: asn1$1.Type.SEQUENCE,
  22838. constructed: true,
  22839. captureAsn1: 'subjectPublicKeyInfo',
  22840. value: [{
  22841. name: 'SubjectPublicKeyInfo.AlgorithmIdentifier',
  22842. tagClass: asn1$1.Class.UNIVERSAL,
  22843. type: asn1$1.Type.SEQUENCE,
  22844. constructed: true,
  22845. value: [{
  22846. name: 'AlgorithmIdentifier.algorithm',
  22847. tagClass: asn1$1.Class.UNIVERSAL,
  22848. type: asn1$1.Type.OID,
  22849. constructed: false,
  22850. capture: 'publicKeyOid'
  22851. }]
  22852. },
  22853. // capture group for ed25519PublicKey
  22854. {
  22855. tagClass: asn1$1.Class.UNIVERSAL,
  22856. type: asn1$1.Type.BITSTRING,
  22857. constructed: false,
  22858. composed: true,
  22859. captureBitStringValue: 'ed25519PublicKey'
  22860. }
  22861. // FIXME: this is capture group for rsaPublicKey, use it in this API or
  22862. // discard?
  22863. /* {
  22864. // subjectPublicKey
  22865. name: 'SubjectPublicKeyInfo.subjectPublicKey',
  22866. tagClass: asn1.Class.UNIVERSAL,
  22867. type: asn1.Type.BITSTRING,
  22868. constructed: false,
  22869. value: [{
  22870. // RSAPublicKey
  22871. name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey',
  22872. tagClass: asn1.Class.UNIVERSAL,
  22873. type: asn1.Type.SEQUENCE,
  22874. constructed: true,
  22875. optional: true,
  22876. captureAsn1: 'rsaPublicKey'
  22877. }]
  22878. } */
  22879. ]
  22880. };
  22881. /**
  22882. * JavaScript implementation of Ed25519.
  22883. *
  22884. * Copyright (c) 2017-2019 Digital Bazaar, Inc.
  22885. *
  22886. * This implementation is based on the most excellent TweetNaCl which is
  22887. * in the public domain. Many thanks to its contributors:
  22888. *
  22889. * https://github.com/dchest/tweetnacl-js
  22890. */
  22891. var forge$6 = forge$F;
  22892. var asn1Validator = asn1Validator$1;
  22893. var publicKeyValidator = asn1Validator.publicKeyValidator;
  22894. var privateKeyValidator = asn1Validator.privateKeyValidator;
  22895. var ByteBuffer = forge$6.util.ByteBuffer;
  22896. var NativeBuffer = typeof Buffer === 'undefined' ? Uint8Array : Buffer;
  22897. /*
  22898. * Ed25519 algorithms, see RFC 8032:
  22899. * https://tools.ietf.org/html/rfc8032
  22900. */
  22901. forge$6.pki = forge$6.pki || {};
  22902. forge$6.pki.ed25519 = forge$6.ed25519 = forge$6.ed25519 || {};
  22903. var ed25519 = forge$6.ed25519;
  22904. ed25519.constants = {};
  22905. ed25519.constants.PUBLIC_KEY_BYTE_LENGTH = 32;
  22906. ed25519.constants.PRIVATE_KEY_BYTE_LENGTH = 64;
  22907. ed25519.constants.SEED_BYTE_LENGTH = 32;
  22908. ed25519.constants.SIGN_BYTE_LENGTH = 64;
  22909. ed25519.constants.HASH_BYTE_LENGTH = 64;
  22910. ed25519.generateKeyPair = function(options) {
  22911. options = options || {};
  22912. var seed = options.seed;
  22913. if(seed === undefined) {
  22914. // generate seed
  22915. seed = forge$6.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH);
  22916. } else if(typeof seed === 'string') {
  22917. if(seed.length !== ed25519.constants.SEED_BYTE_LENGTH) {
  22918. throw new TypeError(
  22919. '"seed" must be ' + ed25519.constants.SEED_BYTE_LENGTH +
  22920. ' bytes in length.');
  22921. }
  22922. } else if(!(seed instanceof Uint8Array)) {
  22923. throw new TypeError(
  22924. '"seed" must be a node.js Buffer, Uint8Array, or a binary string.');
  22925. }
  22926. seed = messageToNativeBuffer({message: seed, encoding: 'binary'});
  22927. var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);
  22928. var sk = new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);
  22929. for(var i = 0; i < 32; ++i) {
  22930. sk[i] = seed[i];
  22931. }
  22932. crypto_sign_keypair(pk, sk);
  22933. return {publicKey: pk, privateKey: sk};
  22934. };
  22935. /**
  22936. * Converts a private key from a RFC8410 ASN.1 encoding.
  22937. *
  22938. * @param obj - The asn1 representation of a private key.
  22939. *
  22940. * @returns {Object} keyInfo - The key information.
  22941. * @returns {Buffer|Uint8Array} keyInfo.privateKeyBytes - 32 private key bytes.
  22942. */
  22943. ed25519.privateKeyFromAsn1 = function(obj) {
  22944. var capture = {};
  22945. var errors = [];
  22946. var valid = forge$6.asn1.validate(obj, privateKeyValidator, capture, errors);
  22947. if(!valid) {
  22948. var error = new Error('Invalid Key.');
  22949. error.errors = errors;
  22950. throw error;
  22951. }
  22952. var oid = forge$6.asn1.derToOid(capture.privateKeyOid);
  22953. var ed25519Oid = forge$6.oids.EdDSA25519;
  22954. if(oid !== ed25519Oid) {
  22955. throw new Error('Invalid OID "' + oid + '"; OID must be "' +
  22956. ed25519Oid + '".');
  22957. }
  22958. var privateKey = capture.privateKey;
  22959. // manually extract the private key bytes from nested octet string, see FIXME:
  22960. // https://github.com/digitalbazaar/forge/blob/master/lib/asn1.js#L542
  22961. var privateKeyBytes = messageToNativeBuffer({
  22962. message: forge$6.asn1.fromDer(privateKey).value,
  22963. encoding: 'binary'
  22964. });
  22965. // TODO: RFC8410 specifies a format for encoding the public key bytes along
  22966. // with the private key bytes. `publicKeyBytes` can be returned in the
  22967. // future. https://tools.ietf.org/html/rfc8410#section-10.3
  22968. return {privateKeyBytes: privateKeyBytes};
  22969. };
  22970. /**
  22971. * Converts a public key from a RFC8410 ASN.1 encoding.
  22972. *
  22973. * @param obj - The asn1 representation of a public key.
  22974. *
  22975. * @return {Buffer|Uint8Array} - 32 public key bytes.
  22976. */
  22977. ed25519.publicKeyFromAsn1 = function(obj) {
  22978. // get SubjectPublicKeyInfo
  22979. var capture = {};
  22980. var errors = [];
  22981. var valid = forge$6.asn1.validate(obj, publicKeyValidator, capture, errors);
  22982. if(!valid) {
  22983. var error = new Error('Invalid Key.');
  22984. error.errors = errors;
  22985. throw error;
  22986. }
  22987. var oid = forge$6.asn1.derToOid(capture.publicKeyOid);
  22988. var ed25519Oid = forge$6.oids.EdDSA25519;
  22989. if(oid !== ed25519Oid) {
  22990. throw new Error('Invalid OID "' + oid + '"; OID must be "' +
  22991. ed25519Oid + '".');
  22992. }
  22993. var publicKeyBytes = capture.ed25519PublicKey;
  22994. if(publicKeyBytes.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) {
  22995. throw new Error('Key length is invalid.');
  22996. }
  22997. return messageToNativeBuffer({
  22998. message: publicKeyBytes,
  22999. encoding: 'binary'
  23000. });
  23001. };
  23002. ed25519.publicKeyFromPrivateKey = function(options) {
  23003. options = options || {};
  23004. var privateKey = messageToNativeBuffer({
  23005. message: options.privateKey, encoding: 'binary'
  23006. });
  23007. if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) {
  23008. throw new TypeError(
  23009. '"options.privateKey" must have a byte length of ' +
  23010. ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);
  23011. }
  23012. var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);
  23013. for(var i = 0; i < pk.length; ++i) {
  23014. pk[i] = privateKey[32 + i];
  23015. }
  23016. return pk;
  23017. };
  23018. ed25519.sign = function(options) {
  23019. options = options || {};
  23020. var msg = messageToNativeBuffer(options);
  23021. var privateKey = messageToNativeBuffer({
  23022. message: options.privateKey,
  23023. encoding: 'binary'
  23024. });
  23025. if(privateKey.length === ed25519.constants.SEED_BYTE_LENGTH) {
  23026. var keyPair = ed25519.generateKeyPair({seed: privateKey});
  23027. privateKey = keyPair.privateKey;
  23028. } else if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) {
  23029. throw new TypeError(
  23030. '"options.privateKey" must have a byte length of ' +
  23031. ed25519.constants.SEED_BYTE_LENGTH + ' or ' +
  23032. ed25519.constants.PRIVATE_KEY_BYTE_LENGTH);
  23033. }
  23034. var signedMsg = new NativeBuffer(
  23035. ed25519.constants.SIGN_BYTE_LENGTH + msg.length);
  23036. crypto_sign(signedMsg, msg, msg.length, privateKey);
  23037. var sig = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH);
  23038. for(var i = 0; i < sig.length; ++i) {
  23039. sig[i] = signedMsg[i];
  23040. }
  23041. return sig;
  23042. };
  23043. ed25519.verify = function(options) {
  23044. options = options || {};
  23045. var msg = messageToNativeBuffer(options);
  23046. if(options.signature === undefined) {
  23047. throw new TypeError(
  23048. '"options.signature" must be a node.js Buffer, a Uint8Array, a forge ' +
  23049. 'ByteBuffer, or a binary string.');
  23050. }
  23051. var sig = messageToNativeBuffer({
  23052. message: options.signature,
  23053. encoding: 'binary'
  23054. });
  23055. if(sig.length !== ed25519.constants.SIGN_BYTE_LENGTH) {
  23056. throw new TypeError(
  23057. '"options.signature" must have a byte length of ' +
  23058. ed25519.constants.SIGN_BYTE_LENGTH);
  23059. }
  23060. var publicKey = messageToNativeBuffer({
  23061. message: options.publicKey,
  23062. encoding: 'binary'
  23063. });
  23064. if(publicKey.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) {
  23065. throw new TypeError(
  23066. '"options.publicKey" must have a byte length of ' +
  23067. ed25519.constants.PUBLIC_KEY_BYTE_LENGTH);
  23068. }
  23069. var sm = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length);
  23070. var m = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length);
  23071. var i;
  23072. for(i = 0; i < ed25519.constants.SIGN_BYTE_LENGTH; ++i) {
  23073. sm[i] = sig[i];
  23074. }
  23075. for(i = 0; i < msg.length; ++i) {
  23076. sm[i + ed25519.constants.SIGN_BYTE_LENGTH] = msg[i];
  23077. }
  23078. return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);
  23079. };
  23080. function messageToNativeBuffer(options) {
  23081. var message = options.message;
  23082. if(message instanceof Uint8Array || message instanceof NativeBuffer) {
  23083. return message;
  23084. }
  23085. var encoding = options.encoding;
  23086. if(message === undefined) {
  23087. if(options.md) {
  23088. // TODO: more rigorous validation that `md` is a MessageDigest
  23089. message = options.md.digest().getBytes();
  23090. encoding = 'binary';
  23091. } else {
  23092. throw new TypeError('"options.message" or "options.md" not specified.');
  23093. }
  23094. }
  23095. if(typeof message === 'string' && !encoding) {
  23096. throw new TypeError('"options.encoding" must be "binary" or "utf8".');
  23097. }
  23098. if(typeof message === 'string') {
  23099. if(typeof Buffer !== 'undefined') {
  23100. return Buffer.from(message, encoding);
  23101. }
  23102. message = new ByteBuffer(message, encoding);
  23103. } else if(!(message instanceof ByteBuffer)) {
  23104. throw new TypeError(
  23105. '"options.message" must be a node.js Buffer, a Uint8Array, a forge ' +
  23106. 'ByteBuffer, or a string with "options.encoding" specifying its ' +
  23107. 'encoding.');
  23108. }
  23109. // convert to native buffer
  23110. var buffer = new NativeBuffer(message.length());
  23111. for(var i = 0; i < buffer.length; ++i) {
  23112. buffer[i] = message.at(i);
  23113. }
  23114. return buffer;
  23115. }
  23116. var gf0 = gf();
  23117. var gf1 = gf([1]);
  23118. var D = gf([
  23119. 0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070,
  23120. 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]);
  23121. var D2 = gf([
  23122. 0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0,
  23123. 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]);
  23124. var X = gf([
  23125. 0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c,
  23126. 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]);
  23127. var Y = gf([
  23128. 0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666,
  23129. 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]);
  23130. var L = new Float64Array([
  23131. 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58,
  23132. 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,
  23133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]);
  23134. var I = gf([
  23135. 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43,
  23136. 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);
  23137. // TODO: update forge buffer implementation to use `Buffer` or `Uint8Array`,
  23138. // whichever is available, to improve performance
  23139. function sha512(msg, msgLen) {
  23140. // Note: `out` and `msg` are NativeBuffer
  23141. var md = forge$6.md.sha512.create();
  23142. var buffer = new ByteBuffer(msg);
  23143. md.update(buffer.getBytes(msgLen), 'binary');
  23144. var hash = md.digest().getBytes();
  23145. if(typeof Buffer !== 'undefined') {
  23146. return Buffer.from(hash, 'binary');
  23147. }
  23148. var out = new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH);
  23149. for(var i = 0; i < 64; ++i) {
  23150. out[i] = hash.charCodeAt(i);
  23151. }
  23152. return out;
  23153. }
  23154. function crypto_sign_keypair(pk, sk) {
  23155. var p = [gf(), gf(), gf(), gf()];
  23156. var i;
  23157. var d = sha512(sk, 32);
  23158. d[0] &= 248;
  23159. d[31] &= 127;
  23160. d[31] |= 64;
  23161. scalarbase(p, d);
  23162. pack(pk, p);
  23163. for(i = 0; i < 32; ++i) {
  23164. sk[i + 32] = pk[i];
  23165. }
  23166. return 0;
  23167. }
  23168. // Note: difference from C - smlen returned, not passed as argument.
  23169. function crypto_sign(sm, m, n, sk) {
  23170. var i, j, x = new Float64Array(64);
  23171. var p = [gf(), gf(), gf(), gf()];
  23172. var d = sha512(sk, 32);
  23173. d[0] &= 248;
  23174. d[31] &= 127;
  23175. d[31] |= 64;
  23176. var smlen = n + 64;
  23177. for(i = 0; i < n; ++i) {
  23178. sm[64 + i] = m[i];
  23179. }
  23180. for(i = 0; i < 32; ++i) {
  23181. sm[32 + i] = d[32 + i];
  23182. }
  23183. var r = sha512(sm.subarray(32), n + 32);
  23184. reduce(r);
  23185. scalarbase(p, r);
  23186. pack(sm, p);
  23187. for(i = 32; i < 64; ++i) {
  23188. sm[i] = sk[i];
  23189. }
  23190. var h = sha512(sm, n + 64);
  23191. reduce(h);
  23192. for(i = 32; i < 64; ++i) {
  23193. x[i] = 0;
  23194. }
  23195. for(i = 0; i < 32; ++i) {
  23196. x[i] = r[i];
  23197. }
  23198. for(i = 0; i < 32; ++i) {
  23199. for(j = 0; j < 32; j++) {
  23200. x[i + j] += h[i] * d[j];
  23201. }
  23202. }
  23203. modL(sm.subarray(32), x);
  23204. return smlen;
  23205. }
  23206. function crypto_sign_open(m, sm, n, pk) {
  23207. var i, mlen;
  23208. var t = new NativeBuffer(32);
  23209. var p = [gf(), gf(), gf(), gf()],
  23210. q = [gf(), gf(), gf(), gf()];
  23211. mlen = -1;
  23212. if(n < 64) {
  23213. return -1;
  23214. }
  23215. if(unpackneg(q, pk)) {
  23216. return -1;
  23217. }
  23218. for(i = 0; i < n; ++i) {
  23219. m[i] = sm[i];
  23220. }
  23221. for(i = 0; i < 32; ++i) {
  23222. m[i + 32] = pk[i];
  23223. }
  23224. var h = sha512(m, n);
  23225. reduce(h);
  23226. scalarmult(p, q, h);
  23227. scalarbase(q, sm.subarray(32));
  23228. add(p, q);
  23229. pack(t, p);
  23230. n -= 64;
  23231. if(crypto_verify_32(sm, 0, t, 0)) {
  23232. for(i = 0; i < n; ++i) {
  23233. m[i] = 0;
  23234. }
  23235. return -1;
  23236. }
  23237. for(i = 0; i < n; ++i) {
  23238. m[i] = sm[i + 64];
  23239. }
  23240. mlen = n;
  23241. return mlen;
  23242. }
  23243. function modL(r, x) {
  23244. var carry, i, j, k;
  23245. for(i = 63; i >= 32; --i) {
  23246. carry = 0;
  23247. for(j = i - 32, k = i - 12; j < k; ++j) {
  23248. x[j] += carry - 16 * x[i] * L[j - (i - 32)];
  23249. carry = (x[j] + 128) >> 8;
  23250. x[j] -= carry * 256;
  23251. }
  23252. x[j] += carry;
  23253. x[i] = 0;
  23254. }
  23255. carry = 0;
  23256. for(j = 0; j < 32; ++j) {
  23257. x[j] += carry - (x[31] >> 4) * L[j];
  23258. carry = x[j] >> 8;
  23259. x[j] &= 255;
  23260. }
  23261. for(j = 0; j < 32; ++j) {
  23262. x[j] -= carry * L[j];
  23263. }
  23264. for(i = 0; i < 32; ++i) {
  23265. x[i + 1] += x[i] >> 8;
  23266. r[i] = x[i] & 255;
  23267. }
  23268. }
  23269. function reduce(r) {
  23270. var x = new Float64Array(64);
  23271. for(var i = 0; i < 64; ++i) {
  23272. x[i] = r[i];
  23273. r[i] = 0;
  23274. }
  23275. modL(r, x);
  23276. }
  23277. function add(p, q) {
  23278. var a = gf(), b = gf(), c = gf(),
  23279. d = gf(), e = gf(), f = gf(),
  23280. g = gf(), h = gf(), t = gf();
  23281. Z(a, p[1], p[0]);
  23282. Z(t, q[1], q[0]);
  23283. M(a, a, t);
  23284. A(b, p[0], p[1]);
  23285. A(t, q[0], q[1]);
  23286. M(b, b, t);
  23287. M(c, p[3], q[3]);
  23288. M(c, c, D2);
  23289. M(d, p[2], q[2]);
  23290. A(d, d, d);
  23291. Z(e, b, a);
  23292. Z(f, d, c);
  23293. A(g, d, c);
  23294. A(h, b, a);
  23295. M(p[0], e, f);
  23296. M(p[1], h, g);
  23297. M(p[2], g, f);
  23298. M(p[3], e, h);
  23299. }
  23300. function cswap(p, q, b) {
  23301. for(var i = 0; i < 4; ++i) {
  23302. sel25519(p[i], q[i], b);
  23303. }
  23304. }
  23305. function pack(r, p) {
  23306. var tx = gf(), ty = gf(), zi = gf();
  23307. inv25519(zi, p[2]);
  23308. M(tx, p[0], zi);
  23309. M(ty, p[1], zi);
  23310. pack25519(r, ty);
  23311. r[31] ^= par25519(tx) << 7;
  23312. }
  23313. function pack25519(o, n) {
  23314. var i, j, b;
  23315. var m = gf(), t = gf();
  23316. for(i = 0; i < 16; ++i) {
  23317. t[i] = n[i];
  23318. }
  23319. car25519(t);
  23320. car25519(t);
  23321. car25519(t);
  23322. for(j = 0; j < 2; ++j) {
  23323. m[0] = t[0] - 0xffed;
  23324. for(i = 1; i < 15; ++i) {
  23325. m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1);
  23326. m[i-1] &= 0xffff;
  23327. }
  23328. m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1);
  23329. b = (m[15] >> 16) & 1;
  23330. m[14] &= 0xffff;
  23331. sel25519(t, m, 1 - b);
  23332. }
  23333. for (i = 0; i < 16; i++) {
  23334. o[2 * i] = t[i] & 0xff;
  23335. o[2 * i + 1] = t[i] >> 8;
  23336. }
  23337. }
  23338. function unpackneg(r, p) {
  23339. var t = gf(), chk = gf(), num = gf(),
  23340. den = gf(), den2 = gf(), den4 = gf(),
  23341. den6 = gf();
  23342. set25519(r[2], gf1);
  23343. unpack25519(r[1], p);
  23344. S(num, r[1]);
  23345. M(den, num, D);
  23346. Z(num, num, r[2]);
  23347. A(den, r[2], den);
  23348. S(den2, den);
  23349. S(den4, den2);
  23350. M(den6, den4, den2);
  23351. M(t, den6, num);
  23352. M(t, t, den);
  23353. pow2523(t, t);
  23354. M(t, t, num);
  23355. M(t, t, den);
  23356. M(t, t, den);
  23357. M(r[0], t, den);
  23358. S(chk, r[0]);
  23359. M(chk, chk, den);
  23360. if(neq25519(chk, num)) {
  23361. M(r[0], r[0], I);
  23362. }
  23363. S(chk, r[0]);
  23364. M(chk, chk, den);
  23365. if(neq25519(chk, num)) {
  23366. return -1;
  23367. }
  23368. if(par25519(r[0]) === (p[31] >> 7)) {
  23369. Z(r[0], gf0, r[0]);
  23370. }
  23371. M(r[3], r[0], r[1]);
  23372. return 0;
  23373. }
  23374. function unpack25519(o, n) {
  23375. var i;
  23376. for(i = 0; i < 16; ++i) {
  23377. o[i] = n[2 * i] + (n[2 * i + 1] << 8);
  23378. }
  23379. o[15] &= 0x7fff;
  23380. }
  23381. function pow2523(o, i) {
  23382. var c = gf();
  23383. var a;
  23384. for(a = 0; a < 16; ++a) {
  23385. c[a] = i[a];
  23386. }
  23387. for(a = 250; a >= 0; --a) {
  23388. S(c, c);
  23389. if(a !== 1) {
  23390. M(c, c, i);
  23391. }
  23392. }
  23393. for(a = 0; a < 16; ++a) {
  23394. o[a] = c[a];
  23395. }
  23396. }
  23397. function neq25519(a, b) {
  23398. var c = new NativeBuffer(32);
  23399. var d = new NativeBuffer(32);
  23400. pack25519(c, a);
  23401. pack25519(d, b);
  23402. return crypto_verify_32(c, 0, d, 0);
  23403. }
  23404. function crypto_verify_32(x, xi, y, yi) {
  23405. return vn(x, xi, y, yi, 32);
  23406. }
  23407. function vn(x, xi, y, yi, n) {
  23408. var i, d = 0;
  23409. for(i = 0; i < n; ++i) {
  23410. d |= x[xi + i] ^ y[yi + i];
  23411. }
  23412. return (1 & ((d - 1) >>> 8)) - 1;
  23413. }
  23414. function par25519(a) {
  23415. var d = new NativeBuffer(32);
  23416. pack25519(d, a);
  23417. return d[0] & 1;
  23418. }
  23419. function scalarmult(p, q, s) {
  23420. var b, i;
  23421. set25519(p[0], gf0);
  23422. set25519(p[1], gf1);
  23423. set25519(p[2], gf1);
  23424. set25519(p[3], gf0);
  23425. for(i = 255; i >= 0; --i) {
  23426. b = (s[(i / 8)|0] >> (i & 7)) & 1;
  23427. cswap(p, q, b);
  23428. add(q, p);
  23429. add(p, p);
  23430. cswap(p, q, b);
  23431. }
  23432. }
  23433. function scalarbase(p, s) {
  23434. var q = [gf(), gf(), gf(), gf()];
  23435. set25519(q[0], X);
  23436. set25519(q[1], Y);
  23437. set25519(q[2], gf1);
  23438. M(q[3], X, Y);
  23439. scalarmult(p, q, s);
  23440. }
  23441. function set25519(r, a) {
  23442. var i;
  23443. for(i = 0; i < 16; i++) {
  23444. r[i] = a[i] | 0;
  23445. }
  23446. }
  23447. function inv25519(o, i) {
  23448. var c = gf();
  23449. var a;
  23450. for(a = 0; a < 16; ++a) {
  23451. c[a] = i[a];
  23452. }
  23453. for(a = 253; a >= 0; --a) {
  23454. S(c, c);
  23455. if(a !== 2 && a !== 4) {
  23456. M(c, c, i);
  23457. }
  23458. }
  23459. for(a = 0; a < 16; ++a) {
  23460. o[a] = c[a];
  23461. }
  23462. }
  23463. function car25519(o) {
  23464. var i, v, c = 1;
  23465. for(i = 0; i < 16; ++i) {
  23466. v = o[i] + c + 65535;
  23467. c = Math.floor(v / 65536);
  23468. o[i] = v - c * 65536;
  23469. }
  23470. o[0] += c - 1 + 37 * (c - 1);
  23471. }
  23472. function sel25519(p, q, b) {
  23473. var t, c = ~(b - 1);
  23474. for(var i = 0; i < 16; ++i) {
  23475. t = c & (p[i] ^ q[i]);
  23476. p[i] ^= t;
  23477. q[i] ^= t;
  23478. }
  23479. }
  23480. function gf(init) {
  23481. var i, r = new Float64Array(16);
  23482. if(init) {
  23483. for(i = 0; i < init.length; ++i) {
  23484. r[i] = init[i];
  23485. }
  23486. }
  23487. return r;
  23488. }
  23489. function A(o, a, b) {
  23490. for(var i = 0; i < 16; ++i) {
  23491. o[i] = a[i] + b[i];
  23492. }
  23493. }
  23494. function Z(o, a, b) {
  23495. for(var i = 0; i < 16; ++i) {
  23496. o[i] = a[i] - b[i];
  23497. }
  23498. }
  23499. function S(o, a) {
  23500. M(o, a, a);
  23501. }
  23502. function M(o, a, b) {
  23503. var v, c,
  23504. t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,
  23505. t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,
  23506. t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,
  23507. t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,
  23508. b0 = b[0],
  23509. b1 = b[1],
  23510. b2 = b[2],
  23511. b3 = b[3],
  23512. b4 = b[4],
  23513. b5 = b[5],
  23514. b6 = b[6],
  23515. b7 = b[7],
  23516. b8 = b[8],
  23517. b9 = b[9],
  23518. b10 = b[10],
  23519. b11 = b[11],
  23520. b12 = b[12],
  23521. b13 = b[13],
  23522. b14 = b[14],
  23523. b15 = b[15];
  23524. v = a[0];
  23525. t0 += v * b0;
  23526. t1 += v * b1;
  23527. t2 += v * b2;
  23528. t3 += v * b3;
  23529. t4 += v * b4;
  23530. t5 += v * b5;
  23531. t6 += v * b6;
  23532. t7 += v * b7;
  23533. t8 += v * b8;
  23534. t9 += v * b9;
  23535. t10 += v * b10;
  23536. t11 += v * b11;
  23537. t12 += v * b12;
  23538. t13 += v * b13;
  23539. t14 += v * b14;
  23540. t15 += v * b15;
  23541. v = a[1];
  23542. t1 += v * b0;
  23543. t2 += v * b1;
  23544. t3 += v * b2;
  23545. t4 += v * b3;
  23546. t5 += v * b4;
  23547. t6 += v * b5;
  23548. t7 += v * b6;
  23549. t8 += v * b7;
  23550. t9 += v * b8;
  23551. t10 += v * b9;
  23552. t11 += v * b10;
  23553. t12 += v * b11;
  23554. t13 += v * b12;
  23555. t14 += v * b13;
  23556. t15 += v * b14;
  23557. t16 += v * b15;
  23558. v = a[2];
  23559. t2 += v * b0;
  23560. t3 += v * b1;
  23561. t4 += v * b2;
  23562. t5 += v * b3;
  23563. t6 += v * b4;
  23564. t7 += v * b5;
  23565. t8 += v * b6;
  23566. t9 += v * b7;
  23567. t10 += v * b8;
  23568. t11 += v * b9;
  23569. t12 += v * b10;
  23570. t13 += v * b11;
  23571. t14 += v * b12;
  23572. t15 += v * b13;
  23573. t16 += v * b14;
  23574. t17 += v * b15;
  23575. v = a[3];
  23576. t3 += v * b0;
  23577. t4 += v * b1;
  23578. t5 += v * b2;
  23579. t6 += v * b3;
  23580. t7 += v * b4;
  23581. t8 += v * b5;
  23582. t9 += v * b6;
  23583. t10 += v * b7;
  23584. t11 += v * b8;
  23585. t12 += v * b9;
  23586. t13 += v * b10;
  23587. t14 += v * b11;
  23588. t15 += v * b12;
  23589. t16 += v * b13;
  23590. t17 += v * b14;
  23591. t18 += v * b15;
  23592. v = a[4];
  23593. t4 += v * b0;
  23594. t5 += v * b1;
  23595. t6 += v * b2;
  23596. t7 += v * b3;
  23597. t8 += v * b4;
  23598. t9 += v * b5;
  23599. t10 += v * b6;
  23600. t11 += v * b7;
  23601. t12 += v * b8;
  23602. t13 += v * b9;
  23603. t14 += v * b10;
  23604. t15 += v * b11;
  23605. t16 += v * b12;
  23606. t17 += v * b13;
  23607. t18 += v * b14;
  23608. t19 += v * b15;
  23609. v = a[5];
  23610. t5 += v * b0;
  23611. t6 += v * b1;
  23612. t7 += v * b2;
  23613. t8 += v * b3;
  23614. t9 += v * b4;
  23615. t10 += v * b5;
  23616. t11 += v * b6;
  23617. t12 += v * b7;
  23618. t13 += v * b8;
  23619. t14 += v * b9;
  23620. t15 += v * b10;
  23621. t16 += v * b11;
  23622. t17 += v * b12;
  23623. t18 += v * b13;
  23624. t19 += v * b14;
  23625. t20 += v * b15;
  23626. v = a[6];
  23627. t6 += v * b0;
  23628. t7 += v * b1;
  23629. t8 += v * b2;
  23630. t9 += v * b3;
  23631. t10 += v * b4;
  23632. t11 += v * b5;
  23633. t12 += v * b6;
  23634. t13 += v * b7;
  23635. t14 += v * b8;
  23636. t15 += v * b9;
  23637. t16 += v * b10;
  23638. t17 += v * b11;
  23639. t18 += v * b12;
  23640. t19 += v * b13;
  23641. t20 += v * b14;
  23642. t21 += v * b15;
  23643. v = a[7];
  23644. t7 += v * b0;
  23645. t8 += v * b1;
  23646. t9 += v * b2;
  23647. t10 += v * b3;
  23648. t11 += v * b4;
  23649. t12 += v * b5;
  23650. t13 += v * b6;
  23651. t14 += v * b7;
  23652. t15 += v * b8;
  23653. t16 += v * b9;
  23654. t17 += v * b10;
  23655. t18 += v * b11;
  23656. t19 += v * b12;
  23657. t20 += v * b13;
  23658. t21 += v * b14;
  23659. t22 += v * b15;
  23660. v = a[8];
  23661. t8 += v * b0;
  23662. t9 += v * b1;
  23663. t10 += v * b2;
  23664. t11 += v * b3;
  23665. t12 += v * b4;
  23666. t13 += v * b5;
  23667. t14 += v * b6;
  23668. t15 += v * b7;
  23669. t16 += v * b8;
  23670. t17 += v * b9;
  23671. t18 += v * b10;
  23672. t19 += v * b11;
  23673. t20 += v * b12;
  23674. t21 += v * b13;
  23675. t22 += v * b14;
  23676. t23 += v * b15;
  23677. v = a[9];
  23678. t9 += v * b0;
  23679. t10 += v * b1;
  23680. t11 += v * b2;
  23681. t12 += v * b3;
  23682. t13 += v * b4;
  23683. t14 += v * b5;
  23684. t15 += v * b6;
  23685. t16 += v * b7;
  23686. t17 += v * b8;
  23687. t18 += v * b9;
  23688. t19 += v * b10;
  23689. t20 += v * b11;
  23690. t21 += v * b12;
  23691. t22 += v * b13;
  23692. t23 += v * b14;
  23693. t24 += v * b15;
  23694. v = a[10];
  23695. t10 += v * b0;
  23696. t11 += v * b1;
  23697. t12 += v * b2;
  23698. t13 += v * b3;
  23699. t14 += v * b4;
  23700. t15 += v * b5;
  23701. t16 += v * b6;
  23702. t17 += v * b7;
  23703. t18 += v * b8;
  23704. t19 += v * b9;
  23705. t20 += v * b10;
  23706. t21 += v * b11;
  23707. t22 += v * b12;
  23708. t23 += v * b13;
  23709. t24 += v * b14;
  23710. t25 += v * b15;
  23711. v = a[11];
  23712. t11 += v * b0;
  23713. t12 += v * b1;
  23714. t13 += v * b2;
  23715. t14 += v * b3;
  23716. t15 += v * b4;
  23717. t16 += v * b5;
  23718. t17 += v * b6;
  23719. t18 += v * b7;
  23720. t19 += v * b8;
  23721. t20 += v * b9;
  23722. t21 += v * b10;
  23723. t22 += v * b11;
  23724. t23 += v * b12;
  23725. t24 += v * b13;
  23726. t25 += v * b14;
  23727. t26 += v * b15;
  23728. v = a[12];
  23729. t12 += v * b0;
  23730. t13 += v * b1;
  23731. t14 += v * b2;
  23732. t15 += v * b3;
  23733. t16 += v * b4;
  23734. t17 += v * b5;
  23735. t18 += v * b6;
  23736. t19 += v * b7;
  23737. t20 += v * b8;
  23738. t21 += v * b9;
  23739. t22 += v * b10;
  23740. t23 += v * b11;
  23741. t24 += v * b12;
  23742. t25 += v * b13;
  23743. t26 += v * b14;
  23744. t27 += v * b15;
  23745. v = a[13];
  23746. t13 += v * b0;
  23747. t14 += v * b1;
  23748. t15 += v * b2;
  23749. t16 += v * b3;
  23750. t17 += v * b4;
  23751. t18 += v * b5;
  23752. t19 += v * b6;
  23753. t20 += v * b7;
  23754. t21 += v * b8;
  23755. t22 += v * b9;
  23756. t23 += v * b10;
  23757. t24 += v * b11;
  23758. t25 += v * b12;
  23759. t26 += v * b13;
  23760. t27 += v * b14;
  23761. t28 += v * b15;
  23762. v = a[14];
  23763. t14 += v * b0;
  23764. t15 += v * b1;
  23765. t16 += v * b2;
  23766. t17 += v * b3;
  23767. t18 += v * b4;
  23768. t19 += v * b5;
  23769. t20 += v * b6;
  23770. t21 += v * b7;
  23771. t22 += v * b8;
  23772. t23 += v * b9;
  23773. t24 += v * b10;
  23774. t25 += v * b11;
  23775. t26 += v * b12;
  23776. t27 += v * b13;
  23777. t28 += v * b14;
  23778. t29 += v * b15;
  23779. v = a[15];
  23780. t15 += v * b0;
  23781. t16 += v * b1;
  23782. t17 += v * b2;
  23783. t18 += v * b3;
  23784. t19 += v * b4;
  23785. t20 += v * b5;
  23786. t21 += v * b6;
  23787. t22 += v * b7;
  23788. t23 += v * b8;
  23789. t24 += v * b9;
  23790. t25 += v * b10;
  23791. t26 += v * b11;
  23792. t27 += v * b12;
  23793. t28 += v * b13;
  23794. t29 += v * b14;
  23795. t30 += v * b15;
  23796. t0 += 38 * t16;
  23797. t1 += 38 * t17;
  23798. t2 += 38 * t18;
  23799. t3 += 38 * t19;
  23800. t4 += 38 * t20;
  23801. t5 += 38 * t21;
  23802. t6 += 38 * t22;
  23803. t7 += 38 * t23;
  23804. t8 += 38 * t24;
  23805. t9 += 38 * t25;
  23806. t10 += 38 * t26;
  23807. t11 += 38 * t27;
  23808. t12 += 38 * t28;
  23809. t13 += 38 * t29;
  23810. t14 += 38 * t30;
  23811. // t15 left as is
  23812. // first car
  23813. c = 1;
  23814. v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
  23815. v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
  23816. v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
  23817. v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
  23818. v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
  23819. v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
  23820. v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
  23821. v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
  23822. v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
  23823. v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
  23824. v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
  23825. v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
  23826. v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
  23827. v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
  23828. v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
  23829. v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
  23830. t0 += c-1 + 37 * (c-1);
  23831. // second car
  23832. c = 1;
  23833. v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
  23834. v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
  23835. v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
  23836. v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
  23837. v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
  23838. v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
  23839. v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
  23840. v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
  23841. v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
  23842. v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
  23843. v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
  23844. v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
  23845. v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
  23846. v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
  23847. v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
  23848. v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
  23849. t0 += c-1 + 37 * (c-1);
  23850. o[ 0] = t0;
  23851. o[ 1] = t1;
  23852. o[ 2] = t2;
  23853. o[ 3] = t3;
  23854. o[ 4] = t4;
  23855. o[ 5] = t5;
  23856. o[ 6] = t6;
  23857. o[ 7] = t7;
  23858. o[ 8] = t8;
  23859. o[ 9] = t9;
  23860. o[10] = t10;
  23861. o[11] = t11;
  23862. o[12] = t12;
  23863. o[13] = t13;
  23864. o[14] = t14;
  23865. o[15] = t15;
  23866. }
  23867. /**
  23868. * Javascript implementation of RSA-KEM.
  23869. *
  23870. * @author Lautaro Cozzani Rodriguez
  23871. * @author Dave Longley
  23872. *
  23873. * Copyright (c) 2014 Lautaro Cozzani <lautaro.cozzani@scytl.com>
  23874. * Copyright (c) 2014 Digital Bazaar, Inc.
  23875. */
  23876. var forge$5 = forge$F;
  23877. forge$5.kem = forge$5.kem || {};
  23878. var BigInteger = forge$5.jsbn.BigInteger;
  23879. /**
  23880. * The API for the RSA Key Encapsulation Mechanism (RSA-KEM) from ISO 18033-2.
  23881. */
  23882. forge$5.kem.rsa = {};
  23883. /**
  23884. * Creates an RSA KEM API object for generating a secret asymmetric key.
  23885. *
  23886. * The symmetric key may be generated via a call to 'encrypt', which will
  23887. * produce a ciphertext to be transmitted to the recipient and a key to be
  23888. * kept secret. The ciphertext is a parameter to be passed to 'decrypt' which
  23889. * will produce the same secret key for the recipient to use to decrypt a
  23890. * message that was encrypted with the secret key.
  23891. *
  23892. * @param kdf the KDF API to use (eg: new forge.kem.kdf1()).
  23893. * @param options the options to use.
  23894. * [prng] a custom crypto-secure pseudo-random number generator to use,
  23895. * that must define "getBytesSync".
  23896. */
  23897. forge$5.kem.rsa.create = function(kdf, options) {
  23898. options = options || {};
  23899. var prng = options.prng || forge$5.random;
  23900. var kem = {};
  23901. /**
  23902. * Generates a secret key and its encapsulation.
  23903. *
  23904. * @param publicKey the RSA public key to encrypt with.
  23905. * @param keyLength the length, in bytes, of the secret key to generate.
  23906. *
  23907. * @return an object with:
  23908. * encapsulation: the ciphertext for generating the secret key, as a
  23909. * binary-encoded string of bytes.
  23910. * key: the secret key to use for encrypting a message.
  23911. */
  23912. kem.encrypt = function(publicKey, keyLength) {
  23913. // generate a random r where 1 < r < n
  23914. var byteLength = Math.ceil(publicKey.n.bitLength() / 8);
  23915. var r;
  23916. do {
  23917. r = new BigInteger(
  23918. forge$5.util.bytesToHex(prng.getBytesSync(byteLength)),
  23919. 16).mod(publicKey.n);
  23920. } while(r.compareTo(BigInteger.ONE) <= 0);
  23921. // prepend r with zeros
  23922. r = forge$5.util.hexToBytes(r.toString(16));
  23923. var zeros = byteLength - r.length;
  23924. if(zeros > 0) {
  23925. r = forge$5.util.fillString(String.fromCharCode(0), zeros) + r;
  23926. }
  23927. // encrypt the random
  23928. var encapsulation = publicKey.encrypt(r, 'NONE');
  23929. // generate the secret key
  23930. var key = kdf.generate(r, keyLength);
  23931. return {encapsulation: encapsulation, key: key};
  23932. };
  23933. /**
  23934. * Decrypts an encapsulated secret key.
  23935. *
  23936. * @param privateKey the RSA private key to decrypt with.
  23937. * @param encapsulation the ciphertext for generating the secret key, as
  23938. * a binary-encoded string of bytes.
  23939. * @param keyLength the length, in bytes, of the secret key to generate.
  23940. *
  23941. * @return the secret key as a binary-encoded string of bytes.
  23942. */
  23943. kem.decrypt = function(privateKey, encapsulation, keyLength) {
  23944. // decrypt the encapsulation and generate the secret key
  23945. var r = privateKey.decrypt(encapsulation, 'NONE');
  23946. return kdf.generate(r, keyLength);
  23947. };
  23948. return kem;
  23949. };
  23950. // TODO: add forge.kem.kdf.create('KDF1', {md: ..., ...}) API?
  23951. /**
  23952. * Creates a key derivation API object that implements KDF1 per ISO 18033-2.
  23953. *
  23954. * @param md the hash API to use.
  23955. * @param [digestLength] an optional digest length that must be positive and
  23956. * less than or equal to md.digestLength.
  23957. *
  23958. * @return a KDF1 API object.
  23959. */
  23960. forge$5.kem.kdf1 = function(md, digestLength) {
  23961. _createKDF(this, md, 0, digestLength || md.digestLength);
  23962. };
  23963. /**
  23964. * Creates a key derivation API object that implements KDF2 per ISO 18033-2.
  23965. *
  23966. * @param md the hash API to use.
  23967. * @param [digestLength] an optional digest length that must be positive and
  23968. * less than or equal to md.digestLength.
  23969. *
  23970. * @return a KDF2 API object.
  23971. */
  23972. forge$5.kem.kdf2 = function(md, digestLength) {
  23973. _createKDF(this, md, 1, digestLength || md.digestLength);
  23974. };
  23975. /**
  23976. * Creates a KDF1 or KDF2 API object.
  23977. *
  23978. * @param md the hash API to use.
  23979. * @param counterStart the starting index for the counter.
  23980. * @param digestLength the digest length to use.
  23981. *
  23982. * @return the KDF API object.
  23983. */
  23984. function _createKDF(kdf, md, counterStart, digestLength) {
  23985. /**
  23986. * Generate a key of the specified length.
  23987. *
  23988. * @param x the binary-encoded byte string to generate a key from.
  23989. * @param length the number of bytes to generate (the size of the key).
  23990. *
  23991. * @return the key as a binary-encoded string.
  23992. */
  23993. kdf.generate = function(x, length) {
  23994. var key = new forge$5.util.ByteBuffer();
  23995. // run counter from counterStart to ceil(length / Hash.len)
  23996. var k = Math.ceil(length / digestLength) + counterStart;
  23997. var c = new forge$5.util.ByteBuffer();
  23998. for(var i = counterStart; i < k; ++i) {
  23999. // I2OSP(i, 4): convert counter to an octet string of 4 octets
  24000. c.putInt32(i);
  24001. // digest 'x' and the counter and add the result to the key
  24002. md.start();
  24003. md.update(x + c.getBytes());
  24004. var hash = md.digest();
  24005. key.putBytes(hash.getBytes(digestLength));
  24006. }
  24007. // truncate to the correct key length
  24008. key.truncate(key.length() - length);
  24009. return key.getBytes();
  24010. };
  24011. }
  24012. /**
  24013. * Cross-browser support for logging in a web application.
  24014. *
  24015. * @author David I. Lehn <dlehn@digitalbazaar.com>
  24016. *
  24017. * Copyright (c) 2008-2013 Digital Bazaar, Inc.
  24018. */
  24019. var forge$4 = forge$F;
  24020. /* LOG API */
  24021. forge$4.log = forge$4.log || {};
  24022. /**
  24023. * Application logging system.
  24024. *
  24025. * Each logger level available as it's own function of the form:
  24026. * forge.log.level(category, args...)
  24027. * The category is an arbitrary string, and the args are the same as
  24028. * Firebug's console.log API. By default the call will be output as:
  24029. * 'LEVEL [category] <args[0]>, args[1], ...'
  24030. * This enables proper % formatting via the first argument.
  24031. * Each category is enabled by default but can be enabled or disabled with
  24032. * the setCategoryEnabled() function.
  24033. */
  24034. // list of known levels
  24035. forge$4.log.levels = [
  24036. 'none', 'error', 'warning', 'info', 'debug', 'verbose', 'max'];
  24037. // info on the levels indexed by name:
  24038. // index: level index
  24039. // name: uppercased display name
  24040. var sLevelInfo = {};
  24041. // list of loggers
  24042. var sLoggers = [];
  24043. /**
  24044. * Standard console logger. If no console support is enabled this will
  24045. * remain null. Check before using.
  24046. */
  24047. var sConsoleLogger = null;
  24048. // logger flags
  24049. /**
  24050. * Lock the level at the current value. Used in cases where user config may
  24051. * set the level such that only critical messages are seen but more verbose
  24052. * messages are needed for debugging or other purposes.
  24053. */
  24054. forge$4.log.LEVEL_LOCKED = (1 << 1);
  24055. /**
  24056. * Always call log function. By default, the logging system will check the
  24057. * message level against logger.level before calling the log function. This
  24058. * flag allows the function to do its own check.
  24059. */
  24060. forge$4.log.NO_LEVEL_CHECK = (1 << 2);
  24061. /**
  24062. * Perform message interpolation with the passed arguments. "%" style
  24063. * fields in log messages will be replaced by arguments as needed. Some
  24064. * loggers, such as Firebug, may do this automatically. The original log
  24065. * message will be available as 'message' and the interpolated version will
  24066. * be available as 'fullMessage'.
  24067. */
  24068. forge$4.log.INTERPOLATE = (1 << 3);
  24069. // setup each log level
  24070. for(var i = 0; i < forge$4.log.levels.length; ++i) {
  24071. var level = forge$4.log.levels[i];
  24072. sLevelInfo[level] = {
  24073. index: i,
  24074. name: level.toUpperCase()
  24075. };
  24076. }
  24077. /**
  24078. * Message logger. Will dispatch a message to registered loggers as needed.
  24079. *
  24080. * @param message message object
  24081. */
  24082. forge$4.log.logMessage = function(message) {
  24083. var messageLevelIndex = sLevelInfo[message.level].index;
  24084. for(var i = 0; i < sLoggers.length; ++i) {
  24085. var logger = sLoggers[i];
  24086. if(logger.flags & forge$4.log.NO_LEVEL_CHECK) {
  24087. logger.f(message);
  24088. } else {
  24089. // get logger level
  24090. var loggerLevelIndex = sLevelInfo[logger.level].index;
  24091. // check level
  24092. if(messageLevelIndex <= loggerLevelIndex) {
  24093. // message critical enough, call logger
  24094. logger.f(logger, message);
  24095. }
  24096. }
  24097. }
  24098. };
  24099. /**
  24100. * Sets the 'standard' key on a message object to:
  24101. * "LEVEL [category] " + message
  24102. *
  24103. * @param message a message log object
  24104. */
  24105. forge$4.log.prepareStandard = function(message) {
  24106. if(!('standard' in message)) {
  24107. message.standard =
  24108. sLevelInfo[message.level].name +
  24109. //' ' + +message.timestamp +
  24110. ' [' + message.category + '] ' +
  24111. message.message;
  24112. }
  24113. };
  24114. /**
  24115. * Sets the 'full' key on a message object to the original message
  24116. * interpolated via % formatting with the message arguments.
  24117. *
  24118. * @param message a message log object.
  24119. */
  24120. forge$4.log.prepareFull = function(message) {
  24121. if(!('full' in message)) {
  24122. // copy args and insert message at the front
  24123. var args = [message.message];
  24124. args = args.concat([] || message['arguments']);
  24125. // format the message
  24126. message.full = forge$4.util.format.apply(this, args);
  24127. }
  24128. };
  24129. /**
  24130. * Applies both preparseStandard() and prepareFull() to a message object and
  24131. * store result in 'standardFull'.
  24132. *
  24133. * @param message a message log object.
  24134. */
  24135. forge$4.log.prepareStandardFull = function(message) {
  24136. if(!('standardFull' in message)) {
  24137. // FIXME implement 'standardFull' logging
  24138. forge$4.log.prepareStandard(message);
  24139. message.standardFull = message.standard;
  24140. }
  24141. };
  24142. // create log level functions
  24143. {
  24144. // levels for which we want functions
  24145. var levels = ['error', 'warning', 'info', 'debug', 'verbose'];
  24146. for(var i = 0; i < levels.length; ++i) {
  24147. // wrap in a function to ensure proper level var is passed
  24148. (function(level) {
  24149. // create function for this level
  24150. forge$4.log[level] = function(category, message/*, args...*/) {
  24151. // convert arguments to real array, remove category and message
  24152. var args = Array.prototype.slice.call(arguments).slice(2);
  24153. // create message object
  24154. // Note: interpolation and standard formatting is done lazily
  24155. var msg = {
  24156. timestamp: new Date(),
  24157. level: level,
  24158. category: category,
  24159. message: message,
  24160. 'arguments': args
  24161. /*standard*/
  24162. /*full*/
  24163. /*fullMessage*/
  24164. };
  24165. // process this message
  24166. forge$4.log.logMessage(msg);
  24167. };
  24168. })(levels[i]);
  24169. }
  24170. }
  24171. /**
  24172. * Creates a new logger with specified custom logging function.
  24173. *
  24174. * The logging function has a signature of:
  24175. * function(logger, message)
  24176. * logger: current logger
  24177. * message: object:
  24178. * level: level id
  24179. * category: category
  24180. * message: string message
  24181. * arguments: Array of extra arguments
  24182. * fullMessage: interpolated message and arguments if INTERPOLATE flag set
  24183. *
  24184. * @param logFunction a logging function which takes a log message object
  24185. * as a parameter.
  24186. *
  24187. * @return a logger object.
  24188. */
  24189. forge$4.log.makeLogger = function(logFunction) {
  24190. var logger = {
  24191. flags: 0,
  24192. f: logFunction
  24193. };
  24194. forge$4.log.setLevel(logger, 'none');
  24195. return logger;
  24196. };
  24197. /**
  24198. * Sets the current log level on a logger.
  24199. *
  24200. * @param logger the target logger.
  24201. * @param level the new maximum log level as a string.
  24202. *
  24203. * @return true if set, false if not.
  24204. */
  24205. forge$4.log.setLevel = function(logger, level) {
  24206. var rval = false;
  24207. if(logger && !(logger.flags & forge$4.log.LEVEL_LOCKED)) {
  24208. for(var i = 0; i < forge$4.log.levels.length; ++i) {
  24209. var aValidLevel = forge$4.log.levels[i];
  24210. if(level == aValidLevel) {
  24211. // set level
  24212. logger.level = level;
  24213. rval = true;
  24214. break;
  24215. }
  24216. }
  24217. }
  24218. return rval;
  24219. };
  24220. /**
  24221. * Locks the log level at its current value.
  24222. *
  24223. * @param logger the target logger.
  24224. * @param lock boolean lock value, default to true.
  24225. */
  24226. forge$4.log.lock = function(logger, lock) {
  24227. if(typeof lock === 'undefined' || lock) {
  24228. logger.flags |= forge$4.log.LEVEL_LOCKED;
  24229. } else {
  24230. logger.flags &= ~forge$4.log.LEVEL_LOCKED;
  24231. }
  24232. };
  24233. /**
  24234. * Adds a logger.
  24235. *
  24236. * @param logger the logger object.
  24237. */
  24238. forge$4.log.addLogger = function(logger) {
  24239. sLoggers.push(logger);
  24240. };
  24241. // setup the console logger if possible, else create fake console.log
  24242. if(typeof(console) !== 'undefined' && 'log' in console) {
  24243. var logger;
  24244. if(console.error && console.warn && console.info && console.debug) {
  24245. // looks like Firebug-style logging is available
  24246. // level handlers map
  24247. var levelHandlers = {
  24248. error: console.error,
  24249. warning: console.warn,
  24250. info: console.info,
  24251. debug: console.debug,
  24252. verbose: console.debug
  24253. };
  24254. var f = function(logger, message) {
  24255. forge$4.log.prepareStandard(message);
  24256. var handler = levelHandlers[message.level];
  24257. // prepend standard message and concat args
  24258. var args = [message.standard];
  24259. args = args.concat(message['arguments'].slice());
  24260. // apply to low-level console function
  24261. handler.apply(console, args);
  24262. };
  24263. logger = forge$4.log.makeLogger(f);
  24264. } else {
  24265. // only appear to have basic console.log
  24266. var f = function(logger, message) {
  24267. forge$4.log.prepareStandardFull(message);
  24268. console.log(message.standardFull);
  24269. };
  24270. logger = forge$4.log.makeLogger(f);
  24271. }
  24272. forge$4.log.setLevel(logger, 'debug');
  24273. forge$4.log.addLogger(logger);
  24274. sConsoleLogger = logger;
  24275. } else {
  24276. // define fake console.log to avoid potential script errors on
  24277. // browsers that do not have console logging
  24278. console = {
  24279. log: function() {}
  24280. };
  24281. }
  24282. /*
  24283. * Check for logging control query vars.
  24284. *
  24285. * console.level=<level-name>
  24286. * Set's the console log level by name. Useful to override defaults and
  24287. * allow more verbose logging before a user config is loaded.
  24288. *
  24289. * console.lock=<true|false>
  24290. * Lock the console log level at whatever level it is set at. This is run
  24291. * after console.level is processed. Useful to force a level of verbosity
  24292. * that could otherwise be limited by a user config.
  24293. */
  24294. if(sConsoleLogger !== null) {
  24295. var query = forge$4.util.getQueryVariables();
  24296. if('console.level' in query) {
  24297. // set with last value
  24298. forge$4.log.setLevel(
  24299. sConsoleLogger, query['console.level'].slice(-1)[0]);
  24300. }
  24301. if('console.lock' in query) {
  24302. // set with last value
  24303. var lock = query['console.lock'].slice(-1)[0];
  24304. if(lock == 'true') {
  24305. forge$4.log.lock(sConsoleLogger);
  24306. }
  24307. }
  24308. }
  24309. // provide public access to console logger
  24310. forge$4.log.consoleLogger = sConsoleLogger;
  24311. /**
  24312. * Javascript implementation of PKCS#7 v1.5.
  24313. *
  24314. * @author Stefan Siegl
  24315. * @author Dave Longley
  24316. *
  24317. * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>
  24318. * Copyright (c) 2012-2015 Digital Bazaar, Inc.
  24319. *
  24320. * Currently this implementation only supports ContentType of EnvelopedData,
  24321. * EncryptedData, or SignedData at the root level. The top level elements may
  24322. * contain only a ContentInfo of ContentType Data, i.e. plain data. Further
  24323. * nesting is not (yet) supported.
  24324. *
  24325. * The Forge validators for PKCS #7's ASN.1 structures are available from
  24326. * a separate file pkcs7asn1.js, since those are referenced from other
  24327. * PKCS standards like PKCS #12.
  24328. */
  24329. var forge$3 = forge$F;
  24330. // shortcut for ASN.1 API
  24331. var asn1 = forge$3.asn1;
  24332. // shortcut for PKCS#7 API
  24333. var p7 = forge$3.pkcs7 = forge$3.pkcs7 || {};
  24334. /**
  24335. * Converts a PKCS#7 message from PEM format.
  24336. *
  24337. * @param pem the PEM-formatted PKCS#7 message.
  24338. *
  24339. * @return the PKCS#7 message.
  24340. */
  24341. p7.messageFromPem = function(pem) {
  24342. var msg = forge$3.pem.decode(pem)[0];
  24343. if(msg.type !== 'PKCS7') {
  24344. var error = new Error('Could not convert PKCS#7 message from PEM; PEM ' +
  24345. 'header type is not "PKCS#7".');
  24346. error.headerType = msg.type;
  24347. throw error;
  24348. }
  24349. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  24350. throw new Error('Could not convert PKCS#7 message from PEM; PEM is encrypted.');
  24351. }
  24352. // convert DER to ASN.1 object
  24353. var obj = asn1.fromDer(msg.body);
  24354. return p7.messageFromAsn1(obj);
  24355. };
  24356. /**
  24357. * Converts a PKCS#7 message to PEM format.
  24358. *
  24359. * @param msg The PKCS#7 message object
  24360. * @param maxline The maximum characters per line, defaults to 64.
  24361. *
  24362. * @return The PEM-formatted PKCS#7 message.
  24363. */
  24364. p7.messageToPem = function(msg, maxline) {
  24365. // convert to ASN.1, then DER, then PEM-encode
  24366. var pemObj = {
  24367. type: 'PKCS7',
  24368. body: asn1.toDer(msg.toAsn1()).getBytes()
  24369. };
  24370. return forge$3.pem.encode(pemObj, {maxline: maxline});
  24371. };
  24372. /**
  24373. * Converts a PKCS#7 message from an ASN.1 object.
  24374. *
  24375. * @param obj the ASN.1 representation of a ContentInfo.
  24376. *
  24377. * @return the PKCS#7 message.
  24378. */
  24379. p7.messageFromAsn1 = function(obj) {
  24380. // validate root level ContentInfo and capture data
  24381. var capture = {};
  24382. var errors = [];
  24383. if(!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) {
  24384. var error = new Error('Cannot read PKCS#7 message. ' +
  24385. 'ASN.1 object is not an PKCS#7 ContentInfo.');
  24386. error.errors = errors;
  24387. throw error;
  24388. }
  24389. var contentType = asn1.derToOid(capture.contentType);
  24390. var msg;
  24391. switch(contentType) {
  24392. case forge$3.pki.oids.envelopedData:
  24393. msg = p7.createEnvelopedData();
  24394. break;
  24395. case forge$3.pki.oids.encryptedData:
  24396. msg = p7.createEncryptedData();
  24397. break;
  24398. case forge$3.pki.oids.signedData:
  24399. msg = p7.createSignedData();
  24400. break;
  24401. default:
  24402. throw new Error('Cannot read PKCS#7 message. ContentType with OID ' +
  24403. contentType + ' is not (yet) supported.');
  24404. }
  24405. msg.fromAsn1(capture.content.value[0]);
  24406. return msg;
  24407. };
  24408. p7.createSignedData = function() {
  24409. var msg = null;
  24410. msg = {
  24411. type: forge$3.pki.oids.signedData,
  24412. version: 1,
  24413. certificates: [],
  24414. crls: [],
  24415. // TODO: add json-formatted signer stuff here?
  24416. signers: [],
  24417. // populated during sign()
  24418. digestAlgorithmIdentifiers: [],
  24419. contentInfo: null,
  24420. signerInfos: [],
  24421. fromAsn1: function(obj) {
  24422. // validate SignedData content block and capture data.
  24423. _fromAsn1(msg, obj, p7.asn1.signedDataValidator);
  24424. msg.certificates = [];
  24425. msg.crls = [];
  24426. msg.digestAlgorithmIdentifiers = [];
  24427. msg.contentInfo = null;
  24428. msg.signerInfos = [];
  24429. if(msg.rawCapture.certificates) {
  24430. var certs = msg.rawCapture.certificates.value;
  24431. for(var i = 0; i < certs.length; ++i) {
  24432. msg.certificates.push(forge$3.pki.certificateFromAsn1(certs[i]));
  24433. }
  24434. }
  24435. // TODO: parse crls
  24436. },
  24437. toAsn1: function() {
  24438. // degenerate case with no content
  24439. if(!msg.contentInfo) {
  24440. msg.sign();
  24441. }
  24442. var certs = [];
  24443. for(var i = 0; i < msg.certificates.length; ++i) {
  24444. certs.push(forge$3.pki.certificateToAsn1(msg.certificates[i]));
  24445. }
  24446. var crls = [];
  24447. // TODO: implement CRLs
  24448. // [0] SignedData
  24449. var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
  24450. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  24451. // Version
  24452. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  24453. asn1.integerToDer(msg.version).getBytes()),
  24454. // DigestAlgorithmIdentifiers
  24455. asn1.create(
  24456. asn1.Class.UNIVERSAL, asn1.Type.SET, true,
  24457. msg.digestAlgorithmIdentifiers),
  24458. // ContentInfo
  24459. msg.contentInfo
  24460. ])
  24461. ]);
  24462. if(certs.length > 0) {
  24463. // [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL
  24464. signedData.value[0].value.push(
  24465. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs));
  24466. }
  24467. if(crls.length > 0) {
  24468. // [1] IMPLICIT CertificateRevocationLists OPTIONAL
  24469. signedData.value[0].value.push(
  24470. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls));
  24471. }
  24472. // SignerInfos
  24473. signedData.value[0].value.push(
  24474. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true,
  24475. msg.signerInfos));
  24476. // ContentInfo
  24477. return asn1.create(
  24478. asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  24479. // ContentType
  24480. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  24481. asn1.oidToDer(msg.type).getBytes()),
  24482. // [0] SignedData
  24483. signedData
  24484. ]);
  24485. },
  24486. /**
  24487. * Add (another) entity to list of signers.
  24488. *
  24489. * Note: If authenticatedAttributes are provided, then, per RFC 2315,
  24490. * they must include at least two attributes: content type and
  24491. * message digest. The message digest attribute value will be
  24492. * auto-calculated during signing and will be ignored if provided.
  24493. *
  24494. * Here's an example of providing these two attributes:
  24495. *
  24496. * forge.pkcs7.createSignedData();
  24497. * p7.addSigner({
  24498. * issuer: cert.issuer.attributes,
  24499. * serialNumber: cert.serialNumber,
  24500. * key: privateKey,
  24501. * digestAlgorithm: forge.pki.oids.sha1,
  24502. * authenticatedAttributes: [{
  24503. * type: forge.pki.oids.contentType,
  24504. * value: forge.pki.oids.data
  24505. * }, {
  24506. * type: forge.pki.oids.messageDigest
  24507. * }]
  24508. * });
  24509. *
  24510. * TODO: Support [subjectKeyIdentifier] as signer's ID.
  24511. *
  24512. * @param signer the signer information:
  24513. * key the signer's private key.
  24514. * [certificate] a certificate containing the public key
  24515. * associated with the signer's private key; use this option as
  24516. * an alternative to specifying signer.issuer and
  24517. * signer.serialNumber.
  24518. * [issuer] the issuer attributes (eg: cert.issuer.attributes).
  24519. * [serialNumber] the signer's certificate's serial number in
  24520. * hexadecimal (eg: cert.serialNumber).
  24521. * [digestAlgorithm] the message digest OID, as a string, to use
  24522. * (eg: forge.pki.oids.sha1).
  24523. * [authenticatedAttributes] an optional array of attributes
  24524. * to also sign along with the content.
  24525. */
  24526. addSigner: function(signer) {
  24527. var issuer = signer.issuer;
  24528. var serialNumber = signer.serialNumber;
  24529. if(signer.certificate) {
  24530. var cert = signer.certificate;
  24531. if(typeof cert === 'string') {
  24532. cert = forge$3.pki.certificateFromPem(cert);
  24533. }
  24534. issuer = cert.issuer.attributes;
  24535. serialNumber = cert.serialNumber;
  24536. }
  24537. var key = signer.key;
  24538. if(!key) {
  24539. throw new Error(
  24540. 'Could not add PKCS#7 signer; no private key specified.');
  24541. }
  24542. if(typeof key === 'string') {
  24543. key = forge$3.pki.privateKeyFromPem(key);
  24544. }
  24545. // ensure OID known for digest algorithm
  24546. var digestAlgorithm = signer.digestAlgorithm || forge$3.pki.oids.sha1;
  24547. switch(digestAlgorithm) {
  24548. case forge$3.pki.oids.sha1:
  24549. case forge$3.pki.oids.sha256:
  24550. case forge$3.pki.oids.sha384:
  24551. case forge$3.pki.oids.sha512:
  24552. case forge$3.pki.oids.md5:
  24553. break;
  24554. default:
  24555. throw new Error(
  24556. 'Could not add PKCS#7 signer; unknown message digest algorithm: ' +
  24557. digestAlgorithm);
  24558. }
  24559. // if authenticatedAttributes is present, then the attributes
  24560. // must contain at least PKCS #9 content-type and message-digest
  24561. var authenticatedAttributes = signer.authenticatedAttributes || [];
  24562. if(authenticatedAttributes.length > 0) {
  24563. var contentType = false;
  24564. var messageDigest = false;
  24565. for(var i = 0; i < authenticatedAttributes.length; ++i) {
  24566. var attr = authenticatedAttributes[i];
  24567. if(!contentType && attr.type === forge$3.pki.oids.contentType) {
  24568. contentType = true;
  24569. if(messageDigest) {
  24570. break;
  24571. }
  24572. continue;
  24573. }
  24574. if(!messageDigest && attr.type === forge$3.pki.oids.messageDigest) {
  24575. messageDigest = true;
  24576. if(contentType) {
  24577. break;
  24578. }
  24579. continue;
  24580. }
  24581. }
  24582. if(!contentType || !messageDigest) {
  24583. throw new Error('Invalid signer.authenticatedAttributes. If ' +
  24584. 'signer.authenticatedAttributes is specified, then it must ' +
  24585. 'contain at least two attributes, PKCS #9 content-type and ' +
  24586. 'PKCS #9 message-digest.');
  24587. }
  24588. }
  24589. msg.signers.push({
  24590. key: key,
  24591. version: 1,
  24592. issuer: issuer,
  24593. serialNumber: serialNumber,
  24594. digestAlgorithm: digestAlgorithm,
  24595. signatureAlgorithm: forge$3.pki.oids.rsaEncryption,
  24596. signature: null,
  24597. authenticatedAttributes: authenticatedAttributes,
  24598. unauthenticatedAttributes: []
  24599. });
  24600. },
  24601. /**
  24602. * Signs the content.
  24603. * @param options Options to apply when signing:
  24604. * [detached] boolean. If signing should be done in detached mode. Defaults to false.
  24605. */
  24606. sign: function(options) {
  24607. options = options || {};
  24608. // auto-generate content info
  24609. if(typeof msg.content !== 'object' || msg.contentInfo === null) {
  24610. // use Data ContentInfo
  24611. msg.contentInfo = asn1.create(
  24612. asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  24613. // ContentType
  24614. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  24615. asn1.oidToDer(forge$3.pki.oids.data).getBytes())
  24616. ]);
  24617. // add actual content, if present
  24618. if('content' in msg) {
  24619. var content;
  24620. if(msg.content instanceof forge$3.util.ByteBuffer) {
  24621. content = msg.content.bytes();
  24622. } else if(typeof msg.content === 'string') {
  24623. content = forge$3.util.encodeUtf8(msg.content);
  24624. }
  24625. if (options.detached) {
  24626. msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content);
  24627. } else {
  24628. msg.contentInfo.value.push(
  24629. // [0] EXPLICIT content
  24630. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
  24631. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,
  24632. content)
  24633. ]));
  24634. }
  24635. }
  24636. }
  24637. // no signers, return early (degenerate case for certificate container)
  24638. if(msg.signers.length === 0) {
  24639. return;
  24640. }
  24641. // generate digest algorithm identifiers
  24642. var mds = addDigestAlgorithmIds();
  24643. // generate signerInfos
  24644. addSignerInfos(mds);
  24645. },
  24646. verify: function() {
  24647. throw new Error('PKCS#7 signature verification not yet implemented.');
  24648. },
  24649. /**
  24650. * Add a certificate.
  24651. *
  24652. * @param cert the certificate to add.
  24653. */
  24654. addCertificate: function(cert) {
  24655. // convert from PEM
  24656. if(typeof cert === 'string') {
  24657. cert = forge$3.pki.certificateFromPem(cert);
  24658. }
  24659. msg.certificates.push(cert);
  24660. },
  24661. /**
  24662. * Add a certificate revokation list.
  24663. *
  24664. * @param crl the certificate revokation list to add.
  24665. */
  24666. addCertificateRevokationList: function(crl) {
  24667. throw new Error('PKCS#7 CRL support not yet implemented.');
  24668. }
  24669. };
  24670. return msg;
  24671. function addDigestAlgorithmIds() {
  24672. var mds = {};
  24673. for(var i = 0; i < msg.signers.length; ++i) {
  24674. var signer = msg.signers[i];
  24675. var oid = signer.digestAlgorithm;
  24676. if(!(oid in mds)) {
  24677. // content digest
  24678. mds[oid] = forge$3.md[forge$3.pki.oids[oid]].create();
  24679. }
  24680. if(signer.authenticatedAttributes.length === 0) {
  24681. // no custom attributes to digest; use content message digest
  24682. signer.md = mds[oid];
  24683. } else {
  24684. // custom attributes to be digested; use own message digest
  24685. // TODO: optimize to just copy message digest state if that
  24686. // feature is ever supported with message digests
  24687. signer.md = forge$3.md[forge$3.pki.oids[oid]].create();
  24688. }
  24689. }
  24690. // add unique digest algorithm identifiers
  24691. msg.digestAlgorithmIdentifiers = [];
  24692. for(var oid in mds) {
  24693. msg.digestAlgorithmIdentifiers.push(
  24694. // AlgorithmIdentifier
  24695. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  24696. // algorithm
  24697. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  24698. asn1.oidToDer(oid).getBytes()),
  24699. // parameters (null)
  24700. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
  24701. ]));
  24702. }
  24703. return mds;
  24704. }
  24705. function addSignerInfos(mds) {
  24706. var content;
  24707. if (msg.detachedContent) {
  24708. // Signature has been made in detached mode.
  24709. content = msg.detachedContent;
  24710. } else {
  24711. // Note: ContentInfo is a SEQUENCE with 2 values, second value is
  24712. // the content field and is optional for a ContentInfo but required here
  24713. // since signers are present
  24714. // get ContentInfo content
  24715. content = msg.contentInfo.value[1];
  24716. // skip [0] EXPLICIT content wrapper
  24717. content = content.value[0];
  24718. }
  24719. if(!content) {
  24720. throw new Error(
  24721. 'Could not sign PKCS#7 message; there is no content to sign.');
  24722. }
  24723. // get ContentInfo content type
  24724. var contentType = asn1.derToOid(msg.contentInfo.value[0].value);
  24725. // serialize content
  24726. var bytes = asn1.toDer(content);
  24727. // skip identifier and length per RFC 2315 9.3
  24728. // skip identifier (1 byte)
  24729. bytes.getByte();
  24730. // read and discard length bytes
  24731. asn1.getBerValueLength(bytes);
  24732. bytes = bytes.getBytes();
  24733. // digest content DER value bytes
  24734. for(var oid in mds) {
  24735. mds[oid].start().update(bytes);
  24736. }
  24737. // sign content
  24738. var signingTime = new Date();
  24739. for(var i = 0; i < msg.signers.length; ++i) {
  24740. var signer = msg.signers[i];
  24741. if(signer.authenticatedAttributes.length === 0) {
  24742. // if ContentInfo content type is not "Data", then
  24743. // authenticatedAttributes must be present per RFC 2315
  24744. if(contentType !== forge$3.pki.oids.data) {
  24745. throw new Error(
  24746. 'Invalid signer; authenticatedAttributes must be present ' +
  24747. 'when the ContentInfo content type is not PKCS#7 Data.');
  24748. }
  24749. } else {
  24750. // process authenticated attributes
  24751. // [0] IMPLICIT
  24752. signer.authenticatedAttributesAsn1 = asn1.create(
  24753. asn1.Class.CONTEXT_SPECIFIC, 0, true, []);
  24754. // per RFC 2315, attributes are to be digested using a SET container
  24755. // not the above [0] IMPLICIT container
  24756. var attrsAsn1 = asn1.create(
  24757. asn1.Class.UNIVERSAL, asn1.Type.SET, true, []);
  24758. for(var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) {
  24759. var attr = signer.authenticatedAttributes[ai];
  24760. if(attr.type === forge$3.pki.oids.messageDigest) {
  24761. // use content message digest as value
  24762. attr.value = mds[signer.digestAlgorithm].digest();
  24763. } else if(attr.type === forge$3.pki.oids.signingTime) {
  24764. // auto-populate signing time if not already set
  24765. if(!attr.value) {
  24766. attr.value = signingTime;
  24767. }
  24768. }
  24769. // convert to ASN.1 and push onto Attributes SET (for signing) and
  24770. // onto authenticatedAttributesAsn1 to complete SignedData ASN.1
  24771. // TODO: optimize away duplication
  24772. attrsAsn1.value.push(_attributeToAsn1(attr));
  24773. signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr));
  24774. }
  24775. // DER-serialize and digest SET OF attributes only
  24776. bytes = asn1.toDer(attrsAsn1).getBytes();
  24777. signer.md.start().update(bytes);
  24778. }
  24779. // sign digest
  24780. signer.signature = signer.key.sign(signer.md, 'RSASSA-PKCS1-V1_5');
  24781. }
  24782. // add signer info
  24783. msg.signerInfos = _signersToAsn1(msg.signers);
  24784. }
  24785. };
  24786. /**
  24787. * Creates an empty PKCS#7 message of type EncryptedData.
  24788. *
  24789. * @return the message.
  24790. */
  24791. p7.createEncryptedData = function() {
  24792. var msg = null;
  24793. msg = {
  24794. type: forge$3.pki.oids.encryptedData,
  24795. version: 0,
  24796. encryptedContent: {
  24797. algorithm: forge$3.pki.oids['aes256-CBC']
  24798. },
  24799. /**
  24800. * Reads an EncryptedData content block (in ASN.1 format)
  24801. *
  24802. * @param obj The ASN.1 representation of the EncryptedData content block
  24803. */
  24804. fromAsn1: function(obj) {
  24805. // Validate EncryptedData content block and capture data.
  24806. _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator);
  24807. },
  24808. /**
  24809. * Decrypt encrypted content
  24810. *
  24811. * @param key The (symmetric) key as a byte buffer
  24812. */
  24813. decrypt: function(key) {
  24814. if(key !== undefined) {
  24815. msg.encryptedContent.key = key;
  24816. }
  24817. _decryptContent(msg);
  24818. }
  24819. };
  24820. return msg;
  24821. };
  24822. /**
  24823. * Creates an empty PKCS#7 message of type EnvelopedData.
  24824. *
  24825. * @return the message.
  24826. */
  24827. p7.createEnvelopedData = function() {
  24828. var msg = null;
  24829. msg = {
  24830. type: forge$3.pki.oids.envelopedData,
  24831. version: 0,
  24832. recipients: [],
  24833. encryptedContent: {
  24834. algorithm: forge$3.pki.oids['aes256-CBC']
  24835. },
  24836. /**
  24837. * Reads an EnvelopedData content block (in ASN.1 format)
  24838. *
  24839. * @param obj the ASN.1 representation of the EnvelopedData content block.
  24840. */
  24841. fromAsn1: function(obj) {
  24842. // validate EnvelopedData content block and capture data
  24843. var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator);
  24844. msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value);
  24845. },
  24846. toAsn1: function() {
  24847. // ContentInfo
  24848. return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  24849. // ContentType
  24850. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  24851. asn1.oidToDer(msg.type).getBytes()),
  24852. // [0] EnvelopedData
  24853. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
  24854. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  24855. // Version
  24856. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  24857. asn1.integerToDer(msg.version).getBytes()),
  24858. // RecipientInfos
  24859. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true,
  24860. _recipientsToAsn1(msg.recipients)),
  24861. // EncryptedContentInfo
  24862. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true,
  24863. _encryptedContentToAsn1(msg.encryptedContent))
  24864. ])
  24865. ])
  24866. ]);
  24867. },
  24868. /**
  24869. * Find recipient by X.509 certificate's issuer.
  24870. *
  24871. * @param cert the certificate with the issuer to look for.
  24872. *
  24873. * @return the recipient object.
  24874. */
  24875. findRecipient: function(cert) {
  24876. var sAttr = cert.issuer.attributes;
  24877. for(var i = 0; i < msg.recipients.length; ++i) {
  24878. var r = msg.recipients[i];
  24879. var rAttr = r.issuer;
  24880. if(r.serialNumber !== cert.serialNumber) {
  24881. continue;
  24882. }
  24883. if(rAttr.length !== sAttr.length) {
  24884. continue;
  24885. }
  24886. var match = true;
  24887. for(var j = 0; j < sAttr.length; ++j) {
  24888. if(rAttr[j].type !== sAttr[j].type ||
  24889. rAttr[j].value !== sAttr[j].value) {
  24890. match = false;
  24891. break;
  24892. }
  24893. }
  24894. if(match) {
  24895. return r;
  24896. }
  24897. }
  24898. return null;
  24899. },
  24900. /**
  24901. * Decrypt enveloped content
  24902. *
  24903. * @param recipient The recipient object related to the private key
  24904. * @param privKey The (RSA) private key object
  24905. */
  24906. decrypt: function(recipient, privKey) {
  24907. if(msg.encryptedContent.key === undefined && recipient !== undefined &&
  24908. privKey !== undefined) {
  24909. switch(recipient.encryptedContent.algorithm) {
  24910. case forge$3.pki.oids.rsaEncryption:
  24911. case forge$3.pki.oids.desCBC:
  24912. var key = privKey.decrypt(recipient.encryptedContent.content);
  24913. msg.encryptedContent.key = forge$3.util.createBuffer(key);
  24914. break;
  24915. default:
  24916. throw new Error('Unsupported asymmetric cipher, ' +
  24917. 'OID ' + recipient.encryptedContent.algorithm);
  24918. }
  24919. }
  24920. _decryptContent(msg);
  24921. },
  24922. /**
  24923. * Add (another) entity to list of recipients.
  24924. *
  24925. * @param cert The certificate of the entity to add.
  24926. */
  24927. addRecipient: function(cert) {
  24928. msg.recipients.push({
  24929. version: 0,
  24930. issuer: cert.issuer.attributes,
  24931. serialNumber: cert.serialNumber,
  24932. encryptedContent: {
  24933. // We simply assume rsaEncryption here, since forge.pki only
  24934. // supports RSA so far. If the PKI module supports other
  24935. // ciphers one day, we need to modify this one as well.
  24936. algorithm: forge$3.pki.oids.rsaEncryption,
  24937. key: cert.publicKey
  24938. }
  24939. });
  24940. },
  24941. /**
  24942. * Encrypt enveloped content.
  24943. *
  24944. * This function supports two optional arguments, cipher and key, which
  24945. * can be used to influence symmetric encryption. Unless cipher is
  24946. * provided, the cipher specified in encryptedContent.algorithm is used
  24947. * (defaults to AES-256-CBC). If no key is provided, encryptedContent.key
  24948. * is (re-)used. If that one's not set, a random key will be generated
  24949. * automatically.
  24950. *
  24951. * @param [key] The key to be used for symmetric encryption.
  24952. * @param [cipher] The OID of the symmetric cipher to use.
  24953. */
  24954. encrypt: function(key, cipher) {
  24955. // Part 1: Symmetric encryption
  24956. if(msg.encryptedContent.content === undefined) {
  24957. cipher = cipher || msg.encryptedContent.algorithm;
  24958. key = key || msg.encryptedContent.key;
  24959. var keyLen, ivLen, ciphFn;
  24960. switch(cipher) {
  24961. case forge$3.pki.oids['aes128-CBC']:
  24962. keyLen = 16;
  24963. ivLen = 16;
  24964. ciphFn = forge$3.aes.createEncryptionCipher;
  24965. break;
  24966. case forge$3.pki.oids['aes192-CBC']:
  24967. keyLen = 24;
  24968. ivLen = 16;
  24969. ciphFn = forge$3.aes.createEncryptionCipher;
  24970. break;
  24971. case forge$3.pki.oids['aes256-CBC']:
  24972. keyLen = 32;
  24973. ivLen = 16;
  24974. ciphFn = forge$3.aes.createEncryptionCipher;
  24975. break;
  24976. case forge$3.pki.oids['des-EDE3-CBC']:
  24977. keyLen = 24;
  24978. ivLen = 8;
  24979. ciphFn = forge$3.des.createEncryptionCipher;
  24980. break;
  24981. default:
  24982. throw new Error('Unsupported symmetric cipher, OID ' + cipher);
  24983. }
  24984. if(key === undefined) {
  24985. key = forge$3.util.createBuffer(forge$3.random.getBytes(keyLen));
  24986. } else if(key.length() != keyLen) {
  24987. throw new Error('Symmetric key has wrong length; ' +
  24988. 'got ' + key.length() + ' bytes, expected ' + keyLen + '.');
  24989. }
  24990. // Keep a copy of the key & IV in the object, so the caller can
  24991. // use it for whatever reason.
  24992. msg.encryptedContent.algorithm = cipher;
  24993. msg.encryptedContent.key = key;
  24994. msg.encryptedContent.parameter = forge$3.util.createBuffer(
  24995. forge$3.random.getBytes(ivLen));
  24996. var ciph = ciphFn(key);
  24997. ciph.start(msg.encryptedContent.parameter.copy());
  24998. ciph.update(msg.content);
  24999. // The finish function does PKCS#7 padding by default, therefore
  25000. // no action required by us.
  25001. if(!ciph.finish()) {
  25002. throw new Error('Symmetric encryption failed.');
  25003. }
  25004. msg.encryptedContent.content = ciph.output;
  25005. }
  25006. // Part 2: asymmetric encryption for each recipient
  25007. for(var i = 0; i < msg.recipients.length; ++i) {
  25008. var recipient = msg.recipients[i];
  25009. // Nothing to do, encryption already done.
  25010. if(recipient.encryptedContent.content !== undefined) {
  25011. continue;
  25012. }
  25013. switch(recipient.encryptedContent.algorithm) {
  25014. case forge$3.pki.oids.rsaEncryption:
  25015. recipient.encryptedContent.content =
  25016. recipient.encryptedContent.key.encrypt(
  25017. msg.encryptedContent.key.data);
  25018. break;
  25019. default:
  25020. throw new Error('Unsupported asymmetric cipher, OID ' +
  25021. recipient.encryptedContent.algorithm);
  25022. }
  25023. }
  25024. }
  25025. };
  25026. return msg;
  25027. };
  25028. /**
  25029. * Converts a single recipient from an ASN.1 object.
  25030. *
  25031. * @param obj the ASN.1 RecipientInfo.
  25032. *
  25033. * @return the recipient object.
  25034. */
  25035. function _recipientFromAsn1(obj) {
  25036. // validate EnvelopedData content block and capture data
  25037. var capture = {};
  25038. var errors = [];
  25039. if(!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) {
  25040. var error = new Error('Cannot read PKCS#7 RecipientInfo. ' +
  25041. 'ASN.1 object is not an PKCS#7 RecipientInfo.');
  25042. error.errors = errors;
  25043. throw error;
  25044. }
  25045. return {
  25046. version: capture.version.charCodeAt(0),
  25047. issuer: forge$3.pki.RDNAttributesAsArray(capture.issuer),
  25048. serialNumber: forge$3.util.createBuffer(capture.serial).toHex(),
  25049. encryptedContent: {
  25050. algorithm: asn1.derToOid(capture.encAlgorithm),
  25051. parameter: capture.encParameter.value,
  25052. content: capture.encKey
  25053. }
  25054. };
  25055. }
  25056. /**
  25057. * Converts a single recipient object to an ASN.1 object.
  25058. *
  25059. * @param obj the recipient object.
  25060. *
  25061. * @return the ASN.1 RecipientInfo.
  25062. */
  25063. function _recipientToAsn1(obj) {
  25064. return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  25065. // Version
  25066. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  25067. asn1.integerToDer(obj.version).getBytes()),
  25068. // IssuerAndSerialNumber
  25069. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  25070. // Name
  25071. forge$3.pki.distinguishedNameToAsn1({attributes: obj.issuer}),
  25072. // Serial
  25073. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  25074. forge$3.util.hexToBytes(obj.serialNumber))
  25075. ]),
  25076. // KeyEncryptionAlgorithmIdentifier
  25077. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  25078. // Algorithm
  25079. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  25080. asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()),
  25081. // Parameter, force NULL, only RSA supported for now.
  25082. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
  25083. ]),
  25084. // EncryptedKey
  25085. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,
  25086. obj.encryptedContent.content)
  25087. ]);
  25088. }
  25089. /**
  25090. * Map a set of RecipientInfo ASN.1 objects to recipient objects.
  25091. *
  25092. * @param infos an array of ASN.1 representations RecipientInfo (i.e. SET OF).
  25093. *
  25094. * @return an array of recipient objects.
  25095. */
  25096. function _recipientsFromAsn1(infos) {
  25097. var ret = [];
  25098. for(var i = 0; i < infos.length; ++i) {
  25099. ret.push(_recipientFromAsn1(infos[i]));
  25100. }
  25101. return ret;
  25102. }
  25103. /**
  25104. * Map an array of recipient objects to ASN.1 RecipientInfo objects.
  25105. *
  25106. * @param recipients an array of recipientInfo objects.
  25107. *
  25108. * @return an array of ASN.1 RecipientInfos.
  25109. */
  25110. function _recipientsToAsn1(recipients) {
  25111. var ret = [];
  25112. for(var i = 0; i < recipients.length; ++i) {
  25113. ret.push(_recipientToAsn1(recipients[i]));
  25114. }
  25115. return ret;
  25116. }
  25117. /**
  25118. * Converts a single signerInfo object to an ASN.1 object.
  25119. *
  25120. * @param obj the signerInfo object.
  25121. *
  25122. * @return the ASN.1 representation of a SignerInfo.
  25123. */
  25124. function _signerToAsn1(obj) {
  25125. // SignerInfo
  25126. var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  25127. // version
  25128. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  25129. asn1.integerToDer(obj.version).getBytes()),
  25130. // issuerAndSerialNumber
  25131. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  25132. // name
  25133. forge$3.pki.distinguishedNameToAsn1({attributes: obj.issuer}),
  25134. // serial
  25135. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  25136. forge$3.util.hexToBytes(obj.serialNumber))
  25137. ]),
  25138. // digestAlgorithm
  25139. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  25140. // algorithm
  25141. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  25142. asn1.oidToDer(obj.digestAlgorithm).getBytes()),
  25143. // parameters (null)
  25144. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
  25145. ])
  25146. ]);
  25147. // authenticatedAttributes (OPTIONAL)
  25148. if(obj.authenticatedAttributesAsn1) {
  25149. // add ASN.1 previously generated during signing
  25150. rval.value.push(obj.authenticatedAttributesAsn1);
  25151. }
  25152. // digestEncryptionAlgorithm
  25153. rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  25154. // algorithm
  25155. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  25156. asn1.oidToDer(obj.signatureAlgorithm).getBytes()),
  25157. // parameters (null)
  25158. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
  25159. ]));
  25160. // encryptedDigest
  25161. rval.value.push(asn1.create(
  25162. asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.signature));
  25163. // unauthenticatedAttributes (OPTIONAL)
  25164. if(obj.unauthenticatedAttributes.length > 0) {
  25165. // [1] IMPLICIT
  25166. var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []);
  25167. for(var i = 0; i < obj.unauthenticatedAttributes.length; ++i) {
  25168. var attr = obj.unauthenticatedAttributes[i];
  25169. attrsAsn1.values.push(_attributeToAsn1(attr));
  25170. }
  25171. rval.value.push(attrsAsn1);
  25172. }
  25173. return rval;
  25174. }
  25175. /**
  25176. * Map an array of signer objects to ASN.1 objects.
  25177. *
  25178. * @param signers an array of signer objects.
  25179. *
  25180. * @return an array of ASN.1 SignerInfos.
  25181. */
  25182. function _signersToAsn1(signers) {
  25183. var ret = [];
  25184. for(var i = 0; i < signers.length; ++i) {
  25185. ret.push(_signerToAsn1(signers[i]));
  25186. }
  25187. return ret;
  25188. }
  25189. /**
  25190. * Convert an attribute object to an ASN.1 Attribute.
  25191. *
  25192. * @param attr the attribute object.
  25193. *
  25194. * @return the ASN.1 Attribute.
  25195. */
  25196. function _attributeToAsn1(attr) {
  25197. var value;
  25198. // TODO: generalize to support more attributes
  25199. if(attr.type === forge$3.pki.oids.contentType) {
  25200. value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  25201. asn1.oidToDer(attr.value).getBytes());
  25202. } else if(attr.type === forge$3.pki.oids.messageDigest) {
  25203. value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,
  25204. attr.value.bytes());
  25205. } else if(attr.type === forge$3.pki.oids.signingTime) {
  25206. /* Note per RFC 2985: Dates between 1 January 1950 and 31 December 2049
  25207. (inclusive) MUST be encoded as UTCTime. Any dates with year values
  25208. before 1950 or after 2049 MUST be encoded as GeneralizedTime. [Further,]
  25209. UTCTime values MUST be expressed in Greenwich Mean Time (Zulu) and MUST
  25210. include seconds (i.e., times are YYMMDDHHMMSSZ), even where the
  25211. number of seconds is zero. Midnight (GMT) must be represented as
  25212. "YYMMDD000000Z". */
  25213. // TODO: make these module-level constants
  25214. var jan_1_1950 = new Date('1950-01-01T00:00:00Z');
  25215. var jan_1_2050 = new Date('2050-01-01T00:00:00Z');
  25216. var date = attr.value;
  25217. if(typeof date === 'string') {
  25218. // try to parse date
  25219. var timestamp = Date.parse(date);
  25220. if(!isNaN(timestamp)) {
  25221. date = new Date(timestamp);
  25222. } else if(date.length === 13) {
  25223. // YYMMDDHHMMSSZ (13 chars for UTCTime)
  25224. date = asn1.utcTimeToDate(date);
  25225. } else {
  25226. // assume generalized time
  25227. date = asn1.generalizedTimeToDate(date);
  25228. }
  25229. }
  25230. if(date >= jan_1_1950 && date < jan_1_2050) {
  25231. value = asn1.create(
  25232. asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false,
  25233. asn1.dateToUtcTime(date));
  25234. } else {
  25235. value = asn1.create(
  25236. asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false,
  25237. asn1.dateToGeneralizedTime(date));
  25238. }
  25239. }
  25240. // TODO: expose as common API call
  25241. // create a RelativeDistinguishedName set
  25242. // each value in the set is an AttributeTypeAndValue first
  25243. // containing the type (an OID) and second the value
  25244. return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  25245. // AttributeType
  25246. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  25247. asn1.oidToDer(attr.type).getBytes()),
  25248. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [
  25249. // AttributeValue
  25250. value
  25251. ])
  25252. ]);
  25253. }
  25254. /**
  25255. * Map messages encrypted content to ASN.1 objects.
  25256. *
  25257. * @param ec The encryptedContent object of the message.
  25258. *
  25259. * @return ASN.1 representation of the encryptedContent object (SEQUENCE).
  25260. */
  25261. function _encryptedContentToAsn1(ec) {
  25262. return [
  25263. // ContentType, always Data for the moment
  25264. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  25265. asn1.oidToDer(forge$3.pki.oids.data).getBytes()),
  25266. // ContentEncryptionAlgorithmIdentifier
  25267. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  25268. // Algorithm
  25269. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  25270. asn1.oidToDer(ec.algorithm).getBytes()),
  25271. // Parameters (IV)
  25272. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,
  25273. ec.parameter.getBytes())
  25274. ]),
  25275. // [0] EncryptedContent
  25276. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
  25277. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false,
  25278. ec.content.getBytes())
  25279. ])
  25280. ];
  25281. }
  25282. /**
  25283. * Reads the "common part" of an PKCS#7 content block (in ASN.1 format)
  25284. *
  25285. * This function reads the "common part" of the PKCS#7 content blocks
  25286. * EncryptedData and EnvelopedData, i.e. version number and symmetrically
  25287. * encrypted content block.
  25288. *
  25289. * The result of the ASN.1 validate and capture process is returned
  25290. * to allow the caller to extract further data, e.g. the list of recipients
  25291. * in case of a EnvelopedData object.
  25292. *
  25293. * @param msg the PKCS#7 object to read the data to.
  25294. * @param obj the ASN.1 representation of the content block.
  25295. * @param validator the ASN.1 structure validator object to use.
  25296. *
  25297. * @return the value map captured by validator object.
  25298. */
  25299. function _fromAsn1(msg, obj, validator) {
  25300. var capture = {};
  25301. var errors = [];
  25302. if(!asn1.validate(obj, validator, capture, errors)) {
  25303. var error = new Error('Cannot read PKCS#7 message. ' +
  25304. 'ASN.1 object is not a supported PKCS#7 message.');
  25305. error.errors = error;
  25306. throw error;
  25307. }
  25308. // Check contentType, so far we only support (raw) Data.
  25309. var contentType = asn1.derToOid(capture.contentType);
  25310. if(contentType !== forge$3.pki.oids.data) {
  25311. throw new Error('Unsupported PKCS#7 message. ' +
  25312. 'Only wrapped ContentType Data supported.');
  25313. }
  25314. if(capture.encryptedContent) {
  25315. var content = '';
  25316. if(forge$3.util.isArray(capture.encryptedContent)) {
  25317. for(var i = 0; i < capture.encryptedContent.length; ++i) {
  25318. if(capture.encryptedContent[i].type !== asn1.Type.OCTETSTRING) {
  25319. throw new Error('Malformed PKCS#7 message, expecting encrypted ' +
  25320. 'content constructed of only OCTET STRING objects.');
  25321. }
  25322. content += capture.encryptedContent[i].value;
  25323. }
  25324. } else {
  25325. content = capture.encryptedContent;
  25326. }
  25327. msg.encryptedContent = {
  25328. algorithm: asn1.derToOid(capture.encAlgorithm),
  25329. parameter: forge$3.util.createBuffer(capture.encParameter.value),
  25330. content: forge$3.util.createBuffer(content)
  25331. };
  25332. }
  25333. if(capture.content) {
  25334. var content = '';
  25335. if(forge$3.util.isArray(capture.content)) {
  25336. for(var i = 0; i < capture.content.length; ++i) {
  25337. if(capture.content[i].type !== asn1.Type.OCTETSTRING) {
  25338. throw new Error('Malformed PKCS#7 message, expecting ' +
  25339. 'content constructed of only OCTET STRING objects.');
  25340. }
  25341. content += capture.content[i].value;
  25342. }
  25343. } else {
  25344. content = capture.content;
  25345. }
  25346. msg.content = forge$3.util.createBuffer(content);
  25347. }
  25348. msg.version = capture.version.charCodeAt(0);
  25349. msg.rawCapture = capture;
  25350. return capture;
  25351. }
  25352. /**
  25353. * Decrypt the symmetrically encrypted content block of the PKCS#7 message.
  25354. *
  25355. * Decryption is skipped in case the PKCS#7 message object already has a
  25356. * (decrypted) content attribute. The algorithm, key and cipher parameters
  25357. * (probably the iv) are taken from the encryptedContent attribute of the
  25358. * message object.
  25359. *
  25360. * @param The PKCS#7 message object.
  25361. */
  25362. function _decryptContent(msg) {
  25363. if(msg.encryptedContent.key === undefined) {
  25364. throw new Error('Symmetric key not available.');
  25365. }
  25366. if(msg.content === undefined) {
  25367. var ciph;
  25368. switch(msg.encryptedContent.algorithm) {
  25369. case forge$3.pki.oids['aes128-CBC']:
  25370. case forge$3.pki.oids['aes192-CBC']:
  25371. case forge$3.pki.oids['aes256-CBC']:
  25372. ciph = forge$3.aes.createDecryptionCipher(msg.encryptedContent.key);
  25373. break;
  25374. case forge$3.pki.oids['desCBC']:
  25375. case forge$3.pki.oids['des-EDE3-CBC']:
  25376. ciph = forge$3.des.createDecryptionCipher(msg.encryptedContent.key);
  25377. break;
  25378. default:
  25379. throw new Error('Unsupported symmetric cipher, OID ' +
  25380. msg.encryptedContent.algorithm);
  25381. }
  25382. ciph.start(msg.encryptedContent.parameter);
  25383. ciph.update(msg.encryptedContent.content);
  25384. if(!ciph.finish()) {
  25385. throw new Error('Symmetric decryption failed.');
  25386. }
  25387. msg.content = ciph.output;
  25388. }
  25389. }
  25390. /**
  25391. * Functions to output keys in SSH-friendly formats.
  25392. *
  25393. * This is part of the Forge project which may be used under the terms of
  25394. * either the BSD License or the GNU General Public License (GPL) Version 2.
  25395. *
  25396. * See: https://github.com/digitalbazaar/forge/blob/cbebca3780658703d925b61b2caffb1d263a6c1d/LICENSE
  25397. *
  25398. * @author https://github.com/shellac
  25399. */
  25400. var forge$2 = forge$F;
  25401. var ssh = forge$2.ssh = forge$2.ssh || {};
  25402. /**
  25403. * Encodes (and optionally encrypts) a private RSA key as a Putty PPK file.
  25404. *
  25405. * @param privateKey the key.
  25406. * @param passphrase a passphrase to protect the key (falsy for no encryption).
  25407. * @param comment a comment to include in the key file.
  25408. *
  25409. * @return the PPK file as a string.
  25410. */
  25411. ssh.privateKeyToPutty = function(privateKey, passphrase, comment) {
  25412. comment = comment || '';
  25413. passphrase = passphrase || '';
  25414. var algorithm = 'ssh-rsa';
  25415. var encryptionAlgorithm = (passphrase === '') ? 'none' : 'aes256-cbc';
  25416. var ppk = 'PuTTY-User-Key-File-2: ' + algorithm + '\r\n';
  25417. ppk += 'Encryption: ' + encryptionAlgorithm + '\r\n';
  25418. ppk += 'Comment: ' + comment + '\r\n';
  25419. // public key into buffer for ppk
  25420. var pubbuffer = forge$2.util.createBuffer();
  25421. _addStringToBuffer(pubbuffer, algorithm);
  25422. _addBigIntegerToBuffer(pubbuffer, privateKey.e);
  25423. _addBigIntegerToBuffer(pubbuffer, privateKey.n);
  25424. // write public key
  25425. var pub = forge$2.util.encode64(pubbuffer.bytes(), 64);
  25426. var length = Math.floor(pub.length / 66) + 1; // 66 = 64 + \r\n
  25427. ppk += 'Public-Lines: ' + length + '\r\n';
  25428. ppk += pub;
  25429. // private key into a buffer
  25430. var privbuffer = forge$2.util.createBuffer();
  25431. _addBigIntegerToBuffer(privbuffer, privateKey.d);
  25432. _addBigIntegerToBuffer(privbuffer, privateKey.p);
  25433. _addBigIntegerToBuffer(privbuffer, privateKey.q);
  25434. _addBigIntegerToBuffer(privbuffer, privateKey.qInv);
  25435. // optionally encrypt the private key
  25436. var priv;
  25437. if(!passphrase) {
  25438. // use the unencrypted buffer
  25439. priv = forge$2.util.encode64(privbuffer.bytes(), 64);
  25440. } else {
  25441. // encrypt RSA key using passphrase
  25442. var encLen = privbuffer.length() + 16 - 1;
  25443. encLen -= encLen % 16;
  25444. // pad private key with sha1-d data -- needs to be a multiple of 16
  25445. var padding = _sha1(privbuffer.bytes());
  25446. padding.truncate(padding.length() - encLen + privbuffer.length());
  25447. privbuffer.putBuffer(padding);
  25448. var aeskey = forge$2.util.createBuffer();
  25449. aeskey.putBuffer(_sha1('\x00\x00\x00\x00', passphrase));
  25450. aeskey.putBuffer(_sha1('\x00\x00\x00\x01', passphrase));
  25451. // encrypt some bytes using CBC mode
  25452. // key is 40 bytes, so truncate *by* 8 bytes
  25453. var cipher = forge$2.aes.createEncryptionCipher(aeskey.truncate(8), 'CBC');
  25454. cipher.start(forge$2.util.createBuffer().fillWithByte(0, 16));
  25455. cipher.update(privbuffer.copy());
  25456. cipher.finish();
  25457. var encrypted = cipher.output;
  25458. // Note: this appears to differ from Putty -- is forge wrong, or putty?
  25459. // due to padding we finish as an exact multiple of 16
  25460. encrypted.truncate(16); // all padding
  25461. priv = forge$2.util.encode64(encrypted.bytes(), 64);
  25462. }
  25463. // output private key
  25464. length = Math.floor(priv.length / 66) + 1; // 64 + \r\n
  25465. ppk += '\r\nPrivate-Lines: ' + length + '\r\n';
  25466. ppk += priv;
  25467. // MAC
  25468. var mackey = _sha1('putty-private-key-file-mac-key', passphrase);
  25469. var macbuffer = forge$2.util.createBuffer();
  25470. _addStringToBuffer(macbuffer, algorithm);
  25471. _addStringToBuffer(macbuffer, encryptionAlgorithm);
  25472. _addStringToBuffer(macbuffer, comment);
  25473. macbuffer.putInt32(pubbuffer.length());
  25474. macbuffer.putBuffer(pubbuffer);
  25475. macbuffer.putInt32(privbuffer.length());
  25476. macbuffer.putBuffer(privbuffer);
  25477. var hmac = forge$2.hmac.create();
  25478. hmac.start('sha1', mackey);
  25479. hmac.update(macbuffer.bytes());
  25480. ppk += '\r\nPrivate-MAC: ' + hmac.digest().toHex() + '\r\n';
  25481. return ppk;
  25482. };
  25483. /**
  25484. * Encodes a public RSA key as an OpenSSH file.
  25485. *
  25486. * @param key the key.
  25487. * @param comment a comment.
  25488. *
  25489. * @return the public key in OpenSSH format.
  25490. */
  25491. ssh.publicKeyToOpenSSH = function(key, comment) {
  25492. var type = 'ssh-rsa';
  25493. comment = comment || '';
  25494. var buffer = forge$2.util.createBuffer();
  25495. _addStringToBuffer(buffer, type);
  25496. _addBigIntegerToBuffer(buffer, key.e);
  25497. _addBigIntegerToBuffer(buffer, key.n);
  25498. return type + ' ' + forge$2.util.encode64(buffer.bytes()) + ' ' + comment;
  25499. };
  25500. /**
  25501. * Encodes a private RSA key as an OpenSSH file.
  25502. *
  25503. * @param key the key.
  25504. * @param passphrase a passphrase to protect the key (falsy for no encryption).
  25505. *
  25506. * @return the public key in OpenSSH format.
  25507. */
  25508. ssh.privateKeyToOpenSSH = function(privateKey, passphrase) {
  25509. if(!passphrase) {
  25510. return forge$2.pki.privateKeyToPem(privateKey);
  25511. }
  25512. // OpenSSH private key is just a legacy format, it seems
  25513. return forge$2.pki.encryptRsaPrivateKey(privateKey, passphrase,
  25514. {legacy: true, algorithm: 'aes128'});
  25515. };
  25516. /**
  25517. * Gets the SSH fingerprint for the given public key.
  25518. *
  25519. * @param options the options to use.
  25520. * [md] the message digest object to use (defaults to forge.md.md5).
  25521. * [encoding] an alternative output encoding, such as 'hex'
  25522. * (defaults to none, outputs a byte buffer).
  25523. * [delimiter] the delimiter to use between bytes for 'hex' encoded
  25524. * output, eg: ':' (defaults to none).
  25525. *
  25526. * @return the fingerprint as a byte buffer or other encoding based on options.
  25527. */
  25528. ssh.getPublicKeyFingerprint = function(key, options) {
  25529. options = options || {};
  25530. var md = options.md || forge$2.md.md5.create();
  25531. var type = 'ssh-rsa';
  25532. var buffer = forge$2.util.createBuffer();
  25533. _addStringToBuffer(buffer, type);
  25534. _addBigIntegerToBuffer(buffer, key.e);
  25535. _addBigIntegerToBuffer(buffer, key.n);
  25536. // hash public key bytes
  25537. md.start();
  25538. md.update(buffer.getBytes());
  25539. var digest = md.digest();
  25540. if(options.encoding === 'hex') {
  25541. var hex = digest.toHex();
  25542. if(options.delimiter) {
  25543. return hex.match(/.{2}/g).join(options.delimiter);
  25544. }
  25545. return hex;
  25546. } else if(options.encoding === 'binary') {
  25547. return digest.getBytes();
  25548. } else if(options.encoding) {
  25549. throw new Error('Unknown encoding "' + options.encoding + '".');
  25550. }
  25551. return digest;
  25552. };
  25553. /**
  25554. * Adds len(val) then val to a buffer.
  25555. *
  25556. * @param buffer the buffer to add to.
  25557. * @param val a big integer.
  25558. */
  25559. function _addBigIntegerToBuffer(buffer, val) {
  25560. var hexVal = val.toString(16);
  25561. // ensure 2s complement +ve
  25562. if(hexVal[0] >= '8') {
  25563. hexVal = '00' + hexVal;
  25564. }
  25565. var bytes = forge$2.util.hexToBytes(hexVal);
  25566. buffer.putInt32(bytes.length);
  25567. buffer.putBytes(bytes);
  25568. }
  25569. /**
  25570. * Adds len(val) then val to a buffer.
  25571. *
  25572. * @param buffer the buffer to add to.
  25573. * @param val a string.
  25574. */
  25575. function _addStringToBuffer(buffer, val) {
  25576. buffer.putInt32(val.length);
  25577. buffer.putString(val);
  25578. }
  25579. /**
  25580. * Hashes the arguments into one value using SHA-1.
  25581. *
  25582. * @return the sha1 hash of the provided arguments.
  25583. */
  25584. function _sha1() {
  25585. var sha = forge$2.md.sha1.create();
  25586. var num = arguments.length;
  25587. for (var i = 0; i < num; ++i) {
  25588. sha.update(arguments[i]);
  25589. }
  25590. return sha.digest();
  25591. }
  25592. /**
  25593. * Support for concurrent task management and synchronization in web
  25594. * applications.
  25595. *
  25596. * @author Dave Longley
  25597. * @author David I. Lehn <dlehn@digitalbazaar.com>
  25598. *
  25599. * Copyright (c) 2009-2013 Digital Bazaar, Inc.
  25600. */
  25601. var forge$1 = forge$F;
  25602. // logging category
  25603. var cat = 'forge.task';
  25604. // track tasks for debugging
  25605. var sTasks = {};
  25606. var sNextTaskId = 0;
  25607. // debug access
  25608. forge$1.debug.set(cat, 'tasks', sTasks);
  25609. // a map of task type to task queue
  25610. var sTaskQueues = {};
  25611. // debug access
  25612. forge$1.debug.set(cat, 'queues', sTaskQueues);
  25613. // name for unnamed tasks
  25614. var sNoTaskName = '?';
  25615. // maximum number of doNext() recursions before a context swap occurs
  25616. // FIXME: might need to tweak this based on the browser
  25617. var sMaxRecursions = 30;
  25618. // time slice for doing tasks before a context swap occurs
  25619. // FIXME: might need to tweak this based on the browser
  25620. var sTimeSlice = 20;
  25621. /**
  25622. * Task states.
  25623. *
  25624. * READY: ready to start processing
  25625. * RUNNING: task or a subtask is running
  25626. * BLOCKED: task is waiting to acquire N permits to continue
  25627. * SLEEPING: task is sleeping for a period of time
  25628. * DONE: task is done
  25629. * ERROR: task has an error
  25630. */
  25631. var READY = 'ready';
  25632. var RUNNING = 'running';
  25633. var BLOCKED = 'blocked';
  25634. var SLEEPING = 'sleeping';
  25635. var DONE = 'done';
  25636. var ERROR = 'error';
  25637. /**
  25638. * Task actions. Used to control state transitions.
  25639. *
  25640. * STOP: stop processing
  25641. * START: start processing tasks
  25642. * BLOCK: block task from continuing until 1 or more permits are released
  25643. * UNBLOCK: release one or more permits
  25644. * SLEEP: sleep for a period of time
  25645. * WAKEUP: wakeup early from SLEEPING state
  25646. * CANCEL: cancel further tasks
  25647. * FAIL: a failure occured
  25648. */
  25649. var STOP = 'stop';
  25650. var START = 'start';
  25651. var BLOCK = 'block';
  25652. var UNBLOCK = 'unblock';
  25653. var SLEEP = 'sleep';
  25654. var WAKEUP = 'wakeup';
  25655. var CANCEL = 'cancel';
  25656. var FAIL = 'fail';
  25657. /**
  25658. * State transition table.
  25659. *
  25660. * nextState = sStateTable[currentState][action]
  25661. */
  25662. var sStateTable = {};
  25663. sStateTable[READY] = {};
  25664. sStateTable[READY][STOP] = READY;
  25665. sStateTable[READY][START] = RUNNING;
  25666. sStateTable[READY][CANCEL] = DONE;
  25667. sStateTable[READY][FAIL] = ERROR;
  25668. sStateTable[RUNNING] = {};
  25669. sStateTable[RUNNING][STOP] = READY;
  25670. sStateTable[RUNNING][START] = RUNNING;
  25671. sStateTable[RUNNING][BLOCK] = BLOCKED;
  25672. sStateTable[RUNNING][UNBLOCK] = RUNNING;
  25673. sStateTable[RUNNING][SLEEP] = SLEEPING;
  25674. sStateTable[RUNNING][WAKEUP] = RUNNING;
  25675. sStateTable[RUNNING][CANCEL] = DONE;
  25676. sStateTable[RUNNING][FAIL] = ERROR;
  25677. sStateTable[BLOCKED] = {};
  25678. sStateTable[BLOCKED][STOP] = BLOCKED;
  25679. sStateTable[BLOCKED][START] = BLOCKED;
  25680. sStateTable[BLOCKED][BLOCK] = BLOCKED;
  25681. sStateTable[BLOCKED][UNBLOCK] = BLOCKED;
  25682. sStateTable[BLOCKED][SLEEP] = BLOCKED;
  25683. sStateTable[BLOCKED][WAKEUP] = BLOCKED;
  25684. sStateTable[BLOCKED][CANCEL] = DONE;
  25685. sStateTable[BLOCKED][FAIL] = ERROR;
  25686. sStateTable[SLEEPING] = {};
  25687. sStateTable[SLEEPING][STOP] = SLEEPING;
  25688. sStateTable[SLEEPING][START] = SLEEPING;
  25689. sStateTable[SLEEPING][BLOCK] = SLEEPING;
  25690. sStateTable[SLEEPING][UNBLOCK] = SLEEPING;
  25691. sStateTable[SLEEPING][SLEEP] = SLEEPING;
  25692. sStateTable[SLEEPING][WAKEUP] = SLEEPING;
  25693. sStateTable[SLEEPING][CANCEL] = DONE;
  25694. sStateTable[SLEEPING][FAIL] = ERROR;
  25695. sStateTable[DONE] = {};
  25696. sStateTable[DONE][STOP] = DONE;
  25697. sStateTable[DONE][START] = DONE;
  25698. sStateTable[DONE][BLOCK] = DONE;
  25699. sStateTable[DONE][UNBLOCK] = DONE;
  25700. sStateTable[DONE][SLEEP] = DONE;
  25701. sStateTable[DONE][WAKEUP] = DONE;
  25702. sStateTable[DONE][CANCEL] = DONE;
  25703. sStateTable[DONE][FAIL] = ERROR;
  25704. sStateTable[ERROR] = {};
  25705. sStateTable[ERROR][STOP] = ERROR;
  25706. sStateTable[ERROR][START] = ERROR;
  25707. sStateTable[ERROR][BLOCK] = ERROR;
  25708. sStateTable[ERROR][UNBLOCK] = ERROR;
  25709. sStateTable[ERROR][SLEEP] = ERROR;
  25710. sStateTable[ERROR][WAKEUP] = ERROR;
  25711. sStateTable[ERROR][CANCEL] = ERROR;
  25712. sStateTable[ERROR][FAIL] = ERROR;
  25713. /**
  25714. * Creates a new task.
  25715. *
  25716. * @param options options for this task
  25717. * run: the run function for the task (required)
  25718. * name: the run function for the task (optional)
  25719. * parent: parent of this task (optional)
  25720. *
  25721. * @return the empty task.
  25722. */
  25723. var Task = function(options) {
  25724. // task id
  25725. this.id = -1;
  25726. // task name
  25727. this.name = options.name || sNoTaskName;
  25728. // task has no parent
  25729. this.parent = options.parent || null;
  25730. // save run function
  25731. this.run = options.run;
  25732. // create a queue of subtasks to run
  25733. this.subtasks = [];
  25734. // error flag
  25735. this.error = false;
  25736. // state of the task
  25737. this.state = READY;
  25738. // number of times the task has been blocked (also the number
  25739. // of permits needed to be released to continue running)
  25740. this.blocks = 0;
  25741. // timeout id when sleeping
  25742. this.timeoutId = null;
  25743. // no swap time yet
  25744. this.swapTime = null;
  25745. // no user data
  25746. this.userData = null;
  25747. // initialize task
  25748. // FIXME: deal with overflow
  25749. this.id = sNextTaskId++;
  25750. sTasks[this.id] = this;
  25751. };
  25752. /**
  25753. * Logs debug information on this task and the system state.
  25754. */
  25755. Task.prototype.debug = function(msg) {
  25756. msg = msg || '';
  25757. forge$1.log.debug(cat, msg,
  25758. '[%s][%s] task:', this.id, this.name, this,
  25759. 'subtasks:', this.subtasks.length,
  25760. 'queue:', sTaskQueues);
  25761. };
  25762. /**
  25763. * Adds a subtask to run after task.doNext() or task.fail() is called.
  25764. *
  25765. * @param name human readable name for this task (optional).
  25766. * @param subrun a function to run that takes the current task as
  25767. * its first parameter.
  25768. *
  25769. * @return the current task (useful for chaining next() calls).
  25770. */
  25771. Task.prototype.next = function(name, subrun) {
  25772. // juggle parameters if it looks like no name is given
  25773. if(typeof(name) === 'function') {
  25774. subrun = name;
  25775. // inherit parent's name
  25776. name = this.name;
  25777. }
  25778. // create subtask, set parent to this task, propagate callbacks
  25779. var subtask = new Task({
  25780. run: subrun,
  25781. name: name,
  25782. parent: this
  25783. });
  25784. // start subtasks running
  25785. subtask.state = RUNNING;
  25786. subtask.type = this.type;
  25787. subtask.successCallback = this.successCallback || null;
  25788. subtask.failureCallback = this.failureCallback || null;
  25789. // queue a new subtask
  25790. this.subtasks.push(subtask);
  25791. return this;
  25792. };
  25793. /**
  25794. * Adds subtasks to run in parallel after task.doNext() or task.fail()
  25795. * is called.
  25796. *
  25797. * @param name human readable name for this task (optional).
  25798. * @param subrun functions to run that take the current task as
  25799. * their first parameter.
  25800. *
  25801. * @return the current task (useful for chaining next() calls).
  25802. */
  25803. Task.prototype.parallel = function(name, subrun) {
  25804. // juggle parameters if it looks like no name is given
  25805. if(forge$1.util.isArray(name)) {
  25806. subrun = name;
  25807. // inherit parent's name
  25808. name = this.name;
  25809. }
  25810. // Wrap parallel tasks in a regular task so they are started at the
  25811. // proper time.
  25812. return this.next(name, function(task) {
  25813. // block waiting for subtasks
  25814. var ptask = task;
  25815. ptask.block(subrun.length);
  25816. // we pass the iterator from the loop below as a parameter
  25817. // to a function because it is otherwise included in the
  25818. // closure and changes as the loop changes -- causing i
  25819. // to always be set to its highest value
  25820. var startParallelTask = function(pname, pi) {
  25821. forge$1.task.start({
  25822. type: pname,
  25823. run: function(task) {
  25824. subrun[pi](task);
  25825. },
  25826. success: function(task) {
  25827. ptask.unblock();
  25828. },
  25829. failure: function(task) {
  25830. ptask.unblock();
  25831. }
  25832. });
  25833. };
  25834. for(var i = 0; i < subrun.length; i++) {
  25835. // Type must be unique so task starts in parallel:
  25836. // name + private string + task id + sub-task index
  25837. // start tasks in parallel and unblock when the finish
  25838. var pname = name + '__parallel-' + task.id + '-' + i;
  25839. var pi = i;
  25840. startParallelTask(pname, pi);
  25841. }
  25842. });
  25843. };
  25844. /**
  25845. * Stops a running task.
  25846. */
  25847. Task.prototype.stop = function() {
  25848. this.state = sStateTable[this.state][STOP];
  25849. };
  25850. /**
  25851. * Starts running a task.
  25852. */
  25853. Task.prototype.start = function() {
  25854. this.error = false;
  25855. this.state = sStateTable[this.state][START];
  25856. // try to restart
  25857. if(this.state === RUNNING) {
  25858. this.start = new Date();
  25859. this.run(this);
  25860. runNext(this, 0);
  25861. }
  25862. };
  25863. /**
  25864. * Blocks a task until it one or more permits have been released. The
  25865. * task will not resume until the requested number of permits have
  25866. * been released with call(s) to unblock().
  25867. *
  25868. * @param n number of permits to wait for(default: 1).
  25869. */
  25870. Task.prototype.block = function(n) {
  25871. n = typeof(n) === 'undefined' ? 1 : n;
  25872. this.blocks += n;
  25873. if(this.blocks > 0) {
  25874. this.state = sStateTable[this.state][BLOCK];
  25875. }
  25876. };
  25877. /**
  25878. * Releases a permit to unblock a task. If a task was blocked by
  25879. * requesting N permits via block(), then it will only continue
  25880. * running once enough permits have been released via unblock() calls.
  25881. *
  25882. * If multiple processes need to synchronize with a single task then
  25883. * use a condition variable (see forge.task.createCondition). It is
  25884. * an error to unblock a task more times than it has been blocked.
  25885. *
  25886. * @param n number of permits to release (default: 1).
  25887. *
  25888. * @return the current block count (task is unblocked when count is 0)
  25889. */
  25890. Task.prototype.unblock = function(n) {
  25891. n = typeof(n) === 'undefined' ? 1 : n;
  25892. this.blocks -= n;
  25893. if(this.blocks === 0 && this.state !== DONE) {
  25894. this.state = RUNNING;
  25895. runNext(this, 0);
  25896. }
  25897. return this.blocks;
  25898. };
  25899. /**
  25900. * Sleep for a period of time before resuming tasks.
  25901. *
  25902. * @param n number of milliseconds to sleep (default: 0).
  25903. */
  25904. Task.prototype.sleep = function(n) {
  25905. n = typeof(n) === 'undefined' ? 0 : n;
  25906. this.state = sStateTable[this.state][SLEEP];
  25907. var self = this;
  25908. this.timeoutId = setTimeout(function() {
  25909. self.timeoutId = null;
  25910. self.state = RUNNING;
  25911. runNext(self, 0);
  25912. }, n);
  25913. };
  25914. /**
  25915. * Waits on a condition variable until notified. The next task will
  25916. * not be scheduled until notification. A condition variable can be
  25917. * created with forge.task.createCondition().
  25918. *
  25919. * Once cond.notify() is called, the task will continue.
  25920. *
  25921. * @param cond the condition variable to wait on.
  25922. */
  25923. Task.prototype.wait = function(cond) {
  25924. cond.wait(this);
  25925. };
  25926. /**
  25927. * If sleeping, wakeup and continue running tasks.
  25928. */
  25929. Task.prototype.wakeup = function() {
  25930. if(this.state === SLEEPING) {
  25931. cancelTimeout(this.timeoutId);
  25932. this.timeoutId = null;
  25933. this.state = RUNNING;
  25934. runNext(this, 0);
  25935. }
  25936. };
  25937. /**
  25938. * Cancel all remaining subtasks of this task.
  25939. */
  25940. Task.prototype.cancel = function() {
  25941. this.state = sStateTable[this.state][CANCEL];
  25942. // remove permits needed
  25943. this.permitsNeeded = 0;
  25944. // cancel timeouts
  25945. if(this.timeoutId !== null) {
  25946. cancelTimeout(this.timeoutId);
  25947. this.timeoutId = null;
  25948. }
  25949. // remove subtasks
  25950. this.subtasks = [];
  25951. };
  25952. /**
  25953. * Finishes this task with failure and sets error flag. The entire
  25954. * task will be aborted unless the next task that should execute
  25955. * is passed as a parameter. This allows levels of subtasks to be
  25956. * skipped. For instance, to abort only this tasks's subtasks, then
  25957. * call fail(task.parent). To abort this task's subtasks and its
  25958. * parent's subtasks, call fail(task.parent.parent). To abort
  25959. * all tasks and simply call the task callback, call fail() or
  25960. * fail(null).
  25961. *
  25962. * The task callback (success or failure) will always, eventually, be
  25963. * called.
  25964. *
  25965. * @param next the task to continue at, or null to abort entirely.
  25966. */
  25967. Task.prototype.fail = function(next) {
  25968. // set error flag
  25969. this.error = true;
  25970. // finish task
  25971. finish(this, true);
  25972. if(next) {
  25973. // propagate task info
  25974. next.error = this.error;
  25975. next.swapTime = this.swapTime;
  25976. next.userData = this.userData;
  25977. // do next task as specified
  25978. runNext(next, 0);
  25979. } else {
  25980. if(this.parent !== null) {
  25981. // finish root task (ensures it is removed from task queue)
  25982. var parent = this.parent;
  25983. while(parent.parent !== null) {
  25984. // propagate task info
  25985. parent.error = this.error;
  25986. parent.swapTime = this.swapTime;
  25987. parent.userData = this.userData;
  25988. parent = parent.parent;
  25989. }
  25990. finish(parent, true);
  25991. }
  25992. // call failure callback if one exists
  25993. if(this.failureCallback) {
  25994. this.failureCallback(this);
  25995. }
  25996. }
  25997. };
  25998. /**
  25999. * Asynchronously start a task.
  26000. *
  26001. * @param task the task to start.
  26002. */
  26003. var start = function(task) {
  26004. task.error = false;
  26005. task.state = sStateTable[task.state][START];
  26006. setTimeout(function() {
  26007. if(task.state === RUNNING) {
  26008. task.swapTime = +new Date();
  26009. task.run(task);
  26010. runNext(task, 0);
  26011. }
  26012. }, 0);
  26013. };
  26014. /**
  26015. * Run the next subtask or finish this task.
  26016. *
  26017. * @param task the task to process.
  26018. * @param recurse the recursion count.
  26019. */
  26020. var runNext = function(task, recurse) {
  26021. // get time since last context swap (ms), if enough time has passed set
  26022. // swap to true to indicate that doNext was performed asynchronously
  26023. // also, if recurse is too high do asynchronously
  26024. var swap =
  26025. (recurse > sMaxRecursions) ||
  26026. (+new Date() - task.swapTime) > sTimeSlice;
  26027. var doNext = function(recurse) {
  26028. recurse++;
  26029. if(task.state === RUNNING) {
  26030. if(swap) {
  26031. // update swap time
  26032. task.swapTime = +new Date();
  26033. }
  26034. if(task.subtasks.length > 0) {
  26035. // run next subtask
  26036. var subtask = task.subtasks.shift();
  26037. subtask.error = task.error;
  26038. subtask.swapTime = task.swapTime;
  26039. subtask.userData = task.userData;
  26040. subtask.run(subtask);
  26041. if(!subtask.error) {
  26042. runNext(subtask, recurse);
  26043. }
  26044. } else {
  26045. finish(task);
  26046. if(!task.error) {
  26047. // chain back up and run parent
  26048. if(task.parent !== null) {
  26049. // propagate task info
  26050. task.parent.error = task.error;
  26051. task.parent.swapTime = task.swapTime;
  26052. task.parent.userData = task.userData;
  26053. // no subtasks left, call run next subtask on parent
  26054. runNext(task.parent, recurse);
  26055. }
  26056. }
  26057. }
  26058. }
  26059. };
  26060. if(swap) {
  26061. // we're swapping, so run asynchronously
  26062. setTimeout(doNext, 0);
  26063. } else {
  26064. // not swapping, so run synchronously
  26065. doNext(recurse);
  26066. }
  26067. };
  26068. /**
  26069. * Finishes a task and looks for the next task in the queue to start.
  26070. *
  26071. * @param task the task to finish.
  26072. * @param suppressCallbacks true to suppress callbacks.
  26073. */
  26074. var finish = function(task, suppressCallbacks) {
  26075. // subtask is now done
  26076. task.state = DONE;
  26077. delete sTasks[task.id];
  26078. // only do queue processing for root tasks
  26079. if(task.parent === null) {
  26080. // report error if queue is missing
  26081. if(!(task.type in sTaskQueues)) {
  26082. forge$1.log.error(cat,
  26083. '[%s][%s] task queue missing [%s]',
  26084. task.id, task.name, task.type);
  26085. } else if(sTaskQueues[task.type].length === 0) {
  26086. // report error if queue is empty
  26087. forge$1.log.error(cat,
  26088. '[%s][%s] task queue empty [%s]',
  26089. task.id, task.name, task.type);
  26090. } else if(sTaskQueues[task.type][0] !== task) {
  26091. // report error if this task isn't the first in the queue
  26092. forge$1.log.error(cat,
  26093. '[%s][%s] task not first in queue [%s]',
  26094. task.id, task.name, task.type);
  26095. } else {
  26096. // remove ourselves from the queue
  26097. sTaskQueues[task.type].shift();
  26098. // clean up queue if it is empty
  26099. if(sTaskQueues[task.type].length === 0) {
  26100. /* Note: Only a task can delete a queue of its own type. This
  26101. is used as a way to synchronize tasks. If a queue for a certain
  26102. task type exists, then a task of that type is running.
  26103. */
  26104. delete sTaskQueues[task.type];
  26105. } else {
  26106. sTaskQueues[task.type][0].start();
  26107. }
  26108. }
  26109. if(!suppressCallbacks) {
  26110. // call final callback if one exists
  26111. if(task.error && task.failureCallback) {
  26112. task.failureCallback(task);
  26113. } else if(!task.error && task.successCallback) {
  26114. task.successCallback(task);
  26115. }
  26116. }
  26117. }
  26118. };
  26119. /* Tasks API */
  26120. forge$1.task = forge$1.task || {};
  26121. /**
  26122. * Starts a new task that will run the passed function asynchronously.
  26123. *
  26124. * In order to finish the task, either task.doNext() or task.fail()
  26125. * *must* be called.
  26126. *
  26127. * The task must have a type (a string identifier) that can be used to
  26128. * synchronize it with other tasks of the same type. That type can also
  26129. * be used to cancel tasks that haven't started yet.
  26130. *
  26131. * To start a task, the following object must be provided as a parameter
  26132. * (each function takes a task object as its first parameter):
  26133. *
  26134. * {
  26135. * type: the type of task.
  26136. * run: the function to run to execute the task.
  26137. * success: a callback to call when the task succeeds (optional).
  26138. * failure: a callback to call when the task fails (optional).
  26139. * }
  26140. *
  26141. * @param options the object as described above.
  26142. */
  26143. forge$1.task.start = function(options) {
  26144. // create a new task
  26145. var task = new Task({
  26146. run: options.run,
  26147. name: options.name || sNoTaskName
  26148. });
  26149. task.type = options.type;
  26150. task.successCallback = options.success || null;
  26151. task.failureCallback = options.failure || null;
  26152. // append the task onto the appropriate queue
  26153. if(!(task.type in sTaskQueues)) {
  26154. // create the queue with the new task
  26155. sTaskQueues[task.type] = [task];
  26156. start(task);
  26157. } else {
  26158. // push the task onto the queue, it will be run after a task
  26159. // with the same type completes
  26160. sTaskQueues[options.type].push(task);
  26161. }
  26162. };
  26163. /**
  26164. * Cancels all tasks of the given type that haven't started yet.
  26165. *
  26166. * @param type the type of task to cancel.
  26167. */
  26168. forge$1.task.cancel = function(type) {
  26169. // find the task queue
  26170. if(type in sTaskQueues) {
  26171. // empty all but the current task from the queue
  26172. sTaskQueues[type] = [sTaskQueues[type][0]];
  26173. }
  26174. };
  26175. /**
  26176. * Creates a condition variable to synchronize tasks. To make a task wait
  26177. * on the condition variable, call task.wait(condition). To notify all
  26178. * tasks that are waiting, call condition.notify().
  26179. *
  26180. * @return the condition variable.
  26181. */
  26182. forge$1.task.createCondition = function() {
  26183. var cond = {
  26184. // all tasks that are blocked
  26185. tasks: {}
  26186. };
  26187. /**
  26188. * Causes the given task to block until notify is called. If the task
  26189. * is already waiting on this condition then this is a no-op.
  26190. *
  26191. * @param task the task to cause to wait.
  26192. */
  26193. cond.wait = function(task) {
  26194. // only block once
  26195. if(!(task.id in cond.tasks)) {
  26196. task.block();
  26197. cond.tasks[task.id] = task;
  26198. }
  26199. };
  26200. /**
  26201. * Notifies all waiting tasks to wake up.
  26202. */
  26203. cond.notify = function() {
  26204. // since unblock() will run the next task from here, make sure to
  26205. // clear the condition's blocked task list before unblocking
  26206. var tmp = cond.tasks;
  26207. cond.tasks = {};
  26208. for(var id in tmp) {
  26209. tmp[id].unblock();
  26210. }
  26211. };
  26212. return cond;
  26213. };
  26214. /**
  26215. * Node.js module for Forge.
  26216. *
  26217. * @author Dave Longley
  26218. *
  26219. * Copyright 2011-2016 Digital Bazaar, Inc.
  26220. */
  26221. var lib = forge$F;
  26222. var forge = lib;
  26223. // a hexString is considered negative if it's most significant bit is 1
  26224. // because serial numbers use ones' complement notation
  26225. // this RFC in section 4.1.2.2 requires serial numbers to be positive
  26226. // http://www.ietf.org/rfc/rfc5280.txt
  26227. function toPositiveHex(hexString){
  26228. var mostSiginficativeHexAsInt = parseInt(hexString[0], 16);
  26229. if (mostSiginficativeHexAsInt < 8){
  26230. return hexString;
  26231. }
  26232. mostSiginficativeHexAsInt -= 8;
  26233. return mostSiginficativeHexAsInt.toString() + hexString.substring(1);
  26234. }
  26235. function getAlgorithm(key) {
  26236. switch (key) {
  26237. case 'sha256':
  26238. return forge.md.sha256.create();
  26239. default:
  26240. return forge.md.sha1.create();
  26241. }
  26242. }
  26243. /**
  26244. *
  26245. * @param {forge.pki.CertificateField[]} attrs Attributes used for subject and issuer.
  26246. * @param {object} options
  26247. * @param {number} [options.days=365] the number of days before expiration
  26248. * @param {number} [options.keySize=1024] the size for the private key in bits
  26249. * @param {object} [options.extensions] additional extensions for the certificate
  26250. * @param {string} [options.algorithm="sha1"] The signature algorithm sha256 or sha1
  26251. * @param {boolean} [options.pkcs7=false] include PKCS#7 as part of the output
  26252. * @param {boolean} [options.clientCertificate=false] generate client cert signed by the original key
  26253. * @param {string} [options.clientCertificateCN="John Doe jdoe123"] client certificate's common name
  26254. * @param {function} [done] Optional callback, if not provided the generation is synchronous
  26255. * @returns
  26256. */
  26257. var generate = selfsigned.generate = function generate(attrs, options, done) {
  26258. if (typeof attrs === 'function') {
  26259. done = attrs;
  26260. attrs = undefined;
  26261. } else if (typeof options === 'function') {
  26262. done = options;
  26263. options = {};
  26264. }
  26265. options = options || {};
  26266. var generatePem = function (keyPair) {
  26267. var cert = forge.pki.createCertificate();
  26268. cert.serialNumber = toPositiveHex(forge.util.bytesToHex(forge.random.getBytesSync(9))); // the serial number can be decimal or hex (if preceded by 0x)
  26269. cert.validity.notBefore = new Date();
  26270. cert.validity.notAfter = new Date();
  26271. cert.validity.notAfter.setDate(cert.validity.notBefore.getDate() + (options.days || 365));
  26272. attrs = attrs || [{
  26273. name: 'commonName',
  26274. value: 'example.org'
  26275. }, {
  26276. name: 'countryName',
  26277. value: 'US'
  26278. }, {
  26279. shortName: 'ST',
  26280. value: 'Virginia'
  26281. }, {
  26282. name: 'localityName',
  26283. value: 'Blacksburg'
  26284. }, {
  26285. name: 'organizationName',
  26286. value: 'Test'
  26287. }, {
  26288. shortName: 'OU',
  26289. value: 'Test'
  26290. }];
  26291. cert.setSubject(attrs);
  26292. cert.setIssuer(attrs);
  26293. cert.publicKey = keyPair.publicKey;
  26294. cert.setExtensions(options.extensions || [{
  26295. name: 'basicConstraints',
  26296. cA: true
  26297. }, {
  26298. name: 'keyUsage',
  26299. keyCertSign: true,
  26300. digitalSignature: true,
  26301. nonRepudiation: true,
  26302. keyEncipherment: true,
  26303. dataEncipherment: true
  26304. }, {
  26305. name: 'subjectAltName',
  26306. altNames: [{
  26307. type: 6, // URI
  26308. value: 'http://example.org/webid#me'
  26309. }]
  26310. }]);
  26311. cert.sign(keyPair.privateKey, getAlgorithm(options && options.algorithm));
  26312. const fingerprint = forge.md.sha1
  26313. .create()
  26314. .update(forge.asn1.toDer(forge.pki.certificateToAsn1(cert)).getBytes())
  26315. .digest()
  26316. .toHex()
  26317. .match(/.{2}/g)
  26318. .join(':');
  26319. var pem = {
  26320. private: forge.pki.privateKeyToPem(keyPair.privateKey),
  26321. public: forge.pki.publicKeyToPem(keyPair.publicKey),
  26322. cert: forge.pki.certificateToPem(cert),
  26323. fingerprint: fingerprint,
  26324. };
  26325. if (options && options.pkcs7) {
  26326. var p7 = forge.pkcs7.createSignedData();
  26327. p7.addCertificate(cert);
  26328. pem.pkcs7 = forge.pkcs7.messageToPem(p7);
  26329. }
  26330. if (options && options.clientCertificate) {
  26331. var clientkeys = forge.pki.rsa.generateKeyPair(1024);
  26332. var clientcert = forge.pki.createCertificate();
  26333. clientcert.serialNumber = toPositiveHex(forge.util.bytesToHex(forge.random.getBytesSync(9)));
  26334. clientcert.validity.notBefore = new Date();
  26335. clientcert.validity.notAfter = new Date();
  26336. clientcert.validity.notAfter.setFullYear(clientcert.validity.notBefore.getFullYear() + 1);
  26337. var clientAttrs = JSON.parse(JSON.stringify(attrs));
  26338. for(var i = 0; i < clientAttrs.length; i++) {
  26339. if(clientAttrs[i].name === 'commonName') {
  26340. if( options.clientCertificateCN )
  26341. clientAttrs[i] = { name: 'commonName', value: options.clientCertificateCN };
  26342. else
  26343. clientAttrs[i] = { name: 'commonName', value: 'John Doe jdoe123' };
  26344. }
  26345. }
  26346. clientcert.setSubject(clientAttrs);
  26347. // Set the issuer to the parent key
  26348. clientcert.setIssuer(attrs);
  26349. clientcert.publicKey = clientkeys.publicKey;
  26350. // Sign client cert with root cert
  26351. clientcert.sign(keyPair.privateKey);
  26352. pem.clientprivate = forge.pki.privateKeyToPem(clientkeys.privateKey);
  26353. pem.clientpublic = forge.pki.publicKeyToPem(clientkeys.publicKey);
  26354. pem.clientcert = forge.pki.certificateToPem(clientcert);
  26355. if (options.pkcs7) {
  26356. var clientp7 = forge.pkcs7.createSignedData();
  26357. clientp7.addCertificate(clientcert);
  26358. pem.clientpkcs7 = forge.pkcs7.messageToPem(clientp7);
  26359. }
  26360. }
  26361. var caStore = forge.pki.createCaStore();
  26362. caStore.addCertificate(cert);
  26363. try {
  26364. forge.pki.verifyCertificateChain(caStore, [cert],
  26365. function (vfd, depth, chain) {
  26366. if (vfd !== true) {
  26367. throw new Error('Certificate could not be verified.');
  26368. }
  26369. return true;
  26370. });
  26371. }
  26372. catch(ex) {
  26373. throw new Error(ex);
  26374. }
  26375. return pem;
  26376. };
  26377. var keySize = options.keySize || 1024;
  26378. if (done) { // async scenario
  26379. return forge.pki.rsa.generateKeyPair({ bits: keySize }, function (err, keyPair) {
  26380. if (err) { return done(err); }
  26381. try {
  26382. return done(null, generatePem(keyPair));
  26383. } catch (ex) {
  26384. return done(ex);
  26385. }
  26386. });
  26387. }
  26388. var keyPair = options.keyPair ? {
  26389. privateKey: forge.pki.privateKeyFromPem(options.keyPair.privateKey),
  26390. publicKey: forge.pki.publicKeyFromPem(options.keyPair.publicKey)
  26391. } : forge.pki.rsa.generateKeyPair(keySize);
  26392. return generatePem(keyPair);
  26393. };
  26394. var index = /*#__PURE__*/Object.assign(/*#__PURE__*/Object.create(null), selfsigned, {
  26395. 'default': selfsigned,
  26396. generate: generate
  26397. });
  26398. exports.index = index;
  26399. //# sourceMappingURL=dep-0e948eb3.js.map