dep-24755698.js 577 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600
  1. 'use strict';
  2. var index = require('./dep-689425f3.js');
  3. var require$$1 = require('crypto');
  4. require('fs');
  5. require('path');
  6. require('url');
  7. require('perf_hooks');
  8. require('tty');
  9. require('os');
  10. require('esbuild');
  11. require('events');
  12. require('assert');
  13. require('resolve');
  14. require('util');
  15. require('stream');
  16. require('net');
  17. require('http');
  18. require('child_process');
  19. require('module');
  20. require('buffer');
  21. require('querystring');
  22. require('zlib');
  23. require('https');
  24. require('tls');
  25. require('worker_threads');
  26. require('readline');
  27. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
  28. var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1);
  29. /**
  30. * Node.js module for Forge.
  31. *
  32. * @author Dave Longley
  33. *
  34. * Copyright 2011-2016 Digital Bazaar, Inc.
  35. */
  36. var forge$s = {
  37. // default options
  38. options: {
  39. usePureJavaScript: false
  40. }
  41. };
  42. /**
  43. * Base-N/Base-X encoding/decoding functions.
  44. *
  45. * Original implementation from base-x:
  46. * https://github.com/cryptocoinjs/base-x
  47. *
  48. * Which is MIT licensed:
  49. *
  50. * The MIT License (MIT)
  51. *
  52. * Copyright base-x contributors (c) 2016
  53. *
  54. * Permission is hereby granted, free of charge, to any person obtaining a copy
  55. * of this software and associated documentation files (the "Software"), to deal
  56. * in the Software without restriction, including without limitation the rights
  57. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  58. * copies of the Software, and to permit persons to whom the Software is
  59. * furnished to do so, subject to the following conditions:
  60. *
  61. * The above copyright notice and this permission notice shall be included in
  62. * all copies or substantial portions of the Software.
  63. *
  64. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  65. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  66. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  67. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  68. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  69. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  70. * DEALINGS IN THE SOFTWARE.
  71. */
  72. var api = {};
  73. var baseN$1 = api;
  74. // baseN alphabet indexes
  75. var _reverseAlphabets = {};
  76. /**
  77. * BaseN-encodes a Uint8Array using the given alphabet.
  78. *
  79. * @param input the Uint8Array to encode.
  80. * @param maxline the maximum number of encoded characters per line to use,
  81. * defaults to none.
  82. *
  83. * @return the baseN-encoded output string.
  84. */
  85. api.encode = function(input, alphabet, maxline) {
  86. if(typeof alphabet !== 'string') {
  87. throw new TypeError('"alphabet" must be a string.');
  88. }
  89. if(maxline !== undefined && typeof maxline !== 'number') {
  90. throw new TypeError('"maxline" must be a number.');
  91. }
  92. var output = '';
  93. if(!(input instanceof Uint8Array)) {
  94. // assume forge byte buffer
  95. output = _encodeWithByteBuffer(input, alphabet);
  96. } else {
  97. var i = 0;
  98. var base = alphabet.length;
  99. var first = alphabet.charAt(0);
  100. var digits = [0];
  101. for(i = 0; i < input.length; ++i) {
  102. for(var j = 0, carry = input[i]; j < digits.length; ++j) {
  103. carry += digits[j] << 8;
  104. digits[j] = carry % base;
  105. carry = (carry / base) | 0;
  106. }
  107. while(carry > 0) {
  108. digits.push(carry % base);
  109. carry = (carry / base) | 0;
  110. }
  111. }
  112. // deal with leading zeros
  113. for(i = 0; input[i] === 0 && i < input.length - 1; ++i) {
  114. output += first;
  115. }
  116. // convert digits to a string
  117. for(i = digits.length - 1; i >= 0; --i) {
  118. output += alphabet[digits[i]];
  119. }
  120. }
  121. if(maxline) {
  122. var regex = new RegExp('.{1,' + maxline + '}', 'g');
  123. output = output.match(regex).join('\r\n');
  124. }
  125. return output;
  126. };
  127. /**
  128. * Decodes a baseN-encoded (using the given alphabet) string to a
  129. * Uint8Array.
  130. *
  131. * @param input the baseN-encoded input string.
  132. *
  133. * @return the Uint8Array.
  134. */
  135. api.decode = function(input, alphabet) {
  136. if(typeof input !== 'string') {
  137. throw new TypeError('"input" must be a string.');
  138. }
  139. if(typeof alphabet !== 'string') {
  140. throw new TypeError('"alphabet" must be a string.');
  141. }
  142. var table = _reverseAlphabets[alphabet];
  143. if(!table) {
  144. // compute reverse alphabet
  145. table = _reverseAlphabets[alphabet] = [];
  146. for(var i = 0; i < alphabet.length; ++i) {
  147. table[alphabet.charCodeAt(i)] = i;
  148. }
  149. }
  150. // remove whitespace characters
  151. input = input.replace(/\s/g, '');
  152. var base = alphabet.length;
  153. var first = alphabet.charAt(0);
  154. var bytes = [0];
  155. for(var i = 0; i < input.length; i++) {
  156. var value = table[input.charCodeAt(i)];
  157. if(value === undefined) {
  158. return;
  159. }
  160. for(var j = 0, carry = value; j < bytes.length; ++j) {
  161. carry += bytes[j] * base;
  162. bytes[j] = carry & 0xff;
  163. carry >>= 8;
  164. }
  165. while(carry > 0) {
  166. bytes.push(carry & 0xff);
  167. carry >>= 8;
  168. }
  169. }
  170. // deal with leading zeros
  171. for(var k = 0; input[k] === first && k < input.length - 1; ++k) {
  172. bytes.push(0);
  173. }
  174. if(typeof Buffer !== 'undefined') {
  175. return Buffer.from(bytes.reverse());
  176. }
  177. return new Uint8Array(bytes.reverse());
  178. };
  179. function _encodeWithByteBuffer(input, alphabet) {
  180. var i = 0;
  181. var base = alphabet.length;
  182. var first = alphabet.charAt(0);
  183. var digits = [0];
  184. for(i = 0; i < input.length(); ++i) {
  185. for(var j = 0, carry = input.at(i); j < digits.length; ++j) {
  186. carry += digits[j] << 8;
  187. digits[j] = carry % base;
  188. carry = (carry / base) | 0;
  189. }
  190. while(carry > 0) {
  191. digits.push(carry % base);
  192. carry = (carry / base) | 0;
  193. }
  194. }
  195. var output = '';
  196. // deal with leading zeros
  197. for(i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) {
  198. output += first;
  199. }
  200. // convert digits to a string
  201. for(i = digits.length - 1; i >= 0; --i) {
  202. output += alphabet[digits[i]];
  203. }
  204. return output;
  205. }
  206. /**
  207. * Utility functions for web applications.
  208. *
  209. * @author Dave Longley
  210. *
  211. * Copyright (c) 2010-2018 Digital Bazaar, Inc.
  212. */
  213. var forge$r = forge$s;
  214. var baseN = baseN$1;
  215. /* Utilities API */
  216. var util$1 = forge$r.util = forge$r.util || {};
  217. // define setImmediate and nextTick
  218. (function() {
  219. // use native nextTick (unless we're in webpack)
  220. // webpack (or better node-libs-browser polyfill) sets process.browser.
  221. // this way we can detect webpack properly
  222. if(typeof process !== 'undefined' && process.nextTick && !process.browser) {
  223. util$1.nextTick = process.nextTick;
  224. if(typeof setImmediate === 'function') {
  225. util$1.setImmediate = setImmediate;
  226. } else {
  227. // polyfill setImmediate with nextTick, older versions of node
  228. // (those w/o setImmediate) won't totally starve IO
  229. util$1.setImmediate = util$1.nextTick;
  230. }
  231. return;
  232. }
  233. // polyfill nextTick with native setImmediate
  234. if(typeof setImmediate === 'function') {
  235. util$1.setImmediate = function() { return setImmediate.apply(undefined, arguments); };
  236. util$1.nextTick = function(callback) {
  237. return setImmediate(callback);
  238. };
  239. return;
  240. }
  241. /* Note: A polyfill upgrade pattern is used here to allow combining
  242. polyfills. For example, MutationObserver is fast, but blocks UI updates,
  243. so it needs to allow UI updates periodically, so it falls back on
  244. postMessage or setTimeout. */
  245. // polyfill with setTimeout
  246. util$1.setImmediate = function(callback) {
  247. setTimeout(callback, 0);
  248. };
  249. // upgrade polyfill to use postMessage
  250. if(typeof window !== 'undefined' &&
  251. typeof window.postMessage === 'function') {
  252. var msg = 'forge.setImmediate';
  253. var callbacks = [];
  254. util$1.setImmediate = function(callback) {
  255. callbacks.push(callback);
  256. // only send message when one hasn't been sent in
  257. // the current turn of the event loop
  258. if(callbacks.length === 1) {
  259. window.postMessage(msg, '*');
  260. }
  261. };
  262. function handler(event) {
  263. if(event.source === window && event.data === msg) {
  264. event.stopPropagation();
  265. var copy = callbacks.slice();
  266. callbacks.length = 0;
  267. copy.forEach(function(callback) {
  268. callback();
  269. });
  270. }
  271. }
  272. window.addEventListener('message', handler, true);
  273. }
  274. // upgrade polyfill to use MutationObserver
  275. if(typeof MutationObserver !== 'undefined') {
  276. // polyfill with MutationObserver
  277. var now = Date.now();
  278. var attr = true;
  279. var div = document.createElement('div');
  280. var callbacks = [];
  281. new MutationObserver(function() {
  282. var copy = callbacks.slice();
  283. callbacks.length = 0;
  284. copy.forEach(function(callback) {
  285. callback();
  286. });
  287. }).observe(div, {attributes: true});
  288. var oldSetImmediate = util$1.setImmediate;
  289. util$1.setImmediate = function(callback) {
  290. if(Date.now() - now > 15) {
  291. now = Date.now();
  292. oldSetImmediate(callback);
  293. } else {
  294. callbacks.push(callback);
  295. // only trigger observer when it hasn't been triggered in
  296. // the current turn of the event loop
  297. if(callbacks.length === 1) {
  298. div.setAttribute('a', attr = !attr);
  299. }
  300. }
  301. };
  302. }
  303. util$1.nextTick = util$1.setImmediate;
  304. })();
  305. // check if running under Node.js
  306. util$1.isNodejs =
  307. typeof process !== 'undefined' && process.versions && process.versions.node;
  308. // 'self' will also work in Web Workers (instance of WorkerGlobalScope) while
  309. // it will point to `window` in the main thread.
  310. // To remain compatible with older browsers, we fall back to 'window' if 'self'
  311. // is not available.
  312. util$1.globalScope = (function() {
  313. if(util$1.isNodejs) {
  314. return index.commonjsGlobal;
  315. }
  316. return typeof self === 'undefined' ? window : self;
  317. })();
  318. // define isArray
  319. util$1.isArray = Array.isArray || function(x) {
  320. return Object.prototype.toString.call(x) === '[object Array]';
  321. };
  322. // define isArrayBuffer
  323. util$1.isArrayBuffer = function(x) {
  324. return typeof ArrayBuffer !== 'undefined' && x instanceof ArrayBuffer;
  325. };
  326. // define isArrayBufferView
  327. util$1.isArrayBufferView = function(x) {
  328. return x && util$1.isArrayBuffer(x.buffer) && x.byteLength !== undefined;
  329. };
  330. /**
  331. * Ensure a bits param is 8, 16, 24, or 32. Used to validate input for
  332. * algorithms where bit manipulation, JavaScript limitations, and/or algorithm
  333. * design only allow for byte operations of a limited size.
  334. *
  335. * @param n number of bits.
  336. *
  337. * Throw Error if n invalid.
  338. */
  339. function _checkBitsParam(n) {
  340. if(!(n === 8 || n === 16 || n === 24 || n === 32)) {
  341. throw new Error('Only 8, 16, 24, or 32 bits supported: ' + n);
  342. }
  343. }
  344. // TODO: set ByteBuffer to best available backing
  345. util$1.ByteBuffer = ByteStringBuffer;
  346. /** Buffer w/BinaryString backing */
  347. /**
  348. * Constructor for a binary string backed byte buffer.
  349. *
  350. * @param [b] the bytes to wrap (either encoded as string, one byte per
  351. * character, or as an ArrayBuffer or Typed Array).
  352. */
  353. function ByteStringBuffer(b) {
  354. // TODO: update to match DataBuffer API
  355. // the data in this buffer
  356. this.data = '';
  357. // the pointer for reading from this buffer
  358. this.read = 0;
  359. if(typeof b === 'string') {
  360. this.data = b;
  361. } else if(util$1.isArrayBuffer(b) || util$1.isArrayBufferView(b)) {
  362. if(typeof Buffer !== 'undefined' && b instanceof Buffer) {
  363. this.data = b.toString('binary');
  364. } else {
  365. // convert native buffer to forge buffer
  366. // FIXME: support native buffers internally instead
  367. var arr = new Uint8Array(b);
  368. try {
  369. this.data = String.fromCharCode.apply(null, arr);
  370. } catch(e) {
  371. for(var i = 0; i < arr.length; ++i) {
  372. this.putByte(arr[i]);
  373. }
  374. }
  375. }
  376. } else if(b instanceof ByteStringBuffer ||
  377. (typeof b === 'object' && typeof b.data === 'string' &&
  378. typeof b.read === 'number')) {
  379. // copy existing buffer
  380. this.data = b.data;
  381. this.read = b.read;
  382. }
  383. // used for v8 optimization
  384. this._constructedStringLength = 0;
  385. }
  386. util$1.ByteStringBuffer = ByteStringBuffer;
  387. /* Note: This is an optimization for V8-based browsers. When V8 concatenates
  388. a string, the strings are only joined logically using a "cons string" or
  389. "constructed/concatenated string". These containers keep references to one
  390. another and can result in very large memory usage. For example, if a 2MB
  391. string is constructed by concatenating 4 bytes together at a time, the
  392. memory usage will be ~44MB; so ~22x increase. The strings are only joined
  393. together when an operation requiring their joining takes place, such as
  394. substr(). This function is called when adding data to this buffer to ensure
  395. these types of strings are periodically joined to reduce the memory
  396. footprint. */
  397. var _MAX_CONSTRUCTED_STRING_LENGTH = 4096;
  398. util$1.ByteStringBuffer.prototype._optimizeConstructedString = function(x) {
  399. this._constructedStringLength += x;
  400. if(this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) {
  401. // this substr() should cause the constructed string to join
  402. this.data.substr(0, 1);
  403. this._constructedStringLength = 0;
  404. }
  405. };
  406. /**
  407. * Gets the number of bytes in this buffer.
  408. *
  409. * @return the number of bytes in this buffer.
  410. */
  411. util$1.ByteStringBuffer.prototype.length = function() {
  412. return this.data.length - this.read;
  413. };
  414. /**
  415. * Gets whether or not this buffer is empty.
  416. *
  417. * @return true if this buffer is empty, false if not.
  418. */
  419. util$1.ByteStringBuffer.prototype.isEmpty = function() {
  420. return this.length() <= 0;
  421. };
  422. /**
  423. * Puts a byte in this buffer.
  424. *
  425. * @param b the byte to put.
  426. *
  427. * @return this buffer.
  428. */
  429. util$1.ByteStringBuffer.prototype.putByte = function(b) {
  430. return this.putBytes(String.fromCharCode(b));
  431. };
  432. /**
  433. * Puts a byte in this buffer N times.
  434. *
  435. * @param b the byte to put.
  436. * @param n the number of bytes of value b to put.
  437. *
  438. * @return this buffer.
  439. */
  440. util$1.ByteStringBuffer.prototype.fillWithByte = function(b, n) {
  441. b = String.fromCharCode(b);
  442. var d = this.data;
  443. while(n > 0) {
  444. if(n & 1) {
  445. d += b;
  446. }
  447. n >>>= 1;
  448. if(n > 0) {
  449. b += b;
  450. }
  451. }
  452. this.data = d;
  453. this._optimizeConstructedString(n);
  454. return this;
  455. };
  456. /**
  457. * Puts bytes in this buffer.
  458. *
  459. * @param bytes the bytes (as a binary encoded string) to put.
  460. *
  461. * @return this buffer.
  462. */
  463. util$1.ByteStringBuffer.prototype.putBytes = function(bytes) {
  464. this.data += bytes;
  465. this._optimizeConstructedString(bytes.length);
  466. return this;
  467. };
  468. /**
  469. * Puts a UTF-16 encoded string into this buffer.
  470. *
  471. * @param str the string to put.
  472. *
  473. * @return this buffer.
  474. */
  475. util$1.ByteStringBuffer.prototype.putString = function(str) {
  476. return this.putBytes(util$1.encodeUtf8(str));
  477. };
  478. /**
  479. * Puts a 16-bit integer in this buffer in big-endian order.
  480. *
  481. * @param i the 16-bit integer.
  482. *
  483. * @return this buffer.
  484. */
  485. util$1.ByteStringBuffer.prototype.putInt16 = function(i) {
  486. return this.putBytes(
  487. String.fromCharCode(i >> 8 & 0xFF) +
  488. String.fromCharCode(i & 0xFF));
  489. };
  490. /**
  491. * Puts a 24-bit integer in this buffer in big-endian order.
  492. *
  493. * @param i the 24-bit integer.
  494. *
  495. * @return this buffer.
  496. */
  497. util$1.ByteStringBuffer.prototype.putInt24 = function(i) {
  498. return this.putBytes(
  499. String.fromCharCode(i >> 16 & 0xFF) +
  500. String.fromCharCode(i >> 8 & 0xFF) +
  501. String.fromCharCode(i & 0xFF));
  502. };
  503. /**
  504. * Puts a 32-bit integer in this buffer in big-endian order.
  505. *
  506. * @param i the 32-bit integer.
  507. *
  508. * @return this buffer.
  509. */
  510. util$1.ByteStringBuffer.prototype.putInt32 = function(i) {
  511. return this.putBytes(
  512. String.fromCharCode(i >> 24 & 0xFF) +
  513. String.fromCharCode(i >> 16 & 0xFF) +
  514. String.fromCharCode(i >> 8 & 0xFF) +
  515. String.fromCharCode(i & 0xFF));
  516. };
  517. /**
  518. * Puts a 16-bit integer in this buffer in little-endian order.
  519. *
  520. * @param i the 16-bit integer.
  521. *
  522. * @return this buffer.
  523. */
  524. util$1.ByteStringBuffer.prototype.putInt16Le = function(i) {
  525. return this.putBytes(
  526. String.fromCharCode(i & 0xFF) +
  527. String.fromCharCode(i >> 8 & 0xFF));
  528. };
  529. /**
  530. * Puts a 24-bit integer in this buffer in little-endian order.
  531. *
  532. * @param i the 24-bit integer.
  533. *
  534. * @return this buffer.
  535. */
  536. util$1.ByteStringBuffer.prototype.putInt24Le = function(i) {
  537. return this.putBytes(
  538. String.fromCharCode(i & 0xFF) +
  539. String.fromCharCode(i >> 8 & 0xFF) +
  540. String.fromCharCode(i >> 16 & 0xFF));
  541. };
  542. /**
  543. * Puts a 32-bit integer in this buffer in little-endian order.
  544. *
  545. * @param i the 32-bit integer.
  546. *
  547. * @return this buffer.
  548. */
  549. util$1.ByteStringBuffer.prototype.putInt32Le = function(i) {
  550. return this.putBytes(
  551. String.fromCharCode(i & 0xFF) +
  552. String.fromCharCode(i >> 8 & 0xFF) +
  553. String.fromCharCode(i >> 16 & 0xFF) +
  554. String.fromCharCode(i >> 24 & 0xFF));
  555. };
  556. /**
  557. * Puts an n-bit integer in this buffer in big-endian order.
  558. *
  559. * @param i the n-bit integer.
  560. * @param n the number of bits in the integer (8, 16, 24, or 32).
  561. *
  562. * @return this buffer.
  563. */
  564. util$1.ByteStringBuffer.prototype.putInt = function(i, n) {
  565. _checkBitsParam(n);
  566. var bytes = '';
  567. do {
  568. n -= 8;
  569. bytes += String.fromCharCode((i >> n) & 0xFF);
  570. } while(n > 0);
  571. return this.putBytes(bytes);
  572. };
  573. /**
  574. * Puts a signed n-bit integer in this buffer in big-endian order. Two's
  575. * complement representation is used.
  576. *
  577. * @param i the n-bit integer.
  578. * @param n the number of bits in the integer (8, 16, 24, or 32).
  579. *
  580. * @return this buffer.
  581. */
  582. util$1.ByteStringBuffer.prototype.putSignedInt = function(i, n) {
  583. // putInt checks n
  584. if(i < 0) {
  585. i += 2 << (n - 1);
  586. }
  587. return this.putInt(i, n);
  588. };
  589. /**
  590. * Puts the given buffer into this buffer.
  591. *
  592. * @param buffer the buffer to put into this one.
  593. *
  594. * @return this buffer.
  595. */
  596. util$1.ByteStringBuffer.prototype.putBuffer = function(buffer) {
  597. return this.putBytes(buffer.getBytes());
  598. };
  599. /**
  600. * Gets a byte from this buffer and advances the read pointer by 1.
  601. *
  602. * @return the byte.
  603. */
  604. util$1.ByteStringBuffer.prototype.getByte = function() {
  605. return this.data.charCodeAt(this.read++);
  606. };
  607. /**
  608. * Gets a uint16 from this buffer in big-endian order and advances the read
  609. * pointer by 2.
  610. *
  611. * @return the uint16.
  612. */
  613. util$1.ByteStringBuffer.prototype.getInt16 = function() {
  614. var rval = (
  615. this.data.charCodeAt(this.read) << 8 ^
  616. this.data.charCodeAt(this.read + 1));
  617. this.read += 2;
  618. return rval;
  619. };
  620. /**
  621. * Gets a uint24 from this buffer in big-endian order and advances the read
  622. * pointer by 3.
  623. *
  624. * @return the uint24.
  625. */
  626. util$1.ByteStringBuffer.prototype.getInt24 = function() {
  627. var rval = (
  628. this.data.charCodeAt(this.read) << 16 ^
  629. this.data.charCodeAt(this.read + 1) << 8 ^
  630. this.data.charCodeAt(this.read + 2));
  631. this.read += 3;
  632. return rval;
  633. };
  634. /**
  635. * Gets a uint32 from this buffer in big-endian order and advances the read
  636. * pointer by 4.
  637. *
  638. * @return the word.
  639. */
  640. util$1.ByteStringBuffer.prototype.getInt32 = function() {
  641. var rval = (
  642. this.data.charCodeAt(this.read) << 24 ^
  643. this.data.charCodeAt(this.read + 1) << 16 ^
  644. this.data.charCodeAt(this.read + 2) << 8 ^
  645. this.data.charCodeAt(this.read + 3));
  646. this.read += 4;
  647. return rval;
  648. };
  649. /**
  650. * Gets a uint16 from this buffer in little-endian order and advances the read
  651. * pointer by 2.
  652. *
  653. * @return the uint16.
  654. */
  655. util$1.ByteStringBuffer.prototype.getInt16Le = function() {
  656. var rval = (
  657. this.data.charCodeAt(this.read) ^
  658. this.data.charCodeAt(this.read + 1) << 8);
  659. this.read += 2;
  660. return rval;
  661. };
  662. /**
  663. * Gets a uint24 from this buffer in little-endian order and advances the read
  664. * pointer by 3.
  665. *
  666. * @return the uint24.
  667. */
  668. util$1.ByteStringBuffer.prototype.getInt24Le = function() {
  669. var rval = (
  670. this.data.charCodeAt(this.read) ^
  671. this.data.charCodeAt(this.read + 1) << 8 ^
  672. this.data.charCodeAt(this.read + 2) << 16);
  673. this.read += 3;
  674. return rval;
  675. };
  676. /**
  677. * Gets a uint32 from this buffer in little-endian order and advances the read
  678. * pointer by 4.
  679. *
  680. * @return the word.
  681. */
  682. util$1.ByteStringBuffer.prototype.getInt32Le = function() {
  683. var rval = (
  684. this.data.charCodeAt(this.read) ^
  685. this.data.charCodeAt(this.read + 1) << 8 ^
  686. this.data.charCodeAt(this.read + 2) << 16 ^
  687. this.data.charCodeAt(this.read + 3) << 24);
  688. this.read += 4;
  689. return rval;
  690. };
  691. /**
  692. * Gets an n-bit integer from this buffer in big-endian order and advances the
  693. * read pointer by ceil(n/8).
  694. *
  695. * @param n the number of bits in the integer (8, 16, 24, or 32).
  696. *
  697. * @return the integer.
  698. */
  699. util$1.ByteStringBuffer.prototype.getInt = function(n) {
  700. _checkBitsParam(n);
  701. var rval = 0;
  702. do {
  703. // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits.
  704. rval = (rval << 8) + this.data.charCodeAt(this.read++);
  705. n -= 8;
  706. } while(n > 0);
  707. return rval;
  708. };
  709. /**
  710. * Gets a signed n-bit integer from this buffer in big-endian order, using
  711. * two's complement, and advances the read pointer by n/8.
  712. *
  713. * @param n the number of bits in the integer (8, 16, 24, or 32).
  714. *
  715. * @return the integer.
  716. */
  717. util$1.ByteStringBuffer.prototype.getSignedInt = function(n) {
  718. // getInt checks n
  719. var x = this.getInt(n);
  720. var max = 2 << (n - 2);
  721. if(x >= max) {
  722. x -= max << 1;
  723. }
  724. return x;
  725. };
  726. /**
  727. * Reads bytes out as a binary encoded string and clears them from the
  728. * buffer. Note that the resulting string is binary encoded (in node.js this
  729. * encoding is referred to as `binary`, it is *not* `utf8`).
  730. *
  731. * @param count the number of bytes to read, undefined or null for all.
  732. *
  733. * @return a binary encoded string of bytes.
  734. */
  735. util$1.ByteStringBuffer.prototype.getBytes = function(count) {
  736. var rval;
  737. if(count) {
  738. // read count bytes
  739. count = Math.min(this.length(), count);
  740. rval = this.data.slice(this.read, this.read + count);
  741. this.read += count;
  742. } else if(count === 0) {
  743. rval = '';
  744. } else {
  745. // read all bytes, optimize to only copy when needed
  746. rval = (this.read === 0) ? this.data : this.data.slice(this.read);
  747. this.clear();
  748. }
  749. return rval;
  750. };
  751. /**
  752. * Gets a binary encoded string of the bytes from this buffer without
  753. * modifying the read pointer.
  754. *
  755. * @param count the number of bytes to get, omit to get all.
  756. *
  757. * @return a string full of binary encoded characters.
  758. */
  759. util$1.ByteStringBuffer.prototype.bytes = function(count) {
  760. return (typeof(count) === 'undefined' ?
  761. this.data.slice(this.read) :
  762. this.data.slice(this.read, this.read + count));
  763. };
  764. /**
  765. * Gets a byte at the given index without modifying the read pointer.
  766. *
  767. * @param i the byte index.
  768. *
  769. * @return the byte.
  770. */
  771. util$1.ByteStringBuffer.prototype.at = function(i) {
  772. return this.data.charCodeAt(this.read + i);
  773. };
  774. /**
  775. * Puts a byte at the given index without modifying the read pointer.
  776. *
  777. * @param i the byte index.
  778. * @param b the byte to put.
  779. *
  780. * @return this buffer.
  781. */
  782. util$1.ByteStringBuffer.prototype.setAt = function(i, b) {
  783. this.data = this.data.substr(0, this.read + i) +
  784. String.fromCharCode(b) +
  785. this.data.substr(this.read + i + 1);
  786. return this;
  787. };
  788. /**
  789. * Gets the last byte without modifying the read pointer.
  790. *
  791. * @return the last byte.
  792. */
  793. util$1.ByteStringBuffer.prototype.last = function() {
  794. return this.data.charCodeAt(this.data.length - 1);
  795. };
  796. /**
  797. * Creates a copy of this buffer.
  798. *
  799. * @return the copy.
  800. */
  801. util$1.ByteStringBuffer.prototype.copy = function() {
  802. var c = util$1.createBuffer(this.data);
  803. c.read = this.read;
  804. return c;
  805. };
  806. /**
  807. * Compacts this buffer.
  808. *
  809. * @return this buffer.
  810. */
  811. util$1.ByteStringBuffer.prototype.compact = function() {
  812. if(this.read > 0) {
  813. this.data = this.data.slice(this.read);
  814. this.read = 0;
  815. }
  816. return this;
  817. };
  818. /**
  819. * Clears this buffer.
  820. *
  821. * @return this buffer.
  822. */
  823. util$1.ByteStringBuffer.prototype.clear = function() {
  824. this.data = '';
  825. this.read = 0;
  826. return this;
  827. };
  828. /**
  829. * Shortens this buffer by triming bytes off of the end of this buffer.
  830. *
  831. * @param count the number of bytes to trim off.
  832. *
  833. * @return this buffer.
  834. */
  835. util$1.ByteStringBuffer.prototype.truncate = function(count) {
  836. var len = Math.max(0, this.length() - count);
  837. this.data = this.data.substr(this.read, len);
  838. this.read = 0;
  839. return this;
  840. };
  841. /**
  842. * Converts this buffer to a hexadecimal string.
  843. *
  844. * @return a hexadecimal string.
  845. */
  846. util$1.ByteStringBuffer.prototype.toHex = function() {
  847. var rval = '';
  848. for(var i = this.read; i < this.data.length; ++i) {
  849. var b = this.data.charCodeAt(i);
  850. if(b < 16) {
  851. rval += '0';
  852. }
  853. rval += b.toString(16);
  854. }
  855. return rval;
  856. };
  857. /**
  858. * Converts this buffer to a UTF-16 string (standard JavaScript string).
  859. *
  860. * @return a UTF-16 string.
  861. */
  862. util$1.ByteStringBuffer.prototype.toString = function() {
  863. return util$1.decodeUtf8(this.bytes());
  864. };
  865. /** End Buffer w/BinaryString backing */
  866. /** Buffer w/UInt8Array backing */
  867. /**
  868. * FIXME: Experimental. Do not use yet.
  869. *
  870. * Constructor for an ArrayBuffer-backed byte buffer.
  871. *
  872. * The buffer may be constructed from a string, an ArrayBuffer, DataView, or a
  873. * TypedArray.
  874. *
  875. * If a string is given, its encoding should be provided as an option,
  876. * otherwise it will default to 'binary'. A 'binary' string is encoded such
  877. * that each character is one byte in length and size.
  878. *
  879. * If an ArrayBuffer, DataView, or TypedArray is given, it will be used
  880. * *directly* without any copying. Note that, if a write to the buffer requires
  881. * more space, the buffer will allocate a new backing ArrayBuffer to
  882. * accommodate. The starting read and write offsets for the buffer may be
  883. * given as options.
  884. *
  885. * @param [b] the initial bytes for this buffer.
  886. * @param options the options to use:
  887. * [readOffset] the starting read offset to use (default: 0).
  888. * [writeOffset] the starting write offset to use (default: the
  889. * length of the first parameter).
  890. * [growSize] the minimum amount, in bytes, to grow the buffer by to
  891. * accommodate writes (default: 1024).
  892. * [encoding] the encoding ('binary', 'utf8', 'utf16', 'hex') for the
  893. * first parameter, if it is a string (default: 'binary').
  894. */
  895. function DataBuffer(b, options) {
  896. // default options
  897. options = options || {};
  898. // pointers for read from/write to buffer
  899. this.read = options.readOffset || 0;
  900. this.growSize = options.growSize || 1024;
  901. var isArrayBuffer = util$1.isArrayBuffer(b);
  902. var isArrayBufferView = util$1.isArrayBufferView(b);
  903. if(isArrayBuffer || isArrayBufferView) {
  904. // use ArrayBuffer directly
  905. if(isArrayBuffer) {
  906. this.data = new DataView(b);
  907. } else {
  908. // TODO: adjust read/write offset based on the type of view
  909. // or specify that this must be done in the options ... that the
  910. // offsets are byte-based
  911. this.data = new DataView(b.buffer, b.byteOffset, b.byteLength);
  912. }
  913. this.write = ('writeOffset' in options ?
  914. options.writeOffset : this.data.byteLength);
  915. return;
  916. }
  917. // initialize to empty array buffer and add any given bytes using putBytes
  918. this.data = new DataView(new ArrayBuffer(0));
  919. this.write = 0;
  920. if(b !== null && b !== undefined) {
  921. this.putBytes(b);
  922. }
  923. if('writeOffset' in options) {
  924. this.write = options.writeOffset;
  925. }
  926. }
  927. util$1.DataBuffer = DataBuffer;
  928. /**
  929. * Gets the number of bytes in this buffer.
  930. *
  931. * @return the number of bytes in this buffer.
  932. */
  933. util$1.DataBuffer.prototype.length = function() {
  934. return this.write - this.read;
  935. };
  936. /**
  937. * Gets whether or not this buffer is empty.
  938. *
  939. * @return true if this buffer is empty, false if not.
  940. */
  941. util$1.DataBuffer.prototype.isEmpty = function() {
  942. return this.length() <= 0;
  943. };
  944. /**
  945. * Ensures this buffer has enough empty space to accommodate the given number
  946. * of bytes. An optional parameter may be given that indicates a minimum
  947. * amount to grow the buffer if necessary. If the parameter is not given,
  948. * the buffer will be grown by some previously-specified default amount
  949. * or heuristic.
  950. *
  951. * @param amount the number of bytes to accommodate.
  952. * @param [growSize] the minimum amount, in bytes, to grow the buffer by if
  953. * necessary.
  954. */
  955. util$1.DataBuffer.prototype.accommodate = function(amount, growSize) {
  956. if(this.length() >= amount) {
  957. return this;
  958. }
  959. growSize = Math.max(growSize || this.growSize, amount);
  960. // grow buffer
  961. var src = new Uint8Array(
  962. this.data.buffer, this.data.byteOffset, this.data.byteLength);
  963. var dst = new Uint8Array(this.length() + growSize);
  964. dst.set(src);
  965. this.data = new DataView(dst.buffer);
  966. return this;
  967. };
  968. /**
  969. * Puts a byte in this buffer.
  970. *
  971. * @param b the byte to put.
  972. *
  973. * @return this buffer.
  974. */
  975. util$1.DataBuffer.prototype.putByte = function(b) {
  976. this.accommodate(1);
  977. this.data.setUint8(this.write++, b);
  978. return this;
  979. };
  980. /**
  981. * Puts a byte in this buffer N times.
  982. *
  983. * @param b the byte to put.
  984. * @param n the number of bytes of value b to put.
  985. *
  986. * @return this buffer.
  987. */
  988. util$1.DataBuffer.prototype.fillWithByte = function(b, n) {
  989. this.accommodate(n);
  990. for(var i = 0; i < n; ++i) {
  991. this.data.setUint8(b);
  992. }
  993. return this;
  994. };
  995. /**
  996. * Puts bytes in this buffer. The bytes may be given as a string, an
  997. * ArrayBuffer, a DataView, or a TypedArray.
  998. *
  999. * @param bytes the bytes to put.
  1000. * @param [encoding] the encoding for the first parameter ('binary', 'utf8',
  1001. * 'utf16', 'hex'), if it is a string (default: 'binary').
  1002. *
  1003. * @return this buffer.
  1004. */
  1005. util$1.DataBuffer.prototype.putBytes = function(bytes, encoding) {
  1006. if(util$1.isArrayBufferView(bytes)) {
  1007. var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
  1008. var len = src.byteLength - src.byteOffset;
  1009. this.accommodate(len);
  1010. var dst = new Uint8Array(this.data.buffer, this.write);
  1011. dst.set(src);
  1012. this.write += len;
  1013. return this;
  1014. }
  1015. if(util$1.isArrayBuffer(bytes)) {
  1016. var src = new Uint8Array(bytes);
  1017. this.accommodate(src.byteLength);
  1018. var dst = new Uint8Array(this.data.buffer);
  1019. dst.set(src, this.write);
  1020. this.write += src.byteLength;
  1021. return this;
  1022. }
  1023. // bytes is a util.DataBuffer or equivalent
  1024. if(bytes instanceof util$1.DataBuffer ||
  1025. (typeof bytes === 'object' &&
  1026. typeof bytes.read === 'number' && typeof bytes.write === 'number' &&
  1027. util$1.isArrayBufferView(bytes.data))) {
  1028. var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length());
  1029. this.accommodate(src.byteLength);
  1030. var dst = new Uint8Array(bytes.data.byteLength, this.write);
  1031. dst.set(src);
  1032. this.write += src.byteLength;
  1033. return this;
  1034. }
  1035. if(bytes instanceof util$1.ByteStringBuffer) {
  1036. // copy binary string and process as the same as a string parameter below
  1037. bytes = bytes.data;
  1038. encoding = 'binary';
  1039. }
  1040. // string conversion
  1041. encoding = encoding || 'binary';
  1042. if(typeof bytes === 'string') {
  1043. var view;
  1044. // decode from string
  1045. if(encoding === 'hex') {
  1046. this.accommodate(Math.ceil(bytes.length / 2));
  1047. view = new Uint8Array(this.data.buffer, this.write);
  1048. this.write += util$1.binary.hex.decode(bytes, view, this.write);
  1049. return this;
  1050. }
  1051. if(encoding === 'base64') {
  1052. this.accommodate(Math.ceil(bytes.length / 4) * 3);
  1053. view = new Uint8Array(this.data.buffer, this.write);
  1054. this.write += util$1.binary.base64.decode(bytes, view, this.write);
  1055. return this;
  1056. }
  1057. // encode text as UTF-8 bytes
  1058. if(encoding === 'utf8') {
  1059. // encode as UTF-8 then decode string as raw binary
  1060. bytes = util$1.encodeUtf8(bytes);
  1061. encoding = 'binary';
  1062. }
  1063. // decode string as raw binary
  1064. if(encoding === 'binary' || encoding === 'raw') {
  1065. // one byte per character
  1066. this.accommodate(bytes.length);
  1067. view = new Uint8Array(this.data.buffer, this.write);
  1068. this.write += util$1.binary.raw.decode(view);
  1069. return this;
  1070. }
  1071. // encode text as UTF-16 bytes
  1072. if(encoding === 'utf16') {
  1073. // two bytes per character
  1074. this.accommodate(bytes.length * 2);
  1075. view = new Uint16Array(this.data.buffer, this.write);
  1076. this.write += util$1.text.utf16.encode(view);
  1077. return this;
  1078. }
  1079. throw new Error('Invalid encoding: ' + encoding);
  1080. }
  1081. throw Error('Invalid parameter: ' + bytes);
  1082. };
  1083. /**
  1084. * Puts the given buffer into this buffer.
  1085. *
  1086. * @param buffer the buffer to put into this one.
  1087. *
  1088. * @return this buffer.
  1089. */
  1090. util$1.DataBuffer.prototype.putBuffer = function(buffer) {
  1091. this.putBytes(buffer);
  1092. buffer.clear();
  1093. return this;
  1094. };
  1095. /**
  1096. * Puts a string into this buffer.
  1097. *
  1098. * @param str the string to put.
  1099. * @param [encoding] the encoding for the string (default: 'utf16').
  1100. *
  1101. * @return this buffer.
  1102. */
  1103. util$1.DataBuffer.prototype.putString = function(str) {
  1104. return this.putBytes(str, 'utf16');
  1105. };
  1106. /**
  1107. * Puts a 16-bit integer in this buffer in big-endian order.
  1108. *
  1109. * @param i the 16-bit integer.
  1110. *
  1111. * @return this buffer.
  1112. */
  1113. util$1.DataBuffer.prototype.putInt16 = function(i) {
  1114. this.accommodate(2);
  1115. this.data.setInt16(this.write, i);
  1116. this.write += 2;
  1117. return this;
  1118. };
  1119. /**
  1120. * Puts a 24-bit integer in this buffer in big-endian order.
  1121. *
  1122. * @param i the 24-bit integer.
  1123. *
  1124. * @return this buffer.
  1125. */
  1126. util$1.DataBuffer.prototype.putInt24 = function(i) {
  1127. this.accommodate(3);
  1128. this.data.setInt16(this.write, i >> 8 & 0xFFFF);
  1129. this.data.setInt8(this.write, i >> 16 & 0xFF);
  1130. this.write += 3;
  1131. return this;
  1132. };
  1133. /**
  1134. * Puts a 32-bit integer in this buffer in big-endian order.
  1135. *
  1136. * @param i the 32-bit integer.
  1137. *
  1138. * @return this buffer.
  1139. */
  1140. util$1.DataBuffer.prototype.putInt32 = function(i) {
  1141. this.accommodate(4);
  1142. this.data.setInt32(this.write, i);
  1143. this.write += 4;
  1144. return this;
  1145. };
  1146. /**
  1147. * Puts a 16-bit integer in this buffer in little-endian order.
  1148. *
  1149. * @param i the 16-bit integer.
  1150. *
  1151. * @return this buffer.
  1152. */
  1153. util$1.DataBuffer.prototype.putInt16Le = function(i) {
  1154. this.accommodate(2);
  1155. this.data.setInt16(this.write, i, true);
  1156. this.write += 2;
  1157. return this;
  1158. };
  1159. /**
  1160. * Puts a 24-bit integer in this buffer in little-endian order.
  1161. *
  1162. * @param i the 24-bit integer.
  1163. *
  1164. * @return this buffer.
  1165. */
  1166. util$1.DataBuffer.prototype.putInt24Le = function(i) {
  1167. this.accommodate(3);
  1168. this.data.setInt8(this.write, i >> 16 & 0xFF);
  1169. this.data.setInt16(this.write, i >> 8 & 0xFFFF, true);
  1170. this.write += 3;
  1171. return this;
  1172. };
  1173. /**
  1174. * Puts a 32-bit integer in this buffer in little-endian order.
  1175. *
  1176. * @param i the 32-bit integer.
  1177. *
  1178. * @return this buffer.
  1179. */
  1180. util$1.DataBuffer.prototype.putInt32Le = function(i) {
  1181. this.accommodate(4);
  1182. this.data.setInt32(this.write, i, true);
  1183. this.write += 4;
  1184. return this;
  1185. };
  1186. /**
  1187. * Puts an n-bit integer in this buffer in big-endian order.
  1188. *
  1189. * @param i the n-bit integer.
  1190. * @param n the number of bits in the integer (8, 16, 24, or 32).
  1191. *
  1192. * @return this buffer.
  1193. */
  1194. util$1.DataBuffer.prototype.putInt = function(i, n) {
  1195. _checkBitsParam(n);
  1196. this.accommodate(n / 8);
  1197. do {
  1198. n -= 8;
  1199. this.data.setInt8(this.write++, (i >> n) & 0xFF);
  1200. } while(n > 0);
  1201. return this;
  1202. };
  1203. /**
  1204. * Puts a signed n-bit integer in this buffer in big-endian order. Two's
  1205. * complement representation is used.
  1206. *
  1207. * @param i the n-bit integer.
  1208. * @param n the number of bits in the integer.
  1209. *
  1210. * @return this buffer.
  1211. */
  1212. util$1.DataBuffer.prototype.putSignedInt = function(i, n) {
  1213. _checkBitsParam(n);
  1214. this.accommodate(n / 8);
  1215. if(i < 0) {
  1216. i += 2 << (n - 1);
  1217. }
  1218. return this.putInt(i, n);
  1219. };
  1220. /**
  1221. * Gets a byte from this buffer and advances the read pointer by 1.
  1222. *
  1223. * @return the byte.
  1224. */
  1225. util$1.DataBuffer.prototype.getByte = function() {
  1226. return this.data.getInt8(this.read++);
  1227. };
  1228. /**
  1229. * Gets a uint16 from this buffer in big-endian order and advances the read
  1230. * pointer by 2.
  1231. *
  1232. * @return the uint16.
  1233. */
  1234. util$1.DataBuffer.prototype.getInt16 = function() {
  1235. var rval = this.data.getInt16(this.read);
  1236. this.read += 2;
  1237. return rval;
  1238. };
  1239. /**
  1240. * Gets a uint24 from this buffer in big-endian order and advances the read
  1241. * pointer by 3.
  1242. *
  1243. * @return the uint24.
  1244. */
  1245. util$1.DataBuffer.prototype.getInt24 = function() {
  1246. var rval = (
  1247. this.data.getInt16(this.read) << 8 ^
  1248. this.data.getInt8(this.read + 2));
  1249. this.read += 3;
  1250. return rval;
  1251. };
  1252. /**
  1253. * Gets a uint32 from this buffer in big-endian order and advances the read
  1254. * pointer by 4.
  1255. *
  1256. * @return the word.
  1257. */
  1258. util$1.DataBuffer.prototype.getInt32 = function() {
  1259. var rval = this.data.getInt32(this.read);
  1260. this.read += 4;
  1261. return rval;
  1262. };
  1263. /**
  1264. * Gets a uint16 from this buffer in little-endian order and advances the read
  1265. * pointer by 2.
  1266. *
  1267. * @return the uint16.
  1268. */
  1269. util$1.DataBuffer.prototype.getInt16Le = function() {
  1270. var rval = this.data.getInt16(this.read, true);
  1271. this.read += 2;
  1272. return rval;
  1273. };
  1274. /**
  1275. * Gets a uint24 from this buffer in little-endian order and advances the read
  1276. * pointer by 3.
  1277. *
  1278. * @return the uint24.
  1279. */
  1280. util$1.DataBuffer.prototype.getInt24Le = function() {
  1281. var rval = (
  1282. this.data.getInt8(this.read) ^
  1283. this.data.getInt16(this.read + 1, true) << 8);
  1284. this.read += 3;
  1285. return rval;
  1286. };
  1287. /**
  1288. * Gets a uint32 from this buffer in little-endian order and advances the read
  1289. * pointer by 4.
  1290. *
  1291. * @return the word.
  1292. */
  1293. util$1.DataBuffer.prototype.getInt32Le = function() {
  1294. var rval = this.data.getInt32(this.read, true);
  1295. this.read += 4;
  1296. return rval;
  1297. };
  1298. /**
  1299. * Gets an n-bit integer from this buffer in big-endian order and advances the
  1300. * read pointer by n/8.
  1301. *
  1302. * @param n the number of bits in the integer (8, 16, 24, or 32).
  1303. *
  1304. * @return the integer.
  1305. */
  1306. util$1.DataBuffer.prototype.getInt = function(n) {
  1307. _checkBitsParam(n);
  1308. var rval = 0;
  1309. do {
  1310. // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits.
  1311. rval = (rval << 8) + this.data.getInt8(this.read++);
  1312. n -= 8;
  1313. } while(n > 0);
  1314. return rval;
  1315. };
  1316. /**
  1317. * Gets a signed n-bit integer from this buffer in big-endian order, using
  1318. * two's complement, and advances the read pointer by n/8.
  1319. *
  1320. * @param n the number of bits in the integer (8, 16, 24, or 32).
  1321. *
  1322. * @return the integer.
  1323. */
  1324. util$1.DataBuffer.prototype.getSignedInt = function(n) {
  1325. // getInt checks n
  1326. var x = this.getInt(n);
  1327. var max = 2 << (n - 2);
  1328. if(x >= max) {
  1329. x -= max << 1;
  1330. }
  1331. return x;
  1332. };
  1333. /**
  1334. * Reads bytes out as a binary encoded string and clears them from the
  1335. * buffer.
  1336. *
  1337. * @param count the number of bytes to read, undefined or null for all.
  1338. *
  1339. * @return a binary encoded string of bytes.
  1340. */
  1341. util$1.DataBuffer.prototype.getBytes = function(count) {
  1342. // TODO: deprecate this method, it is poorly named and
  1343. // this.toString('binary') replaces it
  1344. // add a toTypedArray()/toArrayBuffer() function
  1345. var rval;
  1346. if(count) {
  1347. // read count bytes
  1348. count = Math.min(this.length(), count);
  1349. rval = this.data.slice(this.read, this.read + count);
  1350. this.read += count;
  1351. } else if(count === 0) {
  1352. rval = '';
  1353. } else {
  1354. // read all bytes, optimize to only copy when needed
  1355. rval = (this.read === 0) ? this.data : this.data.slice(this.read);
  1356. this.clear();
  1357. }
  1358. return rval;
  1359. };
  1360. /**
  1361. * Gets a binary encoded string of the bytes from this buffer without
  1362. * modifying the read pointer.
  1363. *
  1364. * @param count the number of bytes to get, omit to get all.
  1365. *
  1366. * @return a string full of binary encoded characters.
  1367. */
  1368. util$1.DataBuffer.prototype.bytes = function(count) {
  1369. // TODO: deprecate this method, it is poorly named, add "getString()"
  1370. return (typeof(count) === 'undefined' ?
  1371. this.data.slice(this.read) :
  1372. this.data.slice(this.read, this.read + count));
  1373. };
  1374. /**
  1375. * Gets a byte at the given index without modifying the read pointer.
  1376. *
  1377. * @param i the byte index.
  1378. *
  1379. * @return the byte.
  1380. */
  1381. util$1.DataBuffer.prototype.at = function(i) {
  1382. return this.data.getUint8(this.read + i);
  1383. };
  1384. /**
  1385. * Puts a byte at the given index without modifying the read pointer.
  1386. *
  1387. * @param i the byte index.
  1388. * @param b the byte to put.
  1389. *
  1390. * @return this buffer.
  1391. */
  1392. util$1.DataBuffer.prototype.setAt = function(i, b) {
  1393. this.data.setUint8(i, b);
  1394. return this;
  1395. };
  1396. /**
  1397. * Gets the last byte without modifying the read pointer.
  1398. *
  1399. * @return the last byte.
  1400. */
  1401. util$1.DataBuffer.prototype.last = function() {
  1402. return this.data.getUint8(this.write - 1);
  1403. };
  1404. /**
  1405. * Creates a copy of this buffer.
  1406. *
  1407. * @return the copy.
  1408. */
  1409. util$1.DataBuffer.prototype.copy = function() {
  1410. return new util$1.DataBuffer(this);
  1411. };
  1412. /**
  1413. * Compacts this buffer.
  1414. *
  1415. * @return this buffer.
  1416. */
  1417. util$1.DataBuffer.prototype.compact = function() {
  1418. if(this.read > 0) {
  1419. var src = new Uint8Array(this.data.buffer, this.read);
  1420. var dst = new Uint8Array(src.byteLength);
  1421. dst.set(src);
  1422. this.data = new DataView(dst);
  1423. this.write -= this.read;
  1424. this.read = 0;
  1425. }
  1426. return this;
  1427. };
  1428. /**
  1429. * Clears this buffer.
  1430. *
  1431. * @return this buffer.
  1432. */
  1433. util$1.DataBuffer.prototype.clear = function() {
  1434. this.data = new DataView(new ArrayBuffer(0));
  1435. this.read = this.write = 0;
  1436. return this;
  1437. };
  1438. /**
  1439. * Shortens this buffer by triming bytes off of the end of this buffer.
  1440. *
  1441. * @param count the number of bytes to trim off.
  1442. *
  1443. * @return this buffer.
  1444. */
  1445. util$1.DataBuffer.prototype.truncate = function(count) {
  1446. this.write = Math.max(0, this.length() - count);
  1447. this.read = Math.min(this.read, this.write);
  1448. return this;
  1449. };
  1450. /**
  1451. * Converts this buffer to a hexadecimal string.
  1452. *
  1453. * @return a hexadecimal string.
  1454. */
  1455. util$1.DataBuffer.prototype.toHex = function() {
  1456. var rval = '';
  1457. for(var i = this.read; i < this.data.byteLength; ++i) {
  1458. var b = this.data.getUint8(i);
  1459. if(b < 16) {
  1460. rval += '0';
  1461. }
  1462. rval += b.toString(16);
  1463. }
  1464. return rval;
  1465. };
  1466. /**
  1467. * Converts this buffer to a string, using the given encoding. If no
  1468. * encoding is given, 'utf8' (UTF-8) is used.
  1469. *
  1470. * @param [encoding] the encoding to use: 'binary', 'utf8', 'utf16', 'hex',
  1471. * 'base64' (default: 'utf8').
  1472. *
  1473. * @return a string representation of the bytes in this buffer.
  1474. */
  1475. util$1.DataBuffer.prototype.toString = function(encoding) {
  1476. var view = new Uint8Array(this.data, this.read, this.length());
  1477. encoding = encoding || 'utf8';
  1478. // encode to string
  1479. if(encoding === 'binary' || encoding === 'raw') {
  1480. return util$1.binary.raw.encode(view);
  1481. }
  1482. if(encoding === 'hex') {
  1483. return util$1.binary.hex.encode(view);
  1484. }
  1485. if(encoding === 'base64') {
  1486. return util$1.binary.base64.encode(view);
  1487. }
  1488. // decode to text
  1489. if(encoding === 'utf8') {
  1490. return util$1.text.utf8.decode(view);
  1491. }
  1492. if(encoding === 'utf16') {
  1493. return util$1.text.utf16.decode(view);
  1494. }
  1495. throw new Error('Invalid encoding: ' + encoding);
  1496. };
  1497. /** End Buffer w/UInt8Array backing */
  1498. /**
  1499. * Creates a buffer that stores bytes. A value may be given to populate the
  1500. * buffer with data. This value can either be string of encoded bytes or a
  1501. * regular string of characters. When passing a string of binary encoded
  1502. * bytes, the encoding `raw` should be given. This is also the default. When
  1503. * passing a string of characters, the encoding `utf8` should be given.
  1504. *
  1505. * @param [input] a string with encoded bytes to store in the buffer.
  1506. * @param [encoding] (default: 'raw', other: 'utf8').
  1507. */
  1508. util$1.createBuffer = function(input, encoding) {
  1509. // TODO: deprecate, use new ByteBuffer() instead
  1510. encoding = encoding || 'raw';
  1511. if(input !== undefined && encoding === 'utf8') {
  1512. input = util$1.encodeUtf8(input);
  1513. }
  1514. return new util$1.ByteBuffer(input);
  1515. };
  1516. /**
  1517. * Fills a string with a particular value. If you want the string to be a byte
  1518. * string, pass in String.fromCharCode(theByte).
  1519. *
  1520. * @param c the character to fill the string with, use String.fromCharCode
  1521. * to fill the string with a byte value.
  1522. * @param n the number of characters of value c to fill with.
  1523. *
  1524. * @return the filled string.
  1525. */
  1526. util$1.fillString = function(c, n) {
  1527. var s = '';
  1528. while(n > 0) {
  1529. if(n & 1) {
  1530. s += c;
  1531. }
  1532. n >>>= 1;
  1533. if(n > 0) {
  1534. c += c;
  1535. }
  1536. }
  1537. return s;
  1538. };
  1539. /**
  1540. * Performs a per byte XOR between two byte strings and returns the result as a
  1541. * string of bytes.
  1542. *
  1543. * @param s1 first string of bytes.
  1544. * @param s2 second string of bytes.
  1545. * @param n the number of bytes to XOR.
  1546. *
  1547. * @return the XOR'd result.
  1548. */
  1549. util$1.xorBytes = function(s1, s2, n) {
  1550. var s3 = '';
  1551. var b = '';
  1552. var t = '';
  1553. var i = 0;
  1554. var c = 0;
  1555. for(; n > 0; --n, ++i) {
  1556. b = s1.charCodeAt(i) ^ s2.charCodeAt(i);
  1557. if(c >= 10) {
  1558. s3 += t;
  1559. t = '';
  1560. c = 0;
  1561. }
  1562. t += String.fromCharCode(b);
  1563. ++c;
  1564. }
  1565. s3 += t;
  1566. return s3;
  1567. };
  1568. /**
  1569. * Converts a hex string into a 'binary' encoded string of bytes.
  1570. *
  1571. * @param hex the hexadecimal string to convert.
  1572. *
  1573. * @return the binary-encoded string of bytes.
  1574. */
  1575. util$1.hexToBytes = function(hex) {
  1576. // TODO: deprecate: "Deprecated. Use util.binary.hex.decode instead."
  1577. var rval = '';
  1578. var i = 0;
  1579. if(hex.length & 1 == 1) {
  1580. // odd number of characters, convert first character alone
  1581. i = 1;
  1582. rval += String.fromCharCode(parseInt(hex[0], 16));
  1583. }
  1584. // convert 2 characters (1 byte) at a time
  1585. for(; i < hex.length; i += 2) {
  1586. rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
  1587. }
  1588. return rval;
  1589. };
  1590. /**
  1591. * Converts a 'binary' encoded string of bytes to hex.
  1592. *
  1593. * @param bytes the byte string to convert.
  1594. *
  1595. * @return the string of hexadecimal characters.
  1596. */
  1597. util$1.bytesToHex = function(bytes) {
  1598. // TODO: deprecate: "Deprecated. Use util.binary.hex.encode instead."
  1599. return util$1.createBuffer(bytes).toHex();
  1600. };
  1601. /**
  1602. * Converts an 32-bit integer to 4-big-endian byte string.
  1603. *
  1604. * @param i the integer.
  1605. *
  1606. * @return the byte string.
  1607. */
  1608. util$1.int32ToBytes = function(i) {
  1609. return (
  1610. String.fromCharCode(i >> 24 & 0xFF) +
  1611. String.fromCharCode(i >> 16 & 0xFF) +
  1612. String.fromCharCode(i >> 8 & 0xFF) +
  1613. String.fromCharCode(i & 0xFF));
  1614. };
  1615. // base64 characters, reverse mapping
  1616. var _base64 =
  1617. 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  1618. var _base64Idx = [
  1619. /*43 -43 = 0*/
  1620. /*'+', 1, 2, 3,'/' */
  1621. 62, -1, -1, -1, 63,
  1622. /*'0','1','2','3','4','5','6','7','8','9' */
  1623. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
  1624. /*15, 16, 17,'=', 19, 20, 21 */
  1625. -1, -1, -1, 64, -1, -1, -1,
  1626. /*65 - 43 = 22*/
  1627. /*'A','B','C','D','E','F','G','H','I','J','K','L','M', */
  1628. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
  1629. /*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */
  1630. 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
  1631. /*91 - 43 = 48 */
  1632. /*48, 49, 50, 51, 52, 53 */
  1633. -1, -1, -1, -1, -1, -1,
  1634. /*97 - 43 = 54*/
  1635. /*'a','b','c','d','e','f','g','h','i','j','k','l','m' */
  1636. 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
  1637. /*'n','o','p','q','r','s','t','u','v','w','x','y','z' */
  1638. 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
  1639. ];
  1640. // base58 characters (Bitcoin alphabet)
  1641. var _base58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
  1642. /**
  1643. * Base64 encodes a 'binary' encoded string of bytes.
  1644. *
  1645. * @param input the binary encoded string of bytes to base64-encode.
  1646. * @param maxline the maximum number of encoded characters per line to use,
  1647. * defaults to none.
  1648. *
  1649. * @return the base64-encoded output.
  1650. */
  1651. util$1.encode64 = function(input, maxline) {
  1652. // TODO: deprecate: "Deprecated. Use util.binary.base64.encode instead."
  1653. var line = '';
  1654. var output = '';
  1655. var chr1, chr2, chr3;
  1656. var i = 0;
  1657. while(i < input.length) {
  1658. chr1 = input.charCodeAt(i++);
  1659. chr2 = input.charCodeAt(i++);
  1660. chr3 = input.charCodeAt(i++);
  1661. // encode 4 character group
  1662. line += _base64.charAt(chr1 >> 2);
  1663. line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4));
  1664. if(isNaN(chr2)) {
  1665. line += '==';
  1666. } else {
  1667. line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6));
  1668. line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63);
  1669. }
  1670. if(maxline && line.length > maxline) {
  1671. output += line.substr(0, maxline) + '\r\n';
  1672. line = line.substr(maxline);
  1673. }
  1674. }
  1675. output += line;
  1676. return output;
  1677. };
  1678. /**
  1679. * Base64 decodes a string into a 'binary' encoded string of bytes.
  1680. *
  1681. * @param input the base64-encoded input.
  1682. *
  1683. * @return the binary encoded string.
  1684. */
  1685. util$1.decode64 = function(input) {
  1686. // TODO: deprecate: "Deprecated. Use util.binary.base64.decode instead."
  1687. // remove all non-base64 characters
  1688. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
  1689. var output = '';
  1690. var enc1, enc2, enc3, enc4;
  1691. var i = 0;
  1692. while(i < input.length) {
  1693. enc1 = _base64Idx[input.charCodeAt(i++) - 43];
  1694. enc2 = _base64Idx[input.charCodeAt(i++) - 43];
  1695. enc3 = _base64Idx[input.charCodeAt(i++) - 43];
  1696. enc4 = _base64Idx[input.charCodeAt(i++) - 43];
  1697. output += String.fromCharCode((enc1 << 2) | (enc2 >> 4));
  1698. if(enc3 !== 64) {
  1699. // decoded at least 2 bytes
  1700. output += String.fromCharCode(((enc2 & 15) << 4) | (enc3 >> 2));
  1701. if(enc4 !== 64) {
  1702. // decoded 3 bytes
  1703. output += String.fromCharCode(((enc3 & 3) << 6) | enc4);
  1704. }
  1705. }
  1706. }
  1707. return output;
  1708. };
  1709. /**
  1710. * Encodes the given string of characters (a standard JavaScript
  1711. * string) as a binary encoded string where the bytes represent
  1712. * a UTF-8 encoded string of characters. Non-ASCII characters will be
  1713. * encoded as multiple bytes according to UTF-8.
  1714. *
  1715. * @param str a standard string of characters to encode.
  1716. *
  1717. * @return the binary encoded string.
  1718. */
  1719. util$1.encodeUtf8 = function(str) {
  1720. return unescape(encodeURIComponent(str));
  1721. };
  1722. /**
  1723. * Decodes a binary encoded string that contains bytes that
  1724. * represent a UTF-8 encoded string of characters -- into a
  1725. * string of characters (a standard JavaScript string).
  1726. *
  1727. * @param str the binary encoded string to decode.
  1728. *
  1729. * @return the resulting standard string of characters.
  1730. */
  1731. util$1.decodeUtf8 = function(str) {
  1732. return decodeURIComponent(escape(str));
  1733. };
  1734. // binary encoding/decoding tools
  1735. // FIXME: Experimental. Do not use yet.
  1736. util$1.binary = {
  1737. raw: {},
  1738. hex: {},
  1739. base64: {},
  1740. base58: {},
  1741. baseN : {
  1742. encode: baseN.encode,
  1743. decode: baseN.decode
  1744. }
  1745. };
  1746. /**
  1747. * Encodes a Uint8Array as a binary-encoded string. This encoding uses
  1748. * a value between 0 and 255 for each character.
  1749. *
  1750. * @param bytes the Uint8Array to encode.
  1751. *
  1752. * @return the binary-encoded string.
  1753. */
  1754. util$1.binary.raw.encode = function(bytes) {
  1755. return String.fromCharCode.apply(null, bytes);
  1756. };
  1757. /**
  1758. * Decodes a binary-encoded string to a Uint8Array. This encoding uses
  1759. * a value between 0 and 255 for each character.
  1760. *
  1761. * @param str the binary-encoded string to decode.
  1762. * @param [output] an optional Uint8Array to write the output to; if it
  1763. * is too small, an exception will be thrown.
  1764. * @param [offset] the start offset for writing to the output (default: 0).
  1765. *
  1766. * @return the Uint8Array or the number of bytes written if output was given.
  1767. */
  1768. util$1.binary.raw.decode = function(str, output, offset) {
  1769. var out = output;
  1770. if(!out) {
  1771. out = new Uint8Array(str.length);
  1772. }
  1773. offset = offset || 0;
  1774. var j = offset;
  1775. for(var i = 0; i < str.length; ++i) {
  1776. out[j++] = str.charCodeAt(i);
  1777. }
  1778. return output ? (j - offset) : out;
  1779. };
  1780. /**
  1781. * Encodes a 'binary' string, ArrayBuffer, DataView, TypedArray, or
  1782. * ByteBuffer as a string of hexadecimal characters.
  1783. *
  1784. * @param bytes the bytes to convert.
  1785. *
  1786. * @return the string of hexadecimal characters.
  1787. */
  1788. util$1.binary.hex.encode = util$1.bytesToHex;
  1789. /**
  1790. * Decodes a hex-encoded string to a Uint8Array.
  1791. *
  1792. * @param hex the hexadecimal string to convert.
  1793. * @param [output] an optional Uint8Array to write the output to; if it
  1794. * is too small, an exception will be thrown.
  1795. * @param [offset] the start offset for writing to the output (default: 0).
  1796. *
  1797. * @return the Uint8Array or the number of bytes written if output was given.
  1798. */
  1799. util$1.binary.hex.decode = function(hex, output, offset) {
  1800. var out = output;
  1801. if(!out) {
  1802. out = new Uint8Array(Math.ceil(hex.length / 2));
  1803. }
  1804. offset = offset || 0;
  1805. var i = 0, j = offset;
  1806. if(hex.length & 1) {
  1807. // odd number of characters, convert first character alone
  1808. i = 1;
  1809. out[j++] = parseInt(hex[0], 16);
  1810. }
  1811. // convert 2 characters (1 byte) at a time
  1812. for(; i < hex.length; i += 2) {
  1813. out[j++] = parseInt(hex.substr(i, 2), 16);
  1814. }
  1815. return output ? (j - offset) : out;
  1816. };
  1817. /**
  1818. * Base64-encodes a Uint8Array.
  1819. *
  1820. * @param input the Uint8Array to encode.
  1821. * @param maxline the maximum number of encoded characters per line to use,
  1822. * defaults to none.
  1823. *
  1824. * @return the base64-encoded output string.
  1825. */
  1826. util$1.binary.base64.encode = function(input, maxline) {
  1827. var line = '';
  1828. var output = '';
  1829. var chr1, chr2, chr3;
  1830. var i = 0;
  1831. while(i < input.byteLength) {
  1832. chr1 = input[i++];
  1833. chr2 = input[i++];
  1834. chr3 = input[i++];
  1835. // encode 4 character group
  1836. line += _base64.charAt(chr1 >> 2);
  1837. line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4));
  1838. if(isNaN(chr2)) {
  1839. line += '==';
  1840. } else {
  1841. line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6));
  1842. line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63);
  1843. }
  1844. if(maxline && line.length > maxline) {
  1845. output += line.substr(0, maxline) + '\r\n';
  1846. line = line.substr(maxline);
  1847. }
  1848. }
  1849. output += line;
  1850. return output;
  1851. };
  1852. /**
  1853. * Decodes a base64-encoded string to a Uint8Array.
  1854. *
  1855. * @param input the base64-encoded input string.
  1856. * @param [output] an optional Uint8Array to write the output to; if it
  1857. * is too small, an exception will be thrown.
  1858. * @param [offset] the start offset for writing to the output (default: 0).
  1859. *
  1860. * @return the Uint8Array or the number of bytes written if output was given.
  1861. */
  1862. util$1.binary.base64.decode = function(input, output, offset) {
  1863. var out = output;
  1864. if(!out) {
  1865. out = new Uint8Array(Math.ceil(input.length / 4) * 3);
  1866. }
  1867. // remove all non-base64 characters
  1868. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
  1869. offset = offset || 0;
  1870. var enc1, enc2, enc3, enc4;
  1871. var i = 0, j = offset;
  1872. while(i < input.length) {
  1873. enc1 = _base64Idx[input.charCodeAt(i++) - 43];
  1874. enc2 = _base64Idx[input.charCodeAt(i++) - 43];
  1875. enc3 = _base64Idx[input.charCodeAt(i++) - 43];
  1876. enc4 = _base64Idx[input.charCodeAt(i++) - 43];
  1877. out[j++] = (enc1 << 2) | (enc2 >> 4);
  1878. if(enc3 !== 64) {
  1879. // decoded at least 2 bytes
  1880. out[j++] = ((enc2 & 15) << 4) | (enc3 >> 2);
  1881. if(enc4 !== 64) {
  1882. // decoded 3 bytes
  1883. out[j++] = ((enc3 & 3) << 6) | enc4;
  1884. }
  1885. }
  1886. }
  1887. // make sure result is the exact decoded length
  1888. return output ? (j - offset) : out.subarray(0, j);
  1889. };
  1890. // add support for base58 encoding/decoding with Bitcoin alphabet
  1891. util$1.binary.base58.encode = function(input, maxline) {
  1892. return util$1.binary.baseN.encode(input, _base58, maxline);
  1893. };
  1894. util$1.binary.base58.decode = function(input, maxline) {
  1895. return util$1.binary.baseN.decode(input, _base58, maxline);
  1896. };
  1897. // text encoding/decoding tools
  1898. // FIXME: Experimental. Do not use yet.
  1899. util$1.text = {
  1900. utf8: {},
  1901. utf16: {}
  1902. };
  1903. /**
  1904. * Encodes the given string as UTF-8 in a Uint8Array.
  1905. *
  1906. * @param str the string to encode.
  1907. * @param [output] an optional Uint8Array to write the output to; if it
  1908. * is too small, an exception will be thrown.
  1909. * @param [offset] the start offset for writing to the output (default: 0).
  1910. *
  1911. * @return the Uint8Array or the number of bytes written if output was given.
  1912. */
  1913. util$1.text.utf8.encode = function(str, output, offset) {
  1914. str = util$1.encodeUtf8(str);
  1915. var out = output;
  1916. if(!out) {
  1917. out = new Uint8Array(str.length);
  1918. }
  1919. offset = offset || 0;
  1920. var j = offset;
  1921. for(var i = 0; i < str.length; ++i) {
  1922. out[j++] = str.charCodeAt(i);
  1923. }
  1924. return output ? (j - offset) : out;
  1925. };
  1926. /**
  1927. * Decodes the UTF-8 contents from a Uint8Array.
  1928. *
  1929. * @param bytes the Uint8Array to decode.
  1930. *
  1931. * @return the resulting string.
  1932. */
  1933. util$1.text.utf8.decode = function(bytes) {
  1934. return util$1.decodeUtf8(String.fromCharCode.apply(null, bytes));
  1935. };
  1936. /**
  1937. * Encodes the given string as UTF-16 in a Uint8Array.
  1938. *
  1939. * @param str the string to encode.
  1940. * @param [output] an optional Uint8Array to write the output to; if it
  1941. * is too small, an exception will be thrown.
  1942. * @param [offset] the start offset for writing to the output (default: 0).
  1943. *
  1944. * @return the Uint8Array or the number of bytes written if output was given.
  1945. */
  1946. util$1.text.utf16.encode = function(str, output, offset) {
  1947. var out = output;
  1948. if(!out) {
  1949. out = new Uint8Array(str.length * 2);
  1950. }
  1951. var view = new Uint16Array(out.buffer);
  1952. offset = offset || 0;
  1953. var j = offset;
  1954. var k = offset;
  1955. for(var i = 0; i < str.length; ++i) {
  1956. view[k++] = str.charCodeAt(i);
  1957. j += 2;
  1958. }
  1959. return output ? (j - offset) : out;
  1960. };
  1961. /**
  1962. * Decodes the UTF-16 contents from a Uint8Array.
  1963. *
  1964. * @param bytes the Uint8Array to decode.
  1965. *
  1966. * @return the resulting string.
  1967. */
  1968. util$1.text.utf16.decode = function(bytes) {
  1969. return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer));
  1970. };
  1971. /**
  1972. * Deflates the given data using a flash interface.
  1973. *
  1974. * @param api the flash interface.
  1975. * @param bytes the data.
  1976. * @param raw true to return only raw deflate data, false to include zlib
  1977. * header and trailer.
  1978. *
  1979. * @return the deflated data as a string.
  1980. */
  1981. util$1.deflate = function(api, bytes, raw) {
  1982. bytes = util$1.decode64(api.deflate(util$1.encode64(bytes)).rval);
  1983. // strip zlib header and trailer if necessary
  1984. if(raw) {
  1985. // zlib header is 2 bytes (CMF,FLG) where FLG indicates that
  1986. // there is a 4-byte DICT (alder-32) block before the data if
  1987. // its 5th bit is set
  1988. var start = 2;
  1989. var flg = bytes.charCodeAt(1);
  1990. if(flg & 0x20) {
  1991. start = 6;
  1992. }
  1993. // zlib trailer is 4 bytes of adler-32
  1994. bytes = bytes.substring(start, bytes.length - 4);
  1995. }
  1996. return bytes;
  1997. };
  1998. /**
  1999. * Inflates the given data using a flash interface.
  2000. *
  2001. * @param api the flash interface.
  2002. * @param bytes the data.
  2003. * @param raw true if the incoming data has no zlib header or trailer and is
  2004. * raw DEFLATE data.
  2005. *
  2006. * @return the inflated data as a string, null on error.
  2007. */
  2008. util$1.inflate = function(api, bytes, raw) {
  2009. // TODO: add zlib header and trailer if necessary/possible
  2010. var rval = api.inflate(util$1.encode64(bytes)).rval;
  2011. return (rval === null) ? null : util$1.decode64(rval);
  2012. };
  2013. /**
  2014. * Sets a storage object.
  2015. *
  2016. * @param api the storage interface.
  2017. * @param id the storage ID to use.
  2018. * @param obj the storage object, null to remove.
  2019. */
  2020. var _setStorageObject = function(api, id, obj) {
  2021. if(!api) {
  2022. throw new Error('WebStorage not available.');
  2023. }
  2024. var rval;
  2025. if(obj === null) {
  2026. rval = api.removeItem(id);
  2027. } else {
  2028. // json-encode and base64-encode object
  2029. obj = util$1.encode64(JSON.stringify(obj));
  2030. rval = api.setItem(id, obj);
  2031. }
  2032. // handle potential flash error
  2033. if(typeof(rval) !== 'undefined' && rval.rval !== true) {
  2034. var error = new Error(rval.error.message);
  2035. error.id = rval.error.id;
  2036. error.name = rval.error.name;
  2037. throw error;
  2038. }
  2039. };
  2040. /**
  2041. * Gets a storage object.
  2042. *
  2043. * @param api the storage interface.
  2044. * @param id the storage ID to use.
  2045. *
  2046. * @return the storage object entry or null if none exists.
  2047. */
  2048. var _getStorageObject = function(api, id) {
  2049. if(!api) {
  2050. throw new Error('WebStorage not available.');
  2051. }
  2052. // get the existing entry
  2053. var rval = api.getItem(id);
  2054. /* Note: We check api.init because we can't do (api == localStorage)
  2055. on IE because of "Class doesn't support Automation" exception. Only
  2056. the flash api has an init method so this works too, but we need a
  2057. better solution in the future. */
  2058. // flash returns item wrapped in an object, handle special case
  2059. if(api.init) {
  2060. if(rval.rval === null) {
  2061. if(rval.error) {
  2062. var error = new Error(rval.error.message);
  2063. error.id = rval.error.id;
  2064. error.name = rval.error.name;
  2065. throw error;
  2066. }
  2067. // no error, but also no item
  2068. rval = null;
  2069. } else {
  2070. rval = rval.rval;
  2071. }
  2072. }
  2073. // handle decoding
  2074. if(rval !== null) {
  2075. // base64-decode and json-decode data
  2076. rval = JSON.parse(util$1.decode64(rval));
  2077. }
  2078. return rval;
  2079. };
  2080. /**
  2081. * Stores an item in local storage.
  2082. *
  2083. * @param api the storage interface.
  2084. * @param id the storage ID to use.
  2085. * @param key the key for the item.
  2086. * @param data the data for the item (any javascript object/primitive).
  2087. */
  2088. var _setItem = function(api, id, key, data) {
  2089. // get storage object
  2090. var obj = _getStorageObject(api, id);
  2091. if(obj === null) {
  2092. // create a new storage object
  2093. obj = {};
  2094. }
  2095. // update key
  2096. obj[key] = data;
  2097. // set storage object
  2098. _setStorageObject(api, id, obj);
  2099. };
  2100. /**
  2101. * Gets an item from local storage.
  2102. *
  2103. * @param api the storage interface.
  2104. * @param id the storage ID to use.
  2105. * @param key the key for the item.
  2106. *
  2107. * @return the item.
  2108. */
  2109. var _getItem = function(api, id, key) {
  2110. // get storage object
  2111. var rval = _getStorageObject(api, id);
  2112. if(rval !== null) {
  2113. // return data at key
  2114. rval = (key in rval) ? rval[key] : null;
  2115. }
  2116. return rval;
  2117. };
  2118. /**
  2119. * Removes an item from local storage.
  2120. *
  2121. * @param api the storage interface.
  2122. * @param id the storage ID to use.
  2123. * @param key the key for the item.
  2124. */
  2125. var _removeItem = function(api, id, key) {
  2126. // get storage object
  2127. var obj = _getStorageObject(api, id);
  2128. if(obj !== null && key in obj) {
  2129. // remove key
  2130. delete obj[key];
  2131. // see if entry has no keys remaining
  2132. var empty = true;
  2133. for(var prop in obj) {
  2134. empty = false;
  2135. break;
  2136. }
  2137. if(empty) {
  2138. // remove entry entirely if no keys are left
  2139. obj = null;
  2140. }
  2141. // set storage object
  2142. _setStorageObject(api, id, obj);
  2143. }
  2144. };
  2145. /**
  2146. * Clears the local disk storage identified by the given ID.
  2147. *
  2148. * @param api the storage interface.
  2149. * @param id the storage ID to use.
  2150. */
  2151. var _clearItems = function(api, id) {
  2152. _setStorageObject(api, id, null);
  2153. };
  2154. /**
  2155. * Calls a storage function.
  2156. *
  2157. * @param func the function to call.
  2158. * @param args the arguments for the function.
  2159. * @param location the location argument.
  2160. *
  2161. * @return the return value from the function.
  2162. */
  2163. var _callStorageFunction = function(func, args, location) {
  2164. var rval = null;
  2165. // default storage types
  2166. if(typeof(location) === 'undefined') {
  2167. location = ['web', 'flash'];
  2168. }
  2169. // apply storage types in order of preference
  2170. var type;
  2171. var done = false;
  2172. var exception = null;
  2173. for(var idx in location) {
  2174. type = location[idx];
  2175. try {
  2176. if(type === 'flash' || type === 'both') {
  2177. if(args[0] === null) {
  2178. throw new Error('Flash local storage not available.');
  2179. }
  2180. rval = func.apply(this, args);
  2181. done = (type === 'flash');
  2182. }
  2183. if(type === 'web' || type === 'both') {
  2184. args[0] = localStorage;
  2185. rval = func.apply(this, args);
  2186. done = true;
  2187. }
  2188. } catch(ex) {
  2189. exception = ex;
  2190. }
  2191. if(done) {
  2192. break;
  2193. }
  2194. }
  2195. if(!done) {
  2196. throw exception;
  2197. }
  2198. return rval;
  2199. };
  2200. /**
  2201. * Stores an item on local disk.
  2202. *
  2203. * The available types of local storage include 'flash', 'web', and 'both'.
  2204. *
  2205. * The type 'flash' refers to flash local storage (SharedObject). In order
  2206. * to use flash local storage, the 'api' parameter must be valid. The type
  2207. * 'web' refers to WebStorage, if supported by the browser. The type 'both'
  2208. * refers to storing using both 'flash' and 'web', not just one or the
  2209. * other.
  2210. *
  2211. * The location array should list the storage types to use in order of
  2212. * preference:
  2213. *
  2214. * ['flash']: flash only storage
  2215. * ['web']: web only storage
  2216. * ['both']: try to store in both
  2217. * ['flash','web']: store in flash first, but if not available, 'web'
  2218. * ['web','flash']: store in web first, but if not available, 'flash'
  2219. *
  2220. * The location array defaults to: ['web', 'flash']
  2221. *
  2222. * @param api the flash interface, null to use only WebStorage.
  2223. * @param id the storage ID to use.
  2224. * @param key the key for the item.
  2225. * @param data the data for the item (any javascript object/primitive).
  2226. * @param location an array with the preferred types of storage to use.
  2227. */
  2228. util$1.setItem = function(api, id, key, data, location) {
  2229. _callStorageFunction(_setItem, arguments, location);
  2230. };
  2231. /**
  2232. * Gets an item on local disk.
  2233. *
  2234. * Set setItem() for details on storage types.
  2235. *
  2236. * @param api the flash interface, null to use only WebStorage.
  2237. * @param id the storage ID to use.
  2238. * @param key the key for the item.
  2239. * @param location an array with the preferred types of storage to use.
  2240. *
  2241. * @return the item.
  2242. */
  2243. util$1.getItem = function(api, id, key, location) {
  2244. return _callStorageFunction(_getItem, arguments, location);
  2245. };
  2246. /**
  2247. * Removes an item on local disk.
  2248. *
  2249. * Set setItem() for details on storage types.
  2250. *
  2251. * @param api the flash interface.
  2252. * @param id the storage ID to use.
  2253. * @param key the key for the item.
  2254. * @param location an array with the preferred types of storage to use.
  2255. */
  2256. util$1.removeItem = function(api, id, key, location) {
  2257. _callStorageFunction(_removeItem, arguments, location);
  2258. };
  2259. /**
  2260. * Clears the local disk storage identified by the given ID.
  2261. *
  2262. * Set setItem() for details on storage types.
  2263. *
  2264. * @param api the flash interface if flash is available.
  2265. * @param id the storage ID to use.
  2266. * @param location an array with the preferred types of storage to use.
  2267. */
  2268. util$1.clearItems = function(api, id, location) {
  2269. _callStorageFunction(_clearItems, arguments, location);
  2270. };
  2271. /**
  2272. * Check if an object is empty.
  2273. *
  2274. * Taken from:
  2275. * http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json/679937#679937
  2276. *
  2277. * @param object the object to check.
  2278. */
  2279. util$1.isEmpty = function(obj) {
  2280. for(var prop in obj) {
  2281. if(obj.hasOwnProperty(prop)) {
  2282. return false;
  2283. }
  2284. }
  2285. return true;
  2286. };
  2287. /**
  2288. * Format with simple printf-style interpolation.
  2289. *
  2290. * %%: literal '%'
  2291. * %s,%o: convert next argument into a string.
  2292. *
  2293. * @param format the string to format.
  2294. * @param ... arguments to interpolate into the format string.
  2295. */
  2296. util$1.format = function(format) {
  2297. var re = /%./g;
  2298. // current match
  2299. var match;
  2300. // current part
  2301. var part;
  2302. // current arg index
  2303. var argi = 0;
  2304. // collected parts to recombine later
  2305. var parts = [];
  2306. // last index found
  2307. var last = 0;
  2308. // loop while matches remain
  2309. while((match = re.exec(format))) {
  2310. part = format.substring(last, re.lastIndex - 2);
  2311. // don't add empty strings (ie, parts between %s%s)
  2312. if(part.length > 0) {
  2313. parts.push(part);
  2314. }
  2315. last = re.lastIndex;
  2316. // switch on % code
  2317. var code = match[0][1];
  2318. switch(code) {
  2319. case 's':
  2320. case 'o':
  2321. // check if enough arguments were given
  2322. if(argi < arguments.length) {
  2323. parts.push(arguments[argi++ + 1]);
  2324. } else {
  2325. parts.push('<?>');
  2326. }
  2327. break;
  2328. // FIXME: do proper formating for numbers, etc
  2329. //case 'f':
  2330. //case 'd':
  2331. case '%':
  2332. parts.push('%');
  2333. break;
  2334. default:
  2335. parts.push('<%' + code + '?>');
  2336. }
  2337. }
  2338. // add trailing part of format string
  2339. parts.push(format.substring(last));
  2340. return parts.join('');
  2341. };
  2342. /**
  2343. * Formats a number.
  2344. *
  2345. * http://snipplr.com/view/5945/javascript-numberformat--ported-from-php/
  2346. */
  2347. util$1.formatNumber = function(number, decimals, dec_point, thousands_sep) {
  2348. // http://kevin.vanzonneveld.net
  2349. // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  2350. // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  2351. // + bugfix by: Michael White (http://crestidg.com)
  2352. // + bugfix by: Benjamin Lupton
  2353. // + bugfix by: Allan Jensen (http://www.winternet.no)
  2354. // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  2355. // * example 1: number_format(1234.5678, 2, '.', '');
  2356. // * returns 1: 1234.57
  2357. var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
  2358. var d = dec_point === undefined ? ',' : dec_point;
  2359. var t = thousands_sep === undefined ?
  2360. '.' : thousands_sep, s = n < 0 ? '-' : '';
  2361. var i = parseInt((n = Math.abs(+n || 0).toFixed(c)), 10) + '';
  2362. var j = (i.length > 3) ? i.length % 3 : 0;
  2363. return s + (j ? i.substr(0, j) + t : '') +
  2364. i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + t) +
  2365. (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');
  2366. };
  2367. /**
  2368. * Formats a byte size.
  2369. *
  2370. * http://snipplr.com/view/5949/format-humanize-file-byte-size-presentation-in-javascript/
  2371. */
  2372. util$1.formatSize = function(size) {
  2373. if(size >= 1073741824) {
  2374. size = util$1.formatNumber(size / 1073741824, 2, '.', '') + ' GiB';
  2375. } else if(size >= 1048576) {
  2376. size = util$1.formatNumber(size / 1048576, 2, '.', '') + ' MiB';
  2377. } else if(size >= 1024) {
  2378. size = util$1.formatNumber(size / 1024, 0) + ' KiB';
  2379. } else {
  2380. size = util$1.formatNumber(size, 0) + ' bytes';
  2381. }
  2382. return size;
  2383. };
  2384. /**
  2385. * Converts an IPv4 or IPv6 string representation into bytes (in network order).
  2386. *
  2387. * @param ip the IPv4 or IPv6 address to convert.
  2388. *
  2389. * @return the 4-byte IPv6 or 16-byte IPv6 address or null if the address can't
  2390. * be parsed.
  2391. */
  2392. util$1.bytesFromIP = function(ip) {
  2393. if(ip.indexOf('.') !== -1) {
  2394. return util$1.bytesFromIPv4(ip);
  2395. }
  2396. if(ip.indexOf(':') !== -1) {
  2397. return util$1.bytesFromIPv6(ip);
  2398. }
  2399. return null;
  2400. };
  2401. /**
  2402. * Converts an IPv4 string representation into bytes (in network order).
  2403. *
  2404. * @param ip the IPv4 address to convert.
  2405. *
  2406. * @return the 4-byte address or null if the address can't be parsed.
  2407. */
  2408. util$1.bytesFromIPv4 = function(ip) {
  2409. ip = ip.split('.');
  2410. if(ip.length !== 4) {
  2411. return null;
  2412. }
  2413. var b = util$1.createBuffer();
  2414. for(var i = 0; i < ip.length; ++i) {
  2415. var num = parseInt(ip[i], 10);
  2416. if(isNaN(num)) {
  2417. return null;
  2418. }
  2419. b.putByte(num);
  2420. }
  2421. return b.getBytes();
  2422. };
  2423. /**
  2424. * Converts an IPv6 string representation into bytes (in network order).
  2425. *
  2426. * @param ip the IPv6 address to convert.
  2427. *
  2428. * @return the 16-byte address or null if the address can't be parsed.
  2429. */
  2430. util$1.bytesFromIPv6 = function(ip) {
  2431. var blanks = 0;
  2432. ip = ip.split(':').filter(function(e) {
  2433. if(e.length === 0) ++blanks;
  2434. return true;
  2435. });
  2436. var zeros = (8 - ip.length + blanks) * 2;
  2437. var b = util$1.createBuffer();
  2438. for(var i = 0; i < 8; ++i) {
  2439. if(!ip[i] || ip[i].length === 0) {
  2440. b.fillWithByte(0, zeros);
  2441. zeros = 0;
  2442. continue;
  2443. }
  2444. var bytes = util$1.hexToBytes(ip[i]);
  2445. if(bytes.length < 2) {
  2446. b.putByte(0);
  2447. }
  2448. b.putBytes(bytes);
  2449. }
  2450. return b.getBytes();
  2451. };
  2452. /**
  2453. * Converts 4-bytes into an IPv4 string representation or 16-bytes into
  2454. * an IPv6 string representation. The bytes must be in network order.
  2455. *
  2456. * @param bytes the bytes to convert.
  2457. *
  2458. * @return the IPv4 or IPv6 string representation if 4 or 16 bytes,
  2459. * respectively, are given, otherwise null.
  2460. */
  2461. util$1.bytesToIP = function(bytes) {
  2462. if(bytes.length === 4) {
  2463. return util$1.bytesToIPv4(bytes);
  2464. }
  2465. if(bytes.length === 16) {
  2466. return util$1.bytesToIPv6(bytes);
  2467. }
  2468. return null;
  2469. };
  2470. /**
  2471. * Converts 4-bytes into an IPv4 string representation. The bytes must be
  2472. * in network order.
  2473. *
  2474. * @param bytes the bytes to convert.
  2475. *
  2476. * @return the IPv4 string representation or null for an invalid # of bytes.
  2477. */
  2478. util$1.bytesToIPv4 = function(bytes) {
  2479. if(bytes.length !== 4) {
  2480. return null;
  2481. }
  2482. var ip = [];
  2483. for(var i = 0; i < bytes.length; ++i) {
  2484. ip.push(bytes.charCodeAt(i));
  2485. }
  2486. return ip.join('.');
  2487. };
  2488. /**
  2489. * Converts 16-bytes into an IPv16 string representation. The bytes must be
  2490. * in network order.
  2491. *
  2492. * @param bytes the bytes to convert.
  2493. *
  2494. * @return the IPv16 string representation or null for an invalid # of bytes.
  2495. */
  2496. util$1.bytesToIPv6 = function(bytes) {
  2497. if(bytes.length !== 16) {
  2498. return null;
  2499. }
  2500. var ip = [];
  2501. var zeroGroups = [];
  2502. var zeroMaxGroup = 0;
  2503. for(var i = 0; i < bytes.length; i += 2) {
  2504. var hex = util$1.bytesToHex(bytes[i] + bytes[i + 1]);
  2505. // canonicalize zero representation
  2506. while(hex[0] === '0' && hex !== '0') {
  2507. hex = hex.substr(1);
  2508. }
  2509. if(hex === '0') {
  2510. var last = zeroGroups[zeroGroups.length - 1];
  2511. var idx = ip.length;
  2512. if(!last || idx !== last.end + 1) {
  2513. zeroGroups.push({start: idx, end: idx});
  2514. } else {
  2515. last.end = idx;
  2516. if((last.end - last.start) >
  2517. (zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start)) {
  2518. zeroMaxGroup = zeroGroups.length - 1;
  2519. }
  2520. }
  2521. }
  2522. ip.push(hex);
  2523. }
  2524. if(zeroGroups.length > 0) {
  2525. var group = zeroGroups[zeroMaxGroup];
  2526. // only shorten group of length > 0
  2527. if(group.end - group.start > 0) {
  2528. ip.splice(group.start, group.end - group.start + 1, '');
  2529. if(group.start === 0) {
  2530. ip.unshift('');
  2531. }
  2532. if(group.end === 7) {
  2533. ip.push('');
  2534. }
  2535. }
  2536. }
  2537. return ip.join(':');
  2538. };
  2539. /**
  2540. * Estimates the number of processes that can be run concurrently. If
  2541. * creating Web Workers, keep in mind that the main JavaScript process needs
  2542. * its own core.
  2543. *
  2544. * @param options the options to use:
  2545. * update true to force an update (not use the cached value).
  2546. * @param callback(err, max) called once the operation completes.
  2547. */
  2548. util$1.estimateCores = function(options, callback) {
  2549. if(typeof options === 'function') {
  2550. callback = options;
  2551. options = {};
  2552. }
  2553. options = options || {};
  2554. if('cores' in util$1 && !options.update) {
  2555. return callback(null, util$1.cores);
  2556. }
  2557. if(typeof navigator !== 'undefined' &&
  2558. 'hardwareConcurrency' in navigator &&
  2559. navigator.hardwareConcurrency > 0) {
  2560. util$1.cores = navigator.hardwareConcurrency;
  2561. return callback(null, util$1.cores);
  2562. }
  2563. if(typeof Worker === 'undefined') {
  2564. // workers not available
  2565. util$1.cores = 1;
  2566. return callback(null, util$1.cores);
  2567. }
  2568. if(typeof Blob === 'undefined') {
  2569. // can't estimate, default to 2
  2570. util$1.cores = 2;
  2571. return callback(null, util$1.cores);
  2572. }
  2573. // create worker concurrency estimation code as blob
  2574. var blobUrl = URL.createObjectURL(new Blob(['(',
  2575. function() {
  2576. self.addEventListener('message', function(e) {
  2577. // run worker for 4 ms
  2578. var st = Date.now();
  2579. var et = st + 4;
  2580. self.postMessage({st: st, et: et});
  2581. });
  2582. }.toString(),
  2583. ')()'], {type: 'application/javascript'}));
  2584. // take 5 samples using 16 workers
  2585. sample([], 5, 16);
  2586. function sample(max, samples, numWorkers) {
  2587. if(samples === 0) {
  2588. // get overlap average
  2589. var avg = Math.floor(max.reduce(function(avg, x) {
  2590. return avg + x;
  2591. }, 0) / max.length);
  2592. util$1.cores = Math.max(1, avg);
  2593. URL.revokeObjectURL(blobUrl);
  2594. return callback(null, util$1.cores);
  2595. }
  2596. map(numWorkers, function(err, results) {
  2597. max.push(reduce(numWorkers, results));
  2598. sample(max, samples - 1, numWorkers);
  2599. });
  2600. }
  2601. function map(numWorkers, callback) {
  2602. var workers = [];
  2603. var results = [];
  2604. for(var i = 0; i < numWorkers; ++i) {
  2605. var worker = new Worker(blobUrl);
  2606. worker.addEventListener('message', function(e) {
  2607. results.push(e.data);
  2608. if(results.length === numWorkers) {
  2609. for(var i = 0; i < numWorkers; ++i) {
  2610. workers[i].terminate();
  2611. }
  2612. callback(null, results);
  2613. }
  2614. });
  2615. workers.push(worker);
  2616. }
  2617. for(var i = 0; i < numWorkers; ++i) {
  2618. workers[i].postMessage(i);
  2619. }
  2620. }
  2621. function reduce(numWorkers, results) {
  2622. // find overlapping time windows
  2623. var overlaps = [];
  2624. for(var n = 0; n < numWorkers; ++n) {
  2625. var r1 = results[n];
  2626. var overlap = overlaps[n] = [];
  2627. for(var i = 0; i < numWorkers; ++i) {
  2628. if(n === i) {
  2629. continue;
  2630. }
  2631. var r2 = results[i];
  2632. if((r1.st > r2.st && r1.st < r2.et) ||
  2633. (r2.st > r1.st && r2.st < r1.et)) {
  2634. overlap.push(i);
  2635. }
  2636. }
  2637. }
  2638. // get maximum overlaps ... don't include overlapping worker itself
  2639. // as the main JS process was also being scheduled during the work and
  2640. // would have to be subtracted from the estimate anyway
  2641. return overlaps.reduce(function(max, overlap) {
  2642. return Math.max(max, overlap.length);
  2643. }, 0);
  2644. }
  2645. };
  2646. /**
  2647. * Object IDs for ASN.1.
  2648. *
  2649. * @author Dave Longley
  2650. *
  2651. * Copyright (c) 2010-2013 Digital Bazaar, Inc.
  2652. */
  2653. var forge$q = forge$s;
  2654. forge$q.pki = forge$q.pki || {};
  2655. var oids$2 = forge$q.pki.oids = forge$q.oids = forge$q.oids || {};
  2656. // set id to name mapping and name to id mapping
  2657. function _IN(id, name) {
  2658. oids$2[id] = name;
  2659. oids$2[name] = id;
  2660. }
  2661. // set id to name mapping only
  2662. function _I_(id, name) {
  2663. oids$2[id] = name;
  2664. }
  2665. // algorithm OIDs
  2666. _IN('1.2.840.113549.1.1.1', 'rsaEncryption');
  2667. // Note: md2 & md4 not implemented
  2668. //_IN('1.2.840.113549.1.1.2', 'md2WithRSAEncryption');
  2669. //_IN('1.2.840.113549.1.1.3', 'md4WithRSAEncryption');
  2670. _IN('1.2.840.113549.1.1.4', 'md5WithRSAEncryption');
  2671. _IN('1.2.840.113549.1.1.5', 'sha1WithRSAEncryption');
  2672. _IN('1.2.840.113549.1.1.7', 'RSAES-OAEP');
  2673. _IN('1.2.840.113549.1.1.8', 'mgf1');
  2674. _IN('1.2.840.113549.1.1.9', 'pSpecified');
  2675. _IN('1.2.840.113549.1.1.10', 'RSASSA-PSS');
  2676. _IN('1.2.840.113549.1.1.11', 'sha256WithRSAEncryption');
  2677. _IN('1.2.840.113549.1.1.12', 'sha384WithRSAEncryption');
  2678. _IN('1.2.840.113549.1.1.13', 'sha512WithRSAEncryption');
  2679. // Edwards-curve Digital Signature Algorithm (EdDSA) Ed25519
  2680. _IN('1.3.101.112', 'EdDSA25519');
  2681. _IN('1.2.840.10040.4.3', 'dsa-with-sha1');
  2682. _IN('1.3.14.3.2.7', 'desCBC');
  2683. _IN('1.3.14.3.2.26', 'sha1');
  2684. // Deprecated equivalent of sha1WithRSAEncryption
  2685. _IN('1.3.14.3.2.29', 'sha1WithRSASignature');
  2686. _IN('2.16.840.1.101.3.4.2.1', 'sha256');
  2687. _IN('2.16.840.1.101.3.4.2.2', 'sha384');
  2688. _IN('2.16.840.1.101.3.4.2.3', 'sha512');
  2689. _IN('2.16.840.1.101.3.4.2.4', 'sha224');
  2690. _IN('2.16.840.1.101.3.4.2.5', 'sha512-224');
  2691. _IN('2.16.840.1.101.3.4.2.6', 'sha512-256');
  2692. _IN('1.2.840.113549.2.2', 'md2');
  2693. _IN('1.2.840.113549.2.5', 'md5');
  2694. // pkcs#7 content types
  2695. _IN('1.2.840.113549.1.7.1', 'data');
  2696. _IN('1.2.840.113549.1.7.2', 'signedData');
  2697. _IN('1.2.840.113549.1.7.3', 'envelopedData');
  2698. _IN('1.2.840.113549.1.7.4', 'signedAndEnvelopedData');
  2699. _IN('1.2.840.113549.1.7.5', 'digestedData');
  2700. _IN('1.2.840.113549.1.7.6', 'encryptedData');
  2701. // pkcs#9 oids
  2702. _IN('1.2.840.113549.1.9.1', 'emailAddress');
  2703. _IN('1.2.840.113549.1.9.2', 'unstructuredName');
  2704. _IN('1.2.840.113549.1.9.3', 'contentType');
  2705. _IN('1.2.840.113549.1.9.4', 'messageDigest');
  2706. _IN('1.2.840.113549.1.9.5', 'signingTime');
  2707. _IN('1.2.840.113549.1.9.6', 'counterSignature');
  2708. _IN('1.2.840.113549.1.9.7', 'challengePassword');
  2709. _IN('1.2.840.113549.1.9.8', 'unstructuredAddress');
  2710. _IN('1.2.840.113549.1.9.14', 'extensionRequest');
  2711. _IN('1.2.840.113549.1.9.20', 'friendlyName');
  2712. _IN('1.2.840.113549.1.9.21', 'localKeyId');
  2713. _IN('1.2.840.113549.1.9.22.1', 'x509Certificate');
  2714. // pkcs#12 safe bags
  2715. _IN('1.2.840.113549.1.12.10.1.1', 'keyBag');
  2716. _IN('1.2.840.113549.1.12.10.1.2', 'pkcs8ShroudedKeyBag');
  2717. _IN('1.2.840.113549.1.12.10.1.3', 'certBag');
  2718. _IN('1.2.840.113549.1.12.10.1.4', 'crlBag');
  2719. _IN('1.2.840.113549.1.12.10.1.5', 'secretBag');
  2720. _IN('1.2.840.113549.1.12.10.1.6', 'safeContentsBag');
  2721. // password-based-encryption for pkcs#12
  2722. _IN('1.2.840.113549.1.5.13', 'pkcs5PBES2');
  2723. _IN('1.2.840.113549.1.5.12', 'pkcs5PBKDF2');
  2724. _IN('1.2.840.113549.1.12.1.1', 'pbeWithSHAAnd128BitRC4');
  2725. _IN('1.2.840.113549.1.12.1.2', 'pbeWithSHAAnd40BitRC4');
  2726. _IN('1.2.840.113549.1.12.1.3', 'pbeWithSHAAnd3-KeyTripleDES-CBC');
  2727. _IN('1.2.840.113549.1.12.1.4', 'pbeWithSHAAnd2-KeyTripleDES-CBC');
  2728. _IN('1.2.840.113549.1.12.1.5', 'pbeWithSHAAnd128BitRC2-CBC');
  2729. _IN('1.2.840.113549.1.12.1.6', 'pbewithSHAAnd40BitRC2-CBC');
  2730. // hmac OIDs
  2731. _IN('1.2.840.113549.2.7', 'hmacWithSHA1');
  2732. _IN('1.2.840.113549.2.8', 'hmacWithSHA224');
  2733. _IN('1.2.840.113549.2.9', 'hmacWithSHA256');
  2734. _IN('1.2.840.113549.2.10', 'hmacWithSHA384');
  2735. _IN('1.2.840.113549.2.11', 'hmacWithSHA512');
  2736. // symmetric key algorithm oids
  2737. _IN('1.2.840.113549.3.7', 'des-EDE3-CBC');
  2738. _IN('2.16.840.1.101.3.4.1.2', 'aes128-CBC');
  2739. _IN('2.16.840.1.101.3.4.1.22', 'aes192-CBC');
  2740. _IN('2.16.840.1.101.3.4.1.42', 'aes256-CBC');
  2741. // certificate issuer/subject OIDs
  2742. _IN('2.5.4.3', 'commonName');
  2743. _IN('2.5.4.4', 'surname');
  2744. _IN('2.5.4.5', 'serialNumber');
  2745. _IN('2.5.4.6', 'countryName');
  2746. _IN('2.5.4.7', 'localityName');
  2747. _IN('2.5.4.8', 'stateOrProvinceName');
  2748. _IN('2.5.4.9', 'streetAddress');
  2749. _IN('2.5.4.10', 'organizationName');
  2750. _IN('2.5.4.11', 'organizationalUnitName');
  2751. _IN('2.5.4.12', 'title');
  2752. _IN('2.5.4.13', 'description');
  2753. _IN('2.5.4.15', 'businessCategory');
  2754. _IN('2.5.4.17', 'postalCode');
  2755. _IN('2.5.4.42', 'givenName');
  2756. _IN('1.3.6.1.4.1.311.60.2.1.2', 'jurisdictionOfIncorporationStateOrProvinceName');
  2757. _IN('1.3.6.1.4.1.311.60.2.1.3', 'jurisdictionOfIncorporationCountryName');
  2758. // X.509 extension OIDs
  2759. _IN('2.16.840.1.113730.1.1', 'nsCertType');
  2760. _IN('2.16.840.1.113730.1.13', 'nsComment'); // deprecated in theory; still widely used
  2761. _I_('2.5.29.1', 'authorityKeyIdentifier'); // deprecated, use .35
  2762. _I_('2.5.29.2', 'keyAttributes'); // obsolete use .37 or .15
  2763. _I_('2.5.29.3', 'certificatePolicies'); // deprecated, use .32
  2764. _I_('2.5.29.4', 'keyUsageRestriction'); // obsolete use .37 or .15
  2765. _I_('2.5.29.5', 'policyMapping'); // deprecated use .33
  2766. _I_('2.5.29.6', 'subtreesConstraint'); // obsolete use .30
  2767. _I_('2.5.29.7', 'subjectAltName'); // deprecated use .17
  2768. _I_('2.5.29.8', 'issuerAltName'); // deprecated use .18
  2769. _I_('2.5.29.9', 'subjectDirectoryAttributes');
  2770. _I_('2.5.29.10', 'basicConstraints'); // deprecated use .19
  2771. _I_('2.5.29.11', 'nameConstraints'); // deprecated use .30
  2772. _I_('2.5.29.12', 'policyConstraints'); // deprecated use .36
  2773. _I_('2.5.29.13', 'basicConstraints'); // deprecated use .19
  2774. _IN('2.5.29.14', 'subjectKeyIdentifier');
  2775. _IN('2.5.29.15', 'keyUsage');
  2776. _I_('2.5.29.16', 'privateKeyUsagePeriod');
  2777. _IN('2.5.29.17', 'subjectAltName');
  2778. _IN('2.5.29.18', 'issuerAltName');
  2779. _IN('2.5.29.19', 'basicConstraints');
  2780. _I_('2.5.29.20', 'cRLNumber');
  2781. _I_('2.5.29.21', 'cRLReason');
  2782. _I_('2.5.29.22', 'expirationDate');
  2783. _I_('2.5.29.23', 'instructionCode');
  2784. _I_('2.5.29.24', 'invalidityDate');
  2785. _I_('2.5.29.25', 'cRLDistributionPoints'); // deprecated use .31
  2786. _I_('2.5.29.26', 'issuingDistributionPoint'); // deprecated use .28
  2787. _I_('2.5.29.27', 'deltaCRLIndicator');
  2788. _I_('2.5.29.28', 'issuingDistributionPoint');
  2789. _I_('2.5.29.29', 'certificateIssuer');
  2790. _I_('2.5.29.30', 'nameConstraints');
  2791. _IN('2.5.29.31', 'cRLDistributionPoints');
  2792. _IN('2.5.29.32', 'certificatePolicies');
  2793. _I_('2.5.29.33', 'policyMappings');
  2794. _I_('2.5.29.34', 'policyConstraints'); // deprecated use .36
  2795. _IN('2.5.29.35', 'authorityKeyIdentifier');
  2796. _I_('2.5.29.36', 'policyConstraints');
  2797. _IN('2.5.29.37', 'extKeyUsage');
  2798. _I_('2.5.29.46', 'freshestCRL');
  2799. _I_('2.5.29.54', 'inhibitAnyPolicy');
  2800. // extKeyUsage purposes
  2801. _IN('1.3.6.1.4.1.11129.2.4.2', 'timestampList');
  2802. _IN('1.3.6.1.5.5.7.1.1', 'authorityInfoAccess');
  2803. _IN('1.3.6.1.5.5.7.3.1', 'serverAuth');
  2804. _IN('1.3.6.1.5.5.7.3.2', 'clientAuth');
  2805. _IN('1.3.6.1.5.5.7.3.3', 'codeSigning');
  2806. _IN('1.3.6.1.5.5.7.3.4', 'emailProtection');
  2807. _IN('1.3.6.1.5.5.7.3.8', 'timeStamping');
  2808. /**
  2809. * Javascript implementation of Abstract Syntax Notation Number One.
  2810. *
  2811. * @author Dave Longley
  2812. *
  2813. * Copyright (c) 2010-2015 Digital Bazaar, Inc.
  2814. *
  2815. * An API for storing data using the Abstract Syntax Notation Number One
  2816. * format using DER (Distinguished Encoding Rules) encoding. This encoding is
  2817. * commonly used to store data for PKI, i.e. X.509 Certificates, and this
  2818. * implementation exists for that purpose.
  2819. *
  2820. * Abstract Syntax Notation Number One (ASN.1) is used to define the abstract
  2821. * syntax of information without restricting the way the information is encoded
  2822. * for transmission. It provides a standard that allows for open systems
  2823. * communication. ASN.1 defines the syntax of information data and a number of
  2824. * simple data types as well as a notation for describing them and specifying
  2825. * values for them.
  2826. *
  2827. * The RSA algorithm creates public and private keys that are often stored in
  2828. * X.509 or PKCS#X formats -- which use ASN.1 (encoded in DER format). This
  2829. * class provides the most basic functionality required to store and load DSA
  2830. * keys that are encoded according to ASN.1.
  2831. *
  2832. * The most common binary encodings for ASN.1 are BER (Basic Encoding Rules)
  2833. * and DER (Distinguished Encoding Rules). DER is just a subset of BER that
  2834. * has stricter requirements for how data must be encoded.
  2835. *
  2836. * Each ASN.1 structure has a tag (a byte identifying the ASN.1 structure type)
  2837. * and a byte array for the value of this ASN1 structure which may be data or a
  2838. * list of ASN.1 structures.
  2839. *
  2840. * Each ASN.1 structure using BER is (Tag-Length-Value):
  2841. *
  2842. * | byte 0 | bytes X | bytes Y |
  2843. * |--------|---------|----------
  2844. * | tag | length | value |
  2845. *
  2846. * ASN.1 allows for tags to be of "High-tag-number form" which allows a tag to
  2847. * be two or more octets, but that is not supported by this class. A tag is
  2848. * only 1 byte. Bits 1-5 give the tag number (ie the data type within a
  2849. * particular 'class'), 6 indicates whether or not the ASN.1 value is
  2850. * constructed from other ASN.1 values, and bits 7 and 8 give the 'class'. If
  2851. * bits 7 and 8 are both zero, the class is UNIVERSAL. If only bit 7 is set,
  2852. * then the class is APPLICATION. If only bit 8 is set, then the class is
  2853. * CONTEXT_SPECIFIC. If both bits 7 and 8 are set, then the class is PRIVATE.
  2854. * The tag numbers for the data types for the class UNIVERSAL are listed below:
  2855. *
  2856. * UNIVERSAL 0 Reserved for use by the encoding rules
  2857. * UNIVERSAL 1 Boolean type
  2858. * UNIVERSAL 2 Integer type
  2859. * UNIVERSAL 3 Bitstring type
  2860. * UNIVERSAL 4 Octetstring type
  2861. * UNIVERSAL 5 Null type
  2862. * UNIVERSAL 6 Object identifier type
  2863. * UNIVERSAL 7 Object descriptor type
  2864. * UNIVERSAL 8 External type and Instance-of type
  2865. * UNIVERSAL 9 Real type
  2866. * UNIVERSAL 10 Enumerated type
  2867. * UNIVERSAL 11 Embedded-pdv type
  2868. * UNIVERSAL 12 UTF8String type
  2869. * UNIVERSAL 13 Relative object identifier type
  2870. * UNIVERSAL 14-15 Reserved for future editions
  2871. * UNIVERSAL 16 Sequence and Sequence-of types
  2872. * UNIVERSAL 17 Set and Set-of types
  2873. * UNIVERSAL 18-22, 25-30 Character string types
  2874. * UNIVERSAL 23-24 Time types
  2875. *
  2876. * The length of an ASN.1 structure is specified after the tag identifier.
  2877. * There is a definite form and an indefinite form. The indefinite form may
  2878. * be used if the encoding is constructed and not all immediately available.
  2879. * The indefinite form is encoded using a length byte with only the 8th bit
  2880. * set. The end of the constructed object is marked using end-of-contents
  2881. * octets (two zero bytes).
  2882. *
  2883. * The definite form looks like this:
  2884. *
  2885. * The length may take up 1 or more bytes, it depends on the length of the
  2886. * value of the ASN.1 structure. DER encoding requires that if the ASN.1
  2887. * structure has a value that has a length greater than 127, more than 1 byte
  2888. * will be used to store its length, otherwise just one byte will be used.
  2889. * This is strict.
  2890. *
  2891. * In the case that the length of the ASN.1 value is less than 127, 1 octet
  2892. * (byte) is used to store the "short form" length. The 8th bit has a value of
  2893. * 0 indicating the length is "short form" and not "long form" and bits 7-1
  2894. * give the length of the data. (The 8th bit is the left-most, most significant
  2895. * bit: also known as big endian or network format).
  2896. *
  2897. * In the case that the length of the ASN.1 value is greater than 127, 2 to
  2898. * 127 octets (bytes) are used to store the "long form" length. The first
  2899. * byte's 8th bit is set to 1 to indicate the length is "long form." Bits 7-1
  2900. * give the number of additional octets. All following octets are in base 256
  2901. * with the most significant digit first (typical big-endian binary unsigned
  2902. * integer storage). So, for instance, if the length of a value was 257, the
  2903. * first byte would be set to:
  2904. *
  2905. * 10000010 = 130 = 0x82.
  2906. *
  2907. * This indicates there are 2 octets (base 256) for the length. The second and
  2908. * third bytes (the octets just mentioned) would store the length in base 256:
  2909. *
  2910. * octet 2: 00000001 = 1 * 256^1 = 256
  2911. * octet 3: 00000001 = 1 * 256^0 = 1
  2912. * total = 257
  2913. *
  2914. * The algorithm for converting a js integer value of 257 to base-256 is:
  2915. *
  2916. * var value = 257;
  2917. * var bytes = [];
  2918. * bytes[0] = (value >>> 8) & 0xFF; // most significant byte first
  2919. * bytes[1] = value & 0xFF; // least significant byte last
  2920. *
  2921. * On the ASN.1 UNIVERSAL Object Identifier (OID) type:
  2922. *
  2923. * An OID can be written like: "value1.value2.value3...valueN"
  2924. *
  2925. * The DER encoding rules:
  2926. *
  2927. * The first byte has the value 40 * value1 + value2.
  2928. * The following bytes, if any, encode the remaining values. Each value is
  2929. * encoded in base 128, most significant digit first (big endian), with as
  2930. * few digits as possible, and the most significant bit of each byte set
  2931. * to 1 except the last in each value's encoding. For example: Given the
  2932. * OID "1.2.840.113549", its DER encoding is (remember each byte except the
  2933. * last one in each encoding is OR'd with 0x80):
  2934. *
  2935. * byte 1: 40 * 1 + 2 = 42 = 0x2A.
  2936. * bytes 2-3: 128 * 6 + 72 = 840 = 6 72 = 6 72 = 0x0648 = 0x8648
  2937. * bytes 4-6: 16384 * 6 + 128 * 119 + 13 = 6 119 13 = 0x06770D = 0x86F70D
  2938. *
  2939. * The final value is: 0x2A864886F70D.
  2940. * The full OID (including ASN.1 tag and length of 6 bytes) is:
  2941. * 0x06062A864886F70D
  2942. */
  2943. var forge$p = forge$s;
  2944. /* ASN.1 API */
  2945. var asn1$6 = forge$p.asn1 = forge$p.asn1 || {};
  2946. /**
  2947. * ASN.1 classes.
  2948. */
  2949. asn1$6.Class = {
  2950. UNIVERSAL: 0x00,
  2951. APPLICATION: 0x40,
  2952. CONTEXT_SPECIFIC: 0x80,
  2953. PRIVATE: 0xC0
  2954. };
  2955. /**
  2956. * ASN.1 types. Not all types are supported by this implementation, only
  2957. * those necessary to implement a simple PKI are implemented.
  2958. */
  2959. asn1$6.Type = {
  2960. NONE: 0,
  2961. BOOLEAN: 1,
  2962. INTEGER: 2,
  2963. BITSTRING: 3,
  2964. OCTETSTRING: 4,
  2965. NULL: 5,
  2966. OID: 6,
  2967. ODESC: 7,
  2968. EXTERNAL: 8,
  2969. REAL: 9,
  2970. ENUMERATED: 10,
  2971. EMBEDDED: 11,
  2972. UTF8: 12,
  2973. ROID: 13,
  2974. SEQUENCE: 16,
  2975. SET: 17,
  2976. PRINTABLESTRING: 19,
  2977. IA5STRING: 22,
  2978. UTCTIME: 23,
  2979. GENERALIZEDTIME: 24,
  2980. BMPSTRING: 30
  2981. };
  2982. /**
  2983. * Creates a new asn1 object.
  2984. *
  2985. * @param tagClass the tag class for the object.
  2986. * @param type the data type (tag number) for the object.
  2987. * @param constructed true if the asn1 object is in constructed form.
  2988. * @param value the value for the object, if it is not constructed.
  2989. * @param [options] the options to use:
  2990. * [bitStringContents] the plain BIT STRING content including padding
  2991. * byte.
  2992. *
  2993. * @return the asn1 object.
  2994. */
  2995. asn1$6.create = function(tagClass, type, constructed, value, options) {
  2996. /* An asn1 object has a tagClass, a type, a constructed flag, and a
  2997. value. The value's type depends on the constructed flag. If
  2998. constructed, it will contain a list of other asn1 objects. If not,
  2999. it will contain the ASN.1 value as an array of bytes formatted
  3000. according to the ASN.1 data type. */
  3001. // remove undefined values
  3002. if(forge$p.util.isArray(value)) {
  3003. var tmp = [];
  3004. for(var i = 0; i < value.length; ++i) {
  3005. if(value[i] !== undefined) {
  3006. tmp.push(value[i]);
  3007. }
  3008. }
  3009. value = tmp;
  3010. }
  3011. var obj = {
  3012. tagClass: tagClass,
  3013. type: type,
  3014. constructed: constructed,
  3015. composed: constructed || forge$p.util.isArray(value),
  3016. value: value
  3017. };
  3018. if(options && 'bitStringContents' in options) {
  3019. // TODO: copy byte buffer if it's a buffer not a string
  3020. obj.bitStringContents = options.bitStringContents;
  3021. // TODO: add readonly flag to avoid this overhead
  3022. // save copy to detect changes
  3023. obj.original = asn1$6.copy(obj);
  3024. }
  3025. return obj;
  3026. };
  3027. /**
  3028. * Copies an asn1 object.
  3029. *
  3030. * @param obj the asn1 object.
  3031. * @param [options] copy options:
  3032. * [excludeBitStringContents] true to not copy bitStringContents
  3033. *
  3034. * @return the a copy of the asn1 object.
  3035. */
  3036. asn1$6.copy = function(obj, options) {
  3037. var copy;
  3038. if(forge$p.util.isArray(obj)) {
  3039. copy = [];
  3040. for(var i = 0; i < obj.length; ++i) {
  3041. copy.push(asn1$6.copy(obj[i], options));
  3042. }
  3043. return copy;
  3044. }
  3045. if(typeof obj === 'string') {
  3046. // TODO: copy byte buffer if it's a buffer not a string
  3047. return obj;
  3048. }
  3049. copy = {
  3050. tagClass: obj.tagClass,
  3051. type: obj.type,
  3052. constructed: obj.constructed,
  3053. composed: obj.composed,
  3054. value: asn1$6.copy(obj.value, options)
  3055. };
  3056. if(options && !options.excludeBitStringContents) {
  3057. // TODO: copy byte buffer if it's a buffer not a string
  3058. copy.bitStringContents = obj.bitStringContents;
  3059. }
  3060. return copy;
  3061. };
  3062. /**
  3063. * Compares asn1 objects for equality.
  3064. *
  3065. * Note this function does not run in constant time.
  3066. *
  3067. * @param obj1 the first asn1 object.
  3068. * @param obj2 the second asn1 object.
  3069. * @param [options] compare options:
  3070. * [includeBitStringContents] true to compare bitStringContents
  3071. *
  3072. * @return true if the asn1 objects are equal.
  3073. */
  3074. asn1$6.equals = function(obj1, obj2, options) {
  3075. if(forge$p.util.isArray(obj1)) {
  3076. if(!forge$p.util.isArray(obj2)) {
  3077. return false;
  3078. }
  3079. if(obj1.length !== obj2.length) {
  3080. return false;
  3081. }
  3082. for(var i = 0; i < obj1.length; ++i) {
  3083. if(!asn1$6.equals(obj1[i], obj2[i])) {
  3084. return false;
  3085. }
  3086. }
  3087. return true;
  3088. }
  3089. if(typeof obj1 !== typeof obj2) {
  3090. return false;
  3091. }
  3092. if(typeof obj1 === 'string') {
  3093. return obj1 === obj2;
  3094. }
  3095. var equal = obj1.tagClass === obj2.tagClass &&
  3096. obj1.type === obj2.type &&
  3097. obj1.constructed === obj2.constructed &&
  3098. obj1.composed === obj2.composed &&
  3099. asn1$6.equals(obj1.value, obj2.value);
  3100. if(options && options.includeBitStringContents) {
  3101. equal = equal && (obj1.bitStringContents === obj2.bitStringContents);
  3102. }
  3103. return equal;
  3104. };
  3105. /**
  3106. * Gets the length of a BER-encoded ASN.1 value.
  3107. *
  3108. * In case the length is not specified, undefined is returned.
  3109. *
  3110. * @param b the BER-encoded ASN.1 byte buffer, starting with the first
  3111. * length byte.
  3112. *
  3113. * @return the length of the BER-encoded ASN.1 value or undefined.
  3114. */
  3115. asn1$6.getBerValueLength = function(b) {
  3116. // TODO: move this function and related DER/BER functions to a der.js
  3117. // file; better abstract ASN.1 away from der/ber.
  3118. var b2 = b.getByte();
  3119. if(b2 === 0x80) {
  3120. return undefined;
  3121. }
  3122. // see if the length is "short form" or "long form" (bit 8 set)
  3123. var length;
  3124. var longForm = b2 & 0x80;
  3125. if(!longForm) {
  3126. // length is just the first byte
  3127. length = b2;
  3128. } else {
  3129. // the number of bytes the length is specified in bits 7 through 1
  3130. // and each length byte is in big-endian base-256
  3131. length = b.getInt((b2 & 0x7F) << 3);
  3132. }
  3133. return length;
  3134. };
  3135. /**
  3136. * Check if the byte buffer has enough bytes. Throws an Error if not.
  3137. *
  3138. * @param bytes the byte buffer to parse from.
  3139. * @param remaining the bytes remaining in the current parsing state.
  3140. * @param n the number of bytes the buffer must have.
  3141. */
  3142. function _checkBufferLength(bytes, remaining, n) {
  3143. if(n > remaining) {
  3144. var error = new Error('Too few bytes to parse DER.');
  3145. error.available = bytes.length();
  3146. error.remaining = remaining;
  3147. error.requested = n;
  3148. throw error;
  3149. }
  3150. }
  3151. /**
  3152. * Gets the length of a BER-encoded ASN.1 value.
  3153. *
  3154. * In case the length is not specified, undefined is returned.
  3155. *
  3156. * @param bytes the byte buffer to parse from.
  3157. * @param remaining the bytes remaining in the current parsing state.
  3158. *
  3159. * @return the length of the BER-encoded ASN.1 value or undefined.
  3160. */
  3161. var _getValueLength = function(bytes, remaining) {
  3162. // TODO: move this function and related DER/BER functions to a der.js
  3163. // file; better abstract ASN.1 away from der/ber.
  3164. // fromDer already checked that this byte exists
  3165. var b2 = bytes.getByte();
  3166. remaining--;
  3167. if(b2 === 0x80) {
  3168. return undefined;
  3169. }
  3170. // see if the length is "short form" or "long form" (bit 8 set)
  3171. var length;
  3172. var longForm = b2 & 0x80;
  3173. if(!longForm) {
  3174. // length is just the first byte
  3175. length = b2;
  3176. } else {
  3177. // the number of bytes the length is specified in bits 7 through 1
  3178. // and each length byte is in big-endian base-256
  3179. var longFormBytes = b2 & 0x7F;
  3180. _checkBufferLength(bytes, remaining, longFormBytes);
  3181. length = bytes.getInt(longFormBytes << 3);
  3182. }
  3183. // FIXME: this will only happen for 32 bit getInt with high bit set
  3184. if(length < 0) {
  3185. throw new Error('Negative length: ' + length);
  3186. }
  3187. return length;
  3188. };
  3189. /**
  3190. * Parses an asn1 object from a byte buffer in DER format.
  3191. *
  3192. * @param bytes the byte buffer to parse from.
  3193. * @param [strict] true to be strict when checking value lengths, false to
  3194. * allow truncated values (default: true).
  3195. * @param [options] object with options or boolean strict flag
  3196. * [strict] true to be strict when checking value lengths, false to
  3197. * allow truncated values (default: true).
  3198. * [parseAllBytes] true to ensure all bytes are parsed
  3199. * (default: true)
  3200. * [decodeBitStrings] true to attempt to decode the content of
  3201. * BIT STRINGs (not OCTET STRINGs) using strict mode. Note that
  3202. * without schema support to understand the data context this can
  3203. * erroneously decode values that happen to be valid ASN.1. This
  3204. * flag will be deprecated or removed as soon as schema support is
  3205. * available. (default: true)
  3206. *
  3207. * @throws Will throw an error for various malformed input conditions.
  3208. *
  3209. * @return the parsed asn1 object.
  3210. */
  3211. asn1$6.fromDer = function(bytes, options) {
  3212. if(options === undefined) {
  3213. options = {
  3214. strict: true,
  3215. parseAllBytes: true,
  3216. decodeBitStrings: true
  3217. };
  3218. }
  3219. if(typeof options === 'boolean') {
  3220. options = {
  3221. strict: options,
  3222. parseAllBytes: true,
  3223. decodeBitStrings: true
  3224. };
  3225. }
  3226. if(!('strict' in options)) {
  3227. options.strict = true;
  3228. }
  3229. if(!('parseAllBytes' in options)) {
  3230. options.parseAllBytes = true;
  3231. }
  3232. if(!('decodeBitStrings' in options)) {
  3233. options.decodeBitStrings = true;
  3234. }
  3235. // wrap in buffer if needed
  3236. if(typeof bytes === 'string') {
  3237. bytes = forge$p.util.createBuffer(bytes);
  3238. }
  3239. var byteCount = bytes.length();
  3240. var value = _fromDer(bytes, bytes.length(), 0, options);
  3241. if(options.parseAllBytes && bytes.length() !== 0) {
  3242. var error = new Error('Unparsed DER bytes remain after ASN.1 parsing.');
  3243. error.byteCount = byteCount;
  3244. error.remaining = bytes.length();
  3245. throw error;
  3246. }
  3247. return value;
  3248. };
  3249. /**
  3250. * Internal function to parse an asn1 object from a byte buffer in DER format.
  3251. *
  3252. * @param bytes the byte buffer to parse from.
  3253. * @param remaining the number of bytes remaining for this chunk.
  3254. * @param depth the current parsing depth.
  3255. * @param options object with same options as fromDer().
  3256. *
  3257. * @return the parsed asn1 object.
  3258. */
  3259. function _fromDer(bytes, remaining, depth, options) {
  3260. // temporary storage for consumption calculations
  3261. var start;
  3262. // minimum length for ASN.1 DER structure is 2
  3263. _checkBufferLength(bytes, remaining, 2);
  3264. // get the first byte
  3265. var b1 = bytes.getByte();
  3266. // consumed one byte
  3267. remaining--;
  3268. // get the tag class
  3269. var tagClass = (b1 & 0xC0);
  3270. // get the type (bits 1-5)
  3271. var type = b1 & 0x1F;
  3272. // get the variable value length and adjust remaining bytes
  3273. start = bytes.length();
  3274. var length = _getValueLength(bytes, remaining);
  3275. remaining -= start - bytes.length();
  3276. // ensure there are enough bytes to get the value
  3277. if(length !== undefined && length > remaining) {
  3278. if(options.strict) {
  3279. var error = new Error('Too few bytes to read ASN.1 value.');
  3280. error.available = bytes.length();
  3281. error.remaining = remaining;
  3282. error.requested = length;
  3283. throw error;
  3284. }
  3285. // Note: be lenient with truncated values and use remaining state bytes
  3286. length = remaining;
  3287. }
  3288. // value storage
  3289. var value;
  3290. // possible BIT STRING contents storage
  3291. var bitStringContents;
  3292. // constructed flag is bit 6 (32 = 0x20) of the first byte
  3293. var constructed = ((b1 & 0x20) === 0x20);
  3294. if(constructed) {
  3295. // parse child asn1 objects from the value
  3296. value = [];
  3297. if(length === undefined) {
  3298. // asn1 object of indefinite length, read until end tag
  3299. for(;;) {
  3300. _checkBufferLength(bytes, remaining, 2);
  3301. if(bytes.bytes(2) === String.fromCharCode(0, 0)) {
  3302. bytes.getBytes(2);
  3303. remaining -= 2;
  3304. break;
  3305. }
  3306. start = bytes.length();
  3307. value.push(_fromDer(bytes, remaining, depth + 1, options));
  3308. remaining -= start - bytes.length();
  3309. }
  3310. } else {
  3311. // parsing asn1 object of definite length
  3312. while(length > 0) {
  3313. start = bytes.length();
  3314. value.push(_fromDer(bytes, length, depth + 1, options));
  3315. remaining -= start - bytes.length();
  3316. length -= start - bytes.length();
  3317. }
  3318. }
  3319. }
  3320. // if a BIT STRING, save the contents including padding
  3321. if(value === undefined && tagClass === asn1$6.Class.UNIVERSAL &&
  3322. type === asn1$6.Type.BITSTRING) {
  3323. bitStringContents = bytes.bytes(length);
  3324. }
  3325. // determine if a non-constructed value should be decoded as a composed
  3326. // value that contains other ASN.1 objects. BIT STRINGs (and OCTET STRINGs)
  3327. // can be used this way.
  3328. if(value === undefined && options.decodeBitStrings &&
  3329. tagClass === asn1$6.Class.UNIVERSAL &&
  3330. // FIXME: OCTET STRINGs not yet supported here
  3331. // .. other parts of forge expect to decode OCTET STRINGs manually
  3332. (type === asn1$6.Type.BITSTRING /*|| type === asn1.Type.OCTETSTRING*/) &&
  3333. length > 1) {
  3334. // save read position
  3335. var savedRead = bytes.read;
  3336. var savedRemaining = remaining;
  3337. var unused = 0;
  3338. if(type === asn1$6.Type.BITSTRING) {
  3339. /* The first octet gives the number of bits by which the length of the
  3340. bit string is less than the next multiple of eight (this is called
  3341. the "number of unused bits").
  3342. The second and following octets give the value of the bit string
  3343. converted to an octet string. */
  3344. _checkBufferLength(bytes, remaining, 1);
  3345. unused = bytes.getByte();
  3346. remaining--;
  3347. }
  3348. // if all bits are used, maybe the BIT/OCTET STRING holds ASN.1 objs
  3349. if(unused === 0) {
  3350. try {
  3351. // attempt to parse child asn1 object from the value
  3352. // (stored in array to signal composed value)
  3353. start = bytes.length();
  3354. var subOptions = {
  3355. // enforce strict mode to avoid parsing ASN.1 from plain data
  3356. strict: true,
  3357. decodeBitStrings: true
  3358. };
  3359. var composed = _fromDer(bytes, remaining, depth + 1, subOptions);
  3360. var used = start - bytes.length();
  3361. remaining -= used;
  3362. if(type == asn1$6.Type.BITSTRING) {
  3363. used++;
  3364. }
  3365. // if the data all decoded and the class indicates UNIVERSAL or
  3366. // CONTEXT_SPECIFIC then assume we've got an encapsulated ASN.1 object
  3367. var tc = composed.tagClass;
  3368. if(used === length &&
  3369. (tc === asn1$6.Class.UNIVERSAL || tc === asn1$6.Class.CONTEXT_SPECIFIC)) {
  3370. value = [composed];
  3371. }
  3372. } catch(ex) {
  3373. }
  3374. }
  3375. if(value === undefined) {
  3376. // restore read position
  3377. bytes.read = savedRead;
  3378. remaining = savedRemaining;
  3379. }
  3380. }
  3381. if(value === undefined) {
  3382. // asn1 not constructed or composed, get raw value
  3383. // TODO: do DER to OID conversion and vice-versa in .toDer?
  3384. if(length === undefined) {
  3385. if(options.strict) {
  3386. throw new Error('Non-constructed ASN.1 object of indefinite length.');
  3387. }
  3388. // be lenient and use remaining state bytes
  3389. length = remaining;
  3390. }
  3391. if(type === asn1$6.Type.BMPSTRING) {
  3392. value = '';
  3393. for(; length > 0; length -= 2) {
  3394. _checkBufferLength(bytes, remaining, 2);
  3395. value += String.fromCharCode(bytes.getInt16());
  3396. remaining -= 2;
  3397. }
  3398. } else {
  3399. value = bytes.getBytes(length);
  3400. remaining -= length;
  3401. }
  3402. }
  3403. // add BIT STRING contents if available
  3404. var asn1Options = bitStringContents === undefined ? null : {
  3405. bitStringContents: bitStringContents
  3406. };
  3407. // create and return asn1 object
  3408. return asn1$6.create(tagClass, type, constructed, value, asn1Options);
  3409. }
  3410. /**
  3411. * Converts the given asn1 object to a buffer of bytes in DER format.
  3412. *
  3413. * @param asn1 the asn1 object to convert to bytes.
  3414. *
  3415. * @return the buffer of bytes.
  3416. */
  3417. asn1$6.toDer = function(obj) {
  3418. var bytes = forge$p.util.createBuffer();
  3419. // build the first byte
  3420. var b1 = obj.tagClass | obj.type;
  3421. // for storing the ASN.1 value
  3422. var value = forge$p.util.createBuffer();
  3423. // use BIT STRING contents if available and data not changed
  3424. var useBitStringContents = false;
  3425. if('bitStringContents' in obj) {
  3426. useBitStringContents = true;
  3427. if(obj.original) {
  3428. useBitStringContents = asn1$6.equals(obj, obj.original);
  3429. }
  3430. }
  3431. if(useBitStringContents) {
  3432. value.putBytes(obj.bitStringContents);
  3433. } else if(obj.composed) {
  3434. // if composed, use each child asn1 object's DER bytes as value
  3435. // turn on 6th bit (0x20 = 32) to indicate asn1 is constructed
  3436. // from other asn1 objects
  3437. if(obj.constructed) {
  3438. b1 |= 0x20;
  3439. } else {
  3440. // type is a bit string, add unused bits of 0x00
  3441. value.putByte(0x00);
  3442. }
  3443. // add all of the child DER bytes together
  3444. for(var i = 0; i < obj.value.length; ++i) {
  3445. if(obj.value[i] !== undefined) {
  3446. value.putBuffer(asn1$6.toDer(obj.value[i]));
  3447. }
  3448. }
  3449. } else {
  3450. // use asn1.value directly
  3451. if(obj.type === asn1$6.Type.BMPSTRING) {
  3452. for(var i = 0; i < obj.value.length; ++i) {
  3453. value.putInt16(obj.value.charCodeAt(i));
  3454. }
  3455. } else {
  3456. // ensure integer is minimally-encoded
  3457. // TODO: should all leading bytes be stripped vs just one?
  3458. // .. ex '00 00 01' => '01'?
  3459. if(obj.type === asn1$6.Type.INTEGER &&
  3460. obj.value.length > 1 &&
  3461. // leading 0x00 for positive integer
  3462. ((obj.value.charCodeAt(0) === 0 &&
  3463. (obj.value.charCodeAt(1) & 0x80) === 0) ||
  3464. // leading 0xFF for negative integer
  3465. (obj.value.charCodeAt(0) === 0xFF &&
  3466. (obj.value.charCodeAt(1) & 0x80) === 0x80))) {
  3467. value.putBytes(obj.value.substr(1));
  3468. } else {
  3469. value.putBytes(obj.value);
  3470. }
  3471. }
  3472. }
  3473. // add tag byte
  3474. bytes.putByte(b1);
  3475. // use "short form" encoding
  3476. if(value.length() <= 127) {
  3477. // one byte describes the length
  3478. // bit 8 = 0 and bits 7-1 = length
  3479. bytes.putByte(value.length() & 0x7F);
  3480. } else {
  3481. // use "long form" encoding
  3482. // 2 to 127 bytes describe the length
  3483. // first byte: bit 8 = 1 and bits 7-1 = # of additional bytes
  3484. // other bytes: length in base 256, big-endian
  3485. var len = value.length();
  3486. var lenBytes = '';
  3487. do {
  3488. lenBytes += String.fromCharCode(len & 0xFF);
  3489. len = len >>> 8;
  3490. } while(len > 0);
  3491. // set first byte to # bytes used to store the length and turn on
  3492. // bit 8 to indicate long-form length is used
  3493. bytes.putByte(lenBytes.length | 0x80);
  3494. // concatenate length bytes in reverse since they were generated
  3495. // little endian and we need big endian
  3496. for(var i = lenBytes.length - 1; i >= 0; --i) {
  3497. bytes.putByte(lenBytes.charCodeAt(i));
  3498. }
  3499. }
  3500. // concatenate value bytes
  3501. bytes.putBuffer(value);
  3502. return bytes;
  3503. };
  3504. /**
  3505. * Converts an OID dot-separated string to a byte buffer. The byte buffer
  3506. * contains only the DER-encoded value, not any tag or length bytes.
  3507. *
  3508. * @param oid the OID dot-separated string.
  3509. *
  3510. * @return the byte buffer.
  3511. */
  3512. asn1$6.oidToDer = function(oid) {
  3513. // split OID into individual values
  3514. var values = oid.split('.');
  3515. var bytes = forge$p.util.createBuffer();
  3516. // first byte is 40 * value1 + value2
  3517. bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10));
  3518. // other bytes are each value in base 128 with 8th bit set except for
  3519. // the last byte for each value
  3520. var last, valueBytes, value, b;
  3521. for(var i = 2; i < values.length; ++i) {
  3522. // produce value bytes in reverse because we don't know how many
  3523. // bytes it will take to store the value
  3524. last = true;
  3525. valueBytes = [];
  3526. value = parseInt(values[i], 10);
  3527. do {
  3528. b = value & 0x7F;
  3529. value = value >>> 7;
  3530. // if value is not last, then turn on 8th bit
  3531. if(!last) {
  3532. b |= 0x80;
  3533. }
  3534. valueBytes.push(b);
  3535. last = false;
  3536. } while(value > 0);
  3537. // add value bytes in reverse (needs to be in big endian)
  3538. for(var n = valueBytes.length - 1; n >= 0; --n) {
  3539. bytes.putByte(valueBytes[n]);
  3540. }
  3541. }
  3542. return bytes;
  3543. };
  3544. /**
  3545. * Converts a DER-encoded byte buffer to an OID dot-separated string. The
  3546. * byte buffer should contain only the DER-encoded value, not any tag or
  3547. * length bytes.
  3548. *
  3549. * @param bytes the byte buffer.
  3550. *
  3551. * @return the OID dot-separated string.
  3552. */
  3553. asn1$6.derToOid = function(bytes) {
  3554. var oid;
  3555. // wrap in buffer if needed
  3556. if(typeof bytes === 'string') {
  3557. bytes = forge$p.util.createBuffer(bytes);
  3558. }
  3559. // first byte is 40 * value1 + value2
  3560. var b = bytes.getByte();
  3561. oid = Math.floor(b / 40) + '.' + (b % 40);
  3562. // other bytes are each value in base 128 with 8th bit set except for
  3563. // the last byte for each value
  3564. var value = 0;
  3565. while(bytes.length() > 0) {
  3566. b = bytes.getByte();
  3567. value = value << 7;
  3568. // not the last byte for the value
  3569. if(b & 0x80) {
  3570. value += b & 0x7F;
  3571. } else {
  3572. // last byte
  3573. oid += '.' + (value + b);
  3574. value = 0;
  3575. }
  3576. }
  3577. return oid;
  3578. };
  3579. /**
  3580. * Converts a UTCTime value to a date.
  3581. *
  3582. * Note: GeneralizedTime has 4 digits for the year and is used for X.509
  3583. * dates past 2049. Parsing that structure hasn't been implemented yet.
  3584. *
  3585. * @param utc the UTCTime value to convert.
  3586. *
  3587. * @return the date.
  3588. */
  3589. asn1$6.utcTimeToDate = function(utc) {
  3590. /* The following formats can be used:
  3591. YYMMDDhhmmZ
  3592. YYMMDDhhmm+hh'mm'
  3593. YYMMDDhhmm-hh'mm'
  3594. YYMMDDhhmmssZ
  3595. YYMMDDhhmmss+hh'mm'
  3596. YYMMDDhhmmss-hh'mm'
  3597. Where:
  3598. YY is the least significant two digits of the year
  3599. MM is the month (01 to 12)
  3600. DD is the day (01 to 31)
  3601. hh is the hour (00 to 23)
  3602. mm are the minutes (00 to 59)
  3603. ss are the seconds (00 to 59)
  3604. Z indicates that local time is GMT, + indicates that local time is
  3605. later than GMT, and - indicates that local time is earlier than GMT
  3606. hh' is the absolute value of the offset from GMT in hours
  3607. mm' is the absolute value of the offset from GMT in minutes */
  3608. var date = new Date();
  3609. // if YY >= 50 use 19xx, if YY < 50 use 20xx
  3610. var year = parseInt(utc.substr(0, 2), 10);
  3611. year = (year >= 50) ? 1900 + year : 2000 + year;
  3612. var MM = parseInt(utc.substr(2, 2), 10) - 1; // use 0-11 for month
  3613. var DD = parseInt(utc.substr(4, 2), 10);
  3614. var hh = parseInt(utc.substr(6, 2), 10);
  3615. var mm = parseInt(utc.substr(8, 2), 10);
  3616. var ss = 0;
  3617. // not just YYMMDDhhmmZ
  3618. if(utc.length > 11) {
  3619. // get character after minutes
  3620. var c = utc.charAt(10);
  3621. var end = 10;
  3622. // see if seconds are present
  3623. if(c !== '+' && c !== '-') {
  3624. // get seconds
  3625. ss = parseInt(utc.substr(10, 2), 10);
  3626. end += 2;
  3627. }
  3628. }
  3629. // update date
  3630. date.setUTCFullYear(year, MM, DD);
  3631. date.setUTCHours(hh, mm, ss, 0);
  3632. if(end) {
  3633. // get +/- after end of time
  3634. c = utc.charAt(end);
  3635. if(c === '+' || c === '-') {
  3636. // get hours+minutes offset
  3637. var hhoffset = parseInt(utc.substr(end + 1, 2), 10);
  3638. var mmoffset = parseInt(utc.substr(end + 4, 2), 10);
  3639. // calculate offset in milliseconds
  3640. var offset = hhoffset * 60 + mmoffset;
  3641. offset *= 60000;
  3642. // apply offset
  3643. if(c === '+') {
  3644. date.setTime(+date - offset);
  3645. } else {
  3646. date.setTime(+date + offset);
  3647. }
  3648. }
  3649. }
  3650. return date;
  3651. };
  3652. /**
  3653. * Converts a GeneralizedTime value to a date.
  3654. *
  3655. * @param gentime the GeneralizedTime value to convert.
  3656. *
  3657. * @return the date.
  3658. */
  3659. asn1$6.generalizedTimeToDate = function(gentime) {
  3660. /* The following formats can be used:
  3661. YYYYMMDDHHMMSS
  3662. YYYYMMDDHHMMSS.fff
  3663. YYYYMMDDHHMMSSZ
  3664. YYYYMMDDHHMMSS.fffZ
  3665. YYYYMMDDHHMMSS+hh'mm'
  3666. YYYYMMDDHHMMSS.fff+hh'mm'
  3667. YYYYMMDDHHMMSS-hh'mm'
  3668. YYYYMMDDHHMMSS.fff-hh'mm'
  3669. Where:
  3670. YYYY is the year
  3671. MM is the month (01 to 12)
  3672. DD is the day (01 to 31)
  3673. hh is the hour (00 to 23)
  3674. mm are the minutes (00 to 59)
  3675. ss are the seconds (00 to 59)
  3676. .fff is the second fraction, accurate to three decimal places
  3677. Z indicates that local time is GMT, + indicates that local time is
  3678. later than GMT, and - indicates that local time is earlier than GMT
  3679. hh' is the absolute value of the offset from GMT in hours
  3680. mm' is the absolute value of the offset from GMT in minutes */
  3681. var date = new Date();
  3682. var YYYY = parseInt(gentime.substr(0, 4), 10);
  3683. var MM = parseInt(gentime.substr(4, 2), 10) - 1; // use 0-11 for month
  3684. var DD = parseInt(gentime.substr(6, 2), 10);
  3685. var hh = parseInt(gentime.substr(8, 2), 10);
  3686. var mm = parseInt(gentime.substr(10, 2), 10);
  3687. var ss = parseInt(gentime.substr(12, 2), 10);
  3688. var fff = 0;
  3689. var offset = 0;
  3690. var isUTC = false;
  3691. if(gentime.charAt(gentime.length - 1) === 'Z') {
  3692. isUTC = true;
  3693. }
  3694. var end = gentime.length - 5, c = gentime.charAt(end);
  3695. if(c === '+' || c === '-') {
  3696. // get hours+minutes offset
  3697. var hhoffset = parseInt(gentime.substr(end + 1, 2), 10);
  3698. var mmoffset = parseInt(gentime.substr(end + 4, 2), 10);
  3699. // calculate offset in milliseconds
  3700. offset = hhoffset * 60 + mmoffset;
  3701. offset *= 60000;
  3702. // apply offset
  3703. if(c === '+') {
  3704. offset *= -1;
  3705. }
  3706. isUTC = true;
  3707. }
  3708. // check for second fraction
  3709. if(gentime.charAt(14) === '.') {
  3710. fff = parseFloat(gentime.substr(14), 10) * 1000;
  3711. }
  3712. if(isUTC) {
  3713. date.setUTCFullYear(YYYY, MM, DD);
  3714. date.setUTCHours(hh, mm, ss, fff);
  3715. // apply offset
  3716. date.setTime(+date + offset);
  3717. } else {
  3718. date.setFullYear(YYYY, MM, DD);
  3719. date.setHours(hh, mm, ss, fff);
  3720. }
  3721. return date;
  3722. };
  3723. /**
  3724. * Converts a date to a UTCTime value.
  3725. *
  3726. * Note: GeneralizedTime has 4 digits for the year and is used for X.509
  3727. * dates past 2049. Converting to a GeneralizedTime hasn't been
  3728. * implemented yet.
  3729. *
  3730. * @param date the date to convert.
  3731. *
  3732. * @return the UTCTime value.
  3733. */
  3734. asn1$6.dateToUtcTime = function(date) {
  3735. // TODO: validate; currently assumes proper format
  3736. if(typeof date === 'string') {
  3737. return date;
  3738. }
  3739. var rval = '';
  3740. // create format YYMMDDhhmmssZ
  3741. var format = [];
  3742. format.push(('' + date.getUTCFullYear()).substr(2));
  3743. format.push('' + (date.getUTCMonth() + 1));
  3744. format.push('' + date.getUTCDate());
  3745. format.push('' + date.getUTCHours());
  3746. format.push('' + date.getUTCMinutes());
  3747. format.push('' + date.getUTCSeconds());
  3748. // ensure 2 digits are used for each format entry
  3749. for(var i = 0; i < format.length; ++i) {
  3750. if(format[i].length < 2) {
  3751. rval += '0';
  3752. }
  3753. rval += format[i];
  3754. }
  3755. rval += 'Z';
  3756. return rval;
  3757. };
  3758. /**
  3759. * Converts a date to a GeneralizedTime value.
  3760. *
  3761. * @param date the date to convert.
  3762. *
  3763. * @return the GeneralizedTime value as a string.
  3764. */
  3765. asn1$6.dateToGeneralizedTime = function(date) {
  3766. // TODO: validate; currently assumes proper format
  3767. if(typeof date === 'string') {
  3768. return date;
  3769. }
  3770. var rval = '';
  3771. // create format YYYYMMDDHHMMSSZ
  3772. var format = [];
  3773. format.push('' + date.getUTCFullYear());
  3774. format.push('' + (date.getUTCMonth() + 1));
  3775. format.push('' + date.getUTCDate());
  3776. format.push('' + date.getUTCHours());
  3777. format.push('' + date.getUTCMinutes());
  3778. format.push('' + date.getUTCSeconds());
  3779. // ensure 2 digits are used for each format entry
  3780. for(var i = 0; i < format.length; ++i) {
  3781. if(format[i].length < 2) {
  3782. rval += '0';
  3783. }
  3784. rval += format[i];
  3785. }
  3786. rval += 'Z';
  3787. return rval;
  3788. };
  3789. /**
  3790. * Converts a javascript integer to a DER-encoded byte buffer to be used
  3791. * as the value for an INTEGER type.
  3792. *
  3793. * @param x the integer.
  3794. *
  3795. * @return the byte buffer.
  3796. */
  3797. asn1$6.integerToDer = function(x) {
  3798. var rval = forge$p.util.createBuffer();
  3799. if(x >= -0x80 && x < 0x80) {
  3800. return rval.putSignedInt(x, 8);
  3801. }
  3802. if(x >= -0x8000 && x < 0x8000) {
  3803. return rval.putSignedInt(x, 16);
  3804. }
  3805. if(x >= -0x800000 && x < 0x800000) {
  3806. return rval.putSignedInt(x, 24);
  3807. }
  3808. if(x >= -0x80000000 && x < 0x80000000) {
  3809. return rval.putSignedInt(x, 32);
  3810. }
  3811. var error = new Error('Integer too large; max is 32-bits.');
  3812. error.integer = x;
  3813. throw error;
  3814. };
  3815. /**
  3816. * Converts a DER-encoded byte buffer to a javascript integer. This is
  3817. * typically used to decode the value of an INTEGER type.
  3818. *
  3819. * @param bytes the byte buffer.
  3820. *
  3821. * @return the integer.
  3822. */
  3823. asn1$6.derToInteger = function(bytes) {
  3824. // wrap in buffer if needed
  3825. if(typeof bytes === 'string') {
  3826. bytes = forge$p.util.createBuffer(bytes);
  3827. }
  3828. var n = bytes.length() * 8;
  3829. if(n > 32) {
  3830. throw new Error('Integer too large; max is 32-bits.');
  3831. }
  3832. return bytes.getSignedInt(n);
  3833. };
  3834. /**
  3835. * Validates that the given ASN.1 object is at least a super set of the
  3836. * given ASN.1 structure. Only tag classes and types are checked. An
  3837. * optional map may also be provided to capture ASN.1 values while the
  3838. * structure is checked.
  3839. *
  3840. * To capture an ASN.1 value, set an object in the validator's 'capture'
  3841. * parameter to the key to use in the capture map. To capture the full
  3842. * ASN.1 object, specify 'captureAsn1'. To capture BIT STRING bytes, including
  3843. * the leading unused bits counter byte, specify 'captureBitStringContents'.
  3844. * To capture BIT STRING bytes, without the leading unused bits counter byte,
  3845. * specify 'captureBitStringValue'.
  3846. *
  3847. * Objects in the validator may set a field 'optional' to true to indicate
  3848. * that it isn't necessary to pass validation.
  3849. *
  3850. * @param obj the ASN.1 object to validate.
  3851. * @param v the ASN.1 structure validator.
  3852. * @param capture an optional map to capture values in.
  3853. * @param errors an optional array for storing validation errors.
  3854. *
  3855. * @return true on success, false on failure.
  3856. */
  3857. asn1$6.validate = function(obj, v, capture, errors) {
  3858. var rval = false;
  3859. // ensure tag class and type are the same if specified
  3860. if((obj.tagClass === v.tagClass || typeof(v.tagClass) === 'undefined') &&
  3861. (obj.type === v.type || typeof(v.type) === 'undefined')) {
  3862. // ensure constructed flag is the same if specified
  3863. if(obj.constructed === v.constructed ||
  3864. typeof(v.constructed) === 'undefined') {
  3865. rval = true;
  3866. // handle sub values
  3867. if(v.value && forge$p.util.isArray(v.value)) {
  3868. var j = 0;
  3869. for(var i = 0; rval && i < v.value.length; ++i) {
  3870. rval = v.value[i].optional || false;
  3871. if(obj.value[j]) {
  3872. rval = asn1$6.validate(obj.value[j], v.value[i], capture, errors);
  3873. if(rval) {
  3874. ++j;
  3875. } else if(v.value[i].optional) {
  3876. rval = true;
  3877. }
  3878. }
  3879. if(!rval && errors) {
  3880. errors.push(
  3881. '[' + v.name + '] ' +
  3882. 'Tag class "' + v.tagClass + '", type "' +
  3883. v.type + '" expected value length "' +
  3884. v.value.length + '", got "' +
  3885. obj.value.length + '"');
  3886. }
  3887. }
  3888. }
  3889. if(rval && capture) {
  3890. if(v.capture) {
  3891. capture[v.capture] = obj.value;
  3892. }
  3893. if(v.captureAsn1) {
  3894. capture[v.captureAsn1] = obj;
  3895. }
  3896. if(v.captureBitStringContents && 'bitStringContents' in obj) {
  3897. capture[v.captureBitStringContents] = obj.bitStringContents;
  3898. }
  3899. if(v.captureBitStringValue && 'bitStringContents' in obj) {
  3900. if(obj.bitStringContents.length < 2) {
  3901. capture[v.captureBitStringValue] = '';
  3902. } else {
  3903. // FIXME: support unused bits with data shifting
  3904. var unused = obj.bitStringContents.charCodeAt(0);
  3905. if(unused !== 0) {
  3906. throw new Error(
  3907. 'captureBitStringValue only supported for zero unused bits');
  3908. }
  3909. capture[v.captureBitStringValue] = obj.bitStringContents.slice(1);
  3910. }
  3911. }
  3912. }
  3913. } else if(errors) {
  3914. errors.push(
  3915. '[' + v.name + '] ' +
  3916. 'Expected constructed "' + v.constructed + '", got "' +
  3917. obj.constructed + '"');
  3918. }
  3919. } else if(errors) {
  3920. if(obj.tagClass !== v.tagClass) {
  3921. errors.push(
  3922. '[' + v.name + '] ' +
  3923. 'Expected tag class "' + v.tagClass + '", got "' +
  3924. obj.tagClass + '"');
  3925. }
  3926. if(obj.type !== v.type) {
  3927. errors.push(
  3928. '[' + v.name + '] ' +
  3929. 'Expected type "' + v.type + '", got "' + obj.type + '"');
  3930. }
  3931. }
  3932. return rval;
  3933. };
  3934. // regex for testing for non-latin characters
  3935. var _nonLatinRegex = /[^\\u0000-\\u00ff]/;
  3936. /**
  3937. * Pretty prints an ASN.1 object to a string.
  3938. *
  3939. * @param obj the object to write out.
  3940. * @param level the level in the tree.
  3941. * @param indentation the indentation to use.
  3942. *
  3943. * @return the string.
  3944. */
  3945. asn1$6.prettyPrint = function(obj, level, indentation) {
  3946. var rval = '';
  3947. // set default level and indentation
  3948. level = level || 0;
  3949. indentation = indentation || 2;
  3950. // start new line for deep levels
  3951. if(level > 0) {
  3952. rval += '\n';
  3953. }
  3954. // create indent
  3955. var indent = '';
  3956. for(var i = 0; i < level * indentation; ++i) {
  3957. indent += ' ';
  3958. }
  3959. // print class:type
  3960. rval += indent + 'Tag: ';
  3961. switch(obj.tagClass) {
  3962. case asn1$6.Class.UNIVERSAL:
  3963. rval += 'Universal:';
  3964. break;
  3965. case asn1$6.Class.APPLICATION:
  3966. rval += 'Application:';
  3967. break;
  3968. case asn1$6.Class.CONTEXT_SPECIFIC:
  3969. rval += 'Context-Specific:';
  3970. break;
  3971. case asn1$6.Class.PRIVATE:
  3972. rval += 'Private:';
  3973. break;
  3974. }
  3975. if(obj.tagClass === asn1$6.Class.UNIVERSAL) {
  3976. rval += obj.type;
  3977. // known types
  3978. switch(obj.type) {
  3979. case asn1$6.Type.NONE:
  3980. rval += ' (None)';
  3981. break;
  3982. case asn1$6.Type.BOOLEAN:
  3983. rval += ' (Boolean)';
  3984. break;
  3985. case asn1$6.Type.INTEGER:
  3986. rval += ' (Integer)';
  3987. break;
  3988. case asn1$6.Type.BITSTRING:
  3989. rval += ' (Bit string)';
  3990. break;
  3991. case asn1$6.Type.OCTETSTRING:
  3992. rval += ' (Octet string)';
  3993. break;
  3994. case asn1$6.Type.NULL:
  3995. rval += ' (Null)';
  3996. break;
  3997. case asn1$6.Type.OID:
  3998. rval += ' (Object Identifier)';
  3999. break;
  4000. case asn1$6.Type.ODESC:
  4001. rval += ' (Object Descriptor)';
  4002. break;
  4003. case asn1$6.Type.EXTERNAL:
  4004. rval += ' (External or Instance of)';
  4005. break;
  4006. case asn1$6.Type.REAL:
  4007. rval += ' (Real)';
  4008. break;
  4009. case asn1$6.Type.ENUMERATED:
  4010. rval += ' (Enumerated)';
  4011. break;
  4012. case asn1$6.Type.EMBEDDED:
  4013. rval += ' (Embedded PDV)';
  4014. break;
  4015. case asn1$6.Type.UTF8:
  4016. rval += ' (UTF8)';
  4017. break;
  4018. case asn1$6.Type.ROID:
  4019. rval += ' (Relative Object Identifier)';
  4020. break;
  4021. case asn1$6.Type.SEQUENCE:
  4022. rval += ' (Sequence)';
  4023. break;
  4024. case asn1$6.Type.SET:
  4025. rval += ' (Set)';
  4026. break;
  4027. case asn1$6.Type.PRINTABLESTRING:
  4028. rval += ' (Printable String)';
  4029. break;
  4030. case asn1$6.Type.IA5String:
  4031. rval += ' (IA5String (ASCII))';
  4032. break;
  4033. case asn1$6.Type.UTCTIME:
  4034. rval += ' (UTC time)';
  4035. break;
  4036. case asn1$6.Type.GENERALIZEDTIME:
  4037. rval += ' (Generalized time)';
  4038. break;
  4039. case asn1$6.Type.BMPSTRING:
  4040. rval += ' (BMP String)';
  4041. break;
  4042. }
  4043. } else {
  4044. rval += obj.type;
  4045. }
  4046. rval += '\n';
  4047. rval += indent + 'Constructed: ' + obj.constructed + '\n';
  4048. if(obj.composed) {
  4049. var subvalues = 0;
  4050. var sub = '';
  4051. for(var i = 0; i < obj.value.length; ++i) {
  4052. if(obj.value[i] !== undefined) {
  4053. subvalues += 1;
  4054. sub += asn1$6.prettyPrint(obj.value[i], level + 1, indentation);
  4055. if((i + 1) < obj.value.length) {
  4056. sub += ',';
  4057. }
  4058. }
  4059. }
  4060. rval += indent + 'Sub values: ' + subvalues + sub;
  4061. } else {
  4062. rval += indent + 'Value: ';
  4063. if(obj.type === asn1$6.Type.OID) {
  4064. var oid = asn1$6.derToOid(obj.value);
  4065. rval += oid;
  4066. if(forge$p.pki && forge$p.pki.oids) {
  4067. if(oid in forge$p.pki.oids) {
  4068. rval += ' (' + forge$p.pki.oids[oid] + ') ';
  4069. }
  4070. }
  4071. }
  4072. if(obj.type === asn1$6.Type.INTEGER) {
  4073. try {
  4074. rval += asn1$6.derToInteger(obj.value);
  4075. } catch(ex) {
  4076. rval += '0x' + forge$p.util.bytesToHex(obj.value);
  4077. }
  4078. } else if(obj.type === asn1$6.Type.BITSTRING) {
  4079. // TODO: shift bits as needed to display without padding
  4080. if(obj.value.length > 1) {
  4081. // remove unused bits field
  4082. rval += '0x' + forge$p.util.bytesToHex(obj.value.slice(1));
  4083. } else {
  4084. rval += '(none)';
  4085. }
  4086. // show unused bit count
  4087. if(obj.value.length > 0) {
  4088. var unused = obj.value.charCodeAt(0);
  4089. if(unused == 1) {
  4090. rval += ' (1 unused bit shown)';
  4091. } else if(unused > 1) {
  4092. rval += ' (' + unused + ' unused bits shown)';
  4093. }
  4094. }
  4095. } else if(obj.type === asn1$6.Type.OCTETSTRING) {
  4096. if(!_nonLatinRegex.test(obj.value)) {
  4097. rval += '(' + obj.value + ') ';
  4098. }
  4099. rval += '0x' + forge$p.util.bytesToHex(obj.value);
  4100. } else if(obj.type === asn1$6.Type.UTF8) {
  4101. try {
  4102. rval += forge$p.util.decodeUtf8(obj.value);
  4103. } catch(e) {
  4104. if(e.message === 'URI malformed') {
  4105. rval +=
  4106. '0x' + forge$p.util.bytesToHex(obj.value) + ' (malformed UTF8)';
  4107. } else {
  4108. throw e;
  4109. }
  4110. }
  4111. } else if(obj.type === asn1$6.Type.PRINTABLESTRING ||
  4112. obj.type === asn1$6.Type.IA5String) {
  4113. rval += obj.value;
  4114. } else if(_nonLatinRegex.test(obj.value)) {
  4115. rval += '0x' + forge$p.util.bytesToHex(obj.value);
  4116. } else if(obj.value.length === 0) {
  4117. rval += '[null]';
  4118. } else {
  4119. rval += obj.value;
  4120. }
  4121. }
  4122. return rval;
  4123. };
  4124. /**
  4125. * Cipher base API.
  4126. *
  4127. * @author Dave Longley
  4128. *
  4129. * Copyright (c) 2010-2014 Digital Bazaar, Inc.
  4130. */
  4131. var forge$o = forge$s;
  4132. forge$o.cipher = forge$o.cipher || {};
  4133. // registered algorithms
  4134. forge$o.cipher.algorithms = forge$o.cipher.algorithms || {};
  4135. /**
  4136. * Creates a cipher object that can be used to encrypt data using the given
  4137. * algorithm and key. The algorithm may be provided as a string value for a
  4138. * previously registered algorithm or it may be given as a cipher algorithm
  4139. * API object.
  4140. *
  4141. * @param algorithm the algorithm to use, either a string or an algorithm API
  4142. * object.
  4143. * @param key the key to use, as a binary-encoded string of bytes or a
  4144. * byte buffer.
  4145. *
  4146. * @return the cipher.
  4147. */
  4148. forge$o.cipher.createCipher = function(algorithm, key) {
  4149. var api = algorithm;
  4150. if(typeof api === 'string') {
  4151. api = forge$o.cipher.getAlgorithm(api);
  4152. if(api) {
  4153. api = api();
  4154. }
  4155. }
  4156. if(!api) {
  4157. throw new Error('Unsupported algorithm: ' + algorithm);
  4158. }
  4159. // assume block cipher
  4160. return new forge$o.cipher.BlockCipher({
  4161. algorithm: api,
  4162. key: key,
  4163. decrypt: false
  4164. });
  4165. };
  4166. /**
  4167. * Creates a decipher object that can be used to decrypt data using the given
  4168. * algorithm and key. The algorithm may be provided as a string value for a
  4169. * previously registered algorithm or it may be given as a cipher algorithm
  4170. * API object.
  4171. *
  4172. * @param algorithm the algorithm to use, either a string or an algorithm API
  4173. * object.
  4174. * @param key the key to use, as a binary-encoded string of bytes or a
  4175. * byte buffer.
  4176. *
  4177. * @return the cipher.
  4178. */
  4179. forge$o.cipher.createDecipher = function(algorithm, key) {
  4180. var api = algorithm;
  4181. if(typeof api === 'string') {
  4182. api = forge$o.cipher.getAlgorithm(api);
  4183. if(api) {
  4184. api = api();
  4185. }
  4186. }
  4187. if(!api) {
  4188. throw new Error('Unsupported algorithm: ' + algorithm);
  4189. }
  4190. // assume block cipher
  4191. return new forge$o.cipher.BlockCipher({
  4192. algorithm: api,
  4193. key: key,
  4194. decrypt: true
  4195. });
  4196. };
  4197. /**
  4198. * Registers an algorithm by name. If the name was already registered, the
  4199. * algorithm API object will be overwritten.
  4200. *
  4201. * @param name the name of the algorithm.
  4202. * @param algorithm the algorithm API object.
  4203. */
  4204. forge$o.cipher.registerAlgorithm = function(name, algorithm) {
  4205. name = name.toUpperCase();
  4206. forge$o.cipher.algorithms[name] = algorithm;
  4207. };
  4208. /**
  4209. * Gets a registered algorithm by name.
  4210. *
  4211. * @param name the name of the algorithm.
  4212. *
  4213. * @return the algorithm, if found, null if not.
  4214. */
  4215. forge$o.cipher.getAlgorithm = function(name) {
  4216. name = name.toUpperCase();
  4217. if(name in forge$o.cipher.algorithms) {
  4218. return forge$o.cipher.algorithms[name];
  4219. }
  4220. return null;
  4221. };
  4222. var BlockCipher = forge$o.cipher.BlockCipher = function(options) {
  4223. this.algorithm = options.algorithm;
  4224. this.mode = this.algorithm.mode;
  4225. this.blockSize = this.mode.blockSize;
  4226. this._finish = false;
  4227. this._input = null;
  4228. this.output = null;
  4229. this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt;
  4230. this._decrypt = options.decrypt;
  4231. this.algorithm.initialize(options);
  4232. };
  4233. /**
  4234. * Starts or restarts the encryption or decryption process, whichever
  4235. * was previously configured.
  4236. *
  4237. * For non-GCM mode, the IV may be a binary-encoded string of bytes, an array
  4238. * of bytes, a byte buffer, or an array of 32-bit integers. If the IV is in
  4239. * bytes, then it must be Nb (16) bytes in length. If the IV is given in as
  4240. * 32-bit integers, then it must be 4 integers long.
  4241. *
  4242. * Note: an IV is not required or used in ECB mode.
  4243. *
  4244. * For GCM-mode, the IV must be given as a binary-encoded string of bytes or
  4245. * a byte buffer. The number of bytes should be 12 (96 bits) as recommended
  4246. * by NIST SP-800-38D but another length may be given.
  4247. *
  4248. * @param options the options to use:
  4249. * iv the initialization vector to use as a binary-encoded string of
  4250. * bytes, null to reuse the last ciphered block from a previous
  4251. * update() (this "residue" method is for legacy support only).
  4252. * additionalData additional authentication data as a binary-encoded
  4253. * string of bytes, for 'GCM' mode, (default: none).
  4254. * tagLength desired length of authentication tag, in bits, for
  4255. * 'GCM' mode (0-128, default: 128).
  4256. * tag the authentication tag to check if decrypting, as a
  4257. * binary-encoded string of bytes.
  4258. * output the output the buffer to write to, null to create one.
  4259. */
  4260. BlockCipher.prototype.start = function(options) {
  4261. options = options || {};
  4262. var opts = {};
  4263. for(var key in options) {
  4264. opts[key] = options[key];
  4265. }
  4266. opts.decrypt = this._decrypt;
  4267. this._finish = false;
  4268. this._input = forge$o.util.createBuffer();
  4269. this.output = options.output || forge$o.util.createBuffer();
  4270. this.mode.start(opts);
  4271. };
  4272. /**
  4273. * Updates the next block according to the cipher mode.
  4274. *
  4275. * @param input the buffer to read from.
  4276. */
  4277. BlockCipher.prototype.update = function(input) {
  4278. if(input) {
  4279. // input given, so empty it into the input buffer
  4280. this._input.putBuffer(input);
  4281. }
  4282. // do cipher operation until it needs more input and not finished
  4283. while(!this._op.call(this.mode, this._input, this.output, this._finish) &&
  4284. !this._finish) {}
  4285. // free consumed memory from input buffer
  4286. this._input.compact();
  4287. };
  4288. /**
  4289. * Finishes encrypting or decrypting.
  4290. *
  4291. * @param pad a padding function to use in CBC mode, null for default,
  4292. * signature(blockSize, buffer, decrypt).
  4293. *
  4294. * @return true if successful, false on error.
  4295. */
  4296. BlockCipher.prototype.finish = function(pad) {
  4297. // backwards-compatibility w/deprecated padding API
  4298. // Note: will overwrite padding functions even after another start() call
  4299. if(pad && (this.mode.name === 'ECB' || this.mode.name === 'CBC')) {
  4300. this.mode.pad = function(input) {
  4301. return pad(this.blockSize, input, false);
  4302. };
  4303. this.mode.unpad = function(output) {
  4304. return pad(this.blockSize, output, true);
  4305. };
  4306. }
  4307. // build options for padding and afterFinish functions
  4308. var options = {};
  4309. options.decrypt = this._decrypt;
  4310. // get # of bytes that won't fill a block
  4311. options.overflow = this._input.length() % this.blockSize;
  4312. if(!this._decrypt && this.mode.pad) {
  4313. if(!this.mode.pad(this._input, options)) {
  4314. return false;
  4315. }
  4316. }
  4317. // do final update
  4318. this._finish = true;
  4319. this.update();
  4320. if(this._decrypt && this.mode.unpad) {
  4321. if(!this.mode.unpad(this.output, options)) {
  4322. return false;
  4323. }
  4324. }
  4325. if(this.mode.afterFinish) {
  4326. if(!this.mode.afterFinish(this.output, options)) {
  4327. return false;
  4328. }
  4329. }
  4330. return true;
  4331. };
  4332. /**
  4333. * Supported cipher modes.
  4334. *
  4335. * @author Dave Longley
  4336. *
  4337. * Copyright (c) 2010-2014 Digital Bazaar, Inc.
  4338. */
  4339. var forge$n = forge$s;
  4340. forge$n.cipher = forge$n.cipher || {};
  4341. // supported cipher modes
  4342. var modes = forge$n.cipher.modes = forge$n.cipher.modes || {};
  4343. /** Electronic codebook (ECB) (Don't use this; it's not secure) **/
  4344. modes.ecb = function(options) {
  4345. options = options || {};
  4346. this.name = 'ECB';
  4347. this.cipher = options.cipher;
  4348. this.blockSize = options.blockSize || 16;
  4349. this._ints = this.blockSize / 4;
  4350. this._inBlock = new Array(this._ints);
  4351. this._outBlock = new Array(this._ints);
  4352. };
  4353. modes.ecb.prototype.start = function(options) {};
  4354. modes.ecb.prototype.encrypt = function(input, output, finish) {
  4355. // not enough input to encrypt
  4356. if(input.length() < this.blockSize && !(finish && input.length() > 0)) {
  4357. return true;
  4358. }
  4359. // get next block
  4360. for(var i = 0; i < this._ints; ++i) {
  4361. this._inBlock[i] = input.getInt32();
  4362. }
  4363. // encrypt block
  4364. this.cipher.encrypt(this._inBlock, this._outBlock);
  4365. // write output
  4366. for(var i = 0; i < this._ints; ++i) {
  4367. output.putInt32(this._outBlock[i]);
  4368. }
  4369. };
  4370. modes.ecb.prototype.decrypt = function(input, output, finish) {
  4371. // not enough input to decrypt
  4372. if(input.length() < this.blockSize && !(finish && input.length() > 0)) {
  4373. return true;
  4374. }
  4375. // get next block
  4376. for(var i = 0; i < this._ints; ++i) {
  4377. this._inBlock[i] = input.getInt32();
  4378. }
  4379. // decrypt block
  4380. this.cipher.decrypt(this._inBlock, this._outBlock);
  4381. // write output
  4382. for(var i = 0; i < this._ints; ++i) {
  4383. output.putInt32(this._outBlock[i]);
  4384. }
  4385. };
  4386. modes.ecb.prototype.pad = function(input, options) {
  4387. // add PKCS#7 padding to block (each pad byte is the
  4388. // value of the number of pad bytes)
  4389. var padding = (input.length() === this.blockSize ?
  4390. this.blockSize : (this.blockSize - input.length()));
  4391. input.fillWithByte(padding, padding);
  4392. return true;
  4393. };
  4394. modes.ecb.prototype.unpad = function(output, options) {
  4395. // check for error: input data not a multiple of blockSize
  4396. if(options.overflow > 0) {
  4397. return false;
  4398. }
  4399. // ensure padding byte count is valid
  4400. var len = output.length();
  4401. var count = output.at(len - 1);
  4402. if(count > (this.blockSize << 2)) {
  4403. return false;
  4404. }
  4405. // trim off padding bytes
  4406. output.truncate(count);
  4407. return true;
  4408. };
  4409. /** Cipher-block Chaining (CBC) **/
  4410. modes.cbc = function(options) {
  4411. options = options || {};
  4412. this.name = 'CBC';
  4413. this.cipher = options.cipher;
  4414. this.blockSize = options.blockSize || 16;
  4415. this._ints = this.blockSize / 4;
  4416. this._inBlock = new Array(this._ints);
  4417. this._outBlock = new Array(this._ints);
  4418. };
  4419. modes.cbc.prototype.start = function(options) {
  4420. // Note: legacy support for using IV residue (has security flaws)
  4421. // if IV is null, reuse block from previous processing
  4422. if(options.iv === null) {
  4423. // must have a previous block
  4424. if(!this._prev) {
  4425. throw new Error('Invalid IV parameter.');
  4426. }
  4427. this._iv = this._prev.slice(0);
  4428. } else if(!('iv' in options)) {
  4429. throw new Error('Invalid IV parameter.');
  4430. } else {
  4431. // save IV as "previous" block
  4432. this._iv = transformIV(options.iv, this.blockSize);
  4433. this._prev = this._iv.slice(0);
  4434. }
  4435. };
  4436. modes.cbc.prototype.encrypt = function(input, output, finish) {
  4437. // not enough input to encrypt
  4438. if(input.length() < this.blockSize && !(finish && input.length() > 0)) {
  4439. return true;
  4440. }
  4441. // get next block
  4442. // CBC XOR's IV (or previous block) with plaintext
  4443. for(var i = 0; i < this._ints; ++i) {
  4444. this._inBlock[i] = this._prev[i] ^ input.getInt32();
  4445. }
  4446. // encrypt block
  4447. this.cipher.encrypt(this._inBlock, this._outBlock);
  4448. // write output, save previous block
  4449. for(var i = 0; i < this._ints; ++i) {
  4450. output.putInt32(this._outBlock[i]);
  4451. }
  4452. this._prev = this._outBlock;
  4453. };
  4454. modes.cbc.prototype.decrypt = function(input, output, finish) {
  4455. // not enough input to decrypt
  4456. if(input.length() < this.blockSize && !(finish && input.length() > 0)) {
  4457. return true;
  4458. }
  4459. // get next block
  4460. for(var i = 0; i < this._ints; ++i) {
  4461. this._inBlock[i] = input.getInt32();
  4462. }
  4463. // decrypt block
  4464. this.cipher.decrypt(this._inBlock, this._outBlock);
  4465. // write output, save previous ciphered block
  4466. // CBC XOR's IV (or previous block) with ciphertext
  4467. for(var i = 0; i < this._ints; ++i) {
  4468. output.putInt32(this._prev[i] ^ this._outBlock[i]);
  4469. }
  4470. this._prev = this._inBlock.slice(0);
  4471. };
  4472. modes.cbc.prototype.pad = function(input, options) {
  4473. // add PKCS#7 padding to block (each pad byte is the
  4474. // value of the number of pad bytes)
  4475. var padding = (input.length() === this.blockSize ?
  4476. this.blockSize : (this.blockSize - input.length()));
  4477. input.fillWithByte(padding, padding);
  4478. return true;
  4479. };
  4480. modes.cbc.prototype.unpad = function(output, options) {
  4481. // check for error: input data not a multiple of blockSize
  4482. if(options.overflow > 0) {
  4483. return false;
  4484. }
  4485. // ensure padding byte count is valid
  4486. var len = output.length();
  4487. var count = output.at(len - 1);
  4488. if(count > (this.blockSize << 2)) {
  4489. return false;
  4490. }
  4491. // trim off padding bytes
  4492. output.truncate(count);
  4493. return true;
  4494. };
  4495. /** Cipher feedback (CFB) **/
  4496. modes.cfb = function(options) {
  4497. options = options || {};
  4498. this.name = 'CFB';
  4499. this.cipher = options.cipher;
  4500. this.blockSize = options.blockSize || 16;
  4501. this._ints = this.blockSize / 4;
  4502. this._inBlock = null;
  4503. this._outBlock = new Array(this._ints);
  4504. this._partialBlock = new Array(this._ints);
  4505. this._partialOutput = forge$n.util.createBuffer();
  4506. this._partialBytes = 0;
  4507. };
  4508. modes.cfb.prototype.start = function(options) {
  4509. if(!('iv' in options)) {
  4510. throw new Error('Invalid IV parameter.');
  4511. }
  4512. // use IV as first input
  4513. this._iv = transformIV(options.iv, this.blockSize);
  4514. this._inBlock = this._iv.slice(0);
  4515. this._partialBytes = 0;
  4516. };
  4517. modes.cfb.prototype.encrypt = function(input, output, finish) {
  4518. // not enough input to encrypt
  4519. var inputLength = input.length();
  4520. if(inputLength === 0) {
  4521. return true;
  4522. }
  4523. // encrypt block
  4524. this.cipher.encrypt(this._inBlock, this._outBlock);
  4525. // handle full block
  4526. if(this._partialBytes === 0 && inputLength >= this.blockSize) {
  4527. // XOR input with output, write input as output
  4528. for(var i = 0; i < this._ints; ++i) {
  4529. this._inBlock[i] = input.getInt32() ^ this._outBlock[i];
  4530. output.putInt32(this._inBlock[i]);
  4531. }
  4532. return;
  4533. }
  4534. // handle partial block
  4535. var partialBytes = (this.blockSize - inputLength) % this.blockSize;
  4536. if(partialBytes > 0) {
  4537. partialBytes = this.blockSize - partialBytes;
  4538. }
  4539. // XOR input with output, write input as partial output
  4540. this._partialOutput.clear();
  4541. for(var i = 0; i < this._ints; ++i) {
  4542. this._partialBlock[i] = input.getInt32() ^ this._outBlock[i];
  4543. this._partialOutput.putInt32(this._partialBlock[i]);
  4544. }
  4545. if(partialBytes > 0) {
  4546. // block still incomplete, restore input buffer
  4547. input.read -= this.blockSize;
  4548. } else {
  4549. // block complete, update input block
  4550. for(var i = 0; i < this._ints; ++i) {
  4551. this._inBlock[i] = this._partialBlock[i];
  4552. }
  4553. }
  4554. // skip any previous partial bytes
  4555. if(this._partialBytes > 0) {
  4556. this._partialOutput.getBytes(this._partialBytes);
  4557. }
  4558. if(partialBytes > 0 && !finish) {
  4559. output.putBytes(this._partialOutput.getBytes(
  4560. partialBytes - this._partialBytes));
  4561. this._partialBytes = partialBytes;
  4562. return true;
  4563. }
  4564. output.putBytes(this._partialOutput.getBytes(
  4565. inputLength - this._partialBytes));
  4566. this._partialBytes = 0;
  4567. };
  4568. modes.cfb.prototype.decrypt = function(input, output, finish) {
  4569. // not enough input to decrypt
  4570. var inputLength = input.length();
  4571. if(inputLength === 0) {
  4572. return true;
  4573. }
  4574. // encrypt block (CFB always uses encryption mode)
  4575. this.cipher.encrypt(this._inBlock, this._outBlock);
  4576. // handle full block
  4577. if(this._partialBytes === 0 && inputLength >= this.blockSize) {
  4578. // XOR input with output, write input as output
  4579. for(var i = 0; i < this._ints; ++i) {
  4580. this._inBlock[i] = input.getInt32();
  4581. output.putInt32(this._inBlock[i] ^ this._outBlock[i]);
  4582. }
  4583. return;
  4584. }
  4585. // handle partial block
  4586. var partialBytes = (this.blockSize - inputLength) % this.blockSize;
  4587. if(partialBytes > 0) {
  4588. partialBytes = this.blockSize - partialBytes;
  4589. }
  4590. // XOR input with output, write input as partial output
  4591. this._partialOutput.clear();
  4592. for(var i = 0; i < this._ints; ++i) {
  4593. this._partialBlock[i] = input.getInt32();
  4594. this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]);
  4595. }
  4596. if(partialBytes > 0) {
  4597. // block still incomplete, restore input buffer
  4598. input.read -= this.blockSize;
  4599. } else {
  4600. // block complete, update input block
  4601. for(var i = 0; i < this._ints; ++i) {
  4602. this._inBlock[i] = this._partialBlock[i];
  4603. }
  4604. }
  4605. // skip any previous partial bytes
  4606. if(this._partialBytes > 0) {
  4607. this._partialOutput.getBytes(this._partialBytes);
  4608. }
  4609. if(partialBytes > 0 && !finish) {
  4610. output.putBytes(this._partialOutput.getBytes(
  4611. partialBytes - this._partialBytes));
  4612. this._partialBytes = partialBytes;
  4613. return true;
  4614. }
  4615. output.putBytes(this._partialOutput.getBytes(
  4616. inputLength - this._partialBytes));
  4617. this._partialBytes = 0;
  4618. };
  4619. /** Output feedback (OFB) **/
  4620. modes.ofb = function(options) {
  4621. options = options || {};
  4622. this.name = 'OFB';
  4623. this.cipher = options.cipher;
  4624. this.blockSize = options.blockSize || 16;
  4625. this._ints = this.blockSize / 4;
  4626. this._inBlock = null;
  4627. this._outBlock = new Array(this._ints);
  4628. this._partialOutput = forge$n.util.createBuffer();
  4629. this._partialBytes = 0;
  4630. };
  4631. modes.ofb.prototype.start = function(options) {
  4632. if(!('iv' in options)) {
  4633. throw new Error('Invalid IV parameter.');
  4634. }
  4635. // use IV as first input
  4636. this._iv = transformIV(options.iv, this.blockSize);
  4637. this._inBlock = this._iv.slice(0);
  4638. this._partialBytes = 0;
  4639. };
  4640. modes.ofb.prototype.encrypt = function(input, output, finish) {
  4641. // not enough input to encrypt
  4642. var inputLength = input.length();
  4643. if(input.length() === 0) {
  4644. return true;
  4645. }
  4646. // encrypt block (OFB always uses encryption mode)
  4647. this.cipher.encrypt(this._inBlock, this._outBlock);
  4648. // handle full block
  4649. if(this._partialBytes === 0 && inputLength >= this.blockSize) {
  4650. // XOR input with output and update next input
  4651. for(var i = 0; i < this._ints; ++i) {
  4652. output.putInt32(input.getInt32() ^ this._outBlock[i]);
  4653. this._inBlock[i] = this._outBlock[i];
  4654. }
  4655. return;
  4656. }
  4657. // handle partial block
  4658. var partialBytes = (this.blockSize - inputLength) % this.blockSize;
  4659. if(partialBytes > 0) {
  4660. partialBytes = this.blockSize - partialBytes;
  4661. }
  4662. // XOR input with output
  4663. this._partialOutput.clear();
  4664. for(var i = 0; i < this._ints; ++i) {
  4665. this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);
  4666. }
  4667. if(partialBytes > 0) {
  4668. // block still incomplete, restore input buffer
  4669. input.read -= this.blockSize;
  4670. } else {
  4671. // block complete, update input block
  4672. for(var i = 0; i < this._ints; ++i) {
  4673. this._inBlock[i] = this._outBlock[i];
  4674. }
  4675. }
  4676. // skip any previous partial bytes
  4677. if(this._partialBytes > 0) {
  4678. this._partialOutput.getBytes(this._partialBytes);
  4679. }
  4680. if(partialBytes > 0 && !finish) {
  4681. output.putBytes(this._partialOutput.getBytes(
  4682. partialBytes - this._partialBytes));
  4683. this._partialBytes = partialBytes;
  4684. return true;
  4685. }
  4686. output.putBytes(this._partialOutput.getBytes(
  4687. inputLength - this._partialBytes));
  4688. this._partialBytes = 0;
  4689. };
  4690. modes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt;
  4691. /** Counter (CTR) **/
  4692. modes.ctr = function(options) {
  4693. options = options || {};
  4694. this.name = 'CTR';
  4695. this.cipher = options.cipher;
  4696. this.blockSize = options.blockSize || 16;
  4697. this._ints = this.blockSize / 4;
  4698. this._inBlock = null;
  4699. this._outBlock = new Array(this._ints);
  4700. this._partialOutput = forge$n.util.createBuffer();
  4701. this._partialBytes = 0;
  4702. };
  4703. modes.ctr.prototype.start = function(options) {
  4704. if(!('iv' in options)) {
  4705. throw new Error('Invalid IV parameter.');
  4706. }
  4707. // use IV as first input
  4708. this._iv = transformIV(options.iv, this.blockSize);
  4709. this._inBlock = this._iv.slice(0);
  4710. this._partialBytes = 0;
  4711. };
  4712. modes.ctr.prototype.encrypt = function(input, output, finish) {
  4713. // not enough input to encrypt
  4714. var inputLength = input.length();
  4715. if(inputLength === 0) {
  4716. return true;
  4717. }
  4718. // encrypt block (CTR always uses encryption mode)
  4719. this.cipher.encrypt(this._inBlock, this._outBlock);
  4720. // handle full block
  4721. if(this._partialBytes === 0 && inputLength >= this.blockSize) {
  4722. // XOR input with output
  4723. for(var i = 0; i < this._ints; ++i) {
  4724. output.putInt32(input.getInt32() ^ this._outBlock[i]);
  4725. }
  4726. } else {
  4727. // handle partial block
  4728. var partialBytes = (this.blockSize - inputLength) % this.blockSize;
  4729. if(partialBytes > 0) {
  4730. partialBytes = this.blockSize - partialBytes;
  4731. }
  4732. // XOR input with output
  4733. this._partialOutput.clear();
  4734. for(var i = 0; i < this._ints; ++i) {
  4735. this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);
  4736. }
  4737. if(partialBytes > 0) {
  4738. // block still incomplete, restore input buffer
  4739. input.read -= this.blockSize;
  4740. }
  4741. // skip any previous partial bytes
  4742. if(this._partialBytes > 0) {
  4743. this._partialOutput.getBytes(this._partialBytes);
  4744. }
  4745. if(partialBytes > 0 && !finish) {
  4746. output.putBytes(this._partialOutput.getBytes(
  4747. partialBytes - this._partialBytes));
  4748. this._partialBytes = partialBytes;
  4749. return true;
  4750. }
  4751. output.putBytes(this._partialOutput.getBytes(
  4752. inputLength - this._partialBytes));
  4753. this._partialBytes = 0;
  4754. }
  4755. // block complete, increment counter (input block)
  4756. inc32(this._inBlock);
  4757. };
  4758. modes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt;
  4759. /** Galois/Counter Mode (GCM) **/
  4760. modes.gcm = function(options) {
  4761. options = options || {};
  4762. this.name = 'GCM';
  4763. this.cipher = options.cipher;
  4764. this.blockSize = options.blockSize || 16;
  4765. this._ints = this.blockSize / 4;
  4766. this._inBlock = new Array(this._ints);
  4767. this._outBlock = new Array(this._ints);
  4768. this._partialOutput = forge$n.util.createBuffer();
  4769. this._partialBytes = 0;
  4770. // R is actually this value concatenated with 120 more zero bits, but
  4771. // we only XOR against R so the other zeros have no effect -- we just
  4772. // apply this value to the first integer in a block
  4773. this._R = 0xE1000000;
  4774. };
  4775. modes.gcm.prototype.start = function(options) {
  4776. if(!('iv' in options)) {
  4777. throw new Error('Invalid IV parameter.');
  4778. }
  4779. // ensure IV is a byte buffer
  4780. var iv = forge$n.util.createBuffer(options.iv);
  4781. // no ciphered data processed yet
  4782. this._cipherLength = 0;
  4783. // default additional data is none
  4784. var additionalData;
  4785. if('additionalData' in options) {
  4786. additionalData = forge$n.util.createBuffer(options.additionalData);
  4787. } else {
  4788. additionalData = forge$n.util.createBuffer();
  4789. }
  4790. // default tag length is 128 bits
  4791. if('tagLength' in options) {
  4792. this._tagLength = options.tagLength;
  4793. } else {
  4794. this._tagLength = 128;
  4795. }
  4796. // if tag is given, ensure tag matches tag length
  4797. this._tag = null;
  4798. if(options.decrypt) {
  4799. // save tag to check later
  4800. this._tag = forge$n.util.createBuffer(options.tag).getBytes();
  4801. if(this._tag.length !== (this._tagLength / 8)) {
  4802. throw new Error('Authentication tag does not match tag length.');
  4803. }
  4804. }
  4805. // create tmp storage for hash calculation
  4806. this._hashBlock = new Array(this._ints);
  4807. // no tag generated yet
  4808. this.tag = null;
  4809. // generate hash subkey
  4810. // (apply block cipher to "zero" block)
  4811. this._hashSubkey = new Array(this._ints);
  4812. this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey);
  4813. // generate table M
  4814. // use 4-bit tables (32 component decomposition of a 16 byte value)
  4815. // 8-bit tables take more space and are known to have security
  4816. // vulnerabilities (in native implementations)
  4817. this.componentBits = 4;
  4818. this._m = this.generateHashTable(this._hashSubkey, this.componentBits);
  4819. // Note: support IV length different from 96 bits? (only supporting
  4820. // 96 bits is recommended by NIST SP-800-38D)
  4821. // generate J_0
  4822. var ivLength = iv.length();
  4823. if(ivLength === 12) {
  4824. // 96-bit IV
  4825. this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1];
  4826. } else {
  4827. // IV is NOT 96-bits
  4828. this._j0 = [0, 0, 0, 0];
  4829. while(iv.length() > 0) {
  4830. this._j0 = this.ghash(
  4831. this._hashSubkey, this._j0,
  4832. [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]);
  4833. }
  4834. this._j0 = this.ghash(
  4835. this._hashSubkey, this._j0, [0, 0].concat(from64To32(ivLength * 8)));
  4836. }
  4837. // generate ICB (initial counter block)
  4838. this._inBlock = this._j0.slice(0);
  4839. inc32(this._inBlock);
  4840. this._partialBytes = 0;
  4841. // consume authentication data
  4842. additionalData = forge$n.util.createBuffer(additionalData);
  4843. // save additional data length as a BE 64-bit number
  4844. this._aDataLength = from64To32(additionalData.length() * 8);
  4845. // pad additional data to 128 bit (16 byte) block size
  4846. var overflow = additionalData.length() % this.blockSize;
  4847. if(overflow) {
  4848. additionalData.fillWithByte(0, this.blockSize - overflow);
  4849. }
  4850. this._s = [0, 0, 0, 0];
  4851. while(additionalData.length() > 0) {
  4852. this._s = this.ghash(this._hashSubkey, this._s, [
  4853. additionalData.getInt32(),
  4854. additionalData.getInt32(),
  4855. additionalData.getInt32(),
  4856. additionalData.getInt32()
  4857. ]);
  4858. }
  4859. };
  4860. modes.gcm.prototype.encrypt = function(input, output, finish) {
  4861. // not enough input to encrypt
  4862. var inputLength = input.length();
  4863. if(inputLength === 0) {
  4864. return true;
  4865. }
  4866. // encrypt block
  4867. this.cipher.encrypt(this._inBlock, this._outBlock);
  4868. // handle full block
  4869. if(this._partialBytes === 0 && inputLength >= this.blockSize) {
  4870. // XOR input with output
  4871. for(var i = 0; i < this._ints; ++i) {
  4872. output.putInt32(this._outBlock[i] ^= input.getInt32());
  4873. }
  4874. this._cipherLength += this.blockSize;
  4875. } else {
  4876. // handle partial block
  4877. var partialBytes = (this.blockSize - inputLength) % this.blockSize;
  4878. if(partialBytes > 0) {
  4879. partialBytes = this.blockSize - partialBytes;
  4880. }
  4881. // XOR input with output
  4882. this._partialOutput.clear();
  4883. for(var i = 0; i < this._ints; ++i) {
  4884. this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]);
  4885. }
  4886. if(partialBytes <= 0 || finish) {
  4887. // handle overflow prior to hashing
  4888. if(finish) {
  4889. // get block overflow
  4890. var overflow = inputLength % this.blockSize;
  4891. this._cipherLength += overflow;
  4892. // truncate for hash function
  4893. this._partialOutput.truncate(this.blockSize - overflow);
  4894. } else {
  4895. this._cipherLength += this.blockSize;
  4896. }
  4897. // get output block for hashing
  4898. for(var i = 0; i < this._ints; ++i) {
  4899. this._outBlock[i] = this._partialOutput.getInt32();
  4900. }
  4901. this._partialOutput.read -= this.blockSize;
  4902. }
  4903. // skip any previous partial bytes
  4904. if(this._partialBytes > 0) {
  4905. this._partialOutput.getBytes(this._partialBytes);
  4906. }
  4907. if(partialBytes > 0 && !finish) {
  4908. // block still incomplete, restore input buffer, get partial output,
  4909. // and return early
  4910. input.read -= this.blockSize;
  4911. output.putBytes(this._partialOutput.getBytes(
  4912. partialBytes - this._partialBytes));
  4913. this._partialBytes = partialBytes;
  4914. return true;
  4915. }
  4916. output.putBytes(this._partialOutput.getBytes(
  4917. inputLength - this._partialBytes));
  4918. this._partialBytes = 0;
  4919. }
  4920. // update hash block S
  4921. this._s = this.ghash(this._hashSubkey, this._s, this._outBlock);
  4922. // increment counter (input block)
  4923. inc32(this._inBlock);
  4924. };
  4925. modes.gcm.prototype.decrypt = function(input, output, finish) {
  4926. // not enough input to decrypt
  4927. var inputLength = input.length();
  4928. if(inputLength < this.blockSize && !(finish && inputLength > 0)) {
  4929. return true;
  4930. }
  4931. // encrypt block (GCM always uses encryption mode)
  4932. this.cipher.encrypt(this._inBlock, this._outBlock);
  4933. // increment counter (input block)
  4934. inc32(this._inBlock);
  4935. // update hash block S
  4936. this._hashBlock[0] = input.getInt32();
  4937. this._hashBlock[1] = input.getInt32();
  4938. this._hashBlock[2] = input.getInt32();
  4939. this._hashBlock[3] = input.getInt32();
  4940. this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock);
  4941. // XOR hash input with output
  4942. for(var i = 0; i < this._ints; ++i) {
  4943. output.putInt32(this._outBlock[i] ^ this._hashBlock[i]);
  4944. }
  4945. // increment cipher data length
  4946. if(inputLength < this.blockSize) {
  4947. this._cipherLength += inputLength % this.blockSize;
  4948. } else {
  4949. this._cipherLength += this.blockSize;
  4950. }
  4951. };
  4952. modes.gcm.prototype.afterFinish = function(output, options) {
  4953. var rval = true;
  4954. // handle overflow
  4955. if(options.decrypt && options.overflow) {
  4956. output.truncate(this.blockSize - options.overflow);
  4957. }
  4958. // handle authentication tag
  4959. this.tag = forge$n.util.createBuffer();
  4960. // concatenate additional data length with cipher length
  4961. var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8));
  4962. // include lengths in hash
  4963. this._s = this.ghash(this._hashSubkey, this._s, lengths);
  4964. // do GCTR(J_0, S)
  4965. var tag = [];
  4966. this.cipher.encrypt(this._j0, tag);
  4967. for(var i = 0; i < this._ints; ++i) {
  4968. this.tag.putInt32(this._s[i] ^ tag[i]);
  4969. }
  4970. // trim tag to length
  4971. this.tag.truncate(this.tag.length() % (this._tagLength / 8));
  4972. // check authentication tag
  4973. if(options.decrypt && this.tag.bytes() !== this._tag) {
  4974. rval = false;
  4975. }
  4976. return rval;
  4977. };
  4978. /**
  4979. * See NIST SP-800-38D 6.3 (Algorithm 1). This function performs Galois
  4980. * field multiplication. The field, GF(2^128), is defined by the polynomial:
  4981. *
  4982. * x^128 + x^7 + x^2 + x + 1
  4983. *
  4984. * Which is represented in little-endian binary form as: 11100001 (0xe1). When
  4985. * the value of a coefficient is 1, a bit is set. The value R, is the
  4986. * concatenation of this value and 120 zero bits, yielding a 128-bit value
  4987. * which matches the block size.
  4988. *
  4989. * This function will multiply two elements (vectors of bytes), X and Y, in
  4990. * the field GF(2^128). The result is initialized to zero. For each bit of
  4991. * X (out of 128), x_i, if x_i is set, then the result is multiplied (XOR'd)
  4992. * by the current value of Y. For each bit, the value of Y will be raised by
  4993. * a power of x (multiplied by the polynomial x). This can be achieved by
  4994. * shifting Y once to the right. If the current value of Y, prior to being
  4995. * multiplied by x, has 0 as its LSB, then it is a 127th degree polynomial.
  4996. * Otherwise, we must divide by R after shifting to find the remainder.
  4997. *
  4998. * @param x the first block to multiply by the second.
  4999. * @param y the second block to multiply by the first.
  5000. *
  5001. * @return the block result of the multiplication.
  5002. */
  5003. modes.gcm.prototype.multiply = function(x, y) {
  5004. var z_i = [0, 0, 0, 0];
  5005. var v_i = y.slice(0);
  5006. // calculate Z_128 (block has 128 bits)
  5007. for(var i = 0; i < 128; ++i) {
  5008. // if x_i is 0, Z_{i+1} = Z_i (unchanged)
  5009. // else Z_{i+1} = Z_i ^ V_i
  5010. // get x_i by finding 32-bit int position, then left shift 1 by remainder
  5011. var x_i = x[(i / 32) | 0] & (1 << (31 - i % 32));
  5012. if(x_i) {
  5013. z_i[0] ^= v_i[0];
  5014. z_i[1] ^= v_i[1];
  5015. z_i[2] ^= v_i[2];
  5016. z_i[3] ^= v_i[3];
  5017. }
  5018. // if LSB(V_i) is 1, V_i = V_i >> 1
  5019. // else V_i = (V_i >> 1) ^ R
  5020. this.pow(v_i, v_i);
  5021. }
  5022. return z_i;
  5023. };
  5024. modes.gcm.prototype.pow = function(x, out) {
  5025. // if LSB(x) is 1, x = x >>> 1
  5026. // else x = (x >>> 1) ^ R
  5027. var lsb = x[3] & 1;
  5028. // always do x >>> 1:
  5029. // starting with the rightmost integer, shift each integer to the right
  5030. // one bit, pulling in the bit from the integer to the left as its top
  5031. // most bit (do this for the last 3 integers)
  5032. for(var i = 3; i > 0; --i) {
  5033. out[i] = (x[i] >>> 1) | ((x[i - 1] & 1) << 31);
  5034. }
  5035. // shift the first integer normally
  5036. out[0] = x[0] >>> 1;
  5037. // if lsb was not set, then polynomial had a degree of 127 and doesn't
  5038. // need to divided; otherwise, XOR with R to find the remainder; we only
  5039. // need to XOR the first integer since R technically ends w/120 zero bits
  5040. if(lsb) {
  5041. out[0] ^= this._R;
  5042. }
  5043. };
  5044. modes.gcm.prototype.tableMultiply = function(x) {
  5045. // assumes 4-bit tables are used
  5046. var z = [0, 0, 0, 0];
  5047. for(var i = 0; i < 32; ++i) {
  5048. var idx = (i / 8) | 0;
  5049. var x_i = (x[idx] >>> ((7 - (i % 8)) * 4)) & 0xF;
  5050. var ah = this._m[i][x_i];
  5051. z[0] ^= ah[0];
  5052. z[1] ^= ah[1];
  5053. z[2] ^= ah[2];
  5054. z[3] ^= ah[3];
  5055. }
  5056. return z;
  5057. };
  5058. /**
  5059. * A continuing version of the GHASH algorithm that operates on a single
  5060. * block. The hash block, last hash value (Ym) and the new block to hash
  5061. * are given.
  5062. *
  5063. * @param h the hash block.
  5064. * @param y the previous value for Ym, use [0, 0, 0, 0] for a new hash.
  5065. * @param x the block to hash.
  5066. *
  5067. * @return the hashed value (Ym).
  5068. */
  5069. modes.gcm.prototype.ghash = function(h, y, x) {
  5070. y[0] ^= x[0];
  5071. y[1] ^= x[1];
  5072. y[2] ^= x[2];
  5073. y[3] ^= x[3];
  5074. return this.tableMultiply(y);
  5075. //return this.multiply(y, h);
  5076. };
  5077. /**
  5078. * Precomputes a table for multiplying against the hash subkey. This
  5079. * mechanism provides a substantial speed increase over multiplication
  5080. * performed without a table. The table-based multiplication this table is
  5081. * for solves X * H by multiplying each component of X by H and then
  5082. * composing the results together using XOR.
  5083. *
  5084. * This function can be used to generate tables with different bit sizes
  5085. * for the components, however, this implementation assumes there are
  5086. * 32 components of X (which is a 16 byte vector), therefore each component
  5087. * takes 4-bits (so the table is constructed with bits=4).
  5088. *
  5089. * @param h the hash subkey.
  5090. * @param bits the bit size for a component.
  5091. */
  5092. modes.gcm.prototype.generateHashTable = function(h, bits) {
  5093. // TODO: There are further optimizations that would use only the
  5094. // first table M_0 (or some variant) along with a remainder table;
  5095. // this can be explored in the future
  5096. var multiplier = 8 / bits;
  5097. var perInt = 4 * multiplier;
  5098. var size = 16 * multiplier;
  5099. var m = new Array(size);
  5100. for(var i = 0; i < size; ++i) {
  5101. var tmp = [0, 0, 0, 0];
  5102. var idx = (i / perInt) | 0;
  5103. var shft = ((perInt - 1 - (i % perInt)) * bits);
  5104. tmp[idx] = (1 << (bits - 1)) << shft;
  5105. m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits);
  5106. }
  5107. return m;
  5108. };
  5109. /**
  5110. * Generates a table for multiplying against the hash subkey for one
  5111. * particular component (out of all possible component values).
  5112. *
  5113. * @param mid the pre-multiplied value for the middle key of the table.
  5114. * @param bits the bit size for a component.
  5115. */
  5116. modes.gcm.prototype.generateSubHashTable = function(mid, bits) {
  5117. // compute the table quickly by minimizing the number of
  5118. // POW operations -- they only need to be performed for powers of 2,
  5119. // all other entries can be composed from those powers using XOR
  5120. var size = 1 << bits;
  5121. var half = size >>> 1;
  5122. var m = new Array(size);
  5123. m[half] = mid.slice(0);
  5124. var i = half >>> 1;
  5125. while(i > 0) {
  5126. // raise m0[2 * i] and store in m0[i]
  5127. this.pow(m[2 * i], m[i] = []);
  5128. i >>= 1;
  5129. }
  5130. i = 2;
  5131. while(i < half) {
  5132. for(var j = 1; j < i; ++j) {
  5133. var m_i = m[i];
  5134. var m_j = m[j];
  5135. m[i + j] = [
  5136. m_i[0] ^ m_j[0],
  5137. m_i[1] ^ m_j[1],
  5138. m_i[2] ^ m_j[2],
  5139. m_i[3] ^ m_j[3]
  5140. ];
  5141. }
  5142. i *= 2;
  5143. }
  5144. m[0] = [0, 0, 0, 0];
  5145. /* Note: We could avoid storing these by doing composition during multiply
  5146. calculate top half using composition by speed is preferred. */
  5147. for(i = half + 1; i < size; ++i) {
  5148. var c = m[i ^ half];
  5149. m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]];
  5150. }
  5151. return m;
  5152. };
  5153. /** Utility functions */
  5154. function transformIV(iv, blockSize) {
  5155. if(typeof iv === 'string') {
  5156. // convert iv string into byte buffer
  5157. iv = forge$n.util.createBuffer(iv);
  5158. }
  5159. if(forge$n.util.isArray(iv) && iv.length > 4) {
  5160. // convert iv byte array into byte buffer
  5161. var tmp = iv;
  5162. iv = forge$n.util.createBuffer();
  5163. for(var i = 0; i < tmp.length; ++i) {
  5164. iv.putByte(tmp[i]);
  5165. }
  5166. }
  5167. if(iv.length() < blockSize) {
  5168. throw new Error(
  5169. 'Invalid IV length; got ' + iv.length() +
  5170. ' bytes and expected ' + blockSize + ' bytes.');
  5171. }
  5172. if(!forge$n.util.isArray(iv)) {
  5173. // convert iv byte buffer into 32-bit integer array
  5174. var ints = [];
  5175. var blocks = blockSize / 4;
  5176. for(var i = 0; i < blocks; ++i) {
  5177. ints.push(iv.getInt32());
  5178. }
  5179. iv = ints;
  5180. }
  5181. return iv;
  5182. }
  5183. function inc32(block) {
  5184. // increment last 32 bits of block only
  5185. block[block.length - 1] = (block[block.length - 1] + 1) & 0xFFFFFFFF;
  5186. }
  5187. function from64To32(num) {
  5188. // convert 64-bit number to two BE Int32s
  5189. return [(num / 0x100000000) | 0, num & 0xFFFFFFFF];
  5190. }
  5191. /**
  5192. * Advanced Encryption Standard (AES) implementation.
  5193. *
  5194. * This implementation is based on the public domain library 'jscrypto' which
  5195. * was written by:
  5196. *
  5197. * Emily Stark (estark@stanford.edu)
  5198. * Mike Hamburg (mhamburg@stanford.edu)
  5199. * Dan Boneh (dabo@cs.stanford.edu)
  5200. *
  5201. * Parts of this code are based on the OpenSSL implementation of AES:
  5202. * http://www.openssl.org
  5203. *
  5204. * @author Dave Longley
  5205. *
  5206. * Copyright (c) 2010-2014 Digital Bazaar, Inc.
  5207. */
  5208. var forge$m = forge$s;
  5209. /* AES API */
  5210. forge$m.aes = forge$m.aes || {};
  5211. /**
  5212. * Deprecated. Instead, use:
  5213. *
  5214. * var cipher = forge.cipher.createCipher('AES-<mode>', key);
  5215. * cipher.start({iv: iv});
  5216. *
  5217. * Creates an AES cipher object to encrypt data using the given symmetric key.
  5218. * The output will be stored in the 'output' member of the returned cipher.
  5219. *
  5220. * The key and iv may be given as a string of bytes, an array of bytes,
  5221. * a byte buffer, or an array of 32-bit words.
  5222. *
  5223. * @param key the symmetric key to use.
  5224. * @param iv the initialization vector to use.
  5225. * @param output the buffer to write to, null to create one.
  5226. * @param mode the cipher mode to use (default: 'CBC').
  5227. *
  5228. * @return the cipher.
  5229. */
  5230. forge$m.aes.startEncrypting = function(key, iv, output, mode) {
  5231. var cipher = _createCipher$1({
  5232. key: key,
  5233. output: output,
  5234. decrypt: false,
  5235. mode: mode
  5236. });
  5237. cipher.start(iv);
  5238. return cipher;
  5239. };
  5240. /**
  5241. * Deprecated. Instead, use:
  5242. *
  5243. * var cipher = forge.cipher.createCipher('AES-<mode>', key);
  5244. *
  5245. * Creates an AES cipher object to encrypt data using the given symmetric key.
  5246. *
  5247. * The key may be given as a string of bytes, an array of bytes, a
  5248. * byte buffer, or an array of 32-bit words.
  5249. *
  5250. * @param key the symmetric key to use.
  5251. * @param mode the cipher mode to use (default: 'CBC').
  5252. *
  5253. * @return the cipher.
  5254. */
  5255. forge$m.aes.createEncryptionCipher = function(key, mode) {
  5256. return _createCipher$1({
  5257. key: key,
  5258. output: null,
  5259. decrypt: false,
  5260. mode: mode
  5261. });
  5262. };
  5263. /**
  5264. * Deprecated. Instead, use:
  5265. *
  5266. * var decipher = forge.cipher.createDecipher('AES-<mode>', key);
  5267. * decipher.start({iv: iv});
  5268. *
  5269. * Creates an AES cipher object to decrypt data using the given symmetric key.
  5270. * The output will be stored in the 'output' member of the returned cipher.
  5271. *
  5272. * The key and iv may be given as a string of bytes, an array of bytes,
  5273. * a byte buffer, or an array of 32-bit words.
  5274. *
  5275. * @param key the symmetric key to use.
  5276. * @param iv the initialization vector to use.
  5277. * @param output the buffer to write to, null to create one.
  5278. * @param mode the cipher mode to use (default: 'CBC').
  5279. *
  5280. * @return the cipher.
  5281. */
  5282. forge$m.aes.startDecrypting = function(key, iv, output, mode) {
  5283. var cipher = _createCipher$1({
  5284. key: key,
  5285. output: output,
  5286. decrypt: true,
  5287. mode: mode
  5288. });
  5289. cipher.start(iv);
  5290. return cipher;
  5291. };
  5292. /**
  5293. * Deprecated. Instead, use:
  5294. *
  5295. * var decipher = forge.cipher.createDecipher('AES-<mode>', key);
  5296. *
  5297. * Creates an AES cipher object to decrypt data using the given symmetric key.
  5298. *
  5299. * The key may be given as a string of bytes, an array of bytes, a
  5300. * byte buffer, or an array of 32-bit words.
  5301. *
  5302. * @param key the symmetric key to use.
  5303. * @param mode the cipher mode to use (default: 'CBC').
  5304. *
  5305. * @return the cipher.
  5306. */
  5307. forge$m.aes.createDecryptionCipher = function(key, mode) {
  5308. return _createCipher$1({
  5309. key: key,
  5310. output: null,
  5311. decrypt: true,
  5312. mode: mode
  5313. });
  5314. };
  5315. /**
  5316. * Creates a new AES cipher algorithm object.
  5317. *
  5318. * @param name the name of the algorithm.
  5319. * @param mode the mode factory function.
  5320. *
  5321. * @return the AES algorithm object.
  5322. */
  5323. forge$m.aes.Algorithm = function(name, mode) {
  5324. if(!init) {
  5325. initialize();
  5326. }
  5327. var self = this;
  5328. self.name = name;
  5329. self.mode = new mode({
  5330. blockSize: 16,
  5331. cipher: {
  5332. encrypt: function(inBlock, outBlock) {
  5333. return _updateBlock$1(self._w, inBlock, outBlock, false);
  5334. },
  5335. decrypt: function(inBlock, outBlock) {
  5336. return _updateBlock$1(self._w, inBlock, outBlock, true);
  5337. }
  5338. }
  5339. });
  5340. self._init = false;
  5341. };
  5342. /**
  5343. * Initializes this AES algorithm by expanding its key.
  5344. *
  5345. * @param options the options to use.
  5346. * key the key to use with this algorithm.
  5347. * decrypt true if the algorithm should be initialized for decryption,
  5348. * false for encryption.
  5349. */
  5350. forge$m.aes.Algorithm.prototype.initialize = function(options) {
  5351. if(this._init) {
  5352. return;
  5353. }
  5354. var key = options.key;
  5355. var tmp;
  5356. /* Note: The key may be a string of bytes, an array of bytes, a byte
  5357. buffer, or an array of 32-bit integers. If the key is in bytes, then
  5358. it must be 16, 24, or 32 bytes in length. If it is in 32-bit
  5359. integers, it must be 4, 6, or 8 integers long. */
  5360. if(typeof key === 'string' &&
  5361. (key.length === 16 || key.length === 24 || key.length === 32)) {
  5362. // convert key string into byte buffer
  5363. key = forge$m.util.createBuffer(key);
  5364. } else if(forge$m.util.isArray(key) &&
  5365. (key.length === 16 || key.length === 24 || key.length === 32)) {
  5366. // convert key integer array into byte buffer
  5367. tmp = key;
  5368. key = forge$m.util.createBuffer();
  5369. for(var i = 0; i < tmp.length; ++i) {
  5370. key.putByte(tmp[i]);
  5371. }
  5372. }
  5373. // convert key byte buffer into 32-bit integer array
  5374. if(!forge$m.util.isArray(key)) {
  5375. tmp = key;
  5376. key = [];
  5377. // key lengths of 16, 24, 32 bytes allowed
  5378. var len = tmp.length();
  5379. if(len === 16 || len === 24 || len === 32) {
  5380. len = len >>> 2;
  5381. for(var i = 0; i < len; ++i) {
  5382. key.push(tmp.getInt32());
  5383. }
  5384. }
  5385. }
  5386. // key must be an array of 32-bit integers by now
  5387. if(!forge$m.util.isArray(key) ||
  5388. !(key.length === 4 || key.length === 6 || key.length === 8)) {
  5389. throw new Error('Invalid key parameter.');
  5390. }
  5391. // encryption operation is always used for these modes
  5392. var mode = this.mode.name;
  5393. var encryptOp = (['CFB', 'OFB', 'CTR', 'GCM'].indexOf(mode) !== -1);
  5394. // do key expansion
  5395. this._w = _expandKey(key, options.decrypt && !encryptOp);
  5396. this._init = true;
  5397. };
  5398. /**
  5399. * Expands a key. Typically only used for testing.
  5400. *
  5401. * @param key the symmetric key to expand, as an array of 32-bit words.
  5402. * @param decrypt true to expand for decryption, false for encryption.
  5403. *
  5404. * @return the expanded key.
  5405. */
  5406. forge$m.aes._expandKey = function(key, decrypt) {
  5407. if(!init) {
  5408. initialize();
  5409. }
  5410. return _expandKey(key, decrypt);
  5411. };
  5412. /**
  5413. * Updates a single block. Typically only used for testing.
  5414. *
  5415. * @param w the expanded key to use.
  5416. * @param input an array of block-size 32-bit words.
  5417. * @param output an array of block-size 32-bit words.
  5418. * @param decrypt true to decrypt, false to encrypt.
  5419. */
  5420. forge$m.aes._updateBlock = _updateBlock$1;
  5421. /** Register AES algorithms **/
  5422. registerAlgorithm$1('AES-ECB', forge$m.cipher.modes.ecb);
  5423. registerAlgorithm$1('AES-CBC', forge$m.cipher.modes.cbc);
  5424. registerAlgorithm$1('AES-CFB', forge$m.cipher.modes.cfb);
  5425. registerAlgorithm$1('AES-OFB', forge$m.cipher.modes.ofb);
  5426. registerAlgorithm$1('AES-CTR', forge$m.cipher.modes.ctr);
  5427. registerAlgorithm$1('AES-GCM', forge$m.cipher.modes.gcm);
  5428. function registerAlgorithm$1(name, mode) {
  5429. var factory = function() {
  5430. return new forge$m.aes.Algorithm(name, mode);
  5431. };
  5432. forge$m.cipher.registerAlgorithm(name, factory);
  5433. }
  5434. /** AES implementation **/
  5435. var init = false; // not yet initialized
  5436. var Nb = 4; // number of words comprising the state (AES = 4)
  5437. var sbox; // non-linear substitution table used in key expansion
  5438. var isbox; // inversion of sbox
  5439. var rcon; // round constant word array
  5440. var mix; // mix-columns table
  5441. var imix; // inverse mix-columns table
  5442. /**
  5443. * Performs initialization, ie: precomputes tables to optimize for speed.
  5444. *
  5445. * One way to understand how AES works is to imagine that 'addition' and
  5446. * 'multiplication' are interfaces that require certain mathematical
  5447. * properties to hold true (ie: they are associative) but they might have
  5448. * different implementations and produce different kinds of results ...
  5449. * provided that their mathematical properties remain true. AES defines
  5450. * its own methods of addition and multiplication but keeps some important
  5451. * properties the same, ie: associativity and distributivity. The
  5452. * explanation below tries to shed some light on how AES defines addition
  5453. * and multiplication of bytes and 32-bit words in order to perform its
  5454. * encryption and decryption algorithms.
  5455. *
  5456. * The basics:
  5457. *
  5458. * The AES algorithm views bytes as binary representations of polynomials
  5459. * that have either 1 or 0 as the coefficients. It defines the addition
  5460. * or subtraction of two bytes as the XOR operation. It also defines the
  5461. * multiplication of two bytes as a finite field referred to as GF(2^8)
  5462. * (Note: 'GF' means "Galois Field" which is a field that contains a finite
  5463. * number of elements so GF(2^8) has 256 elements).
  5464. *
  5465. * This means that any two bytes can be represented as binary polynomials;
  5466. * when they multiplied together and modularly reduced by an irreducible
  5467. * polynomial of the 8th degree, the results are the field GF(2^8). The
  5468. * specific irreducible polynomial that AES uses in hexadecimal is 0x11b.
  5469. * This multiplication is associative with 0x01 as the identity:
  5470. *
  5471. * (b * 0x01 = GF(b, 0x01) = b).
  5472. *
  5473. * The operation GF(b, 0x02) can be performed at the byte level by left
  5474. * shifting b once and then XOR'ing it (to perform the modular reduction)
  5475. * with 0x11b if b is >= 128. Repeated application of the multiplication
  5476. * of 0x02 can be used to implement the multiplication of any two bytes.
  5477. *
  5478. * For instance, multiplying 0x57 and 0x13, denoted as GF(0x57, 0x13), can
  5479. * be performed by factoring 0x13 into 0x01, 0x02, and 0x10. Then these
  5480. * factors can each be multiplied by 0x57 and then added together. To do
  5481. * the multiplication, values for 0x57 multiplied by each of these 3 factors
  5482. * can be precomputed and stored in a table. To add them, the values from
  5483. * the table are XOR'd together.
  5484. *
  5485. * AES also defines addition and multiplication of words, that is 4-byte
  5486. * numbers represented as polynomials of 3 degrees where the coefficients
  5487. * are the values of the bytes.
  5488. *
  5489. * The word [a0, a1, a2, a3] is a polynomial a3x^3 + a2x^2 + a1x + a0.
  5490. *
  5491. * Addition is performed by XOR'ing like powers of x. Multiplication
  5492. * is performed in two steps, the first is an algebriac expansion as
  5493. * you would do normally (where addition is XOR). But the result is
  5494. * a polynomial larger than 3 degrees and thus it cannot fit in a word. So
  5495. * next the result is modularly reduced by an AES-specific polynomial of
  5496. * degree 4 which will always produce a polynomial of less than 4 degrees
  5497. * such that it will fit in a word. In AES, this polynomial is x^4 + 1.
  5498. *
  5499. * The modular product of two polynomials 'a' and 'b' is thus:
  5500. *
  5501. * d(x) = d3x^3 + d2x^2 + d1x + d0
  5502. * with
  5503. * d0 = GF(a0, b0) ^ GF(a3, b1) ^ GF(a2, b2) ^ GF(a1, b3)
  5504. * d1 = GF(a1, b0) ^ GF(a0, b1) ^ GF(a3, b2) ^ GF(a2, b3)
  5505. * d2 = GF(a2, b0) ^ GF(a1, b1) ^ GF(a0, b2) ^ GF(a3, b3)
  5506. * d3 = GF(a3, b0) ^ GF(a2, b1) ^ GF(a1, b2) ^ GF(a0, b3)
  5507. *
  5508. * As a matrix:
  5509. *
  5510. * [d0] = [a0 a3 a2 a1][b0]
  5511. * [d1] [a1 a0 a3 a2][b1]
  5512. * [d2] [a2 a1 a0 a3][b2]
  5513. * [d3] [a3 a2 a1 a0][b3]
  5514. *
  5515. * Special polynomials defined by AES (0x02 == {02}):
  5516. * a(x) = {03}x^3 + {01}x^2 + {01}x + {02}
  5517. * a^-1(x) = {0b}x^3 + {0d}x^2 + {09}x + {0e}.
  5518. *
  5519. * These polynomials are used in the MixColumns() and InverseMixColumns()
  5520. * operations, respectively, to cause each element in the state to affect
  5521. * the output (referred to as diffusing).
  5522. *
  5523. * RotWord() uses: a0 = a1 = a2 = {00} and a3 = {01}, which is the
  5524. * polynomial x3.
  5525. *
  5526. * The ShiftRows() method modifies the last 3 rows in the state (where
  5527. * the state is 4 words with 4 bytes per word) by shifting bytes cyclically.
  5528. * The 1st byte in the second row is moved to the end of the row. The 1st
  5529. * and 2nd bytes in the third row are moved to the end of the row. The 1st,
  5530. * 2nd, and 3rd bytes are moved in the fourth row.
  5531. *
  5532. * More details on how AES arithmetic works:
  5533. *
  5534. * In the polynomial representation of binary numbers, XOR performs addition
  5535. * and subtraction and multiplication in GF(2^8) denoted as GF(a, b)
  5536. * corresponds with the multiplication of polynomials modulo an irreducible
  5537. * polynomial of degree 8. In other words, for AES, GF(a, b) will multiply
  5538. * polynomial 'a' with polynomial 'b' and then do a modular reduction by
  5539. * an AES-specific irreducible polynomial of degree 8.
  5540. *
  5541. * A polynomial is irreducible if its only divisors are one and itself. For
  5542. * the AES algorithm, this irreducible polynomial is:
  5543. *
  5544. * m(x) = x^8 + x^4 + x^3 + x + 1,
  5545. *
  5546. * or {01}{1b} in hexadecimal notation, where each coefficient is a bit:
  5547. * 100011011 = 283 = 0x11b.
  5548. *
  5549. * For example, GF(0x57, 0x83) = 0xc1 because
  5550. *
  5551. * 0x57 = 87 = 01010111 = x^6 + x^4 + x^2 + x + 1
  5552. * 0x85 = 131 = 10000101 = x^7 + x + 1
  5553. *
  5554. * (x^6 + x^4 + x^2 + x + 1) * (x^7 + x + 1)
  5555. * = x^13 + x^11 + x^9 + x^8 + x^7 +
  5556. * x^7 + x^5 + x^3 + x^2 + x +
  5557. * x^6 + x^4 + x^2 + x + 1
  5558. * = x^13 + x^11 + x^9 + x^8 + x^6 + x^5 + x^4 + x^3 + 1 = y
  5559. * y modulo (x^8 + x^4 + x^3 + x + 1)
  5560. * = x^7 + x^6 + 1.
  5561. *
  5562. * The modular reduction by m(x) guarantees the result will be a binary
  5563. * polynomial of less than degree 8, so that it can fit in a byte.
  5564. *
  5565. * The operation to multiply a binary polynomial b with x (the polynomial
  5566. * x in binary representation is 00000010) is:
  5567. *
  5568. * b_7x^8 + b_6x^7 + b_5x^6 + b_4x^5 + b_3x^4 + b_2x^3 + b_1x^2 + b_0x^1
  5569. *
  5570. * To get GF(b, x) we must reduce that by m(x). If b_7 is 0 (that is the
  5571. * most significant bit is 0 in b) then the result is already reduced. If
  5572. * it is 1, then we can reduce it by subtracting m(x) via an XOR.
  5573. *
  5574. * It follows that multiplication by x (00000010 or 0x02) can be implemented
  5575. * by performing a left shift followed by a conditional bitwise XOR with
  5576. * 0x1b. This operation on bytes is denoted by xtime(). Multiplication by
  5577. * higher powers of x can be implemented by repeated application of xtime().
  5578. *
  5579. * By adding intermediate results, multiplication by any constant can be
  5580. * implemented. For instance:
  5581. *
  5582. * GF(0x57, 0x13) = 0xfe because:
  5583. *
  5584. * xtime(b) = (b & 128) ? (b << 1 ^ 0x11b) : (b << 1)
  5585. *
  5586. * Note: We XOR with 0x11b instead of 0x1b because in javascript our
  5587. * datatype for b can be larger than 1 byte, so a left shift will not
  5588. * automatically eliminate bits that overflow a byte ... by XOR'ing the
  5589. * overflow bit with 1 (the extra one from 0x11b) we zero it out.
  5590. *
  5591. * GF(0x57, 0x02) = xtime(0x57) = 0xae
  5592. * GF(0x57, 0x04) = xtime(0xae) = 0x47
  5593. * GF(0x57, 0x08) = xtime(0x47) = 0x8e
  5594. * GF(0x57, 0x10) = xtime(0x8e) = 0x07
  5595. *
  5596. * GF(0x57, 0x13) = GF(0x57, (0x01 ^ 0x02 ^ 0x10))
  5597. *
  5598. * And by the distributive property (since XOR is addition and GF() is
  5599. * multiplication):
  5600. *
  5601. * = GF(0x57, 0x01) ^ GF(0x57, 0x02) ^ GF(0x57, 0x10)
  5602. * = 0x57 ^ 0xae ^ 0x07
  5603. * = 0xfe.
  5604. */
  5605. function initialize() {
  5606. init = true;
  5607. /* Populate the Rcon table. These are the values given by
  5608. [x^(i-1),{00},{00},{00}] where x^(i-1) are powers of x (and x = 0x02)
  5609. in the field of GF(2^8), where i starts at 1.
  5610. rcon[0] = [0x00, 0x00, 0x00, 0x00]
  5611. rcon[1] = [0x01, 0x00, 0x00, 0x00] 2^(1-1) = 2^0 = 1
  5612. rcon[2] = [0x02, 0x00, 0x00, 0x00] 2^(2-1) = 2^1 = 2
  5613. ...
  5614. rcon[9] = [0x1B, 0x00, 0x00, 0x00] 2^(9-1) = 2^8 = 0x1B
  5615. rcon[10] = [0x36, 0x00, 0x00, 0x00] 2^(10-1) = 2^9 = 0x36
  5616. We only store the first byte because it is the only one used.
  5617. */
  5618. rcon = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36];
  5619. // compute xtime table which maps i onto GF(i, 0x02)
  5620. var xtime = new Array(256);
  5621. for(var i = 0; i < 128; ++i) {
  5622. xtime[i] = i << 1;
  5623. xtime[i + 128] = (i + 128) << 1 ^ 0x11B;
  5624. }
  5625. // compute all other tables
  5626. sbox = new Array(256);
  5627. isbox = new Array(256);
  5628. mix = new Array(4);
  5629. imix = new Array(4);
  5630. for(var i = 0; i < 4; ++i) {
  5631. mix[i] = new Array(256);
  5632. imix[i] = new Array(256);
  5633. }
  5634. var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime;
  5635. for(var i = 0; i < 256; ++i) {
  5636. /* We need to generate the SubBytes() sbox and isbox tables so that
  5637. we can perform byte substitutions. This requires us to traverse
  5638. all of the elements in GF, find their multiplicative inverses,
  5639. and apply to each the following affine transformation:
  5640. bi' = bi ^ b(i + 4) mod 8 ^ b(i + 5) mod 8 ^ b(i + 6) mod 8 ^
  5641. b(i + 7) mod 8 ^ ci
  5642. for 0 <= i < 8, where bi is the ith bit of the byte, and ci is the
  5643. ith bit of a byte c with the value {63} or {01100011}.
  5644. It is possible to traverse every possible value in a Galois field
  5645. using what is referred to as a 'generator'. There are many
  5646. generators (128 out of 256): 3,5,6,9,11,82 to name a few. To fully
  5647. traverse GF we iterate 255 times, multiplying by our generator
  5648. each time.
  5649. On each iteration we can determine the multiplicative inverse for
  5650. the current element.
  5651. Suppose there is an element in GF 'e'. For a given generator 'g',
  5652. e = g^x. The multiplicative inverse of e is g^(255 - x). It turns
  5653. out that if use the inverse of a generator as another generator
  5654. it will produce all of the corresponding multiplicative inverses
  5655. at the same time. For this reason, we choose 5 as our inverse
  5656. generator because it only requires 2 multiplies and 1 add and its
  5657. inverse, 82, requires relatively few operations as well.
  5658. In order to apply the affine transformation, the multiplicative
  5659. inverse 'ei' of 'e' can be repeatedly XOR'd (4 times) with a
  5660. bit-cycling of 'ei'. To do this 'ei' is first stored in 's' and
  5661. 'x'. Then 's' is left shifted and the high bit of 's' is made the
  5662. low bit. The resulting value is stored in 's'. Then 'x' is XOR'd
  5663. with 's' and stored in 'x'. On each subsequent iteration the same
  5664. operation is performed. When 4 iterations are complete, 'x' is
  5665. XOR'd with 'c' (0x63) and the transformed value is stored in 'x'.
  5666. For example:
  5667. s = 01000001
  5668. x = 01000001
  5669. iteration 1: s = 10000010, x ^= s
  5670. iteration 2: s = 00000101, x ^= s
  5671. iteration 3: s = 00001010, x ^= s
  5672. iteration 4: s = 00010100, x ^= s
  5673. x ^= 0x63
  5674. This can be done with a loop where s = (s << 1) | (s >> 7). However,
  5675. it can also be done by using a single 16-bit (in this case 32-bit)
  5676. number 'sx'. Since XOR is an associative operation, we can set 'sx'
  5677. to 'ei' and then XOR it with 'sx' left-shifted 1,2,3, and 4 times.
  5678. The most significant bits will flow into the high 8 bit positions
  5679. and be correctly XOR'd with one another. All that remains will be
  5680. to cycle the high 8 bits by XOR'ing them all with the lower 8 bits
  5681. afterwards.
  5682. At the same time we're populating sbox and isbox we can precompute
  5683. the multiplication we'll need to do to do MixColumns() later.
  5684. */
  5685. // apply affine transformation
  5686. sx = ei ^ (ei << 1) ^ (ei << 2) ^ (ei << 3) ^ (ei << 4);
  5687. sx = (sx >> 8) ^ (sx & 255) ^ 0x63;
  5688. // update tables
  5689. sbox[e] = sx;
  5690. isbox[sx] = e;
  5691. /* Mixing columns is done using matrix multiplication. The columns
  5692. that are to be mixed are each a single word in the current state.
  5693. The state has Nb columns (4 columns). Therefore each column is a
  5694. 4 byte word. So to mix the columns in a single column 'c' where
  5695. its rows are r0, r1, r2, and r3, we use the following matrix
  5696. multiplication:
  5697. [2 3 1 1]*[r0,c]=[r'0,c]
  5698. [1 2 3 1] [r1,c] [r'1,c]
  5699. [1 1 2 3] [r2,c] [r'2,c]
  5700. [3 1 1 2] [r3,c] [r'3,c]
  5701. r0, r1, r2, and r3 are each 1 byte of one of the words in the
  5702. state (a column). To do matrix multiplication for each mixed
  5703. column c' we multiply the corresponding row from the left matrix
  5704. with the corresponding column from the right matrix. In total, we
  5705. get 4 equations:
  5706. r0,c' = 2*r0,c + 3*r1,c + 1*r2,c + 1*r3,c
  5707. r1,c' = 1*r0,c + 2*r1,c + 3*r2,c + 1*r3,c
  5708. r2,c' = 1*r0,c + 1*r1,c + 2*r2,c + 3*r3,c
  5709. r3,c' = 3*r0,c + 1*r1,c + 1*r2,c + 2*r3,c
  5710. As usual, the multiplication is as previously defined and the
  5711. addition is XOR. In order to optimize mixing columns we can store
  5712. the multiplication results in tables. If you think of the whole
  5713. column as a word (it might help to visualize by mentally rotating
  5714. the equations above by counterclockwise 90 degrees) then you can
  5715. see that it would be useful to map the multiplications performed on
  5716. each byte (r0, r1, r2, r3) onto a word as well. For instance, we
  5717. could map 2*r0,1*r0,1*r0,3*r0 onto a word by storing 2*r0 in the
  5718. highest 8 bits and 3*r0 in the lowest 8 bits (with the other two
  5719. respectively in the middle). This means that a table can be
  5720. constructed that uses r0 as an index to the word. We can do the
  5721. same with r1, r2, and r3, creating a total of 4 tables.
  5722. To construct a full c', we can just look up each byte of c in
  5723. their respective tables and XOR the results together.
  5724. Also, to build each table we only have to calculate the word
  5725. for 2,1,1,3 for every byte ... which we can do on each iteration
  5726. of this loop since we will iterate over every byte. After we have
  5727. calculated 2,1,1,3 we can get the results for the other tables
  5728. by cycling the byte at the end to the beginning. For instance
  5729. we can take the result of table 2,1,1,3 and produce table 3,2,1,1
  5730. by moving the right most byte to the left most position just like
  5731. how you can imagine the 3 moved out of 2,1,1,3 and to the front
  5732. to produce 3,2,1,1.
  5733. There is another optimization in that the same multiples of
  5734. the current element we need in order to advance our generator
  5735. to the next iteration can be reused in performing the 2,1,1,3
  5736. calculation. We also calculate the inverse mix column tables,
  5737. with e,9,d,b being the inverse of 2,1,1,3.
  5738. When we're done, and we need to actually mix columns, the first
  5739. byte of each state word should be put through mix[0] (2,1,1,3),
  5740. the second through mix[1] (3,2,1,1) and so forth. Then they should
  5741. be XOR'd together to produce the fully mixed column.
  5742. */
  5743. // calculate mix and imix table values
  5744. sx2 = xtime[sx];
  5745. e2 = xtime[e];
  5746. e4 = xtime[e2];
  5747. e8 = xtime[e4];
  5748. me =
  5749. (sx2 << 24) ^ // 2
  5750. (sx << 16) ^ // 1
  5751. (sx << 8) ^ // 1
  5752. (sx ^ sx2); // 3
  5753. ime =
  5754. (e2 ^ e4 ^ e8) << 24 ^ // E (14)
  5755. (e ^ e8) << 16 ^ // 9
  5756. (e ^ e4 ^ e8) << 8 ^ // D (13)
  5757. (e ^ e2 ^ e8); // B (11)
  5758. // produce each of the mix tables by rotating the 2,1,1,3 value
  5759. for(var n = 0; n < 4; ++n) {
  5760. mix[n][e] = me;
  5761. imix[n][sx] = ime;
  5762. // cycle the right most byte to the left most position
  5763. // ie: 2,1,1,3 becomes 3,2,1,1
  5764. me = me << 24 | me >>> 8;
  5765. ime = ime << 24 | ime >>> 8;
  5766. }
  5767. // get next element and inverse
  5768. if(e === 0) {
  5769. // 1 is the inverse of 1
  5770. e = ei = 1;
  5771. } else {
  5772. // e = 2e + 2*2*2*(10e)) = multiply e by 82 (chosen generator)
  5773. // ei = ei + 2*2*ei = multiply ei by 5 (inverse generator)
  5774. e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]];
  5775. ei ^= xtime[xtime[ei]];
  5776. }
  5777. }
  5778. }
  5779. /**
  5780. * Generates a key schedule using the AES key expansion algorithm.
  5781. *
  5782. * The AES algorithm takes the Cipher Key, K, and performs a Key Expansion
  5783. * routine to generate a key schedule. The Key Expansion generates a total
  5784. * of Nb*(Nr + 1) words: the algorithm requires an initial set of Nb words,
  5785. * and each of the Nr rounds requires Nb words of key data. The resulting
  5786. * key schedule consists of a linear array of 4-byte words, denoted [wi ],
  5787. * with i in the range 0 <= i < Nb(Nr + 1).
  5788. *
  5789. * KeyExpansion(byte key[4*Nk], word w[Nb*(Nr+1)], Nk)
  5790. * AES-128 (Nb=4, Nk=4, Nr=10)
  5791. * AES-192 (Nb=4, Nk=6, Nr=12)
  5792. * AES-256 (Nb=4, Nk=8, Nr=14)
  5793. * Note: Nr=Nk+6.
  5794. *
  5795. * Nb is the number of columns (32-bit words) comprising the State (or
  5796. * number of bytes in a block). For AES, Nb=4.
  5797. *
  5798. * @param key the key to schedule (as an array of 32-bit words).
  5799. * @param decrypt true to modify the key schedule to decrypt, false not to.
  5800. *
  5801. * @return the generated key schedule.
  5802. */
  5803. function _expandKey(key, decrypt) {
  5804. // copy the key's words to initialize the key schedule
  5805. var w = key.slice(0);
  5806. /* RotWord() will rotate a word, moving the first byte to the last
  5807. byte's position (shifting the other bytes left).
  5808. We will be getting the value of Rcon at i / Nk. 'i' will iterate
  5809. from Nk to (Nb * Nr+1). Nk = 4 (4 byte key), Nb = 4 (4 words in
  5810. a block), Nr = Nk + 6 (10). Therefore 'i' will iterate from
  5811. 4 to 44 (exclusive). Each time we iterate 4 times, i / Nk will
  5812. increase by 1. We use a counter iNk to keep track of this.
  5813. */
  5814. // go through the rounds expanding the key
  5815. var temp, iNk = 1;
  5816. var Nk = w.length;
  5817. var Nr1 = Nk + 6 + 1;
  5818. var end = Nb * Nr1;
  5819. for(var i = Nk; i < end; ++i) {
  5820. temp = w[i - 1];
  5821. if(i % Nk === 0) {
  5822. // temp = SubWord(RotWord(temp)) ^ Rcon[i / Nk]
  5823. temp =
  5824. sbox[temp >>> 16 & 255] << 24 ^
  5825. sbox[temp >>> 8 & 255] << 16 ^
  5826. sbox[temp & 255] << 8 ^
  5827. sbox[temp >>> 24] ^ (rcon[iNk] << 24);
  5828. iNk++;
  5829. } else if(Nk > 6 && (i % Nk === 4)) {
  5830. // temp = SubWord(temp)
  5831. temp =
  5832. sbox[temp >>> 24] << 24 ^
  5833. sbox[temp >>> 16 & 255] << 16 ^
  5834. sbox[temp >>> 8 & 255] << 8 ^
  5835. sbox[temp & 255];
  5836. }
  5837. w[i] = w[i - Nk] ^ temp;
  5838. }
  5839. /* When we are updating a cipher block we always use the code path for
  5840. encryption whether we are decrypting or not (to shorten code and
  5841. simplify the generation of look up tables). However, because there
  5842. are differences in the decryption algorithm, other than just swapping
  5843. in different look up tables, we must transform our key schedule to
  5844. account for these changes:
  5845. 1. The decryption algorithm gets its key rounds in reverse order.
  5846. 2. The decryption algorithm adds the round key before mixing columns
  5847. instead of afterwards.
  5848. We don't need to modify our key schedule to handle the first case,
  5849. we can just traverse the key schedule in reverse order when decrypting.
  5850. The second case requires a little work.
  5851. The tables we built for performing rounds will take an input and then
  5852. perform SubBytes() and MixColumns() or, for the decrypt version,
  5853. InvSubBytes() and InvMixColumns(). But the decrypt algorithm requires
  5854. us to AddRoundKey() before InvMixColumns(). This means we'll need to
  5855. apply some transformations to the round key to inverse-mix its columns
  5856. so they'll be correct for moving AddRoundKey() to after the state has
  5857. had its columns inverse-mixed.
  5858. To inverse-mix the columns of the state when we're decrypting we use a
  5859. lookup table that will apply InvSubBytes() and InvMixColumns() at the
  5860. same time. However, the round key's bytes are not inverse-substituted
  5861. in the decryption algorithm. To get around this problem, we can first
  5862. substitute the bytes in the round key so that when we apply the
  5863. transformation via the InvSubBytes()+InvMixColumns() table, it will
  5864. undo our substitution leaving us with the original value that we
  5865. want -- and then inverse-mix that value.
  5866. This change will correctly alter our key schedule so that we can XOR
  5867. each round key with our already transformed decryption state. This
  5868. allows us to use the same code path as the encryption algorithm.
  5869. We make one more change to the decryption key. Since the decryption
  5870. algorithm runs in reverse from the encryption algorithm, we reverse
  5871. the order of the round keys to avoid having to iterate over the key
  5872. schedule backwards when running the encryption algorithm later in
  5873. decryption mode. In addition to reversing the order of the round keys,
  5874. we also swap each round key's 2nd and 4th rows. See the comments
  5875. section where rounds are performed for more details about why this is
  5876. done. These changes are done inline with the other substitution
  5877. described above.
  5878. */
  5879. if(decrypt) {
  5880. var tmp;
  5881. var m0 = imix[0];
  5882. var m1 = imix[1];
  5883. var m2 = imix[2];
  5884. var m3 = imix[3];
  5885. var wnew = w.slice(0);
  5886. end = w.length;
  5887. for(var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) {
  5888. // do not sub the first or last round key (round keys are Nb
  5889. // words) as no column mixing is performed before they are added,
  5890. // but do change the key order
  5891. if(i === 0 || i === (end - Nb)) {
  5892. wnew[i] = w[wi];
  5893. wnew[i + 1] = w[wi + 3];
  5894. wnew[i + 2] = w[wi + 2];
  5895. wnew[i + 3] = w[wi + 1];
  5896. } else {
  5897. // substitute each round key byte because the inverse-mix
  5898. // table will inverse-substitute it (effectively cancel the
  5899. // substitution because round key bytes aren't sub'd in
  5900. // decryption mode) and swap indexes 3 and 1
  5901. for(var n = 0; n < Nb; ++n) {
  5902. tmp = w[wi + n];
  5903. wnew[i + (3&-n)] =
  5904. m0[sbox[tmp >>> 24]] ^
  5905. m1[sbox[tmp >>> 16 & 255]] ^
  5906. m2[sbox[tmp >>> 8 & 255]] ^
  5907. m3[sbox[tmp & 255]];
  5908. }
  5909. }
  5910. }
  5911. w = wnew;
  5912. }
  5913. return w;
  5914. }
  5915. /**
  5916. * Updates a single block (16 bytes) using AES. The update will either
  5917. * encrypt or decrypt the block.
  5918. *
  5919. * @param w the key schedule.
  5920. * @param input the input block (an array of 32-bit words).
  5921. * @param output the updated output block.
  5922. * @param decrypt true to decrypt the block, false to encrypt it.
  5923. */
  5924. function _updateBlock$1(w, input, output, decrypt) {
  5925. /*
  5926. Cipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])
  5927. begin
  5928. byte state[4,Nb]
  5929. state = in
  5930. AddRoundKey(state, w[0, Nb-1])
  5931. for round = 1 step 1 to Nr-1
  5932. SubBytes(state)
  5933. ShiftRows(state)
  5934. MixColumns(state)
  5935. AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])
  5936. end for
  5937. SubBytes(state)
  5938. ShiftRows(state)
  5939. AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])
  5940. out = state
  5941. end
  5942. InvCipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)])
  5943. begin
  5944. byte state[4,Nb]
  5945. state = in
  5946. AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])
  5947. for round = Nr-1 step -1 downto 1
  5948. InvShiftRows(state)
  5949. InvSubBytes(state)
  5950. AddRoundKey(state, w[round*Nb, (round+1)*Nb-1])
  5951. InvMixColumns(state)
  5952. end for
  5953. InvShiftRows(state)
  5954. InvSubBytes(state)
  5955. AddRoundKey(state, w[0, Nb-1])
  5956. out = state
  5957. end
  5958. */
  5959. // Encrypt: AddRoundKey(state, w[0, Nb-1])
  5960. // Decrypt: AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])
  5961. var Nr = w.length / 4 - 1;
  5962. var m0, m1, m2, m3, sub;
  5963. if(decrypt) {
  5964. m0 = imix[0];
  5965. m1 = imix[1];
  5966. m2 = imix[2];
  5967. m3 = imix[3];
  5968. sub = isbox;
  5969. } else {
  5970. m0 = mix[0];
  5971. m1 = mix[1];
  5972. m2 = mix[2];
  5973. m3 = mix[3];
  5974. sub = sbox;
  5975. }
  5976. var a, b, c, d, a2, b2, c2;
  5977. a = input[0] ^ w[0];
  5978. b = input[decrypt ? 3 : 1] ^ w[1];
  5979. c = input[2] ^ w[2];
  5980. d = input[decrypt ? 1 : 3] ^ w[3];
  5981. var i = 3;
  5982. /* In order to share code we follow the encryption algorithm when both
  5983. encrypting and decrypting. To account for the changes required in the
  5984. decryption algorithm, we use different lookup tables when decrypting
  5985. and use a modified key schedule to account for the difference in the
  5986. order of transformations applied when performing rounds. We also get
  5987. key rounds in reverse order (relative to encryption). */
  5988. for(var round = 1; round < Nr; ++round) {
  5989. /* As described above, we'll be using table lookups to perform the
  5990. column mixing. Each column is stored as a word in the state (the
  5991. array 'input' has one column as a word at each index). In order to
  5992. mix a column, we perform these transformations on each row in c,
  5993. which is 1 byte in each word. The new column for c0 is c'0:
  5994. m0 m1 m2 m3
  5995. r0,c'0 = 2*r0,c0 + 3*r1,c0 + 1*r2,c0 + 1*r3,c0
  5996. r1,c'0 = 1*r0,c0 + 2*r1,c0 + 3*r2,c0 + 1*r3,c0
  5997. r2,c'0 = 1*r0,c0 + 1*r1,c0 + 2*r2,c0 + 3*r3,c0
  5998. r3,c'0 = 3*r0,c0 + 1*r1,c0 + 1*r2,c0 + 2*r3,c0
  5999. So using mix tables where c0 is a word with r0 being its upper
  6000. 8 bits and r3 being its lower 8 bits:
  6001. m0[c0 >> 24] will yield this word: [2*r0,1*r0,1*r0,3*r0]
  6002. ...
  6003. m3[c0 & 255] will yield this word: [1*r3,1*r3,3*r3,2*r3]
  6004. Therefore to mix the columns in each word in the state we
  6005. do the following (& 255 omitted for brevity):
  6006. c'0,r0 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]
  6007. c'0,r1 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]
  6008. c'0,r2 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]
  6009. c'0,r3 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3]
  6010. However, before mixing, the algorithm requires us to perform
  6011. ShiftRows(). The ShiftRows() transformation cyclically shifts the
  6012. last 3 rows of the state over different offsets. The first row
  6013. (r = 0) is not shifted.
  6014. s'_r,c = s_r,(c + shift(r, Nb) mod Nb
  6015. for 0 < r < 4 and 0 <= c < Nb and
  6016. shift(1, 4) = 1
  6017. shift(2, 4) = 2
  6018. shift(3, 4) = 3.
  6019. This causes the first byte in r = 1 to be moved to the end of
  6020. the row, the first 2 bytes in r = 2 to be moved to the end of
  6021. the row, the first 3 bytes in r = 3 to be moved to the end of
  6022. the row:
  6023. r1: [c0 c1 c2 c3] => [c1 c2 c3 c0]
  6024. r2: [c0 c1 c2 c3] [c2 c3 c0 c1]
  6025. r3: [c0 c1 c2 c3] [c3 c0 c1 c2]
  6026. We can make these substitutions inline with our column mixing to
  6027. generate an updated set of equations to produce each word in the
  6028. state (note the columns have changed positions):
  6029. c0 c1 c2 c3 => c0 c1 c2 c3
  6030. c0 c1 c2 c3 c1 c2 c3 c0 (cycled 1 byte)
  6031. c0 c1 c2 c3 c2 c3 c0 c1 (cycled 2 bytes)
  6032. c0 c1 c2 c3 c3 c0 c1 c2 (cycled 3 bytes)
  6033. Therefore:
  6034. c'0 = 2*r0,c0 + 3*r1,c1 + 1*r2,c2 + 1*r3,c3
  6035. c'0 = 1*r0,c0 + 2*r1,c1 + 3*r2,c2 + 1*r3,c3
  6036. c'0 = 1*r0,c0 + 1*r1,c1 + 2*r2,c2 + 3*r3,c3
  6037. c'0 = 3*r0,c0 + 1*r1,c1 + 1*r2,c2 + 2*r3,c3
  6038. c'1 = 2*r0,c1 + 3*r1,c2 + 1*r2,c3 + 1*r3,c0
  6039. c'1 = 1*r0,c1 + 2*r1,c2 + 3*r2,c3 + 1*r3,c0
  6040. c'1 = 1*r0,c1 + 1*r1,c2 + 2*r2,c3 + 3*r3,c0
  6041. c'1 = 3*r0,c1 + 1*r1,c2 + 1*r2,c3 + 2*r3,c0
  6042. ... and so forth for c'2 and c'3. The important distinction is
  6043. that the columns are cycling, with c0 being used with the m0
  6044. map when calculating c0, but c1 being used with the m0 map when
  6045. calculating c1 ... and so forth.
  6046. When performing the inverse we transform the mirror image and
  6047. skip the bottom row, instead of the top one, and move upwards:
  6048. c3 c2 c1 c0 => c0 c3 c2 c1 (cycled 3 bytes) *same as encryption
  6049. c3 c2 c1 c0 c1 c0 c3 c2 (cycled 2 bytes)
  6050. c3 c2 c1 c0 c2 c1 c0 c3 (cycled 1 byte) *same as encryption
  6051. c3 c2 c1 c0 c3 c2 c1 c0
  6052. If you compare the resulting matrices for ShiftRows()+MixColumns()
  6053. and for InvShiftRows()+InvMixColumns() the 2nd and 4th columns are
  6054. different (in encrypt mode vs. decrypt mode). So in order to use
  6055. the same code to handle both encryption and decryption, we will
  6056. need to do some mapping.
  6057. If in encryption mode we let a=c0, b=c1, c=c2, d=c3, and r<N> be
  6058. a row number in the state, then the resulting matrix in encryption
  6059. mode for applying the above transformations would be:
  6060. r1: a b c d
  6061. r2: b c d a
  6062. r3: c d a b
  6063. r4: d a b c
  6064. If we did the same in decryption mode we would get:
  6065. r1: a d c b
  6066. r2: b a d c
  6067. r3: c b a d
  6068. r4: d c b a
  6069. If instead we swap d and b (set b=c3 and d=c1), then we get:
  6070. r1: a b c d
  6071. r2: d a b c
  6072. r3: c d a b
  6073. r4: b c d a
  6074. Now the 1st and 3rd rows are the same as the encryption matrix. All
  6075. we need to do then to make the mapping exactly the same is to swap
  6076. the 2nd and 4th rows when in decryption mode. To do this without
  6077. having to do it on each iteration, we swapped the 2nd and 4th rows
  6078. in the decryption key schedule. We also have to do the swap above
  6079. when we first pull in the input and when we set the final output. */
  6080. a2 =
  6081. m0[a >>> 24] ^
  6082. m1[b >>> 16 & 255] ^
  6083. m2[c >>> 8 & 255] ^
  6084. m3[d & 255] ^ w[++i];
  6085. b2 =
  6086. m0[b >>> 24] ^
  6087. m1[c >>> 16 & 255] ^
  6088. m2[d >>> 8 & 255] ^
  6089. m3[a & 255] ^ w[++i];
  6090. c2 =
  6091. m0[c >>> 24] ^
  6092. m1[d >>> 16 & 255] ^
  6093. m2[a >>> 8 & 255] ^
  6094. m3[b & 255] ^ w[++i];
  6095. d =
  6096. m0[d >>> 24] ^
  6097. m1[a >>> 16 & 255] ^
  6098. m2[b >>> 8 & 255] ^
  6099. m3[c & 255] ^ w[++i];
  6100. a = a2;
  6101. b = b2;
  6102. c = c2;
  6103. }
  6104. /*
  6105. Encrypt:
  6106. SubBytes(state)
  6107. ShiftRows(state)
  6108. AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1])
  6109. Decrypt:
  6110. InvShiftRows(state)
  6111. InvSubBytes(state)
  6112. AddRoundKey(state, w[0, Nb-1])
  6113. */
  6114. // Note: rows are shifted inline
  6115. output[0] =
  6116. (sub[a >>> 24] << 24) ^
  6117. (sub[b >>> 16 & 255] << 16) ^
  6118. (sub[c >>> 8 & 255] << 8) ^
  6119. (sub[d & 255]) ^ w[++i];
  6120. output[decrypt ? 3 : 1] =
  6121. (sub[b >>> 24] << 24) ^
  6122. (sub[c >>> 16 & 255] << 16) ^
  6123. (sub[d >>> 8 & 255] << 8) ^
  6124. (sub[a & 255]) ^ w[++i];
  6125. output[2] =
  6126. (sub[c >>> 24] << 24) ^
  6127. (sub[d >>> 16 & 255] << 16) ^
  6128. (sub[a >>> 8 & 255] << 8) ^
  6129. (sub[b & 255]) ^ w[++i];
  6130. output[decrypt ? 1 : 3] =
  6131. (sub[d >>> 24] << 24) ^
  6132. (sub[a >>> 16 & 255] << 16) ^
  6133. (sub[b >>> 8 & 255] << 8) ^
  6134. (sub[c & 255]) ^ w[++i];
  6135. }
  6136. /**
  6137. * Deprecated. Instead, use:
  6138. *
  6139. * forge.cipher.createCipher('AES-<mode>', key);
  6140. * forge.cipher.createDecipher('AES-<mode>', key);
  6141. *
  6142. * Creates a deprecated AES cipher object. This object's mode will default to
  6143. * CBC (cipher-block-chaining).
  6144. *
  6145. * The key and iv may be given as a string of bytes, an array of bytes, a
  6146. * byte buffer, or an array of 32-bit words.
  6147. *
  6148. * @param options the options to use.
  6149. * key the symmetric key to use.
  6150. * output the buffer to write to.
  6151. * decrypt true for decryption, false for encryption.
  6152. * mode the cipher mode to use (default: 'CBC').
  6153. *
  6154. * @return the cipher.
  6155. */
  6156. function _createCipher$1(options) {
  6157. options = options || {};
  6158. var mode = (options.mode || 'CBC').toUpperCase();
  6159. var algorithm = 'AES-' + mode;
  6160. var cipher;
  6161. if(options.decrypt) {
  6162. cipher = forge$m.cipher.createDecipher(algorithm, options.key);
  6163. } else {
  6164. cipher = forge$m.cipher.createCipher(algorithm, options.key);
  6165. }
  6166. // backwards compatible start API
  6167. var start = cipher.start;
  6168. cipher.start = function(iv, options) {
  6169. // backwards compatibility: support second arg as output buffer
  6170. var output = null;
  6171. if(options instanceof forge$m.util.ByteBuffer) {
  6172. output = options;
  6173. options = {};
  6174. }
  6175. options = options || {};
  6176. options.output = output;
  6177. options.iv = iv;
  6178. start.call(cipher, options);
  6179. };
  6180. return cipher;
  6181. }
  6182. /**
  6183. * DES (Data Encryption Standard) implementation.
  6184. *
  6185. * This implementation supports DES as well as 3DES-EDE in ECB and CBC mode.
  6186. * It is based on the BSD-licensed implementation by Paul Tero:
  6187. *
  6188. * Paul Tero, July 2001
  6189. * http://www.tero.co.uk/des/
  6190. *
  6191. * Optimised for performance with large blocks by
  6192. * Michael Hayworth, November 2001
  6193. * http://www.netdealing.com
  6194. *
  6195. * THIS SOFTWARE IS PROVIDED "AS IS" AND
  6196. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  6197. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  6198. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  6199. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  6200. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  6201. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  6202. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  6203. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  6204. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  6205. * SUCH DAMAGE.
  6206. *
  6207. * @author Stefan Siegl
  6208. * @author Dave Longley
  6209. *
  6210. * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>
  6211. * Copyright (c) 2012-2014 Digital Bazaar, Inc.
  6212. */
  6213. var forge$l = forge$s;
  6214. /* DES API */
  6215. forge$l.des = forge$l.des || {};
  6216. /**
  6217. * Deprecated. Instead, use:
  6218. *
  6219. * var cipher = forge.cipher.createCipher('DES-<mode>', key);
  6220. * cipher.start({iv: iv});
  6221. *
  6222. * Creates an DES cipher object to encrypt data using the given symmetric key.
  6223. * The output will be stored in the 'output' member of the returned cipher.
  6224. *
  6225. * The key and iv may be given as binary-encoded strings of bytes or
  6226. * byte buffers.
  6227. *
  6228. * @param key the symmetric key to use (64 or 192 bits).
  6229. * @param iv the initialization vector to use.
  6230. * @param output the buffer to write to, null to create one.
  6231. * @param mode the cipher mode to use (default: 'CBC' if IV is
  6232. * given, 'ECB' if null).
  6233. *
  6234. * @return the cipher.
  6235. */
  6236. forge$l.des.startEncrypting = function(key, iv, output, mode) {
  6237. var cipher = _createCipher({
  6238. key: key,
  6239. output: output,
  6240. decrypt: false,
  6241. mode: mode || (iv === null ? 'ECB' : 'CBC')
  6242. });
  6243. cipher.start(iv);
  6244. return cipher;
  6245. };
  6246. /**
  6247. * Deprecated. Instead, use:
  6248. *
  6249. * var cipher = forge.cipher.createCipher('DES-<mode>', key);
  6250. *
  6251. * Creates an DES cipher object to encrypt data using the given symmetric key.
  6252. *
  6253. * The key may be given as a binary-encoded string of bytes or a byte buffer.
  6254. *
  6255. * @param key the symmetric key to use (64 or 192 bits).
  6256. * @param mode the cipher mode to use (default: 'CBC').
  6257. *
  6258. * @return the cipher.
  6259. */
  6260. forge$l.des.createEncryptionCipher = function(key, mode) {
  6261. return _createCipher({
  6262. key: key,
  6263. output: null,
  6264. decrypt: false,
  6265. mode: mode
  6266. });
  6267. };
  6268. /**
  6269. * Deprecated. Instead, use:
  6270. *
  6271. * var decipher = forge.cipher.createDecipher('DES-<mode>', key);
  6272. * decipher.start({iv: iv});
  6273. *
  6274. * Creates an DES cipher object to decrypt data using the given symmetric key.
  6275. * The output will be stored in the 'output' member of the returned cipher.
  6276. *
  6277. * The key and iv may be given as binary-encoded strings of bytes or
  6278. * byte buffers.
  6279. *
  6280. * @param key the symmetric key to use (64 or 192 bits).
  6281. * @param iv the initialization vector to use.
  6282. * @param output the buffer to write to, null to create one.
  6283. * @param mode the cipher mode to use (default: 'CBC' if IV is
  6284. * given, 'ECB' if null).
  6285. *
  6286. * @return the cipher.
  6287. */
  6288. forge$l.des.startDecrypting = function(key, iv, output, mode) {
  6289. var cipher = _createCipher({
  6290. key: key,
  6291. output: output,
  6292. decrypt: true,
  6293. mode: mode || (iv === null ? 'ECB' : 'CBC')
  6294. });
  6295. cipher.start(iv);
  6296. return cipher;
  6297. };
  6298. /**
  6299. * Deprecated. Instead, use:
  6300. *
  6301. * var decipher = forge.cipher.createDecipher('DES-<mode>', key);
  6302. *
  6303. * Creates an DES cipher object to decrypt data using the given symmetric key.
  6304. *
  6305. * The key may be given as a binary-encoded string of bytes or a byte buffer.
  6306. *
  6307. * @param key the symmetric key to use (64 or 192 bits).
  6308. * @param mode the cipher mode to use (default: 'CBC').
  6309. *
  6310. * @return the cipher.
  6311. */
  6312. forge$l.des.createDecryptionCipher = function(key, mode) {
  6313. return _createCipher({
  6314. key: key,
  6315. output: null,
  6316. decrypt: true,
  6317. mode: mode
  6318. });
  6319. };
  6320. /**
  6321. * Creates a new DES cipher algorithm object.
  6322. *
  6323. * @param name the name of the algorithm.
  6324. * @param mode the mode factory function.
  6325. *
  6326. * @return the DES algorithm object.
  6327. */
  6328. forge$l.des.Algorithm = function(name, mode) {
  6329. var self = this;
  6330. self.name = name;
  6331. self.mode = new mode({
  6332. blockSize: 8,
  6333. cipher: {
  6334. encrypt: function(inBlock, outBlock) {
  6335. return _updateBlock(self._keys, inBlock, outBlock, false);
  6336. },
  6337. decrypt: function(inBlock, outBlock) {
  6338. return _updateBlock(self._keys, inBlock, outBlock, true);
  6339. }
  6340. }
  6341. });
  6342. self._init = false;
  6343. };
  6344. /**
  6345. * Initializes this DES algorithm by expanding its key.
  6346. *
  6347. * @param options the options to use.
  6348. * key the key to use with this algorithm.
  6349. * decrypt true if the algorithm should be initialized for decryption,
  6350. * false for encryption.
  6351. */
  6352. forge$l.des.Algorithm.prototype.initialize = function(options) {
  6353. if(this._init) {
  6354. return;
  6355. }
  6356. var key = forge$l.util.createBuffer(options.key);
  6357. if(this.name.indexOf('3DES') === 0) {
  6358. if(key.length() !== 24) {
  6359. throw new Error('Invalid Triple-DES key size: ' + key.length() * 8);
  6360. }
  6361. }
  6362. // do key expansion to 16 or 48 subkeys (single or triple DES)
  6363. this._keys = _createKeys(key);
  6364. this._init = true;
  6365. };
  6366. /** Register DES algorithms **/
  6367. registerAlgorithm('DES-ECB', forge$l.cipher.modes.ecb);
  6368. registerAlgorithm('DES-CBC', forge$l.cipher.modes.cbc);
  6369. registerAlgorithm('DES-CFB', forge$l.cipher.modes.cfb);
  6370. registerAlgorithm('DES-OFB', forge$l.cipher.modes.ofb);
  6371. registerAlgorithm('DES-CTR', forge$l.cipher.modes.ctr);
  6372. registerAlgorithm('3DES-ECB', forge$l.cipher.modes.ecb);
  6373. registerAlgorithm('3DES-CBC', forge$l.cipher.modes.cbc);
  6374. registerAlgorithm('3DES-CFB', forge$l.cipher.modes.cfb);
  6375. registerAlgorithm('3DES-OFB', forge$l.cipher.modes.ofb);
  6376. registerAlgorithm('3DES-CTR', forge$l.cipher.modes.ctr);
  6377. function registerAlgorithm(name, mode) {
  6378. var factory = function() {
  6379. return new forge$l.des.Algorithm(name, mode);
  6380. };
  6381. forge$l.cipher.registerAlgorithm(name, factory);
  6382. }
  6383. /** DES implementation **/
  6384. 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];
  6385. 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];
  6386. 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];
  6387. 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];
  6388. 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];
  6389. 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];
  6390. 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];
  6391. 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];
  6392. /**
  6393. * Create necessary sub keys.
  6394. *
  6395. * @param key the 64-bit or 192-bit key.
  6396. *
  6397. * @return the expanded keys.
  6398. */
  6399. function _createKeys(key) {
  6400. var pc2bytes0 = [0,0x4,0x20000000,0x20000004,0x10000,0x10004,0x20010000,0x20010004,0x200,0x204,0x20000200,0x20000204,0x10200,0x10204,0x20010200,0x20010204],
  6401. pc2bytes1 = [0,0x1,0x100000,0x100001,0x4000000,0x4000001,0x4100000,0x4100001,0x100,0x101,0x100100,0x100101,0x4000100,0x4000101,0x4100100,0x4100101],
  6402. pc2bytes2 = [0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808,0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808],
  6403. pc2bytes3 = [0,0x200000,0x8000000,0x8200000,0x2000,0x202000,0x8002000,0x8202000,0x20000,0x220000,0x8020000,0x8220000,0x22000,0x222000,0x8022000,0x8222000],
  6404. pc2bytes4 = [0,0x40000,0x10,0x40010,0,0x40000,0x10,0x40010,0x1000,0x41000,0x1010,0x41010,0x1000,0x41000,0x1010,0x41010],
  6405. pc2bytes5 = [0,0x400,0x20,0x420,0,0x400,0x20,0x420,0x2000000,0x2000400,0x2000020,0x2000420,0x2000000,0x2000400,0x2000020,0x2000420],
  6406. pc2bytes6 = [0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002,0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002],
  6407. pc2bytes7 = [0,0x10000,0x800,0x10800,0x20000000,0x20010000,0x20000800,0x20010800,0x20000,0x30000,0x20800,0x30800,0x20020000,0x20030000,0x20020800,0x20030800],
  6408. pc2bytes8 = [0,0x40000,0,0x40000,0x2,0x40002,0x2,0x40002,0x2000000,0x2040000,0x2000000,0x2040000,0x2000002,0x2040002,0x2000002,0x2040002],
  6409. pc2bytes9 = [0,0x10000000,0x8,0x10000008,0,0x10000000,0x8,0x10000008,0x400,0x10000400,0x408,0x10000408,0x400,0x10000400,0x408,0x10000408],
  6410. pc2bytes10 = [0,0x20,0,0x20,0x100000,0x100020,0x100000,0x100020,0x2000,0x2020,0x2000,0x2020,0x102000,0x102020,0x102000,0x102020],
  6411. pc2bytes11 = [0,0x1000000,0x200,0x1000200,0x200000,0x1200000,0x200200,0x1200200,0x4000000,0x5000000,0x4000200,0x5000200,0x4200000,0x5200000,0x4200200,0x5200200],
  6412. pc2bytes12 = [0,0x1000,0x8000000,0x8001000,0x80000,0x81000,0x8080000,0x8081000,0x10,0x1010,0x8000010,0x8001010,0x80010,0x81010,0x8080010,0x8081010],
  6413. pc2bytes13 = [0,0x4,0x100,0x104,0,0x4,0x100,0x104,0x1,0x5,0x101,0x105,0x1,0x5,0x101,0x105];
  6414. // how many iterations (1 for des, 3 for triple des)
  6415. // changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys
  6416. var iterations = key.length() > 8 ? 3 : 1;
  6417. // stores the return keys
  6418. var keys = [];
  6419. // now define the left shifts which need to be done
  6420. var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0];
  6421. var n = 0, tmp;
  6422. for(var j = 0; j < iterations; j++) {
  6423. var left = key.getInt32();
  6424. var right = key.getInt32();
  6425. tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;
  6426. right ^= tmp;
  6427. left ^= (tmp << 4);
  6428. tmp = ((right >>> -16) ^ left) & 0x0000ffff;
  6429. left ^= tmp;
  6430. right ^= (tmp << -16);
  6431. tmp = ((left >>> 2) ^ right) & 0x33333333;
  6432. right ^= tmp;
  6433. left ^= (tmp << 2);
  6434. tmp = ((right >>> -16) ^ left) & 0x0000ffff;
  6435. left ^= tmp;
  6436. right ^= (tmp << -16);
  6437. tmp = ((left >>> 1) ^ right) & 0x55555555;
  6438. right ^= tmp;
  6439. left ^= (tmp << 1);
  6440. tmp = ((right >>> 8) ^ left) & 0x00ff00ff;
  6441. left ^= tmp;
  6442. right ^= (tmp << 8);
  6443. tmp = ((left >>> 1) ^ right) & 0x55555555;
  6444. right ^= tmp;
  6445. left ^= (tmp << 1);
  6446. // right needs to be shifted and OR'd with last four bits of left
  6447. tmp = (left << 8) | ((right >>> 20) & 0x000000f0);
  6448. // left needs to be put upside down
  6449. left = ((right << 24) | ((right << 8) & 0xff0000) |
  6450. ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0));
  6451. right = tmp;
  6452. // now go through and perform these shifts on the left and right keys
  6453. for(var i = 0; i < shifts.length; ++i) {
  6454. //shift the keys either one or two bits to the left
  6455. if(shifts[i]) {
  6456. left = (left << 2) | (left >>> 26);
  6457. right = (right << 2) | (right >>> 26);
  6458. } else {
  6459. left = (left << 1) | (left >>> 27);
  6460. right = (right << 1) | (right >>> 27);
  6461. }
  6462. left &= -0xf;
  6463. right &= -0xf;
  6464. // now apply PC-2, in such a way that E is easier when encrypting or
  6465. // decrypting this conversion will look like PC-2 except only the last 6
  6466. // bits of each byte are used rather than 48 consecutive bits and the
  6467. // order of lines will be according to how the S selection functions will
  6468. // be applied: S2, S4, S6, S8, S1, S3, S5, S7
  6469. var lefttmp = (
  6470. pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] |
  6471. pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(left >>> 16) & 0xf] |
  6472. pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] |
  6473. pc2bytes6[(left >>> 4) & 0xf]);
  6474. var righttmp = (
  6475. pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] |
  6476. pc2bytes9[(right >>> 20) & 0xf] | pc2bytes10[(right >>> 16) & 0xf] |
  6477. pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] |
  6478. pc2bytes13[(right >>> 4) & 0xf]);
  6479. tmp = ((righttmp >>> 16) ^ lefttmp) & 0x0000ffff;
  6480. keys[n++] = lefttmp ^ tmp;
  6481. keys[n++] = righttmp ^ (tmp << 16);
  6482. }
  6483. }
  6484. return keys;
  6485. }
  6486. /**
  6487. * Updates a single block (1 byte) using DES. The update will either
  6488. * encrypt or decrypt the block.
  6489. *
  6490. * @param keys the expanded keys.
  6491. * @param input the input block (an array of 32-bit words).
  6492. * @param output the updated output block.
  6493. * @param decrypt true to decrypt the block, false to encrypt it.
  6494. */
  6495. function _updateBlock(keys, input, output, decrypt) {
  6496. // set up loops for single or triple DES
  6497. var iterations = keys.length === 32 ? 3 : 9;
  6498. var looping;
  6499. if(iterations === 3) {
  6500. looping = decrypt ? [30, -2, -2] : [0, 32, 2];
  6501. } else {
  6502. looping = (decrypt ?
  6503. [94, 62, -2, 32, 64, 2, 30, -2, -2] :
  6504. [0, 32, 2, 62, 30, -2, 64, 96, 2]);
  6505. }
  6506. var tmp;
  6507. var left = input[0];
  6508. var right = input[1];
  6509. // first each 64 bit chunk of the message must be permuted according to IP
  6510. tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;
  6511. right ^= tmp;
  6512. left ^= (tmp << 4);
  6513. tmp = ((left >>> 16) ^ right) & 0x0000ffff;
  6514. right ^= tmp;
  6515. left ^= (tmp << 16);
  6516. tmp = ((right >>> 2) ^ left) & 0x33333333;
  6517. left ^= tmp;
  6518. right ^= (tmp << 2);
  6519. tmp = ((right >>> 8) ^ left) & 0x00ff00ff;
  6520. left ^= tmp;
  6521. right ^= (tmp << 8);
  6522. tmp = ((left >>> 1) ^ right) & 0x55555555;
  6523. right ^= tmp;
  6524. left ^= (tmp << 1);
  6525. // rotate left 1 bit
  6526. left = ((left << 1) | (left >>> 31));
  6527. right = ((right << 1) | (right >>> 31));
  6528. for(var j = 0; j < iterations; j += 3) {
  6529. var endloop = looping[j + 1];
  6530. var loopinc = looping[j + 2];
  6531. // now go through and perform the encryption or decryption
  6532. for(var i = looping[j]; i != endloop; i += loopinc) {
  6533. var right1 = right ^ keys[i];
  6534. var right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1];
  6535. // passing these bytes through the S selection functions
  6536. tmp = left;
  6537. left = right;
  6538. right = tmp ^ (
  6539. spfunction2[(right1 >>> 24) & 0x3f] |
  6540. spfunction4[(right1 >>> 16) & 0x3f] |
  6541. spfunction6[(right1 >>> 8) & 0x3f] |
  6542. spfunction8[right1 & 0x3f] |
  6543. spfunction1[(right2 >>> 24) & 0x3f] |
  6544. spfunction3[(right2 >>> 16) & 0x3f] |
  6545. spfunction5[(right2 >>> 8) & 0x3f] |
  6546. spfunction7[right2 & 0x3f]);
  6547. }
  6548. // unreverse left and right
  6549. tmp = left;
  6550. left = right;
  6551. right = tmp;
  6552. }
  6553. // rotate right 1 bit
  6554. left = ((left >>> 1) | (left << 31));
  6555. right = ((right >>> 1) | (right << 31));
  6556. // now perform IP-1, which is IP in the opposite direction
  6557. tmp = ((left >>> 1) ^ right) & 0x55555555;
  6558. right ^= tmp;
  6559. left ^= (tmp << 1);
  6560. tmp = ((right >>> 8) ^ left) & 0x00ff00ff;
  6561. left ^= tmp;
  6562. right ^= (tmp << 8);
  6563. tmp = ((right >>> 2) ^ left) & 0x33333333;
  6564. left ^= tmp;
  6565. right ^= (tmp << 2);
  6566. tmp = ((left >>> 16) ^ right) & 0x0000ffff;
  6567. right ^= tmp;
  6568. left ^= (tmp << 16);
  6569. tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f;
  6570. right ^= tmp;
  6571. left ^= (tmp << 4);
  6572. output[0] = left;
  6573. output[1] = right;
  6574. }
  6575. /**
  6576. * Deprecated. Instead, use:
  6577. *
  6578. * forge.cipher.createCipher('DES-<mode>', key);
  6579. * forge.cipher.createDecipher('DES-<mode>', key);
  6580. *
  6581. * Creates a deprecated DES cipher object. This object's mode will default to
  6582. * CBC (cipher-block-chaining).
  6583. *
  6584. * The key may be given as a binary-encoded string of bytes or a byte buffer.
  6585. *
  6586. * @param options the options to use.
  6587. * key the symmetric key to use (64 or 192 bits).
  6588. * output the buffer to write to.
  6589. * decrypt true for decryption, false for encryption.
  6590. * mode the cipher mode to use (default: 'CBC').
  6591. *
  6592. * @return the cipher.
  6593. */
  6594. function _createCipher(options) {
  6595. options = options || {};
  6596. var mode = (options.mode || 'CBC').toUpperCase();
  6597. var algorithm = 'DES-' + mode;
  6598. var cipher;
  6599. if(options.decrypt) {
  6600. cipher = forge$l.cipher.createDecipher(algorithm, options.key);
  6601. } else {
  6602. cipher = forge$l.cipher.createCipher(algorithm, options.key);
  6603. }
  6604. // backwards compatible start API
  6605. var start = cipher.start;
  6606. cipher.start = function(iv, options) {
  6607. // backwards compatibility: support second arg as output buffer
  6608. var output = null;
  6609. if(options instanceof forge$l.util.ByteBuffer) {
  6610. output = options;
  6611. options = {};
  6612. }
  6613. options = options || {};
  6614. options.output = output;
  6615. options.iv = iv;
  6616. start.call(cipher, options);
  6617. };
  6618. return cipher;
  6619. }
  6620. /**
  6621. * Node.js module for Forge message digests.
  6622. *
  6623. * @author Dave Longley
  6624. *
  6625. * Copyright 2011-2017 Digital Bazaar, Inc.
  6626. */
  6627. var forge$k = forge$s;
  6628. forge$k.md = forge$k.md || {};
  6629. forge$k.md.algorithms = forge$k.md.algorithms || {};
  6630. /**
  6631. * Hash-based Message Authentication Code implementation. Requires a message
  6632. * digest object that can be obtained, for example, from forge.md.sha1 or
  6633. * forge.md.md5.
  6634. *
  6635. * @author Dave Longley
  6636. *
  6637. * Copyright (c) 2010-2012 Digital Bazaar, Inc. All rights reserved.
  6638. */
  6639. var forge$j = forge$s;
  6640. /* HMAC API */
  6641. var hmac = forge$j.hmac = forge$j.hmac || {};
  6642. /**
  6643. * Creates an HMAC object that uses the given message digest object.
  6644. *
  6645. * @return an HMAC object.
  6646. */
  6647. hmac.create = function() {
  6648. // the hmac key to use
  6649. var _key = null;
  6650. // the message digest to use
  6651. var _md = null;
  6652. // the inner padding
  6653. var _ipadding = null;
  6654. // the outer padding
  6655. var _opadding = null;
  6656. // hmac context
  6657. var ctx = {};
  6658. /**
  6659. * Starts or restarts the HMAC with the given key and message digest.
  6660. *
  6661. * @param md the message digest to use, null to reuse the previous one,
  6662. * a string to use builtin 'sha1', 'md5', 'sha256'.
  6663. * @param key the key to use as a string, array of bytes, byte buffer,
  6664. * or null to reuse the previous key.
  6665. */
  6666. ctx.start = function(md, key) {
  6667. if(md !== null) {
  6668. if(typeof md === 'string') {
  6669. // create builtin message digest
  6670. md = md.toLowerCase();
  6671. if(md in forge$j.md.algorithms) {
  6672. _md = forge$j.md.algorithms[md].create();
  6673. } else {
  6674. throw new Error('Unknown hash algorithm "' + md + '"');
  6675. }
  6676. } else {
  6677. // store message digest
  6678. _md = md;
  6679. }
  6680. }
  6681. if(key === null) {
  6682. // reuse previous key
  6683. key = _key;
  6684. } else {
  6685. if(typeof key === 'string') {
  6686. // convert string into byte buffer
  6687. key = forge$j.util.createBuffer(key);
  6688. } else if(forge$j.util.isArray(key)) {
  6689. // convert byte array into byte buffer
  6690. var tmp = key;
  6691. key = forge$j.util.createBuffer();
  6692. for(var i = 0; i < tmp.length; ++i) {
  6693. key.putByte(tmp[i]);
  6694. }
  6695. }
  6696. // if key is longer than blocksize, hash it
  6697. var keylen = key.length();
  6698. if(keylen > _md.blockLength) {
  6699. _md.start();
  6700. _md.update(key.bytes());
  6701. key = _md.digest();
  6702. }
  6703. // mix key into inner and outer padding
  6704. // ipadding = [0x36 * blocksize] ^ key
  6705. // opadding = [0x5C * blocksize] ^ key
  6706. _ipadding = forge$j.util.createBuffer();
  6707. _opadding = forge$j.util.createBuffer();
  6708. keylen = key.length();
  6709. for(var i = 0; i < keylen; ++i) {
  6710. var tmp = key.at(i);
  6711. _ipadding.putByte(0x36 ^ tmp);
  6712. _opadding.putByte(0x5C ^ tmp);
  6713. }
  6714. // if key is shorter than blocksize, add additional padding
  6715. if(keylen < _md.blockLength) {
  6716. var tmp = _md.blockLength - keylen;
  6717. for(var i = 0; i < tmp; ++i) {
  6718. _ipadding.putByte(0x36);
  6719. _opadding.putByte(0x5C);
  6720. }
  6721. }
  6722. _key = key;
  6723. _ipadding = _ipadding.bytes();
  6724. _opadding = _opadding.bytes();
  6725. }
  6726. // digest is done like so: hash(opadding | hash(ipadding | message))
  6727. // prepare to do inner hash
  6728. // hash(ipadding | message)
  6729. _md.start();
  6730. _md.update(_ipadding);
  6731. };
  6732. /**
  6733. * Updates the HMAC with the given message bytes.
  6734. *
  6735. * @param bytes the bytes to update with.
  6736. */
  6737. ctx.update = function(bytes) {
  6738. _md.update(bytes);
  6739. };
  6740. /**
  6741. * Produces the Message Authentication Code (MAC).
  6742. *
  6743. * @return a byte buffer containing the digest value.
  6744. */
  6745. ctx.getMac = function() {
  6746. // digest is done like so: hash(opadding | hash(ipadding | message))
  6747. // here we do the outer hashing
  6748. var inner = _md.digest().bytes();
  6749. _md.start();
  6750. _md.update(_opadding);
  6751. _md.update(inner);
  6752. return _md.digest();
  6753. };
  6754. // alias for getMac
  6755. ctx.digest = ctx.getMac;
  6756. return ctx;
  6757. };
  6758. /**
  6759. * Password-Based Key-Derivation Function #2 implementation.
  6760. *
  6761. * See RFC 2898 for details.
  6762. *
  6763. * @author Dave Longley
  6764. *
  6765. * Copyright (c) 2010-2013 Digital Bazaar, Inc.
  6766. */
  6767. var forge$i = forge$s;
  6768. var pkcs5 = forge$i.pkcs5 = forge$i.pkcs5 || {};
  6769. var crypto;
  6770. if(forge$i.util.isNodejs && !forge$i.options.usePureJavaScript) {
  6771. crypto = require$$1__default;
  6772. }
  6773. /**
  6774. * Derives a key from a password.
  6775. *
  6776. * @param p the password as a binary-encoded string of bytes.
  6777. * @param s the salt as a binary-encoded string of bytes.
  6778. * @param c the iteration count, a positive integer.
  6779. * @param dkLen the intended length, in bytes, of the derived key,
  6780. * (max: 2^32 - 1) * hash length of the PRF.
  6781. * @param [md] the message digest (or algorithm identifier as a string) to use
  6782. * in the PRF, defaults to SHA-1.
  6783. * @param [callback(err, key)] presence triggers asynchronous version, called
  6784. * once the operation completes.
  6785. *
  6786. * @return the derived key, as a binary-encoded string of bytes, for the
  6787. * synchronous version (if no callback is specified).
  6788. */
  6789. forge$i.pbkdf2 = pkcs5.pbkdf2 = function(
  6790. p, s, c, dkLen, md, callback) {
  6791. if(typeof md === 'function') {
  6792. callback = md;
  6793. md = null;
  6794. }
  6795. // use native implementation if possible and not disabled, note that
  6796. // some node versions only support SHA-1, others allow digest to be changed
  6797. if(forge$i.util.isNodejs && !forge$i.options.usePureJavaScript &&
  6798. crypto.pbkdf2 && (md === null || typeof md !== 'object') &&
  6799. (crypto.pbkdf2Sync.length > 4 || (!md || md === 'sha1'))) {
  6800. if(typeof md !== 'string') {
  6801. // default prf to SHA-1
  6802. md = 'sha1';
  6803. }
  6804. p = Buffer.from(p, 'binary');
  6805. s = Buffer.from(s, 'binary');
  6806. if(!callback) {
  6807. if(crypto.pbkdf2Sync.length === 4) {
  6808. return crypto.pbkdf2Sync(p, s, c, dkLen).toString('binary');
  6809. }
  6810. return crypto.pbkdf2Sync(p, s, c, dkLen, md).toString('binary');
  6811. }
  6812. if(crypto.pbkdf2Sync.length === 4) {
  6813. return crypto.pbkdf2(p, s, c, dkLen, function(err, key) {
  6814. if(err) {
  6815. return callback(err);
  6816. }
  6817. callback(null, key.toString('binary'));
  6818. });
  6819. }
  6820. return crypto.pbkdf2(p, s, c, dkLen, md, function(err, key) {
  6821. if(err) {
  6822. return callback(err);
  6823. }
  6824. callback(null, key.toString('binary'));
  6825. });
  6826. }
  6827. if(typeof md === 'undefined' || md === null) {
  6828. // default prf to SHA-1
  6829. md = 'sha1';
  6830. }
  6831. if(typeof md === 'string') {
  6832. if(!(md in forge$i.md.algorithms)) {
  6833. throw new Error('Unknown hash algorithm: ' + md);
  6834. }
  6835. md = forge$i.md[md].create();
  6836. }
  6837. var hLen = md.digestLength;
  6838. /* 1. If dkLen > (2^32 - 1) * hLen, output "derived key too long" and
  6839. stop. */
  6840. if(dkLen > (0xFFFFFFFF * hLen)) {
  6841. var err = new Error('Derived key is too long.');
  6842. if(callback) {
  6843. return callback(err);
  6844. }
  6845. throw err;
  6846. }
  6847. /* 2. Let len be the number of hLen-octet blocks in the derived key,
  6848. rounding up, and let r be the number of octets in the last
  6849. block:
  6850. len = CEIL(dkLen / hLen),
  6851. r = dkLen - (len - 1) * hLen. */
  6852. var len = Math.ceil(dkLen / hLen);
  6853. var r = dkLen - (len - 1) * hLen;
  6854. /* 3. For each block of the derived key apply the function F defined
  6855. below to the password P, the salt S, the iteration count c, and
  6856. the block index to compute the block:
  6857. T_1 = F(P, S, c, 1),
  6858. T_2 = F(P, S, c, 2),
  6859. ...
  6860. T_len = F(P, S, c, len),
  6861. where the function F is defined as the exclusive-or sum of the
  6862. first c iterates of the underlying pseudorandom function PRF
  6863. applied to the password P and the concatenation of the salt S
  6864. and the block index i:
  6865. F(P, S, c, i) = u_1 XOR u_2 XOR ... XOR u_c
  6866. where
  6867. u_1 = PRF(P, S || INT(i)),
  6868. u_2 = PRF(P, u_1),
  6869. ...
  6870. u_c = PRF(P, u_{c-1}).
  6871. Here, INT(i) is a four-octet encoding of the integer i, most
  6872. significant octet first. */
  6873. var prf = forge$i.hmac.create();
  6874. prf.start(md, p);
  6875. var dk = '';
  6876. var xor, u_c, u_c1;
  6877. // sync version
  6878. if(!callback) {
  6879. for(var i = 1; i <= len; ++i) {
  6880. // PRF(P, S || INT(i)) (first iteration)
  6881. prf.start(null, null);
  6882. prf.update(s);
  6883. prf.update(forge$i.util.int32ToBytes(i));
  6884. xor = u_c1 = prf.digest().getBytes();
  6885. // PRF(P, u_{c-1}) (other iterations)
  6886. for(var j = 2; j <= c; ++j) {
  6887. prf.start(null, null);
  6888. prf.update(u_c1);
  6889. u_c = prf.digest().getBytes();
  6890. // F(p, s, c, i)
  6891. xor = forge$i.util.xorBytes(xor, u_c, hLen);
  6892. u_c1 = u_c;
  6893. }
  6894. /* 4. Concatenate the blocks and extract the first dkLen octets to
  6895. produce a derived key DK:
  6896. DK = T_1 || T_2 || ... || T_len<0..r-1> */
  6897. dk += (i < len) ? xor : xor.substr(0, r);
  6898. }
  6899. /* 5. Output the derived key DK. */
  6900. return dk;
  6901. }
  6902. // async version
  6903. var i = 1, j;
  6904. function outer() {
  6905. if(i > len) {
  6906. // done
  6907. return callback(null, dk);
  6908. }
  6909. // PRF(P, S || INT(i)) (first iteration)
  6910. prf.start(null, null);
  6911. prf.update(s);
  6912. prf.update(forge$i.util.int32ToBytes(i));
  6913. xor = u_c1 = prf.digest().getBytes();
  6914. // PRF(P, u_{c-1}) (other iterations)
  6915. j = 2;
  6916. inner();
  6917. }
  6918. function inner() {
  6919. if(j <= c) {
  6920. prf.start(null, null);
  6921. prf.update(u_c1);
  6922. u_c = prf.digest().getBytes();
  6923. // F(p, s, c, i)
  6924. xor = forge$i.util.xorBytes(xor, u_c, hLen);
  6925. u_c1 = u_c;
  6926. ++j;
  6927. return forge$i.util.setImmediate(inner);
  6928. }
  6929. /* 4. Concatenate the blocks and extract the first dkLen octets to
  6930. produce a derived key DK:
  6931. DK = T_1 || T_2 || ... || T_len<0..r-1> */
  6932. dk += (i < len) ? xor : xor.substr(0, r);
  6933. ++i;
  6934. outer();
  6935. }
  6936. outer();
  6937. };
  6938. /**
  6939. * Javascript implementation of basic PEM (Privacy Enhanced Mail) algorithms.
  6940. *
  6941. * See: RFC 1421.
  6942. *
  6943. * @author Dave Longley
  6944. *
  6945. * Copyright (c) 2013-2014 Digital Bazaar, Inc.
  6946. *
  6947. * A Forge PEM object has the following fields:
  6948. *
  6949. * type: identifies the type of message (eg: "RSA PRIVATE KEY").
  6950. *
  6951. * procType: identifies the type of processing performed on the message,
  6952. * it has two subfields: version and type, eg: 4,ENCRYPTED.
  6953. *
  6954. * contentDomain: identifies the type of content in the message, typically
  6955. * only uses the value: "RFC822".
  6956. *
  6957. * dekInfo: identifies the message encryption algorithm and mode and includes
  6958. * any parameters for the algorithm, it has two subfields: algorithm and
  6959. * parameters, eg: DES-CBC,F8143EDE5960C597.
  6960. *
  6961. * headers: contains all other PEM encapsulated headers -- where order is
  6962. * significant (for pairing data like recipient ID + key info).
  6963. *
  6964. * body: the binary-encoded body.
  6965. */
  6966. var forge$h = forge$s;
  6967. // shortcut for pem API
  6968. var pem = forge$h.pem = forge$h.pem || {};
  6969. /**
  6970. * Encodes (serializes) the given PEM object.
  6971. *
  6972. * @param msg the PEM message object to encode.
  6973. * @param options the options to use:
  6974. * maxline the maximum characters per line for the body, (default: 64).
  6975. *
  6976. * @return the PEM-formatted string.
  6977. */
  6978. pem.encode = function(msg, options) {
  6979. options = options || {};
  6980. var rval = '-----BEGIN ' + msg.type + '-----\r\n';
  6981. // encode special headers
  6982. var header;
  6983. if(msg.procType) {
  6984. header = {
  6985. name: 'Proc-Type',
  6986. values: [String(msg.procType.version), msg.procType.type]
  6987. };
  6988. rval += foldHeader(header);
  6989. }
  6990. if(msg.contentDomain) {
  6991. header = {name: 'Content-Domain', values: [msg.contentDomain]};
  6992. rval += foldHeader(header);
  6993. }
  6994. if(msg.dekInfo) {
  6995. header = {name: 'DEK-Info', values: [msg.dekInfo.algorithm]};
  6996. if(msg.dekInfo.parameters) {
  6997. header.values.push(msg.dekInfo.parameters);
  6998. }
  6999. rval += foldHeader(header);
  7000. }
  7001. if(msg.headers) {
  7002. // encode all other headers
  7003. for(var i = 0; i < msg.headers.length; ++i) {
  7004. rval += foldHeader(msg.headers[i]);
  7005. }
  7006. }
  7007. // terminate header
  7008. if(msg.procType) {
  7009. rval += '\r\n';
  7010. }
  7011. // add body
  7012. rval += forge$h.util.encode64(msg.body, options.maxline || 64) + '\r\n';
  7013. rval += '-----END ' + msg.type + '-----\r\n';
  7014. return rval;
  7015. };
  7016. /**
  7017. * Decodes (deserializes) all PEM messages found in the given string.
  7018. *
  7019. * @param str the PEM-formatted string to decode.
  7020. *
  7021. * @return the PEM message objects in an array.
  7022. */
  7023. pem.decode = function(str) {
  7024. var rval = [];
  7025. // split string into PEM messages (be lenient w/EOF on BEGIN line)
  7026. var rMessage = /\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g;
  7027. var rHeader = /([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/;
  7028. var rCRLF = /\r?\n/;
  7029. var match;
  7030. while(true) {
  7031. match = rMessage.exec(str);
  7032. if(!match) {
  7033. break;
  7034. }
  7035. // accept "NEW CERTIFICATE REQUEST" as "CERTIFICATE REQUEST"
  7036. // https://datatracker.ietf.org/doc/html/rfc7468#section-7
  7037. var type = match[1];
  7038. if(type === 'NEW CERTIFICATE REQUEST') {
  7039. type = 'CERTIFICATE REQUEST';
  7040. }
  7041. var msg = {
  7042. type: type,
  7043. procType: null,
  7044. contentDomain: null,
  7045. dekInfo: null,
  7046. headers: [],
  7047. body: forge$h.util.decode64(match[3])
  7048. };
  7049. rval.push(msg);
  7050. // no headers
  7051. if(!match[2]) {
  7052. continue;
  7053. }
  7054. // parse headers
  7055. var lines = match[2].split(rCRLF);
  7056. var li = 0;
  7057. while(match && li < lines.length) {
  7058. // get line, trim any rhs whitespace
  7059. var line = lines[li].replace(/\s+$/, '');
  7060. // RFC2822 unfold any following folded lines
  7061. for(var nl = li + 1; nl < lines.length; ++nl) {
  7062. var next = lines[nl];
  7063. if(!/\s/.test(next[0])) {
  7064. break;
  7065. }
  7066. line += next;
  7067. li = nl;
  7068. }
  7069. // parse header
  7070. match = line.match(rHeader);
  7071. if(match) {
  7072. var header = {name: match[1], values: []};
  7073. var values = match[2].split(',');
  7074. for(var vi = 0; vi < values.length; ++vi) {
  7075. header.values.push(ltrim(values[vi]));
  7076. }
  7077. // Proc-Type must be the first header
  7078. if(!msg.procType) {
  7079. if(header.name !== 'Proc-Type') {
  7080. throw new Error('Invalid PEM formatted message. The first ' +
  7081. 'encapsulated header must be "Proc-Type".');
  7082. } else if(header.values.length !== 2) {
  7083. throw new Error('Invalid PEM formatted message. The "Proc-Type" ' +
  7084. 'header must have two subfields.');
  7085. }
  7086. msg.procType = {version: values[0], type: values[1]};
  7087. } else if(!msg.contentDomain && header.name === 'Content-Domain') {
  7088. // special-case Content-Domain
  7089. msg.contentDomain = values[0] || '';
  7090. } else if(!msg.dekInfo && header.name === 'DEK-Info') {
  7091. // special-case DEK-Info
  7092. if(header.values.length === 0) {
  7093. throw new Error('Invalid PEM formatted message. The "DEK-Info" ' +
  7094. 'header must have at least one subfield.');
  7095. }
  7096. msg.dekInfo = {algorithm: values[0], parameters: values[1] || null};
  7097. } else {
  7098. msg.headers.push(header);
  7099. }
  7100. }
  7101. ++li;
  7102. }
  7103. if(msg.procType === 'ENCRYPTED' && !msg.dekInfo) {
  7104. throw new Error('Invalid PEM formatted message. The "DEK-Info" ' +
  7105. 'header must be present if "Proc-Type" is "ENCRYPTED".');
  7106. }
  7107. }
  7108. if(rval.length === 0) {
  7109. throw new Error('Invalid PEM formatted message.');
  7110. }
  7111. return rval;
  7112. };
  7113. function foldHeader(header) {
  7114. var rval = header.name + ': ';
  7115. // ensure values with CRLF are folded
  7116. var values = [];
  7117. var insertSpace = function(match, $1) {
  7118. return ' ' + $1;
  7119. };
  7120. for(var i = 0; i < header.values.length; ++i) {
  7121. values.push(header.values[i].replace(/^(\S+\r\n)/, insertSpace));
  7122. }
  7123. rval += values.join(',') + '\r\n';
  7124. // do folding
  7125. var length = 0;
  7126. var candidate = -1;
  7127. for(var i = 0; i < rval.length; ++i, ++length) {
  7128. if(length > 65 && candidate !== -1) {
  7129. var insert = rval[candidate];
  7130. if(insert === ',') {
  7131. ++candidate;
  7132. rval = rval.substr(0, candidate) + '\r\n ' + rval.substr(candidate);
  7133. } else {
  7134. rval = rval.substr(0, candidate) +
  7135. '\r\n' + insert + rval.substr(candidate + 1);
  7136. }
  7137. length = (i - candidate - 1);
  7138. candidate = -1;
  7139. ++i;
  7140. } else if(rval[i] === ' ' || rval[i] === '\t' || rval[i] === ',') {
  7141. candidate = i;
  7142. }
  7143. }
  7144. return rval;
  7145. }
  7146. function ltrim(str) {
  7147. return str.replace(/^\s+/, '');
  7148. }
  7149. /**
  7150. * Secure Hash Algorithm with 256-bit digest (SHA-256) implementation.
  7151. *
  7152. * See FIPS 180-2 for details.
  7153. *
  7154. * @author Dave Longley
  7155. *
  7156. * Copyright (c) 2010-2015 Digital Bazaar, Inc.
  7157. */
  7158. var forge$g = forge$s;
  7159. var sha256 = forge$g.sha256 = forge$g.sha256 || {};
  7160. forge$g.md.sha256 = forge$g.md.algorithms.sha256 = sha256;
  7161. /**
  7162. * Creates a SHA-256 message digest object.
  7163. *
  7164. * @return a message digest object.
  7165. */
  7166. sha256.create = function() {
  7167. // do initialization as necessary
  7168. if(!_initialized$1) {
  7169. _init$1();
  7170. }
  7171. // SHA-256 state contains eight 32-bit integers
  7172. var _state = null;
  7173. // input buffer
  7174. var _input = forge$g.util.createBuffer();
  7175. // used for word storage
  7176. var _w = new Array(64);
  7177. // message digest object
  7178. var md = {
  7179. algorithm: 'sha256',
  7180. blockLength: 64,
  7181. digestLength: 32,
  7182. // 56-bit length of message so far (does not including padding)
  7183. messageLength: 0,
  7184. // true message length
  7185. fullMessageLength: null,
  7186. // size of message length in bytes
  7187. messageLengthSize: 8
  7188. };
  7189. /**
  7190. * Starts the digest.
  7191. *
  7192. * @return this digest object.
  7193. */
  7194. md.start = function() {
  7195. // up to 56-bit message length for convenience
  7196. md.messageLength = 0;
  7197. // full message length (set md.messageLength64 for backwards-compatibility)
  7198. md.fullMessageLength = md.messageLength64 = [];
  7199. var int32s = md.messageLengthSize / 4;
  7200. for(var i = 0; i < int32s; ++i) {
  7201. md.fullMessageLength.push(0);
  7202. }
  7203. _input = forge$g.util.createBuffer();
  7204. _state = {
  7205. h0: 0x6A09E667,
  7206. h1: 0xBB67AE85,
  7207. h2: 0x3C6EF372,
  7208. h3: 0xA54FF53A,
  7209. h4: 0x510E527F,
  7210. h5: 0x9B05688C,
  7211. h6: 0x1F83D9AB,
  7212. h7: 0x5BE0CD19
  7213. };
  7214. return md;
  7215. };
  7216. // start digest automatically for first time
  7217. md.start();
  7218. /**
  7219. * Updates the digest with the given message input. The given input can
  7220. * treated as raw input (no encoding will be applied) or an encoding of
  7221. * 'utf8' maybe given to encode the input using UTF-8.
  7222. *
  7223. * @param msg the message input to update with.
  7224. * @param encoding the encoding to use (default: 'raw', other: 'utf8').
  7225. *
  7226. * @return this digest object.
  7227. */
  7228. md.update = function(msg, encoding) {
  7229. if(encoding === 'utf8') {
  7230. msg = forge$g.util.encodeUtf8(msg);
  7231. }
  7232. // update message length
  7233. var len = msg.length;
  7234. md.messageLength += len;
  7235. len = [(len / 0x100000000) >>> 0, len >>> 0];
  7236. for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {
  7237. md.fullMessageLength[i] += len[1];
  7238. len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);
  7239. md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;
  7240. len[0] = ((len[1] / 0x100000000) >>> 0);
  7241. }
  7242. // add bytes to input buffer
  7243. _input.putBytes(msg);
  7244. // process bytes
  7245. _update$1(_state, _w, _input);
  7246. // compact input buffer every 2K or if empty
  7247. if(_input.read > 2048 || _input.length() === 0) {
  7248. _input.compact();
  7249. }
  7250. return md;
  7251. };
  7252. /**
  7253. * Produces the digest.
  7254. *
  7255. * @return a byte buffer containing the digest value.
  7256. */
  7257. md.digest = function() {
  7258. /* Note: Here we copy the remaining bytes in the input buffer and
  7259. add the appropriate SHA-256 padding. Then we do the final update
  7260. on a copy of the state so that if the user wants to get
  7261. intermediate digests they can do so. */
  7262. /* Determine the number of bytes that must be added to the message
  7263. to ensure its length is congruent to 448 mod 512. In other words,
  7264. the data to be digested must be a multiple of 512 bits (or 128 bytes).
  7265. This data includes the message, some padding, and the length of the
  7266. message. Since the length of the message will be encoded as 8 bytes (64
  7267. bits), that means that the last segment of the data must have 56 bytes
  7268. (448 bits) of message and padding. Therefore, the length of the message
  7269. plus the padding must be congruent to 448 mod 512 because
  7270. 512 - 128 = 448.
  7271. In order to fill up the message length it must be filled with
  7272. padding that begins with 1 bit followed by all 0 bits. Padding
  7273. must *always* be present, so if the message length is already
  7274. congruent to 448 mod 512, then 512 padding bits must be added. */
  7275. var finalBlock = forge$g.util.createBuffer();
  7276. finalBlock.putBytes(_input.bytes());
  7277. // compute remaining size to be digested (include message length size)
  7278. var remaining = (
  7279. md.fullMessageLength[md.fullMessageLength.length - 1] +
  7280. md.messageLengthSize);
  7281. // add padding for overflow blockSize - overflow
  7282. // _padding starts with 1 byte with first bit is set (byte value 128), then
  7283. // there may be up to (blockSize - 1) other pad bytes
  7284. var overflow = remaining & (md.blockLength - 1);
  7285. finalBlock.putBytes(_padding$1.substr(0, md.blockLength - overflow));
  7286. // serialize message length in bits in big-endian order; since length
  7287. // is stored in bytes we multiply by 8 and add carry from next int
  7288. var next, carry;
  7289. var bits = md.fullMessageLength[0] * 8;
  7290. for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {
  7291. next = md.fullMessageLength[i + 1] * 8;
  7292. carry = (next / 0x100000000) >>> 0;
  7293. bits += carry;
  7294. finalBlock.putInt32(bits >>> 0);
  7295. bits = next >>> 0;
  7296. }
  7297. finalBlock.putInt32(bits);
  7298. var s2 = {
  7299. h0: _state.h0,
  7300. h1: _state.h1,
  7301. h2: _state.h2,
  7302. h3: _state.h3,
  7303. h4: _state.h4,
  7304. h5: _state.h5,
  7305. h6: _state.h6,
  7306. h7: _state.h7
  7307. };
  7308. _update$1(s2, _w, finalBlock);
  7309. var rval = forge$g.util.createBuffer();
  7310. rval.putInt32(s2.h0);
  7311. rval.putInt32(s2.h1);
  7312. rval.putInt32(s2.h2);
  7313. rval.putInt32(s2.h3);
  7314. rval.putInt32(s2.h4);
  7315. rval.putInt32(s2.h5);
  7316. rval.putInt32(s2.h6);
  7317. rval.putInt32(s2.h7);
  7318. return rval;
  7319. };
  7320. return md;
  7321. };
  7322. // sha-256 padding bytes not initialized yet
  7323. var _padding$1 = null;
  7324. var _initialized$1 = false;
  7325. // table of constants
  7326. var _k = null;
  7327. /**
  7328. * Initializes the constant tables.
  7329. */
  7330. function _init$1() {
  7331. // create padding
  7332. _padding$1 = String.fromCharCode(128);
  7333. _padding$1 += forge$g.util.fillString(String.fromCharCode(0x00), 64);
  7334. // create K table for SHA-256
  7335. _k = [
  7336. 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
  7337. 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
  7338. 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
  7339. 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
  7340. 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
  7341. 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
  7342. 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
  7343. 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
  7344. 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
  7345. 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
  7346. 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
  7347. 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
  7348. 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
  7349. 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
  7350. 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
  7351. 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];
  7352. // now initialized
  7353. _initialized$1 = true;
  7354. }
  7355. /**
  7356. * Updates a SHA-256 state with the given byte buffer.
  7357. *
  7358. * @param s the SHA-256 state to update.
  7359. * @param w the array to use to store words.
  7360. * @param bytes the byte buffer to update with.
  7361. */
  7362. function _update$1(s, w, bytes) {
  7363. // consume 512 bit (64 byte) chunks
  7364. var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h;
  7365. var len = bytes.length();
  7366. while(len >= 64) {
  7367. // the w array will be populated with sixteen 32-bit big-endian words
  7368. // and then extended into 64 32-bit words according to SHA-256
  7369. for(i = 0; i < 16; ++i) {
  7370. w[i] = bytes.getInt32();
  7371. }
  7372. for(; i < 64; ++i) {
  7373. // XOR word 2 words ago rot right 17, rot right 19, shft right 10
  7374. t1 = w[i - 2];
  7375. t1 =
  7376. ((t1 >>> 17) | (t1 << 15)) ^
  7377. ((t1 >>> 19) | (t1 << 13)) ^
  7378. (t1 >>> 10);
  7379. // XOR word 15 words ago rot right 7, rot right 18, shft right 3
  7380. t2 = w[i - 15];
  7381. t2 =
  7382. ((t2 >>> 7) | (t2 << 25)) ^
  7383. ((t2 >>> 18) | (t2 << 14)) ^
  7384. (t2 >>> 3);
  7385. // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^32
  7386. w[i] = (t1 + w[i - 7] + t2 + w[i - 16]) | 0;
  7387. }
  7388. // initialize hash value for this chunk
  7389. a = s.h0;
  7390. b = s.h1;
  7391. c = s.h2;
  7392. d = s.h3;
  7393. e = s.h4;
  7394. f = s.h5;
  7395. g = s.h6;
  7396. h = s.h7;
  7397. // round function
  7398. for(i = 0; i < 64; ++i) {
  7399. // Sum1(e)
  7400. s1 =
  7401. ((e >>> 6) | (e << 26)) ^
  7402. ((e >>> 11) | (e << 21)) ^
  7403. ((e >>> 25) | (e << 7));
  7404. // Ch(e, f, g) (optimized the same way as SHA-1)
  7405. ch = g ^ (e & (f ^ g));
  7406. // Sum0(a)
  7407. s0 =
  7408. ((a >>> 2) | (a << 30)) ^
  7409. ((a >>> 13) | (a << 19)) ^
  7410. ((a >>> 22) | (a << 10));
  7411. // Maj(a, b, c) (optimized the same way as SHA-1)
  7412. maj = (a & b) | (c & (a ^ b));
  7413. // main algorithm
  7414. t1 = h + s1 + ch + _k[i] + w[i];
  7415. t2 = s0 + maj;
  7416. h = g;
  7417. g = f;
  7418. f = e;
  7419. // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug
  7420. // can't truncate with `| 0`
  7421. e = (d + t1) >>> 0;
  7422. d = c;
  7423. c = b;
  7424. b = a;
  7425. // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug
  7426. // can't truncate with `| 0`
  7427. a = (t1 + t2) >>> 0;
  7428. }
  7429. // update hash state
  7430. s.h0 = (s.h0 + a) | 0;
  7431. s.h1 = (s.h1 + b) | 0;
  7432. s.h2 = (s.h2 + c) | 0;
  7433. s.h3 = (s.h3 + d) | 0;
  7434. s.h4 = (s.h4 + e) | 0;
  7435. s.h5 = (s.h5 + f) | 0;
  7436. s.h6 = (s.h6 + g) | 0;
  7437. s.h7 = (s.h7 + h) | 0;
  7438. len -= 64;
  7439. }
  7440. }
  7441. /**
  7442. * A javascript implementation of a cryptographically-secure
  7443. * Pseudo Random Number Generator (PRNG). The Fortuna algorithm is followed
  7444. * here though the use of SHA-256 is not enforced; when generating an
  7445. * a PRNG context, the hashing algorithm and block cipher used for
  7446. * the generator are specified via a plugin.
  7447. *
  7448. * @author Dave Longley
  7449. *
  7450. * Copyright (c) 2010-2014 Digital Bazaar, Inc.
  7451. */
  7452. var forge$f = forge$s;
  7453. var _crypto$1 = null;
  7454. if(forge$f.util.isNodejs && !forge$f.options.usePureJavaScript &&
  7455. !process.versions['node-webkit']) {
  7456. _crypto$1 = require$$1__default;
  7457. }
  7458. /* PRNG API */
  7459. var prng = forge$f.prng = forge$f.prng || {};
  7460. /**
  7461. * Creates a new PRNG context.
  7462. *
  7463. * A PRNG plugin must be passed in that will provide:
  7464. *
  7465. * 1. A function that initializes the key and seed of a PRNG context. It
  7466. * will be given a 16 byte key and a 16 byte seed. Any key expansion
  7467. * or transformation of the seed from a byte string into an array of
  7468. * integers (or similar) should be performed.
  7469. * 2. The cryptographic function used by the generator. It takes a key and
  7470. * a seed.
  7471. * 3. A seed increment function. It takes the seed and returns seed + 1.
  7472. * 4. An api to create a message digest.
  7473. *
  7474. * For an example, see random.js.
  7475. *
  7476. * @param plugin the PRNG plugin to use.
  7477. */
  7478. prng.create = function(plugin) {
  7479. var ctx = {
  7480. plugin: plugin,
  7481. key: null,
  7482. seed: null,
  7483. time: null,
  7484. // number of reseeds so far
  7485. reseeds: 0,
  7486. // amount of data generated so far
  7487. generated: 0,
  7488. // no initial key bytes
  7489. keyBytes: ''
  7490. };
  7491. // create 32 entropy pools (each is a message digest)
  7492. var md = plugin.md;
  7493. var pools = new Array(32);
  7494. for(var i = 0; i < 32; ++i) {
  7495. pools[i] = md.create();
  7496. }
  7497. ctx.pools = pools;
  7498. // entropy pools are written to cyclically, starting at index 0
  7499. ctx.pool = 0;
  7500. /**
  7501. * Generates random bytes. The bytes may be generated synchronously or
  7502. * asynchronously. Web workers must use the asynchronous interface or
  7503. * else the behavior is undefined.
  7504. *
  7505. * @param count the number of random bytes to generate.
  7506. * @param [callback(err, bytes)] called once the operation completes.
  7507. *
  7508. * @return count random bytes as a string.
  7509. */
  7510. ctx.generate = function(count, callback) {
  7511. // do synchronously
  7512. if(!callback) {
  7513. return ctx.generateSync(count);
  7514. }
  7515. // simple generator using counter-based CBC
  7516. var cipher = ctx.plugin.cipher;
  7517. var increment = ctx.plugin.increment;
  7518. var formatKey = ctx.plugin.formatKey;
  7519. var formatSeed = ctx.plugin.formatSeed;
  7520. var b = forge$f.util.createBuffer();
  7521. // paranoid deviation from Fortuna:
  7522. // reset key for every request to protect previously
  7523. // generated random bytes should the key be discovered;
  7524. // there is no 100ms based reseeding because of this
  7525. // forced reseed for every `generate` call
  7526. ctx.key = null;
  7527. generate();
  7528. function generate(err) {
  7529. if(err) {
  7530. return callback(err);
  7531. }
  7532. // sufficient bytes generated
  7533. if(b.length() >= count) {
  7534. return callback(null, b.getBytes(count));
  7535. }
  7536. // if amount of data generated is greater than 1 MiB, trigger reseed
  7537. if(ctx.generated > 0xfffff) {
  7538. ctx.key = null;
  7539. }
  7540. if(ctx.key === null) {
  7541. // prevent stack overflow
  7542. return forge$f.util.nextTick(function() {
  7543. _reseed(generate);
  7544. });
  7545. }
  7546. // generate the random bytes
  7547. var bytes = cipher(ctx.key, ctx.seed);
  7548. ctx.generated += bytes.length;
  7549. b.putBytes(bytes);
  7550. // generate bytes for a new key and seed
  7551. ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed)));
  7552. ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));
  7553. forge$f.util.setImmediate(generate);
  7554. }
  7555. };
  7556. /**
  7557. * Generates random bytes synchronously.
  7558. *
  7559. * @param count the number of random bytes to generate.
  7560. *
  7561. * @return count random bytes as a string.
  7562. */
  7563. ctx.generateSync = function(count) {
  7564. // simple generator using counter-based CBC
  7565. var cipher = ctx.plugin.cipher;
  7566. var increment = ctx.plugin.increment;
  7567. var formatKey = ctx.plugin.formatKey;
  7568. var formatSeed = ctx.plugin.formatSeed;
  7569. // paranoid deviation from Fortuna:
  7570. // reset key for every request to protect previously
  7571. // generated random bytes should the key be discovered;
  7572. // there is no 100ms based reseeding because of this
  7573. // forced reseed for every `generateSync` call
  7574. ctx.key = null;
  7575. var b = forge$f.util.createBuffer();
  7576. while(b.length() < count) {
  7577. // if amount of data generated is greater than 1 MiB, trigger reseed
  7578. if(ctx.generated > 0xfffff) {
  7579. ctx.key = null;
  7580. }
  7581. if(ctx.key === null) {
  7582. _reseedSync();
  7583. }
  7584. // generate the random bytes
  7585. var bytes = cipher(ctx.key, ctx.seed);
  7586. ctx.generated += bytes.length;
  7587. b.putBytes(bytes);
  7588. // generate bytes for a new key and seed
  7589. ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed)));
  7590. ctx.seed = formatSeed(cipher(ctx.key, ctx.seed));
  7591. }
  7592. return b.getBytes(count);
  7593. };
  7594. /**
  7595. * Private function that asynchronously reseeds a generator.
  7596. *
  7597. * @param callback(err) called once the operation completes.
  7598. */
  7599. function _reseed(callback) {
  7600. if(ctx.pools[0].messageLength >= 32) {
  7601. _seed();
  7602. return callback();
  7603. }
  7604. // not enough seed data...
  7605. var needed = (32 - ctx.pools[0].messageLength) << 5;
  7606. ctx.seedFile(needed, function(err, bytes) {
  7607. if(err) {
  7608. return callback(err);
  7609. }
  7610. ctx.collect(bytes);
  7611. _seed();
  7612. callback();
  7613. });
  7614. }
  7615. /**
  7616. * Private function that synchronously reseeds a generator.
  7617. */
  7618. function _reseedSync() {
  7619. if(ctx.pools[0].messageLength >= 32) {
  7620. return _seed();
  7621. }
  7622. // not enough seed data...
  7623. var needed = (32 - ctx.pools[0].messageLength) << 5;
  7624. ctx.collect(ctx.seedFileSync(needed));
  7625. _seed();
  7626. }
  7627. /**
  7628. * Private function that seeds a generator once enough bytes are available.
  7629. */
  7630. function _seed() {
  7631. // update reseed count
  7632. ctx.reseeds = (ctx.reseeds === 0xffffffff) ? 0 : ctx.reseeds + 1;
  7633. // goal is to update `key` via:
  7634. // key = hash(key + s)
  7635. // where 's' is all collected entropy from selected pools, then...
  7636. // create a plugin-based message digest
  7637. var md = ctx.plugin.md.create();
  7638. // consume current key bytes
  7639. md.update(ctx.keyBytes);
  7640. // digest the entropy of pools whose index k meet the
  7641. // condition 'n mod 2^k == 0' where n is the number of reseeds
  7642. var _2powK = 1;
  7643. for(var k = 0; k < 32; ++k) {
  7644. if(ctx.reseeds % _2powK === 0) {
  7645. md.update(ctx.pools[k].digest().getBytes());
  7646. ctx.pools[k].start();
  7647. }
  7648. _2powK = _2powK << 1;
  7649. }
  7650. // get digest for key bytes
  7651. ctx.keyBytes = md.digest().getBytes();
  7652. // paranoid deviation from Fortuna:
  7653. // update `seed` via `seed = hash(key)`
  7654. // instead of initializing to zero once and only
  7655. // ever incrementing it
  7656. md.start();
  7657. md.update(ctx.keyBytes);
  7658. var seedBytes = md.digest().getBytes();
  7659. // update state
  7660. ctx.key = ctx.plugin.formatKey(ctx.keyBytes);
  7661. ctx.seed = ctx.plugin.formatSeed(seedBytes);
  7662. ctx.generated = 0;
  7663. }
  7664. /**
  7665. * The built-in default seedFile. This seedFile is used when entropy
  7666. * is needed immediately.
  7667. *
  7668. * @param needed the number of bytes that are needed.
  7669. *
  7670. * @return the random bytes.
  7671. */
  7672. function defaultSeedFile(needed) {
  7673. // use window.crypto.getRandomValues strong source of entropy if available
  7674. var getRandomValues = null;
  7675. var globalScope = forge$f.util.globalScope;
  7676. var _crypto = globalScope.crypto || globalScope.msCrypto;
  7677. if(_crypto && _crypto.getRandomValues) {
  7678. getRandomValues = function(arr) {
  7679. return _crypto.getRandomValues(arr);
  7680. };
  7681. }
  7682. var b = forge$f.util.createBuffer();
  7683. if(getRandomValues) {
  7684. while(b.length() < needed) {
  7685. // max byte length is 65536 before QuotaExceededError is thrown
  7686. // http://www.w3.org/TR/WebCryptoAPI/#RandomSource-method-getRandomValues
  7687. var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4);
  7688. var entropy = new Uint32Array(Math.floor(count));
  7689. try {
  7690. getRandomValues(entropy);
  7691. for(var i = 0; i < entropy.length; ++i) {
  7692. b.putInt32(entropy[i]);
  7693. }
  7694. } catch(e) {
  7695. /* only ignore QuotaExceededError */
  7696. if(!(typeof QuotaExceededError !== 'undefined' &&
  7697. e instanceof QuotaExceededError)) {
  7698. throw e;
  7699. }
  7700. }
  7701. }
  7702. }
  7703. // be sad and add some weak random data
  7704. if(b.length() < needed) {
  7705. /* Draws from Park-Miller "minimal standard" 31 bit PRNG,
  7706. implemented with David G. Carta's optimization: with 32 bit math
  7707. and without division (Public Domain). */
  7708. var hi, lo, next;
  7709. var seed = Math.floor(Math.random() * 0x010000);
  7710. while(b.length() < needed) {
  7711. lo = 16807 * (seed & 0xFFFF);
  7712. hi = 16807 * (seed >> 16);
  7713. lo += (hi & 0x7FFF) << 16;
  7714. lo += hi >> 15;
  7715. lo = (lo & 0x7FFFFFFF) + (lo >> 31);
  7716. seed = lo & 0xFFFFFFFF;
  7717. // consume lower 3 bytes of seed
  7718. for(var i = 0; i < 3; ++i) {
  7719. // throw in more pseudo random
  7720. next = seed >>> (i << 3);
  7721. next ^= Math.floor(Math.random() * 0x0100);
  7722. b.putByte(next & 0xFF);
  7723. }
  7724. }
  7725. }
  7726. return b.getBytes(needed);
  7727. }
  7728. // initialize seed file APIs
  7729. if(_crypto$1) {
  7730. // use nodejs async API
  7731. ctx.seedFile = function(needed, callback) {
  7732. _crypto$1.randomBytes(needed, function(err, bytes) {
  7733. if(err) {
  7734. return callback(err);
  7735. }
  7736. callback(null, bytes.toString());
  7737. });
  7738. };
  7739. // use nodejs sync API
  7740. ctx.seedFileSync = function(needed) {
  7741. return _crypto$1.randomBytes(needed).toString();
  7742. };
  7743. } else {
  7744. ctx.seedFile = function(needed, callback) {
  7745. try {
  7746. callback(null, defaultSeedFile(needed));
  7747. } catch(e) {
  7748. callback(e);
  7749. }
  7750. };
  7751. ctx.seedFileSync = defaultSeedFile;
  7752. }
  7753. /**
  7754. * Adds entropy to a prng ctx's accumulator.
  7755. *
  7756. * @param bytes the bytes of entropy as a string.
  7757. */
  7758. ctx.collect = function(bytes) {
  7759. // iterate over pools distributing entropy cyclically
  7760. var count = bytes.length;
  7761. for(var i = 0; i < count; ++i) {
  7762. ctx.pools[ctx.pool].update(bytes.substr(i, 1));
  7763. ctx.pool = (ctx.pool === 31) ? 0 : ctx.pool + 1;
  7764. }
  7765. };
  7766. /**
  7767. * Collects an integer of n bits.
  7768. *
  7769. * @param i the integer entropy.
  7770. * @param n the number of bits in the integer.
  7771. */
  7772. ctx.collectInt = function(i, n) {
  7773. var bytes = '';
  7774. for(var x = 0; x < n; x += 8) {
  7775. bytes += String.fromCharCode((i >> x) & 0xFF);
  7776. }
  7777. ctx.collect(bytes);
  7778. };
  7779. /**
  7780. * Registers a Web Worker to receive immediate entropy from the main thread.
  7781. * This method is required until Web Workers can access the native crypto
  7782. * API. This method should be called twice for each created worker, once in
  7783. * the main thread, and once in the worker itself.
  7784. *
  7785. * @param worker the worker to register.
  7786. */
  7787. ctx.registerWorker = function(worker) {
  7788. // worker receives random bytes
  7789. if(worker === self) {
  7790. ctx.seedFile = function(needed, callback) {
  7791. function listener(e) {
  7792. var data = e.data;
  7793. if(data.forge && data.forge.prng) {
  7794. self.removeEventListener('message', listener);
  7795. callback(data.forge.prng.err, data.forge.prng.bytes);
  7796. }
  7797. }
  7798. self.addEventListener('message', listener);
  7799. self.postMessage({forge: {prng: {needed: needed}}});
  7800. };
  7801. } else {
  7802. // main thread sends random bytes upon request
  7803. var listener = function(e) {
  7804. var data = e.data;
  7805. if(data.forge && data.forge.prng) {
  7806. ctx.seedFile(data.forge.prng.needed, function(err, bytes) {
  7807. worker.postMessage({forge: {prng: {err: err, bytes: bytes}}});
  7808. });
  7809. }
  7810. };
  7811. // TODO: do we need to remove the event listener when the worker dies?
  7812. worker.addEventListener('message', listener);
  7813. }
  7814. };
  7815. return ctx;
  7816. };
  7817. /**
  7818. * An API for getting cryptographically-secure random bytes. The bytes are
  7819. * generated using the Fortuna algorithm devised by Bruce Schneier and
  7820. * Niels Ferguson.
  7821. *
  7822. * Getting strong random bytes is not yet easy to do in javascript. The only
  7823. * truish random entropy that can be collected is from the mouse, keyboard, or
  7824. * from timing with respect to page loads, etc. This generator makes a poor
  7825. * attempt at providing random bytes when those sources haven't yet provided
  7826. * enough entropy to initially seed or to reseed the PRNG.
  7827. *
  7828. * @author Dave Longley
  7829. *
  7830. * Copyright (c) 2009-2014 Digital Bazaar, Inc.
  7831. */
  7832. var forge$e = forge$s;
  7833. (function() {
  7834. // forge.random already defined
  7835. if(forge$e.random && forge$e.random.getBytes) {
  7836. return;
  7837. }
  7838. (function(jQuery) {
  7839. // the default prng plugin, uses AES-128
  7840. var prng_aes = {};
  7841. var _prng_aes_output = new Array(4);
  7842. var _prng_aes_buffer = forge$e.util.createBuffer();
  7843. prng_aes.formatKey = function(key) {
  7844. // convert the key into 32-bit integers
  7845. var tmp = forge$e.util.createBuffer(key);
  7846. key = new Array(4);
  7847. key[0] = tmp.getInt32();
  7848. key[1] = tmp.getInt32();
  7849. key[2] = tmp.getInt32();
  7850. key[3] = tmp.getInt32();
  7851. // return the expanded key
  7852. return forge$e.aes._expandKey(key, false);
  7853. };
  7854. prng_aes.formatSeed = function(seed) {
  7855. // convert seed into 32-bit integers
  7856. var tmp = forge$e.util.createBuffer(seed);
  7857. seed = new Array(4);
  7858. seed[0] = tmp.getInt32();
  7859. seed[1] = tmp.getInt32();
  7860. seed[2] = tmp.getInt32();
  7861. seed[3] = tmp.getInt32();
  7862. return seed;
  7863. };
  7864. prng_aes.cipher = function(key, seed) {
  7865. forge$e.aes._updateBlock(key, seed, _prng_aes_output, false);
  7866. _prng_aes_buffer.putInt32(_prng_aes_output[0]);
  7867. _prng_aes_buffer.putInt32(_prng_aes_output[1]);
  7868. _prng_aes_buffer.putInt32(_prng_aes_output[2]);
  7869. _prng_aes_buffer.putInt32(_prng_aes_output[3]);
  7870. return _prng_aes_buffer.getBytes();
  7871. };
  7872. prng_aes.increment = function(seed) {
  7873. // FIXME: do we care about carry or signed issues?
  7874. ++seed[3];
  7875. return seed;
  7876. };
  7877. prng_aes.md = forge$e.md.sha256;
  7878. /**
  7879. * Creates a new PRNG.
  7880. */
  7881. function spawnPrng() {
  7882. var ctx = forge$e.prng.create(prng_aes);
  7883. /**
  7884. * Gets random bytes. If a native secure crypto API is unavailable, this
  7885. * method tries to make the bytes more unpredictable by drawing from data that
  7886. * can be collected from the user of the browser, eg: mouse movement.
  7887. *
  7888. * If a callback is given, this method will be called asynchronously.
  7889. *
  7890. * @param count the number of random bytes to get.
  7891. * @param [callback(err, bytes)] called once the operation completes.
  7892. *
  7893. * @return the random bytes in a string.
  7894. */
  7895. ctx.getBytes = function(count, callback) {
  7896. return ctx.generate(count, callback);
  7897. };
  7898. /**
  7899. * Gets random bytes asynchronously. If a native secure crypto API is
  7900. * unavailable, this method tries to make the bytes more unpredictable by
  7901. * drawing from data that can be collected from the user of the browser,
  7902. * eg: mouse movement.
  7903. *
  7904. * @param count the number of random bytes to get.
  7905. *
  7906. * @return the random bytes in a string.
  7907. */
  7908. ctx.getBytesSync = function(count) {
  7909. return ctx.generate(count);
  7910. };
  7911. return ctx;
  7912. }
  7913. // create default prng context
  7914. var _ctx = spawnPrng();
  7915. // add other sources of entropy only if window.crypto.getRandomValues is not
  7916. // available -- otherwise this source will be automatically used by the prng
  7917. var getRandomValues = null;
  7918. var globalScope = forge$e.util.globalScope;
  7919. var _crypto = globalScope.crypto || globalScope.msCrypto;
  7920. if(_crypto && _crypto.getRandomValues) {
  7921. getRandomValues = function(arr) {
  7922. return _crypto.getRandomValues(arr);
  7923. };
  7924. }
  7925. if((!forge$e.util.isNodejs && !getRandomValues)) {
  7926. // get load time entropy
  7927. _ctx.collectInt(+new Date(), 32);
  7928. // add some entropy from navigator object
  7929. if(typeof(navigator) !== 'undefined') {
  7930. var _navBytes = '';
  7931. for(var key in navigator) {
  7932. try {
  7933. if(typeof(navigator[key]) == 'string') {
  7934. _navBytes += navigator[key];
  7935. }
  7936. } catch(e) {
  7937. /* Some navigator keys might not be accessible, e.g. the geolocation
  7938. attribute throws an exception if touched in Mozilla chrome://
  7939. context.
  7940. Silently ignore this and just don't use this as a source of
  7941. entropy. */
  7942. }
  7943. }
  7944. _ctx.collect(_navBytes);
  7945. _navBytes = null;
  7946. }
  7947. // add mouse and keyboard collectors if jquery is available
  7948. if(jQuery) {
  7949. // set up mouse entropy capture
  7950. jQuery().mousemove(function(e) {
  7951. // add mouse coords
  7952. _ctx.collectInt(e.clientX, 16);
  7953. _ctx.collectInt(e.clientY, 16);
  7954. });
  7955. // set up keyboard entropy capture
  7956. jQuery().keypress(function(e) {
  7957. _ctx.collectInt(e.charCode, 8);
  7958. });
  7959. }
  7960. }
  7961. /* Random API */
  7962. if(!forge$e.random) {
  7963. forge$e.random = _ctx;
  7964. } else {
  7965. // extend forge.random with _ctx
  7966. for(var key in _ctx) {
  7967. forge$e.random[key] = _ctx[key];
  7968. }
  7969. }
  7970. // expose spawn PRNG
  7971. forge$e.random.createInstance = spawnPrng;
  7972. })(typeof(jQuery) !== 'undefined' ? jQuery : null);
  7973. })();
  7974. /**
  7975. * RC2 implementation.
  7976. *
  7977. * @author Stefan Siegl
  7978. *
  7979. * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>
  7980. *
  7981. * Information on the RC2 cipher is available from RFC #2268,
  7982. * http://www.ietf.org/rfc/rfc2268.txt
  7983. */
  7984. var forge$d = forge$s;
  7985. var piTable = [
  7986. 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d,
  7987. 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2,
  7988. 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32,
  7989. 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82,
  7990. 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc,
  7991. 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26,
  7992. 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03,
  7993. 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7,
  7994. 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a,
  7995. 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec,
  7996. 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39,
  7997. 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31,
  7998. 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9,
  7999. 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9,
  8000. 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e,
  8001. 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad
  8002. ];
  8003. var s = [1, 2, 3, 5];
  8004. /**
  8005. * Rotate a word left by given number of bits.
  8006. *
  8007. * Bits that are shifted out on the left are put back in on the right
  8008. * hand side.
  8009. *
  8010. * @param word The word to shift left.
  8011. * @param bits The number of bits to shift by.
  8012. * @return The rotated word.
  8013. */
  8014. var rol = function(word, bits) {
  8015. return ((word << bits) & 0xffff) | ((word & 0xffff) >> (16 - bits));
  8016. };
  8017. /**
  8018. * Rotate a word right by given number of bits.
  8019. *
  8020. * Bits that are shifted out on the right are put back in on the left
  8021. * hand side.
  8022. *
  8023. * @param word The word to shift right.
  8024. * @param bits The number of bits to shift by.
  8025. * @return The rotated word.
  8026. */
  8027. var ror = function(word, bits) {
  8028. return ((word & 0xffff) >> bits) | ((word << (16 - bits)) & 0xffff);
  8029. };
  8030. /* RC2 API */
  8031. forge$d.rc2 = forge$d.rc2 || {};
  8032. /**
  8033. * Perform RC2 key expansion as per RFC #2268, section 2.
  8034. *
  8035. * @param key variable-length user key (between 1 and 128 bytes)
  8036. * @param effKeyBits number of effective key bits (default: 128)
  8037. * @return the expanded RC2 key (ByteBuffer of 128 bytes)
  8038. */
  8039. forge$d.rc2.expandKey = function(key, effKeyBits) {
  8040. if(typeof key === 'string') {
  8041. key = forge$d.util.createBuffer(key);
  8042. }
  8043. effKeyBits = effKeyBits || 128;
  8044. /* introduce variables that match the names used in RFC #2268 */
  8045. var L = key;
  8046. var T = key.length();
  8047. var T1 = effKeyBits;
  8048. var T8 = Math.ceil(T1 / 8);
  8049. var TM = 0xff >> (T1 & 0x07);
  8050. var i;
  8051. for(i = T; i < 128; i++) {
  8052. L.putByte(piTable[(L.at(i - 1) + L.at(i - T)) & 0xff]);
  8053. }
  8054. L.setAt(128 - T8, piTable[L.at(128 - T8) & TM]);
  8055. for(i = 127 - T8; i >= 0; i--) {
  8056. L.setAt(i, piTable[L.at(i + 1) ^ L.at(i + T8)]);
  8057. }
  8058. return L;
  8059. };
  8060. /**
  8061. * Creates a RC2 cipher object.
  8062. *
  8063. * @param key the symmetric key to use (as base for key generation).
  8064. * @param bits the number of effective key bits.
  8065. * @param encrypt false for decryption, true for encryption.
  8066. *
  8067. * @return the cipher.
  8068. */
  8069. var createCipher = function(key, bits, encrypt) {
  8070. var _finish = false, _input = null, _output = null, _iv = null;
  8071. var mixRound, mashRound;
  8072. var i, j, K = [];
  8073. /* Expand key and fill into K[] Array */
  8074. key = forge$d.rc2.expandKey(key, bits);
  8075. for(i = 0; i < 64; i++) {
  8076. K.push(key.getInt16Le());
  8077. }
  8078. if(encrypt) {
  8079. /**
  8080. * Perform one mixing round "in place".
  8081. *
  8082. * @param R Array of four words to perform mixing on.
  8083. */
  8084. mixRound = function(R) {
  8085. for(i = 0; i < 4; i++) {
  8086. R[i] += K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) +
  8087. ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);
  8088. R[i] = rol(R[i], s[i]);
  8089. j++;
  8090. }
  8091. };
  8092. /**
  8093. * Perform one mashing round "in place".
  8094. *
  8095. * @param R Array of four words to perform mashing on.
  8096. */
  8097. mashRound = function(R) {
  8098. for(i = 0; i < 4; i++) {
  8099. R[i] += K[R[(i + 3) % 4] & 63];
  8100. }
  8101. };
  8102. } else {
  8103. /**
  8104. * Perform one r-mixing round "in place".
  8105. *
  8106. * @param R Array of four words to perform mixing on.
  8107. */
  8108. mixRound = function(R) {
  8109. for(i = 3; i >= 0; i--) {
  8110. R[i] = ror(R[i], s[i]);
  8111. R[i] -= K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) +
  8112. ((~R[(i + 3) % 4]) & R[(i + 1) % 4]);
  8113. j--;
  8114. }
  8115. };
  8116. /**
  8117. * Perform one r-mashing round "in place".
  8118. *
  8119. * @param R Array of four words to perform mashing on.
  8120. */
  8121. mashRound = function(R) {
  8122. for(i = 3; i >= 0; i--) {
  8123. R[i] -= K[R[(i + 3) % 4] & 63];
  8124. }
  8125. };
  8126. }
  8127. /**
  8128. * Run the specified cipher execution plan.
  8129. *
  8130. * This function takes four words from the input buffer, applies the IV on
  8131. * it (if requested) and runs the provided execution plan.
  8132. *
  8133. * The plan must be put together in form of a array of arrays. Where the
  8134. * outer one is simply a list of steps to perform and the inner one needs
  8135. * to have two elements: the first one telling how many rounds to perform,
  8136. * the second one telling what to do (i.e. the function to call).
  8137. *
  8138. * @param {Array} plan The plan to execute.
  8139. */
  8140. var runPlan = function(plan) {
  8141. var R = [];
  8142. /* Get data from input buffer and fill the four words into R */
  8143. for(i = 0; i < 4; i++) {
  8144. var val = _input.getInt16Le();
  8145. if(_iv !== null) {
  8146. if(encrypt) {
  8147. /* We're encrypting, apply the IV first. */
  8148. val ^= _iv.getInt16Le();
  8149. } else {
  8150. /* We're decryption, keep cipher text for next block. */
  8151. _iv.putInt16Le(val);
  8152. }
  8153. }
  8154. R.push(val & 0xffff);
  8155. }
  8156. /* Reset global "j" variable as per spec. */
  8157. j = encrypt ? 0 : 63;
  8158. /* Run execution plan. */
  8159. for(var ptr = 0; ptr < plan.length; ptr++) {
  8160. for(var ctr = 0; ctr < plan[ptr][0]; ctr++) {
  8161. plan[ptr][1](R);
  8162. }
  8163. }
  8164. /* Write back result to output buffer. */
  8165. for(i = 0; i < 4; i++) {
  8166. if(_iv !== null) {
  8167. if(encrypt) {
  8168. /* We're encrypting in CBC-mode, feed back encrypted bytes into
  8169. IV buffer to carry it forward to next block. */
  8170. _iv.putInt16Le(R[i]);
  8171. } else {
  8172. R[i] ^= _iv.getInt16Le();
  8173. }
  8174. }
  8175. _output.putInt16Le(R[i]);
  8176. }
  8177. };
  8178. /* Create cipher object */
  8179. var cipher = null;
  8180. cipher = {
  8181. /**
  8182. * Starts or restarts the encryption or decryption process, whichever
  8183. * was previously configured.
  8184. *
  8185. * To use the cipher in CBC mode, iv may be given either as a string
  8186. * of bytes, or as a byte buffer. For ECB mode, give null as iv.
  8187. *
  8188. * @param iv the initialization vector to use, null for ECB mode.
  8189. * @param output the output the buffer to write to, null to create one.
  8190. */
  8191. start: function(iv, output) {
  8192. if(iv) {
  8193. /* CBC mode */
  8194. if(typeof iv === 'string') {
  8195. iv = forge$d.util.createBuffer(iv);
  8196. }
  8197. }
  8198. _finish = false;
  8199. _input = forge$d.util.createBuffer();
  8200. _output = output || new forge$d.util.createBuffer();
  8201. _iv = iv;
  8202. cipher.output = _output;
  8203. },
  8204. /**
  8205. * Updates the next block.
  8206. *
  8207. * @param input the buffer to read from.
  8208. */
  8209. update: function(input) {
  8210. if(!_finish) {
  8211. // not finishing, so fill the input buffer with more input
  8212. _input.putBuffer(input);
  8213. }
  8214. while(_input.length() >= 8) {
  8215. runPlan([
  8216. [ 5, mixRound ],
  8217. [ 1, mashRound ],
  8218. [ 6, mixRound ],
  8219. [ 1, mashRound ],
  8220. [ 5, mixRound ]
  8221. ]);
  8222. }
  8223. },
  8224. /**
  8225. * Finishes encrypting or decrypting.
  8226. *
  8227. * @param pad a padding function to use, null for PKCS#7 padding,
  8228. * signature(blockSize, buffer, decrypt).
  8229. *
  8230. * @return true if successful, false on error.
  8231. */
  8232. finish: function(pad) {
  8233. var rval = true;
  8234. if(encrypt) {
  8235. if(pad) {
  8236. rval = pad(8, _input, !encrypt);
  8237. } else {
  8238. // add PKCS#7 padding to block (each pad byte is the
  8239. // value of the number of pad bytes)
  8240. var padding = (_input.length() === 8) ? 8 : (8 - _input.length());
  8241. _input.fillWithByte(padding, padding);
  8242. }
  8243. }
  8244. if(rval) {
  8245. // do final update
  8246. _finish = true;
  8247. cipher.update();
  8248. }
  8249. if(!encrypt) {
  8250. // check for error: input data not a multiple of block size
  8251. rval = (_input.length() === 0);
  8252. if(rval) {
  8253. if(pad) {
  8254. rval = pad(8, _output, !encrypt);
  8255. } else {
  8256. // ensure padding byte count is valid
  8257. var len = _output.length();
  8258. var count = _output.at(len - 1);
  8259. if(count > len) {
  8260. rval = false;
  8261. } else {
  8262. // trim off padding bytes
  8263. _output.truncate(count);
  8264. }
  8265. }
  8266. }
  8267. }
  8268. return rval;
  8269. }
  8270. };
  8271. return cipher;
  8272. };
  8273. /**
  8274. * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the
  8275. * given symmetric key. The output will be stored in the 'output' member
  8276. * of the returned cipher.
  8277. *
  8278. * The key and iv may be given as a string of bytes or a byte buffer.
  8279. * The cipher is initialized to use 128 effective key bits.
  8280. *
  8281. * @param key the symmetric key to use.
  8282. * @param iv the initialization vector to use.
  8283. * @param output the buffer to write to, null to create one.
  8284. *
  8285. * @return the cipher.
  8286. */
  8287. forge$d.rc2.startEncrypting = function(key, iv, output) {
  8288. var cipher = forge$d.rc2.createEncryptionCipher(key, 128);
  8289. cipher.start(iv, output);
  8290. return cipher;
  8291. };
  8292. /**
  8293. * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the
  8294. * given symmetric key.
  8295. *
  8296. * The key may be given as a string of bytes or a byte buffer.
  8297. *
  8298. * To start encrypting call start() on the cipher with an iv and optional
  8299. * output buffer.
  8300. *
  8301. * @param key the symmetric key to use.
  8302. *
  8303. * @return the cipher.
  8304. */
  8305. forge$d.rc2.createEncryptionCipher = function(key, bits) {
  8306. return createCipher(key, bits, true);
  8307. };
  8308. /**
  8309. * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the
  8310. * given symmetric key. The output will be stored in the 'output' member
  8311. * of the returned cipher.
  8312. *
  8313. * The key and iv may be given as a string of bytes or a byte buffer.
  8314. * The cipher is initialized to use 128 effective key bits.
  8315. *
  8316. * @param key the symmetric key to use.
  8317. * @param iv the initialization vector to use.
  8318. * @param output the buffer to write to, null to create one.
  8319. *
  8320. * @return the cipher.
  8321. */
  8322. forge$d.rc2.startDecrypting = function(key, iv, output) {
  8323. var cipher = forge$d.rc2.createDecryptionCipher(key, 128);
  8324. cipher.start(iv, output);
  8325. return cipher;
  8326. };
  8327. /**
  8328. * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the
  8329. * given symmetric key.
  8330. *
  8331. * The key may be given as a string of bytes or a byte buffer.
  8332. *
  8333. * To start decrypting call start() on the cipher with an iv and optional
  8334. * output buffer.
  8335. *
  8336. * @param key the symmetric key to use.
  8337. *
  8338. * @return the cipher.
  8339. */
  8340. forge$d.rc2.createDecryptionCipher = function(key, bits) {
  8341. return createCipher(key, bits, false);
  8342. };
  8343. // Copyright (c) 2005 Tom Wu
  8344. // All Rights Reserved.
  8345. // See "LICENSE" for details.
  8346. // Basic JavaScript BN library - subset useful for RSA encryption.
  8347. /*
  8348. Licensing (LICENSE)
  8349. -------------------
  8350. This software is covered under the following copyright:
  8351. */
  8352. /*
  8353. * Copyright (c) 2003-2005 Tom Wu
  8354. * All Rights Reserved.
  8355. *
  8356. * Permission is hereby granted, free of charge, to any person obtaining
  8357. * a copy of this software and associated documentation files (the
  8358. * "Software"), to deal in the Software without restriction, including
  8359. * without limitation the rights to use, copy, modify, merge, publish,
  8360. * distribute, sublicense, and/or sell copies of the Software, and to
  8361. * permit persons to whom the Software is furnished to do so, subject to
  8362. * the following conditions:
  8363. *
  8364. * The above copyright notice and this permission notice shall be
  8365. * included in all copies or substantial portions of the Software.
  8366. *
  8367. * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
  8368. * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
  8369. * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
  8370. *
  8371. * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
  8372. * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER
  8373. * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF
  8374. * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT
  8375. * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  8376. *
  8377. * In addition, the following condition applies:
  8378. *
  8379. * All redistributions must retain an intact copy of this copyright notice
  8380. * and disclaimer.
  8381. */
  8382. /*
  8383. Address all questions regarding this license to:
  8384. Tom Wu
  8385. tjw@cs.Stanford.EDU
  8386. */
  8387. var forge$c = forge$s;
  8388. forge$c.jsbn = forge$c.jsbn || {};
  8389. // Bits per digit
  8390. var dbits;
  8391. // (public) Constructor
  8392. function BigInteger$1(a,b,c) {
  8393. this.data = [];
  8394. if(a != null)
  8395. if("number" == typeof a) this.fromNumber(a,b,c);
  8396. else if(b == null && "string" != typeof a) this.fromString(a,256);
  8397. else this.fromString(a,b);
  8398. }
  8399. forge$c.jsbn.BigInteger = BigInteger$1;
  8400. // return new, unset BigInteger
  8401. function nbi() { return new BigInteger$1(null); }
  8402. // am: Compute w_j += (x*this_i), propagate carries,
  8403. // c is initial carry, returns final carry.
  8404. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue
  8405. // We need to select the fastest one that works in this environment.
  8406. // am1: use a single mult and divide to get the high bits,
  8407. // max digit bits should be 26 because
  8408. // max internal value = 2*dvalue^2-2*dvalue (< 2^53)
  8409. function am1(i,x,w,j,c,n) {
  8410. while(--n >= 0) {
  8411. var v = x*this.data[i++]+w.data[j]+c;
  8412. c = Math.floor(v/0x4000000);
  8413. w.data[j++] = v&0x3ffffff;
  8414. }
  8415. return c;
  8416. }
  8417. // am2 avoids a big mult-and-extract completely.
  8418. // Max digit bits should be <= 30 because we do bitwise ops
  8419. // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
  8420. function am2(i,x,w,j,c,n) {
  8421. var xl = x&0x7fff, xh = x>>15;
  8422. while(--n >= 0) {
  8423. var l = this.data[i]&0x7fff;
  8424. var h = this.data[i++]>>15;
  8425. var m = xh*l+h*xl;
  8426. l = xl*l+((m&0x7fff)<<15)+w.data[j]+(c&0x3fffffff);
  8427. c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);
  8428. w.data[j++] = l&0x3fffffff;
  8429. }
  8430. return c;
  8431. }
  8432. // Alternately, set max digit bits to 28 since some
  8433. // browsers slow down when dealing with 32-bit numbers.
  8434. function am3(i,x,w,j,c,n) {
  8435. var xl = x&0x3fff, xh = x>>14;
  8436. while(--n >= 0) {
  8437. var l = this.data[i]&0x3fff;
  8438. var h = this.data[i++]>>14;
  8439. var m = xh*l+h*xl;
  8440. l = xl*l+((m&0x3fff)<<14)+w.data[j]+c;
  8441. c = (l>>28)+(m>>14)+xh*h;
  8442. w.data[j++] = l&0xfffffff;
  8443. }
  8444. return c;
  8445. }
  8446. // node.js (no browser)
  8447. if(typeof(navigator) === 'undefined')
  8448. {
  8449. BigInteger$1.prototype.am = am3;
  8450. dbits = 28;
  8451. } else if((navigator.appName == "Microsoft Internet Explorer")) {
  8452. BigInteger$1.prototype.am = am2;
  8453. dbits = 30;
  8454. } else if((navigator.appName != "Netscape")) {
  8455. BigInteger$1.prototype.am = am1;
  8456. dbits = 26;
  8457. } else { // Mozilla/Netscape seems to prefer am3
  8458. BigInteger$1.prototype.am = am3;
  8459. dbits = 28;
  8460. }
  8461. BigInteger$1.prototype.DB = dbits;
  8462. BigInteger$1.prototype.DM = ((1<<dbits)-1);
  8463. BigInteger$1.prototype.DV = (1<<dbits);
  8464. var BI_FP = 52;
  8465. BigInteger$1.prototype.FV = Math.pow(2,BI_FP);
  8466. BigInteger$1.prototype.F1 = BI_FP-dbits;
  8467. BigInteger$1.prototype.F2 = 2*dbits-BI_FP;
  8468. // Digit conversions
  8469. var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
  8470. var BI_RC = new Array();
  8471. var rr,vv;
  8472. rr = "0".charCodeAt(0);
  8473. for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv;
  8474. rr = "a".charCodeAt(0);
  8475. for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
  8476. rr = "A".charCodeAt(0);
  8477. for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
  8478. function int2char(n) { return BI_RM.charAt(n); }
  8479. function intAt(s,i) {
  8480. var c = BI_RC[s.charCodeAt(i)];
  8481. return (c==null)?-1:c;
  8482. }
  8483. // (protected) copy this to r
  8484. function bnpCopyTo(r) {
  8485. for(var i = this.t-1; i >= 0; --i) r.data[i] = this.data[i];
  8486. r.t = this.t;
  8487. r.s = this.s;
  8488. }
  8489. // (protected) set from integer value x, -DV <= x < DV
  8490. function bnpFromInt(x) {
  8491. this.t = 1;
  8492. this.s = (x<0)?-1:0;
  8493. if(x > 0) this.data[0] = x;
  8494. else if(x < -1) this.data[0] = x+this.DV;
  8495. else this.t = 0;
  8496. }
  8497. // return bigint initialized to value
  8498. function nbv(i) { var r = nbi(); r.fromInt(i); return r; }
  8499. // (protected) set from string and radix
  8500. function bnpFromString(s,b) {
  8501. var k;
  8502. if(b == 16) k = 4;
  8503. else if(b == 8) k = 3;
  8504. else if(b == 256) k = 8; // byte array
  8505. else if(b == 2) k = 1;
  8506. else if(b == 32) k = 5;
  8507. else if(b == 4) k = 2;
  8508. else { this.fromRadix(s,b); return; }
  8509. this.t = 0;
  8510. this.s = 0;
  8511. var i = s.length, mi = false, sh = 0;
  8512. while(--i >= 0) {
  8513. var x = (k==8)?s[i]&0xff:intAt(s,i);
  8514. if(x < 0) {
  8515. if(s.charAt(i) == "-") mi = true;
  8516. continue;
  8517. }
  8518. mi = false;
  8519. if(sh == 0)
  8520. this.data[this.t++] = x;
  8521. else if(sh+k > this.DB) {
  8522. this.data[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh;
  8523. this.data[this.t++] = (x>>(this.DB-sh));
  8524. } else
  8525. this.data[this.t-1] |= x<<sh;
  8526. sh += k;
  8527. if(sh >= this.DB) sh -= this.DB;
  8528. }
  8529. if(k == 8 && (s[0]&0x80) != 0) {
  8530. this.s = -1;
  8531. if(sh > 0) this.data[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh;
  8532. }
  8533. this.clamp();
  8534. if(mi) BigInteger$1.ZERO.subTo(this,this);
  8535. }
  8536. // (protected) clamp off excess high words
  8537. function bnpClamp() {
  8538. var c = this.s&this.DM;
  8539. while(this.t > 0 && this.data[this.t-1] == c) --this.t;
  8540. }
  8541. // (public) return string representation in given radix
  8542. function bnToString(b) {
  8543. if(this.s < 0) return "-"+this.negate().toString(b);
  8544. var k;
  8545. if(b == 16) k = 4;
  8546. else if(b == 8) k = 3;
  8547. else if(b == 2) k = 1;
  8548. else if(b == 32) k = 5;
  8549. else if(b == 4) k = 2;
  8550. else return this.toRadix(b);
  8551. var km = (1<<k)-1, d, m = false, r = "", i = this.t;
  8552. var p = this.DB-(i*this.DB)%k;
  8553. if(i-- > 0) {
  8554. if(p < this.DB && (d = this.data[i]>>p) > 0) { m = true; r = int2char(d); }
  8555. while(i >= 0) {
  8556. if(p < k) {
  8557. d = (this.data[i]&((1<<p)-1))<<(k-p);
  8558. d |= this.data[--i]>>(p+=this.DB-k);
  8559. } else {
  8560. d = (this.data[i]>>(p-=k))&km;
  8561. if(p <= 0) { p += this.DB; --i; }
  8562. }
  8563. if(d > 0) m = true;
  8564. if(m) r += int2char(d);
  8565. }
  8566. }
  8567. return m?r:"0";
  8568. }
  8569. // (public) -this
  8570. function bnNegate() { var r = nbi(); BigInteger$1.ZERO.subTo(this,r); return r; }
  8571. // (public) |this|
  8572. function bnAbs() { return (this.s<0)?this.negate():this; }
  8573. // (public) return + if this > a, - if this < a, 0 if equal
  8574. function bnCompareTo(a) {
  8575. var r = this.s-a.s;
  8576. if(r != 0) return r;
  8577. var i = this.t;
  8578. r = i-a.t;
  8579. if(r != 0) return (this.s<0)?-r:r;
  8580. while(--i >= 0) if((r=this.data[i]-a.data[i]) != 0) return r;
  8581. return 0;
  8582. }
  8583. // returns bit length of the integer x
  8584. function nbits(x) {
  8585. var r = 1, t;
  8586. if((t=x>>>16) != 0) { x = t; r += 16; }
  8587. if((t=x>>8) != 0) { x = t; r += 8; }
  8588. if((t=x>>4) != 0) { x = t; r += 4; }
  8589. if((t=x>>2) != 0) { x = t; r += 2; }
  8590. if((t=x>>1) != 0) { x = t; r += 1; }
  8591. return r;
  8592. }
  8593. // (public) return the number of bits in "this"
  8594. function bnBitLength() {
  8595. if(this.t <= 0) return 0;
  8596. return this.DB*(this.t-1)+nbits(this.data[this.t-1]^(this.s&this.DM));
  8597. }
  8598. // (protected) r = this << n*DB
  8599. function bnpDLShiftTo(n,r) {
  8600. var i;
  8601. for(i = this.t-1; i >= 0; --i) r.data[i+n] = this.data[i];
  8602. for(i = n-1; i >= 0; --i) r.data[i] = 0;
  8603. r.t = this.t+n;
  8604. r.s = this.s;
  8605. }
  8606. // (protected) r = this >> n*DB
  8607. function bnpDRShiftTo(n,r) {
  8608. for(var i = n; i < this.t; ++i) r.data[i-n] = this.data[i];
  8609. r.t = Math.max(this.t-n,0);
  8610. r.s = this.s;
  8611. }
  8612. // (protected) r = this << n
  8613. function bnpLShiftTo(n,r) {
  8614. var bs = n%this.DB;
  8615. var cbs = this.DB-bs;
  8616. var bm = (1<<cbs)-1;
  8617. var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i;
  8618. for(i = this.t-1; i >= 0; --i) {
  8619. r.data[i+ds+1] = (this.data[i]>>cbs)|c;
  8620. c = (this.data[i]&bm)<<bs;
  8621. }
  8622. for(i = ds-1; i >= 0; --i) r.data[i] = 0;
  8623. r.data[ds] = c;
  8624. r.t = this.t+ds+1;
  8625. r.s = this.s;
  8626. r.clamp();
  8627. }
  8628. // (protected) r = this >> n
  8629. function bnpRShiftTo(n,r) {
  8630. r.s = this.s;
  8631. var ds = Math.floor(n/this.DB);
  8632. if(ds >= this.t) { r.t = 0; return; }
  8633. var bs = n%this.DB;
  8634. var cbs = this.DB-bs;
  8635. var bm = (1<<bs)-1;
  8636. r.data[0] = this.data[ds]>>bs;
  8637. for(var i = ds+1; i < this.t; ++i) {
  8638. r.data[i-ds-1] |= (this.data[i]&bm)<<cbs;
  8639. r.data[i-ds] = this.data[i]>>bs;
  8640. }
  8641. if(bs > 0) r.data[this.t-ds-1] |= (this.s&bm)<<cbs;
  8642. r.t = this.t-ds;
  8643. r.clamp();
  8644. }
  8645. // (protected) r = this - a
  8646. function bnpSubTo(a,r) {
  8647. var i = 0, c = 0, m = Math.min(a.t,this.t);
  8648. while(i < m) {
  8649. c += this.data[i]-a.data[i];
  8650. r.data[i++] = c&this.DM;
  8651. c >>= this.DB;
  8652. }
  8653. if(a.t < this.t) {
  8654. c -= a.s;
  8655. while(i < this.t) {
  8656. c += this.data[i];
  8657. r.data[i++] = c&this.DM;
  8658. c >>= this.DB;
  8659. }
  8660. c += this.s;
  8661. } else {
  8662. c += this.s;
  8663. while(i < a.t) {
  8664. c -= a.data[i];
  8665. r.data[i++] = c&this.DM;
  8666. c >>= this.DB;
  8667. }
  8668. c -= a.s;
  8669. }
  8670. r.s = (c<0)?-1:0;
  8671. if(c < -1) r.data[i++] = this.DV+c;
  8672. else if(c > 0) r.data[i++] = c;
  8673. r.t = i;
  8674. r.clamp();
  8675. }
  8676. // (protected) r = this * a, r != this,a (HAC 14.12)
  8677. // "this" should be the larger one if appropriate.
  8678. function bnpMultiplyTo(a,r) {
  8679. var x = this.abs(), y = a.abs();
  8680. var i = x.t;
  8681. r.t = i+y.t;
  8682. while(--i >= 0) r.data[i] = 0;
  8683. for(i = 0; i < y.t; ++i) r.data[i+x.t] = x.am(0,y.data[i],r,i,0,x.t);
  8684. r.s = 0;
  8685. r.clamp();
  8686. if(this.s != a.s) BigInteger$1.ZERO.subTo(r,r);
  8687. }
  8688. // (protected) r = this^2, r != this (HAC 14.16)
  8689. function bnpSquareTo(r) {
  8690. var x = this.abs();
  8691. var i = r.t = 2*x.t;
  8692. while(--i >= 0) r.data[i] = 0;
  8693. for(i = 0; i < x.t-1; ++i) {
  8694. var c = x.am(i,x.data[i],r,2*i,0,1);
  8695. 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) {
  8696. r.data[i+x.t] -= x.DV;
  8697. r.data[i+x.t+1] = 1;
  8698. }
  8699. }
  8700. if(r.t > 0) r.data[r.t-1] += x.am(i,x.data[i],r,2*i,0,1);
  8701. r.s = 0;
  8702. r.clamp();
  8703. }
  8704. // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
  8705. // r != q, this != m. q or r may be null.
  8706. function bnpDivRemTo(m,q,r) {
  8707. var pm = m.abs();
  8708. if(pm.t <= 0) return;
  8709. var pt = this.abs();
  8710. if(pt.t < pm.t) {
  8711. if(q != null) q.fromInt(0);
  8712. if(r != null) this.copyTo(r);
  8713. return;
  8714. }
  8715. if(r == null) r = nbi();
  8716. var y = nbi(), ts = this.s, ms = m.s;
  8717. var nsh = this.DB-nbits(pm.data[pm.t-1]); // normalize modulus
  8718. if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); } else { pm.copyTo(y); pt.copyTo(r); }
  8719. var ys = y.t;
  8720. var y0 = y.data[ys-1];
  8721. if(y0 == 0) return;
  8722. var yt = y0*(1<<this.F1)+((ys>1)?y.data[ys-2]>>this.F2:0);
  8723. var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2;
  8724. var i = r.t, j = i-ys, t = (q==null)?nbi():q;
  8725. y.dlShiftTo(j,t);
  8726. if(r.compareTo(t) >= 0) {
  8727. r.data[r.t++] = 1;
  8728. r.subTo(t,r);
  8729. }
  8730. BigInteger$1.ONE.dlShiftTo(ys,t);
  8731. t.subTo(y,y); // "negative" y so we can replace sub with am later
  8732. while(y.t < ys) y.data[y.t++] = 0;
  8733. while(--j >= 0) {
  8734. // Estimate quotient digit
  8735. var qd = (r.data[--i]==y0)?this.DM:Math.floor(r.data[i]*d1+(r.data[i-1]+e)*d2);
  8736. if((r.data[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out
  8737. y.dlShiftTo(j,t);
  8738. r.subTo(t,r);
  8739. while(r.data[i] < --qd) r.subTo(t,r);
  8740. }
  8741. }
  8742. if(q != null) {
  8743. r.drShiftTo(ys,q);
  8744. if(ts != ms) BigInteger$1.ZERO.subTo(q,q);
  8745. }
  8746. r.t = ys;
  8747. r.clamp();
  8748. if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder
  8749. if(ts < 0) BigInteger$1.ZERO.subTo(r,r);
  8750. }
  8751. // (public) this mod a
  8752. function bnMod(a) {
  8753. var r = nbi();
  8754. this.abs().divRemTo(a,null,r);
  8755. if(this.s < 0 && r.compareTo(BigInteger$1.ZERO) > 0) a.subTo(r,r);
  8756. return r;
  8757. }
  8758. // Modular reduction using "classic" algorithm
  8759. function Classic(m) { this.m = m; }
  8760. function cConvert(x) {
  8761. if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);
  8762. else return x;
  8763. }
  8764. function cRevert(x) { return x; }
  8765. function cReduce(x) { x.divRemTo(this.m,null,x); }
  8766. function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
  8767. function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
  8768. Classic.prototype.convert = cConvert;
  8769. Classic.prototype.revert = cRevert;
  8770. Classic.prototype.reduce = cReduce;
  8771. Classic.prototype.mulTo = cMulTo;
  8772. Classic.prototype.sqrTo = cSqrTo;
  8773. // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
  8774. // justification:
  8775. // xy == 1 (mod m)
  8776. // xy = 1+km
  8777. // xy(2-xy) = (1+km)(1-km)
  8778. // x[y(2-xy)] = 1-k^2m^2
  8779. // x[y(2-xy)] == 1 (mod m^2)
  8780. // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
  8781. // should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
  8782. // JS multiply "overflows" differently from C/C++, so care is needed here.
  8783. function bnpInvDigit() {
  8784. if(this.t < 1) return 0;
  8785. var x = this.data[0];
  8786. if((x&1) == 0) return 0;
  8787. var y = x&3; // y == 1/x mod 2^2
  8788. y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4
  8789. y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8
  8790. y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16
  8791. // last step - calculate inverse mod DV directly;
  8792. // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
  8793. y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits
  8794. // we really want the negative inverse, and -DV < y < DV
  8795. return (y>0)?this.DV-y:-y;
  8796. }
  8797. // Montgomery reduction
  8798. function Montgomery(m) {
  8799. this.m = m;
  8800. this.mp = m.invDigit();
  8801. this.mpl = this.mp&0x7fff;
  8802. this.mph = this.mp>>15;
  8803. this.um = (1<<(m.DB-15))-1;
  8804. this.mt2 = 2*m.t;
  8805. }
  8806. // xR mod m
  8807. function montConvert(x) {
  8808. var r = nbi();
  8809. x.abs().dlShiftTo(this.m.t,r);
  8810. r.divRemTo(this.m,null,r);
  8811. if(x.s < 0 && r.compareTo(BigInteger$1.ZERO) > 0) this.m.subTo(r,r);
  8812. return r;
  8813. }
  8814. // x/R mod m
  8815. function montRevert(x) {
  8816. var r = nbi();
  8817. x.copyTo(r);
  8818. this.reduce(r);
  8819. return r;
  8820. }
  8821. // x = x/R mod m (HAC 14.32)
  8822. function montReduce(x) {
  8823. while(x.t <= this.mt2) // pad x so am has enough room later
  8824. x.data[x.t++] = 0;
  8825. for(var i = 0; i < this.m.t; ++i) {
  8826. // faster way of calculating u0 = x.data[i]*mp mod DV
  8827. var j = x.data[i]&0x7fff;
  8828. var u0 = (j*this.mpl+(((j*this.mph+(x.data[i]>>15)*this.mpl)&this.um)<<15))&x.DM;
  8829. // use am to combine the multiply-shift-add into one call
  8830. j = i+this.m.t;
  8831. x.data[j] += this.m.am(0,u0,x,i,0,this.m.t);
  8832. // propagate carry
  8833. while(x.data[j] >= x.DV) { x.data[j] -= x.DV; x.data[++j]++; }
  8834. }
  8835. x.clamp();
  8836. x.drShiftTo(this.m.t,x);
  8837. if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
  8838. }
  8839. // r = "x^2/R mod m"; x != r
  8840. function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
  8841. // r = "xy/R mod m"; x,y != r
  8842. function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
  8843. Montgomery.prototype.convert = montConvert;
  8844. Montgomery.prototype.revert = montRevert;
  8845. Montgomery.prototype.reduce = montReduce;
  8846. Montgomery.prototype.mulTo = montMulTo;
  8847. Montgomery.prototype.sqrTo = montSqrTo;
  8848. // (protected) true iff this is even
  8849. function bnpIsEven() { return ((this.t>0)?(this.data[0]&1):this.s) == 0; }
  8850. // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
  8851. function bnpExp(e,z) {
  8852. if(e > 0xffffffff || e < 1) return BigInteger$1.ONE;
  8853. var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;
  8854. g.copyTo(r);
  8855. while(--i >= 0) {
  8856. z.sqrTo(r,r2);
  8857. if((e&(1<<i)) > 0) z.mulTo(r2,g,r);
  8858. else { var t = r; r = r2; r2 = t; }
  8859. }
  8860. return z.revert(r);
  8861. }
  8862. // (public) this^e % m, 0 <= e < 2^32
  8863. function bnModPowInt(e,m) {
  8864. var z;
  8865. if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);
  8866. return this.exp(e,z);
  8867. }
  8868. // protected
  8869. BigInteger$1.prototype.copyTo = bnpCopyTo;
  8870. BigInteger$1.prototype.fromInt = bnpFromInt;
  8871. BigInteger$1.prototype.fromString = bnpFromString;
  8872. BigInteger$1.prototype.clamp = bnpClamp;
  8873. BigInteger$1.prototype.dlShiftTo = bnpDLShiftTo;
  8874. BigInteger$1.prototype.drShiftTo = bnpDRShiftTo;
  8875. BigInteger$1.prototype.lShiftTo = bnpLShiftTo;
  8876. BigInteger$1.prototype.rShiftTo = bnpRShiftTo;
  8877. BigInteger$1.prototype.subTo = bnpSubTo;
  8878. BigInteger$1.prototype.multiplyTo = bnpMultiplyTo;
  8879. BigInteger$1.prototype.squareTo = bnpSquareTo;
  8880. BigInteger$1.prototype.divRemTo = bnpDivRemTo;
  8881. BigInteger$1.prototype.invDigit = bnpInvDigit;
  8882. BigInteger$1.prototype.isEven = bnpIsEven;
  8883. BigInteger$1.prototype.exp = bnpExp;
  8884. // public
  8885. BigInteger$1.prototype.toString = bnToString;
  8886. BigInteger$1.prototype.negate = bnNegate;
  8887. BigInteger$1.prototype.abs = bnAbs;
  8888. BigInteger$1.prototype.compareTo = bnCompareTo;
  8889. BigInteger$1.prototype.bitLength = bnBitLength;
  8890. BigInteger$1.prototype.mod = bnMod;
  8891. BigInteger$1.prototype.modPowInt = bnModPowInt;
  8892. // "constants"
  8893. BigInteger$1.ZERO = nbv(0);
  8894. BigInteger$1.ONE = nbv(1);
  8895. // jsbn2 lib
  8896. //Copyright (c) 2005-2009 Tom Wu
  8897. //All Rights Reserved.
  8898. //See "LICENSE" for details (See jsbn.js for LICENSE).
  8899. //Extended JavaScript BN functions, required for RSA private ops.
  8900. //Version 1.1: new BigInteger("0", 10) returns "proper" zero
  8901. //(public)
  8902. function bnClone() { var r = nbi(); this.copyTo(r); return r; }
  8903. //(public) return value as integer
  8904. function bnIntValue() {
  8905. if(this.s < 0) {
  8906. if(this.t == 1) return this.data[0]-this.DV;
  8907. else if(this.t == 0) return -1;
  8908. } else if(this.t == 1) return this.data[0];
  8909. else if(this.t == 0) return 0;
  8910. // assumes 16 < DB < 32
  8911. return ((this.data[1]&((1<<(32-this.DB))-1))<<this.DB)|this.data[0];
  8912. }
  8913. //(public) return value as byte
  8914. function bnByteValue() { return (this.t==0)?this.s:(this.data[0]<<24)>>24; }
  8915. //(public) return value as short (assumes DB>=16)
  8916. function bnShortValue() { return (this.t==0)?this.s:(this.data[0]<<16)>>16; }
  8917. //(protected) return x s.t. r^x < DV
  8918. function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); }
  8919. //(public) 0 if this == 0, 1 if this > 0
  8920. function bnSigNum() {
  8921. if(this.s < 0) return -1;
  8922. else if(this.t <= 0 || (this.t == 1 && this.data[0] <= 0)) return 0;
  8923. else return 1;
  8924. }
  8925. //(protected) convert to radix string
  8926. function bnpToRadix(b) {
  8927. if(b == null) b = 10;
  8928. if(this.signum() == 0 || b < 2 || b > 36) return "0";
  8929. var cs = this.chunkSize(b);
  8930. var a = Math.pow(b,cs);
  8931. var d = nbv(a), y = nbi(), z = nbi(), r = "";
  8932. this.divRemTo(d,y,z);
  8933. while(y.signum() > 0) {
  8934. r = (a+z.intValue()).toString(b).substr(1) + r;
  8935. y.divRemTo(d,y,z);
  8936. }
  8937. return z.intValue().toString(b) + r;
  8938. }
  8939. //(protected) convert from radix string
  8940. function bnpFromRadix(s,b) {
  8941. this.fromInt(0);
  8942. if(b == null) b = 10;
  8943. var cs = this.chunkSize(b);
  8944. var d = Math.pow(b,cs), mi = false, j = 0, w = 0;
  8945. for(var i = 0; i < s.length; ++i) {
  8946. var x = intAt(s,i);
  8947. if(x < 0) {
  8948. if(s.charAt(i) == "-" && this.signum() == 0) mi = true;
  8949. continue;
  8950. }
  8951. w = b*w+x;
  8952. if(++j >= cs) {
  8953. this.dMultiply(d);
  8954. this.dAddOffset(w,0);
  8955. j = 0;
  8956. w = 0;
  8957. }
  8958. }
  8959. if(j > 0) {
  8960. this.dMultiply(Math.pow(b,j));
  8961. this.dAddOffset(w,0);
  8962. }
  8963. if(mi) BigInteger$1.ZERO.subTo(this,this);
  8964. }
  8965. //(protected) alternate constructor
  8966. function bnpFromNumber(a,b,c) {
  8967. if("number" == typeof b) {
  8968. // new BigInteger(int,int,RNG)
  8969. if(a < 2) this.fromInt(1);
  8970. else {
  8971. this.fromNumber(a,c);
  8972. if(!this.testBit(a-1)) // force MSB set
  8973. this.bitwiseTo(BigInteger$1.ONE.shiftLeft(a-1),op_or,this);
  8974. if(this.isEven()) this.dAddOffset(1,0); // force odd
  8975. while(!this.isProbablePrime(b)) {
  8976. this.dAddOffset(2,0);
  8977. if(this.bitLength() > a) this.subTo(BigInteger$1.ONE.shiftLeft(a-1),this);
  8978. }
  8979. }
  8980. } else {
  8981. // new BigInteger(int,RNG)
  8982. var x = new Array(), t = a&7;
  8983. x.length = (a>>3)+1;
  8984. b.nextBytes(x);
  8985. if(t > 0) x[0] &= ((1<<t)-1); else x[0] = 0;
  8986. this.fromString(x,256);
  8987. }
  8988. }
  8989. //(public) convert to bigendian byte array
  8990. function bnToByteArray() {
  8991. var i = this.t, r = new Array();
  8992. r[0] = this.s;
  8993. var p = this.DB-(i*this.DB)%8, d, k = 0;
  8994. if(i-- > 0) {
  8995. if(p < this.DB && (d = this.data[i]>>p) != (this.s&this.DM)>>p)
  8996. r[k++] = d|(this.s<<(this.DB-p));
  8997. while(i >= 0) {
  8998. if(p < 8) {
  8999. d = (this.data[i]&((1<<p)-1))<<(8-p);
  9000. d |= this.data[--i]>>(p+=this.DB-8);
  9001. } else {
  9002. d = (this.data[i]>>(p-=8))&0xff;
  9003. if(p <= 0) { p += this.DB; --i; }
  9004. }
  9005. if((d&0x80) != 0) d |= -256;
  9006. if(k == 0 && (this.s&0x80) != (d&0x80)) ++k;
  9007. if(k > 0 || d != this.s) r[k++] = d;
  9008. }
  9009. }
  9010. return r;
  9011. }
  9012. function bnEquals(a) { return(this.compareTo(a)==0); }
  9013. function bnMin(a) { return (this.compareTo(a)<0)?this:a; }
  9014. function bnMax(a) { return (this.compareTo(a)>0)?this:a; }
  9015. //(protected) r = this op a (bitwise)
  9016. function bnpBitwiseTo(a,op,r) {
  9017. var i, f, m = Math.min(a.t,this.t);
  9018. for(i = 0; i < m; ++i) r.data[i] = op(this.data[i],a.data[i]);
  9019. if(a.t < this.t) {
  9020. f = a.s&this.DM;
  9021. for(i = m; i < this.t; ++i) r.data[i] = op(this.data[i],f);
  9022. r.t = this.t;
  9023. } else {
  9024. f = this.s&this.DM;
  9025. for(i = m; i < a.t; ++i) r.data[i] = op(f,a.data[i]);
  9026. r.t = a.t;
  9027. }
  9028. r.s = op(this.s,a.s);
  9029. r.clamp();
  9030. }
  9031. //(public) this & a
  9032. function op_and(x,y) { return x&y; }
  9033. function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }
  9034. //(public) this | a
  9035. function op_or(x,y) { return x|y; }
  9036. function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }
  9037. //(public) this ^ a
  9038. function op_xor(x,y) { return x^y; }
  9039. function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }
  9040. //(public) this & ~a
  9041. function op_andnot(x,y) { return x&~y; }
  9042. function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; }
  9043. //(public) ~this
  9044. function bnNot() {
  9045. var r = nbi();
  9046. for(var i = 0; i < this.t; ++i) r.data[i] = this.DM&~this.data[i];
  9047. r.t = this.t;
  9048. r.s = ~this.s;
  9049. return r;
  9050. }
  9051. //(public) this << n
  9052. function bnShiftLeft(n) {
  9053. var r = nbi();
  9054. if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r);
  9055. return r;
  9056. }
  9057. //(public) this >> n
  9058. function bnShiftRight(n) {
  9059. var r = nbi();
  9060. if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r);
  9061. return r;
  9062. }
  9063. //return index of lowest 1-bit in x, x < 2^31
  9064. function lbit(x) {
  9065. if(x == 0) return -1;
  9066. var r = 0;
  9067. if((x&0xffff) == 0) { x >>= 16; r += 16; }
  9068. if((x&0xff) == 0) { x >>= 8; r += 8; }
  9069. if((x&0xf) == 0) { x >>= 4; r += 4; }
  9070. if((x&3) == 0) { x >>= 2; r += 2; }
  9071. if((x&1) == 0) ++r;
  9072. return r;
  9073. }
  9074. //(public) returns index of lowest 1-bit (or -1 if none)
  9075. function bnGetLowestSetBit() {
  9076. for(var i = 0; i < this.t; ++i)
  9077. if(this.data[i] != 0) return i*this.DB+lbit(this.data[i]);
  9078. if(this.s < 0) return this.t*this.DB;
  9079. return -1;
  9080. }
  9081. //return number of 1 bits in x
  9082. function cbit(x) {
  9083. var r = 0;
  9084. while(x != 0) { x &= x-1; ++r; }
  9085. return r;
  9086. }
  9087. //(public) return number of set bits
  9088. function bnBitCount() {
  9089. var r = 0, x = this.s&this.DM;
  9090. for(var i = 0; i < this.t; ++i) r += cbit(this.data[i]^x);
  9091. return r;
  9092. }
  9093. //(public) true iff nth bit is set
  9094. function bnTestBit(n) {
  9095. var j = Math.floor(n/this.DB);
  9096. if(j >= this.t) return(this.s!=0);
  9097. return((this.data[j]&(1<<(n%this.DB)))!=0);
  9098. }
  9099. //(protected) this op (1<<n)
  9100. function bnpChangeBit(n,op) {
  9101. var r = BigInteger$1.ONE.shiftLeft(n);
  9102. this.bitwiseTo(r,op,r);
  9103. return r;
  9104. }
  9105. //(public) this | (1<<n)
  9106. function bnSetBit(n) { return this.changeBit(n,op_or); }
  9107. //(public) this & ~(1<<n)
  9108. function bnClearBit(n) { return this.changeBit(n,op_andnot); }
  9109. //(public) this ^ (1<<n)
  9110. function bnFlipBit(n) { return this.changeBit(n,op_xor); }
  9111. //(protected) r = this + a
  9112. function bnpAddTo(a,r) {
  9113. var i = 0, c = 0, m = Math.min(a.t,this.t);
  9114. while(i < m) {
  9115. c += this.data[i]+a.data[i];
  9116. r.data[i++] = c&this.DM;
  9117. c >>= this.DB;
  9118. }
  9119. if(a.t < this.t) {
  9120. c += a.s;
  9121. while(i < this.t) {
  9122. c += this.data[i];
  9123. r.data[i++] = c&this.DM;
  9124. c >>= this.DB;
  9125. }
  9126. c += this.s;
  9127. } else {
  9128. c += this.s;
  9129. while(i < a.t) {
  9130. c += a.data[i];
  9131. r.data[i++] = c&this.DM;
  9132. c >>= this.DB;
  9133. }
  9134. c += a.s;
  9135. }
  9136. r.s = (c<0)?-1:0;
  9137. if(c > 0) r.data[i++] = c;
  9138. else if(c < -1) r.data[i++] = this.DV+c;
  9139. r.t = i;
  9140. r.clamp();
  9141. }
  9142. //(public) this + a
  9143. function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }
  9144. //(public) this - a
  9145. function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }
  9146. //(public) this * a
  9147. function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }
  9148. //(public) this / a
  9149. function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }
  9150. //(public) this % a
  9151. function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; }
  9152. //(public) [this/a,this%a]
  9153. function bnDivideAndRemainder(a) {
  9154. var q = nbi(), r = nbi();
  9155. this.divRemTo(a,q,r);
  9156. return new Array(q,r);
  9157. }
  9158. //(protected) this *= n, this >= 0, 1 < n < DV
  9159. function bnpDMultiply(n) {
  9160. this.data[this.t] = this.am(0,n-1,this,0,0,this.t);
  9161. ++this.t;
  9162. this.clamp();
  9163. }
  9164. //(protected) this += n << w words, this >= 0
  9165. function bnpDAddOffset(n,w) {
  9166. if(n == 0) return;
  9167. while(this.t <= w) this.data[this.t++] = 0;
  9168. this.data[w] += n;
  9169. while(this.data[w] >= this.DV) {
  9170. this.data[w] -= this.DV;
  9171. if(++w >= this.t) this.data[this.t++] = 0;
  9172. ++this.data[w];
  9173. }
  9174. }
  9175. //A "null" reducer
  9176. function NullExp() {}
  9177. function nNop(x) { return x; }
  9178. function nMulTo(x,y,r) { x.multiplyTo(y,r); }
  9179. function nSqrTo(x,r) { x.squareTo(r); }
  9180. NullExp.prototype.convert = nNop;
  9181. NullExp.prototype.revert = nNop;
  9182. NullExp.prototype.mulTo = nMulTo;
  9183. NullExp.prototype.sqrTo = nSqrTo;
  9184. //(public) this^e
  9185. function bnPow(e) { return this.exp(e,new NullExp()); }
  9186. //(protected) r = lower n words of "this * a", a.t <= n
  9187. //"this" should be the larger one if appropriate.
  9188. function bnpMultiplyLowerTo(a,n,r) {
  9189. var i = Math.min(this.t+a.t,n);
  9190. r.s = 0; // assumes a,this >= 0
  9191. r.t = i;
  9192. while(i > 0) r.data[--i] = 0;
  9193. var j;
  9194. 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);
  9195. for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a.data[i],r,i,0,n-i);
  9196. r.clamp();
  9197. }
  9198. //(protected) r = "this * a" without lower n words, n > 0
  9199. //"this" should be the larger one if appropriate.
  9200. function bnpMultiplyUpperTo(a,n,r) {
  9201. --n;
  9202. var i = r.t = this.t+a.t-n;
  9203. r.s = 0; // assumes a,this >= 0
  9204. while(--i >= 0) r.data[i] = 0;
  9205. for(i = Math.max(n-this.t,0); i < a.t; ++i)
  9206. r.data[this.t+i-n] = this.am(n-i,a.data[i],r,0,0,this.t+i-n);
  9207. r.clamp();
  9208. r.drShiftTo(1,r);
  9209. }
  9210. //Barrett modular reduction
  9211. function Barrett(m) {
  9212. // setup Barrett
  9213. this.r2 = nbi();
  9214. this.q3 = nbi();
  9215. BigInteger$1.ONE.dlShiftTo(2*m.t,this.r2);
  9216. this.mu = this.r2.divide(m);
  9217. this.m = m;
  9218. }
  9219. function barrettConvert(x) {
  9220. if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m);
  9221. else if(x.compareTo(this.m) < 0) return x;
  9222. else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }
  9223. }
  9224. function barrettRevert(x) { return x; }
  9225. //x = x mod m (HAC 14.42)
  9226. function barrettReduce(x) {
  9227. x.drShiftTo(this.m.t-1,this.r2);
  9228. if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }
  9229. this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);
  9230. this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);
  9231. while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1);
  9232. x.subTo(this.r2,x);
  9233. while(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
  9234. }
  9235. //r = x^2 mod m; x != r
  9236. function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
  9237. //r = x*y mod m; x,y != r
  9238. function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
  9239. Barrett.prototype.convert = barrettConvert;
  9240. Barrett.prototype.revert = barrettRevert;
  9241. Barrett.prototype.reduce = barrettReduce;
  9242. Barrett.prototype.mulTo = barrettMulTo;
  9243. Barrett.prototype.sqrTo = barrettSqrTo;
  9244. //(public) this^e % m (HAC 14.85)
  9245. function bnModPow(e,m) {
  9246. var i = e.bitLength(), k, r = nbv(1), z;
  9247. if(i <= 0) return r;
  9248. else if(i < 18) k = 1;
  9249. else if(i < 48) k = 3;
  9250. else if(i < 144) k = 4;
  9251. else if(i < 768) k = 5;
  9252. else k = 6;
  9253. if(i < 8)
  9254. z = new Classic(m);
  9255. else if(m.isEven())
  9256. z = new Barrett(m);
  9257. else
  9258. z = new Montgomery(m);
  9259. // precomputation
  9260. var g = new Array(), n = 3, k1 = k-1, km = (1<<k)-1;
  9261. g[1] = z.convert(this);
  9262. if(k > 1) {
  9263. var g2 = nbi();
  9264. z.sqrTo(g[1],g2);
  9265. while(n <= km) {
  9266. g[n] = nbi();
  9267. z.mulTo(g2,g[n-2],g[n]);
  9268. n += 2;
  9269. }
  9270. }
  9271. var j = e.t-1, w, is1 = true, r2 = nbi(), t;
  9272. i = nbits(e.data[j])-1;
  9273. while(j >= 0) {
  9274. if(i >= k1) w = (e.data[j]>>(i-k1))&km;
  9275. else {
  9276. w = (e.data[j]&((1<<(i+1))-1))<<(k1-i);
  9277. if(j > 0) w |= e.data[j-1]>>(this.DB+i-k1);
  9278. }
  9279. n = k;
  9280. while((w&1) == 0) { w >>= 1; --n; }
  9281. if((i -= n) < 0) { i += this.DB; --j; }
  9282. if(is1) { // ret == 1, don't bother squaring or multiplying it
  9283. g[w].copyTo(r);
  9284. is1 = false;
  9285. } else {
  9286. while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; }
  9287. if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; }
  9288. z.mulTo(r2,g[w],r);
  9289. }
  9290. while(j >= 0 && (e.data[j]&(1<<i)) == 0) {
  9291. z.sqrTo(r,r2); t = r; r = r2; r2 = t;
  9292. if(--i < 0) { i = this.DB-1; --j; }
  9293. }
  9294. }
  9295. return z.revert(r);
  9296. }
  9297. //(public) gcd(this,a) (HAC 14.54)
  9298. function bnGCD(a) {
  9299. var x = (this.s<0)?this.negate():this.clone();
  9300. var y = (a.s<0)?a.negate():a.clone();
  9301. if(x.compareTo(y) < 0) { var t = x; x = y; y = t; }
  9302. var i = x.getLowestSetBit(), g = y.getLowestSetBit();
  9303. if(g < 0) return x;
  9304. if(i < g) g = i;
  9305. if(g > 0) {
  9306. x.rShiftTo(g,x);
  9307. y.rShiftTo(g,y);
  9308. }
  9309. while(x.signum() > 0) {
  9310. if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x);
  9311. if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y);
  9312. if(x.compareTo(y) >= 0) {
  9313. x.subTo(y,x);
  9314. x.rShiftTo(1,x);
  9315. } else {
  9316. y.subTo(x,y);
  9317. y.rShiftTo(1,y);
  9318. }
  9319. }
  9320. if(g > 0) y.lShiftTo(g,y);
  9321. return y;
  9322. }
  9323. //(protected) this % n, n < 2^26
  9324. function bnpModInt(n) {
  9325. if(n <= 0) return 0;
  9326. var d = this.DV%n, r = (this.s<0)?n-1:0;
  9327. if(this.t > 0)
  9328. if(d == 0) r = this.data[0]%n;
  9329. else for(var i = this.t-1; i >= 0; --i) r = (d*r+this.data[i])%n;
  9330. return r;
  9331. }
  9332. //(public) 1/this % m (HAC 14.61)
  9333. function bnModInverse(m) {
  9334. var ac = m.isEven();
  9335. if((this.isEven() && ac) || m.signum() == 0) return BigInteger$1.ZERO;
  9336. var u = m.clone(), v = this.clone();
  9337. var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);
  9338. while(u.signum() != 0) {
  9339. while(u.isEven()) {
  9340. u.rShiftTo(1,u);
  9341. if(ac) {
  9342. if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); }
  9343. a.rShiftTo(1,a);
  9344. } else if(!b.isEven()) b.subTo(m,b);
  9345. b.rShiftTo(1,b);
  9346. }
  9347. while(v.isEven()) {
  9348. v.rShiftTo(1,v);
  9349. if(ac) {
  9350. if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); }
  9351. c.rShiftTo(1,c);
  9352. } else if(!d.isEven()) d.subTo(m,d);
  9353. d.rShiftTo(1,d);
  9354. }
  9355. if(u.compareTo(v) >= 0) {
  9356. u.subTo(v,u);
  9357. if(ac) a.subTo(c,a);
  9358. b.subTo(d,b);
  9359. } else {
  9360. v.subTo(u,v);
  9361. if(ac) c.subTo(a,c);
  9362. d.subTo(b,d);
  9363. }
  9364. }
  9365. if(v.compareTo(BigInteger$1.ONE) != 0) return BigInteger$1.ZERO;
  9366. if(d.compareTo(m) >= 0) return d.subtract(m);
  9367. if(d.signum() < 0) d.addTo(m,d); else return d;
  9368. if(d.signum() < 0) return d.add(m); else return d;
  9369. }
  9370. 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];
  9371. var lplim = (1<<26)/lowprimes[lowprimes.length-1];
  9372. //(public) test primality with certainty >= 1-.5^t
  9373. function bnIsProbablePrime(t) {
  9374. var i, x = this.abs();
  9375. if(x.t == 1 && x.data[0] <= lowprimes[lowprimes.length-1]) {
  9376. for(i = 0; i < lowprimes.length; ++i)
  9377. if(x.data[0] == lowprimes[i]) return true;
  9378. return false;
  9379. }
  9380. if(x.isEven()) return false;
  9381. i = 1;
  9382. while(i < lowprimes.length) {
  9383. var m = lowprimes[i], j = i+1;
  9384. while(j < lowprimes.length && m < lplim) m *= lowprimes[j++];
  9385. m = x.modInt(m);
  9386. while(i < j) if(m%lowprimes[i++] == 0) return false;
  9387. }
  9388. return x.millerRabin(t);
  9389. }
  9390. //(protected) true if probably prime (HAC 4.24, Miller-Rabin)
  9391. function bnpMillerRabin(t) {
  9392. var n1 = this.subtract(BigInteger$1.ONE);
  9393. var k = n1.getLowestSetBit();
  9394. if(k <= 0) return false;
  9395. var r = n1.shiftRight(k);
  9396. var prng = bnGetPrng();
  9397. var a;
  9398. for(var i = 0; i < t; ++i) {
  9399. // select witness 'a' at random from between 1 and n1
  9400. do {
  9401. a = new BigInteger$1(this.bitLength(), prng);
  9402. }
  9403. while(a.compareTo(BigInteger$1.ONE) <= 0 || a.compareTo(n1) >= 0);
  9404. var y = a.modPow(r,this);
  9405. if(y.compareTo(BigInteger$1.ONE) != 0 && y.compareTo(n1) != 0) {
  9406. var j = 1;
  9407. while(j++ < k && y.compareTo(n1) != 0) {
  9408. y = y.modPowInt(2,this);
  9409. if(y.compareTo(BigInteger$1.ONE) == 0) return false;
  9410. }
  9411. if(y.compareTo(n1) != 0) return false;
  9412. }
  9413. }
  9414. return true;
  9415. }
  9416. // get pseudo random number generator
  9417. function bnGetPrng() {
  9418. // create prng with api that matches BigInteger secure random
  9419. return {
  9420. // x is an array to fill with bytes
  9421. nextBytes: function(x) {
  9422. for(var i = 0; i < x.length; ++i) {
  9423. x[i] = Math.floor(Math.random() * 0x0100);
  9424. }
  9425. }
  9426. };
  9427. }
  9428. //protected
  9429. BigInteger$1.prototype.chunkSize = bnpChunkSize;
  9430. BigInteger$1.prototype.toRadix = bnpToRadix;
  9431. BigInteger$1.prototype.fromRadix = bnpFromRadix;
  9432. BigInteger$1.prototype.fromNumber = bnpFromNumber;
  9433. BigInteger$1.prototype.bitwiseTo = bnpBitwiseTo;
  9434. BigInteger$1.prototype.changeBit = bnpChangeBit;
  9435. BigInteger$1.prototype.addTo = bnpAddTo;
  9436. BigInteger$1.prototype.dMultiply = bnpDMultiply;
  9437. BigInteger$1.prototype.dAddOffset = bnpDAddOffset;
  9438. BigInteger$1.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
  9439. BigInteger$1.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
  9440. BigInteger$1.prototype.modInt = bnpModInt;
  9441. BigInteger$1.prototype.millerRabin = bnpMillerRabin;
  9442. //public
  9443. BigInteger$1.prototype.clone = bnClone;
  9444. BigInteger$1.prototype.intValue = bnIntValue;
  9445. BigInteger$1.prototype.byteValue = bnByteValue;
  9446. BigInteger$1.prototype.shortValue = bnShortValue;
  9447. BigInteger$1.prototype.signum = bnSigNum;
  9448. BigInteger$1.prototype.toByteArray = bnToByteArray;
  9449. BigInteger$1.prototype.equals = bnEquals;
  9450. BigInteger$1.prototype.min = bnMin;
  9451. BigInteger$1.prototype.max = bnMax;
  9452. BigInteger$1.prototype.and = bnAnd;
  9453. BigInteger$1.prototype.or = bnOr;
  9454. BigInteger$1.prototype.xor = bnXor;
  9455. BigInteger$1.prototype.andNot = bnAndNot;
  9456. BigInteger$1.prototype.not = bnNot;
  9457. BigInteger$1.prototype.shiftLeft = bnShiftLeft;
  9458. BigInteger$1.prototype.shiftRight = bnShiftRight;
  9459. BigInteger$1.prototype.getLowestSetBit = bnGetLowestSetBit;
  9460. BigInteger$1.prototype.bitCount = bnBitCount;
  9461. BigInteger$1.prototype.testBit = bnTestBit;
  9462. BigInteger$1.prototype.setBit = bnSetBit;
  9463. BigInteger$1.prototype.clearBit = bnClearBit;
  9464. BigInteger$1.prototype.flipBit = bnFlipBit;
  9465. BigInteger$1.prototype.add = bnAdd;
  9466. BigInteger$1.prototype.subtract = bnSubtract;
  9467. BigInteger$1.prototype.multiply = bnMultiply;
  9468. BigInteger$1.prototype.divide = bnDivide;
  9469. BigInteger$1.prototype.remainder = bnRemainder;
  9470. BigInteger$1.prototype.divideAndRemainder = bnDivideAndRemainder;
  9471. BigInteger$1.prototype.modPow = bnModPow;
  9472. BigInteger$1.prototype.modInverse = bnModInverse;
  9473. BigInteger$1.prototype.pow = bnPow;
  9474. BigInteger$1.prototype.gcd = bnGCD;
  9475. BigInteger$1.prototype.isProbablePrime = bnIsProbablePrime;
  9476. /**
  9477. * Secure Hash Algorithm with 160-bit digest (SHA-1) implementation.
  9478. *
  9479. * @author Dave Longley
  9480. *
  9481. * Copyright (c) 2010-2015 Digital Bazaar, Inc.
  9482. */
  9483. var forge$b = forge$s;
  9484. var sha1 = forge$b.sha1 = forge$b.sha1 || {};
  9485. forge$b.md.sha1 = forge$b.md.algorithms.sha1 = sha1;
  9486. /**
  9487. * Creates a SHA-1 message digest object.
  9488. *
  9489. * @return a message digest object.
  9490. */
  9491. sha1.create = function() {
  9492. // do initialization as necessary
  9493. if(!_initialized) {
  9494. _init();
  9495. }
  9496. // SHA-1 state contains five 32-bit integers
  9497. var _state = null;
  9498. // input buffer
  9499. var _input = forge$b.util.createBuffer();
  9500. // used for word storage
  9501. var _w = new Array(80);
  9502. // message digest object
  9503. var md = {
  9504. algorithm: 'sha1',
  9505. blockLength: 64,
  9506. digestLength: 20,
  9507. // 56-bit length of message so far (does not including padding)
  9508. messageLength: 0,
  9509. // true message length
  9510. fullMessageLength: null,
  9511. // size of message length in bytes
  9512. messageLengthSize: 8
  9513. };
  9514. /**
  9515. * Starts the digest.
  9516. *
  9517. * @return this digest object.
  9518. */
  9519. md.start = function() {
  9520. // up to 56-bit message length for convenience
  9521. md.messageLength = 0;
  9522. // full message length (set md.messageLength64 for backwards-compatibility)
  9523. md.fullMessageLength = md.messageLength64 = [];
  9524. var int32s = md.messageLengthSize / 4;
  9525. for(var i = 0; i < int32s; ++i) {
  9526. md.fullMessageLength.push(0);
  9527. }
  9528. _input = forge$b.util.createBuffer();
  9529. _state = {
  9530. h0: 0x67452301,
  9531. h1: 0xEFCDAB89,
  9532. h2: 0x98BADCFE,
  9533. h3: 0x10325476,
  9534. h4: 0xC3D2E1F0
  9535. };
  9536. return md;
  9537. };
  9538. // start digest automatically for first time
  9539. md.start();
  9540. /**
  9541. * Updates the digest with the given message input. The given input can
  9542. * treated as raw input (no encoding will be applied) or an encoding of
  9543. * 'utf8' maybe given to encode the input using UTF-8.
  9544. *
  9545. * @param msg the message input to update with.
  9546. * @param encoding the encoding to use (default: 'raw', other: 'utf8').
  9547. *
  9548. * @return this digest object.
  9549. */
  9550. md.update = function(msg, encoding) {
  9551. if(encoding === 'utf8') {
  9552. msg = forge$b.util.encodeUtf8(msg);
  9553. }
  9554. // update message length
  9555. var len = msg.length;
  9556. md.messageLength += len;
  9557. len = [(len / 0x100000000) >>> 0, len >>> 0];
  9558. for(var i = md.fullMessageLength.length - 1; i >= 0; --i) {
  9559. md.fullMessageLength[i] += len[1];
  9560. len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0);
  9561. md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0;
  9562. len[0] = ((len[1] / 0x100000000) >>> 0);
  9563. }
  9564. // add bytes to input buffer
  9565. _input.putBytes(msg);
  9566. // process bytes
  9567. _update(_state, _w, _input);
  9568. // compact input buffer every 2K or if empty
  9569. if(_input.read > 2048 || _input.length() === 0) {
  9570. _input.compact();
  9571. }
  9572. return md;
  9573. };
  9574. /**
  9575. * Produces the digest.
  9576. *
  9577. * @return a byte buffer containing the digest value.
  9578. */
  9579. md.digest = function() {
  9580. /* Note: Here we copy the remaining bytes in the input buffer and
  9581. add the appropriate SHA-1 padding. Then we do the final update
  9582. on a copy of the state so that if the user wants to get
  9583. intermediate digests they can do so. */
  9584. /* Determine the number of bytes that must be added to the message
  9585. to ensure its length is congruent to 448 mod 512. In other words,
  9586. the data to be digested must be a multiple of 512 bits (or 128 bytes).
  9587. This data includes the message, some padding, and the length of the
  9588. message. Since the length of the message will be encoded as 8 bytes (64
  9589. bits), that means that the last segment of the data must have 56 bytes
  9590. (448 bits) of message and padding. Therefore, the length of the message
  9591. plus the padding must be congruent to 448 mod 512 because
  9592. 512 - 128 = 448.
  9593. In order to fill up the message length it must be filled with
  9594. padding that begins with 1 bit followed by all 0 bits. Padding
  9595. must *always* be present, so if the message length is already
  9596. congruent to 448 mod 512, then 512 padding bits must be added. */
  9597. var finalBlock = forge$b.util.createBuffer();
  9598. finalBlock.putBytes(_input.bytes());
  9599. // compute remaining size to be digested (include message length size)
  9600. var remaining = (
  9601. md.fullMessageLength[md.fullMessageLength.length - 1] +
  9602. md.messageLengthSize);
  9603. // add padding for overflow blockSize - overflow
  9604. // _padding starts with 1 byte with first bit is set (byte value 128), then
  9605. // there may be up to (blockSize - 1) other pad bytes
  9606. var overflow = remaining & (md.blockLength - 1);
  9607. finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow));
  9608. // serialize message length in bits in big-endian order; since length
  9609. // is stored in bytes we multiply by 8 and add carry from next int
  9610. var next, carry;
  9611. var bits = md.fullMessageLength[0] * 8;
  9612. for(var i = 0; i < md.fullMessageLength.length - 1; ++i) {
  9613. next = md.fullMessageLength[i + 1] * 8;
  9614. carry = (next / 0x100000000) >>> 0;
  9615. bits += carry;
  9616. finalBlock.putInt32(bits >>> 0);
  9617. bits = next >>> 0;
  9618. }
  9619. finalBlock.putInt32(bits);
  9620. var s2 = {
  9621. h0: _state.h0,
  9622. h1: _state.h1,
  9623. h2: _state.h2,
  9624. h3: _state.h3,
  9625. h4: _state.h4
  9626. };
  9627. _update(s2, _w, finalBlock);
  9628. var rval = forge$b.util.createBuffer();
  9629. rval.putInt32(s2.h0);
  9630. rval.putInt32(s2.h1);
  9631. rval.putInt32(s2.h2);
  9632. rval.putInt32(s2.h3);
  9633. rval.putInt32(s2.h4);
  9634. return rval;
  9635. };
  9636. return md;
  9637. };
  9638. // sha-1 padding bytes not initialized yet
  9639. var _padding = null;
  9640. var _initialized = false;
  9641. /**
  9642. * Initializes the constant tables.
  9643. */
  9644. function _init() {
  9645. // create padding
  9646. _padding = String.fromCharCode(128);
  9647. _padding += forge$b.util.fillString(String.fromCharCode(0x00), 64);
  9648. // now initialized
  9649. _initialized = true;
  9650. }
  9651. /**
  9652. * Updates a SHA-1 state with the given byte buffer.
  9653. *
  9654. * @param s the SHA-1 state to update.
  9655. * @param w the array to use to store words.
  9656. * @param bytes the byte buffer to update with.
  9657. */
  9658. function _update(s, w, bytes) {
  9659. // consume 512 bit (64 byte) chunks
  9660. var t, a, b, c, d, e, f, i;
  9661. var len = bytes.length();
  9662. while(len >= 64) {
  9663. // the w array will be populated with sixteen 32-bit big-endian words
  9664. // and then extended into 80 32-bit words according to SHA-1 algorithm
  9665. // and for 32-79 using Max Locktyukhin's optimization
  9666. // initialize hash value for this chunk
  9667. a = s.h0;
  9668. b = s.h1;
  9669. c = s.h2;
  9670. d = s.h3;
  9671. e = s.h4;
  9672. // round 1
  9673. for(i = 0; i < 16; ++i) {
  9674. t = bytes.getInt32();
  9675. w[i] = t;
  9676. f = d ^ (b & (c ^ d));
  9677. t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;
  9678. e = d;
  9679. d = c;
  9680. // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug
  9681. c = ((b << 30) | (b >>> 2)) >>> 0;
  9682. b = a;
  9683. a = t;
  9684. }
  9685. for(; i < 20; ++i) {
  9686. t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);
  9687. t = (t << 1) | (t >>> 31);
  9688. w[i] = t;
  9689. f = d ^ (b & (c ^ d));
  9690. t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t;
  9691. e = d;
  9692. d = c;
  9693. // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug
  9694. c = ((b << 30) | (b >>> 2)) >>> 0;
  9695. b = a;
  9696. a = t;
  9697. }
  9698. // round 2
  9699. for(; i < 32; ++i) {
  9700. t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]);
  9701. t = (t << 1) | (t >>> 31);
  9702. w[i] = t;
  9703. f = b ^ c ^ d;
  9704. t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;
  9705. e = d;
  9706. d = c;
  9707. // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug
  9708. c = ((b << 30) | (b >>> 2)) >>> 0;
  9709. b = a;
  9710. a = t;
  9711. }
  9712. for(; i < 40; ++i) {
  9713. t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);
  9714. t = (t << 2) | (t >>> 30);
  9715. w[i] = t;
  9716. f = b ^ c ^ d;
  9717. t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t;
  9718. e = d;
  9719. d = c;
  9720. // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug
  9721. c = ((b << 30) | (b >>> 2)) >>> 0;
  9722. b = a;
  9723. a = t;
  9724. }
  9725. // round 3
  9726. for(; i < 60; ++i) {
  9727. t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);
  9728. t = (t << 2) | (t >>> 30);
  9729. w[i] = t;
  9730. f = (b & c) | (d & (b ^ c));
  9731. t = ((a << 5) | (a >>> 27)) + f + e + 0x8F1BBCDC + t;
  9732. e = d;
  9733. d = c;
  9734. // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug
  9735. c = ((b << 30) | (b >>> 2)) >>> 0;
  9736. b = a;
  9737. a = t;
  9738. }
  9739. // round 4
  9740. for(; i < 80; ++i) {
  9741. t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]);
  9742. t = (t << 2) | (t >>> 30);
  9743. w[i] = t;
  9744. f = b ^ c ^ d;
  9745. t = ((a << 5) | (a >>> 27)) + f + e + 0xCA62C1D6 + t;
  9746. e = d;
  9747. d = c;
  9748. // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug
  9749. c = ((b << 30) | (b >>> 2)) >>> 0;
  9750. b = a;
  9751. a = t;
  9752. }
  9753. // update hash state
  9754. s.h0 = (s.h0 + a) | 0;
  9755. s.h1 = (s.h1 + b) | 0;
  9756. s.h2 = (s.h2 + c) | 0;
  9757. s.h3 = (s.h3 + d) | 0;
  9758. s.h4 = (s.h4 + e) | 0;
  9759. len -= 64;
  9760. }
  9761. }
  9762. /**
  9763. * Partial implementation of PKCS#1 v2.2: RSA-OEAP
  9764. *
  9765. * Modified but based on the following MIT and BSD licensed code:
  9766. *
  9767. * https://github.com/kjur/jsjws/blob/master/rsa.js:
  9768. *
  9769. * The 'jsjws'(JSON Web Signature JavaScript Library) License
  9770. *
  9771. * Copyright (c) 2012 Kenji Urushima
  9772. *
  9773. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9774. * of this software and associated documentation files (the "Software"), to deal
  9775. * in the Software without restriction, including without limitation the rights
  9776. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9777. * copies of the Software, and to permit persons to whom the Software is
  9778. * furnished to do so, subject to the following conditions:
  9779. *
  9780. * The above copyright notice and this permission notice shall be included in
  9781. * all copies or substantial portions of the Software.
  9782. *
  9783. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  9784. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  9785. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  9786. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  9787. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  9788. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  9789. * THE SOFTWARE.
  9790. *
  9791. * http://webrsa.cvs.sourceforge.net/viewvc/webrsa/Client/RSAES-OAEP.js?content-type=text%2Fplain:
  9792. *
  9793. * RSAES-OAEP.js
  9794. * $Id: RSAES-OAEP.js,v 1.1.1.1 2003/03/19 15:37:20 ellispritchard Exp $
  9795. * JavaScript Implementation of PKCS #1 v2.1 RSA CRYPTOGRAPHY STANDARD (RSA Laboratories, June 14, 2002)
  9796. * Copyright (C) Ellis Pritchard, Guardian Unlimited 2003.
  9797. * Contact: ellis@nukinetics.com
  9798. * Distributed under the BSD License.
  9799. *
  9800. * Official documentation: http://www.rsa.com/rsalabs/node.asp?id=2125
  9801. *
  9802. * @author Evan Jones (http://evanjones.ca/)
  9803. * @author Dave Longley
  9804. *
  9805. * Copyright (c) 2013-2014 Digital Bazaar, Inc.
  9806. */
  9807. var forge$a = forge$s;
  9808. // shortcut for PKCS#1 API
  9809. var pkcs1 = forge$a.pkcs1 = forge$a.pkcs1 || {};
  9810. /**
  9811. * Encode the given RSAES-OAEP message (M) using key, with optional label (L)
  9812. * and seed.
  9813. *
  9814. * This method does not perform RSA encryption, it only encodes the message
  9815. * using RSAES-OAEP.
  9816. *
  9817. * @param key the RSA key to use.
  9818. * @param message the message to encode.
  9819. * @param options the options to use:
  9820. * label an optional label to use.
  9821. * seed the seed to use.
  9822. * md the message digest object to use, undefined for SHA-1.
  9823. * mgf1 optional mgf1 parameters:
  9824. * md the message digest object to use for MGF1.
  9825. *
  9826. * @return the encoded message bytes.
  9827. */
  9828. pkcs1.encode_rsa_oaep = function(key, message, options) {
  9829. // parse arguments
  9830. var label;
  9831. var seed;
  9832. var md;
  9833. var mgf1Md;
  9834. // legacy args (label, seed, md)
  9835. if(typeof options === 'string') {
  9836. label = options;
  9837. seed = arguments[3] || undefined;
  9838. md = arguments[4] || undefined;
  9839. } else if(options) {
  9840. label = options.label || undefined;
  9841. seed = options.seed || undefined;
  9842. md = options.md || undefined;
  9843. if(options.mgf1 && options.mgf1.md) {
  9844. mgf1Md = options.mgf1.md;
  9845. }
  9846. }
  9847. // default OAEP to SHA-1 message digest
  9848. if(!md) {
  9849. md = forge$a.md.sha1.create();
  9850. } else {
  9851. md.start();
  9852. }
  9853. // default MGF-1 to same as OAEP
  9854. if(!mgf1Md) {
  9855. mgf1Md = md;
  9856. }
  9857. // compute length in bytes and check output
  9858. var keyLength = Math.ceil(key.n.bitLength() / 8);
  9859. var maxLength = keyLength - 2 * md.digestLength - 2;
  9860. if(message.length > maxLength) {
  9861. var error = new Error('RSAES-OAEP input message length is too long.');
  9862. error.length = message.length;
  9863. error.maxLength = maxLength;
  9864. throw error;
  9865. }
  9866. if(!label) {
  9867. label = '';
  9868. }
  9869. md.update(label, 'raw');
  9870. var lHash = md.digest();
  9871. var PS = '';
  9872. var PS_length = maxLength - message.length;
  9873. for(var i = 0; i < PS_length; i++) {
  9874. PS += '\x00';
  9875. }
  9876. var DB = lHash.getBytes() + PS + '\x01' + message;
  9877. if(!seed) {
  9878. seed = forge$a.random.getBytes(md.digestLength);
  9879. } else if(seed.length !== md.digestLength) {
  9880. var error = new Error('Invalid RSAES-OAEP seed. The seed length must ' +
  9881. 'match the digest length.');
  9882. error.seedLength = seed.length;
  9883. error.digestLength = md.digestLength;
  9884. throw error;
  9885. }
  9886. var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);
  9887. var maskedDB = forge$a.util.xorBytes(DB, dbMask, DB.length);
  9888. var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);
  9889. var maskedSeed = forge$a.util.xorBytes(seed, seedMask, seed.length);
  9890. // return encoded message
  9891. return '\x00' + maskedSeed + maskedDB;
  9892. };
  9893. /**
  9894. * Decode the given RSAES-OAEP encoded message (EM) using key, with optional
  9895. * label (L).
  9896. *
  9897. * This method does not perform RSA decryption, it only decodes the message
  9898. * using RSAES-OAEP.
  9899. *
  9900. * @param key the RSA key to use.
  9901. * @param em the encoded message to decode.
  9902. * @param options the options to use:
  9903. * label an optional label to use.
  9904. * md the message digest object to use for OAEP, undefined for SHA-1.
  9905. * mgf1 optional mgf1 parameters:
  9906. * md the message digest object to use for MGF1.
  9907. *
  9908. * @return the decoded message bytes.
  9909. */
  9910. pkcs1.decode_rsa_oaep = function(key, em, options) {
  9911. // parse args
  9912. var label;
  9913. var md;
  9914. var mgf1Md;
  9915. // legacy args
  9916. if(typeof options === 'string') {
  9917. label = options;
  9918. md = arguments[3] || undefined;
  9919. } else if(options) {
  9920. label = options.label || undefined;
  9921. md = options.md || undefined;
  9922. if(options.mgf1 && options.mgf1.md) {
  9923. mgf1Md = options.mgf1.md;
  9924. }
  9925. }
  9926. // compute length in bytes
  9927. var keyLength = Math.ceil(key.n.bitLength() / 8);
  9928. if(em.length !== keyLength) {
  9929. var error = new Error('RSAES-OAEP encoded message length is invalid.');
  9930. error.length = em.length;
  9931. error.expectedLength = keyLength;
  9932. throw error;
  9933. }
  9934. // default OAEP to SHA-1 message digest
  9935. if(md === undefined) {
  9936. md = forge$a.md.sha1.create();
  9937. } else {
  9938. md.start();
  9939. }
  9940. // default MGF-1 to same as OAEP
  9941. if(!mgf1Md) {
  9942. mgf1Md = md;
  9943. }
  9944. if(keyLength < 2 * md.digestLength + 2) {
  9945. throw new Error('RSAES-OAEP key is too short for the hash function.');
  9946. }
  9947. if(!label) {
  9948. label = '';
  9949. }
  9950. md.update(label, 'raw');
  9951. var lHash = md.digest().getBytes();
  9952. // split the message into its parts
  9953. var y = em.charAt(0);
  9954. var maskedSeed = em.substring(1, md.digestLength + 1);
  9955. var maskedDB = em.substring(1 + md.digestLength);
  9956. var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);
  9957. var seed = forge$a.util.xorBytes(maskedSeed, seedMask, maskedSeed.length);
  9958. var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);
  9959. var db = forge$a.util.xorBytes(maskedDB, dbMask, maskedDB.length);
  9960. var lHashPrime = db.substring(0, md.digestLength);
  9961. // constant time check that all values match what is expected
  9962. var error = (y !== '\x00');
  9963. // constant time check lHash vs lHashPrime
  9964. for(var i = 0; i < md.digestLength; ++i) {
  9965. error |= (lHash.charAt(i) !== lHashPrime.charAt(i));
  9966. }
  9967. // "constant time" find the 0x1 byte separating the padding (zeros) from the
  9968. // message
  9969. // TODO: It must be possible to do this in a better/smarter way?
  9970. var in_ps = 1;
  9971. var index = md.digestLength;
  9972. for(var j = md.digestLength; j < db.length; j++) {
  9973. var code = db.charCodeAt(j);
  9974. var is_0 = (code & 0x1) ^ 0x1;
  9975. // non-zero if not 0 or 1 in the ps section
  9976. var error_mask = in_ps ? 0xfffe : 0x0000;
  9977. error |= (code & error_mask);
  9978. // latch in_ps to zero after we find 0x1
  9979. in_ps = in_ps & is_0;
  9980. index += in_ps;
  9981. }
  9982. if(error || db.charCodeAt(index) !== 0x1) {
  9983. throw new Error('Invalid RSAES-OAEP padding.');
  9984. }
  9985. return db.substring(index + 1);
  9986. };
  9987. function rsa_mgf1(seed, maskLength, hash) {
  9988. // default to SHA-1 message digest
  9989. if(!hash) {
  9990. hash = forge$a.md.sha1.create();
  9991. }
  9992. var t = '';
  9993. var count = Math.ceil(maskLength / hash.digestLength);
  9994. for(var i = 0; i < count; ++i) {
  9995. var c = String.fromCharCode(
  9996. (i >> 24) & 0xFF, (i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF);
  9997. hash.start();
  9998. hash.update(seed + c);
  9999. t += hash.digest().getBytes();
  10000. }
  10001. return t.substring(0, maskLength);
  10002. }
  10003. /**
  10004. * Prime number generation API.
  10005. *
  10006. * @author Dave Longley
  10007. *
  10008. * Copyright (c) 2014 Digital Bazaar, Inc.
  10009. */
  10010. var forge$9 = forge$s;
  10011. (function() {
  10012. // forge.prime already defined
  10013. if(forge$9.prime) {
  10014. return;
  10015. }
  10016. /* PRIME API */
  10017. var prime = forge$9.prime = forge$9.prime || {};
  10018. var BigInteger = forge$9.jsbn.BigInteger;
  10019. // primes are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29
  10020. var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];
  10021. var THIRTY = new BigInteger(null);
  10022. THIRTY.fromInt(30);
  10023. var op_or = function(x, y) {return x|y;};
  10024. /**
  10025. * Generates a random probable prime with the given number of bits.
  10026. *
  10027. * Alternative algorithms can be specified by name as a string or as an
  10028. * object with custom options like so:
  10029. *
  10030. * {
  10031. * name: 'PRIMEINC',
  10032. * options: {
  10033. * maxBlockTime: <the maximum amount of time to block the main
  10034. * thread before allowing I/O other JS to run>,
  10035. * millerRabinTests: <the number of miller-rabin tests to run>,
  10036. * workerScript: <the worker script URL>,
  10037. * workers: <the number of web workers (if supported) to use,
  10038. * -1 to use estimated cores minus one>.
  10039. * workLoad: the size of the work load, ie: number of possible prime
  10040. * numbers for each web worker to check per work assignment,
  10041. * (default: 100).
  10042. * }
  10043. * }
  10044. *
  10045. * @param bits the number of bits for the prime number.
  10046. * @param options the options to use.
  10047. * [algorithm] the algorithm to use (default: 'PRIMEINC').
  10048. * [prng] a custom crypto-secure pseudo-random number generator to use,
  10049. * that must define "getBytesSync".
  10050. *
  10051. * @return callback(err, num) called once the operation completes.
  10052. */
  10053. prime.generateProbablePrime = function(bits, options, callback) {
  10054. if(typeof options === 'function') {
  10055. callback = options;
  10056. options = {};
  10057. }
  10058. options = options || {};
  10059. // default to PRIMEINC algorithm
  10060. var algorithm = options.algorithm || 'PRIMEINC';
  10061. if(typeof algorithm === 'string') {
  10062. algorithm = {name: algorithm};
  10063. }
  10064. algorithm.options = algorithm.options || {};
  10065. // create prng with api that matches BigInteger secure random
  10066. var prng = options.prng || forge$9.random;
  10067. var rng = {
  10068. // x is an array to fill with bytes
  10069. nextBytes: function(x) {
  10070. var b = prng.getBytesSync(x.length);
  10071. for(var i = 0; i < x.length; ++i) {
  10072. x[i] = b.charCodeAt(i);
  10073. }
  10074. }
  10075. };
  10076. if(algorithm.name === 'PRIMEINC') {
  10077. return primeincFindPrime(bits, rng, algorithm.options, callback);
  10078. }
  10079. throw new Error('Invalid prime generation algorithm: ' + algorithm.name);
  10080. };
  10081. function primeincFindPrime(bits, rng, options, callback) {
  10082. if('workers' in options) {
  10083. return primeincFindPrimeWithWorkers(bits, rng, options, callback);
  10084. }
  10085. return primeincFindPrimeWithoutWorkers(bits, rng, options, callback);
  10086. }
  10087. function primeincFindPrimeWithoutWorkers(bits, rng, options, callback) {
  10088. // initialize random number
  10089. var num = generateRandom(bits, rng);
  10090. /* Note: All primes are of the form 30k+i for i < 30 and gcd(30, i)=1. The
  10091. number we are given is always aligned at 30k + 1. Each time the number is
  10092. determined not to be prime we add to get to the next 'i', eg: if the number
  10093. was at 30k + 1 we add 6. */
  10094. var deltaIdx = 0;
  10095. // get required number of MR tests
  10096. var mrTests = getMillerRabinTests(num.bitLength());
  10097. if('millerRabinTests' in options) {
  10098. mrTests = options.millerRabinTests;
  10099. }
  10100. // find prime nearest to 'num' for maxBlockTime ms
  10101. // 10 ms gives 5ms of leeway for other calculations before dropping
  10102. // below 60fps (1000/60 == 16.67), but in reality, the number will
  10103. // likely be higher due to an 'atomic' big int modPow
  10104. var maxBlockTime = 10;
  10105. if('maxBlockTime' in options) {
  10106. maxBlockTime = options.maxBlockTime;
  10107. }
  10108. _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);
  10109. }
  10110. function _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) {
  10111. var start = +new Date();
  10112. do {
  10113. // overflow, regenerate random number
  10114. if(num.bitLength() > bits) {
  10115. num = generateRandom(bits, rng);
  10116. }
  10117. // do primality test
  10118. if(num.isProbablePrime(mrTests)) {
  10119. return callback(null, num);
  10120. }
  10121. // get next potential prime
  10122. num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);
  10123. } while(maxBlockTime < 0 || (+new Date() - start < maxBlockTime));
  10124. // keep trying later
  10125. forge$9.util.setImmediate(function() {
  10126. _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback);
  10127. });
  10128. }
  10129. // NOTE: This algorithm is indeterminate in nature because workers
  10130. // run in parallel looking at different segments of numbers. Even if this
  10131. // algorithm is run twice with the same input from a predictable RNG, it
  10132. // may produce different outputs.
  10133. function primeincFindPrimeWithWorkers(bits, rng, options, callback) {
  10134. // web workers unavailable
  10135. if(typeof Worker === 'undefined') {
  10136. return primeincFindPrimeWithoutWorkers(bits, rng, options, callback);
  10137. }
  10138. // initialize random number
  10139. var num = generateRandom(bits, rng);
  10140. // use web workers to generate keys
  10141. var numWorkers = options.workers;
  10142. var workLoad = options.workLoad || 100;
  10143. var range = workLoad * 30 / 8;
  10144. var workerScript = options.workerScript || 'forge/prime.worker.js';
  10145. if(numWorkers === -1) {
  10146. return forge$9.util.estimateCores(function(err, cores) {
  10147. if(err) {
  10148. // default to 2
  10149. cores = 2;
  10150. }
  10151. numWorkers = cores - 1;
  10152. generate();
  10153. });
  10154. }
  10155. generate();
  10156. function generate() {
  10157. // require at least 1 worker
  10158. numWorkers = Math.max(1, numWorkers);
  10159. // TODO: consider optimizing by starting workers outside getPrime() ...
  10160. // note that in order to clean up they will have to be made internally
  10161. // asynchronous which may actually be slower
  10162. // start workers immediately
  10163. var workers = [];
  10164. for(var i = 0; i < numWorkers; ++i) {
  10165. // FIXME: fix path or use blob URLs
  10166. workers[i] = new Worker(workerScript);
  10167. }
  10168. // listen for requests from workers and assign ranges to find prime
  10169. for(var i = 0; i < numWorkers; ++i) {
  10170. workers[i].addEventListener('message', workerMessage);
  10171. }
  10172. /* Note: The distribution of random numbers is unknown. Therefore, each
  10173. web worker is continuously allocated a range of numbers to check for a
  10174. random number until one is found.
  10175. Every 30 numbers will be checked just 8 times, because prime numbers
  10176. have the form:
  10177. 30k+i, for i < 30 and gcd(30, i)=1 (there are 8 values of i for this)
  10178. Therefore, if we want a web worker to run N checks before asking for
  10179. a new range of numbers, each range must contain N*30/8 numbers.
  10180. For 100 checks (workLoad), this is a range of 375. */
  10181. var found = false;
  10182. function workerMessage(e) {
  10183. // ignore message, prime already found
  10184. if(found) {
  10185. return;
  10186. }
  10187. var data = e.data;
  10188. if(data.found) {
  10189. // terminate all workers
  10190. for(var i = 0; i < workers.length; ++i) {
  10191. workers[i].terminate();
  10192. }
  10193. found = true;
  10194. return callback(null, new BigInteger(data.prime, 16));
  10195. }
  10196. // overflow, regenerate random number
  10197. if(num.bitLength() > bits) {
  10198. num = generateRandom(bits, rng);
  10199. }
  10200. // assign new range to check
  10201. var hex = num.toString(16);
  10202. // start prime search
  10203. e.target.postMessage({
  10204. hex: hex,
  10205. workLoad: workLoad
  10206. });
  10207. num.dAddOffset(range, 0);
  10208. }
  10209. }
  10210. }
  10211. /**
  10212. * Generates a random number using the given number of bits and RNG.
  10213. *
  10214. * @param bits the number of bits for the number.
  10215. * @param rng the random number generator to use.
  10216. *
  10217. * @return the random number.
  10218. */
  10219. function generateRandom(bits, rng) {
  10220. var num = new BigInteger(bits, rng);
  10221. // force MSB set
  10222. var bits1 = bits - 1;
  10223. if(!num.testBit(bits1)) {
  10224. num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num);
  10225. }
  10226. // align number on 30k+1 boundary
  10227. num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0);
  10228. return num;
  10229. }
  10230. /**
  10231. * Returns the required number of Miller-Rabin tests to generate a
  10232. * prime with an error probability of (1/2)^80.
  10233. *
  10234. * See Handbook of Applied Cryptography Chapter 4, Table 4.4.
  10235. *
  10236. * @param bits the bit size.
  10237. *
  10238. * @return the required number of iterations.
  10239. */
  10240. function getMillerRabinTests(bits) {
  10241. if(bits <= 100) return 27;
  10242. if(bits <= 150) return 18;
  10243. if(bits <= 200) return 15;
  10244. if(bits <= 250) return 12;
  10245. if(bits <= 300) return 9;
  10246. if(bits <= 350) return 8;
  10247. if(bits <= 400) return 7;
  10248. if(bits <= 500) return 6;
  10249. if(bits <= 600) return 5;
  10250. if(bits <= 800) return 4;
  10251. if(bits <= 1250) return 3;
  10252. return 2;
  10253. }
  10254. })();
  10255. /**
  10256. * Javascript implementation of basic RSA algorithms.
  10257. *
  10258. * @author Dave Longley
  10259. *
  10260. * Copyright (c) 2010-2014 Digital Bazaar, Inc.
  10261. *
  10262. * The only algorithm currently supported for PKI is RSA.
  10263. *
  10264. * An RSA key is often stored in ASN.1 DER format. The SubjectPublicKeyInfo
  10265. * ASN.1 structure is composed of an algorithm of type AlgorithmIdentifier
  10266. * and a subjectPublicKey of type bit string.
  10267. *
  10268. * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters
  10269. * for the algorithm, if any. In the case of RSA, there aren't any.
  10270. *
  10271. * SubjectPublicKeyInfo ::= SEQUENCE {
  10272. * algorithm AlgorithmIdentifier,
  10273. * subjectPublicKey BIT STRING
  10274. * }
  10275. *
  10276. * AlgorithmIdentifer ::= SEQUENCE {
  10277. * algorithm OBJECT IDENTIFIER,
  10278. * parameters ANY DEFINED BY algorithm OPTIONAL
  10279. * }
  10280. *
  10281. * For an RSA public key, the subjectPublicKey is:
  10282. *
  10283. * RSAPublicKey ::= SEQUENCE {
  10284. * modulus INTEGER, -- n
  10285. * publicExponent INTEGER -- e
  10286. * }
  10287. *
  10288. * PrivateKeyInfo ::= SEQUENCE {
  10289. * version Version,
  10290. * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
  10291. * privateKey PrivateKey,
  10292. * attributes [0] IMPLICIT Attributes OPTIONAL
  10293. * }
  10294. *
  10295. * Version ::= INTEGER
  10296. * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
  10297. * PrivateKey ::= OCTET STRING
  10298. * Attributes ::= SET OF Attribute
  10299. *
  10300. * An RSA private key as the following structure:
  10301. *
  10302. * RSAPrivateKey ::= SEQUENCE {
  10303. * version Version,
  10304. * modulus INTEGER, -- n
  10305. * publicExponent INTEGER, -- e
  10306. * privateExponent INTEGER, -- d
  10307. * prime1 INTEGER, -- p
  10308. * prime2 INTEGER, -- q
  10309. * exponent1 INTEGER, -- d mod (p-1)
  10310. * exponent2 INTEGER, -- d mod (q-1)
  10311. * coefficient INTEGER -- (inverse of q) mod p
  10312. * }
  10313. *
  10314. * Version ::= INTEGER
  10315. *
  10316. * The OID for the RSA key algorithm is: 1.2.840.113549.1.1.1
  10317. */
  10318. var forge$8 = forge$s;
  10319. if(typeof BigInteger === 'undefined') {
  10320. var BigInteger = forge$8.jsbn.BigInteger;
  10321. }
  10322. var _crypto = forge$8.util.isNodejs ? require$$1__default : null;
  10323. // shortcut for asn.1 API
  10324. var asn1$5 = forge$8.asn1;
  10325. // shortcut for util API
  10326. var util = forge$8.util;
  10327. /*
  10328. * RSA encryption and decryption, see RFC 2313.
  10329. */
  10330. forge$8.pki = forge$8.pki || {};
  10331. forge$8.pki.rsa = forge$8.rsa = forge$8.rsa || {};
  10332. var pki$4 = forge$8.pki;
  10333. // for finding primes, which are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29
  10334. var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2];
  10335. // validator for a PrivateKeyInfo structure
  10336. var privateKeyValidator = {
  10337. // PrivateKeyInfo
  10338. name: 'PrivateKeyInfo',
  10339. tagClass: asn1$5.Class.UNIVERSAL,
  10340. type: asn1$5.Type.SEQUENCE,
  10341. constructed: true,
  10342. value: [{
  10343. // Version (INTEGER)
  10344. name: 'PrivateKeyInfo.version',
  10345. tagClass: asn1$5.Class.UNIVERSAL,
  10346. type: asn1$5.Type.INTEGER,
  10347. constructed: false,
  10348. capture: 'privateKeyVersion'
  10349. }, {
  10350. // privateKeyAlgorithm
  10351. name: 'PrivateKeyInfo.privateKeyAlgorithm',
  10352. tagClass: asn1$5.Class.UNIVERSAL,
  10353. type: asn1$5.Type.SEQUENCE,
  10354. constructed: true,
  10355. value: [{
  10356. name: 'AlgorithmIdentifier.algorithm',
  10357. tagClass: asn1$5.Class.UNIVERSAL,
  10358. type: asn1$5.Type.OID,
  10359. constructed: false,
  10360. capture: 'privateKeyOid'
  10361. }]
  10362. }, {
  10363. // PrivateKey
  10364. name: 'PrivateKeyInfo',
  10365. tagClass: asn1$5.Class.UNIVERSAL,
  10366. type: asn1$5.Type.OCTETSTRING,
  10367. constructed: false,
  10368. capture: 'privateKey'
  10369. }]
  10370. };
  10371. // validator for an RSA private key
  10372. var rsaPrivateKeyValidator = {
  10373. // RSAPrivateKey
  10374. name: 'RSAPrivateKey',
  10375. tagClass: asn1$5.Class.UNIVERSAL,
  10376. type: asn1$5.Type.SEQUENCE,
  10377. constructed: true,
  10378. value: [{
  10379. // Version (INTEGER)
  10380. name: 'RSAPrivateKey.version',
  10381. tagClass: asn1$5.Class.UNIVERSAL,
  10382. type: asn1$5.Type.INTEGER,
  10383. constructed: false,
  10384. capture: 'privateKeyVersion'
  10385. }, {
  10386. // modulus (n)
  10387. name: 'RSAPrivateKey.modulus',
  10388. tagClass: asn1$5.Class.UNIVERSAL,
  10389. type: asn1$5.Type.INTEGER,
  10390. constructed: false,
  10391. capture: 'privateKeyModulus'
  10392. }, {
  10393. // publicExponent (e)
  10394. name: 'RSAPrivateKey.publicExponent',
  10395. tagClass: asn1$5.Class.UNIVERSAL,
  10396. type: asn1$5.Type.INTEGER,
  10397. constructed: false,
  10398. capture: 'privateKeyPublicExponent'
  10399. }, {
  10400. // privateExponent (d)
  10401. name: 'RSAPrivateKey.privateExponent',
  10402. tagClass: asn1$5.Class.UNIVERSAL,
  10403. type: asn1$5.Type.INTEGER,
  10404. constructed: false,
  10405. capture: 'privateKeyPrivateExponent'
  10406. }, {
  10407. // prime1 (p)
  10408. name: 'RSAPrivateKey.prime1',
  10409. tagClass: asn1$5.Class.UNIVERSAL,
  10410. type: asn1$5.Type.INTEGER,
  10411. constructed: false,
  10412. capture: 'privateKeyPrime1'
  10413. }, {
  10414. // prime2 (q)
  10415. name: 'RSAPrivateKey.prime2',
  10416. tagClass: asn1$5.Class.UNIVERSAL,
  10417. type: asn1$5.Type.INTEGER,
  10418. constructed: false,
  10419. capture: 'privateKeyPrime2'
  10420. }, {
  10421. // exponent1 (d mod (p-1))
  10422. name: 'RSAPrivateKey.exponent1',
  10423. tagClass: asn1$5.Class.UNIVERSAL,
  10424. type: asn1$5.Type.INTEGER,
  10425. constructed: false,
  10426. capture: 'privateKeyExponent1'
  10427. }, {
  10428. // exponent2 (d mod (q-1))
  10429. name: 'RSAPrivateKey.exponent2',
  10430. tagClass: asn1$5.Class.UNIVERSAL,
  10431. type: asn1$5.Type.INTEGER,
  10432. constructed: false,
  10433. capture: 'privateKeyExponent2'
  10434. }, {
  10435. // coefficient ((inverse of q) mod p)
  10436. name: 'RSAPrivateKey.coefficient',
  10437. tagClass: asn1$5.Class.UNIVERSAL,
  10438. type: asn1$5.Type.INTEGER,
  10439. constructed: false,
  10440. capture: 'privateKeyCoefficient'
  10441. }]
  10442. };
  10443. // validator for an RSA public key
  10444. var rsaPublicKeyValidator = {
  10445. // RSAPublicKey
  10446. name: 'RSAPublicKey',
  10447. tagClass: asn1$5.Class.UNIVERSAL,
  10448. type: asn1$5.Type.SEQUENCE,
  10449. constructed: true,
  10450. value: [{
  10451. // modulus (n)
  10452. name: 'RSAPublicKey.modulus',
  10453. tagClass: asn1$5.Class.UNIVERSAL,
  10454. type: asn1$5.Type.INTEGER,
  10455. constructed: false,
  10456. capture: 'publicKeyModulus'
  10457. }, {
  10458. // publicExponent (e)
  10459. name: 'RSAPublicKey.exponent',
  10460. tagClass: asn1$5.Class.UNIVERSAL,
  10461. type: asn1$5.Type.INTEGER,
  10462. constructed: false,
  10463. capture: 'publicKeyExponent'
  10464. }]
  10465. };
  10466. // validator for an SubjectPublicKeyInfo structure
  10467. // Note: Currently only works with an RSA public key
  10468. var publicKeyValidator$1 = forge$8.pki.rsa.publicKeyValidator = {
  10469. name: 'SubjectPublicKeyInfo',
  10470. tagClass: asn1$5.Class.UNIVERSAL,
  10471. type: asn1$5.Type.SEQUENCE,
  10472. constructed: true,
  10473. captureAsn1: 'subjectPublicKeyInfo',
  10474. value: [{
  10475. name: 'SubjectPublicKeyInfo.AlgorithmIdentifier',
  10476. tagClass: asn1$5.Class.UNIVERSAL,
  10477. type: asn1$5.Type.SEQUENCE,
  10478. constructed: true,
  10479. value: [{
  10480. name: 'AlgorithmIdentifier.algorithm',
  10481. tagClass: asn1$5.Class.UNIVERSAL,
  10482. type: asn1$5.Type.OID,
  10483. constructed: false,
  10484. capture: 'publicKeyOid'
  10485. }]
  10486. }, {
  10487. // subjectPublicKey
  10488. name: 'SubjectPublicKeyInfo.subjectPublicKey',
  10489. tagClass: asn1$5.Class.UNIVERSAL,
  10490. type: asn1$5.Type.BITSTRING,
  10491. constructed: false,
  10492. value: [{
  10493. // RSAPublicKey
  10494. name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey',
  10495. tagClass: asn1$5.Class.UNIVERSAL,
  10496. type: asn1$5.Type.SEQUENCE,
  10497. constructed: true,
  10498. optional: true,
  10499. captureAsn1: 'rsaPublicKey'
  10500. }]
  10501. }]
  10502. };
  10503. // validator for a DigestInfo structure
  10504. var digestInfoValidator = {
  10505. name: 'DigestInfo',
  10506. tagClass: asn1$5.Class.UNIVERSAL,
  10507. type: asn1$5.Type.SEQUENCE,
  10508. constructed: true,
  10509. value: [{
  10510. name: 'DigestInfo.DigestAlgorithm',
  10511. tagClass: asn1$5.Class.UNIVERSAL,
  10512. type: asn1$5.Type.SEQUENCE,
  10513. constructed: true,
  10514. value: [{
  10515. name: 'DigestInfo.DigestAlgorithm.algorithmIdentifier',
  10516. tagClass: asn1$5.Class.UNIVERSAL,
  10517. type: asn1$5.Type.OID,
  10518. constructed: false,
  10519. capture: 'algorithmIdentifier'
  10520. }, {
  10521. // NULL paramters
  10522. name: 'DigestInfo.DigestAlgorithm.parameters',
  10523. tagClass: asn1$5.Class.UNIVERSAL,
  10524. type: asn1$5.Type.NULL,
  10525. // captured only to check existence for md2 and md5
  10526. capture: 'parameters',
  10527. optional: true,
  10528. constructed: false
  10529. }]
  10530. }, {
  10531. // digest
  10532. name: 'DigestInfo.digest',
  10533. tagClass: asn1$5.Class.UNIVERSAL,
  10534. type: asn1$5.Type.OCTETSTRING,
  10535. constructed: false,
  10536. capture: 'digest'
  10537. }]
  10538. };
  10539. /**
  10540. * Wrap digest in DigestInfo object.
  10541. *
  10542. * This function implements EMSA-PKCS1-v1_5-ENCODE as per RFC 3447.
  10543. *
  10544. * DigestInfo ::= SEQUENCE {
  10545. * digestAlgorithm DigestAlgorithmIdentifier,
  10546. * digest Digest
  10547. * }
  10548. *
  10549. * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
  10550. * Digest ::= OCTET STRING
  10551. *
  10552. * @param md the message digest object with the hash to sign.
  10553. *
  10554. * @return the encoded message (ready for RSA encrytion)
  10555. */
  10556. var emsaPkcs1v15encode = function(md) {
  10557. // get the oid for the algorithm
  10558. var oid;
  10559. if(md.algorithm in pki$4.oids) {
  10560. oid = pki$4.oids[md.algorithm];
  10561. } else {
  10562. var error = new Error('Unknown message digest algorithm.');
  10563. error.algorithm = md.algorithm;
  10564. throw error;
  10565. }
  10566. var oidBytes = asn1$5.oidToDer(oid).getBytes();
  10567. // create the digest info
  10568. var digestInfo = asn1$5.create(
  10569. asn1$5.Class.UNIVERSAL, asn1$5.Type.SEQUENCE, true, []);
  10570. var digestAlgorithm = asn1$5.create(
  10571. asn1$5.Class.UNIVERSAL, asn1$5.Type.SEQUENCE, true, []);
  10572. digestAlgorithm.value.push(asn1$5.create(
  10573. asn1$5.Class.UNIVERSAL, asn1$5.Type.OID, false, oidBytes));
  10574. digestAlgorithm.value.push(asn1$5.create(
  10575. asn1$5.Class.UNIVERSAL, asn1$5.Type.NULL, false, ''));
  10576. var digest = asn1$5.create(
  10577. asn1$5.Class.UNIVERSAL, asn1$5.Type.OCTETSTRING,
  10578. false, md.digest().getBytes());
  10579. digestInfo.value.push(digestAlgorithm);
  10580. digestInfo.value.push(digest);
  10581. // encode digest info
  10582. return asn1$5.toDer(digestInfo).getBytes();
  10583. };
  10584. /**
  10585. * Performs x^c mod n (RSA encryption or decryption operation).
  10586. *
  10587. * @param x the number to raise and mod.
  10588. * @param key the key to use.
  10589. * @param pub true if the key is public, false if private.
  10590. *
  10591. * @return the result of x^c mod n.
  10592. */
  10593. var _modPow = function(x, key, pub) {
  10594. if(pub) {
  10595. return x.modPow(key.e, key.n);
  10596. }
  10597. if(!key.p || !key.q) {
  10598. // allow calculation without CRT params (slow)
  10599. return x.modPow(key.d, key.n);
  10600. }
  10601. // pre-compute dP, dQ, and qInv if necessary
  10602. if(!key.dP) {
  10603. key.dP = key.d.mod(key.p.subtract(BigInteger.ONE));
  10604. }
  10605. if(!key.dQ) {
  10606. key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE));
  10607. }
  10608. if(!key.qInv) {
  10609. key.qInv = key.q.modInverse(key.p);
  10610. }
  10611. /* Chinese remainder theorem (CRT) states:
  10612. Suppose n1, n2, ..., nk are positive integers which are pairwise
  10613. coprime (n1 and n2 have no common factors other than 1). For any
  10614. integers x1, x2, ..., xk there exists an integer x solving the
  10615. system of simultaneous congruences (where ~= means modularly
  10616. congruent so a ~= b mod n means a mod n = b mod n):
  10617. x ~= x1 mod n1
  10618. x ~= x2 mod n2
  10619. ...
  10620. x ~= xk mod nk
  10621. This system of congruences has a single simultaneous solution x
  10622. between 0 and n - 1. Furthermore, each xk solution and x itself
  10623. is congruent modulo the product n = n1*n2*...*nk.
  10624. So x1 mod n = x2 mod n = xk mod n = x mod n.
  10625. The single simultaneous solution x can be solved with the following
  10626. equation:
  10627. x = sum(xi*ri*si) mod n where ri = n/ni and si = ri^-1 mod ni.
  10628. Where x is less than n, xi = x mod ni.
  10629. For RSA we are only concerned with k = 2. The modulus n = pq, where
  10630. p and q are coprime. The RSA decryption algorithm is:
  10631. y = x^d mod n
  10632. Given the above:
  10633. x1 = x^d mod p
  10634. r1 = n/p = q
  10635. s1 = q^-1 mod p
  10636. x2 = x^d mod q
  10637. r2 = n/q = p
  10638. s2 = p^-1 mod q
  10639. So y = (x1r1s1 + x2r2s2) mod n
  10640. = ((x^d mod p)q(q^-1 mod p) + (x^d mod q)p(p^-1 mod q)) mod n
  10641. According to Fermat's Little Theorem, if the modulus P is prime,
  10642. for any integer A not evenly divisible by P, A^(P-1) ~= 1 mod P.
  10643. Since A is not divisible by P it follows that if:
  10644. N ~= M mod (P - 1), then A^N mod P = A^M mod P. Therefore:
  10645. A^N mod P = A^(M mod (P - 1)) mod P. (The latter takes less effort
  10646. to calculate). In order to calculate x^d mod p more quickly the
  10647. exponent d mod (p - 1) is stored in the RSA private key (the same
  10648. is done for x^d mod q). These values are referred to as dP and dQ
  10649. respectively. Therefore we now have:
  10650. y = ((x^dP mod p)q(q^-1 mod p) + (x^dQ mod q)p(p^-1 mod q)) mod n
  10651. Since we'll be reducing x^dP by modulo p (same for q) we can also
  10652. reduce x by p (and q respectively) before hand. Therefore, let
  10653. xp = ((x mod p)^dP mod p), and
  10654. xq = ((x mod q)^dQ mod q), yielding:
  10655. y = (xp*q*(q^-1 mod p) + xq*p*(p^-1 mod q)) mod n
  10656. This can be further reduced to a simple algorithm that only
  10657. requires 1 inverse (the q inverse is used) to be used and stored.
  10658. The algorithm is called Garner's algorithm. If qInv is the
  10659. inverse of q, we simply calculate:
  10660. y = (qInv*(xp - xq) mod p) * q + xq
  10661. However, there are two further complications. First, we need to
  10662. ensure that xp > xq to prevent signed BigIntegers from being used
  10663. so we add p until this is true (since we will be mod'ing with
  10664. p anyway). Then, there is a known timing attack on algorithms
  10665. using the CRT. To mitigate this risk, "cryptographic blinding"
  10666. should be used. This requires simply generating a random number r
  10667. between 0 and n-1 and its inverse and multiplying x by r^e before
  10668. calculating y and then multiplying y by r^-1 afterwards. Note that
  10669. r must be coprime with n (gcd(r, n) === 1) in order to have an
  10670. inverse.
  10671. */
  10672. // cryptographic blinding
  10673. var r;
  10674. do {
  10675. r = new BigInteger(
  10676. forge$8.util.bytesToHex(forge$8.random.getBytes(key.n.bitLength() / 8)),
  10677. 16);
  10678. } while(r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger.ONE));
  10679. x = x.multiply(r.modPow(key.e, key.n)).mod(key.n);
  10680. // calculate xp and xq
  10681. var xp = x.mod(key.p).modPow(key.dP, key.p);
  10682. var xq = x.mod(key.q).modPow(key.dQ, key.q);
  10683. // xp must be larger than xq to avoid signed bit usage
  10684. while(xp.compareTo(xq) < 0) {
  10685. xp = xp.add(key.p);
  10686. }
  10687. // do last step
  10688. var y = xp.subtract(xq)
  10689. .multiply(key.qInv).mod(key.p)
  10690. .multiply(key.q).add(xq);
  10691. // remove effect of random for cryptographic blinding
  10692. y = y.multiply(r.modInverse(key.n)).mod(key.n);
  10693. return y;
  10694. };
  10695. /**
  10696. * NOTE: THIS METHOD IS DEPRECATED, use 'sign' on a private key object or
  10697. * 'encrypt' on a public key object instead.
  10698. *
  10699. * Performs RSA encryption.
  10700. *
  10701. * The parameter bt controls whether to put padding bytes before the
  10702. * message passed in. Set bt to either true or false to disable padding
  10703. * completely (in order to handle e.g. EMSA-PSS encoding seperately before),
  10704. * signaling whether the encryption operation is a public key operation
  10705. * (i.e. encrypting data) or not, i.e. private key operation (data signing).
  10706. *
  10707. * For PKCS#1 v1.5 padding pass in the block type to use, i.e. either 0x01
  10708. * (for signing) or 0x02 (for encryption). The key operation mode (private
  10709. * or public) is derived from this flag in that case).
  10710. *
  10711. * @param m the message to encrypt as a byte string.
  10712. * @param key the RSA key to use.
  10713. * @param bt for PKCS#1 v1.5 padding, the block type to use
  10714. * (0x01 for private key, 0x02 for public),
  10715. * to disable padding: true = public key, false = private key.
  10716. *
  10717. * @return the encrypted bytes as a string.
  10718. */
  10719. pki$4.rsa.encrypt = function(m, key, bt) {
  10720. var pub = bt;
  10721. var eb;
  10722. // get the length of the modulus in bytes
  10723. var k = Math.ceil(key.n.bitLength() / 8);
  10724. if(bt !== false && bt !== true) {
  10725. // legacy, default to PKCS#1 v1.5 padding
  10726. pub = (bt === 0x02);
  10727. eb = _encodePkcs1_v1_5(m, key, bt);
  10728. } else {
  10729. eb = forge$8.util.createBuffer();
  10730. eb.putBytes(m);
  10731. }
  10732. // load encryption block as big integer 'x'
  10733. // FIXME: hex conversion inefficient, get BigInteger w/byte strings
  10734. var x = new BigInteger(eb.toHex(), 16);
  10735. // do RSA encryption
  10736. var y = _modPow(x, key, pub);
  10737. // convert y into the encrypted data byte string, if y is shorter in
  10738. // bytes than k, then prepend zero bytes to fill up ed
  10739. // FIXME: hex conversion inefficient, get BigInteger w/byte strings
  10740. var yhex = y.toString(16);
  10741. var ed = forge$8.util.createBuffer();
  10742. var zeros = k - Math.ceil(yhex.length / 2);
  10743. while(zeros > 0) {
  10744. ed.putByte(0x00);
  10745. --zeros;
  10746. }
  10747. ed.putBytes(forge$8.util.hexToBytes(yhex));
  10748. return ed.getBytes();
  10749. };
  10750. /**
  10751. * NOTE: THIS METHOD IS DEPRECATED, use 'decrypt' on a private key object or
  10752. * 'verify' on a public key object instead.
  10753. *
  10754. * Performs RSA decryption.
  10755. *
  10756. * The parameter ml controls whether to apply PKCS#1 v1.5 padding
  10757. * or not. Set ml = false to disable padding removal completely
  10758. * (in order to handle e.g. EMSA-PSS later on) and simply pass back
  10759. * the RSA encryption block.
  10760. *
  10761. * @param ed the encrypted data to decrypt in as a byte string.
  10762. * @param key the RSA key to use.
  10763. * @param pub true for a public key operation, false for private.
  10764. * @param ml the message length, if known, false to disable padding.
  10765. *
  10766. * @return the decrypted message as a byte string.
  10767. */
  10768. pki$4.rsa.decrypt = function(ed, key, pub, ml) {
  10769. // get the length of the modulus in bytes
  10770. var k = Math.ceil(key.n.bitLength() / 8);
  10771. // error if the length of the encrypted data ED is not k
  10772. if(ed.length !== k) {
  10773. var error = new Error('Encrypted message length is invalid.');
  10774. error.length = ed.length;
  10775. error.expected = k;
  10776. throw error;
  10777. }
  10778. // convert encrypted data into a big integer
  10779. // FIXME: hex conversion inefficient, get BigInteger w/byte strings
  10780. var y = new BigInteger(forge$8.util.createBuffer(ed).toHex(), 16);
  10781. // y must be less than the modulus or it wasn't the result of
  10782. // a previous mod operation (encryption) using that modulus
  10783. if(y.compareTo(key.n) >= 0) {
  10784. throw new Error('Encrypted message is invalid.');
  10785. }
  10786. // do RSA decryption
  10787. var x = _modPow(y, key, pub);
  10788. // create the encryption block, if x is shorter in bytes than k, then
  10789. // prepend zero bytes to fill up eb
  10790. // FIXME: hex conversion inefficient, get BigInteger w/byte strings
  10791. var xhex = x.toString(16);
  10792. var eb = forge$8.util.createBuffer();
  10793. var zeros = k - Math.ceil(xhex.length / 2);
  10794. while(zeros > 0) {
  10795. eb.putByte(0x00);
  10796. --zeros;
  10797. }
  10798. eb.putBytes(forge$8.util.hexToBytes(xhex));
  10799. if(ml !== false) {
  10800. // legacy, default to PKCS#1 v1.5 padding
  10801. return _decodePkcs1_v1_5(eb.getBytes(), key, pub);
  10802. }
  10803. // return message
  10804. return eb.getBytes();
  10805. };
  10806. /**
  10807. * Creates an RSA key-pair generation state object. It is used to allow
  10808. * key-generation to be performed in steps. It also allows for a UI to
  10809. * display progress updates.
  10810. *
  10811. * @param bits the size for the private key in bits, defaults to 2048.
  10812. * @param e the public exponent to use, defaults to 65537 (0x10001).
  10813. * @param [options] the options to use.
  10814. * prng a custom crypto-secure pseudo-random number generator to use,
  10815. * that must define "getBytesSync".
  10816. * algorithm the algorithm to use (default: 'PRIMEINC').
  10817. *
  10818. * @return the state object to use to generate the key-pair.
  10819. */
  10820. pki$4.rsa.createKeyPairGenerationState = function(bits, e, options) {
  10821. // TODO: migrate step-based prime generation code to forge.prime
  10822. // set default bits
  10823. if(typeof(bits) === 'string') {
  10824. bits = parseInt(bits, 10);
  10825. }
  10826. bits = bits || 2048;
  10827. // create prng with api that matches BigInteger secure random
  10828. options = options || {};
  10829. var prng = options.prng || forge$8.random;
  10830. var rng = {
  10831. // x is an array to fill with bytes
  10832. nextBytes: function(x) {
  10833. var b = prng.getBytesSync(x.length);
  10834. for(var i = 0; i < x.length; ++i) {
  10835. x[i] = b.charCodeAt(i);
  10836. }
  10837. }
  10838. };
  10839. var algorithm = options.algorithm || 'PRIMEINC';
  10840. // create PRIMEINC algorithm state
  10841. var rval;
  10842. if(algorithm === 'PRIMEINC') {
  10843. rval = {
  10844. algorithm: algorithm,
  10845. state: 0,
  10846. bits: bits,
  10847. rng: rng,
  10848. eInt: e || 65537,
  10849. e: new BigInteger(null),
  10850. p: null,
  10851. q: null,
  10852. qBits: bits >> 1,
  10853. pBits: bits - (bits >> 1),
  10854. pqState: 0,
  10855. num: null,
  10856. keys: null
  10857. };
  10858. rval.e.fromInt(rval.eInt);
  10859. } else {
  10860. throw new Error('Invalid key generation algorithm: ' + algorithm);
  10861. }
  10862. return rval;
  10863. };
  10864. /**
  10865. * Attempts to runs the key-generation algorithm for at most n seconds
  10866. * (approximately) using the given state. When key-generation has completed,
  10867. * the keys will be stored in state.keys.
  10868. *
  10869. * To use this function to update a UI while generating a key or to prevent
  10870. * causing browser lockups/warnings, set "n" to a value other than 0. A
  10871. * simple pattern for generating a key and showing a progress indicator is:
  10872. *
  10873. * var state = pki.rsa.createKeyPairGenerationState(2048);
  10874. * var step = function() {
  10875. * // step key-generation, run algorithm for 100 ms, repeat
  10876. * if(!forge.pki.rsa.stepKeyPairGenerationState(state, 100)) {
  10877. * setTimeout(step, 1);
  10878. * } else {
  10879. * // key-generation complete
  10880. * // TODO: turn off progress indicator here
  10881. * // TODO: use the generated key-pair in "state.keys"
  10882. * }
  10883. * };
  10884. * // TODO: turn on progress indicator here
  10885. * setTimeout(step, 0);
  10886. *
  10887. * @param state the state to use.
  10888. * @param n the maximum number of milliseconds to run the algorithm for, 0
  10889. * to run the algorithm to completion.
  10890. *
  10891. * @return true if the key-generation completed, false if not.
  10892. */
  10893. pki$4.rsa.stepKeyPairGenerationState = function(state, n) {
  10894. // set default algorithm if not set
  10895. if(!('algorithm' in state)) {
  10896. state.algorithm = 'PRIMEINC';
  10897. }
  10898. // TODO: migrate step-based prime generation code to forge.prime
  10899. // TODO: abstract as PRIMEINC algorithm
  10900. // do key generation (based on Tom Wu's rsa.js, see jsbn.js license)
  10901. // with some minor optimizations and designed to run in steps
  10902. // local state vars
  10903. var THIRTY = new BigInteger(null);
  10904. THIRTY.fromInt(30);
  10905. var deltaIdx = 0;
  10906. var op_or = function(x, y) {return x | y;};
  10907. // keep stepping until time limit is reached or done
  10908. var t1 = +new Date();
  10909. var t2;
  10910. var total = 0;
  10911. while(state.keys === null && (n <= 0 || total < n)) {
  10912. // generate p or q
  10913. if(state.state === 0) {
  10914. /* Note: All primes are of the form:
  10915. 30k+i, for i < 30 and gcd(30, i)=1, where there are 8 values for i
  10916. When we generate a random number, we always align it at 30k + 1. Each
  10917. time the number is determined not to be prime we add to get to the
  10918. next 'i', eg: if the number was at 30k + 1 we add 6. */
  10919. var bits = (state.p === null) ? state.pBits : state.qBits;
  10920. var bits1 = bits - 1;
  10921. // get a random number
  10922. if(state.pqState === 0) {
  10923. state.num = new BigInteger(bits, state.rng);
  10924. // force MSB set
  10925. if(!state.num.testBit(bits1)) {
  10926. state.num.bitwiseTo(
  10927. BigInteger.ONE.shiftLeft(bits1), op_or, state.num);
  10928. }
  10929. // align number on 30k+1 boundary
  10930. state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0);
  10931. deltaIdx = 0;
  10932. ++state.pqState;
  10933. } else if(state.pqState === 1) {
  10934. // try to make the number a prime
  10935. if(state.num.bitLength() > bits) {
  10936. // overflow, try again
  10937. state.pqState = 0;
  10938. // do primality test
  10939. } else if(state.num.isProbablePrime(
  10940. _getMillerRabinTests(state.num.bitLength()))) {
  10941. ++state.pqState;
  10942. } else {
  10943. // get next potential prime
  10944. state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0);
  10945. }
  10946. } else if(state.pqState === 2) {
  10947. // ensure number is coprime with e
  10948. state.pqState =
  10949. (state.num.subtract(BigInteger.ONE).gcd(state.e)
  10950. .compareTo(BigInteger.ONE) === 0) ? 3 : 0;
  10951. } else if(state.pqState === 3) {
  10952. // store p or q
  10953. state.pqState = 0;
  10954. if(state.p === null) {
  10955. state.p = state.num;
  10956. } else {
  10957. state.q = state.num;
  10958. }
  10959. // advance state if both p and q are ready
  10960. if(state.p !== null && state.q !== null) {
  10961. ++state.state;
  10962. }
  10963. state.num = null;
  10964. }
  10965. } else if(state.state === 1) {
  10966. // ensure p is larger than q (swap them if not)
  10967. if(state.p.compareTo(state.q) < 0) {
  10968. state.num = state.p;
  10969. state.p = state.q;
  10970. state.q = state.num;
  10971. }
  10972. ++state.state;
  10973. } else if(state.state === 2) {
  10974. // compute phi: (p - 1)(q - 1) (Euler's totient function)
  10975. state.p1 = state.p.subtract(BigInteger.ONE);
  10976. state.q1 = state.q.subtract(BigInteger.ONE);
  10977. state.phi = state.p1.multiply(state.q1);
  10978. ++state.state;
  10979. } else if(state.state === 3) {
  10980. // ensure e and phi are coprime
  10981. if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) {
  10982. // phi and e are coprime, advance
  10983. ++state.state;
  10984. } else {
  10985. // phi and e aren't coprime, so generate a new p and q
  10986. state.p = null;
  10987. state.q = null;
  10988. state.state = 0;
  10989. }
  10990. } else if(state.state === 4) {
  10991. // create n, ensure n is has the right number of bits
  10992. state.n = state.p.multiply(state.q);
  10993. // ensure n is right number of bits
  10994. if(state.n.bitLength() === state.bits) {
  10995. // success, advance
  10996. ++state.state;
  10997. } else {
  10998. // failed, get new q
  10999. state.q = null;
  11000. state.state = 0;
  11001. }
  11002. } else if(state.state === 5) {
  11003. // set keys
  11004. var d = state.e.modInverse(state.phi);
  11005. state.keys = {
  11006. privateKey: pki$4.rsa.setPrivateKey(
  11007. state.n, state.e, d, state.p, state.q,
  11008. d.mod(state.p1), d.mod(state.q1),
  11009. state.q.modInverse(state.p)),
  11010. publicKey: pki$4.rsa.setPublicKey(state.n, state.e)
  11011. };
  11012. }
  11013. // update timing
  11014. t2 = +new Date();
  11015. total += t2 - t1;
  11016. t1 = t2;
  11017. }
  11018. return state.keys !== null;
  11019. };
  11020. /**
  11021. * Generates an RSA public-private key pair in a single call.
  11022. *
  11023. * To generate a key-pair in steps (to allow for progress updates and to
  11024. * prevent blocking or warnings in slow browsers) then use the key-pair
  11025. * generation state functions.
  11026. *
  11027. * To generate a key-pair asynchronously (either through web-workers, if
  11028. * available, or by breaking up the work on the main thread), pass a
  11029. * callback function.
  11030. *
  11031. * @param [bits] the size for the private key in bits, defaults to 2048.
  11032. * @param [e] the public exponent to use, defaults to 65537.
  11033. * @param [options] options for key-pair generation, if given then 'bits'
  11034. * and 'e' must *not* be given:
  11035. * bits the size for the private key in bits, (default: 2048).
  11036. * e the public exponent to use, (default: 65537 (0x10001)).
  11037. * workerScript the worker script URL.
  11038. * workers the number of web workers (if supported) to use,
  11039. * (default: 2).
  11040. * workLoad the size of the work load, ie: number of possible prime
  11041. * numbers for each web worker to check per work assignment,
  11042. * (default: 100).
  11043. * prng a custom crypto-secure pseudo-random number generator to use,
  11044. * that must define "getBytesSync". Disables use of native APIs.
  11045. * algorithm the algorithm to use (default: 'PRIMEINC').
  11046. * @param [callback(err, keypair)] called once the operation completes.
  11047. *
  11048. * @return an object with privateKey and publicKey properties.
  11049. */
  11050. pki$4.rsa.generateKeyPair = function(bits, e, options, callback) {
  11051. // (bits), (options), (callback)
  11052. if(arguments.length === 1) {
  11053. if(typeof bits === 'object') {
  11054. options = bits;
  11055. bits = undefined;
  11056. } else if(typeof bits === 'function') {
  11057. callback = bits;
  11058. bits = undefined;
  11059. }
  11060. } else if(arguments.length === 2) {
  11061. // (bits, e), (bits, options), (bits, callback), (options, callback)
  11062. if(typeof bits === 'number') {
  11063. if(typeof e === 'function') {
  11064. callback = e;
  11065. e = undefined;
  11066. } else if(typeof e !== 'number') {
  11067. options = e;
  11068. e = undefined;
  11069. }
  11070. } else {
  11071. options = bits;
  11072. callback = e;
  11073. bits = undefined;
  11074. e = undefined;
  11075. }
  11076. } else if(arguments.length === 3) {
  11077. // (bits, e, options), (bits, e, callback), (bits, options, callback)
  11078. if(typeof e === 'number') {
  11079. if(typeof options === 'function') {
  11080. callback = options;
  11081. options = undefined;
  11082. }
  11083. } else {
  11084. callback = options;
  11085. options = e;
  11086. e = undefined;
  11087. }
  11088. }
  11089. options = options || {};
  11090. if(bits === undefined) {
  11091. bits = options.bits || 2048;
  11092. }
  11093. if(e === undefined) {
  11094. e = options.e || 0x10001;
  11095. }
  11096. // use native code if permitted, available, and parameters are acceptable
  11097. if(!options.prng &&
  11098. bits >= 256 && bits <= 16384 && (e === 0x10001 || e === 3)) {
  11099. if(callback) {
  11100. // try native async
  11101. if(_detectNodeCrypto('generateKeyPair')) {
  11102. return _crypto.generateKeyPair('rsa', {
  11103. modulusLength: bits,
  11104. publicExponent: e,
  11105. publicKeyEncoding: {
  11106. type: 'spki',
  11107. format: 'pem'
  11108. },
  11109. privateKeyEncoding: {
  11110. type: 'pkcs8',
  11111. format: 'pem'
  11112. }
  11113. }, function(err, pub, priv) {
  11114. if(err) {
  11115. return callback(err);
  11116. }
  11117. callback(null, {
  11118. privateKey: pki$4.privateKeyFromPem(priv),
  11119. publicKey: pki$4.publicKeyFromPem(pub)
  11120. });
  11121. });
  11122. }
  11123. if(_detectSubtleCrypto('generateKey') &&
  11124. _detectSubtleCrypto('exportKey')) {
  11125. // use standard native generateKey
  11126. return util.globalScope.crypto.subtle.generateKey({
  11127. name: 'RSASSA-PKCS1-v1_5',
  11128. modulusLength: bits,
  11129. publicExponent: _intToUint8Array(e),
  11130. hash: {name: 'SHA-256'}
  11131. }, true /* key can be exported*/, ['sign', 'verify'])
  11132. .then(function(pair) {
  11133. return util.globalScope.crypto.subtle.exportKey(
  11134. 'pkcs8', pair.privateKey);
  11135. // avoiding catch(function(err) {...}) to support IE <= 8
  11136. }).then(undefined, function(err) {
  11137. callback(err);
  11138. }).then(function(pkcs8) {
  11139. if(pkcs8) {
  11140. var privateKey = pki$4.privateKeyFromAsn1(
  11141. asn1$5.fromDer(forge$8.util.createBuffer(pkcs8)));
  11142. callback(null, {
  11143. privateKey: privateKey,
  11144. publicKey: pki$4.setRsaPublicKey(privateKey.n, privateKey.e)
  11145. });
  11146. }
  11147. });
  11148. }
  11149. if(_detectSubtleMsCrypto('generateKey') &&
  11150. _detectSubtleMsCrypto('exportKey')) {
  11151. var genOp = util.globalScope.msCrypto.subtle.generateKey({
  11152. name: 'RSASSA-PKCS1-v1_5',
  11153. modulusLength: bits,
  11154. publicExponent: _intToUint8Array(e),
  11155. hash: {name: 'SHA-256'}
  11156. }, true /* key can be exported*/, ['sign', 'verify']);
  11157. genOp.oncomplete = function(e) {
  11158. var pair = e.target.result;
  11159. var exportOp = util.globalScope.msCrypto.subtle.exportKey(
  11160. 'pkcs8', pair.privateKey);
  11161. exportOp.oncomplete = function(e) {
  11162. var pkcs8 = e.target.result;
  11163. var privateKey = pki$4.privateKeyFromAsn1(
  11164. asn1$5.fromDer(forge$8.util.createBuffer(pkcs8)));
  11165. callback(null, {
  11166. privateKey: privateKey,
  11167. publicKey: pki$4.setRsaPublicKey(privateKey.n, privateKey.e)
  11168. });
  11169. };
  11170. exportOp.onerror = function(err) {
  11171. callback(err);
  11172. };
  11173. };
  11174. genOp.onerror = function(err) {
  11175. callback(err);
  11176. };
  11177. return;
  11178. }
  11179. } else {
  11180. // try native sync
  11181. if(_detectNodeCrypto('generateKeyPairSync')) {
  11182. var keypair = _crypto.generateKeyPairSync('rsa', {
  11183. modulusLength: bits,
  11184. publicExponent: e,
  11185. publicKeyEncoding: {
  11186. type: 'spki',
  11187. format: 'pem'
  11188. },
  11189. privateKeyEncoding: {
  11190. type: 'pkcs8',
  11191. format: 'pem'
  11192. }
  11193. });
  11194. return {
  11195. privateKey: pki$4.privateKeyFromPem(keypair.privateKey),
  11196. publicKey: pki$4.publicKeyFromPem(keypair.publicKey)
  11197. };
  11198. }
  11199. }
  11200. }
  11201. // use JavaScript implementation
  11202. var state = pki$4.rsa.createKeyPairGenerationState(bits, e, options);
  11203. if(!callback) {
  11204. pki$4.rsa.stepKeyPairGenerationState(state, 0);
  11205. return state.keys;
  11206. }
  11207. _generateKeyPair(state, options, callback);
  11208. };
  11209. /**
  11210. * Sets an RSA public key from BigIntegers modulus and exponent.
  11211. *
  11212. * @param n the modulus.
  11213. * @param e the exponent.
  11214. *
  11215. * @return the public key.
  11216. */
  11217. pki$4.setRsaPublicKey = pki$4.rsa.setPublicKey = function(n, e) {
  11218. var key = {
  11219. n: n,
  11220. e: e
  11221. };
  11222. /**
  11223. * Encrypts the given data with this public key. Newer applications
  11224. * should use the 'RSA-OAEP' decryption scheme, 'RSAES-PKCS1-V1_5' is for
  11225. * legacy applications.
  11226. *
  11227. * @param data the byte string to encrypt.
  11228. * @param scheme the encryption scheme to use:
  11229. * 'RSAES-PKCS1-V1_5' (default),
  11230. * 'RSA-OAEP',
  11231. * 'RAW', 'NONE', or null to perform raw RSA encryption,
  11232. * an object with an 'encode' property set to a function
  11233. * with the signature 'function(data, key)' that returns
  11234. * a binary-encoded string representing the encoded data.
  11235. * @param schemeOptions any scheme-specific options.
  11236. *
  11237. * @return the encrypted byte string.
  11238. */
  11239. key.encrypt = function(data, scheme, schemeOptions) {
  11240. if(typeof scheme === 'string') {
  11241. scheme = scheme.toUpperCase();
  11242. } else if(scheme === undefined) {
  11243. scheme = 'RSAES-PKCS1-V1_5';
  11244. }
  11245. if(scheme === 'RSAES-PKCS1-V1_5') {
  11246. scheme = {
  11247. encode: function(m, key, pub) {
  11248. return _encodePkcs1_v1_5(m, key, 0x02).getBytes();
  11249. }
  11250. };
  11251. } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {
  11252. scheme = {
  11253. encode: function(m, key) {
  11254. return forge$8.pkcs1.encode_rsa_oaep(key, m, schemeOptions);
  11255. }
  11256. };
  11257. } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {
  11258. scheme = {encode: function(e) {return e;}};
  11259. } else if(typeof scheme === 'string') {
  11260. throw new Error('Unsupported encryption scheme: "' + scheme + '".');
  11261. }
  11262. // do scheme-based encoding then rsa encryption
  11263. var e = scheme.encode(data, key, true);
  11264. return pki$4.rsa.encrypt(e, key, true);
  11265. };
  11266. /**
  11267. * Verifies the given signature against the given digest.
  11268. *
  11269. * PKCS#1 supports multiple (currently two) signature schemes:
  11270. * RSASSA-PKCS1-V1_5 and RSASSA-PSS.
  11271. *
  11272. * By default this implementation uses the "old scheme", i.e.
  11273. * RSASSA-PKCS1-V1_5, in which case once RSA-decrypted, the
  11274. * signature is an OCTET STRING that holds a DigestInfo.
  11275. *
  11276. * DigestInfo ::= SEQUENCE {
  11277. * digestAlgorithm DigestAlgorithmIdentifier,
  11278. * digest Digest
  11279. * }
  11280. * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
  11281. * Digest ::= OCTET STRING
  11282. *
  11283. * To perform PSS signature verification, provide an instance
  11284. * of Forge PSS object as the scheme parameter.
  11285. *
  11286. * @param digest the message digest hash to compare against the signature,
  11287. * as a binary-encoded string.
  11288. * @param signature the signature to verify, as a binary-encoded string.
  11289. * @param scheme signature verification scheme to use:
  11290. * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5,
  11291. * a Forge PSS object for RSASSA-PSS,
  11292. * 'NONE' or null for none, DigestInfo will not be expected, but
  11293. * PKCS#1 v1.5 padding will still be used.
  11294. * @param options optional verify options
  11295. * _parseAllDigestBytes testing flag to control parsing of all
  11296. * digest bytes. Unsupported and not for general usage.
  11297. * (default: true)
  11298. *
  11299. * @return true if the signature was verified, false if not.
  11300. */
  11301. key.verify = function(digest, signature, scheme, options) {
  11302. if(typeof scheme === 'string') {
  11303. scheme = scheme.toUpperCase();
  11304. } else if(scheme === undefined) {
  11305. scheme = 'RSASSA-PKCS1-V1_5';
  11306. }
  11307. if(options === undefined) {
  11308. options = {
  11309. _parseAllDigestBytes: true
  11310. };
  11311. }
  11312. if(!('_parseAllDigestBytes' in options)) {
  11313. options._parseAllDigestBytes = true;
  11314. }
  11315. if(scheme === 'RSASSA-PKCS1-V1_5') {
  11316. scheme = {
  11317. verify: function(digest, d) {
  11318. // remove padding
  11319. d = _decodePkcs1_v1_5(d, key, true);
  11320. // d is ASN.1 BER-encoded DigestInfo
  11321. var obj = asn1$5.fromDer(d, {
  11322. parseAllBytes: options._parseAllDigestBytes
  11323. });
  11324. // validate DigestInfo
  11325. var capture = {};
  11326. var errors = [];
  11327. if(!asn1$5.validate(obj, digestInfoValidator, capture, errors)) {
  11328. var error = new Error(
  11329. 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' +
  11330. 'DigestInfo value.');
  11331. error.errors = errors;
  11332. throw error;
  11333. }
  11334. // check hash algorithm identifier
  11335. // see PKCS1-v1-5DigestAlgorithms in RFC 8017
  11336. // FIXME: add support to vaidator for strict value choices
  11337. var oid = asn1$5.derToOid(capture.algorithmIdentifier);
  11338. if(!(oid === forge$8.oids.md2 ||
  11339. oid === forge$8.oids.md5 ||
  11340. oid === forge$8.oids.sha1 ||
  11341. oid === forge$8.oids.sha224 ||
  11342. oid === forge$8.oids.sha256 ||
  11343. oid === forge$8.oids.sha384 ||
  11344. oid === forge$8.oids.sha512 ||
  11345. oid === forge$8.oids['sha512-224'] ||
  11346. oid === forge$8.oids['sha512-256'])) {
  11347. var error = new Error(
  11348. 'Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.');
  11349. error.oid = oid;
  11350. throw error;
  11351. }
  11352. // special check for md2 and md5 that NULL parameters exist
  11353. if(oid === forge$8.oids.md2 || oid === forge$8.oids.md5) {
  11354. if(!('parameters' in capture)) {
  11355. throw new Error(
  11356. 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' +
  11357. 'DigestInfo value. ' +
  11358. 'Missing algorithm identifer NULL parameters.');
  11359. }
  11360. }
  11361. // compare the given digest to the decrypted one
  11362. return digest === capture.digest;
  11363. }
  11364. };
  11365. } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {
  11366. scheme = {
  11367. verify: function(digest, d) {
  11368. // remove padding
  11369. d = _decodePkcs1_v1_5(d, key, true);
  11370. return digest === d;
  11371. }
  11372. };
  11373. }
  11374. // do rsa decryption w/o any decoding, then verify -- which does decoding
  11375. var d = pki$4.rsa.decrypt(signature, key, true, false);
  11376. return scheme.verify(digest, d, key.n.bitLength());
  11377. };
  11378. return key;
  11379. };
  11380. /**
  11381. * Sets an RSA private key from BigIntegers modulus, exponent, primes,
  11382. * prime exponents, and modular multiplicative inverse.
  11383. *
  11384. * @param n the modulus.
  11385. * @param e the public exponent.
  11386. * @param d the private exponent ((inverse of e) mod n).
  11387. * @param p the first prime.
  11388. * @param q the second prime.
  11389. * @param dP exponent1 (d mod (p-1)).
  11390. * @param dQ exponent2 (d mod (q-1)).
  11391. * @param qInv ((inverse of q) mod p)
  11392. *
  11393. * @return the private key.
  11394. */
  11395. pki$4.setRsaPrivateKey = pki$4.rsa.setPrivateKey = function(
  11396. n, e, d, p, q, dP, dQ, qInv) {
  11397. var key = {
  11398. n: n,
  11399. e: e,
  11400. d: d,
  11401. p: p,
  11402. q: q,
  11403. dP: dP,
  11404. dQ: dQ,
  11405. qInv: qInv
  11406. };
  11407. /**
  11408. * Decrypts the given data with this private key. The decryption scheme
  11409. * must match the one used to encrypt the data.
  11410. *
  11411. * @param data the byte string to decrypt.
  11412. * @param scheme the decryption scheme to use:
  11413. * 'RSAES-PKCS1-V1_5' (default),
  11414. * 'RSA-OAEP',
  11415. * 'RAW', 'NONE', or null to perform raw RSA decryption.
  11416. * @param schemeOptions any scheme-specific options.
  11417. *
  11418. * @return the decrypted byte string.
  11419. */
  11420. key.decrypt = function(data, scheme, schemeOptions) {
  11421. if(typeof scheme === 'string') {
  11422. scheme = scheme.toUpperCase();
  11423. } else if(scheme === undefined) {
  11424. scheme = 'RSAES-PKCS1-V1_5';
  11425. }
  11426. // do rsa decryption w/o any decoding
  11427. var d = pki$4.rsa.decrypt(data, key, false, false);
  11428. if(scheme === 'RSAES-PKCS1-V1_5') {
  11429. scheme = {decode: _decodePkcs1_v1_5};
  11430. } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') {
  11431. scheme = {
  11432. decode: function(d, key) {
  11433. return forge$8.pkcs1.decode_rsa_oaep(key, d, schemeOptions);
  11434. }
  11435. };
  11436. } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) {
  11437. scheme = {decode: function(d) {return d;}};
  11438. } else {
  11439. throw new Error('Unsupported encryption scheme: "' + scheme + '".');
  11440. }
  11441. // decode according to scheme
  11442. return scheme.decode(d, key, false);
  11443. };
  11444. /**
  11445. * Signs the given digest, producing a signature.
  11446. *
  11447. * PKCS#1 supports multiple (currently two) signature schemes:
  11448. * RSASSA-PKCS1-V1_5 and RSASSA-PSS.
  11449. *
  11450. * By default this implementation uses the "old scheme", i.e.
  11451. * RSASSA-PKCS1-V1_5. In order to generate a PSS signature, provide
  11452. * an instance of Forge PSS object as the scheme parameter.
  11453. *
  11454. * @param md the message digest object with the hash to sign.
  11455. * @param scheme the signature scheme to use:
  11456. * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5,
  11457. * a Forge PSS object for RSASSA-PSS,
  11458. * 'NONE' or null for none, DigestInfo will not be used but
  11459. * PKCS#1 v1.5 padding will still be used.
  11460. *
  11461. * @return the signature as a byte string.
  11462. */
  11463. key.sign = function(md, scheme) {
  11464. /* Note: The internal implementation of RSA operations is being
  11465. transitioned away from a PKCS#1 v1.5 hard-coded scheme. Some legacy
  11466. code like the use of an encoding block identifier 'bt' will eventually
  11467. be removed. */
  11468. // private key operation
  11469. var bt = false;
  11470. if(typeof scheme === 'string') {
  11471. scheme = scheme.toUpperCase();
  11472. }
  11473. if(scheme === undefined || scheme === 'RSASSA-PKCS1-V1_5') {
  11474. scheme = {encode: emsaPkcs1v15encode};
  11475. bt = 0x01;
  11476. } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {
  11477. scheme = {encode: function() {return md;}};
  11478. bt = 0x01;
  11479. }
  11480. // encode and then encrypt
  11481. var d = scheme.encode(md, key.n.bitLength());
  11482. return pki$4.rsa.encrypt(d, key, bt);
  11483. };
  11484. return key;
  11485. };
  11486. /**
  11487. * Wraps an RSAPrivateKey ASN.1 object in an ASN.1 PrivateKeyInfo object.
  11488. *
  11489. * @param rsaKey the ASN.1 RSAPrivateKey.
  11490. *
  11491. * @return the ASN.1 PrivateKeyInfo.
  11492. */
  11493. pki$4.wrapRsaPrivateKey = function(rsaKey) {
  11494. // PrivateKeyInfo
  11495. return asn1$5.create(asn1$5.Class.UNIVERSAL, asn1$5.Type.SEQUENCE, true, [
  11496. // version (0)
  11497. asn1$5.create(asn1$5.Class.UNIVERSAL, asn1$5.Type.INTEGER, false,
  11498. asn1$5.integerToDer(0).getBytes()),
  11499. // privateKeyAlgorithm
  11500. asn1$5.create(asn1$5.Class.UNIVERSAL, asn1$5.Type.SEQUENCE, true, [
  11501. asn1$5.create(
  11502. asn1$5.Class.UNIVERSAL, asn1$5.Type.OID, false,
  11503. asn1$5.oidToDer(pki$4.oids.rsaEncryption).getBytes()),
  11504. asn1$5.create(asn1$5.Class.UNIVERSAL, asn1$5.Type.NULL, false, '')
  11505. ]),
  11506. // PrivateKey
  11507. asn1$5.create(asn1$5.Class.UNIVERSAL, asn1$5.Type.OCTETSTRING, false,
  11508. asn1$5.toDer(rsaKey).getBytes())
  11509. ]);
  11510. };
  11511. /**
  11512. * Converts a private key from an ASN.1 object.
  11513. *
  11514. * @param obj the ASN.1 representation of a PrivateKeyInfo containing an
  11515. * RSAPrivateKey or an RSAPrivateKey.
  11516. *
  11517. * @return the private key.
  11518. */
  11519. pki$4.privateKeyFromAsn1 = function(obj) {
  11520. // get PrivateKeyInfo
  11521. var capture = {};
  11522. var errors = [];
  11523. if(asn1$5.validate(obj, privateKeyValidator, capture, errors)) {
  11524. obj = asn1$5.fromDer(forge$8.util.createBuffer(capture.privateKey));
  11525. }
  11526. // get RSAPrivateKey
  11527. capture = {};
  11528. errors = [];
  11529. if(!asn1$5.validate(obj, rsaPrivateKeyValidator, capture, errors)) {
  11530. var error = new Error('Cannot read private key. ' +
  11531. 'ASN.1 object does not contain an RSAPrivateKey.');
  11532. error.errors = errors;
  11533. throw error;
  11534. }
  11535. // Note: Version is currently ignored.
  11536. // capture.privateKeyVersion
  11537. // FIXME: inefficient, get a BigInteger that uses byte strings
  11538. var n, e, d, p, q, dP, dQ, qInv;
  11539. n = forge$8.util.createBuffer(capture.privateKeyModulus).toHex();
  11540. e = forge$8.util.createBuffer(capture.privateKeyPublicExponent).toHex();
  11541. d = forge$8.util.createBuffer(capture.privateKeyPrivateExponent).toHex();
  11542. p = forge$8.util.createBuffer(capture.privateKeyPrime1).toHex();
  11543. q = forge$8.util.createBuffer(capture.privateKeyPrime2).toHex();
  11544. dP = forge$8.util.createBuffer(capture.privateKeyExponent1).toHex();
  11545. dQ = forge$8.util.createBuffer(capture.privateKeyExponent2).toHex();
  11546. qInv = forge$8.util.createBuffer(capture.privateKeyCoefficient).toHex();
  11547. // set private key
  11548. return pki$4.setRsaPrivateKey(
  11549. new BigInteger(n, 16),
  11550. new BigInteger(e, 16),
  11551. new BigInteger(d, 16),
  11552. new BigInteger(p, 16),
  11553. new BigInteger(q, 16),
  11554. new BigInteger(dP, 16),
  11555. new BigInteger(dQ, 16),
  11556. new BigInteger(qInv, 16));
  11557. };
  11558. /**
  11559. * Converts a private key to an ASN.1 RSAPrivateKey.
  11560. *
  11561. * @param key the private key.
  11562. *
  11563. * @return the ASN.1 representation of an RSAPrivateKey.
  11564. */
  11565. pki$4.privateKeyToAsn1 = pki$4.privateKeyToRSAPrivateKey = function(key) {
  11566. // RSAPrivateKey
  11567. return asn1$5.create(asn1$5.Class.UNIVERSAL, asn1$5.Type.SEQUENCE, true, [
  11568. // version (0 = only 2 primes, 1 multiple primes)
  11569. asn1$5.create(asn1$5.Class.UNIVERSAL, asn1$5.Type.INTEGER, false,
  11570. asn1$5.integerToDer(0).getBytes()),
  11571. // modulus (n)
  11572. asn1$5.create(asn1$5.Class.UNIVERSAL, asn1$5.Type.INTEGER, false,
  11573. _bnToBytes(key.n)),
  11574. // publicExponent (e)
  11575. asn1$5.create(asn1$5.Class.UNIVERSAL, asn1$5.Type.INTEGER, false,
  11576. _bnToBytes(key.e)),
  11577. // privateExponent (d)
  11578. asn1$5.create(asn1$5.Class.UNIVERSAL, asn1$5.Type.INTEGER, false,
  11579. _bnToBytes(key.d)),
  11580. // privateKeyPrime1 (p)
  11581. asn1$5.create(asn1$5.Class.UNIVERSAL, asn1$5.Type.INTEGER, false,
  11582. _bnToBytes(key.p)),
  11583. // privateKeyPrime2 (q)
  11584. asn1$5.create(asn1$5.Class.UNIVERSAL, asn1$5.Type.INTEGER, false,
  11585. _bnToBytes(key.q)),
  11586. // privateKeyExponent1 (dP)
  11587. asn1$5.create(asn1$5.Class.UNIVERSAL, asn1$5.Type.INTEGER, false,
  11588. _bnToBytes(key.dP)),
  11589. // privateKeyExponent2 (dQ)
  11590. asn1$5.create(asn1$5.Class.UNIVERSAL, asn1$5.Type.INTEGER, false,
  11591. _bnToBytes(key.dQ)),
  11592. // coefficient (qInv)
  11593. asn1$5.create(asn1$5.Class.UNIVERSAL, asn1$5.Type.INTEGER, false,
  11594. _bnToBytes(key.qInv))
  11595. ]);
  11596. };
  11597. /**
  11598. * Converts a public key from an ASN.1 SubjectPublicKeyInfo or RSAPublicKey.
  11599. *
  11600. * @param obj the asn1 representation of a SubjectPublicKeyInfo or RSAPublicKey.
  11601. *
  11602. * @return the public key.
  11603. */
  11604. pki$4.publicKeyFromAsn1 = function(obj) {
  11605. // get SubjectPublicKeyInfo
  11606. var capture = {};
  11607. var errors = [];
  11608. if(asn1$5.validate(obj, publicKeyValidator$1, capture, errors)) {
  11609. // get oid
  11610. var oid = asn1$5.derToOid(capture.publicKeyOid);
  11611. if(oid !== pki$4.oids.rsaEncryption) {
  11612. var error = new Error('Cannot read public key. Unknown OID.');
  11613. error.oid = oid;
  11614. throw error;
  11615. }
  11616. obj = capture.rsaPublicKey;
  11617. }
  11618. // get RSA params
  11619. errors = [];
  11620. if(!asn1$5.validate(obj, rsaPublicKeyValidator, capture, errors)) {
  11621. var error = new Error('Cannot read public key. ' +
  11622. 'ASN.1 object does not contain an RSAPublicKey.');
  11623. error.errors = errors;
  11624. throw error;
  11625. }
  11626. // FIXME: inefficient, get a BigInteger that uses byte strings
  11627. var n = forge$8.util.createBuffer(capture.publicKeyModulus).toHex();
  11628. var e = forge$8.util.createBuffer(capture.publicKeyExponent).toHex();
  11629. // set public key
  11630. return pki$4.setRsaPublicKey(
  11631. new BigInteger(n, 16),
  11632. new BigInteger(e, 16));
  11633. };
  11634. /**
  11635. * Converts a public key to an ASN.1 SubjectPublicKeyInfo.
  11636. *
  11637. * @param key the public key.
  11638. *
  11639. * @return the asn1 representation of a SubjectPublicKeyInfo.
  11640. */
  11641. pki$4.publicKeyToAsn1 = pki$4.publicKeyToSubjectPublicKeyInfo = function(key) {
  11642. // SubjectPublicKeyInfo
  11643. return asn1$5.create(asn1$5.Class.UNIVERSAL, asn1$5.Type.SEQUENCE, true, [
  11644. // AlgorithmIdentifier
  11645. asn1$5.create(asn1$5.Class.UNIVERSAL, asn1$5.Type.SEQUENCE, true, [
  11646. // algorithm
  11647. asn1$5.create(asn1$5.Class.UNIVERSAL, asn1$5.Type.OID, false,
  11648. asn1$5.oidToDer(pki$4.oids.rsaEncryption).getBytes()),
  11649. // parameters (null)
  11650. asn1$5.create(asn1$5.Class.UNIVERSAL, asn1$5.Type.NULL, false, '')
  11651. ]),
  11652. // subjectPublicKey
  11653. asn1$5.create(asn1$5.Class.UNIVERSAL, asn1$5.Type.BITSTRING, false, [
  11654. pki$4.publicKeyToRSAPublicKey(key)
  11655. ])
  11656. ]);
  11657. };
  11658. /**
  11659. * Converts a public key to an ASN.1 RSAPublicKey.
  11660. *
  11661. * @param key the public key.
  11662. *
  11663. * @return the asn1 representation of a RSAPublicKey.
  11664. */
  11665. pki$4.publicKeyToRSAPublicKey = function(key) {
  11666. // RSAPublicKey
  11667. return asn1$5.create(asn1$5.Class.UNIVERSAL, asn1$5.Type.SEQUENCE, true, [
  11668. // modulus (n)
  11669. asn1$5.create(asn1$5.Class.UNIVERSAL, asn1$5.Type.INTEGER, false,
  11670. _bnToBytes(key.n)),
  11671. // publicExponent (e)
  11672. asn1$5.create(asn1$5.Class.UNIVERSAL, asn1$5.Type.INTEGER, false,
  11673. _bnToBytes(key.e))
  11674. ]);
  11675. };
  11676. /**
  11677. * Encodes a message using PKCS#1 v1.5 padding.
  11678. *
  11679. * @param m the message to encode.
  11680. * @param key the RSA key to use.
  11681. * @param bt the block type to use, i.e. either 0x01 (for signing) or 0x02
  11682. * (for encryption).
  11683. *
  11684. * @return the padded byte buffer.
  11685. */
  11686. function _encodePkcs1_v1_5(m, key, bt) {
  11687. var eb = forge$8.util.createBuffer();
  11688. // get the length of the modulus in bytes
  11689. var k = Math.ceil(key.n.bitLength() / 8);
  11690. /* use PKCS#1 v1.5 padding */
  11691. if(m.length > (k - 11)) {
  11692. var error = new Error('Message is too long for PKCS#1 v1.5 padding.');
  11693. error.length = m.length;
  11694. error.max = k - 11;
  11695. throw error;
  11696. }
  11697. /* A block type BT, a padding string PS, and the data D shall be
  11698. formatted into an octet string EB, the encryption block:
  11699. EB = 00 || BT || PS || 00 || D
  11700. The block type BT shall be a single octet indicating the structure of
  11701. the encryption block. For this version of the document it shall have
  11702. value 00, 01, or 02. For a private-key operation, the block type
  11703. shall be 00 or 01. For a public-key operation, it shall be 02.
  11704. The padding string PS shall consist of k-3-||D|| octets. For block
  11705. type 00, the octets shall have value 00; for block type 01, they
  11706. shall have value FF; and for block type 02, they shall be
  11707. pseudorandomly generated and nonzero. This makes the length of the
  11708. encryption block EB equal to k. */
  11709. // build the encryption block
  11710. eb.putByte(0x00);
  11711. eb.putByte(bt);
  11712. // create the padding
  11713. var padNum = k - 3 - m.length;
  11714. var padByte;
  11715. // private key op
  11716. if(bt === 0x00 || bt === 0x01) {
  11717. padByte = (bt === 0x00) ? 0x00 : 0xFF;
  11718. for(var i = 0; i < padNum; ++i) {
  11719. eb.putByte(padByte);
  11720. }
  11721. } else {
  11722. // public key op
  11723. // pad with random non-zero values
  11724. while(padNum > 0) {
  11725. var numZeros = 0;
  11726. var padBytes = forge$8.random.getBytes(padNum);
  11727. for(var i = 0; i < padNum; ++i) {
  11728. padByte = padBytes.charCodeAt(i);
  11729. if(padByte === 0) {
  11730. ++numZeros;
  11731. } else {
  11732. eb.putByte(padByte);
  11733. }
  11734. }
  11735. padNum = numZeros;
  11736. }
  11737. }
  11738. // zero followed by message
  11739. eb.putByte(0x00);
  11740. eb.putBytes(m);
  11741. return eb;
  11742. }
  11743. /**
  11744. * Decodes a message using PKCS#1 v1.5 padding.
  11745. *
  11746. * @param em the message to decode.
  11747. * @param key the RSA key to use.
  11748. * @param pub true if the key is a public key, false if it is private.
  11749. * @param ml the message length, if specified.
  11750. *
  11751. * @return the decoded bytes.
  11752. */
  11753. function _decodePkcs1_v1_5(em, key, pub, ml) {
  11754. // get the length of the modulus in bytes
  11755. var k = Math.ceil(key.n.bitLength() / 8);
  11756. /* It is an error if any of the following conditions occurs:
  11757. 1. The encryption block EB cannot be parsed unambiguously.
  11758. 2. The padding string PS consists of fewer than eight octets
  11759. or is inconsisent with the block type BT.
  11760. 3. The decryption process is a public-key operation and the block
  11761. type BT is not 00 or 01, or the decryption process is a
  11762. private-key operation and the block type is not 02.
  11763. */
  11764. // parse the encryption block
  11765. var eb = forge$8.util.createBuffer(em);
  11766. var first = eb.getByte();
  11767. var bt = eb.getByte();
  11768. if(first !== 0x00 ||
  11769. (pub && bt !== 0x00 && bt !== 0x01) ||
  11770. (!pub && bt != 0x02) ||
  11771. (pub && bt === 0x00 && typeof(ml) === 'undefined')) {
  11772. throw new Error('Encryption block is invalid.');
  11773. }
  11774. var padNum = 0;
  11775. if(bt === 0x00) {
  11776. // check all padding bytes for 0x00
  11777. padNum = k - 3 - ml;
  11778. for(var i = 0; i < padNum; ++i) {
  11779. if(eb.getByte() !== 0x00) {
  11780. throw new Error('Encryption block is invalid.');
  11781. }
  11782. }
  11783. } else if(bt === 0x01) {
  11784. // find the first byte that isn't 0xFF, should be after all padding
  11785. padNum = 0;
  11786. while(eb.length() > 1) {
  11787. if(eb.getByte() !== 0xFF) {
  11788. --eb.read;
  11789. break;
  11790. }
  11791. ++padNum;
  11792. }
  11793. } else if(bt === 0x02) {
  11794. // look for 0x00 byte
  11795. padNum = 0;
  11796. while(eb.length() > 1) {
  11797. if(eb.getByte() === 0x00) {
  11798. --eb.read;
  11799. break;
  11800. }
  11801. ++padNum;
  11802. }
  11803. }
  11804. // zero must be 0x00 and padNum must be (k - 3 - message length)
  11805. var zero = eb.getByte();
  11806. if(zero !== 0x00 || padNum !== (k - 3 - eb.length())) {
  11807. throw new Error('Encryption block is invalid.');
  11808. }
  11809. return eb.getBytes();
  11810. }
  11811. /**
  11812. * Runs the key-generation algorithm asynchronously, either in the background
  11813. * via Web Workers, or using the main thread and setImmediate.
  11814. *
  11815. * @param state the key-pair generation state.
  11816. * @param [options] options for key-pair generation:
  11817. * workerScript the worker script URL.
  11818. * workers the number of web workers (if supported) to use,
  11819. * (default: 2, -1 to use estimated cores minus one).
  11820. * workLoad the size of the work load, ie: number of possible prime
  11821. * numbers for each web worker to check per work assignment,
  11822. * (default: 100).
  11823. * @param callback(err, keypair) called once the operation completes.
  11824. */
  11825. function _generateKeyPair(state, options, callback) {
  11826. if(typeof options === 'function') {
  11827. callback = options;
  11828. options = {};
  11829. }
  11830. options = options || {};
  11831. var opts = {
  11832. algorithm: {
  11833. name: options.algorithm || 'PRIMEINC',
  11834. options: {
  11835. workers: options.workers || 2,
  11836. workLoad: options.workLoad || 100,
  11837. workerScript: options.workerScript
  11838. }
  11839. }
  11840. };
  11841. if('prng' in options) {
  11842. opts.prng = options.prng;
  11843. }
  11844. generate();
  11845. function generate() {
  11846. // find p and then q (done in series to simplify)
  11847. getPrime(state.pBits, function(err, num) {
  11848. if(err) {
  11849. return callback(err);
  11850. }
  11851. state.p = num;
  11852. if(state.q !== null) {
  11853. return finish(err, state.q);
  11854. }
  11855. getPrime(state.qBits, finish);
  11856. });
  11857. }
  11858. function getPrime(bits, callback) {
  11859. forge$8.prime.generateProbablePrime(bits, opts, callback);
  11860. }
  11861. function finish(err, num) {
  11862. if(err) {
  11863. return callback(err);
  11864. }
  11865. // set q
  11866. state.q = num;
  11867. // ensure p is larger than q (swap them if not)
  11868. if(state.p.compareTo(state.q) < 0) {
  11869. var tmp = state.p;
  11870. state.p = state.q;
  11871. state.q = tmp;
  11872. }
  11873. // ensure p is coprime with e
  11874. if(state.p.subtract(BigInteger.ONE).gcd(state.e)
  11875. .compareTo(BigInteger.ONE) !== 0) {
  11876. state.p = null;
  11877. generate();
  11878. return;
  11879. }
  11880. // ensure q is coprime with e
  11881. if(state.q.subtract(BigInteger.ONE).gcd(state.e)
  11882. .compareTo(BigInteger.ONE) !== 0) {
  11883. state.q = null;
  11884. getPrime(state.qBits, finish);
  11885. return;
  11886. }
  11887. // compute phi: (p - 1)(q - 1) (Euler's totient function)
  11888. state.p1 = state.p.subtract(BigInteger.ONE);
  11889. state.q1 = state.q.subtract(BigInteger.ONE);
  11890. state.phi = state.p1.multiply(state.q1);
  11891. // ensure e and phi are coprime
  11892. if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) !== 0) {
  11893. // phi and e aren't coprime, so generate a new p and q
  11894. state.p = state.q = null;
  11895. generate();
  11896. return;
  11897. }
  11898. // create n, ensure n is has the right number of bits
  11899. state.n = state.p.multiply(state.q);
  11900. if(state.n.bitLength() !== state.bits) {
  11901. // failed, get new q
  11902. state.q = null;
  11903. getPrime(state.qBits, finish);
  11904. return;
  11905. }
  11906. // set keys
  11907. var d = state.e.modInverse(state.phi);
  11908. state.keys = {
  11909. privateKey: pki$4.rsa.setPrivateKey(
  11910. state.n, state.e, d, state.p, state.q,
  11911. d.mod(state.p1), d.mod(state.q1),
  11912. state.q.modInverse(state.p)),
  11913. publicKey: pki$4.rsa.setPublicKey(state.n, state.e)
  11914. };
  11915. callback(null, state.keys);
  11916. }
  11917. }
  11918. /**
  11919. * Converts a positive BigInteger into 2's-complement big-endian bytes.
  11920. *
  11921. * @param b the big integer to convert.
  11922. *
  11923. * @return the bytes.
  11924. */
  11925. function _bnToBytes(b) {
  11926. // prepend 0x00 if first byte >= 0x80
  11927. var hex = b.toString(16);
  11928. if(hex[0] >= '8') {
  11929. hex = '00' + hex;
  11930. }
  11931. var bytes = forge$8.util.hexToBytes(hex);
  11932. // ensure integer is minimally-encoded
  11933. if(bytes.length > 1 &&
  11934. // leading 0x00 for positive integer
  11935. ((bytes.charCodeAt(0) === 0 &&
  11936. (bytes.charCodeAt(1) & 0x80) === 0) ||
  11937. // leading 0xFF for negative integer
  11938. (bytes.charCodeAt(0) === 0xFF &&
  11939. (bytes.charCodeAt(1) & 0x80) === 0x80))) {
  11940. return bytes.substr(1);
  11941. }
  11942. return bytes;
  11943. }
  11944. /**
  11945. * Returns the required number of Miller-Rabin tests to generate a
  11946. * prime with an error probability of (1/2)^80.
  11947. *
  11948. * See Handbook of Applied Cryptography Chapter 4, Table 4.4.
  11949. *
  11950. * @param bits the bit size.
  11951. *
  11952. * @return the required number of iterations.
  11953. */
  11954. function _getMillerRabinTests(bits) {
  11955. if(bits <= 100) return 27;
  11956. if(bits <= 150) return 18;
  11957. if(bits <= 200) return 15;
  11958. if(bits <= 250) return 12;
  11959. if(bits <= 300) return 9;
  11960. if(bits <= 350) return 8;
  11961. if(bits <= 400) return 7;
  11962. if(bits <= 500) return 6;
  11963. if(bits <= 600) return 5;
  11964. if(bits <= 800) return 4;
  11965. if(bits <= 1250) return 3;
  11966. return 2;
  11967. }
  11968. /**
  11969. * Performs feature detection on the Node crypto interface.
  11970. *
  11971. * @param fn the feature (function) to detect.
  11972. *
  11973. * @return true if detected, false if not.
  11974. */
  11975. function _detectNodeCrypto(fn) {
  11976. return forge$8.util.isNodejs && typeof _crypto[fn] === 'function';
  11977. }
  11978. /**
  11979. * Performs feature detection on the SubtleCrypto interface.
  11980. *
  11981. * @param fn the feature (function) to detect.
  11982. *
  11983. * @return true if detected, false if not.
  11984. */
  11985. function _detectSubtleCrypto(fn) {
  11986. return (typeof util.globalScope !== 'undefined' &&
  11987. typeof util.globalScope.crypto === 'object' &&
  11988. typeof util.globalScope.crypto.subtle === 'object' &&
  11989. typeof util.globalScope.crypto.subtle[fn] === 'function');
  11990. }
  11991. /**
  11992. * Performs feature detection on the deprecated Microsoft Internet Explorer
  11993. * outdated SubtleCrypto interface. This function should only be used after
  11994. * checking for the modern, standard SubtleCrypto interface.
  11995. *
  11996. * @param fn the feature (function) to detect.
  11997. *
  11998. * @return true if detected, false if not.
  11999. */
  12000. function _detectSubtleMsCrypto(fn) {
  12001. return (typeof util.globalScope !== 'undefined' &&
  12002. typeof util.globalScope.msCrypto === 'object' &&
  12003. typeof util.globalScope.msCrypto.subtle === 'object' &&
  12004. typeof util.globalScope.msCrypto.subtle[fn] === 'function');
  12005. }
  12006. function _intToUint8Array(x) {
  12007. var bytes = forge$8.util.hexToBytes(x.toString(16));
  12008. var buffer = new Uint8Array(bytes.length);
  12009. for(var i = 0; i < bytes.length; ++i) {
  12010. buffer[i] = bytes.charCodeAt(i);
  12011. }
  12012. return buffer;
  12013. }
  12014. /**
  12015. * Password-based encryption functions.
  12016. *
  12017. * @author Dave Longley
  12018. * @author Stefan Siegl <stesie@brokenpipe.de>
  12019. *
  12020. * Copyright (c) 2010-2013 Digital Bazaar, Inc.
  12021. * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>
  12022. *
  12023. * An EncryptedPrivateKeyInfo:
  12024. *
  12025. * EncryptedPrivateKeyInfo ::= SEQUENCE {
  12026. * encryptionAlgorithm EncryptionAlgorithmIdentifier,
  12027. * encryptedData EncryptedData }
  12028. *
  12029. * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
  12030. *
  12031. * EncryptedData ::= OCTET STRING
  12032. */
  12033. var forge$7 = forge$s;
  12034. // shortcut for asn.1 API
  12035. var asn1$4 = forge$7.asn1;
  12036. /* Password-based encryption implementation. */
  12037. var pki$3 = forge$7.pki = forge$7.pki || {};
  12038. pki$3.pbe = forge$7.pbe = forge$7.pbe || {};
  12039. var oids$1 = pki$3.oids;
  12040. // validator for an EncryptedPrivateKeyInfo structure
  12041. // Note: Currently only works w/algorithm params
  12042. var encryptedPrivateKeyValidator = {
  12043. name: 'EncryptedPrivateKeyInfo',
  12044. tagClass: asn1$4.Class.UNIVERSAL,
  12045. type: asn1$4.Type.SEQUENCE,
  12046. constructed: true,
  12047. value: [{
  12048. name: 'EncryptedPrivateKeyInfo.encryptionAlgorithm',
  12049. tagClass: asn1$4.Class.UNIVERSAL,
  12050. type: asn1$4.Type.SEQUENCE,
  12051. constructed: true,
  12052. value: [{
  12053. name: 'AlgorithmIdentifier.algorithm',
  12054. tagClass: asn1$4.Class.UNIVERSAL,
  12055. type: asn1$4.Type.OID,
  12056. constructed: false,
  12057. capture: 'encryptionOid'
  12058. }, {
  12059. name: 'AlgorithmIdentifier.parameters',
  12060. tagClass: asn1$4.Class.UNIVERSAL,
  12061. type: asn1$4.Type.SEQUENCE,
  12062. constructed: true,
  12063. captureAsn1: 'encryptionParams'
  12064. }]
  12065. }, {
  12066. // encryptedData
  12067. name: 'EncryptedPrivateKeyInfo.encryptedData',
  12068. tagClass: asn1$4.Class.UNIVERSAL,
  12069. type: asn1$4.Type.OCTETSTRING,
  12070. constructed: false,
  12071. capture: 'encryptedData'
  12072. }]
  12073. };
  12074. // validator for a PBES2Algorithms structure
  12075. // Note: Currently only works w/PBKDF2 + AES encryption schemes
  12076. var PBES2AlgorithmsValidator = {
  12077. name: 'PBES2Algorithms',
  12078. tagClass: asn1$4.Class.UNIVERSAL,
  12079. type: asn1$4.Type.SEQUENCE,
  12080. constructed: true,
  12081. value: [{
  12082. name: 'PBES2Algorithms.keyDerivationFunc',
  12083. tagClass: asn1$4.Class.UNIVERSAL,
  12084. type: asn1$4.Type.SEQUENCE,
  12085. constructed: true,
  12086. value: [{
  12087. name: 'PBES2Algorithms.keyDerivationFunc.oid',
  12088. tagClass: asn1$4.Class.UNIVERSAL,
  12089. type: asn1$4.Type.OID,
  12090. constructed: false,
  12091. capture: 'kdfOid'
  12092. }, {
  12093. name: 'PBES2Algorithms.params',
  12094. tagClass: asn1$4.Class.UNIVERSAL,
  12095. type: asn1$4.Type.SEQUENCE,
  12096. constructed: true,
  12097. value: [{
  12098. name: 'PBES2Algorithms.params.salt',
  12099. tagClass: asn1$4.Class.UNIVERSAL,
  12100. type: asn1$4.Type.OCTETSTRING,
  12101. constructed: false,
  12102. capture: 'kdfSalt'
  12103. }, {
  12104. name: 'PBES2Algorithms.params.iterationCount',
  12105. tagClass: asn1$4.Class.UNIVERSAL,
  12106. type: asn1$4.Type.INTEGER,
  12107. constructed: false,
  12108. capture: 'kdfIterationCount'
  12109. }, {
  12110. name: 'PBES2Algorithms.params.keyLength',
  12111. tagClass: asn1$4.Class.UNIVERSAL,
  12112. type: asn1$4.Type.INTEGER,
  12113. constructed: false,
  12114. optional: true,
  12115. capture: 'keyLength'
  12116. }, {
  12117. // prf
  12118. name: 'PBES2Algorithms.params.prf',
  12119. tagClass: asn1$4.Class.UNIVERSAL,
  12120. type: asn1$4.Type.SEQUENCE,
  12121. constructed: true,
  12122. optional: true,
  12123. value: [{
  12124. name: 'PBES2Algorithms.params.prf.algorithm',
  12125. tagClass: asn1$4.Class.UNIVERSAL,
  12126. type: asn1$4.Type.OID,
  12127. constructed: false,
  12128. capture: 'prfOid'
  12129. }]
  12130. }]
  12131. }]
  12132. }, {
  12133. name: 'PBES2Algorithms.encryptionScheme',
  12134. tagClass: asn1$4.Class.UNIVERSAL,
  12135. type: asn1$4.Type.SEQUENCE,
  12136. constructed: true,
  12137. value: [{
  12138. name: 'PBES2Algorithms.encryptionScheme.oid',
  12139. tagClass: asn1$4.Class.UNIVERSAL,
  12140. type: asn1$4.Type.OID,
  12141. constructed: false,
  12142. capture: 'encOid'
  12143. }, {
  12144. name: 'PBES2Algorithms.encryptionScheme.iv',
  12145. tagClass: asn1$4.Class.UNIVERSAL,
  12146. type: asn1$4.Type.OCTETSTRING,
  12147. constructed: false,
  12148. capture: 'encIv'
  12149. }]
  12150. }]
  12151. };
  12152. var pkcs12PbeParamsValidator = {
  12153. name: 'pkcs-12PbeParams',
  12154. tagClass: asn1$4.Class.UNIVERSAL,
  12155. type: asn1$4.Type.SEQUENCE,
  12156. constructed: true,
  12157. value: [{
  12158. name: 'pkcs-12PbeParams.salt',
  12159. tagClass: asn1$4.Class.UNIVERSAL,
  12160. type: asn1$4.Type.OCTETSTRING,
  12161. constructed: false,
  12162. capture: 'salt'
  12163. }, {
  12164. name: 'pkcs-12PbeParams.iterations',
  12165. tagClass: asn1$4.Class.UNIVERSAL,
  12166. type: asn1$4.Type.INTEGER,
  12167. constructed: false,
  12168. capture: 'iterations'
  12169. }]
  12170. };
  12171. /**
  12172. * Encrypts a ASN.1 PrivateKeyInfo object, producing an EncryptedPrivateKeyInfo.
  12173. *
  12174. * PBES2Algorithms ALGORITHM-IDENTIFIER ::=
  12175. * { {PBES2-params IDENTIFIED BY id-PBES2}, ...}
  12176. *
  12177. * id-PBES2 OBJECT IDENTIFIER ::= {pkcs-5 13}
  12178. *
  12179. * PBES2-params ::= SEQUENCE {
  12180. * keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},
  12181. * encryptionScheme AlgorithmIdentifier {{PBES2-Encs}}
  12182. * }
  12183. *
  12184. * PBES2-KDFs ALGORITHM-IDENTIFIER ::=
  12185. * { {PBKDF2-params IDENTIFIED BY id-PBKDF2}, ... }
  12186. *
  12187. * PBES2-Encs ALGORITHM-IDENTIFIER ::= { ... }
  12188. *
  12189. * PBKDF2-params ::= SEQUENCE {
  12190. * salt CHOICE {
  12191. * specified OCTET STRING,
  12192. * otherSource AlgorithmIdentifier {{PBKDF2-SaltSources}}
  12193. * },
  12194. * iterationCount INTEGER (1..MAX),
  12195. * keyLength INTEGER (1..MAX) OPTIONAL,
  12196. * prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1
  12197. * }
  12198. *
  12199. * @param obj the ASN.1 PrivateKeyInfo object.
  12200. * @param password the password to encrypt with.
  12201. * @param options:
  12202. * algorithm the encryption algorithm to use
  12203. * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'.
  12204. * count the iteration count to use.
  12205. * saltSize the salt size to use.
  12206. * prfAlgorithm the PRF message digest algorithm to use
  12207. * ('sha1', 'sha224', 'sha256', 'sha384', 'sha512')
  12208. *
  12209. * @return the ASN.1 EncryptedPrivateKeyInfo.
  12210. */
  12211. pki$3.encryptPrivateKeyInfo = function(obj, password, options) {
  12212. // set default options
  12213. options = options || {};
  12214. options.saltSize = options.saltSize || 8;
  12215. options.count = options.count || 2048;
  12216. options.algorithm = options.algorithm || 'aes128';
  12217. options.prfAlgorithm = options.prfAlgorithm || 'sha1';
  12218. // generate PBE params
  12219. var salt = forge$7.random.getBytesSync(options.saltSize);
  12220. var count = options.count;
  12221. var countBytes = asn1$4.integerToDer(count);
  12222. var dkLen;
  12223. var encryptionAlgorithm;
  12224. var encryptedData;
  12225. if(options.algorithm.indexOf('aes') === 0 || options.algorithm === 'des') {
  12226. // do PBES2
  12227. var ivLen, encOid, cipherFn;
  12228. switch(options.algorithm) {
  12229. case 'aes128':
  12230. dkLen = 16;
  12231. ivLen = 16;
  12232. encOid = oids$1['aes128-CBC'];
  12233. cipherFn = forge$7.aes.createEncryptionCipher;
  12234. break;
  12235. case 'aes192':
  12236. dkLen = 24;
  12237. ivLen = 16;
  12238. encOid = oids$1['aes192-CBC'];
  12239. cipherFn = forge$7.aes.createEncryptionCipher;
  12240. break;
  12241. case 'aes256':
  12242. dkLen = 32;
  12243. ivLen = 16;
  12244. encOid = oids$1['aes256-CBC'];
  12245. cipherFn = forge$7.aes.createEncryptionCipher;
  12246. break;
  12247. case 'des':
  12248. dkLen = 8;
  12249. ivLen = 8;
  12250. encOid = oids$1['desCBC'];
  12251. cipherFn = forge$7.des.createEncryptionCipher;
  12252. break;
  12253. default:
  12254. var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.');
  12255. error.algorithm = options.algorithm;
  12256. throw error;
  12257. }
  12258. // get PRF message digest
  12259. var prfAlgorithm = 'hmacWith' + options.prfAlgorithm.toUpperCase();
  12260. var md = prfAlgorithmToMessageDigest(prfAlgorithm);
  12261. // encrypt private key using pbe SHA-1 and AES/DES
  12262. var dk = forge$7.pkcs5.pbkdf2(password, salt, count, dkLen, md);
  12263. var iv = forge$7.random.getBytesSync(ivLen);
  12264. var cipher = cipherFn(dk);
  12265. cipher.start(iv);
  12266. cipher.update(asn1$4.toDer(obj));
  12267. cipher.finish();
  12268. encryptedData = cipher.output.getBytes();
  12269. // get PBKDF2-params
  12270. var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm);
  12271. encryptionAlgorithm = asn1$4.create(
  12272. asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [
  12273. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false,
  12274. asn1$4.oidToDer(oids$1['pkcs5PBES2']).getBytes()),
  12275. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [
  12276. // keyDerivationFunc
  12277. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [
  12278. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false,
  12279. asn1$4.oidToDer(oids$1['pkcs5PBKDF2']).getBytes()),
  12280. // PBKDF2-params
  12281. params
  12282. ]),
  12283. // encryptionScheme
  12284. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [
  12285. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false,
  12286. asn1$4.oidToDer(encOid).getBytes()),
  12287. // iv
  12288. asn1$4.create(
  12289. asn1$4.Class.UNIVERSAL, asn1$4.Type.OCTETSTRING, false, iv)
  12290. ])
  12291. ])
  12292. ]);
  12293. } else if(options.algorithm === '3des') {
  12294. // Do PKCS12 PBE
  12295. dkLen = 24;
  12296. var saltBytes = new forge$7.util.ByteBuffer(salt);
  12297. var dk = pki$3.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen);
  12298. var iv = pki$3.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen);
  12299. var cipher = forge$7.des.createEncryptionCipher(dk);
  12300. cipher.start(iv);
  12301. cipher.update(asn1$4.toDer(obj));
  12302. cipher.finish();
  12303. encryptedData = cipher.output.getBytes();
  12304. encryptionAlgorithm = asn1$4.create(
  12305. asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [
  12306. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false,
  12307. asn1$4.oidToDer(oids$1['pbeWithSHAAnd3-KeyTripleDES-CBC']).getBytes()),
  12308. // pkcs-12PbeParams
  12309. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [
  12310. // salt
  12311. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OCTETSTRING, false, salt),
  12312. // iteration count
  12313. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.INTEGER, false,
  12314. countBytes.getBytes())
  12315. ])
  12316. ]);
  12317. } else {
  12318. var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.');
  12319. error.algorithm = options.algorithm;
  12320. throw error;
  12321. }
  12322. // EncryptedPrivateKeyInfo
  12323. var rval = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [
  12324. // encryptionAlgorithm
  12325. encryptionAlgorithm,
  12326. // encryptedData
  12327. asn1$4.create(
  12328. asn1$4.Class.UNIVERSAL, asn1$4.Type.OCTETSTRING, false, encryptedData)
  12329. ]);
  12330. return rval;
  12331. };
  12332. /**
  12333. * Decrypts a ASN.1 PrivateKeyInfo object.
  12334. *
  12335. * @param obj the ASN.1 EncryptedPrivateKeyInfo object.
  12336. * @param password the password to decrypt with.
  12337. *
  12338. * @return the ASN.1 PrivateKeyInfo on success, null on failure.
  12339. */
  12340. pki$3.decryptPrivateKeyInfo = function(obj, password) {
  12341. var rval = null;
  12342. // get PBE params
  12343. var capture = {};
  12344. var errors = [];
  12345. if(!asn1$4.validate(obj, encryptedPrivateKeyValidator, capture, errors)) {
  12346. var error = new Error('Cannot read encrypted private key. ' +
  12347. 'ASN.1 object is not a supported EncryptedPrivateKeyInfo.');
  12348. error.errors = errors;
  12349. throw error;
  12350. }
  12351. // get cipher
  12352. var oid = asn1$4.derToOid(capture.encryptionOid);
  12353. var cipher = pki$3.pbe.getCipher(oid, capture.encryptionParams, password);
  12354. // get encrypted data
  12355. var encrypted = forge$7.util.createBuffer(capture.encryptedData);
  12356. cipher.update(encrypted);
  12357. if(cipher.finish()) {
  12358. rval = asn1$4.fromDer(cipher.output);
  12359. }
  12360. return rval;
  12361. };
  12362. /**
  12363. * Converts a EncryptedPrivateKeyInfo to PEM format.
  12364. *
  12365. * @param epki the EncryptedPrivateKeyInfo.
  12366. * @param maxline the maximum characters per line, defaults to 64.
  12367. *
  12368. * @return the PEM-formatted encrypted private key.
  12369. */
  12370. pki$3.encryptedPrivateKeyToPem = function(epki, maxline) {
  12371. // convert to DER, then PEM-encode
  12372. var msg = {
  12373. type: 'ENCRYPTED PRIVATE KEY',
  12374. body: asn1$4.toDer(epki).getBytes()
  12375. };
  12376. return forge$7.pem.encode(msg, {maxline: maxline});
  12377. };
  12378. /**
  12379. * Converts a PEM-encoded EncryptedPrivateKeyInfo to ASN.1 format. Decryption
  12380. * is not performed.
  12381. *
  12382. * @param pem the EncryptedPrivateKeyInfo in PEM-format.
  12383. *
  12384. * @return the ASN.1 EncryptedPrivateKeyInfo.
  12385. */
  12386. pki$3.encryptedPrivateKeyFromPem = function(pem) {
  12387. var msg = forge$7.pem.decode(pem)[0];
  12388. if(msg.type !== 'ENCRYPTED PRIVATE KEY') {
  12389. var error = new Error('Could not convert encrypted private key from PEM; ' +
  12390. 'PEM header type is "ENCRYPTED PRIVATE KEY".');
  12391. error.headerType = msg.type;
  12392. throw error;
  12393. }
  12394. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  12395. throw new Error('Could not convert encrypted private key from PEM; ' +
  12396. 'PEM is encrypted.');
  12397. }
  12398. // convert DER to ASN.1 object
  12399. return asn1$4.fromDer(msg.body);
  12400. };
  12401. /**
  12402. * Encrypts an RSA private key. By default, the key will be wrapped in
  12403. * a PrivateKeyInfo and encrypted to produce a PKCS#8 EncryptedPrivateKeyInfo.
  12404. * This is the standard, preferred way to encrypt a private key.
  12405. *
  12406. * To produce a non-standard PEM-encrypted private key that uses encapsulated
  12407. * headers to indicate the encryption algorithm (old-style non-PKCS#8 OpenSSL
  12408. * private key encryption), set the 'legacy' option to true. Note: Using this
  12409. * option will cause the iteration count to be forced to 1.
  12410. *
  12411. * Note: The 'des' algorithm is supported, but it is not considered to be
  12412. * secure because it only uses a single 56-bit key. If possible, it is highly
  12413. * recommended that a different algorithm be used.
  12414. *
  12415. * @param rsaKey the RSA key to encrypt.
  12416. * @param password the password to use.
  12417. * @param options:
  12418. * algorithm: the encryption algorithm to use
  12419. * ('aes128', 'aes192', 'aes256', '3des', 'des').
  12420. * count: the iteration count to use.
  12421. * saltSize: the salt size to use.
  12422. * legacy: output an old non-PKCS#8 PEM-encrypted+encapsulated
  12423. * headers (DEK-Info) private key.
  12424. *
  12425. * @return the PEM-encoded ASN.1 EncryptedPrivateKeyInfo.
  12426. */
  12427. pki$3.encryptRsaPrivateKey = function(rsaKey, password, options) {
  12428. // standard PKCS#8
  12429. options = options || {};
  12430. if(!options.legacy) {
  12431. // encrypt PrivateKeyInfo
  12432. var rval = pki$3.wrapRsaPrivateKey(pki$3.privateKeyToAsn1(rsaKey));
  12433. rval = pki$3.encryptPrivateKeyInfo(rval, password, options);
  12434. return pki$3.encryptedPrivateKeyToPem(rval);
  12435. }
  12436. // legacy non-PKCS#8
  12437. var algorithm;
  12438. var iv;
  12439. var dkLen;
  12440. var cipherFn;
  12441. switch(options.algorithm) {
  12442. case 'aes128':
  12443. algorithm = 'AES-128-CBC';
  12444. dkLen = 16;
  12445. iv = forge$7.random.getBytesSync(16);
  12446. cipherFn = forge$7.aes.createEncryptionCipher;
  12447. break;
  12448. case 'aes192':
  12449. algorithm = 'AES-192-CBC';
  12450. dkLen = 24;
  12451. iv = forge$7.random.getBytesSync(16);
  12452. cipherFn = forge$7.aes.createEncryptionCipher;
  12453. break;
  12454. case 'aes256':
  12455. algorithm = 'AES-256-CBC';
  12456. dkLen = 32;
  12457. iv = forge$7.random.getBytesSync(16);
  12458. cipherFn = forge$7.aes.createEncryptionCipher;
  12459. break;
  12460. case '3des':
  12461. algorithm = 'DES-EDE3-CBC';
  12462. dkLen = 24;
  12463. iv = forge$7.random.getBytesSync(8);
  12464. cipherFn = forge$7.des.createEncryptionCipher;
  12465. break;
  12466. case 'des':
  12467. algorithm = 'DES-CBC';
  12468. dkLen = 8;
  12469. iv = forge$7.random.getBytesSync(8);
  12470. cipherFn = forge$7.des.createEncryptionCipher;
  12471. break;
  12472. default:
  12473. var error = new Error('Could not encrypt RSA private key; unsupported ' +
  12474. 'encryption algorithm "' + options.algorithm + '".');
  12475. error.algorithm = options.algorithm;
  12476. throw error;
  12477. }
  12478. // encrypt private key using OpenSSL legacy key derivation
  12479. var dk = forge$7.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);
  12480. var cipher = cipherFn(dk);
  12481. cipher.start(iv);
  12482. cipher.update(asn1$4.toDer(pki$3.privateKeyToAsn1(rsaKey)));
  12483. cipher.finish();
  12484. var msg = {
  12485. type: 'RSA PRIVATE KEY',
  12486. procType: {
  12487. version: '4',
  12488. type: 'ENCRYPTED'
  12489. },
  12490. dekInfo: {
  12491. algorithm: algorithm,
  12492. parameters: forge$7.util.bytesToHex(iv).toUpperCase()
  12493. },
  12494. body: cipher.output.getBytes()
  12495. };
  12496. return forge$7.pem.encode(msg);
  12497. };
  12498. /**
  12499. * Decrypts an RSA private key.
  12500. *
  12501. * @param pem the PEM-formatted EncryptedPrivateKeyInfo to decrypt.
  12502. * @param password the password to use.
  12503. *
  12504. * @return the RSA key on success, null on failure.
  12505. */
  12506. pki$3.decryptRsaPrivateKey = function(pem, password) {
  12507. var rval = null;
  12508. var msg = forge$7.pem.decode(pem)[0];
  12509. if(msg.type !== 'ENCRYPTED PRIVATE KEY' &&
  12510. msg.type !== 'PRIVATE KEY' &&
  12511. msg.type !== 'RSA PRIVATE KEY') {
  12512. var error = new Error('Could not convert private key from PEM; PEM header type ' +
  12513. 'is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');
  12514. error.headerType = error;
  12515. throw error;
  12516. }
  12517. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  12518. var dkLen;
  12519. var cipherFn;
  12520. switch(msg.dekInfo.algorithm) {
  12521. case 'DES-CBC':
  12522. dkLen = 8;
  12523. cipherFn = forge$7.des.createDecryptionCipher;
  12524. break;
  12525. case 'DES-EDE3-CBC':
  12526. dkLen = 24;
  12527. cipherFn = forge$7.des.createDecryptionCipher;
  12528. break;
  12529. case 'AES-128-CBC':
  12530. dkLen = 16;
  12531. cipherFn = forge$7.aes.createDecryptionCipher;
  12532. break;
  12533. case 'AES-192-CBC':
  12534. dkLen = 24;
  12535. cipherFn = forge$7.aes.createDecryptionCipher;
  12536. break;
  12537. case 'AES-256-CBC':
  12538. dkLen = 32;
  12539. cipherFn = forge$7.aes.createDecryptionCipher;
  12540. break;
  12541. case 'RC2-40-CBC':
  12542. dkLen = 5;
  12543. cipherFn = function(key) {
  12544. return forge$7.rc2.createDecryptionCipher(key, 40);
  12545. };
  12546. break;
  12547. case 'RC2-64-CBC':
  12548. dkLen = 8;
  12549. cipherFn = function(key) {
  12550. return forge$7.rc2.createDecryptionCipher(key, 64);
  12551. };
  12552. break;
  12553. case 'RC2-128-CBC':
  12554. dkLen = 16;
  12555. cipherFn = function(key) {
  12556. return forge$7.rc2.createDecryptionCipher(key, 128);
  12557. };
  12558. break;
  12559. default:
  12560. var error = new Error('Could not decrypt private key; unsupported ' +
  12561. 'encryption algorithm "' + msg.dekInfo.algorithm + '".');
  12562. error.algorithm = msg.dekInfo.algorithm;
  12563. throw error;
  12564. }
  12565. // use OpenSSL legacy key derivation
  12566. var iv = forge$7.util.hexToBytes(msg.dekInfo.parameters);
  12567. var dk = forge$7.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen);
  12568. var cipher = cipherFn(dk);
  12569. cipher.start(iv);
  12570. cipher.update(forge$7.util.createBuffer(msg.body));
  12571. if(cipher.finish()) {
  12572. rval = cipher.output.getBytes();
  12573. } else {
  12574. return rval;
  12575. }
  12576. } else {
  12577. rval = msg.body;
  12578. }
  12579. if(msg.type === 'ENCRYPTED PRIVATE KEY') {
  12580. rval = pki$3.decryptPrivateKeyInfo(asn1$4.fromDer(rval), password);
  12581. } else {
  12582. // decryption already performed above
  12583. rval = asn1$4.fromDer(rval);
  12584. }
  12585. if(rval !== null) {
  12586. rval = pki$3.privateKeyFromAsn1(rval);
  12587. }
  12588. return rval;
  12589. };
  12590. /**
  12591. * Derives a PKCS#12 key.
  12592. *
  12593. * @param password the password to derive the key material from, null or
  12594. * undefined for none.
  12595. * @param salt the salt, as a ByteBuffer, to use.
  12596. * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC).
  12597. * @param iter the iteration count.
  12598. * @param n the number of bytes to derive from the password.
  12599. * @param md the message digest to use, defaults to SHA-1.
  12600. *
  12601. * @return a ByteBuffer with the bytes derived from the password.
  12602. */
  12603. pki$3.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md) {
  12604. var j, l;
  12605. if(typeof md === 'undefined' || md === null) {
  12606. if(!('sha1' in forge$7.md)) {
  12607. throw new Error('"sha1" hash algorithm unavailable.');
  12608. }
  12609. md = forge$7.md.sha1.create();
  12610. }
  12611. var u = md.digestLength;
  12612. var v = md.blockLength;
  12613. var result = new forge$7.util.ByteBuffer();
  12614. /* Convert password to Unicode byte buffer + trailing 0-byte. */
  12615. var passBuf = new forge$7.util.ByteBuffer();
  12616. if(password !== null && password !== undefined) {
  12617. for(l = 0; l < password.length; l++) {
  12618. passBuf.putInt16(password.charCodeAt(l));
  12619. }
  12620. passBuf.putInt16(0);
  12621. }
  12622. /* Length of salt and password in BYTES. */
  12623. var p = passBuf.length();
  12624. var s = salt.length();
  12625. /* 1. Construct a string, D (the "diversifier"), by concatenating
  12626. v copies of ID. */
  12627. var D = new forge$7.util.ByteBuffer();
  12628. D.fillWithByte(id, v);
  12629. /* 2. Concatenate copies of the salt together to create a string S of length
  12630. v * ceil(s / v) bytes (the final copy of the salt may be trunacted
  12631. to create S).
  12632. Note that if the salt is the empty string, then so is S. */
  12633. var Slen = v * Math.ceil(s / v);
  12634. var S = new forge$7.util.ByteBuffer();
  12635. for(l = 0; l < Slen; l++) {
  12636. S.putByte(salt.at(l % s));
  12637. }
  12638. /* 3. Concatenate copies of the password together to create a string P of
  12639. length v * ceil(p / v) bytes (the final copy of the password may be
  12640. truncated to create P).
  12641. Note that if the password is the empty string, then so is P. */
  12642. var Plen = v * Math.ceil(p / v);
  12643. var P = new forge$7.util.ByteBuffer();
  12644. for(l = 0; l < Plen; l++) {
  12645. P.putByte(passBuf.at(l % p));
  12646. }
  12647. /* 4. Set I=S||P to be the concatenation of S and P. */
  12648. var I = S;
  12649. I.putBuffer(P);
  12650. /* 5. Set c=ceil(n / u). */
  12651. var c = Math.ceil(n / u);
  12652. /* 6. For i=1, 2, ..., c, do the following: */
  12653. for(var i = 1; i <= c; i++) {
  12654. /* a) Set Ai=H^r(D||I). (l.e. the rth hash of D||I, H(H(H(...H(D||I)))) */
  12655. var buf = new forge$7.util.ByteBuffer();
  12656. buf.putBytes(D.bytes());
  12657. buf.putBytes(I.bytes());
  12658. for(var round = 0; round < iter; round++) {
  12659. md.start();
  12660. md.update(buf.getBytes());
  12661. buf = md.digest();
  12662. }
  12663. /* b) Concatenate copies of Ai to create a string B of length v bytes (the
  12664. final copy of Ai may be truncated to create B). */
  12665. var B = new forge$7.util.ByteBuffer();
  12666. for(l = 0; l < v; l++) {
  12667. B.putByte(buf.at(l % u));
  12668. }
  12669. /* c) Treating I as a concatenation I0, I1, ..., Ik-1 of v-byte blocks,
  12670. where k=ceil(s / v) + ceil(p / v), modify I by setting
  12671. Ij=(Ij+B+1) mod 2v for each j. */
  12672. var k = Math.ceil(s / v) + Math.ceil(p / v);
  12673. var Inew = new forge$7.util.ByteBuffer();
  12674. for(j = 0; j < k; j++) {
  12675. var chunk = new forge$7.util.ByteBuffer(I.getBytes(v));
  12676. var x = 0x1ff;
  12677. for(l = B.length() - 1; l >= 0; l--) {
  12678. x = x >> 8;
  12679. x += B.at(l) + chunk.at(l);
  12680. chunk.setAt(l, x & 0xff);
  12681. }
  12682. Inew.putBuffer(chunk);
  12683. }
  12684. I = Inew;
  12685. /* Add Ai to A. */
  12686. result.putBuffer(buf);
  12687. }
  12688. result.truncate(result.length() - n);
  12689. return result;
  12690. };
  12691. /**
  12692. * Get new Forge cipher object instance.
  12693. *
  12694. * @param oid the OID (in string notation).
  12695. * @param params the ASN.1 params object.
  12696. * @param password the password to decrypt with.
  12697. *
  12698. * @return new cipher object instance.
  12699. */
  12700. pki$3.pbe.getCipher = function(oid, params, password) {
  12701. switch(oid) {
  12702. case pki$3.oids['pkcs5PBES2']:
  12703. return pki$3.pbe.getCipherForPBES2(oid, params, password);
  12704. case pki$3.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']:
  12705. case pki$3.oids['pbewithSHAAnd40BitRC2-CBC']:
  12706. return pki$3.pbe.getCipherForPKCS12PBE(oid, params, password);
  12707. default:
  12708. var error = new Error('Cannot read encrypted PBE data block. Unsupported OID.');
  12709. error.oid = oid;
  12710. error.supportedOids = [
  12711. 'pkcs5PBES2',
  12712. 'pbeWithSHAAnd3-KeyTripleDES-CBC',
  12713. 'pbewithSHAAnd40BitRC2-CBC'
  12714. ];
  12715. throw error;
  12716. }
  12717. };
  12718. /**
  12719. * Get new Forge cipher object instance according to PBES2 params block.
  12720. *
  12721. * The returned cipher instance is already started using the IV
  12722. * from PBES2 parameter block.
  12723. *
  12724. * @param oid the PKCS#5 PBKDF2 OID (in string notation).
  12725. * @param params the ASN.1 PBES2-params object.
  12726. * @param password the password to decrypt with.
  12727. *
  12728. * @return new cipher object instance.
  12729. */
  12730. pki$3.pbe.getCipherForPBES2 = function(oid, params, password) {
  12731. // get PBE params
  12732. var capture = {};
  12733. var errors = [];
  12734. if(!asn1$4.validate(params, PBES2AlgorithmsValidator, capture, errors)) {
  12735. var error = new Error('Cannot read password-based-encryption algorithm ' +
  12736. 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.');
  12737. error.errors = errors;
  12738. throw error;
  12739. }
  12740. // check oids
  12741. oid = asn1$4.derToOid(capture.kdfOid);
  12742. if(oid !== pki$3.oids['pkcs5PBKDF2']) {
  12743. var error = new Error('Cannot read encrypted private key. ' +
  12744. 'Unsupported key derivation function OID.');
  12745. error.oid = oid;
  12746. error.supportedOids = ['pkcs5PBKDF2'];
  12747. throw error;
  12748. }
  12749. oid = asn1$4.derToOid(capture.encOid);
  12750. if(oid !== pki$3.oids['aes128-CBC'] &&
  12751. oid !== pki$3.oids['aes192-CBC'] &&
  12752. oid !== pki$3.oids['aes256-CBC'] &&
  12753. oid !== pki$3.oids['des-EDE3-CBC'] &&
  12754. oid !== pki$3.oids['desCBC']) {
  12755. var error = new Error('Cannot read encrypted private key. ' +
  12756. 'Unsupported encryption scheme OID.');
  12757. error.oid = oid;
  12758. error.supportedOids = [
  12759. 'aes128-CBC', 'aes192-CBC', 'aes256-CBC', 'des-EDE3-CBC', 'desCBC'];
  12760. throw error;
  12761. }
  12762. // set PBE params
  12763. var salt = capture.kdfSalt;
  12764. var count = forge$7.util.createBuffer(capture.kdfIterationCount);
  12765. count = count.getInt(count.length() << 3);
  12766. var dkLen;
  12767. var cipherFn;
  12768. switch(pki$3.oids[oid]) {
  12769. case 'aes128-CBC':
  12770. dkLen = 16;
  12771. cipherFn = forge$7.aes.createDecryptionCipher;
  12772. break;
  12773. case 'aes192-CBC':
  12774. dkLen = 24;
  12775. cipherFn = forge$7.aes.createDecryptionCipher;
  12776. break;
  12777. case 'aes256-CBC':
  12778. dkLen = 32;
  12779. cipherFn = forge$7.aes.createDecryptionCipher;
  12780. break;
  12781. case 'des-EDE3-CBC':
  12782. dkLen = 24;
  12783. cipherFn = forge$7.des.createDecryptionCipher;
  12784. break;
  12785. case 'desCBC':
  12786. dkLen = 8;
  12787. cipherFn = forge$7.des.createDecryptionCipher;
  12788. break;
  12789. }
  12790. // get PRF message digest
  12791. var md = prfOidToMessageDigest(capture.prfOid);
  12792. // decrypt private key using pbe with chosen PRF and AES/DES
  12793. var dk = forge$7.pkcs5.pbkdf2(password, salt, count, dkLen, md);
  12794. var iv = capture.encIv;
  12795. var cipher = cipherFn(dk);
  12796. cipher.start(iv);
  12797. return cipher;
  12798. };
  12799. /**
  12800. * Get new Forge cipher object instance for PKCS#12 PBE.
  12801. *
  12802. * The returned cipher instance is already started using the key & IV
  12803. * derived from the provided password and PKCS#12 PBE salt.
  12804. *
  12805. * @param oid The PKCS#12 PBE OID (in string notation).
  12806. * @param params The ASN.1 PKCS#12 PBE-params object.
  12807. * @param password The password to decrypt with.
  12808. *
  12809. * @return the new cipher object instance.
  12810. */
  12811. pki$3.pbe.getCipherForPKCS12PBE = function(oid, params, password) {
  12812. // get PBE params
  12813. var capture = {};
  12814. var errors = [];
  12815. if(!asn1$4.validate(params, pkcs12PbeParamsValidator, capture, errors)) {
  12816. var error = new Error('Cannot read password-based-encryption algorithm ' +
  12817. 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.');
  12818. error.errors = errors;
  12819. throw error;
  12820. }
  12821. var salt = forge$7.util.createBuffer(capture.salt);
  12822. var count = forge$7.util.createBuffer(capture.iterations);
  12823. count = count.getInt(count.length() << 3);
  12824. var dkLen, dIvLen, cipherFn;
  12825. switch(oid) {
  12826. case pki$3.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']:
  12827. dkLen = 24;
  12828. dIvLen = 8;
  12829. cipherFn = forge$7.des.startDecrypting;
  12830. break;
  12831. case pki$3.oids['pbewithSHAAnd40BitRC2-CBC']:
  12832. dkLen = 5;
  12833. dIvLen = 8;
  12834. cipherFn = function(key, iv) {
  12835. var cipher = forge$7.rc2.createDecryptionCipher(key, 40);
  12836. cipher.start(iv, null);
  12837. return cipher;
  12838. };
  12839. break;
  12840. default:
  12841. var error = new Error('Cannot read PKCS #12 PBE data block. Unsupported OID.');
  12842. error.oid = oid;
  12843. throw error;
  12844. }
  12845. // get PRF message digest
  12846. var md = prfOidToMessageDigest(capture.prfOid);
  12847. var key = pki$3.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md);
  12848. md.start();
  12849. var iv = pki$3.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md);
  12850. return cipherFn(key, iv);
  12851. };
  12852. /**
  12853. * OpenSSL's legacy key derivation function.
  12854. *
  12855. * See: http://www.openssl.org/docs/crypto/EVP_BytesToKey.html
  12856. *
  12857. * @param password the password to derive the key from.
  12858. * @param salt the salt to use, null for none.
  12859. * @param dkLen the number of bytes needed for the derived key.
  12860. * @param [options] the options to use:
  12861. * [md] an optional message digest object to use.
  12862. */
  12863. pki$3.pbe.opensslDeriveBytes = function(password, salt, dkLen, md) {
  12864. if(typeof md === 'undefined' || md === null) {
  12865. if(!('md5' in forge$7.md)) {
  12866. throw new Error('"md5" hash algorithm unavailable.');
  12867. }
  12868. md = forge$7.md.md5.create();
  12869. }
  12870. if(salt === null) {
  12871. salt = '';
  12872. }
  12873. var digests = [hash(md, password + salt)];
  12874. for(var length = 16, i = 1; length < dkLen; ++i, length += 16) {
  12875. digests.push(hash(md, digests[i - 1] + password + salt));
  12876. }
  12877. return digests.join('').substr(0, dkLen);
  12878. };
  12879. function hash(md, bytes) {
  12880. return md.start().update(bytes).digest().getBytes();
  12881. }
  12882. function prfOidToMessageDigest(prfOid) {
  12883. // get PRF algorithm, default to SHA-1
  12884. var prfAlgorithm;
  12885. if(!prfOid) {
  12886. prfAlgorithm = 'hmacWithSHA1';
  12887. } else {
  12888. prfAlgorithm = pki$3.oids[asn1$4.derToOid(prfOid)];
  12889. if(!prfAlgorithm) {
  12890. var error = new Error('Unsupported PRF OID.');
  12891. error.oid = prfOid;
  12892. error.supported = [
  12893. 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384',
  12894. 'hmacWithSHA512'];
  12895. throw error;
  12896. }
  12897. }
  12898. return prfAlgorithmToMessageDigest(prfAlgorithm);
  12899. }
  12900. function prfAlgorithmToMessageDigest(prfAlgorithm) {
  12901. var factory = forge$7.md;
  12902. switch(prfAlgorithm) {
  12903. case 'hmacWithSHA224':
  12904. factory = forge$7.md.sha512;
  12905. case 'hmacWithSHA1':
  12906. case 'hmacWithSHA256':
  12907. case 'hmacWithSHA384':
  12908. case 'hmacWithSHA512':
  12909. prfAlgorithm = prfAlgorithm.substr(8).toLowerCase();
  12910. break;
  12911. default:
  12912. var error = new Error('Unsupported PRF algorithm.');
  12913. error.algorithm = prfAlgorithm;
  12914. error.supported = [
  12915. 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384',
  12916. 'hmacWithSHA512'];
  12917. throw error;
  12918. }
  12919. if(!factory || !(prfAlgorithm in factory)) {
  12920. throw new Error('Unknown hash algorithm: ' + prfAlgorithm);
  12921. }
  12922. return factory[prfAlgorithm].create();
  12923. }
  12924. function createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) {
  12925. var params = asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [
  12926. // salt
  12927. asn1$4.create(
  12928. asn1$4.Class.UNIVERSAL, asn1$4.Type.OCTETSTRING, false, salt),
  12929. // iteration count
  12930. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.INTEGER, false,
  12931. countBytes.getBytes())
  12932. ]);
  12933. // when PRF algorithm is not SHA-1 default, add key length and PRF algorithm
  12934. if(prfAlgorithm !== 'hmacWithSHA1') {
  12935. params.value.push(
  12936. // key length
  12937. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.INTEGER, false,
  12938. forge$7.util.hexToBytes(dkLen.toString(16))),
  12939. // AlgorithmIdentifier
  12940. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.SEQUENCE, true, [
  12941. // algorithm
  12942. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.OID, false,
  12943. asn1$4.oidToDer(pki$3.oids[prfAlgorithm]).getBytes()),
  12944. // parameters (null)
  12945. asn1$4.create(asn1$4.Class.UNIVERSAL, asn1$4.Type.NULL, false, '')
  12946. ]));
  12947. }
  12948. return params;
  12949. }
  12950. /**
  12951. * Javascript implementation of ASN.1 validators for PKCS#7 v1.5.
  12952. *
  12953. * @author Dave Longley
  12954. * @author Stefan Siegl
  12955. *
  12956. * Copyright (c) 2012-2015 Digital Bazaar, Inc.
  12957. * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>
  12958. *
  12959. * The ASN.1 representation of PKCS#7 is as follows
  12960. * (see RFC #2315 for details, http://www.ietf.org/rfc/rfc2315.txt):
  12961. *
  12962. * A PKCS#7 message consists of a ContentInfo on root level, which may
  12963. * contain any number of further ContentInfo nested into it.
  12964. *
  12965. * ContentInfo ::= SEQUENCE {
  12966. * contentType ContentType,
  12967. * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL
  12968. * }
  12969. *
  12970. * ContentType ::= OBJECT IDENTIFIER
  12971. *
  12972. * EnvelopedData ::= SEQUENCE {
  12973. * version Version,
  12974. * recipientInfos RecipientInfos,
  12975. * encryptedContentInfo EncryptedContentInfo
  12976. * }
  12977. *
  12978. * EncryptedData ::= SEQUENCE {
  12979. * version Version,
  12980. * encryptedContentInfo EncryptedContentInfo
  12981. * }
  12982. *
  12983. * id-signedData OBJECT IDENTIFIER ::= { iso(1) member-body(2)
  12984. * us(840) rsadsi(113549) pkcs(1) pkcs7(7) 2 }
  12985. *
  12986. * SignedData ::= SEQUENCE {
  12987. * version INTEGER,
  12988. * digestAlgorithms DigestAlgorithmIdentifiers,
  12989. * contentInfo ContentInfo,
  12990. * certificates [0] IMPLICIT Certificates OPTIONAL,
  12991. * crls [1] IMPLICIT CertificateRevocationLists OPTIONAL,
  12992. * signerInfos SignerInfos
  12993. * }
  12994. *
  12995. * SignerInfos ::= SET OF SignerInfo
  12996. *
  12997. * SignerInfo ::= SEQUENCE {
  12998. * version Version,
  12999. * issuerAndSerialNumber IssuerAndSerialNumber,
  13000. * digestAlgorithm DigestAlgorithmIdentifier,
  13001. * authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL,
  13002. * digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier,
  13003. * encryptedDigest EncryptedDigest,
  13004. * unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL
  13005. * }
  13006. *
  13007. * EncryptedDigest ::= OCTET STRING
  13008. *
  13009. * Attributes ::= SET OF Attribute
  13010. *
  13011. * Attribute ::= SEQUENCE {
  13012. * attrType OBJECT IDENTIFIER,
  13013. * attrValues SET OF AttributeValue
  13014. * }
  13015. *
  13016. * AttributeValue ::= ANY
  13017. *
  13018. * Version ::= INTEGER
  13019. *
  13020. * RecipientInfos ::= SET OF RecipientInfo
  13021. *
  13022. * EncryptedContentInfo ::= SEQUENCE {
  13023. * contentType ContentType,
  13024. * contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,
  13025. * encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL
  13026. * }
  13027. *
  13028. * ContentEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
  13029. *
  13030. * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters
  13031. * for the algorithm, if any. In the case of AES and DES3, there is only one,
  13032. * the IV.
  13033. *
  13034. * AlgorithmIdentifer ::= SEQUENCE {
  13035. * algorithm OBJECT IDENTIFIER,
  13036. * parameters ANY DEFINED BY algorithm OPTIONAL
  13037. * }
  13038. *
  13039. * EncryptedContent ::= OCTET STRING
  13040. *
  13041. * RecipientInfo ::= SEQUENCE {
  13042. * version Version,
  13043. * issuerAndSerialNumber IssuerAndSerialNumber,
  13044. * keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier,
  13045. * encryptedKey EncryptedKey
  13046. * }
  13047. *
  13048. * IssuerAndSerialNumber ::= SEQUENCE {
  13049. * issuer Name,
  13050. * serialNumber CertificateSerialNumber
  13051. * }
  13052. *
  13053. * CertificateSerialNumber ::= INTEGER
  13054. *
  13055. * KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
  13056. *
  13057. * EncryptedKey ::= OCTET STRING
  13058. */
  13059. var forge$6 = forge$s;
  13060. // shortcut for ASN.1 API
  13061. var asn1$3 = forge$6.asn1;
  13062. // shortcut for PKCS#7 API
  13063. var p7v = forge$6.pkcs7asn1 = forge$6.pkcs7asn1 || {};
  13064. forge$6.pkcs7 = forge$6.pkcs7 || {};
  13065. forge$6.pkcs7.asn1 = p7v;
  13066. var contentInfoValidator$1 = {
  13067. name: 'ContentInfo',
  13068. tagClass: asn1$3.Class.UNIVERSAL,
  13069. type: asn1$3.Type.SEQUENCE,
  13070. constructed: true,
  13071. value: [{
  13072. name: 'ContentInfo.ContentType',
  13073. tagClass: asn1$3.Class.UNIVERSAL,
  13074. type: asn1$3.Type.OID,
  13075. constructed: false,
  13076. capture: 'contentType'
  13077. }, {
  13078. name: 'ContentInfo.content',
  13079. tagClass: asn1$3.Class.CONTEXT_SPECIFIC,
  13080. type: 0,
  13081. constructed: true,
  13082. optional: true,
  13083. captureAsn1: 'content'
  13084. }]
  13085. };
  13086. p7v.contentInfoValidator = contentInfoValidator$1;
  13087. var encryptedContentInfoValidator = {
  13088. name: 'EncryptedContentInfo',
  13089. tagClass: asn1$3.Class.UNIVERSAL,
  13090. type: asn1$3.Type.SEQUENCE,
  13091. constructed: true,
  13092. value: [{
  13093. name: 'EncryptedContentInfo.contentType',
  13094. tagClass: asn1$3.Class.UNIVERSAL,
  13095. type: asn1$3.Type.OID,
  13096. constructed: false,
  13097. capture: 'contentType'
  13098. }, {
  13099. name: 'EncryptedContentInfo.contentEncryptionAlgorithm',
  13100. tagClass: asn1$3.Class.UNIVERSAL,
  13101. type: asn1$3.Type.SEQUENCE,
  13102. constructed: true,
  13103. value: [{
  13104. name: 'EncryptedContentInfo.contentEncryptionAlgorithm.algorithm',
  13105. tagClass: asn1$3.Class.UNIVERSAL,
  13106. type: asn1$3.Type.OID,
  13107. constructed: false,
  13108. capture: 'encAlgorithm'
  13109. }, {
  13110. name: 'EncryptedContentInfo.contentEncryptionAlgorithm.parameter',
  13111. tagClass: asn1$3.Class.UNIVERSAL,
  13112. captureAsn1: 'encParameter'
  13113. }]
  13114. }, {
  13115. name: 'EncryptedContentInfo.encryptedContent',
  13116. tagClass: asn1$3.Class.CONTEXT_SPECIFIC,
  13117. type: 0,
  13118. /* The PKCS#7 structure output by OpenSSL somewhat differs from what
  13119. * other implementations do generate.
  13120. *
  13121. * OpenSSL generates a structure like this:
  13122. * SEQUENCE {
  13123. * ...
  13124. * [0]
  13125. * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38
  13126. * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45
  13127. * ...
  13128. * }
  13129. *
  13130. * Whereas other implementations (and this PKCS#7 module) generate:
  13131. * SEQUENCE {
  13132. * ...
  13133. * [0] {
  13134. * OCTET STRING
  13135. * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38
  13136. * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45
  13137. * ...
  13138. * }
  13139. * }
  13140. *
  13141. * In order to support both, we just capture the context specific
  13142. * field here. The OCTET STRING bit is removed below.
  13143. */
  13144. capture: 'encryptedContent',
  13145. captureAsn1: 'encryptedContentAsn1'
  13146. }]
  13147. };
  13148. p7v.envelopedDataValidator = {
  13149. name: 'EnvelopedData',
  13150. tagClass: asn1$3.Class.UNIVERSAL,
  13151. type: asn1$3.Type.SEQUENCE,
  13152. constructed: true,
  13153. value: [{
  13154. name: 'EnvelopedData.Version',
  13155. tagClass: asn1$3.Class.UNIVERSAL,
  13156. type: asn1$3.Type.INTEGER,
  13157. constructed: false,
  13158. capture: 'version'
  13159. }, {
  13160. name: 'EnvelopedData.RecipientInfos',
  13161. tagClass: asn1$3.Class.UNIVERSAL,
  13162. type: asn1$3.Type.SET,
  13163. constructed: true,
  13164. captureAsn1: 'recipientInfos'
  13165. }].concat(encryptedContentInfoValidator)
  13166. };
  13167. p7v.encryptedDataValidator = {
  13168. name: 'EncryptedData',
  13169. tagClass: asn1$3.Class.UNIVERSAL,
  13170. type: asn1$3.Type.SEQUENCE,
  13171. constructed: true,
  13172. value: [{
  13173. name: 'EncryptedData.Version',
  13174. tagClass: asn1$3.Class.UNIVERSAL,
  13175. type: asn1$3.Type.INTEGER,
  13176. constructed: false,
  13177. capture: 'version'
  13178. }].concat(encryptedContentInfoValidator)
  13179. };
  13180. var signerValidator = {
  13181. name: 'SignerInfo',
  13182. tagClass: asn1$3.Class.UNIVERSAL,
  13183. type: asn1$3.Type.SEQUENCE,
  13184. constructed: true,
  13185. value: [{
  13186. name: 'SignerInfo.version',
  13187. tagClass: asn1$3.Class.UNIVERSAL,
  13188. type: asn1$3.Type.INTEGER,
  13189. constructed: false
  13190. }, {
  13191. name: 'SignerInfo.issuerAndSerialNumber',
  13192. tagClass: asn1$3.Class.UNIVERSAL,
  13193. type: asn1$3.Type.SEQUENCE,
  13194. constructed: true,
  13195. value: [{
  13196. name: 'SignerInfo.issuerAndSerialNumber.issuer',
  13197. tagClass: asn1$3.Class.UNIVERSAL,
  13198. type: asn1$3.Type.SEQUENCE,
  13199. constructed: true,
  13200. captureAsn1: 'issuer'
  13201. }, {
  13202. name: 'SignerInfo.issuerAndSerialNumber.serialNumber',
  13203. tagClass: asn1$3.Class.UNIVERSAL,
  13204. type: asn1$3.Type.INTEGER,
  13205. constructed: false,
  13206. capture: 'serial'
  13207. }]
  13208. }, {
  13209. name: 'SignerInfo.digestAlgorithm',
  13210. tagClass: asn1$3.Class.UNIVERSAL,
  13211. type: asn1$3.Type.SEQUENCE,
  13212. constructed: true,
  13213. value: [{
  13214. name: 'SignerInfo.digestAlgorithm.algorithm',
  13215. tagClass: asn1$3.Class.UNIVERSAL,
  13216. type: asn1$3.Type.OID,
  13217. constructed: false,
  13218. capture: 'digestAlgorithm'
  13219. }, {
  13220. name: 'SignerInfo.digestAlgorithm.parameter',
  13221. tagClass: asn1$3.Class.UNIVERSAL,
  13222. constructed: false,
  13223. captureAsn1: 'digestParameter',
  13224. optional: true
  13225. }]
  13226. }, {
  13227. name: 'SignerInfo.authenticatedAttributes',
  13228. tagClass: asn1$3.Class.CONTEXT_SPECIFIC,
  13229. type: 0,
  13230. constructed: true,
  13231. optional: true,
  13232. capture: 'authenticatedAttributes'
  13233. }, {
  13234. name: 'SignerInfo.digestEncryptionAlgorithm',
  13235. tagClass: asn1$3.Class.UNIVERSAL,
  13236. type: asn1$3.Type.SEQUENCE,
  13237. constructed: true,
  13238. capture: 'signatureAlgorithm'
  13239. }, {
  13240. name: 'SignerInfo.encryptedDigest',
  13241. tagClass: asn1$3.Class.UNIVERSAL,
  13242. type: asn1$3.Type.OCTETSTRING,
  13243. constructed: false,
  13244. capture: 'signature'
  13245. }, {
  13246. name: 'SignerInfo.unauthenticatedAttributes',
  13247. tagClass: asn1$3.Class.CONTEXT_SPECIFIC,
  13248. type: 1,
  13249. constructed: true,
  13250. optional: true,
  13251. capture: 'unauthenticatedAttributes'
  13252. }]
  13253. };
  13254. p7v.signedDataValidator = {
  13255. name: 'SignedData',
  13256. tagClass: asn1$3.Class.UNIVERSAL,
  13257. type: asn1$3.Type.SEQUENCE,
  13258. constructed: true,
  13259. value: [{
  13260. name: 'SignedData.Version',
  13261. tagClass: asn1$3.Class.UNIVERSAL,
  13262. type: asn1$3.Type.INTEGER,
  13263. constructed: false,
  13264. capture: 'version'
  13265. }, {
  13266. name: 'SignedData.DigestAlgorithms',
  13267. tagClass: asn1$3.Class.UNIVERSAL,
  13268. type: asn1$3.Type.SET,
  13269. constructed: true,
  13270. captureAsn1: 'digestAlgorithms'
  13271. },
  13272. contentInfoValidator$1,
  13273. {
  13274. name: 'SignedData.Certificates',
  13275. tagClass: asn1$3.Class.CONTEXT_SPECIFIC,
  13276. type: 0,
  13277. optional: true,
  13278. captureAsn1: 'certificates'
  13279. }, {
  13280. name: 'SignedData.CertificateRevocationLists',
  13281. tagClass: asn1$3.Class.CONTEXT_SPECIFIC,
  13282. type: 1,
  13283. optional: true,
  13284. captureAsn1: 'crls'
  13285. }, {
  13286. name: 'SignedData.SignerInfos',
  13287. tagClass: asn1$3.Class.UNIVERSAL,
  13288. type: asn1$3.Type.SET,
  13289. capture: 'signerInfos',
  13290. optional: true,
  13291. value: [signerValidator]
  13292. }]
  13293. };
  13294. p7v.recipientInfoValidator = {
  13295. name: 'RecipientInfo',
  13296. tagClass: asn1$3.Class.UNIVERSAL,
  13297. type: asn1$3.Type.SEQUENCE,
  13298. constructed: true,
  13299. value: [{
  13300. name: 'RecipientInfo.version',
  13301. tagClass: asn1$3.Class.UNIVERSAL,
  13302. type: asn1$3.Type.INTEGER,
  13303. constructed: false,
  13304. capture: 'version'
  13305. }, {
  13306. name: 'RecipientInfo.issuerAndSerial',
  13307. tagClass: asn1$3.Class.UNIVERSAL,
  13308. type: asn1$3.Type.SEQUENCE,
  13309. constructed: true,
  13310. value: [{
  13311. name: 'RecipientInfo.issuerAndSerial.issuer',
  13312. tagClass: asn1$3.Class.UNIVERSAL,
  13313. type: asn1$3.Type.SEQUENCE,
  13314. constructed: true,
  13315. captureAsn1: 'issuer'
  13316. }, {
  13317. name: 'RecipientInfo.issuerAndSerial.serialNumber',
  13318. tagClass: asn1$3.Class.UNIVERSAL,
  13319. type: asn1$3.Type.INTEGER,
  13320. constructed: false,
  13321. capture: 'serial'
  13322. }]
  13323. }, {
  13324. name: 'RecipientInfo.keyEncryptionAlgorithm',
  13325. tagClass: asn1$3.Class.UNIVERSAL,
  13326. type: asn1$3.Type.SEQUENCE,
  13327. constructed: true,
  13328. value: [{
  13329. name: 'RecipientInfo.keyEncryptionAlgorithm.algorithm',
  13330. tagClass: asn1$3.Class.UNIVERSAL,
  13331. type: asn1$3.Type.OID,
  13332. constructed: false,
  13333. capture: 'encAlgorithm'
  13334. }, {
  13335. name: 'RecipientInfo.keyEncryptionAlgorithm.parameter',
  13336. tagClass: asn1$3.Class.UNIVERSAL,
  13337. constructed: false,
  13338. captureAsn1: 'encParameter',
  13339. optional: true
  13340. }]
  13341. }, {
  13342. name: 'RecipientInfo.encryptedKey',
  13343. tagClass: asn1$3.Class.UNIVERSAL,
  13344. type: asn1$3.Type.OCTETSTRING,
  13345. constructed: false,
  13346. capture: 'encKey'
  13347. }]
  13348. };
  13349. /**
  13350. * Javascript implementation of mask generation function MGF1.
  13351. *
  13352. * @author Stefan Siegl
  13353. * @author Dave Longley
  13354. *
  13355. * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>
  13356. * Copyright (c) 2014 Digital Bazaar, Inc.
  13357. */
  13358. var forge$5 = forge$s;
  13359. forge$5.mgf = forge$5.mgf || {};
  13360. var mgf1 = forge$5.mgf.mgf1 = forge$5.mgf1 = forge$5.mgf1 || {};
  13361. /**
  13362. * Creates a MGF1 mask generation function object.
  13363. *
  13364. * @param md the message digest API to use (eg: forge.md.sha1.create()).
  13365. *
  13366. * @return a mask generation function object.
  13367. */
  13368. mgf1.create = function(md) {
  13369. var mgf = {
  13370. /**
  13371. * Generate mask of specified length.
  13372. *
  13373. * @param {String} seed The seed for mask generation.
  13374. * @param maskLen Number of bytes to generate.
  13375. * @return {String} The generated mask.
  13376. */
  13377. generate: function(seed, maskLen) {
  13378. /* 2. Let T be the empty octet string. */
  13379. var t = new forge$5.util.ByteBuffer();
  13380. /* 3. For counter from 0 to ceil(maskLen / hLen), do the following: */
  13381. var len = Math.ceil(maskLen / md.digestLength);
  13382. for(var i = 0; i < len; i++) {
  13383. /* a. Convert counter to an octet string C of length 4 octets */
  13384. var c = new forge$5.util.ByteBuffer();
  13385. c.putInt32(i);
  13386. /* b. Concatenate the hash of the seed mgfSeed and C to the octet
  13387. * string T: */
  13388. md.start();
  13389. md.update(seed + c.getBytes());
  13390. t.putBuffer(md.digest());
  13391. }
  13392. /* Output the leading maskLen octets of T as the octet string mask. */
  13393. t.truncate(t.length() - maskLen);
  13394. return t.getBytes();
  13395. }
  13396. };
  13397. return mgf;
  13398. };
  13399. /**
  13400. * Node.js module for Forge mask generation functions.
  13401. *
  13402. * @author Stefan Siegl
  13403. *
  13404. * Copyright 2012 Stefan Siegl <stesie@brokenpipe.de>
  13405. */
  13406. var forge$4 = forge$s;
  13407. forge$4.mgf = forge$4.mgf || {};
  13408. forge$4.mgf.mgf1 = forge$4.mgf1;
  13409. /**
  13410. * Javascript implementation of PKCS#1 PSS signature padding.
  13411. *
  13412. * @author Stefan Siegl
  13413. *
  13414. * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>
  13415. */
  13416. var forge$3 = forge$s;
  13417. // shortcut for PSS API
  13418. var pss = forge$3.pss = forge$3.pss || {};
  13419. /**
  13420. * Creates a PSS signature scheme object.
  13421. *
  13422. * There are several ways to provide a salt for encoding:
  13423. *
  13424. * 1. Specify the saltLength only and the built-in PRNG will generate it.
  13425. * 2. Specify the saltLength and a custom PRNG with 'getBytesSync' defined that
  13426. * will be used.
  13427. * 3. Specify the salt itself as a forge.util.ByteBuffer.
  13428. *
  13429. * @param options the options to use:
  13430. * md the message digest object to use, a forge md instance.
  13431. * mgf the mask generation function to use, a forge mgf instance.
  13432. * [saltLength] the length of the salt in octets.
  13433. * [prng] the pseudo-random number generator to use to produce a salt.
  13434. * [salt] the salt to use when encoding.
  13435. *
  13436. * @return a signature scheme object.
  13437. */
  13438. pss.create = function(options) {
  13439. // backwards compatibility w/legacy args: hash, mgf, sLen
  13440. if(arguments.length === 3) {
  13441. options = {
  13442. md: arguments[0],
  13443. mgf: arguments[1],
  13444. saltLength: arguments[2]
  13445. };
  13446. }
  13447. var hash = options.md;
  13448. var mgf = options.mgf;
  13449. var hLen = hash.digestLength;
  13450. var salt_ = options.salt || null;
  13451. if(typeof salt_ === 'string') {
  13452. // assume binary-encoded string
  13453. salt_ = forge$3.util.createBuffer(salt_);
  13454. }
  13455. var sLen;
  13456. if('saltLength' in options) {
  13457. sLen = options.saltLength;
  13458. } else if(salt_ !== null) {
  13459. sLen = salt_.length();
  13460. } else {
  13461. throw new Error('Salt length not specified or specific salt not given.');
  13462. }
  13463. if(salt_ !== null && salt_.length() !== sLen) {
  13464. throw new Error('Given salt length does not match length of given salt.');
  13465. }
  13466. var prng = options.prng || forge$3.random;
  13467. var pssobj = {};
  13468. /**
  13469. * Encodes a PSS signature.
  13470. *
  13471. * This function implements EMSA-PSS-ENCODE as per RFC 3447, section 9.1.1.
  13472. *
  13473. * @param md the message digest object with the hash to sign.
  13474. * @param modsBits the length of the RSA modulus in bits.
  13475. *
  13476. * @return the encoded message as a binary-encoded string of length
  13477. * ceil((modBits - 1) / 8).
  13478. */
  13479. pssobj.encode = function(md, modBits) {
  13480. var i;
  13481. var emBits = modBits - 1;
  13482. var emLen = Math.ceil(emBits / 8);
  13483. /* 2. Let mHash = Hash(M), an octet string of length hLen. */
  13484. var mHash = md.digest().getBytes();
  13485. /* 3. If emLen < hLen + sLen + 2, output "encoding error" and stop. */
  13486. if(emLen < hLen + sLen + 2) {
  13487. throw new Error('Message is too long to encrypt.');
  13488. }
  13489. /* 4. Generate a random octet string salt of length sLen; if sLen = 0,
  13490. * then salt is the empty string. */
  13491. var salt;
  13492. if(salt_ === null) {
  13493. salt = prng.getBytesSync(sLen);
  13494. } else {
  13495. salt = salt_.bytes();
  13496. }
  13497. /* 5. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt; */
  13498. var m_ = new forge$3.util.ByteBuffer();
  13499. m_.fillWithByte(0, 8);
  13500. m_.putBytes(mHash);
  13501. m_.putBytes(salt);
  13502. /* 6. Let H = Hash(M'), an octet string of length hLen. */
  13503. hash.start();
  13504. hash.update(m_.getBytes());
  13505. var h = hash.digest().getBytes();
  13506. /* 7. Generate an octet string PS consisting of emLen - sLen - hLen - 2
  13507. * zero octets. The length of PS may be 0. */
  13508. var ps = new forge$3.util.ByteBuffer();
  13509. ps.fillWithByte(0, emLen - sLen - hLen - 2);
  13510. /* 8. Let DB = PS || 0x01 || salt; DB is an octet string of length
  13511. * emLen - hLen - 1. */
  13512. ps.putByte(0x01);
  13513. ps.putBytes(salt);
  13514. var db = ps.getBytes();
  13515. /* 9. Let dbMask = MGF(H, emLen - hLen - 1). */
  13516. var maskLen = emLen - hLen - 1;
  13517. var dbMask = mgf.generate(h, maskLen);
  13518. /* 10. Let maskedDB = DB \xor dbMask. */
  13519. var maskedDB = '';
  13520. for(i = 0; i < maskLen; i++) {
  13521. maskedDB += String.fromCharCode(db.charCodeAt(i) ^ dbMask.charCodeAt(i));
  13522. }
  13523. /* 11. Set the leftmost 8emLen - emBits bits of the leftmost octet in
  13524. * maskedDB to zero. */
  13525. var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF;
  13526. maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) +
  13527. maskedDB.substr(1);
  13528. /* 12. Let EM = maskedDB || H || 0xbc.
  13529. * 13. Output EM. */
  13530. return maskedDB + h + String.fromCharCode(0xbc);
  13531. };
  13532. /**
  13533. * Verifies a PSS signature.
  13534. *
  13535. * This function implements EMSA-PSS-VERIFY as per RFC 3447, section 9.1.2.
  13536. *
  13537. * @param mHash the message digest hash, as a binary-encoded string, to
  13538. * compare against the signature.
  13539. * @param em the encoded message, as a binary-encoded string
  13540. * (RSA decryption result).
  13541. * @param modsBits the length of the RSA modulus in bits.
  13542. *
  13543. * @return true if the signature was verified, false if not.
  13544. */
  13545. pssobj.verify = function(mHash, em, modBits) {
  13546. var i;
  13547. var emBits = modBits - 1;
  13548. var emLen = Math.ceil(emBits / 8);
  13549. /* c. Convert the message representative m to an encoded message EM
  13550. * of length emLen = ceil((modBits - 1) / 8) octets, where modBits
  13551. * is the length in bits of the RSA modulus n */
  13552. em = em.substr(-emLen);
  13553. /* 3. If emLen < hLen + sLen + 2, output "inconsistent" and stop. */
  13554. if(emLen < hLen + sLen + 2) {
  13555. throw new Error('Inconsistent parameters to PSS signature verification.');
  13556. }
  13557. /* 4. If the rightmost octet of EM does not have hexadecimal value
  13558. * 0xbc, output "inconsistent" and stop. */
  13559. if(em.charCodeAt(emLen - 1) !== 0xbc) {
  13560. throw new Error('Encoded message does not end in 0xBC.');
  13561. }
  13562. /* 5. Let maskedDB be the leftmost emLen - hLen - 1 octets of EM, and
  13563. * let H be the next hLen octets. */
  13564. var maskLen = emLen - hLen - 1;
  13565. var maskedDB = em.substr(0, maskLen);
  13566. var h = em.substr(maskLen, hLen);
  13567. /* 6. If the leftmost 8emLen - emBits bits of the leftmost octet in
  13568. * maskedDB are not all equal to zero, output "inconsistent" and stop. */
  13569. var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF;
  13570. if((maskedDB.charCodeAt(0) & mask) !== 0) {
  13571. throw new Error('Bits beyond keysize not zero as expected.');
  13572. }
  13573. /* 7. Let dbMask = MGF(H, emLen - hLen - 1). */
  13574. var dbMask = mgf.generate(h, maskLen);
  13575. /* 8. Let DB = maskedDB \xor dbMask. */
  13576. var db = '';
  13577. for(i = 0; i < maskLen; i++) {
  13578. db += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i));
  13579. }
  13580. /* 9. Set the leftmost 8emLen - emBits bits of the leftmost octet
  13581. * in DB to zero. */
  13582. db = String.fromCharCode(db.charCodeAt(0) & ~mask) + db.substr(1);
  13583. /* 10. If the emLen - hLen - sLen - 2 leftmost octets of DB are not zero
  13584. * or if the octet at position emLen - hLen - sLen - 1 (the leftmost
  13585. * position is "position 1") does not have hexadecimal value 0x01,
  13586. * output "inconsistent" and stop. */
  13587. var checkLen = emLen - hLen - sLen - 2;
  13588. for(i = 0; i < checkLen; i++) {
  13589. if(db.charCodeAt(i) !== 0x00) {
  13590. throw new Error('Leftmost octets not zero as expected');
  13591. }
  13592. }
  13593. if(db.charCodeAt(checkLen) !== 0x01) {
  13594. throw new Error('Inconsistent PSS signature, 0x01 marker not found');
  13595. }
  13596. /* 11. Let salt be the last sLen octets of DB. */
  13597. var salt = db.substr(-sLen);
  13598. /* 12. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt */
  13599. var m_ = new forge$3.util.ByteBuffer();
  13600. m_.fillWithByte(0, 8);
  13601. m_.putBytes(mHash);
  13602. m_.putBytes(salt);
  13603. /* 13. Let H' = Hash(M'), an octet string of length hLen. */
  13604. hash.start();
  13605. hash.update(m_.getBytes());
  13606. var h_ = hash.digest().getBytes();
  13607. /* 14. If H = H', output "consistent." Otherwise, output "inconsistent." */
  13608. return h === h_;
  13609. };
  13610. return pssobj;
  13611. };
  13612. /**
  13613. * Javascript implementation of X.509 and related components (such as
  13614. * Certification Signing Requests) of a Public Key Infrastructure.
  13615. *
  13616. * @author Dave Longley
  13617. *
  13618. * Copyright (c) 2010-2014 Digital Bazaar, Inc.
  13619. *
  13620. * The ASN.1 representation of an X.509v3 certificate is as follows
  13621. * (see RFC 2459):
  13622. *
  13623. * Certificate ::= SEQUENCE {
  13624. * tbsCertificate TBSCertificate,
  13625. * signatureAlgorithm AlgorithmIdentifier,
  13626. * signatureValue BIT STRING
  13627. * }
  13628. *
  13629. * TBSCertificate ::= SEQUENCE {
  13630. * version [0] EXPLICIT Version DEFAULT v1,
  13631. * serialNumber CertificateSerialNumber,
  13632. * signature AlgorithmIdentifier,
  13633. * issuer Name,
  13634. * validity Validity,
  13635. * subject Name,
  13636. * subjectPublicKeyInfo SubjectPublicKeyInfo,
  13637. * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
  13638. * -- If present, version shall be v2 or v3
  13639. * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
  13640. * -- If present, version shall be v2 or v3
  13641. * extensions [3] EXPLICIT Extensions OPTIONAL
  13642. * -- If present, version shall be v3
  13643. * }
  13644. *
  13645. * Version ::= INTEGER { v1(0), v2(1), v3(2) }
  13646. *
  13647. * CertificateSerialNumber ::= INTEGER
  13648. *
  13649. * Name ::= CHOICE {
  13650. * // only one possible choice for now
  13651. * RDNSequence
  13652. * }
  13653. *
  13654. * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
  13655. *
  13656. * RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
  13657. *
  13658. * AttributeTypeAndValue ::= SEQUENCE {
  13659. * type AttributeType,
  13660. * value AttributeValue
  13661. * }
  13662. * AttributeType ::= OBJECT IDENTIFIER
  13663. * AttributeValue ::= ANY DEFINED BY AttributeType
  13664. *
  13665. * Validity ::= SEQUENCE {
  13666. * notBefore Time,
  13667. * notAfter Time
  13668. * }
  13669. *
  13670. * Time ::= CHOICE {
  13671. * utcTime UTCTime,
  13672. * generalTime GeneralizedTime
  13673. * }
  13674. *
  13675. * UniqueIdentifier ::= BIT STRING
  13676. *
  13677. * SubjectPublicKeyInfo ::= SEQUENCE {
  13678. * algorithm AlgorithmIdentifier,
  13679. * subjectPublicKey BIT STRING
  13680. * }
  13681. *
  13682. * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
  13683. *
  13684. * Extension ::= SEQUENCE {
  13685. * extnID OBJECT IDENTIFIER,
  13686. * critical BOOLEAN DEFAULT FALSE,
  13687. * extnValue OCTET STRING
  13688. * }
  13689. *
  13690. * The only key algorithm currently supported for PKI is RSA.
  13691. *
  13692. * RSASSA-PSS signatures are described in RFC 3447 and RFC 4055.
  13693. *
  13694. * PKCS#10 v1.7 describes certificate signing requests:
  13695. *
  13696. * CertificationRequestInfo:
  13697. *
  13698. * CertificationRequestInfo ::= SEQUENCE {
  13699. * version INTEGER { v1(0) } (v1,...),
  13700. * subject Name,
  13701. * subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }},
  13702. * attributes [0] Attributes{{ CRIAttributes }}
  13703. * }
  13704. *
  13705. * Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }}
  13706. *
  13707. * CRIAttributes ATTRIBUTE ::= {
  13708. * ... -- add any locally defined attributes here -- }
  13709. *
  13710. * Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE {
  13711. * type ATTRIBUTE.&id({IOSet}),
  13712. * values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type})
  13713. * }
  13714. *
  13715. * CertificationRequest ::= SEQUENCE {
  13716. * certificationRequestInfo CertificationRequestInfo,
  13717. * signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }},
  13718. * signature BIT STRING
  13719. * }
  13720. */
  13721. var forge$2 = forge$s;
  13722. // shortcut for asn.1 API
  13723. var asn1$2 = forge$2.asn1;
  13724. /* Public Key Infrastructure (PKI) implementation. */
  13725. var pki$2 = forge$2.pki = forge$2.pki || {};
  13726. var oids = pki$2.oids;
  13727. // short name OID mappings
  13728. var _shortNames = {};
  13729. _shortNames['CN'] = oids['commonName'];
  13730. _shortNames['commonName'] = 'CN';
  13731. _shortNames['C'] = oids['countryName'];
  13732. _shortNames['countryName'] = 'C';
  13733. _shortNames['L'] = oids['localityName'];
  13734. _shortNames['localityName'] = 'L';
  13735. _shortNames['ST'] = oids['stateOrProvinceName'];
  13736. _shortNames['stateOrProvinceName'] = 'ST';
  13737. _shortNames['O'] = oids['organizationName'];
  13738. _shortNames['organizationName'] = 'O';
  13739. _shortNames['OU'] = oids['organizationalUnitName'];
  13740. _shortNames['organizationalUnitName'] = 'OU';
  13741. _shortNames['E'] = oids['emailAddress'];
  13742. _shortNames['emailAddress'] = 'E';
  13743. // validator for an SubjectPublicKeyInfo structure
  13744. // Note: Currently only works with an RSA public key
  13745. var publicKeyValidator = forge$2.pki.rsa.publicKeyValidator;
  13746. // validator for an X.509v3 certificate
  13747. var x509CertificateValidator = {
  13748. name: 'Certificate',
  13749. tagClass: asn1$2.Class.UNIVERSAL,
  13750. type: asn1$2.Type.SEQUENCE,
  13751. constructed: true,
  13752. value: [{
  13753. name: 'Certificate.TBSCertificate',
  13754. tagClass: asn1$2.Class.UNIVERSAL,
  13755. type: asn1$2.Type.SEQUENCE,
  13756. constructed: true,
  13757. captureAsn1: 'tbsCertificate',
  13758. value: [{
  13759. name: 'Certificate.TBSCertificate.version',
  13760. tagClass: asn1$2.Class.CONTEXT_SPECIFIC,
  13761. type: 0,
  13762. constructed: true,
  13763. optional: true,
  13764. value: [{
  13765. name: 'Certificate.TBSCertificate.version.integer',
  13766. tagClass: asn1$2.Class.UNIVERSAL,
  13767. type: asn1$2.Type.INTEGER,
  13768. constructed: false,
  13769. capture: 'certVersion'
  13770. }]
  13771. }, {
  13772. name: 'Certificate.TBSCertificate.serialNumber',
  13773. tagClass: asn1$2.Class.UNIVERSAL,
  13774. type: asn1$2.Type.INTEGER,
  13775. constructed: false,
  13776. capture: 'certSerialNumber'
  13777. }, {
  13778. name: 'Certificate.TBSCertificate.signature',
  13779. tagClass: asn1$2.Class.UNIVERSAL,
  13780. type: asn1$2.Type.SEQUENCE,
  13781. constructed: true,
  13782. value: [{
  13783. name: 'Certificate.TBSCertificate.signature.algorithm',
  13784. tagClass: asn1$2.Class.UNIVERSAL,
  13785. type: asn1$2.Type.OID,
  13786. constructed: false,
  13787. capture: 'certinfoSignatureOid'
  13788. }, {
  13789. name: 'Certificate.TBSCertificate.signature.parameters',
  13790. tagClass: asn1$2.Class.UNIVERSAL,
  13791. optional: true,
  13792. captureAsn1: 'certinfoSignatureParams'
  13793. }]
  13794. }, {
  13795. name: 'Certificate.TBSCertificate.issuer',
  13796. tagClass: asn1$2.Class.UNIVERSAL,
  13797. type: asn1$2.Type.SEQUENCE,
  13798. constructed: true,
  13799. captureAsn1: 'certIssuer'
  13800. }, {
  13801. name: 'Certificate.TBSCertificate.validity',
  13802. tagClass: asn1$2.Class.UNIVERSAL,
  13803. type: asn1$2.Type.SEQUENCE,
  13804. constructed: true,
  13805. // Note: UTC and generalized times may both appear so the capture
  13806. // names are based on their detected order, the names used below
  13807. // are only for the common case, which validity time really means
  13808. // "notBefore" and which means "notAfter" will be determined by order
  13809. value: [{
  13810. // notBefore (Time) (UTC time case)
  13811. name: 'Certificate.TBSCertificate.validity.notBefore (utc)',
  13812. tagClass: asn1$2.Class.UNIVERSAL,
  13813. type: asn1$2.Type.UTCTIME,
  13814. constructed: false,
  13815. optional: true,
  13816. capture: 'certValidity1UTCTime'
  13817. }, {
  13818. // notBefore (Time) (generalized time case)
  13819. name: 'Certificate.TBSCertificate.validity.notBefore (generalized)',
  13820. tagClass: asn1$2.Class.UNIVERSAL,
  13821. type: asn1$2.Type.GENERALIZEDTIME,
  13822. constructed: false,
  13823. optional: true,
  13824. capture: 'certValidity2GeneralizedTime'
  13825. }, {
  13826. // notAfter (Time) (only UTC time is supported)
  13827. name: 'Certificate.TBSCertificate.validity.notAfter (utc)',
  13828. tagClass: asn1$2.Class.UNIVERSAL,
  13829. type: asn1$2.Type.UTCTIME,
  13830. constructed: false,
  13831. optional: true,
  13832. capture: 'certValidity3UTCTime'
  13833. }, {
  13834. // notAfter (Time) (only UTC time is supported)
  13835. name: 'Certificate.TBSCertificate.validity.notAfter (generalized)',
  13836. tagClass: asn1$2.Class.UNIVERSAL,
  13837. type: asn1$2.Type.GENERALIZEDTIME,
  13838. constructed: false,
  13839. optional: true,
  13840. capture: 'certValidity4GeneralizedTime'
  13841. }]
  13842. }, {
  13843. // Name (subject) (RDNSequence)
  13844. name: 'Certificate.TBSCertificate.subject',
  13845. tagClass: asn1$2.Class.UNIVERSAL,
  13846. type: asn1$2.Type.SEQUENCE,
  13847. constructed: true,
  13848. captureAsn1: 'certSubject'
  13849. },
  13850. // SubjectPublicKeyInfo
  13851. publicKeyValidator,
  13852. {
  13853. // issuerUniqueID (optional)
  13854. name: 'Certificate.TBSCertificate.issuerUniqueID',
  13855. tagClass: asn1$2.Class.CONTEXT_SPECIFIC,
  13856. type: 1,
  13857. constructed: true,
  13858. optional: true,
  13859. value: [{
  13860. name: 'Certificate.TBSCertificate.issuerUniqueID.id',
  13861. tagClass: asn1$2.Class.UNIVERSAL,
  13862. type: asn1$2.Type.BITSTRING,
  13863. constructed: false,
  13864. // TODO: support arbitrary bit length ids
  13865. captureBitStringValue: 'certIssuerUniqueId'
  13866. }]
  13867. }, {
  13868. // subjectUniqueID (optional)
  13869. name: 'Certificate.TBSCertificate.subjectUniqueID',
  13870. tagClass: asn1$2.Class.CONTEXT_SPECIFIC,
  13871. type: 2,
  13872. constructed: true,
  13873. optional: true,
  13874. value: [{
  13875. name: 'Certificate.TBSCertificate.subjectUniqueID.id',
  13876. tagClass: asn1$2.Class.UNIVERSAL,
  13877. type: asn1$2.Type.BITSTRING,
  13878. constructed: false,
  13879. // TODO: support arbitrary bit length ids
  13880. captureBitStringValue: 'certSubjectUniqueId'
  13881. }]
  13882. }, {
  13883. // Extensions (optional)
  13884. name: 'Certificate.TBSCertificate.extensions',
  13885. tagClass: asn1$2.Class.CONTEXT_SPECIFIC,
  13886. type: 3,
  13887. constructed: true,
  13888. captureAsn1: 'certExtensions',
  13889. optional: true
  13890. }]
  13891. }, {
  13892. // AlgorithmIdentifier (signature algorithm)
  13893. name: 'Certificate.signatureAlgorithm',
  13894. tagClass: asn1$2.Class.UNIVERSAL,
  13895. type: asn1$2.Type.SEQUENCE,
  13896. constructed: true,
  13897. value: [{
  13898. // algorithm
  13899. name: 'Certificate.signatureAlgorithm.algorithm',
  13900. tagClass: asn1$2.Class.UNIVERSAL,
  13901. type: asn1$2.Type.OID,
  13902. constructed: false,
  13903. capture: 'certSignatureOid'
  13904. }, {
  13905. name: 'Certificate.TBSCertificate.signature.parameters',
  13906. tagClass: asn1$2.Class.UNIVERSAL,
  13907. optional: true,
  13908. captureAsn1: 'certSignatureParams'
  13909. }]
  13910. }, {
  13911. // SignatureValue
  13912. name: 'Certificate.signatureValue',
  13913. tagClass: asn1$2.Class.UNIVERSAL,
  13914. type: asn1$2.Type.BITSTRING,
  13915. constructed: false,
  13916. captureBitStringValue: 'certSignature'
  13917. }]
  13918. };
  13919. var rsassaPssParameterValidator = {
  13920. name: 'rsapss',
  13921. tagClass: asn1$2.Class.UNIVERSAL,
  13922. type: asn1$2.Type.SEQUENCE,
  13923. constructed: true,
  13924. value: [{
  13925. name: 'rsapss.hashAlgorithm',
  13926. tagClass: asn1$2.Class.CONTEXT_SPECIFIC,
  13927. type: 0,
  13928. constructed: true,
  13929. value: [{
  13930. name: 'rsapss.hashAlgorithm.AlgorithmIdentifier',
  13931. tagClass: asn1$2.Class.UNIVERSAL,
  13932. type: asn1$2.Class.SEQUENCE,
  13933. constructed: true,
  13934. optional: true,
  13935. value: [{
  13936. name: 'rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm',
  13937. tagClass: asn1$2.Class.UNIVERSAL,
  13938. type: asn1$2.Type.OID,
  13939. constructed: false,
  13940. capture: 'hashOid'
  13941. /* parameter block omitted, for SHA1 NULL anyhow. */
  13942. }]
  13943. }]
  13944. }, {
  13945. name: 'rsapss.maskGenAlgorithm',
  13946. tagClass: asn1$2.Class.CONTEXT_SPECIFIC,
  13947. type: 1,
  13948. constructed: true,
  13949. value: [{
  13950. name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier',
  13951. tagClass: asn1$2.Class.UNIVERSAL,
  13952. type: asn1$2.Class.SEQUENCE,
  13953. constructed: true,
  13954. optional: true,
  13955. value: [{
  13956. name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm',
  13957. tagClass: asn1$2.Class.UNIVERSAL,
  13958. type: asn1$2.Type.OID,
  13959. constructed: false,
  13960. capture: 'maskGenOid'
  13961. }, {
  13962. name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params',
  13963. tagClass: asn1$2.Class.UNIVERSAL,
  13964. type: asn1$2.Type.SEQUENCE,
  13965. constructed: true,
  13966. value: [{
  13967. name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm',
  13968. tagClass: asn1$2.Class.UNIVERSAL,
  13969. type: asn1$2.Type.OID,
  13970. constructed: false,
  13971. capture: 'maskGenHashOid'
  13972. /* parameter block omitted, for SHA1 NULL anyhow. */
  13973. }]
  13974. }]
  13975. }]
  13976. }, {
  13977. name: 'rsapss.saltLength',
  13978. tagClass: asn1$2.Class.CONTEXT_SPECIFIC,
  13979. type: 2,
  13980. optional: true,
  13981. value: [{
  13982. name: 'rsapss.saltLength.saltLength',
  13983. tagClass: asn1$2.Class.UNIVERSAL,
  13984. type: asn1$2.Class.INTEGER,
  13985. constructed: false,
  13986. capture: 'saltLength'
  13987. }]
  13988. }, {
  13989. name: 'rsapss.trailerField',
  13990. tagClass: asn1$2.Class.CONTEXT_SPECIFIC,
  13991. type: 3,
  13992. optional: true,
  13993. value: [{
  13994. name: 'rsapss.trailer.trailer',
  13995. tagClass: asn1$2.Class.UNIVERSAL,
  13996. type: asn1$2.Class.INTEGER,
  13997. constructed: false,
  13998. capture: 'trailer'
  13999. }]
  14000. }]
  14001. };
  14002. // validator for a CertificationRequestInfo structure
  14003. var certificationRequestInfoValidator = {
  14004. name: 'CertificationRequestInfo',
  14005. tagClass: asn1$2.Class.UNIVERSAL,
  14006. type: asn1$2.Type.SEQUENCE,
  14007. constructed: true,
  14008. captureAsn1: 'certificationRequestInfo',
  14009. value: [{
  14010. name: 'CertificationRequestInfo.integer',
  14011. tagClass: asn1$2.Class.UNIVERSAL,
  14012. type: asn1$2.Type.INTEGER,
  14013. constructed: false,
  14014. capture: 'certificationRequestInfoVersion'
  14015. }, {
  14016. // Name (subject) (RDNSequence)
  14017. name: 'CertificationRequestInfo.subject',
  14018. tagClass: asn1$2.Class.UNIVERSAL,
  14019. type: asn1$2.Type.SEQUENCE,
  14020. constructed: true,
  14021. captureAsn1: 'certificationRequestInfoSubject'
  14022. },
  14023. // SubjectPublicKeyInfo
  14024. publicKeyValidator,
  14025. {
  14026. name: 'CertificationRequestInfo.attributes',
  14027. tagClass: asn1$2.Class.CONTEXT_SPECIFIC,
  14028. type: 0,
  14029. constructed: true,
  14030. optional: true,
  14031. capture: 'certificationRequestInfoAttributes',
  14032. value: [{
  14033. name: 'CertificationRequestInfo.attributes',
  14034. tagClass: asn1$2.Class.UNIVERSAL,
  14035. type: asn1$2.Type.SEQUENCE,
  14036. constructed: true,
  14037. value: [{
  14038. name: 'CertificationRequestInfo.attributes.type',
  14039. tagClass: asn1$2.Class.UNIVERSAL,
  14040. type: asn1$2.Type.OID,
  14041. constructed: false
  14042. }, {
  14043. name: 'CertificationRequestInfo.attributes.value',
  14044. tagClass: asn1$2.Class.UNIVERSAL,
  14045. type: asn1$2.Type.SET,
  14046. constructed: true
  14047. }]
  14048. }]
  14049. }]
  14050. };
  14051. // validator for a CertificationRequest structure
  14052. var certificationRequestValidator = {
  14053. name: 'CertificationRequest',
  14054. tagClass: asn1$2.Class.UNIVERSAL,
  14055. type: asn1$2.Type.SEQUENCE,
  14056. constructed: true,
  14057. captureAsn1: 'csr',
  14058. value: [
  14059. certificationRequestInfoValidator, {
  14060. // AlgorithmIdentifier (signature algorithm)
  14061. name: 'CertificationRequest.signatureAlgorithm',
  14062. tagClass: asn1$2.Class.UNIVERSAL,
  14063. type: asn1$2.Type.SEQUENCE,
  14064. constructed: true,
  14065. value: [{
  14066. // algorithm
  14067. name: 'CertificationRequest.signatureAlgorithm.algorithm',
  14068. tagClass: asn1$2.Class.UNIVERSAL,
  14069. type: asn1$2.Type.OID,
  14070. constructed: false,
  14071. capture: 'csrSignatureOid'
  14072. }, {
  14073. name: 'CertificationRequest.signatureAlgorithm.parameters',
  14074. tagClass: asn1$2.Class.UNIVERSAL,
  14075. optional: true,
  14076. captureAsn1: 'csrSignatureParams'
  14077. }]
  14078. }, {
  14079. // signature
  14080. name: 'CertificationRequest.signature',
  14081. tagClass: asn1$2.Class.UNIVERSAL,
  14082. type: asn1$2.Type.BITSTRING,
  14083. constructed: false,
  14084. captureBitStringValue: 'csrSignature'
  14085. }
  14086. ]
  14087. };
  14088. /**
  14089. * Converts an RDNSequence of ASN.1 DER-encoded RelativeDistinguishedName
  14090. * sets into an array with objects that have type and value properties.
  14091. *
  14092. * @param rdn the RDNSequence to convert.
  14093. * @param md a message digest to append type and value to if provided.
  14094. */
  14095. pki$2.RDNAttributesAsArray = function(rdn, md) {
  14096. var rval = [];
  14097. // each value in 'rdn' in is a SET of RelativeDistinguishedName
  14098. var set, attr, obj;
  14099. for(var si = 0; si < rdn.value.length; ++si) {
  14100. // get the RelativeDistinguishedName set
  14101. set = rdn.value[si];
  14102. // each value in the SET is an AttributeTypeAndValue sequence
  14103. // containing first a type (an OID) and second a value (defined by
  14104. // the OID)
  14105. for(var i = 0; i < set.value.length; ++i) {
  14106. obj = {};
  14107. attr = set.value[i];
  14108. obj.type = asn1$2.derToOid(attr.value[0].value);
  14109. obj.value = attr.value[1].value;
  14110. obj.valueTagClass = attr.value[1].type;
  14111. // if the OID is known, get its name and short name
  14112. if(obj.type in oids) {
  14113. obj.name = oids[obj.type];
  14114. if(obj.name in _shortNames) {
  14115. obj.shortName = _shortNames[obj.name];
  14116. }
  14117. }
  14118. if(md) {
  14119. md.update(obj.type);
  14120. md.update(obj.value);
  14121. }
  14122. rval.push(obj);
  14123. }
  14124. }
  14125. return rval;
  14126. };
  14127. /**
  14128. * Converts ASN.1 CRIAttributes into an array with objects that have type and
  14129. * value properties.
  14130. *
  14131. * @param attributes the CRIAttributes to convert.
  14132. */
  14133. pki$2.CRIAttributesAsArray = function(attributes) {
  14134. var rval = [];
  14135. // each value in 'attributes' in is a SEQUENCE with an OID and a SET
  14136. for(var si = 0; si < attributes.length; ++si) {
  14137. // get the attribute sequence
  14138. var seq = attributes[si];
  14139. // each value in the SEQUENCE containing first a type (an OID) and
  14140. // second a set of values (defined by the OID)
  14141. var type = asn1$2.derToOid(seq.value[0].value);
  14142. var values = seq.value[1].value;
  14143. for(var vi = 0; vi < values.length; ++vi) {
  14144. var obj = {};
  14145. obj.type = type;
  14146. obj.value = values[vi].value;
  14147. obj.valueTagClass = values[vi].type;
  14148. // if the OID is known, get its name and short name
  14149. if(obj.type in oids) {
  14150. obj.name = oids[obj.type];
  14151. if(obj.name in _shortNames) {
  14152. obj.shortName = _shortNames[obj.name];
  14153. }
  14154. }
  14155. // parse extensions
  14156. if(obj.type === oids.extensionRequest) {
  14157. obj.extensions = [];
  14158. for(var ei = 0; ei < obj.value.length; ++ei) {
  14159. obj.extensions.push(pki$2.certificateExtensionFromAsn1(obj.value[ei]));
  14160. }
  14161. }
  14162. rval.push(obj);
  14163. }
  14164. }
  14165. return rval;
  14166. };
  14167. /**
  14168. * Gets an issuer or subject attribute from its name, type, or short name.
  14169. *
  14170. * @param obj the issuer or subject object.
  14171. * @param options a short name string or an object with:
  14172. * shortName the short name for the attribute.
  14173. * name the name for the attribute.
  14174. * type the type for the attribute.
  14175. *
  14176. * @return the attribute.
  14177. */
  14178. function _getAttribute(obj, options) {
  14179. if(typeof options === 'string') {
  14180. options = {shortName: options};
  14181. }
  14182. var rval = null;
  14183. var attr;
  14184. for(var i = 0; rval === null && i < obj.attributes.length; ++i) {
  14185. attr = obj.attributes[i];
  14186. if(options.type && options.type === attr.type) {
  14187. rval = attr;
  14188. } else if(options.name && options.name === attr.name) {
  14189. rval = attr;
  14190. } else if(options.shortName && options.shortName === attr.shortName) {
  14191. rval = attr;
  14192. }
  14193. }
  14194. return rval;
  14195. }
  14196. /**
  14197. * Converts signature parameters from ASN.1 structure.
  14198. *
  14199. * Currently only RSASSA-PSS supported. The PKCS#1 v1.5 signature scheme had
  14200. * no parameters.
  14201. *
  14202. * RSASSA-PSS-params ::= SEQUENCE {
  14203. * hashAlgorithm [0] HashAlgorithm DEFAULT
  14204. * sha1Identifier,
  14205. * maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT
  14206. * mgf1SHA1Identifier,
  14207. * saltLength [2] INTEGER DEFAULT 20,
  14208. * trailerField [3] INTEGER DEFAULT 1
  14209. * }
  14210. *
  14211. * HashAlgorithm ::= AlgorithmIdentifier
  14212. *
  14213. * MaskGenAlgorithm ::= AlgorithmIdentifier
  14214. *
  14215. * AlgorithmIdentifer ::= SEQUENCE {
  14216. * algorithm OBJECT IDENTIFIER,
  14217. * parameters ANY DEFINED BY algorithm OPTIONAL
  14218. * }
  14219. *
  14220. * @param oid The OID specifying the signature algorithm
  14221. * @param obj The ASN.1 structure holding the parameters
  14222. * @param fillDefaults Whether to use return default values where omitted
  14223. * @return signature parameter object
  14224. */
  14225. var _readSignatureParameters = function(oid, obj, fillDefaults) {
  14226. var params = {};
  14227. if(oid !== oids['RSASSA-PSS']) {
  14228. return params;
  14229. }
  14230. if(fillDefaults) {
  14231. params = {
  14232. hash: {
  14233. algorithmOid: oids['sha1']
  14234. },
  14235. mgf: {
  14236. algorithmOid: oids['mgf1'],
  14237. hash: {
  14238. algorithmOid: oids['sha1']
  14239. }
  14240. },
  14241. saltLength: 20
  14242. };
  14243. }
  14244. var capture = {};
  14245. var errors = [];
  14246. if(!asn1$2.validate(obj, rsassaPssParameterValidator, capture, errors)) {
  14247. var error = new Error('Cannot read RSASSA-PSS parameter block.');
  14248. error.errors = errors;
  14249. throw error;
  14250. }
  14251. if(capture.hashOid !== undefined) {
  14252. params.hash = params.hash || {};
  14253. params.hash.algorithmOid = asn1$2.derToOid(capture.hashOid);
  14254. }
  14255. if(capture.maskGenOid !== undefined) {
  14256. params.mgf = params.mgf || {};
  14257. params.mgf.algorithmOid = asn1$2.derToOid(capture.maskGenOid);
  14258. params.mgf.hash = params.mgf.hash || {};
  14259. params.mgf.hash.algorithmOid = asn1$2.derToOid(capture.maskGenHashOid);
  14260. }
  14261. if(capture.saltLength !== undefined) {
  14262. params.saltLength = capture.saltLength.charCodeAt(0);
  14263. }
  14264. return params;
  14265. };
  14266. /**
  14267. * Create signature digest for OID.
  14268. *
  14269. * @param options
  14270. * signatureOid: the OID specifying the signature algorithm.
  14271. * type: a human readable type for error messages
  14272. * @return a created md instance. throws if unknown oid.
  14273. */
  14274. var _createSignatureDigest = function(options) {
  14275. switch(oids[options.signatureOid]) {
  14276. case 'sha1WithRSAEncryption':
  14277. // deprecated alias
  14278. case 'sha1WithRSASignature':
  14279. return forge$2.md.sha1.create();
  14280. case 'md5WithRSAEncryption':
  14281. return forge$2.md.md5.create();
  14282. case 'sha256WithRSAEncryption':
  14283. return forge$2.md.sha256.create();
  14284. case 'sha384WithRSAEncryption':
  14285. return forge$2.md.sha384.create();
  14286. case 'sha512WithRSAEncryption':
  14287. return forge$2.md.sha512.create();
  14288. case 'RSASSA-PSS':
  14289. return forge$2.md.sha256.create();
  14290. default:
  14291. var error = new Error(
  14292. 'Could not compute ' + options.type + ' digest. ' +
  14293. 'Unknown signature OID.');
  14294. error.signatureOid = options.signatureOid;
  14295. throw error;
  14296. }
  14297. };
  14298. /**
  14299. * Verify signature on certificate or CSR.
  14300. *
  14301. * @param options:
  14302. * certificate the certificate or CSR to verify.
  14303. * md the signature digest.
  14304. * signature the signature
  14305. * @return a created md instance. throws if unknown oid.
  14306. */
  14307. var _verifySignature = function(options) {
  14308. var cert = options.certificate;
  14309. var scheme;
  14310. switch(cert.signatureOid) {
  14311. case oids.sha1WithRSAEncryption:
  14312. // deprecated alias
  14313. case oids.sha1WithRSASignature:
  14314. /* use PKCS#1 v1.5 padding scheme */
  14315. break;
  14316. case oids['RSASSA-PSS']:
  14317. var hash, mgf;
  14318. /* initialize mgf */
  14319. hash = oids[cert.signatureParameters.mgf.hash.algorithmOid];
  14320. if(hash === undefined || forge$2.md[hash] === undefined) {
  14321. var error = new Error('Unsupported MGF hash function.');
  14322. error.oid = cert.signatureParameters.mgf.hash.algorithmOid;
  14323. error.name = hash;
  14324. throw error;
  14325. }
  14326. mgf = oids[cert.signatureParameters.mgf.algorithmOid];
  14327. if(mgf === undefined || forge$2.mgf[mgf] === undefined) {
  14328. var error = new Error('Unsupported MGF function.');
  14329. error.oid = cert.signatureParameters.mgf.algorithmOid;
  14330. error.name = mgf;
  14331. throw error;
  14332. }
  14333. mgf = forge$2.mgf[mgf].create(forge$2.md[hash].create());
  14334. /* initialize hash function */
  14335. hash = oids[cert.signatureParameters.hash.algorithmOid];
  14336. if(hash === undefined || forge$2.md[hash] === undefined) {
  14337. var error = new Error('Unsupported RSASSA-PSS hash function.');
  14338. error.oid = cert.signatureParameters.hash.algorithmOid;
  14339. error.name = hash;
  14340. throw error;
  14341. }
  14342. scheme = forge$2.pss.create(
  14343. forge$2.md[hash].create(), mgf, cert.signatureParameters.saltLength
  14344. );
  14345. break;
  14346. }
  14347. // verify signature on cert using public key
  14348. return cert.publicKey.verify(
  14349. options.md.digest().getBytes(), options.signature, scheme
  14350. );
  14351. };
  14352. /**
  14353. * Converts an X.509 certificate from PEM format.
  14354. *
  14355. * Note: If the certificate is to be verified then compute hash should
  14356. * be set to true. This will scan the TBSCertificate part of the ASN.1
  14357. * object while it is converted so it doesn't need to be converted back
  14358. * to ASN.1-DER-encoding later.
  14359. *
  14360. * @param pem the PEM-formatted certificate.
  14361. * @param computeHash true to compute the hash for verification.
  14362. * @param strict true to be strict when checking ASN.1 value lengths, false to
  14363. * allow truncated values (default: true).
  14364. *
  14365. * @return the certificate.
  14366. */
  14367. pki$2.certificateFromPem = function(pem, computeHash, strict) {
  14368. var msg = forge$2.pem.decode(pem)[0];
  14369. if(msg.type !== 'CERTIFICATE' &&
  14370. msg.type !== 'X509 CERTIFICATE' &&
  14371. msg.type !== 'TRUSTED CERTIFICATE') {
  14372. var error = new Error(
  14373. 'Could not convert certificate from PEM; PEM header type ' +
  14374. 'is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');
  14375. error.headerType = msg.type;
  14376. throw error;
  14377. }
  14378. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  14379. throw new Error(
  14380. 'Could not convert certificate from PEM; PEM is encrypted.');
  14381. }
  14382. // convert DER to ASN.1 object
  14383. var obj = asn1$2.fromDer(msg.body, strict);
  14384. return pki$2.certificateFromAsn1(obj, computeHash);
  14385. };
  14386. /**
  14387. * Converts an X.509 certificate to PEM format.
  14388. *
  14389. * @param cert the certificate.
  14390. * @param maxline the maximum characters per line, defaults to 64.
  14391. *
  14392. * @return the PEM-formatted certificate.
  14393. */
  14394. pki$2.certificateToPem = function(cert, maxline) {
  14395. // convert to ASN.1, then DER, then PEM-encode
  14396. var msg = {
  14397. type: 'CERTIFICATE',
  14398. body: asn1$2.toDer(pki$2.certificateToAsn1(cert)).getBytes()
  14399. };
  14400. return forge$2.pem.encode(msg, {maxline: maxline});
  14401. };
  14402. /**
  14403. * Converts an RSA public key from PEM format.
  14404. *
  14405. * @param pem the PEM-formatted public key.
  14406. *
  14407. * @return the public key.
  14408. */
  14409. pki$2.publicKeyFromPem = function(pem) {
  14410. var msg = forge$2.pem.decode(pem)[0];
  14411. if(msg.type !== 'PUBLIC KEY' && msg.type !== 'RSA PUBLIC KEY') {
  14412. var error = new Error('Could not convert public key from PEM; PEM header ' +
  14413. 'type is not "PUBLIC KEY" or "RSA PUBLIC KEY".');
  14414. error.headerType = msg.type;
  14415. throw error;
  14416. }
  14417. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  14418. throw new Error('Could not convert public key from PEM; PEM is encrypted.');
  14419. }
  14420. // convert DER to ASN.1 object
  14421. var obj = asn1$2.fromDer(msg.body);
  14422. return pki$2.publicKeyFromAsn1(obj);
  14423. };
  14424. /**
  14425. * Converts an RSA public key to PEM format (using a SubjectPublicKeyInfo).
  14426. *
  14427. * @param key the public key.
  14428. * @param maxline the maximum characters per line, defaults to 64.
  14429. *
  14430. * @return the PEM-formatted public key.
  14431. */
  14432. pki$2.publicKeyToPem = function(key, maxline) {
  14433. // convert to ASN.1, then DER, then PEM-encode
  14434. var msg = {
  14435. type: 'PUBLIC KEY',
  14436. body: asn1$2.toDer(pki$2.publicKeyToAsn1(key)).getBytes()
  14437. };
  14438. return forge$2.pem.encode(msg, {maxline: maxline});
  14439. };
  14440. /**
  14441. * Converts an RSA public key to PEM format (using an RSAPublicKey).
  14442. *
  14443. * @param key the public key.
  14444. * @param maxline the maximum characters per line, defaults to 64.
  14445. *
  14446. * @return the PEM-formatted public key.
  14447. */
  14448. pki$2.publicKeyToRSAPublicKeyPem = function(key, maxline) {
  14449. // convert to ASN.1, then DER, then PEM-encode
  14450. var msg = {
  14451. type: 'RSA PUBLIC KEY',
  14452. body: asn1$2.toDer(pki$2.publicKeyToRSAPublicKey(key)).getBytes()
  14453. };
  14454. return forge$2.pem.encode(msg, {maxline: maxline});
  14455. };
  14456. /**
  14457. * Gets a fingerprint for the given public key.
  14458. *
  14459. * @param options the options to use.
  14460. * [md] the message digest object to use (defaults to forge.md.sha1).
  14461. * [type] the type of fingerprint, such as 'RSAPublicKey',
  14462. * 'SubjectPublicKeyInfo' (defaults to 'RSAPublicKey').
  14463. * [encoding] an alternative output encoding, such as 'hex'
  14464. * (defaults to none, outputs a byte buffer).
  14465. * [delimiter] the delimiter to use between bytes for 'hex' encoded
  14466. * output, eg: ':' (defaults to none).
  14467. *
  14468. * @return the fingerprint as a byte buffer or other encoding based on options.
  14469. */
  14470. pki$2.getPublicKeyFingerprint = function(key, options) {
  14471. options = options || {};
  14472. var md = options.md || forge$2.md.sha1.create();
  14473. var type = options.type || 'RSAPublicKey';
  14474. var bytes;
  14475. switch(type) {
  14476. case 'RSAPublicKey':
  14477. bytes = asn1$2.toDer(pki$2.publicKeyToRSAPublicKey(key)).getBytes();
  14478. break;
  14479. case 'SubjectPublicKeyInfo':
  14480. bytes = asn1$2.toDer(pki$2.publicKeyToAsn1(key)).getBytes();
  14481. break;
  14482. default:
  14483. throw new Error('Unknown fingerprint type "' + options.type + '".');
  14484. }
  14485. // hash public key bytes
  14486. md.start();
  14487. md.update(bytes);
  14488. var digest = md.digest();
  14489. if(options.encoding === 'hex') {
  14490. var hex = digest.toHex();
  14491. if(options.delimiter) {
  14492. return hex.match(/.{2}/g).join(options.delimiter);
  14493. }
  14494. return hex;
  14495. } else if(options.encoding === 'binary') {
  14496. return digest.getBytes();
  14497. } else if(options.encoding) {
  14498. throw new Error('Unknown encoding "' + options.encoding + '".');
  14499. }
  14500. return digest;
  14501. };
  14502. /**
  14503. * Converts a PKCS#10 certification request (CSR) from PEM format.
  14504. *
  14505. * Note: If the certification request is to be verified then compute hash
  14506. * should be set to true. This will scan the CertificationRequestInfo part of
  14507. * the ASN.1 object while it is converted so it doesn't need to be converted
  14508. * back to ASN.1-DER-encoding later.
  14509. *
  14510. * @param pem the PEM-formatted certificate.
  14511. * @param computeHash true to compute the hash for verification.
  14512. * @param strict true to be strict when checking ASN.1 value lengths, false to
  14513. * allow truncated values (default: true).
  14514. *
  14515. * @return the certification request (CSR).
  14516. */
  14517. pki$2.certificationRequestFromPem = function(pem, computeHash, strict) {
  14518. var msg = forge$2.pem.decode(pem)[0];
  14519. if(msg.type !== 'CERTIFICATE REQUEST') {
  14520. var error = new Error('Could not convert certification request from PEM; ' +
  14521. 'PEM header type is not "CERTIFICATE REQUEST".');
  14522. error.headerType = msg.type;
  14523. throw error;
  14524. }
  14525. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  14526. throw new Error('Could not convert certification request from PEM; ' +
  14527. 'PEM is encrypted.');
  14528. }
  14529. // convert DER to ASN.1 object
  14530. var obj = asn1$2.fromDer(msg.body, strict);
  14531. return pki$2.certificationRequestFromAsn1(obj, computeHash);
  14532. };
  14533. /**
  14534. * Converts a PKCS#10 certification request (CSR) to PEM format.
  14535. *
  14536. * @param csr the certification request.
  14537. * @param maxline the maximum characters per line, defaults to 64.
  14538. *
  14539. * @return the PEM-formatted certification request.
  14540. */
  14541. pki$2.certificationRequestToPem = function(csr, maxline) {
  14542. // convert to ASN.1, then DER, then PEM-encode
  14543. var msg = {
  14544. type: 'CERTIFICATE REQUEST',
  14545. body: asn1$2.toDer(pki$2.certificationRequestToAsn1(csr)).getBytes()
  14546. };
  14547. return forge$2.pem.encode(msg, {maxline: maxline});
  14548. };
  14549. /**
  14550. * Creates an empty X.509v3 RSA certificate.
  14551. *
  14552. * @return the certificate.
  14553. */
  14554. pki$2.createCertificate = function() {
  14555. var cert = {};
  14556. cert.version = 0x02;
  14557. cert.serialNumber = '00';
  14558. cert.signatureOid = null;
  14559. cert.signature = null;
  14560. cert.siginfo = {};
  14561. cert.siginfo.algorithmOid = null;
  14562. cert.validity = {};
  14563. cert.validity.notBefore = new Date();
  14564. cert.validity.notAfter = new Date();
  14565. cert.issuer = {};
  14566. cert.issuer.getField = function(sn) {
  14567. return _getAttribute(cert.issuer, sn);
  14568. };
  14569. cert.issuer.addField = function(attr) {
  14570. _fillMissingFields([attr]);
  14571. cert.issuer.attributes.push(attr);
  14572. };
  14573. cert.issuer.attributes = [];
  14574. cert.issuer.hash = null;
  14575. cert.subject = {};
  14576. cert.subject.getField = function(sn) {
  14577. return _getAttribute(cert.subject, sn);
  14578. };
  14579. cert.subject.addField = function(attr) {
  14580. _fillMissingFields([attr]);
  14581. cert.subject.attributes.push(attr);
  14582. };
  14583. cert.subject.attributes = [];
  14584. cert.subject.hash = null;
  14585. cert.extensions = [];
  14586. cert.publicKey = null;
  14587. cert.md = null;
  14588. /**
  14589. * Sets the subject of this certificate.
  14590. *
  14591. * @param attrs the array of subject attributes to use.
  14592. * @param uniqueId an optional a unique ID to use.
  14593. */
  14594. cert.setSubject = function(attrs, uniqueId) {
  14595. // set new attributes, clear hash
  14596. _fillMissingFields(attrs);
  14597. cert.subject.attributes = attrs;
  14598. delete cert.subject.uniqueId;
  14599. if(uniqueId) {
  14600. // TODO: support arbitrary bit length ids
  14601. cert.subject.uniqueId = uniqueId;
  14602. }
  14603. cert.subject.hash = null;
  14604. };
  14605. /**
  14606. * Sets the issuer of this certificate.
  14607. *
  14608. * @param attrs the array of issuer attributes to use.
  14609. * @param uniqueId an optional a unique ID to use.
  14610. */
  14611. cert.setIssuer = function(attrs, uniqueId) {
  14612. // set new attributes, clear hash
  14613. _fillMissingFields(attrs);
  14614. cert.issuer.attributes = attrs;
  14615. delete cert.issuer.uniqueId;
  14616. if(uniqueId) {
  14617. // TODO: support arbitrary bit length ids
  14618. cert.issuer.uniqueId = uniqueId;
  14619. }
  14620. cert.issuer.hash = null;
  14621. };
  14622. /**
  14623. * Sets the extensions of this certificate.
  14624. *
  14625. * @param exts the array of extensions to use.
  14626. */
  14627. cert.setExtensions = function(exts) {
  14628. for(var i = 0; i < exts.length; ++i) {
  14629. _fillMissingExtensionFields(exts[i], {cert: cert});
  14630. }
  14631. // set new extensions
  14632. cert.extensions = exts;
  14633. };
  14634. /**
  14635. * Gets an extension by its name or id.
  14636. *
  14637. * @param options the name to use or an object with:
  14638. * name the name to use.
  14639. * id the id to use.
  14640. *
  14641. * @return the extension or null if not found.
  14642. */
  14643. cert.getExtension = function(options) {
  14644. if(typeof options === 'string') {
  14645. options = {name: options};
  14646. }
  14647. var rval = null;
  14648. var ext;
  14649. for(var i = 0; rval === null && i < cert.extensions.length; ++i) {
  14650. ext = cert.extensions[i];
  14651. if(options.id && ext.id === options.id) {
  14652. rval = ext;
  14653. } else if(options.name && ext.name === options.name) {
  14654. rval = ext;
  14655. }
  14656. }
  14657. return rval;
  14658. };
  14659. /**
  14660. * Signs this certificate using the given private key.
  14661. *
  14662. * @param key the private key to sign with.
  14663. * @param md the message digest object to use (defaults to forge.md.sha1).
  14664. */
  14665. cert.sign = function(key, md) {
  14666. // TODO: get signature OID from private key
  14667. cert.md = md || forge$2.md.sha1.create();
  14668. var algorithmOid = oids[cert.md.algorithm + 'WithRSAEncryption'];
  14669. if(!algorithmOid) {
  14670. var error = new Error('Could not compute certificate digest. ' +
  14671. 'Unknown message digest algorithm OID.');
  14672. error.algorithm = cert.md.algorithm;
  14673. throw error;
  14674. }
  14675. cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid;
  14676. // get TBSCertificate, convert to DER
  14677. cert.tbsCertificate = pki$2.getTBSCertificate(cert);
  14678. var bytes = asn1$2.toDer(cert.tbsCertificate);
  14679. // digest and sign
  14680. cert.md.update(bytes.getBytes());
  14681. cert.signature = key.sign(cert.md);
  14682. };
  14683. /**
  14684. * Attempts verify the signature on the passed certificate using this
  14685. * certificate's public key.
  14686. *
  14687. * @param child the certificate to verify.
  14688. *
  14689. * @return true if verified, false if not.
  14690. */
  14691. cert.verify = function(child) {
  14692. var rval = false;
  14693. if(!cert.issued(child)) {
  14694. var issuer = child.issuer;
  14695. var subject = cert.subject;
  14696. var error = new Error(
  14697. 'The parent certificate did not issue the given child ' +
  14698. 'certificate; the child certificate\'s issuer does not match the ' +
  14699. 'parent\'s subject.');
  14700. error.expectedIssuer = subject.attributes;
  14701. error.actualIssuer = issuer.attributes;
  14702. throw error;
  14703. }
  14704. var md = child.md;
  14705. if(md === null) {
  14706. // create digest for OID signature types
  14707. md = _createSignatureDigest({
  14708. signatureOid: child.signatureOid,
  14709. type: 'certificate'
  14710. });
  14711. // produce DER formatted TBSCertificate and digest it
  14712. var tbsCertificate = child.tbsCertificate || pki$2.getTBSCertificate(child);
  14713. var bytes = asn1$2.toDer(tbsCertificate);
  14714. md.update(bytes.getBytes());
  14715. }
  14716. if(md !== null) {
  14717. rval = _verifySignature({
  14718. certificate: cert, md: md, signature: child.signature
  14719. });
  14720. }
  14721. return rval;
  14722. };
  14723. /**
  14724. * Returns true if this certificate's issuer matches the passed
  14725. * certificate's subject. Note that no signature check is performed.
  14726. *
  14727. * @param parent the certificate to check.
  14728. *
  14729. * @return true if this certificate's issuer matches the passed certificate's
  14730. * subject.
  14731. */
  14732. cert.isIssuer = function(parent) {
  14733. var rval = false;
  14734. var i = cert.issuer;
  14735. var s = parent.subject;
  14736. // compare hashes if present
  14737. if(i.hash && s.hash) {
  14738. rval = (i.hash === s.hash);
  14739. } else if(i.attributes.length === s.attributes.length) {
  14740. // all attributes are the same so issuer matches subject
  14741. rval = true;
  14742. var iattr, sattr;
  14743. for(var n = 0; rval && n < i.attributes.length; ++n) {
  14744. iattr = i.attributes[n];
  14745. sattr = s.attributes[n];
  14746. if(iattr.type !== sattr.type || iattr.value !== sattr.value) {
  14747. // attribute mismatch
  14748. rval = false;
  14749. }
  14750. }
  14751. }
  14752. return rval;
  14753. };
  14754. /**
  14755. * Returns true if this certificate's subject matches the issuer of the
  14756. * given certificate). Note that not signature check is performed.
  14757. *
  14758. * @param child the certificate to check.
  14759. *
  14760. * @return true if this certificate's subject matches the passed
  14761. * certificate's issuer.
  14762. */
  14763. cert.issued = function(child) {
  14764. return child.isIssuer(cert);
  14765. };
  14766. /**
  14767. * Generates the subjectKeyIdentifier for this certificate as byte buffer.
  14768. *
  14769. * @return the subjectKeyIdentifier for this certificate as byte buffer.
  14770. */
  14771. cert.generateSubjectKeyIdentifier = function() {
  14772. /* See: 4.2.1.2 section of the the RFC3280, keyIdentifier is either:
  14773. (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
  14774. value of the BIT STRING subjectPublicKey (excluding the tag,
  14775. length, and number of unused bits).
  14776. (2) The keyIdentifier is composed of a four bit type field with
  14777. the value 0100 followed by the least significant 60 bits of the
  14778. SHA-1 hash of the value of the BIT STRING subjectPublicKey
  14779. (excluding the tag, length, and number of unused bit string bits).
  14780. */
  14781. // skipping the tag, length, and number of unused bits is the same
  14782. // as just using the RSAPublicKey (for RSA keys, which are the
  14783. // only ones supported)
  14784. return pki$2.getPublicKeyFingerprint(cert.publicKey, {type: 'RSAPublicKey'});
  14785. };
  14786. /**
  14787. * Verifies the subjectKeyIdentifier extension value for this certificate
  14788. * against its public key. If no extension is found, false will be
  14789. * returned.
  14790. *
  14791. * @return true if verified, false if not.
  14792. */
  14793. cert.verifySubjectKeyIdentifier = function() {
  14794. var oid = oids['subjectKeyIdentifier'];
  14795. for(var i = 0; i < cert.extensions.length; ++i) {
  14796. var ext = cert.extensions[i];
  14797. if(ext.id === oid) {
  14798. var ski = cert.generateSubjectKeyIdentifier().getBytes();
  14799. return (forge$2.util.hexToBytes(ext.subjectKeyIdentifier) === ski);
  14800. }
  14801. }
  14802. return false;
  14803. };
  14804. return cert;
  14805. };
  14806. /**
  14807. * Converts an X.509v3 RSA certificate from an ASN.1 object.
  14808. *
  14809. * Note: If the certificate is to be verified then compute hash should
  14810. * be set to true. There is currently no implementation for converting
  14811. * a certificate back to ASN.1 so the TBSCertificate part of the ASN.1
  14812. * object needs to be scanned before the cert object is created.
  14813. *
  14814. * @param obj the asn1 representation of an X.509v3 RSA certificate.
  14815. * @param computeHash true to compute the hash for verification.
  14816. *
  14817. * @return the certificate.
  14818. */
  14819. pki$2.certificateFromAsn1 = function(obj, computeHash) {
  14820. // validate certificate and capture data
  14821. var capture = {};
  14822. var errors = [];
  14823. if(!asn1$2.validate(obj, x509CertificateValidator, capture, errors)) {
  14824. var error = new Error('Cannot read X.509 certificate. ' +
  14825. 'ASN.1 object is not an X509v3 Certificate.');
  14826. error.errors = errors;
  14827. throw error;
  14828. }
  14829. // get oid
  14830. var oid = asn1$2.derToOid(capture.publicKeyOid);
  14831. if(oid !== pki$2.oids.rsaEncryption) {
  14832. throw new Error('Cannot read public key. OID is not RSA.');
  14833. }
  14834. // create certificate
  14835. var cert = pki$2.createCertificate();
  14836. cert.version = capture.certVersion ?
  14837. capture.certVersion.charCodeAt(0) : 0;
  14838. var serial = forge$2.util.createBuffer(capture.certSerialNumber);
  14839. cert.serialNumber = serial.toHex();
  14840. cert.signatureOid = forge$2.asn1.derToOid(capture.certSignatureOid);
  14841. cert.signatureParameters = _readSignatureParameters(
  14842. cert.signatureOid, capture.certSignatureParams, true);
  14843. cert.siginfo.algorithmOid = forge$2.asn1.derToOid(capture.certinfoSignatureOid);
  14844. cert.siginfo.parameters = _readSignatureParameters(cert.siginfo.algorithmOid,
  14845. capture.certinfoSignatureParams, false);
  14846. cert.signature = capture.certSignature;
  14847. var validity = [];
  14848. if(capture.certValidity1UTCTime !== undefined) {
  14849. validity.push(asn1$2.utcTimeToDate(capture.certValidity1UTCTime));
  14850. }
  14851. if(capture.certValidity2GeneralizedTime !== undefined) {
  14852. validity.push(asn1$2.generalizedTimeToDate(
  14853. capture.certValidity2GeneralizedTime));
  14854. }
  14855. if(capture.certValidity3UTCTime !== undefined) {
  14856. validity.push(asn1$2.utcTimeToDate(capture.certValidity3UTCTime));
  14857. }
  14858. if(capture.certValidity4GeneralizedTime !== undefined) {
  14859. validity.push(asn1$2.generalizedTimeToDate(
  14860. capture.certValidity4GeneralizedTime));
  14861. }
  14862. if(validity.length > 2) {
  14863. throw new Error('Cannot read notBefore/notAfter validity times; more ' +
  14864. 'than two times were provided in the certificate.');
  14865. }
  14866. if(validity.length < 2) {
  14867. throw new Error('Cannot read notBefore/notAfter validity times; they ' +
  14868. 'were not provided as either UTCTime or GeneralizedTime.');
  14869. }
  14870. cert.validity.notBefore = validity[0];
  14871. cert.validity.notAfter = validity[1];
  14872. // keep TBSCertificate to preserve signature when exporting
  14873. cert.tbsCertificate = capture.tbsCertificate;
  14874. if(computeHash) {
  14875. // create digest for OID signature type
  14876. cert.md = _createSignatureDigest({
  14877. signatureOid: cert.signatureOid,
  14878. type: 'certificate'
  14879. });
  14880. // produce DER formatted TBSCertificate and digest it
  14881. var bytes = asn1$2.toDer(cert.tbsCertificate);
  14882. cert.md.update(bytes.getBytes());
  14883. }
  14884. // handle issuer, build issuer message digest
  14885. var imd = forge$2.md.sha1.create();
  14886. var ibytes = asn1$2.toDer(capture.certIssuer);
  14887. imd.update(ibytes.getBytes());
  14888. cert.issuer.getField = function(sn) {
  14889. return _getAttribute(cert.issuer, sn);
  14890. };
  14891. cert.issuer.addField = function(attr) {
  14892. _fillMissingFields([attr]);
  14893. cert.issuer.attributes.push(attr);
  14894. };
  14895. cert.issuer.attributes = pki$2.RDNAttributesAsArray(capture.certIssuer);
  14896. if(capture.certIssuerUniqueId) {
  14897. cert.issuer.uniqueId = capture.certIssuerUniqueId;
  14898. }
  14899. cert.issuer.hash = imd.digest().toHex();
  14900. // handle subject, build subject message digest
  14901. var smd = forge$2.md.sha1.create();
  14902. var sbytes = asn1$2.toDer(capture.certSubject);
  14903. smd.update(sbytes.getBytes());
  14904. cert.subject.getField = function(sn) {
  14905. return _getAttribute(cert.subject, sn);
  14906. };
  14907. cert.subject.addField = function(attr) {
  14908. _fillMissingFields([attr]);
  14909. cert.subject.attributes.push(attr);
  14910. };
  14911. cert.subject.attributes = pki$2.RDNAttributesAsArray(capture.certSubject);
  14912. if(capture.certSubjectUniqueId) {
  14913. cert.subject.uniqueId = capture.certSubjectUniqueId;
  14914. }
  14915. cert.subject.hash = smd.digest().toHex();
  14916. // handle extensions
  14917. if(capture.certExtensions) {
  14918. cert.extensions = pki$2.certificateExtensionsFromAsn1(capture.certExtensions);
  14919. } else {
  14920. cert.extensions = [];
  14921. }
  14922. // convert RSA public key from ASN.1
  14923. cert.publicKey = pki$2.publicKeyFromAsn1(capture.subjectPublicKeyInfo);
  14924. return cert;
  14925. };
  14926. /**
  14927. * Converts an ASN.1 extensions object (with extension sequences as its
  14928. * values) into an array of extension objects with types and values.
  14929. *
  14930. * Supported extensions:
  14931. *
  14932. * id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 }
  14933. * KeyUsage ::= BIT STRING {
  14934. * digitalSignature (0),
  14935. * nonRepudiation (1),
  14936. * keyEncipherment (2),
  14937. * dataEncipherment (3),
  14938. * keyAgreement (4),
  14939. * keyCertSign (5),
  14940. * cRLSign (6),
  14941. * encipherOnly (7),
  14942. * decipherOnly (8)
  14943. * }
  14944. *
  14945. * id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 }
  14946. * BasicConstraints ::= SEQUENCE {
  14947. * cA BOOLEAN DEFAULT FALSE,
  14948. * pathLenConstraint INTEGER (0..MAX) OPTIONAL
  14949. * }
  14950. *
  14951. * subjectAltName EXTENSION ::= {
  14952. * SYNTAX GeneralNames
  14953. * IDENTIFIED BY id-ce-subjectAltName
  14954. * }
  14955. *
  14956. * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
  14957. *
  14958. * GeneralName ::= CHOICE {
  14959. * otherName [0] INSTANCE OF OTHER-NAME,
  14960. * rfc822Name [1] IA5String,
  14961. * dNSName [2] IA5String,
  14962. * x400Address [3] ORAddress,
  14963. * directoryName [4] Name,
  14964. * ediPartyName [5] EDIPartyName,
  14965. * uniformResourceIdentifier [6] IA5String,
  14966. * IPAddress [7] OCTET STRING,
  14967. * registeredID [8] OBJECT IDENTIFIER
  14968. * }
  14969. *
  14970. * OTHER-NAME ::= TYPE-IDENTIFIER
  14971. *
  14972. * EDIPartyName ::= SEQUENCE {
  14973. * nameAssigner [0] DirectoryString {ub-name} OPTIONAL,
  14974. * partyName [1] DirectoryString {ub-name}
  14975. * }
  14976. *
  14977. * @param exts the extensions ASN.1 with extension sequences to parse.
  14978. *
  14979. * @return the array.
  14980. */
  14981. pki$2.certificateExtensionsFromAsn1 = function(exts) {
  14982. var rval = [];
  14983. for(var i = 0; i < exts.value.length; ++i) {
  14984. // get extension sequence
  14985. var extseq = exts.value[i];
  14986. for(var ei = 0; ei < extseq.value.length; ++ei) {
  14987. rval.push(pki$2.certificateExtensionFromAsn1(extseq.value[ei]));
  14988. }
  14989. }
  14990. return rval;
  14991. };
  14992. /**
  14993. * Parses a single certificate extension from ASN.1.
  14994. *
  14995. * @param ext the extension in ASN.1 format.
  14996. *
  14997. * @return the parsed extension as an object.
  14998. */
  14999. pki$2.certificateExtensionFromAsn1 = function(ext) {
  15000. // an extension has:
  15001. // [0] extnID OBJECT IDENTIFIER
  15002. // [1] critical BOOLEAN DEFAULT FALSE
  15003. // [2] extnValue OCTET STRING
  15004. var e = {};
  15005. e.id = asn1$2.derToOid(ext.value[0].value);
  15006. e.critical = false;
  15007. if(ext.value[1].type === asn1$2.Type.BOOLEAN) {
  15008. e.critical = (ext.value[1].value.charCodeAt(0) !== 0x00);
  15009. e.value = ext.value[2].value;
  15010. } else {
  15011. e.value = ext.value[1].value;
  15012. }
  15013. // if the oid is known, get its name
  15014. if(e.id in oids) {
  15015. e.name = oids[e.id];
  15016. // handle key usage
  15017. if(e.name === 'keyUsage') {
  15018. // get value as BIT STRING
  15019. var ev = asn1$2.fromDer(e.value);
  15020. var b2 = 0x00;
  15021. var b3 = 0x00;
  15022. if(ev.value.length > 1) {
  15023. // skip first byte, just indicates unused bits which
  15024. // will be padded with 0s anyway
  15025. // get bytes with flag bits
  15026. b2 = ev.value.charCodeAt(1);
  15027. b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0;
  15028. }
  15029. // set flags
  15030. e.digitalSignature = (b2 & 0x80) === 0x80;
  15031. e.nonRepudiation = (b2 & 0x40) === 0x40;
  15032. e.keyEncipherment = (b2 & 0x20) === 0x20;
  15033. e.dataEncipherment = (b2 & 0x10) === 0x10;
  15034. e.keyAgreement = (b2 & 0x08) === 0x08;
  15035. e.keyCertSign = (b2 & 0x04) === 0x04;
  15036. e.cRLSign = (b2 & 0x02) === 0x02;
  15037. e.encipherOnly = (b2 & 0x01) === 0x01;
  15038. e.decipherOnly = (b3 & 0x80) === 0x80;
  15039. } else if(e.name === 'basicConstraints') {
  15040. // handle basic constraints
  15041. // get value as SEQUENCE
  15042. var ev = asn1$2.fromDer(e.value);
  15043. // get cA BOOLEAN flag (defaults to false)
  15044. if(ev.value.length > 0 && ev.value[0].type === asn1$2.Type.BOOLEAN) {
  15045. e.cA = (ev.value[0].value.charCodeAt(0) !== 0x00);
  15046. } else {
  15047. e.cA = false;
  15048. }
  15049. // get path length constraint
  15050. var value = null;
  15051. if(ev.value.length > 0 && ev.value[0].type === asn1$2.Type.INTEGER) {
  15052. value = ev.value[0].value;
  15053. } else if(ev.value.length > 1) {
  15054. value = ev.value[1].value;
  15055. }
  15056. if(value !== null) {
  15057. e.pathLenConstraint = asn1$2.derToInteger(value);
  15058. }
  15059. } else if(e.name === 'extKeyUsage') {
  15060. // handle extKeyUsage
  15061. // value is a SEQUENCE of OIDs
  15062. var ev = asn1$2.fromDer(e.value);
  15063. for(var vi = 0; vi < ev.value.length; ++vi) {
  15064. var oid = asn1$2.derToOid(ev.value[vi].value);
  15065. if(oid in oids) {
  15066. e[oids[oid]] = true;
  15067. } else {
  15068. e[oid] = true;
  15069. }
  15070. }
  15071. } else if(e.name === 'nsCertType') {
  15072. // handle nsCertType
  15073. // get value as BIT STRING
  15074. var ev = asn1$2.fromDer(e.value);
  15075. var b2 = 0x00;
  15076. if(ev.value.length > 1) {
  15077. // skip first byte, just indicates unused bits which
  15078. // will be padded with 0s anyway
  15079. // get bytes with flag bits
  15080. b2 = ev.value.charCodeAt(1);
  15081. }
  15082. // set flags
  15083. e.client = (b2 & 0x80) === 0x80;
  15084. e.server = (b2 & 0x40) === 0x40;
  15085. e.email = (b2 & 0x20) === 0x20;
  15086. e.objsign = (b2 & 0x10) === 0x10;
  15087. e.reserved = (b2 & 0x08) === 0x08;
  15088. e.sslCA = (b2 & 0x04) === 0x04;
  15089. e.emailCA = (b2 & 0x02) === 0x02;
  15090. e.objCA = (b2 & 0x01) === 0x01;
  15091. } else if(
  15092. e.name === 'subjectAltName' ||
  15093. e.name === 'issuerAltName') {
  15094. // handle subjectAltName/issuerAltName
  15095. e.altNames = [];
  15096. // ev is a SYNTAX SEQUENCE
  15097. var gn;
  15098. var ev = asn1$2.fromDer(e.value);
  15099. for(var n = 0; n < ev.value.length; ++n) {
  15100. // get GeneralName
  15101. gn = ev.value[n];
  15102. var altName = {
  15103. type: gn.type,
  15104. value: gn.value
  15105. };
  15106. e.altNames.push(altName);
  15107. // Note: Support for types 1,2,6,7,8
  15108. switch(gn.type) {
  15109. // rfc822Name
  15110. case 1:
  15111. // dNSName
  15112. case 2:
  15113. // uniformResourceIdentifier (URI)
  15114. case 6:
  15115. break;
  15116. // IPAddress
  15117. case 7:
  15118. // convert to IPv4/IPv6 string representation
  15119. altName.ip = forge$2.util.bytesToIP(gn.value);
  15120. break;
  15121. // registeredID
  15122. case 8:
  15123. altName.oid = asn1$2.derToOid(gn.value);
  15124. break;
  15125. // unsupported
  15126. }
  15127. }
  15128. } else if(e.name === 'subjectKeyIdentifier') {
  15129. // value is an OCTETSTRING w/the hash of the key-type specific
  15130. // public key structure (eg: RSAPublicKey)
  15131. var ev = asn1$2.fromDer(e.value);
  15132. e.subjectKeyIdentifier = forge$2.util.bytesToHex(ev.value);
  15133. }
  15134. }
  15135. return e;
  15136. };
  15137. /**
  15138. * Converts a PKCS#10 certification request (CSR) from an ASN.1 object.
  15139. *
  15140. * Note: If the certification request is to be verified then compute hash
  15141. * should be set to true. There is currently no implementation for converting
  15142. * a certificate back to ASN.1 so the CertificationRequestInfo part of the
  15143. * ASN.1 object needs to be scanned before the csr object is created.
  15144. *
  15145. * @param obj the asn1 representation of a PKCS#10 certification request (CSR).
  15146. * @param computeHash true to compute the hash for verification.
  15147. *
  15148. * @return the certification request (CSR).
  15149. */
  15150. pki$2.certificationRequestFromAsn1 = function(obj, computeHash) {
  15151. // validate certification request and capture data
  15152. var capture = {};
  15153. var errors = [];
  15154. if(!asn1$2.validate(obj, certificationRequestValidator, capture, errors)) {
  15155. var error = new Error('Cannot read PKCS#10 certificate request. ' +
  15156. 'ASN.1 object is not a PKCS#10 CertificationRequest.');
  15157. error.errors = errors;
  15158. throw error;
  15159. }
  15160. // get oid
  15161. var oid = asn1$2.derToOid(capture.publicKeyOid);
  15162. if(oid !== pki$2.oids.rsaEncryption) {
  15163. throw new Error('Cannot read public key. OID is not RSA.');
  15164. }
  15165. // create certification request
  15166. var csr = pki$2.createCertificationRequest();
  15167. csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0;
  15168. csr.signatureOid = forge$2.asn1.derToOid(capture.csrSignatureOid);
  15169. csr.signatureParameters = _readSignatureParameters(
  15170. csr.signatureOid, capture.csrSignatureParams, true);
  15171. csr.siginfo.algorithmOid = forge$2.asn1.derToOid(capture.csrSignatureOid);
  15172. csr.siginfo.parameters = _readSignatureParameters(
  15173. csr.siginfo.algorithmOid, capture.csrSignatureParams, false);
  15174. csr.signature = capture.csrSignature;
  15175. // keep CertificationRequestInfo to preserve signature when exporting
  15176. csr.certificationRequestInfo = capture.certificationRequestInfo;
  15177. if(computeHash) {
  15178. // create digest for OID signature type
  15179. csr.md = _createSignatureDigest({
  15180. signatureOid: csr.signatureOid,
  15181. type: 'certification request'
  15182. });
  15183. // produce DER formatted CertificationRequestInfo and digest it
  15184. var bytes = asn1$2.toDer(csr.certificationRequestInfo);
  15185. csr.md.update(bytes.getBytes());
  15186. }
  15187. // handle subject, build subject message digest
  15188. var smd = forge$2.md.sha1.create();
  15189. csr.subject.getField = function(sn) {
  15190. return _getAttribute(csr.subject, sn);
  15191. };
  15192. csr.subject.addField = function(attr) {
  15193. _fillMissingFields([attr]);
  15194. csr.subject.attributes.push(attr);
  15195. };
  15196. csr.subject.attributes = pki$2.RDNAttributesAsArray(
  15197. capture.certificationRequestInfoSubject, smd);
  15198. csr.subject.hash = smd.digest().toHex();
  15199. // convert RSA public key from ASN.1
  15200. csr.publicKey = pki$2.publicKeyFromAsn1(capture.subjectPublicKeyInfo);
  15201. // convert attributes from ASN.1
  15202. csr.getAttribute = function(sn) {
  15203. return _getAttribute(csr, sn);
  15204. };
  15205. csr.addAttribute = function(attr) {
  15206. _fillMissingFields([attr]);
  15207. csr.attributes.push(attr);
  15208. };
  15209. csr.attributes = pki$2.CRIAttributesAsArray(
  15210. capture.certificationRequestInfoAttributes || []);
  15211. return csr;
  15212. };
  15213. /**
  15214. * Creates an empty certification request (a CSR or certificate signing
  15215. * request). Once created, its public key and attributes can be set and then
  15216. * it can be signed.
  15217. *
  15218. * @return the empty certification request.
  15219. */
  15220. pki$2.createCertificationRequest = function() {
  15221. var csr = {};
  15222. csr.version = 0x00;
  15223. csr.signatureOid = null;
  15224. csr.signature = null;
  15225. csr.siginfo = {};
  15226. csr.siginfo.algorithmOid = null;
  15227. csr.subject = {};
  15228. csr.subject.getField = function(sn) {
  15229. return _getAttribute(csr.subject, sn);
  15230. };
  15231. csr.subject.addField = function(attr) {
  15232. _fillMissingFields([attr]);
  15233. csr.subject.attributes.push(attr);
  15234. };
  15235. csr.subject.attributes = [];
  15236. csr.subject.hash = null;
  15237. csr.publicKey = null;
  15238. csr.attributes = [];
  15239. csr.getAttribute = function(sn) {
  15240. return _getAttribute(csr, sn);
  15241. };
  15242. csr.addAttribute = function(attr) {
  15243. _fillMissingFields([attr]);
  15244. csr.attributes.push(attr);
  15245. };
  15246. csr.md = null;
  15247. /**
  15248. * Sets the subject of this certification request.
  15249. *
  15250. * @param attrs the array of subject attributes to use.
  15251. */
  15252. csr.setSubject = function(attrs) {
  15253. // set new attributes
  15254. _fillMissingFields(attrs);
  15255. csr.subject.attributes = attrs;
  15256. csr.subject.hash = null;
  15257. };
  15258. /**
  15259. * Sets the attributes of this certification request.
  15260. *
  15261. * @param attrs the array of attributes to use.
  15262. */
  15263. csr.setAttributes = function(attrs) {
  15264. // set new attributes
  15265. _fillMissingFields(attrs);
  15266. csr.attributes = attrs;
  15267. };
  15268. /**
  15269. * Signs this certification request using the given private key.
  15270. *
  15271. * @param key the private key to sign with.
  15272. * @param md the message digest object to use (defaults to forge.md.sha1).
  15273. */
  15274. csr.sign = function(key, md) {
  15275. // TODO: get signature OID from private key
  15276. csr.md = md || forge$2.md.sha1.create();
  15277. var algorithmOid = oids[csr.md.algorithm + 'WithRSAEncryption'];
  15278. if(!algorithmOid) {
  15279. var error = new Error('Could not compute certification request digest. ' +
  15280. 'Unknown message digest algorithm OID.');
  15281. error.algorithm = csr.md.algorithm;
  15282. throw error;
  15283. }
  15284. csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid;
  15285. // get CertificationRequestInfo, convert to DER
  15286. csr.certificationRequestInfo = pki$2.getCertificationRequestInfo(csr);
  15287. var bytes = asn1$2.toDer(csr.certificationRequestInfo);
  15288. // digest and sign
  15289. csr.md.update(bytes.getBytes());
  15290. csr.signature = key.sign(csr.md);
  15291. };
  15292. /**
  15293. * Attempts verify the signature on the passed certification request using
  15294. * its public key.
  15295. *
  15296. * A CSR that has been exported to a file in PEM format can be verified using
  15297. * OpenSSL using this command:
  15298. *
  15299. * openssl req -in <the-csr-pem-file> -verify -noout -text
  15300. *
  15301. * @return true if verified, false if not.
  15302. */
  15303. csr.verify = function() {
  15304. var rval = false;
  15305. var md = csr.md;
  15306. if(md === null) {
  15307. md = _createSignatureDigest({
  15308. signatureOid: csr.signatureOid,
  15309. type: 'certification request'
  15310. });
  15311. // produce DER formatted CertificationRequestInfo and digest it
  15312. var cri = csr.certificationRequestInfo ||
  15313. pki$2.getCertificationRequestInfo(csr);
  15314. var bytes = asn1$2.toDer(cri);
  15315. md.update(bytes.getBytes());
  15316. }
  15317. if(md !== null) {
  15318. rval = _verifySignature({
  15319. certificate: csr, md: md, signature: csr.signature
  15320. });
  15321. }
  15322. return rval;
  15323. };
  15324. return csr;
  15325. };
  15326. /**
  15327. * Converts an X.509 subject or issuer to an ASN.1 RDNSequence.
  15328. *
  15329. * @param obj the subject or issuer (distinguished name).
  15330. *
  15331. * @return the ASN.1 RDNSequence.
  15332. */
  15333. function _dnToAsn1(obj) {
  15334. // create an empty RDNSequence
  15335. var rval = asn1$2.create(
  15336. asn1$2.Class.UNIVERSAL, asn1$2.Type.SEQUENCE, true, []);
  15337. // iterate over attributes
  15338. var attr, set;
  15339. var attrs = obj.attributes;
  15340. for(var i = 0; i < attrs.length; ++i) {
  15341. attr = attrs[i];
  15342. var value = attr.value;
  15343. // reuse tag class for attribute value if available
  15344. var valueTagClass = asn1$2.Type.PRINTABLESTRING;
  15345. if('valueTagClass' in attr) {
  15346. valueTagClass = attr.valueTagClass;
  15347. if(valueTagClass === asn1$2.Type.UTF8) {
  15348. value = forge$2.util.encodeUtf8(value);
  15349. }
  15350. // FIXME: handle more encodings
  15351. }
  15352. // create a RelativeDistinguishedName set
  15353. // each value in the set is an AttributeTypeAndValue first
  15354. // containing the type (an OID) and second the value
  15355. set = asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.SET, true, [
  15356. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.SEQUENCE, true, [
  15357. // AttributeType
  15358. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.OID, false,
  15359. asn1$2.oidToDer(attr.type).getBytes()),
  15360. // AttributeValue
  15361. asn1$2.create(asn1$2.Class.UNIVERSAL, valueTagClass, false, value)
  15362. ])
  15363. ]);
  15364. rval.value.push(set);
  15365. }
  15366. return rval;
  15367. }
  15368. /**
  15369. * Fills in missing fields in attributes.
  15370. *
  15371. * @param attrs the attributes to fill missing fields in.
  15372. */
  15373. function _fillMissingFields(attrs) {
  15374. var attr;
  15375. for(var i = 0; i < attrs.length; ++i) {
  15376. attr = attrs[i];
  15377. // populate missing name
  15378. if(typeof attr.name === 'undefined') {
  15379. if(attr.type && attr.type in pki$2.oids) {
  15380. attr.name = pki$2.oids[attr.type];
  15381. } else if(attr.shortName && attr.shortName in _shortNames) {
  15382. attr.name = pki$2.oids[_shortNames[attr.shortName]];
  15383. }
  15384. }
  15385. // populate missing type (OID)
  15386. if(typeof attr.type === 'undefined') {
  15387. if(attr.name && attr.name in pki$2.oids) {
  15388. attr.type = pki$2.oids[attr.name];
  15389. } else {
  15390. var error = new Error('Attribute type not specified.');
  15391. error.attribute = attr;
  15392. throw error;
  15393. }
  15394. }
  15395. // populate missing shortname
  15396. if(typeof attr.shortName === 'undefined') {
  15397. if(attr.name && attr.name in _shortNames) {
  15398. attr.shortName = _shortNames[attr.name];
  15399. }
  15400. }
  15401. // convert extensions to value
  15402. if(attr.type === oids.extensionRequest) {
  15403. attr.valueConstructed = true;
  15404. attr.valueTagClass = asn1$2.Type.SEQUENCE;
  15405. if(!attr.value && attr.extensions) {
  15406. attr.value = [];
  15407. for(var ei = 0; ei < attr.extensions.length; ++ei) {
  15408. attr.value.push(pki$2.certificateExtensionToAsn1(
  15409. _fillMissingExtensionFields(attr.extensions[ei])));
  15410. }
  15411. }
  15412. }
  15413. if(typeof attr.value === 'undefined') {
  15414. var error = new Error('Attribute value not specified.');
  15415. error.attribute = attr;
  15416. throw error;
  15417. }
  15418. }
  15419. }
  15420. /**
  15421. * Fills in missing fields in certificate extensions.
  15422. *
  15423. * @param e the extension.
  15424. * @param [options] the options to use.
  15425. * [cert] the certificate the extensions are for.
  15426. *
  15427. * @return the extension.
  15428. */
  15429. function _fillMissingExtensionFields(e, options) {
  15430. options = options || {};
  15431. // populate missing name
  15432. if(typeof e.name === 'undefined') {
  15433. if(e.id && e.id in pki$2.oids) {
  15434. e.name = pki$2.oids[e.id];
  15435. }
  15436. }
  15437. // populate missing id
  15438. if(typeof e.id === 'undefined') {
  15439. if(e.name && e.name in pki$2.oids) {
  15440. e.id = pki$2.oids[e.name];
  15441. } else {
  15442. var error = new Error('Extension ID not specified.');
  15443. error.extension = e;
  15444. throw error;
  15445. }
  15446. }
  15447. if(typeof e.value !== 'undefined') {
  15448. return e;
  15449. }
  15450. // handle missing value:
  15451. // value is a BIT STRING
  15452. if(e.name === 'keyUsage') {
  15453. // build flags
  15454. var unused = 0;
  15455. var b2 = 0x00;
  15456. var b3 = 0x00;
  15457. if(e.digitalSignature) {
  15458. b2 |= 0x80;
  15459. unused = 7;
  15460. }
  15461. if(e.nonRepudiation) {
  15462. b2 |= 0x40;
  15463. unused = 6;
  15464. }
  15465. if(e.keyEncipherment) {
  15466. b2 |= 0x20;
  15467. unused = 5;
  15468. }
  15469. if(e.dataEncipherment) {
  15470. b2 |= 0x10;
  15471. unused = 4;
  15472. }
  15473. if(e.keyAgreement) {
  15474. b2 |= 0x08;
  15475. unused = 3;
  15476. }
  15477. if(e.keyCertSign) {
  15478. b2 |= 0x04;
  15479. unused = 2;
  15480. }
  15481. if(e.cRLSign) {
  15482. b2 |= 0x02;
  15483. unused = 1;
  15484. }
  15485. if(e.encipherOnly) {
  15486. b2 |= 0x01;
  15487. unused = 0;
  15488. }
  15489. if(e.decipherOnly) {
  15490. b3 |= 0x80;
  15491. unused = 7;
  15492. }
  15493. // create bit string
  15494. var value = String.fromCharCode(unused);
  15495. if(b3 !== 0) {
  15496. value += String.fromCharCode(b2) + String.fromCharCode(b3);
  15497. } else if(b2 !== 0) {
  15498. value += String.fromCharCode(b2);
  15499. }
  15500. e.value = asn1$2.create(
  15501. asn1$2.Class.UNIVERSAL, asn1$2.Type.BITSTRING, false, value);
  15502. } else if(e.name === 'basicConstraints') {
  15503. // basicConstraints is a SEQUENCE
  15504. e.value = asn1$2.create(
  15505. asn1$2.Class.UNIVERSAL, asn1$2.Type.SEQUENCE, true, []);
  15506. // cA BOOLEAN flag defaults to false
  15507. if(e.cA) {
  15508. e.value.value.push(asn1$2.create(
  15509. asn1$2.Class.UNIVERSAL, asn1$2.Type.BOOLEAN, false,
  15510. String.fromCharCode(0xFF)));
  15511. }
  15512. if('pathLenConstraint' in e) {
  15513. e.value.value.push(asn1$2.create(
  15514. asn1$2.Class.UNIVERSAL, asn1$2.Type.INTEGER, false,
  15515. asn1$2.integerToDer(e.pathLenConstraint).getBytes()));
  15516. }
  15517. } else if(e.name === 'extKeyUsage') {
  15518. // extKeyUsage is a SEQUENCE of OIDs
  15519. e.value = asn1$2.create(
  15520. asn1$2.Class.UNIVERSAL, asn1$2.Type.SEQUENCE, true, []);
  15521. var seq = e.value.value;
  15522. for(var key in e) {
  15523. if(e[key] !== true) {
  15524. continue;
  15525. }
  15526. // key is name in OID map
  15527. if(key in oids) {
  15528. seq.push(asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.OID,
  15529. false, asn1$2.oidToDer(oids[key]).getBytes()));
  15530. } else if(key.indexOf('.') !== -1) {
  15531. // assume key is an OID
  15532. seq.push(asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.OID,
  15533. false, asn1$2.oidToDer(key).getBytes()));
  15534. }
  15535. }
  15536. } else if(e.name === 'nsCertType') {
  15537. // nsCertType is a BIT STRING
  15538. // build flags
  15539. var unused = 0;
  15540. var b2 = 0x00;
  15541. if(e.client) {
  15542. b2 |= 0x80;
  15543. unused = 7;
  15544. }
  15545. if(e.server) {
  15546. b2 |= 0x40;
  15547. unused = 6;
  15548. }
  15549. if(e.email) {
  15550. b2 |= 0x20;
  15551. unused = 5;
  15552. }
  15553. if(e.objsign) {
  15554. b2 |= 0x10;
  15555. unused = 4;
  15556. }
  15557. if(e.reserved) {
  15558. b2 |= 0x08;
  15559. unused = 3;
  15560. }
  15561. if(e.sslCA) {
  15562. b2 |= 0x04;
  15563. unused = 2;
  15564. }
  15565. if(e.emailCA) {
  15566. b2 |= 0x02;
  15567. unused = 1;
  15568. }
  15569. if(e.objCA) {
  15570. b2 |= 0x01;
  15571. unused = 0;
  15572. }
  15573. // create bit string
  15574. var value = String.fromCharCode(unused);
  15575. if(b2 !== 0) {
  15576. value += String.fromCharCode(b2);
  15577. }
  15578. e.value = asn1$2.create(
  15579. asn1$2.Class.UNIVERSAL, asn1$2.Type.BITSTRING, false, value);
  15580. } else if(e.name === 'subjectAltName' || e.name === 'issuerAltName') {
  15581. // SYNTAX SEQUENCE
  15582. e.value = asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.SEQUENCE, true, []);
  15583. var altName;
  15584. for(var n = 0; n < e.altNames.length; ++n) {
  15585. altName = e.altNames[n];
  15586. var value = altName.value;
  15587. // handle IP
  15588. if(altName.type === 7 && altName.ip) {
  15589. value = forge$2.util.bytesFromIP(altName.ip);
  15590. if(value === null) {
  15591. var error = new Error(
  15592. 'Extension "ip" value is not a valid IPv4 or IPv6 address.');
  15593. error.extension = e;
  15594. throw error;
  15595. }
  15596. } else if(altName.type === 8) {
  15597. // handle OID
  15598. if(altName.oid) {
  15599. value = asn1$2.oidToDer(asn1$2.oidToDer(altName.oid));
  15600. } else {
  15601. // deprecated ... convert value to OID
  15602. value = asn1$2.oidToDer(value);
  15603. }
  15604. }
  15605. e.value.value.push(asn1$2.create(
  15606. asn1$2.Class.CONTEXT_SPECIFIC, altName.type, false,
  15607. value));
  15608. }
  15609. } else if(e.name === 'nsComment' && options.cert) {
  15610. // sanity check value is ASCII (req'd) and not too big
  15611. if(!(/^[\x00-\x7F]*$/.test(e.comment)) ||
  15612. (e.comment.length < 1) || (e.comment.length > 128)) {
  15613. throw new Error('Invalid "nsComment" content.');
  15614. }
  15615. // IA5STRING opaque comment
  15616. e.value = asn1$2.create(
  15617. asn1$2.Class.UNIVERSAL, asn1$2.Type.IA5STRING, false, e.comment);
  15618. } else if(e.name === 'subjectKeyIdentifier' && options.cert) {
  15619. var ski = options.cert.generateSubjectKeyIdentifier();
  15620. e.subjectKeyIdentifier = ski.toHex();
  15621. // OCTETSTRING w/digest
  15622. e.value = asn1$2.create(
  15623. asn1$2.Class.UNIVERSAL, asn1$2.Type.OCTETSTRING, false, ski.getBytes());
  15624. } else if(e.name === 'authorityKeyIdentifier' && options.cert) {
  15625. // SYNTAX SEQUENCE
  15626. e.value = asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.SEQUENCE, true, []);
  15627. var seq = e.value.value;
  15628. if(e.keyIdentifier) {
  15629. var keyIdentifier = (e.keyIdentifier === true ?
  15630. options.cert.generateSubjectKeyIdentifier().getBytes() :
  15631. e.keyIdentifier);
  15632. seq.push(
  15633. asn1$2.create(asn1$2.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier));
  15634. }
  15635. if(e.authorityCertIssuer) {
  15636. var authorityCertIssuer = [
  15637. asn1$2.create(asn1$2.Class.CONTEXT_SPECIFIC, 4, true, [
  15638. _dnToAsn1(e.authorityCertIssuer === true ?
  15639. options.cert.issuer : e.authorityCertIssuer)
  15640. ])
  15641. ];
  15642. seq.push(
  15643. asn1$2.create(asn1$2.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer));
  15644. }
  15645. if(e.serialNumber) {
  15646. var serialNumber = forge$2.util.hexToBytes(e.serialNumber === true ?
  15647. options.cert.serialNumber : e.serialNumber);
  15648. seq.push(
  15649. asn1$2.create(asn1$2.Class.CONTEXT_SPECIFIC, 2, false, serialNumber));
  15650. }
  15651. } else if(e.name === 'cRLDistributionPoints') {
  15652. e.value = asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.SEQUENCE, true, []);
  15653. var seq = e.value.value;
  15654. // Create sub SEQUENCE of DistributionPointName
  15655. var subSeq = asn1$2.create(
  15656. asn1$2.Class.UNIVERSAL, asn1$2.Type.SEQUENCE, true, []);
  15657. // Create fullName CHOICE
  15658. var fullNameGeneralNames = asn1$2.create(
  15659. asn1$2.Class.CONTEXT_SPECIFIC, 0, true, []);
  15660. var altName;
  15661. for(var n = 0; n < e.altNames.length; ++n) {
  15662. altName = e.altNames[n];
  15663. var value = altName.value;
  15664. // handle IP
  15665. if(altName.type === 7 && altName.ip) {
  15666. value = forge$2.util.bytesFromIP(altName.ip);
  15667. if(value === null) {
  15668. var error = new Error(
  15669. 'Extension "ip" value is not a valid IPv4 or IPv6 address.');
  15670. error.extension = e;
  15671. throw error;
  15672. }
  15673. } else if(altName.type === 8) {
  15674. // handle OID
  15675. if(altName.oid) {
  15676. value = asn1$2.oidToDer(asn1$2.oidToDer(altName.oid));
  15677. } else {
  15678. // deprecated ... convert value to OID
  15679. value = asn1$2.oidToDer(value);
  15680. }
  15681. }
  15682. fullNameGeneralNames.value.push(asn1$2.create(
  15683. asn1$2.Class.CONTEXT_SPECIFIC, altName.type, false,
  15684. value));
  15685. }
  15686. // Add to the parent SEQUENCE
  15687. subSeq.value.push(asn1$2.create(
  15688. asn1$2.Class.CONTEXT_SPECIFIC, 0, true, [fullNameGeneralNames]));
  15689. seq.push(subSeq);
  15690. }
  15691. // ensure value has been defined by now
  15692. if(typeof e.value === 'undefined') {
  15693. var error = new Error('Extension value not specified.');
  15694. error.extension = e;
  15695. throw error;
  15696. }
  15697. return e;
  15698. }
  15699. /**
  15700. * Convert signature parameters object to ASN.1
  15701. *
  15702. * @param {String} oid Signature algorithm OID
  15703. * @param params The signature parametrs object
  15704. * @return ASN.1 object representing signature parameters
  15705. */
  15706. function _signatureParametersToAsn1(oid, params) {
  15707. switch(oid) {
  15708. case oids['RSASSA-PSS']:
  15709. var parts = [];
  15710. if(params.hash.algorithmOid !== undefined) {
  15711. parts.push(asn1$2.create(asn1$2.Class.CONTEXT_SPECIFIC, 0, true, [
  15712. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.SEQUENCE, true, [
  15713. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.OID, false,
  15714. asn1$2.oidToDer(params.hash.algorithmOid).getBytes()),
  15715. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.NULL, false, '')
  15716. ])
  15717. ]));
  15718. }
  15719. if(params.mgf.algorithmOid !== undefined) {
  15720. parts.push(asn1$2.create(asn1$2.Class.CONTEXT_SPECIFIC, 1, true, [
  15721. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.SEQUENCE, true, [
  15722. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.OID, false,
  15723. asn1$2.oidToDer(params.mgf.algorithmOid).getBytes()),
  15724. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.SEQUENCE, true, [
  15725. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.OID, false,
  15726. asn1$2.oidToDer(params.mgf.hash.algorithmOid).getBytes()),
  15727. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.NULL, false, '')
  15728. ])
  15729. ])
  15730. ]));
  15731. }
  15732. if(params.saltLength !== undefined) {
  15733. parts.push(asn1$2.create(asn1$2.Class.CONTEXT_SPECIFIC, 2, true, [
  15734. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.INTEGER, false,
  15735. asn1$2.integerToDer(params.saltLength).getBytes())
  15736. ]));
  15737. }
  15738. return asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.SEQUENCE, true, parts);
  15739. default:
  15740. return asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.NULL, false, '');
  15741. }
  15742. }
  15743. /**
  15744. * Converts a certification request's attributes to an ASN.1 set of
  15745. * CRIAttributes.
  15746. *
  15747. * @param csr certification request.
  15748. *
  15749. * @return the ASN.1 set of CRIAttributes.
  15750. */
  15751. function _CRIAttributesToAsn1(csr) {
  15752. // create an empty context-specific container
  15753. var rval = asn1$2.create(asn1$2.Class.CONTEXT_SPECIFIC, 0, true, []);
  15754. // no attributes, return empty container
  15755. if(csr.attributes.length === 0) {
  15756. return rval;
  15757. }
  15758. // each attribute has a sequence with a type and a set of values
  15759. var attrs = csr.attributes;
  15760. for(var i = 0; i < attrs.length; ++i) {
  15761. var attr = attrs[i];
  15762. var value = attr.value;
  15763. // reuse tag class for attribute value if available
  15764. var valueTagClass = asn1$2.Type.UTF8;
  15765. if('valueTagClass' in attr) {
  15766. valueTagClass = attr.valueTagClass;
  15767. }
  15768. if(valueTagClass === asn1$2.Type.UTF8) {
  15769. value = forge$2.util.encodeUtf8(value);
  15770. }
  15771. var valueConstructed = false;
  15772. if('valueConstructed' in attr) {
  15773. valueConstructed = attr.valueConstructed;
  15774. }
  15775. // FIXME: handle more encodings
  15776. // create a RelativeDistinguishedName set
  15777. // each value in the set is an AttributeTypeAndValue first
  15778. // containing the type (an OID) and second the value
  15779. var seq = asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.SEQUENCE, true, [
  15780. // AttributeType
  15781. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.OID, false,
  15782. asn1$2.oidToDer(attr.type).getBytes()),
  15783. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.SET, true, [
  15784. // AttributeValue
  15785. asn1$2.create(
  15786. asn1$2.Class.UNIVERSAL, valueTagClass, valueConstructed, value)
  15787. ])
  15788. ]);
  15789. rval.value.push(seq);
  15790. }
  15791. return rval;
  15792. }
  15793. var jan_1_1950 = new Date('1950-01-01T00:00:00Z');
  15794. var jan_1_2050 = new Date('2050-01-01T00:00:00Z');
  15795. /**
  15796. * Converts a Date object to ASN.1
  15797. * Handles the different format before and after 1st January 2050
  15798. *
  15799. * @param date date object.
  15800. *
  15801. * @return the ASN.1 object representing the date.
  15802. */
  15803. function _dateToAsn1(date) {
  15804. if(date >= jan_1_1950 && date < jan_1_2050) {
  15805. return asn1$2.create(
  15806. asn1$2.Class.UNIVERSAL, asn1$2.Type.UTCTIME, false,
  15807. asn1$2.dateToUtcTime(date));
  15808. } else {
  15809. return asn1$2.create(
  15810. asn1$2.Class.UNIVERSAL, asn1$2.Type.GENERALIZEDTIME, false,
  15811. asn1$2.dateToGeneralizedTime(date));
  15812. }
  15813. }
  15814. /**
  15815. * Gets the ASN.1 TBSCertificate part of an X.509v3 certificate.
  15816. *
  15817. * @param cert the certificate.
  15818. *
  15819. * @return the asn1 TBSCertificate.
  15820. */
  15821. pki$2.getTBSCertificate = function(cert) {
  15822. // TBSCertificate
  15823. var notBefore = _dateToAsn1(cert.validity.notBefore);
  15824. var notAfter = _dateToAsn1(cert.validity.notAfter);
  15825. var tbs = asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.SEQUENCE, true, [
  15826. // version
  15827. asn1$2.create(asn1$2.Class.CONTEXT_SPECIFIC, 0, true, [
  15828. // integer
  15829. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.INTEGER, false,
  15830. asn1$2.integerToDer(cert.version).getBytes())
  15831. ]),
  15832. // serialNumber
  15833. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.INTEGER, false,
  15834. forge$2.util.hexToBytes(cert.serialNumber)),
  15835. // signature
  15836. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.SEQUENCE, true, [
  15837. // algorithm
  15838. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.OID, false,
  15839. asn1$2.oidToDer(cert.siginfo.algorithmOid).getBytes()),
  15840. // parameters
  15841. _signatureParametersToAsn1(
  15842. cert.siginfo.algorithmOid, cert.siginfo.parameters)
  15843. ]),
  15844. // issuer
  15845. _dnToAsn1(cert.issuer),
  15846. // validity
  15847. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.SEQUENCE, true, [
  15848. notBefore,
  15849. notAfter
  15850. ]),
  15851. // subject
  15852. _dnToAsn1(cert.subject),
  15853. // SubjectPublicKeyInfo
  15854. pki$2.publicKeyToAsn1(cert.publicKey)
  15855. ]);
  15856. if(cert.issuer.uniqueId) {
  15857. // issuerUniqueID (optional)
  15858. tbs.value.push(
  15859. asn1$2.create(asn1$2.Class.CONTEXT_SPECIFIC, 1, true, [
  15860. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.BITSTRING, false,
  15861. // TODO: support arbitrary bit length ids
  15862. String.fromCharCode(0x00) +
  15863. cert.issuer.uniqueId
  15864. )
  15865. ])
  15866. );
  15867. }
  15868. if(cert.subject.uniqueId) {
  15869. // subjectUniqueID (optional)
  15870. tbs.value.push(
  15871. asn1$2.create(asn1$2.Class.CONTEXT_SPECIFIC, 2, true, [
  15872. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.BITSTRING, false,
  15873. // TODO: support arbitrary bit length ids
  15874. String.fromCharCode(0x00) +
  15875. cert.subject.uniqueId
  15876. )
  15877. ])
  15878. );
  15879. }
  15880. if(cert.extensions.length > 0) {
  15881. // extensions (optional)
  15882. tbs.value.push(pki$2.certificateExtensionsToAsn1(cert.extensions));
  15883. }
  15884. return tbs;
  15885. };
  15886. /**
  15887. * Gets the ASN.1 CertificationRequestInfo part of a
  15888. * PKCS#10 CertificationRequest.
  15889. *
  15890. * @param csr the certification request.
  15891. *
  15892. * @return the asn1 CertificationRequestInfo.
  15893. */
  15894. pki$2.getCertificationRequestInfo = function(csr) {
  15895. // CertificationRequestInfo
  15896. var cri = asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.SEQUENCE, true, [
  15897. // version
  15898. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.INTEGER, false,
  15899. asn1$2.integerToDer(csr.version).getBytes()),
  15900. // subject
  15901. _dnToAsn1(csr.subject),
  15902. // SubjectPublicKeyInfo
  15903. pki$2.publicKeyToAsn1(csr.publicKey),
  15904. // attributes
  15905. _CRIAttributesToAsn1(csr)
  15906. ]);
  15907. return cri;
  15908. };
  15909. /**
  15910. * Converts a DistinguishedName (subject or issuer) to an ASN.1 object.
  15911. *
  15912. * @param dn the DistinguishedName.
  15913. *
  15914. * @return the asn1 representation of a DistinguishedName.
  15915. */
  15916. pki$2.distinguishedNameToAsn1 = function(dn) {
  15917. return _dnToAsn1(dn);
  15918. };
  15919. /**
  15920. * Converts an X.509v3 RSA certificate to an ASN.1 object.
  15921. *
  15922. * @param cert the certificate.
  15923. *
  15924. * @return the asn1 representation of an X.509v3 RSA certificate.
  15925. */
  15926. pki$2.certificateToAsn1 = function(cert) {
  15927. // prefer cached TBSCertificate over generating one
  15928. var tbsCertificate = cert.tbsCertificate || pki$2.getTBSCertificate(cert);
  15929. // Certificate
  15930. return asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.SEQUENCE, true, [
  15931. // TBSCertificate
  15932. tbsCertificate,
  15933. // AlgorithmIdentifier (signature algorithm)
  15934. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.SEQUENCE, true, [
  15935. // algorithm
  15936. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.OID, false,
  15937. asn1$2.oidToDer(cert.signatureOid).getBytes()),
  15938. // parameters
  15939. _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters)
  15940. ]),
  15941. // SignatureValue
  15942. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.BITSTRING, false,
  15943. String.fromCharCode(0x00) + cert.signature)
  15944. ]);
  15945. };
  15946. /**
  15947. * Converts X.509v3 certificate extensions to ASN.1.
  15948. *
  15949. * @param exts the extensions to convert.
  15950. *
  15951. * @return the extensions in ASN.1 format.
  15952. */
  15953. pki$2.certificateExtensionsToAsn1 = function(exts) {
  15954. // create top-level extension container
  15955. var rval = asn1$2.create(asn1$2.Class.CONTEXT_SPECIFIC, 3, true, []);
  15956. // create extension sequence (stores a sequence for each extension)
  15957. var seq = asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.SEQUENCE, true, []);
  15958. rval.value.push(seq);
  15959. for(var i = 0; i < exts.length; ++i) {
  15960. seq.value.push(pki$2.certificateExtensionToAsn1(exts[i]));
  15961. }
  15962. return rval;
  15963. };
  15964. /**
  15965. * Converts a single certificate extension to ASN.1.
  15966. *
  15967. * @param ext the extension to convert.
  15968. *
  15969. * @return the extension in ASN.1 format.
  15970. */
  15971. pki$2.certificateExtensionToAsn1 = function(ext) {
  15972. // create a sequence for each extension
  15973. var extseq = asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.SEQUENCE, true, []);
  15974. // extnID (OID)
  15975. extseq.value.push(asn1$2.create(
  15976. asn1$2.Class.UNIVERSAL, asn1$2.Type.OID, false,
  15977. asn1$2.oidToDer(ext.id).getBytes()));
  15978. // critical defaults to false
  15979. if(ext.critical) {
  15980. // critical BOOLEAN DEFAULT FALSE
  15981. extseq.value.push(asn1$2.create(
  15982. asn1$2.Class.UNIVERSAL, asn1$2.Type.BOOLEAN, false,
  15983. String.fromCharCode(0xFF)));
  15984. }
  15985. var value = ext.value;
  15986. if(typeof ext.value !== 'string') {
  15987. // value is asn.1
  15988. value = asn1$2.toDer(value).getBytes();
  15989. }
  15990. // extnValue (OCTET STRING)
  15991. extseq.value.push(asn1$2.create(
  15992. asn1$2.Class.UNIVERSAL, asn1$2.Type.OCTETSTRING, false, value));
  15993. return extseq;
  15994. };
  15995. /**
  15996. * Converts a PKCS#10 certification request to an ASN.1 object.
  15997. *
  15998. * @param csr the certification request.
  15999. *
  16000. * @return the asn1 representation of a certification request.
  16001. */
  16002. pki$2.certificationRequestToAsn1 = function(csr) {
  16003. // prefer cached CertificationRequestInfo over generating one
  16004. var cri = csr.certificationRequestInfo ||
  16005. pki$2.getCertificationRequestInfo(csr);
  16006. // Certificate
  16007. return asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.SEQUENCE, true, [
  16008. // CertificationRequestInfo
  16009. cri,
  16010. // AlgorithmIdentifier (signature algorithm)
  16011. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.SEQUENCE, true, [
  16012. // algorithm
  16013. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.OID, false,
  16014. asn1$2.oidToDer(csr.signatureOid).getBytes()),
  16015. // parameters
  16016. _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters)
  16017. ]),
  16018. // signature
  16019. asn1$2.create(asn1$2.Class.UNIVERSAL, asn1$2.Type.BITSTRING, false,
  16020. String.fromCharCode(0x00) + csr.signature)
  16021. ]);
  16022. };
  16023. /**
  16024. * Creates a CA store.
  16025. *
  16026. * @param certs an optional array of certificate objects or PEM-formatted
  16027. * certificate strings to add to the CA store.
  16028. *
  16029. * @return the CA store.
  16030. */
  16031. pki$2.createCaStore = function(certs) {
  16032. // create CA store
  16033. var caStore = {
  16034. // stored certificates
  16035. certs: {}
  16036. };
  16037. /**
  16038. * Gets the certificate that issued the passed certificate or its
  16039. * 'parent'.
  16040. *
  16041. * @param cert the certificate to get the parent for.
  16042. *
  16043. * @return the parent certificate or null if none was found.
  16044. */
  16045. caStore.getIssuer = function(cert) {
  16046. var rval = getBySubject(cert.issuer);
  16047. // see if there are multiple matches
  16048. /*if(forge.util.isArray(rval)) {
  16049. // TODO: resolve multiple matches by checking
  16050. // authorityKey/subjectKey/issuerUniqueID/other identifiers, etc.
  16051. // FIXME: or alternatively do authority key mapping
  16052. // if possible (X.509v1 certs can't work?)
  16053. throw new Error('Resolving multiple issuer matches not implemented yet.');
  16054. }*/
  16055. return rval;
  16056. };
  16057. /**
  16058. * Adds a trusted certificate to the store.
  16059. *
  16060. * @param cert the certificate to add as a trusted certificate (either a
  16061. * pki.certificate object or a PEM-formatted certificate).
  16062. */
  16063. caStore.addCertificate = function(cert) {
  16064. // convert from pem if necessary
  16065. if(typeof cert === 'string') {
  16066. cert = forge$2.pki.certificateFromPem(cert);
  16067. }
  16068. ensureSubjectHasHash(cert.subject);
  16069. if(!caStore.hasCertificate(cert)) { // avoid duplicate certificates in store
  16070. if(cert.subject.hash in caStore.certs) {
  16071. // subject hash already exists, append to array
  16072. var tmp = caStore.certs[cert.subject.hash];
  16073. if(!forge$2.util.isArray(tmp)) {
  16074. tmp = [tmp];
  16075. }
  16076. tmp.push(cert);
  16077. caStore.certs[cert.subject.hash] = tmp;
  16078. } else {
  16079. caStore.certs[cert.subject.hash] = cert;
  16080. }
  16081. }
  16082. };
  16083. /**
  16084. * Checks to see if the given certificate is in the store.
  16085. *
  16086. * @param cert the certificate to check (either a pki.certificate or a
  16087. * PEM-formatted certificate).
  16088. *
  16089. * @return true if the certificate is in the store, false if not.
  16090. */
  16091. caStore.hasCertificate = function(cert) {
  16092. // convert from pem if necessary
  16093. if(typeof cert === 'string') {
  16094. cert = forge$2.pki.certificateFromPem(cert);
  16095. }
  16096. var match = getBySubject(cert.subject);
  16097. if(!match) {
  16098. return false;
  16099. }
  16100. if(!forge$2.util.isArray(match)) {
  16101. match = [match];
  16102. }
  16103. // compare DER-encoding of certificates
  16104. var der1 = asn1$2.toDer(pki$2.certificateToAsn1(cert)).getBytes();
  16105. for(var i = 0; i < match.length; ++i) {
  16106. var der2 = asn1$2.toDer(pki$2.certificateToAsn1(match[i])).getBytes();
  16107. if(der1 === der2) {
  16108. return true;
  16109. }
  16110. }
  16111. return false;
  16112. };
  16113. /**
  16114. * Lists all of the certificates kept in the store.
  16115. *
  16116. * @return an array of all of the pki.certificate objects in the store.
  16117. */
  16118. caStore.listAllCertificates = function() {
  16119. var certList = [];
  16120. for(var hash in caStore.certs) {
  16121. if(caStore.certs.hasOwnProperty(hash)) {
  16122. var value = caStore.certs[hash];
  16123. if(!forge$2.util.isArray(value)) {
  16124. certList.push(value);
  16125. } else {
  16126. for(var i = 0; i < value.length; ++i) {
  16127. certList.push(value[i]);
  16128. }
  16129. }
  16130. }
  16131. }
  16132. return certList;
  16133. };
  16134. /**
  16135. * Removes a certificate from the store.
  16136. *
  16137. * @param cert the certificate to remove (either a pki.certificate or a
  16138. * PEM-formatted certificate).
  16139. *
  16140. * @return the certificate that was removed or null if the certificate
  16141. * wasn't in store.
  16142. */
  16143. caStore.removeCertificate = function(cert) {
  16144. var result;
  16145. // convert from pem if necessary
  16146. if(typeof cert === 'string') {
  16147. cert = forge$2.pki.certificateFromPem(cert);
  16148. }
  16149. ensureSubjectHasHash(cert.subject);
  16150. if(!caStore.hasCertificate(cert)) {
  16151. return null;
  16152. }
  16153. var match = getBySubject(cert.subject);
  16154. if(!forge$2.util.isArray(match)) {
  16155. result = caStore.certs[cert.subject.hash];
  16156. delete caStore.certs[cert.subject.hash];
  16157. return result;
  16158. }
  16159. // compare DER-encoding of certificates
  16160. var der1 = asn1$2.toDer(pki$2.certificateToAsn1(cert)).getBytes();
  16161. for(var i = 0; i < match.length; ++i) {
  16162. var der2 = asn1$2.toDer(pki$2.certificateToAsn1(match[i])).getBytes();
  16163. if(der1 === der2) {
  16164. result = match[i];
  16165. match.splice(i, 1);
  16166. }
  16167. }
  16168. if(match.length === 0) {
  16169. delete caStore.certs[cert.subject.hash];
  16170. }
  16171. return result;
  16172. };
  16173. function getBySubject(subject) {
  16174. ensureSubjectHasHash(subject);
  16175. return caStore.certs[subject.hash] || null;
  16176. }
  16177. function ensureSubjectHasHash(subject) {
  16178. // produce subject hash if it doesn't exist
  16179. if(!subject.hash) {
  16180. var md = forge$2.md.sha1.create();
  16181. subject.attributes = pki$2.RDNAttributesAsArray(_dnToAsn1(subject), md);
  16182. subject.hash = md.digest().toHex();
  16183. }
  16184. }
  16185. // auto-add passed in certs
  16186. if(certs) {
  16187. // parse PEM-formatted certificates as necessary
  16188. for(var i = 0; i < certs.length; ++i) {
  16189. var cert = certs[i];
  16190. caStore.addCertificate(cert);
  16191. }
  16192. }
  16193. return caStore;
  16194. };
  16195. /**
  16196. * Certificate verification errors, based on TLS.
  16197. */
  16198. pki$2.certificateError = {
  16199. bad_certificate: 'forge.pki.BadCertificate',
  16200. unsupported_certificate: 'forge.pki.UnsupportedCertificate',
  16201. certificate_revoked: 'forge.pki.CertificateRevoked',
  16202. certificate_expired: 'forge.pki.CertificateExpired',
  16203. certificate_unknown: 'forge.pki.CertificateUnknown',
  16204. unknown_ca: 'forge.pki.UnknownCertificateAuthority'
  16205. };
  16206. /**
  16207. * Verifies a certificate chain against the given Certificate Authority store
  16208. * with an optional custom verify callback.
  16209. *
  16210. * @param caStore a certificate store to verify against.
  16211. * @param chain the certificate chain to verify, with the root or highest
  16212. * authority at the end (an array of certificates).
  16213. * @param options a callback to be called for every certificate in the chain or
  16214. * an object with:
  16215. * verify a callback to be called for every certificate in the
  16216. * chain
  16217. * validityCheckDate the date against which the certificate
  16218. * validity period should be checked. Pass null to not check
  16219. * the validity period. By default, the current date is used.
  16220. *
  16221. * The verify callback has the following signature:
  16222. *
  16223. * verified - Set to true if certificate was verified, otherwise the
  16224. * pki.certificateError for why the certificate failed.
  16225. * depth - The current index in the chain, where 0 is the end point's cert.
  16226. * certs - The certificate chain, *NOTE* an empty chain indicates an anonymous
  16227. * end point.
  16228. *
  16229. * The function returns true on success and on failure either the appropriate
  16230. * pki.certificateError or an object with 'error' set to the appropriate
  16231. * pki.certificateError and 'message' set to a custom error message.
  16232. *
  16233. * @return true if successful, error thrown if not.
  16234. */
  16235. pki$2.verifyCertificateChain = function(caStore, chain, options) {
  16236. /* From: RFC3280 - Internet X.509 Public Key Infrastructure Certificate
  16237. Section 6: Certification Path Validation
  16238. See inline parentheticals related to this particular implementation.
  16239. The primary goal of path validation is to verify the binding between
  16240. a subject distinguished name or a subject alternative name and subject
  16241. public key, as represented in the end entity certificate, based on the
  16242. public key of the trust anchor. This requires obtaining a sequence of
  16243. certificates that support that binding. That sequence should be provided
  16244. in the passed 'chain'. The trust anchor should be in the given CA
  16245. store. The 'end entity' certificate is the certificate provided by the
  16246. end point (typically a server) and is the first in the chain.
  16247. To meet this goal, the path validation process verifies, among other
  16248. things, that a prospective certification path (a sequence of n
  16249. certificates or a 'chain') satisfies the following conditions:
  16250. (a) for all x in {1, ..., n-1}, the subject of certificate x is
  16251. the issuer of certificate x+1;
  16252. (b) certificate 1 is issued by the trust anchor;
  16253. (c) certificate n is the certificate to be validated; and
  16254. (d) for all x in {1, ..., n}, the certificate was valid at the
  16255. time in question.
  16256. Note that here 'n' is index 0 in the chain and 1 is the last certificate
  16257. in the chain and it must be signed by a certificate in the connection's
  16258. CA store.
  16259. The path validation process also determines the set of certificate
  16260. policies that are valid for this path, based on the certificate policies
  16261. extension, policy mapping extension, policy constraints extension, and
  16262. inhibit any-policy extension.
  16263. Note: Policy mapping extension not supported (Not Required).
  16264. Note: If the certificate has an unsupported critical extension, then it
  16265. must be rejected.
  16266. Note: A certificate is self-issued if the DNs that appear in the subject
  16267. and issuer fields are identical and are not empty.
  16268. The path validation algorithm assumes the following seven inputs are
  16269. provided to the path processing logic. What this specific implementation
  16270. will use is provided parenthetically:
  16271. (a) a prospective certification path of length n (the 'chain')
  16272. (b) the current date/time: ('now').
  16273. (c) user-initial-policy-set: A set of certificate policy identifiers
  16274. naming the policies that are acceptable to the certificate user.
  16275. The user-initial-policy-set contains the special value any-policy
  16276. if the user is not concerned about certificate policy
  16277. (Not implemented. Any policy is accepted).
  16278. (d) trust anchor information, describing a CA that serves as a trust
  16279. anchor for the certification path. The trust anchor information
  16280. includes:
  16281. (1) the trusted issuer name,
  16282. (2) the trusted public key algorithm,
  16283. (3) the trusted public key, and
  16284. (4) optionally, the trusted public key parameters associated
  16285. with the public key.
  16286. (Trust anchors are provided via certificates in the CA store).
  16287. The trust anchor information may be provided to the path processing
  16288. procedure in the form of a self-signed certificate. The trusted anchor
  16289. information is trusted because it was delivered to the path processing
  16290. procedure by some trustworthy out-of-band procedure. If the trusted
  16291. public key algorithm requires parameters, then the parameters are
  16292. provided along with the trusted public key (No parameters used in this
  16293. implementation).
  16294. (e) initial-policy-mapping-inhibit, which indicates if policy mapping is
  16295. allowed in the certification path.
  16296. (Not implemented, no policy checking)
  16297. (f) initial-explicit-policy, which indicates if the path must be valid
  16298. for at least one of the certificate policies in the user-initial-
  16299. policy-set.
  16300. (Not implemented, no policy checking)
  16301. (g) initial-any-policy-inhibit, which indicates whether the
  16302. anyPolicy OID should be processed if it is included in a
  16303. certificate.
  16304. (Not implemented, so any policy is valid provided that it is
  16305. not marked as critical) */
  16306. /* Basic Path Processing:
  16307. For each certificate in the 'chain', the following is checked:
  16308. 1. The certificate validity period includes the current time.
  16309. 2. The certificate was signed by its parent (where the parent is either
  16310. the next in the chain or from the CA store). Allow processing to
  16311. continue to the next step if no parent is found but the certificate is
  16312. in the CA store.
  16313. 3. TODO: The certificate has not been revoked.
  16314. 4. The certificate issuer name matches the parent's subject name.
  16315. 5. TODO: If the certificate is self-issued and not the final certificate
  16316. in the chain, skip this step, otherwise verify that the subject name
  16317. is within one of the permitted subtrees of X.500 distinguished names
  16318. and that each of the alternative names in the subjectAltName extension
  16319. (critical or non-critical) is within one of the permitted subtrees for
  16320. that name type.
  16321. 6. TODO: If the certificate is self-issued and not the final certificate
  16322. in the chain, skip this step, otherwise verify that the subject name
  16323. is not within one of the excluded subtrees for X.500 distinguished
  16324. names and none of the subjectAltName extension names are excluded for
  16325. that name type.
  16326. 7. The other steps in the algorithm for basic path processing involve
  16327. handling the policy extension which is not presently supported in this
  16328. implementation. Instead, if a critical policy extension is found, the
  16329. certificate is rejected as not supported.
  16330. 8. If the certificate is not the first or if its the only certificate in
  16331. the chain (having no parent from the CA store or is self-signed) and it
  16332. has a critical key usage extension, verify that the keyCertSign bit is
  16333. set. If the key usage extension exists, verify that the basic
  16334. constraints extension exists. If the basic constraints extension exists,
  16335. verify that the cA flag is set. If pathLenConstraint is set, ensure that
  16336. the number of certificates that precede in the chain (come earlier
  16337. in the chain as implemented below), excluding the very first in the
  16338. chain (typically the end-entity one), isn't greater than the
  16339. pathLenConstraint. This constraint limits the number of intermediate
  16340. CAs that may appear below a CA before only end-entity certificates
  16341. may be issued. */
  16342. // if a verify callback is passed as the third parameter, package it within
  16343. // the options object. This is to support a legacy function signature that
  16344. // expected the verify callback as the third parameter.
  16345. if(typeof options === 'function') {
  16346. options = {verify: options};
  16347. }
  16348. options = options || {};
  16349. // copy cert chain references to another array to protect against changes
  16350. // in verify callback
  16351. chain = chain.slice(0);
  16352. var certs = chain.slice(0);
  16353. var validityCheckDate = options.validityCheckDate;
  16354. // if no validityCheckDate is specified, default to the current date. Make
  16355. // sure to maintain the value null because it indicates that the validity
  16356. // period should not be checked.
  16357. if(typeof validityCheckDate === 'undefined') {
  16358. validityCheckDate = new Date();
  16359. }
  16360. // verify each cert in the chain using its parent, where the parent
  16361. // is either the next in the chain or from the CA store
  16362. var first = true;
  16363. var error = null;
  16364. var depth = 0;
  16365. do {
  16366. var cert = chain.shift();
  16367. var parent = null;
  16368. var selfSigned = false;
  16369. if(validityCheckDate) {
  16370. // 1. check valid time
  16371. if(validityCheckDate < cert.validity.notBefore ||
  16372. validityCheckDate > cert.validity.notAfter) {
  16373. error = {
  16374. message: 'Certificate is not valid yet or has expired.',
  16375. error: pki$2.certificateError.certificate_expired,
  16376. notBefore: cert.validity.notBefore,
  16377. notAfter: cert.validity.notAfter,
  16378. // TODO: we might want to reconsider renaming 'now' to
  16379. // 'validityCheckDate' should this API be changed in the future.
  16380. now: validityCheckDate
  16381. };
  16382. }
  16383. }
  16384. // 2. verify with parent from chain or CA store
  16385. if(error === null) {
  16386. parent = chain[0] || caStore.getIssuer(cert);
  16387. if(parent === null) {
  16388. // check for self-signed cert
  16389. if(cert.isIssuer(cert)) {
  16390. selfSigned = true;
  16391. parent = cert;
  16392. }
  16393. }
  16394. if(parent) {
  16395. // FIXME: current CA store implementation might have multiple
  16396. // certificates where the issuer can't be determined from the
  16397. // certificate (happens rarely with, eg: old certificates) so normalize
  16398. // by always putting parents into an array
  16399. // TODO: there's may be an extreme degenerate case currently uncovered
  16400. // where an old intermediate certificate seems to have a matching parent
  16401. // but none of the parents actually verify ... but the intermediate
  16402. // is in the CA and it should pass this check; needs investigation
  16403. var parents = parent;
  16404. if(!forge$2.util.isArray(parents)) {
  16405. parents = [parents];
  16406. }
  16407. // try to verify with each possible parent (typically only one)
  16408. var verified = false;
  16409. while(!verified && parents.length > 0) {
  16410. parent = parents.shift();
  16411. try {
  16412. verified = parent.verify(cert);
  16413. } catch(ex) {
  16414. // failure to verify, don't care why, try next one
  16415. }
  16416. }
  16417. if(!verified) {
  16418. error = {
  16419. message: 'Certificate signature is invalid.',
  16420. error: pki$2.certificateError.bad_certificate
  16421. };
  16422. }
  16423. }
  16424. if(error === null && (!parent || selfSigned) &&
  16425. !caStore.hasCertificate(cert)) {
  16426. // no parent issuer and certificate itself is not trusted
  16427. error = {
  16428. message: 'Certificate is not trusted.',
  16429. error: pki$2.certificateError.unknown_ca
  16430. };
  16431. }
  16432. }
  16433. // TODO: 3. check revoked
  16434. // 4. check for matching issuer/subject
  16435. if(error === null && parent && !cert.isIssuer(parent)) {
  16436. // parent is not issuer
  16437. error = {
  16438. message: 'Certificate issuer is invalid.',
  16439. error: pki$2.certificateError.bad_certificate
  16440. };
  16441. }
  16442. // 5. TODO: check names with permitted names tree
  16443. // 6. TODO: check names against excluded names tree
  16444. // 7. check for unsupported critical extensions
  16445. if(error === null) {
  16446. // supported extensions
  16447. var se = {
  16448. keyUsage: true,
  16449. basicConstraints: true
  16450. };
  16451. for(var i = 0; error === null && i < cert.extensions.length; ++i) {
  16452. var ext = cert.extensions[i];
  16453. if(ext.critical && !(ext.name in se)) {
  16454. error = {
  16455. message:
  16456. 'Certificate has an unsupported critical extension.',
  16457. error: pki$2.certificateError.unsupported_certificate
  16458. };
  16459. }
  16460. }
  16461. }
  16462. // 8. check for CA if cert is not first or is the only certificate
  16463. // remaining in chain with no parent or is self-signed
  16464. if(error === null &&
  16465. (!first || (chain.length === 0 && (!parent || selfSigned)))) {
  16466. // first check keyUsage extension and then basic constraints
  16467. var bcExt = cert.getExtension('basicConstraints');
  16468. var keyUsageExt = cert.getExtension('keyUsage');
  16469. if(keyUsageExt !== null) {
  16470. // keyCertSign must be true and there must be a basic
  16471. // constraints extension
  16472. if(!keyUsageExt.keyCertSign || bcExt === null) {
  16473. // bad certificate
  16474. error = {
  16475. message:
  16476. 'Certificate keyUsage or basicConstraints conflict ' +
  16477. 'or indicate that the certificate is not a CA. ' +
  16478. 'If the certificate is the only one in the chain or ' +
  16479. 'isn\'t the first then the certificate must be a ' +
  16480. 'valid CA.',
  16481. error: pki$2.certificateError.bad_certificate
  16482. };
  16483. }
  16484. }
  16485. // basic constraints cA flag must be set
  16486. if(error === null && bcExt !== null && !bcExt.cA) {
  16487. // bad certificate
  16488. error = {
  16489. message:
  16490. 'Certificate basicConstraints indicates the certificate ' +
  16491. 'is not a CA.',
  16492. error: pki$2.certificateError.bad_certificate
  16493. };
  16494. }
  16495. // if error is not null and keyUsage is available, then we know it
  16496. // has keyCertSign and there is a basic constraints extension too,
  16497. // which means we can check pathLenConstraint (if it exists)
  16498. if(error === null && keyUsageExt !== null &&
  16499. 'pathLenConstraint' in bcExt) {
  16500. // pathLen is the maximum # of intermediate CA certs that can be
  16501. // found between the current certificate and the end-entity (depth 0)
  16502. // certificate; this number does not include the end-entity (depth 0,
  16503. // last in the chain) even if it happens to be a CA certificate itself
  16504. var pathLen = depth - 1;
  16505. if(pathLen > bcExt.pathLenConstraint) {
  16506. // pathLenConstraint violated, bad certificate
  16507. error = {
  16508. message:
  16509. 'Certificate basicConstraints pathLenConstraint violated.',
  16510. error: pki$2.certificateError.bad_certificate
  16511. };
  16512. }
  16513. }
  16514. }
  16515. // call application callback
  16516. var vfd = (error === null) ? true : error.error;
  16517. var ret = options.verify ? options.verify(vfd, depth, certs) : vfd;
  16518. if(ret === true) {
  16519. // clear any set error
  16520. error = null;
  16521. } else {
  16522. // if passed basic tests, set default message and alert
  16523. if(vfd === true) {
  16524. error = {
  16525. message: 'The application rejected the certificate.',
  16526. error: pki$2.certificateError.bad_certificate
  16527. };
  16528. }
  16529. // check for custom error info
  16530. if(ret || ret === 0) {
  16531. // set custom message and error
  16532. if(typeof ret === 'object' && !forge$2.util.isArray(ret)) {
  16533. if(ret.message) {
  16534. error.message = ret.message;
  16535. }
  16536. if(ret.error) {
  16537. error.error = ret.error;
  16538. }
  16539. } else if(typeof ret === 'string') {
  16540. // set custom error
  16541. error.error = ret;
  16542. }
  16543. }
  16544. // throw error
  16545. throw error;
  16546. }
  16547. // no longer first cert in chain
  16548. first = false;
  16549. ++depth;
  16550. } while(chain.length > 0);
  16551. return true;
  16552. };
  16553. /**
  16554. * Javascript implementation of PKCS#12.
  16555. *
  16556. * @author Dave Longley
  16557. * @author Stefan Siegl <stesie@brokenpipe.de>
  16558. *
  16559. * Copyright (c) 2010-2014 Digital Bazaar, Inc.
  16560. * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de>
  16561. *
  16562. * The ASN.1 representation of PKCS#12 is as follows
  16563. * (see ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12-tc1.pdf for details)
  16564. *
  16565. * PFX ::= SEQUENCE {
  16566. * version INTEGER {v3(3)}(v3,...),
  16567. * authSafe ContentInfo,
  16568. * macData MacData OPTIONAL
  16569. * }
  16570. *
  16571. * MacData ::= SEQUENCE {
  16572. * mac DigestInfo,
  16573. * macSalt OCTET STRING,
  16574. * iterations INTEGER DEFAULT 1
  16575. * }
  16576. * Note: The iterations default is for historical reasons and its use is
  16577. * deprecated. A higher value, like 1024, is recommended.
  16578. *
  16579. * DigestInfo is defined in PKCS#7 as follows:
  16580. *
  16581. * DigestInfo ::= SEQUENCE {
  16582. * digestAlgorithm DigestAlgorithmIdentifier,
  16583. * digest Digest
  16584. * }
  16585. *
  16586. * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
  16587. *
  16588. * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters
  16589. * for the algorithm, if any. In the case of SHA1 there is none.
  16590. *
  16591. * AlgorithmIdentifer ::= SEQUENCE {
  16592. * algorithm OBJECT IDENTIFIER,
  16593. * parameters ANY DEFINED BY algorithm OPTIONAL
  16594. * }
  16595. *
  16596. * Digest ::= OCTET STRING
  16597. *
  16598. *
  16599. * ContentInfo ::= SEQUENCE {
  16600. * contentType ContentType,
  16601. * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL
  16602. * }
  16603. *
  16604. * ContentType ::= OBJECT IDENTIFIER
  16605. *
  16606. * AuthenticatedSafe ::= SEQUENCE OF ContentInfo
  16607. * -- Data if unencrypted
  16608. * -- EncryptedData if password-encrypted
  16609. * -- EnvelopedData if public key-encrypted
  16610. *
  16611. *
  16612. * SafeContents ::= SEQUENCE OF SafeBag
  16613. *
  16614. * SafeBag ::= SEQUENCE {
  16615. * bagId BAG-TYPE.&id ({PKCS12BagSet})
  16616. * bagValue [0] EXPLICIT BAG-TYPE.&Type({PKCS12BagSet}{@bagId}),
  16617. * bagAttributes SET OF PKCS12Attribute OPTIONAL
  16618. * }
  16619. *
  16620. * PKCS12Attribute ::= SEQUENCE {
  16621. * attrId ATTRIBUTE.&id ({PKCS12AttrSet}),
  16622. * attrValues SET OF ATTRIBUTE.&Type ({PKCS12AttrSet}{@attrId})
  16623. * } -- This type is compatible with the X.500 type 'Attribute'
  16624. *
  16625. * PKCS12AttrSet ATTRIBUTE ::= {
  16626. * friendlyName | -- from PKCS #9
  16627. * localKeyId, -- from PKCS #9
  16628. * ... -- Other attributes are allowed
  16629. * }
  16630. *
  16631. * CertBag ::= SEQUENCE {
  16632. * certId BAG-TYPE.&id ({CertTypes}),
  16633. * certValue [0] EXPLICIT BAG-TYPE.&Type ({CertTypes}{@certId})
  16634. * }
  16635. *
  16636. * x509Certificate BAG-TYPE ::= {OCTET STRING IDENTIFIED BY {certTypes 1}}
  16637. * -- DER-encoded X.509 certificate stored in OCTET STRING
  16638. *
  16639. * sdsiCertificate BAG-TYPE ::= {IA5String IDENTIFIED BY {certTypes 2}}
  16640. * -- Base64-encoded SDSI certificate stored in IA5String
  16641. *
  16642. * CertTypes BAG-TYPE ::= {
  16643. * x509Certificate |
  16644. * sdsiCertificate,
  16645. * ... -- For future extensions
  16646. * }
  16647. */
  16648. var forge$1 = forge$s;
  16649. // shortcut for asn.1 & PKI API
  16650. var asn1$1 = forge$1.asn1;
  16651. var pki$1 = forge$1.pki;
  16652. // shortcut for PKCS#12 API
  16653. var p12 = forge$1.pkcs12 = forge$1.pkcs12 || {};
  16654. var contentInfoValidator = {
  16655. name: 'ContentInfo',
  16656. tagClass: asn1$1.Class.UNIVERSAL,
  16657. type: asn1$1.Type.SEQUENCE, // a ContentInfo
  16658. constructed: true,
  16659. value: [{
  16660. name: 'ContentInfo.contentType',
  16661. tagClass: asn1$1.Class.UNIVERSAL,
  16662. type: asn1$1.Type.OID,
  16663. constructed: false,
  16664. capture: 'contentType'
  16665. }, {
  16666. name: 'ContentInfo.content',
  16667. tagClass: asn1$1.Class.CONTEXT_SPECIFIC,
  16668. constructed: true,
  16669. captureAsn1: 'content'
  16670. }]
  16671. };
  16672. var pfxValidator = {
  16673. name: 'PFX',
  16674. tagClass: asn1$1.Class.UNIVERSAL,
  16675. type: asn1$1.Type.SEQUENCE,
  16676. constructed: true,
  16677. value: [{
  16678. name: 'PFX.version',
  16679. tagClass: asn1$1.Class.UNIVERSAL,
  16680. type: asn1$1.Type.INTEGER,
  16681. constructed: false,
  16682. capture: 'version'
  16683. },
  16684. contentInfoValidator, {
  16685. name: 'PFX.macData',
  16686. tagClass: asn1$1.Class.UNIVERSAL,
  16687. type: asn1$1.Type.SEQUENCE,
  16688. constructed: true,
  16689. optional: true,
  16690. captureAsn1: 'mac',
  16691. value: [{
  16692. name: 'PFX.macData.mac',
  16693. tagClass: asn1$1.Class.UNIVERSAL,
  16694. type: asn1$1.Type.SEQUENCE, // DigestInfo
  16695. constructed: true,
  16696. value: [{
  16697. name: 'PFX.macData.mac.digestAlgorithm',
  16698. tagClass: asn1$1.Class.UNIVERSAL,
  16699. type: asn1$1.Type.SEQUENCE, // DigestAlgorithmIdentifier
  16700. constructed: true,
  16701. value: [{
  16702. name: 'PFX.macData.mac.digestAlgorithm.algorithm',
  16703. tagClass: asn1$1.Class.UNIVERSAL,
  16704. type: asn1$1.Type.OID,
  16705. constructed: false,
  16706. capture: 'macAlgorithm'
  16707. }, {
  16708. name: 'PFX.macData.mac.digestAlgorithm.parameters',
  16709. tagClass: asn1$1.Class.UNIVERSAL,
  16710. captureAsn1: 'macAlgorithmParameters'
  16711. }]
  16712. }, {
  16713. name: 'PFX.macData.mac.digest',
  16714. tagClass: asn1$1.Class.UNIVERSAL,
  16715. type: asn1$1.Type.OCTETSTRING,
  16716. constructed: false,
  16717. capture: 'macDigest'
  16718. }]
  16719. }, {
  16720. name: 'PFX.macData.macSalt',
  16721. tagClass: asn1$1.Class.UNIVERSAL,
  16722. type: asn1$1.Type.OCTETSTRING,
  16723. constructed: false,
  16724. capture: 'macSalt'
  16725. }, {
  16726. name: 'PFX.macData.iterations',
  16727. tagClass: asn1$1.Class.UNIVERSAL,
  16728. type: asn1$1.Type.INTEGER,
  16729. constructed: false,
  16730. optional: true,
  16731. capture: 'macIterations'
  16732. }]
  16733. }]
  16734. };
  16735. var safeBagValidator = {
  16736. name: 'SafeBag',
  16737. tagClass: asn1$1.Class.UNIVERSAL,
  16738. type: asn1$1.Type.SEQUENCE,
  16739. constructed: true,
  16740. value: [{
  16741. name: 'SafeBag.bagId',
  16742. tagClass: asn1$1.Class.UNIVERSAL,
  16743. type: asn1$1.Type.OID,
  16744. constructed: false,
  16745. capture: 'bagId'
  16746. }, {
  16747. name: 'SafeBag.bagValue',
  16748. tagClass: asn1$1.Class.CONTEXT_SPECIFIC,
  16749. constructed: true,
  16750. captureAsn1: 'bagValue'
  16751. }, {
  16752. name: 'SafeBag.bagAttributes',
  16753. tagClass: asn1$1.Class.UNIVERSAL,
  16754. type: asn1$1.Type.SET,
  16755. constructed: true,
  16756. optional: true,
  16757. capture: 'bagAttributes'
  16758. }]
  16759. };
  16760. var attributeValidator = {
  16761. name: 'Attribute',
  16762. tagClass: asn1$1.Class.UNIVERSAL,
  16763. type: asn1$1.Type.SEQUENCE,
  16764. constructed: true,
  16765. value: [{
  16766. name: 'Attribute.attrId',
  16767. tagClass: asn1$1.Class.UNIVERSAL,
  16768. type: asn1$1.Type.OID,
  16769. constructed: false,
  16770. capture: 'oid'
  16771. }, {
  16772. name: 'Attribute.attrValues',
  16773. tagClass: asn1$1.Class.UNIVERSAL,
  16774. type: asn1$1.Type.SET,
  16775. constructed: true,
  16776. capture: 'values'
  16777. }]
  16778. };
  16779. var certBagValidator = {
  16780. name: 'CertBag',
  16781. tagClass: asn1$1.Class.UNIVERSAL,
  16782. type: asn1$1.Type.SEQUENCE,
  16783. constructed: true,
  16784. value: [{
  16785. name: 'CertBag.certId',
  16786. tagClass: asn1$1.Class.UNIVERSAL,
  16787. type: asn1$1.Type.OID,
  16788. constructed: false,
  16789. capture: 'certId'
  16790. }, {
  16791. name: 'CertBag.certValue',
  16792. tagClass: asn1$1.Class.CONTEXT_SPECIFIC,
  16793. constructed: true,
  16794. /* So far we only support X.509 certificates (which are wrapped in
  16795. an OCTET STRING, hence hard code that here). */
  16796. value: [{
  16797. name: 'CertBag.certValue[0]',
  16798. tagClass: asn1$1.Class.UNIVERSAL,
  16799. type: asn1$1.Class.OCTETSTRING,
  16800. constructed: false,
  16801. capture: 'cert'
  16802. }]
  16803. }]
  16804. };
  16805. /**
  16806. * Search SafeContents structure for bags with matching attributes.
  16807. *
  16808. * The search can optionally be narrowed by a certain bag type.
  16809. *
  16810. * @param safeContents the SafeContents structure to search in.
  16811. * @param attrName the name of the attribute to compare against.
  16812. * @param attrValue the attribute value to search for.
  16813. * @param [bagType] bag type to narrow search by.
  16814. *
  16815. * @return an array of matching bags.
  16816. */
  16817. function _getBagsByAttribute(safeContents, attrName, attrValue, bagType) {
  16818. var result = [];
  16819. for(var i = 0; i < safeContents.length; i++) {
  16820. for(var j = 0; j < safeContents[i].safeBags.length; j++) {
  16821. var bag = safeContents[i].safeBags[j];
  16822. if(bagType !== undefined && bag.type !== bagType) {
  16823. continue;
  16824. }
  16825. // only filter by bag type, no attribute specified
  16826. if(attrName === null) {
  16827. result.push(bag);
  16828. continue;
  16829. }
  16830. if(bag.attributes[attrName] !== undefined &&
  16831. bag.attributes[attrName].indexOf(attrValue) >= 0) {
  16832. result.push(bag);
  16833. }
  16834. }
  16835. }
  16836. return result;
  16837. }
  16838. /**
  16839. * Converts a PKCS#12 PFX in ASN.1 notation into a PFX object.
  16840. *
  16841. * @param obj The PKCS#12 PFX in ASN.1 notation.
  16842. * @param strict true to use strict DER decoding, false not to (default: true).
  16843. * @param {String} password Password to decrypt with (optional).
  16844. *
  16845. * @return PKCS#12 PFX object.
  16846. */
  16847. p12.pkcs12FromAsn1 = function(obj, strict, password) {
  16848. // handle args
  16849. if(typeof strict === 'string') {
  16850. password = strict;
  16851. strict = true;
  16852. } else if(strict === undefined) {
  16853. strict = true;
  16854. }
  16855. // validate PFX and capture data
  16856. var capture = {};
  16857. var errors = [];
  16858. if(!asn1$1.validate(obj, pfxValidator, capture, errors)) {
  16859. var error = new Error('Cannot read PKCS#12 PFX. ' +
  16860. 'ASN.1 object is not an PKCS#12 PFX.');
  16861. error.errors = error;
  16862. throw error;
  16863. }
  16864. var pfx = {
  16865. version: capture.version.charCodeAt(0),
  16866. safeContents: [],
  16867. /**
  16868. * Gets bags with matching attributes.
  16869. *
  16870. * @param filter the attributes to filter by:
  16871. * [localKeyId] the localKeyId to search for.
  16872. * [localKeyIdHex] the localKeyId in hex to search for.
  16873. * [friendlyName] the friendly name to search for.
  16874. * [bagType] bag type to narrow each attribute search by.
  16875. *
  16876. * @return a map of attribute type to an array of matching bags or, if no
  16877. * attribute was given but a bag type, the map key will be the
  16878. * bag type.
  16879. */
  16880. getBags: function(filter) {
  16881. var rval = {};
  16882. var localKeyId;
  16883. if('localKeyId' in filter) {
  16884. localKeyId = filter.localKeyId;
  16885. } else if('localKeyIdHex' in filter) {
  16886. localKeyId = forge$1.util.hexToBytes(filter.localKeyIdHex);
  16887. }
  16888. // filter on bagType only
  16889. if(localKeyId === undefined && !('friendlyName' in filter) &&
  16890. 'bagType' in filter) {
  16891. rval[filter.bagType] = _getBagsByAttribute(
  16892. pfx.safeContents, null, null, filter.bagType);
  16893. }
  16894. if(localKeyId !== undefined) {
  16895. rval.localKeyId = _getBagsByAttribute(
  16896. pfx.safeContents, 'localKeyId',
  16897. localKeyId, filter.bagType);
  16898. }
  16899. if('friendlyName' in filter) {
  16900. rval.friendlyName = _getBagsByAttribute(
  16901. pfx.safeContents, 'friendlyName',
  16902. filter.friendlyName, filter.bagType);
  16903. }
  16904. return rval;
  16905. },
  16906. /**
  16907. * DEPRECATED: use getBags() instead.
  16908. *
  16909. * Get bags with matching friendlyName attribute.
  16910. *
  16911. * @param friendlyName the friendly name to search for.
  16912. * @param [bagType] bag type to narrow search by.
  16913. *
  16914. * @return an array of bags with matching friendlyName attribute.
  16915. */
  16916. getBagsByFriendlyName: function(friendlyName, bagType) {
  16917. return _getBagsByAttribute(
  16918. pfx.safeContents, 'friendlyName', friendlyName, bagType);
  16919. },
  16920. /**
  16921. * DEPRECATED: use getBags() instead.
  16922. *
  16923. * Get bags with matching localKeyId attribute.
  16924. *
  16925. * @param localKeyId the localKeyId to search for.
  16926. * @param [bagType] bag type to narrow search by.
  16927. *
  16928. * @return an array of bags with matching localKeyId attribute.
  16929. */
  16930. getBagsByLocalKeyId: function(localKeyId, bagType) {
  16931. return _getBagsByAttribute(
  16932. pfx.safeContents, 'localKeyId', localKeyId, bagType);
  16933. }
  16934. };
  16935. if(capture.version.charCodeAt(0) !== 3) {
  16936. var error = new Error('PKCS#12 PFX of version other than 3 not supported.');
  16937. error.version = capture.version.charCodeAt(0);
  16938. throw error;
  16939. }
  16940. if(asn1$1.derToOid(capture.contentType) !== pki$1.oids.data) {
  16941. var error = new Error('Only PKCS#12 PFX in password integrity mode supported.');
  16942. error.oid = asn1$1.derToOid(capture.contentType);
  16943. throw error;
  16944. }
  16945. var data = capture.content.value[0];
  16946. if(data.tagClass !== asn1$1.Class.UNIVERSAL ||
  16947. data.type !== asn1$1.Type.OCTETSTRING) {
  16948. throw new Error('PKCS#12 authSafe content data is not an OCTET STRING.');
  16949. }
  16950. data = _decodePkcs7Data(data);
  16951. // check for MAC
  16952. if(capture.mac) {
  16953. var md = null;
  16954. var macKeyBytes = 0;
  16955. var macAlgorithm = asn1$1.derToOid(capture.macAlgorithm);
  16956. switch(macAlgorithm) {
  16957. case pki$1.oids.sha1:
  16958. md = forge$1.md.sha1.create();
  16959. macKeyBytes = 20;
  16960. break;
  16961. case pki$1.oids.sha256:
  16962. md = forge$1.md.sha256.create();
  16963. macKeyBytes = 32;
  16964. break;
  16965. case pki$1.oids.sha384:
  16966. md = forge$1.md.sha384.create();
  16967. macKeyBytes = 48;
  16968. break;
  16969. case pki$1.oids.sha512:
  16970. md = forge$1.md.sha512.create();
  16971. macKeyBytes = 64;
  16972. break;
  16973. case pki$1.oids.md5:
  16974. md = forge$1.md.md5.create();
  16975. macKeyBytes = 16;
  16976. break;
  16977. }
  16978. if(md === null) {
  16979. throw new Error('PKCS#12 uses unsupported MAC algorithm: ' + macAlgorithm);
  16980. }
  16981. // verify MAC (iterations default to 1)
  16982. var macSalt = new forge$1.util.ByteBuffer(capture.macSalt);
  16983. var macIterations = (('macIterations' in capture) ?
  16984. parseInt(forge$1.util.bytesToHex(capture.macIterations), 16) : 1);
  16985. var macKey = p12.generateKey(
  16986. password, macSalt, 3, macIterations, macKeyBytes, md);
  16987. var mac = forge$1.hmac.create();
  16988. mac.start(md, macKey);
  16989. mac.update(data.value);
  16990. var macValue = mac.getMac();
  16991. if(macValue.getBytes() !== capture.macDigest) {
  16992. throw new Error('PKCS#12 MAC could not be verified. Invalid password?');
  16993. }
  16994. }
  16995. _decodeAuthenticatedSafe(pfx, data.value, strict, password);
  16996. return pfx;
  16997. };
  16998. /**
  16999. * Decodes PKCS#7 Data. PKCS#7 (RFC 2315) defines "Data" as an OCTET STRING,
  17000. * but it is sometimes an OCTET STRING that is composed/constructed of chunks,
  17001. * each its own OCTET STRING. This is BER-encoding vs. DER-encoding. This
  17002. * function transforms this corner-case into the usual simple,
  17003. * non-composed/constructed OCTET STRING.
  17004. *
  17005. * This function may be moved to ASN.1 at some point to better deal with
  17006. * more BER-encoding issues, should they arise.
  17007. *
  17008. * @param data the ASN.1 Data object to transform.
  17009. */
  17010. function _decodePkcs7Data(data) {
  17011. // handle special case of "chunked" data content: an octet string composed
  17012. // of other octet strings
  17013. if(data.composed || data.constructed) {
  17014. var value = forge$1.util.createBuffer();
  17015. for(var i = 0; i < data.value.length; ++i) {
  17016. value.putBytes(data.value[i].value);
  17017. }
  17018. data.composed = data.constructed = false;
  17019. data.value = value.getBytes();
  17020. }
  17021. return data;
  17022. }
  17023. /**
  17024. * Decode PKCS#12 AuthenticatedSafe (BER encoded) into PFX object.
  17025. *
  17026. * The AuthenticatedSafe is a BER-encoded SEQUENCE OF ContentInfo.
  17027. *
  17028. * @param pfx The PKCS#12 PFX object to fill.
  17029. * @param {String} authSafe BER-encoded AuthenticatedSafe.
  17030. * @param strict true to use strict DER decoding, false not to.
  17031. * @param {String} password Password to decrypt with (optional).
  17032. */
  17033. function _decodeAuthenticatedSafe(pfx, authSafe, strict, password) {
  17034. authSafe = asn1$1.fromDer(authSafe, strict); /* actually it's BER encoded */
  17035. if(authSafe.tagClass !== asn1$1.Class.UNIVERSAL ||
  17036. authSafe.type !== asn1$1.Type.SEQUENCE ||
  17037. authSafe.constructed !== true) {
  17038. throw new Error('PKCS#12 AuthenticatedSafe expected to be a ' +
  17039. 'SEQUENCE OF ContentInfo');
  17040. }
  17041. for(var i = 0; i < authSafe.value.length; i++) {
  17042. var contentInfo = authSafe.value[i];
  17043. // validate contentInfo and capture data
  17044. var capture = {};
  17045. var errors = [];
  17046. if(!asn1$1.validate(contentInfo, contentInfoValidator, capture, errors)) {
  17047. var error = new Error('Cannot read ContentInfo.');
  17048. error.errors = errors;
  17049. throw error;
  17050. }
  17051. var obj = {
  17052. encrypted: false
  17053. };
  17054. var safeContents = null;
  17055. var data = capture.content.value[0];
  17056. switch(asn1$1.derToOid(capture.contentType)) {
  17057. case pki$1.oids.data:
  17058. if(data.tagClass !== asn1$1.Class.UNIVERSAL ||
  17059. data.type !== asn1$1.Type.OCTETSTRING) {
  17060. throw new Error('PKCS#12 SafeContents Data is not an OCTET STRING.');
  17061. }
  17062. safeContents = _decodePkcs7Data(data).value;
  17063. break;
  17064. case pki$1.oids.encryptedData:
  17065. safeContents = _decryptSafeContents(data, password);
  17066. obj.encrypted = true;
  17067. break;
  17068. default:
  17069. var error = new Error('Unsupported PKCS#12 contentType.');
  17070. error.contentType = asn1$1.derToOid(capture.contentType);
  17071. throw error;
  17072. }
  17073. obj.safeBags = _decodeSafeContents(safeContents, strict, password);
  17074. pfx.safeContents.push(obj);
  17075. }
  17076. }
  17077. /**
  17078. * Decrypt PKCS#7 EncryptedData structure.
  17079. *
  17080. * @param data ASN.1 encoded EncryptedContentInfo object.
  17081. * @param password The user-provided password.
  17082. *
  17083. * @return The decrypted SafeContents (ASN.1 object).
  17084. */
  17085. function _decryptSafeContents(data, password) {
  17086. var capture = {};
  17087. var errors = [];
  17088. if(!asn1$1.validate(
  17089. data, forge$1.pkcs7.asn1.encryptedDataValidator, capture, errors)) {
  17090. var error = new Error('Cannot read EncryptedContentInfo.');
  17091. error.errors = errors;
  17092. throw error;
  17093. }
  17094. var oid = asn1$1.derToOid(capture.contentType);
  17095. if(oid !== pki$1.oids.data) {
  17096. var error = new Error(
  17097. 'PKCS#12 EncryptedContentInfo ContentType is not Data.');
  17098. error.oid = oid;
  17099. throw error;
  17100. }
  17101. // get cipher
  17102. oid = asn1$1.derToOid(capture.encAlgorithm);
  17103. var cipher = pki$1.pbe.getCipher(oid, capture.encParameter, password);
  17104. // get encrypted data
  17105. var encryptedContentAsn1 = _decodePkcs7Data(capture.encryptedContentAsn1);
  17106. var encrypted = forge$1.util.createBuffer(encryptedContentAsn1.value);
  17107. cipher.update(encrypted);
  17108. if(!cipher.finish()) {
  17109. throw new Error('Failed to decrypt PKCS#12 SafeContents.');
  17110. }
  17111. return cipher.output.getBytes();
  17112. }
  17113. /**
  17114. * Decode PKCS#12 SafeContents (BER-encoded) into array of Bag objects.
  17115. *
  17116. * The safeContents is a BER-encoded SEQUENCE OF SafeBag.
  17117. *
  17118. * @param {String} safeContents BER-encoded safeContents.
  17119. * @param strict true to use strict DER decoding, false not to.
  17120. * @param {String} password Password to decrypt with (optional).
  17121. *
  17122. * @return {Array} Array of Bag objects.
  17123. */
  17124. function _decodeSafeContents(safeContents, strict, password) {
  17125. // if strict and no safe contents, return empty safes
  17126. if(!strict && safeContents.length === 0) {
  17127. return [];
  17128. }
  17129. // actually it's BER-encoded
  17130. safeContents = asn1$1.fromDer(safeContents, strict);
  17131. if(safeContents.tagClass !== asn1$1.Class.UNIVERSAL ||
  17132. safeContents.type !== asn1$1.Type.SEQUENCE ||
  17133. safeContents.constructed !== true) {
  17134. throw new Error(
  17135. 'PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.');
  17136. }
  17137. var res = [];
  17138. for(var i = 0; i < safeContents.value.length; i++) {
  17139. var safeBag = safeContents.value[i];
  17140. // validate SafeBag and capture data
  17141. var capture = {};
  17142. var errors = [];
  17143. if(!asn1$1.validate(safeBag, safeBagValidator, capture, errors)) {
  17144. var error = new Error('Cannot read SafeBag.');
  17145. error.errors = errors;
  17146. throw error;
  17147. }
  17148. /* Create bag object and push to result array. */
  17149. var bag = {
  17150. type: asn1$1.derToOid(capture.bagId),
  17151. attributes: _decodeBagAttributes(capture.bagAttributes)
  17152. };
  17153. res.push(bag);
  17154. var validator, decoder;
  17155. var bagAsn1 = capture.bagValue.value[0];
  17156. switch(bag.type) {
  17157. case pki$1.oids.pkcs8ShroudedKeyBag:
  17158. /* bagAsn1 has a EncryptedPrivateKeyInfo, which we need to decrypt.
  17159. Afterwards we can handle it like a keyBag,
  17160. which is a PrivateKeyInfo. */
  17161. bagAsn1 = pki$1.decryptPrivateKeyInfo(bagAsn1, password);
  17162. if(bagAsn1 === null) {
  17163. throw new Error(
  17164. 'Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?');
  17165. }
  17166. /* fall through */
  17167. case pki$1.oids.keyBag:
  17168. /* A PKCS#12 keyBag is a simple PrivateKeyInfo as understood by our
  17169. PKI module, hence we don't have to do validation/capturing here,
  17170. just pass what we already got. */
  17171. try {
  17172. bag.key = pki$1.privateKeyFromAsn1(bagAsn1);
  17173. } catch(e) {
  17174. // ignore unknown key type, pass asn1 value
  17175. bag.key = null;
  17176. bag.asn1 = bagAsn1;
  17177. }
  17178. continue; /* Nothing more to do. */
  17179. case pki$1.oids.certBag:
  17180. /* A PKCS#12 certBag can wrap both X.509 and sdsi certificates.
  17181. Therefore put the SafeBag content through another validator to
  17182. capture the fields. Afterwards check & store the results. */
  17183. validator = certBagValidator;
  17184. decoder = function() {
  17185. if(asn1$1.derToOid(capture.certId) !== pki$1.oids.x509Certificate) {
  17186. var error = new Error(
  17187. 'Unsupported certificate type, only X.509 supported.');
  17188. error.oid = asn1$1.derToOid(capture.certId);
  17189. throw error;
  17190. }
  17191. // true=produce cert hash
  17192. var certAsn1 = asn1$1.fromDer(capture.cert, strict);
  17193. try {
  17194. bag.cert = pki$1.certificateFromAsn1(certAsn1, true);
  17195. } catch(e) {
  17196. // ignore unknown cert type, pass asn1 value
  17197. bag.cert = null;
  17198. bag.asn1 = certAsn1;
  17199. }
  17200. };
  17201. break;
  17202. default:
  17203. var error = new Error('Unsupported PKCS#12 SafeBag type.');
  17204. error.oid = bag.type;
  17205. throw error;
  17206. }
  17207. /* Validate SafeBag value (i.e. CertBag, etc.) and capture data if needed. */
  17208. if(validator !== undefined &&
  17209. !asn1$1.validate(bagAsn1, validator, capture, errors)) {
  17210. var error = new Error('Cannot read PKCS#12 ' + validator.name);
  17211. error.errors = errors;
  17212. throw error;
  17213. }
  17214. /* Call decoder function from above to store the results. */
  17215. decoder();
  17216. }
  17217. return res;
  17218. }
  17219. /**
  17220. * Decode PKCS#12 SET OF PKCS12Attribute into JavaScript object.
  17221. *
  17222. * @param attributes SET OF PKCS12Attribute (ASN.1 object).
  17223. *
  17224. * @return the decoded attributes.
  17225. */
  17226. function _decodeBagAttributes(attributes) {
  17227. var decodedAttrs = {};
  17228. if(attributes !== undefined) {
  17229. for(var i = 0; i < attributes.length; ++i) {
  17230. var capture = {};
  17231. var errors = [];
  17232. if(!asn1$1.validate(attributes[i], attributeValidator, capture, errors)) {
  17233. var error = new Error('Cannot read PKCS#12 BagAttribute.');
  17234. error.errors = errors;
  17235. throw error;
  17236. }
  17237. var oid = asn1$1.derToOid(capture.oid);
  17238. if(pki$1.oids[oid] === undefined) {
  17239. // unsupported attribute type, ignore.
  17240. continue;
  17241. }
  17242. decodedAttrs[pki$1.oids[oid]] = [];
  17243. for(var j = 0; j < capture.values.length; ++j) {
  17244. decodedAttrs[pki$1.oids[oid]].push(capture.values[j].value);
  17245. }
  17246. }
  17247. }
  17248. return decodedAttrs;
  17249. }
  17250. /**
  17251. * Wraps a private key and certificate in a PKCS#12 PFX wrapper. If a
  17252. * password is provided then the private key will be encrypted.
  17253. *
  17254. * An entire certificate chain may also be included. To do this, pass
  17255. * an array for the "cert" parameter where the first certificate is
  17256. * the one that is paired with the private key and each subsequent one
  17257. * verifies the previous one. The certificates may be in PEM format or
  17258. * have been already parsed by Forge.
  17259. *
  17260. * @todo implement password-based-encryption for the whole package
  17261. *
  17262. * @param key the private key.
  17263. * @param cert the certificate (may be an array of certificates in order
  17264. * to specify a certificate chain).
  17265. * @param password the password to use, null for none.
  17266. * @param options:
  17267. * algorithm the encryption algorithm to use
  17268. * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'.
  17269. * count the iteration count to use.
  17270. * saltSize the salt size to use.
  17271. * useMac true to include a MAC, false not to, defaults to true.
  17272. * localKeyId the local key ID to use, in hex.
  17273. * friendlyName the friendly name to use.
  17274. * generateLocalKeyId true to generate a random local key ID,
  17275. * false not to, defaults to true.
  17276. *
  17277. * @return the PKCS#12 PFX ASN.1 object.
  17278. */
  17279. p12.toPkcs12Asn1 = function(key, cert, password, options) {
  17280. // set default options
  17281. options = options || {};
  17282. options.saltSize = options.saltSize || 8;
  17283. options.count = options.count || 2048;
  17284. options.algorithm = options.algorithm || options.encAlgorithm || 'aes128';
  17285. if(!('useMac' in options)) {
  17286. options.useMac = true;
  17287. }
  17288. if(!('localKeyId' in options)) {
  17289. options.localKeyId = null;
  17290. }
  17291. if(!('generateLocalKeyId' in options)) {
  17292. options.generateLocalKeyId = true;
  17293. }
  17294. var localKeyId = options.localKeyId;
  17295. var bagAttrs;
  17296. if(localKeyId !== null) {
  17297. localKeyId = forge$1.util.hexToBytes(localKeyId);
  17298. } else if(options.generateLocalKeyId) {
  17299. // use SHA-1 of paired cert, if available
  17300. if(cert) {
  17301. var pairedCert = forge$1.util.isArray(cert) ? cert[0] : cert;
  17302. if(typeof pairedCert === 'string') {
  17303. pairedCert = pki$1.certificateFromPem(pairedCert);
  17304. }
  17305. var sha1 = forge$1.md.sha1.create();
  17306. sha1.update(asn1$1.toDer(pki$1.certificateToAsn1(pairedCert)).getBytes());
  17307. localKeyId = sha1.digest().getBytes();
  17308. } else {
  17309. // FIXME: consider using SHA-1 of public key (which can be generated
  17310. // from private key components), see: cert.generateSubjectKeyIdentifier
  17311. // generate random bytes
  17312. localKeyId = forge$1.random.getBytes(20);
  17313. }
  17314. }
  17315. var attrs = [];
  17316. if(localKeyId !== null) {
  17317. attrs.push(
  17318. // localKeyID
  17319. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.SEQUENCE, true, [
  17320. // attrId
  17321. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.OID, false,
  17322. asn1$1.oidToDer(pki$1.oids.localKeyId).getBytes()),
  17323. // attrValues
  17324. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.SET, true, [
  17325. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.OCTETSTRING, false,
  17326. localKeyId)
  17327. ])
  17328. ]));
  17329. }
  17330. if('friendlyName' in options) {
  17331. attrs.push(
  17332. // friendlyName
  17333. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.SEQUENCE, true, [
  17334. // attrId
  17335. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.OID, false,
  17336. asn1$1.oidToDer(pki$1.oids.friendlyName).getBytes()),
  17337. // attrValues
  17338. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.SET, true, [
  17339. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.BMPSTRING, false,
  17340. options.friendlyName)
  17341. ])
  17342. ]));
  17343. }
  17344. if(attrs.length > 0) {
  17345. bagAttrs = asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.SET, true, attrs);
  17346. }
  17347. // collect contents for AuthenticatedSafe
  17348. var contents = [];
  17349. // create safe bag(s) for certificate chain
  17350. var chain = [];
  17351. if(cert !== null) {
  17352. if(forge$1.util.isArray(cert)) {
  17353. chain = cert;
  17354. } else {
  17355. chain = [cert];
  17356. }
  17357. }
  17358. var certSafeBags = [];
  17359. for(var i = 0; i < chain.length; ++i) {
  17360. // convert cert from PEM as necessary
  17361. cert = chain[i];
  17362. if(typeof cert === 'string') {
  17363. cert = pki$1.certificateFromPem(cert);
  17364. }
  17365. // SafeBag
  17366. var certBagAttrs = (i === 0) ? bagAttrs : undefined;
  17367. var certAsn1 = pki$1.certificateToAsn1(cert);
  17368. var certSafeBag =
  17369. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.SEQUENCE, true, [
  17370. // bagId
  17371. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.OID, false,
  17372. asn1$1.oidToDer(pki$1.oids.certBag).getBytes()),
  17373. // bagValue
  17374. asn1$1.create(asn1$1.Class.CONTEXT_SPECIFIC, 0, true, [
  17375. // CertBag
  17376. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.SEQUENCE, true, [
  17377. // certId
  17378. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.OID, false,
  17379. asn1$1.oidToDer(pki$1.oids.x509Certificate).getBytes()),
  17380. // certValue (x509Certificate)
  17381. asn1$1.create(asn1$1.Class.CONTEXT_SPECIFIC, 0, true, [
  17382. asn1$1.create(
  17383. asn1$1.Class.UNIVERSAL, asn1$1.Type.OCTETSTRING, false,
  17384. asn1$1.toDer(certAsn1).getBytes())
  17385. ])])]),
  17386. // bagAttributes (OPTIONAL)
  17387. certBagAttrs
  17388. ]);
  17389. certSafeBags.push(certSafeBag);
  17390. }
  17391. if(certSafeBags.length > 0) {
  17392. // SafeContents
  17393. var certSafeContents = asn1$1.create(
  17394. asn1$1.Class.UNIVERSAL, asn1$1.Type.SEQUENCE, true, certSafeBags);
  17395. // ContentInfo
  17396. var certCI =
  17397. // PKCS#7 ContentInfo
  17398. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.SEQUENCE, true, [
  17399. // contentType
  17400. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.OID, false,
  17401. // OID for the content type is 'data'
  17402. asn1$1.oidToDer(pki$1.oids.data).getBytes()),
  17403. // content
  17404. asn1$1.create(asn1$1.Class.CONTEXT_SPECIFIC, 0, true, [
  17405. asn1$1.create(
  17406. asn1$1.Class.UNIVERSAL, asn1$1.Type.OCTETSTRING, false,
  17407. asn1$1.toDer(certSafeContents).getBytes())
  17408. ])
  17409. ]);
  17410. contents.push(certCI);
  17411. }
  17412. // create safe contents for private key
  17413. var keyBag = null;
  17414. if(key !== null) {
  17415. // SafeBag
  17416. var pkAsn1 = pki$1.wrapRsaPrivateKey(pki$1.privateKeyToAsn1(key));
  17417. if(password === null) {
  17418. // no encryption
  17419. keyBag = asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.SEQUENCE, true, [
  17420. // bagId
  17421. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.OID, false,
  17422. asn1$1.oidToDer(pki$1.oids.keyBag).getBytes()),
  17423. // bagValue
  17424. asn1$1.create(asn1$1.Class.CONTEXT_SPECIFIC, 0, true, [
  17425. // PrivateKeyInfo
  17426. pkAsn1
  17427. ]),
  17428. // bagAttributes (OPTIONAL)
  17429. bagAttrs
  17430. ]);
  17431. } else {
  17432. // encrypted PrivateKeyInfo
  17433. keyBag = asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.SEQUENCE, true, [
  17434. // bagId
  17435. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.OID, false,
  17436. asn1$1.oidToDer(pki$1.oids.pkcs8ShroudedKeyBag).getBytes()),
  17437. // bagValue
  17438. asn1$1.create(asn1$1.Class.CONTEXT_SPECIFIC, 0, true, [
  17439. // EncryptedPrivateKeyInfo
  17440. pki$1.encryptPrivateKeyInfo(pkAsn1, password, options)
  17441. ]),
  17442. // bagAttributes (OPTIONAL)
  17443. bagAttrs
  17444. ]);
  17445. }
  17446. // SafeContents
  17447. var keySafeContents =
  17448. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.SEQUENCE, true, [keyBag]);
  17449. // ContentInfo
  17450. var keyCI =
  17451. // PKCS#7 ContentInfo
  17452. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.SEQUENCE, true, [
  17453. // contentType
  17454. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.OID, false,
  17455. // OID for the content type is 'data'
  17456. asn1$1.oidToDer(pki$1.oids.data).getBytes()),
  17457. // content
  17458. asn1$1.create(asn1$1.Class.CONTEXT_SPECIFIC, 0, true, [
  17459. asn1$1.create(
  17460. asn1$1.Class.UNIVERSAL, asn1$1.Type.OCTETSTRING, false,
  17461. asn1$1.toDer(keySafeContents).getBytes())
  17462. ])
  17463. ]);
  17464. contents.push(keyCI);
  17465. }
  17466. // create AuthenticatedSafe by stringing together the contents
  17467. var safe = asn1$1.create(
  17468. asn1$1.Class.UNIVERSAL, asn1$1.Type.SEQUENCE, true, contents);
  17469. var macData;
  17470. if(options.useMac) {
  17471. // MacData
  17472. var sha1 = forge$1.md.sha1.create();
  17473. var macSalt = new forge$1.util.ByteBuffer(
  17474. forge$1.random.getBytes(options.saltSize));
  17475. var count = options.count;
  17476. // 160-bit key
  17477. var key = p12.generateKey(password, macSalt, 3, count, 20);
  17478. var mac = forge$1.hmac.create();
  17479. mac.start(sha1, key);
  17480. mac.update(asn1$1.toDer(safe).getBytes());
  17481. var macValue = mac.getMac();
  17482. macData = asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.SEQUENCE, true, [
  17483. // mac DigestInfo
  17484. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.SEQUENCE, true, [
  17485. // digestAlgorithm
  17486. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.SEQUENCE, true, [
  17487. // algorithm = SHA-1
  17488. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.OID, false,
  17489. asn1$1.oidToDer(pki$1.oids.sha1).getBytes()),
  17490. // parameters = Null
  17491. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.NULL, false, '')
  17492. ]),
  17493. // digest
  17494. asn1$1.create(
  17495. asn1$1.Class.UNIVERSAL, asn1$1.Type.OCTETSTRING,
  17496. false, macValue.getBytes())
  17497. ]),
  17498. // macSalt OCTET STRING
  17499. asn1$1.create(
  17500. asn1$1.Class.UNIVERSAL, asn1$1.Type.OCTETSTRING, false, macSalt.getBytes()),
  17501. // iterations INTEGER (XXX: Only support count < 65536)
  17502. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.INTEGER, false,
  17503. asn1$1.integerToDer(count).getBytes()
  17504. )
  17505. ]);
  17506. }
  17507. // PFX
  17508. return asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.SEQUENCE, true, [
  17509. // version (3)
  17510. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.INTEGER, false,
  17511. asn1$1.integerToDer(3).getBytes()),
  17512. // PKCS#7 ContentInfo
  17513. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.SEQUENCE, true, [
  17514. // contentType
  17515. asn1$1.create(asn1$1.Class.UNIVERSAL, asn1$1.Type.OID, false,
  17516. // OID for the content type is 'data'
  17517. asn1$1.oidToDer(pki$1.oids.data).getBytes()),
  17518. // content
  17519. asn1$1.create(asn1$1.Class.CONTEXT_SPECIFIC, 0, true, [
  17520. asn1$1.create(
  17521. asn1$1.Class.UNIVERSAL, asn1$1.Type.OCTETSTRING, false,
  17522. asn1$1.toDer(safe).getBytes())
  17523. ])
  17524. ]),
  17525. macData
  17526. ]);
  17527. };
  17528. /**
  17529. * Derives a PKCS#12 key.
  17530. *
  17531. * @param password the password to derive the key material from, null or
  17532. * undefined for none.
  17533. * @param salt the salt, as a ByteBuffer, to use.
  17534. * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC).
  17535. * @param iter the iteration count.
  17536. * @param n the number of bytes to derive from the password.
  17537. * @param md the message digest to use, defaults to SHA-1.
  17538. *
  17539. * @return a ByteBuffer with the bytes derived from the password.
  17540. */
  17541. p12.generateKey = forge$1.pbe.generatePkcs12Key;
  17542. /**
  17543. * Javascript implementation of a basic Public Key Infrastructure, including
  17544. * support for RSA public and private keys.
  17545. *
  17546. * @author Dave Longley
  17547. *
  17548. * Copyright (c) 2010-2013 Digital Bazaar, Inc.
  17549. */
  17550. var forge = forge$s;
  17551. // shortcut for asn.1 API
  17552. var asn1 = forge.asn1;
  17553. /* Public Key Infrastructure (PKI) implementation. */
  17554. var pki = forge.pki = forge.pki || {};
  17555. /**
  17556. * NOTE: THIS METHOD IS DEPRECATED. Use pem.decode() instead.
  17557. *
  17558. * Converts PEM-formatted data to DER.
  17559. *
  17560. * @param pem the PEM-formatted data.
  17561. *
  17562. * @return the DER-formatted data.
  17563. */
  17564. pki.pemToDer = function(pem) {
  17565. var msg = forge.pem.decode(pem)[0];
  17566. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  17567. throw new Error('Could not convert PEM to DER; PEM is encrypted.');
  17568. }
  17569. return forge.util.createBuffer(msg.body);
  17570. };
  17571. /**
  17572. * Converts an RSA private key from PEM format.
  17573. *
  17574. * @param pem the PEM-formatted private key.
  17575. *
  17576. * @return the private key.
  17577. */
  17578. pki.privateKeyFromPem = function(pem) {
  17579. var msg = forge.pem.decode(pem)[0];
  17580. if(msg.type !== 'PRIVATE KEY' && msg.type !== 'RSA PRIVATE KEY') {
  17581. var error = new Error('Could not convert private key from PEM; PEM ' +
  17582. 'header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".');
  17583. error.headerType = msg.type;
  17584. throw error;
  17585. }
  17586. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  17587. throw new Error('Could not convert private key from PEM; PEM is encrypted.');
  17588. }
  17589. // convert DER to ASN.1 object
  17590. var obj = asn1.fromDer(msg.body);
  17591. return pki.privateKeyFromAsn1(obj);
  17592. };
  17593. /**
  17594. * Converts an RSA private key to PEM format.
  17595. *
  17596. * @param key the private key.
  17597. * @param maxline the maximum characters per line, defaults to 64.
  17598. *
  17599. * @return the PEM-formatted private key.
  17600. */
  17601. pki.privateKeyToPem = function(key, maxline) {
  17602. // convert to ASN.1, then DER, then PEM-encode
  17603. var msg = {
  17604. type: 'RSA PRIVATE KEY',
  17605. body: asn1.toDer(pki.privateKeyToAsn1(key)).getBytes()
  17606. };
  17607. return forge.pem.encode(msg, {maxline: maxline});
  17608. };
  17609. /**
  17610. * Converts a PrivateKeyInfo to PEM format.
  17611. *
  17612. * @param pki the PrivateKeyInfo.
  17613. * @param maxline the maximum characters per line, defaults to 64.
  17614. *
  17615. * @return the PEM-formatted private key.
  17616. */
  17617. pki.privateKeyInfoToPem = function(pki, maxline) {
  17618. // convert to DER, then PEM-encode
  17619. var msg = {
  17620. type: 'PRIVATE KEY',
  17621. body: asn1.toDer(pki).getBytes()
  17622. };
  17623. return forge.pem.encode(msg, {maxline: maxline});
  17624. };
  17625. // Simplified fork of selfsigned with inlined options and partial
  17626. // a hexString is considered negative if it's most significant bit is 1
  17627. // because serial numbers use ones' complement notation
  17628. // this RFC in section 4.1.2.2 requires serial numbers to be positive
  17629. // http://www.ietf.org/rfc/rfc5280.txt
  17630. function toPositiveHex(hexString) {
  17631. let mostSignificativeHexAsInt = parseInt(hexString[0], 16);
  17632. if (mostSignificativeHexAsInt < 8) {
  17633. return hexString;
  17634. }
  17635. mostSignificativeHexAsInt -= 8;
  17636. return mostSignificativeHexAsInt.toString() + hexString.substring(1);
  17637. }
  17638. function createCertificate() {
  17639. const days = 30;
  17640. const keySize = 2048;
  17641. const extensions = [
  17642. // {
  17643. // name: 'basicConstraints',
  17644. // cA: true,
  17645. // },
  17646. {
  17647. name: 'keyUsage',
  17648. keyCertSign: true,
  17649. digitalSignature: true,
  17650. nonRepudiation: true,
  17651. keyEncipherment: true,
  17652. dataEncipherment: true
  17653. },
  17654. {
  17655. name: 'extKeyUsage',
  17656. serverAuth: true,
  17657. clientAuth: true,
  17658. codeSigning: true,
  17659. timeStamping: true
  17660. },
  17661. {
  17662. name: 'subjectAltName',
  17663. altNames: [
  17664. {
  17665. // type 2 is DNS
  17666. type: 2,
  17667. value: 'localhost'
  17668. },
  17669. {
  17670. type: 2,
  17671. value: 'localhost.localdomain'
  17672. },
  17673. {
  17674. type: 2,
  17675. value: 'lvh.me'
  17676. },
  17677. {
  17678. type: 2,
  17679. value: '*.lvh.me'
  17680. },
  17681. {
  17682. type: 2,
  17683. value: '[::1]'
  17684. },
  17685. {
  17686. // type 7 is IP
  17687. type: 7,
  17688. ip: '127.0.0.1'
  17689. },
  17690. {
  17691. type: 7,
  17692. ip: 'fe80::1'
  17693. }
  17694. ]
  17695. }
  17696. ];
  17697. const attrs = [
  17698. {
  17699. name: 'commonName',
  17700. value: 'example.org'
  17701. },
  17702. {
  17703. name: 'countryName',
  17704. value: 'US'
  17705. },
  17706. {
  17707. shortName: 'ST',
  17708. value: 'Virginia'
  17709. },
  17710. {
  17711. name: 'localityName',
  17712. value: 'Blacksburg'
  17713. },
  17714. {
  17715. name: 'organizationName',
  17716. value: 'Test'
  17717. },
  17718. {
  17719. shortName: 'OU',
  17720. value: 'Test'
  17721. }
  17722. ];
  17723. const keyPair = forge$s.pki.rsa.generateKeyPair(keySize);
  17724. const cert = forge$s.pki.createCertificate();
  17725. cert.serialNumber = toPositiveHex(forge$s.util.bytesToHex(forge$s.random.getBytesSync(9))); // the serial number can be decimal or hex (if preceded by 0x)
  17726. cert.validity.notBefore = new Date();
  17727. cert.validity.notAfter = new Date();
  17728. cert.validity.notAfter.setDate(cert.validity.notBefore.getDate() + days);
  17729. cert.setSubject(attrs);
  17730. cert.setIssuer(attrs);
  17731. cert.publicKey = keyPair.publicKey;
  17732. cert.setExtensions(extensions);
  17733. const algorithm = forge$s.md.sha256.create();
  17734. cert.sign(keyPair.privateKey, algorithm);
  17735. const privateKeyPem = forge$s.pki.privateKeyToPem(keyPair.privateKey);
  17736. const certPem = forge$s.pki.certificateToPem(cert);
  17737. return privateKeyPem + certPem;
  17738. }
  17739. exports.createCertificate = createCertificate;